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:
authorNolan Cotter <186326284+NolanCotter@users.noreply.github.com>2026-11-22 20:39:59 -0700
committerNolan Cotter <186326284+NolanCotter@users.noreply.github.com>2026-11-22 20:39:59 -0700
commitfa5f26db8eafd2cc27f627b68c0a5a5949bcf2ff (patch)
treefc57e238be829295fc216dff89a6d93e64c16b50 /runtime
parent9b693ecd8a2f90799f6c47f8f06cf062feb9820c (diff)
parent7b7d73f890f9fbbf5967bbb694390bbc99e33ba6 (diff)
Merge origin/main: DXGI device fields coexist with the console-ABI device state
Diffstat (limited to 'runtime')
-rw-r--r--runtime/CMakeLists.txt234
-rw-r--r--runtime/README.md59
-rw-r--r--runtime/shims/d3d12_com.cpp39
-rw-r--r--runtime/shims/d3d12_com.h5
-rw-r--r--runtime/shims/d3d12_feature_compat.h69
-rw-r--r--runtime/shims/d3d12_vulkan_device.cpp747
-rw-r--r--runtime/shims/d3d12_xs_device.cpp175
-rw-r--r--runtime/shims/d3d12_xs_device.h18
-rw-r--r--runtime/shims/dxgi_com.cpp169
-rw-r--r--runtime/shims/dxgi_swapchain.h74
-rw-r--r--runtime/shims/file_system.cpp46
-rw-r--r--runtime/shims/gameinput.cpp108
-rw-r--r--runtime/shims/gameinput.h17
-rw-r--r--runtime/shims/process.cpp101
-rw-r--r--runtime/shims/winhttp_offline.cpp7
-rw-r--r--runtime/shims/xgameruntime.cpp248
-rw-r--r--runtime/shims/xgameruntime_user.cpp539
-rw-r--r--runtime/shims/xmem.cpp48
-rw-r--r--runtime/src/active_input.h146
-rw-r--r--runtime/src/buffer_va_index.h31
-rw-r--r--runtime/src/command_list.h27
-rw-r--r--runtime/src/depth24_fragment.h445
-rw-r--r--runtime/src/gfx10_descriptors.h9
-rw-r--r--runtime/src/indirect_dispatch_count.comp34
-rw-r--r--runtime/src/indirect_dispatch_count_spv.h84
-rw-r--r--runtime/src/pe_loader.cpp28
-rw-r--r--runtime/src/pe_loader.h17
-rw-r--r--runtime/src/queue_families.h20
-rw-r--r--runtime/src/shader_library.h11
-rw-r--r--runtime/src/vulkan_backend.h71
-rw-r--r--runtime/src/vulkan_indirect_dispatch_count.h199
-rw-r--r--runtime/src/vulkan_memory.h9
-rw-r--r--runtime/src/vulkan_present.h26
-rw-r--r--runtime/src/vulkan_replay.h132
-rw-r--r--runtime/test/active_input_test.cpp236
-rw-r--r--runtime/test/buffer_va_index_test.cpp36
-rw-r--r--runtime/test/bvh_builder_test.cpp22
-rw-r--r--runtime/test/check_atexit.cmake71
-rw-r--r--runtime/test/check_sparse_queue_family.py117
-rw-r--r--runtime/test/check_tiny_frame.py124
-rw-r--r--runtime/test/command_list_test.cpp2
-rw-r--r--runtime/test/cpp_unwind_test.cpp31
-rw-r--r--runtime/test/cs_wave_probe_spv.h63
-rw-r--r--runtime/test/d3d12_buffer_tiles_test.cpp42
-rw-r--r--runtime/test/d3d12_bundle_test.cpp17
-rw-r--r--runtime/test/d3d12_com_test.cpp6
-rw-r--r--runtime/test/d3d12_compute_test.cpp18
-rw-r--r--runtime/test/d3d12_copy_xfmt_test.cpp61
-rw-r--r--runtime/test/d3d12_depth24_draw_test.cpp464
-rw-r--r--runtime/test/d3d12_descriptor_test.cpp119
-rw-r--r--runtime/test/d3d12_draw_test.cpp17
-rw-r--r--runtime/test/d3d12_fspx_compute_test.cpp15
-rw-r--r--runtime/test/d3d12_geometry_test.cpp4
-rw-r--r--runtime/test/d3d12_heap_properties_test.cpp284
-rw-r--r--runtime/test/d3d12_indirect_dispatch_count_test.cpp231
-rw-r--r--runtime/test/d3d12_m2_textured_test.cpp100
-rw-r--r--runtime/test/d3d12_method_variants_test.cpp311
-rw-r--r--runtime/test/d3d12_msaa_draw_test.cpp10
-rw-r--r--runtime/test/d3d12_pipeline_library_test.cpp14
-rw-r--r--runtime/test/d3d12_placed_dimensions_test.cpp347
-rw-r--r--runtime/test/d3d12_present_test.cpp55
-rw-r--r--runtime/test/d3d12_residency_test.cpp421
-rw-r--r--runtime/test/d3d12_set0_compute_test.cpp10
-rw-r--r--runtime/test/d3d12_shader_cache_test.cpp26
-rw-r--r--runtime/test/d3d12_sparse_queue_family_test.cpp175
-rw-r--r--runtime/test/d3d12_state_map_test.cpp15
-rw-r--r--runtime/test/d3d12_subgroup_test.cpp5
-rw-r--r--runtime/test/d3d12_typeless_families_test.cpp13
-rw-r--r--runtime/test/d3d12_vulkan_device_test.cpp342
-rw-r--r--runtime/test/dxgi_device_test.cpp349
-rw-r--r--runtime/test/dxgi_swapchain_count_test.cpp354
-rw-r--r--runtime/test/dxgi_swapchain_test.cpp240
-rw-r--r--runtime/test/file_system_test.cpp46
-rw-r--r--runtime/test/fixtures/d3d12_xs_stub.cpp10
-rw-r--r--runtime/test/fixtures/d3d12_xs_stub.def3
-rw-r--r--runtime/test/fixtures/dll_thread_calls.cpp9
-rw-r--r--runtime/test/fixtures/gameinput_host.cpp43
-rw-r--r--runtime/test/fixtures/tiny_atexit.cpp92
-rw-r--r--runtime/test/fixtures/tiny_frame.cpp166
-rw-r--r--runtime/test/fixtures/tiny_gdk_load.cpp5
-rw-r--r--runtime/test/fixtures/tiny_tls_cb_only.cpp9
-rw-r--r--runtime/test/gameinput_host_test.cpp90
-rw-r--r--runtime/test/gameinput_test.cpp154
-rw-r--r--runtime/test/gfx10_descriptors_test.cpp9
-rw-r--r--runtime/test/glsl/cs_indirect_dispatch_count.comp17
-rw-r--r--runtime/test/glsl/cs_wave_probe.comp31
-rw-r--r--runtime/test/glsl/gs_depth.geom15
-rw-r--r--runtime/test/glsl/ps_depth_empty.frag11
-rw-r--r--runtime/test/glsl/ps_depth_write.frag13
-rw-r--r--runtime/test/glsl/vs_depth.vert16
-rw-r--r--runtime/test/large_module_gate.h179
-rw-r--r--runtime/test/large_module_gate_test.cpp159
-rw-r--r--runtime/test/loader_test.cpp55
-rw-r--r--runtime/test/queue_proxy_test.cpp15
-rw-r--r--runtime/test/replay_cpu_bench.cpp13
-rw-r--r--runtime/test/replay_query_predication_test.cpp50
-rw-r--r--runtime/test/root_signature_oracle_test.cpp366
-rw-r--r--runtime/test/shader_library_test.cpp4
-rw-r--r--runtime/test/shaders/build.py7
-rw-r--r--runtime/test/shaders/check.py38
-rw-r--r--runtime/test/shaders/cs_bvh.asm6
-rw-r--r--runtime/test/shaders/cs_bvh32.asm12
-rw-r--r--runtime/test/shaders/cs_smem_sconst_off.asm47
-rw-r--r--runtime/test/shaders/ps_far_branch.asm321
-rw-r--r--runtime/test/shaders/ps_m2_literal.asm21
-rw-r--r--runtime/test/shaders/ps_sample_c.asm25
-rw-r--r--runtime/test/shaders/ps_sample_c_b.asm25
-rw-r--r--runtime/test/shaders/ps_texture_b_cl.asm23
-rw-r--r--runtime/test/shaders/ps_texture_cl.asm23
-rw-r--r--runtime/test/shaders/ps_w64_a_discard.asm65
-rw-r--r--runtime/test/shaders/w64_graphics.py11
-rw-r--r--runtime/test/test_runtime_types.cpp15
-rw-r--r--runtime/test/test_temp_dir.h67
-rw-r--r--runtime/test/vk_command_replay_test.cpp81
-rw-r--r--runtime/test/vk_compute_test.cpp157
-rw-r--r--runtime/test/vk_pipeline_check.cpp164
-rw-r--r--runtime/test/vk_presenter_sync_test.cpp86
-rw-r--r--runtime/test/vk_queue_test.cpp28
-rw-r--r--runtime/test/vk_sandbox.cpp734
-rw-r--r--runtime/test/vk_texture_test.cpp39
-rw-r--r--runtime/test/vulkan13_features_test.cpp61
-rw-r--r--runtime/test/winhttp_offline_test.cpp75
-rw-r--r--runtime/test/xbox_present_test.cpp60
-rw-r--r--runtime/test/xgameruntime_test.cpp189
-rw-r--r--runtime/test/xgameruntime_user_test.cpp227
-rw-r--r--runtime/test/xmem_test.cpp63
126 files changed, 12399 insertions, 610 deletions
diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt
index 896c125a8..4d34b7f0d 100644
--- a/runtime/CMakeLists.txt
+++ b/runtime/CMakeLists.txt
@@ -4,12 +4,26 @@ project(gta6rt LANGUAGES CXX)
4set(CMAKE_CXX_STANDARD 20) 4set(CMAKE_CXX_STANDARD 20)
5set(CMAKE_CXX_STANDARD_REQUIRED ON) 5set(CMAKE_CXX_STANDARD_REQUIRED ON)
6 6
7# The sources are UTF-8. Without /utf-8, MSVC reads them in the system's ANSI code page, so on code page 936 (or
8# any other non-1252 locale) it prints C4819 for every non-ASCII comment. Many targets set /utf-8 themselves; this
9# covers every target, including those that don't. clang-cl accepts it too. Only C and C++: ml64 (abi_probe.asm) has
10# no /utf-8 and warns A4018 for it.
11if(MSVC)
12 add_compile_options($<$<COMPILE_LANGUAGE:C,CXX>:/utf-8>)
13endif()
14
7if(NOT CMAKE_SIZEOF_VOID_P EQUAL 8) 15if(NOT CMAKE_SIZEOF_VOID_P EQUAL 8)
8 message(FATAL_ERROR "gta6rt must be built for x64 (run from an x64 Native Tools prompt or vcvars64.bat)") 16 message(FATAL_ERROR "gta6rt must be built for x64 (run from an x64 Native Tools prompt or vcvars64.bat)")
9endif() 17endif()
10 18
11option(LEONIDA_BUILD_WINDOWS_RUNTIME "Build the Windows runtime, its shims and their tests" ${WIN32}) 19option(LEONIDA_BUILD_WINDOWS_RUNTIME "Build the Windows runtime, its shims and their tests" ${WIN32})
12if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) 20if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME)
21 # Custom CMAKE_CXX_FLAGS can replace MSVC's default /EHsc. Require C++ stack unwinding so error
22 # paths in the runtime and its libraries still destroy automatic objects when an exception leaves a frame.
23 if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC")
24 add_compile_options($<$<COMPILE_LANGUAGE:CXX>:/EHsc>)
25 endif()
26
13 # The d3d12_xs shim and its tests use version 1.2 root signatures (D3D12_ROOT_SIGNATURE_DESC2), which the Windows 27 # The d3d12_xs shim and its tests use version 1.2 root signatures (D3D12_ROOT_SIGNATURE_DESC2), which the Windows
14 # SDK declares from 10.0.26100 on. Stop here with the fix instead of failing halfway through the build. 28 # SDK declares from 10.0.26100 on. Stop here with the fix instead of failing halfway through the build.
15 include(CheckCXXSourceCompiles) 29 include(CheckCXXSourceCompiles)
@@ -97,6 +111,7 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME)
97 shims/d3d12_xs.cpp 111 shims/d3d12_xs.cpp
98 shims/d3d12_xs_device.cpp 112 shims/d3d12_xs_device.cpp
99 shims/xgameruntime.cpp 113 shims/xgameruntime.cpp
114 shims/xgameruntime_user.cpp
100 shims/library_loader.cpp 115 shims/library_loader.cpp
101 shims/process.cpp 116 shims/process.cpp
102 ) 117 )
@@ -226,9 +241,10 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME)
226 add_executable(xgameruntime_test 241 add_executable(xgameruntime_test
227 test/xgameruntime_test.cpp 242 test/xgameruntime_test.cpp
228 shims/xgameruntime.cpp 243 shims/xgameruntime.cpp
229 shims/file_system.cpp 244 shims/xgameruntime_user.cpp
230 shims/library_loader.cpp 245 shims/library_loader.cpp
231 shims/registry.cpp 246 shims/registry.cpp
247 shims/file_system.cpp
232 ) 248 )
233 target_include_directories(xgameruntime_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) 249 target_include_directories(xgameruntime_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims)
234 target_compile_definitions(xgameruntime_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) 250 target_compile_definitions(xgameruntime_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
@@ -236,6 +252,21 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME)
236 target_link_options(xgameruntime_test PRIVATE /OPT:NOREF) 252 target_link_options(xgameruntime_test PRIVATE /OPT:NOREF)
237 target_link_libraries(xgameruntime_test PRIVATE gta6rt_xtaskqueue) 253 target_link_libraries(xgameruntime_test PRIVATE gta6rt_xtaskqueue)
238 254
255 # XUserImpl (offline local user) through QueryApiImpl, slot by slot as xgameruntime.lib's thunks call it.
256 add_executable(xgameruntime_user_test
257 test/xgameruntime_user_test.cpp
258 shims/xgameruntime.cpp
259 shims/xgameruntime_user.cpp
260 shims/library_loader.cpp
261 shims/registry.cpp
262 shims/file_system.cpp
263 )
264 target_include_directories(xgameruntime_user_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims)
265 target_compile_definitions(xgameruntime_user_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
266 target_compile_options(xgameruntime_user_test PRIVATE /W4 /permissive- /utf-8)
267 target_link_options(xgameruntime_user_test PRIVATE /OPT:NOREF)
268 target_link_libraries(xgameruntime_user_test PRIVATE gta6rt_xtaskqueue)
269
239 # GameInput shim on SDL3 (zlib licence): any controller SDL supports, DualSense trigger effects and lightbar. 270 # GameInput shim on SDL3 (zlib licence): any controller SDL supports, DualSense trigger effects and lightbar.
240 # Nothing is downloaded unless asked. The shim is built when SDL3 is available: 271 # Nothing is downloaded unless asked. The shim is built when SDL3 is available:
241 # - an installed SDL3 3.2+ that find_package finds (SDL3_DIR / CMAKE_PREFIX_PATH), or 272 # - an installed SDL3 3.2+ that find_package finds (SDL3_DIR / CMAKE_PREFIX_PATH), or
@@ -308,6 +339,11 @@ if(BUILD_TESTING)
308 339
309 add_executable(pipeline_cache_file_test test/pipeline_cache_file_test.cpp) 340 add_executable(pipeline_cache_file_test test/pipeline_cache_file_test.cpp)
310 add_test(NAME pipeline_cache_file COMMAND pipeline_cache_file_test) 341 add_test(NAME pipeline_cache_file COMMAND pipeline_cache_file_test)
342 # vk_pipeline_check's memory budget for large modules: pure stdlib, no Vulkan device.
343 add_executable(large_module_gate_test test/large_module_gate_test.cpp)
344 find_package(Threads REQUIRED)
345 target_link_libraries(large_module_gate_test PRIVATE Threads::Threads)
346 add_test(NAME large_module_gate COMMAND large_module_gate_test)
311 # XDXR build descriptions (docs/xdxr.md); compared with d3d12.h where the Windows SDK provides it. 347 # XDXR build descriptions (docs/xdxr.md); compared with d3d12.h where the Windows SDK provides it.
312 add_executable(xdxr_descs_test test/xdxr_descs_test.cpp) 348 add_executable(xdxr_descs_test test/xdxr_descs_test.cpp)
313 add_test(NAME xdxr_descs COMMAND xdxr_descs_test) 349 add_test(NAME xdxr_descs COMMAND xdxr_descs_test)
@@ -316,6 +352,11 @@ if(BUILD_TESTING)
316 target_include_directories(vulkan_device_filter_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) 352 target_include_directories(vulkan_device_filter_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src)
317 add_test(NAME vulkan_device_filter COMMAND vulkan_device_filter_test) 353 add_test(NAME vulkan_device_filter COMMAND vulkan_device_filter_test)
318 if(TARGET gta6rt) 354 if(TARGET gta6rt)
355 if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC")
356 add_executable(cpp_unwind_test test/cpp_unwind_test.cpp)
357 add_test(NAME cpp_unwind COMMAND cpp_unwind_test)
358 endif()
359
319 # Compile-time ABI checks (D3D12/XMem structure sizes, alignments and member offsets against the Windows SDK). 360 # Compile-time ABI checks (D3D12/XMem structure sizes, alignments and member offsets against the Windows SDK).
320 # The file existed but no target built it, so none of its static_asserts ever ran. 361 # The file existed but no target built it, so none of its static_asserts ever ran.
321 add_executable(runtime_types_test test/test_runtime_types.cpp) 362 add_executable(runtime_types_test test/test_runtime_types.cpp)
@@ -445,6 +486,12 @@ if(BUILD_TESTING)
445 RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$<CONFIG>" 486 RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$<CONFIG>"
446 ) 487 )
447 endforeach() 488 endforeach()
489 add_executable(tiny_atexit test/fixtures/tiny_atexit.cpp)
490 target_compile_definitions(tiny_atexit PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
491 target_compile_options(tiny_atexit PRIVATE /W4 /permissive- /utf-8)
492 set_target_properties(tiny_atexit PROPERTIES
493 RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$<CONFIG>"
494 )
448 add_executable(tiny_game test/fixtures/tiny_game.cpp) 495 add_executable(tiny_game test/fixtures/tiny_game.cpp)
449 target_link_libraries(tiny_game PRIVATE xgameruntime_stub) 496 target_link_libraries(tiny_game PRIVATE xgameruntime_stub)
450 target_compile_definitions(tiny_game PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS) # plain fopen, as games use 497 target_compile_definitions(tiny_game PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS) # plain fopen, as games use
@@ -563,6 +610,34 @@ if(BUILD_TESTING)
563 COMMAND dll_thread_calls_test "$<TARGET_FILE:dll_thread_calls>" 610 COMMAND dll_thread_calls_test "$<TARGET_FILE:dll_thread_calls>"
564 ) 611 )
565 612
613 # The host GameInput path (docs/gameinput.md): mapped code that imports GameInputCreate from GameInput.dll, with no
614 # GameInput shim linked. Needs the SDK's gameinput.lib and GameInput.h to build the fixture, and a GameInput.dll on
615 # the machine to run (the test skips with 77 only when Windows cannot load GameInput.dll). No game files.
616 find_library(GAMEINPUT_LIBRARY NAMES gameinput HINTS ${_sdk_lib_hints})
617 if(GAMEINPUT_LIBRARY)
618 add_library(gameinput_host SHARED test/fixtures/gameinput_host.cpp)
619 target_compile_options(gameinput_host PRIVATE /W4 /permissive- /utf-8 /GS-)
620 target_link_options(gameinput_host PRIVATE /NODEFAULTLIB /ENTRY:gameinput_host_main)
621 target_link_libraries(gameinput_host PRIVATE kernel32 ${GAMEINPUT_LIBRARY})
622 set_target_properties(gameinput_host PROPERTIES
623 OUTPUT_NAME gameinput_host
624 PREFIX ""
625 RUNTIME_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}"
626 ARCHIVE_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}"
627 )
628 add_executable(gameinput_host_test
629 test/gameinput_host_test.cpp
630 src/pe_loader.cpp
631 shims/registry.cpp
632 )
633 target_include_directories(gameinput_host_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src)
634 target_compile_definitions(gameinput_host_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
635 target_compile_options(gameinput_host_test PRIVATE /W4 /permissive- /utf-8 /EHsc)
636 add_dependencies(gameinput_host_test gameinput_host)
637 add_test(NAME gameinput_host COMMAND gameinput_host_test "$<TARGET_FILE:gameinput_host>")
638 set_tests_properties(gameinput_host PROPERTIES SKIP_RETURN_CODE 77) # Windows cannot load GameInput.dll
639 endif()
640
566 # LEONIDA_UNIMPLEMENTED=log|fail|stop: builds its own image with two imports that bind to nothing, calls them in 641 # LEONIDA_UNIMPLEMENTED=log|fail|stop: builds its own image with two imports that bind to nothing, calls them in
567 # process (log, fail) and in child processes (default/env parsing, stop). No game files, no GPU. 642 # process (log, fail) and in child processes (default/env parsing, stop). No game files, no GPU.
568 add_executable(unimplemented_policy_test 643 add_executable(unimplemented_policy_test
@@ -737,7 +812,20 @@ if(BUILD_TESTING)
737 endif() 812 endif()
738 if(WIN32 AND TARGET xgameruntime_test) 813 if(WIN32 AND TARGET xgameruntime_test)
739 add_test(NAME xgameruntime COMMAND xgameruntime_test) 814 add_test(NAME xgameruntime COMMAND xgameruntime_test)
815 add_test(NAME xgameruntime_user COMMAND xgameruntime_user_test)
816 add_test(NAME xgameruntime_user_gamertag COMMAND xgameruntime_user_test --expect-gamertag Tester42)
817 set_tests_properties(xgameruntime_user_gamertag PROPERTIES ENVIRONMENT "LEONIDA_GAMERTAG=Tester42")
818 # Longer than getenv_s's old 64-byte buffer: still the "Player" fallback (and its message), not a silent one.
819 add_test(NAME xgameruntime_user_gamertag_long COMMAND xgameruntime_user_test --expect-gamertag Player)
820 set_tests_properties(xgameruntime_user_gamertag_long PROPERTIES ENVIRONMENT "LEONIDA_GAMERTAG=GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG")
821 endif()
822 # The active-input tracker the GameInput shim feeds (src/active_input.h), on synthetic samples: no SDL, no
823 # controller, no GPU, so it builds and runs everywhere, with or without SDL3.
824 add_executable(active_input_test test/active_input_test.cpp)
825 if(MSVC)
826 target_compile_options(active_input_test PRIVATE /W4 /permissive- /utf-8)
740 endif() 827 endif()
828 add_test(NAME active_input COMMAND active_input_test)
741 if(WIN32 AND TARGET gameinput_test) 829 if(WIN32 AND TARGET gameinput_test)
742 add_test(NAME gameinput COMMAND gameinput_test) 830 add_test(NAME gameinput COMMAND gameinput_test)
743 elseif(TARGET gta6rt) 831 elseif(TARGET gta6rt)
@@ -758,6 +846,10 @@ if(BUILD_TESTING)
758 add_test(NAME run_tiny_bundled_load COMMAND ${CMAKE_COMMAND} 846 add_test(NAME run_tiny_bundled_load COMMAND ${CMAKE_COMMAND}
759 "-DLOADER=$<TARGET_FILE:gta6rt>" "-DGUEST=$<TARGET_FILE:tiny_bundled_load>" 847 "-DLOADER=$<TARGET_FILE:gta6rt>" "-DGUEST=$<TARGET_FILE:tiny_bundled_load>"
760 "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_loaded_bundled.cmake") 848 "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_loaded_bundled.cmake")
849 # atexit handlers, static destructors and the ways out, compared with the same program run natively.
850 add_test(NAME run_tiny_atexit COMMAND ${CMAKE_COMMAND}
851 "-DLOADER=$<TARGET_FILE:gta6rt>" "-DGUEST=$<TARGET_FILE:tiny_atexit>"
852 "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_atexit.cmake")
761 add_test(NAME run_tiny_game COMMAND gta6rt --run $<TARGET_FILE:tiny_game> -- hello 42) 853 add_test(NAME run_tiny_game COMMAND gta6rt --run $<TARGET_FILE:tiny_game> -- hello 42)
762 add_test(NAME run_tiny_game_console_paths COMMAND ${CMAKE_COMMAND} 854 add_test(NAME run_tiny_game_console_paths COMMAND ${CMAKE_COMMAND}
763 "-DLOADER=$<TARGET_FILE:gta6rt>" "-DGUEST=$<TARGET_FILE:tiny_game>" 855 "-DLOADER=$<TARGET_FILE:gta6rt>" "-DGUEST=$<TARGET_FILE:tiny_game>"
@@ -848,7 +940,7 @@ endif()
848if(TARGET Vulkan::Headers) 940if(TARGET Vulkan::Headers)
849 foreach(tool vk_harness vk_texture_test vk_sampler_test vk_compute_test vk_store_test vk_pipeline_check vk_command_replay_test 941 foreach(tool vk_harness vk_texture_test vk_sampler_test vk_compute_test vk_store_test vk_pipeline_check vk_command_replay_test
850 vk_bindless_test vk_image_fuzz vk_descriptor_bench depth24_convert_test vk_predicate_capture_test vk_predicated_copy_test 942 vk_bindless_test vk_image_fuzz vk_descriptor_bench depth24_convert_test vk_predicate_capture_test vk_predicated_copy_test
851 vk_xdxr_build_test vk_queue_test) 943 vk_xdxr_build_test vk_queue_test vk_sandbox)
852 add_executable(${tool} test/${tool}.cpp) 944 add_executable(${tool} test/${tool}.cpp)
853 target_link_libraries(${tool} PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) 945 target_link_libraries(${tool} PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS})
854 if(WIN32) 946 if(WIN32)
@@ -1138,6 +1230,22 @@ if(TARGET Vulkan::Headers)
1138 add_test(NAME d3d12_buffer_tiles COMMAND d3d12_buffer_tiles_test) 1230 add_test(NAME d3d12_buffer_tiles COMMAND d3d12_buffer_tiles_test)
1139 set_tests_properties(d3d12_buffer_tiles PROPERTIES SKIP_RETURN_CODE 77 1231 set_tests_properties(d3d12_buffer_tiles PROPERTIES SKIP_RETURN_CODE 77
1140 FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") 1232 FAIL_REGULAR_EXPRESSION "Validation Error;VUID-")
1233 # D3D12 permits UpdateTileMappings on DIRECT/COPY/COMPUTE and a sparse buffer must remain
1234 # accessible across their selected Vulkan families. The optional API-dump check catches an
1235 # EXCLUSIVE VkBuffer even on drivers that happen to return correct bytes without ownership barriers.
1236 add_executable(d3d12_sparse_queue_family_test test/d3d12_sparse_queue_family_test.cpp)
1237 target_link_libraries(d3d12_sparse_queue_family_test PRIVATE gta6rt_d3d12_com d3d12 dxgi)
1238 target_compile_definitions(d3d12_sparse_queue_family_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
1239 target_compile_options(d3d12_sparse_queue_family_test PRIVATE /W4 /permissive- /utf-8)
1240 add_test(NAME d3d12_sparse_queue_family COMMAND d3d12_sparse_queue_family_test)
1241 set_tests_properties(d3d12_sparse_queue_family PROPERTIES SKIP_RETURN_CODE 77
1242 FAIL_REGULAR_EXPRESSION "Validation Error;VUID-")
1243 if(Python3_FOUND AND NOT CMAKE_CROSSCOMPILING)
1244 add_test(NAME d3d12_sparse_queue_family_contract COMMAND "${Python3_EXECUTABLE}" -I
1245 "${CMAKE_CURRENT_SOURCE_DIR}/test/check_sparse_queue_family.py"
1246 "$<TARGET_FILE:d3d12_sparse_queue_family_test>")
1247 set_tests_properties(d3d12_sparse_queue_family_contract PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 65)
1248 endif()
1141 set_tests_properties(d3d12_vulkan_device PROPERTIES SKIP_RETURN_CODE 77) 1249 set_tests_properties(d3d12_vulkan_device PROPERTIES SKIP_RETURN_CODE 77)
1142 1250
1143 add_executable(d3d12_texture1d_test test/d3d12_texture1d_test.cpp) 1251 add_executable(d3d12_texture1d_test test/d3d12_texture1d_test.cpp)
@@ -1147,6 +1255,15 @@ if(TARGET Vulkan::Headers)
1147 add_test(NAME d3d12_texture1d COMMAND d3d12_texture1d_test) 1255 add_test(NAME d3d12_texture1d COMMAND d3d12_texture1d_test)
1148 set_tests_properties(d3d12_texture1d PROPERTIES SKIP_RETURN_CODE 77) 1256 set_tests_properties(d3d12_texture1d PROPERTIES SKIP_RETURN_CODE 77)
1149 1257
1258 # Placed 1D and 3D textures against the host runtime and WARP, and a copy round trip through them.
1259 add_executable(d3d12_placed_dimensions_test test/d3d12_placed_dimensions_test.cpp)
1260 target_link_libraries(d3d12_placed_dimensions_test PRIVATE gta6rt_d3d12_com d3d12 dxgi)
1261 target_compile_definitions(d3d12_placed_dimensions_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
1262 target_compile_options(d3d12_placed_dimensions_test PRIVATE /W4 /permissive- /utf-8)
1263 add_test(NAME d3d12_placed_dimensions COMMAND d3d12_placed_dimensions_test)
1264 set_tests_properties(d3d12_placed_dimensions PROPERTIES SKIP_RETURN_CODE 77
1265 FAIL_REGULAR_EXPRESSION "Validation Error;VUID-")
1266
1150 # ClearUnorderedAccessViewUint/Float on buffers and textures, read back through D3D12. 1267 # ClearUnorderedAccessViewUint/Float on buffers and textures, read back through D3D12.
1151 add_executable(d3d12_uav_clear_test test/d3d12_uav_clear_test.cpp) 1268 add_executable(d3d12_uav_clear_test test/d3d12_uav_clear_test.cpp)
1152 target_link_libraries(d3d12_uav_clear_test PRIVATE gta6rt_d3d12_com) 1269 target_link_libraries(d3d12_uav_clear_test PRIVATE gta6rt_d3d12_com)
@@ -1230,6 +1347,14 @@ if(TARGET Vulkan::Headers)
1230 target_compile_options(allocator_proxy_test PRIVATE /W4 /permissive- /utf-8) 1347 target_compile_options(allocator_proxy_test PRIVATE /W4 /permissive- /utf-8)
1231 add_test(NAME allocator_proxy COMMAND allocator_proxy_test) 1348 add_test(NAME allocator_proxy COMMAND allocator_proxy_test)
1232 set_tests_properties(allocator_proxy PROPERTIES SKIP_RETURN_CODE 77) 1349 set_tests_properties(allocator_proxy PROPERTIES SKIP_RETURN_CODE 77)
1350 # IDXGIDevice1 on the device proxy (the GDKX boot step: QueryInterface, GetAdapter, EnumOutputs), on the host
1351 # runtime and on the Vulkan device: COM identity with the device, the adapter's LUID. 77: no device at all.
1352 add_executable(dxgi_device_test test/dxgi_device_test.cpp)
1353 target_link_libraries(dxgi_device_test PRIVATE gta6rt_d3d12_com d3d12 dxgi)
1354 target_compile_definitions(dxgi_device_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
1355 target_compile_options(dxgi_device_test PRIVATE /W4 /permissive- /utf-8)
1356 add_test(NAME dxgi_device COMMAND dxgi_device_test)
1357 set_tests_properties(dxgi_device PROPERTIES SKIP_RETURN_CODE 77)
1233 # The countdown behind those event-backed waits, with no GPU: the full unsigned count, no wrap past zero. 1358 # The countdown behind those event-backed waits, with no GPU: the full unsigned count, no wrap past zero.
1234 add_executable(d3d12_fence_waiter_test test/d3d12_fence_waiter_test.cpp) 1359 add_executable(d3d12_fence_waiter_test test/d3d12_fence_waiter_test.cpp)
1235 target_compile_definitions(d3d12_fence_waiter_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) 1360 target_compile_definitions(d3d12_fence_waiter_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
@@ -1301,6 +1426,24 @@ if(TARGET Vulkan::Headers)
1301 target_compile_options(d3d12_predicated_copy_test PRIVATE /W4 /permissive- /utf-8) 1426 target_compile_options(d3d12_predicated_copy_test PRIVATE /W4 /permissive- /utf-8)
1302 add_test(NAME d3d12_predicated_copy COMMAND d3d12_predicated_copy_test) 1427 add_test(NAME d3d12_predicated_copy COMMAND d3d12_predicated_copy_test)
1303 set_tests_properties(d3d12_predicated_copy PROPERTIES SKIP_RETURN_CODE 77) 1428 set_tests_properties(d3d12_predicated_copy PROPERTIES SKIP_RETURN_CODE 77)
1429 # A DISPATCH-only ExecuteIndirect signature with a GPU count buffer: native Windows WARP versus Vulkan GPU,
1430 # including a GPU-written count that changes between two calls in the same command list.
1431 if(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE)
1432 set(_indirect_count_spv ${CMAKE_CURRENT_BINARY_DIR}/generated/cs_indirect_dispatch_count.spv)
1433 add_custom_command(OUTPUT ${_indirect_count_spv}
1434 COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.2
1435 -o ${_indirect_count_spv} ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_indirect_dispatch_count.comp
1436 DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_indirect_dispatch_count.comp
1437 COMMENT "Compiling the counted indirect dispatch test shader" VERBATIM)
1438 add_executable(d3d12_indirect_dispatch_count_test test/d3d12_indirect_dispatch_count_test.cpp
1439 ${_indirect_count_spv})
1440 target_link_libraries(d3d12_indirect_dispatch_count_test PRIVATE gta6rt_d3d12_com d3d12 dxgi)
1441 target_compile_definitions(d3d12_indirect_dispatch_count_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX
1442 LEONIDA_TEST_INDIRECT_COUNT_SPV="${_indirect_count_spv}")
1443 target_compile_options(d3d12_indirect_dispatch_count_test PRIVATE /W4 /permissive- /utf-8)
1444 add_test(NAME d3d12_indirect_dispatch_count COMMAND d3d12_indirect_dispatch_count_test)
1445 set_tests_properties(d3d12_indirect_dispatch_count PROPERTIES SKIP_RETURN_CODE 77)
1446 endif()
1304 1447
1305 # Differential regression: run explicitly (requires Vulkan hardware and Windows WARP). 1448 # Differential regression: run explicitly (requires Vulkan hardware and Windows WARP).
1306 add_executable(d3d12_clear_test test/d3d12_clear_test.cpp) 1449 add_executable(d3d12_clear_test test/d3d12_clear_test.cpp)
@@ -1379,6 +1522,22 @@ if(TARGET Vulkan::Headers)
1379 add_test(NAME d3d12_subresource_copy COMMAND d3d12_subresource_copy_test) 1522 add_test(NAME d3d12_subresource_copy COMMAND d3d12_subresource_copy_test)
1380 set_tests_properties(d3d12_subresource_copy PROPERTIES SKIP_RETURN_CODE 77) 1523 set_tests_properties(d3d12_subresource_copy PROPERTIES SKIP_RETURN_CODE 77)
1381 1524
1525 # MakeResident, Evict, SetResidencyPriority and EnqueueMakeResident, compared with the host runtime.
1526 add_executable(d3d12_residency_test test/d3d12_residency_test.cpp)
1527 target_link_libraries(d3d12_residency_test PRIVATE gta6rt_d3d12_com d3d12 dxgi)
1528 target_compile_definitions(d3d12_residency_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
1529 target_compile_options(d3d12_residency_test PRIVATE /W4 /permissive- /utf-8)
1530 add_test(NAME d3d12_residency COMMAND d3d12_residency_test)
1531 set_tests_properties(d3d12_residency PROPERTIES SKIP_RETURN_CODE 77)
1532
1533 # ID3D12Resource::GetHeapProperties for committed, placed and reserved resources, compared with the host runtime.
1534 add_executable(d3d12_heap_properties_test test/d3d12_heap_properties_test.cpp)
1535 target_link_libraries(d3d12_heap_properties_test PRIVATE gta6rt_d3d12_com d3d12 dxgi)
1536 target_compile_definitions(d3d12_heap_properties_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
1537 target_compile_options(d3d12_heap_properties_test PRIVATE /W4 /permissive- /utf-8)
1538 add_test(NAME d3d12_heap_properties COMMAND d3d12_heap_properties_test)
1539 set_tests_properties(d3d12_heap_properties PROPERTIES SKIP_RETURN_CODE 77)
1540
1382 # Milestone M0: a window, 60 cleared frames presented through the proxy on Vulkan. 1541 # Milestone M0: a window, 60 cleared frames presented through the proxy on Vulkan.
1383 add_executable(d3d12_present_test test/d3d12_present_test.cpp) 1542 add_executable(d3d12_present_test test/d3d12_present_test.cpp)
1384 target_link_libraries(d3d12_present_test PRIVATE gta6rt_d3d12_com user32 gdi32 dxgi) 1543 target_link_libraries(d3d12_present_test PRIVATE gta6rt_d3d12_com user32 gdi32 dxgi)
@@ -1460,18 +1619,20 @@ if(TARGET Vulkan::Headers)
1460 # D3D12 API only. 1619 # D3D12 API only.
1461 set(LEONIDA_M2_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/m2_shaders) 1620 set(LEONIDA_M2_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/m2_shaders)
1462 set(LEONIDA_M2_FILES ${LEONIDA_M2_DIR}/spirv/index.json ${LEONIDA_M2_DIR}/fssm/vs_m2.fssm 1621 set(LEONIDA_M2_FILES ${LEONIDA_M2_DIR}/spirv/index.json ${LEONIDA_M2_DIR}/fssm/vs_m2.fssm
1463 ${LEONIDA_M2_DIR}/fssm/ps_m2.fssm ${LEONIDA_M2_DIR}/fssm/ps_m2_uoff.fssm) 1622 ${LEONIDA_M2_DIR}/fssm/ps_m2.fssm ${LEONIDA_M2_DIR}/fssm/ps_m2_uoff.fssm
1623 ${LEONIDA_M2_DIR}/fssm/ps_m2_literal.fssm)
1464 add_custom_command( 1624 add_custom_command(
1465 OUTPUT ${LEONIDA_M2_FILES} 1625 OUTPUT ${LEONIDA_M2_FILES}
1466 COMMAND ${CMAKE_COMMAND} -E remove_directory ${LEONIDA_M2_DIR} 1626 COMMAND ${CMAKE_COMMAND} -E remove_directory ${LEONIDA_M2_DIR}
1467 COMMAND ${CMAKE_COMMAND} -E env "LLVM_MC=${LEONIDA_LLVM_MC}" "LEONIDA_SPIRV_TOOLS=${LEONIDA_SPIRV_TOOLS_NATIVE}" 1627 COMMAND ${CMAKE_COMMAND} -E env "LLVM_MC=${LEONIDA_LLVM_MC}" "LEONIDA_SPIRV_TOOLS=${LEONIDA_SPIRV_TOOLS_NATIVE}"
1468 $<TARGET_FILE:Python3::Interpreter> -I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py 1628 $<TARGET_FILE:Python3::Interpreter> -I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py
1469 ${LEONIDA_M2_DIR} vs_m2 ps_m2 ps_m2_uoff 1629 ${LEONIDA_M2_DIR} vs_m2 ps_m2 ps_m2_uoff ps_m2_literal
1470 DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py 1630 DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py
1471 ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/compute_fixture.py 1631 ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/compute_fixture.py
1472 ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/vs_m2.asm 1632 ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/vs_m2.asm
1473 ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_m2.asm 1633 ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_m2.asm
1474 ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_m2_uoff.asm 1634 ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_m2_uoff.asm
1635 ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_m2_literal.asm
1475 ${CMAKE_CURRENT_SOURCE_DIR}/../tools/rdna2spirv.py 1636 ${CMAKE_CURRENT_SOURCE_DIR}/../tools/rdna2spirv.py
1476 COMMENT "Translating vs_m2 and ps_m2 for the textured draw test" 1637 COMMENT "Translating vs_m2 and ps_m2 for the textured draw test"
1477 VERBATIM) 1638 VERBATIM)
@@ -1653,6 +1814,14 @@ if(TARGET Vulkan::Headers)
1653 add_test(NAME dxgi_swapchain COMMAND dxgi_swapchain_test) 1814 add_test(NAME dxgi_swapchain COMMAND dxgi_swapchain_test)
1654 set_tests_properties(dxgi_swapchain PROPERTIES SKIP_RETURN_CODE 77) 1815 set_tests_properties(dxgi_swapchain PROPERTIES SKIP_RETURN_CODE 77)
1655 1816
1817 # Synthetic (no GPU): VulkanSwapchain's DXGI BufferCount contract when Vulkan returns more images than the
1818 # app asked for, or the surface minimum exceeds the request (D3D-389).
1819 add_executable(dxgi_swapchain_count_test test/dxgi_swapchain_count_test.cpp)
1820 target_link_libraries(dxgi_swapchain_count_test PRIVATE Vulkan::Headers)
1821 target_compile_definitions(dxgi_swapchain_count_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
1822 target_compile_options(dxgi_swapchain_count_test PRIVATE /W4 /permissive- /utf-8)
1823 add_test(NAME dxgi_swapchain_count COMMAND dxgi_swapchain_count_test)
1824
1656 # ExecuteIndirect with CountBuffer (vkCmdDrawIndirectCount) + optional BLAS/TLAS/RayQueryKHR GPU test. 1825 # ExecuteIndirect with CountBuffer (vkCmdDrawIndirectCount) + optional BLAS/TLAS/RayQueryKHR GPU test.
1657 add_executable(d3d12_indirect_rt_test test/d3d12_indirect_rt_test.cpp) 1826 add_executable(d3d12_indirect_rt_test test/d3d12_indirect_rt_test.cpp)
1658 target_link_libraries(d3d12_indirect_rt_test PRIVATE gta6rt_d3d12_com) 1827 target_link_libraries(d3d12_indirect_rt_test PRIVATE gta6rt_d3d12_com)
@@ -1789,6 +1958,36 @@ if(TARGET Vulkan::Headers)
1789 target_compile_options(d3d12_geometry_test PRIVATE /W4 /permissive- /utf-8) 1958 target_compile_options(d3d12_geometry_test PRIVATE /W4 /permissive- /utf-8)
1790 add_test(NAME d3d12_geometry COMMAND d3d12_geometry_test) 1959 add_test(NAME d3d12_geometry COMMAND d3d12_geometry_test)
1791 set_tests_properties(d3d12_geometry PROPERTIES SKIP_RETURN_CODE 77) 1960 set_tests_properties(d3d12_geometry PROPERTIES SKIP_RETURN_CODE 77)
1961 # D3D-309: D24 depth bias and 24-bit depth in draws, with and without a pixel shader and with a geometry shader
1962 # (src/depth24_fragment.h).
1963 set(LEONIDA_TEST_VS_DEPTH ${CMAKE_CURRENT_BINARY_DIR}/generated/vs_depth.spv)
1964 set(LEONIDA_TEST_PS_DEPTH_EMPTY ${CMAKE_CURRENT_BINARY_DIR}/generated/ps_depth_empty.spv)
1965 set(LEONIDA_TEST_PS_DEPTH_WRITE ${CMAKE_CURRENT_BINARY_DIR}/generated/ps_depth_write.spv)
1966 set(LEONIDA_TEST_GS_DEPTH ${CMAKE_CURRENT_BINARY_DIR}/generated/gs_depth.spv)
1967 foreach(pair "vs_depth.vert;${LEONIDA_TEST_VS_DEPTH}" "ps_depth_empty.frag;${LEONIDA_TEST_PS_DEPTH_EMPTY}"
1968 "ps_depth_write.frag;${LEONIDA_TEST_PS_DEPTH_WRITE}" "gs_depth.geom;${LEONIDA_TEST_GS_DEPTH}")
1969 list(GET pair 0 source)
1970 list(GET pair 1 output)
1971 add_custom_command(
1972 OUTPUT ${output}
1973 COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${output}
1974 ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${source}
1975 DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${source}
1976 COMMENT "Compiling the D24 draw test shader ${source}"
1977 VERBATIM)
1978 endforeach()
1979 add_executable(d3d12_depth24_draw_test test/d3d12_depth24_draw_test.cpp shims/d3d12_xs_device.cpp
1980 ${LEONIDA_TEST_VS_DEPTH} ${LEONIDA_TEST_PS_DEPTH_EMPTY} ${LEONIDA_TEST_PS_DEPTH_WRITE}
1981 ${LEONIDA_TEST_GS_DEPTH})
1982 target_link_libraries(d3d12_depth24_draw_test PRIVATE gta6rt_d3d12_com)
1983 target_compile_definitions(d3d12_depth24_draw_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX
1984 LEONIDA_TEST_VS_DEPTH_SPV="${LEONIDA_TEST_VS_DEPTH}"
1985 LEONIDA_TEST_PS_DEPTH_EMPTY_SPV="${LEONIDA_TEST_PS_DEPTH_EMPTY}"
1986 LEONIDA_TEST_PS_DEPTH_WRITE_SPV="${LEONIDA_TEST_PS_DEPTH_WRITE}"
1987 LEONIDA_TEST_GS_DEPTH_SPV="${LEONIDA_TEST_GS_DEPTH}")
1988 target_compile_options(d3d12_depth24_draw_test PRIVATE /W4 /permissive- /utf-8)
1989 add_test(NAME d3d12_depth24_draw COMMAND d3d12_depth24_draw_test)
1990 set_tests_properties(d3d12_depth24_draw PROPERTIES SKIP_RETURN_CODE 77)
1792 # Set 0 from the compute bind point: a compute PSO whose shader declares set-0 bindings samples through the 1991 # Set 0 from the compute bind point: a compute PSO whose shader declares set-0 bindings samples through the
1793 # device's bindless set, which nothing but the layer binds. 1992 # device's bindless set, which nothing but the layer binds.
1794 set(LEONIDA_TEST_CS_SET0_SAMPLE ${CMAKE_CURRENT_BINARY_DIR}/generated/cs_set0_sample.spv) 1993 set(LEONIDA_TEST_CS_SET0_SAMPLE ${CMAKE_CURRENT_BINARY_DIR}/generated/cs_set0_sample.spv)
@@ -1894,6 +2093,33 @@ if(TARGET Vulkan::Headers)
1894 if(TARGET gta6rt) 2093 if(TARGET gta6rt)
1895 target_link_libraries(gta6rt PRIVATE gta6rt_d3d12_com user32) # user32: the PresentX window 2094 target_link_libraries(gta6rt PRIVATE gta6rt_d3d12_com user32) # user32: the PresentX window
1896 target_compile_definitions(gta6rt PRIVATE LEONIDA_VULKAN_DEVICE) 2095 target_compile_definitions(gta6rt PRIVATE LEONIDA_VULKAN_DEVICE)
2096
2097 # A stand-in title that imports d3d12_xs.dll!D3D12XboxCreateDevice and runs a clear and a readback on the
2098 # device it gets, mapped and run by `gta6rt --run` with LEONIDA_D3D12=vulkan: the loader, the game thread, the
2099 # proxies and the Vulkan device in one process. check_tiny_frame.py reads the verdict, the binding and the
2100 # call order from outside; d3d12_com_test is its probe for "no usable Vulkan device" (exit code 77).
2101 add_library(d3d12_xs_stub SHARED test/fixtures/d3d12_xs_stub.cpp test/fixtures/d3d12_xs_stub.def)
2102 target_compile_definitions(d3d12_xs_stub PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
2103 target_compile_options(d3d12_xs_stub PRIVATE /W4 /permissive- /utf-8)
2104 set_target_properties(d3d12_xs_stub PROPERTIES
2105 OUTPUT_NAME d3d12_xs
2106 PREFIX ""
2107 RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/stubs/$<CONFIG>"
2108 ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/stubs/$<CONFIG>"
2109 )
2110 add_executable(tiny_frame test/fixtures/tiny_frame.cpp)
2111 target_link_libraries(tiny_frame PRIVATE d3d12_xs_stub)
2112 target_compile_definitions(tiny_frame PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
2113 target_compile_options(tiny_frame PRIVATE /W4 /permissive- /utf-8)
2114 set_target_properties(tiny_frame PROPERTIES
2115 RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$<CONFIG>"
2116 )
2117 if(Python3_FOUND)
2118 add_test(NAME run_tiny_frame COMMAND "${Python3_EXECUTABLE}" -I
2119 "${CMAKE_CURRENT_SOURCE_DIR}/test/check_tiny_frame.py" "$<TARGET_FILE:gta6rt>"
2120 "$<TARGET_FILE:tiny_frame>" "--probe=$<TARGET_FILE:d3d12_com_test>" ${_trace_runner})
2121 set_tests_properties(run_tiny_frame PROPERTIES SKIP_RETURN_CODE 77)
2122 endif()
1897 endif() 2123 endif()
1898 # bvh_builder_test can put the package's XboxBvhBuilder on this device too (LEONIDA_BVH_DEVICE=vulkan). 2124 # bvh_builder_test can put the package's XboxBvhBuilder on this device too (LEONIDA_BVH_DEVICE=vulkan).
1899 if(TARGET bvh_builder_test) 2125 if(TARGET bvh_builder_test)
diff --git a/runtime/README.md b/runtime/README.md
index 23eb2fb97..aace038d9 100644
--- a/runtime/README.md
+++ b/runtime/README.md
@@ -161,8 +161,9 @@ Current limits, by design:
161 the measured-slot Xbox-ABI proxy: the host PC `ID3D12Device` by default, or the Vulkan-backed device 161 the measured-slot Xbox-ABI proxy: the host PC `ID3D12Device` by default, or the Vulkan-backed device
162 (`shims/d3d12_vulkan_device.cpp`) when `LEONIDA_D3D12=vulkan` is set and the runtime was built with the 162 (`shims/d3d12_vulkan_device.cpp`) when `LEONIDA_D3D12=vulkan` is set and the runtime was built with the
163 Vulkan SDK and Python 3. The Vulkan device covers command submission, descriptor heaps, render-target and 163 Vulkan SDK and Python 3. The Vulkan device covers command submission, descriptor heaps, render-target and
164 depth views, committed resources and copies (uploads, readbacks, BC textures); see `docs/d3d12_vulkan.md` 164 depth views, committed resources and copies (uploads, readbacks, BC textures), root signatures, graphics and
165 section 3.2 for what is missing. 165 compute pipeline states, draws, dispatches and `ExecuteIndirect`; see `docs/d3d12_vulkan.md` for what is
166 missing.
166 167
167- `gameinput.dll` / `xgameruntime.dll` — `GameInputCreate`: the v0 GameInput API for gamepads on SDL3 168- `gameinput.dll` / `xgameruntime.dll` — `GameInputCreate`: the v0 GameInput API for gamepads on SDL3
168 (`shims/gameinput.cpp`), so any controller SDL supports works, with rumble, Xbox trigger rumble, force feedback 169 (`shims/gameinput.cpp`), so any controller SDL supports works, with rumble, Xbox trigger rumble, force feedback
@@ -172,6 +173,22 @@ Current limits, by design:
172 `scripts/build_runtime.ps1` cl.exe fallback never builds it. See [docs/gameinput.md](../docs/gameinput.md) for the mapping, the `LEONIDA_DS_*` settings and what is 173 `scripts/build_runtime.ps1` cl.exe fallback never builds it. See [docs/gameinput.md](../docs/gameinput.md) for the mapping, the `LEONIDA_DS_*` settings and what is
173 unverified. 174 unverified.
174 175
176### What `xgameruntime.dll` reports: environment overrides
177
178The `xgameruntime` shim (`shims/xgameruntime.cpp`) answers the title's questions about the console and its package
179with fixed values. Five environment variables change an answer, for trying another of the title's code paths. Each
180is read on every call, and a value that is empty or too long for its buffer is ignored.
181`tests/test_docs_env_vars.py` fails when the runtime or `make_game.py` reads a `LEONIDA_*` variable that no
182document names.
183
184| variable | default | what it changes |
185|---|---|---|
186| `LEONIDA_DEVICE_TYPE` | `7` | The `XSystemDeviceType` that `XSystemGetDeviceType` returns: `0` Unknown, `1` Pc, `2` XboxOne, `3` XboxOneS, `4` XboxOneX, `5` XboxOneXDevkit, `6` XboxScarlettLockhart (Series S), `7` XboxScarlettAnaconda (Series X), `8` XboxScarlettDevkit. A number outside 0..8 is ignored; text that is not a number counts as `0`. `6` also makes `XSystemGetAnalyticsInfo` report the form `Xbox Series S` instead of `Xbox Series X`. |
187| `LEONIDA_ANALYTICS_FORM` | unset | The `form` string of `XSystemGetAnalyticsInfo`, in place of the one the device type gives (up to 63 characters). |
188| `LEONIDA_PACKAGE_ID` | `LeonidaPackageIdentifier00000000` | The identifier `XPackageGetCurrentProcessPackageIdentifier` returns (up to 32 characters). It is also the one identifier `XPackageMount` refuses with `E_ACCESSDENIED`, as the game's own package. |
189| `LEONIDA_CONTENT_PACKAGES` | unset | The content packages `XPackageMount` can mount: `id1=path1;id2=path2` (up to 1,023 characters). The mount path of a listed identifier is its path, as written; any other identifier is `ERROR_NOT_FOUND`, and a path longer than 259 characters is `ERROR_INSUFFICIENT_BUFFER`. |
190| `LEONIDA_PACKAGED` | `1` | `0`, or text that is not a number, makes `XPackageIsPackagedProcess` return false. Any other number keeps it true. |
191
175The two serializer functions and `D3D12XboxCreateDevice` are the only `d3d12_xs` imports used by the 192The two serializer functions and `D3D12XboxCreateDevice` are the only `d3d12_xs` imports used by the
176shipped DLLs (measured; see `docs/design.md` and `docs/d3d12_vulkan.md`). The game executable's own 193shipped DLLs (measured; see `docs/design.md` and `docs/d3d12_vulkan.md`). The game executable's own
177imports are unknown until it is available. 194imports are unknown until it is available.
@@ -254,10 +271,36 @@ It prints counts only; on the 1.0.2.1 corpus all 26,503 containers resolve.
254 271
255`gta6rt --run <exe> [-- args]` runs an executable's entry point inside the runtime (`shims/process.cpp` gives it its 272`gta6rt --run <exe> [-- args]` runs an executable's entry point inside the runtime (`shims/process.cpp` gives it its
256own command line and turns its `exit` into the end of the run); CTest's `run_tiny_game` does that with a stand-in game. 273own command line and turns its `exit` into the end of the run); CTest's `run_tiny_game` does that with a stand-in game.
274The game's `atexit` handlers and static destructors go to a table of the run's own (the CRT's process-wide one is
275shared with gta6rt): `exit` and a return from `main` run them newest first before the run ends, `_cexit` runs them and
276returns, and `_exit`, `quick_exit`, `ExitProcess` and `abort` skip them, as natively. `run_tiny_atexit` runs a stand-in
277program natively and through `--run` for each of those paths (and for `_exit` from a second thread during `exit`) and
278holds both to the Windows sequence (under Wine, whose CRT differs, a native difference is only reported). Not covered
279yet: `at_quick_exit` handlers (`quick_exit` runs none) and the thread-local destructor callback
280(`_register_thread_local_exe_atexit_callback`); both still reach the host CRT.
281`run_tiny_frame` does it with a stand-in that imports `d3d12_xs.dll!D3D12XboxCreateDevice` and, with
282`LEONIDA_D3D12=vulkan`, clears a render target and reads it back on the Vulkan device: the loader, the game thread,
283the Xbox-ABI proxies and the device in one process (`test/fixtures/tiny_frame.cpp`; `test/check_tiny_frame.py` checks
284the verdict, the `shim` binding and the call order in the `--trace-d3d12` output, and skips without a Vulkan GPU).
257The game does not boot yet. The missing executable blocks the import-driven work: the real device 285The game does not boot yet. The missing executable blocks the import-driven work: the real device
258entry point, command-list/queue/fence extensions, `PresentX`, and most of the `xgameruntime` surface (an offline 286entry point, command-list/queue/fence extensions, `PresentX`, and most of the `xgameruntime` surface (an offline
259shim covers `XGameRuntimeInitialize`, device/console queries, `XTaskQueue` and `XAsync`; see `xgameruntime_test`). The 287shim covers `XGameRuntimeInitialize`, device/console queries, `XTaskQueue` and `XAsync`; see `xgameruntime_test`). The
260D3D12-to-Vulkan design and the measured console ABI are in 288D3D12-to-Vulkan design and the measured console ABI are in
289The game does not boot yet, and none of this has been measured against the real executable. The missing executable
290blocks the import-driven work:
291
292- The device entry point: `D3D12XboxCreateDevice` exists and wraps the PC or the Vulkan-backed device in the
293 measured-slot proxy, but its parameter and flag layout is unmeasured and so is the Xbox device vtable beyond
294 slots 62, 67 and 76.
295- The command-queue and fence extensions: the proxies forward the public slots, and the console's own methods past
296 them (`PresentX`, `SuspendX`, `ResumeX`) have unknown slots, so they are refused with a log.
297 `PresentX` and the frame events themselves are implemented (`shims/xbox_present.*`, `xbox_present_test`) but
298 nothing reaches them yet: their queue and device slots are unmeasured.
299- Most of the `xgameruntime` surface: an offline shim covers `XGameRuntimeInitialize`, device/console queries,
300 `XTaskQueue` and `XAsync`, and `QueryApiImpl` serves `XThreadingImpl`, `XErrorImpl`, `XNetworkingImpl` and
301 `XSystemImpl` (see `xgameruntime_test`); any other class is refused with a log.
302
303The D3D12-to-Vulkan design and the measured console ABI are in
261[docs/d3d12_vulkan.md](../docs/d3d12_vulkan.md); the shader translator and its GPU checks are described 304[docs/d3d12_vulkan.md](../docs/d3d12_vulkan.md); the shader translator and its GPU checks are described
262in [docs/design.md](../docs/design.md), and the differential-validation design is in the shader-validation 305in [docs/design.md](../docs/design.md), and the differential-validation design is in the shader-validation
263work. 306work.
@@ -294,6 +337,7 @@ from the ANSI code page.
294| `tls_callback` | before each TLS callback the Loader runs (process attach and detach; thread events run under the Windows loader lock and are not traced) | `module`, `at` (module+RVA), `reason` | 337| `tls_callback` | before each TLS callback the Loader runs (process attach and detach; thread events run under the Windows loader lock and are not traced) | `module`, `at` (module+RVA), `reason` |
295| `dllmain` | after `DllMain(DLL_PROCESS_ATTACH)` returns | `module`, `result` | 338| `dllmain` | after `DllMain(DLL_PROCESS_ATTACH)` returns | `module`, `result` |
296| `unimplemented_call` | first call of each unimplemented import | `import` (`dll!name`), `caller` (module+RVA) | 339| `unimplemented_call` | first call of each unimplemented import | `import` (`dll!name`), `caller` (module+RVA) |
340| `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) |
297| `debug_string` | `OutputDebugStringA/W` with no debugger attached | `text` | 341| `debug_string` | `OutputDebugStringA/W` with no debugger attached | `text` |
298| `exception` | any exception, before handlers run | `code`, `at`, `access`/`address` for access violations, `cpp` for C++ throws, `stack` (up to 16 frames) | 342| `exception` | any exception, before handlers run | `code`, `at`, `access`/`address` for access violations, `cpp` for C++ throws, `stack` (up to 16 frames) |
299| `exit` / `error` | `--run` returns, or the loader throws | `code` / `what` | 343| `exit` / `error` | `--run` returns, or the loader throws | `code` / `what` |
@@ -379,6 +423,17 @@ $env:LEONIDA_VK_VALIDATION = '1'
379.\runtime\build\RelWithDebInfo\d3d12_resource_desc_test.exe 423.\runtime\build\RelWithDebInfo\d3d12_resource_desc_test.exe
380``` 424```
381 425
426`d3d12_placed_dimensions_test` places 1D and 3D textures (arrays, mips, BC1, UAV and render targets, plus a 2D
427control) in heaps big enough for both sides' `GetResourceAllocationInfo`, at offset 0 and at 64 KiB, on the
428Vulkan-backed device and on Windows D3D12 (the default adapter and WARP), and compares the answers and `GetDesc`. A
429dimension outside the enum must be refused alike. It also copies a pattern through a buffer into every subresource of a placed
4303D texture and a placed 1D array and back, and checks the bytes. It needs a Vulkan GPU.
431
432```powershell
433$env:LEONIDA_VK_VALIDATION = '1'
434.\runtime\build\RelWithDebInfo\d3d12_placed_dimensions_test.exe
435```
436
382### Depth and stencil resolves 437### Depth and stencil resolves
383 438
384`d3d12_depth_resolve_test` resolves one plane of a 4x D32 or D24S8 target into a 1x one with 439`d3d12_depth_resolve_test` resolves one plane of a 4x D32 or D24S8 target into a 1x one with
diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp
index d9b1a009c..6858f073c 100644
--- a/runtime/shims/d3d12_com.cpp
+++ b/runtime/shims/d3d12_com.cpp
@@ -368,6 +368,7 @@ public:
368 if (count > D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT) return check(false); 368 if (count > D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT) return check(false);
369 render_targets_.fill({}); 369 render_targets_.fill({});
370 render_target_count_ = count; 370 render_target_count_ = count;
371 draw_views_stale_ = true;
371 for (UINT i = 0; i < count && targets; ++i) { 372 for (UINT i = 0; i < count && targets; ++i) {
372 const SIZE_T handle = single_range ? targets[0].ptr + SIZE_T(i) * descriptor_size : targets[i].ptr; 373 const SIZE_T handle = single_range ? targets[0].ptr + SIZE_T(i) * descriptor_size : targets[i].ptr;
373 if (handle) render_targets_[i] = *reinterpret_cast<const leonida::TargetView*>(handle); 374 if (handle) render_targets_[i] = *reinterpret_cast<const leonida::TargetView*>(handle);
@@ -989,6 +990,10 @@ private:
989 leonida::Rect scissor_{}; 990 leonida::Rect scissor_{};
990 std::array<leonida::TargetView, D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT> render_targets_{}; 991 std::array<leonida::TargetView, D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT> render_targets_{};
991 UINT render_target_count_ = 0; 992 UINT render_target_count_ = 0;
993 // One block shared by every draw that keeps the same targets and buffers, rebuilt when either changes, so a
994 // run of draws does not allocate per draw.
995 std::shared_ptr<const leonida::DrawViews> draw_views_;
996 bool draw_views_stale_ = true;
992 leonida::TargetView depth_{}; 997 leonida::TargetView depth_{};
993 std::array<float, 4> blend_factor_{1, 1, 1, 1}; 998 std::array<float, 4> blend_factor_{1, 1, 1, 1};
994 999
@@ -1053,12 +1058,14 @@ private:
1053 scissor_ = {}; 1058 scissor_ = {};
1054 render_targets_.fill({}); 1059 render_targets_.fill({});
1055 render_target_count_ = 0; 1060 render_target_count_ = 0;
1061 draw_views_stale_ = true;
1056 depth_ = {}; 1062 depth_ = {};
1057 blend_factor_ = {1, 1, 1, 1}; 1063 blend_factor_ = {1, 1, 1, 1};
1058 set_pipeline(state); 1064 set_pipeline(state);
1059 } 1065 }
1060 1066
1061 void set_vertex_buffers(UINT start, UINT count, const D3D12_VERTEX_BUFFER_VIEW* views) { 1067 void set_vertex_buffers(UINT start, UINT count, const D3D12_VERTEX_BUFFER_VIEW* views) {
1068 if (count) draw_views_stale_ = true;
1062 for (UINT i = 0; i < count; ++i) 1069 for (UINT i = 0; i < count; ++i)
1063 vertex_buffers_[start + i] = views ? leonida::VertexBufferView{views[i].BufferLocation, views[i].SizeInBytes, 1070 vertex_buffers_[start + i] = views ? leonida::VertexBufferView{views[i].BufferLocation, views[i].SizeInBytes,
1064 views[i].StrideInBytes} 1071 views[i].StrideInBytes}
@@ -1075,16 +1082,28 @@ private:
1075 check(list_.dispatch({compute_pipeline_, compute_.data, x, y, z})); 1082 check(list_.dispatch({compute_pipeline_, compute_.data, x, y, z}));
1076 } 1083 }
1077 1084
1085 // The views block a draw records. Rebuilt only when the render targets or the bound vertex buffers change.
1086 const std::shared_ptr<const leonida::DrawViews>& draw_views() {
1087 if (draw_views_stale_ || !draw_views_) {
1088 auto views = std::make_shared<leonida::DrawViews>();
1089 views->render_targets = render_targets_;
1090 views->vertex_buffers = vertex_buffers_;
1091 views->render_target_count = render_target_count_;
1092 draw_views_ = std::move(views);
1093 draw_views_stale_ = false;
1094 }
1095 return draw_views_;
1096 }
1097
1078 // A draw needs a graphics pipeline, a graphics root signature and a topology. 1098 // A draw needs a graphics pipeline, a graphics root signature and a topology.
1079 void record_draw(bool indexed, UINT count, UINT instances, UINT first, INT base_vertex, UINT first_instance) { 1099 void record_draw(bool indexed, UINT count, UINT instances, UINT first, INT base_vertex, UINT first_instance) {
1080 if (!graphics_pipeline_ || !graphics_.layout || !topology_) return check(false); 1100 if (!graphics_pipeline_ || !graphics_.layout || !topology_) return check(false);
1081 // No viewport (never set, or unbound with RSSetViewports(0)) or an empty one: D3D12 rasterizes nothing, 1101 // No viewport (never set, or unbound with RSSetViewports(0)) or an empty one: D3D12 rasterizes nothing,
1082 // and Vulkan forbids a 0x0 viewport, so the draw is not recorded. 1102 // and Vulkan forbids a 0x0 viewport, so the draw is not recorded.
1083 if (!(viewport_.width > 0) || !(viewport_.height > 0)) return; 1103 if (!(viewport_.width > 0) || !(viewport_.height > 0)) return;
1084 leonida::Draw draw{graphics_pipeline_, graphics_.data, render_targets_, depth_, 1104 leonida::Draw draw{graphics_pipeline_, graphics_.data, draw_views(), depth_, index_, topology_, viewport_,
1085 vertex_buffers_, index_, topology_, viewport_, scissor_, 1105 scissor_, blend_factor_, front_stencil_ref_, back_stencil_ref_, indexed, count, instances,
1086 blend_factor_, front_stencil_ref_, back_stencil_ref_, indexed, count, instances, first, 1106 first, base_vertex, first_instance};
1087 base_vertex, first_instance, render_target_count_};
1088 check(list_.draw(std::move(draw))); 1107 check(list_.draw(std::move(draw)));
1089 } 1108 }
1090}; 1109};
@@ -1542,8 +1561,11 @@ HRESULT create_command_queue(leonida::VulkanContext& context, VkQueue queue, std
1542} 1561}
1543 1562
1544HRESULT create_command_allocator(D3D12_COMMAND_LIST_TYPE type, REFIID riid, void** out, IUnknown* device) { 1563HRESULT create_command_allocator(D3D12_COMMAND_LIST_TYPE type, REFIID riid, void** out, IUnknown* device) {
1545 if (!out) return E_POINTER; 1564 // The host runtime's order (d3d12_vulkan_device_test, compare_invalid_arguments "command allocator:"): a type
1546 *out = nullptr; 1565 // past VIDEO_ENCODE is E_INVALIDARG, then a null output is E_UNEXPECTED.
1566 if (out) *out = nullptr;
1567 if (UINT(type) > UINT(D3D12_COMMAND_LIST_TYPE_VIDEO_ENCODE)) return E_INVALIDARG;
1568 if (!out) return E_UNEXPECTED;
1547 auto* object = new CommandAllocator(type); 1569 auto* object = new CommandAllocator(type);
1548 object->attach_device(device); 1570 object->attach_device(device);
1549 return hand_out(object, riid, out); 1571 return hand_out(object, riid, out);
@@ -1551,12 +1573,13 @@ HRESULT create_command_allocator(D3D12_COMMAND_LIST_TYPE type, REFIID riid, void
1551 1573
1552HRESULT create_command_list(D3D12_COMMAND_LIST_TYPE type, ID3D12CommandAllocator* allocator, REFIID riid, 1574HRESULT create_command_list(D3D12_COMMAND_LIST_TYPE type, ID3D12CommandAllocator* allocator, REFIID riid,
1553 void** out, IUnknown* device, ID3D12PipelineState* initial_state) { 1575 void** out, IUnknown* device, ID3D12PipelineState* initial_state) {
1554 if (!out) return E_POINTER; 1576 if (out) *out = nullptr;
1555 *out = nullptr;
1556 CommandAllocator* command_allocator = CommandAllocator::from(allocator); 1577 CommandAllocator* command_allocator = CommandAllocator::from(allocator);
1557 if (!command_allocator || command_allocator->type() != type) return E_INVALIDARG; 1578 if (!command_allocator || command_allocator->type() != type) return E_INVALIDARG;
1558 // A list is created open, so the allocator must be free: E_INVALIDARG as on the PC runtime (D3D-51). 1579 // A list is created open, so the allocator must be free: E_INVALIDARG as on the PC runtime (D3D-51).
1559 if (command_allocator->recording()) return E_INVALIDARG; 1580 if (command_allocator->recording()) return E_INVALIDARG;
1581 // A null output only after the arguments, as the host runtime answers ("command list:" cases).
1582 if (!out) return E_UNEXPECTED;
1560 if (type != D3D12_COMMAND_LIST_TYPE_DIRECT && type != D3D12_COMMAND_LIST_TYPE_BUNDLE && 1583 if (type != D3D12_COMMAND_LIST_TYPE_DIRECT && type != D3D12_COMMAND_LIST_TYPE_BUNDLE &&
1561 type != D3D12_COMMAND_LIST_TYPE_COMPUTE && type != D3D12_COMMAND_LIST_TYPE_COPY) 1584 type != D3D12_COMMAND_LIST_TYPE_COMPUTE && type != D3D12_COMMAND_LIST_TYPE_COPY)
1562 stub("create_command_list(non-direct type)"); 1585 stub("create_command_list(non-direct type)");
diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h
index d8e084478..6cab20a8e 100644
--- a/runtime/shims/d3d12_com.h
+++ b/runtime/shims/d3d12_com.h
@@ -185,7 +185,9 @@ HRESULT create_vulkan_device(const VulkanDeviceInfo& info, REFIID riid, void** o
185HRESULT create_vulkan_device_standalone(REFIID riid, void** out); 185HRESULT create_vulkan_device_standalone(REFIID riid, void** out);
186 186
187// Tells a device from create_vulkan_device* that `outer` (the Xbox-ABI proxy that owns it) is what its children's 187// Tells a device from create_vulkan_device* that `outer` (the Xbox-ABI proxy that owns it) is what its children's
188// GetDevice must return. No reference is taken: the outer object owns the device. 188// GetDevice must return. No reference is taken: the outer object owns the device. `outer` may be the proxy's
189// IDXGIDevice1 pointer (what create_device_proxy returns for that IID); the proxy itself becomes the outer. For a
190// proxy it also makes the proxy's IDXGIDevice1::GetAdapter return this layer's adapter (d3d12_xs_device.h).
189void set_device_outer(ID3D12Device* device, IUnknown* outer); 191void set_device_outer(ID3D12Device* device, IUnknown* outer);
190 192
191// The VkImage behind a texture created by such a device, or VK_NULL_HANDLE. For tests and the swapchain. 193// The VkImage behind a texture created by such a device, or VK_NULL_HANDLE. For tests and the swapchain.
@@ -299,6 +301,7 @@ public:
299 bool enable_capture(); 301 bool enable_capture();
300 // See VulkanPresenter::set_abort: polled while a present waits for a swapchain image. 302 // See VulkanPresenter::set_abort: polled while a present waits for a swapchain image.
301 void set_abort(std::function<bool()> abort); 303 void set_abort(std::function<bool()> abort);
304 // See VulkanPresenter::read_back: false after a present skipped while the window is minimised, too.
302 bool read_back(std::vector<std::uint8_t>& pixels, VkExtent2D* extent, VkFormat* format); 305 bool read_back(std::vector<std::uint8_t>& pixels, VkExtent2D* extent, VkFormat* format);
303 VkExtent2D extent() const; 306 VkExtent2D extent() const;
304 std::uint64_t presented() const; 307 std::uint64_t presented() const;
diff --git a/runtime/shims/d3d12_feature_compat.h b/runtime/shims/d3d12_feature_compat.h
index ad14f19cd..efba257a7 100644
--- a/runtime/shims/d3d12_feature_compat.h
+++ b/runtime/shims/d3d12_feature_compat.h
@@ -2,10 +2,15 @@
2 2
3#include <d3d12.h> 3#include <d3d12.h>
4 4
5// D3D12_FEATURE values introduced after Windows SDK 10.0.26100.0. Keep their ABI values and payload available to 5#include <cstddef>
6// the runtime and its tests without requiring a newer d3d12.h. 6
7// D3D12 values newer than some Windows SDK 10.0.26100 releases. The README asks for "Windows SDK 10.0.26100 or newer",
8// but the SDK's d3d12.h moved within 10.0.26100 (D3D12_SDK_VERSION 612 in 10.0.26100.6584, 616 later), so anything the
9// runtime uses from a newer header is declared here with its ABI value and payload, and checked against the header
10// where the header has it. That keeps the runtime and its tests building on every 10.0.26100 SDK.
7namespace rt::d3d12::compat { 11namespace rt::d3d12::compat {
8 12
13// Feature values introduced after Windows SDK 10.0.26100.0.
9inline constexpr D3D12_FEATURE kFeatureApplicationSpecificDriverState = static_cast<D3D12_FEATURE>(56); 14inline constexpr D3D12_FEATURE kFeatureApplicationSpecificDriverState = static_cast<D3D12_FEATURE>(56);
10inline constexpr D3D12_FEATURE kFeatureBytecodeBypassHashSupported = static_cast<D3D12_FEATURE>(57); 15inline constexpr D3D12_FEATURE kFeatureBytecodeBypassHashSupported = static_cast<D3D12_FEATURE>(57);
11 16
@@ -15,4 +20,64 @@ struct FeatureSupportFlag {
15 20
16static_assert(sizeof(FeatureSupportFlag) == sizeof(BOOL)); 21static_assert(sizeof(FeatureSupportFlag) == sizeof(BOOL));
17 22
23// D3D12_FEATURE_D3D12_OPTIONS20 and D3D12_FEATURE_PREDICATION: D3D12_SDK_VERSION 611 (DirectX-Headers v1.611.0); not
24// in 610. PREDICATION's payload is one BOOL, FeatureSupportFlag above.
25inline constexpr D3D12_FEATURE kFeatureOptions20 = static_cast<D3D12_FEATURE>(49);
26inline constexpr D3D12_FEATURE kFeaturePredication = static_cast<D3D12_FEATURE>(50);
27inline constexpr UINT kRecreateAtTierNotSupported = 0; // D3D12_RECREATE_AT_TIER_NOT_SUPPORTED
28
29struct FeatureDataOptions20 {
30 BOOL ComputeOnlyWriteWatchSupported;
31 UINT RecreateAtTier; // D3D12_RECREATE_AT_TIER
32};
33
34static_assert(sizeof(FeatureDataOptions20) == 8);
35
36#if defined(D3D12_SDK_VERSION) && D3D12_SDK_VERSION >= 611
37static_assert(kFeatureOptions20 == D3D12_FEATURE_D3D12_OPTIONS20);
38static_assert(kFeaturePredication == D3D12_FEATURE_PREDICATION);
39static_assert(kRecreateAtTierNotSupported == UINT(D3D12_RECREATE_AT_TIER_NOT_SUPPORTED));
40static_assert(sizeof(FeatureDataOptions20) == sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS20));
41static_assert(sizeof(D3D12_RECREATE_AT_TIER) == sizeof(UINT));
42static_assert(offsetof(FeatureDataOptions20, RecreateAtTier) ==
43 offsetof(D3D12_FEATURE_DATA_D3D12_OPTIONS20, RecreateAtTier));
44static_assert(sizeof(FeatureSupportFlag) == sizeof(D3D12_FEATURE_DATA_PREDICATION));
45#endif
46
47// D3D12_FEATURE_D3D12_OPTIONS21 (work graphs and the ExecuteIndirect tier): D3D12_SDK_VERSION 613 (DirectX-Headers
48// v1.613.0); not in 611. The enums are UINT-sized in d3d12.h, as here.
49inline constexpr D3D12_FEATURE kFeatureOptions21 = static_cast<D3D12_FEATURE>(53);
50inline constexpr UINT kWorkGraphsTierNotSupported = 0; // D3D12_WORK_GRAPHS_TIER_NOT_SUPPORTED
51inline constexpr UINT kExecuteIndirectTier1_0 = 10; // D3D12_EXECUTE_INDIRECT_TIER_1_0
52
53struct FeatureDataOptions21 {
54 UINT WorkGraphsTier; // D3D12_WORK_GRAPHS_TIER
55 UINT ExecuteIndirectTier; // D3D12_EXECUTE_INDIRECT_TIER
56 BOOL SampleCmpGradientAndBiasSupported;
57 BOOL ExtendedCommandInfoSupported;
58};
59
60static_assert(sizeof(FeatureDataOptions21) == 16);
61
62// D3D12_INDIRECT_ARGUMENT_TYPE_INCREMENTING_CONSTANT (ExecuteIndirect tier 1.1): the value after DISPATCH_MESH, from
63// the same header version as OPTIONS21.
64inline constexpr D3D12_INDIRECT_ARGUMENT_TYPE kIndirectArgumentIncrementingConstant =
65 static_cast<D3D12_INDIRECT_ARGUMENT_TYPE>(D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH + 1);
66
67#if defined(D3D12_SDK_VERSION) && D3D12_SDK_VERSION >= 613
68// A header that declares these must agree with the values above.
69static_assert(kFeatureOptions21 == D3D12_FEATURE_D3D12_OPTIONS21);
70static_assert(kWorkGraphsTierNotSupported == UINT(D3D12_WORK_GRAPHS_TIER_NOT_SUPPORTED));
71static_assert(kExecuteIndirectTier1_0 == UINT(D3D12_EXECUTE_INDIRECT_TIER_1_0));
72static_assert(kIndirectArgumentIncrementingConstant == D3D12_INDIRECT_ARGUMENT_TYPE_INCREMENTING_CONSTANT);
73static_assert(sizeof(FeatureDataOptions21) == sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS21));
74static_assert(sizeof(D3D12_WORK_GRAPHS_TIER) == sizeof(UINT) && sizeof(D3D12_EXECUTE_INDIRECT_TIER) == sizeof(UINT));
75static_assert(offsetof(FeatureDataOptions21, ExecuteIndirectTier) ==
76 offsetof(D3D12_FEATURE_DATA_D3D12_OPTIONS21, ExecuteIndirectTier));
77static_assert(offsetof(FeatureDataOptions21, SampleCmpGradientAndBiasSupported) ==
78 offsetof(D3D12_FEATURE_DATA_D3D12_OPTIONS21, SampleCmpGradientAndBiasSupported));
79static_assert(offsetof(FeatureDataOptions21, ExtendedCommandInfoSupported) ==
80 offsetof(D3D12_FEATURE_DATA_D3D12_OPTIONS21, ExtendedCommandInfoSupported));
81#endif
82
18} // namespace rt::d3d12::compat 83} // namespace rt::d3d12::compat
diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp
index 2b6d1c806..ded17e79d 100644
--- a/runtime/shims/d3d12_vulkan_device.cpp
+++ b/runtime/shims/d3d12_vulkan_device.cpp
@@ -16,6 +16,7 @@
16#include "d3d12_xs_device.h" 16#include "d3d12_xs_device.h"
17#include "dxgi_com.h" 17#include "dxgi_com.h"
18#include "../src/gfx10_descriptors.h" 18#include "../src/gfx10_descriptors.h"
19#include "../src/depth24_fragment.h"
19#include "../src/uav_clear.h" 20#include "../src/uav_clear.h"
20#include "../src/vulkan_bindless.h" 21#include "../src/vulkan_bindless.h"
21#include "../src/vulkan_memory.h" 22#include "../src/vulkan_memory.h"
@@ -79,6 +80,81 @@ void log_once(const char* what, int value) {
79 if (seen.insert({what, value}).second) std::fprintf(stderr, "[rt] d3d12: %s %d\n", what, value); 80 if (seen.insert({what, value}).second) std::fprintf(stderr, "[rt] d3d12: %s %d\n", what, value);
80} 81}
81 82
83// The pipelines build stage writes its cache beside gta6rt.exe, independently of the working directory.
84std::filesystem::path pipeline_cache_path() {
85 std::wstring path(32768, L'\0');
86 const DWORD length = GetModuleFileNameW(nullptr, path.data(), static_cast<DWORD>(path.size()));
87 if (!length || length >= path.size()) return {};
88 path.resize(length);
89 return std::filesystem::path(path).parent_path() / L"pipeline_cache.bin";
90}
91
92// A corpus cache may be several GiB. Keep the read-only view alive through vkCreatePipelineCache
93// and deny writers while the view is in use.
94class PipelineCacheSeed {
95public:
96 explicit PipelineCacheSeed(const std::filesystem::path& path) {
97 if (path.empty()) return;
98 file_ = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, nullptr,
99 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
100 if (file_ == INVALID_HANDLE_VALUE) return;
101 LARGE_INTEGER length{};
102 constexpr auto header_size = static_cast<LONGLONG>(sizeof(VkPipelineCacheHeaderVersionOne));
103 if (!GetFileSizeEx(file_, &length) || length.QuadPart < header_size)
104 return;
105 const HANDLE mapping = CreateFileMappingW(file_, nullptr, PAGE_READONLY, 0, 0, nullptr);
106 if (!mapping) return;
107 data_ = MapViewOfFile(mapping, FILE_MAP_READ, 0, 0, 0);
108 CloseHandle(mapping);
109 if (data_) size_ = static_cast<std::size_t>(length.QuadPart);
110 }
111
112 ~PipelineCacheSeed() {
113 if (data_) UnmapViewOfFile(data_);
114 if (file_ != INVALID_HANDLE_VALUE) CloseHandle(file_);
115 }
116
117 PipelineCacheSeed(const PipelineCacheSeed&) = delete;
118 PipelineCacheSeed& operator=(const PipelineCacheSeed&) = delete;
119
120 const void* data() const { return data_; }
121 std::size_t size() const { return size_; }
122
123 bool compatible(const leonida::cached_pso::Identity& identity) const {
124 static_assert(sizeof(VkPipelineCacheHeaderVersionOne) == 32);
125 VkPipelineCacheHeaderVersionOne header{};
126 // The header is little-endian, like the host. The driver interprets the opaque payload.
127 std::memcpy(&header, data_, sizeof(header));
128 return header.headerSize == sizeof(header) && header.headerVersion == VK_PIPELINE_CACHE_HEADER_VERSION_ONE &&
129 header.vendorID == identity.vendor && header.deviceID == identity.device &&
130 std::memcmp(header.pipelineCacheUUID, identity.cache_uuid, VK_UUID_SIZE) == 0;
131 }
132
133private:
134 HANDLE file_ = INVALID_HANDLE_VALUE;
135 const void* data_ = nullptr;
136 std::size_t size_ = 0;
137};
138
139VkPipelineCache create_seeded_pipeline_cache(PFN_vkCreatePipelineCache create_cache, VkDevice device,
140 const leonida::cached_pso::Identity& identity) {
141 const PipelineCacheSeed seed(pipeline_cache_path());
142 if (!seed.data()) return VK_NULL_HANDLE;
143 if (!seed.compatible(identity)) {
144 std::fprintf(stderr, "[rt] d3d12: pipeline_cache.bin does not match this Vulkan device\n");
145 return VK_NULL_HANDLE;
146 }
147 const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO,
148 nullptr, 0, seed.size(), seed.data()};
149 VkPipelineCache cache = VK_NULL_HANDLE;
150 if (create_cache(device, &create, nullptr, &cache) != VK_SUCCESS) {
151 std::fprintf(stderr, "[rt] d3d12: Vulkan declined the pipeline cache seed\n");
152 return VK_NULL_HANDLE;
153 }
154 std::fprintf(stderr, "[rt] d3d12: loaded %zu bytes from pipeline_cache.bin\n", seed.size());
155 return cache;
156}
157
82// A shader whose subgroup size cannot be had runs at the device's: inexact if it crosses the halves of a wave64 (or, 158// A shader whose subgroup size cannot be had runs at the device's: inexact if it crosses the halves of a wave64 (or,
83// for a wave32 shader on a 64-wide default, reads lanes that are not its own). Logged once per stage with the first 159// for a wave32 shader on a 64-wide default, reads lanes that are not its own). Logged once per stage with the first
84// shader's name, then again at 10, 100, 1000... of that stage so a whole corpus stays readable. 160// shader's name, then again at 10, 100, 1000... of that stage so a whole corpus stays readable.
@@ -407,6 +483,8 @@ struct DeviceState {
407 // D3D-96: upload-heap buffers prefer DEVICE_LOCAL | HOST_VISIBLE memory, so the GPU reads them from VRAM. Only 483 // D3D-96: upload-heap buffers prefer DEVICE_LOCAL | HOST_VISIBLE memory, so the GPU reads them from VRAM. Only
408 // with Resizable BAR (leonida::resizable_bar); LEONIDA_UPLOAD_SYSMEM=1 keeps them in system memory to compare. 484 // with Resizable BAR (leonida::resizable_bar); LEONIDA_UPLOAD_SYSMEM=1 keeps them in system memory to compare.
409 bool upload_in_vram = false; 485 bool upload_in_vram = false;
486 // D3D-299: the first texture or default-heap buffer that lands outside device-local memory is logged, once.
487 mutable std::once_flag spill_logged;
410 488
411 // What D3D12_OPTIONS1 answers with: the physical device's own subgroup facts, read on first use. 489 // What D3D12_OPTIONS1 answers with: the physical device's own subgroup facts, read on first use.
412 struct SubgroupFacts { 490 struct SubgroupFacts {
@@ -422,6 +500,23 @@ struct DeviceState {
422 PFN_vkGetDeviceImageMemoryRequirements image_requirements = nullptr; // Vulkan 1.3 or VK_KHR_maintenance4 500 PFN_vkGetDeviceImageMemoryRequirements image_requirements = nullptr; // Vulkan 1.3 or VK_KHR_maintenance4
423 LUID luid{}; // VkPhysicalDeviceIDProperties::deviceLUID; zero when the driver reports none 501 LUID luid{}; // VkPhysicalDeviceIDProperties::deviceLUID; zero when the driver reports none
424 leonida::cached_pso::Identity pso_identity; // what GetCachedBlob records and CachedPSO is checked against 502 leonida::cached_pso::Identity pso_identity; // what GetCachedBlob records and CachedPSO is checked against
503 std::once_flag pipeline_cache_once;
504 VkPipelineCache pipeline_cache_handle = VK_NULL_HANDLE;
505
506 VkPipelineCache pipeline_cache() {
507 std::call_once(pipeline_cache_once, [this] {
508 const auto& vk = context->vk;
509 if (!vk.vkCreatePipelineCache || !vk.vkDestroyPipelineCache) return;
510 pipeline_cache_handle = create_seeded_pipeline_cache(vk.vkCreatePipelineCache, info.device, pso_identity);
511 if (pipeline_cache_handle) return;
512 const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO};
513 if (vk.vkCreatePipelineCache(info.device, &create, nullptr, &pipeline_cache_handle) != VK_SUCCESS)
514 pipeline_cache_handle = VK_NULL_HANDLE;
515 });
516 // Without EXTERNALLY_SYNCHRONIZED_BIT the driver synchronizes concurrent pipeline creation using this cache.
517 return pipeline_cache_handle;
518 }
519
425 QueueClock clock; // what every queue's GetClockCalibration uses 520 QueueClock clock; // what every queue's GetClockCalibration uses
426 PFN_vkGetPhysicalDeviceFormatProperties2 format_properties2 = nullptr; 521 PFN_vkGetPhysicalDeviceFormatProperties2 format_properties2 = nullptr;
427 // True when VK_FORMAT_E5B9G9R9_UFLOAT_PACK32 lacks native STORAGE_IMAGE but mutable R32_UINT+{R32_UINT,E5B9G9R9} 522 // True when VK_FORMAT_E5B9G9R9_UFLOAT_PACK32 lacks native STORAGE_IMAGE but mutable R32_UINT+{R32_UINT,E5B9G9R9}
@@ -483,6 +578,10 @@ struct DeviceState {
483 VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | 578 VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT |
484 VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; 579 VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT;
485 if (info.conditional_rendering) result.usage |= VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT; 580 if (info.conditional_rendering) result.usage |= VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT;
581 // D3D12 reserved buffers are visible to DIRECT, COPY and COMPUTE queues without exposing Vulkan
582 // queue-family ownership. Their tile bindings and accesses may use distinct families, so match the
583 // CONCURRENT sharing policy used for ordinary buffers and the GPU address arena.
584 share(result);
486 return result; 585 return result;
487 } 586 }
488 587
@@ -1111,12 +1210,15 @@ struct DeviceState {
1111 if (context->vk.vkAllocateMemory(info.device, &allocate, nullptr, &out) == VK_SUCCESS) { 1210 if (context->vk.vkAllocateMemory(info.device, &allocate, nullptr, &out) == VK_SUCCESS) {
1112 if (chosen) *chosen = memory.memoryTypes[i].propertyFlags; 1211 if (chosen) *chosen = memory.memoryTypes[i].propertyFlags;
1113 if (chosen_type) *chosen_type = i; 1212 if (chosen_type) *chosen_type = i;
1114 if ((preferred & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) && 1213 if (leonida::spilled_to_host(required, preferred, memory.memoryTypes[i].propertyFlags))
1115 !(memory.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)) { 1214 std::call_once(spill_logged, [&] {
1116 const std::string msg = "resource allocation spilled from DEVICE_LOCAL to host memory (heap " + 1215 const std::uint32_t heap = memory.memoryTypes[i].heapIndex;
1117 std::to_string(memory.memoryTypes[i].heapIndex) + "); size in KiB:"; 1216 std::fprintf(stderr,
1118 log_once(msg.c_str(), static_cast<int>(requirements.size / 1024)); 1217 "[rt] d3d12: a %llu-byte allocation did not fit in device-local memory and went "
1119 } 1218 "to memory type %u (heap %u, %llu MiB); later ones are not logged\n",
1219 static_cast<unsigned long long>(requirements.size), i, heap,
1220 static_cast<unsigned long long>(memory.memoryHeaps[heap].size >> 20));
1221 });
1120 return out; 1222 return out;
1121 } 1223 }
1122 } 1224 }
@@ -1377,6 +1479,30 @@ const char* committed_resource_refusal(const D3D12_HEAP_PROPERTIES& heap, D3D12_
1377 return nullptr; 1479 return nullptr;
1378} 1480}
1379 1481
1482// Why the host refuses this enhanced-barrier initial layout for `desc`, or null when valid (measured on Windows D3D12).
1483const char* barrier_layout_refusal(const D3D12_RESOURCE_DESC& desc, D3D12_BARRIER_LAYOUT layout) {
1484 if (desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER)
1485 return layout == D3D12_BARRIER_LAYOUT_UNDEFINED ? nullptr : "buffer barrier layout";
1486 const UINT flags = UINT(desc.Flags);
1487 switch (layout) {
1488 case D3D12_BARRIER_LAYOUT_RENDER_TARGET:
1489 return (flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) ? nullptr : "RENDER_TARGET barrier layout";
1490 case D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS:
1491 case D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_UNORDERED_ACCESS:
1492 case D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_UNORDERED_ACCESS:
1493 return (flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) ? nullptr : "UNORDERED_ACCESS barrier layout";
1494 case D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE:
1495 case D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_READ:
1496 return (flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) ? nullptr : "DEPTH_STENCIL barrier layout";
1497 case D3D12_BARRIER_LAYOUT_SHADER_RESOURCE:
1498 case D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_SHADER_RESOURCE:
1499 case D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_SHADER_RESOURCE:
1500 return (flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) ? "SHADER_RESOURCE barrier layout" : nullptr;
1501 default:
1502 return nullptr;
1503 }
1504}
1505
1380class DescriptorHeap final 1506class DescriptorHeap final
1381 : public Child<DescriptorHeap, ID3D12DescriptorHeapStubs, ID3D12Object, ID3D12DeviceChild, ID3D12Pageable, 1507 : public Child<DescriptorHeap, ID3D12DescriptorHeapStubs, ID3D12Object, ID3D12DeviceChild, ID3D12Pageable,
1382 ID3D12DescriptorHeap> { 1508 ID3D12DescriptorHeap> {
@@ -1451,7 +1577,7 @@ public:
1451 // here and nothing goes back to the arena when this object dies. 1577 // here and nothing goes back to the arena when this object dies.
1452 Resource(DeviceState& device, const D3D12_RESOURCE_DESC& desc, const D3D12_HEAP_PROPERTIES& heap, 1578 Resource(DeviceState& device, const D3D12_RESOURCE_DESC& desc, const D3D12_HEAP_PROPERTIES& heap,
1453 D3D12_HEAP_FLAGS heap_flags, VkDeviceSize placed_va) 1579 D3D12_HEAP_FLAGS heap_flags, VkDeviceSize placed_va)
1454 : device_(device), desc_(desc), heap_(heap), heap_flags_(heap_flags), va_(placed_va) {} 1580 : device_(device), desc_(desc), heap_(heap), heap_flags_(heap_flags), placed_(true), va_(placed_va) {}
1455 1581
1456 ~Resource() override { 1582 ~Resource() override {
1457 if (accel_) { 1583 if (accel_) {
@@ -1576,8 +1702,6 @@ public:
1576 if (vk.vkMapMemory(device_.info.device, memory_, 0, VK_WHOLE_SIZE, 0, &mapped_) != VK_SUCCESS) 1702 if (vk.vkMapMemory(device_.info.device, memory_, 0, VK_WHOLE_SIZE, 0, &mapped_) != VK_SUCCESS)
1577 return E_OUTOFMEMORY; 1703 return E_OUTOFMEMORY;
1578 std::memset(mapped_, 0, std::size_t(desc_.Width)); // committed resources start zeroed 1704 std::memset(mapped_, 0, std::size_t(desc_.Width)); // committed resources start zeroed
1579 } else {
1580 log_once("default-heap buffers are not zero-filled yet; dimension", int(desc_.Dimension));
1581 } 1705 }
1582 if (need_bda && vk.vkGetBufferDeviceAddress) { 1706 if (need_bda && vk.vkGetBufferDeviceAddress) {
1583 VkBufferDeviceAddressInfo bda{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; 1707 VkBufferDeviceAddressInfo bda{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO};
@@ -1610,6 +1734,10 @@ public:
1610 heap_.CPUPageProperty == D3D12_CPU_PAGE_PROPERTY_WRITE_BACK)); 1734 heap_.CPUPageProperty == D3D12_CPU_PAGE_PROPERTY_WRITE_BACK));
1611 binding.va = va_; 1735 binding.va = va_;
1612 device_.context->add_resource(id(), binding); 1736 device_.context->add_resource(id(), binding);
1737 // Committed resources start zeroed unless the heap says otherwise; the host cannot reach device-local memory,
1738 // so the next submission fills it (D3D-71).
1739 if (!host && !(heap_flags_ & D3D12_HEAP_FLAG_CREATE_NOT_ZEROED))
1740 device_.context->zero_on_next_submit(id(), buffer_);
1613 return S_OK; 1741 return S_OK;
1614 } 1742 }
1615 1743
@@ -1775,6 +1903,8 @@ public:
1775 desc_.Layout = layout; 1903 desc_.Layout = layout;
1776 } 1904 }
1777 bool reserved() const { return reserved_; } 1905 bool reserved() const { return reserved_; }
1906 // A committed resource: neither placed in a heap nor reserved. It owns its memory, like a heap does.
1907 bool committed() const { return !placed_ && !reserved_; }
1778 1908
1779 // D3D12 answers only for committed and placed resources (E_INVALIDARG for reserved ones, measured on the PC 1909 // D3D12 answers only for committed and placed resources (E_INVALIDARG for reserved ones, measured on the PC
1780 // runtime). 1910 // runtime).
@@ -1808,6 +1938,9 @@ public:
1808 else if (desc_.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) 1938 else if (desc_.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL))
1809 deny = deny_buffers | deny_non_rt_ds; 1939 deny = deny_buffers | deny_non_rt_ds;
1810 const UINT creation_only = D3D12_HEAP_FLAG_CREATE_NOT_RESIDENT | D3D12_HEAP_FLAG_CREATE_NOT_ZEROED; 1940 const UINT creation_only = D3D12_HEAP_FLAG_CREATE_NOT_RESIDENT | D3D12_HEAP_FLAG_CREATE_NOT_ZEROED;
1941 // A placed resource reports its heap's flags as they are (an ALLOW_ALL heap reads back 0): the DENY bits
1942 // are the runtime's choice only for the implicit heap of a committed resource (d3d12_heap_properties_test).
1943 if (placed_) return D3D12_HEAP_FLAGS(UINT(heap_flags_) & ~creation_only);
1811 return D3D12_HEAP_FLAGS((UINT(heap_flags_) & ~creation_only) | deny); 1944 return D3D12_HEAP_FLAGS((UINT(heap_flags_) & ~creation_only) | deny);
1812 } 1945 }
1813 1946
@@ -2075,6 +2208,7 @@ private:
2075 std::uint64_t buffer_va_ = 0; 2208 std::uint64_t buffer_va_ = 0;
2076 std::uint64_t gpu_va_ = 0; 2209 std::uint64_t gpu_va_ = 0;
2077 bool reserved_ = false; 2210 bool reserved_ = false;
2211 bool placed_ = false;
2078 leonida::ResourceBinding binding_{}; // a texture's, as registered with the context 2212 leonida::ResourceBinding binding_{}; // a texture's, as registered with the context
2079 bool host_transfer_ = false; // created with VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT 2213 bool host_transfer_ = false; // created with VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT
2080 D3D12_GPU_VIRTUAL_ADDRESS va_ = 0; 2214 D3D12_GPU_VIRTUAL_ADDRESS va_ = 0;
@@ -2306,6 +2440,17 @@ private:
2306// Among index entries for one program (containers with the same FSSM program; 789 groups in the 26,503-shader 2440// Among index entries for one program (containers with the same FSSM program; 789 groups in the 26,503-shader
2307// corpus), the one to build: the first that `fits` and declares no set-0 bindings (the cheaper pipeline); else the 2441// corpus), the one to build: the first that `fits` and declares no set-0 bindings (the cheaper pipeline); else the
2308// first that fits; else the first without bindings; else the first. Null when there is none. 2442// first that fits; else the first without bindings; else the first. Null when there is none.
2443// The S#s a shader builds from immediates (literal_samplers in its index entry) are named by no heap slot, so
2444// nothing else gives them a sampler and a hash-table key: without this their lookup finds the fallback sampler
2445// (index 0) and the shader samples with the wrong filter and address modes (docs/design.md, Literal samplers).
2446// Registering is idempotent and also runs when the pipeline is created again.
2447void register_literal_samplers(DeviceState& device, const leonida::ShaderEntry& entry) {
2448 for (const leonida::gfx10::SamplerWords& words : entry.literal_samplers)
2449 if (!device.bind_sampler(words))
2450 log_once("a shader's literal S# has no sampler (no bindless set, or its sampler array is full); words",
2451 int(entry.literal_samplers.size()));
2452}
2453
2309template<typename Fits> 2454template<typename Fits>
2310const leonida::ShaderEntry* pick_entry(const std::vector<const leonida::ShaderEntry*>& candidates, Fits&& fits) { 2455const leonida::ShaderEntry* pick_entry(const std::vector<const leonida::ShaderEntry*>& candidates, Fits&& fits) {
2311 const leonida::ShaderEntry* fitting = nullptr; 2456 const leonida::ShaderEntry* fitting = nullptr;
@@ -2535,11 +2680,13 @@ public:
2535 bool graphics() const { return registered_ && is_graphics_; } 2680 bool graphics() const { return registered_ && is_graphics_; }
2536 const std::vector<leonida::SubgroupRequest>& subgroup_requests() const { return subgroup_requests_; } 2681 const std::vector<leonida::SubgroupRequest>& subgroup_requests() const { return subgroup_requests_; }
2537 2682
2538 // A VS (+ PS) pipeline for dynamic rendering. Vertex input comes from the input layout matched to the VS's 2683 // A VS (+ GS) (+ PS) pipeline for dynamic rendering. Vertex input comes from the input layout matched to the
2539 // input signature by semantic name and index: location = the element's register, the translator's rule 2684 // VS's input signature by semantic name and index: location = the element's register, the translator's rule
2540 // (docs/design.md, "Vertex fetch"). Hull, domain and geometry stages, more than one sample, and two stages 2685 // (docs/design.md, "Vertex fetch"). Refused with a log: hull and domain stages, stream output, the centre
2541 // that both read their code base are refused with a log. Viewport, scissor, topology, vertex strides, stencil 2686 // multisample pattern, two stages that both read their code base, and state that needs a Vulkan feature the
2542 // reference and blend factor are dynamic, set from the list's state at each draw. 2687 // device lacks (including the geometryShader feature a GS needs). A GS takes triangles; the sample count may
2688 // be above one. Viewport, scissor, topology, vertex strides, stencil reference and blend factor are dynamic,
2689 // set from the list's state at each draw.
2543 HRESULT create_graphics(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc) { 2690 HRESULT create_graphics(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc) {
2544 auto& vk = device_.context->vk; 2691 auto& vk = device_.context->vk;
2545 const VkDevice dev = device_.info.device; 2692 const VkDevice dev = device_.info.device;
@@ -2611,6 +2758,21 @@ public:
2611 // Chained from stage_infos, which the recipe keeps for variants built at draw time: so they live in the recipe. 2758 // Chained from stage_infos, which the recipe keeps for variants built at draw time: so they live in the recipe.
2612 auto& required_sizes = recipe_.required_sizes; 2759 auto& required_sizes = recipe_.required_sizes;
2613 const Stage* code_stage = nullptr; 2760 const Stage* code_stage = nullptr;
2761 // D24_UNORM_S8_UINT stored as D32_SFLOAT_S8_UINT (no D24 on the GPU): the pixel stage writes the depth D24
2762 // would hold, biased in D24 units and quantised (src/depth24_fragment.h, D3D-309), and the rasterizer's own
2763 // bias is turned off. Multisampled targets keep the old path: a FragDepth write is per pixel.
2764 const bool d24_as_float = desc.DSVFormat != DXGI_FORMAT_UNKNOWN &&
2765 vulkan_format(desc.DSVFormat, true).format == VK_FORMAT_D24_UNORM_S8_UINT &&
2766 !device_.depth_usable(VK_FORMAT_D24_UNORM_S8_UINT);
2767 bool depth24_fragment = d24_as_float && desc.DepthStencilState.DepthEnable;
2768 if (depth24_fragment && samples > 1) {
2769 log_once("D24 depth stored as D32 keeps float depth bias and precision on multisampled targets; samples",
2770 int(samples));
2771 depth24_fragment = false;
2772 }
2773 const leonida::Depth24Bias depth24_bias{desc.RasterizerState.DepthBias,
2774 desc.RasterizerState.SlopeScaledDepthBias,
2775 desc.RasterizerState.DepthBiasClamp};
2614 for (Stage& stage : stages) { 2776 for (Stage& stage : stages) {
2615 if (!stage.code.pShaderBytecode || !stage.code.BytecodeLength) continue; // no PS: depth only 2777 if (!stage.code.pShaderBytecode || !stage.code.BytecodeLength) continue; // no PS: depth only
2616 stage.fssm = leonida::fssm_program( 2778 stage.fssm = leonida::fssm_program(
@@ -2637,6 +2799,7 @@ public:
2637 return E_NOTIMPL; 2799 return E_NOTIMPL;
2638 } 2800 }
2639 uses_bindless = true; 2801 uses_bindless = true;
2802 register_literal_samplers(device_, *stage.entry);
2640 } 2803 }
2641 if (stage.entry->uses_code_base) { 2804 if (stage.entry->uses_code_base) {
2642 if (code_stage) { 2805 if (code_stage) {
@@ -2668,6 +2831,18 @@ public:
2668 } 2831 }
2669 for (Stage& stage : stages) { 2832 for (Stage& stage : stages) {
2670 if (!stage.entry) continue; 2833 if (!stage.entry) continue;
2834 // After the f16 link above, which can also edit the pixel shader's words.
2835 if (depth24_fragment && stage.bit == VK_SHADER_STAGE_FRAGMENT_BIT) {
2836 std::string why;
2837 std::vector<std::uint32_t> patched = leonida::depth24_patch_fragment(stage.words, depth24_bias, why);
2838 if (patched.empty()) {
2839 std::fprintf(stderr, "[rt] d3d12: %s keeps float depth on a D24 target stored as D32: %s\n",
2840 stage.entry->name.c_str(), why.c_str());
2841 depth24_fragment = false;
2842 } else {
2843 stage.words = std::move(patched);
2844 }
2845 }
2671 VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; 2846 VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO};
2672 module_info.codeSize = stage.words.size() * 4; 2847 module_info.codeSize = stage.words.size() * 4;
2673 module_info.pCode = stage.words.data(); 2848 module_info.pCode = stage.words.data();
@@ -2681,6 +2856,21 @@ public:
2681 subgroup_size_for(*stage.entry, required_sizes[stage_infos.size()], info); 2856 subgroup_size_for(*stage.entry, required_sizes[stage_infos.size()], info);
2682 stage_infos.push_back(info); 2857 stage_infos.push_back(info);
2683 } 2858 }
2859 if (depth24_fragment && !ps_stage.entry) { // no pixel shader: a built-in one writes the depth
2860 const std::vector<std::uint32_t> words = leonida::depth24_depth_only_fragment(depth24_bias);
2861 VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO};
2862 module_info.codeSize = words.size() * 4;
2863 module_info.pCode = words.data();
2864 VkShaderModule module = VK_NULL_HANDLE;
2865 if (words.empty() || vk.vkCreateShaderModule(dev, &module_info, nullptr, &module) != VK_SUCCESS)
2866 return E_FAIL;
2867 modules_.push_back(module);
2868 VkPipelineShaderStageCreateInfo info{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO};
2869 info.stage = VK_SHADER_STAGE_FRAGMENT_BIT;
2870 info.module = module;
2871 info.pName = "main";
2872 stage_infos.push_back(info);
2873 }
2684 2874
2685 // Input layout -> vertex input, by semantic. 2875 // Input layout -> vertex input, by semantic.
2686 std::vector<VkVertexInputAttributeDescription> attributes; 2876 std::vector<VkVertexInputAttributeDescription> attributes;
@@ -2776,10 +2966,14 @@ public:
2776 : VK_CULL_MODE_NONE; 2966 : VK_CULL_MODE_NONE;
2777 // With the negative-height viewport, framebuffer winding matches D3D12's screen-space winding. 2967 // With the negative-height viewport, framebuffer winding matches D3D12's screen-space winding.
2778 raster.frontFace = r.FrontCounterClockwise ? VK_FRONT_FACE_COUNTER_CLOCKWISE : VK_FRONT_FACE_CLOCKWISE; 2968 raster.frontFace = r.FrontCounterClockwise ? VK_FRONT_FACE_COUNTER_CLOCKWISE : VK_FRONT_FACE_CLOCKWISE;
2779 raster.depthBiasEnable = r.DepthBias || r.SlopeScaledDepthBias != 0.0f; 2969 // The D24-as-D32 pixel stage applies the bias itself, in D24 units (depth24_fragment above): the
2780 raster.depthBiasConstantFactor = float(r.DepthBias); 2970 // rasterizer's bias stays off and zero, so its clamp needs no depthBiasClamp feature either.
2781 raster.depthBiasClamp = r.DepthBiasClamp; 2971 raster.depthBiasEnable = !depth24_fragment && (r.DepthBias || r.SlopeScaledDepthBias != 0.0f);
2782 raster.depthBiasSlopeFactor = r.SlopeScaledDepthBias; 2972 if (raster.depthBiasEnable) {
2973 raster.depthBiasConstantFactor = float(r.DepthBias);
2974 raster.depthBiasClamp = r.DepthBiasClamp;
2975 raster.depthBiasSlopeFactor = r.SlopeScaledDepthBias;
2976 }
2783 raster.lineWidth = 1.0f; 2977 raster.lineWidth = 1.0f;
2784 // No depth clipping: fragments outside the viewport's depth range are kept and their depth clamped to it, as 2978 // No depth clipping: fragments outside the viewport's depth range are kept and their depth clamped to it, as
2785 // D3D12 clamps output depth to MinDepth..MaxDepth anyway (needs depthClamp, checked below). 2979 // D3D12 clamps output depth to MinDepth..MaxDepth anyway (needs depthClamp, checked below).
@@ -3029,6 +3223,7 @@ public:
3029 entry->name.c_str()); 3223 entry->name.c_str());
3030 return E_NOTIMPL; 3224 return E_NOTIMPL;
3031 } 3225 }
3226 if (entry->binding_count) register_literal_samplers(device_, *entry);
3032 // SHADER-309: a module over the device's maxComputeSharedMemorySize is invalid usage that spirv-val accepts 3227 // SHADER-309: a module over the device's maxComputeSharedMemorySize is invalid usage that spirv-val accepts
3033 // and RADV dies on (#1721); some drivers report 32768. Refuse it here instead of creating the pipeline. 3228 // and RADV dies on (#1721); some drivers report 32768. Refuse it here instead of creating the pipeline.
3034 if (entry->lds_bytes) { 3229 if (entry->lds_bytes) {
@@ -3078,7 +3273,7 @@ public:
3078 VkPipelineShaderStageRequiredSubgroupSizeCreateInfo required_size{}; 3273 VkPipelineShaderStageRequiredSubgroupSizeCreateInfo required_size{};
3079 subgroup_size_for(*entry, required_size, pipeline_info.stage); 3274 subgroup_size_for(*entry, required_size, pipeline_info.stage);
3080 pipeline_info.layout = pipeline_.layout; 3275 pipeline_info.layout = pipeline_.layout;
3081 if (vk.vkCreateComputePipelines(dev, VK_NULL_HANDLE, 1, &pipeline_info, nullptr, &pipeline_.pipeline) != 3276 if (vk.vkCreateComputePipelines(dev, device_.pipeline_cache(), 1, &pipeline_info, nullptr, &pipeline_.pipeline) !=
3082 VK_SUCCESS) 3277 VK_SUCCESS)
3083 return E_FAIL; 3278 return E_FAIL;
3084 3279
@@ -3184,8 +3379,8 @@ private:
3184 info.pDynamicState = &dynamic; 3379 info.pDynamicState = &dynamic;
3185 info.layout = graphics_.layout; 3380 info.layout = graphics_.layout;
3186 VkPipeline pipeline = VK_NULL_HANDLE; 3381 VkPipeline pipeline = VK_NULL_HANDLE;
3187 if (device_.context->vk.vkCreateGraphicsPipelines(device_.info.device, VK_NULL_HANDLE, 1, &info, nullptr, 3382 if (device_.context->vk.vkCreateGraphicsPipelines(device_.info.device, device_.pipeline_cache(), 1,
3188 &pipeline) != VK_SUCCESS) 3383 &info, nullptr, &pipeline) != VK_SUCCESS)
3189 return VK_NULL_HANDLE; 3384 return VK_NULL_HANDLE;
3190 return pipeline; 3385 return pipeline;
3191 } 3386 }
@@ -3907,7 +4102,8 @@ leonida::gfx10::Sampler sampler_descriptor(const D3D12_SAMPLER_DESC& desc, Devic
3907// A query heap: one VkQueryPool, registered with the context so that lists can resolve it by ID 4102// A query heap: one VkQueryPool, registered with the context so that lists can resolve it by ID
3908// (docs/d3d12_vulkan.md section 4.6). Occlusion heaps hold both OCCLUSION and BINARY_OCCLUSION queries; timestamp 4103// (docs/d3d12_vulkan.md section 4.6). Occlusion heaps hold both OCCLUSION and BINARY_OCCLUSION queries; timestamp
3909// and copy-queue timestamp heaps are timestamp pools; pipeline-statistics heaps count all eleven Vulkan 4104// and copy-queue timestamp heaps are timestamp pools; pipeline-statistics heaps count all eleven Vulkan
3910// statistics, whose result order is the field order of D3D12_QUERY_DATA_PIPELINE_STATISTICS. 4105// statistics, whose result order is the field order of D3D12_QUERY_DATA_PIPELINE_STATISTICS. Stream-output
4106// statistics heaps have no pool: without stream output every such query is zero.
3911class QueryHeap final 4107class QueryHeap final
3912 : public Child<QueryHeap, ID3D12QueryHeapStubs, ID3D12Object, ID3D12DeviceChild, ID3D12Pageable, 4108 : public Child<QueryHeap, ID3D12QueryHeapStubs, ID3D12Object, ID3D12DeviceChild, ID3D12Pageable,
3913 ID3D12QueryHeap> { 4109 ID3D12QueryHeap> {
@@ -3918,9 +4114,9 @@ public:
3918 explicit QueryHeap(DeviceState& device) : device_(device) {} 4114 explicit QueryHeap(DeviceState& device) : device_(device) {}
3919 4115
3920 ~QueryHeap() override { 4116 ~QueryHeap() override {
3921 if (!pool_) return; 4117 if (!registered_) return;
3922 device_.context->remove_query_pool(id()); 4118 device_.context->remove_query_pool(id());
3923 device_.context->vk.vkDestroyQueryPool(device_.info.device, pool_, nullptr); 4119 if (pool_) device_.context->vk.vkDestroyQueryPool(device_.info.device, pool_, nullptr);
3924 } 4120 }
3925 4121
3926 leonida::QueryHeapId id() const { return query_heap_id(this); } 4122 leonida::QueryHeapId id() const { return query_heap_id(this); }
@@ -3941,6 +4137,12 @@ public:
3941 } 4137 }
3942 info.queryType = VK_QUERY_TYPE_TIMESTAMP; 4138 info.queryType = VK_QUERY_TYPE_TIMESTAMP;
3943 break; 4139 break;
4140 case h::so_statistics:
4141 // The layer has no stream output: a graphics PSO with StreamOutput entries is refused (E_NOTIMPL) and
4142 // SOSetTargets is not implemented, so no primitive ever reaches a stream and every query of this heap
4143 // counts 0 written and 0 needed. That needs no Vulkan pool: Begin/EndQuery run nothing and a resolve fills zeros. When stream
4144 // output lands, this becomes a VK_QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM_EXT pool (D3D-302).
4145 return register_pool(desc);
3944 case h::pipeline_statistics: 4146 case h::pipeline_statistics:
3945 if (!device_.info.pipeline_statistics_query) { 4147 if (!device_.info.pipeline_statistics_query) {
3946 log_once("pipeline-statistics query heap: pipelineStatisticsQuery not enabled; type", desc.Type); 4148 log_once("pipeline-statistics query heap: pipelineStatisticsQuery not enabled; type", desc.Type);
@@ -3950,7 +4152,7 @@ public:
3950 info.pipelineStatistics = kPipelineStatistics; 4152 info.pipelineStatistics = kPipelineStatistics;
3951 break; 4153 break;
3952 default: 4154 default:
3953 // Stream output, video decode and mesh-shader statistics (PIPELINE_STATISTICS1) have no path yet. 4155 // Video decode and mesh-shader statistics (PIPELINE_STATISTICS1) have no path yet.
3954 log_once("query heap type not supported:", desc.Type); 4156 log_once("query heap type not supported:", desc.Type);
3955 return E_NOTIMPL; 4157 return E_NOTIMPL;
3956 } 4158 }
@@ -3958,6 +4160,11 @@ public:
3958 pool_ = VK_NULL_HANDLE; 4160 pool_ = VK_NULL_HANDLE;
3959 return E_OUTOFMEMORY; 4161 return E_OUTOFMEMORY;
3960 } 4162 }
4163 return register_pool(desc);
4164 }
4165
4166private:
4167 HRESULT register_pool(const D3D12_QUERY_HEAP_DESC& desc) {
3961 leonida::QueryPool pool{}; 4168 leonida::QueryPool pool{};
3962 pool.pool = pool_; 4169 pool.pool = pool_;
3963 pool.heap_type = desc.Type; 4170 pool.heap_type = desc.Type;
@@ -3965,10 +4172,10 @@ public:
3965 pool.precise = device_.info.occlusion_query_precise; 4172 pool.precise = device_.info.occlusion_query_precise;
3966 pool.ended.assign(desc.Count, false); 4173 pool.ended.assign(desc.Count, false);
3967 device_.context->add_query_pool(id(), pool); 4174 device_.context->add_query_pool(id(), pool);
4175 registered_ = true;
3968 return S_OK; 4176 return S_OK;
3969 } 4177 }
3970 4178
3971private:
3972 // VK_QUERY_PIPELINE_STATISTIC_INPUT_ASSEMBLY_VERTICES_BIT through COMPUTE_SHADER_INVOCATIONS_BIT (0x1-0x400): 4179 // VK_QUERY_PIPELINE_STATISTIC_INPUT_ASSEMBLY_VERTICES_BIT through COMPUTE_SHADER_INVOCATIONS_BIT (0x1-0x400):
3973 // IAVertices, IAPrimitives, VSInvocations, GSInvocations, GSPrimitives, CInvocations, CPrimitives, 4180 // IAVertices, IAPrimitives, VSInvocations, GSInvocations, GSPrimitives, CInvocations, CPrimitives,
3974 // PSInvocations, HSInvocations (patches), DSInvocations, CSInvocations. 4181 // PSInvocations, HSInvocations (patches), DSInvocations, CSInvocations.
@@ -3976,7 +4183,8 @@ private:
3976 static_assert(sizeof(D3D12_QUERY_DATA_PIPELINE_STATISTICS) == 11 * sizeof(UINT64)); 4183 static_assert(sizeof(D3D12_QUERY_DATA_PIPELINE_STATISTICS) == 11 * sizeof(UINT64));
3977 4184
3978 DeviceState& device_; 4185 DeviceState& device_;
3979 VkQueryPool pool_ = VK_NULL_HANDLE; 4186 VkQueryPool pool_ = VK_NULL_HANDLE; // null for a stream-output heap (no Vulkan query behind it)
4187 bool registered_ = false; // added to the context, so removed from it on destruction
3980}; 4188};
3981 4189
3982// The Vulkan objects create_vulkan_device_standalone made, destroyed with the device. 4190// The Vulkan objects create_vulkan_device_standalone made, destroyed with the device.
@@ -4122,6 +4330,14 @@ public:
4122 state_.context->enable_copy_scratch(get_device, [this](const VkMemoryRequirements& requirements) { 4330 state_.context->enable_copy_scratch(get_device, [this](const VkMemoryRequirements& requirements) {
4123 return state_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); 4331 return state_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
4124 }); 4332 });
4333 if (info.buffer_device_address && info.physical && info.get_instance_proc) {
4334 if (const auto get_props = reinterpret_cast<PFN_vkGetPhysicalDeviceProperties>(
4335 info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties"))) {
4336 VkPhysicalDeviceProperties props{};
4337 get_props(info.physical, &props);
4338 state_.context->configure_counted_dispatch(get_device, state_.memory, props.limits);
4339 }
4340 }
4125 // The copies of a D24 texture stored as D32 convert on the GPU (vulkan_depth24.h), and so do the copies of 4341 // The copies of a D24 texture stored as D32 convert on the GPU (vulkan_depth24.h), and so do the copies of
4126 // a 96-bit texture, which every GPU stores as RGBA32 (D3D-62): the converter is there whether or not the 4342 // a 96-bit texture, which every GPU stores as RGBA32 (D3D-62): the converter is there whether or not the
4127 // GPU has a native D24_UNORM_S8_UINT. It costs nothing until a copy needs it (its pipeline is made on the 4343 // GPU has a native D24_UNORM_S8_UINT. It costs nothing until a copy needs it (its pipeline is made on the
@@ -4380,6 +4596,8 @@ public:
4380 vk.vkDestroyBuffer(state_.info.device, state_.arena.buffer, nullptr); 4596 vk.vkDestroyBuffer(state_.info.device, state_.arena.buffer, nullptr);
4381 if (state_.arena.memory) vk.vkFreeMemory(state_.info.device, state_.arena.memory, nullptr); 4597 if (state_.arena.memory) vk.vkFreeMemory(state_.info.device, state_.arena.memory, nullptr);
4382 } 4598 }
4599 if (state_.pipeline_cache_handle)
4600 state_.context->vk.vkDestroyPipelineCache(state_.info.device, state_.pipeline_cache_handle, nullptr);
4383 state_.context.reset(); 4601 state_.context.reset();
4384 if (owned_.device) owned_.destroy_device(owned_.device, nullptr); 4602 if (owned_.device) owned_.destroy_device(owned_.device, nullptr);
4385 if (owned_.instance) owned_.destroy_instance(owned_.instance, nullptr); 4603 if (owned_.instance) owned_.destroy_instance(owned_.instance, nullptr);
@@ -4468,20 +4686,31 @@ public:
4468 4686
4469 // Device1: priorities only order what the OS evicts first under memory pressure. VK_EXT_pageable_device_local_memory 4687 // Device1: priorities only order what the OS evicts first under memory pressure. VK_EXT_pageable_device_local_memory
4470 // could pass them on, but it is optional and changes no result, so they are accepted and dropped. Any UINT is a 4688 // could pass them on, but it is optional and changes no result, so they are accepted and dropped. Any UINT is a
4471 // valid priority (the D3D12_RESIDENCY_PRIORITY values are named points, the low 24 bits a refinement). 4689 // valid priority (the D3D12_RESIDENCY_PRIORITY values are named points, the low 24 bits a refinement). As on the
4690 // host runtime (d3d12_residency_test, RTX 3060 / 610.88), only objects that own their memory take one: committed
4691 // resources and heaps. A placed resource (a reserved one too, by the same rule; not measured), a descriptor heap, a query heap or a fence is E_INVALIDARG.
4692 // The host also removes its device then (DXGI_ERROR_INVALID_CALL); the layer doesn't, since a console title that
4693 // sets priorities on its placed resources would lose its device over a hint.
4472 HRESULT STDMETHODCALLTYPE SetResidencyPriority(UINT count, ID3D12Pageable* const* objects, 4694 HRESULT STDMETHODCALLTYPE SetResidencyPriority(UINT count, ID3D12Pageable* const* objects,
4473 const D3D12_RESIDENCY_PRIORITY* priorities) override { 4695 const D3D12_RESIDENCY_PRIORITY* priorities) override {
4474 return count && (!objects || !priorities) ? E_INVALIDARG : S_OK; 4696 if (count && (!objects || !priorities)) return E_INVALIDARG;
4697 for (UINT i = 0; i < count; ++i) {
4698 if (from<Heap>(objects[i])) continue;
4699 const Resource* resource = from<Resource>(objects[i]);
4700 if (!resource || !resource->committed()) return E_INVALIDARG;
4701 }
4702 return S_OK;
4475 } 4703 }
4476 4704
4477 // Device3: the asynchronous MakeResident. The objects are already resident, so the work is complete at once 4705 // Device3: the asynchronous MakeResident. The objects are already resident, so the work is complete at once
4478 // and the fence is signalled from the CPU now. The caller's queue Wait on it must not hang, which is why the 4706 // and the fence is signalled from the CPU now. The caller's queue Wait on it must not hang, which is why the
4479 // signal is kept although the residency part is a no-op. DENY_OVERBUDGET cannot fail: nothing is paged in. 4707 // signal is kept although the residency part is a no-op. DENY_OVERBUDGET cannot fail: nothing is paged in. A
4708 // null fence is accepted, as the host runtime does: there is nothing to signal.
4480 HRESULT STDMETHODCALLTYPE EnqueueMakeResident(D3D12_RESIDENCY_FLAGS flags, UINT count, 4709 HRESULT STDMETHODCALLTYPE EnqueueMakeResident(D3D12_RESIDENCY_FLAGS flags, UINT count,
4481 ID3D12Pageable* const* objects, ID3D12Fence* fence, 4710 ID3D12Pageable* const* objects, ID3D12Fence* fence,
4482 UINT64 value) override { 4711 UINT64 value) override {
4483 if (!fence || (count && !objects) || (flags & ~D3D12_RESIDENCY_FLAG_DENY_OVERBUDGET)) return E_INVALIDARG; 4712 if ((count && !objects) || (flags & ~D3D12_RESIDENCY_FLAG_DENY_OVERBUDGET)) return E_INVALIDARG;
4484 return fence->Signal(value); 4713 return fence ? fence->Signal(value) : S_OK;
4485 } 4714 }
4486 4715
4487 // Stable power state pins GPU clocks for profiling, a developer-mode feature on Windows. Vulkan has no clock 4716 // Stable power state pins GPU clocks for profiling, a developer-mode feature on Windows. Vulkan has no clock
@@ -4622,20 +4851,27 @@ public:
4622 return d3d12_trace::result(method, create_command_allocator(type, riid, out, identity())); 4851 return d3d12_trace::result(method, create_command_allocator(type, riid, out, identity()));
4623 } 4852 }
4624 4853
4625 HRESULT STDMETHODCALLTYPE CreateCommandList(UINT, D3D12_COMMAND_LIST_TYPE type, ID3D12CommandAllocator* allocator, 4854 HRESULT STDMETHODCALLTYPE CreateCommandList(UINT node_mask, D3D12_COMMAND_LIST_TYPE type,
4626 ID3D12PipelineState* state, REFIID riid, void** out) override { 4855 ID3D12CommandAllocator* allocator, ID3D12PipelineState* state,
4856 REFIID riid, void** out) override {
4627 constexpr auto method = "ID3D12Device::CreateCommandList"; 4857 constexpr auto method = "ID3D12Device::CreateCommandList";
4858 if (out) *out = nullptr;
4859 if (node_mask & ~1u) return d3d12_trace::result(method, E_INVALIDARG); // one node, as the host answers
4628 // The initial pipeline state is set as SetPipelineState would set it (a bundle's is its first deferred call). 4860 // The initial pipeline state is set as SetPipelineState would set it (a bundle's is its first deferred call).
4629 HRESULT hr = create_command_list(type, allocator, riid, out, identity(), state); 4861 HRESULT hr = create_command_list(type, allocator, riid, out, identity(), state);
4630 return d3d12_trace::result(method, hr); 4862 return d3d12_trace::result(method, hr);
4631 } 4863 }
4632 4864
4633 // Device4: a list created closed, without an allocator. 4865 // Device4: a list created closed, without an allocator.
4634 HRESULT STDMETHODCALLTYPE CreateCommandList1(UINT, D3D12_COMMAND_LIST_TYPE type, D3D12_COMMAND_LIST_FLAGS, 4866 HRESULT STDMETHODCALLTYPE CreateCommandList1(UINT node_mask, D3D12_COMMAND_LIST_TYPE type,
4635 REFIID riid, void** out) override { 4867 D3D12_COMMAND_LIST_FLAGS, REFIID riid, void** out) override {
4636 constexpr auto method = "ID3D12Device4::CreateCommandList1"; 4868 constexpr auto method = "ID3D12Device4::CreateCommandList1";
4637 if (!out) return d3d12_trace::result(method, E_POINTER); 4869 // The host runtime's order ("command list1:" cases): one node and a type up to VIDEO_ENCODE, then a null
4638 *out = nullptr; 4870 // output is E_UNEXPECTED.
4871 if (out) *out = nullptr;
4872 if ((node_mask & ~1u) || UINT(type) > UINT(D3D12_COMMAND_LIST_TYPE_VIDEO_ENCODE))
4873 return d3d12_trace::result(method, E_INVALIDARG);
4874 if (!out) return d3d12_trace::result(method, E_UNEXPECTED);
4639 ID3D12CommandAllocator* allocator = nullptr; 4875 ID3D12CommandAllocator* allocator = nullptr;
4640 HRESULT hr = create_command_allocator(type, IID_PPV_ARGS(&allocator), identity()); 4876 HRESULT hr = create_command_allocator(type, IID_PPV_ARGS(&allocator), identity());
4641 if (FAILED(hr)) return d3d12_trace::result(method, hr); 4877 if (FAILED(hr)) return d3d12_trace::result(method, hr);
@@ -4686,7 +4922,7 @@ public:
4686 case D3D12_INDIRECT_ARGUMENT_TYPE_VERTEX_BUFFER_VIEW: size += sizeof(D3D12_VERTEX_BUFFER_VIEW); break; 4922 case D3D12_INDIRECT_ARGUMENT_TYPE_VERTEX_BUFFER_VIEW: size += sizeof(D3D12_VERTEX_BUFFER_VIEW); break;
4687 case D3D12_INDIRECT_ARGUMENT_TYPE_INDEX_BUFFER_VIEW: size += sizeof(D3D12_INDEX_BUFFER_VIEW); break; 4923 case D3D12_INDIRECT_ARGUMENT_TYPE_INDEX_BUFFER_VIEW: size += sizeof(D3D12_INDEX_BUFFER_VIEW); break;
4688 case D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT: size += UINT64{4} * arg.Constant.Num32BitValuesToSet; break; 4924 case D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT: size += UINT64{4} * arg.Constant.Num32BitValuesToSet; break;
4689 case D3D12_INDIRECT_ARGUMENT_TYPE_INCREMENTING_CONSTANT: size += 4; break; 4925 case compat::kIndirectArgumentIncrementingConstant: size += 4; break;
4690 case D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT_BUFFER_VIEW: 4926 case D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT_BUFFER_VIEW:
4691 case D3D12_INDIRECT_ARGUMENT_TYPE_SHADER_RESOURCE_VIEW: 4927 case D3D12_INDIRECT_ARGUMENT_TYPE_SHADER_RESOURCE_VIEW:
4692 case D3D12_INDIRECT_ARGUMENT_TYPE_UNORDERED_ACCESS_VIEW: size += sizeof(D3D12_GPU_VIRTUAL_ADDRESS); break; 4928 case D3D12_INDIRECT_ARGUMENT_TYPE_UNORDERED_ACCESS_VIEW: size += sizeof(D3D12_GPU_VIRTUAL_ADDRESS); break;
@@ -4888,6 +5124,7 @@ public:
4888 } 5124 }
4889 layout.parameters.push_back({parsed.sig.params[i].type, first, parsed.sig.params[i].num_values}); 5125 layout.parameters.push_back({parsed.sig.params[i].type, first, parsed.sig.params[i].num_values});
4890 } 5126 }
5127 register_static_samplers(parsed.sig);
4891 auto* signature = new RootSignature( 5128 auto* signature = new RootSignature(
4892 std::move(layout), leonida::sha256_hex({static_cast<const std::uint8_t*>(blob), size})); 5129 std::move(layout), leonida::sha256_hex({static_cast<const std::uint8_t*>(blob), size}));
4893 signature->attach_device(identity()); 5130 signature->attach_device(identity());
@@ -5545,17 +5782,25 @@ public:
5545 log_once(refusal, desc->Flags); 5782 log_once(refusal, desc->Flags);
5546 return; 5783 return;
5547 } 5784 }
5548 const bool uint_border = desc->Flags & D3D12_SAMPLER_FLAG_UINT_BORDER_COLOR; 5785 const leonida::gfx10::SamplerWords words = sampler2_words(*desc);
5549 D3D12_SAMPLER_DESC base{desc->Filter, desc->AddressU, desc->AddressV, desc->AddressW, 5786 std::memset(reinterpret_cast<void*>(destination.ptr), 0, kDescriptorSize);
5550 desc->MipLODBias, desc->MaxAnisotropy, desc->ComparisonFunc, {}, 5787 std::memcpy(reinterpret_cast<void*>(destination.ptr), words.data(), sizeof(words));
5551 desc->MinLOD, desc->MaxLOD}; 5788 state_.bind_sampler(words);
5552 if (!uint_border) std::memcpy(base.BorderColor, desc->FloatBorderColor, sizeof(base.BorderColor)); 5789 }
5790
5791 // The S# of a D3D12_SAMPLER_DESC2 that sampler2_refusal accepts.
5792 leonida::gfx10::SamplerWords sampler2_words(const D3D12_SAMPLER_DESC2& desc) {
5793 const bool uint_border = desc.Flags & D3D12_SAMPLER_FLAG_UINT_BORDER_COLOR;
5794 D3D12_SAMPLER_DESC base{desc.Filter, desc.AddressU, desc.AddressV, desc.AddressW,
5795 desc.MipLODBias, desc.MaxAnisotropy, desc.ComparisonFunc, {},
5796 desc.MinLOD, desc.MaxLOD};
5797 if (!uint_border) std::memcpy(base.BorderColor, desc.FloatBorderColor, sizeof(base.BorderColor));
5553 leonida::gfx10::Sampler sampler = sampler_descriptor(base, uint_border ? nullptr : &state_); 5798 leonida::gfx10::Sampler sampler = sampler_descriptor(base, uint_border ? nullptr : &state_);
5554 if (uint_border) { 5799 if (uint_border) {
5555 // The S#'s border types are the float ones', plus the layer's integer mark (kIntegerBorderPtr), which 5800 // The S#'s border types are the float ones', plus the layer's integer mark (kIntegerBorderPtr), which
5556 // gives the integer border its own key and VK_BORDER_COLOR_INT_* in Vulkan. 5801 // gives the integer border its own key and VK_BORDER_COLOR_INT_* in Vulkan.
5557 namespace g = leonida::gfx10; 5802 namespace g = leonida::gfx10;
5558 const UINT* c = desc->UintBorderColor; 5803 const UINT* c = desc.UintBorderColor;
5559 const bool black = c[0] == 0 && c[1] == 0 && c[2] == 0; 5804 const bool black = c[0] == 0 && c[1] == 0 && c[2] == 0;
5560 if (black && c[3] == 0) { 5805 if (black && c[3] == 0) {
5561 sampler.border_color = g::BorderColor::transparent_black; 5806 sampler.border_color = g::BorderColor::transparent_black;
@@ -5569,11 +5814,54 @@ public:
5569 } 5814 }
5570 sampler.integer_border = true; 5815 sampler.integer_border = true;
5571 } 5816 }
5572 sampler.unnormalized = desc->Flags & D3D12_SAMPLER_FLAG_NON_NORMALIZED_COORDINATES; 5817 sampler.unnormalized = desc.Flags & D3D12_SAMPLER_FLAG_NON_NORMALIZED_COORDINATES;
5573 const leonida::gfx10::SamplerWords words = leonida::gfx10::encode(sampler); 5818 return leonida::gfx10::encode(sampler);
5574 std::memset(reinterpret_cast<void*>(destination.ptr), 0, kDescriptorSize); 5819 }
5575 std::memcpy(reinterpret_cast<void*>(destination.ptr), words.data(), sizeof(words)); 5820
5576 state_.bind_sampler(words); 5821 // A root signature's static samplers take no root argument: a shader that uses one holds its S# by value
5822 // (docs/d3d12_vulkan.md section 3.5). So each gets a sampler in set 0 and a key in the hash table here, as
5823 // CreateSampler gives a heap slot's S#; without them the shader's lookup misses and it samples through the
5824 // fallback sampler. A static sampler is a D3D12_SAMPLER_DESC2 whose border colour is one of five named ones
5825 // (D3D12_STATIC_BORDER_COLOR; the two UINT ones can be in a blob of any version, the flags only in 1.2).
5826 void register_static_samplers(const rt::rootsig::RootSignature& signature) {
5827 for (const rt::rootsig::StaticSampler& s : signature.static_samplers) {
5828 D3D12_SAMPLER_DESC2 desc{};
5829 desc.Filter = D3D12_FILTER(s.filter);
5830 desc.AddressU = D3D12_TEXTURE_ADDRESS_MODE(s.address_u);
5831 desc.AddressV = D3D12_TEXTURE_ADDRESS_MODE(s.address_v);
5832 desc.AddressW = D3D12_TEXTURE_ADDRESS_MODE(s.address_w);
5833 desc.MipLODBias = s.mip_lod_bias;
5834 desc.MaxAnisotropy = s.max_anisotropy;
5835 desc.ComparisonFunc = D3D12_COMPARISON_FUNC(s.comparison_func);
5836 desc.MinLOD = s.min_lod;
5837 desc.MaxLOD = s.max_lod;
5838 desc.Flags = D3D12_SAMPLER_FLAGS(s.flags);
5839 const bool white = s.border_color == D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE ||
5840 s.border_color == D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE_UINT;
5841 if (s.border_color == D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK_UINT ||
5842 s.border_color == D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE_UINT) {
5843 desc.Flags |= D3D12_SAMPLER_FLAG_UINT_BORDER_COLOR;
5844 desc.UintBorderColor[0] = desc.UintBorderColor[1] = desc.UintBorderColor[2] = white ? 1u : 0u;
5845 desc.UintBorderColor[3] = 1;
5846 } else if (s.border_color > D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE_UINT ||
5847 (desc.Flags & D3D12_SAMPLER_FLAG_UINT_BORDER_COLOR)) {
5848 // A value past the enum, or the UINT flag with a float border: not a sampler D3D12 defines.
5849 log_once("static sampler not registered: border colour and flags do not go together; border colour",
5850 int(s.border_color));
5851 continue;
5852 } else {
5853 desc.FloatBorderColor[0] = desc.FloatBorderColor[1] = desc.FloatBorderColor[2] = white ? 1.0f : 0.0f;
5854 desc.FloatBorderColor[3] =
5855 s.border_color == D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK ? 0.0f : 1.0f;
5856 }
5857 if (sampler2_refusal(desc)) {
5858 log_once("static sampler not registered: a sampler CreateSampler2 refuses; flags", int(desc.Flags));
5859 continue;
5860 }
5861 if (!state_.bind_sampler(sampler2_words(desc)))
5862 log_once("static sampler not registered: no room in the bindless set; register",
5863 int(s.shader_register));
5864 }
5577 } 5865 }
5578 5866
5579 // Why the PC runtime refuses a D3D12_SAMPLER_DESC2, or null. The non-normalized rules are its debug layer's 5867 // Why the PC runtime refuses a D3D12_SAMPLER_DESC2, or null. The non-normalized rules are its debug layer's
@@ -5601,32 +5889,8 @@ public:
5601 const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state, 5889 const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state,
5602 const D3D12_CLEAR_VALUE* clear, REFIID riid, 5890 const D3D12_CLEAR_VALUE* clear, REFIID riid,
5603 void** out) override { 5891 void** out) override {
5604 constexpr auto method = "ID3D12Device::CreateCommittedResource"; 5892 return create_committed_validated("ID3D12Device::CreateCommittedResource", heap, heap_flags, desc, state, clear,
5605 if (out) *out = nullptr; 5893 0, nullptr, riid, out);
5606 if (!heap || !desc) return d3d12_trace::result(method, E_INVALIDARG);
5607 // The host runtime's argument checks (D3D-49). A refusal is logged once per reason and dimension, since a
5608 // game that trips one (for example with an Xbox-only flag through slot 76) gets no resource.
5609 if (const char* why = committed_resource_refusal(*heap, heap_flags, *desc, state, clear,
5610 acceleration_structures())) {
5611 log_once((std::string("CreateCommittedResource refused (") + why + "), dimension").c_str(),
5612 desc->Dimension);
5613 return d3d12_trace::result(method, E_INVALIDARG);
5614 }
5615 // The sample quality is checked above as the host does it here: CreateCommittedResource accepts a quality on a
5616 // single-sampled texture and the two standard MSAA patterns, which GetResourceAllocationInfo's rules refuse.
5617 // The size, mip and alignment checks below run on a copy with quality 0.
5618 D3D12_RESOURCE_DESC checked = *desc;
5619 if (checked.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) checked.SampleDesc.Quality = 0;
5620 if ((desc->Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D ||
5621 desc->Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D) &&
5622 allocation(checked).SizeInBytes == UINT64_MAX) {
5623 // Extents, mips, samples and alignment, as GetResourceAllocationInfo answers.
5624 log_once("CreateCommittedResource refused (texture size, mips, samples or alignment), dimension",
5625 desc->Dimension);
5626 return d3d12_trace::result(method, E_INVALIDARG);
5627 }
5628 return d3d12_trace::result(method, create_committed(heap, heap_flags, desc, state, 0, nullptr, riid,
5629 out));
5630 } 5894 }
5631 5895
5632 // Reserved buffers use sparse binding where available. Textures and fallback buffers are fully backed. 5896 // Reserved buffers use sparse binding where available. Textures and fallback buffers are fully backed.
@@ -5637,8 +5901,7 @@ public:
5637 HRESULT STDMETHODCALLTYPE CreateReservedResource(const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state, 5901 HRESULT STDMETHODCALLTYPE CreateReservedResource(const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state,
5638 const D3D12_CLEAR_VALUE* clear, REFIID riid, 5902 const D3D12_CLEAR_VALUE* clear, REFIID riid,
5639 void** out) override { 5903 void** out) override {
5640 constexpr auto method = "ID3D12Device::CreateReservedResource"; 5904 return create_reserved("ID3D12Device::CreateReservedResource", desc, state, clear, 0, nullptr, riid, out);
5641 return d3d12_trace::result(method, create_reserved(desc, state, clear, riid, out));
5642 } 5905 }
5643 5906
5644 // Device4. Protected sessions are not supported. 5907 // Device4. Protected sessions are not supported.
@@ -5646,23 +5909,29 @@ public:
5646 const D3D12_CLEAR_VALUE* clear, 5909 const D3D12_CLEAR_VALUE* clear,
5647 ID3D12ProtectedResourceSession* session, REFIID riid, 5910 ID3D12ProtectedResourceSession* session, REFIID riid,
5648 void** out) override { 5911 void** out) override {
5649 if (session) { 5912 constexpr auto method = "ID3D12Device4::CreateReservedResource1";
5650 if (out) *out = nullptr; 5913 if (out) *out = nullptr;
5651 log_once("CreateReservedResource1 with a protected session not supported:", 1); 5914 if (!desc) return d3d12_trace::result(method, E_INVALIDARG);
5652 return E_NOTIMPL; 5915 if (session) return d3d12_trace::result(method, refuse_protected_session("CreateReservedResource1"));
5653 } 5916 return create_reserved(method, desc, state, clear, 0, nullptr, riid, out);
5654 return create_reserved(desc, state, clear, riid, out);
5655 } 5917 }
5656 5918
5657 // Device10: an initial layout instead of a state (resources start in their first use's layout here anyway). 5919 // Device10: an initial layout instead of a state (resources start in their first use's layout here anyway), and a
5658 // Castable formats are not used: typeless resources are already mutable-format images. 5920 // castable-format list forwarded to the backing texture.
5659 HRESULT STDMETHODCALLTYPE CreateReservedResource2(const D3D12_RESOURCE_DESC* desc, D3D12_BARRIER_LAYOUT, 5921 HRESULT STDMETHODCALLTYPE CreateReservedResource2(const D3D12_RESOURCE_DESC* desc, D3D12_BARRIER_LAYOUT layout,
5660 const D3D12_CLEAR_VALUE* clear, 5922 const D3D12_CLEAR_VALUE* clear,
5661 ID3D12ProtectedResourceSession* session, 5923 ID3D12ProtectedResourceSession* session,
5662 UINT32 castable_formats, const DXGI_FORMAT*, REFIID riid, 5924 UINT32 castable_formats, const DXGI_FORMAT* castable, REFIID riid,
5663 void** out) override { 5925 void** out) override {
5664 if (castable_formats) log_once("CreateReservedResource2: castable formats ignored, count", int(castable_formats)); 5926 constexpr auto method = "ID3D12Device10::CreateReservedResource2";
5665 return CreateReservedResource1(desc, D3D12_RESOURCE_STATE_COMMON, clear, session, riid, out); 5927 if (out) *out = nullptr;
5928 if (!desc) return d3d12_trace::result(method, E_INVALIDARG);
5929 if (session) return d3d12_trace::result(method, refuse_protected_session("CreateReservedResource2"));
5930 if (const char* why = barrier_layout_refusal(*desc, layout)) {
5931 log_once((std::string(method) + " refused (" + why + "), layout").c_str(), int(layout));
5932 return d3d12_trace::result(method, E_INVALIDARG);
5933 }
5934 return create_reserved(method, desc, D3D12_RESOURCE_STATE_COMMON, clear, castable_formats, castable, riid, out);
5666 } 5935 }
5667 5936
5668 // Tiling of a reserved resource or a tiled (64KB_UNDEFINED_SWIZZLE) texture (src/resource_tiling.h). Anything 5937 // Tiling of a reserved resource or a tiled (64KB_UNDEFINED_SWIZZLE) texture (src/resource_tiling.h). Anything
@@ -5701,7 +5970,7 @@ public:
5701 ID3D12ProtectedResourceSession* session, REFIID riid, 5970 ID3D12ProtectedResourceSession* session, REFIID riid,
5702 void** out) override { 5971 void** out) override {
5703 if (out) *out = nullptr; 5972 if (out) *out = nullptr;
5704 if (session) return refuse_protected_session(1); 5973 if (session) return refuse_protected_session("CreateCommittedResource1");
5705 return CreateCommittedResource(heap, heap_flags, desc, state, clear, riid, out); 5974 return CreateCommittedResource(heap, heap_flags, desc, state, clear, riid, out);
5706 } 5975 }
5707 5976
@@ -5712,7 +5981,7 @@ public:
5712 void** out) override { 5981 void** out) override {
5713 if (out) *out = nullptr; 5982 if (out) *out = nullptr;
5714 if (!desc) return E_INVALIDARG; 5983 if (!desc) return E_INVALIDARG;
5715 if (session) return refuse_protected_session(2); 5984 if (session) return refuse_protected_session("CreateCommittedResource2");
5716 if (texture_mip_region(*desc)) return E_INVALIDARG; 5985 if (texture_mip_region(*desc)) return E_INVALIDARG;
5717 const D3D12_RESOURCE_DESC base = resource_desc(*desc); 5986 const D3D12_RESOURCE_DESC base = resource_desc(*desc);
5718 return CreateCommittedResource(heap, heap_flags, &base, state, clear, riid, out); 5987 return CreateCommittedResource(heap, heap_flags, &base, state, clear, riid, out);
@@ -5720,23 +5989,25 @@ public:
5720 5989
5721 HRESULT STDMETHODCALLTYPE CreateCommittedResource3(const D3D12_HEAP_PROPERTIES* heap, D3D12_HEAP_FLAGS heap_flags, 5990 HRESULT STDMETHODCALLTYPE CreateCommittedResource3(const D3D12_HEAP_PROPERTIES* heap, D3D12_HEAP_FLAGS heap_flags,
5722 const D3D12_RESOURCE_DESC1* desc, D3D12_BARRIER_LAYOUT layout, 5991 const D3D12_RESOURCE_DESC1* desc, D3D12_BARRIER_LAYOUT layout,
5723 const D3D12_CLEAR_VALUE*, 5992 const D3D12_CLEAR_VALUE* clear,
5724 ID3D12ProtectedResourceSession* session, UINT32 castable_count, 5993 ID3D12ProtectedResourceSession* session, UINT32 castable_count,
5725 const DXGI_FORMAT* castable, REFIID riid, void** out) override { 5994 const DXGI_FORMAT* castable, REFIID riid, void** out) override {
5995 constexpr auto method = "ID3D12Device10::CreateCommittedResource3";
5726 if (out) *out = nullptr; 5996 if (out) *out = nullptr;
5727 if (!desc) return E_INVALIDARG; 5997 if (!desc) return d3d12_trace::result(method, E_INVALIDARG);
5728 if (session) return refuse_protected_session(3); 5998 if (session) return d3d12_trace::result(method, refuse_protected_session("CreateCommittedResource3"));
5729 if (texture_mip_region(*desc)) return E_INVALIDARG; 5999 if (texture_mip_region(*desc)) return d3d12_trace::result(method, E_INVALIDARG);
5730 // Enhanced barriers: a buffer has no layout, so its initial layout must be UNDEFINED.
5731 if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER && layout != D3D12_BARRIER_LAYOUT_UNDEFINED)
5732 return E_INVALIDARG;
5733 // A count with a null array is no list (as on the PC runtime). The layer reports relaxed format casting, so 6000 // A count with a null array is no list (as on the PC runtime). The layer reports relaxed format casting, so
5734 // a real list is passed through; only buffers are refused. 6001 // a real list is passed through; only buffers are refused.
5735 const D3D12_RESOURCE_DESC base = resource_desc(*desc); 6002 const D3D12_RESOURCE_DESC base = resource_desc(*desc);
6003 if (const char* why = barrier_layout_refusal(base, layout)) {
6004 log_once((std::string(method) + " refused (" + why + "), layout").c_str(), int(layout));
6005 return d3d12_trace::result(method, E_INVALIDARG);
6006 }
5736 // D3D12_BARRIER_LAYOUT has no acceleration-structure value; an AS buffer's state comes through the 6007 // D3D12_BARRIER_LAYOUT has no acceleration-structure value; an AS buffer's state comes through the
5737 // legacy CreateCommittedResource path. Buffers here start COMMON, as before. 6008 // legacy CreateCommittedResource path. Buffers here start COMMON, as before.
5738 return create_committed(heap, heap_flags, &base, D3D12_RESOURCE_STATE_COMMON, castable_count, castable, 6009 return create_committed_validated(method, heap, heap_flags, &base, D3D12_RESOURCE_STATE_COMMON, clear,
5739 riid, out); 6010 castable_count, castable, riid, out);
5740 } 6011 }
5741 6012
5742 // Device9. The creator ID only groups queues for tools; one creator is as good as another here. 6013 // Device9. The creator ID only groups queues for tools; one creator is as good as another here.
@@ -5786,7 +6057,8 @@ public:
5786 HRESULT STDMETHODCALLTYPE CreatePlacedResource(ID3D12Heap* heap_interface, UINT64 heap_offset, 6057 HRESULT STDMETHODCALLTYPE CreatePlacedResource(ID3D12Heap* heap_interface, UINT64 heap_offset,
5787 const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state, 6058 const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state,
5788 const D3D12_CLEAR_VALUE* clear, REFIID riid, void** out) override { 6059 const D3D12_CLEAR_VALUE* clear, REFIID riid, void** out) override {
5789 return create_placed(heap_interface, heap_offset, desc, state, clear, 0, nullptr, riid, out); 6060 return create_placed("ID3D12Device::CreatePlacedResource", heap_interface, heap_offset, desc, state, clear, 0,
6061 nullptr, riid, out);
5790 } 6062 }
5791 6063
5792 // Device8: the DESC1 placed variant without a castable list. A texture with a mip region gets the failure 6064 // Device8: the DESC1 placed variant without a castable list. A texture with a mip region gets the failure
@@ -5794,11 +6066,12 @@ public:
5794 HRESULT STDMETHODCALLTYPE CreatePlacedResource1(ID3D12Heap* heap_interface, UINT64 heap_offset, 6066 HRESULT STDMETHODCALLTYPE CreatePlacedResource1(ID3D12Heap* heap_interface, UINT64 heap_offset,
5795 const D3D12_RESOURCE_DESC1* desc, D3D12_RESOURCE_STATES state, 6067 const D3D12_RESOURCE_DESC1* desc, D3D12_RESOURCE_STATES state,
5796 const D3D12_CLEAR_VALUE* clear, REFIID riid, void** out) override { 6068 const D3D12_CLEAR_VALUE* clear, REFIID riid, void** out) override {
6069 constexpr auto method = "ID3D12Device8::CreatePlacedResource1";
5797 if (out) *out = nullptr; 6070 if (out) *out = nullptr;
5798 if (!desc) return E_INVALIDARG; 6071 if (!desc) return d3d12_trace::result(method, E_INVALIDARG);
5799 if (texture_mip_region(*desc)) return E_INVALIDARG; 6072 if (texture_mip_region(*desc)) return d3d12_trace::result(method, E_INVALIDARG);
5800 const D3D12_RESOURCE_DESC base = resource_desc(*desc); 6073 const D3D12_RESOURCE_DESC base = resource_desc(*desc);
5801 return create_placed(heap_interface, heap_offset, &base, state, clear, 0, nullptr, riid, out); 6074 return create_placed(method, heap_interface, heap_offset, &base, state, clear, 0, nullptr, riid, out);
5802 } 6075 }
5803 6076
5804 // Device10: an initial layout instead of a state, and the castable-format list, which the placed texture's 6077 // Device10: an initial layout instead of a state, and the castable-format list, which the placed texture's
@@ -5808,16 +6081,18 @@ public:
5808 const D3D12_RESOURCE_DESC1* desc, D3D12_BARRIER_LAYOUT layout, 6081 const D3D12_RESOURCE_DESC1* desc, D3D12_BARRIER_LAYOUT layout,
5809 const D3D12_CLEAR_VALUE* clear, UINT32 castable_count, 6082 const D3D12_CLEAR_VALUE* clear, UINT32 castable_count,
5810 const DXGI_FORMAT* castable, REFIID riid, void** out) override { 6083 const DXGI_FORMAT* castable, REFIID riid, void** out) override {
6084 constexpr auto method = "ID3D12Device10::CreatePlacedResource2";
5811 if (out) *out = nullptr; 6085 if (out) *out = nullptr;
5812 if (!desc) return E_INVALIDARG; 6086 if (!desc) return d3d12_trace::result(method, E_INVALIDARG);
5813 if (texture_mip_region(*desc)) return E_INVALIDARG; 6087 if (texture_mip_region(*desc)) return d3d12_trace::result(method, E_INVALIDARG);
5814 // Enhanced barriers: a buffer has no layout, so its initial layout must be UNDEFINED.
5815 if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER && layout != D3D12_BARRIER_LAYOUT_UNDEFINED)
5816 return E_INVALIDARG;
5817 const D3D12_RESOURCE_DESC base = resource_desc(*desc); 6088 const D3D12_RESOURCE_DESC base = resource_desc(*desc);
6089 if (const char* why = barrier_layout_refusal(base, layout)) {
6090 log_once((std::string(method) + " refused (" + why + "), layout").c_str(), int(layout));
6091 return d3d12_trace::result(method, E_INVALIDARG);
6092 }
5818 // An initial layout replaces the state, so the state rules are not this call's. 6093 // An initial layout replaces the state, so the state rules are not this call's.
5819 return create_placed(heap_interface, heap_offset, &base, D3D12_RESOURCE_STATE_COMMON, clear, castable_count, 6094 return create_placed(method, heap_interface, heap_offset, &base, D3D12_RESOURCE_STATE_COMMON, clear,
5820 castable, riid, out); 6095 castable_count, castable, riid, out);
5821 } 6096 }
5822 6097
5823 // The placed path every CreatePlacedResource variant shares. A castable-format list reaches the placed 6098 // The placed path every CreatePlacedResource variant shares. A castable-format list reaches the placed
@@ -5828,15 +6103,15 @@ public:
5828 // CreateCommittedResource has, then the placement: a buffer at a 64 KiB-aligned offset, a texture at a 6103 // CreateCommittedResource has, then the placement: a buffer at a 64 KiB-aligned offset, a texture at a
5829 // multiple of its GetResourceAllocationInfo alignment (4 KiB for a small texture), in a heap aligned at least 6104 // multiple of its GetResourceAllocationInfo alignment (4 KiB for a small texture), in a heap aligned at least
5830 // as much, and the whole resource inside the heap. Only then is a null output E_UNEXPECTED, with nothing made. 6105 // as much, and the whole resource inside the heap. Only then is a null output E_UNEXPECTED, with nothing made.
5831 HRESULT create_placed(ID3D12Heap* heap_interface, UINT64 heap_offset, const D3D12_RESOURCE_DESC* desc, 6106 HRESULT create_placed(const char* method, ID3D12Heap* heap_interface, UINT64 heap_offset,
5832 D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear, UINT32 castable_count, 6107 const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear,
5833 const DXGI_FORMAT* castable, REFIID riid, void** out) { 6108 UINT32 castable_count, const DXGI_FORMAT* castable, REFIID riid, void** out) {
5834 if (out) *out = nullptr; 6109 if (out) *out = nullptr;
5835 auto* heap = Heap::from<Heap>(heap_interface); 6110 auto* heap = Heap::from<Heap>(heap_interface);
5836 if (!heap || !desc) return E_INVALIDARG; 6111 if (!heap || !desc) return d3d12_trace::result(method, E_INVALIDARG);
5837 if (castable_count && castable && desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { 6112 if (castable_count && castable && desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) {
5838 log_once("castable formats on a placed buffer are invalid; count", int(castable_count)); 6113 log_once("castable formats on a placed buffer are invalid; count", int(castable_count));
5839 return E_INVALIDARG; 6114 return d3d12_trace::result(method, E_INVALIDARG);
5840 } 6115 }
5841 // The description, state and clear value rules of a committed resource, but on a default heap: the heap's 6116 // The description, state and clear value rules of a committed resource, but on a default heap: the heap's
5842 // DENY flags are checked against the resource below, and the host takes any initial state for a buffer in 6117 // DENY flags are checked against the resource below, and the host takes any initial state for a buffer in
@@ -5850,62 +6125,73 @@ public:
5850 (desc->Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) 6125 (desc->Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS))
5851 why = "UAV access in an upload or readback heap"; 6126 why = "UAV access in an upload or readback heap";
5852 if (why) { 6127 if (why) {
5853 log_once((std::string("CreatePlacedResource refused (") + why + "), dimension").c_str(), 6128 log_once((std::string(method) + " refused (" + why + "), dimension").c_str(), int(desc->Dimension));
5854 desc->Dimension); 6129 return d3d12_trace::result(method, E_INVALIDARG);
5855 return E_INVALIDARG;
5856 } 6130 }
5857 const bool tiled = is_tiled_layout(desc->Layout); 6131 const bool tiled = is_tiled_layout(desc->Layout);
6132 const bool msaa = desc->SampleDesc.Count > 1;
5858 if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { 6133 if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) {
5859 if (heap->flags() & D3D12_HEAP_FLAG_DENY_BUFFERS) return E_INVALIDARG; 6134 if (heap->flags() & D3D12_HEAP_FLAG_DENY_BUFFERS) return d3d12_trace::result(method, E_INVALIDARG);
5860 if (heap_offset % D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT) { 6135 if (heap_offset % D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT) {
5861 log_once("placed buffer offset not 64 KiB aligned:", int(heap_offset)); 6136 log_once("placed buffer offset not 64 KiB aligned:", int(heap_offset));
5862 return E_INVALIDARG; 6137 return d3d12_trace::result(method, E_INVALIDARG);
5863 } 6138 }
5864 if (desc->Width > heap->bytes() || heap_offset > heap->bytes() - desc->Width) return E_INVALIDARG; 6139 if (desc->Width > heap->bytes() || heap_offset > heap->bytes() - desc->Width)
6140 return d3d12_trace::result(method, E_INVALIDARG);
5865 } else { 6141 } else {
5866 if (heap->properties().Type == D3D12_HEAP_TYPE_UPLOAD || 6142 if (heap->properties().Type == D3D12_HEAP_TYPE_UPLOAD ||
5867 heap->properties().Type == D3D12_HEAP_TYPE_READBACK) 6143 heap->properties().Type == D3D12_HEAP_TYPE_READBACK)
5868 return E_INVALIDARG; 6144 return d3d12_trace::result(method, E_INVALIDARG);
5869 const bool rt_ds = (desc->Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | 6145 const bool rt_ds = (desc->Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET |
5870 D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) != 0; 6146 D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) != 0;
5871 if (rt_ds && (heap->flags() & D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES)) return E_INVALIDARG; 6147 if (rt_ds && (heap->flags() & D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES))
5872 if (!rt_ds && (heap->flags() & D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES)) return E_INVALIDARG; 6148 return d3d12_trace::result(method, E_INVALIDARG);
6149 if (!rt_ds && (heap->flags() & D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES))
6150 return d3d12_trace::result(method, E_INVALIDARG);
5873 if (tiled && desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D && 6151 if (tiled && desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D &&
5874 desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE3D) 6152 desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE3D)
5875 return E_INVALIDARG; 6153 return d3d12_trace::result(method, E_INVALIDARG);
5876 if (desc->SampleDesc.Count > 1 && desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) 6154 if (msaa && desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D)
5877 return E_INVALIDARG; 6155 return d3d12_trace::result(method, E_INVALIDARG);
5878 // Extents, mips, samples, layout and alignment, as GetResourceAllocationInfo answers them (the sample 6156 // Extents, mips, samples, layout and alignment, as GetResourceAllocationInfo answers them (the sample
5879 // quality is the description rules' above, as in CreateCommittedResource). 6157 // quality is the description rules' above, as in CreateCommittedResource).
5880 D3D12_RESOURCE_DESC checked = *desc; 6158 D3D12_RESOURCE_DESC checked = *desc;
5881 checked.SampleDesc.Quality = 0; 6159 checked.SampleDesc.Quality = 0;
5882 const D3D12_RESOURCE_ALLOCATION_INFO alloc = allocation(checked); 6160 const D3D12_RESOURCE_ALLOCATION_INFO alloc = allocation(checked);
5883 if (alloc.SizeInBytes == UINT64_MAX || heap->alignment() < alloc.Alignment || 6161 if (alloc.SizeInBytes == UINT64_MAX || heap->alignment() < alloc.Alignment ||
5884 heap_offset % alloc.Alignment || alloc.SizeInBytes > heap->bytes() || 6162 heap_offset % alloc.Alignment) {
5885 heap_offset > heap->bytes() - alloc.SizeInBytes) {
5886 log_once("placed texture refused (size, alignment or room in the heap), dimension", 6163 log_once("placed texture refused (size, alignment or room in the heap), dimension",
5887 int(desc->Dimension)); 6164 int(desc->Dimension));
5888 return E_INVALIDARG; 6165 return d3d12_trace::result(method, E_INVALIDARG);
6166 }
6167 const UINT64 fit_bytes =
6168 (tiled || msaa)
6169 ? alloc.SizeInBytes
6170 : min_placed_texture_bytes(checked, state_.texture_format(checked), alloc.Alignment,
6171 alloc.SizeInBytes);
6172 if (fit_bytes > heap->bytes() || heap_offset > heap->bytes() - fit_bytes) {
6173 log_once("placed texture refused (size, alignment or room in the heap), dimension",
6174 int(desc->Dimension));
6175 return d3d12_trace::result(method, E_INVALIDARG);
5889 } 6176 }
5890 if (tiled && static_cast<UINT>(desc->Layout) == kXboxTiledLayout) { 6177 if (tiled && static_cast<UINT>(desc->Layout) == kXboxTiledLayout) {
5891 log_once("placed resource with the Xbox tiled layout, as 64KB_UNDEFINED_SWIZZLE; dimension", 6178 log_once("placed resource with the Xbox tiled layout, as 64KB_UNDEFINED_SWIZZLE; dimension",
5892 int(desc->Dimension)); 6179 int(desc->Dimension));
5893 } 6180 }
5894 } 6181 }
5895 if (!out) return E_UNEXPECTED; 6182 if (!out) return d3d12_trace::result(method, E_UNEXPECTED);
5896 if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER && !heap->use_as_placed_buffer(true)) { 6183 if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER && !heap->use_as_placed_buffer(true)) {
5897 log_once("placed buffer refused: heap uses a separate allocation for sparse tiles", 1); 6184 log_once("placed buffer refused: heap uses a separate allocation for sparse tiles", 1);
5898 return E_NOTIMPL; 6185 return d3d12_trace::result(method, E_NOTIMPL);
5899 } 6186 }
5900 // Only buffers are addressable, as in D3D12: a placed texture keeps a null VA and its own Vulkan image. 6187 // Only buffers are addressable, as in D3D12: a placed texture keeps a null VA and its own Vulkan image, which
6188 // create_texture makes for 1D, 2D and 3D alike (arrays and mips included), as for a committed texture.
5901 const VkDeviceSize placed_va = desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER ? heap->offset() + heap_offset : 0; 6189 const VkDeviceSize placed_va = desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER ? heap->offset() + heap_offset : 0;
5902 auto* resource = new Resource(state_, *desc, heap->properties(), heap->flags(), placed_va); 6190 auto* resource = new Resource(state_, *desc, heap->properties(), heap->flags(), placed_va);
5903 resource->attach_device(identity()); 6191 resource->attach_device(identity());
5904 HRESULT hr = E_NOTIMPL; 6192 HRESULT hr = E_NOTIMPL;
5905 if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { 6193 if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) {
5906 hr = resource->create_placed_buffer(); 6194 hr = resource->create_placed_buffer();
5907 } else if (!tiled && desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) {
5908 log_once("placed resource dimension not supported:", int(desc->Dimension));
5909 } else { 6195 } else {
5910 hr = S_OK; 6196 hr = S_OK;
5911 const Format format = state_.texture_format(*desc); 6197 const Format format = state_.texture_format(*desc);
@@ -5920,9 +6206,9 @@ public:
5920 } 6206 }
5921 if (FAILED(hr)) { 6207 if (FAILED(hr)) {
5922 resource->Release(); 6208 resource->Release();
5923 return hr; 6209 return d3d12_trace::result(method, hr);
5924 } 6210 }
5925 return hand_out(resource, riid, out); 6211 return d3d12_trace::result(method, hand_out(resource, riid, out));
5926 } 6212 }
5927 6213
5928 // Footprints for copies through a buffer: rows padded to D3D12_TEXTURE_DATA_PITCH_ALIGNMENT (512 for planar 6214 // Footprints for copies through a buffer: rows padded to D3D12_TEXTURE_DATA_PITCH_ALIGNMENT (512 for planar
@@ -6020,16 +6306,23 @@ public:
6020 // to D3D12's alignment for it; the alignment itself is D3D12's, since placed textures bind their own memory 6306 // to D3D12's alignment for it; the alignment itself is D3D12's, since placed textures bind their own memory
6021 // (section 4.2). Several resources are laid out one after another, each at its own alignment. An invalid 6307 // (section 4.2). Several resources are laid out one after another, each at its own alignment. An invalid
6022 // description gives SizeInBytes = UINT64_MAX, as on D3D12. d3d12_vulkan_device_test compares with the PC runtime. 6308 // description gives SizeInBytes = UINT64_MAX, as on D3D12. d3d12_vulkan_device_test compares with the PC runtime.
6309 // A visible mask above 1 names a node the single-node adapter lacks: the same invalid answer, also for no
6310 // resources at all, and the per-resource array is left untouched (host runtime and WARP, measured).
6023 D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE GetResourceAllocationInfo( 6311 D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE GetResourceAllocationInfo(
6024 UINT, UINT count, const D3D12_RESOURCE_DESC* descs) override { 6312 UINT visible_mask, UINT count, const D3D12_RESOURCE_DESC* descs) override {
6313 if (visible_mask > 1) return kInvalidAllocation;
6025 return place(count, descs, [&](UINT i) { return descs[i]; }, nullptr); 6314 return place(count, descs, [&](UINT i) { return descs[i]; }, nullptr);
6026 } 6315 }
6027 D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE GetResourceAllocationInfo1( 6316 D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE GetResourceAllocationInfo1(
6028 UINT, UINT count, const D3D12_RESOURCE_DESC* descs, D3D12_RESOURCE_ALLOCATION_INFO1* each) override { 6317 UINT visible_mask, UINT count, const D3D12_RESOURCE_DESC* descs,
6318 D3D12_RESOURCE_ALLOCATION_INFO1* each) override {
6319 if (visible_mask > 1) return kInvalidAllocation;
6029 return place(count, descs, [&](UINT i) { return descs[i]; }, each); 6320 return place(count, descs, [&](UINT i) { return descs[i]; }, each);
6030 } 6321 }
6031 D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE GetResourceAllocationInfo2( 6322 D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE GetResourceAllocationInfo2(
6032 UINT, UINT count, const D3D12_RESOURCE_DESC1* descs, D3D12_RESOURCE_ALLOCATION_INFO1* each) override { 6323 UINT visible_mask, UINT count, const D3D12_RESOURCE_DESC1* descs,
6324 D3D12_RESOURCE_ALLOCATION_INFO1* each) override {
6325 if (visible_mask > 1) return kInvalidAllocation;
6033 return place(count, descs, [&](UINT i) { 6326 return place(count, descs, [&](UINT i) {
6034 const D3D12_RESOURCE_DESC1& d = descs[i]; 6327 const D3D12_RESOURCE_DESC1& d = descs[i];
6035 if (d.SamplerFeedbackMipRegion.Width || d.SamplerFeedbackMipRegion.Height || 6328 if (d.SamplerFeedbackMipRegion.Width || d.SamplerFeedbackMipRegion.Height ||
@@ -6276,20 +6569,20 @@ public:
6276 opts->ComputeOnlyCustomHeapSupported = FALSE; 6569 opts->ComputeOnlyCustomHeapSupported = FALSE;
6277 return d3d12_trace::result(method, S_OK); 6570 return d3d12_trace::result(method, S_OK);
6278 } 6571 }
6279 case D3D12_FEATURE_D3D12_OPTIONS20: { 6572 case compat::kFeatureOptions20: {
6280 if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS20)) return d3d12_trace::result(method, E_INVALIDARG); 6573 if (size != sizeof(compat::FeatureDataOptions20)) return d3d12_trace::result(method, E_INVALIDARG);
6281 auto* opts = static_cast<D3D12_FEATURE_DATA_D3D12_OPTIONS20*>(data); 6574 auto* opts = static_cast<compat::FeatureDataOptions20*>(data);
6282 *opts = {}; 6575 *opts = {};
6283 opts->ComputeOnlyWriteWatchSupported = FALSE; 6576 opts->ComputeOnlyWriteWatchSupported = FALSE;
6284 opts->RecreateAtTier = D3D12_RECREATE_AT_TIER_NOT_SUPPORTED; 6577 opts->RecreateAtTier = compat::kRecreateAtTierNotSupported;
6285 return d3d12_trace::result(method, S_OK); 6578 return d3d12_trace::result(method, S_OK);
6286 } 6579 }
6287 case D3D12_FEATURE_D3D12_OPTIONS21: { 6580 case compat::kFeatureOptions21: {
6288 if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS21)) return d3d12_trace::result(method, E_INVALIDARG); 6581 if (size != sizeof(compat::FeatureDataOptions21)) return d3d12_trace::result(method, E_INVALIDARG);
6289 auto* opts = static_cast<D3D12_FEATURE_DATA_D3D12_OPTIONS21*>(data); 6582 auto* opts = static_cast<compat::FeatureDataOptions21*>(data);
6290 *opts = {}; 6583 *opts = {};
6291 opts->WorkGraphsTier = D3D12_WORK_GRAPHS_TIER_NOT_SUPPORTED; 6584 opts->WorkGraphsTier = compat::kWorkGraphsTierNotSupported;
6292 opts->ExecuteIndirectTier = D3D12_EXECUTE_INDIRECT_TIER_1_0; 6585 opts->ExecuteIndirectTier = compat::kExecuteIndirectTier1_0;
6293 opts->SampleCmpGradientAndBiasSupported = FALSE; 6586 opts->SampleCmpGradientAndBiasSupported = FALSE;
6294 opts->ExtendedCommandInfoSupported = FALSE; 6587 opts->ExtendedCommandInfoSupported = FALSE;
6295 return d3d12_trace::result(method, S_OK); 6588 return d3d12_trace::result(method, S_OK);
@@ -6718,8 +7011,8 @@ public:
6718 case D3D12_FEATURE_QUERY_META_COMMAND: 7011 case D3D12_FEATURE_QUERY_META_COMMAND:
6719 // EnumerateMetaCommands reports 0 meta-commands, so any query is rejected (as on host D3D12). 7012 // EnumerateMetaCommands reports 0 meta-commands, so any query is rejected (as on host D3D12).
6720 return d3d12_trace::result(method, E_INVALIDARG); 7013 return d3d12_trace::result(method, E_INVALIDARG);
6721 case D3D12_FEATURE_PREDICATION: 7014 case compat::kFeaturePredication:
6722 return write_supported_feature<D3D12_FEATURE_DATA_PREDICATION>( 7015 return write_supported_feature<compat::FeatureSupportFlag>(
6723 method, data, size, state_.info.conditional_rendering ? TRUE : FALSE); 7016 method, data, size, state_.info.conditional_rendering ? TRUE : FALSE);
6724 case compat::kFeatureApplicationSpecificDriverState: 7017 case compat::kFeatureApplicationSpecificDriverState:
6725 return write_supported_feature<compat::FeatureSupportFlag>(method, data, size, FALSE); 7018 return write_supported_feature<compat::FeatureSupportFlag>(method, data, size, FALSE);
@@ -6870,6 +7163,42 @@ private:
6870 tiles(volume ? desc.DepthOrArraySize : 1, 1, shape.depth) <= 16; 7163 tiles(volume ? desc.DepthOrArraySize : 1, 1, shape.depth) <= 16;
6871 } 7164 }
6872 7165
7166 // Strict lower bound on the heap bytes a non-tiled single-sample texture needs: sums uncompressed texel/block
7167 // payload across subresources and rounds to `alignment`, capped at `fallback` (Vulkan allocation size). Avoids
7168 // rejecting host-valid placed textures when Vulkan driver padding exceeds D3D12's GetResourceAllocationInfo.
7169 static UINT64 min_placed_texture_bytes(const D3D12_RESOURCE_DESC& desc, const Format& format, UINT64 alignment,
7170 UINT64 fallback) {
7171 const VkImageAspectFlags aspect =
7172 (format.aspects & VK_IMAGE_ASPECT_DEPTH_BIT) ? VK_IMAGE_ASPECT_DEPTH_BIT : format.aspects;
7173 const leonida::BlockFormat block = footprint_block(format, aspect);
7174 if (!block.bytes || !alignment) return fallback;
7175 const bool volume = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D;
7176 const bool one_d = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D;
7177 const UINT depth = volume ? desc.DepthOrArraySize : 1;
7178 const UINT slices = volume ? 1 : desc.DepthOrArraySize;
7179 const UINT mips = desc.MipLevels ? desc.MipLevels : full_mips(desc.Width, desc.Height, depth);
7180 UINT64 per_slice = 0;
7181 for (UINT m = 0; m < mips; ++m) {
7182 const UINT64 w = std::max<UINT64>(1, desc.Width >> m);
7183 const UINT64 h = one_d ? 1 : std::max<UINT64>(1, desc.Height >> m);
7184 const UINT64 d = volume ? std::max<UINT64>(1, depth >> m) : 1;
7185 const UINT64 bw = (w + block.block - 1) / block.block;
7186 const UINT64 bh = (h + block.block - 1) / block.block;
7187 if (bw > UINT64_MAX / bh) return fallback;
7188 const UINT64 blocks = bw * bh;
7189 if (blocks > UINT64_MAX / d) return fallback;
7190 const UINT64 count = blocks * d;
7191 if (count > UINT64_MAX / block.bytes) return fallback;
7192 const UINT64 mip_bytes = count * block.bytes;
7193 if (per_slice > UINT64_MAX - mip_bytes) return fallback;
7194 per_slice += mip_bytes;
7195 }
7196 if (slices && per_slice > UINT64_MAX / slices) return fallback;
7197 const UINT64 total = per_slice * slices;
7198 if (total > UINT64_MAX - (alignment - 1)) return fallback;
7199 return std::min(fallback, align_up(total, alignment));
7200 }
7201
6873 // Writes the view's T# into the slot and makes sure set 0 and the hash table know it. A view that cannot be 7202 // Writes the view's T# into the slot and makes sure set 0 and the hash table know it. A view that cannot be
6874 // shown leaves the slot a null descriptor. 7203 // shown leaves the slot a null descriptor.
6875 void write_image_descriptor(const Resource& resource, const TextureView& view, 7204 void write_image_descriptor(const Resource& resource, const TextureView& view,
@@ -6884,9 +7213,40 @@ private:
6884 std::memcpy(reinterpret_cast<void*>(destination.ptr), words.data(), sizeof(words)); 7213 std::memcpy(reinterpret_cast<void*>(destination.ptr), words.data(), sizeof(words));
6885 } 7214 }
6886 7215
6887 // Shared by CreateCommittedResource and CreateCommittedResource3. A castable-format list is only meaningful on 7216 // Validation shared by CreateCommittedResource and CreateCommittedResource3; internal callers pass null `method`
6888 // textures; the layer reports RelaxedFormatCastingSupported, so each format is mapped and handed to Vulkan as a 7217 // to skip trace recording.
6889 // VkImageFormatListCreateInfo. A nonzero count with a null list is no list, as on the PC runtime. 7218 HRESULT create_committed_validated(const char* method, const D3D12_HEAP_PROPERTIES* heap,
7219 D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC* desc,
7220 D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear,
7221 UINT32 castable_count, const DXGI_FORMAT* castable, REFIID riid, void** out) {
7222 const auto finish = [&](HRESULT hr) { return method ? d3d12_trace::result(method, hr) : hr; };
7223 if (out) *out = nullptr;
7224 if (!heap || !desc) return finish(E_INVALIDARG);
7225 if (const char* why = committed_resource_refusal(*heap, heap_flags, *desc, state, clear,
7226 acceleration_structures())) {
7227 log_once((std::string(method ? method : "CreateCommittedResource") + " refused (" + why + "), dimension")
7228 .c_str(),
7229 int(desc->Dimension));
7230 return finish(E_INVALIDARG);
7231 }
7232 // The sample quality is checked above as the host does it here: CreateCommittedResource accepts a quality on a
7233 // 1x texture while GetResourceAllocationInfo requires 0; the other texture checks stay shared with allocation.
7234 D3D12_RESOURCE_DESC checked = *desc;
7235 if (checked.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) checked.SampleDesc.Quality = 0;
7236 if (desc->Dimension != D3D12_RESOURCE_DIMENSION_BUFFER && allocation(checked).SizeInBytes == UINT64_MAX) {
7237 log_once((std::string(method ? method : "CreateCommittedResource") +
7238 " refused (texture size, mips, samples or alignment), dimension")
7239 .c_str(),
7240 int(desc->Dimension));
7241 return finish(E_INVALIDARG);
7242 }
7243 return finish(create_committed(heap, heap_flags, desc, state, castable_count, castable, riid, out));
7244 }
7245
7246 // Shared by CreateCommittedResource, CreateCommittedResource3 and CreateReservedResource*. A castable-format list
7247 // is only meaningful on textures; the layer reports RelaxedFormatCastingSupported, so each format is mapped and
7248 // handed to Vulkan as a VkImageFormatListCreateInfo. A nonzero count with a null list is no list, as on the PC
7249 // runtime.
6890 HRESULT create_committed(const D3D12_HEAP_PROPERTIES* heap, D3D12_HEAP_FLAGS heap_flags, 7250 HRESULT create_committed(const D3D12_HEAP_PROPERTIES* heap, D3D12_HEAP_FLAGS heap_flags,
6891 const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES initial_state, 7251 const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES initial_state,
6892 UINT32 castable_count, const DXGI_FORMAT* castable, REFIID riid, void** out) { 7252 UINT32 castable_count, const DXGI_FORMAT* castable, REFIID riid, void** out) {
@@ -7012,43 +7372,47 @@ private:
7012 // compare_placed_reserved, RTX 3060 / 610.88): the description, initial state and clear value rules of a 7372 // compare_placed_reserved, RTX 3060 / 610.88): the description, initial state and clear value rules of a
7013 // committed resource on a default heap, the reserved layouts below, and only then E_UNEXPECTED for a null 7373 // committed resource on a default heap, the reserved layouts below, and only then E_UNEXPECTED for a null
7014 // output, with nothing made. 7374 // output, with nothing made.
7015 HRESULT create_reserved(const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state, 7375 HRESULT create_reserved(const char* method, const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state,
7016 const D3D12_CLEAR_VALUE* clear, REFIID riid, void** out) { 7376 const D3D12_CLEAR_VALUE* clear, UINT32 castable_count, const DXGI_FORMAT* castable,
7377 REFIID riid, void** out) {
7017 if (out) *out = nullptr; 7378 if (out) *out = nullptr;
7018 if (!desc) return E_INVALIDARG; 7379 if (!desc) return d3d12_trace::result(method, E_INVALIDARG);
7380 if (castable_count && castable && desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) {
7381 log_once("castable formats on a reserved buffer are invalid; count", int(castable_count));
7382 return d3d12_trace::result(method, E_INVALIDARG);
7383 }
7019 D3D12_RESOURCE_DESC backing = *desc; 7384 D3D12_RESOURCE_DESC backing = *desc;
7020 const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; 7385 const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT};
7021 if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { 7386 if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) {
7022 if (desc->Layout != D3D12_TEXTURE_LAYOUT_ROW_MAJOR) return E_INVALIDARG; 7387 if (desc->Layout != D3D12_TEXTURE_LAYOUT_ROW_MAJOR) return d3d12_trace::result(method, E_INVALIDARG);
7023 } else { 7388 } else {
7024 if (static_cast<UINT>(desc->Layout) == kXboxTiledLayout) { 7389 if (static_cast<UINT>(desc->Layout) == kXboxTiledLayout) {
7025 log_once("reserved resource with the Xbox tiled layout, as 64KB_UNDEFINED_SWIZZLE; dimension", 7390 log_once("reserved resource with the Xbox tiled layout, as 64KB_UNDEFINED_SWIZZLE; dimension",
7026 desc->Dimension); 7391 desc->Dimension);
7027 } else if (desc->Layout != D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE) { 7392 } else if (desc->Layout != D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE) {
7028 return E_INVALIDARG; // 64KB_STANDARD_SWIZZLE too: CheckFeatureSupport reports it unsupported 7393 return d3d12_trace::result(method, E_INVALIDARG); // 64KB_STANDARD_SWIZZLE too: CheckFeatureSupport reports it unsupported
7029 } 7394 }
7030 backing.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; 7395 backing.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
7031 leonida::ResourceTiling tiling; 7396 leonida::ResourceTiling tiling;
7032 backing.MipLevels = std::max<UINT16>(desc->MipLevels, 1); // any count: only the format is checked here 7397 backing.MipLevels = std::max<UINT16>(desc->MipLevels, 1); // any count: only the format is checked here
7033 if (!resource_tiling(backing, tiling)) { 7398 if (!resource_tiling(backing, tiling)) {
7034 log_once("reserved texture format has no tile shape:", desc->Format); 7399 log_once("reserved texture format has no tile shape:", desc->Format);
7035 return E_INVALIDARG; 7400 return d3d12_trace::result(method, E_INVALIDARG);
7036 } 7401 }
7037 backing.MipLevels = desc->MipLevels; 7402 backing.MipLevels = desc->MipLevels;
7038 } 7403 }
7039 if (const char* why = committed_resource_refusal(heap, D3D12_HEAP_FLAG_NONE, backing, state, clear, 7404 if (const char* why = committed_resource_refusal(heap, D3D12_HEAP_FLAG_NONE, backing, state, clear,
7040 acceleration_structures())) { 7405 acceleration_structures())) {
7041 log_once((std::string("CreateReservedResource refused (") + why + "), dimension").c_str(), 7406 log_once((std::string(method) + " refused (" + why + "), dimension").c_str(), int(desc->Dimension));
7042 desc->Dimension); 7407 return d3d12_trace::result(method, E_INVALIDARG);
7043 return E_INVALIDARG;
7044 } 7408 }
7045 if (desc->Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) { 7409 if (desc->Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) {
7046 // Extents, mips and samples, as the committed backing below checks them (GetResourceAllocationInfo). 7410 // Extents, mips and samples, as the committed backing below checks them (GetResourceAllocationInfo).
7047 D3D12_RESOURCE_DESC checked = backing; 7411 D3D12_RESOURCE_DESC checked = backing;
7048 checked.SampleDesc.Quality = 0; 7412 checked.SampleDesc.Quality = 0;
7049 if (allocation(checked).SizeInBytes == UINT64_MAX) return E_INVALIDARG; 7413 if (allocation(checked).SizeInBytes == UINT64_MAX) return d3d12_trace::result(method, E_INVALIDARG);
7050 } 7414 }
7051 if (!out) return E_UNEXPECTED; 7415 if (!out) return d3d12_trace::result(method, E_UNEXPECTED);
7052 ID3D12Resource* resource = nullptr; 7416 ID3D12Resource* resource = nullptr;
7053 HRESULT hr; 7417 HRESULT hr;
7054 if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER && state_.sparse_buffer_memory_types) { 7418 if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER && state_.sparse_buffer_memory_types) {
@@ -7057,18 +7421,18 @@ private:
7057 hr = sparse->create_sparse_buffer(); 7421 hr = sparse->create_sparse_buffer();
7058 if (FAILED(hr)) { 7422 if (FAILED(hr)) {
7059 sparse->Release(); 7423 sparse->Release();
7060 return hr; 7424 return d3d12_trace::result(method, hr);
7061 } 7425 }
7062 resource = sparse; 7426 resource = sparse;
7063 } else { 7427 } else {
7064 hr = CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &backing, D3D12_RESOURCE_STATE_COMMON, 7428 hr = create_committed_validated(nullptr, &heap, D3D12_HEAP_FLAG_NONE, &backing, D3D12_RESOURCE_STATE_COMMON,
7065 nullptr, IID_PPV_ARGS(&resource)); 7429 clear, castable_count, castable, IID_PPV_ARGS(&resource));
7066 } 7430 }
7067 if (FAILED(hr)) return hr; 7431 if (FAILED(hr)) return d3d12_trace::result(method, hr);
7068 Resource::from<Resource>(resource)->make_reserved(desc->Layout); 7432 Resource::from<Resource>(resource)->make_reserved(desc->Layout);
7069 hr = resource->QueryInterface(riid, out); 7433 hr = resource->QueryInterface(riid, out);
7070 resource->Release(); 7434 resource->Release();
7071 return hr; 7435 return d3d12_trace::result(method, hr);
7072 } 7436 }
7073 7437
7074 // The tiling of a reserved resource's description; false for formats without a tile shape (three- and 7438 // The tiling of a reserved resource's description; false for formats without a tile shape (three- and
@@ -7133,9 +7497,9 @@ private:
7133 } 7497 }
7134 7498
7135 // The layer reports no protected-session support, so a session is refused, as D3D12 refuses one on a device 7499 // The layer reports no protected-session support, so a session is refused, as D3D12 refuses one on a device
7136 // without D3D12_FEATURE_PROTECTED_RESOURCE_SESSION_SUPPORT. `variant` is the method's number. 7500 // without D3D12_FEATURE_PROTECTED_RESOURCE_SESSION_SUPPORT.
7137 static HRESULT refuse_protected_session(int variant) { 7501 static HRESULT refuse_protected_session(const char* method) {
7138 log_once("protected resource session refused (not supported) by CreateCommittedResource", variant); 7502 log_once((std::string("protected resource session refused (not supported) by ") + method + ':').c_str(), 1);
7139 return E_INVALIDARG; 7503 return E_INVALIDARG;
7140 } 7504 }
7141 7505
@@ -7181,7 +7545,28 @@ std::shared_ptr<const leonida::TileHeapAllocation> tile_heap(ID3D12Heap* heap, c
7181} 7545}
7182 7546
7183void set_device_outer(ID3D12Device* device, IUnknown* outer) { 7547void set_device_outer(ID3D12Device* device, IUnknown* outer) {
7184 if (Device* d = Device::from<Device>(device)) d->set_outer(outer); 7548 Device* d = Device::from<Device>(device);
7549 if (!d) return;
7550 // A caller passes what create_device_proxy returned, which is the proxy's DXGI pointer when the title asked
7551 // for IDXGIDevice1: the device's outer identity is the proxy itself either way.
7552 if (void* proxy = rt::d3d12_xs::device_proxy_primary(outer)) outer = static_cast<IUnknown*>(proxy);
7553 d->set_outer(outer);
7554 // Second job, for an outer that is the Xbox-ABI proxy: its IDXGIDevice1::GetAdapter (d3d12_xs_device.h) hands
7555 // out this layer's adapter, the one create_dxgi_factory enumerates, so a title on the Vulkan device never gets
7556 // a host DXGI object from it.
7557 if (!rt::d3d12_xs::is_device_proxy(outer)) return;
7558 rt::d3d12_xs::set_device_adapter_provider(outer, [](ID3D12Device* real, REFIID riid, void** out) {
7559 IDXGIFactory1* factory = nullptr;
7560 HRESULT hr = create_dxgi_factory(real, __uuidof(IDXGIFactory1), reinterpret_cast<void**>(&factory));
7561 if (FAILED(hr)) return hr;
7562 IDXGIAdapter* adapter = nullptr;
7563 hr = factory->EnumAdapters(0, &adapter);
7564 factory->Release();
7565 if (FAILED(hr)) return hr;
7566 hr = adapter->QueryInterface(riid, out);
7567 adapter->Release();
7568 return hr;
7569 });
7185} 7570}
7186 7571
7187const RootArgumentLayout* root_signature_layout(ID3D12RootSignature* signature) { 7572const RootArgumentLayout* root_signature_layout(ID3D12RootSignature* signature) {
@@ -7835,7 +8220,15 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) {
7835 q.pQueuePriorities = priorities.data(); 8220 q.pQueuePriorities = priorities.data();
7836 queue_infos.push_back(q); 8221 queue_infos.push_back(q);
7837 } 8222 }
7838 const auto picked = leonida::pick_queue_families(families, info.queue_family); 8223 const auto preferred = leonida::pick_queue_families(families, info.queue_family);
8224 // D3D12 permits UpdateTileMappings on DIRECT, COMPUTE and COPY queues. Vulkan requires
8225 // VK_QUEUE_SPARSE_BINDING_BIT on the VkQueue passed to vkQueueBindSparse. A dedicated
8226 // async family without that capability cannot implement all D3D12 queue operations;
8227 // fall back to the graphics family when sparse buffers are supported. QueueKind still
8228 // enforces the D3D12 COPY/COMPUTE stage restrictions on the more capable family.
8229 const bool sparse_buffers = chosen_features.sparseBinding && chosen_features.sparseResidencyBuffer &&
8230 chosen_features.sparseResidencyAliased;
8231 const auto picked = leonida::sparse_capable_queue_families(families, preferred, sparse_buffers);
7839 std::uint32_t compute_count = 0, copy_count = 0; 8232 std::uint32_t compute_count = 0, copy_count = 0;
7840 if (picked.compute != info.queue_family) { 8233 if (picked.compute != info.queue_family) {
7841 info.compute_family = picked.compute; 8234 info.compute_family = picked.compute;
diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp
index 3c3cf6724..31c91745f 100644
--- a/runtime/shims/d3d12_xs_device.cpp
+++ b/runtime/shims/d3d12_xs_device.cpp
@@ -26,8 +26,10 @@
26#endif 26#endif
27 27
28#include <windows.h> 28#include <windows.h>
29#include <dxgi1_4.h>
29 30
30#include <atomic> 31#include <atomic>
32#include <cstddef>
31#include <cstdint> 33#include <cstdint>
32#include <cstdio> 34#include <cstdio>
33#include <iterator> 35#include <iterator>
@@ -66,6 +68,11 @@ struct DeviceProxy {
66 // Set by create_device_proxy: false hands real (PC-shaped) lists back from CreateCommandList for callers 68 // Set by create_device_proxy: false hands real (PC-shaped) lists back from CreateCommandList for callers
67 // compiled against the PC headers. 69 // compiled against the PC headers.
68 bool console_lists = true; 70 bool console_lists = true;
71 // The device's IDXGIDevice1 (see "IDXGIDevice1 on the device" below): a title's IDXGIDevice1* points here.
72 void** dxgi_vtable;
73 DxgiAdapterProvider adapter_provider;
74 std::atomic<int> gpu_thread_priority;
75 std::atomic<unsigned> max_frame_latency;
69}; 76};
70 77
71// Freed in proxy_release; defined where the states are complete. 78// Freed in proxy_release; defined where the states are complete.
@@ -227,6 +234,12 @@ HRESULT proxy_query_interface(DeviceProxy* self, const IID* riid, void** out) {
227 proxy_add_ref(self); 234 proxy_add_ref(self);
228 return S_OK; 235 return S_OK;
229 } 236 }
237 if (IsEqualIID(*riid, __uuidof(IDXGIObject)) || IsEqualIID(*riid, __uuidof(IDXGIDevice)) ||
238 IsEqualIID(*riid, __uuidof(IDXGIDevice1))) {
239 *out = &self->dxgi_vtable;
240 proxy_add_ref(self);
241 return S_OK;
242 }
230 if (!is_device_iid(*riid)) return E_NOINTERFACE; 243 if (!is_device_iid(*riid)) return E_NOINTERFACE;
231 244
232 // Only claim an interface the PC device really implements; the proxy vtable covers its slots. 245 // Only claim an interface the PC device really implements; the proxy vtable covers its slots.
@@ -240,6 +253,142 @@ HRESULT proxy_query_interface(DeviceProxy* self, const IID* riid, void** out) {
240 return S_OK; 253 return S_OK;
241} 254}
242 255
256// ---- IDXGIDevice1 on the device ---------------------------------------------------------------------------------
257//
258// A GDKX title finds its output through the device: QueryInterface for IDXGIDevice1, GetAdapter, EnumOutputs(0),
259// and hands that output to SetFrameIntervalX (docs/d3d12_vulkan.md section 4.5, from the public samples). A PC
260// ID3D12Device has no IDXGIDevice, so the proxy answers it itself: a second vtable pointer inside the proxy object,
261// with the proxy's reference count and QueryInterface, so the two pointers are one COM object. Only IDXGIDevice and
262// IDXGIDevice1 are answered (what the samples ask for). The 14 slots are the public dxgi.h order; that the console
263// keeps it is the same assumption as for the queue and the fence.
264//
265// GetAdapter and GetParent hand out the adapter of the device behind the proxy. The provider says how: the default
266// asks the host's DXGI for the adapter with the device's LUID (the host backend); set_device_adapter_provider puts
267// the Vulkan layer's own adapter there, so that backend never loads the host's dxgi.dll for it.
268constexpr unsigned kDxgiDeviceSlots = 14; // IUnknown 3, IDXGIObject 4, IDXGIDevice 5, IDXGIDevice1 2
269
270DeviceProxy* dxgi_owner(void* self) {
271 return reinterpret_cast<DeviceProxy*>(static_cast<char*>(self) - offsetof(DeviceProxy, dxgi_vtable));
272}
273
274HRESULT host_adapter(ID3D12Device* real, REFIID riid, void** out) {
275 using CreateFactoryFn = HRESULT(WINAPI*)(REFIID, void**);
276 static const CreateFactoryFn create_factory = [] {
277 const HMODULE dxgi = LoadLibraryExA("dxgi.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
278 return dxgi ? reinterpret_cast<CreateFactoryFn>(
279 reinterpret_cast<void*>(GetProcAddress(dxgi, "CreateDXGIFactory1")))
280 : nullptr;
281 }();
282 if (!create_factory) return DXGI_ERROR_NOT_FOUND;
283 IDXGIFactory4* factory = nullptr;
284 HRESULT hr = create_factory(__uuidof(IDXGIFactory4), reinterpret_cast<void**>(&factory));
285 if (FAILED(hr) || !factory) return FAILED(hr) ? hr : DXGI_ERROR_NOT_FOUND;
286 hr = factory->EnumAdapterByLuid(real->GetAdapterLuid(), riid, out);
287 factory->Release();
288 return hr;
289}
290
291HRESULT dxgi_adapter(DeviceProxy* self, REFIID riid, void** out) {
292 if (!out) return E_POINTER;
293 *out = nullptr;
294 const DxgiAdapterProvider provider = self->adapter_provider ? self->adapter_provider : &host_adapter;
295 const HRESULT hr = provider(self->real, riid, out);
296 if (FAILED(hr)) *out = nullptr;
297 return hr;
298}
299
300void note_dxgi(const char* method) {
301 d3d12_trace::record(method);
302}
303
304HRESULT WINAPI dxgi_query_interface(void* self, const IID* riid, void** out) {
305 return proxy_query_interface(dxgi_owner(self), riid, out);
306}
307ULONG WINAPI dxgi_add_ref(void* self) { return proxy_add_ref(dxgi_owner(self)); }
308ULONG WINAPI dxgi_release(void* self) { return proxy_release(dxgi_owner(self)); }
309
310// IDXGIObject's private data is the device's: ID3D12Object has the same three methods with the same arguments.
311HRESULT WINAPI dxgi_set_private_data(void* self, const GUID* name, UINT size, const void* data) {
312 if (!name) return E_INVALIDARG;
313 return dxgi_owner(self)->real->SetPrivateData(*name, size, data);
314}
315HRESULT WINAPI dxgi_set_private_data_interface(void* self, const GUID* name, const IUnknown* object) {
316 if (!name) return E_INVALIDARG;
317 return dxgi_owner(self)->real->SetPrivateDataInterface(*name, object);
318}
319HRESULT WINAPI dxgi_get_private_data(void* self, const GUID* name, UINT* size, void* data) {
320 if (!name) return E_INVALIDARG;
321 return dxgi_owner(self)->real->GetPrivateData(*name, size, data);
322}
323HRESULT WINAPI dxgi_get_parent(void* self, const IID* riid, void** out) {
324 note_dxgi("XboxIDXGIDevice::GetParent");
325 if (!riid) return E_POINTER;
326 return dxgi_adapter(dxgi_owner(self), *riid, out);
327}
328HRESULT WINAPI dxgi_get_adapter(void* self, IDXGIAdapter** out) {
329 note_dxgi("XboxIDXGIDevice::GetAdapter");
330 return dxgi_adapter(dxgi_owner(self), __uuidof(IDXGIAdapter), reinterpret_cast<void**>(out));
331}
332// CreateSurface and QueryResourceResidency are D3D10/11-era methods no D3D12 title has a use for; what the console
333// answers is not measured, so they are refused and say so once.
334HRESULT WINAPI dxgi_create_surface(void*, const DXGI_SURFACE_DESC*, UINT, DXGI_USAGE, const DXGI_SHARED_RESOURCE*,
335 IDXGISurface** out) {
336 static std::atomic<bool> logged{false};
337 if (!logged.exchange(true, std::memory_order_relaxed))
338 std::fprintf(stderr, "[rt] d3d12_xs: IDXGIDevice::CreateSurface is not implemented; returning E_NOTIMPL\n");
339 if (out) *out = nullptr;
340 return E_NOTIMPL;
341}
342HRESULT WINAPI dxgi_query_resource_residency(void*, IUnknown* const*, DXGI_RESIDENCY*, UINT) {
343 static std::atomic<bool> logged{false};
344 if (!logged.exchange(true, std::memory_order_relaxed))
345 std::fprintf(stderr,
346 "[rt] d3d12_xs: IDXGIDevice::QueryResourceResidency is not implemented; returning E_NOTIMPL\n");
347 return E_NOTIMPL;
348}
349// The priority and the frame latency are kept and read back; nothing acts on them (the Xbox presenter's latency is
350// SetFrameIntervalX's). The ranges are the documented ones: -7..7, and 1..16 with 0 for the default of 3.
351HRESULT WINAPI dxgi_set_gpu_thread_priority(void* self, INT priority) {
352 if (priority < -7 || priority > 7) return E_INVALIDARG;
353 dxgi_owner(self)->gpu_thread_priority.store(priority, std::memory_order_relaxed);
354 return S_OK;
355}
356HRESULT WINAPI dxgi_get_gpu_thread_priority(void* self, INT* priority) {
357 if (!priority) return E_POINTER;
358 *priority = dxgi_owner(self)->gpu_thread_priority.load(std::memory_order_relaxed);
359 return S_OK;
360}
361HRESULT WINAPI dxgi_set_maximum_frame_latency(void* self, UINT latency) {
362 if (latency > 16) return DXGI_ERROR_INVALID_CALL;
363 dxgi_owner(self)->max_frame_latency.store(latency ? latency : 3, std::memory_order_relaxed);
364 return S_OK;
365}
366HRESULT WINAPI dxgi_get_maximum_frame_latency(void* self, UINT* latency) {
367 if (!latency) return E_POINTER;
368 *latency = dxgi_owner(self)->max_frame_latency.load(std::memory_order_relaxed);
369 return S_OK;
370}
371
372void** get_dxgi_vtable() {
373 static void* table[kDxgiDeviceSlots] = {
374 reinterpret_cast<void*>(&dxgi_query_interface), // 0
375 reinterpret_cast<void*>(&dxgi_add_ref), // 1
376 reinterpret_cast<void*>(&dxgi_release), // 2
377 reinterpret_cast<void*>(&dxgi_set_private_data), // 3 IDXGIObject
378 reinterpret_cast<void*>(&dxgi_set_private_data_interface),
379 reinterpret_cast<void*>(&dxgi_get_private_data),
380 reinterpret_cast<void*>(&dxgi_get_parent),
381 reinterpret_cast<void*>(&dxgi_get_adapter), // 7 IDXGIDevice
382 reinterpret_cast<void*>(&dxgi_create_surface),
383 reinterpret_cast<void*>(&dxgi_query_resource_residency),
384 reinterpret_cast<void*>(&dxgi_set_gpu_thread_priority),
385 reinterpret_cast<void*>(&dxgi_get_gpu_thread_priority),
386 reinterpret_cast<void*>(&dxgi_set_maximum_frame_latency), // 12 IDXGIDevice1
387 reinterpret_cast<void*>(&dxgi_get_maximum_frame_latency),
388 };
389 return table;
390}
391
243unsigned long heap_add_ref(HeapProxy* self) { 392unsigned long heap_add_ref(HeapProxy* self) {
244 note_heap_slot(1); 393 note_heap_slot(1);
245 return self->refs.fetch_add(1, std::memory_order_relaxed) + 1; 394 return self->refs.fetch_add(1, std::memory_order_relaxed) + 1;
@@ -1984,6 +2133,10 @@ HRESULT create_device_proxy(ID3D12Device* real, REFIID riid, void** out, bool co
1984 proxy->slot_count = detect_slot_count(real); 2133 proxy->slot_count = detect_slot_count(real);
1985 proxy->console_lists = console_lists; 2134 proxy->console_lists = console_lists;
1986 proxy->refs.store(1, std::memory_order_relaxed); 2135 proxy->refs.store(1, std::memory_order_relaxed);
2136 proxy->dxgi_vtable = get_dxgi_vtable();
2137 proxy->adapter_provider = nullptr;
2138 proxy->gpu_thread_priority.store(0, std::memory_order_relaxed);
2139 proxy->max_frame_latency.store(3, std::memory_order_relaxed);
1987 2140
1988 const unsigned slot_count = proxy->slot_count; 2141 const unsigned slot_count = proxy->slot_count;
1989 HRESULT hr = proxy_query_interface(proxy, &riid, out); 2142 HRESULT hr = proxy_query_interface(proxy, &riid, out);
@@ -2003,6 +2156,28 @@ bool is_device_proxy(const void* device) {
2003 return device && *reinterpret_cast<void* const*>(device) == reinterpret_cast<void*>(get_vtable()); 2156 return device && *reinterpret_cast<void* const*>(device) == reinterpret_cast<void*>(get_vtable());
2004} 2157}
2005 2158
2159void* device_proxy_from_dxgi_device(void* dxgi_device) {
2160 if (!dxgi_device || *static_cast<void***>(dxgi_device) != get_dxgi_vtable()) return nullptr;
2161 return dxgi_owner(dxgi_device);
2162}
2163
2164void* device_proxy_primary(void* device) {
2165 if (is_device_proxy(device)) return device;
2166 return device_proxy_from_dxgi_device(device);
2167}
2168
2169bool set_device_adapter_provider(void* device, DxgiAdapterProvider provider) {
2170 auto* proxy = static_cast<DeviceProxy*>(device_proxy_primary(device));
2171 if (!proxy) {
2172 // Not installing one silently would leave the host's adapter in its place.
2173 std::fprintf(stderr, "[rt] d3d12_xs: set_device_adapter_provider: %p is not a device proxy; no provider set\n",
2174 device);
2175 return false;
2176 }
2177 proxy->adapter_provider = provider;
2178 return true;
2179}
2180
2006bool is_heap_proxy(const void* heap) { 2181bool is_heap_proxy(const void* heap) {
2007 return heap && *reinterpret_cast<void* const*>(heap) == reinterpret_cast<void*>(get_heap_vtable()); 2182 return heap && *reinterpret_cast<void* const*>(heap) == reinterpret_cast<void*>(get_heap_vtable());
2008} 2183}
diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h
index 76bbf5377..ed5d33ada 100644
--- a/runtime/shims/d3d12_xs_device.h
+++ b/runtime/shims/d3d12_xs_device.h
@@ -61,6 +61,24 @@ HRESULT create_device_proxy(ID3D12Device* real, REFIID riid, void** out, bool co
61// True when `device` points at a proxy created by create_device_proxy. Used by the tests. 61// True when `device` points at a proxy created by create_device_proxy. Used by the tests.
62bool is_device_proxy(const void* device); 62bool is_device_proxy(const void* device);
63 63
64// IDXGIDevice1 on the device. A GDKX title asks its device for IDXGIDevice1, then GetAdapter and EnumOutputs(0),
65// to find the output it gives SetFrameIntervalX (docs/d3d12_vulkan.md section 4.5). The proxy answers IDXGIObject,
66// IDXGIDevice and IDXGIDevice1 itself, as one COM object with the device (same reference count, QueryInterface
67// both ways). GetAdapter and GetParent return the adapter of the device behind the proxy: by default the host DXGI
68// adapter with that device's LUID. A provider replaces that: `real` is the device behind the proxy, and it returns
69// the adapter as `riid`. rt::d3d12::set_device_outer sets one for the Vulkan-backed device (the layer's own adapter).
70//
71// A title may ask D3D12XboxCreateDevice (so create_device_proxy) for IDXGIDevice1 directly. What comes back then is
72// the proxy's DXGI pointer, not the proxy: is_device_proxy is false for it. Code that takes "the proxy" from a
73// creation call goes through device_proxy_primary first.
74using DxgiAdapterProvider = HRESULT (*)(ID3D12Device* real, REFIID riid, void** out);
75// `device` is the proxy or its DXGI pointer. False, with a line on stderr, when it is neither: nothing is set then.
76bool set_device_adapter_provider(void* device, DxgiAdapterProvider provider);
77// The device proxy an IDXGIDevice pointer handed out by one belongs to, or null.
78void* device_proxy_from_dxgi_device(void* dxgi_device);
79// The device proxy itself, given the proxy or its DXGI pointer; null for anything else.
80void* device_proxy_primary(void* device);
81
64// True when `heap` is a descriptor-heap proxy created by device slot 14. 82// True when `heap` is a descriptor-heap proxy created by device slot 14.
65bool is_heap_proxy(const void* heap); 83bool is_heap_proxy(const void* heap);
66ID3D12DescriptorHeap* heap_proxy_real_heap(const void* heap); 84ID3D12DescriptorHeap* heap_proxy_real_heap(const void* heap);
diff --git a/runtime/shims/dxgi_com.cpp b/runtime/shims/dxgi_com.cpp
index 734824e07..54aa57991 100644
--- a/runtime/shims/dxgi_com.cpp
+++ b/runtime/shims/dxgi_com.cpp
@@ -3,6 +3,7 @@
3 3
4#include <algorithm> 4#include <algorithm>
5#include <atomic> 5#include <atomic>
6#include <cstdint>
6#include <cstdio> 7#include <cstdio>
7#include <cstring> 8#include <cstring>
8#include <map> 9#include <map>
@@ -26,6 +27,90 @@ void stub(const char* method) {
26 if (seen.insert(method).second) std::fprintf(stderr, "[rt] dxgi: unimplemented %s\n", method); 27 if (seen.insert(method).second) std::fprintf(stderr, "[rt] dxgi: unimplemented %s\n", method);
27} 28}
28 29
30// IDXGIObject private data, shared by the factory, adapter and swapchain. SetPrivateData keeps a copy of the bytes;
31// SetPrivateDataInterface holds one reference until the entry is replaced, removed or the owner dies (Microsoft:
32// IDXGIObject::SetPrivateDataInterface). Zero bytes remove the entry. GetPrivateData gives an interface back with a
33// reference added, and a buffer too small for the entry gets DXGI_ERROR_MORE_DATA and the size to retry with.
34class PrivateDataStore {
35public:
36 PrivateDataStore() = default;
37 PrivateDataStore(const PrivateDataStore&) = delete;
38 PrivateDataStore& operator=(const PrivateDataStore&) = delete;
39 ~PrivateDataStore() {
40 for (auto& entry : data_)
41 if (entry.object) entry.object->Release();
42 }
43
44 HRESULT get(REFGUID guid, UINT* size, void* data) {
45 if (!size) return E_INVALIDARG;
46 std::lock_guard lock(mutex_);
47 for (const auto& entry : data_) {
48 if (entry.key != guid) continue;
49 const UINT bytes = entry.object ? UINT(sizeof(IUnknown*)) : UINT(entry.bytes.size());
50 if (data && *size < bytes) {
51 *size = bytes;
52 return DXGI_ERROR_MORE_DATA;
53 }
54 if (data) {
55 if (entry.object) {
56 entry.object->AddRef();
57 std::memcpy(data, &entry.object, sizeof(IUnknown*));
58 } else {
59 std::memcpy(data, entry.bytes.data(), bytes);
60 }
61 }
62 *size = bytes;
63 return S_OK;
64 }
65 *size = 0;
66 return DXGI_ERROR_NOT_FOUND;
67 }
68
69 HRESULT set(REFGUID guid, UINT size, const void* data) {
70 if (size && !data) return E_INVALIDARG;
71 Entry entry{guid, {}, nullptr};
72 if (size) {
73 const auto* bytes = static_cast<const std::uint8_t*>(data);
74 entry.bytes.assign(bytes, bytes + size);
75 }
76 store(std::move(entry), size != 0);
77 return S_OK;
78 }
79
80 HRESULT set_interface(REFGUID guid, const IUnknown* object) {
81 IUnknown* held = const_cast<IUnknown*>(object);
82 if (held) held->AddRef();
83 store(Entry{guid, {}, held}, held != nullptr);
84 return S_OK;
85 }
86
87private:
88 struct Entry {
89 GUID key;
90 std::vector<std::uint8_t> bytes;
91 IUnknown* object;
92 };
93
94 // The replaced interface is released after the lock is dropped, since its Release may run arbitrary code.
95 void store(Entry entry, bool keep) {
96 IUnknown* released = nullptr;
97 {
98 std::lock_guard lock(mutex_);
99 for (auto it = data_.begin(); it != data_.end(); ++it) {
100 if (it->key != entry.key) continue;
101 released = it->object;
102 data_.erase(it);
103 break;
104 }
105 if (keep) data_.push_back(std::move(entry));
106 }
107 if (released) released->Release();
108 }
109
110 std::mutex mutex_;
111 std::vector<Entry> data_;
112};
113
29bool valid_flip_buffer_count(UINT count) { 114bool valid_flip_buffer_count(UINT count) {
30 return count >= 2 && count <= DXGI_MAX_SWAP_CHAIN_BUFFERS; 115 return count >= 2 && count <= DXGI_MAX_SWAP_CHAIN_BUFFERS;
31} 116}
@@ -177,9 +262,15 @@ public:
177 } 262 }
178 263
179 // IDXGIObject 264 // IDXGIObject
180 HRESULT STDMETHODCALLTYPE SetPrivateData(REFGUID, UINT, const void*) override { return S_OK; } 265 HRESULT STDMETHODCALLTYPE SetPrivateData(REFGUID guid, UINT size, const void* data) override {
181 HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(REFGUID, const IUnknown*) override { return S_OK; } 266 return private_data_.set(guid, size, data);
182 HRESULT STDMETHODCALLTYPE GetPrivateData(REFGUID, UINT*, void*) override { return DXGI_ERROR_NOT_FOUND; } 267 }
268 HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(REFGUID guid, const IUnknown* object) override {
269 return private_data_.set_interface(guid, object);
270 }
271 HRESULT STDMETHODCALLTYPE GetPrivateData(REFGUID guid, UINT* size, void* data) override {
272 return private_data_.get(guid, size, data);
273 }
183 HRESULT STDMETHODCALLTYPE GetParent(REFIID riid, void** out) override { 274 HRESULT STDMETHODCALLTYPE GetParent(REFIID riid, void** out) override {
184 if (!out) return E_POINTER; 275 if (!out) return E_POINTER;
185 *out = nullptr; 276 *out = nullptr;
@@ -481,6 +572,7 @@ private:
481 } 572 }
482 573
483 std::atomic<ULONG> refs_{1}; 574 std::atomic<ULONG> refs_{1};
575 PrivateDataStore private_data_;
484 IDXGIFactory4* parent_ = nullptr; 576 IDXGIFactory4* parent_ = nullptr;
485 IUnknown* device_ = nullptr; 577 IUnknown* device_ = nullptr;
486 leonida::VulkanContext& context_; 578 leonida::VulkanContext& context_;
@@ -573,9 +665,15 @@ public:
573 } 665 }
574 666
575 // IDXGIObject 667 // IDXGIObject
576 HRESULT STDMETHODCALLTYPE SetPrivateData(REFGUID, UINT, const void*) override { return S_OK; } 668 HRESULT STDMETHODCALLTYPE SetPrivateData(REFGUID guid, UINT size, const void* data) override {
577 HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(REFGUID, const IUnknown*) override { return S_OK; } 669 return private_data_.set(guid, size, data);
578 HRESULT STDMETHODCALLTYPE GetPrivateData(REFGUID, UINT*, void*) override { return DXGI_ERROR_NOT_FOUND; } 670 }
671 HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(REFGUID guid, const IUnknown* object) override {
672 return private_data_.set_interface(guid, object);
673 }
674 HRESULT STDMETHODCALLTYPE GetPrivateData(REFGUID guid, UINT* size, void* data) override {
675 return private_data_.get(guid, size, data);
676 }
579 HRESULT STDMETHODCALLTYPE GetParent(REFIID riid, void** out) override { 677 HRESULT STDMETHODCALLTYPE GetParent(REFIID riid, void** out) override {
580 if (!out) return E_POINTER; 678 if (!out) return E_POINTER;
581 *out = nullptr; 679 *out = nullptr;
@@ -767,6 +865,7 @@ private:
767 865
768 std::atomic<DWORD> next_budget_cookie_{1}; 866 std::atomic<DWORD> next_budget_cookie_{1};
769 std::atomic<ULONG> refs_{1}; 867 std::atomic<ULONG> refs_{1};
868 PrivateDataStore private_data_;
770 IDXGIFactory4* parent_ = nullptr; 869 IDXGIFactory4* parent_ = nullptr;
771 PFN_vkGetInstanceProcAddr gipa_ = nullptr; 870 PFN_vkGetInstanceProcAddr gipa_ = nullptr;
772 VkInstance instance_ = VK_NULL_HANDLE; 871 VkInstance instance_ = VK_NULL_HANDLE;
@@ -805,9 +904,15 @@ public:
805 } 904 }
806 905
807 // IDXGIObject 906 // IDXGIObject
808 HRESULT STDMETHODCALLTYPE SetPrivateData(REFGUID, UINT, const void*) override { return S_OK; } 907 HRESULT STDMETHODCALLTYPE SetPrivateData(REFGUID guid, UINT size, const void* data) override {
809 HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(REFGUID, const IUnknown*) override { return S_OK; } 908 return private_data_.set(guid, size, data);
810 HRESULT STDMETHODCALLTYPE GetPrivateData(REFGUID, UINT*, void*) override { return DXGI_ERROR_NOT_FOUND; } 909 }
910 HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(REFGUID guid, const IUnknown* object) override {
911 return private_data_.set_interface(guid, object);
912 }
913 HRESULT STDMETHODCALLTYPE GetPrivateData(REFGUID guid, UINT* size, void* data) override {
914 return private_data_.get(guid, size, data);
915 }
811 HRESULT STDMETHODCALLTYPE GetParent(REFIID, void** out) override { 916 HRESULT STDMETHODCALLTYPE GetParent(REFIID, void** out) override {
812 if (!out) return E_POINTER; 917 if (!out) return E_POINTER;
813 *out = nullptr; 918 *out = nullptr;
@@ -883,6 +988,49 @@ public:
883 HRESULT STDMETHODCALLTYPE CreateSwapChainForHwnd(IUnknown* device, HWND hwnd, const DXGI_SWAP_CHAIN_DESC1* desc, 988 HRESULT STDMETHODCALLTYPE CreateSwapChainForHwnd(IUnknown* device, HWND hwnd, const DXGI_SWAP_CHAIN_DESC1* desc,
884 const DXGI_SWAP_CHAIN_FULLSCREEN_DESC*, IDXGIOutput* restrict_to_output, 989 const DXGI_SWAP_CHAIN_FULLSCREEN_DESC*, IDXGIOutput* restrict_to_output,
885 IDXGISwapChain1** out) override { 990 IDXGISwapChain1** out) override {
991 if (out) *out = nullptr;
992 if (const HRESULT hr = check_hwnd_swap_chain(device, hwnd, desc, out); FAILED(hr)) return hr;
993 return create_swap_chain(device, hwnd, desc, restrict_to_output, out);
994 }
995
996 // What the host runtime's DXGI refuses for a D3D12 swap chain on a window (dxgi_swapchain_test compares these,
997 // RTX 5070 / 621.14): a null queue, window, description or output, an ID3D12Device in place of the queue, the
998 // bitblt effects, a scaling or alpha mode a window can't present, a flag outside the ones a D3D12 window swap chain
999 // takes (MODE_SWITCH, DISPLAY_ONLY, FRAME_LATENCY_WAITABLE_OBJECT, ALLOW_TEARING, the holographic restriction and
1000 // 0x2000), a shared, read-only, discard-on-present or unordered-access buffer usage, MSAA, a buffer count outside
1001 // 2..16 and a format the swap chain can't take are DXGI_ERROR_INVALID_CALL; a side above 16384 is E_INVALIDARG,
1002 // only when nothing else is wrong.
1003 static HRESULT check_hwnd_swap_chain(IUnknown* device, HWND hwnd, const DXGI_SWAP_CHAIN_DESC1* desc,
1004 IDXGISwapChain1** out) {
1005 if (!device || !hwnd || !desc || !out) return DXGI_ERROR_INVALID_CALL;
1006 ID3D12CommandQueue* queue = nullptr;
1007 if (FAILED(device->QueryInterface(IID_PPV_ARGS(&queue))) || !queue) return DXGI_ERROR_INVALID_CALL;
1008 queue->Release();
1009 if (desc->SwapEffect != DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL && desc->SwapEffect != DXGI_SWAP_EFFECT_FLIP_DISCARD)
1010 return DXGI_ERROR_INVALID_CALL;
1011 if (desc->Scaling != DXGI_SCALING_STRETCH && desc->Scaling != DXGI_SCALING_NONE) return DXGI_ERROR_INVALID_CALL;
1012 if (desc->AlphaMode != DXGI_ALPHA_MODE_UNSPECIFIED && desc->AlphaMode != DXGI_ALPHA_MODE_IGNORE)
1013 return DXGI_ERROR_INVALID_CALL;
1014 constexpr UINT kWindowFlags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH | DXGI_SWAP_CHAIN_FLAG_DISPLAY_ONLY |
1015 DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT |
1016 DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING | 0x1000u | 0x2000u;
1017 if (desc->Flags & ~kWindowFlags) return DXGI_ERROR_INVALID_CALL;
1018 constexpr DXGI_USAGE kRefusedUsage =
1019 DXGI_USAGE_SHARED | DXGI_USAGE_READ_ONLY | DXGI_USAGE_DISCARD_ON_PRESENT | DXGI_USAGE_UNORDERED_ACCESS;
1020 if (desc->BufferUsage & kRefusedUsage) return DXGI_ERROR_INVALID_CALL;
1021 // The host checks these before the size: MSAA 4 or one buffer at width 16385 is still INVALID_CALL.
1022 if (desc->SampleDesc.Count != 1 || desc->SampleDesc.Quality != 0) return DXGI_ERROR_INVALID_CALL;
1023 if (!valid_flip_buffer_count(desc->BufferCount)) return DXGI_ERROR_INVALID_CALL;
1024 if (dxgi_to_vk_format(desc->Format) == VK_FORMAT_UNDEFINED) return DXGI_ERROR_INVALID_CALL;
1025 if (desc->Width > D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION || desc->Height > D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION)
1026 return E_INVALIDARG;
1027 return S_OK;
1028 }
1029
1030 // The swap chain itself, for a window or (through its HWND) a CoreWindow. The CoreWindow path keeps only these
1031 // checks: the host's rules for it (ASPECT_RATIO_STRETCH, for one) can't be compared without a real CoreWindow.
1032 HRESULT create_swap_chain(IUnknown* device, HWND hwnd, const DXGI_SWAP_CHAIN_DESC1* desc,
1033 IDXGIOutput* restrict_to_output, IDXGISwapChain1** out) {
886 if (!out) return E_POINTER; 1034 if (!out) return E_POINTER;
887 *out = nullptr; 1035 *out = nullptr;
888 if (!hwnd || !desc) return E_INVALIDARG; 1036 if (!hwnd || !desc) return E_INVALIDARG;
@@ -922,7 +1070,7 @@ public:
922 const HRESULT hr = interop->get_WindowHandle(&hwnd); 1070 const HRESULT hr = interop->get_WindowHandle(&hwnd);
923 interop->Release(); 1071 interop->Release();
924 if (FAILED(hr) || !hwnd) return DXGI_ERROR_INVALID_CALL; 1072 if (FAILED(hr) || !hwnd) return DXGI_ERROR_INVALID_CALL;
925 return CreateSwapChainForHwnd(device, hwnd, desc, nullptr, restrict_to_output, out); 1073 return create_swap_chain(device, hwnd, desc, restrict_to_output, out);
926 } 1074 }
927 HRESULT STDMETHODCALLTYPE GetSharedResourceAdapterLuid(HANDLE, LUID*) override { return E_NOTIMPL; } 1075 HRESULT STDMETHODCALLTYPE GetSharedResourceAdapterLuid(HANDLE, LUID*) override { return E_NOTIMPL; }
928 HRESULT STDMETHODCALLTYPE RegisterStereoStatusWindow(HWND, UINT, DWORD*) override { return E_NOTIMPL; } 1076 HRESULT STDMETHODCALLTYPE RegisterStereoStatusWindow(HWND, UINT, DWORD*) override { return E_NOTIMPL; }
@@ -1047,6 +1195,7 @@ private:
1047 } 1195 }
1048 1196
1049 std::atomic<ULONG> refs_{1}; 1197 std::atomic<ULONG> refs_{1};
1198 PrivateDataStore private_data_;
1050 leonida::VulkanContext& context_; 1199 leonida::VulkanContext& context_;
1051 PFN_vkGetInstanceProcAddr gipa_; 1200 PFN_vkGetInstanceProcAddr gipa_;
1052 VkInstance instance_; 1201 VkInstance instance_;
diff --git a/runtime/shims/dxgi_swapchain.h b/runtime/shims/dxgi_swapchain.h
index 6c6684a66..531a49f28 100644
--- a/runtime/shims/dxgi_swapchain.h
+++ b/runtime/shims/dxgi_swapchain.h
@@ -166,7 +166,7 @@ public:
166 } 166 }
167 allow_tearing_ = allow_tearing; 167 allow_tearing_ = allow_tearing;
168 const VkFormat fmt = (preferred_format != VK_FORMAT_UNDEFINED) ? preferred_format : format_; 168 const VkFormat fmt = (preferred_format != VK_FORMAT_UNDEFINED) ? preferred_format : format_;
169 const std::uint32_t count = buffer_count ? buffer_count : static_cast<std::uint32_t>(images_.size()); 169 const std::uint32_t count = buffer_count ? buffer_count : exposed_count_;
170 return rebuild(width, height, fmt, count ? count : 2u); 170 return rebuild(width, height, fmt, count ? count : 2u);
171 } 171 }
172 172
@@ -177,11 +177,21 @@ public:
177 &out_index); 177 &out_index);
178 if (r != VK_SUCCESS && r != VK_SUBOPTIMAL_KHR) return false; 178 if (r != VK_SUCCESS && r != VK_SUBOPTIMAL_KHR) return false;
179 if (fn_.wait_for_fences(device_, 1, &acquire_fence_, VK_TRUE, timeout_ns) != VK_SUCCESS) return false; 179 if (fn_.wait_for_fences(device_, 1, &acquire_fence_, VK_TRUE, timeout_ns) != VK_SUCCESS) return false;
180 current_index_ = out_index; 180 acquired_index_ = out_index;
181 if (is_offscreen()) {
182 // The native image count may differ from the DXGI BufferCount (Vulkan is free to return more
183 // images than minImageCount, and caps.minImageCount can exceed the app's request). The app's
184 // backbuffers are the stable offscreen ring; each present blits the current slot into whichever
185 // native image was acquired, so the exposed index never follows the native one.
186 current_index_ = next_back_buffer_;
187 next_back_buffer_ = (next_back_buffer_ + 1) % exposed_count_;
188 } else {
189 current_index_ = out_index;
190 }
181 // D3D12 swapchain backbuffers begin in D3D12_RESOURCE_STATE_PRESENT; transition each newly acquired 191 // D3D12 swapchain backbuffers begin in D3D12_RESOURCE_STATE_PRESENT; transition each newly acquired
182 // native swapchain image once from UNDEFINED -> PRESENT_SRC_KHR so presenting an untouched backbuffer 192 // native swapchain image once from UNDEFINED -> PRESENT_SRC_KHR so presenting an untouched backbuffer
183 // or transitioning from PRESENT matches the tracked layout. 193 // or transitioning from PRESENT matches the tracked layout.
184 if (offscreen_images_.empty() && out_index < image_initialized_.size() && !image_initialized_[out_index]) { 194 if (!is_offscreen() && out_index < image_initialized_.size() && !image_initialized_[out_index]) {
185 if (!transition_image_layout(images_[out_index], VK_IMAGE_LAYOUT_UNDEFINED, 195 if (!transition_image_layout(images_[out_index], VK_IMAGE_LAYOUT_UNDEFINED,
186 VK_IMAGE_LAYOUT_PRESENT_SRC_KHR)) 196 VK_IMAGE_LAYOUT_PRESENT_SRC_KHR))
187 return false; 197 return false;
@@ -190,10 +200,12 @@ public:
190 return true; 200 return true;
191 } 201 }
192 202
193 bool present(std::uint32_t image_index) { 203 bool present(std::uint32_t back_buffer_index) {
194 if (!swapchain_ || image_index >= images_.size()) return false; 204 if (!swapchain_ || back_buffer_index >= exposed_count_ || acquired_index_ >= images_.size()) return false;
195 if (!offscreen_images_.empty()) { 205 std::uint32_t image_index = back_buffer_index;
196 if (!blit_to_swapchain(image_index)) return false; 206 if (is_offscreen()) {
207 if (!blit_to_swapchain(back_buffer_index)) return false;
208 image_index = acquired_index_;
197 } 209 }
198 VkPresentInfoKHR pi{VK_STRUCTURE_TYPE_PRESENT_INFO_KHR}; 210 VkPresentInfoKHR pi{VK_STRUCTURE_TYPE_PRESENT_INFO_KHR};
199 pi.swapchainCount = 1; 211 pi.swapchainCount = 1;
@@ -204,21 +216,24 @@ public:
204 return r == VK_SUCCESS || r == VK_SUBOPTIMAL_KHR; 216 return r == VK_SUCCESS || r == VK_SUBOPTIMAL_KHR;
205 } 217 }
206 218
207 std::uint32_t image_count() const { return static_cast<std::uint32_t>(images_.size()); } 219 // DXGI exposes exactly the BufferCount the app asked for (GetDesc/GetDesc1 and GetCurrentBackBufferIndex
220 // stay inside it). When Vulkan supplies a different number of native images the extra ones are hidden
221 // behind a stable offscreen ring (is_offscreen()).
222 std::uint32_t image_count() const { return exposed_count_; }
208 std::uint32_t current_back_buffer_index() const { return current_index_; } 223 std::uint32_t current_back_buffer_index() const { return current_index_; }
209 VkFormat format() const { return format_; } 224 VkFormat format() const { return format_; }
210 VkExtent2D extent() const { return extent_; } 225 VkExtent2D extent() const { return extent_; }
211 bool is_offscreen() const { return !offscreen_images_.empty(); } 226 bool is_offscreen() const { return !offscreen_images_.empty(); }
212 VkPresentModeKHR present_mode() const { return present_mode_; } 227 VkPresentModeKHR present_mode() const { return present_mode_; }
213 VkImage image(std::uint32_t i) const { 228 VkImage image(std::uint32_t i) const {
214 if (i >= images_.size()) return VK_NULL_HANDLE; 229 if (i >= exposed_count_) return VK_NULL_HANDLE;
215 return !offscreen_images_.empty() ? offscreen_images_[i] : images_[i]; 230 return is_offscreen() ? offscreen_images_[i] : images_[i];
216 } 231 }
217 232
218 ResourceBinding resource_binding(std::uint32_t i) const { 233 ResourceBinding resource_binding(std::uint32_t i) const {
219 ResourceBinding b{}; 234 ResourceBinding b{};
220 if (i >= images_.size()) return b; 235 if (i >= exposed_count_) return b;
221 const bool offscreen = !offscreen_images_.empty(); 236 const bool offscreen = is_offscreen();
222 b.image = offscreen ? offscreen_images_[i] : images_[i]; 237 b.image = offscreen ? offscreen_images_[i] : images_[i];
223 b.format = format_; 238 b.format = format_;
224 b.aspects = VK_IMAGE_ASPECT_COLOR_BIT; 239 b.aspects = VK_IMAGE_ASPECT_COLOR_BIT;
@@ -280,6 +295,7 @@ private:
280 } 295 }
281 } 296 }
282 images_.clear(); 297 images_.clear();
298 exposed_count_ = 0;
283 } 299 }
284 300
285 bool create_offscreen_backbuffers(std::uint32_t count) { 301 bool create_offscreen_backbuffers(std::uint32_t count) {
@@ -383,7 +399,10 @@ private:
383 } 399 }
384 400
385 bool blit_to_swapchain(std::uint32_t image_index) { 401 bool blit_to_swapchain(std::uint32_t image_index) {
386 if (!blit_cmd_ || !blit_fence_ || image_index >= offscreen_images_.size()) return false; 402 if (!blit_cmd_ || !blit_fence_ || image_index >= offscreen_images_.size() ||
403 acquired_index_ >= images_.size())
404 return false;
405 const VkImage dst_image = images_[acquired_index_];
387 std::lock_guard lock(submit_mutex_); 406 std::lock_guard lock(submit_mutex_);
388 if (fn_.reset_fences(device_, 1, &blit_fence_) != VK_SUCCESS) return false; 407 if (fn_.reset_fences(device_, 1, &blit_fence_) != VK_SUCCESS) return false;
389 if (fn_.reset_cmd_buf(blit_cmd_, 0) != VK_SUCCESS) return false; 408 if (fn_.reset_cmd_buf(blit_cmd_, 0) != VK_SUCCESS) return false;
@@ -409,7 +428,7 @@ private:
409 pre[1].newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; 428 pre[1].newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
410 pre[1].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; 429 pre[1].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
411 pre[1].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; 430 pre[1].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
412 pre[1].image = images_[image_index]; 431 pre[1].image = dst_image;
413 pre[1].subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; 432 pre[1].subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
414 433
415 fn_.cmd_barrier(blit_cmd_, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 434 fn_.cmd_barrier(blit_cmd_, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr,
@@ -422,7 +441,7 @@ private:
422 region.dstOffsets[1] = {static_cast<std::int32_t>(surface_extent_.width), 441 region.dstOffsets[1] = {static_cast<std::int32_t>(surface_extent_.width),
423 static_cast<std::int32_t>(surface_extent_.height), 1}; 442 static_cast<std::int32_t>(surface_extent_.height), 1};
424 fn_.cmd_blit(blit_cmd_, offscreen_images_[image_index], VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, 443 fn_.cmd_blit(blit_cmd_, offscreen_images_[image_index], VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
425 images_[image_index], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &region, VK_FILTER_LINEAR); 444 dst_image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &region, VK_FILTER_LINEAR);
426 445
427 VkImageMemoryBarrier post[2]{}; 446 VkImageMemoryBarrier post[2]{};
428 post[0].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; 447 post[0].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
@@ -442,7 +461,7 @@ private:
442 post[1].newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; 461 post[1].newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
443 post[1].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; 462 post[1].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
444 post[1].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; 463 post[1].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
445 post[1].image = images_[image_index]; 464 post[1].image = dst_image;
446 post[1].subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; 465 post[1].subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
447 466
448 fn_.cmd_barrier(blit_cmd_, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 0, nullptr, 467 fn_.cmd_barrier(blit_cmd_, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 0, nullptr,
@@ -532,15 +551,27 @@ private:
532 551
533 std::uint32_t img_count = 0; 552 std::uint32_t img_count = 0;
534 fn_.get_images(device_, swapchain_, &img_count, nullptr); 553 fn_.get_images(device_, swapchain_, &img_count, nullptr);
554 if (img_count == 0) return false;
535 images_.resize(img_count); 555 images_.resize(img_count);
536 fn_.get_images(device_, swapchain_, &img_count, images_.data()); 556 fn_.get_images(device_, swapchain_, &img_count, images_.data());
537 image_initialized_.assign(img_count, false); 557 image_initialized_.assign(img_count, false);
538 if (extent_.width != surface_extent_.width || extent_.height != surface_extent_.height || 558 const std::uint32_t requested = buffer_count ? buffer_count : 2u;
539 format_ != chosen.format) { 559 const bool blit_needed = extent_.width != surface_extent_.width || extent_.height != surface_extent_.height ||
540 if (!create_offscreen_backbuffers(img_count)) return false; 560 format_ != chosen.format;
561 if (blit_needed || img_count != requested) {
562 // A varying native count (Vulkan may return more images than minImageCount, and minImageCount may
563 // exceed the app's request) cannot be mapped one-to-one onto DXGI backbuffers: the app owns one
564 // persistent resource per BufferCount index. Expose the requested count as offscreen images and
565 // blit the presented slot into the acquired native image instead.
566 if (!create_offscreen_backbuffers(requested)) return false;
567 exposed_count_ = requested;
568 } else {
569 exposed_count_ = img_count;
541 } 570 }
542 current_index_ = 0; 571 current_index_ = 0;
543 return !images_.empty(); 572 next_back_buffer_ = 0;
573 acquired_index_ = 0;
574 return true;
544 } 575 }
545 576
546 SwapchainFunctions fn_{}; 577 SwapchainFunctions fn_{};
@@ -566,7 +597,10 @@ private:
566 std::vector<bool> image_initialized_; 597 std::vector<bool> image_initialized_;
567 std::vector<VkImage> offscreen_images_; 598 std::vector<VkImage> offscreen_images_;
568 std::vector<VkDeviceMemory> offscreen_memory_; 599 std::vector<VkDeviceMemory> offscreen_memory_;
600 std::uint32_t exposed_count_ = 0;
569 std::uint32_t current_index_ = 0; 601 std::uint32_t current_index_ = 0;
602 std::uint32_t acquired_index_ = 0;
603 std::uint32_t next_back_buffer_ = 0;
570}; 604};
571 605
572} // namespace leonida 606} // namespace leonida
diff --git a/runtime/shims/file_system.cpp b/runtime/shims/file_system.cpp
index 5b9f92199..014514597 100644
--- a/runtime/shims/file_system.cpp
+++ b/runtime/shims/file_system.cpp
@@ -393,9 +393,11 @@ Target write_target(const std::wstring& path, bool copy_up) {
393 return t; 393 return t;
394} 394}
395 395
396// MAXIMUM_ALLOWED names no right and grants every one the file allows, write included, so it is a write-open: opened
397// as a read it handed out a handle to the package file itself, and a WriteFile through it changed the package.
396bool writes(DWORD access, DWORD disposition) { 398bool writes(DWORD access, DWORD disposition) {
397 constexpr DWORD kWriteAccess = GENERIC_WRITE | GENERIC_ALL | FILE_WRITE_DATA | FILE_APPEND_DATA | FILE_WRITE_EA | 399 constexpr DWORD kWriteAccess = GENERIC_WRITE | GENERIC_ALL | MAXIMUM_ALLOWED | FILE_WRITE_DATA | FILE_APPEND_DATA |
398 FILE_WRITE_ATTRIBUTES | DELETE | WRITE_DAC | WRITE_OWNER; 400 FILE_WRITE_EA | FILE_WRITE_ATTRIBUTES | DELETE | WRITE_DAC | WRITE_OWNER;
399 if ((access & kWriteAccess) != 0) return true; 401 if ((access & kWriteAccess) != 0) return true;
400 return disposition == CREATE_NEW || disposition == CREATE_ALWAYS || disposition == OPEN_ALWAYS || 402 return disposition == CREATE_NEW || disposition == CREATE_ALWAYS || disposition == OPEN_ALWAYS ||
401 disposition == TRUNCATE_EXISTING; 403 disposition == TRUNCATE_EXISTING;
@@ -1043,12 +1045,50 @@ BOOL WINAPI copy_file_ex_a(LPCSTR from, LPCSTR to, LPPROGRESS_ROUTINE progress,
1043 return copy_file_ex_w(wide_from.c_str(), wide_to.c_str(), progress, data, cancel, flags); 1045 return copy_file_ex_w(wide_from.c_str(), wide_to.c_str(), progress, data, cancel, flags);
1044} 1046}
1045 1047
1048namespace {
1049
1050// The host's CopyFile2, or null where the host has none. Wine 9's kernel32 and kernelbase don't export it: Wine's
1051// loader binds a static import of it to a stub that aborts the process when called ("unimplemented function
1052// KERNEL32.dll.CopyFile2, aborting"), so a direct ::CopyFile2 call (or MSVC's std::filesystem::copy_file, which uses
1053// it) kills a title under Wine 9 or a Proton built on it; pe_loader.cpp and loader_tls_test.cpp avoid it for the same
1054// reason. GetProcAddress returns null there instead, and the fallback below runs.
1055using CopyFile2Fn = HRESULT(WINAPI*)(PCWSTR, PCWSTR, COPYFILE2_EXTENDED_PARAMETERS*);
1056CopyFile2Fn host_copy_file2() {
1057 static const CopyFile2Fn fn = [] {
1058 for (const wchar_t* dll : {L"kernelbase.dll", L"kernel32.dll"}) {
1059 if (const HMODULE module = GetModuleHandleW(dll))
1060 if (const FARPROC p = GetProcAddress(module, "CopyFile2")) return reinterpret_cast<CopyFile2Fn>(p);
1061 }
1062 return CopyFile2Fn{};
1063 }();
1064 return fn;
1065}
1066
1067// CopyFile2 through CopyFileExW, for hosts without it. The flags both calls define are passed on; the rest are
1068// CopyFile2-only hints and privilege requests (no offload, compressed traffic, low-free-space mode, ...) that don't
1069// change what a plain file copy produces, and CopyFileExW refuses flags it doesn't know. The cancel flag has the same
1070// type in both. A COPYFILE2 progress routine has another signature and message set, so it isn't called here.
1071HRESULT copy_file2_fallback(const wchar_t* source, const wchar_t* destination,
1072 const COPYFILE2_EXTENDED_PARAMETERS* parameters) {
1073 constexpr DWORD kCopyFileExFlags = COPY_FILE_FAIL_IF_EXISTS | COPY_FILE_RESTARTABLE |
1074 COPY_FILE_OPEN_SOURCE_FOR_WRITE | COPY_FILE_ALLOW_DECRYPTED_DESTINATION |
1075 COPY_FILE_COPY_SYMLINK | COPY_FILE_NO_BUFFERING;
1076 const DWORD flags = parameters ? parameters->dwCopyFlags & kCopyFileExFlags : 0;
1077 BOOL* const cancel = parameters ? parameters->pfCancel : nullptr;
1078 if (::CopyFileExW(source, destination, nullptr, nullptr, cancel, flags)) return S_OK;
1079 const DWORD error = GetLastError();
1080 return HRESULT_FROM_WIN32(error ? error : ERROR_GEN_FAILURE);
1081}
1082
1083} // namespace
1084
1046HRESULT WINAPI copy_file2(PCWSTR from, PCWSTR to, COPYFILE2_EXTENDED_PARAMETERS* parameters) { 1085HRESULT WINAPI copy_file2(PCWSTR from, PCWSTR to, COPYFILE2_EXTENDED_PARAMETERS* parameters) {
1047 const bool fail_if_exists = parameters && (parameters->dwCopyFlags & COPY_FILE_FAIL_IF_EXISTS) != 0; 1086 const bool fail_if_exists = parameters && (parameters->dwCopyFlags & COPY_FILE_FAIL_IF_EXISTS) != 0;
1048 std::filesystem::path source, destination; 1087 std::filesystem::path source, destination;
1049 DWORD error = 0; 1088 DWORD error = 0;
1050 if (!copy_paths(from, to, fail_if_exists, source, destination, error)) return HRESULT_FROM_WIN32(error); 1089 if (!copy_paths(from, to, fail_if_exists, source, destination, error)) return HRESULT_FROM_WIN32(error);
1051 return ::CopyFile2(source.c_str(), destination.c_str(), parameters); 1090 if (const CopyFile2Fn host = host_copy_file2()) return host(source.c_str(), destination.c_str(), parameters);
1091 return copy_file2_fallback(source.c_str(), destination.c_str(), parameters);
1052} 1092}
1053 1093
1054BOOL WINAPI set_file_attributes_w(LPCWSTR name, DWORD attributes) { 1094BOOL WINAPI set_file_attributes_w(LPCWSTR name, DWORD attributes) {
diff --git a/runtime/shims/gameinput.cpp b/runtime/shims/gameinput.cpp
index 69707f75a..2bc486042 100644
--- a/runtime/shims/gameinput.cpp
+++ b/runtime/shims/gameinput.cpp
@@ -16,6 +16,8 @@
16// SDL_CreateHapticEffect/RunHapticEffect (IGameInputForceFeedbackEffect); haptic trigger motors, reported from the 16// SDL_CreateHapticEffect/RunHapticEffect (IGameInputForceFeedbackEffect); haptic trigger motors, reported from the
17// trigger motors the pad already has, played as an intensity through the same trigger output as SetRumbleState 17// trigger motors the pad already has, played as an intensity through the same trigger output as SetRumbleState
18// - the keyboard pad (LEONIDA_KEYBOARD_PAD): one SDL virtual gamepad driven by the keyboard and mouse 18// - the keyboard pad (LEONIDA_KEYBOARD_PAD): one SDL virtual gamepad driven by the keyboard and mouse
19// - which kind of device the player used last (rt::gameinput::active_input, LEONIDA_PROMPTS), for the runtime's
20// own use: the title is told every pad is an Xbox One pad
19// 21//
20// One thread owns SDL: the background poll thread by default, or the caller of rt::gameinput::poll() when 22// One thread owns SDL: the background poll thread by default, or the caller of rt::gameinput::poll() when
21// LEONIDA_GAMEINPUT_THREAD=0. Title calls never touch SDL: they read the latest snapshot and leave rumble requests 23// LEONIDA_GAMEINPUT_THREAD=0. Title calls never touch SDL: they read the latest snapshot and leave rumble requests
@@ -170,6 +172,19 @@ rt::gameinput::Config read_config() {
170 else if (!k.empty() && k != "0" && k != "off") 172 else if (!k.empty() && k != "0" && k != "off")
171 std::fprintf(stderr, "[rt] gameinput: LEONIDA_KEYBOARD_PAD=%s unknown (1, always or off), keyboard pad off\n", 173 std::fprintf(stderr, "[rt] gameinput: LEONIDA_KEYBOARD_PAD=%s unknown (1, always or off), keyboard pad off\n",
172 k.c_str()); 174 k.c_str());
175 using leonida::InputFamily;
176 const std::string p = env("LEONIDA_PROMPTS");
177 if (p == "xbox") c.prompts = InputFamily::Xbox;
178 else if (p == "playstation" || p == "ps5") c.prompts = InputFamily::PlayStation5;
179 else if (p == "ps4") c.prompts = InputFamily::PlayStation4;
180 else if (p == "ps3") c.prompts = InputFamily::PlayStation3;
181 else if (p == "nintendo" || p == "switch") c.prompts = InputFamily::Nintendo;
182 else if (p == "keyboard") c.prompts = InputFamily::Keyboard;
183 else if (!p.empty() && p != "auto")
184 std::fprintf(stderr, "[rt] gameinput: LEONIDA_PROMPTS=%s unknown (auto, xbox, playstation, ps5, ps4, ps3, "
185 "nintendo or keyboard), following the devices\n", p.c_str());
186 if (const std::string m = env("LEONIDA_PROMPTS_SWITCH_MS"); !m.empty())
187 c.prompts_switch_ms = static_cast<uint32_t>(std::clamp(std::atoi(m.c_str()), 0, 2000));
173 return c; 188 return c;
174} 189}
175 190
@@ -508,6 +523,7 @@ public:
508 int sent_gain = -1; // device gain 0..100 last sent, so a steady gain costs one call 523 int sent_gain = -1; // device gain 0..100 last sent, so a steady gain costs one call
509 uint32_t haptic_motors = 0; // trigger haptic motors the pad reports (0 or 2) 524 uint32_t haptic_motors = 0; // trigger haptic motors the pad reports (0 or 2)
510 rt::gameinput::OutputState sent{}; 525 rt::gameinput::OutputState sent{};
526 leonida::InputFamily family = leonida::InputFamily::Xbox; // what kind of device it really is (active_input)
511 Snapshot last_snap{}; // what the latest reading holds 527 Snapshot last_snap{}; // what the latest reading holds
512 uint64_t last_reading_us = 0; // for the motion cadence: readings stream at ~125 Hz on pads with sensors 528 uint64_t last_reading_us = 0; // for the motion cadence: readings stream at ~125 Hz on pads with sensors
513 uint64_t motors_sent_at = 0, triggers_sent_at = 0, battery_at = 0; 529 uint64_t motors_sent_at = 0, triggers_sent_at = 0, battery_at = 0;
@@ -923,6 +939,79 @@ float axis(SDL_Gamepad* p, SDL_GamepadAxis a) { return std::max(-1.0f, SDL_GetGa
923 939
924float norm(float v, float max) { return std::clamp(v / max, -1.0f, 1.0f); } 940float norm(float v, float max) { return std::clamp(v / max, -1.0f, 1.0f); }
925 941
942bool is_keyboard_pad(SDL_JoystickID jid); // with the keyboard pad below
943
944// What kind of device a pad really is, for active_input(): SDL's gamepad type, which it takes from the vendor and
945// product id. Anything SDL does not place (a generic or unknown pad, a GameCube adapter) counts as Xbox, the layout
946// GameInput itself describes.
947leonida::InputFamily family_of(SDL_JoystickID jid, SDL_Gamepad* p) {
948 using leonida::InputFamily;
949 if (is_keyboard_pad(jid)) return InputFamily::Keyboard;
950 switch (SDL_GetGamepadType(p)) {
951 case SDL_GAMEPAD_TYPE_PS5: return InputFamily::PlayStation5;
952 case SDL_GAMEPAD_TYPE_PS4: return InputFamily::PlayStation4;
953 case SDL_GAMEPAD_TYPE_PS3: return InputFamily::PlayStation3;
954 case SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_PRO:
955 case SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_LEFT:
956 case SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_RIGHT:
957 case SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_PAIR: return InputFamily::Nintendo;
958 default: return InputFamily::Xbox;
959 }
960}
961
962// ---- active input (src/active_input.h) ----
963//
964// The tracker is poll-thread state, under poll_mu like the rest of the poll. What it answers is published in one word,
965// so active_input() needs no lock and never sees a family from one change with the generation of another: the family
966// in bits 0-7, forced in bit 8, the generation from bit 16.
967leonida::ActiveInputTracker g_tracker;
968std::atomic<uint64_t> g_active{0};
969
970void publish_active() {
971 g_active.store(static_cast<uint64_t>(g_tracker.active()) | (g_tracker.forced() ? 1ull << 8 : 0) |
972 (g_tracker.generation() << 16),
973 std::memory_order_release);
974}
975
976leonida::InputSample sample_of(const Snapshot& s) {
977 static_assert(kButtonCount <= 32, "every SDL gamepad button needs a bit");
978 leonida::InputSample out;
979 for (uint32_t i = 0; i < kButtonCount; ++i) // all of SDL's buttons: guide, touchpad and paddles included
980 if (s.buttons[i]) out.buttons |= 1u << i;
981 out.left_trigger = s.gamepad.leftTrigger;
982 out.right_trigger = s.gamepad.rightTrigger;
983 out.left_x = s.gamepad.leftThumbstickX;
984 out.left_y = s.gamepad.leftThumbstickY;
985 out.right_x = s.gamepad.rightThumbstickX;
986 out.right_y = s.gamepad.rightThumbstickY;
987 return out;
988}
989
990// LEONIDA_PROMPTS and LEONIDA_PROMPTS_SWITCH_MS, applied at each poll: reload_config can change them at any time.
991void apply_prompt_config() {
992 std::optional<leonida::InputFamily> want;
993 uint32_t switch_ms;
994 {
995 std::lock_guard lock(g().mu);
996 want = g().config.prompts;
997 switch_ms = g().config.prompts_switch_ms;
998 }
999 leonida::ActiveInputTracker::Thresholds t = g_tracker.thresholds();
1000 t.min_switch_us = uint64_t{switch_ms} * 1000;
1001 g_tracker.set_thresholds(t);
1002 const std::optional<leonida::InputFamily> now =
1003 g_tracker.forced() ? std::optional<leonida::InputFamily>(g_tracker.active()) : std::nullopt;
1004 if (want == now) return;
1005 g_tracker.force(want);
1006 publish_active();
1007 if (want)
1008 std::fprintf(stderr, "[rt] gameinput: LEONIDA_PROMPTS: input family set to %s\n",
1009 leonida::input_family_name(*want));
1010 else
1011 std::fprintf(stderr, "[rt] gameinput: LEONIDA_PROMPTS cleared: input family follows the devices (%s now)\n",
1012 leonida::input_family_name(g_tracker.active()));
1013}
1014
926Snapshot read_pad(Device* d) { 1015Snapshot read_pad(Device* d) {
927 SDL_Gamepad* p = d->pad; 1016 SDL_Gamepad* p = d->pad;
928 Snapshot s; 1017 Snapshot s;
@@ -1243,6 +1332,7 @@ void open_pad(SDL_JoystickID jid, uint64_t ts) {
1243 } 1332 }
1244 d->pad = p; 1333 d->pad = p;
1245 d->id = jid; 1334 d->id = jid;
1335 d->family = family_of(jid, p);
1246 d->is_dualsense = SDL_GetGamepadType(p) == SDL_GAMEPAD_TYPE_PS5; 1336 d->is_dualsense = SDL_GetGamepadType(p) == SDL_GAMEPAD_TYPE_PS5;
1247 d->has_rumble = SDL_GetBooleanProperty(props, SDL_PROP_GAMEPAD_CAP_RUMBLE_BOOLEAN, false); 1337 d->has_rumble = SDL_GetBooleanProperty(props, SDL_PROP_GAMEPAD_CAP_RUMBLE_BOOLEAN, false);
1248 d->has_trigger_rumble = SDL_GetBooleanProperty(props, SDL_PROP_GAMEPAD_CAP_TRIGGER_RUMBLE_BOOLEAN, false); 1338 d->has_trigger_rumble = SDL_GetBooleanProperty(props, SDL_PROP_GAMEPAD_CAP_TRIGGER_RUMBLE_BOOLEAN, false);
@@ -1343,6 +1433,7 @@ void open_pad(SDL_JoystickID jid, uint64_t ts) {
1343 1433
1344void close_pad(Device* d, uint64_t ts) { 1434void close_pad(Device* d, uint64_t ts) {
1345 State& s = g(); 1435 State& s = g();
1436 g_tracker.forget(d->id); // poll-thread state: a pad that comes back starts from a fresh baseline
1346 std::lock_guard lock(s.mu); 1437 std::lock_guard lock(s.mu);
1347 const uint32_t old = d->status.exchange(GameInputDeviceNoStatus); 1438 const uint32_t old = d->status.exchange(GameInputDeviceNoStatus);
1348 SDL_CloseGamepad(d->pad); 1439 SDL_CloseGamepad(d->pad);
@@ -1636,6 +1727,8 @@ struct KeyboardPad {
1636}; 1727};
1637KeyboardPad g_keyboard; 1728KeyboardPad g_keyboard;
1638 1729
1730bool is_keyboard_pad(SDL_JoystickID jid) { return jid != 0 && jid == g_keyboard.id; }
1731
1639void detach_keyboard_pad() { 1732void detach_keyboard_pad() {
1640 if (g_keyboard.js) SDL_CloseJoystick(g_keyboard.js); 1733 if (g_keyboard.js) SDL_CloseJoystick(g_keyboard.js);
1641 if (g_keyboard.id) SDL_DetachVirtualJoystick(g_keyboard.id); 1734 if (g_keyboard.id) SDL_DetachVirtualJoystick(g_keyboard.id);
@@ -1782,6 +1875,7 @@ void poll_once() {
1782 State& s = g(); 1875 State& s = g();
1783 std::lock_guard pl(s.poll_mu); 1876 std::lock_guard pl(s.poll_mu);
1784 if (!init_sdl()) return; 1877 if (!init_sdl()) return;
1878 apply_prompt_config();
1785 update_keyboard_pad(); 1879 update_keyboard_pad();
1786 SDL_UpdateGamepads(); 1880 SDL_UpdateGamepads();
1787 const uint64_t now = now_us(); 1881 const uint64_t now = now_us();
@@ -1818,6 +1912,15 @@ void poll_once() {
1818 const bool guide_changed = d->last_snap.guide != snap.guide; 1912 const bool guide_changed = d->last_snap.guide != snap.guide;
1819 const bool changed = !(d->last_snap == snap); 1913 const bool changed = !(d->last_snap == snap);
1820 d->last_snap = snap; 1914 d->last_snap = snap;
1915 // A newly opened pad's first sample here is its baseline (active_input.h), so connecting a pad with a button
1916 // held changes nothing.
1917 if (const leonida::InputEdge edge = g_tracker.observe(d->id, d->family, sample_of(snap), now);
1918 edge != leonida::InputEdge::None) {
1919 publish_active();
1920 if (!g_tracker.forced())
1921 std::fprintf(stderr, "[rt] gameinput: input in use: %s (%s, %s)\n",
1922 leonida::input_family_name(d->family), d->name.c_str(), leonida::input_edge_name(edge));
1923 }
1821 // A pad with sensors streams readings at ~125 Hz even when nothing else changes, so motion the title reads 1924 // A pad with sensors streams readings at ~125 Hz even when nothing else changes, so motion the title reads
1822 // between its frames is never stuck at the last button event; pads without sensors only read on change, as 1925 // between its frames is never stuck at the last button event; pads without sensors only read on change, as
1823 // before. push_reading stamps last_reading_us, so the cadence follows the actual history. 1926 // before. push_reading stamps last_reading_us, so the cadence follows the actual history.
@@ -2447,6 +2550,11 @@ int connected_count() {
2447 return static_cast<int>(g().connected.size()); 2550 return static_cast<int>(g().connected.size());
2448} 2551}
2449 2552
2553ActiveInput active_input() {
2554 const uint64_t v = g_active.load(std::memory_order_acquire);
2555 return {static_cast<leonida::InputFamily>(v & 0xFF), v >> 16, ((v >> 8) & 1) != 0};
2556}
2557
2450bool output_state(int i, OutputState* out) { 2558bool output_state(int i, OutputState* out) {
2451 std::lock_guard lock(g().mu); 2559 std::lock_guard lock(g().mu);
2452 if (i < 0 || i >= static_cast<int>(g().connected.size()) || !out) return false; 2560 if (i < 0 || i >= static_cast<int>(g().connected.size()) || !out) return false;
diff --git a/runtime/shims/gameinput.h b/runtime/shims/gameinput.h
index acee24e85..57dbfc503 100644
--- a/runtime/shims/gameinput.h
+++ b/runtime/shims/gameinput.h
@@ -5,6 +5,8 @@
5#include <cstdint> 5#include <cstdint>
6#include <vector> 6#include <vector>
7 7
8#include "../src/active_input.h" // leonida::InputFamily (and std::optional) for Config::prompts and active_input()
9
8namespace rt::gameinput { 10namespace rt::gameinput {
9 11
10// How the impulse-trigger motors (GameInputRumbleParams::leftTrigger/rightTrigger) reach a DualSense. 12// How the impulse-trigger motors (GameInputRumbleParams::leftTrigger/rightTrigger) reach a DualSense.
@@ -15,6 +17,10 @@ enum class DsTriggerMode { Off, Rumble, Resistance };
15enum class KeyboardPadMode { Off, Focused, Always }; 17enum class KeyboardPadMode { Off, Focused, Always };
16 18
17struct Config { 19struct Config {
20 // LEONIDA_PROMPTS=auto|xbox|playstation|ps5|ps4|ps3|nintendo|keyboard: a family that active_input() reports
21 // whatever is in use; unset or auto follows the devices.
22 std::optional<leonida::InputFamily> prompts;
23 uint32_t prompts_switch_ms = 300; // LEONIDA_PROMPTS_SWITCH_MS, 0..2000: shortest time between two changes
18 DsTriggerMode ds_triggers = DsTriggerMode::Rumble; // LEONIDA_DS_TRIGGERS=off|rumble|resistance 24 DsTriggerMode ds_triggers = DsTriggerMode::Rumble; // LEONIDA_DS_TRIGGERS=off|rumble|resistance
19 float ds_trigger_gain = 1.0f; // LEONIDA_DS_TRIGGER_GAIN, 0..4, scales the effect strength 25 float ds_trigger_gain = 1.0f; // LEONIDA_DS_TRIGGER_GAIN, 0..4, scales the effect strength
20 float mouse_sensitivity = 1.0f; // LEONIDA_MOUSE_SENSITIVITY, 0.1..10, scales mouse movement 26 float mouse_sensitivity = 1.0f; // LEONIDA_MOUSE_SENSITIVITY, 0.1..10, scales mouse movement
@@ -40,6 +46,17 @@ void poll();
40// Number of gamepads currently open by the backend (tests, gameinput_probe). 46// Number of gamepads currently open by the backend (tests, gameinput_probe).
41int connected_count(); 47int connected_count();
42 48
49// The kind of device the player used last (src/active_input.h has the rules), or the one LEONIDA_PROMPTS forces.
50// The title is told every pad is an Xbox One pad; this is for the runtime's own use, such as button prompt glyphs.
51// Safe from any thread. `generation` goes up by one with each change of `family`, so a reader can check it every
52// frame and act only when it moved. Xbox, generation 0, until the first deliberate input.
53struct ActiveInput {
54 leonida::InputFamily family = leonida::InputFamily::Xbox;
55 uint64_t generation = 0;
56 bool forced = false; // LEONIDA_PROMPTS set the family
57};
58ActiveInput active_input();
59
43// The SDL haptic calls the shim makes, one entry per call, so a test can stand in for them: SDL's virtual joysticks 60// The SDL haptic calls the shim makes, one entry per call, so a test can stand in for them: SDL's virtual joysticks
44// report no haptics, and a pad that does is the only other way to reach this path. `joystick` is the SDL_Joystick the 61// report no haptics, and a pad that does is the only other way to reach this path. `joystick` is the SDL_Joystick the
45// gamepad was opened from, `haptic` what open_joystick returned, `effect` is an SDL_HapticEffect. Returning null from 62// gamepad was opened from, `haptic` what open_joystick returned, `effect` is an SDL_HapticEffect. Returning null from
diff --git a/runtime/shims/process.cpp b/runtime/shims/process.cpp
index 1fc4fee7f..0bca28443 100644
--- a/runtime/shims/process.cpp
+++ b/runtime/shims/process.cpp
@@ -5,8 +5,14 @@
5// - argv/argc and the command line are the game's (set by run_entry), not gta6rt's; 5// - argv/argc and the command line are the game's (set by run_entry), not gta6rt's;
6// - exit(), _exit(), quick_exit(), ExitProcess() and abort() from the game end the game's run, not the host: 6// - exit(), _exit(), quick_exit(), ExitProcess() and abort() from the game end the game's run, not the host:
7// the exit code is recorded, the run is signalled as finished and the calling thread waits for the host to 7// the exit code is recorded, the run is signalled as finished and the calling thread waits for the host to
8// exit. atexit handlers and static destructors of the game are not run (its CRT shares the host's, whose 8// exit;
9// process-wide atexit table also holds gta6rt's own). 9// - the game's atexit registrations (_crt_atexit, which MSVC's atexit and static destructors reach; msvcrt's
10// atexit and _onexit) go to a table of the run's own instead of the CRT's process-wide one, which the game
11// shares with gta6rt. exit() runs it newest first, as the CRT does, before the run ends; _exit(), _Exit(),
12// quick_exit(), ExitProcess() and abort() do not. _cexit() runs it and returns, _c_exit() returns. A second
13// thread that calls exit(), _exit(), _Exit() or quick_exit() while the first is leaving waits, as with the
14// CRT's exit lock. Not covered yet: at_quick_exit() handlers (quick_exit() runs none) and the thread-local
15// destructor callback (_register_thread_local_exe_atexit_callback); both still reach the host CRT.
10// Covered CRTs: the Universal CRT (api-ms-win-crt-runtime-l1-1-0.dll / ucrtbase.dll, what MSVC links; ucrtbased.dll in Debug) and 16// Covered CRTs: the Universal CRT (api-ms-win-crt-runtime-l1-1-0.dll / ucrtbase.dll, what MSVC links; ucrtbased.dll in Debug) and
11// msvcrt.dll (MinGW). Calls made inside host DLLs, not through the game's imports, are not seen here. 17// msvcrt.dll (MinGW). Calls made inside host DLLs, not through the game's imports, are not seen here.
12// The loader matches imports by exact DLL name, so GetCommandLineA/W and ExitProcess are served under every name a 18// The loader matches imports by exact DLL name, so GetCommandLineA/W and ExitProcess are served under every name a
@@ -19,6 +25,8 @@
19#include <cstdio> 25#include <cstdio>
20#include <cstdlib> 26#include <cstdlib>
21#include <cstring> 27#include <cstring>
28#include <mutex>
29#include <new>
22#include <string> 30#include <string>
23#include <type_traits> 31#include <type_traits>
24#include <vector> 32#include <vector>
@@ -84,8 +92,77 @@ std::string narrow(const std::wstring& w) {
84 ExitProcess(static_cast<UINT>(g_exit_code.load())); 92 ExitProcess(static_cast<UINT>(g_exit_code.load()));
85} 93}
86 94
95// ---- the game's atexit table
96using AtexitFn = void(__cdecl*)();
97using OnexitFn = int(__cdecl*)();
98std::mutex g_atexit_lock;
99std::vector<AtexitFn> g_atexit;
100std::atomic<DWORD> g_exiting_thread{0};
101
102bool register_atexit(AtexitFn fn) {
103 std::lock_guard<std::mutex> lock(g_atexit_lock);
104 try {
105 g_atexit.push_back(fn);
106 } catch (const std::bad_alloc&) {
107 return false; // the CRT reports a full table as a failed registration
108 }
109 return true;
110}
111
112// Newest first. A handler registered while the handlers run goes on the end and so runs next, as in the UCRT.
113void run_atexit_handlers() {
114 for (;;) {
115 AtexitFn fn;
116 {
117 std::lock_guard<std::mutex> lock(g_atexit_lock);
118 if (g_atexit.empty()) return;
119 fn = g_atexit.back();
120 g_atexit.pop_back();
121 }
122 fn();
123 }
124}
125
126// UCRT: int _crt_atexit(_PVFV), 0 on success. MSVC's atexit() and the static destructors of an EXE reach it.
127int __cdecl game_crt_atexit(AtexitFn fn) {
128 return fn && register_atexit(fn) ? 0 : -1;
129}
130// msvcrt.dll (MinGW): int atexit(void (*)(void)) and _onexit_t _onexit(_onexit_t).
131int __cdecl game_msvcrt_atexit(AtexitFn fn) { return game_crt_atexit(fn); }
132OnexitFn __cdecl game_onexit(OnexitFn fn) {
133 // its int result is ignored, as the CRT ignores it
134 return fn && register_atexit(reinterpret_cast<AtexitFn>(fn)) ? fn : nullptr;
135}
136
87// ---- the way out 137// ---- the way out
88void __cdecl game_exit(int code) { end_run(code); } 138// The CRT's exit lock, which exit(), _exit(), _Exit() and quick_exit() all take: the first thread to leave owns it
139// and ends the run; any other thread that tries to leave waits forever. The owner may leave again from a handler
140// (undefined in C): that ends the run with the new code and skips the remaining handlers.
141bool take_exit_lock() {
142 const DWORD self = GetCurrentThreadId();
143 DWORD owner = 0;
144 if (g_exiting_thread.compare_exchange_strong(owner, self)) return true;
145 if (owner != self) {
146 for (;;) Sleep(INFINITE);
147 }
148 return false;
149}
150// exit(): the game's handlers and static destructors, then the end of the run.
151void __cdecl game_exit(int code) {
152 if (take_exit_lock()) run_atexit_handlers();
153 end_run(code);
154}
155// _exit(), _Exit(), quick_exit(): the end of the run without the atexit handlers.
156void __cdecl game_quick_exit(int code) {
157 take_exit_lock();
158 end_run(code);
159}
160// _cexit() runs the handlers and flushes the streams, then returns; _c_exit() only returns.
161void __cdecl game_cexit() {
162 run_atexit_handlers();
163 std::fflush(nullptr);
164}
165void __cdecl game_c_exit() {}
89void __stdcall game_exit_process(UINT code) { end_run(static_cast<int>(code)); } 166void __stdcall game_exit_process(UINT code) { end_run(static_cast<int>(code)); }
90void __cdecl game_abort() { 167void __cdecl game_abort() {
91 std::fprintf(stderr, "[rt] process: the game called abort()\n"); 168 std::fprintf(stderr, "[rt] process: the game called abort()\n");
@@ -203,6 +280,11 @@ void set_command_line(const std::wstring& program, const std::vector<std::wstrin
203} 280}
204 281
205int run_entry(void* entry, size_t stack_bytes) { 282int run_entry(void* entry, size_t stack_bytes) {
283 {
284 std::lock_guard<std::mutex> lock(g_atexit_lock);
285 g_atexit.clear(); // a run never sees the handlers of an earlier one
286 }
287 g_exiting_thread = 0;
206 g_exited = false; 288 g_exited = false;
207 g_exit_code = 0; 289 g_exit_code = 0;
208 g_done = CreateEventW(nullptr, TRUE, FALSE, nullptr); 290 g_done = CreateEventW(nullptr, TRUE, FALSE, nullptr);
@@ -242,8 +324,11 @@ int run_entry(void* entry, size_t stack_bytes) {
242namespace { 324namespace {
243using namespace rt::process; 325using namespace rt::process;
244#define UCRT(dll) \ 326#define UCRT(dll) \
245 {dll, "exit", reinterpret_cast<void*>(&game_exit)}, {dll, "_exit", reinterpret_cast<void*>(&game_exit)}, \ 327 {dll, "exit", reinterpret_cast<void*>(&game_exit)}, {dll, "_exit", reinterpret_cast<void*>(&game_quick_exit)}, \
246 {dll, "_Exit", reinterpret_cast<void*>(&game_exit)}, {dll, "quick_exit", reinterpret_cast<void*>(&game_exit)}, \ 328 {dll, "_Exit", reinterpret_cast<void*>(&game_quick_exit)}, \
329 {dll, "quick_exit", reinterpret_cast<void*>(&game_quick_exit)}, \
330 {dll, "_crt_atexit", reinterpret_cast<void*>(&game_crt_atexit)}, \
331 {dll, "_cexit", reinterpret_cast<void*>(&game_cexit)}, {dll, "_c_exit", reinterpret_cast<void*>(&game_c_exit)}, \
247 {dll, "abort", reinterpret_cast<void*>(&game_abort)}, {dll, "__p___argc", reinterpret_cast<void*>(&game_p_argc)}, \ 332 {dll, "abort", reinterpret_cast<void*>(&game_abort)}, {dll, "__p___argc", reinterpret_cast<void*>(&game_p_argc)}, \
248 {dll, "__p___argv", reinterpret_cast<void*>(&game_p_argv)}, \ 333 {dll, "__p___argv", reinterpret_cast<void*>(&game_p_argv)}, \
249 {dll, "__p___wargv", reinterpret_cast<void*>(&game_p_wargv)}, \ 334 {dll, "__p___wargv", reinterpret_cast<void*>(&game_p_wargv)}, \
@@ -264,7 +349,11 @@ SHIM_TABLE(process,
264 UCRT("ucrtbase.dll"), 349 UCRT("ucrtbase.dll"),
265 UCRT("ucrtbased.dll"), // the Debug UCRT: a Debug build of the stand-in game (run_tiny_game) links it 350 UCRT("ucrtbased.dll"), // the Debug UCRT: a Debug build of the stand-in game (run_tiny_game) links it
266 {"msvcrt.dll", "exit", reinterpret_cast<void*>(&game_exit)}, 351 {"msvcrt.dll", "exit", reinterpret_cast<void*>(&game_exit)},
267 {"msvcrt.dll", "_exit", reinterpret_cast<void*>(&game_exit)}, 352 {"msvcrt.dll", "_exit", reinterpret_cast<void*>(&game_quick_exit)},
353 {"msvcrt.dll", "atexit", reinterpret_cast<void*>(&game_msvcrt_atexit)},
354 {"msvcrt.dll", "_onexit", reinterpret_cast<void*>(&game_onexit)},
355 {"msvcrt.dll", "_cexit", reinterpret_cast<void*>(&game_cexit)},
356 {"msvcrt.dll", "_c_exit", reinterpret_cast<void*>(&game_c_exit)},
268 {"msvcrt.dll", "abort", reinterpret_cast<void*>(&game_abort)}, 357 {"msvcrt.dll", "abort", reinterpret_cast<void*>(&game_abort)},
269 {"msvcrt.dll", "__getmainargs", reinterpret_cast<void*>(&game_getmainargs)}, 358 {"msvcrt.dll", "__getmainargs", reinterpret_cast<void*>(&game_getmainargs)},
270 {"msvcrt.dll", "__wgetmainargs", reinterpret_cast<void*>(&game_wgetmainargs)}, 359 {"msvcrt.dll", "__wgetmainargs", reinterpret_cast<void*>(&game_wgetmainargs)},
diff --git a/runtime/shims/winhttp_offline.cpp b/runtime/shims/winhttp_offline.cpp
index 284f19eb1..10854d5f2 100644
--- a/runtime/shims/winhttp_offline.cpp
+++ b/runtime/shims/winhttp_offline.cpp
@@ -15,7 +15,8 @@
15// WinHttpWriteData fail with ERROR_WINHTTP_INCORRECT_HANDLE_STATE: no request ever got that far. 15// WinHttpWriteData fail with ERROR_WINHTTP_INCORRECT_HANDLE_STATE: no request ever got that far.
16// - Options, timeouts and request headers are accepted. WINHTTP_OPTION_CONTEXT_VALUE is kept per handle and 16// - Options, timeouts and request headers are accepted. WINHTTP_OPTION_CONTEXT_VALUE is kept per handle and
17// WINHTTP_OPTION_HANDLE_TYPE answered; WinHttpQueryOption reports ERROR_WINHTTP_INVALID_OPTION for the rest. 17// WINHTTP_OPTION_HANDLE_TYPE answered; WinHttpQueryOption reports ERROR_WINHTTP_INVALID_OPTION for the rest.
18// - A status callback set on a handle is inherited by the handles created under it, as in WinHTTP. 18// - A status callback set on a handle is inherited by the handles created under it, as in WinHTTP, and so is
19// the handle's WINHTTP_OPTION_CONTEXT_VALUE as it is when the child is made.
19// WINHTTP_CALLBACK_STATUS_HANDLE_CREATED is reported when a child handle is made, and 20// WINHTTP_CALLBACK_STATUS_HANDLE_CREATED is reported when a child handle is made, and
20// WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING once per handle, last, after WinHttpCloseHandle and any callback still 21// WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING once per handle, last, after WinHttpCloseHandle and any callback still
21// running for it. 22// running for it.
@@ -122,10 +123,12 @@ HINTERNET make_handle(Kind kind, Handle* parent, bool async) {
122 h->parent = parent; 123 h->parent = parent;
123 h->async = async; 124 h->async = async;
124 if (parent) { 125 if (parent) {
125 // A callback set on a handle is inherited by the handles created under it. 126 // A callback set on a handle is inherited by the handles created under it, and so is the context value
127 // (WINHTTP_OPTION_CONTEXT_VALUE), as the host's winhttp.dll does: what the parent has at this moment.
126 std::lock_guard lock(parent->mutex); 128 std::lock_guard lock(parent->mutex);
127 h->callback = parent->callback; 129 h->callback = parent->callback;
128 h->notifications = parent->notifications; 130 h->notifications = parent->notifications;
131 h->context = parent->context;
129 } 132 }
130 { 133 {
131 std::lock_guard lock(live_mutex()); 134 std::lock_guard lock(live_mutex());
diff --git a/runtime/shims/xgameruntime.cpp b/runtime/shims/xgameruntime.cpp
index 482c0ec5a..f6a8ec175 100644
--- a/runtime/shims/xgameruntime.cpp
+++ b/runtime/shims/xgameruntime.cpp
@@ -17,12 +17,15 @@
17#include <cstdio> 17#include <cstdio>
18#include <cstdlib> 18#include <cstdlib>
19#include <cstring> 19#include <cstring>
20#include <cctype>
20#include <filesystem> 21#include <filesystem>
22#include <fstream>
21#include <iterator> 23#include <iterator>
22#include <mutex> 24#include <mutex>
23#include <string> 25#include <string>
24#include <system_error> 26#include <system_error>
25#include <unordered_map> 27#include <unordered_map>
28#include <vector>
26 29
27#include <XAsync.h> 30#include <XAsync.h>
28#include <XAsyncProvider.h> 31#include <XAsyncProvider.h>
@@ -31,6 +34,10 @@
31#include "file_system.h" 34#include "file_system.h"
32#include "shims.h" 35#include "shims.h"
33 36
37namespace rt::shims {
38bool xgameruntime_user_query(const GUID& class_id, REFIID interface_id, void** out, HRESULT* hr);
39}
40
34namespace { 41namespace {
35 42
36// ---- XGameRuntime ---- 43// ---- XGameRuntime ----
@@ -483,13 +490,18 @@ RuntimeObject g_networking{kNetworkingVtable, &kNetworkingClass, kNetworkingIids
483const GUID* const kPersistentStorageIids[] = {&kPersistentStorage2, &kPersistentStorage3, nullptr}; 490const GUID* const kPersistentStorageIids[] = {&kPersistentStorage2, &kPersistentStorage3, nullptr};
484RuntimeObject g_persistent_storage{kPersistentStorageVtable, &kPersistentStorageClass, kPersistentStorageIids}; 491RuntimeObject g_persistent_storage{kPersistentStorageVtable, &kPersistentStorageClass, kPersistentStorageIids};
485 492
486RuntimeObject& system_object(); // XSystemImpl, defined after the XSystem functions it serves 493RuntimeObject& system_object(); // XSystemImpl, defined after the XSystem functions it serves
494RuntimeObject& package_object(); // XPackageImpl, after the XPackage functions
495RuntimeObject& game_object(); // XGameImpl, after XPackageImpl
487 496
488HRESULT WINAPI QueryApiImpl(const GUID* class_id, REFIID interface_id, void** out) { 497HRESULT WINAPI QueryApiImpl(const GUID* class_id, REFIID interface_id, void** out) {
489 if (out) *out = nullptr; 498 if (out) *out = nullptr;
490 if (class_id && out) { 499 if (class_id && out) {
491 for (RuntimeObject* o : {&g_threading, &g_error, &g_networking, &g_persistent_storage, &system_object()}) 500 for (RuntimeObject* o : {&g_threading, &g_error, &g_networking, &g_persistent_storage, &system_object(),
501 &package_object(), &game_object()})
492 if (*class_id == *o->class_id) return object_query_interface(o, interface_id, out); 502 if (*class_id == *o->class_id) return object_query_interface(o, interface_id, out);
503 HRESULT hr = S_OK;
504 if (rt::shims::xgameruntime_user_query(*class_id, interface_id, out, &hr)) return hr; // xgameruntime_user.cpp
493 } 505 }
494 char cls[40], iid[40]; 506 char cls[40], iid[40];
495 print_guid(cls, class_id); 507 print_guid(cls, class_id);
@@ -840,6 +852,238 @@ bool __stdcall XPackageIsPackagedProcess() {
840 return true; 852 return true;
841} 853}
842 854
855// ---- XPackageImpl (asked for as IXPackageImpl3), offline ----
856//
857// libHttpClient.GDK.dll asks QueryApiImpl for XPackageImpl with IXPackageImpl3's id through 30 thunks (slots 3-19,
858// 22, 24-27, 30, 32-34, 37-40), each in the argument shape of the method at that position of xgameruntime-docs'
859// IXPackageImpl (slots 3-34), IXPackageImpl2 (35-38) and IXPackageImpl3 (39-40) lists (docs/runtime_imports.md).
860// The slots with an offline answer forward to the XPackage functions above (the package identifier, whether the
861// process is packaged, the mount path and its size, the user's locale); every other slot logs its number once and
862// returns E_NOTIMPL, so the first boot shows which ones the title needs.
863
864constexpr GUID kPackageClass = {0xaf406016, 0xe850, 0x4aa8, {0xa8, 0x8d, 0x2f, 0x3d, 0xcb, 0x9d, 0xac, 0x7e}};
865// IXPackageImpl3 : IXPackageImpl2 : IXPackageImpl (xgameruntime include/xpackage.idl); the class id is its own.
866constexpr GUID kPackage1 = {0x3720de07, 0xe8e4, 0x44a3, {0xad, 0x32, 0xb3, 0x59, 0xe8, 0xad, 0xbe, 0x55}};
867constexpr GUID kPackage2 = {0xf92d8712, 0x2b27, 0x4d8a, {0xbf, 0x01, 0x11, 0xa6, 0xf8, 0xe3, 0xeb, 0x42}};
868constexpr GUID kPackage3 = {0xe2a4734b, 0x2f4a, 0x456d, {0xaa, 0x8f, 0xd0, 0x65, 0xe0, 0x4f, 0xb2, 0x09}};
869const GUID* const kPackageIids[] = {&kPackage1, &kPackage2, &kPackage3, nullptr};
870
871template <int Slot> HRESULT STDMETHODCALLTYPE package_not_implemented(void*) {
872 static std::atomic<bool> s_logged{false};
873 if (!s_logged.exchange(true))
874 std::fprintf(stderr, "[rt] xgameruntime: XPackageImpl slot %d not implemented offline (E_NOTIMPL)\n", Slot);
875 return E_NOTIMPL;
876}
877HRESULT STDMETHODCALLTYPE pkg_identifier(void*, size_t size, char* buffer) {
878 return XPackageGetCurrentProcessPackageIdentifier(size, buffer);
879}
880bool STDMETHODCALLTYPE pkg_is_packaged(void*) { return XPackageIsPackagedProcess(); }
881// The locales the package declares: <Resources><Resource Language="xx-YY"/> in MicrosoftGame.Config, read from
882// the game folder (LEONIDA_GAME_DIR, else --game-dir). Empty when there is no config or it declares none.
883// The package's MicrosoftGame.Config as text, from the game folder (LEONIDA_GAME_DIR, else --game-dir); empty when
884// there is no folder or no config. Wide on purpose: a game folder named outside the ANSI code page must reach the file
885// intact.
886std::string package_config() {
887 wchar_t env[MAX_PATH] = {};
888 const DWORD n = GetEnvironmentVariableW(L"LEONIDA_GAME_DIR", env, MAX_PATH);
889 const std::filesystem::path dir = (n > 0 && n < MAX_PATH) ? std::filesystem::path(env) : rt::fs::game_dir();
890 if (dir.empty()) return {};
891 std::ifstream f(dir / L"MicrosoftGame.Config", std::ios::binary);
892 if (!f) return {};
893 return std::string{std::istreambuf_iterator<char>(f), {}};
894}
895
896std::vector<std::string> package_locales() {
897 std::vector<std::string> out;
898 const std::string xml = package_config();
899 if (xml.empty()) return out;
900 for (size_t at = 0; (at = xml.find("<Resource", at)) != std::string::npos; ++at) {
901 if (xml.compare(at, 10, "<Resources") == 0) continue;
902 const size_t end = xml.find('>', at);
903 const size_t key = xml.find("Language=", at);
904 if (end == std::string::npos || key == std::string::npos || key + 10 > end) continue;
905 const char quote = xml[key + 9];
906 const size_t close = xml.find(quote, key + 10);
907 if ((quote == '"' || quote == '\'') && close != std::string::npos && close < end)
908 out.push_back(xml.substr(key + 10, close - key - 10));
909 }
910 return out;
911}
912
913// XPackageGetUserLocale(size_t localeSize, char* locale): of the locales the package declares, the one closest to
914// the user's (the same name, else the same language, else the first declared). Microsoft's contract: "If no locale
915// information is declared for the package, this function succeeds but does not return a user locale". The host's
916// locale is never handed out as the package's.
917HRESULT STDMETHODCALLTYPE pkg_user_locale(void*, size_t size, char* locale) {
918 if (!locale || !size) return E_INVALIDARG;
919 const std::vector<std::string> declared = package_locales();
920 if (declared.empty()) return S_OK;
921 wchar_t wide[LOCALE_NAME_MAX_LENGTH] = {};
922 char user[LOCALE_NAME_MAX_LENGTH * 4] = "";
923 if (GetUserDefaultLocaleName(wide, LOCALE_NAME_MAX_LENGTH) > 0)
924 WideCharToMultiByte(CP_UTF8, 0, wide, -1, user, static_cast<int>(sizeof(user)), nullptr, nullptr);
925 const auto language = [](const std::string& name) { return name.substr(0, name.find('-')); };
926 const auto same = [](const std::string& a, const std::string& b) { return _stricmp(a.c_str(), b.c_str()) == 0; };
927 const std::string* pick = &declared.front();
928 bool exact = false;
929 for (const std::string& d : declared)
930 if (same(d, user)) { pick = &d; exact = true; break; }
931 if (!exact)
932 for (const std::string& d : declared)
933 if (same(language(d), language(user))) { pick = &d; break; }
934 if (size < pick->size() + 1) return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
935 std::memcpy(locale, pick->c_str(), pick->size() + 1);
936 return S_OK;
937}
938// Slots 23-26 forward to the named exports' content-package mounts (XPackageMount and its handle registry), so the two
939// ways in behave the same. XPackageMountHandle is one u64, passed in a register like the named exports take it.
940HRESULT STDMETHODCALLTYPE pkg_mount(void*, const char* package_identifier, XPackageMountHandle* mount) {
941 return XPackageMount(package_identifier, mount);
942}
943HRESULT STDMETHODCALLTYPE pkg_mount_path_size(void*, XPackageMountHandle mount, size_t* size) {
944 return XPackageGetMountPathSize(mount, size);
945}
946HRESULT STDMETHODCALLTYPE pkg_mount_path(void*, XPackageMountHandle mount, size_t size, char* path) {
947 return XPackageGetMountPath(mount, size, path);
948}
949void STDMETHODCALLTYPE pkg_close_mount(void*, XPackageMountHandle mount) { XPackageCloseMountHandle(mount); }
950
951// XPackageInstallationProgress: totalBytes, installedBytes, launchBytes (u64), launchable, completed (bool).
952struct InstallationProgress {
953 uint64_t total_bytes, installed_bytes, launch_bytes;
954 bool launchable, completed;
955};
956static_assert(sizeof(InstallationProgress) == 32, "XPackageInstallationProgress layout");
957// void XPackageGetInstallationProgress(monitor, XPackageInstallationProgress*): an offline package is installed,
958// launchable and completed, every byte present.
959void STDMETHODCALLTYPE pkg_installation_progress(void*, void*, InstallationProgress* progress) {
960 if (progress) *progress = {0, 0, 0, true, true};
961}
962// The bool methods with no offline work, as Microsoft documents them: XPackageUpdateInstallationMonitor is false
963// (nothing changed), the two Unregister* calls are true (nothing pending), XPackageUninstallPackage is false (not
964// uninstalled). A generic E_NOTIMPL stub would read as true in al.
965bool STDMETHODCALLTYPE pkg_update_monitor(void*, void*) { return false; }
966bool STDMETHODCALLTYPE pkg_unregister_progress(void*, void*, XTaskQueueRegistrationToken, bool) { return true; }
967bool STDMETHODCALLTYPE pkg_unregister_installed(void*, XTaskQueueRegistrationToken, bool) { return true; }
968bool STDMETHODCALLTYPE pkg_uninstall_package(void*, const char*) { return false; }
969
970#define PN(n) reinterpret_cast<const void*>(&package_not_implemented<n>)
971const void* const kPackageVtable[] = {
972 reinterpret_cast<const void*>(&object_query_interface), reinterpret_cast<const void*>(&object_add_ref),
973 reinterpret_cast<const void*>(&object_release),
974 reinterpret_cast<const void*>(&pkg_identifier), // 3 XPackageGetCurrentProcessPackageIdentifier
975 reinterpret_cast<const void*>(&pkg_is_packaged), // 4 XPackageIsPackagedProcess
976 PN(5), PN(6), // 5-6 installation monitor: create, close
977 reinterpret_cast<const void*>(&pkg_installation_progress), // 7 XPackageGetInstallationProgress (void, writes)
978 reinterpret_cast<const void*>(&pkg_update_monitor), // 8 XPackageUpdateInstallationMonitor (bool)
979 PN(9), // 9 XPackageRegisterInstallationProgressChanged
980 reinterpret_cast<const void*>(&pkg_unregister_progress), // 10 ...UnregisterInstallationProgressChanged (bool)
981 reinterpret_cast<const void*>(&pkg_user_locale), // 11 XPackageGetUserLocale
982 PN(12), PN(13), PN(14), PN(15), PN(16), PN(17), // 12-19 chunks: find / enumerate availability, change order,
983 PN(18), PN(19), // install (+ async, result), estimate size, uninstall
984 PN(20), PN(21), // 20-21 _unknown_ (older enumerate / register installed)
985 reinterpret_cast<const void*>(&pkg_unregister_installed), // 22 XPackageUnregisterPackageInstalled (bool)
986 reinterpret_cast<const void*>(&pkg_mount), // 23 XPackageMount
987 reinterpret_cast<const void*>(&pkg_mount_path_size), // 24 XPackageGetMountPathSize
988 reinterpret_cast<const void*>(&pkg_mount_path), // 25 XPackageGetMountPath
989 reinterpret_cast<const void*>(&pkg_close_mount), // 26 XPackageCloseMountHandle
990 PN(27), PN(28), PN(29), PN(30), PN(31), // 27 _unknown_, 28 EnumeratePackages, 29 RegisterPackageInstalled,
991 // 30 GetWriteStats, 31 _unknown_
992 PN(32), PN(33), // 32 UninstallUWPInstance, 33 EnumerateFeatures
993 reinterpret_cast<const void*>(&pkg_uninstall_package), // 34 XPackageUninstallPackage (bool)
994 PN(35), PN(36), PN(37), PN(38), // IXPackageImpl2: EnumeratePackages, RegisterPackageInstalled,
995 // MountWithUiAsync, MountWithUiResult
996 PN(39), PN(40), // IXPackageImpl3: EnumeratePackages, RegisterPackageInstalled
997};
998#undef PN
999static_assert(std::size(kPackageVtable) == 41, "IUnknown + IXPackageImpl's 32 + IXPackageImpl2's 4 + IXPackageImpl3's 2");
1000
1001RuntimeObject& package_object() {
1002 static RuntimeObject object{kPackageVtable, &kPackageClass, kPackageIids};
1003 return object;
1004}
1005
1006// ---- XGameImpl (asked for as IXGameImpl3), offline ----
1007//
1008// IXGameImpl3 : IXGameImpl2 : IXGameImpl (xgameruntime include/xgame.idl); the class id is IXGameImpl's. Three
1009// methods after IUnknown: 3 XGameGetXboxTitleId (IXGameImpl), 4 XLaunchNewGame (IXGameImpl2), 5 XLaunchRestartOnCrash
1010// (IXGameImpl3). A retail Gen9 title asks QueryApiImpl for this class (Freminet/ScarlettX's README, observed on
1011// Concept Destruction); the executable here is not available yet, so its own requests are unmeasured.
1012
1013constexpr GUID kGameClass = {0x973a344e, 0x24bf, 0x4d0f, {0x84, 0x57, 0x56, 0xc5, 0x34, 0x89, 0x2b, 0x29}};
1014constexpr GUID kGame2 = {0x50849859, 0x0ad8, 0x4f81, {0x80, 0xe4, 0x5b, 0xc7, 0x86, 0x26, 0xf8, 0x52}};
1015constexpr GUID kGame3 = {0x2549f142, 0x6419, 0x4a06, {0x97, 0xb5, 0x93, 0x1a, 0xab, 0x7c, 0x2f, 0x34}};
1016const GUID* const kGameIids[] = {&kGame2, &kGame3, nullptr};
1017
1018// The title id MicrosoftGame.Config declares (<TitleId>, eight hex digits), or false when there is none or it is not
1019// hex. The first <TitleId> element counts; surrounding whitespace is allowed.
1020bool package_title_id(uint32_t& out) {
1021 const std::string xml = package_config();
1022 const size_t open = xml.find("<TitleId>");
1023 if (open == std::string::npos) return false;
1024 const size_t begin = xml.find_first_not_of(" \t\r\n", open + 9);
1025 const size_t close = xml.find("</TitleId>", open);
1026 if (begin == std::string::npos || close == std::string::npos || begin >= close) return false;
1027 size_t end = close;
1028 while (end > begin && std::isspace(static_cast<unsigned char>(xml[end - 1]))) --end;
1029 if (end - begin == 0 || end - begin > 8) return false;
1030 uint32_t value = 0;
1031 for (size_t i = begin; i < end; ++i) {
1032 const char c = xml[i];
1033 const int digit = c >= '0' && c <= '9' ? c - '0' : c >= 'a' && c <= 'f' ? c - 'a' + 10
1034 : c >= 'A' && c <= 'F' ? c - 'A' + 10 : -1;
1035 if (digit < 0) return false;
1036 value = value << 4 | static_cast<uint32_t>(digit);
1037 }
1038 out = value;
1039 return true;
1040}
1041
1042// HRESULT XGameGetXboxTitleId(uint32_t* titleId): the package's title id. Without a config that declares one there
1043// is no title id to give (E_FAIL), rather than a made-up one.
1044HRESULT STDMETHODCALLTYPE game_get_title_id(void*, uint32_t* title_id) {
1045 if (!title_id) return E_INVALIDARG;
1046 uint32_t id = 0;
1047 if (!package_title_id(id)) {
1048 static std::atomic<bool> s_logged{false};
1049 if (!s_logged.exchange(true))
1050 std::fprintf(stderr, "[rt] xgameruntime: XGameGetXboxTitleId: no <TitleId> in MicrosoftGame.Config\n");
1051 return E_FAIL;
1052 }
1053 *title_id = id;
1054 return S_OK;
1055}
1056
1057// void XLaunchNewGame(const char* exePath, const char* args, XUserHandle defaultUser): on the console this ends the
1058// title and starts another. Offline there is no other title to start; the call is logged and returns.
1059void STDMETHODCALLTYPE game_launch_new(void*, const char* exe_path, const char* args, void*) {
1060 std::fprintf(stderr, "[rt] xgameruntime: XLaunchNewGame(\"%s\", \"%s\") ignored offline\n",
1061 exe_path ? exe_path : "", args ? args : "");
1062}
1063
1064// HRESULT XLaunchRestartOnCrash(const char* args, uint32_t reserved): asks the console to restart the title after a
1065// crash. Nothing restarts the process here; it succeeds with nothing registered.
1066HRESULT STDMETHODCALLTYPE game_restart_on_crash(void*, const char*, uint32_t) {
1067 static std::atomic<bool> s_logged{false};
1068 if (!s_logged.exchange(true))
1069 std::fprintf(stderr, "[rt] xgameruntime: XLaunchRestartOnCrash: no restart is registered offline\n");
1070 return S_OK;
1071}
1072
1073const void* const kGameVtable[] = {
1074 reinterpret_cast<const void*>(&object_query_interface), reinterpret_cast<const void*>(&object_add_ref),
1075 reinterpret_cast<const void*>(&object_release),
1076 reinterpret_cast<const void*>(&game_get_title_id), // 3 XGameGetXboxTitleId (IXGameImpl)
1077 reinterpret_cast<const void*>(&game_launch_new), // 4 XLaunchNewGame (IXGameImpl2, void)
1078 reinterpret_cast<const void*>(&game_restart_on_crash), // 5 XLaunchRestartOnCrash (IXGameImpl3)
1079};
1080static_assert(std::size(kGameVtable) == 6, "IUnknown + IXGameImpl3's 3 methods");
1081
1082RuntimeObject& game_object() {
1083 static RuntimeObject object{kGameVtable, &kGameClass, kGameIids};
1084 return object;
1085}
1086
843#define XGR(name) {"xgameruntime.dll", #name, reinterpret_cast<void*>(&name)} 1087#define XGR(name) {"xgameruntime.dll", #name, reinterpret_cast<void*>(&name)}
844 1088
845} // namespace 1089} // namespace
diff --git a/runtime/shims/xgameruntime_user.cpp b/runtime/shims/xgameruntime_user.cpp
new file mode 100644
index 000000000..0cc343393
--- /dev/null
+++ b/runtime/shims/xgameruntime_user.cpp
@@ -0,0 +1,539 @@
1// xgameruntime: XUserImpl, the class xgameruntime.lib's XUser* functions reach through QueryApiImpl, offline.
2//
3// A GDK title links XUserAddAsync, XUserGetId, XUserGetGamertag and the rest statically (xgameruntime.lib); each of
4// those thunks asks QueryApiImpl for XUserImpl and calls one slot with the function's own arguments after `this`
5// (docs/runtime_imports.md, "Run-time loaded modules"; xgameruntime.cpp serves the other classes the same way).
6// The class and interface ids and the slot order are xodus-gaming/xgameruntime-docs' "Layout" lists (GPL-3.0; facts
7// only, nothing copied). Signatures, enum values and error codes follow Microsoft's public GDK reference
8// (learn.microsoft.com/gaming/gdk, XUser and Error Codes pages). No GDK header or library code is used.
9//
10// Offline there is one local user, always signed in: the default user XUserAddAsync returns (with or without
11// AddDefaultUserSilently), with a fixed Xbox user id and local id, and a gamertag from LEONIDA_GAMERTAG (15 ASCII
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.
14//
15// ASSUMPTION: the console executable is not available, so which of these slots it calls is unknown until its first
16// boot. Private and PC-only slots log once when called, so that boot lists them.
17#include <windows.h>
18
19#include <atomic>
20#include <cstdint>
21#include <cstdio>
22#include <cstdlib>
23#include <cstring>
24#include <iterator>
25#include <mutex>
26#include <set>
27#include <unordered_set>
28
29#include <XAsync.h>
30#include <XAsyncProvider.h>
31#include <XTaskQueue.h>
32
33namespace {
34
35// ---- Public GDK types (XUser.h, as the GDK reference documents them) ----
36
37using XUserHandle = struct XUserLocal*; // opaque to the title
38using XUserSignOutDeferralHandle = struct XUserSignOutDeferral*;
39struct XUserLocalId {
40 uint64_t value;
41};
42enum class XUserAddOptions : uint32_t { None = 0x00, AddDefaultUserSilently = 0x01, AllowGuests = 0x02, AddDefaultUserAllowingUI = 0x04 };
43enum class XUserState : uint32_t { SignedIn = 0, SigningOut = 1, SignedOut = 2 };
44enum class XUserAgeGroup : uint32_t { Unknown = 0, Child = 1, Teen = 2, Adult = 3 };
45enum class XUserGamertagComponent : uint32_t { Classic = 0, Modern = 1, ModernSuffix = 2, UniqueModern = 3 };
46enum class XUserPrivilegeDenyReason : uint32_t { None = 0 };
47enum class XUserChangeEvent : uint32_t { SignedInAgain = 0 };
48using XUserChangeEventCallback = void(CALLBACK*)(void* context, XUserLocalId user, XUserChangeEvent event);
49
50// XGameErr.h values, from the GDK "Error codes" page.
51constexpr HRESULT E_GAMEUSER_USER_NOT_FOUND = static_cast<HRESULT>(0x89245104);
52constexpr HRESULT E_GAMEUSER_DEFERRAL_NOT_AVAILABLE = static_cast<HRESULT>(0x89245103);
53constexpr HRESULT E_GAMEUSER_FAILED_TO_RESOLVE = static_cast<HRESULT>(0x89245107);
54constexpr HRESULT E_GAMEUSER_FAILED_TO_GET_TOKEN = static_cast<HRESULT>(0x89245111);
55constexpr HRESULT kInsufficientBuffer = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
56
57// ---- The offline user ----
58
59// Fixed, non-zero ids. The Xbox user id has the shape of a real XUID (a 64-bit number); nothing checks it offline.
60constexpr uint64_t kOfflineXuid = 0x0009000000000001ull;
61constexpr uint64_t kOfflineLocalId = 1;
62
63const char* gamertag() {
64 static char tag[16] = "Player";
65 static std::once_flag once;
66 std::call_once(once, [] {
67 size_t length = 0; // with the terminator; 0 when unset
68 if (getenv_s(&length, nullptr, 0, "LEONIDA_GAMERTAG") != 0 || length <= 1) return;
69 if (length - 1 > 15) {
70 std::fprintf(stderr, "[rt] xgameruntime: LEONIDA_GAMERTAG is longer than 15 characters; using \"Player\"\n");
71 return;
72 }
73 char value[16] = {};
74 if (getenv_s(&length, value, "LEONIDA_GAMERTAG") != 0) return;
75 for (size_t i = 0; i + 1 < length; ++i)
76 if (static_cast<unsigned char>(value[i]) < 0x20 || static_cast<unsigned char>(value[i]) > 0x7e) {
77 std::fprintf(stderr, "[rt] xgameruntime: LEONIDA_GAMERTAG is not printable ASCII; using \"Player\"\n");
78 return;
79 }
80 std::memcpy(tag, value, length);
81 });
82 return tag;
83}
84
85// A title must close every XUserHandle it gets exactly once, so each one is its own allocation; they all name the
86// one local user. A handle is valid while it is in the live set: it's looked up, never read, so a closed or foreign
87// pointer is refused without touching its memory. The block is freed on close, so the heap may hand its address out
88// again; a stale handle then names a newer live one, which is harmless here since every handle names the same user.
89struct XUserLocal {
90 uint32_t unused;
91};
92std::mutex g_handles_mutex;
93std::unordered_set<const void*> g_handles;
94
95XUserHandle new_handle() {
96 auto* h = new XUserLocal{};
97 std::lock_guard<std::mutex> lock(g_handles_mutex);
98 g_handles.insert(h);
99 return h;
100}
101bool valid(XUserHandle h) {
102 if (!h) return false;
103 std::lock_guard<std::mutex> lock(g_handles_mutex);
104 return g_handles.count(h) != 0;
105}
106
107// ---- IXUserImpl (slots 3-36) ----
108
109// 3: HRESULT XUserDuplicateHandle(XUserHandle handle, XUserHandle* duplicatedHandle)
110HRESULT STDMETHODCALLTYPE user_duplicate(void*, XUserHandle handle, XUserHandle* dup) {
111 if (!dup) return E_POINTER;
112 *dup = nullptr;
113 if (!valid(handle)) return E_INVALIDARG;
114 *dup = new_handle();
115 return S_OK;
116}
117
118// 4: void XUserCloseHandle(XUserHandle user)
119void STDMETHODCALLTYPE user_close(void*, XUserHandle user) {
120 {
121 std::lock_guard<std::mutex> lock(g_handles_mutex);
122 if (!user || g_handles.erase(user) == 0) return; // closed already, or not ours
123 }
124 delete user;
125}
126
127// 5: int32_t XUserCompare(XUserHandle user1, XUserHandle user2): 0 when both name the same user. Every valid handle
128// names the one local user.
129int32_t STDMETHODCALLTYPE user_compare(void*, XUserHandle a, XUserHandle b) {
130 const bool va = valid(a), vb = valid(b);
131 if (va && vb) return 0;
132 if (va != vb) return va ? 1 : -1;
133 return a == b ? 0 : (a < b ? -1 : 1);
134}
135
136// 6: HRESULT XUserGetMaxUsers(uint32_t* maxUsers). One local user offline.
137HRESULT STDMETHODCALLTYPE user_get_max_users(void*, uint32_t* max_users) {
138 if (!max_users) return E_POINTER;
139 *max_users = 1;
140 return S_OK;
141}
142
143// XAsync providers. The result of an add is a new handle, created when the title collects it, so a result the
144// title never collects leaks nothing.
145const char kAddIdentity = 0;
146const char kAddByIdIdentity = 0;
147const char kResolveIdentity = 0;
148
149HRESULT CALLBACK add_provider(XAsyncOp op, const XAsyncProviderData* data) {
150 switch (op) {
151 case XAsyncOp::Begin:
152 return XAsyncSchedule(data->async, 0);
153 case XAsyncOp::DoWork:
154 XAsyncComplete(data->async, S_OK, sizeof(XUserHandle));
155 return S_OK;
156 case XAsyncOp::GetResult:
157 if (data->bufferSize < sizeof(XUserHandle) || !data->buffer) return E_INVALIDARG;
158 *static_cast<XUserHandle*>(data->buffer) = new_handle();
159 return S_OK;
160 default:
161 return S_OK;
162 }
163}
164
165// The add-by-id flavour: the context is the requested id; an id other than the local user's completes with
166// E_GAMEUSER_USER_NOT_FOUND (no other user can sign in offline).
167HRESULT CALLBACK add_by_id_provider(XAsyncOp op, const XAsyncProviderData* data) {
168 switch (op) {
169 case XAsyncOp::Begin:
170 return XAsyncSchedule(data->async, 0);
171 case XAsyncOp::DoWork: {
172 const bool known = reinterpret_cast<uintptr_t>(data->context) == static_cast<uintptr_t>(kOfflineXuid);
173 XAsyncComplete(data->async, known ? S_OK : E_GAMEUSER_USER_NOT_FOUND, known ? sizeof(XUserHandle) : 0);
174 return S_OK;
175 }
176 case XAsyncOp::GetResult:
177 if (data->bufferSize < sizeof(XUserHandle) || !data->buffer) return E_INVALIDARG;
178 *static_cast<XUserHandle*>(data->buffer) = new_handle();
179 return S_OK;
180 default:
181 return S_OK;
182 }
183}
184
185// Resolving a privilege: every privilege is granted offline, so there is nothing to show; completes with S_OK.
186HRESULT CALLBACK resolve_provider(XAsyncOp op, const XAsyncProviderData* data) {
187 if (op == XAsyncOp::Begin) return XAsyncSchedule(data->async, 0);
188 if (op == XAsyncOp::DoWork) XAsyncComplete(data->async, S_OK, 0);
189 return S_OK;
190}
191
192// 7: HRESULT XUserAddAsync(XUserAddOptions options, XAsyncBlock* async). AllowGuests with AddDefaultUserSilently is
193// refused, as documented ("A guest cannot be the default user"). Without a silent option the console would show the
194// account picker; offline the one user is the answer either way.
195HRESULT STDMETHODCALLTYPE user_add_async(void*, XUserAddOptions options, XAsyncBlock* async) {
196 if (!async) return E_POINTER;
197 const auto bits = static_cast<uint32_t>(options);
198 if ((bits & static_cast<uint32_t>(XUserAddOptions::AddDefaultUserSilently)) &&
199 (bits & static_cast<uint32_t>(XUserAddOptions::AllowGuests)))
200 return E_INVALIDARG;
201 return XAsyncBegin(async, nullptr, &kAddIdentity, "XUserAddAsync", add_provider);
202}
203
204// 8: HRESULT XUserAddResult(XAsyncBlock* async, XUserHandle* newUser)
205HRESULT STDMETHODCALLTYPE user_add_result(void*, XAsyncBlock* async, XUserHandle* user) {
206 if (!user) return E_POINTER;
207 *user = nullptr;
208 return XAsyncGetResult(async, &kAddIdentity, sizeof(*user), user, nullptr);
209}
210
211// 9: HRESULT XUserGetLocalId(XUserHandle user, XUserLocalId* userLocalId)
212HRESULT STDMETHODCALLTYPE user_get_local_id(void*, XUserHandle user, XUserLocalId* id) {
213 if (!id) return E_POINTER;
214 if (!valid(user)) return E_INVALIDARG;
215 id->value = kOfflineLocalId;
216 return S_OK;
217}
218
219// 10: HRESULT XUserFindUserByLocalId(XUserLocalId userLocalId, XUserHandle* handle)
220HRESULT STDMETHODCALLTYPE user_find_by_local_id(void*, XUserLocalId id, XUserHandle* handle) {
221 if (!handle) return E_POINTER;
222 *handle = nullptr;
223 if (id.value != kOfflineLocalId) return E_GAMEUSER_USER_NOT_FOUND;
224 *handle = new_handle();
225 return S_OK;
226}
227
228// 11: HRESULT XUserGetId(XUserHandle user, uint64_t* userId)
229HRESULT STDMETHODCALLTYPE user_get_id(void*, XUserHandle user, uint64_t* id) {
230 if (!id) return E_POINTER;
231 if (!valid(user)) return E_INVALIDARG;
232 *id = kOfflineXuid;
233 return S_OK;
234}
235
236// 12: HRESULT XUserFindUserById(uint64_t userId, XUserHandle* handle)
237HRESULT STDMETHODCALLTYPE user_find_by_id(void*, uint64_t id, XUserHandle* handle) {
238 if (!handle) return E_POINTER;
239 *handle = nullptr;
240 if (id != kOfflineXuid) return E_GAMEUSER_USER_NOT_FOUND;
241 *handle = new_handle();
242 return S_OK;
243}
244
245// 13: HRESULT XUserGetIsGuest(XUserHandle user, bool* isGuest)
246HRESULT STDMETHODCALLTYPE user_get_is_guest(void*, XUserHandle user, bool* guest) {
247 if (!guest) return E_POINTER;
248 if (!valid(user)) return E_INVALIDARG;
249 *guest = false;
250 return S_OK;
251}
252
253// 14: HRESULT XUserGetState(XUserHandle user, XUserState* state)
254HRESULT STDMETHODCALLTYPE user_get_state(void*, XUserHandle user, XUserState* state) {
255 if (!state) return E_POINTER;
256 if (!valid(user)) return E_INVALIDARG;
257 *state = XUserState::SignedIn;
258 return S_OK;
259}
260
261// A slot with no public signature, logged once. Slot 15 (the docs' "unknown") answers E_NOTIMPL, so a caller fails
262// instead of reading outputs nothing wrote. Slot 47, IXUserImpl6's undocumented XUserIsSignOutPresent, is read as a
263// bool, where E_NOTIMPL's low byte (1) would mean true, so it answers 0 (false: nothing signs out offline).
264template <int Slot> HRESULT STDMETHODCALLTYPE unknown_slot(void*) {
265 static std::atomic<bool> s_logged{false};
266 if (!s_logged.exchange(true))
267 std::fprintf(stderr, "[rt] xgameruntime: XUserImpl slot %d has no public signature; answering E_NOTIMPL\n", Slot);
268 return E_NOTIMPL;
269}
270template <int Slot> uint64_t STDMETHODCALLTYPE private_slot(void*) {
271 static std::atomic<bool> s_logged{false};
272 if (!s_logged.exchange(true))
273 std::fprintf(stderr, "[rt] xgameruntime: XUserImpl private slot %d called; answering 0\n", Slot);
274 return 0;
275}
276
277// An operation that needs the network or a system UI the offline runtime doesn't have. The *Async function fails
278// before starting, so the XAsyncBlock is never used and no callback runs; its Result/ResultSize partners return the
279// same error. Their arguments don't matter, so the functions take none (x64: the caller owns the argument area).
280template <int Slot, HRESULT Error> HRESULT STDMETHODCALLTYPE offline_failure(void*) {
281 static std::atomic<bool> s_logged{false};
282 if (!s_logged.exchange(true))
283 std::fprintf(stderr, "[rt] xgameruntime: XUserImpl slot %d is not available offline (HRESULT 0x%08lx)\n", Slot,
284 static_cast<unsigned long>(Error));
285 return Error;
286}
287
288// 19: HRESULT XUserGetAgeGroup(XUserHandle user, XUserAgeGroup* ageGroup)
289HRESULT STDMETHODCALLTYPE user_get_age_group(void*, XUserHandle user, XUserAgeGroup* group) {
290 if (!group) return E_POINTER;
291 if (!valid(user)) return E_INVALIDARG;
292 *group = XUserAgeGroup::Adult;
293 return S_OK;
294}
295
296// 20: HRESULT XUserCheckPrivilege(XUserHandle user, XUserPrivilegeOptions options, XUserPrivilege privilege,
297// bool* hasPrivilege, XUserPrivilegeDenyReason* reason). Everything is allowed offline
298// (multiplayer and the like then fail at the network, as on a console without one).
299HRESULT STDMETHODCALLTYPE user_check_privilege(void*, XUserHandle user, uint32_t, uint32_t, bool* has,
300 XUserPrivilegeDenyReason* reason) {
301 if (!has) return E_POINTER;
302 if (!valid(user)) return E_INVALIDARG;
303 *has = true;
304 if (reason) *reason = XUserPrivilegeDenyReason::None;
305 return S_OK;
306}
307
308// 21: HRESULT XUserResolvePrivilegeWithUiAsync(XUserHandle user, XUserPrivilegeOptions options, XUserPrivilege privilege,
309// XAsyncBlock* async)
310HRESULT STDMETHODCALLTYPE user_resolve_privilege_async(void*, XUserHandle user, uint32_t, uint32_t, XAsyncBlock* async) {
311 if (!async) return E_POINTER;
312 if (!valid(user)) return E_INVALIDARG;
313 return XAsyncBegin(async, nullptr, &kResolveIdentity, "XUserResolvePrivilegeWithUiAsync", resolve_provider);
314}
315
316// 22: HRESULT XUserResolvePrivilegeWithUiResult(XAsyncBlock* async)
317HRESULT STDMETHODCALLTYPE user_resolve_privilege_result(void*, XAsyncBlock* async) {
318 return XAsyncGetResult(async, &kResolveIdentity, 0, nullptr, nullptr);
319}
320
321// 33: HRESULT XUserRegisterForChangeEvent(XTaskQueueHandle queue, void* context, XUserChangeEventCallback* callback,
322// XTaskQueueRegistrationToken* token)
323// 34: bool XUserUnregisterForChangeEvent(XTaskQueueRegistrationToken token, bool wait)
324// The user never changes offline, so the callbacks are kept only as tokens.
325std::mutex g_tokens_mutex;
326std::set<uint64_t> g_tokens;
327uint64_t g_next_token = 1;
328
329HRESULT STDMETHODCALLTYPE user_register_change(void*, XTaskQueueHandle, void*, XUserChangeEventCallback callback,
330 XTaskQueueRegistrationToken* token) {
331 if (!callback || !token) return E_POINTER;
332 std::lock_guard<std::mutex> lock(g_tokens_mutex);
333 token->token = g_next_token++;
334 g_tokens.insert(token->token);
335 return S_OK;
336}
337
338// false means "wait was false and the unregistration is still pending"; nothing is ever pending offline, so it is
339// true for every token, including one already unregistered or never handed out (a title polling with wait = false
340// would otherwise spin).
341bool STDMETHODCALLTYPE user_unregister_change(void*, XTaskQueueRegistrationToken token, bool) {
342 std::lock_guard<std::mutex> lock(g_tokens_mutex);
343 g_tokens.erase(token.token);
344 return true;
345}
346
347// 35: HRESULT XUserGetSignOutDeferral(XUserSignOutDeferralHandle* deferral): nothing signs out offline, so there is
348// no sign-out to defer (the documented E_GAMEUSER_DEFERRAL_NOT_AVAILABLE).
349HRESULT STDMETHODCALLTYPE user_get_signout_deferral(void*, XUserSignOutDeferralHandle* deferral) {
350 if (deferral) *deferral = nullptr;
351 return E_GAMEUSER_DEFERRAL_NOT_AVAILABLE;
352}
353
354// 36: void XUserCloseSignOutDeferralHandle(XUserSignOutDeferralHandle deferral)
355void STDMETHODCALLTYPE user_close_signout_deferral(void*, XUserSignOutDeferralHandle) {}
356
357// ---- IXUserImpl2 (37-38) ----
358
359// 37: HRESULT XUserAddByIdWithUiAsync(uint64_t userId, XAsyncBlock* async)
360HRESULT STDMETHODCALLTYPE user_add_by_id_async(void*, uint64_t id, XAsyncBlock* async) {
361 if (!async) return E_POINTER;
362 return XAsyncBegin(async, reinterpret_cast<void*>(static_cast<uintptr_t>(id)), &kAddByIdIdentity,
363 "XUserAddByIdWithUiAsync", add_by_id_provider);
364}
365
366// 38: HRESULT XUserAddByIdWithUiResult(XAsyncBlock* async, XUserHandle* newUser)
367HRESULT STDMETHODCALLTYPE user_add_by_id_result(void*, XAsyncBlock* async, XUserHandle* user) {
368 if (!user) return E_POINTER;
369 *user = nullptr;
370 return XAsyncGetResult(async, &kAddByIdIdentity, sizeof(*user), user, nullptr);
371}
372
373// ---- IXUserImpl4 (42) ----
374
375// 42: bool XUserIsStoreUser(XUserHandle user): the handle is _In_opt_, and the GDK reference says the function
376// always returns true on console.
377bool STDMETHODCALLTYPE user_is_store_user(void*, XUserHandle) { return true; }
378
379// ---- IXUserGamertagImpl (its slot 3) ----
380
381// HRESULT XUserGetGamertag(XUserHandle user, XUserGamertagComponent component, size_t gamertagSize, char* gamertag,
382// size_t* gamertagUsed). The offline user has a classic gamertag: Modern and UniqueModern are
383// the same text (a classic tag has no '#' and no suffix) and ModernSuffix is empty. gamertagUsed counts the
384// terminator.
385HRESULT STDMETHODCALLTYPE user_get_gamertag(void*, XUserHandle user, XUserGamertagComponent component, size_t size,
386 char* out, size_t* used) {
387 if (used) *used = 0;
388 if (!valid(user)) return E_INVALIDARG;
389 const char* text = nullptr;
390 switch (component) {
391 case XUserGamertagComponent::Classic:
392 case XUserGamertagComponent::Modern:
393 case XUserGamertagComponent::UniqueModern:
394 text = gamertag();
395 break;
396 case XUserGamertagComponent::ModernSuffix:
397 text = "";
398 break;
399 default:
400 return E_INVALIDARG;
401 }
402 const size_t need = std::strlen(text) + 1;
403 if (!out || size < need) return kInsufficientBuffer;
404 std::memcpy(out, text, need);
405 if (used) *used = need;
406 return S_OK;
407}
408
409// ---- The object: one vtable for the IXUserImpl..IXUserImpl6 chain, one for IXUserGamertagImpl ----
410
411constexpr GUID kUserClass = {0x01acd177, 0x91f9, 0x4763, {0xa3, 0x8e, 0xcc, 0xbb, 0x55, 0xce, 0x32, 0xe0}};
412// IXUserImpl's id is the class id; IXUserImpl2..6 extend it, so each of them answers with the same vtable.
413constexpr GUID kUserInterfaces[] = {
414 kUserClass,
415 {0xeb9bf948, 0x18dc, 0x4d82, {0xbb, 0xcc, 0x40, 0xe0, 0xa8, 0x09, 0xc4, 0xc0}}, // IXUserImpl2
416 {0x1bf2f8c5, 0xd507, 0x4e52, {0xbb, 0x05, 0xf7, 0x26, 0xd0, 0xe7, 0x11, 0x61}}, // IXUserImpl3
417 {0x079415e3, 0x6727, 0x437f, {0x8e, 0x9d, 0x8f, 0x8f, 0x9b, 0x24, 0x39, 0xf7}}, // IXUserImpl4
418 {0x26f3c674, 0xa2fe, 0x44fa, {0xb6, 0xc4, 0xa3, 0x23, 0xbc, 0x94, 0xff, 0x53}}, // IXUserImpl5
419 {0x5131d685, 0x4394, 0x4ee6, {0x8c, 0x18, 0xbf, 0xb5, 0xd4, 0xae, 0xf1, 0xff}}, // IXUserImpl6
420};
421constexpr GUID kGamertagInterface = {0xcef4fac0, 0x7676, 0x4a94, {0xa1, 0x19, 0x4c, 0x43, 0xf9, 0xeb, 0x5b, 0x74}};
422constexpr GUID kIUnknown = {0x00000000, 0x0000, 0x0000, {0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}};
423
424struct UserObject {
425 const void* const* vtable; // IXUserImpl6
426 const void* const* gamertag_vtable; // IXUserGamertagImpl
427};
428UserObject* user_object();
429
430HRESULT query(REFIID iid, void** out) {
431 if (!out) return E_POINTER;
432 *out = nullptr;
433 UserObject* o = user_object();
434 if (iid == kIUnknown) {
435 *out = &o->vtable;
436 return S_OK;
437 }
438 for (const GUID& id : kUserInterfaces)
439 if (iid == id) {
440 *out = &o->vtable;
441 return S_OK;
442 }
443 if (iid == kGamertagInterface) {
444 *out = &o->gamertag_vtable;
445 return S_OK;
446 }
447 return E_NOINTERFACE;
448}
449
450// A process-wide singleton, as the other runtime classes: AddRef and Release don't free.
451HRESULT STDMETHODCALLTYPE object_query_interface(void*, REFIID iid, void** out) { return query(iid, out); }
452ULONG STDMETHODCALLTYPE object_add_ref(void*) { return 2; }
453ULONG STDMETHODCALLTYPE object_release(void*) { return 1; }
454
455#define FN(f) reinterpret_cast<const void*>(&f)
456
457const void* const kUserVtable[] = {
458 FN(object_query_interface), FN(object_add_ref), FN(object_release), // 0-2 IUnknown
459 FN(user_duplicate), // 3 XUserDuplicateHandle
460 FN(user_close), // 4 XUserCloseHandle
461 FN(user_compare), // 5 XUserCompare
462 FN(user_get_max_users), // 6 XUserGetMaxUsers
463 FN(user_add_async), // 7 XUserAddAsync
464 FN(user_add_result), // 8 XUserAddResult
465 FN(user_get_local_id), // 9 XUserGetLocalId
466 FN(user_find_by_local_id), // 10 XUserFindUserByLocalId
467 FN(user_get_id), // 11 XUserGetId
468 FN(user_find_by_id), // 12 XUserFindUserById
469 FN(user_get_is_guest), // 13 XUserGetIsGuest
470 FN(user_get_state), // 14 XUserGetState
471 FN(unknown_slot<15>), // 15 (unknown in the docs)
472 FN((offline_failure<16, E_FAIL>)), // 16 XUserGetGamerPictureAsync
473 FN((offline_failure<17, E_FAIL>)), // 17 XUserGetGamerPictureResultSize
474 FN((offline_failure<18, E_FAIL>)), // 18 XUserGetGamerPictureResult
475 FN(user_get_age_group), // 19 XUserGetAgeGroup
476 FN(user_check_privilege), // 20 XUserCheckPrivilege
477 FN(user_resolve_privilege_async), // 21 XUserResolvePrivilegeWithUiAsync
478 FN(user_resolve_privilege_result), // 22 XUserResolvePrivilegeWithUiResult
479 FN((offline_failure<23, E_GAMEUSER_FAILED_TO_GET_TOKEN>)), // 23 XUserGetTokenAndSignatureAsync
480 FN((offline_failure<24, E_GAMEUSER_FAILED_TO_GET_TOKEN>)), // 24 ...ResultSize
481 FN((offline_failure<25, E_GAMEUSER_FAILED_TO_GET_TOKEN>)), // 25 ...Result
482 FN((offline_failure<26, E_GAMEUSER_FAILED_TO_GET_TOKEN>)), // 26 XUserGetTokenAndSignatureUtf16Async
483 FN((offline_failure<27, E_GAMEUSER_FAILED_TO_GET_TOKEN>)), // 27 ...Utf16ResultSize
484 FN((offline_failure<28, E_GAMEUSER_FAILED_TO_GET_TOKEN>)), // 28 ...Utf16Result
485 FN((offline_failure<29, E_GAMEUSER_FAILED_TO_RESOLVE>)), // 29 XUserResolveIssueWithUiAsync
486 FN((offline_failure<30, E_GAMEUSER_FAILED_TO_RESOLVE>)), // 30 XUserResolveIssueWithUiResult
487 FN((offline_failure<31, E_GAMEUSER_FAILED_TO_RESOLVE>)), // 31 XUserResolveIssueWithUiUtf16Async
488 FN((offline_failure<32, E_GAMEUSER_FAILED_TO_RESOLVE>)), // 32 XUserResolveIssueWithUiUtf16Result
489 FN(user_register_change), // 33 XUserRegisterForChangeEvent
490 FN(user_unregister_change), // 34 XUserUnregisterForChangeEvent
491 FN(user_get_signout_deferral), // 35 XUserGetSignOutDeferral
492 FN(user_close_signout_deferral), // 36 XUserCloseSignOutDeferralHandle
493 FN(user_add_by_id_async), // 37 XUserAddByIdWithUiAsync (2)
494 FN(user_add_by_id_result), // 38 XUserAddByIdWithUiResult (2)
495 FN((offline_failure<39, E_GAMEUSER_FAILED_TO_GET_TOKEN>)), // 39 XUserGetMsaTokenSilentlyAsync (3)
496 FN((offline_failure<40, E_GAMEUSER_FAILED_TO_GET_TOKEN>)), // 40 ...Result (3)
497 FN((offline_failure<41, E_GAMEUSER_FAILED_TO_GET_TOKEN>)), // 41 ...ResultSize (3)
498 FN(user_is_store_user), // 42 XUserIsStoreUser (4)
499 FN((offline_failure<43, E_NOTIMPL>)), // 43 XUserPlatformRemoteConnectSetEventHandlers (5, PC)
500 FN((offline_failure<44, E_NOTIMPL>)), // 44 XUserPlatformRemoteConnectCancelPrompt (5, PC)
501 FN((offline_failure<45, E_NOTIMPL>)), // 45 XUserPlatformSpopPromptSetEventHandlers (5, PC)
502 FN((offline_failure<46, E_NOTIMPL>)), // 46 XUserPlatformSpopPromptComplete (5, PC)
503 FN(private_slot<47>), // 47 XUserIsSignOutPresent (6): false
504 FN((offline_failure<48, E_NOTIMPL>)), // 48 XUserSignOutAsync (6)
505 FN((offline_failure<49, E_NOTIMPL>)), // 49 XUserSignOutResult (6)
506};
507static_assert(std::size(kUserVtable) == 50, "IUnknown + IXUserImpl's 34 methods + 2 + 3 + 1 + 4 + 3");
508
509// The gamertag face's IUnknown slots get `this` = &gamertag_vtable; the object is a singleton, so they ignore it.
510const void* const kGamertagVtable[] = {
511 FN(object_query_interface), FN(object_add_ref), FN(object_release),
512 FN(user_get_gamertag), // 3 XUserGetGamertag
513};
514
515#undef FN
516
517UserObject* user_object() {
518 static UserObject o{kUserVtable, kGamertagVtable};
519 return &o;
520}
521
522} // namespace
523
524namespace rt::shims {
525
526// Called by xgameruntime.cpp's QueryApiImpl for every class: true when the class is XUserImpl, with *hr set.
527bool xgameruntime_user_query(const GUID& class_id, REFIID interface_id, void** out, HRESULT* hr) {
528 if (class_id != kUserClass) return false;
529 *hr = query(interface_id, out);
530 return true;
531}
532
533// For tests: the XUserHandles a title holds open.
534long xgameruntime_user_open_handles() {
535 std::lock_guard<std::mutex> lock(g_handles_mutex);
536 return static_cast<long>(g_handles.size());
537}
538
539} // namespace rt::shims
diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp
index e925d3ee4..c7cfb76c0 100644
--- a/runtime/shims/xmem.cpp
+++ b/runtime/shims/xmem.cpp
@@ -10,6 +10,7 @@
10// site shows the alignment/type fields, every block is 64-byte aligned (covers cache lines and SIMD) and a size of 10// site shows the alignment/type fields, every block is 64-byte aligned (covers cache lines and SIMD) and a size of
11// zero is rounded up to one byte so the result is a stable, non-null pointer that XMemFree can release. 11// zero is rounded up to one byte so the result is a stable, non-null pointer that XMemFree can release.
12#include <windows.h> 12#include <windows.h>
13#include <intrin.h>
13#include <malloc.h> 14#include <malloc.h>
14#include <psapi.h> 15#include <psapi.h>
15 16
@@ -18,16 +19,46 @@
18#include <cstdio> 19#include <cstdio>
19#include <cstring> 20#include <cstring>
20#include <limits> 21#include <limits>
22#include <mutex>
23#include <set>
24#include <utility>
21 25
22#include "shims.h" 26#include "shims.h"
27#include "startup_trace.h"
23 28
24namespace { 29namespace {
25 30
26constexpr size_t kAlign = 64; 31constexpr size_t kAlign = 64;
27 32
28void* __stdcall XMemAlloc(size_t size, uint64_t /*attributes*/) { return _aligned_malloc(size ? size : 1, kAlign); } 33// gta6rt --trace FILE: the first XMemAlloc and the first XMemFree for each distinct raw attribute word go to the
34// startup trace as an "xmem_attributes" event (api, the word, the size for an allocation, the caller as module+RVA). The
35// bits of the attribute word are not known yet; this records them from a real run without logging every allocation,
36// which would fill the file. Off: one relaxed load per call.
37void note_attributes(bool is_alloc, uint64_t attributes, size_t size, const void* caller) {
38 if (!rt::startup_trace::enabled()) return;
39 static std::mutex mutex;
40 static std::set<std::pair<bool, uint64_t>> seen;
41 {
42 const std::lock_guard lock(mutex);
43 if (!seen.insert({is_alloc, attributes}).second) return;
44 }
45 std::string fields = std::string("\"api\":\"") + (is_alloc ? "XMemAlloc" : "XMemFree") +
46 "\",\"attributes\":" + rt::startup_trace::quote(rt::startup_trace::hex(attributes));
47 if (is_alloc) fields += ",\"size\":" + std::to_string(size);
48 fields += ",\"caller\":" +
49 rt::startup_trace::quote(rt::startup_trace::where(reinterpret_cast<uint64_t>(caller)));
50 rt::startup_trace::event("xmem_attributes", fields);
51}
29 52
30void __stdcall XMemFree(void* p, uint64_t /*attributes*/) { _aligned_free(p); } 53void* __stdcall XMemAlloc(size_t size, uint64_t attributes) {
54 note_attributes(true, attributes, size, _ReturnAddress());
55 return _aligned_malloc(size ? size : 1, kAlign);
56}
57
58void __stdcall XMemFree(void* p, uint64_t attributes) {
59 note_attributes(false, attributes, 0, _ReturnAddress());
60 _aligned_free(p);
61}
31 62
32// Measured call sites pass a zeroed 64-byte structure. Only the MEMORY_BASIC_INFORMATION-compatible prefix is 63// Measured call sites pass a zeroed 64-byte structure. Only the MEMORY_BASIC_INFORMATION-compatible prefix is
33// known: callers read at least the base and size fields. Fill that prefix from VirtualQueryEx and zero the rest. 64// known: callers read at least the base and size fields. Fill that prefix from VirtualQueryEx and zero the rest.
@@ -64,8 +95,10 @@ SIZE_T __stdcall XMemVirtualQuery(HANDLE process, const void* address, void* out
64// 0x75b1): ECX is the constant 0x20000001 (its meaning is not known) and RDX points at a stack buffer (0x80 bytes 95// 0x75b1): ECX is the constant 0x20000001 (its meaning is not known) and RDX points at a stack buffer (0x80 bytes
65// where the frame shows it). The caller reads a 64-bit size at +8 and treats a zero return as "no data". Taking the 96// where the frame shows it). The caller reads a 64-bit size at +8 and treats a zero return as "no data". Taking the
66// pointer from the first argument wrote to address 0x20000001. 97// pointer from the first argument wrote to address 0x20000001.
67// Only the first 16 bytes are touched: zero at +0 (unknown) and the process working set at +8. Do not claim more of 98// The measured FSR sites establish argument shape, kind and the 64-bit working-set read at +8; +0's title-total memory
68// the struct than is measured. 99// limit interpretation is inferred from other Series implementations (xcl, xbox-emulator) and title engine telemetry
100// sizing memory pools (RT-220). Note that if GlobalMemoryStatusEx reports 0 physical memory, XMem falls back to the
101// 12 GiB title limit, whereas XSystemGetAppMemoryUsageLimit remains 0.
69BOOL __stdcall XMemGetWorkingSetStatistics(uint32_t /*kind*/, void* stats) { 102BOOL __stdcall XMemGetWorkingSetStatistics(uint32_t /*kind*/, void* stats) {
70 if (!stats) { 103 if (!stats) {
71 static std::atomic<bool> warned{false}; 104 static std::atomic<bool> warned{false};
@@ -78,8 +111,15 @@ BOOL __stdcall XMemGetWorkingSetStatistics(uint32_t /*kind*/, void* stats) {
78 PROCESS_MEMORY_COUNTERS pmc{}; 111 PROCESS_MEMORY_COUNTERS pmc{};
79 if (!GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc))) return FALSE; 112 if (!GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc))) return FALSE;
80 113
114 MEMORYSTATUSEX ms{sizeof(ms)};
115 uint64_t total_memory = 12ULL * 1024 * 1024 * 1024;
116 if (GlobalMemoryStatusEx(&ms) && ms.ullTotalPhys != 0) {
117 total_memory = ms.ullTotalPhys;
118 }
119
81 uint8_t* bytes = static_cast<uint8_t*>(stats); 120 uint8_t* bytes = static_cast<uint8_t*>(stats);
82 std::memset(bytes, 0, 16); 121 std::memset(bytes, 0, 16);
122 std::memcpy(bytes + 0, &total_memory, sizeof(total_memory));
83 uint64_t working_set = pmc.WorkingSetSize; 123 uint64_t working_set = pmc.WorkingSetSize;
84 std::memcpy(bytes + 8, &working_set, sizeof(working_set)); 124 std::memcpy(bytes + 8, &working_set, sizeof(working_set));
85 return TRUE; 125 return TRUE;
diff --git a/runtime/src/active_input.h b/runtime/src/active_input.h
new file mode 100644
index 000000000..c0f7451b1
--- /dev/null
+++ b/runtime/src/active_input.h
@@ -0,0 +1,146 @@
1#pragma once
2
3// Which kind of input device the player used last: an Xbox-style pad, a PlayStation pad, a Nintendo pad or the
4// keyboard pad (docs/gameinput.md). The GameInput shim reports every pad to the title as an Xbox One pad, so the title
5// itself cannot tell; this is the port's own record, for whatever wants to follow the device in use (button prompt
6// glyphs first). No SDL, no Windows headers: the shim feeds it one sample per device per poll, and tests feed it
7// synthetic samples with their own times.
8//
9// The rules, chosen so that only deliberate input changes the answer:
10// * Only an edge counts: a button going down, a trigger rising past `trigger`, a stick leaving the `stick` radius.
11// A button held down, a trigger held, a stick held over, stick drift that stays inside the radius and analog
12// noise never count, so a pad lying on the desk cannot take over. The keyboard pad's right stick follows the
13// mouse, so a real mouse movement counts as keyboard input through the same stick rule.
14// * A device's first sample is its baseline and counts for nothing: a pad that connects with a button held or a
15// worn stick resting past the radius does not switch anything until it produces a new edge.
16// * After a change, another change waits until `min_switch_us` has passed. An edge from another family inside that
17// window is ignored (not queued), so two devices used at once cannot make the answer flicker.
18// * Edges from a device of the family already active change nothing.
19// * Before any edge the answer is `initial` (Xbox unless the caller says otherwise).
20// * A forced family (LEONIDA_PROMPTS) wins over all of this; the tracking still runs underneath, so clearing the
21// force goes straight back to the device in use.
22// `generation` counts changes of the answer (tracked or forced), so a reader can tell that something changed without
23// comparing families.
24
25#include <cmath>
26#include <cstdint>
27#include <optional>
28#include <unordered_map>
29
30namespace leonida {
31
32enum class InputFamily : std::uint8_t {
33 Xbox, // Xbox One/Series, Xbox 360, and any pad SDL does not know better (generic, unknown)
34 PlayStation5, // DualSense, DualSense Edge
35 PlayStation4, // DualShock 4
36 PlayStation3, // DualShock 3
37 Nintendo, // Switch Pro controller and Joy-Cons
38 Keyboard, // the keyboard pad: keyboard and mouse
39};
40
41inline const char* input_family_name(InputFamily f) {
42 switch (f) {
43 case InputFamily::Xbox: return "Xbox";
44 case InputFamily::PlayStation5: return "PlayStation 5";
45 case InputFamily::PlayStation4: return "PlayStation 4";
46 case InputFamily::PlayStation3: return "PlayStation 3";
47 case InputFamily::Nintendo: return "Nintendo";
48 case InputFamily::Keyboard: return "keyboard and mouse";
49 }
50 return "unknown";
51}
52
53// One device's state at one poll, in GameInput's units: sticks -1..1, triggers 0..1. `buttons` is any bit set per
54// pressed button (the shim passes the GameInput gamepad bits plus one bit for the guide button); only its changes
55// matter.
56struct InputSample {
57 std::uint32_t buttons = 0;
58 float left_trigger = 0, right_trigger = 0;
59 float left_x = 0, left_y = 0, right_x = 0, right_y = 0;
60};
61
62// What made the answer change, for the log line.
63enum class InputEdge : std::uint8_t { None, Button, Trigger, Stick };
64
65inline const char* input_edge_name(InputEdge e) {
66 switch (e) {
67 case InputEdge::None: return "none";
68 case InputEdge::Button: return "button press";
69 case InputEdge::Trigger: return "trigger pull";
70 case InputEdge::Stick: return "stick movement";
71 }
72 return "unknown";
73}
74
75class ActiveInputTracker {
76public:
77 struct Thresholds {
78 float stick = 0.35f; // radius a stick has to leave
79 float trigger = 0.3f; // a trigger has to rise past this
80 std::uint64_t min_switch_us = 300'000; // shortest time between two changes
81 };
82
83 explicit ActiveInputTracker(InputFamily initial = InputFamily::Xbox) : tracked_(initial) {}
84 ActiveInputTracker(InputFamily initial, Thresholds t) : thresholds_(t), tracked_(initial) {}
85
86 // One sample of one device (`device` is any key that stays the same while the device is connected). Returns the
87 // edge that changed the tracked family, or None when it did not change. With a family forced, the tracked family
88 // still follows the devices, but active() does not move.
89 InputEdge observe(std::uint64_t device, InputFamily family, const InputSample& now, std::uint64_t time_us) {
90 auto it = devices_.find(device);
91 if (it == devices_.end()) {
92 devices_.emplace(device, now); // the baseline: counts for nothing
93 return InputEdge::None;
94 }
95 const InputEdge edge = edge_between(it->second, now);
96 it->second = now;
97 if (edge == InputEdge::None || family == tracked_) return InputEdge::None;
98 if (changed_once_ && time_us - changed_at_ < thresholds_.min_switch_us) return InputEdge::None;
99 const InputFamily before = active();
100 tracked_ = family;
101 changed_at_ = time_us;
102 changed_once_ = true;
103 if (active() != before) ++generation_;
104 return edge;
105 }
106
107 // The device disconnected: its next sample, if it comes back, is a baseline again.
108 void forget(std::uint64_t device) { devices_.erase(device); }
109
110 // Forces the answer (a family) or returns to tracking (nullopt). Changing what active() returns bumps generation.
111 void force(std::optional<InputFamily> family) {
112 const InputFamily before = active();
113 forced_ = family;
114 if (active() != before) ++generation_;
115 }
116
117 InputFamily active() const { return forced_ ? *forced_ : tracked_; }
118 InputFamily tracked() const { return tracked_; }
119 bool forced() const { return forced_.has_value(); }
120 std::uint64_t generation() const { return generation_; }
121 const Thresholds& thresholds() const { return thresholds_; }
122 void set_thresholds(const Thresholds& t) { thresholds_ = t; }
123
124private:
125 InputEdge edge_between(const InputSample& was, const InputSample& now) const {
126 if (now.buttons & ~was.buttons) return InputEdge::Button;
127 const float t = thresholds_.trigger;
128 if ((was.left_trigger <= t && now.left_trigger > t) || (was.right_trigger <= t && now.right_trigger > t))
129 return InputEdge::Trigger;
130 const auto out = [this](float x, float y) { return std::hypot(x, y) > thresholds_.stick; };
131 if ((!out(was.left_x, was.left_y) && out(now.left_x, now.left_y)) ||
132 (!out(was.right_x, was.right_y) && out(now.right_x, now.right_y)))
133 return InputEdge::Stick;
134 return InputEdge::None;
135 }
136
137 Thresholds thresholds_{};
138 InputFamily tracked_;
139 std::optional<InputFamily> forced_;
140 std::uint64_t generation_ = 0;
141 std::uint64_t changed_at_ = 0;
142 bool changed_once_ = false;
143 std::unordered_map<std::uint64_t, InputSample> devices_;
144};
145
146} // namespace leonida
diff --git a/runtime/src/buffer_va_index.h b/runtime/src/buffer_va_index.h
index 5abab65df..5096771c7 100644
--- a/runtime/src/buffer_va_index.h
+++ b/runtime/src/buffer_va_index.h
@@ -5,9 +5,13 @@
5// every registered resource. No Vulkan or Windows dependency; not thread-safe (VulkanContext guards it with 5// every registered resource. No Vulkan or Windows dependency; not thread-safe (VulkanContext guards it with
6// resource_mutex_, like the bindings themselves). 6// resource_mutex_, like the bindings themselves).
7// 7//
8// D3D12 lets placed buffers alias, so ranges may overlap. A lookup then returns the containing range that starts 8// D3D12 lets placed buffers alias, so ranges may overlap. A lookup names the bytes it needs, [va, va + bytes), and
9// closest below the VA (the larger ID on a tie): the walk goes down from the nearest start and stops once no range can 9// returns, among the ranges that hold va, the one that starts closest below it (the larger ID on a tie) that also
10// still reach the VA, which `longest_` bounds. Without overlaps the first range it looks at is the answer, or none is. 10// holds all of those bytes; when none does, the closest one that holds va. So a view that starts in a small placed
11// buffer and runs past its end resolves to a larger buffer that aliases the same memory and holds all of it, instead
12// of being cut at the small one's end (found in review of #2823). The walk goes down from the nearest start and stops
13// once no range can still reach the VA, or, with a fallback found, once no range can still hold all the bytes; both
14// are bounded by `longest_`. Without overlaps the first range it looks at is the answer, or none is.
11// `longest_` is the longest range indexed now, not the longest ever: a large buffer that is freed stops lengthening 15// `longest_` is the longest range indexed now, not the longest ever: a large buffer that is freed stops lengthening
12// later misses. A miss still walks every start within the longest live range below the VA. 16// later misses. A miss still walks every start within the longest live range below the VA.
13 17
@@ -49,20 +53,29 @@ public:
49 std::uint64_t size; 53 std::uint64_t size;
50 }; 54 };
51 55
52 // The range that holds `va`; false when none does. 56 // The range that holds `va`, preferring one that holds [va, va + bytes) (bytes 0 counts as 1); false when none
53 bool find(std::uint64_t va, Hit& out) const { 57 // holds va.
58 bool find(std::uint64_t va, Hit& out, std::uint64_t bytes = 1) const {
59 if (!bytes) bytes = 1;
60 bool found = false; // `out` holds the closest range that holds va, though not all the bytes
54 auto it = ranges_.upper_bound({va, max_id()}); 61 auto it = ranges_.upper_bound({va, max_id()});
55 while (it != ranges_.begin()) { 62 while (it != ranges_.begin()) {
56 --it; 63 --it;
57 const std::uint64_t start = it->first.first; 64 const std::uint64_t start = it->first.first;
58 const std::uint64_t offset = va - start; // start <= va here 65 const std::uint64_t offset = va - start; // start <= va here; it only grows as the walk goes down
59 if (offset >= longest_) return false; // no range that starts this low reaches va 66 if (offset >= longest_) break; // no range that starts this low reaches va
60 if (offset < it->second) { 67 if (found && bytes > longest_ - offset) break; // nor holds all the bytes
68 if (offset >= it->second) continue;
69 if (bytes <= it->second - offset) {
61 out = {it->first.second, start, it->second}; 70 out = {it->first.second, start, it->second};
62 return true; 71 return true;
63 } 72 }
73 if (!found) {
74 out = {it->first.second, start, it->second};
75 found = true;
76 }
64 } 77 }
65 return false; 78 return found;
66 } 79 }
67 80
68 std::size_t size() const { return ranges_.size(); } 81 std::size_t size() const { return ranges_.size(); }
diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h
index fcdc1ca33..7e612e1eb 100644
--- a/runtime/src/command_list.h
+++ b/runtime/src/command_list.h
@@ -12,6 +12,7 @@
12#include <cstdint> 12#include <cstdint>
13#include <optional> 13#include <optional>
14#include <span> 14#include <span>
15#include <memory>
15#include <string> 16#include <string>
16#include <utility> 17#include <utility>
17#include <variant> 18#include <variant>
@@ -179,6 +180,11 @@ inline constexpr std::uint32_t video_decode_statistics = 8;
179inline constexpr std::uint32_t pipeline_statistics1 = 10; 180inline constexpr std::uint32_t pipeline_statistics1 = 10;
180} // namespace d3d12_query 181} // namespace d3d12_query
181 182
183// A stream-output statistics query (SO_STATISTICS_STREAM0..3).
184constexpr bool is_so_statistics(std::uint32_t query_type) {
185 return query_type >= d3d12_query::so_statistics_stream0 && query_type <= d3d12_query::so_statistics_stream3;
186}
187
182// Whether a heap of `heap_type` holds queries of `query_type` (the D3D12 pairing rules). 188// Whether a heap of `heap_type` holds queries of `query_type` (the D3D12 pairing rules).
183constexpr bool query_fits_heap(std::uint32_t heap_type, std::uint32_t query_type) { 189constexpr bool query_fits_heap(std::uint32_t heap_type, std::uint32_t query_type) {
184 namespace h = d3d12_query_heap; 190 namespace h = d3d12_query_heap;
@@ -196,7 +202,8 @@ constexpr bool query_fits_heap(std::uint32_t heap_type, std::uint32_t query_type
196} 202}
197 203
198// Bytes one resolved query takes: a UINT64 for occlusion and timestamps, D3D12_QUERY_DATA_PIPELINE_STATISTICS 204// Bytes one resolved query takes: a UINT64 for occlusion and timestamps, D3D12_QUERY_DATA_PIPELINE_STATISTICS
199// (11 UINT64s) for pipeline statistics. 0 for the types this layer does not resolve. 205// (11 UINT64s) for pipeline statistics, D3D12_QUERY_DATA_SO_STATISTICS (2 UINT64s) for stream output. 0 for the
206// types this layer does not resolve.
200constexpr std::uint32_t query_result_size(std::uint32_t query_type) { 207constexpr std::uint32_t query_result_size(std::uint32_t query_type) {
201 namespace q = d3d12_query; 208 namespace q = d3d12_query;
202 switch (query_type) { 209 switch (query_type) {
@@ -204,6 +211,11 @@ constexpr std::uint32_t query_result_size(std::uint32_t query_type) {
204 case q::binary_occlusion: 211 case q::binary_occlusion:
205 case q::timestamp: return 8; 212 case q::timestamp: return 8;
206 case q::pipeline_statistics: return 11 * 8; 213 case q::pipeline_statistics: return 11 * 8;
214 // D3D12_QUERY_DATA_SO_STATISTICS: NumPrimitivesWritten, PrimitivesStorageNeeded.
215 case q::so_statistics_stream0:
216 case q::so_statistics_stream0 + 1:
217 case q::so_statistics_stream0 + 2:
218 case q::so_statistics_stream3: return 2 * 8;
207 default: return 0; 219 default: return 0;
208 } 220 }
209} 221}
@@ -392,6 +404,15 @@ struct IndexBufferView {
392 std::uint32_t format; // DXGI_FORMAT_R16_UINT (57) or DXGI_FORMAT_R32_UINT (42) 404 std::uint32_t format; // DXGI_FORMAT_R16_UINT (57) or DXGI_FORMAT_R32_UINT (42)
393}; 405};
394 406
407// The views a draw captured, at the D3D12 maxima. Kept by value because the CPU descriptor slots and the bound
408// views can change after the draw is recorded, and out of line because the command variant is sized by its largest
409// member: inline they made every recorded command, barriers included, 976 bytes.
410struct DrawViews {
411 std::array<TargetView, 8> render_targets{};
412 std::array<VertexBufferView, 32> vertex_buffers{}; // by input slot
413 std::uint32_t render_target_count = 8;
414};
415
395// DrawInstanced / DrawIndexedInstanced, with everything they use captured when they are recorded: D3D12 reads 416// DrawInstanced / DrawIndexedInstanced, with everything they use captured when they are recorded: D3D12 reads
396// render-target and depth descriptors at OMSetRenderTargets, and every other piece of state is the list's state at 417// render-target and depth descriptors at OMSetRenderTargets, and every other piece of state is the list's state at
397// the draw. resource 0 marks an unbound render-target slot or no depth buffer. 418// the draw. resource 0 marks an unbound render-target slot or no depth buffer.
@@ -400,9 +421,8 @@ struct IndexBufferView {
400struct Draw { 421struct Draw {
401 std::uintptr_t pipeline = 0; 422 std::uintptr_t pipeline = 0;
402 std::array<std::uint32_t, 32> user_data{}; 423 std::array<std::uint32_t, 32> user_data{};
403 std::array<TargetView, 8> render_targets{}; 424 std::shared_ptr<const DrawViews> views; // null: no render targets or vertex buffers captured
404 TargetView depth{}; 425 TargetView depth{};
405 std::array<VertexBufferView, 32> vertex_buffers{}; // by input slot
406 IndexBufferView index{}; 426 IndexBufferView index{};
407 std::uint32_t topology = 0; // D3D_PRIMITIVE_TOPOLOGY 427 std::uint32_t topology = 0; // D3D_PRIMITIVE_TOPOLOGY
408 Viewport viewport{}; // the first; more viewports are not modelled yet 428 Viewport viewport{}; // the first; more viewports are not modelled yet
@@ -416,7 +436,6 @@ struct Draw {
416 std::uint32_t first = 0; // first vertex or first index 436 std::uint32_t first = 0; // first vertex or first index
417 std::int32_t base_vertex = 0; 437 std::int32_t base_vertex = 0;
418 std::uint32_t first_instance = 0; 438 std::uint32_t first_instance = 0;
419 std::uint32_t render_target_count = 8;
420}; 439};
421 440
422// D3D12_TEXTURE_DATA_PITCH_ALIGNMENT and D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT. 441// D3D12_TEXTURE_DATA_PITCH_ALIGNMENT and D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT.
diff --git a/runtime/src/depth24_fragment.h b/runtime/src/depth24_fragment.h
new file mode 100644
index 000000000..10f0dada8
--- /dev/null
+++ b/runtime/src/depth24_fragment.h
@@ -0,0 +1,445 @@
1#pragma once
2
3// D24_UNORM_S8_UINT on a GPU without D24 (the layer stores D32_SFLOAT_S8_UINT, depth24.h) in draws (D3D-309).
4//
5// Two D3D rules break when the depth attachment is float (found by @marquezinii, measured by @Vonsek on #291):
6// * the integer RasterizerState.DepthBias is in fixed D24 units, r = 1 / (2^24 - 1) ("the minimum representable
7// value > 0 in the depth-buffer format"), while Vulkan scales a float attachment's constant bias by the
8// primitive's exponent;
9// * clears are quantised to the D24 code (depth24_clear_value), fragment depth is not, so an EQUAL test at a
10// cleared value fails where D24 hardware passes.
11// The fix moves both into the pixel stage: the fragment writes FragDepth = quantise(z + bias), with z the rasterised
12// depth, bias = DepthBias * r + SlopeScaledDepthBias * max(|dz/dx|, |dz/dy|) clamped by DepthBiasClamp (D3D's
13// formula), and quantise = depth24_to_float(depth24_quantize(.)) from depth24_convert.comp, so a fragment holds
14// exactly the float a D24 code reads back as. The rasterizer's own bias is then turned off for the pipeline.
15// A shader that writes its own depth (SV_Depth) keeps its value, quantised; D3D applies no bias to it.
16//
17// depth24_patch_fragment edits a translated pixel shader's SPIR-V; depth24_depth_only_fragment builds the stage
18// for a pipeline without a pixel shader (depth-only passes such as shadow maps). Both are plain word editing with
19// no dependency beyond the standard library; d3d12_depth24_draw_test runs them (with LEONIDA_VK_VALIDATION=1 the
20// validation layer checks the modules).
21//
22// Not covered (logged by the caller): a pixel shader with EarlyFragmentTests (its FragDepth write would be ignored),
23// multisampled targets (FragDepth is per pixel, which would flatten per-sample depth), and a viewport depth range
24// narrower than the biased depth (D3D clamps to MinDepth..MaxDepth before quantising; the quantisation here clamps
25// to 0..1 and Vulkan's clamp to the viewport range follows it).
26
27#include <array>
28#include <cmath>
29#include <cstdint>
30#include <cstring>
31#include <string>
32#include <vector>
33
34namespace leonida {
35
36struct Depth24Bias {
37 int constant = 0; // D3D12_RASTERIZER_DESC::DepthBias
38 float slope = 0.0f; // SlopeScaledDepthBias
39 float clamp = 0.0f; // DepthBiasClamp: > 0 caps the bias, < 0 floors it, 0 leaves it
40 bool any() const { return constant != 0 || slope != 0.0f; }
41};
42
43// D3D's constant term in float: (float)DepthBias * r, with r the float nearest 1 / (2^24 - 1).
44inline float depth24_bias_constant(int bias) {
45 return float(bias) * float(1.0 / 16777215.0);
46}
47
48namespace spirv24 {
49
50enum : std::uint32_t {
51 op_name = 5, op_line = 8, op_ext_inst_import = 11, op_ext_inst = 12, op_memory_model = 14, op_entry_point = 15,
52 op_execution_mode = 16, op_capability = 17, op_type_void = 19, op_type_bool = 20, op_type_int = 21,
53 op_type_float = 22, op_type_vector = 23, op_type_pointer = 32, op_type_function = 33, op_constant = 43,
54 op_function = 54, op_function_end = 56, op_variable = 59, op_load = 61, op_store = 62, op_decorate = 71,
55 op_composite_extract = 81, op_convert_f_to_u = 109, op_convert_u_to_f = 112, op_bitcast = 124, op_i_add = 128,
56 op_f_add = 129, op_i_sub = 130, op_f_mul = 133, op_select = 169, op_i_equal = 170, op_u_greater_than = 172,
57 op_u_greater_than_equal = 174, op_shift_left_logical = 196, op_dpdx = 207, op_dpdy = 208, op_label = 248,
58 op_return = 253, op_no_line = 317, op_execution_mode_id = 331,
59};
60enum : std::uint32_t { storage_input = 1, storage_output = 3 };
61enum : std::uint32_t { decoration_builtin = 11, builtin_frag_coord = 15, builtin_frag_depth = 22 };
62enum : std::uint32_t { model_fragment = 4 };
63enum : std::uint32_t {
64 mode_origin_upper_left = 7, mode_early_fragment_tests = 9, mode_depth_replacing = 12, mode_depth_greater = 14,
65 mode_depth_less = 15, mode_depth_unchanged = 16,
66};
67enum : std::uint32_t { glsl_round_even = 2, glsl_fabs = 4, glsl_fmin = 37, glsl_fmax = 40, glsl_find_umsb = 75 };
68
69using Inst = std::vector<std::uint32_t>; // a whole instruction, word 0 included
70
71inline std::uint32_t opcode(const Inst& i) { return i[0] & 0xffffu; }
72inline Inst make(std::uint32_t op, std::initializer_list<std::uint32_t> operands) {
73 Inst i;
74 i.reserve(operands.size() + 1);
75 i.push_back(std::uint32_t(operands.size() + 1) << 16 | op);
76 i.insert(i.end(), operands.begin(), operands.end());
77 return i;
78}
79inline void append_string(Inst& i, const char* s) {
80 const std::size_t n = std::strlen(s) + 1, words = (n + 3) / 4;
81 const std::size_t at = i.size();
82 i.resize(at + words, 0);
83 std::memcpy(&i[at], s, n);
84}
85inline void fix_length(Inst& i) { i[0] = std::uint32_t(i.size()) << 16 | opcode(i); }
86inline std::uint32_t bits(float f) {
87 std::uint32_t u;
88 std::memcpy(&u, &f, 4);
89 return u;
90}
91// Words a literal string takes in an instruction, starting at `at`.
92inline std::size_t string_words(const Inst& i, std::size_t at) {
93 std::size_t w = at;
94 while (w < i.size()) {
95 const std::uint32_t word = i[w++];
96 if ((word & 0xff000000u) == 0 || (word & 0x00ff0000u) == 0 || (word & 0x0000ff00u) == 0 ||
97 (word & 0x000000ffu) == 0)
98 break;
99 }
100 return w - at;
101}
102
103inline bool is_global_decl(std::uint32_t op) {
104 return op == 1 /* OpUndef */ || (op >= op_type_void && op <= 39) || (op >= 41 && op <= 52) || op == op_variable;
105}
106
107class Module {
108public:
109 bool parse(const std::vector<std::uint32_t>& words, std::string& why) {
110 if (words.size() < 5 || words[0] != 0x07230203u) {
111 why = "not a SPIR-V module";
112 return false;
113 }
114 header_.assign(words.begin(), words.begin() + 5);
115 for (std::size_t w = 5; w < words.size();) {
116 const std::uint32_t count = words[w] >> 16;
117 if (count == 0 || w + count > words.size()) {
118 why = "truncated instruction";
119 return false;
120 }
121 insts_.emplace_back(words.begin() + std::ptrdiff_t(w), words.begin() + std::ptrdiff_t(w + count));
122 w += count;
123 }
124 return true;
125 }
126 std::vector<std::uint32_t> words() const {
127 std::vector<std::uint32_t> out = header_;
128 for (const Inst& i : insts_) out.insert(out.end(), i.begin(), i.end());
129 return out;
130 }
131 std::uint32_t fresh() { return header_[3]++; }
132 std::uint32_t version() const { return header_[1]; }
133 std::vector<Inst>& insts() { return insts_; }
134 std::vector<std::uint32_t>& header() { return header_; }
135
136private:
137 std::vector<std::uint32_t> header_;
138 std::vector<Inst> insts_;
139};
140
141// The edit, on a parsed module. Globals are collected first and spliced in at their section's end.
142class Patch {
143public:
144 Patch(Module& m, std::uint32_t entry) : m_(m), entry_(entry) {
145 // Copies: apply() moves the module's instructions while the code at returns still looks types up.
146 for (const Inst& i : m.insts()) {
147 if (opcode(i) == op_function) break;
148 existing_.push_back(i);
149 }
150 }
151
152 // A type, reused when the module already declares it (SPIR-V forbids duplicate non-aggregate types).
153 std::uint32_t type(std::uint32_t op, std::initializer_list<std::uint32_t> operands) {
154 auto same = [&](const Inst& i) {
155 if (opcode(i) != op || i.size() != operands.size() + 2) return false;
156 std::size_t k = 2;
157 for (std::uint32_t o : operands)
158 if (i[k++] != o) return false;
159 return true;
160 };
161 for (const Inst& ex : existing_)
162 if (same(ex)) return ex[1];
163 for (const Inst& i : globals_)
164 if (same(i)) return i[1];
165 const std::uint32_t id = m_.fresh();
166 Inst i = make(op, {id});
167 i.insert(i.end(), operands.begin(), operands.end());
168 fix_length(i);
169 globals_.push_back(std::move(i));
170 return id;
171 }
172 std::uint32_t t_float() { return type(op_type_float, {32}); }
173 std::uint32_t t_uint() { return type(op_type_int, {32, 0}); }
174 std::uint32_t t_bool() { return type(op_type_bool, {}); }
175 // Constants are cached by type and value: all of them are declared before apply() writes the globals out.
176 std::uint32_t constant(std::uint32_t t, std::uint32_t value) {
177 for (const auto& c : constants_)
178 if (c[0] == t && c[1] == value) return c[2];
179 const std::uint32_t id = m_.fresh();
180 globals_.push_back(make(op_constant, {t, id, value}));
181 constants_.push_back({t, value, id});
182 return id;
183 }
184 // Declares what quantise() uses, so it can run inside apply() (at returns) without adding globals.
185 void prime_quantise() {
186 t_bool();
187 glsl();
188 for (float f : {16777215.0f, 0.0f}) f32(f);
189 for (std::uint32_t u : {0x3f800000u, 0xffffffu, 0x7f800000u, 0u, 23u, 1u, 80u}) u32(u);
190 }
191 std::uint32_t f32(float f) { return constant(t_float(), bits(f)); }
192 std::uint32_t u32(std::uint32_t u) { return constant(t_uint(), u); }
193
194 std::uint32_t glsl() {
195 if (glsl_) return glsl_;
196 for (const Inst& ex : existing_) {
197 if (opcode(ex) != op_ext_inst_import || ex.size() < 3) continue;
198 std::string name((ex.size() - 2) * 4, '\0');
199 std::memcpy(name.data(), &ex[2], name.size());
200 if (std::strcmp(name.c_str(), "GLSL.std.450") == 0) return glsl_ = ex[1];
201 }
202 glsl_ = m_.fresh();
203 Inst i = make(op_ext_inst_import, {glsl_});
204 append_string(i, "GLSL.std.450");
205 fix_length(i);
206 import_ = std::move(i);
207 return glsl_;
208 }
209
210 // A built-in variable already decorated in the module, or 0.
211 std::uint32_t builtin_variable(std::uint32_t builtin) const {
212 for (const Inst& ex : existing_)
213 if (opcode(ex) == op_decorate && ex.size() == 4 && ex[2] == decoration_builtin && ex[3] == builtin)
214 return ex[1];
215 return 0;
216 }
217 std::uint32_t variable(std::uint32_t pointer_type, std::uint32_t storage, std::uint32_t builtin) {
218 const std::uint32_t id = m_.fresh();
219 globals_.push_back(make(op_variable, {pointer_type, id, storage}));
220 decorations_.push_back(make(op_decorate, {id, decoration_builtin, builtin}));
221 interface_.push_back(id);
222 return id;
223 }
224 void ensure_interface(std::uint32_t id) { interface_.push_back(id); }
225 void mode(std::uint32_t m) { modes_.push_back(make(op_execution_mode, {entry_, m})); }
226
227 // Instructions in a function body: emit returns the result id.
228 std::uint32_t emit(std::vector<Inst>& code, std::uint32_t op, std::uint32_t type,
229 std::initializer_list<std::uint32_t> operands) {
230 const std::uint32_t id = m_.fresh();
231 Inst i = make(op, {type, id});
232 i.insert(i.end(), operands.begin(), operands.end());
233 fix_length(i);
234 code.push_back(std::move(i));
235 return id;
236 }
237 std::uint32_t ext(std::vector<Inst>& code, std::uint32_t type, std::uint32_t inst,
238 std::initializer_list<std::uint32_t> operands) {
239 const std::uint32_t id = m_.fresh();
240 Inst i = make(op_ext_inst, {type, id, glsl(), inst});
241 i.insert(i.end(), operands.begin(), operands.end());
242 fix_length(i);
243 code.push_back(std::move(i));
244 return id;
245 }
246
247 // depth24_to_float(depth24_from_bits(z)) of depth24_convert.comp, branch-free.
248 std::uint32_t quantise(std::vector<Inst>& code, std::uint32_t z) {
249 const std::uint32_t tf = t_float(), tu = t_uint(), tb = t_bool();
250 const std::uint32_t b = emit(code, op_bitcast, tu, {z});
251 const std::uint32_t product = emit(code, op_f_mul, tf, {z, f32(16777215.0f)});
252 const std::uint32_t rounded = ext(code, tf, glsl_round_even, {product});
253 // Clamped before the conversion so an out-of-range float never reaches OpConvertFToU (undefined there).
254 const std::uint32_t safe = ext(code, tf, glsl_fmin, {ext(code, tf, glsl_fmax, {rounded, f32(0.0f)}),
255 f32(16777215.0f)});
256 const std::uint32_t code_mid = emit(code, op_convert_f_to_u, tu, {safe});
257 const std::uint32_t at_least_one = emit(code, op_u_greater_than_equal, tb, {b, u32(0x3f800000u)});
258 const std::uint32_t code_hi = emit(code, op_select, tu, {at_least_one, u32(0xffffffu), code_mid});
259 const std::uint32_t negative_or_nan = emit(code, op_u_greater_than, tb, {b, u32(0x7f800000u)});
260 const std::uint32_t d = emit(code, op_select, tu, {negative_or_nan, u32(0), code_hi});
261 // float(m + 1) * 2^(e - 47) with e = findMSB(d) and m = d << (23 - e); d == 0 gives 0.
262 const std::uint32_t e = ext(code, tu, glsl_find_umsb, {d});
263 const std::uint32_t m = emit(code, op_shift_left_logical, tu, {d, emit(code, op_i_sub, tu, {u32(23), e})});
264 const std::uint32_t mf = emit(code, op_convert_u_to_f, tf, {emit(code, op_i_add, tu, {m, u32(1)})});
265 const std::uint32_t exponent = emit(code, op_shift_left_logical, tu, {emit(code, op_i_add, tu, {e, u32(80)}),
266 u32(23)});
267 const std::uint32_t scale = emit(code, op_bitcast, tf, {exponent});
268 const std::uint32_t value = emit(code, op_f_mul, tf, {mf, scale});
269 const std::uint32_t zero = emit(code, op_i_equal, tb, {d, u32(0)});
270 return emit(code, op_select, tf, {zero, f32(0.0f), value});
271 }
272
273 // Splices everything into the module.
274 void apply(std::vector<Inst> entry_code, std::vector<Inst> (*at_return)(Patch&, void*), void* ctx,
275 bool drop_conservative_modes) {
276 auto& in = m_.insts();
277 std::size_t last_entry_point = 0;
278 for (std::size_t k = 0; k < in.size(); ++k)
279 if (opcode(in[k]) == op_entry_point) last_entry_point = k;
280 std::vector<Inst> out;
281 out.reserve(in.size() + globals_.size() + entry_code.size() + 16);
282 bool imported = import_.empty(), decorated = false, declared = false;
283 bool in_main = false, entry_done = false;
284 for (std::size_t k = 0; k < in.size(); ++k) {
285 Inst& i = in[k];
286 const std::uint32_t op = opcode(i);
287 if (!imported && op == op_memory_model) {
288 out.push_back(std::move(import_));
289 imported = true;
290 }
291 if (op == op_execution_mode && i.size() >= 3 && i[1] == entry_ && drop_conservative_modes &&
292 (i[2] == mode_depth_greater || i[2] == mode_depth_less || i[2] == mode_depth_unchanged ||
293 i[2] == mode_depth_replacing))
294 continue; // replaced by the DepthReplacing in modes_
295 if (op == op_entry_point && i.size() > 2 && i[2] == entry_) {
296 const std::size_t names = 3 + string_words(i, 3);
297 for (std::uint32_t id : interface_) {
298 bool listed = false;
299 for (std::size_t w = names; w < i.size(); ++w) listed |= i[w] == id;
300 if (!listed) i.push_back(id);
301 }
302 fix_length(i);
303 }
304 if (!decorated && (is_global_decl(op) || op == op_function)) {
305 for (Inst& d : decorations_) out.push_back(std::move(d));
306 decorated = true;
307 }
308 if (!declared && op == op_function) {
309 for (const Inst& g : globals_) out.push_back(g); // copies: type() may still read them
310 declared = true;
311 }
312 if (op == op_function && i.size() > 2 && i[2] == entry_) in_main = true;
313 if (in_main && !entry_done && op != op_function && op != op_label && op != op_variable &&
314 op != op_line && op != op_no_line && op != 55 /* OpFunctionParameter */) {
315 for (Inst& c : entry_code) out.push_back(std::move(c));
316 entry_done = true;
317 }
318 if (in_main && op == op_return && at_return) {
319 for (Inst& c : at_return(*this, ctx)) out.push_back(std::move(c));
320 }
321 if (op == op_function_end) in_main = false;
322 out.push_back(std::move(i));
323 if (k == last_entry_point) // execution modes follow the entry points
324 for (Inst& mo : modes_) out.push_back(std::move(mo));
325 }
326 in = std::move(out);
327 }
328
329private:
330 Module& m_;
331 std::uint32_t entry_;
332 std::vector<Inst> existing_;
333 std::vector<Inst> globals_, decorations_, modes_;
334 Inst import_;
335 std::vector<std::uint32_t> interface_;
336 std::vector<std::array<std::uint32_t, 3>> constants_; // type, value, id
337 std::uint32_t glsl_ = 0;
338};
339
340} // namespace spirv24
341
342// Edits a pixel shader so it writes the D24-quantised (and, unless it writes depth itself, D3D-biased) depth.
343// Returns the new words, or an empty vector with `why` set when the shader can't take the edit.
344inline std::vector<std::uint32_t> depth24_patch_fragment(const std::vector<std::uint32_t>& words,
345 const Depth24Bias& bias, std::string& why) {
346 using namespace spirv24;
347 Module m;
348 if (!m.parse(words, why)) return {};
349 std::uint32_t entry = 0;
350 for (const Inst& i : m.insts()) {
351 if (opcode(i) == op_entry_point && i.size() > 2 && i[1] == model_fragment) {
352 if (entry) {
353 why = "more than one fragment entry point";
354 return {};
355 }
356 entry = i[2];
357 }
358 if (opcode(i) == op_function) break;
359 }
360 if (!entry) {
361 why = "no fragment entry point";
362 return {};
363 }
364 for (const Inst& i : m.insts()) {
365 if (opcode(i) == op_execution_mode && i.size() >= 3 && i[1] == entry && i[2] == mode_early_fragment_tests) {
366 why = "the shader forces early fragment tests, which ignore a FragDepth write";
367 return {};
368 }
369 if (opcode(i) == op_function) break;
370 }
371
372 Patch p(m, entry);
373 const std::uint32_t tf = p.t_float();
374 p.prime_quantise();
375 std::uint32_t frag_depth = p.builtin_variable(builtin_frag_depth);
376 const bool shader_writes_depth = frag_depth != 0;
377 if (!shader_writes_depth)
378 frag_depth = p.variable(p.type(op_type_pointer, {storage_output, tf}), storage_output, builtin_frag_depth);
379 else
380 p.ensure_interface(frag_depth);
381 p.mode(mode_depth_replacing);
382
383 std::vector<Inst> entry_code;
384 if (!shader_writes_depth) {
385 std::uint32_t frag_coord = p.builtin_variable(builtin_frag_coord);
386 const std::uint32_t tv4 = p.type(op_type_vector, {tf, 4});
387 if (!frag_coord)
388 frag_coord = p.variable(p.type(op_type_pointer, {storage_input, tv4}), storage_input, builtin_frag_coord);
389 else
390 p.ensure_interface(frag_coord);
391 const std::uint32_t coord = p.emit(entry_code, op_load, tv4, {frag_coord});
392 std::uint32_t z = p.emit(entry_code, op_composite_extract, tf, {coord, 2});
393 if (bias.any()) {
394 // In the entry block: uniform control flow, so the derivatives are defined.
395 const std::uint32_t dx = p.ext(entry_code, tf, glsl_fabs, {p.emit(entry_code, op_dpdx, tf, {z})});
396 const std::uint32_t dy = p.ext(entry_code, tf, glsl_fabs, {p.emit(entry_code, op_dpdy, tf, {z})});
397 const std::uint32_t max_slope = p.ext(entry_code, tf, glsl_fmax, {dx, dy});
398 std::uint32_t amount = p.emit(entry_code, op_f_mul, tf, {p.f32(bias.slope), max_slope});
399 amount = p.emit(entry_code, op_f_add, tf, {amount, p.f32(depth24_bias_constant(bias.constant))});
400 if (bias.clamp > 0.0f) amount = p.ext(entry_code, tf, glsl_fmin, {amount, p.f32(bias.clamp)});
401 if (bias.clamp < 0.0f) amount = p.ext(entry_code, tf, glsl_fmax, {amount, p.f32(bias.clamp)});
402 z = p.emit(entry_code, op_f_add, tf, {z, amount});
403 }
404 const std::uint32_t q = p.quantise(entry_code, z);
405 entry_code.push_back(make(op_store, {frag_depth, q}));
406 p.apply(std::move(entry_code), nullptr, nullptr, true);
407 } else {
408 struct Ctx { std::uint32_t var, tf; } ctx{frag_depth, tf};
409 p.apply({}, [](Patch& patch, void* c) {
410 const auto& x = *static_cast<Ctx*>(c);
411 std::vector<Inst> code;
412 const std::uint32_t written = patch.emit(code, op_load, x.tf, {x.var});
413 code.push_back(make(op_store, {x.var, patch.quantise(code, written)}));
414 return code;
415 }, &ctx, true);
416 }
417 return m.words();
418}
419
420// A pixel stage for a pipeline without one: no colour output, only the biased, quantised depth.
421inline std::vector<std::uint32_t> depth24_depth_only_fragment(const Depth24Bias& bias) {
422 using namespace spirv24;
423 // OpCapability Shader; OpMemoryModel Logical GLSL450; OpEntryPoint Fragment %main "main";
424 // OpExecutionMode %main OriginUpperLeft; %void; %fn = void(); %main = function { label; return }
425 enum : std::uint32_t { id_main = 1, id_void = 2, id_fn = 3, id_label = 4, bound = 5 };
426 std::vector<std::uint32_t> w = {0x07230203u, 0x00010000u, 0, bound, 0};
427 auto put = [&](Inst i) { w.insert(w.end(), i.begin(), i.end()); };
428 put(make(op_capability, {1}));
429 put(make(op_memory_model, {0, 1}));
430 Inst ep = make(op_entry_point, {model_fragment, id_main});
431 append_string(ep, "main");
432 fix_length(ep);
433 put(ep);
434 put(make(op_execution_mode, {id_main, mode_origin_upper_left}));
435 put(make(op_type_void, {id_void}));
436 put(make(op_type_function, {id_fn, id_void}));
437 put(make(op_function, {id_void, id_main, 0, id_fn}));
438 put(make(op_label, {id_label}));
439 put(make(op_return, {}));
440 put(make(op_function_end, {}));
441 std::string why;
442 return depth24_patch_fragment(w, bias, why);
443}
444
445} // namespace leonida
diff --git a/runtime/src/gfx10_descriptors.h b/runtime/src/gfx10_descriptors.h
index 537f81623..b225cddef 100644
--- a/runtime/src/gfx10_descriptors.h
+++ b/runtime/src/gfx10_descriptors.h
@@ -630,6 +630,15 @@ inline VkSamplerCreateInfo vulkan_sampler(const Sampler& sampler, float max_lod_
630 } 630 }
631 if (sampler.unnormalized) { 631 if (sampler.unnormalized) {
632 info.unnormalizedCoordinates = VK_TRUE; 632 info.unnormalizedCoordinates = VK_TRUE;
633 // VUID-VkSamplerCreateInfo-unnormalizedCoordinates-01075: U and V clamp to the edge or the border (a
634 // repeating mode would wrap at a texel count the sampler cannot know); -01072: one filter for min and mag.
635 // The S# allows any address mode with FORCE_UNNORMALIZED, and WRAP is its default (word 0 = 0).
636 const auto clamp_or_border = [](VkSamplerAddressMode m) {
637 return m == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ? m : VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
638 };
639 info.addressModeU = clamp_or_border(info.addressModeU);
640 info.addressModeV = clamp_or_border(info.addressModeV);
641 info.minFilter = info.magFilter;
633 info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; 642 info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST;
634 info.minLod = info.maxLod = 0.0f; 643 info.minLod = info.maxLod = 0.0f;
635 info.anisotropyEnable = VK_FALSE; 644 info.anisotropyEnable = VK_FALSE;
diff --git a/runtime/src/indirect_dispatch_count.comp b/runtime/src/indirect_dispatch_count.comp
new file mode 100644
index 000000000..9cbc371d9
--- /dev/null
+++ b/runtime/src/indirect_dispatch_count.comp
@@ -0,0 +1,34 @@
1// Clamp a GPU-written D3D12 ExecuteIndirect DISPATCH count without reading it on the CPU.
2// Each record is a VkDispatchIndirectCommand (three uints); disabled records are zero.
3#version 460
4#extension GL_EXT_buffer_reference : require
5layout(local_size_x = 64) in;
6layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer WordsIn {
7 uint data[];
8};
9layout(buffer_reference, std430, buffer_reference_align = 4) buffer WordsOut {
10 uint data[];
11};
12layout(push_constant) uniform Params {
13 WordsIn arguments;
14 WordsIn count;
15 WordsOut output_words;
16 uint stride_words;
17 uint first_record;
18 uint records;
19} p;
20void main() {
21 const uint local_record = gl_GlobalInvocationID.x;
22 if (local_record >= p.records) return;
23 const uint target = local_record * 3u;
24 if (p.first_record + local_record < p.count.data[0]) {
25 const uint source = local_record * p.stride_words;
26 p.output_words.data[target] = p.arguments.data[source];
27 p.output_words.data[target + 1u] = p.arguments.data[source + 1u];
28 p.output_words.data[target + 2u] = p.arguments.data[source + 2u];
29 } else {
30 p.output_words.data[target] = 0u;
31 p.output_words.data[target + 1u] = 0u;
32 p.output_words.data[target + 2u] = 0u;
33 }
34}
diff --git a/runtime/src/indirect_dispatch_count_spv.h b/runtime/src/indirect_dispatch_count_spv.h
new file mode 100644
index 000000000..9cf7bbae5
--- /dev/null
+++ b/runtime/src/indirect_dispatch_count_spv.h
@@ -0,0 +1,84 @@
1// Generated with glslangValidator -V --target-env vulkan1.2 -Os --spirv-val indirect_dispatch_count.comp
2#pragma once
3#include <cstdint>
4namespace leonida {
5inline constexpr std::uint32_t indirect_dispatch_count_spirv[] = {
6 0x07230203u, 0x00010500u, 0x0008000bu, 0x00000074u, 0x00000000u, 0x00020011u, 0x00000001u, 0x00020011u,
7 0x000014e3u, 0x0006000bu, 0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu,
8 0x000014e4u, 0x00000001u, 0x0007000fu, 0x00000005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x0000000bu,
9 0x00000019u, 0x00060010u, 0x00000004u, 0x00000011u, 0x00000040u, 0x00000001u, 0x00000001u, 0x00030003u,
10 0x00000002u, 0x000001ccu, 0x00070004u, 0x455f4c47u, 0x625f5458u, 0x65666675u, 0x65725f72u, 0x65726566u,
11 0x0065636eu, 0x00040005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00080005u, 0x0000000bu, 0x475f6c67u,
12 0x61626f6cu, 0x766e496cu, 0x7461636fu, 0x496e6f69u, 0x00000044u, 0x00040005u, 0x00000013u, 0x61726150u,
13 0x0000736du, 0x00060006u, 0x00000013u, 0x00000000u, 0x75677261u, 0x746e656du, 0x00000073u, 0x00050006u,
14 0x00000013u, 0x00000001u, 0x6e756f63u, 0x00000074u, 0x00070006u, 0x00000013u, 0x00000002u, 0x7074756fu,
15 0x775f7475u, 0x7364726fu, 0x00000000u, 0x00070006u, 0x00000013u, 0x00000003u, 0x69727473u, 0x775f6564u,
16 0x7364726fu, 0x00000000u, 0x00070006u, 0x00000013u, 0x00000004u, 0x73726966u, 0x65725f74u, 0x64726f63u,
17 0x00000000u, 0x00050006u, 0x00000013u, 0x00000005u, 0x6f636572u, 0x00736472u, 0x00040005u, 0x00000015u,
18 0x64726f57u, 0x006e4973u, 0x00050006u, 0x00000015u, 0x00000000u, 0x61746164u, 0x00000000u, 0x00050005u,
19 0x00000017u, 0x64726f57u, 0x74754f73u, 0x00000000u, 0x00050006u, 0x00000017u, 0x00000000u, 0x61746164u,
20 0x00000000u, 0x00030005u, 0x00000019u, 0x00000070u, 0x00040047u, 0x0000000bu, 0x0000000bu, 0x0000001cu,
21 0x00030047u, 0x00000013u, 0x00000002u, 0x00050048u, 0x00000013u, 0x00000000u, 0x00000023u, 0x00000000u,
22 0x00050048u, 0x00000013u, 0x00000001u, 0x00000023u, 0x00000008u, 0x00050048u, 0x00000013u, 0x00000002u,
23 0x00000023u, 0x00000010u, 0x00050048u, 0x00000013u, 0x00000003u, 0x00000023u, 0x00000018u, 0x00050048u,
24 0x00000013u, 0x00000004u, 0x00000023u, 0x0000001cu, 0x00050048u, 0x00000013u, 0x00000005u, 0x00000023u,
25 0x00000020u, 0x00040047u, 0x00000014u, 0x00000006u, 0x00000004u, 0x00030047u, 0x00000015u, 0x00000002u,
26 0x00040048u, 0x00000015u, 0x00000000u, 0x00000018u, 0x00050048u, 0x00000015u, 0x00000000u, 0x00000023u,
27 0x00000000u, 0x00040047u, 0x00000016u, 0x00000006u, 0x00000004u, 0x00030047u, 0x00000017u, 0x00000002u,
28 0x00050048u, 0x00000017u, 0x00000000u, 0x00000023u, 0x00000000u, 0x00040047u, 0x00000071u, 0x0000000bu,
29 0x00000019u, 0x00020013u, 0x00000002u, 0x00030021u, 0x00000003u, 0x00000002u, 0x00040015u, 0x00000006u,
30 0x00000020u, 0x00000000u, 0x00040017u, 0x00000009u, 0x00000006u, 0x00000003u, 0x00040020u, 0x0000000au,
31 0x00000001u, 0x00000009u, 0x0004003bu, 0x0000000au, 0x0000000bu, 0x00000001u, 0x0004002bu, 0x00000006u,
32 0x0000000cu, 0x00000000u, 0x00040020u, 0x0000000du, 0x00000001u, 0x00000006u, 0x00030027u, 0x00000011u,
33 0x000014e5u, 0x00030027u, 0x00000012u, 0x000014e5u, 0x0008001eu, 0x00000013u, 0x00000011u, 0x00000011u,
34 0x00000012u, 0x00000006u, 0x00000006u, 0x00000006u, 0x0003001du, 0x00000014u, 0x00000006u, 0x0003001eu,
35 0x00000015u, 0x00000014u, 0x00040020u, 0x00000011u, 0x000014e5u, 0x00000015u, 0x0003001du, 0x00000016u,
36 0x00000006u, 0x0003001eu, 0x00000017u, 0x00000016u, 0x00040020u, 0x00000012u, 0x000014e5u, 0x00000017u,
37 0x00040020u, 0x00000018u, 0x00000009u, 0x00000013u, 0x0004003bu, 0x00000018u, 0x00000019u, 0x00000009u,
38 0x00040015u, 0x0000001au, 0x00000020u, 0x00000001u, 0x0004002bu, 0x0000001au, 0x0000001bu, 0x00000005u,
39 0x00040020u, 0x0000001cu, 0x00000009u, 0x00000006u, 0x00020014u, 0x0000001fu, 0x0004002bu, 0x00000006u,
40 0x00000026u, 0x00000003u, 0x0004002bu, 0x0000001au, 0x00000028u, 0x00000004u, 0x0004002bu, 0x0000001au,
41 0x0000002du, 0x00000001u, 0x00040020u, 0x0000002eu, 0x00000009u, 0x00000011u, 0x0004002bu, 0x0000001au,
42 0x00000031u, 0x00000000u, 0x00040020u, 0x00000032u, 0x000014e5u, 0x00000006u, 0x0004002bu, 0x0000001au,
43 0x0000003au, 0x00000003u, 0x0004002bu, 0x0000001au, 0x0000003eu, 0x00000002u, 0x00040020u, 0x0000003fu,
44 0x00000009u, 0x00000012u, 0x0004002bu, 0x00000006u, 0x0000004cu, 0x00000001u, 0x0004002bu, 0x00000006u,
45 0x00000058u, 0x00000002u, 0x0004002bu, 0x00000006u, 0x00000070u, 0x00000040u, 0x0006002cu, 0x00000009u,
46 0x00000071u, 0x00000070u, 0x0000004cu, 0x0000004cu, 0x00050036u, 0x00000002u, 0x00000004u, 0x00000000u,
47 0x00000003u, 0x000200f8u, 0x00000005u, 0x000300f7u, 0x00000072u, 0x00000000u, 0x000300fbu, 0x0000000cu,
48 0x00000073u, 0x000200f8u, 0x00000073u, 0x00050041u, 0x0000000du, 0x0000000eu, 0x0000000bu, 0x0000000cu,
49 0x0004003du, 0x00000006u, 0x0000000fu, 0x0000000eu, 0x00050041u, 0x0000001cu, 0x0000001du, 0x00000019u,
50 0x0000001bu, 0x0004003du, 0x00000006u, 0x0000001eu, 0x0000001du, 0x000500aeu, 0x0000001fu, 0x00000020u,
51 0x0000000fu, 0x0000001eu, 0x000300f7u, 0x00000022u, 0x00000000u, 0x000400fau, 0x00000020u, 0x00000021u,
52 0x00000022u, 0x000200f8u, 0x00000021u, 0x000200f9u, 0x00000072u, 0x000200f8u, 0x00000022u, 0x00050084u,
53 0x00000006u, 0x00000027u, 0x0000000fu, 0x00000026u, 0x00050041u, 0x0000001cu, 0x00000029u, 0x00000019u,
54 0x00000028u, 0x0004003du, 0x00000006u, 0x0000002au, 0x00000029u, 0x00050080u, 0x00000006u, 0x0000002cu,
55 0x0000002au, 0x0000000fu, 0x00050041u, 0x0000002eu, 0x0000002fu, 0x00000019u, 0x0000002du, 0x0004003du,
56 0x00000011u, 0x00000030u, 0x0000002fu, 0x00060041u, 0x00000032u, 0x00000033u, 0x00000030u, 0x00000031u,
57 0x00000031u, 0x0006003du, 0x00000006u, 0x00000034u, 0x00000033u, 0x00000002u, 0x00000004u, 0x000500b0u,
58 0x0000001fu, 0x00000035u, 0x0000002cu, 0x00000034u, 0x000300f7u, 0x00000037u, 0x00000000u, 0x000400fau,
59 0x00000035u, 0x00000036u, 0x00000061u, 0x000200f8u, 0x00000036u, 0x00050041u, 0x0000001cu, 0x0000003bu,
60 0x00000019u, 0x0000003au, 0x0004003du, 0x00000006u, 0x0000003cu, 0x0000003bu, 0x00050084u, 0x00000006u,
61 0x0000003du, 0x0000000fu, 0x0000003cu, 0x00050041u, 0x0000003fu, 0x00000040u, 0x00000019u, 0x0000003eu,
62 0x0004003du, 0x00000012u, 0x00000041u, 0x00000040u, 0x00050041u, 0x0000002eu, 0x00000043u, 0x00000019u,
63 0x00000031u, 0x0004003du, 0x00000011u, 0x00000044u, 0x00000043u, 0x00060041u, 0x00000032u, 0x00000046u,
64 0x00000044u, 0x00000031u, 0x0000003du, 0x0006003du, 0x00000006u, 0x00000047u, 0x00000046u, 0x00000002u,
65 0x00000004u, 0x00060041u, 0x00000032u, 0x00000048u, 0x00000041u, 0x00000031u, 0x00000027u, 0x0005003eu,
66 0x00000048u, 0x00000047u, 0x00000002u, 0x00000004u, 0x00050080u, 0x00000006u, 0x0000004du, 0x00000027u,
67 0x0000004cu, 0x00050080u, 0x00000006u, 0x00000051u, 0x0000003du, 0x0000004cu, 0x00060041u, 0x00000032u,
68 0x00000052u, 0x00000044u, 0x00000031u, 0x00000051u, 0x0006003du, 0x00000006u, 0x00000053u, 0x00000052u,
69 0x00000002u, 0x00000004u, 0x00060041u, 0x00000032u, 0x00000054u, 0x00000041u, 0x00000031u, 0x0000004du,
70 0x0005003eu, 0x00000054u, 0x00000053u, 0x00000002u, 0x00000004u, 0x00050080u, 0x00000006u, 0x00000059u,
71 0x00000027u, 0x00000058u, 0x00050080u, 0x00000006u, 0x0000005du, 0x0000003du, 0x00000058u, 0x00060041u,
72 0x00000032u, 0x0000005eu, 0x00000044u, 0x00000031u, 0x0000005du, 0x0006003du, 0x00000006u, 0x0000005fu,
73 0x0000005eu, 0x00000002u, 0x00000004u, 0x00060041u, 0x00000032u, 0x00000060u, 0x00000041u, 0x00000031u,
74 0x00000059u, 0x0005003eu, 0x00000060u, 0x0000005fu, 0x00000002u, 0x00000004u, 0x000200f9u, 0x00000037u,
75 0x000200f8u, 0x00000061u, 0x00050041u, 0x0000003fu, 0x00000062u, 0x00000019u, 0x0000003eu, 0x0004003du,
76 0x00000012u, 0x00000063u, 0x00000062u, 0x00060041u, 0x00000032u, 0x00000065u, 0x00000063u, 0x00000031u,
77 0x00000027u, 0x0005003eu, 0x00000065u, 0x0000000cu, 0x00000002u, 0x00000004u, 0x00050080u, 0x00000006u,
78 0x00000069u, 0x00000027u, 0x0000004cu, 0x00060041u, 0x00000032u, 0x0000006au, 0x00000063u, 0x00000031u,
79 0x00000069u, 0x0005003eu, 0x0000006au, 0x0000000cu, 0x00000002u, 0x00000004u, 0x00050080u, 0x00000006u,
80 0x0000006eu, 0x00000027u, 0x00000058u, 0x00060041u, 0x00000032u, 0x0000006fu, 0x00000063u, 0x00000031u,
81 0x0000006eu, 0x0005003eu, 0x0000006fu, 0x0000000cu, 0x00000002u, 0x00000004u, 0x000200f9u, 0x00000037u,
82 0x000200f8u, 0x00000037u, 0x000200f9u, 0x00000072u, 0x000200f8u, 0x00000072u, 0x000100fdu, 0x00010038u,
83};
84} // namespace leonida
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp
index 278444c6f..3c7f9da08 100644
--- a/runtime/src/pe_loader.cpp
+++ b/runtime/src/pe_loader.cpp
@@ -529,15 +529,7 @@ void cleanup_tls_clones() { cleanup_tls_clones_internal(); }
529 529
530namespace { 530namespace {
531bool lookup_in_loader(void* ctx, uint64_t address, std::string& module, uint32_t& rva) { 531bool lookup_in_loader(void* ctx, uint64_t address, std::string& module, uint32_t& rva) {
532 for (const Module* m : static_cast<Loader*>(ctx)->modules()) { 532 return static_cast<Loader*>(ctx)->find_address(address, module, rva);
533 const auto base = reinterpret_cast<uint64_t>(m->base);
534 if (m->base && address >= base && address - base < m->size) {
535 module = m->name;
536 rva = static_cast<uint32_t>(address - base);
537 return true;
538 }
539 }
540 return false;
541} 533}
542 534
543void* bundled_find_loaded(void* ctx, const std::string& dll_lower) { 535void* bundled_find_loaded(void* ctx, const std::string& dll_lower) {
@@ -732,6 +724,18 @@ void* Loader::resolve_module_export(void* module_handle, const std::string& sym,
732 return nullptr; 724 return nullptr;
733} 725}
734 726
727bool Loader::find_address(uint64_t address, std::string& module, uint32_t& rva) const {
728 std::shared_lock lock(ranges_mutex_);
729 for (const MappedRange& r : ranges_) {
730 if (address >= r.base && address - r.base < r.size) {
731 module = r.name;
732 rva = static_cast<uint32_t>(address - r.base);
733 return true;
734 }
735 }
736 return false;
737}
738
735bool Loader::owns_module_handle(void* module_handle) const { 739bool Loader::owns_module_handle(void* module_handle) const {
736 if (!module_handle) return false; 740 if (!module_handle) return false;
737 std::lock_guard lock(mutex_); 741 std::lock_guard lock(mutex_);
@@ -873,6 +877,12 @@ Module& Loader::map_image(const std::filesystem::path& path) {
873 m->base = static_cast<uint8_t*>(VirtualAlloc(nullptr, oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); 877 m->base = static_cast<uint8_t*>(VirtualAlloc(nullptr, oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE));
874 if (!m->base) throw std::runtime_error(m->name + ": VirtualAlloc failed"); 878 if (!m->base) throw std::runtime_error(m->name + ": VirtualAlloc failed");
875 } 879 }
880 {
881 // From here an address inside the image names it. The memory stays until ~Loader, which unregisters the
882 // lookup first.
883 std::unique_lock lock(ranges_mutex_);
884 ranges_.push_back({reinterpret_cast<uint64_t>(m->base), m->size, m->name});
885 }
876 886
877 std::memcpy(m->base, file.data(), oh.SizeOfHeaders); 887 std::memcpy(m->base, file.data(), oh.SizeOfHeaders);
878 auto* sec = IMAGE_FIRST_SECTION(nt); 888 auto* sec = IMAGE_FIRST_SECTION(nt);
diff --git a/runtime/src/pe_loader.h b/runtime/src/pe_loader.h
index e73c36339..d7e5be91c 100644
--- a/runtime/src/pe_loader.h
+++ b/runtime/src/pe_loader.h
@@ -9,6 +9,7 @@
9#include <filesystem> 9#include <filesystem>
10#include <map> 10#include <map>
11#include <mutex> 11#include <mutex>
12#include <shared_mutex>
12#include <string> 13#include <string>
13#include <vector> 14#include <vector>
14 15
@@ -79,6 +80,11 @@ public:
79 80
80 const std::vector<Module*>& modules() const { return order_; } 81 const std::vector<Module*>& modules() const { return order_; }
81 82
83 // The mapped module `address` lies in, with its RVA there. Safe from any thread at any time, also while another
84 // thread is in load(): it is what the shim registry asks for a caller's module (rt::shims::mapped_image_base on
85 // every C++ throw from a mapped image, and the trace and stop lines), and it reads its own table, not modules().
86 bool find_address(uint64_t address, std::string& module, uint32_t& rva) const;
87
82 // The order initialise() runs modules in: each module after every module it imports (a cycle is broken at the 88 // The order initialise() runs modules in: each module after every module it imports (a cycle is broken at the
83 // module that closed it). modules() is mapping order, which puts an importer before its imports. 89 // module that closed it). modules() is mapping order, which puts an importer before its imports.
84 const std::vector<Module*>& initialisation_order() const { return init_order_; } 90 const std::vector<Module*>& initialisation_order() const { return init_order_; }
@@ -133,6 +139,17 @@ private:
133 std::map<std::string, Module*> by_name_; // lower-case file name 139 std::map<std::string, Module*> by_name_; // lower-case file name
134 std::vector<Module*> order_; // mapping order; owns the modules 140 std::vector<Module*> order_; // mapping order; owns the modules
135 std::vector<Module*> init_order_; // dependencies first, see initialisation_order() 141 std::vector<Module*> init_order_; // dependencies first, see initialisation_order()
142
143 // What find_address reads: one entry per mapped image, added once its memory exists. Under ranges_mutex_, a leaf
144 // lock: mutex_ is held while image code runs and the registry holds its own lock around the lookup, so the
145 // lookup must not wait for either.
146 struct MappedRange {
147 uint64_t base = 0;
148 uint32_t size = 0;
149 std::string name;
150 };
151 mutable std::shared_mutex ranges_mutex_; // shared in find_address: lookups on different threads do not queue
152 std::vector<MappedRange> ranges_;
136}; 153};
137 154
138// Frees the TLS helper clones load() created and deletes their files (Module::tls_index background). load() 155// Frees the TLS helper clones load() created and deletes their files (Module::tls_index background). load()
diff --git a/runtime/src/queue_families.h b/runtime/src/queue_families.h
index 32ef1eb1d..e7dd50fe6 100644
--- a/runtime/src/queue_families.h
+++ b/runtime/src/queue_families.h
@@ -45,4 +45,24 @@ inline QueueFamilies pick_queue_families(std::span<const VkQueueFamilyProperties
45 return out; 45 return out;
46} 46}
47 47
48// A D3D12 COPY/COMPUTE queue may call UpdateTileMappings at any time. Vulkan binds sparse
49// pages on the VkQueue itself, so a family without SPARSE_BINDING cannot back that D3D12
50// queue when reserved buffers are offered. Use the graphics family (already checked for
51// sparse support by the device) rather than submitting an invalid vkQueueBindSparse.
52// Kept separate from the preference-only picker so devices without sparse resources keep
53// their dedicated async families unchanged.
54inline QueueFamilies sparse_capable_queue_families(std::span<const VkQueueFamilyProperties> families,
55 QueueFamilies chosen, bool sparse_buffers) {
56 if (!sparse_buffers || chosen.direct >= families.size() ||
57 !(families[chosen.direct].queueFlags & VK_QUEUE_SPARSE_BINDING_BIT))
58 return chosen;
59 if (chosen.compute >= families.size() ||
60 !(families[chosen.compute].queueFlags & VK_QUEUE_SPARSE_BINDING_BIT))
61 chosen.compute = chosen.direct;
62 if (chosen.copy >= families.size() ||
63 !(families[chosen.copy].queueFlags & VK_QUEUE_SPARSE_BINDING_BIT))
64 chosen.copy = chosen.direct;
65 return chosen;
66}
67
48} // namespace leonida 68} // namespace leonida
diff --git a/runtime/src/shader_library.h b/runtime/src/shader_library.h
index 528fd013d..69572ccd0 100644
--- a/runtime/src/shader_library.h
+++ b/runtime/src/shader_library.h
@@ -642,6 +642,9 @@ struct ShaderEntry {
642 std::vector<std::uint32_t> outputs; // pixel/vertex shaders: output locations written 642 std::vector<std::uint32_t> outputs; // pixel/vertex shaders: output locations written
643 // --f16-interp-fallback: param/attr index -> {low_half_location, high_half_location} (SHADER-378). 643 // --f16-interp-fallback: param/attr index -> {low_half_location, high_half_location} (SHADER-378).
644 std::map<std::uint32_t, std::array<std::uint32_t, 2>> f16_halves; 644 std::map<std::uint32_t, std::array<std::uint32_t, 2>> f16_halves;
645 // The S#s the shader builds from immediates (the index's literal_samplers): no heap slot names them, so a
646 // pipeline that uses the shader registers them in the bindless set itself (docs/design.md, Literal samplers).
647 std::vector<std::array<std::uint32_t, 4>> literal_samplers;
645}; 648};
646 649
647class ShaderLibrary { 650class ShaderLibrary {
@@ -813,6 +816,14 @@ private:
813 e.f16_halves[std::uint32_t(param)] = {u32(&val.array[0]), u32(&val.array[1])}; 816 e.f16_halves[std::uint32_t(param)] = {u32(&val.array[0]), u32(&val.array[1])};
814 } 817 }
815 } 818 }
819 if (const Json* l = meta.find("literal_samplers"); l && l->kind == Json::Kind::array) {
820 for (const Json& item : l->array) {
821 if (item.kind != Json::Kind::array || item.array.size() != 4) continue;
822 std::array<std::uint32_t, 4> words{};
823 for (std::size_t i = 0; i < 4; ++i) words[i] = u32(&item.array[i]);
824 e.literal_samplers.push_back(words);
825 }
826 }
816 if (by_fspx) fspx_entries_[{e.stage, e.fspx_code_sha256}].push_back(e); 827 if (by_fspx) fspx_entries_[{e.stage, e.fspx_code_sha256}].push_back(e);
817 if (by_fssm) entries_[{e.stage, e.fssm_sha256}].push_back(std::move(e)); 828 if (by_fssm) entries_[{e.stage, e.fssm_sha256}].push_back(std::move(e));
818 if (by_fspx && prefix == "fspx/") ++fspx_count_; 829 if (by_fspx && prefix == "fspx/") ++fspx_count_;
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h
index 03ab7ba26..d247b8cb0 100644
--- a/runtime/src/vulkan_backend.h
+++ b/runtime/src/vulkan_backend.h
@@ -17,6 +17,7 @@
17#include "statistics_sum_spirv.h" 17#include "statistics_sum_spirv.h"
18#include "vulkan13_features.h" 18#include "vulkan13_features.h"
19#include "vulkan_depth24.h" 19#include "vulkan_depth24.h"
20#include "vulkan_indirect_dispatch_count.h"
20#include "vulkan_scratch.h" 21#include "vulkan_scratch.h"
21#include "vulkan_replay.h" 22#include "vulkan_replay.h"
22#include "queue_families.h" 23#include "queue_families.h"
@@ -85,6 +86,7 @@ struct VulkanDeviceFunctions {
85 X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) \ 86 X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) \
86 X(vkCmdSetBlendConstants) X(vkCmdDraw) \ 87 X(vkCmdSetBlendConstants) X(vkCmdDraw) \
87 X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) \ 88 X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) \
89 X(vkCreatePipelineCache) X(vkDestroyPipelineCache) \
88 X(vkCreateEvent) X(vkDestroyEvent) X(vkResetEvent) X(vkCmdSetEvent) X(vkCmdWaitEvents) 90 X(vkCreateEvent) X(vkDestroyEvent) X(vkResetEvent) X(vkCmdSetEvent) X(vkCmdWaitEvents)
89#define LEONIDA_VK_MEMBER(name) PFN_##name name = nullptr; 91#define LEONIDA_VK_MEMBER(name) PFN_##name name = nullptr;
90 LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_MEMBER) 92 LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_MEMBER)
@@ -866,7 +868,7 @@ public:
866 // buffer as out of bounds, which is no reason to drop the submission. 868 // buffer as out of bounds, which is no reason to drop the submission.
867 replay_.buffer_at = [this](std::uint64_t va, std::uint64_t& size, VkBuffer& buffer, VkDeviceSize& offset) { 869 replay_.buffer_at = [this](std::uint64_t va, std::uint64_t& size, VkBuffer& buffer, VkDeviceSize& offset) {
868 BufferVaIndex<ResourceId>::Hit hit{}; 870 BufferVaIndex<ResourceId>::Hit hit{};
869 if (!buffer_vas_.find(va, hit)) return false; 871 if (!buffer_vas_.find(va, hit, size)) return false; // prefers an aliasing buffer that holds all of it
870 const ResourceBinding* b = resolve(hit.id); 872 const ResourceBinding* b = resolve(hit.id);
871 if (!b) return false; 873 if (!b) return false;
872 buffer = b->buffer; 874 buffer = b->buffer;
@@ -953,6 +955,13 @@ public:
953 std::unique_lock lock(resource_mutex_); 955 std::unique_lock lock(resource_mutex_);
954 predicated_copier_ = std::make_unique<PredicatedBufferCopier>(get, device_, limits); 956 predicated_copier_ = std::make_unique<PredicatedBufferCopier>(get, device_, limits);
955 } 957 }
958 // Counts for DISPATCH-only ExecuteIndirect are read by a helper compute shader from GPU memory.
959 // Requires Vulkan bufferDeviceAddress, already enabled for the D3D12 address arena.
960 void configure_counted_dispatch(PFN_vkGetDeviceProcAddr get, const VkPhysicalDeviceMemoryProperties& memory,
961 const VkPhysicalDeviceLimits& limits) {
962 std::unique_lock lock(resource_mutex_);
963 counted_dispatch_ = std::make_unique<IndirectDispatchCounter>(get, device_, memory, limits);
964 }
956 VkDevice device() const { return device_; } 965 VkDevice device() const { return device_; }
957 966
958 // Debug markers become labels from here on; call before any queue or list uses the context. Incomplete sets 967 // Debug markers become labels from here on; call before any queue or list uses the context. Incomplete sets
@@ -990,6 +999,14 @@ public:
990 storage_pending_.insert(id); 999 storage_pending_.insert(id);
991 } 1000 }
992 1001
1002 // A device-local buffer D3D12 says starts zeroed (D3D-71): the host cannot write it, so the next submission on
1003 // any queue fills it with zeros ahead of its lists. That submission publishes the same initialisation semaphore as
1004 // the storage images above, so a list on another queue that uses the buffer first waits for the fill.
1005 void zero_on_next_submit(ResourceId id, VkBuffer buffer) {
1006 std::lock_guard lock(storage_mutex_);
1007 zero_pending_.push_back({id, buffer});
1008 }
1009
993 void add_sparse_buffer(ResourceId id, const ResourceBinding& binding, std::shared_ptr<SparseBuffer> buffer) { 1010 void add_sparse_buffer(ResourceId id, const ResourceBinding& binding, std::shared_ptr<SparseBuffer> buffer) {
994 std::unique_lock lock(resource_mutex_); 1011 std::unique_lock lock(resource_mutex_);
995 set_resource_locked(id, binding); 1012 set_resource_locked(id, binding);
@@ -1007,6 +1024,10 @@ public:
1007 resources_.erase(it); 1024 resources_.erase(it);
1008 sparse_buffers_.erase(id); 1025 sparse_buffers_.erase(id);
1009 } 1026 }
1027 {
1028 std::lock_guard lock(storage_mutex_); // a buffer destroyed before any submission is not filled
1029 std::erase_if(zero_pending_, [id](const PendingZero& zero) { return zero.id == id; });
1030 }
1010 if (img) { 1031 if (img) {
1011 std::lock_guard vlock(views_mutex_); 1032 std::lock_guard vlock(views_mutex_);
1012 for (auto v = views_.begin(); v != views_.end();) { 1033 for (auto v = views_.begin(); v != views_.end();) {
@@ -1346,8 +1367,13 @@ private:
1346 std::unordered_map<std::uintptr_t, GraphicsPipeline> graphics_pipelines_; 1367 std::unordered_map<std::uintptr_t, GraphicsPipeline> graphics_pipelines_;
1347 std::unordered_map<std::uint64_t, VkAccelerationStructureKHR> acceleration_structures_; 1368 std::unordered_map<std::uint64_t, VkAccelerationStructureKHR> acceleration_structures_;
1348 LayoutTracker tracker_; 1369 LayoutTracker tracker_;
1349 std::mutex storage_mutex_; // a leaf lock: guards storage_pending_ only 1370 std::mutex storage_mutex_; // a leaf lock: guards storage_pending_ and zero_pending_ only
1350 std::unordered_set<ResourceId> storage_pending_; 1371 std::unordered_set<ResourceId> storage_pending_;
1372 struct PendingZero {
1373 ResourceId id;
1374 VkBuffer buffer;
1375 };
1376 std::vector<PendingZero> zero_pending_; // zero_on_next_submit
1351 // The last submission that initialized storage images (its queue's progress semaphore and ticket) and a counter 1377 // The last submission that initialized storage images (its queue's progress semaphore and ticket) and a counter
1352 // that says which one: every other queue's next submission waits for it, so no queue uses such an image before 1378 // that says which one: every other queue's next submission waits for it, so no queue uses such an image before
1353 // the zero-fill that put it in GENERAL has run. 1379 // the zero-fill that put it in GENERAL has run.
@@ -1366,6 +1392,7 @@ private:
1366 ReplayFunctions replay_; 1392 ReplayFunctions replay_;
1367 std::unique_ptr<PredicateReducer> predicate_reducer_; 1393 std::unique_ptr<PredicateReducer> predicate_reducer_;
1368 std::unique_ptr<PredicatedBufferCopier> predicated_copier_; 1394 std::unique_ptr<PredicatedBufferCopier> predicated_copier_;
1395 std::unique_ptr<IndirectDispatchCounter> counted_dispatch_;
1369 std::uint32_t predicate_family_ = UINT32_MAX; 1396 std::uint32_t predicate_family_ = UINT32_MAX;
1370 std::uint32_t transfer_only_family_ = UINT32_MAX; 1397 std::uint32_t transfer_only_family_ = UINT32_MAX;
1371 DebugLabelFunctions labels_; 1398 DebugLabelFunctions labels_;
@@ -1489,6 +1516,12 @@ public:
1489 if (context_.depth24_) context_.depth24_->forget(progress_); // its scratch is idle now 1516 if (context_.depth24_) context_.depth24_->forget(progress_); // its scratch is idle now
1490 if (context_.scratch_) context_.scratch_->forget(progress_); 1517 if (context_.scratch_) context_.scratch_->forget(progress_);
1491 } 1518 }
1519 if (progress_) {
1520 // This queue is idle, so whatever initialisation it published (storage images, zero-filled buffers) has
1521 // finished: the next submission on another queue must not wait on a semaphore that is about to go.
1522 std::lock_guard lock(context_.storage_mutex_);
1523 if (context_.storage_init_semaphore_ == progress_) context_.storage_init_semaphore_ = VK_NULL_HANDLE;
1524 }
1492 if (pool_) vk.vkDestroyCommandPool(context_.device(), pool_, nullptr); 1525 if (pool_) vk.vkDestroyCommandPool(context_.device(), pool_, nullptr);
1493 if (progress_) vk.vkDestroySemaphore(context_.device(), progress_, nullptr); 1526 if (progress_) vk.vkDestroySemaphore(context_.device(), progress_, nullptr);
1494 for (auto& slot : buffers_) free_events_.insert(free_events_.end(), slot.events.begin(), slot.events.end()); 1527 for (auto& slot : buffers_) free_events_.insert(free_events_.end(), slot.events.begin(), slot.events.end());
@@ -1690,6 +1723,7 @@ private:
1690 if (const auto* p = std::get_if<Predication>(&command); p && p->buffer) ++captures; 1723 if (const auto* p = std::get_if<Predication>(&command); p && p->buffer) ++captures;
1691 std::unique_ptr<PredicateReducer::Batch> batch; 1724 std::unique_ptr<PredicateReducer::Batch> batch;
1692 std::unique_ptr<PredicatedBufferCopier::Batch> copy_batch; 1725 std::unique_ptr<PredicatedBufferCopier::Batch> copy_batch;
1726 std::unique_ptr<IndirectDispatchCounter::Batch> counted_batch;
1693 if (captures) { 1727 if (captures) {
1694 if (kind_ == QueueKind::copy || !context_.predicate_reducer_ || family_ != context_.predicate_family_) 1728 if (kind_ == QueueKind::copy || !context_.predicate_reducer_ || family_ != context_.predicate_family_)
1695 return ReplayResult::unsupported; 1729 return ReplayResult::unsupported;
@@ -1727,6 +1761,19 @@ private:
1727 return context_.scratch_->get(bytes, buffer, offset); 1761 return context_.scratch_->get(bytes, buffer, offset);
1728 }; 1762 };
1729 } 1763 }
1764 if (kind_ != QueueKind::copy && context_.counted_dispatch_) {
1765 replay.prepare_counted_dispatch = [this, &tracker_lock, &counted_batch](
1766 VkBuffer args, VkDeviceSize args_offset, VkBuffer count, VkDeviceSize count_offset,
1767 std::uint32_t stride, std::uint32_t maximum, CountedDispatch& out) {
1768 // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation.
1769 if (!tracker_lock.owns_lock()) tracker_lock.lock();
1770 if (!counted_batch) counted_batch = context_.counted_dispatch_->batch();
1771 return counted_batch->prepare(args, args_offset, count, count_offset, stride, maximum, out);
1772 };
1773 replay.emit_counted_dispatch = [this](VkCommandBuffer cb, const CountedDispatch& job) {
1774 context_.counted_dispatch_->emit(cb, job);
1775 };
1776 }
1730 if (context_.depth24_ && !transfer_only) { 1777 if (context_.depth24_ && !transfer_only) {
1731 replay.depth24_prepare = [this, &tracker_lock, &depth24_guard](Depth24Job& job, 1778 replay.depth24_prepare = [this, &tracker_lock, &depth24_guard](Depth24Job& job,
1732 std::vector<Depth24Job>& parts) { 1779 std::vector<Depth24Job>& parts) {
@@ -1871,6 +1918,7 @@ private:
1871 runs_shaders |= std::holds_alternative<Dispatch>(command) || std::holds_alternative<Draw>(command) || 1918 runs_shaders |= std::holds_alternative<Dispatch>(command) || std::holds_alternative<Draw>(command) ||
1872 std::holds_alternative<ExecuteIndirect>(command); 1919 std::holds_alternative<ExecuteIndirect>(command);
1873 std::vector<ResourceId> storage_images; 1920 std::vector<ResourceId> storage_images;
1921 std::vector<VulkanContext::PendingZero> zero_buffers;
1874 { 1922 {
1875 std::lock_guard lock(context_.storage_mutex_); 1923 std::lock_guard lock(context_.storage_mutex_);
1876 if (context_.storage_init_semaphore_ && context_.storage_init_semaphore_ != progress_ && 1924 if (context_.storage_init_semaphore_ && context_.storage_init_semaphore_ != progress_ &&
@@ -1882,6 +1930,16 @@ private:
1882 if (kind_ != QueueKind::copy && runs_shaders) 1930 if (kind_ != QueueKind::copy && runs_shaders)
1883 storage_images.assign(context_.storage_pending_.begin(), context_.storage_pending_.end()); 1931 storage_images.assign(context_.storage_pending_.begin(), context_.storage_pending_.end());
1884 if (!storage_images.empty()) context_.storage_pending_.clear(); 1932 if (!storage_images.empty()) context_.storage_pending_.clear();
1933 zero_buffers.swap(context_.zero_pending_); // any queue can fill a buffer
1934 }
1935 for (const auto& zero : zero_buffers)
1936 context_.vk.vkCmdFillBuffer(command_buffer, zero.buffer, 0, VK_WHOLE_SIZE, 0);
1937 if (!zero_buffers.empty()) {
1938 VkMemoryBarrier filled{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
1939 filled.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
1940 filled.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
1941 context_.vk.vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT,
1942 VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1, &filled, 0, nullptr, 0, nullptr);
1885 } 1943 }
1886 for (const ResourceId id : storage_images) { 1944 for (const ResourceId id : storage_images) {
1887 const ResourceBinding* image = context_.resolve(id); 1945 const ResourceBinding* image = context_.resolve(id);
@@ -1937,11 +1995,13 @@ private:
1937 wait_values_.push_back(submitted_); 1995 wait_values_.push_back(submitted_);
1938 } 1996 }
1939 const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0); 1997 const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0);
1940 if (!submitted && !storage_images.empty()) { // not initialized after all: try again with the next submission 1998 if (!submitted && (!storage_images.empty() || !zero_buffers.empty())) {
1999 // not initialized after all: try again with the next submission
1941 std::lock_guard lock(context_.storage_mutex_); 2000 std::lock_guard lock(context_.storage_mutex_);
1942 context_.storage_pending_.insert(storage_images.begin(), storage_images.end()); 2001 context_.storage_pending_.insert(storage_images.begin(), storage_images.end());
2002 context_.zero_pending_.insert(context_.zero_pending_.end(), zero_buffers.begin(), zero_buffers.end());
1943 } 2003 }
1944 if (submitted && !storage_images.empty()) { 2004 if (submitted && (!storage_images.empty() || !zero_buffers.empty())) {
1945 std::lock_guard lock(context_.storage_mutex_); 2005 std::lock_guard lock(context_.storage_mutex_);
1946 context_.storage_init_semaphore_ = progress_; 2006 context_.storage_init_semaphore_ = progress_;
1947 context_.storage_init_value_ = submitted_; 2007 context_.storage_init_value_ = submitted_;
@@ -1956,6 +2016,7 @@ private:
1956 context_.tracker_ = std::move(next_tracker); 2016 context_.tracker_ = std::move(next_tracker);
1957 slot->predicate = std::move(batch); 2017 slot->predicate = std::move(batch);
1958 slot->predicated_copy = std::move(copy_batch); 2018 slot->predicated_copy = std::move(copy_batch);
2019 slot->counted_dispatch = std::move(counted_batch);
1959 queries.commit(); 2020 queries.commit();
1960 slot->segments = std::move(queries.retained); 2021 slot->segments = std::move(queries.retained);
1961 } else { 2022 } else {
@@ -2110,6 +2171,7 @@ private:
2110 std::vector<std::shared_ptr<const OcclusionSegmentPool>> segments; 2171 std::vector<std::shared_ptr<const OcclusionSegmentPool>> segments;
2111 std::vector<VkEvent> events; // order_timestamp_copy's, reset and reused once the slot completes 2172 std::vector<VkEvent> events; // order_timestamp_copy's, reset and reused once the slot completes
2112 std::unique_ptr<PredicatedBufferCopier::Batch> predicated_copy; 2173 std::unique_ptr<PredicatedBufferCopier::Batch> predicated_copy;
2174 std::unique_ptr<IndirectDispatchCounter::Batch> counted_dispatch;
2113 std::unique_ptr<PredicateReducer::Batch> predicate; // retained until this slot completes 2175 std::unique_ptr<PredicateReducer::Batch> predicate; // retained until this slot completes
2114 }; 2176 };
2115 2177
@@ -2228,6 +2290,7 @@ private:
2228 if (context_.vk.vkResetCommandBuffer(reuse->buffer, 0) != VK_SUCCESS) return nullptr; 2290 if (context_.vk.vkResetCommandBuffer(reuse->buffer, 0) != VK_SUCCESS) return nullptr;
2229 reuse->predicate.reset(); 2291 reuse->predicate.reset();
2230 reuse->predicated_copy.reset(); 2292 reuse->predicated_copy.reset();
2293 reuse->counted_dispatch.reset();
2231 reuse->ticket = UINT64_MAX; // in use until submitted 2294 reuse->ticket = UINT64_MAX; // in use until submitted
2232 return reuse; 2295 return reuse;
2233 } 2296 }
diff --git a/runtime/src/vulkan_indirect_dispatch_count.h b/runtime/src/vulkan_indirect_dispatch_count.h
new file mode 100644
index 000000000..225f7c1fc
--- /dev/null
+++ b/runtime/src/vulkan_indirect_dispatch_count.h
@@ -0,0 +1,199 @@
1// GPU-only count gating for simple D3D12 ExecuteIndirect(DISPATCH) signatures.
2// Vulkan has vkCmdDispatchIndirect but no vkCmdDispatchIndirectCount. We prepare a private indirect
3// buffer with zero-group records past the GPU count, then execute all MaxCommandCount records.
4#pragma once
5#ifndef VK_NO_PROTOTYPES
6#define VK_NO_PROTOTYPES
7#endif
8#include <vulkan/vulkan.h>
9#include <algorithm>
10#include <cstdint>
11#include <limits>
12#include <memory>
13#include <vector>
14#include "indirect_dispatch_count_spv.h"
15
16namespace leonida {
17
18struct CountedDispatch {
19 VkBuffer indirect = VK_NULL_HANDLE;
20 VkDeviceSize offset = 0;
21 VkDeviceAddress arguments = 0;
22 VkDeviceAddress count = 0;
23 VkDeviceAddress output = 0;
24 std::uint32_t stride = 0;
25 std::uint32_t max_count = 0;
26};
27
28class IndirectDispatchCounter {
29public:
30 IndirectDispatchCounter(PFN_vkGetDeviceProcAddr get, VkDevice device,
31 const VkPhysicalDeviceMemoryProperties& memory, const VkPhysicalDeviceLimits& limits)
32 : get_(get), device_(device), memory_(memory), limits_(limits) {}
33 ~IndirectDispatchCounter() {
34 if (pipeline_) fn<PFN_vkDestroyPipeline>("vkDestroyPipeline")(device_, pipeline_, nullptr);
35 if (layout_) fn<PFN_vkDestroyPipelineLayout>("vkDestroyPipelineLayout")(device_, layout_, nullptr);
36 }
37 IndirectDispatchCounter(const IndirectDispatchCounter&) = delete;
38 IndirectDispatchCounter& operator=(const IndirectDispatchCounter&) = delete;
39
40 // Retained by the command-buffer slot until its submission's timeline ticket completes.
41 struct Batch {
42 IndirectDispatchCounter& owner;
43 struct Allocation {
44 VkBuffer buffer = VK_NULL_HANDLE;
45 VkDeviceMemory memory = VK_NULL_HANDLE;
46 };
47 std::vector<Allocation> allocations;
48 explicit Batch(IndirectDispatchCounter& value) : owner(value) {}
49 ~Batch() {
50 for (auto& a : allocations) {
51 if (a.buffer) owner.fn<PFN_vkDestroyBuffer>("vkDestroyBuffer")(owner.device_, a.buffer, nullptr);
52 if (a.memory) owner.fn<PFN_vkFreeMemory>("vkFreeMemory")(owner.device_, a.memory, nullptr);
53 }
54 }
55 Batch(const Batch&) = delete;
56 Batch& operator=(const Batch&) = delete;
57
58 bool prepare(VkBuffer arguments, VkDeviceSize argument_offset, VkBuffer count,
59 VkDeviceSize count_offset, std::uint32_t stride, std::uint32_t max_count,
60 CountedDispatch& out) {
61 out = {};
62 if (!arguments || !count || !stride || stride % 4 || !max_count ||
63 !owner.limits_.maxComputeWorkGroupCount[0] || !owner.make_pipeline()) return false;
64 constexpr VkDeviceSize record_bytes = 3 * sizeof(std::uint32_t);
65 if (VkDeviceSize(max_count) > std::numeric_limits<VkDeviceSize>::max() / record_bytes)
66 return false;
67 const VkDeviceSize bytes = VkDeviceSize(max_count) * record_bytes;
68 VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
69 info.size = bytes;
70 info.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT |
71 VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT;
72 Allocation scratch{};
73 if (owner.fn<PFN_vkCreateBuffer>("vkCreateBuffer")(owner.device_, &info, nullptr, &scratch.buffer) != VK_SUCCESS)
74 return false;
75 allocations.push_back(scratch); // all failure paths free it with the batch
76 auto& a = allocations.back();
77 VkMemoryRequirements requirements{};
78 owner.fn<PFN_vkGetBufferMemoryRequirements>("vkGetBufferMemoryRequirements")(
79 owner.device_, a.buffer, &requirements);
80 std::uint32_t memory_type = UINT32_MAX;
81 for (std::uint32_t i = 0; i < owner.memory_.memoryTypeCount; ++i) {
82 if (!(requirements.memoryTypeBits & (1u << i))) continue;
83 if (memory_type == UINT32_MAX) memory_type = i;
84 if (owner.memory_.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) {
85 memory_type = i;
86 break;
87 }
88 }
89 if (memory_type == UINT32_MAX) return false;
90 VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO};
91 flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT;
92 VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, &flags};
93 allocation.allocationSize = requirements.size;
94 allocation.memoryTypeIndex = memory_type;
95 if (owner.fn<PFN_vkAllocateMemory>("vkAllocateMemory")(owner.device_, &allocation, nullptr, &a.memory) != VK_SUCCESS ||
96 owner.fn<PFN_vkBindBufferMemory>("vkBindBufferMemory")(owner.device_, a.buffer, a.memory, 0) != VK_SUCCESS)
97 return false;
98 const auto address = owner.fn<PFN_vkGetBufferDeviceAddress>("vkGetBufferDeviceAddress");
99 VkBufferDeviceAddressInfo addr{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO};
100 addr.buffer = arguments;
101 const VkDeviceAddress args_va = address(owner.device_, &addr);
102 addr.buffer = count;
103 const VkDeviceAddress count_va = address(owner.device_, &addr);
104 addr.buffer = a.buffer;
105 const VkDeviceAddress output_va = address(owner.device_, &addr);
106 if (!args_va || !count_va || !output_va ||
107 argument_offset > UINT64_MAX - args_va || count_offset > UINT64_MAX - count_va)
108 return false;
109 out = {a.buffer, 0, args_va + argument_offset, count_va + count_offset,
110 output_va, stride, max_count};
111 return true;
112 }
113 };
114
115 std::unique_ptr<Batch> batch() { return std::make_unique<Batch>(*this); }
116
117 void emit(VkCommandBuffer cb, const CountedDispatch& job) const {
118 const auto barrier = fn<PFN_vkCmdPipelineBarrier>("vkCmdPipelineBarrier");
119 VkMemoryBarrier before{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
120 before.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT;
121 before.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
122 barrier(cb, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
123 0, 1, &before, 0, nullptr, 0, nullptr);
124 fn<PFN_vkCmdBindPipeline>("vkCmdBindPipeline")(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_);
125 struct Push {
126 VkDeviceAddress arguments, count, output;
127 std::uint32_t stride_words, first_record, records;
128 };
129 static_assert(sizeof(Push) == 40);
130 const VkDeviceSize dispatch_limit = VkDeviceSize(limits_.maxComputeWorkGroupCount[0]) * 64;
131 // Bound per-dispatch indexing to 32 bits, even when the D3D12 stride is very large.
132 // The shader loads three consecutive dwords, so leave room for the final +2.
133 const VkDeviceSize index_limit = (UINT32_MAX - 2u) / (job.stride / 4);
134 const VkDeviceSize chunk_limit = std::min(dispatch_limit, index_limit + 1);
135 for (VkDeviceSize first = 0; first < job.max_count;) {
136 const std::uint32_t count = std::uint32_t(std::min<VkDeviceSize>(chunk_limit, job.max_count - first));
137 const Push push{job.arguments + first * job.stride, job.count, job.output + first * 12,
138 job.stride / 4, std::uint32_t(first), count};
139 fn<PFN_vkCmdPushConstants>("vkCmdPushConstants")(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT,
140 0, sizeof(push), &push);
141 fn<PFN_vkCmdDispatch>("vkCmdDispatch")(cb, (count + 63u) / 64u, 1, 1);
142 first += count;
143 }
144 VkMemoryBarrier after{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
145 after.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_SHADER_READ_BIT;
146 after.dstAccessMask = VK_ACCESS_INDIRECT_COMMAND_READ_BIT | VK_ACCESS_MEMORY_READ_BIT |
147 VK_ACCESS_MEMORY_WRITE_BIT;
148 barrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
149 0, 1, &after, 0, nullptr, 0, nullptr);
150 }
151
152private:
153 template<typename T> T fn(const char* name) const { return reinterpret_cast<T>(get_(device_, name)); }
154 bool make_pipeline() {
155 if (pipeline_) return true;
156 for (const char* name : {"vkCreateBuffer", "vkDestroyBuffer", "vkGetBufferMemoryRequirements",
157 "vkAllocateMemory", "vkFreeMemory", "vkBindBufferMemory", "vkGetBufferDeviceAddress",
158 "vkCreateShaderModule", "vkDestroyShaderModule", "vkCreatePipelineLayout",
159 "vkDestroyPipelineLayout", "vkCreateComputePipelines", "vkDestroyPipeline",
160 "vkCmdPipelineBarrier", "vkCmdBindPipeline", "vkCmdPushConstants", "vkCmdDispatch"})
161 if (!get_(device_, name)) return false;
162 VkShaderModule module = VK_NULL_HANDLE;
163 VkPipelineLayout layout = VK_NULL_HANDLE;
164 VkPipeline pipeline = VK_NULL_HANDLE;
165 VkShaderModuleCreateInfo shader{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO};
166 shader.codeSize = sizeof(indirect_dispatch_count_spirv);
167 shader.pCode = indirect_dispatch_count_spirv;
168 bool ok = fn<PFN_vkCreateShaderModule>("vkCreateShaderModule")(device_, &shader, nullptr, &module) == VK_SUCCESS;
169 const VkPushConstantRange range{VK_SHADER_STAGE_COMPUTE_BIT, 0, 40};
170 VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO};
171 layout_info.pushConstantRangeCount = 1;
172 layout_info.pPushConstantRanges = &range;
173 ok = ok && fn<PFN_vkCreatePipelineLayout>("vkCreatePipelineLayout")(device_, &layout_info, nullptr, &layout) == VK_SUCCESS;
174 VkComputePipelineCreateInfo info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO};
175 info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO};
176 info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT;
177 info.stage.module = module;
178 info.stage.pName = "main";
179 info.layout = layout;
180 ok = ok && fn<PFN_vkCreateComputePipelines>("vkCreateComputePipelines")(
181 device_, VK_NULL_HANDLE, 1, &info, nullptr, &pipeline) == VK_SUCCESS;
182 if (module) fn<PFN_vkDestroyShaderModule>("vkDestroyShaderModule")(device_, module, nullptr);
183 if (!ok) {
184 if (pipeline) fn<PFN_vkDestroyPipeline>("vkDestroyPipeline")(device_, pipeline, nullptr);
185 if (layout) fn<PFN_vkDestroyPipelineLayout>("vkDestroyPipelineLayout")(device_, layout, nullptr);
186 return false;
187 }
188 layout_ = layout;
189 pipeline_ = pipeline;
190 return true;
191 }
192 PFN_vkGetDeviceProcAddr get_;
193 VkDevice device_;
194 VkPhysicalDeviceMemoryProperties memory_;
195 VkPhysicalDeviceLimits limits_;
196 VkPipelineLayout layout_ = VK_NULL_HANDLE;
197 VkPipeline pipeline_ = VK_NULL_HANDLE;
198};
199} // namespace leonida
diff --git a/runtime/src/vulkan_memory.h b/runtime/src/vulkan_memory.h
index c89a68575..08c764d33 100644
--- a/runtime/src/vulkan_memory.h
+++ b/runtime/src/vulkan_memory.h
@@ -56,4 +56,13 @@ inline std::vector<std::uint32_t> memory_type_order(const VkPhysicalDeviceMemory
56 return order; 56 return order;
57} 57}
58 58
59// D3D-299: true when an allocation that preferred DEVICE_LOCAL without needing host access (a texture, a default-heap
60// buffer outside the arena) got a type without it, so the GPU now reads it from system memory. A host-visible
61// allocation (the arena, an upload heap) in system memory is the memory type policy without Resizable BAR, not this.
62inline bool spilled_to_host(VkMemoryPropertyFlags required, VkMemoryPropertyFlags preferred,
63 VkMemoryPropertyFlags chosen) {
64 return (preferred & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) && !(required & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) &&
65 !(chosen & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
66}
67
59} // namespace leonida 68} // namespace leonida
diff --git a/runtime/src/vulkan_present.h b/runtime/src/vulkan_present.h
index fc6d1699e..a29cce3fa 100644
--- a/runtime/src/vulkan_present.h
+++ b/runtime/src/vulkan_present.h
@@ -166,8 +166,10 @@ public:
166 { 166 {
167 std::lock_guard lock(context_.submit_mutex()); 167 std::lock_guard lock(context_.submit_mutex());
168 vk.vkQueueWaitIdle(queue_); 168 vk.vkQueueWaitIdle(queue_);
169 // A WSI layer may perform a device-wide idle while destroying the swapchain.
170 // Keep that implicit idle serialized with submits from every context queue.
171 release(swapchain_);
169 } 172 }
170 release(swapchain_);
171 swapchain_ = VK_NULL_HANDLE; 173 swapchain_ = VK_NULL_HANDLE;
172 release_capture(); 174 release_capture();
173 composer_.reset(); 175 composer_.reset();
@@ -299,7 +301,9 @@ public:
299 } 301 }
300 302
301 // The last presented frame as the swapchain stores it (4 bytes a texel, rows tightly packed, format() order). 303 // The last presented frame as the swapchain stores it (4 bytes a texel, rows tightly packed, format() order).
302 // Waits for the frame to finish. False if no captured frame is available or the wait fails. 304 // Waits for the frame to finish. False when nothing was presented since enable_capture(), after a present
305 // that was skipped because the window is minimised (it returned VK_SUCCESS but showed nothing), until the next
306 // frame that is shown (the frame before it is not what the window was last asked to show), or when the wait fails.
303 bool read_back(std::vector<std::uint8_t>& pixels, VkExtent2D* extent, VkFormat* format) { 307 bool read_back(std::vector<std::uint8_t>& pixels, VkExtent2D* extent, VkFormat* format) {
304 if (!capture_ || !capture_ptr_ || !captured_) return false; 308 if (!capture_ || !capture_ptr_ || !captured_) return false;
305 const Frame& frame = frames_[(frame_index_ + frames_.size() - 1) % frames_.size()]; 309 const Frame& frame = frames_[(frame_index_ + frames_.size() - 1) % frames_.size()];
@@ -331,6 +335,7 @@ public:
331 } 335 }
332 if (!swapchain_) { // minimised: try again next frame 336 if (!swapchain_) { // minimised: try again next frame
333 stale_ = true; 337 stale_ = true;
338 captured_ = false; // nothing was shown: read_back() must not hand out the frame before
334 return VK_SUCCESS; 339 return VK_SUCCESS;
335 } 340 }
336 if (binding && !presentable(source)) return VK_ERROR_UNKNOWN; // checked before an image is acquired for it 341 if (binding && !presentable(source)) return VK_ERROR_UNKNOWN; // checked before an image is acquired for it
@@ -347,7 +352,10 @@ public:
347 VkResult acquired = acquire(frame.acquired, &image); 352 VkResult acquired = acquire(frame.acquired, &image);
348 if (acquired == VK_ERROR_OUT_OF_DATE_KHR) { 353 if (acquired == VK_ERROR_OUT_OF_DATE_KHR) {
349 if (!recreate(vsync, swapchain_srgb_, swapchain_hdr_req_)) return acquired; 354 if (!recreate(vsync, swapchain_srgb_, swapchain_hdr_req_)) return acquired;
350 if (!swapchain_) return VK_SUCCESS; 355 if (!swapchain_) { // minimised since the last present: skipped, as above
356 captured_ = false;
357 return VK_SUCCESS;
358 }
351 acquired = acquire(frame.acquired, &image); 359 acquired = acquire(frame.acquired, &image);
352 } 360 }
353 if (acquired != VK_SUCCESS && acquired != VK_SUBOPTIMAL_KHR) return acquired; // nothing was acquired 361 if (acquired != VK_SUCCESS && acquired != VK_SUBOPTIMAL_KHR) return acquired; // nothing was acquired
@@ -873,7 +881,10 @@ private:
873 } 881 }
874 } 882 }
875 if (extent.width == 0 || extent.height == 0) { 883 if (extent.width == 0 || extent.height == 0) {
876 release(swapchain_); 884 {
885 std::lock_guard lock(context_.submit_mutex());
886 release(swapchain_);
887 }
877 swapchain_ = VK_NULL_HANDLE; 888 swapchain_ = VK_NULL_HANDLE;
878 vsync_ = vsync; 889 vsync_ = vsync;
879 swapchain_srgb_ = srgb; 890 swapchain_srgb_ = srgb;
@@ -985,13 +996,18 @@ private:
985 info.oldSwapchain = old; 996 info.oldSwapchain = old;
986 VkSwapchainKHR fresh = VK_NULL_HANDLE; 997 VkSwapchainKHR fresh = VK_NULL_HANDLE;
987 const VkResult created = vkCreateSwapchainKHR_(device, &info, nullptr, &fresh); 998 const VkResult created = vkCreateSwapchainKHR_(device, &info, nullptr, &fresh);
988 release(old); // retired by the creation attempt, whether or not it succeeded 999 {
1000 std::lock_guard lock(context_.submit_mutex());
1001 release(old); // retired by the creation attempt, whether or not it succeeded
1002 }
989 if (created != VK_SUCCESS) return false; 1003 if (created != VK_SUCCESS) return false;
990 1004
991 std::vector<VkImage> images; 1005 std::vector<VkImage> images;
992 std::vector<VkSemaphore> ready; 1006 std::vector<VkSemaphore> ready;
993 const auto discard = [&] { 1007 const auto discard = [&] {
994 for (VkSemaphore semaphore : ready) vk.vkDestroySemaphore(device, semaphore, nullptr); 1008 for (VkSemaphore semaphore : ready) vk.vkDestroySemaphore(device, semaphore, nullptr);
1009 // The WSI implementation may block on the device here too.
1010 std::lock_guard lock(context_.submit_mutex());
995 vkDestroySwapchainKHR_(device, fresh, nullptr); 1011 vkDestroySwapchainKHR_(device, fresh, nullptr);
996 return false; 1012 return false;
997 }; 1013 };
diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h
index 4185d6ff8..d5effb830 100644
--- a/runtime/src/vulkan_replay.h
+++ b/runtime/src/vulkan_replay.h
@@ -37,6 +37,7 @@
37#include <vulkan/vulkan.h> 37#include <vulkan/vulkan.h>
38#include "vulkan_predicate.h" 38#include "vulkan_predicate.h"
39#include "vulkan_predicated_copy.h" 39#include "vulkan_predicated_copy.h"
40#include "vulkan_indirect_dispatch_count.h"
40 41
41#include <algorithm> 42#include <algorithm>
42#include <array> 43#include <array>
@@ -721,6 +722,8 @@ struct OcclusionResult {
721// A D3D12 query heap on Vulkan. The host tracks which queries hold a result. A resolve of a query that 722// A D3D12 query heap on Vulkan. The host tracks which queries hold a result. A resolve of a query that
722// was never ended writes zeros instead of waiting on it. 723// was never ended writes zeros instead of waiting on it.
723struct QueryPool { 724struct QueryPool {
725 // Null for a stream-output statistics heap: the layer has no stream output (PSOs with StreamOutput entries are
726 // refused), so every SO_STATISTICS_STREAMn query counts 0 written and 0 needed, and a resolve fills zeros.
724 VkQueryPool pool = VK_NULL_HANDLE; 727 VkQueryPool pool = VK_NULL_HANDLE;
725 std::uint32_t heap_type = 0; // d3d12_query_heap 728 std::uint32_t heap_type = 0; // d3d12_query_heap
726 std::uint32_t count = 0; 729 std::uint32_t count = 0;
@@ -799,6 +802,10 @@ struct ReplayFunctions {
799 std::function<void(VkCommandBuffer)> order_timestamp_copy; 802 std::function<void(VkCommandBuffer)> order_timestamp_copy;
800 std::function<void(VkCommandBuffer, VkQueryPool, std::uint32_t, std::uint32_t, VkBuffer, VkDeviceSize)> 803 std::function<void(VkCommandBuffer, VkQueryPool, std::uint32_t, std::uint32_t, VkBuffer, VkDeviceSize)>
801 sum_occlusion; 804 sum_occlusion;
805 // Creates a query pool of `count` queries of that type for the single-list replay()'s occlusion and
806 // pipeline-statistics segments (D3D-399); the batched path creates its own. Unset, or with any sum helper unset,
807 // replay() refuses a list whose queries overlap, as before.
808 std::function<std::shared_ptr<const OcclusionSegmentPool>(VkQueryType, std::uint32_t count)> create_segment_pool;
802 PFN_vkCmdBindPipeline bind_pipeline = nullptr; // dispatches 809 PFN_vkCmdBindPipeline bind_pipeline = nullptr; // dispatches
803 PFN_vkCmdPushConstants push_constants = nullptr; 810 PFN_vkCmdPushConstants push_constants = nullptr;
804 PFN_vkCmdBindDescriptorSets bind_descriptor_sets = nullptr; // set 0 of pipelines that declare bindings 811 PFN_vkCmdBindDescriptorSets bind_descriptor_sets = nullptr; // set 0 of pipelines that declare bindings
@@ -845,6 +852,11 @@ struct ReplayFunctions {
845 PFN_vkCmdDrawIndirectCount draw_indirect_count = nullptr; 852 PFN_vkCmdDrawIndirectCount draw_indirect_count = nullptr;
846 PFN_vkCmdDrawIndexedIndirectCount draw_indexed_indirect_count = nullptr; 853 PFN_vkCmdDrawIndexedIndirectCount draw_indexed_indirect_count = nullptr;
847 PFN_vkCmdDispatchIndirect dispatch_indirect = nullptr; 854 PFN_vkCmdDispatchIndirect dispatch_indirect = nullptr;
855 // A DISPATCH-only ExecuteIndirect signature with a GPU count buffer needs a compute prepass to clamp
856 // the number of commands. The resulting scratch buffer is owned by the queue's timeline-retained batch.
857 std::function<bool(VkBuffer, VkDeviceSize, VkBuffer, VkDeviceSize, std::uint32_t, std::uint32_t,
858 CountedDispatch&)> prepare_counted_dispatch;
859 std::function<void(VkCommandBuffer, const CountedDispatch&)> emit_counted_dispatch;
848 // Optional VK_KHR_acceleration_structure: BuildRaytracingAccelerationStructure. 860 // Optional VK_KHR_acceleration_structure: BuildRaytracingAccelerationStructure.
849 PFN_vkCmdBuildAccelerationStructuresKHR build_acceleration_structures = nullptr; 861 PFN_vkCmdBuildAccelerationStructuresKHR build_acceleration_structures = nullptr;
850 // XDXR BVH4 builds (xdxr_build.h), used instead of the KHR ones when set: `xdxr_check` refuses inputs the builder 862 // XDXR BVH4 builds (xdxr_build.h), used instead of the KHR ones when set: `xdxr_check` refuses inputs the builder
@@ -926,6 +938,7 @@ struct Prepared {
926 std::uint32_t statistics_begin = PreparedQuery::no_segment; 938 std::uint32_t statistics_begin = PreparedQuery::no_segment;
927 PredicateCapture predicate; 939 PredicateCapture predicate;
928 std::vector<PredicatedCopyDispatch> predicated_copy; 940 std::vector<PredicatedCopyDispatch> predicated_copy;
941 CountedDispatch counted_dispatch;
929 ResourceBinding binding; 942 ResourceBinding binding;
930 VkImageSubresourceRange range{}; // the barrier range, or the cleared view (cleared aspects only) 943 VkImageSubresourceRange range{}; // the barrier range, or the cleared view (cleared aspects only)
931 VkImageView view = VK_NULL_HANDLE; 944 VkImageView view = VK_NULL_HANDLE;
@@ -937,6 +950,7 @@ struct Prepared {
937 std::vector<VkBufferCopy> buffer_copies; 950 std::vector<VkBufferCopy> buffer_copies;
938 std::vector<VkBufferImageCopy> buffer_image_copies; // one direction, given by which side is an image 951 std::vector<VkBufferImageCopy> buffer_image_copies; // one direction, given by which side is an image
939 std::vector<VkImageCopy> image_copies; 952 std::vector<VkImageCopy> image_copies;
953 bool same_copy_subresource = false;
940 VkImageResolve resolve{}; // resolves 954 VkImageResolve resolve{}; // resolves
941 // Depth or stencil resolves: the mode, and the destination view (`view` is the source's). 955 // Depth or stencil resolves: the mode, and the destination view (`view` is the source's).
942 VkResolveModeFlagBits resolve_mode = VK_RESOLVE_MODE_NONE; 956 VkResolveModeFlagBits resolve_mode = VK_RESOLVE_MODE_NONE;
@@ -1544,6 +1558,8 @@ inline ReplayResult prepare_texture_copy(const CopyTexture& copy, Prepared& p) {
1544 p.binding.volume != p.source.volume || p.binding.samples != p.source.samples || 1558 p.binding.volume != p.source.volume || p.binding.samples != p.source.samples ||
1545 p.binding.rgb96 != p.source.rgb96) 1559 p.binding.rgb96 != p.source.rgb96)
1546 return ReplayResult::invalid_copy; 1560 return ReplayResult::invalid_copy;
1561 p.same_copy_subresource = p.source.image == p.binding.image && src.aspectMask == dst.aspectMask &&
1562 src.baseMipLevel == dst.baseMipLevel && src.baseArrayLayer == dst.baseArrayLayer;
1547 const VkExtent2D from = mip_extent(p.source, src.baseMipLevel), to = mip_extent(p.binding, dst.baseMipLevel); 1563 const VkExtent2D from = mip_extent(p.source, src.baseMipLevel), to = mip_extent(p.binding, dst.baseMipLevel);
1548 const auto from_depth = std::max(1u, p.source.depth >> src.baseMipLevel); 1564 const auto from_depth = std::max(1u, p.source.depth >> src.baseMipLevel);
1549 const auto to_depth = std::max(1u, p.binding.depth >> dst.baseMipLevel); 1565 const auto to_depth = std::max(1u, p.binding.depth >> dst.baseMipLevel);
@@ -1568,21 +1584,37 @@ inline ReplayResult prepare_texture_copy(const CopyTexture& copy, Prepared& p) {
1568 return ReplayResult::invalid_copy; 1584 return ReplayResult::invalid_copy;
1569 const std::uint32_t w = std::min(padded(box.right - box.left), from.width - box.left); 1585 const std::uint32_t w = std::min(padded(box.right - box.left), from.width - box.left);
1570 const std::uint32_t h = std::min(padded(box.bottom - box.top), from.height - box.top); 1586 const std::uint32_t h = std::min(padded(box.bottom - box.top), from.height - box.top);
1571 // shortcut: into a BC mip whose edge block is partial, Vulkan's extent cannot reach the padded edge; such 1587 const VkImageCopy region{{src.aspectMask, src.baseMipLevel, src.baseArrayLayer, 1},
1572 // a copy is refused until it is staged through a buffer. 1588 {std::int32_t(box.left), std::int32_t(box.top), std::int32_t(box.front)},
1573 if (dst_block > 1 && (copy.x + w * dst_block > to.width || copy.y + h * dst_block > to.height)) 1589 {dst.aspectMask, dst.baseMipLevel, dst.baseArrayLayer, 1},
1574 return ReplayResult::invalid_copy; 1590 {std::int32_t(copy.x), std::int32_t(copy.y), std::int32_t(copy.z)},
1575 p.image_copies.push_back({{src.aspectMask, src.baseMipLevel, src.baseArrayLayer, 1}, 1591 {w, h, box.back - box.front}};
1576 {std::int32_t(box.left), std::int32_t(box.top), std::int32_t(box.front)}, 1592 const std::uint32_t dst_w = w * dst_block, dst_h = h * dst_block;
1577 {dst.aspectMask, dst.baseMipLevel, dst.baseArrayLayer, 1}, 1593 if (dst_block > 1 && (copy.x + dst_w > to.width || copy.y + dst_h > to.height)) {
1578 {std::int32_t(copy.x), std::int32_t(copy.y), std::int32_t(copy.z)}, 1594 // Each uncompressed texel supplies a whole BC block. Keep the same scratch row and slice strides
1579 {w, h, box.back - box.front}}); 1595 // in bytes on both sides, with a destination extent clipped to the actual mip.
1596 const VkBufferImageCopy read{0, w, h, region.srcSubresource, region.srcOffset, region.extent};
1597 const VkBufferImageCopy write{0, dst_w, dst_h, region.dstSubresource, region.dstOffset,
1598 {std::min(dst_w, to.width - copy.x), std::min(dst_h, to.height - copy.y), region.extent.depth}};
1599 p.staged_reads.push_back(read);
1600 p.staged_writes.push_back(write);
1601 } else {
1602 p.image_copies.push_back(region);
1603 }
1580 p.range = dst; 1604 p.range = dst;
1581 p.source_range = src; 1605 p.source_range = src;
1582 return ReplayResult::success; 1606 return ReplayResult::success;
1583 } 1607 }
1584 std::uint32_t w = box.right - box.left, h = box.bottom - box.top; 1608 std::uint32_t w = box.right - box.left, h = box.bottom - box.top;
1585 const std::uint32_t d = box.back - box.front; 1609 const std::uint32_t d = box.back - box.front;
1610 if (p.same_copy_subresource) {
1611 const auto intersects = [](std::uint32_t a, std::uint32_t b, std::uint32_t size) {
1612 return (a < b ? b - a : a - b) < size;
1613 };
1614 if (intersects(box.left, copy.x, padded(w)) && intersects(box.top, copy.y, padded(h)) &&
1615 intersects(box.front, copy.z, d))
1616 return ReplayResult::invalid_copy;
1617 }
1586 if (block > 1) { 1618 if (block > 1) {
1587 // D3D12 copies whole blocks: the box is rounded up to blocks and must fit the destination's padded mip. 1619 // D3D12 copies whole blocks: the box is rounded up to blocks and must fit the destination's padded mip.
1588 // Vulkan takes an extent that is a block multiple or reaches the edge of each image separately, so the 1620 // Vulkan takes an extent that is a block multiple or reaches the edge of each image separately, so the
@@ -1934,8 +1966,9 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct
1934 }; 1966 };
1935 1967
1936 p.colors.assign(pipeline->color_formats.size(), {}); 1968 p.colors.assign(pipeline->color_formats.size(), {});
1937 for (std::size_t slot = 0; slot < draw.render_target_count && slot < draw.render_targets.size() && slot < p.colors.size(); ++slot) { 1969 const std::uint32_t render_target_count = draw.views ? draw.views->render_target_count : 0;
1938 const TargetView& target = draw.render_targets[slot]; 1970 for (std::size_t slot = 0; slot < render_target_count && slot < p.colors.size(); ++slot) {
1971 const TargetView& target = draw.views->render_targets[slot];
1939 if (!target.resource) continue; 1972 if (!target.resource) continue;
1940 const ResourceBinding* binding = resolve(target.resource); 1973 const ResourceBinding* binding = resolve(target.resource);
1941 if (!binding) return ReplayResult::unresolved_resource; 1974 if (!binding) return ReplayResult::unresolved_resource;
@@ -1993,7 +2026,8 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct
1993 p.vertex_offsets.resize(slot + 1, 0); 2026 p.vertex_offsets.resize(slot + 1, 0);
1994 p.vertex_sizes.resize(slot + 1, VK_WHOLE_SIZE); 2027 p.vertex_sizes.resize(slot + 1, VK_WHOLE_SIZE);
1995 p.vertex_strides.resize(slot + 1, 0); 2028 p.vertex_strides.resize(slot + 1, 0);
1996 const bool bound = slot < draw.vertex_buffers.size() && draw.vertex_buffers[slot].va; 2029 const bool bound = draw.views && slot < draw.views->vertex_buffers.size() &&
2030 draw.views->vertex_buffers[slot].va;
1997 if (!bound) { 2031 if (!bound) {
1998 if (!vk.zero_buffer) return ReplayResult::unresolved_resource; 2032 if (!vk.zero_buffer) return ReplayResult::unresolved_resource;
1999 p.vertex_buffers[slot] = vk.zero_buffer; 2033 p.vertex_buffers[slot] = vk.zero_buffer;
@@ -2002,7 +2036,7 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct
2002 p.vertex_strides[slot] = 0; 2036 p.vertex_strides[slot] = 0;
2003 continue; 2037 continue;
2004 } 2038 }
2005 const VertexBufferView& view = draw.vertex_buffers[slot]; 2039 const VertexBufferView& view = draw.views->vertex_buffers[slot];
2006 std::uint64_t size = view.size; 2040 std::uint64_t size = view.size;
2007 if (!vk.buffer_at(view.va, size, p.vertex_buffers[slot], p.vertex_offsets[slot])) 2041 if (!vk.buffer_at(view.va, size, p.vertex_buffers[slot], p.vertex_offsets[slot]))
2008 return ReplayResult::unresolved_resource; 2042 return ReplayResult::unresolved_resource;
@@ -2163,14 +2197,16 @@ inline void plan_statistics_segments(PreparedList& out) {
2163 std::size_t next_query = 0; 2197 std::size_t next_query = 0;
2164 for (std::size_t i = 0; i < out.commands.size(); ++i) { 2198 for (std::size_t i = 0; i < out.commands.size(); ++i) {
2165 auto& p = out.commands[i]; 2199 auto& p = out.commands[i];
2166 if (begin && (p.predicate.scratch || !p.predicated_copy.empty() || p.has_depth24)) 2200 if (begin && (p.predicate.scratch || !p.predicated_copy.empty() || p.has_depth24 ||
2201 p.counted_dispatch.indirect))
2167 inner.push_back({&p.statistics_end, &p.statistics_begin}); 2202 inner.push_back({&p.statistics_end, &p.statistics_begin});
2168 if (next_query == out.queries.size() || out.queries[next_query].command != i) continue; 2203 if (next_query == out.queries.size() || out.queries[next_query].command != i) continue;
2169 auto& query = out.queries[next_query++]; 2204 auto& query = out.queries[next_query++];
2170 const Command& command = out.list->commands()[i]; 2205 const Command& command = out.list->commands()[i];
2171 const auto range = query_range(command); 2206 const auto range = query_range(command);
2172 if (std::holds_alternative<ResolveQueries>(command)) { 2207 if (std::holds_alternative<ResolveQueries>(command)) {
2173 if (begin && range.type != d3d12_query::timestamp) 2208 // A stream-output resolve only fills zeros (no dispatch), so it needs no split.
2209 if (begin && range.type != d3d12_query::timestamp && !is_so_statistics(range.type))
2174 inner.push_back({&query.statistics_end, &query.statistics_begin}); 2210 inner.push_back({&query.statistics_end, &query.statistics_begin});
2175 } else if (range.type == d3d12_query::pipeline_statistics) { 2211 } else if (range.type == d3d12_query::pipeline_statistics) {
2176 if (std::holds_alternative<BeginQuery>(command)) { 2212 if (std::holds_alternative<BeginQuery>(command)) {
@@ -2212,7 +2248,8 @@ inline ReplayResult plan_overlapping_statistics_segments(PreparedList& out) {
2212 if (!query) { 2248 if (!query) {
2213 // A helper dispatch while a query runs would be counted into it (D3D-162): close the shared physical 2249 // A helper dispatch while a query runs would be counted into it (D3D-162): close the shared physical
2214 // segment before it and open a new one after, the way resolves do. 2250 // segment before it and open a new one after, the way resolves do.
2215 if (!active.empty() && (p.predicate.scratch || !p.predicated_copy.empty() || p.has_depth24)) { 2251 if (!active.empty() && (p.predicate.scratch || !p.predicated_copy.empty() || p.has_depth24 ||
2252 p.counted_dispatch.indirect)) {
2216 p.statistics_end = current; 2253 p.statistics_end = current;
2217 current = out.statistics_segment_count++; 2254 current = out.statistics_segment_count++;
2218 p.statistics_begin = current; 2255 p.statistics_begin = current;
@@ -2703,6 +2740,8 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2703 } else if (range.type == d3d12_query::binary_occlusion) { 2740 } else if (range.type == d3d12_query::binary_occlusion) {
2704 overlaps |= begin && (ordinary_active || binary_active); 2741 overlaps |= begin && (ordinary_active || binary_active);
2705 if (begin) ++binary_active; else --binary_active; 2742 if (begin) ++binary_active; else --binary_active;
2743 } else if (is_so_statistics(range.type)) {
2744 // No Vulkan query runs for it (QueryPool::pool is null), so it overlaps nothing.
2706 } else { 2745 } else {
2707 statistics_overlaps |= begin && statistics_active_count; 2746 statistics_overlaps |= begin && statistics_active_count;
2708 if (begin) ++statistics_active_count; else --statistics_active_count; 2747 if (begin) ++statistics_active_count; else --statistics_active_count;
@@ -2742,10 +2781,19 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2742 if (!detail::indirect_range(*cnt, ind->count_offset, sizeof(std::uint32_t))) 2781 if (!detail::indirect_range(*cnt, ind->count_offset, sizeof(std::uint32_t)))
2743 return ReplayResult::invalid_indirect_arguments; 2782 return ReplayResult::invalid_indirect_arguments;
2744 p.source = *cnt; 2783 p.source = *cnt;
2745 if ((ind->kind == IndirectKind::draw && !vk.draw_indirect_count) || 2784 if (ind->kind == IndirectKind::dispatch) {
2746 (ind->kind == IndirectKind::draw_indexed && !vk.draw_indexed_indirect_count) || 2785 // Vulkan lacks vkCmdDispatchIndirectCount. Copy the GPU-visible commands to private scratch
2747 ind->kind == IndirectKind::dispatch) 2786 // and replace commands past min(count, max_count) with zero-group dispatches.
2787 if (!ind->pipeline || !vk.dispatch_indirect || !vk.prepare_counted_dispatch ||
2788 !vk.emit_counted_dispatch || (statistics_active && !statistics_helpers) ||
2789 !vk.prepare_counted_dispatch(p.binding.buffer, p.binding.buffer_offset + ind->argument_offset,
2790 p.source.buffer, p.source.buffer_offset + ind->count_offset,
2791 ind->stride, ind->max_count, p.counted_dispatch))
2792 return ReplayResult::unsupported;
2793 } else if ((ind->kind == IndirectKind::draw && !vk.draw_indirect_count) ||
2794 (ind->kind == IndirectKind::draw_indexed && !vk.draw_indexed_indirect_count)) {
2748 return ReplayResult::unsupported; 2795 return ReplayResult::unsupported;
2796 }
2749 } else { 2797 } else {
2750 if ((ind->kind == IndirectKind::draw && !vk.draw_indirect) || 2798 if ((ind->kind == IndirectKind::draw && !vk.draw_indirect) ||
2751 (ind->kind == IndirectKind::draw_indexed && !vk.draw_indexed_indirect) || 2799 (ind->kind == IndirectKind::draw_indexed && !vk.draw_indexed_indirect) ||
@@ -2980,6 +3028,9 @@ inline void emit_query(const PreparedList& list, const detail::PreparedQuery& qu
2980 begin_statistics(); 3028 begin_statistics();
2981 return; 3029 return;
2982 } 3030 }
3031 // A heap without a Vulkan pool (stream-output statistics: the layer has no stream output) runs nothing for
3032 // BeginQuery and EndQuery; its resolves were planned as zero fills.
3033 if (!heap.pool && !std::holds_alternative<ResolveQueries>(command)) return;
2983 if (const auto* begin = std::get_if<BeginQuery>(&command)) { 3034 if (const auto* begin = std::get_if<BeginQuery>(&command)) {
2984 vk.reset_query_pool(cb, heap.pool, begin->index, 1); 3035 vk.reset_query_pool(cb, heap.pool, begin->index, 1);
2985 const bool precise = begin->type == d3d12_query::occlusion && heap.precise; 3036 const bool precise = begin->type == d3d12_query::occlusion && heap.precise;
@@ -3346,10 +3397,14 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3346 vk.copy_buffer_to_image(command_buffer, p.staged, p.binding.image, dst_layout, 3397 vk.copy_buffer_to_image(command_buffer, p.staged, p.binding.image, dst_layout,
3347 std::uint32_t(p.staged_writes.size()), p.staged_writes.data()); 3398 std::uint32_t(p.staged_writes.size()), p.staged_writes.data());
3348 } else if (!p.image_copies.empty()) { 3399 } else if (!p.image_copies.empty()) {
3400 // A subresource can be both the source and destination only in a shared layout.
3401 const bool self = p.same_copy_subresource;
3349 const VkImageLayout src_layout = detail::copy_layout( 3402 const VkImageLayout src_layout = detail::copy_layout(
3350 vk, command_buffer, p.source, src_id, detail::planes_for_layout(p.source, p.source_range, separate), 3403 vk, command_buffer, p.source, src_id, detail::planes_for_layout(p.source, p.source_range, separate),
3351 VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT, tracker); 3404 self ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
3352 const VkImageLayout dst_layout = detail::copy_layout( 3405 self ? VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT : VK_ACCESS_TRANSFER_READ_BIT,
3406 tracker);
3407 const VkImageLayout dst_layout = self ? src_layout : detail::copy_layout(
3353 vk, command_buffer, p.binding, dst_id, detail::planes_for_layout(p.binding, p.range, separate), 3408 vk, command_buffer, p.binding, dst_id, detail::planes_for_layout(p.binding, p.range, separate),
3354 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, tracker); 3409 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, tracker);
3355 const auto count = std::uint32_t(p.image_copies.size()); 3410 const auto count = std::uint32_t(p.image_copies.size());
@@ -3562,7 +3617,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3562 vk.copy_buffer(command_buffer, p.source.buffer, p.binding.buffer, 1, p.buffer_copies.data()); 3617 vk.copy_buffer(command_buffer, p.source.buffer, p.binding.buffer, 1, p.buffer_copies.data());
3563 } else if (const auto* ind = std::get_if<ExecuteIndirect>(&command)) { 3618 } else if (const auto* ind = std::get_if<ExecuteIndirect>(&command)) {
3564 const VkDeviceSize arguments = p.binding.buffer_offset + ind->argument_offset; 3619 const VkDeviceSize arguments = p.binding.buffer_offset + ind->argument_offset;
3565 if (ind->count_buffer) { 3620 if (ind->count_buffer && ind->kind != IndirectKind::dispatch) {
3566 const VkDeviceSize count = p.source.buffer_offset + ind->count_offset; 3621 const VkDeviceSize count = p.source.buffer_offset + ind->count_offset;
3567 if (ind->kind == IndirectKind::draw) { 3622 if (ind->kind == IndirectKind::draw) {
3568 vk.draw_indirect_count(command_buffer, p.binding.buffer, arguments, p.source.buffer, 3623 vk.draw_indirect_count(command_buffer, p.binding.buffer, arguments, p.source.buffer,
@@ -3577,6 +3632,12 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3577 } else if (ind->kind == IndirectKind::draw_indexed) { 3632 } else if (ind->kind == IndirectKind::draw_indexed) {
3578 vk.draw_indexed_indirect(command_buffer, p.binding.buffer, arguments, ind->max_count, ind->stride); 3633 vk.draw_indexed_indirect(command_buffer, p.binding.buffer, arguments, ind->max_count, ind->stride);
3579 } else if (ind->kind == IndirectKind::dispatch) { 3634 } else if (ind->kind == IndirectKind::dispatch) {
3635 if (ind->count_buffer) {
3636 // No D3D12 query must count this internal compute pass as an application dispatch.
3637 end_statistics();
3638 vk.emit_counted_dispatch(command_buffer, p.counted_dispatch);
3639 begin_statistics();
3640 }
3580 if (ind->pipeline) { 3641 if (ind->pipeline) {
3581 ShaderUserData data{}; 3642 ShaderUserData data{};
3582 std::copy(ind->user_data.begin(), ind->user_data.end(), data.s); 3643 std::copy(ind->user_data.begin(), ind->user_data.end(), data.s);
@@ -3590,8 +3651,10 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3590 &data); 3651 &data);
3591 } 3652 }
3592 for (std::uint32_t k = 0; k < ind->max_count; ++k) { 3653 for (std::uint32_t k = 0; k < ind->max_count; ++k) {
3593 vk.dispatch_indirect(command_buffer, p.binding.buffer, 3654 vk.dispatch_indirect(command_buffer,
3594 arguments + VkDeviceSize(k) * ind->stride); 3655 ind->count_buffer ? p.counted_dispatch.indirect : p.binding.buffer,
3656 (ind->count_buffer ? p.counted_dispatch.offset + VkDeviceSize(k) * 12
3657 : arguments + VkDeviceSize(k) * ind->stride));
3595 } 3658 }
3596 } 3659 }
3597 } 3660 }
@@ -3758,18 +3821,33 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3758} 3821}
3759 3822
3760// prepare + emit for one list. A failed replay leaves the command buffer and the tracker untouched. 3823// prepare + emit for one list. A failed replay leaves the command buffer and the tracker untouched.
3824// With `keep` and vk.create_segment_pool (and the sum helpers) set, overlapping occlusion or statistics queries get
3825// segment pools as in the batched path; the caller holds `keep` until the command buffer has completed.
3761template<typename Resolve> 3826template<typename Resolve>
3762ReplayResult replay(const CommandList& list, VkCommandBuffer command_buffer, Resolve&& resolve, 3827ReplayResult replay(const CommandList& list, VkCommandBuffer command_buffer, Resolve&& resolve,
3763 const ReplayFunctions& vk, LayoutTracker* tracker = nullptr) { 3828 const ReplayFunctions& vk, LayoutTracker* tracker = nullptr,
3829 std::vector<std::shared_ptr<const OcclusionSegmentPool>>* keep = nullptr) {
3764 if (tracker && tracker->separate_depth_stencil_layouts() != vk.separate_depth_stencil_layouts) 3830 if (tracker && tracker->separate_depth_stencil_layouts() != vk.separate_depth_stencil_layouts)
3765 return ReplayResult::unsupported; 3831 return ReplayResult::unsupported;
3832 const bool pools = keep && vk.create_segment_pool && vk.sum_occlusion && vk.resolve_binary_occlusion &&
3833 vk.sum_statistics && vk.sum_binary_occlusion;
3766 PreparedList prepared; 3834 PreparedList prepared;
3767 if (const auto result = prepare(list, resolve, vk, prepared); result != ReplayResult::success) return result; 3835 if (const auto result = prepare(list, resolve, vk, prepared, pools); result != ReplayResult::success)
3836 return result;
3768 if (tracker && zero_clear_unavailable(prepared, vk, *tracker)) return ReplayResult::unsupported; 3837 if (tracker && zero_clear_unavailable(prepared, vk, *tracker)) return ReplayResult::unsupported;
3838 std::shared_ptr<const OcclusionSegmentPool> physical, statistics;
3839 if (pools && prepared.segment_count &&
3840 !(physical = vk.create_segment_pool(VK_QUERY_TYPE_OCCLUSION, prepared.segment_count)))
3841 return ReplayResult::unsupported;
3842 if (pools && prepared.statistics_segment_count &&
3843 !(statistics = vk.create_segment_pool(VK_QUERY_TYPE_PIPELINE_STATISTICS, prepared.statistics_segment_count)))
3844 return ReplayResult::unsupported;
3769 QueryReplay queries; 3845 QueryReplay queries;
3770 if (const auto result = queries.plan(prepared); result != ReplayResult::success) return result; 3846 if (const auto result = queries.plan(prepared, physical, 0, pools, statistics, 0); result != ReplayResult::success)
3847 return result;
3771 emit(prepared, command_buffer, vk, tracker); 3848 emit(prepared, command_buffer, vk, tracker);
3772 queries.commit(); // the caller owns submission of the legacy command buffer 3849 queries.commit(); // the caller owns submission of the legacy command buffer
3850 if (keep) keep->insert(keep->end(), queries.retained.begin(), queries.retained.end());
3773 return ReplayResult::success; 3851 return ReplayResult::success;
3774} 3852}
3775 3853
diff --git a/runtime/test/active_input_test.cpp b/runtime/test/active_input_test.cpp
new file mode 100644
index 000000000..11c628320
--- /dev/null
+++ b/runtime/test/active_input_test.cpp
@@ -0,0 +1,236 @@
1// ActiveInputTracker (src/active_input.h) on synthetic samples with its own clock: what counts as deliberate input
2// (edges only, thresholds, baselines), the minimum time between changes, several devices of one family, a device that
3// goes and comes back, and a forced family. No SDL, no controller, no GPU.
4#include "../src/active_input.h"
5
6#include <cstdio>
7#include <iterator>
8#include <string_view>
9
10using namespace leonida;
11
12#define EXPECT(condition) do { \
13 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
14} while (0)
15
16namespace {
17
18constexpr std::uint64_t ms = 1000; // the tracker's clock is in microseconds
19
20InputSample rest() { return {}; }
21
22InputSample button(std::uint32_t bits) {
23 InputSample s;
24 s.buttons = bits;
25 return s;
26}
27
28InputSample left_stick(float x, float y) {
29 InputSample s;
30 s.left_x = x;
31 s.left_y = y;
32 return s;
33}
34
35InputSample right_stick(float x, float y) {
36 InputSample s;
37 s.right_x = x;
38 s.right_y = y;
39 return s;
40}
41
42InputSample triggers(float left, float right) {
43 InputSample s;
44 s.left_trigger = left;
45 s.right_trigger = right;
46 return s;
47}
48
49// Device keys and families used below.
50constexpr std::uint64_t xbox = 1, dualsense = 2, ds4 = 3, keyboard = 4, xbox2 = 5, switch_pro = 6;
51
52int test_start_and_baseline() {
53 ActiveInputTracker t;
54 EXPECT(t.active() == InputFamily::Xbox && t.generation() == 0 && !t.forced());
55
56 // A first sample is a baseline, whatever it holds: a pad connecting with a button down changes nothing.
57 EXPECT(t.observe(dualsense, InputFamily::PlayStation5, button(1), 0) == InputEdge::None);
58 EXPECT(t.active() == InputFamily::Xbox && t.generation() == 0);
59 // Still held: no edge.
60 EXPECT(t.observe(dualsense, InputFamily::PlayStation5, button(1), 10 * ms) == InputEdge::None);
61 // Released, then pressed again: that press is the first deliberate input, and the first change needs no wait.
62 EXPECT(t.observe(dualsense, InputFamily::PlayStation5, rest(), 20 * ms) == InputEdge::None);
63 EXPECT(t.observe(dualsense, InputFamily::PlayStation5, button(1), 30 * ms) == InputEdge::Button);
64 EXPECT(t.active() == InputFamily::PlayStation5 && t.generation() == 1);
65 return 0;
66}
67
68int test_drift_and_thresholds() {
69 ActiveInputTracker t;
70 EXPECT(t.observe(xbox, InputFamily::Xbox, rest(), 0) == InputEdge::None);
71 EXPECT(t.observe(dualsense, InputFamily::PlayStation5, rest(), 0) == InputEdge::None);
72
73 // A worn stick drifting around inside the radius never counts, however long it wanders.
74 for (int i = 0; i < 200; ++i) {
75 const float d = 0.05f + 0.25f * static_cast<float>(i % 7) / 6.0f; // 0.05 .. 0.30
76 EXPECT(t.observe(dualsense, InputFamily::PlayStation5, left_stick(d, -d * 0.5f), (1 + i) * ms) ==
77 InputEdge::None);
78 }
79 // Just inside the radius (0.35 along a diagonal is 0.247 per axis): nothing.
80 EXPECT(t.observe(dualsense, InputFamily::PlayStation5, left_stick(0.24f, 0.24f), 300 * ms) == InputEdge::None);
81 // Leaving it is an edge.
82 EXPECT(t.observe(dualsense, InputFamily::PlayStation5, left_stick(0.3f, 0.3f), 310 * ms) == InputEdge::Stick);
83 EXPECT(t.active() == InputFamily::PlayStation5 && t.generation() == 1);
84 // Held over the radius: no further edge from the same stick.
85 EXPECT(t.observe(dualsense, InputFamily::PlayStation5, left_stick(1.0f, 0.0f), 320 * ms) == InputEdge::None);
86
87 // Triggers: resting at 0.29 is not a pull; rising past 0.3 is.
88 EXPECT(t.observe(xbox, InputFamily::Xbox, triggers(0.29f, 0.0f), 700 * ms) == InputEdge::None);
89 EXPECT(t.active() == InputFamily::PlayStation5);
90 EXPECT(t.observe(xbox, InputFamily::Xbox, triggers(0.31f, 0.0f), 710 * ms) == InputEdge::Trigger);
91 EXPECT(t.active() == InputFamily::Xbox && t.generation() == 2);
92 // A trigger held further down does not count again.
93 EXPECT(t.observe(xbox, InputFamily::Xbox, triggers(0.9f, 0.0f), 720 * ms) == InputEdge::None);
94 return 0;
95}
96
97int test_min_switch_time() {
98 ActiveInputTracker t;
99 t.observe(xbox, InputFamily::Xbox, rest(), 0);
100 t.observe(dualsense, InputFamily::PlayStation5, rest(), 0);
101
102 EXPECT(t.observe(dualsense, InputFamily::PlayStation5, button(2), 1000 * ms) == InputEdge::Button);
103 EXPECT(t.active() == InputFamily::PlayStation5 && t.generation() == 1);
104 // 100 ms later the Xbox pad's press is inside the window: ignored, and not remembered for later.
105 EXPECT(t.observe(xbox, InputFamily::Xbox, button(1), 1100 * ms) == InputEdge::None);
106 EXPECT(t.active() == InputFamily::PlayStation5);
107 EXPECT(t.observe(xbox, InputFamily::Xbox, button(1), 1400 * ms) == InputEdge::None); // still held: no edge
108 EXPECT(t.active() == InputFamily::PlayStation5);
109 // Released and pressed again after the window: that one counts.
110 t.observe(xbox, InputFamily::Xbox, rest(), 1500 * ms);
111 EXPECT(t.observe(xbox, InputFamily::Xbox, button(1), 1600 * ms) == InputEdge::Button);
112 EXPECT(t.active() == InputFamily::Xbox && t.generation() == 2);
113 // Exactly at the window's end counts (the window is "less than min_switch_us").
114 EXPECT(t.observe(dualsense, InputFamily::PlayStation5, button(2 | 4), 1900 * ms) == InputEdge::Button);
115 EXPECT(t.active() == InputFamily::PlayStation5 && t.generation() == 3);
116
117 // A zero window lets every deliberate input switch at once.
118 ActiveInputTracker fast(InputFamily::Xbox, {0.35f, 0.3f, 0});
119 fast.observe(xbox, InputFamily::Xbox, rest(), 0);
120 fast.observe(keyboard, InputFamily::Keyboard, rest(), 0);
121 EXPECT(fast.observe(keyboard, InputFamily::Keyboard, button(8), 1) == InputEdge::Button);
122 EXPECT(fast.observe(xbox, InputFamily::Xbox, button(8), 2) == InputEdge::Button);
123 EXPECT(fast.active() == InputFamily::Xbox && fast.generation() == 2);
124 return 0;
125}
126
127int test_same_family_and_holds() {
128 ActiveInputTracker t;
129 for (std::uint64_t d : {xbox, xbox2}) t.observe(d, InputFamily::Xbox, rest(), 0);
130 t.observe(keyboard, InputFamily::Keyboard, rest(), 0);
131
132 // Input from a second pad of the family already in use changes nothing.
133 EXPECT(t.observe(xbox2, InputFamily::Xbox, button(1), 10 * ms) == InputEdge::None);
134 EXPECT(t.active() == InputFamily::Xbox && t.generation() == 0);
135
136 // The keyboard pad: W held pushes the left stick to full. The first push is the edge; holding it is not.
137 EXPECT(t.observe(keyboard, InputFamily::Keyboard, left_stick(0.0f, 1.0f), 20 * ms) == InputEdge::Stick);
138 EXPECT(t.active() == InputFamily::Keyboard && t.generation() == 1);
139 // The player picks up the Xbox pad while W is still held down: the pad takes over after the window and the held
140 // key does not take it back.
141 EXPECT(t.observe(xbox, InputFamily::Xbox, button(1), 400 * ms) == InputEdge::Button);
142 for (int i = 0; i < 50; ++i)
143 EXPECT(t.observe(keyboard, InputFamily::Keyboard, left_stick(0.0f, 1.0f), (410 + 10 * i) * ms) ==
144 InputEdge::None);
145 EXPECT(t.active() == InputFamily::Xbox && t.generation() == 2);
146
147 // The mouse moves the keyboard pad's right stick: a small jitter stays inside the radius, a real movement
148 // leaves it.
149 t.observe(keyboard, InputFamily::Keyboard, rest(), 1000 * ms);
150 EXPECT(t.observe(keyboard, InputFamily::Keyboard, right_stick(0.03f, 0.0f), 1010 * ms) == InputEdge::None);
151 EXPECT(t.observe(keyboard, InputFamily::Keyboard, right_stick(0.5f, -0.1f), 1020 * ms) == InputEdge::Stick);
152 EXPECT(t.active() == InputFamily::Keyboard && t.generation() == 3);
153 return 0;
154}
155
156int test_reconnect() {
157 ActiveInputTracker t;
158 t.observe(ds4, InputFamily::PlayStation4, rest(), 0);
159 EXPECT(t.observe(ds4, InputFamily::PlayStation4, button(1), 10 * ms) == InputEdge::Button);
160 EXPECT(t.active() == InputFamily::PlayStation4);
161
162 // Unplugged while the button was down; it comes back with the button still down. The new first sample is a
163 // baseline, so there is no edge to count, and no stale state from before.
164 t.forget(ds4);
165 t.observe(switch_pro, InputFamily::Nintendo, rest(), 0);
166 EXPECT(t.observe(switch_pro, InputFamily::Nintendo, button(1), 500 * ms) == InputEdge::Button);
167 EXPECT(t.active() == InputFamily::Nintendo);
168 EXPECT(t.observe(ds4, InputFamily::PlayStation4, button(1), 900 * ms) == InputEdge::None);
169 EXPECT(t.active() == InputFamily::Nintendo);
170 t.observe(ds4, InputFamily::PlayStation4, rest(), 910 * ms);
171 EXPECT(t.observe(ds4, InputFamily::PlayStation4, button(1), 920 * ms) == InputEdge::Button);
172 EXPECT(t.active() == InputFamily::PlayStation4 && t.generation() == 3);
173 return 0;
174}
175
176int test_forced() {
177 ActiveInputTracker t;
178 t.observe(dualsense, InputFamily::PlayStation5, rest(), 0);
179 t.observe(keyboard, InputFamily::Keyboard, rest(), 0);
180
181 t.force(InputFamily::Keyboard);
182 EXPECT(t.forced() && t.active() == InputFamily::Keyboard && t.generation() == 1);
183 // Forcing the same family again changes nothing.
184 t.force(InputFamily::Keyboard);
185 EXPECT(t.generation() == 1);
186
187 // Tracking still runs underneath: the DualSense becomes the tracked family, but the answer stays forced and the
188 // generation does not move.
189 EXPECT(t.observe(dualsense, InputFamily::PlayStation5, button(1), 10 * ms) == InputEdge::Button);
190 EXPECT(t.tracked() == InputFamily::PlayStation5 && t.active() == InputFamily::Keyboard && t.generation() == 1);
191
192 // Clearing the force goes straight back to the device in use.
193 t.force(std::nullopt);
194 EXPECT(!t.forced() && t.active() == InputFamily::PlayStation5 && t.generation() == 2);
195
196 // Forcing the family that is already tracked does not change the answer, so no new generation.
197 t.force(InputFamily::PlayStation5);
198 EXPECT(t.forced() && t.active() == InputFamily::PlayStation5 && t.generation() == 2);
199 t.force(std::nullopt);
200 EXPECT(t.generation() == 2);
201 return 0;
202}
203
204int test_names() {
205 EXPECT(std::string_view(input_family_name(InputFamily::PlayStation5)) == "PlayStation 5");
206 EXPECT(std::string_view(input_family_name(InputFamily::Keyboard)) == "keyboard and mouse");
207 EXPECT(std::string_view(input_edge_name(InputEdge::Stick)) == "stick movement");
208 return 0;
209}
210
211} // namespace
212
213int main() {
214 struct Case {
215 const char* name;
216 int (*run)();
217 };
218 const Case cases[] = {
219 {"start and baseline", test_start_and_baseline},
220 {"drift and thresholds", test_drift_and_thresholds},
221 {"minimum time between changes", test_min_switch_time},
222 {"one family, held input", test_same_family_and_holds},
223 {"reconnect", test_reconnect},
224 {"forced family", test_forced},
225 {"names", test_names},
226 };
227 int failures = 0;
228 for (const Case& c : cases) {
229 const int r = c.run();
230 std::printf("%s: %s\n", c.name, r ? "FAIL" : "ok");
231 failures += r;
232 }
233 const int total = static_cast<int>(std::size(cases));
234 std::printf("active input: %d of %d cases pass\n", total - failures, total);
235 return failures ? 1 : 0;
236}
diff --git a/runtime/test/buffer_va_index_test.cpp b/runtime/test/buffer_va_index_test.cpp
index 3368e8b8b..b5b5e997f 100644
--- a/runtime/test/buffer_va_index_test.cpp
+++ b/runtime/test/buffer_va_index_test.cpp
@@ -27,10 +27,10 @@ void check(bool ok, const char* what) {
27 ++failures; 27 ++failures;
28} 28}
29 29
30// The id that holds `va`, 0 for none. 30// The id that holds `va` (preferring one that holds `bytes` from it), 0 for none.
31std::uintptr_t at(const Index& index, std::uint64_t va) { 31std::uintptr_t at(const Index& index, std::uint64_t va, std::uint64_t bytes = 1) {
32 Index::Hit hit{}; 32 Index::Hit hit{};
33 return index.find(va, hit) ? hit.id : 0; 33 return index.find(va, hit, bytes) ? hit.id : 0;
34} 34}
35 35
36void fixed_cases() { 36void fixed_cases() {
@@ -64,6 +64,13 @@ void fixed_cases() {
64 check(at(alias, 0x1f000) == 10, "past every short buffer"); 64 check(at(alias, 0x1f000) == 10, "past every short buffer");
65 check(at(alias, 0x20000) == 0, "past the long buffer"); 65 check(at(alias, 0x20000) == 0, "past the long buffer");
66 66
67 // A view that starts in a short buffer and runs past its end: the long buffer around it holds all of it.
68 check(at(alias, 0x11080, 0x80) == 11, "a view that fits in the short buffer stays in it");
69 check(at(alias, 0x11080, 0x81) == 10, "a view past the short buffer's end goes to the long one around it");
70 check(at(alias, 0x1ff00, 0x200) == 10, "a view no range holds: the closest that holds its start");
71 check(at(alias, 0x11080, 0x10000) == 11, "a view past the long buffer too: the closest start, as without a size");
72 check(at(alias, 0x11080, 0) == 11, "a size of 0 counts as one byte");
73
67 // Two resources placed at the same offset: the larger ID, either way they were added. 74 // Two resources placed at the same offset: the larger ID, either way they were added.
68 alias.insert(0x30000, 0x100, 21); 75 alias.insert(0x30000, 0x100, 21);
69 alias.insert(0x30000, 0x200, 20); 76 alias.insert(0x30000, 0x200, 20);
@@ -100,19 +107,25 @@ void fixed_cases() {
100 check(bound.longest() == 0 && bound.size() == 0, "an empty index has no bound"); 107 check(bound.longest() == 0 && bound.size() == 0, "an empty index has no bound");
101} 108}
102 109
103// The rule BufferVaIndex follows, by a scan: among the ranges that hold va, the greatest (start, id). 110// The rule BufferVaIndex follows, by a scan: among the ranges that hold all of [va, va + bytes), the greatest
111// (start, id); when none does, the greatest among those that hold va.
104struct Range { 112struct Range {
105 std::uint64_t start, size; 113 std::uint64_t start, size;
106 std::uintptr_t id; 114 std::uintptr_t id;
107}; 115};
108 116
109std::uintptr_t scan(const std::vector<Range>& ranges, std::uint64_t va) { 117std::uintptr_t scan(const std::vector<Range>& ranges, std::uint64_t va, std::uint64_t bytes = 1) {
110 const Range* best = nullptr; 118 const Range* best = nullptr;
119 const Range* whole = nullptr;
120 const auto greater = [](const Range& a, const Range* b) {
121 return !b || a.start > b->start || (a.start == b->start && a.id > b->id);
122 };
111 for (const Range& r : ranges) { 123 for (const Range& r : ranges) {
112 if (va < r.start || va - r.start >= r.size) continue; 124 if (va < r.start || va - r.start >= r.size) continue;
113 if (!best || r.start > best->start || (r.start == best->start && r.id > best->id)) best = &r; 125 if (greater(r, best)) best = &r;
126 if (bytes <= r.size - (va - r.start) && greater(r, whole)) whole = &r;
114 } 127 }
115 return best ? best->id : 0; 128 return whole ? whole->id : best ? best->id : 0;
116} 129}
117 130
118void random_tables() { 131void random_tables() {
@@ -148,9 +161,12 @@ void random_tables() {
148 } 161 }
149 for (int q = 0; q < 2000; ++q) { 162 for (int q = 0; q < 2000; ++q) {
150 const std::uint64_t va = 0x8000 + rng() % (next + 0x20000); 163 const std::uint64_t va = 0x8000 + rng() % (next + 0x20000);
151 if (at(index, va) != scan(ranges, va)) { 164 // A quarter of the lookups name one byte, the rest a view of up to twice the largest buffer.
152 std::printf("FAIL: round %d va 0x%llx: index %llu, scan %llu\n", round, (unsigned long long)va, 165 const std::uint64_t bytes = q % 4 ? 1 + rng() % 0x8000 : 1;
153 (unsigned long long)at(index, va), (unsigned long long)scan(ranges, va)); 166 if (at(index, va, bytes) != scan(ranges, va, bytes)) {
167 std::printf("FAIL: round %d va 0x%llx bytes 0x%llx: index %llu, scan %llu\n", round,
168 (unsigned long long)va, (unsigned long long)bytes,
169 (unsigned long long)at(index, va, bytes), (unsigned long long)scan(ranges, va, bytes));
154 ++failures; 170 ++failures;
155 return; 171 return;
156 } 172 }
diff --git a/runtime/test/bvh_builder_test.cpp b/runtime/test/bvh_builder_test.cpp
index 16e5db4d8..2635711c9 100644
--- a/runtime/test/bvh_builder_test.cpp
+++ b/runtime/test/bvh_builder_test.cpp
@@ -8,7 +8,8 @@
8// LEONIDA_BVH_FLAG=1 (optional: pass true as the constructor's bool argument) 8// LEONIDA_BVH_FLAG=1 (optional: pass true as the constructor's bool argument)
9// LEONIDA_BVH_WARP=1 (optional: use the WARP adapter; the default on an NVIDIA adapter, RT-54) 9// LEONIDA_BVH_WARP=1 (optional: use the WARP adapter; the default on an NVIDIA adapter, RT-54)
10// LEONIDA_BVH_HARDWARE=1 (optional: keep an NVIDIA adapter instead of switching to WARP) 10// LEONIDA_BVH_HARDWARE=1 (optional: keep an NVIDIA adapter instead of switching to WARP)
11// LEONIDA_BVH_RECORD62=1 (optional: print each CreateComputePipelineState's container shape) 11// LEONIDA_BVH_RECORD62=1 (optional: print each CreateComputePipelineState's container shape, its ILDN
12// module name and digest)
12// LEONIDA_BVH_DXIL=1 (optional, with RECORD62: dx.op counts and validator error kinds, needs 13// LEONIDA_BVH_DXIL=1 (optional, with RECORD62: dx.op counts and validator error kinds, needs
13// dxcompiler.dll and dxil.dll on PATH) 14// dxcompiler.dll and dxil.dll on PATH)
14// LEONIDA_BVH_DEVICE=vulkan (optional: the Vulkan-backed ID3D12Device from #119 instead of a PC device) 15// LEONIDA_BVH_DEVICE=vulkan (optional: the Vulkan-backed ID3D12Device from #119 instead of a PC device)
@@ -309,7 +310,8 @@ bool looks_like_iid(uint64_t p, const IID& iid) {
309uint64_t g_slot62_ok = 0, g_slot62_failed = 0; 310uint64_t g_slot62_ok = 0, g_slot62_failed = 0;
310 311
311// The shape of a DXBC container, for the record: its parts (four-character code and size), the DXIL part's shader 312// The shape of a DXBC container, for the record: its parts (four-character code and size), the DXIL part's shader
312// model and DXIL version, the SFI0 feature flags, and whether the hash is zero (unsigned). Counts and flags only. 313// model and DXIL version, the SFI0 feature flags, whether the hash is zero (unsigned), the ILDN module name and the
314// first four bytes of the digest. Counts, flags and names only.
313std::string container_shape(const void* bytecode, size_t length) { 315std::string container_shape(const void* bytecode, size_t length) {
314 const auto* b = static_cast<const uint8_t*>(bytecode); 316 const auto* b = static_cast<const uint8_t*>(bytecode);
315 auto u32 = [&](size_t o) { 317 auto u32 = [&](size_t o) {
@@ -340,9 +342,23 @@ std::string container_shape(const void* bytecode, size_t length) {
340 std::snprintf(item, sizeof(item), "(flags %#llx)", 342 std::snprintf(item, sizeof(item), "(flags %#llx)",
341 static_cast<unsigned long long>(u32(data) | (uint64_t(u32(data + 4)) << 32))); 343 static_cast<unsigned long long>(u32(data) | (uint64_t(u32(data + 4)) << 32)));
342 out += item; 344 out += item;
345 } else if (!std::strcmp(fourcc, "ILDN") && size >= 4) {
346 // ILDN: u16 flags, u16 name length, the debug name (NUL-padded): the module's PDB path, which names the
347 // container (docs/embedded_shaders.md section 3). Only the file name is printed.
348 const uint32_t name_length = u32(data) >> 16;
349 if (size_t(data) + 4 + name_length <= length && name_length > 0) {
350 std::string name(reinterpret_cast<const char*>(b + data + 4), name_length);
351 name.erase(name.find_last_not_of('\0') + 1);
352 name = name.substr(name.find_last_of("\\/") + 1);
353 out += "(" + name + ")";
354 }
343 } 355 }
344 } 356 }
345 return out; 357 // The first four bytes of the container digest (bytes 4..19 of the header), to tell two creations of the same
358 // container from two containers with the same module name.
359 char digest[24];
360 std::snprintf(digest, sizeof(digest), " digest %02x%02x%02x%02x", b[4], b[5], b[6], b[7]);
361 return out + digest;
346} 362}
347 363
348// The module a container belongs to: the file name (without ".pdb") in its ILDN part, a DXIL debug-name record 364// The module a container belongs to: the file name (without ".pdb") in its ILDN part, a DXIL debug-name record
diff --git a/runtime/test/check_atexit.cmake b/runtime/test/check_atexit.cmake
new file mode 100644
index 000000000..255bb3a4f
--- /dev/null
+++ b/runtime/test/check_atexit.cmake
@@ -0,0 +1,71 @@
1# atexit handlers, static destructors and every way out: tiny_atexit run through `gta6rt --run` must print the
2# sequence written below and end with its exit code. That is what the program does natively on Windows, and the
3# native run is held to the same sequence, so the two cannot agree on a wrong answer. Under Wine both runs go through
4# RUNNER, and Wine's own CRT differs in places (it drops a handler registered while handlers run, and its _exit does
5# not wait for the exit lock), so there a native difference is reported without failing; --run is still held to the
6# Windows sequence.
7get_filename_component(guest_dir "${GUEST}" DIRECTORY)
8get_filename_component(guest_name "${GUEST}" NAME)
9
10set(ctors "ctor first;ctor second;main")
11set(handlers "atexit two;atexit registers late;atexit late;atexit one;dtor second;dtor first")
12set(expect_return "${ctors};${handlers}")
13set(code_return 3)
14set(expect_exit "${ctors};${handlers}")
15set(code_exit 7)
16set(expect__exit "${ctors}")
17set(code__exit 8)
18set(expect_quick_exit "${ctors}")
19set(code_quick_exit 9)
20set(expect_ExitProcess "${ctors}")
21set(code_ExitProcess 10)
22set(expect_cexit "${ctors};${handlers};after _cexit")
23set(code_cexit 11)
24set(expect_c_exit "${ctors};after _c_exit;${handlers}")
25set(code_c_exit 12)
26# exit(7) is running a slow handler when a second thread calls _exit(7): the exit lock holds it back.
27set(expect_concurrent_exit "${ctors};slow handler started;slow handler done;${handlers}")
28set(code_concurrent_exit 7)
29
30# The program's own lines, in order, without the prefix; everything gta6rt prints is dropped.
31function(guest_lines output result)
32 string(REPLACE "\r\n" "\n" output "${output}")
33 string(REPLACE ";" "," output "${output}")
34 string(REPLACE "\n" ";" output "${output}")
35 set(lines)
36 foreach(line IN LISTS output)
37 if(line MATCHES "^tiny_atexit: (.*)$")
38 list(APPEND lines "${CMAKE_MATCH_1}")
39 endif()
40 endforeach()
41 set(${result} "${lines}" PARENT_SCOPE)
42endfunction()
43
44set(failures "")
45foreach(mode return exit _exit quick_exit ExitProcess cexit c_exit concurrent_exit)
46 execute_process(COMMAND ${RUNNER} "${GUEST}" ${mode}
47 WORKING_DIRECTORY "${guest_dir}" TIMEOUT 60
48 RESULT_VARIABLE native_code OUTPUT_VARIABLE native_out ERROR_VARIABLE native_err)
49 execute_process(COMMAND ${RUNNER} "${LOADER}" --run "${guest_name}" -- ${mode}
50 WORKING_DIRECTORY "${guest_dir}" TIMEOUT 60
51 RESULT_VARIABLE run_code OUTPUT_VARIABLE run_out ERROR_VARIABLE run_err)
52 guest_lines("${native_out}" native_lines)
53 guest_lines("${run_out}" run_lines)
54 if(NOT native_code STREQUAL code_${mode} OR NOT native_lines STREQUAL expect_${mode})
55 string(CONCAT native_diff "[${mode}] native run differs from the expected sequence"
56 "\n expected (${code_${mode}}): ${expect_${mode}}\n native (${native_code}): ${native_lines}")
57 if(RUNNER)
58 message(STATUS "${native_diff}\n (the host CRT differs from Windows; not a gta6rt failure)")
59 else()
60 string(APPEND failures "\n${native_diff}\n (the fixture or the host changed)")
61 endif()
62 endif()
63 if(NOT run_code STREQUAL code_${mode} OR NOT run_lines STREQUAL expect_${mode})
64 string(APPEND failures "\n[${mode}] gta6rt --run differs from the expected sequence"
65 "\n expected (${code_${mode}}): ${expect_${mode}}\n --run (${run_code}): ${run_lines}\n${run_err}")
66 endif()
67endforeach()
68if(failures)
69 message(FATAL_ERROR "atexit/termination differences:${failures}")
70endif()
71message(STATUS "tiny_atexit: 8 termination paths match the Windows sequence")
diff --git a/runtime/test/check_sparse_queue_family.py b/runtime/test/check_sparse_queue_family.py
new file mode 100644
index 000000000..2a2ce7470
--- /dev/null
+++ b/runtime/test/check_sparse_queue_family.py
@@ -0,0 +1,117 @@
1"""Repo-friendly, optional GPU test: byte-exact Leonida COPY/COMPUTE tiled-buffer replay
2AND actual VK_SHARING_MODE_CONCURRENT on *every* sparse VkBuffer created by the layer.
3
4Runs the original synthetic `d3d12_sparse_queue_family_test` target.
5Invokes the SDK's VK_LAYER_LUNARG_api_dump in a short-lived isolated directory;
6no private-game files, asset paths, device memory dumps, or committed logs.
7
8 python -I check_sparse_queue_family.py path/to/d3d12_sparse_queue_family_test.exe
9 python -I check_sparse_queue_family.py path/to/baseline.exe --expect-baseline-exclusive
10
11By default the baseline fails (exit 1) and patched runtime passes (exit 0).
12If the API dump layer is absent the result skips (exit 77, CTest SKIP_RETURN_CODE).
13"""
14from __future__ import annotations
15
16import argparse
17import os
18import re
19import subprocess
20import sys
21import tempfile
22from pathlib import Path
23
24
25SPARSE_FLAGS = "VkBufferCreateFlags = 7 (VK_BUFFER_CREATE_SPARSE_BINDING_BIT"
26MODE = re.compile(r"sharingMode:\s+VkSharingMode = (VK_SHARING_MODE_\w+)")
27COUNT = re.compile(r"queueFamilyIndexCount:\s+uint32_t = (\d+)")
28INDICES = re.compile(r"pQueueFamilyIndices\[(\d+)\]:\s+const uint32_t = (\d+)")
29CASE = re.compile(r"^RESULT (LAYER_MAP_(?:DIRECT|COPY|COMPUTE)_COPY_COMPUTE) PASS mapped_mismatch=0/65536 unmapped_nonzero=0/65536$", re.M)
30
31
32def check_trace(path: Path, expect_exclusive: bool) -> tuple[int, int]:
33 rows = path.read_text(encoding="utf-8", errors="replace").splitlines()
34 seen = []
35 for i, line in enumerate(rows):
36 if SPARSE_FLAGS not in line:
37 continue
38 tail = "\n".join(rows[i + 1 : i + 13])
39 mode, count = MODE.search(tail), COUNT.search(tail)
40 if not mode or not count:
41 raise AssertionError(f"incomplete API dump sparse VkBuffer at line {i+1}")
42 inds = tuple(int(index) for _, index in INDICES.findall(tail))
43 seen.append((mode.group(1), int(count.group(1)), inds))
44 if len(seen) < 6 or len(seen) % 2:
45 raise AssertionError(f"insufficient sparse VkBuffer create-info records: {len(seen)}")
46 if expect_exclusive:
47 assert all(mode == "VK_SHARING_MODE_EXCLUSIVE" and count == 0
48 for mode, count, _ in seen), f"baseline negative control not reproduced: {set(seen)}"
49 else:
50 assert all(mode == "VK_SHARING_MODE_CONCURRENT" and count >= 2 and len(inds) == count
51 and len(set(inds)) == count
52 for mode, count, inds in seen), f"BUG: not all sparse buffers share active families: {set(seen)}"
53 return len(seen) // 2, len(seen)
54
55
56def main() -> int:
57 parser = argparse.ArgumentParser()
58 parser.add_argument("executable", type=Path, help="Compiled Leonida d3d12_sparse_queue_family_test binary")
59 parser.add_argument("--expect-baseline-exclusive", action="store_true",
60 help="negative-control mode: prove buggy EXCLUSIVE create infos instead of requiring fix")
61 args = parser.parse_args()
62 exe = args.executable.resolve()
63 if not exe.is_file():
64 print(f"ERROR: missing executable {exe}", file=sys.stderr)
65 return 2
66 env = os.environ.copy()
67 # An implicit Vulkan layer may be forced by the loader even if the application
68 # enabled VK_LAYER_KHRONOS_validation explicitly via LEONIDA_VK_VALIDATION.
69 env["VK_INSTANCE_LAYERS"] = "VK_LAYER_LUNARG_api_dump"
70 env["LEONIDA_VK_VALIDATION"] = "1"
71 with tempfile.TemporaryDirectory(prefix="leonida_sparse_trace_") as td:
72 path = Path(td)
73 dump_name = path / "sparse_create_info.log"
74 (path / "vk_layer_settings.txt").write_text(
75 "lunarg_api_dump.file = true\n"
76 f"lunarg_api_dump.log_filename = {dump_name}\n"
77 "lunarg_api_dump.output_format = text\n"
78 "lunarg_api_dump.pre_dump = true\n"
79 "lunarg_api_dump.detailed = true\n",
80 encoding="utf-8",
81 )
82 env["VK_LAYER_SETTINGS_PATH"] = str(path)
83 run = subprocess.run([str(exe)], cwd=path, env=env, capture_output=True,
84 text=True, encoding="utf-8", errors="replace", timeout=40)
85 out = run.stdout + "\n" + run.stderr
86 if run.returncode == 77:
87 print("SKIP 77: Leonida Vulkan device / sparse features unavailable")
88 return 77
89 # The loader refuses the instance when a layer named in VK_INSTANCE_LAYERS (or the validation layer
90 # LEONIDA_VK_VALIDATION asks for) is not installed: that is the "layer absent" skip, not a layer failure.
91 if run.returncode != 0 and "vkCreateInstance" in out and "failed" in out:
92 print("SKIP 77: VK_LAYER_LUNARG_api_dump or VK_LAYER_KHRONOS_validation unavailable (vkCreateInstance failed)")
93 return 77
94 if run.returncode != 0:
95 print(out[-7000:], file=sys.stderr)
96 raise AssertionError(f"Leonida GPU test failed exit={run.returncode}")
97 kinds = sorted(CASE.findall(out))
98 if len(kinds) != 3 or "LAYER_FINAL PASS" not in out:
99 raise AssertionError(f"GPU byte verification missing: cases={kinds}; tail={out[-2000:]}")
100 candidates = list(path.glob("sparse_create_info.log*"))
101 if not candidates:
102 print("SKIP 77: Vulkan SDK VK_LAYER_LUNARG_api_dump unavailable or did not write trace")
103 return 77
104 calls, infos = check_trace(candidates[0], args.expect_baseline_exclusive)
105 print(f"GPU PASS: {len(kinds)} COPY/COMPUTE sparse queue cases, mapped 65,536 bytes exact, unmapped 65,536 zeros")
106 print(f"VK API CONTRACT PASS: {calls} sparse VkBuffer creations / {infos} create-info records = "
107 f"{'EXCLUSIVE negative-control' if args.expect_baseline_exclusive else 'CONCURRENT with 2+ unique families'}")
108 print("Khronos validation enabled; no validation errors observed (GPU does not need to corrupt data for this test)")
109 return 0
110
111
112if __name__ == "__main__":
113 try:
114 raise SystemExit(main())
115 except (AssertionError, subprocess.TimeoutExpired) as error:
116 print(f"FAIL: {error}", file=sys.stderr)
117 raise SystemExit(1)
diff --git a/runtime/test/check_tiny_frame.py b/runtime/test/check_tiny_frame.py
new file mode 100644
index 000000000..8d7dbd8ac
--- /dev/null
+++ b/runtime/test/check_tiny_frame.py
@@ -0,0 +1,124 @@
1"""Run tiny_frame under `gta6rt --run --trace-d3d12` on the Vulkan D3D12 device and check the run from outside.
2
3 python -I check_tiny_frame.py <gta6rt.exe> <tiny_frame.exe> [--probe d3d12_com_test.exe] [--runner wine ...]
4
5Checks the guest's verdict and exit code, that the loader's report binds d3d12_xs.dll!D3D12XboxCreateDevice to the
6shim, and that the D3D12 trace is a gapless numbered sequence in which the calls a first frame needs appear in
7order. Exits 77 (ctest: skipped) when --probe, one of the Vulkan device tests, says
8there is no usable Vulkan device on this machine.
9"""
10
11import argparse
12import os
13import re
14import subprocess
15import sys
16
17SKIP = 77
18
19# The first frame, in the order the fixture makes the calls, as the trace words them (`called` for a method that
20# returns nothing). Other traced calls, such as the queue and fence proxies' own entries, may sit between them.
21EXPECTED = [
22 "D3D12XboxCreateDevice ok",
23 "ID3D12Device::CreateCommandQueue ok",
24 "ID3D12Device::CreateCommandAllocator ok",
25 "ID3D12Device::CreateCommandList ok",
26 "ID3D12Device::CreateFence ok",
27 "ID3D12Device::CreateDescriptorHeap ok",
28 "ID3D12Device::CreateCommittedResource ok",
29 "ID3D12Device::CreateCommittedResource ok",
30 "ID3D12Device::CreateRenderTargetView called",
31 "ID3D12GraphicsCommandList::ClearRenderTargetView called",
32 "ID3D12GraphicsCommandList::ResourceBarrier called",
33 "ID3D12GraphicsCommandList::CopyTextureRegion called",
34 "ID3D12GraphicsCommandList::Close ok",
35 "ID3D12CommandQueue::ExecuteCommandLists ok",
36 "ID3D12CommandQueue::Signal ok",
37]
38
39
40def ordered_subsequence(expected, entries):
41 """The first expected entry that does not appear, in order, in entries; None when all do."""
42 position = 0
43 for want in expected:
44 while position < len(entries) and entries[position] != want:
45 position += 1
46 if position == len(entries):
47 return want
48 position += 1
49 return None
50
51
52def parse_trace(lines):
53 """[(method, outcome)] from the `[d3d12-trace] #N method outcome` lines; raises ValueError on a gap."""
54 entries = []
55 for line in lines:
56 if not line.startswith("[d3d12-trace]"):
57 continue
58 match = re.fullmatch(r"\[d3d12-trace\] #(\d+) (.+) (called|ok|failed|unsupported|ignored|refused)", line)
59 if not match or int(match[1]) != len(entries) + 1:
60 raise ValueError(f"invalid trace sequence at entry {len(entries) + 1}: {line}")
61 entries.append((match[2], match[3]))
62 return entries
63
64
65def check_output(code, output):
66 """A list of problems with one run's exit code and combined output; empty when it is what the test expects."""
67 problems = []
68 lines = output.replace("\r\n", "\n").split("\n")
69 if code != 0:
70 problems.append(f"exit code {code}")
71 if "tiny_frame: OK" not in lines:
72 problems.append("the guest did not print `tiny_frame: OK`")
73 if any(line.startswith("tiny_frame: FAIL") for line in lines):
74 problems.append("the guest reported a failed check")
75 if "game exited with code 0" not in lines:
76 problems.append("gta6rt did not report `game exited with code 0`")
77 if not any(re.fullmatch(r" +shim +d3d12_xs\.dll!D3D12XboxCreateDevice", line) for line in lines):
78 problems.append("d3d12_xs.dll!D3D12XboxCreateDevice was not bound to the shim")
79 try:
80 entries = parse_trace(lines)
81 except ValueError as error:
82 return problems + [str(error)]
83 bad = [f"{method} {outcome}" for method, outcome in entries if outcome in ("failed", "unsupported", "refused")]
84 if bad:
85 problems.append("traced calls that did not succeed: " + ", ".join(bad))
86 missing = ordered_subsequence(EXPECTED, [f"{method} {outcome}" for method, outcome in entries])
87 if missing:
88 problems.append(f"the trace has no `{missing}` at its place in the first-frame order")
89 return problems
90
91
92def main():
93 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
94 parser.add_argument("loader")
95 parser.add_argument("guest")
96 parser.add_argument("--probe", help="a Vulkan device test; its exit code 77 skips this test")
97 parser.add_argument("--runner", action="append", default=[],
98 help="run Windows executables through this command (repeat for its arguments), e.g. wine")
99 options = parser.parse_args()
100 timeout = 180 if options.runner else 90 # a first start of Wine in a fresh prefix can take tens of seconds
101
102 if options.probe:
103 probe = subprocess.run([*options.runner, options.probe], capture_output=True, timeout=timeout)
104 if probe.returncode == SKIP:
105 print("SKIP: no usable Vulkan device (the probe test skipped)")
106 return SKIP
107
108 environment = dict(os.environ, LEONIDA_D3D12="vulkan")
109 run = subprocess.run([*options.runner, options.loader, "--run", os.path.basename(options.guest), "--trace-d3d12"],
110 cwd=os.path.dirname(os.path.abspath(options.guest)), env=environment, capture_output=True,
111 text=True, encoding="utf-8", errors="replace", timeout=timeout)
112 output = run.stdout + run.stderr
113 problems = check_output(run.returncode, output)
114 if problems:
115 print(output)
116 for problem in problems:
117 print(f"FAIL: {problem}")
118 return 1
119 print("tiny_frame under gta6rt --run on the Vulkan D3D12 device: OK")
120 return 0
121
122
123if __name__ == "__main__":
124 sys.exit(main())
diff --git a/runtime/test/command_list_test.cpp b/runtime/test/command_list_test.cpp
index e459b4cc8..4d877d429 100644
--- a/runtime/test/command_list_test.cpp
+++ b/runtime/test/command_list_test.cpp
@@ -306,6 +306,6 @@ int main() {
306 CHECK(query_fits_heap(h::copy_queue_timestamp, q::timestamp) && !query_fits_heap(h::timestamp, q::occlusion)); 306 CHECK(query_fits_heap(h::copy_queue_timestamp, q::timestamp) && !query_fits_heap(h::timestamp, q::occlusion));
307 CHECK(query_fits_heap(h::so_statistics, q::so_statistics_stream3) && !query_fits_heap(6, q::occlusion)); 307 CHECK(query_fits_heap(h::so_statistics, q::so_statistics_stream3) && !query_fits_heap(6, q::occlusion));
308 CHECK(query_result_size(q::occlusion) == 8 && query_result_size(q::timestamp) == 8); 308 CHECK(query_result_size(q::occlusion) == 8 && query_result_size(q::timestamp) == 8);
309 CHECK(query_result_size(q::pipeline_statistics) == 88 && query_result_size(q::so_statistics_stream0) == 0); 309 CHECK(query_result_size(q::pipeline_statistics) == 88 && query_result_size(q::so_statistics_stream0) == 16);
310 return 0; 310 return 0;
311} 311}
diff --git a/runtime/test/cpp_unwind_test.cpp b/runtime/test/cpp_unwind_test.cpp
new file mode 100644
index 000000000..30cfc6ca1
--- /dev/null
+++ b/runtime/test/cpp_unwind_test.cpp
@@ -0,0 +1,31 @@
1#include <cstdio>
2
3namespace {
4
5struct UnwindMarker {
6 bool& destroyed;
7 ~UnwindMarker() { destroyed = true; }
8};
9
10struct TestException {};
11
12// Keep the object in a separate frame, outside the catch handler's function.
13__declspec(noinline) void throw_with_marker(bool& destroyed) {
14 UnwindMarker marker{destroyed};
15 throw TestException{};
16}
17
18} // namespace
19
20int main() {
21 bool destroyed = false;
22 try {
23 throw_with_marker(destroyed);
24 } catch (const TestException&) {
25 if (destroyed) return 0;
26 std::fputs("C++ exception unwound without running a destructor\n", stderr);
27 return 1;
28 }
29 std::fputs("Expected a C++ exception\n", stderr);
30 return 1;
31}
diff --git a/runtime/test/cs_wave_probe_spv.h b/runtime/test/cs_wave_probe_spv.h
new file mode 100644
index 000000000..28745ac06
--- /dev/null
+++ b/runtime/test/cs_wave_probe_spv.h
@@ -0,0 +1,63 @@
1// runtime/test/glsl/cs_wave_probe.comp, generated with glslang 16.6.0 (tests/test_cs_wave_probe_spv.py checks it):
2// glslangValidator -V --target-env vulkan1.2 -Os -o cs_wave_probe.spv runtime/test/glsl/cs_wave_probe.comp
3// SPIR-V 1.5, as the translator emits, so varying subgroup sizes are not allowed in it either.
4#pragma once
5#include <cstdint>
6namespace leonida::vk_test {
7inline constexpr std::uint32_t cs_wave_probe_spirv[] = {
8 0x07230203u, 0x00010500u, 0x0008000bu, 0x00000042u, 0x00000000u, 0x00020011u, 0x00000001u, 0x00020011u,
9 0x0000003du, 0x00020011u, 0x00000040u, 0x00020011u, 0x000014e3u, 0x0006000bu, 0x00000001u, 0x4c534c47u,
10 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu, 0x000014e4u, 0x00000001u, 0x000a000fu, 0x00000005u,
11 0x00000004u, 0x6e69616du, 0x00000000u, 0x0000000fu, 0x00000019u, 0x00000021u, 0x00000029u, 0x00000030u,
12 0x00060010u, 0x00000004u, 0x00000011u, 0x00000001u, 0x00000001u, 0x00000001u, 0x00030003u, 0x00000002u,
13 0x000001c2u, 0x00070004u, 0x455f4c47u, 0x625f5458u, 0x65666675u, 0x65725f72u, 0x65726566u, 0x0065636eu,
14 0x00090004u, 0x455f4c47u, 0x625f5458u, 0x65666675u, 0x65725f72u, 0x65726566u, 0x5f65636eu, 0x63657675u,
15 0x00000032u, 0x00090004u, 0x4b5f4c47u, 0x735f5248u, 0x65646168u, 0x75735f72u, 0x6f726762u, 0x625f7075u,
16 0x6f6c6c61u, 0x00000074u, 0x00090004u, 0x4b5f4c47u, 0x735f5248u, 0x65646168u, 0x75735f72u, 0x6f726762u,
17 0x625f7075u, 0x63697361u, 0x00000000u, 0x00040005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00040005u,
18 0x00000009u, 0x64726f57u, 0x00000073u, 0x00040006u, 0x00000009u, 0x00000000u, 0x00000077u, 0x00050005u,
19 0x0000000du, 0x72657355u, 0x61746144u, 0x00000000u, 0x00050006u, 0x0000000du, 0x00000000u, 0x65736162u,
20 0x00000000u, 0x00030005u, 0x0000000fu, 0x00006370u, 0x00080005u, 0x00000019u, 0x4c5f6c67u, 0x6c61636fu,
21 0x6f766e49u, 0x69746163u, 0x6e496e6fu, 0x00786564u, 0x00060005u, 0x00000021u, 0x535f6c67u, 0x72676275u,
22 0x5370756fu, 0x00657a69u, 0x00080005u, 0x00000029u, 0x535f6c67u, 0x72676275u, 0x4970756fu, 0x636f766eu,
23 0x6f697461u, 0x0044496eu, 0x00060005u, 0x00000030u, 0x535f6c67u, 0x72676275u, 0x4970756fu, 0x00000044u,
24 0x00040047u, 0x00000008u, 0x00000006u, 0x00000004u, 0x00030047u, 0x00000009u, 0x00000002u, 0x00050048u,
25 0x00000009u, 0x00000000u, 0x00000023u, 0x00000000u, 0x00030047u, 0x0000000du, 0x00000002u, 0x00050048u,
26 0x0000000du, 0x00000000u, 0x00000023u, 0x00000000u, 0x00040047u, 0x00000019u, 0x0000000bu, 0x0000001du,
27 0x00030047u, 0x00000021u, 0x00000000u, 0x00040047u, 0x00000021u, 0x0000000bu, 0x00000024u, 0x00030047u,
28 0x00000022u, 0x00000000u, 0x00030047u, 0x00000029u, 0x00000000u, 0x00040047u, 0x00000029u, 0x0000000bu,
29 0x00000029u, 0x00030047u, 0x0000002au, 0x00000000u, 0x00040047u, 0x00000030u, 0x0000000bu, 0x00000028u,
30 0x00040047u, 0x0000003du, 0x00000001u, 0x00000000u, 0x00040047u, 0x0000003eu, 0x00000001u, 0x00000001u,
31 0x00040047u, 0x0000003fu, 0x00000001u, 0x00000002u, 0x00040047u, 0x00000041u, 0x0000000bu, 0x00000019u,
32 0x00020013u, 0x00000002u, 0x00030021u, 0x00000003u, 0x00000002u, 0x00030027u, 0x00000006u, 0x000014e5u,
33 0x00040015u, 0x00000007u, 0x00000020u, 0x00000000u, 0x0003001du, 0x00000008u, 0x00000007u, 0x0003001eu,
34 0x00000009u, 0x00000008u, 0x00040020u, 0x00000006u, 0x000014e5u, 0x00000009u, 0x00040017u, 0x0000000cu,
35 0x00000007u, 0x00000002u, 0x0003001eu, 0x0000000du, 0x0000000cu, 0x00040020u, 0x0000000eu, 0x00000009u,
36 0x0000000du, 0x0004003bu, 0x0000000eu, 0x0000000fu, 0x00000009u, 0x00040015u, 0x00000010u, 0x00000020u,
37 0x00000001u, 0x0004002bu, 0x00000010u, 0x00000011u, 0x00000000u, 0x00040020u, 0x00000012u, 0x00000009u,
38 0x0000000cu, 0x00040020u, 0x00000018u, 0x00000001u, 0x00000007u, 0x0004003bu, 0x00000018u, 0x00000019u,
39 0x00000001u, 0x0004002bu, 0x00000007u, 0x0000001bu, 0x00000004u, 0x0004003bu, 0x00000018u, 0x00000021u,
40 0x00000001u, 0x00040020u, 0x00000023u, 0x000014e5u, 0x00000007u, 0x0004002bu, 0x00000007u, 0x00000027u,
41 0x00000001u, 0x0004003bu, 0x00000018u, 0x00000029u, 0x00000001u, 0x0004002bu, 0x00000007u, 0x0000002eu,
42 0x00000002u, 0x0004003bu, 0x00000018u, 0x00000030u, 0x00000001u, 0x0004002bu, 0x00000007u, 0x00000035u,
43 0x00000003u, 0x00020014u, 0x00000037u, 0x00030029u, 0x00000037u, 0x00000038u, 0x00040017u, 0x00000039u,
44 0x00000007u, 0x00000004u, 0x00040032u, 0x00000007u, 0x0000003du, 0x00000001u, 0x00040032u, 0x00000007u,
45 0x0000003eu, 0x00000001u, 0x00040032u, 0x00000007u, 0x0000003fu, 0x00000001u, 0x00040017u, 0x00000040u,
46 0x00000007u, 0x00000003u, 0x00060033u, 0x00000040u, 0x00000041u, 0x0000003du, 0x0000003eu, 0x0000003fu,
47 0x00050036u, 0x00000002u, 0x00000004u, 0x00000000u, 0x00000003u, 0x000200f8u, 0x00000005u, 0x00050041u,
48 0x00000012u, 0x00000013u, 0x0000000fu, 0x00000011u, 0x0004003du, 0x0000000cu, 0x00000014u, 0x00000013u,
49 0x0004007cu, 0x00000006u, 0x00000015u, 0x00000014u, 0x0004003du, 0x00000007u, 0x0000001au, 0x00000019u,
50 0x00050084u, 0x00000007u, 0x0000001cu, 0x0000001au, 0x0000001bu, 0x0004003du, 0x00000007u, 0x00000022u,
51 0x00000021u, 0x00060041u, 0x00000023u, 0x00000024u, 0x00000015u, 0x00000011u, 0x0000001cu, 0x0005003eu,
52 0x00000024u, 0x00000022u, 0x00000002u, 0x00000004u, 0x00050080u, 0x00000007u, 0x00000028u, 0x0000001cu,
53 0x00000027u, 0x0004003du, 0x00000007u, 0x0000002au, 0x00000029u, 0x00060041u, 0x00000023u, 0x0000002bu,
54 0x00000015u, 0x00000011u, 0x00000028u, 0x0005003eu, 0x0000002bu, 0x0000002au, 0x00000002u, 0x00000004u,
55 0x00050080u, 0x00000007u, 0x0000002fu, 0x0000001cu, 0x0000002eu, 0x0004003du, 0x00000007u, 0x00000031u,
56 0x00000030u, 0x00060041u, 0x00000023u, 0x00000032u, 0x00000015u, 0x00000011u, 0x0000002fu, 0x0005003eu,
57 0x00000032u, 0x00000031u, 0x00000002u, 0x00000004u, 0x00050080u, 0x00000007u, 0x00000036u, 0x0000001cu,
58 0x00000035u, 0x00050153u, 0x00000039u, 0x0000003au, 0x00000035u, 0x00000038u, 0x00060156u, 0x00000007u,
59 0x0000003bu, 0x00000035u, 0x00000000u, 0x0000003au, 0x00060041u, 0x00000023u, 0x0000003cu, 0x00000015u,
60 0x00000011u, 0x00000036u, 0x0005003eu, 0x0000003cu, 0x0000003bu, 0x00000002u, 0x00000004u, 0x000100fdu,
61 0x00010038u,
62};
63}
diff --git a/runtime/test/d3d12_buffer_tiles_test.cpp b/runtime/test/d3d12_buffer_tiles_test.cpp
index 0e2b4bad7..8e6079bdd 100644
--- a/runtime/test/d3d12_buffer_tiles_test.cpp
+++ b/runtime/test/d3d12_buffer_tiles_test.cpp
@@ -6,8 +6,10 @@
6 6
7#include <algorithm> 7#include <algorithm>
8#include <array> 8#include <array>
9#include <cctype>
9#include <cstdint> 10#include <cstdint>
10#include <cstdio> 11#include <cstdio>
12#include <string>
11 13
12#define EXPECT(condition) do { \ 14#define EXPECT(condition) do { \
13 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return false; } \ 15 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return false; } \
@@ -170,25 +172,55 @@ bool run(ID3D12Device& device, Results& result, bool layer = false) {
170 172
171 EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); 173 EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped)));
172 const auto* data = static_cast<const std::uint32_t*>(mapped); 174 const auto* data = static_cast<const std::uint32_t*>(mapped);
175 // Every word of every tile, with the first wrong word of each tile printed, so a failure says which side,
176 // snapshot and tile differ and what was read there.
177 UINT wrong_tiles = 0;
173 for (UINT i = 0; i < snapshots; ++i) { 178 for (UINT i = 0; i < snapshots; ++i) {
174 for (UINT tile = 0; tile < tiles_per_buffer; ++tile) { 179 for (UINT tile = 0; tile < tiles_per_buffer; ++tile) {
175 const auto* first = data + (i * tiles_per_buffer + tile) * words_per_tile; 180 const auto* first = data + (i * tiles_per_buffer + tile) * words_per_tile;
176 result[i][tile] = *first; 181 result[i][tile] = *first;
177 EXPECT(std::all_of(first, first + words_per_tile, [&](auto word) { return word == expected[i][tile]; })); 182 const auto* bad = std::find_if(first, first + words_per_tile, [&](auto word) { return word != expected[i][tile]; });
183 if (bad == first + words_per_tile) continue;
184 ++wrong_tiles;
185 const auto wrong_words = std::count_if(bad, first + words_per_tile,
186 [&](auto word) { return word != expected[i][tile]; });
187 std::fprintf(stderr, "%s snapshot %u tile %u: word %u reads %#010x, want %#010x (%lld of %llu words wrong)\n",
188 layer ? "Vulkan layer" : "native D3D12", i, tile, unsigned(bad - first), unsigned(*bad),
189 unsigned(expected[i][tile]), static_cast<long long>(wrong_words),
190 static_cast<unsigned long long>(words_per_tile));
178 } 191 }
179 } 192 }
180 readback->Unmap(0, &empty); 193 readback->Unmap(0, &empty);
194 EXPECT(wrong_tiles == 0);
181 return true; 195 return true;
182} 196}
183 197
198// The host adapter for the native half. LEONIDA_HOST_ADAPTER picks it as in d3d12_copy_compare.h: "warp", or part of
199// an adapter name (case-insensitive); a value that names no adapter with tiled resources tier 2 skips the native half
200// rather than testing another GPU. Unset: the first hardware adapter with tier 2 or more.
184ComPtr<ID3D12Device> native_device() { 201ComPtr<ID3D12Device> native_device() {
185 ComPtr<IDXGIFactory4> factory; 202 ComPtr<IDXGIFactory4> factory;
186 if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return {}; 203 if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return {};
204 char want[128] = {};
205 GetEnvironmentVariableA("LEONIDA_HOST_ADAPTER", want, sizeof(want));
206 std::string needle(want);
207 std::transform(needle.begin(), needle.end(), needle.begin(), [](unsigned char c) { return char(std::tolower(c)); });
187 for (UINT i = 0;; ++i) { 208 for (UINT i = 0;; ++i) {
188 ComPtr<IDXGIAdapter1> adapter; 209 ComPtr<IDXGIAdapter1> adapter;
189 if (factory->EnumAdapters1(i, &adapter) != S_OK) return {}; 210 if (needle == "warp") {
211 if (i > 0 || FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)))) break;
212 } else if (factory->EnumAdapters1(i, &adapter) != S_OK) {
213 break;
214 }
190 DXGI_ADAPTER_DESC1 desc{}; 215 DXGI_ADAPTER_DESC1 desc{};
191 if (FAILED(adapter->GetDesc1(&desc)) || (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)) continue; 216 if (FAILED(adapter->GetDesc1(&desc))) continue;
217 if (needle.empty()) {
218 if (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) continue;
219 } else if (needle != "warp") {
220 std::string name;
221 for (const wchar_t* c = desc.Description; *c; ++c) name += char(std::tolower(*c < 128 ? *c : '?'));
222 if (name.find(needle) == std::string::npos) continue;
223 }
192 ComPtr<ID3D12Device> device; 224 ComPtr<ID3D12Device> device;
193 if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&device)))) continue; 225 if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&device)))) continue;
194 D3D12_FEATURE_DATA_D3D12_OPTIONS options{}; 226 D3D12_FEATURE_DATA_D3D12_OPTIONS options{};
@@ -197,6 +229,10 @@ ComPtr<ID3D12Device> native_device() {
197 std::printf("Native D3D12: %ls, tiled resources tier %u\n", desc.Description, unsigned(options.TiledResourcesTier)); 229 std::printf("Native D3D12: %ls, tiled resources tier %u\n", desc.Description, unsigned(options.TiledResourcesTier));
198 return device; 230 return device;
199 } 231 }
232 if (!needle.empty())
233 std::printf("Native D3D12: no adapter matching LEONIDA_HOST_ADAPTER=%s with tiled resources tier 2 or more; "
234 "native half skipped\n", want);
235 return {};
200} 236}
201 237
202} // namespace 238} // namespace
diff --git a/runtime/test/d3d12_bundle_test.cpp b/runtime/test/d3d12_bundle_test.cpp
index fd14dc29b..9839f17f7 100644
--- a/runtime/test/d3d12_bundle_test.cpp
+++ b/runtime/test/d3d12_bundle_test.cpp
@@ -12,6 +12,7 @@
12// (one line per call the application made, however often the bundle runs) and for object lifetimes. 12// (one line per call the application made, however often the bundle runs) and for object lifetimes.
13// Both host adapters always run (LEONIDA_HOST_ADAPTER is not read), except under Wine, where the host is skipped. 13// Both host adapters always run (LEONIDA_HOST_ADAPTER is not read), except under Wine, where the host is skipped.
14// No game data. 14// No game data.
15#include "test_temp_dir.h"
15#include "vk_test_device.h" 16#include "vk_test_device.h"
16#include "d3d12_test_shaders.h" 17#include "d3d12_test_shaders.h"
17#include "host_wine.h" 18#include "host_wine.h"
@@ -730,18 +731,10 @@ int main() {
730 const auto vs_program = fssm_program({0x56530101, 0xbf810000}); 731 const auto vs_program = fssm_program({0x56530101, 0xbf810000});
731 const auto ps_program = fssm_program({0x50530101, 0xbf810000}); 732 const auto ps_program = fssm_program({0x50530101, 0xbf810000});
732 const auto vs_container = shader_container(vs_program), ps_container = shader_container(ps_program); 733 const auto vs_container = shader_container(vs_program), ps_container = shader_container(ps_program);
733 // Removed on every way out of main. 734 const testfiles::ScratchDir scratch("leonida_bundle_test"); // removed on every way out of main
734 struct Scratch { 735 const auto& library = scratch.path();
735 std::filesystem::path path = std::filesystem::temp_directory_path() / "leonida_bundle_test"; 736 REQUIRE(testfiles::copy_file(LEONIDA_TEST_VS_SPV, library / "vs_draw.spv"));
736 Scratch() { std::filesystem::create_directories(path); } 737 REQUIRE(testfiles::copy_file(LEONIDA_TEST_PS_SPV, library / "ps_draw.spv"));
737 ~Scratch() {
738 std::error_code ignored;
739 std::filesystem::remove_all(path, ignored);
740 }
741 } scratch;
742 const auto& library = scratch.path;
743 std::filesystem::copy_file(LEONIDA_TEST_VS_SPV, library / "vs_draw.spv", std::filesystem::copy_options::overwrite_existing);
744 std::filesystem::copy_file(LEONIDA_TEST_PS_SPV, library / "ps_draw.spv", std::filesystem::copy_options::overwrite_existing);
745 { 738 {
746 std::ofstream index(library / "index.json", std::ios::binary); 739 std::ofstream index(library / "index.json", std::ios::binary);
747 index << "{\"vs_draw\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_program) 740 index << "{\"vs_draw\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_program)
diff --git a/runtime/test/d3d12_com_test.cpp b/runtime/test/d3d12_com_test.cpp
index eb921ddce..e9eeed3a6 100644
--- a/runtime/test/d3d12_com_test.cpp
+++ b/runtime/test/d3d12_com_test.cpp
@@ -31,8 +31,10 @@ struct Ref {
31 31
32static_assert(std::is_move_constructible_v<leonida::Draw>); 32static_assert(std::is_move_constructible_v<leonida::Draw>);
33static_assert(std::is_move_assignable_v<leonida::Draw>); 33static_assert(std::is_move_assignable_v<leonida::Draw>);
34static_assert(sizeof(leonida::Draw::render_targets) == sizeof(leonida::TargetView) * 8); 34static_assert(sizeof(leonida::DrawViews::render_targets) == sizeof(leonida::TargetView) * 8);
35static_assert(sizeof(leonida::Draw::vertex_buffers) == sizeof(leonida::VertexBufferView) * 32); 35static_assert(sizeof(leonida::DrawViews::vertex_buffers) == sizeof(leonida::VertexBufferView) * 32);
36// The views stay out of the variant: a recorded command is sized by its largest member, Draw included.
37static_assert(sizeof(leonida::Draw) < sizeof(leonida::DrawViews));
36 38
37int main(int argc, char** argv) { 39int main(int argc, char** argv) {
38 if (argc == 2 && std::strcmp(argv[1], "--trace-d3d12") == 0) rt::d3d12_trace::set_enabled(true); 40 if (argc == 2 && std::strcmp(argv[1], "--trace-d3d12") == 0) rt::d3d12_trace::set_enabled(true);
diff --git a/runtime/test/d3d12_compute_test.cpp b/runtime/test/d3d12_compute_test.cpp
index 2b0b14cda..c8b29d29c 100644
--- a/runtime/test/d3d12_compute_test.cpp
+++ b/runtime/test/d3d12_compute_test.cpp
@@ -9,7 +9,9 @@
9// The shader (test/glsl/cs_user_data.comp) is written to the translator's push-constant and address contract. 9// The shader (test/glsl/cs_user_data.comp) is written to the translator's push-constant and address contract.
10// No game data. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. 10// No game data. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation.
11#include "shader_fixture_path.h" 11#include "shader_fixture_path.h"
12#include "test_temp_dir.h"
12#include "vk_test_device.h" 13#include "vk_test_device.h"
14#include "host_wine.h"
13#include "../shims/d3d12_com.h" 15#include "../shims/d3d12_com.h"
14#include "../src/gfx10_descriptors.h" 16#include "../src/gfx10_descriptors.h"
15#include "../src/cached_pso.h" 17#include "../src/cached_pso.h"
@@ -203,9 +205,11 @@ std::vector<HRESULT> cached_pso_cases(Device* device, D3D12_COMPUTE_PIPELINE_STA
203} 205}
204 206
205// The same cases on the PC runtime, with an empty compute shader from d3dcompiler_47: the default adapter, then WARP. 207// The same cases on the PC runtime, with an empty compute shader from d3dcompiler_47: the default adapter, then WARP.
206// Empty when the host has no D3D12 device or no compiler (Wine), which the caller reports as a skip. 208// Empty when the host has no D3D12 device or no compiler, or is Wine's, which the caller reports as a skip: vkd3d has
209// both, but its GetCachedBlob is a stub, so every host answered nothing and the comparison failed on each run.
207std::vector<std::vector<HRESULT>> host_cached_pso_cases(const std::vector<std::uint8_t>& root_blob, 210std::vector<std::vector<HRESULT>> host_cached_pso_cases(const std::vector<std::uint8_t>& root_blob,
208 const std::vector<std::uint8_t>& other_root_blob) { 211 const std::vector<std::uint8_t>& other_root_blob) {
212 if (hostwine::host_is_wine()) return {};
209 using CompileFn = HRESULT(WINAPI*)(LPCVOID, SIZE_T, LPCSTR, const void*, void*, LPCSTR, LPCSTR, UINT, UINT, 213 using CompileFn = HRESULT(WINAPI*)(LPCVOID, SIZE_T, LPCSTR, const void*, void*, LPCSTR, LPCSTR, UINT, UINT,
210 ID3DBlob**, ID3DBlob**); 214 ID3DBlob**, ID3DBlob**);
211 using CreateDeviceFn = decltype(&::D3D12CreateDevice); 215 using CreateDeviceFn = decltype(&::D3D12CreateDevice);
@@ -268,10 +272,9 @@ int main() {
268 for (std::uint32_t i = 0; i < 14; ++i) put32(fssm, 0xbf810000u + i); // filler, s_endpgm-like words 272 for (std::uint32_t i = 0; i < 14; ++i) put32(fssm, 0xbf810000u + i); // filler, s_endpgm-like words
269 const auto container = shader_container(fssm); 273 const auto container = shader_container(fssm);
270 EXPECT(leonida::fssm_program(container) == fssm); 274 EXPECT(leonida::fssm_program(container) == fssm);
271 const auto library = std::filesystem::temp_directory_path() / "leonida_compute_test"; 275 const testfiles::ScratchDir scratch("leonida_compute_test");
272 std::filesystem::create_directories(library); 276 const auto& library = scratch.path();
273 std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), library / "cs_user_data.spv", 277 EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), library / "cs_user_data.spv"));
274 std::filesystem::copy_options::overwrite_existing);
275 { 278 {
276 std::ofstream index(library / "index.json", std::ios::binary); 279 std::ofstream index(library / "index.json", std::ios::binary);
277 // An entry for the same program with set-0 bindings comes first, as in one group of the corpus: the PSO 280 // An entry for the same program with set-0 bindings comes first, as in one group of the corpus: the PSO
@@ -387,7 +390,9 @@ int main() {
387 E_INVALIDARG, E_INVALIDARG, S_OK}; 390 E_INVALIDARG, E_INVALIDARG, S_OK};
388 EXPECT(layer == expected); 391 EXPECT(layer == expected);
389 const auto hosts = host_cached_pso_cases(root_blob, other_root_blob); 392 const auto hosts = host_cached_pso_cases(root_blob, other_root_blob);
390 if (hosts.empty()) std::printf("SKIP: no host D3D12 device or compiler for the CachedPSO comparison\n"); 393 if (hosts.empty())
394 std::printf("SKIP: no host D3D12 reference (Wine, or no device or compiler) for the CachedPSO "
395 "comparison\n");
391 for (const auto& host : hosts) EXPECT(host == layer); 396 for (const auto& host : hosts) EXPECT(host == layer);
392 if (!hosts.empty()) std::printf("cached PSO: %zu host adapter(s) gave the same %d answers\n", hosts.size(), cached_case_count); 397 if (!hosts.empty()) std::printf("cached PSO: %zu host adapter(s) gave the same %d answers\n", hosts.size(), cached_case_count);
393 398
@@ -889,7 +894,6 @@ int main() {
889 fence.reset(); 894 fence.reset();
890 EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); 895 EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1);
891 } 896 }
892 std::filesystem::remove_all(library);
893 897
894 unsigned mismatches = 0; 898 unsigned mismatches = 0;
895 for (std::uint32_t i = 0; i < elements; ++i) { 899 for (std::uint32_t i = 0; i < elements; ++i) {
diff --git a/runtime/test/d3d12_copy_xfmt_test.cpp b/runtime/test/d3d12_copy_xfmt_test.cpp
index 0a504b266..e4b22868c 100644
--- a/runtime/test/d3d12_copy_xfmt_test.cpp
+++ b/runtime/test/d3d12_copy_xfmt_test.cpp
@@ -49,11 +49,13 @@ D3D12_RESOURCE_DESC buf(UINT64 bytes) {
49struct Case { 49struct Case {
50 const char* name; 50 const char* name;
51 D3D12_RESOURCE_DESC src, dst; 51 D3D12_RESOURCE_DESC src, dst;
52 bool whole; // CopyResource, else CopyTextureRegion of subresource 0 with no box 52 bool whole; // CopyResource, else CopyTextureRegion
53 bool depth_values; // also marks the depth <-> colour cases, counted apart from the BC ones (both fail the test) 53 bool depth_values; // also marks the depth <-> colour cases, counted apart from the BC ones (both fail the test)
54 UINT x = 0, y = 0; // CopyTextureRegion destination offset 54 UINT x = 0, y = 0; // CopyTextureRegion destination offset
55 bool has_box = false; 55 bool has_box = false;
56 D3D12_BOX box{}; 56 D3D12_BOX box{};
57 UINT dst_mip = 0;
58 bool check_edge_bytes = false;
57}; 59};
58 60
59D3D12_RESOURCE_BARRIER transition(ID3D12Resource* r, D3D12_RESOURCE_STATES a, D3D12_RESOURCE_STATES b) { 61D3D12_RESOURCE_BARRIER transition(ID3D12Resource* r, D3D12_RESOURCE_STATES a, D3D12_RESOURCE_STATES b) {
@@ -66,7 +68,11 @@ D3D12_RESOURCE_BARRIER transition(ID3D12Resource* r, D3D12_RESOURCE_STATES a, D3
66 return x; 68 return x;
67} 69}
68 70
69// Returns false when the device refuses something; out: the destination's footprint rows, every mip. 71unsigned char upload_byte(UINT64 index) {
72 return static_cast<unsigned char>(index * 7 + 3);
73}
74
75// Pack the destination footprint rows for the copied mip, or every mip for CopyResource.
70bool run(ID3D12Device* dev, const Case& c, std::vector<unsigned char>& out, HRESULT& close_hr) { 76bool run(ID3D12Device* dev, const Case& c, std::vector<unsigned char>& out, HRESULT& close_hr) {
71 D3D12_COMMAND_QUEUE_DESC qd{}; 77 D3D12_COMMAND_QUEUE_DESC qd{};
72 Ref<ID3D12CommandQueue> q; 78 Ref<ID3D12CommandQueue> q;
@@ -78,7 +84,7 @@ bool run(ID3D12Device* dev, const Case& c, std::vector<unsigned char>& out, HRES
78 FAILED(dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, a.p, nullptr, IID_PPV_ARGS(&l.p))) || 84 FAILED(dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, a.p, nullptr, IID_PPV_ARGS(&l.p))) ||
79 FAILED(dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))) 85 FAILED(dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p))))
80 return false; 86 return false;
81 // Every mip goes up and comes back (one array layer). 87 // One array layer. Upload every source mip so both copy calls have initialized input.
82 const UINT ns = c.src.MipLevels, nd = c.dst.MipLevels; 88 const UINT ns = c.src.MipLevels, nd = c.dst.MipLevels;
83 D3D12_PLACED_SUBRESOURCE_FOOTPRINT sf[16]{}, df[16]{}; 89 D3D12_PLACED_SUBRESOURCE_FOOTPRINT sf[16]{}, df[16]{};
84 UINT rows[16]{}; 90 UINT rows[16]{};
@@ -100,12 +106,21 @@ bool run(ID3D12Device* dev, const Case& c, std::vector<unsigned char>& out, HRES
100 return false; 106 return false;
101 unsigned char* p = nullptr; 107 unsigned char* p = nullptr;
102 if (FAILED(upload->Map(0, nullptr, reinterpret_cast<void**>(&p)))) return false; 108 if (FAILED(upload->Map(0, nullptr, reinterpret_cast<void**>(&p)))) return false;
103 for (UINT64 i = 0; i < sbytes; ++i) p[i] = static_cast<unsigned char>(i * 7 + 3); 109 for (UINT64 i = 0; i < sbytes; ++i) p[i] = upload_byte(i);
104 if (c.depth_values) // normal floats in [0, 1): a host driver may flush denormals 110 if (c.depth_values) // normal floats in [0, 1): a host driver may flush denormals
105 for (UINT64 i = 0; i + 4 <= sbytes; i += 4) { 111 for (UINT64 i = 0; i + 4 <= sbytes; i += 4) {
106 const float v = float((i / 4) % 1000) / 1000.0f; 112 const float v = float((i / 4) % 1000) / 1000.0f;
107 std::memcpy(p + i, &v, 4); 113 std::memcpy(p + i, &v, 4);
108 } 114 }
115 if (c.check_edge_bytes) {
116 // The edge fixtures copy whole R32G32_UINT source rows, one eight-byte texel per BC1 block.
117 // Count the data bytes, excluding padding, so each row contains a different pattern.
118 const UINT64 bytes_per_row = c.src.Width * 8;
119 for (UINT y = 0; y < c.src.Height; ++y) {
120 auto* row = p + sf[0].Offset + UINT64(y) * sf[0].Footprint.RowPitch;
121 for (UINT64 x = 0; x < bytes_per_row; ++x) row[x] = upload_byte(y * bytes_per_row + x);
122 }
123 }
109 upload->Unmap(0, nullptr); 124 upload->Unmap(0, nullptr);
110 if (FAILED(readback->Map(0, nullptr, reinterpret_cast<void**>(&p)))) return false; 125 if (FAILED(readback->Map(0, nullptr, reinterpret_cast<void**>(&p)))) return false;
111 std::memset(p, 0xcd, size_t(dbytes)); 126 std::memset(p, 0xcd, size_t(dbytes));
@@ -123,11 +138,13 @@ bool run(ID3D12Device* dev, const Case& c, std::vector<unsigned char>& out, HRES
123 l->CopyResource(dst.p, src.p); 138 l->CopyResource(dst.p, src.p);
124 } else { 139 } else {
125 D3D12_TEXTURE_COPY_LOCATION s{src.p}, d{dst.p}; 140 D3D12_TEXTURE_COPY_LOCATION s{src.p}, d{dst.p};
141 d.SubresourceIndex = c.dst_mip;
126 l->CopyTextureRegion(&d, c.x, c.y, 0, &s, c.has_box ? &c.box : nullptr); 142 l->CopyTextureRegion(&d, c.x, c.y, 0, &s, c.has_box ? &c.box : nullptr);
127 } 143 }
128 b = transition(dst.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE); 144 b = transition(dst.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE);
129 l->ResourceBarrier(1, &b); 145 l->ResourceBarrier(1, &b);
130 for (UINT i = 0; i < nd; ++i) { 146 const UINT first_mip = c.whole ? 0 : c.dst_mip, end_mip = c.whole ? nd : c.dst_mip + 1;
147 for (UINT i = first_mip; i < end_mip; ++i) {
131 D3D12_TEXTURE_COPY_LOCATION rs{dst.p}, rd{readback.p, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; 148 D3D12_TEXTURE_COPY_LOCATION rs{dst.p}, rd{readback.p, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT};
132 rs.SubresourceIndex = i; 149 rs.SubresourceIndex = i;
133 rd.PlacedFootprint = df[i]; 150 rd.PlacedFootprint = df[i];
@@ -143,9 +160,9 @@ bool run(ID3D12Device* dev, const Case& c, std::vector<unsigned char>& out, HRES
143 WaitForSingleObject(e, 10000); 160 WaitForSingleObject(e, 10000);
144 CloseHandle(e); 161 CloseHandle(e);
145 if (FAILED(readback->Map(0, nullptr, reinterpret_cast<void**>(&p)))) return false; 162 if (FAILED(readback->Map(0, nullptr, reinterpret_cast<void**>(&p)))) return false;
146 // Only the bytes inside each row, every mip. 163 // Compare the bytes inside the rows and leave footprint padding out.
147 out.clear(); 164 out.clear();
148 for (UINT i = 0; i < nd; ++i) 165 for (UINT i = first_mip; i < end_mip; ++i)
149 for (UINT r = 0; r < rows[i]; ++r) { 166 for (UINT r = 0; r < rows[i]; ++r) {
150 const unsigned char* row = p + df[i].Offset + r * df[i].Footprint.RowPitch; 167 const unsigned char* row = p + df[i].Offset + r * df[i].Footprint.RowPitch;
151 out.insert(out.end(), row, row + row_bytes[i]); 168 out.insert(out.end(), row, row + row_bytes[i]);
@@ -207,6 +224,12 @@ int main() {
207 {"CopyTextureRegion BC7 16x16 -> R32G32B32A32_UINT 4x4", tex(DXGI_FORMAT_BC7_UNORM, 16, 16), tex(DXGI_FORMAT_R32G32B32A32_UINT, 4, 4), false, false}, 224 {"CopyTextureRegion BC7 16x16 -> R32G32B32A32_UINT 4x4", tex(DXGI_FORMAT_BC7_UNORM, 16, 16), tex(DXGI_FORMAT_R32G32B32A32_UINT, 4, 4), false, false},
208 {"CopyTextureRegion BC1 box 4..12 x 8..16 -> R16G16B16A16_UINT 8x8 at (3, 1)", tex(DXGI_FORMAT_BC1_UNORM, 16, 16), tex(DXGI_FORMAT_R16G16B16A16_UINT, 8, 8), false, false, 3, 1, true, {4, 8, 0, 12, 16, 1}}, 225 {"CopyTextureRegion BC1 box 4..12 x 8..16 -> R16G16B16A16_UINT 8x8 at (3, 1)", tex(DXGI_FORMAT_BC1_UNORM, 16, 16), tex(DXGI_FORMAT_R16G16B16A16_UINT, 8, 8), false, false, 3, 1, true, {4, 8, 0, 12, 16, 1}},
209 {"CopyTextureRegion BC1 10x6 (padded box) -> R32G32_UINT 3x2", tex(DXGI_FORMAT_BC1_UNORM, 10, 6), tex(DXGI_FORMAT_R32G32_UINT, 3, 2), false, false}, 226 {"CopyTextureRegion BC1 10x6 (padded box) -> R32G32_UINT 3x2", tex(DXGI_FORMAT_BC1_UNORM, 10, 6), tex(DXGI_FORMAT_R32G32_UINT, 3, 2), false, false},
227 {.name = "CopyTextureRegion R32G32_UINT 3x2 -> BC1 10x6",
228 .src = tex(DXGI_FORMAT_R32G32_UINT, 3, 2), .dst = tex(DXGI_FORMAT_BC1_UNORM, 10, 6),
229 .whole = false, .depth_values = false, .check_edge_bytes = true},
230 {.name = "CopyTextureRegion R32G32_UINT 2x1 -> BC1 12x8 mip 1 (6x4)",
231 .src = tex(DXGI_FORMAT_R32G32_UINT, 2, 1), .dst = mips(tex(DXGI_FORMAT_BC1_UNORM, 12, 8), 2),
232 .whole = false, .depth_values = false, .dst_mip = 1, .check_edge_bytes = true},
210 {"CopyTextureRegion R32G32_UINT 2x2 -> BC1 16x16 at (8, 4)", tex(DXGI_FORMAT_R32G32_UINT, 2, 2), tex(DXGI_FORMAT_BC1_UNORM, 16, 16), false, false, 8, 4}, 233 {"CopyTextureRegion R32G32_UINT 2x2 -> BC1 16x16 at (8, 4)", tex(DXGI_FORMAT_R32G32_UINT, 2, 2), tex(DXGI_FORMAT_BC1_UNORM, 16, 16), false, false, 8, 4},
211 {"negative control: CopyTextureRegion R32_UINT 4x4 -> BC1 16x16", tex(DXGI_FORMAT_R32_UINT, 4, 4), tex(DXGI_FORMAT_BC1_UNORM, 16, 16), false, false}, 234 {"negative control: CopyTextureRegion R32_UINT 4x4 -> BC1 16x16", tex(DXGI_FORMAT_R32_UINT, 4, 4), tex(DXGI_FORMAT_BC1_UNORM, 16, 16), false, false},
212 {"negative control: CopyTextureRegion R32G32_UINT 4x4 -> BC1 16x16 at (12, 0)", tex(DXGI_FORMAT_R32G32_UINT, 4, 4), tex(DXGI_FORMAT_BC1_UNORM, 16, 16), false, false, 12, 0}, 235 {"negative control: CopyTextureRegion R32G32_UINT 4x4 -> BC1 16x16 at (12, 0)", tex(DXGI_FORMAT_R32G32_UINT, 4, 4), tex(DXGI_FORMAT_BC1_UNORM, 16, 16), false, false, 12, 0},
@@ -225,6 +248,23 @@ int main() {
225 unsigned differ = 0, differ_depth = 0, compared = 0; 248 unsigned differ = 0, differ_depth = 0, compared = 0;
226 for (const bool warp : {false, true}) { 249 for (const bool warp : {false, true}) {
227 for (const Case& c : cases) { 250 for (const Case& c : cases) {
251 // Check the full output of the partial-edge fixtures against the upload bytes on every available
252 // Vulkan device. Compare the same cases against native D3D12 using WARP when available.
253 if (!warp && (c.check_edge_bytes || std::strncmp(c.name, "negative", 8) == 0)) continue;
254 std::vector<unsigned char> h, o;
255 HRESULT hh = S_OK, oh = S_OK;
256 if (c.check_edge_bytes) {
257 std::vector<unsigned char> expected(size_t(c.src.Width) * c.src.Height * 8);
258 for (size_t i = 0; i < expected.size(); ++i) expected[i] = upload_byte(i);
259 const bool ours_ok = run(ours.p, c, o, oh);
260 if (!ours_ok || o != expected) {
261 std::fprintf(stderr, "%s: expected %zu upload bytes (read %zu bytes, Close 0x%08lx)\n",
262 c.name, expected.size(), o.size(), (unsigned long)oh);
263 ++differ;
264 continue;
265 }
266 std::printf("%s: matches %zu upload bytes\n", c.name, expected.size());
267 }
228 // A fresh device per case: an invalid copy removes the host device. 268 // A fresh device per case: an invalid copy removes the host device.
229 Ref<IDXGIAdapter> adapter; 269 Ref<IDXGIAdapter> adapter;
230 Ref<ID3D12Device> host; 270 Ref<ID3D12Device> host;
@@ -232,15 +272,12 @@ int main() {
232 if (!hostadapter::reference(factory.p, vk, warp, &adapter.p, adapter_name)) continue; 272 if (!hostadapter::reference(factory.p, vk, warp, &adapter.p, adapter_name)) continue;
233 const char* hn = adapter_name.c_str(); 273 const char* hn = adapter_name.c_str();
234 if (FAILED(D3D12CreateDevice(adapter.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) continue; 274 if (FAILED(D3D12CreateDevice(adapter.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) continue;
235 // Only WARP validates; a hardware driver may run an invalid copy.
236 if (!warp && std::strncmp(c.name, "negative", 8) == 0) continue;
237 std::vector<unsigned char> h, o;
238 HRESULT hh = S_OK, oh = S_OK;
239 const bool host_ok = run(host.p, c, h, hh); 275 const bool host_ok = run(host.p, c, h, hh);
240 drain(host.p); 276 drain(host.p);
241 if (!host_ok) { 277 if (!host_ok) {
242 std::printf("%s: %s refuses it (Close 0x%08lx, removed reason 0x%08lx), skipped\n", c.name, hn, 278 std::printf("%s: %s refuses it (Close 0x%08lx, removed reason 0x%08lx), skipped\n", c.name, hn,
243 (unsigned long)hh, (unsigned long)host->GetDeviceRemovedReason()); 279 (unsigned long)hh, (unsigned long)host->GetDeviceRemovedReason());
280 if (c.check_edge_bytes) continue; // the layer's output was already checked against the upload
244 // The layer must refuse it too (at Close or execution), never write out of bounds (validation). 281 // The layer must refuse it too (at Close or execution), never write out of bounds (validation).
245 const unsigned before = vk.validation_errors(); 282 const unsigned before = vk.validation_errors();
246 run(ours.p, c, o, oh); 283 run(ours.p, c, o, oh);
@@ -248,7 +285,7 @@ int main() {
248 vk.validation_errors() - before); 285 vk.validation_errors() - before);
249 continue; 286 continue;
250 } 287 }
251 const bool ours_ok = run(ours.p, c, o, oh); 288 const bool ours_ok = c.check_edge_bytes || run(ours.p, c, o, oh);
252 ++compared; 289 ++compared;
253 if (ours_ok && o == h) { 290 if (ours_ok && o == h) {
254 std::printf("%s: matches %s\n", c.name, hn); 291 std::printf("%s: matches %s\n", c.name, hn);
diff --git a/runtime/test/d3d12_depth24_draw_test.cpp b/runtime/test/d3d12_depth24_draw_test.cpp
new file mode 100644
index 000000000..436336e02
--- /dev/null
+++ b/runtime/test/d3d12_depth24_draw_test.cpp
@@ -0,0 +1,464 @@
1// D24_UNORM_S8_UINT in draws (D3D-309): depth bias in D24 units and depth quantised to 24 bits, as D3D12 gives on
2// any device. On a GPU without a D24 attachment (AMD) the layer stores D32_SFLOAT_S8_UINT and its pixel stage writes
3// the depth D24 would hold (src/depth24_fragment.h); with a native D24 the same expectations hold, so the test runs
4// on both and says which path it took.
5//
6// The cases of the finding (@marquezinii, measured by @Vonsek on #291, native D3D12 on an RTX 5080, a Radeon iGPU and
7// WARP): with the target cleared to 0.15625 + 2^-24 and a LESS test, a flat triangle at 0.15625 passes with bias 0
8// and fails everywhere with bias +1 and +2; an EQUAL test at exactly the cleared 0.15625 passes everywhere. Passing
9// pixels are counted through the stencil plane (INCR on pass), so pipelines without a pixel shader count too. Then
10// stored depth is read back through a footprint: a flat triangle with a constant bias, a sloped one with a
11// slope-scaled bias (with and without DepthBiasClamp, within one 24-bit step: the slope is the GPU's), and a pixel
12// shader that writes its own depth (stored quantised, not biased). Each runs with and without a pixel shader. The
13// finding's cases run once more through a pass-through geometry shader without a pixel shader, which also gets the
14// built-in depth stage.
15//
16// The shaders are GLSL written to the translator's contract (test/glsl/vs_depth.vert, ps_depth_empty.frag,
17// ps_depth_write.frag, gs_depth.geom). No game data.
18#include "vk_test_device.h"
19#include "d3d12_test_shaders.h"
20#include "../shims/d3d12_com.h"
21#include "../shims/d3d12_xs_device.h"
22#include "../src/depth24.h"
23#include "../src/shader_library.h"
24
25#include <algorithm>
26#include <cmath>
27#include <cstdio>
28#include <cstring>
29#include <fstream>
30#include <string>
31
32#if !defined(LEONIDA_TEST_VS_DEPTH_SPV) || !defined(LEONIDA_TEST_PS_DEPTH_EMPTY_SPV) || \
33 !defined(LEONIDA_TEST_PS_DEPTH_WRITE_SPV) || !defined(LEONIDA_TEST_GS_DEPTH_SPV)
34#error "the compiled test shaders must be named"
35#endif
36
37#define EXPECT(condition) do { \
38 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
39} while (0)
40
41using namespace d3d12test;
42using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slot 9: handle in RAX
43
44namespace {
45
46constexpr UINT target_side = 64;
47int g_failures = 0;
48
49void check(bool ok, const std::string& what) {
50 std::printf("%s %s\n", ok ? "PASS" : "FAIL", what.c_str());
51 if (!ok) ++g_failures;
52}
53
54std::uint32_t f2u(float f) {
55 std::uint32_t u;
56 std::memcpy(&u, &f, 4);
57 return u;
58}
59
60// D3D's bias for a UNORM24 target: (float)DepthBias * r + SlopeScaledDepthBias * MaxDepthSlope, clamped.
61float d3d_bias(int constant, float slope, float clamp, float max_slope) {
62 float bias = float(constant) * float(1.0 / 16777215.0) + slope * max_slope;
63 if (clamp > 0.0f) bias = std::fmin(bias, clamp);
64 if (clamp < 0.0f) bias = std::fmax(bias, clamp);
65 return bias;
66}
67
68struct Pass {
69 bool pixel_shader = false; // ps_depth_empty, else no pixel shader
70 bool shader_depth = false; // ps_depth_write instead
71 bool geometry_shader = false; // gs_depth between the VS and the (absent) pixel shader
72 int bias = 0;
73 float slope = 0.0f, clamp = 0.0f;
74 D3D12_COMPARISON_FUNC func = D3D12_COMPARISON_FUNC_ALWAYS;
75 bool write = true;
76 float clear = 1.0f;
77 float z = 0.5f, dz = 0.0f, shader_z = 0.0f; // s0, s1 (vs_depth.vert), s2 (ps_depth_write.frag)
78};
79
80struct Result {
81 std::vector<std::uint32_t> depth; // 24-bit codes, target_side * target_side
82 std::vector<std::uint8_t> stencil;
83};
84
85struct Harness {
86 ID3D12Device* device = nullptr;
87 ID3D12RootSignature* root = nullptr;
88 std::vector<std::uint8_t> vs, ps_empty, ps_write, gs;
89 Ref<ID3D12Resource> depth, readback;
90 Ref<ID3D12DescriptorHeap> dsv_heap;
91 D3D12_CPU_DESCRIPTOR_HANDLE dsv{};
92 D3D12_PLACED_SUBRESOURCE_FOOTPRINT foot[2]{};
93 Ref<ID3D12CommandQueue> queue;
94 Ref<ID3D12CommandAllocator> allocator;
95 Ref<ID3D12GraphicsCommandList> list;
96 Ref<ID3D12Fence> fence;
97 UINT64 fence_value = 0;
98
99 bool run(const Pass& p, Result& out, std::string& error) {
100 D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{};
101 desc.pRootSignature = root;
102 desc.VS = {vs.data(), vs.size()};
103 if (p.shader_depth)
104 desc.PS = {ps_write.data(), ps_write.size()};
105 else if (p.pixel_shader)
106 desc.PS = {ps_empty.data(), ps_empty.size()};
107 if (p.geometry_shader) desc.GS = {gs.data(), gs.size()};
108 desc.SampleMask = 0xffffffff;
109 desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID;
110 desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE;
111 desc.RasterizerState.DepthClipEnable = TRUE;
112 desc.RasterizerState.DepthBias = p.bias;
113 desc.RasterizerState.SlopeScaledDepthBias = p.slope;
114 desc.RasterizerState.DepthBiasClamp = p.clamp;
115 desc.DepthStencilState.DepthEnable = TRUE;
116 desc.DepthStencilState.DepthWriteMask = p.write ? D3D12_DEPTH_WRITE_MASK_ALL : D3D12_DEPTH_WRITE_MASK_ZERO;
117 desc.DepthStencilState.DepthFunc = p.func;
118 desc.DepthStencilState.StencilEnable = TRUE;
119 desc.DepthStencilState.StencilReadMask = 0xff;
120 desc.DepthStencilState.StencilWriteMask = 0xff;
121 const D3D12_DEPTH_STENCILOP_DESC count{D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP,
122 D3D12_STENCIL_OP_INCR_SAT, D3D12_COMPARISON_FUNC_ALWAYS};
123 desc.DepthStencilState.FrontFace = desc.DepthStencilState.BackFace = count;
124 desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
125 desc.DSVFormat = DXGI_FORMAT_D24_UNORM_S8_UINT;
126 desc.SampleDesc.Count = 1;
127 Ref<ID3D12PipelineState> pso;
128 if (FAILED(device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pso.p)))) {
129 error = "CreateGraphicsPipelineState failed";
130 return false;
131 }
132 if (FAILED(allocator->Reset()) || FAILED(list->Reset(allocator.p, pso.p))) {
133 error = "list reset failed";
134 return false;
135 }
136 D3D12_RESOURCE_BARRIER to_write = transition(depth.p, D3D12_RESOURCE_STATE_COPY_SOURCE,
137 D3D12_RESOURCE_STATE_DEPTH_WRITE);
138 list->ResourceBarrier(1, &to_write);
139 list->ClearDepthStencilView(dsv, D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, p.clear, 0, 0, nullptr);
140 list->SetGraphicsRootSignature(root);
141 const std::uint32_t constants[3] = {f2u(p.z), f2u(p.dz), f2u(p.shader_z)};
142 list->SetGraphicsRoot32BitConstants(0, 3, constants, 0);
143 list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
144 const D3D12_VIEWPORT viewport{0, 0, float(target_side), float(target_side), 0, 1};
145 const D3D12_RECT scissor{0, 0, LONG(target_side), LONG(target_side)};
146 list->RSSetViewports(1, &viewport);
147 list->RSSetScissorRects(1, &scissor);
148 list->OMSetRenderTargets(0, nullptr, FALSE, &dsv);
149 list->DrawInstanced(3, 1, 0, 0);
150 D3D12_RESOURCE_BARRIER to_copy = transition(depth.p, D3D12_RESOURCE_STATE_DEPTH_WRITE,
151 D3D12_RESOURCE_STATE_COPY_SOURCE);
152 list->ResourceBarrier(1, &to_copy);
153 for (UINT plane = 0; plane < 2; ++plane) {
154 D3D12_TEXTURE_COPY_LOCATION dst{};
155 dst.pResource = readback.p;
156 dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
157 dst.PlacedFootprint = foot[plane];
158 D3D12_TEXTURE_COPY_LOCATION src{};
159 src.pResource = depth.p;
160 src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
161 src.SubresourceIndex = plane;
162 list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
163 }
164 if (list->Close() != S_OK) {
165 error = "Close failed";
166 return false;
167 }
168 ID3D12CommandList* lists[] = {list.p};
169 queue->ExecuteCommandLists(1, lists);
170 if (rt::d3d12::last_execute_result(queue.p) != leonida::ReplayResult::success) {
171 error = "the layer refused the list";
172 return false;
173 }
174 if (FAILED(queue->Signal(fence.p, ++fence_value)) || FAILED(fence->SetEventOnCompletion(fence_value, nullptr))) {
175 error = "fence wait failed";
176 return false;
177 }
178 std::uint8_t* mapped = nullptr;
179 if (FAILED(readback->Map(0, nullptr, reinterpret_cast<void**>(&mapped)))) {
180 error = "Map failed";
181 return false;
182 }
183 out.depth.assign(target_side * target_side, 0);
184 out.stencil.assign(target_side * target_side, 0);
185 for (UINT y = 0; y < target_side; ++y)
186 for (UINT x = 0; x < target_side; ++x) {
187 std::uint32_t word;
188 std::memcpy(&word, mapped + foot[0].Offset + y * foot[0].Footprint.RowPitch + x * 4, 4);
189 out.depth[y * target_side + x] = word & leonida::depth24_max;
190 out.stencil[y * target_side + x] = mapped[foot[1].Offset + y * foot[1].Footprint.RowPitch + x];
191 }
192 readback->Unmap(0, nullptr);
193 return true;
194 }
195};
196
197std::string describe(const Pass& p) {
198 char text[200];
199 const char* stages = p.shader_depth ? "PS writes depth"
200 : p.pixel_shader ? "with PS"
201 : p.geometry_shader ? "GS, no PS"
202 : "no PS";
203 std::snprintf(text, sizeof(text), "%s, bias %d, slope %g, clamp %g", stages, p.bias, p.slope, p.clamp);
204 return text;
205}
206
207} // namespace
208
209int main() {
210 vktest::Device d;
211 const auto device_status = d.initialize();
212 if (device_status == vktest::DeviceStatus::unavailable) {
213 std::fprintf(stderr, "SKIP: no usable Vulkan 1.3 device\n");
214 return 77;
215 }
216 EXPECT(device_status == vktest::DeviceStatus::ready);
217 bool native = true;
218 {
219 const auto props = reinterpret_cast<PFN_vkGetPhysicalDeviceFormatProperties>(
220 d.instance_proc(d.instance, "vkGetPhysicalDeviceFormatProperties"));
221 VkFormatProperties d24{};
222 props(d.physical, VK_FORMAT_D24_UNORM_S8_UINT, &d24);
223 native = d24.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT;
224 std::printf("D24_UNORM_S8_UINT: %s\n", native ? "native D24" : "stored as D32_SFLOAT_S8_UINT");
225 }
226
227 const auto vs_program = fssm_program({0x56530309, 0xbf810000});
228 const auto ps_empty_program = fssm_program({0x50530309, 0xbf810000});
229 const auto ps_write_program = fssm_program({0x50530310, 0xbf810000});
230 const auto gs_program = fssm_program({0x47530309, 0xbf810000});
231 const auto library = std::filesystem::temp_directory_path() / "leonida_depth24_draw_test";
232 std::filesystem::create_directories(library);
233 const auto copy = std::filesystem::copy_options::overwrite_existing;
234 std::filesystem::copy_file(LEONIDA_TEST_VS_DEPTH_SPV, library / "vs_depth.spv", copy);
235 std::filesystem::copy_file(LEONIDA_TEST_PS_DEPTH_EMPTY_SPV, library / "ps_depth_empty.spv", copy);
236 std::filesystem::copy_file(LEONIDA_TEST_PS_DEPTH_WRITE_SPV, library / "ps_depth_write.spv", copy);
237 std::filesystem::copy_file(LEONIDA_TEST_GS_DEPTH_SPV, library / "gs_depth.spv", copy);
238 {
239 std::ofstream index(library / "index.json", std::ios::binary);
240 index << "{\"vs_depth\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_program)
241 << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"input_signature\": []},\n"
242 " \"ps_depth_empty\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(ps_empty_program)
243 << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"outputs\": []},\n"
244 " \"ps_depth_write\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(ps_write_program)
245 << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"outputs\": []},\n"
246 " \"gs_depth\": {\"stage\": \"gs\", \"fssm_sha256\": \"" << leonida::sha256_hex(gs_program)
247 << "\", \"bindings\": [], \"push_constant_bytes\": 144}}";
248 }
249
250 {
251 rt::d3d12::VulkanDeviceInfo info{};
252 info.get_instance_proc = d.instance_proc;
253 info.instance = d.instance;
254 info.physical = d.physical;
255 info.device = d.device;
256 info.queue = d.queue;
257 info.queue_family = d.family;
258 info.buffer_device_address = true;
259 info.subgroup = d.subgroup;
260 info.shader_dir = library.string();
261 info.features = d.enabled; // depthBiasClamp and geometryShader among them
262 ID3D12Device* inner = nullptr;
263 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner))));
264 Ref<ID3D12Device> device;
265 EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device),
266 reinterpret_cast<void**>(&device.p))));
267 rt::d3d12::set_device_outer(inner, device.p);
268
269 D3D12_ROOT_PARAMETER param{};
270 param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
271 param.Constants = {0, 0, 3};
272 D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{};
273 root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
274 root_desc.Desc_1_0 = {1, &param, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE};
275 const auto root_blob = serialize_root_signature(root_desc);
276 EXPECT(!root_blob.empty());
277 Ref<ID3D12RootSignature> root;
278 EXPECT(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p))));
279
280 Harness h;
281 h.device = device.p;
282 h.root = root.p;
283 h.vs = shader_container(vs_program);
284 h.ps_empty = shader_container(ps_empty_program);
285 h.ps_write = shader_container(ps_write_program);
286 h.gs = shader_container(gs_program);
287
288 D3D12_RESOURCE_DESC depth_desc{};
289 depth_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
290 depth_desc.Width = depth_desc.Height = target_side;
291 depth_desc.DepthOrArraySize = 1;
292 depth_desc.MipLevels = 1;
293 depth_desc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
294 depth_desc.SampleDesc.Count = 1;
295 depth_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
296 D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT};
297 D3D12_CLEAR_VALUE clear{};
298 clear.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
299 clear.DepthStencil.Depth = 1.0f;
300 EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &depth_desc,
301 D3D12_RESOURCE_STATE_COPY_SOURCE, &clear,
302 IID_PPV_ARGS(&h.depth.p))));
303 UINT64 total = 0;
304 device->GetCopyableFootprints(&depth_desc, 0, 2, 0, h.foot, nullptr, nullptr, &total);
305 D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK};
306 const D3D12_RESOURCE_DESC readback_desc = buffer_desc(total);
307 EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc,
308 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
309 IID_PPV_ARGS(&h.readback.p))));
310 const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0};
311 EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&h.dsv_heap.p))));
312 h.dsv = {SIZE_T(reinterpret_cast<XboxHeapHandleFn>(slot(h.dsv_heap.p, 9))(h.dsv_heap.p))};
313 device->CreateDepthStencilView(h.depth.p, nullptr, h.dsv);
314 D3D12_COMMAND_QUEUE_DESC queue_desc{};
315 EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&h.queue.p))));
316 EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&h.allocator.p))));
317 EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, h.allocator.p, nullptr,
318 IID_PPV_ARGS(&h.list.p))));
319 EXPECT(SUCCEEDED(h.list->Close()));
320 EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&h.fence.p))));
321
322 const auto passing = [](const Result& r) {
323 int n = 0;
324 for (std::uint8_t s : r.stencil) n += s != 0;
325 return n;
326 };
327 constexpr int all = int(target_side * target_side);
328 // Without a pixel shader, with one, and through a geometry shader without one.
329 for (int mode = 0; mode < 3; ++mode) {
330 const bool ps = mode == 1, gs = mode == 2;
331 if (gs && !d.enabled.geometryShader) {
332 std::printf("SKIP the geometry-shader cases: no geometryShader on this GPU\n");
333 continue;
334 }
335 // The finding's cases: one 24-bit step above 0.15625, LESS, bias 0, +1, +2.
336 const float above = 0.15625f + 5.9604645e-8f; // 0.15625 + 2^-24
337 for (int bias : {0, 1, 2}) {
338 Pass p;
339 p.pixel_shader = ps;
340 p.geometry_shader = gs;
341 p.bias = bias;
342 p.func = D3D12_COMPARISON_FUNC_LESS;
343 p.write = false;
344 p.clear = above;
345 p.z = 0.15625f;
346 Result r;
347 std::string error;
348 EXPECT(h.run(p, r, error) || (std::fprintf(stderr, "%s\n", error.c_str()), false));
349 const int expected = bias == 0 ? all : 0;
350 check(passing(r) == expected, "LESS against 0.15625 + 2^-24, " + describe(p) + ": " +
351 std::to_string(passing(r)) + " of " + std::to_string(all) +
352 " pass, expected " + std::to_string(expected));
353 }
354 { // EQUAL at exactly the cleared value.
355 Pass p;
356 p.pixel_shader = ps;
357 p.geometry_shader = gs;
358 p.func = D3D12_COMPARISON_FUNC_EQUAL;
359 p.write = false;
360 p.clear = 0.15625f;
361 p.z = 0.15625f;
362 Result r;
363 std::string error;
364 EXPECT(h.run(p, r, error) || (std::fprintf(stderr, "%s\n", error.c_str()), false));
365 check(passing(r) == all, "EQUAL at the cleared 0.15625, " + describe(p) + ": " +
366 std::to_string(passing(r)) + " of " + std::to_string(all) + " pass");
367 }
368 // Stored depth, flat: the D24 code of z + bias * r. z sits on a 24-bit step, so no rounding tie decides the
369 // code (NVIDIA breaks ties differently from WARP and AMD, depth24.h).
370 for (int bias : {0, 3, -5, 1000}) {
371 Pass p;
372 p.pixel_shader = ps;
373 p.geometry_shader = gs;
374 p.bias = bias;
375 p.z = leonida::depth24_to_float(5033000);
376 Result r;
377 std::string error;
378 EXPECT(h.run(p, r, error) || (std::fprintf(stderr, "%s\n", error.c_str()), false));
379 const std::uint32_t expected = leonida::depth24_quantize(p.z + d3d_bias(bias, 0, 0, 0));
380 int wrong = 0;
381 for (std::uint32_t c : r.depth) wrong += c != expected;
382 if (native && bias != 0 && wrong) {
383 // Vulkan lets a fixed-point attachment's r be up to 2 * 2^-24 without VK_EXT_depth_bias_control's
384 // depthBiasExact, and the layer doesn't ask for it yet: reported, not failed (follow-up).
385 std::printf("KNOWN stored depth, flat, %s: native D24 bias not exact (code %u, D3D gives %u)\n",
386 describe(p).c_str(), r.depth[0], expected);
387 continue;
388 }
389 check(wrong == 0, "stored depth, flat, " + describe(p) + ": " + std::to_string(wrong) +
390 " of " + std::to_string(all) + " differ from code " + std::to_string(expected) +
391 " (first " + std::to_string(r.depth[0]) + ")");
392 }
393 // Stored depth, sloped: z = 0.5 + 0.25 * x_clip, so 1/128 per pixel in x. Within one 24-bit step without a
394 // slope term; with one, within two: on the D32 path the slope comes from the derivatives of the
395 // interpolated depth (a few float ulps), where D24 hardware uses the triangle's plane.
396 for (const auto& [slope, clamp] : {std::pair{0.0f, 0.0f}, {1.0f, 0.0f}, {1.0f, 0.004f}, {-2.0f, -0.01f}}) {
397 Pass p;
398 p.pixel_shader = ps;
399 p.geometry_shader = gs;
400 p.bias = 2;
401 p.slope = slope;
402 p.clamp = clamp;
403 p.z = 0.5f;
404 p.dz = 0.25f;
405 if (clamp != 0.0f && native && !d.enabled.depthBiasClamp) {
406 // The native path clamps in the rasterizer, which needs the feature this device left off.
407 std::printf("SKIP stored depth, sloped, %s: no depthBiasClamp on a native D24\n",
408 describe(p).c_str());
409 continue;
410 }
411 Result r;
412 std::string error;
413 EXPECT(h.run(p, r, error) || (std::fprintf(stderr, "%s\n", error.c_str()), false));
414 int wrong = 0;
415 std::uint32_t first_bad = 0, first_expected = 0, worst = 0;
416 const std::uint32_t tolerance = slope != 0.0f ? 2 : 1;
417 for (UINT y = 0; y < target_side; ++y)
418 for (UINT x = 0; x < target_side; ++x) {
419 const float x_clip = (float(x) + 0.5f) * 2.0f / float(target_side) - 1.0f;
420 const float z = 0.5f + 0.25f * x_clip;
421 const std::uint32_t expected =
422 leonida::depth24_quantize(z + d3d_bias(p.bias, slope, clamp, 0.25f * 2.0f / float(target_side)));
423 const std::uint32_t got = r.depth[y * target_side + x];
424 const std::uint32_t diff = got > expected ? got - expected : expected - got;
425 worst = std::max(worst, diff);
426 if (diff > tolerance) {
427 if (!wrong) first_bad = got, first_expected = expected;
428 ++wrong;
429 }
430 }
431 if (native && wrong) {
432 std::printf("KNOWN stored depth, sloped, %s: native D24 bias not exact (code %u, D3D gives %u)\n",
433 describe(p).c_str(), first_bad, first_expected);
434 continue;
435 }
436 check(wrong == 0, "stored depth, sloped, " + describe(p) + ": " + std::to_string(wrong) + " of " +
437 std::to_string(all) + " more than " + std::to_string(tolerance) +
438 " step(s) off, largest " + std::to_string(worst) +
439 (wrong ? " (got " + std::to_string(first_bad) + ", expected " +
440 std::to_string(first_expected) + ")"
441 : std::string()));
442 }
443 }
444 // A pixel shader that writes its own depth: stored quantised, and D3D adds no bias to it.
445 for (int bias : {0, 7}) {
446 Pass p;
447 p.shader_depth = true;
448 p.bias = bias;
449 p.shader_z = 0.7f;
450 Result r;
451 std::string error;
452 EXPECT(h.run(p, r, error) || (std::fprintf(stderr, "%s\n", error.c_str()), false));
453 const std::uint32_t expected = leonida::depth24_quantize(0.7f);
454 int wrong = 0;
455 for (std::uint32_t c : r.depth) wrong += c != expected;
456 check(wrong == 0, "stored depth, " + describe(p) + " 0.7: " + std::to_string(wrong) + " of " +
457 std::to_string(all) + " differ from code " + std::to_string(expected) + " (first " +
458 std::to_string(r.depth[0]) + ")");
459 }
460 }
461 std::filesystem::remove_all(library);
462 std::printf("%d failure(s)\n", g_failures);
463 return g_failures ? 1 : 0;
464}
diff --git a/runtime/test/d3d12_descriptor_test.cpp b/runtime/test/d3d12_descriptor_test.cpp
index 77d37fa1e..e89735782 100644
--- a/runtime/test/d3d12_descriptor_test.cpp
+++ b/runtime/test/d3d12_descriptor_test.cpp
@@ -58,6 +58,23 @@ struct Ref {
58 58
59void* slot(void* object, unsigned index) { return (*reinterpret_cast<void***>(object))[index]; } 59void* slot(void* object, unsigned index) { return (*reinterpret_cast<void***>(object))[index]; }
60 60
61// A root signature blob from the PC runtime's own serializer; empty when it has none for that version.
62std::vector<std::uint8_t> serialize_root_signature(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC& desc) {
63 using SerializeFn = HRESULT(WINAPI*)(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC*, ID3DBlob**, ID3DBlob**);
64 const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
65 const auto fn = d3d12 ? reinterpret_cast<SerializeFn>(
66 reinterpret_cast<void*>(GetProcAddress(d3d12, "D3D12SerializeVersionedRootSignature")))
67 : nullptr;
68 std::vector<std::uint8_t> out;
69 ID3DBlob* blob = nullptr;
70 if (fn && SUCCEEDED(fn(&desc, &blob, nullptr)) && blob) {
71 const auto* bytes = static_cast<const std::uint8_t*>(blob->GetBufferPointer());
72 out.assign(bytes, bytes + blob->GetBufferSize());
73 blob->Release();
74 }
75 return out;
76}
77
61D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes, D3D12_RESOURCE_FLAGS flags) { 78D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes, D3D12_RESOURCE_FLAGS flags) {
62 D3D12_RESOURCE_DESC desc{}; 79 D3D12_RESOURCE_DESC desc{};
63 desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; 80 desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
@@ -869,6 +886,90 @@ int main() {
869 const g::SamplerWords biased_samplers[] = {negative_bias, positive_bias}; 886 const g::SamplerWords biased_samplers[] = {negative_bias, positive_bias};
870 EXPECT(rt::d3d12::register_samplers(device.p, biased_samplers) == S_OK); 887 EXPECT(rt::d3d12::register_samplers(device.p, biased_samplers) == S_OK);
871 888
889 // Static samplers of a root signature (docs/d3d12_vulkan.md section 3.5): no heap slot and no root argument,
890 // the shader holds the S# by value, so CreateRootSignature has to register it. One per blob version, each
891 // the wrapping sampler above with its own LOD range (so its own key), and one that only the fourth has:
892 // a border sampler with the UINT white border of the static enum. None is in the hash table before its
893 // root signature is created, all are after. A version the PC serializer here does not write is skipped.
894 const auto sampler_index = [&](const g::SamplerWords& words) {
895 std::uint32_t key[8]{~0u, ~0u, ~0u, ~0u, ~0u, ~0u, ~0u, ~0u};
896 std::memcpy(key, words.data(), sizeof(words));
897 return rt::d3d12::bindless_hash_lookup(device.p, key);
898 };
899 struct StaticCase {
900 D3D_ROOT_SIGNATURE_VERSION version;
901 const char* name;
902 float max_lod;
903 bool uint_white_border;
904 g::SamplerWords words;
905 bool created;
906 } static_cases[] = {{D3D_ROOT_SIGNATURE_VERSION_1_0, "1.0", 6.0f, false, {}, false},
907 {D3D_ROOT_SIGNATURE_VERSION_1_1, "1.1", 7.0f, false, {}, false},
908 {D3D_ROOT_SIGNATURE_VERSION_1_2, "1.2", 8.0f, false, {}, false},
909 {D3D_ROOT_SIGNATURE_VERSION_1_1, "1.1, UINT white border", 9.0f, true, {}, false}};
910 std::vector<Ref<ID3D12RootSignature>> static_roots(std::size(static_cases));
911 UINT static_created = 0;
912 for (std::size_t c = 0; c < std::size(static_cases); ++c) {
913 StaticCase& test = static_cases[c];
914 g::Sampler expected = sampler;
915 expected.max_lod = test.max_lod;
916 if (test.uint_white_border) {
917 expected.address_u = g::AddressMode::clamp_border;
918 expected.border_color = g::BorderColor::opaque_white;
919 expected.integer_border = true;
920 }
921 test.words = g::encode(expected);
922 EXPECT(test.words != sampler_words && sampler_index(test.words) == 0);
923
924 D3D12_STATIC_SAMPLER_DESC1 fixed{};
925 fixed.Filter = sampler_desc.Filter;
926 fixed.AddressU = test.uint_white_border ? D3D12_TEXTURE_ADDRESS_MODE_BORDER : sampler_desc.AddressU;
927 fixed.AddressV = sampler_desc.AddressV;
928 fixed.AddressW = sampler_desc.AddressW;
929 fixed.MaxAnisotropy = sampler_desc.MaxAnisotropy;
930 fixed.ComparisonFunc = sampler_desc.ComparisonFunc;
931 fixed.BorderColor = test.uint_white_border ? D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE_UINT
932 : D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK;
933 fixed.MaxLOD = test.max_lod;
934 fixed.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
935 // D3D12_STATIC_SAMPLER_DESC is D3D12_STATIC_SAMPLER_DESC1 without the trailing Flags.
936 D3D12_STATIC_SAMPLER_DESC fixed0{};
937 std::memcpy(&fixed0, &fixed, sizeof(fixed0));
938 D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{};
939 root_desc.Version = test.version;
940 if (test.version == D3D_ROOT_SIGNATURE_VERSION_1_0) {
941 root_desc.Desc_1_0.NumStaticSamplers = 1;
942 root_desc.Desc_1_0.pStaticSamplers = &fixed0;
943 } else if (test.version == D3D_ROOT_SIGNATURE_VERSION_1_1) {
944 root_desc.Desc_1_1.NumStaticSamplers = 1;
945 root_desc.Desc_1_1.pStaticSamplers = &fixed0;
946 } else {
947 root_desc.Desc_1_2.NumStaticSamplers = 1;
948 root_desc.Desc_1_2.pStaticSamplers = &fixed;
949 }
950 const std::vector<std::uint8_t> blob = serialize_root_signature(root_desc);
951 if (blob.empty()) {
952 std::printf("static sampler, root signature %s: the PC serializer does not write it, skipped\n",
953 test.name);
954 continue;
955 }
956 EXPECT(SUCCEEDED(device->CreateRootSignature(0, blob.data(), blob.size(),
957 IID_PPV_ARGS(&static_roots[c].p))));
958 EXPECT(sampler_index(test.words) != 0);
959 test.created = true;
960 ++static_created;
961 }
962 // The entries outlive their root signatures, as a heap slot's S# outlives the heap: the shader pass below
963 // samples with them after the last reference is gone.
964 for (std::size_t c = 0; c < std::size(static_cases); ++c) {
965 const std::uint32_t before = sampler_index(static_cases[c].words);
966 static_roots[c].reset();
967 EXPECT(sampler_index(static_cases[c].words) == before);
968 }
969 std::printf("static samplers: %u of %u root signatures registered their S#\n", static_created,
970 UINT(std::size(static_cases)));
971 EXPECT(static_created >= 3); // 1.0 and 1.1 are in every d3d12.dll; 1.2 came later
972
872 // The UINT texture's view in slot 0, and three border samplers after the first: UINT (0,0,0,0) and 973 // The UINT texture's view in slot 0, and three border samplers after the first: UINT (0,0,0,0) and
873 // (1,1,1,1) from CreateSampler2, which the proxy does not have (the inner device does), and float white. 974 // (1,1,1,1) from CreateSampler2, which the proxy does not have (the inner device does), and float white.
874 constexpr UINT uint_slot = 0, uint_black = 1, uint_white = 2, float_white = 3; 975 constexpr UINT uint_slot = 0, uint_black = 1, uint_white = 2, float_white = 3;
@@ -1551,6 +1652,24 @@ int main() {
1551 clamped, texels); 1652 clamped, texels);
1552 EXPECT(wrapped == texels && clamped == texels); 1653 EXPECT(wrapped == texels && clamped == texels);
1553 1654
1655 // The static samplers' S#s: the three wrapping ones give the texture, texel for texel, as the registered
1656 // literal does. Unregistered (CreateRootSignature dropping them) they would clamp like the second above.
1657 for (const StaticCase& test : static_cases) {
1658 if (!test.created || test.uint_white_border) continue;
1659 SampleKeys key = keys[0];
1660 std::memcpy(key.ssharp, test.words.data(), sizeof(key.ssharp));
1661 std::array<std::uint8_t, bytes> pixels{};
1662 EXPECT(sample_through_set(d, set0, set0_layout, {&key, 1}, pixels.data()));
1663 UINT static_wrapped = 0, static_clamped = 0;
1664 for (UINT i = 0; i < texels; ++i) {
1665 static_wrapped += std::memcmp(pixels.data() + 4 * i, texel(i % size, i / size).data(), 4) == 0;
1666 static_clamped += std::memcmp(pixels.data() + 4 * i, texel(size - 1, i / size).data(), 4) == 0;
1667 }
1668 std::printf("static sampler, root signature %s: %u/%u texels wrapped (%u would match a clamp)\n",
1669 test.name, static_wrapped, texels, static_clamped);
1670 EXPECT(static_wrapped == texels && static_clamped < texels);
1671 }
1672
1554 // With LOD zero requested, opposite bias extremes select the first and last mips. 1673 // With LOD zero requested, opposite bias extremes select the first and last mips.
1555 for (const auto& words : biased_samplers) { 1674 for (const auto& words : biased_samplers) {
1556 SampleKeys key = keys[0]; 1675 SampleKeys key = keys[0];
diff --git a/runtime/test/d3d12_draw_test.cpp b/runtime/test/d3d12_draw_test.cpp
index 25c198d7a..eb530b084 100644
--- a/runtime/test/d3d12_draw_test.cpp
+++ b/runtime/test/d3d12_draw_test.cpp
@@ -13,6 +13,7 @@
13// The shaders are GLSL written to the translator's contract (test/glsl/vs_draw.vert, ps_draw.frag). No game data. 13// The shaders are GLSL written to the translator's contract (test/glsl/vs_draw.vert, ps_draw.frag). No game data.
14// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. 14// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation.
15#include "shader_fixture_path.h" 15#include "shader_fixture_path.h"
16#include "test_temp_dir.h"
16#include "vk_test_device.h" 17#include "vk_test_device.h"
17#include "d3d12_test_shaders.h" 18#include "d3d12_test_shaders.h"
18#include "../shims/d3d12_com.h" 19#include "../shims/d3d12_com.h"
@@ -68,14 +69,13 @@ int main() {
68 const auto vs_container = shader_container(vs_program), ps_container = shader_container(ps_program); 69 const auto vs_container = shader_container(vs_program), ps_container = shader_container(ps_program);
69 const auto fullscreen_container = shader_container(fullscreen_program); 70 const auto fullscreen_container = shader_container(fullscreen_program);
70 const auto vs_int_container = shader_container(vs_int_program); 71 const auto vs_int_container = shader_container(vs_int_program);
71 const auto library = std::filesystem::temp_directory_path() / "leonida_draw_test"; 72 const testfiles::ScratchDir scratch("leonida_draw_test");
72 std::filesystem::create_directories(library); 73 const auto& library = scratch.path();
73 std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_VS_SPV), library / "vs_draw.spv", std::filesystem::copy_options::overwrite_existing); 74 EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_VS_SPV), library / "vs_draw.spv"));
74 std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_PS_SPV), library / "ps_draw.spv", std::filesystem::copy_options::overwrite_existing); 75 EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_PS_SPV), library / "ps_draw.spv"));
75 std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_VS_FULLSCREEN_SPV), library / "vs_fullscreen.spv", 76 EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_VS_FULLSCREEN_SPV),
76 std::filesystem::copy_options::overwrite_existing); 77 library / "vs_fullscreen.spv"));
77 std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_VS_INT_SPV), library / "vs_draw_int.spv", 78 EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_VS_INT_SPV), library / "vs_draw_int.spv"));
78 std::filesystem::copy_options::overwrite_existing);
79 { 79 {
80 std::ofstream index(library / "index.json", std::ios::binary); 80 std::ofstream index(library / "index.json", std::ios::binary);
81 index << "{\"vs_draw\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_program) 81 index << "{\"vs_draw\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_program)
@@ -895,7 +895,6 @@ int main() {
895 fence.reset(); 895 fence.reset();
896 EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); 896 EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1);
897 } 897 }
898 std::filesystem::remove_all(library);
899 898
900 unsigned mismatches = 0; 899 unsigned mismatches = 0;
901 for (UINT row = 0; row < size; ++row) { 900 for (UINT row = 0; row < size; ++row) {
diff --git a/runtime/test/d3d12_fspx_compute_test.cpp b/runtime/test/d3d12_fspx_compute_test.cpp
index 22202dd50..2f788dc75 100644
--- a/runtime/test/d3d12_fspx_compute_test.cpp
+++ b/runtime/test/d3d12_fspx_compute_test.cpp
@@ -10,6 +10,7 @@
10// The shader (test/glsl/cs_user_data.comp) stands in for a translated one. No game data. Set LEONIDA_VK_VALIDATION=1 10// The shader (test/glsl/cs_user_data.comp) stands in for a translated one. No game data. Set LEONIDA_VK_VALIDATION=1
11// to run under VK_LAYER_KHRONOS_validation. 11// to run under VK_LAYER_KHRONOS_validation.
12#include "shader_fixture_path.h" 12#include "shader_fixture_path.h"
13#include "test_temp_dir.h"
13#include "vk_test_device.h" 14#include "vk_test_device.h"
14#include "../shims/d3d12_com.h" 15#include "../shims/d3d12_com.h"
15#include "../src/shader_library.h" 16#include "../src/shader_library.h"
@@ -163,15 +164,18 @@ int main() {
163 constexpr std::uint32_t marker_a = 5000, marker_b = 7000; 164 constexpr std::uint32_t marker_a = 5000, marker_b = 7000;
164 const auto code_a = kind6(marker_a), code_b = kind6(marker_b); 165 const auto code_a = kind6(marker_a), code_b = kind6(marker_b);
165 const auto container_a = container(payload(code_a)); 166 const auto container_a = container(payload(code_a));
166 const auto library = std::filesystem::temp_directory_path() / "leonida_fspx_compute_test"; 167 const testfiles::ScratchDir scratch("leonida_fspx_compute_test");
167 std::filesystem::remove_all(library); 168 const auto& library = scratch.path();
168 std::filesystem::create_directories(library / "fspx"); 169 std::filesystem::create_directories(library / "fspx");
169 std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), library / "fspx" / "cs_user_data.spv"); 170 EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV),
170 std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), library / "fspx" / "cs_user_data_b.spv"); 171 library / "fspx" / "cs_user_data.spv"));
172 EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV),
173 library / "fspx" / "cs_user_data_b.spv"));
171 // The review case on #1911: program C in two containers whose kind-0 entries differ, translated to two 174 // The review case on #1911: program C in two containers whose kind-0 entries differ, translated to two
172 // different modules (the second has another generator word in its header, still a valid module). 175 // different modules (the second has another generator word in its header, still a valid module).
173 const auto code_c = kind6(9100); 176 const auto code_c = kind6(9100);
174 std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), library / "fspx" / "cs_c_state1.spv"); 177 EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV),
178 library / "fspx" / "cs_c_state1.spv"));
175 { 179 {
176 std::ifstream in(LEONIDA_TEST_CS_SPV, std::ios::binary); 180 std::ifstream in(LEONIDA_TEST_CS_SPV, std::ios::binary);
177 std::vector<char> words((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>()); 181 std::vector<char> words((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
@@ -395,7 +399,6 @@ int main() {
395 fence.reset(); 399 fence.reset();
396 EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); 400 EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1);
397 } 401 }
398 std::filesystem::remove_all(library);
399 402
400 unsigned mismatches = 0; 403 unsigned mismatches = 0;
401 for (std::uint32_t i = 0; i < elements; ++i) { 404 for (std::uint32_t i = 0; i < elements; ++i) {
diff --git a/runtime/test/d3d12_geometry_test.cpp b/runtime/test/d3d12_geometry_test.cpp
index 3ee4420c3..1cfe035b7 100644
--- a/runtime/test/d3d12_geometry_test.cpp
+++ b/runtime/test/d3d12_geometry_test.cpp
@@ -40,7 +40,9 @@ struct Vertex {
40 40
41int main() { 41int main() {
42 vktest::Device d; 42 vktest::Device d;
43 EXPECT(d.create()); 43 const auto device_status = d.initialize();
44 if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU (hosted CI): ctest skips
45 EXPECT(device_status == vktest::DeviceStatus::ready);
44 if (!d.enabled.geometryShader) { 46 if (!d.enabled.geometryShader) {
45 std::printf("SKIP: no geometryShader on this GPU\n"); 47 std::printf("SKIP: no geometryShader on this GPU\n");
46 return 77; // ctest's SKIP_RETURN_CODE 48 return 77; // ctest's SKIP_RETURN_CODE
diff --git a/runtime/test/d3d12_heap_properties_test.cpp b/runtime/test/d3d12_heap_properties_test.cpp
new file mode 100644
index 000000000..434a7522b
--- /dev/null
+++ b/runtime/test/d3d12_heap_properties_test.cpp
@@ -0,0 +1,284 @@
1// ID3D12Resource::GetHeapProperties on the Vulkan-backed device, compared with the host PC runtime: the properties
2// (type, CPU page property, memory pool, node masks) and heap flags it reports for committed resources in every heap
3// type (custom ones included) and with SHARED, ALLOW_DISPLAY, CREATE_NOT_ZEROED and CREATE_NOT_RESIDENT, for placed
4// resources in heaps of each kind, and for a reserved resource, with null arguments too. d3d12_node_mask_test covers
5// the node masks and DENY bits of a few committed resources; this test covers the rest. Every value is recorded,
6// with whether the call wrote its outputs (they start as a sentinel), and the two records must be the same. A
7// resource one device refuses to create is reported and its steps aren't compared. No shaders or game data. Skips
8// (77) without a Vulkan GPU or the standalone device; without a host D3D12 device only the layer's own record is
9// printed. Set LEONIDA_D3D49_VERBOSE=1 to print every value.
10#include "../shims/d3d12_com.h"
11
12#include <cstdint>
13#include <cstdio>
14#include <cstring>
15#include <string>
16#include <vector>
17
18#define EXPECT(condition) do { \
19 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
20} while (0)
21
22namespace {
23
24template<class T>
25struct Ref {
26 T* p = nullptr;
27 ~Ref() { reset(); }
28 void reset() {
29 if (p) p->Release();
30 p = nullptr;
31 }
32 T* operator->() const { return p; }
33};
34
35constexpr std::uint64_t kFaulted = 0xFA017EDull;
36constexpr std::uint64_t kNotCreated = 0x5C1F1Dull; // the resource couldn't be created on this device
37constexpr UINT kSentinel = 0xCDCDCDCDu;
38
39D3D12_RESOURCE_DESC buffer(UINT64 bytes = 64 * 1024) {
40 D3D12_RESOURCE_DESC d{};
41 d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
42 d.Width = bytes;
43 d.Height = 1;
44 d.DepthOrArraySize = 1;
45 d.MipLevels = 1;
46 d.SampleDesc.Count = 1;
47 d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
48 return d;
49}
50
51D3D12_RESOURCE_DESC texture(DXGI_FORMAT format = DXGI_FORMAT_R8G8B8A8_UNORM,
52 D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) {
53 D3D12_RESOURCE_DESC d{};
54 d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
55 d.Width = 64;
56 d.Height = 64;
57 d.DepthOrArraySize = 1;
58 d.MipLevels = 1;
59 d.Format = format;
60 d.SampleDesc.Count = 1;
61 d.Flags = flags;
62 return d;
63}
64
65D3D12_HEAP_PROPERTIES heap(D3D12_HEAP_TYPE type) { return D3D12_HEAP_PROPERTIES{type}; }
66D3D12_HEAP_PROPERTIES custom(D3D12_CPU_PAGE_PROPERTY page, D3D12_MEMORY_POOL pool) {
67 return D3D12_HEAP_PROPERTIES{D3D12_HEAP_TYPE_CUSTOM, page, pool};
68}
69
70enum class Kind { committed, placed, reserved };
71
72struct Case {
73 const char* name;
74 Kind kind;
75 D3D12_HEAP_PROPERTIES props; // the committed resource's, or the placed resource's heap
76 D3D12_HEAP_FLAGS flags;
77 D3D12_RESOURCE_DESC desc;
78 D3D12_RESOURCE_STATES state;
79};
80
81const D3D12_HEAP_FLAGS kNone = D3D12_HEAP_FLAG_NONE;
82const D3D12_RESOURCE_STATES kCommon = D3D12_RESOURCE_STATE_COMMON;
83
84std::vector<Case> cases() {
85 const auto rt = texture(DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET);
86 const auto ds = texture(DXGI_FORMAT_D32_FLOAT, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL);
87 const auto uav = texture(DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS);
88 auto uav_buffer = buffer();
89 uav_buffer.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
90 const auto wb = custom(D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, D3D12_MEMORY_POOL_L0);
91 const auto wc = custom(D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE, D3D12_MEMORY_POOL_L0);
92 const auto none_l0 = custom(D3D12_CPU_PAGE_PROPERTY_NOT_AVAILABLE, D3D12_MEMORY_POOL_L0);
93 const auto none_l1 = custom(D3D12_CPU_PAGE_PROPERTY_NOT_AVAILABLE, D3D12_MEMORY_POOL_L1);
94 auto masks = heap(D3D12_HEAP_TYPE_DEFAULT);
95 masks.CreationNodeMask = 1;
96 masks.VisibleNodeMask = 1;
97 return {
98 {"committed buffer, DEFAULT", Kind::committed, heap(D3D12_HEAP_TYPE_DEFAULT), kNone, buffer(), kCommon},
99 {"committed UAV buffer, DEFAULT", Kind::committed, heap(D3D12_HEAP_TYPE_DEFAULT), kNone, uav_buffer, kCommon},
100 {"committed buffer, UPLOAD", Kind::committed, heap(D3D12_HEAP_TYPE_UPLOAD), kNone, buffer(),
101 D3D12_RESOURCE_STATE_GENERIC_READ},
102 {"committed buffer, READBACK", Kind::committed, heap(D3D12_HEAP_TYPE_READBACK), kNone, buffer(),
103 D3D12_RESOURCE_STATE_COPY_DEST},
104 {"committed buffer, CUSTOM write-back L0", Kind::committed, wb, kNone, buffer(), kCommon},
105 {"committed buffer, CUSTOM write-combine L0", Kind::committed, wc, kNone, buffer(), kCommon},
106 {"committed buffer, CUSTOM not-available L0", Kind::committed, none_l0, kNone, buffer(), kCommon},
107 {"committed buffer, CUSTOM not-available L1", Kind::committed, none_l1, kNone, buffer(), kCommon},
108 {"committed buffer, DEFAULT with node masks 1", Kind::committed, masks, kNone, buffer(), kCommon},
109 {"committed buffer, DEFAULT, SHARED", Kind::committed, heap(D3D12_HEAP_TYPE_DEFAULT), D3D12_HEAP_FLAG_SHARED,
110 buffer(), kCommon},
111 {"committed buffer, DEFAULT, CREATE_NOT_ZEROED", Kind::committed, heap(D3D12_HEAP_TYPE_DEFAULT),
112 D3D12_HEAP_FLAG_CREATE_NOT_ZEROED, buffer(), kCommon},
113 {"committed buffer, DEFAULT, CREATE_NOT_RESIDENT", Kind::committed, heap(D3D12_HEAP_TYPE_DEFAULT),
114 D3D12_HEAP_FLAG_CREATE_NOT_RESIDENT, buffer(), kCommon},
115 {"committed buffer, DEFAULT, SHARED | CREATE_NOT_ZEROED", Kind::committed, heap(D3D12_HEAP_TYPE_DEFAULT),
116 D3D12_HEAP_FLAG_SHARED | D3D12_HEAP_FLAG_CREATE_NOT_ZEROED, buffer(), kCommon},
117 {"committed texture, DEFAULT", Kind::committed, heap(D3D12_HEAP_TYPE_DEFAULT), kNone, texture(), kCommon},
118 {"committed render target, DEFAULT", Kind::committed, heap(D3D12_HEAP_TYPE_DEFAULT), kNone, rt, kCommon},
119 {"committed depth texture, DEFAULT", Kind::committed, heap(D3D12_HEAP_TYPE_DEFAULT), kNone, ds,
120 D3D12_RESOURCE_STATE_DEPTH_WRITE},
121 {"committed UAV texture, DEFAULT", Kind::committed, heap(D3D12_HEAP_TYPE_DEFAULT), kNone, uav, kCommon},
122 {"committed render target, DEFAULT, ALLOW_DISPLAY", Kind::committed, heap(D3D12_HEAP_TYPE_DEFAULT),
123 D3D12_HEAP_FLAG_ALLOW_DISPLAY, rt, kCommon},
124 {"committed render target, DEFAULT, SHARED", Kind::committed, heap(D3D12_HEAP_TYPE_DEFAULT),
125 D3D12_HEAP_FLAG_SHARED, rt, kCommon},
126 {"committed texture, CUSTOM write-back L0", Kind::committed, wb, kNone, texture(), kCommon},
127 {"committed texture, CUSTOM write-combine L0", Kind::committed, wc, kNone, texture(), kCommon},
128
129 {"placed buffer, DEFAULT heap, ALLOW_ONLY_BUFFERS", Kind::placed, heap(D3D12_HEAP_TYPE_DEFAULT),
130 D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS, buffer(), kCommon},
131 {"placed buffer, DEFAULT heap, ALLOW_ALL", Kind::placed, heap(D3D12_HEAP_TYPE_DEFAULT),
132 D3D12_HEAP_FLAG_ALLOW_ALL_BUFFERS_AND_TEXTURES, buffer(), kCommon},
133 {"placed texture, DEFAULT heap, ALLOW_ONLY_NON_RT_DS_TEXTURES", Kind::placed, heap(D3D12_HEAP_TYPE_DEFAULT),
134 D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES, texture(), kCommon},
135 {"placed render target, DEFAULT heap, ALLOW_ONLY_RT_DS_TEXTURES", Kind::placed,
136 heap(D3D12_HEAP_TYPE_DEFAULT), D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES, rt, kCommon},
137 {"placed texture, DEFAULT heap, ALLOW_ALL", Kind::placed, heap(D3D12_HEAP_TYPE_DEFAULT),
138 D3D12_HEAP_FLAG_ALLOW_ALL_BUFFERS_AND_TEXTURES, texture(), kCommon},
139 {"placed buffer, UPLOAD heap", Kind::placed, heap(D3D12_HEAP_TYPE_UPLOAD),
140 D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS, buffer(), D3D12_RESOURCE_STATE_GENERIC_READ},
141 {"placed buffer, READBACK heap", Kind::placed, heap(D3D12_HEAP_TYPE_READBACK),
142 D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS, buffer(), D3D12_RESOURCE_STATE_COPY_DEST},
143 {"placed buffer, CUSTOM write-back L0 heap", Kind::placed, wb, D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS, buffer(),
144 kCommon},
145 {"placed buffer, DEFAULT heap, SHARED", Kind::placed, heap(D3D12_HEAP_TYPE_DEFAULT),
146 D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS | D3D12_HEAP_FLAG_SHARED, buffer(), kCommon},
147 {"placed buffer, DEFAULT heap, CREATE_NOT_ZEROED", Kind::placed, heap(D3D12_HEAP_TYPE_DEFAULT),
148 D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS | D3D12_HEAP_FLAG_CREATE_NOT_ZEROED, buffer(), kCommon},
149
150 {"reserved buffer", Kind::reserved, {}, kNone, buffer(), kCommon},
151 {"reserved texture", Kind::reserved, {}, kNone, [] {
152 auto d = texture();
153 d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
154 return d;
155 }(), kCommon},
156 };
157}
158
159struct Record {
160 std::vector<std::string> names;
161 std::vector<std::uint64_t> values;
162 void add(const std::string& name, std::uint64_t value) {
163 names.push_back(name);
164 values.push_back(value);
165 }
166};
167
168HRESULT create(ID3D12Device* device, const Case& c, Ref<ID3D12Heap>& h, Ref<ID3D12Resource>& r) {
169 switch (c.kind) {
170 case Kind::committed:
171 return device->CreateCommittedResource(&c.props, c.flags, &c.desc, c.state, nullptr, IID_PPV_ARGS(&r.p));
172 case Kind::placed: {
173 D3D12_HEAP_DESC hd{};
174 hd.SizeInBytes = 4 * 1024 * 1024;
175 hd.Properties = c.props;
176 hd.Flags = c.flags;
177 const HRESULT hr = device->CreateHeap(&hd, IID_PPV_ARGS(&h.p));
178 if (FAILED(hr)) return hr;
179 return device->CreatePlacedResource(h.p, 0, &c.desc, c.state, nullptr, IID_PPV_ARGS(&r.p));
180 }
181 case Kind::reserved:
182 return device->CreateReservedResource(&c.desc, c.state, nullptr, IID_PPV_ARGS(&r.p));
183 }
184 return E_FAIL;
185}
186
187HRESULT get(ID3D12Resource* r, D3D12_HEAP_PROPERTIES* p, D3D12_HEAP_FLAGS* f) {
188 __try {
189 return r->GetHeapProperties(p, f);
190 } __except (EXCEPTION_EXECUTE_HANDLER) {
191 return HRESULT(kFaulted);
192 }
193}
194
195void record_call(Record& out, const std::string& what, ID3D12Resource* r, bool want_props, bool want_flags) {
196 D3D12_HEAP_PROPERTIES p;
197 std::memset(&p, 0xCD, sizeof(p));
198 auto f = D3D12_HEAP_FLAGS(kSentinel);
199 const HRESULT hr = get(r, want_props ? &p : nullptr, want_flags ? &f : nullptr);
200 out.add(what + ": hr", std::uint32_t(hr));
201 if (want_props) {
202 out.add(what + ": Type", std::uint32_t(p.Type));
203 out.add(what + ": CPUPageProperty", std::uint32_t(p.CPUPageProperty));
204 out.add(what + ": MemoryPoolPreference", std::uint32_t(p.MemoryPoolPreference));
205 out.add(what + ": CreationNodeMask", p.CreationNodeMask);
206 out.add(what + ": VisibleNodeMask", p.VisibleNodeMask);
207 }
208 if (want_flags) out.add(what + ": flags", std::uint32_t(f));
209}
210
211void run(ID3D12Device* device, Record& out) {
212 for (const Case& c : cases()) {
213 Ref<ID3D12Heap> h;
214 Ref<ID3D12Resource> r;
215 const HRESULT created = create(device, c, h, r);
216 out.add(std::string(c.name) + ": created", std::uint32_t(created));
217 if (FAILED(created) || !r.p) {
218 out.add(std::string(c.name) + " [not created]", kNotCreated);
219 continue;
220 }
221 record_call(out, c.name, r.p, true, true);
222 record_call(out, std::string(c.name) + ", properties only", r.p, true, false);
223 record_call(out, std::string(c.name) + ", flags only", r.p, false, true);
224 record_call(out, std::string(c.name) + ", both null", r.p, false, false);
225 }
226}
227
228} // namespace
229
230int main() {
231 Ref<ID3D12Device> device;
232 if (FAILED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&device.p))) || !device.p) {
233 std::printf("heap properties: no Vulkan device, skipped\n");
234 return 77;
235 }
236 const bool verbose = GetEnvironmentVariableA("LEONIDA_D3D49_VERBOSE", nullptr, 0) > 0;
237 Record ours;
238 run(device.p, ours);
239
240 const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
241 const auto create_host = d3d12 ? reinterpret_cast<PFN_D3D12_CREATE_DEVICE>(
242 reinterpret_cast<void*>(GetProcAddress(d3d12, "D3D12CreateDevice")))
243 : nullptr;
244 Ref<ID3D12Device> host;
245 if (!create_host || FAILED(create_host(nullptr, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) {
246 std::printf("heap properties: no host D3D12 device to compare with; %zu values recorded, not compared\n",
247 ours.values.size());
248 } else {
249 Record theirs;
250 run(host.p, theirs);
251 // A resource one side couldn't create has fewer entries: compare case by case on the names both have.
252 int mismatches = 0, compared = 0, skipped = 0;
253 std::size_t j = 0;
254 for (std::size_t i = 0; i < ours.names.size(); ++i) {
255 while (j < theirs.names.size() && theirs.names[j] != ours.names[i]) ++j;
256 if (j == theirs.names.size()) {
257 std::printf("heap properties %s: ours 0x%llx, the host has no such value (not compared)\n",
258 ours.names[i].c_str(), static_cast<unsigned long long>(ours.values[i]));
259 ++skipped;
260 j = 0;
261 continue;
262 }
263 const std::uint64_t a = ours.values[i], b = theirs.values[j];
264 if (b == kFaulted) {
265 std::printf("heap properties %s: the host faults, not compared (ours 0x%llx)\n", ours.names[i].c_str(),
266 static_cast<unsigned long long>(a));
267 ++skipped;
268 continue;
269 }
270 ++compared;
271 const bool same = a == b;
272 if (verbose || !same)
273 std::printf("heap properties %s: ours 0x%llx host 0x%llx%s\n", ours.names[i].c_str(),
274 static_cast<unsigned long long>(a), static_cast<unsigned long long>(b),
275 same ? "" : " MISMATCH");
276 mismatches += !same;
277 }
278 std::printf("heap properties: %d values compared with the host (%d more not compared), %d mismatches\n",
279 compared, skipped, mismatches);
280 EXPECT(mismatches == 0);
281 }
282 std::printf("d3d12_heap_properties_test: OK\n");
283 return 0;
284}
diff --git a/runtime/test/d3d12_indirect_dispatch_count_test.cpp b/runtime/test/d3d12_indirect_dispatch_count_test.cpp
new file mode 100644
index 000000000..75a86b220
--- /dev/null
+++ b/runtime/test/d3d12_indirect_dispatch_count_test.cpp
@@ -0,0 +1,231 @@
1// D3D12 ExecuteIndirect with a GPU count buffer and one DISPATCH argument per record.
2// The same synthetic workload runs on native WARP and on the Vulkan layer, with actual GPU readback.
3// Set LEONIDA_VK_VALIDATION=1 to enable Vulkan core and synchronization validation.
4#include "vk_test_device.h"
5#include "shader_fixture_path.h"
6#include "d3d12_test_shaders.h"
7#include "../shims/d3d12_com.h"
8#include "../src/shader_library.h"
9#include <dxgi1_4.h>
10#include <d3dcompiler.h>
11#include <array>
12#include <cstdio>
13#include <cstring>
14#include <fstream>
15
16#ifndef LEONIDA_TEST_INDIRECT_COUNT_SPV
17#error "LEONIDA_TEST_INDIRECT_COUNT_SPV must name the synthetic GLSL compute module"
18#endif
19
20using namespace d3d12test;
21namespace {
22constexpr UINT kMaximum = 3, kStride = 20, kArgsOffset = 32, kCountOffset = 44;
23const char native_shader[] = R"(
24RWByteAddressBuffer output : register(u0);
25[numthreads(1,1,1)]
26void main(uint3 group : SV_GroupID) {
27 uint old;
28 output.InterlockedAdd(0, 1, old);
29 output.InterlockedAdd(4, group.x + 1, old);
30}
31)";
32
33bool run(ID3D12Device* dev, const std::vector<std::uint8_t>& shader, UINT count, bool gpu_update,
34 std::array<UINT, 2>& result, bool shim) {
35 Ref<ID3D12RootSignature> root;
36 D3D12_ROOT_PARAMETER param{};
37 param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV;
38 param.Descriptor = {0, 0};
39 param.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
40 D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{};
41 root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
42 root_desc.Desc_1_0 = {1, &param, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE};
43 const auto serialized = serialize_root_signature(root_desc);
44 if (serialized.empty() ||
45 FAILED(dev->CreateRootSignature(0, serialized.data(), serialized.size(), IID_PPV_ARGS(&root.p))))
46 return false;
47 D3D12_COMPUTE_PIPELINE_STATE_DESC desc{};
48 desc.pRootSignature = root.p;
49 desc.CS = {shader.data(), shader.size()};
50 Ref<ID3D12PipelineState> pso;
51 if (FAILED(dev->CreateComputePipelineState(&desc, IID_PPV_ARGS(&pso.p)))) return false;
52 const D3D12_INDIRECT_ARGUMENT_DESC argument{D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH};
53 const D3D12_COMMAND_SIGNATURE_DESC signature_desc{kStride, 1, &argument, 0};
54 Ref<ID3D12CommandSignature> signature;
55 if (FAILED(dev->CreateCommandSignature(&signature_desc, nullptr, IID_PPV_ARGS(&signature.p))))
56 return false;
57 const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD};
58 const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT};
59 const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK};
60 Ref<ID3D12Resource> source, args, counts, output, readback;
61 const auto create = [&](Ref<ID3D12Resource>& dest, D3D12_HEAP_PROPERTIES heap,
62 D3D12_RESOURCE_STATES state, D3D12_RESOURCE_FLAGS flags) {
63 const auto buffer = buffer_desc(256, flags);
64 return SUCCEEDED(dev->CreateCommittedResource(
65 &heap, D3D12_HEAP_FLAG_NONE, &buffer, state, nullptr, IID_PPV_ARGS(&dest.p)));
66 };
67 if (!create(source, upload_heap, D3D12_RESOURCE_STATE_GENERIC_READ, D3D12_RESOURCE_FLAG_NONE) ||
68 !create(args, default_heap, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE) ||
69 !create(counts, default_heap, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE) ||
70 !create(output, default_heap, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) ||
71 !create(readback, readback_heap, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE))
72 return false;
73 std::array<UINT, 64> input{};
74 for (UINT i = 0; i < kMaximum; ++i) {
75 const UINT base = (kArgsOffset + i * kStride) / 4;
76 input[base] = i + 1; // number of groups in the record, 1 then 2 then 3
77 input[base + 1] = input[base + 2] = 1;
78 input[base + 3] = 0xa5a5a5a5; // padding: must be ignored
79 input[base + 4] = 0x5a5a5a5a;
80 }
81 input[40] = count; // source offset 160, copied to destination +44
82 input[41] = 3; // update count from source offset 164
83 void* mapped = nullptr;
84 if (FAILED(source->Map(0, nullptr, &mapped)) || !mapped) return false;
85 std::memcpy(mapped, input.data(), sizeof(input));
86 source->Unmap(0, nullptr);
87
88 const D3D12_COMMAND_QUEUE_DESC queue_desc{D3D12_COMMAND_LIST_TYPE_COMPUTE};
89 Ref<ID3D12CommandQueue> queue;
90 Ref<ID3D12CommandAllocator> allocator;
91 Ref<ID3D12GraphicsCommandList> list;
92 Ref<ID3D12Fence> fence;
93 if (FAILED(dev->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p))) ||
94 FAILED(dev->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE, IID_PPV_ARGS(&allocator.p))) ||
95 FAILED(dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, allocator.p,
96 pso.p, IID_PPV_ARGS(&list.p))) ||
97 FAILED(dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p))))
98 return false;
99 list->CopyBufferRegion(args.p, kArgsOffset, source.p, kArgsOffset, kMaximum * kStride);
100 list->CopyBufferRegion(counts.p, kCountOffset, source.p, 160, 4);
101 list->CopyBufferRegion(output.p, 0, source.p, 0, 8); // initialize the UAV to zero
102 const D3D12_RESOURCE_BARRIER ready[] = {
103 transition(args.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT),
104 transition(counts.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT),
105 transition(output.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)};
106 list->ResourceBarrier(3, ready);
107 list->SetComputeRootSignature(root.p);
108 list->SetPipelineState(pso.p);
109 list->SetComputeRootUnorderedAccessView(0, output->GetGPUVirtualAddress());
110 list->ExecuteIndirect(signature.p, kMaximum, args.p, kArgsOffset, counts.p, kCountOffset);
111 if (gpu_update) {
112 auto to_copy = transition(counts.p, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
113 D3D12_RESOURCE_STATE_COPY_DEST);
114 list->ResourceBarrier(1, &to_copy);
115 list->CopyBufferRegion(counts.p, kCountOffset, source.p, 164, 4);
116 auto to_indirect = transition(counts.p, D3D12_RESOURCE_STATE_COPY_DEST,
117 D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT);
118 list->ResourceBarrier(1, &to_indirect);
119 // Repeat with a count produced by a GPU copy after the previous indirect dispatch.
120 list->ExecuteIndirect(signature.p, kMaximum, args.p, kArgsOffset, counts.p, kCountOffset);
121 }
122 const auto to_copy = transition(output.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
123 D3D12_RESOURCE_STATE_COPY_SOURCE);
124 list->ResourceBarrier(1, &to_copy);
125 list->CopyBufferRegion(readback.p, 0, output.p, 0, 8);
126 if (FAILED(list->Close())) return false;
127 ID3D12CommandList* lists[] = {list.p};
128 queue->ExecuteCommandLists(1, lists);
129 if (shim && rt::d3d12::last_execute_result(queue.p) != leonida::ReplayResult::success) return false;
130 if (FAILED(queue->Signal(fence.p, 1))) return false;
131 const HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
132 if (!event) return false;
133 const bool completed = SUCCEEDED(fence->SetEventOnCompletion(1, event)) &&
134 WaitForSingleObject(event, 20000) == WAIT_OBJECT_0;
135 CloseHandle(event);
136 if (!completed || FAILED(readback->Map(0, nullptr, &mapped)) || !mapped) return false;
137 std::memcpy(result.data(), mapped, sizeof(result));
138 readback->Unmap(0, nullptr);
139 return true;
140}
141
142std::array<UINT, 2> expected(UINT count, bool update) {
143 auto result = std::array<UINT, 2>{};
144 const auto accumulate = [&](UINT c) {
145 for (UINT i = 0; i < std::min(c, kMaximum); ++i) {
146 result[0] += i + 1;
147 result[1] += (i + 1) * (i + 2) / 2;
148 }
149 };
150 accumulate(count);
151 if (update) accumulate(3);
152 return result;
153}
154} // namespace
155
156int main() {
157 using Compile = decltype(&D3DCompile);
158 const HMODULE compiler = LoadLibraryExW(L"d3dcompiler_47.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
159 if (!compiler) return 77;
160 const auto compile = reinterpret_cast<Compile>(GetProcAddress(compiler, "D3DCompile"));
161 if (!compile) return 77;
162 Ref<ID3DBlob> native, errors;
163 if (FAILED(compile(native_shader, std::strlen(native_shader), nullptr, nullptr, nullptr,
164 "main", "cs_5_0", 0, 0, &native.p, &errors.p)) || !native.p)
165 return 1;
166 const auto* native_bytes = static_cast<const std::uint8_t*>(native->GetBufferPointer());
167 const std::vector<std::uint8_t> native_code(native_bytes, native_bytes + native->GetBufferSize());
168 Ref<IDXGIFactory4> factory;
169 Ref<IDXGIAdapter> warp;
170 Ref<ID3D12Device> host;
171 if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p))) ||
172 FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&warp.p))) ||
173 FAILED(D3D12CreateDevice(warp.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p))))
174 return 77;
175
176 vktest::Device vk;
177 vk.request_buffer_device_address = true;
178 const auto status = vk.initialize();
179 if (status == vktest::DeviceStatus::unavailable) return 77;
180 if (status != vktest::DeviceStatus::ready) return 1;
181 if (!vk.buffer_device_address) return 77;
182 std::vector<std::uint8_t> program = fssm_program({0x1100u, 0x44u, 0x55u, 0x66u, 0x77u, 0x88u});
183 for (UINT i = 0; i < 12; ++i) put32(program, 0xbf810000 + i);
184 const auto container = shader_container(program);
185 const auto fixture = std::filesystem::temp_directory_path() /
186 ("leonida_indirect_dispatch_count_" + std::to_string(GetCurrentProcessId()));
187 std::filesystem::create_directories(fixture);
188 std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_INDIRECT_COUNT_SPV),
189 fixture / "count.spv", std::filesystem::copy_options::overwrite_existing);
190 {
191 std::ofstream index(fixture / "index.json", std::ios::binary);
192 index << "{\"count\":{\"stage\":\"cs\",\"fssm_sha256\":\"" << leonida::sha256_hex(program)
193 << "\",\"bindings\":[],\"push_constant_bytes\":144,\"local_size\":[1,1,1],"
194 "\"uses_code_base\":false,\"wave64\":false}}";
195 }
196 rt::d3d12::VulkanDeviceInfo info{};
197 info.get_instance_proc = vk.instance_proc;
198 info.instance = vk.instance;
199 info.physical = vk.physical;
200 info.device = vk.device;
201 info.queue = vk.queue;
202 info.queue_family = vk.family;
203 info.buffer_device_address = vk.buffer_device_address;
204 info.shader_dir = fixture.string();
205 Ref<ID3D12Device> layer;
206 if (FAILED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&layer.p)))) return 1;
207
208 unsigned cases = 0;
209 for (UINT count : {0u, 1u, 3u, 7u}) {
210 for (bool update : {false, true}) {
211 std::array<UINT, 2> native_result{}, layer_result{};
212 if (!run(host.p, native_code, count, update, native_result, false) ||
213 !run(layer.p, container, count, update, layer_result, true) ||
214 native_result != expected(count, update) || layer_result != native_result) {
215 std::fprintf(stderr, "count %u update %d: host %u/%u, layer %u/%u, expected %u/%u\n",
216 count, int(update), native_result[0], native_result[1],
217 layer_result[0], layer_result[1],
218 expected(count, update)[0], expected(count, update)[1]);
219 return 1;
220 }
221 ++cases;
222 }
223 }
224 if (vk.validation_errors()) {
225 std::fprintf(stderr, "validation errors: %u\n", vk.validation_errors());
226 return 1;
227 }
228 std::printf("counted ExecuteIndirect(DISPATCH): %u native WARP / Vulkan GPU comparisons passed; "
229 "count=0,1,max,>max, nonzero offsets and GPU count overwrite, no validation errors\n", cases);
230 return 0;
231}
diff --git a/runtime/test/d3d12_m2_textured_test.cpp b/runtime/test/d3d12_m2_textured_test.cpp
index e742de72e..cd9448c75 100644
--- a/runtime/test/d3d12_m2_textured_test.cpp
+++ b/runtime/test/d3d12_m2_textured_test.cpp
@@ -14,6 +14,9 @@
14// the left half is drawn from the gradient, the right half (the second draw switches the SRV table to slot 1) from 14// the left half is drawn from the gradient, the right half (the second draw switches the SRV table to slot 1) from
15// the reflected texture. Compared byte for byte (error 0). The test also checks the hash table: the T# of each view and the S# 15// the reflected texture. Compared byte for byte (error 0). The test also checks the hash table: the T# of each view and the S#
16// have distinct non-zero indices, and bytes that were never created have none (the fallback, 0). 16// have distinct non-zero indices, and bytes that were never created have none (the fallback, 0).
17// The same quad is also drawn with LINEAR/CLAMP. Each RGBA8 channel is checked against the four clamped
18// texels at that pixel center, allowing one quantization level.
19//
17// Sampler control (suggested and measured by @Vonsek in #1489): with U in range, POINT/CLAMP, POINT/WRAP and the 20// Sampler control (suggested and measured by @Vonsek in #1489): with U in range, POINT/CLAMP, POINT/WRAP and the
18// fallback sampler all give the same pixels, so the draw above cannot tell which sampler it used. A second pass draws 21// fallback sampler all give the same pixels, so the draw above cannot tell which sampler it used. A second pass draws
19// with ps_m2_uoff.asm, which adds 1 to U just before image_sample, and two sampler-heap slots, [0] POINT/CLAMP and 22// with ps_m2_uoff.asm, which adds 1 to U just before image_sample, and two sampler-heap slots, [0] POINT/CLAMP and
@@ -30,6 +33,7 @@
30 33
31#include <algorithm> 34#include <algorithm>
32#include <array> 35#include <array>
36#include <cmath>
33#include <cstring> 37#include <cstring>
34#include <filesystem> 38#include <filesystem>
35#include <fstream> 39#include <fstream>
@@ -66,6 +70,26 @@ Texel gradient(UINT x, UINT y) {
66// The second texture: the first one point-reflected, so no texel of it is in the same place. 70// The second texture: the first one point-reflected, so no texel of it is in the same place.
67Texel reflected(UINT x, UINT y) { return gradient(texture_size - 1 - x, texture_size - 1 - y); } 71Texel reflected(UINT x, UINT y) { return gradient(texture_size - 1 - x, texture_size - 1 - y); }
68 72
73Texel linear_clamp(UINT col, UINT row) {
74 const float x = (col + 0.5f) * texture_size / target_size - 0.5f;
75 const float y = (row + 0.5f) * texture_size / target_size - 0.5f;
76 const int x0 = int(std::floor(x)), y0 = int(std::floor(y));
77 const float fx = x - x0, fy = y - y0;
78 const auto texel = col < target_size / 2 ? gradient : reflected;
79 auto tap = [&](int dx, int dy) {
80 return texel(std::clamp(x0 + dx, 0, int(texture_size) - 1),
81 std::clamp(y0 + dy, 0, int(texture_size) - 1));
82 };
83 const Texel a = tap(0, 0), b = tap(1, 0), c = tap(0, 1), d = tap(1, 1);
84 Texel result{};
85 for (unsigned k = 0; k < result.size(); ++k) {
86 const float top = a[k] + fx * (b[k] - a[k]);
87 const float bottom = c[k] + fx * (d[k] - c[k]);
88 result[k] = std::uint8_t(std::lround(top + fy * (bottom - top)));
89 }
90 return result;
91}
92
69} // namespace 93} // namespace
70 94
71int main() { 95int main() {
@@ -92,8 +116,15 @@ int main() {
92 const auto uoff_program = read_file(root_dir / "fssm" / "ps_m2_uoff.fssm"); 116 const auto uoff_program = read_file(root_dir / "fssm" / "ps_m2_uoff.fssm");
93 EXPECT(uoff_program.size() >= 4 && library.find("ps", leonida::sha256_hex(uoff_program))); 117 EXPECT(uoff_program.size() >= 4 && library.find("ps", leonida::sha256_hex(uoff_program)));
94 const auto uoff_container = shader_container(uoff_program); 118 const auto uoff_container = shader_container(uoff_program);
119 // ps_m2_literal builds its S# from immediates: the index lists it under literal_samplers.
120 const auto literal_program = read_file(root_dir / "fssm" / "ps_m2_literal.fssm");
121 const auto* literal_entry = library.find("ps", leonida::sha256_hex(literal_program));
122 EXPECT(literal_program.size() >= 4 && literal_entry);
123 const leonida::gfx10::SamplerWords literal_words{0x92u, 0xc00000u, 0x14500000u, 0u};
124 EXPECT(literal_entry->literal_samplers.size() == 1 && literal_entry->literal_samplers[0] == literal_words);
125 const auto literal_container = shader_container(literal_program);
95 126
96 std::vector<std::uint8_t> pixels(std::size_t(target_pitch) * target_size), control_pixels = pixels; 127 std::vector<std::uint8_t> pixels(std::size_t(target_pitch) * target_size), control_pixels = pixels, linear_pixels = pixels;
97 unsigned image_hits = 0, sampler_hits = 0; 128 unsigned image_hits = 0, sampler_hits = 0;
98 { 129 {
99 rt::d3d12::VulkanDeviceInfo info{}; 130 rt::d3d12::VulkanDeviceInfo info{};
@@ -167,6 +198,20 @@ int main() {
167 pso_desc.pRootSignature = indexed_root.p; 198 pso_desc.pRootSignature = indexed_root.p;
168 pso_desc.PS = {uoff_container.data(), uoff_container.size()}; 199 pso_desc.PS = {uoff_container.data(), uoff_container.size()};
169 EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&uoff_pso.p)))); 200 EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&uoff_pso.p))));
201 {
202 // A pipeline with a literal-S# shader registers that S#: before it the hash table has no key for the
203 // words (a lookup gives the fallback, 0), after it a sampler index. Nothing else names this S#.
204 std::uint32_t key[8];
205 std::memcpy(key, literal_words.data(), 16);
206 std::fill(key + 4, key + 8, 0xffffffffu);
207 EXPECT(rt::d3d12::bindless_hash_lookup(device.p, key) == 0);
208 D3D12_GRAPHICS_PIPELINE_STATE_DESC literal_desc = pso_desc;
209 literal_desc.pRootSignature = root.p;
210 literal_desc.PS = {literal_container.data(), literal_container.size()};
211 Ref<ID3D12PipelineState> literal_pso;
212 EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&literal_desc, IID_PPV_ARGS(&literal_pso.p))));
213 EXPECT(rt::d3d12::bindless_hash_lookup(device.p, key) != 0);
214 }
170 215
171 const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; 216 const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT};
172 const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}; 217 const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD};
@@ -218,7 +263,7 @@ int main() {
218 // The two heaps; their start handles come back in RAX (heap slots 9 and 10). 263 // The two heaps; their start handles come back in RAX (heap slots 9 and 10).
219 const D3D12_DESCRIPTOR_HEAP_DESC srv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 4, 264 const D3D12_DESCRIPTOR_HEAP_DESC srv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 4,
220 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; 265 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0};
221 const D3D12_DESCRIPTOR_HEAP_DESC sampler_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 2, 266 const D3D12_DESCRIPTOR_HEAP_DESC sampler_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 3,
222 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; 267 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0};
223 Ref<ID3D12DescriptorHeap> srv_heap, sampler_heap; 268 Ref<ID3D12DescriptorHeap> srv_heap, sampler_heap;
224 EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&srv_heap_desc, IID_PPV_ARGS(&srv_heap.p)))); 269 EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&srv_heap_desc, IID_PPV_ARGS(&srv_heap.p))));
@@ -252,6 +297,10 @@ int main() {
252 EXPECT(sampler_step >= 16); 297 EXPECT(sampler_step >= 16);
253 sampler_desc.AddressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP; 298 sampler_desc.AddressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
254 device->CreateSampler(&sampler_desc, D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(sampler_cpu + sampler_step)}); 299 device->CreateSampler(&sampler_desc, D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(sampler_cpu + sampler_step)});
300 sampler_desc.AddressU = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
301 sampler_desc.Filter = D3D12_FILTER_MIN_MAG_LINEAR_MIP_POINT;
302 device->CreateSampler(&sampler_desc, D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(sampler_cpu + 2 * sampler_step)});
303
255 304
256 // The hash table, after the descriptors were created and before anything has run: a T# is 8 dwords of the 305 // The hash table, after the descriptors were created and before anything has run: a T# is 8 dwords of the
257 // heap slot, an S# 4 dwords followed by 0xFFFFFFFF x4. Each of the three has an index, they differ, and 306 // heap slot, an S# 4 dwords followed by 0xFFFFFFFF x4. Each of the three has an index, they differ, and
@@ -326,15 +375,18 @@ int main() {
326 const D3D12_VIEWPORT viewport{0, 0, float(target_size), float(target_size), 0, 1}; 375 const D3D12_VIEWPORT viewport{0, 0, float(target_size), float(target_size), 0, 1};
327 list->RSSetViewports(1, &viewport); 376 list->RSSetViewports(1, &viewport);
328 list->OMSetRenderTargets(1, &rtv, FALSE, nullptr); 377 list->OMSetRenderTargets(1, &rtv, FALSE, nullptr);
329 list->SetGraphicsRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE{sampler_gpu}); 378 auto draw_halves = [&](std::uint64_t sampler) {
330 for (UINT half = 0; half < 2; ++half) { 379 list->SetGraphicsRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE{sampler});
331 // The same quad over the whole target; the scissor rectangle keeps one half, and the SRV table names 380 for (UINT half = 0; half < 2; ++half) {
332 // the texture of that half. 381 // The same quad over the whole target; the scissor rectangle keeps one half, and the SRV table names
333 const D3D12_RECT scissor{LONG(half * target_size / 2), 0, LONG((half + 1) * target_size / 2), LONG(target_size)}; 382 // the texture of that half.
334 list->RSSetScissorRects(1, &scissor); 383 const D3D12_RECT scissor{LONG(half * target_size / 2), 0, LONG((half + 1) * target_size / 2), LONG(target_size)};
335 list->SetGraphicsRootDescriptorTable(0, D3D12_GPU_DESCRIPTOR_HANDLE{srv_gpu + std::uint64_t(half) * step}); 384 list->RSSetScissorRects(1, &scissor);
336 list->DrawIndexedInstanced(6, 1, 0, 0, 0); 385 list->SetGraphicsRootDescriptorTable(0, D3D12_GPU_DESCRIPTOR_HANDLE{srv_gpu + std::uint64_t(half) * step});
337 } 386 list->DrawIndexedInstanced(6, 1, 0, 0, 0);
387 }
388 };
389 draw_halves(sampler_gpu);
338 390
339 D3D12_RESOURCE_BARRIER to_copy = transition(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET, 391 D3D12_RESOURCE_BARRIER to_copy = transition(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET,
340 D3D12_RESOURCE_STATE_COPY_SOURCE); 392 D3D12_RESOURCE_STATE_COPY_SOURCE);
@@ -347,6 +399,13 @@ int main() {
347 src.pResource = target.p; 399 src.pResource = target.p;
348 src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; 400 src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
349 list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); 401 list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
402 auto to_render = transition(target.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET);
403 list->ResourceBarrier(1, &to_render);
404 list->ClearRenderTargetView(rtv, clear, 0, nullptr);
405 draw_halves(sampler_gpu + 2 * sampler_step);
406 list->ResourceBarrier(1, &to_copy);
407 dst.pResource = readback2.p;
408 list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
350 EXPECT(list->Close() == S_OK); 409 EXPECT(list->Close() == S_OK);
351 ID3D12CommandList* lists[] = {list.p}; 410 ID3D12CommandList* lists[] = {list.p};
352 queue->ExecuteCommandLists(1, lists); 411 queue->ExecuteCommandLists(1, lists);
@@ -357,6 +416,11 @@ int main() {
357 EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); 416 EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped)));
358 std::memcpy(pixels.data(), mapped, pixels.size()); 417 std::memcpy(pixels.data(), mapped, pixels.size());
359 418
419 void* mapped_linear = nullptr;
420 EXPECT(SUCCEEDED(readback2->Map(0, nullptr, &mapped_linear)));
421 std::memcpy(linear_pixels.data(), mapped_linear, linear_pixels.size());
422 readback2->Unmap(0, nullptr);
423
360 // The control pass: U + 1 in the PS, WRAP sampler (slot 1) on the left, CLAMP (slot 0) on the right. 424 // The control pass: U + 1 in the PS, WRAP sampler (slot 1) on the left, CLAMP (slot 0) on the right.
361 Ref<ID3D12CommandAllocator> allocator2; 425 Ref<ID3D12CommandAllocator> allocator2;
362 Ref<ID3D12GraphicsCommandList> list2; 426 Ref<ID3D12GraphicsCommandList> list2;
@@ -418,12 +482,22 @@ int main() {
418 EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); 482 EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1);
419 } 483 }
420 484
421 unsigned mismatches = 0; 485 unsigned mismatches = 0, linear_mismatches = 0;
486 int max_linear_error = 0;
422 for (UINT row = 0; row < target_size; ++row) { 487 for (UINT row = 0; row < target_size; ++row) {
423 for (UINT col = 0; col < target_size; ++col) { 488 for (UINT col = 0; col < target_size; ++col) {
424 const UINT tx = col / (target_size / texture_size), ty = row / (target_size / texture_size); 489 const UINT tx = col / (target_size / texture_size), ty = row / (target_size / texture_size);
425 const Texel want = col < target_size / 2 ? gradient(tx, ty) : reflected(tx, ty); 490 const Texel want = col < target_size / 2 ? gradient(tx, ty) : reflected(tx, ty);
426 const std::uint8_t* got = &pixels[std::size_t(row) * target_pitch + col * 4]; 491 const std::uint8_t* got = &pixels[std::size_t(row) * target_pitch + col * 4];
492 const Texel filtered = linear_clamp(col, row);
493 const auto* linear = &linear_pixels[std::size_t(row) * target_pitch + col * 4];
494 for (unsigned k = 0; k < filtered.size(); ++k) {
495 const int error = std::abs(int(linear[k]) - filtered[k]);
496 max_linear_error = std::max(max_linear_error, error);
497 if (error > 1 && linear_mismatches++ < 8)
498 std::fprintf(stderr, "LINEAR (%u, %u) channel %u: got %u want %u\n",
499 col, row, k, unsigned(linear[k]), unsigned(filtered[k]));
500 }
427 if (std::memcmp(got, want.data(), 4) == 0) continue; 501 if (std::memcmp(got, want.data(), 4) == 0) continue;
428 if (mismatches++ < 8) 502 if (mismatches++ < 8)
429 std::fprintf(stderr, "pixel (%u, %u): got %u,%u,%u,%u want %u,%u,%u,%u\n", col, row, got[0], got[1], 503 std::fprintf(stderr, "pixel (%u, %u): got %u,%u,%u,%u want %u,%u,%u,%u\n", col, row, got[0], got[1],
@@ -431,6 +505,8 @@ int main() {
431 } 505 }
432 } 506 }
433 EXPECT(!mismatches); 507 EXPECT(!mismatches);
508 EXPECT(!linear_mismatches);
509 std::printf("M2 LINEAR: %u pixels, maximum RGBA8 channel error %d\n", target_size * target_size, max_linear_error);
434 510
435 // The control pass: left half the gradient (WRAP: U + 1 wraps back), right half the reflected texture's last 511 // The control pass: left half the gradient (WRAP: U + 1 wraps back), right half the reflected texture's last
436 // column per row (CLAMP: U + 1 is past the edge). Pixels that differ from the plain pass tell the clamp was used. 512 // column per row (CLAMP: U + 1 is past the edge). Pixels that differ from the plain pass tell the clamp was used.
diff --git a/runtime/test/d3d12_method_variants_test.cpp b/runtime/test/d3d12_method_variants_test.cpp
index 943577fff..d1b8edf4a 100644
--- a/runtime/test/d3d12_method_variants_test.cpp
+++ b/runtime/test/d3d12_method_variants_test.cpp
@@ -1,5 +1,6 @@
1// The 1/2/3 method variants of the Vulkan-backed ID3D12Device (D3D-28), each compared with the method it wraps: 1// The 1/2/3 method variants of the Vulkan-backed ID3D12Device (D3D-28), each compared with the method it wraps:
2// CreateCommittedResource1/2/3 with CreateCommittedResource, CreateCommandQueue1 with CreateCommandQueue and 2// CreateCommittedResource1/2/3 with CreateCommittedResource, CreatePlacedResource2 with CreatePlacedResource,
3// CreateReservedResource1/2 with CreateReservedResource, CreateCommandQueue1 with CreateCommandQueue and
3// GetCopyableFootprints1 with GetCopyableFootprints. The device is called directly, not through the Xbox-ABI proxy, 4// GetCopyableFootprints1 with GetCopyableFootprints. The device is called directly, not through the Xbox-ABI proxy,
4// because the proxy's slot 76 is the Xbox texture method, not CreateCommittedResource3 (docs/d3d12_vulkan.md 5// because the proxy's slot 76 is the Xbox texture method, not CreateCommittedResource3 (docs/d3d12_vulkan.md
5// section 7). The newer arguments' edge cases are checked against the PC runtime's answers, live when the host has 6// section 7). The newer arguments' edge cases are checked against the PC runtime's answers, live when the host has
@@ -215,22 +216,65 @@ struct Edge {
215// The edge cases of the newer arguments, run on any ID3D12Device10: ours, or the host's PC runtime to compare 216// The edge cases of the newer arguments, run on any ID3D12Device10: ours, or the host's PC runtime to compare
216// with. A GetCopyableFootprints1 answer is S_FALSE when every output is all ones (the failure answer), S_OK when 217// with. A GetCopyableFootprints1 answer is S_FALSE when every output is all ones (the failure answer), S_OK when
217// the footprint is the ordinary one, E_FAIL otherwise. 218// the footprint is the ordinary one, E_FAIL otherwise.
218std::vector<Edge> edge_answers(ID3D12Device10* device) { 219std::vector<Edge> edge_answers(ID3D12Device10* device, ID3D12Device10* placed_device,
219 const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}, upload_heap{D3D12_HEAP_TYPE_UPLOAD}; 220 ID3D12Device* size_host = nullptr) {
221 const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}, upload_heap{D3D12_HEAP_TYPE_UPLOAD},
222 readback_heap{D3D12_HEAP_TYPE_READBACK}, bad_heap{D3D12_HEAP_TYPE(99)};
220 D3D12_RESOURCE_DESC1 texture = desc1(texture_desc(8, 8, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE)); 223 D3D12_RESOURCE_DESC1 texture = desc1(texture_desc(8, 8, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE));
224 D3D12_RESOURCE_DESC1 rt_tex =
225 desc1(texture_desc(8, 8, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET));
226 D3D12_RESOURCE_DESC1 ds_tex =
227 desc1(texture_desc(8, 8, DXGI_FORMAT_D32_FLOAT, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL));
228 D3D12_RESOURCE_DESC1 ds_deny_tex = desc1(texture_desc(
229 8, 8, DXGI_FORMAT_D32_FLOAT, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE));
230 D3D12_RESOURCE_DESC1 uav_tex =
231 desc1(texture_desc(8, 8, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS));
232 D3D12_RESOURCE_DESC1 rt_ds_tex = desc1(texture_desc(
233 8, 8, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL));
234 D3D12_RESOURCE_DESC1 ds_uav_tex = desc1(texture_desc(
235 8, 8, DXGI_FORMAT_D32_FLOAT, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS));
236 D3D12_RESOURCE_DESC1 deny_only_tex =
237 desc1(texture_desc(8, 8, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE));
238 D3D12_RESOURCE_DESC1 zero_width_tex = desc1(texture_desc(0, 8, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE));
239 D3D12_RESOURCE_DESC1 big_tex =
240 desc1(texture_desc(1024, 1024, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE));
241 D3D12_RESOURCE_DESC1 tex_256x256 =
242 desc1(texture_desc(256, 256, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE));
243 D3D12_RESOURCE_DESC base_1000x600_10m =
244 texture_desc(1000, 600, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE, 10);
245 D3D12_RESOURCE_DESC base_300x200_f16 =
246 texture_desc(300, 200, DXGI_FORMAT_R16G16B16A16_FLOAT, D3D12_RESOURCE_FLAG_NONE);
247 D3D12_RESOURCE_DESC base_1x1024 =
248 texture_desc(1, 1024, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE);
249
221 D3D12_RESOURCE_DESC1 buffer = desc1(buffer_desc(300)); 250 D3D12_RESOURCE_DESC1 buffer = desc1(buffer_desc(300));
251 D3D12_RESOURCE_DESC1 uav_buffer = desc1(buffer_desc(256));
252 uav_buffer.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
253 D3D12_RESOURCE_DESC1 tall_buffer = desc1(buffer_desc(256));
254 tall_buffer.Height = 2;
255
222 D3D12_RESOURCE_DESC1 texture_region = texture, buffer_region = buffer; 256 D3D12_RESOURCE_DESC1 texture_region = texture, buffer_region = buffer;
223 texture_region.SamplerFeedbackMipRegion = buffer_region.SamplerFeedbackMipRegion = {4, 4, 1}; 257 texture_region.SamplerFeedbackMipRegion = buffer_region.SamplerFeedbackMipRegion = {4, 4, 1};
258
259 D3D12_CLEAR_VALUE cv_rt{DXGI_FORMAT_R8G8B8A8_UNORM, {0.f, 0.f, 0.f, 1.f}};
260 D3D12_CLEAR_VALUE cv_ds{DXGI_FORMAT_D32_FLOAT, {1.f, 0}};
261 D3D12_CLEAR_VALUE cv_bad{DXGI_FORMAT_R32_FLOAT, {0.f, 0.f, 0.f, 1.f}};
262
263 const DXGI_FORMAT srgb_cast[] = {DXGI_FORMAT_R8G8B8A8_UNORM_SRGB};
264 const DXGI_FORMAT unknown_cast[] = {DXGI_FORMAT_UNKNOWN};
265 const DXGI_FORMAT wide_cast[] = {DXGI_FORMAT_R16G16B16A16_FLOAT};
266
224 const auto v2 = [&](const D3D12_HEAP_PROPERTIES& heap, const D3D12_RESOURCE_DESC1& desc) { 267 const auto v2 = [&](const D3D12_HEAP_PROPERTIES& heap, const D3D12_RESOURCE_DESC1& desc) {
225 Ref<ID3D12Resource> r; 268 Ref<ID3D12Resource> r;
226 return device->CreateCommittedResource2(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, 269 return device->CreateCommittedResource2(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON,
227 nullptr, nullptr, IID_PPV_ARGS(&r.p)); 270 nullptr, nullptr, IID_PPV_ARGS(&r.p));
228 }; 271 };
229 const auto v3 = [&](const D3D12_HEAP_PROPERTIES& heap, const D3D12_RESOURCE_DESC1& desc, D3D12_BARRIER_LAYOUT layout, 272 const auto v3 = [&](const D3D12_HEAP_PROPERTIES& heap, const D3D12_RESOURCE_DESC1& desc, D3D12_BARRIER_LAYOUT layout,
230 UINT32 castable_count = 0, bool output = true) { 273 UINT32 castable_count = 0, bool output = true, D3D12_HEAP_FLAGS heap_flags = D3D12_HEAP_FLAG_NONE,
274 const D3D12_CLEAR_VALUE* clear = nullptr, const DXGI_FORMAT* castable = nullptr) {
231 Ref<ID3D12Resource> r; 275 Ref<ID3D12Resource> r;
232 return device->CreateCommittedResource3(&heap, D3D12_HEAP_FLAG_NONE, &desc, layout, nullptr, nullptr, 276 return device->CreateCommittedResource3(&heap, heap_flags, &desc, layout, clear, nullptr, castable_count,
233 castable_count, nullptr, __uuidof(ID3D12Resource), 277 castable, __uuidof(ID3D12Resource),
234 output ? reinterpret_cast<void**>(&r.p) : nullptr); 278 output ? reinterpret_cast<void**>(&r.p) : nullptr);
235 }; 279 };
236 const auto footprint = [&](const D3D12_RESOURCE_DESC1& desc) { 280 const auto footprint = [&](const D3D12_RESOURCE_DESC1& desc) {
@@ -245,6 +289,53 @@ std::vector<Edge> edge_answers(ID3D12Device10* device) {
245 void* queue = nullptr; 289 void* queue = nullptr;
246 const HRESULT null_queue = device->CreateCommandQueue1(nullptr, creator, __uuidof(ID3D12CommandQueue), &queue); 290 const HRESULT null_queue = device->CreateCommandQueue1(nullptr, creator, __uuidof(ID3D12CommandQueue), &queue);
247 if (queue) static_cast<IUnknown*>(queue)->Release(); 291 if (queue) static_cast<IUnknown*>(queue)->Release();
292
293 // Placed v2 setup.
294 D3D12_HEAP_DESC placed_heap_desc{256 * 1024, default_heap, D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT,
295 D3D12_HEAP_FLAG_NONE};
296 D3D12_HEAP_DESC upload_heap_desc{256 * 1024, upload_heap, D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT,
297 D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS};
298 Ref<ID3D12Heap> placed_heap, upload_placed_heap;
299 placed_device->CreateHeap(&placed_heap_desc, IID_PPV_ARGS(&placed_heap.p));
300 placed_device->CreateHeap(&upload_heap_desc, IID_PPV_ARGS(&upload_placed_heap.p));
301 const auto p2 = [&](ID3D12Heap* heap, UINT64 offset, const D3D12_RESOURCE_DESC1& desc, D3D12_BARRIER_LAYOUT layout,
302 const D3D12_CLEAR_VALUE* clear = nullptr, UINT32 cast_count = 0,
303 const DXGI_FORMAT* cast = nullptr) {
304 Ref<ID3D12Resource> r;
305 return placed_device->CreatePlacedResource2(heap, offset, &desc, layout, clear, cast_count, cast,
306 IID_PPV_ARGS(&r.p));
307 };
308 const auto p2_host_sized = [&](const D3D12_RESOURCE_DESC& base, UINT64 fallback_bytes) {
309 const UINT64 bytes = size_host ? size_host->GetResourceAllocationInfo(0, 1, &base).SizeInBytes
310 : fallback_bytes;
311 D3D12_HEAP_DESC hd{bytes, default_heap, D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT, D3D12_HEAP_FLAG_NONE};
312 Ref<ID3D12Heap> h;
313 if (FAILED(placed_device->CreateHeap(&hd, IID_PPV_ARGS(&h.p)))) return E_FAIL;
314 return p2(h.p, 0, desc1(base), D3D12_BARRIER_LAYOUT_COMMON);
315 };
316
317 // Reserved v1/v2 setup.
318 D3D12_RESOURCE_DESC res_tex = texture_desc(64, 64, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE);
319 res_tex.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
320 D3D12_RESOURCE_DESC res_rt = res_tex;
321 res_rt.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
322 D3D12_RESOURCE_DESC res_uav = res_tex;
323 res_uav.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
324 D3D12_RESOURCE_DESC res_ds_deny = texture_desc(
325 64, 64, DXGI_FORMAT_D32_FLOAT, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE);
326 res_ds_deny.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
327 D3D12_RESOURCE_DESC res_buf = buffer_desc(65536);
328 const auto r1 = [&](const D3D12_RESOURCE_DESC& desc, D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear) {
329 Ref<ID3D12Resource> r;
330 return device->CreateReservedResource1(&desc, state, clear, nullptr, IID_PPV_ARGS(&r.p));
331 };
332 const auto r2 = [&](const D3D12_RESOURCE_DESC& desc, D3D12_BARRIER_LAYOUT layout,
333 const D3D12_CLEAR_VALUE* clear = nullptr, UINT32 cast_count = 0,
334 const DXGI_FORMAT* cast = nullptr) {
335 Ref<ID3D12Resource> r;
336 return device->CreateReservedResource2(&desc, layout, clear, nullptr, cast_count, cast, IID_PPV_ARGS(&r.p));
337 };
338
248 return { 339 return {
249 {"CreateCommittedResource2, texture with a mip region", v2(default_heap, texture_region), E_INVALIDARG}, 340 {"CreateCommittedResource2, texture with a mip region", v2(default_heap, texture_region), E_INVALIDARG},
250 {"CreateCommittedResource2, buffer with a mip region", v2(upload_heap, buffer_region), S_OK}, 341 {"CreateCommittedResource2, buffer with a mip region", v2(upload_heap, buffer_region), S_OK},
@@ -254,12 +345,138 @@ std::vector<Edge> edge_answers(ID3D12Device10* device) {
254 v3(upload_heap, buffer_region, D3D12_BARRIER_LAYOUT_UNDEFINED), S_OK}, 345 v3(upload_heap, buffer_region, D3D12_BARRIER_LAYOUT_UNDEFINED), S_OK},
255 {"CreateCommittedResource3, buffer in layout COMMON", v3(upload_heap, buffer, D3D12_BARRIER_LAYOUT_COMMON), 346 {"CreateCommittedResource3, buffer in layout COMMON", v3(upload_heap, buffer, D3D12_BARRIER_LAYOUT_COMMON),
256 E_INVALIDARG}, 347 E_INVALIDARG},
348 {"CreateCommittedResource3, upload buffer in UNDEFINED",
349 v3(upload_heap, buffer, D3D12_BARRIER_LAYOUT_UNDEFINED), S_OK},
350 {"CreateCommittedResource3, readback buffer in COMMON",
351 v3(readback_heap, buffer, D3D12_BARRIER_LAYOUT_COMMON), E_INVALIDARG},
352 {"CreateCommittedResource3, readback buffer in UNDEFINED",
353 v3(readback_heap, buffer, D3D12_BARRIER_LAYOUT_UNDEFINED), S_OK},
354 {"CreateCommittedResource3, upload buffer with ALLOW_UAV",
355 v3(upload_heap, uav_buffer, D3D12_BARRIER_LAYOUT_UNDEFINED), E_INVALIDARG},
356 {"CreateCommittedResource3, buffer with Height=2",
357 v3(default_heap, tall_buffer, D3D12_BARRIER_LAYOUT_UNDEFINED), E_INVALIDARG},
257 {"CreateCommittedResource3, texture in layout UNDEFINED", 358 {"CreateCommittedResource3, texture in layout UNDEFINED",
258 v3(default_heap, texture, D3D12_BARRIER_LAYOUT_UNDEFINED), S_OK}, 359 v3(default_heap, texture, D3D12_BARRIER_LAYOUT_UNDEFINED), S_OK},
259 {"CreateCommittedResource3, castable count with a null list", 360 {"CreateCommittedResource3, castable count with a null list",
260 v3(default_heap, texture, D3D12_BARRIER_LAYOUT_COMMON, 2), S_OK}, 361 v3(default_heap, texture, D3D12_BARRIER_LAYOUT_COMMON, 2), S_OK},
261 {"CreateCommittedResource3, null output", 362 {"CreateCommittedResource3, null output",
262 v3(default_heap, texture, D3D12_BARRIER_LAYOUT_COMMON, 0, false), S_FALSE}, 363 v3(default_heap, texture, D3D12_BARRIER_LAYOUT_COMMON, 0, false), S_FALSE},
364 {"CreateCommittedResource3, bad heap type",
365 v3(bad_heap, texture, D3D12_BARRIER_LAYOUT_COMMON), E_INVALIDARG},
366 {"CreateCommittedResource3, DENY_BUFFERS heap flag",
367 v3(default_heap, texture, D3D12_BARRIER_LAYOUT_COMMON, 0, true, D3D12_HEAP_FLAG_DENY_BUFFERS), E_INVALIDARG},
368 {"CreateCommittedResource3, ALLOW_DISPLAY on buffer",
369 v3(default_heap, buffer, D3D12_BARRIER_LAYOUT_UNDEFINED, 0, true, D3D12_HEAP_FLAG_ALLOW_DISPLAY),
370 E_INVALIDARG},
371 {"CreateCommittedResource3, clear value on buffer",
372 v3(upload_heap, buffer, D3D12_BARRIER_LAYOUT_UNDEFINED, 0, true, D3D12_HEAP_FLAG_NONE, &cv_rt), E_INVALIDARG},
373 {"CreateCommittedResource3, clear value on plain texture",
374 v3(default_heap, texture, D3D12_BARRIER_LAYOUT_COMMON, 0, true, D3D12_HEAP_FLAG_NONE, &cv_rt), E_INVALIDARG},
375 {"CreateCommittedResource3, mismatched clear value on RT",
376 v3(default_heap, rt_tex, D3D12_BARRIER_LAYOUT_COMMON, 0, true, D3D12_HEAP_FLAG_NONE, &cv_bad), E_INVALIDARG},
377 {"CreateCommittedResource3, valid clear value on RT",
378 v3(default_heap, rt_tex, D3D12_BARRIER_LAYOUT_RENDER_TARGET, 0, true, D3D12_HEAP_FLAG_NONE, &cv_rt), S_OK},
379 {"CreateCommittedResource3, valid clear value on DS",
380 v3(default_heap, ds_tex, D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE, 0, true, D3D12_HEAP_FLAG_NONE, &cv_ds),
381 S_OK},
382 {"CreateCommittedResource3, RT | DS flags",
383 v3(default_heap, rt_ds_tex, D3D12_BARRIER_LAYOUT_COMMON), E_INVALIDARG},
384 {"CreateCommittedResource3, DS | UAV flags",
385 v3(default_heap, ds_uav_tex, D3D12_BARRIER_LAYOUT_COMMON), E_INVALIDARG},
386 {"CreateCommittedResource3, DENY_SHADER_RESOURCE without DS",
387 v3(default_heap, deny_only_tex, D3D12_BARRIER_LAYOUT_COMMON), E_INVALIDARG},
388 {"CreateCommittedResource3, texture Width=0",
389 v3(default_heap, zero_width_tex, D3D12_BARRIER_LAYOUT_COMMON), E_INVALIDARG},
390 {"CreateCommittedResource3, non-RT texture in RENDER_TARGET",
391 v3(default_heap, texture, D3D12_BARRIER_LAYOUT_RENDER_TARGET), E_INVALIDARG},
392 {"CreateCommittedResource3, non-UAV texture in UNORDERED_ACCESS",
393 v3(default_heap, texture, D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS), E_INVALIDARG},
394 {"CreateCommittedResource3, non-UAV texture in DIRECT_QUEUE_UAV",
395 v3(default_heap, texture, D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_UNORDERED_ACCESS), E_INVALIDARG},
396 {"CreateCommittedResource3, non-UAV texture in COMPUTE_QUEUE_UAV",
397 v3(default_heap, texture, D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_UNORDERED_ACCESS), E_INVALIDARG},
398 {"CreateCommittedResource3, UAV texture in DIRECT_QUEUE_UAV",
399 v3(default_heap, uav_tex, D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_UNORDERED_ACCESS), S_OK},
400 {"CreateCommittedResource3, non-DS texture in DEPTH_STENCIL_WRITE",
401 v3(default_heap, texture, D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE), E_INVALIDARG},
402 {"CreateCommittedResource3, non-DS texture in DEPTH_STENCIL_READ",
403 v3(default_heap, texture, D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_READ), E_INVALIDARG},
404 {"CreateCommittedResource3, DS texture in DEPTH_STENCIL_READ",
405 v3(default_heap, ds_tex, D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_READ), S_OK},
406 {"CreateCommittedResource3, DS+DENY_SR in SHADER_RESOURCE",
407 v3(default_heap, ds_deny_tex, D3D12_BARRIER_LAYOUT_SHADER_RESOURCE), E_INVALIDARG},
408 {"CreateCommittedResource3, DS+DENY_SR in DIRECT_QUEUE_SHADER_RESOURCE",
409 v3(default_heap, ds_deny_tex, D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_SHADER_RESOURCE), E_INVALIDARG},
410 {"CreateCommittedResource3, DS+DENY_SR in COMPUTE_QUEUE_SHADER_RESOURCE",
411 v3(default_heap, ds_deny_tex, D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_SHADER_RESOURCE), E_INVALIDARG},
412 {"CreateCommittedResource3, DS+DENY_SR in GENERIC_READ",
413 v3(default_heap, ds_deny_tex, D3D12_BARRIER_LAYOUT_GENERIC_READ), S_OK},
414 {"CreatePlacedResource2, buffer in COMMON",
415 p2(upload_placed_heap.p, 0, buffer, D3D12_BARRIER_LAYOUT_COMMON), E_INVALIDARG},
416 {"CreatePlacedResource2, buffer with Height=2",
417 p2(placed_heap.p, 0, tall_buffer, D3D12_BARRIER_LAYOUT_UNDEFINED), E_INVALIDARG},
418 {"CreatePlacedResource2, upload buffer with ALLOW_UAV",
419 p2(upload_placed_heap.p, 0, uav_buffer, D3D12_BARRIER_LAYOUT_UNDEFINED), E_INVALIDARG},
420 {"CreatePlacedResource2, clear value on buffer",
421 p2(placed_heap.p, 0, buffer, D3D12_BARRIER_LAYOUT_UNDEFINED, &cv_rt), E_INVALIDARG},
422 {"CreatePlacedResource2, clear value on plain texture",
423 p2(placed_heap.p, 0, texture, D3D12_BARRIER_LAYOUT_COMMON, &cv_rt), E_INVALIDARG},
424 {"CreatePlacedResource2, valid clear value on RT",
425 p2(placed_heap.p, 0, rt_tex, D3D12_BARRIER_LAYOUT_RENDER_TARGET, &cv_rt), S_OK},
426 {"CreatePlacedResource2, oversized 1024x1024 texture in 256 KiB heap",
427 p2(placed_heap.p, 0, big_tex, D3D12_BARRIER_LAYOUT_COMMON), E_INVALIDARG},
428 {"CreatePlacedResource2, 256x256 at 64 KiB in 256 KiB heap",
429 p2(placed_heap.p, 65536, tex_256x256, D3D12_BARRIER_LAYOUT_COMMON), E_INVALIDARG},
430 {"CreatePlacedResource2, 1000x600 RGBA8 10 mips in host-sized heap",
431 p2_host_sized(base_1000x600_10m, 3538944), S_OK},
432 {"CreatePlacedResource2, 300x200 RGBA16F in host-sized heap",
433 p2_host_sized(base_300x200_f16, 589824), S_OK},
434 {"CreatePlacedResource2, 1x1024 RGBA8 in 64 KiB heap",
435 p2_host_sized(base_1x1024, 65536), S_OK},
436 {"CreatePlacedResource2, 8x8 texture at 192 KiB in 256 KiB heap",
437 p2(placed_heap.p, 3 * 65536, texture, D3D12_BARRIER_LAYOUT_COMMON), S_OK},
438 {"CreatePlacedResource2, non-RT texture in RENDER_TARGET",
439 p2(placed_heap.p, 0, texture, D3D12_BARRIER_LAYOUT_RENDER_TARGET), E_INVALIDARG},
440 {"CreatePlacedResource2, non-UAV texture in UNORDERED_ACCESS",
441 p2(placed_heap.p, 0, texture, D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS), E_INVALIDARG},
442 {"CreatePlacedResource2, non-DS texture in DEPTH_STENCIL_WRITE",
443 p2(placed_heap.p, 0, texture, D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE), E_INVALIDARG},
444 {"CreatePlacedResource2, DS+DENY_SR in DIRECT_QUEUE_SHADER_RESOURCE",
445 p2(placed_heap.p, 0, ds_deny_tex, D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_SHADER_RESOURCE), E_INVALIDARG},
446 {"CreateReservedResource1, clear value on plain texture",
447 r1(res_tex, D3D12_RESOURCE_STATE_COMMON, &cv_rt), E_INVALIDARG},
448 {"CreateReservedResource2, buffer in COMMON",
449 r2(res_buf, D3D12_BARRIER_LAYOUT_COMMON), E_INVALIDARG},
450 {"CreateReservedResource2, buffer in UNDEFINED",
451 r2(res_buf, D3D12_BARRIER_LAYOUT_UNDEFINED), S_OK},
452 {"CreateReservedResource2, clear value on buffer",
453 r2(res_buf, D3D12_BARRIER_LAYOUT_UNDEFINED, &cv_rt), E_INVALIDARG},
454 {"CreateReservedResource2, clear value on plain texture",
455 r2(res_tex, D3D12_BARRIER_LAYOUT_COMMON, &cv_rt), E_INVALIDARG},
456 {"CreateReservedResource2, mismatched clear value on RT",
457 r2(res_rt, D3D12_BARRIER_LAYOUT_COMMON, &cv_bad), E_INVALIDARG},
458 {"CreateReservedResource2, valid clear value on RT",
459 r2(res_rt, D3D12_BARRIER_LAYOUT_RENDER_TARGET, &cv_rt), S_OK},
460 {"CreateReservedResource2, non-RT texture in RENDER_TARGET",
461 r2(res_tex, D3D12_BARRIER_LAYOUT_RENDER_TARGET), E_INVALIDARG},
462 {"CreateReservedResource2, non-UAV texture in UNORDERED_ACCESS",
463 r2(res_tex, D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS), E_INVALIDARG},
464 {"CreateReservedResource2, UAV texture in COMPUTE_QUEUE_UAV",
465 r2(res_uav, D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_UNORDERED_ACCESS), S_OK},
466 {"CreateReservedResource2, non-DS texture in DEPTH_STENCIL_WRITE",
467 r2(res_tex, D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE), E_INVALIDARG},
468 {"CreateReservedResource2, DS+DENY_SR in SHADER_RESOURCE",
469 r2(res_ds_deny, D3D12_BARRIER_LAYOUT_SHADER_RESOURCE), E_INVALIDARG},
470 {"CreateReservedResource2, castable format on buffer",
471 r2(res_buf, D3D12_BARRIER_LAYOUT_UNDEFINED, nullptr, 1, srgb_cast), E_INVALIDARG},
472 {"CreateReservedResource2, unknown castable format on texture",
473 r2(res_tex, D3D12_BARRIER_LAYOUT_COMMON, nullptr, 1, unknown_cast), E_INVALIDARG},
474 {"CreateReservedResource2, mismatched texel-size castable format",
475 r2(res_tex, D3D12_BARRIER_LAYOUT_COMMON, nullptr, 1, wide_cast), E_INVALIDARG},
476 {"CreateReservedResource2, valid castable format on texture",
477 r2(res_tex, D3D12_BARRIER_LAYOUT_COMMON, nullptr, 1, srgb_cast), S_OK},
478 {"CreateReservedResource2, castable count with null list",
479 r2(res_tex, D3D12_BARRIER_LAYOUT_COMMON, nullptr, 2, nullptr), S_OK},
263 {"CreateCommandQueue1, null description", null_queue, E_INVALIDARG}, 480 {"CreateCommandQueue1, null description", null_queue, E_INVALIDARG},
264 {"GetCopyableFootprints1, texture with a mip region", footprint(texture_region), S_FALSE}, 481 {"GetCopyableFootprints1, texture with a mip region", footprint(texture_region), S_FALSE},
265 {"GetCopyableFootprints1, buffer with a mip region", footprint(buffer_region), S_OK}, 482 {"GetCopyableFootprints1, buffer with a mip region", footprint(buffer_region), S_OK},
@@ -297,32 +514,47 @@ int main() {
297 EXPECT(create(device.p, via, upload_heap, buffer_desc(256), &out, fake_session()) == E_INVALIDARG); 514 EXPECT(create(device.p, via, upload_heap, buffer_desc(256), &out, fake_session()) == E_INVALIDARG);
298 EXPECT(out == nullptr); 515 EXPECT(out == nullptr);
299 } 516 }
517 {
518 D3D12_RESOURCE_DESC tiled_buf = buffer_desc(65536);
519 void* out = reinterpret_cast<void*>(1);
520 EXPECT(device->CreateReservedResource1(&tiled_buf, D3D12_RESOURCE_STATE_COMMON, nullptr, fake_session(),
521 __uuidof(ID3D12Resource), &out) == E_INVALIDARG);
522 EXPECT(out == nullptr);
523 out = reinterpret_cast<void*>(1);
524 EXPECT(device->CreateReservedResource2(&tiled_buf, D3D12_BARRIER_LAYOUT_UNDEFINED, nullptr, fake_session(),
525 0, nullptr, __uuidof(ID3D12Resource), &out) == E_INVALIDARG);
526 EXPECT(out == nullptr);
527 }
300 528
301 // The newer arguments' edge cases, each with the answer the PC runtime gives (and, when the host has a 529 // The newer arguments' edge cases, each with the answer the PC runtime gives (and, when the host has a
302 // D3D12 device, compared with it live). 530 // D3D12 device, compared with it live). Placed cases use standalone_device so the heap arena is present.
303 const std::vector<Edge> ours = edge_answers(device.p); 531 const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
532 const auto create_host = d3d12 ? reinterpret_cast<PFN_D3D12_CREATE_DEVICE>(
533 reinterpret_cast<void*>(GetProcAddress(d3d12, "D3D12CreateDevice")))
534 : nullptr;
535 Ref<ID3D12Device10> host;
536 const bool have_host =
537 create_host && SUCCEEDED(create_host(nullptr, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)));
538 Ref<ID3D12Device> standalone_base;
539 Ref<ID3D12Device10> standalone_device;
540 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&standalone_base.p))));
541 EXPECT(SUCCEEDED(standalone_base->QueryInterface(IID_PPV_ARGS(&standalone_device.p))));
542 const std::vector<Edge> ours = edge_answers(device.p, standalone_device.p, host.p);
304 for (const Edge& e : ours) { 543 for (const Edge& e : ours) {
305 if (e.got == e.want) continue; 544 if (e.got == e.want) continue;
306 std::fprintf(stderr, "%s: got %08lx, want %08lx\n", e.name, e.got, e.want); 545 std::fprintf(stderr, "%s: got %08lx, want %08lx\n", e.name, e.got, e.want);
307 return 1; 546 return 1;
308 } 547 }
309 { 548 if (have_host) {
310 const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); 549 const std::vector<Edge> theirs = edge_answers(host.p, host.p, host.p);
311 const auto create_host = d3d12 ? reinterpret_cast<PFN_D3D12_CREATE_DEVICE>( 550 for (std::size_t i = 0; i < ours.size(); ++i) {
312 reinterpret_cast<void*>(GetProcAddress(d3d12, "D3D12CreateDevice"))) 551 if (ours[i].got == theirs[i].got) continue;
313 : nullptr; 552 std::fprintf(stderr, "%s: ours %08lx, host runtime %08lx\n", ours[i].name, ours[i].got,
314 Ref<ID3D12Device10> host; 553 theirs[i].got);
315 if (create_host && SUCCEEDED(create_host(nullptr, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) { 554 return 1;
316 const std::vector<Edge> theirs = edge_answers(host.p);
317 for (std::size_t i = 0; i < ours.size(); ++i) {
318 if (ours[i].got == theirs[i].got) continue;
319 std::fprintf(stderr, "%s: ours %08lx, host runtime %08lx\n", ours[i].name, ours[i].got,
320 theirs[i].got);
321 return 1;
322 }
323 } else {
324 std::printf("no host D3D12 device: edge cases checked against their recorded answers only\n");
325 } 555 }
556 } else {
557 std::printf("no host D3D12 device: edge cases checked against their recorded answers only\n");
326 } 558 }
327 559
328 // Castable formats: the layer reports relaxed format casting and passes a real list to 560 // Castable formats: the layer reports relaxed format casting and passes a real list to
@@ -359,7 +591,7 @@ int main() {
359 Ref<ID3D12DescriptorHeap> heap; 591 Ref<ID3D12DescriptorHeap> heap;
360 D3D12_DESCRIPTOR_HEAP_DESC heap_desc{}; 592 D3D12_DESCRIPTOR_HEAP_DESC heap_desc{};
361 heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; 593 heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
362 heap_desc.NumDescriptors = 3; 594 heap_desc.NumDescriptors = 4;
363 heap_desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE; 595 heap_desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
364 EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap.p)))); 596 EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap.p))));
365 D3D12_CPU_DESCRIPTOR_HANDLE slot = heap->GetCPUDescriptorHandleForHeapStart(); 597 D3D12_CPU_DESCRIPTOR_HANDLE slot = heap->GetCPUDescriptorHandleForHeapStart();
@@ -413,6 +645,30 @@ int main() {
413 nonzero = false; 645 nonzero = false;
414 for (std::uint32_t word : words) nonzero = nonzero || word != 0; 646 for (std::uint32_t word : words) nonzero = nonzero || word != 0;
415 EXPECT(nonzero); 647 EXPECT(nonzero);
648
649 // CreateReservedResource2 forwards its castable list to the backing Vulkan image too.
650 const auto slot_is_zero = [](D3D12_CPU_DESCRIPTOR_HANDLE handle) {
651 std::uint32_t descriptor_words[8]{};
652 std::memcpy(descriptor_words, reinterpret_cast<void*>(handle.ptr), sizeof(descriptor_words));
653 for (std::uint32_t word : descriptor_words)
654 if (word != 0) return false;
655 return true;
656 };
657 D3D12_RESOURCE_DESC res_tex = texture_desc(64, 64, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE);
658 res_tex.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
659 Ref<ID3D12Resource> reserved_srgb;
660 EXPECT(SUCCEEDED(device->CreateReservedResource2(&res_tex, D3D12_BARRIER_LAYOUT_COMMON, nullptr, nullptr, 1,
661 srgb_only, IID_PPV_ARGS(&reserved_srgb.p))));
662 slot.ptr += stride;
663 srv.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
664 device->CreateShaderResourceView(reserved_srgb.p, &srv, slot);
665 EXPECT(!slot_is_zero(slot));
666 srv.Format = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;
667 device->CreateShaderResourceView(reserved_srgb.p, &srv, slot);
668 EXPECT(!slot_is_zero(slot));
669 srv.Format = DXGI_FORMAT_R8G8B8A8_UINT;
670 device->CreateShaderResourceView(reserved_srgb.p, &srv, slot);
671 EXPECT(slot_is_zero(slot));
416 } 672 }
417 673
418 // A texture from CreateCommittedResource3 (a castable count with a null list, which is no list) is 674 // A texture from CreateCommittedResource3 (a castable count with a null list, which is no list) is
@@ -523,7 +779,8 @@ int main() {
523 std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); 779 std::fprintf(stderr, "%u validation errors\n", d.validation_errors());
524 return 1; 780 return 1;
525 } 781 }
526 std::printf("D3D12 method variants: CreateCommittedResource1/2/3, CreateCommandQueue1 and GetCopyableFootprints1 " 782 std::printf("D3D12 method variants: CreateCommittedResource1/2/3, CreatePlacedResource2, "
527 "matched their base methods and the PC runtime's edge-case answers; a texture round-tripped\n"); 783 "CreateReservedResource1/2, CreateCommandQueue1 and GetCopyableFootprints1 matched their base methods "
784 "and the PC runtime's edge-case answers; a texture round-tripped\n");
528 return 0; 785 return 0;
529} 786}
diff --git a/runtime/test/d3d12_msaa_draw_test.cpp b/runtime/test/d3d12_msaa_draw_test.cpp
index 9cafc994e..3437fe030 100644
--- a/runtime/test/d3d12_msaa_draw_test.cpp
+++ b/runtime/test/d3d12_msaa_draw_test.cpp
@@ -11,6 +11,7 @@
11// (invalid_subresource) instead of reaching the driver. Shaders: test/glsl/vs_draw.vert, ps_draw.frag. No game data. 11// (invalid_subresource) instead of reaching the driver. Shaders: test/glsl/vs_draw.vert, ps_draw.frag. No game data.
12// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. 12// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation.
13#include "shader_fixture_path.h" 13#include "shader_fixture_path.h"
14#include "test_temp_dir.h"
14#include "vk_test_device.h" 15#include "vk_test_device.h"
15#include "d3d12_test_shaders.h" 16#include "d3d12_test_shaders.h"
16#include "../shims/d3d12_com.h" 17#include "../shims/d3d12_com.h"
@@ -54,10 +55,10 @@ int main() {
54 const auto vs_program = fssm_program({0x56530001, 0xbf810000}); 55 const auto vs_program = fssm_program({0x56530001, 0xbf810000});
55 const auto ps_program = fssm_program({0x50530001, 0xbf810000}); 56 const auto ps_program = fssm_program({0x50530001, 0xbf810000});
56 const auto vs_container = shader_container(vs_program), ps_container = shader_container(ps_program); 57 const auto vs_container = shader_container(vs_program), ps_container = shader_container(ps_program);
57 const auto library = std::filesystem::temp_directory_path() / "leonida_msaa_draw_test"; 58 const testfiles::ScratchDir scratch("leonida_msaa_draw_test");
58 std::filesystem::create_directories(library); 59 const auto& library = scratch.path();
59 std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_VS_SPV), library / "vs_draw.spv", std::filesystem::copy_options::overwrite_existing); 60 EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_VS_SPV), library / "vs_draw.spv"));
60 std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_PS_SPV), library / "ps_draw.spv", std::filesystem::copy_options::overwrite_existing); 61 EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_PS_SPV), library / "ps_draw.spv"));
61 { 62 {
62 std::ofstream index(library / "index.json", std::ios::binary); 63 std::ofstream index(library / "index.json", std::ios::binary);
63 index << "{\"vs_draw\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_program) 64 index << "{\"vs_draw\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_program)
@@ -310,7 +311,6 @@ int main() {
310 fence.reset(); 311 fence.reset();
311 EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); 312 EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1);
312 } 313 }
313 std::filesystem::remove_all(library);
314 314
315 // Pixel centre in clip space; the triangle covers y > x. Sample offsets are under half a pixel on each axis, 315 // Pixel centre in clip space; the triangle covers y > x. Sample offsets are under half a pixel on each axis,
316 // so a pixel whose centre is more than one pixel width (2 / size in clip space, over both axes) from the edge 316 // so a pixel whose centre is more than one pixel width (2 / size in clip space, over both axes) from the edge
diff --git a/runtime/test/d3d12_pipeline_library_test.cpp b/runtime/test/d3d12_pipeline_library_test.cpp
index fbc7bb5fc..08d6a5323 100644
--- a/runtime/test/d3d12_pipeline_library_test.cpp
+++ b/runtime/test/d3d12_pipeline_library_test.cpp
@@ -9,6 +9,7 @@
9// - GPU execution of both loaded compute and loaded graphics PSOs under LEONIDA_VK_VALIDATION=1. 9// - GPU execution of both loaded compute and loaded graphics PSOs under LEONIDA_VK_VALIDATION=1.
10// No game data. 10// No game data.
11#include "shader_fixture_path.h" 11#include "shader_fixture_path.h"
12#include "test_temp_dir.h"
12#include "vk_test_device.h" 13#include "vk_test_device.h"
13#include "d3d12_test_shaders.h" 14#include "d3d12_test_shaders.h"
14#include "../shims/d3d12_com.h" 15#include "../shims/d3d12_com.h"
@@ -68,14 +69,11 @@ int main() {
68 const auto vs_dxbc = shader_container(vs_prog); 69 const auto vs_dxbc = shader_container(vs_prog);
69 const auto ps_dxbc = shader_container(ps_prog); 70 const auto ps_dxbc = shader_container(ps_prog);
70 71
71 const auto lib_dir = std::filesystem::temp_directory_path() / "leonida_pipeline_library_test"; 72 const testfiles::ScratchDir scratch("leonida_pipeline_library_test");
72 std::filesystem::create_directories(lib_dir); 73 const auto& lib_dir = scratch.path();
73 std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), lib_dir / "cs.spv", 74 EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), lib_dir / "cs.spv"));
74 std::filesystem::copy_options::overwrite_existing); 75 EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_VS_SPV), lib_dir / "vs.spv"));
75 std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_VS_SPV), lib_dir / "vs.spv", 76 EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_PS_SPV), lib_dir / "ps.spv"));
76 std::filesystem::copy_options::overwrite_existing);
77 std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_PS_SPV), lib_dir / "ps.spv",
78 std::filesystem::copy_options::overwrite_existing);
79 { 77 {
80 std::ofstream idx(lib_dir / "index.json", std::ios::binary); 78 std::ofstream idx(lib_dir / "index.json", std::ios::binary);
81 idx << "{\"cs\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << leonida::sha256_hex(cs_prog) 79 idx << "{\"cs\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << leonida::sha256_hex(cs_prog)
diff --git a/runtime/test/d3d12_placed_dimensions_test.cpp b/runtime/test/d3d12_placed_dimensions_test.cpp
new file mode 100644
index 000000000..09b0894b4
--- /dev/null
+++ b/runtime/test/d3d12_placed_dimensions_test.cpp
@@ -0,0 +1,347 @@
1// Placed 1D and 3D textures (CreatePlacedResource) on the Vulkan-backed device:
2// - compared with Windows D3D12 on the default adapter and on WARP: the answer for each description in a heap sized
3// for both sides' GetResourceAllocationInfo, at offset 0 and at 64 KiB, and the description a placed resource
4// reads back. A dimension outside the enum is refused alike;
5// - on the layer alone: bytes copied through a buffer into every subresource of a placed 3D texture and a placed 1D
6// array, and back out, come back unchanged.
7// No game data or shaders. LEONIDA_VK_VALIDATION=1 adds VK_LAYER_KHRONOS_validation to the layer's device.
8#include "host_wine.h"
9#include "../shims/d3d12_com.h"
10#include <dxgi1_4.h>
11
12#include <cstdint>
13#include <cstdio>
14#include <cstring>
15#include <vector>
16
17namespace {
18template<class T>
19struct Ref {
20 T* p = nullptr;
21 ~Ref() { reset(); }
22 T* operator->() const { return p; }
23 void reset() {
24 if (p) p->Release();
25 p = nullptr;
26 }
27};
28
29constexpr UINT64 k64 = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT;
30constexpr auto t1 = D3D12_RESOURCE_DIMENSION_TEXTURE1D, t2 = D3D12_RESOURCE_DIMENSION_TEXTURE2D,
31 t3 = D3D12_RESOURCE_DIMENSION_TEXTURE3D;
32
33D3D12_RESOURCE_DESC texture(D3D12_RESOURCE_DIMENSION dimension, UINT64 width, UINT height, UINT16 depth_or_layers,
34 UINT16 mips, DXGI_FORMAT format, D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) {
35 D3D12_RESOURCE_DESC desc{};
36 desc.Dimension = dimension;
37 desc.Width = width;
38 desc.Height = height;
39 desc.DepthOrArraySize = depth_or_layers;
40 desc.MipLevels = mips;
41 desc.Format = format;
42 desc.SampleDesc.Count = 1;
43 desc.Flags = flags;
44 return desc;
45}
46
47D3D12_RESOURCE_DESC buffer(UINT64 bytes) {
48 D3D12_RESOURCE_DESC desc{};
49 desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
50 desc.Width = bytes;
51 desc.Height = desc.DepthOrArraySize = desc.MipLevels = 1;
52 desc.SampleDesc.Count = 1;
53 desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
54 return desc;
55}
56
57UINT64 round_up(UINT64 value, UINT64 alignment) { return (value + alignment - 1) / alignment * alignment; }
58
59// A default heap of `bytes` that takes `desc`'s class of texture on any resource-heap tier.
60HRESULT make_heap(ID3D12Device* device, const D3D12_RESOURCE_DESC& desc, UINT64 bytes, ID3D12Heap** heap) {
61 D3D12_HEAP_DESC heap_desc{};
62 heap_desc.SizeInBytes = bytes;
63 heap_desc.Properties.Type = D3D12_HEAP_TYPE_DEFAULT;
64 heap_desc.Alignment = k64;
65 const bool rt_ds =
66 (desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) != 0;
67 heap_desc.Flags = rt_ds ? D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES : D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES;
68 return device->CreateHeap(&heap_desc, IID_PPV_ARGS(heap));
69}
70
71bool same(const D3D12_RESOURCE_DESC& a, const D3D12_RESOURCE_DESC& b) {
72 return a.Dimension == b.Dimension && a.Alignment == b.Alignment && a.Width == b.Width && a.Height == b.Height &&
73 a.DepthOrArraySize == b.DepthOrArraySize && a.MipLevels == b.MipLevels && a.Format == b.Format &&
74 a.SampleDesc.Count == b.SampleDesc.Count && a.SampleDesc.Quality == b.SampleDesc.Quality &&
75 a.Layout == b.Layout && a.Flags == b.Flags;
76}
77
78struct Case {
79 const char* name;
80 D3D12_RESOURCE_DESC desc;
81};
82
83struct Placed {
84 Ref<ID3D12Heap> heap; // declared first, so the resource is released before its heap
85 Ref<ID3D12Resource> resource;
86 HRESULT hr = E_FAIL;
87};
88
89void place(ID3D12Device* device, const D3D12_RESOURCE_DESC& desc, UINT64 heap_bytes, UINT64 offset, Placed& out) {
90 out.hr = make_heap(device, desc, heap_bytes, &out.heap.p);
91 if (FAILED(out.hr)) {
92 std::fprintf(stderr, "CreateHeap of %llu bytes failed (0x%08lx)\n", static_cast<unsigned long long>(heap_bytes),
93 static_cast<unsigned long>(out.hr));
94 return;
95 }
96 out.hr = device->CreatePlacedResource(out.heap.p, offset, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr,
97 IID_PPV_ARGS(&out.resource.p));
98}
99
100// Every answer and every description read back must be the host's. Returns the number that differ.
101unsigned compare(ID3D12Device* ours, ID3D12Device* host, const char* host_name, const std::vector<Case>& cases,
102 unsigned& compared) {
103 unsigned differ = 0;
104 for (const Case& c : cases) {
105 // The heap is sized for the larger of the two answers: each side checks the room in the heap against its own
106 // size (the layer's is Vulkan's, which can be larger than a host driver's), and what is compared here is
107 // whether a texture of that dimension is placed at all. A description with no size (an invalid dimension)
108 // still gets a heap, to see the refusal.
109 const D3D12_RESOURCE_ALLOCATION_INFO info = host->GetResourceAllocationInfo(0, 1, &c.desc);
110 const D3D12_RESOURCE_ALLOCATION_INFO mine = ours->GetResourceAllocationInfo(0, 1, &c.desc);
111 UINT64 bytes = 1024 * 1024;
112 if (info.SizeInBytes != UINT64_MAX) {
113 bytes = info.SizeInBytes;
114 if (mine.SizeInBytes != UINT64_MAX && mine.SizeInBytes != info.SizeInBytes) {
115 std::printf("%s: %s's size %llu, the layer's %llu; the heap takes the larger\n", c.name, host_name,
116 static_cast<unsigned long long>(info.SizeInBytes),
117 static_cast<unsigned long long>(mine.SizeInBytes));
118 if (mine.SizeInBytes > bytes) bytes = mine.SizeInBytes;
119 }
120 bytes = round_up(bytes, k64);
121 }
122 for (const UINT64 offset : {UINT64(0), k64}) {
123 Placed expected, actual;
124 place(host, c.desc, bytes + offset, offset, expected);
125 place(ours, c.desc, bytes + offset, offset, actual);
126 ++compared;
127 if (expected.hr != actual.hr) {
128 ++differ;
129 std::fprintf(stderr, "%s at %llu: ours 0x%08lx, %s 0x%08lx\n", c.name,
130 static_cast<unsigned long long>(offset), static_cast<unsigned long>(actual.hr), host_name,
131 static_cast<unsigned long>(expected.hr));
132 continue;
133 }
134 if (FAILED(expected.hr)) continue;
135 ++compared;
136 if (!same(actual.resource->GetDesc(), expected.resource->GetDesc())) {
137 ++differ;
138 std::fprintf(stderr, "%s at %llu: GetDesc differs from %s\n", c.name,
139 static_cast<unsigned long long>(offset), host_name);
140 }
141 ++compared;
142 if (actual.resource->GetGPUVirtualAddress() != 0) { // only buffers are addressable
143 ++differ;
144 std::fprintf(stderr, "%s at %llu: a placed texture has a GPU VA\n", c.name,
145 static_cast<unsigned long long>(offset));
146 }
147 }
148 }
149 return differ;
150}
151
152std::uint8_t pattern(UINT subresource, UINT z, UINT y, UINT64 x) {
153 return static_cast<std::uint8_t>(subresource * 61 + z * 29 + y * 7 + x * 3 + 1);
154}
155
156// Writes a pattern into every subresource of a placed texture through an upload buffer, copies it back out to a
157// readback buffer and compares. True when every byte came back.
158bool round_trip(ID3D12Device* device, ID3D12CommandQueue* queue, ID3D12Fence* fence, UINT64& fence_value,
159 const char* name, const D3D12_RESOURCE_DESC& desc) {
160 const D3D12_RESOURCE_ALLOCATION_INFO info = device->GetResourceAllocationInfo(0, 1, &desc);
161 if (info.SizeInBytes == UINT64_MAX) {
162 std::fprintf(stderr, "%s: no allocation size\n", name);
163 return false;
164 }
165 Ref<ID3D12Heap> heap;
166 Ref<ID3D12Resource> placed;
167 if (FAILED(make_heap(device, desc, round_up(info.SizeInBytes, k64), &heap.p)) ||
168 FAILED(device->CreatePlacedResource(heap.p, 0, &desc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
169 IID_PPV_ARGS(&placed.p)))) {
170 std::fprintf(stderr, "%s: not placed\n", name);
171 return false;
172 }
173 const UINT layers = desc.Dimension == t3 ? 1u : desc.DepthOrArraySize;
174 const UINT count = desc.MipLevels * layers;
175 std::vector<D3D12_PLACED_SUBRESOURCE_FOOTPRINT> layouts(count);
176 std::vector<UINT> rows(count);
177 std::vector<UINT64> row_bytes(count);
178 UINT64 total = 0;
179 device->GetCopyableFootprints(&desc, 0, count, 0, layouts.data(), rows.data(), row_bytes.data(), &total);
180
181 D3D12_HEAP_PROPERTIES upload_heap{}, readback_heap{};
182 upload_heap.Type = D3D12_HEAP_TYPE_UPLOAD;
183 readback_heap.Type = D3D12_HEAP_TYPE_READBACK;
184 const D3D12_RESOURCE_DESC staging = buffer(total);
185 Ref<ID3D12Resource> upload, readback;
186 if (FAILED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &staging,
187 D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&upload.p))) ||
188 FAILED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &staging,
189 D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&readback.p)))) {
190 std::fprintf(stderr, "%s: no staging buffers\n", name);
191 return false;
192 }
193 // Where row y of slice z of subresource s starts in either staging buffer.
194 const auto row_at = [&](UINT s, UINT z, UINT y) {
195 const UINT64 pitch = layouts[s].Footprint.RowPitch;
196 return layouts[s].Offset + (UINT64(z) * rows[s] + y) * pitch;
197 };
198 void* mapped = nullptr;
199 if (FAILED(upload->Map(0, nullptr, &mapped))) return false;
200 for (UINT s = 0; s < count; ++s)
201 for (UINT z = 0; z < layouts[s].Footprint.Depth; ++z)
202 for (UINT y = 0; y < rows[s]; ++y) {
203 auto* row = static_cast<std::uint8_t*>(mapped) + row_at(s, z, y);
204 for (UINT64 x = 0; x < row_bytes[s]; ++x) row[x] = pattern(s, z, y, x);
205 }
206 upload->Unmap(0, nullptr);
207
208 Ref<ID3D12CommandAllocator> allocator;
209 Ref<ID3D12GraphicsCommandList> list;
210 if (FAILED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p))) ||
211 FAILED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr,
212 IID_PPV_ARGS(&list.p))))
213 return false;
214 for (UINT s = 0; s < count; ++s) {
215 D3D12_TEXTURE_COPY_LOCATION dst{placed.p, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}};
216 dst.SubresourceIndex = s;
217 D3D12_TEXTURE_COPY_LOCATION src{upload.p, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}};
218 src.PlacedFootprint = layouts[s];
219 list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
220 }
221 D3D12_RESOURCE_BARRIER barrier{};
222 barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
223 barrier.Transition = {placed.p, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_COPY_DEST,
224 D3D12_RESOURCE_STATE_COPY_SOURCE};
225 list->ResourceBarrier(1, &barrier);
226 for (UINT s = 0; s < count; ++s) {
227 D3D12_TEXTURE_COPY_LOCATION dst{readback.p, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}};
228 dst.PlacedFootprint = layouts[s];
229 D3D12_TEXTURE_COPY_LOCATION src{placed.p, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}};
230 src.SubresourceIndex = s;
231 list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
232 }
233 if (FAILED(list->Close())) return false;
234 ID3D12CommandList* lists[] = {list.p};
235 queue->ExecuteCommandLists(1, lists);
236 ++fence_value;
237 if (FAILED(queue->Signal(fence, fence_value)) || FAILED(fence->SetEventOnCompletion(fence_value, nullptr))) {
238 std::fprintf(stderr, "%s: the copies did not finish\n", name);
239 return false;
240 }
241
242 if (FAILED(readback->Map(0, nullptr, &mapped))) return false;
243 UINT64 wrong = 0, checked = 0;
244 for (UINT s = 0; s < count; ++s)
245 for (UINT z = 0; z < layouts[s].Footprint.Depth; ++z)
246 for (UINT y = 0; y < rows[s]; ++y) {
247 const auto* row = static_cast<const std::uint8_t*>(mapped) + row_at(s, z, y);
248 for (UINT64 x = 0; x < row_bytes[s]; ++x, ++checked) {
249 if (row[x] == pattern(s, z, y, x)) continue;
250 if (!wrong++)
251 std::fprintf(stderr, "%s: subresource %u slice %u row %u byte %llu reads 0x%02x, want 0x%02x\n",
252 name, s, z, y, static_cast<unsigned long long>(x), row[x], pattern(s, z, y, x));
253 }
254 }
255 readback->Unmap(0, nullptr);
256 if (wrong) {
257 std::fprintf(stderr, "%s: %llu of %llu bytes differ\n", name, static_cast<unsigned long long>(wrong),
258 static_cast<unsigned long long>(checked));
259 return false;
260 }
261 std::printf("%s: %u subresources, %llu bytes round-tripped\n", name, count,
262 static_cast<unsigned long long>(checked));
263 return true;
264}
265} // namespace
266
267int main() {
268 Ref<ID3D12Device> ours;
269 if (FAILED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&ours.p))) || !ours.p) {
270 std::printf("SKIP: no Vulkan device\n");
271 return 77;
272 }
273 unsigned failures = 0;
274
275 {
276 D3D12_COMMAND_QUEUE_DESC queue_desc{};
277 queue_desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
278 Ref<ID3D12CommandQueue> queue;
279 Ref<ID3D12Fence> fence;
280 if (FAILED(ours->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p))) ||
281 FAILED(ours->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))) {
282 std::fprintf(stderr, "no command queue or fence\n");
283 return 1;
284 }
285 UINT64 fence_value = 0;
286 const Case trips[] = {
287 {"placed 3D R8G8B8A8_UNORM 8x8x4, 2 mips", texture(t3, 8, 8, 4, 2, DXGI_FORMAT_R8G8B8A8_UNORM)},
288 {"placed 3D R16G16B16A16_FLOAT 4x4x4", texture(t3, 4, 4, 4, 1, DXGI_FORMAT_R16G16B16A16_FLOAT)},
289 {"placed 1D array R8G8B8A8_UNORM 64 x3, 3 mips", texture(t1, 64, 1, 3, 3, DXGI_FORMAT_R8G8B8A8_UNORM)},
290 };
291 for (const Case& c : trips)
292 if (!round_trip(ours.p, queue.p, fence.p, fence_value, c.name, c.desc)) ++failures;
293 }
294
295 // A desc with a dimension outside the enum, which the host refuses.
296 D3D12_RESOURCE_DESC unknown = texture(t2, 64, 64, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM);
297 unknown.Dimension = D3D12_RESOURCE_DIMENSION_UNKNOWN;
298 D3D12_RESOURCE_DESC past_3d = unknown;
299 past_3d.Dimension = D3D12_RESOURCE_DIMENSION(5);
300 constexpr auto rgba8 = DXGI_FORMAT_R8G8B8A8_UNORM;
301 constexpr auto uav = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, target = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
302 const std::vector<Case> cases = {
303 {"1D 4096", texture(t1, 4096, 1, 1, 1, rgba8)},
304 {"1D 256, all mips", texture(t1, 256, 1, 1, 0, rgba8)},
305 {"1D array of 8, 13 mips", texture(t1, 4096, 1, 8, 13, rgba8)},
306 {"1D R32_FLOAT unordered access", texture(t1, 1024, 1, 1, 1, DXGI_FORMAT_R32_FLOAT, uav)},
307 {"1D render target", texture(t1, 1024, 1, 1, 1, rgba8, target)},
308 {"3D 64x64x64", texture(t3, 64, 64, 64, 1, rgba8)},
309 {"3D 32x32x32, all mips", texture(t3, 32, 32, 32, 0, rgba8)},
310 {"3D 64x16x4, all mips", texture(t3, 64, 16, 4, 0, rgba8)},
311 {"3D BC1 128x128x16", texture(t3, 128, 128, 16, 1, DXGI_FORMAT_BC1_UNORM)},
312 {"3D R16G16B16A16_FLOAT 32x32x32", texture(t3, 32, 32, 32, 1, DXGI_FORMAT_R16G16B16A16_FLOAT)},
313 {"3D R32_FLOAT unordered access", texture(t3, 64, 64, 64, 1, DXGI_FORMAT_R32_FLOAT, uav)},
314 {"3D render target", texture(t3, 64, 64, 64, 1, rgba8, target)},
315 {"2D 64x64 (control)", texture(t2, 64, 64, 1, 1, rgba8)},
316 {"dimension UNKNOWN", unknown},
317 {"dimension 5", past_3d},
318 };
319
320 if (hostwine::host_is_wine()) {
321 std::printf("placed dimensions: the host comparison is skipped under Wine\n");
322 return failures ? 1 : 0;
323 }
324 Ref<IDXGIFactory4> factory;
325 if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p)))) {
326 std::fprintf(stderr, "no DXGI factory\n");
327 return 1;
328 }
329 unsigned references = 0;
330 for (const bool warp : {false, true}) {
331 Ref<IDXGIAdapter> adapter;
332 Ref<ID3D12Device> host;
333 if (warp && FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter.p)))) continue;
334 if (FAILED(D3D12CreateDevice(adapter.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) continue;
335 const char* name = warp ? "WARP" : "the default adapter";
336 unsigned compared = 0;
337 const unsigned differ = compare(ours.p, host.p, name, cases, compared);
338 std::printf("placed dimensions against %s: %u answers compared, %u differ\n", name, compared, differ);
339 failures += differ;
340 ++references;
341 }
342 if (!references) {
343 std::fprintf(stderr, "no D3D12 reference device (default adapter or WARP)\n");
344 return 1;
345 }
346 return failures ? 1 : 0;
347}
diff --git a/runtime/test/d3d12_present_test.cpp b/runtime/test/d3d12_present_test.cpp
index 520af0e98..9e638ae09 100644
--- a/runtime/test/d3d12_present_test.cpp
+++ b/runtime/test/d3d12_present_test.cpp
@@ -3,9 +3,9 @@
3// moves the back buffer PRESENT -> RENDER_TARGET, clears it, moves it back, executes, presents and signals a fence. 3// moves the back buffer PRESENT -> RENDER_TARGET, clears it, moves it back, executes, presents and signals a fence.
4// The window is then resized, which recreates the swapchain and scales the blit. The presented images are copied 4// The window is then resized, which recreates the swapchain and scales the blit. The presented images are copied
5// back (the presenter's capture) and must hold the clear colour at the swapchain's size. Last, the colour on screen 5// back (the presenter's capture) and must hold the clear colour at the swapchain's size. Last, the colour on screen
6// is read back with GDI on native Windows when the window is in front, the display is in SDR and GDI can read the 6// is read back with GDI on native Windows when the window is in front with no other window over its centre, the
7// screen. Under Wine, rootless XWayland can return black for desktop reads, so the swapchain checks confirm the 7// display is in SDR and GDI can read the screen. Under Wine, rootless XWayland can return black for desktop reads,
8// colour there. No shaders or game data. 8// so the swapchain checks confirm the colour there. No shaders or game data.
9// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation; any validation error fails the test. 9// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation; any validation error fails the test.
10#include "vk_test_device.h" 10#include "vk_test_device.h"
11#include "../shims/d3d12_com.h" 11#include "../shims/d3d12_com.h"
@@ -90,6 +90,17 @@ bool has_interactive_window_station() {
90 return (flags.dwFlags & WSF_VISIBLE) != 0; 90 return (flags.dwFlags & WSF_VISIBLE) != 0;
91} 91}
92 92
93// True when the window manager reports this window as the top-level window at a screen point. Being the foreground
94// window does not make it so: an always-on-top window, or one another process showed without taking the foreground,
95// can lie over it, and a GDI read of the screen then returns that window's pixel. WindowFromPoint passes over hidden
96// and disabled windows and over windows that are transparent to hit testing (a click-through overlay,
97// WS_EX_LAYERED | WS_EX_TRANSPARENT), so an overlay of that kind drawn over the point is not noticed, and neither
98// is anything the compositor draws there itself.
99bool is_top_window_at(HWND window, POINT screen_point) {
100 const HWND hit = WindowFromPoint(screen_point);
101 return hit && GetAncestor(hit, GA_ROOT) == window;
102}
103
93void set_client_size(HWND window, int width, int height) { 104void set_client_size(HWND window, int width, int height) {
94 RECT rect{0, 0, width, height}; 105 RECT rect{0, 0, width, height};
95 AdjustWindowRect(&rect, WS_OVERLAPPEDWINDOW, FALSE); 106 AdjustWindowRect(&rect, WS_OVERLAPPEDWINDOW, FALSE);
@@ -478,16 +489,44 @@ int main() {
478 GetClientRect(window, &client); 489 GetClientRect(window, &client);
479 POINT centre{(client.right - client.left) / 2, (client.bottom - client.top) / 2}; 490 POINT centre{(client.right - client.left) / 2, (client.bottom - client.top) / 2};
480 ClientToScreen(window, &centre); 491 ClientToScreen(window, &centre);
481 HDC screen = GetDC(nullptr); 492 const auto is_clear_colour = [](COLORREF c) {
482 const COLORREF pixel = GetPixel(screen, centre.x, centre.y); 493 return std::abs(GetRValue(c) - 51) <= 3 && std::abs(GetGValue(c) - 153) <= 3 &&
483 ReleaseDC(nullptr, screen); 494 std::abs(GetBValue(c) - 230) <= 3;
484 if (pixel == CLR_INVALID) { 495 };
496 // The foreground window can still be covered at its centre, so a read counts only when this window
497 // was the top one there both before and after it. How long the compositor takes to show the last
498 // frame, or to stop showing a window that has just gone, is not known (the 200 ms above is a guess),
499 // so a pixel that is not the clear colour is read again for up to a second. Nothing is presented
500 // meanwhile: a late frame passes, a wrong colour that stays fails.
501 COLORREF pixel = CLR_INVALID, first_pixel = CLR_INVALID;
502 bool covered = false;
503 int reads = 0;
504 for (;;) {
505 covered = !is_top_window_at(window, centre);
506 if (covered) break;
507 HDC screen = GetDC(nullptr);
508 pixel = GetPixel(screen, centre.x, centre.y);
509 ReleaseDC(nullptr, screen);
510 covered = !is_top_window_at(window, centre);
511 if (covered) break;
512 if (++reads == 1) first_pixel = pixel;
513 if (pixel == CLR_INVALID || is_clear_colour(pixel) || reads > 20) break;
514 Sleep(50);
515 pump();
516 }
517 if (covered) {
518 std::printf("another window covers the window centre: on-screen colour check skipped, the "
519 "colour was checked in the presented images\n");
520 } else if (pixel == CLR_INVALID) {
485 std::printf("GDI cannot read the screen here (GetPixel on the screen DC returns CLR_INVALID): " 521 std::printf("GDI cannot read the screen here (GetPixel on the screen DC returns CLR_INVALID): "
486 "on-screen colour check skipped, the colour was checked in the presented images\n"); 522 "on-screen colour check skipped, the colour was checked in the presented images\n");
487 } else { 523 } else {
488 const int r = GetRValue(pixel), g = GetGValue(pixel), b = GetBValue(pixel); 524 const int r = GetRValue(pixel), g = GetGValue(pixel), b = GetBValue(pixel);
489 std::printf("screen pixel at the window centre: %d,%d,%d (cleared to 51,153,230)\n", r, g, b); 525 std::printf("screen pixel at the window centre: %d,%d,%d (cleared to 51,153,230)\n", r, g, b);
490 EXPECT(std::abs(r - 51) <= 3 && std::abs(g - 153) <= 3 && std::abs(b - 230) <= 3); 526 if (reads > 1)
527 std::printf("read %d times, 50 ms apart; the first read was %d,%d,%d\n", reads,
528 GetRValue(first_pixel), GetGValue(first_pixel), GetBValue(first_pixel));
529 EXPECT(is_clear_colour(pixel));
491 screen_checked = true; 530 screen_checked = true;
492 } 531 }
493 } 532 }
diff --git a/runtime/test/d3d12_residency_test.cpp b/runtime/test/d3d12_residency_test.cpp
new file mode 100644
index 000000000..d0f90d5fc
--- /dev/null
+++ b/runtime/test/d3d12_residency_test.cpp
@@ -0,0 +1,421 @@
1// Residency on the Vulkan-backed device, compared with the host PC runtime: MakeResident, Evict,
2// SetResidencyPriority (ID3D12Device1) and EnqueueMakeResident (ID3D12Device3). The same script runs on both devices
3// with pageable objects of each (a committed buffer, a heap, a placed buffer, a descriptor heap, a query heap and a
4// fence): counts of 0, null arrays, null entries, the same object twice, evicting twice, every named priority and a
5// few others, residency flags, a null fence, and the fence values EnqueueMakeResident signals (the value the fence
6// reaches is recorded too). Every HRESULT is recorded and the two records must be the same, step by step. A step the
7// host runtime faults on is reported and not compared. No shaders or game data. Skips (77) without a Vulkan GPU;
8// without a host D3D12 device only the layer's own record is printed. Set LEONIDA_D3D49_VERBOSE=1 to print every
9// step.
10#include "vk_test_device.h"
11#include "../shims/d3d12_com.h"
12
13#include <cstdint>
14#include <cstdio>
15#include <cstdlib>
16#include <cstring>
17#include <string>
18#include <vector>
19
20#define EXPECT(condition) do { \
21 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
22} while (0)
23
24namespace {
25
26template<class T>
27struct Ref {
28 T* p = nullptr;
29 ~Ref() { reset(); }
30 void reset() {
31 if (p) p->Release();
32 p = nullptr;
33 }
34 T* operator->() const { return p; }
35};
36
37constexpr std::uint64_t kFaulted = 0xFA017EDull; // the call raised an exception
38
39struct Objects {
40 ID3D12Device1* device1 = nullptr;
41 ID3D12Device3* device3 = nullptr;
42 ID3D12Device* device = nullptr;
43 ID3D12Pageable* all[6] = {}; // buffer, heap, placed, descriptor heap, query heap, fence
44 ID3D12Fence* fence = nullptr;
45};
46
47using Call = HRESULT (*)(Objects&);
48
49HRESULT guarded(Call call, Objects* o) {
50 __try {
51 return call(*o);
52 } __except (EXCEPTION_EXECUTE_HANDLER) {
53 return HRESULT(kFaulted);
54 }
55}
56
57HRESULT priority(Objects& o, std::uint32_t value) {
58 const auto p = D3D12_RESIDENCY_PRIORITY(value);
59 return o.device1->SetResidencyPriority(1, o.all, &p);
60}
61
62HRESULT priority1(Objects& o, int which) {
63 const D3D12_RESIDENCY_PRIORITY p = D3D12_RESIDENCY_PRIORITY_NORMAL;
64 return o.device1->SetResidencyPriority(1, o.all + which, &p);
65}
66
67struct Step {
68 const char* name;
69 Call call;
70 UINT64 fence_value = 0; // EnqueueMakeResident: also record the value the fence reaches (waits for this one)
71 bool isolated = false; // on the host, run in a process of its own (see below)
72};
73
74const Step kSteps[] = {
75 {"MakeResident 0, null", [](Objects& o) { return o.device->MakeResident(0, nullptr); }},
76 {"MakeResident all six", [](Objects& o) { return o.device->MakeResident(6, o.all); }},
77 {"MakeResident 0 with an array", [](Objects& o) { return o.device->MakeResident(0, o.all); }},
78 {"MakeResident the buffer twice", [](Objects& o) {
79 ID3D12Pageable* twice[] = {o.all[0], o.all[0]};
80 return o.device->MakeResident(2, twice);
81 }},
82 {"MakeResident a resident buffer", [](Objects& o) { return o.device->MakeResident(1, o.all); }},
83 {"Evict 0, null", [](Objects& o) { return o.device->Evict(0, nullptr); }},
84 {"Evict 0 with an array", [](Objects& o) { return o.device->Evict(0, o.all); }},
85 {"Evict the buffer", [](Objects& o) { return o.device->Evict(1, o.all); }},
86 {"Evict the buffer again", [](Objects& o) { return o.device->Evict(1, o.all); }},
87 {"MakeResident the evicted buffer", [](Objects& o) { return o.device->MakeResident(1, o.all); }},
88 {"Evict all six", [](Objects& o) { return o.device->Evict(6, o.all); }},
89 {"MakeResident all six after Evict", [](Objects& o) { return o.device->MakeResident(6, o.all); }},
90 {"Evict the heap and the placed buffer", [](Objects& o) { return o.device->Evict(2, o.all + 1); }},
91 {"MakeResident the placed buffer alone", [](Objects& o) { return o.device->MakeResident(1, o.all + 2); }},
92 {"MakeResident the heap", [](Objects& o) { return o.device->MakeResident(1, o.all + 1); }},
93
94 {"SetResidencyPriority 0, null, null", [](Objects& o) { return o.device1->SetResidencyPriority(0, nullptr, nullptr); }},
95 {"SetResidencyPriority 0 with arrays", [](Objects& o) {
96 const D3D12_RESIDENCY_PRIORITY p = D3D12_RESIDENCY_PRIORITY_NORMAL;
97 return o.device1->SetResidencyPriority(0, o.all, &p);
98 }},
99 {"SetResidencyPriority the buffer", [](Objects& o) { return priority1(o, 0); }},
100 {"SetResidencyPriority the heap", [](Objects& o) { return priority1(o, 1); }},
101 {"SetResidencyPriority MINIMUM", [](Objects& o) { return priority(o, std::uint32_t(D3D12_RESIDENCY_PRIORITY_MINIMUM)); }},
102 {"SetResidencyPriority LOW", [](Objects& o) { return priority(o, std::uint32_t(D3D12_RESIDENCY_PRIORITY_LOW)); }},
103 {"SetResidencyPriority HIGH", [](Objects& o) { return priority(o, std::uint32_t(D3D12_RESIDENCY_PRIORITY_HIGH)); }},
104 {"SetResidencyPriority MAXIMUM", [](Objects& o) { return priority(o, std::uint32_t(D3D12_RESIDENCY_PRIORITY_MAXIMUM)); }},
105 {"SetResidencyPriority 0", [](Objects& o) { return priority(o, 0); }},
106 {"SetResidencyPriority 1", [](Objects& o) { return priority(o, 1); }},
107 {"SetResidencyPriority NORMAL + 0x1234", [](Objects& o) { return priority(o, std::uint32_t(D3D12_RESIDENCY_PRIORITY_NORMAL) + 0x1234); }},
108 {"SetResidencyPriority 0x12345678", [](Objects& o) { return priority(o, 0x12345678u); }},
109 {"SetResidencyPriority 0x9fffffff", [](Objects& o) { return priority(o, 0x9fffffffu); }},
110 {"SetResidencyPriority 0xc8000000", [](Objects& o) { return priority(o, 0xc8000000u); }},
111 {"SetResidencyPriority 0xffffffff", [](Objects& o) { return priority(o, 0xffffffffu); }},
112 {"SetResidencyPriority an evicted object", [](Objects& o) {
113 o.device->Evict(1, o.all);
114 const HRESULT hr = priority(o, std::uint32_t(D3D12_RESIDENCY_PRIORITY_HIGH));
115 o.device->MakeResident(1, o.all);
116 return hr;
117 }},
118
119 {"EnqueueMakeResident NONE, two objects, value 7", [](Objects& o) {
120 return o.device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, 2, o.all, o.fence, 7);
121 }, 7},
122 {"EnqueueMakeResident DENY_OVERBUDGET, 0, null, value 9", [](Objects& o) {
123 return o.device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_DENY_OVERBUDGET, 0, nullptr, o.fence, 9);
124 }, 9},
125 {"EnqueueMakeResident all six, value 10", [](Objects& o) {
126 return o.device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, 6, o.all, o.fence, 10);
127 }, 10},
128 {"EnqueueMakeResident a null fence", [](Objects& o) {
129 return o.device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, 1, o.all, nullptr, 11);
130 }},
131 {"EnqueueMakeResident flags 0x2", [](Objects& o) {
132 return o.device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAGS(0x2), 1, o.all, o.fence, 11);
133 }},
134 {"EnqueueMakeResident flags 0xffffffff", [](Objects& o) {
135 return o.device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAGS(0xffffffffu), 1, o.all, o.fence, 11);
136 }},
137 {"EnqueueMakeResident 0 with an array, value 12", [](Objects& o) {
138 return o.device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, 0, o.all, o.fence, 12);
139 }, 12},
140 {"EnqueueMakeResident an evicted buffer, value 13", [](Objects& o) {
141 o.device->Evict(1, o.all);
142 return o.device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, 1, o.all, o.fence, 13);
143 }, 13},
144 {"EnqueueMakeResident the buffer twice, value 14", [](Objects& o) {
145 ID3D12Pageable* twice[] = {o.all[0], o.all[0]};
146 return o.device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, 2, twice, o.fence, 14);
147 }, 14},
148 {"EnqueueMakeResident the fence it signals, value 15", [](Objects& o) {
149 return o.device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, 1, o.all + 5, o.fence, 15);
150 }, 15},
151 {"EnqueueMakeResident a value below the fence's [backwards], value 3", [](Objects& o) {
152 return o.device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, 1, o.all, o.fence, 3);
153 }, 3},
154 {"EnqueueMakeResident the same value again [backwards], value 3", [](Objects& o) {
155 return o.device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, 1, o.all, o.fence, 3);
156 }, 3},
157
158 // Steps after which the host runtime isn't usable any more. On the host each runs in a process of its own with a
159 // fresh device (--host-step): SetResidencyPriority on anything but a committed resource or a heap (the host
160 // answers E_INVALIDARG and removes its device, DXGI_ERROR_INVALID_CALL), and a count with a null array or a null
161 // entry in an array (the host dereferences them).
162 {"SetResidencyPriority the placed buffer", [](Objects& o) { return priority1(o, 2); }, 0, true},
163 {"SetResidencyPriority the descriptor heap", [](Objects& o) { return priority1(o, 3); }, 0, true},
164 {"SetResidencyPriority the query heap", [](Objects& o) { return priority1(o, 4); }, 0, true},
165 {"SetResidencyPriority the fence", [](Objects& o) { return priority1(o, 5); }, 0, true},
166 {"SetResidencyPriority all six NORMAL", [](Objects& o) {
167 const D3D12_RESIDENCY_PRIORITY p[6] = {D3D12_RESIDENCY_PRIORITY_NORMAL, D3D12_RESIDENCY_PRIORITY_NORMAL,
168 D3D12_RESIDENCY_PRIORITY_NORMAL, D3D12_RESIDENCY_PRIORITY_NORMAL,
169 D3D12_RESIDENCY_PRIORITY_NORMAL, D3D12_RESIDENCY_PRIORITY_NORMAL};
170 return o.device1->SetResidencyPriority(6, o.all, p);
171 }, 0, true},
172 {"SetResidencyPriority the buffer and the placed buffer", [](Objects& o) {
173 ID3D12Pageable* two[] = {o.all[0], o.all[2]};
174 const D3D12_RESIDENCY_PRIORITY p[2] = {D3D12_RESIDENCY_PRIORITY_NORMAL, D3D12_RESIDENCY_PRIORITY_NORMAL};
175 return o.device1->SetResidencyPriority(2, two, p);
176 }, 0, true},
177 {"MakeResident 1, null", [](Objects& o) { return o.device->MakeResident(1, nullptr); }, 0, true},
178 {"Evict 1, null", [](Objects& o) { return o.device->Evict(1, nullptr); }, 0, true},
179 {"SetResidencyPriority 1, objects, null", [](Objects& o) {
180 return o.device1->SetResidencyPriority(1, o.all, nullptr);
181 }, 0, true},
182 {"SetResidencyPriority 1, null, priorities", [](Objects& o) {
183 const D3D12_RESIDENCY_PRIORITY p = D3D12_RESIDENCY_PRIORITY_NORMAL;
184 return o.device1->SetResidencyPriority(1, nullptr, &p);
185 }, 0, true},
186 {"EnqueueMakeResident 1, null objects", [](Objects& o) {
187 return o.device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, 1, nullptr, o.fence, 11);
188 }, 0, true},
189 {"MakeResident 1, [null]", [](Objects& o) {
190 ID3D12Pageable* none[] = {nullptr};
191 return o.device->MakeResident(1, none);
192 }, 0, true},
193 {"Evict 1, [null]", [](Objects& o) {
194 ID3D12Pageable* none[] = {nullptr};
195 return o.device->Evict(1, none);
196 }, 0, true},
197 {"SetResidencyPriority 1, [null]", [](Objects& o) {
198 ID3D12Pageable* none[] = {nullptr};
199 const D3D12_RESIDENCY_PRIORITY p = D3D12_RESIDENCY_PRIORITY_NORMAL;
200 return o.device1->SetResidencyPriority(1, none, &p);
201 }, 0, true},
202 {"EnqueueMakeResident 1, [null]", [](Objects& o) {
203 ID3D12Pageable* none[] = {nullptr};
204 return o.device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, 1, none, o.fence, 20);
205 }, 0, true},
206};
207
208struct Record {
209 std::vector<std::string> names;
210 std::vector<std::uint64_t> values;
211 void add(const std::string& name, std::uint64_t value) {
212 names.push_back(name);
213 values.push_back(value);
214 }
215};
216
217// The value `fence` settles at after an EnqueueMakeResident that asked for `want`: the host signals it from a
218// paging queue, so wait (up to 2 s) for it to reach `want`, or, for a value below the current one, to change.
219UINT64 settled(ID3D12Fence* fence, UINT64 before, UINT64 want) {
220 for (int i = 0; i < 200; ++i) {
221 const UINT64 now = fence->GetCompletedValue();
222 if (now == want || (want < before && now != before)) return now;
223 Sleep(10);
224 }
225 return fence->GetCompletedValue();
226}
227
228// The pageable objects of one device, and the references that keep them alive.
229struct Holder {
230 Ref<ID3D12Device1> device1;
231 Ref<ID3D12Device3> device3;
232 Ref<ID3D12Resource> buffer, placed;
233 Ref<ID3D12Heap> heap;
234 Ref<ID3D12DescriptorHeap> descriptors;
235 Ref<ID3D12QueryHeap> queries;
236 Ref<ID3D12Fence> fence;
237 Objects o;
238};
239
240bool make(ID3D12Device* device, Holder& h) {
241 h.o.device = device;
242 if (FAILED(device->QueryInterface(IID_PPV_ARGS(&h.device1.p))) ||
243 FAILED(device->QueryInterface(IID_PPV_ARGS(&h.device3.p))))
244 return false;
245 h.o.device1 = h.device1.p;
246 h.o.device3 = h.device3.p;
247 const D3D12_HEAP_PROPERTIES gpu{D3D12_HEAP_TYPE_DEFAULT};
248 D3D12_RESOURCE_DESC desc{};
249 desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
250 desc.Width = 64 * 1024;
251 desc.Height = 1;
252 desc.DepthOrArraySize = 1;
253 desc.MipLevels = 1;
254 desc.SampleDesc.Count = 1;
255 desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
256 D3D12_HEAP_DESC heap_desc{};
257 heap_desc.SizeInBytes = 64 * 1024;
258 heap_desc.Properties = gpu;
259 heap_desc.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS;
260 const D3D12_DESCRIPTOR_HEAP_DESC dh{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 16,
261 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0};
262 const D3D12_QUERY_HEAP_DESC qh{D3D12_QUERY_HEAP_TYPE_TIMESTAMP, 4, 0};
263 if (FAILED(device->CreateCommittedResource(&gpu, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr,
264 IID_PPV_ARGS(&h.buffer.p))) ||
265 FAILED(device->CreateHeap(&heap_desc, IID_PPV_ARGS(&h.heap.p))) ||
266 FAILED(device->CreatePlacedResource(h.heap.p, 0, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr,
267 IID_PPV_ARGS(&h.placed.p))) ||
268 FAILED(device->CreateDescriptorHeap(&dh, IID_PPV_ARGS(&h.descriptors.p))) ||
269 FAILED(device->CreateQueryHeap(&qh, IID_PPV_ARGS(&h.queries.p))) ||
270 FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&h.fence.p))))
271 return false;
272 h.o.all[0] = h.buffer.p;
273 h.o.all[1] = h.heap.p;
274 h.o.all[2] = h.placed.p;
275 h.o.all[3] = h.descriptors.p;
276 h.o.all[4] = h.queries.p;
277 h.o.all[5] = h.fence.p;
278 h.o.fence = h.fence.p;
279 return true;
280}
281
282ID3D12Device* create_host() {
283 const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
284 const auto create = d3d12 ? reinterpret_cast<PFN_D3D12_CREATE_DEVICE>(
285 reinterpret_cast<void*>(GetProcAddress(d3d12, "D3D12CreateDevice")))
286 : nullptr;
287 ID3D12Device* host = nullptr;
288 if (!create || FAILED(create(nullptr, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host)))) return nullptr;
289 return host;
290}
291
292constexpr std::uint64_t kNoChild = 0xC41DFA11ull; // the child process couldn't run the step
293constexpr int kMaxNotCompared = 11; // values the host can't give: see the end of main
294
295// Step `index` on a fresh host device, in a child process (this executable with --host-step): its exit code is the
296// HRESULT, or a crash status, which counts as a fault.
297std::uint64_t isolated(std::size_t index) {
298 wchar_t exe[MAX_PATH] = {};
299 GetModuleFileNameW(nullptr, exe, MAX_PATH);
300 std::wstring command = L"\"" + std::wstring(exe) + L"\" --host-step " + std::to_wstring(index);
301 STARTUPINFOW startup{};
302 startup.cb = sizeof(startup);
303 PROCESS_INFORMATION process{};
304 if (!CreateProcessW(nullptr, command.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW, nullptr, nullptr,
305 &startup, &process))
306 return kNoChild;
307 DWORD code = DWORD(kNoChild);
308 if (WaitForSingleObject(process.hProcess, 60000) == WAIT_OBJECT_0) GetExitCodeProcess(process.hProcess, &code);
309 else TerminateProcess(process.hProcess, DWORD(kNoChild));
310 CloseHandle(process.hThread);
311 CloseHandle(process.hProcess);
312 // Checked before the crash statuses below, which kNoChild would otherwise fall into: a child that couldn't run
313 // its step is a broken test, not a host fault, and fails it.
314 if (code == DWORD(kNoChild)) return kNoChild;
315 if ((code & 0xF0000000u) == 0xC0000000u) return kFaulted; // an access violation or fail-fast the guard missed
316 return code;
317}
318
319// Runs the script on `device` and records it. `host`: run the isolated steps in child processes.
320bool run(ID3D12Device* device, bool host, Record& out) {
321 Holder h;
322 if (!make(device, h)) return false;
323 for (std::size_t i = 0; i < sizeof(kSteps) / sizeof(kSteps[0]); ++i) {
324 const Step& s = kSteps[i];
325 if (s.isolated) {
326 out.add(s.name, host ? isolated(i) : std::uint64_t(std::uint32_t(guarded(s.call, &h.o))));
327 continue;
328 }
329 const UINT64 before = h.fence->GetCompletedValue();
330 const HRESULT hr = guarded(s.call, &h.o);
331 out.add(s.name, std::uint64_t(std::uint32_t(hr)));
332 out.add(std::string(s.name) + " (removed reason)", std::uint64_t(std::uint32_t(device->GetDeviceRemovedReason())));
333 if (s.fence_value)
334 out.add(std::string(s.name) + " (fence)",
335 hr == HRESULT(kFaulted) ? kFaulted : settled(h.fence.p, before, s.fence_value));
336 }
337 return true;
338}
339
340// --host-step N: one isolated step on a fresh host device; the exit code is its HRESULT.
341int host_step(std::size_t index) {
342 if (index >= sizeof(kSteps) / sizeof(kSteps[0])) return int(kNoChild);
343 Ref<ID3D12Device> host;
344 host.p = create_host();
345 Holder h;
346 if (!host.p || !make(host.p, h)) return int(kNoChild);
347 return int(guarded(kSteps[index].call, &h.o));
348}
349
350} // namespace
351
352int main(int argc, char** argv) {
353 if (argc == 3 && std::strcmp(argv[1], "--host-step") == 0) return host_step(std::size_t(std::atoi(argv[2])));
354 vktest::Device d;
355 const auto device_status = d.initialize();
356 if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips
357 if (device_status != vktest::DeviceStatus::ready) return 1;
358 const bool verbose = GetEnvironmentVariableA("LEONIDA_D3D49_VERBOSE", nullptr, 0) > 0;
359 {
360 rt::d3d12::VulkanDeviceInfo info{};
361 info.get_instance_proc = d.instance_proc;
362 info.instance = d.instance;
363 info.physical = d.physical;
364 info.device = d.device;
365 info.queue = d.queue;
366 info.queue_family = d.family;
367 info.buffer_device_address = true; // heaps live in the GPU address arena
368 Ref<ID3D12Device> device;
369 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p))));
370 Record ours;
371 EXPECT(run(device.p, false, ours));
372
373 Ref<ID3D12Device> host;
374 host.p = create_host();
375 if (!host.p) {
376 std::printf("residency: no host D3D12 device to compare with; %zu steps recorded, not compared\n",
377 ours.values.size());
378 } else {
379 Record theirs;
380 EXPECT(run(host.p, true, theirs));
381 EXPECT(theirs.names == ours.names);
382 int mismatches = 0, faulted = 0;
383 for (std::size_t i = 0; i < ours.values.size(); ++i) {
384 if (theirs.values[i] == kNoChild)
385 std::printf("residency %s: the host step's child process didn't run it\n", ours.names[i].c_str());
386 EXPECT(theirs.values[i] != kNoChild);
387 if (theirs.values[i] == kFaulted) {
388 std::printf("residency %s: the host faults, not compared (ours 0x%llx)\n", ours.names[i].c_str(),
389 static_cast<unsigned long long>(ours.values[i]));
390 ++faulted;
391 continue;
392 }
393 // A fence the layer would have to move backwards: Vulkan timelines only go up, so the layer's fence
394 // stays where it was (docs/d3d12_vulkan.md); the HRESULT is still compared.
395 if (ours.names[i].find("[backwards]") != std::string::npos &&
396 ours.names[i].find("(fence)") != std::string::npos) {
397 std::printf("residency %s: ours 0x%llx host 0x%llx (a fence can't go backwards here; not "
398 "compared)\n", ours.names[i].c_str(), static_cast<unsigned long long>(ours.values[i]),
399 static_cast<unsigned long long>(theirs.values[i]));
400 ++faulted;
401 continue;
402 }
403 const bool same = ours.values[i] == theirs.values[i];
404 if (verbose || !same)
405 std::printf("residency %s: ours 0x%llx host 0x%llx%s\n", ours.names[i].c_str(),
406 static_cast<unsigned long long>(ours.values[i]),
407 static_cast<unsigned long long>(theirs.values[i]), same ? "" : " MISMATCH");
408 mismatches += !same;
409 }
410 std::printf("residency: %zu values from %zu steps compared with the host (%d more not compared), "
411 "%d mismatches\n", ours.values.size() - faulted, sizeof(kSteps) / sizeof(kSteps[0]), faulted,
412 mismatches);
413 EXPECT(mismatches == 0);
414 // The values left out are the null-pointer steps the host faults on and the backwards fence. A host that
415 // faulted on more would make the comparison vacuous while still passing, so the count is held to that.
416 EXPECT(faulted <= kMaxNotCompared);
417 }
418 }
419 std::printf("d3d12_residency_test: OK\n");
420 return 0;
421}
diff --git a/runtime/test/d3d12_set0_compute_test.cpp b/runtime/test/d3d12_set0_compute_test.cpp
index 503492610..1d51c9e70 100644
--- a/runtime/test/d3d12_set0_compute_test.cpp
+++ b/runtime/test/d3d12_set0_compute_test.cpp
@@ -16,6 +16,7 @@
16// GLSL written to the translator's contract. 16// GLSL written to the translator's contract.
17// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation (0 errors required). 17// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation (0 errors required).
18#include "shader_fixture_path.h" 18#include "shader_fixture_path.h"
19#include "test_temp_dir.h"
19#include "vk_test_device.h" 20#include "vk_test_device.h"
20#include "d3d12_test_shaders.h" 21#include "d3d12_test_shaders.h"
21#include "../shims/d3d12_com.h" 22#include "../shims/d3d12_com.h"
@@ -68,10 +69,10 @@ int main() {
68 // set-0 bindings for the shader, as the translator does for one that samples. 69 // set-0 bindings for the shader, as the translator does for one that samples.
69 const auto program = fssm_program({0x43530003, 0xbf810000}); 70 const auto program = fssm_program({0x43530003, 0xbf810000});
70 const auto container = shader_container(program); 71 const auto container = shader_container(program);
71 const auto library = std::filesystem::temp_directory_path() / "leonida_set0_compute_test"; 72 const testfiles::ScratchDir scratch("leonida_set0_compute_test");
72 std::filesystem::create_directories(library); 73 const auto& library = scratch.path();
73 std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SET0_SAMPLE_SPV), library / "cs_set0_sample.spv", 74 EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SET0_SAMPLE_SPV),
74 std::filesystem::copy_options::overwrite_existing); 75 library / "cs_set0_sample.spv"));
75 { 76 {
76 std::ofstream index(library / "index.json", std::ios::binary); 77 std::ofstream index(library / "index.json", std::ios::binary);
77 index << "{\"cs_set0_sample\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << leonida::sha256_hex(program) 78 index << "{\"cs_set0_sample\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << leonida::sha256_hex(program)
@@ -309,7 +310,6 @@ int main() {
309 fence.reset(); 310 fence.reset();
310 EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); 311 EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1);
311 } 312 }
312 std::filesystem::remove_all(library);
313 313
314 // Runs 0, 1 and 3 against the textures; run 2 is the fallback image, whose colour the test does not fix: it 314 // Runs 0, 1 and 3 against the textures; run 2 is the fallback image, whose colour the test does not fix: it
315 // must be one colour everywhere, which neither texture gives. 315 // must be one colour everywhere, which neither texture gives.
diff --git a/runtime/test/d3d12_shader_cache_test.cpp b/runtime/test/d3d12_shader_cache_test.cpp
index 8f6a68288..bc4b2704d 100644
--- a/runtime/test/d3d12_shader_cache_test.cpp
+++ b/runtime/test/d3d12_shader_cache_test.cpp
@@ -28,7 +28,7 @@ struct Ref {
28 T* operator->() const { return p; } 28 T* operator->() const { return p; }
29}; 29};
30 30
31int exercise_shader_cache(ID3D12Device9* dev, const char* label, bool test_null_in_params) { 31int exercise_shader_cache(ID3D12Device9* dev, const char* label, bool is_vulkan_layer) {
32 // {7c83f2a1-4b5e-4d19-9a32-1f2e3d4c5b6a} 32 // {7c83f2a1-4b5e-4d19-9a32-1f2e3d4c5b6a}
33 const GUID id1 = {0x7c83f2a1, 0x4b5e, 0x4d19, {0x9a, 0x32, 0x1f, 0x2e, 0x3d, 0x4c, 0x5b, 0x6a}}; 33 const GUID id1 = {0x7c83f2a1, 0x4b5e, 0x4d19, {0x9a, 0x32, 0x1f, 0x2e, 0x3d, 0x4c, 0x5b, 0x6a}};
34 const GUID id2 = {0x1b74e9d0, 0x2c3a, 0x4f81, {0x8e, 0x11, 0x5a, 0x6b, 0x7c, 0x8d, 0x9e, 0x0f}}; 34 const GUID id2 = {0x1b74e9d0, 0x2c3a, 0x4f81, {0x8e, 0x11, 0x5a, 0x6b, 0x7c, 0x8d, 0x9e, 0x0f}};
@@ -42,9 +42,9 @@ int exercise_shader_cache(ID3D12Device9* dev, const char* label, bool test_null_
42 42
43 // 1. CreateShaderCacheSession argument validation & capability check (null output -> S_FALSE). 43 // 1. CreateShaderCacheSession argument validation & capability check (null output -> S_FALSE).
44 // Passing nullptr for SAL _In_/_Inout_ parameters (pDesc, pKey, pValue, pValueSize) is undefined 44 // Passing nullptr for SAL _In_/_Inout_ parameters (pDesc, pKey, pValue, pValueSize) is undefined
45 // behaviour on older in-box Windows D3D12 runtimes (e.g. Win11 23H2 22621.5415 AVs), so those 45 // behaviour on older in-box Windows D3D12 runtimes, so those null-pointer guards are exercised
46 // null-pointer guards are exercised only on the Vulkan layer. 46 // only on the Vulkan layer.
47 if (test_null_in_params) { 47 if (is_vulkan_layer) {
48 EXPECT(dev->CreateShaderCacheSession(nullptr, __uuidof(ID3D12ShaderCacheSession), nullptr) == E_INVALIDARG); 48 EXPECT(dev->CreateShaderCacheSession(nullptr, __uuidof(ID3D12ShaderCacheSession), nullptr) == E_INVALIDARG);
49 } 49 }
50 EXPECT(dev->CreateShaderCacheSession(&desc, __uuidof(ID3D12ShaderCacheSession), nullptr) == S_FALSE); 50 EXPECT(dev->CreateShaderCacheSession(&desc, __uuidof(ID3D12ShaderCacheSession), nullptr) == S_FALSE);
@@ -81,16 +81,16 @@ int exercise_shader_cache(ID3D12Device9* dev, const char* label, bool test_null_
81 UINT sz = sizeof(out_v); 81 UINT sz = sizeof(out_v);
82 EXPECT(s1->FindValue(&k1, sizeof(k1), &out_v, &sz) == DXGI_ERROR_NOT_FOUND); 82 EXPECT(s1->FindValue(&k1, sizeof(k1), &out_v, &sz) == DXGI_ERROR_NOT_FOUND);
83 EXPECT(sz == sizeof(out_v)); 83 EXPECT(sz == sizeof(out_v));
84 if (test_null_in_params) { 84 if (is_vulkan_layer) {
85 EXPECT(s1->FindValue(nullptr, sizeof(k1), &out_v, &sz) == E_INVALIDARG); 85 EXPECT(s1->FindValue(nullptr, sizeof(k1), &out_v, &sz) == E_INVALIDARG);
86 } 86 }
87 EXPECT(s1->FindValue(&k1, 0, &out_v, &sz) == E_INVALIDARG); 87 EXPECT(s1->FindValue(&k1, 0, &out_v, &sz) == E_INVALIDARG);
88 if (test_null_in_params) { 88 if (is_vulkan_layer) {
89 EXPECT(s1->FindValue(&k1, sizeof(k1), &out_v, nullptr) == E_INVALIDARG); 89 EXPECT(s1->FindValue(&k1, sizeof(k1), &out_v, nullptr) == E_INVALIDARG);
90 EXPECT(s1->StoreValue(nullptr, sizeof(k1), &v1, sizeof(v1)) == E_INVALIDARG); 90 EXPECT(s1->StoreValue(nullptr, sizeof(k1), &v1, sizeof(v1)) == E_INVALIDARG);
91 } 91 }
92 EXPECT(s1->StoreValue(&k1, 0, &v1, sizeof(v1)) == E_INVALIDARG); 92 EXPECT(s1->StoreValue(&k1, 0, &v1, sizeof(v1)) == E_INVALIDARG);
93 if (test_null_in_params) { 93 if (is_vulkan_layer) {
94 EXPECT(s1->StoreValue(&k1, sizeof(k1), nullptr, sizeof(v1)) == E_INVALIDARG); 94 EXPECT(s1->StoreValue(&k1, sizeof(k1), nullptr, sizeof(v1)) == E_INVALIDARG);
95 } 95 }
96 EXPECT(s1->StoreValue(&k1, sizeof(k1), &v1, 0) == E_INVALIDARG); 96 EXPECT(s1->StoreValue(&k1, sizeof(k1), &v1, 0) == E_INVALIDARG);
@@ -118,17 +118,21 @@ int exercise_shader_cache(ID3D12Device9* dev, const char* label, bool test_null_
118 EXPECT(s2->FindValue(&k1, sizeof(k1), &out_v, &sz) == S_OK && sz == sizeof(v1) && out_v == v1); 118 EXPECT(s2->FindValue(&k1, sizeof(k1), &out_v, &sz) == S_OK && sz == sizeof(v1) && out_v == v1);
119 119
120 // Different Identifier does not see k1. 120 // Different Identifier does not see k1.
121 // Older in-box Windows D3D12 runtimes (e.g. Win11 23H2 d3d12.dll 10.0.22621.5415) AV (0xC0000005)
122 // when releasing a D3D12_SHADER_CACHE_MODE_MEMORY session after SetDeleteOnDestroy(), so exercise
123 // SetDeleteOnDestroy() on MODE_MEMORY only on the Vulkan layer; MODE_MEMORY still discards on final
124 // release on both runtimes.
121 D3D12_SHADER_CACHE_SESSION_DESC desc2 = desc; 125 D3D12_SHADER_CACHE_SESSION_DESC desc2 = desc;
122 desc2.Identifier = id2; 126 desc2.Identifier = id2;
123 Ref<ID3D12ShaderCacheSession> other; 127 Ref<ID3D12ShaderCacheSession> other;
124 EXPECT(SUCCEEDED(dev->CreateShaderCacheSession(&desc2, IID_PPV_ARGS(&other.p))) && other.p); 128 EXPECT(SUCCEEDED(dev->CreateShaderCacheSession(&desc2, IID_PPV_ARGS(&other.p))) && other.p);
125 sz = sizeof(out_v); 129 sz = sizeof(out_v);
126 EXPECT(other->FindValue(&k1, sizeof(k1), &out_v, &sz) == DXGI_ERROR_NOT_FOUND); 130 EXPECT(other->FindValue(&k1, sizeof(k1), &out_v, &sz) == DXGI_ERROR_NOT_FOUND);
127 other->SetDeleteOnDestroy(); 131 if (is_vulkan_layer) other->SetDeleteOnDestroy();
128 other.reset(); 132 other.reset();
129 133
130 // Marking s1 delete-on-destroy keeps data alive while s2 is still open, then deletes once s2 releases. 134 // Releasing s1 keeps data alive while s2 is still open, then discards once s2 releases.
131 s1->SetDeleteOnDestroy(); 135 if (is_vulkan_layer) s1->SetDeleteOnDestroy();
132 s1.reset(); 136 s1.reset();
133 sz = sizeof(out_v); 137 sz = sizeof(out_v);
134 out_v = 0; 138 out_v = 0;
@@ -139,7 +143,7 @@ int exercise_shader_cache(ID3D12Device9* dev, const char* label, bool test_null_
139 EXPECT(SUCCEEDED(dev->CreateShaderCacheSession(&desc, IID_PPV_ARGS(&s3.p))) && s3.p); 143 EXPECT(SUCCEEDED(dev->CreateShaderCacheSession(&desc, IID_PPV_ARGS(&s3.p))) && s3.p);
140 sz = sizeof(out_v); 144 sz = sizeof(out_v);
141 EXPECT(s3->FindValue(&k1, sizeof(k1), &out_v, &sz) == DXGI_ERROR_NOT_FOUND); 145 EXPECT(s3->FindValue(&k1, sizeof(k1), &out_v, &sz) == DXGI_ERROR_NOT_FOUND);
142 s3->SetDeleteOnDestroy(); 146 if (is_vulkan_layer) s3->SetDeleteOnDestroy();
143 s3.reset(); 147 s3.reset();
144 148
145 // 4. ShaderCacheControl invalid-argument checks (same on host and layer). 149 // 4. ShaderCacheControl invalid-argument checks (same on host and layer).
diff --git a/runtime/test/d3d12_sparse_queue_family_test.cpp b/runtime/test/d3d12_sparse_queue_family_test.cpp
new file mode 100644
index 000000000..04caee442
--- /dev/null
+++ b/runtime/test/d3d12_sparse_queue_family_test.cpp
@@ -0,0 +1,175 @@
1// Synthetic D3D12 reserved-buffer mapping on DIRECT/COPY/COMPUTE queues, with GPU readback.
2#include <windows.h>
3#include <d3d12.h>
4#include <dxgi1_6.h>
5#include "../shims/d3d12_com.h"
6#include <wrl/client.h>
7#include <algorithm>
8#include <cstdint>
9#include <cstdio>
10#include <cstring>
11#include <stdexcept>
12#include <string>
13
14using Microsoft::WRL::ComPtr;
15constexpr UINT64 PAGE_BYTES = 65536, BUFFER_BYTES = 2 * PAGE_BYTES;
16
17static void ok(HRESULT hr, const char* where) {
18 if (FAILED(hr)) {
19 std::printf("FAIL %s hr=0x%08lx\n", where, static_cast<unsigned long>(hr));
20 throw std::runtime_error(where);
21 }
22}
23static unsigned char pattern(size_t n) {
24 return static_cast<unsigned char>((n * 131u + (n >> 7u) * 17u + 29u) & 255u);
25}
26static D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes) {
27 D3D12_RESOURCE_DESC d{};
28 d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
29 d.Alignment = 0;
30 d.Width = bytes;
31 d.Height = 1;
32 d.DepthOrArraySize = 1;
33 d.MipLevels = 1;
34 d.Format = DXGI_FORMAT_UNKNOWN;
35 d.SampleDesc.Count = 1;
36 d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
37 return d;
38}
39static ComPtr<ID3D12Resource> committed(ID3D12Device* dev, UINT64 bytes,
40 D3D12_HEAP_TYPE type, D3D12_RESOURCE_STATES state) {
41 ComPtr<ID3D12Resource> res;
42 D3D12_HEAP_PROPERTIES hp{};
43 hp.Type = type;
44 auto desc = buffer_desc(bytes);
45 ok(dev->CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr,
46 IID_PPV_ARGS(&res)), "CreateCommittedResource");
47 return res;
48}
49static ComPtr<ID3D12CommandQueue> make_queue(ID3D12Device* dev, D3D12_COMMAND_LIST_TYPE type) {
50 D3D12_COMMAND_QUEUE_DESC desc{};
51 desc.Type = type;
52 ComPtr<ID3D12CommandQueue> q;
53 ok(dev->CreateCommandQueue(&desc, IID_PPV_ARGS(&q)), "CreateCommandQueue");
54 return q;
55}
56struct CopyList {
57 ComPtr<ID3D12CommandAllocator> alloc;
58 ComPtr<ID3D12GraphicsCommandList> list;
59};
60static CopyList copy_list(ID3D12Device* dev, D3D12_COMMAND_LIST_TYPE type,
61 ID3D12Resource* dst, ID3D12Resource* src, UINT64 bytes) {
62 CopyList cl;
63 ok(dev->CreateCommandAllocator(type, IID_PPV_ARGS(&cl.alloc)), "CreateCommandAllocator");
64 ok(dev->CreateCommandList(0, type, cl.alloc.Get(), nullptr, IID_PPV_ARGS(&cl.list)),
65 "CreateCommandList");
66 cl.list->CopyBufferRegion(dst, 0, src, 0, bytes);
67 ok(cl.list->Close(), "Close command list");
68 return cl;
69}
70
71static bool run_case(ID3D12Device* dev, D3D12_COMMAND_LIST_TYPE map_type,
72 ID3D12CommandQueue* direct, ID3D12CommandQueue* copy,
73 ID3D12CommandQueue* compute, const char* label) {
74 ID3D12CommandQueue* mapper = map_type == D3D12_COMMAND_LIST_TYPE_DIRECT ? direct :
75 map_type == D3D12_COMMAND_LIST_TYPE_COMPUTE ? compute : copy;
76
77 D3D12_HEAP_DESC hdesc{};
78 hdesc.SizeInBytes = PAGE_BYTES;
79 hdesc.Alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT;
80 hdesc.Properties.Type = D3D12_HEAP_TYPE_DEFAULT;
81 hdesc.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS;
82 ComPtr<ID3D12Heap> heap;
83 ok(dev->CreateHeap(&hdesc, IID_PPV_ARGS(&heap)), "CreateHeap(one tile)");
84 ComPtr<ID3D12Resource> sparse;
85 auto desc = buffer_desc(BUFFER_BYTES);
86 ok(dev->CreateReservedResource(&desc, D3D12_RESOURCE_STATE_COMMON, nullptr,
87 IID_PPV_ARGS(&sparse)), "CreateReservedResource(buffer)");
88 UINT total_tiles = 0;
89 dev->GetResourceTiling(sparse.Get(), &total_tiles, nullptr, nullptr, nullptr, 0, nullptr);
90 std::printf("case=%s reserved_tiles=%u mapping_queue=%d\n", label, total_tiles, int(map_type));
91 if (total_tiles != 2) throw std::runtime_error("unexpected reserved-buffer tile count");
92
93 auto upload = committed(dev, PAGE_BYTES, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ);
94 auto readback = committed(dev, BUFFER_BYTES, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST);
95 unsigned char* host = nullptr;
96 D3D12_RANGE empty{0, 0};
97 ok(upload->Map(0, &empty, reinterpret_cast<void**>(&host)), "Upload Map");
98 for (size_t i = 0; i < PAGE_BYTES; ++i) host[i] = pattern(i);
99 D3D12_RANGE written{0, size_t(PAGE_BYTES)};
100 upload->Unmap(0, &written);
101
102 ComPtr<ID3D12Fence> fence;
103 ok(dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)), "CreateFence");
104 D3D12_TILED_RESOURCE_COORDINATE coord{};
105 D3D12_TILE_REGION_SIZE region{};
106 region.NumTiles = 1;
107 region.UseBox = FALSE;
108 D3D12_TILE_RANGE_FLAGS range_flags = D3D12_TILE_RANGE_FLAG_NONE;
109 UINT heap_start = 0, range_count = 1;
110 mapper->UpdateTileMappings(sparse.Get(), 1, &coord, &region, heap.Get(),
111 1, &range_flags, &heap_start, &range_count, D3D12_TILE_MAPPING_FLAG_NONE);
112 ok(mapper->Signal(fence.Get(), 1), "mapper Signal 1");
113
114 auto write = copy_list(dev, D3D12_COMMAND_LIST_TYPE_COPY, sparse.Get(), upload.Get(), PAGE_BYTES);
115 ok(copy->Wait(fence.Get(), 1), "copy Wait 1");
116 ID3D12CommandList* write_lists[] = {write.list.Get()};
117 copy->ExecuteCommandLists(1, write_lists);
118 ok(copy->Signal(fence.Get(), 2), "copy Signal 2");
119
120 auto read = copy_list(dev, D3D12_COMMAND_LIST_TYPE_COMPUTE, readback.Get(), sparse.Get(), BUFFER_BYTES);
121 ok(compute->Wait(fence.Get(), 2), "compute Wait 2");
122 ID3D12CommandList* read_lists[] = {read.list.Get()};
123 compute->ExecuteCommandLists(1, read_lists);
124 ok(compute->Signal(fence.Get(), 3), "compute Signal 3");
125
126 HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr);
127 if (!done) throw std::runtime_error("CreateEventW failed");
128 ok(fence->SetEventOnCompletion(3, done), "SetEventOnCompletion");
129 DWORD wait = WaitForSingleObject(done, 15000);
130 CloseHandle(done);
131 if (wait != WAIT_OBJECT_0) throw std::runtime_error("GPU fence timeout");
132
133 D3D12_RANGE read_range{0, size_t(BUFFER_BYTES)};
134 unsigned char* data = nullptr;
135 ok(readback->Map(0, &read_range, reinterpret_cast<void**>(&data)), "Readback Map");
136 size_t wrong_mapped = 0, wrong_unmapped = 0;
137 for (size_t i = 0; i < PAGE_BYTES; ++i) wrong_mapped += data[i] != pattern(i);
138 for (size_t i = PAGE_BYTES; i < BUFFER_BYTES; ++i) wrong_unmapped += data[i] != 0;
139 readback->Unmap(0, &empty);
140 const bool passed = wrong_mapped == 0 && wrong_unmapped == 0;
141 std::printf("RESULT %s %s mapped_mismatch=%zu/65536 unmapped_nonzero=%zu/65536\n",
142 label, passed ? "PASS" : "FAIL", wrong_mapped, wrong_unmapped);
143 return passed;
144}
145
146int main() {
147 try {
148 ComPtr<ID3D12Device> device;
149 ok(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&device)),
150 "Leonida create_vulkan_device_standalone");
151 if (!rt::d3d12::device_sparse_buffer_tiles(device.Get())) {
152 std::puts("SKIP Leonida sparse_buffer_tiles not supported");
153 return 77;
154 }
155 std::puts("LEONIDA Vulkan-layer test; independent D3D12 API surface, direct->copy->compute queues");
156 auto direct = make_queue(device.Get(), D3D12_COMMAND_LIST_TYPE_DIRECT);
157 auto copy = make_queue(device.Get(), D3D12_COMMAND_LIST_TYPE_COPY);
158 auto compute = make_queue(device.Get(), D3D12_COMMAND_LIST_TYPE_COMPUTE);
159 bool all_pass = true;
160 all_pass &= run_case(device.Get(), D3D12_COMMAND_LIST_TYPE_DIRECT,
161 direct.Get(), copy.Get(), compute.Get(), "LAYER_MAP_DIRECT_COPY_COMPUTE");
162 all_pass &= run_case(device.Get(), D3D12_COMMAND_LIST_TYPE_COPY,
163 direct.Get(), copy.Get(), compute.Get(), "LAYER_MAP_COPY_COPY_COMPUTE");
164 all_pass &= run_case(device.Get(), D3D12_COMMAND_LIST_TYPE_COMPUTE,
165 direct.Get(), copy.Get(), compute.Get(), "LAYER_MAP_COMPUTE_COPY_COMPUTE");
166 const HRESULT removed = device->GetDeviceRemovedReason();
167 std::printf("DEVICE_REMOVED_HRESULT=0x%08lx\n", static_cast<unsigned long>(removed));
168 all_pass &= SUCCEEDED(removed);
169 std::printf("LAYER_FINAL %s\n", all_pass ? "PASS" : "FAIL");
170 return all_pass ? 0 : 1;
171 } catch (const std::exception& e) {
172 std::fprintf(stderr, "LAYER_FATAL: %s\n", e.what());
173 return 2;
174 }
175}
diff --git a/runtime/test/d3d12_state_map_test.cpp b/runtime/test/d3d12_state_map_test.cpp
index 58a649437..d7466b781 100644
--- a/runtime/test/d3d12_state_map_test.cpp
+++ b/runtime/test/d3d12_state_map_test.cpp
@@ -660,6 +660,21 @@ int main() {
660 CHECK(!resizable_bar(VkPhysicalDeviceMemoryProperties{})); 660 CHECK(!resizable_bar(VkPhysicalDeviceMemoryProperties{}));
661 } 661 }
662 662
663 // D3D-299: a texture (required 0, preferred DEVICE_LOCAL) in host memory has spilled; the arena (required
664 // HOST_VISIBLE | HOST_COHERENT, preferred DEVICE_LOCAL) in host memory has not, and neither has anything that
665 // got DEVICE_LOCAL or never asked for it.
666 {
667 constexpr VkMemoryPropertyFlags local = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
668 constexpr VkMemoryPropertyFlags host = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
669 CHECK(spilled_to_host(0, local, host));
670 CHECK(spilled_to_host(0, local, 0));
671 CHECK(!spilled_to_host(0, local, local));
672 CHECK(!spilled_to_host(0, local, local | host));
673 CHECK(!spilled_to_host(host, local, host));
674 CHECK(!spilled_to_host(host, 0, host));
675 CHECK(!spilled_to_host(0, 0, host));
676 }
677
663 // Memory type choice. Heaps as an RTX 3090 without Resizable BAR reports them: VRAM, system memory, and the 678 // Memory type choice. Heaps as an RTX 3090 without Resizable BAR reports them: VRAM, system memory, and the
664 // 214 MiB BAR heap that holds the only DEVICE_LOCAL | HOST_VISIBLE type. 679 // 214 MiB BAR heap that holds the only DEVICE_LOCAL | HOST_VISIBLE type.
665 { 680 {
diff --git a/runtime/test/d3d12_subgroup_test.cpp b/runtime/test/d3d12_subgroup_test.cpp
index 4894f70e2..abc6f2bd0 100644
--- a/runtime/test/d3d12_subgroup_test.cpp
+++ b/runtime/test/d3d12_subgroup_test.cpp
@@ -10,6 +10,7 @@
10// Each case also prints a control run with the layer's size request switched off, to show what the request changes 10// Each case also prints a control run with the layer's size request switched off, to show what the request changes
11// on this GPU; the control is not judged. No game data. Set LEONIDA_VK_VALIDATION=1 to run under 11// on this GPU; the control is not judged. No game data. Set LEONIDA_VK_VALIDATION=1 to run under
12// VK_LAYER_KHRONOS_validation; validation errors fail the test. 12// VK_LAYER_KHRONOS_validation; validation errors fail the test.
13#include "test_temp_dir.h"
13#include "vk_test_device.h" 14#include "vk_test_device.h"
14#include "../shims/d3d12_com.h" 15#include "../shims/d3d12_com.h"
15#include "../src/shader_library.h" 16#include "../src/shader_library.h"
@@ -313,14 +314,14 @@ struct LibraryEntry {
313 314
314// A translator-style folder with the entries' modules, every entry keyed by the fixture program's hash. 315// A translator-style folder with the entries' modules, every entry keyed by the fixture program's hash.
315std::filesystem::path make_library(const std::string& tag, const std::vector<LibraryEntry>& entries) { 316std::filesystem::path make_library(const std::string& tag, const std::vector<LibraryEntry>& entries) {
316 const auto dir = std::filesystem::temp_directory_path() / ("leonida_subgroup_" + tag); 317 const auto dir = testfiles::process_temp_dir("leonida_subgroup_" + tag);
317 std::filesystem::remove_all(dir); 318 std::filesystem::remove_all(dir);
318 std::filesystem::create_directories(dir); 319 std::filesystem::create_directories(dir);
319 std::ofstream index(dir / "index.json", std::ios::binary); 320 std::ofstream index(dir / "index.json", std::ios::binary);
320 index << "{"; 321 index << "{";
321 bool first = true; 322 bool first = true;
322 for (const LibraryEntry& e : entries) { 323 for (const LibraryEntry& e : entries) {
323 std::filesystem::copy_file(e.spv, dir / (e.name + ".spv"), std::filesystem::copy_options::overwrite_existing); 324 testfiles::copy_file(e.spv, dir / (e.name + ".spv")); // a missing module is reported, and the PSO fails
324 index << (first ? "" : ",\n") << "\"" << e.name << "\": {\"stage\": \"" << e.stage << "\", \"fssm_sha256\": \"" 325 index << (first ? "" : ",\n") << "\"" << e.name << "\": {\"stage\": \"" << e.stage << "\", \"fssm_sha256\": \""
325 << leonida::sha256_hex(fixture_fssm()) << "\", \"bindings\": [], \"push_constant_bytes\": 144, " 326 << leonida::sha256_hex(fixture_fssm()) << "\", \"bindings\": [], \"push_constant_bytes\": 144, "
326 << e.tail << "}"; 327 << e.tail << "}";
diff --git a/runtime/test/d3d12_typeless_families_test.cpp b/runtime/test/d3d12_typeless_families_test.cpp
index 936fbbbee..b6fe4ea86 100644
--- a/runtime/test/d3d12_typeless_families_test.cpp
+++ b/runtime/test/d3d12_typeless_families_test.cpp
@@ -10,6 +10,7 @@
10// A view format the layer does not map yet (its CheckFeatureSupport gives no RENDER_TARGET) is reported and skipped, 10// A view format the layer does not map yet (its CheckFeatureSupport gives no RENDER_TARGET) is reported and skipped,
11// so the R8 family and the 16-bit integer and normalized formats are covered as soon as their mapping lands. 11// so the R8 family and the 16-bit integer and normalized formats are covered as soon as their mapping lands.
12// Synthetic data only. LEONIDA_VK_VALIDATION=1 runs it under VK_LAYER_KHRONOS_validation. 12// Synthetic data only. LEONIDA_VK_VALIDATION=1 runs it under VK_LAYER_KHRONOS_validation.
13#include "test_temp_dir.h"
13#include "vk_test_device.h" 14#include "vk_test_device.h"
14#include "host_wine.h" 15#include "host_wine.h"
15#include "../shims/d3d12_com.h" 16#include "../shims/d3d12_com.h"
@@ -260,12 +261,12 @@ int main() {
260 const auto vs_container = d3d12test::shader_container(vs_program); 261 const auto vs_container = d3d12test::shader_container(vs_program);
261 const auto ps_float_container = d3d12test::shader_container(ps_float_program); 262 const auto ps_float_container = d3d12test::shader_container(ps_float_program);
262 const auto ps_uint_container = d3d12test::shader_container(ps_uint_program); 263 const auto ps_uint_container = d3d12test::shader_container(ps_uint_program);
263 const auto library = std::filesystem::temp_directory_path() / "leonida_typeless_families_test"; 264 const testfiles::ScratchDir scratch("leonida_typeless_families_test");
264 std::filesystem::create_directories(library); 265 const auto& library = scratch.path();
265 const auto overwrite = std::filesystem::copy_options::overwrite_existing; 266 if (!testfiles::copy_file(LEONIDA_TYPELESS_VS_SPV, library / "vs.spv") ||
266 std::filesystem::copy_file(LEONIDA_TYPELESS_VS_SPV, library / "vs.spv", overwrite); 267 !testfiles::copy_file(LEONIDA_TYPELESS_PS_FLOAT_SPV, library / "ps_float.spv") ||
267 std::filesystem::copy_file(LEONIDA_TYPELESS_PS_FLOAT_SPV, library / "ps_float.spv", overwrite); 268 !testfiles::copy_file(LEONIDA_TYPELESS_PS_UINT_SPV, library / "ps_uint.spv"))
268 std::filesystem::copy_file(LEONIDA_TYPELESS_PS_UINT_SPV, library / "ps_uint.spv", overwrite); 269 return 1;
269 { 270 {
270 std::ofstream index(library / "index.json", std::ios::binary); 271 std::ofstream index(library / "index.json", std::ios::binary);
271 index << "{\"vs\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_program) 272 index << "{\"vs\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_program)
diff --git a/runtime/test/d3d12_vulkan_device_test.cpp b/runtime/test/d3d12_vulkan_device_test.cpp
index c16ecd6a7..f7a1ed319 100644
--- a/runtime/test/d3d12_vulkan_device_test.cpp
+++ b/runtime/test/d3d12_vulkan_device_test.cpp
@@ -867,6 +867,56 @@ int compare_allocation_info(ID3D12Device* ours) {
867 if (empty_a.SizeInBytes != empty_b.SizeInBytes || empty_a.Alignment != empty_b.Alignment) 867 if (empty_a.SizeInBytes != empty_b.SizeInBytes || empty_a.Alignment != empty_b.Alignment)
868 mismatch("no resources", empty_a, empty_b); 868 mismatch("no resources", empty_a, empty_b);
869 869
870 // A visible mask above 1 names a node a single-node adapter does not have: the host answers the invalid
871 // allocation (size UINT64_MAX, 64 KiB alignment), for one resource and for none, through GetResourceAllocationInfo
872 // and its 1 and 2 variants, and leaves the per-resource array as it was.
873 {
874 Ref<ID3D12Device4> ours4, host4;
875 Ref<ID3D12Device8> ours8_mask, host8_mask;
876 ours->QueryInterface(IID_PPV_ARGS(&ours4.p));
877 host->QueryInterface(IID_PPV_ARGS(&host4.p));
878 ours->QueryInterface(IID_PPV_ARGS(&ours8_mask.p));
879 host->QueryInterface(IID_PPV_ARGS(&host8_mask.p));
880 const D3D12_RESOURCE_DESC buffer = buffer_desc(256);
881 D3D12_RESOURCE_DESC1 buffer1{};
882 buffer1.Dimension = buffer.Dimension;
883 buffer1.Width = buffer.Width;
884 buffer1.Height = buffer1.DepthOrArraySize = buffer1.MipLevels = 1;
885 buffer1.SampleDesc.Count = 1;
886 buffer1.Layout = buffer.Layout;
887 const auto same_info = [](const D3D12_RESOURCE_ALLOCATION_INFO& x, const D3D12_RESOURCE_ALLOCATION_INFO& y) {
888 return x.SizeInBytes == y.SizeInBytes && x.Alignment == y.Alignment;
889 };
890 for (const UINT mask : {0u, 1u, 2u, 3u, 0x80000000u}) {
891 char name[64];
892 std::snprintf(name, sizeof(name), "visible mask 0x%x", mask);
893 for (const UINT count : {0u, 1u}) {
894 const D3D12_RESOURCE_DESC* descs = count ? &buffer : nullptr;
895 const auto ia = ours->GetResourceAllocationInfo(mask, count, descs);
896 const auto ib = host->GetResourceAllocationInfo(mask, count, descs);
897 if (!same_info(ia, ib)) mismatch(name, ia, ib);
898 }
899 if (ours4.p && host4.p) {
900 const D3D12_RESOURCE_ALLOCATION_INFO1 sentinel{0xdead, 0xbeef, 0xcafe};
901 D3D12_RESOURCE_ALLOCATION_INFO1 each_a = sentinel, each_b = sentinel;
902 const auto ia = ours4->GetResourceAllocationInfo1(mask, 1, &buffer, &each_a);
903 const auto ib = host4->GetResourceAllocationInfo1(mask, 1, &buffer, &each_b);
904 if (!same_info(ia, ib) || each_a.Offset != each_b.Offset || each_a.SizeInBytes != each_b.SizeInBytes ||
905 each_a.Alignment != each_b.Alignment)
906 mismatch("visible mask, GetResourceAllocationInfo1", ia, ib);
907 }
908 if (ours8_mask.p && host8_mask.p) {
909 const D3D12_RESOURCE_ALLOCATION_INFO1 sentinel{0xdead, 0xbeef, 0xcafe};
910 D3D12_RESOURCE_ALLOCATION_INFO1 each_a = sentinel, each_b = sentinel;
911 const auto ia = ours8_mask->GetResourceAllocationInfo2(mask, 1, &buffer1, &each_a);
912 const auto ib = host8_mask->GetResourceAllocationInfo2(mask, 1, &buffer1, &each_b);
913 if (!same_info(ia, ib) || each_a.Offset != each_b.Offset || each_a.SizeInBytes != each_b.SizeInBytes ||
914 each_a.Alignment != each_b.Alignment)
915 mismatch("visible mask, GetResourceAllocationInfo2", ia, ib);
916 }
917 }
918 }
919
870 Ref<ID3D12Device8> ours8; 920 Ref<ID3D12Device8> ours8;
871 // MULTISAMPLE_QUALITY_LEVELS with TILED_RESOURCE: the same answers as the host, except 128-bit formats at 4x, 921 // MULTISAMPLE_QUALITY_LEVELS with TILED_RESOURCE: the same answers as the host, except 128-bit formats at 4x,
872 // which the AMD drivers refuse and WARP and NVIDIA report (and GetResourceAllocationInfo allocates here). 922 // which the AMD drivers refuse and WARP and NVIDIA report (and GetResourceAllocationInfo allocates here).
@@ -1968,6 +2018,7 @@ int new_format_round_trips(ID3D12Device* device, const rt::d3d12::VulkanDeviceIn
1968 }; 2018 };
1969 constexpr UINT size = 4, pitch = 256, slot = 1024; 2019 constexpr UINT size = 4, pitch = 256, slot = 1024;
1970 int failures = 0; 2020 int failures = 0;
2021 unsigned host_compared = 0, host_lacking = 0;
1971 const auto fail = [&](DXGI_FORMAT format, const char* what) { 2022 const auto fail = [&](DXGI_FORMAT format, const char* what) {
1972 if (failures++ < 16) std::fprintf(stderr, "new format %d: %s\n", int(format), what); 2023 if (failures++ < 16) std::fprintf(stderr, "new format %d: %s\n", int(format), what);
1973 }; 2024 };
@@ -2041,17 +2092,21 @@ int new_format_round_trips(ID3D12Device* device, const rt::d3d12::VulkanDeviceIn
2041 } 2092 }
2042 if (host.p) { 2093 if (host.p) {
2043 // A host runtime older than the format has nothing to match: A4B4G4R4_UNORM is not in Windows 10's D3D12, 2094 // A host runtime older than the format has nothing to match: A4B4G4R4_UNORM is not in Windows 10's D3D12,
2044 // which reports no 2D texture support for it and refuses it. Compare only where the host itself says it 2095 // which answers the query with an error (E_FAIL on Windows 10 build 19045, E_INVALIDARG on another 19041
2045 // has the format, so a host that reports it and still refuses the texture fails as before. 2096 // host) or reports no 2D texture, and refuses the texture. Compare only where the host itself says it has
2097 // the format, so a host that reports it and still refuses the texture fails as before. The answer is
2098 // printed, so an unexpected code stays visible.
2046 D3D12_FEATURE_DATA_FORMAT_SUPPORT host_support{format}; 2099 D3D12_FEATURE_DATA_FORMAT_SUPPORT host_support{format};
2047 const bool host_has_format = 2100 const HRESULT query = host->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &host_support,
2048 SUCCEEDED(host->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &host_support, 2101 sizeof(host_support));
2049 sizeof(host_support))) && 2102 const bool host_has_format = SUCCEEDED(query) && (host_support.Support1 & D3D12_FORMAT_SUPPORT1_TEXTURE2D);
2050 (host_support.Support1 & D3D12_FORMAT_SUPPORT1_TEXTURE2D);
2051 if (!host_has_format) { 2103 if (!host_has_format) {
2052 std::printf("new format %d: the host runtime has no such 2D texture (e.g. Windows 10), " 2104 ++host_lacking;
2053 "host comparison skipped\n", int(format)); 2105 std::printf("new format %d: the host runtime has no such 2D texture (FORMAT_SUPPORT answered %08lx, "
2106 "e.g. Windows 10), host comparison skipped\n",
2107 int(format), static_cast<unsigned long>(query));
2054 } else { 2108 } else {
2109 ++host_compared;
2055 Ref<ID3D12Resource> native; 2110 Ref<ID3D12Resource> native;
2056 if (FAILED(host->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &desc, 2111 if (FAILED(host->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &desc,
2057 D3D12_RESOURCE_STATE_COPY_DEST, nullptr, 2112 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
@@ -2172,9 +2227,12 @@ int new_format_round_trips(ID3D12Device* device, const rt::d3d12::VulkanDeviceIn
2172 } 2227 }
2173 upload->Unmap(0, nullptr); 2228 upload->Unmap(0, nullptr);
2174 readback->Unmap(0, nullptr); 2229 readback->Unmap(0, nullptr);
2230 char compared[64] = "";
2231 if (host.p) std::snprintf(compared, sizeof(compared), " (host compared on %u, host lacks %u)", host_compared,
2232 host_lacking);
2175 std::printf("new formats: %u of %zu created and copied both ways bit for bit%s, %u render-target clears " 2233 std::printf("new formats: %u of %zu created and copied both ways bit for bit%s, %u render-target clears "
2176 "matched the host, A4B4G4R4 render target %s, %d failures\n", 2234 "matched the host, A4B4G4R4 render target %s, %d failures\n",
2177 round_trips, std::size(formats), host.p ? " (host compared)" : "", clears_matched, 2235 round_trips, std::size(formats), compared, clears_matched,
2178 a4_target ? (a4_cleared == 4 ? "cleared to R, G, B and A" : "cleared wrong") : "not reported, skipped", 2236 a4_target ? (a4_cleared == 4 ? "cleared to R, G, B and A" : "cleared wrong") : "not reported, skipped",
2179 failures); 2237 failures);
2180 return failures; 2238 return failures;
@@ -2236,8 +2294,8 @@ int compare_feature_options(ID3D12Device* ours, const rt::d3d12::VulkanDeviceInf
2236 D3D12_FEATURE_DATA_D3D12_OPTIONS16 o16{}; 2294 D3D12_FEATURE_DATA_D3D12_OPTIONS16 o16{};
2237 D3D12_FEATURE_DATA_D3D12_OPTIONS18 o18{}; 2295 D3D12_FEATURE_DATA_D3D12_OPTIONS18 o18{};
2238 D3D12_FEATURE_DATA_D3D12_OPTIONS19 o19{}; 2296 D3D12_FEATURE_DATA_D3D12_OPTIONS19 o19{};
2239 D3D12_FEATURE_DATA_D3D12_OPTIONS20 o20{}; 2297 rt::d3d12::compat::FeatureDataOptions20 o20{};
2240 D3D12_FEATURE_DATA_D3D12_OPTIONS21 o21{}; 2298 rt::d3d12::compat::FeatureDataOptions21 o21{};
2241 2299
2242 query_ours(std::pair{"OPTIONS2", D3D12_FEATURE_D3D12_OPTIONS2}, o2); 2300 query_ours(std::pair{"OPTIONS2", D3D12_FEATURE_D3D12_OPTIONS2}, o2);
2243 query_ours(std::pair{"OPTIONS3", D3D12_FEATURE_D3D12_OPTIONS3}, o3); 2301 query_ours(std::pair{"OPTIONS3", D3D12_FEATURE_D3D12_OPTIONS3}, o3);
@@ -2252,14 +2310,14 @@ int compare_feature_options(ID3D12Device* ours, const rt::d3d12::VulkanDeviceInf
2252 query_ours(std::pair{"OPTIONS16", D3D12_FEATURE_D3D12_OPTIONS16}, o16); 2310 query_ours(std::pair{"OPTIONS16", D3D12_FEATURE_D3D12_OPTIONS16}, o16);
2253 query_ours(std::pair{"OPTIONS18", D3D12_FEATURE_D3D12_OPTIONS18}, o18); 2311 query_ours(std::pair{"OPTIONS18", D3D12_FEATURE_D3D12_OPTIONS18}, o18);
2254 query_ours(std::pair{"OPTIONS19", D3D12_FEATURE_D3D12_OPTIONS19}, o19); 2312 query_ours(std::pair{"OPTIONS19", D3D12_FEATURE_D3D12_OPTIONS19}, o19);
2255 query_ours(std::pair{"OPTIONS20", D3D12_FEATURE_D3D12_OPTIONS20}, o20); 2313 query_ours(std::pair{"OPTIONS20", rt::d3d12::compat::kFeatureOptions20}, o20);
2256 query_ours(std::pair{"OPTIONS21", D3D12_FEATURE_D3D12_OPTIONS21}, o21); 2314 query_ours(std::pair{"OPTIONS21", rt::d3d12::compat::kFeatureOptions21}, o21);
2257 2315
2258 D3D12_FEATURE_DATA_SHADER_CACHE shader_cache{}; 2316 D3D12_FEATURE_DATA_SHADER_CACHE shader_cache{};
2259 D3D12_FEATURE_DATA_EXISTING_HEAPS existing_heaps{}; 2317 D3D12_FEATURE_DATA_EXISTING_HEAPS existing_heaps{};
2260 D3D12_FEATURE_DATA_CROSS_NODE cross_node{}; 2318 D3D12_FEATURE_DATA_CROSS_NODE cross_node{};
2261 D3D12_FEATURE_DATA_DISPLAYABLE displayable{}; 2319 D3D12_FEATURE_DATA_DISPLAYABLE displayable{};
2262 D3D12_FEATURE_DATA_PREDICATION predication{}; 2320 rt::d3d12::compat::FeatureSupportFlag predication{};
2263 rt::d3d12::compat::FeatureSupportFlag driver_state{}; 2321 rt::d3d12::compat::FeatureSupportFlag driver_state{};
2264 rt::d3d12::compat::FeatureSupportFlag bypass_hash{}; 2322 rt::d3d12::compat::FeatureSupportFlag bypass_hash{};
2265 D3D12_FEATURE_DATA_PROTECTED_RESOURCE_SESSION_SUPPORT prot_support{}; 2323 D3D12_FEATURE_DATA_PROTECTED_RESOURCE_SESSION_SUPPORT prot_support{};
@@ -2272,7 +2330,7 @@ int compare_feature_options(ID3D12Device* ours, const rt::d3d12::VulkanDeviceInf
2272 query_ours(std::pair{"EXISTING_HEAPS", D3D12_FEATURE_EXISTING_HEAPS}, existing_heaps); 2330 query_ours(std::pair{"EXISTING_HEAPS", D3D12_FEATURE_EXISTING_HEAPS}, existing_heaps);
2273 query_ours(std::pair{"CROSS_NODE", D3D12_FEATURE_CROSS_NODE}, cross_node); 2331 query_ours(std::pair{"CROSS_NODE", D3D12_FEATURE_CROSS_NODE}, cross_node);
2274 query_ours(std::pair{"DISPLAYABLE", D3D12_FEATURE_DISPLAYABLE}, displayable); 2332 query_ours(std::pair{"DISPLAYABLE", D3D12_FEATURE_DISPLAYABLE}, displayable);
2275 query_ours(std::pair{"PREDICATION", D3D12_FEATURE_PREDICATION}, predication); 2333 query_ours(std::pair{"PREDICATION", rt::d3d12::compat::kFeaturePredication}, predication);
2276 query_ours(std::pair{"APPLICATION_SPECIFIC_DRIVER_STATE", 2334 query_ours(std::pair{"APPLICATION_SPECIFIC_DRIVER_STATE",
2277 rt::d3d12::compat::kFeatureApplicationSpecificDriverState}, 2335 rt::d3d12::compat::kFeatureApplicationSpecificDriverState},
2278 driver_state); 2336 driver_state);
@@ -2341,11 +2399,11 @@ int compare_feature_options(ID3D12Device* ours, const rt::d3d12::VulkanDeviceInf
2341 o19.MaxViewDescriptorHeapSize != D3D12_MAX_SHADER_VISIBLE_DESCRIPTOR_HEAP_SIZE_TIER_2 || 2399 o19.MaxViewDescriptorHeapSize != D3D12_MAX_SHADER_VISIBLE_DESCRIPTOR_HEAP_SIZE_TIER_2 ||
2342 o19.ComputeOnlyCustomHeapSupported) 2400 o19.ComputeOnlyCustomHeapSupported)
2343 fail("OPTIONS19 mismatch"); 2401 fail("OPTIONS19 mismatch");
2344 if (o20.ComputeOnlyWriteWatchSupported || o20.RecreateAtTier != D3D12_RECREATE_AT_TIER_NOT_SUPPORTED) 2402 if (o20.ComputeOnlyWriteWatchSupported || o20.RecreateAtTier != rt::d3d12::compat::kRecreateAtTierNotSupported)
2345 fail("OPTIONS20 unexpected support"); 2403 fail("OPTIONS20 unexpected support");
2346 if (o21.WorkGraphsTier != D3D12_WORK_GRAPHS_TIER_NOT_SUPPORTED || 2404 if (o21.WorkGraphsTier != rt::d3d12::compat::kWorkGraphsTierNotSupported ||
2347 o21.ExecuteIndirectTier != D3D12_EXECUTE_INDIRECT_TIER_1_0 || o21.SampleCmpGradientAndBiasSupported || 2405 o21.ExecuteIndirectTier != rt::d3d12::compat::kExecuteIndirectTier1_0 ||
2348 o21.ExtendedCommandInfoSupported) 2406 o21.SampleCmpGradientAndBiasSupported || o21.ExtendedCommandInfoSupported)
2349 fail("OPTIONS21 unexpected support"); 2407 fail("OPTIONS21 unexpected support");
2350 2408
2351 // Verify OPTIONS19.AnisoFilterWithPointMipSupported follows VulkanDeviceInfo::sampler_anisotropy. 2409 // Verify OPTIONS19.AnisoFilterWithPointMipSupported follows VulkanDeviceInfo::sampler_anisotropy.
@@ -2448,8 +2506,9 @@ int compare_feature_options(ID3D12Device* ours, const rt::d3d12::VulkanDeviceInf
2448 if (FAILED(rt::d3d12::create_vulkan_device(no_pred_info, IID_PPV_ARGS(&no_pred.p)))) { 2506 if (FAILED(rt::d3d12::create_vulkan_device(no_pred_info, IID_PPV_ARGS(&no_pred.p)))) {
2449 fail("failed to create conditional_rendering=false device"); 2507 fail("failed to create conditional_rendering=false device");
2450 } else { 2508 } else {
2451 D3D12_FEATURE_DATA_PREDICATION pred_off{TRUE}; 2509 rt::d3d12::compat::FeatureSupportFlag pred_off{TRUE};
2452 if (FAILED(no_pred->CheckFeatureSupport(D3D12_FEATURE_PREDICATION, &pred_off, sizeof(pred_off))) || 2510 if (FAILED(no_pred->CheckFeatureSupport(rt::d3d12::compat::kFeaturePredication, &pred_off,
2511 sizeof(pred_off))) ||
2453 pred_off.Supported != FALSE) 2512 pred_off.Supported != FALSE)
2454 fail("PREDICATION did not become FALSE when conditional_rendering is off"); 2513 fail("PREDICATION did not become FALSE when conditional_rendering is off");
2455 } 2514 }
@@ -2629,13 +2688,13 @@ int compare_feature_options(ID3D12Device* ours, const rt::d3d12::VulkanDeviceInf
2629 check_bool(n, "ComputeOnlyCustomHeapSupported", a.ComputeOnlyCustomHeapSupported, 2688 check_bool(n, "ComputeOnlyCustomHeapSupported", a.ComputeOnlyCustomHeapSupported,
2630 b.ComputeOnlyCustomHeapSupported); 2689 b.ComputeOnlyCustomHeapSupported);
2631 }); 2690 });
2632 compare_host("OPTIONS20", D3D12_FEATURE_D3D12_OPTIONS20, o20, 2691 compare_host("OPTIONS20", rt::d3d12::compat::kFeatureOptions20, o20,
2633 [&](const char* n, const auto& a, const auto& b) { 2692 [&](const char* n, const auto& a, const auto& b) {
2634 check_bool(n, "ComputeOnlyWriteWatchSupported", a.ComputeOnlyWriteWatchSupported, 2693 check_bool(n, "ComputeOnlyWriteWatchSupported", a.ComputeOnlyWriteWatchSupported,
2635 b.ComputeOnlyWriteWatchSupported); 2694 b.ComputeOnlyWriteWatchSupported);
2636 check_tier(n, "RecreateAtTier", int(a.RecreateAtTier), int(b.RecreateAtTier)); 2695 check_tier(n, "RecreateAtTier", int(a.RecreateAtTier), int(b.RecreateAtTier));
2637 }); 2696 });
2638 compare_host("OPTIONS21", D3D12_FEATURE_D3D12_OPTIONS21, o21, 2697 compare_host("OPTIONS21", rt::d3d12::compat::kFeatureOptions21, o21,
2639 [&](const char* n, const auto& a, const auto& b) { 2698 [&](const char* n, const auto& a, const auto& b) {
2640 check_tier(n, "WorkGraphsTier", int(a.WorkGraphsTier), int(b.WorkGraphsTier)); 2699 check_tier(n, "WorkGraphsTier", int(a.WorkGraphsTier), int(b.WorkGraphsTier));
2641 check_tier(n, "ExecuteIndirectTier", int(a.ExecuteIndirectTier), int(b.ExecuteIndirectTier)); 2700 check_tier(n, "ExecuteIndirectTier", int(a.ExecuteIndirectTier), int(b.ExecuteIndirectTier));
@@ -2666,7 +2725,7 @@ int compare_feature_options(ID3D12Device* ours, const rt::d3d12::VulkanDeviceInf
2666 check_tier(n, "SharedResourceCompatibilityTier", int(a.SharedResourceCompatibilityTier), 2725 check_tier(n, "SharedResourceCompatibilityTier", int(a.SharedResourceCompatibilityTier),
2667 int(b.SharedResourceCompatibilityTier)); 2726 int(b.SharedResourceCompatibilityTier));
2668 }); 2727 });
2669 compare_host("PREDICATION", D3D12_FEATURE_PREDICATION, predication, 2728 compare_host("PREDICATION", rt::d3d12::compat::kFeaturePredication, predication,
2670 [&](const char* n, const auto& a, const auto& b) { 2729 [&](const char* n, const auto& a, const auto& b) {
2671 check_bool(n, "Supported", a.Supported, b.Supported); 2730 check_bool(n, "Supported", a.Supported, b.Supported);
2672 }); 2731 });
@@ -2883,6 +2942,35 @@ HRESULT fence(ID3D12Device* device, D3D12_FENCE_FLAGS flags, REFIID riid = __uui
2883 return released(device->CreateFence(0, flags, riid, &out), &out); 2942 return released(device->CreateFence(0, flags, riid, &out), &out);
2884} 2943}
2885 2944
2945HRESULT command_allocator(ID3D12Device* device, D3D12_COMMAND_LIST_TYPE type, bool output = true,
2946 REFIID riid = __uuidof(ID3D12CommandAllocator)) {
2947 void* out = nullptr;
2948 return released(device->CreateCommandAllocator(type, riid, output ? &out : nullptr), &out);
2949}
2950
2951// CreateCommandList with a fresh allocator of `allocator_type` (or none when it is -2).
2952HRESULT command_list(ID3D12Device* device, UINT node_mask, D3D12_COMMAND_LIST_TYPE type,
2953 int allocator_type, bool output = true) {
2954 void* allocator = nullptr;
2955 if (allocator_type != -2)
2956 device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE(allocator_type), __uuidof(ID3D12CommandAllocator),
2957 &allocator);
2958 void* out = nullptr;
2959 const HRESULT hr = device->CreateCommandList(node_mask, type, static_cast<ID3D12CommandAllocator*>(allocator),
2960 nullptr, __uuidof(ID3D12GraphicsCommandList), output ? &out : nullptr);
2961 released(S_OK, &allocator);
2962 return released(hr, &out);
2963}
2964
2965HRESULT command_list1(ID3D12Device* device, UINT node_mask, D3D12_COMMAND_LIST_TYPE type, bool output = true) {
2966 Ref<ID3D12Device4> device4;
2967 if (FAILED(device->QueryInterface(IID_PPV_ARGS(&device4.p)))) return E_NOINTERFACE;
2968 void* out = nullptr;
2969 return released(device4->CreateCommandList1(node_mask, type, D3D12_COMMAND_LIST_FLAG_NONE,
2970 __uuidof(ID3D12GraphicsCommandList), output ? &out : nullptr),
2971 &out);
2972}
2973
2886// A 64 KiB heap description for the CreateHeap cases (D3D-238). 2974// A 64 KiB heap description for the CreateHeap cases (D3D-238).
2887D3D12_HEAP_DESC heap_desc_of(UINT64 alignment, D3D12_HEAP_PROPERTIES properties = {D3D12_HEAP_TYPE_DEFAULT}, 2975D3D12_HEAP_DESC heap_desc_of(UINT64 alignment, D3D12_HEAP_PROPERTIES properties = {D3D12_HEAP_TYPE_DEFAULT},
2888 D3D12_HEAP_FLAGS flags = D3D12_HEAP_FLAG_NONE, UINT64 size = 64 * 1024) { 2976 D3D12_HEAP_FLAGS flags = D3D12_HEAP_FLAG_NONE, UINT64 size = 64 * 1024) {
@@ -2977,6 +3065,19 @@ bool host_ray_tracing(ID3D12Device* host) {
2977 o5.RaytracingTier != D3D12_RAYTRACING_TIER_NOT_SUPPORTED; 3065 o5.RaytracingTier != D3D12_RAYTRACING_TIER_NOT_SUPPORTED;
2978} 3066}
2979 3067
3068// Windows 10's runtime (no ID3D12Device10) still checks a buffer's initial state and refuses a HARDWARE_PROTECTED
3069// heap, where newer runtimes and the layer accept them (measured on Windows 10 22H2 build 19045.5737). For a case
3070// marked windows10_refuses only that pair is excused: the layer's S_OK against the host's E_INVALIDARG, on a host
3071// without ID3D12Device10. Any other difference, and any difference on a newer host, is still a mismatch.
3072bool windows10_refusal(const char* name, ID3D12Device* host, HRESULT ours, HRESULT theirs) {
3073 if (ours != S_OK || theirs != E_INVALIDARG) return false;
3074 Ref<ID3D12Device10> newer;
3075 if (SUCCEEDED(host->QueryInterface(IID_PPV_ARGS(&newer.p)))) return false;
3076 std::printf("invalid arguments %s: Windows 10's runtime refuses it (ours 0x%08lx, host 0x%08lx)\n", name, ours,
3077 theirs);
3078 return true;
3079}
3080
2980int compare_invalid_arguments(ID3D12Device* ours) { 3081int compare_invalid_arguments(ID3D12Device* ours) {
2981 Ref<ID3D12Device> host; 3082 Ref<ID3D12Device> host;
2982 if (!create_host_device(host)) return -1; 3083 if (!create_host_device(host)) return -1;
@@ -2985,6 +3086,7 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2985 const char* name; 3086 const char* name;
2986 InvalidCase call; 3087 InvalidCase call;
2987 bool (*comparable)(ID3D12Device*) = nullptr; 3088 bool (*comparable)(ID3D12Device*) = nullptr;
3089 bool windows10_refuses = false;
2988 }; 3090 };
2989 const auto device10 = [](ID3D12Device* d) { 3091 const auto device10 = [](ID3D12Device* d) {
2990 Ref<ID3D12Device10> newer; 3092 Ref<ID3D12Device10> newer;
@@ -3094,13 +3196,14 @@ int compare_invalid_arguments(ID3D12Device* ours) {
3094 {"committed: texture in RESOLVE_DEST state", [](ID3D12Device* d) { 3196 {"committed: texture in RESOLVE_DEST state", [](ID3D12Device* d) {
3095 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, rgba8(), D3D12_RESOURCE_STATE_RESOLVE_DEST); 3197 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, rgba8(), D3D12_RESOURCE_STATE_RESOLVE_DEST);
3096 }}, 3198 }},
3199 // A buffer's initial state: Windows 10's runtime refuses these two, newer ones accept them, as the layer does.
3097 {"committed: buffer in state 0x80000000", [](ID3D12Device* d) { 3200 {"committed: buffer in state 0x80000000", [](ID3D12Device* d) {
3098 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, buffer_desc(256), D3D12_RESOURCE_STATES(0x80000000u)); 3201 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, buffer_desc(256), D3D12_RESOURCE_STATES(0x80000000u));
3099 }}, 3202 }, nullptr, true},
3100 {"committed: buffer in RENDER_TARGET | UNORDERED_ACCESS state", [](ID3D12Device* d) { 3203 {"committed: buffer in RENDER_TARGET | UNORDERED_ACCESS state", [](ID3D12Device* d) {
3101 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, buffer_desc(256), 3204 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, buffer_desc(256),
3102 D3D12_RESOURCE_STATE_RENDER_TARGET | D3D12_RESOURCE_STATE_UNORDERED_ACCESS); 3205 D3D12_RESOURCE_STATE_RENDER_TARGET | D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
3103 }}, 3206 }, nullptr, true},
3104 {"committed: buffer in RAYTRACING_ACCELERATION_STRUCTURE state", [](ID3D12Device* d) { 3207 {"committed: buffer in RAYTRACING_ACCELERATION_STRUCTURE state", [](ID3D12Device* d) {
3105 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, buffer_desc(256), 3208 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, buffer_desc(256),
3106 D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE); 3209 D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE);
@@ -3835,6 +3938,98 @@ int compare_invalid_arguments(ID3D12Device* ours) {
3835 {"command queue: high priority", [](ID3D12Device* d) { 3938 {"command queue: high priority", [](ID3D12Device* d) {
3836 return command_queue(d, {D3D12_COMMAND_LIST_TYPE_DIRECT, D3D12_COMMAND_QUEUE_PRIORITY_HIGH}); 3939 return command_queue(d, {D3D12_COMMAND_LIST_TYPE_DIRECT, D3D12_COMMAND_QUEUE_PRIORITY_HIGH});
3837 }}, 3940 }},
3941 // Command allocators and lists (video list types are only created here, not compared: the host hands out
3942 // a video list, which is not an ID3D12GraphicsCommandList). Types past VIDEO_ENCODE and nodes other than 0
3943 // are refused first; a null output is then E_UNEXPECTED.
3944 {"command allocator: type direct", [](ID3D12Device* d) {
3945 return command_allocator(d, D3D12_COMMAND_LIST_TYPE(0));
3946 }},
3947 {"command allocator: type bundle", [](ID3D12Device* d) {
3948 return command_allocator(d, D3D12_COMMAND_LIST_TYPE(1));
3949 }},
3950 {"command allocator: type compute", [](ID3D12Device* d) {
3951 return command_allocator(d, D3D12_COMMAND_LIST_TYPE(2));
3952 }},
3953 {"command allocator: type copy", [](ID3D12Device* d) {
3954 return command_allocator(d, D3D12_COMMAND_LIST_TYPE(3));
3955 }},
3956 {"command allocator: type video encode", [](ID3D12Device* d) {
3957 return command_allocator(d, D3D12_COMMAND_LIST_TYPE(6));
3958 }},
3959 {"command allocator: type 7", [](ID3D12Device* d) { return command_allocator(d, D3D12_COMMAND_LIST_TYPE(7)); }},
3960 {"command allocator: type 99", [](ID3D12Device* d) {
3961 return command_allocator(d, D3D12_COMMAND_LIST_TYPE(99));
3962 }},
3963 {"command allocator: type -1", [](ID3D12Device* d) {
3964 return command_allocator(d, D3D12_COMMAND_LIST_TYPE(-1));
3965 }},
3966 {"command allocator: null output", [](ID3D12Device* d) {
3967 return command_allocator(d, D3D12_COMMAND_LIST_TYPE_DIRECT, false);
3968 }},
3969 {"command allocator: null output, type 99", [](ID3D12Device* d) {
3970 return command_allocator(d, D3D12_COMMAND_LIST_TYPE(99), false);
3971 }},
3972 {"command allocator: null output, wrong interface", [](ID3D12Device* d) {
3973 return command_allocator(d, D3D12_COMMAND_LIST_TYPE_DIRECT, false, __uuidof(ID3D12Fence));
3974 }},
3975 {"command allocator: wrong interface", [](ID3D12Device* d) {
3976 return command_allocator(d, D3D12_COMMAND_LIST_TYPE_DIRECT, true, __uuidof(ID3D12Fence));
3977 }},
3978 {"command list: direct", [](ID3D12Device* d) { return command_list(d, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, 0); }},
3979 {"command list: bundle", [](ID3D12Device* d) { return command_list(d, 0, D3D12_COMMAND_LIST_TYPE_BUNDLE, 1); }},
3980 {"command list: node mask 1", [](ID3D12Device* d) {
3981 return command_list(d, 1, D3D12_COMMAND_LIST_TYPE_DIRECT, 0);
3982 }},
3983 {"command list: node mask 2", [](ID3D12Device* d) {
3984 return command_list(d, 2, D3D12_COMMAND_LIST_TYPE_DIRECT, 0);
3985 }},
3986 {"command list: node mask 3", [](ID3D12Device* d) {
3987 return command_list(d, 3, D3D12_COMMAND_LIST_TYPE_DIRECT, 0);
3988 }},
3989 {"command list: compute allocator", [](ID3D12Device* d) {
3990 return command_list(d, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, 2);
3991 }},
3992 {"command list: no allocator", [](ID3D12Device* d) {
3993 return command_list(d, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, -2);
3994 }},
3995 {"command list: type 99", [](ID3D12Device* d) { return command_list(d, 0, D3D12_COMMAND_LIST_TYPE(99), 0); }},
3996 {"command list: null output", [](ID3D12Device* d) {
3997 return command_list(d, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, 0, false);
3998 }},
3999 {"command list: null output, node mask 2", [](ID3D12Device* d) {
4000 return command_list(d, 2, D3D12_COMMAND_LIST_TYPE_DIRECT, 0, false);
4001 }},
4002 {"command list: null output, no allocator", [](ID3D12Device* d) {
4003 return command_list(d, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, -2, false);
4004 }},
4005 {"command list1: type direct", [](ID3D12Device* d) { return command_list1(d, 0, D3D12_COMMAND_LIST_TYPE(0)); }},
4006 {"command list1: type bundle", [](ID3D12Device* d) { return command_list1(d, 0, D3D12_COMMAND_LIST_TYPE(1)); }},
4007 {"command list1: type compute", [](ID3D12Device* d) {
4008 return command_list1(d, 0, D3D12_COMMAND_LIST_TYPE(2));
4009 }},
4010 {"command list1: type copy", [](ID3D12Device* d) { return command_list1(d, 0, D3D12_COMMAND_LIST_TYPE(3)); }},
4011 {"command list1: type 7", [](ID3D12Device* d) { return command_list1(d, 0, D3D12_COMMAND_LIST_TYPE(7)); }},
4012 {"command list1: type 99", [](ID3D12Device* d) { return command_list1(d, 0, D3D12_COMMAND_LIST_TYPE(99)); }},
4013 // NONE (-1): Windows 10's runtime (19045, no ID3D12Device10) creates the list and Windows 11's refuses it
4014 // (measured on #2297), so it is compared only on a host with ID3D12Device10.
4015 {"command list1: type -1", [](ID3D12Device* d) {
4016 return command_list1(d, 0, D3D12_COMMAND_LIST_TYPE(-1));
4017 }, +device10},
4018 {"command list1: node mask 1", [](ID3D12Device* d) {
4019 return command_list1(d, 1, D3D12_COMMAND_LIST_TYPE_DIRECT);
4020 }},
4021 {"command list1: node mask 2", [](ID3D12Device* d) {
4022 return command_list1(d, 2, D3D12_COMMAND_LIST_TYPE_DIRECT);
4023 }},
4024 {"command list1: null output", [](ID3D12Device* d) {
4025 return command_list1(d, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, false);
4026 }},
4027 {"command list1: null output, node mask 2", [](ID3D12Device* d) {
4028 return command_list1(d, 2, D3D12_COMMAND_LIST_TYPE_DIRECT, false);
4029 }},
4030 {"command list1: null output, type 99", [](ID3D12Device* d) {
4031 return command_list1(d, 0, D3D12_COMMAND_LIST_TYPE(99), false);
4032 }},
3838 // CreateCommandSignature (no root signature). A null description faults in the host runtime, so it is not 4033 // CreateCommandSignature (no root signature). A null description faults in the host runtime, so it is not
3839 // compared. 4034 // compared.
3840 {"command signature: null output", [](ID3D12Device* d) { 4035 {"command signature: null output", [](ID3D12Device* d) {
@@ -4004,6 +4199,7 @@ int compare_invalid_arguments(ID3D12Device* ours) {
4004 const HRESULT a = call_guarded(c.call, ours), b = call_guarded(c.call, host.p); 4199 const HRESULT a = call_guarded(c.call, ours), b = call_guarded(c.call, host.p);
4005 if (verbose) std::printf(" ours 0x%08lx host 0x%08lx\n", a, b); 4200 if (verbose) std::printf(" ours 0x%08lx host 0x%08lx\n", a, b);
4006 if (a == b) continue; 4201 if (a == b) continue;
4202 if (c.windows10_refuses && windows10_refusal(c.name, host.p, a, b)) continue;
4007 if (c.comparable && !c.comparable(host.p)) { 4203 if (c.comparable && !c.comparable(host.p)) {
4008 std::printf("invalid arguments %s: not comparable on this host (ours 0x%08lx, host 0x%08lx)\n", c.name, 4204 std::printf("invalid arguments %s: not comparable on this host (ours 0x%08lx, host 0x%08lx)\n", c.name,
4009 a, b); 4205 a, b);
@@ -4074,6 +4270,7 @@ int compare_heap_neighbours(ID3D12Device* ours) {
4074 struct Case { 4270 struct Case {
4075 const char* name; 4271 const char* name;
4076 InvalidCase call; 4272 InvalidCase call;
4273 bool windows10_refuses = false;
4077 }; 4274 };
4078 static const Case cases[] = { 4275 static const Case cases[] = {
4079 {"heap: alignment 0", [](ID3D12Device* d) { return heap_create(d, heap_desc_of(0)); }}, 4276 {"heap: alignment 0", [](ID3D12Device* d) { return heap_create(d, heap_desc_of(0)); }},
@@ -4100,15 +4297,16 @@ int compare_heap_neighbours(ID3D12Device* ours) {
4100 return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT}, D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS)); 4297 return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT}, D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS));
4101 }}, 4298 }},
4102 // The D3D12_HEAP_FLAGS documentation calls it unsupported, but the host accepts it (RTX 4070 SUPER and 4299 // The D3D12_HEAP_FLAGS documentation calls it unsupported, but the host accepts it (RTX 4070 SUPER and
4103 // UHD 770, @CowBoYdu76). 4300 // UHD 770, @CowBoYdu76). Windows 10's runtime refuses it, as it refuses the committed case above.
4104 {"heap: HARDWARE_PROTECTED", [](ID3D12Device* d) { 4301 {"heap: HARDWARE_PROTECTED", [](ID3D12Device* d) {
4105 return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT}, D3D12_HEAP_FLAG_HARDWARE_PROTECTED)); 4302 return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT}, D3D12_HEAP_FLAG_HARDWARE_PROTECTED));
4106 }}, 4303 }, true},
4107 }; 4304 };
4108 int mismatches = 0; 4305 int mismatches = 0;
4109 for (const Case& c : cases) { 4306 for (const Case& c : cases) {
4110 const HRESULT a = call_guarded(c.call, ours), b = call_guarded(c.call, host.p); 4307 const HRESULT a = call_guarded(c.call, ours), b = call_guarded(c.call, host.p);
4111 if (a == b) continue; 4308 if (a == b) continue;
4309 if (c.windows10_refuses && windows10_refusal(c.name, host.p, a, b)) continue;
4112 ++mismatches; 4310 ++mismatches;
4113 std::fprintf(stderr, "invalid arguments %s: ours 0x%08lx, host 0x%08lx\n", c.name, a, b); 4311 std::fprintf(stderr, "invalid arguments %s: ours 0x%08lx, host 0x%08lx\n", c.name, a, b);
4114 } 4312 }
@@ -4126,6 +4324,7 @@ int compare_placed_reserved(ID3D12Device* ours) {
4126 const char* name; 4324 const char* name;
4127 InvalidCase call; 4325 InvalidCase call;
4128 bool (*comparable)(ID3D12Device*) = nullptr; 4326 bool (*comparable)(ID3D12Device*) = nullptr;
4327 bool windows10_refuses = false;
4129 }; 4328 };
4130 static const Case cases[] = { 4329 static const Case cases[] = {
4131 // The standalone device has acceleration structures (XDXR, or KHR with LEONIDA_RT_AS=khr) and accepts a UAV 4330 // The standalone device has acceleration structures (XDXR, or KHR with LEONIDA_RT_AS=khr) and accepts a UAV
@@ -4339,7 +4538,7 @@ int compare_placed_reserved(ID3D12Device* ours) {
4339 a.heap.Properties.Type = D3D12_HEAP_TYPE_UPLOAD; 4538 a.heap.Properties.Type = D3D12_HEAP_TYPE_UPLOAD;
4340 a.state = D3D12_RESOURCE_STATE_COPY_DEST; 4539 a.state = D3D12_RESOURCE_STATE_COPY_DEST;
4341 return placed(d, buffer_desc(256), a); 4540 return placed(d, buffer_desc(256), a);
4342 }}, 4541 }, nullptr, true},
4343 {"placed: upload buffer with ALLOW_UNORDERED_ACCESS", [](ID3D12Device* d) { 4542 {"placed: upload buffer with ALLOW_UNORDERED_ACCESS", [](ID3D12Device* d) {
4344 auto desc = buffer_desc(256); 4543 auto desc = buffer_desc(256);
4345 desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; 4544 desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
@@ -4359,12 +4558,12 @@ int compare_placed_reserved(ID3D12Device* ours) {
4359 a.heap.Properties.Type = D3D12_HEAP_TYPE_READBACK; 4558 a.heap.Properties.Type = D3D12_HEAP_TYPE_READBACK;
4360 a.state = D3D12_RESOURCE_STATE_GENERIC_READ; 4559 a.state = D3D12_RESOURCE_STATE_GENERIC_READ;
4361 return placed(d, buffer_desc(256), a); 4560 return placed(d, buffer_desc(256), a);
4362 }}, 4561 }, nullptr, true},
4363 {"placed: default buffer in state 0x80000000", [](ID3D12Device* d) { 4562 {"placed: default buffer in state 0x80000000", [](ID3D12Device* d) {
4364 PlacedArgs a; 4563 PlacedArgs a;
4365 a.state = D3D12_RESOURCE_STATES(0x80000000u); 4564 a.state = D3D12_RESOURCE_STATES(0x80000000u);
4366 return placed(d, buffer_desc(256), a); 4565 return placed(d, buffer_desc(256), a);
4367 }}, 4566 }, nullptr, true},
4368 {"placed: depth texture in DEPTH_WRITE", [](ID3D12Device* d) { 4567 {"placed: depth texture in DEPTH_WRITE", [](ID3D12Device* d) {
4369 PlacedArgs a; 4568 PlacedArgs a;
4370 a.state = D3D12_RESOURCE_STATE_DEPTH_WRITE; 4569 a.state = D3D12_RESOURCE_STATE_DEPTH_WRITE;
@@ -4460,7 +4659,7 @@ int compare_placed_reserved(ID3D12Device* ours) {
4460 }}, 4659 }},
4461 {"reserved: buffer in state 0x80000000", [](ID3D12Device* d) { 4660 {"reserved: buffer in state 0x80000000", [](ID3D12Device* d) {
4462 return reserved(d, buffer_desc(64 * 1024), D3D12_RESOURCE_STATES(0x80000000u)); 4661 return reserved(d, buffer_desc(64 * 1024), D3D12_RESOURCE_STATES(0x80000000u));
4463 }}, 4662 }, nullptr, true},
4464 {"reserved: texture", [](ID3D12Device* d) { 4663 {"reserved: texture", [](ID3D12Device* d) {
4465 return reserved(d, tiled(texture_desc(256, 256, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE))); 4664 return reserved(d, tiled(texture_desc(256, 256, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE)));
4466 }}, 4665 }},
@@ -4544,6 +4743,7 @@ int compare_placed_reserved(ID3D12Device* ours) {
4544 const HRESULT a = call_guarded(c.call, ours), b = call_guarded(c.call, host.p); 4743 const HRESULT a = call_guarded(c.call, ours), b = call_guarded(c.call, host.p);
4545 if (verbose) std::printf(" ours 0x%08lx host 0x%08lx\n", a, b); 4744 if (verbose) std::printf(" ours 0x%08lx host 0x%08lx\n", a, b);
4546 if (a == b) continue; 4745 if (a == b) continue;
4746 if (c.windows10_refuses && windows10_refusal(c.name, host.p, a, b)) continue;
4547 if (c.comparable && !c.comparable(host.p)) { 4747 if (c.comparable && !c.comparable(host.p)) {
4548 std::printf("invalid arguments %s: not comparable on this host (ours 0x%08lx, host 0x%08lx)\n", c.name, 4748 std::printf("invalid arguments %s: not comparable on this host (ours 0x%08lx, host 0x%08lx)\n", c.name,
4549 a, b); 4749 a, b);
@@ -5284,7 +5484,9 @@ int main() {
5284 EXPECT(SUCCEEDED(device->QueryInterface(IID_PPV_ARGS(&device1.p)))); 5484 EXPECT(SUCCEEDED(device->QueryInterface(IID_PPV_ARGS(&device1.p))));
5285 const D3D12_RESIDENCY_PRIORITY priorities[] = {D3D12_RESIDENCY_PRIORITY_MAXIMUM, 5485 const D3D12_RESIDENCY_PRIORITY priorities[] = {D3D12_RESIDENCY_PRIORITY_MAXIMUM,
5286 D3D12_RESIDENCY_PRIORITY(D3D12_RESIDENCY_PRIORITY_LOW + 5)}; 5486 D3D12_RESIDENCY_PRIORITY(D3D12_RESIDENCY_PRIORITY_LOW + 5)};
5287 EXPECT(device1->SetResidencyPriority(2, pageables, priorities) == S_OK); 5487 // Only committed resources and heaps take a priority, as on the host runtime (d3d12_residency_test): a
5488 // fence and an allocator don't.
5489 EXPECT(device1->SetResidencyPriority(2, pageables, priorities) == E_INVALIDARG);
5288 EXPECT(device1->SetResidencyPriority(0, nullptr, nullptr) == S_OK); 5490 EXPECT(device1->SetResidencyPriority(0, nullptr, nullptr) == S_OK);
5289 EXPECT(device1->SetResidencyPriority(1, pageables, nullptr) == E_INVALIDARG); 5491 EXPECT(device1->SetResidencyPriority(1, pageables, nullptr) == E_INVALIDARG);
5290 EXPECT(device1->SetResidencyPriority(1, nullptr, priorities) == E_INVALIDARG); 5492 EXPECT(device1->SetResidencyPriority(1, nullptr, priorities) == E_INVALIDARG);
@@ -5296,8 +5498,9 @@ int main() {
5296 EXPECT(device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_DENY_OVERBUDGET, 0, nullptr, residency.p, 9) == 5498 EXPECT(device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_DENY_OVERBUDGET, 0, nullptr, residency.p, 9) ==
5297 S_OK); 5499 S_OK);
5298 EXPECT(residency->GetCompletedValue() == 9); 5500 EXPECT(residency->GetCompletedValue() == 9);
5299 // Refused calls leave the fence alone. 5501 // A null fence is accepted (the host runtime's answer) and signals nothing; refused calls leave the fence
5300 EXPECT(device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, 1, pageables, nullptr, 11) == E_INVALIDARG); 5502 // alone.
5503 EXPECT(device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, 1, pageables, nullptr, 11) == S_OK);
5301 EXPECT(device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, 1, nullptr, residency.p, 11) == 5504 EXPECT(device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, 1, nullptr, residency.p, 11) ==
5302 E_INVALIDARG); 5505 E_INVALIDARG);
5303 EXPECT(device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAGS(0x2), 1, pageables, residency.p, 11) == 5506 EXPECT(device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAGS(0x2), 1, pageables, residency.p, 11) ==
@@ -6271,7 +6474,7 @@ int main() {
6271 UINT64 frequency = 0; 6474 UINT64 frequency = 0;
6272 EXPECT(SUCCEEDED(queue->GetTimestampFrequency(&frequency)) && frequency >= 1'000'000); 6475 EXPECT(SUCCEEDED(queue->GetTimestampFrequency(&frequency)) && frequency >= 1'000'000);
6273 EXPECT(queue->GetTimestampFrequency(nullptr) == E_INVALIDARG); 6476 EXPECT(queue->GetTimestampFrequency(nullptr) == E_INVALIDARG);
6274 Ref<ID3D12QueryHeap> occlusion, timestamps, statistics, refused; 6477 Ref<ID3D12QueryHeap> occlusion, timestamps, statistics, so, refused;
6275 D3D12_QUERY_HEAP_DESC query_desc{D3D12_QUERY_HEAP_TYPE_OCCLUSION, 4, 0}; 6478 D3D12_QUERY_HEAP_DESC query_desc{D3D12_QUERY_HEAP_TYPE_OCCLUSION, 4, 0};
6276 EXPECT(SUCCEEDED(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(&occlusion.p)))); 6479 EXPECT(SUCCEEDED(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(&occlusion.p))));
6277 // A null output is E_UNEXPECTED, as on the host runtime (compare_invalid_arguments, "query heap:"). 6480 // A null output is E_UNEXPECTED, as on the host runtime (compare_invalid_arguments, "query heap:").
@@ -6284,16 +6487,20 @@ int main() {
6284 EXPECT(SUCCEEDED(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(&timestamps.p)))); 6487 EXPECT(SUCCEEDED(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(&timestamps.p))));
6285 query_desc = {D3D12_QUERY_HEAP_TYPE_OCCLUSION, 0, 0}; 6488 query_desc = {D3D12_QUERY_HEAP_TYPE_OCCLUSION, 0, 0};
6286 EXPECT(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(&refused.p)) == E_INVALIDARG && !refused.p); 6489 EXPECT(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(&refused.p)) == E_INVALIDARG && !refused.p);
6287 query_desc = {D3D12_QUERY_HEAP_TYPE_SO_STATISTICS, 1, 0}; // no stream output path yet 6490 // The layer has no stream output, so stream-output statistics heaps are made without a Vulkan pool and
6288 EXPECT(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(&refused.p)) == E_NOTIMPL && !refused.p); 6491 // every query reads zero (D3D-302).
6492 query_desc = {D3D12_QUERY_HEAP_TYPE_SO_STATISTICS, 3, 0};
6493 EXPECT(SUCCEEDED(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(&so.p))));
6289 query_desc = {D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS, 2, 0}; 6494 query_desc = {D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS, 2, 0};
6290 if (d.pipeline_statistics_query) 6495 if (d.pipeline_statistics_query)
6291 EXPECT(SUCCEEDED(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(&statistics.p)))); 6496 EXPECT(SUCCEEDED(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(&statistics.p))));
6292 else 6497 else
6293 std::printf("pipeline statistics: no pipelineStatisticsQuery, skipped\n"); 6498 std::printf("pipeline statistics: no pipelineStatisticsQuery, skipped\n");
6294 6499
6295 // Readback layout: timestamps at 0, occlusion at 64, statistics at 256, the second run's at 1024. 6500 // Readback layout: timestamps at 0, occlusion at 64, statistics at 256, stream output at 512, the second
6296 constexpr UINT64 ts_at = 0, occlusion_at = 64, statistics_at = 256, again_at = 1024; 6501 // run's at 1024.
6502 constexpr UINT64 ts_at = 0, occlusion_at = 64, statistics_at = 256, so_at = 512, again_at = 1024;
6503 static_assert(sizeof(D3D12_QUERY_DATA_SO_STATISTICS) == 16);
6297 const auto u64 = [&](UINT64 offset) { 6504 const auto u64 = [&](UINT64 offset) {
6298 UINT64 value; 6505 UINT64 value;
6299 std::memcpy(&value, down + offset, sizeof(value)); 6506 std::memcpy(&value, down + offset, sizeof(value));
@@ -6303,15 +6510,21 @@ int main() {
6303 EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, nullptr))); 6510 EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, nullptr)));
6304 list->EndQuery(timestamps.p, D3D12_QUERY_TYPE_TIMESTAMP, 0); 6511 list->EndQuery(timestamps.p, D3D12_QUERY_TYPE_TIMESTAMP, 0);
6305 if (statistics.p) list->BeginQuery(statistics.p, D3D12_QUERY_TYPE_PIPELINE_STATISTICS, 0); 6512 if (statistics.p) list->BeginQuery(statistics.p, D3D12_QUERY_TYPE_PIPELINE_STATISTICS, 0);
6513 // Two streams at once, inside the statistics query and crossing the occlusion one: none of them is a
6514 // Vulkan query, so none overlaps.
6515 list->BeginQuery(so.p, D3D12_QUERY_TYPE_SO_STATISTICS_STREAM0, 0);
6516 list->BeginQuery(so.p, D3D12_QUERY_TYPE_SO_STATISTICS_STREAM3, 1);
6306 // A rectangle clear runs in a render pass inside a query; clears count no samples. 6517 // A rectangle clear runs in a render pass inside a query; clears count no samples.
6307 device->CreateRenderTargetView(rt_resource.p, &rtv_desc, rtv1); // the resolve test reused it 6518 device->CreateRenderTargetView(rt_resource.p, &rtv_desc, rtv1); // the resolve test reused it
6308 list->BeginQuery(occlusion.p, D3D12_QUERY_TYPE_OCCLUSION, 0); 6519 list->BeginQuery(occlusion.p, D3D12_QUERY_TYPE_OCCLUSION, 0);
6309 barrier = transition(rt_resource.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET); 6520 barrier = transition(rt_resource.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET);
6310 list->ResourceBarrier(1, &barrier); 6521 list->ResourceBarrier(1, &barrier);
6311 list->ClearRenderTargetView(rtv1, red, 1, &square); 6522 list->ClearRenderTargetView(rtv1, red, 1, &square);
6523 list->EndQuery(so.p, D3D12_QUERY_TYPE_SO_STATISTICS_STREAM0, 0);
6312 list->EndQuery(occlusion.p, D3D12_QUERY_TYPE_OCCLUSION, 0); 6524 list->EndQuery(occlusion.p, D3D12_QUERY_TYPE_OCCLUSION, 0);
6313 list->BeginQuery(occlusion.p, D3D12_QUERY_TYPE_BINARY_OCCLUSION, 1); 6525 list->BeginQuery(occlusion.p, D3D12_QUERY_TYPE_BINARY_OCCLUSION, 1);
6314 list->CopyBufferRegion(readback.p, 8192, upload.p, 0, 32768); 6526 list->CopyBufferRegion(readback.p, 8192, upload.p, 0, 32768);
6527 list->EndQuery(so.p, D3D12_QUERY_TYPE_SO_STATISTICS_STREAM3, 1);
6315 list->EndQuery(occlusion.p, D3D12_QUERY_TYPE_BINARY_OCCLUSION, 1); 6528 list->EndQuery(occlusion.p, D3D12_QUERY_TYPE_BINARY_OCCLUSION, 1);
6316 if (statistics.p) list->EndQuery(statistics.p, D3D12_QUERY_TYPE_PIPELINE_STATISTICS, 0); 6529 if (statistics.p) list->EndQuery(statistics.p, D3D12_QUERY_TYPE_PIPELINE_STATISTICS, 0);
6317 list->EndQuery(timestamps.p, D3D12_QUERY_TYPE_TIMESTAMP, 1); 6530 list->EndQuery(timestamps.p, D3D12_QUERY_TYPE_TIMESTAMP, 1);
@@ -6322,6 +6535,8 @@ int main() {
6322 if (statistics.p) 6535 if (statistics.p)
6323 list->ResolveQueryData(statistics.p, D3D12_QUERY_TYPE_PIPELINE_STATISTICS, 0, 2, readback.p, 6536 list->ResolveQueryData(statistics.p, D3D12_QUERY_TYPE_PIPELINE_STATISTICS, 0, 2, readback.p,
6324 statistics_at); 6537 statistics_at);
6538 list->ResolveQueryData(so.p, D3D12_QUERY_TYPE_SO_STATISTICS_STREAM0, 0, 1, readback.p, so_at);
6539 list->ResolveQueryData(so.p, D3D12_QUERY_TYPE_SO_STATISTICS_STREAM3, 1, 2, readback.p, so_at + 16); // 2: never
6325 EXPECT(list->Close() == S_OK); 6540 EXPECT(list->Close() == S_OK);
6326 queue->ExecuteCommandLists(1, lists); 6541 queue->ExecuteCommandLists(1, lists);
6327 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); 6542 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
@@ -6334,6 +6549,8 @@ int main() {
6334 for (UINT i = 0; i < 4; ++i) EXPECT(u64(occlusion_at + 8 * i) == 0); 6549 for (UINT i = 0; i < 4; ++i) EXPECT(u64(occlusion_at + 8 * i) == 0);
6335 for (UINT i = 0; statistics.p && i < 22; ++i) EXPECT(u64(statistics_at + 8 * i) == 0); 6550 for (UINT i = 0; statistics.p && i < 22; ++i) EXPECT(u64(statistics_at + 8 * i) == 0);
6336 EXPECT(u64(statistics.p ? statistics_at + 176 : statistics_at) == 0xcdcdcdcdcdcdcdcdull); // not past it 6551 EXPECT(u64(statistics.p ? statistics_at + 176 : statistics_at) == 0xcdcdcdcdcdcdcdcdull); // not past it
6552 for (UINT i = 0; i < 6; ++i) EXPECT(u64(so_at + 8 * i) == 0); // written and needed, three queries
6553 EXPECT(u64(so_at + 48) == 0xcdcdcdcdcdcdcdcdull); // not past them
6337 6554
6338 // A second execution reuses timestamp 0 (reset before it is written again) and resolves timestamp 1, 6555 // A second execution reuses timestamp 0 (reset before it is written again) and resolves timestamp 1,
6339 // which keeps the result of the first execution. 6556 // which keeps the result of the first execution.
@@ -6393,6 +6610,12 @@ int main() {
6393 [&] { list->ResolveQueryData(occlusion.p, D3D12_QUERY_TYPE_OCCLUSION, 3, 2, readback.p, 0); })); 6610 [&] { list->ResolveQueryData(occlusion.p, D3D12_QUERY_TYPE_OCCLUSION, 3, 2, readback.p, 0); }));
6394 EXPECT(refuse(S_OK, R::invalid_query, // a type the heap does not hold 6611 EXPECT(refuse(S_OK, R::invalid_query, // a type the heap does not hold
6395 [&] { list->EndQuery(occlusion.p, D3D12_QUERY_TYPE_TIMESTAMP, 0); })); 6612 [&] { list->EndQuery(occlusion.p, D3D12_QUERY_TYPE_TIMESTAMP, 0); }));
6613 EXPECT(refuse(S_OK, R::invalid_query, [&] { // a stream-output query in an occlusion heap
6614 list->BeginQuery(occlusion.p, D3D12_QUERY_TYPE_SO_STATISTICS_STREAM1, 0);
6615 list->EndQuery(occlusion.p, D3D12_QUERY_TYPE_SO_STATISTICS_STREAM1, 0);
6616 }));
6617 EXPECT(refuse(E_INVALIDARG, R::invalid_query, // a stream-output query begun and never ended
6618 [&] { list->BeginQuery(so.p, D3D12_QUERY_TYPE_SO_STATISTICS_STREAM2, 0); }));
6396 EXPECT(refuse(S_OK, R::invalid_query, // into a texture 6619 EXPECT(refuse(S_OK, R::invalid_query, // into a texture
6397 [&] { list->ResolveQueryData(timestamps.p, D3D12_QUERY_TYPE_TIMESTAMP, 0, 1, rt_resource.p, 0); })); 6620 [&] { list->ResolveQueryData(timestamps.p, D3D12_QUERY_TYPE_TIMESTAMP, 0, 1, rt_resource.p, 0); }));
6398 EXPECT(refuse(S_OK, R::invalid_query, // past the end of the buffer 6621 EXPECT(refuse(S_OK, R::invalid_query, // past the end of the buffer
@@ -6498,6 +6721,45 @@ int main() {
6498 } 6721 }
6499 } 6722 }
6500 6723
6724 // D3D-71: a default-heap buffer outside the arena (this device has none) starts zeroed, as D3D12 committed
6725 // resources do. Its memory is first dirtied through an earlier buffer, which is then released so the next
6726 // allocation is likely to reuse it. CREATE_NOT_ZEROED skips the fill; a copy into the same list still lands.
6727 {
6728 constexpr UINT64 bytes = 4096;
6729 const D3D12_HEAP_PROPERTIES default_buffer_heap{D3D12_HEAP_TYPE_DEFAULT};
6730 std::memset(up, 0xab, std::size_t(bytes));
6731 {
6732 Ref<ID3D12Resource> dirty;
6733 EXPECT(SUCCEEDED(create(default_buffer_heap, buffer_desc(bytes), D3D12_RESOURCE_STATE_COMMON, dirty)));
6734 EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, nullptr)));
6735 list->CopyBufferRegion(dirty.p, 0, upload.p, 0, bytes);
6736 EXPECT(list->Close() == S_OK);
6737 queue->ExecuteCommandLists(1, lists);
6738 EXPECT(submit_and_wait());
6739 }
6740 Ref<ID3D12Resource> fresh, not_zeroed;
6741 EXPECT(SUCCEEDED(create(default_buffer_heap, buffer_desc(bytes), D3D12_RESOURCE_STATE_COMMON, fresh)));
6742 const D3D12_RESOURCE_DESC zero_desc = buffer_desc(bytes);
6743 EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_buffer_heap, D3D12_HEAP_FLAG_CREATE_NOT_ZEROED,
6744 &zero_desc, D3D12_RESOURCE_STATE_COMMON, nullptr,
6745 IID_PPV_ARGS(&not_zeroed.p))));
6746 std::memset(down, 0xcd, std::size_t(2 * bytes));
6747 EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, nullptr)));
6748 list->CopyBufferRegion(readback.p, 0, fresh.p, 0, bytes);
6749 list->CopyBufferRegion(not_zeroed.p, 0, upload.p, 0, bytes); // written before it is read
6750 auto readable = transition(not_zeroed.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE);
6751 list->ResourceBarrier(1, &readable);
6752 list->CopyBufferRegion(readback.p, bytes, not_zeroed.p, 0, bytes);
6753 EXPECT(list->Close() == S_OK);
6754 queue->ExecuteCommandLists(1, lists);
6755 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
6756 EXPECT(submit_and_wait());
6757 const std::uint8_t zero[4] = {}, written[4] = {0xab, 0xab, 0xab, 0xab};
6758 for (UINT64 i = 0; i < bytes; i += 4) report("zero-filled buffer byte", UINT(i), down + i, zero, 4);
6759 for (UINT64 i = 0; i < bytes; i += 4)
6760 report("NOT_ZEROED buffer byte after a copy", UINT(i), down + bytes + i, written, 4);
6761 }
6762
6501 // Every child holds the proxy; once they are gone the proxy holds the only reference. 6763 // Every child holds the proxy; once they are gone the proxy holds the only reference.
6502 upload->Unmap(0, nullptr); 6764 upload->Unmap(0, nullptr);
6503 readback->Unmap(0, nullptr); 6765 readback->Unmap(0, nullptr);
diff --git a/runtime/test/dxgi_device_test.cpp b/runtime/test/dxgi_device_test.cpp
new file mode 100644
index 000000000..5b02cb762
--- /dev/null
+++ b/runtime/test/dxgi_device_test.cpp
@@ -0,0 +1,349 @@
1// IDXGIDevice1 on the Xbox-ABI device proxy (d3d12_xs_device.h): the step a GDKX title takes to find its output
2// (docs/d3d12_vulkan.md section 4.5: QueryInterface the device for IDXGIDevice1, GetAdapter, EnumOutputs(0)). Walked
3// on the host PC runtime (WARP, and the first hardware adapter when there is one) and on the Vulkan-backed device:
4// - the PC device behind the proxy has no IDXGIDevice of its own (host runtime), so the proxy's answer is its own;
5// - QueryInterface for IDXGIDevice, IDXGIDevice1 and IDXGIObject gives one pointer, which is not the device's but
6// is the same COM object: one IUnknown, QueryInterface back to ID3D12Device gives the proxy, one reference count;
7// - IDXGIDevice2 and later are refused;
8// - GetAdapter and GetParent(IDXGIAdapter) give the adapter of the device behind the proxy: its LUID is the
9// device's GetAdapterLuid. On the host runtime it is the host's adapter; on the Vulkan device it is the layer's
10// own (rt::dxgi, which stops at IDXGIAdapter3 and whose parent is the layer's factory);
11// - EnumOutputs(0) on that adapter answers S_OK with an output or DXGI_ERROR_NOT_FOUND, never anything else;
12// - null arguments, the frame latency and the GPU thread priority, and private data shared with the device;
13// - a device created as IDXGIDevice1 directly (a title may pass that IID to D3D12XboxCreateDevice): the pointer
14// that comes back is the DXGI one, the proxy behind it is the device's identity (a fence's GetDevice gives it),
15// and the adapter provider still reaches it, so the Vulkan device hands out the layer's adapter there too.
16// Exits 77 when neither a host D3D12 device nor a Vulkan device can be made. No shaders, game data or Xbox DLLs.
17#include "vk_test_device.h"
18#include "../shims/d3d12_com.h"
19#include "../shims/d3d12_xs_device.h"
20
21#include <d3d12.h>
22#include <dxgi1_6.h>
23
24#include <cstdint>
25#include <cstdio>
26#include <cstring>
27
28#define EXPECT(condition) do { \
29 if (!(condition)) { std::fprintf(stderr, "%s line %d: %s\n", label, __LINE__, #condition); return 1; } \
30} while (0)
31
32namespace {
33
34namespace xs = rt::d3d12_xs;
35
36template <class T>
37struct Ref {
38 T* p = nullptr;
39 Ref() = default;
40 Ref(const Ref&) = delete;
41 Ref& operator=(const Ref&) = delete;
42 ~Ref() { reset(); }
43 void reset() {
44 if (p) p->Release();
45 p = nullptr;
46 }
47 T* operator->() const { return p; }
48};
49
50// {8f3a1c52-6e0b-4d97-b1c4-2a7e9d5f0c36}: a private-data key of this test.
51constexpr GUID kTestData{0x8f3a1c52, 0x6e0b, 0x4d97, {0xb1, 0xc4, 0x2a, 0x7e, 0x9d, 0x5f, 0x0c, 0x36}};
52
53bool same_luid(const LUID& a, const LUID& b) { return a.LowPart == b.LowPart && a.HighPart == b.HighPart; }
54
55// `device` is the device proxy, `real` the device behind it.
56int check_backend(const char* label, ID3D12Device* device, ID3D12Device* real, bool vulkan) {
57 const unsigned long device_refs = xs::device_proxy_ref_count(device);
58
59 // The device behind the proxy: the PC runtime's has no IDXGIDevice, which is why the proxy answers it itself.
60 if (!vulkan) {
61 void* none = reinterpret_cast<void*>(1);
62 EXPECT(real->QueryInterface(__uuidof(IDXGIDevice1), &none) == E_NOINTERFACE && !none);
63 }
64
65 Ref<IDXGIDevice1> dxgi;
66 EXPECT(device->QueryInterface(__uuidof(IDXGIDevice1), reinterpret_cast<void**>(&dxgi.p)) == S_OK && dxgi.p);
67 EXPECT(static_cast<void*>(dxgi.p) != static_cast<void*>(device));
68 EXPECT(xs::device_proxy_from_dxgi_device(dxgi.p) == device && !xs::device_proxy_from_dxgi_device(device));
69 EXPECT(xs::device_proxy_ref_count(device) == device_refs + 1);
70 {
71 // One COM object: every DXGI interface is the same pointer, IUnknown is the device's, and QueryInterface
72 // leads back to the device proxy from each of them.
73 Ref<IDXGIDevice> dxgi0;
74 Ref<IDXGIObject> object;
75 Ref<IUnknown> unknown_a, unknown_b;
76 Ref<ID3D12Device> back;
77 EXPECT(dxgi->QueryInterface(__uuidof(IDXGIDevice), reinterpret_cast<void**>(&dxgi0.p)) == S_OK);
78 EXPECT(device->QueryInterface(__uuidof(IDXGIObject), reinterpret_cast<void**>(&object.p)) == S_OK);
79 EXPECT(static_cast<void*>(dxgi0.p) == static_cast<void*>(dxgi.p) &&
80 static_cast<void*>(object.p) == static_cast<void*>(dxgi.p));
81 EXPECT(dxgi->QueryInterface(__uuidof(IUnknown), reinterpret_cast<void**>(&unknown_a.p)) == S_OK);
82 EXPECT(device->QueryInterface(__uuidof(IUnknown), reinterpret_cast<void**>(&unknown_b.p)) == S_OK);
83 EXPECT(unknown_a.p == unknown_b.p && static_cast<void*>(unknown_a.p) == static_cast<void*>(device));
84 EXPECT(dxgi->QueryInterface(__uuidof(ID3D12Device), reinterpret_cast<void**>(&back.p)) == S_OK);
85 EXPECT(back.p == device);
86 EXPECT(xs::device_proxy_ref_count(device) == device_refs + 6);
87 // Later DXGI device interfaces, and a null output or IID.
88 void* none = reinterpret_cast<void*>(1);
89 EXPECT(device->QueryInterface(__uuidof(IDXGIDevice2), &none) == E_NOINTERFACE && !none);
90 none = reinterpret_cast<void*>(1);
91 EXPECT(dxgi->QueryInterface(__uuidof(IDXGIDevice2), &none) == E_NOINTERFACE && !none);
92 EXPECT(dxgi->QueryInterface(__uuidof(IDXGIDevice1), nullptr) == E_POINTER);
93 }
94 EXPECT(xs::device_proxy_ref_count(device) == device_refs + 1);
95 // AddRef and Release on the DXGI pointer count on the device.
96 EXPECT(dxgi->AddRef() == device_refs + 2 && dxgi->Release() == device_refs + 1);
97
98 // GetAdapter: the adapter of the device behind the proxy.
99 const LUID device_luid = device->GetAdapterLuid();
100 EXPECT(same_luid(device_luid, real->GetAdapterLuid()));
101 Ref<IDXGIAdapter> adapter;
102 EXPECT(dxgi->GetAdapter(&adapter.p) == S_OK && adapter.p);
103 DXGI_ADAPTER_DESC desc{};
104 EXPECT(adapter->GetDesc(&desc) == S_OK && same_luid(desc.AdapterLuid, device_luid));
105 char name[128] = {};
106 WideCharToMultiByte(CP_UTF8, 0, desc.Description, -1, name, sizeof(name) - 1, nullptr, nullptr);
107 EXPECT(dxgi->GetAdapter(nullptr) == E_POINTER);
108 {
109 // GetParent is the same adapter by another road, as any interface it has; the device is not its own parent.
110 Ref<IDXGIAdapter> parent;
111 EXPECT(dxgi->GetParent(__uuidof(IDXGIAdapter), reinterpret_cast<void**>(&parent.p)) == S_OK && parent.p);
112 DXGI_ADAPTER_DESC parent_desc{};
113 EXPECT(parent->GetDesc(&parent_desc) == S_OK && same_luid(parent_desc.AdapterLuid, device_luid));
114 void* none = reinterpret_cast<void*>(1);
115 EXPECT(FAILED(dxgi->GetParent(__uuidof(ID3D12Device), &none)) && !none);
116 EXPECT(dxgi->GetParent(__uuidof(IDXGIAdapter), nullptr) == E_POINTER);
117 }
118 {
119 // Whose adapter it is. The layer's own stops at IDXGIAdapter3 and its parent is the layer's factory, which
120 // enumerates exactly that one adapter; the host's is the host DXGI's (IDXGIAdapter4 since Windows 10 1803).
121 Ref<IDXGIAdapter4> adapter4;
122 const HRESULT hr4 = adapter->QueryInterface(__uuidof(IDXGIAdapter4), reinterpret_cast<void**>(&adapter4.p));
123 Ref<IDXGIFactory1> factory;
124 EXPECT(adapter->GetParent(__uuidof(IDXGIFactory1), reinterpret_cast<void**>(&factory.p)) == S_OK);
125 Ref<IDXGIAdapter> second;
126 const HRESULT second_hr = factory->EnumAdapters(1, &second.p);
127 if (vulkan) {
128 EXPECT(hr4 == E_NOINTERFACE && !adapter4.p);
129 EXPECT(second_hr == DXGI_ERROR_NOT_FOUND && !second.p);
130 }
131 }
132 // The next step of the sequence. Which answer comes back is the adapter's business (a software adapter has no
133 // output; the layer's adapter has none before D3D-313): it is one of the two, and an output only with S_OK.
134 Ref<IDXGIOutput> output;
135 const HRESULT output_hr = adapter->EnumOutputs(0, &output.p);
136 EXPECT((output_hr == S_OK && output.p) || (output_hr == DXGI_ERROR_NOT_FOUND && !output.p));
137
138 // IDXGIDevice1's own state: kept and read back.
139 UINT latency = 0;
140 EXPECT(dxgi->GetMaximumFrameLatency(&latency) == S_OK && latency == 3);
141 EXPECT(dxgi->SetMaximumFrameLatency(1) == S_OK && dxgi->GetMaximumFrameLatency(&latency) == S_OK && latency == 1);
142 EXPECT(dxgi->SetMaximumFrameLatency(17) == DXGI_ERROR_INVALID_CALL);
143 EXPECT(dxgi->GetMaximumFrameLatency(&latency) == S_OK && latency == 1);
144 EXPECT(dxgi->SetMaximumFrameLatency(0) == S_OK && dxgi->GetMaximumFrameLatency(&latency) == S_OK && latency == 3);
145 EXPECT(dxgi->GetMaximumFrameLatency(nullptr) == E_POINTER);
146 INT priority = 99;
147 EXPECT(dxgi->GetGPUThreadPriority(&priority) == S_OK && priority == 0);
148 EXPECT(dxgi->SetGPUThreadPriority(7) == S_OK && dxgi->GetGPUThreadPriority(&priority) == S_OK && priority == 7);
149 EXPECT(dxgi->SetGPUThreadPriority(8) == E_INVALIDARG && dxgi->SetGPUThreadPriority(-8) == E_INVALIDARG);
150 EXPECT(dxgi->GetGPUThreadPriority(&priority) == S_OK && priority == 7);
151 EXPECT(dxgi->GetGPUThreadPriority(nullptr) == E_POINTER);
152 IDXGISurface* surface = reinterpret_cast<IDXGISurface*>(std::uintptr_t{1});
153 EXPECT(dxgi->CreateSurface(nullptr, 0, 0, nullptr, &surface) == E_NOTIMPL && !surface);
154 EXPECT(dxgi->QueryResourceResidency(nullptr, nullptr, 0) == E_NOTIMPL);
155
156 // Private data set through the DXGI interface is the device's, and the other way round.
157 const std::uint32_t written = 0x12345678;
158 std::uint32_t read = 0;
159 UINT size = sizeof(read);
160 EXPECT(dxgi->SetPrivateData(kTestData, sizeof(written), &written) == S_OK);
161 EXPECT(device->GetPrivateData(kTestData, &size, &read) == S_OK && size == sizeof(read) && read == written);
162 EXPECT(device->SetPrivateData(kTestData, 0, nullptr) == S_OK);
163 size = sizeof(read);
164 EXPECT(FAILED(dxgi->GetPrivateData(kTestData, &size, &read)));
165
166 // The adapter does not keep the device alive, and the device outlives its DXGI pointer's last use.
167 adapter.reset();
168 output.reset();
169 dxgi.reset();
170 EXPECT(xs::device_proxy_ref_count(device) == device_refs);
171 std::printf("%s: IDXGIDevice1 on the device proxy is one COM object with it; GetAdapter and GetParent give \"%s\" "
172 "(%s adapter, the device's LUID); EnumOutputs(0) %s\n",
173 label, name, vulkan ? "the layer's own" : "the host's",
174 output_hr == S_OK ? "gives an output" : "is DXGI_ERROR_NOT_FOUND");
175 return 0;
176}
177
178// The device created as IDXGIDevice1, the way D3D12XboxCreateDevice creates it when a title passes that IID: the
179// proxy over `real` (which takes one reference to it), then set_device_outer with what came back for the Vulkan
180// device. `real` is released by the proxy's last reference.
181int check_direct(const char* label, ID3D12Device* real, bool vulkan) {
182 IDXGIDevice1* dxgi = nullptr;
183 EXPECT(xs::create_device_proxy(real, __uuidof(IDXGIDevice1), reinterpret_cast<void**>(&dxgi)) == S_OK && dxgi);
184 EXPECT(!xs::is_device_proxy(dxgi)); // the DXGI pointer, not the proxy
185 void* const proxy = xs::device_proxy_from_dxgi_device(dxgi);
186 EXPECT(proxy && xs::is_device_proxy(proxy) && xs::device_proxy_primary(dxgi) == proxy &&
187 xs::device_proxy_primary(proxy) == proxy);
188 EXPECT(xs::device_proxy_ref_count(proxy) == 1); // the caller's one reference, held through the DXGI pointer
189 if (vulkan) rt::d3d12::set_device_outer(real, dxgi);
190 {
191 // QueryInterface back to the device gives the proxy, and the device's children name the proxy as their
192 // device: the outer identity is the proxy, not the DXGI pointer that creation returned.
193 Ref<ID3D12Device> device;
194 EXPECT(dxgi->QueryInterface(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device.p)) == S_OK);
195 EXPECT(static_cast<void*>(device.p) == proxy && xs::device_proxy_ref_count(proxy) == 2);
196 Ref<ID3D12Fence> fence;
197 EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p))));
198 Ref<ID3D12Device> owner;
199 EXPECT(SUCCEEDED(fence->GetDevice(IID_PPV_ARGS(&owner.p))) && static_cast<void*>(owner.p) == proxy);
200 // The adapter: the device's LUID, and on the Vulkan device the layer's own, as on the query path.
201 Ref<IDXGIAdapter> adapter;
202 EXPECT(dxgi->GetAdapter(&adapter.p) == S_OK && adapter.p);
203 DXGI_ADAPTER_DESC desc{};
204 EXPECT(adapter->GetDesc(&desc) == S_OK && same_luid(desc.AdapterLuid, real->GetAdapterLuid()));
205 Ref<IDXGIAdapter4> adapter4;
206 const HRESULT hr4 = adapter->QueryInterface(__uuidof(IDXGIAdapter4), reinterpret_cast<void**>(&adapter4.p));
207 Ref<IDXGIFactory1> factory;
208 EXPECT(adapter->GetParent(__uuidof(IDXGIFactory1), reinterpret_cast<void**>(&factory.p)) == S_OK);
209 Ref<IDXGIAdapter> second;
210 const HRESULT second_hr = factory->EnumAdapters(1, &second.p);
211 if (vulkan) {
212 EXPECT(hr4 == E_NOINTERFACE && !adapter4.p);
213 EXPECT(second_hr == DXGI_ERROR_NOT_FOUND && !second.p);
214 }
215 }
216 EXPECT(xs::device_proxy_ref_count(proxy) == 1);
217 {
218 // A provider set through the DXGI pointer is the one GetAdapter asks, and one handed something that is not
219 // a proxy is refused (it says so on stderr) instead of leaving the default in place unnoticed.
220 const xs::DxgiAdapterProvider refuse = [](ID3D12Device*, REFIID, void** out) {
221 *out = reinterpret_cast<void*>(std::uintptr_t{1}); // a failing provider's output is not handed on
222 return E_ABORT;
223 };
224 EXPECT(xs::set_device_adapter_provider(dxgi, refuse));
225 IDXGIAdapter* none = reinterpret_cast<IDXGIAdapter*>(std::uintptr_t{1});
226 EXPECT(dxgi->GetAdapter(&none) == E_ABORT && !none);
227 EXPECT(xs::set_device_adapter_provider(proxy, nullptr)); // back to the default (the host's adapter)
228 Ref<IDXGIAdapter> host;
229 EXPECT(dxgi->GetAdapter(&host.p) == S_OK && host.p);
230 void* not_a_proxy = nullptr; // pointer-sized: the helpers read a vtable pointer from what they are given
231 EXPECT(!xs::set_device_adapter_provider(&not_a_proxy, refuse) && !xs::set_device_adapter_provider(real, refuse));
232 EXPECT(!xs::device_proxy_primary(&not_a_proxy) && !xs::device_proxy_primary(nullptr));
233 }
234 EXPECT(dxgi->Release() == 0); // the last reference: the proxy goes, and with it its reference to `real`
235 std::printf("%s: created as IDXGIDevice1: the proxy is the device's identity and the adapter is %s\n", label,
236 vulkan ? "the layer's own" : "the host's");
237 return 0;
238}
239
240int run_host(IDXGIAdapter1* adapter, const char* label) {
241 ID3D12Device* real = nullptr;
242 if (FAILED(D3D12CreateDevice(adapter, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&real)))) {
243 std::printf("%s: no D3D12 device, skipped\n", label);
244 return 77;
245 }
246 real->AddRef(); // for the second proxy below: each proxy takes one reference
247 if (check_direct(label, real, false)) {
248 real->Release();
249 return 1;
250 }
251 real->AddRef(); // the backend's own reference; the proxy takes the other
252 Ref<ID3D12Device> device;
253 if (FAILED(xs::create_device_proxy(real, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device.p)))) {
254 real->Release();
255 real->Release();
256 std::fprintf(stderr, "%s: device proxy creation failed\n", label);
257 return 1;
258 }
259 const int result = check_backend(label, device.p, real, false);
260 device.reset();
261 if (result) return 1;
262 if (real->Release() != 0) {
263 std::fprintf(stderr, "%s: the PC device outlives its proxy\n", label);
264 return 1;
265 }
266 return 0;
267}
268
269} // namespace
270
271// A failure ends the process with a message on stderr, never in a dialog a test run would wait on.
272static void no_dialogs() {
273 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
274 SetErrorMode(GetErrorMode() | SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
275}
276
277int main() {
278 no_dialogs();
279 std::setvbuf(stdout, nullptr, _IONBF, 0);
280 const char* label = "dxgi_device_test";
281 int ran = 0;
282
283 // Host PC runtime: WARP, then the first hardware adapter. Under Wine the host d3d12.dll is Wine's own, not the
284 // PC runtime the proxy is written against, so only Vulkan runs there.
285 const bool wine = GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "wine_get_version") != nullptr;
286 Ref<IDXGIFactory4> factory;
287 if (wine) std::printf("host D3D12: under Wine, skipped\n");
288 if (!wine && SUCCEEDED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p)))) {
289 Ref<IDXGIAdapter1> warp;
290 if (SUCCEEDED(factory->EnumWarpAdapter(IID_PPV_ARGS(&warp.p)))) {
291 const int r = run_host(warp.p, "host WARP");
292 if (r == 1) return 1;
293 ran += r == 0;
294 }
295 for (UINT i = 0;; ++i) {
296 Ref<IDXGIAdapter1> adapter;
297 if (factory->EnumAdapters1(i, &adapter.p) == DXGI_ERROR_NOT_FOUND) break;
298 DXGI_ADAPTER_DESC1 desc{};
299 if (FAILED(adapter->GetDesc1(&desc)) || (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)) continue;
300 const int r = run_host(adapter.p, "host hardware adapter");
301 if (r == 1) return 1;
302 ran += r == 0;
303 break;
304 }
305 }
306
307 // The Vulkan-backed device, the way D3D12XboxCreateDevice hands it out with LEONIDA_D3D12=vulkan.
308 vktest::Device d;
309 if (d.create()) {
310 label = "Vulkan";
311 rt::d3d12::VulkanDeviceInfo info{};
312 info.get_instance_proc = d.instance_proc;
313 info.instance = d.instance;
314 info.physical = d.physical;
315 info.device = d.device;
316 info.queue = d.queue;
317 info.queue_family = d.family;
318 ID3D12Device* inner = nullptr;
319 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner))));
320 inner->AddRef(); // the backend's own reference; the proxy takes the other
321 ID3D12Device* device = nullptr;
322 EXPECT(SUCCEEDED(xs::create_device_proxy(inner, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device))));
323 rt::d3d12::set_device_outer(inner, device);
324 const int result = check_backend(label, device, inner, true);
325 device->Release();
326 if (result) return 1;
327 EXPECT(inner->Release() == 0); // nothing the adapter or the factory made kept the layer's device alive
328 // A second device on the same Vulkan device, created as IDXGIDevice1.
329 ID3D12Device* direct = nullptr;
330 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&direct))));
331 direct->AddRef(); // the backend's own reference; the proxy takes the other
332 if (check_direct(label, direct, true)) return 1;
333 EXPECT(direct->Release() == 0);
334 ++ran;
335 if (d.validation_errors()) {
336 std::fprintf(stderr, "%u validation errors\n", d.validation_errors());
337 return 1;
338 }
339 } else {
340 std::printf("Vulkan: no device, skipped\n");
341 }
342
343 if (!ran) {
344 std::printf("SKIP dxgi_device_test: neither a host D3D12 device nor a Vulkan device\n");
345 return 77;
346 }
347 std::printf("dxgi_device_test: %d backend(s) passed\n", ran);
348 return 0;
349}
diff --git a/runtime/test/dxgi_swapchain_count_test.cpp b/runtime/test/dxgi_swapchain_count_test.cpp
new file mode 100644
index 000000000..13da2028e
--- /dev/null
+++ b/runtime/test/dxgi_swapchain_count_test.cpp
@@ -0,0 +1,354 @@
1// Synthetic regression test for the DXGI swapchain buffer-count contract (D3D-389), with no GPU and no
2// window: VulkanSwapchain (runtime/shims/dxgi_swapchain.h) runs on a fake Vulkan function table, so
3// vkGetSwapchainImagesKHR can report more images than the app's requested BufferCount.
4//
5// DXGI rule: GetDesc/GetDesc1 report the BufferCount the app created with, and GetCurrentBackBufferIndex is
6// always below it, one stable resource per index. The shim must not expose images the driver added above
7// minImageCount, and must hide a caps.minImageCount above the request. When the native count differs, the
8// exposed buffers form an offscreen ring; each present blits the current slot into the acquired native image.
9#include "../shims/dxgi_swapchain.h"
10
11#include <cstdint>
12#include <cstdio>
13#include <cstring>
14#include <mutex>
15#include <vector>
16
17namespace {
18
19constexpr std::uintptr_t kSurface = 0x5100;
20constexpr std::uintptr_t kSwapchain = 0x5101;
21constexpr std::uintptr_t kFence = 0x5102;
22constexpr std::uintptr_t kPool = 0x5103;
23constexpr std::uintptr_t kCmd = 0x5104;
24constexpr std::uintptr_t kNativeBase = 0x6000;
25constexpr std::uintptr_t kOffscreenBase = 0x7000;
26
27struct Fake {
28 std::uint32_t min_image_count = 2;
29 std::uint32_t max_image_count = 0;
30 std::uint32_t returned_images = 2;
31 std::uint32_t create_min_image_count = 0;
32 std::uint32_t acquire_cursor = 0;
33 std::uint32_t last_acquired = 0;
34 std::uint32_t presented_image = UINT32_MAX;
35 VkImage blit_src = VK_NULL_HANDLE;
36 VkImage blit_dst = VK_NULL_HANDLE;
37 unsigned presents = 0;
38 unsigned created_offscreen = 0;
39};
40Fake g;
41
42VkImage native_image(std::uint32_t i) {
43 return reinterpret_cast<VkImage>(static_cast<std::uintptr_t>(kNativeBase + i));
44}
45
46template <typename T>
47PFN_vkVoidFunction as_function(T fn) {
48 return reinterpret_cast<PFN_vkVoidFunction>(fn);
49}
50
51VKAPI_ATTR VkResult VKAPI_CALL create_win32_surface(VkInstance, const VkWin32SurfaceCreateInfoKHR*,
52 const VkAllocationCallbacks*, VkSurfaceKHR* out) {
53 if (out) *out = reinterpret_cast<VkSurfaceKHR>(kSurface);
54 return VK_SUCCESS;
55}
56VKAPI_ATTR void VKAPI_CALL destroy_surface(VkInstance, VkSurfaceKHR, const VkAllocationCallbacks*) {}
57VKAPI_ATTR VkResult VKAPI_CALL surface_support(VkPhysicalDevice, std::uint32_t, VkSurfaceKHR, VkBool32* out) {
58 if (out) *out = VK_TRUE;
59 return VK_SUCCESS;
60}
61VKAPI_ATTR VkResult VKAPI_CALL surface_caps(VkPhysicalDevice, VkSurfaceKHR, VkSurfaceCapabilitiesKHR* caps) {
62 if (!caps) return VK_ERROR_INITIALIZATION_FAILED;
63 std::memset(caps, 0, sizeof(*caps));
64 caps->minImageCount = g.min_image_count;
65 caps->maxImageCount = g.max_image_count;
66 caps->currentExtent = {64, 64};
67 caps->minImageExtent = {1, 1};
68 caps->maxImageExtent = {4096, 4096};
69 caps->supportedUsageFlags = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT |
70 VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
71 caps->currentTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
72 return VK_SUCCESS;
73}
74VKAPI_ATTR VkResult VKAPI_CALL surface_formats(VkPhysicalDevice, VkSurfaceKHR, std::uint32_t* count,
75 VkSurfaceFormatKHR* formats) {
76 if (!count) return VK_ERROR_INITIALIZATION_FAILED;
77 if (formats && *count) {
78 formats[0].format = VK_FORMAT_B8G8R8A8_UNORM;
79 formats[0].colorSpace = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR;
80 }
81 *count = 1;
82 return VK_SUCCESS;
83}
84VKAPI_ATTR VkResult VKAPI_CALL surface_present_modes(VkPhysicalDevice, VkSurfaceKHR, std::uint32_t* count,
85 VkPresentModeKHR* modes) {
86 if (!count) return VK_ERROR_INITIALIZATION_FAILED;
87 if (modes && *count) modes[0] = VK_PRESENT_MODE_FIFO_KHR;
88 *count = 1;
89 return VK_SUCCESS;
90}
91VKAPI_ATTR void VKAPI_CALL memory_properties(VkPhysicalDevice, VkPhysicalDeviceMemoryProperties* props) {
92 std::memset(props, 0, sizeof(*props));
93 props->memoryTypeCount = 1;
94 props->memoryTypes[0].propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
95 props->memoryHeapCount = 1;
96 props->memoryHeaps[0].size = 1ull << 30;
97 props->memoryHeaps[0].flags = VK_MEMORY_HEAP_DEVICE_LOCAL_BIT;
98}
99VKAPI_ATTR VkResult VKAPI_CALL create_swapchain(VkDevice, const VkSwapchainCreateInfoKHR* info,
100 const VkAllocationCallbacks*, VkSwapchainKHR* out) {
101 if (!info || !out) return VK_ERROR_INITIALIZATION_FAILED;
102 g.create_min_image_count = info->minImageCount;
103 *out = reinterpret_cast<VkSwapchainKHR>(kSwapchain);
104 return VK_SUCCESS;
105}
106VKAPI_ATTR void VKAPI_CALL destroy_swapchain(VkDevice, VkSwapchainKHR, const VkAllocationCallbacks*) {}
107VKAPI_ATTR VkResult VKAPI_CALL get_images(VkDevice, VkSwapchainKHR, std::uint32_t* count, VkImage* images) {
108 if (!count) return VK_ERROR_INITIALIZATION_FAILED;
109 if (images) {
110 for (std::uint32_t i = 0; i < g.returned_images && i < *count; ++i) images[i] = native_image(i);
111 }
112 *count = g.returned_images;
113 return VK_SUCCESS;
114}
115VKAPI_ATTR VkResult VKAPI_CALL acquire_next_image(VkDevice, VkSwapchainKHR, std::uint64_t, VkSemaphore, VkFence,
116 std::uint32_t* out) {
117 if (!out || g.returned_images == 0) return VK_ERROR_INITIALIZATION_FAILED;
118 g.last_acquired = g.acquire_cursor % g.returned_images;
119 ++g.acquire_cursor;
120 *out = g.last_acquired;
121 return VK_SUCCESS;
122}
123VKAPI_ATTR VkResult VKAPI_CALL queue_present(VkQueue, const VkPresentInfoKHR* info) {
124 if (!info || info->swapchainCount != 1 || !info->pImageIndices) return VK_ERROR_INITIALIZATION_FAILED;
125 g.presented_image = info->pImageIndices[0];
126 ++g.presents;
127 return VK_SUCCESS;
128}
129VKAPI_ATTR VkResult VKAPI_CALL create_fence(VkDevice, const VkFenceCreateInfo*, const VkAllocationCallbacks*,
130 VkFence* out) {
131 if (out) *out = reinterpret_cast<VkFence>(kFence);
132 return VK_SUCCESS;
133}
134VKAPI_ATTR void VKAPI_CALL destroy_fence(VkDevice, VkFence, const VkAllocationCallbacks*) {}
135VKAPI_ATTR VkResult VKAPI_CALL wait_for_fences(VkDevice, std::uint32_t, const VkFence*, VkBool32, std::uint64_t) {
136 return VK_SUCCESS;
137}
138VKAPI_ATTR VkResult VKAPI_CALL reset_fences(VkDevice, std::uint32_t, const VkFence*) { return VK_SUCCESS; }
139VKAPI_ATTR VkResult VKAPI_CALL device_wait_idle(VkDevice) { return VK_SUCCESS; }
140VKAPI_ATTR VkResult VKAPI_CALL create_image(VkDevice, const VkImageCreateInfo*, const VkAllocationCallbacks*,
141 VkImage* out) {
142 if (!out) return VK_ERROR_INITIALIZATION_FAILED;
143 *out = reinterpret_cast<VkImage>(static_cast<std::uintptr_t>(kOffscreenBase + g.created_offscreen++));
144 return VK_SUCCESS;
145}
146VKAPI_ATTR void VKAPI_CALL destroy_image(VkDevice, VkImage, const VkAllocationCallbacks*) {}
147VKAPI_ATTR void VKAPI_CALL image_mem_req(VkDevice, VkImage, VkMemoryRequirements* req) {
148 std::memset(req, 0, sizeof(*req));
149 req->size = 4096;
150 req->alignment = 1;
151 req->memoryTypeBits = 1;
152}
153VKAPI_ATTR VkResult VKAPI_CALL alloc_mem(VkDevice, const VkMemoryAllocateInfo*, const VkAllocationCallbacks*,
154 VkDeviceMemory* out) {
155 if (out) *out = reinterpret_cast<VkDeviceMemory>(kOffscreenBase);
156 return VK_SUCCESS;
157}
158VKAPI_ATTR void VKAPI_CALL free_mem(VkDevice, VkDeviceMemory, const VkAllocationCallbacks*) {}
159VKAPI_ATTR VkResult VKAPI_CALL bind_image_mem(VkDevice, VkImage, VkDeviceMemory, VkDeviceSize) {
160 return VK_SUCCESS;
161}
162VKAPI_ATTR VkResult VKAPI_CALL create_cmd_pool(VkDevice, const VkCommandPoolCreateInfo*,
163 const VkAllocationCallbacks*, VkCommandPool* out) {
164 if (out) *out = reinterpret_cast<VkCommandPool>(kPool);
165 return VK_SUCCESS;
166}
167VKAPI_ATTR void VKAPI_CALL destroy_cmd_pool(VkDevice, VkCommandPool, const VkAllocationCallbacks*) {}
168VKAPI_ATTR VkResult VKAPI_CALL alloc_cmd_bufs(VkDevice, const VkCommandBufferAllocateInfo*,
169 VkCommandBuffer* out) {
170 if (out) *out = reinterpret_cast<VkCommandBuffer>(kCmd);
171 return VK_SUCCESS;
172}
173VKAPI_ATTR VkResult VKAPI_CALL reset_cmd_buf(VkCommandBuffer, VkCommandBufferResetFlags) { return VK_SUCCESS; }
174VKAPI_ATTR VkResult VKAPI_CALL begin_cmd_buf(VkCommandBuffer, const VkCommandBufferBeginInfo*) {
175 return VK_SUCCESS;
176}
177VKAPI_ATTR VkResult VKAPI_CALL end_cmd_buf(VkCommandBuffer) { return VK_SUCCESS; }
178VKAPI_ATTR void VKAPI_CALL cmd_barrier(VkCommandBuffer, VkPipelineStageFlags, VkPipelineStageFlags, std::uint32_t,
179 const VkMemoryBarrier*, std::uint32_t, const VkBufferMemoryBarrier*,
180 std::uint32_t, const VkImageMemoryBarrier*) {}
181VKAPI_ATTR void VKAPI_CALL cmd_blit(VkCommandBuffer, VkImage src, VkImageLayout, VkImage dst, VkImageLayout,
182 std::uint32_t, const VkImageBlit*, VkFilter) {
183 g.blit_src = src;
184 g.blit_dst = dst;
185}
186VKAPI_ATTR VkResult VKAPI_CALL queue_submit(VkQueue, std::uint32_t, const VkSubmitInfo*, VkFence) {
187 return VK_SUCCESS;
188}
189
190struct Entry {
191 const char* name;
192 PFN_vkVoidFunction fn;
193};
194const Entry kEntries[] = {
195 {"vkCreateWin32SurfaceKHR", as_function(create_win32_surface)},
196 {"vkDestroySurfaceKHR", as_function(destroy_surface)},
197 {"vkGetPhysicalDeviceSurfaceSupportKHR", as_function(surface_support)},
198 {"vkGetPhysicalDeviceSurfaceCapabilitiesKHR", as_function(surface_caps)},
199 {"vkGetPhysicalDeviceSurfaceFormatsKHR", as_function(surface_formats)},
200 {"vkGetPhysicalDeviceSurfacePresentModesKHR", as_function(surface_present_modes)},
201 {"vkGetPhysicalDeviceMemoryProperties", as_function(memory_properties)},
202 {"vkCreateSwapchainKHR", as_function(create_swapchain)},
203 {"vkDestroySwapchainKHR", as_function(destroy_swapchain)},
204 {"vkGetSwapchainImagesKHR", as_function(get_images)},
205 {"vkAcquireNextImageKHR", as_function(acquire_next_image)},
206 {"vkQueuePresentKHR", as_function(queue_present)},
207 {"vkCreateFence", as_function(create_fence)},
208 {"vkDestroyFence", as_function(destroy_fence)},
209 {"vkWaitForFences", as_function(wait_for_fences)},
210 {"vkResetFences", as_function(reset_fences)},
211 {"vkDeviceWaitIdle", as_function(device_wait_idle)},
212 {"vkCreateImage", as_function(create_image)},
213 {"vkDestroyImage", as_function(destroy_image)},
214 {"vkGetImageMemoryRequirements", as_function(image_mem_req)},
215 {"vkAllocateMemory", as_function(alloc_mem)},
216 {"vkFreeMemory", as_function(free_mem)},
217 {"vkBindImageMemory", as_function(bind_image_mem)},
218 {"vkCreateCommandPool", as_function(create_cmd_pool)},
219 {"vkDestroyCommandPool", as_function(destroy_cmd_pool)},
220 {"vkAllocateCommandBuffers", as_function(alloc_cmd_bufs)},
221 {"vkResetCommandBuffer", as_function(reset_cmd_buf)},
222 {"vkBeginCommandBuffer", as_function(begin_cmd_buf)},
223 {"vkEndCommandBuffer", as_function(end_cmd_buf)},
224 {"vkCmdPipelineBarrier", as_function(cmd_barrier)},
225 {"vkCmdBlitImage", as_function(cmd_blit)},
226 {"vkQueueSubmit", as_function(queue_submit)},
227};
228
229PFN_vkVoidFunction lookup(const char* name) {
230 for (const Entry& entry : kEntries)
231 if (name && std::strcmp(name, entry.name) == 0) return entry.fn;
232 return nullptr;
233}
234
235VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_instance_proc(VkInstance, const char* name) { return lookup(name); }
236VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_device_proc(VkDevice, const char* name) { return lookup(name); }
237
238int fail(const char* what) {
239 std::fprintf(stderr, "FAIL: %s\n", what);
240 return 1;
241}
242
243// Requests `requested` buffers while faking `native` images and a surface minimum of `minimum`.
244int run_case(const char* label, std::uint32_t requested, std::uint32_t native, std::uint32_t minimum,
245 bool expect_offscreen) {
246 g = Fake{};
247 g.min_image_count = minimum;
248 g.returned_images = native;
249 std::mutex mutex;
250 leonida::VulkanSwapchain swapchain(get_instance_proc, reinterpret_cast<VkInstance>(1),
251 reinterpret_cast<VkPhysicalDevice>(2), get_device_proc,
252 reinterpret_cast<VkDevice>(3), reinterpret_cast<VkQueue>(4), 0, mutex);
253 if (!swapchain.create(reinterpret_cast<HWND>(static_cast<std::uintptr_t>(1)), 64, 64,
254 VK_FORMAT_B8G8R8A8_UNORM, requested))
255 return fail("VulkanSwapchain::create");
256
257 // GetDesc/GetDesc1 read image_count(): the app's request, never the native count.
258 if (swapchain.image_count() != requested) {
259 std::fprintf(stderr, "FAIL: %s: exposed BufferCount %u, requested %u (native %u)\n", label,
260 swapchain.image_count(), requested, native);
261 return 1;
262 }
263 const std::uint32_t expected_min = minimum > requested ? minimum : requested;
264 if (g.create_min_image_count != expected_min) {
265 std::fprintf(stderr, "FAIL: %s: vkCreateSwapchainKHR minImageCount %u, expected %u\n", label,
266 g.create_min_image_count, expected_min);
267 return 1;
268 }
269 if (swapchain.is_offscreen() != expect_offscreen)
270 return fail(expect_offscreen ? "expected the offscreen ring" : "expected direct native images");
271
272 if (expect_offscreen) {
273 if (g.created_offscreen != requested) return fail("offscreen ring size != requested BufferCount");
274 std::vector<VkImage> exposed;
275 for (std::uint32_t i = 0; i < requested; ++i) {
276 const leonida::ResourceBinding binding = swapchain.resource_binding(i);
277 if (!binding.image || binding.presentable) return fail("offscreen backbuffer binding is not offscreen");
278 if (binding.image != swapchain.image(i)) return fail("binding/image disagree");
279 for (VkImage other : exposed)
280 if (other == binding.image) return fail("two exposed backbuffers share one image");
281 exposed.push_back(binding.image);
282 }
283 if (swapchain.current_back_buffer_index() >= requested)
284 return fail("initial current index out of range");
285
286 std::uint32_t index = 0;
287 if (!swapchain.acquire_next_image(index)) return fail("first acquire");
288 constexpr unsigned kFrames = 20;
289 for (unsigned frame = 0; frame < kFrames; ++frame) {
290 const std::uint32_t current = swapchain.current_back_buffer_index();
291 if (current >= requested) return fail("GetCurrentBackBufferIndex >= BufferCount");
292 if (current != frame % requested) return fail("current index does not cycle over the exposed ring");
293 const std::uint32_t acquired = g.last_acquired;
294 g.blit_src = g.blit_dst = VK_NULL_HANDLE;
295 g.presented_image = UINT32_MAX;
296 if (!swapchain.present(current)) return fail("present");
297 if (g.blit_src != exposed[current]) return fail("present did not blit the current backbuffer");
298 if (g.blit_dst != native_image(acquired)) return fail("present blitted to the wrong acquired image");
299 if (g.presented_image != acquired) return fail("presented an image other than the acquired one");
300 if (frame + 1 < kFrames && !swapchain.acquire_next_image(index)) return fail("acquire");
301 }
302 // ResizeBuffers(count=0) keeps the exposed BufferCount, not the native image count.
303 if (!swapchain.resize(64, 64)) return fail("resize");
304 if (swapchain.image_count() != requested) return fail("resize(count=0) changed the exposed BufferCount");
305 if (!swapchain.is_offscreen()) return fail("resize dropped the offscreen ring");
306 return 0;
307 }
308
309 // Direct path: exposed index and native image index are the same, and nothing is blitted.
310 if (swapchain.current_back_buffer_index() != 0) return fail("direct initial index");
311 std::uint32_t index = 0;
312 if (!swapchain.acquire_next_image(index)) return fail("direct first acquire");
313 for (unsigned frame = 0; frame < 9; ++frame) {
314 const std::uint32_t current = swapchain.current_back_buffer_index();
315 if (current >= requested) return fail("direct GetCurrentBackBufferIndex >= BufferCount");
316 if (current != g.last_acquired) return fail("direct current index is not the acquired image");
317 if (swapchain.resource_binding(current).image != native_image(current))
318 return fail("direct binding is not the native image");
319 g.blit_src = g.blit_dst = VK_NULL_HANDLE;
320 g.presented_image = UINT32_MAX;
321 if (!swapchain.present(current)) return fail("direct present");
322 if (g.blit_src || g.blit_dst) return fail("direct present took the blit path");
323 if (g.presented_image != current) return fail("direct present index");
324 if (frame + 1 < 9 && !swapchain.acquire_next_image(index)) return fail("direct acquire");
325 }
326 return 0;
327}
328
329struct Case {
330 const char* label;
331 std::uint32_t requested;
332 std::uint32_t native;
333 std::uint32_t minimum;
334 bool offscreen;
335};
336
337} // namespace
338
339int main() {
340 const Case cases[] = {
341 // Vulkan returns more images than minImageCount: the app asked for 2 and must see 2.
342 {"driver returns 4 for BufferCount 2", 2, 4, 2, true},
343 // The surface minimum exceeds the request (2): still expose the app's 2.
344 {"minImageCount 3 for BufferCount 2", 2, 3, 3, true},
345 // Control: the app asks for more than minImageCount; native and exposed counts agree, no blit.
346 {"BufferCount 3 above minImageCount 2", 3, 3, 2, false},
347 };
348 for (const Case& c : cases) {
349 if (const int result = run_case(c.label, c.requested, c.native, c.minimum, c.offscreen)) return result;
350 }
351 std::printf("dxgi_swapchain_count_test: PASS (3 cases: extra native images, min above request, "
352 "request above min)\n");
353 return 0;
354}
diff --git a/runtime/test/dxgi_swapchain_test.cpp b/runtime/test/dxgi_swapchain_test.cpp
index ca1491153..1ef864ff1 100644
--- a/runtime/test/dxgi_swapchain_test.cpp
+++ b/runtime/test/dxgi_swapchain_test.cpp
@@ -16,6 +16,7 @@
16#include <cstdio> 16#include <cstdio>
17#include <cstdlib> 17#include <cstdlib>
18#include <cstring> 18#include <cstring>
19#include <iterator>
19#include <vector> 20#include <vector>
20 21
21namespace { 22namespace {
@@ -91,8 +92,220 @@ bool check_statistics_disjoint(IDXGISwapChain* swapchain) {
91 return swapchain->GetFrameStatistics(&stats) == S_OK; 92 return swapchain->GetFrameStatistics(&stats) == S_OK;
92} 93}
93 94
95// Counts references: AddRef/Release of the private-data interface are observable through refs.
96struct CountedUnknown final : IUnknown {
97 ULONG refs = 1;
98 HRESULT STDMETHODCALLTYPE QueryInterface(REFIID, void** out) override {
99 if (out) *out = nullptr;
100 return E_NOINTERFACE;
101 }
102 ULONG STDMETHODCALLTYPE AddRef() override { return ++refs; }
103 ULONG STDMETHODCALLTYPE Release() override { return --refs; }
104};
105
106// IDXGIObject private data (Microsoft: IDXGIObject::SetPrivateData / SetPrivateDataInterface / GetPrivateData):
107// the bytes are copied, an interface is held with a reference until it is replaced or removed, and the same GUID
108// replaces the entry. Returns null on success or the failing step.
109const char* check_private_data(IDXGIObject* object) {
110 static constexpr GUID key{0x6c2c5b0e, 0x4d9a, 0x4f43, {0x9e, 0x1b, 0x3a, 0x57, 0x0c, 0x91, 0x2d, 0x44}};
111 UINT size = 99;
112 if (object->GetPrivateData(key, &size, nullptr) != DXGI_ERROR_NOT_FOUND) return "GetPrivateData before any Set";
113 std::uint32_t value = 0x12345678u;
114 if (object->SetPrivateData(key, sizeof(value), &value) != S_OK) return "SetPrivateData";
115 value = 0; // SetPrivateData copies
116 size = 0;
117 if (object->GetPrivateData(key, &size, nullptr) != S_OK || size != sizeof(value)) return "GetPrivateData size query";
118 std::uint32_t read = 0;
119 size = sizeof(read);
120 if (object->GetPrivateData(key, &size, &read) != S_OK || size != sizeof(read) || read != 0x12345678u)
121 return "GetPrivateData did not return the stored bytes";
122 std::uint16_t too_small = 0;
123 size = sizeof(too_small);
124 if (object->GetPrivateData(key, &size, &too_small) != DXGI_ERROR_MORE_DATA || size != sizeof(read))
125 return "GetPrivateData with a small buffer should be DXGI_ERROR_MORE_DATA and report the size";
126 CountedUnknown counted;
127 if (object->SetPrivateDataInterface(key, &counted) != S_OK || counted.refs != 2) return "SetPrivateDataInterface";
128 IUnknown* got = nullptr;
129 size = sizeof(got);
130 if (object->GetPrivateData(key, &size, &got) != S_OK || got != &counted || counted.refs != 3)
131 return "GetPrivateData did not return the interface with a reference added";
132 got->Release();
133 if (object->SetPrivateData(key, sizeof(read), &read) != S_OK || counted.refs != 1)
134 return "SetPrivateData with the same GUID should release the held interface";
135 if (object->SetPrivateDataInterface(key, &counted) != S_OK || counted.refs != 2) return "SetPrivateDataInterface again";
136 if (object->SetPrivateDataInterface(key, nullptr) != S_OK || counted.refs != 1)
137 return "SetPrivateDataInterface(null) should remove the entry and release the interface";
138 size = 99;
139 if (object->GetPrivateData(key, &size, nullptr) != DXGI_ERROR_NOT_FOUND) return "GetPrivateData after removal";
140 return nullptr;
141}
142
94} // namespace 143} // namespace
95 144
145
146// CreateSwapChainForHwnd on a guarded call: a host runtime that faults on a case reports it instead of ending the test.
147HRESULT create_guarded(IDXGIFactory4* factory, IUnknown* queue, HWND hwnd, const DXGI_SWAP_CHAIN_DESC1* desc,
148 IDXGISwapChain1** out) {
149 __try {
150 return factory->CreateSwapChainForHwnd(queue, hwnd, desc, nullptr, nullptr, out);
151 } __except (EXCEPTION_EXECUTE_HANDLER) {
152 return HRESULT(0xC0000005);
153 }
154}
155
156// CreateSwapChainForHwnd with descriptions D3D12 refuses (and the valid ones next to them), against the host runtime's
157// DXGI: each case gets its own window on each side, and the HRESULTs must match. Returns the number of mismatches,
158// or -1 without a host D3D12 device.
159int compare_swap_chain_arguments(IDXGIFactory4* ours, ID3D12Device* our_device, ID3D12CommandQueue* our_queue) {
160 using CreateDevice = HRESULT(WINAPI*)(IUnknown*, D3D_FEATURE_LEVEL, REFIID, void**);
161 using CreateFactory2 = HRESULT(WINAPI*)(UINT, REFIID, void**);
162 const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
163 const HMODULE dxgi = LoadLibraryExA("dxgi.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
164 const auto create_device = d3d12 ? reinterpret_cast<CreateDevice>(
165 reinterpret_cast<void*>(GetProcAddress(d3d12, "D3D12CreateDevice")))
166 : nullptr;
167 const auto create_factory = dxgi ? reinterpret_cast<CreateFactory2>(
168 reinterpret_cast<void*>(GetProcAddress(dxgi, "CreateDXGIFactory2")))
169 : nullptr;
170 ID3D12Device* host_device = nullptr;
171 IDXGIFactory4* host_factory = nullptr;
172 ID3D12CommandQueue* host_queue = nullptr;
173 const D3D12_COMMAND_QUEUE_DESC queue_desc{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, D3D12_COMMAND_QUEUE_FLAG_NONE, 0};
174 if (!create_device || !create_factory ||
175 FAILED(create_device(nullptr, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host_device))) ||
176 FAILED(create_factory(0, IID_PPV_ARGS(&host_factory))) ||
177 FAILED(host_device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&host_queue)))) {
178 if (host_factory) host_factory->Release();
179 if (host_device) host_device->Release();
180 return -1;
181 }
182 DXGI_SWAP_CHAIN_DESC1 base{};
183 base.Width = 64;
184 base.Height = 64;
185 base.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
186 base.SampleDesc.Count = 1;
187 base.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
188 base.BufferCount = 2;
189 base.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
190 enum class Pass { queue, null_queue, device, null_window, null_desc, null_out };
191 struct Case {
192 const char* name;
193 DXGI_SWAP_CHAIN_DESC1 desc;
194 Pass pass = Pass::queue;
195 };
196 const auto with = [&](void (*edit)(DXGI_SWAP_CHAIN_DESC1&)) {
197 DXGI_SWAP_CHAIN_DESC1 d = base;
198 edit(d);
199 return d;
200 };
201 const Case cases[] = {
202 {"valid", base},
203 {"flip sequential, 3 buffers", with([](DXGI_SWAP_CHAIN_DESC1& d) {
204 d.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;
205 d.BufferCount = 3;
206 })},
207 {"effect DISCARD", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; })},
208 {"effect SEQUENTIAL", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.SwapEffect = DXGI_SWAP_EFFECT_SEQUENTIAL; })},
209 {"effect 99", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.SwapEffect = DXGI_SWAP_EFFECT(99); })},
210 {"scaling NONE", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Scaling = DXGI_SCALING_NONE; })},
211 {"scaling ASPECT_RATIO_STRETCH",
212 with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Scaling = DXGI_SCALING_ASPECT_RATIO_STRETCH; })},
213 {"scaling 7", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Scaling = DXGI_SCALING(7); })},
214 {"alpha IGNORE", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.AlphaMode = DXGI_ALPHA_MODE_IGNORE; })},
215 {"alpha PREMULTIPLIED", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.AlphaMode = DXGI_ALPHA_MODE_PREMULTIPLIED; })},
216 {"alpha STRAIGHT", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.AlphaMode = DXGI_ALPHA_MODE_STRAIGHT; })},
217 {"alpha 9", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.AlphaMode = DXGI_ALPHA_MODE(9); })},
218 {"flag NONPREROTATED", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Flags = DXGI_SWAP_CHAIN_FLAG_NONPREROTATED; })},
219 {"flag ALLOW_MODE_SWITCH",
220 with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; })},
221 {"flag GDI_COMPATIBLE", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Flags = DXGI_SWAP_CHAIN_FLAG_GDI_COMPATIBLE; })},
222 {"flag DISPLAY_ONLY", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Flags = DXGI_SWAP_CHAIN_FLAG_DISPLAY_ONLY; })},
223 {"flag FRAME_LATENCY_WAITABLE_OBJECT", with([](DXGI_SWAP_CHAIN_DESC1& d) {
224 d.Flags = DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT;
225 })},
226 {"flag FOREGROUND_LAYER",
227 with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Flags = DXGI_SWAP_CHAIN_FLAG_FOREGROUND_LAYER; })},
228 {"flag HW_PROTECTED", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Flags = DXGI_SWAP_CHAIN_FLAG_HW_PROTECTED; })},
229 {"flag ALLOW_TEARING", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING; })},
230 {"flag 0x1000", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Flags = 0x1000; })},
231 {"flag 0x2000", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Flags = 0x2000; })},
232 {"flag 0x4000", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Flags = 0x4000; })},
233 {"flag 0x80000000", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Flags = 0x80000000u; })},
234 {"usage 0", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.BufferUsage = 0; })},
235 {"usage SHADER_INPUT", with([](DXGI_SWAP_CHAIN_DESC1& d) {
236 d.BufferUsage = DXGI_USAGE_SHADER_INPUT | DXGI_USAGE_RENDER_TARGET_OUTPUT;
237 })},
238 {"usage SHARED", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.BufferUsage = DXGI_USAGE_SHARED; })},
239 {"usage READ_ONLY", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.BufferUsage = DXGI_USAGE_READ_ONLY; })},
240 {"usage DISCARD_ON_PRESENT",
241 with([](DXGI_SWAP_CHAIN_DESC1& d) { d.BufferUsage = DXGI_USAGE_DISCARD_ON_PRESENT; })},
242 {"usage UNORDERED_ACCESS", with([](DXGI_SWAP_CHAIN_DESC1& d) {
243 d.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT | DXGI_USAGE_UNORDERED_ACCESS;
244 })},
245 {"16384 x 16", with([](DXGI_SWAP_CHAIN_DESC1& d) {
246 d.Width = 16384;
247 d.Height = 16;
248 })},
249 {"width 16385", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Width = 16385; })},
250 {"height 16385", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Height = 16385; })},
251 {"one buffer", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.BufferCount = 1; })},
252 {"MSAA 4", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.SampleDesc.Count = 4; })},
253 {"width 16385 and MSAA 4", with([](DXGI_SWAP_CHAIN_DESC1& d) {
254 d.Width = 16385;
255 d.SampleDesc.Count = 4;
256 })},
257 {"width 16385 and one buffer", with([](DXGI_SWAP_CHAIN_DESC1& d) {
258 d.Width = 16385;
259 d.BufferCount = 1;
260 })},
261 {"width 16385 and format UNKNOWN", with([](DXGI_SWAP_CHAIN_DESC1& d) {
262 d.Width = 16385;
263 d.Format = DXGI_FORMAT_UNKNOWN;
264 })},
265 {"height 16385 and format BC1", with([](DXGI_SWAP_CHAIN_DESC1& d) {
266 d.Height = 16385;
267 d.Format = DXGI_FORMAT_BC1_UNORM;
268 })},
269 {"width 16385 and effect DISCARD", with([](DXGI_SWAP_CHAIN_DESC1& d) {
270 d.Width = 16385;
271 d.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
272 })},
273 {"null queue", base, Pass::null_queue},
274 {"a device, not a queue", base, Pass::device},
275 {"null window", base, Pass::null_window},
276 {"null description", base, Pass::null_desc},
277 {"null output", base, Pass::null_out},
278 };
279 int mismatches = 0;
280 for (const Case& c : cases) {
281 HRESULT result[2];
282 for (int side = 0; side < 2; ++side) {
283 IDXGIFactory4* factory = side ? host_factory : ours;
284 IUnknown* queue = side ? static_cast<IUnknown*>(host_queue) : static_cast<IUnknown*>(our_queue);
285 if (c.pass == Pass::null_queue) queue = nullptr;
286 if (c.pass == Pass::device) queue = side ? static_cast<IUnknown*>(host_device) : our_device;
287 HWND hwnd = create_test_window(64, 64);
288 IDXGISwapChain1* chain = nullptr;
289 result[side] = create_guarded(factory, queue, c.pass == Pass::null_window ? nullptr : hwnd,
290 c.pass == Pass::null_desc ? nullptr : &c.desc,
291 c.pass == Pass::null_out ? nullptr : &chain);
292 if (chain) chain->Release();
293 if (hwnd) DestroyWindow(hwnd);
294 }
295 if (result[0] != result[1]) {
296 ++mismatches;
297 std::fprintf(stderr, "CreateSwapChainForHwnd %s: ours 0x%08lx, host 0x%08lx\n", c.name,
298 static_cast<unsigned long>(result[0]), static_cast<unsigned long>(result[1]));
299 }
300 }
301 std::printf("CreateSwapChainForHwnd: %zu descriptions compared with the host runtime, %d mismatches\n",
302 std::size(cases), mismatches);
303 host_queue->Release();
304 host_factory->Release();
305 host_device->Release();
306 return mismatches;
307}
308
96int main() { 309int main() {
97 const PFN_vkGetInstanceProcAddr gipa = load_vulkan(); 310 const PFN_vkGetInstanceProcAddr gipa = load_vulkan();
98 if (!gipa) { 311 if (!gipa) {
@@ -286,6 +499,11 @@ int main() {
286 return fail("queue/alloc/cl/fence"); 499 return fail("queue/alloc/cl/fence");
287 cl->Close(); 500 cl->Close();
288 501
502 // Before the test's own swap chain: the host comparison creates and releases its own windows and chains.
503 const int argument_mismatches = compare_swap_chain_arguments(factory, dev, queue);
504 if (argument_mismatches < 0) std::printf("CreateSwapChainForHwnd: no host D3D12 device to compare with, skipped\n");
505 if (argument_mismatches > 0) return fail("CreateSwapChainForHwnd answers differ from the host runtime");
506
289 DXGI_SWAP_CHAIN_DESC1 scd{}; 507 DXGI_SWAP_CHAIN_DESC1 scd{};
290 scd.Width = 128; 508 scd.Width = 128;
291 scd.Height = 128; 509 scd.Height = 128;
@@ -327,6 +545,16 @@ int main() {
327 if (FAILED(sc1->QueryInterface(IID_PPV_ARGS(&sc))) || !sc) return fail("QI IDXGISwapChain3"); 545 if (FAILED(sc1->QueryInterface(IID_PPV_ARGS(&sc))) || !sc) return fail("QI IDXGISwapChain3");
328 sc1->Release(); 546 sc1->Release();
329 547
548 // DXGI reports the BufferCount the app created with, never a larger native/Vulkan image count (D3D-389).
549 {
550 DXGI_SWAP_CHAIN_DESC1 created_desc{};
551 DXGI_SWAP_CHAIN_DESC created_desc0{};
552 if (FAILED(sc->GetDesc1(&created_desc)) || created_desc.BufferCount != scd.BufferCount)
553 return fail("GetDesc1 BufferCount is not the requested count");
554 if (FAILED(sc->GetDesc(&created_desc0)) || created_desc0.BufferCount != scd.BufferCount)
555 return fail("GetDesc BufferCount is not the requested count");
556 }
557
330 if (!check_statistics_disjoint(sc)) return fail("initial frame-statistics disjoint notification"); 558 if (!check_statistics_disjoint(sc)) return fail("initial frame-statistics disjoint notification");
331 559
332 ID3D12Device* got_device = nullptr; 560 ID3D12Device* got_device = nullptr;
@@ -401,6 +629,7 @@ int main() {
401 return 1; 629 return 1;
402 } 630 }
403 const UINT idx = sc->GetCurrentBackBufferIndex(); 631 const UINT idx = sc->GetCurrentBackBufferIndex();
632 if (idx >= cur_desc.BufferCount) return fail("GetCurrentBackBufferIndex >= BufferCount");
404 ID3D12Resource* bb = nullptr; 633 ID3D12Resource* bb = nullptr;
405 if (FAILED(sc->GetBuffer(idx, IID_PPV_ARGS(&bb))) || !bb) return fail("GetBuffer"); 634 if (FAILED(sc->GetBuffer(idx, IID_PPV_ARGS(&bb))) || !bb) return fail("GetBuffer");
406 635
@@ -610,6 +839,7 @@ int main() {
610 return fail("GetDesc1 did not preserve 37x19 R10G10B10A2_UNORM"); 839 return fail("GetDesc1 did not preserve 37x19 R10G10B10A2_UNORM");
611 840
612 const UINT idx = sc->GetCurrentBackBufferIndex(); 841 const UINT idx = sc->GetCurrentBackBufferIndex();
842 if (idx >= d10.BufferCount) return fail("GetCurrentBackBufferIndex >= BufferCount (10-bit)");
613 ID3D12Resource* bb = nullptr; 843 ID3D12Resource* bb = nullptr;
614 if (FAILED(sc->GetBuffer(idx, IID_PPV_ARGS(&bb))) || !bb) return fail("GetBuffer (10-bit)"); 844 if (FAILED(sc->GetBuffer(idx, IID_PPV_ARGS(&bb))) || !bb) return fail("GetBuffer (10-bit)");
615 const D3D12_RESOURCE_DESC bb_desc = bb->GetDesc(); 845 const D3D12_RESOURCE_DESC bb_desc = bb->GetDesc();
@@ -822,6 +1052,16 @@ int main() {
822 return fail("Non-waitable SetMaximumFrameLatency should return DXGI_ERROR_INVALID_CALL"); 1052 return fail("Non-waitable SetMaximumFrameLatency should return DXGI_ERROR_INVALID_CALL");
823 } 1053 }
824 1054
1055 // IDXGIObject private data on the swapchain, the factory and an adapter.
1056 {
1057 if (const char* step = check_private_data(sc)) return fail(step);
1058 if (const char* step = check_private_data(factory)) return fail(step);
1059 IDXGIAdapter1* pd_adapter = nullptr;
1060 if (FAILED(factory->EnumAdapters1(0, &pd_adapter)) || !pd_adapter) return fail("EnumAdapters1(0) for private data");
1061 if (const char* step = check_private_data(pd_adapter)) return fail(step);
1062 pd_adapter->Release();
1063 }
1064
825 // IDXGIFactory4 adapter enumeration, IDXGIAdapter3 descriptors, EnumAdapterByLuid, and QueryVideoMemoryInfo. 1065 // IDXGIFactory4 adapter enumeration, IDXGIAdapter3 descriptors, EnumAdapterByLuid, and QueryVideoMemoryInfo.
826 { 1066 {
827 IDXGIAdapter1* adapter1 = nullptr; 1067 IDXGIAdapter1* adapter1 = nullptr;
diff --git a/runtime/test/file_system_test.cpp b/runtime/test/file_system_test.cpp
index f51dd32e0..58233ee98 100644
--- a/runtime/test/file_system_test.cpp
+++ b/runtime/test/file_system_test.cpp
@@ -571,6 +571,52 @@ int main() {
571 "CreateFile2 refuses a path above GAME:"); 571 "CreateFile2 refuses a path above GAME:");
572 if (h_esc != INVALID_HANDLE_VALUE) ::CloseHandle(h_esc); 572 if (h_esc != INVALID_HANDLE_VALUE) ::CloseHandle(h_esc);
573 573
574 // MAXIMUM_ALLOWED asks for every right the file grants, write included, without naming one. Such an open of
575 // a package file is a write-open: it gets the overlay copy, so a write through the handle cannot reach the
576 // package. CreateFileW, CreateFileA and CreateFile2 share the rule. The write is shorter than the file, so
577 // the bytes after it show the overlay copy started as the package file's contents (OPEN_EXISTING keeps them).
578 {
579 write_path(package / "data" / "max_w.txt", "pkg-max");
580 write_path(package / "data" / "max_a.txt", "pkg-max");
581 write_path(package / "data" / "max_2.txt", "pkg-max");
582 const auto write_through = [](HANDLE h) {
583 if (h == INVALID_HANDLE_VALUE) return false;
584 DWORD written = 0;
585 const BOOL ok = ::WriteFile(h, "OV", 2, &written, nullptr);
586 ::CloseHandle(h);
587 return ok != FALSE && written == 2;
588 };
589 check(write_through(create_w(L"GAME:\\data\\max_w.txt", MAXIMUM_ALLOWED, 0, nullptr, OPEN_EXISTING, 0,
590 nullptr)),
591 "CreateFileW(MAXIMUM_ALLOWED, OPEN_EXISTING) opens a package file for writing");
592 check(read_path(package / "data" / "max_w.txt") == "pkg-max",
593 "a write through a MAXIMUM_ALLOWED handle does not reach the package (CreateFileW)");
594 check(read_path(overlay / "data" / "max_w.txt") == "OVg-max",
595 "the write through a MAXIMUM_ALLOWED handle is in the overlay copy (CreateFileW)");
596
597 check(write_through(create_a("GAME:\\data\\max_a.txt", MAXIMUM_ALLOWED | GENERIC_READ, 0, nullptr,
598 OPEN_EXISTING, 0, nullptr)),
599 "CreateFileA(MAXIMUM_ALLOWED | GENERIC_READ, OPEN_EXISTING) opens a package file for writing");
600 check(read_path(package / "data" / "max_a.txt") == "pkg-max" &&
601 read_path(overlay / "data" / "max_a.txt") == "OVg-max",
602 "the write goes to the overlay and not the package (CreateFileA)");
603
604 check(write_through(create2(L"GAME:\\data\\max_2.txt", MAXIMUM_ALLOWED, 0, OPEN_EXISTING, &ext)),
605 "CreateFile2(MAXIMUM_ALLOWED, OPEN_EXISTING) opens a package file for writing");
606 check(read_path(package / "data" / "max_2.txt") == "pkg-max" &&
607 read_path(overlay / "data" / "max_2.txt") == "OVg-max",
608 "the write goes to the overlay and not the package (CreateFile2)");
609
610 // A plain read still opens the package file in place: no overlay copy appears for it.
611 write_path(package / "data" / "max_read.txt", "pkg-max");
612 const HANDLE h_plain = create_w(L"GAME:\\data\\max_read.txt", GENERIC_READ, FILE_SHARE_READ, nullptr,
613 OPEN_EXISTING, 0, nullptr);
614 check(h_plain != INVALID_HANDLE_VALUE && read_handle(h_plain) == "pkg-max" &&
615 !std::filesystem::exists(overlay / "data" / "max_read.txt"),
616 "a GENERIC_READ open is still a read: no overlay copy is made");
617 if (h_plain != INVALID_HANDLE_VALUE) ::CloseHandle(h_plain);
618 }
619
574 // FindFirstFileExW merges package + overlay and honours FindExInfoBasic & FindExSearchLimitToDirectories. 620 // FindFirstFileExW merges package + overlay and honours FindExInfoBasic & FindExSearchLimitToDirectories.
575 WIN32_FIND_DATAW fd{}; 621 WIN32_FIND_DATAW fd{};
576 std::vector<std::wstring> basic_names; 622 std::vector<std::wstring> basic_names;
diff --git a/runtime/test/fixtures/d3d12_xs_stub.cpp b/runtime/test/fixtures/d3d12_xs_stub.cpp
new file mode 100644
index 000000000..e60c9b388
--- /dev/null
+++ b/runtime/test/fixtures/d3d12_xs_stub.cpp
@@ -0,0 +1,10 @@
1// Link-time stand-in for the console's d3d12_xs.dll, so tiny_frame.exe gets a real import of
2// D3D12XboxCreateDevice. Under `gta6rt --run` the shim registry answers the import and this DLL never loads; it is
3// built into a folder the loader does not search. Test code, not game content.
4#include <windows.h>
5#include <unknwn.h>
6
7extern "C" HRESULT __stdcall D3D12XboxCreateDevice(IUnknown*, const void*, const IID*, void** out) {
8 if (out) *out = nullptr;
9 return E_FAIL;
10}
diff --git a/runtime/test/fixtures/d3d12_xs_stub.def b/runtime/test/fixtures/d3d12_xs_stub.def
new file mode 100644
index 000000000..608feffc1
--- /dev/null
+++ b/runtime/test/fixtures/d3d12_xs_stub.def
@@ -0,0 +1,3 @@
1LIBRARY d3d12_xs
2EXPORTS
3 D3D12XboxCreateDevice
diff --git a/runtime/test/fixtures/dll_thread_calls.cpp b/runtime/test/fixtures/dll_thread_calls.cpp
index 4f4d73eb8..4d50229c5 100644
--- a/runtime/test/fixtures/dll_thread_calls.cpp
+++ b/runtime/test/fixtures/dll_thread_calls.cpp
@@ -4,6 +4,15 @@
4// data. 4// data.
5#include <windows.h> 5#include <windows.h>
6 6
7#ifdef __MSVC_RUNTIME_CHECKS
8// Debug builds compile with /RTC1 (the Visual Studio generator's default), whose checks call into the CRT; /NODEFAULTLIB
9// leaves these unresolved (LNK1120). The checks have nothing to check here, so they do nothing.
10extern "C" {
11void __cdecl _RTC_InitBase() {}
12void __cdecl _RTC_Shutdown() {}
13}
14#endif
15
7extern "C" BOOL WINAPI dll_thread_calls_main(HINSTANCE instance, DWORD reason, LPVOID) { 16extern "C" BOOL WINAPI dll_thread_calls_main(HINSTANCE instance, DWORD reason, LPVOID) {
8 if (reason == DLL_PROCESS_ATTACH) return DisableThreadLibraryCalls(instance); 17 if (reason == DLL_PROCESS_ATTACH) return DisableThreadLibraryCalls(instance);
9 return TRUE; 18 return TRUE;
diff --git a/runtime/test/fixtures/gameinput_host.cpp b/runtime/test/fixtures/gameinput_host.cpp
new file mode 100644
index 000000000..f28945045
--- /dev/null
+++ b/runtime/test/fixtures/gameinput_host.cpp
@@ -0,0 +1,43 @@
1// A DLL that does what a title's input code does first: GameInputCreate, a timestamp, a gamepad reading. It uses the
2// Windows SDK's public GameInput.h and links against the SDK's gameinput.lib, so GameInputCreate is imported from
3// GameInput.dll (by ordinal) like any title's import. Built without the CRT: DllMain does nothing and the exports call
4// only GameInput. gameinput_host_test maps it with the loader. No game data.
5#include <windows.h>
6
7#include <GameInput.h>
8
9extern "C" BOOL WINAPI gameinput_host_main(HINSTANCE, DWORD, LPVOID) { return TRUE; }
10
11#ifdef __MSVC_RUNTIME_CHECKS
12// Debug builds compile with /RTC1 (the Visual Studio generator's default), whose checks call into the CRT; /NODEFAULTLIB
13// leaves these three unresolved (LNK1120). The checks have nothing to check here, so they do nothing.
14extern "C" {
15void __cdecl _RTC_InitBase() {}
16void __cdecl _RTC_Shutdown() {}
17void __fastcall _RTC_CheckStackVars(void*, void*) {}
18}
19#endif
20
21// Returns 1 when the library was created. reading_hr is S_OK with a gamepad attached and
22// GAMEINPUT_E_READING_NOT_FOUND without one (E_FAIL when the library was not created); state_ok is 1 when
23// GetGamepadState succeeded on a reading.
24extern "C" __declspec(dllexport) int gameinput_host_probe(long* create_hr, unsigned long long* timestamp,
25 long* reading_hr, int* state_ok) {
26 IGameInput* input = nullptr;
27 IGameInputReading* reading = nullptr;
28 const HRESULT hr = GameInputCreate(&input);
29 *create_hr = hr;
30 *timestamp = 0;
31 *reading_hr = E_FAIL; // not S_OK: a failed GameInputCreate must not look like an attached gamepad
32 *state_ok = 0;
33 if (FAILED(hr) || !input) return 0;
34 *timestamp = input->GetCurrentTimestamp();
35 *reading_hr = input->GetCurrentReading(GameInputKindGamepad, nullptr, &reading);
36 if (SUCCEEDED(*reading_hr) && reading) {
37 GameInputGamepadState state;
38 *state_ok = reading->GetGamepadState(&state) ? 1 : 0;
39 reading->Release();
40 }
41 input->Release();
42 return 1;
43}
diff --git a/runtime/test/fixtures/tiny_atexit.cpp b/runtime/test/fixtures/tiny_atexit.cpp
new file mode 100644
index 000000000..fbe071e7f
--- /dev/null
+++ b/runtime/test/fixtures/tiny_atexit.cpp
@@ -0,0 +1,92 @@
1// A stand-in program for `gta6rt --run`: atexit handlers, static destructors and the ways a program ends.
2// Test code, not game content. check_atexit.cmake runs it natively and through the loader with each mode below
3// and compares the lines it prints.
4// return main returns: handlers and static destructors run, in reverse order of registration
5// exit exit(7): the same
6// _exit _exit(8): no handlers, no destructors
7// quick_exit quick_exit(9): no atexit handlers, no destructors
8// ExitProcess ExitProcess(10): no handlers, no destructors
9// cexit _cexit() runs every handler and returns; main then returns 11
10// c_exit _c_exit() runs none and returns; main then returns 12, and exit runs them all
11// concurrent_exit a second thread calls _exit(7) while exit(7) runs a handler: it waits for them all
12// One handler registers another while the handlers run: it must still run, next.
13#include <windows.h>
14#include <process.h> // _cexit, _c_exit
15
16#include <cstdio>
17#include <cstdlib>
18#include <cstring>
19
20namespace {
21
22void say(const char* what) {
23 std::printf("tiny_atexit: %s\n", what);
24 std::fflush(stdout); // every line reaches the pipe before any way out, natively and under the loader
25}
26
27struct Tracer {
28 const char* name;
29 explicit Tracer(const char* n) : name(n) {
30 std::printf("tiny_atexit: ctor %s\n", name);
31 std::fflush(stdout);
32 }
33 ~Tracer() {
34 std::printf("tiny_atexit: dtor %s\n", name);
35 std::fflush(stdout);
36 }
37};
38Tracer g_first("first");
39Tracer g_second("second");
40
41void handler_one() { say("atexit one"); }
42void handler_two() { say("atexit two"); }
43void handler_late() { say("atexit late"); }
44void handler_registers() {
45 say("atexit registers late");
46 std::atexit(handler_late);
47}
48
49// concurrent_exit: while exit() runs this handler on the main thread, a second thread calls _exit(). The CRT lets
50// it go once the handlers are done, so either call may set the exit code: both use 7.
51HANDLE g_slow_started = nullptr;
52void handler_slow() {
53 say("slow handler started");
54 SetEvent(g_slow_started);
55 Sleep(300);
56 say("slow handler done");
57}
58DWORD WINAPI quick_exit_thread(void*) {
59 WaitForSingleObject(g_slow_started, INFINITE);
60 _exit(7);
61}
62
63} // namespace
64
65int main(int argc, char** argv) {
66 const char* mode = argc > 1 ? argv[1] : "return";
67 std::atexit(handler_one);
68 std::atexit(handler_registers);
69 std::atexit(handler_two);
70 say("main");
71 if (!std::strcmp(mode, "concurrent_exit")) {
72 g_slow_started = CreateEventW(nullptr, TRUE, FALSE, nullptr);
73 std::atexit(handler_slow);
74 CloseHandle(CreateThread(nullptr, 0, quick_exit_thread, nullptr, 0, nullptr));
75 std::exit(7);
76 }
77 if (!std::strcmp(mode, "exit")) std::exit(7);
78 if (!std::strcmp(mode, "_exit")) _exit(8);
79 if (!std::strcmp(mode, "quick_exit")) std::quick_exit(9);
80 if (!std::strcmp(mode, "ExitProcess")) ExitProcess(10);
81 if (!std::strcmp(mode, "cexit")) {
82 _cexit();
83 say("after _cexit");
84 return 11;
85 }
86 if (!std::strcmp(mode, "c_exit")) {
87 _c_exit();
88 say("after _c_exit");
89 return 12;
90 }
91 return 3;
92}
diff --git a/runtime/test/fixtures/tiny_frame.cpp b/runtime/test/fixtures/tiny_frame.cpp
new file mode 100644
index 000000000..c30f7cc5c
--- /dev/null
+++ b/runtime/test/fixtures/tiny_frame.cpp
@@ -0,0 +1,166 @@
1// A stand-in title for `gta6rt --run` that reaches the D3D12 layer the way a title does: it imports
2// d3d12_xs.dll!D3D12XboxCreateDevice (from a link-time stub; the shim registry answers it) and then does the least
3// a title does before its first frame, on the device that call returns: a direct queue, an allocator, a command
4// list, a fence, an RTV heap whose start handle is read in the console shape (the 8-byte handle in RAX, heap slot 9),
5// a committed render target, a clear, a copy into a readback buffer, Signal and a fence wait, Map, and a check of
6// every pixel. It then returns from main with the device, the queue and the fence still alive, as a title's exit
7// does. With LEONIDA_D3D12=vulkan (check_tiny_frame.py sets it) that device is the Vulkan-backed one, so this is the
8// loader, the game thread, the Xbox-ABI proxies and the Vulkan device in one process. Hand-written test code, public
9// D3D12 API only; no game data and no shader.
10#include <windows.h>
11#include <d3d12.h>
12
13#include <cstdint>
14#include <cstdio>
15#include <cstring>
16
17extern "C" __declspec(dllimport) HRESULT __stdcall D3D12XboxCreateDevice(IUnknown* adapter, const void* params,
18 const IID* riid, void** device);
19
20namespace {
21
22int g_failures = 0;
23
24bool check(bool ok, const char* what) {
25 std::printf("tiny_frame: %s %s\n", ok ? "PASS" : "FAIL", what);
26 if (!ok) ++g_failures;
27 return ok;
28}
29
30int finish() {
31 std::printf("tiny_frame: %s\n", g_failures ? "FAILED" : "OK");
32 std::fflush(stdout);
33 return g_failures ? 1 : 0;
34}
35
36// Descriptor-heap slot 9 on the console returns the handle in RAX (docs/d3d12_vulkan.md section 7); the PC header's
37// GetCPUDescriptorHandleForHeapStart returns it through a hidden pointer, which the heap proxy does not serve.
38using HeapStartFn = std::uint64_t(__stdcall*)(void* heap);
39
40constexpr UINT kWidth = 8, kHeight = 4;
41
42} // namespace
43
44int main() {
45 std::setvbuf(stdout, nullptr, _IONBF, 0);
46
47 // The entry point's second argument is a block the shim logs and does not interpret; a title passes its own.
48 std::uint32_t params[24] = {};
49 const IID device_iid = __uuidof(ID3D12Device);
50 ID3D12Device* device = nullptr;
51 HRESULT hr = D3D12XboxCreateDevice(nullptr, params, &device_iid, reinterpret_cast<void**>(&device));
52 if (!check(hr == S_OK && device, "D3D12XboxCreateDevice returns a device")) {
53 std::printf("tiny_frame: hr=0x%08lx\n", static_cast<unsigned long>(hr));
54 return finish();
55 }
56
57 ID3D12CommandQueue* queue = nullptr;
58 ID3D12CommandAllocator* allocator = nullptr;
59 ID3D12GraphicsCommandList* list = nullptr;
60 ID3D12Fence* fence = nullptr;
61 D3D12_COMMAND_QUEUE_DESC queue_desc{};
62 queue_desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
63 check(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue))) && queue, "a direct command queue");
64 check(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator))) &&
65 allocator, "a command allocator");
66 if (allocator)
67 check(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator, nullptr,
68 IID_PPV_ARGS(&list))) && list, "a command list");
69 check(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence))) && fence, "a fence");
70
71 ID3D12DescriptorHeap* rtv_heap = nullptr;
72 D3D12_DESCRIPTOR_HEAP_DESC heap_desc{};
73 heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
74 heap_desc.NumDescriptors = 1;
75 check(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&rtv_heap))) && rtv_heap, "an RTV heap");
76 if (!queue || !list || !fence || !rtv_heap) return finish();
77 const std::uint64_t start = reinterpret_cast<HeapStartFn>((*reinterpret_cast<void***>(rtv_heap))[9])(rtv_heap);
78 check(start != 0, "the heap's start handle comes back in RAX (heap slot 9)");
79 const D3D12_CPU_DESCRIPTOR_HANDLE rtv{static_cast<SIZE_T>(start)};
80
81 D3D12_HEAP_PROPERTIES default_heap{}, readback_heap{};
82 default_heap.Type = D3D12_HEAP_TYPE_DEFAULT;
83 readback_heap.Type = D3D12_HEAP_TYPE_READBACK;
84 D3D12_RESOURCE_DESC target_desc{};
85 target_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
86 target_desc.Width = kWidth;
87 target_desc.Height = kHeight;
88 target_desc.DepthOrArraySize = 1;
89 target_desc.MipLevels = 1;
90 target_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
91 target_desc.SampleDesc.Count = 1;
92 target_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
93 ID3D12Resource* target = nullptr;
94 check(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &target_desc,
95 D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr,
96 IID_PPV_ARGS(&target))) && target, "a committed render target");
97
98 D3D12_PLACED_SUBRESOURCE_FOOTPRINT placed{};
99 UINT rows = 0;
100 UINT64 row_bytes = 0, total = 0;
101 device->GetCopyableFootprints(&target_desc, 0, 1, 0, &placed, &rows, &row_bytes, &total);
102 check(rows == kHeight && row_bytes == kWidth * 4 && placed.Footprint.RowPitch >= kWidth * 4 && total != 0,
103 "GetCopyableFootprints describes the target");
104 D3D12_RESOURCE_DESC buffer_desc{};
105 buffer_desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
106 buffer_desc.Width = total ? total : 4096;
107 buffer_desc.Height = 1;
108 buffer_desc.DepthOrArraySize = 1;
109 buffer_desc.MipLevels = 1;
110 buffer_desc.SampleDesc.Count = 1;
111 buffer_desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
112 ID3D12Resource* readback = nullptr;
113 check(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &buffer_desc,
114 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
115 IID_PPV_ARGS(&readback))) && readback, "a readback buffer");
116 if (!target || !readback) return finish();
117
118 device->CreateRenderTargetView(target, nullptr, rtv);
119 const FLOAT colour[4] = {64.0f / 255.0f, 128.0f / 255.0f, 191.0f / 255.0f, 1.0f};
120 list->ClearRenderTargetView(rtv, colour, 0, nullptr);
121 D3D12_RESOURCE_BARRIER barrier{};
122 barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
123 barrier.Transition.pResource = target;
124 barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
125 barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET;
126 barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE;
127 list->ResourceBarrier(1, &barrier);
128 D3D12_TEXTURE_COPY_LOCATION from{}, to{};
129 from.pResource = target;
130 from.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
131 to.pResource = readback;
132 to.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
133 to.PlacedFootprint = placed;
134 list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr);
135 check(SUCCEEDED(list->Close()), "the list closes");
136 ID3D12CommandList* lists[] = {list};
137 queue->ExecuteCommandLists(1, lists);
138
139 HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr);
140 check(SUCCEEDED(queue->Signal(fence, 1)), "Signal");
141 check(done && SUCCEEDED(fence->SetEventOnCompletion(1, done)) && WaitForSingleObject(done, 30000) == WAIT_OBJECT_0,
142 "the fence reaches the signalled value");
143 check(fence->GetCompletedValue() >= 1, "GetCompletedValue is past the signal");
144 if (done) CloseHandle(done);
145
146 void* bytes = nullptr;
147 if (check(SUCCEEDED(readback->Map(0, nullptr, &bytes)) && bytes, "Map of the readback buffer")) {
148 const std::uint8_t want[4] = {64, 128, 191, 255};
149 unsigned wrong = 0;
150 for (UINT y = 0; y < kHeight; ++y)
151 for (UINT x = 0; x < kWidth; ++x)
152 wrong += std::memcmp(static_cast<const std::uint8_t*>(bytes) + placed.Offset +
153 y * placed.Footprint.RowPitch + x * 4, want, 4) != 0;
154 check(wrong == 0, "all 32 pixels are the clear colour (64, 128, 191, 255)");
155 readback->Unmap(0, nullptr);
156 }
157
158 // What a frame owns is released; the device, the queue and the fence stay alive across the return from main, so
159 // the run ends through the CRT's exit with the layer still up.
160 readback->Release();
161 target->Release();
162 rtv_heap->Release();
163 list->Release();
164 allocator->Release();
165 return finish();
166}
diff --git a/runtime/test/fixtures/tiny_gdk_load.cpp b/runtime/test/fixtures/tiny_gdk_load.cpp
index b37307369..9b4ad4e90 100644
--- a/runtime/test/fixtures/tiny_gdk_load.cpp
+++ b/runtime/test/fixtures/tiny_gdk_load.cpp
@@ -98,8 +98,9 @@ int main() {
98 reinterpret_cast<Close>(vtable[17])(obj, queue); 98 reinterpret_cast<Close>(vtable[17])(obj, queue);
99 reinterpret_cast<Release>(vtable[2])(obj); 99 reinterpret_cast<Release>(vtable[2])(obj);
100 100
101 // A class not served (an id no runtime class has) is refused, with the out pointer cleared. 101 // A class not served (an id no runtime class has) is refused, with the out pointer cleared: XGameSaveImpl
102 const GUID unserved = {0x973a344e, 0x24bf, 0x4d0f, {0x84, 0x57, 0x56, 0xc5, 0x34, 0x89, 0x2b, 0x29}}; 102 // (xgameruntime include/xgamesave.idl), which is not served yet.
103 const GUID unserved = {0x704c3f58, 0xe629, 0x4cc2, {0xb1, 0x97, 0x30, 0x51, 0x1b, 0x99, 0x6f, 0xe2}};
103 void* out = reinterpret_cast<void*>(1); 104 void* out = reinterpret_cast<void*>(1);
104 hr = query(&unserved, unserved, &out); 105 hr = query(&unserved, unserved, &out);
105 if (hr != static_cast<HRESULT>(0x80070032) || out != nullptr) 106 if (hr != static_cast<HRESULT>(0x80070032) || out != nullptr)
diff --git a/runtime/test/fixtures/tiny_tls_cb_only.cpp b/runtime/test/fixtures/tiny_tls_cb_only.cpp
index d8062c073..e8f80010a 100644
--- a/runtime/test/fixtures/tiny_tls_cb_only.cpp
+++ b/runtime/test/fixtures/tiny_tls_cb_only.cpp
@@ -2,6 +2,15 @@
2// and SizeOfZeroFill == 0 while providing a TLS callback (no CRT .tls section). Ordinary test code, not game data. 2// and SizeOfZeroFill == 0 while providing a TLS callback (no CRT .tls section). Ordinary test code, not game data.
3#include <windows.h> 3#include <windows.h>
4 4
5#ifdef __MSVC_RUNTIME_CHECKS
6// Debug builds compile with /RTC1 (the Visual Studio generator's default), whose checks call into the CRT; /NODEFAULTLIB
7// leaves these unresolved (LNK1120). The checks have nothing to check here, so they do nothing.
8extern "C" {
9void __cdecl _RTC_InitBase() {}
10void __cdecl _RTC_Shutdown() {}
11}
12#endif
13
5namespace { 14namespace {
6 15
7ULONG g_tls_index = 0; 16ULONG g_tls_index = 0;
diff --git a/runtime/test/gameinput_host_test.cpp b/runtime/test/gameinput_host_test.cpp
new file mode 100644
index 000000000..cdd071055
--- /dev/null
+++ b/runtime/test/gameinput_host_test.cpp
@@ -0,0 +1,90 @@
1// The host GameInput path: mapped code that imports GameInputCreate from GameInput.dll, with no GameInput shim.
2//
3// docs/gameinput.md: without the SDL3 shim, the loader binds GameInputCreate to the host's GameInput.dll. This checks
4// that path with a synthetic DLL (test/fixtures/gameinput_host.cpp) mapped by rt::Loader:
5// - its GameInput.dll import binds to the host's copy (this test links no shim table, so it cannot be a shim);
6// - GameInputCreate succeeds from mapped code, and the library answers GetCurrentTimestamp;
7// - GetCurrentReading says either "reading" or "no reading found": no crash, no other error. With a gamepad attached
8// GetGamepadState must succeed on the reading; the test passes with or without one.
9// Skips (exit 77) only where Windows itself cannot load GameInput.dll (asked before mapping, with LoadLibraryExW).
10// When the DLL is there, an import that binds to nothing is a failure, not a skip. No game files.
11#include <windows.h>
12
13#include <cstdio>
14#include <filesystem>
15#include <stdexcept>
16#include <string>
17
18#include "pe_loader.h"
19
20namespace {
21
22using ProbeFn = int (*)(long*, unsigned long long*, long*, int*);
23constexpr unsigned long kReadingNotFound = 0x838A0003UL; // GAMEINPUT_E_READING_NOT_FOUND
24
25int g_failures = 0;
26
27void check(bool ok, const std::string& what) {
28 std::printf("%s %s\n", ok ? "PASS" : "FAIL", what.c_str());
29 std::fflush(stdout);
30 if (!ok) ++g_failures;
31}
32
33} // namespace
34
35int main(int argc, char** argv) {
36 if (argc != 2) {
37 std::fprintf(stderr, "usage: gameinput_host_test <gameinput_host.dll>\n");
38 return 2;
39 }
40 const std::filesystem::path fixture = argv[1];
41
42 // Decide the skip from the machine, not from the loader's answer: a broken host binding must fail the test.
43 HMODULE const host_gameinput = LoadLibraryExW(L"GameInput.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
44 if (!host_gameinput) {
45 const DWORD error = GetLastError();
46 if (error == ERROR_MOD_NOT_FOUND || error == ERROR_FILE_NOT_FOUND || error == ERROR_PATH_NOT_FOUND) {
47 std::printf("SKIP: no GameInput.dll on this machine\n");
48 return 77;
49 }
50 std::printf("FAIL GameInput.dll is present but does not load (error %lu)\n", static_cast<unsigned long>(error));
51 return 1;
52 }
53
54 try {
55 rt::Loader loader(fixture.parent_path());
56 rt::Module& m = loader.load(fixture);
57
58 // The SDK's import library imports by ordinal, so match the DLL name, not the function name.
59 rt::Binding binding = rt::Binding::Unimplemented;
60 int seen = 0;
61 for (const auto& r : m.imports)
62 if (rt::lower(r.dll) == "gameinput.dll") {
63 binding = r.binding;
64 ++seen;
65 }
66 check(seen == 1 && binding == rt::Binding::Host, "the GameInput.dll import binds to the host's copy");
67
68 loader.initialise();
69 const auto probe = reinterpret_cast<ProbeFn>(m.exports.at("gameinput_host_probe"));
70 long create_hr = -1, reading_hr = -1;
71 unsigned long long timestamp = 0;
72 int state_ok = 0;
73 const int created = probe(&create_hr, &timestamp, &reading_hr, &state_ok);
74 std::printf(" create hr=0x%08lX, timestamp=%llu, reading hr=0x%08lX\n", static_cast<unsigned long>(create_hr),
75 timestamp, static_cast<unsigned long>(reading_hr));
76 check(created == 1 && create_hr == 0, "GameInputCreate succeeds from mapped code");
77 check(timestamp != 0, "GetCurrentTimestamp returns a time");
78 const bool pad = created == 1 && reading_hr == 0;
79 check(pad || static_cast<unsigned long>(reading_hr) == kReadingNotFound,
80 "GetCurrentReading says either 'reading' or 'no reading found'");
81 std::printf(" gamepad reading: %s\n", pad ? "yes (a gamepad is attached)" : "none (no gamepad attached)");
82 if (pad) check(state_ok == 1, "GetGamepadState succeeds on a real reading");
83 } catch (const std::exception& e) {
84 std::printf("FAIL unexpected exception: %s\n", e.what());
85 ++g_failures;
86 }
87 FreeLibrary(host_gameinput);
88 std::printf("gameinput_host_test: %s (%d failures)\n", g_failures ? "FAILED" : "OK", g_failures);
89 return g_failures ? 1 : 0;
90}
diff --git a/runtime/test/gameinput_test.cpp b/runtime/test/gameinput_test.cpp
index 1389b8f6d..679adf19f 100644
--- a/runtime/test/gameinput_test.cpp
+++ b/runtime/test/gameinput_test.cpp
@@ -6,7 +6,8 @@
6// without trigger motors. The test covers enumeration and device callbacks, readings and their button/axis mapping, 6// without trigger motors. The test covers enumeration and device callbacks, readings and their button/axis mapping,
7// UI navigation, the guide button, rumble and trigger rumble as SDL receives them, the DualSense effect bytes for 7// UI navigation, the guide button, rumble and trigger rumble as SDL receives them, the DualSense effect bytes for
8// each LEONIDA_DS_TRIGGERS mode, the lightbar, a dispatcher, unplug/replug, reading history, 8// each LEONIDA_DS_TRIGGERS mode, the lightbar, a dispatcher, unplug/replug, reading history,
9// and identification of two or three otherwise indistinguishable pads. No game data. 9// identification of two or three otherwise indistinguishable pads, and which kind of device was used last
10// (active_input, LEONIDA_PROMPTS). No game data.
10#include <windows.h> 11#include <windows.h>
11 12
12#include <SDL3/SDL.h> 13#include <SDL3/SDL.h>
@@ -794,6 +795,156 @@ void test_keyboard_pad(IGameInput* input) {
794 rt::gameinput::set_cursor_source(nullptr); 795 rt::gameinput::set_cursor_source(nullptr);
795} 796}
796 797
798// active_input(): which kind of device the player used last. Virtual pads with a DualSense, a DualShock 4 and an Xbox
799// pad's vendor and product id (SDL takes the gamepad type from them) plus the keyboard pad; first with no wait
800// between changes (LEONIDA_PROMPTS_SWITCH_MS=0), then with the default 300 ms window on the real clock, then a family
801// forced by LEONIDA_PROMPTS.
802void test_active_input() {
803 using leonida::InputFamily;
804 const auto family = [] { return rt::gameinput::active_input().family; };
805 const auto generation = [] { return rt::gameinput::active_input().generation; };
806
807 set_env("LEONIDA_PROMPTS", nullptr);
808 set_env("LEONIDA_PROMPTS_SWITCH_MS", "0");
809 rt::gameinput::reload_config();
810 rt::gameinput::poll();
811 check(!rt::gameinput::active_input().forced, "active input: not forced without LEONIDA_PROMPTS");
812
813 Pad ds, ds4, xbox;
814 attach(ds, "Leonida virtual DualSense", 0x054C, 0x0CE6, false);
815 attach(ds4, "Leonida virtual DualShock 4", 0x054C, 0x09CC, false);
816 attach(xbox, "Leonida virtual Xbox pad", 0x045E, 0x0B12, true);
817 SDL_SetJoystickVirtualButton(ds.js, SDL_GAMEPAD_BUTTON_SOUTH, true); // held while it connects
818 const uint64_t at_connect = generation();
819 rt::gameinput::poll();
820 check(rt::gameinput::connected_count() == 3, "active input: three pads open");
821 check(generation() == at_connect, "active input: connecting pads (one with a button held) changes nothing");
822
823 auto press = [](Pad& p, SDL_GamepadButton b) {
824 SDL_SetJoystickVirtualButton(p.js, b, true);
825 rt::gameinput::poll();
826 SDL_SetJoystickVirtualButton(p.js, b, false);
827 rt::gameinput::poll();
828 };
829 SDL_SetJoystickVirtualButton(ds.js, SDL_GAMEPAD_BUTTON_SOUTH, false); // the held button, let go
830 rt::gameinput::poll();
831 check(generation() == at_connect, "active input: letting go of a button is not input");
832
833 // The tests before this one leave whichever pad they used last; an Xbox press makes the start known.
834 press(xbox, SDL_GAMEPAD_BUTTON_SOUTH);
835 check(family() == InputFamily::Xbox, "active input: the Xbox pad in use");
836 const uint64_t g0 = generation();
837
838 press(ds, SDL_GAMEPAD_BUTTON_SOUTH);
839 check(family() == InputFamily::PlayStation5 && generation() == g0 + 1, "active input: DualSense press");
840 press(ds4, SDL_GAMEPAD_BUTTON_EAST);
841 check(family() == InputFamily::PlayStation4 && generation() == g0 + 2, "active input: DualShock 4 press");
842
843 // Stick drift on the Xbox pad (0.18) is not input; the stick pushed over is.
844 SDL_SetJoystickVirtualAxis(xbox.js, SDL_GAMEPAD_AXIS_LEFTX, 6000);
845 rt::gameinput::poll();
846 check(family() == InputFamily::PlayStation4 && generation() == g0 + 2, "active input: stick drift changes nothing");
847 SDL_SetJoystickVirtualAxis(xbox.js, SDL_GAMEPAD_AXIS_LEFTX, 32767);
848 rt::gameinput::poll();
849 check(family() == InputFamily::Xbox && generation() == g0 + 3, "active input: Xbox stick pushed over");
850 SDL_SetJoystickVirtualAxis(xbox.js, SDL_GAMEPAD_AXIS_LEFTX, 0);
851 rt::gameinput::poll();
852
853 // Buttons GameInput's gamepad state leaves out count too: the DualSense touchpad.
854 press(ds, SDL_GAMEPAD_BUTTON_TOUCHPAD);
855 check(family() == InputFamily::PlayStation5 && generation() == g0 + 4, "active input: DualSense touchpad click");
856 // A trigger pulled on the DualShock 4.
857 SDL_SetJoystickVirtualAxis(ds4.js, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, 32767);
858 rt::gameinput::poll();
859 check(family() == InputFamily::PlayStation4 && generation() == g0 + 5, "active input: DualShock 4 trigger pull");
860 SDL_SetJoystickVirtualAxis(ds4.js, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, -32768);
861 rt::gameinput::poll();
862
863 // The keyboard pad: a key, and the mouse through the keyboard pad's right stick.
864 rt::gameinput::set_keyboard_source(fake_key_down, fake_focus);
865 rt::gameinput::set_cursor_source(fake_cursor);
866 std::memset(g_keys, 0, sizeof g_keys);
867 g_cursor_x = g_cursor_y = 0;
868 set_env("LEONIDA_KEYBOARD_PAD", "always");
869 rt::gameinput::reload_config();
870 rt::gameinput::poll(); // attaches the keyboard pad
871 rt::gameinput::poll(); // opens it: its first sample is the baseline
872 check(rt::gameinput::connected_count() == 4 && generation() == g0 + 5,
873 "active input: the keyboard pad connecting changes nothing");
874 g_keys[VK_RETURN] = true;
875 rt::gameinput::poll();
876 g_keys[VK_RETURN] = false;
877 rt::gameinput::poll();
878 check(family() == InputFamily::Keyboard && generation() == g0 + 6, "active input: Enter on the keyboard pad");
879 press(xbox, SDL_GAMEPAD_BUTTON_SOUTH);
880 check(family() == InputFamily::Xbox && generation() == g0 + 7, "active input: back to the Xbox pad");
881 g_cursor_x += 1; // a 1-count jitter stays well inside the stick radius
882 rt::gameinput::poll();
883 check(family() == InputFamily::Xbox, "active input: mouse jitter changes nothing");
884 g_cursor_x += 20; // a real movement pushes the right stick past the radius
885 rt::gameinput::poll();
886 check(family() == InputFamily::Keyboard && generation() == g0 + 8, "active input: mouse movement");
887 for (int i = 0; i < 80; ++i) rt::gameinput::poll(); // the stick falls back to rest
888
889 // The default window on the real clock: a second change within 300 ms of the last is ignored.
890 set_env("LEONIDA_PROMPTS_SWITCH_MS", nullptr);
891 rt::gameinput::reload_config();
892 check(rt::gameinput::config().prompts_switch_ms == 300, "active input: 300 ms by default");
893 Sleep(350);
894 press(ds, SDL_GAMEPAD_BUTTON_NORTH);
895 check(family() == InputFamily::PlayStation5 && generation() == g0 + 9, "active input: DualSense after the window");
896 press(xbox, SDL_GAMEPAD_BUTTON_WEST);
897 check(family() == InputFamily::PlayStation5 && generation() == g0 + 9,
898 "active input: an Xbox press right after a change is ignored");
899 Sleep(350);
900 press(xbox, SDL_GAMEPAD_BUTTON_WEST);
901 check(family() == InputFamily::Xbox && generation() == g0 + 10,
902 "active input: the Xbox press once the window passed");
903
904 // LEONIDA_PROMPTS forces a family; tracking goes on underneath and takes over again when it is cleared.
905 set_env("LEONIDA_PROMPTS_SWITCH_MS", "0");
906 set_env("LEONIDA_PROMPTS", "keyboard");
907 rt::gameinput::reload_config();
908 rt::gameinput::poll();
909 check(family() == InputFamily::Keyboard && rt::gameinput::active_input().forced && generation() == g0 + 11,
910 "active input: LEONIDA_PROMPTS=keyboard");
911 press(ds, SDL_GAMEPAD_BUTTON_SOUTH);
912 check(family() == InputFamily::Keyboard && generation() == g0 + 11,
913 "active input: forced, a DualSense press shows nothing");
914 set_env("LEONIDA_PROMPTS", "PlayStation"); // case does not matter
915 rt::gameinput::reload_config();
916 rt::gameinput::poll();
917 check(family() == InputFamily::PlayStation5 && rt::gameinput::active_input().forced && generation() == g0 + 12,
918 "active input: LEONIDA_PROMPTS=PlayStation (any case) is PlayStation 5");
919 set_env("LEONIDA_PROMPTS", "ps4");
920 rt::gameinput::reload_config();
921 rt::gameinput::poll();
922 check(family() == InputFamily::PlayStation4 && generation() == g0 + 13, "active input: LEONIDA_PROMPTS=ps4");
923 set_env("LEONIDA_PROMPTS", "nonsense"); // warns and follows the devices
924 rt::gameinput::reload_config();
925 rt::gameinput::poll();
926 check(!rt::gameinput::active_input().forced && family() == InputFamily::PlayStation5 && generation() == g0 + 14,
927 "active input: an unknown LEONIDA_PROMPTS follows the devices (the DualSense pressed while forced)");
928 set_env("LEONIDA_PROMPTS", "playstation");
929 rt::gameinput::reload_config();
930 rt::gameinput::poll();
931 check(family() == InputFamily::PlayStation5 && rt::gameinput::active_input().forced && generation() == g0 + 14,
932 "active input: forcing the family already in use changes no generation");
933
934 // Clean up: everything off and unplugged.
935 set_env("LEONIDA_PROMPTS", nullptr);
936 set_env("LEONIDA_PROMPTS_SWITCH_MS", nullptr);
937 set_env("LEONIDA_KEYBOARD_PAD", nullptr);
938 rt::gameinput::reload_config();
939 detach(ds);
940 detach(ds4);
941 detach(xbox);
942 rt::gameinput::poll();
943 check(rt::gameinput::connected_count() == 0, "active input: all pads closed at the end");
944 rt::gameinput::set_keyboard_source(nullptr, nullptr);
945 rt::gameinput::set_cursor_source(nullptr);
946}
947
797bool same_id(const AppLocalDeviceId& a, const AppLocalDeviceId& b) { return std::memcmp(&a, &b, sizeof a) == 0; } 948bool same_id(const AppLocalDeviceId& a, const AppLocalDeviceId& b) { return std::memcmp(&a, &b, sizeof a) == 0; }
798 949
799// The id the shim derives from SDL: the GUID, then two FNV-1a hashes of "s:" serial, "p:" path or nothing, with 950// The id the shim derives from SDL: the GUID, then two FNV-1a hashes of "s:" serial, "p:" path or nothing, with
@@ -1815,6 +1966,7 @@ int main() {
1815 rt::gameinput::poll(); 1966 rt::gameinput::poll();
1816 check(rt::gameinput::connected_count() == 0, "all pads closed after detaching"); 1967 check(rt::gameinput::connected_count() == 0, "all pads closed after detaching");
1817 1968
1969 test_active_input();
1818 test_twins(input); 1970 test_twins(input);
1819 test_keyboard_pad(input); 1971 test_keyboard_pad(input);
1820 test_motion(input); 1972 test_motion(input);
diff --git a/runtime/test/gfx10_descriptors_test.cpp b/runtime/test/gfx10_descriptors_test.cpp
index 48724afae..523180ee7 100644
--- a/runtime/test/gfx10_descriptors_test.cpp
+++ b/runtime/test/gfx10_descriptors_test.cpp
@@ -362,6 +362,15 @@ int main() {
362 .compare = CompareFunction::greater, .max_lod = 9.0f, .unnormalized = true}); 362 .compare = CompareFunction::greater, .max_lod = 9.0f, .unnormalized = true});
363 CHECK(info.unnormalizedCoordinates == VK_TRUE && info.mipmapMode == VK_SAMPLER_MIPMAP_MODE_NEAREST); 363 CHECK(info.unnormalizedCoordinates == VK_TRUE && info.mipmapMode == VK_SAMPLER_MIPMAP_MODE_NEAREST);
364 CHECK(info.maxLod == 0.0f && info.anisotropyEnable == VK_FALSE && info.compareEnable == VK_FALSE); 364 CHECK(info.maxLod == 0.0f && info.anisotropyEnable == VK_FALSE && info.compareEnable == VK_FALSE);
365 // Unnormalised: U and V clamp (wrap, the default S# mode, would be invalid: VUID ...-01075), border stays border,
366 // W is free; min and mag filter agree (VUID ...-01072).
367 CHECK(info.addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE &&
368 info.addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE &&
369 info.addressModeW == VK_SAMPLER_ADDRESS_MODE_REPEAT && info.minFilter == info.magFilter);
370 info = vulkan_sampler({.address_u = AddressMode::clamp_border, .address_v = AddressMode::mirror,
371 .min_filter = Filter::bilinear, .unnormalized = true});
372 CHECK(info.addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER &&
373 info.addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE && info.minFilter == VK_FILTER_NEAREST);
365 CHECK(vulkan_address_mode(AddressMode::mirror) == VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT); 374 CHECK(vulkan_address_mode(AddressMode::mirror) == VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT);
366 CHECK(vulkan_address_mode(AddressMode::mirror_once_last_texel) == VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE); 375 CHECK(vulkan_address_mode(AddressMode::mirror_once_last_texel) == VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE);
367 CHECK(vulkan_address_mode(AddressMode::clamp_half_border) == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE); 376 CHECK(vulkan_address_mode(AddressMode::clamp_half_border) == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE);
diff --git a/runtime/test/glsl/cs_indirect_dispatch_count.comp b/runtime/test/glsl/cs_indirect_dispatch_count.comp
new file mode 100644
index 000000000..234575467
--- /dev/null
+++ b/runtime/test/glsl/cs_indirect_dispatch_count.comp
@@ -0,0 +1,17 @@
1#version 460
2// Synthetic translated-shader stand-in: root UAV s0:s1, plus the 144-byte user-data contract.
3#extension GL_EXT_buffer_reference : require
4#extension GL_EXT_buffer_reference_uvec2 : require
5layout(local_size_x = 1) in;
6layout(buffer_reference, std430, buffer_reference_align = 4) buffer Words { uint w[]; };
7layout(push_constant) uniform UserData { uint s[32]; uvec2 heap_base; uvec2 code_base; } pc;
8uvec2 add64(uvec2 a, uvec2 b) {
9 uint carry;
10 uint lo = uaddCarry(a.x, b.x, carry);
11 return uvec2(lo, a.y + b.y + carry);
12}
13void main() {
14 Words result = Words(add64(pc.heap_base, uvec2(pc.s[0], pc.s[1])));
15 atomicAdd(result.w[0], 1u);
16 atomicAdd(result.w[1], gl_WorkGroupID.x + 1u);
17}
diff --git a/runtime/test/glsl/cs_wave_probe.comp b/runtime/test/glsl/cs_wave_probe.comp
new file mode 100644
index 000000000..d18987908
--- /dev/null
+++ b/runtime/test/glsl/cs_wave_probe.comp
@@ -0,0 +1,31 @@
1#version 450
2// vk_compute_test's subgroup probe (cs_wave_probe_spv.h). Where the device can't pin a compute subgroup size
3// (MoltenVK: requiredSubgroupSizeStages is 0), vk_compute_test runs this first, with the test shader's local size
4// and pipeline flags, and checks what each invocation reports: its subgroup's size, its lane and subgroup number,
5// and how many lanes a ballot of the whole subgroup counts. The ballot is the real width: MoltenVK's MSL declares
6// SubgroupSize as the constant 32, while the lane, the subgroup number and simd_ballot come from the hardware.
7// Four words per invocation at base + 16 * gl_LocalInvocationIndex, the buffer address in the first push-constant
8// words (s0, s1), so the probe fits the 128-byte push-constant layout of --pc-tail-ubo as well as the 144-byte one.
9#extension GL_EXT_buffer_reference : require
10#extension GL_EXT_buffer_reference_uvec2 : require
11#extension GL_KHR_shader_subgroup_basic : require
12#extension GL_KHR_shader_subgroup_ballot : require
13
14layout(local_size_x_id = 0, local_size_y_id = 1, local_size_z_id = 2) in;
15
16layout(buffer_reference, std430, buffer_reference_align = 4) buffer Words {
17 uint w[];
18};
19
20layout(push_constant) uniform UserData {
21 uvec2 base;
22} pc;
23
24void main() {
25 Words o = Words(pc.base);
26 const uint i = gl_LocalInvocationIndex * 4u;
27 o.w[i + 0u] = gl_SubgroupSize;
28 o.w[i + 1u] = gl_SubgroupInvocationID;
29 o.w[i + 2u] = gl_SubgroupID;
30 o.w[i + 3u] = subgroupBallotBitCount(subgroupBallot(true));
31}
diff --git a/runtime/test/glsl/gs_depth.geom b/runtime/test/glsl/gs_depth.geom
new file mode 100644
index 000000000..0661c7acf
--- /dev/null
+++ b/runtime/test/glsl/gs_depth.geom
@@ -0,0 +1,15 @@
1#version 460
2// A pass-through geometry shader with the interface of a translated one (docs/design.md, "Geometry shaders":
3// triangles in, a triangle strip out), for d3d12_depth24_draw_test: a VS + GS pipeline without a pixel shader still
4// gets the built-in D24 depth stage. It reads no input but the position and writes none but gl_Position.
5
6layout(triangles) in;
7layout(triangle_strip, max_vertices = 3) out;
8
9void main() {
10 for (int i = 0; i < 3; ++i) {
11 gl_Position = gl_in[i].gl_Position;
12 EmitVertex();
13 }
14 EndPrimitive();
15}
diff --git a/runtime/test/glsl/ps_depth_empty.frag b/runtime/test/glsl/ps_depth_empty.frag
new file mode 100644
index 000000000..8bc5bce70
--- /dev/null
+++ b/runtime/test/glsl/ps_depth_empty.frag
@@ -0,0 +1,11 @@
1#version 460
2// A pixel shader with no outputs, for d3d12_depth24_draw_test: it stands in for a translated shader in a pipeline
3// with no render target, so the layer's D24 depth edit (src/depth24_fragment.h) runs on a shader it did not build.
4
5layout(push_constant) uniform UserData {
6 uint s[32];
7 uvec2 heap_base;
8 uvec2 code_base;
9} pc;
10
11void main() {}
diff --git a/runtime/test/glsl/ps_depth_write.frag b/runtime/test/glsl/ps_depth_write.frag
new file mode 100644
index 000000000..959d1dd9d
--- /dev/null
+++ b/runtime/test/glsl/ps_depth_write.frag
@@ -0,0 +1,13 @@
1#version 460
2// A pixel shader that writes its own depth (SV_Depth), for d3d12_depth24_draw_test: s2 is the depth it writes. On a
3// D24 target the value is stored quantised to 24 bits, and D3D applies no depth bias to it.
4
5layout(push_constant) uniform UserData {
6 uint s[32];
7 uvec2 heap_base;
8 uvec2 code_base;
9} pc;
10
11void main() {
12 gl_FragDepth = uintBitsToFloat(pc.s[2]);
13}
diff --git a/runtime/test/glsl/vs_depth.vert b/runtime/test/glsl/vs_depth.vert
new file mode 100644
index 000000000..de1d6ee40
--- /dev/null
+++ b/runtime/test/glsl/vs_depth.vert
@@ -0,0 +1,16 @@
1#version 460
2// A full-screen triangle at a chosen depth, written to the translator's runtime contract (docs/design.md, "User
3// data"), for d3d12_depth24_draw_test: s0 is the depth at the centre and s1 how much it changes per unit of clip-space
4// x, so s1 = 0 gives a flat triangle and anything else a constant slope across the target.
5
6layout(push_constant) uniform UserData {
7 uint s[32];
8 uvec2 heap_base;
9 uvec2 code_base;
10} pc;
11
12void main() {
13 const vec2 corner = vec2(float(gl_VertexIndex & 2), float((gl_VertexIndex << 1) & 2));
14 const vec2 xy = corner * 2.0 - 1.0;
15 gl_Position = vec4(xy, uintBitsToFloat(pc.s[0]) + uintBitsToFloat(pc.s[1]) * xy.x, 1.0);
16}
diff --git a/runtime/test/large_module_gate.h b/runtime/test/large_module_gate.h
new file mode 100644
index 000000000..53aa61f2d
--- /dev/null
+++ b/runtime/test/large_module_gate.h
@@ -0,0 +1,179 @@
1// How many large SPIR-V modules vk_pipeline_check lets into the driver at once, by a memory budget.
2//
3// Measured on RADV GFX1201 (Mesa 25.3.6) with the Mesa shader cache off: a 5.7 MB translated ray-tracing compute
4// module peaks at 1.96 GB of process memory compiling alone (~330 bytes per SPIR-V byte), a 0.36 MB one at 94 MB.
5// Compiling the large ones strictly one at a time left the other threads idle: 40 modules (27 over 4 MiB) on 6
6// threads took 308 s exclusively and 75 s in parallel, 7.0 GB and 8.7 GB peak. kBytesPerSpirvByte keeps a margin
7// over the measurement.
8//
9// The process grew past one module's peak even one at a time because glibc keeps freed memory in per-thread arenas
10// (6 threads: 6.2 GB; MALLOC_ARENA_MAX=1: 2.1 GB, same modules). release_free_memory() hands it back after each
11// large module.
12#pragma once
13
14#include <algorithm>
15#include <condition_variable>
16#include <cstdint>
17#include <cstdio>
18#include <mutex>
19#include <string>
20
21#ifdef _WIN32
22#ifndef NOMINMAX
23#define NOMINMAX
24#endif
25#include <windows.h>
26#endif
27#if defined(__GLIBC__)
28#include <malloc.h>
29#endif
30
31namespace leonida {
32
33inline constexpr uint64_t kBytesPerSpirvByte = 512;
34
35inline uint64_t large_module_estimate(uint64_t spirv_bytes) { return spirv_bytes * kBytesPerSpirvByte; }
36
37#if defined(__linux__)
38// The first unsigned number in a file ("max" and unreadable files give no value).
39inline bool read_u64_file(const std::string& path, uint64_t& value) {
40 std::FILE* f = std::fopen(path.c_str(), "r");
41 if (!f) return false;
42 unsigned long long v = 0;
43 const bool ok = std::fscanf(f, "%llu", &v) == 1;
44 std::fclose(f);
45 value = v;
46 return ok;
47}
48
49// The room left under the cgroup v2 memory.max of this process and of every cgroup above it (a container or
50// systemd-run -p MemoryMax=...), or UINT64_MAX when none sets a limit. cgroup_root is a parameter for the tests.
51inline uint64_t cgroup_memory_room(const std::string& self_cgroup_file = "/proc/self/cgroup",
52 const std::string& cgroup_root = "/sys/fs/cgroup") {
53 std::FILE* f = std::fopen(self_cgroup_file.c_str(), "r");
54 if (!f) return UINT64_MAX;
55 char line[4096];
56 std::string rel;
57 while (std::fgets(line, sizeof(line), f)) {
58 std::string l(line);
59 if (l.rfind("0::", 0) == 0) { // the cgroup v2 line
60 rel = l.substr(3);
61 while (!rel.empty() && (rel.back() == '\n' || rel.back() == '\r')) rel.pop_back();
62 break;
63 }
64 }
65 std::fclose(f);
66 uint64_t room = UINT64_MAX;
67 for (std::string dir = rel; !dir.empty() && dir != "/";) {
68 uint64_t max = 0, current = 0;
69 if (read_u64_file(cgroup_root + dir + "/memory.max", max) &&
70 read_u64_file(cgroup_root + dir + "/memory.current", current))
71 room = std::min(room, max > current ? max - current : 0);
72 const auto slash = dir.find_last_of('/');
73 dir = slash == std::string::npos ? std::string() : dir.substr(0, slash);
74 }
75 return room;
76}
77#endif
78
79// Memory the OS could give this process now, or 0 when it can't tell (then the caller keeps the old exclusive gate).
80inline uint64_t available_memory_bytes() {
81#ifdef _WIN32
82 MEMORYSTATUSEX status{};
83 status.dwLength = sizeof(status);
84 return GlobalMemoryStatusEx(&status) ? uint64_t(status.ullAvailPhys) : 0;
85#elif defined(__linux__)
86 std::FILE* f = std::fopen("/proc/meminfo", "r");
87 if (!f) return 0;
88 char line[256];
89 unsigned long long kb = 0;
90 bool found = false;
91 while (std::fgets(line, sizeof(line), f))
92 if (std::sscanf(line, "MemAvailable: %llu kB", &kb) == 1) { found = true; break; }
93 std::fclose(f);
94 if (!found) return 0;
95 const uint64_t room = cgroup_memory_room();
96 return std::max<uint64_t>(1, std::min(uint64_t(kb) * 1024, room)); // 0 would mean "unknown"
97#else
98 return 0;
99#endif
100}
101
102// Return memory freed by the driver's compiler to the OS (glibc keeps it in the arena of the thread that freed it).
103inline void release_free_memory() {
104#if defined(__GLIBC__)
105 malloc_trim(0);
106#endif
107}
108
109// Lets large modules in while their estimates fit the budget and fewer than max_inflight are in. One always gets in
110// when none is, so a module bigger than the whole budget still compiles (alone among the large ones).
111class LargeModuleGate {
112public:
113 LargeModuleGate(uint64_t budget, unsigned max_inflight)
114 : budget_(budget), max_inflight_(max_inflight ? max_inflight : 1) {}
115
116 bool admits(uint64_t estimate) const {
117 std::lock_guard<std::mutex> g(mu_);
118 return admits_locked(estimate);
119 }
120 void enter(uint64_t estimate) {
121 std::unique_lock<std::mutex> l(mu_);
122 cv_.wait(l, [&] { return admits_locked(estimate); });
123 used_ += estimate;
124 ++inflight_;
125 }
126 void leave(uint64_t estimate) {
127 {
128 std::lock_guard<std::mutex> g(mu_);
129 used_ -= estimate;
130 --inflight_;
131 }
132 cv_.notify_all();
133 }
134 unsigned inflight() const {
135 std::lock_guard<std::mutex> g(mu_);
136 return inflight_;
137 }
138 uint64_t budget() const { return budget_; }
139 unsigned max_inflight() const { return max_inflight_; }
140
141 // Holds a place from construction until destruction (or release()), then hands freed memory back.
142 class Ticket {
143 public:
144 Ticket() = default;
145 Ticket(LargeModuleGate& gate, uint64_t estimate) : gate_(&gate), estimate_(estimate) { gate.enter(estimate); }
146 Ticket(Ticket&& o) noexcept : gate_(o.gate_), estimate_(o.estimate_) { o.gate_ = nullptr; }
147 Ticket& operator=(Ticket&& o) noexcept {
148 if (this != &o) { release(); gate_ = o.gate_; estimate_ = o.estimate_; o.gate_ = nullptr; }
149 return *this;
150 }
151 Ticket(const Ticket&) = delete;
152 Ticket& operator=(const Ticket&) = delete;
153 ~Ticket() { release(); }
154 void release() {
155 if (!gate_) return;
156 gate_->leave(estimate_);
157 gate_ = nullptr;
158 release_free_memory();
159 }
160 private:
161 LargeModuleGate* gate_ = nullptr;
162 uint64_t estimate_ = 0;
163 };
164
165private:
166 bool admits_locked(uint64_t estimate) const {
167 if (inflight_ == 0) return true;
168 return inflight_ < max_inflight_ && used_ + estimate <= budget_;
169 }
170
171 const uint64_t budget_;
172 const unsigned max_inflight_;
173 mutable std::mutex mu_;
174 std::condition_variable cv_;
175 uint64_t used_ = 0;
176 unsigned inflight_ = 0;
177};
178
179} // namespace leonida
diff --git a/runtime/test/large_module_gate_test.cpp b/runtime/test/large_module_gate_test.cpp
new file mode 100644
index 000000000..ed8d18a0c
--- /dev/null
+++ b/runtime/test/large_module_gate_test.cpp
@@ -0,0 +1,159 @@
1// vk_pipeline_check's memory budget for large modules (large_module_gate.h), without a Vulkan device.
2#include "large_module_gate.h"
3
4#include <atomic>
5#include <string>
6#ifndef _WIN32
7#include <unistd.h>
8#endif
9#include <chrono>
10#include <cstdio>
11#include <thread>
12#include <vector>
13
14#define CHECK(condition) do { \
15 if (!(condition)) { \
16 std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); \
17 return 1; \
18 } \
19} while (0)
20
21using leonida::LargeModuleGate;
22
23static int budget_and_count() {
24 LargeModuleGate gate(10, 3);
25 CHECK(gate.admits(4));
26 gate.enter(4);
27 CHECK(gate.admits(4));
28 gate.enter(4);
29 CHECK(!gate.admits(4)); // 12 > 10
30 CHECK(gate.admits(2)); // 10 fits exactly
31 gate.enter(2);
32 CHECK(!gate.admits(0)); // three in: max_inflight
33 gate.leave(4);
34 CHECK(gate.admits(4));
35 gate.leave(4);
36 gate.leave(2);
37 CHECK(gate.inflight() == 0);
38 return 0;
39}
40
41static int oversized_module_still_gets_in_alone() {
42 // Before: a module whose estimate exceeds the whole budget would wait forever.
43 LargeModuleGate gate(10, 4);
44 CHECK(gate.admits(100));
45 gate.enter(100);
46 CHECK(!gate.admits(1)); // nothing joins it
47 gate.leave(100);
48 CHECK(gate.admits(1));
49 return 0;
50}
51
52static int max_inflight_zero_means_one() {
53 LargeModuleGate gate(100, 0);
54 CHECK(gate.max_inflight() == 1);
55 gate.enter(1);
56 CHECK(!gate.admits(1));
57 gate.leave(1);
58 return 0;
59}
60
61static int ticket_releases() {
62 LargeModuleGate gate(10, 2);
63 {
64 LargeModuleGate::Ticket a(gate, 6);
65 CHECK(gate.inflight() == 1);
66 LargeModuleGate::Ticket moved = std::move(a); // the moved-from ticket must not leave twice
67 CHECK(gate.inflight() == 1);
68 LargeModuleGate::Ticket b;
69 b = LargeModuleGate::Ticket(gate, 4);
70 CHECK(gate.inflight() == 2);
71 b.release();
72 CHECK(gate.inflight() == 1);
73 }
74 CHECK(gate.inflight() == 0);
75 return 0;
76}
77
78static int threads_never_exceed_the_budget() {
79 constexpr uint64_t kBudget = 10;
80 LargeModuleGate gate(kBudget, 3);
81 std::atomic<uint64_t> used{0};
82 std::atomic<unsigned> in{0};
83 std::atomic<bool> over{false};
84 std::vector<std::thread> threads;
85 for (int t = 0; t < 8; ++t) {
86 threads.emplace_back([&, t] {
87 for (int i = 0; i < 200; ++i) {
88 const uint64_t est = 1 + uint64_t((t + i) % 5); // 1..5
89 LargeModuleGate::Ticket ticket(gate, est);
90 const uint64_t u = used += est;
91 const unsigned n = ++in;
92 if (n > 3 || (n > 1 && u > kBudget)) over = true;
93 std::this_thread::sleep_for(std::chrono::microseconds(50));
94 --in;
95 used -= est;
96 }
97 });
98 }
99 for (auto& th : threads) th.join();
100 CHECK(!over);
101 CHECK(gate.inflight() == 0);
102 return 0;
103}
104
105static int estimate_and_memory_query() {
106 CHECK(leonida::large_module_estimate(4u << 20) == (uint64_t(4) << 20) * leonida::kBytesPerSpirvByte);
107#if defined(__linux__) || defined(_WIN32)
108 CHECK(leonida::available_memory_bytes() > 0); // Linux: MemAvailable; Windows: ullAvailPhys
109#endif
110 leonida::release_free_memory(); // must be callable anywhere
111 return 0;
112}
113
114#if defined(__linux__)
115#include <filesystem>
116#include <fstream>
117
118static void write_file(const std::filesystem::path& p, const char* text) {
119 std::filesystem::create_directories(p.parent_path());
120 std::ofstream(p) << text;
121}
122
123static int cgroup_limits_are_read_up_the_tree() {
124 // Before: only MemAvailable was read, so under systemd-run -p MemoryMax=... (or in a container) the budget was
125 // the whole machine's and the checker could be killed by its own cgroup.
126 namespace fs = std::filesystem;
127 const fs::path root = fs::temp_directory_path() / ("lmg_test_" + std::to_string(::getpid()));
128 fs::remove_all(root);
129 write_file(root / "self", "0::/user.slice/app.scope\n");
130 write_file(root / "cg/user.slice/memory.max", "10000\n");
131 write_file(root / "cg/user.slice/memory.current", "4000\n"); // room 6000
132 write_file(root / "cg/user.slice/app.scope/memory.max", "max\n"); // no limit of its own
133 write_file(root / "cg/user.slice/app.scope/memory.current", "3000\n");
134 CHECK(leonida::cgroup_memory_room((root / "self").string(), (root / "cg").string()) == 6000);
135 write_file(root / "cg/user.slice/app.scope/memory.max", "5000\n"); // room 2000, the tighter one
136 CHECK(leonida::cgroup_memory_room((root / "self").string(), (root / "cg").string()) == 2000);
137 write_file(root / "cg/user.slice/app.scope/memory.current", "7000\n"); // over its limit: no room
138 CHECK(leonida::cgroup_memory_room((root / "self").string(), (root / "cg").string()) == 0);
139 write_file(root / "self", "12:memory:/legacy\n"); // cgroup v1 only: no limit read
140 CHECK(leonida::cgroup_memory_room((root / "self").string(), (root / "cg").string()) == UINT64_MAX);
141 CHECK(leonida::cgroup_memory_room((root / "missing").string(), (root / "cg").string()) == UINT64_MAX);
142 fs::remove_all(root);
143 return 0;
144}
145#endif
146
147int main() {
148#if defined(__linux__)
149 if (int r = cgroup_limits_are_read_up_the_tree()) return r;
150#endif
151 if (int r = budget_and_count()) return r;
152 if (int r = oversized_module_still_gets_in_alone()) return r;
153 if (int r = max_inflight_zero_means_one()) return r;
154 if (int r = ticket_releases()) return r;
155 if (int r = threads_never_exceed_the_budget()) return r;
156 if (int r = estimate_and_memory_query()) return r;
157 std::puts("large_module_gate: ok");
158 return 0;
159}
diff --git a/runtime/test/loader_test.cpp b/runtime/test/loader_test.cpp
index 58aae185b..7a4e10cfd 100644
--- a/runtime/test/loader_test.cpp
+++ b/runtime/test/loader_test.cpp
@@ -8,6 +8,7 @@
8#include <intrin.h> 8#include <intrin.h>
9 9
10#include <algorithm> 10#include <algorithm>
11#include <atomic>
11#include <chrono> 12#include <chrono>
12#include <cstdio> 13#include <cstdio>
13#include <cstdlib> 14#include <cstdlib>
@@ -16,6 +17,7 @@
16#include <fstream> 17#include <fstream>
17#include <stdexcept> 18#include <stdexcept>
18#include <string> 19#include <string>
20#include <thread>
19#include <vector> 21#include <vector>
20 22
21#include "../shims/shims.h" 23#include "../shims/shims.h"
@@ -1166,6 +1168,58 @@ void test_unwind_registration() {
1166 1168
1167// An export whose address-table entry is past SizeOfImage (not a forwarder: outside the export directory) is 1169// An export whose address-table entry is past SizeOfImage (not a forwarder: outside the export directory) is
1168// refused instead of being stored as base + rva, a pointer outside the mapping. 1170// refused instead of being stored as base + rva, a pointer outside the mapping.
1171// The address-to-module lookup the shim registry uses (on every C++ throw from a mapped image, and for trace and
1172// stop lines) runs on whatever thread asks, while another thread may be inside load(). It used to walk the Loader's
1173// module vector with no lock while load() appended to it. Without the fix this fails for certain only under
1174// AddressSanitizer; here it checks that every answer given during 300 loads is right.
1175void test_lookup_during_loads() {
1176 const char* what = "the address lookup is right while another thread loads modules";
1177 try {
1178 rt::Loader loader(g_dir);
1179 auto first = make_image();
1180 auto* first_nt = reinterpret_cast<IMAGE_NT_HEADERS64*>(first.data() + 0x80);
1181 first_nt->OptionalHeader.ImageBase = 0x200000000ull;
1182 rt::Module& anchor = loader.load(write_image(first));
1183 const uint64_t inside = reinterpret_cast<uint64_t>(anchor.base) + 0x1004;
1184
1185 std::atomic<bool> stop{false};
1186 std::atomic<unsigned> lookups{0}, wrong{0};
1187 std::thread reader([&] {
1188 while (!stop.load()) {
1189 uint64_t base = 0;
1190 if (!rt::shims::mapped_image_base(inside, base) || base != reinterpret_cast<uint64_t>(anchor.base))
1191 ++wrong;
1192 if (rt::shims::module_offset(inside).find("+0x1004") == std::string::npos) ++wrong;
1193 uint64_t none = 0;
1194 if (rt::shims::mapped_image_base(0x10, none)) ++wrong; // in no image
1195 ++lookups;
1196 }
1197 });
1198 unsigned loaded = 0;
1199 for (unsigned i = 1; i <= 300; ++i) {
1200 auto img = make_image();
1201 auto* nt = reinterpret_cast<IMAGE_NT_HEADERS64*>(img.data() + 0x80);
1202 nt->OptionalHeader.ImageBase = 0x200000000ull + i * 0x10000ull;
1203 rt::Module& m = loader.load(write_image(img));
1204 uint64_t base = 0;
1205 if (rt::shims::mapped_image_base(reinterpret_cast<uint64_t>(m.base) + 0x1000, base) &&
1206 base == reinterpret_cast<uint64_t>(m.base))
1207 ++loaded;
1208 }
1209 while (lookups.load() < 1000) std::this_thread::yield();
1210 stop = true;
1211 reader.join();
1212 if (wrong.load())
1213 failed(what, std::to_string(wrong.load()) + " wrong answers in " + std::to_string(lookups.load()) + " lookups");
1214 else if (loaded != 300)
1215 failed(what, "only " + std::to_string(loaded) + " of 300 new modules were found by address");
1216 else
1217 pass(what);
1218 } catch (const std::exception& e) {
1219 failed(what, e.what());
1220 }
1221}
1222
1169void test_export_bounds() { 1223void test_export_bounds() {
1170 auto outside = make_forwarder_image("KERNEL32.GetCurrentProcessId", 0x180000000); 1224 auto outside = make_forwarder_image("KERNEL32.GetCurrentProcessId", 0x180000000);
1171 nt_of(outside)->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size = sizeof(IMAGE_EXPORT_DIRECTORY); 1225 nt_of(outside)->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size = sizeof(IMAGE_EXPORT_DIRECTORY);
@@ -1273,6 +1327,7 @@ int main() {
1273 test_export_bounds(); 1327 test_export_bounds();
1274 test_tls_directory_count(); 1328 test_tls_directory_count();
1275 test_unwind_registration(); 1329 test_unwind_registration();
1330 test_lookup_during_loads();
1276 } catch (const std::exception& e) { 1331 } catch (const std::exception& e) {
1277 // A write that fails (write_image throws) ends the run with the reason, instead of terminating the process. 1332 // A write that fails (write_image throws) ends the run with the reason, instead of terminating the process.
1278 failed("writing the test images", e.what()); 1333 failed("writing the test images", e.what());
diff --git a/runtime/test/queue_proxy_test.cpp b/runtime/test/queue_proxy_test.cpp
index 2259cf5d3..75feecf15 100644
--- a/runtime/test/queue_proxy_test.cpp
+++ b/runtime/test/queue_proxy_test.cpp
@@ -1017,12 +1017,15 @@ int run_runner_child(const char* mode, unsigned long bytes) {
1017int check_child_runner() { 1017int check_child_runner() {
1018 const char* label = "child runner"; 1018 const char* label = "child runner";
1019 ChildResult report; 1019 ChildResult report;
1020 ChildRun run = run_self(L"--child-flood 0", 30000); 1020 ChildRun run;
1021 EXPECT(run.end == ChildEnd::exited && run.exit_code == 0 && parse_diff_report(run.tail, report)); 1021 // The first two successful starts and the first failed start make Windows load and cache their persistent process
1022 EXPECT(report.ran == 1 && report.hr == 0 && report.removed == 0 && report.validation == 0); 1022 // handles (on Windows 11 26200, a second CreateProcessW caches the HKCU root key and a failed CreateProcessW keeps
1023 // The first start and the first failed start make Windows load what it keeps for them (a failed CreateProcessW 1023 // 41-42 AppCompat/PCA handles; later starts add none). Warm up both before reading handles_before.
1024 // leaves 42 handles the first time on Windows 11 26200, none on every later one): both run once before the handle 1024 for (int warmup = 0; warmup < 2; ++warmup) {
1025 // count is taken, and every case after it must leave the count as it was. 1025 run = run_self(L"--child-flood 0", 30000);
1026 EXPECT(run.end == ChildEnd::exited && run.exit_code == 0 && parse_diff_report(run.tail, report));
1027 EXPECT(report.ran == 1 && report.hr == 0 && report.removed == 0 && report.validation == 0);
1028 }
1026 std::fprintf(stderr, "child runner: the next four errors are expected\n"); 1029 std::fprintf(stderr, "child runner: the next four errors are expected\n");
1027 const std::wstring missing = self_path() + L".missing.exe"; 1030 const std::wstring missing = self_path() + L".missing.exe";
1028 run = run_process(missing.c_str(), L"", 5000); 1031 run = run_process(missing.c_str(), L"", 5000);
diff --git a/runtime/test/replay_cpu_bench.cpp b/runtime/test/replay_cpu_bench.cpp
index f3eb316c1..8de50299e 100644
--- a/runtime/test/replay_cpu_bench.cpp
+++ b/runtime/test/replay_cpu_bench.cpp
@@ -31,6 +31,7 @@
31#include <functional> 31#include <functional>
32#include <iterator> 32#include <iterator>
33#include <map> 33#include <map>
34#include <memory>
34#include <new> 35#include <new>
35#include <string> 36#include <string>
36#include <tuple> 37#include <tuple>
@@ -276,11 +277,13 @@ bool uav_clear(CommandList& list, std::uint32_t index) {
276bool draw(CommandList& list, std::uint32_t index, bool indexed) { 277bool draw(CommandList& list, std::uint32_t index, bool indexed) {
277 Draw d{}; 278 Draw d{};
278 d.pipeline = Scene::pipeline_id; 279 d.pipeline = Scene::pipeline_id;
279 d.render_targets = {color_view}; 280 auto views = std::make_shared<DrawViews>(); // out of line since D3D-391
281 views->render_targets = {color_view};
280 d.depth = depth_view; 282 d.depth = depth_view;
281 const std::uint64_t base = Scene::geometry_va + (index % 256) * 65536ull; 283 const std::uint64_t base = Scene::geometry_va + (index % 256) * 65536ull;
282 d.vertex_buffers[0] = {base, 24576, 12}; // by input slot, inlined since D3D-289 284 views->vertex_buffers[0] = {base, 24576, 12}; // by input slot
283 d.vertex_buffers[1] = {base + 24576, 16384, 8}; 285 views->vertex_buffers[1] = {base + 24576, 16384, 8};
286 d.views = std::move(views);
284 if (indexed) d.index = {base + 40960, 6144, 57}; 287 if (indexed) d.index = {base + 40960, 6144, 57};
285 d.topology = 4; // D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST 288 d.topology = 4; // D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST
286 d.viewport = {0, 0, 1920, 1080, 0, 1}; 289 d.viewport = {0, 0, 1920, 1080, 0, 1};
@@ -577,7 +580,9 @@ int main(int argc, char** argv) {
577 CommandList earlier, later; 580 CommandList earlier, later;
578 Draw plain{}; 581 Draw plain{};
579 plain.pipeline = Scene::bare_id; 582 plain.pipeline = Scene::bare_id;
580 plain.render_targets = {color_view}; 583 auto plain_views = std::make_shared<DrawViews>();
584 plain_views->render_targets = {color_view};
585 plain.views = std::move(plain_views);
581 plain.topology = 4; 586 plain.topology = 4;
582 plain.viewport = {0, 0, 1920, 1080, 0, 1}; 587 plain.viewport = {0, 0, 1920, 1080, 0, 1};
583 plain.scissor = {0, 0, 1920, 1080}; 588 plain.scissor = {0, 0, 1920, 1080};
diff --git a/runtime/test/replay_query_predication_test.cpp b/runtime/test/replay_query_predication_test.cpp
index df4e22718..e4a513676 100644
--- a/runtime/test/replay_query_predication_test.cpp
+++ b/runtime/test/replay_query_predication_test.cpp
@@ -5,7 +5,7 @@
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). No GPU or game data. 8// queries, and the single-list refusal (D3D-252) and, with a pool, its replay (D3D-399). No GPU or game data.
9#include "../src/vulkan_replay.h" 9#include "../src/vulkan_replay.h"
10#include <cstdint> 10#include <cstdint>
11#include <cstdio> 11#include <cstdio>
@@ -571,6 +571,54 @@ int main() {
571 expect(trace.events.empty(), "no segment pool: nothing was emitted for the refused list"); 571 expect(trace.events.empty(), "no segment pool: nothing was emitted for the refused list");
572 } 572 }
573 573
574 // 14. D3D-399, the single-list replay() with a segment pool: the list case 13 refuses replays as on the batched
575 // path, and so does case 10's occlusion pair. The pools are created to the planned size and handed to `keep`.
576 {
577 Trace trace;
578 g_trace = &trace;
579 std::vector<std::pair<VkQueryType, std::uint32_t>> created;
580 ReplayFunctions pooled = vk;
581 pooled.create_segment_pool = [&](VkQueryType type, std::uint32_t count) {
582 created.emplace_back(type, count);
583 auto pool = std::make_shared<OcclusionSegmentPool>();
584 pool->pool = handle<VkQueryPool>(type == VK_QUERY_TYPE_OCCLUSION ? 8 : 9);
585 pool->destroy = mock_destroy_pool;
586 return std::shared_ptr<const OcclusionSegmentPool>(pool);
587 };
588 CommandList statistics_list; // case 13's list
589 expect(statistics_list.begin_query({6, d3d12_query::pipeline_statistics, 0}), "record pooled begin 0");
590 expect(statistics_list.begin_query({6, d3d12_query::pipeline_statistics, 1}), "record pooled begin 1");
591 expect(statistics_list.end_query({6, d3d12_query::pipeline_statistics, 0}), "record pooled end 0");
592 expect(statistics_list.end_query({6, d3d12_query::pipeline_statistics, 1}), "record pooled end 1");
593 expect(statistics_list.close(), "close pooled statistics list");
594 CommandList occlusion_list; // case 10's list
595 expect(occlusion_list.begin_query({1, d3d12_query::occlusion, 0}), "record pooled occlusion begin");
596 expect(occlusion_list.begin_query({1, d3d12_query::binary_occlusion, 1}), "record pooled binary begin");
597 expect(occlusion_list.end_query({1, d3d12_query::binary_occlusion, 1}), "record pooled binary end");
598 expect(occlusion_list.end_query({1, d3d12_query::occlusion, 0}), "record pooled occlusion end");
599 expect(occlusion_list.resolve_queries({1, d3d12_query::occlusion, 0, 1, 1, 0}), "record pooled resolve");
600 expect(occlusion_list.close(), "close pooled occlusion list");
601 expect(replay(statistics_list, VK_NULL_HANDLE, resolve, pooled) == ReplayResult::unsupported &&
602 replay(occlusion_list, VK_NULL_HANDLE, resolve, vk) == ReplayResult::unsupported &&
603 created.empty() && trace.events.empty(),
604 "pooled: without `keep` or a pool both lists are still refused and no pool is made");
605 std::vector<std::shared_ptr<const OcclusionSegmentPool>> keep;
606 const auto r0 = replay(statistics_list, VK_NULL_HANDLE, resolve, pooled, nullptr, &keep);
607 const auto r1 = replay(occlusion_list, VK_NULL_HANDLE, resolve, pooled, nullptr, &keep);
608 expect(r0 == ReplayResult::success && r1 == ReplayResult::success,
609 "pooled: overlapping statistics and occlusion queries replay on the single-list path");
610 const std::vector<std::pair<VkQueryType, std::uint32_t>> sizes{{VK_QUERY_TYPE_PIPELINE_STATISTICS, 3},
611 {VK_QUERY_TYPE_OCCLUSION, 3}};
612 expect(created == sizes, "pooled: one pool of each type, sized to the planned segments");
613 expect(keep.size() == 2, "pooled: both pools are handed to the caller");
614 const std::vector<std::string> want{"begin_query 9:0", "end_query 9:0", "begin_query 9:1",
615 "end_query 9:1", "begin_query 9:2", "end_query 9:2",
616 "begin_query 8:0", "end_query 8:0", "begin_query 8:1",
617 "end_query 8:1", "begin_query 8:2", "end_query 8:2",
618 "sum_occlusion 8:0+3"};
619 expect(trace.events == want, "pooled: the same segments and sums as the batched path");
620 }
621
574 if (failures) return 1; 622 if (failures) return 1;
575 std::puts("replay_query_predication_test: query resolves suspend conditional rendering around fills, copies and dispatches"); 623 std::puts("replay_query_predication_test: query resolves suspend conditional rendering around fills, copies and dispatches");
576 return 0; 624 return 0;
diff --git a/runtime/test/root_signature_oracle_test.cpp b/runtime/test/root_signature_oracle_test.cpp
index 261004328..a5d90c141 100644
--- a/runtime/test/root_signature_oracle_test.cpp
+++ b/runtime/test/root_signature_oracle_test.cpp
@@ -25,6 +25,13 @@ void check(bool condition, const char* what) {
25 if (!condition) ++g_failures; 25 if (!condition) ++g_failures;
26} 26}
27 27
28// One line per assertion: "case: what", so a failure names the signature and the field instead of just "false".
29void check_named(bool condition, const char* name, const char* what) {
30 char line[256];
31 std::snprintf(line, sizeof(line), "%s: %s", name, what);
32 check(condition, line);
33}
34
28struct Blobs { 35struct Blobs {
29 ID3DBlob* blob = nullptr; 36 ID3DBlob* blob = nullptr;
30 ID3DBlob* error = nullptr; 37 ID3DBlob* error = nullptr;
@@ -70,6 +77,41 @@ bool parse_blob(ID3DBlob* blob, rt::rootsig::RootSignature& model) {
70 return true; 77 return true;
71} 78}
72 79
80// Parses and logs "case: parses"; false means the caller must not index the model (that segfaulted CI).
81bool parse_checked(ID3DBlob* blob, const char* name, rt::rootsig::RootSignature& model) {
82 const bool parsed = parse_blob(blob, model);
83 check_named(parsed, name, "parses");
84 return parsed;
85}
86
87// Serializes one synthetic desc and, on failure, prints the runtime's own complaint: that text is what tells a
88// rejected flag apart from a rejected layout.
89bool serialize_desc(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC& desc, Blobs& out, const char* name) {
90 const HRESULT hr = D3D12SerializeVersionedRootSignature(&desc, &out.blob, &out.error);
91 check_named(hr == S_OK, name, "Microsoft serializer accepts it");
92 if (hr != S_OK) {
93 if (out.error != nullptr) {
94 std::printf("serializer error: %s\n",
95 static_cast<const char*>(out.error->GetBufferPointer()));
96 }
97 return false;
98 }
99 return true;
100}
101
102// Every field of one static sampler, plus whether this root-signature version carries the 1.2 flags dword.
103bool same_sampler(const rt::rootsig::StaticSampler& got, const D3D12_STATIC_SAMPLER_DESC1& want, bool flags) {
104 return got.filter == uint32_t(want.Filter) && got.address_u == uint32_t(want.AddressU) &&
105 got.address_v == uint32_t(want.AddressV) && got.address_w == uint32_t(want.AddressW) &&
106 got.mip_lod_bias == want.MipLODBias && got.max_anisotropy == want.MaxAnisotropy &&
107 got.comparison_func == uint32_t(want.ComparisonFunc) &&
108 got.border_color == uint32_t(want.BorderColor) && got.min_lod == want.MinLOD &&
109 got.max_lod == want.MaxLOD && got.shader_register == want.ShaderRegister &&
110 got.register_space == want.RegisterSpace &&
111 got.visibility == static_cast<rt::rootsig::Visibility>(want.ShaderVisibility) &&
112 got.flags == (flags ? uint32_t(want.Flags) : 0u);
113}
114
73} // namespace 115} // namespace
74 116
75int main() { 117int main() {
@@ -115,7 +157,9 @@ int main() {
115 model.params[0].num_values == 4 && 157 model.params[0].num_values == 4 &&
116 model.params[0].visibility == Visibility::Vertex, 158 model.params[0].visibility == Visibility::Vertex,
117 "oracle constants match"); 159 "oracle constants match");
118 check(model.params[1].type == ParamType::Descriptor, 160 check(model.params[1].type == ParamType::Descriptor &&
161 model.params[1].descriptor_register == 2 &&
162 model.params[1].descriptor_space == 0,
119 "oracle CBV matches"); 163 "oracle CBV matches");
120 const PackResult packed = pack(model); 164 const PackResult packed = pack(model);
121 check(packed.ok && packed.dword_count == 6, "oracle model packs to 6 dwords"); 165 check(packed.ok && packed.dword_count == 6, "oracle model packs to 6 dwords");
@@ -213,17 +257,6 @@ int main() {
213 params1[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV; 257 params1[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV;
214 params1[1].Descriptor = {5, 1, D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE}; 258 params1[1].Descriptor = {5, 1, D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE};
215 259
216 const auto same_sampler = [](const StaticSampler& got, const D3D12_STATIC_SAMPLER_DESC1& want, bool flags) {
217 return got.filter == uint32_t(want.Filter) && got.address_u == uint32_t(want.AddressU) &&
218 got.address_v == uint32_t(want.AddressV) && got.address_w == uint32_t(want.AddressW) &&
219 got.mip_lod_bias == want.MipLODBias && got.max_anisotropy == want.MaxAnisotropy &&
220 got.comparison_func == uint32_t(want.ComparisonFunc) &&
221 got.border_color == uint32_t(want.BorderColor) && got.min_lod == want.MinLOD &&
222 got.max_lod == want.MaxLOD && got.shader_register == want.ShaderRegister &&
223 got.register_space == want.RegisterSpace &&
224 got.visibility == static_cast<Visibility>(want.ShaderVisibility) &&
225 got.flags == (flags ? uint32_t(want.Flags) : 0u);
226 };
227 // Ranges as the model should hold them: 1.0 has no range flags (0 in the model); 1.1 and 1.2 use range1. 260 // Ranges as the model should hold them: 1.0 has no range flags (0 in the model); 1.1 and 1.2 use range1.
228 const auto same_ranges = [&](const std::vector<DescriptorRange>& got, bool range_flags) { 261 const auto same_ranges = [&](const std::vector<DescriptorRange>& got, bool range_flags) {
229 if (got.size() != 2) return false; 262 if (got.size() != 2) return false;
@@ -242,19 +275,10 @@ int main() {
242 bool sampler_flags) { 275 bool sampler_flags) {
243 const bool range_flags = version != Version::V1_0; 276 const bool range_flags = version != Version::V1_0;
244 Blobs out; 277 Blobs out;
245 char what[160]; 278 if (!serialize_desc(d, out, name)) return;
246 const HRESULT result = D3D12SerializeVersionedRootSignature(&d, &out.blob, &out.error);
247 std::snprintf(what, sizeof(what), "%s: Microsoft serializer accepts it", name);
248 check(result == S_OK, what);
249 if (result != S_OK) {
250 if (out.error) std::printf("serializer error: %s\n", static_cast<const char*>(out.error->GetBufferPointer()));
251 return;
252 }
253 RootSignature got; 279 RootSignature got;
254 std::snprintf(what, sizeof(what), "%s: parses", name); 280 if (!parse_checked(out.blob, name, got)) return;
255 const bool parsed = parse_blob(out.blob, got); 281 char what[160];
256 check(parsed, what);
257 if (!parsed) return;
258 std::snprintf(what, sizeof(what), "%s: version, a two-range table, a root SRV and two samplers", name); 282 std::snprintf(what, sizeof(what), "%s: version, a two-range table, a root SRV and two samplers", name);
259 check(got.version == version && got.params.size() == 2 && got.params[0].type == ParamType::Table && 283 check(got.version == version && got.params.size() == 2 && got.params[0].type == ParamType::Table &&
260 got.params[0].ranges.size() == 2 && got.params[0].ranges[0].range_type == 0 && 284 got.params[0].ranges.size() == 2 && got.params[0].ranges[0].range_type == 0 &&
@@ -291,6 +315,300 @@ int main() {
291 v11.Desc_1_1 = {2, params1, 2, samplers0, D3D12_ROOT_SIGNATURE_FLAG_NONE}; 315 v11.Desc_1_1 = {2, params1, 2, samplers0, D3D12_ROOT_SIGNATURE_FLAG_NONE};
292 serialize(v11, Version::V1_1, "1.1 with static samplers", false); 316 serialize(v11, Version::V1_1, "1.1 with static samplers", false);
293 317
318 // An empty signature (no parameters, no samplers) is legal and is the shape of a bindless compute signature.
319 // It proves the header's count and offset words are believed when both are zero instead of being read as a
320 // truncated table, and the canonical codec has a model to keep.
321 D3D12_VERSIONED_ROOT_SIGNATURE_DESC empty11{};
322 empty11.Version = D3D_ROOT_SIGNATURE_VERSION_1_1;
323 empty11.Desc_1_1 = {0, nullptr, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE};
324 {
325 Blobs out;
326 RootSignature got;
327 if (serialize_desc(empty11, out, "1.1 empty") && parse_checked(out.blob, "1.1 empty", got)) {
328 check_named(got.version == Version::V1_1 && got.params.empty() && got.static_samplers.empty() &&
329 got.flags == 0,
330 "1.1 empty", "version 1.1, no parameters, no samplers, flags 0");
331 const std::vector<uint8_t> bytes = encode_canonical(got);
332 const DecodeResult again = decode_canonical(bytes.data(), bytes.size());
333 check_named(again.ok && again.sig.params.empty() && again.sig.static_samplers.empty() &&
334 again.sig.flags == 0,
335 "1.1 empty", "canonical codec round-trips the empty model");
336 }
337 }
338
339 // Every root-signature flag that a signature with no parameters can legally carry, in one blob. A graphics
340 // signature sets ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT and a bindless one sets the heap-direct bits, so a parser
341 // that read the flags from the wrong header word would pick the other binding model without failing anywhere
342 // else. There are no parameters because the DENY_* bits are invalid next to a parameter any of those stages
343 // can see.
344 const uint32_t every_pc_flag =
345 D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT |
346 D3D12_ROOT_SIGNATURE_FLAG_DENY_VERTEX_SHADER_ROOT_ACCESS |
347 D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS |
348 D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS |
349 D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS |
350 D3D12_ROOT_SIGNATURE_FLAG_DENY_PIXEL_SHADER_ROOT_ACCESS |
351 D3D12_ROOT_SIGNATURE_FLAG_ALLOW_STREAM_OUTPUT |
352 D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED |
353 D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED;
354 D3D12_VERSIONED_ROOT_SIGNATURE_DESC flagged11{};
355 flagged11.Version = D3D_ROOT_SIGNATURE_VERSION_1_1;
356 flagged11.Desc_1_1 = {0, nullptr, 0, nullptr, static_cast<D3D12_ROOT_SIGNATURE_FLAGS>(every_pc_flag)};
357 {
358 Blobs out;
359 RootSignature got;
360 if (serialize_desc(flagged11, out, "1.1 with every root-signature flag") &&
361 parse_checked(out.blob, "1.1 with every root-signature flag", got)) {
362 check_named(got.flags == every_pc_flag, "1.1 with every root-signature flag",
363 "the whole PC flag word round-trips (heap-direct bits included)");
364 const std::vector<uint8_t> bytes = encode_canonical(got);
365 const DecodeResult again = decode_canonical(bytes.data(), bytes.size());
366 check_named(again.ok && again.sig.flags == every_pc_flag, "1.1 with every root-signature flag",
367 "canonical codec keeps the flag word");
368 }
369 }
370
371 // A 1.0 signature with all three root view types and a table last. A root UAV opens most compute signatures,
372 // 1.0 root views have no flags dword, and the table last means its payload cannot be found by a fixed stride.
373 D3D12_DESCRIPTOR_RANGE view_range =
374 {D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 4, 0, 0, D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND};
375 D3D12_ROOT_PARAMETER view_params[4]{};
376 view_params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
377 view_params[0].Descriptor = {2, 3};
378 view_params[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
379 view_params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV;
380 view_params[1].Descriptor = {5, 1};
381 view_params[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX;
382 view_params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV;
383 view_params[2].Descriptor = {7, 2};
384 view_params[2].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
385 view_params[3].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
386 view_params[3].DescriptorTable = {1, &view_range};
387 view_params[3].ShaderVisibility = D3D12_SHADER_VISIBILITY_GEOMETRY;
388 D3D12_VERSIONED_ROOT_SIGNATURE_DESC views10{};
389 views10.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
390 views10.Desc_1_0 = {4, view_params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE};
391 {
392 Blobs out;
393 RootSignature got;
394 if (serialize_desc(views10, out, "1.0 root CBV, SRV and UAV with a table last") &&
395 parse_checked(out.blob, "1.0 root CBV, SRV and UAV with a table last", got)) {
396 check_named(got.params.size() == 4 &&
397 got.params[0].type == ParamType::Descriptor &&
398 got.params[0].descriptor_register == 2 && got.params[0].descriptor_space == 3 &&
399 uint32_t(got.params[0].visibility) == uint32_t(D3D12_SHADER_VISIBILITY_ALL) &&
400 got.params[1].type == ParamType::Descriptor &&
401 got.params[1].descriptor_register == 5 && got.params[1].descriptor_space == 1 &&
402 uint32_t(got.params[1].visibility) == uint32_t(D3D12_SHADER_VISIBILITY_VERTEX) &&
403 got.params[2].type == ParamType::Descriptor &&
404 got.params[2].descriptor_register == 7 && got.params[2].descriptor_space == 2 &&
405 uint32_t(got.params[2].visibility) == uint32_t(D3D12_SHADER_VISIBILITY_PIXEL),
406 "1.0 root CBV, SRV and UAV with a table last",
407 "each root view type keeps its register, space and stage");
408 check_named(got.params.size() == 4 && got.params[3].type == ParamType::Table &&
409 uint32_t(got.params[3].visibility) == uint32_t(D3D12_SHADER_VISIBILITY_GEOMETRY) &&
410 got.params[3].ranges.size() == 1 &&
411 got.params[3].ranges[0].range_type == 0 &&
412 got.params[3].ranges[0].num_descriptors == 4 &&
413 got.params[3].ranges[0].offset_in_table == kRangeOffsetAppend,
414 "1.0 root CBV, SRV and UAV with a table last",
415 "the table after three views keeps its range");
416 const PackResult packed_views = pack(got);
417 check_named(packed_views.ok && packed_views.dword_count == 8,
418 "1.0 root CBV, SRV and UAV with a table last",
419 "three views and a table use 8 user dwords in parameter order");
420 }
421 }
422
423 // 64 constants is the largest legal root-constant parameter and exactly fills the 64-dword D3D12 budget. It is
424 // legal D3D12 and impossible for the console's 32 user SGPRs, so the parse must recover all 64 and pack must
425 // refuse the signature by name instead of truncating every draw at 32.
426 D3D12_ROOT_PARAMETER1 huge_constants[1]{};
427 huge_constants[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
428 huge_constants[0].Constants = {0, 1, 64};
429 huge_constants[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
430 D3D12_VERSIONED_ROOT_SIGNATURE_DESC constants64{};
431 constants64.Version = D3D_ROOT_SIGNATURE_VERSION_1_1;
432 constants64.Desc_1_1 = {1, huge_constants, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE};
433 {
434 Blobs out;
435 RootSignature got;
436 if (serialize_desc(constants64, out, "1.1 with 64 root constants") &&
437 parse_checked(out.blob, "1.1 with 64 root constants", got)) {
438 check_named(got.params.size() == 1 && got.params[0].type == ParamType::Constants &&
439 got.params[0].num_values == 64 && got.params[0].shader_register == 0 &&
440 got.params[0].register_space == 1,
441 "1.1 with 64 root constants",
442 "all 64 constant dwords and the non-zero space survive");
443 const PackResult packed_huge = pack(got);
444 check_named(!packed_huge.ok && packed_huge.error.find("spill") != std::string::npos,
445 "1.1 with 64 root constants",
446 "pack refuses 64 constants as spill instead of truncating");
447 }
448 }
449
450 // All eight D3D12 shader-visibility values in one signature, with the constant registers in descending order.
451 // The existing cases only reach ALL, VERTEX and PIXEL; a game with amplification and mesh shaders binds root
452 // parameters to stages 6 and 7, which no oracle case had put through the serializer before.
453 const D3D12_SHADER_VISIBILITY stages[8] = {
454 D3D12_SHADER_VISIBILITY_ALL, D3D12_SHADER_VISIBILITY_VERTEX, D3D12_SHADER_VISIBILITY_HULL,
455 D3D12_SHADER_VISIBILITY_DOMAIN, D3D12_SHADER_VISIBILITY_GEOMETRY, D3D12_SHADER_VISIBILITY_PIXEL,
456 D3D12_SHADER_VISIBILITY_AMPLIFICATION, D3D12_SHADER_VISIBILITY_MESH};
457 D3D12_ROOT_PARAMETER1 staged_params[8]{};
458 for (int i = 0; i < 8; ++i) {
459 staged_params[i].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
460 staged_params[i].Constants = {static_cast<UINT>(7 - i), 0, 1};
461 staged_params[i].ShaderVisibility = stages[i];
462 }
463 D3D12_VERSIONED_ROOT_SIGNATURE_DESC staged11{};
464 staged11.Version = D3D_ROOT_SIGNATURE_VERSION_1_1;
465 staged11.Desc_1_1 = {8, staged_params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE};
466 {
467 Blobs out;
468 RootSignature got;
469 if (serialize_desc(staged11, out, "1.1 with all eight visibilities") &&
470 parse_checked(out.blob, "1.1 with all eight visibilities", got)) {
471 bool stages_match = got.params.size() == 8;
472 for (uint32_t i = 0; stages_match && i < 8; ++i) {
473 stages_match = got.params[i].type == ParamType::Constants &&
474 got.params[i].num_values == 1 &&
475 got.params[i].shader_register == 7 - i &&
476 uint32_t(got.params[i].visibility) == uint32_t(stages[i]);
477 }
478 check_named(stages_match, "1.1 with all eight visibilities",
479 "every stage value keeps its parameter and the descending registers stay in order");
480 const PackResult packed_stages = pack(got);
481 check_named(packed_stages.ok && packed_stages.dword_count == 8,
482 "1.1 with all eight visibilities",
483 "eight single-dword constants pack in parameter order");
484 }
485 }
486
487 // Every descriptor range type, with an unbounded SRV range and a non-zero base register and space on each.
488 // Bindless signatures declare "all descriptors from here on" with NumDescriptors == UINT_MAX, and D3D12 forces
489 // sampler ranges into a table of their own (the serializer rejects a mixed table), so the signature carries two
490 // tables; a parser that treated UINT_MAX as an error or a signed count would lose the tail of every bindless
491 // table.
492 D3D12_DESCRIPTOR_RANGE1 resource_ranges[3] = {
493 {D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 0xFFFFFFFFu, 0, 1,
494 D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE, D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND},
495 {D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, 2, 3, D3D12_DESCRIPTOR_RANGE_FLAG_NONE, 0},
496 {D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 8, 1, 2,
497 static_cast<D3D12_DESCRIPTOR_RANGE_FLAGS>(D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE |
498 D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE),
499 16}};
500 D3D12_DESCRIPTOR_RANGE1 sampler_range = {
501 D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, 4, 1, 4, D3D12_DESCRIPTOR_RANGE_FLAG_NONE,
502 D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND};
503 D3D12_ROOT_PARAMETER1 range_params[2]{};
504 range_params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
505 range_params[0].DescriptorTable = {3, resource_ranges};
506 range_params[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
507 range_params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
508 range_params[1].DescriptorTable = {1, &sampler_range};
509 range_params[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
510 D3D12_VERSIONED_ROOT_SIGNATURE_DESC ranges11{};
511 ranges11.Version = D3D_ROOT_SIGNATURE_VERSION_1_1;
512 ranges11.Desc_1_1 = {2, range_params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE};
513 {
514 Blobs out;
515 RootSignature got;
516 if (serialize_desc(ranges11, out, "1.1 with all four range types") &&
517 parse_checked(out.blob, "1.1 with all four range types", got)) {
518 if (got.params.size() != 2 || got.params[0].ranges.size() != 3 ||
519 got.params[1].ranges.size() != 1) {
520 check_named(false, "1.1 with all four range types", "two tables: three resources, one sampler");
521 } else {
522 const std::vector<DescriptorRange>& ranges = got.params[0].ranges;
523 check_named(ranges[0].range_type == 0 && ranges[0].num_descriptors == 0xFFFFFFFFu &&
524 ranges[0].base_shader_register == 0 && ranges[0].register_space == 1 &&
525 ranges[0].flags == D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE &&
526 ranges[0].offset_in_table == kRangeOffsetAppend,
527 "1.1 with all four range types",
528 "unbounded SRV range keeps UINT_MAX, its space, flags and appended offset");
529 check_named(ranges[1].range_type == 2 && ranges[1].num_descriptors == 1 &&
530 ranges[1].base_shader_register == 2 && ranges[1].register_space == 3 &&
531 ranges[1].flags == 0 && ranges[1].offset_in_table == 0,
532 "1.1 with all four range types",
533 "CBV range keeps base 2 space 3 and an explicit table offset of 0");
534 check_named(ranges[2].range_type == 1 && ranges[2].num_descriptors == 8 &&
535 ranges[2].base_shader_register == 1 && ranges[2].register_space == 2 &&
536 ranges[2].flags ==
537 uint32_t(D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE |
538 D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE) &&
539 ranges[2].offset_in_table == 16,
540 "1.1 with all four range types",
541 "UAV range keeps the combined data and descriptor flags before offset 16");
542 check_named(got.params[1].ranges[0].range_type == 3 &&
543 got.params[1].ranges[0].num_descriptors == 4 &&
544 got.params[1].ranges[0].base_shader_register == 1 &&
545 got.params[1].ranges[0].register_space == 4 &&
546 got.params[1].ranges[0].offset_in_table == kRangeOffsetAppend,
547 "1.1 with all four range types",
548 "the sampler table keeps its own range, base register and space");
549 const std::vector<uint8_t> bytes = encode_canonical(got);
550 const DecodeResult again = decode_canonical(bytes.data(), bytes.size());
551 check_named(again.ok && again.sig.params.size() == 2 &&
552 again.sig.params[0].ranges.size() == 3 &&
553 again.sig.params[0].ranges[0].num_descriptors == 0xFFFFFFFFu &&
554 again.sig.params[0].ranges[2].flags ==
555 uint32_t(D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE |
556 D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE) &&
557 again.sig.params[1].ranges.size() == 1 &&
558 again.sig.params[1].ranges[0].range_type == 3,
559 "1.1 with all four range types",
560 "canonical codec keeps the unbounded count, the flags and the second table");
561 }
562 }
563 }
564
565 // A shadow sampler: comparison filter, MIRROR_ONCE addressing, a non-zero min LOD and GEOMETRY visibility. The
566 // existing samplers are anisotropic and point-clamp, so no comparison filter or MIRROR_ONCE value reached the
567 // parser; the single root constant beside it uses a non-zero register and space, which the first case cannot
568 // distinguish from a swapped register/space read.
569 D3D12_STATIC_SAMPLER_DESC1 shadow_sampler{};
570 shadow_sampler.Filter = D3D12_FILTER_COMPARISON_ANISOTROPIC;
571 shadow_sampler.AddressU = D3D12_TEXTURE_ADDRESS_MODE_MIRROR_ONCE;
572 shadow_sampler.AddressV = D3D12_TEXTURE_ADDRESS_MODE_MIRROR_ONCE;
573 shadow_sampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_MIRROR_ONCE;
574 shadow_sampler.MipLODBias = 0.25f;
575 shadow_sampler.MaxAnisotropy = 16;
576 shadow_sampler.ComparisonFunc = D3D12_COMPARISON_FUNC_GREATER_EQUAL;
577 shadow_sampler.BorderColor = D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK;
578 shadow_sampler.MinLOD = 0.5f;
579 shadow_sampler.MaxLOD = 12.0f;
580 shadow_sampler.ShaderRegister = 9;
581 shadow_sampler.RegisterSpace = 5;
582 shadow_sampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_GEOMETRY;
583 const D3D12_STATIC_SAMPLER_DESC shadow_sampler0 = {
584 shadow_sampler.Filter, shadow_sampler.AddressU, shadow_sampler.AddressV, shadow_sampler.AddressW,
585 shadow_sampler.MipLODBias, shadow_sampler.MaxAnisotropy, shadow_sampler.ComparisonFunc,
586 shadow_sampler.BorderColor, shadow_sampler.MinLOD, shadow_sampler.MaxLOD, shadow_sampler.ShaderRegister,
587 shadow_sampler.RegisterSpace, shadow_sampler.ShaderVisibility};
588 D3D12_ROOT_PARAMETER1 shadow_params[1]{};
589 shadow_params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
590 shadow_params[0].Constants = {3, 2, 1};
591 shadow_params[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
592 D3D12_VERSIONED_ROOT_SIGNATURE_DESC shadow11{};
593 shadow11.Version = D3D_ROOT_SIGNATURE_VERSION_1_1;
594 shadow11.Desc_1_1 = {1, shadow_params, 1, &shadow_sampler0, D3D12_ROOT_SIGNATURE_FLAG_NONE};
595 {
596 Blobs out;
597 RootSignature got;
598 if (serialize_desc(shadow11, out, "1.1 with a comparison sampler") &&
599 parse_checked(out.blob, "1.1 with a comparison sampler", got)) {
600 check_named(got.params.size() == 1 && got.params[0].type == ParamType::Constants &&
601 got.params[0].num_values == 1 && got.params[0].shader_register == 3 &&
602 got.params[0].register_space == 2,
603 "1.1 with a comparison sampler",
604 "one constant at b3 space 2 keeps every field");
605 check_named(got.static_samplers.size() == 1 &&
606 same_sampler(got.static_samplers[0], shadow_sampler, false),
607 "1.1 with a comparison sampler",
608 "comparison filter, MIRROR_ONCE, GEOMETRY and every other sampler field round-trip");
609 }
610 }
611
294 // The 1.2 cases below need a host that serializes 1.2. Windows 10's built-in d3d12.dll stops at 1.1 and rejects 612 // The 1.2 cases below need a host that serializes 1.2. Windows 10's built-in d3d12.dll stops at 1.1 and rejects
295 // even an empty 1.2 description; their sampler flags have no 1.1 form, so they are skipped there. 613 // even an empty 1.2 description; their sampler flags have no 1.1 form, so they are skipped there.
296 D3D12_VERSIONED_ROOT_SIGNATURE_DESC empty12{}; 614 D3D12_VERSIONED_ROOT_SIGNATURE_DESC empty12{};
diff --git a/runtime/test/shader_library_test.cpp b/runtime/test/shader_library_test.cpp
index 85d7a2b6a..ba8b4f9e2 100644
--- a/runtime/test/shader_library_test.cpp
+++ b/runtime/test/shader_library_test.cpp
@@ -2,6 +2,7 @@
2// Huffman blocks, compressed from synthetic data with Python's zlib), the JSON reader, FSSM extraction from a 2// Huffman blocks, compressed from synthetic data with Python's zlib), the JSON reader, FSSM extraction from a
3// synthetic DXBC container, and index lookup by content hash. No game data. 3// synthetic DXBC container, and index lookup by content hash. No game data.
4#include "../src/shader_library.h" 4#include "../src/shader_library.h"
5#include "test_temp_dir.h"
5 6
6#include <cstdio> 7#include <cstdio>
7#include <filesystem> 8#include <filesystem>
@@ -343,7 +344,8 @@ int main() {
343 CHECK(fssm_program(container({{dynamic, 600}, {fixed, 25}})) == bytes("hello hello hello leonida")); 344 CHECK(fssm_program(container({{dynamic, 600}, {fixed, 25}})) == bytes("hello hello hello leonida"));
344 345
345 // An index with one findable shader, one without a hash, and the module next to it. 346 // An index with one findable shader, one without a hash, and the module next to it.
346 const auto dir = std::filesystem::temp_directory_path() / "leonida_shader_library_test"; 347 const testfiles::ScratchDir scratch("leonida_shader_library_test");
348 const auto& dir = scratch.path();
347 std::filesystem::create_directories(dir); 349 std::filesystem::create_directories(dir);
348 const std::string hash = sha256_hex(skewed(600)); 350 const std::string hash = sha256_hex(skewed(600));
349 const std::string hash2 = sha256_hex(bytes("another program")); 351 const std::string hash2 = sha256_hex(bytes("another program"));
diff --git a/runtime/test/shaders/build.py b/runtime/test/shaders/build.py
index b002201c9..ec9251dfa 100644
--- a/runtime/test/shaders/build.py
+++ b/runtime/test/shaders/build.py
@@ -16,8 +16,9 @@ are also what a shader reads through s_getpc_b64 (the code base) at that offset.
16The stage comes from the name's prefix. Mesh shaders (ms_) also need a DXBC container with their PSV0, which this 16The stage comes from the name's prefix. Mesh shaders (ms_) also need a DXBC container with their PSV0, which this
17doesn't make; geometry shaders (gs_) get gs_tri's signatures (gs_container). 17doesn't make; geometry shaders (gs_) get gs_tri's signatures (gs_container).
18The comment at the top of each .asm says which test program to run on the result and what it should print. 18The comment at the top of each .asm says which test program to run on the result and what it should print.
19With LEONIDA_FMA=khr (or glsl), the fused multiply-adds are translated with --fma khr (OpFmaKHR, which needs 19With LEONIDA_FMA=khr (or glsl, or exact), the fused multiply-adds are translated with --fma khr (OpFmaKHR, which needs
20VK_KHR_shader_fma; the test programs enable it when the device has it, else they exit 77) or --fma glsl. 20VK_KHR_shader_fma; the test programs enable it when the device has it, else they exit 77), --fma glsl, or --fma exact
21(a single rounding built from plain f32 ops, for a driver that splits GLSL Fma and has no VK_KHR_shader_fma).
21With LEONIDA_BARY_FALLBACK=1, pixel shaders that read raw barycentrics are translated with --bary-fallback, and 22With LEONIDA_BARY_FALLBACK=1, pixel shaders that read raw barycentrics are translated with --bary-fallback, and
22each gets a pass-through geometry shader, <name>.bary_gs.spv, that check.py draws it with (tools/bary_fallback_gs.py). 23each gets a pass-through geometry shader, <name>.bary_gs.spv, that check.py draws it with (tools/bary_fallback_gs.py).
23Under that or LEONIDA_F16_INTERP_FALLBACK=1, ps_ij_computed isn't built: its computed I/J pair needs PerVertexKHR 24Under that or LEONIDA_F16_INTERP_FALLBACK=1, ps_ij_computed isn't built: its computed I/J pair needs PerVertexKHR
@@ -164,7 +165,7 @@ def translate_tests(work, names):
164 cmd.append("--wave64-emulate") 165 cmd.append("--wave64-emulate")
165 if os.environ.get("LEONIDA_BARY_FALLBACK") == "1": # raw barycentrics without VK_KHR_fragment_shader_barycentric 166 if os.environ.get("LEONIDA_BARY_FALLBACK") == "1": # raw barycentrics without VK_KHR_fragment_shader_barycentric
166 cmd.append("--bary-fallback") 167 cmd.append("--bary-fallback")
167 if os.environ.get("LEONIDA_FMA") in ("glsl", "khr"): # fused multiply-add as GLSL Fma (default) or OpFmaKHR 168 if os.environ.get("LEONIDA_FMA") in ("glsl", "khr", "exact"): # GLSL Fma (default), OpFmaKHR, or emulated
168 cmd += ["--fma", os.environ["LEONIDA_FMA"]] 169 cmd += ["--fma", os.environ["LEONIDA_FMA"]]
169 if os.environ.get("LEONIDA_F16_INTERP_FALLBACK") == "1": # f16 interpolation without PerVertexKHR (MoltenVK) 170 if os.environ.get("LEONIDA_F16_INTERP_FALLBACK") == "1": # f16 interpolation without PerVertexKHR (MoltenVK)
170 cmd.append("--f16-interp-fallback") 171 cmd.append("--f16-interp-fallback")
diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py
index 330af9f4f..de286fa77 100644
--- a/runtime/test/shaders/check.py
+++ b/runtime/test/shaders/check.py
@@ -163,6 +163,8 @@ CS_DUMPS = [*CS_DPP, ("cs_store", CS_STORE), ("cs_smem_soffset_imm", CS_SMEM),
163BOUNDS = [("cs_bounds", [0x12345678, 0x12345678, 0x00000000, 0xEEEEEEEE]), 163BOUNDS = [("cs_bounds", [0x12345678, 0x12345678, 0x00000000, 0xEEEEEEEE]),
164 ("cs_smem_bounds", [0, 0x5eed0010, 0x5eed000c, 0, 0x5eed000c, 0x5eed0010, 0, 0]), 164 ("cs_smem_bounds", [0, 0x5eed0010, 0x5eed000c, 0, 0x5eed000c, 0x5eed0010, 0, 0]),
165 ("cs_smem_stride_align", [0x5eed0010, 0, 0, 0x5eed0000, 0x5eed0000, 0x5eed0000, 0x5eed0000, 0x5eed0004]), 165 ("cs_smem_stride_align", [0x5eed0010, 0, 0, 0x5eed0000, 0x5eed0000, 0x5eed0000, 0x5eed0000, 0x5eed0004]),
166 # SHADER-328: a constant SGPR offset gives what the run-time one gives (no 32-bit wrap)
167 ("cs_smem_sconst_off", [0, 0x5eed0018, 0x5eed0018, 0x5eed0014]),
166 ("cs_smem_sload_neg", [0x5eed0004, 0x5eed0000, 0x5eed0004, 0x5eed0004, 0x5eed0008, 0x5eed000c, 168 ("cs_smem_sload_neg", [0x5eed0004, 0x5eed0000, 0x5eed0004, 0x5eed0004, 0x5eed0008, 0x5eed000c,
167 0xeeeeeeee, 0xeeeeeeee]), 169 0xeeeeeeee, 0xeeeeeeee]),
168 ("cs_buf_tail", [0, 0x5eed000c, 0x5eed0008, 0x5eed000c, 0, 0, 0x5eed0010, 0]), 170 ("cs_buf_tail", [0, 0x5eed000c, 0x5eed0008, 0x5eed000c, 0, 0, 0x5eed0010, 0]),
@@ -364,6 +366,8 @@ PIXEL_BITS = {"ps_clip_color": (0x3e800000, 0x3f000000, 0x3f400000, 0x3f800000),
364 "ps_fnan_fract": (0x3f7fffff, 0x00003bff, 0xc0200000, 0xc0200000), 366 "ps_fnan_fract": (0x3f7fffff, 0x00003bff, 0xc0200000, 0xc0200000),
365 # TEST-175: docs/design.md rules that were checked on the CPU only (derivations in the .asm headers) 367 # TEST-175: docs/design.md rules that were checked on the CPU only (derivations in the .asm headers)
366 "ps_cmp_nlg": (0x40000037, 0x40000007, 0x40000001, 0x3f800000), 368 "ps_cmp_nlg": (0x40000037, 0x40000007, 0x40000001, 0x3f800000),
369 # far branches: s_getpc/s_add|s_sub/s_addc|s_subb/s_setpc forward, backward loops, conditional (.asm header)
370 "ps_far_branch": (0x00000007, 0x00000013, 0x00000051, 0x0000000b),
367 # 16-bit float v_cmp, all 16 predicates, e32 and e64 with swapped operands (.asm headers) 371 # 16-bit float v_cmp, all 16 predicates, e32 and e64 with swapped operands (.asm headers)
368 "ps_vcmp_f16": (0x48a12080, 0x4ce9b1a2, 0x4ba72c98, 0x4fefbdba), 372 "ps_vcmp_f16": (0x48a12080, 0x4ce9b1a2, 0x4ba72c98, 0x4fefbdba),
369 "ps_vcmp_f16_e64": (0x44c11100, 0x4cf171c1, 0x47c71d18, 0x4ff77dd9), 373 "ps_vcmp_f16_e64": (0x44c11100, 0x4cf171c1, 0x47c71d18, 0x4ff77dd9),
@@ -533,6 +537,19 @@ def run(*cmd, env=None):
533 return r.returncode, r.stdout + r.stderr 537 return r.returncode, r.stdout + r.stderr
534 538
535 539
540def run_readback(path, launch, *args, **kwargs):
541 """Require this invocation to write its framebuffer before comparing it."""
542 path = Path(path)
543 try:
544 path.unlink(missing_ok=True)
545 except OSError as err:
546 return 1, f"could not remove the previous readback {path.name}: {err}"
547 code, output = launch(*args, **kwargs)
548 if code == 0 and not path.is_file():
549 return 1, f"{output.rstrip()}\nmissing readback: {path.name}".lstrip()
550 return code, output
551
552
536def failure(code, output, lines): 553def failure(code, output, lines):
537 details = "\n".join(output.strip().splitlines()[-lines:]) 554 details = "\n".join(output.strip().splitlines()[-lines:])
538 return f"exit {code}: {details or 'no test output'}" 555 return f"exit {code}: {details or 'no test output'}"
@@ -643,11 +660,11 @@ def mesh_v5_test(tools, spirv, raw):
643 fs = Path(spirv) / "fs_passthru.spv" 660 fs = Path(spirv) / "fs_passthru.spv"
644 if not fs.is_file(): 661 if not fs.is_file():
645 return "missing fs_passthru.spv" 662 return "missing fs_passthru.spv"
646 code, out = run(os.path.join(tools, "vk_harness" + EXE), shader, fs, raw, "--mesh-group-readback", "2", "3", "4", 663 code, out = run_readback(raw, run, os.path.join(tools, "vk_harness" + EXE), shader, fs, raw,
647 env=mesh_env(spirv, "ms_v5_workgroup")) 664 "--mesh-group-readback", "2", "3", "4", env=mesh_env(spirv, "ms_v5_workgroup"))
648 if code == UNSUPPORTED: 665 if code == UNSUPPORTED:
649 return Skip("SKIP (mesh shading unavailable)") 666 return Skip("SKIP (mesh shading unavailable)")
650 if code or not raw.is_file(): 667 if code:
651 return failure(code, out, 3) 668 return failure(code, out, 3)
652 return check_mesh_v5(raw.read_bytes()) 669 return check_mesh_v5(raw.read_bytes())
653 670
@@ -688,7 +705,9 @@ def narrow_subgroup_skip(out):
688 705
689def unpinned_subgroup_skip(out): 706def unpinned_subgroup_skip(out):
690 """A Skip when vk_compute_test says the VKC_SUBGROUP_SIZE it was given can't be pinned on this device, else None. 707 """A Skip when vk_compute_test says the VKC_SUBGROUP_SIZE it was given can't be pinned on this device, else None.
691 Output without the line (an older vk_compute_test) is judged as before.""" 708 Output without the line (an older vk_compute_test) is judged as before. "compute subgroup size: 32 (observed: ...)"
709 (MoltenVK: not requirable, but its probe saw 32 lanes) is judged, and "observed wrong" comes with exit 1, a
710 failure."""
692 m = re.search(r"^compute subgroup size: (\d+) not available$", out, re.MULTILINE) 711 m = re.search(r"^compute subgroup size: (\d+) not available$", out, re.MULTILINE)
693 if m: 712 if m:
694 return Skip(f"SKIP (the device can't run this shader at {m.group(1)} lanes on request)") 713 return Skip(f"SKIP (the device can't run this shader at {m.group(1)} lanes on request)")
@@ -939,14 +958,17 @@ def bindless_test(tools, spirv, pixel="ps_tex"):
939# Samples with a16 coordinates after whole-VGPR arguments (gradients, a bias, a clamp). On the 8x8 gradient every 958# Samples with a16 coordinates after whole-VGPR arguments (gradients, a bias, a clamp). On the 8x8 gradient every
940# pixel must be the texel its own (u, v) reads. ps_texture_grad_cl_a16 draws on the two-mip texture instead, where its 959# pixel must be the texel its own (u, v) reads. ps_texture_grad_cl_a16 draws on the two-mip texture instead, where its
941# clamp picks mip 0 left of x = 32 and mip 1 from there on. 960# clamp picks mip 0 left of x = 32 and mip 1 from there on.
942GRADIENT_TESTS = ("ps_texture_grad_a16", "ps_texture_bias_a16", "ps_texture_grad_cl_a16") 961GRADIENT_TESTS = ("ps_texture_grad_a16", "ps_texture_bias_a16", "ps_texture_grad_cl_a16", "ps_texture_cl", "ps_texture_b_cl")
962# ps_texture_cl / ps_texture_b_cl (image_sample_cl / _b_cl) draw on the two-mip texture too: the left half reads mip 0 (red,
963# the top-left quadrant), the right half mip 1 (cyan) where the clamp is 1.
964CLAMP_TESTS = ("ps_texture_cl", "ps_texture_b_cl")
943 965
944 966
945def texture_gradient_a16_test(tools: str, spirv: str, name: str = "ps_texture_grad_a16") -> str: 967def texture_gradient_a16_test(tools: str, spirv: str, name: str = "ps_texture_grad_a16") -> str:
946 """Check every pixel of one of the GRADIENT_TESTS samples.""" 968 """Check every pixel of one of the GRADIENT_TESTS samples."""
947 vs = os.path.join(spirv, "vs_ids.spv") 969 vs = os.path.join(spirv, "vs_ids.spv")
948 fs = os.path.join(spirv, name + ".spv") 970 fs = os.path.join(spirv, name + ".spv")
949 two_mip = name == "ps_texture_grad_cl_a16" 971 two_mip = name == "ps_texture_grad_cl_a16" or name in CLAMP_TESTS
950 with tempfile.TemporaryDirectory(prefix="leonida-texture-") as tmp: 972 with tempfile.TemporaryDirectory(prefix="leonida-texture-") as tmp:
951 raw = Path(tmp) / "pixels.raw" 973 raw = Path(tmp) / "pixels.raw"
952 code, out = run(os.path.join(tools, "vk_texture_test" + EXE), vs, fs, raw, 974 code, out = run(os.path.join(tools, "vk_texture_test" + EXE), vs, fs, raw,
@@ -963,7 +985,9 @@ def texture_gradient_a16_test(tools: str, spirv: str, name: str = "ps_texture_gr
963 first = "" 985 first = ""
964 for index, pixel in enumerate(struct.iter_unpack("<4f", data)): 986 for index, pixel in enumerate(struct.iter_unpack("<4f", data)):
965 x, y = index % 64, index // 64 987 x, y = index % 64, index // 64
966 if two_mip: # mip 1 (cyan) where the clamp is 1, else mip 0's red and blue quadrants 988 if name in CLAMP_TESTS: # mip 1 (cyan) where the clamp is 1, else mip 0's top-left quadrant (red)
989 want = (0.0, 1.0, 1.0, 1.0) if x >= 32 else (1.0, 0.0, 0.0, 1.0)
990 elif two_mip: # mip 1 (cyan) where the clamp is 1, else mip 0's red and blue quadrants
967 want = (0.0, 1.0, 1.0, 1.0) if x >= 32 else (1.0, 0.0, 0.0, 1.0) if y < 32 else (0.0, 0.0, 1.0, 1.0) 991 want = (0.0, 1.0, 1.0, 1.0) if x >= 32 else (1.0, 0.0, 0.0, 1.0) if y < 32 else (0.0, 0.0, 1.0, 1.0)
968 else: 992 else:
969 want = (32 * (x // 8) / 255, 32 * (y // 8) / 255, 128 / 255, 1.0) 993 want = (32 * (x // 8) / 255, 32 * (y // 8) / 255, 128 / 255, 1.0)
diff --git a/runtime/test/shaders/cs_bvh.asm b/runtime/test/shaders/cs_bvh.asm
index 92caa125f..465816a6c 100644
--- a/runtime/test/shaders/cs_bvh.asm
+++ b/runtime/test/shaders/cs_bvh.asm
@@ -1,6 +1,8 @@
1; image_bvh64_intersect_ray emulation: vk_compute_test writes an AMD-format BVH into the heap (box32 root 0x100 -> triangle 1; image_bvh64_intersect_ray emulation: vk_compute_test writes an AMD-format BVH into the heap (box32 root 0x100 -> triangle
2; z=10 node 0x40, triangle z=5 node 0x48, missed box, NaN box). Ray (0.25,0.25,0) +z. Run: vk_compute_test cs_bvh.spv 1 bvh 2; z=10 node 0x40, triangle z=5 node 0x48, missed box, box 0x68 with a NaN min.x). Ray (0.25,0.25,0) +z. Run:
3; -> box result 0x48 0x40 0xffffffff 0xffffffff (sorted), triangle result -10 -1 -0.25 -0.25 (t = 10, bary 0.25/0.25). 3; vk_compute_test cs_bvh.spv 1 bvh
4; -> box result 0x68 0x48 0x40 0xffffffff (sorted; RDNA2 skips the NaN plane and enters box 0x68 at t = 0, SHADER-650),
5; triangle result -10 -1 -0.25 -0.25 (t = 10, bary 0.25/0.25).
4v_cmpx_eq_u32_e32 0, v0 6v_cmpx_eq_u32_e32 0, v0
5v_mov_b32_e32 v1, 0x25 7v_mov_b32_e32 v1, 0x25
6v_mov_b32_e32 v2, 0 8v_mov_b32_e32 v2, 0
diff --git a/runtime/test/shaders/cs_bvh32.asm b/runtime/test/shaders/cs_bvh32.asm
index c73f6cd9d..4fe0f78e0 100644
--- a/runtime/test/shaders/cs_bvh32.asm
+++ b/runtime/test/shaders/cs_bvh32.asm
@@ -2,13 +2,15 @@
2; is 11 dwords: node, ray extent (t max), origin xyz, direction xyz, inverse direction xyz. The 64-bit form has the 2; is 11 dwords: node, ray extent (t max), origin xyz, direction xyz, inverse direction xyz. The 64-bit form has the
3; node's high dword after the low one, so read with that layout every operand here would be one register off. 3; node's high dword after the low one, so read with that layout every operand here would be one register off.
4; Same scene and ray as cs_bvh.asm: vk_compute_test writes an AMD-format BVH into the heap (box32 root at 0x100 -> 4; Same scene and ray as cs_bvh.asm: vk_compute_test writes an AMD-format BVH into the heap (box32 root at 0x100 ->
5; triangle z=10 node 0x40, triangle z=5 node 0x48, a box the ray misses, a NaN box). Ray origin (0.25, 0.25, 0), 5; triangle z=10 node 0x40, triangle z=5 node 0x48, a box the ray misses, a box with a NaN min.x). Ray origin
6; direction +z, t max 100. Run: vk_compute_test cs_bvh32.spv 1 bvh 6; (0.25, 0.25, 0), direction +z, t max 100. Run: vk_compute_test cs_bvh32.spv 1 bvh
7; Expected, from the "Ray tracing" row of docs/design.md (one traversal step, RADV's software box and triangle tests): 7; Expected, from the "Ray tracing" row of docs/design.md (one traversal step; the box test as measured on RDNA2,
8; SHADER-650, and RADV's software triangle test):
8; box node 0x25 (address 0x100 >> 3 | type 5): along +z the ray enters a box that contains its x and y at the 9; box node 0x25 (address 0x100 >> 3 | type 5): along +z the ray enters a box that contains its x and y at the
9; box's near z, so child 0x40 (z = 10) at 10 and child 0x48 (z = 5) at 5. The third box lies at x in [5, 6], which 10; box's near z, so child 0x40 (z = 10) at 10 and child 0x48 (z = 5) at 5. The third box lies at x in [5, 6], which
10; the ray never reaches, and the fourth has a NaN corner: both give 0xffffffff. box_sort_enable (descriptor bit 63, 11; the ray never reaches: 0xffffffff. The fourth (0x68) has min.x = NaN; the hardware skips a NaN plane, so the box
11; set in s5) orders the children by entry distance: out[0..3] = 0x48 0x40 0xffffffff 0xffffffff. 12; is x <= 1, y and z in [0, 1], which the ray is in at t = 0. box_sort_enable (descriptor bit 63, set in s5) orders
13; the children by entry distance clamped to 0: out[0..3] = 0x68 0x48 0x40 0xffffffff (native gfx1030 gives the same).
12; triangle node 0x40 (address 0x200, vertices (0,0,10) (1,0,10) (0,1,10)): the ray runs along z, so the vertices 14; triangle node 0x40 (address 0x200, vertices (0,0,10) (1,0,10) (0,1,10)): the ray runs along z, so the vertices
13; relative to the origin project onto xy unsheared: A = (-0.25, -0.25), B = (0.75, -0.25), C = (-0.25, 0.75). The 15; relative to the origin project onto xy unsheared: A = (-0.25, -0.25), B = (0.75, -0.25), C = (-0.25, 0.75). The
14; edge functions are u = Cx By - Cy Bx = -0.5, v = Ax Cy - Ay Cx = -0.25 and w = Bx Ay - By Ax = -0.25, all of one 16; edge functions are u = Cx By - Cy Bx = -0.5, v = Ax Cy - Ay Cx = -0.25 and w = Bx Ay - By Ax = -0.25, all of one
diff --git a/runtime/test/shaders/cs_smem_sconst_off.asm b/runtime/test/shaders/cs_smem_sconst_off.asm
new file mode 100644
index 000000000..1da78df89
--- /dev/null
+++ b/runtime/test/shaders/cs_smem_sconst_off.asm
@@ -0,0 +1,47 @@
1; SHADER-328: an s_buffer_load SGPR offset the translator can see as a constant gives what the same offset gives at run
2; time. The rule (docs/design.md, Scalar/buffer memory): off = zext(soffset & ~3) + (imm & ~3) in 64 bits, and the
3; dword is 0 when off + 4 > limit. #1686 folded a constant soffset as a 32-bit sum, so 0xfffffffc + 20 wrapped to 16
4; and read data; gfx1036 (tools/hw_oracle, #1686) reads 0.
5; Thread 0 seeds heap bytes 0x40..0x5f (region offset X = byte 0x40 + X) with 0x5eed0000 + X and byte 0x60 with
6; 4, then loads through a V# it builds itself (base 0x40, stride 0, NUM_RECORDS 0x40, word3 0x31016fac):
7; s_buffer_load_dword s24, s8=-4 offset:20 (constant) -> 0xfffffffc + 0x14 > 0x40: 0 (32-bit wrap: 0x5eed0010)
8; s_buffer_load_dword s25, s9=4 offset:20 (from heap 0x60) -> run time, in range: 0x5eed0018, as s26
9; s_buffer_load_dword s26, s10=4 offset:20 (constant) -> 0x18: 0x5eed0018
10; s_buffer_load_dword s27, s11=0x10 offset:4 (constant) -> 0x14: 0x5eed0014
11; and writes s24..s27 to out[0..3]. The run-time load stays in range: an out-of-range run-time sOFF (-4) made llvmpipe
12; (Mesa 26.0.8) do the guarded load anyway and segfault (#1938 review); the CPU tests cover that path.
13; Run: vk_compute_test cs_smem_sconst_off.spv 1 dump -> out[0..3] = 0x00000000 0x5eed0018 0x5eed0018 0x5eed0014.
14v_cmpx_eq_u32_e32 0, v0
15v_mov_b32 v1, 0x5eed0000
16v_mov_b32 v2, 0x5eed0004
17v_mov_b32 v3, 0x5eed0008
18v_mov_b32 v4, 0x5eed000c
19buffer_store_dwordx4 v[1:4], off, s[0:3], 0 offset:64
20v_mov_b32 v1, 0x5eed0010
21v_mov_b32 v2, 0x5eed0014
22v_mov_b32 v3, 0x5eed0018
23v_mov_b32 v4, 0x5eed001c
24buffer_store_dwordx4 v[1:4], off, s[0:3], 0 offset:80
25v_mov_b32 v5, 4
26buffer_store_dword v5, off, s[0:3], 0 offset:96
27s_waitcnt vmcnt(0)
28s_mov_b32 s4, 0x40
29s_mov_b32 s5, 0
30s_mov_b32 s6, 0x40
31s_mov_b32 s7, 0x31016fac
32s_mov_b32 s8, -4
33s_buffer_load_dword s9, s[0:3], 0x60
34s_mov_b32 s10, 4
35s_mov_b32 s11, 0x10
36s_waitcnt lgkmcnt(0)
37s_buffer_load_dword s24, s[4:7], s8 offset:0x14
38s_buffer_load_dword s25, s[4:7], s9 offset:0x14
39s_buffer_load_dword s26, s[4:7], s10 offset:0x14
40s_buffer_load_dword s27, s[4:7], s11 offset:0x4
41s_waitcnt lgkmcnt(0)
42v_mov_b32 v1, s24
43v_mov_b32 v2, s25
44v_mov_b32 v3, s26
45v_mov_b32 v4, s27
46buffer_store_dwordx4 v[1:4], off, s[0:3], 0
47s_endpgm
diff --git a/runtime/test/shaders/ps_far_branch.asm b/runtime/test/shaders/ps_far_branch.asm
new file mode 100644
index 000000000..15f807291
--- /dev/null
+++ b/runtime/test/shaders/ps_far_branch.asm
@@ -0,0 +1,321 @@
1; Far branches: the idiom s_getpc_b64 s[a:a+1]; s_add_u32 sa, sa, K; s_addc_u32 sa+1, sa+1, 0|-1; s_setpc_b64 s[a:a+1] (and the
2; s_sub_u32/s_subb_u32 form), which jumps beyond the +-32K dwords an s_branch reaches. docs/design.md "Far branches": the
3; translator folds the four instructions into one branch. RDNA2 ISA: S_GETPC_B64 returns the address of the next
4; instruction; S_ADD_U32 / S_ADDC_U32 add K to that 64-bit address (carry through SCC; the high word is 0 for a forward
5; K and 0xffffffff, as -1, with K = 2^32 - |K| for a backward one; S_SUB_U32 / S_SUBB_U32 subtract |K|); S_SETPC_B64
6; sets PC. K is in bytes from the instruction after s_getpc. The block between a far branch and its target holds
7; "poison" ORs that must never run, and 40 s_nop (4 bytes each, 160 bytes) so that K > 64 is a 32-bit literal.
8; Sizes (bytes): s_nop 4, s_or_b32 with an inline constant 4, with a literal 8, s_add_u32/s_sub_u32/s_cmp with a literal 8.
9; x (s10 = 1 to start): two forward far branches, one through s[4:5], one through s[8:9]:
10; K = add (8) + addc (4) + setpc (4) + poison s_or literal (8) + 40 nops (160) = 184 = 0xb8, landing on "s_or s10, 2";
11; the poison ORs 0x100 / 0x200 are skipped, the targets OR 2 and 4: x = 1 | 2 | 4 = 0x00000007.
12; y (s11 = 0): a backward loop with s_sub_u32 / s_subb_u32 (hi = 0). The body is s_add_u32 s11, 1 (4) + 40 nops (160) +
13; s_cmp_ge_u32 s11, 3 (4) + s_cbranch_scc1 (4) + s_getpc (4) = 176 bytes from the loop top to the instruction after
14; s_getpc, so K = 176 = 0xb0. The far branch back is taken after iterations 1 and 2 and not after iteration 3
15; (scc = 1 jumps over it), so s11 counts 3; then s_or s11, 0x10: y = 0x00000013.
16; z (s12 = 0): a backward loop with s_add_u32 K / s_addc_u32 -1, K = -180 = 0xffffff4c: body s_add_u32 s12, 0x10 (4) +
17; 40 nops (160) + s_cmp_ge_u32 s12, 0x50 (literal, 8) + s_cbranch_scc1 (4) + s_getpc (4) = 180. s12 steps by 0x10 and
18; the loop leaves when s12 >= 0x50, after 5 iterations (the far branch back taken 4 times): s12 = 0x50, then
19; s_or s12, 1: z = 0x00000051.
20; w (s13 = 0): a far forward branch behind a conditional branch that skips it (s_cbranch_scc0 over the 5 dwords of the
21; sequence), run twice. First scc = (s13 == 1) = 0: the sequence is skipped, the code after it runs: s13 |= 1, then
22; the target ORs 2 (K = 8+4+4 + 4 + 160 = 180 = 0xb4), s13 = 3. Second scc = (s13 == 3) = 1: the sequence runs, it
23; jumps over "s_or s13, 4" and the nops to the target: s13 |= 8: w = 0x0000000b.
24; A translation that folded a far branch to the wrong target runs a poison OR (x gains 0x300), repeats or skips a
25; loop iteration (y, z), or mishandles the conditional case (w). The loops count on s11/s12, so a wrong target shows
26; as a different count, not just a hang.
27; Expected mrt0 bits: 0x00000007, 0x00000013, 0x00000051, 0x0000000b
28s_mov_b32 s10, 1
29s_getpc_b64 s[4:5]
30s_add_u32 s4, s4, 184
31s_addc_u32 s5, s5, 0
32s_setpc_b64 s[4:5]
33s_or_b32 s10, s10, 0x100
34s_nop 0
35s_nop 0
36s_nop 0
37s_nop 0
38s_nop 0
39s_nop 0
40s_nop 0
41s_nop 0
42s_nop 0
43s_nop 0
44s_nop 0
45s_nop 0
46s_nop 0
47s_nop 0
48s_nop 0
49s_nop 0
50s_nop 0
51s_nop 0
52s_nop 0
53s_nop 0
54s_nop 0
55s_nop 0
56s_nop 0
57s_nop 0
58s_nop 0
59s_nop 0
60s_nop 0
61s_nop 0
62s_nop 0
63s_nop 0
64s_nop 0
65s_nop 0
66s_nop 0
67s_nop 0
68s_nop 0
69s_nop 0
70s_nop 0
71s_nop 0
72s_nop 0
73s_nop 0
74s_or_b32 s10, s10, 2
75s_getpc_b64 s[8:9]
76s_add_u32 s8, s8, 184
77s_addc_u32 s9, s9, 0
78s_setpc_b64 s[8:9]
79s_or_b32 s10, s10, 0x200
80s_nop 0
81s_nop 0
82s_nop 0
83s_nop 0
84s_nop 0
85s_nop 0
86s_nop 0
87s_nop 0
88s_nop 0
89s_nop 0
90s_nop 0
91s_nop 0
92s_nop 0
93s_nop 0
94s_nop 0
95s_nop 0
96s_nop 0
97s_nop 0
98s_nop 0
99s_nop 0
100s_nop 0
101s_nop 0
102s_nop 0
103s_nop 0
104s_nop 0
105s_nop 0
106s_nop 0
107s_nop 0
108s_nop 0
109s_nop 0
110s_nop 0
111s_nop 0
112s_nop 0
113s_nop 0
114s_nop 0
115s_nop 0
116s_nop 0
117s_nop 0
118s_nop 0
119s_nop 0
120s_or_b32 s10, s10, 4
121s_mov_b32 s11, 0
122s_add_u32 s11, s11, 1
123s_nop 0
124s_nop 0
125s_nop 0
126s_nop 0
127s_nop 0
128s_nop 0
129s_nop 0
130s_nop 0
131s_nop 0
132s_nop 0
133s_nop 0
134s_nop 0
135s_nop 0
136s_nop 0
137s_nop 0
138s_nop 0
139s_nop 0
140s_nop 0
141s_nop 0
142s_nop 0
143s_nop 0
144s_nop 0
145s_nop 0
146s_nop 0
147s_nop 0
148s_nop 0
149s_nop 0
150s_nop 0
151s_nop 0
152s_nop 0
153s_nop 0
154s_nop 0
155s_nop 0
156s_nop 0
157s_nop 0
158s_nop 0
159s_nop 0
160s_nop 0
161s_nop 0
162s_nop 0
163s_cmp_ge_u32 s11, 3
164s_cbranch_scc1 5
165s_getpc_b64 s[6:7]
166s_sub_u32 s6, s6, 176
167s_subb_u32 s7, s7, 0
168s_setpc_b64 s[6:7]
169s_or_b32 s11, s11, 0x10
170s_mov_b32 s12, 0
171s_add_u32 s12, s12, 0x10
172s_nop 0
173s_nop 0
174s_nop 0
175s_nop 0
176s_nop 0
177s_nop 0
178s_nop 0
179s_nop 0
180s_nop 0
181s_nop 0
182s_nop 0
183s_nop 0
184s_nop 0
185s_nop 0
186s_nop 0
187s_nop 0
188s_nop 0
189s_nop 0
190s_nop 0
191s_nop 0
192s_nop 0
193s_nop 0
194s_nop 0
195s_nop 0
196s_nop 0
197s_nop 0
198s_nop 0
199s_nop 0
200s_nop 0
201s_nop 0
202s_nop 0
203s_nop 0
204s_nop 0
205s_nop 0
206s_nop 0
207s_nop 0
208s_nop 0
209s_nop 0
210s_nop 0
211s_nop 0
212s_cmp_ge_u32 s12, 0x50
213s_cbranch_scc1 5
214s_getpc_b64 s[8:9]
215s_add_u32 s8, s8, 0xffffff4c
216s_addc_u32 s9, s9, -1
217s_setpc_b64 s[8:9]
218s_or_b32 s12, s12, 1
219s_mov_b32 s13, 0
220s_cmp_eq_u32 s13, 1
221s_cbranch_scc0 5
222s_getpc_b64 s[4:5]
223s_add_u32 s4, s4, 180
224s_addc_u32 s5, s5, 0
225s_setpc_b64 s[4:5]
226s_or_b32 s13, s13, 1
227s_nop 0
228s_nop 0
229s_nop 0
230s_nop 0
231s_nop 0
232s_nop 0
233s_nop 0
234s_nop 0
235s_nop 0
236s_nop 0
237s_nop 0
238s_nop 0
239s_nop 0
240s_nop 0
241s_nop 0
242s_nop 0
243s_nop 0
244s_nop 0
245s_nop 0
246s_nop 0
247s_nop 0
248s_nop 0
249s_nop 0
250s_nop 0
251s_nop 0
252s_nop 0
253s_nop 0
254s_nop 0
255s_nop 0
256s_nop 0
257s_nop 0
258s_nop 0
259s_nop 0
260s_nop 0
261s_nop 0
262s_nop 0
263s_nop 0
264s_nop 0
265s_nop 0
266s_nop 0
267s_or_b32 s13, s13, 2
268s_cmp_eq_u32 s13, 3
269s_cbranch_scc0 5
270s_getpc_b64 s[4:5]
271s_add_u32 s4, s4, 180
272s_addc_u32 s5, s5, 0
273s_setpc_b64 s[4:5]
274s_or_b32 s13, s13, 4
275s_nop 0
276s_nop 0
277s_nop 0
278s_nop 0
279s_nop 0
280s_nop 0
281s_nop 0
282s_nop 0
283s_nop 0
284s_nop 0
285s_nop 0
286s_nop 0
287s_nop 0
288s_nop 0
289s_nop 0
290s_nop 0
291s_nop 0
292s_nop 0
293s_nop 0
294s_nop 0
295s_nop 0
296s_nop 0
297s_nop 0
298s_nop 0
299s_nop 0
300s_nop 0
301s_nop 0
302s_nop 0
303s_nop 0
304s_nop 0
305s_nop 0
306s_nop 0
307s_nop 0
308s_nop 0
309s_nop 0
310s_nop 0
311s_nop 0
312s_nop 0
313s_nop 0
314s_nop 0
315s_or_b32 s13, s13, 8
316v_mov_b32_e32 v10, s10
317v_mov_b32_e32 v11, s11
318v_mov_b32_e32 v12, s12
319v_mov_b32_e32 v13, s13
320exp mrt0 v10, v11, v12, v13 done vm
321s_endpgm
diff --git a/runtime/test/shaders/ps_m2_literal.asm b/runtime/test/shaders/ps_m2_literal.asm
new file mode 100644
index 000000000..f77ef197f
--- /dev/null
+++ b/runtime/test/shaders/ps_m2_literal.asm
@@ -0,0 +1,21 @@
1; M2 literal sampler: ps_m2.asm with its S# built from immediates instead of loaded from the sampler table, as game
2; shaders do (docs/design.md, Literal samplers): CLAMP_LAST_TEXEL on all axes, bilinear min/mag, point mip, MAX_LOD
3; 12. No heap slot names this S#, so the layer registers it when a pipeline uses the shader; otherwise the shader's
4; hash lookup finds the fallback sampler. Run: d3d12_m2_textured_test.
5; s[0:1] = console VA of the SRV table's first slot (the T#). attr0.xy = (u, v). mrt0 = the sampled texel.
6; fssm-at: 0x10
7; fssm-data: 0x324d5350 0x4c544c20
8s_load_dwordx8 s[8:15], s[0:1], 0x0
9s_movk_i32 s16, 0x92
10s_mov_b32 s17, 0xc00000
11s_mov_b32 s18, 0x14500000
12s_mov_b32 s19, 0
13s_waitcnt lgkmcnt(0)
14v_interp_p1_f32_e32 v2, v0, attr0.x
15v_interp_p2_f32_e32 v2, v1, attr0.x
16v_interp_p1_f32_e32 v3, v0, attr0.y
17v_interp_p2_f32_e32 v3, v1, attr0.y
18image_sample v[4:7], v[2:3], s[8:15], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_2D
19s_waitcnt vmcnt(0)
20exp mrt0 v4, v5, v6, v7 done vm
21s_endpgm
diff --git a/runtime/test/shaders/ps_sample_c.asm b/runtime/test/shaders/ps_sample_c.asm
new file mode 100644
index 000000000..8d6616cdc
--- /dev/null
+++ b/runtime/test/shaders/ps_sample_c.asm
@@ -0,0 +1,25 @@
1; Depth-compare sampling with implicit LOD: image_sample_c of an 8x8 D32 texture whose texel x holds depth (x + 0.5) / 8,
2; reference 0.5 against a LESS_OR_EQUAL compare sampler (S# DEPTH_COMPARE_FUNC 3 at s[16:19]), at u, v from attr0 (a
3; pixel shader, so the LOD comes from the derivatives: OpImageSampleDrefImplicitLod). Address v[4:6] = (z-compare,
4; u, v). The same sample without and with d16; the d16 result (an f16 in the low half) is widened with v_cvt_f32_f16.
5; The one-level texture makes the LOD 0 whatever the derivatives. mrt0 = (f32 result, widened d16 result, u, v).
6; Run: vk_texture_test dref_c -> every pixel's first two components are 1.0 where its texel has x >= 4, else 0.0
7v_interp_p1_f32_e32 v2, v0, attr0.x
8v_interp_p2_f32_e32 v2, v1, attr0.x
9v_interp_p1_f32_e32 v3, v0, attr0.y
10v_interp_p2_f32_e32 v3, v1, attr0.y
11v_mov_b32_e32 v4, 0.5
12v_mov_b32_e32 v5, v2
13v_mov_b32_e32 v6, v3
14s_load_dwordx8 s[8:15], s[0:1], 0x0
15s_waitcnt lgkmcnt(0)
16s_mov_b32 s16, 0x3092
17s_mov_b32 s17, 0xc00000
18s_mov_b32 s18, 0x14500000
19s_mov_b32 s19, 0
20image_sample_c v9, v[4:6], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D
21image_sample_c v10, v[4:6], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D d16
22s_waitcnt vmcnt(0)
23v_cvt_f32_f16_e32 v11, v10
24exp mrt0 v9, v11, v2, v3 done vm
25s_endpgm
diff --git a/runtime/test/shaders/ps_sample_c_b.asm b/runtime/test/shaders/ps_sample_c_b.asm
new file mode 100644
index 000000000..ad86f20df
--- /dev/null
+++ b/runtime/test/shaders/ps_sample_c_b.asm
@@ -0,0 +1,25 @@
1; Depth-compare sampling with a LOD bias: image_sample_c_b, as ps_sample_c with the bias 1.0 in front of the z-compare
2; (address v[4:7] = bias, z-compare 0.5, u, v). A bias read as the reference (1.0 compares false everywhere) or the
3; reference as the bias would change every result; on the one-level texture the bias itself has no other effect.
4; mrt0 = (f32 result, widened d16 result, u, v).
5; Run: vk_texture_test dref_c_b -> every pixel's first two components are 1.0 where its texel has x >= 4, else 0.0
6v_interp_p1_f32_e32 v2, v0, attr0.x
7v_interp_p2_f32_e32 v2, v1, attr0.x
8v_interp_p1_f32_e32 v3, v0, attr0.y
9v_interp_p2_f32_e32 v3, v1, attr0.y
10v_mov_b32_e32 v4, 1.0
11v_mov_b32_e32 v5, 0.5
12v_mov_b32_e32 v6, v2
13v_mov_b32_e32 v7, v3
14s_load_dwordx8 s[8:15], s[0:1], 0x0
15s_waitcnt lgkmcnt(0)
16s_mov_b32 s16, 0x3092
17s_mov_b32 s17, 0xc00000
18s_mov_b32 s18, 0x14500000
19s_mov_b32 s19, 0
20image_sample_c_b v9, v[4:7], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D
21image_sample_c_b v10, v[4:7], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D d16
22s_waitcnt vmcnt(0)
23v_cvt_f32_f16_e32 v11, v10
24exp mrt0 v9, v11, v2, v3 done vm
25s_endpgm
diff --git a/runtime/test/shaders/ps_texture_b_cl.asm b/runtime/test/shaders/ps_texture_b_cl.asm
new file mode 100644
index 000000000..ba8970667
--- /dev/null
+++ b/runtime/test/shaders/ps_texture_b_cl.asm
@@ -0,0 +1,23 @@
1; image_sample_b_cl: as ps_texture_cl with a LOD bias of 0.0 in front of the coordinates (address v[3:6] = bias,
2; u / 4, v / 4, clamp), so the bias and the clamp each have to come from their own VGPR. Left half mip 0 (red), right
3; half mip 1 (cyan). A bias read from the clamp's register (1.0) would still give cyan on the right but also move the
4; left half to mip 1; the clamp read as the bias would never clamp.
5v_interp_p1_f32_e32 v2, v0, attr0.x
6v_interp_p2_f32_e32 v2, v1, attr0.x
7v_interp_p1_f32_e32 v3, v0, attr0.y
8v_interp_p2_f32_e32 v3, v1, attr0.y
9s_load_dwordx8 s[8:15], s[0:1], 0x0
10s_waitcnt lgkmcnt(0)
11s_mov_b32 s16, 0x92
12s_mov_b32 s17, 0xc00000
13s_mov_b32 s18, 0x14500000
14s_mov_b32 s19, 0
15v_cmp_le_f32_e32 vcc_lo, 0.5, v2
16v_mul_f32_e32 v4, 0.25, v2
17v_mul_f32_e32 v5, 0.25, v3
18v_mov_b32_e32 v3, 0
19v_cndmask_b32_e64 v6, 0, 1.0, vcc_lo
20image_sample_b_cl v[8:11], v[3:6], s[8:15], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_2D
21s_waitcnt vmcnt(0)
22exp mrt0 v8, v9, v10, v11 done vm
23s_endpgm
diff --git a/runtime/test/shaders/ps_texture_cl.asm b/runtime/test/shaders/ps_texture_cl.asm
new file mode 100644
index 000000000..932427c9d
--- /dev/null
+++ b/runtime/test/shaders/ps_texture_cl.asm
@@ -0,0 +1,23 @@
1; image_sample_cl on vk_texture_test's two-mip texture (--two-mip: 128x128 quadrants, solid cyan mip 1) drawn on 64x64:
2; the coordinates are u / 4, v / 4, so the unclamped LOD is -1 (mip 0, the top-left quadrant, red). The min-LOD clamp
3; after the coordinates is 0.0 left of x = 32 and 1.0 from there on: the left half must read mip 0 (red), the right half
4; mip 1 (cyan). A clamp read from the wrong register, or ignored, makes the right half red too.
5; Address v[4:6] = (u / 4, v / 4, clamp); MinLod on an implicit-LOD sample (OpImageSampleImplicitLod ... MinLod).
6v_interp_p1_f32_e32 v2, v0, attr0.x
7v_interp_p2_f32_e32 v2, v1, attr0.x
8v_interp_p1_f32_e32 v3, v0, attr0.y
9v_interp_p2_f32_e32 v3, v1, attr0.y
10s_load_dwordx8 s[8:15], s[0:1], 0x0
11s_waitcnt lgkmcnt(0)
12s_mov_b32 s16, 0x92
13s_mov_b32 s17, 0xc00000
14s_mov_b32 s18, 0x14500000
15s_mov_b32 s19, 0
16v_cmp_le_f32_e32 vcc_lo, 0.5, v2
17v_mul_f32_e32 v4, 0.25, v2
18v_mul_f32_e32 v5, 0.25, v3
19v_cndmask_b32_e64 v6, 0, 1.0, vcc_lo
20image_sample_cl v[8:11], v[4:6], s[8:15], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_2D
21s_waitcnt vmcnt(0)
22exp mrt0 v8, v9, v10, v11 done vm
23s_endpgm
diff --git a/runtime/test/shaders/ps_w64_a_discard.asm b/runtime/test/shaders/ps_w64_a_discard.asm
new file mode 100644
index 000000000..b8f4c16a5
--- /dev/null
+++ b/runtime/test/shaders/ps_w64_a_discard.asm
@@ -0,0 +1,65 @@
1; SHADER-10 tier A (docs/design.md, "Wave64 graphics: partition invariance"): the early exit of a pixel kill. A wave64
2; pixel shader whose 32-lane halves can lose every pixel while the other half lives on gives the same image when its
3; 64 lanes are cut into two 32-lane subgroups. x = floor(u * 64), y = floor(v * 64) are the pixel's coordinates on
4; the 64x64 target (u, v = attr0.xy of vs_ids), so every expected word is a function of (x, y) and not of the lane
5; the pixel landed on.
6; Three kills, each `s_andn2_b64 live, live, <kill mask>` then `s_cbranch_scc0` to its own exit block, which only
7; sets EXEC from the (empty) live mask, exports null with done vm and ends (an exit shared by several kills reads a
8; mask redefined behind the earlier votes: tier C tainted-exec, a stale scalar). The run side narrows EXEC into the
9; whole quads of the live mask (s_wqm_b64, s_and_b64 exec) and never widens it.
10; (1) x < 30, through v_cmpx (EXEC = the pixels to kill); (2) y >= 50, through VCC; (3) x % 4 == 3 and y odd
11; ((y & 1) * 4 + (x & 3) == 7), through VCC.
12; The first two discard large regions: whole waves and, at x = 30 and y = 50, halves whose pixels are all dead
13; next to halves that live (for a wave tiled as 8x8 cut into 8x4 or 4x8 halves, among others).
14; Before the export EXEC is narrowed to the live mask itself, so the helper lanes of the quads are discarded.
15; Live pixel: r0 = 7 * y + x, r1 = 1, r2 = 2000 + y, r3 = x % 4 + 1. A discarded pixel keeps the harness clear
16; value, -1.0f in every word (0xbf800000).
17; Run: vk_harness vs_ids.spv ps_w64_a_discard.spv out.raw, once with VKH_SUBGROUP_SIZE=64 and once with 32: the two
18; images must be equal (and equal to the expected words). Output is raw bits (r0, r1, r2, r3) per pixel.
19; mattr: +wavefrontsize64,-wavefrontsize32
20v_interp_p1_f32_e32 v2, v0, attr0.x
21v_interp_p2_f32_e32 v2, v1, attr0.x
22v_interp_p1_f32_e32 v3, v0, attr0.y
23v_interp_p2_f32_e32 v3, v1, attr0.y
24v_mul_f32_e32 v2, 0x42800000, v2
25v_mul_f32_e32 v3, 0x42800000, v3
26v_cvt_u32_f32_e32 v2, v2
27v_cvt_u32_f32_e32 v3, v3
28s_mov_b64 s[10:11], exec
29s_mov_b64 s[20:21], exec
30v_cmpx_gt_u32_e32 30, v2
31s_andn2_b64 s[20:21], s[20:21], exec
32s_cbranch_scc0 34
33s_wqm_b64 s[22:23], s[20:21]
34s_and_b64 exec, s[10:11], s[22:23]
35v_cmp_lt_u32_e32 vcc, 49, v3
36s_andn2_b64 s[20:21], s[20:21], vcc
37s_cbranch_scc0 25
38s_wqm_b64 s[22:23], s[20:21]
39s_and_b64 exec, exec, s[22:23]
40v_and_b32_e32 v4, 3, v2
41v_and_b32_e32 v5, 1, v3
42v_lshlrev_b32_e32 v5, 2, v5
43v_add_nc_u32_e32 v5, v5, v4
44v_cmp_eq_u32_e32 vcc, 7, v5
45s_andn2_b64 s[20:21], s[20:21], vcc
46s_cbranch_scc0 12
47s_wqm_b64 s[22:23], s[20:21]
48s_and_b64 exec, exec, s[22:23]
49v_mul_u32_u24_e32 v6, 7, v3
50v_add_nc_u32_e32 v6, v6, v2
51v_mov_b32_e32 v7, 1
52v_add_nc_u32_e32 v8, 0x7d0, v3
53v_add_nc_u32_e32 v9, 1, v4
54s_and_b64 exec, exec, s[20:21]
55exp mrt0 v6, v7, v8, v9 done vm
56s_endpgm
57s_mov_b64 exec, s[20:21]
58exp null off, off, off, off done vm
59s_endpgm
60s_mov_b64 exec, s[20:21]
61exp null off, off, off, off done vm
62s_endpgm
63s_mov_b64 exec, s[20:21]
64exp null off, off, off, off done vm
65s_endpgm
diff --git a/runtime/test/shaders/w64_graphics.py b/runtime/test/shaders/w64_graphics.py
index cea4f29c0..64aa532b7 100644
--- a/runtime/test/shaders/w64_graphics.py
+++ b/runtime/test/shaders/w64_graphics.py
@@ -63,6 +63,16 @@ def _a_skip(i):
63 return (7 * y + x if x % 4 == 1 else 1000 + x, int(x % 4 < 2), 2000 + y + (9 if y % 4 == 2 else 0), x % 4 + 1) 63 return (7 * y + x if x % 4 == 1 else 1000 + x, int(x % 4 < 2), 2000 + y + (9 if y % 4 == 2 else 0), x % 4 + 1)
64 64
65 65
66CLEAR = 0xBF800000 # the harness clears the target to -1.0f: the words of a pixel no shader wrote
67
68
69def _a_discard(i):
70 x, y = _x(i), _y(i)
71 if x < 30 or y >= 50 or (x % 4 == 3 and y % 2 == 1):
72 return (CLEAR,) * 4
73 return (7 * y + x, 1, 2000 + y, x % 4 + 1)
74
75
66def _b_waterfall(i): 76def _b_waterfall(i):
67 x, y = _x(i), _y(i) 77 x, y = _x(i), _y(i)
68 a = x % 4 + 4 * (y % 4) 78 a = x % 4 + 4 * (y % 4)
@@ -169,6 +179,7 @@ FIXTURES = {
169 "ps_w64_a_permlane": ("A", _a_permlane, {}), 179 "ps_w64_a_permlane": ("A", _a_permlane, {}),
170 "ps_w64_a_swizzle": ("A", _a_swizzle, {}), 180 "ps_w64_a_swizzle": ("A", _a_swizzle, {}),
171 "ps_w64_a_bpermute": ("A", _a_bpermute, {}), 181 "ps_w64_a_bpermute": ("A", _a_bpermute, {}),
182 "ps_w64_a_discard": ("A", _a_discard, {}),
172 "ps_w64_b_waterfall": ("B", _b_waterfall, {}), 183 "ps_w64_b_waterfall": ("B", _b_waterfall, {}),
173 "ps_w64_b_readfirstlane": ("B", _b_readfirstlane, {"VKH_SGPRS": "0,0,0,0,123"}), 184 "ps_w64_b_readfirstlane": ("B", _b_readfirstlane, {"VKH_SGPRS": "0,0,0,0,123"}),
174 "ps_w64_b_readlane_uniform": ("B", _b_readlane_uniform, {"VKH_SGPRS": "0,0,0,0,123"}), 185 "ps_w64_b_readlane_uniform": ("B", _b_readlane_uniform, {"VKH_SGPRS": "0,0,0,0,123"}),
diff --git a/runtime/test/test_runtime_types.cpp b/runtime/test/test_runtime_types.cpp
index 1a0b5ed2a..a71deb000 100644
--- a/runtime/test/test_runtime_types.cpp
+++ b/runtime/test/test_runtime_types.cpp
@@ -525,18 +525,27 @@ void test_xmem_working_set_statistics_abi_layout() {
525 check(ok != FALSE && pmc.WorkingSetSize > 0, 525 check(ok != FALSE && pmc.WorkingSetSize > 0,
526 "GetProcessMemoryInfo succeeds and returns non-zero WorkingSetSize"); 526 "GetProcessMemoryInfo succeeds and returns non-zero WorkingSetSize");
527 527
528 // Verify FidelityFX / XMem layout contract: 528 // Verify FidelityFX / XMem layout contract (RT-220):
529 // stats[0..7] = 0 (unknown/reserved), stats[8..15] = WorkingSetSize (uint64_t) 529 // The measured FSR sites establish argument shape, kind and the +8 working-set read; +0's title-total memory
530 // limit is inferred from other Series implementations (xcl, xbox-emulator).
531 // stats[0..7] = TotalMemoryLimit (uint64_t), stats[8..15] = WorkingSetSize (uint64_t)
530 alignas(64) uint8_t stats[64]; 532 alignas(64) uint8_t stats[64];
531 std::memset(stats, 0xA5, sizeof(stats)); 533 std::memset(stats, 0xA5, sizeof(stats));
532 534
533 std::memset(stats, 0, 16); 535 std::memset(stats, 0, 16);
536 MEMORYSTATUSEX ms{sizeof(ms)};
537 uint64_t total_memory = 12ULL * 1024 * 1024 * 1024;
538 if (GlobalMemoryStatusEx(&ms) && ms.ullTotalPhys != 0) {
539 total_memory = ms.ullTotalPhys;
540 }
541 std::memcpy(stats + 0, &total_memory, sizeof(total_memory));
534 const uint64_t working_set = static_cast<uint64_t>(pmc.WorkingSetSize); 542 const uint64_t working_set = static_cast<uint64_t>(pmc.WorkingSetSize);
535 std::memcpy(stats + 8, &working_set, sizeof(working_set)); 543 std::memcpy(stats + 8, &working_set, sizeof(working_set));
536 544
537 uint64_t prefix0 = 0; 545 uint64_t prefix0 = 0;
538 std::memcpy(&prefix0, stats, sizeof(prefix0)); 546 std::memcpy(&prefix0, stats, sizeof(prefix0));
539 check(prefix0 == 0, "Working set statistics prefix at +0 is 0"); 547 check(prefix0 == total_memory && prefix0 >= working_set,
548 "Working set statistics total memory at +0 holds title memory limit >= working set");
540 549
541 uint64_t extracted_ws = 0; 550 uint64_t extracted_ws = 0;
542 std::memcpy(&extracted_ws, stats + 8, sizeof(extracted_ws)); 551 std::memcpy(&extracted_ws, stats + 8, sizeof(extracted_ws));
diff --git a/runtime/test/test_temp_dir.h b/runtime/test/test_temp_dir.h
new file mode 100644
index 000000000..3601f35d0
--- /dev/null
+++ b/runtime/test/test_temp_dir.h
@@ -0,0 +1,67 @@
1// Scratch folders for tests that write files (a translator-style shader library, an index) under the temp directory.
2//
3// The folder name carries the process id. Under one fixed name, every copy of a test running at the same time (ctest
4// -j, or two suites sharing one Wine prefix or one TMPDIR) used the same folder, and one copy's remove_all deleted the
5// modules another copy was still loading: with four copies of d3d12_compute at once, 6 of 40 runs failed at PSO
6// creation or in copy_file, while 125 runs one at a time all passed (Apple M3 Max, MoltenVK 1.4.3 under Wine 11).
7#pragma once
8
9#include <cstdio>
10#include <filesystem>
11#include <string>
12#include <string_view>
13#include <system_error>
14
15#ifdef _WIN32
16#include <process.h>
17#else
18#include <unistd.h>
19#endif
20
21namespace testfiles {
22
23// <temp>/<name>_<pid>: a folder no other running process uses.
24inline std::filesystem::path process_temp_dir(std::string_view name) {
25#ifdef _WIN32
26 const long pid = long(_getpid());
27#else
28 const long pid = long(getpid());
29#endif
30 return std::filesystem::temp_directory_path() / (std::string(name) + "_" + std::to_string(pid));
31}
32
33// process_temp_dir(name), emptied and created on construction (a crashed run may have left the same name behind) and
34// removed with its contents on destruction, so early returns don't leave one folder per failed run.
35class ScratchDir {
36public:
37 explicit ScratchDir(std::string_view name) : path_(process_temp_dir(name)) {
38 std::error_code ec;
39 std::filesystem::remove_all(path_, ec);
40 std::filesystem::create_directories(path_, ec);
41 if (ec) std::fprintf(stderr, "cannot create %s: %s\n", path_.string().c_str(), ec.message().c_str());
42 }
43 ~ScratchDir() {
44 std::error_code ec;
45 std::filesystem::remove_all(path_, ec);
46 }
47 ScratchDir(const ScratchDir&) = delete;
48 ScratchDir& operator=(const ScratchDir&) = delete;
49
50 const std::filesystem::path& path() const { return path_; }
51
52private:
53 std::filesystem::path path_;
54};
55
56// Copies `from` (a file the build compiled into the test, LEONIDA_TEST_*_SPV) to `to`, overwriting it. Returns false
57// and says why when it can't: std::filesystem::copy_file would throw instead, and the uncaught exception ends the
58// test without a message (abort; exit code 3 under Wine), which reads as a crash rather than a missing file.
59inline bool copy_file(const std::filesystem::path& from, const std::filesystem::path& to) {
60 std::error_code ec;
61 std::filesystem::copy_file(from, to, std::filesystem::copy_options::overwrite_existing, ec);
62 if (ec) std::fprintf(stderr, "cannot copy %s to %s: %s\n", from.string().c_str(), to.string().c_str(),
63 ec.message().c_str());
64 return !ec;
65}
66
67} // namespace testfiles
diff --git a/runtime/test/vk_command_replay_test.cpp b/runtime/test/vk_command_replay_test.cpp
index cf32f094b..9769e70be 100644
--- a/runtime/test/vk_command_replay_test.cpp
+++ b/runtime/test/vk_command_replay_test.cpp
@@ -7,7 +7,8 @@
7// Part F (D3D-26) runs immediate buffer writes, atomic copies and discards. Part G copies one subresource twice in one 7// Part F (D3D-26) runs immediate buffer writes, atomic copies and discards. Part G copies one subresource twice in one
8// list, which D3D12 orders on the queue and needs an explicit dependency for on Vulkan. Part H copies depth to colour 8// list, which D3D12 orders on the queue and needs an explicit dependency for on Vulkan. Part H copies depth to colour
9// and back (D32_FLOAT <-> R32_FLOAT), which the replay stages through a scratch buffer. Part I resolves a depth 9// and back (D32_FLOAT <-> R32_FLOAT), which the replay stages through a scratch buffer. Part I resolves a depth
10// rectangle (MIN) and checks that the texels around it keep their values. 10// rectangle (MIN) and checks that the texels around it keep their values. Part J copies between disjoint regions
11// of one texture subresource.
11// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation; any validation error fails the test. 12// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation; any validation error fails the test.
12#include "vk_test_device.h" 13#include "vk_test_device.h"
13#include "../src/vulkan_replay.h" 14#include "../src/vulkan_replay.h"
@@ -1188,6 +1189,82 @@ int part_i(vktest::Device& d) {
1188 return 0; 1189 return 0;
1189} 1190}
1190 1191
1192int part_j(vktest::Device& d) {
1193 constexpr std::uint32_t width = 4, height = 2, pitch = texture_data_pitch_alignment;
1194 constexpr VkFormat format = VK_FORMAT_R8G8B8A8_UNORM;
1195 const VkImage image = d.image(format, width, height, 1, 0);
1196 void* upload_data = nullptr;
1197 const VkBuffer upload = d.buffer(pitch * height, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &upload_data);
1198 void* readback_data = nullptr;
1199 const VkBuffer readback = d.buffer(width * height * 4, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &readback_data);
1200 EXPECT(image && upload && readback);
1201 for (std::uint32_t y = 0; y < height; ++y)
1202 std::memcpy(static_cast<std::uint8_t*>(upload_data) + pitch * y, (y ? green : red).data(), 4);
1203
1204 constexpr ResourceId image_id = 40, upload_id = 41;
1205 ResourceBinding image_binding{}, upload_binding{};
1206 image_binding.image = image;
1207 image_binding.format = format;
1208 image_binding.width = width;
1209 image_binding.height = height;
1210 upload_binding.buffer = upload;
1211 upload_binding.size = pitch * height;
1212 const auto resolve = [&](ResourceId id) -> const ResourceBinding* {
1213 if (id == image_id) return &image_binding;
1214 if (id == upload_id) return &upload_binding;
1215 return nullptr;
1216 };
1217 LayoutTracker tracker;
1218 tracker.track(image_id, image_binding, VK_IMAGE_LAYOUT_UNDEFINED);
1219 ReplayFunctions vk{};
1220 vk.pipeline_barrier = d.fn<PFN_vkCmdPipelineBarrier>("vkCmdPipelineBarrier");
1221 vk.pipeline_barrier2 = d.fn<PFN_vkCmdPipelineBarrier2>("vkCmdPipelineBarrier2");
1222 vk.clear_color_image = d.fn<PFN_vkCmdClearColorImage>("vkCmdClearColorImage");
1223 vk.copy_buffer = d.fn<PFN_vkCmdCopyBuffer>("vkCmdCopyBuffer");
1224 vk.copy_image_to_buffer = d.fn<PFN_vkCmdCopyImageToBuffer>("vkCmdCopyImageToBuffer");
1225 vk.copy_buffer_to_image = d.fn<PFN_vkCmdCopyBufferToImage>("vkCmdCopyBufferToImage");
1226 vk.copy_image = d.fn<PFN_vkCmdCopyImage>("vkCmdCopyImage");
1227
1228 namespace a = d3d12_access;
1229 namespace l = d3d12_layout;
1230 namespace y = d3d12_sync;
1231 const CopyLocation texture{image_id, false, 0, 0, 0, 0, 0, 0};
1232 const CopyLocation footprint{upload_id, true, 0, 0, 1, height, 1, pitch};
1233 const CopyBox column{0, 0, 0, 1, height, 1};
1234 const BarrierSubresourceRange all{all_subresources, 0, 0, 0, 0, 0};
1235 CommandList first;
1236 EXPECT(first.copy_texture({texture, 2, 0, 0, texture, true, column}));
1237 EXPECT(first.close());
1238 CommandList list;
1239 EXPECT(list.barrier(TextureBarrier{y::copy, y::copy, a::copy_dest, a::copy_dest,
1240 l::common, l::copy_dest, image_id, all, 0}));
1241 EXPECT(list.copy_texture({texture, 0, 0, 0, footprint, false, {}}));
1242 EXPECT(list.barrier(TextureBarrier{y::copy, y::copy, a::copy_dest, a::copy_source | a::copy_dest,
1243 l::copy_dest, l::common, image_id, all, 0}));
1244 EXPECT(list.copy_texture({texture, 1, 0, 0, texture, true, column})); // touching edges, not overlapping
1245 EXPECT(list.barrier(TextureBarrier{y::copy, y::copy, a::copy_dest, a::copy_source,
1246 l::common, l::copy_source, image_id, all, 0}));
1247 EXPECT(list.close());
1248 CommandList overlap;
1249 EXPECT(overlap.copy_texture({texture, 1, 0, 0, texture, true, {0, 0, 0, 2, height, 1}}));
1250 EXPECT(overlap.close());
1251 EXPECT(d.run([&](VkCommandBuffer cb) {
1252 if (replay(overlap, cb, resolve, vk, &tracker) != ReplayResult::invalid_copy) return false;
1253 if (replay(first, cb, resolve, vk, &tracker) != ReplayResult::success ||
1254 tracker.layout(image_id, 0) != VK_IMAGE_LAYOUT_GENERAL) return false;
1255 if (replay(list, cb, resolve, vk, &tracker) != ReplayResult::success) return false;
1256 d.read_back(cb, image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_ASPECT_COLOR_BIT, width, height, 1,
1257 readback, 0);
1258 return true;
1259 }));
1260 const auto* pixels = static_cast<const std::uint8_t*>(readback_data);
1261 for (std::uint32_t y = 0; y < height; ++y)
1262 for (std::uint32_t x = 0; x < width; ++x)
1263 expect_rgba("J self-copy", pixels, y * width + x, x < 2 ? (y ? green : red) : Rgba{});
1264 std::printf("J: disjoint same-subresource copies, overlapping copy rejected\n");
1265 return 0;
1266}
1267
1191} // namespace 1268} // namespace
1192 1269
1193int main() { 1270int main() {
@@ -1199,7 +1276,7 @@ int main() {
1199 } 1276 }
1200 EXPECT(status == vktest::DeviceStatus::ready); 1277 EXPECT(status == vktest::DeviceStatus::ready);
1201 if (part_a(device) || part_b(device) || part_c(device) || part_d(device) || part_e(device) || part_f(device) || 1278 if (part_a(device) || part_b(device) || part_c(device) || part_d(device) || part_e(device) || part_f(device) ||
1202 part_g(device) || part_h(device) || part_i(device)) 1279 part_g(device) || part_h(device) || part_i(device) || part_j(device))
1203 return 1; 1280 return 1;
1204 if (g_mismatches) return 1; 1281 if (g_mismatches) return 1;
1205 if (device.validation_errors()) { 1282 if (device.validation_errors()) {
diff --git a/runtime/test/vk_compute_test.cpp b/runtime/test/vk_compute_test.cpp
index 69e3bd014..f962cdff6 100644
--- a/runtime/test/vk_compute_test.cpp
+++ b/runtime/test/vk_compute_test.cpp
@@ -11,6 +11,11 @@
11// and before the dispatch, so a program can read prepared inputs (a root table, descriptors, data) from the heap. 11// and before the dispatch, so a program can read prepared inputs (a root table, descriptors, data) from the heap.
12// The file must fit in the buffer (raise VKC_OUT_WORDS); bytes past it keep the fill. 12// The file must fit in the buffer (raise VKC_OUT_WORDS); bytes past it keep the fill.
13// --require-wave64: require full 64-wide subgroups (local size X must be a multiple of 64), or exit 77. 13// --require-wave64: require full 64-wide subgroups (local size X must be a multiple of 64), or exit 77.
14// VKC_SUBGROUP_SIZE=N (env): run at N lanes. Where the device can't require a compute subgroup size but N is its
15// default subgroupSize (MoltenVK: 32, and requiredSubgroupSizeStages 0), the size is still fixed for a SPIR-V 1.5
16// module (no varying subgroup size); cs_wave_probe.comp then checks, with the test's local size and flags, that every
17// subgroup is N lanes wide (by its lane numbers and a ballot), or the test fails (exit 1) without running; N-lane
18// subgroups not in invocation order print "not available", as a size that can't be pinned does.
14// VKC_SGPRS=w4,w5,... (env): set s4, s5, ... (decimal or 0x hex, up to s31), the user SGPRs after the output V#, 19// VKC_SGPRS=w4,w5,... (env): set s4, s5, ... (decimal or 0x hex, up to s31), the user SGPRs after the output V#,
15// so a test can take input words (cs_user_sgprs.asm). They are zero otherwise. Same syntax as vk_harness's VKH_SGPRS. 20// so a test can take input words (cs_user_sgprs.asm). They are zero otherwise. Same syntax as vk_harness's VKH_SGPRS.
16// Contract (docs/design.md): push constants = s0..s31 (128 bytes), heap base lo/hi, code base lo/hi (144 bytes). 21// Contract (docs/design.md): push constants = s0..s31 (128 bytes), heap base lo/hi, code base lo/hi (144 bytes).
@@ -20,6 +25,7 @@
20#include "vk_device_pick.h" 25#include "vk_device_pick.h"
21#include "vk_shader_fma.h" 26#include "vk_shader_fma.h"
22#include "vk_pc_tail.h" 27#include "vk_pc_tail.h"
28#include "cs_wave_probe_spv.h"
23 29
24#include <cctype> 30#include <cctype>
25#include <cmath> 31#include <cmath>
@@ -54,6 +60,37 @@ static bool parse_u32(const char*& s, uint32_t& v) {
54 return true; 60 return true;
55} 61}
56 62
63// The module's SPIR-V version and the OpExecutionMode LocalSize of its GLCompute entry point "main", the one the
64// pipeline is made from. All zero when there is none (no such entry point, or LocalSizeId), and then the size is
65// unknown: nothing that needs it (the subgroup probe, full subgroups) is done.
66static uint32_t spirv_local_size(const std::vector<char>& code, uint32_t local[3]) {
67 local[0] = local[1] = local[2] = 0;
68 const std::size_t n = code.size() / 4;
69 std::vector<uint32_t> w(n);
70 if (n) std::memcpy(w.data(), code.data(), n * 4);
71 if (n < 5 || w[0] != 0x07230203u) return 0;
72 constexpr uint32_t kOpEntryPoint = 15, kOpExecutionMode = 16, kGLCompute = 5, kLocalSize = 17;
73 uint32_t main_id = 0;
74 bool have_main = false;
75 for (std::size_t i = 5; i < n;) {
76 const uint32_t len = w[i] >> 16, op = w[i] & 0xFFFFu;
77 if (!len || i + len > n) break;
78 // OpEntryPoint model id "name" ...: the name is a nul-terminated string packed little-endian into words.
79 if (op == kOpEntryPoint && len >= 4 && w[i + 1] == kGLCompute) {
80 const char* name = reinterpret_cast<const char*>(&w[i + 3]);
81 if (std::strncmp(name, "main", 4 * (len - 3)) == 0 && std::memchr(name, 0, 4 * (len - 3))) {
82 main_id = w[i + 2];
83 have_main = true;
84 }
85 }
86 if (op == kOpExecutionMode && len == 6 && have_main && w[i + 1] == main_id && w[i + 2] == kLocalSize) {
87 local[0] = w[i + 3]; local[1] = w[i + 4]; local[2] = w[i + 5];
88 }
89 i += len;
90 }
91 return w[1];
92}
93
57static bool next_item(const char*& s) { 94static bool next_item(const char*& s) {
58 if (!*s) return true; 95 if (!*s) return true;
59 return *s++ == ',' && *s; 96 return *s++ == ',' && *s;
@@ -110,6 +147,10 @@ int main(int argc, char** argv) {
110 } 147 }
111 out_words = uint32_t(n); 148 out_words = uint32_t(n);
112 } 149 }
150 std::ifstream f(argv[1], std::ios::binary);
151 std::vector<char> code((std::istreambuf_iterator<char>(f)), {});
152 uint32_t local[3];
153 const uint32_t spirv_version = spirv_local_size(code, local);
113 gipa = load_vulkan(); 154 gipa = load_vulkan();
114 if (!gipa) return 1; 155 if (!gipa) return 1;
115#define LOADI(name) auto name = reinterpret_cast<PFN_##name>(gipa(inst, #name)) 156#define LOADI(name) auto name = reinterpret_cast<PFN_##name>(gipa(inst, #name))
@@ -166,19 +207,31 @@ int main(int argc, char** argv) {
166 std::fprintf(stderr, "full 64-wide compute subgroups unavailable\n"); 207 std::fprintf(stderr, "full 64-wide compute subgroups unavailable\n");
167 return 77; 208 return 77;
168 } 209 }
169 std::ifstream f(argv[1], std::ios::binary);
170 std::vector<char> code((std::istreambuf_iterator<char>(f)), {});
171 const bool needs_float64 = leonida::vk_test::spirv_declares_capability(code.data(), code.size(), 10); // Float64 210 const bool needs_float64 = leonida::vk_test::spirv_declares_capability(code.data(), code.size(), 10); // Float64
172 if (needs_float64 && !f2q.features.shaderFloat64) { 211 if (needs_float64 && !f2q.features.shaderFloat64) {
173 std::fprintf(stderr, "unsupported: %s uses Float64 and the device has no shaderFloat64\n", argv[1]); 212 std::fprintf(stderr, "unsupported: %s uses Float64 and the device has no shaderFloat64\n", argv[1]);
174 return 77; 213 return 77;
175 } 214 }
215 // A size the device can't require but runs anyway: one min..max range (fixed), or its default subgroupSize in a
216 // module below SPIR-V 1.6 (Vulkan "Varying Subgroup Size": SubgroupSize then always equals subgroupSize), which
217 // cs_wave_probe checks before the test runs (observed). Full subgroups where local size X is a multiple of
218 // maxSubgroupSize (VUID-VkPipelineShaderStageCreateInfo-flags-02759).
219 const bool fixed = req_sg && sgProps.minSubgroupSize == sgProps.maxSubgroupSize && subgroup.subgroupSize == req_sg;
220 const uint32_t local_total = local[0] * local[1] * local[2];
221 // The probe itself needs subgroup operations in compute: the basic built-ins and a ballot.
222 const bool probe_runs = (subgroup.supportedStages & VK_SHADER_STAGE_COMPUTE_BIT) &&
223 (subgroup.supportedOperations & VK_SUBGROUP_FEATURE_BASIC_BIT) &&
224 (subgroup.supportedOperations & VK_SUBGROUP_FEATURE_BALLOT_BIT);
225 const bool observed = req_sg && !require_wave64 && !can_request_size && !fixed && probe_runs &&
226 subgroup.subgroupSize == req_sg && spirv_version && spirv_version < 0x00010600u &&
227 local_total && local_total <= 1024;
228 const bool observed_full = observed && f13q.computeFullSubgroups && local[0] % sgProps.maxSubgroupSize == 0;
176 VkPhysicalDeviceVulkan13Features f13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES}; 229 VkPhysicalDeviceVulkan13Features f13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES};
177 VkPhysicalDeviceVulkan12Features f12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES}; 230 VkPhysicalDeviceVulkan12Features f12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES};
178 f12.bufferDeviceAddress = VK_TRUE; 231 f12.bufferDeviceAddress = VK_TRUE;
179 if (f13q.subgroupSizeControl || require_wave64) { 232 if (f13q.subgroupSizeControl || require_wave64) {
180 f13.subgroupSizeControl = f13q.subgroupSizeControl; 233 f13.subgroupSizeControl = f13q.subgroupSizeControl;
181 f13.computeFullSubgroups = require_wave64 ? VK_TRUE : VK_FALSE; 234 f13.computeFullSubgroups = require_wave64 || observed_full ? VK_TRUE : VK_FALSE;
182 f12.pNext = &f13; 235 f12.pNext = &f13;
183 } 236 }
184 VkPhysicalDeviceFeatures2 f2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; 237 VkPhysicalDeviceFeatures2 f2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2};
@@ -242,7 +295,7 @@ int main(int argc, char** argv) {
242 if (!std::strcmp(argv[3], "bvh")) { 295 if (!std::strcmp(argv[3], "bvh")) {
243 // AMD-format BVH in the heap (runtime/test/shaders/cs_bvh.asm): box32 root at 0x100 whose children are a 296 // AMD-format BVH in the heap (runtime/test/shaders/cs_bvh.asm): box32 root at 0x100 whose children are a
244 // triangle at z=10 (node 0x40, addr 0x200), a triangle at z=5 (node 0x48, addr 0x240), a box the ray 297 // triangle at z=10 (node 0x40, addr 0x200), a triangle at z=5 (node 0x48, addr 0x240), a box the ray
245 // misses, and an inactive (NaN) box. Node id = address >> 3 | type. 298 // misses, and a box with a NaN min.x that RDNA2 still enters at t = 0 (SHADER-650). Node id = address >> 3 | type.
246 auto f32 = [&](uint32_t at, float v) { std::memcpy(static_cast<char*>(map) + at, &v, 4); }; 299 auto f32 = [&](uint32_t at, float v) { std::memcpy(static_cast<char*>(map) + at, &v, 4); };
247 auto u32 = [&](uint32_t at, uint32_t v) { std::memcpy(static_cast<char*>(map) + at, &v, 4); }; 300 auto u32 = [&](uint32_t at, uint32_t v) { std::memcpy(static_cast<char*>(map) + at, &v, 4); };
248 u32(0x100, 0x40); u32(0x104, 0x48); u32(0x108, 0x60); u32(0x10C, 0x68); 301 u32(0x100, 0x40); u32(0x104, 0x48); u32(0x108, 0x60); u32(0x10C, 0x68);
@@ -290,7 +343,7 @@ int main(int argc, char** argv) {
290 reqSg.requiredSubgroupSize = req_sg; 343 reqSg.requiredSubgroupSize = req_sg;
291 if (can_request_size) 344 if (can_request_size)
292 cpi.stage.pNext = &reqSg; 345 cpi.stage.pNext = &reqSg;
293 if (require_wave64) 346 if (require_wave64 || observed_full)
294 cpi.stage.flags = VK_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT; 347 cpi.stage.flags = VK_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT;
295 cpi.layout = pl; 348 cpi.layout = pl;
296 VkPipeline pipe; CHECK(vkCreateComputePipelines(dev, VK_NULL_HANDLE, 1, &cpi, nullptr, &pipe)); 349 VkPipeline pipe; CHECK(vkCreateComputePipelines(dev, VK_NULL_HANDLE, 1, &cpi, nullptr, &pipe));
@@ -298,9 +351,8 @@ int main(int argc, char** argv) {
298 else if (req_sg) { 351 else if (req_sg) {
299 // VKC_SUBGROUP_SIZE: say whether the pipeline really runs at that size, so a runner can skip a test the device 352 // VKC_SUBGROUP_SIZE: say whether the pipeline really runs at that size, so a runner can skip a test the device
300 // can't pin instead of judging words from whatever size the driver picked (#774). 353 // can't pin instead of judging words from whatever size the driver picked (#774).
301 const bool fixed = sgProps.minSubgroupSize == sgProps.maxSubgroupSize && subgroup.subgroupSize == req_sg;
302 if (can_request_size || fixed) std::printf("compute subgroup size: %u\n", req_sg); 354 if (can_request_size || fixed) std::printf("compute subgroup size: %u\n", req_sg);
303 else std::printf("compute subgroup size: %u not available\n", req_sg); 355 else if (!observed) std::printf("compute subgroup size: %u not available\n", req_sg);
304 } 356 }
305 357
306 pc[0] = 0; pc[1] = 0; pc[2] = 0xFFFFFFFFu; pc[3] = 0x31016FACu; // V#: base 0, stride 0, num_records max, OOB_SELECT 3 (raw) 358 pc[0] = 0; pc[1] = 0; pc[2] = 0xFFFFFFFFu; pc[3] = 0x31016FACu; // V#: base 0, stride 0, num_records max, OOB_SELECT 3 (raw)
@@ -311,6 +363,95 @@ int main(int argc, char** argv) {
311 VkCommandBufferAllocateInfo cai{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; 363 VkCommandBufferAllocateInfo cai{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO};
312 cai.commandPool = pool; cai.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; cai.commandBufferCount = 1; 364 cai.commandPool = pool; cai.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; cai.commandBufferCount = 1;
313 VkCommandBuffer cmd; CHECK(vkAllocateCommandBuffers(dev, &cai, &cmd)); 365 VkCommandBuffer cmd; CHECK(vkAllocateCommandBuffers(dev, &cai, &cmd));
366 if (observed) {
367 // cs_wave_probe with the test's local size and flags, one group, four words per invocation in its own buffer.
368 VkBufferCreateInfo pbi{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
369 pbi.size = VkDeviceSize(local_total) * 16;
370 pbi.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT;
371 VkBuffer pbuf; CHECK(vkCreateBuffer(dev, &pbi, nullptr, &pbuf));
372 VkMemoryRequirements pmr; vkGetBufferMemoryRequirements(dev, pbuf, &pmr);
373 VkMemoryAllocateInfo pmai = mai;
374 pmai.allocationSize = pmr.size;
375 VkDeviceMemory pmem; CHECK(vkAllocateMemory(dev, &pmai, nullptr, &pmem));
376 CHECK(vkBindBufferMemory(dev, pbuf, pmem, 0));
377 void* pmap; CHECK(vkMapMemory(dev, pmem, 0, pbi.size, 0, &pmap));
378 std::memset(pmap, 0xEE, size_t(pbi.size));
379 VkBufferDeviceAddressInfo pbai{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO};
380 pbai.buffer = pbuf;
381 const uint64_t paddr = vkGetBufferDeviceAddress(dev, &pbai);
382 VkShaderModuleCreateInfo psmi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO};
383 psmi.codeSize = sizeof(leonida::vk_test::cs_wave_probe_spirv);
384 psmi.pCode = leonida::vk_test::cs_wave_probe_spirv;
385 VkShaderModule psm; CHECK(vkCreateShaderModule(dev, &psmi, nullptr, &psm));
386 const VkSpecializationMapEntry entries[3] = {{0, 0, 4}, {1, 4, 4}, {2, 8, 4}};
387 const VkSpecializationInfo spec{3, entries, sizeof(local), local};
388 VkComputePipelineCreateInfo pcpi = cpi;
389 pcpi.flags = 0;
390 pcpi.stage.module = psm;
391 pcpi.stage.pSpecializationInfo = &spec;
392 VkPipeline ppipe; CHECK(vkCreateComputePipelines(dev, VK_NULL_HANDLE, 1, &pcpi, nullptr, &ppipe));
393 const uint32_t ppc[2] = {uint32_t(paddr), uint32_t(paddr >> 32)}; // cs_wave_probe's buffer address
394 VkCommandBuffer pcmd; CHECK(vkAllocateCommandBuffers(dev, &cai, &pcmd));
395 VkCommandBufferBeginInfo pcbi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO};
396 CHECK(vkBeginCommandBuffer(pcmd, &pcbi));
397 vkCmdBindPipeline(pcmd, VK_PIPELINE_BIND_POINT_COMPUTE, ppipe);
398 vkCmdPushConstants(pcmd, pl, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(ppc), ppc);
399 vkCmdDispatch(pcmd, 1, 1, 1);
400 VkMemoryBarrier pread{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
401 pread.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
402 pread.dstAccessMask = VK_ACCESS_HOST_READ_BIT;
403 vkCmdPipelineBarrier(pcmd, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0,
404 1, &pread, 0, nullptr, 0, nullptr);
405 CHECK(vkEndCommandBuffer(pcmd));
406 VkSubmitInfo psi{VK_STRUCTURE_TYPE_SUBMIT_INFO};
407 psi.commandBufferCount = 1; psi.pCommandBuffers = &pcmd;
408 CHECK(vkQueueSubmit(q, 1, &psi, VK_NULL_HANDLE));
409 CHECK(vkQueueWaitIdle(q));
410 // Width first, from what each invocation reports: every subgroup has N lanes (one may have the rest of a
411 // group that isn't a multiple of N), each lane once, and a ballot of the subgroup counts them all. A wrong
412 // width fails the test. Then the order: the translator takes a wave32 lane as LocalInvocationIndex % N, so
413 // invocation l must be lane l % N of subgroup l / N. Vulkan doesn't promise that mapping; where it differs,
414 // the size is reported as not available, as on a device that can't give N at all (the runners skip).
415 const uint32_t* pw = static_cast<const uint32_t*>(pmap);
416 const uint32_t subgroups = (local_total + req_sg - 1) / req_sg, tail = local_total % req_sg;
417 std::vector<uint32_t> count(subgroups, 0), seen(std::size_t(subgroups) * req_sg, 0);
418 std::vector<bool> bad(local_total, false);
419 for (uint32_t l = 0; l < local_total; l++) {
420 const uint32_t* w = pw + 4 * l;
421 if (w[0] == req_sg && w[2] < subgroups && w[1] < req_sg && !seen[std::size_t(w[2]) * req_sg + w[1]]++)
422 count[w[2]]++;
423 else
424 bad[l] = true;
425 }
426 uint32_t wrong = 0, first = 0, misplaced = 0, first_misplaced = 0, partial = 0;
427 for (uint32_t c : count)
428 if (c != req_sg) partial++;
429 for (uint32_t l = 0; l < local_total; l++) {
430 const uint32_t* w = pw + 4 * l;
431 if (bad[l] || w[3] != count[w[2]]) {
432 if (!wrong++) first = l;
433 }
434 if ((w[1] != l % req_sg || w[2] != l / req_sg) && !misplaced++) first_misplaced = l;
435 }
436 if (!wrong && partial > (tail ? 1u : 0u)) wrong = partial; // e.g. two half-filled subgroups
437 if (wrong) {
438 const uint32_t* w = pw + 4 * first;
439 std::printf("compute subgroup size: %u observed wrong in %u of %u invocations; invocation %u has "
440 "SubgroupSize %u, lane %u, subgroup %u, a ballot of %u lanes\n", req_sg, wrong, local_total,
441 first, w[0], w[1], w[2], w[3]);
442 return 1;
443 }
444 if (misplaced) {
445 const uint32_t* w = pw + 4 * first_misplaced;
446 std::fprintf(stderr, "%u-lane subgroups, but not in invocation order: invocation %u is lane %u of "
447 "subgroup %u\n", req_sg, first_misplaced, w[1], w[2]);
448 // As where the size can't be pinned at all: say so, run the test, and let the runner skip it.
449 std::printf("compute subgroup size: %u not available\n", req_sg);
450 } else {
451 std::printf("compute subgroup size: %u (observed: all %u invocations of a %ux%ux%u group%s)\n", req_sg,
452 local_total, local[0], local[1], local[2], observed_full ? ", full subgroups" : "");
453 }
454 }
314 VkCommandBufferBeginInfo cbi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; 455 VkCommandBufferBeginInfo cbi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO};
315 CHECK(vkBeginCommandBuffer(cmd, &cbi)); 456 CHECK(vkBeginCommandBuffer(cmd, &cbi));
316 vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pipe); 457 vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pipe);
@@ -432,7 +573,7 @@ int main(int argc, char** argv) {
432 } 573 }
433 } 574 }
434 if (!std::strcmp(argv[3], "bvh")) { 575 if (!std::strcmp(argv[3], "bvh")) {
435 const uint32_t want[8] = {0x48, 0x40, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xC1200000u, 0xBF800000u, 0xBE800000u, 0xBE800000u}; 576 const uint32_t want[8] = {0x68, 0x48, 0x40, 0xFFFFFFFFu, 0xC1200000u, 0xBF800000u, 0xBE800000u, 0xBE800000u};
436 for (int i = 0; i < 8; i++) if (out[i] != want[i]) { if (!bad) first_bad = i; bad++; } 577 for (int i = 0; i < 8; i++) if (out[i] != want[i]) { if (!bad) first_bad = i; bad++; }
437 std::printf("bvh out = %08x %08x %08x %08x | %08x %08x %08x %08x\n", out[0], out[1], out[2], out[3], out[4], out[5], out[6], out[7]); 578 std::printf("bvh out = %08x %08x %08x %08x | %08x %08x %08x %08x\n", out[0], out[1], out[2], out[3], out[4], out[5], out[6], out[7]);
438 } 579 }
diff --git a/runtime/test/vk_pipeline_check.cpp b/runtime/test/vk_pipeline_check.cpp
index 0312b48a4..a3e886d51 100644
--- a/runtime/test/vk_pipeline_check.cpp
+++ b/runtime/test/vk_pipeline_check.cpp
@@ -3,7 +3,8 @@
3// pipeline with the translator's resource contract (set 0: sampled images 0, 3, 5, 6; samplers 1; descriptor hash 3// pipeline with the translator's resource contract (set 0: sampled images 0, 3, 5, 6; samplers 1; descriptor hash
4// table 2; storage images 4, 7 and 8..19; set 1 binding 0 dynamic UBO for --pc-tail-ubo shaders; push constants 4// table 2; storage images 4, 7 and 8..19; set 1 binding 0 dynamic UBO for --pc-tail-ubo shaders; push constants
5// sized from push_constant_bytes, default 144 or 128 with pc_tail): 5// sized from push_constant_bytes, default 144 or 128 with pc_tail):
6// - cs: compute pipeline via vkCreateComputePipelines 6// - cs: compute pipeline via vkCreateComputePipelines, using the runtime layout and subgroup request for
7// descriptor-free shaders with the standard push-constant range
7// - ps/vs/ms/gs: graphics pipeline via vkCreateGraphicsPipelines (Vulkan 1.3 dynamic rendering, no render pass) 8// - ps/vs/ms/gs: graphics pipeline via vkCreateGraphicsPipelines (Vulkan 1.3 dynamic rendering, no render pass)
8// paired with minimal partner stubs from <spirv dir>/stubs/ (generated by tools/spirv_stubs.py) 9// paired with minimal partner stubs from <spirv dir>/stubs/ (generated by tools/spirv_stubs.py)
9// Only optional device extensions needed by the selected shaders (and supported by the GPU) are enabled. Shaders 10// Only optional device extensions needed by the selected shaders (and supported by the GPU) are enabled. Shaders
@@ -11,7 +12,11 @@
11// [cache.bin] loaded first if it exists (a stopped run resumes: cached pipelines are instant), saved every 12// [cache.bin] loaded first if it exists (a stopped run resumes: cached pipelines are instant), saved every
12// 10 minutes and at the end 13// 10 minutes and at the end
13// --jobs N compile on up to N worker threads (default: half the hardware threads) 14// --jobs N compile on up to N worker threads (default: half the hardware threads)
14// --large-module-bytes N compile modules larger than N bytes alone (default: 4194304; 0 disables isolation) 15// --large-module-bytes N modules larger than N bytes are "large" (default: 4194304; 0 disables the gate)
16// --large-parallel N how many large modules may be in the driver at once: 0 (default) = as many as fit 3/4 of
17// the memory available at start, at large_module_gate.h's estimate per module, up to --jobs, with the
18// small ones compiling alongside; 1 = each large module alone, the other threads waiting (the
19// behaviour before; also what 0 falls back to when the available memory can't be read)
15// --start I --count N check only index entries [I, I+N) (sorted by name) 20// --start I --count N check only index entries [I, I+N) (sorted by name)
16// --slow SEC print pipelines slower than SEC (default 30); compiles past 60 s are named while running 21// --slow SEC print pipelines slower than SEC (default 30); compiles past 60 s are named while running
17// --max-bytes N skip modules whose .spv is larger than N bytes (0 = no limit; names every skip) 22// --max-bytes N skip modules whose .spv is larger than N bytes (0 = no limit; names every skip)
@@ -30,8 +35,10 @@
30// --inflight-file F keep the modules that are in the driver in F, one "name<TAB>phase" line each (phase: module 35// --inflight-file F keep the modules that are in the driver in F, one "name<TAB>phase" line each (phase: module
31// while vkCreateShaderModule runs, pipeline while its pipeline is created), so whoever ran the check 36// while vkCreateShaderModule runs, pipeline while its pipeline is created), so whoever ran the check
32// can tell which module was there when the process died. F is rewritten when a module over 37// can tell which module was there when the process died. F is rewritten when a module over
33// --large-module-bytes enters or leaves the driver (it is alone then, so F names exactly it) and by 38// --large-module-bytes enters or leaves the driver (with --large-parallel 1 it is alone then, so F
34// the 5 s watchdog for the others, and emptied at the end. make_game.py's pipelines stage reads it. 39// names exactly it; otherwise F names every module in flight and make_game.py retries each alone)
40// and by the 5 s watchdog for the others, and emptied at the end. make_game.py's pipelines stage
41// reads it.
35// --skip-file F modules named in F (one per line) are not compiled: each is reported as MODULE CRASH and counted 42// --skip-file F modules named in F (one per line) are not compiled: each is reported as MODULE CRASH and counted
36// as a failed pipeline, as --isolate does for a module that killed the driver. make_game.py writes F 43// as a failed pipeline, as --isolate does for a module that killed the driver. make_game.py writes F
37// after a crash, so the next run checks everything else instead of dying on the same module. 44// after a crash, so the next run checks everything else instead of dying on the same module.
@@ -42,9 +49,12 @@
42#include "vk_device_pick.h" 49#include "vk_device_pick.h"
43#include "pipeline_cache_file.h" 50#include "pipeline_cache_file.h"
44#include "pipeline_cache_snapshot.h" 51#include "pipeline_cache_snapshot.h"
52#include "large_module_gate.h"
45#include "../src/spirv_words.h" 53#include "../src/spirv_words.h"
54#include "../src/subgroup_size.h"
46 55
47#include <algorithm> 56#include <algorithm>
57#include <array>
48#include <atomic> 58#include <atomic>
49#include <cctype> 59#include <cctype>
50#include <charconv> 60#include <charconv>
@@ -90,6 +100,10 @@ struct ShaderMeta {
90 uint32_t lds_bytes = 0; 100 uint32_t lds_bytes = 0;
91 uint32_t push_constant_bytes = 0; // 0 = absent in index (128 with pc_tail, else 144) 101 uint32_t push_constant_bytes = 0; // 0 = absent in index (128 with pc_tail, else 144)
92 uint32_t pc_tail_bytes = 0; // >0 = --pc-tail-ubo uniform block at set 1, binding 0 102 uint32_t pc_tail_bytes = 0; // >0 = --pc-tail-ubo uniform block at set 1, binding 0
103 bool no_set0_bindings = false;
104 bool wave64 = false;
105 std::array<uint32_t, 3> local_size{1, 1, 1};
106 std::string wave64_exchange;
93 bool writes_depth = false; 107 bool writes_depth = false;
94 bool needs_maintenance8 = false; 108 bool needs_maintenance8 = false;
95 std::vector<std::string> features; 109 std::vector<std::string> features;
@@ -222,6 +236,22 @@ struct JsonParser {
222 if (!error) fail("unterminated u32 array"); 236 if (!error) fail("unterminated u32 array");
223 return out; 237 return out;
224 } 238 }
239 void parse_local_size(std::array<uint32_t, 3>& out) {
240 if (!consume('[')) { skip_value(); return; }
241 for (size_t dim = 0; !error && i < s.size(); ++dim) {
242 if (consume(']')) return;
243 const char* start = s.data() + i;
244 skip_value();
245 if (dim < out.size()) {
246 char* end = nullptr;
247 const double size = std::strtod(start, &end);
248 out[dim] = end == s.data() + i && size >= 0 && size <= UINT32_MAX ? uint32_t(size) : 0;
249 }
250 if (consume(']')) return;
251 if (!consume(',')) { fail("expected ',' or ']' in local size"); return; }
252 }
253 if (!error) fail("unterminated local size");
254 }
225 std::vector<std::string> parse_str_array() { 255 std::vector<std::string> parse_str_array() {
226 std::vector<std::string> out; 256 std::vector<std::string> out;
227 if (!consume('[')) { skip_value(); return out; } 257 if (!consume('[')) { skip_value(); return out; }
@@ -318,6 +348,25 @@ struct JsonParser {
318 else if (k == "push_constant_bytes") 348 else if (k == "push_constant_bytes")
319 m.push_constant_bytes = parse_strict_u32("expected unsigned 32-bit push_constant_bytes"); 349 m.push_constant_bytes = parse_strict_u32("expected unsigned 32-bit push_constant_bytes");
320 else if (k == "pc_tail") m.pc_tail_bytes = parse_pc_tail_bytes(); 350 else if (k == "pc_tail") m.pc_tail_bytes = parse_pc_tail_bytes();
351 else if (k == "bindings") {
352 const size_t start = i;
353 m.no_set0_bindings = consume('[') && consume(']');
354 if (!m.no_set0_bindings) {
355 i = start;
356 skip_value();
357 }
358 }
359 else if (k == "wave64") {
360 ws();
361 if (s.compare(i, 4, "true") == 0 || s.compare(i, 5, "false") == 0) m.wave64 = parse_bool();
362 else skip_value();
363 }
364 else if (k == "wave64_exchange") {
365 ws();
366 if (i < s.size() && s[i] == '"') m.wave64_exchange = parse_string();
367 else skip_value();
368 }
369 else if (k == "local_size") parse_local_size(m.local_size);
321 else if (k == "writes_depth") m.writes_depth = parse_bool(); 370 else if (k == "writes_depth") m.writes_depth = parse_bool();
322 else if (k == "needs_maintenance8") m.needs_maintenance8 = parse_bool(); 371 else if (k == "needs_maintenance8") m.needs_maintenance8 = parse_bool();
323 else if (k == "features") m.features = parse_str_array(); 372 else if (k == "features") m.features = parse_str_array();
@@ -452,6 +501,13 @@ constexpr uint32_t required_push_bytes(uint32_t push_constant_bytes, uint32_t pc
452 return raw > (std::numeric_limits<uint32_t>::max() - 3u) ? raw : ((raw + 3u) & ~3u); 501 return raw > (std::numeric_limits<uint32_t>::max() - 3u) ? raw : ((raw + 3u) & ~3u);
453} 502}
454 503
504constexpr uint32_t runtime_compute_push_bytes = 144; // sizeof(leonida::ShaderUserData)
505
506bool uses_runtime_compute_layout(const ShaderMeta& meta) {
507 return meta.stage == "cs" && meta.no_set0_bindings && !meta.pc_tail_bytes &&
508 required_push_bytes(meta.push_constant_bytes, meta.pc_tail_bytes) == runtime_compute_push_bytes;
509}
510
455static_assert(required_push_bytes(0, 0) == 144); 511static_assert(required_push_bytes(0, 0) == 144);
456static_assert(required_push_bytes(0, 16) == 128); 512static_assert(required_push_bytes(0, 16) == 128);
457static_assert(required_push_bytes(128, 0) == 128); 513static_assert(required_push_bytes(128, 0) == 128);
@@ -588,7 +644,7 @@ int main(int argc, char** argv) {
588 if (argc < 2) { 644 if (argc < 2) {
589 std::fprintf(stderr, 645 std::fprintf(stderr,
590 "usage: vk_pipeline_check <spirv dir> [cache.bin] [--jobs N] [--start I] [--count N] [--slow SEC] " 646 "usage: vk_pipeline_check <spirv dir> [cache.bin] [--jobs N] [--start I] [--count N] [--slow SEC] "
591 "[--max-bytes N] [--large-module-bytes N] [--stage all|cs|graphics | --compute-only | --graphics-only] " 647 "[--max-bytes N] [--large-module-bytes N] [--large-parallel N] [--stage all|cs|graphics | --compute-only | --graphics-only] "
592 "[--stats FILE] [--cache-feedback] [--isolate [--isolate-batch N]] [--inflight-file F] " 648 "[--stats FILE] [--cache-feedback] [--isolate [--isolate-batch N]] [--inflight-file F] "
593 "[--skip-file F]\n"); 649 "[--skip-file F]\n");
594 return 2; 650 return 2;
@@ -599,6 +655,7 @@ int main(int argc, char** argv) {
599 uint32_t jobs = std::max(1u, std::thread::hardware_concurrency() / 2); 655 uint32_t jobs = std::max(1u, std::thread::hardware_concurrency() / 2);
600 size_t start = 0, count = 0, max_bytes = 0; 656 size_t start = 0, count = 0, max_bytes = 0;
601 size_t large_module_bytes = 4 * 1024 * 1024; 657 size_t large_module_bytes = 4 * 1024 * 1024;
658 unsigned large_parallel = 0; // 0 = by the memory budget
602 double slow = 30.0; 659 double slow = 30.0;
603 std::string stage_filter = "all"; 660 std::string stage_filter = "all";
604 bool cache_feedback = false, isolate = false, iso_child = false; 661 bool cache_feedback = false, isolate = false, iso_child = false;
@@ -640,6 +697,7 @@ int main(int argc, char** argv) {
640 else if (a == "--graphics-only") stage_filter = "graphics"; 697 else if (a == "--graphics-only") stage_filter = "graphics";
641 else if (a == "--max-bytes") valid = number(max_bytes); 698 else if (a == "--max-bytes") valid = number(max_bytes);
642 else if (a == "--large-module-bytes") valid = number(large_module_bytes); 699 else if (a == "--large-module-bytes") valid = number(large_module_bytes);
700 else if (a == "--large-parallel") valid = number(large_parallel);
643 else if (a == "--stats") valid = !(stats_path = value()).empty(); 701 else if (a == "--stats") valid = !(stats_path = value()).empty();
644 else if (a == "--inflight-file") valid = !(inflight_path = value()).empty(); 702 else if (a == "--inflight-file") valid = !(inflight_path = value()).empty();
645 else if (a == "--skip-file") valid = !(skip_path = value()).empty(); 703 else if (a == "--skip-file") valid = !(skip_path = value()).empty();
@@ -726,7 +784,8 @@ int main(int argc, char** argv) {
726 if (auto self = std::filesystem::read_symlink("/proc/self/exe", ec); !ec) exe = self.string(); 784 if (auto self = std::filesystem::read_symlink("/proc/self/exe", ec); !ec) exe = self.string();
727 std::vector<std::string> pass = {"--jobs", std::to_string(jobs), "--slow", std::to_string(slow), "--stage", stage_filter, 785 std::vector<std::string> pass = {"--jobs", std::to_string(jobs), "--slow", std::to_string(slow), "--stage", stage_filter,
728 "--max-bytes", std::to_string(max_bytes), 786 "--max-bytes", std::to_string(max_bytes),
729 "--large-module-bytes", std::to_string(large_module_bytes)}; 787 "--large-module-bytes", std::to_string(large_module_bytes),
788 "--large-parallel", std::to_string(large_parallel)};
730 if (cache_feedback) pass.push_back("--cache-feedback"); 789 if (cache_feedback) pass.push_back("--cache-feedback");
731 if (!skip_path.empty()) pass.insert(pass.end(), {"--skip-file", skip_path}); 790 if (!skip_path.empty()) pass.insert(pass.end(), {"--skip-file", skip_path});
732 struct Agg { uint32_t mod_ok = 0, mod_bad = 0, pipe_ok = 0, pipe_bad = 0, pipe_skip = 0, big = 0, crashed = 0, fb[3] = {}; }; 791 struct Agg { uint32_t mod_ok = 0, mod_bad = 0, pipe_ok = 0, pipe_bad = 0, pipe_skip = 0, big = 0, crashed = 0, fb[3] = {}; };
@@ -958,15 +1017,33 @@ int main(int argc, char** argv) {
958 dci.enabledExtensionCount = uint32_t(enable.size()); dci.ppEnabledExtensionNames = enable.data(); 1017 dci.enabledExtensionCount = uint32_t(enable.size()); dci.ppEnabledExtensionNames = enable.data();
959 VkDevice dev; 1018 VkDevice dev;
960 if (VkResult r = vkCreateDevice(pd, &dci, nullptr, &dev)) { std::fprintf(stderr, "vkCreateDevice %d\n", r); return 1; } 1019 if (VkResult r = vkCreateDevice(pd, &dci, nullptr, &dev)) { std::fprintf(stderr, "vkCreateDevice %d\n", r); return 1; }
1020 leonida::SubgroupSizeCaps runtime_subgroups;
1021 leonida::query_subgroup_size_caps(vkGetPhysicalDeviceProperties2, pd, f13.subgroupSizeControl,
1022 f13.computeFullSubgroups, runtime_subgroups);
961 auto can_require_sg = [&](uint32_t sg, VkShaderStageFlagBits bit) -> bool { 1023 auto can_require_sg = [&](uint32_t sg, VkShaderStageFlagBits bit) -> bool {
962 return f13.subgroupSizeControl && 1024 return f13.subgroupSizeControl &&
963 sg >= sgProps.minSubgroupSize && 1025 sg >= sgProps.minSubgroupSize &&
964 sg <= sgProps.maxSubgroupSize && 1026 sg <= sgProps.maxSubgroupSize &&
965 (sgProps.requiredSubgroupSizeStages & bit); 1027 (sgProps.requiredSubgroupSizeStages & bit);
966 }; 1028 };
1029 auto runtime_compute_subgroup = [&](const ShaderMeta& meta) {
1030 leonida::ShaderEntry entry;
1031 entry.stage = meta.stage;
1032 entry.subgroup_size = meta.subgroup_size;
1033 entry.wave64 = meta.wave64;
1034 entry.wave64_exchange = meta.wave64_exchange;
1035 entry.local_size = meta.local_size;
1036 return leonida::decide_subgroup_size(entry, runtime_subgroups);
1037 };
967 { 1038 {
968 std::map<uint32_t, std::set<std::string>> unforced_by_sg; 1039 std::map<uint32_t, std::set<std::string>> unforced_by_sg;
969 for (const auto& [_, meta] : work) { 1040 for (const auto& [_, meta] : work) {
1041 if (uses_runtime_compute_layout(*meta)) {
1042 const auto request = runtime_compute_subgroup(*meta);
1043 if (request.outcome == leonida::SubgroupOutcome::unavailable)
1044 unforced_by_sg[request.wanted].insert(meta->stage);
1045 continue;
1046 }
970 const VkShaderStageFlagBits bit = stage_bit(meta->stage); 1047 const VkShaderStageFlagBits bit = stage_bit(meta->stage);
971 if (bit && meta->subgroup_size > 0 && !can_require_sg(meta->subgroup_size, bit)) { 1048 if (bit && meta->subgroup_size > 0 && !can_require_sg(meta->subgroup_size, bit)) {
972 unforced_by_sg[meta->subgroup_size].insert(meta->stage); 1049 unforced_by_sg[meta->subgroup_size].insert(meta->stage);
@@ -1097,6 +1174,20 @@ int main(int argc, char** argv) {
1097 const uint32_t need_pc = required_push_bytes(meta.push_constant_bytes, meta.pc_tail_bytes); 1174 const uint32_t need_pc = required_push_bytes(meta.push_constant_bytes, meta.pc_tail_bytes);
1098 return layouts.at({need_pc, meta.pc_tail_bytes != 0}); 1175 return layouts.at({need_pc, meta.pc_tail_bytes != 0});
1099 }; 1176 };
1177 VkPipelineLayout runtime_compute_layout = VK_NULL_HANDLE;
1178 if (runtime_compute_push_bytes <= props.limits.maxPushConstantsSize &&
1179 std::any_of(work.begin(), work.end(), [](const Item& item) {
1180 return uses_runtime_compute_layout(*item.second);
1181 })) {
1182 const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, runtime_compute_push_bytes};
1183 VkPipelineLayoutCreateInfo info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO};
1184 info.pushConstantRangeCount = 1;
1185 info.pPushConstantRanges = &push;
1186 if (VkResult r = vkCreatePipelineLayout(dev, &info, nullptr, &runtime_compute_layout)) {
1187 std::fprintf(stderr, "runtime compute pipeline layout %d\n", r);
1188 return 1;
1189 }
1190 }
1100 VkPipelineCacheCreateInfo pci{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO}; 1191 VkPipelineCacheCreateInfo pci{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO};
1101 std::vector<char> seed; 1192 std::vector<char> seed;
1102 if (!cache_path.empty()) { // resume: pipelines already in the cache compile instantly 1193 if (!cache_path.empty()) { // resume: pipelines already in the cache compile instantly
@@ -1136,8 +1227,26 @@ int main(int argc, char** argv) {
1136 work.size(), lo, hi, stage_filter.c_str(), worker_count); 1227 work.size(), lo, hi, stage_filter.c_str(), worker_count);
1137 1228
1138 std::mutex mu; // guards counters, stdout, stub cache and in-flight table 1229 std::mutex mu; // guards counters, stdout, stub cache and in-flight table
1139 std::shared_mutex compile_gate; // large modules exclude other shader and pipeline work 1230 std::shared_mutex compile_gate; // --large-parallel 1: large modules exclude other shader and pipeline work
1140 size_t isolated_modules = 0; 1231 size_t isolated_modules = 0;
1232 // Otherwise large modules share a memory budget and the small ones are never held back (large_module_gate.h).
1233 const uint64_t available_memory = leonida::available_memory_bytes();
1234 const bool large_exclusive = large_parallel == 1 || (large_parallel == 0 && available_memory == 0);
1235 leonida::LargeModuleGate large_gate(
1236 large_parallel == 0 ? available_memory / 4 * 3 : UINT64_MAX,
1237 large_parallel == 0 ? jobs : std::min<unsigned>(large_parallel, jobs));
1238 if (large_module_bytes) {
1239 if (large_exclusive)
1240 std::fprintf(stderr, "large modules (over %zu bytes): one at a time, the other threads waiting\n",
1241 large_module_bytes);
1242 else if (large_parallel == 0)
1243 std::fprintf(stderr, "large modules (over %zu bytes): up to %u at once within %.1f GB "
1244 "(3/4 of the %.1f GB available)\n", large_module_bytes, large_gate.max_inflight(),
1245 large_gate.budget() / 1e9, available_memory / 1e9);
1246 else
1247 std::fprintf(stderr, "large modules (over %zu bytes): up to %u at once\n", large_module_bytes,
1248 large_gate.max_inflight());
1249 }
1141 std::map<std::string, uint32_t> modules_ok, modules_bad, big_skipped; 1250 std::map<std::string, uint32_t> modules_ok, modules_bad, big_skipped;
1142 std::map<std::string, StageStats> stats; 1251 std::map<std::string, StageStats> stats;
1143 std::map<std::string, VkShaderModule> stub_cache; 1252 std::map<std::string, VkShaderModule> stub_cache;
@@ -1234,7 +1343,7 @@ int main(int argc, char** argv) {
1234 VkResult r, double sec, VkPipelineCreationFeedbackFlags fb_flags) { 1343 VkResult r, double sec, VkPipelineCreationFeedbackFlags fb_flags) {
1235 std::lock_guard<std::mutex> g(mu); 1344 std::lock_guard<std::mutex> g(mu);
1236 inflight.erase(std::this_thread::get_id()); 1345 inflight.erase(std::this_thread::get_id());
1237 if (inflight.empty()) write_inflight(); // a large module just finished (it compiles alone) 1346 if (inflight.empty()) write_inflight(); // a large module just finished (alone with --large-parallel 1)
1238 auto& st = stats[stage]; 1347 auto& st = stats[stage];
1239 st.seconds += sec; 1348 st.seconds += sec;
1240 if (sec > st.max_sec) { st.max_sec = sec; st.max_name = name; } 1349 if (sec > st.max_sec) { st.max_sec = sec; st.max_name = name; }
@@ -1310,12 +1419,18 @@ int main(int argc, char** argv) {
1310 const bool isolated = large_module_bytes && std::cmp_greater(file_size, large_module_bytes); 1419 const bool isolated = large_module_bytes && std::cmp_greater(file_size, large_module_bytes);
1311 std::unique_lock exclusive(compile_gate, std::defer_lock); 1420 std::unique_lock exclusive(compile_gate, std::defer_lock);
1312 std::shared_lock parallel(compile_gate, std::defer_lock); 1421 std::shared_lock parallel(compile_gate, std::defer_lock);
1313 if (isolated) exclusive.lock(); 1422 leonida::LargeModuleGate::Ticket large_ticket; // left after the module and its pipeline are gone
1314 else if (large_module_bytes) parallel.lock(); 1423 if (large_exclusive) {
1424 if (isolated) exclusive.lock();
1425 else if (large_module_bytes) parallel.lock();
1426 } else if (isolated) {
1427 large_ticket = leonida::LargeModuleGate::Ticket(large_gate,
1428 leonida::large_module_estimate(file_size));
1429 }
1315 { // in flight from here: vkCreateShaderModule can also take long or die in the driver 1430 { // in flight from here: vkCreateShaderModule can also take long or die in the driver
1316 std::lock_guard<std::mutex> g(mu); 1431 std::lock_guard<std::mutex> g(mu);
1317 inflight[std::this_thread::get_id()] = {name, std::chrono::steady_clock::now(), "module"}; 1432 inflight[std::this_thread::get_id()] = {name, std::chrono::steady_clock::now(), "module"};
1318 if (isolated) write_inflight(); // alone in flight: the file names exactly this module 1433 if (isolated) write_inflight(); // a large module: name it now (alone with --large-parallel 1)
1319 } 1434 }
1320 1435
1321 const auto code = leonida::read_spirv_words(f, file_size); 1436 const auto code = leonida::read_spirv_words(f, file_size);
@@ -1338,15 +1453,23 @@ int main(int argc, char** argv) {
1338 if (!miss.empty()) { 1453 if (!miss.empty()) {
1339 record_skip(name, stage, miss); 1454 record_skip(name, stage, miss);
1340 } else { 1455 } else {
1341 VkPipelineShaderStageRequiredSubgroupSizeCreateInfo reqSg{ 1456 VkPipelineShaderStageRequiredSubgroupSizeCreateInfo reqSg{};
1342 VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO};
1343 reqSg.requiredSubgroupSize = meta.subgroup_size;
1344 VkComputePipelineCreateInfo cpi{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; 1457 VkComputePipelineCreateInfo cpi{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO};
1345 cpi.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; 1458 cpi.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO};
1346 cpi.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; cpi.stage.module = sm; cpi.stage.pName = "main"; 1459 cpi.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; cpi.stage.module = sm; cpi.stage.pName = "main";
1347 const bool sg_forced = can_require_sg(meta.subgroup_size, VK_SHADER_STAGE_COMPUTE_BIT); 1460 bool sg_forced = false;
1348 if (sg_forced) cpi.stage.pNext = &reqSg; 1461 if (uses_runtime_compute_layout(meta)) {
1349 cpi.layout = layout_for(meta); 1462 const auto request = runtime_compute_subgroup(meta);
1463 leonida::apply_subgroup_request(request, reqSg, cpi.stage);
1464 sg_forced = request.size != 0;
1465 cpi.layout = runtime_compute_layout;
1466 } else {
1467 reqSg.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO;
1468 reqSg.requiredSubgroupSize = meta.subgroup_size;
1469 sg_forced = can_require_sg(meta.subgroup_size, VK_SHADER_STAGE_COMPUTE_BIT);
1470 if (sg_forced) cpi.stage.pNext = &reqSg;
1471 cpi.layout = layout_for(meta);
1472 }
1350 cpi.flags = capture; 1473 cpi.flags = capture;
1351 // Only whole-pipeline feedback is reported. 1474 // Only whole-pipeline feedback is reported.
1352 VkPipelineCreationFeedback fb{}; 1475 VkPipelineCreationFeedback fb{};
@@ -1357,7 +1480,7 @@ int main(int argc, char** argv) {
1357 { 1480 {
1358 std::lock_guard<std::mutex> g(mu); 1481 std::lock_guard<std::mutex> g(mu);
1359 inflight[std::this_thread::get_id()] = {name, t0, "pipeline"}; 1482 inflight[std::this_thread::get_id()] = {name, t0, "pipeline"};
1360 if (isolated) write_inflight(); // alone in flight: the file names exactly this module 1483 if (isolated) write_inflight(); // a large module: name it now (alone with --large-parallel 1)
1361 } 1484 }
1362 VkPipeline p = VK_NULL_HANDLE; 1485 VkPipeline p = VK_NULL_HANDLE;
1363 maybe_simulate_crash(name); 1486 maybe_simulate_crash(name);
@@ -1531,7 +1654,7 @@ int main(int argc, char** argv) {
1531 { 1654 {
1532 std::lock_guard<std::mutex> g(mu); 1655 std::lock_guard<std::mutex> g(mu);
1533 inflight[std::this_thread::get_id()] = {name, t0, "pipeline"}; 1656 inflight[std::this_thread::get_id()] = {name, t0, "pipeline"};
1534 if (isolated) write_inflight(); // alone in flight: the file names exactly this module 1657 if (isolated) write_inflight(); // a large module: name it now (alone with --large-parallel 1)
1535 } 1658 }
1536 VkPipeline p = VK_NULL_HANDLE; 1659 VkPipeline p = VK_NULL_HANDLE;
1537 maybe_simulate_crash(name); 1660 maybe_simulate_crash(name);
@@ -1658,7 +1781,8 @@ int main(int argc, char** argv) {
1658 std::printf("; checked %zu of %zu\n", work.size() - big_total, work.size()); 1781 std::printf("; checked %zu of %zu\n", work.size() - big_total, work.size());
1659 } 1782 }
1660 if (isolated_modules) 1783 if (isolated_modules)
1661 std::printf("large modules checked exclusively: %zu (over %zu bytes)\n", isolated_modules, 1784 std::printf("large modules checked %s: %zu (over %zu bytes)\n",
1785 large_exclusive ? "exclusively" : "within the memory budget", isolated_modules,
1662 large_module_bytes); 1786 large_module_bytes);
1663 std::printf("wall time: %.1fs on %u threads\n", elapsed(), worker_count); 1787 std::printf("wall time: %.1fs on %u threads\n", elapsed(), worker_count);
1664 const bool cache_saved = save_cache(true); // keep successful pipelines even if another entry failed 1788 const bool cache_saved = save_cache(true); // keep successful pipelines even if another entry failed
diff --git a/runtime/test/vk_presenter_sync_test.cpp b/runtime/test/vk_presenter_sync_test.cpp
index c26703ef5..3834c5c08 100644
--- a/runtime/test/vk_presenter_sync_test.cpp
+++ b/runtime/test/vk_presenter_sync_test.cpp
@@ -6,6 +6,7 @@
6// A failed capture fence wait also leaves the caller's outputs untouched. 6// A failed capture fence wait also leaves the caller's outputs untouched.
7// 3. Concurrent present() + VulkanQueue::execute() + add_resource()/remove_resource() follows VulkanContext's 7// 3. Concurrent present() + VulkanQueue::execute() + add_resource()/remove_resource() follows VulkanContext's
8// resource_mutex_ -> tracker_mutex_ -> submit_mutex_ lock hierarchy without data races or deadlocks. 8// resource_mutex_ -> tracker_mutex_ -> submit_mutex_ lock hierarchy without data races or deadlocks.
9// 4. A swapchain-destroy WSI layer which calls vkDeviceWaitIdle cannot overlap vkQueueSubmit on another thread.
9// Skips with exit code 77 when no Vulkan 1.3 device with Win32 presentation is available. No game data. 10// Skips with exit code 77 when no Vulkan 1.3 device with Win32 presentation is available. No game data.
10#ifndef WIN32_LEAN_AND_MEAN 11#ifndef WIN32_LEAN_AND_MEAN
11#define WIN32_LEAN_AND_MEAN 12#define WIN32_LEAN_AND_MEAN
@@ -58,6 +59,8 @@ PFN_vkQueuePresentKHR real_present = nullptr;
58PFN_vkWaitForFences real_wait = nullptr; 59PFN_vkWaitForFences real_wait = nullptr;
59PFN_vkCmdPipelineBarrier real_barrier = nullptr; 60PFN_vkCmdPipelineBarrier real_barrier = nullptr;
60PFN_vkCmdCopyImageToBuffer real_copy_i2b = nullptr; 61PFN_vkCmdCopyImageToBuffer real_copy_i2b = nullptr;
62PFN_vkDestroySwapchainKHR real_destroy_swapchain = nullptr;
63PFN_vkDeviceWaitIdle real_device_wait_idle = nullptr;
61 64
62std::atomic<VkResult> fail_next_submit{VK_SUCCESS}; 65std::atomic<VkResult> fail_next_submit{VK_SUCCESS};
63std::atomic<VkResult> fail_next_wait{VK_SUCCESS}; 66std::atomic<VkResult> fail_next_wait{VK_SUCCESS};
@@ -66,9 +69,36 @@ std::atomic<bool> observe_capture{false};
66std::atomic<bool> saw_capture_waw{false}; 69std::atomic<bool> saw_capture_waw{false};
67std::atomic<std::uint32_t> capture_copies{0}; 70std::atomic<std::uint32_t> capture_copies{0};
68std::atomic<std::uint32_t> capture_waw_barriers{0}; 71std::atomic<std::uint32_t> capture_waw_barriers{0};
72std::atomic<bool> check_swapchain_destroy{false};
73std::atomic<bool> destroy_entered{false};
74std::atomic<bool> submit_entered{false};
75std::atomic<bool> overlap_detected{false};
76std::atomic<bool> unexpected_submit_error{false};
77std::mutex destroy_mutex;
78std::condition_variable destroy_cv;
79bool allow_destroy_finish = false;
80
81// Synthetic WSI layer: a destroy hook initiates vkDeviceWaitIdle, as a capture layer may do internally.
82// Holding the hook behind a condition variable makes the concurrency window deterministic rather than dependent
83// on the installed capture software or validation logging overhead. Only the test hook waits on this condition.
84VKAPI_ATTR void VKAPI_CALL destroy_swapchain(VkDevice device, VkSwapchainKHR swapchain,
85 const VkAllocationCallbacks* alloc) {
86 if (check_swapchain_destroy.load(std::memory_order_relaxed)) {
87 destroy_entered.store(true, std::memory_order_release);
88 destroy_cv.notify_all();
89 {
90 std::unique_lock lock(destroy_mutex);
91 destroy_cv.wait(lock, [] { return allow_destroy_finish; });
92 }
93 overlap_detected.store(submit_entered.load(std::memory_order_acquire), std::memory_order_release);
94 if (real_device_wait_idle(device) != VK_SUCCESS) unexpected_submit_error.store(true);
95 }
96 real_destroy_swapchain(device, swapchain, alloc);
97}
69 98
70VKAPI_ATTR VkResult VKAPI_CALL queue_submit(VkQueue queue, std::uint32_t count, const VkSubmitInfo* submits, 99VKAPI_ATTR VkResult VKAPI_CALL queue_submit(VkQueue queue, std::uint32_t count, const VkSubmitInfo* submits,
71 VkFence fence) { 100 VkFence fence) {
101 submit_entered.store(true, std::memory_order_release);
72 const VkResult armed = fail_next_submit.exchange(VK_SUCCESS); 102 const VkResult armed = fail_next_submit.exchange(VK_SUCCESS);
73 if (armed != VK_SUCCESS) return armed; 103 if (armed != VK_SUCCESS) return armed;
74 return real_submit(queue, count, submits, fence); 104 return real_submit(queue, count, submits, fence);
@@ -124,6 +154,7 @@ VKAPI_ATTR void VKAPI_CALL cmd_copy_image_to_buffer(VkCommandBuffer cb, VkImage
124 154
125VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_device(VkDevice device, const char* name) { 155VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_device(VkDevice device, const char* name) {
126 const std::string_view n = name; 156 const std::string_view n = name;
157 if (n == "vkDestroySwapchainKHR") return reinterpret_cast<PFN_vkVoidFunction>(destroy_swapchain);
127 if (n == "vkQueueSubmit") return reinterpret_cast<PFN_vkVoidFunction>(queue_submit); 158 if (n == "vkQueueSubmit") return reinterpret_cast<PFN_vkVoidFunction>(queue_submit);
128 if (n == "vkQueuePresentKHR") return reinterpret_cast<PFN_vkVoidFunction>(queue_present); 159 if (n == "vkQueuePresentKHR") return reinterpret_cast<PFN_vkVoidFunction>(queue_present);
129 if (n == "vkWaitForFences") return reinterpret_cast<PFN_vkVoidFunction>(wait_for_fences); 160 if (n == "vkWaitForFences") return reinterpret_cast<PFN_vkVoidFunction>(wait_for_fences);
@@ -140,6 +171,8 @@ VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_instance(VkInstance instance, const
140void install(PFN_vkGetInstanceProcAddr instance_proc, VkInstance instance, VkDevice device) { 171void install(PFN_vkGetInstanceProcAddr instance_proc, VkInstance instance, VkDevice device) {
141 real_get_instance = instance_proc; 172 real_get_instance = instance_proc;
142 real_get_device = reinterpret_cast<PFN_vkGetDeviceProcAddr>(instance_proc(instance, "vkGetDeviceProcAddr")); 173 real_get_device = reinterpret_cast<PFN_vkGetDeviceProcAddr>(instance_proc(instance, "vkGetDeviceProcAddr"));
174 real_destroy_swapchain = reinterpret_cast<PFN_vkDestroySwapchainKHR>(real_get_device(device, "vkDestroySwapchainKHR"));
175 real_device_wait_idle = reinterpret_cast<PFN_vkDeviceWaitIdle>(real_get_device(device, "vkDeviceWaitIdle"));
143 real_submit = reinterpret_cast<PFN_vkQueueSubmit>(real_get_device(device, "vkQueueSubmit")); 176 real_submit = reinterpret_cast<PFN_vkQueueSubmit>(real_get_device(device, "vkQueueSubmit"));
144 real_present = reinterpret_cast<PFN_vkQueuePresentKHR>(real_get_device(device, "vkQueuePresentKHR")); 177 real_present = reinterpret_cast<PFN_vkQueuePresentKHR>(real_get_device(device, "vkQueuePresentKHR"));
145 real_wait = reinterpret_cast<PFN_vkWaitForFences>(real_get_device(device, "vkWaitForFences")); 178 real_wait = reinterpret_cast<PFN_vkWaitForFences>(real_get_device(device, "vkWaitForFences"));
@@ -350,6 +383,59 @@ int main() {
350 EXPECT(!worker_failed.load()); 383 EXPECT(!worker_failed.load());
351 EXPECT(queue.idle() && worker_queue.idle()); 384 EXPECT(queue.idle() && worker_queue.idle());
352 std::printf("presenter sync: concurrent present + queue.execute + tracker mutations ok\n"); 385 std::printf("presenter sync: concurrent present + queue.execute + tracker mutations ok\n");
386
387 // 4. Emulate a WSI capture layer that performs device-idle inside vkDestroySwapchainKHR.
388 // The presenter first enters the destroy hook; a second thread then attempts a real queue submission.
389 // Once the hook is released, that submission must not have entered the Vulkan driver while the hook ran.
390 driver::destroy_entered.store(false);
391 driver::submit_entered.store(false);
392 driver::overlap_detected.store(false);
393 driver::unexpected_submit_error.store(false);
394 {
395 std::lock_guard lock(driver::destroy_mutex);
396 driver::allow_destroy_finish = false;
397 }
398 driver::check_swapchain_destroy.store(true);
399 VkResult recreated = VK_ERROR_UNKNOWN;
400 std::thread destroy_thread([&] { recreated = presenter.present(1, true); });
401 bool entered = false;
402 {
403 std::unique_lock lock(driver::destroy_mutex);
404 entered = driver::destroy_cv.wait_for(lock, std::chrono::seconds(5),
405 [] { return driver::destroy_entered.load(); });
406 }
407 std::atomic<bool> submit_started{false};
408 ReplayResult submit_result = ReplayResult::unsupported;
409 std::thread submit_thread;
410 if (entered) {
411 submit_thread = std::thread([&] {
412 submit_started.store(true);
413 CommandList list;
414 if (!list.clear_render_target({1, 0, 0, 1}, {0.3f, 0.2f, 0.1f, 1.0f}) || !list.close()) return;
415 const CommandList* ptr = &list;
416 submit_result = worker_queue.execute({&ptr, 1});
417 });
418 for (int attempt = 0; attempt < 100 && !submit_started.load(); ++attempt)
419 std::this_thread::sleep_for(std::chrono::milliseconds(1));
420 // Give the competing thread time to reach the submit point if no mutex is protecting destruction.
421 std::this_thread::sleep_for(std::chrono::milliseconds(50));
422 }
423 {
424 std::lock_guard lock(driver::destroy_mutex);
425 driver::allow_destroy_finish = true;
426 }
427 driver::destroy_cv.notify_all();
428 destroy_thread.join();
429 if (submit_thread.joinable()) submit_thread.join();
430 driver::check_swapchain_destroy.store(false);
431 EXPECT(entered);
432 EXPECT(recreated == VK_SUCCESS);
433 EXPECT(submit_started.load());
434 EXPECT(submit_result == ReplayResult::success);
435 EXPECT(!driver::overlap_detected.load());
436 EXPECT(!driver::unexpected_submit_error.load());
437 EXPECT(queue.idle() && worker_queue.idle());
438 std::printf("presenter sync: synthetic WSI device-idle during swapchain destruction serialized ok\n");
353 } 439 }
354 440
355 DestroyWindow(window); 441 DestroyWindow(window);
diff --git a/runtime/test/vk_queue_test.cpp b/runtime/test/vk_queue_test.cpp
index 84289198c..9df720356 100644
--- a/runtime/test/vk_queue_test.cpp
+++ b/runtime/test/vk_queue_test.cpp
@@ -61,7 +61,33 @@ int check_picker() {
61 const auto q = pick_queue_families(f, 0); 61 const auto q = pick_queue_families(f, 0);
62 EXPECT(q.copy == 2); 62 EXPECT(q.copy == 2);
63 } 63 }
64 std::printf("queue family picker: 4 layouts ok\n"); 64 // D3D12 tile mapping is legal on all queue kinds. Dedicated async queues that cannot
65 // bind sparse pages must use the graphics family when sparse buffers are offered.
66 {
67 constexpr VkQueueFlags S = VK_QUEUE_SPARSE_BINDING_BIT;
68 const std::array f{fam(G | S), fam(T), fam(C)};
69 const auto preferred = pick_queue_families(f, 0);
70 EXPECT(preferred.compute == 2 && preferred.copy == 1);
71 const auto corrected = sparse_capable_queue_families(f, preferred, true);
72 EXPECT(corrected.direct == 0 && corrected.compute == 0 && corrected.copy == 0);
73 const auto no_sparse = sparse_capable_queue_families(f, preferred, false);
74 EXPECT(no_sparse.compute == 2 && no_sparse.copy == 1);
75 }
76 {
77 constexpr VkQueueFlags S = VK_QUEUE_SPARSE_BINDING_BIT;
78 const std::array f{fam(G | S), fam(T | S), fam(C | S)};
79 const auto preferred = pick_queue_families(f, 0);
80 const auto corrected = sparse_capable_queue_families(f, preferred, true);
81 EXPECT(corrected.compute == 2 && corrected.copy == 1); // preserve dedicated queues
82 }
83 {
84 constexpr VkQueueFlags S = VK_QUEUE_SPARSE_BINDING_BIT;
85 const std::array f{fam(G | S), fam(T), fam(C | S)};
86 const auto preferred = pick_queue_families(f, 0);
87 const auto corrected = sparse_capable_queue_families(f, preferred, true);
88 EXPECT(corrected.compute == 2 && corrected.copy == 0); // mixed capabilities
89 }
90 std::printf("queue family picker: 7 layouts ok\n");
65 return 0; 91 return 0;
66} 92}
67 93
diff --git a/runtime/test/vk_sandbox.cpp b/runtime/test/vk_sandbox.cpp
new file mode 100644
index 000000000..b5de7bd13
--- /dev/null
+++ b/runtime/test/vk_sandbox.cpp
@@ -0,0 +1,734 @@
1// Real-shader sandbox: draws a tools/sandbox_scene.py scene through two translated game shaders.
2//
3// vk_sandbox <scene.bin> <vs.spv> <ps.spv> --out <image.ppm> [--size W H] [--cam x y z yaw pitch] [--fov deg]
4// vk_sandbox <scene.bin> <vs.spv> <ps.spv> --window [--size W H] [--cam ...] [--mode fly|walk|drive] (Windows only)
5// --window --frames N --out <image.ppm>: test run, the window shows without activation and quits after N frames
6//
7// The pair (chosen by tools/sandbox.py) is a transform VS with POSITION/NORMAL/TEXCOORD inputs and a textured PS, both reading user SGPR 8:
8// a 32-bit pointer (high dword forced to 0) to one table of descriptors in the heap, laid out as the shaders load it:
9// +0x00 V# of the object constants: world rows 0..2 at 0x00/0x10/0x20, translation at 0x30
10// +0x20 T# of the albedo texture (8 dwords)
11// +0x40 V# of the view constants: light direction at 0xa0, view-projection rows at 0x160 (row-vector convention)
12// +0x60 V# of the colour constants: rgba at 0x00
13// Every draw gets its own table and object constants; view and colour constants are shared. The PS samples with the
14// S# literal in its own code, so the sampler is built from those words (gfx10::decode). Nothing here is game data:
15// the scene file and the shaders come from the user's work folder.
16//
17// Window keys (only while the window has focus): WASD move, mouse with the right button held looks, Q/E down/up,
18// Shift faster, 1 fly, 2 walk (eye 1.7 m over the ground under the camera), 3 drive (eye 1.2 m, accelerates),
19// P writes sandbox_shot.ppm, Esc quits.
20#define VK_NO_PROTOTYPES
21#ifdef _WIN32
22#define VK_USE_PLATFORM_WIN32_KHR
23#include <windows.h>
24#endif
25#include "vulkan_loader.h"
26#include "vk_device_pick.h"
27
28#include <algorithm>
29#include <array>
30#include <chrono>
31#include <cmath>
32#include <cstdio>
33#include <cstdlib>
34#include <cstring>
35#include <fstream>
36#include <string>
37#include <unordered_map>
38#include <vector>
39
40#include "../src/descriptor_table.h"
41#include "../src/gfx10_descriptors.h"
42
43static PFN_vkGetInstanceProcAddr gipa;
44#define CHECK(x) \
45 do { \
46 VkResult r_ = (x); \
47 if (r_ != VK_SUCCESS) { \
48 std::fprintf(stderr, "FAILED %s -> %d (line %d)\n", #x, r_, __LINE__); \
49 return 1; \
50 } \
51 } while (0)
52
53namespace {
54
55struct Texture { uint32_t w, h; std::vector<uint8_t> rgba; };
56struct Mesh { uint32_t first_vertex, vertex_count, first_index, index_count; };
57struct Draw { uint32_t mesh; int32_t texture; float rows[4][3]; };
58struct Scene {
59 std::vector<Texture> textures;
60 std::vector<Mesh> meshes;
61 std::vector<Draw> draws;
62 std::vector<float> vertices; // 8 floats each
63 std::vector<uint32_t> indices;
64 float center[3];
65};
66
67bool load_scene(const char* path, Scene& s) {
68 std::ifstream f(path, std::ios::binary | std::ios::ate);
69 const uint64_t file_size = f ? uint64_t(f.tellg()) : 0;
70 f.seekg(0);
71 char magic[4];
72 uint32_t hdr[4];
73 if (!f.read(magic, 4) || std::memcmp(magic, "LSB1", 4) || !f.read(reinterpret_cast<char*>(hdr), 16) ||
74 hdr[0] != 1 || !f.read(reinterpret_cast<char*>(s.center), 12))
75 return false;
76 for (uint32_t i = 0; i < hdr[1]; ++i) {
77 Texture t;
78 f.read(reinterpret_cast<char*>(&t.w), 4).read(reinterpret_cast<char*>(&t.h), 4);
79 if (!f || !t.w || !t.h || t.w > 16384 || t.h > 16384 || uint64_t(t.w) * t.h * 4 > file_size) return false;
80 t.rgba.resize(size_t(t.w) * t.h * 4);
81 f.read(reinterpret_cast<char*>(t.rgba.data()), std::streamsize(t.rgba.size()));
82 s.textures.push_back(std::move(t));
83 }
84 for (uint32_t i = 0; i < hdr[2]; ++i) {
85 uint32_t vc = 0, ic = 0;
86 f.read(reinterpret_cast<char*>(&vc), 4).read(reinterpret_cast<char*>(&ic), 4);
87 if (!f || uint64_t(vc) * 32 + uint64_t(ic) * 4 > file_size) return false;
88 Mesh m{uint32_t(s.vertices.size() / 8), vc, uint32_t(s.indices.size()), ic};
89 s.vertices.resize(s.vertices.size() + size_t(vc) * 8);
90 s.indices.resize(s.indices.size() + ic);
91 f.read(reinterpret_cast<char*>(s.vertices.data() + size_t(m.first_vertex) * 8), std::streamsize(vc) * 32);
92 f.read(reinterpret_cast<char*>(s.indices.data() + m.first_index), std::streamsize(ic) * 4);
93 if (!f) return false;
94 for (uint32_t k = 0; k < ic; ++k)
95 if (s.indices[m.first_index + k] >= vc) return false;
96 s.meshes.push_back(m);
97 }
98 for (uint32_t i = 0; i < hdr[3]; ++i) {
99 Draw d;
100 f.read(reinterpret_cast<char*>(&d), sizeof(d));
101 if (!f || d.mesh >= s.meshes.size() || d.texture >= int32_t(s.textures.size())) return false;
102 s.draws.push_back(d);
103 }
104 return bool(f);
105}
106
107std::vector<uint32_t> read_spv(const char* p) {
108 std::ifstream f(p, std::ios::binary);
109 std::vector<char> b((std::istreambuf_iterator<char>(f)), {});
110 std::vector<uint32_t> w(b.size() / 4);
111 std::memcpy(w.data(), b.data(), w.size() * 4);
112 return w;
113}
114
115struct Camera {
116 float pos[3], yaw = 0, pitch = 0, fov = 70, speed = 0;
117 int mode = 0; // 0 fly, 1 walk, 2 drive
118 void forward(float f[3]) const {
119 f[0] = std::cos(pitch) * std::cos(yaw); f[1] = std::cos(pitch) * std::sin(yaw); f[2] = std::sin(pitch);
120 }
121};
122
123// clip = wx*row0 + wy*row1 + wz*row2 + row3 (D3D clip space: y up, z 0..1), stored as 16 floats.
124void view_projection(const Camera& c, float aspect, float out[16]) {
125 float f[3]; c.forward(f);
126 float r[3] = {f[1], -f[0], 0};
127 const float rl = std::sqrt(r[0] * r[0] + r[1] * r[1]);
128 if (rl < 1e-6f) { r[0] = std::sin(c.yaw); r[1] = -std::cos(c.yaw); } else { r[0] /= rl; r[1] /= rl; }
129 const float u[3] = {r[1] * f[2] - r[2] * f[1], r[2] * f[0] - r[0] * f[2], r[0] * f[1] - r[1] * f[0]};
130 const float n = 0.1f, fa = 5000.f, sy = 1.f / std::tan(c.fov * 3.14159265f / 360.f), sx = sy / aspect;
131 const float A = fa / (fa - n), B = -n * fa / (fa - n);
132 // view = (dot(w - p, r), dot(w - p, u), dot(w - p, f)); clip = (vx*sx, vy*sy, vz*A + B, vz)
133 const float* axes[3] = {r, u, f};
134 const float scale[4] = {sx, sy, A, 1};
135 for (int k = 0; k < 4; ++k) {
136 const float* a = axes[k < 3 ? k : 2];
137 for (int j = 0; j < 3; ++j) out[j * 4 + k] = a[j] * scale[k];
138 out[12 + k] = -(a[0] * c.pos[0] + a[1] * c.pos[1] + a[2] * c.pos[2]) * scale[k] + (k == 2 ? B : 0);
139 }
140}
141
142// Ground under a point: highest scene triangle below z + 1 at (x, y), from a 4 m grid built once.
143struct Ground {
144 float cell = 4, x0 = 0, y0 = 0;
145 int nx = 0, ny = 0;
146 std::vector<std::vector<float>> tris; // per cell: 9 floats a triangle
147 void build(const Scene& s) {
148 float lo[2] = {1e30f, 1e30f}, hi[2] = {-1e30f, -1e30f};
149 std::vector<float> all;
150 for (const Draw& d : s.draws) {
151 const Mesh& m = s.meshes[d.mesh];
152 for (uint32_t i = 0; i + 2 < m.index_count; i += 3)
153 for (int k = 0; k < 3; ++k) {
154 const float* v = &s.vertices[size_t(m.first_vertex + s.indices[m.first_index + i + k]) * 8];
155 for (int j = 0; j < 3; ++j) {
156 const float w = v[0] * d.rows[0][j] + v[1] * d.rows[1][j] + v[2] * d.rows[2][j] + d.rows[3][j];
157 all.push_back(w);
158 if (j < 2) { lo[j] = std::min(lo[j], w); hi[j] = std::max(hi[j], w); }
159 }
160 }
161 }
162 if (all.empty()) return;
163 x0 = lo[0]; y0 = lo[1];
164 nx = std::min(4096, int((hi[0] - lo[0]) / cell) + 1); ny = std::min(4096, int((hi[1] - lo[1]) / cell) + 1);
165 tris.assign(size_t(nx) * ny, {});
166 for (size_t t = 0; t < all.size(); t += 9) {
167 const float* p = &all[t];
168 const float ax = std::min({p[0], p[3], p[6]}), bx = std::max({p[0], p[3], p[6]});
169 const float ay = std::min({p[1], p[4], p[7]}), by = std::max({p[1], p[4], p[7]});
170 if (bx - ax > 64 || by - ay > 64) continue; // skip huge sheets (skydomes, water planes)
171 for (int cy = std::max(0, int(std::floor((ay - y0) / cell))); cy <= std::min(ny - 1, int(std::floor((by - y0) / cell))); ++cy)
172 for (int cx = std::max(0, int(std::floor((ax - x0) / cell))); cx <= std::min(nx - 1, int(std::floor((bx - x0) / cell))); ++cx)
173 tris[size_t(cy) * nx + cx].insert(tris[size_t(cy) * nx + cx].end(), p, p + 9);
174 }
175 }
176 bool height(float x, float y, float below, float& out) const {
177 const int cx = int(std::floor((x - x0) / cell)), cy = int(std::floor((y - y0) / cell));
178 if (cx < 0 || cy < 0 || cx >= nx || cy >= ny) return false;
179 bool hit = false;
180 const auto& v = tris[size_t(cy) * nx + cx];
181 for (size_t t = 0; t < v.size(); t += 9) {
182 const float* p = &v[t];
183 const float d = (p[3] - p[0]) * (p[7] - p[1]) - (p[6] - p[0]) * (p[4] - p[1]);
184 if (std::fabs(d) < 1e-9f) continue;
185 const float a = ((p[3] - x) * (p[7] - y) - (p[6] - x) * (p[4] - y)) / d;
186 const float b = ((p[6] - x) * (p[1] - y) - (p[0] - x) * (p[7] - y)) / d;
187 const float c = 1 - a - b;
188 if (a < 0 || b < 0 || c < 0) continue;
189 const float z = a * p[2] + b * p[5] + c * p[8];
190 if (z <= below && (!hit || z > out)) { out = z; hit = true; }
191 }
192 return hit;
193 }
194};
195
196#ifdef _WIN32
197bool g_quit = false, g_look = false;
198int g_mx = 0, g_my = 0, g_dx = 0, g_dy = 0;
199LRESULT CALLBACK wndproc(HWND h, UINT m, WPARAM w, LPARAM l) {
200 switch (m) {
201 case WM_CLOSE: g_quit = true; return 0;
202 case WM_RBUTTONDOWN: g_look = true; g_mx = short(LOWORD(l)); g_my = short(HIWORD(l)); SetCapture(h); return 0;
203 case WM_RBUTTONUP: g_look = false; ReleaseCapture(); return 0;
204 case WM_MOUSEMOVE:
205 if (g_look) { const int x = short(LOWORD(l)), y = short(HIWORD(l)); g_dx += x - g_mx; g_dy += y - g_my; g_mx = x; g_my = y; }
206 return 0;
207 }
208 return DefWindowProcW(h, m, w, l);
209}
210#endif
211
212bool write_ppm(const char* path, const uint8_t* bgra_or_rgba, uint32_t w, uint32_t h, bool bgra) {
213 std::ofstream o(path, std::ios::binary);
214 o << "P6\n" << w << " " << h << "\n255\n";
215 for (size_t i = 0; i < size_t(w) * h; ++i) {
216 const uint8_t* p = bgra_or_rgba + i * 4;
217 const char px[3] = {char(p[bgra ? 2 : 0]), char(p[1]), char(p[bgra ? 0 : 2])};
218 o.write(px, 3);
219 }
220 return bool(o);
221}
222
223} // namespace
224
225int main(int argc, char** argv) {
226 if (argc < 4) {
227 std::fprintf(stderr, "usage: vk_sandbox scene.bin vs.spv ps.spv (--out image.ppm | --window) [--size W H] "
228 "[--cam x y z yaw pitch] [--fov deg]\n");
229 return 2;
230 }
231 Scene scene;
232 if (!load_scene(argv[1], scene)) { std::fprintf(stderr, "bad scene file %s\n", argv[1]); return 2; }
233 uint32_t W = 1280, H = 720;
234 const char* out_path = nullptr;
235 bool window = false;
236 int frames = 0; // --frames N: window test run, shown without activation, quits after N frames
237 Camera cam{};
238 cam.pos[0] = scene.center[0] - 40; cam.pos[1] = scene.center[1] - 40; cam.pos[2] = scene.center[2] + 25;
239 cam.yaw = 0.785398f; cam.pitch = -0.35f;
240 for (int i = 4; i < argc; ++i) {
241 if (!std::strcmp(argv[i], "--out") && i + 1 < argc) out_path = argv[++i];
242 else if (!std::strcmp(argv[i], "--window")) window = true;
243 else if (!std::strcmp(argv[i], "--frames") && i + 1 < argc) frames = std::atoi(argv[++i]);
244 else if (!std::strcmp(argv[i], "--mode") && i + 1 < argc) {
245 const char* m = argv[++i];
246 cam.mode = !std::strcmp(m, "walk") ? 1 : !std::strcmp(m, "drive") ? 2 : 0;
247 }
248 else if (!std::strcmp(argv[i], "--size") && i + 2 < argc) { W = std::atoi(argv[++i]); H = std::atoi(argv[++i]); }
249 else if (!std::strcmp(argv[i], "--fov") && i + 1 < argc) cam.fov = float(std::atof(argv[++i]));
250 else if (!std::strcmp(argv[i], "--cam") && i + 5 < argc) {
251 for (int k = 0; k < 3; ++k) cam.pos[k] = float(std::atof(argv[++i]));
252 cam.yaw = float(std::atof(argv[++i])) * 3.14159265f / 180; cam.pitch = float(std::atof(argv[++i])) * 3.14159265f / 180;
253 } else { std::fprintf(stderr, "unknown argument %s\n", argv[i]); return 2; }
254 }
255#ifndef _WIN32
256 if (window) { std::fprintf(stderr, "--window needs Windows\n"); return 2; }
257#endif
258 if (window && frames && !out_path) { std::fprintf(stderr, "--frames needs --out\n"); return 2; }
259 if (!out_path && !window) { std::fprintf(stderr, "give --out or --window\n"); return 2; }
260 std::fprintf(stderr, "scene: %zu draws, %zu meshes, %zu textures, %zu triangles\n", scene.draws.size(),
261 scene.meshes.size(), scene.textures.size(), scene.indices.size() / 3);
262
263 gipa = load_vulkan();
264 if (!gipa) { std::fprintf(stderr, "the Vulkan loader was not found\n"); return 77; }
265 VkInstance inst = VK_NULL_HANDLE;
266#define LI(n) auto n = reinterpret_cast<PFN_##n>(gipa(inst, #n))
267 LI(vkCreateInstance);
268 VkApplicationInfo app{VK_STRUCTURE_TYPE_APPLICATION_INFO}; app.apiVersion = VK_API_VERSION_1_2;
269 const char* inst_ext[2] = {"VK_KHR_surface", "VK_KHR_win32_surface"};
270 VkInstanceCreateInfo ici{VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; ici.pApplicationInfo = &app;
271 if (window) { ici.enabledExtensionCount = 2; ici.ppEnabledExtensionNames = inst_ext; }
272 if (vkCreateInstance(&ici, nullptr, &inst) != VK_SUCCESS) { std::fprintf(stderr, "unsupported: no Vulkan instance\n"); return 77; }
273 LI(vkEnumeratePhysicalDevices); LI(vkGetPhysicalDeviceProperties); LI(vkGetPhysicalDeviceQueueFamilyProperties);
274 LI(vkGetPhysicalDeviceMemoryProperties); LI(vkCreateDevice); LI(vkGetDeviceProcAddr);
275 uint32_t n = 0;
276 CHECK(vkEnumeratePhysicalDevices(inst, &n, nullptr));
277 if (!n) { std::fprintf(stderr, "unsupported: no Vulkan physical device\n"); return 77; }
278 std::vector<VkPhysicalDevice> pds(n);
279 CHECK(vkEnumeratePhysicalDevices(inst, &n, pds.data()));
280 VkPhysicalDevice pd = VK_NULL_HANDLE;
281 VkPhysicalDeviceProperties props{};
282 int best = -1;
283 for (auto p : pds) {
284 VkPhysicalDeviceProperties pp; vkGetPhysicalDeviceProperties(p, &pp);
285 if (int r = leonida::vk_test::device_rank(pp.deviceType, pp.vendorID); r > best) { pd = p; props = pp; best = r; }
286 }
287 constexpr uint32_t push_words = 36, push_bytes = push_words * 4;
288 if (props.limits.maxPushConstantsSize < push_bytes) { std::fprintf(stderr, "unsupported: push constants\n"); return 77; }
289 std::fprintf(stderr, "device: %s\n", props.deviceName);
290 uint32_t qn = 0; vkGetPhysicalDeviceQueueFamilyProperties(pd, &qn, nullptr);
291 std::vector<VkQueueFamilyProperties> qf(qn); vkGetPhysicalDeviceQueueFamilyProperties(pd, &qn, qf.data());
292 uint32_t qi = 0;
293 while (qi < qn && !(qf[qi].queueFlags & VK_QUEUE_GRAPHICS_BIT)) ++qi;
294 if (qi == qn) { std::fprintf(stderr, "unsupported: no graphics queue\n"); return 77; }
295
296#ifdef _WIN32
297 HWND hwnd = nullptr;
298 VkSurfaceKHR surface = VK_NULL_HANDLE;
299 if (window) {
300 WNDCLASSW wc{}; wc.lpfnWndProc = wndproc; wc.hInstance = GetModuleHandleW(nullptr); wc.lpszClassName = L"vk_sandbox";
301 wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
302 RegisterClassW(&wc);
303 RECT rc{0, 0, LONG(W), LONG(H)}; AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, FALSE);
304 hwnd = CreateWindowExW(0, L"vk_sandbox", L"Leonida real-shader sandbox", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT,
305 CW_USEDEFAULT, rc.right - rc.left, rc.bottom - rc.top, nullptr, nullptr, wc.hInstance, nullptr);
306 ShowWindow(hwnd, frames ? SW_SHOWNOACTIVATE : SW_SHOWNORMAL);
307 LI(vkCreateWin32SurfaceKHR);
308 VkWin32SurfaceCreateInfoKHR sci{VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR};
309 sci.hinstance = wc.hInstance; sci.hwnd = hwnd;
310 CHECK(vkCreateWin32SurfaceKHR(inst, &sci, nullptr, &surface));
311 }
312#endif
313
314 float prio = 1;
315 VkDeviceQueueCreateInfo qci{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO};
316 qci.queueFamilyIndex = qi; qci.queueCount = 1; qci.pQueuePriorities = &prio;
317 VkPhysicalDeviceVulkan12Features f12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES};
318 f12.bufferDeviceAddress = VK_TRUE; f12.runtimeDescriptorArray = VK_TRUE; f12.descriptorIndexing = VK_TRUE;
319 f12.shaderSampledImageArrayNonUniformIndexing = VK_TRUE;
320 VkPhysicalDeviceFeatures2 f2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; f2.pNext = &f12;
321 f2.features.shaderInt64 = VK_TRUE;
322 const char* dev_ext[1] = {"VK_KHR_swapchain"};
323 VkDeviceCreateInfo dci{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO};
324 dci.pNext = &f2; dci.queueCreateInfoCount = 1; dci.pQueueCreateInfos = &qci;
325 if (window) { dci.enabledExtensionCount = 1; dci.ppEnabledExtensionNames = dev_ext; }
326 VkDevice dev; CHECK(vkCreateDevice(pd, &dci, nullptr, &dev));
327#define LD(n) auto n = reinterpret_cast<PFN_##n>(vkGetDeviceProcAddr(dev, #n))
328 LD(vkGetDeviceQueue); LD(vkCreateImage); LD(vkGetImageMemoryRequirements); LD(vkAllocateMemory);
329 LD(vkBindImageMemory); LD(vkCreateImageView); LD(vkCreateRenderPass); LD(vkCreateFramebuffer);
330 LD(vkCreateShaderModule); LD(vkCreatePipelineLayout); LD(vkCreateGraphicsPipelines); LD(vkCreateCommandPool);
331 LD(vkAllocateCommandBuffers); LD(vkBeginCommandBuffer); LD(vkCmdBeginRenderPass); LD(vkCmdBindPipeline);
332 LD(vkCmdDrawIndexed); LD(vkCmdEndRenderPass); LD(vkCmdCopyImageToBuffer); LD(vkCmdCopyBufferToImage);
333 LD(vkEndCommandBuffer); LD(vkQueueSubmit); LD(vkQueueWaitIdle); LD(vkCreateBuffer); LD(vkResetCommandBuffer);
334 LD(vkGetBufferMemoryRequirements); LD(vkBindBufferMemory); LD(vkMapMemory); LD(vkGetBufferDeviceAddress);
335 LD(vkCreateSampler); LD(vkCreateDescriptorSetLayout); LD(vkCreateDescriptorPool); LD(vkAllocateDescriptorSets);
336 LD(vkUpdateDescriptorSets); LD(vkCmdBindDescriptorSets); LD(vkCmdPushConstants); LD(vkCmdPipelineBarrier);
337 LD(vkCmdBindVertexBuffers); LD(vkCmdBindIndexBuffer); LD(vkCmdBlitImage);
338 VkQueue q; vkGetDeviceQueue(dev, qi, 0, &q);
339 VkPhysicalDeviceMemoryProperties mp; vkGetPhysicalDeviceMemoryProperties(pd, &mp);
340 auto memtype = [&](uint32_t bits, VkMemoryPropertyFlags want) {
341 for (uint32_t i = 0; i < mp.memoryTypeCount; i++)
342 if ((bits & (1u << i)) && (mp.memoryTypes[i].propertyFlags & want) == want) return i;
343 return 0u;
344 };
345 auto make_buffer = [&](VkDeviceSize size, VkBufferUsageFlags usage, VkBuffer* b, void** map) {
346 VkBufferCreateInfo bi{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; bi.size = size; bi.usage = usage;
347 VkResult r = vkCreateBuffer(dev, &bi, nullptr, b); if (r) return r;
348 VkMemoryRequirements mr; vkGetBufferMemoryRequirements(dev, *b, &mr);
349 VkMemoryAllocateFlagsInfo fi{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO}; fi.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT;
350 VkMemoryAllocateInfo ai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; ai.pNext = &fi; ai.allocationSize = mr.size;
351 ai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
352 VkDeviceMemory m; r = vkAllocateMemory(dev, &ai, nullptr, &m); if (r) return r;
353 r = vkBindBufferMemory(dev, *b, m, 0); if (r) return r;
354 return vkMapMemory(dev, m, 0, size, 0, map);
355 };
356 auto make_image = [&](uint32_t w, uint32_t h, VkFormat fmt, VkImageUsageFlags usage, VkImageAspectFlags aspect,
357 VkImage* img, VkImageView* view) {
358 VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO};
359 ii.imageType = VK_IMAGE_TYPE_2D; ii.format = fmt; ii.extent = {w, h, 1}; ii.mipLevels = 1; ii.arrayLayers = 1;
360 ii.samples = VK_SAMPLE_COUNT_1_BIT; ii.tiling = VK_IMAGE_TILING_OPTIMAL; ii.usage = usage;
361 VkResult r = vkCreateImage(dev, &ii, nullptr, img); if (r) return r;
362 VkMemoryRequirements mr; vkGetImageMemoryRequirements(dev, *img, &mr);
363 VkMemoryAllocateInfo ai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; ai.allocationSize = mr.size;
364 ai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
365 VkDeviceMemory m; r = vkAllocateMemory(dev, &ai, nullptr, &m); if (r) return r;
366 r = vkBindImageMemory(dev, *img, m, 0); if (r) return r;
367 VkImageViewCreateInfo vi{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO};
368 vi.image = *img; vi.viewType = VK_IMAGE_VIEW_TYPE_2D; vi.format = fmt; vi.subresourceRange = {aspect, 0, 1, 0, 1};
369 return vkCreateImageView(dev, &vi, nullptr, view);
370 };
371
372 // Heap: the Xbox GPU VA window. 0x1000 view constants, 0x1200 colour constants, then 0x80 per draw: the
373 // descriptor table at +0 (0x70 bytes used) and nothing else; object constants follow all tables.
374 const uint32_t view_va = 0x1000, colour_va = 0x1200, table_va = 0x2000;
375 const uint32_t ndraw = uint32_t(scene.draws.size());
376 const uint32_t object_va = table_va + ndraw * 0x80;
377 const VkDeviceSize heap_bytes = object_va + VkDeviceSize(ndraw) * 0x40 + 0x1000;
378 VkBuffer heap; void* heapp;
379 CHECK(make_buffer(heap_bytes, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, &heap, &heapp));
380 std::memset(heapp, 0, size_t(heap_bytes));
381 auto heap_u32 = [&](uint32_t va) { return reinterpret_cast<uint32_t*>(static_cast<char*>(heapp) + va); };
382 auto heap_f32 = [&](uint32_t va) { return reinterpret_cast<float*>(static_cast<char*>(heapp) + va); };
383 VkBufferDeviceAddressInfo bdai{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; bdai.buffer = heap;
384 const VkDeviceAddress heap_base = vkGetBufferDeviceAddress(dev, &bdai);
385 // A raw V#: base in word0/word1[15:0], stride 0, NUM_RECORDS bytes, OOB_SELECT 3 (raw byte range).
386 auto vsharp = [&](uint32_t at, uint32_t base, uint32_t bytes) {
387 uint32_t* p = heap_u32(at); p[0] = base; p[1] = 0; p[2] = bytes; p[3] = 3u << 28;
388 };
389 // T# keys: unique words per texture with the RGBA8 UNORM format in word 1 (the numeric type the shader reads).
390 const uint32_t fmt_word = leonida::gfx10::format_from_vulkan(VK_FORMAT_R8G8B8A8_UNORM) << 20;
391 auto tsharp = [&](uint32_t image) {
392 std::array<uint32_t, 8> t{0x5A000000u | image, fmt_word, 0x7FF7FFu, 0, 0, 0, 0, 0};
393 return t;
394 };
395 const uint32_t nimg = uint32_t(scene.textures.size()) + 1; // image 0: 1x1 white for untextured draws
396 leonida::DescriptorTable table(2 * (nimg + 2));
397 for (uint32_t i = 0; i < nimg; ++i) table.insert(tsharp(i).data(), i);
398 uint32_t ssharp[8] = {1024, 12582912, 418381824, 0, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu}; // the PS's literal S#
399 table.insert(ssharp, 0);
400 for (uint32_t d = 0; d < ndraw; ++d) {
401 const Draw& dr = scene.draws[d];
402 const uint32_t t = table_va + d * 0x80, o = object_va + d * 0x40;
403 vsharp(t + 0x00, o, 0x40);
404 const auto ts = tsharp(dr.texture < 0 ? 0 : uint32_t(dr.texture) + 1);
405 std::memcpy(heap_u32(t + 0x20), ts.data(), 32);
406 vsharp(t + 0x40, view_va, 0x1a0);
407 vsharp(t + 0x60, colour_va, 0x10);
408 float* ob = heap_f32(o);
409 for (int r = 0; r < 4; ++r) for (int j = 0; j < 3; ++j) ob[r * 4 + j] = dr.rows[r][j];
410 }
411 float* colour = heap_f32(colour_va); colour[0] = colour[1] = colour[2] = colour[3] = 1;
412 float* light = heap_f32(view_va + 0xa0);
413 { const float l[3] = {-0.55f, -0.45f, 0.7f}; const float ln = std::sqrt(l[0] * l[0] + l[1] * l[1] + l[2] * l[2]);
414 for (int k = 0; k < 3; ++k) light[k] = l[k] / ln; }
415 const auto gpu_table = table.build_gpu_buffer(true);
416 VkBuffer tb; void* tbp;
417 CHECK(make_buffer(gpu_table.size() * 4, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &tb, &tbp));
418 std::memcpy(tbp, gpu_table.data(), gpu_table.size() * 4);
419
420 // Geometry.
421 VkBuffer vb, ib; void* vbp; void* ibp;
422 CHECK(make_buffer(std::max<size_t>(32, scene.vertices.size() * 4), VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, &vb, &vbp));
423 CHECK(make_buffer(std::max<size_t>(4, scene.indices.size() * 4), VK_BUFFER_USAGE_INDEX_BUFFER_BIT, &ib, &ibp));
424 std::memcpy(vbp, scene.vertices.data(), scene.vertices.size() * 4);
425 std::memcpy(ibp, scene.indices.data(), scene.indices.size() * 4);
426
427 // Textures.
428 std::vector<VkImage> timg(nimg); std::vector<VkImageView> tview(nimg);
429 VkDeviceSize up_bytes = 4;
430 for (const auto& t : scene.textures) up_bytes += t.rgba.size();
431 VkBuffer up; void* upp;
432 CHECK(make_buffer(up_bytes, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &up, &upp));
433 std::vector<VkDeviceSize> up_off(nimg);
434 { const uint32_t white = 0xFFFFFFFFu; std::memcpy(upp, &white, 4); VkDeviceSize at = 4;
435 for (uint32_t i = 1; i < nimg; ++i) { up_off[i] = at; std::memcpy(static_cast<char*>(upp) + at, scene.textures[i - 1].rgba.data(), scene.textures[i - 1].rgba.size()); at += scene.textures[i - 1].rgba.size(); } }
436 for (uint32_t i = 0; i < nimg; ++i)
437 CHECK(make_image(i ? scene.textures[i - 1].w : 1, i ? scene.textures[i - 1].h : 1, VK_FORMAT_R8G8B8A8_UNORM,
438 VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, VK_IMAGE_ASPECT_COLOR_BIT, &timg[i], &tview[i]));
439 VkSamplerCreateInfo sci = leonida::gfx10::vulkan_sampler(leonida::gfx10::decode(
440 leonida::gfx10::SamplerWords{ssharp[0], ssharp[1], ssharp[2], ssharp[3]}));
441 sci.maxLod = 0; // the scene stores mip 0 only
442 VkSampler smp; CHECK(vkCreateSampler(dev, &sci, nullptr, &smp));
443
444 // Targets: RGBA8 colour + D32 depth.
445 const VkFormat cfmt = VK_FORMAT_R8G8B8A8_UNORM, dfmt = VK_FORMAT_D32_SFLOAT;
446 VkImage rt, dt; VkImageView rtv, dtv;
447 CHECK(make_image(W, H, cfmt, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT, VK_IMAGE_ASPECT_COLOR_BIT, &rt, &rtv));
448 CHECK(make_image(W, H, dfmt, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, VK_IMAGE_ASPECT_DEPTH_BIT, &dt, &dtv));
449 VkAttachmentDescription ad[2]{};
450 ad[0].format = cfmt; ad[0].samples = VK_SAMPLE_COUNT_1_BIT; ad[0].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
451 ad[0].storeOp = VK_ATTACHMENT_STORE_OP_STORE; ad[0].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
452 ad[0].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
453 ad[0].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; ad[0].finalLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
454 ad[1] = ad[0]; ad[1].format = dfmt; ad[1].storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
455 ad[1].finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
456 VkAttachmentReference car{0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}, dar{1, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL};
457 VkSubpassDescription sd{}; sd.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
458 sd.colorAttachmentCount = 1; sd.pColorAttachments = &car; sd.pDepthStencilAttachment = &dar;
459 VkSubpassDependency dep{0, VK_SUBPASS_EXTERNAL, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
460 VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT};
461 VkRenderPassCreateInfo rpi{VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO};
462 rpi.attachmentCount = 2; rpi.pAttachments = ad; rpi.subpassCount = 1; rpi.pSubpasses = &sd;
463 rpi.dependencyCount = 1; rpi.pDependencies = &dep;
464 VkRenderPass rp; CHECK(vkCreateRenderPass(dev, &rpi, nullptr, &rp));
465 VkImageView fbv[2] = {rtv, dtv};
466 VkFramebufferCreateInfo fbi{VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO};
467 fbi.renderPass = rp; fbi.attachmentCount = 2; fbi.pAttachments = fbv; fbi.width = W; fbi.height = H; fbi.layers = 1;
468 VkFramebuffer fb; CHECK(vkCreateFramebuffer(dev, &fbi, nullptr, &fb));
469
470 // Descriptor set: binding 0 images[], 1 samplers[], 2 the descriptor hash table.
471 VkDescriptorSetLayoutBinding b[3]{};
472 b[0] = {0, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, nimg, VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_VERTEX_BIT, nullptr};
473 b[1] = {1, VK_DESCRIPTOR_TYPE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_VERTEX_BIT, nullptr};
474 b[2] = {2, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_VERTEX_BIT, nullptr};
475 VkDescriptorSetLayoutCreateInfo dli{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; dli.bindingCount = 3; dli.pBindings = b;
476 VkDescriptorSetLayout dsl; CHECK(vkCreateDescriptorSetLayout(dev, &dli, nullptr, &dsl));
477 VkDescriptorPoolSize ps[3]{{VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, nimg}, {VK_DESCRIPTOR_TYPE_SAMPLER, 1}, {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}};
478 VkDescriptorPoolCreateInfo dpi{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; dpi.maxSets = 1; dpi.poolSizeCount = 3; dpi.pPoolSizes = ps;
479 VkDescriptorPool dp; CHECK(vkCreateDescriptorPool(dev, &dpi, nullptr, &dp));
480 VkDescriptorSetAllocateInfo dai{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; dai.descriptorPool = dp; dai.descriptorSetCount = 1; dai.pSetLayouts = &dsl;
481 VkDescriptorSet ds; CHECK(vkAllocateDescriptorSets(dev, &dai, &ds));
482 std::vector<VkDescriptorImageInfo> iinfo(nimg);
483 for (uint32_t i = 0; i < nimg; ++i) iinfo[i] = {VK_NULL_HANDLE, tview[i], VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL};
484 VkDescriptorImageInfo sinfo{smp};
485 VkDescriptorBufferInfo tinfo{tb, 0, VK_WHOLE_SIZE};
486 VkWriteDescriptorSet wr[3]{};
487 for (auto& w : wr) { w.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; w.dstSet = ds; }
488 wr[0].dstBinding = 0; wr[0].descriptorCount = nimg; wr[0].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; wr[0].pImageInfo = iinfo.data();
489 wr[1].dstBinding = 1; wr[1].descriptorCount = 1; wr[1].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER; wr[1].pImageInfo = &sinfo;
490 wr[2].dstBinding = 2; wr[2].descriptorCount = 1; wr[2].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; wr[2].pBufferInfo = &tinfo;
491 vkUpdateDescriptorSets(dev, 3, wr, 0, nullptr);
492
493 // Pipeline: the translated VS and PS, vertices (pos, normal, uv) at locations 0..2, depth test, no culling.
494 auto module = [&](const char* p, VkShaderModule* m) {
495 auto code = read_spv(p);
496 if (code.empty()) { std::fprintf(stderr, "cannot read %s\n", p); return VK_ERROR_INITIALIZATION_FAILED; }
497 VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; smi.codeSize = code.size() * 4; smi.pCode = code.data();
498 return vkCreateShaderModule(dev, &smi, nullptr, m);
499 };
500 VkShaderModule vs, fs; CHECK(module(argv[2], &vs)); CHECK(module(argv[3], &fs));
501 VkPipelineShaderStageCreateInfo st[2]{{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}, {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}};
502 st[0].stage = VK_SHADER_STAGE_VERTEX_BIT; st[0].module = vs; st[0].pName = "main";
503 st[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; st[1].module = fs; st[1].pName = "main";
504 VkPushConstantRange pcr{VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_VERTEX_BIT, 0, push_bytes};
505 VkPipelineLayoutCreateInfo pli{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO};
506 pli.setLayoutCount = 1; pli.pSetLayouts = &dsl; pli.pushConstantRangeCount = 1; pli.pPushConstantRanges = &pcr;
507 VkPipelineLayout pl; CHECK(vkCreatePipelineLayout(dev, &pli, nullptr, &pl));
508 VkVertexInputBindingDescription vbd{0, 32, VK_VERTEX_INPUT_RATE_VERTEX};
509 VkVertexInputAttributeDescription vad[3]{{0, 0, VK_FORMAT_R32G32B32_SFLOAT, 0}, {1, 0, VK_FORMAT_R32G32B32_SFLOAT, 12},
510 {2, 0, VK_FORMAT_R32G32_SFLOAT, 24}};
511 VkPipelineVertexInputStateCreateInfo vin{VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO};
512 vin.vertexBindingDescriptionCount = 1; vin.pVertexBindingDescriptions = &vbd;
513 vin.vertexAttributeDescriptionCount = 3; vin.pVertexAttributeDescriptions = vad;
514 VkPipelineInputAssemblyStateCreateInfo ia{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO}; ia.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
515 // D3D clip space has y up: a negative-height viewport (Vulkan 1.1) keeps the game's matrices unchanged.
516 VkViewport vp{0, float(H), float(W), -float(H), 0, 1}; VkRect2D sc{{0, 0}, {W, H}};
517 VkPipelineViewportStateCreateInfo vps{VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO};
518 vps.viewportCount = 1; vps.pViewports = &vp; vps.scissorCount = 1; vps.pScissors = &sc;
519 VkPipelineRasterizationStateCreateInfo rs{VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO}; rs.cullMode = VK_CULL_MODE_NONE; rs.lineWidth = 1;
520 VkPipelineMultisampleStateCreateInfo ms{VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO}; ms.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
521 VkPipelineDepthStencilStateCreateInfo dss{VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO};
522 dss.depthTestEnable = VK_TRUE; dss.depthWriteEnable = VK_TRUE; dss.depthCompareOp = VK_COMPARE_OP_LESS;
523 VkPipelineColorBlendAttachmentState cba{}; cba.colorWriteMask = 0xF;
524 VkPipelineColorBlendStateCreateInfo cb{VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO}; cb.attachmentCount = 1; cb.pAttachments = &cba;
525 VkGraphicsPipelineCreateInfo gpi{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO};
526 gpi.stageCount = 2; gpi.pStages = st; gpi.pVertexInputState = &vin; gpi.pInputAssemblyState = &ia; gpi.pViewportState = &vps;
527 gpi.pRasterizationState = &rs; gpi.pMultisampleState = &ms; gpi.pDepthStencilState = &dss; gpi.pColorBlendState = &cb;
528 gpi.layout = pl; gpi.renderPass = rp;
529 VkPipeline pipe; CHECK(vkCreateGraphicsPipelines(dev, VK_NULL_HANDLE, 1, &gpi, nullptr, &pipe));
530
531 VkCommandPoolCreateInfo cpi{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; cpi.queueFamilyIndex = qi;
532 cpi.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
533 VkCommandPool pool; CHECK(vkCreateCommandPool(dev, &cpi, nullptr, &pool));
534 VkCommandBufferAllocateInfo cai{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; cai.commandPool = pool; cai.commandBufferCount = 1;
535 VkCommandBuffer cmd; CHECK(vkAllocateCommandBuffers(dev, &cai, &cmd));
536 auto barrier = [&](VkImage img, VkImageLayout from, VkImageLayout to, VkAccessFlags sa, VkAccessFlags da,
537 VkPipelineStageFlags ss, VkPipelineStageFlags dst) {
538 VkImageMemoryBarrier ib{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER};
539 ib.oldLayout = from; ib.newLayout = to; ib.image = img; ib.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
540 ib.srcAccessMask = sa; ib.dstAccessMask = da; ib.srcQueueFamilyIndex = ib.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
541 vkCmdPipelineBarrier(cmd, ss, dst, 0, 0, nullptr, 0, nullptr, 1, &ib);
542 };
543 auto submit = [&]() { VkSubmitInfo si{VK_STRUCTURE_TYPE_SUBMIT_INFO}; si.commandBufferCount = 1; si.pCommandBuffers = &cmd;
544 VkResult r = vkQueueSubmit(q, 1, &si, VK_NULL_HANDLE); return r ? r : vkQueueWaitIdle(q); };
545 { // Upload the textures once.
546 VkCommandBufferBeginInfo cbi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; CHECK(vkBeginCommandBuffer(cmd, &cbi));
547 for (uint32_t i = 0; i < nimg; ++i) {
548 barrier(timg[i], VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 0, VK_ACCESS_TRANSFER_WRITE_BIT,
549 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT);
550 VkBufferImageCopy c{}; c.bufferOffset = up_off[i]; c.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
551 c.imageExtent = {i ? scene.textures[i - 1].w : 1, i ? scene.textures[i - 1].h : 1, 1};
552 vkCmdCopyBufferToImage(cmd, up, timg[i], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &c);
553 barrier(timg[i], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT,
554 VK_ACCESS_SHADER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT);
555 }
556 CHECK(vkEndCommandBuffer(cmd)); CHECK(submit());
557 }
558 // Records the scene into rt (left in TRANSFER_SRC_OPTIMAL). The caller ends and submits.
559 auto record = [&]() {
560 view_projection(cam, float(W) / float(H), heap_f32(view_va + 0x160));
561 VkClearValue clear[2]{}; clear[0].color = {{0.55f, 0.68f, 0.85f, 1}}; clear[1].depthStencil = {1, 0};
562 VkRenderPassBeginInfo rbi{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO};
563 rbi.renderPass = rp; rbi.framebuffer = fb; rbi.renderArea = sc; rbi.clearValueCount = 2; rbi.pClearValues = clear;
564 vkCmdBeginRenderPass(cmd, &rbi, VK_SUBPASS_CONTENTS_INLINE);
565 vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipe);
566 vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pl, 0, 1, &ds, 0, nullptr);
567 VkDeviceSize zero = 0;
568 vkCmdBindVertexBuffers(cmd, 0, 1, &vb, &zero);
569 vkCmdBindIndexBuffer(cmd, ib, 0, VK_INDEX_TYPE_UINT32);
570 uint32_t pc[push_words] = {};
571 pc[32] = uint32_t(heap_base); pc[33] = uint32_t(heap_base >> 32);
572 for (uint32_t d = 0; d < ndraw; ++d) {
573 const Mesh& m = scene.meshes[scene.draws[d].mesh];
574 pc[8] = table_va + d * 0x80; // s8: the descriptor table; s9 (the PS's M0) stays 0
575 vkCmdPushConstants(cmd, pl, VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_VERTEX_BIT, 0, push_bytes, pc);
576 vkCmdDrawIndexed(cmd, m.index_count, 1, m.first_index, int32_t(m.first_vertex), 0);
577 }
578 vkCmdEndRenderPass(cmd);
579 };
580 VkBuffer rb; void* rbp;
581 CHECK(make_buffer(VkDeviceSize(W) * H * 4, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &rb, &rbp));
582 auto read_back = [&]() {
583 VkBufferImageCopy rc{}; rc.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; rc.imageExtent = {W, H, 1};
584 vkCmdCopyImageToBuffer(cmd, rt, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, rb, 1, &rc);
585 };
586
587 if (!window) {
588 VkCommandBufferBeginInfo cbi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; CHECK(vkBeginCommandBuffer(cmd, &cbi));
589 record(); read_back();
590 CHECK(vkEndCommandBuffer(cmd)); CHECK(submit());
591 if (!write_ppm(out_path, static_cast<const uint8_t*>(rbp), W, H, false)) { std::fprintf(stderr, "cannot write %s\n", out_path); return 1; }
592 // Coverage: pixels that differ from the clear colour were written by the translated PS.
593 const uint8_t* px = static_cast<const uint8_t*>(rbp);
594 const uint8_t clear_px[3] = {uint8_t(0.55f * 255 + 0.5f), uint8_t(0.68f * 255 + 0.5f), uint8_t(0.85f * 255 + 0.5f)};
595 size_t covered = 0;
596 for (size_t i = 0; i < size_t(W) * H; ++i)
597 covered += std::abs(px[i * 4] - clear_px[0]) > 1 || std::abs(px[i * 4 + 1] - clear_px[1]) > 1 || std::abs(px[i * 4 + 2] - clear_px[2]) > 1;
598 std::printf("vk_sandbox: %u draws, %zu of %u pixels covered -> %s\n", ndraw, covered, W * H, out_path);
599 return 0;
600 }
601
602#ifdef _WIN32
603 LI(vkGetPhysicalDeviceSurfaceCapabilitiesKHR); LI(vkGetPhysicalDeviceSurfaceFormatsKHR); LI(vkGetPhysicalDeviceSurfaceSupportKHR);
604 LD(vkCreateSwapchainKHR); LD(vkDestroySwapchainKHR); LD(vkGetSwapchainImagesKHR); LD(vkAcquireNextImageKHR);
605 LD(vkQueuePresentKHR); LD(vkCreateSemaphore);
606 VkBool32 can_present = VK_FALSE; vkGetPhysicalDeviceSurfaceSupportKHR(pd, qi, surface, &can_present);
607 if (!can_present) { std::fprintf(stderr, "the graphics queue cannot present\n"); return 1; }
608 uint32_t nf = 0; vkGetPhysicalDeviceSurfaceFormatsKHR(pd, surface, &nf, nullptr);
609 std::vector<VkSurfaceFormatKHR> sfs(nf); vkGetPhysicalDeviceSurfaceFormatsKHR(pd, surface, &nf, sfs.data());
610 if (sfs.empty()) { std::fprintf(stderr, "the surface has no formats\n"); return 1; }
611 VkSurfaceFormatKHR sf = sfs[0]; // a UNORM format keeps the blit byte-exact with the headless render
612 for (const VkSurfaceFormatKHR& c : sfs)
613 if (c.format == VK_FORMAT_B8G8R8A8_UNORM || c.format == VK_FORMAT_R8G8B8A8_UNORM) { sf = c; break; }
614 VkSwapchainCreateInfoKHR swi{VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR};
615 VkSwapchainKHR swap = VK_NULL_HANDLE;
616 std::vector<VkImage> simg;
617 // (Re)creates the swapchain for the window's current size; false while it is minimised (extent 0).
618 auto make_swap = [&]() -> int {
619 VkSurfaceCapabilitiesKHR caps;
620 if (vkGetPhysicalDeviceSurfaceCapabilitiesKHR(pd, surface, &caps) != VK_SUCCESS) return -1;
621 if (!(caps.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_DST_BIT)) return -1;
622 const VkExtent2D ext = caps.currentExtent.width != 0xFFFFFFFFu ? caps.currentExtent : VkExtent2D{W, H};
623 if (!ext.width || !ext.height) return 0;
624 vkQueueWaitIdle(q);
625 swi.surface = surface; swi.minImageCount = std::max(2u, caps.minImageCount);
626 if (caps.maxImageCount) swi.minImageCount = std::min(swi.minImageCount, caps.maxImageCount);
627 swi.imageFormat = sf.format; swi.imageColorSpace = sf.colorSpace; swi.imageExtent = ext;
628 swi.imageArrayLayers = 1; swi.imageUsage = VK_IMAGE_USAGE_TRANSFER_DST_BIT; swi.preTransform = caps.currentTransform;
629 swi.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; swi.presentMode = VK_PRESENT_MODE_FIFO_KHR; swi.clipped = VK_TRUE;
630 swi.oldSwapchain = swap;
631 VkSwapchainKHR next;
632 if (vkCreateSwapchainKHR(dev, &swi, nullptr, &next) != VK_SUCCESS) return -1;
633 if (swap) vkDestroySwapchainKHR(dev, swap, nullptr);
634 swap = next;
635 uint32_t ns = 0; vkGetSwapchainImagesKHR(dev, swap, &ns, nullptr);
636 simg.resize(ns); vkGetSwapchainImagesKHR(dev, swap, &ns, simg.data());
637 return 1;
638 };
639 if (make_swap() < 0) { std::fprintf(stderr, "cannot create a swapchain (TRANSFER_DST unsupported?)\n"); return 1; }
640 VkSemaphoreCreateInfo semi{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO};
641 VkSemaphore acquired; CHECK(vkCreateSemaphore(dev, &semi, nullptr, &acquired));
642 Ground ground; ground.build(scene);
643 auto last = std::chrono::steady_clock::now();
644 bool shot_held = false;
645 int frame = 0;
646 while (!g_quit) {
647 MSG msg;
648 while (PeekMessageW(&msg, nullptr, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessageW(&msg); }
649 const auto now = std::chrono::steady_clock::now();
650 const float dt = std::min(0.1f, std::chrono::duration<float>(now - last).count()); last = now;
651 const bool focus = GetForegroundWindow() == hwnd;
652 auto key = [&](int vk) { return focus && (GetAsyncKeyState(vk) & 0x8000); };
653 if (key(VK_ESCAPE)) break;
654 if (key('1')) cam.mode = 0; if (key('2')) cam.mode = 1; if (key('3')) cam.mode = 2;
655 cam.yaw -= g_dx * 0.004f; cam.pitch = std::clamp(cam.pitch - g_dy * 0.004f, -1.5f, 1.5f); g_dx = g_dy = 0;
656 float f[3]; cam.forward(f);
657 const float r[2] = {std::sin(cam.yaw), -std::cos(cam.yaw)};
658 const float fwd = float(key('W')) - float(key('S')), side = float(key('D')) - float(key('A'));
659 if (cam.mode == 0) {
660 const float v = (key(VK_SHIFT) ? 60.f : 12.f) * dt;
661 for (int k = 0; k < 3; ++k) cam.pos[k] += f[k] * fwd * v;
662 cam.pos[0] += r[0] * side * v; cam.pos[1] += r[1] * side * v;
663 cam.pos[2] += (float(key('E')) - float(key('Q'))) * v;
664 } else {
665 const float h = std::hypot(f[0], f[1]) > 1e-4f ? std::hypot(f[0], f[1]) : 1;
666 if (cam.mode == 1) cam.speed = fwd * (key(VK_SHIFT) ? 7.f : 2.5f);
667 else { cam.speed += fwd * 12.f * dt; cam.speed *= std::pow(0.6f, dt); cam.yaw -= side * dt * std::clamp(cam.speed / 10.f, -1.f, 1.f); }
668 cam.pos[0] += f[0] / h * cam.speed * dt; cam.pos[1] += f[1] / h * cam.speed * dt;
669 if (cam.mode == 1) { cam.pos[0] += r[0] * side * 2.5f * dt; cam.pos[1] += r[1] * side * 2.5f * dt; }
670 const float eye = cam.mode == 1 ? 1.7f : 1.2f;
671 float gz;
672 if (ground.height(cam.pos[0], cam.pos[1], cam.pos[2] - eye + 0.6f, gz)) cam.pos[2] = gz + eye;
673 }
674 uint32_t idx = 0;
675 if (!swap) { // minimised at start or since the last resize
676 const int made = make_swap();
677 if (made < 0) { std::fprintf(stderr, "cannot recreate the swapchain\n"); return 1; }
678 if (!made) { Sleep(50); continue; }
679 }
680 const VkResult acq = vkAcquireNextImageKHR(dev, swap, UINT64_MAX, acquired, VK_NULL_HANDLE, &idx);
681 if (acq == VK_ERROR_OUT_OF_DATE_KHR) {
682 const int made = make_swap();
683 if (made < 0) { std::fprintf(stderr, "cannot recreate the swapchain\n"); return 1; }
684 if (!made) { vkDestroySwapchainKHR(dev, swap, nullptr); swap = VK_NULL_HANDLE; Sleep(50); }
685 continue;
686 }
687 if (acq != VK_SUCCESS && acq != VK_SUBOPTIMAL_KHR) { std::fprintf(stderr, "vkAcquireNextImageKHR failed (%d)\n", int(acq)); return 1; }
688 CHECK(vkResetCommandBuffer(cmd, 0));
689 VkCommandBufferBeginInfo cbi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; CHECK(vkBeginCommandBuffer(cmd, &cbi));
690 record();
691 const bool last_frame = frames && ++frame >= frames;
692 const bool shot = (key('P') && !shot_held) || last_frame; shot_held = key('P');
693 if (shot) read_back();
694 barrier(simg[idx], VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 0, VK_ACCESS_TRANSFER_WRITE_BIT,
695 VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT);
696 VkImageBlit bl{}; bl.srcSubresource = bl.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
697 bl.srcOffsets[1] = {int32_t(W), int32_t(H), 1};
698 bl.dstOffsets[1] = {int32_t(swi.imageExtent.width), int32_t(swi.imageExtent.height), 1};
699 vkCmdBlitImage(cmd, rt, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, simg[idx], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &bl, VK_FILTER_LINEAR);
700 barrier(simg[idx], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, VK_ACCESS_TRANSFER_WRITE_BIT, 0,
701 VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
702 CHECK(vkEndCommandBuffer(cmd));
703 VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_TRANSFER_BIT;
704 VkSubmitInfo si{VK_STRUCTURE_TYPE_SUBMIT_INFO}; si.waitSemaphoreCount = 1; si.pWaitSemaphores = &acquired;
705 si.pWaitDstStageMask = &wait_stage; si.commandBufferCount = 1; si.pCommandBuffers = &cmd;
706 CHECK(vkQueueSubmit(q, 1, &si, VK_NULL_HANDLE)); CHECK(vkQueueWaitIdle(q));
707 if (shot) {
708 const char* path = last_frame ? out_path : "sandbox_shot.ppm";
709 if (!write_ppm(path, static_cast<const uint8_t*>(rbp), W, H, false)) {
710 std::fprintf(stderr, "cannot write %s\n", path);
711 if (last_frame) return 1;
712 }
713 }
714 VkPresentInfoKHR pi{VK_STRUCTURE_TYPE_PRESENT_INFO_KHR}; pi.swapchainCount = 1; pi.pSwapchains = &swap; pi.pImageIndices = &idx;
715 const VkResult pres = vkQueuePresentKHR(q, &pi);
716 if ((pres == VK_ERROR_OUT_OF_DATE_KHR || pres == VK_SUBOPTIMAL_KHR || acq == VK_SUBOPTIMAL_KHR) && !last_frame) {
717 const int made = make_swap();
718 if (made < 0) { std::fprintf(stderr, "cannot recreate the swapchain\n"); return 1; }
719 if (!made) { vkDestroySwapchainKHR(dev, swap, nullptr); swap = VK_NULL_HANDLE; }
720 }
721 char title[160];
722 std::snprintf(title, sizeof title, "Leonida real-shader sandbox [%s] %.0f %.0f %.0f %.0f fps", cam.mode == 0 ? "fly" : cam.mode == 1 ? "walk" : "drive",
723 cam.pos[0], cam.pos[1], cam.pos[2], 1.f / std::max(dt, 1e-4f));
724 SetWindowTextA(hwnd, title);
725 if (last_frame) {
726 std::printf("vk_sandbox: window ran %d frames -> %s, camera %.2f %.2f %.2f\n", frame, out_path,
727 cam.pos[0], cam.pos[1], cam.pos[2]);
728 break;
729 }
730 }
731 vkQueueWaitIdle(q);
732#endif
733 return 0;
734}
diff --git a/runtime/test/vk_texture_test.cpp b/runtime/test/vk_texture_test.cpp
index a2191eae3..474264dcf 100644
--- a/runtime/test/vk_texture_test.cpp
+++ b/runtime/test/vk_texture_test.cpp
@@ -13,6 +13,7 @@
13// (x + 0.5) / 8) and a LESS_OR_EQUAL compare sampler at index 1; both of its results, f32 and d16, must be the 13// (x + 0.5) / 8) and a LESS_OR_EQUAL compare sampler at index 1; both of its results, f32 and d16, must be the
14// 1.0 or 0.0 the reference 0.5 gives against the texel each pixel reads. 14// 1.0 or 0.0 the reference 0.5 gives against the texel each pixel reads.
15// vk_texture_test dref_a16 [out.raw]: the same with ps_sample_c_lz_a16 (16-bit coordinates). 15// vk_texture_test dref_a16 [out.raw]: the same with ps_sample_c_lz_a16 (16-bit coordinates).
16// vk_texture_test dref_c / dref_c_b [out.raw]: the same with ps_sample_c (implicit LOD) / ps_sample_c_b (LOD bias).
16// VKT_HEAP_MB=<n>: size of the heap in MiB (default 64 KiB) 17// VKT_HEAP_MB=<n>: size of the heap in MiB (default 64 KiB)
17// VKT_NEED_MAINTENANCE8=1: the shader has a non-constant texel Offset outside gather (image_sample*_o, see 18// VKT_NEED_MAINTENANCE8=1: the shader has a non-constant texel Offset outside gather (image_sample*_o, see
18// ps_texoff.asm); print "unsupported: ..." and exit 77 when VK_KHR_maintenance8 cannot be enabled. 19// ps_texoff.asm); print "unsupported: ..." and exit 77 when VK_KHR_maintenance8 cannot be enabled.
@@ -72,8 +73,15 @@ int main(int argc, char** argv) {
72 std::string vs_path, fs_path, out_path; 73 std::string vs_path, fs_path, out_path;
73 int ptr_sgpr = 0; 74 int ptr_sgpr = 0;
74 const bool cube = argc >= 2 && !std::strcmp(argv[1], "cube"); 75 const bool cube = argc >= 2 && !std::strcmp(argv[1], "cube");
75 const bool dref_a16 = argc >= 2 && !std::strcmp(argv[1], "dref_a16"); 76 // dref_c / dref_c_b: image_sample_c / image_sample_c_b (implicit LOD, bias), same texture and expected results.
76 const bool dref = dref_a16 || (argc >= 2 && !std::strcmp(argv[1], "dref")); 77 const char* dref_ps = nullptr;
78 if (argc >= 2) {
79 if (!std::strcmp(argv[1], "dref")) dref_ps = "ps_sample_c_lz.spv";
80 else if (!std::strcmp(argv[1], "dref_a16")) dref_ps = "ps_sample_c_lz_a16.spv";
81 else if (!std::strcmp(argv[1], "dref_c")) dref_ps = "ps_sample_c.spv";
82 else if (!std::strcmp(argv[1], "dref_c_b")) dref_ps = "ps_sample_c_b.spv";
83 }
84 const bool dref = dref_ps != nullptr;
77 bool autonomous = false; 85 bool autonomous = false;
78 uint32_t ssharp[8] = {0x92, 0xc00000, 0x14500000, 0, 86 uint32_t ssharp[8] = {0x92, 0xc00000, 0x14500000, 0,
79 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu}; 87 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu};
@@ -102,15 +110,14 @@ int main(int argc, char** argv) {
102 return std::string("runtime/build/shaders/spirv/") + name; 110 return std::string("runtime/build/shaders/spirv/") + name;
103 }; 111 };
104 vs_path = find_spv("vs_ids.spv"); 112 vs_path = find_spv("vs_ids.spv");
105 fs_path = find_spv(cube ? "ps_cube_sample.spv" : dref_a16 ? "ps_sample_c_lz_a16.spv" 113 fs_path = find_spv(cube ? "ps_cube_sample.spv" : dref ? dref_ps : "ps_texture_sample.spv");
106 : dref ? "ps_sample_c_lz.spv" : "ps_texture_sample.spv");
107 const int out_arg = cube || dref ? 2 : 1; 114 const int out_arg = cube || dref ? 2 : 1;
108 out_path = argc > out_arg ? argv[out_arg] : "runtime/build/vk_texture_test_out.raw"; 115 out_path = argc > out_arg ? argv[out_arg] : "runtime/build/vk_texture_test_out.raw";
109 ptr_sgpr = 0; 116 ptr_sgpr = 0;
110 if (dref) 117 if (dref)
111 ssharp[0] |= 3u << 12; // the shader's S#: DEPTH_COMPARE_FUNC = LESSEQUAL 118 ssharp[0] |= 3u << 12; // the shader's S#: DEPTH_COMPARE_FUNC = LESSEQUAL
112 } else { 119 } else {
113 std::fprintf(stderr, "usage: vk_texture_test [cube|dref|dref_a16] [out] | vs fs out ptr_sgpr s0 s1 s2 s3 [--two-mip|--two-mip-sint]\n"); 120 std::fprintf(stderr, "usage: vk_texture_test [cube|dref|dref_a16|dref_c|dref_c_b] [out] | vs fs out ptr_sgpr s0 s1 s2 s3 [--two-mip|--two-mip-sint]\n");
114 return 2; 121 return 2;
115 } 122 }
116 // Word 1 also selects the numeric type when the shader fetches through this key. Word 3 keeps BASE_LEVEL [15:12] 123 // Word 1 also selects the numeric type when the shader fetches through this key. Word 3 keeps BASE_LEVEL [15:12]
@@ -144,18 +151,16 @@ int main(int argc, char** argv) {
144 std::fprintf(stderr, "unsupported: no Vulkan physical device\n"); 151 std::fprintf(stderr, "unsupported: no Vulkan physical device\n");
145 return 77; // a missing device is a skip in every texture-test mode 152 return 77; // a missing device is a skip in every texture-test mode
146 } 153 }
147 VkPhysicalDevice pd = VK_NULL_HANDLE; 154 // LEONIDA_VK_DEVICE picks one GPU on a machine with several, as in the other test programs.
148 VkPhysicalDeviceProperties properties{}; 155 std::vector<VkPhysicalDeviceProperties> candidates(n);
149 int best_rank = -1; 156 for (uint32_t i = 0; i < n; ++i) vkGetPhysicalDeviceProperties(pds[i], &candidates[i]);
150 for (uint32_t i = 0; i < n; ++i) { 157 const size_t chosen = leonida::vk_test::pick_device(candidates);
151 VkPhysicalDeviceProperties p; 158 if (chosen >= n) {
152 vkGetPhysicalDeviceProperties(pds[i], &p); 159 leonida::vk_test::report_no_device();
153 if (const int rank = leonida::vk_test::device_rank(p.deviceType, p.vendorID); rank > best_rank) { 160 return 1;
154 pd = pds[i];
155 properties = p;
156 best_rank = rank;
157 }
158 } 161 }
162 VkPhysicalDevice pd = pds[chosen];
163 VkPhysicalDeviceProperties properties = candidates[chosen];
159 constexpr uint32_t push_words = 36; 164 constexpr uint32_t push_words = 36;
160 // LEONIDA_PC_TAIL_UBO=1 (rdna2spirv.py --pc-tail-ubo): s0..s31 only; the heap base is in a uniform block at set 1 165 // LEONIDA_PC_TAIL_UBO=1 (rdna2spirv.py --pc-tail-ubo): s0..s31 only; the heap base is in a uniform block at set 1
161 // (vk_pc_tail.h), so a 128-byte device runs these tests too. 166 // (vk_pc_tail.h), so a 128-byte device runs these tests too.
@@ -211,7 +216,7 @@ int main(int argc, char** argv) {
211 for (auto& x : exts) m8_on = m8_on || !std::strcmp(x.extensionName, VK_KHR_MAINTENANCE_8_EXTENSION_NAME); 216 for (auto& x : exts) m8_on = m8_on || !std::strcmp(x.extensionName, VK_KHR_MAINTENANCE_8_EXTENSION_NAME);
212 if (m8_on) { 217 if (m8_on) {
213 enable.push_back(VK_KHR_MAINTENANCE_8_EXTENSION_NAME); 218 enable.push_back(VK_KHR_MAINTENANCE_8_EXTENSION_NAME);
214 m8.maintenance8 = VK_TRUE; f12.pNext = &m8; 219 m8.maintenance8 = VK_TRUE; f11.pNext = &m8;
215 std::fprintf(stderr, "enabled %s\n", VK_KHR_MAINTENANCE_8_EXTENSION_NAME); 220 std::fprintf(stderr, "enabled %s\n", VK_KHR_MAINTENANCE_8_EXTENSION_NAME);
216 } 221 }
217#endif 222#endif
diff --git a/runtime/test/vulkan13_features_test.cpp b/runtime/test/vulkan13_features_test.cpp
index cf1b4d99c..d0c446495 100644
--- a/runtime/test/vulkan13_features_test.cpp
+++ b/runtime/test/vulkan13_features_test.cpp
@@ -248,11 +248,30 @@ int main() {
248 EXPECT(types[2] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES); 248 EXPECT(types[2] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES);
249 EXPECT(types[3] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2); 249 EXPECT(types[3] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2);
250 250
251 const auto* rendering = static_cast<const VkPhysicalDeviceDynamicRenderingFeaturesKHR*>(head);
252 const auto* sync2 = static_cast<const VkPhysicalDeviceSynchronization2FeaturesKHR*>(rendering->pNext);
253 EXPECT(rendering->dynamicRendering == VK_TRUE);
254 EXPECT(sync2->synchronization2 == VK_TRUE);
255
251 std::vector<const char*> exts; 256 std::vector<const char*> exts;
252 v13.add_extensions(exts); 257 v13.add_extensions(exts);
253 EXPECT(exts.size() == 2); 258 EXPECT(exts.size() == 2);
254 EXPECT(std::strcmp(exts[0], VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME) == 0); 259 EXPECT(std::strcmp(exts[0], VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME) == 0);
255 EXPECT(std::strcmp(exts[1], VK_KHR_SYNCHRONIZATION_2_EXTENSION_NAME) == 0); 260 EXPECT(std::strcmp(exts[1], VK_KHR_SYNCHRONIZATION_2_EXTENSION_NAME) == 0);
261
262 // Extensions advertised, but each required feature bit cleared in turn after a successful query.
263 dev.features2_calls = 0;
264 dev.dynamic_rendering = VK_FALSE;
265 dev.synchronization2 = VK_TRUE;
266 v13.query(VK_NULL_HANDLE, VK_API_VERSION_1_2, fake_get_features2, fake_enumerate_extensions);
267 EXPECT(dev.features2_calls == 1);
268 EXPECT(!v13.core && !v13.dynamic_rendering && v13.synchronization2 && !v13.usable());
269
270 dev.dynamic_rendering = VK_TRUE;
271 dev.synchronization2 = VK_FALSE;
272 v13.query(VK_NULL_HANDLE, VK_API_VERSION_1_2, fake_get_features2, fake_enumerate_extensions);
273 EXPECT(dev.features2_calls == 2);
274 EXPECT(!v13.core && v13.dynamic_rendering && !v13.synchronization2 && !v13.usable());
256 } 275 }
257 276
258 // Vulkan 1.2 with only EDS1 (missing EDS2), or both extensions with one feature bit false: EDS stays off. 277 // Vulkan 1.2 with only EDS1 (missing EDS2), or both extensions with one feature bit false: EDS stays off.
@@ -323,6 +342,15 @@ int main() {
323 EXPECT(types[4] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES); 342 EXPECT(types[4] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES);
324 EXPECT(types[5] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2); 343 EXPECT(types[5] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2);
325 344
345 const auto* rendering = static_cast<const VkPhysicalDeviceDynamicRenderingFeaturesKHR*>(head);
346 const auto* sync2 = static_cast<const VkPhysicalDeviceSynchronization2FeaturesKHR*>(rendering->pNext);
347 const auto* eds = static_cast<const VkPhysicalDeviceExtendedDynamicStateFeaturesEXT*>(sync2->pNext);
348 const auto* eds2 = static_cast<const VkPhysicalDeviceExtendedDynamicState2FeaturesEXT*>(eds->pNext);
349 EXPECT(rendering->dynamicRendering == VK_TRUE);
350 EXPECT(sync2->synchronization2 == VK_TRUE);
351 EXPECT(eds->extendedDynamicState == VK_TRUE);
352 EXPECT(eds2->extendedDynamicState2 == VK_TRUE);
353
326 std::vector<const char*> exts; 354 std::vector<const char*> exts;
327 chosen.add_extensions(exts); 355 chosen.add_extensions(exts);
328 EXPECT(exts.size() == 4); 356 EXPECT(exts.size() == 4);
@@ -332,6 +360,39 @@ int main() {
332 EXPECT(std::strcmp(exts[3], VK_EXT_EXTENDED_DYNAMIC_STATE_2_EXTENSION_NAME) == 0); 360 EXPECT(std::strcmp(exts[3], VK_EXT_EXTENDED_DYNAMIC_STATE_2_EXTENSION_NAME) == 0);
333 } 361 }
334 362
363 // choose() with a Vulkan 1.3 candidate preserves core=true and subgroup flags after source overwrite.
364 {
365 FakeDevice dev;
366 dev.dynamic_rendering = VK_TRUE;
367 dev.synchronization2 = VK_TRUE;
368 dev.subgroup_size_control = VK_TRUE;
369 dev.compute_full_subgroups = VK_TRUE;
370 g_device = &dev;
371
372 Vulkan13Features candidate;
373 candidate.query(VK_NULL_HANDLE, VK_API_VERSION_1_3, fake_get_features2, nullptr);
374 EXPECT(candidate.core && candidate.usable());
375
376 Vulkan13Features chosen;
377 chosen.choose(candidate);
378 candidate.query(VK_NULL_HANDLE, VK_API_VERSION_1_1, fake_get_features2, fake_enumerate_extensions);
379 EXPECT(!candidate.core && !candidate.usable());
380 EXPECT(chosen.core && chosen.usable() && chosen.extended_dynamic_state);
381 EXPECT(chosen.subgroup_size_control && chosen.compute_full_subgroups);
382
383 VkBaseOutStructure tail{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, nullptr};
384 void* head = chosen.enable(&tail);
385 const auto* enable13 = static_cast<const VkPhysicalDeviceVulkan13Features*>(head);
386 EXPECT(enable13->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES);
387 EXPECT(enable13->dynamicRendering == VK_TRUE && enable13->synchronization2 == VK_TRUE);
388 EXPECT(enable13->subgroupSizeControl == VK_TRUE && enable13->computeFullSubgroups == VK_TRUE);
389 EXPECT(enable13->pNext == &tail);
390
391 std::vector<const char*> exts;
392 chosen.add_extensions(exts);
393 EXPECT(exts.empty());
394 }
395
335 // device_proc_or_khr resolves core first, then KHR, then EXT, else null. 396 // device_proc_or_khr resolves core first, then KHR, then EXT, else null.
336 { 397 {
337 ProcLookup lookup; 398 ProcLookup lookup;
diff --git a/runtime/test/winhttp_offline_test.cpp b/runtime/test/winhttp_offline_test.cpp
index 4181103fd..f7ea661de 100644
--- a/runtime/test/winhttp_offline_test.cpp
+++ b/runtime/test/winhttp_offline_test.cpp
@@ -10,6 +10,7 @@
10#include <chrono> 10#include <chrono>
11#include <cstdio> 11#include <cstdio>
12#include <cstring> 12#include <cstring>
13#include <vector>
13 14
14#include "shims.h" 15#include "shims.h"
15 16
@@ -84,6 +85,13 @@ double ms_since(std::chrono::steady_clock::time_point start) {
84 return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count(); 85 return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count();
85} 86}
86 87
88// HANDLE_CLOSING arrives on the callback thread, so a count read right after WinHttpCloseHandle can be short, and a
89// notification that comes late lands in the next block's count (TEST-721). Waits up to two seconds for `n`.
90bool wait_for_closing(const Seen& s, int n) {
91 for (int i = 0; i < 200 && s.closing.load() < n; ++i) Sleep(10);
92 return s.closing.load() >= n;
93}
94
87} // namespace 95} // namespace
88 96
89int main() { 97int main() {
@@ -256,7 +264,7 @@ int main() {
256 "and HANDLE_CLOSING follows once, after the error"); 264 "and HANDLE_CLOSING follows once, after the error");
257 close(connection); 265 close(connection);
258 close(session); 266 close(session);
259 check(seen.closing.load() == 3, "every handle reports HANDLE_CLOSING once"); 267 check(wait_for_closing(seen, 3) && seen.closing.load() == 3, "every handle reports HANDLE_CLOSING once");
260 } 268 }
261 269
262 // A callback that closes its request while handling the error, as libHttpClient-style code does. 270 // A callback that closes its request while handling the error, as libHttpClient-style code does.
@@ -277,6 +285,8 @@ int main() {
277 seen.close_in_callback = nullptr; 285 seen.close_in_callback = nullptr;
278 close(connection); 286 close(connection);
279 close(session); 287 close(session);
288 check(wait_for_closing(seen, 3) && seen.closing.load() == 3,
289 "the connection and the session report HANDLE_CLOSING before the next block counts its own");
280 } 290 }
281 291
282 // A request closed before its queued failure is delivered gets no error callback, only HANDLE_CLOSING. 292 // A request closed before its queued failure is delivered gets no error callback, only HANDLE_CLOSING.
@@ -300,6 +310,69 @@ int main() {
300 CloseHandle(seen.error_event); 310 CloseHandle(seen.error_event);
301 CloseHandle(seen.closing_event); 311 CloseHandle(seen.closing_event);
302 312
313 // WINHTTP_OPTION_CONTEXT_VALUE is inherited like the callback: a handle starts with the context its parent has
314 // when it is created, and keeps it when the parent's changes later. The host's winhttp.dll gave these values.
315 {
316 struct Event {
317 HINTERNET handle;
318 DWORD status;
319 DWORD_PTR context;
320 };
321 static std::vector<Event> events; // a synchronous session: every callback runs on this thread
322 const WINHTTP_STATUS_CALLBACK record = [](HINTERNET handle, DWORD_PTR context, DWORD status, LPVOID, DWORD) {
323 events.push_back({handle, status, context});
324 };
325 const auto context_of = [&](HINTERNET handle) -> DWORD_PTR {
326 DWORD_PTR value = ~DWORD_PTR{0};
327 DWORD size = sizeof(value);
328 return query_option(handle, WINHTTP_OPTION_CONTEXT_VALUE, &value, &size) ? value : ~DWORD_PTR{0};
329 };
330 const auto set_context = [&](HINTERNET handle, DWORD_PTR value) {
331 return set_option(handle, WINHTTP_OPTION_CONTEXT_VALUE, &value, sizeof(value)) != FALSE;
332 };
333 const auto context_at = [&](HINTERNET handle, DWORD status) -> DWORD_PTR {
334 for (const Event& e : events)
335 if (e.handle == handle && e.status == status) return e.context;
336 return ~DWORD_PTR{0};
337 };
338
339 const HINTERNET session = open(L"test", WINHTTP_ACCESS_TYPE_NO_PROXY, nullptr, nullptr, 0);
340 set_callback(session, record, WINHTTP_CALLBACK_FLAG_HANDLES, 0);
341 check(set_context(session, 7), "WINHTTP_OPTION_CONTEXT_VALUE can be set on a session");
342 const HINTERNET connection = connect(session, L"127.0.0.1", 1, 0);
343 const HINTERNET request = open_request(connection, L"GET", L"/", nullptr, WINHTTP_NO_REFERER,
344 WINHTTP_DEFAULT_ACCEPT_TYPES, 0);
345 check(context_of(connection) == 7 && context_of(request) == 7,
346 "a connection and a request start with the session's context");
347 check(context_at(connection, WINHTTP_CALLBACK_STATUS_HANDLE_CREATED) == 7 &&
348 context_at(request, WINHTTP_CALLBACK_STATUS_HANDLE_CREATED) == 7,
349 "and their HANDLE_CREATED callbacks carry it");
350
351 check(set_context(request, 9) && context_of(request) == 9 && context_of(connection) == 7,
352 "a context set on the request replaces the inherited one for that request only");
353 check(set_context(session, 11) && context_of(connection) == 7 && context_of(request) == 9,
354 "a context set on the session later does not change handles that exist");
355 const HINTERNET late = connect(session, L"127.0.0.1", 1, 0);
356 check(context_of(late) == 11, "a connection made after that starts with the new one");
357
358 const HINTERNET sent = open_request(connection, L"GET", L"/", nullptr, WINHTTP_NO_REFERER,
359 WINHTTP_DEFAULT_ACCEPT_TYPES, 0);
360 check(context_of(sent) == 7, "a request starts with its connection's context, not the session's");
361 send(sent, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0x51);
362 check(context_of(sent) == 0x51, "the context WinHttpSendRequest is given replaces the inherited one");
363
364 close(sent);
365 close(request);
366 close(late);
367 close(connection);
368 close(session);
369 check(context_at(sent, WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING) == 0x51 &&
370 context_at(request, WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING) == 9 &&
371 context_at(late, WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING) == 11 &&
372 context_at(connection, WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING) == 7,
373 "HANDLE_CLOSING carries each handle's own context");
374 }
375
303 // WinHttpCrackUrl is parsing only and stays the host's. 376 // WinHttpCrackUrl is parsing only and stays the host's.
304 { 377 {
305 wchar_t host[64] = {}, path[64] = {}; 378 wchar_t host[64] = {}, path[64] = {};
diff --git a/runtime/test/xbox_present_test.cpp b/runtime/test/xbox_present_test.cpp
index 6ea54280a..bcea1e2a7 100644
--- a/runtime/test/xbox_present_test.cpp
+++ b/runtime/test/xbox_present_test.cpp
@@ -1263,21 +1263,63 @@ int main() {
1263 constexpr int frames = 30; 1263 constexpr int frames = 30;
1264 const auto start = std::chrono::steady_clock::now(); 1264 const auto start = std::chrono::steady_clock::now();
1265 std::uint64_t last = 0; 1265 std::uint64_t last = 0;
1266 for (int i = 0; i < frames; ++i) { 1266 // One real-time frame: wait for the origin, present colour `c`. True with `shown` false when the present was
1267 // skipped because the window is minimised (PresentX still S_OK, nothing on screen, nothing to read back).
1268 const auto real_frame = [&](int c, bool& shown) -> bool {
1267 pump(); 1269 pump();
1268 std::uint64_t t = 0; 1270 std::uint64_t t = 0;
1269 EXPECT(real.WaitFrameEventX(rt::d3d12::xbox_frame_event_origin, 1000, 0, &t) == S_OK); 1271 if (real.WaitFrameEventX(rt::d3d12::xbox_frame_event_origin, 1000, 0, &t) != S_OK || t != last + 1) {
1270 EXPECT(t == last + 1); 1272 std::fprintf(stderr, "real time: token %llu after %llu\n", static_cast<unsigned long long>(t),
1273 static_cast<unsigned long long>(last));
1274 return false;
1275 }
1271 last = t; 1276 last = t;
1272 auto p = plane_of(colours[i % 3], t); 1277 auto p = plane_of(colours[c], t);
1273 EXPECT(real.PresentX(1, &p, nullptr) == S_OK); 1278 if (real.PresentX(1, &p, nullptr) != S_OK) return false;
1274 EXPECT(real.presenter().read_back(frame.bytes, &frame.extent, &frame.format)); 1279 shown = real.presenter().read_back(frame.bytes, &frame.extent, &frame.format);
1275 EXPECT(close_to(frame.at(width / 2, height / 2), expect_rgb[i % 3], 0)); 1280 if (!shown) return IsIconic(window) != FALSE; // skipped only while minimised
1281 const Px got = frame.at(width / 2, height / 2);
1282 if (close_to(got, expect_rgb[c], 0)) return true;
1283 std::fprintf(stderr, "real time: centre %d,%d,%d, presented %d,%d,%d\n", got.r, got.g, got.b, expect_rgb[c].r,
1284 expect_rgb[c].g, expect_rgb[c].b);
1285 return false;
1286 };
1287 // Someone at the desktop can minimise the window during the loop (Win+D in the middle of a CTest run): those
1288 // presents are skipped, and the window is restored so the rest of the loop is seen again.
1289 int unseen = 0;
1290 for (int i = 0; i < frames; ++i) {
1291 bool shown = false;
1292 EXPECT(real_frame(i % 3, shown));
1293 if (!shown) {
1294 ++unseen;
1295 ShowWindow(window, SW_RESTORE);
1296 }
1276 } 1297 }
1277 const auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start).count(); 1298 const auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start).count();
1278 std::printf("real time: %d frames at 60 Hz in %lld ms (ideal %d)\n", frames, static_cast<long long>(ms), 1299 std::printf("real time: %d frames at 60 Hz in %lld ms (ideal %d), %d skipped while minimised\n", frames,
1279 frames * int(period) / 1000); 1300 static_cast<long long>(ms), frames * int(period) / 1000, unseen);
1280 EXPECT(ms >= (frames - 1) * int(period) / 1000 * 9 / 10 && ms < 5000); 1301 EXPECT(ms >= (frames - 1) * int(period) / 1000 * 9 / 10 && ms < 5000);
1302 EXPECT(unseen < frames);
1303
1304 // Minimised on purpose: the surface is 0x0 (VK_KHR_win32_surface), so PresentX succeeds without showing the
1305 // frame, and read_back must say so rather than hand out the frame before it (TEST-378: the real-time loop
1306 // above once compared that older frame). Each colour differs from the one shown last, so a stale frame fails.
1307 // Restored, the next frame is shown and read back again.
1308 {
1309 ShowWindow(window, SW_MINIMIZE);
1310 int skipped_presents = 0;
1311 for (int i = 0; i < 3; ++i) { // the first present can still reach the old swapchain (then out of date)
1312 bool shown = true;
1313 EXPECT(real_frame(i, shown));
1314 if (!shown) ++skipped_presents;
1315 }
1316 EXPECT(skipped_presents > 0);
1317 ShowWindow(window, SW_RESTORE);
1318 bool shown = false;
1319 for (int i = 0; i < 3 && !shown; ++i) EXPECT(real_frame((i + 1) % 3, shown)); // stale, then recreated
1320 EXPECT(shown);
1321 std::printf("minimised: %d of 3 presents skipped and not read back; restored: shown again\n", skipped_presents);
1322 }
1281 EXPECT(real.PresentX(0, nullptr, nullptr) == S_OK); // the shutdown blank 1323 EXPECT(real.PresentX(0, nullptr, nullptr) == S_OK); // the shutdown blank
1282 } 1324 }
1283 DestroyWindow(window); 1325 DestroyWindow(window);
diff --git a/runtime/test/xgameruntime_test.cpp b/runtime/test/xgameruntime_test.cpp
index 6464b4907..5102c54ab 100644
--- a/runtime/test/xgameruntime_test.cpp
+++ b/runtime/test/xgameruntime_test.cpp
@@ -231,7 +231,8 @@ void check_run_time_load() {
231 auto query = reinterpret_cast<Query>(get_proc(rt_mod, "QueryApiImpl")); 231 auto query = reinterpret_cast<Query>(get_proc(rt_mod, "QueryApiImpl"));
232 auto uninit_api = reinterpret_cast<Uninit>(get_proc(rt_mod, "UninitializeApiImpl")); 232 auto uninit_api = reinterpret_cast<Uninit>(get_proc(rt_mod, "UninitializeApiImpl"));
233 check(init_ex2(0x2410, 0x0, 0x02, &options) == S_OK, "InitializeApiImplEx2 succeeds offline"); 233 check(init_ex2(0x2410, 0x0, 0x02, &options) == S_OK, "InitializeApiImplEx2 succeeds offline");
234 const GUID some_class = {0x973a344e, 0x24bf, 0x4d0f, {0x84, 0x57, 0x56, 0xc5, 0x34, 0x89, 0x2b, 0x29}}; 234 // XGameSaveImpl (xgameruntime include/xgamesave.idl), not served yet.
235 const GUID some_class = {0x704c3f58, 0xe629, 0x4cc2, {0xb1, 0x97, 0x30, 0x51, 0x1b, 0x99, 0x6f, 0xe2}};
235 void* out = reinterpret_cast<void*>(1); 236 void* out = reinterpret_cast<void*>(1);
236 check(query(&some_class, some_class, &out) == static_cast<HRESULT>(0x80070032) && out == nullptr, 237 check(query(&some_class, some_class, &out) == static_cast<HRESULT>(0x80070032) && out == nullptr,
237 "QueryApiImpl refuses a class it doesn't provide yet (HRESULT 0x80070032) and clears the out pointer"); 238 "QueryApiImpl refuses a class it doesn't provide yet (HRESULT 0x80070032) and clears the out pointer");
@@ -489,13 +490,13 @@ void check_run_time_load() {
489 {0x67ce4bfc, 0xb1d1, 0x4ac7, {0xbc, 0x3a, 0xcb, 0x92, 0x19, 0xa9, 0x7a, 0x85}}, 490 {0x67ce4bfc, 0xb1d1, 0x4ac7, {0xbc, 0x3a, 0xcb, 0x92, 0x19, 0xa9, 0x7a, 0x85}},
490 {0xdadc2895, 0x34b0, 0x4ef5, {0xa8, 0x3e, 0x45, 0x11, 0x4d, 0x62, 0x9b, 0x80}}, 491 {0xdadc2895, 0x34b0, 0x4ef5, {0xa8, 0x3e, 0x45, 0x11, 0x4d, 0x62, 0x9b, 0x80}},
491 system5}; 492 system5};
492 bool all = true; 493 bool all_inherited = true;
493 for (const GUID& iid : chain) { 494 for (const GUID& iid : chain) {
494 void* same = nullptr; 495 void* same = nullptr;
495 all = all && query(&system_cls, iid, &same) == S_OK && same == sy; 496 all_inherited = all_inherited && query(&system_cls, iid, &same) == S_OK && same == sy;
496 if (same) release(same); 497 if (same) release(same);
497 } 498 }
498 check(all, "IXSystemImpl5 answers for every interface it inherits (IXSystemImpl .. IXSystemImpl4)"); 499 check(all_inherited, "IXSystemImpl5 answers for every interface it inherits (IXSystemImpl .. IXSystemImpl4)");
499 check(reinterpret_cast<IdQuery>(slot(sy, 5))(sy, sizeof(buf), buf, &used) == S_OK && used == 45 && 500 check(reinterpret_cast<IdQuery>(slot(sy, 5))(sy, sizeof(buf), buf, &used) == S_OK && used == 45 &&
500 reinterpret_cast<IdQuery>(slot(sy, 5))(sy, 44, buf, &used) == 501 reinterpret_cast<IdQuery>(slot(sy, 5))(sy, 44, buf, &used) ==
501 HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER) && 502 HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER) &&
@@ -512,6 +513,186 @@ void check_run_time_load() {
512 "slots 6-8 (handle tracking, handle check, download bandwidth) answer offline"); 513 "slots 6-8 (handle tracking, handle check, download bandwidth) answer offline");
513 release(sy); 514 release(sy);
514 } 515 }
516
517 // XPackageImpl, asked for as libHttpClient.GDK.dll does: the class id with IXPackageImpl3's interface id. The
518 // slots with an offline answer agree with the named exports; the others are E_NOTIMPL.
519 const GUID package_cls = {0xaf406016, 0xe850, 0x4aa8, {0xa8, 0x8d, 0x2f, 0x3d, 0xcb, 0x9d, 0xac, 0x7e}};
520 const GUID package3 = {0xe2a4734b, 0x2f4a, 0x456d, {0xaa, 0x8f, 0xd0, 0x65, 0xe0, 0x4f, 0xb2, 0x09}};
521 void* pk = nullptr;
522 check(query(&package_cls, package3, &pk) == S_OK && pk, "QueryApiImpl hands out XPackageImpl for IXPackageImpl3");
523 if (pk) {
524 using Ident = HRESULT(STDMETHODCALLTYPE*)(void*, size_t, char*);
525 using IdentExport = HRESULT(__stdcall*)(size_t, char*);
526 char a[64] = {}, b[64] = {};
527 const auto ident_export = reinterpret_cast<IdentExport>(
528 rt::shims::find("xgameruntime.dll", "XPackageGetCurrentProcessPackageIdentifier"));
529 check(reinterpret_cast<Ident>(slot(pk, 3))(pk, sizeof(a), a) == S_OK && ident_export &&
530 ident_export(sizeof(b), b) == S_OK && std::strcmp(a, b) == 0,
531 "slot 3 is XPackageGetCurrentProcessPackageIdentifier, the same answer as the export");
532 using IsPackaged = bool(STDMETHODCALLTYPE*)(void*);
533 using IsPackagedExport = bool(__stdcall*)();
534 const auto packaged_export =
535 reinterpret_cast<IsPackagedExport>(rt::shims::find("xgameruntime.dll", "XPackageIsPackagedProcess"));
536 check(packaged_export && reinterpret_cast<IsPackaged>(slot(pk, 4))(pk) == packaged_export(),
537 "slot 4 is XPackageIsPackagedProcess");
538 // Slot 11, XPackageGetUserLocale: one of the package's declared locales, never the host's; nothing written
539 // (but S_OK) when the package declares none.
540 using Locale = HRESULT(STDMETHODCALLTYPE*)(void*, size_t, char*);
541 char tmp[MAX_PATH] = {};
542 GetTempPathA(sizeof(tmp), tmp);
543 const std::string game = std::string(tmp) + "leonida_xpackage_locale_test";
544 CreateDirectoryA(game.c_str(), nullptr);
545 SetEnvironmentVariableA("LEONIDA_GAME_DIR", game.c_str());
546 char locale[128];
547 std::memset(locale, 'z', sizeof(locale));
548 check(reinterpret_cast<Locale>(slot(pk, 11))(pk, sizeof(locale), locale) == S_OK && locale[0] == 'z',
549 "slot 11 without declared locales: S_OK and nothing written");
550 if (FILE* f = std::fopen((game + "\\MicrosoftGame.Config").c_str(), "wb")) {
551 std::fputs("<Game><Resources><Resource Language=\"zz-ZZ\"/><Resource Language='xx-YY'/></Resources></Game>",
552 f);
553 std::fclose(f);
554 }
555 check(reinterpret_cast<Locale>(slot(pk, 11))(pk, sizeof(locale), locale) == S_OK &&
556 (std::strcmp(locale, "zz-ZZ") == 0 || std::strcmp(locale, "xx-YY") == 0) &&
557 reinterpret_cast<Locale>(slot(pk, 11))(pk, 3, locale) == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER),
558 "slot 11 gives one of the package's declared locales, not the host's; a short buffer is refused");
559 DeleteFileA((game + "\\MicrosoftGame.Config").c_str());
560 RemoveDirectoryA(game.c_str());
561 SetEnvironmentVariableA("LEONIDA_GAME_DIR", nullptr);
562 {
563 // A game folder outside every ANSI code page (U+16A0, a runic letter) reaches MicrosoftGame.Config intact.
564 wchar_t wtmp[MAX_PATH] = {};
565 GetTempPathW(MAX_PATH, wtmp);
566 const std::wstring wide = std::wstring(wtmp) + L"leonida_xpackage_\u16a0ocale";
567 CreateDirectoryW(wide.c_str(), nullptr);
568 SetEnvironmentVariableW(L"LEONIDA_GAME_DIR", wide.c_str());
569 const std::wstring wconfig = wide + L"\\MicrosoftGame.Config";
570 if (FILE* f = _wfopen(wconfig.c_str(), L"wb")) {
571 std::fputs("<Game><Resources><Resource Language=\"qq-QQ\"/></Resources></Game>", f);
572 std::fclose(f);
573 }
574 char wlocale[32] = {};
575 check(reinterpret_cast<Locale>(slot(pk, 11))(pk, sizeof(wlocale), wlocale) == S_OK &&
576 std::strcmp(wlocale, "qq-QQ") == 0,
577 "slot 11 reads MicrosoftGame.Config from a game folder named outside the ANSI code page");
578 DeleteFileW(wconfig.c_str());
579 RemoveDirectoryW(wide.c_str());
580 SetEnvironmentVariableW(L"LEONIDA_GAME_DIR", nullptr);
581 }
582 // Slots 23-26 are the named exports' content-package mounts: XPackageMount, the path size and path of the
583 // handle, and closing it. XPackageMountHandle is one u64, passed by value.
584 using Mount = HRESULT(STDMETHODCALLTYPE*)(void*, const char*, uint64_t*);
585 using PathSize = HRESULT(STDMETHODCALLTYPE*)(void*, uint64_t, size_t*);
586 using Path = HRESULT(STDMETHODCALLTYPE*)(void*, uint64_t, size_t, char*);
587 using CloseMount = void(STDMETHODCALLTYPE*)(void*, uint64_t);
588 SetEnvironmentVariableA("LEONIDA_CONTENT_PACKAGES", "SLOTDLC_12345678901234567890123=C:\\LeonidaSlotDLC");
589 uint64_t handle = 0;
590 size_t need = 0;
591 char path[MAX_PATH] = {};
592 check(reinterpret_cast<Mount>(slot(pk, 23))(pk, "SLOTDLC_12345678901234567890123", &handle) == S_OK &&
593 handle != 0,
594 "slot 23 (XPackageMount) mounts a content package and hands out a handle");
595 check(reinterpret_cast<PathSize>(slot(pk, 24))(pk, handle, &need) == S_OK &&
596 need == std::strlen("C:\\LeonidaSlotDLC") + 1 &&
597 reinterpret_cast<Path>(slot(pk, 25))(pk, handle, need, path) == S_OK &&
598 std::strcmp(path, "C:\\LeonidaSlotDLC") == 0 &&
599 reinterpret_cast<Path>(slot(pk, 25))(pk, handle, need - 1, path) ==
600 HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER),
601 "slots 24/25: the mount's path, and exactly the size XPackageGetMountPath needs");
602 reinterpret_cast<CloseMount>(slot(pk, 26))(pk, handle);
603 check(reinterpret_cast<PathSize>(slot(pk, 24))(pk, handle, &need) == HRESULT_FROM_WIN32(ERROR_NOT_FOUND),
604 "slot 26 (XPackageCloseMountHandle) closes the handle");
605 SetEnvironmentVariableA("LEONIDA_CONTENT_PACKAGES", nullptr);
606 using Stub = HRESULT(STDMETHODCALLTYPE*)(void*);
607 check(reinterpret_cast<Stub>(slot(pk, 5))(pk) == E_NOTIMPL && reinterpret_cast<Stub>(slot(pk, 40))(pk) == E_NOTIMPL,
608 "the slots without an offline answer (5, 40) are E_NOTIMPL");
609 struct Progress {
610 uint64_t total, installed, launch;
611 bool launchable, completed;
612 } progress{~0ull, 7, 7, false, false};
613 using GetProgress = void(STDMETHODCALLTYPE*)(void*, void*, Progress*);
614 reinterpret_cast<GetProgress>(slot(pk, 7))(pk, nullptr, &progress);
615 check(progress.launchable && progress.completed && progress.installed == progress.total,
616 "slot 7 (void XPackageGetInstallationProgress) writes an installed, launchable, completed package");
617 using Update = bool(STDMETHODCALLTYPE*)(void*, void*);
618 using UnregProgress = bool(STDMETHODCALLTYPE*)(void*, void*, XTaskQueueRegistrationToken, bool);
619 using UnregInstalled = bool(STDMETHODCALLTYPE*)(void*, XTaskQueueRegistrationToken, bool);
620 using Uninstall = bool(STDMETHODCALLTYPE*)(void*, const char*);
621 check(!reinterpret_cast<Update>(slot(pk, 8))(pk, nullptr) &&
622 reinterpret_cast<UnregProgress>(slot(pk, 10))(pk, nullptr, XTaskQueueRegistrationToken{1}, true) &&
623 reinterpret_cast<UnregInstalled>(slot(pk, 22))(pk, XTaskQueueRegistrationToken{1}, false) &&
624 !reinterpret_cast<Uninstall>(slot(pk, 34))(pk, "pkg"),
625 "the bool slots 8, 10, 22 and 34 return their documented offline answers");
626 const GUID chain[] = {
627 package_cls,
628 {0x3720de07, 0xe8e4, 0x44a3, {0xad, 0x32, 0xb3, 0x59, 0xe8, 0xad, 0xbe, 0x55}},
629 {0xf92d8712, 0x2b27, 0x4d8a, {0xbf, 0x01, 0x11, 0xa6, 0xf8, 0xe3, 0xeb, 0x42}},
630 package3};
631 bool all = true;
632 for (const GUID& iid : chain) {
633 void* same = nullptr;
634 all = all && query(&package_cls, iid, &same) == S_OK && same == pk;
635 if (same) release(same);
636 }
637 check(all, "IXPackageImpl3 answers for IXPackageImpl and IXPackageImpl2 too");
638 release(pk);
639 }
640 {
641 // XGameImpl (IXGameImpl3 : IXGameImpl2 : IXGameImpl, xgameruntime include/xgame.idl); IXGameImpl's id is the
642 // class id. Slots: 3 XGameGetXboxTitleId, 4 XLaunchNewGame (void), 5 XLaunchRestartOnCrash.
643 const GUID game_cls = {0x973a344e, 0x24bf, 0x4d0f, {0x84, 0x57, 0x56, 0xc5, 0x34, 0x89, 0x2b, 0x29}};
644 const GUID game2 = {0x50849859, 0x0ad8, 0x4f81, {0x80, 0xe4, 0x5b, 0xc7, 0x86, 0x26, 0xf8, 0x52}};
645 const GUID game3 = {0x2549f142, 0x6419, 0x4a06, {0x97, 0xb5, 0x93, 0x1a, 0xab, 0x7c, 0x2f, 0x34}};
646 void* g = get(game_cls);
647 check(g != nullptr, "QueryApiImpl hands out XGameImpl for its class id");
648 bool every = g != nullptr;
649 for (const GUID& iid : {game2, game3}) {
650 void* same = nullptr;
651 every = every && query(&game_cls, iid, &same) == S_OK && same == g;
652 if (same) release(same);
653 }
654 check(every, "XGameImpl answers for IXGameImpl2's and IXGameImpl3's ids, the same object");
655 if (g) {
656 using TitleId = HRESULT(STDMETHODCALLTYPE*)(void*, uint32_t*);
657 using LaunchNew = void(STDMETHODCALLTYPE*)(void*, const char*, const char*, void*);
658 using Restart = HRESULT(STDMETHODCALLTYPE*)(void*, const char*, uint32_t);
659 char tmp[MAX_PATH] = {};
660 GetTempPathA(sizeof(tmp), tmp);
661 const std::string game = std::string(tmp) + "leonida_xgame_title_test";
662 CreateDirectoryA(game.c_str(), nullptr);
663 SetEnvironmentVariableA("LEONIDA_GAME_DIR", game.c_str());
664 const std::string config = game + "\\MicrosoftGame.Config";
665 auto write_config = [&](const char* text) {
666 if (FILE* f = std::fopen(config.c_str(), "wb")) {
667 std::fputs(text, f);
668 std::fclose(f);
669 }
670 };
671 uint32_t id = 0x5a5a5a5a;
672 DeleteFileA(config.c_str());
673 check(reinterpret_cast<TitleId>(slot(g, 3))(g, &id) == E_FAIL && id == 0x5a5a5a5a,
674 "slot 3 (XGameGetXboxTitleId) without a config: E_FAIL, nothing written");
675 write_config("<Game configVersion=\"1\">\n <TitleId> 1a2B3c4D </TitleId>\n</Game>\n");
676 check(reinterpret_cast<TitleId>(slot(g, 3))(g, &id) == S_OK && id == 0x1A2B3C4Du,
677 "slot 3 gives the config's <TitleId> (hex, either case, whitespace allowed)");
678 check(reinterpret_cast<TitleId>(slot(g, 3))(g, nullptr) == E_INVALIDARG,
679 "slot 3 with a null pointer is E_INVALIDARG");
680 write_config("<Game><TitleId>not-hex</TitleId></Game>");
681 id = 0x5a5a5a5a;
682 check(reinterpret_cast<TitleId>(slot(g, 3))(g, &id) == E_FAIL && id == 0x5a5a5a5a,
683 "slot 3 refuses a <TitleId> that is not hex");
684 write_config("<Game><TitleId>123456789</TitleId></Game>");
685 check(reinterpret_cast<TitleId>(slot(g, 3))(g, &id) == E_FAIL, "slot 3 refuses more than 8 hex digits");
686 DeleteFileA(config.c_str());
687 RemoveDirectoryA(game.c_str());
688 SetEnvironmentVariableA("LEONIDA_GAME_DIR", nullptr);
689 reinterpret_cast<LaunchNew>(slot(g, 4))(g, "other.exe", "", nullptr);
690 check(true, "slot 4 (void XLaunchNewGame) returns offline");
691 check(reinterpret_cast<Restart>(slot(g, 5))(g, "--restarted", 0) == S_OK,
692 "slot 5 (XLaunchRestartOnCrash) succeeds offline");
693 release(g);
694 }
695 }
515 check(uninit_api() == S_OK, "UninitializeApiImpl succeeds"); 696 check(uninit_api() == S_OK, "UninitializeApiImpl succeeds");
516 697
517 HMODULE k32 = load_w(L"kernel32.dll"); 698 HMODULE k32 = load_w(L"kernel32.dll");
diff --git a/runtime/test/xgameruntime_user_test.cpp b/runtime/test/xgameruntime_user_test.cpp
new file mode 100644
index 000000000..3a9b4c8e0
--- /dev/null
+++ b/runtime/test/xgameruntime_user_test.cpp
@@ -0,0 +1,227 @@
1// XUserImpl through QueryApiImpl, called the way xgameruntime.lib's XUser* thunks call it: QueryApiImpl with the
2// class id (or a later interface id), one vtable slot with `this` first. Slots follow xgameruntime-docs' layout;
3// arguments and expected values follow the public GDK reference. No game data; nothing online.
4//
5// xgameruntime_user_test the offline user, its handles, gamertag "Player"
6// xgameruntime_user_test --expect-gamertag TAG the same, run with LEONIDA_GAMERTAG=TAG
7#include <windows.h>
8
9#include <cstdint>
10#include <cstdio>
11#include <cstring>
12
13#include <XAsync.h>
14#include <XAsyncProvider.h>
15#include <XTaskQueue.h>
16
17#include "shims.h"
18
19namespace rt::shims {
20long xgameruntime_user_open_handles();
21}
22
23namespace {
24
25int g_checks = 0;
26int g_failures = 0;
27
28void check(bool condition, const char* what) {
29 ++g_checks;
30 std::printf("%s %s\n", condition ? "PASS" : "FAIL", what);
31 if (!condition) ++g_failures;
32}
33
34using XUserHandle = void*;
35struct XUserLocalId {
36 uint64_t value;
37};
38
39constexpr HRESULT E_GAMEUSER_USER_NOT_FOUND = static_cast<HRESULT>(0x89245104);
40constexpr HRESULT E_GAMEUSER_DEFERRAL_NOT_AVAILABLE = static_cast<HRESULT>(0x89245103);
41constexpr HRESULT E_GAMEUSER_FAILED_TO_GET_TOKEN = static_cast<HRESULT>(0x89245111);
42
43constexpr GUID kUserClass = {0x01acd177, 0x91f9, 0x4763, {0xa3, 0x8e, 0xcc, 0xbb, 0x55, 0xce, 0x32, 0xe0}};
44constexpr GUID kUserImpl3 = {0x1bf2f8c5, 0xd507, 0x4e52, {0xbb, 0x05, 0xf7, 0x26, 0xd0, 0xe7, 0x11, 0x61}};
45constexpr GUID kUserImpl6 = {0x5131d685, 0x4394, 0x4ee6, {0x8c, 0x18, 0xbf, 0xb5, 0xd4, 0xae, 0xf1, 0xff}};
46constexpr GUID kGamertag = {0xcef4fac0, 0x7676, 0x4a94, {0xa1, 0x19, 0x4c, 0x43, 0xf9, 0xeb, 0x5b, 0x74}};
47constexpr GUID kOther = {0x973a344e, 0x24bf, 0x4d0f, {0x84, 0x57, 0x56, 0xc5, 0x34, 0x89, 0x2b, 0x29}}; // XGameImpl
48
49using Query = HRESULT(WINAPI*)(const GUID*, REFIID, void**);
50using Fn = void*;
51Fn slot(void* obj, int index) { return (*static_cast<Fn* const*>(obj))[index]; }
52template <class F> F at(void* obj, int index) { return reinterpret_cast<F>(slot(obj, index)); }
53
54// Waits for an XAsyncBlock on the process queue, as a title polling XAsyncGetStatus(wait = true) does.
55bool finished(XAsyncBlock* async) { return XAsyncGetStatus(async, true) != E_PENDING; }
56
57} // namespace
58
59int main(int argc, char** argv) {
60 const char* expect_tag = "Player";
61 if (argc == 3 && std::strcmp(argv[1], "--expect-gamertag") == 0) expect_tag = argv[2];
62 std::printf("xgameruntime_user_test: XUserImpl through QueryApiImpl (gamertag \"%s\")\n", expect_tag);
63
64 auto query = reinterpret_cast<Query>(rt::shims::find("xgameruntime.dll", "QueryApiImpl"));
65 check(query != nullptr, "QueryApiImpl is registered");
66 if (!query) return 1;
67
68 // ---- the object and its interfaces ----
69 void* user = nullptr;
70 check(query(&kUserClass, kUserClass, &user) == S_OK && user, "QueryApiImpl hands out XUserImpl for its class id");
71 if (!user) return 1;
72 void* user6 = nullptr;
73 void* user3 = nullptr;
74 check(query(&kUserClass, kUserImpl6, &user6) == S_OK && user6 == user &&
75 query(&kUserClass, kUserImpl3, &user3) == S_OK && user3 == user,
76 "IXUserImpl3 and IXUserImpl6 (later versions of the same vtable) answer with the same object");
77 void* tag_face = nullptr;
78 check(query(&kUserClass, kGamertag, &tag_face) == S_OK && tag_face && tag_face != user,
79 "IXUserGamertagImpl is a second interface of the object");
80 void* none = reinterpret_cast<void*>(1);
81 check(query(&kUserClass, kOther, &none) == E_NOINTERFACE && none == nullptr,
82 "an interface the class doesn't have is E_NOINTERFACE with a cleared out pointer");
83
84 // ---- XUserAddAsync / XUserAddResult (slots 7, 8) ----
85 using AddAsync = HRESULT(STDMETHODCALLTYPE*)(void*, uint32_t, XAsyncBlock*);
86 using AddResult = HRESULT(STDMETHODCALLTYPE*)(void*, XAsyncBlock*, XUserHandle*);
87 XAsyncBlock add{};
88 check(at<AddAsync>(user, 7)(user, 0x01, &add) == S_OK, "XUserAddAsync(AddDefaultUserSilently) starts");
89 check(finished(&add) && XAsyncGetStatus(&add, false) == S_OK, "it completes with S_OK");
90 XUserHandle h = nullptr;
91 check(at<AddResult>(user, 8)(user, &add, &h) == S_OK && h != nullptr, "XUserAddResult hands out a user handle");
92 XAsyncBlock bad{};
93 check(at<AddAsync>(user, 7)(user, 0x01 | 0x02, &bad) == E_INVALIDARG,
94 "AllowGuests with AddDefaultUserSilently is refused (a guest can't be the default user)");
95 XAsyncBlock picker{};
96 XUserHandle h_picker = nullptr;
97 check(at<AddAsync>(user, 7)(user, 0x00, &picker) == S_OK && finished(&picker) &&
98 at<AddResult>(user, 8)(user, &picker, &h_picker) == S_OK && h_picker,
99 "XUserAddAsync without a silent option also adds the offline user (no account picker offline)");
100
101 // ---- identity (slots 5, 6, 9-14, 19, 20) ----
102 using Compare = int32_t(STDMETHODCALLTYPE*)(void*, XUserHandle, XUserHandle);
103 using MaxUsers = HRESULT(STDMETHODCALLTYPE*)(void*, uint32_t*);
104 using GetLocalId = HRESULT(STDMETHODCALLTYPE*)(void*, XUserHandle, XUserLocalId*);
105 using FindLocal = HRESULT(STDMETHODCALLTYPE*)(void*, XUserLocalId, XUserHandle*);
106 using GetId = HRESULT(STDMETHODCALLTYPE*)(void*, XUserHandle, uint64_t*);
107 using FindId = HRESULT(STDMETHODCALLTYPE*)(void*, uint64_t, XUserHandle*);
108 using GetBool = HRESULT(STDMETHODCALLTYPE*)(void*, XUserHandle, bool*);
109 using GetU32 = HRESULT(STDMETHODCALLTYPE*)(void*, XUserHandle, uint32_t*);
110 using CheckPrivilege = HRESULT(STDMETHODCALLTYPE*)(void*, XUserHandle, uint32_t, uint32_t, bool*, uint32_t*);
111 uint32_t max_users = 0;
112 check(at<MaxUsers>(user, 6)(user, &max_users) == S_OK && max_users == 1, "XUserGetMaxUsers: one local user");
113 check(at<Compare>(user, 5)(user, h, h_picker) == 0, "XUserCompare: both handles name the same user");
114 XUserLocalId local{};
115 check(at<GetLocalId>(user, 9)(user, h, &local) == S_OK && local.value != 0, "XUserGetLocalId: a non-zero local id");
116 uint64_t xuid = 0;
117 check(at<GetId>(user, 11)(user, h, &xuid) == S_OK && xuid != 0, "XUserGetId: a non-zero user id");
118 XUserHandle by_local = nullptr, by_id = nullptr, missing = reinterpret_cast<XUserHandle>(1);
119 check(at<FindLocal>(user, 10)(user, local, &by_local) == S_OK && by_local &&
120 at<Compare>(user, 5)(user, by_local, h) == 0,
121 "XUserFindUserByLocalId finds it");
122 check(at<FindLocal>(user, 10)(user, XUserLocalId{local.value + 1}, &missing) == E_GAMEUSER_USER_NOT_FOUND &&
123 missing == nullptr,
124 "another local id is E_GAMEUSER_USER_NOT_FOUND");
125 check(at<FindId>(user, 12)(user, xuid, &by_id) == S_OK && by_id, "XUserFindUserById finds it");
126 missing = reinterpret_cast<XUserHandle>(1);
127 check(at<FindId>(user, 12)(user, xuid + 1, &missing) == E_GAMEUSER_USER_NOT_FOUND && missing == nullptr,
128 "another user id is E_GAMEUSER_USER_NOT_FOUND");
129 bool guest = true;
130 check(at<GetBool>(user, 13)(user, h, &guest) == S_OK && !guest, "XUserGetIsGuest: not a guest");
131 uint32_t state = 99, age = 99;
132 check(at<GetU32>(user, 14)(user, h, &state) == S_OK && state == 0, "XUserGetState: SignedIn (0)");
133 check(at<GetU32>(user, 19)(user, h, &age) == S_OK && age == 3, "XUserGetAgeGroup: Adult (3)");
134 bool has = false;
135 uint32_t reason = 99;
136 check(at<CheckPrivilege>(user, 20)(user, h, 0, 254, &has, &reason) == S_OK && has && reason == 0,
137 "XUserCheckPrivilege: granted, deny reason None (0)");
138 check(at<GetBool>(user, 13)(user, nullptr, &guest) == E_INVALIDARG, "a null handle is E_INVALIDARG");
139
140 // ---- XUserResolvePrivilegeWithUiAsync / Result (21, 22) ----
141 using ResolveAsync = HRESULT(STDMETHODCALLTYPE*)(void*, XUserHandle, uint32_t, uint32_t, XAsyncBlock*);
142 using ResolveResult = HRESULT(STDMETHODCALLTYPE*)(void*, XAsyncBlock*);
143 XAsyncBlock resolve{};
144 check(at<ResolveAsync>(user, 21)(user, h, 0, 254, &resolve) == S_OK && finished(&resolve) &&
145 at<ResolveResult>(user, 22)(user, &resolve) == S_OK,
146 "XUserResolvePrivilegeWithUiAsync completes with S_OK (nothing to resolve)");
147
148 // ---- tokens: not available offline (23) ----
149 using TokenAsync = HRESULT(STDMETHODCALLTYPE*)(void*, XUserHandle, uint32_t, const char*, const char*, size_t,
150 const void*, size_t, const void*, XAsyncBlock*);
151 XAsyncBlock token{};
152 check(at<TokenAsync>(user, 23)(user, h, 0, "GET", "https://example.invalid/", 0, nullptr, 0, nullptr, &token) ==
153 E_GAMEUSER_FAILED_TO_GET_TOKEN,
154 "XUserGetTokenAndSignatureAsync fails before starting: E_GAMEUSER_FAILED_TO_GET_TOKEN");
155
156 // ---- change events, sign-out deferral (33-36) ----
157 using Register = HRESULT(STDMETHODCALLTYPE*)(void*, XTaskQueueHandle, void*, void(CALLBACK*)(void*, XUserLocalId, uint32_t),
158 XTaskQueueRegistrationToken*);
159 using Unregister = bool(STDMETHODCALLTYPE*)(void*, XTaskQueueRegistrationToken, bool);
160 using Deferral = HRESULT(STDMETHODCALLTYPE*)(void*, void**);
161 auto on_change = [](void*, XUserLocalId, uint32_t) {};
162 XTaskQueueRegistrationToken reg{};
163 check(at<Register>(user, 33)(user, nullptr, nullptr, on_change, &reg) == S_OK && reg.token != 0,
164 "XUserRegisterForChangeEvent hands out a token");
165 check(at<Unregister>(user, 34)(user, reg, false) && at<Unregister>(user, 34)(user, reg, false) &&
166 at<Unregister>(user, 34)(user, XTaskQueueRegistrationToken{999}, false),
167 "XUserUnregisterForChangeEvent: true, also with wait = false for a token already gone or never issued "
168 "(false would mean still pending, which never happens offline)");
169 void* deferral = reinterpret_cast<void*>(1);
170 check(at<Deferral>(user, 35)(user, &deferral) == E_GAMEUSER_DEFERRAL_NOT_AVAILABLE && deferral == nullptr,
171 "XUserGetSignOutDeferral: E_GAMEUSER_DEFERRAL_NOT_AVAILABLE (nothing signs out offline)");
172
173 // ---- IXUserImpl2: XUserAddByIdWithUiAsync / Result (37, 38) ----
174 using AddByIdAsync = HRESULT(STDMETHODCALLTYPE*)(void*, uint64_t, XAsyncBlock*);
175 XAsyncBlock by_id_add{}, by_other{};
176 XUserHandle h_by_id = nullptr, h_other = reinterpret_cast<XUserHandle>(1);
177 check(at<AddByIdAsync>(user, 37)(user, xuid, &by_id_add) == S_OK && finished(&by_id_add) &&
178 at<AddResult>(user, 38)(user, &by_id_add, &h_by_id) == S_OK && h_by_id,
179 "XUserAddByIdWithUiAsync with the local user's id adds it");
180 check(at<AddByIdAsync>(user, 37)(user, xuid + 1, &by_other) == S_OK && finished(&by_other) &&
181 at<AddResult>(user, 38)(user, &by_other, &h_other) == E_GAMEUSER_USER_NOT_FOUND && h_other == nullptr,
182 "with another id it completes with E_GAMEUSER_USER_NOT_FOUND");
183
184 // ---- IXUserImpl4: XUserIsStoreUser (42) ----
185 using IsStore = bool(STDMETHODCALLTYPE*)(void*, XUserHandle);
186 check(at<IsStore>(user, 42)(user, h) && at<IsStore>(user, 42)(user, nullptr),
187 "XUserIsStoreUser: true, also for a null handle (_In_opt_; always true on console)");
188 using Unknown = HRESULT(STDMETHODCALLTYPE*)(void*, XUserHandle, size_t, char*, size_t*);
189 char probe[16] = "untouched";
190 size_t probe_used = 42;
191 check(at<Unknown>(user, 15)(user, h, sizeof(probe), probe, &probe_used) == E_NOTIMPL,
192 "slot 15 (no public signature) answers E_NOTIMPL rather than S_OK with nothing written");
193
194 // ---- IXUserGamertagImpl: XUserGetGamertag (3) ----
195 using GetTag = HRESULT(STDMETHODCALLTYPE*)(void*, XUserHandle, uint32_t, size_t, char*, size_t*);
196 auto tag = at<GetTag>(tag_face, 3);
197 char buf[101] = {};
198 size_t used = 0;
199 const size_t want = std::strlen(expect_tag) + 1;
200 check(tag(tag_face, h, 0, sizeof(buf), buf, &used) == S_OK && std::strcmp(buf, expect_tag) == 0 && used == want,
201 "XUserGetGamertag(Classic): the gamertag, gamertagUsed counting the terminator");
202 check(tag(tag_face, h, 3, sizeof(buf), buf, &used) == S_OK && std::strcmp(buf, expect_tag) == 0,
203 "UniqueModern of a classic gamertag: the same text, no '#' and no suffix");
204 check(tag(tag_face, h, 1, sizeof(buf), buf, &used) == S_OK && std::strcmp(buf, expect_tag) == 0,
205 "Modern: the classic gamertag when none is set");
206 check(tag(tag_face, h, 2, sizeof(buf), buf, &used) == S_OK && buf[0] == 0 && used == 1,
207 "ModernSuffix: empty (just the terminator)");
208 check(tag(tag_face, h, 0, want - 1, buf, &used) == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER),
209 "a buffer one byte short is E_INSUFFICIENT_BUFFER");
210 check(tag(tag_face, h, 7, sizeof(buf), buf, &used) == E_INVALIDARG, "an unknown component is E_INVALIDARG");
211
212 // ---- handles: duplicate, close, all accounted for (3, 4) ----
213 using Dup = HRESULT(STDMETHODCALLTYPE*)(void*, XUserHandle, XUserHandle*);
214 using Close = void(STDMETHODCALLTYPE*)(void*, XUserHandle);
215 XUserHandle dup = nullptr;
216 check(at<Dup>(user, 3)(user, h, &dup) == S_OK && dup && dup != h && at<Compare>(user, 5)(user, dup, h) == 0,
217 "XUserDuplicateHandle: a new handle for the same user");
218 check(rt::shims::xgameruntime_user_open_handles() == 6, "six handles are open: two adds, two finds, an add by id and a duplicate");
219 for (XUserHandle x : {h, h_picker, by_local, by_id, h_by_id, dup}) at<Close>(user, 4)(user, x);
220 check(rt::shims::xgameruntime_user_open_handles() == 0, "XUserCloseHandle closes each of them");
221 at<Close>(user, 4)(user, h); // a double close: the handle is looked up, not read, so this is a no-op
222 check(rt::shims::xgameruntime_user_open_handles() == 0 && at<GetBool>(user, 13)(user, h, &guest) == E_INVALIDARG,
223 "a closed handle is refused and closing it again does nothing");
224
225 std::printf("xgameruntime_user_test: %d of %d checks failed\n", g_failures, g_checks);
226 return g_failures ? 1 : 0;
227}
diff --git a/runtime/test/xmem_test.cpp b/runtime/test/xmem_test.cpp
index 1ad4080f7..bd38cab39 100644
--- a/runtime/test/xmem_test.cpp
+++ b/runtime/test/xmem_test.cpp
@@ -10,8 +10,12 @@
10#include <cstdint> 10#include <cstdint>
11#include <cstdio> 11#include <cstdio>
12#include <cstring> 12#include <cstring>
13#include <fstream>
14#include <sstream>
15#include <string>
13 16
14#include "shims.h" 17#include "shims.h"
18#include "startup_trace.h"
15 19
16namespace { 20namespace {
17 21
@@ -79,10 +83,26 @@ void test_working_set(XMemGetWorkingSetStatisticsFn get_stats) {
79 const BOOL ok = get_stats(kMeasuredKind, stats); 83 const BOOL ok = get_stats(kMeasuredKind, stats);
80 check(ok != FALSE, "XMemGetWorkingSetStatistics(kind, 64-byte out) returns TRUE"); 84 check(ok != FALSE, "XMemGetWorkingSetStatistics(kind, 64-byte out) returns TRUE");
81 85
86 uint64_t total_memory = 0;
87 std::memcpy(&total_memory, stats + 0, sizeof(total_memory));
88 check(ok != FALSE && total_memory != 0, "XMemGetWorkingSetStatistics writes a non-zero total memory at +0");
89
90 MEMORYSTATUSEX ms{sizeof(ms)};
91 if (GlobalMemoryStatusEx(&ms) && ms.ullTotalPhys != 0) {
92 check(ok != FALSE && total_memory == ms.ullTotalPhys,
93 "XMemGetWorkingSetStatistics total memory (+0) matches GlobalMemoryStatusEx ullTotalPhys");
94 } else {
95 check(ok != FALSE && total_memory == 12ULL * 1024 * 1024 * 1024,
96 "XMemGetWorkingSetStatistics total memory (+0) falls back to 12 GiB title limit");
97 }
98
82 uint64_t working_set = 0; 99 uint64_t working_set = 0;
83 std::memcpy(&working_set, stats + 8, sizeof(working_set)); 100 std::memcpy(&working_set, stats + 8, sizeof(working_set));
84 check(ok != FALSE && working_set != 0, "XMemGetWorkingSetStatistics writes a non-zero size at +8"); 101 check(ok != FALSE && working_set != 0, "XMemGetWorkingSetStatistics writes a non-zero size at +8");
85 102
103 check(ok != FALSE && total_memory >= working_set,
104 "XMemGetWorkingSetStatistics total memory (+0) >= working set (+8)");
105
86 bool tail_untouched = true; 106 bool tail_untouched = true;
87 for (size_t i = 16; i < sizeof(stats); ++i) { 107 for (size_t i = 16; i < sizeof(stats); ++i) {
88 if (stats[i] != 0xa5) { 108 if (stats[i] != 0xa5) {
@@ -204,6 +224,48 @@ void test_virtual_alloc(XMemVirtualAllocFn virtual_alloc, XMemGetWriteWatchFn ge
204 "nonzero XMem allocation attributes are rejected before host allocation"); 224 "nonzero XMem allocation attributes are rejected before host allocation");
205} 225}
206 226
227// gta6rt --trace: one "xmem_attributes" event per distinct raw attribute word and API, none with the trace off.
228void test_attribute_trace(XMemAllocFn alloc, XMemFreeFn free_mem) {
229 wchar_t temp[MAX_PATH];
230 GetTempPathW(MAX_PATH, temp);
231 const std::wstring path =
232 std::wstring(temp) + L"xmem_trace_test_" + std::to_wstring(GetCurrentProcessId()) + L".jsonl";
233 DeleteFileW(path.c_str());
234
235 void* untraced = alloc(64, 0x1111); // trace not open yet: nothing to write, nothing to crash
236 check(untraced != nullptr, "XMemAlloc with the trace off still allocates");
237 free_mem(untraced, 0x1111);
238
239 check(rt::startup_trace::open(path.c_str()), "open the startup trace file");
240 void* a = alloc(4096, 0x5e50000);
241 void* b = alloc(8192, 0x5e50000); // same word again: no second event
242 void* c = alloc(16, 0x99);
243 free_mem(a, 0x5e50000);
244 free_mem(b, 0x5e50000); // same word again: no second event
245 free_mem(c, 0x99);
246 free_mem(nullptr, 0x77); // a free-only word is recorded too
247 rt::startup_trace::close();
248
249 std::ifstream in(path);
250 std::stringstream text;
251 text << in.rdbuf();
252 const std::string log = text.str();
253 auto count = [&](const std::string& needle) {
254 int n = 0;
255 for (size_t at = log.find(needle); at != std::string::npos; at = log.find(needle, at + 1)) ++n;
256 return n;
257 };
258 check(count("\"kind\":\"xmem_attributes\"") == 5, "five events: two XMemAlloc words and three XMemFree words");
259 check(count("\"api\":\"XMemAlloc\",\"attributes\":\"0x5e50000\",\"size\":4096") == 1,
260 "XMemAlloc 0x5e50000 is recorded once, with the size of the first call");
261 check(count("\"api\":\"XMemAlloc\",\"attributes\":\"0x99\",\"size\":16") == 1, "XMemAlloc 0x99 is recorded once");
262 check(count("\"api\":\"XMemFree\",\"attributes\":\"0x5e50000\"") == 1, "XMemFree 0x5e50000 is recorded once");
263 check(count("\"api\":\"XMemFree\",\"attributes\":\"0x77\"") == 1, "XMemFree 0x77 is recorded");
264 check(count("\"attributes\":\"0x1111\"") == 0, "nothing was recorded while the trace was off");
265 check(count("\"caller\":\"") == 5, "every event names its caller");
266 DeleteFileW(path.c_str());
267}
268
207using HostVirtualAllocFn = void*(WINAPI*)(void*, SIZE_T, DWORD, DWORD); 269using HostVirtualAllocFn = void*(WINAPI*)(void*, SIZE_T, DWORD, DWORD);
208 270
209// RT-217: a title's kernel32!VirtualAlloc carries the console's MEM_GRAPHICS / MEM_TITLE type bits, which the host 271// RT-217: a title's kernel32!VirtualAlloc carries the console's MEM_GRAPHICS / MEM_TITLE type bits, which the host
@@ -277,6 +339,7 @@ int main() {
277 if (virtual_alloc && get_write_watch && reset_write_watch) { 339 if (virtual_alloc && get_write_watch && reset_write_watch) {
278 test_virtual_alloc(virtual_alloc, get_write_watch, reset_write_watch); 340 test_virtual_alloc(virtual_alloc, get_write_watch, reset_write_watch);
279 } 341 }
342 test_attribute_trace(alloc, free_mem);
280 343
281 test_title_virtual_alloc(); 344 test_title_virtual_alloc();
282 345