diff --git a/docs/README.md b/docs/README.md index fabeabda4..923b50a24 100644 --- a/docs/README.md +++ b/docs/README.md @@ -10,6 +10,7 @@ method, scope and caveats. No game data is included. |---|---| | [design.md](design.md) | Overall project design, asset status, translator contract and open blockers. | | [related_projects.md](related_projects.md) | Prior art we may read and the licence boundaries on it. | +| [ztrx-gap-analysis.md](ztrx-gap-analysis.md) | ztrx against the runtime, from source: licence, gap table; not run. | | [rpf.md](rpf.md) | RPF9 archive layout, the carve tools and the unreadable encrypted TOC. | | [linux.md](linux.md) | Linux in one page: what runs natively and what runs under Wine or Proton, the Ubuntu packages, `Build.sh`, the runtime cross-build, and why there is no native Linux `gta6rt`. | | [testing.md](testing.md) | Running the GPU tests on your own GPU: setup per OS, wave64 emulation, running without a GPU on Mesa llvmpipe, and known problems. | diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 59ea5179e..639cfc099 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2455,7 +2455,9 @@ The trace will enumerate them. created with `VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT` when the device supports that usage with the requested image format and flags, moved to `GENERAL` and zero-filled on the host at creation, and copied with `vkCopyMemoryToImageEXT`/ - `vkCopyImageToMemoryEXT` while they stay in `GENERAL` (D3D12's `COMMON`). Every other case (no extension, a + `vkCopyImageToMemoryEXT` while they stay in `GENERAL` (D3D12's `COMMON`). A driver can accept the usage and then + name no memory type for the image (NVIDIA 582.66 on a GTX 1070 Ti: `memoryTypeBits` 0 with the usage, 0x82 + without it); the image is then made again without the usage. Every other case (no extension, such an image, a texture a barrier has moved, a default-heap texture, which D3D12 does not allow but the layer copies and logs) is a `CopyTextureRegion` from or to a host-visible staging buffer, replayed on the device's queue and waited for, so the layout tracker and a first use's zero fill behave exactly as for the application's own copies. @@ -2511,7 +2513,10 @@ The trace will enumerate them. device does on purpose (`d3d12_vulkan_device_test` fails on a `TRUE`). The PC runtime answers differently: on an RTX 4090 (driver 621.14) and on WARP it reports the capability as supported, and a list with `Offset` 16 and `RowPitch` 260 for an `R8G8B8A8_UNORM` footprint closes with `S_OK` (measured with a stand-alone D3D12 program, - Windows 11 26200). The layer cannot simply say the same: Vulkan takes a copy's buffer offset as a multiple of + Windows 11 26200). An older PC runtime keeps the rule: on Windows 10 22H2 (`d3d12.dll` and `d3d10warp.dll` + 10.0.19041.3636) the query for `D3D12_FEATURE_D3D12_OPTIONS13` answers `E_INVALIDARG`, and WARP and a GTX 1070 Ti + close such a list with `E_INVALIDARG`, as the layer does; `d3d12_close_parity_test` counts its three cases as + matches on such a WARP. The layer cannot simply say the same: Vulkan takes a copy's buffer offset as a multiple of the texel block size and its row length in texels (VUID-vkCmdCopyBufferToImage-dstImage-07975), while the capability lifts D3D12's two alignments and is not documented as keeping offsets and pitches texel multiples (not tested here), so a footprint that is not texel-aligned would have to be repacked through scratch memory @@ -2557,7 +2562,7 @@ The trace will enumerate them. `d3d12_clear_test` (renamed from `d3d12_uint_clear_test` in #525, D3D-45) compares full and rectangular D3D12 readbacks with WARP over eleven integer input sets on every UINT and SINT render-target format it lists, beside the UNORM/SNORM/FLOAT and depth/stencil cases. ctest runs only its `--rgb9e5` mode (`d3d12_rgb9e5_rtv`), so the - WARP comparison is run by hand until #521's 0.5 tie rounding lands (`runtime/CMakeLists.txt`). + WARP comparison is run by hand until #521's 0.5 tie rounding lands (`runtime/cmake/d3d12_vulkan.cmake`). `clear_color_test` checks both replay paths without a GPU, including unchanged float values. This does not add typed-view reinterpretation of typeless resources or new integer formats. - **RGBA8 typeless RTV clears:** explicit UNORM, SRGB, UINT, SINT and SNORM RTVs on a diff --git a/docs/design.md b/docs/design.md index 4af74867f..18c62c49c 100644 --- a/docs/design.md +++ b/docs/design.md @@ -114,7 +114,7 @@ SPIRV-Tools 2026.1 validates this fixture. Version 2025.1 reports a known error It sets up MSVC through `vcvars64.bat` and builds at BelowNormal priority on half the cores, writing to `runtime\build\`. If VS's "C++ CMake tools" component is installed, it uses CMake and Ninja. Otherwise it calls `cl` directly. That component may not be installed, and the devkitPro MSYS `cmake` on PATH can't build MSVC projects. When you -add a source file, add it to `runtime\CMakeLists.txt` and to the file list in `build_runtime.ps1`. +add a source file, add it to `runtime\cmake\windows_runtime.cmake` and to the file list in `build_runtime.ps1`. ## Asset status (no exe needed) diff --git a/docs/directstorage.md b/docs/directstorage.md index dc2987a55..c7d933275 100644 --- a/docs/directstorage.md +++ b/docs/directstorage.md @@ -106,7 +106,7 @@ The first boot with the executable settles most of this: the dry-run report show 7. a zero size: a success that touches no memory (an assumption: the reference does not say); 8. a range past the end of the file (`E_DSTORAGE_END_OF_FILE`), then a destination or source the process cannot access (`E_DSTORAGE_ACCESS_VIOLATION`; the worker survives it). This needs asynchronous exceptions under - clang-cl, so `runtime/CMakeLists.txt` builds `dstorage.cpp` with `/EHa` there; MSVC always catches it. + clang-cl, so `runtime/cmake/windows_runtime.cmake` builds `dstorage.cpp` with `/EHa` there; MSVC always catches it. Step 7 does not apply to a zlib request (its `DestinationSize` is never 0 after step 5); its stream fails as described next. diff --git a/docs/pipeline_check.md b/docs/pipeline_check.md index 62e5417a3..5e8872cad 100644 --- a/docs/pipeline_check.md +++ b/docs/pipeline_check.md @@ -306,8 +306,8 @@ A driver compiles on the thread that creates the shader module or the pipeline, the shader's control-flow nesting. On Windows a thread that asks for no stack size gets the reserve written in the executable's PE header, 1 MB by default. That is the checker's main thread and every `std::thread` worker. -`vk_pipeline_check` is linked with an **8 MB** reserve: `/STACK:8388608` in `runtime/CMakeLists.txt` and on the -checker's `cl` line in `scripts/build_runtime.ps1`. The CTest `vk_pipeline_check_stack` reads `SizeOfStackReserve` +`vk_pipeline_check` is linked with an **8 MB** reserve: `/STACK:8388608` in `runtime/cmake/vulkan_tools.cmake` and on +the checker's `cl` line in `scripts/build_runtime.ps1`. The CTest `vk_pipeline_check_stack` reads `SizeOfStackReserve` back from the built file (`runtime/test/check_stack_reserve.cmake`; the program is not run), and `tests/test_build_runtime_fallback.py` keeps the two numbers the same. @@ -336,8 +336,9 @@ Not measured: other AMD GPU families, other vendors' Windows drivers, and a corp (`runtime/shims/d3d12_vulkan_device.cpp`), so there the compiler runs on a game thread. The entry thread has 8 MB from `run_entry` (`runtime/shims/process_shim.h`). A thread the game starts with `dwStackSize` 0, a thread-pool thread and a `std::thread` of the shims get the reserve in `gta6rt.exe`'s header, because the game's `CreateThread` -is Windows' own. `gta6rt` is therefore linked with the same 8 MB (`GTA6RT_STACK` in `runtime/CMakeLists.txt`, and -the loader's `cl` line in `scripts/build_runtime.ps1`). The CTest `gta6rt_stack` reads the header, and +is Windows' own. `gta6rt` is therefore linked with the same 8 MB (`GTA6RT_STACK` in +`runtime/cmake/windows_runtime.cmake`, and the loader's `cl` line in `scripts/build_runtime.ps1`). The CTest +`gta6rt_stack` reads the header, and `run_tiny_game_stack` asks Windows from inside a program the loader runs: the entry thread and a thread created with `dwStackSize` 0 both report 8 MB. Not covered: a thread the title creates with an explicit smaller size keeps that size. Which threads the game creates pipelines on is not known without its executable. diff --git a/docs/retail_boot_chain.md b/docs/retail_boot_chain.md index cbe29cf83..fc2e9fcdb 100644 --- a/docs/retail_boot_chain.md +++ b/docs/retail_boot_chain.md @@ -90,7 +90,10 @@ and `state = 0xFFFFFFFF`, which isn't a valid PC state. At the first call, `va` range the title had just reserved, and `desc` is a buffer of that range's size with Xbox bits in `Flags` above the PC flags. The shape matches the console `CreatePlacedResourceX`. A buffer on those pages is imported with `VK_EXT_external_memory_host` where the driver allows it, so the title's writes are the GPU's reads; a driver that -refuses falls back to a committed buffer. A texture gets a committed texture whose `GetGPUVirtualAddress` is the +refuses falls back to a committed buffer. So does a buffer placed inside a page at an offset the driver cannot bind +it at: NVIDIA 582.66 on a GTX 1070 Ti binds such a buffer only at a multiple of 256 bytes, so one placed 64 bytes +into a page is not imported there (`d3d12_existing_heap_test`). +A texture gets a committed texture whose `GetGPUVirtualAddress` is the title's address (the console behavior: a title clears a texture through that pointer), but its pixels do not alias the title's pages yet. Both paths limit `Flags` to the PC bits; the buffer path also makes the Xbox layout word `ROW_MAJOR`. diff --git a/docs/ztrx-gap-analysis.md b/docs/ztrx-gap-analysis.md new file mode 100644 index 000000000..4b2b10ec7 --- /dev/null +++ b/docs/ztrx-gap-analysis.md @@ -0,0 +1,438 @@ +# ztrx compared with Leonida: gap analysis + +Studied 2026-11-25. Leonida side: branch `refactor/layers` at `abdaf16`. ztrx side: a local source snapshot +(folder name `ztrx-main`, no git history, so there is no commit to cite). The study was read-only: nothing was +built or run in either tree, nothing was written into the ztrx folder and no game file was opened. + +Brought up to date at `387cc16` of the same branch: the rows and notes of C2, G7 and G8, section 7 and the new +section 9.1 say what was done since the study. Everything else stands as studied. + +Every statement about ztrx comes from reading its sources and its three documentation pages. Every statement +about Leonida names the file it was read in. Where a part was not read or not compared, the row says so. +No ztrx code is quoted on this page; file and function names are given so a reader can find the place. + +## 1. Licence and origin + +- ztrx is **GPL-3.0-or-later**: its `LICENSE` file is the plain GPLv3 text and its `Cargo.toml` declares + `license = "GPL-3.0-or-later"`. +- Its README names its origin: based on VIctory (Marvisak) and victory-fork (fxceless). +- Leonida is GPL-3.0-or-later too, so the licences are compatible. Adapted code may be used with attribution + and the licence notice, the case [related_projects.md](related_projects.md) describes for SCARAB. +- The house rule of that page still applies: facts first, write the implementation in Leonida's style, do not + copy a whole component because the licence allows it. + +Parts of ztrx carry terms of their own: + +| Part of ztrx | Its terms | What that means here | +|---|---|---| +| `crates/victory-formats/src/texture.rs` | AMD, MIT notice in the file | usable, the notice stays with the code | +| `crates/victory-shader/src/gfx10/opcodes.rs` | Valve, MIT notice in the file | usable, the notice stays | +| `crates/victory-formats/src/xma.rs`, `xma/tables.rs` | follow FFmpeg (LGPL-2.1-or-later) | usable under GPLv3 | +| `crates/victory-loader/src/console_insn.rs` | says it is ported from XCL (GPL-2.0-only) | **do not copy** | + +The last row matters. [related_projects.md](related_projects.md) records XCL as GPL-2.0-only and incompatible +with this repository. The file header in ztrx says the instruction decoder (`console_insn_decode.rs`) is XCL's, +unchanged. This page does not judge ztrx; for Leonida those two files are off limits whatever licence the +surrounding project declares. Leonida does not need them: `runtime/src/cpu_emulation.h` covers the same +instructions from the vendor manuals. + +Result for reuse: ideas and measured facts from ztrx may be used, and code may be adapted with attribution, +except the two XCL-derived files. Nothing was copied for this page, and Leonida's tracked text does not mention +ztrx anywhere yet (searched: every Markdown file, `runtime`, `tools`, `scripts`). + +## 2. How ztrx is laid out and built + +A Rust workspace (edition 2024, minimum Rust 1.88) with 11 packages and about 107,000 lines. 135 Rust files +sit under its `crates` and `apps` folders. + +| Package | Role, from its architecture page | Lines counted | +|---|---|---| +| `victory-core` | settings, the guard against writing game-derived data into the source tree, logging | not counted | +| `victory-pe` | read-only PE32+ and import-library analysis | not counted | +| `victory-loader` | prepare, map, bind and start the title image | 3,684 | +| `victory-hle` | console API implementations and the host pass-through policy | 18,120 | +| `victory-gpu` | console D3D12 objects, command lists and GPU memory on host D3D12 | 36,050 | +| `victory-shader` | console shader containers to host shaders | 41,237 | +| `victory-formats` | texture layouts, audio codecs | not counted | +| `victory-pipeline` | converter trait, content-addressed cache | not counted | +| `victory-game` | title-specific formats, build identities, hooks | not counted | +| `apps/victory` | command-line front end | not counted | +| `xtask` | asset-policy check, git hooks | not counted | + +A stand-in title of its own code (the hle-probe fixture) serves its loader tests. A `diagnostics` feature and a +`diag` profile switch debug output and the D3D12 debug layer on. Its CI workflow and its play script were not +read. + +## 3. How ztrx starts a title + +Entry point: `apps/victory/src/main.rs`, which hands over to `run.rs`. The order read there: + +1. Wait for a previous instance of the title to end (`lifecycle::wait_for_previous`). +2. Read the package's `MicrosoftGame.config`. +3. Mount two drives: `G:` for the package and `T:` for a temporary folder (`files::mount_at`). +4. Set the console model (Series X unless the user says otherwise). +5. Prepare and load the executable, load and bind the DLLs the title ships. +6. Install crash reporting and name a crash log file next to the temporary folder. +7. Load the title's remaining DLLs late, under a loader lock that may be entered again. +8. Start the title's main thread (`spawn_main`). + +How the executable gets into the process (`crates/victory-loader/src/prepare.rs`, `windows.rs`): + +- ztrx patches a **copy** of the executable in its cache folder: the copy is marked as a DLL, loses its entry + point, has its import directory pointed at the terminator, loses its TLS callback pointer, and has the + integrity flag and the checksum cleared. +- The Windows loader then maps that copy as an ordinary module. ztrx binds the imports itself. +- Import order, for every function: ztrx's own implementation, then the host's function when the pass-through + policy allows that DLL, then a DLL the title ships, then a generated stub that names the import when called. +- An executable reads its thread-local block through TLS index 0. Mapped as a DLL it gets another index, so + ztrx rewrites each such read into a call that yields the right slot (`tls.rs`). +- The prepared copy has no entry point and no TLS callbacks, so ztrx's own TLS callback passes thread start and + end on to every attached image (`threads.rs`). + +Leonida reaches the same point by another road: it maps the image itself (`runtime/src/pe_loader.cpp`) and takes +its TLS index from a small anchor DLL (`runtime/src/tls_host.cpp`). Both roads end in title code running +natively with every import bound, so the loader is not where the gap is. + +## 4. The main frame in ztrx + +"Main frame" on this page means the loop a title turns once per frame, whatever it draws: device creation, +queue and list and fence, the frame events (set an interval, schedule the origin event, wait for it and get a +token), and the present call that carries the token to a window. + +- **Device** (`crates/victory-gpu/src/device.rs`): one static object laid out as the title's inlined code + expects, with a table of 160 functions. One byte in the object is kept non-zero so the title's inlined fast + paths call out of line, and the list limits are kept at zero so every command arrives as a call. It answers + interface queries for device versions 1 to 8 and 11 itself. Feature queries are answered from a fixed table + describing the console GPU. GPU addresses are CPU addresses; descriptor handles are plain addresses. +- **Queues and fences** (`queue.rs`, `fence.rs`): submitted lists run on the host GPU and are waited for, so a + fence signal completes at once. Work given to a queue after a wait for a fence value not yet reached is kept + in order and runs when the fence gets there. +- **Frame pacing** (`frame.rs`): one clock, started by the first interval the title sets, with absolute ticks. + A wait for the origin event hands out consecutive frame tokens, also when the wait times out. The four calls + sit at table offsets 0x270 to 0x288, which is slots 78 to 81: the slots Leonida uses. +- **Present** (`host.rs`): a window of its own and a DXGI flip-model swap chain with two buffers. The texture + the title presents is copied into the back buffer in a swap chain format of the same family. A meter shows + the frame rate in the window caption. +- **Host device** (`host.rs`): one D3D12 device at feature level 12_0 and one direct queue, created on first + use. Without a host device ztrx logs a warning and goes on; command lists then do not run. Host objects that + are let go are kept until the submissions that may still use them have finished. +- **DXGI** (`dxgi.rs`): one static adapter that reports the console GPU's vendor, one factory and one output + with one display mode (3840x2160 at 60 Hz unless a variable says otherwise). + +## 5. Finding: ztrx has no Vulkan path + +The brief for this study asked how ztrx handles the GPU on Vulkan. It does not use Vulkan: + +- A search of the whole snapshot for Vulkan, SPIR-V and the usual binding names finds one line, a comment in + `crates/victory-shader/src/bvh.rs` about a public software model of an instruction. +- `victory-gpu` describes itself as the console's D3D12 on host D3D12. Shaders are translated to DXIL by an + emitter of its own (`crates/victory-shader/src/emit`), which also computes the container hash D3D12 checks. +- So device selection, queue setup, swap chain and synchronisation in ztrx are all D3D12 and DXGI. What carries + over to a Vulkan backend is the model (clock, tokens, present by copy, waits), not the calls. + +There is no special handling for the GeForce 10 series either. The NVIDIA-specific places found are general: +a descriptor heap limit of 1,000,000 views, and a wave width of 32 lanes for compute programs written for 64. +A pipeline with a mesh shader is refused, with a message, when the host lacks mesh shaders or shader model 6.6 +(`crates/victory-gpu/src/pipeline/host.rs`, `Host::mesh_shaders` in `host.rs`); there is no replacement path. + +## 6. Gap table + +Legend. Has it: yes, part, no, or ? when it was not established. Risk: low, med, high; it is the risk of the +missing piece or, when nothing is missing, of the assumption both projects share. Effort: none, S (under a +day), M (days), L (weeks), XL (months), ? when no comparison was made. Main frame: yes when the loop of +section 4 cannot turn without it, no when it is optional for that loop. File names in the table are short; +the notes under each table give the paths. + +### 6.1 Loader and process + +| ID | Capability in ztrx | Has it | Where in Leonida | What is missing | Risk | Effort | Main frame | +|---|---|---|---|---|---|---|---| +| L1 | Exe mapped in the process | yes | `pe_loader.cpp` | nothing known | low | none | yes | +| L2 | Imports bound in order | yes | `registry.cpp` | nothing known | low | none | yes | +| L3 | TLS for index-0 reads | yes | `pe_loader.cpp` | nothing known | med | none | yes | +| L4 | Thread notices to images | yes | `tls_host.cpp` | nothing known | med | none | yes | +| L5 | Stubs for unbound imports | yes | `registry.cpp` | nothing | low | none | yes | +| L6 | Zen 2 instructions emulated | yes | `cpu_emulation.h` | nothing | low | none | yes | +| L7 | Main thread started | yes | `process.cpp` | nothing known | low | none | yes | +| L8 | Console drives mounted | yes | `file_system.cpp` | nothing known | low | none | yes | +| L9 | Title DLLs loaded late | yes | `library_loader.cpp` | lock not compared | med | ? | yes | +| L10 | Crash report and crash log | part | `startup_trace.h` | always-on report | med | M | no | +| L11 | Wait for previous instance | no | none | whole feature | low | S | no | +| L12 | Package config read | no | none | reader | med | S | no | +| L13 | Console model choice | yes | `xgameruntime.cpp` | nothing | low | none | no | + +Notes: + +- **L1 to L4.** `runtime/src/pe_loader.h` states the contract: map, relocate, bind through the shim registry, + register the unwind table, install static TLS. `runtime/src/pe_loader.cpp` rewrites an executable's index-0 + TLS reads and handles thread attach and detach through `runtime/src/tls_host.cpp`. + `runtime/src/base_reservation.h` keeps the preferred base free for an image without relocations. +- **L5.** `runtime/shims/registry.cpp` has three policies (log, fail, stop) behind `LEONIDA_UNIMPLEMENTED`; + ztrx has two (trap, return zero). +- **L7.** `rt::process::run_entry` in `runtime/shims/process.cpp` starts the entry point on a thread of its own + with an 8 MiB stack reservation. +- **L8.** `runtime/shims/file_system.cpp` maps `GAME:`, `G:\` and `T:\`, with writes going to an overlay. +- **L9.** `runtime/shims/library_loader.cpp` returns pseudo handles for the DLLs the shims own, and the loader + has a dynamic-load path. Whether a load from inside a module's start-up code is safe was not compared. +- **L10.** `runtime/shims/startup_trace.h` records an exception with a stack, but only under `--trace`. There + is no unhandled-exception filter and no crash log by default. ztrx prints the faulting code first-chance for + the fatal kinds, reports what nobody handles, and appends it to a crash log with the title's last debug + output. Not needed to turn the loop, but it is what makes a later real run readable; it is step 4 of + milestone 1 already. +- **L12.** Only `make_game.py` looks for the package config (to find the game folder); the runtime does not + read it. What ztrx takes from it beyond the title's identity was not established. + +### 6.2 Settings, logging, policy + +| ID | Capability in ztrx | Has it | Where in Leonida | What is missing | Risk | Effort | Main frame | +|---|---|---|---|---|---|---|---| +| C1 | Settings: env, file, default | yes | `config.cpp` | nothing | low | none | no | +| C2 | Log levels, module filter | part | `log.h` | module filter | low | S | no | +| C3 | Repo-write guard at run time | no | none | whole guard | low | S | no | +| C4 | Stand-in title for tests | yes | `tiny_game` | nothing | low | none | no | + +Notes: + +- **C1.** `runtime/core/config.h` and `runtime/core/config.cpp` hold one table for every setting, and + `gta6rt config` prints each value with its source. ztrx has four values (game, cache and data folders, test + titles) with the same lookup order. +- **C2.** ztrx filters by level and by module through one variable, and a plain release build is capped at + info. Leonida printed `[rt] : ...` lines to the error stream without levels when this page was + written; 249 such lines were counted before this study. Since then `runtime/core/log.h` gives each of those + lines one of five levels (error, warn, info, debug, trace) behind one setting, `log.level` (`LEONIDA_LOG`, + described in `runtime/README.md`). The default, debug, prints every line that was printed before. The + filter by module was left out: the level is one value for the whole process. Compiled only; the levels were + never seen in a run. +- **C3.** ztrx refuses to write game-derived data inside its source tree, found by a marker file at the root + and by the path it was compiled from. In Leonida only `tools/progress_dashboard.py` refuses an output folder + inside the repository; the runtime has no such check. + +### 6.3 Console API implementations + +| ID | Capability in ztrx | Has it | Where in Leonida | What is missing | Risk | Effort | Main frame | +|---|---|---|---|---|---|---|---| +| H1 | Table of served DLLs | yes | `registry.cpp` | not compared | med | ? | yes | +| H2 | Host pass-through policy | yes | `pe_loader.cpp` | not compared | med | ? | yes | +| H3 | Pseudo handle, console DLLs | yes | `library_loader.cpp` | nothing | low | none | yes | +| H4 | Offline answers, saves | yes | `xgameruntime.cpp` | not compared | med | ? | no | +| H5 | Audio, media, speech | part | `acphal.cpp` | not compared | med | ? | no | + +Notes: + +- **H1, H2.** ztrx groups its implementations in 26 modules (kernel, files, storage, xmem, xgameruntime and + its user, save, store, package and system parts, gameinput, dstorage, display, the D3D12 entry points, audio + and more). Leonida has 44 files under `runtime/shims`. The two sets were **not** compared function by + function, so this page cannot say which imports only one of them serves. That comparison needs the title's + import list, which `docs/runtime_imports.md` covers on Leonida's side. +- **H5.** Leonida has `runtime/shims/acphal.cpp` and `runtime/shims/xapu_chad.cpp`; ztrx has separate audio, + DSP, media and speech modules. Not compared. + +### 6.4 GPU and the frame + +| ID | Capability in ztrx | Has it | Where in Leonida | What is missing | Risk | Effort | Main frame | +|---|---|---|---|---|---|---|---| +| G1 | Own device, console layout | part | `d3d12_xs_device.cpp` | PC-order proxy | high | L | yes | +| G2 | Device 1 to 8 and 11 answered | part | `d3d12_xs_device.cpp` | follows the host | high | M | yes | +| G3 | Feature answers as RDNA 2 | part | `d3d12_vulkan_device.cpp` | host answers kept | med | M | no | +| G4 | Virtual memory call answered | part | `d3d12_xs.cpp` | accepts, ignores | low | S | no | +| G5 | Queues, lists, fences | yes | `d3d12_xs_device.cpp` | layouts not compared | med | ? | yes | +| G6 | Wait before signal held | yes | `queue_holds.h` | nothing known | low | none | yes | +| G7 | Frame clock and tokens | part | `frame_pacer.h` | no sink set yet | med | S | yes | +| G8 | Present call on the queue | part | `xbox_present.cpp` | slot unmeasured, no sink set | high | S | yes | +| G9 | Window and swap chain | part | `vulkan_present.h` | host path has none | med | M | yes | +| G10 | Host device at level 12_0 | yes | `d3d12_xs.cpp` | nothing | low | none | yes | +| G11 | DXGI adapter and one output | part | `dxgi_com.cpp` | identity differs | med | S | no | +| G12 | Run without a host GPU | no | none | whole mode | low | S | no | +| G13 | Frame-rate meter | no | none | whole feature | low | S | no | +| G14 | Presented frames to files | yes | `vulkan_present.h` | Vulkan only | low | none | no | + +Notes: + +- **G1.** This is the deepest difference. ztrx gives the title an object of its own in the console's layout and + takes every call itself. Leonida's host path wraps a PC device: `runtime/shims/d3d12_xs_device.h` says only + the measured slots are overridden and the rest follow the PC table. Whether the title's inlined code reads + device fields directly, and what the proxy shows at those offsets, was not checked for this page. + [retail_boot_chain.md](retail_boot_chain.md) lists the stops measured so far. Leonida's Vulkan path is closer + to ztrx in shape: `runtime/shims/d3d12_vulkan_device.cpp` implements the objects itself, behind the same + proxy. +- **G2.** The proxy answers only the interfaces it models and otherwise depends on what the wrapped device + offers. Measured on this PC at commit `6591ba9`, before runs with game files were ruled out: the host path + stopped with the runtime's own line "D3D12XboxCreateDevice: proxy creation failed (hr=0x80004002)", which is + the code for an interface that is not there. The host D3D12 of this PC (Windows 10, `d3d12.dll` + 10.0.19041.3636) ends at device version 8. Hypothesis, not proven: the title asks for a newer version. ztrx + answers version 11 from its own object, whatever the host has. +- **G3.** On the Vulkan path Leonida derives its answers from the Vulkan device (the mesh shader tier, for + example, follows the mesh shader extension). On the host path the query is presumed to reach the PC device; + that was not read. Whether the title changes course on any answer is unknown without a run, hence optional. +- **G4.** `runtime/shims/d3d12_xs.cpp` accepts the call and ignores it; ztrx reports all of user space. +- **G5.** Device slots 48 and 73 (queue and list creation in the console's form) are handled and can be moved + by settings. ztrx switches between two table layouts for lists and queues by runtime generation; Leonida's + tables were not compared with them slot by slot. +- **G7.** `runtime/src/frame_pacer.h` models the clock, the origin event, the allowed latency and the tokens, + and `runtime/shims/xbox_present.cpp` exposes the four frame calls on top of it; both are covered by tests. + When this page was written neither was reached from the device proxy: `runtime/shims/d3d12_xs_device.cpp` + answered slots 78 to 80 with a token counter of its own, and its wait returned at once. Since `4ecdc6b` the + proxy has a frame-event sink (`FrameEventSink` in `runtime/shims/d3d12_xs_device.h`): when one is set, the + three calls go to it and its result is the title's. The ctest `xs_proxy_mock` puts a frame pacer on a clock + that only the test moves behind the sink. What is left: nothing sets a sink. No file under `runtime/shims` + or `runtime/src` other than `xbox_present.cpp` itself uses the presentation class, and `gta6rt` creates + none, so a run still gets the proxy's own answers. Slot 81 (the frame statistics) is not routed: the layout + of the console's entries is not measured. Compiled only, never run. +- **G8.** The presentation class has the present call. When this page was written the queue proxy refused + every slot past the public table and logged it. The public numbers for the slot are 30 (older runtime + layout) and 32 (newer), measured by another project on other titles (`runtime/shims/xbox_present.h`); the + slot this title calls is not measured. Since `387cc16` a setting names it: `d3d12.present_x_slot` + (`LEONIDA_XS_PRESENT_X_SLOT`, a queue slot from 19 to 127). It is not set by default, so no slot is taken + on a guess. A call on the named slot goes to the present sink of the queue's device (`PresentSink` in + `runtime/shims/d3d12_xs_device.h`) with the real queue and the title's three words. The ctests + `xs_proxy_mock_present_slot` and `xs_proxy_mock_present_slot_invalid` are the synthetic caller. What is + left: nothing sets a sink, so the call is still refused, and that the slot is right for this title needs a + real run. Compiled only, never run. +- **G9.** `runtime/src/vulkan_present.h` puts a back buffer on screen (scaled copy, two frames in flight, + swap chain rebuilt on resize, blank present, source rectangle), and `runtime/shims/dxgi_swapchain.h` serves + the DXGI front end. On the host D3D12 path nothing was found that owns a window and a swap chain for the + console's present call: the only windows created under `runtime/shims` are a probe in `dxgi_com.cpp` and the + raw-mouse window in `gameinput.cpp`. +- **G11.** `runtime/shims/dxgi_com.cpp` reports the host GPU's vendor on the Vulkan path; ztrx reports the + console GPU's. The mode lists were not compared. + +### 6.5 Shaders and pipelines + +| ID | Capability in ztrx | Has it | Where in Leonida | What is missing | Risk | Effort | Main frame | +|---|---|---|---|---|---|---|---| +| S1 | Translate at pipeline creation | no | `shader_library.h` | prebuilt lookup only | high | XL | no | +| S2 | DXIL emitter, container hash | no | none | whole emitter | high | XL | no | +| S3 | Shader cache on disk | part | `shader_library.h` | not needed yet | low | ? | no | +| S4 | Pipeline library, workers | part | `cached_pso.h` | not compared | med | ? | no | +| S5 | Mesh pipeline refused cleanly | yes | `d3d12_vulkan_device.cpp` | no replacement | high | XL | no | +| S6 | Wave64 on 32-lane hosts | ? | `subgroup_size.h` | not compared | med | ? | no | +| S7 | Ray tests in software | ? | `xdxr_build.h` | not compared | high | ? | no | + +Notes: + +- **Why "no" for the main frame.** The loop of section 4 turns and presents without a single title shader. A + picture with content needs them, so every row here is needed for the step after the main frame. +- **S1, S3.** ztrx translates from the bytes the title passes when it creates a pipeline, and keeps the result + on disk. Leonida translates ahead of time in `make_game.py`; `runtime/src/shader_library.h` finds the + prebuilt SPIR-V by the hash of the native program. A shader that is not in the prebuilt set has no path. +- **S2.** Leonida's translator emits SPIR-V. A DXIL emitter is the direction chosen earlier for the host + D3D12 backend; nothing of it exists on this branch. +- **S4.** `runtime/src/cached_pso.h` and the seeded pipeline cache in `runtime/shims/d3d12_vulkan_device.cpp` + cover the cache blob and a warm start. ztrx also compiles pipelines on worker threads and starts the ones + worth having early; Leonida's side of that was not read. +- **S5.** Both refuse a mesh pipeline when the host cannot run it, and both log why. Neither has a replacement + for hosts without mesh shaders. `runtime/src/vulkan_mesh_limits.h` adds a limit check before creation. +- **S6, S7.** Established by name only: `runtime/src/subgroup_size.h`, `runtime/src/xdxr_build.h` and the + wave64 and BVH test files under `tests/semantic` exist; none was read for this page. On ztrx's side the + title's ray tracing is ordinary compute code plus one hardware instruction for the node test, which ztrx + models in software; its own page says nothing is lit by ray tracing yet. + +## 7. The eight failing `d3d12_*` tests + +ztrx solves none of them, and cannot: they test Leonida's D3D12-on-Vulkan layer against the host's D3D12, and +ztrx has neither a Vulkan layer nor tests of that kind. + +The causes were not determined when this page was written. They were found afterwards, one test at a time: + +| Test | Cause found on this PC | Changed | Now | Commit | +|---|---|---|---|---| +| `d3d12_subresource_copy` | a host-transfer image gets no memory type | the layer | passes | `9dbbad1` | +| `d3d12_r9g9b9e5_uav` | the same | the layer | passes | `9dbbad1` | +| `d3d12_heap_properties` | a tier 1 host refuses mixed-category heaps | the test | passes | `b9f59de` | +| `d3d12_vulkan_device` | the same | the test | passes | `b9f59de` | +| `d3d12_dxr_validation_khr` | no acceleration structure build on this GPU | the test | skips | `8a27ff8` | +| `d3d12_set_descriptor_heaps` | the host serializer refuses two root signature flags | the test | passes | `acfd9ff` | +| `d3d12_close_parity` | this WARP refuses three lists the measured column accepts | the test | passes | `ad9d51b` | +| `d3d12_existing_heap` | the driver binds no buffer 64 bytes into a page | the test | passes | `06372ec` | + +- This PC has a GTX 1070 Ti and Windows 10 with `d3d12.dll` 10.0.19041. The results come from real runs made + before running anything on this PC was ruled out: one run of the whole suite at `06372ec` gave 254 passed, + 14 skipped and 1 failed. +- The one failure left is `root_signature_oracle`, which is not one of the eight. The host serializer refuses + the same two flags there; that test is unchanged. +- One commit changes the layer: when the driver lists the host image copy extension but gives such an image no + memory type, `runtime/shims/d3d12_vulkan_device.cpp` makes the image again without that usage and copies + through staging buffers. The other five change tests. +- Not covered on a PC of this class after the changes: mixed-category heaps against a tier 1 host, the + validation of acceleration structure builds, three copy cases of the close-parity table, and the import of a + buffer the title places inside a page. They are covered on a tier 2 host, a newer GPU and a newer Windows. + +Two habits of ztrx were kept in mind for this, as ideas and not as fixes: ask the host what it can do at run +time and refuse the one object with a clear message (S5), and go on with a warning when a whole device is +missing (G12). + +## 8. What this PC adds + +| Fact | Source | Effect | +|---|---|---| +| Host D3D12 ends at device version 8, shader model 6.5, mesh shader tier 0 | measured on this PC earlier | see below | +| GTX 1070 Ti has no mesh shader, ray query or shading rate extension in Vulkan | the owner's report | unconfirmed | +| No 16-bit float shader arithmetic in Vulkan | the owner's report | unconfirmed | + +- ztrx's README asks for shader model 6.6 and mesh shaders (an RTX 20 series card or newer). On this PC its + mesh pipelines would be refused. What its other translated shaders need from the host was not established. +- The Vulkan facts are the owner's and count as hypotheses until a test queries them on the device. +- For Leonida this means: every item taken over for the main frame has to ask for such a feature at run time + and fall back or report, never require it. + +## 9. Candidates for the main frame, and one open decision + +Needed for the main frame and not finished in Leonida: + +| ID | Item | Testable without the game | Needs a real run for | +|---|---|---|---| +| G7 | Frame calls of the device proxy reach the frame pacer | yes, with a fake clock | the interval values | +| G8 | The present call of the queue proxy reaches the presentation class | yes, with a synthetic caller | the slot | +| G9 | A window and swap chain behind the present call on the chosen backend | yes, with a test window | scaling, HDR | +| G2 | The device answers the interface versions the title asks for | partly | which versions it asks for | +| G1 | The device shows the console's layout where the title reads it | no | everything | + +Left out on purpose: everything marked "no" above, and G1 as a whole, because nothing about it can be checked +without the title. + +The open decision is the backend. The brief asks for the main frame on Vulkan. ztrx, the reference, has it on +host D3D12 only. The direction chosen earlier for Leonida was host D3D12 with a DXIL emitter, with the Vulkan +layer frozen as the second backend, and the host D3D12 of this PC stops below what ztrx asks for. G7 and G8 are +the same work on either backend. G9 exists on Vulkan and is missing on host D3D12. The decision is the +maintainer's and is not made here. + +### 9.1 State at `387cc16` + +Integrated and compiled; NOT verified by running anything. The two steps below were built with MSVC on +Windows 10, and no program, test or game was executed for them. + +| ID | State | Done | Left | Needs a real run for | +|---|---|---|---|---| +| G7 | partly | sink on device slots 78 to 80, `4ecdc6b` | a sink set in `gta6rt`; slot 81 | interval values | +| G8 | partly | sink on the queue and the slot setting, `387cc16` | a sink set in `gta6rt` | the title's slot | +| G9 | not done | nothing | a window and swap chain on the chosen backend | scaling, HDR | +| G2 | not done | nothing | answers from the proxy itself | which versions the title asks for | +| G1 | not done | left out on purpose | everything | everything | + +- **Chosen: G7 and G8.** They are the same work on either backend, so they do not wait for the open decision. + The proxies do not know the presentation class. A sink, a context pointer and one function per call, stands + between them, so the device proxy still needs neither a presenter nor Vulkan. +- **Left of G7 and G8.** An adapter that puts the presentation class behind the two sinks, and `gta6rt` + creating that class. The class takes a window presenter, which exists on the Vulkan path only + (`runtime/shims/xbox_present.h`), so both wait for the backend decision with G9. Until then a run gets the + proxy's own frame answers, and the present call is refused with a log line. +- **Left out: G2.** That the title asks for a device version the host lacks is a hypothesis from one stop + code. Answering versions on a guess could hide the real cause; a run has to name the version first. +- **Left out: G1,** as before: nothing about it can be checked without the title. +- **Features an older GPU lacks.** Neither step asks the GPU for anything, so there is no ray query, mesh + shader, shading rate or 16-bit float requirement to query yet. G9 is the first step that has to ask. +- **Still to run, on another machine or in CI:** the ctests `xs_proxy_mock`, `xs_proxy_mock_present_slot`, + `xs_proxy_mock_present_slot_invalid`, `core_config` and `core_log`, and the text tests under `tests/`. The + expected values of the new checks were written by reading the code and have never been compared with a run. + +## 10. Limits of this study + +- Read in ztrx: the README, the manifest, the architecture and ray tracing pages, the front end's `main.rs` + and `run.rs`, the loader's `lib.rs`, `prepare.rs` and `windows.rs`, the core crate, the HLE crate's `lib.rs` + and `registry.rs`, and in the GPU crate `lib.rs`, `device.rs`, `dxgi.rs`, `frame.rs`, `queue.rs` and the + parts of `host.rs` that create the device, present, and ask for mesh shaders. +- Read as file headers only: the loader's crash, thread, TLS and stub files, and the other GPU files. +- Not read: the HLE modules, the shader crate beyond its top file, the formats, pipeline and game crates, the + asset-policy page, the CI workflow and the play script. How ztrx picks an adapter was not established. +- Nothing here was verified by running either program. Statements about what a title does at run time are + what the two code bases say about it. diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index a6c914e34..6a3801672 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -16,6 +16,14 @@ if(NOT CMAKE_SIZEOF_VOID_P EQUAL 8) message(FATAL_ERROR "gta6rt must be built for x64 (run from an x64 Native Tools prompt or vcvars64.bat)") endif() +# The diagnostics build (the `diag` preset in CMakePresets.json): every target is compiled with LEONIDA_DIAGNOSTICS +# defined. Code that only helps to find a fault (debug and trace logging, captures, stack dumps) goes behind it, so +# a release build neither carries nor runs it. +option(LEONIDA_DIAGNOSTICS "Compile in the diagnostics a release build leaves out" OFF) +if(LEONIDA_DIAGNOSTICS) + add_compile_definitions(LEONIDA_DIAGNOSTICS=1) +endif() + # Portable root-signature model + packer to user SGPRs (no d3d12.h, no windows.h), and the host CPU preflight of # --init/--run (src/host_cpu.h). Built on every OS, so their tests run in the Linux and macOS jobs as well as with the # Windows runtime. @@ -31,8 +39,23 @@ target_link_libraries(root_signature_test PRIVATE gta6rt_root_signature) # AVX, OSXSAVE and XCR0 YMM state from synthetic CPUID/XCR0 words, plus one call on the real host. add_executable(host_cpu_test test/host_cpu_test.cpp src/host_cpu.cpp) target_include_directories(host_cpu_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) +# The core layer: what every other part of the runtime may use, and which uses none of them. It holds the settings +# table (core/config.h): a value comes from its environment variable, else from leonida.toml, else from the default. +# It also holds the log (core/log.h): the levels of the "[rt]" lines. The log's macros need only the header; +# core/log.cpp reads the level from the setting log.level. +add_library(gta6rt_core STATIC + core/config.cpp + core/log.cpp +) +# The table's shape, the order of the three sources, the file reader and leonida.example.toml against the table. +add_executable(core_config_test test/core_config_test.cpp) +target_link_libraries(core_config_test PRIVATE gta6rt_core) +# Which lines each log level prints, a value that is not a level, and log.level through the three sources. +add_executable(core_log_test test/core_log_test.cpp) +target_link_libraries(core_log_test PRIVATE gta6rt_core) if(MSVC) - foreach(_portable gta6rt_root_signature root_signature_test host_cpu_test) + foreach(_portable gta6rt_root_signature root_signature_test host_cpu_test gta6rt_core core_config_test + core_log_test) target_compile_definitions(${_portable} PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) target_compile_options(${_portable} PRIVATE /W4 /permissive- /utf-8) endforeach() @@ -41,474 +64,8 @@ endif() option(LEONIDA_BUILD_WINDOWS_RUNTIME "Build the Windows runtime, its shims and their tests" ${WIN32}) if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) - # Custom CMAKE_CXX_FLAGS can replace MSVC's default /EHsc. Require C++ stack unwinding so error - # paths in the runtime and its libraries still destroy automatic objects when an exception leaves a frame. - if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") - add_compile_options($<$:/EHsc>) - endif() - - # The d3d12_xs shim and its tests use version 1.2 root signatures (D3D12_ROOT_SIGNATURE_DESC2), which the Windows - # SDK declares from 10.0.26100 on. Stop here with the fix instead of failing halfway through the build. - include(CheckCXXSourceCompiles) - check_cxx_source_compiles([=[ - #include - int main() { D3D12_VERSIONED_ROOT_SIGNATURE_DESC d{}; d.Version = D3D_ROOT_SIGNATURE_VERSION_1_2; - return static_cast(sizeof(d.Desc_1_2)); } - ]=] GTA6RT_SDK_HAS_ROOT_SIGNATURE_1_2) - if(NOT GTA6RT_SDK_HAS_ROOT_SIGNATURE_1_2) - if(CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION) - set(_gta6rt_sdk "${CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION}") - elseif(DEFINED ENV{WindowsSDKVersion}) - string(REGEX REPLACE "[\\/]+$" "" _gta6rt_sdk "$ENV{WindowsSDKVersion}") - else() - set(_gta6rt_sdk "an older one") - endif() - message(FATAL_ERROR - "gta6rt needs the Windows SDK 10.0.26100 or newer (version 1.2 root signatures); " - "this build uses ${_gta6rt_sdk}. Install it with " - "`winget install Microsoft.WindowsSDK.10.0.26100` or the Visual Studio Installer, then delete the build " - "folder and configure again.") - endif() - - # Root-signature flag fix, shared by the d3d12_xs shim and its tests. - add_library(gta6rt_d3d12_xs_rootsig STATIC - shims/d3d12_xs_rootsig.cpp - ) - target_include_directories(gta6rt_d3d12_xs_rootsig PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/shims) - target_compile_definitions(gta6rt_d3d12_xs_rootsig PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(gta6rt_d3d12_xs_rootsig PRIVATE /W4 /permissive- /utf-8) - - # XTaskQueue/XAsync from microsoft/libHttpClient (MIT), vendored in third_party/xtaskqueue; shims/xtaskqueue/pch.h - # stands in for libHttpClient's pch.h so only the task queue builds. Used by the xgameruntime shim. - set(XTASKQUEUE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../third_party/xtaskqueue) - add_library(gta6rt_xtaskqueue STATIC - ${XTASKQUEUE_DIR}/Source/Task/TaskQueue.cpp - ${XTASKQUEUE_DIR}/Source/Task/AsyncLib.cpp - ${XTASKQUEUE_DIR}/Source/Task/ThreadPool_win32.cpp - ${XTASKQUEUE_DIR}/Source/Task/WaitTimer_win32.cpp - ) - target_include_directories(gta6rt_xtaskqueue - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims/xtaskqueue ${XTASKQUEUE_DIR}/Source/Task ${XTASKQUEUE_DIR}/Source/Common - PUBLIC ${XTASKQUEUE_DIR}/Include) - target_compile_definitions(gta6rt_xtaskqueue PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(gta6rt_xtaskqueue PRIVATE /utf-8) # third-party code: its own warning level - target_link_libraries(gta6rt_xtaskqueue PUBLIC ole32) - - # Reserves one loader-assigned module TLS index for mapped images. Loaded from the executable's directory by - # Loader::initialize_tls; its trivial DllMain only keeps the TLS anchor in the image. Built in the same directory as - # the executables that map images, because the loader looks for it next to the running EXE. - add_library(gta6rt_tls_host SHARED src/tls_host.cpp) - target_compile_options(gta6rt_tls_host PRIVATE /W4 /permissive- /utf-8 /GS-) - target_compile_definitions(gta6rt_tls_host PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - set_target_properties(gta6rt_tls_host PROPERTIES - OUTPUT_NAME gta6rt_tls_host - PREFIX "" - MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>" - ) - - add_executable(gta6rt - src/main.cpp - src/host_cpu.cpp - src/pe_loader.cpp - shims/registry.cpp - shims/file_system.cpp - shims/winhttp_offline.cpp - shims/xmem.cpp - shims/xg_xs.cpp - shims/acphal.cpp - shims/d3d12_xs.cpp - shims/d3d12_xs_device.cpp - shims/xgameruntime.cpp - shims/xgameruntime_user.cpp - shims/xgameruntime_gamesave.cpp - shims/xgameruntime_store.cpp - shims/xgameruntime_offline.cpp - shims/library_loader.cpp - shims/process.cpp - shims/com_shim.cpp - shims/bcrypt_rng.cpp - shims/xapu_chad.cpp - shims/dstorage.cpp - ) - # dstorage.cpp's guarded_move turns an access violation in a title's buffer into E_DSTORAGE_ACCESS_VIOLATION with - # __try. MSVC always catches it; clang-cl only with asynchronous exceptions (as for tiny_dll below). A source file - # property, so gta6rt and dstorage_test both get it. - set_source_files_properties(shims/dstorage.cpp PROPERTIES COMPILE_OPTIONS "$<$:/EHa>") - add_dependencies(gta6rt gta6rt_tls_host) - target_compile_definitions(gta6rt PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE) - target_compile_options(gta6rt PRIVATE /W4 /permissive- /utf-8) - # Static shim tables register themselves at startup; keep the linker from dropping their objects. - # GTA6RT_HOST_BASE keeps the loader's own image off the default x64 EXE base (0x140000000), where a mapped EXE - # without relocations wants to go. Windows moves the EXE with ASLR anyway; Wine loads it at its preferred base. - set(GTA6RT_HOST_BASE /BASE:0x10000000000) - # BUILD-1457: a thread that asks for no stack size gets the reserve in this program's PE header, 1 MB by default: - # a thread the game starts with dwStackSize 0, a thread-pool thread, a std::thread of the shims. The D3D12 shim - # creates Vulkan pipelines on the calling thread, the driver compiles there, and AMD's Windows compiler (26.11.2) - # overflows 1 MB on some of the game's shaders (docs/pipeline_check.md, "Stack reserve"). run_entry already gives - # the entry thread 8 MB (shims/process_shim.h); this is the same number for the others. Keep it in step with - # scripts/build_runtime.ps1. - set(GTA6RT_STACK 8388608) - target_link_options(gta6rt PRIVATE /OPT:NOREF ${GTA6RT_HOST_BASE} /STACK:${GTA6RT_STACK}) - target_link_libraries(gta6rt PRIVATE gta6rt_d3d12_xs_rootsig gta6rt_xtaskqueue psapi) - - # Root-signature forwarding test: needs a real PC d3d12.lib to serialize the synthetic descriptors. - # find_library searches %LIB% (a Developer Prompt), not the Windows SDK the Visual Studio generator links - # against, so also look in that SDK's um/x64 folder. - set(_sdk_lib_hints) - if(DEFINED ENV{WindowsSdkDir} AND DEFINED ENV{WindowsSDKLibVersion}) - list(APPEND _sdk_lib_hints "$ENV{WindowsSdkDir}Lib/$ENV{WindowsSDKLibVersion}um/x64") - endif() - get_filename_component(_kits_root - "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots;KitsRoot10]" ABSOLUTE) - if(CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION AND EXISTS "${_kits_root}") - list(APPEND _sdk_lib_hints "${_kits_root}/Lib/${CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION}/um/x64") - endif() - find_library(D3D12_LIBRARY NAMES d3d12 HINTS ${_sdk_lib_hints}) - find_library(DXGI_LIBRARY NAMES dxgi HINTS ${_sdk_lib_hints}) - if(D3D12_LIBRARY) - add_executable(root_sig_test - test/root_sig_test.cpp - shims/registry.cpp - shims/d3d12_xs.cpp - shims/d3d12_xs_device.cpp - ) - target_link_libraries(root_sig_test PRIVATE gta6rt_d3d12_xs_rootsig ${D3D12_LIBRARY}) - target_compile_definitions(root_sig_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(root_sig_test PRIVATE /W4 /permissive- /utf-8) - target_link_options(root_sig_test PRIVATE /OPT:NOREF) - - # RTS0 parser oracle: synthetic descriptors only, serialized by the real PC - # d3d12.dll and parsed back by rt::rootsig::parse_rts0. A layout mismatch - # fails here with the blob bytes, never silently in a draw. - add_executable(root_signature_oracle_test - test/root_signature_oracle_test.cpp - ) - target_link_libraries(root_signature_oracle_test PRIVATE gta6rt_root_signature ${D3D12_LIBRARY}) - target_compile_definitions(root_signature_oracle_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(root_signature_oracle_test PRIVATE /W4 /permissive- /utf-8) - target_link_options(root_signature_oracle_test PRIVATE /OPT:NOREF) - - # Xbox-ABI device proxy test: WARP PC device, no game executable. Needs DXGI for the WARP adapter. - if(DXGI_LIBRARY) - add_executable(device_proxy_test - test/device_proxy_test.cpp - shims/registry.cpp - shims/d3d12_xs.cpp - shims/d3d12_xs_device.cpp - ) - target_link_libraries(device_proxy_test PRIVATE gta6rt_d3d12_xs_rootsig ${D3D12_LIBRARY} ${DXGI_LIBRARY}) - target_compile_definitions(device_proxy_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(device_proxy_test PRIVATE /W4 /permissive- /utf-8) - target_link_options(device_proxy_test PRIVATE /OPT:NOREF) - else() - message(STATUS "dxgi.lib not found: device_proxy_test is not built") - endif() - # The queue and fence proxies over synthetic COM objects: no D3D12 runtime, no GPU. Replaces operator new and - # patches its own import table to inject failures, so the proxy source is compiled into it alone. - add_executable(xs_proxy_mock_test - test/xs_proxy_mock_test.cpp - shims/d3d12_xs_device.cpp - ) - target_compile_definitions(xs_proxy_mock_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(xs_proxy_mock_test PRIVATE /W4 /permissive- /utf-8 /EHsc) - else() - message(STATUS "d3d12.lib not found: root_sig_test and device_proxy_test are not built") - endif() - - # xmem shim ABI test: resolves the registered xmem.dll exports itself, so xmem.cpp and registry.cpp are compiled - # into this executable instead of reusing gta6rt's objects (which would duplicate their symbols). - add_executable(xmem_test - test/xmem_test.cpp - shims/xmem.cpp - shims/registry.cpp - ) - target_include_directories(xmem_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) - target_compile_definitions(xmem_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(xmem_test PRIVATE /W4 /permissive- /utf-8 $<$:/EHa>) - target_link_options(xmem_test PRIVATE /OPT:NOREF) - target_link_libraries(xmem_test PRIVATE psapi) - - # xg_xs shim: the two exports and the texture computer's slots against the measured call shapes. - add_executable(xg_xs_test - test/xg_xs_test.cpp - shims/xg_xs.cpp - shims/registry.cpp - ) - target_include_directories(xg_xs_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) - target_compile_definitions(xg_xs_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(xg_xs_test PRIVATE /W4 /permissive- /utf-8) - target_link_options(xg_xs_test PRIVATE /OPT:NOREF) - - # acphal shim ABI test: resolves the registered acphal.dll exports through the registry. - add_executable(acphal_test - test/acphal_test.cpp - shims/acphal.cpp - shims/registry.cpp - ) - target_include_directories(acphal_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) - target_compile_definitions(acphal_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(acphal_test PRIVATE /W4 /permissive- /utf-8) - target_link_options(acphal_test PRIVATE /OPT:NOREF) - - # The Zen 2 instructions a desktop CPU may lack (src/cpu_emulation.h): decoded, emulated on a CONTEXT, and run for - # real with the #UD handler installed, so an Intel host takes the emulated path and an AMD one the native path. - add_executable(cpu_emulation_test test/cpu_emulation_test.cpp) - target_include_directories(cpu_emulation_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) - target_compile_definitions(cpu_emulation_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(cpu_emulation_test PRIVATE /W4 /permissive- /utf-8) - - # Xbox DirectStorage (DStorageGetFactory under dstorage_xs.dll, xcrdapi.dll and dstorage.dll) over synthetic files: - # GAME: paths through the file shims, queues, status arrays, fences and errors. No GPU, no game data. - add_executable(dstorage_test - test/dstorage_test.cpp - shims/dstorage.cpp - shims/file_system.cpp - shims/registry.cpp - ) - target_include_directories(dstorage_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) - target_compile_definitions(dstorage_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(dstorage_test PRIVATE /W4 /permissive- /utf-8) - target_link_options(dstorage_test PRIVATE /OPT:NOREF) - - # xapu.dll and chad.dll, the APU and audio DSP command queues, resolved through the registry like xmem_test. - add_executable(xapu_chad_test - test/xapu_chad_test.cpp - shims/xapu_chad.cpp - shims/registry.cpp - ) - target_include_directories(xapu_chad_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) - target_compile_definitions(xapu_chad_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(xapu_chad_test PRIVATE /W4 /permissive- /utf-8) - target_link_options(xapu_chad_test PRIVATE /OPT:NOREF) - - # The process shim's command line: GetCommandLineW must parse (CommandLineToArgvW) back to its __wargv. - add_executable(process_cmdline_test - test/process_cmdline_test.cpp - shims/process.cpp - shims/registry.cpp - ) - target_include_directories(process_cmdline_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) - target_compile_definitions(process_cmdline_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(process_cmdline_test PRIVATE /W4 /permissive- /utf-8) - target_link_options(process_cmdline_test PRIVATE /OPT:NOREF) - target_link_libraries(process_cmdline_test PRIVATE shell32) - - # Console paths (GAME:) and the write overlay: the file shims resolved through the registry, over temporary folders. - add_executable(file_system_test - test/file_system_test.cpp - shims/file_system.cpp - shims/registry.cpp - ) - target_include_directories(file_system_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) - target_compile_definitions(file_system_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(file_system_test PRIVATE /W4 /permissive- /utf-8) - target_link_options(file_system_test PRIVATE /OPT:NOREF) - target_link_libraries(file_system_test PRIVATE advapi32) # the ACL calls of the unlistable-marker-folder check - - # LEONIDA_SKIP_INT3 (shims/startup_trace.h): its own executable, the variable is read once per process. - add_executable(int3_skip_test - test/int3_skip_test.cpp - shims/registry.cpp - ) - target_include_directories(int3_skip_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) - target_compile_definitions(int3_skip_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(int3_skip_test PRIVATE /W4 /permissive- /utf-8) - target_link_options(int3_skip_test PRIVATE /OPT:NOREF) - - # Offline WinHTTP for mapped images (the package's XCurl.dll and libHttpClient.GDK.dll); no network is touched. - add_executable(winhttp_offline_test - test/winhttp_offline_test.cpp - shims/winhttp_offline.cpp - shims/registry.cpp - ) - target_include_directories(winhttp_offline_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) - target_compile_definitions(winhttp_offline_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(winhttp_offline_test PRIVATE /W4 /permissive- /utf-8) - target_link_options(winhttp_offline_test PRIVATE /OPT:NOREF) - - # COM lifecycle and helper shims for api-ms-win-core-com-l1-1-*.dll. - add_executable(com_shim_test - test/com_shim_test.cpp - shims/com_shim.cpp - shims/registry.cpp - ) - target_include_directories(com_shim_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) - target_compile_definitions(com_shim_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(com_shim_test PRIVATE /W4 /permissive- /utf-8) - target_link_options(com_shim_test PRIVATE /OPT:NOREF) - - # BCrypt RNG and algorithm provider shims. - add_executable(bcrypt_rng_test - test/bcrypt_rng_test.cpp - shims/bcrypt_rng.cpp - shims/registry.cpp - ) - target_include_directories(bcrypt_rng_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) - target_compile_definitions(bcrypt_rng_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(bcrypt_rng_test PRIVATE /W4 /permissive- /utf-8) - target_link_options(bcrypt_rng_test PRIVATE /OPT:NOREF) - - # Synthetic tests for the atomic API reference lifecycle. - add_executable(api_ref_state_test test/api_ref_state_test.cpp) - target_include_directories(api_ref_state_test PRIVATE - ${XTASKQUEUE_DIR}/Source/Task) - target_compile_definitions(api_ref_state_test PRIVATE - WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(api_ref_state_test PRIVATE - /W4 /permissive- /utf-8) - # Verify global reference accounting during task queue teardown. - add_executable(api_global_refs_test test/api_global_refs_test.cpp) - target_compile_definitions(api_global_refs_test PRIVATE - WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(api_global_refs_test PRIVATE - /W4 /permissive- /utf-8) - target_link_libraries(api_global_refs_test PRIVATE - gta6rt_xtaskqueue) - # Offline GDK runtime shim (XGameRuntime, XSystem, XTaskQueue, XAsync), driven through the shim registry the way - # a title calls it at boot. Like xmem_test it compiles its own registry.cpp. - add_executable(xgameruntime_test - test/xgameruntime_test.cpp - shims/xgameruntime.cpp - shims/xgameruntime_user.cpp - shims/xgameruntime_gamesave.cpp - shims/xgameruntime_store.cpp - shims/xgameruntime_offline.cpp - shims/library_loader.cpp - shims/registry.cpp - shims/file_system.cpp - ) - target_include_directories(xgameruntime_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) - target_compile_definitions(xgameruntime_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(xgameruntime_test PRIVATE /W4 /permissive- /utf-8) - target_link_options(xgameruntime_test PRIVATE /OPT:NOREF) - target_link_libraries(xgameruntime_test PRIVATE gta6rt_xtaskqueue) - - # XUserImpl (offline local user) through QueryApiImpl, slot by slot as xgameruntime.lib's thunks call it. - add_executable(xgameruntime_user_test - test/xgameruntime_user_test.cpp - shims/xgameruntime.cpp - shims/xgameruntime_user.cpp - shims/xgameruntime_gamesave.cpp - shims/xgameruntime_store.cpp - shims/xgameruntime_offline.cpp - shims/library_loader.cpp - shims/registry.cpp - shims/file_system.cpp - ) - target_include_directories(xgameruntime_user_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) - target_compile_definitions(xgameruntime_user_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(xgameruntime_user_test PRIVATE /W4 /permissive- /utf-8) - target_link_options(xgameruntime_user_test PRIVATE /OPT:NOREF) - target_link_libraries(xgameruntime_user_test PRIVATE gta6rt_xtaskqueue) - - # XGameSaveImpl (offline saves in LEONIDA_SAVE_DIR) through QueryApiImpl, slot by slot. - add_executable(xgameruntime_gamesave_test - test/xgameruntime_gamesave_test.cpp - shims/xgameruntime.cpp - shims/xgameruntime_user.cpp - shims/xgameruntime_gamesave.cpp - shims/xgameruntime_store.cpp - shims/xgameruntime_offline.cpp - shims/library_loader.cpp - shims/registry.cpp - shims/file_system.cpp - ) - target_include_directories(xgameruntime_gamesave_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) - target_compile_definitions(xgameruntime_gamesave_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(xgameruntime_gamesave_test PRIVATE /W4 /permissive- /utf-8) - target_link_options(xgameruntime_gamesave_test PRIVATE /OPT:NOREF) - target_link_libraries(xgameruntime_gamesave_test PRIVATE gta6rt_xtaskqueue) - - # XStoreImpl (offline: the game is owned, no add-ons, no updates) through QueryApiImpl, slot by slot. - add_executable(xgameruntime_store_test - test/xgameruntime_store_test.cpp - shims/xgameruntime.cpp - shims/xgameruntime_user.cpp - shims/xgameruntime_gamesave.cpp - shims/xgameruntime_store.cpp - shims/xgameruntime_offline.cpp - shims/library_loader.cpp - shims/registry.cpp - shims/file_system.cpp - ) - target_include_directories(xgameruntime_store_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) - target_compile_definitions(xgameruntime_store_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(xgameruntime_store_test PRIVATE /W4 /permissive- /utf-8) - target_link_options(xgameruntime_store_test PRIVATE /OPT:NOREF) - target_link_libraries(xgameruntime_store_test PRIVATE gta6rt_xtaskqueue) - - # XGameEventImpl, XGameUiImpl, XGameStreamingImpl (offline) through QueryApiImpl. - add_executable(xgameruntime_offline_test - test/xgameruntime_offline_test.cpp - shims/xgameruntime.cpp - shims/xgameruntime_user.cpp - shims/xgameruntime_gamesave.cpp - shims/xgameruntime_store.cpp - shims/xgameruntime_offline.cpp - shims/library_loader.cpp - shims/registry.cpp - shims/file_system.cpp - ) - target_include_directories(xgameruntime_offline_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) - target_compile_definitions(xgameruntime_offline_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(xgameruntime_offline_test PRIVATE /W4 /permissive- /utf-8) - target_link_options(xgameruntime_offline_test PRIVATE /OPT:NOREF) - target_link_libraries(xgameruntime_offline_test PRIVATE gta6rt_xtaskqueue) - - # GameInput shim on SDL3 (zlib licence): any controller SDL supports, DualSense trigger effects and lightbar. - # Nothing is downloaded unless asked. The shim is built when SDL3 is available: - # - an installed SDL3 3.2+ that find_package finds (SDL3_DIR / CMAKE_PREFIX_PATH), or - # - -DLEONIDA_SDL3_FETCH=ON: download the pinned release below once at configure time (hash-checked) and build it - # static, or -DFETCHCONTENT_SOURCE_DIR_SDL3= to build that copy without downloading. - # Otherwise, or with -DLEONIDA_SDL3=OFF, gta6rt is built without the shim and the loader binds GameInputCreate to the - # host's GameInput.dll or the unimplemented thunk as before. docs/gameinput.md has the details. - option(LEONIDA_SDL3 "Build the GameInput shim when SDL3 is available" ON) - option(LEONIDA_SDL3_FETCH "Download the pinned SDL3 release if no installed SDL3 is found" OFF) - if(LEONIDA_SDL3) - find_package(SDL3 3.2 CONFIG QUIET COMPONENTS SDL3-static NO_SYSTEM_ENVIRONMENT_PATH) - if(NOT TARGET SDL3::SDL3-static AND (LEONIDA_SDL3_FETCH OR FETCHCONTENT_SOURCE_DIR_SDL3)) - include(FetchContent) - FetchContent_Declare(SDL3 - URL https://github.com/libsdl-org/SDL/releases/download/release-3.4.20/SDL3-3.4.20.tar.gz - URL_HASH SHA256=f3bb06f55bed9557227a700af2ea62e49497ebdf58037732a731a5fb3ef8581f - DOWNLOAD_EXTRACT_TIMESTAMP TRUE) - # Only what gamepads need: the joystick, HIDAPI, haptic, sensor and power code, in a static library. - set(SDL_SHARED OFF CACHE BOOL "" FORCE) - set(SDL_STATIC ON CACHE BOOL "" FORCE) - set(SDL_TEST_LIBRARY OFF CACHE BOOL "" FORCE) - set(SDL_TESTS OFF CACHE BOOL "" FORCE) - set(SDL_EXAMPLES OFF CACHE BOOL "" FORCE) - set(SDL_INSTALL OFF CACHE BOOL "" FORCE) - set(SDL_DISABLE_INSTALL ON CACHE BOOL "" FORCE) - foreach(_sdl_off SDL_AUDIO SDL_VIDEO SDL_GPU SDL_RENDER SDL_CAMERA SDL_DIALOG SDL_TRAY) - set(${_sdl_off} OFF CACHE BOOL "" FORCE) - endforeach() - FetchContent_MakeAvailable(SDL3) - endif() - endif() - if(LEONIDA_SDL3 AND TARGET SDL3::SDL3-static) - target_sources(gta6rt PRIVATE shims/gameinput.cpp) - target_link_libraries(gta6rt PRIVATE SDL3::SDL3-static) - - # GameInput through the shim registry on SDL virtual joysticks: no controller, no game data. - add_executable(gameinput_test test/gameinput_test.cpp shims/gameinput.cpp shims/registry.cpp) - # gameinput_probe: the same shim on a real controller, run by hand (not a CTest). - add_executable(gameinput_probe test/gameinput_probe.cpp shims/gameinput.cpp shims/registry.cpp) - foreach(_gi gameinput_test gameinput_probe) - target_include_directories(${_gi} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) - target_compile_definitions(${_gi} PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(${_gi} PRIVATE /W4 /permissive- /utf-8) - target_link_options(${_gi} PRIVATE /OPT:NOREF) - target_link_libraries(${_gi} PRIVATE SDL3::SDL3-static) - endforeach() - else() - if(LEONIDA_SDL3) - message(STATUS "GameInput shim not built: no installed SDL3 found. Set SDL3_DIR, or pass -DLEONIDA_SDL3_FETCH=ON " - "to download the pinned SDL3 release (see docs/gameinput.md)") - else() - message(STATUS "GameInput shim not built (LEONIDA_SDL3=OFF)") - endif() - endif() + # gta6rt.exe, the libraries its shims link and the shim test programs. + include("${CMAKE_CURRENT_SOURCE_DIR}/cmake/windows_runtime.cmake") elseif(NOT WIN32) message(STATUS "gta6rt requires Windows; only Vulkan tools are available on Linux") @@ -517,827 +74,11 @@ endif() include(CTest) # LEONIDA_TRANSLATOR_DEPS: what the rules that run test/shaders/build.py depend on besides their .asm files. include("${CMAKE_CURRENT_SOURCE_DIR}/cmake/translator_deps.cmake") +# leonida_add_d3d12_xs_stub(): the import stub the stand-in titles link. +include("${CMAKE_CURRENT_SOURCE_DIR}/cmake/fixtures.cmake") if(BUILD_TESTING) - add_executable(gfx10_tiling_test test/gfx10_tiling_test.cpp) - add_test(NAME gfx10_tiling COMMAND gfx10_tiling_test) - - add_executable(retire_tickets_test test/retire_tickets_test.cpp) - add_test(NAME retire_tickets COMMAND retire_tickets_test) - # VulkanContext::buffer_at's VA index (runtime/src/buffer_va_index.h): pure stdlib, no Vulkan instance. - add_executable(buffer_va_index_test test/buffer_va_index_test.cpp) - add_test(NAME buffer_va_index COMMAND buffer_va_index_test) - - add_executable(xbox_present_readback_size_test test/xbox_present_readback_size_test.cpp) - add_test(NAME xbox_present_readback_size COMMAND xbox_present_readback_size_test) - - add_executable(pipeline_cache_file_test test/pipeline_cache_file_test.cpp) - add_test(NAME pipeline_cache_file COMMAND pipeline_cache_file_test) - - add_executable(xdxr_build_output_test test/xdxr_build_output_test.cpp) - add_test(NAME xdxr_build_output COMMAND xdxr_build_output_test) - - # vk_pipeline_check's memory budget for large modules: pure stdlib, no Vulkan device. - add_executable(large_module_gate_test test/large_module_gate_test.cpp) - find_package(Threads REQUIRED) - target_link_libraries(large_module_gate_test PRIVATE Threads::Threads) - add_test(NAME large_module_gate COMMAND large_module_gate_test) - # vk_pipeline_check's isolate summary stage set: pure stdlib, no Vulkan device. - add_executable(pipeline_summary_test test/pipeline_summary_test.cpp) - add_test(NAME pipeline_summary COMMAND pipeline_summary_test) - # XDXR build descriptions (docs/xdxr.md); compared with d3d12.h where the Windows SDK provides it. - add_executable(xdxr_descs_test test/xdxr_descs_test.cpp) - add_test(NAME xdxr_descs COMMAND xdxr_descs_test) - # LEONIDA_VK_DEVICE name matching (runtime/src/vulkan_device_filter.h): pure stdlib, no Vulkan instance. - add_executable(vulkan_device_filter_test test/vulkan_device_filter_test.cpp) - target_include_directories(vulkan_device_filter_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) - add_test(NAME vulkan_device_filter COMMAND vulkan_device_filter_test) - add_executable(vk_presenter_capture_colour_test test/vk_presenter_capture_colour_test.cpp) - add_test(NAME vk_presenter_capture_colour COMMAND vk_presenter_capture_colour_test) - if(TARGET gta6rt) - if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") - add_executable(cpp_unwind_test test/cpp_unwind_test.cpp) - add_test(NAME cpp_unwind COMMAND cpp_unwind_test) - endif() - - # Compile-time ABI checks (D3D12/XMem structure sizes, alignments and member offsets against the Windows SDK). - # The file existed but no target built it, so none of its static_asserts ever ran. - add_executable(runtime_types_test test/test_runtime_types.cpp) - target_include_directories(runtime_types_test PRIVATE - ${CMAKE_CURRENT_SOURCE_DIR}/src ${CMAKE_CURRENT_SOURCE_DIR}/shims) - add_test(NAME runtime_types COMMAND runtime_types_test) - - # Loader tests. They build their own PE images, so they need neither the game nor any other input. - add_executable(loader_test - test/loader_test.cpp - src/pe_loader.cpp - shims/registry.cpp - ) - target_compile_definitions(loader_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE) - target_compile_options(loader_test PRIVATE /W4 /permissive- /utf-8 /EHsc) - target_link_options(loader_test PRIVATE /OPT:NOREF ${GTA6RT_HOST_BASE}) - add_dependencies(loader_test gta6rt_tls_host) - add_test(NAME loader COMMAND loader_test) - # PE loader tests use two locally built fixtures: a DLL with exports, imports and relocations, and an EXE that - # imports it so Loader::load exercises recursive module loading. They contain no game data. - set(TINY_FIXTURE_DIR "${CMAKE_CURRENT_BINARY_DIR}/fixtures/$") - - add_library(tiny_dll SHARED test/fixtures/tiny_dll.cpp) - target_compile_definitions(tiny_dll PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(tiny_dll PRIVATE /W4 /permissive- /utf-8 /GS-) - # tiny_fault_caught faults inside its own __try. MSVC always catches that; clang-cl only with asynchronous - # exceptions, otherwise the access violation escapes and the unwind-registration check fails. - target_compile_options(tiny_dll PRIVATE $<$:/EHa>) - set_target_properties(tiny_dll PROPERTIES - OUTPUT_NAME tiny_dll - PREFIX "" - RUNTIME_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" - ARCHIVE_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" - MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>" - ) - - add_executable(tiny_exe test/fixtures/tiny_exe.cpp) - target_link_libraries(tiny_exe PRIVATE tiny_dll) - target_compile_definitions(tiny_exe PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(tiny_exe PRIVATE /W4 /permissive- /utf-8 /GS-) - set_target_properties(tiny_exe PROPERTIES - OUTPUT_NAME tiny_exe - RUNTIME_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" - MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>" - ) - - # An EXE built with /GA reads its TLS at index 0 without _tls_index; loader_tls_test maps it and reads it from - # threads that existed before load() and from ones that did not. - add_executable(tiny_ga_tls test/fixtures/tiny_ga_tls.cpp) - target_compile_definitions(tiny_ga_tls PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(tiny_ga_tls PRIVATE /W4 /permissive- /utf-8 /GS- /GA) - set_target_properties(tiny_ga_tls PROPERTIES - OUTPUT_NAME tiny_ga_tls - RUNTIME_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" - MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>" - ) - - add_executable(module_names_test test/module_names_test.cpp src/pe_loader.cpp shims/registry.cpp) - target_include_directories(module_names_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) - target_compile_definitions(module_names_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(module_names_test PRIVATE /W4 /permissive- /utf-8 /EHsc) - target_link_options(module_names_test PRIVATE /OPT:NOREF) - add_dependencies(module_names_test gta6rt_tls_host tiny_dll) - add_test(NAME module_names COMMAND module_names_test "$") - - add_executable(tiny_module_names test/fixtures/tiny_module_names.cpp) - target_compile_definitions(tiny_module_names PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(tiny_module_names PRIVATE /W4 /permissive- /utf-8 /EHsc) - set_target_properties(tiny_module_names PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}") - - # Native Windows and --dry-run/--init/--run share original renamed fixtures, including an ACP-named import. - if(NOT CMAKE_CROSSCOMPILING) - find_package(Python3 COMPONENTS Interpreter QUIET) - if(Python3_FOUND) - add_test(NAME run_module_names COMMAND "${Python3_EXECUTABLE}" -I - "${CMAKE_CURRENT_SOURCE_DIR}/test/check_module_names.py" - "--loader=$" "--guest=$" - "--importer=$" "--dependency=$" - "--work-dir=${CMAKE_CURRENT_BINARY_DIR}" - "--report=${CMAKE_CURRENT_BINARY_DIR}/module-names-results.json") - set_tests_properties(run_module_names PROPERTIES TIMEOUT 90) - endif() - endif() - - # pe_loader.cpp needs the shim registry for shims::find/make_unimplemented_thunk. The xmem and d3d12_xs tables - # are linked too so the optional LEONIDA_GAME_DIR run classifies the shipped modules' imports exactly like - # gta6rt does (no d3d12.lib is needed: d3d12_xs resolves its host entry points at run time). - add_executable(pe_loader_test - test/pe_loader_test.cpp - src/pe_loader.cpp - shims/registry.cpp - shims/xmem.cpp - shims/d3d12_xs.cpp - shims/d3d12_xs_device.cpp - ) - target_include_directories(pe_loader_test PRIVATE - ${CMAKE_CURRENT_SOURCE_DIR}/src - ${CMAKE_CURRENT_SOURCE_DIR}/shims - ) - target_compile_definitions(pe_loader_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(pe_loader_test PRIVATE /W4 /permissive- /utf-8 /EHsc) - target_link_options(pe_loader_test PRIVATE /OPT:NOREF) - target_link_libraries(pe_loader_test PRIVATE gta6rt_d3d12_xs_rootsig psapi) - add_dependencies(pe_loader_test tiny_dll tiny_exe gta6rt_tls_host) - - # `gta6rt --run` rehearsal: a stand-in game EXE (CRT startup, statics, heap, files, threads) that imports - # xgameruntime.dll from a link-time stub; under --run the shim registry answers those imports instead. - add_library(xgameruntime_stub SHARED test/fixtures/xgameruntime_stub.cpp test/fixtures/xgameruntime_stub.def) - target_include_directories(xgameruntime_stub PUBLIC ${XTASKQUEUE_DIR}/Include) - target_compile_definitions(xgameruntime_stub PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - set_target_properties(xgameruntime_stub PROPERTIES - OUTPUT_NAME xgameruntime - PREFIX "" - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" - ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" - ) - add_executable(tiny_async test/fixtures/tiny_async.cpp) - target_link_libraries(tiny_async PRIVATE xgameruntime_stub) - set_target_properties(tiny_async PROPERTIES - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" - ) - # Reaches xgameruntime.dll through LoadLibraryW/GetProcAddress, as xgameruntime.lib's thunks do (no import). - add_executable(tiny_gdk_load test/fixtures/tiny_gdk_load.cpp) - target_compile_definitions(tiny_gdk_load PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(tiny_gdk_load PRIVATE /W4 /permissive- /utf-8) - set_target_properties(tiny_gdk_load PROPERTIES - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" - ) - # Run-time LoadLibrary of a bundled Xbox DLL (importing xmem.dll) through rt::Loader. - add_library(xmem_stub SHARED test/fixtures/xmem_stub.cpp test/fixtures/xmem_stub.def) - target_compile_definitions(xmem_stub PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(xmem_stub PRIVATE /W4 /permissive- /utf-8) - set_target_properties(xmem_stub PROPERTIES - OUTPUT_NAME xmem - PREFIX "" - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/stubs/$" - ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/stubs/$" - ) - add_library(tiny_bundled_dll SHARED test/fixtures/tiny_bundled_dll.cpp test/fixtures/tiny_bundled_dll.def) - target_link_libraries(tiny_bundled_dll PRIVATE xmem_stub) - target_compile_definitions(tiny_bundled_dll PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(tiny_bundled_dll PRIVATE /W4 /permissive- /utf-8) - set_target_properties(tiny_bundled_dll PROPERTIES - OUTPUT_NAME tiny_bundled_dll - PREFIX "" - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" - ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/stubs/$" - ) - add_executable(tiny_bundled_load test/fixtures/tiny_bundled_load.cpp) - target_compile_definitions(tiny_bundled_load PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(tiny_bundled_load PRIVATE /W4 /permissive- /utf-8) - add_dependencies(tiny_bundled_load tiny_bundled_dll) - set_target_properties(tiny_bundled_load PROPERTIES - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" - ) - add_library(tiny_startup_cmdline_dll SHARED test/fixtures/tiny_startup_cmdline.cpp) - target_compile_definitions(tiny_startup_cmdline_dll PRIVATE STARTUP_CMDLINE_DLL) - add_executable(tiny_startup_cmdline test/fixtures/tiny_startup_cmdline.cpp) - target_link_libraries(tiny_startup_cmdline PRIVATE tiny_startup_cmdline_dll) - foreach(target tiny_startup_cmdline_dll tiny_startup_cmdline) - target_compile_definitions(${target} PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(${target} PRIVATE /W4 /permissive- /utf-8) - set_target_properties(${target} PROPERTIES - PREFIX "" - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" - ) - endforeach() - # These linker-selected startup modes are specific to the MSVC CRT. - if(MSVC) - foreach(width a w) - foreach(mode default expand noargs) - set(target tiny_argv_${mode}_${width}) - add_executable(${target} test/fixtures/tiny_argv_modes.cpp) - target_compile_definitions(${target} PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(${target} PRIVATE /W4 /permissive- /utf-8) - if(width STREQUAL "w") - target_compile_definitions(${target} PRIVATE APP_WIDE) - endif() - if(mode STREQUAL "expand") - if(width STREQUAL "w") - target_link_options(${target} PRIVATE wsetargv.obj) - else() - target_link_options(${target} PRIVATE setargv.obj) - endif() - elseif(mode STREQUAL "noargs") - target_link_options(${target} PRIVATE noarg.obj) - endif() - set_target_properties(${target} PROPERTIES - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$") - endforeach() - endforeach() - endif() - add_executable(tiny_atexit test/fixtures/tiny_atexit.cpp) - target_compile_definitions(tiny_atexit PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(tiny_atexit PRIVATE /W4 /permissive- /utf-8) - set_target_properties(tiny_atexit PROPERTIES - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" - ) - add_executable(tiny_game test/fixtures/tiny_game.cpp) - target_link_libraries(tiny_game PRIVATE xgameruntime_stub) - target_compile_definitions(tiny_game PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS) # plain fopen, as games use - target_compile_options(tiny_game PRIVATE /W4 /permissive- /utf-8 /EHsc) - set_target_properties(tiny_game PROPERTIES - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" - ) - # The same game with no .reloc, at the default EXE base, as RT-22 asks about the real one: it can only run at - # 0x140000000, which arm64 Wine on macOS uses for itself (src/base_reservation.h). - add_executable(tiny_game_fixed test/fixtures/tiny_game.cpp) - target_link_libraries(tiny_game_fixed PRIVATE xgameruntime_stub) - target_compile_definitions(tiny_game_fixed PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS) - target_compile_options(tiny_game_fixed PRIVATE /W4 /permissive- /utf-8 /EHsc) - target_link_options(tiny_game_fixed PRIVATE /FIXED /DYNAMICBASE:NO /BASE:0x140000000) - set_target_properties(tiny_game_fixed PROPERTIES - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" - ) - add_executable(tiny_game_exit_code_test test/tiny_game_exit_code_test.cpp) - target_compile_definitions(tiny_game_exit_code_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(tiny_game_exit_code_test PRIVATE /W4 /permissive- /utf-8) - add_dependencies(tiny_game_exit_code_test gta6rt tiny_game tiny_game_fixed) - # abort() must reach the guest's SIGABRT handler before the run ends with the CRT's abort code (3). - add_executable(tiny_game_abort_test test/tiny_game_abort_test.cpp) - target_compile_definitions(tiny_game_abort_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(tiny_game_abort_test PRIVATE /W4 /permissive- /utf-8) - add_dependencies(tiny_game_abort_test gta6rt tiny_game) - add_test(NAME pe_loader COMMAND pe_loader_test "$" "$") - - # Synthetic, hand-built images through Loader::load: range checks, wrapping RVAs, import-table termination and - # base relocations (HIGHLOW included). No fixture DLL is needed; the images are written to a temporary folder. - add_executable(test_pe_loader_bounds - test/test_pe_loader_bounds.cpp - src/pe_loader.cpp - shims/registry.cpp - shims/xmem.cpp - shims/d3d12_xs.cpp - shims/d3d12_xs_device.cpp - ) - target_include_directories(test_pe_loader_bounds PRIVATE - ${CMAKE_CURRENT_SOURCE_DIR}/src - ${CMAKE_CURRENT_SOURCE_DIR}/shims - ) - target_compile_definitions(test_pe_loader_bounds PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(test_pe_loader_bounds PRIVATE /W4 /permissive- /utf-8 /EHsc) - target_link_options(test_pe_loader_bounds PRIVATE /OPT:NOREF ${GTA6RT_HOST_BASE}) - target_link_libraries(test_pe_loader_bounds PRIVATE gta6rt_d3d12_xs_rootsig psapi) - add_dependencies(test_pe_loader_bounds gta6rt_tls_host) - add_test(NAME pe_loader_bounds COMMAND test_pe_loader_bounds) - - # RT-388: a deterministic mutation fuzzer over synthetic images through Loader::load (test/pe_loader_fuzz.cpp). - # ctest runs a fixed seed and case count; docs/testing.md has the long runs. With LEONIDA_LOADER_FUZZ_ASAN the - # fuzzer and the loader sources it compiles are built with AddressSanitizer (use RelWithDebInfo or Release: - # /fsanitize=address does not combine with the /RTC1 of a Debug build). - option(LEONIDA_LOADER_FUZZ_ASAN "Build pe_loader_fuzz with AddressSanitizer" OFF) - add_executable(pe_loader_fuzz - test/pe_loader_fuzz.cpp - src/pe_loader.cpp - shims/registry.cpp - shims/xmem.cpp - shims/d3d12_xs.cpp - shims/d3d12_xs_device.cpp - ) - target_include_directories(pe_loader_fuzz PRIVATE - ${CMAKE_CURRENT_SOURCE_DIR}/src - ${CMAKE_CURRENT_SOURCE_DIR}/shims - ) - target_compile_definitions(pe_loader_fuzz PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(pe_loader_fuzz PRIVATE /W4 /permissive- /utf-8 /EHsc) - target_link_options(pe_loader_fuzz PRIVATE /OPT:NOREF ${GTA6RT_HOST_BASE}) - target_link_libraries(pe_loader_fuzz PRIVATE gta6rt_d3d12_xs_rootsig psapi) - add_dependencies(pe_loader_fuzz gta6rt_tls_host) - if(LEONIDA_LOADER_FUZZ_ASAN) - target_compile_options(pe_loader_fuzz PRIVATE /fsanitize=address /Zi) - target_link_options(pe_loader_fuzz PRIVATE /INCREMENTAL:NO /DEBUG) - # No STL container annotations: they need stl_asan.lib from the VS component, and the libraries linked here - # are built without ASan, so the annotate_string/annotate_vector /FAILIFMISMATCH keys must stay as theirs. - target_compile_definitions(pe_loader_fuzz PRIVATE _DISABLE_STRING_ANNOTATION _DISABLE_VECTOR_ANNOTATION) - # The ASan runtime: next to cl.exe for MSVC (the VS "C++ AddressSanitizer" component), under the resource - # directory for clang-cl. Its objects name the runtime libraries; the folder goes on the library path, and the - # DLL is copied beside the test so it runs without a Developer prompt or a PATH change. - get_filename_component(_leonida_cc_dir "${CMAKE_CXX_COMPILER}" DIRECTORY) - file(GLOB _leonida_asan_dll - "${_leonida_cc_dir}/clang_rt.asan_dynamic-x86_64.dll" - "${_leonida_cc_dir}/../lib/clang/*/lib/windows/clang_rt.asan_dynamic-x86_64.dll") - if(_leonida_asan_dll) - list(GET _leonida_asan_dll 0 _leonida_asan_dll) - get_filename_component(_leonida_asan_dir "${_leonida_asan_dll}" DIRECTORY) - target_link_directories(pe_loader_fuzz PRIVATE "${_leonida_asan_dir}") - if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang") - # clang-cl 23's stack-use-after-return frames break MSVC C++ exception dispatch at /O2: a rethrow faults - # in vcruntime's _C_specific_handler_noexcept (a five-line try/throw/catch does it). Without them it works. - target_compile_options(pe_loader_fuzz PRIVATE -fsanitize-address-use-after-return=never) - # clang-cl names these only when it runs the link itself; CMake calls the linker directly. - target_link_options(pe_loader_fuzz PRIVATE clang_rt.asan_dynamic-x86_64.lib - /wholearchive:clang_rt.asan_dynamic_runtime_thunk-x86_64.lib) - endif() - add_custom_command(TARGET pe_loader_fuzz POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy_if_different "${_leonida_asan_dll}" "$") - else() - message(WARNING "LEONIDA_LOADER_FUZZ_ASAN: no clang_rt.asan_dynamic-x86_64.dll beside ${CMAKE_CXX_COMPILER}") - endif() - endif() - add_test(NAME pe_loader_fuzz COMMAND pe_loader_fuzz --quiet) - - # Static TLS fixture: a DLL with __declspec(thread) and a TLS callback. It is ordinary test code; no game data - # is involved. loader_tls_test needs gta6rt_tls_host.dll next to its own EXE, because that is where - # Loader::initialize_tls looks for the reserved module TLS index. - add_library(tiny_tls SHARED test/fixtures/tiny_tls.cpp) - target_compile_definitions(tiny_tls PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(tiny_tls PRIVATE /W4 /permissive- /utf-8 /GS-) - set_target_properties(tiny_tls PROPERTIES - OUTPUT_NAME tiny_tls - PREFIX "" - RUNTIME_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" - ARCHIVE_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" - ) - - add_library(tiny_tls_cb_only SHARED test/fixtures/tiny_tls_cb_only.cpp) - target_compile_definitions(tiny_tls_cb_only PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(tiny_tls_cb_only PRIVATE /W4 /permissive- /utf-8 /GS-) - target_link_options(tiny_tls_cb_only PRIVATE /NODEFAULTLIB /ENTRY:DllMainCRTStartup) - target_link_libraries(tiny_tls_cb_only PRIVATE kernel32) - set_target_properties(tiny_tls_cb_only PROPERTIES - OUTPUT_NAME tiny_tls_cb_only - PREFIX "" - RUNTIME_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" - ARCHIVE_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" - ) - - # pe_loader.cpp needs the shim registry for shims::find/make_unimplemented_thunk. The fixtures import only host - # DLLs, so no shim tables are linked. - add_executable(loader_tls_test - test/loader_tls_test.cpp - src/pe_loader.cpp - shims/registry.cpp - ) - target_include_directories(loader_tls_test PRIVATE - ${CMAKE_CURRENT_SOURCE_DIR}/src - ) - target_compile_definitions(loader_tls_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(loader_tls_test PRIVATE /W4 /permissive- /utf-8 /EHsc) - add_dependencies(loader_tls_test tiny_tls tiny_tls_cb_only tiny_ga_tls gta6rt_tls_host) - add_test(NAME loader_tls - COMMAND loader_tls_test "$" - ) - - # DisableThreadLibraryCalls from a mapped DllMain (shims/library_loader.cpp). The fixture is built without the CRT, so - # DllMain's only work is that one call. No game files. - add_library(dll_thread_calls SHARED test/fixtures/dll_thread_calls.cpp) - target_compile_options(dll_thread_calls PRIVATE /W4 /permissive- /utf-8 /GS-) - target_link_options(dll_thread_calls PRIVATE /NODEFAULTLIB /ENTRY:dll_thread_calls_main) - target_link_libraries(dll_thread_calls PRIVATE kernel32) - set_target_properties(dll_thread_calls PROPERTIES - OUTPUT_NAME dll_thread_calls - PREFIX "" - RUNTIME_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" - ARCHIVE_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" - ) - add_executable(dll_thread_calls_test - test/dll_thread_calls_test.cpp - src/pe_loader.cpp - shims/library_loader.cpp - shims/registry.cpp - shims/xmem.cpp - ) - target_include_directories(dll_thread_calls_test PRIVATE - ${CMAKE_CURRENT_SOURCE_DIR}/src - ${CMAKE_CURRENT_SOURCE_DIR}/shims - ) - target_compile_definitions(dll_thread_calls_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(dll_thread_calls_test PRIVATE /W4 /permissive- /utf-8 /EHsc) - target_link_options(dll_thread_calls_test PRIVATE /OPT:NOREF) - target_link_libraries(dll_thread_calls_test PRIVATE psapi) - add_dependencies(dll_thread_calls_test dll_thread_calls) - add_test(NAME dll_thread_calls - COMMAND dll_thread_calls_test "$" - ) - - # The host GameInput path (docs/gameinput.md): mapped code that imports GameInputCreate from GameInput.dll, with no - # GameInput shim linked. Needs the SDK's gameinput.lib and GameInput.h to build the fixture, and a GameInput.dll on - # the machine to run (the test skips with 77 only when Windows cannot load GameInput.dll). No game files. - find_library(GAMEINPUT_LIBRARY NAMES gameinput HINTS ${_sdk_lib_hints}) - if(GAMEINPUT_LIBRARY) - add_library(gameinput_host SHARED test/fixtures/gameinput_host.cpp) - target_compile_options(gameinput_host PRIVATE /W4 /permissive- /utf-8 /GS-) - target_link_options(gameinput_host PRIVATE /NODEFAULTLIB /ENTRY:gameinput_host_main) - target_link_libraries(gameinput_host PRIVATE kernel32 ${GAMEINPUT_LIBRARY}) - set_target_properties(gameinput_host PROPERTIES - OUTPUT_NAME gameinput_host - PREFIX "" - RUNTIME_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" - ARCHIVE_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" - ) - add_executable(gameinput_host_test - test/gameinput_host_test.cpp - src/pe_loader.cpp - shims/registry.cpp - ) - target_include_directories(gameinput_host_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) - target_compile_definitions(gameinput_host_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(gameinput_host_test PRIVATE /W4 /permissive- /utf-8 /EHsc) - add_dependencies(gameinput_host_test gameinput_host) - add_test(NAME gameinput_host COMMAND gameinput_host_test "$") - set_tests_properties(gameinput_host PROPERTIES SKIP_RETURN_CODE 77) # Windows cannot load GameInput.dll - endif() - - # LEONIDA_UNIMPLEMENTED=log|fail|stop: builds its own image with two imports that bind to nothing, calls them in - # process (log, fail) and in child processes (default/env parsing, stop). No game files, no GPU. - add_executable(unimplemented_policy_test - test/unimplemented_policy_test.cpp - src/pe_loader.cpp - shims/registry.cpp - ) - # The register-preservation check needs a caller that sets rbx/rbp/rdi/rsi/r12-r15 and xmm6-15, which MSVC x64 - # cannot do inline: test/fixtures/abi_probe.asm (MASM). Without ml64 the rest of the test still runs. - # Visual Studio locates cl.exe without adding its directory to PATH. - # Keep looking for ml64 specifically so Ninja cannot select the 32-bit assembler. - get_filename_component(_gta6rt_compiler_bin "${CMAKE_CXX_COMPILER}" DIRECTORY) - find_program(LEONIDA_ML64 NAMES ml64 HINTS "${_gta6rt_compiler_bin}") - if(LEONIDA_ML64) - set(CMAKE_ASM_MASM_COMPILER "${LEONIDA_ML64}") - enable_language(ASM_MASM) - target_sources(unimplemented_policy_test PRIVATE test/fixtures/abi_probe.asm) - target_compile_definitions(unimplemented_policy_test PRIVATE LEONIDA_HAVE_ABI_PROBE=1) - else() - message(STATUS "ml64 not found: unimplemented_policy_test skips the register-preservation check") - endif() - target_include_directories(unimplemented_policy_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) - target_compile_definitions(unimplemented_policy_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE _CRT_SECURE_NO_WARNINGS) - target_compile_options(unimplemented_policy_test PRIVATE $<$:/W4 /permissive- /utf-8 /EHsc>) - target_link_options(unimplemented_policy_test PRIVATE /OPT:NOREF) - add_dependencies(unimplemented_policy_test gta6rt_tls_host) - add_test(NAME unimplemented_policy COMMAND unimplemented_policy_test) - - # gta6rt --trace FILE (shims/startup_trace.h): a synthetic image with an unimplemented import, an - # OutputDebugStringA call and a read of address 0; checks the JSON lines. No game files, no GPU. - add_executable(startup_trace_test - test/startup_trace_test.cpp - src/pe_loader.cpp - shims/registry.cpp - ) - target_include_directories(startup_trace_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) - target_compile_definitions(startup_trace_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE _CRT_SECURE_NO_WARNINGS) - target_compile_options(startup_trace_test PRIVATE /W4 /permissive- /utf-8 /EHsc) - target_link_options(startup_trace_test PRIVATE /OPT:NOREF) - add_dependencies(startup_trace_test gta6rt_tls_host) - add_test(NAME startup_trace COMMAND startup_trace_test) - endif() - - if(TARGET device_proxy_test) - add_test(NAME device_proxy COMMAND device_proxy_test) - set_tests_properties(device_proxy PROPERTIES SKIP_RETURN_CODE 77) # no WARP adapter (Wine) - # With --trace-d3d12 the 24 D3D12XboxCreateDevice parameter words still print (docs/boot.md, question 1), - # and the line with run-specific pointers does not. - add_test(NAME device_proxy_trace COMMAND device_proxy_test --trace-d3d12) - set_tests_properties(device_proxy_trace PROPERTIES SKIP_RETURN_CODE 77 - PASS_REGULAR_EXPRESSION "D3D12XboxCreateDevice params\\[24\\] =1234abcd" - FAIL_REGULAR_EXPRESSION "FAIL;D3D12XboxCreateDevice adapter=") - endif() - if(TARGET xs_proxy_mock_test) - add_test(NAME xs_proxy_mock COMMAND xs_proxy_mock_test) - # The guard region's setup failing (one process each: the tables are built once per process). - add_test(NAME xs_proxy_mock_no_reserve COMMAND xs_proxy_mock_test --fail-virtualalloc) - add_test(NAME xs_proxy_mock_no_protect COMMAND xs_proxy_mock_test --fail-virtualprotect) - add_test(NAME xs_proxy_mock_no_handler COMMAND xs_proxy_mock_test --fail-veh) - # The routes are read once per process, so each override case is its own test. - add_test(NAME xs_proxy_mock_env_slots COMMAND xs_proxy_mock_test --env-slots) - add_test(NAME xs_proxy_mock_env_slots_invalid COMMAND xs_proxy_mock_test --env-slots-invalid) - endif() - if(TARGET root_sig_test) - add_test(NAME root_sig COMMAND root_sig_test) - endif() - add_executable(command_list_test test/command_list_test.cpp) - add_test(NAME command_list COMMAND command_list_test) - # Which SPIR-V modules declare a storage image or buffer they may write (src/spirv_stores.h), on hand-built words. - add_executable(spirv_stores_test test/spirv_stores_test.cpp) - add_test(NAME spirv_stores COMMAND spirv_stores_test) - add_executable(shader_fixture_path_test test/shader_fixture_path_test.cpp) - add_test(NAME shader_fixture_path COMMAND shader_fixture_path_test) - add_executable(resource_tiling_test test/resource_tiling_test.cpp) - add_test(NAME resource_tiling COMMAND resource_tiling_test) - add_executable(resource_detile_test test/resource_detile_test.cpp) - add_test(NAME resource_detile COMMAND resource_detile_test) - add_executable(descriptor_table_test test/descriptor_table_test.cpp) - add_test(NAME descriptor_table COMMAND descriptor_table_test) - add_executable(shader_library_test test/shader_library_test.cpp) - add_test(NAME shader_library COMMAND shader_library_test) - add_executable(spirv_f16_halves_test test/spirv_f16_halves_test.cpp) - add_test(NAME spirv_f16_halves COMMAND spirv_f16_halves_test) - # Optional: skips unless LEONIDA_SHADERS names a translated work folder (/shaders/spirv). - add_executable(shader_library_corpus_test test/shader_library_corpus_test.cpp) - add_test(NAME shader_library_corpus COMMAND shader_library_corpus_test) - # Reads all 26,503 containers and modules: about 9 minutes from a hard disk. - set_tests_properties(shader_library_corpus PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 3600) - if(TARGET gta6rt) - # Optional: skips unless LEONIDA_GAME_DIR and LEONIDA_MOVIE are set. - add_executable(bink_decode_test - test/bink_decode_test.cpp - src/pe_loader.cpp - shims/registry.cpp - shims/xmem.cpp - ) - target_compile_definitions(bink_decode_test PRIVATE - WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE _CRT_SECURE_NO_WARNINGS) - target_compile_options(bink_decode_test PRIVATE /W4 /permissive- /EHsc /utf-8) - target_link_options(bink_decode_test PRIVATE /OPT:NOREF) - target_link_libraries(bink_decode_test PRIVATE psapi) - add_dependencies(bink_decode_test gta6rt_tls_host) - add_test(NAME bink_decode COMMAND bink_decode_test) - set_tests_properties(bink_decode PROPERTIES SKIP_RETURN_CODE 77) - - # Optional: skips unless LEONIDA_GAME_DIR and LEONIDA_BINK_INDEX are set. Measures the HBINK/BINKSUMMARY - # offsets and the decode return values over every stream of movies.rpf (docs/movies.md section 5). - add_executable(bink_abi_test - test/bink_abi_test.cpp - src/pe_loader.cpp - shims/registry.cpp - shims/xmem.cpp - ) - target_compile_definitions(bink_abi_test PRIVATE - WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE _CRT_SECURE_NO_WARNINGS) - target_compile_options(bink_abi_test PRIVATE /W4 /permissive- /EHsc /utf-8) - target_link_options(bink_abi_test PRIVATE /OPT:NOREF) - target_link_libraries(bink_abi_test PRIVATE psapi) - add_dependencies(bink_abi_test gta6rt_tls_host) - add_test(NAME bink_abi COMMAND bink_abi_test) - set_tests_properties(bink_abi PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 3600) - - # Optional local viewer: plays a .bk2 in a window through the package's Bink2Scarlett.dll (test/bink_play.cpp). - # The CTest entry is the headless smoke run; it skips unless LEONIDA_GAME_DIR and LEONIDA_MOVIE are set. - add_executable(bink_play - test/bink_play.cpp - src/pe_loader.cpp - shims/registry.cpp - shims/xmem.cpp - ) - target_compile_definitions(bink_play PRIVATE - WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE _CRT_SECURE_NO_WARNINGS) - target_compile_options(bink_play PRIVATE /W4 /permissive- /EHsc /utf-8) - target_link_options(bink_play PRIVATE /OPT:NOREF) - target_link_libraries(bink_play PRIVATE psapi user32 gdi32) - add_dependencies(bink_play gta6rt_tls_host) - add_test(NAME bink_play_headless COMMAND bink_play --headless --frames 30) - set_tests_properties(bink_play_headless PROPERTIES SKIP_RETURN_CODE 77) - - # Optional: skips unless LEONIDA_GAME_DIR is set. Drives the package's FSR DLL on the Xbox-ABI device proxy. - if(D3D12_LIBRARY AND DXGI_LIBRARY) - add_executable(fsr_dispatch_test - test/fsr_dispatch_test.cpp - src/pe_loader.cpp - shims/registry.cpp - shims/xmem.cpp - shims/d3d12_xs.cpp - shims/d3d12_xs_device.cpp - ) - target_compile_definitions(fsr_dispatch_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS) - target_compile_options(fsr_dispatch_test PRIVATE /W4 /permissive- /EHsc /utf-8) - target_link_options(fsr_dispatch_test PRIVATE /OPT:NOREF) - target_link_libraries(fsr_dispatch_test PRIVATE gta6rt_d3d12_xs_rootsig ${D3D12_LIBRARY} ${DXGI_LIBRARY} psapi) - add_dependencies(fsr_dispatch_test gta6rt_tls_host) - add_test(NAME fsr_dispatch COMMAND fsr_dispatch_test) - set_tests_properties(fsr_dispatch PROPERTIES SKIP_RETURN_CODE 77) - - # Optional: skips unless LEONIDA_GAME_DIR is set. Constructs the package's XboxBvhBuilder on the device proxy. - add_executable(bvh_builder_test - test/bvh_builder_test.cpp - src/pe_loader.cpp - shims/registry.cpp - shims/xmem.cpp - shims/d3d12_xs.cpp - shims/d3d12_xs_device.cpp - ) - target_compile_definitions(bvh_builder_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS) - target_compile_options(bvh_builder_test PRIVATE /W4 /permissive- /EHsc /utf-8) - target_link_options(bvh_builder_test PRIVATE /OPT:NOREF) - target_link_libraries(bvh_builder_test PRIVATE gta6rt_d3d12_xs_rootsig ${D3D12_LIBRARY} ${DXGI_LIBRARY} psapi) - add_dependencies(bvh_builder_test gta6rt_tls_host) - add_test(NAME bvh_builder COMMAND bvh_builder_test) - set_tests_properties(bvh_builder PROPERTIES SKIP_RETURN_CODE 77) - endif() - - # Optional: skips unless LEONIDA_GAME_DIR and LEONIDA_MOVIE_AUDIO are set. - add_executable(bink_audio_test - test/bink_audio_test.cpp - src/pe_loader.cpp - shims/registry.cpp - shims/xmem.cpp - ) - target_compile_definitions(bink_audio_test PRIVATE - WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE _CRT_SECURE_NO_WARNINGS) - target_compile_options(bink_audio_test PRIVATE /W4 /permissive- /EHsc /utf-8) - target_link_options(bink_audio_test PRIVATE /OPT:NOREF) - target_link_libraries(bink_audio_test PRIVATE psapi) - add_dependencies(bink_audio_test gta6rt_tls_host) - add_test(NAME bink_audio COMMAND bink_audio_test) - set_tests_properties(bink_audio PROPERTIES SKIP_RETURN_CODE 77) - endif() - if(WIN32 AND TARGET xmem_test) - add_test(NAME xmem COMMAND xmem_test) - endif() - if(WIN32 AND TARGET xg_xs_test) - add_test(NAME xg_xs COMMAND xg_xs_test) - endif() - if(WIN32 AND TARGET acphal_test) - add_test(NAME acphal COMMAND acphal_test) - endif() - if(WIN32 AND TARGET cpu_emulation_test) - add_test(NAME cpu_emulation COMMAND cpu_emulation_test) - endif() - if(WIN32 AND TARGET xapu_chad_test) - add_test(NAME xapu_chad COMMAND xapu_chad_test) - endif() - if(WIN32 AND TARGET process_cmdline_test) - add_test(NAME process_cmdline COMMAND process_cmdline_test) - endif() - if(WIN32 AND TARGET file_system_test) - add_test(NAME file_system COMMAND file_system_test) - endif() - if(WIN32 AND TARGET int3_skip_test) - add_test(NAME int3_skip COMMAND int3_skip_test) - endif() - if(WIN32 AND TARGET winhttp_offline_test) - add_test(NAME winhttp_offline COMMAND winhttp_offline_test) - endif() - if(WIN32 AND TARGET com_shim_test) - add_test(NAME com_shim COMMAND com_shim_test) - endif() - if(WIN32 AND TARGET bcrypt_rng_test) - add_test(NAME bcrypt_rng COMMAND bcrypt_rng_test) - add_test(NAME bcrypt_rng_seeded COMMAND bcrypt_rng_test --seeded) - set_tests_properties(bcrypt_rng_seeded PROPERTIES ENVIRONMENT "LEONIDA_RNG_SEED=0x123456789abcdef0") - endif() - if(WIN32 AND TARGET api_ref_state_test) - add_test(NAME api_ref_state COMMAND api_ref_state_test) - set_tests_properties(api_ref_state PROPERTIES TIMEOUT 30) - endif() - if(WIN32 AND TARGET api_global_refs_test) - add_test(NAME api_global_refs COMMAND api_global_refs_test) - set_tests_properties(api_global_refs PROPERTIES TIMEOUT 30) - endif() - # Internal XTaskQueue context pinning and rundown regression tests. - if(WIN32 AND TARGET gta6rt_xtaskqueue) - foreach(_context_test context_pinning context_rundown context_reentrant context_concurrent_detach context_attach_detach_stress) - add_executable(${_context_test}_test - test/${_context_test}_test.cpp - ) - target_include_directories(${_context_test}_test PRIVATE - ${CMAKE_CURRENT_SOURCE_DIR}/shims/xtaskqueue - ${XTASKQUEUE_DIR}/Source/Task - ${XTASKQUEUE_DIR}/Source/Common - ) - target_compile_definitions(${_context_test}_test PRIVATE - WIN32_LEAN_AND_MEAN NOMINMAX - ) - target_compile_options(${_context_test}_test PRIVATE - /W4 /permissive- /utf-8 /EHsc - ) - target_link_libraries(${_context_test}_test PRIVATE - gta6rt_xtaskqueue - ) - add_test(NAME ${_context_test} - COMMAND ${_context_test}_test - ) - set_tests_properties(${_context_test} PROPERTIES TIMEOUT 15) - endforeach() - - add_executable(wait_registration_test test/wait_registration_test.cpp) - target_include_directories(wait_registration_test PRIVATE - ${CMAKE_CURRENT_SOURCE_DIR}/shims/xtaskqueue ${XTASKQUEUE_DIR}/Source/Task ${XTASKQUEUE_DIR}/Source/Common) - target_link_libraries(wait_registration_test PRIVATE gta6rt_xtaskqueue) - foreach(_case unregister undispatched terminate parked self presignaled monitor close composite snapshot - cross concurrent held_snapshot admission cancel_unregister reentrant_admission - reentrant_vs_external_unregister multi_dispatcher_terminate multi_dispatcher_unregister_replace) - add_test(NAME wait_registration_${_case} COMMAND wait_registration_test ${_case}) - set_tests_properties(wait_registration_${_case} PROPERTIES TIMEOUT 15) - endforeach() - endif() - if(WIN32 AND TARGET dstorage_test) - add_test(NAME dstorage COMMAND dstorage_test) - endif() - if(WIN32 AND TARGET xgameruntime_test) - add_test(NAME xgameruntime COMMAND xgameruntime_test) - add_test(NAME xgameruntime_user COMMAND xgameruntime_user_test) - add_test(NAME xgameruntime_gamesave COMMAND xgameruntime_gamesave_test) - add_test(NAME xgameruntime_store COMMAND xgameruntime_store_test) - add_test(NAME xgameruntime_offline COMMAND xgameruntime_offline_test) - add_test(NAME xgameruntime_offline_hdr COMMAND xgameruntime_offline_test) - set_tests_properties(xgameruntime_offline_hdr PROPERTIES ENVIRONMENT "LEONIDA_HDR=1") - add_test(NAME xgameruntime_user_gamertag COMMAND xgameruntime_user_test --expect-gamertag Tester42) - set_tests_properties(xgameruntime_user_gamertag PROPERTIES ENVIRONMENT "LEONIDA_GAMERTAG=Tester42") - # Longer than getenv_s's old 64-byte buffer: still the "Player" fallback (and its message), not a silent one. - add_test(NAME xgameruntime_user_gamertag_long COMMAND xgameruntime_user_test --expect-gamertag Player) - set_tests_properties(xgameruntime_user_gamertag_long PROPERTIES ENVIRONMENT "LEONIDA_GAMERTAG=GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG") - endif() - # The active-input tracker the GameInput shim feeds (src/active_input.h), on synthetic samples: no SDL, no - # controller, no GPU, so it builds and runs everywhere, with or without SDL3. - add_executable(active_input_test test/active_input_test.cpp) - if(MSVC) - target_compile_options(active_input_test PRIVATE /W4 /permissive- /utf-8) - endif() - add_test(NAME active_input COMMAND active_input_test) - if(WIN32 AND TARGET gameinput_test) - add_test(NAME gameinput COMMAND gameinput_test) - elseif(TARGET gta6rt) - # Built without SDL3: listed as "Not Run (Disabled)" so it is visible that the shim was not tested. - add_test(NAME gameinput COMMAND ${CMAKE_COMMAND} -E echo "built without SDL3") - set_tests_properties(gameinput PROPERTIES DISABLED TRUE) - endif() - if(WIN32 AND TARGET gta6rt AND TARGET tiny_game) - if(TARGET tiny_argv_default_a AND NOT CMAKE_CROSSCOMPILING) - find_package(Python3 COMPONENTS Interpreter QUIET) - if(Python3_FOUND) - add_test(NAME run_argv_modes COMMAND "${Python3_EXECUTABLE}" -I - "${CMAKE_CURRENT_SOURCE_DIR}/test/check_argv_modes.py" - --loader "$" --fixtures "$" - --work-dir "${CMAKE_CURRENT_BINARY_DIR}") - set_tests_properties(run_argv_modes PROPERTIES TIMEOUT 90) - endif() - endif() - add_test(NAME run_startup_cmdline COMMAND ${CMAKE_COMMAND} - "-DLOADER=$" "-DGUEST=$" - "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_startup_cmdline.cmake") - add_test(NAME run_tiny_async COMMAND ${CMAKE_COMMAND} - "-DLOADER=$" "-DGUEST=$" - "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_loaded_async.cmake") - add_test(NAME run_tiny_gdk_load COMMAND ${CMAKE_COMMAND} - "-DLOADER=$" "-DGUEST=$" - "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_loaded_gdk.cmake") - add_test(NAME run_tiny_bundled_load COMMAND ${CMAKE_COMMAND} - "-DLOADER=$" "-DGUEST=$" - "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_loaded_bundled.cmake") - # atexit handlers, static destructors and the ways out, compared with the same program run natively. - add_test(NAME run_tiny_atexit COMMAND ${CMAKE_COMMAND} - "-DLOADER=$" "-DGUEST=$" - "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_atexit.cmake") - add_test(NAME run_tiny_game COMMAND gta6rt --run $ -- hello 42) - add_test(NAME run_tiny_game_console_paths COMMAND ${CMAKE_COMMAND} - "-DLOADER=$" "-DGUEST=$" - "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_console_paths.cmake") - add_test(NAME run_tiny_game_exit_code COMMAND tiny_game_exit_code_test - "$" "$") - add_test(NAME run_tiny_game_abort_exit_codes COMMAND tiny_game_abort_test - "$" "$") - # Without relocations it can only run at 0x140000000 (base_reservation.h), so passing means it got there; the - # game's exact exit code comes back through the relaunch. - add_test(NAME run_tiny_game_fixed COMMAND gta6rt --run $ -- hello 42) - add_test(NAME run_tiny_game_fixed_exit_code COMMAND tiny_game_exit_code_test - "$" "$") - # Two modes at once are refused before anything is mapped (#886). The stand-in game's own arguments are passed, - # so a gta6rt that ignored the conflict would run it, print "running" and exit 0. - foreach(modes "dry-run;run" "dry-run;init" "init;run") - string(REPLACE ";" "_" name "${modes}") - list(TRANSFORM modes PREPEND "--") - add_test(NAME gta6rt_rejects_${name} COMMAND gta6rt ${modes} $ -- hello 42) - set_tests_properties(gta6rt_rejects_${name} PROPERTIES - PASS_REGULAR_EXPRESSION "usage: gta6rt" - FAIL_REGULAR_EXPRESSION "running |module\\(s\\) mapped") - endforeach() - # The opt-in checks, one test each: thread_local on the game's threads, a C++ exception caught inside the image. - add_test(NAME run_tiny_game_tls COMMAND gta6rt --run $ -- hello 42 tls) - add_test(NAME run_tiny_game_eh COMMAND gta6rt --run $ -- hello 42 eh) - # BUILD-1457: the stack a game thread gets. gta6rt_stack reads SizeOfStackReserve from the built loader (nothing - # is run); run_tiny_game_stack asks Windows, on the entry thread and on a thread created with dwStackSize 0. - add_test(NAME gta6rt_stack COMMAND "${CMAKE_COMMAND}" - "-DTOOL=$" "-DWANT=${GTA6RT_STACK}" - -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_stack_reserve.cmake") - add_test(NAME run_tiny_game_stack COMMAND gta6rt --run $ -- hello 42 stack) - # GAME: is the game folder, absolute, when gta6rt is given a bare image name or `--game-dir .`. - add_test(NAME run_tiny_game_dir COMMAND ${CMAKE_COMMAND} - "-DLOADER=$" "-DGUEST=$" - "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_game_dir.cmake") - endif() - if(TARGET root_signature_test) - add_test(NAME root_signature COMMAND root_signature_test) - endif() - if(TARGET host_cpu_test) - add_test(NAME host_cpu COMMAND host_cpu_test) - endif() - if(WIN32 AND TARGET root_signature_oracle_test) - add_test(NAME root_signature_oracle COMMAND root_signature_oracle_test) - endif() + # The tests that need no Vulkan headers, and the stand-in titles gta6rt maps in them. + include("${CMAKE_CURRENT_SOURCE_DIR}/cmake/runtime_tests.cmake") endif() if(TARGET gta6rt_d3d12_xs_rootsig) @@ -1398,1975 +139,58 @@ if(NOT TARGET Vulkan::Headers) endif() endif() if(TARGET Vulkan::Headers) - foreach(tool vk_harness vk_ps_sweep vk_texture_test vk_sampler_test vk_compute_test vk_store_test vk_pipeline_check vk_command_replay_test - vk_bindless_test vk_image_fuzz vk_descriptor_bench depth24_convert_test vk_predicate_capture_test vk_predicated_copy_test - vk_xdxr_build_test vk_queue_test vk_sandbox) - add_executable(${tool} test/${tool}.cpp) - target_link_libraries(${tool} PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) - if(WIN32) - target_compile_definitions(${tool} PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - endif() - endforeach() - # OpFmaKHR width gate of vk_shader_fma.h (shaderFmaFloat32 / shaderFmaFloat64): no Vulkan instance, no GPU. - add_executable(vk_shader_fma_test test/vk_shader_fma_test.cpp) - target_link_libraries(vk_shader_fma_test PRIVATE Vulkan::Headers) - add_test(NAME vk_shader_fma COMMAND vk_shader_fma_test) - # LEONIDA_VK_DEVICE names the GPU in every harness (docs/testing.md, "Choosing the GPU"): a filter that matches no - # device fails the run in vk_descriptor_bench and vk_sandbox too, instead of testing another GPU (TEST-1141). - find_package(Python3 COMPONENTS Interpreter QUIET) - if(Python3_FOUND) - add_test(NAME vk_device_filter_tools COMMAND "${Python3_EXECUTABLE}" -I - "${CMAKE_CURRENT_SOURCE_DIR}/test/check_device_filter_tools.py" "$" - "$" "${CMAKE_CURRENT_BINARY_DIR}/vk_device_filter_tools") - set_tests_properties(vk_device_filter_tools PROPERTIES SKIP_RETURN_CODE 77) - endif() - if(MSVC) - # Keep the checker and its worker threads on the toolchain's C++ runtime under Wine. - set_property(TARGET vk_pipeline_check PROPERTY - MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") - endif() - # BUILD-1457: a driver compiles on the thread that creates the pipeline, and its compiler can recurse with the - # shader's nesting. On Windows a thread that asks for no size gets the reserve in the PE header, 1 MB by default: - # the main thread and every std::thread worker of the checker. AMD's Windows compiler (26.11.2) overflows that - # on 26 of the corpus's mesh shaders, and 2 MB is still too little for compute shaders nested deeper than 16 - # (docs/pipeline_check.md, "Stack reserve"). Keep the number in step with scripts/build_runtime.ps1. - set(LEONIDA_PIPELINE_CHECK_STACK 8388608) - if(WIN32) - if(MSVC) - target_link_options(vk_pipeline_check PRIVATE /STACK:${LEONIDA_PIPELINE_CHECK_STACK}) - else() - target_link_options(vk_pipeline_check PRIVATE -Wl,--stack,${LEONIDA_PIPELINE_CHECK_STACK}) - endif() - endif() - if(BUILD_TESTING) - if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) - # Real Win32 environment and DXGI names, with D3D12 device creation stubbed: no GPU commands or game files. - # It includes the runtime's D3D12 shim headers, so it needs the same Windows SDK as the runtime. - add_executable(host_adapter_test test/host_adapter_test.cpp) - target_link_libraries(host_adapter_test PRIVATE Vulkan::Headers dxgi) - target_compile_definitions(host_adapter_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - if(MSVC) - target_compile_options(host_adapter_test PRIVATE /W4 /permissive- /EHsc /utf-8) - endif() - add_test(NAME host_adapter COMMAND host_adapter_test) - endif() - add_test(NAME vk_pipeline_check_cli COMMAND "${CMAKE_COMMAND}" - "-DTOOL=$" - "-DTEST_DIR=${CMAKE_CURRENT_BINARY_DIR}/vk_pipeline_check_cli_input" - "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" - -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_vk_pipeline_cli.cmake") - add_test(NAME vk_texture_cube_alpha COMMAND vk_texture_test --self-test-cube-alpha) - if(WIN32) - # Reads SizeOfStackReserve from the built file; the program is not run, so it needs no emulator. - add_test(NAME vk_pipeline_check_stack COMMAND "${CMAKE_COMMAND}" - "-DTOOL=$" - "-DWANT=${LEONIDA_PIPELINE_CHECK_STACK}" - -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_stack_reserve.cmake") - endif() - add_test(NAME depth24_convert COMMAND depth24_convert_test) - set_tests_properties(depth24_convert PROPERTIES SKIP_RETURN_CODE 77) - # Self-checking Vulkan tests with no shaders or game data; each exits 77 without a Vulkan device (TEST-514). - foreach(test vk_command_replay vk_predicated_copy vk_predicate_capture vk_queue) - add_test(NAME ${test} COMMAND ${test}_test) - set_tests_properties(${test} PROPERTIES SKIP_RETURN_CODE 77) - endforeach() - # The XDXR BVH builder: the GPU writes every case, then tools/xdxr_bvh.py validates and traces them. - set(LEONIDA_XDXR_OUT "${CMAKE_CURRENT_BINARY_DIR}/xdxr_build_cases") - file(MAKE_DIRECTORY "${LEONIDA_XDXR_OUT}") - add_test(NAME xdxr_build COMMAND vk_xdxr_build_test "${LEONIDA_XDXR_OUT}") - set_tests_properties(xdxr_build PROPERTIES SKIP_RETURN_CODE 77 FIXTURES_SETUP xdxr_build_cases) - find_package(Python3 COMPONENTS Interpreter QUIET) - if(Python3_FOUND) - add_test(NAME xdxr_build_check COMMAND "${Python3_EXECUTABLE}" -I - "${CMAKE_CURRENT_SOURCE_DIR}/../tools/xdxr_bvh.py" check-build "${LEONIDA_XDXR_OUT}" --rays 1000) - set_tests_properties(xdxr_build_check PROPERTIES FIXTURES_REQUIRED xdxr_build_cases SKIP_RETURN_CODE 77) - endif() - endif() - # VulkanQueue/VulkanContext query-state synchronization (remove_query_pool vs commit, cross-queue plan/commit) - # and pending Wait() preservation across transient vkQueueSubmit failures. - add_executable(vk_queue_query_sync_test test/vk_queue_query_sync_test.cpp) - target_link_libraries(vk_queue_query_sync_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) - if(WIN32) - target_compile_definitions(vk_queue_query_sync_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - else() - find_package(Threads REQUIRED) - target_link_libraries(vk_queue_query_sync_test PRIVATE Threads::Threads) - endif() - if(MSVC) - target_compile_options(vk_queue_query_sync_test PRIVATE /W4 /permissive- /utf-8) - endif() - if(BUILD_TESTING) - add_test(NAME vk_queue_query_sync COMMAND vk_queue_query_sync_test) - set_tests_properties(vk_queue_query_sync PROPERTIES SKIP_RETURN_CODE 77) - endif() - # With LEONIDA_VK_VALIDATION=1: synchronization validation reports a missing barrier (and not a present one), so - # the other GPU tests' "0 validation errors" was checked by an active layer. 77 without validation or a device. - add_executable(vk_sync_validation_selftest test/vk_sync_validation_selftest.cpp) - target_link_libraries(vk_sync_validation_selftest PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) - if(WIN32) - target_compile_definitions(vk_sync_validation_selftest PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - endif() - if(MSVC) - target_compile_options(vk_sync_validation_selftest PRIVATE /W4 /permissive- /utf-8) - endif() - if(BUILD_TESTING) - add_test(NAME vk_sync_validation COMMAND vk_sync_validation_selftest) - set_tests_properties(vk_sync_validation PROPERTIES SKIP_RETURN_CODE 77) - endif() - if(NOT Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) - find_program(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE glslangValidator HINTS "$ENV{VULKAN_SDK}/Bin" "$ENV{VULKAN_SDK}/bin") - endif() - if(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) - add_executable(vk_overlapping_occlusion_test test/vk_overlapping_occlusion_test.cpp) - target_link_libraries(vk_overlapping_occlusion_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) - if(WIN32) - target_compile_definitions(vk_overlapping_occlusion_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - endif() - foreach(stage vert frag) - set(source "${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/overlapping_occlusion.${stage}") - set(output "${CMAKE_CURRENT_BINARY_DIR}/overlapping_occlusion.${stage}.spv") - add_custom_command(OUTPUT "${output}" - COMMAND "${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE}" -V --target-env vulkan1.0 - -o "${output}" "${source}" - DEPENDS "${source}" VERBATIM) - target_sources(vk_overlapping_occlusion_test PRIVATE "${output}") - endforeach() - if(BUILD_TESTING) - add_test(NAME vk_overlapping_occlusion COMMAND vk_overlapping_occlusion_test - "${CMAKE_CURRENT_BINARY_DIR}/overlapping_occlusion.vert.spv" - "${CMAKE_CURRENT_BINARY_DIR}/overlapping_occlusion.frag.spv") - # The same test as a device without pipelineStatisticsQuery runs it (MoltenVK), on whatever device is here. - add_test(NAME vk_overlapping_occlusion_no_statistics COMMAND vk_overlapping_occlusion_test - "${CMAKE_CURRENT_BINARY_DIR}/overlapping_occlusion.vert.spv" - "${CMAKE_CURRENT_BINARY_DIR}/overlapping_occlusion.frag.spv" --no-statistics) - set_tests_properties(vk_overlapping_occlusion vk_overlapping_occlusion_no_statistics - PROPERTIES SKIP_RETURN_CODE 77) - endif() - endif() - # CPU-only: the ranking that makes these harnesses prefer a native ICD over Mesa's Dozen (#915). No GPU needed. - add_executable(vk_device_pick_test test/vk_device_pick_test.cpp) - target_link_libraries(vk_device_pick_test PRIVATE Vulkan::Headers) - if(BUILD_TESTING) - add_test(NAME vk_device_pick COMMAND vk_device_pick_test) - endif() - # Committed BC* texture zero-initialization via vk.zero_buffer or vk.copy_scratch (D3D-220). - add_executable(vk_bc_zero_init_test test/vk_bc_zero_init_test.cpp) - target_link_libraries(vk_bc_zero_init_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) - if(WIN32) - target_compile_definitions(vk_bc_zero_init_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - endif() - if(MSVC) - target_compile_options(vk_bc_zero_init_test PRIVATE /W4 /permissive- /utf-8) - endif() - if(BUILD_TESTING) - add_test(NAME vk_bc_zero_init COMMAND vk_bc_zero_init_test) - set_tests_properties(vk_bc_zero_init PROPERTIES SKIP_RETURN_CODE 77) - endif() - # FenceWaitDispatcher concurrency and device-lost regressions (re-entrant callbacks, wakeup on device lost, counter error drain). - add_executable(vk_fence_dispatcher_sync_test test/vk_fence_dispatcher_sync_test.cpp) - target_link_libraries(vk_fence_dispatcher_sync_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) - if(WIN32) - target_compile_definitions(vk_fence_dispatcher_sync_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - else() - find_package(Threads REQUIRED) - target_link_libraries(vk_fence_dispatcher_sync_test PRIVATE Threads::Threads) - endif() - if(MSVC) - target_compile_options(vk_fence_dispatcher_sync_test PRIVATE /W4 /permissive- /utf-8) - endif() - if(BUILD_TESTING) - add_test(NAME vk_fence_dispatcher_sync COMMAND vk_fence_dispatcher_sync_test) - set_tests_properties(vk_fence_dispatcher_sync PROPERTIES SKIP_RETURN_CODE 77) - endif() - # CPU-only: the bindless set's array sizes from synthetic device limits. - add_executable(bindless_sizing_test test/bindless_sizing_test.cpp) - target_link_libraries(bindless_sizing_test PRIVATE Vulkan::Headers) - if(BUILD_TESTING) - add_test(NAME bindless_sizing COMMAND bindless_sizing_test) - endif() - # CPU-only: a mesh PSO's output, workgroup and shared-memory needs against synthetic device limits (vulkan_mesh_limits.h). - add_executable(vulkan_mesh_limits_test test/vulkan_mesh_limits_test.cpp) - target_link_libraries(vulkan_mesh_limits_test PRIVATE Vulkan::Headers) - if(BUILD_TESTING) - add_test(NAME vulkan_mesh_limits COMMAND vulkan_mesh_limits_test) - endif() - # CPU-only: Vulkan 1.3 core vs 1.2 KHR/EXT feature probing and proc fallback (runtime/src/vulkan13_features.h). - add_executable(vulkan13_features_test test/vulkan13_features_test.cpp) - target_link_libraries(vulkan13_features_test PRIVATE Vulkan::Headers) - if(MSVC) - target_compile_options(vulkan13_features_test PRIVATE /W4 /permissive- /utf-8) - endif() - if(BUILD_TESTING) - add_test(NAME vulkan13_features COMMAND vulkan13_features_test) - endif() - # Buffer registrations keep their binding, VA lookup, and sparse owner in step on host allocation failure. - add_executable(vk_buffer_registration_oom_test test/vk_buffer_registration_oom_test.cpp) - target_link_libraries(vk_buffer_registration_oom_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) - if(WIN32) - target_compile_definitions(vk_buffer_registration_oom_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - if(MSVC) - target_compile_options(vk_buffer_registration_oom_test PRIVATE /W4 /permissive- /EHsc /utf-8) - endif() - endif() - if(BUILD_TESTING) - add_test(NAME vk_buffer_registration_oom COMMAND vk_buffer_registration_oom_test) - endif() - # CPU-only: ScratchBuffers chunk alignment, retire/collect/forget, and spare cap (runtime/src/vulkan_scratch.h). - add_executable(vulkan_scratch_test test/vulkan_scratch_test.cpp) - target_link_libraries(vulkan_scratch_test PRIVATE Vulkan::Headers) - if(MSVC) - target_compile_options(vulkan_scratch_test PRIVATE /W4 /permissive- /utf-8) - endif() - if(BUILD_TESTING) - add_test(NAME vulkan_scratch COMMAND vulkan_scratch_test) - endif() - if(WIN32 AND BUILD_TESTING) - # VulkanPresenter tracker lock / failed-submit rollback and capture-buffer WAW synchronization. - add_executable(vk_presenter_sync_test test/vk_presenter_sync_test.cpp) - target_link_libraries(vk_presenter_sync_test PRIVATE Vulkan::Headers user32) - target_compile_definitions(vk_presenter_sync_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - if(MSVC) - target_compile_options(vk_presenter_sync_test PRIVATE /W4 /permissive- /utf-8) - endif() - add_test(NAME vk_presenter_sync COMMAND vk_presenter_sync_test) - set_tests_properties(vk_presenter_sync PROPERTIES SKIP_RETURN_CODE 77) - endif() - if(NOT Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) - find_program(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE glslangValidator HINTS "$ENV{VULKAN_SDK}/Bin" "$ENV{VULKAN_SDK}/bin") - endif() - if(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) - add_executable(vk_binary_occlusion_test test/vk_binary_occlusion_test.cpp) - target_link_libraries(vk_binary_occlusion_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) - if(WIN32) - target_compile_definitions(vk_binary_occlusion_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - endif() - foreach(stage vert frag) - set(source "${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/binary_occlusion.${stage}") - set(output "${CMAKE_CURRENT_BINARY_DIR}/binary_occlusion.${stage}.spv") - add_custom_command(OUTPUT "${output}" - COMMAND "${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE}" -V --target-env vulkan1.0 - -o "${output}" "${source}" - DEPENDS "${source}" VERBATIM) - target_sources(vk_binary_occlusion_test PRIVATE "${output}") - endforeach() - if(BUILD_TESTING) - add_test(NAME vk_binary_occlusion COMMAND vk_binary_occlusion_test - "${CMAKE_CURRENT_BINARY_DIR}/binary_occlusion.vert.spv" - "${CMAKE_CURRENT_BINARY_DIR}/binary_occlusion.frag.spv") - set_tests_properties(vk_binary_occlusion PROPERTIES SKIP_RETURN_CODE 77) - endif() - endif() - # D3D12 COM objects over the Vulkan backend. Their method stubs are generated from the SDK's d3d12.h at build - # time (tools/gen_d3d12_stubs.py), so nothing derived from the SDK header is checked in. - find_package(Python3 COMPONENTS Interpreter QUIET) - # The generator finds d3d12.h through INCLUDE, which a Developer Prompt sets. A cross build (for example - # runtime/cmake/clang-cl-xwin.cmake) has no such prompt, so it is handed the header CMake finds. - set(_stubs_header) - set(_stubs_header_ok TRUE) - if(TARGET gta6rt AND CMAKE_CROSSCOMPILING) - find_file(LEONIDA_D3D12_HEADER d3d12.h) - if(LEONIDA_D3D12_HEADER) - set(_stubs_header --header "${LEONIDA_D3D12_HEADER}") - else() - set(_stubs_header_ok FALSE) - message(STATUS "d3d12.h not found (set CMAKE_INCLUDE_PATH): the D3D12 COM objects are not built") - endif() - endif() - if(TARGET gta6rt AND Python3_FOUND AND _stubs_header_ok) - set(LEONIDA_STUBS ${CMAKE_CURRENT_BINARY_DIR}/generated/d3d12_stubs.h) - add_custom_command( - OUTPUT ${LEONIDA_STUBS} - COMMAND "${Python3_EXECUTABLE}" -I ${CMAKE_CURRENT_SOURCE_DIR}/../tools/gen_d3d12_stubs.py --out ${LEONIDA_STUBS} - ${_stubs_header} - ID3D12GraphicsCommandList8 ID3D12CommandQueue ID3D12CommandAllocator ID3D12Fence1 - ID3D12Device11 ID3D12DescriptorHeap ID3D12Heap ID3D12Resource ID3D12QueryHeap ID3D12RootSignature - ID3D12PipelineState ID3D12CommandSignature ID3D12PipelineLibrary1 ID3D12ShaderCacheSession - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/../tools/gen_d3d12_stubs.py ${LEONIDA_D3D12_HEADER} - COMMENT "Generating D3D12 COM stubs" - VERBATIM) - add_library(gta6rt_d3d12_com STATIC shims/d3d12_com.cpp shims/d3d12_vulkan_device.cpp shims/d3d12_xs_device.cpp shims/xbox_present.cpp - shims/dxgi_com.cpp ${LEONIDA_STUBS}) # d3d12_vulkan_device.cpp reads the PC device behind the proxy (#224) - target_include_directories(gta6rt_d3d12_com PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/generated) - target_link_libraries(gta6rt_d3d12_com PUBLIC Vulkan::Headers gta6rt_root_signature) - target_compile_definitions(gta6rt_d3d12_com PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - # /bigobj: a Debug build of d3d12_vulkan_device.cpp has more sections than a COFF object holds by default - # (fatal error C1128), because without optimisation every inline function keeps its own COMDAT. - target_compile_options(gta6rt_d3d12_com PRIVATE /W4 /permissive- /utf-8 /bigobj) - - add_executable(d3d12_com_test test/d3d12_com_test.cpp) - target_link_libraries(d3d12_com_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_com_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_com_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_com COMMAND d3d12_com_test) - set_tests_properties(d3d12_com PROPERTIES SKIP_RETURN_CODE 77) - - # Where the device finds its translated shaders (shader_path.txt, a path that is not UTF-8). No GPU. - add_executable(d3d12_shader_path_test test/d3d12_shader_path_test.cpp) - target_link_libraries(d3d12_shader_path_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_shader_path_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_shader_path_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_shader_path COMMAND d3d12_shader_path_test) - - # Multi-threaded concurrent submissions across two D3D12 queues + resource creation/destruction churn. - add_executable(d3d12_multithread_test test/d3d12_multithread_test.cpp) - target_link_libraries(d3d12_multithread_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_multithread_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_multithread_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_multithread COMMAND d3d12_multithread_test) - # 300 s, not 120: the test's 60 s fence waits need headroom when other GPU tests share the device - # (two concurrent `ctest -j 6` suites pushed it to 91-120 s; TEST-514 follow-up). - set_tests_properties(d3d12_multithread PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 300) - # Several threads make the first CheckFeatureSupport(D3D12_OPTIONS1) call of a new device at the same time. - add_executable(d3d12_options1_first_use_test test/d3d12_options1_first_use_test.cpp) - target_link_libraries(d3d12_options1_first_use_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_options1_first_use_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_options1_first_use_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_options1_first_use COMMAND d3d12_options1_first_use_test) - set_tests_properties(d3d12_options1_first_use PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) - # A queued Wait must not block a Signal submitted by another D3D12 queue. - add_executable(d3d12_queue_wait_test test/d3d12_queue_wait_test.cpp) - target_link_libraries(d3d12_queue_wait_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_queue_wait_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_queue_wait_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_queue_wait COMMAND d3d12_queue_wait_test) - add_executable(d3d12_noop_copy_test test/d3d12_noop_copy_test.cpp) - target_link_libraries(d3d12_noop_copy_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_noop_copy_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_noop_copy_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_noop_copy COMMAND d3d12_noop_copy_test) - set_tests_properties(d3d12_noop_copy PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 45) - set_tests_properties(d3d12_queue_wait PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) - add_test(NAME d3d12_queue_wait_timeout COMMAND d3d12_queue_wait_test --timeout-control) - # Under Ubuntu's Wine 9.0 this test runs into the 10 s without printing anything. With 60 s (9002b42) it no longer - # did, but the tests after it stayed slow and the wine (ubuntu) job was cancelled at 30 minutes (run 45428701383); - # with 10 s the same job passed in 694 s (run 45410688081). Why is not known yet, so the limit stays. - set_tests_properties(d3d12_queue_wait_timeout PROPERTIES SKIP_RETURN_CODE 77 WILL_FAIL TRUE TIMEOUT 10) - # ExecuteCommandLists refuses a list whose type isn't the queue's (debug-layer message 836). - add_executable(d3d12_queue_list_type_test test/d3d12_queue_list_type_test.cpp) - target_link_libraries(d3d12_queue_list_type_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_queue_list_type_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_queue_list_type_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_queue_list_type COMMAND d3d12_queue_list_type_test) - set_tests_properties(d3d12_queue_list_type PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30) - # Cross-device ownership validation: Signal, Wait, SetEventOnMultipleFenceCompletion, ExecuteCommandLists, ExecuteBundle. - add_executable(d3d12_cross_device_validation_test test/d3d12_cross_device_validation_test.cpp) - target_link_libraries(d3d12_cross_device_validation_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_cross_device_validation_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_cross_device_validation_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_cross_device_validation COMMAND d3d12_cross_device_validation_test) - set_tests_properties(d3d12_cross_device_validation PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60 - FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") - # Wait-before-Signal with a texture and a buffer handed over between the COPY, COMPUTE and DIRECT queues, in every - # submission order, on the layer and on the host runtime (docs/d3d12_vulkan.md section 4.4). - add_executable(d3d12_queue_handover_test test/d3d12_queue_handover_test.cpp) - target_link_libraries(d3d12_queue_handover_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_queue_handover_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_queue_handover_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_queue_handover COMMAND d3d12_queue_handover_test) - set_tests_properties(d3d12_queue_handover PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 400 - FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") - # The same on a caller-owned device: two VkQueues handed to the layer (the D3D12 queues share them), and one - # (every D3D12 queue shares it, where a Wait ahead of its Signal would never progress on the GPU). - add_test(NAME d3d12_queue_handover_two_queues COMMAND d3d12_queue_handover_test --two-queues) - add_test(NAME d3d12_queue_handover_shared_queue COMMAND d3d12_queue_handover_test --shared-queue) - set_tests_properties(d3d12_queue_handover_two_queues d3d12_queue_handover_shared_queue PROPERTIES - SKIP_RETURN_CODE 77 TIMEOUT 400 FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") - # More D3D12 queues than Vulkan queues: they share VkQueues, keeping fences and Wait-before-Signal (section 4.4). - # The _one_queue runs make every GPU look like the Intel UHD 770 (one family, one VkQueue): every queue shares it. - add_executable(d3d12_queue_share_test test/d3d12_queue_share_test.cpp) - target_link_libraries(d3d12_queue_share_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_queue_share_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_queue_share_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_queue_share COMMAND d3d12_queue_share_test) - add_test(NAME d3d12_queue_share_one_queue COMMAND d3d12_queue_share_test) - set_tests_properties(d3d12_queue_share d3d12_queue_share_one_queue PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 300 - FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") - add_test(NAME d3d12_queue_wait_one_queue COMMAND d3d12_queue_wait_test) - set_tests_properties(d3d12_queue_wait_one_queue PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) - set_tests_properties(d3d12_queue_share_one_queue d3d12_queue_wait_one_queue PROPERTIES - ENVIRONMENT "LEONIDA_VK_MAX_QUEUES_PER_FAMILY=1;LEONIDA_VK_GRAPHICS_FAMILY_ONLY=1") - # A misspelt case or count is refused with the usage line (exit code 2) before a device exists, instead of - # passing with nothing run. No GPU needed. - set(_share_bad_arguments "case_typo|--case|typo" "iterations_zero|--iterations|0" - "iterations_word|--iterations|banana" "iterations_too_many|--iterations|99999999999") - foreach(_bad IN LISTS _share_bad_arguments) - string(REPLACE "|" ";" _bad "${_bad}") - list(POP_FRONT _bad _bad_name) - add_test(NAME d3d12_queue_share_rejects_${_bad_name} COMMAND d3d12_queue_share_test ${_bad}) - set_tests_properties(d3d12_queue_share_rejects_${_bad_name} PROPERTIES TIMEOUT 60 - PASS_REGULAR_EXPRESSION "\nusage: d3d12_queue_share_test ") - endforeach() - - # XDXR acceleration structures through BuildRaytracingAccelerationStructure (docs/d3d12_vulkan.md 4.8): the - # device builds them, tools/xdxr_bvh.py checks them. - add_executable(d3d12_xdxr_rt_test test/d3d12_xdxr_rt_test.cpp) - target_link_libraries(d3d12_xdxr_rt_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_xdxr_rt_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_xdxr_rt_test PRIVATE /W4 /permissive- /utf-8) - set(LEONIDA_D3D12_XDXR_OUT "${CMAKE_CURRENT_BINARY_DIR}/d3d12_xdxr_cases") - file(MAKE_DIRECTORY "${LEONIDA_D3D12_XDXR_OUT}") - add_test(NAME d3d12_xdxr_rt COMMAND d3d12_xdxr_rt_test "${LEONIDA_D3D12_XDXR_OUT}") - set_tests_properties(d3d12_xdxr_rt PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60 FIXTURES_SETUP d3d12_xdxr_cases) - find_package(Python3 COMPONENTS Interpreter QUIET) - if(Python3_FOUND) - add_test(NAME d3d12_xdxr_rt_check COMMAND "${Python3_EXECUTABLE}" -I - "${CMAKE_CURRENT_SOURCE_DIR}/../tools/xdxr_bvh.py" check-build "${LEONIDA_D3D12_XDXR_OUT}" --rays 1000) - set_tests_properties(d3d12_xdxr_rt_check PROPERTIES FIXTURES_REQUIRED d3d12_xdxr_cases SKIP_RETURN_CODE 77) - endif() - - # GCL8's QueryInterface and its one method need an allocator and a list, not a Vulkan device. - add_executable(d3d12_gcl8_test test/d3d12_gcl8_test.cpp) - target_link_libraries(d3d12_gcl8_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_gcl8_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_gcl8_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_gcl8 COMMAND d3d12_gcl8_test) - # Python runs on the host; a cross-compiled fixture runs through the emulator (Wine), which the script prepends. - # The interpreter is named by path, because ctest would put the emulator in front of an executable target. - set(_trace_runner) - foreach(_part IN LISTS CMAKE_CROSSCOMPILING_EMULATOR) - list(APPEND _trace_runner "--runner=${_part}") # one word each, even one that starts with "-" (xvfb-run -a) - endforeach() - add_test(NAME d3d12_trace COMMAND "${Python3_EXECUTABLE}" -I - "${CMAKE_CURRENT_SOURCE_DIR}/test/check_d3d12_trace.py" "$" ${_trace_runner}) - - # The Vulkan device behind the Xbox-ABI proxy, end to end. - add_executable(d3d12_vulkan_device_test test/d3d12_vulkan_device_test.cpp) - target_link_libraries(d3d12_vulkan_device_test PRIVATE gta6rt_d3d12_com dxguid) # IID_ID3D12MetaCommand (#1440) - target_compile_definitions(d3d12_vulkan_device_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_vulkan_device_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_vulkan_device COMMAND d3d12_vulkan_device_test) - - add_executable(d3d12_buffer_tiles_test test/d3d12_buffer_tiles_test.cpp) - target_link_libraries(d3d12_buffer_tiles_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_buffer_tiles_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_buffer_tiles_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_buffer_tiles COMMAND d3d12_buffer_tiles_test) - set_tests_properties(d3d12_buffer_tiles PROPERTIES SKIP_RETURN_CODE 77 - FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") - add_executable(d3d12_texture_tiles_test test/d3d12_texture_tiles_test.cpp) - target_link_libraries(d3d12_texture_tiles_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_texture_tiles_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_texture_tiles_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_texture_tiles COMMAND d3d12_texture_tiles_test) - set_tests_properties(d3d12_texture_tiles PROPERTIES SKIP_RETURN_CODE 77 - FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") - - # DXR acceleration-structure prebuild and command-list recording validation parity test. - add_executable(d3d12_dxr_validation_test test/d3d12_dxr_validation_test.cpp) - target_link_libraries(d3d12_dxr_validation_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_dxr_validation_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_dxr_validation_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_dxr_validation COMMAND d3d12_dxr_validation_test) - add_test(NAME d3d12_dxr_validation_khr COMMAND d3d12_dxr_validation_test) - set_tests_properties(d3d12_dxr_validation d3d12_dxr_validation_khr PROPERTIES SKIP_RETURN_CODE 77 - FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") - set_tests_properties(d3d12_dxr_validation_khr PROPERTIES ENVIRONMENT "LEONIDA_RT_AS=khr") - - # D3D12 permits UpdateTileMappings on DIRECT/COPY/COMPUTE and a sparse buffer must remain - # accessible across their selected Vulkan families. The optional API-dump check catches an - # EXCLUSIVE VkBuffer even on drivers that happen to return correct bytes without ownership barriers. - add_executable(d3d12_sparse_queue_family_test test/d3d12_sparse_queue_family_test.cpp) - target_link_libraries(d3d12_sparse_queue_family_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_sparse_queue_family_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_sparse_queue_family_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_sparse_queue_family COMMAND d3d12_sparse_queue_family_test) - set_tests_properties(d3d12_sparse_queue_family PROPERTIES SKIP_RETURN_CODE 77 - FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") - if(Python3_FOUND AND NOT CMAKE_CROSSCOMPILING) - add_test(NAME d3d12_sparse_queue_family_contract COMMAND "${Python3_EXECUTABLE}" -I - "${CMAKE_CURRENT_SOURCE_DIR}/test/check_sparse_queue_family.py" - "$") - set_tests_properties(d3d12_sparse_queue_family_contract PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 65) - endif() - set_tests_properties(d3d12_vulkan_device PROPERTIES SKIP_RETURN_CODE 77) - - add_executable(d3d12_texture1d_test test/d3d12_texture1d_test.cpp) - target_link_libraries(d3d12_texture1d_test PRIVATE gta6rt_d3d12_com dxguid) - target_compile_definitions(d3d12_texture1d_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_texture1d_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_texture1d COMMAND d3d12_texture1d_test) - set_tests_properties(d3d12_texture1d PROPERTIES SKIP_RETURN_CODE 77) - - # Placed 1D and 3D textures against the host runtime and WARP, and a copy round trip through them. - add_executable(d3d12_placed_dimensions_test test/d3d12_placed_dimensions_test.cpp) - target_link_libraries(d3d12_placed_dimensions_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_placed_dimensions_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_placed_dimensions_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_placed_dimensions COMMAND d3d12_placed_dimensions_test) - set_tests_properties(d3d12_placed_dimensions PROPERTIES SKIP_RETURN_CODE 77 - FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") - - # FORMAT_SUPPORT of the depth- and stencil-plane view formats and comparison sampling, against the host runtime. - add_executable(d3d12_depth_view_format_support_test test/d3d12_depth_view_format_support_test.cpp) - target_link_libraries(d3d12_depth_view_format_support_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_depth_view_format_support_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_depth_view_format_support_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_depth_view_format_support COMMAND d3d12_depth_view_format_support_test) - set_tests_properties(d3d12_depth_view_format_support PROPERTIES SKIP_RETURN_CODE 77) - - # A placed buffer keeps its heap's arena range after the application releases the heap. - add_executable(d3d12_placed_heap_lifetime_test test/d3d12_placed_heap_lifetime_test.cpp) - target_link_libraries(d3d12_placed_heap_lifetime_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_placed_heap_lifetime_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_placed_heap_lifetime_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_placed_heap_lifetime COMMAND d3d12_placed_heap_lifetime_test) - set_tests_properties(d3d12_placed_heap_lifetime PROPERTIES SKIP_RETURN_CODE 77 - FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") - - # ClearUnorderedAccessViewUint/Float on buffers and textures, read back through D3D12. - add_executable(d3d12_uav_clear_test test/d3d12_uav_clear_test.cpp) - target_link_libraries(d3d12_uav_clear_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_uav_clear_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_uav_clear_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_uav_clear COMMAND d3d12_uav_clear_test) - set_tests_properties(d3d12_uav_clear PROPERTIES SKIP_RETURN_CODE 77) - - add_executable(d3d12_short_uav_clear_test test/d3d12_short_uav_clear_test.cpp) - target_link_libraries(d3d12_short_uav_clear_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_short_uav_clear_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_short_uav_clear_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_short_uav_clear COMMAND d3d12_short_uav_clear_test) - set_tests_properties(d3d12_short_uav_clear PROPERTIES SKIP_RETURN_CODE 77 - ENVIRONMENT "LEONIDA_HOST_ADAPTER=warp") - - # Emulation of R9G9B9E5_SHAREDEXP UAV textures as mutable R32_UINT on GPUs without E5B9G9R9 storage: - # format support, 1D/2D/3D/reserved creation, SRV/UAV T#s, WARP differential UAV clears, cross-backing copies, - # and set-0 storage write -> E5B9G9R9 sampled HDR round-trip. - add_executable(d3d12_d24_support_test test/d3d12_d24_support_test.cpp) - target_link_libraries(d3d12_d24_support_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_d24_support_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_d24_support_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_d24_support COMMAND d3d12_d24_support_test) - set_tests_properties(d3d12_d24_support PROPERTIES SKIP_RETURN_CODE 77) - add_executable(d3d12_b5g5r5a1_uav_test test/d3d12_b5g5r5a1_uav_test.cpp) - target_link_libraries(d3d12_b5g5r5a1_uav_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_b5g5r5a1_uav_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_b5g5r5a1_uav_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_b5g5r5a1_uav COMMAND d3d12_b5g5r5a1_uav_test) - set_tests_properties(d3d12_b5g5r5a1_uav PROPERTIES SKIP_RETURN_CODE 77) - add_executable(d3d12_srgb_uav_test test/d3d12_srgb_uav_test.cpp) - target_link_libraries(d3d12_srgb_uav_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_srgb_uav_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_srgb_uav_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_srgb_uav COMMAND d3d12_srgb_uav_test) - set_tests_properties(d3d12_srgb_uav PROPERTIES SKIP_RETURN_CODE 77) # native sRGB storage, no Vulkan GPU, or Wine - add_executable(d3d12_r9g9b9e5_uav_test test/d3d12_r9g9b9e5_uav_test.cpp) - target_link_libraries(d3d12_r9g9b9e5_uav_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_r9g9b9e5_uav_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_r9g9b9e5_uav_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_r9g9b9e5_uav COMMAND d3d12_r9g9b9e5_uav_test) - set_tests_properties(d3d12_r9g9b9e5_uav PROPERTIES SKIP_RETURN_CODE 77) - if(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) - set(LEONIDA_TEST_CS_R9G9B9E5_UAV ${CMAKE_CURRENT_BINARY_DIR}/generated/cs_r9g9b9e5_uav.spv) - add_custom_command( - OUTPUT ${LEONIDA_TEST_CS_R9G9B9E5_UAV} - COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${LEONIDA_TEST_CS_R9G9B9E5_UAV} - ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_r9g9b9e5_uav.comp - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_r9g9b9e5_uav.comp - COMMENT "Compiling cs_r9g9b9e5_uav.comp" - VERBATIM) - target_sources(d3d12_r9g9b9e5_uav_test PRIVATE ${LEONIDA_TEST_CS_R9G9B9E5_UAV}) - target_compile_definitions(d3d12_r9g9b9e5_uav_test PRIVATE - LEONIDA_TEST_CS_R9G9B9E5_UAV_SPV="${LEONIDA_TEST_CS_R9G9B9E5_UAV}") - endif() - - # Debug markers as VK_EXT_debug_utils labels, and private data on every object (D3D-24). - add_executable(d3d12_debug_markers_test test/d3d12_debug_markers_test.cpp) - target_link_libraries(d3d12_debug_markers_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_debug_markers_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_debug_markers_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_debug_markers COMMAND d3d12_debug_markers_test) - set_tests_properties(d3d12_debug_markers PROPERTIES SKIP_RETURN_CODE 77) - - # Existing-memory heaps and lifetime trackers: the arguments the host refuses (OpenExistingHeapFromAddress, - # OpenExistingHeapFromFileMapping, CreateLifetimeTracker). - add_executable(d3d12_existing_heap_test test/d3d12_existing_heap_test.cpp) - target_link_libraries(d3d12_existing_heap_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_existing_heap_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_existing_heap_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_existing_heap COMMAND d3d12_existing_heap_test) - set_tests_properties(d3d12_existing_heap PROPERTIES SKIP_RETURN_CODE 77) - # Slot 133 on untouched xmem physical pages: committed through the pages hook, then imported. xmem.cpp and - # registry.cpp are compiled in, as xmem_test does, to reach the registered XMem* exports. - add_executable(d3d12_xmem_placed_test test/d3d12_xmem_placed_test.cpp shims/xmem.cpp shims/registry.cpp) - target_link_libraries(d3d12_xmem_placed_test PRIVATE gta6rt_d3d12_com d3d12 dxgi psapi) - target_compile_definitions(d3d12_xmem_placed_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_xmem_placed_test PRIVATE /W4 /permissive- /utf-8) - target_link_options(d3d12_xmem_placed_test PRIVATE /OPT:NOREF) - add_test(NAME d3d12_xmem_placed COMMAND d3d12_xmem_placed_test) - set_tests_properties(d3d12_xmem_placed PROPERTIES SKIP_RETURN_CODE 77) - - # Fences and timing (D3D-30): multiple-fence waits, clock calibration, adapter LUID, custom heap properties. - add_executable(d3d12_fence_timing_test test/d3d12_fence_timing_test.cpp) - target_link_libraries(d3d12_fence_timing_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_fence_timing_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_fence_timing_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_fence_timing COMMAND d3d12_fence_timing_test) - set_tests_properties(d3d12_fence_timing PROPERTIES SKIP_RETURN_CODE 77) - # Fence events the host runtime sets or refuses (released fences, no fences), compared with the host devices. - add_executable(d3d12_fence_events_test test/d3d12_fence_events_test.cpp) - target_link_libraries(d3d12_fence_events_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_fence_events_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_fence_events_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_fence_events COMMAND d3d12_fence_events_test) - set_tests_properties(d3d12_fence_events PROPERTIES SKIP_RETURN_CODE 77) - add_executable(d3d12_fence_device_lost_counter_test test/d3d12_fence_device_lost_counter_test.cpp) - target_link_libraries(d3d12_fence_device_lost_counter_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_fence_device_lost_counter_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_fence_device_lost_counter_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_fence_device_lost_counter COMMAND d3d12_fence_device_lost_counter_test) - set_tests_properties(d3d12_fence_device_lost_counter PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) - # Xbox-ABI queue and fence proxies behind the device proxy, on the host runtime (WARP, a hardware adapter) and - # on the Vulkan device: forwarding, refusal past the public chain, fence unwrapping. 77: no device at all. - add_executable(queue_proxy_test test/queue_proxy_test.cpp) - target_link_libraries(queue_proxy_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(queue_proxy_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(queue_proxy_test PRIVATE /W4 /permissive- /utf-8 /EHsc) - add_test(NAME queue_proxy COMMAND queue_proxy_test) - set_tests_properties(queue_proxy PROPERTIES SKIP_RETURN_CODE 77) - # Xbox-ABI command allocator proxies (device slot 9) on the Vulkan device, and the unwrapped PC allocator on the - # host runtime: forwarding, refused tail, guard region, lists and GPU copies on the proxy. 77: no device at all. - add_executable(allocator_proxy_test test/allocator_proxy_test.cpp) - target_link_libraries(allocator_proxy_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(allocator_proxy_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(allocator_proxy_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME allocator_proxy COMMAND allocator_proxy_test) - set_tests_properties(allocator_proxy PROPERTIES SKIP_RETURN_CODE 77) - # IDXGIDevice1 on the device proxy (the GDKX boot step: QueryInterface, GetAdapter, EnumOutputs), on the host - # runtime and on the Vulkan device: COM identity with the device, the adapter's LUID. 77: no device at all. - add_executable(dxgi_device_test test/dxgi_device_test.cpp) - target_link_libraries(dxgi_device_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(dxgi_device_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(dxgi_device_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME dxgi_device COMMAND dxgi_device_test) - set_tests_properties(dxgi_device PROPERTIES SKIP_RETURN_CODE 77) - add_executable(dxgi_host_answers_test test/dxgi_host_answers_test.cpp) - target_link_libraries(dxgi_host_answers_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(dxgi_host_answers_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(dxgi_host_answers_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME dxgi_host_answers COMMAND dxgi_host_answers_test) - set_tests_properties(dxgi_host_answers PROPERTIES SKIP_RETURN_CODE 77) - # The countdown behind those event-backed waits, with no GPU: the full unsigned count, no wrap past zero. - add_executable(d3d12_fence_waiter_test test/d3d12_fence_waiter_test.cpp) - target_compile_definitions(d3d12_fence_waiter_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_fence_waiter_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_fence_waiter COMMAND d3d12_fence_waiter_test) - # The 1/2/3 method variants (D3D-28) against the methods they wrap, on the Vulkan device directly. - add_executable(d3d12_method_variants_test test/d3d12_method_variants_test.cpp) - target_link_libraries(d3d12_method_variants_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_method_variants_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_method_variants_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_method_variants COMMAND d3d12_method_variants_test) - # ID3D12Device9::CreateShaderCacheSession, ID3D12ShaderCacheSession and ShaderCacheControl (D3D-34). - add_executable(d3d12_shader_cache_test test/d3d12_shader_cache_test.cpp) - target_link_libraries(d3d12_shader_cache_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_shader_cache_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_shader_cache_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_shader_cache COMMAND d3d12_shader_cache_test) - set_tests_properties(d3d12_shader_cache PROPERTIES SKIP_RETURN_CODE 77) - set_tests_properties(d3d12_method_variants PROPERTIES SKIP_RETURN_CODE 77) - # ID3D12Object private data (GetPrivateData, SetPrivateData, SetPrivateDataInterface, SetName) compared with - # the host runtime's answers on the device and four child objects. - add_executable(d3d12_private_data_test test/d3d12_private_data_test.cpp) - target_link_libraries(d3d12_private_data_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_private_data_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_private_data_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_private_data COMMAND d3d12_private_data_test) - set_tests_properties(d3d12_private_data PROPERTIES SKIP_RETURN_CODE 77) - - # CreateSampler2 (D3D-28) against CreateSampler, and its refusals against the host's PC runtime. - add_executable(d3d12_sampler2_test test/d3d12_sampler2_test.cpp) - target_link_libraries(d3d12_sampler2_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_sampler2_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_sampler2_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_sampler2 COMMAND d3d12_sampler2_test) - set_tests_properties(d3d12_sampler2 PROPERTIES SKIP_RETURN_CODE 77) - - # Descriptors through the proxy: copies between heaps, what texture views and samplers write into their slots, - # and (where glslangValidator is found) a compute shader the test runs on the device's bindless set, which - # finds a T# and an S# through the hash table and samples. The shader is GLSL, compiled here. - add_executable(d3d12_descriptor_test test/d3d12_descriptor_test.cpp) - target_link_libraries(d3d12_descriptor_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_descriptor_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_descriptor_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_descriptor COMMAND d3d12_descriptor_test) - set_tests_properties(d3d12_descriptor PROPERTIES SKIP_RETURN_CODE 77) - if(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) - function(descriptor_test_shader shader definition) - set(source ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${shader}) - set(binary ${CMAKE_CURRENT_BINARY_DIR}/generated/${definition}.spv) - add_custom_command(OUTPUT ${binary} - COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 ${ARGN} -o ${binary} ${source} - DEPENDS ${source} COMMENT "Compiling descriptor test shader ${shader}" VERBATIM) - target_sources(d3d12_descriptor_test PRIVATE ${binary}) - target_compile_definitions(d3d12_descriptor_test PRIVATE ${definition}="${binary}") - endfunction() - descriptor_test_shader(cs_sample.comp LEONIDA_TEST_CS_SAMPLE_SPV) - descriptor_test_shader(cs_sample.comp LEONIDA_TEST_GATHER_ALPHA_SPV -DTEST_GATHER_ALPHA=1) - descriptor_test_shader(cs_sample.comp LEONIDA_TEST_MS_FLOAT_SPV -DTEST_MS_FLOAT=1) - descriptor_test_shader(cs_sample.comp LEONIDA_TEST_MS_UINT_SPV -DTEST_MS_UINT=1) - descriptor_test_shader(cs_sample.comp LEONIDA_TEST_MS_SINT_SPV -DTEST_MS_SINT=1) - descriptor_test_shader(msaa_seed.vert LEONIDA_TEST_MSAA_VERT_SPV) - descriptor_test_shader(msaa_seed.frag LEONIDA_TEST_MSAA_FRAG_SPV) - else() - message(STATUS "glslangValidator not found: d3d12_descriptor_test skips its shader") - endif() - - add_executable(d3d12_predicated_copy_test test/d3d12_predicated_copy_test.cpp) - target_link_libraries(d3d12_predicated_copy_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_predicated_copy_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_predicated_copy_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_predicated_copy COMMAND d3d12_predicated_copy_test) - set_tests_properties(d3d12_predicated_copy PROPERTIES SKIP_RETURN_CODE 77) - # A DISPATCH-only ExecuteIndirect signature with a GPU count buffer: native Windows WARP versus Vulkan GPU, - # including a GPU-written count that changes between two calls in the same command list. - if(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) - set(_indirect_count_spv ${CMAKE_CURRENT_BINARY_DIR}/generated/cs_indirect_dispatch_count.spv) - add_custom_command(OUTPUT ${_indirect_count_spv} - COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.2 - -o ${_indirect_count_spv} ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_indirect_dispatch_count.comp - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_indirect_dispatch_count.comp - COMMENT "Compiling the counted indirect dispatch test shader" VERBATIM) - add_executable(d3d12_indirect_dispatch_count_test test/d3d12_indirect_dispatch_count_test.cpp - ${_indirect_count_spv}) - target_link_libraries(d3d12_indirect_dispatch_count_test PRIVATE gta6rt_d3d12_com d3d12 dxgi version) - target_compile_definitions(d3d12_indirect_dispatch_count_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_TEST_INDIRECT_COUNT_SPV="${_indirect_count_spv}") - target_compile_options(d3d12_indirect_dispatch_count_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_indirect_dispatch_count COMMAND d3d12_indirect_dispatch_count_test) - set_tests_properties(d3d12_indirect_dispatch_count PROPERTIES SKIP_RETURN_CODE 77) - endif() - - # What Close returns after one recorded call, against WARP; today's differences are listed in the test. - add_executable(d3d12_close_parity_test test/d3d12_close_parity_test.cpp) - target_link_libraries(d3d12_close_parity_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_close_parity_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_close_parity_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_close_parity COMMAND d3d12_close_parity_test) - set_tests_properties(d3d12_close_parity PROPERTIES SKIP_RETURN_CODE 77) - - # ExecuteIndirect recording-time Close() parity against live WARP and hardware D3D12, plus GPU dispatch sanity. - add_executable(d3d12_execute_indirect_validation_test test/d3d12_execute_indirect_validation_test.cpp) - target_link_libraries(d3d12_execute_indirect_validation_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_execute_indirect_validation_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_execute_indirect_validation_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_execute_indirect_validation COMMAND d3d12_execute_indirect_validation_test) - set_tests_properties(d3d12_execute_indirect_validation PROPERTIES - SKIP_RETURN_CODE 77 - FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") - - # Set{Compute,Graphics}Root* closed-list, zero-count null, CBV alignment, and foreign root signature parity. - add_executable(d3d12_root_args_validation_test test/d3d12_root_args_validation_test.cpp) - target_link_libraries(d3d12_root_args_validation_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_root_args_validation_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_root_args_validation_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_root_args_validation COMMAND d3d12_root_args_validation_test) - set_tests_properties(d3d12_root_args_validation PROPERTIES - SKIP_RETURN_CODE 77 - FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") + # The standalone Vulkan tools and the Vulkan tests that do not use the D3D12 COM objects. + include("${CMAKE_CURRENT_SOURCE_DIR}/cmake/vulkan_tools.cmake") + # The D3D12 COM objects over the Vulkan backend and their tests. + include("${CMAKE_CURRENT_SOURCE_DIR}/cmake/d3d12_vulkan.cmake") - # ClearState predication reset (GPU readback) + SetPredication / AtomicCopyBuffer Close() parity against WARP & HW. - add_executable(d3d12_predication_atomic_copy_test test/d3d12_predication_atomic_copy_test.cpp) - target_link_libraries(d3d12_predication_atomic_copy_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_predication_atomic_copy_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_predication_atomic_copy_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_predication_atomic_copy COMMAND d3d12_predication_atomic_copy_test) - set_tests_properties(d3d12_predication_atomic_copy PROPERTIES - SKIP_RETURN_CODE 77 - FAIL_REGULAR_EXPRESSION "Validation Error;VUID-" - ) - - # Differential regression: run explicitly (requires Vulkan hardware and Windows WARP). - add_executable(d3d12_clear_test test/d3d12_clear_test.cpp) - target_link_libraries(d3d12_clear_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_clear_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_clear_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_rgb9e5_rtv COMMAND d3d12_clear_test --rgb9e5) - set_tests_properties(d3d12_rgb9e5_rtv PROPERTIES SKIP_RETURN_CODE 77) - add_test(NAME d3d12_clear COMMAND d3d12_clear_test) - set_tests_properties(d3d12_clear PROPERTIES SKIP_RETURN_CODE 77) - - # Synthetic typed-view readbacks against Windows WARP; run explicitly on a Vulkan GPU. - add_executable(d3d12_typeless_rtv_test test/d3d12_typeless_rtv_test.cpp) - target_link_libraries(d3d12_typeless_rtv_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_typeless_rtv_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_typeless_rtv_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_typeless_rtv COMMAND d3d12_typeless_rtv_test) - # 1D render targets and depth buffers: creation against the host and WARP, clears read back against WARP. - add_executable(d3d12_texture1d_target_test test/d3d12_texture1d_target_test.cpp) - target_link_libraries(d3d12_texture1d_target_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_texture1d_target_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_texture1d_target_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_texture1d_target COMMAND d3d12_texture1d_target_test) - set_tests_properties(d3d12_texture1d_target PROPERTIES SKIP_RETURN_CODE 77) # no Vulkan GPU, or Wine - - # ArraySize -1 in array RTVs and DSVs (every slice from the first on), against the host on the same adapter - # and WARP. - add_executable(d3d12_view_slices_test test/d3d12_view_slices_test.cpp) - target_link_libraries(d3d12_view_slices_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_view_slices_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_view_slices_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_view_slices COMMAND d3d12_view_slices_test) - set_tests_properties(d3d12_view_slices PROPERTIES SKIP_RETURN_CODE 77) - - # Typed RTV clears and draws of every TYPELESS color family against the host on the same adapter and WARP - # (D3D-275). The draws need glslangValidator for their GLSL stand-ins of translated shaders. - add_executable(d3d12_typeless_families_test test/d3d12_typeless_families_test.cpp) - target_link_libraries(d3d12_typeless_families_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_typeless_families_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_typeless_families_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_typeless_families COMMAND d3d12_typeless_families_test) - set_tests_properties(d3d12_typeless_families PROPERTIES SKIP_RETURN_CODE 77) - if(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) - foreach(pair "vs_fullscreen.vert;LEONIDA_TYPELESS_VS_SPV;typeless_vs.spv" - "ps_typeless_float.frag;LEONIDA_TYPELESS_PS_FLOAT_SPV;typeless_ps_float.spv" - "ps_typeless_uint.frag;LEONIDA_TYPELESS_PS_UINT_SPV;typeless_ps_uint.spv") - list(GET pair 0 shader) - list(GET pair 1 definition) - list(GET pair 2 name) - set(binary ${CMAKE_CURRENT_BINARY_DIR}/generated/${name}) - add_custom_command(OUTPUT ${binary} - COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${binary} - ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${shader} - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${shader} - COMMENT "Compiling the typeless draw test shader ${shader}" VERBATIM) - target_sources(d3d12_typeless_families_test PRIVATE ${binary}) - target_compile_definitions(d3d12_typeless_families_test PRIVATE ${definition}="${binary}") - endforeach() - else() - message(STATUS "glslangValidator not found: d3d12_typeless_families_test runs its clears only") - endif() - - # Fixed-function state (blend, depth, stencil) swept against the host D3D12 device on the same adapter. Needs - # glslangValidator for the GLSL stand-ins of translated shaders. - if(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) - add_executable(d3d12_state_sweep_test test/d3d12_state_sweep_test.cpp) - target_link_libraries(d3d12_state_sweep_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_state_sweep_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_state_sweep_test PRIVATE /W4 /permissive- /utf-8) - foreach(pair "vs_fullscreen.vert;LEONIDA_SWEEP_VS_SPV;sweep_vs.spv" - "ps_sweep.frag;LEONIDA_SWEEP_PS_SPV;sweep_ps.spv") - list(GET pair 0 shader) - list(GET pair 1 definition) - list(GET pair 2 name) - set(binary ${CMAKE_CURRENT_BINARY_DIR}/generated/${name}) - add_custom_command(OUTPUT ${binary} - COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${binary} - ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${shader} - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${shader} - COMMENT "Compiling the state sweep test shader ${shader}" VERBATIM) - target_sources(d3d12_state_sweep_test PRIVATE ${binary}) - target_compile_definitions(d3d12_state_sweep_test PRIVATE ${definition}="${binary}") - endforeach() - add_test(NAME d3d12_state_sweep COMMAND d3d12_state_sweep_test) - set_tests_properties(d3d12_state_sweep PROPERTIES SKIP_RETURN_CODE 77) - endif() - - # 96-bit R32G32B32 textures (D3D-62): footprints and every copy path against Windows WARP. - add_executable(d3d12_rgb96_test test/d3d12_rgb96_test.cpp) - target_link_libraries(d3d12_rgb96_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_rgb96_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_rgb96_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_rgb96 COMMAND d3d12_rgb96_test) - set_tests_properties(d3d12_rgb96 PROPERTIES SKIP_RETURN_CODE 77) # no Vulkan GPU or no WARP adapter - set_tests_properties(d3d12_typeless_rtv PROPERTIES SKIP_RETURN_CODE 77) - - # Depth/stencil ResolveSubresourceRegion against the host runtime and WARP; run explicitly on a Vulkan GPU. - add_executable(d3d12_depth_resolve_test test/d3d12_depth_resolve_test.cpp) - target_link_libraries(d3d12_depth_resolve_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_depth_resolve_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_depth_resolve_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_depth_resolve COMMAND d3d12_depth_resolve_test) - set_tests_properties(d3d12_depth_resolve PROPERTIES SKIP_RETURN_CODE 77) - # The edge cases (TEST-848) draw with a GLSL stand-in for a translated vertex shader; without glslangValidator - # only the clear cases run. - if(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) - set(binary ${CMAKE_CURRENT_BINARY_DIR}/generated/depth_edge_vs.spv) - add_custom_command(OUTPUT ${binary} - COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${binary} - ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/vs_depth_edge.vert - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/vs_depth_edge.vert - COMMENT "Compiling the depth resolve test shader vs_depth_edge.vert" VERBATIM) - target_sources(d3d12_depth_resolve_test PRIVATE ${binary}) - target_compile_definitions(d3d12_depth_resolve_test PRIVATE LEONIDA_DEPTH_EDGE_VS_SPV="${binary}") - endif() - - # ID3D12Resource::GetDesc against the host runtime and WARP; run explicitly on a Vulkan GPU. - add_executable(d3d12_resource_desc_test test/d3d12_resource_desc_test.cpp) - target_link_libraries(d3d12_resource_desc_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_resource_desc_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_resource_desc_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_resource_desc COMMAND d3d12_resource_desc_test) - set_tests_properties(d3d12_resource_desc PROPERTIES SKIP_RETURN_CODE 77) - - # Typeless depth-stencil textures without ALLOW_DEPTH_STENCIL, copied from a depth buffer, against WARP. - add_executable(d3d12_typeless_depth_test test/d3d12_typeless_depth_test.cpp) - target_link_libraries(d3d12_typeless_depth_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_typeless_depth_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_typeless_depth_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_typeless_depth COMMAND d3d12_typeless_depth_test) - set_tests_properties(d3d12_typeless_depth PROPERTIES SKIP_RETURN_CODE 77) - - # WriteToSubresource/ReadFromSubresource arguments and bytes, compared with the host runtime. - add_executable(d3d12_subresource_copy_test test/d3d12_subresource_copy_test.cpp) - target_link_libraries(d3d12_subresource_copy_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_subresource_copy_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_subresource_copy_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_subresource_copy COMMAND d3d12_subresource_copy_test) - set_tests_properties(d3d12_subresource_copy PROPERTIES SKIP_RETURN_CODE 77) - - # MakeResident, Evict, SetResidencyPriority and EnqueueMakeResident, compared with the host runtime. - add_executable(d3d12_residency_test test/d3d12_residency_test.cpp) - target_link_libraries(d3d12_residency_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_residency_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_residency_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_residency COMMAND d3d12_residency_test) - set_tests_properties(d3d12_residency PROPERTIES SKIP_RETURN_CODE 77) - - # ID3D12Resource::GetHeapProperties for committed, placed and reserved resources, compared with the host runtime. - add_executable(d3d12_heap_properties_test test/d3d12_heap_properties_test.cpp) - target_link_libraries(d3d12_heap_properties_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_heap_properties_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_heap_properties_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_heap_properties COMMAND d3d12_heap_properties_test) - set_tests_properties(d3d12_heap_properties PROPERTIES SKIP_RETURN_CODE 77) - - # CreatePipelineLibrary and ID3D12PipelineLibrary1 arguments, compared with the host runtime. - add_executable(d3d12_pipeline_library_host_test test/d3d12_pipeline_library_host_test.cpp) - target_link_libraries(d3d12_pipeline_library_host_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_pipeline_library_host_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_pipeline_library_host_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_pipeline_library_host COMMAND d3d12_pipeline_library_host_test) - set_tests_properties(d3d12_pipeline_library_host PROPERTIES SKIP_RETURN_CODE 77) - - # Milestone M0: a window, 60 cleared frames presented through the proxy on Vulkan. - add_executable(d3d12_present_test test/d3d12_present_test.cpp) - target_link_libraries(d3d12_present_test PRIVATE gta6rt_d3d12_com user32 gdi32 dxgi) - target_compile_definitions(d3d12_present_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_present_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_present COMMAND d3d12_present_test) - set_tests_properties(d3d12_present PROPERTIES SKIP_RETURN_CODE 77) - - # Per-pipeline --f16-interp-fallback linking (SHADER-378): 16-param VS + colliding PS rendered on Vulkan. - add_executable(d3d12_f16_halves_test test/d3d12_f16_halves_test.cpp shims/d3d12_xs_device.cpp) - target_link_libraries(d3d12_f16_halves_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_f16_halves_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_f16_halves_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_f16_halves COMMAND d3d12_f16_halves_test) - set_tests_properties(d3d12_f16_halves PROPERTIES SKIP_RETURN_CODE 77) - - # PresentX and the frame events on the Vulkan device (shims/xbox_present.h), checked on swapchain pixels. - add_executable(xbox_present_test test/xbox_present_test.cpp) - target_link_libraries(xbox_present_test PRIVATE gta6rt_d3d12_com user32) - target_compile_definitions(xbox_present_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(xbox_present_test PRIVATE /W4 /permissive- /utf-8) - # Needs a Vulkan GPU and a window; exits 77 (skipped) without a Vulkan device. - add_test(NAME xbox_present COMMAND xbox_present_test) - set_tests_properties(xbox_present PROPERTIES SKIP_RETURN_CODE 77) - - # TEST-528: a real boot-movie frame (the package's Bink2Scarlett.dll) uploaded through the Xbox-ABI proxy and - # presented with PresentX, checked against the decoded BGRA. Package-gated like bink_decode_test: skips (77) - # unless LEONIDA_GAME_DIR and LEONIDA_MOVIE are set; no game data is written into the repo. - add_executable(d3d12_boot_movie_test - test/d3d12_boot_movie_test.cpp - src/pe_loader.cpp - shims/registry.cpp - shims/xmem.cpp - ) - target_link_libraries(d3d12_boot_movie_test PRIVATE gta6rt_d3d12_com user32 psapi) - target_compile_definitions(d3d12_boot_movie_test PRIVATE - WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE _CRT_SECURE_NO_WARNINGS) - target_compile_options(d3d12_boot_movie_test PRIVATE /W4 /permissive- /utf-8 /EHsc) - target_link_options(d3d12_boot_movie_test PRIVATE /OPT:NOREF) - add_dependencies(d3d12_boot_movie_test gta6rt_tls_host) - add_test(NAME d3d12_boot_movie COMMAND d3d12_boot_movie_test) - set_tests_properties(d3d12_boot_movie PROPERTIES SKIP_RETURN_CODE 77) - - # First light through D3D12 (docs/first_light.md): the real model and translated VS/PS that tools/first_light.py - # wrote to LEONIDA_FIRST_LIGHT_DIR, drawn through the device proxy. Skips (77) unless that variable is set. - add_executable(d3d12_first_light_test test/d3d12_first_light_test.cpp shims/d3d12_xs_device.cpp) - target_link_libraries(d3d12_first_light_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_first_light_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS) - target_compile_options(d3d12_first_light_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_first_light COMMAND d3d12_first_light_test) - set_tests_properties(d3d12_first_light PROPERTIES SKIP_RETURN_CODE 77) - - # M1.5 (D3D-53): a draw whose VS and PS are translator output. test/shaders/vs_m15.asm and ps_m15.asm are assembled - # with llvm-mc and translated by tools/rdna2spirv.py through test/shaders/build.py, which also writes the FSSM - # programs their index entries are keyed by. Needs llvm-mc with the AMDGPU target (LLVM_MC in the environment, as - # for the other shader tests, or llvm-mc on PATH or in C:/msys64/ucrt64/bin) and the Vulkan SDK's spirv-as and - # spirv-val; without them the test is not built. - if(NOT LEONIDA_LLVM_MC) - if(DEFINED ENV{LLVM_MC}) - set(LEONIDA_LLVM_MC "$ENV{LLVM_MC}") - else() - find_program(LEONIDA_LLVM_MC llvm-mc HINTS "C:/msys64/ucrt64/bin") - endif() - endif() - find_program(LEONIDA_SPIRV_AS spirv-as HINTS "$ENV{VULKAN_SDK}/Bin" "$ENV{VULKAN_SDK}/bin") - find_program(LEONIDA_SPIRV_VAL spirv-val HINTS "$ENV{VULKAN_SDK}/Bin" "$ENV{VULKAN_SDK}/bin") - if(LEONIDA_LLVM_MC AND LEONIDA_SPIRV_AS AND LEONIDA_SPIRV_VAL) - set(LEONIDA_M15_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/m15_shaders) - get_filename_component(LEONIDA_SPIRV_TOOLS_DIR ${LEONIDA_SPIRV_AS} DIRECTORY) - file(TO_NATIVE_PATH "${LEONIDA_SPIRV_TOOLS_DIR}" LEONIDA_SPIRV_TOOLS_NATIVE) - set(LEONIDA_M15_FILES ${LEONIDA_M15_DIR}/spirv/index.json ${LEONIDA_M15_DIR}/fssm/vs_m15.fssm - ${LEONIDA_M15_DIR}/fssm/ps_m15.fssm) - add_custom_command( - OUTPUT ${LEONIDA_M15_FILES} - COMMAND ${CMAKE_COMMAND} -E remove_directory ${LEONIDA_M15_DIR} - COMMAND ${CMAKE_COMMAND} -E env "LLVM_MC=${LEONIDA_LLVM_MC}" "LEONIDA_SPIRV_TOOLS=${LEONIDA_SPIRV_TOOLS_NATIVE}" - $ -I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py - ${LEONIDA_M15_DIR} vs_m15 ps_m15 - DEPENDS ${LEONIDA_TRANSLATOR_DEPS} - ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/vs_m15.asm - ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_m15.asm - COMMENT "Translating vs_m15 and ps_m15 for the translated draw test" - VERBATIM) - add_executable(d3d12_translated_draw_test test/d3d12_translated_draw_test.cpp shims/d3d12_xs_device.cpp - ${LEONIDA_M15_FILES}) - target_link_libraries(d3d12_translated_draw_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_translated_draw_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_TEST_M15_DIR="${LEONIDA_M15_DIR}") - target_compile_options(d3d12_translated_draw_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_translated_draw COMMAND d3d12_translated_draw_test) - set_tests_properties(d3d12_translated_draw PROPERTIES SKIP_RETURN_CODE 77) - - # vk_bindless_test (the bindless set and its table at the Vulkan level, no D3D12) takes the translated vs_ids, - # ps_tex and ps_imgatomic; it was only run by scripts/run_gpu_tests.py and check.py until D3D-314 needed it. - set(LEONIDA_BINDLESS_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/bindless_shaders) - set(LEONIDA_BINDLESS_FILES ${LEONIDA_BINDLESS_DIR}/spirv/vs_ids.spv ${LEONIDA_BINDLESS_DIR}/spirv/ps_tex.spv - ${LEONIDA_BINDLESS_DIR}/spirv/ps_imgatomic.spv) - add_custom_command( - OUTPUT ${LEONIDA_BINDLESS_FILES} - COMMAND ${CMAKE_COMMAND} -E remove_directory ${LEONIDA_BINDLESS_DIR} - COMMAND ${CMAKE_COMMAND} -E env "LLVM_MC=${LEONIDA_LLVM_MC}" "LEONIDA_SPIRV_TOOLS=${LEONIDA_SPIRV_TOOLS_NATIVE}" - $ -I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py - ${LEONIDA_BINDLESS_DIR} vs_ids ps_tex ps_imgatomic - DEPENDS ${LEONIDA_TRANSLATOR_DEPS} - ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/vs_ids.asm - ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_tex.asm - ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_imgatomic.asm - COMMENT "Translating vs_ids, ps_tex and ps_imgatomic for vk_bindless_test" - VERBATIM) - add_custom_target(vk_bindless_shaders ALL DEPENDS ${LEONIDA_BINDLESS_FILES}) - add_dependencies(vk_bindless_test vk_bindless_shaders) - add_test(NAME vk_bindless_ps_tex COMMAND vk_bindless_test ${LEONIDA_BINDLESS_DIR}/spirv/vs_ids.spv - ${LEONIDA_BINDLESS_DIR}/spirv/ps_tex.spv) - add_test(NAME vk_bindless_ps_imgatomic COMMAND vk_bindless_test ${LEONIDA_BINDLESS_DIR}/spirv/vs_ids.spv - ${LEONIDA_BINDLESS_DIR}/spirv/ps_imgatomic.spv) - set_tests_properties(vk_bindless_ps_tex vk_bindless_ps_imgatomic PROPERTIES SKIP_RETURN_CODE 77) - - # M2: a textured quad. vs_m2.asm and ps_m2.asm (the PS samples a T#/S# it loads from two descriptor tables) go - # through the same build; the test creates the heaps, the SRV, the sampler and the root signature through the - # D3D12 API only. - set(LEONIDA_M2_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/m2_shaders) - set(LEONIDA_M2_FILES ${LEONIDA_M2_DIR}/spirv/index.json ${LEONIDA_M2_DIR}/fssm/vs_m2.fssm - ${LEONIDA_M2_DIR}/fssm/ps_m2.fssm ${LEONIDA_M2_DIR}/fssm/ps_m2_uoff.fssm - ${LEONIDA_M2_DIR}/fssm/ps_m2_literal.fssm) - add_custom_command( - OUTPUT ${LEONIDA_M2_FILES} - COMMAND ${CMAKE_COMMAND} -E remove_directory ${LEONIDA_M2_DIR} - COMMAND ${CMAKE_COMMAND} -E env "LLVM_MC=${LEONIDA_LLVM_MC}" "LEONIDA_SPIRV_TOOLS=${LEONIDA_SPIRV_TOOLS_NATIVE}" - $ -I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py - ${LEONIDA_M2_DIR} vs_m2 ps_m2 ps_m2_uoff ps_m2_literal - DEPENDS ${LEONIDA_TRANSLATOR_DEPS} - ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/vs_m2.asm - ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_m2.asm - ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_m2_uoff.asm - ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_m2_literal.asm - COMMENT "Translating vs_m2 and ps_m2 for the textured draw test" - VERBATIM) - add_executable(d3d12_m2_textured_test test/d3d12_m2_textured_test.cpp shims/d3d12_xs_device.cpp - ${LEONIDA_M2_FILES}) - target_link_libraries(d3d12_m2_textured_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_m2_textured_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_TEST_M2_DIR="${LEONIDA_M2_DIR}") - target_compile_options(d3d12_m2_textured_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_m2_textured COMMAND d3d12_m2_textured_test) - set_tests_properties(d3d12_m2_textured PROPERTIES SKIP_RETURN_CODE 77) - - # M2, formats: BC1 and BC7 textures with mip chains and an R8G8B8A8 2D array through the same descriptor path. - # vs_m2.asm with ps_m2.asm (2D) and ps_m2_array.asm (2D array, slice 1.0 of the view). - set(LEONIDA_M2F_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/m2f_shaders) - set(LEONIDA_M2F_FILES ${LEONIDA_M2F_DIR}/spirv/index.json ${LEONIDA_M2F_DIR}/fssm/vs_m2.fssm - ${LEONIDA_M2F_DIR}/fssm/ps_m2.fssm ${LEONIDA_M2F_DIR}/fssm/ps_m2_array.fssm) - add_custom_command( - OUTPUT ${LEONIDA_M2F_FILES} - COMMAND ${CMAKE_COMMAND} -E remove_directory ${LEONIDA_M2F_DIR} - COMMAND ${CMAKE_COMMAND} -E env "LLVM_MC=${LEONIDA_LLVM_MC}" "LEONIDA_SPIRV_TOOLS=${LEONIDA_SPIRV_TOOLS_NATIVE}" - $ -I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py - ${LEONIDA_M2F_DIR} vs_m2 ps_m2 ps_m2_array - DEPENDS ${LEONIDA_TRANSLATOR_DEPS} - ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/vs_m2.asm - ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_m2.asm - ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_m2_array.asm - COMMENT "Translating vs_m2, ps_m2 and ps_m2_array for the M2 formats test" - VERBATIM) - add_executable(d3d12_m2_formats_test test/d3d12_m2_formats_test.cpp shims/d3d12_xs_device.cpp - ${LEONIDA_M2F_FILES}) - target_link_libraries(d3d12_m2_formats_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_m2_formats_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_TEST_M2F_DIR="${LEONIDA_M2F_DIR}") - target_compile_options(d3d12_m2_formats_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_m2_formats COMMAND d3d12_m2_formats_test) - set_tests_properties(d3d12_m2_formats PROPERTIES SKIP_RETURN_CODE 77) - - # M3 (synthetic part): frames with two render targets and a depth/stencil buffer, an occlusion query, resource - # barriers and a second pass that samples the first one's target, three frames in flight with a fence each. - # Pass 1's two-output PS and its single-output occlusion probe go through the same translator build. - set(LEONIDA_M3_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/m3_shaders) - set(LEONIDA_M3_FILES ${LEONIDA_M3_DIR}/spirv/index.json ${LEONIDA_M3_DIR}/fssm/vs_m3.fssm - ${LEONIDA_M3_DIR}/fssm/ps_m3.fssm ${LEONIDA_M3_DIR}/fssm/vs_m2.fssm - ${LEONIDA_M3_DIR}/fssm/ps_m3_post.fssm ${LEONIDA_M3_DIR}/fssm/ps_m3_query.fssm) - add_custom_command( - OUTPUT ${LEONIDA_M3_FILES} - COMMAND ${CMAKE_COMMAND} -E remove_directory ${LEONIDA_M3_DIR} - COMMAND ${CMAKE_COMMAND} -E env "LLVM_MC=${LEONIDA_LLVM_MC}" "LEONIDA_SPIRV_TOOLS=${LEONIDA_SPIRV_TOOLS_NATIVE}" - $ -I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py - ${LEONIDA_M3_DIR} vs_m3 ps_m3 vs_m2 ps_m3_post ps_m3_query - DEPENDS ${LEONIDA_TRANSLATOR_DEPS} - ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/vs_m3.asm - ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_m3.asm - ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/vs_m2.asm - ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_m3_post.asm - ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_m3_query.asm - COMMENT "Translating M3 frame and single-output occlusion-probe shaders" - VERBATIM) - add_executable(d3d12_m3_frame_test test/d3d12_m3_frame_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_M3_FILES}) - target_link_libraries(d3d12_m3_frame_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_m3_frame_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_TEST_M3_DIR="${LEONIDA_M3_DIR}") - target_compile_options(d3d12_m3_frame_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_m3_frame COMMAND d3d12_m3_frame_test) - add_test(NAME d3d12_m3_first_pass COMMAND d3d12_m3_frame_test --first-pass-only) - set_tests_properties(d3d12_m3_frame d3d12_m3_first_pass PROPERTIES SKIP_RETURN_CODE 77) - - # M4 (synthetic part): compute PSOs, a UAV table (structured and raw buffers, an R32_UINT storage image), an indirect - # dispatch from arguments a first dispatch wrote, and a copy queue that streams the input in and reads the results - # back across queue fences. cs_m4_fill.asm and cs_m4_indirect.asm go through the same build; build.py publishes - # their synthetic FSSM programs (the compute header and the words their "fssm-data" comments give), which the - # test wraps in shader containers. - set(LEONIDA_M4_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/m4_shaders) - set(LEONIDA_M4_FILES ${LEONIDA_M4_DIR}/spirv/index.json ${LEONIDA_M4_DIR}/fssm/cs_m4_fill.fssm - ${LEONIDA_M4_DIR}/fssm/cs_m4_indirect.fssm) - add_custom_command( - OUTPUT ${LEONIDA_M4_FILES} - COMMAND ${CMAKE_COMMAND} -E remove_directory ${LEONIDA_M4_DIR} - # LEONIDA_USER_DATA_SHIFT=4: the fixtures read their user data from s0; a D3D12 compute PSO gets its root - # arguments from s4 (rt::rootsig::pack_stage, D3D-448), so they are built with every SGPR 4 higher. - COMMAND ${CMAKE_COMMAND} -E env "LLVM_MC=${LEONIDA_LLVM_MC}" "LEONIDA_SPIRV_TOOLS=${LEONIDA_SPIRV_TOOLS_NATIVE}" - LEONIDA_USER_DATA_SHIFT=4 - $ -I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py - ${LEONIDA_M4_DIR} cs_m4_fill cs_m4_indirect - DEPENDS ${LEONIDA_TRANSLATOR_DEPS} - ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/cs_m4_fill.asm - ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/cs_m4_indirect.asm - COMMENT "Translating cs_m4_fill and cs_m4_indirect for the compute test" - VERBATIM) - add_executable(d3d12_m4_compute_test test/d3d12_m4_compute_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_M4_FILES}) - target_link_libraries(d3d12_m4_compute_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_m4_compute_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_TEST_M4_DIR="${LEONIDA_M4_DIR}") - target_compile_options(d3d12_m4_compute_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_m4_compute COMMAND d3d12_m4_compute_test) - set_tests_properties(d3d12_m4_compute PROPERTIES SKIP_RETURN_CODE 77) - - # Typed buffer UAVs and UAV counters: cs_buf_typed.asm writes typed views through V#s with a FORMAT, and - # cs_buf_counter.asm appends to and consumes from a structured view whose counter is the second V# of its slot; - # the test also compares typed-buffer and counter clears with the host runtime on the layer's adapter. - set(LEONIDA_BUFFER_UAV_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/buffer_uav_shaders) - set(LEONIDA_BUFFER_UAV_FILES ${LEONIDA_BUFFER_UAV_DIR}/spirv/index.json - ${LEONIDA_BUFFER_UAV_DIR}/fssm/cs_buf_typed.fssm - ${LEONIDA_BUFFER_UAV_DIR}/fssm/cs_buf_counter.fssm) - add_custom_command( - OUTPUT ${LEONIDA_BUFFER_UAV_FILES} - COMMAND ${CMAKE_COMMAND} -E remove_directory ${LEONIDA_BUFFER_UAV_DIR} - # LEONIDA_USER_DATA_SHIFT=4: root arguments from s4 in a D3D12 compute PSO (see the M4 shaders above). - COMMAND ${CMAKE_COMMAND} -E env "LLVM_MC=${LEONIDA_LLVM_MC}" "LEONIDA_SPIRV_TOOLS=${LEONIDA_SPIRV_TOOLS_NATIVE}" - LEONIDA_USER_DATA_SHIFT=4 - $ -I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py - ${LEONIDA_BUFFER_UAV_DIR} cs_buf_typed cs_buf_counter - DEPENDS ${LEONIDA_TRANSLATOR_DEPS} - ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/cs_buf_typed.asm - ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/cs_buf_counter.asm - COMMENT "Translating cs_buf_typed and cs_buf_counter for the buffer UAV test" - VERBATIM) - add_executable(d3d12_buffer_uav_test test/d3d12_buffer_uav_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_BUFFER_UAV_FILES}) - target_link_libraries(d3d12_buffer_uav_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_buffer_uav_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_TEST_BUFFER_UAV_DIR="${LEONIDA_BUFFER_UAV_DIR}") - target_compile_options(d3d12_buffer_uav_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_buffer_uav COMMAND d3d12_buffer_uav_test) - set_tests_properties(d3d12_buffer_uav PROPERTIES SKIP_RETURN_CODE 77) - else() - message(STATUS "llvm-mc (set LLVM_MC) or the SDK's spirv-as/spirv-val not found: d3d12_translated_draw_test, d3d12_m2_textured_test, d3d12_m2_formats_test, d3d12_m3_frame_test, d3d12_m4_compute_test and d3d12_buffer_uav_test are not built") - endif() - # ID3D12Resource::GetHeapProperties and ID3D12DescriptorHeap::GetDesc (node masks, resolved heap flags) against the - # host runtime and WARP; run explicitly on a Vulkan GPU. - add_executable(d3d12_node_mask_test test/d3d12_node_mask_test.cpp) - target_link_libraries(d3d12_node_mask_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_node_mask_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_node_mask_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_node_mask COMMAND d3d12_node_mask_test) - - # Console Xbox CreateDescriptorHeap extended ABI (issue #313 comment 7107265058): the title passes address/size - # after the PC desc and expects GetCPU/GPUDescriptorHandleForHeapStart() == address. Synthetic test; no title-memory - # aliasing / §3.3 backing coverage. - add_executable(d3d12_console_descriptor_heap_test test/d3d12_console_descriptor_heap_test.cpp shims/d3d12_xs_device.cpp) - target_link_libraries(d3d12_console_descriptor_heap_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_console_descriptor_heap_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_console_descriptor_heap_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_console_descriptor_heap COMMAND d3d12_console_descriptor_heap_test) - set_tests_properties(d3d12_console_descriptor_heap PROPERTIES SKIP_RETURN_CODE 77) - add_executable(d3d12_indirect_zero_test test/d3d12_indirect_zero_test.cpp) - target_link_libraries(d3d12_indirect_zero_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_indirect_zero_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_indirect_zero_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_indirect_zero COMMAND d3d12_indirect_zero_test) - set_tests_properties(d3d12_indirect_zero PROPERTIES SKIP_RETURN_CODE 77) - set_tests_properties(d3d12_node_mask PROPERTIES SKIP_RETURN_CODE 77) - set_tests_properties(d3d12_indirect_zero PROPERTIES SKIP_RETURN_CODE 77) - - # CopyResource / CopyTextureRegion between BC and its uncompressed equivalent (and depth <-> colour) against the - # host runtime and WARP; run explicitly on a Vulkan GPU. - add_executable(d3d12_copy_xfmt_test test/d3d12_copy_xfmt_test.cpp) - target_link_libraries(d3d12_copy_xfmt_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_copy_xfmt_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_copy_xfmt_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_copy_xfmt COMMAND d3d12_copy_xfmt_test) - set_tests_properties(d3d12_copy_xfmt PROPERTIES SKIP_RETURN_CODE 77) - - add_executable(d3d12_stencil_copy_test test/d3d12_stencil_copy_test.cpp) - target_link_libraries(d3d12_stencil_copy_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_stencil_copy_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_stencil_copy_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_stencil_copy COMMAND d3d12_stencil_copy_test) - set_tests_properties(d3d12_stencil_copy PROPERTIES SKIP_RETURN_CODE 77 - ENVIRONMENT "LEONIDA_HOST_ADAPTER=warp") - - # Query heaps and query calls by list type (Close results, CreateQueryHeap node masks, timestamp heap kinds) - # against the host runtime and WARP; run explicitly on a Vulkan GPU. - add_executable(d3d12_query_rules_test test/d3d12_query_rules_test.cpp) - target_link_libraries(d3d12_query_rules_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_query_rules_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_query_rules_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_query_rules COMMAND d3d12_query_rules_test) - set_tests_properties(d3d12_query_rules PROPERTIES SKIP_RETURN_CODE 77) - - # Vulkan-backed IDXGIFactory4 / IDXGISwapChain3 presentation over a Win32 HWND. - add_executable(dxgi_swapchain_test test/dxgi_swapchain_test.cpp) - target_link_libraries(dxgi_swapchain_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(dxgi_swapchain_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(dxgi_swapchain_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME dxgi_swapchain COMMAND dxgi_swapchain_test) - set_tests_properties(dxgi_swapchain PROPERTIES SKIP_RETURN_CODE 77) - - # The layer's DXGI against the host runtime's (hardware adapter, or WARP with PROBE_WARP=1): IDXGIAdapter4, - # GetRestrictToOutput without an output, ResizeBuffers flag bits and null out-pointers. - add_executable(dxgi_host_parity_test test/dxgi_host_parity_test.cpp) - target_link_libraries(dxgi_host_parity_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(dxgi_host_parity_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(dxgi_host_parity_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME dxgi_host_parity COMMAND dxgi_host_parity_test) - set_tests_properties(dxgi_host_parity PROPERTIES SKIP_RETURN_CODE 77) - - # Host-parity test for DXGI waitable swap chain frame-latency semaphore behavior. - add_executable(dxgi_waitable_latency_test test/dxgi_waitable_latency_test.cpp) - target_link_libraries(dxgi_waitable_latency_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(dxgi_waitable_latency_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(dxgi_waitable_latency_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME dxgi_waitable_latency COMMAND dxgi_waitable_latency_test) - set_tests_properties(dxgi_waitable_latency PROPERTIES - SKIP_RETURN_CODE 77 - FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") - - # Synthetic (no GPU): VulkanSwapchain's DXGI BufferCount contract when Vulkan returns more images than the - # app asked for, or the surface minimum exceeds the request (D3D-389). - add_executable(dxgi_swapchain_count_test test/dxgi_swapchain_count_test.cpp) - target_link_libraries(dxgi_swapchain_count_test PRIVATE Vulkan::Headers) - target_compile_definitions(dxgi_swapchain_count_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(dxgi_swapchain_count_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME dxgi_swapchain_count COMMAND dxgi_swapchain_count_test) - - # ExecuteIndirect with CountBuffer (vkCmdDrawIndirectCount) + optional BLAS/TLAS/RayQueryKHR GPU test. - add_executable(d3d12_indirect_rt_test test/d3d12_indirect_rt_test.cpp) - target_link_libraries(d3d12_indirect_rt_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_indirect_rt_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_indirect_rt_test PRIVATE /W4 /permissive- /utf-8) - if(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) - set(LEONIDA_TEST_VS_TRI ${CMAKE_CURRENT_BINARY_DIR}/generated/vs_tri.spv) - set(LEONIDA_TEST_FS_SOLID ${CMAKE_CURRENT_BINARY_DIR}/generated/fs_solid.spv) - set(LEONIDA_TEST_CS_RAYQUERY ${CMAKE_CURRENT_BINARY_DIR}/generated/cs_rayquery.spv) - add_custom_command( - OUTPUT ${LEONIDA_TEST_VS_TRI} - COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${LEONIDA_TEST_VS_TRI} - ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/vs_tri.vert - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/vs_tri.vert - COMMENT "Compiling vs_tri.vert" - VERBATIM) - add_custom_command( - OUTPUT ${LEONIDA_TEST_FS_SOLID} - COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${LEONIDA_TEST_FS_SOLID} - ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/fs_solid.frag - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/fs_solid.frag - COMMENT "Compiling fs_solid.frag" - VERBATIM) - add_custom_command( - OUTPUT ${LEONIDA_TEST_CS_RAYQUERY} - COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${LEONIDA_TEST_CS_RAYQUERY} - ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_rayquery.comp - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_rayquery.comp - COMMENT "Compiling cs_rayquery.comp" - VERBATIM) - target_sources(d3d12_indirect_rt_test PRIVATE - ${LEONIDA_TEST_VS_TRI} ${LEONIDA_TEST_FS_SOLID} ${LEONIDA_TEST_CS_RAYQUERY}) - target_compile_definitions(d3d12_indirect_rt_test PRIVATE - LEONIDA_TEST_VS_TRI_SPV="${LEONIDA_TEST_VS_TRI}" - LEONIDA_TEST_FS_SOLID_SPV="${LEONIDA_TEST_FS_SOLID}" - LEONIDA_TEST_CS_RAYQUERY_SPV="${LEONIDA_TEST_CS_RAYQUERY}") - endif() - add_test(NAME d3d12_indirect_rt COMMAND d3d12_indirect_rt_test) - set_tests_properties(d3d12_indirect_rt PROPERTIES SKIP_RETURN_CODE 77) - # Upload heaps in system memory, as on a GPU without Resizable BAR: their VAs can lie below the arena and wrap. - add_test(NAME d3d12_indirect_rt_upload_sysmem COMMAND d3d12_indirect_rt_test) - set_tests_properties(d3d12_indirect_rt_upload_sysmem PROPERTIES SKIP_RETURN_CODE 77 - ENVIRONMENT "LEONIDA_UPLOAD_SYSMEM=1") - - # The compute path: root signature, compute PSO from a translator-style index, root arguments, dispatch. Its - # shader is GLSL written to the translator's push-constant/address contract, compiled here. - if(NOT Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) - find_program(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE glslangValidator HINTS "$ENV{VULKAN_SDK}/Bin" "$ENV{VULKAN_SDK}/bin") - endif() - if(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) - set(LEONIDA_TEST_CS ${CMAKE_CURRENT_BINARY_DIR}/generated/cs_user_data.spv) - add_custom_command( - OUTPUT ${LEONIDA_TEST_CS} - COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${LEONIDA_TEST_CS} - ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_user_data.comp - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_user_data.comp - COMMENT "Compiling the compute test shader" - VERBATIM) - add_executable(d3d12_compute_test test/d3d12_compute_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_TEST_CS}) - target_link_libraries(d3d12_compute_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_compute_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_TEST_CS_SPV="${LEONIDA_TEST_CS}") - target_compile_options(d3d12_compute_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_compute COMMAND d3d12_compute_test) - set_tests_properties(d3d12_compute PROPERTIES SKIP_RETURN_CODE 77) - # Compute PSOs from FSPX programs (docs/fspx.md): an ACCC container at slot 62 and a bare kind-6 program. - add_executable(d3d12_fspx_compute_test test/d3d12_fspx_compute_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_TEST_CS}) - target_link_libraries(d3d12_fspx_compute_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_fspx_compute_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_TEST_CS_SPV="${LEONIDA_TEST_CS}") - target_compile_options(d3d12_fspx_compute_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_fspx_compute COMMAND d3d12_fspx_compute_test) - set_tests_properties(d3d12_fspx_compute PROPERTIES SKIP_RETURN_CODE 77) - # Milestone M1: a VS+PS pipeline and indexed draws, shaders written to the same contract. - set(LEONIDA_TEST_VS ${CMAKE_CURRENT_BINARY_DIR}/generated/vs_draw.spv) - set(LEONIDA_TEST_PS ${CMAKE_CURRENT_BINARY_DIR}/generated/ps_draw.spv) - set(LEONIDA_TEST_PS_UINT ${CMAKE_CURRENT_BINARY_DIR}/generated/ps_draw_uint.spv) - set(LEONIDA_TEST_VS_FULLSCREEN ${CMAKE_CURRENT_BINARY_DIR}/generated/vs_fullscreen.spv) - set(LEONIDA_TEST_VS_INT ${CMAKE_CURRENT_BINARY_DIR}/generated/vs_draw_int.spv) - set(LEONIDA_TEST_GS_DOUBLE ${CMAKE_CURRENT_BINARY_DIR}/generated/gs_double.spv) - foreach(pair "vs_draw.vert;${LEONIDA_TEST_VS}" "ps_draw.frag;${LEONIDA_TEST_PS}" - "ps_draw_uint.frag;${LEONIDA_TEST_PS_UINT}" "vs_fullscreen.vert;${LEONIDA_TEST_VS_FULLSCREEN}" "vs_draw_int.vert;${LEONIDA_TEST_VS_INT}" - "gs_double.geom;${LEONIDA_TEST_GS_DOUBLE}") - list(GET pair 0 source) - list(GET pair 1 output) - add_custom_command( - OUTPUT ${output} - COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${output} - ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${source} - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${source} - COMMENT "Compiling the draw test shader ${source}" - VERBATIM) - endforeach() - add_executable(d3d12_draw_test test/d3d12_draw_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_TEST_VS} - ${LEONIDA_TEST_PS} ${LEONIDA_TEST_PS_UINT} ${LEONIDA_TEST_VS_FULLSCREEN} ${LEONIDA_TEST_VS_INT}) - target_link_libraries(d3d12_draw_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_draw_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_TEST_VS_SPV="${LEONIDA_TEST_VS}" LEONIDA_TEST_PS_SPV="${LEONIDA_TEST_PS}" - LEONIDA_TEST_PS_UINT_SPV="${LEONIDA_TEST_PS_UINT}" - LEONIDA_TEST_VS_FULLSCREEN_SPV="${LEONIDA_TEST_VS_FULLSCREEN}" - LEONIDA_TEST_VS_INT_SPV="${LEONIDA_TEST_VS_INT}") - target_compile_options(d3d12_draw_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_draw COMMAND d3d12_draw_test) - set_tests_properties(d3d12_draw PROPERTIES SKIP_RETURN_CODE 77) - # Graphics & compute PSO descriptor validation parity against live Windows D3D12 (WARP and HW). - add_executable(d3d12_pso_validation_test test/d3d12_pso_validation_test.cpp ${LEONIDA_TEST_VS} - ${LEONIDA_TEST_PS} ${LEONIDA_TEST_PS_UINT} ${LEONIDA_TEST_VS_FULLSCREEN} ${LEONIDA_TEST_CS}) - target_link_libraries(d3d12_pso_validation_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_pso_validation_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_TEST_VS_SPV="${LEONIDA_TEST_VS}" LEONIDA_TEST_PS_SPV="${LEONIDA_TEST_PS}" - LEONIDA_TEST_PS_UINT_SPV="${LEONIDA_TEST_PS_UINT}" - LEONIDA_TEST_VS_FULLSCREEN_SPV="${LEONIDA_TEST_VS_FULLSCREEN}" - LEONIDA_TEST_CS_SPV="${LEONIDA_TEST_CS}") - target_compile_options(d3d12_pso_validation_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_pso_validation COMMAND d3d12_pso_validation_test) - set_tests_properties(d3d12_pso_validation PROPERTIES SKIP_RETURN_CODE 77 - FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") - # Conservative raster Tier 1, with geometric coverage bounds and host D3D12 references. - set(LEONIDA_CONSERVATIVE_VS ${CMAKE_CURRENT_BINARY_DIR}/generated/vs_conservative.spv) - set(LEONIDA_CONSERVATIVE_PS ${CMAKE_CURRENT_BINARY_DIR}/generated/ps_conservative.spv) - foreach(pair "vs_conservative.vert;${LEONIDA_CONSERVATIVE_VS}" "ps_conservative.frag;${LEONIDA_CONSERVATIVE_PS}") - list(GET pair 0 source) - list(GET pair 1 output) - add_custom_command(OUTPUT ${output} - COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${output} - ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${source} - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${source} VERBATIM) - endforeach() - add_executable(d3d12_conservative_raster_test test/d3d12_conservative_raster_test.cpp - ${LEONIDA_CONSERVATIVE_VS} ${LEONIDA_CONSERVATIVE_PS}) - target_link_libraries(d3d12_conservative_raster_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_conservative_raster_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_CONSERVATIVE_VS="${LEONIDA_CONSERVATIVE_VS}" LEONIDA_CONSERVATIVE_PS="${LEONIDA_CONSERVATIVE_PS}") - target_compile_options(d3d12_conservative_raster_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_conservative_raster COMMAND d3d12_conservative_raster_test) - set_tests_properties(d3d12_conservative_raster PROPERTIES SKIP_RETURN_CODE 77 - ENVIRONMENT "LEONIDA_HOST_ADAPTER=warp") - set(LEONIDA_CONSERVATIVE_TIER2_VS ${CMAKE_CURRENT_BINARY_DIR}/generated/vs_conservative_tier2.spv) - set(LEONIDA_CONSERVATIVE_TIER2_PS ${CMAKE_CURRENT_BINARY_DIR}/generated/ps_conservative_tier2.spv) - foreach(pair "vs_conservative_tier2.vert;${LEONIDA_CONSERVATIVE_TIER2_VS}" "ps_conservative_tier2.frag;${LEONIDA_CONSERVATIVE_TIER2_PS}") - list(GET pair 0 source) - list(GET pair 1 output) - add_custom_command(OUTPUT ${output} - COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${output} - ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${source} - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${source} VERBATIM) - endforeach() - add_executable(d3d12_conservative_tier2_test test/d3d12_conservative_tier2_test.cpp - ${LEONIDA_CONSERVATIVE_TIER2_VS} ${LEONIDA_CONSERVATIVE_TIER2_PS}) - target_link_libraries(d3d12_conservative_tier2_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_conservative_tier2_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_CONSERVATIVE_TIER2_VS="${LEONIDA_CONSERVATIVE_TIER2_VS}" LEONIDA_CONSERVATIVE_TIER2_PS="${LEONIDA_CONSERVATIVE_TIER2_PS}") - target_compile_options(d3d12_conservative_tier2_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_conservative_tier2 COMMAND d3d12_conservative_tier2_test) - set_tests_properties(d3d12_conservative_tier2 PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_HOST_ADAPTER=warp") - set(LEONIDA_CONSERVATIVE_TIER3_PS ${CMAKE_CURRENT_BINARY_DIR}/generated/ps_conservative_tier3.spv) - add_custom_command(OUTPUT ${LEONIDA_CONSERVATIVE_TIER3_PS} - COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${LEONIDA_CONSERVATIVE_TIER3_PS} - ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/ps_conservative_tier3.frag - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/ps_conservative_tier3.frag VERBATIM) - add_executable(d3d12_conservative_tier3_test test/d3d12_conservative_tier3_test.cpp - ${LEONIDA_CONSERVATIVE_VS} ${LEONIDA_CONSERVATIVE_TIER3_PS}) - target_link_libraries(d3d12_conservative_tier3_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_conservative_tier3_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_CONSERVATIVE_VS="${LEONIDA_CONSERVATIVE_VS}" - LEONIDA_CONSERVATIVE_TIER3_PS="${LEONIDA_CONSERVATIVE_TIER3_PS}") - target_compile_options(d3d12_conservative_tier3_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME inner_coverage_oracle COMMAND d3d12_conservative_tier3_test --oracle-only) - add_test(NAME d3d12_inner_coverage_guards COMMAND d3d12_conservative_tier3_test --guards-only) - add_test(NAME d3d12_inner_coverage_native COMMAND d3d12_conservative_tier3_test --native-only) - add_test(NAME d3d12_conservative_tier3 COMMAND d3d12_conservative_tier3_test) - set_tests_properties(d3d12_inner_coverage_guards d3d12_inner_coverage_native d3d12_conservative_tier3 - PROPERTIES SKIP_RETURN_CODE 77) - add_executable(d3d12_msaa_draw_test test/d3d12_msaa_draw_test.cpp shims/d3d12_xs_device.cpp - ${LEONIDA_TEST_VS} ${LEONIDA_TEST_PS}) - target_link_libraries(d3d12_msaa_draw_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_msaa_draw_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_TEST_VS_SPV="${LEONIDA_TEST_VS}" LEONIDA_TEST_PS_SPV="${LEONIDA_TEST_PS}") - target_compile_options(d3d12_msaa_draw_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_msaa_draw COMMAND d3d12_msaa_draw_test) - set_tests_properties(d3d12_msaa_draw PROPERTIES SKIP_RETURN_CODE 77) - # Geometry shaders: a VS+GS+PS pipeline whose GS emits each triangle twice. - add_executable(d3d12_geometry_test test/d3d12_geometry_test.cpp shims/d3d12_xs_device.cpp - ${LEONIDA_TEST_VS} ${LEONIDA_TEST_GS_DOUBLE} ${LEONIDA_TEST_PS}) - target_link_libraries(d3d12_geometry_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_geometry_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_TEST_VS_SPV="${LEONIDA_TEST_VS}" LEONIDA_TEST_GS_SPV="${LEONIDA_TEST_GS_DOUBLE}" - LEONIDA_TEST_PS_SPV="${LEONIDA_TEST_PS}") - target_compile_options(d3d12_geometry_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_geometry COMMAND d3d12_geometry_test) - set_tests_properties(d3d12_geometry PROPERTIES SKIP_RETURN_CODE 77) - # D3D-309: D24 depth bias and 24-bit depth in draws, with and without a pixel shader and with a geometry shader - # (src/depth24_fragment.h). - set(LEONIDA_TEST_VS_DEPTH ${CMAKE_CURRENT_BINARY_DIR}/generated/vs_depth.spv) - set(LEONIDA_TEST_PS_DEPTH_EMPTY ${CMAKE_CURRENT_BINARY_DIR}/generated/ps_depth_empty.spv) - set(LEONIDA_TEST_PS_DEPTH_WRITE ${CMAKE_CURRENT_BINARY_DIR}/generated/ps_depth_write.spv) - set(LEONIDA_TEST_GS_DEPTH ${CMAKE_CURRENT_BINARY_DIR}/generated/gs_depth.spv) - foreach(pair "vs_depth.vert;${LEONIDA_TEST_VS_DEPTH}" "ps_depth_empty.frag;${LEONIDA_TEST_PS_DEPTH_EMPTY}" - "ps_depth_write.frag;${LEONIDA_TEST_PS_DEPTH_WRITE}" "gs_depth.geom;${LEONIDA_TEST_GS_DEPTH}") - list(GET pair 0 source) - list(GET pair 1 output) - add_custom_command( - OUTPUT ${output} - COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${output} - ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${source} - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${source} - COMMENT "Compiling the D24 draw test shader ${source}" - VERBATIM) - endforeach() - add_executable(d3d12_depth24_draw_test test/d3d12_depth24_draw_test.cpp shims/d3d12_xs_device.cpp - ${LEONIDA_TEST_VS_DEPTH} ${LEONIDA_TEST_PS_DEPTH_EMPTY} ${LEONIDA_TEST_PS_DEPTH_WRITE} - ${LEONIDA_TEST_GS_DEPTH}) - target_link_libraries(d3d12_depth24_draw_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_depth24_draw_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_TEST_VS_DEPTH_SPV="${LEONIDA_TEST_VS_DEPTH}" - LEONIDA_TEST_PS_DEPTH_EMPTY_SPV="${LEONIDA_TEST_PS_DEPTH_EMPTY}" - LEONIDA_TEST_PS_DEPTH_WRITE_SPV="${LEONIDA_TEST_PS_DEPTH_WRITE}" - LEONIDA_TEST_GS_DEPTH_SPV="${LEONIDA_TEST_GS_DEPTH}") - target_compile_options(d3d12_depth24_draw_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_depth24_draw COMMAND d3d12_depth24_draw_test) - set_tests_properties(d3d12_depth24_draw PROPERTIES SKIP_RETURN_CODE 77) - # Set 0 from the compute bind point: a compute PSO whose shader declares set-0 bindings samples through the - # device's bindless set, which nothing but the layer binds. - set(LEONIDA_TEST_CS_SET0_SAMPLE ${CMAKE_CURRENT_BINARY_DIR}/generated/cs_set0_sample.spv) - add_custom_command( - OUTPUT ${LEONIDA_TEST_CS_SET0_SAMPLE} - COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${LEONIDA_TEST_CS_SET0_SAMPLE} - ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_set0_sample.comp - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_set0_sample.comp - COMMENT "Compiling the set-0 compute test shader" - VERBATIM) - add_executable(d3d12_set0_compute_test test/d3d12_set0_compute_test.cpp shims/d3d12_xs_device.cpp - ${LEONIDA_TEST_CS_SET0_SAMPLE}) - target_link_libraries(d3d12_set0_compute_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_set0_compute_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_TEST_CS_SET0_SAMPLE_SPV="${LEONIDA_TEST_CS_SET0_SAMPLE}") - target_compile_options(d3d12_set0_compute_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_set0_compute COMMAND d3d12_set0_compute_test) - set_tests_properties(d3d12_set0_compute PROPERTIES SKIP_RETURN_CODE 77) - # Bindless table churn on a direct and a compute queue: the table grows and live keys move without a - # device-idle wait (D3D-314); the same shader, run twice (deferred retirement, and the old wait for timing). - add_executable(d3d12_bindless_churn_test test/d3d12_bindless_churn_test.cpp shims/d3d12_xs_device.cpp - ${LEONIDA_TEST_CS_SET0_SAMPLE}) - target_link_libraries(d3d12_bindless_churn_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_bindless_churn_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_TEST_CS_SET0_SAMPLE_SPV="${LEONIDA_TEST_CS_SET0_SAMPLE}") - target_compile_options(d3d12_bindless_churn_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_bindless_churn COMMAND d3d12_bindless_churn_test) - set_tests_properties(d3d12_bindless_churn PROPERTIES SKIP_RETURN_CODE 77) - add_test(NAME d3d12_bindless_churn_validated COMMAND d3d12_bindless_churn_test --validated) - set_tests_properties(d3d12_bindless_churn_validated PROPERTIES SKIP_RETURN_CODE 77) - add_executable(d3d12_pipeline_library_test test/d3d12_pipeline_library_test.cpp - ${LEONIDA_TEST_CS} ${LEONIDA_TEST_VS} ${LEONIDA_TEST_PS}) - target_link_libraries(d3d12_pipeline_library_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_pipeline_library_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_TEST_CS_SPV="${LEONIDA_TEST_CS}" - LEONIDA_TEST_VS_SPV="${LEONIDA_TEST_VS}" - LEONIDA_TEST_PS_SPV="${LEONIDA_TEST_PS}") - target_compile_options(d3d12_pipeline_library_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_pipeline_library COMMAND d3d12_pipeline_library_test) - set_tests_properties(d3d12_pipeline_library PROPERTIES SKIP_RETURN_CODE 77) - # ExecuteBundle: what a bundle's draws inherit and hand back, against the host runtime and WARP. - add_executable(d3d12_bundle_test test/d3d12_bundle_test.cpp ${LEONIDA_TEST_VS} ${LEONIDA_TEST_PS}) - target_link_libraries(d3d12_bundle_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_bundle_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS - LEONIDA_TEST_VS_SPV="${LEONIDA_TEST_VS}" LEONIDA_TEST_PS_SPV="${LEONIDA_TEST_PS}") - target_compile_options(d3d12_bundle_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_bundle COMMAND d3d12_bundle_test) - set_tests_properties(d3d12_bundle PROPERTIES SKIP_RETURN_CODE 77) - # Calls a bundle may not make, Close of the bundle and of its parent, against the host runtime and WARP. - add_executable(d3d12_bundle_forbidden_test test/d3d12_bundle_forbidden_test.cpp) - target_link_libraries(d3d12_bundle_forbidden_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_bundle_forbidden_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_bundle_forbidden_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_bundle_forbidden COMMAND d3d12_bundle_forbidden_test) - set_tests_properties(d3d12_bundle_forbidden PROPERTIES SKIP_RETURN_CODE 77) - # A pixel shader with a writable storage image (an image atomic) needs fragmentStoresAndAtomics: refused on a - # device without it, created on the runtime's own device, under the validation layer where it is installed. - set(LEONIDA_TEST_PS_ATOMIC ${CMAKE_CURRENT_BINARY_DIR}/generated/ps_image_atomic.spv) - add_custom_command( - OUTPUT ${LEONIDA_TEST_PS_ATOMIC} - COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${LEONIDA_TEST_PS_ATOMIC} - ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/ps_image_atomic.frag - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/ps_image_atomic.frag - COMMENT "Compiling the stores-and-atomics test shader ps_image_atomic.frag" - VERBATIM) - add_executable(d3d12_stores_atomics_test test/d3d12_stores_atomics_test.cpp ${LEONIDA_TEST_VS_FULLSCREEN} - ${LEONIDA_TEST_PS} ${LEONIDA_TEST_PS_ATOMIC}) - target_link_libraries(d3d12_stores_atomics_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_stores_atomics_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_TEST_VS_FULLSCREEN_SPV="${LEONIDA_TEST_VS_FULLSCREEN}" - LEONIDA_TEST_PS_SPV="${LEONIDA_TEST_PS}" - LEONIDA_TEST_PS_ATOMIC_SPV="${LEONIDA_TEST_PS_ATOMIC}") - target_compile_options(d3d12_stores_atomics_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_stores_atomics COMMAND d3d12_stores_atomics_test) - set_tests_properties(d3d12_stores_atomics PROPERTIES SKIP_RETURN_CODE 77) - - # D3D-29: mesh-shader PSOs from pipeline state streams and DispatchMesh (skips without VK_EXT_mesh_shader). - set(LEONIDA_TEST_MS ${CMAKE_CURRENT_BINARY_DIR}/generated/ms_draw.spv) - add_custom_command( - OUTPUT ${LEONIDA_TEST_MS} - # Vulkan 1.2 (SPIR-V 1.5), the translator's target: 1.3 would emit LocalSizeId, which needs maintenance4. - COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.2 -o ${LEONIDA_TEST_MS} - ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/ms_draw.mesh - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/ms_draw.mesh - COMMENT "Compiling the mesh test shader ms_draw.mesh" - VERBATIM) - add_executable(d3d12_mesh_test test/d3d12_mesh_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_TEST_MS} - ${LEONIDA_TEST_PS} ${LEONIDA_TEST_VS_FULLSCREEN}) - target_link_libraries(d3d12_mesh_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_mesh_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_TEST_MS_SPV="${LEONIDA_TEST_MS}" LEONIDA_TEST_PS_SPV="${LEONIDA_TEST_PS}" - LEONIDA_TEST_VS_FULLSCREEN_SPV="${LEONIDA_TEST_VS_FULLSCREEN}") - target_compile_options(d3d12_mesh_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_mesh COMMAND d3d12_mesh_test) - set_tests_properties(d3d12_mesh PROPERTIES SKIP_RETURN_CODE 77) - else() - message(STATUS "glslangValidator not found: d3d12_compute_test, d3d12_draw_test, d3d12_set0_compute_test and d3d12_mesh_test are not built") - endif() - - # Native D3D12 SV_InnerCoverage reference; its HLSL is compiled at runtime, so glslang is not needed. - add_executable(d3d12_conservative_tier3_reference_test test/d3d12_conservative_tier3_reference_test.cpp) - target_link_libraries(d3d12_conservative_tier3_reference_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_conservative_tier3_reference_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_conservative_tier3_reference_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_conservative_tier3_reference COMMAND d3d12_conservative_tier3_reference_test) - set_tests_properties(d3d12_conservative_tier3_reference PROPERTIES SKIP_RETURN_CODE 77) - - # Subgroup size control in PSOs, end to end: runtime/test/shaders/cs_w64x_readlane.asm translated natively and with - # --wave64-emulate, and cs_wqm_w32.asm, built here with tools/rdna2spirv.py through test/shaders/build.py. Needs - # llvm-mc with the AMDGPU target (LLVM_MC in the environment, as for the other shader tests, or llvm-mc on PATH) - # and the Vulkan SDK's spirv tools; without them the test is not built. - if(DEFINED ENV{LLVM_MC}) - set(LEONIDA_LLVM_MC "$ENV{LLVM_MC}") - else() - find_program(LEONIDA_LLVM_MC llvm-mc HINTS "C:/msys64/ucrt64/bin") - endif() - if(LEONIDA_LLVM_MC AND Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) - set(LEONIDA_SG_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/subgroup_shaders) - set(LEONIDA_SG_INDEXES "") - foreach(case "w64_native;cs_w64x_readlane;0" "w64_emulated;cs_w64x_readlane;1" "w32_native;cs_wqm_w32;0" - "ps_w64_native;ps_w64x_readlane;0") - list(GET case 0 folder) - list(GET case 1 shader) - list(GET case 2 emulate) - set(index ${LEONIDA_SG_DIR}/${folder}/spirv/index.json) - add_custom_command( - OUTPUT ${index} - # The standalone harness runs these with the V# at s[0:3]; d3d12_subgroup_test passes it as four root - # constants, which the D3D12 compute layout puts at s[4:7] (LEONIDA_USER_DATA_SHIFT=4, D3D-448). - COMMAND ${CMAKE_COMMAND} -E env LLVM_MC=${LEONIDA_LLVM_MC} LEONIDA_W64_EMULATE=${emulate} - LEONIDA_USER_DATA_SHIFT=4 - $ -I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py - ${LEONIDA_SG_DIR}/${folder} ${shader} - DEPENDS ${LEONIDA_TRANSLATOR_DEPS} - ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/${shader}.asm - COMMENT "Translating ${shader} for the subgroup size test (${folder})" - VERBATIM) - list(APPEND LEONIDA_SG_INDEXES ${index}) - endforeach() - # The probe shaders that store the subgroup size the driver ran them with, and a one-triangle vertex shader. - foreach(source cs_sg_probe.comp ps_sg_probe.frag vs_sg_fullscreen.vert) - set(output ${LEONIDA_SG_DIR}/glsl/${source}.spv) - add_custom_command( - OUTPUT ${output} - COMMAND ${CMAKE_COMMAND} -E make_directory ${LEONIDA_SG_DIR}/glsl - COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${output} - ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${source} - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${source} - COMMENT "Compiling ${source}" - VERBATIM) - list(APPEND LEONIDA_SG_INDEXES ${output}) - endforeach() - add_executable(d3d12_subgroup_test test/d3d12_subgroup_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_SG_INDEXES}) - target_link_libraries(d3d12_subgroup_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_subgroup_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_TEST_SUBGROUP_SHADERS="${LEONIDA_SG_DIR}") - target_compile_options(d3d12_subgroup_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_subgroup COMMAND d3d12_subgroup_test) - set_tests_properties(d3d12_subgroup PROPERTIES SKIP_RETURN_CODE 77) - else() - message(STATUS "llvm-mc (set LLVM_MC) or glslangValidator not found: d3d12_subgroup_test is not built") - endif() - - # Clears on every format class against WARP (needs a Vulkan GPU; exit 77 without one). - add_executable(d3d12_clear_formats_test test/d3d12_clear_formats_test.cpp) - target_link_libraries(d3d12_clear_formats_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_clear_formats_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_clear_formats_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_clear_formats COMMAND d3d12_clear_formats_test) - set_tests_properties(d3d12_clear_formats PROPERTIES SKIP_RETURN_CODE 77) - - # SetDescriptorHeaps validation, Reset/ClearState/bundle parity, lifetime pinning, direct-index flags. - add_executable(d3d12_set_descriptor_heaps_test test/d3d12_set_descriptor_heaps_test.cpp) - target_link_libraries(d3d12_set_descriptor_heaps_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_set_descriptor_heaps_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_set_descriptor_heaps_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_set_descriptor_heaps COMMAND d3d12_set_descriptor_heaps_test) - set_tests_properties(d3d12_set_descriptor_heaps PROPERTIES SKIP_RETURN_CODE 77 - FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") - - # The loader can create this device instead of the host's (D3D12XboxCreateDevice, LEONIDA_D3D12=vulkan). - if(TARGET gta6rt) - target_link_libraries(gta6rt PRIVATE gta6rt_d3d12_com) - target_compile_definitions(gta6rt PRIVATE LEONIDA_VULKAN_DEVICE) - - # A stand-in title that imports d3d12_xs.dll!D3D12XboxCreateDevice and runs a clear and a readback on the - # device it gets, mapped and run by `gta6rt --run` with LEONIDA_D3D12=vulkan: the loader, the game thread, the - # proxies and the Vulkan device in one process. check_tiny_frame.py reads the verdict, the binding and the - # call order from outside; d3d12_com_test is its probe for "no usable Vulkan device" (exit code 77). - add_library(d3d12_xs_stub SHARED test/fixtures/d3d12_xs_stub.cpp test/fixtures/d3d12_xs_stub.def) - target_compile_definitions(d3d12_xs_stub PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_xs_stub PRIVATE /W4 /permissive- /utf-8) - set_target_properties(d3d12_xs_stub PROPERTIES - OUTPUT_NAME d3d12_xs - PREFIX "" - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/stubs/$" - ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/stubs/$" - ) - add_executable(tiny_frame test/fixtures/tiny_frame.cpp) - target_link_libraries(tiny_frame PRIVATE d3d12_xs_stub) - target_compile_definitions(tiny_frame PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(tiny_frame PRIVATE /W4 /permissive- /utf-8) - set_target_properties(tiny_frame PROPERTIES - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" - ) - if(Python3_FOUND) - add_test(NAME run_tiny_frame COMMAND "${Python3_EXECUTABLE}" -I - "${CMAKE_CURRENT_SOURCE_DIR}/test/check_tiny_frame.py" "$" - "$" "--probe=$" ${_trace_runner}) - set_tests_properties(run_tiny_frame PROPERTIES SKIP_RETURN_CODE 77) - # The queue test settings are for the tests only: left set, they must not shrink the game's device. - add_test(NAME run_tiny_frame_queue_test_settings COMMAND "${Python3_EXECUTABLE}" -I - "${CMAKE_CURRENT_SOURCE_DIR}/test/check_tiny_frame.py" "$" - "$" "--probe=$" --queue-test-settings - ${_trace_runner}) - set_tests_properties(run_tiny_frame_queue_test_settings PROPERTIES SKIP_RETURN_CODE 77) - endif() - endif() - - # M1.5 as a `gta6rt --run` guest: test/d3d12_translated_draw_test.cpp built again with LEONIDA_M15_GUEST as - # tiny_guest_draw.exe, whose only device is the D3D12XboxCreateDevice it imports from d3d12_xs.dll. The import - # library comes from a failing stub built into fixtures/stubs, away from the guest, so only gta6rt's shim registry - # can answer it. The guest links nothing from src/ or shims/ and can be - # copied with its ordinary CRT dependencies, given the m15 folder as its argument. test/run_guest_draw.cmake checks the exit code and the marker line. - # Opt-in: it needs a Vulkan GPU and the guest cannot tell a missing one from a bug, so default runs are unchanged. - option(LEONIDA_TEST_GUEST_DRAW - "Build tiny_guest_draw.exe and run the M1.5 draw through gta6rt --run (needs a Vulkan GPU)" OFF) - option(LEONIDA_GUEST_SCENE "Build the headless 600-frame synthetic guest test (requires static SDL3)" OFF) - if(LEONIDA_TEST_GUEST_DRAW OR LEONIDA_GUEST_SCENE) - # Share the import stub with the tiny_frame clear/readback guest from PR #3488. - if(NOT TARGET d3d12_xs_stub) - add_library(d3d12_xs_stub SHARED test/fixtures/d3d12_xs_stub.cpp test/fixtures/d3d12_xs_stub.def) - target_compile_definitions(d3d12_xs_stub PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_xs_stub PRIVATE /W4 /permissive- /utf-8) - set_target_properties(d3d12_xs_stub PROPERTIES - OUTPUT_NAME d3d12_xs - PREFIX "" - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/stubs/$" - ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/stubs/$" - ) - endif() - add_executable(tiny_guest_draw test/d3d12_translated_draw_test.cpp) - target_link_libraries(tiny_guest_draw PRIVATE d3d12_xs_stub Vulkan::Headers) - target_compile_definitions(tiny_guest_draw PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_M15_GUEST) - target_compile_options(tiny_guest_draw PRIVATE /W4 /permissive- /utf-8) - set_target_properties(tiny_guest_draw PROPERTIES - OUTPUT_NAME tiny_guest_draw - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/guest_draw/$" - ) - if(LEONIDA_GUEST_SCENE) - if(NOT TARGET gta6rt OR NOT TARGET SDL3::SDL3-static OR NOT LEONIDA_SDL3) - message(FATAL_ERROR "LEONIDA_GUEST_SCENE requires static SDL3; configure SDL3_DIR or LEONIDA_SDL3_FETCH") - endif() - target_compile_definitions(tiny_guest_draw PRIVATE LEONIDA_GUEST_SCENE) - target_sources(gta6rt PRIVATE test/scene_input_driver.cpp) - endif() - # This guest can use a synthetic fixture produced on another machine. Register the automated test - # if the tools to generate the fixture are available locally. - if(CMAKE_HOST_WIN32 AND NOT CMAKE_CROSSCOMPILING AND TARGET d3d12_translated_draw_test AND TARGET gta6rt) - add_dependencies(tiny_guest_draw d3d12_translated_draw_test gta6rt) - add_test(NAME d3d12_translated_draw_guest - COMMAND ${CMAKE_COMMAND} -DGTA6RT=$ -DGUEST=$ - -DFIXTURE=${LEONIDA_M15_DIR} -P ${CMAKE_CURRENT_SOURCE_DIR}/test/run_guest_draw.cmake) - set_tests_properties(d3d12_translated_draw_guest PROPERTIES TIMEOUT 180) - else() - message(STATUS "tiny_guest_draw will build. For an external synthetic M1.5 fixture or Wine run see runtime/README.md.") - endif() - if(LEONIDA_GUEST_SCENE AND Python3_Interpreter_FOUND AND TARGET d3d12_translated_draw_test) - set(_scene_wine_args) - if(CMAKE_CROSSCOMPILING AND CMAKE_CROSSCOMPILING_EMULATOR) - set(_scene_emulator ${CMAKE_CROSSCOMPILING_EMULATOR}) - list(POP_FRONT _scene_emulator _scene_launcher) - list(APPEND _scene_wine_args "--wine=${_scene_launcher}") - foreach(_arg IN LISTS _scene_emulator) - list(APPEND _scene_wine_args "--wine-arg=${_arg}") - endforeach() - add_dependencies(tiny_guest_draw d3d12_translated_draw_test gta6rt) - endif() - if((CMAKE_HOST_WIN32 AND NOT CMAKE_CROSSCOMPILING) OR _scene_wine_args) - add_test(NAME d3d12_guest_scene - COMMAND "${Python3_EXECUTABLE}" -I "${CMAKE_CURRENT_SOURCE_DIR}/../scripts/run_guest_scene.py" - --loader $ --guest $ - --shaders "${LEONIDA_M15_DIR}" --negative-controls ${_scene_wine_args}) - set_tests_properties(d3d12_guest_scene PROPERTIES TIMEOUT 900) - endif() - endif() - endif() - # bvh_builder_test can put the package's XboxBvhBuilder on this device too (LEONIDA_BVH_DEVICE=vulkan). - if(TARGET bvh_builder_test) - target_link_libraries(bvh_builder_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(bvh_builder_test PRIVATE LEONIDA_VULKAN_DEVICE) - endif() - # fsr_dispatch_test can put the package's FidelityFX DLL on this device too (LEONIDA_FSR_DEVICE=vulkan). - if(TARGET fsr_dispatch_test) - target_link_libraries(fsr_dispatch_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(fsr_dispatch_test PRIVATE LEONIDA_VULKAN_DEVICE) - endif() - elseif(TARGET gta6rt) - message(STATUS "Python 3 or d3d12.h missing: the D3D12 COM objects and d3d12_com_test are not built") - endif() - - # Needs only the Vulkan headers, not a GPU. - if(BUILD_TESTING) - add_executable(typeless_rtv_test test/typeless_rtv_test.cpp) - target_link_libraries(typeless_rtv_test PRIVATE Vulkan::Headers) - if(WIN32) - target_compile_definitions(typeless_rtv_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - endif() - add_test(NAME typeless_rtv COMMAND typeless_rtv_test) - add_executable(pipeline_cache_snapshot_test test/pipeline_cache_snapshot_test.cpp) - target_link_libraries(pipeline_cache_snapshot_test PRIVATE Vulkan::Headers) - add_test(NAME pipeline_cache_snapshot COMMAND pipeline_cache_snapshot_test) - add_executable(predicated_copy_test test/predicated_copy_test.cpp) - target_link_libraries(predicated_copy_test PRIVATE Vulkan::Headers) - if(WIN32) - target_compile_definitions(predicated_copy_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - endif() - add_test(NAME predicated_copy COMMAND predicated_copy_test) - # CopyResource (buffer-to-buffer) and CopyTexture (including depth24_as_float) apply ResourceBinding::buffer_offset (no GPU). - add_executable(replay_copy_offset_test test/replay_copy_offset_test.cpp) - target_link_libraries(replay_copy_offset_test PRIVATE Vulkan::Headers) - if(WIN32) - target_compile_definitions(replay_copy_offset_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - endif() - add_test(NAME replay_copy_offset COMMAND replay_copy_offset_test) - # KHR CopyRaytracingAccelerationStructure (CLONE, COMPACT) and COMPACTED_SIZE postbuild (no GPU). - add_executable(replay_khr_as_copy_postbuild_test test/replay_khr_as_copy_postbuild_test.cpp) - target_link_libraries(replay_khr_as_copy_postbuild_test PRIVATE Vulkan::Headers) - if(WIN32) - target_compile_definitions(replay_khr_as_copy_postbuild_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - endif() - if(MSVC) - target_compile_options(replay_khr_as_copy_postbuild_test PRIVATE /W4 /permissive- /utf-8) - endif() - add_test(NAME replay_khr_as_copy_postbuild COMMAND replay_khr_as_copy_postbuild_test) - # PreparedList::wrote_readback and readback_src_stages match the actual producer stage (depth24, rgb96, UAV clear; no GPU). - add_executable(replay_readback_stages_test test/replay_readback_stages_test.cpp) - target_link_libraries(replay_readback_stages_test PRIVATE Vulkan::Headers) - if(WIN32) - target_compile_definitions(replay_readback_stages_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - endif() - add_test(NAME replay_readback_stages COMMAND replay_readback_stages_test) - # emit of an enhanced texture barrier: no heap allocation for one layout piece, one barrier for each piece (no GPU). - add_executable(replay_texture_barrier_test test/replay_texture_barrier_test.cpp) - target_link_libraries(replay_texture_barrier_test PRIVATE Vulkan::Headers) - if(WIN32) - target_compile_definitions(replay_texture_barrier_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - endif() - add_test(NAME replay_texture_barrier COMMAND replay_texture_barrier_test) - add_executable(clear_color_test test/clear_color_test.cpp) - target_link_libraries(clear_color_test PRIVATE Vulkan::Headers) - if(WIN32) - target_compile_definitions(clear_color_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - endif() - add_test(NAME clear_color COMMAND clear_color_test) - # FramePacer of the Xbox presentation path on a fake clock (src/frame_pacer.h); no GPU, no Vulkan. - add_executable(frame_pacer_test test/frame_pacer_test.cpp) - find_package(Threads REQUIRED) - target_link_libraries(frame_pacer_test PRIVATE Threads::Threads) - if(MSVC) - target_compile_options(frame_pacer_test PRIVATE /W4 /permissive- /utf-8) - endif() - add_test(NAME frame_pacer COMMAND frame_pacer_test) - - # Replay refuses a list whose whole-view or implicit zero-clear needs an unset vkCmdClear*Image (no GPU). - add_executable(replay_clear_gate_test test/replay_clear_gate_test.cpp) - target_link_libraries(replay_clear_gate_test PRIVATE Vulkan::Headers) - if(WIN32) - target_compile_definitions(replay_clear_gate_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - endif() - add_test(NAME replay_clear_gate COMMAND replay_clear_gate_test) - # WriteBufferImmediate suspends conditional rendering around vkCmdUpdateBuffer so Intel drivers do not drop it. - add_executable(replay_write_immediate_predication_test test/replay_write_immediate_predication_test.cpp) - target_link_libraries(replay_write_immediate_predication_test PRIVATE Vulkan::Headers) - if(WIN32) - target_compile_definitions(replay_write_immediate_predication_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - endif() - add_test(NAME replay_write_immediate_predication COMMAND replay_write_immediate_predication_test) - add_executable(d3d12_state_map_test test/d3d12_state_map_test.cpp) - target_link_libraries(d3d12_state_map_test PRIVATE Vulkan::Headers) - if(WIN32) - target_compile_definitions(d3d12_state_map_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - endif() - add_test(NAME d3d12_state_map COMMAND d3d12_state_map_test) - add_executable(indirect_dispatch_count_alloc_test test/indirect_dispatch_count_alloc_test.cpp) - target_link_libraries(indirect_dispatch_count_alloc_test PRIVATE Vulkan::Headers) - if(WIN32) - target_compile_definitions(indirect_dispatch_count_alloc_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - endif() - add_test(NAME indirect_dispatch_count_alloc COMMAND indirect_dispatch_count_alloc_test) - # A buffer UAV clear writes where its resource starts in a shared VkBuffer (no GPU). - add_executable(replay_uav_clear_offset_test test/replay_uav_clear_offset_test.cpp) - target_link_libraries(replay_uav_clear_offset_test PRIVATE Vulkan::Headers) - add_test(NAME replay_uav_clear_offset COMMAND replay_uav_clear_offset_test) - # ResolveQueryData suspends conditional rendering around un-ended vkCmdFillBuffer runs as well as dispatches (D3D-148). - add_executable(replay_query_predication_test test/replay_query_predication_test.cpp) - target_link_libraries(replay_query_predication_test PRIVATE Vulkan::Headers) - if(WIN32) - target_compile_definitions(replay_query_predication_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - endif() - add_test(NAME replay_query_predication COMMAND replay_query_predication_test) - # Query edge cases and queue ownership, with CPU mocks (no GPU or game data). - add_executable(replay_query_edges_test test/replay_query_edges_test.cpp) - target_link_libraries(replay_query_edges_test PRIVATE Vulkan::Headers) - if(WIN32) - target_compile_definitions(replay_query_edges_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - endif() - add_test(NAME replay_query_edges COMMAND replay_query_edges_test) - # GFX10 T#/S#/V# descriptor encoding and its Vulkan mappings (src/gfx10_descriptors.h). - add_executable(gfx10_descriptors_test test/gfx10_descriptors_test.cpp) - target_link_libraries(gfx10_descriptors_test PRIVATE Vulkan::Headers) - add_test(NAME gfx10_descriptors COMMAND gfx10_descriptors_test) - # CPU cost of the D3D12 -> Vulkan replay per command (record, prepare, emit) with no-op Vulkan entry points: - # no GPU or driver. ctest runs its quick self-test; run it without arguments for the numbers. - add_executable(replay_cpu_bench test/replay_cpu_bench.cpp) - target_link_libraries(replay_cpu_bench PRIVATE Vulkan::Headers) - if(WIN32) - target_compile_definitions(replay_cpu_bench PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - endif() - add_test(NAME replay_cpu_bench_selftest COMMAND replay_cpu_bench --self-test) - add_test(NAME vk_descriptor_bench_selftest COMMAND vk_descriptor_bench --self-test) - # mods.h: mod.json manifests and archetype swaps (docs/modding.md) - add_executable(mods_test test/mods_test.cpp) - target_link_libraries(mods_test PRIVATE Vulkan::Headers) - add_test(NAME mods COMMAND mods_test) - if(WIN32) - # code_hooks.h: the remapping thunk and direct-call redirection the archetype hook uses (x64 Windows) - add_executable(code_hooks_test test/code_hooks_test.cpp) - target_link_libraries(code_hooks_test PRIVATE Vulkan::Headers) - target_compile_definitions(code_hooks_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - add_test(NAME code_hooks COMMAND code_hooks_test) - endif() - # The subgroup size a pipeline stage asks for, from synthetic index entries and device properties. - add_executable(subgroup_size_test test/subgroup_size_test.cpp) - target_link_libraries(subgroup_size_test PRIVATE Vulkan::Headers) - add_test(NAME subgroup_size COMMAND subgroup_size_test) - add_executable(conservative_raster_test test/conservative_raster_test.cpp) - add_test(NAME conservative_raster COMMAND conservative_raster_test) - # The GPU address arena's size from LEONIDA_ARENA_MB and synthetic device buffer limits. - add_executable(arena_size_test test/arena_size_test.cpp) - target_link_libraries(arena_size_test PRIVATE Vulkan::Headers) - add_test(NAME arena_size COMMAND arena_size_test) - # Queue construction cleans its Vulkan handles if holder registration runs out of host memory. - add_executable(vk_queue_constructor_oom_test test/vk_queue_constructor_oom_test.cpp) - target_link_libraries(vk_queue_constructor_oom_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) - if(WIN32) - target_compile_definitions(vk_queue_constructor_oom_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - if(MSVC) - target_compile_options(vk_queue_constructor_oom_test PRIVATE /W4 /permissive- /EHsc /utf-8) - endif() - endif() - add_test(NAME vk_queue_constructor_oom COMMAND vk_queue_constructor_oom_test) - endif() + # The tests of the Vulkan layer that need its headers but no GPU. + include("${CMAKE_CURRENT_SOURCE_DIR}/cmake/vulkan_cpu_tests.cmake") else() include("${CMAKE_CURRENT_SOURCE_DIR}/cmake/vulkan_headers_missing.cmake") leonida_vulkan_headers_missing() endif() +# The sources that read a setting from the table (core/config.h). Many targets compile them directly (the loader +# tests build src/pe_loader.cpp themselves), so every target that compiles one of them links gta6rt_core here, in one +# place, and a source that moves to the table is added to this list. The list goes when the layers are libraries +# that carry the dependency themselves. +set(LEONIDA_SETTING_READERS + src/host_cpu.cpp + src/pe_loader.cpp + shims/registry.cpp + shims/bcrypt_rng.cpp + shims/xgameruntime.cpp + shims/xgameruntime_user.cpp + shims/xgameruntime_offline.cpp + shims/xgameruntime_gamesave.cpp + shims/d3d12_xs.cpp + shims/d3d12_xs_device.cpp + shims/xbox_present.cpp + shims/gameinput.cpp + shims/d3d12_vulkan_device.cpp + src/main.cpp +) +list(TRANSFORM LEONIDA_SETTING_READERS PREPEND "${CMAKE_CURRENT_SOURCE_DIR}/") +get_property(_gta6rt_targets DIRECTORY PROPERTY BUILDSYSTEM_TARGETS) +foreach(_target IN LISTS _gta6rt_targets) + get_target_property(_type ${_target} TYPE) + get_target_property(_sources ${_target} SOURCES) + if(NOT _sources OR NOT _type MATCHES "^(EXECUTABLE|STATIC_LIBRARY|SHARED_LIBRARY|MODULE_LIBRARY)$") + continue() + endif() + foreach(_source IN LISTS _sources) + if(_source MATCHES "^\\$<") + continue() # a generator expression: objects of another target, not a source file + endif() + get_filename_component(_source "${_source}" ABSOLUTE BASE_DIR "${CMAKE_CURRENT_SOURCE_DIR}") + if(_source IN_LIST LEONIDA_SETTING_READERS) + target_link_libraries(${_target} PRIVATE gta6rt_core) + break() + endif() + endforeach() +endforeach() + # Timed condition-variable waits on Wine 9 (#3796): every Windows executable and DLL built against the dynamic CRT # (/MD, the default) gets src/crt_timed_wait.cpp, which keeps msvcprt.lib's statically linked timed wait out of the # link so that a wait and the mutex it unlocks always use msvcp140's own layout. A target that links the CRT diff --git a/runtime/CMakePresets.json b/runtime/CMakePresets.json new file mode 100644 index 000000000..ad47d527d --- /dev/null +++ b/runtime/CMakePresets.json @@ -0,0 +1,53 @@ +{ + "version": 5, + "cmakeMinimumRequired": { "major": 3, "minor": 24, "patch": 0 }, + "configurePresets": [ + { + "name": "base", + "hidden": true, + "generator": "Ninja" + }, + { + "name": "dev", + "displayName": "dev", + "description": "For working on the runtime: no optimisation, assertions on, diagnostics compiled in", + "inherits": "base", + "binaryDir": "${sourceDir}/build-dev", + "cacheVariables": { + "CMAKE_BUILD_TYPE": "Debug", + "LEONIDA_DIAGNOSTICS": "ON" + } + }, + { + "name": "release", + "displayName": "release", + "description": "What a player runs: optimised, with debug information, no diagnostics. Builds into runtime/build", + "inherits": "base", + "binaryDir": "${sourceDir}/build", + "cacheVariables": { + "CMAKE_BUILD_TYPE": "RelWithDebInfo", + "LEONIDA_DIAGNOSTICS": "OFF" + } + }, + { + "name": "diag", + "displayName": "diag", + "description": "The release build with diagnostics compiled in, for finding a fault at release speed", + "inherits": "release", + "binaryDir": "${sourceDir}/build-diag", + "cacheVariables": { + "LEONIDA_DIAGNOSTICS": "ON" + } + } + ], + "buildPresets": [ + { "name": "dev", "configurePreset": "dev" }, + { "name": "release", "configurePreset": "release" }, + { "name": "diag", "configurePreset": "diag" } + ], + "testPresets": [ + { "name": "dev", "configurePreset": "dev", "output": { "outputOnFailure": true } }, + { "name": "release", "configurePreset": "release", "output": { "outputOnFailure": true } }, + { "name": "diag", "configurePreset": "diag", "output": { "outputOnFailure": true } } + ] +} diff --git a/runtime/README.md b/runtime/README.md index 61794a2c2..9226e9b93 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -22,6 +22,38 @@ cmake -S runtime -B runtime/build cmake --build runtime/build --config RelWithDebInfo ``` +`runtime/CMakePresets.json` names three builds. They use Ninja, so run them from an x64 Native Tools prompt, inside +`runtime/`: + +| Preset | Build type | `LEONIDA_DIAGNOSTICS` | Folder | +|---|---|---|---| +| `dev` | `Debug` | on | `runtime/build-dev` | +| `release` | `RelWithDebInfo` | off | `runtime/build` | +| `diag` | `RelWithDebInfo` | on | `runtime/build-diag` | + +```powershell +cmake --preset diag +cmake --build --preset diag +ctest --preset diag +``` + +`LEONIDA_DIAGNOSTICS=ON` compiles every target with `LEONIDA_DIAGNOSTICS` defined; code that only helps to find a +fault belongs behind it. `release` shares `runtime/build` with the commands above: a folder configured with another +generator has to be removed before the preset can use it. + +`runtime/CMakeLists.txt` holds the options and the order of the build; the targets are in the files it includes: + +| File | What it defines | +|---|---| +| `runtime/cmake/windows_runtime.cmake` | `gta6rt.exe`, the libraries its shims link, the shim test programs | +| `runtime/cmake/runtime_tests.cmake` | the tests that need no Vulkan headers, the stand-in titles (`tiny_*`) | +| `runtime/cmake/vulkan_tools.cmake` | the standalone Vulkan tools and their tests | +| `runtime/cmake/d3d12_vulkan.cmake` | the D3D12 COM objects over the Vulkan backend and their tests | +| `runtime/cmake/vulkan_cpu_tests.cmake` | the tests of the Vulkan layer that need its headers but no GPU | + +A test that checks the build by reading it uses `tests/runtime_cmake.py`, which reads these files along with +`runtime/CMakeLists.txt`. + Requirements: Windows x64, Visual Studio 2022 with the C++ desktop workload. The GPU tools need the Vulkan SDK; the runtime and CPU tests do not. The loader is x64-only and the PE mapper rejects any other machine. @@ -130,6 +162,60 @@ With `LEONIDA_RNG_SEED=` (decimal, or hexadecimal with `0x`; read once w runs with the same seed get the same bytes. The shim prints `[rt] bcrypt: deterministic LEONIDA_RNG_SEED enabled` with the seed on stderr; a seed of 0 uses a fixed non-zero state. Unset, the host's generator answers as before. +## Settings: `leonida.toml` and `gta6rt config` + +Every setting of the runtime is a row of one table, `kSettings` in `runtime/core/config.h`: a name in the settings +file (`section.name`), an environment variable and a default. A value is taken from the first of these that has one: + +1. the environment variable, when it is set and not empty; +2. the settings file; +3. the default. + +The settings file is the one `LEONIDA_CONFIG` names, else `leonida.toml` in the folder of `gta6rt.exe`, if there is +one. `runtime/leonida.example.toml` lists every setting with its default and its variable; copy it and remove the +`# ` in front of what you change. The file is read once, when `gta6rt` starts. A section or name that is not in the +table, a name set twice, or a `LEONIDA_CONFIG` that names no file ends the run with exit code 2 and a line such as +`leonida.toml:12: there is no setting vulkan.validaton`, so a misspelt setting cannot pass as one that does nothing. + +The format is the part of TOML the file needs: `[section]` lines, `name = value` lines and `#` comments. A value is +text in single quotes (taken as written, so a Windows path needs no doubled backslashes), text in double quotes +(only `\\` and `\"` are escapes), a number, or `true`/`false`. `''` leaves a setting unset. + +`gta6rt config` prints the file in use and one line per setting: its name, where its value comes from (`default`, +`file` or `environment`), its variable and the value. + +```text +settings file: C:\leonida\runtime\build\leonida.toml +system.gamertag environment LEONIDA_GAMERTAG Tester +vulkan.validation file LEONIDA_VK_VALIDATION 1 +vulkan.arena_mb default LEONIDA_ARENA_MB 256 +``` + +Only `gta6rt` loads a settings file. The test programs and tools load none, so for them a setting comes from its +environment variable or is the default. + +## Log levels: `LEONIDA_LOG` + +The runtime's diagnostics are the `[rt] : ...` lines on stderr. Each has a level: `error`, `warn`, `info` +or `debug`. `LEONIDA_LOG` (`log.level` in `leonida.toml`) names the highest level that is printed: `off`, `error`, +`warn`, `info`, `debug` or `trace`, in any case. A level prints its own lines and those of the levels before it; +`off` prints none. The default is `debug`, which prints what the runtime printed before it had levels; no line has +the level `trace` yet. There is one level for all modules. + +A value that is not a level prints one warning that lists the levels, and `debug` is used: + +```text +[rt] log: LEONIDA_LOG=loud unknown (off, error, warn, info, debug or trace), using debug +``` + +Not filtered, because they are answers of the program and not log lines: the usage text and the `error: ...` lines +of the command line, the binding report, the `gta6rt config` table and the `[d3d12-trace]` lines of +`--trace-d3d12`. `gta6rt` reads the setting once, at startup. The test programs do not read it and log at the +default. + +In the code a log line is one of the macros of `runtime/core/log.h`, such as `RT_LOG_WARN("module: text\n", ...)`; +the macro adds the `[rt] ` prefix. The header needs no library, so a header-only part of the runtime can log. + ## PE loader `src/pe_loader.cpp` maps x86-64 images at their preferred base, or elsewhere (with relocations) when @@ -406,8 +492,13 @@ blocks the import-driven work: console-only pipeline call, and the rest is open (`docs/d3d12_vulkan.md`, question 2). - The command-queue and fence extensions: the proxies forward the public slots, and the console's own methods past them (`PresentX`, `SuspendX`, `ResumeX`) have unknown slots, so they are refused with a log. - `PresentX` and the frame events themselves are implemented (`shims/xbox_present.*`, `xbox_present_test`) but - nothing reaches them yet: their queue and device slots are unmeasured. + `PresentX` and the frame events themselves are implemented (`shims/xbox_present.*`, `xbox_present_test`), and the + proxies have a place to hang them: a frame-event sink on device slots 78/79/80 and a present sink on the queue + (`shims/d3d12_xs_device.h`). `gta6rt` sets neither sink yet, so the frame calls still get the proxy's own answers + and a `PresentX` is still refused. The `PresentX` slot is not measured for this title (public code gives 30 for + an older runtime layout and 32 for a newer one), so no slot is taken for it by default: + `LEONIDA_XS_PRESENT_X_SLOT` (`d3d12.present_x_slot` in `leonida.toml`) names it, a queue slot from 19 to 127. A + value outside that range is logged once and ignored. The setting is read once per run. - Most of the `xgameruntime` surface: an offline shim covers `XGameRuntimeInitialize`, device/console queries, `XTaskQueue` and `XAsync`, and `QueryApiImpl` serves `XThreadingImpl`, `XErrorImpl`, `XNetworkingImpl`, `XPersistentLocalStorageImpl` and `XSystemImpl` (see `xgameruntime_test`); any other class is refused with a log. diff --git a/runtime/cmake/clang-cl-xwin.cmake b/runtime/cmake/clang-cl-xwin.cmake index 419550bc0..2848e5dca 100644 --- a/runtime/cmake/clang-cl-xwin.cmake +++ b/runtime/cmake/clang-cl-xwin.cmake @@ -103,7 +103,7 @@ set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE BOTH) set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) # LLVM's MASM stands in for ml64, so unimplemented_policy_test keeps its register-preservation check (abi_probe.asm). -# runtime/CMakeLists.txt keeps a LEONIDA_ML64 that is already set. +# runtime/cmake/runtime_tests.cmake keeps a LEONIDA_ML64 that is already set. find_program(LEONIDA_ML64 NAMES ml64 llvm-ml64) # ctest runs the PE tests through Wine, or Proton's wine (-DCMAKE_CROSSCOMPILING_EMULATOR=/files/bin/wine). diff --git a/runtime/cmake/d3d12_vulkan.cmake b/runtime/cmake/d3d12_vulkan.cmake new file mode 100644 index 000000000..a0f0219ae --- /dev/null +++ b/runtime/cmake/d3d12_vulkan.cmake @@ -0,0 +1,1538 @@ +# The D3D12 COM objects over the Vulkan backend (gta6rt_d3d12_com), their generated method stubs and their tests. +# Included by runtime/CMakeLists.txt inside if(TARGET Vulkan::Headers). + +# D3D12 COM objects over the Vulkan backend. Their method stubs are generated from the SDK's d3d12.h at build +# time (tools/gen_d3d12_stubs.py), so nothing derived from the SDK header is checked in. +find_package(Python3 COMPONENTS Interpreter QUIET) +# The generator finds d3d12.h through INCLUDE, which a Developer Prompt sets. A cross build (for example +# runtime/cmake/clang-cl-xwin.cmake) has no such prompt, so it is handed the header CMake finds. +set(_stubs_header) +set(_stubs_header_ok TRUE) +if(TARGET gta6rt AND CMAKE_CROSSCOMPILING) + find_file(LEONIDA_D3D12_HEADER d3d12.h) + if(LEONIDA_D3D12_HEADER) + set(_stubs_header --header "${LEONIDA_D3D12_HEADER}") + else() + set(_stubs_header_ok FALSE) + message(STATUS "d3d12.h not found (set CMAKE_INCLUDE_PATH): the D3D12 COM objects are not built") + endif() +endif() +if(TARGET gta6rt AND Python3_FOUND AND _stubs_header_ok) + set(LEONIDA_STUBS ${CMAKE_CURRENT_BINARY_DIR}/generated/d3d12_stubs.h) + add_custom_command( + OUTPUT ${LEONIDA_STUBS} + COMMAND "${Python3_EXECUTABLE}" -I ${CMAKE_CURRENT_SOURCE_DIR}/../tools/gen_d3d12_stubs.py --out ${LEONIDA_STUBS} + ${_stubs_header} + ID3D12GraphicsCommandList8 ID3D12CommandQueue ID3D12CommandAllocator ID3D12Fence1 + ID3D12Device11 ID3D12DescriptorHeap ID3D12Heap ID3D12Resource ID3D12QueryHeap ID3D12RootSignature + ID3D12PipelineState ID3D12CommandSignature ID3D12PipelineLibrary1 ID3D12ShaderCacheSession + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/../tools/gen_d3d12_stubs.py ${LEONIDA_D3D12_HEADER} + COMMENT "Generating D3D12 COM stubs" + VERBATIM) + add_library(gta6rt_d3d12_com STATIC shims/d3d12_com.cpp shims/d3d12_vulkan_device.cpp shims/d3d12_xs_device.cpp shims/xbox_present.cpp + shims/dxgi_com.cpp ${LEONIDA_STUBS}) # d3d12_vulkan_device.cpp reads the PC device behind the proxy (#224) + target_include_directories(gta6rt_d3d12_com PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/generated) + target_link_libraries(gta6rt_d3d12_com PUBLIC Vulkan::Headers gta6rt_root_signature) + target_compile_definitions(gta6rt_d3d12_com PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + # /bigobj: a Debug build of d3d12_vulkan_device.cpp has more sections than a COFF object holds by default + # (fatal error C1128), because without optimisation every inline function keeps its own COMDAT. + target_compile_options(gta6rt_d3d12_com PRIVATE /W4 /permissive- /utf-8 /bigobj) + + add_executable(d3d12_com_test test/d3d12_com_test.cpp) + target_link_libraries(d3d12_com_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_com_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_com_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_com COMMAND d3d12_com_test) + set_tests_properties(d3d12_com PROPERTIES SKIP_RETURN_CODE 77) + + # Where the device finds its translated shaders (shader_path.txt, a path that is not UTF-8). No GPU. + add_executable(d3d12_shader_path_test test/d3d12_shader_path_test.cpp) + target_link_libraries(d3d12_shader_path_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_shader_path_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_shader_path_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_shader_path COMMAND d3d12_shader_path_test) + + # Multi-threaded concurrent submissions across two D3D12 queues + resource creation/destruction churn. + add_executable(d3d12_multithread_test test/d3d12_multithread_test.cpp) + target_link_libraries(d3d12_multithread_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_multithread_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_multithread_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_multithread COMMAND d3d12_multithread_test) + # 300 s, not 120: the test's 60 s fence waits need headroom when other GPU tests share the device + # (two concurrent `ctest -j 6` suites pushed it to 91-120 s; TEST-514 follow-up). + set_tests_properties(d3d12_multithread PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 300) + # Several threads make the first CheckFeatureSupport(D3D12_OPTIONS1) call of a new device at the same time. + add_executable(d3d12_options1_first_use_test test/d3d12_options1_first_use_test.cpp) + target_link_libraries(d3d12_options1_first_use_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_options1_first_use_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_options1_first_use_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_options1_first_use COMMAND d3d12_options1_first_use_test) + set_tests_properties(d3d12_options1_first_use PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) + # A queued Wait must not block a Signal submitted by another D3D12 queue. + add_executable(d3d12_queue_wait_test test/d3d12_queue_wait_test.cpp) + target_link_libraries(d3d12_queue_wait_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_queue_wait_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_queue_wait_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_queue_wait COMMAND d3d12_queue_wait_test) + add_executable(d3d12_noop_copy_test test/d3d12_noop_copy_test.cpp) + target_link_libraries(d3d12_noop_copy_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_noop_copy_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_noop_copy_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_noop_copy COMMAND d3d12_noop_copy_test) + set_tests_properties(d3d12_noop_copy PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 45) + set_tests_properties(d3d12_queue_wait PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + add_test(NAME d3d12_queue_wait_timeout COMMAND d3d12_queue_wait_test --timeout-control) + # Under Ubuntu's Wine 9.0 this test runs into the 10 s without printing anything. With 60 s (9002b42) it no longer + # did, but the tests after it stayed slow and the wine (ubuntu) job was cancelled at 30 minutes (run 45428701383); + # with 10 s the same job passed in 694 s (run 45410688081). Why is not known yet, so the limit stays. + set_tests_properties(d3d12_queue_wait_timeout PROPERTIES SKIP_RETURN_CODE 77 WILL_FAIL TRUE TIMEOUT 10) + # ExecuteCommandLists refuses a list whose type isn't the queue's (debug-layer message 836). + add_executable(d3d12_queue_list_type_test test/d3d12_queue_list_type_test.cpp) + target_link_libraries(d3d12_queue_list_type_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_queue_list_type_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_queue_list_type_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_queue_list_type COMMAND d3d12_queue_list_type_test) + set_tests_properties(d3d12_queue_list_type PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30) + # Cross-device ownership validation: Signal, Wait, SetEventOnMultipleFenceCompletion, ExecuteCommandLists, ExecuteBundle. + add_executable(d3d12_cross_device_validation_test test/d3d12_cross_device_validation_test.cpp) + target_link_libraries(d3d12_cross_device_validation_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_cross_device_validation_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_cross_device_validation_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_cross_device_validation COMMAND d3d12_cross_device_validation_test) + set_tests_properties(d3d12_cross_device_validation PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60 + FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") + # Wait-before-Signal with a texture and a buffer handed over between the COPY, COMPUTE and DIRECT queues, in every + # submission order, on the layer and on the host runtime (docs/d3d12_vulkan.md section 4.4). + add_executable(d3d12_queue_handover_test test/d3d12_queue_handover_test.cpp) + target_link_libraries(d3d12_queue_handover_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_queue_handover_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_queue_handover_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_queue_handover COMMAND d3d12_queue_handover_test) + set_tests_properties(d3d12_queue_handover PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 400 + FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") + # The same on a caller-owned device: two VkQueues handed to the layer (the D3D12 queues share them), and one + # (every D3D12 queue shares it, where a Wait ahead of its Signal would never progress on the GPU). + add_test(NAME d3d12_queue_handover_two_queues COMMAND d3d12_queue_handover_test --two-queues) + add_test(NAME d3d12_queue_handover_shared_queue COMMAND d3d12_queue_handover_test --shared-queue) + set_tests_properties(d3d12_queue_handover_two_queues d3d12_queue_handover_shared_queue PROPERTIES + SKIP_RETURN_CODE 77 TIMEOUT 400 FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") + # More D3D12 queues than Vulkan queues: they share VkQueues, keeping fences and Wait-before-Signal (section 4.4). + # The _one_queue runs make every GPU look like the Intel UHD 770 (one family, one VkQueue): every queue shares it. + add_executable(d3d12_queue_share_test test/d3d12_queue_share_test.cpp) + target_link_libraries(d3d12_queue_share_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_queue_share_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_queue_share_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_queue_share COMMAND d3d12_queue_share_test) + add_test(NAME d3d12_queue_share_one_queue COMMAND d3d12_queue_share_test) + set_tests_properties(d3d12_queue_share d3d12_queue_share_one_queue PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 300 + FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") + add_test(NAME d3d12_queue_wait_one_queue COMMAND d3d12_queue_wait_test) + set_tests_properties(d3d12_queue_wait_one_queue PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + set_tests_properties(d3d12_queue_share_one_queue d3d12_queue_wait_one_queue PROPERTIES + ENVIRONMENT "LEONIDA_VK_MAX_QUEUES_PER_FAMILY=1;LEONIDA_VK_GRAPHICS_FAMILY_ONLY=1") + # A misspelt case or count is refused with the usage line (exit code 2) before a device exists, instead of + # passing with nothing run. No GPU needed. + set(_share_bad_arguments "case_typo|--case|typo" "iterations_zero|--iterations|0" + "iterations_word|--iterations|banana" "iterations_too_many|--iterations|99999999999") + foreach(_bad IN LISTS _share_bad_arguments) + string(REPLACE "|" ";" _bad "${_bad}") + list(POP_FRONT _bad _bad_name) + add_test(NAME d3d12_queue_share_rejects_${_bad_name} COMMAND d3d12_queue_share_test ${_bad}) + set_tests_properties(d3d12_queue_share_rejects_${_bad_name} PROPERTIES TIMEOUT 60 + PASS_REGULAR_EXPRESSION "\nusage: d3d12_queue_share_test ") + endforeach() + + # XDXR acceleration structures through BuildRaytracingAccelerationStructure (docs/d3d12_vulkan.md 4.8): the + # device builds them, tools/xdxr_bvh.py checks them. + add_executable(d3d12_xdxr_rt_test test/d3d12_xdxr_rt_test.cpp) + target_link_libraries(d3d12_xdxr_rt_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_xdxr_rt_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_xdxr_rt_test PRIVATE /W4 /permissive- /utf-8) + set(LEONIDA_D3D12_XDXR_OUT "${CMAKE_CURRENT_BINARY_DIR}/d3d12_xdxr_cases") + file(MAKE_DIRECTORY "${LEONIDA_D3D12_XDXR_OUT}") + add_test(NAME d3d12_xdxr_rt COMMAND d3d12_xdxr_rt_test "${LEONIDA_D3D12_XDXR_OUT}") + set_tests_properties(d3d12_xdxr_rt PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60 FIXTURES_SETUP d3d12_xdxr_cases) + find_package(Python3 COMPONENTS Interpreter QUIET) + if(Python3_FOUND) + add_test(NAME d3d12_xdxr_rt_check COMMAND "${Python3_EXECUTABLE}" -I + "${CMAKE_CURRENT_SOURCE_DIR}/../tools/xdxr_bvh.py" check-build "${LEONIDA_D3D12_XDXR_OUT}" --rays 1000) + set_tests_properties(d3d12_xdxr_rt_check PROPERTIES FIXTURES_REQUIRED d3d12_xdxr_cases SKIP_RETURN_CODE 77) + endif() + + # GCL8's QueryInterface and its one method need an allocator and a list, not a Vulkan device. + add_executable(d3d12_gcl8_test test/d3d12_gcl8_test.cpp) + target_link_libraries(d3d12_gcl8_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_gcl8_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_gcl8_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_gcl8 COMMAND d3d12_gcl8_test) + # Python runs on the host; a cross-compiled fixture runs through the emulator (Wine), which the script prepends. + # The interpreter is named by path, because ctest would put the emulator in front of an executable target. + set(_trace_runner) + foreach(_part IN LISTS CMAKE_CROSSCOMPILING_EMULATOR) + list(APPEND _trace_runner "--runner=${_part}") # one word each, even one that starts with "-" (xvfb-run -a) + endforeach() + add_test(NAME d3d12_trace COMMAND "${Python3_EXECUTABLE}" -I + "${CMAKE_CURRENT_SOURCE_DIR}/test/check_d3d12_trace.py" "$" ${_trace_runner}) + + # The Vulkan device behind the Xbox-ABI proxy, end to end. + add_executable(d3d12_vulkan_device_test test/d3d12_vulkan_device_test.cpp) + target_link_libraries(d3d12_vulkan_device_test PRIVATE gta6rt_d3d12_com dxguid) # IID_ID3D12MetaCommand (#1440) + target_compile_definitions(d3d12_vulkan_device_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_vulkan_device_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_vulkan_device COMMAND d3d12_vulkan_device_test) + + add_executable(d3d12_buffer_tiles_test test/d3d12_buffer_tiles_test.cpp) + target_link_libraries(d3d12_buffer_tiles_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_buffer_tiles_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_buffer_tiles_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_buffer_tiles COMMAND d3d12_buffer_tiles_test) + set_tests_properties(d3d12_buffer_tiles PROPERTIES SKIP_RETURN_CODE 77 + FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") + add_executable(d3d12_texture_tiles_test test/d3d12_texture_tiles_test.cpp) + target_link_libraries(d3d12_texture_tiles_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_texture_tiles_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_texture_tiles_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_texture_tiles COMMAND d3d12_texture_tiles_test) + set_tests_properties(d3d12_texture_tiles PROPERTIES SKIP_RETURN_CODE 77 + FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") + + # DXR acceleration-structure prebuild and command-list recording validation parity test. + add_executable(d3d12_dxr_validation_test test/d3d12_dxr_validation_test.cpp) + target_link_libraries(d3d12_dxr_validation_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_dxr_validation_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_dxr_validation_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_dxr_validation COMMAND d3d12_dxr_validation_test) + add_test(NAME d3d12_dxr_validation_khr COMMAND d3d12_dxr_validation_test) + set_tests_properties(d3d12_dxr_validation d3d12_dxr_validation_khr PROPERTIES SKIP_RETURN_CODE 77 + FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") + set_tests_properties(d3d12_dxr_validation_khr PROPERTIES ENVIRONMENT "LEONIDA_RT_AS=khr") + + # D3D12 permits UpdateTileMappings on DIRECT/COPY/COMPUTE and a sparse buffer must remain + # accessible across their selected Vulkan families. The optional API-dump check catches an + # EXCLUSIVE VkBuffer even on drivers that happen to return correct bytes without ownership barriers. + add_executable(d3d12_sparse_queue_family_test test/d3d12_sparse_queue_family_test.cpp) + target_link_libraries(d3d12_sparse_queue_family_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_sparse_queue_family_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_sparse_queue_family_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_sparse_queue_family COMMAND d3d12_sparse_queue_family_test) + set_tests_properties(d3d12_sparse_queue_family PROPERTIES SKIP_RETURN_CODE 77 + FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") + if(Python3_FOUND AND NOT CMAKE_CROSSCOMPILING) + add_test(NAME d3d12_sparse_queue_family_contract COMMAND "${Python3_EXECUTABLE}" -I + "${CMAKE_CURRENT_SOURCE_DIR}/test/check_sparse_queue_family.py" + "$") + set_tests_properties(d3d12_sparse_queue_family_contract PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 65) + endif() + set_tests_properties(d3d12_vulkan_device PROPERTIES SKIP_RETURN_CODE 77) + + add_executable(d3d12_texture1d_test test/d3d12_texture1d_test.cpp) + target_link_libraries(d3d12_texture1d_test PRIVATE gta6rt_d3d12_com dxguid) + target_compile_definitions(d3d12_texture1d_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_texture1d_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_texture1d COMMAND d3d12_texture1d_test) + set_tests_properties(d3d12_texture1d PROPERTIES SKIP_RETURN_CODE 77) + + # Placed 1D and 3D textures against the host runtime and WARP, and a copy round trip through them. + add_executable(d3d12_placed_dimensions_test test/d3d12_placed_dimensions_test.cpp) + target_link_libraries(d3d12_placed_dimensions_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_placed_dimensions_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_placed_dimensions_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_placed_dimensions COMMAND d3d12_placed_dimensions_test) + set_tests_properties(d3d12_placed_dimensions PROPERTIES SKIP_RETURN_CODE 77 + FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") + + # FORMAT_SUPPORT of the depth- and stencil-plane view formats and comparison sampling, against the host runtime. + add_executable(d3d12_depth_view_format_support_test test/d3d12_depth_view_format_support_test.cpp) + target_link_libraries(d3d12_depth_view_format_support_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_depth_view_format_support_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_depth_view_format_support_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_depth_view_format_support COMMAND d3d12_depth_view_format_support_test) + set_tests_properties(d3d12_depth_view_format_support PROPERTIES SKIP_RETURN_CODE 77) + + # A placed buffer keeps its heap's arena range after the application releases the heap. + add_executable(d3d12_placed_heap_lifetime_test test/d3d12_placed_heap_lifetime_test.cpp) + target_link_libraries(d3d12_placed_heap_lifetime_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_placed_heap_lifetime_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_placed_heap_lifetime_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_placed_heap_lifetime COMMAND d3d12_placed_heap_lifetime_test) + set_tests_properties(d3d12_placed_heap_lifetime PROPERTIES SKIP_RETURN_CODE 77 + FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") + + # ClearUnorderedAccessViewUint/Float on buffers and textures, read back through D3D12. + add_executable(d3d12_uav_clear_test test/d3d12_uav_clear_test.cpp) + target_link_libraries(d3d12_uav_clear_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_uav_clear_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_uav_clear_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_uav_clear COMMAND d3d12_uav_clear_test) + set_tests_properties(d3d12_uav_clear PROPERTIES SKIP_RETURN_CODE 77) + + add_executable(d3d12_short_uav_clear_test test/d3d12_short_uav_clear_test.cpp) + target_link_libraries(d3d12_short_uav_clear_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_short_uav_clear_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_short_uav_clear_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_short_uav_clear COMMAND d3d12_short_uav_clear_test) + set_tests_properties(d3d12_short_uav_clear PROPERTIES SKIP_RETURN_CODE 77 + ENVIRONMENT "LEONIDA_HOST_ADAPTER=warp") + + # Emulation of R9G9B9E5_SHAREDEXP UAV textures as mutable R32_UINT on GPUs without E5B9G9R9 storage: + # format support, 1D/2D/3D/reserved creation, SRV/UAV T#s, WARP differential UAV clears, cross-backing copies, + # and set-0 storage write -> E5B9G9R9 sampled HDR round-trip. + add_executable(d3d12_d24_support_test test/d3d12_d24_support_test.cpp) + target_link_libraries(d3d12_d24_support_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_d24_support_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_d24_support_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_d24_support COMMAND d3d12_d24_support_test) + set_tests_properties(d3d12_d24_support PROPERTIES SKIP_RETURN_CODE 77) + add_executable(d3d12_b5g5r5a1_uav_test test/d3d12_b5g5r5a1_uav_test.cpp) + target_link_libraries(d3d12_b5g5r5a1_uav_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_b5g5r5a1_uav_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_b5g5r5a1_uav_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_b5g5r5a1_uav COMMAND d3d12_b5g5r5a1_uav_test) + set_tests_properties(d3d12_b5g5r5a1_uav PROPERTIES SKIP_RETURN_CODE 77) + add_executable(d3d12_srgb_uav_test test/d3d12_srgb_uav_test.cpp) + target_link_libraries(d3d12_srgb_uav_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_srgb_uav_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_srgb_uav_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_srgb_uav COMMAND d3d12_srgb_uav_test) + set_tests_properties(d3d12_srgb_uav PROPERTIES SKIP_RETURN_CODE 77) # native sRGB storage, no Vulkan GPU, or Wine + add_executable(d3d12_r9g9b9e5_uav_test test/d3d12_r9g9b9e5_uav_test.cpp) + target_link_libraries(d3d12_r9g9b9e5_uav_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_r9g9b9e5_uav_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_r9g9b9e5_uav_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_r9g9b9e5_uav COMMAND d3d12_r9g9b9e5_uav_test) + set_tests_properties(d3d12_r9g9b9e5_uav PROPERTIES SKIP_RETURN_CODE 77) + if(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) + set(LEONIDA_TEST_CS_R9G9B9E5_UAV ${CMAKE_CURRENT_BINARY_DIR}/generated/cs_r9g9b9e5_uav.spv) + add_custom_command( + OUTPUT ${LEONIDA_TEST_CS_R9G9B9E5_UAV} + COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${LEONIDA_TEST_CS_R9G9B9E5_UAV} + ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_r9g9b9e5_uav.comp + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_r9g9b9e5_uav.comp + COMMENT "Compiling cs_r9g9b9e5_uav.comp" + VERBATIM) + target_sources(d3d12_r9g9b9e5_uav_test PRIVATE ${LEONIDA_TEST_CS_R9G9B9E5_UAV}) + target_compile_definitions(d3d12_r9g9b9e5_uav_test PRIVATE + LEONIDA_TEST_CS_R9G9B9E5_UAV_SPV="${LEONIDA_TEST_CS_R9G9B9E5_UAV}") + endif() + + # Debug markers as VK_EXT_debug_utils labels, and private data on every object (D3D-24). + add_executable(d3d12_debug_markers_test test/d3d12_debug_markers_test.cpp) + target_link_libraries(d3d12_debug_markers_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_debug_markers_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_debug_markers_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_debug_markers COMMAND d3d12_debug_markers_test) + set_tests_properties(d3d12_debug_markers PROPERTIES SKIP_RETURN_CODE 77) + + # Existing-memory heaps and lifetime trackers: the arguments the host refuses (OpenExistingHeapFromAddress, + # OpenExistingHeapFromFileMapping, CreateLifetimeTracker). + add_executable(d3d12_existing_heap_test test/d3d12_existing_heap_test.cpp) + target_link_libraries(d3d12_existing_heap_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_existing_heap_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_existing_heap_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_existing_heap COMMAND d3d12_existing_heap_test) + set_tests_properties(d3d12_existing_heap PROPERTIES SKIP_RETURN_CODE 77) + # Slot 133 on untouched xmem physical pages: committed through the pages hook, then imported. xmem.cpp and + # registry.cpp are compiled in, as xmem_test does, to reach the registered XMem* exports. + add_executable(d3d12_xmem_placed_test test/d3d12_xmem_placed_test.cpp shims/xmem.cpp shims/registry.cpp) + target_link_libraries(d3d12_xmem_placed_test PRIVATE gta6rt_d3d12_com d3d12 dxgi psapi) + target_compile_definitions(d3d12_xmem_placed_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_xmem_placed_test PRIVATE /W4 /permissive- /utf-8) + target_link_options(d3d12_xmem_placed_test PRIVATE /OPT:NOREF) + add_test(NAME d3d12_xmem_placed COMMAND d3d12_xmem_placed_test) + set_tests_properties(d3d12_xmem_placed PROPERTIES SKIP_RETURN_CODE 77) + + # Fences and timing (D3D-30): multiple-fence waits, clock calibration, adapter LUID, custom heap properties. + add_executable(d3d12_fence_timing_test test/d3d12_fence_timing_test.cpp) + target_link_libraries(d3d12_fence_timing_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_fence_timing_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_fence_timing_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_fence_timing COMMAND d3d12_fence_timing_test) + set_tests_properties(d3d12_fence_timing PROPERTIES SKIP_RETURN_CODE 77) + # Fence events the host runtime sets or refuses (released fences, no fences), compared with the host devices. + add_executable(d3d12_fence_events_test test/d3d12_fence_events_test.cpp) + target_link_libraries(d3d12_fence_events_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_fence_events_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_fence_events_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_fence_events COMMAND d3d12_fence_events_test) + set_tests_properties(d3d12_fence_events PROPERTIES SKIP_RETURN_CODE 77) + add_executable(d3d12_fence_device_lost_counter_test test/d3d12_fence_device_lost_counter_test.cpp) + target_link_libraries(d3d12_fence_device_lost_counter_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_fence_device_lost_counter_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_fence_device_lost_counter_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_fence_device_lost_counter COMMAND d3d12_fence_device_lost_counter_test) + set_tests_properties(d3d12_fence_device_lost_counter PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + # Xbox-ABI queue and fence proxies behind the device proxy, on the host runtime (WARP, a hardware adapter) and + # on the Vulkan device: forwarding, refusal past the public chain, fence unwrapping. 77: no device at all. + add_executable(queue_proxy_test test/queue_proxy_test.cpp) + target_link_libraries(queue_proxy_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(queue_proxy_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(queue_proxy_test PRIVATE /W4 /permissive- /utf-8 /EHsc) + add_test(NAME queue_proxy COMMAND queue_proxy_test) + set_tests_properties(queue_proxy PROPERTIES SKIP_RETURN_CODE 77) + # Xbox-ABI command allocator proxies (device slot 9) on the Vulkan device, and the unwrapped PC allocator on the + # host runtime: forwarding, refused tail, guard region, lists and GPU copies on the proxy. 77: no device at all. + add_executable(allocator_proxy_test test/allocator_proxy_test.cpp) + target_link_libraries(allocator_proxy_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(allocator_proxy_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(allocator_proxy_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME allocator_proxy COMMAND allocator_proxy_test) + set_tests_properties(allocator_proxy PROPERTIES SKIP_RETURN_CODE 77) + # IDXGIDevice1 on the device proxy (the GDKX boot step: QueryInterface, GetAdapter, EnumOutputs), on the host + # runtime and on the Vulkan device: COM identity with the device, the adapter's LUID. 77: no device at all. + add_executable(dxgi_device_test test/dxgi_device_test.cpp) + target_link_libraries(dxgi_device_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(dxgi_device_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(dxgi_device_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME dxgi_device COMMAND dxgi_device_test) + set_tests_properties(dxgi_device PROPERTIES SKIP_RETURN_CODE 77) + add_executable(dxgi_host_answers_test test/dxgi_host_answers_test.cpp) + target_link_libraries(dxgi_host_answers_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(dxgi_host_answers_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(dxgi_host_answers_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME dxgi_host_answers COMMAND dxgi_host_answers_test) + set_tests_properties(dxgi_host_answers PROPERTIES SKIP_RETURN_CODE 77) + # The countdown behind those event-backed waits, with no GPU: the full unsigned count, no wrap past zero. + add_executable(d3d12_fence_waiter_test test/d3d12_fence_waiter_test.cpp) + target_compile_definitions(d3d12_fence_waiter_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_fence_waiter_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_fence_waiter COMMAND d3d12_fence_waiter_test) + # The 1/2/3 method variants (D3D-28) against the methods they wrap, on the Vulkan device directly. + add_executable(d3d12_method_variants_test test/d3d12_method_variants_test.cpp) + target_link_libraries(d3d12_method_variants_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_method_variants_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_method_variants_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_method_variants COMMAND d3d12_method_variants_test) + # ID3D12Device9::CreateShaderCacheSession, ID3D12ShaderCacheSession and ShaderCacheControl (D3D-34). + add_executable(d3d12_shader_cache_test test/d3d12_shader_cache_test.cpp) + target_link_libraries(d3d12_shader_cache_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_shader_cache_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_shader_cache_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_shader_cache COMMAND d3d12_shader_cache_test) + set_tests_properties(d3d12_shader_cache PROPERTIES SKIP_RETURN_CODE 77) + set_tests_properties(d3d12_method_variants PROPERTIES SKIP_RETURN_CODE 77) + # ID3D12Object private data (GetPrivateData, SetPrivateData, SetPrivateDataInterface, SetName) compared with + # the host runtime's answers on the device and four child objects. + add_executable(d3d12_private_data_test test/d3d12_private_data_test.cpp) + target_link_libraries(d3d12_private_data_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_private_data_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_private_data_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_private_data COMMAND d3d12_private_data_test) + set_tests_properties(d3d12_private_data PROPERTIES SKIP_RETURN_CODE 77) + + # CreateSampler2 (D3D-28) against CreateSampler, and its refusals against the host's PC runtime. + add_executable(d3d12_sampler2_test test/d3d12_sampler2_test.cpp) + target_link_libraries(d3d12_sampler2_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_sampler2_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_sampler2_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_sampler2 COMMAND d3d12_sampler2_test) + set_tests_properties(d3d12_sampler2 PROPERTIES SKIP_RETURN_CODE 77) + + # Descriptors through the proxy: copies between heaps, what texture views and samplers write into their slots, + # and (where glslangValidator is found) a compute shader the test runs on the device's bindless set, which + # finds a T# and an S# through the hash table and samples. The shader is GLSL, compiled here. + add_executable(d3d12_descriptor_test test/d3d12_descriptor_test.cpp) + target_link_libraries(d3d12_descriptor_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_descriptor_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_descriptor_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_descriptor COMMAND d3d12_descriptor_test) + set_tests_properties(d3d12_descriptor PROPERTIES SKIP_RETURN_CODE 77) + if(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) + function(descriptor_test_shader shader definition) + set(source ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${shader}) + set(binary ${CMAKE_CURRENT_BINARY_DIR}/generated/${definition}.spv) + add_custom_command(OUTPUT ${binary} + COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 ${ARGN} -o ${binary} ${source} + DEPENDS ${source} COMMENT "Compiling descriptor test shader ${shader}" VERBATIM) + target_sources(d3d12_descriptor_test PRIVATE ${binary}) + target_compile_definitions(d3d12_descriptor_test PRIVATE ${definition}="${binary}") + endfunction() + descriptor_test_shader(cs_sample.comp LEONIDA_TEST_CS_SAMPLE_SPV) + descriptor_test_shader(cs_sample.comp LEONIDA_TEST_GATHER_ALPHA_SPV -DTEST_GATHER_ALPHA=1) + descriptor_test_shader(cs_sample.comp LEONIDA_TEST_MS_FLOAT_SPV -DTEST_MS_FLOAT=1) + descriptor_test_shader(cs_sample.comp LEONIDA_TEST_MS_UINT_SPV -DTEST_MS_UINT=1) + descriptor_test_shader(cs_sample.comp LEONIDA_TEST_MS_SINT_SPV -DTEST_MS_SINT=1) + descriptor_test_shader(msaa_seed.vert LEONIDA_TEST_MSAA_VERT_SPV) + descriptor_test_shader(msaa_seed.frag LEONIDA_TEST_MSAA_FRAG_SPV) + else() + message(STATUS "glslangValidator not found: d3d12_descriptor_test skips its shader") + endif() + + add_executable(d3d12_predicated_copy_test test/d3d12_predicated_copy_test.cpp) + target_link_libraries(d3d12_predicated_copy_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_predicated_copy_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_predicated_copy_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_predicated_copy COMMAND d3d12_predicated_copy_test) + set_tests_properties(d3d12_predicated_copy PROPERTIES SKIP_RETURN_CODE 77) + # A DISPATCH-only ExecuteIndirect signature with a GPU count buffer: native Windows WARP versus Vulkan GPU, + # including a GPU-written count that changes between two calls in the same command list. + if(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) + set(_indirect_count_spv ${CMAKE_CURRENT_BINARY_DIR}/generated/cs_indirect_dispatch_count.spv) + add_custom_command(OUTPUT ${_indirect_count_spv} + COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.2 + -o ${_indirect_count_spv} ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_indirect_dispatch_count.comp + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_indirect_dispatch_count.comp + COMMENT "Compiling the counted indirect dispatch test shader" VERBATIM) + add_executable(d3d12_indirect_dispatch_count_test test/d3d12_indirect_dispatch_count_test.cpp + ${_indirect_count_spv}) + target_link_libraries(d3d12_indirect_dispatch_count_test PRIVATE gta6rt_d3d12_com d3d12 dxgi version) + target_compile_definitions(d3d12_indirect_dispatch_count_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_INDIRECT_COUNT_SPV="${_indirect_count_spv}") + target_compile_options(d3d12_indirect_dispatch_count_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_indirect_dispatch_count COMMAND d3d12_indirect_dispatch_count_test) + set_tests_properties(d3d12_indirect_dispatch_count PROPERTIES SKIP_RETURN_CODE 77) + endif() + + # What Close returns after one recorded call, against WARP; today's differences are listed in the test. + add_executable(d3d12_close_parity_test test/d3d12_close_parity_test.cpp) + target_link_libraries(d3d12_close_parity_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_close_parity_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_close_parity_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_close_parity COMMAND d3d12_close_parity_test) + set_tests_properties(d3d12_close_parity PROPERTIES SKIP_RETURN_CODE 77) + + # ExecuteIndirect recording-time Close() parity against live WARP and hardware D3D12, plus GPU dispatch sanity. + add_executable(d3d12_execute_indirect_validation_test test/d3d12_execute_indirect_validation_test.cpp) + target_link_libraries(d3d12_execute_indirect_validation_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_execute_indirect_validation_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_execute_indirect_validation_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_execute_indirect_validation COMMAND d3d12_execute_indirect_validation_test) + set_tests_properties(d3d12_execute_indirect_validation PROPERTIES + SKIP_RETURN_CODE 77 + FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") + + # Set{Compute,Graphics}Root* closed-list, zero-count null, CBV alignment, and foreign root signature parity. + add_executable(d3d12_root_args_validation_test test/d3d12_root_args_validation_test.cpp) + target_link_libraries(d3d12_root_args_validation_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_root_args_validation_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_root_args_validation_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_root_args_validation COMMAND d3d12_root_args_validation_test) + set_tests_properties(d3d12_root_args_validation PROPERTIES + SKIP_RETURN_CODE 77 + FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") + + # ClearState predication reset (GPU readback) + SetPredication / AtomicCopyBuffer Close() parity against WARP & HW. + add_executable(d3d12_predication_atomic_copy_test test/d3d12_predication_atomic_copy_test.cpp) + target_link_libraries(d3d12_predication_atomic_copy_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_predication_atomic_copy_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_predication_atomic_copy_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_predication_atomic_copy COMMAND d3d12_predication_atomic_copy_test) + set_tests_properties(d3d12_predication_atomic_copy PROPERTIES + SKIP_RETURN_CODE 77 + FAIL_REGULAR_EXPRESSION "Validation Error;VUID-" + ) + + # Differential regression: run explicitly (requires Vulkan hardware and Windows WARP). + add_executable(d3d12_clear_test test/d3d12_clear_test.cpp) + target_link_libraries(d3d12_clear_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_clear_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_clear_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_rgb9e5_rtv COMMAND d3d12_clear_test --rgb9e5) + set_tests_properties(d3d12_rgb9e5_rtv PROPERTIES SKIP_RETURN_CODE 77) + add_test(NAME d3d12_clear COMMAND d3d12_clear_test) + set_tests_properties(d3d12_clear PROPERTIES SKIP_RETURN_CODE 77) + + # Synthetic typed-view readbacks against Windows WARP; run explicitly on a Vulkan GPU. + add_executable(d3d12_typeless_rtv_test test/d3d12_typeless_rtv_test.cpp) + target_link_libraries(d3d12_typeless_rtv_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_typeless_rtv_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_typeless_rtv_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_typeless_rtv COMMAND d3d12_typeless_rtv_test) + # 1D render targets and depth buffers: creation against the host and WARP, clears read back against WARP. + add_executable(d3d12_texture1d_target_test test/d3d12_texture1d_target_test.cpp) + target_link_libraries(d3d12_texture1d_target_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_texture1d_target_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_texture1d_target_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_texture1d_target COMMAND d3d12_texture1d_target_test) + set_tests_properties(d3d12_texture1d_target PROPERTIES SKIP_RETURN_CODE 77) # no Vulkan GPU, or Wine + + # ArraySize -1 in array RTVs and DSVs (every slice from the first on), against the host on the same adapter + # and WARP. + add_executable(d3d12_view_slices_test test/d3d12_view_slices_test.cpp) + target_link_libraries(d3d12_view_slices_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_view_slices_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_view_slices_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_view_slices COMMAND d3d12_view_slices_test) + set_tests_properties(d3d12_view_slices PROPERTIES SKIP_RETURN_CODE 77) + + # Typed RTV clears and draws of every TYPELESS color family against the host on the same adapter and WARP + # (D3D-275). The draws need glslangValidator for their GLSL stand-ins of translated shaders. + add_executable(d3d12_typeless_families_test test/d3d12_typeless_families_test.cpp) + target_link_libraries(d3d12_typeless_families_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_typeless_families_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_typeless_families_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_typeless_families COMMAND d3d12_typeless_families_test) + set_tests_properties(d3d12_typeless_families PROPERTIES SKIP_RETURN_CODE 77) + if(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) + foreach(pair "vs_fullscreen.vert;LEONIDA_TYPELESS_VS_SPV;typeless_vs.spv" + "ps_typeless_float.frag;LEONIDA_TYPELESS_PS_FLOAT_SPV;typeless_ps_float.spv" + "ps_typeless_uint.frag;LEONIDA_TYPELESS_PS_UINT_SPV;typeless_ps_uint.spv") + list(GET pair 0 shader) + list(GET pair 1 definition) + list(GET pair 2 name) + set(binary ${CMAKE_CURRENT_BINARY_DIR}/generated/${name}) + add_custom_command(OUTPUT ${binary} + COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${binary} + ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${shader} + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${shader} + COMMENT "Compiling the typeless draw test shader ${shader}" VERBATIM) + target_sources(d3d12_typeless_families_test PRIVATE ${binary}) + target_compile_definitions(d3d12_typeless_families_test PRIVATE ${definition}="${binary}") + endforeach() + else() + message(STATUS "glslangValidator not found: d3d12_typeless_families_test runs its clears only") + endif() + + # Fixed-function state (blend, depth, stencil) swept against the host D3D12 device on the same adapter. Needs + # glslangValidator for the GLSL stand-ins of translated shaders. + if(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) + add_executable(d3d12_state_sweep_test test/d3d12_state_sweep_test.cpp) + target_link_libraries(d3d12_state_sweep_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_state_sweep_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_state_sweep_test PRIVATE /W4 /permissive- /utf-8) + foreach(pair "vs_fullscreen.vert;LEONIDA_SWEEP_VS_SPV;sweep_vs.spv" + "ps_sweep.frag;LEONIDA_SWEEP_PS_SPV;sweep_ps.spv") + list(GET pair 0 shader) + list(GET pair 1 definition) + list(GET pair 2 name) + set(binary ${CMAKE_CURRENT_BINARY_DIR}/generated/${name}) + add_custom_command(OUTPUT ${binary} + COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${binary} + ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${shader} + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${shader} + COMMENT "Compiling the state sweep test shader ${shader}" VERBATIM) + target_sources(d3d12_state_sweep_test PRIVATE ${binary}) + target_compile_definitions(d3d12_state_sweep_test PRIVATE ${definition}="${binary}") + endforeach() + add_test(NAME d3d12_state_sweep COMMAND d3d12_state_sweep_test) + set_tests_properties(d3d12_state_sweep PROPERTIES SKIP_RETURN_CODE 77) + endif() + + # 96-bit R32G32B32 textures (D3D-62): footprints and every copy path against Windows WARP. + add_executable(d3d12_rgb96_test test/d3d12_rgb96_test.cpp) + target_link_libraries(d3d12_rgb96_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_rgb96_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_rgb96_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_rgb96 COMMAND d3d12_rgb96_test) + set_tests_properties(d3d12_rgb96 PROPERTIES SKIP_RETURN_CODE 77) # no Vulkan GPU or no WARP adapter + set_tests_properties(d3d12_typeless_rtv PROPERTIES SKIP_RETURN_CODE 77) + + # Depth/stencil ResolveSubresourceRegion against the host runtime and WARP; run explicitly on a Vulkan GPU. + add_executable(d3d12_depth_resolve_test test/d3d12_depth_resolve_test.cpp) + target_link_libraries(d3d12_depth_resolve_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_depth_resolve_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_depth_resolve_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_depth_resolve COMMAND d3d12_depth_resolve_test) + set_tests_properties(d3d12_depth_resolve PROPERTIES SKIP_RETURN_CODE 77) + # The edge cases (TEST-848) draw with a GLSL stand-in for a translated vertex shader; without glslangValidator + # only the clear cases run. + if(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) + set(binary ${CMAKE_CURRENT_BINARY_DIR}/generated/depth_edge_vs.spv) + add_custom_command(OUTPUT ${binary} + COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${binary} + ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/vs_depth_edge.vert + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/vs_depth_edge.vert + COMMENT "Compiling the depth resolve test shader vs_depth_edge.vert" VERBATIM) + target_sources(d3d12_depth_resolve_test PRIVATE ${binary}) + target_compile_definitions(d3d12_depth_resolve_test PRIVATE LEONIDA_DEPTH_EDGE_VS_SPV="${binary}") + endif() + + # ID3D12Resource::GetDesc against the host runtime and WARP; run explicitly on a Vulkan GPU. + add_executable(d3d12_resource_desc_test test/d3d12_resource_desc_test.cpp) + target_link_libraries(d3d12_resource_desc_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_resource_desc_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_resource_desc_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_resource_desc COMMAND d3d12_resource_desc_test) + set_tests_properties(d3d12_resource_desc PROPERTIES SKIP_RETURN_CODE 77) + + # Typeless depth-stencil textures without ALLOW_DEPTH_STENCIL, copied from a depth buffer, against WARP. + add_executable(d3d12_typeless_depth_test test/d3d12_typeless_depth_test.cpp) + target_link_libraries(d3d12_typeless_depth_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_typeless_depth_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_typeless_depth_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_typeless_depth COMMAND d3d12_typeless_depth_test) + set_tests_properties(d3d12_typeless_depth PROPERTIES SKIP_RETURN_CODE 77) + + # WriteToSubresource/ReadFromSubresource arguments and bytes, compared with the host runtime. + add_executable(d3d12_subresource_copy_test test/d3d12_subresource_copy_test.cpp) + target_link_libraries(d3d12_subresource_copy_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_subresource_copy_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_subresource_copy_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_subresource_copy COMMAND d3d12_subresource_copy_test) + set_tests_properties(d3d12_subresource_copy PROPERTIES SKIP_RETURN_CODE 77) + + # MakeResident, Evict, SetResidencyPriority and EnqueueMakeResident, compared with the host runtime. + add_executable(d3d12_residency_test test/d3d12_residency_test.cpp) + target_link_libraries(d3d12_residency_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_residency_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_residency_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_residency COMMAND d3d12_residency_test) + set_tests_properties(d3d12_residency PROPERTIES SKIP_RETURN_CODE 77) + + # ID3D12Resource::GetHeapProperties for committed, placed and reserved resources, compared with the host runtime. + add_executable(d3d12_heap_properties_test test/d3d12_heap_properties_test.cpp) + target_link_libraries(d3d12_heap_properties_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_heap_properties_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_heap_properties_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_heap_properties COMMAND d3d12_heap_properties_test) + set_tests_properties(d3d12_heap_properties PROPERTIES SKIP_RETURN_CODE 77) + + # CreatePipelineLibrary and ID3D12PipelineLibrary1 arguments, compared with the host runtime. + add_executable(d3d12_pipeline_library_host_test test/d3d12_pipeline_library_host_test.cpp) + target_link_libraries(d3d12_pipeline_library_host_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_pipeline_library_host_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_pipeline_library_host_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_pipeline_library_host COMMAND d3d12_pipeline_library_host_test) + set_tests_properties(d3d12_pipeline_library_host PROPERTIES SKIP_RETURN_CODE 77) + + # Milestone M0: a window, 60 cleared frames presented through the proxy on Vulkan. + add_executable(d3d12_present_test test/d3d12_present_test.cpp) + target_link_libraries(d3d12_present_test PRIVATE gta6rt_d3d12_com user32 gdi32 dxgi) + target_compile_definitions(d3d12_present_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_present_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_present COMMAND d3d12_present_test) + set_tests_properties(d3d12_present PROPERTIES SKIP_RETURN_CODE 77) + + # Per-pipeline --f16-interp-fallback linking (SHADER-378): 16-param VS + colliding PS rendered on Vulkan. + add_executable(d3d12_f16_halves_test test/d3d12_f16_halves_test.cpp shims/d3d12_xs_device.cpp) + target_link_libraries(d3d12_f16_halves_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_f16_halves_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_f16_halves_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_f16_halves COMMAND d3d12_f16_halves_test) + set_tests_properties(d3d12_f16_halves PROPERTIES SKIP_RETURN_CODE 77) + + # PresentX and the frame events on the Vulkan device (shims/xbox_present.h), checked on swapchain pixels. + add_executable(xbox_present_test test/xbox_present_test.cpp) + target_link_libraries(xbox_present_test PRIVATE gta6rt_d3d12_com user32) + target_compile_definitions(xbox_present_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(xbox_present_test PRIVATE /W4 /permissive- /utf-8) + # Needs a Vulkan GPU and a window; exits 77 (skipped) without a Vulkan device. + add_test(NAME xbox_present COMMAND xbox_present_test) + set_tests_properties(xbox_present PROPERTIES SKIP_RETURN_CODE 77) + + # TEST-528: a real boot-movie frame (the package's Bink2Scarlett.dll) uploaded through the Xbox-ABI proxy and + # presented with PresentX, checked against the decoded BGRA. Package-gated like bink_decode_test: skips (77) + # unless LEONIDA_GAME_DIR and LEONIDA_MOVIE are set; no game data is written into the repo. + add_executable(d3d12_boot_movie_test + test/d3d12_boot_movie_test.cpp + src/pe_loader.cpp + shims/registry.cpp + shims/xmem.cpp + ) + target_link_libraries(d3d12_boot_movie_test PRIVATE gta6rt_d3d12_com user32 psapi) + target_compile_definitions(d3d12_boot_movie_test PRIVATE + WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE _CRT_SECURE_NO_WARNINGS) + target_compile_options(d3d12_boot_movie_test PRIVATE /W4 /permissive- /utf-8 /EHsc) + target_link_options(d3d12_boot_movie_test PRIVATE /OPT:NOREF) + add_dependencies(d3d12_boot_movie_test gta6rt_tls_host) + add_test(NAME d3d12_boot_movie COMMAND d3d12_boot_movie_test) + set_tests_properties(d3d12_boot_movie PROPERTIES SKIP_RETURN_CODE 77) + + # First light through D3D12 (docs/first_light.md): the real model and translated VS/PS that tools/first_light.py + # wrote to LEONIDA_FIRST_LIGHT_DIR, drawn through the device proxy. Skips (77) unless that variable is set. + add_executable(d3d12_first_light_test test/d3d12_first_light_test.cpp shims/d3d12_xs_device.cpp) + target_link_libraries(d3d12_first_light_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_first_light_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS) + target_compile_options(d3d12_first_light_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_first_light COMMAND d3d12_first_light_test) + set_tests_properties(d3d12_first_light PROPERTIES SKIP_RETURN_CODE 77) + + # M1.5 (D3D-53): a draw whose VS and PS are translator output. test/shaders/vs_m15.asm and ps_m15.asm are assembled + # with llvm-mc and translated by tools/rdna2spirv.py through test/shaders/build.py, which also writes the FSSM + # programs their index entries are keyed by. Needs llvm-mc with the AMDGPU target (LLVM_MC in the environment, as + # for the other shader tests, or llvm-mc on PATH or in C:/msys64/ucrt64/bin) and the Vulkan SDK's spirv-as and + # spirv-val; without them the test is not built. + if(NOT LEONIDA_LLVM_MC) + if(DEFINED ENV{LLVM_MC}) + set(LEONIDA_LLVM_MC "$ENV{LLVM_MC}") + else() + find_program(LEONIDA_LLVM_MC llvm-mc HINTS "C:/msys64/ucrt64/bin") + endif() + endif() + find_program(LEONIDA_SPIRV_AS spirv-as HINTS "$ENV{VULKAN_SDK}/Bin" "$ENV{VULKAN_SDK}/bin") + find_program(LEONIDA_SPIRV_VAL spirv-val HINTS "$ENV{VULKAN_SDK}/Bin" "$ENV{VULKAN_SDK}/bin") + if(LEONIDA_LLVM_MC AND LEONIDA_SPIRV_AS AND LEONIDA_SPIRV_VAL) + set(LEONIDA_M15_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/m15_shaders) + get_filename_component(LEONIDA_SPIRV_TOOLS_DIR ${LEONIDA_SPIRV_AS} DIRECTORY) + file(TO_NATIVE_PATH "${LEONIDA_SPIRV_TOOLS_DIR}" LEONIDA_SPIRV_TOOLS_NATIVE) + set(LEONIDA_M15_FILES ${LEONIDA_M15_DIR}/spirv/index.json ${LEONIDA_M15_DIR}/fssm/vs_m15.fssm + ${LEONIDA_M15_DIR}/fssm/ps_m15.fssm) + add_custom_command( + OUTPUT ${LEONIDA_M15_FILES} + COMMAND ${CMAKE_COMMAND} -E remove_directory ${LEONIDA_M15_DIR} + COMMAND ${CMAKE_COMMAND} -E env "LLVM_MC=${LEONIDA_LLVM_MC}" "LEONIDA_SPIRV_TOOLS=${LEONIDA_SPIRV_TOOLS_NATIVE}" + $ -I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py + ${LEONIDA_M15_DIR} vs_m15 ps_m15 + DEPENDS ${LEONIDA_TRANSLATOR_DEPS} + ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/vs_m15.asm + ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_m15.asm + COMMENT "Translating vs_m15 and ps_m15 for the translated draw test" + VERBATIM) + add_executable(d3d12_translated_draw_test test/d3d12_translated_draw_test.cpp shims/d3d12_xs_device.cpp + ${LEONIDA_M15_FILES}) + target_link_libraries(d3d12_translated_draw_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_translated_draw_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_M15_DIR="${LEONIDA_M15_DIR}") + target_compile_options(d3d12_translated_draw_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_translated_draw COMMAND d3d12_translated_draw_test) + set_tests_properties(d3d12_translated_draw PROPERTIES SKIP_RETURN_CODE 77) + + # vk_bindless_test (the bindless set and its table at the Vulkan level, no D3D12) takes the translated vs_ids, + # ps_tex and ps_imgatomic; it was only run by scripts/run_gpu_tests.py and check.py until D3D-314 needed it. + set(LEONIDA_BINDLESS_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/bindless_shaders) + set(LEONIDA_BINDLESS_FILES ${LEONIDA_BINDLESS_DIR}/spirv/vs_ids.spv ${LEONIDA_BINDLESS_DIR}/spirv/ps_tex.spv + ${LEONIDA_BINDLESS_DIR}/spirv/ps_imgatomic.spv) + add_custom_command( + OUTPUT ${LEONIDA_BINDLESS_FILES} + COMMAND ${CMAKE_COMMAND} -E remove_directory ${LEONIDA_BINDLESS_DIR} + COMMAND ${CMAKE_COMMAND} -E env "LLVM_MC=${LEONIDA_LLVM_MC}" "LEONIDA_SPIRV_TOOLS=${LEONIDA_SPIRV_TOOLS_NATIVE}" + $ -I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py + ${LEONIDA_BINDLESS_DIR} vs_ids ps_tex ps_imgatomic + DEPENDS ${LEONIDA_TRANSLATOR_DEPS} + ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/vs_ids.asm + ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_tex.asm + ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_imgatomic.asm + COMMENT "Translating vs_ids, ps_tex and ps_imgatomic for vk_bindless_test" + VERBATIM) + add_custom_target(vk_bindless_shaders ALL DEPENDS ${LEONIDA_BINDLESS_FILES}) + add_dependencies(vk_bindless_test vk_bindless_shaders) + add_test(NAME vk_bindless_ps_tex COMMAND vk_bindless_test ${LEONIDA_BINDLESS_DIR}/spirv/vs_ids.spv + ${LEONIDA_BINDLESS_DIR}/spirv/ps_tex.spv) + add_test(NAME vk_bindless_ps_imgatomic COMMAND vk_bindless_test ${LEONIDA_BINDLESS_DIR}/spirv/vs_ids.spv + ${LEONIDA_BINDLESS_DIR}/spirv/ps_imgatomic.spv) + set_tests_properties(vk_bindless_ps_tex vk_bindless_ps_imgatomic PROPERTIES SKIP_RETURN_CODE 77) + + # M2: a textured quad. vs_m2.asm and ps_m2.asm (the PS samples a T#/S# it loads from two descriptor tables) go + # through the same build; the test creates the heaps, the SRV, the sampler and the root signature through the + # D3D12 API only. + set(LEONIDA_M2_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/m2_shaders) + set(LEONIDA_M2_FILES ${LEONIDA_M2_DIR}/spirv/index.json ${LEONIDA_M2_DIR}/fssm/vs_m2.fssm + ${LEONIDA_M2_DIR}/fssm/ps_m2.fssm ${LEONIDA_M2_DIR}/fssm/ps_m2_uoff.fssm + ${LEONIDA_M2_DIR}/fssm/ps_m2_literal.fssm) + add_custom_command( + OUTPUT ${LEONIDA_M2_FILES} + COMMAND ${CMAKE_COMMAND} -E remove_directory ${LEONIDA_M2_DIR} + COMMAND ${CMAKE_COMMAND} -E env "LLVM_MC=${LEONIDA_LLVM_MC}" "LEONIDA_SPIRV_TOOLS=${LEONIDA_SPIRV_TOOLS_NATIVE}" + $ -I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py + ${LEONIDA_M2_DIR} vs_m2 ps_m2 ps_m2_uoff ps_m2_literal + DEPENDS ${LEONIDA_TRANSLATOR_DEPS} + ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/vs_m2.asm + ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_m2.asm + ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_m2_uoff.asm + ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_m2_literal.asm + COMMENT "Translating vs_m2 and ps_m2 for the textured draw test" + VERBATIM) + add_executable(d3d12_m2_textured_test test/d3d12_m2_textured_test.cpp shims/d3d12_xs_device.cpp + ${LEONIDA_M2_FILES}) + target_link_libraries(d3d12_m2_textured_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_m2_textured_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_M2_DIR="${LEONIDA_M2_DIR}") + target_compile_options(d3d12_m2_textured_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_m2_textured COMMAND d3d12_m2_textured_test) + set_tests_properties(d3d12_m2_textured PROPERTIES SKIP_RETURN_CODE 77) + + # M2, formats: BC1 and BC7 textures with mip chains and an R8G8B8A8 2D array through the same descriptor path. + # vs_m2.asm with ps_m2.asm (2D) and ps_m2_array.asm (2D array, slice 1.0 of the view). + set(LEONIDA_M2F_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/m2f_shaders) + set(LEONIDA_M2F_FILES ${LEONIDA_M2F_DIR}/spirv/index.json ${LEONIDA_M2F_DIR}/fssm/vs_m2.fssm + ${LEONIDA_M2F_DIR}/fssm/ps_m2.fssm ${LEONIDA_M2F_DIR}/fssm/ps_m2_array.fssm) + add_custom_command( + OUTPUT ${LEONIDA_M2F_FILES} + COMMAND ${CMAKE_COMMAND} -E remove_directory ${LEONIDA_M2F_DIR} + COMMAND ${CMAKE_COMMAND} -E env "LLVM_MC=${LEONIDA_LLVM_MC}" "LEONIDA_SPIRV_TOOLS=${LEONIDA_SPIRV_TOOLS_NATIVE}" + $ -I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py + ${LEONIDA_M2F_DIR} vs_m2 ps_m2 ps_m2_array + DEPENDS ${LEONIDA_TRANSLATOR_DEPS} + ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/vs_m2.asm + ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_m2.asm + ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_m2_array.asm + COMMENT "Translating vs_m2, ps_m2 and ps_m2_array for the M2 formats test" + VERBATIM) + add_executable(d3d12_m2_formats_test test/d3d12_m2_formats_test.cpp shims/d3d12_xs_device.cpp + ${LEONIDA_M2F_FILES}) + target_link_libraries(d3d12_m2_formats_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_m2_formats_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_M2F_DIR="${LEONIDA_M2F_DIR}") + target_compile_options(d3d12_m2_formats_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_m2_formats COMMAND d3d12_m2_formats_test) + set_tests_properties(d3d12_m2_formats PROPERTIES SKIP_RETURN_CODE 77) + + # M3 (synthetic part): frames with two render targets and a depth/stencil buffer, an occlusion query, resource + # barriers and a second pass that samples the first one's target, three frames in flight with a fence each. + # Pass 1's two-output PS and its single-output occlusion probe go through the same translator build. + set(LEONIDA_M3_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/m3_shaders) + set(LEONIDA_M3_FILES ${LEONIDA_M3_DIR}/spirv/index.json ${LEONIDA_M3_DIR}/fssm/vs_m3.fssm + ${LEONIDA_M3_DIR}/fssm/ps_m3.fssm ${LEONIDA_M3_DIR}/fssm/vs_m2.fssm + ${LEONIDA_M3_DIR}/fssm/ps_m3_post.fssm ${LEONIDA_M3_DIR}/fssm/ps_m3_query.fssm) + add_custom_command( + OUTPUT ${LEONIDA_M3_FILES} + COMMAND ${CMAKE_COMMAND} -E remove_directory ${LEONIDA_M3_DIR} + COMMAND ${CMAKE_COMMAND} -E env "LLVM_MC=${LEONIDA_LLVM_MC}" "LEONIDA_SPIRV_TOOLS=${LEONIDA_SPIRV_TOOLS_NATIVE}" + $ -I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py + ${LEONIDA_M3_DIR} vs_m3 ps_m3 vs_m2 ps_m3_post ps_m3_query + DEPENDS ${LEONIDA_TRANSLATOR_DEPS} + ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/vs_m3.asm + ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_m3.asm + ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/vs_m2.asm + ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_m3_post.asm + ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_m3_query.asm + COMMENT "Translating M3 frame and single-output occlusion-probe shaders" + VERBATIM) + add_executable(d3d12_m3_frame_test test/d3d12_m3_frame_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_M3_FILES}) + target_link_libraries(d3d12_m3_frame_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_m3_frame_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_M3_DIR="${LEONIDA_M3_DIR}") + target_compile_options(d3d12_m3_frame_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_m3_frame COMMAND d3d12_m3_frame_test) + add_test(NAME d3d12_m3_first_pass COMMAND d3d12_m3_frame_test --first-pass-only) + set_tests_properties(d3d12_m3_frame d3d12_m3_first_pass PROPERTIES SKIP_RETURN_CODE 77) + + # M4 (synthetic part): compute PSOs, a UAV table (structured and raw buffers, an R32_UINT storage image), an indirect + # dispatch from arguments a first dispatch wrote, and a copy queue that streams the input in and reads the results + # back across queue fences. cs_m4_fill.asm and cs_m4_indirect.asm go through the same build; build.py publishes + # their synthetic FSSM programs (the compute header and the words their "fssm-data" comments give), which the + # test wraps in shader containers. + set(LEONIDA_M4_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/m4_shaders) + set(LEONIDA_M4_FILES ${LEONIDA_M4_DIR}/spirv/index.json ${LEONIDA_M4_DIR}/fssm/cs_m4_fill.fssm + ${LEONIDA_M4_DIR}/fssm/cs_m4_indirect.fssm) + add_custom_command( + OUTPUT ${LEONIDA_M4_FILES} + COMMAND ${CMAKE_COMMAND} -E remove_directory ${LEONIDA_M4_DIR} + # LEONIDA_USER_DATA_SHIFT=4: the fixtures read their user data from s0; a D3D12 compute PSO gets its root + # arguments from s4 (rt::rootsig::pack_stage, D3D-448), so they are built with every SGPR 4 higher. + COMMAND ${CMAKE_COMMAND} -E env "LLVM_MC=${LEONIDA_LLVM_MC}" "LEONIDA_SPIRV_TOOLS=${LEONIDA_SPIRV_TOOLS_NATIVE}" + LEONIDA_USER_DATA_SHIFT=4 + $ -I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py + ${LEONIDA_M4_DIR} cs_m4_fill cs_m4_indirect + DEPENDS ${LEONIDA_TRANSLATOR_DEPS} + ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/cs_m4_fill.asm + ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/cs_m4_indirect.asm + COMMENT "Translating cs_m4_fill and cs_m4_indirect for the compute test" + VERBATIM) + add_executable(d3d12_m4_compute_test test/d3d12_m4_compute_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_M4_FILES}) + target_link_libraries(d3d12_m4_compute_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_m4_compute_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_M4_DIR="${LEONIDA_M4_DIR}") + target_compile_options(d3d12_m4_compute_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_m4_compute COMMAND d3d12_m4_compute_test) + set_tests_properties(d3d12_m4_compute PROPERTIES SKIP_RETURN_CODE 77) + + # Typed buffer UAVs and UAV counters: cs_buf_typed.asm writes typed views through V#s with a FORMAT, and + # cs_buf_counter.asm appends to and consumes from a structured view whose counter is the second V# of its slot; + # the test also compares typed-buffer and counter clears with the host runtime on the layer's adapter. + set(LEONIDA_BUFFER_UAV_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/buffer_uav_shaders) + set(LEONIDA_BUFFER_UAV_FILES ${LEONIDA_BUFFER_UAV_DIR}/spirv/index.json + ${LEONIDA_BUFFER_UAV_DIR}/fssm/cs_buf_typed.fssm + ${LEONIDA_BUFFER_UAV_DIR}/fssm/cs_buf_counter.fssm) + add_custom_command( + OUTPUT ${LEONIDA_BUFFER_UAV_FILES} + COMMAND ${CMAKE_COMMAND} -E remove_directory ${LEONIDA_BUFFER_UAV_DIR} + # LEONIDA_USER_DATA_SHIFT=4: root arguments from s4 in a D3D12 compute PSO (see the M4 shaders above). + COMMAND ${CMAKE_COMMAND} -E env "LLVM_MC=${LEONIDA_LLVM_MC}" "LEONIDA_SPIRV_TOOLS=${LEONIDA_SPIRV_TOOLS_NATIVE}" + LEONIDA_USER_DATA_SHIFT=4 + $ -I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py + ${LEONIDA_BUFFER_UAV_DIR} cs_buf_typed cs_buf_counter + DEPENDS ${LEONIDA_TRANSLATOR_DEPS} + ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/cs_buf_typed.asm + ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/cs_buf_counter.asm + COMMENT "Translating cs_buf_typed and cs_buf_counter for the buffer UAV test" + VERBATIM) + add_executable(d3d12_buffer_uav_test test/d3d12_buffer_uav_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_BUFFER_UAV_FILES}) + target_link_libraries(d3d12_buffer_uav_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_buffer_uav_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_BUFFER_UAV_DIR="${LEONIDA_BUFFER_UAV_DIR}") + target_compile_options(d3d12_buffer_uav_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_buffer_uav COMMAND d3d12_buffer_uav_test) + set_tests_properties(d3d12_buffer_uav PROPERTIES SKIP_RETURN_CODE 77) + else() + message(STATUS "llvm-mc (set LLVM_MC) or the SDK's spirv-as/spirv-val not found: d3d12_translated_draw_test, d3d12_m2_textured_test, d3d12_m2_formats_test, d3d12_m3_frame_test, d3d12_m4_compute_test and d3d12_buffer_uav_test are not built") + endif() + # ID3D12Resource::GetHeapProperties and ID3D12DescriptorHeap::GetDesc (node masks, resolved heap flags) against the + # host runtime and WARP; run explicitly on a Vulkan GPU. + add_executable(d3d12_node_mask_test test/d3d12_node_mask_test.cpp) + target_link_libraries(d3d12_node_mask_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_node_mask_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_node_mask_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_node_mask COMMAND d3d12_node_mask_test) + + # Console Xbox CreateDescriptorHeap extended ABI (issue #313 comment 7107265058): the title passes address/size + # after the PC desc and expects GetCPU/GPUDescriptorHandleForHeapStart() == address. Synthetic test; no title-memory + # aliasing / §3.3 backing coverage. + add_executable(d3d12_console_descriptor_heap_test test/d3d12_console_descriptor_heap_test.cpp shims/d3d12_xs_device.cpp) + target_link_libraries(d3d12_console_descriptor_heap_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_console_descriptor_heap_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_console_descriptor_heap_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_console_descriptor_heap COMMAND d3d12_console_descriptor_heap_test) + set_tests_properties(d3d12_console_descriptor_heap PROPERTIES SKIP_RETURN_CODE 77) + add_executable(d3d12_indirect_zero_test test/d3d12_indirect_zero_test.cpp) + target_link_libraries(d3d12_indirect_zero_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_indirect_zero_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_indirect_zero_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_indirect_zero COMMAND d3d12_indirect_zero_test) + set_tests_properties(d3d12_indirect_zero PROPERTIES SKIP_RETURN_CODE 77) + set_tests_properties(d3d12_node_mask PROPERTIES SKIP_RETURN_CODE 77) + set_tests_properties(d3d12_indirect_zero PROPERTIES SKIP_RETURN_CODE 77) + + # CopyResource / CopyTextureRegion between BC and its uncompressed equivalent (and depth <-> colour) against the + # host runtime and WARP; run explicitly on a Vulkan GPU. + add_executable(d3d12_copy_xfmt_test test/d3d12_copy_xfmt_test.cpp) + target_link_libraries(d3d12_copy_xfmt_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_copy_xfmt_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_copy_xfmt_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_copy_xfmt COMMAND d3d12_copy_xfmt_test) + set_tests_properties(d3d12_copy_xfmt PROPERTIES SKIP_RETURN_CODE 77) + + add_executable(d3d12_stencil_copy_test test/d3d12_stencil_copy_test.cpp) + target_link_libraries(d3d12_stencil_copy_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_stencil_copy_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_stencil_copy_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_stencil_copy COMMAND d3d12_stencil_copy_test) + set_tests_properties(d3d12_stencil_copy PROPERTIES SKIP_RETURN_CODE 77 + ENVIRONMENT "LEONIDA_HOST_ADAPTER=warp") + + # Query heaps and query calls by list type (Close results, CreateQueryHeap node masks, timestamp heap kinds) + # against the host runtime and WARP; run explicitly on a Vulkan GPU. + add_executable(d3d12_query_rules_test test/d3d12_query_rules_test.cpp) + target_link_libraries(d3d12_query_rules_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_query_rules_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_query_rules_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_query_rules COMMAND d3d12_query_rules_test) + set_tests_properties(d3d12_query_rules PROPERTIES SKIP_RETURN_CODE 77) + + # Vulkan-backed IDXGIFactory4 / IDXGISwapChain3 presentation over a Win32 HWND. + add_executable(dxgi_swapchain_test test/dxgi_swapchain_test.cpp) + target_link_libraries(dxgi_swapchain_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(dxgi_swapchain_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(dxgi_swapchain_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME dxgi_swapchain COMMAND dxgi_swapchain_test) + set_tests_properties(dxgi_swapchain PROPERTIES SKIP_RETURN_CODE 77) + + # The layer's DXGI against the host runtime's (hardware adapter, or WARP with PROBE_WARP=1): IDXGIAdapter4, + # GetRestrictToOutput without an output, ResizeBuffers flag bits and null out-pointers. + add_executable(dxgi_host_parity_test test/dxgi_host_parity_test.cpp) + target_link_libraries(dxgi_host_parity_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(dxgi_host_parity_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(dxgi_host_parity_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME dxgi_host_parity COMMAND dxgi_host_parity_test) + set_tests_properties(dxgi_host_parity PROPERTIES SKIP_RETURN_CODE 77) + + # Host-parity test for DXGI waitable swap chain frame-latency semaphore behavior. + add_executable(dxgi_waitable_latency_test test/dxgi_waitable_latency_test.cpp) + target_link_libraries(dxgi_waitable_latency_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(dxgi_waitable_latency_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(dxgi_waitable_latency_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME dxgi_waitable_latency COMMAND dxgi_waitable_latency_test) + set_tests_properties(dxgi_waitable_latency PROPERTIES + SKIP_RETURN_CODE 77 + FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") + + # Synthetic (no GPU): VulkanSwapchain's DXGI BufferCount contract when Vulkan returns more images than the + # app asked for, or the surface minimum exceeds the request (D3D-389). + add_executable(dxgi_swapchain_count_test test/dxgi_swapchain_count_test.cpp) + target_link_libraries(dxgi_swapchain_count_test PRIVATE Vulkan::Headers) + target_compile_definitions(dxgi_swapchain_count_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(dxgi_swapchain_count_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME dxgi_swapchain_count COMMAND dxgi_swapchain_count_test) + + # ExecuteIndirect with CountBuffer (vkCmdDrawIndirectCount) + optional BLAS/TLAS/RayQueryKHR GPU test. + add_executable(d3d12_indirect_rt_test test/d3d12_indirect_rt_test.cpp) + target_link_libraries(d3d12_indirect_rt_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_indirect_rt_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_indirect_rt_test PRIVATE /W4 /permissive- /utf-8) + if(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) + set(LEONIDA_TEST_VS_TRI ${CMAKE_CURRENT_BINARY_DIR}/generated/vs_tri.spv) + set(LEONIDA_TEST_FS_SOLID ${CMAKE_CURRENT_BINARY_DIR}/generated/fs_solid.spv) + set(LEONIDA_TEST_CS_RAYQUERY ${CMAKE_CURRENT_BINARY_DIR}/generated/cs_rayquery.spv) + add_custom_command( + OUTPUT ${LEONIDA_TEST_VS_TRI} + COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${LEONIDA_TEST_VS_TRI} + ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/vs_tri.vert + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/vs_tri.vert + COMMENT "Compiling vs_tri.vert" + VERBATIM) + add_custom_command( + OUTPUT ${LEONIDA_TEST_FS_SOLID} + COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${LEONIDA_TEST_FS_SOLID} + ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/fs_solid.frag + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/fs_solid.frag + COMMENT "Compiling fs_solid.frag" + VERBATIM) + add_custom_command( + OUTPUT ${LEONIDA_TEST_CS_RAYQUERY} + COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${LEONIDA_TEST_CS_RAYQUERY} + ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_rayquery.comp + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_rayquery.comp + COMMENT "Compiling cs_rayquery.comp" + VERBATIM) + target_sources(d3d12_indirect_rt_test PRIVATE + ${LEONIDA_TEST_VS_TRI} ${LEONIDA_TEST_FS_SOLID} ${LEONIDA_TEST_CS_RAYQUERY}) + target_compile_definitions(d3d12_indirect_rt_test PRIVATE + LEONIDA_TEST_VS_TRI_SPV="${LEONIDA_TEST_VS_TRI}" + LEONIDA_TEST_FS_SOLID_SPV="${LEONIDA_TEST_FS_SOLID}" + LEONIDA_TEST_CS_RAYQUERY_SPV="${LEONIDA_TEST_CS_RAYQUERY}") + endif() + add_test(NAME d3d12_indirect_rt COMMAND d3d12_indirect_rt_test) + set_tests_properties(d3d12_indirect_rt PROPERTIES SKIP_RETURN_CODE 77) + # Upload heaps in system memory, as on a GPU without Resizable BAR: their VAs can lie below the arena and wrap. + add_test(NAME d3d12_indirect_rt_upload_sysmem COMMAND d3d12_indirect_rt_test) + set_tests_properties(d3d12_indirect_rt_upload_sysmem PROPERTIES SKIP_RETURN_CODE 77 + ENVIRONMENT "LEONIDA_UPLOAD_SYSMEM=1") + + # The compute path: root signature, compute PSO from a translator-style index, root arguments, dispatch. Its + # shader is GLSL written to the translator's push-constant/address contract, compiled here. + if(NOT Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) + find_program(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE glslangValidator HINTS "$ENV{VULKAN_SDK}/Bin" "$ENV{VULKAN_SDK}/bin") + endif() + if(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) + set(LEONIDA_TEST_CS ${CMAKE_CURRENT_BINARY_DIR}/generated/cs_user_data.spv) + add_custom_command( + OUTPUT ${LEONIDA_TEST_CS} + COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${LEONIDA_TEST_CS} + ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_user_data.comp + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_user_data.comp + COMMENT "Compiling the compute test shader" + VERBATIM) + add_executable(d3d12_compute_test test/d3d12_compute_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_TEST_CS}) + target_link_libraries(d3d12_compute_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_compute_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_CS_SPV="${LEONIDA_TEST_CS}") + target_compile_options(d3d12_compute_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_compute COMMAND d3d12_compute_test) + set_tests_properties(d3d12_compute PROPERTIES SKIP_RETURN_CODE 77) + # Compute PSOs from FSPX programs (docs/fspx.md): an ACCC container at slot 62 and a bare kind-6 program. + add_executable(d3d12_fspx_compute_test test/d3d12_fspx_compute_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_TEST_CS}) + target_link_libraries(d3d12_fspx_compute_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_fspx_compute_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_CS_SPV="${LEONIDA_TEST_CS}") + target_compile_options(d3d12_fspx_compute_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_fspx_compute COMMAND d3d12_fspx_compute_test) + set_tests_properties(d3d12_fspx_compute PROPERTIES SKIP_RETURN_CODE 77) + # Milestone M1: a VS+PS pipeline and indexed draws, shaders written to the same contract. + set(LEONIDA_TEST_VS ${CMAKE_CURRENT_BINARY_DIR}/generated/vs_draw.spv) + set(LEONIDA_TEST_PS ${CMAKE_CURRENT_BINARY_DIR}/generated/ps_draw.spv) + set(LEONIDA_TEST_PS_UINT ${CMAKE_CURRENT_BINARY_DIR}/generated/ps_draw_uint.spv) + set(LEONIDA_TEST_VS_FULLSCREEN ${CMAKE_CURRENT_BINARY_DIR}/generated/vs_fullscreen.spv) + set(LEONIDA_TEST_VS_INT ${CMAKE_CURRENT_BINARY_DIR}/generated/vs_draw_int.spv) + set(LEONIDA_TEST_GS_DOUBLE ${CMAKE_CURRENT_BINARY_DIR}/generated/gs_double.spv) + foreach(pair "vs_draw.vert;${LEONIDA_TEST_VS}" "ps_draw.frag;${LEONIDA_TEST_PS}" + "ps_draw_uint.frag;${LEONIDA_TEST_PS_UINT}" "vs_fullscreen.vert;${LEONIDA_TEST_VS_FULLSCREEN}" "vs_draw_int.vert;${LEONIDA_TEST_VS_INT}" + "gs_double.geom;${LEONIDA_TEST_GS_DOUBLE}") + list(GET pair 0 source) + list(GET pair 1 output) + add_custom_command( + OUTPUT ${output} + COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${output} + ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${source} + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${source} + COMMENT "Compiling the draw test shader ${source}" + VERBATIM) + endforeach() + add_executable(d3d12_draw_test test/d3d12_draw_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_TEST_VS} + ${LEONIDA_TEST_PS} ${LEONIDA_TEST_PS_UINT} ${LEONIDA_TEST_VS_FULLSCREEN} ${LEONIDA_TEST_VS_INT}) + target_link_libraries(d3d12_draw_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_draw_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_VS_SPV="${LEONIDA_TEST_VS}" LEONIDA_TEST_PS_SPV="${LEONIDA_TEST_PS}" + LEONIDA_TEST_PS_UINT_SPV="${LEONIDA_TEST_PS_UINT}" + LEONIDA_TEST_VS_FULLSCREEN_SPV="${LEONIDA_TEST_VS_FULLSCREEN}" + LEONIDA_TEST_VS_INT_SPV="${LEONIDA_TEST_VS_INT}") + target_compile_options(d3d12_draw_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_draw COMMAND d3d12_draw_test) + set_tests_properties(d3d12_draw PROPERTIES SKIP_RETURN_CODE 77) + # Graphics & compute PSO descriptor validation parity against live Windows D3D12 (WARP and HW). + add_executable(d3d12_pso_validation_test test/d3d12_pso_validation_test.cpp ${LEONIDA_TEST_VS} + ${LEONIDA_TEST_PS} ${LEONIDA_TEST_PS_UINT} ${LEONIDA_TEST_VS_FULLSCREEN} ${LEONIDA_TEST_CS}) + target_link_libraries(d3d12_pso_validation_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_pso_validation_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_VS_SPV="${LEONIDA_TEST_VS}" LEONIDA_TEST_PS_SPV="${LEONIDA_TEST_PS}" + LEONIDA_TEST_PS_UINT_SPV="${LEONIDA_TEST_PS_UINT}" + LEONIDA_TEST_VS_FULLSCREEN_SPV="${LEONIDA_TEST_VS_FULLSCREEN}" + LEONIDA_TEST_CS_SPV="${LEONIDA_TEST_CS}") + target_compile_options(d3d12_pso_validation_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_pso_validation COMMAND d3d12_pso_validation_test) + set_tests_properties(d3d12_pso_validation PROPERTIES SKIP_RETURN_CODE 77 + FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") + # Conservative raster Tier 1, with geometric coverage bounds and host D3D12 references. + set(LEONIDA_CONSERVATIVE_VS ${CMAKE_CURRENT_BINARY_DIR}/generated/vs_conservative.spv) + set(LEONIDA_CONSERVATIVE_PS ${CMAKE_CURRENT_BINARY_DIR}/generated/ps_conservative.spv) + foreach(pair "vs_conservative.vert;${LEONIDA_CONSERVATIVE_VS}" "ps_conservative.frag;${LEONIDA_CONSERVATIVE_PS}") + list(GET pair 0 source) + list(GET pair 1 output) + add_custom_command(OUTPUT ${output} + COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${output} + ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${source} + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${source} VERBATIM) + endforeach() + add_executable(d3d12_conservative_raster_test test/d3d12_conservative_raster_test.cpp + ${LEONIDA_CONSERVATIVE_VS} ${LEONIDA_CONSERVATIVE_PS}) + target_link_libraries(d3d12_conservative_raster_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_conservative_raster_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_CONSERVATIVE_VS="${LEONIDA_CONSERVATIVE_VS}" LEONIDA_CONSERVATIVE_PS="${LEONIDA_CONSERVATIVE_PS}") + target_compile_options(d3d12_conservative_raster_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_conservative_raster COMMAND d3d12_conservative_raster_test) + set_tests_properties(d3d12_conservative_raster PROPERTIES SKIP_RETURN_CODE 77 + ENVIRONMENT "LEONIDA_HOST_ADAPTER=warp") + set(LEONIDA_CONSERVATIVE_TIER2_VS ${CMAKE_CURRENT_BINARY_DIR}/generated/vs_conservative_tier2.spv) + set(LEONIDA_CONSERVATIVE_TIER2_PS ${CMAKE_CURRENT_BINARY_DIR}/generated/ps_conservative_tier2.spv) + foreach(pair "vs_conservative_tier2.vert;${LEONIDA_CONSERVATIVE_TIER2_VS}" "ps_conservative_tier2.frag;${LEONIDA_CONSERVATIVE_TIER2_PS}") + list(GET pair 0 source) + list(GET pair 1 output) + add_custom_command(OUTPUT ${output} + COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${output} + ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${source} + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${source} VERBATIM) + endforeach() + add_executable(d3d12_conservative_tier2_test test/d3d12_conservative_tier2_test.cpp + ${LEONIDA_CONSERVATIVE_TIER2_VS} ${LEONIDA_CONSERVATIVE_TIER2_PS}) + target_link_libraries(d3d12_conservative_tier2_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_conservative_tier2_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_CONSERVATIVE_TIER2_VS="${LEONIDA_CONSERVATIVE_TIER2_VS}" LEONIDA_CONSERVATIVE_TIER2_PS="${LEONIDA_CONSERVATIVE_TIER2_PS}") + target_compile_options(d3d12_conservative_tier2_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_conservative_tier2 COMMAND d3d12_conservative_tier2_test) + set_tests_properties(d3d12_conservative_tier2 PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_HOST_ADAPTER=warp") + set(LEONIDA_CONSERVATIVE_TIER3_PS ${CMAKE_CURRENT_BINARY_DIR}/generated/ps_conservative_tier3.spv) + add_custom_command(OUTPUT ${LEONIDA_CONSERVATIVE_TIER3_PS} + COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${LEONIDA_CONSERVATIVE_TIER3_PS} + ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/ps_conservative_tier3.frag + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/ps_conservative_tier3.frag VERBATIM) + add_executable(d3d12_conservative_tier3_test test/d3d12_conservative_tier3_test.cpp + ${LEONIDA_CONSERVATIVE_VS} ${LEONIDA_CONSERVATIVE_TIER3_PS}) + target_link_libraries(d3d12_conservative_tier3_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_conservative_tier3_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_CONSERVATIVE_VS="${LEONIDA_CONSERVATIVE_VS}" + LEONIDA_CONSERVATIVE_TIER3_PS="${LEONIDA_CONSERVATIVE_TIER3_PS}") + target_compile_options(d3d12_conservative_tier3_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME inner_coverage_oracle COMMAND d3d12_conservative_tier3_test --oracle-only) + add_test(NAME d3d12_inner_coverage_guards COMMAND d3d12_conservative_tier3_test --guards-only) + add_test(NAME d3d12_inner_coverage_native COMMAND d3d12_conservative_tier3_test --native-only) + add_test(NAME d3d12_conservative_tier3 COMMAND d3d12_conservative_tier3_test) + set_tests_properties(d3d12_inner_coverage_guards d3d12_inner_coverage_native d3d12_conservative_tier3 + PROPERTIES SKIP_RETURN_CODE 77) + add_executable(d3d12_msaa_draw_test test/d3d12_msaa_draw_test.cpp shims/d3d12_xs_device.cpp + ${LEONIDA_TEST_VS} ${LEONIDA_TEST_PS}) + target_link_libraries(d3d12_msaa_draw_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_msaa_draw_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_VS_SPV="${LEONIDA_TEST_VS}" LEONIDA_TEST_PS_SPV="${LEONIDA_TEST_PS}") + target_compile_options(d3d12_msaa_draw_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_msaa_draw COMMAND d3d12_msaa_draw_test) + set_tests_properties(d3d12_msaa_draw PROPERTIES SKIP_RETURN_CODE 77) + # Geometry shaders: a VS+GS+PS pipeline whose GS emits each triangle twice. + add_executable(d3d12_geometry_test test/d3d12_geometry_test.cpp shims/d3d12_xs_device.cpp + ${LEONIDA_TEST_VS} ${LEONIDA_TEST_GS_DOUBLE} ${LEONIDA_TEST_PS}) + target_link_libraries(d3d12_geometry_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_geometry_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_VS_SPV="${LEONIDA_TEST_VS}" LEONIDA_TEST_GS_SPV="${LEONIDA_TEST_GS_DOUBLE}" + LEONIDA_TEST_PS_SPV="${LEONIDA_TEST_PS}") + target_compile_options(d3d12_geometry_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_geometry COMMAND d3d12_geometry_test) + set_tests_properties(d3d12_geometry PROPERTIES SKIP_RETURN_CODE 77) + # D3D-309: D24 depth bias and 24-bit depth in draws, with and without a pixel shader and with a geometry shader + # (src/depth24_fragment.h). + set(LEONIDA_TEST_VS_DEPTH ${CMAKE_CURRENT_BINARY_DIR}/generated/vs_depth.spv) + set(LEONIDA_TEST_PS_DEPTH_EMPTY ${CMAKE_CURRENT_BINARY_DIR}/generated/ps_depth_empty.spv) + set(LEONIDA_TEST_PS_DEPTH_WRITE ${CMAKE_CURRENT_BINARY_DIR}/generated/ps_depth_write.spv) + set(LEONIDA_TEST_GS_DEPTH ${CMAKE_CURRENT_BINARY_DIR}/generated/gs_depth.spv) + foreach(pair "vs_depth.vert;${LEONIDA_TEST_VS_DEPTH}" "ps_depth_empty.frag;${LEONIDA_TEST_PS_DEPTH_EMPTY}" + "ps_depth_write.frag;${LEONIDA_TEST_PS_DEPTH_WRITE}" "gs_depth.geom;${LEONIDA_TEST_GS_DEPTH}") + list(GET pair 0 source) + list(GET pair 1 output) + add_custom_command( + OUTPUT ${output} + COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${output} + ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${source} + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${source} + COMMENT "Compiling the D24 draw test shader ${source}" + VERBATIM) + endforeach() + add_executable(d3d12_depth24_draw_test test/d3d12_depth24_draw_test.cpp shims/d3d12_xs_device.cpp + ${LEONIDA_TEST_VS_DEPTH} ${LEONIDA_TEST_PS_DEPTH_EMPTY} ${LEONIDA_TEST_PS_DEPTH_WRITE} + ${LEONIDA_TEST_GS_DEPTH}) + target_link_libraries(d3d12_depth24_draw_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_depth24_draw_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_VS_DEPTH_SPV="${LEONIDA_TEST_VS_DEPTH}" + LEONIDA_TEST_PS_DEPTH_EMPTY_SPV="${LEONIDA_TEST_PS_DEPTH_EMPTY}" + LEONIDA_TEST_PS_DEPTH_WRITE_SPV="${LEONIDA_TEST_PS_DEPTH_WRITE}" + LEONIDA_TEST_GS_DEPTH_SPV="${LEONIDA_TEST_GS_DEPTH}") + target_compile_options(d3d12_depth24_draw_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_depth24_draw COMMAND d3d12_depth24_draw_test) + set_tests_properties(d3d12_depth24_draw PROPERTIES SKIP_RETURN_CODE 77) + # Set 0 from the compute bind point: a compute PSO whose shader declares set-0 bindings samples through the + # device's bindless set, which nothing but the layer binds. + set(LEONIDA_TEST_CS_SET0_SAMPLE ${CMAKE_CURRENT_BINARY_DIR}/generated/cs_set0_sample.spv) + add_custom_command( + OUTPUT ${LEONIDA_TEST_CS_SET0_SAMPLE} + COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${LEONIDA_TEST_CS_SET0_SAMPLE} + ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_set0_sample.comp + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_set0_sample.comp + COMMENT "Compiling the set-0 compute test shader" + VERBATIM) + add_executable(d3d12_set0_compute_test test/d3d12_set0_compute_test.cpp shims/d3d12_xs_device.cpp + ${LEONIDA_TEST_CS_SET0_SAMPLE}) + target_link_libraries(d3d12_set0_compute_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_set0_compute_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_CS_SET0_SAMPLE_SPV="${LEONIDA_TEST_CS_SET0_SAMPLE}") + target_compile_options(d3d12_set0_compute_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_set0_compute COMMAND d3d12_set0_compute_test) + set_tests_properties(d3d12_set0_compute PROPERTIES SKIP_RETURN_CODE 77) + # Bindless table churn on a direct and a compute queue: the table grows and live keys move without a + # device-idle wait (D3D-314); the same shader, run twice (deferred retirement, and the old wait for timing). + add_executable(d3d12_bindless_churn_test test/d3d12_bindless_churn_test.cpp shims/d3d12_xs_device.cpp + ${LEONIDA_TEST_CS_SET0_SAMPLE}) + target_link_libraries(d3d12_bindless_churn_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_bindless_churn_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_CS_SET0_SAMPLE_SPV="${LEONIDA_TEST_CS_SET0_SAMPLE}") + target_compile_options(d3d12_bindless_churn_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_bindless_churn COMMAND d3d12_bindless_churn_test) + set_tests_properties(d3d12_bindless_churn PROPERTIES SKIP_RETURN_CODE 77) + add_test(NAME d3d12_bindless_churn_validated COMMAND d3d12_bindless_churn_test --validated) + set_tests_properties(d3d12_bindless_churn_validated PROPERTIES SKIP_RETURN_CODE 77) + add_executable(d3d12_pipeline_library_test test/d3d12_pipeline_library_test.cpp + ${LEONIDA_TEST_CS} ${LEONIDA_TEST_VS} ${LEONIDA_TEST_PS}) + target_link_libraries(d3d12_pipeline_library_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_pipeline_library_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_CS_SPV="${LEONIDA_TEST_CS}" + LEONIDA_TEST_VS_SPV="${LEONIDA_TEST_VS}" + LEONIDA_TEST_PS_SPV="${LEONIDA_TEST_PS}") + target_compile_options(d3d12_pipeline_library_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_pipeline_library COMMAND d3d12_pipeline_library_test) + set_tests_properties(d3d12_pipeline_library PROPERTIES SKIP_RETURN_CODE 77) + # ExecuteBundle: what a bundle's draws inherit and hand back, against the host runtime and WARP. + add_executable(d3d12_bundle_test test/d3d12_bundle_test.cpp ${LEONIDA_TEST_VS} ${LEONIDA_TEST_PS}) + target_link_libraries(d3d12_bundle_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_bundle_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS + LEONIDA_TEST_VS_SPV="${LEONIDA_TEST_VS}" LEONIDA_TEST_PS_SPV="${LEONIDA_TEST_PS}") + target_compile_options(d3d12_bundle_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_bundle COMMAND d3d12_bundle_test) + set_tests_properties(d3d12_bundle PROPERTIES SKIP_RETURN_CODE 77) + # Calls a bundle may not make, Close of the bundle and of its parent, against the host runtime and WARP. + add_executable(d3d12_bundle_forbidden_test test/d3d12_bundle_forbidden_test.cpp) + target_link_libraries(d3d12_bundle_forbidden_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_bundle_forbidden_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_bundle_forbidden_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_bundle_forbidden COMMAND d3d12_bundle_forbidden_test) + set_tests_properties(d3d12_bundle_forbidden PROPERTIES SKIP_RETURN_CODE 77) + # A pixel shader with a writable storage image (an image atomic) needs fragmentStoresAndAtomics: refused on a + # device without it, created on the runtime's own device, under the validation layer where it is installed. + set(LEONIDA_TEST_PS_ATOMIC ${CMAKE_CURRENT_BINARY_DIR}/generated/ps_image_atomic.spv) + add_custom_command( + OUTPUT ${LEONIDA_TEST_PS_ATOMIC} + COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${LEONIDA_TEST_PS_ATOMIC} + ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/ps_image_atomic.frag + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/ps_image_atomic.frag + COMMENT "Compiling the stores-and-atomics test shader ps_image_atomic.frag" + VERBATIM) + add_executable(d3d12_stores_atomics_test test/d3d12_stores_atomics_test.cpp ${LEONIDA_TEST_VS_FULLSCREEN} + ${LEONIDA_TEST_PS} ${LEONIDA_TEST_PS_ATOMIC}) + target_link_libraries(d3d12_stores_atomics_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_stores_atomics_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_VS_FULLSCREEN_SPV="${LEONIDA_TEST_VS_FULLSCREEN}" + LEONIDA_TEST_PS_SPV="${LEONIDA_TEST_PS}" + LEONIDA_TEST_PS_ATOMIC_SPV="${LEONIDA_TEST_PS_ATOMIC}") + target_compile_options(d3d12_stores_atomics_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_stores_atomics COMMAND d3d12_stores_atomics_test) + set_tests_properties(d3d12_stores_atomics PROPERTIES SKIP_RETURN_CODE 77) + + # D3D-29: mesh-shader PSOs from pipeline state streams and DispatchMesh (skips without VK_EXT_mesh_shader). + set(LEONIDA_TEST_MS ${CMAKE_CURRENT_BINARY_DIR}/generated/ms_draw.spv) + add_custom_command( + OUTPUT ${LEONIDA_TEST_MS} + # Vulkan 1.2 (SPIR-V 1.5), the translator's target: 1.3 would emit LocalSizeId, which needs maintenance4. + COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.2 -o ${LEONIDA_TEST_MS} + ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/ms_draw.mesh + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/ms_draw.mesh + COMMENT "Compiling the mesh test shader ms_draw.mesh" + VERBATIM) + add_executable(d3d12_mesh_test test/d3d12_mesh_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_TEST_MS} + ${LEONIDA_TEST_PS} ${LEONIDA_TEST_VS_FULLSCREEN}) + target_link_libraries(d3d12_mesh_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_mesh_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_MS_SPV="${LEONIDA_TEST_MS}" LEONIDA_TEST_PS_SPV="${LEONIDA_TEST_PS}" + LEONIDA_TEST_VS_FULLSCREEN_SPV="${LEONIDA_TEST_VS_FULLSCREEN}") + target_compile_options(d3d12_mesh_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_mesh COMMAND d3d12_mesh_test) + set_tests_properties(d3d12_mesh PROPERTIES SKIP_RETURN_CODE 77) + else() + message(STATUS "glslangValidator not found: d3d12_compute_test, d3d12_draw_test, d3d12_set0_compute_test and d3d12_mesh_test are not built") + endif() + + # Native D3D12 SV_InnerCoverage reference; its HLSL is compiled at runtime, so glslang is not needed. + add_executable(d3d12_conservative_tier3_reference_test test/d3d12_conservative_tier3_reference_test.cpp) + target_link_libraries(d3d12_conservative_tier3_reference_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_conservative_tier3_reference_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_conservative_tier3_reference_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_conservative_tier3_reference COMMAND d3d12_conservative_tier3_reference_test) + set_tests_properties(d3d12_conservative_tier3_reference PROPERTIES SKIP_RETURN_CODE 77) + + # Subgroup size control in PSOs, end to end: runtime/test/shaders/cs_w64x_readlane.asm translated natively and with + # --wave64-emulate, and cs_wqm_w32.asm, built here with tools/rdna2spirv.py through test/shaders/build.py. Needs + # llvm-mc with the AMDGPU target (LLVM_MC in the environment, as for the other shader tests, or llvm-mc on PATH) + # and the Vulkan SDK's spirv tools; without them the test is not built. + if(DEFINED ENV{LLVM_MC}) + set(LEONIDA_LLVM_MC "$ENV{LLVM_MC}") + else() + find_program(LEONIDA_LLVM_MC llvm-mc HINTS "C:/msys64/ucrt64/bin") + endif() + if(LEONIDA_LLVM_MC AND Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) + set(LEONIDA_SG_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/subgroup_shaders) + set(LEONIDA_SG_INDEXES "") + foreach(case "w64_native;cs_w64x_readlane;0" "w64_emulated;cs_w64x_readlane;1" "w32_native;cs_wqm_w32;0" + "ps_w64_native;ps_w64x_readlane;0") + list(GET case 0 folder) + list(GET case 1 shader) + list(GET case 2 emulate) + set(index ${LEONIDA_SG_DIR}/${folder}/spirv/index.json) + add_custom_command( + OUTPUT ${index} + # The standalone harness runs these with the V# at s[0:3]; d3d12_subgroup_test passes it as four root + # constants, which the D3D12 compute layout puts at s[4:7] (LEONIDA_USER_DATA_SHIFT=4, D3D-448). + COMMAND ${CMAKE_COMMAND} -E env LLVM_MC=${LEONIDA_LLVM_MC} LEONIDA_W64_EMULATE=${emulate} + LEONIDA_USER_DATA_SHIFT=4 + $ -I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py + ${LEONIDA_SG_DIR}/${folder} ${shader} + DEPENDS ${LEONIDA_TRANSLATOR_DEPS} + ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/${shader}.asm + COMMENT "Translating ${shader} for the subgroup size test (${folder})" + VERBATIM) + list(APPEND LEONIDA_SG_INDEXES ${index}) + endforeach() + # The probe shaders that store the subgroup size the driver ran them with, and a one-triangle vertex shader. + foreach(source cs_sg_probe.comp ps_sg_probe.frag vs_sg_fullscreen.vert) + set(output ${LEONIDA_SG_DIR}/glsl/${source}.spv) + add_custom_command( + OUTPUT ${output} + COMMAND ${CMAKE_COMMAND} -E make_directory ${LEONIDA_SG_DIR}/glsl + COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${output} + ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${source} + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${source} + COMMENT "Compiling ${source}" + VERBATIM) + list(APPEND LEONIDA_SG_INDEXES ${output}) + endforeach() + add_executable(d3d12_subgroup_test test/d3d12_subgroup_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_SG_INDEXES}) + target_link_libraries(d3d12_subgroup_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_subgroup_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_SUBGROUP_SHADERS="${LEONIDA_SG_DIR}") + target_compile_options(d3d12_subgroup_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_subgroup COMMAND d3d12_subgroup_test) + set_tests_properties(d3d12_subgroup PROPERTIES SKIP_RETURN_CODE 77) + else() + message(STATUS "llvm-mc (set LLVM_MC) or glslangValidator not found: d3d12_subgroup_test is not built") + endif() + + # Clears on every format class against WARP (needs a Vulkan GPU; exit 77 without one). + add_executable(d3d12_clear_formats_test test/d3d12_clear_formats_test.cpp) + target_link_libraries(d3d12_clear_formats_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_clear_formats_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_clear_formats_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_clear_formats COMMAND d3d12_clear_formats_test) + set_tests_properties(d3d12_clear_formats PROPERTIES SKIP_RETURN_CODE 77) + + # SetDescriptorHeaps validation, Reset/ClearState/bundle parity, lifetime pinning, direct-index flags. + add_executable(d3d12_set_descriptor_heaps_test test/d3d12_set_descriptor_heaps_test.cpp) + target_link_libraries(d3d12_set_descriptor_heaps_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_set_descriptor_heaps_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_set_descriptor_heaps_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_set_descriptor_heaps COMMAND d3d12_set_descriptor_heaps_test) + set_tests_properties(d3d12_set_descriptor_heaps PROPERTIES SKIP_RETURN_CODE 77 + FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") + + # The loader can create this device instead of the host's (D3D12XboxCreateDevice, LEONIDA_D3D12=vulkan). + if(TARGET gta6rt) + target_link_libraries(gta6rt PRIVATE gta6rt_d3d12_com) + target_compile_definitions(gta6rt PRIVATE LEONIDA_VULKAN_DEVICE) + + # A stand-in title that imports d3d12_xs.dll!D3D12XboxCreateDevice and runs a clear and a readback on the + # device it gets, mapped and run by `gta6rt --run` with LEONIDA_D3D12=vulkan: the loader, the game thread, the + # proxies and the Vulkan device in one process. check_tiny_frame.py reads the verdict, the binding and the + # call order from outside; d3d12_com_test is its probe for "no usable Vulkan device" (exit code 77). + leonida_add_d3d12_xs_stub() + add_executable(tiny_frame test/fixtures/tiny_frame.cpp) + target_link_libraries(tiny_frame PRIVATE d3d12_xs_stub) + target_compile_definitions(tiny_frame PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(tiny_frame PRIVATE /W4 /permissive- /utf-8) + set_target_properties(tiny_frame PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" + ) + if(Python3_FOUND) + add_test(NAME run_tiny_frame COMMAND "${Python3_EXECUTABLE}" -I + "${CMAKE_CURRENT_SOURCE_DIR}/test/check_tiny_frame.py" "$" + "$" "--probe=$" ${_trace_runner}) + set_tests_properties(run_tiny_frame PROPERTIES SKIP_RETURN_CODE 77) + # The queue test settings are for the tests only: left set, they must not shrink the game's device. + add_test(NAME run_tiny_frame_queue_test_settings COMMAND "${Python3_EXECUTABLE}" -I + "${CMAKE_CURRENT_SOURCE_DIR}/test/check_tiny_frame.py" "$" + "$" "--probe=$" --queue-test-settings + ${_trace_runner}) + set_tests_properties(run_tiny_frame_queue_test_settings PROPERTIES SKIP_RETURN_CODE 77) + endif() + endif() + + # M1.5 as a `gta6rt --run` guest: test/d3d12_translated_draw_test.cpp built again with LEONIDA_M15_GUEST as + # tiny_guest_draw.exe, whose only device is the D3D12XboxCreateDevice it imports from d3d12_xs.dll. The import + # library comes from a failing stub built into fixtures/stubs, away from the guest, so only gta6rt's shim registry + # can answer it. The guest links nothing from src/ or shims/ and can be + # copied with its ordinary CRT dependencies, given the m15 folder as its argument. test/run_guest_draw.cmake checks the exit code and the marker line. + # Opt-in: it needs a Vulkan GPU and the guest cannot tell a missing one from a bug, so default runs are unchanged. + option(LEONIDA_TEST_GUEST_DRAW + "Build tiny_guest_draw.exe and run the M1.5 draw through gta6rt --run (needs a Vulkan GPU)" OFF) + option(LEONIDA_GUEST_SCENE "Build the headless 600-frame synthetic guest test (requires static SDL3)" OFF) + if(LEONIDA_TEST_GUEST_DRAW OR LEONIDA_GUEST_SCENE) + # The import stub is shared with the tiny_frame clear/readback guest. + leonida_add_d3d12_xs_stub() + add_executable(tiny_guest_draw test/d3d12_translated_draw_test.cpp) + target_link_libraries(tiny_guest_draw PRIVATE d3d12_xs_stub Vulkan::Headers) + target_compile_definitions(tiny_guest_draw PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_M15_GUEST) + target_compile_options(tiny_guest_draw PRIVATE /W4 /permissive- /utf-8) + set_target_properties(tiny_guest_draw PROPERTIES + OUTPUT_NAME tiny_guest_draw + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/guest_draw/$" + ) + if(LEONIDA_GUEST_SCENE) + if(NOT TARGET gta6rt OR NOT TARGET SDL3::SDL3-static OR NOT LEONIDA_SDL3) + message(FATAL_ERROR "LEONIDA_GUEST_SCENE requires static SDL3; configure SDL3_DIR or LEONIDA_SDL3_FETCH") + endif() + target_compile_definitions(tiny_guest_draw PRIVATE LEONIDA_GUEST_SCENE) + target_sources(gta6rt PRIVATE test/scene_input_driver.cpp) + endif() + # This guest can use a synthetic fixture produced on another machine. Register the automated test + # if the tools to generate the fixture are available locally. + if(CMAKE_HOST_WIN32 AND NOT CMAKE_CROSSCOMPILING AND TARGET d3d12_translated_draw_test AND TARGET gta6rt) + add_dependencies(tiny_guest_draw d3d12_translated_draw_test gta6rt) + add_test(NAME d3d12_translated_draw_guest + COMMAND ${CMAKE_COMMAND} -DGTA6RT=$ -DGUEST=$ + -DFIXTURE=${LEONIDA_M15_DIR} -P ${CMAKE_CURRENT_SOURCE_DIR}/test/run_guest_draw.cmake) + set_tests_properties(d3d12_translated_draw_guest PROPERTIES TIMEOUT 180) + else() + message(STATUS "tiny_guest_draw will build. For an external synthetic M1.5 fixture or Wine run see runtime/README.md.") + endif() + if(LEONIDA_GUEST_SCENE AND Python3_Interpreter_FOUND AND TARGET d3d12_translated_draw_test) + set(_scene_wine_args) + if(CMAKE_CROSSCOMPILING AND CMAKE_CROSSCOMPILING_EMULATOR) + set(_scene_emulator ${CMAKE_CROSSCOMPILING_EMULATOR}) + list(POP_FRONT _scene_emulator _scene_launcher) + list(APPEND _scene_wine_args "--wine=${_scene_launcher}") + foreach(_arg IN LISTS _scene_emulator) + list(APPEND _scene_wine_args "--wine-arg=${_arg}") + endforeach() + add_dependencies(tiny_guest_draw d3d12_translated_draw_test gta6rt) + endif() + if((CMAKE_HOST_WIN32 AND NOT CMAKE_CROSSCOMPILING) OR _scene_wine_args) + add_test(NAME d3d12_guest_scene + COMMAND "${Python3_EXECUTABLE}" -I "${CMAKE_CURRENT_SOURCE_DIR}/../scripts/run_guest_scene.py" + --loader $ --guest $ + --shaders "${LEONIDA_M15_DIR}" --negative-controls ${_scene_wine_args}) + set_tests_properties(d3d12_guest_scene PROPERTIES TIMEOUT 900) + endif() + endif() + endif() + # bvh_builder_test can put the package's XboxBvhBuilder on this device too (LEONIDA_BVH_DEVICE=vulkan). + if(TARGET bvh_builder_test) + target_link_libraries(bvh_builder_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(bvh_builder_test PRIVATE LEONIDA_VULKAN_DEVICE) + endif() + # fsr_dispatch_test can put the package's FidelityFX DLL on this device too (LEONIDA_FSR_DEVICE=vulkan). + if(TARGET fsr_dispatch_test) + target_link_libraries(fsr_dispatch_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(fsr_dispatch_test PRIVATE LEONIDA_VULKAN_DEVICE) + endif() +elseif(TARGET gta6rt) + message(STATUS "Python 3 or d3d12.h missing: the D3D12 COM objects and d3d12_com_test are not built") +endif() diff --git a/runtime/cmake/fixtures.cmake b/runtime/cmake/fixtures.cmake new file mode 100644 index 000000000..9ac19f476 --- /dev/null +++ b/runtime/cmake/fixtures.cmake @@ -0,0 +1,23 @@ +# Test fixtures that more than one part of the build needs. + +# d3d12_xs_stub: d3d12_xs.dll with an import library, for the stand-in titles that import +# d3d12_xs.dll!D3D12XboxCreateDevice (tiny_frame, tiny_guest_draw). It is built into fixtures/stubs, away from the +# guests, so at run time only gta6rt's shim registry can answer the import. Callable from any directory; the target +# is created by the first call. +function(leonida_add_d3d12_xs_stub) + if(TARGET d3d12_xs_stub) + return() + endif() + add_library(d3d12_xs_stub SHARED + "${PROJECT_SOURCE_DIR}/test/fixtures/d3d12_xs_stub.cpp" + "${PROJECT_SOURCE_DIR}/test/fixtures/d3d12_xs_stub.def" + ) + target_compile_definitions(d3d12_xs_stub PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_xs_stub PRIVATE /W4 /permissive- /utf-8) + set_target_properties(d3d12_xs_stub PROPERTIES + OUTPUT_NAME d3d12_xs + PREFIX "" + RUNTIME_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/fixtures/stubs/$" + ARCHIVE_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/fixtures/stubs/$" + ) +endfunction() diff --git a/runtime/cmake/runtime_tests.cmake b/runtime/cmake/runtime_tests.cmake new file mode 100644 index 000000000..85c0738ea --- /dev/null +++ b/runtime/cmake/runtime_tests.cmake @@ -0,0 +1,834 @@ +# Tests that need no Vulkan headers: the CPU-only test programs, the stand-in titles and DLLs (tiny_*) that gta6rt +# maps, and the add_test() calls for the shim test programs of windows_runtime.cmake. +# Included by runtime/CMakeLists.txt inside if(BUILD_TESTING). + +add_executable(gfx10_tiling_test test/gfx10_tiling_test.cpp) +add_test(NAME gfx10_tiling COMMAND gfx10_tiling_test) + +add_executable(retire_tickets_test test/retire_tickets_test.cpp) +add_test(NAME retire_tickets COMMAND retire_tickets_test) +# VulkanContext::buffer_at's VA index (runtime/src/buffer_va_index.h): pure stdlib, no Vulkan instance. +add_executable(buffer_va_index_test test/buffer_va_index_test.cpp) +add_test(NAME buffer_va_index COMMAND buffer_va_index_test) + +add_executable(xbox_present_readback_size_test test/xbox_present_readback_size_test.cpp) +add_test(NAME xbox_present_readback_size COMMAND xbox_present_readback_size_test) + +add_executable(pipeline_cache_file_test test/pipeline_cache_file_test.cpp) +add_test(NAME pipeline_cache_file COMMAND pipeline_cache_file_test) + +add_executable(xdxr_build_output_test test/xdxr_build_output_test.cpp) +add_test(NAME xdxr_build_output COMMAND xdxr_build_output_test) + +# vk_pipeline_check's memory budget for large modules: pure stdlib, no Vulkan device. +add_executable(large_module_gate_test test/large_module_gate_test.cpp) +find_package(Threads REQUIRED) +target_link_libraries(large_module_gate_test PRIVATE Threads::Threads) +add_test(NAME large_module_gate COMMAND large_module_gate_test) +# vk_pipeline_check's isolate summary stage set: pure stdlib, no Vulkan device. +add_executable(pipeline_summary_test test/pipeline_summary_test.cpp) +add_test(NAME pipeline_summary COMMAND pipeline_summary_test) +# XDXR build descriptions (docs/xdxr.md); compared with d3d12.h where the Windows SDK provides it. +add_executable(xdxr_descs_test test/xdxr_descs_test.cpp) +add_test(NAME xdxr_descs COMMAND xdxr_descs_test) +# LEONIDA_VK_DEVICE name matching (runtime/src/vulkan_device_filter.h): pure stdlib, no Vulkan instance. +add_executable(vulkan_device_filter_test test/vulkan_device_filter_test.cpp) +target_include_directories(vulkan_device_filter_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) +add_test(NAME vulkan_device_filter COMMAND vulkan_device_filter_test) +add_executable(vk_presenter_capture_colour_test test/vk_presenter_capture_colour_test.cpp) +add_test(NAME vk_presenter_capture_colour COMMAND vk_presenter_capture_colour_test) +if(TARGET gta6rt) + if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") + add_executable(cpp_unwind_test test/cpp_unwind_test.cpp) + add_test(NAME cpp_unwind COMMAND cpp_unwind_test) + endif() + + # Compile-time ABI checks (D3D12/XMem structure sizes, alignments and member offsets against the Windows SDK). + # The file existed but no target built it, so none of its static_asserts ever ran. + add_executable(runtime_types_test test/test_runtime_types.cpp) + target_include_directories(runtime_types_test PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/src ${CMAKE_CURRENT_SOURCE_DIR}/shims) + add_test(NAME runtime_types COMMAND runtime_types_test) + + # Loader tests. They build their own PE images, so they need neither the game nor any other input. + add_executable(loader_test + test/loader_test.cpp + src/pe_loader.cpp + shims/registry.cpp + ) + target_compile_definitions(loader_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE) + target_compile_options(loader_test PRIVATE /W4 /permissive- /utf-8 /EHsc) + target_link_options(loader_test PRIVATE /OPT:NOREF ${GTA6RT_HOST_BASE}) + add_dependencies(loader_test gta6rt_tls_host) + add_test(NAME loader COMMAND loader_test) + # PE loader tests use two locally built fixtures: a DLL with exports, imports and relocations, and an EXE that + # imports it so Loader::load exercises recursive module loading. They contain no game data. + set(TINY_FIXTURE_DIR "${CMAKE_CURRENT_BINARY_DIR}/fixtures/$") + + add_library(tiny_dll SHARED test/fixtures/tiny_dll.cpp) + target_compile_definitions(tiny_dll PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(tiny_dll PRIVATE /W4 /permissive- /utf-8 /GS-) + # tiny_fault_caught faults inside its own __try. MSVC always catches that; clang-cl only with asynchronous + # exceptions, otherwise the access violation escapes and the unwind-registration check fails. + target_compile_options(tiny_dll PRIVATE $<$:/EHa>) + set_target_properties(tiny_dll PROPERTIES + OUTPUT_NAME tiny_dll + PREFIX "" + RUNTIME_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" + ARCHIVE_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" + MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>" + ) + + add_executable(tiny_exe test/fixtures/tiny_exe.cpp) + target_link_libraries(tiny_exe PRIVATE tiny_dll) + target_compile_definitions(tiny_exe PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(tiny_exe PRIVATE /W4 /permissive- /utf-8 /GS-) + set_target_properties(tiny_exe PROPERTIES + OUTPUT_NAME tiny_exe + RUNTIME_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" + MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>" + ) + + # An EXE built with /GA reads its TLS at index 0 without _tls_index; loader_tls_test maps it and reads it from + # threads that existed before load() and from ones that did not. + add_executable(tiny_ga_tls test/fixtures/tiny_ga_tls.cpp) + target_compile_definitions(tiny_ga_tls PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(tiny_ga_tls PRIVATE /W4 /permissive- /utf-8 /GS- /GA) + set_target_properties(tiny_ga_tls PROPERTIES + OUTPUT_NAME tiny_ga_tls + RUNTIME_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" + MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>" + ) + + add_executable(module_names_test test/module_names_test.cpp src/pe_loader.cpp shims/registry.cpp) + target_include_directories(module_names_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) + target_compile_definitions(module_names_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(module_names_test PRIVATE /W4 /permissive- /utf-8 /EHsc) + target_link_options(module_names_test PRIVATE /OPT:NOREF) + add_dependencies(module_names_test gta6rt_tls_host tiny_dll) + add_test(NAME module_names COMMAND module_names_test "$") + + add_executable(tiny_module_names test/fixtures/tiny_module_names.cpp) + target_compile_definitions(tiny_module_names PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(tiny_module_names PRIVATE /W4 /permissive- /utf-8 /EHsc) + set_target_properties(tiny_module_names PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}") + + # Native Windows and --dry-run/--init/--run share original renamed fixtures, including an ACP-named import. + if(NOT CMAKE_CROSSCOMPILING) + find_package(Python3 COMPONENTS Interpreter QUIET) + if(Python3_FOUND) + add_test(NAME run_module_names COMMAND "${Python3_EXECUTABLE}" -I + "${CMAKE_CURRENT_SOURCE_DIR}/test/check_module_names.py" + "--loader=$" "--guest=$" + "--importer=$" "--dependency=$" + "--work-dir=${CMAKE_CURRENT_BINARY_DIR}" + "--report=${CMAKE_CURRENT_BINARY_DIR}/module-names-results.json") + set_tests_properties(run_module_names PROPERTIES TIMEOUT 90) + endif() + endif() + + # pe_loader.cpp needs the shim registry for shims::find/make_unimplemented_thunk. The xmem and d3d12_xs tables + # are linked too so the optional LEONIDA_GAME_DIR run classifies the shipped modules' imports exactly like + # gta6rt does (no d3d12.lib is needed: d3d12_xs resolves its host entry points at run time). + add_executable(pe_loader_test + test/pe_loader_test.cpp + src/pe_loader.cpp + shims/registry.cpp + shims/xmem.cpp + shims/d3d12_xs.cpp + shims/d3d12_xs_device.cpp + ) + target_include_directories(pe_loader_test PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/src + ${CMAKE_CURRENT_SOURCE_DIR}/shims + ) + target_compile_definitions(pe_loader_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(pe_loader_test PRIVATE /W4 /permissive- /utf-8 /EHsc) + target_link_options(pe_loader_test PRIVATE /OPT:NOREF) + target_link_libraries(pe_loader_test PRIVATE gta6rt_d3d12_xs_rootsig psapi) + add_dependencies(pe_loader_test tiny_dll tiny_exe gta6rt_tls_host) + + # `gta6rt --run` rehearsal: a stand-in game EXE (CRT startup, statics, heap, files, threads) that imports + # xgameruntime.dll from a link-time stub; under --run the shim registry answers those imports instead. + add_library(xgameruntime_stub SHARED test/fixtures/xgameruntime_stub.cpp test/fixtures/xgameruntime_stub.def) + target_include_directories(xgameruntime_stub PUBLIC ${XTASKQUEUE_DIR}/Include) + target_compile_definitions(xgameruntime_stub PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + set_target_properties(xgameruntime_stub PROPERTIES + OUTPUT_NAME xgameruntime + PREFIX "" + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" + ) + add_executable(tiny_async test/fixtures/tiny_async.cpp) + target_link_libraries(tiny_async PRIVATE xgameruntime_stub) + set_target_properties(tiny_async PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" + ) + # Reaches xgameruntime.dll through LoadLibraryW/GetProcAddress, as xgameruntime.lib's thunks do (no import). + add_executable(tiny_gdk_load test/fixtures/tiny_gdk_load.cpp) + target_compile_definitions(tiny_gdk_load PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(tiny_gdk_load PRIVATE /W4 /permissive- /utf-8) + set_target_properties(tiny_gdk_load PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" + ) + # Run-time LoadLibrary of a bundled Xbox DLL (importing xmem.dll) through rt::Loader. + add_library(xmem_stub SHARED test/fixtures/xmem_stub.cpp test/fixtures/xmem_stub.def) + target_compile_definitions(xmem_stub PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(xmem_stub PRIVATE /W4 /permissive- /utf-8) + set_target_properties(xmem_stub PROPERTIES + OUTPUT_NAME xmem + PREFIX "" + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/stubs/$" + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/stubs/$" + ) + add_library(tiny_bundled_dll SHARED test/fixtures/tiny_bundled_dll.cpp test/fixtures/tiny_bundled_dll.def) + target_link_libraries(tiny_bundled_dll PRIVATE xmem_stub) + target_compile_definitions(tiny_bundled_dll PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(tiny_bundled_dll PRIVATE /W4 /permissive- /utf-8) + set_target_properties(tiny_bundled_dll PROPERTIES + OUTPUT_NAME tiny_bundled_dll + PREFIX "" + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/stubs/$" + ) + add_executable(tiny_bundled_load test/fixtures/tiny_bundled_load.cpp) + target_compile_definitions(tiny_bundled_load PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(tiny_bundled_load PRIVATE /W4 /permissive- /utf-8) + add_dependencies(tiny_bundled_load tiny_bundled_dll) + set_target_properties(tiny_bundled_load PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" + ) + add_library(tiny_startup_cmdline_dll SHARED test/fixtures/tiny_startup_cmdline.cpp) + target_compile_definitions(tiny_startup_cmdline_dll PRIVATE STARTUP_CMDLINE_DLL) + add_executable(tiny_startup_cmdline test/fixtures/tiny_startup_cmdline.cpp) + target_link_libraries(tiny_startup_cmdline PRIVATE tiny_startup_cmdline_dll) + foreach(target tiny_startup_cmdline_dll tiny_startup_cmdline) + target_compile_definitions(${target} PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(${target} PRIVATE /W4 /permissive- /utf-8) + set_target_properties(${target} PROPERTIES + PREFIX "" + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" + ) + endforeach() + # These linker-selected startup modes are specific to the MSVC CRT. + if(MSVC) + foreach(width a w) + foreach(mode default expand noargs) + set(target tiny_argv_${mode}_${width}) + add_executable(${target} test/fixtures/tiny_argv_modes.cpp) + target_compile_definitions(${target} PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(${target} PRIVATE /W4 /permissive- /utf-8) + if(width STREQUAL "w") + target_compile_definitions(${target} PRIVATE APP_WIDE) + endif() + if(mode STREQUAL "expand") + if(width STREQUAL "w") + target_link_options(${target} PRIVATE wsetargv.obj) + else() + target_link_options(${target} PRIVATE setargv.obj) + endif() + elseif(mode STREQUAL "noargs") + target_link_options(${target} PRIVATE noarg.obj) + endif() + set_target_properties(${target} PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$") + endforeach() + endforeach() + endif() + add_executable(tiny_atexit test/fixtures/tiny_atexit.cpp) + target_compile_definitions(tiny_atexit PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(tiny_atexit PRIVATE /W4 /permissive- /utf-8) + set_target_properties(tiny_atexit PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" + ) + add_executable(tiny_game test/fixtures/tiny_game.cpp) + target_link_libraries(tiny_game PRIVATE xgameruntime_stub) + target_compile_definitions(tiny_game PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS) # plain fopen, as games use + target_compile_options(tiny_game PRIVATE /W4 /permissive- /utf-8 /EHsc) + set_target_properties(tiny_game PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" + ) + # The same game with no .reloc, at the default EXE base, as RT-22 asks about the real one: it can only run at + # 0x140000000, which arm64 Wine on macOS uses for itself (src/base_reservation.h). + add_executable(tiny_game_fixed test/fixtures/tiny_game.cpp) + target_link_libraries(tiny_game_fixed PRIVATE xgameruntime_stub) + target_compile_definitions(tiny_game_fixed PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS) + target_compile_options(tiny_game_fixed PRIVATE /W4 /permissive- /utf-8 /EHsc) + target_link_options(tiny_game_fixed PRIVATE /FIXED /DYNAMICBASE:NO /BASE:0x140000000) + set_target_properties(tiny_game_fixed PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" + ) + add_executable(tiny_game_exit_code_test test/tiny_game_exit_code_test.cpp) + target_compile_definitions(tiny_game_exit_code_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(tiny_game_exit_code_test PRIVATE /W4 /permissive- /utf-8) + add_dependencies(tiny_game_exit_code_test gta6rt tiny_game tiny_game_fixed) + # abort() must reach the guest's SIGABRT handler before the run ends with the CRT's abort code (3). + add_executable(tiny_game_abort_test test/tiny_game_abort_test.cpp) + target_compile_definitions(tiny_game_abort_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(tiny_game_abort_test PRIVATE /W4 /permissive- /utf-8) + add_dependencies(tiny_game_abort_test gta6rt tiny_game) + add_test(NAME pe_loader COMMAND pe_loader_test "$" "$") + + # Synthetic, hand-built images through Loader::load: range checks, wrapping RVAs, import-table termination and + # base relocations (HIGHLOW included). No fixture DLL is needed; the images are written to a temporary folder. + add_executable(test_pe_loader_bounds + test/test_pe_loader_bounds.cpp + src/pe_loader.cpp + shims/registry.cpp + shims/xmem.cpp + shims/d3d12_xs.cpp + shims/d3d12_xs_device.cpp + ) + target_include_directories(test_pe_loader_bounds PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/src + ${CMAKE_CURRENT_SOURCE_DIR}/shims + ) + target_compile_definitions(test_pe_loader_bounds PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(test_pe_loader_bounds PRIVATE /W4 /permissive- /utf-8 /EHsc) + target_link_options(test_pe_loader_bounds PRIVATE /OPT:NOREF ${GTA6RT_HOST_BASE}) + target_link_libraries(test_pe_loader_bounds PRIVATE gta6rt_d3d12_xs_rootsig psapi) + add_dependencies(test_pe_loader_bounds gta6rt_tls_host) + add_test(NAME pe_loader_bounds COMMAND test_pe_loader_bounds) + + # RT-388: a deterministic mutation fuzzer over synthetic images through Loader::load (test/pe_loader_fuzz.cpp). + # ctest runs a fixed seed and case count; docs/testing.md has the long runs. With LEONIDA_LOADER_FUZZ_ASAN the + # fuzzer and the loader sources it compiles are built with AddressSanitizer (use RelWithDebInfo or Release: + # /fsanitize=address does not combine with the /RTC1 of a Debug build). + option(LEONIDA_LOADER_FUZZ_ASAN "Build pe_loader_fuzz with AddressSanitizer" OFF) + add_executable(pe_loader_fuzz + test/pe_loader_fuzz.cpp + src/pe_loader.cpp + shims/registry.cpp + shims/xmem.cpp + shims/d3d12_xs.cpp + shims/d3d12_xs_device.cpp + ) + target_include_directories(pe_loader_fuzz PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/src + ${CMAKE_CURRENT_SOURCE_DIR}/shims + ) + target_compile_definitions(pe_loader_fuzz PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(pe_loader_fuzz PRIVATE /W4 /permissive- /utf-8 /EHsc) + target_link_options(pe_loader_fuzz PRIVATE /OPT:NOREF ${GTA6RT_HOST_BASE}) + target_link_libraries(pe_loader_fuzz PRIVATE gta6rt_d3d12_xs_rootsig psapi) + add_dependencies(pe_loader_fuzz gta6rt_tls_host) + if(LEONIDA_LOADER_FUZZ_ASAN) + target_compile_options(pe_loader_fuzz PRIVATE /fsanitize=address /Zi) + target_link_options(pe_loader_fuzz PRIVATE /INCREMENTAL:NO /DEBUG) + # No STL container annotations: they need stl_asan.lib from the VS component, and the libraries linked here + # are built without ASan, so the annotate_string/annotate_vector /FAILIFMISMATCH keys must stay as theirs. + target_compile_definitions(pe_loader_fuzz PRIVATE _DISABLE_STRING_ANNOTATION _DISABLE_VECTOR_ANNOTATION) + # The ASan runtime: next to cl.exe for MSVC (the VS "C++ AddressSanitizer" component), under the resource + # directory for clang-cl. Its objects name the runtime libraries; the folder goes on the library path, and the + # DLL is copied beside the test so it runs without a Developer prompt or a PATH change. + get_filename_component(_leonida_cc_dir "${CMAKE_CXX_COMPILER}" DIRECTORY) + file(GLOB _leonida_asan_dll + "${_leonida_cc_dir}/clang_rt.asan_dynamic-x86_64.dll" + "${_leonida_cc_dir}/../lib/clang/*/lib/windows/clang_rt.asan_dynamic-x86_64.dll") + if(_leonida_asan_dll) + list(GET _leonida_asan_dll 0 _leonida_asan_dll) + get_filename_component(_leonida_asan_dir "${_leonida_asan_dll}" DIRECTORY) + target_link_directories(pe_loader_fuzz PRIVATE "${_leonida_asan_dir}") + if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang") + # clang-cl 23's stack-use-after-return frames break MSVC C++ exception dispatch at /O2: a rethrow faults + # in vcruntime's _C_specific_handler_noexcept (a five-line try/throw/catch does it). Without them it works. + target_compile_options(pe_loader_fuzz PRIVATE -fsanitize-address-use-after-return=never) + # clang-cl names these only when it runs the link itself; CMake calls the linker directly. + target_link_options(pe_loader_fuzz PRIVATE clang_rt.asan_dynamic-x86_64.lib + /wholearchive:clang_rt.asan_dynamic_runtime_thunk-x86_64.lib) + endif() + add_custom_command(TARGET pe_loader_fuzz POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy_if_different "${_leonida_asan_dll}" "$") + else() + message(WARNING "LEONIDA_LOADER_FUZZ_ASAN: no clang_rt.asan_dynamic-x86_64.dll beside ${CMAKE_CXX_COMPILER}") + endif() + endif() + add_test(NAME pe_loader_fuzz COMMAND pe_loader_fuzz --quiet) + + # Static TLS fixture: a DLL with __declspec(thread) and a TLS callback. It is ordinary test code; no game data + # is involved. loader_tls_test needs gta6rt_tls_host.dll next to its own EXE, because that is where + # Loader::initialize_tls looks for the reserved module TLS index. + add_library(tiny_tls SHARED test/fixtures/tiny_tls.cpp) + target_compile_definitions(tiny_tls PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(tiny_tls PRIVATE /W4 /permissive- /utf-8 /GS-) + set_target_properties(tiny_tls PROPERTIES + OUTPUT_NAME tiny_tls + PREFIX "" + RUNTIME_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" + ARCHIVE_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" + ) + + add_library(tiny_tls_cb_only SHARED test/fixtures/tiny_tls_cb_only.cpp) + target_compile_definitions(tiny_tls_cb_only PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(tiny_tls_cb_only PRIVATE /W4 /permissive- /utf-8 /GS-) + target_link_options(tiny_tls_cb_only PRIVATE /NODEFAULTLIB /ENTRY:DllMainCRTStartup) + target_link_libraries(tiny_tls_cb_only PRIVATE kernel32) + set_target_properties(tiny_tls_cb_only PROPERTIES + OUTPUT_NAME tiny_tls_cb_only + PREFIX "" + RUNTIME_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" + ARCHIVE_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" + ) + + # pe_loader.cpp needs the shim registry for shims::find/make_unimplemented_thunk. The fixtures import only host + # DLLs, so no shim tables are linked. + add_executable(loader_tls_test + test/loader_tls_test.cpp + src/pe_loader.cpp + shims/registry.cpp + ) + target_include_directories(loader_tls_test PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/src + ) + target_compile_definitions(loader_tls_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(loader_tls_test PRIVATE /W4 /permissive- /utf-8 /EHsc) + add_dependencies(loader_tls_test tiny_tls tiny_tls_cb_only tiny_ga_tls gta6rt_tls_host) + add_test(NAME loader_tls + COMMAND loader_tls_test "$" + ) + + # DisableThreadLibraryCalls from a mapped DllMain (shims/library_loader.cpp). The fixture is built without the CRT, so + # DllMain's only work is that one call. No game files. + add_library(dll_thread_calls SHARED test/fixtures/dll_thread_calls.cpp) + target_compile_options(dll_thread_calls PRIVATE /W4 /permissive- /utf-8 /GS-) + target_link_options(dll_thread_calls PRIVATE /NODEFAULTLIB /ENTRY:dll_thread_calls_main) + target_link_libraries(dll_thread_calls PRIVATE kernel32) + set_target_properties(dll_thread_calls PROPERTIES + OUTPUT_NAME dll_thread_calls + PREFIX "" + RUNTIME_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" + ARCHIVE_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" + ) + add_executable(dll_thread_calls_test + test/dll_thread_calls_test.cpp + src/pe_loader.cpp + shims/library_loader.cpp + shims/registry.cpp + shims/xmem.cpp + ) + target_include_directories(dll_thread_calls_test PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/src + ${CMAKE_CURRENT_SOURCE_DIR}/shims + ) + target_compile_definitions(dll_thread_calls_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(dll_thread_calls_test PRIVATE /W4 /permissive- /utf-8 /EHsc) + target_link_options(dll_thread_calls_test PRIVATE /OPT:NOREF) + target_link_libraries(dll_thread_calls_test PRIVATE psapi) + add_dependencies(dll_thread_calls_test dll_thread_calls) + add_test(NAME dll_thread_calls + COMMAND dll_thread_calls_test "$" + ) + + # The host GameInput path (docs/gameinput.md): mapped code that imports GameInputCreate from GameInput.dll, with no + # GameInput shim linked. Needs the SDK's gameinput.lib and GameInput.h to build the fixture, and a GameInput.dll on + # the machine to run (the test skips with 77 only when Windows cannot load GameInput.dll). No game files. + find_library(GAMEINPUT_LIBRARY NAMES gameinput HINTS ${_sdk_lib_hints}) + if(GAMEINPUT_LIBRARY) + add_library(gameinput_host SHARED test/fixtures/gameinput_host.cpp) + target_compile_options(gameinput_host PRIVATE /W4 /permissive- /utf-8 /GS-) + target_link_options(gameinput_host PRIVATE /NODEFAULTLIB /ENTRY:gameinput_host_main) + target_link_libraries(gameinput_host PRIVATE kernel32 ${GAMEINPUT_LIBRARY}) + set_target_properties(gameinput_host PROPERTIES + OUTPUT_NAME gameinput_host + PREFIX "" + RUNTIME_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" + ARCHIVE_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" + ) + add_executable(gameinput_host_test + test/gameinput_host_test.cpp + src/pe_loader.cpp + shims/registry.cpp + ) + target_include_directories(gameinput_host_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) + target_compile_definitions(gameinput_host_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(gameinput_host_test PRIVATE /W4 /permissive- /utf-8 /EHsc) + add_dependencies(gameinput_host_test gameinput_host) + add_test(NAME gameinput_host COMMAND gameinput_host_test "$") + set_tests_properties(gameinput_host PROPERTIES SKIP_RETURN_CODE 77) # Windows cannot load GameInput.dll + endif() + + # LEONIDA_UNIMPLEMENTED=log|fail|stop: builds its own image with two imports that bind to nothing, calls them in + # process (log, fail) and in child processes (default/env parsing, stop). No game files, no GPU. + add_executable(unimplemented_policy_test + test/unimplemented_policy_test.cpp + src/pe_loader.cpp + shims/registry.cpp + ) + # The register-preservation check needs a caller that sets rbx/rbp/rdi/rsi/r12-r15 and xmm6-15, which MSVC x64 + # cannot do inline: test/fixtures/abi_probe.asm (MASM). Without ml64 the rest of the test still runs. + # Visual Studio locates cl.exe without adding its directory to PATH. + # Keep looking for ml64 specifically so Ninja cannot select the 32-bit assembler. + get_filename_component(_gta6rt_compiler_bin "${CMAKE_CXX_COMPILER}" DIRECTORY) + find_program(LEONIDA_ML64 NAMES ml64 HINTS "${_gta6rt_compiler_bin}") + if(LEONIDA_ML64) + set(CMAKE_ASM_MASM_COMPILER "${LEONIDA_ML64}") + enable_language(ASM_MASM) + target_sources(unimplemented_policy_test PRIVATE test/fixtures/abi_probe.asm) + target_compile_definitions(unimplemented_policy_test PRIVATE LEONIDA_HAVE_ABI_PROBE=1) + else() + message(STATUS "ml64 not found: unimplemented_policy_test skips the register-preservation check") + endif() + target_include_directories(unimplemented_policy_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) + target_compile_definitions(unimplemented_policy_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE _CRT_SECURE_NO_WARNINGS) + target_compile_options(unimplemented_policy_test PRIVATE $<$:/W4 /permissive- /utf-8 /EHsc>) + target_link_options(unimplemented_policy_test PRIVATE /OPT:NOREF) + add_dependencies(unimplemented_policy_test gta6rt_tls_host) + add_test(NAME unimplemented_policy COMMAND unimplemented_policy_test) + + # gta6rt --trace FILE (shims/startup_trace.h): a synthetic image with an unimplemented import, an + # OutputDebugStringA call and a read of address 0; checks the JSON lines. No game files, no GPU. + add_executable(startup_trace_test + test/startup_trace_test.cpp + src/pe_loader.cpp + shims/registry.cpp + ) + target_include_directories(startup_trace_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) + target_compile_definitions(startup_trace_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE _CRT_SECURE_NO_WARNINGS) + target_compile_options(startup_trace_test PRIVATE /W4 /permissive- /utf-8 /EHsc) + target_link_options(startup_trace_test PRIVATE /OPT:NOREF) + add_dependencies(startup_trace_test gta6rt_tls_host) + add_test(NAME startup_trace COMMAND startup_trace_test) +endif() + +if(TARGET device_proxy_test) + add_test(NAME device_proxy COMMAND device_proxy_test) + set_tests_properties(device_proxy PROPERTIES SKIP_RETURN_CODE 77) # no WARP adapter (Wine) + # With --trace-d3d12 the 24 D3D12XboxCreateDevice parameter words still print (docs/boot.md, question 1), + # and the line with run-specific pointers does not. + add_test(NAME device_proxy_trace COMMAND device_proxy_test --trace-d3d12) + set_tests_properties(device_proxy_trace PROPERTIES SKIP_RETURN_CODE 77 + PASS_REGULAR_EXPRESSION "D3D12XboxCreateDevice params\\[24\\] =1234abcd" + FAIL_REGULAR_EXPRESSION "FAIL;D3D12XboxCreateDevice adapter=") +endif() +if(TARGET xs_proxy_mock_test) + add_test(NAME xs_proxy_mock COMMAND xs_proxy_mock_test) + # The guard region's setup failing (one process each: the tables are built once per process). + add_test(NAME xs_proxy_mock_no_reserve COMMAND xs_proxy_mock_test --fail-virtualalloc) + add_test(NAME xs_proxy_mock_no_protect COMMAND xs_proxy_mock_test --fail-virtualprotect) + add_test(NAME xs_proxy_mock_no_handler COMMAND xs_proxy_mock_test --fail-veh) + # The routes are read once per process, so each override case is its own test. + add_test(NAME xs_proxy_mock_env_slots COMMAND xs_proxy_mock_test --env-slots) + add_test(NAME xs_proxy_mock_env_slots_invalid COMMAND xs_proxy_mock_test --env-slots-invalid) + # PresentX on the queue: the slot is read once per process, so the named slot and the ignored value are two tests. + add_test(NAME xs_proxy_mock_present_slot COMMAND xs_proxy_mock_test --present-slot) + add_test(NAME xs_proxy_mock_present_slot_invalid COMMAND xs_proxy_mock_test --present-slot-invalid) +endif() +if(TARGET root_sig_test) + add_test(NAME root_sig COMMAND root_sig_test) +endif() +add_executable(command_list_test test/command_list_test.cpp) +add_test(NAME command_list COMMAND command_list_test) +# Which SPIR-V modules declare a storage image or buffer they may write (src/spirv_stores.h), on hand-built words. +add_executable(spirv_stores_test test/spirv_stores_test.cpp) +add_test(NAME spirv_stores COMMAND spirv_stores_test) +add_executable(shader_fixture_path_test test/shader_fixture_path_test.cpp) +add_test(NAME shader_fixture_path COMMAND shader_fixture_path_test) +add_executable(resource_tiling_test test/resource_tiling_test.cpp) +add_test(NAME resource_tiling COMMAND resource_tiling_test) +add_executable(resource_detile_test test/resource_detile_test.cpp) +add_test(NAME resource_detile COMMAND resource_detile_test) +add_executable(descriptor_table_test test/descriptor_table_test.cpp) +add_test(NAME descriptor_table COMMAND descriptor_table_test) +add_executable(shader_library_test test/shader_library_test.cpp) +add_test(NAME shader_library COMMAND shader_library_test) +add_executable(spirv_f16_halves_test test/spirv_f16_halves_test.cpp) +add_test(NAME spirv_f16_halves COMMAND spirv_f16_halves_test) +# Optional: skips unless LEONIDA_SHADERS names a translated work folder (/shaders/spirv). +add_executable(shader_library_corpus_test test/shader_library_corpus_test.cpp) +add_test(NAME shader_library_corpus COMMAND shader_library_corpus_test) +# Reads all 26,503 containers and modules: about 9 minutes from a hard disk. +set_tests_properties(shader_library_corpus PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 3600) +if(TARGET gta6rt) + # Optional: skips unless LEONIDA_GAME_DIR and LEONIDA_MOVIE are set. + add_executable(bink_decode_test + test/bink_decode_test.cpp + src/pe_loader.cpp + shims/registry.cpp + shims/xmem.cpp + ) + target_compile_definitions(bink_decode_test PRIVATE + WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE _CRT_SECURE_NO_WARNINGS) + target_compile_options(bink_decode_test PRIVATE /W4 /permissive- /EHsc /utf-8) + target_link_options(bink_decode_test PRIVATE /OPT:NOREF) + target_link_libraries(bink_decode_test PRIVATE psapi) + add_dependencies(bink_decode_test gta6rt_tls_host) + add_test(NAME bink_decode COMMAND bink_decode_test) + set_tests_properties(bink_decode PROPERTIES SKIP_RETURN_CODE 77) + + # Optional: skips unless LEONIDA_GAME_DIR and LEONIDA_BINK_INDEX are set. Measures the HBINK/BINKSUMMARY + # offsets and the decode return values over every stream of movies.rpf (docs/movies.md section 5). + add_executable(bink_abi_test + test/bink_abi_test.cpp + src/pe_loader.cpp + shims/registry.cpp + shims/xmem.cpp + ) + target_compile_definitions(bink_abi_test PRIVATE + WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE _CRT_SECURE_NO_WARNINGS) + target_compile_options(bink_abi_test PRIVATE /W4 /permissive- /EHsc /utf-8) + target_link_options(bink_abi_test PRIVATE /OPT:NOREF) + target_link_libraries(bink_abi_test PRIVATE psapi) + add_dependencies(bink_abi_test gta6rt_tls_host) + add_test(NAME bink_abi COMMAND bink_abi_test) + set_tests_properties(bink_abi PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 3600) + + # Optional local viewer: plays a .bk2 in a window through the package's Bink2Scarlett.dll (test/bink_play.cpp). + # The CTest entry is the headless smoke run; it skips unless LEONIDA_GAME_DIR and LEONIDA_MOVIE are set. + add_executable(bink_play + test/bink_play.cpp + src/pe_loader.cpp + shims/registry.cpp + shims/xmem.cpp + ) + target_compile_definitions(bink_play PRIVATE + WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE _CRT_SECURE_NO_WARNINGS) + target_compile_options(bink_play PRIVATE /W4 /permissive- /EHsc /utf-8) + target_link_options(bink_play PRIVATE /OPT:NOREF) + target_link_libraries(bink_play PRIVATE psapi user32 gdi32) + add_dependencies(bink_play gta6rt_tls_host) + add_test(NAME bink_play_headless COMMAND bink_play --headless --frames 30) + set_tests_properties(bink_play_headless PROPERTIES SKIP_RETURN_CODE 77) + + # Optional: skips unless LEONIDA_GAME_DIR is set. Drives the package's FSR DLL on the Xbox-ABI device proxy. + if(D3D12_LIBRARY AND DXGI_LIBRARY) + add_executable(fsr_dispatch_test + test/fsr_dispatch_test.cpp + src/pe_loader.cpp + shims/registry.cpp + shims/xmem.cpp + shims/d3d12_xs.cpp + shims/d3d12_xs_device.cpp + ) + target_compile_definitions(fsr_dispatch_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS) + target_compile_options(fsr_dispatch_test PRIVATE /W4 /permissive- /EHsc /utf-8) + target_link_options(fsr_dispatch_test PRIVATE /OPT:NOREF) + target_link_libraries(fsr_dispatch_test PRIVATE gta6rt_d3d12_xs_rootsig ${D3D12_LIBRARY} ${DXGI_LIBRARY} psapi) + add_dependencies(fsr_dispatch_test gta6rt_tls_host) + add_test(NAME fsr_dispatch COMMAND fsr_dispatch_test) + set_tests_properties(fsr_dispatch PROPERTIES SKIP_RETURN_CODE 77) + + # Optional: skips unless LEONIDA_GAME_DIR is set. Constructs the package's XboxBvhBuilder on the device proxy. + add_executable(bvh_builder_test + test/bvh_builder_test.cpp + src/pe_loader.cpp + shims/registry.cpp + shims/xmem.cpp + shims/d3d12_xs.cpp + shims/d3d12_xs_device.cpp + ) + target_compile_definitions(bvh_builder_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS) + target_compile_options(bvh_builder_test PRIVATE /W4 /permissive- /EHsc /utf-8) + target_link_options(bvh_builder_test PRIVATE /OPT:NOREF) + target_link_libraries(bvh_builder_test PRIVATE gta6rt_d3d12_xs_rootsig ${D3D12_LIBRARY} ${DXGI_LIBRARY} psapi) + add_dependencies(bvh_builder_test gta6rt_tls_host) + add_test(NAME bvh_builder COMMAND bvh_builder_test) + set_tests_properties(bvh_builder PROPERTIES SKIP_RETURN_CODE 77) + endif() + + # Optional: skips unless LEONIDA_GAME_DIR and LEONIDA_MOVIE_AUDIO are set. + add_executable(bink_audio_test + test/bink_audio_test.cpp + src/pe_loader.cpp + shims/registry.cpp + shims/xmem.cpp + ) + target_compile_definitions(bink_audio_test PRIVATE + WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE _CRT_SECURE_NO_WARNINGS) + target_compile_options(bink_audio_test PRIVATE /W4 /permissive- /EHsc /utf-8) + target_link_options(bink_audio_test PRIVATE /OPT:NOREF) + target_link_libraries(bink_audio_test PRIVATE psapi) + add_dependencies(bink_audio_test gta6rt_tls_host) + add_test(NAME bink_audio COMMAND bink_audio_test) + set_tests_properties(bink_audio PROPERTIES SKIP_RETURN_CODE 77) +endif() +if(WIN32 AND TARGET xmem_test) + add_test(NAME xmem COMMAND xmem_test) +endif() +if(WIN32 AND TARGET xg_xs_test) + add_test(NAME xg_xs COMMAND xg_xs_test) +endif() +if(WIN32 AND TARGET acphal_test) + add_test(NAME acphal COMMAND acphal_test) +endif() +if(WIN32 AND TARGET cpu_emulation_test) + add_test(NAME cpu_emulation COMMAND cpu_emulation_test) +endif() +if(WIN32 AND TARGET xapu_chad_test) + add_test(NAME xapu_chad COMMAND xapu_chad_test) +endif() +if(WIN32 AND TARGET process_cmdline_test) + add_test(NAME process_cmdline COMMAND process_cmdline_test) +endif() +if(WIN32 AND TARGET file_system_test) + add_test(NAME file_system COMMAND file_system_test) +endif() +if(WIN32 AND TARGET int3_skip_test) + add_test(NAME int3_skip COMMAND int3_skip_test) +endif() +if(WIN32 AND TARGET winhttp_offline_test) + add_test(NAME winhttp_offline COMMAND winhttp_offline_test) +endif() +if(WIN32 AND TARGET com_shim_test) + add_test(NAME com_shim COMMAND com_shim_test) +endif() +if(WIN32 AND TARGET bcrypt_rng_test) + add_test(NAME bcrypt_rng COMMAND bcrypt_rng_test) + add_test(NAME bcrypt_rng_seeded COMMAND bcrypt_rng_test --seeded) + set_tests_properties(bcrypt_rng_seeded PROPERTIES ENVIRONMENT "LEONIDA_RNG_SEED=0x123456789abcdef0") +endif() +if(WIN32 AND TARGET api_ref_state_test) + add_test(NAME api_ref_state COMMAND api_ref_state_test) + set_tests_properties(api_ref_state PROPERTIES TIMEOUT 30) +endif() +if(WIN32 AND TARGET api_global_refs_test) + add_test(NAME api_global_refs COMMAND api_global_refs_test) + set_tests_properties(api_global_refs PROPERTIES TIMEOUT 30) +endif() +# Internal XTaskQueue context pinning and rundown regression tests. +if(WIN32 AND TARGET gta6rt_xtaskqueue) + foreach(_context_test context_pinning context_rundown context_reentrant context_concurrent_detach context_attach_detach_stress) + add_executable(${_context_test}_test + test/${_context_test}_test.cpp + ) + target_include_directories(${_context_test}_test PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/shims/xtaskqueue + ${XTASKQUEUE_DIR}/Source/Task + ${XTASKQUEUE_DIR}/Source/Common + ) + target_compile_definitions(${_context_test}_test PRIVATE + WIN32_LEAN_AND_MEAN NOMINMAX + ) + target_compile_options(${_context_test}_test PRIVATE + /W4 /permissive- /utf-8 /EHsc + ) + target_link_libraries(${_context_test}_test PRIVATE + gta6rt_xtaskqueue + ) + add_test(NAME ${_context_test} + COMMAND ${_context_test}_test + ) + set_tests_properties(${_context_test} PROPERTIES TIMEOUT 15) + endforeach() + + add_executable(wait_registration_test test/wait_registration_test.cpp) + target_include_directories(wait_registration_test PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/shims/xtaskqueue ${XTASKQUEUE_DIR}/Source/Task ${XTASKQUEUE_DIR}/Source/Common) + target_link_libraries(wait_registration_test PRIVATE gta6rt_xtaskqueue) + foreach(_case unregister undispatched terminate parked self presignaled monitor close composite snapshot + cross concurrent held_snapshot admission cancel_unregister reentrant_admission + reentrant_vs_external_unregister multi_dispatcher_terminate multi_dispatcher_unregister_replace) + add_test(NAME wait_registration_${_case} COMMAND wait_registration_test ${_case}) + set_tests_properties(wait_registration_${_case} PROPERTIES TIMEOUT 15) + endforeach() +endif() +if(WIN32 AND TARGET dstorage_test) + add_test(NAME dstorage COMMAND dstorage_test) +endif() +if(WIN32 AND TARGET xgameruntime_test) + add_test(NAME xgameruntime COMMAND xgameruntime_test) + add_test(NAME xgameruntime_user COMMAND xgameruntime_user_test) + add_test(NAME xgameruntime_gamesave COMMAND xgameruntime_gamesave_test) + add_test(NAME xgameruntime_store COMMAND xgameruntime_store_test) + add_test(NAME xgameruntime_offline COMMAND xgameruntime_offline_test) + add_test(NAME xgameruntime_offline_hdr COMMAND xgameruntime_offline_test) + set_tests_properties(xgameruntime_offline_hdr PROPERTIES ENVIRONMENT "LEONIDA_HDR=1") + add_test(NAME xgameruntime_user_gamertag COMMAND xgameruntime_user_test --expect-gamertag Tester42) + set_tests_properties(xgameruntime_user_gamertag PROPERTIES ENVIRONMENT "LEONIDA_GAMERTAG=Tester42") + # Longer than getenv_s's old 64-byte buffer: still the "Player" fallback (and its message), not a silent one. + add_test(NAME xgameruntime_user_gamertag_long COMMAND xgameruntime_user_test --expect-gamertag Player) + set_tests_properties(xgameruntime_user_gamertag_long PROPERTIES ENVIRONMENT "LEONIDA_GAMERTAG=GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG") +endif() +# The active-input tracker the GameInput shim feeds (src/active_input.h), on synthetic samples: no SDL, no +# controller, no GPU, so it builds and runs everywhere, with or without SDL3. +add_executable(active_input_test test/active_input_test.cpp) +if(MSVC) + target_compile_options(active_input_test PRIVATE /W4 /permissive- /utf-8) +endif() +add_test(NAME active_input COMMAND active_input_test) +if(WIN32 AND TARGET gameinput_test) + add_test(NAME gameinput COMMAND gameinput_test) +elseif(TARGET gta6rt) + # Built without SDL3: listed as "Not Run (Disabled)" so it is visible that the shim was not tested. + add_test(NAME gameinput COMMAND ${CMAKE_COMMAND} -E echo "built without SDL3") + set_tests_properties(gameinput PROPERTIES DISABLED TRUE) +endif() +if(WIN32 AND TARGET gta6rt AND TARGET tiny_game) + if(TARGET tiny_argv_default_a AND NOT CMAKE_CROSSCOMPILING) + find_package(Python3 COMPONENTS Interpreter QUIET) + if(Python3_FOUND) + add_test(NAME run_argv_modes COMMAND "${Python3_EXECUTABLE}" -I + "${CMAKE_CURRENT_SOURCE_DIR}/test/check_argv_modes.py" + --loader "$" --fixtures "$" + --work-dir "${CMAKE_CURRENT_BINARY_DIR}") + set_tests_properties(run_argv_modes PROPERTIES TIMEOUT 90) + endif() + endif() + add_test(NAME run_startup_cmdline COMMAND ${CMAKE_COMMAND} + "-DLOADER=$" "-DGUEST=$" + "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_startup_cmdline.cmake") + add_test(NAME run_tiny_async COMMAND ${CMAKE_COMMAND} + "-DLOADER=$" "-DGUEST=$" + "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_loaded_async.cmake") + add_test(NAME run_tiny_gdk_load COMMAND ${CMAKE_COMMAND} + "-DLOADER=$" "-DGUEST=$" + "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_loaded_gdk.cmake") + add_test(NAME run_tiny_bundled_load COMMAND ${CMAKE_COMMAND} + "-DLOADER=$" "-DGUEST=$" + "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_loaded_bundled.cmake") + # atexit handlers, static destructors and the ways out, compared with the same program run natively. + add_test(NAME run_tiny_atexit COMMAND ${CMAKE_COMMAND} + "-DLOADER=$" "-DGUEST=$" + "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_atexit.cmake") + add_test(NAME run_tiny_game COMMAND gta6rt --run $ -- hello 42) + add_test(NAME run_tiny_game_console_paths COMMAND ${CMAKE_COMMAND} + "-DLOADER=$" "-DGUEST=$" + "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_console_paths.cmake") + add_test(NAME run_tiny_game_exit_code COMMAND tiny_game_exit_code_test + "$" "$") + add_test(NAME run_tiny_game_abort_exit_codes COMMAND tiny_game_abort_test + "$" "$") + # Without relocations it can only run at 0x140000000 (base_reservation.h), so passing means it got there; the + # game's exact exit code comes back through the relaunch. + add_test(NAME run_tiny_game_fixed COMMAND gta6rt --run $ -- hello 42) + add_test(NAME run_tiny_game_fixed_exit_code COMMAND tiny_game_exit_code_test + "$" "$") + # Two modes at once are refused before anything is mapped (#886). The stand-in game's own arguments are passed, + # so a gta6rt that ignored the conflict would run it, print "running" and exit 0. + foreach(modes "dry-run;run" "dry-run;init" "init;run") + string(REPLACE ";" "_" name "${modes}") + list(TRANSFORM modes PREPEND "--") + add_test(NAME gta6rt_rejects_${name} COMMAND gta6rt ${modes} $ -- hello 42) + set_tests_properties(gta6rt_rejects_${name} PROPERTIES + PASS_REGULAR_EXPRESSION "usage: gta6rt" + FAIL_REGULAR_EXPRESSION "running |module\\(s\\) mapped") + endforeach() + # The opt-in checks, one test each: thread_local on the game's threads, a C++ exception caught inside the image. + add_test(NAME run_tiny_game_tls COMMAND gta6rt --run $ -- hello 42 tls) + add_test(NAME run_tiny_game_eh COMMAND gta6rt --run $ -- hello 42 eh) + # BUILD-1457: the stack a game thread gets. gta6rt_stack reads SizeOfStackReserve from the built loader (nothing + # is run); run_tiny_game_stack asks Windows, on the entry thread and on a thread created with dwStackSize 0. + add_test(NAME gta6rt_stack COMMAND "${CMAKE_COMMAND}" + "-DTOOL=$" "-DWANT=${GTA6RT_STACK}" + -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_stack_reserve.cmake") + add_test(NAME run_tiny_game_stack COMMAND gta6rt --run $ -- hello 42 stack) + # GAME: is the game folder, absolute, when gta6rt is given a bare image name or `--game-dir .`. + add_test(NAME run_tiny_game_dir COMMAND ${CMAKE_COMMAND} + "-DLOADER=$" "-DGUEST=$" + "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_game_dir.cmake") +endif() +if(TARGET root_signature_test) + add_test(NAME root_signature COMMAND root_signature_test) +endif() +if(TARGET host_cpu_test) + add_test(NAME host_cpu COMMAND host_cpu_test) +endif() +if(TARGET core_config_test) + # The example file is an argument, so the test reads the tracked file and not a copy made at configure time. + add_test(NAME core_config COMMAND core_config_test "${CMAKE_CURRENT_SOURCE_DIR}/leonida.example.toml") +endif() +if(TARGET core_log_test) + add_test(NAME core_log COMMAND core_log_test) +endif() +if(WIN32 AND TARGET root_signature_oracle_test) + add_test(NAME root_signature_oracle COMMAND root_signature_oracle_test) +endif() diff --git a/runtime/cmake/vulkan_cpu_tests.cmake b/runtime/cmake/vulkan_cpu_tests.cmake new file mode 100644 index 000000000..e5ca3cbbe --- /dev/null +++ b/runtime/cmake/vulkan_cpu_tests.cmake @@ -0,0 +1,155 @@ +# CPU-only tests of the Vulkan layer: they need the Vulkan headers, not a GPU. +# Included by runtime/CMakeLists.txt inside if(TARGET Vulkan::Headers). + +# Needs only the Vulkan headers, not a GPU. +if(BUILD_TESTING) + add_executable(typeless_rtv_test test/typeless_rtv_test.cpp) + target_link_libraries(typeless_rtv_test PRIVATE Vulkan::Headers) + if(WIN32) + target_compile_definitions(typeless_rtv_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + endif() + add_test(NAME typeless_rtv COMMAND typeless_rtv_test) + add_executable(pipeline_cache_snapshot_test test/pipeline_cache_snapshot_test.cpp) + target_link_libraries(pipeline_cache_snapshot_test PRIVATE Vulkan::Headers) + add_test(NAME pipeline_cache_snapshot COMMAND pipeline_cache_snapshot_test) + add_executable(predicated_copy_test test/predicated_copy_test.cpp) + target_link_libraries(predicated_copy_test PRIVATE Vulkan::Headers) + if(WIN32) + target_compile_definitions(predicated_copy_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + endif() + add_test(NAME predicated_copy COMMAND predicated_copy_test) + # CopyResource (buffer-to-buffer) and CopyTexture (including depth24_as_float) apply ResourceBinding::buffer_offset (no GPU). + add_executable(replay_copy_offset_test test/replay_copy_offset_test.cpp) + target_link_libraries(replay_copy_offset_test PRIVATE Vulkan::Headers) + if(WIN32) + target_compile_definitions(replay_copy_offset_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + endif() + add_test(NAME replay_copy_offset COMMAND replay_copy_offset_test) + # KHR CopyRaytracingAccelerationStructure (CLONE, COMPACT) and COMPACTED_SIZE postbuild (no GPU). + add_executable(replay_khr_as_copy_postbuild_test test/replay_khr_as_copy_postbuild_test.cpp) + target_link_libraries(replay_khr_as_copy_postbuild_test PRIVATE Vulkan::Headers) + if(WIN32) + target_compile_definitions(replay_khr_as_copy_postbuild_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + endif() + if(MSVC) + target_compile_options(replay_khr_as_copy_postbuild_test PRIVATE /W4 /permissive- /utf-8) + endif() + add_test(NAME replay_khr_as_copy_postbuild COMMAND replay_khr_as_copy_postbuild_test) + # PreparedList::wrote_readback and readback_src_stages match the actual producer stage (depth24, rgb96, UAV clear; no GPU). + add_executable(replay_readback_stages_test test/replay_readback_stages_test.cpp) + target_link_libraries(replay_readback_stages_test PRIVATE Vulkan::Headers) + if(WIN32) + target_compile_definitions(replay_readback_stages_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + endif() + add_test(NAME replay_readback_stages COMMAND replay_readback_stages_test) + # emit of an enhanced texture barrier: no heap allocation for one layout piece, one barrier for each piece (no GPU). + add_executable(replay_texture_barrier_test test/replay_texture_barrier_test.cpp) + target_link_libraries(replay_texture_barrier_test PRIVATE Vulkan::Headers) + if(WIN32) + target_compile_definitions(replay_texture_barrier_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + endif() + add_test(NAME replay_texture_barrier COMMAND replay_texture_barrier_test) + add_executable(clear_color_test test/clear_color_test.cpp) + target_link_libraries(clear_color_test PRIVATE Vulkan::Headers) + if(WIN32) + target_compile_definitions(clear_color_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + endif() + add_test(NAME clear_color COMMAND clear_color_test) + # FramePacer of the Xbox presentation path on a fake clock (src/frame_pacer.h); no GPU, no Vulkan. + add_executable(frame_pacer_test test/frame_pacer_test.cpp) + find_package(Threads REQUIRED) + target_link_libraries(frame_pacer_test PRIVATE Threads::Threads) + if(MSVC) + target_compile_options(frame_pacer_test PRIVATE /W4 /permissive- /utf-8) + endif() + add_test(NAME frame_pacer COMMAND frame_pacer_test) + + # Replay refuses a list whose whole-view or implicit zero-clear needs an unset vkCmdClear*Image (no GPU). + add_executable(replay_clear_gate_test test/replay_clear_gate_test.cpp) + target_link_libraries(replay_clear_gate_test PRIVATE Vulkan::Headers) + if(WIN32) + target_compile_definitions(replay_clear_gate_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + endif() + add_test(NAME replay_clear_gate COMMAND replay_clear_gate_test) + # WriteBufferImmediate suspends conditional rendering around vkCmdUpdateBuffer so Intel drivers do not drop it. + add_executable(replay_write_immediate_predication_test test/replay_write_immediate_predication_test.cpp) + target_link_libraries(replay_write_immediate_predication_test PRIVATE Vulkan::Headers) + if(WIN32) + target_compile_definitions(replay_write_immediate_predication_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + endif() + add_test(NAME replay_write_immediate_predication COMMAND replay_write_immediate_predication_test) + add_executable(d3d12_state_map_test test/d3d12_state_map_test.cpp) + target_link_libraries(d3d12_state_map_test PRIVATE Vulkan::Headers) + if(WIN32) + target_compile_definitions(d3d12_state_map_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + endif() + add_test(NAME d3d12_state_map COMMAND d3d12_state_map_test) + add_executable(indirect_dispatch_count_alloc_test test/indirect_dispatch_count_alloc_test.cpp) + target_link_libraries(indirect_dispatch_count_alloc_test PRIVATE Vulkan::Headers) + if(WIN32) + target_compile_definitions(indirect_dispatch_count_alloc_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + endif() + add_test(NAME indirect_dispatch_count_alloc COMMAND indirect_dispatch_count_alloc_test) + # A buffer UAV clear writes where its resource starts in a shared VkBuffer (no GPU). + add_executable(replay_uav_clear_offset_test test/replay_uav_clear_offset_test.cpp) + target_link_libraries(replay_uav_clear_offset_test PRIVATE Vulkan::Headers) + add_test(NAME replay_uav_clear_offset COMMAND replay_uav_clear_offset_test) + # ResolveQueryData suspends conditional rendering around un-ended vkCmdFillBuffer runs as well as dispatches (D3D-148). + add_executable(replay_query_predication_test test/replay_query_predication_test.cpp) + target_link_libraries(replay_query_predication_test PRIVATE Vulkan::Headers) + if(WIN32) + target_compile_definitions(replay_query_predication_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + endif() + add_test(NAME replay_query_predication COMMAND replay_query_predication_test) + # Query edge cases and queue ownership, with CPU mocks (no GPU or game data). + add_executable(replay_query_edges_test test/replay_query_edges_test.cpp) + target_link_libraries(replay_query_edges_test PRIVATE Vulkan::Headers) + if(WIN32) + target_compile_definitions(replay_query_edges_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + endif() + add_test(NAME replay_query_edges COMMAND replay_query_edges_test) + # GFX10 T#/S#/V# descriptor encoding and its Vulkan mappings (src/gfx10_descriptors.h). + add_executable(gfx10_descriptors_test test/gfx10_descriptors_test.cpp) + target_link_libraries(gfx10_descriptors_test PRIVATE Vulkan::Headers) + add_test(NAME gfx10_descriptors COMMAND gfx10_descriptors_test) + # CPU cost of the D3D12 -> Vulkan replay per command (record, prepare, emit) with no-op Vulkan entry points: + # no GPU or driver. ctest runs its quick self-test; run it without arguments for the numbers. + add_executable(replay_cpu_bench test/replay_cpu_bench.cpp) + target_link_libraries(replay_cpu_bench PRIVATE Vulkan::Headers) + if(WIN32) + target_compile_definitions(replay_cpu_bench PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + endif() + add_test(NAME replay_cpu_bench_selftest COMMAND replay_cpu_bench --self-test) + add_test(NAME vk_descriptor_bench_selftest COMMAND vk_descriptor_bench --self-test) + # mods.h: mod.json manifests and archetype swaps (docs/modding.md) + add_executable(mods_test test/mods_test.cpp) + target_link_libraries(mods_test PRIVATE Vulkan::Headers) + add_test(NAME mods COMMAND mods_test) + if(WIN32) + # code_hooks.h: the remapping thunk and direct-call redirection the archetype hook uses (x64 Windows) + add_executable(code_hooks_test test/code_hooks_test.cpp) + target_link_libraries(code_hooks_test PRIVATE Vulkan::Headers) + target_compile_definitions(code_hooks_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + add_test(NAME code_hooks COMMAND code_hooks_test) + endif() + # The subgroup size a pipeline stage asks for, from synthetic index entries and device properties. + add_executable(subgroup_size_test test/subgroup_size_test.cpp) + target_link_libraries(subgroup_size_test PRIVATE Vulkan::Headers) + add_test(NAME subgroup_size COMMAND subgroup_size_test) + add_executable(conservative_raster_test test/conservative_raster_test.cpp) + add_test(NAME conservative_raster COMMAND conservative_raster_test) + # The GPU address arena's size from LEONIDA_ARENA_MB and synthetic device buffer limits. + add_executable(arena_size_test test/arena_size_test.cpp) + target_link_libraries(arena_size_test PRIVATE Vulkan::Headers) + add_test(NAME arena_size COMMAND arena_size_test) + # Queue construction cleans its Vulkan handles if holder registration runs out of host memory. + add_executable(vk_queue_constructor_oom_test test/vk_queue_constructor_oom_test.cpp) + target_link_libraries(vk_queue_constructor_oom_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) + if(WIN32) + target_compile_definitions(vk_queue_constructor_oom_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + if(MSVC) + target_compile_options(vk_queue_constructor_oom_test PRIVATE /W4 /permissive- /EHsc /utf-8) + endif() + endif() + add_test(NAME vk_queue_constructor_oom COMMAND vk_queue_constructor_oom_test) +endif() diff --git a/runtime/cmake/vulkan_tools.cmake b/runtime/cmake/vulkan_tools.cmake new file mode 100644 index 000000000..fbd142d3f --- /dev/null +++ b/runtime/cmake/vulkan_tools.cmake @@ -0,0 +1,262 @@ +# The standalone Vulkan tools (vk_harness, vk_pipeline_check, vk_sandbox and the others of the loop below) and the +# Vulkan tests that do not use the D3D12 COM objects. +# Included by runtime/CMakeLists.txt inside if(TARGET Vulkan::Headers). + +foreach(tool vk_harness vk_ps_sweep vk_texture_test vk_sampler_test vk_compute_test vk_store_test vk_pipeline_check vk_command_replay_test + vk_bindless_test vk_image_fuzz vk_descriptor_bench depth24_convert_test vk_predicate_capture_test vk_predicated_copy_test + vk_xdxr_build_test vk_queue_test vk_sandbox) + add_executable(${tool} test/${tool}.cpp) + target_link_libraries(${tool} PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) + if(WIN32) + target_compile_definitions(${tool} PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + endif() +endforeach() +# OpFmaKHR width gate of vk_shader_fma.h (shaderFmaFloat32 / shaderFmaFloat64): no Vulkan instance, no GPU. +add_executable(vk_shader_fma_test test/vk_shader_fma_test.cpp) +target_link_libraries(vk_shader_fma_test PRIVATE Vulkan::Headers) +add_test(NAME vk_shader_fma COMMAND vk_shader_fma_test) +# LEONIDA_VK_DEVICE names the GPU in every harness (docs/testing.md, "Choosing the GPU"): a filter that matches no +# device fails the run in vk_descriptor_bench and vk_sandbox too, instead of testing another GPU (TEST-1141). +find_package(Python3 COMPONENTS Interpreter QUIET) +if(Python3_FOUND) + add_test(NAME vk_device_filter_tools COMMAND "${Python3_EXECUTABLE}" -I + "${CMAKE_CURRENT_SOURCE_DIR}/test/check_device_filter_tools.py" "$" + "$" "${CMAKE_CURRENT_BINARY_DIR}/vk_device_filter_tools") + set_tests_properties(vk_device_filter_tools PROPERTIES SKIP_RETURN_CODE 77) +endif() +if(MSVC) + # Keep the checker and its worker threads on the toolchain's C++ runtime under Wine. + set_property(TARGET vk_pipeline_check PROPERTY + MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") +endif() +# BUILD-1457: a driver compiles on the thread that creates the pipeline, and its compiler can recurse with the +# shader's nesting. On Windows a thread that asks for no size gets the reserve in the PE header, 1 MB by default: +# the main thread and every std::thread worker of the checker. AMD's Windows compiler (26.11.2) overflows that +# on 26 of the corpus's mesh shaders, and 2 MB is still too little for compute shaders nested deeper than 16 +# (docs/pipeline_check.md, "Stack reserve"). Keep the number in step with scripts/build_runtime.ps1. +set(LEONIDA_PIPELINE_CHECK_STACK 8388608) +if(WIN32) + if(MSVC) + target_link_options(vk_pipeline_check PRIVATE /STACK:${LEONIDA_PIPELINE_CHECK_STACK}) + else() + target_link_options(vk_pipeline_check PRIVATE -Wl,--stack,${LEONIDA_PIPELINE_CHECK_STACK}) + endif() +endif() +if(BUILD_TESTING) + if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) + # Real Win32 environment and DXGI names, with D3D12 device creation stubbed: no GPU commands or game files. + # It includes the runtime's D3D12 shim headers, so it needs the same Windows SDK as the runtime. + add_executable(host_adapter_test test/host_adapter_test.cpp) + target_link_libraries(host_adapter_test PRIVATE Vulkan::Headers dxgi) + target_compile_definitions(host_adapter_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + if(MSVC) + target_compile_options(host_adapter_test PRIVATE /W4 /permissive- /EHsc /utf-8) + endif() + add_test(NAME host_adapter COMMAND host_adapter_test) + endif() + add_test(NAME vk_pipeline_check_cli COMMAND "${CMAKE_COMMAND}" + "-DTOOL=$" + "-DTEST_DIR=${CMAKE_CURRENT_BINARY_DIR}/vk_pipeline_check_cli_input" + "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" + -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_vk_pipeline_cli.cmake") + add_test(NAME vk_texture_cube_alpha COMMAND vk_texture_test --self-test-cube-alpha) + if(WIN32) + # Reads SizeOfStackReserve from the built file; the program is not run, so it needs no emulator. + add_test(NAME vk_pipeline_check_stack COMMAND "${CMAKE_COMMAND}" + "-DTOOL=$" + "-DWANT=${LEONIDA_PIPELINE_CHECK_STACK}" + -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_stack_reserve.cmake") + endif() + add_test(NAME depth24_convert COMMAND depth24_convert_test) + set_tests_properties(depth24_convert PROPERTIES SKIP_RETURN_CODE 77) + # Self-checking Vulkan tests with no shaders or game data; each exits 77 without a Vulkan device (TEST-514). + foreach(test vk_command_replay vk_predicated_copy vk_predicate_capture vk_queue) + add_test(NAME ${test} COMMAND ${test}_test) + set_tests_properties(${test} PROPERTIES SKIP_RETURN_CODE 77) + endforeach() + # The XDXR BVH builder: the GPU writes every case, then tools/xdxr_bvh.py validates and traces them. + set(LEONIDA_XDXR_OUT "${CMAKE_CURRENT_BINARY_DIR}/xdxr_build_cases") + file(MAKE_DIRECTORY "${LEONIDA_XDXR_OUT}") + add_test(NAME xdxr_build COMMAND vk_xdxr_build_test "${LEONIDA_XDXR_OUT}") + set_tests_properties(xdxr_build PROPERTIES SKIP_RETURN_CODE 77 FIXTURES_SETUP xdxr_build_cases) + find_package(Python3 COMPONENTS Interpreter QUIET) + if(Python3_FOUND) + add_test(NAME xdxr_build_check COMMAND "${Python3_EXECUTABLE}" -I + "${CMAKE_CURRENT_SOURCE_DIR}/../tools/xdxr_bvh.py" check-build "${LEONIDA_XDXR_OUT}" --rays 1000) + set_tests_properties(xdxr_build_check PROPERTIES FIXTURES_REQUIRED xdxr_build_cases SKIP_RETURN_CODE 77) + endif() +endif() +# VulkanQueue/VulkanContext query-state synchronization (remove_query_pool vs commit, cross-queue plan/commit) +# and pending Wait() preservation across transient vkQueueSubmit failures. +add_executable(vk_queue_query_sync_test test/vk_queue_query_sync_test.cpp) +target_link_libraries(vk_queue_query_sync_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) +if(WIN32) + target_compile_definitions(vk_queue_query_sync_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) +else() + find_package(Threads REQUIRED) + target_link_libraries(vk_queue_query_sync_test PRIVATE Threads::Threads) +endif() +if(MSVC) + target_compile_options(vk_queue_query_sync_test PRIVATE /W4 /permissive- /utf-8) +endif() +if(BUILD_TESTING) + add_test(NAME vk_queue_query_sync COMMAND vk_queue_query_sync_test) + set_tests_properties(vk_queue_query_sync PROPERTIES SKIP_RETURN_CODE 77) +endif() +# With LEONIDA_VK_VALIDATION=1: synchronization validation reports a missing barrier (and not a present one), so +# the other GPU tests' "0 validation errors" was checked by an active layer. 77 without validation or a device. +add_executable(vk_sync_validation_selftest test/vk_sync_validation_selftest.cpp) +target_link_libraries(vk_sync_validation_selftest PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) +if(WIN32) + target_compile_definitions(vk_sync_validation_selftest PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) +endif() +if(MSVC) + target_compile_options(vk_sync_validation_selftest PRIVATE /W4 /permissive- /utf-8) +endif() +if(BUILD_TESTING) + add_test(NAME vk_sync_validation COMMAND vk_sync_validation_selftest) + set_tests_properties(vk_sync_validation PROPERTIES SKIP_RETURN_CODE 77) +endif() +if(NOT Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) + find_program(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE glslangValidator HINTS "$ENV{VULKAN_SDK}/Bin" "$ENV{VULKAN_SDK}/bin") +endif() +if(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) + add_executable(vk_overlapping_occlusion_test test/vk_overlapping_occlusion_test.cpp) + target_link_libraries(vk_overlapping_occlusion_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) + if(WIN32) + target_compile_definitions(vk_overlapping_occlusion_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + endif() + foreach(stage vert frag) + set(source "${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/overlapping_occlusion.${stage}") + set(output "${CMAKE_CURRENT_BINARY_DIR}/overlapping_occlusion.${stage}.spv") + add_custom_command(OUTPUT "${output}" + COMMAND "${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE}" -V --target-env vulkan1.0 + -o "${output}" "${source}" + DEPENDS "${source}" VERBATIM) + target_sources(vk_overlapping_occlusion_test PRIVATE "${output}") + endforeach() + if(BUILD_TESTING) + add_test(NAME vk_overlapping_occlusion COMMAND vk_overlapping_occlusion_test + "${CMAKE_CURRENT_BINARY_DIR}/overlapping_occlusion.vert.spv" + "${CMAKE_CURRENT_BINARY_DIR}/overlapping_occlusion.frag.spv") + # The same test as a device without pipelineStatisticsQuery runs it (MoltenVK), on whatever device is here. + add_test(NAME vk_overlapping_occlusion_no_statistics COMMAND vk_overlapping_occlusion_test + "${CMAKE_CURRENT_BINARY_DIR}/overlapping_occlusion.vert.spv" + "${CMAKE_CURRENT_BINARY_DIR}/overlapping_occlusion.frag.spv" --no-statistics) + set_tests_properties(vk_overlapping_occlusion vk_overlapping_occlusion_no_statistics + PROPERTIES SKIP_RETURN_CODE 77) + endif() +endif() +# CPU-only: the ranking that makes these harnesses prefer a native ICD over Mesa's Dozen (#915). No GPU needed. +add_executable(vk_device_pick_test test/vk_device_pick_test.cpp) +target_link_libraries(vk_device_pick_test PRIVATE Vulkan::Headers) +if(BUILD_TESTING) + add_test(NAME vk_device_pick COMMAND vk_device_pick_test) +endif() +# Committed BC* texture zero-initialization via vk.zero_buffer or vk.copy_scratch (D3D-220). +add_executable(vk_bc_zero_init_test test/vk_bc_zero_init_test.cpp) +target_link_libraries(vk_bc_zero_init_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) +if(WIN32) + target_compile_definitions(vk_bc_zero_init_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) +endif() +if(MSVC) + target_compile_options(vk_bc_zero_init_test PRIVATE /W4 /permissive- /utf-8) +endif() +if(BUILD_TESTING) + add_test(NAME vk_bc_zero_init COMMAND vk_bc_zero_init_test) + set_tests_properties(vk_bc_zero_init PROPERTIES SKIP_RETURN_CODE 77) +endif() +# FenceWaitDispatcher concurrency and device-lost regressions (re-entrant callbacks, wakeup on device lost, counter error drain). +add_executable(vk_fence_dispatcher_sync_test test/vk_fence_dispatcher_sync_test.cpp) +target_link_libraries(vk_fence_dispatcher_sync_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) +if(WIN32) + target_compile_definitions(vk_fence_dispatcher_sync_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) +else() + find_package(Threads REQUIRED) + target_link_libraries(vk_fence_dispatcher_sync_test PRIVATE Threads::Threads) +endif() +if(MSVC) + target_compile_options(vk_fence_dispatcher_sync_test PRIVATE /W4 /permissive- /utf-8) +endif() +if(BUILD_TESTING) + add_test(NAME vk_fence_dispatcher_sync COMMAND vk_fence_dispatcher_sync_test) + set_tests_properties(vk_fence_dispatcher_sync PROPERTIES SKIP_RETURN_CODE 77) +endif() +# CPU-only: the bindless set's array sizes from synthetic device limits. +add_executable(bindless_sizing_test test/bindless_sizing_test.cpp) +target_link_libraries(bindless_sizing_test PRIVATE Vulkan::Headers) +if(BUILD_TESTING) + add_test(NAME bindless_sizing COMMAND bindless_sizing_test) +endif() +# CPU-only: a mesh PSO's output, workgroup and shared-memory needs against synthetic device limits (vulkan_mesh_limits.h). +add_executable(vulkan_mesh_limits_test test/vulkan_mesh_limits_test.cpp) +target_link_libraries(vulkan_mesh_limits_test PRIVATE Vulkan::Headers) +if(BUILD_TESTING) + add_test(NAME vulkan_mesh_limits COMMAND vulkan_mesh_limits_test) +endif() +# CPU-only: Vulkan 1.3 core vs 1.2 KHR/EXT feature probing and proc fallback (runtime/src/vulkan13_features.h). +add_executable(vulkan13_features_test test/vulkan13_features_test.cpp) +target_link_libraries(vulkan13_features_test PRIVATE Vulkan::Headers) +if(MSVC) + target_compile_options(vulkan13_features_test PRIVATE /W4 /permissive- /utf-8) +endif() +if(BUILD_TESTING) + add_test(NAME vulkan13_features COMMAND vulkan13_features_test) +endif() +# Buffer registrations keep their binding, VA lookup, and sparse owner in step on host allocation failure. +add_executable(vk_buffer_registration_oom_test test/vk_buffer_registration_oom_test.cpp) +target_link_libraries(vk_buffer_registration_oom_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) +if(WIN32) + target_compile_definitions(vk_buffer_registration_oom_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + if(MSVC) + target_compile_options(vk_buffer_registration_oom_test PRIVATE /W4 /permissive- /EHsc /utf-8) + endif() +endif() +if(BUILD_TESTING) + add_test(NAME vk_buffer_registration_oom COMMAND vk_buffer_registration_oom_test) +endif() +# CPU-only: ScratchBuffers chunk alignment, retire/collect/forget, and spare cap (runtime/src/vulkan_scratch.h). +add_executable(vulkan_scratch_test test/vulkan_scratch_test.cpp) +target_link_libraries(vulkan_scratch_test PRIVATE Vulkan::Headers) +if(MSVC) + target_compile_options(vulkan_scratch_test PRIVATE /W4 /permissive- /utf-8) +endif() +if(BUILD_TESTING) + add_test(NAME vulkan_scratch COMMAND vulkan_scratch_test) +endif() +if(WIN32 AND BUILD_TESTING) + # VulkanPresenter tracker lock / failed-submit rollback and capture-buffer WAW synchronization. + add_executable(vk_presenter_sync_test test/vk_presenter_sync_test.cpp) + target_link_libraries(vk_presenter_sync_test PRIVATE Vulkan::Headers user32) + target_compile_definitions(vk_presenter_sync_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + if(MSVC) + target_compile_options(vk_presenter_sync_test PRIVATE /W4 /permissive- /utf-8) + endif() + add_test(NAME vk_presenter_sync COMMAND vk_presenter_sync_test) + set_tests_properties(vk_presenter_sync PROPERTIES SKIP_RETURN_CODE 77) +endif() +if(NOT Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) + find_program(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE glslangValidator HINTS "$ENV{VULKAN_SDK}/Bin" "$ENV{VULKAN_SDK}/bin") +endif() +if(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) + add_executable(vk_binary_occlusion_test test/vk_binary_occlusion_test.cpp) + target_link_libraries(vk_binary_occlusion_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) + if(WIN32) + target_compile_definitions(vk_binary_occlusion_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + endif() + foreach(stage vert frag) + set(source "${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/binary_occlusion.${stage}") + set(output "${CMAKE_CURRENT_BINARY_DIR}/binary_occlusion.${stage}.spv") + add_custom_command(OUTPUT "${output}" + COMMAND "${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE}" -V --target-env vulkan1.0 + -o "${output}" "${source}" + DEPENDS "${source}" VERBATIM) + target_sources(vk_binary_occlusion_test PRIVATE "${output}") + endforeach() + if(BUILD_TESTING) + add_test(NAME vk_binary_occlusion COMMAND vk_binary_occlusion_test + "${CMAKE_CURRENT_BINARY_DIR}/binary_occlusion.vert.spv" + "${CMAKE_CURRENT_BINARY_DIR}/binary_occlusion.frag.spv") + set_tests_properties(vk_binary_occlusion PROPERTIES SKIP_RETURN_CODE 77) + endif() +endif() diff --git a/runtime/cmake/windows_runtime.cmake b/runtime/cmake/windows_runtime.cmake new file mode 100644 index 000000000..e5fd04c3f --- /dev/null +++ b/runtime/cmake/windows_runtime.cmake @@ -0,0 +1,472 @@ +# The Windows runtime: gta6rt.exe, the libraries its shims link (the root-signature fix, XTaskQueue, the TLS host +# DLL, GameInput on SDL3) and the shim test programs. Their add_test() calls are in runtime_tests.cmake. +# Included by runtime/CMakeLists.txt inside if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME). + +# Custom CMAKE_CXX_FLAGS can replace MSVC's default /EHsc. Require C++ stack unwinding so error +# paths in the runtime and its libraries still destroy automatic objects when an exception leaves a frame. +if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") + add_compile_options($<$:/EHsc>) +endif() + +# The d3d12_xs shim and its tests use version 1.2 root signatures (D3D12_ROOT_SIGNATURE_DESC2), which the Windows +# SDK declares from 10.0.26100 on. Stop here with the fix instead of failing halfway through the build. +include(CheckCXXSourceCompiles) +check_cxx_source_compiles([=[ + #include + int main() { D3D12_VERSIONED_ROOT_SIGNATURE_DESC d{}; d.Version = D3D_ROOT_SIGNATURE_VERSION_1_2; + return static_cast(sizeof(d.Desc_1_2)); } +]=] GTA6RT_SDK_HAS_ROOT_SIGNATURE_1_2) +if(NOT GTA6RT_SDK_HAS_ROOT_SIGNATURE_1_2) + if(CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION) + set(_gta6rt_sdk "${CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION}") + elseif(DEFINED ENV{WindowsSDKVersion}) + string(REGEX REPLACE "[\\/]+$" "" _gta6rt_sdk "$ENV{WindowsSDKVersion}") + else() + set(_gta6rt_sdk "an older one") + endif() + message(FATAL_ERROR + "gta6rt needs the Windows SDK 10.0.26100 or newer (version 1.2 root signatures); " + "this build uses ${_gta6rt_sdk}. Install it with " + "`winget install Microsoft.WindowsSDK.10.0.26100` or the Visual Studio Installer, then delete the build " + "folder and configure again.") +endif() + +# Root-signature flag fix, shared by the d3d12_xs shim and its tests. +add_library(gta6rt_d3d12_xs_rootsig STATIC + shims/d3d12_xs_rootsig.cpp +) +target_include_directories(gta6rt_d3d12_xs_rootsig PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/shims) +target_compile_definitions(gta6rt_d3d12_xs_rootsig PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) +target_compile_options(gta6rt_d3d12_xs_rootsig PRIVATE /W4 /permissive- /utf-8) + +# XTaskQueue/XAsync from microsoft/libHttpClient (MIT), vendored in third_party/xtaskqueue; shims/xtaskqueue/pch.h +# stands in for libHttpClient's pch.h so only the task queue builds. Used by the xgameruntime shim. +set(XTASKQUEUE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../third_party/xtaskqueue) +add_library(gta6rt_xtaskqueue STATIC + ${XTASKQUEUE_DIR}/Source/Task/TaskQueue.cpp + ${XTASKQUEUE_DIR}/Source/Task/AsyncLib.cpp + ${XTASKQUEUE_DIR}/Source/Task/ThreadPool_win32.cpp + ${XTASKQUEUE_DIR}/Source/Task/WaitTimer_win32.cpp +) +target_include_directories(gta6rt_xtaskqueue + PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims/xtaskqueue ${XTASKQUEUE_DIR}/Source/Task ${XTASKQUEUE_DIR}/Source/Common + PUBLIC ${XTASKQUEUE_DIR}/Include) +target_compile_definitions(gta6rt_xtaskqueue PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) +target_compile_options(gta6rt_xtaskqueue PRIVATE /utf-8) # third-party code: its own warning level +target_link_libraries(gta6rt_xtaskqueue PUBLIC ole32) + +# Reserves one loader-assigned module TLS index for mapped images. Loaded from the executable's directory by +# Loader::initialize_tls; its trivial DllMain only keeps the TLS anchor in the image. Built in the same directory as +# the executables that map images, because the loader looks for it next to the running EXE. +add_library(gta6rt_tls_host SHARED src/tls_host.cpp) +target_compile_options(gta6rt_tls_host PRIVATE /W4 /permissive- /utf-8 /GS-) +target_compile_definitions(gta6rt_tls_host PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) +set_target_properties(gta6rt_tls_host PROPERTIES + OUTPUT_NAME gta6rt_tls_host + PREFIX "" + MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>" +) + +add_executable(gta6rt + src/main.cpp + src/host_cpu.cpp + src/pe_loader.cpp + shims/registry.cpp + shims/file_system.cpp + shims/winhttp_offline.cpp + shims/xmem.cpp + shims/xg_xs.cpp + shims/acphal.cpp + shims/d3d12_xs.cpp + shims/d3d12_xs_device.cpp + shims/xgameruntime.cpp + shims/xgameruntime_user.cpp + shims/xgameruntime_gamesave.cpp + shims/xgameruntime_store.cpp + shims/xgameruntime_offline.cpp + shims/library_loader.cpp + shims/process.cpp + shims/com_shim.cpp + shims/bcrypt_rng.cpp + shims/xapu_chad.cpp + shims/dstorage.cpp +) +# dstorage.cpp's guarded_move turns an access violation in a title's buffer into E_DSTORAGE_ACCESS_VIOLATION with +# __try. MSVC always catches it; clang-cl only with asynchronous exceptions (as for tiny_dll below). A source file +# property, so gta6rt and dstorage_test both get it. +set_source_files_properties(shims/dstorage.cpp PROPERTIES COMPILE_OPTIONS "$<$:/EHa>") +add_dependencies(gta6rt gta6rt_tls_host) +target_compile_definitions(gta6rt PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE) +target_compile_options(gta6rt PRIVATE /W4 /permissive- /utf-8) +# Static shim tables register themselves at startup; keep the linker from dropping their objects. +# GTA6RT_HOST_BASE keeps the loader's own image off the default x64 EXE base (0x140000000), where a mapped EXE +# without relocations wants to go. Windows moves the EXE with ASLR anyway; Wine loads it at its preferred base. +set(GTA6RT_HOST_BASE /BASE:0x10000000000) +# BUILD-1457: a thread that asks for no stack size gets the reserve in this program's PE header, 1 MB by default: +# a thread the game starts with dwStackSize 0, a thread-pool thread, a std::thread of the shims. The D3D12 shim +# creates Vulkan pipelines on the calling thread, the driver compiles there, and AMD's Windows compiler (26.11.2) +# overflows 1 MB on some of the game's shaders (docs/pipeline_check.md, "Stack reserve"). run_entry already gives +# the entry thread 8 MB (shims/process_shim.h); this is the same number for the others. Keep it in step with +# scripts/build_runtime.ps1. +set(GTA6RT_STACK 8388608) +target_link_options(gta6rt PRIVATE /OPT:NOREF ${GTA6RT_HOST_BASE} /STACK:${GTA6RT_STACK}) +target_link_libraries(gta6rt PRIVATE gta6rt_core gta6rt_d3d12_xs_rootsig gta6rt_xtaskqueue psapi) + +# Root-signature forwarding test: needs a real PC d3d12.lib to serialize the synthetic descriptors. +# find_library searches %LIB% (a Developer Prompt), not the Windows SDK the Visual Studio generator links +# against, so also look in that SDK's um/x64 folder. +set(_sdk_lib_hints) +if(DEFINED ENV{WindowsSdkDir} AND DEFINED ENV{WindowsSDKLibVersion}) + list(APPEND _sdk_lib_hints "$ENV{WindowsSdkDir}Lib/$ENV{WindowsSDKLibVersion}um/x64") +endif() +get_filename_component(_kits_root + "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots;KitsRoot10]" ABSOLUTE) +if(CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION AND EXISTS "${_kits_root}") + list(APPEND _sdk_lib_hints "${_kits_root}/Lib/${CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION}/um/x64") +endif() +find_library(D3D12_LIBRARY NAMES d3d12 HINTS ${_sdk_lib_hints}) +find_library(DXGI_LIBRARY NAMES dxgi HINTS ${_sdk_lib_hints}) +if(D3D12_LIBRARY) + add_executable(root_sig_test + test/root_sig_test.cpp + shims/registry.cpp + shims/d3d12_xs.cpp + shims/d3d12_xs_device.cpp + ) + target_link_libraries(root_sig_test PRIVATE gta6rt_d3d12_xs_rootsig ${D3D12_LIBRARY}) + target_compile_definitions(root_sig_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(root_sig_test PRIVATE /W4 /permissive- /utf-8) + target_link_options(root_sig_test PRIVATE /OPT:NOREF) + + # RTS0 parser oracle: synthetic descriptors only, serialized by the real PC + # d3d12.dll and parsed back by rt::rootsig::parse_rts0. A layout mismatch + # fails here with the blob bytes, never silently in a draw. + add_executable(root_signature_oracle_test + test/root_signature_oracle_test.cpp + ) + target_link_libraries(root_signature_oracle_test PRIVATE gta6rt_root_signature ${D3D12_LIBRARY}) + target_compile_definitions(root_signature_oracle_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(root_signature_oracle_test PRIVATE /W4 /permissive- /utf-8) + target_link_options(root_signature_oracle_test PRIVATE /OPT:NOREF) + + # Xbox-ABI device proxy test: WARP PC device, no game executable. Needs DXGI for the WARP adapter. + if(DXGI_LIBRARY) + add_executable(device_proxy_test + test/device_proxy_test.cpp + shims/registry.cpp + shims/d3d12_xs.cpp + shims/d3d12_xs_device.cpp + ) + target_link_libraries(device_proxy_test PRIVATE gta6rt_d3d12_xs_rootsig ${D3D12_LIBRARY} ${DXGI_LIBRARY}) + target_compile_definitions(device_proxy_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(device_proxy_test PRIVATE /W4 /permissive- /utf-8) + target_link_options(device_proxy_test PRIVATE /OPT:NOREF) + else() + message(STATUS "dxgi.lib not found: device_proxy_test is not built") + endif() + # The queue and fence proxies over synthetic COM objects: no D3D12 runtime, no GPU. Replaces operator new and + # patches its own import table to inject failures, so the proxy source is compiled into it alone. + add_executable(xs_proxy_mock_test + test/xs_proxy_mock_test.cpp + shims/d3d12_xs_device.cpp + ) + target_compile_definitions(xs_proxy_mock_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(xs_proxy_mock_test PRIVATE /W4 /permissive- /utf-8 /EHsc) +else() + message(STATUS "d3d12.lib not found: root_sig_test and device_proxy_test are not built") +endif() + +# xmem shim ABI test: resolves the registered xmem.dll exports itself, so xmem.cpp and registry.cpp are compiled +# into this executable instead of reusing gta6rt's objects (which would duplicate their symbols). +add_executable(xmem_test + test/xmem_test.cpp + shims/xmem.cpp + shims/registry.cpp +) +target_include_directories(xmem_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) +target_compile_definitions(xmem_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) +target_compile_options(xmem_test PRIVATE /W4 /permissive- /utf-8 $<$:/EHa>) +target_link_options(xmem_test PRIVATE /OPT:NOREF) +target_link_libraries(xmem_test PRIVATE psapi) + +# xg_xs shim: the two exports and the texture computer's slots against the measured call shapes. +add_executable(xg_xs_test + test/xg_xs_test.cpp + shims/xg_xs.cpp + shims/registry.cpp +) +target_include_directories(xg_xs_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) +target_compile_definitions(xg_xs_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) +target_compile_options(xg_xs_test PRIVATE /W4 /permissive- /utf-8) +target_link_options(xg_xs_test PRIVATE /OPT:NOREF) + +# acphal shim ABI test: resolves the registered acphal.dll exports through the registry. +add_executable(acphal_test + test/acphal_test.cpp + shims/acphal.cpp + shims/registry.cpp +) +target_include_directories(acphal_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) +target_compile_definitions(acphal_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) +target_compile_options(acphal_test PRIVATE /W4 /permissive- /utf-8) +target_link_options(acphal_test PRIVATE /OPT:NOREF) + +# The Zen 2 instructions a desktop CPU may lack (src/cpu_emulation.h): decoded, emulated on a CONTEXT, and run for +# real with the #UD handler installed, so an Intel host takes the emulated path and an AMD one the native path. +add_executable(cpu_emulation_test test/cpu_emulation_test.cpp) +target_include_directories(cpu_emulation_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) +target_compile_definitions(cpu_emulation_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) +target_compile_options(cpu_emulation_test PRIVATE /W4 /permissive- /utf-8) + +# Xbox DirectStorage (DStorageGetFactory under dstorage_xs.dll, xcrdapi.dll and dstorage.dll) over synthetic files: +# GAME: paths through the file shims, queues, status arrays, fences and errors. No GPU, no game data. +add_executable(dstorage_test + test/dstorage_test.cpp + shims/dstorage.cpp + shims/file_system.cpp + shims/registry.cpp +) +target_include_directories(dstorage_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) +target_compile_definitions(dstorage_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) +target_compile_options(dstorage_test PRIVATE /W4 /permissive- /utf-8) +target_link_options(dstorage_test PRIVATE /OPT:NOREF) + +# xapu.dll and chad.dll, the APU and audio DSP command queues, resolved through the registry like xmem_test. +add_executable(xapu_chad_test + test/xapu_chad_test.cpp + shims/xapu_chad.cpp + shims/registry.cpp +) +target_include_directories(xapu_chad_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) +target_compile_definitions(xapu_chad_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) +target_compile_options(xapu_chad_test PRIVATE /W4 /permissive- /utf-8) +target_link_options(xapu_chad_test PRIVATE /OPT:NOREF) + +# The process shim's command line: GetCommandLineW must parse (CommandLineToArgvW) back to its __wargv. +add_executable(process_cmdline_test + test/process_cmdline_test.cpp + shims/process.cpp + shims/registry.cpp +) +target_include_directories(process_cmdline_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) +target_compile_definitions(process_cmdline_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) +target_compile_options(process_cmdline_test PRIVATE /W4 /permissive- /utf-8) +target_link_options(process_cmdline_test PRIVATE /OPT:NOREF) +target_link_libraries(process_cmdline_test PRIVATE shell32) + +# Console paths (GAME:) and the write overlay: the file shims resolved through the registry, over temporary folders. +add_executable(file_system_test + test/file_system_test.cpp + shims/file_system.cpp + shims/registry.cpp +) +target_include_directories(file_system_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) +target_compile_definitions(file_system_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) +target_compile_options(file_system_test PRIVATE /W4 /permissive- /utf-8) +target_link_options(file_system_test PRIVATE /OPT:NOREF) +target_link_libraries(file_system_test PRIVATE advapi32) # the ACL calls of the unlistable-marker-folder check + +# loader.skip_int3 (LEONIDA_SKIP_INT3; shims/startup_trace.h): its own executable, the switch is for the whole process. +add_executable(int3_skip_test + test/int3_skip_test.cpp + shims/registry.cpp +) +target_include_directories(int3_skip_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) +target_compile_definitions(int3_skip_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) +target_compile_options(int3_skip_test PRIVATE /W4 /permissive- /utf-8) +target_link_options(int3_skip_test PRIVATE /OPT:NOREF) + +# Offline WinHTTP for mapped images (the package's XCurl.dll and libHttpClient.GDK.dll); no network is touched. +add_executable(winhttp_offline_test + test/winhttp_offline_test.cpp + shims/winhttp_offline.cpp + shims/registry.cpp +) +target_include_directories(winhttp_offline_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) +target_compile_definitions(winhttp_offline_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) +target_compile_options(winhttp_offline_test PRIVATE /W4 /permissive- /utf-8) +target_link_options(winhttp_offline_test PRIVATE /OPT:NOREF) + +# COM lifecycle and helper shims for api-ms-win-core-com-l1-1-*.dll. +add_executable(com_shim_test + test/com_shim_test.cpp + shims/com_shim.cpp + shims/registry.cpp +) +target_include_directories(com_shim_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) +target_compile_definitions(com_shim_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) +target_compile_options(com_shim_test PRIVATE /W4 /permissive- /utf-8) +target_link_options(com_shim_test PRIVATE /OPT:NOREF) + +# BCrypt RNG and algorithm provider shims. +add_executable(bcrypt_rng_test + test/bcrypt_rng_test.cpp + shims/bcrypt_rng.cpp + shims/registry.cpp +) +target_include_directories(bcrypt_rng_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) +target_compile_definitions(bcrypt_rng_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) +target_compile_options(bcrypt_rng_test PRIVATE /W4 /permissive- /utf-8) +target_link_options(bcrypt_rng_test PRIVATE /OPT:NOREF) + +# Synthetic tests for the atomic API reference lifecycle. +add_executable(api_ref_state_test test/api_ref_state_test.cpp) +target_include_directories(api_ref_state_test PRIVATE + ${XTASKQUEUE_DIR}/Source/Task) +target_compile_definitions(api_ref_state_test PRIVATE + WIN32_LEAN_AND_MEAN NOMINMAX) +target_compile_options(api_ref_state_test PRIVATE + /W4 /permissive- /utf-8) +# Verify global reference accounting during task queue teardown. +add_executable(api_global_refs_test test/api_global_refs_test.cpp) +target_compile_definitions(api_global_refs_test PRIVATE + WIN32_LEAN_AND_MEAN NOMINMAX) +target_compile_options(api_global_refs_test PRIVATE + /W4 /permissive- /utf-8) +target_link_libraries(api_global_refs_test PRIVATE + gta6rt_xtaskqueue) +# Offline GDK runtime shim (XGameRuntime, XSystem, XTaskQueue, XAsync), driven through the shim registry the way +# a title calls it at boot. Like xmem_test it compiles its own registry.cpp. +add_executable(xgameruntime_test + test/xgameruntime_test.cpp + shims/xgameruntime.cpp + shims/xgameruntime_user.cpp + shims/xgameruntime_gamesave.cpp + shims/xgameruntime_store.cpp + shims/xgameruntime_offline.cpp + shims/library_loader.cpp + shims/registry.cpp + shims/file_system.cpp +) +target_include_directories(xgameruntime_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) +target_compile_definitions(xgameruntime_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) +target_compile_options(xgameruntime_test PRIVATE /W4 /permissive- /utf-8) +target_link_options(xgameruntime_test PRIVATE /OPT:NOREF) +target_link_libraries(xgameruntime_test PRIVATE gta6rt_xtaskqueue) + +# XUserImpl (offline local user) through QueryApiImpl, slot by slot as xgameruntime.lib's thunks call it. +add_executable(xgameruntime_user_test + test/xgameruntime_user_test.cpp + shims/xgameruntime.cpp + shims/xgameruntime_user.cpp + shims/xgameruntime_gamesave.cpp + shims/xgameruntime_store.cpp + shims/xgameruntime_offline.cpp + shims/library_loader.cpp + shims/registry.cpp + shims/file_system.cpp +) +target_include_directories(xgameruntime_user_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) +target_compile_definitions(xgameruntime_user_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) +target_compile_options(xgameruntime_user_test PRIVATE /W4 /permissive- /utf-8) +target_link_options(xgameruntime_user_test PRIVATE /OPT:NOREF) +target_link_libraries(xgameruntime_user_test PRIVATE gta6rt_xtaskqueue) + +# XGameSaveImpl (offline saves in LEONIDA_SAVE_DIR) through QueryApiImpl, slot by slot. +add_executable(xgameruntime_gamesave_test + test/xgameruntime_gamesave_test.cpp + shims/xgameruntime.cpp + shims/xgameruntime_user.cpp + shims/xgameruntime_gamesave.cpp + shims/xgameruntime_store.cpp + shims/xgameruntime_offline.cpp + shims/library_loader.cpp + shims/registry.cpp + shims/file_system.cpp +) +target_include_directories(xgameruntime_gamesave_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) +target_compile_definitions(xgameruntime_gamesave_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) +target_compile_options(xgameruntime_gamesave_test PRIVATE /W4 /permissive- /utf-8) +target_link_options(xgameruntime_gamesave_test PRIVATE /OPT:NOREF) +target_link_libraries(xgameruntime_gamesave_test PRIVATE gta6rt_xtaskqueue) + +# XStoreImpl (offline: the game is owned, no add-ons, no updates) through QueryApiImpl, slot by slot. +add_executable(xgameruntime_store_test + test/xgameruntime_store_test.cpp + shims/xgameruntime.cpp + shims/xgameruntime_user.cpp + shims/xgameruntime_gamesave.cpp + shims/xgameruntime_store.cpp + shims/xgameruntime_offline.cpp + shims/library_loader.cpp + shims/registry.cpp + shims/file_system.cpp +) +target_include_directories(xgameruntime_store_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) +target_compile_definitions(xgameruntime_store_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) +target_compile_options(xgameruntime_store_test PRIVATE /W4 /permissive- /utf-8) +target_link_options(xgameruntime_store_test PRIVATE /OPT:NOREF) +target_link_libraries(xgameruntime_store_test PRIVATE gta6rt_xtaskqueue) + +# XGameEventImpl, XGameUiImpl, XGameStreamingImpl (offline) through QueryApiImpl. +add_executable(xgameruntime_offline_test + test/xgameruntime_offline_test.cpp + shims/xgameruntime.cpp + shims/xgameruntime_user.cpp + shims/xgameruntime_gamesave.cpp + shims/xgameruntime_store.cpp + shims/xgameruntime_offline.cpp + shims/library_loader.cpp + shims/registry.cpp + shims/file_system.cpp +) +target_include_directories(xgameruntime_offline_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) +target_compile_definitions(xgameruntime_offline_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) +target_compile_options(xgameruntime_offline_test PRIVATE /W4 /permissive- /utf-8) +target_link_options(xgameruntime_offline_test PRIVATE /OPT:NOREF) +target_link_libraries(xgameruntime_offline_test PRIVATE gta6rt_xtaskqueue) + +# GameInput shim on SDL3 (zlib licence): any controller SDL supports, DualSense trigger effects and lightbar. +# Nothing is downloaded unless asked. The shim is built when SDL3 is available: +# - an installed SDL3 3.2+ that find_package finds (SDL3_DIR / CMAKE_PREFIX_PATH), or +# - -DLEONIDA_SDL3_FETCH=ON: download the pinned release below once at configure time (hash-checked) and build it +# static, or -DFETCHCONTENT_SOURCE_DIR_SDL3= to build that copy without downloading. +# Otherwise, or with -DLEONIDA_SDL3=OFF, gta6rt is built without the shim and the loader binds GameInputCreate to the +# host's GameInput.dll or the unimplemented thunk as before. docs/gameinput.md has the details. +option(LEONIDA_SDL3 "Build the GameInput shim when SDL3 is available" ON) +option(LEONIDA_SDL3_FETCH "Download the pinned SDL3 release if no installed SDL3 is found" OFF) +if(LEONIDA_SDL3) + find_package(SDL3 3.2 CONFIG QUIET COMPONENTS SDL3-static NO_SYSTEM_ENVIRONMENT_PATH) + if(NOT TARGET SDL3::SDL3-static AND (LEONIDA_SDL3_FETCH OR FETCHCONTENT_SOURCE_DIR_SDL3)) + include(FetchContent) + FetchContent_Declare(SDL3 + URL https://github.com/libsdl-org/SDL/releases/download/release-3.4.20/SDL3-3.4.20.tar.gz + URL_HASH SHA256=f3bb06f55bed9557227a700af2ea62e49497ebdf58037732a731a5fb3ef8581f + DOWNLOAD_EXTRACT_TIMESTAMP TRUE) + # Only what gamepads need: the joystick, HIDAPI, haptic, sensor and power code, in a static library. + set(SDL_SHARED OFF CACHE BOOL "" FORCE) + set(SDL_STATIC ON CACHE BOOL "" FORCE) + set(SDL_TEST_LIBRARY OFF CACHE BOOL "" FORCE) + set(SDL_TESTS OFF CACHE BOOL "" FORCE) + set(SDL_EXAMPLES OFF CACHE BOOL "" FORCE) + set(SDL_INSTALL OFF CACHE BOOL "" FORCE) + set(SDL_DISABLE_INSTALL ON CACHE BOOL "" FORCE) + foreach(_sdl_off SDL_AUDIO SDL_VIDEO SDL_GPU SDL_RENDER SDL_CAMERA SDL_DIALOG SDL_TRAY) + set(${_sdl_off} OFF CACHE BOOL "" FORCE) + endforeach() + FetchContent_MakeAvailable(SDL3) + endif() +endif() +if(LEONIDA_SDL3 AND TARGET SDL3::SDL3-static) + target_sources(gta6rt PRIVATE shims/gameinput.cpp) + target_link_libraries(gta6rt PRIVATE SDL3::SDL3-static) + + # GameInput through the shim registry on SDL virtual joysticks: no controller, no game data. + add_executable(gameinput_test test/gameinput_test.cpp shims/gameinput.cpp shims/registry.cpp) + # gameinput_probe: the same shim on a real controller, run by hand (not a CTest). + add_executable(gameinput_probe test/gameinput_probe.cpp shims/gameinput.cpp shims/registry.cpp) + foreach(_gi gameinput_test gameinput_probe) + target_include_directories(${_gi} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) + target_compile_definitions(${_gi} PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(${_gi} PRIVATE /W4 /permissive- /utf-8) + target_link_options(${_gi} PRIVATE /OPT:NOREF) + target_link_libraries(${_gi} PRIVATE SDL3::SDL3-static) + endforeach() +else() + if(LEONIDA_SDL3) + message(STATUS "GameInput shim not built: no installed SDL3 found. Set SDL3_DIR, or pass -DLEONIDA_SDL3_FETCH=ON " + "to download the pinned SDL3 release (see docs/gameinput.md)") + else() + message(STATUS "GameInput shim not built (LEONIDA_SDL3=OFF)") + endif() +endif() diff --git a/runtime/core/config.cpp b/runtime/core/config.cpp new file mode 100644 index 000000000..ed046b75a --- /dev/null +++ b/runtime/core/config.cpp @@ -0,0 +1,353 @@ +#include "config.h" + +#include +#include +#include +#include +#include +#include + +#if defined(_WIN32) +#include +#else +#include +#endif + +namespace rt::config { + +namespace { + +// ---- text, paths and the environment ---- + +#if defined(_WIN32) +// Flags 0 in both directions: a character that cannot be converted is replaced, so neither conversion fails. +std::string narrow(std::wstring_view wide) { + if (wide.empty()) return {}; + const int size = WideCharToMultiByte(CP_UTF8, 0, wide.data(), static_cast(wide.size()), nullptr, 0, nullptr, + nullptr); + if (size <= 0) return {}; + std::string text(static_cast(size), '\0'); + WideCharToMultiByte(CP_UTF8, 0, wide.data(), static_cast(wide.size()), text.data(), size, nullptr, nullptr); + return text; +} + +std::wstring widen(std::string_view text) { + if (text.empty()) return {}; + const int size = MultiByteToWideChar(CP_UTF8, 0, text.data(), static_cast(text.size()), nullptr, 0); + if (size <= 0) return {}; + std::wstring wide(static_cast(size), L'\0'); + MultiByteToWideChar(CP_UTF8, 0, text.data(), static_cast(text.size()), wide.data(), size); + return wide; +} + +std::string to_utf8(const std::filesystem::path& p) { return narrow(p.native()); } +std::filesystem::path to_path(std::string_view text) { return std::filesystem::path(widen(text)); } +#else +std::string to_utf8(const std::filesystem::path& p) { return p.string(); } +std::filesystem::path to_path(std::string_view text) { return std::filesystem::path(std::string(text)); } +#endif + +// The variable's value in UTF-8; nullopt when it is unset or empty, which get() treats alike. +std::optional environment(const char* variable) { +#if defined(_WIN32) + // GetEnvironmentVariableW and not getenv: the CRT's copy of the environment does not follow + // SetEnvironmentVariable, which the tests use to set a variable in their own process. The thread's last error + // is put back, because shims read settings in the middle of a call from the title. + const DWORD last_error = GetLastError(); + std::wstring name; + for (const char* c = variable; *c; ++c) name.push_back(static_cast(static_cast(*c))); + std::wstring wide(260, L'\0'); + DWORD length = 0; + for (;;) { + length = GetEnvironmentVariableW(name.c_str(), wide.data(), static_cast(wide.size())); + if (length < wide.size()) break; // 0: unset or empty; else the length without the terminator + wide.resize(static_cast(length) + 1); // too small: `length` is the size the value needs + } + SetLastError(last_error); + if (length == 0) return std::nullopt; + wide.resize(length); + return narrow(wide); +#else + const char* value = std::getenv(variable); + if (!value || !*value) return std::nullopt; + return std::string(value); +#endif +} + +// ---- the loaded file ---- + +struct Loaded { + std::mutex mutex; + FileValues values; + std::filesystem::path file; +}; + +// Never destroyed: a thread of the title may still read a setting while the process exits. +Loaded& loaded() { + static Loaded* const state = new Loaded; + return *state; +} + +// ---- the file format ---- + +constexpr bool is_blank(char c) { return c == ' ' || c == '\t' || c == '\r'; } +constexpr bool is_digit(char c) { return c >= '0' && c <= '9'; } + +std::string_view trim(std::string_view s) { + while (!s.empty() && is_blank(s.front())) s.remove_prefix(1); + while (!s.empty() && is_blank(s.back())) s.remove_suffix(1); + return s; +} + +// A section or setting name as TOML allows it without quotes: letters, digits, _ and -. +bool is_name(std::string_view s) { + if (s.empty()) return false; + for (const char c : s) + if (!(is_digit(c) || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || c == '-')) return false; + return true; +} + +// A number in the forms a setting uses: 30, -1, 1.5, 0x1f. +bool is_number(std::string_view s) { + const bool has_sign = !s.empty() && (s.front() == '+' || s.front() == '-'); + if (has_sign) s.remove_prefix(1); + if (!has_sign && s.size() > 2 && s[0] == '0' && s[1] == 'x') { + for (const char c : s.substr(2)) + if (!(is_digit(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))) return false; + return true; + } + std::size_t i = 0; + while (i < s.size() && is_digit(s[i])) ++i; + if (i == 0) return false; + if (i == s.size()) return true; + if (s[i] != '.') return false; + const std::size_t fraction = ++i; + while (i < s.size() && is_digit(s[i])) ++i; + return i > fraction && i == s.size(); +} + +bool has_section(std::string_view section) { + for (const Setting& setting : kSettings) { + const std::string_view key = setting.key; + if (key.size() > section.size() && key[section.size()] == '.' && key.substr(0, section.size()) == section) + return true; + } + return false; +} + +// True when nothing but a comment follows. +bool ends_here(std::string_view rest) { + rest = trim(rest); + return rest.empty() || rest.front() == '#'; +} + +// The value `rest` starts with, as the text get() returns. False with the reason in *what when it is not a value +// this reader takes or something other than a comment follows it. +bool read_value(std::string_view rest, std::string* value, std::string* what) { + value->clear(); + std::size_t end = 0; + if (rest.empty() || rest.front() == '#') { + *what = "the value after = is missing"; + return false; + } + if (rest.front() == '\'') { + const std::size_t close = rest.find('\'', 1); + if (close == std::string_view::npos) { + *what = "the closing ' is missing"; + return false; + } + value->assign(rest.substr(1, close - 1)); + end = close + 1; + } else if (rest.front() == '"') { + std::size_t i = 1; + for (;; ++i) { + if (i == rest.size()) { + *what = "the closing \" is missing"; + return false; + } + if (rest[i] == '"') break; + if (rest[i] == '\\') { + if (i + 1 == rest.size() || (rest[i + 1] != '\\' && rest[i + 1] != '"')) { + *what = "in double quotes a backslash starts an escape, and only \\\\ and \\\" are read here; " + "write a Windows path in single quotes"; + return false; + } + ++i; + } + value->push_back(rest[i]); + } + end = i + 1; + } else { + while (end < rest.size() && !is_blank(rest[end]) && rest[end] != '#') ++end; + const std::string_view word = rest.substr(0, end); + if (word == "true") *value = "1"; + else if (word == "false") *value = "0"; + else if (is_number(word)) value->assign(word); + else { + *what = "the value must be text in quotes, a number, true or false"; + return false; + } + } + if (!ends_here(rest.substr(end))) { + *what = "only a # comment may follow the value"; + return false; + } + return true; +} + +std::string padded(std::string_view text, std::size_t width) { + std::string out(text); + if (out.size() < width) out.append(width - out.size(), ' '); + return out; +} + +} // namespace + +std::optional Name::find(std::string_view key_or_variable) { + for (std::size_t i = 0; i < kSettingCount; ++i) + if (key_or_variable == kSettings[i].key || key_or_variable == kSettings[i].variable) return at(i); + return std::nullopt; +} + +const char* source_name(Source source) { + switch (source) { + case Source::Environment: return "environment"; + case Source::File: return "file"; + default: return "default"; + } +} + +Value get(Name name) { + const Setting& setting = name.setting(); + if (auto value = environment(setting.variable)) return Value{std::move(*value), Source::Environment}; + { + Loaded& state = loaded(); + const std::lock_guard lock(state.mutex); + if (const auto& value = state.values[name.index()]) return Value{*value, Source::File}; + } + return Value{setting.fallback, Source::Default}; +} + +std::filesystem::path path(Name name) { return to_path(get(name).text); } + +bool parse(std::string_view text, std::string_view file_name, FileValues* values, std::string* error) { + FileValues found; + std::array seen{}; // apart from `found`: a setting set to '' is seen and stays unset + std::vector sections; + std::string_view section; + std::size_t line_number = 0; + const auto fail = [&](const std::string& what) { + if (error) *error = std::string(file_name) + ":" + std::to_string(line_number) + ": " + what; + return false; + }; + + if (text.starts_with("\xEF\xBB\xBF")) text.remove_prefix(3); // a UTF-8 byte order mark, as Notepad writes it + while (!text.empty()) { + ++line_number; + const std::size_t newline = text.find('\n'); + const std::string_view line = trim(text.substr(0, newline)); + text.remove_prefix(newline == std::string_view::npos ? text.size() : newline + 1); + if (line.empty() || line.front() == '#') continue; + + if (line.front() == '[') { + const std::size_t close = line.find(']'); + if (close == std::string_view::npos) return fail("the closing ] is missing"); + const std::string_view name = trim(line.substr(1, close - 1)); + if (!is_name(name) || !has_section(name)) + return fail("there is no section [" + std::string(name) + "]"); + if (!ends_here(line.substr(close + 1))) return fail("only a # comment may follow a [section]"); + for (const std::string_view earlier : sections) + if (earlier == name) return fail("[" + std::string(name) + "] is in the file twice"); + sections.push_back(name); + section = name; + continue; + } + + const std::size_t equals = line.find('='); + const std::string_view name = trim(line.substr(0, equals)); + if (equals == std::string_view::npos || !is_name(name)) return fail("expected [section] or name = value"); + if (section.empty()) return fail("a setting needs its [section] line above it"); + const std::string key = std::string(section) + "." + std::string(name); + const std::size_t index = index_of_key(key); + if (index == kSettingCount) + return fail("there is no setting " + key + "; `gta6rt config` lists the settings"); + if (seen[index]) return fail(key + " is set twice"); + seen[index] = true; + std::string value, what; + if (!read_value(trim(line.substr(equals + 1)), &value, &what)) return fail(key + ": " + what); + if (!value.empty()) found[index] = std::move(value); + } + *values = std::move(found); + return true; +} + +bool load_file(const std::filesystem::path& file, std::string* error) { + const std::string name = to_utf8(file); + std::ifstream in(file, std::ios::binary); + const std::string text{std::istreambuf_iterator(in), std::istreambuf_iterator()}; + if (!in.is_open() || in.bad()) { + if (error) *error = name + ": cannot be read"; + return false; + } + FileValues values; + if (!parse(text, name, &values, error)) return false; + // Absolute, so that the report still names the file after the title has changed the current directory. + std::error_code failed; + std::filesystem::path absolute = std::filesystem::absolute(file, failed); + Loaded& state = loaded(); + const std::lock_guard lock(state.mutex); + state.values = std::move(values); + state.file = failed ? file : std::move(absolute); + return true; +} + +bool load(const std::filesystem::path& program_dir, std::string* error) { + std::error_code ignored; + if (const auto named = environment(kFileVariable)) { + const std::filesystem::path file = to_path(*named); + if (!std::filesystem::is_regular_file(file, ignored)) { + if (error) *error = std::string(kFileVariable) + " names " + *named + ", which is not a file"; + return false; + } + return load_file(file, error); + } + if (program_dir.empty()) return true; + const std::filesystem::path file = program_dir / kFileName; + if (!std::filesystem::is_regular_file(file, ignored)) return true; + return load_file(file, error); +} + +void unload() { + Loaded& state = loaded(); + const std::lock_guard lock(state.mutex); + state.values = {}; + state.file.clear(); +} + +std::filesystem::path loaded_file() { + Loaded& state = loaded(); + const std::lock_guard lock(state.mutex); + return state.file; +} + +std::string report() { + const std::filesystem::path file = loaded_file(); + std::string out = "settings file: "; + out += file.empty() ? std::string("none (") + kFileVariable + ", or " + kFileName + " next to the program)" + : to_utf8(file); + out += '\n'; + std::size_t key_width = 0, variable_width = 0; + for (const Setting& setting : kSettings) { + if (const std::size_t n = std::string_view(setting.key).size(); n > key_width) key_width = n; + if (const std::size_t n = std::string_view(setting.variable).size(); n > variable_width) variable_width = n; + } + for (std::size_t i = 0; i < kSettingCount; ++i) { + const Setting& setting = kSettings[i]; + const Value value = get(Name::at(i)); + out += padded(setting.key, key_width + 2) + padded(source_name(value.source), 13) + + padded(setting.variable, variable_width + 2) + (value.text.empty() ? "(not set)" : value.text) + '\n'; + } + return out; +} + +} // namespace rt::config diff --git a/runtime/core/config.h b/runtime/core/config.h new file mode 100644 index 000000000..c63dbad38 --- /dev/null +++ b/runtime/core/config.h @@ -0,0 +1,188 @@ +// The runtime's settings: one table, looked up one way. +// +// Every setting has a name in leonida.toml ("section.name"), an environment variable and a default. A value is taken +// from the first of these that has one: the environment variable, the file, the default. The environment is read at +// each call and not cached, so a variable that a test or a launcher sets is seen by the next read. The file is read +// once, by load(). +// +// A reader names its setting with a string literal, and the name is checked when the code is compiled: +// +// if (rt::config::get("vulkan.validation").text != "0") ... +// +// A name that is not in kSettings does not build. A new setting gets a row in kSettings, a line in +// leonida.example.toml (test/core_config_test.cpp compares the two) and a line in a document +// (tests/test_docs_env_vars.py). +// +// Nothing here needs windows.h, so it is built and tested on every OS. +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace rt::config { + +struct Setting { + const char* key; // "section.name": [section] and name in leonida.toml + const char* variable; // the environment variable; when set, it wins over the file + const char* fallback; // the default as text; "" when the default is "not set" +}; + +// The defaults repeat what each reader does when nothing is set. What the values mean is in leonida.example.toml, +// runtime/README.md, docs/gameinput.md and docs/d3d12_vulkan.md. +inline constexpr Setting kSettings[] = { + {"paths.game_dir", "LEONIDA_GAME_DIR", ""}, + {"paths.save_dir", "LEONIDA_SAVE_DIR", ""}, + {"paths.shaders", "LEONIDA_SHADERS", ""}, + {"paths.compat_dir", "LEONIDA_COMPAT_DIR", ""}, + + {"loader.unimplemented", "LEONIDA_UNIMPLEMENTED", "log"}, + {"loader.tls_ga_patch", "LEONIDA_TLS_GA_PATCH", "1"}, + {"loader.skip_cpu_check", "LEONIDA_SKIP_CPU_CHECK", "0"}, + {"loader.skip_int3", "LEONIDA_SKIP_INT3", "0"}, + {"loader.rng_seed", "LEONIDA_RNG_SEED", ""}, + + {"log.level", "LEONIDA_LOG", "debug"}, // core/log.h + + {"system.device_type", "LEONIDA_DEVICE_TYPE", "7"}, + {"system.analytics_form", "LEONIDA_ANALYTICS_FORM", ""}, + {"system.package_id", "LEONIDA_PACKAGE_ID", "LeonidaPackageIdentifier00000000"}, + {"system.content_packages", "LEONIDA_CONTENT_PACKAGES", ""}, + {"system.packaged", "LEONIDA_PACKAGED", "1"}, + {"system.gamertag", "LEONIDA_GAMERTAG", "Player"}, + {"system.hdr", "LEONIDA_HDR", "0"}, + {"system.log_game_events", "LEONIDA_LOG_GAME_EVENTS", "0"}, + + {"d3d12.backend", "LEONIDA_D3D12", "host"}, + {"d3d12.xs_trace", "XS_TRACE", "0"}, + {"d3d12.frame_interval_slot", "LEONIDA_XS_FRAME_INTERVAL_SLOT", "78"}, + {"d3d12.schedule_event_slot", "LEONIDA_XS_SCHEDULE_EVENT_SLOT", "79"}, + {"d3d12.wait_event_slot", "LEONIDA_XS_WAIT_EVENT_SLOT", "80"}, + {"d3d12.queue_x_slot", "LEONIDA_XS_QUEUE_X_SLOT", "48"}, + {"d3d12.list_x_slot", "LEONIDA_XS_LIST_X_SLOT", "73"}, + {"d3d12.present_x_slot", "LEONIDA_XS_PRESENT_X_SLOT", ""}, + + {"vulkan.device", "LEONIDA_VK_DEVICE", ""}, + {"vulkan.validation", "LEONIDA_VK_VALIDATION", "0"}, + {"vulkan.max_queues_per_family", "LEONIDA_VK_MAX_QUEUES_PER_FAMILY", "16"}, + {"vulkan.graphics_family_only", "LEONIDA_VK_GRAPHICS_FAMILY_ONLY", "0"}, + {"vulkan.arena_mb", "LEONIDA_ARENA_MB", "256"}, + {"vulkan.arena_log", "LEONIDA_ARENA_LOG", "0"}, + {"vulkan.upload_sysmem", "LEONIDA_UPLOAD_SYSMEM", "0"}, + {"vulkan.bindless_idle_wait", "LEONIDA_BINDLESS_IDLE_WAIT", "0"}, + {"vulkan.rt_as", "LEONIDA_RT_AS", "xdxr"}, + + {"present.sdr_eotf", "LEONIDA_SDR_EOTF", "srgb"}, + {"present.uncap", "LEONIDA_PRESENT_UNCAP", "0"}, + {"present.no_tear", "LEONIDA_PRESENT_NO_TEAR", "0"}, + {"present.capture_dir", "LEONIDA_CAPTURE", ""}, + {"present.capture_every", "LEONIDA_CAPTURE_EVERY", "30"}, + {"present.capture_limit", "LEONIDA_CAPTURE_LIMIT", "24"}, + + {"input.prompts", "LEONIDA_PROMPTS", "auto"}, + {"input.prompts_switch_ms", "LEONIDA_PROMPTS_SWITCH_MS", "300"}, + {"input.ds_triggers", "LEONIDA_DS_TRIGGERS", "rumble"}, + {"input.ds_trigger_gain", "LEONIDA_DS_TRIGGER_GAIN", "1"}, + {"input.ds_trigger_freq", "LEONIDA_DS_TRIGGER_FREQ", "30"}, + {"input.ds_lightbar", "LEONIDA_DS_LIGHTBAR", ""}, + {"input.rumble", "LEONIDA_RUMBLE", "1"}, + {"input.thread", "LEONIDA_GAMEINPUT_THREAD", "1"}, + {"input.keyboard_pad", "LEONIDA_KEYBOARD_PAD", "off"}, + {"input.mouse_sensitivity", "LEONIDA_MOUSE_SENSITIVITY", "1"}, +}; +inline constexpr std::size_t kSettingCount = std::size(kSettings); + +// The settings file: the one this variable names, else kFileName in the folder of the program (load()). +inline constexpr char kFileVariable[] = "LEONIDA_CONFIG"; +inline constexpr char kFileName[] = "leonida.toml"; + +// The row of kSettings with this key; kSettingCount when there is none. +constexpr std::size_t index_of_key(std::string_view key) { + for (std::size_t i = 0; i < kSettingCount; ++i) + if (key == kSettings[i].key) return i; + return kSettingCount; +} + +namespace detail { +// Declared, never defined and not constexpr: Name's constructor reaches it only for a name that is not in kSettings, +// and the compiler reports that as an error at the place that wrote the name. +void this_setting_name_is_not_in_kSettings(); +} // namespace detail + +// A setting, by its key. Made from a string literal at compile time, so a misspelt key is a build error and a read +// costs no search. +class Name { +public: + consteval Name(const char* key) : index_(index_of_key(key)) { + if (index_ == kSettingCount) detail::this_setting_name_is_not_in_kSettings(); + } + + // For a name that is only known at run time (the file reader, a test): by key or by variable. + static std::optional find(std::string_view key_or_variable); + // The setting in row `index` of kSettings; `index` must be below kSettingCount. + static constexpr Name at(std::size_t index) { return Name(index, Row{}); } + + constexpr std::size_t index() const { return index_; } + constexpr const Setting& setting() const { return kSettings[index_]; } + +private: + struct Row {}; + constexpr Name(std::size_t index, Row) : index_(index) {} + + std::size_t index_; +}; + +enum class Source { Default, File, Environment }; + +// "default", "file" or "environment". +const char* source_name(Source source); + +struct Value { + std::string text; // UTF-8 + Source source = Source::Default; // where `text` comes from + + // True when the environment or the file gave the value, false when it is the default. + bool is_set() const { return source != Source::Default; } +}; + +// The setting's value: the environment variable if it is set and not empty, else what the loaded file says, else the +// default. Safe to call from any thread. +Value get(Name name); + +// The same value as a path; empty when the setting is not set. +std::filesystem::path path(Name name); + +// What a settings file sets, one entry per row of kSettings. +using FileValues = std::array, kSettingCount>; + +// Reads `text` as a settings file. The format is the part of TOML the file needs: [section] lines, `name = value` +// lines and # comments, where a value is text in single quotes (taken as written) or double quotes (\\ and \" only), +// a number, or true/false (stored as 1/0). A value of '' leaves the setting unset. +// +// A section or name that is not in kSettings, a name set twice and anything else this reader does not take make it +// return false with ":: " in *error; *values is then unchanged. A misspelt setting is +// therefore an error and not a setting that silently does nothing. +bool parse(std::string_view text, std::string_view file_name, FileValues* values, std::string* error); + +// Reads `file` and makes its values the ones get() falls back on. On failure the values loaded before stay. +bool load_file(const std::filesystem::path& file, std::string* error); + +// What gta6rt does at startup: reads the file kFileVariable names (an error if it does not exist), else +// /leonida.toml if there is one. True when there is no file to read. +bool load(const std::filesystem::path& program_dir, std::string* error); + +// Forgets the loaded file (tests). +void unload(); + +// The file whose values are loaded; empty when none is. +std::filesystem::path loaded_file(); + +// What `gta6rt config` prints: the loaded file, then one line per setting with its key, where its value comes from, +// its variable and the value. +std::string report(); + +} // namespace rt::config diff --git a/runtime/core/log.cpp b/runtime/core/log.cpp new file mode 100644 index 000000000..8e4d09c5c --- /dev/null +++ b/runtime/core/log.cpp @@ -0,0 +1,27 @@ +// rt::log (core/log.h): the level the setting log.level asks for. +#include "log.h" + +#include "config.h" + +namespace rt::log { + +Level level_from_settings(std::string* warning) { + if (warning) warning->clear(); + constexpr rt::config::Name setting("log.level"); + const std::string text = rt::config::get(setting).text; + if (const std::optional named = parse_level(text)) return *named; + // The variable is named also when the value came from the file, as the other readers do. + if (warning) + *warning = std::string("log: ") + setting.setting().variable + "=" + text + " unknown (" + kLevelList + + "), using " + level_name(kDefaultLevel); + return kDefaultLevel; +} + +void apply_settings(bool print_warning) { + std::string warning; + set_level(level_from_settings(&warning)); + // With a warning the level in use is the default, which lets warnings through. + if (print_warning && !warning.empty()) RT_LOG_WARN("%s\n", warning.c_str()); +} + +} // namespace rt::log diff --git a/runtime/core/log.h b/runtime/core/log.h new file mode 100644 index 000000000..abdd3f336 --- /dev/null +++ b/runtime/core/log.h @@ -0,0 +1,100 @@ +// The runtime's log: the "[rt] ..." lines on stderr, each with a level. +// +// RT_LOG_WARN("gameinput: LEONIDA_PROMPTS=%s unknown\n", text.c_str()); +// +// prints "[rt] gameinput: LEONIDA_PROMPTS=... unknown" when the level in use lets warnings through. The first +// argument is a string literal, ": \n" by convention. The macro puts "[rt] " in front of it and hands +// the rest to std::fprintf as written, so the compiler still checks the arguments against the format, a line is one +// fprintf call as it was before the levels, and a line that is held back evaluates none of its arguments. +// +// The levels, in order: off, error, warn, info, debug, trace. A line is printed when its level is at or below the +// level in use. The default is debug: it prints every line the runtime printed before it had levels, and holds +// back only trace lines. There is one level for all modules; a form such as "warn,gameinput=debug" is not read. +// +// The level in use is one value per program. It starts at the default. gta6rt sets it once at startup from the +// setting log.level (LEONIDA_LOG) with apply_settings(). That function and level_from_settings() are in +// core/log.cpp and need gta6rt_core. Everything else is in this header and needs neither gta6rt_core nor windows.h, +// so a header that logs and a test that links no library can include it. A program that does not call +// apply_settings() logs at the default. +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace rt::log { + +enum class Level : int { Off, Error, Warn, Info, Debug, Trace }; + +inline constexpr Level kDefaultLevel = Level::Debug; +// The values log.level takes, as a warning lists them. +inline constexpr char kLevelList[] = "off, error, warn, info, debug or trace"; + +constexpr const char* level_name(Level level) { + switch (level) { + case Level::Off: return "off"; + case Level::Error: return "error"; + case Level::Warn: return "warn"; + case Level::Info: return "info"; + case Level::Debug: return "debug"; + case Level::Trace: return "trace"; + } + return "?"; +} + +// The level `text` names, in any case; nullopt for anything else, also for an empty text. +constexpr std::optional parse_level(std::string_view text) { + constexpr Level all[] = {Level::Off, Level::Error, Level::Warn, Level::Info, Level::Debug, Level::Trace}; + for (const Level level : all) { + const std::string_view name = level_name(level); + if (name.size() != text.size()) continue; + bool same = true; + for (std::size_t i = 0; i < name.size(); ++i) { + const char c = text[i]; + if ((c >= 'A' && c <= 'Z' ? static_cast(c - 'A' + 'a') : c) != name[i]) same = false; + } + if (same) return level; + } + return std::nullopt; +} + +namespace detail { +inline std::atomic g_level{static_cast(kDefaultLevel)}; +} // namespace detail + +// The level in use. Safe to call from any thread. +inline Level level() { return static_cast(detail::g_level.load(std::memory_order_relaxed)); } +inline void set_level(Level level) { detail::g_level.store(static_cast(level), std::memory_order_relaxed); } + +// True when a line of `line_level` is printed at the level in use. Off is not a level a line has: nothing is +// printed for it. +inline bool enabled(Level line_level) { + return line_level != Level::Off && + static_cast(line_level) <= detail::g_level.load(std::memory_order_relaxed); +} + +// ---- in core/log.cpp (gta6rt_core) ---- + +// The level the setting log.level asks for (core/config.h: its variable if set and not empty, else leonida.toml, +// else the default). A value that is not a level gives the default; *warning is then the line that says so, without +// "[rt] " and without a line break, and is empty otherwise. +Level level_from_settings(std::string* warning = nullptr); + +// Makes that level the level in use. A value that is not a level is reported once, as the line +// "[rt] log: ..."; print_warning false leaves that line out, for a program whose parent already printed it. +void apply_settings(bool print_warning = true); + +} // namespace rt::log + +// The first of the variable arguments is the format, a string literal. +#define RT_LOG_AT(level, ...) \ + (::rt::log::enabled(level) ? static_cast(std::fprintf(stderr, "[rt] " __VA_ARGS__)) \ + : static_cast(0)) +#define RT_LOG_ERROR(...) RT_LOG_AT(::rt::log::Level::Error, __VA_ARGS__) +#define RT_LOG_WARN(...) RT_LOG_AT(::rt::log::Level::Warn, __VA_ARGS__) +#define RT_LOG_INFO(...) RT_LOG_AT(::rt::log::Level::Info, __VA_ARGS__) +#define RT_LOG_DEBUG(...) RT_LOG_AT(::rt::log::Level::Debug, __VA_ARGS__) +#define RT_LOG_TRACE(...) RT_LOG_AT(::rt::log::Level::Trace, __VA_ARGS__) diff --git a/runtime/leonida.example.toml b/runtime/leonida.example.toml new file mode 100644 index 000000000..93ea0005c --- /dev/null +++ b/runtime/leonida.example.toml @@ -0,0 +1,190 @@ +# Settings of gta6rt. Copy this file to `leonida.toml` next to gta6rt.exe and change what you need. +# +# A value is taken from the first place that has one: the environment variable named with each setting, then this +# file, then the default. LEONIDA_CONFIG names another file to read in place of the one next to the program. +# `gta6rt config` prints every setting with its value and where the value comes from. +# +# Every setting is listed below with its default, switched off by the "# " in front of it; remove the "# " to set +# it. Text goes in single quotes, which take a Windows path as written ('D:\games\gta6'). Numbers, true and false +# need no quotes. A value of '' means "not set". A name this file format does not know is an error, so a misspelt +# setting cannot go unnoticed. + +[paths] +# LEONIDA_GAME_DIR: the game folder the package's MicrosoftGame.Config is read from. +# Not set: the folder --game-dir names, else the folder of the image. +# game_dir = '' + +# LEONIDA_SAVE_DIR: where saved games go. Not set: %LOCALAPPDATA%\Leonida\saves. +# save_dir = '' + +# LEONIDA_SHADERS: the folder of translated shaders (\shaders\spirv of make_game.py). +# Not set: the folder that shader_path.txt next to the program names. +# shaders = '' + +# LEONIDA_COMPAT_DIR: a folder of compat modules (runtime/README.md, "Compat modules"). Not set: none are used. +# compat_dir = '' + +[loader] +# LEONIDA_UNIMPLEMENTED: what a call to an import without a shim does: 'log', 'fail' or 'stop' (runtime/README.md). +# unimplemented = 'log' + +# LEONIDA_TLS_GA_PATCH: false turns off the loader's TLS rewrite of the image, to measure what the image does +# without it (runtime/README.md, "PE loader"). +# tls_ga_patch = true + +# LEONIDA_SKIP_CPU_CHECK: true skips the AVX check that --init and --run make before any code of the game runs. +# skip_cpu_check = false + +# LEONIDA_SKIP_INT3: a diagnostic for --trace. true logs an int3 in the game's code once per address and steps +# over it. +# skip_int3 = false + +# LEONIDA_RNG_SEED: a number, decimal or hexadecimal with 0x. With it the bcrypt shim returns the same bytes in +# every run. Not set: random bytes from the host. +# rng_seed = '' + +[log] +# LEONIDA_LOG: which of the runtime's "[rt]" lines are printed on stderr: 'off', 'error', 'warn', 'info', 'debug' +# or 'trace'. A level prints its own lines and those of the levels before it. 'debug' prints every line the +# runtime printed before it had levels. +# level = 'debug' + +[system] +# What xgameruntime.dll reports to the title (runtime/README.md, "environment overrides"). + +# LEONIDA_DEVICE_TYPE: the XSystemDeviceType, 0 to 8; 7 is Xbox Series X. +# device_type = 7 + +# LEONIDA_ANALYTICS_FORM: the form string of XSystemGetAnalyticsInfo. Not set: the one the device type gives. +# analytics_form = '' + +# LEONIDA_PACKAGE_ID: the identifier of the running package, up to 32 characters. +# package_id = 'LeonidaPackageIdentifier00000000' + +# LEONIDA_CONTENT_PACKAGES: the content packages XPackageMount can mount, as 'id1=path1;id2=path2'. Not set: none. +# content_packages = '' + +# LEONIDA_PACKAGED: false makes XPackageIsPackagedProcess answer false. +# packaged = true + +# LEONIDA_GAMERTAG: the offline user's gamertag, up to 15 characters of printable ASCII. +# gamertag = 'Player' + +# LEONIDA_HDR: what the title is told when it asks for HDR output (docs/runtime_imports.md, "HDR"). +# false: HDR is reported as disabled. +# hdr = false + +# LEONIDA_LOG_GAME_EVENTS: true logs every event the title writes, with its dimensions and measurements. +# log_game_events = false + +[d3d12] +# LEONIDA_D3D12: the device behind D3D12XboxCreateDevice: 'host' is the D3D12 of this PC, 'vulkan' the runtime's +# D3D12 over Vulkan. +# backend = 'host' + +# XS_TRACE: true logs the first call of each slot of the Xbox device. +# xs_trace = false + +# The slots of the Xbox device's own methods, each 3 to 127 (docs/d3d12_vulkan.md). Change them only for a trace +# that disagrees with the defaults. +# LEONIDA_XS_FRAME_INTERVAL_SLOT: SetFrameIntervalX. +# frame_interval_slot = 78 +# LEONIDA_XS_SCHEDULE_EVENT_SLOT: ScheduleFrameEventX. +# schedule_event_slot = 79 +# LEONIDA_XS_WAIT_EVENT_SLOT: WaitFrameEventX. +# wait_event_slot = 80 +# LEONIDA_XS_QUEUE_X_SLOT: CreateCommandQueueX. +# queue_x_slot = 48 +# LEONIDA_XS_LIST_X_SLOT: CreateCommandListX. +# list_x_slot = 73 + +# LEONIDA_XS_PRESENT_X_SLOT: the slot of PresentX on the Xbox command queue, 19 to 127 (runtime/README.md). Not set: +# no slot is taken for it, and the call is refused with a log line that names the slot the title called. +# present_x_slot = '' + +[vulkan] +# The Vulkan backend (docs/d3d12_vulkan.md). + +# LEONIDA_VK_DEVICE: picks the GPU by its name (runtime/src/vulkan_device_filter.h). Not set: the runtime's choice. +# device = '' + +# LEONIDA_VK_VALIDATION: true runs the device under the Khronos validation layer. +# validation = false + +# LEONIDA_VK_MAX_QUEUES_PER_FAMILY: a test setting, 1 to 16: at most this many Vulkan queues per queue family. +# The game's device ignores it. +# max_queues_per_family = 16 + +# LEONIDA_VK_GRAPHICS_FAMILY_ONLY: a test setting: true puts every D3D12 queue in the graphics family. +# The game's device ignores it. +# graphics_family_only = false + +# LEONIDA_ARENA_MB: the size of the device's memory arena in MiB, at most 4095. +# arena_mb = 256 + +# LEONIDA_ARENA_LOG: true logs every address the arena hands out and every allocation it refuses. +# arena_log = false + +# LEONIDA_UPLOAD_SYSMEM: true keeps upload heaps in system memory on a GPU with Resizable BAR. +# upload_sysmem = false + +# LEONIDA_BINDLESS_IDLE_WAIT: true brings back the old wait before the bindless descriptor set is replaced. +# bindless_idle_wait = false + +# LEONIDA_RT_AS: how acceleration structures are built: 'xdxr' writes the records the game's shaders read, 'khr' +# builds Vulkan's own (docs/bvh.md). +# rt_as = 'xdxr' + +[present] +# LEONIDA_SDR_EOTF: how SDR output is decoded: 'srgb' is piecewise sRGB, 'gamma22' (or '2.2') a pure power of 2.2. +# sdr_eotf = 'srgb' + +# LEONIDA_PRESENT_UNCAP: true takes the frame-rate cap off: frame events return at once and presents do not wait +# for vblank. +# uncap = false + +# LEONIDA_PRESENT_NO_TEAR: true never lets a late frame tear. +# no_tear = false + +# LEONIDA_CAPTURE: a folder. With it, presented frames are also written there as PPM files. Not set: no capture. +# capture_dir = '' + +# LEONIDA_CAPTURE_EVERY: with a capture folder, every how many presented frames one is written. +# capture_every = 30 + +# LEONIDA_CAPTURE_LIMIT: with a capture folder, how many frames are written at most. +# capture_limit = 24 + +[input] +# Controllers, keyboard and mouse (docs/gameinput.md). + +# LEONIDA_PROMPTS: the input family the title is told is in use: 'auto' follows the devices; or 'xbox', +# 'playstation' (or 'ps5'), 'ps4', 'ps3', 'nintendo', 'keyboard'. +# prompts = 'auto' + +# LEONIDA_PROMPTS_SWITCH_MS: the shortest time between two changes of that family, 0 to 2000 ms. +# prompts_switch_ms = 300 + +# LEONIDA_DS_TRIGGERS: DualSense trigger effects: 'off', 'rumble' or 'resistance'. +# ds_triggers = 'rumble' + +# LEONIDA_DS_TRIGGER_GAIN: scales the trigger level before it becomes an effect, 0 to 4. +# ds_trigger_gain = 1 + +# LEONIDA_DS_TRIGGER_FREQ: the vibration frequency of the 'rumble' trigger mode, 1 to 255. +# ds_trigger_freq = 30 + +# LEONIDA_DS_LIGHTBAR: the lightbar colour as 'RRGGBB' (hexadecimal), or 'off'. Not set: SDL's player colour. +# ds_lightbar = '' + +# LEONIDA_RUMBLE: false turns all rumble, trigger and force-feedback output off. +# rumble = true + +# LEONIDA_GAMEINPUT_THREAD: false stops the background poll thread (tests). +# thread = true + +# LEONIDA_KEYBOARD_PAD: the keyboard as a gamepad: 'off'; 'focus' while this program has the focus; 'always'. +# keyboard_pad = 'off' + +# LEONIDA_MOUSE_SENSITIVITY: scales how far the mouse moves the keyboard pad's right stick, 0.1 to 10. +# mouse_sensitivity = 1 diff --git a/runtime/shims/acphal.cpp b/runtime/shims/acphal.cpp index 5ead016d6..6350422d9 100644 --- a/runtime/shims/acphal.cpp +++ b/runtime/shims/acphal.cpp @@ -27,6 +27,7 @@ #include #include +#include "../core/log.h" #include "shims.h" #include "startup_trace.h" @@ -310,8 +311,7 @@ struct AcpHalImpl { (void)d3; static std::atomic warned{false}; if (!warned.exchange(true, std::memory_order_relaxed)) { - std::fprintf(stderr, - "[rt] acphal: command accepted and dropped: no audio DSP hardware on PC\n"); + RT_LOG_WARN("acphal: command accepted and dropped: no audio DSP hardware on PC\n"); } trace_call("AcpHal::SubmitCommand", ""); return S_OK; diff --git a/runtime/shims/bcrypt_rng.cpp b/runtime/shims/bcrypt_rng.cpp index 68dbbf507..2fb346208 100644 --- a/runtime/shims/bcrypt_rng.cpp +++ b/runtime/shims/bcrypt_rng.cpp @@ -21,7 +21,10 @@ using NTSTATUS = LONG; #include #include #include +#include +#include "../core/config.h" +#include "../core/log.h" #include "shims.h" namespace rt::bcrypt_rng { @@ -77,14 +80,14 @@ BOOL CALLBACK init_bcrypt_once(PINIT_ONCE, PVOID, PVOID*) { g_rtl_gen_random = reinterpret_cast(GetProcAddress(adv, "SystemFunction036")); } - char seed_buf[64]{}; - const DWORD len = GetEnvironmentVariableA("LEONIDA_RNG_SEED", seed_buf, static_cast(sizeof(seed_buf))); + // A value of 64 characters or more is not taken as a seed, as before the setting moved to the table. + const std::string seed_text = rt::config::get("loader.rng_seed").text; uint64_t seed = 0; - if (len > 0 && len < sizeof(seed_buf) && parse_u64(seed_buf, seed)) { + if (seed_text.size() < 64 && parse_u64(seed_text.c_str(), seed)) { g_seeded_mode = true; g_prng_state = seed ? seed : 0x9E3779B97F4A7C15ULL; - std::fprintf(stderr, "[rt] bcrypt: deterministic LEONIDA_RNG_SEED enabled (0x%llx)\n", - static_cast(seed)); + RT_LOG_INFO("bcrypt: deterministic LEONIDA_RNG_SEED enabled (0x%llx)\n", + static_cast(seed)); } return TRUE; } diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index 4f4904e96..bd8cd5b75 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -5,6 +5,7 @@ #include "d3d12_fence_waiter.h" #include "d3d12_trace.h" #include "d3d12_xs_device.h" +#include "../core/log.h" #include "../src/gfx10_descriptors.h" #include @@ -67,7 +68,7 @@ void stub(const char* method) { static std::mutex mutex; static std::set seen; std::lock_guard lock(mutex); - if (seen.insert(method).second) std::fprintf(stderr, "[rt] d3d12: unimplemented %s\n", method); + if (seen.insert(method).second) RT_LOG_WARN("d3d12: unimplemented %s\n", method); } namespace { @@ -77,7 +78,7 @@ void note_once(const char* what) { static std::mutex mutex; static std::set seen; std::lock_guard lock(mutex); - if (seen.insert(what).second) std::fprintf(stderr, "[rt] d3d12: %s\n", what); + if (seen.insert(what).second) RT_LOG_WARN("d3d12: %s\n", what); } const char* name(leonida::ReplayResult result) { @@ -1510,7 +1511,7 @@ class Fence final private: bool claim_locked(UINT64 value, bool queue) { if (value <= highest_) { - std::fprintf(stderr, "[rt] d3d12: fence signal %llu is not above %llu; Vulkan timelines cannot go back\n", + RT_LOG_ERROR("d3d12: fence signal %llu is not above %llu; Vulkan timelines cannot go back\n", static_cast(value), static_cast(highest_)); return false; } @@ -1606,15 +1607,13 @@ class CommandQueue final for (UINT i = 0; i < count; ++i) { const GraphicsCommandList* list = GraphicsCommandList::from(lists[i]); if (!list || list->type() == D3D12_COMMAND_LIST_TYPE_BUNDLE) { - std::fprintf(stderr, "[rt] d3d12: ExecuteCommandLists: list %u is not a direct command list\n", i); + RT_LOG_ERROR("d3d12: ExecuteCommandLists: list %u is not a direct command list\n", i); last_result_ = leonida::ReplayResult::unsupported; d3d12_trace::record(method, "failed"); return; } if (list->attached_device() != attached_device()) { - std::fprintf(stderr, - "[rt] d3d12: ExecuteCommandLists: list %u belongs to a different device; refusing batch\n", - i); + RT_LOG_ERROR("d3d12: ExecuteCommandLists: list %u belongs to a different device; refusing batch\n", i); last_result_ = leonida::ReplayResult::unsupported; d3d12_trace::record(method, "failed"); return; @@ -1623,7 +1622,7 @@ class CommandQueue final // message 836): a DIRECT list's draws would otherwise be recorded for a COPY queue's transfer-only // Vulkan family. The whole batch is refused, as for the other checks here. if (list->type() != desc_.Type) { - std::fprintf(stderr, "[rt] d3d12: ExecuteCommandLists: list %u has type %d, the queue type %d\n", i, + RT_LOG_ERROR("d3d12: ExecuteCommandLists: list %u has type %d, the queue type %d\n", i, int(list->type()), int(desc_.Type)); last_result_ = leonida::ReplayResult::unsupported; d3d12_trace::record(method, "failed"); @@ -1631,7 +1630,7 @@ class CommandQueue final } // A list whose recording failed (Close returned E_INVALIDARG) must not replay its earlier commands. if (list->invalid()) { - std::fprintf(stderr, "[rt] d3d12: ExecuteCommandLists: list %u is invalid; refusing batch\n", i); + RT_LOG_ERROR("d3d12: ExecuteCommandLists: list %u is invalid; refusing batch\n", i); last_result_ = leonida::ReplayResult::unsupported; d3d12_trace::record(method, "failed"); return; @@ -1647,8 +1646,7 @@ class CommandQueue final last_result_ = queue_.execute(recorded, [&graphics] { return pin_lists(graphics); }); d3d12_trace::record(method, last_result_ == leonida::ReplayResult::success ? "ok" : "failed"); if (last_result_ != leonida::ReplayResult::success) - std::fprintf(stderr, "[rt] d3d12: ExecuteCommandLists failed: %s; nothing was submitted\n", - name(last_result_)); + RT_LOG_ERROR("d3d12: ExecuteCommandLists failed: %s; nothing was submitted\n", name(last_result_)); } // A copy list's timestamps go to COPY_QUEUE_TIMESTAMP heaps and every other list's to TIMESTAMP heaps. diff --git a/runtime/shims/d3d12_com_object.h b/runtime/shims/d3d12_com_object.h index c7d46d775..f16cb9a04 100644 --- a/runtime/shims/d3d12_com_object.h +++ b/runtime/shims/d3d12_com_object.h @@ -14,6 +14,8 @@ #include #include +#include "../core/log.h" + namespace rt::d3d12 { void stub(const char* method); @@ -39,10 +41,9 @@ class Object : public Stubs { } else if (riid == __uuidof(IUnknown) || ((riid == __uuidof(Interfaces)) || ...)) { *out = static_cast(this); // one inheritance chain: every interface shares this pointer } else { - std::fprintf(stderr, - "[rt] d3d12: QueryInterface: unknown IID {%08lx-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}\n", - static_cast(riid.Data1), riid.Data2, riid.Data3, riid.Data4[0], riid.Data4[1], - riid.Data4[2], riid.Data4[3], riid.Data4[4], riid.Data4[5], riid.Data4[6], riid.Data4[7]); + RT_LOG_WARN("d3d12: QueryInterface: unknown IID {%08lx-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}\n", + static_cast(riid.Data1), riid.Data2, riid.Data3, riid.Data4[0], riid.Data4[1], + riid.Data4[2], riid.Data4[3], riid.Data4[4], riid.Data4[5], riid.Data4[6], riid.Data4[7]); return E_NOINTERFACE; } AddRef(); diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 0273f9339..008be5023 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -15,6 +15,8 @@ #include "d3d12_trace.h" #include "d3d12_xs_device.h" #include "dxgi_com.h" +#include "../core/config.h" +#include "../core/log.h" #include "../src/arena_size.h" #include "../src/gfx10_descriptors.h" #include "../src/depth24_fragment.h" @@ -82,7 +84,7 @@ void log_once(const char* what, int value) { static std::mutex mutex; static std::set> seen; std::lock_guard lock(mutex); - if (seen.insert({what, value}).second) std::fprintf(stderr, "[rt] d3d12: %s %d\n", what, value); + if (seen.insert({what, value}).second) RT_LOG_WARN("d3d12: %s %d\n", what, value); } // Two test settings that make the standalone device look like a GPU with fewer Vulkan queues, so the path where D3D12 @@ -91,37 +93,42 @@ void log_once(const char* what, int value) { // number from 1 to 16: 16). LEONIDA_VK_GRAPHICS_FAMILY_ONLY=1: COMPUTE and COPY queues use the graphics family, as on // a GPU without async compute or transfer families. The game's device ignores both (QueueTestSettings::ignore). -// The setting's value, or false when it is unset; set but ignored, it says so. -bool queue_test_setting(const char* name, char* text, size_t size, rt::d3d12::QueueTestSettings settings) { - size_t length = 0; - if (getenv_s(&length, text, size, name) != 0 || length <= 1) return false; - if (settings == rt::d3d12::QueueTestSettings::apply) return true; - std::fprintf(stderr, "[rt] d3d12: %s is a test setting; the game's device ignores it (all its Vulkan queues)\n", - name); +// The setting's value in *text, or false when nothing sets it (its variable, else leonida.toml); set but ignored, it +// says so, naming the variable also when the value came from the file. `size` is the size of the buffer the variable +// was read into before the settings moved to the table: a value of that many characters or more counts as unset. +bool queue_test_setting(rt::config::Name setting, std::string* text, size_t size, + rt::d3d12::QueueTestSettings settings) { + const rt::config::Value value = rt::config::get(setting); + if (!value.is_set() || value.text.size() >= size) return false; + if (settings == rt::d3d12::QueueTestSettings::apply) { + *text = value.text; + return true; + } + RT_LOG_WARN("d3d12: %s is a test setting; the game's device ignores it (all its Vulkan queues)\n", + setting.setting().variable); return false; } bool graphics_family_only(rt::d3d12::QueueTestSettings settings) { - char text[8] = {}; - const bool on = queue_test_setting("LEONIDA_VK_GRAPHICS_FAMILY_ONLY", text, sizeof(text), settings) && - text[0] != '0'; - if (on) std::fprintf(stderr, "[rt] d3d12: LEONIDA_VK_GRAPHICS_FAMILY_ONLY: every D3D12 queue in the graphics family\n"); + std::string text; + const bool on = queue_test_setting("vulkan.graphics_family_only", &text, 8, settings) && text[0] != '0'; + if (on) RT_LOG_INFO("d3d12: LEONIDA_VK_GRAPHICS_FAMILY_ONLY: every D3D12 queue in the graphics family\n"); return on; } std::uint32_t max_queues_per_family(rt::d3d12::QueueTestSettings settings) { constexpr std::uint32_t most = 16; - char text[16] = {}; - if (!queue_test_setting("LEONIDA_VK_MAX_QUEUES_PER_FAMILY", text, sizeof(text), settings)) return most; + std::string text; + if (!queue_test_setting("vulkan.max_queues_per_family", &text, 16, settings)) return most; char* end = nullptr; - const unsigned long value = std::strtoul(text, &end, 10); - if (end == text || *end || value < 1 || value > most) { - std::fprintf(stderr, "[rt] d3d12: LEONIDA_VK_MAX_QUEUES_PER_FAMILY=%s is not a number from 1 to %u: ignored\n", - text, most); + const unsigned long value = std::strtoul(text.c_str(), &end, 10); + if (end == text.c_str() || *end || value < 1 || value > most) { + RT_LOG_WARN("d3d12: LEONIDA_VK_MAX_QUEUES_PER_FAMILY=%s is not a number from 1 to %u: ignored\n", + text.c_str(), most); return most; } - std::fprintf(stderr, "[rt] d3d12: LEONIDA_VK_MAX_QUEUES_PER_FAMILY: at most %lu Vulkan queue(s) per family\n", - value); + RT_LOG_INFO("d3d12: LEONIDA_VK_MAX_QUEUES_PER_FAMILY: at most %lu Vulkan queue(s) per family\n", + value); return std::uint32_t(value); } @@ -186,17 +193,17 @@ VkPipelineCache create_seeded_pipeline_cache(PFN_vkCreatePipelineCache create_ca const PipelineCacheSeed seed(pipeline_cache_path()); if (!seed.data()) return VK_NULL_HANDLE; if (!seed.compatible(identity)) { - std::fprintf(stderr, "[rt] d3d12: pipeline_cache.bin does not match this Vulkan device\n"); + RT_LOG_WARN("d3d12: pipeline_cache.bin does not match this Vulkan device\n"); return VK_NULL_HANDLE; } const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, nullptr, 0, seed.size(), seed.data()}; VkPipelineCache cache = VK_NULL_HANDLE; if (create_cache(device, &create, nullptr, &cache) != VK_SUCCESS) { - std::fprintf(stderr, "[rt] d3d12: Vulkan declined the pipeline cache seed\n"); + RT_LOG_WARN("d3d12: Vulkan declined the pipeline cache seed\n"); return VK_NULL_HANDLE; } - std::fprintf(stderr, "[rt] d3d12: loaded %zu bytes from pipeline_cache.bin\n", seed.size()); + RT_LOG_INFO("d3d12: loaded %zu bytes from pipeline_cache.bin\n", seed.size()); return cache; } @@ -216,19 +223,18 @@ void report_subgroup_unavailable(const leonida::ShaderEntry& entry, const leonid const bool emulable = entry.stage == "cs" || entry.stage == "ms"; const std::string so_far = names.size() > 1 ? " (shaders of this stage so far: " + std::to_string(names.size()) + ")" : ""; - std::fprintf(stderr, - "[rt] d3d12: %s (%s) is a %u-wide shader but this device cannot require that subgroup size for the " - "stage (device sizes %u..%u, default %u, subgroupSizeControl %s); it runs at the device's size and " - "is inexact where lanes of the other half matter%s\n", - entry.name.c_str(), entry.stage.c_str(), request.wanted, caps.min_size, caps.max_size, - caps.default_size, caps.subgroup_size_control ? "on" : "off", - so_far.c_str()); + RT_LOG_WARN("d3d12: %s (%s) is a %u-wide shader but this device cannot require that subgroup size for the " + "stage (device sizes %u..%u, default %u, subgroupSizeControl %s); it runs at the device's size and " + "is inexact where lanes of the other half matter%s\n", + entry.name.c_str(), entry.stage.c_str(), request.wanted, caps.min_size, caps.max_size, + caps.default_size, caps.subgroup_size_control ? "on" : "off", + so_far.c_str()); if (emulable && request.wanted == 64) - std::fprintf(stderr, "[rt] d3d12: translate wave64 %s shaders with --wave64-emulate for this GPU " - "(make_game.py --wave64-emulate auto does)\n", entry.stage.c_str()); + RT_LOG_WARN("d3d12: translate wave64 %s shaders with --wave64-emulate for this GPU " + "(make_game.py --wave64-emulate auto does)\n", entry.stage.c_str()); else if (request.wanted == 64) - std::fprintf(stderr, "[rt] d3d12: no emulation exists for wave64 %s shaders yet (docs/d3d12_vulkan.md, " - "subgroup size)\n", entry.stage.c_str()); + RT_LOG_WARN("d3d12: no emulation exists for wave64 %s shaders yet (docs/d3d12_vulkan.md, " + "subgroup size)\n", entry.stage.c_str()); } struct Format { @@ -718,13 +724,13 @@ struct DeviceState { arena.use_in_use[use] += bytes; arena.use_peak[use] = std::max(arena.use_peak[use], arena.use_in_use[use]); if (arena.log) - std::fprintf(stderr, "[rt] d3d12: arena %s VA 0x%llx + 0x%llx\n", kArenaUseNames[use], + RT_LOG_DEBUG("d3d12: arena %s VA 0x%llx + 0x%llx\n", kArenaUseNames[use], (unsigned long long)start, (unsigned long long)bytes); return true; } ++arena.failures; if (arena.log) - std::fprintf(stderr, "[rt] d3d12: arena %s: no room for 0x%llx bytes\n", kArenaUseNames[use], + RT_LOG_DEBUG("d3d12: arena %s: no room for 0x%llx bytes\n", kArenaUseNames[use], (unsigned long long)bytes); return false; } @@ -732,7 +738,7 @@ struct DeviceState { // A console VA outside the arena (an upload or readback buffer: its device address minus heap_base). void log_va(const char* what, std::uint64_t va, VkDeviceSize bytes) { if (arena.log) - std::fprintf(stderr, "[rt] d3d12: %s VA 0x%llx + 0x%llx (outside the arena)\n", what, + RT_LOG_DEBUG("d3d12: %s VA 0x%llx + 0x%llx (outside the arena)\n", what, (unsigned long long)va, (unsigned long long)bytes); } @@ -741,14 +747,13 @@ struct DeviceState { std::lock_guard lock(arena.mutex); if (!arena.size) return; const double mib = 1.0 / (1 << 20); - std::fprintf(stderr, - "[rt] d3d12: GPU address arena: peak end %.1f of %.1f MiB (%.1f%%), peak live %.1f MiB " - "(buffers %.1f, descriptor heaps %.1f, shaders %.1f, heaps %.1f), %llu allocations, %llu refused\n", - arena.peak_end * mib, arena.size * mib, 100.0 * double(arena.peak_end) / double(arena.size), - arena.peak_in_use * mib, arena.use_peak[arena_buffer] * mib, - arena.use_peak[arena_descriptor_heap] * mib, arena.use_peak[arena_shader] * mib, - arena.use_peak[arena_heap] * mib, - (unsigned long long)arena.allocations, (unsigned long long)arena.failures); + RT_LOG_INFO("d3d12: GPU address arena: peak end %.1f of %.1f MiB (%.1f%%), peak live %.1f MiB " + "(buffers %.1f, descriptor heaps %.1f, shaders %.1f, heaps %.1f), %llu allocations, %llu refused\n", + arena.peak_end * mib, arena.size * mib, 100.0 * double(arena.peak_end) / double(arena.size), + arena.peak_in_use * mib, arena.use_peak[arena_buffer] * mib, + arena.use_peak[arena_descriptor_heap] * mib, arena.use_peak[arena_shader] * mib, + arena.use_peak[arena_heap] * mib, + (unsigned long long)arena.allocations, (unsigned long long)arena.failures); } void arena_release(VkDeviceSize offset, VkDeviceSize bytes, ArenaUse use) { @@ -785,19 +790,18 @@ struct DeviceState { const std::filesystem::path dir = info.shader_dir.empty() ? configured_shader_directory(&error) : std::filesystem::path(info.shader_dir); if (!error.empty()) - std::fprintf(stderr, "[rt] d3d12: invalid translated shader path: %s\n", error.c_str()); + RT_LOG_ERROR("d3d12: invalid translated shader path: %s\n", error.c_str()); else if (dir.empty()) - std::fprintf(stderr, - "[rt] d3d12: no translated shaders: set LEONIDA_SHADERS to /shaders/spirv\n"); + RT_LOG_WARN("d3d12: no translated shaders: set LEONIDA_SHADERS to /shaders/spirv\n"); else if (!shader_library.load(dir, &error)) - std::fprintf(stderr, "[rt] d3d12: %s\n", error.c_str()); + RT_LOG_ERROR("d3d12: %s\n", error.c_str()); else { const auto path = shader_library.directory().u8string(); - std::fprintf(stderr, "[rt] d3d12: %zu translated shaders from %s\n", - shader_library.size(), reinterpret_cast(path.c_str())); + RT_LOG_INFO("d3d12: %zu translated shaders from %s\n", + shader_library.size(), reinterpret_cast(path.c_str())); } } catch (const std::exception& e) { - std::fprintf(stderr, "[rt] d3d12: invalid translated shader path: %s\n", e.what()); + RT_LOG_ERROR("d3d12: invalid translated shader path: %s\n", e.what()); } } return shader_library.loaded() ? &shader_library : nullptr; @@ -1384,11 +1388,10 @@ struct DeviceState { if (leonida::spilled_to_host(required, preferred, memory.memoryTypes[i].propertyFlags)) std::call_once(spill_logged, [&] { const std::uint32_t heap = memory.memoryTypes[i].heapIndex; - std::fprintf(stderr, - "[rt] d3d12: a %llu-byte allocation did not fit in device-local memory and went " - "to memory type %u (heap %u, %llu MiB); later ones are not logged\n", - static_cast(requirements.size), i, heap, - static_cast(memory.memoryHeaps[heap].size >> 20)); + RT_LOG_WARN("d3d12: a %llu-byte allocation did not fit in device-local memory and went " + "to memory type %u (heap %u, %llu MiB); later ones are not logged\n", + static_cast(requirements.size), i, heap, + static_cast(memory.memoryHeaps[heap].size >> 20)); }); return out; } @@ -2238,6 +2241,20 @@ class Resource final } VkMemoryRequirements requirements{}; vk.vkGetImageMemoryRequirements(device_.info.device, image_, &requirements); + if (host_transfer_ && !requirements.memoryTypeBits) { + // A driver can accept the host-transfer usage and then name no memory type for the image: NVIDIA 582.66 on + // a GTX 1070 Ti answers memoryTypeBits 0 with the usage and 0x82 without it. Make the image again without + // the usage, so its CPU copies take the staging path. + log_once("no memory type for a host-transfer image, using staging copies; format", int(info.format)); + vk.vkDestroyImage(device_.info.device, image_, nullptr); + image_ = VK_NULL_HANDLE; + host_transfer_ = false; + info.usage &= ~VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT; + support = device_.check_image_support(info); + if (FAILED(support)) return support; + if (vk.vkCreateImage(device_.info.device, &info, nullptr, &image_) != VK_SUCCESS) return E_OUTOFMEMORY; + vk.vkGetImageMemoryRequirements(device_.info.device, image_, &requirements); + } memory_ = device_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &memory_flags_); if (!memory_ || vk.vkBindImageMemory(device_.info.device, image_, memory_, 0) != VK_SUCCESS) return E_OUTOFMEMORY; @@ -3537,12 +3554,12 @@ class PipelineState final return !vertex || layout_feeds(e, desc.InputLayout); }); if (!stage.entry) { - std::fprintf(stderr, "[rt] d3d12: no translated %s for FSSM sha256 %s\n", stage.name, hash.c_str()); + RT_LOG_ERROR("d3d12: no translated %s for FSSM sha256 %s\n", stage.name, hash.c_str()); return E_INVALIDARG; } if (stage.entry->binding_count) { if (!device_.bindless) { - std::fprintf(stderr, "[rt] d3d12: %s uses set-0 bindings; the device has no bindless set 0\n", + RT_LOG_ERROR("d3d12: %s uses set-0 bindings; the device has no bindless set 0\n", stage.entry->name.c_str()); return E_NOTIMPL; } @@ -3555,7 +3572,7 @@ class PipelineState final // (docs/d3d12_vulkan.md, "Pipelines"). if (const std::string refusal = leonida::mesh_limit_refusal(*stage.entry, device_.mesh_limits()); !refusal.empty()) { - std::fprintf(stderr, "[rt] d3d12: %s\n", refusal.c_str()); + RT_LOG_ERROR("d3d12: %s\n", refusal.c_str()); return E_NOTIMPL; } } @@ -3593,7 +3610,7 @@ class PipelineState final std::string link_error; if (!leonida::link_f16_halves(vs_stage.words, *vs_stage.entry, ps_stage.words, *ps_stage.entry, &link_error, device_.f16_half_top_location)) { - std::fprintf(stderr, "[rt] d3d12: %s\n", link_error.c_str()); + RT_LOG_ERROR("d3d12: %s\n", link_error.c_str()); return E_FAIL; } } @@ -3606,8 +3623,7 @@ class PipelineState final const VkBool32 allowed = pixel ? device_.info.features.fragmentStoresAndAtomics : device_.info.features.vertexPipelineStoresAndAtomics; if (allowed || !leonida::spirv_declares_writable_storage(stage.words)) continue; - std::fprintf(stderr, - "[rt] d3d12: %s (%s) writes a storage image or buffer, which needs the Vulkan feature %s; " + RT_LOG_ERROR("d3d12: %s (%s) writes a storage image or buffer, which needs the Vulkan feature %s; " "the device does not have it enabled, so the pipeline is refused\n", stage.entry->name.c_str(), stage.name, pixel ? "fragmentStoresAndAtomics" : "vertexPipelineStoresAndAtomics"); @@ -3620,8 +3636,8 @@ class PipelineState final std::string why; std::vector patched = leonida::depth24_patch_fragment(stage.words, depth24_bias, why); if (patched.empty()) { - std::fprintf(stderr, "[rt] d3d12: %s keeps float depth on a D24 target stored as D32: %s\n", - stage.entry->name.c_str(), why.c_str()); + RT_LOG_WARN("d3d12: %s keeps float depth on a D24 target stored as D32: %s\n", + stage.entry->name.c_str(), why.c_str()); depth24_fragment = false; } else { stage.words = std::move(patched); @@ -3708,7 +3724,7 @@ class PipelineState final const bool fed = std::any_of(attributes.begin(), attributes.end(), [&](const auto& a) { return a.location == e.register_index; }); if (!fed) { // D3D12 rejects an input layout that leaves a shader input unfed - std::fprintf(stderr, "[rt] d3d12: the input layout does not feed %s%u (register %u)\n", + RT_LOG_ERROR("d3d12: the input layout does not feed %s%u (register %u)\n", e.semantic.c_str(), e.semantic_index, e.register_index); return E_INVALIDARG; } @@ -3998,10 +4014,10 @@ class PipelineState final if (!entry) { const bool fspx = program.kind == leonida::ComputeProgram::Kind::fspx; if (ambiguous) - std::fprintf(stderr, "[rt] d3d12: FSPX kind-6 program sha256 %s is ambiguous without its kind-0 " - "state: its translations differ\n", leonida::sha256_hex(program.bytes).c_str()); + RT_LOG_ERROR("d3d12: FSPX kind-6 program sha256 %s is ambiguous without its kind-0 " + "state: its translations differ\n", leonida::sha256_hex(program.bytes).c_str()); else - std::fprintf(stderr, "[rt] d3d12: no translated compute shader for %s sha256 %s\n", + RT_LOG_ERROR("d3d12: no translated compute shader for %s sha256 %s\n", fspx ? (program.state.empty() ? "FSPX kind-6" : "FSPX kind-6 and kind-0") : "FSSM", leonida::sha256_hex(program.bytes).c_str()); return E_INVALIDARG; @@ -4009,7 +4025,7 @@ class PipelineState final // Set 0 (bindless images, samplers, the descriptor hash table): the device keeps it, and a pipeline whose // shader declares bindings has it in its layout and has it bound at every dispatch. if (entry->binding_count && !device_.bindless) { - std::fprintf(stderr, "[rt] d3d12: %s uses set-0 bindings; the device has no bindless set 0\n", + RT_LOG_ERROR("d3d12: %s uses set-0 bindings; the device has no bindless set 0\n", entry->name.c_str()); return E_NOTIMPL; } @@ -4024,8 +4040,7 @@ class PipelineState final VkPhysicalDeviceProperties props{}; get_props(dinfo.physical, &props); if (entry->lds_bytes > props.limits.maxComputeSharedMemorySize) { - std::fprintf(stderr, - "[rt] d3d12: %s declares %u bytes of workgroup memory, over the device's " + RT_LOG_ERROR("d3d12: %s declares %u bytes of workgroup memory, over the device's " "maxComputeSharedMemorySize %u\n", entry->name.c_str(), unsigned(entry->lds_bytes), unsigned(props.limits.maxComputeSharedMemorySize)); @@ -4035,7 +4050,7 @@ class PipelineState final } const std::vector words = library->spirv(*entry); if (words.empty()) { - std::fprintf(stderr, "[rt] d3d12: %s.spv is missing or not SPIR-V\n", entry->name.c_str()); + RT_LOG_ERROR("d3d12: %s.spv is missing or not SPIR-V\n", entry->name.c_str()); return E_FAIL; } @@ -5052,14 +5067,15 @@ class Device final state_.probe_uint_backed_uav(VK_FORMAT_B8G8R8A8_SRGB, VK_FORMAT_B8G8R8A8_UNORM); memory_properties(info.physical, &state_.memory); { - char text[4] = {}; - size_t length = 0; - const bool sysmem = getenv_s(&length, text, "LEONIDA_UPLOAD_SYSMEM") == 0 && length > 1 && text[0] != '0'; + // vulkan.upload_sysmem (LEONIDA_UPLOAD_SYSMEM): on for a value that does not start with 0. A value of 4 + // characters or more is ignored, as before the setting moved to the table. + const std::string text = rt::config::get("vulkan.upload_sysmem").text; + const bool sysmem = !text.empty() && text.size() < 4 && text[0] != '0'; state_.upload_in_vram = leonida::resizable_bar(state_.memory) && !sysmem; - std::fprintf(stderr, "[rt] d3d12: upload heaps in %s\n", - state_.upload_in_vram ? "VRAM (DEVICE_LOCAL | HOST_VISIBLE, Resizable BAR)" - : sysmem ? "system memory (LEONIDA_UPLOAD_SYSMEM)" - : "system memory (no Resizable BAR)"); + RT_LOG_INFO("d3d12: upload heaps in %s\n", + state_.upload_in_vram ? "VRAM (DEVICE_LOCAL | HOST_VISIBLE, Resizable BAR)" + : sysmem ? "system memory (LEONIDA_UPLOAD_SYSMEM)" + : "system memory (no Resizable BAR)"); } for (const char* name : {"vkGetDeviceImageMemoryRequirements", "vkGetDeviceImageMemoryRequirementsKHR"}) if (!state_.image_requirements) @@ -5129,7 +5145,7 @@ class Device final }); } if (info.buffer_device_address && state_.context->loaded() && !create_arena()) - std::fprintf(stderr, "[rt] d3d12: the GPU address arena could not be created\n"); + RT_LOG_ERROR("d3d12: the GPU address arena could not be created\n"); if (info.conditional_rendering) { const auto properties = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties")); @@ -5185,7 +5201,7 @@ class Device final }, max_storage_range); } if (info.bindless && state_.context->loaded() && !create_bindless(get_device)) - std::fprintf(stderr, "[rt] d3d12: the bindless set 0 could not be created\n"); + RT_LOG_ERROR("d3d12: the bindless set 0 could not be created\n"); query_luid_and_clock(get_device); // Timestamps: what the one VkQueue every D3D12 queue submits to can write. VkPhysicalDeviceProperties properties{}; @@ -5231,7 +5247,7 @@ class Device final load(labels.queue_end, "vkQueueEndDebugUtilsLabelEXT"); state_.context->enable_debug_labels(labels); if (!state_.context->debug_labels()) - std::fprintf(stderr, "[rt] d3d12: VK_EXT_debug_utils entry points missing; debug markers are off\n"); + RT_LOG_WARN("d3d12: VK_EXT_debug_utils entry points missing; debug markers are off\n"); } const bool sparse_aliasing = state_.context->vk.vkQueueBindSparse && info.features.sparseBinding && @@ -5290,25 +5306,25 @@ class Device final }; if (!leonida::bindless::size_bindings(features, properties.properties.limits, v11, indexed, layout_supported)) - std::fprintf(stderr, "[rt] d3d12: the device's descriptor limits are below the bindless set's default " - "sizes; it holds less\n"); + RT_LOG_WARN("d3d12: the device's descriptor limits are below the bindless set's default " + "sizes; it holds less\n"); } namespace b = leonida::bindless; - std::fprintf(stderr, "[rt] d3d12: bindless set: %u 2D images, %u samplers, %u 2D-array, %u 3D, %u 1D, " - "%u storage indices in 2D\n", - features.counts[b::sampled_binding(leonida::ImageDimension::dim_2d)], - features.counts[b::sampler_binding], - features.counts[b::sampled_binding(leonida::ImageDimension::dim_2d_array)], - features.counts[b::sampled_binding(leonida::ImageDimension::dim_3d)], - features.counts[b::sampled_binding(leonida::ImageDimension::dim_1d)], - features.counts[b::storage_binding(leonida::ImageDimension::dim_2d, 0)]); + RT_LOG_INFO("d3d12: bindless set: %u 2D images, %u samplers, %u 2D-array, %u 3D, %u 1D, " + "%u storage indices in 2D\n", + features.counts[b::sampled_binding(leonida::ImageDimension::dim_2d)], + features.counts[b::sampler_binding], + features.counts[b::sampled_binding(leonida::ImageDimension::dim_2d_array)], + features.counts[b::sampled_binding(leonida::ImageDimension::dim_3d)], + features.counts[b::sampled_binding(leonida::ImageDimension::dim_1d)], + features.counts[b::storage_binding(leonida::ImageDimension::dim_2d, 0)]); // D3D12 promises a shader holds a full shader-visible sampler heap. Past this many distinct S#s, CreateSampler // logs that the array is full and a shader reads the fallback (clamping) sampler. if (features.counts[b::sampler_binding] < D3D12_MAX_SHADER_VISIBLE_SAMPLER_HEAP_SIZE + 1) - std::fprintf(stderr, "[rt] d3d12: the bindless set holds fewer samplers than a full shader-visible " - "sampler heap (%u of %u besides the fallback): its limits or " - "vkGetDescriptorSetLayoutSupport allow no more\n", - features.counts[b::sampler_binding] - 1, unsigned(D3D12_MAX_SHADER_VISIBLE_SAMPLER_HEAP_SIZE)); + RT_LOG_WARN("d3d12: the bindless set holds fewer samplers than a full shader-visible " + "sampler heap (%u of %u besides the fallback): its limits or " + "vkGetDescriptorSetLayoutSupport allow no more\n", + features.counts[b::sampler_binding] - 1, unsigned(D3D12_MAX_SHADER_VISIBLE_SAMPLER_HEAP_SIZE)); state_.bindless = std::make_unique(get_device, state_.info.device, state_.memory, features); if (!state_.bindless->ok() || !state_.context->vk.vkCreateSampler) { state_.bindless.reset(); @@ -5346,8 +5362,8 @@ class Device final constexpr std::size_t max_retired = 8; if (state_.bindless->retired_count() > max_retired) { if (!state_.bindless_cap_logged.exchange(true)) - std::fprintf(stderr, "[rt] d3d12: more than %zu retired bindless table generations: waiting " - "for the queues that still use the oldest\n", max_retired); + RT_LOG_WARN("d3d12: more than %zu retired bindless table generations: waiting " + "for the queues that still use the oldest\n", max_retired); const std::uint64_t oldest = state_.bindless->oldest_retired_ticket(); lock.unlock(); const std::uint64_t completed = context.wait_retire_ticket(oldest); @@ -5367,10 +5383,10 @@ class Device final return state_.bindless ? state_.bindless->set() : VK_NULL_HANDLE; }); { - char text[8] = {}; - size_t length = 0; - state_.bindless_legacy_idle = getenv_s(&length, text, "LEONIDA_BINDLESS_IDLE_WAIT") == 0 && length > 1 && - text[0] != '0'; + // vulkan.bindless_idle_wait (LEONIDA_BINDLESS_IDLE_WAIT): on for a value that does not start with 0. A + // value of 8 characters or more is ignored, as before the setting moved to the table. + const std::string text = rt::config::get("vulkan.bindless_idle_wait").text; + state_.bindless_legacy_idle = !text.empty() && text.size() < 8 && text[0] != '0'; } state_.context->set_bindless_commit([this](bool submitted) { std::lock_guard lock(state_.descriptor_mutex); @@ -5385,9 +5401,11 @@ class Device final bool create_arena() { auto& vk = state_.context->vk; if (!vk.vkGetBufferDeviceAddress) return false; - char text[16] = {}; - size_t length = 0; - const bool set = getenv_s(&length, text, "LEONIDA_ARENA_MB") == 0 && length > 1; + // vulkan.arena_mb (LEONIDA_ARENA_MB): the text goes to decide_arena_size as written. Nothing set, or a value + // of 16 characters or more (ignored, as before the setting moved to the table), gives the default size. + const rt::config::Value arena_mb = rt::config::get("vulkan.arena_mb"); + const bool set = arena_mb.is_set() && arena_mb.text.size() < 16; + const char* text = arena_mb.text.c_str(); const leonida::ArenaLimits limits{state_.info.max_buffer_size, state_.info.max_memory_allocation_size}; leonida::ArenaSize size = leonida::decide_arena_size(set ? text : nullptr, limits); auto& arena = state_.arena; @@ -5429,10 +5447,10 @@ class Device final } } if (size.capped) - std::fprintf(stderr, "[rt] d3d12: GPU address arena: %llu MiB of the %llu MiB asked for, capped by the " - "device's %s\n", - static_cast(size.bytes >> 20), - static_cast(size.requested >> 20), leonida::arena_cap_name(size.capped)); + RT_LOG_WARN("d3d12: GPU address arena: %llu MiB of the %llu MiB asked for, capped by the " + "device's %s\n", + static_cast(size.bytes >> 20), + static_cast(size.requested >> 20), leonida::arena_cap_name(size.capped)); arena.memory = state_.allocate(requirements, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, nullptr, true, &arena.memory_type); @@ -5455,9 +5473,10 @@ class Device final arena.size = info.size; arena.free[kArenaReserved] = arena.size - kArenaReserved; arena.peak_end = kArenaReserved; - char log[4] = {}; - length = 0; - arena.log = getenv_s(&length, log, "LEONIDA_ARENA_LOG") == 0 && length > 1 && log[0] != '0'; + // vulkan.arena_log (LEONIDA_ARENA_LOG): on for a value that does not start with 0. A value of 4 + // characters or more is ignored, as before the setting moved to the table. + const std::string log = rt::config::get("vulkan.arena_log").text; + arena.log = !log.empty() && log.size() < 4 && log[0] != '0'; state_.context->set_heap_base(arena.address); state_.context->set_zero_page(arena.buffer, 0, kArenaReserved); return true; @@ -6022,7 +6041,7 @@ class Device final // the console spills those to memory, in a layout that is still open), and so does this. const rt::rootsig::DecodeResult parsed = rt::rootsig::parse_rts0(bytes, size); if (!parsed.ok) { - std::fprintf(stderr, "[rt] d3d12: root signature not understood: %s\n", parsed.error.c_str()); + RT_LOG_ERROR("d3d12: root signature not understood: %s\n", parsed.error.c_str()); return E_INVALIDARG; } // Two layouts, one per bind point (RootArgumentLayout): graphics keeps pack(), compute takes the console @@ -6030,14 +6049,14 @@ class Device final const rt::rootsig::PackResult packed = rt::rootsig::pack(parsed.sig); const rt::rootsig::StagePackResult compute = rt::rootsig::pack_stage(parsed.sig, rt::rootsig::Stage::Compute); if (!packed.ok && !compute.ok) { - std::fprintf(stderr, "[rt] d3d12: root signature refused: %s (compute: %s)\n", packed.error.c_str(), + RT_LOG_ERROR("d3d12: root signature refused: %s (compute: %s)\n", packed.error.c_str(), compute.error.c_str()); return E_INVALIDARG; } if (!packed.ok) - std::fprintf(stderr, "[rt] d3d12: root signature usable for compute only: %s\n", packed.error.c_str()); + RT_LOG_WARN("d3d12: root signature usable for compute only: %s\n", packed.error.c_str()); if (!compute.ok) - std::fprintf(stderr, "[rt] d3d12: root signature usable for graphics only: %s\n", compute.error.c_str()); + RT_LOG_WARN("d3d12: root signature usable for graphics only: %s\n", compute.error.c_str()); RootArgumentLayout layout; layout.flags = parsed.sig.flags; layout.graphics_ok = packed.ok; @@ -8745,7 +8764,7 @@ class Device final const auto transition = reinterpret_cast(get_device(dev, "vkTransitionImageLayoutEXT")); if (!properties2 || !state_.format_properties2 || !to_image || !to_memory || !transition) { - std::fprintf(stderr, "[rt] d3d12: VK_EXT_host_image_copy entry points missing; using staging copies\n"); + RT_LOG_WARN("d3d12: VK_EXT_host_image_copy entry points missing; using staging copies\n"); return; } VkPhysicalDeviceHostImageCopyPropertiesEXT host{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_HOST_IMAGE_COPY_PROPERTIES_EXT}; @@ -8759,7 +8778,7 @@ class Device final return std::find(layouts.begin(), layouts.end(), VK_IMAGE_LAYOUT_GENERAL) != layouts.end(); }; if (!general(src) || !general(dst)) { - std::fprintf(stderr, "[rt] d3d12: host image copies do not accept GENERAL; using staging copies\n"); + RT_LOG_WARN("d3d12: host image copies do not accept GENERAL; using staging copies\n"); return; } state_.copy_memory_to_image = to_image; @@ -9079,7 +9098,7 @@ WindowPresenter::~WindowPresenter() { namespace { HRESULT present_result(VkResult result) { if (result == VK_SUCCESS) return S_OK; - std::fprintf(stderr, "[rt] d3d12: present failed (VkResult %d)\n", int(result)); + RT_LOG_ERROR("d3d12: present failed (VkResult %d)\n", int(result)); if (result == VK_ERROR_DEVICE_LOST) return DXGI_ERROR_DEVICE_REMOVED; if (result == VK_ERROR_FORMAT_NOT_SUPPORTED) return DXGI_ERROR_UNSUPPORTED; return E_FAIL; @@ -9173,13 +9192,13 @@ std::unique_ptr create_window_presenter(ID3D12Device* device, H ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); Device* d = Device::from(real ? real : device); if (device && !d) - std::fprintf(stderr, "[rt] d3d12: create_window_presenter: %p is neither the Xbox device proxy nor a device of " - "this layer; no presenter\n", + RT_LOG_ERROR("d3d12: create_window_presenter: %p is neither the Xbox device proxy nor a device of " + "this layer; no presenter\n", static_cast(device)); if (!d || !window) return nullptr; const VulkanDeviceInfo& info = d->state().info; if (!info.presentation) { - std::fprintf(stderr, "[rt] d3d12: the Vulkan device was created without presentation support\n"); + RT_LOG_ERROR("d3d12: the Vulkan device was created without presentation support\n"); return nullptr; } const auto create_surface = reinterpret_cast( @@ -9192,15 +9211,15 @@ std::unique_ptr create_window_presenter(ID3D12Device* device, H if (create_surface(info.instance, &surface_info, nullptr, &surface) != VK_SUCCESS) return nullptr; // LEONIDA_PRESENT_NO_TEAR=1 keeps the swapchain FIFO-only (ImmediateThresholdPercent then does nothing). // Any non-empty value other than "0" turns it off. - bool tear_allowed = true; - { - char* value = nullptr; - std::size_t length = 0; - if (_dupenv_s(&value, &length, "LEONIDA_PRESENT_NO_TEAR") == 0 && value) { - tear_allowed = value[0] == '\0' || std::strcmp(value, "0") == 0; - std::free(value); - } - } + const std::string no_tear = rt::config::get("present.no_tear").text; + const bool tear_allowed = no_tear.empty() || no_tear == "0"; + // present.capture_dir, present.capture_every and present.capture_limit (LEONIDA_CAPTURE, LEONIDA_CAPTURE_EVERY, + // LEONIDA_CAPTURE_LIMIT): the presenter writes presented frames to that folder (src/vulkan_present.h). The two + // numbers are read with atoi and raised to 1 by the presenter, as before the settings moved to the table. + leonida::PresentCapture capture; + capture.dir = rt::config::path("present.capture_dir"); + capture.every = std::atoi(rt::config::get("present.capture_every").text.c_str()); + capture.limit = std::atoi(rt::config::get("present.capture_limit").text.c_str()); auto presenter = std::make_unique(*d->state().context, info.get_instance_proc, info.instance, info.physical, info.queue, info.queue_family, surface, // owns the surface @@ -9227,9 +9246,10 @@ std::unique_ptr create_window_presenter(ID3D12Device* device, H &made) != VK_SUCCESS) return VK_NULL_HANDLE; return made; - }); + }, + std::move(capture)); if (!presenter->ok()) { - std::fprintf(stderr, "[rt] d3d12: cannot present to this window from the device's queue family\n"); + RT_LOG_ERROR("d3d12: cannot present to this window from the device's queue family\n"); return nullptr; } auto window_presenter = std::make_unique(d->holder(), std::move(presenter)); @@ -9271,7 +9291,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin reinterpret_cast(GetProcAddress(library, "vkGetInstanceProcAddr"))) : nullptr; if (!get) { - std::fprintf(stderr, "[rt] d3d12: vulkan-1.dll not found\n"); + RT_LOG_ERROR("d3d12: vulkan-1.dll not found\n"); return E_FAIL; } const auto create_instance = reinterpret_cast(get(nullptr, "vkCreateInstance")); @@ -9326,9 +9346,10 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin VkValidationFeaturesEXT validation_features{VK_STRUCTURE_TYPE_VALIDATION_FEATURES_EXT}; validation_features.enabledValidationFeatureCount = 1; validation_features.pEnabledValidationFeatures = &sync_validation; - char validation[8] = {}; - size_t length = 0; - if (getenv_s(&length, validation, "LEONIDA_VK_VALIDATION") == 0 && length > 1 && validation[0] != '0') { + // vulkan.validation (LEONIDA_VK_VALIDATION): on for a value that does not start with 0. A value of 8 characters + // or more is ignored, as before the setting moved to the table. + const std::string validation = rt::config::get("vulkan.validation").text; + if (!validation.empty() && validation.size() < 8 && validation[0] != '0') { // Ask for the layer only when the loader lists it, and say so when it does not: an instance that cannot be // made because of a missing layer left the caller with "Vulkan unavailable" and no hint that validation was // the cause. Wine does not list the Linux loader's layers to the program and refuses an explicit request for @@ -9348,8 +9369,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin instance_info.enabledLayerCount = 1; instance_info.ppEnabledLayerNames = &layer; } else { - std::fprintf(stderr, - "[rt] d3d12: LEONIDA_VK_VALIDATION is set but %s is not listed by the Vulkan loader " + RT_LOG_ERROR("d3d12: LEONIDA_VK_VALIDATION is set but %s is not listed by the Vulkan loader " "(install the Vulkan SDK; under Wine set VK_INSTANCE_LAYERS=%s instead)\n", layer, layer); return E_FAIL; @@ -9373,12 +9393,12 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin instance_info.ppEnabledExtensionNames = inst_exts.empty() ? nullptr : inst_exts.data(); OwnedRuntime owned{}; if (create_instance(&instance_info, nullptr, &owned.instance) != VK_SUCCESS) { - std::fprintf(stderr, "[rt] d3d12: vkCreateInstance (Vulkan 1.3) failed\n"); + RT_LOG_ERROR("d3d12: vkCreateInstance (Vulkan 1.3) failed\n"); return E_FAIL; } owned.destroy_instance = reinterpret_cast(get(owned.instance, "vkDestroyInstance")); const auto fail = [&](const char* why) { - std::fprintf(stderr, "[rt] d3d12: %s\n", why); + RT_LOG_ERROR("d3d12: %s\n", why); owned.destroy_instance(owned.instance, nullptr); return E_FAIL; }; @@ -9411,10 +9431,13 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin // The first usable device of the highest vulkan_device_rank: a native driver over Microsoft's Dozen (which says // it is a discrete GPU, #915), then discrete over integrated; the test harnesses (vk_device_pick.h) pick the same. int chosen_rank = -1; + // vulkan.device (LEONIDA_VK_DEVICE, else leonida.toml): part of the device's name, compared without case + // (src/vulkan_device_filter.h). Nothing set takes every device. + const std::string device_filter = leonida::vulkan_device_filter_of(rt::config::get("vulkan.device").text); for (VkPhysicalDevice candidate : physicals) { VkPhysicalDeviceProperties props{}; vkGetPhysicalDeviceProperties(candidate, &props); - if (!leonida::vulkan_device_wanted(props.deviceName)) continue; + if (!leonida::vulkan_device_wanted(props.deviceName, device_filter)) continue; candidate13.query(candidate, props.apiVersion, vkGetPhysicalDeviceFeatures2, vkEnumerateDeviceExtensionProperties); if (!candidate13.usable()) continue; VkPhysicalDeviceVulkan11Features f11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES}; @@ -9446,17 +9469,17 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin } } if (!info.physical) - return fail(leonida::vulkan_device_filter().empty() + return fail(device_filter.empty() ? "no Vulkan 1.3 GPU (or 1.2 with VK_KHR_dynamic_rendering and VK_KHR_synchronization2) with " "dynamicRendering, synchronization2, timelineSemaphore and separateDepthStencilLayouts" : "no GPU named by LEONIDA_VK_DEVICE has Vulkan 1.3 (or 1.2 with VK_KHR_dynamic_rendering and " "VK_KHR_synchronization2) with dynamicRendering, synchronization2, timelineSemaphore and " "separateDepthStencilLayouts"); if (!v13.core) - std::fprintf(stderr, "[rt] d3d12: Vulkan 1.2 device: dynamicRendering and synchronization2 through their KHR " - "extensions; %s\n", - v13.extended_dynamic_state ? "extended dynamic state through VK_EXT_extended_dynamic_state(2)" - : "no extended dynamic state, so no graphics pipelines"); + RT_LOG_INFO("d3d12: Vulkan 1.2 device: dynamicRendering and synchronization2 through their KHR " + "extensions; %s\n", + v13.extended_dynamic_state ? "extended dynamic state through VK_EXT_extended_dynamic_state(2)" + : "no extended dynamic state, so no graphics pipelines"); // VK_EXT_conditional_rendering for SetPredication, VK_KHR_swapchain for DXGI presentation, and optional // VK_KHR_acceleration_structure + VK_KHR_ray_query for hardware BVH builds (BLAS + TLAS). @@ -9493,7 +9516,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin } } if (!info.mesh_shader) - std::fprintf(stderr, "[rt] d3d12: the GPU has no VK_EXT_mesh_shader: mesh-shader PSOs are unsupported\n"); + RT_LOG_WARN("d3d12: the GPU has no VK_EXT_mesh_shader: mesh-shader PSOs are unsupported\n"); if (has_as && has_dho && has_rq && chosen12.bufferDeviceAddress) { as_features.pNext = &rq_features; VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &as_features}; @@ -9502,16 +9525,13 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin } // The game's translated RT shaders read XDXR BVH4 records, which a VkAccelerationStructureKHR is not // (docs/d3d12_vulkan.md 4.8): build those, unless LEONIDA_RT_AS=khr asks for #743's KHR builds instead. - char rt_as[8] = {}; - std::size_t rt_as_length = 0; - const bool khr = getenv_s(&rt_as_length, rt_as, "LEONIDA_RT_AS") == 0 && rt_as_length > 1 && - std::strcmp(rt_as, "khr") == 0; + const bool khr = rt::config::get("vulkan.rt_as").text == "khr"; if (!khr && chosen12.bufferDeviceAddress) { info.xdxr_acceleration_structures = true; info.ray_tracing = false; // no KHR extensions: AS resources keep their console VAs } if (!info.conditional_rendering) - std::fprintf(stderr, "[rt] d3d12: the GPU has no VK_EXT_conditional_rendering: SetPredication is unsupported\n"); + RT_LOG_WARN("d3d12: the GPU has no VK_EXT_conditional_rendering: SetPredication is unsupported\n"); } VkPhysicalDeviceConditionalRenderingFeaturesEXT enable_conditional{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONDITIONAL_RENDERING_FEATURES_EXT}; @@ -9550,7 +9570,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin VkPhysicalDeviceVulkan11Features enable11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, v13.enable(ext_chain)}; enable11.shaderDrawParameters = chosen_draw_params ? VK_TRUE : VK_FALSE; - if (!chosen_draw_params) std::fprintf(stderr, "[rt] d3d12: the GPU has no shaderDrawParameters\n"); + if (!chosen_draw_params) RT_LOG_WARN("d3d12: the GPU has no shaderDrawParameters\n"); VkPhysicalDeviceVulkan12Features enable12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &enable11}; enable12.timelineSemaphore = VK_TRUE; enable12.separateDepthStencilLayouts = VK_TRUE; @@ -9581,7 +9601,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin enable12.shaderOutputLayer = info.shader_output_layer; enable12.shaderOutputViewportIndex = info.shader_output_viewport_index; if (!info.bindless) - std::fprintf(stderr, "[rt] d3d12: the GPU lacks a descriptor-indexing feature the bindless set needs\n"); + RT_LOG_WARN("d3d12: the GPU lacks a descriptor-indexing feature the bindless set needs\n"); enable12.bufferDeviceAddress = VK_TRUE; info.buffer_device_address = true; std::uint32_t family_count = 0; @@ -9640,13 +9660,13 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin enable.shaderSampledImageArrayDynamicIndexing = info.bindless; enable.shaderStorageImageArrayDynamicIndexing = info.bindless; if (!chosen_features.shaderInt64) - std::fprintf(stderr, "[rt] d3d12: the GPU has no shaderInt64; translated shaders (all declare Int64) will not load\n"); + RT_LOG_WARN("d3d12: the GPU has no shaderInt64; translated shaders (all declare Int64) will not load\n"); enable.samplerAnisotropy = info.sampler_anisotropy; enable.occlusionQueryPrecise = chosen_features.occlusionQueryPrecise; // exact D3D12 occlusion counts enable.pipelineStatisticsQuery = chosen_features.pipelineStatisticsQuery; info.occlusion_query_precise = chosen_features.occlusionQueryPrecise == VK_TRUE; info.pipeline_statistics_query = chosen_features.pipelineStatisticsQuery == VK_TRUE; - if (!chosen_bc) std::fprintf(stderr, "[rt] d3d12: the GPU has no BC texture support\n"); + if (!chosen_bc) RT_LOG_WARN("d3d12: the GPU has no BC texture support\n"); const char* conditional_extension = VK_EXT_CONDITIONAL_RENDERING_EXTENSION_NAME; // Optional: VK_EXT_host_image_copy lets WriteToSubresource/ReadFromSubresource copy on the CPU. @@ -9714,7 +9734,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin host_copy.pNext = *v13.next(); // after the conditional rendering features, if any *v13.next() = &host_copy; } else { - std::fprintf(stderr, "[rt] d3d12: no VK_EXT_host_image_copy; CPU texture copies use a staging submit\n"); + RT_LOG_WARN("d3d12: no VK_EXT_host_image_copy; CPU texture copies use a staging submit\n"); } // The pixel-shader extensions translated shaders can declare (VulkanDeviceInfo::fragment_shader_barycentric and @@ -9877,8 +9897,8 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin custom_border.pNext = *v13.next(); // where later feature structs go since #1706 *v13.next() = &custom_border; } else { - std::fprintf(stderr, - "[rt] d3d12: no VK_EXT_custom_border_color; custom sampler border colours fall back to transparent black\n"); + RT_LOG_WARN( + "d3d12: no VK_EXT_custom_border_color; custom sampler border colours fall back to transparent black\n"); } // Optional: VK_EXT_external_memory_host lets OpenExistingHeapFromAddress import the caller's committed memory as @@ -9958,19 +9978,17 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin info.queue = info.command_queues[0]; info.max_push_constants_size = chosen.limits.maxPushConstantsSize; info.push_constants_need_fallback = (info.max_push_constants_size < 144); - std::fprintf(stderr, "[rt] d3d12: Vulkan device: %s (maxPushConstantsSize: %u bytes)\n", chosen.deviceName, - chosen.limits.maxPushConstantsSize); - std::fprintf(stderr, - "[rt] d3d12: subgroup sizes %u..%u (default %u), requirable in stages 0x%x, subgroupSizeControl %s, " - "computeFullSubgroups %s\n", - info.subgroup.min_size, info.subgroup.max_size, info.subgroup.default_size, - unsigned(info.subgroup.required_stages), info.subgroup.subgroup_size_control ? "on" : "off", - info.subgroup.compute_full_subgroups ? "on" : "off"); + RT_LOG_INFO("d3d12: Vulkan device: %s (maxPushConstantsSize: %u bytes)\n", chosen.deviceName, + chosen.limits.maxPushConstantsSize); + RT_LOG_INFO("d3d12: subgroup sizes %u..%u (default %u), requirable in stages 0x%x, subgroupSizeControl %s, " + "computeFullSubgroups %s\n", + info.subgroup.min_size, info.subgroup.max_size, info.subgroup.default_size, + unsigned(info.subgroup.required_stages), info.subgroup.subgroup_size_control ? "on" : "off", + info.subgroup.compute_full_subgroups ? "on" : "off"); if (info.push_constants_need_fallback) { - std::fprintf(stderr, - "[rt] d3d12: WARNING: GPU maxPushConstantsSize (%u bytes) is below the 144 bytes required by " - "the shader contract; uniform-buffer fallback required for the 16-byte tail\n", - chosen.limits.maxPushConstantsSize); + RT_LOG_WARN("d3d12: WARNING: GPU maxPushConstantsSize (%u bytes) is below the 144 bytes required by " + "the shader contract; uniform-buffer fallback required for the 16-byte tail\n", + chosen.limits.maxPushConstantsSize); } auto* device = new Device(info); @@ -10031,15 +10049,8 @@ HRESULT create_console_descriptor_heap(ID3D12Device* device, const D3D12_DESCRIP std::filesystem::path configured_shader_directory(std::string* error, const std::filesystem::path& config) { try { - constexpr wchar_t env_name[] = L"LEONIDA_SHADERS"; - if (const DWORD size = ::GetEnvironmentVariableW(env_name, nullptr, 0)) { - std::wstring value(size, L'\0'); - const DWORD length = ::GetEnvironmentVariableW(env_name, value.data(), size); - if (length && length < size) { - value.resize(length); - return std::filesystem::path(value); - } - } + // paths.shaders (LEONIDA_SHADERS, else leonida.toml) wins over shader_path.txt. + if (std::filesystem::path shaders = rt::config::path("paths.shaders"); !shaders.empty()) return shaders; if (!config.empty()) return shader_directory_from_file(config); std::wstring exe(32768, L'\0'); const DWORD length = ::GetModuleFileNameW(nullptr, exe.data(), static_cast(exe.size())); diff --git a/runtime/shims/d3d12_xs.cpp b/runtime/shims/d3d12_xs.cpp index 01a1d534b..fa65a6849 100644 --- a/runtime/shims/d3d12_xs.cpp +++ b/runtime/shims/d3d12_xs.cpp @@ -15,6 +15,8 @@ #include #include +#include "../core/config.h" +#include "../core/log.h" #ifdef LEONIDA_VULKAN_DEVICE #include "d3d12_com.h" #endif @@ -28,7 +30,7 @@ namespace { FARPROC host(const char* name) { static HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); FARPROC p = d3d12 ? GetProcAddress(d3d12, name) : nullptr; - if (!p) std::fprintf(stderr, "[rt] d3d12_xs: host d3d12.dll has no %s\n", name); + if (!p) RT_LOG_ERROR("d3d12_xs: host d3d12.dll has no %s\n", name); return p; } @@ -61,10 +63,9 @@ HRESULT WINAPI serialize_root_signature(const D3D12_VERSIONED_ROOT_SIGNATURE_DES D3D12_VERSIONED_ROOT_SIGNATURE_DESC cleared{}; if (!rt::d3d12_xs::copy_versioned_root_signature_desc_clear_xbox_flags(*desc, cleared)) { - std::fprintf(stderr, - "[rt] d3d12_xs: D3D12SerializeVersionedRootSignature: unknown descriptor version %d; " - "forwarding unchanged (Xbox flags not cleared)\n", - static_cast(desc->Version)); + RT_LOG_WARN("d3d12_xs: D3D12SerializeVersionedRootSignature: unknown descriptor version %d; " + "forwarding unchanged (Xbox flags not cleared)\n", + static_cast(desc->Version)); return fn(desc, blob, error); } if (cleared.Version == D3D_ROOT_SIGNATURE_VERSION_1_2 && !host_serializes_1_2(fn)) { @@ -72,8 +73,7 @@ HRESULT WINAPI serialize_root_signature(const D3D12_VERSIONED_ROOT_SIGNATURE_DES std::vector samplers; D3D12_VERSIONED_ROOT_SIGNATURE_DESC v11{}; if (!rt::d3d12_xs::downgrade_root_signature_1_2_to_1_1(cleared, samplers, v11)) { - std::fprintf(stderr, - "[rt] d3d12_xs: D3D12SerializeVersionedRootSignature: version 1.2 with static sampler flags, " + RT_LOG_ERROR("d3d12_xs: D3D12SerializeVersionedRootSignature: version 1.2 with static sampler flags, " "and the host d3d12.dll serializes only up to 1.1; refused\n"); if (blob) *blob = nullptr; if (error) *error = nullptr; @@ -81,9 +81,8 @@ HRESULT WINAPI serialize_root_signature(const D3D12_VERSIONED_ROOT_SIGNATURE_DES } static std::atomic logged{false}; if (!logged.exchange(true)) - std::fprintf(stderr, - "[rt] d3d12_xs: the host d3d12.dll serializes root signatures only up to 1.1; version 1.2 " - "descriptions without static sampler flags are serialized as 1.1\n"); + RT_LOG_INFO("d3d12_xs: the host d3d12.dll serializes root signatures only up to 1.1; version 1.2 " + "descriptions without static sampler flags are serialized as 1.1\n"); return fn(&v11, blob, error); } return fn(&cleared, blob, error); @@ -138,7 +137,7 @@ HRESULT WINAPI D3D12XboxCreateDevice(IUnknown* adapter, const void* params, cons const bool tracing = rt::d3d12_trace::enabled(); if (!tracing) - std::fprintf(stderr, "[rt] d3d12_xs: D3D12XboxCreateDevice adapter=%p params=%p riid=%08lx-%04x-%04x\n", + RT_LOG_DEBUG("d3d12_xs: D3D12XboxCreateDevice adapter=%p params=%p riid=%08lx-%04x-%04x\n", adapter, params, static_cast(riid->Data1), riid->Data2, riid->Data3); // The 24 words are the title's device parameters (docs/boot.md, question 1). Unlike the pointers above they are the // same on every run, so they are printed with --trace-d3d12 as well, and one traced run shows them. @@ -153,42 +152,39 @@ HRESULT WINAPI D3D12XboxCreateDevice(IUnknown* adapter, const void* params, cons if (n < 0) break; used += static_cast(n); } - std::fprintf(stderr, "[rt] d3d12_xs: D3D12XboxCreateDevice params[24] =%s\n", line); + RT_LOG_DEBUG("d3d12_xs: D3D12XboxCreateDevice params[24] =%s\n", line); } else { - std::fprintf(stderr, "[rt] d3d12_xs: D3D12XboxCreateDevice params = null\n"); + RT_LOG_DEBUG("d3d12_xs: D3D12XboxCreateDevice params = null\n"); } static std::atomic proxy_logged{false}; if (!proxy_logged.exchange(true, std::memory_order_relaxed)) { - std::fprintf(stderr, - "[rt] d3d12_xs: D3D12XboxCreateDevice: wrapping the PC ID3D12Device in the Xbox-ABI proxy " + RT_LOG_DEBUG("d3d12_xs: D3D12XboxCreateDevice: wrapping the PC ID3D12Device in the Xbox-ABI proxy " "(slot 62 -> CreateComputePipelineState, slot 76 -> CreateCommittedResource).\n"); } #ifdef LEONIDA_VULKAN_DEVICE // Opt-in until the Vulkan device covers the first frame: LEONIDA_D3D12=vulkan puts the Vulkan-backed device // behind the same proxy instead of the host's D3D12 device. - char backend[16] = {}; - size_t backend_length = 0; - if (getenv_s(&backend_length, backend, "LEONIDA_D3D12") == 0 && std::strcmp(backend, "vulkan") == 0) { + if (rt::config::get("d3d12.backend").text == "vulkan") { ID3D12Device* vulkan = nullptr; HRESULT vhr = rt::d3d12::create_vulkan_device_standalone( __uuidof(ID3D12Device), reinterpret_cast(&vulkan), rt::d3d12::QueueTestSettings::ignore); if (FAILED(vhr)) { - std::fprintf(stderr, "[rt] d3d12_xs: D3D12XboxCreateDevice: Vulkan device failed (hr=0x%08lx)\n", + RT_LOG_ERROR("d3d12_xs: D3D12XboxCreateDevice: Vulkan device failed (hr=0x%08lx)\n", static_cast(vhr)); return result(method, vhr); } vhr = rt::d3d12_xs::create_device_proxy(vulkan, *riid, out); if (FAILED(vhr)) { vulkan->Release(); - std::fprintf(stderr, "[rt] d3d12_xs: D3D12XboxCreateDevice: proxy over the Vulkan device failed " - "(hr=0x%08lx)\n", static_cast(vhr)); + RT_LOG_ERROR("d3d12_xs: D3D12XboxCreateDevice: proxy over the Vulkan device failed " + "(hr=0x%08lx)\n", static_cast(vhr)); return result(method, vhr); } rt::d3d12::set_device_outer(vulkan, static_cast(*out)); if (!tracing) - std::fprintf(stderr, "[rt] d3d12_xs: D3D12XboxCreateDevice -> proxy %p (Vulkan device %p)\n", *out, + RT_LOG_DEBUG("d3d12_xs: D3D12XboxCreateDevice -> proxy %p (Vulkan device %p)\n", *out, static_cast(vulkan)); return result(method, S_OK); } @@ -202,7 +198,7 @@ HRESULT WINAPI D3D12XboxCreateDevice(IUnknown* adapter, const void* params, cons reinterpret_cast(&real)); if (FAILED(hr) || !real) { if (real) real->Release(); - std::fprintf(stderr, "[rt] d3d12_xs: D3D12XboxCreateDevice: PC D3D12CreateDevice failed (hr=0x%08lx)\n", + RT_LOG_ERROR("d3d12_xs: D3D12XboxCreateDevice: PC D3D12CreateDevice failed (hr=0x%08lx)\n", static_cast(hr)); return result(method, FAILED(hr) ? hr : E_FAIL); } @@ -211,12 +207,12 @@ HRESULT WINAPI D3D12XboxCreateDevice(IUnknown* adapter, const void* params, cons if (FAILED(hr)) { // create_device_proxy keeps the caller's reference on failure. real->Release(); - std::fprintf(stderr, "[rt] d3d12_xs: D3D12XboxCreateDevice: proxy creation failed (hr=0x%08lx)\n", + RT_LOG_ERROR("d3d12_xs: D3D12XboxCreateDevice: proxy creation failed (hr=0x%08lx)\n", static_cast(hr)); return result(method, hr); } if (!tracing) - std::fprintf(stderr, "[rt] d3d12_xs: D3D12XboxCreateDevice -> proxy %p (PC device %p)\n", *out, + RT_LOG_DEBUG("d3d12_xs: D3D12XboxCreateDevice -> proxy %p (PC device %p)\n", *out, static_cast(real)); return result(method, S_OK); } diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 1045b86fb..30b6707f2 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -24,6 +24,8 @@ // behind the device before a presenter exists, so WaitFrameEventX returns at once with a fresh non-zero token. #include "d3d12_xs_device.h" #include "d3d12_trace.h" +#include "../core/config.h" +#include "../core/log.h" #include "../src/shader_library.h" // leonida::fspx_payload_from_parts for slot 67 #include @@ -39,6 +41,7 @@ #include #include #include +#include #include namespace rt::d3d12_xs { @@ -75,6 +78,10 @@ struct DeviceProxy { std::atomic frame_latency{1}; std::atomic frame_event_scheduled{false}; std::atomic frame_next_token{1}; + // Takes the three frame calls over when set (set_device_frame_event_sink); the fields above stay unused then. + std::atomic frame_sink{nullptr}; + // Where a PresentX on one of this device's queues goes (set_device_present_sink); null: the call is refused. + std::atomic present_sink{nullptr}; }; constexpr unsigned kHeapSlots = 11; // IUnknown + ID3D12Object + DeviceChild + Pageable + GetDesc + 2 handles @@ -114,10 +121,11 @@ bool first_call(std::atomic& seen) { } bool trace_enabled() { + // d3d12.xs_trace (XS_TRACE): on for a value that does not start with 0. A value of 8 characters or more is + // ignored, as before the setting moved to the table. static const bool enabled = [] { - char value[8] = {}; - const DWORD length = GetEnvironmentVariableA("XS_TRACE", value, sizeof(value)); - return length > 0 && value[0] != '\0' && value[0] != '0'; + const std::string value = rt::config::get("d3d12.xs_trace").text; + return !value.empty() && value.size() < 8 && value[0] != '0'; }(); return enabled; } @@ -163,9 +171,9 @@ void note_slot(unsigned slot) { count_hit(g_hits[slot]); const bool first = first_call(g_first[slot]); if (first) { - std::fprintf(stderr, "[rt] d3d12_xs: device slot %u (%s) first call\n", slot, slot_name(slot)); + RT_LOG_DEBUG("d3d12_xs: device slot %u (%s) first call\n", slot, slot_name(slot)); } else if (slot >= 3 && trace_enabled()) { - std::fprintf(stderr, "[rt] d3d12_xs: device slot %u (%s) call\n", slot, slot_name(slot)); + RT_LOG_DEBUG("d3d12_xs: device slot %u (%s) call\n", slot, slot_name(slot)); } } @@ -181,20 +189,23 @@ struct XboxDeviceSlotRoutes { unsigned list_x = 73; // CreateCommandListX(desc, allocator, initial_state, riid, out) }; -unsigned env_device_slot(const char* name, unsigned fallback) { - char value[32] = {}; - const DWORD length = GetEnvironmentVariableA(name, value, sizeof(value)); - if (length == 0) return fallback; - if (length >= sizeof(value)) { - std::fprintf(stderr, "[rt] d3d12_xs: %s is too long for a device slot; the default is kept\n", name); +// The slot a setting of the table names (its variable, else leonida.toml); `fallback` when nothing sets it. The +// messages name the variable also when the value came from the file. +unsigned env_device_slot(rt::config::Name setting, unsigned fallback) { + const char* name = setting.setting().variable; + const rt::config::Value configured = rt::config::get(setting); + if (!configured.is_set()) return fallback; + const std::string& value = configured.text; + if (value.size() >= 32) { // the size of the buffer the variable was read into before it moved to the table + RT_LOG_WARN("d3d12_xs: %s is too long for a device slot; the default is kept\n", name); return fallback; } errno = 0; char* end = nullptr; - const unsigned long slot = std::strtoul(value, &end, 0); - if (errno != 0 || end == value || *end != '\0' || slot < 3 || slot > 127) { - std::fprintf(stderr, "[rt] d3d12_xs: %s=%s is not a device slot in 3..127; the default is kept\n", name, - value); + const unsigned long slot = std::strtoul(value.c_str(), &end, 0); + if (errno != 0 || end == value.c_str() || *end != '\0' || slot < 3 || slot > 127) { + RT_LOG_WARN("d3d12_xs: %s=%s is not a device slot in 3..127; the default is kept\n", name, + value.c_str()); return fallback; } return static_cast(slot); @@ -203,11 +214,11 @@ unsigned env_device_slot(const char* name, unsigned fallback) { const XboxDeviceSlotRoutes& xbox_device_slot_routes() { static const XboxDeviceSlotRoutes routes = [] { XboxDeviceSlotRoutes r; - const unsigned frame_interval = env_device_slot("LEONIDA_XS_FRAME_INTERVAL_SLOT", r.frame_interval); - const unsigned schedule_event = env_device_slot("LEONIDA_XS_SCHEDULE_EVENT_SLOT", r.schedule_event); - const unsigned wait_event = env_device_slot("LEONIDA_XS_WAIT_EVENT_SLOT", r.wait_event); - const unsigned queue_x = env_device_slot("LEONIDA_XS_QUEUE_X_SLOT", r.queue_x); - const unsigned list_x = env_device_slot("LEONIDA_XS_LIST_X_SLOT", r.list_x); + const unsigned frame_interval = env_device_slot("d3d12.frame_interval_slot", r.frame_interval); + const unsigned schedule_event = env_device_slot("d3d12.schedule_event_slot", r.schedule_event); + const unsigned wait_event = env_device_slot("d3d12.wait_event_slot", r.wait_event); + const unsigned queue_x = env_device_slot("d3d12.queue_x_slot", r.queue_x); + const unsigned list_x = env_device_slot("d3d12.list_x_slot", r.list_x); const bool moved = frame_interval != r.frame_interval || schedule_event != r.schedule_event || wait_event != r.wait_event || queue_x != r.queue_x || list_x != r.list_x; r.frame_interval = frame_interval; @@ -216,10 +227,9 @@ const XboxDeviceSlotRoutes& xbox_device_slot_routes() { r.queue_x = queue_x; r.list_x = list_x; if (moved) - std::fprintf(stderr, - "[rt] d3d12_xs: Xbox device slots: SetFrameIntervalX=%u ScheduleFrameEventX=%u " - "WaitFrameEventX=%u CreateCommandQueueX=%u CreateCommandListX=%u\n", - r.frame_interval, r.schedule_event, r.wait_event, r.queue_x, r.list_x); + RT_LOG_INFO("d3d12_xs: Xbox device slots: SetFrameIntervalX=%u ScheduleFrameEventX=%u " + "WaitFrameEventX=%u CreateCommandQueueX=%u CreateCommandListX=%u\n", + r.frame_interval, r.schedule_event, r.wait_event, r.queue_x, r.list_x); return r; }(); return routes; @@ -234,8 +244,7 @@ void log_xbox_route_once(unsigned slot, const char* name, std::uint64_t a1, std: if (slot >= kMaxSlots) return; bool expected = false; if (!logged[slot].compare_exchange_strong(expected, true, std::memory_order_relaxed)) return; - std::fprintf(stderr, - "[rt] d3d12_xs: device slot %u routed to %s (args 0x%llx 0x%llx 0x%llx 0x%llx 0x%llx)\n", slot, + RT_LOG_DEBUG("d3d12_xs: device slot %u routed to %s (args 0x%llx 0x%llx 0x%llx 0x%llx 0x%llx)\n", slot, name, static_cast(a1), static_cast(a2), static_cast(a3), static_cast(a4), static_cast(a5)); @@ -259,9 +268,9 @@ void note_heap_slot(unsigned slot) { count_hit(g_heap_hits[slot]); const bool first = first_call(g_heap_first[slot]); if (first) { - std::fprintf(stderr, "[rt] d3d12_xs: heap slot %u (%s) first call\n", slot, heap_slot_name(slot)); + RT_LOG_DEBUG("d3d12_xs: heap slot %u (%s) first call\n", slot, heap_slot_name(slot)); } else if (slot >= 3 && trace_enabled()) { - std::fprintf(stderr, "[rt] d3d12_xs: heap slot %u (%s) call\n", slot, heap_slot_name(slot)); + RT_LOG_DEBUG("d3d12_xs: heap slot %u (%s) call\n", slot, heap_slot_name(slot)); } } @@ -427,15 +436,14 @@ HRESULT WINAPI dxgi_create_surface(void*, const DXGI_SURFACE_DESC*, UINT, DXGI_U IDXGISurface** out) { static std::atomic logged{false}; if (!logged.exchange(true, std::memory_order_relaxed)) - std::fprintf(stderr, "[rt] d3d12_xs: IDXGIDevice::CreateSurface is not implemented; returning E_NOTIMPL\n"); + RT_LOG_WARN("d3d12_xs: IDXGIDevice::CreateSurface is not implemented; returning E_NOTIMPL\n"); if (out) *out = nullptr; return E_NOTIMPL; } HRESULT WINAPI dxgi_query_resource_residency(void*, IUnknown* const*, DXGI_RESIDENCY*, UINT) { static std::atomic logged{false}; if (!logged.exchange(true, std::memory_order_relaxed)) - std::fprintf(stderr, - "[rt] d3d12_xs: IDXGIDevice::QueryResourceResidency is not implemented; returning E_NOTIMPL\n"); + RT_LOG_WARN("d3d12_xs: IDXGIDevice::QueryResourceResidency is not implemented; returning E_NOTIMPL\n"); return E_NOTIMPL; } // The priority and the frame latency are kept and read back; nothing acts on them (the Xbox presenter's latency is @@ -617,7 +625,7 @@ HRESULT create_heap_proxy(ID3D12DescriptorHeap* real, DeviceProxy* device, REFII return hr; } if (!d3d12_trace::enabled()) - std::fprintf(stderr, "[rt] d3d12_xs: heap proxy %p wraps PC heap %p (device proxy %p)\n", + RT_LOG_DEBUG("d3d12_xs: heap proxy %p wraps PC heap %p (device proxy %p)\n", static_cast(proxy), static_cast(real), static_cast(device)); heap_release(proxy); return S_OK; @@ -630,7 +638,7 @@ HRESULT create_heap_proxy(ID3D12DescriptorHeap* real, DeviceProxy* device, REFII // the public chain in PC order, exactly like the device proxy, and a slot past the PC vtable is logged and refused // with E_NOTIMPL. PresentX, SuspendX and ResumeX are queue methods past the public chain // (docs/d3d12_command_objects.md §5.3). Their slots are not known and nothing is guessed: the first run of the -// executable names them in the log. +// executable names them in the log. PresentX alone has a route, at the slot a setting names (present_x_slot below). // // Slot numbers are those of the Windows SDK 10.0.26100 d3d12.h: ID3D12CommandQueue has 19, ID3D12Fence 11 and // ID3D12Fence1 12. That the console keeps these public slots, and keeps device slots 8/32/36/75, is an assumption @@ -760,10 +768,10 @@ void note_child_slot(unsigned slot) { const bool first = first_call(S::first[slot]); const char* method = child_public_name(slot); if (first) { - std::fprintf(stderr, "[rt] d3d12_xs: %s slot %u (%s) first call\n", child_kind_name(), slot, + RT_LOG_DEBUG("d3d12_xs: %s slot %u (%s) first call\n", child_kind_name(), slot, method ? method : "past the public chain"); } else if (slot >= 3 && trace_enabled()) { - std::fprintf(stderr, "[rt] d3d12_xs: %s slot %u (%s) call\n", child_kind_name(), slot, + RT_LOG_DEBUG("d3d12_xs: %s slot %u (%s) call\n", child_kind_name(), slot, method ? method : "past the public chain"); } } @@ -841,11 +849,10 @@ void log_refused_iid(const char* kind, const IID& iid) { if (log) seen[count++] = iid; ReleaseSRWLockExclusive(&lock); if (!log) return; - std::fprintf(stderr, - "[rt] d3d12_xs: %s proxy refuses {%08lX-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}, which the real " - "object implements; E_NOINTERFACE\n", - kind, iid.Data1, iid.Data2, iid.Data3, iid.Data4[0], iid.Data4[1], iid.Data4[2], iid.Data4[3], - iid.Data4[4], iid.Data4[5], iid.Data4[6], iid.Data4[7]); + RT_LOG_WARN("d3d12_xs: %s proxy refuses {%08lX-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}, which the real " + "object implements; E_NOINTERFACE\n", + kind, iid.Data1, iid.Data2, iid.Data3, iid.Data4[0], iid.Data4[1], iid.Data4[2], iid.Data4[3], + iid.Data4[4], iid.Data4[5], iid.Data4[6], iid.Data4[7]); } template @@ -974,7 +981,7 @@ inline void note_list_slot(unsigned slot, std::uint64_t a1 = 0, std::uint64_t a2 ListStats::hits[slot].fetch_add(1, std::memory_order_relaxed); bool expected = false; if (ListStats::first[slot].compare_exchange_strong(expected, true, std::memory_order_relaxed)) - std::fprintf(stderr, "[rt] d3d12_xs: list slot %u first call (args 0x%llx 0x%llx 0x%llx 0x%llx)\n", slot, + RT_LOG_DEBUG("d3d12_xs: list slot %u first call (args 0x%llx 0x%llx 0x%llx 0x%llx)\n", slot, static_cast(a1), static_cast(a2), static_cast(a3), static_cast(a4)); } @@ -1067,9 +1074,9 @@ std::uint64_t WINAPI list_slot(ListProxy* self, std::uint64_t a1, std::uint64_t if constexpr (Slot == 148) { static std::atomic logged{false}; if (!logged.exchange(true, std::memory_order_relaxed)) - std::fprintf(stderr, - "[rt] d3d12_xs: console list slot 148 AllocateUploadMemory stub called (size %llu, align %llu)\n", - static_cast(a1), static_cast(a2)); + RT_LOG_WARN( + "d3d12_xs: console list slot 148 AllocateUploadMemory stub called (size %llu, align %llu)\n", + static_cast(a1), static_cast(a2)); } return 0; } else { @@ -1077,10 +1084,9 @@ std::uint64_t WINAPI list_slot(ListProxy* self, std::uint64_t a1, std::uint64_t static std::atomic beyond_warned[kListSlots]; bool expected = false; if (beyond_warned[Slot].compare_exchange_strong(expected, true, std::memory_order_relaxed)) - std::fprintf(stderr, - "[rt] d3d12_xs: list slot %u maps to PC slot %u, beyond the real list's %u " - "slots; returning E_NOTIMPL\n", - Slot, pc, self->pc_slot_count); + RT_LOG_WARN("d3d12_xs: list slot %u maps to PC slot %u, beyond the real list's %u " + "slots; returning E_NOTIMPL\n", + Slot, pc, self->pc_slot_count); return hr_to_u64(E_NOTIMPL); } using ForwardFn = std::uint64_t(WINAPI*)(void*, std::uint64_t, std::uint64_t, std::uint64_t, @@ -1142,7 +1148,7 @@ HRESULT wrap_list(IUnknown* created, DeviceProxy* device, const IID* riid, void* } static std::atomic logged{false}; if (!d3d12_trace::enabled() && (!logged.exchange(true, std::memory_order_relaxed) || trace_enabled())) - std::fprintf(stderr, "[rt] d3d12_xs: list proxy %p wraps %p (%u PC vtable slots)\n", + RT_LOG_DEBUG("d3d12_xs: list proxy %p wraps %p (%u PC vtable slots)\n", static_cast(proxy), static_cast(created), proxy->pc_slot_count); proxy->refs.fetch_sub(1, std::memory_order_relaxed); return S_OK; @@ -1158,6 +1164,9 @@ void report_table_overrun(std::uintptr_t address) { const std::uintptr_t limit = S::region_end.load(std::memory_order_acquire); if (!end || address < end || address >= limit) return; S::overruns.fetch_add(1, std::memory_order_relaxed); + // An error line of the log (core/log.h). It is put together and written by hand because this runs inside the + // fault handler; the level is one atomic read. + if (!::rt::log::enabled(::rt::log::Level::Error)) return; char line[160]; unsigned long long slot = (address - begin) / sizeof(void*); char digits[24]; @@ -1190,6 +1199,51 @@ LONG CALLBACK table_overrun_handler(EXCEPTION_POINTERS* info) { return EXCEPTION_CONTINUE_SEARCH; // diagnostics only: the fault goes on to the title's handlers or the crash } +// PresentX on the queue (PresentSink in d3d12_xs_device.h). Its slot is the one d3d12.present_x_slot +// (LEONIDA_XS_PRESENT_X_SLOT) names, read once: a slot of the refused tail, or 0 when the setting names none or its +// value is not such a slot (logged once). No default is taken from the public numbers: they are other titles'. +unsigned present_x_slot() { + static const unsigned slot = [] { + const rt::config::Name setting("d3d12.present_x_slot"); + const char* name = setting.setting().variable; + const rt::config::Value configured = rt::config::get(setting); + if (!configured.is_set()) return 0u; + const std::string& value = configured.text; + errno = 0; + char* end = nullptr; + const unsigned long parsed = value.size() < 32 ? std::strtoul(value.c_str(), &end, 0) : 0; + if (value.size() >= 32 || errno != 0 || end == value.c_str() || *end != '\0' || + parsed < kQueuePublicSlots || parsed >= kQueueSlots) { + RT_LOG_WARN("d3d12_xs: %s=%.40s is not a queue slot in %u..%u; no slot is taken for PresentX\n", name, + value.c_str(), kQueuePublicSlots, kQueueSlots - 1); + return 0u; + } + RT_LOG_INFO("d3d12_xs: Xbox queue slot: PresentX=%lu\n", parsed); + return static_cast(parsed); + }(); + return slot; +} + +// A call on the PresentX slot: PresentX(plane count, planes, parameters). It goes to the present sink of the queue's +// device with the real queue behind the proxy; without a sink it is refused like the rest of the tail, with a line +// that says why. +HRESULT queue_present_x(ChildProxy* self, unsigned slot, std::uint64_t plane_count, std::uint64_t planes, + std::uint64_t params) { + const PresentSink* sink = self->device ? self->device->present_sink.load(std::memory_order_acquire) : nullptr; + if (!sink || !sink->present_x) { + static std::atomic logged{false}; + if (first_call(logged)) + RT_LOG_WARN("d3d12_xs: queue slot %u is taken for PresentX and the device has no present sink; " + "returning E_NOTIMPL\n", slot); + d3d12_trace::record(child_trace_name(slot), "unsupported"); + return E_NOTIMPL; + } + d3d12_trace::record(child_trace_name(slot)); // "called": the sink's result is the title's + return sink->present_x(sink->context, reinterpret_cast(self->real), + static_cast(plane_count), reinterpret_cast(planes), + reinterpret_cast(params)); +} + template std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, std::uint64_t a4, std::uint64_t a5, std::uint64_t a6, std::uint64_t a7, @@ -1209,16 +1263,20 @@ std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_ reinterpret_cast(a2))); } else { note_child_slot(Slot); + // The slot a setting names for PresentX, before the tail is refused. Only a tail slot of the queue table can + // be that slot, so the public chain, the fences and the allocators never ask. + if constexpr (K == ChildKind::queue && Slot >= kQueuePublicSlots) { + if (Slot == present_x_slot()) return hr_to_u64(queue_present_x(self, Slot, a1, a2, a3)); + } if (Slot >= self->slot_count) { bool expected = false; if (ChildStats::beyond_warned[Slot].compare_exchange_strong(expected, true, std::memory_order_relaxed)) { - std::fprintf(stderr, - "[rt] d3d12_xs: %s slot %u is beyond the PC %s vtable (%u slots); returning E_NOTIMPL " - "(args 0x%llx 0x%llx 0x%llx 0x%llx)\n", - child_kind_name(), Slot, child_kind_name(), self->slot_count, - static_cast(a1), static_cast(a2), - static_cast(a3), static_cast(a4)); + RT_LOG_WARN("d3d12_xs: %s slot %u is beyond the PC %s vtable (%u slots); returning E_NOTIMPL " + "(args 0x%llx 0x%llx 0x%llx 0x%llx)\n", + child_kind_name(), Slot, child_kind_name(), self->slot_count, + static_cast(a1), static_cast(a2), + static_cast(a3), static_cast(a4)); } d3d12_trace::record(child_trace_name(Slot), "unsupported"); return hr_to_u64(E_NOTIMPL); @@ -1251,7 +1309,7 @@ void fill_child_vtable(void** vtable, std::index_sequence) { bool install_table_overrun_handler() { static const bool installed = [] { if (AddVectoredExceptionHandler(0, &table_overrun_handler)) return true; - std::fprintf(stderr, "[rt] d3d12_xs: AddVectoredExceptionHandler failed (error %lu); a slot past a queue or " + RT_LOG_ERROR("d3d12_xs: AddVectoredExceptionHandler failed (error %lu); a slot past a queue or " "fence proxy table faults without being named\n", GetLastError()); return false; }(); @@ -1272,8 +1330,8 @@ void** get_child_vtable() { fill_child_vtable(table, std::make_index_sequence{}); DWORD old = 0; if (!VirtualProtect(base, page, PAGE_READONLY, &old)) // the table works, but stays writable - std::fprintf(stderr, "[rt] d3d12_xs: %s proxy table stays writable (VirtualProtect error %lu)\n", - child_kind_name(), GetLastError()); + RT_LOG_WARN("d3d12_xs: %s proxy table stays writable (VirtualProtect error %lu)\n", + child_kind_name(), GetLastError()); S::table_begin.store(reinterpret_cast(table), std::memory_order_release); S::region_end.store(reinterpret_cast(base) + kTableRegion, std::memory_order_release); // table_end is what "guarded" means (command_object_tables_guarded, the fault logger): set only when @@ -1285,7 +1343,7 @@ void** get_child_vtable() { VirtualFree(base, 0, MEM_RELEASE); } // No reservation: the table still works, but a slot past it is not caught. - std::fprintf(stderr, "[rt] d3d12_xs: %s proxy table without a guard region\n", child_kind_name()); + RT_LOG_WARN("d3d12_xs: %s proxy table without a guard region\n", child_kind_name()); static void* storage[S::kSlots]; fill_child_vtable(storage, std::make_index_sequence{}); return storage; @@ -1325,7 +1383,7 @@ HRESULT wrap_child(IUnknown* created, DeviceProxy* device, const IID* riid, void // Titles create fences at run time: the first proxy of each kind is logged, every one only with XS_TRACE. static std::atomic logged{false}; if (!d3d12_trace::enabled() && (!logged.exchange(true, std::memory_order_relaxed) || trace_enabled())) - std::fprintf(stderr, "[rt] d3d12_xs: %s proxy %p wraps %p (device proxy %p, %u public slots)\n", + RT_LOG_DEBUG("d3d12_xs: %s proxy %p wraps %p (device proxy %p, %u public slots)\n", child_kind_name(), static_cast(proxy), static_cast(created), static_cast(device), proxy->slot_count); proxy->refs.fetch_sub(1, std::memory_order_relaxed); // drop the creation reference; `out` holds the caller's @@ -1347,10 +1405,9 @@ std::uint64_t forward_device(DeviceProxy* self, std::uint64_t a1, std::uint64_t HRESULT refuse_beyond_device(unsigned slot, unsigned slot_count) { bool expected = false; if (slot < kMaxSlots && g_beyond_warned[slot].compare_exchange_strong(expected, true, std::memory_order_relaxed)) - std::fprintf(stderr, - "[rt] d3d12_xs: device slot %u (%s) is beyond the PC device vtable (%u slots); returning " - "E_NOTIMPL\n", - slot, slot_name(slot), slot_count); + RT_LOG_WARN("d3d12_xs: device slot %u (%s) is beyond the PC device vtable (%u slots); returning " + "E_NOTIMPL\n", + slot, slot_name(slot), slot_count); return E_NOTIMPL; } @@ -1376,6 +1433,12 @@ HRESULT proxy_create_command_queue(DeviceProxy* self, const D3D12_COMMAND_QUEUE_ // 60 Hz), and latency is the allowed frames in flight. S_OK even for 0: a boot must not abort here, and nothing paces. HRESULT proxy_set_frame_interval_x(DeviceProxy* self, std::uint64_t output, std::uint64_t interval_us, std::uint64_t latency, std::uint64_t flags) { + // A sink (set_device_frame_event_sink) takes the call over, with the title's words and its own result. + if (const FrameEventSink* sink = self->frame_sink.load(std::memory_order_acquire); + sink && sink->set_frame_interval) + return sink->set_frame_interval(sink->context, reinterpret_cast(output), + static_cast(interval_us), + static_cast(latency), static_cast(flags)); (void)output; (void)flags; self->frame_interval_us.store(static_cast(interval_us), std::memory_order_relaxed); @@ -1386,6 +1449,10 @@ HRESULT proxy_set_frame_interval_x(DeviceProxy* self, std::uint64_t output, std: // Xbox device slot 79 (public HLE): ScheduleFrameEventX(event, offset_us, pEvent, flags); our pacer has only the origin. HRESULT proxy_schedule_frame_event_x(DeviceProxy* self, std::uint64_t event, std::uint64_t offset_us, std::uint64_t flags) { + if (const FrameEventSink* sink = self->frame_sink.load(std::memory_order_acquire); + sink && sink->schedule_frame_event) + return sink->schedule_frame_event(sink->context, static_cast(event), + static_cast(offset_us), static_cast(flags)); (void)event; (void)offset_us; (void)flags; @@ -1398,11 +1465,17 @@ HRESULT proxy_schedule_frame_event_x(DeviceProxy* self, std::uint64_t event, std // a zero wait cannot stall the title. A null token pointer is E_POINTER, as a _Out_ parameter. HRESULT proxy_wait_frame_event_x(DeviceProxy* self, std::uint64_t event, std::uint64_t timeout_ms, std::uint64_t flags, std::uint64_t token_word) { + auto* token = reinterpret_cast(token_word); + if (!token) return E_POINTER; + // With a sink the wait is the sink's: it may block, and its result and token are the title's. + if (const FrameEventSink* sink = self->frame_sink.load(std::memory_order_acquire); + sink && sink->wait_frame_event) + return sink->wait_frame_event(sink->context, static_cast(event), + static_cast(timeout_ms), static_cast(flags), + token); (void)event; (void)timeout_ms; (void)flags; - auto* token = reinterpret_cast(token_word); - if (!token) return E_POINTER; std::uint64_t value = self->frame_next_token.fetch_add(1, std::memory_order_relaxed); if (value == 0) value = self->frame_next_token.fetch_add(1, std::memory_order_relaxed); // skip the null token *token = value; @@ -1428,8 +1501,7 @@ HRESULT proxy_create_command_list_x(DeviceProxy* self, std::uint64_t desc_word, static std::atomic logged{false}; if (first_call(logged)) - std::fprintf(stderr, - "[rt] d3d12_xs: slot 73 CreateCommandListX desc words 0x%08x 0x%08x -> node mask 0, type %d\n", + RT_LOG_DEBUG("d3d12_xs: slot 73 CreateCommandListX desc words 0x%08x 0x%08x -> node mask 0, type %d\n", words[0], words[1], static_cast(type)); // Leonida wraps its Vulkan allocators; a PC allocator comes back unwrapped and is passed as it is. Pipeline states @@ -1503,8 +1575,8 @@ HRESULT proxy_create_command_allocator(DeviceProxy* self, std::uint64_t type, co if (!resolves_allocator_proxies(allocator)) { static std::atomic logged{false}; if (!logged.exchange(true, std::memory_order_relaxed)) - std::fprintf(stderr, "[rt] d3d12_xs: allocators of this device are not wrapped: its command lists " - "cannot resolve an allocator proxy\n"); + RT_LOG_WARN("d3d12_xs: allocators of this device are not wrapped: its command lists " + "cannot resolve an allocator proxy\n"); const HRESULT asked = allocator->QueryInterface(*riid, out); allocator->Release(); return asked; @@ -1647,8 +1719,8 @@ HRESULT proxy_create_compute_pipeline_state(DeviceProxy* self, const D3D12_COMPU if (w2 || w3) { static std::atomic logged{false}; if (!logged.exchange(true, std::memory_order_relaxed)) - std::fprintf(stderr, "[rt] d3d12_xs: slot 62 extra words 0x%llx 0x%llx (ignored)\n", - static_cast(w2), static_cast(w3)); + RT_LOG_WARN("d3d12_xs: slot 62 extra words 0x%llx 0x%llx (ignored)\n", + static_cast(w2), static_cast(w3)); } if (!out) return E_POINTER; *out = nullptr; @@ -1704,8 +1776,7 @@ HRESULT proxy_create_compute_pipeline_from_native_code(DeviceProxy* self, const if (payload.empty()) { static std::atomic logged{false}; if (!logged.exchange(true, std::memory_order_relaxed)) - std::fprintf(stderr, - "[rt] d3d12_xs: slot 67 refused: a pointer/size pair is inconsistent or too large " + RT_LOG_ERROR("d3d12_xs: slot 67 refused: a pointer/size pair is inconsistent or too large " "(kind0 %llu B, kind1 %llu B, kind6 %llu B, kind7 %llu B)\n", static_cast(xbox_desc->kind0_size), static_cast(xbox_desc->kind1_size), @@ -1727,8 +1798,7 @@ HRESULT proxy_create_compute_pipeline_from_native_code(DeviceProxy* self, const const std::uint64_t call = calls.fetch_add(1, std::memory_order_relaxed) + 1; const HRESULT hr = self->real->CreateComputePipelineState(&pc_desc, *riid, out); if (FAILED(hr)) - std::fprintf(stderr, - "[rt] d3d12_xs: slot 67 call %llu failed with 0x%08lx (kind 0 %llu B, kind 1 %llu B, kind 6 %llu B, " + RT_LOG_ERROR("d3d12_xs: slot 67 call %llu failed with 0x%08lx (kind 0 %llu B, kind 1 %llu B, kind 6 %llu B, " "kind 7 %llu B)\n", static_cast(call), static_cast(hr), static_cast(xbox_desc->kind0_size), @@ -1758,8 +1828,7 @@ HRESULT proxy_create_resource(DeviceProxy* self, const D3D12_HEAP_PROPERTIES* he static std::atomic logged{false}; if (!logged.exchange(true, std::memory_order_relaxed)) { - std::fprintf(stderr, - "[rt] d3d12_xs: slot 76 resource: dimension=%d xbox layout=0x%x -> PC layout=0x%x\n", + RT_LOG_DEBUG("d3d12_xs: slot 76 resource: dimension=%d xbox layout=0x%x -> PC layout=0x%x\n", static_cast(pc_desc.Dimension), xbox_layout, static_cast(pc_desc.Layout)); } return self->real->CreateCommittedResource(heap_properties, heap_flags, &pc_desc, initial_state, clear_value, @@ -1798,8 +1867,7 @@ HRESULT proxy_create_placed_resource_x(DeviceProxy* self, void* va, const D3D12_ : D3D12_TEXTURE_LAYOUT_UNKNOWN; static std::atomic logged{false}; if (!logged.exchange(true, std::memory_order_relaxed)) { - std::fprintf(stderr, - "[rt] d3d12_xs: slot 133 CreatePlacedResourceX: va=%p dimension=%d width=%llu xbox flags=0x%x " + RT_LOG_DEBUG("d3d12_xs: slot 133 CreatePlacedResourceX: va=%p dimension=%d width=%llu xbox flags=0x%x " "state=0x%x -> a buffer on the title's pages\n", va, static_cast(pc_desc.Dimension), static_cast(pc_desc.Width), xbox_flags, state); @@ -1810,7 +1878,7 @@ HRESULT proxy_create_placed_resource_x(DeviceProxy* self, void* va, const D3D12_ !pages(va, static_cast(pc_desc.Width))) { static std::atomic refused{false}; if (!refused.exchange(true, std::memory_order_relaxed)) { - std::fprintf(stderr, "[rt] d3d12_xs: slot 133: committing the pages of va=%p width=%llu failed (error %lu)\n", + RT_LOG_ERROR("d3d12_xs: slot 133: committing the pages of va=%p width=%llu failed (error %lu)\n", va, static_cast(pc_desc.Width), GetLastError()); } } @@ -2006,7 +2074,7 @@ HRESULT create_device_proxy(ID3D12Device* real, REFIID riid, void** out) { return hr; } if (!d3d12_trace::enabled()) - std::fprintf(stderr, "[rt] d3d12_xs: device proxy %p wraps PC device %p (%u PC vtable slots)\n", + RT_LOG_DEBUG("d3d12_xs: device proxy %p wraps PC device %p (%u PC vtable slots)\n", static_cast(proxy), static_cast(real), slot_count); proxy_release(proxy); // drop the creation reference; `out` holds the caller's reference return S_OK; @@ -2030,7 +2098,7 @@ bool set_device_adapter_provider(void* device, DxgiAdapterProvider provider) { auto* proxy = static_cast(device_proxy_primary(device)); if (!proxy) { // Not installing one silently would leave the host's adapter in its place. - std::fprintf(stderr, "[rt] d3d12_xs: set_device_adapter_provider: %p is not a device proxy; no provider set\n", + RT_LOG_ERROR("d3d12_xs: set_device_adapter_provider: %p is not a device proxy; no provider set\n", device); return false; } @@ -2038,6 +2106,40 @@ bool set_device_adapter_provider(void* device, DxgiAdapterProvider provider) { return true; } +bool set_device_frame_event_sink(void* device, const FrameEventSink* sink) { + auto* proxy = static_cast(device_proxy_primary(device)); + if (!proxy) { + // Not setting one silently would leave the frame calls with the proxy's own answers, unpaced. + RT_LOG_ERROR("d3d12_xs: set_device_frame_event_sink: %p is not a device proxy; no sink set\n", device); + return false; + } + proxy->frame_sink.store(sink, std::memory_order_release); + return true; +} + +const FrameEventSink* device_frame_event_sink(const void* device) { + if (!is_device_proxy(device)) return nullptr; + return static_cast(device)->frame_sink.load(std::memory_order_acquire); +} + +bool set_device_present_sink(void* device, const PresentSink* sink) { + auto* proxy = static_cast(device_proxy_primary(device)); + if (!proxy) { + // Not setting one silently would leave every PresentX of the device's queues refused. + RT_LOG_ERROR("d3d12_xs: set_device_present_sink: %p is not a device proxy; no sink set\n", device); + return false; + } + proxy->present_sink.store(sink, std::memory_order_release); + return true; +} + +const PresentSink* device_present_sink(const void* device) { + if (!is_device_proxy(device)) return nullptr; + return static_cast(device)->present_sink.load(std::memory_order_acquire); +} + +unsigned queue_present_x_slot() { return present_x_slot(); } + bool is_heap_proxy(const void* heap) { return heap && *reinterpret_cast(heap) == reinterpret_cast(get_heap_vtable()); } diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h index 20ed4afc1..6838ec54f 100644 --- a/runtime/shims/d3d12_xs_device.h +++ b/runtime/shims/d3d12_xs_device.h @@ -15,6 +15,7 @@ // slots 78/79/80 SetFrameIntervalX, ScheduleFrameEventX, WaitFrameEventX. A per-device token state machine answers // them before the PC vtable is indexed; WaitFrameEventX returns at once with a fresh non-zero token. // Slot 80 is outside a PC ID3D12Device11 table, so it is checked before the beyond-table refusal. +// A frame-event sink (set_device_frame_event_sink below) takes the three calls over when one is set. // The slots 48/73/78/79/80 are the public HLE Freminet/ScarlettX's observation, not Microsoft documentation, and can // be moved with LEONIDA_XS_QUEUE_X_SLOT, LEONIDA_XS_LIST_X_SLOT, LEONIDA_XS_FRAME_INTERVAL_SLOT, // LEONIDA_XS_SCHEDULE_EVENT_SLOT and LEONIDA_XS_WAIT_EVENT_SLOT (3..127; anything else is logged once and ignored). @@ -38,8 +39,9 @@ // in PC order, and a slot past it, up to the end of the proxy's table (128 queue, 64 fence slots), is logged with its // first four argument words and refused with E_NOTIMPL. A slot past the table faults on the vtable read inside a // reserved, never-committed region, and the fault is logged with the slot. That is where the console's queue methods -// (PresentX, SuspendX, ResumeX) will show up; their slots are not known and are not guessed, and that the console -// keeps the public slots is an assumption (docs/d3d12_command_objects.md §5.2). Heap, queue and fence proxies are +// (PresentX, SuspendX, ResumeX) will show up; their slots are not known and are not guessed (PresentX is routed only +// at a slot a setting names, see PresentSink below), and that the console keeps the public slots is an assumption +// (docs/d3d12_command_objects.md §5.2). Heap, queue and fence proxies are // unwrapped wherever a device or queue method hands them to the real runtime: queue Signal/Wait (14/15), device // CreateSharedHandle (31), MakeResident/Evict (34/35), SetEventOnMultipleFenceCompletion (45), SetResidencyPriority // (46) and EnqueueMakeResident (50). Command lists are not wrapped, so ExecuteCommandLists passes them through and a @@ -80,6 +82,53 @@ void* device_proxy_from_dxgi_device(void* dxgi_device); // The device proxy itself, given the proxy or its DXGI pointer; null for anything else. void* device_proxy_primary(void* device); +// The frame calls of device slots 78/79/80 (at their configured indices). With no sink the proxy answers them +// itself, as described at the top: S_OK, and a fresh non-zero token at once. A sink takes them over: the proxy passes +// the title's words on and returns the sink's result. A sink is meant to stand in front of the presentation class +// (rt::d3d12::XboxPresentation, whose timing is src/frame_pacer.h); the proxy does not know that class, so this file +// needs neither a presenter nor Vulkan. A null function leaves that one call with the proxy's own answer. +// The reserved pointer of ScheduleFrameEventX and WaitFrameEventX (their third word) is not passed on: nothing models +// it. A null token pointer is refused with E_POINTER before the sink is called. +// The sink is not copied: it and what `context` points at must stay valid until another sink (or null) is set and +// every frame call that had already entered the sink has returned. A wait can block in the sink, so whoever takes a +// sink away makes its waits return first. +struct FrameEventSink { + void* context; + HRESULT (*set_frame_interval)(void* context, void* output, std::uint32_t interval_us, std::uint32_t latency, + std::uint32_t flags); + HRESULT (*schedule_frame_event)(void* context, std::uint32_t event, std::uint32_t offset_us, std::uint32_t flags); + HRESULT (*wait_frame_event)(void* context, std::uint32_t event, std::uint32_t timeout_ms, std::uint32_t flags, + std::uint64_t* token); +}; +// `device` is the proxy or its DXGI pointer; a null `sink` goes back to the proxy's own answers. False, with a line +// on stderr, when `device` is neither: nothing is set then. +bool set_device_frame_event_sink(void* device, const FrameEventSink* sink); +// The sink set on a device proxy, or null. Test helper. +const FrameEventSink* device_frame_event_sink(const void* device); + +// PresentX on the command queue. It is a queue method past the public chain and its slot is not measured for this +// title (public code gives 30 for an older runtime layout and 32 for a newer one, shims/xbox_present.h), so no slot +// is taken for it unless a setting names one: d3d12.present_x_slot (LEONIDA_XS_PRESENT_X_SLOT), a slot of the queue +// proxy's refused tail (19..127; anything else is logged once and ignored). The setting is read once, on the first +// queue call past the public chain or the first queue_present_x_slot(). +// A call on that slot goes to the present sink of the queue's device, also for a queue made before the sink was set: +// the sink gets the real queue behind the proxy and the title's three words (plane count, planes, parameters), and +// its result is the title's. The two structures are not read here; their layouts are in shims/xbox_present.h. With +// the slot set and no sink (or a sink with a null function) the call is refused with E_NOTIMPL and logged once. +// The sink is not copied; the lifetime rule is the frame-event sink's. +struct PresentSink { + void* context; + HRESULT (*present_x)(void* context, ID3D12CommandQueue* queue, std::uint32_t plane_count, const void* planes, + const void* params); +}; +// `device` is the proxy or its DXGI pointer; a null `sink` takes the sink away. False, with a line on stderr, when +// `device` is neither: nothing is set then. +bool set_device_present_sink(void* device, const PresentSink* sink); +// The present sink set on a device proxy, or null. Test helper. +const PresentSink* device_present_sink(const void* device); +// The queue slot taken for PresentX, or 0 when the setting names none. +unsigned queue_present_x_slot(); + // True when `heap` is a descriptor-heap proxy created by device slot 14. bool is_heap_proxy(const void* heap); ID3D12DescriptorHeap* heap_proxy_real_heap(const void* heap); diff --git a/runtime/shims/dstorage.cpp b/runtime/shims/dstorage.cpp index 81abaea3d..8ceb7e4a0 100644 --- a/runtime/shims/dstorage.cpp +++ b/runtime/shims/dstorage.cpp @@ -33,6 +33,7 @@ #include #include "../src/shader_library.h" // leonida::zlib_inflate +#include "../core/log.h" #include "dstorage_xs_abi.h" #include "shims.h" @@ -53,7 +54,7 @@ void log_once(const std::string& key, const std::string& line) { static auto* seen = new std::set; std::lock_guard lock(log_mutex()); if (!seen->insert(key).second) return; - std::fprintf(stderr, "[rt] dstorage: %s\n", line.c_str()); + RT_LOG_WARN("dstorage: %s\n", line.c_str()); } std::string guid_text(const GUID& g) { diff --git a/runtime/shims/dxgi_com.cpp b/runtime/shims/dxgi_com.cpp index ce40348f8..63c5990d4 100644 --- a/runtime/shims/dxgi_com.cpp +++ b/runtime/shims/dxgi_com.cpp @@ -1,5 +1,6 @@ #include "dxgi_com.h" #include "d3d12_stubs.h" +#include "../core/log.h" #include // NTSTATUS, which d3dkmthk.h needs and WIN32_LEAN_AND_MEAN leaves out #include @@ -27,7 +28,7 @@ void stub(const char* method) { static std::mutex mutex; static std::set seen; std::lock_guard lock(mutex); - if (seen.insert(method).second) std::fprintf(stderr, "[rt] dxgi: unimplemented %s\n", method); + if (seen.insert(method).second) RT_LOG_WARN("dxgi: unimplemented %s\n", method); } // IDXGIObject private data, shared by the factory, adapter and swapchain. SetPrivateData keeps a copy of the bytes; diff --git a/runtime/shims/gameinput.cpp b/runtime/shims/gameinput.cpp index 402179cde..8624b71b6 100644 --- a/runtime/shims/gameinput.cpp +++ b/runtime/shims/gameinput.cpp @@ -49,6 +49,8 @@ #include #include +#include "../core/config.h" +#include "../core/log.h" #include "gameinput.h" #include "gameinput_abi.h" #include "shims.h" @@ -131,28 +133,31 @@ const rt::gameinput::HapticApi& haptics() { return *g_haptic_api.load(); } // ---- configuration ---------------------------------------------------------------------------------------------- -std::string env(const char* name) { - char buf[64]; - const DWORD n = GetEnvironmentVariableA(name, buf, sizeof buf); - if (n == 0 || n >= sizeof buf) return {}; - std::string s(buf, n); +// A setting of the table (its variable, else leonida.toml), lower-cased; empty when nothing sets it. A value of 64 +// characters or more is ignored, as before the settings moved to the table. The messages below name the variable +// also when the value came from the file. +std::string env(rt::config::Name setting) { + const rt::config::Value value = rt::config::get(setting); + if (!value.is_set() || value.text.size() >= 64) return {}; + std::string s = value.text; for (auto& c : s) c = static_cast(std::tolower(static_cast(c))); return s; } rt::gameinput::Config read_config() { rt::gameinput::Config c; - const std::string t = env("LEONIDA_DS_TRIGGERS"); + const std::string t = env("input.ds_triggers"); if (t == "off" || t == "0") c.ds_triggers = rt::gameinput::DsTriggerMode::Off; else if (t == "resistance") c.ds_triggers = rt::gameinput::DsTriggerMode::Resistance; - else if (!t.empty() && t != "rumble") std::fprintf(stderr, "[rt] gameinput: LEONIDA_DS_TRIGGERS=%s unknown, using rumble\n", t.c_str()); - if (const std::string g = env("LEONIDA_DS_TRIGGER_GAIN"); !g.empty()) + else if (!t.empty() && t != "rumble") + RT_LOG_WARN("gameinput: LEONIDA_DS_TRIGGERS=%s unknown, using rumble\n", t.c_str()); + if (const std::string g = env("input.ds_trigger_gain"); !g.empty()) c.ds_trigger_gain = std::clamp(static_cast(std::atof(g.c_str())), 0.0f, 4.0f); - if (const std::string g = env("LEONIDA_MOUSE_SENSITIVITY"); !g.empty()) + if (const std::string g = env("input.mouse_sensitivity"); !g.empty()) c.mouse_sensitivity = std::clamp(static_cast(std::atof(g.c_str())), 0.1f, 10.0f); - if (const std::string f = env("LEONIDA_DS_TRIGGER_FREQ"); !f.empty()) + if (const std::string f = env("input.ds_trigger_freq"); !f.empty()) c.ds_trigger_frequency = static_cast(std::clamp(std::atoi(f.c_str()), 1, 255)); - if (const std::string l = env("LEONIDA_DS_LIGHTBAR"); !l.empty()) { + if (const std::string l = env("input.ds_lightbar"); !l.empty()) { if (l == "off") { c.lightbar_set = true; } else if (l.size() == 6 && l.find_first_not_of("0123456789abcdef") == std::string::npos) { @@ -162,19 +167,19 @@ rt::gameinput::Config read_config() { c.lightbar[1] = static_cast(rgb >> 8); c.lightbar[2] = static_cast(rgb); } else { - std::fprintf(stderr, "[rt] gameinput: LEONIDA_DS_LIGHTBAR=%s is not RRGGBB or off, ignored\n", l.c_str()); + RT_LOG_WARN("gameinput: LEONIDA_DS_LIGHTBAR=%s is not RRGGBB or off, ignored\n", l.c_str()); } } - if (env("LEONIDA_RUMBLE") == "0") c.rumble = false; - if (env("LEONIDA_GAMEINPUT_THREAD") == "0") c.background_thread = false; - const std::string k = env("LEONIDA_KEYBOARD_PAD"); + if (env("input.rumble") == "0") c.rumble = false; + if (env("input.thread") == "0") c.background_thread = false; + const std::string k = env("input.keyboard_pad"); if (k == "1" || k == "on" || k == "focus") c.keyboard_pad = rt::gameinput::KeyboardPadMode::Focused; else if (k == "always") c.keyboard_pad = rt::gameinput::KeyboardPadMode::Always; else if (!k.empty() && k != "0" && k != "off") - std::fprintf(stderr, "[rt] gameinput: LEONIDA_KEYBOARD_PAD=%s unknown (1, always or off), keyboard pad off\n", - k.c_str()); + RT_LOG_WARN("gameinput: LEONIDA_KEYBOARD_PAD=%s unknown (1, always or off), keyboard pad off\n", + k.c_str()); using leonida::InputFamily; - const std::string p = env("LEONIDA_PROMPTS"); + const std::string p = env("input.prompts"); if (p == "xbox") c.prompts = InputFamily::Xbox; else if (p == "playstation" || p == "ps5") c.prompts = InputFamily::PlayStation5; else if (p == "ps4") c.prompts = InputFamily::PlayStation4; @@ -182,9 +187,9 @@ rt::gameinput::Config read_config() { else if (p == "nintendo" || p == "switch") c.prompts = InputFamily::Nintendo; else if (p == "keyboard") c.prompts = InputFamily::Keyboard; else if (!p.empty() && p != "auto") - std::fprintf(stderr, "[rt] gameinput: LEONIDA_PROMPTS=%s unknown (auto, xbox, playstation, ps5, ps4, ps3, " - "nintendo or keyboard), following the devices\n", p.c_str()); - if (const std::string m = env("LEONIDA_PROMPTS_SWITCH_MS"); !m.empty()) + RT_LOG_WARN("gameinput: LEONIDA_PROMPTS=%s unknown (auto, xbox, playstation, ps5, ps4, ps3, " + "nintendo or keyboard), following the devices\n", p.c_str()); + if (const std::string m = env("input.prompts_switch_ms"); !m.empty()) c.prompts_switch_ms = static_cast(std::clamp(std::atoi(m.c_str()), 0, 2000)); return c; } @@ -1025,11 +1030,11 @@ void apply_prompt_config() { g_tracker.force(want); publish_active(); if (want) - std::fprintf(stderr, "[rt] gameinput: LEONIDA_PROMPTS: input family set to %s\n", - leonida::input_family_name(*want)); + RT_LOG_INFO("gameinput: LEONIDA_PROMPTS: input family set to %s\n", + leonida::input_family_name(*want)); else - std::fprintf(stderr, "[rt] gameinput: LEONIDA_PROMPTS cleared: input family follows the devices (%s now)\n", - leonida::input_family_name(g_tracker.active())); + RT_LOG_INFO("gameinput: LEONIDA_PROMPTS cleared: input family follows the devices (%s now)\n", + leonida::input_family_name(g_tracker.active())); } Snapshot read_pad(Device* d) { @@ -1274,10 +1279,10 @@ void open_raw(Device* d, const char* path) { // SDL reads Xbox pads on Windows through XInput ("XInput#n"); SDL's hidapi skips their XInput HID interface // (&IG_ in the path), which carries no full HID reports, so they have no raw I/O here. const bool xinput = path && std::strncmp(path, "XInput#", 7) == 0; - std::fprintf(stderr, "[rt] gameinput: %s: no raw HID (%s)\n", d->name.c_str(), - xinput ? "an XInput pad: SDL's hidapi does not open XInput HID interfaces" - : path && *path ? "its HID device could not be opened" - : "SDL reports no device path"); + RT_LOG_WARN("gameinput: %s: no raw HID (%s)\n", d->name.c_str(), + xinput ? "an XInput pad: SDL's hidapi does not open XInput HID interfaces" + : path && *path ? "its HID device could not be opened" + : "SDL reports no device path"); return; } std::vector desc(4096); @@ -1285,8 +1290,8 @@ void open_raw(Device* d, const char* path) { std::vector reports; const bool parsed = n > 0 && rt::gameinput::parse_report_descriptor(desc.data(), static_cast(n), &reports); if (!parsed || reports.empty()) { - std::fprintf(stderr, "[rt] gameinput: %s: no raw HID (%s)\n", d->name.c_str(), - n <= 0 ? "no report descriptor" : !parsed ? "malformed report descriptor" : "no reports declared"); + RT_LOG_WARN("gameinput: %s: no raw HID (%s)\n", d->name.c_str(), + n <= 0 ? "no report descriptor" : !parsed ? "malformed report descriptor" : "no reports declared"); b->close(h); return; } @@ -1347,7 +1352,7 @@ void open_pad(SDL_JoystickID jid, uint64_t ts) { State& s = g(); SDL_Gamepad* p = SDL_OpenGamepad(jid); if (!p) { - std::fprintf(stderr, "[rt] gameinput: cannot open gamepad %u: %s\n", static_cast(jid), SDL_GetError()); + RT_LOG_ERROR("gameinput: cannot open gamepad %u: %s\n", static_cast(jid), SDL_GetError()); return; } const char* serial = SDL_GetGamepadSerial(p); @@ -1478,10 +1483,10 @@ void open_pad(SDL_JoystickID jid, uint64_t ts) { d->last_snap = snap; push_reading(d, snap, ts); queue_event({CbType::Device, d, nullptr, ts, status, GameInputDeviceNoStatus, false, 0}); - std::fprintf(stderr, "[rt] gameinput: connected %s (%04x:%04x, player %d%s%s%s%s)\n", d->name.c_str(), - d->info.vendorId, d->info.productId, player + 1, d->is_dualsense ? ", DualSense trigger effects" : "", - d->has_trigger_rumble ? ", trigger rumble" : "", d->has_motion ? ", gyro" : "", - d->haptic ? ", force feedback" : ""); + RT_LOG_INFO("gameinput: connected %s (%04x:%04x, player %d%s%s%s%s)\n", d->name.c_str(), + d->info.vendorId, d->info.productId, player + 1, d->is_dualsense ? ", DualSense trigger effects" : "", + d->has_trigger_rumble ? ", trigger rumble" : "", d->has_motion ? ", gyro" : "", + d->haptic ? ", force feedback" : ""); } void close_pad(Device* d, uint64_t ts) { @@ -1511,7 +1516,7 @@ void close_pad(Device* d, uint64_t ts) { d->history.clear(); s.connected.erase(std::remove(s.connected.begin(), s.connected.end(), d), s.connected.end()); queue_event({CbType::Device, d, nullptr, ts, GameInputDeviceNoStatus, old, false, 0}); - std::fprintf(stderr, "[rt] gameinput: disconnected %s\n", d->name.c_str()); + RT_LOG_INFO("gameinput: disconnected %s\n", d->name.c_str()); } void ds_effect(float strength, uint8_t out[11]) { @@ -1723,8 +1728,8 @@ void raw_mouse_thread() { HWND hwnd = CreateWindowExW(0, L"LeonidaRawMouse", L"", 0, 0, 0, 0, 0, HWND_MESSAGE, nullptr, inst, nullptr); if (!hwnd) { - std::fprintf(stderr, "[rt] gameinput: no raw mouse input (window: error %lu); using the cursor position\n", - GetLastError()); + RT_LOG_WARN("gameinput: no raw mouse input (window: error %lu); using the cursor position\n", + GetLastError()); return; } RAWINPUTDEVICE dev{}; @@ -1733,13 +1738,13 @@ void raw_mouse_thread() { dev.dwFlags = RIDEV_INPUTSINK; // also while this (invisible) window has no focus; focus is checked per poll dev.hwndTarget = hwnd; if (!RegisterRawInputDevices(&dev, 1, sizeof(dev))) { - std::fprintf(stderr, "[rt] gameinput: no raw mouse input (register: error %lu); using the cursor position\n", - GetLastError()); + RT_LOG_WARN("gameinput: no raw mouse input (register: error %lu); using the cursor position\n", + GetLastError()); DestroyWindow(hwnd); return; } g_raw_ready = true; - std::fprintf(stderr, "[rt] gameinput: raw mouse input on (the right stick does not stop at the screen edge)\n"); + RT_LOG_INFO("gameinput: raw mouse input on (the right stick does not stop at the screen edge)\n"); MSG m; while (GetMessageW(&m, nullptr, 0, 0) > 0) DispatchMessageW(&m); } @@ -1786,7 +1791,7 @@ bool is_keyboard_pad(SDL_JoystickID jid) { return jid != 0 && jid == g_keyboard. void detach_keyboard_pad() { if (g_keyboard.js) SDL_CloseJoystick(g_keyboard.js); if (g_keyboard.id) SDL_DetachVirtualJoystick(g_keyboard.id); - if (g_keyboard.id) std::fprintf(stderr, "[rt] gameinput: keyboard pad removed\n"); + if (g_keyboard.id) RT_LOG_INFO("gameinput: keyboard pad removed\n"); g_keyboard = {}; } @@ -1829,14 +1834,14 @@ bool attach_keyboard_pad() { g_keyboard.id = SDL_AttachVirtualJoystick(&d); g_keyboard.js = g_keyboard.id ? SDL_OpenJoystick(g_keyboard.id) : nullptr; if (!g_keyboard.js) { - std::fprintf(stderr, "[rt] gameinput: cannot attach the keyboard pad: %s\n", SDL_GetError()); + RT_LOG_ERROR("gameinput: cannot attach the keyboard pad: %s\n", SDL_GetError()); detach_keyboard_pad(); g_keyboard.failed = true; return false; } - std::fprintf(stderr, "[rt] gameinput: keyboard pad attached (arrows d-pad, Enter A, Backspace B, X X, Y Y, " - "Q/E shoulders, Esc Menu, Tab View, WASD left stick, mouse right stick, right/left " - "button LT/RT)\n"); + RT_LOG_INFO("gameinput: keyboard pad attached (arrows d-pad, Enter A, Backspace B, X X, Y Y, " + "Q/E shoulders, Esc Menu, Tab View, WASD left stick, mouse right stick, right/left " + "button LT/RT)\n"); start_raw_mouse(); return true; } @@ -1913,15 +1918,15 @@ bool init_sdl() { #endif SDL_SetGamepadEventsEnabled(false); // the shim reads state directly; nothing drains an event queue if (!SDL_InitSubSystem(SDL_INIT_GAMEPAD)) { - std::fprintf(stderr, "[rt] gameinput: SDL gamepad init failed: %s; no controllers\n", SDL_GetError()); + RT_LOG_ERROR("gameinput: SDL gamepad init failed: %s; no controllers\n", SDL_GetError()); s.sdl_failed = true; return false; } SDL_SetGamepadEventsEnabled(false); s.sdl_ready = true; const int v = SDL_GetVersion(); - std::fprintf(stderr, "[rt] gameinput: SDL %d.%d.%d gamepads\n", SDL_VERSIONNUM_MAJOR(v), SDL_VERSIONNUM_MINOR(v), - SDL_VERSIONNUM_MICRO(v)); + RT_LOG_INFO("gameinput: SDL %d.%d.%d gamepads\n", SDL_VERSIONNUM_MAJOR(v), SDL_VERSIONNUM_MINOR(v), + SDL_VERSIONNUM_MICRO(v)); return true; } @@ -1972,8 +1977,8 @@ void poll_once() { edge != leonida::InputEdge::None) { publish_active(); if (!g_tracker.forced()) - std::fprintf(stderr, "[rt] gameinput: input in use: %s (%s, %s)\n", - leonida::input_family_name(d->family), d->name.c_str(), leonida::input_edge_name(edge)); + RT_LOG_INFO("gameinput: input in use: %s (%s, %s)\n", + leonida::input_family_name(d->family), d->name.c_str(), leonida::input_edge_name(edge)); } // A pad with sensors streams readings at ~125 Hz even when nothing else changes, so motion the title reads // between its frames is never stuck at the last button event; pads without sensors only read on change, as diff --git a/runtime/shims/library_loader.cpp b/runtime/shims/library_loader.cpp index 82dd75493..a94709d94 100644 --- a/runtime/shims/library_loader.cpp +++ b/runtime/shims/library_loader.cpp @@ -21,6 +21,7 @@ #include #include +#include "../core/log.h" #include "shims.h" namespace rt::shims::library_loader { @@ -121,7 +122,7 @@ HMODULE owned_handle(const std::string& path) { if (p.dll == dll) return reinterpret_cast(&p); pseudos().push_back(Pseudo{}); pseudos().back().dll = dll; - std::fprintf(stderr, "[rt] loader: %s is served by the shims (run-time load)\n", dll.c_str()); + RT_LOG_INFO("loader: %s is served by the shims (run-time load)\n", dll.c_str()); return reinterpret_cast(&pseudos().back()); } @@ -244,7 +245,7 @@ FARPROC WINAPI get_proc_address(HMODULE module, LPCSTR name) { static auto* seen = new std::set; std::lock_guard lock(*m); if (seen->insert(p->dll + "!" + what).second) - std::fprintf(stderr, "[rt] loader: GetProcAddress(%s, %s): not served\n", p->dll.c_str(), what.c_str()); + RT_LOG_WARN("loader: GetProcAddress(%s, %s): not served\n", p->dll.c_str(), what.c_str()); } SetLastError(ERROR_PROC_NOT_FOUND); return nullptr; diff --git a/runtime/shims/process.cpp b/runtime/shims/process.cpp index 08023ea78..58c424fa3 100644 --- a/runtime/shims/process.cpp +++ b/runtime/shims/process.cpp @@ -34,6 +34,7 @@ #include #include +#include "../core/log.h" #include "process_shim.h" #include "shims.h" @@ -201,9 +202,9 @@ DWORD_PTR __stdcall game_set_thread_affinity_mask(HANDLE thread, DWORD_PTR mask) static std::atomic substituted{0}; const int n = ++substituted; if (n <= 8) - std::fprintf(stderr, "[rt] process: SetThreadAffinityMask(0x%llx) names cores the host lacks; the thread stays, " - "answered its mask 0x%llx (call %d)\n", - static_cast(mask), static_cast(actual), n); + RT_LOG_WARN("process: SetThreadAffinityMask(0x%llx) names cores the host lacks; the thread stays, " + "answered its mask 0x%llx (call %d)\n", + static_cast(mask), static_cast(actual), n); // The log may have failed (a closed stderr pipe leaves ERROR_NO_DATA); the call itself succeeded. SetLastError(ERROR_SUCCESS); return actual; @@ -227,10 +228,10 @@ BOOL __stdcall game_set_thread_group_affinity(HANDLE thread, const GROUP_AFFINIT static std::atomic substituted{0}; const int n = ++substituted; if (n <= 8) - std::fprintf(stderr, "[rt] process: SetThreadGroupAffinity(group %u, 0x%llx) names cores or a group the host lacks; " - "the thread stays, answered group %u mask 0x%llx (call %d)\n", - static_cast(requested->Group), static_cast(requested->Mask), - static_cast(actual.Group), static_cast(actual.Mask), n); + RT_LOG_WARN("process: SetThreadGroupAffinity(group %u, 0x%llx) names cores or a group the host lacks; " + "the thread stays, answered group %u mask 0x%llx (call %d)\n", + static_cast(requested->Group), static_cast(requested->Mask), + static_cast(actual.Group), static_cast(actual.Mask), n); // The log may have failed (a closed stderr pipe leaves ERROR_NO_DATA); the call itself succeeded. SetLastError(ERROR_SUCCESS); return TRUE; @@ -239,7 +240,7 @@ BOOL __stdcall game_set_thread_group_affinity(HANDLE thread, const GROUP_AFFINIT // host's own affinity runs the same work, so it succeeds and changes nothing. BOOL __stdcall game_set_threadpool_affinity_mask(PTP_POOL, DWORD_PTR) { return TRUE; } void __cdecl game_abort() { - std::fprintf(stderr, "[rt] process: the game called abort()\n"); + RT_LOG_ERROR("process: the game called abort()\n"); // The game's signal() import is not shimmed: its handler goes into the host CRT's process-wide table, which // std::signal here reads too. UCRT's abort() raises SIGABRT before it terminates; do the same only when a // handler is installed, because raising it with the default action would terminate the host process. A handler diff --git a/runtime/shims/registry.cpp b/runtime/shims/registry.cpp index 6ec36e31c..be2ac8eda 100644 --- a/runtime/shims/registry.cpp +++ b/runtime/shims/registry.cpp @@ -12,6 +12,8 @@ #include #include +#include "../core/config.h" +#include "../core/log.h" #include "shims.h" #include "startup_trace.h" @@ -193,8 +195,7 @@ extern "C" uint64_t rt_unimplemented(const char* what, const CallInfo* info) { ",\"caller\":" + startup_trace::quote(module_offset(info->ret))); if (policy == UnimplementedPolicy::Stop) { - std::fprintf(stderr, - "[rt] STOP: unimplemented import %s called\n" + RT_LOG_ERROR("STOP: unimplemented import %s called\n" "[rt] caller %s\n" "[rt] rcx=0x%llx rdx=0x%llx r8=0x%llx r9=0x%llx\n" "[rt] return class: %s (LEONIDA_UNIMPLEMENTED=fail returns %s)\n", @@ -203,21 +204,21 @@ extern "C" uint64_t rt_unimplemented(const char* what, const CallInfo* info) { static_cast(info->r9), cls == ReturnClass::HResult ? "hresult" : "other", cls == ReturnClass::HResult ? "E_NOTIMPL" : "0"); if (IsDebuggerPresent()) { - std::fprintf(stderr, "[rt] debugger attached: breaking; continuing returns the `fail` value\n"); + RT_LOG_ERROR(" debugger attached: breaking; continuing returns the `fail` value\n"); std::fflush(stderr); __debugbreak(); return fail_value; } - std::fprintf(stderr, "[rt] no debugger attached: terminating the process (exit code %d)\n", kStopExitCode); + RT_LOG_ERROR(" no debugger attached: terminating the process (exit code %d)\n", kStopExitCode); std::fflush(stderr); TerminateProcess(GetCurrentProcess(), kStopExitCode); return 0; // not reached } if (first) - std::fprintf(stderr, "[rt] unimplemented: %s%s\n", what, - policy == UnimplementedPolicy::Fail - ? (cls == ReturnClass::HResult ? " (returns E_NOTIMPL)" : " (returns 0)") - : ""); + RT_LOG_WARN("unimplemented: %s%s\n", what, + policy == UnimplementedPolicy::Fail + ? (cls == ReturnClass::HResult ? " (returns E_NOTIMPL)" : " (returns 0)") + : ""); return policy == UnimplementedPolicy::Fail ? fail_value : 0; } @@ -286,8 +287,8 @@ void* make_common_stub() { rf->UnwindData = kUnwindOffset; // Without the table the stub still works; only a stack walk through it (a debugger, an exception) stops there. if (!RtlAddFunctionTable(rf, 1, reinterpret_cast(region))) - std::fprintf(stderr, "[rt] RtlAddFunctionTable failed for the unimplemented-import stub (error %lu): " - "stack walks cannot pass through it\n", GetLastError()); + RT_LOG_ERROR("RtlAddFunctionTable failed for the unimplemented-import stub (error %lu): " + "stack walks cannot pass through it\n", GetLastError()); FlushInstructionCache(GetCurrentProcess(), region, kRegionSize); return region; } @@ -308,11 +309,10 @@ UnimplementedPolicy parse_unimplemented_policy(const char* text, bool* valid) { UnimplementedPolicy unimplemented_policy() { int p = g_policy.load(); if (p < 0) { - char buf[32] = {}; - const DWORD n = GetEnvironmentVariableA("LEONIDA_UNIMPLEMENTED", buf, sizeof buf); + const std::string text = rt::config::get("loader.unimplemented").text; bool valid = true; - const UnimplementedPolicy parsed = parse_unimplemented_policy(n < sizeof buf ? buf : "?", &valid); - if (!valid) std::fprintf(stderr, "[rt] LEONIDA_UNIMPLEMENTED: expected log, fail or stop; using log\n"); + const UnimplementedPolicy parsed = parse_unimplemented_policy(text.c_str(), &valid); + if (!valid) RT_LOG_WARN("LEONIDA_UNIMPLEMENTED: expected log, fail or stop; using log\n"); int expected = -1; g_policy.compare_exchange_strong(expected, static_cast(parsed)); p = g_policy.load(); diff --git a/runtime/shims/shims.h b/runtime/shims/shims.h index 76a7e761f..d157a582b 100644 --- a/runtime/shims/shims.h +++ b/runtime/shims/shims.h @@ -1,5 +1,5 @@ // Shim registry: reimplementations of console-only imports. -// Add a DLL by writing a shims/.cpp with a SHIM_TABLE and listing it in CMakeLists.txt. +// Add a DLL by writing a shims/.cpp with a SHIM_TABLE and listing it in cmake/windows_runtime.cmake. #pragma once #include #include diff --git a/runtime/shims/startup_trace.h b/runtime/shims/startup_trace.h index 7b47d993a..4f14a715f 100644 --- a/runtime/shims/startup_trace.h +++ b/runtime/shims/startup_trace.h @@ -49,6 +49,8 @@ inline unsigned long long seq = 0; inline std::chrono::steady_clock::time_point start; inline void* veh = nullptr; inline thread_local bool in_handler = false; +// set_skip_int3(): whether the handler steps over an int3 in guest code (skip_int3, below). +inline std::atomic skip_int3_on{false}; // With nothing to handle it, OutputDebugStringW's DBG_PRINTEXCEPTION_WIDE_C falls back to OutputDebugStringA on its // own ANSI copy (ExceptionInformation[3]), a second, lossy exception for the same text. Every debug string on the // thread resets this, so only the exception right after the wide one, with that same pointer, is skipped. @@ -79,6 +81,10 @@ inline void append_escaped(std::string& out, const char* s, size_t n) { inline bool enabled() noexcept { return detail::on.load(std::memory_order_acquire); } +// loader.skip_int3 (LEONIDA_SKIP_INT3): whether the handler steps over an int3 in guest code (skip_int3, below). +// Off until this is called; gta6rt calls it from the setting before it opens the trace. +inline void set_skip_int3(bool skip) noexcept { detail::skip_int3_on.store(skip, std::memory_order_release); } + // A JSON string literal, quotes included. inline std::string quote(const std::string& s) { std::string out = "\""; @@ -191,12 +197,13 @@ inline void log_exception(const EXCEPTION_POINTERS& info) { } } -// LEONIDA_SKIP_INT3 (diagnostic, with --trace): an int3 in guest code is logged once per address and stepped over, -// so a boot can be followed past the title's soft asserts (an int3 followed by code that carries on). Off by default: -// a console title never reaches one in a correct run, so each skipped address is a finding, not a fix. +// loader.skip_int3 (LEONIDA_SKIP_INT3; diagnostic, with --trace): an int3 in guest code is logged once per address +// and stepped over, so a boot can be followed past the title's soft asserts (an int3 followed by code that carries +// on). Off by default: a console title never reaches one in a correct run, so each skipped address is a finding, not +// a fix. This header reads no setting itself: gta6rt turns it on with set_skip_int3() before it opens the trace. inline bool skip_int3(EXCEPTION_POINTERS* info) { - static const bool skip = GetEnvironmentVariableW(L"LEONIDA_SKIP_INT3", nullptr, 0) != 0; - if (!skip || info->ExceptionRecord->ExceptionCode != EXCEPTION_BREAKPOINT || !info->ContextRecord) return false; + if (!detail::skip_int3_on.load(std::memory_order_acquire)) return false; + if (info->ExceptionRecord->ExceptionCode != EXCEPTION_BREAKPOINT || !info->ContextRecord) return false; const auto* at = static_cast(info->ExceptionRecord->ExceptionAddress); if (!at || *at != 0xCC || info->ContextRecord->Rip != reinterpret_cast(at)) return false; static std::mutex m; diff --git a/runtime/shims/winhttp_offline.cpp b/runtime/shims/winhttp_offline.cpp index e8467f06c..1321d9d72 100644 --- a/runtime/shims/winhttp_offline.cpp +++ b/runtime/shims/winhttp_offline.cpp @@ -36,6 +36,7 @@ #include #include +#include "../core/log.h" #include "shims.h" namespace rt::winhttp { @@ -166,7 +167,9 @@ void log_refused(const Handle* request) { static auto* mutex = new std::mutex; const std::wstring server = server_of(request); std::lock_guard lock(*mutex); - if (logged->insert(server).second) std::fwprintf(stderr, L"[rt] winhttp: offline, refused %ls\n", server.c_str()); + if (logged->insert(server).second && rt::log::enabled(rt::log::Level::Warn)) { + std::fwprintf(stderr, L"[rt] winhttp: offline, refused %ls\n", server.c_str()); + } } void CALLBACK send_failed(PTP_CALLBACK_INSTANCE, void* context) { @@ -190,7 +193,7 @@ BOOL fail(DWORD error) { HINTERNET WINAPI open_session(LPCWSTR, DWORD, LPCWSTR, LPCWSTR, DWORD flags) { static std::once_flag once; std::call_once(once, [] { - std::fprintf(stderr, "[rt] winhttp: offline; requests fail with ERROR_WINHTTP_CANNOT_CONNECT\n"); + RT_LOG_INFO("winhttp: offline; requests fail with ERROR_WINHTTP_CANNOT_CONNECT\n"); }); return make_handle(Kind::Session, nullptr, (flags & WINHTTP_FLAG_ASYNC) != 0); } diff --git a/runtime/shims/xbox_present.cpp b/runtime/shims/xbox_present.cpp index dd5f810cf..c3653cdb5 100644 --- a/runtime/shims/xbox_present.cpp +++ b/runtime/shims/xbox_present.cpp @@ -2,6 +2,8 @@ #include "d3d12_trace.h" +#include "../core/config.h" +#include "../core/log.h" #include "../src/vulkan_present.h" #include @@ -9,6 +11,7 @@ #include #include #include +#include namespace rt::d3d12 { @@ -23,7 +26,7 @@ HRESULT from_pacer(std::int32_t value) { return HRESULT(value); } void log_once(bool& done, const char* text) { if (done) return; done = true; - std::fprintf(stderr, "[rt] present: %s\n", text); + RT_LOG_WARN("present: %s\n", text); } } // namespace @@ -34,33 +37,27 @@ XboxPresentation::XboxPresentation(std::unique_ptr presenter, l pacer_(clock ? *clock : *own_clock_) { // A present waiting for a swapchain image gives up once SuspendX has been called. presenter_->set_abort([this] { return pacer_.suspended(); }); - // LEONIDA_SDR_EOTF=gamma22 (or 2.2, any case) decodes SDR with a pure power of 2.2 instead of piecewise sRGB; "srgb" or - // unset keeps the default; anything else (also a value too long for the buffer, ERANGE) is logged once and ignored. - char eotf[32] = {}; - std::size_t eotf_length = 0; - const errno_t env = getenv_s(&eotf_length, eotf, "LEONIDA_SDR_EOTF"); - if (env == 0 && eotf_length > 1) { - if (!_stricmp(eotf, "gamma22") || !_stricmp(eotf, "2.2")) sdr_eotf_ = leonida::PresentPlanes::SdrEotf::gamma22; - else if (_stricmp(eotf, "srgb") != 0) - std::fprintf(stderr, "[rt] present: LEONIDA_SDR_EOTF=%s is not srgb, gamma22 or 2.2: piecewise sRGB used\n", eotf); - } else if (env == ERANGE) { - std::fprintf(stderr, "[rt] present: LEONIDA_SDR_EOTF is too long to be srgb, gamma22 or 2.2: piecewise sRGB used\n"); + // present.sdr_eotf (LEONIDA_SDR_EOTF): gamma22 (or 2.2, any case) decodes SDR with a pure power of 2.2 instead + // of piecewise sRGB; "srgb" or unset keeps the default; anything else (also a value of 32 characters or more, + // the size of the buffer the variable was read into before it moved to the table) is logged once and ignored. + const std::string eotf = rt::config::get("present.sdr_eotf").text; + if (eotf.size() >= 32) { + RT_LOG_WARN("present: LEONIDA_SDR_EOTF is too long to be srgb, gamma22 or 2.2: piecewise sRGB " + "used\n"); + } else if (!_stricmp(eotf.c_str(), "gamma22") || !_stricmp(eotf.c_str(), "2.2")) { + sdr_eotf_ = leonida::PresentPlanes::SdrEotf::gamma22; + } else if (_stricmp(eotf.c_str(), "srgb") != 0) { + RT_LOG_WARN("present: LEONIDA_SDR_EOTF=%s is not srgb, gamma22 or 2.2: piecewise sRGB used\n", + eotf.c_str()); } // LEONIDA_PRESENT_UNCAP (any non-empty value other than "0") takes the frame-rate cap off: a WaitFrameEventX // hands a token out at once instead of at the next interval origin, and presents go unsynced (MAILBOX or // IMMEDIATE, not FIFO), so the frame rate is whatever the title renders. Registration and suspension still // apply, so the title keeps its call sequence. - { - char* value = nullptr; - std::size_t length = 0; - if (_dupenv_s(&value, &length, "LEONIDA_PRESENT_UNCAP") == 0 && value) { - if (value[0] != '\0' && std::strcmp(value, "0") != 0) { - pacer_.set_uncapped(true); - std::fprintf(stderr, "[rt] present: LEONIDA_PRESENT_UNCAP is set: frame events return at once and " - "presents do not wait for vblank\n"); - } - std::free(value); - } + if (const std::string uncap = rt::config::get("present.uncap").text; !uncap.empty() && uncap != "0") { + pacer_.set_uncapped(true); + RT_LOG_INFO("present: LEONIDA_PRESENT_UNCAP is set: frame events return at once and " + "presents do not wait for vblank\n"); } display_white_thread_ = std::thread([this] { display_white_worker(); }); } diff --git a/runtime/shims/xg_xs.cpp b/runtime/shims/xg_xs.cpp index b45fbf689..b190d284a 100644 --- a/runtime/shims/xg_xs.cpp +++ b/runtime/shims/xg_xs.cpp @@ -32,6 +32,7 @@ #include #include +#include "../core/log.h" #include "shims.h" namespace { @@ -45,8 +46,8 @@ void warn_once(std::atomic& warned, const char* what, int slot, const void char name[64]; if (slot < 0) std::snprintf(name, sizeof(name), "%s", what); else std::snprintf(name, sizeof(name), "%s%d", what, slot); - std::fprintf(stderr, "[rt] xg_xs: %s: no console texture layout on the PC; E_NOTIMPL (caller %s, logged once)\n", - name, rt::shims::module_offset(reinterpret_cast(caller)).c_str()); + RT_LOG_WARN("xg_xs: %s: no console texture layout on the PC; E_NOTIMPL (caller %s, logged once)\n", + name, rt::shims::module_offset(reinterpret_cast(caller)).c_str()); } ULONG __stdcall computer_add_ref(void*) { return 1; } diff --git a/runtime/shims/xgameruntime.cpp b/runtime/shims/xgameruntime.cpp index 2b44229be..6a1382838 100644 --- a/runtime/shims/xgameruntime.cpp +++ b/runtime/shims/xgameruntime.cpp @@ -34,6 +34,8 @@ #include #include +#include "../core/config.h" +#include "../core/log.h" #include "file_system.h" #include "shims.h" @@ -75,9 +77,9 @@ std::atomic g_api_refs{0}; HRESULT api_initialize(const char* which, ULONG gdk_ver, ULONG gs_ver, int mode, const ApiImplOptions* options) { if (g_api_refs.fetch_add(1) == 0) - std::fprintf(stderr, "[rt] xgameruntime: %s(gdk=%lu, gs=%lu, mode=%#x, options=%s) (offline)\n", which, - gdk_ver, gs_ver, mode & 0xFF, - options ? (options->is_inline ? "inline game config" : "default game config") : "none"); + RT_LOG_INFO("xgameruntime: %s(gdk=%lu, gs=%lu, mode=%#x, options=%s) (offline)\n", which, + gdk_ver, gs_ver, mode & 0xFF, + options ? (options->is_inline ? "inline game config" : "default game config") : "none"); return S_OK; } @@ -169,7 +171,7 @@ ULONG STDMETHODCALLTYPE object_release(void* self) { template uint64_t STDMETHODCALLTYPE private_slot(void*) { static std::atomic s_logged{false}; if (!s_logged.exchange(true)) - std::fprintf(stderr, "[rt] xgameruntime: XThreadingImpl private slot %d called; answering 0\n", Slot); + RT_LOG_WARN("xgameruntime: XThreadingImpl private slot %d called; answering 0\n", Slot); return 0; } @@ -179,8 +181,8 @@ template uint64_t STDMETHODCALLTYPE private_slot(void*) { HRESULT STDMETHODCALLTYPE begin_alloc_not_provided(void*) { static std::atomic s_logged{false}; if (!s_logged.exchange(true)) - std::fprintf(stderr, "[rt] xgameruntime: XThreadingImpl slot 8 (XAsyncBeginAlloc) called; not provided, " - "returning E_NOTIMPL\n"); + RT_LOG_WARN("xgameruntime: XThreadingImpl slot 8 (XAsyncBeginAlloc) called; not provided, " + "returning E_NOTIMPL\n"); return E_NOTIMPL; } @@ -242,7 +244,7 @@ std::mutex g_error_mutex{}; // guards g_error_callback + g_error_context as on HRESULT STDMETHODCALLTYPE error_report(void*, HRESULT hr, const char* message) { static std::atomic s_logged{0}; if (s_logged.fetch_add(1) < 64) - std::fprintf(stderr, "[rt] xgameruntime: XErrorReport(0x%08lx, %s)\n", static_cast(hr), + RT_LOG_ERROR("xgameruntime: XErrorReport(0x%08lx, %s)\n", static_cast(hr), message ? message : "(null)"); std::lock_guard lock(g_error_mutex); if (XErrorCallback cb = g_error_callback.load()) cb(hr, message, g_error_context.load()); @@ -634,7 +636,7 @@ HRESULT WINAPI QueryApiImpl(const GUID* class_id, REFIID interface_id, void** ou print_guid(iid, &interface_id); static std::atomic s_logged{0}; if (s_logged.fetch_add(1) < 256) // one line per request, bounded - std::fprintf(stderr, "[rt] xgameruntime: QueryApiImpl(class %s, interface %s): not provided yet\n", cls, iid); + RT_LOG_WARN("xgameruntime: QueryApiImpl(class %s, interface %s): not provided yet\n", cls, iid); return kClassNotProvided; } @@ -653,7 +655,7 @@ HRESULT WINAPI GetApiVersionImpl(uint64_t* first, uint64_t* second) { // HRESULT XGameRuntimeInitialize(). Reference counted, as in the GDK: each call needs an XGameRuntimeUninitialize. HRESULT __stdcall XGameRuntimeInitialize() { - if (g_runtime_refs.fetch_add(1) == 0) std::fprintf(stderr, "[rt] xgameruntime: initialized (offline)\n"); + if (g_runtime_refs.fetch_add(1) == 0) RT_LOG_INFO("xgameruntime: initialized (offline)\n"); return S_OK; } @@ -675,10 +677,10 @@ enum class XSystemDeviceType : uint32_t { // XSystemDeviceType XSystemGetDeviceType(). The package is the Xbox Series build, so report Series X (Anaconda). // LEONIDA_DEVICE_TYPE=<0..8> overrides it, for trying other code paths on day one. uint32_t __stdcall XSystemGetDeviceType() { - char s[16]; - const DWORD n = GetEnvironmentVariableA("LEONIDA_DEVICE_TYPE", s, sizeof(s)); - if (n > 0 && n < sizeof(s)) { - int v = std::atoi(s); + // A value of 16 characters or more is ignored, as before the setting moved to the table. + const std::string s = rt::config::get("system.device_type").text; + if (s.size() < 16) { + int v = std::atoi(s.c_str()); if (v >= 0 && v <= 8) return static_cast(v); } return static_cast(XSystemDeviceType::XboxScarlettAnaconda); @@ -824,10 +826,10 @@ XSystemAnalyticsInfo __stdcall XSystemGetAnalyticsInfo() { copy_string_padded(info.form, sizeof(info.form), "Xbox Series X"); } - char form_override[64]; - const DWORD n = GetEnvironmentVariableA("LEONIDA_ANALYTICS_FORM", form_override, sizeof(form_override)); - if (n > 0 && n < sizeof(form_override)) { - copy_string_padded(info.form, sizeof(info.form), form_override); + // A form of 64 characters or more is ignored, as before the setting moved to the table. + const std::string form_override = rt::config::get("system.analytics_form").text; + if (!form_override.empty() && form_override.size() < 64) { + copy_string_padded(info.form, sizeof(info.form), form_override.c_str()); } return info; } @@ -839,15 +841,22 @@ constexpr char kDefaultPackageIdentifier[XPACKAGE_IDENTIFIER_MAX_LENGTH] = "Leon static_assert(sizeof(kDefaultPackageIdentifier) == XPACKAGE_IDENTIFIER_MAX_LENGTH, "default package identifier must match XPACKAGE_IDENTIFIER_MAX_LENGTH"); +// The identifier of the running package: system.package_id (LEONIDA_PACKAGE_ID). A value too long for an +// identifier is ignored and the default is used, as before the setting moved to the table. +static std::string configured_package_identifier() { + std::string id = rt::config::get("system.package_id").text; + if (id.empty() || id.size() >= XPACKAGE_IDENTIFIER_MAX_LENGTH) id = kDefaultPackageIdentifier; + return id; +} + // HRESULT XPackageGetCurrentProcessPackageIdentifier(size_t bufferSize, char* buffer). // Retrieves the package identifier string for the current process. HRESULT __stdcall XPackageGetCurrentProcessPackageIdentifier(size_t bufferSize, char* buffer) { if (!buffer || bufferSize == 0) return E_INVALIDARG; - char id[XPACKAGE_IDENTIFIER_MAX_LENGTH] = {}; - const DWORD n = GetEnvironmentVariableA("LEONIDA_PACKAGE_ID", id, sizeof(id)); - const char* selected = (n > 0 && n < sizeof(id)) ? id : kDefaultPackageIdentifier; - const size_t len = std::strlen(selected); + const std::string id = configured_package_identifier(); + const char* selected = id.c_str(); + const size_t len = id.size(); if (bufferSize < len + 1) return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); std::memcpy(buffer, selected, len + 1); @@ -869,29 +878,14 @@ static std::unordered_map s_active_mounts; static std::string resolve_package_path(const char* packageIdentifier, HRESULT& result) { // Check against configured process/game package identifier; mounting the game itself is denied - char game_id[XPACKAGE_IDENTIFIER_MAX_LENGTH] = {}; - const DWORD n = GetEnvironmentVariableA("LEONIDA_PACKAGE_ID", game_id, sizeof(game_id)); - const char* process_id = (n > 0 && n < sizeof(game_id)) ? game_id : kDefaultPackageIdentifier; - - if (std::strcmp(packageIdentifier, process_id) == 0) { + if (configured_package_identifier() == packageIdentifier) { result = E_ACCESSDENIED; return {}; } // Check optional installed content packages mapping: "id1=path1;id2=path2" - DWORD capacity = GetEnvironmentVariableW(L"LEONIDA_CONTENT_PACKAGES", nullptr, 0); - std::wstring wide_mapping; - DWORD map_len = 0; - while (capacity > 0) { - wide_mapping.resize(capacity); - map_len = GetEnvironmentVariableW(L"LEONIDA_CONTENT_PACKAGES", wide_mapping.data(), capacity); - if (map_len < capacity) break; - capacity = map_len; - } - if (map_len > 0 && map_len < capacity) { - // The GDK returns UTF-8 bytes even when Windows uses a legacy ANSI code page. - wide_mapping.resize(map_len); - std::string mapping = utf8_of(wide_mapping); + // The table gives UTF-8, which is what the GDK returns even when Windows uses a legacy ANSI code page. + if (std::string mapping = rt::config::get("system.content_packages").text; !mapping.empty()) { char* token = mapping.data(); while (token && *token) { char* sep = std::strchr(token, ';'); @@ -978,11 +972,9 @@ HRESULT __stdcall XPackageGetMountPath(XPackageMountHandle mount, size_t pathSiz // bool XPackageIsPackagedProcess(). // Returns true on Xbox Series console. LEONIDA_PACKAGED=0 overrides it. bool __stdcall XPackageIsPackagedProcess() { - char s[16]; - const DWORD n = GetEnvironmentVariableA("LEONIDA_PACKAGED", s, sizeof(s)); - if (n > 0 && n < sizeof(s)) { - if (std::atoi(s) == 0) return false; - } + // A value of 16 characters or more is ignored, as before the setting moved to the table. + const std::string s = rt::config::get("system.packaged").text; + if (s.size() < 16 && std::atoi(s.c_str()) == 0) return false; return true; } @@ -1005,7 +997,7 @@ const GUID* const kPackageIids[] = {&kPackage1, &kPackage2, &kPackage3, nullptr} template HRESULT STDMETHODCALLTYPE package_not_implemented(void*) { static std::atomic s_logged{false}; if (!s_logged.exchange(true)) - std::fprintf(stderr, "[rt] xgameruntime: XPackageImpl slot %d not implemented offline (E_NOTIMPL)\n", Slot); + RT_LOG_WARN("xgameruntime: XPackageImpl slot %d not implemented offline (E_NOTIMPL)\n", Slot); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE pkg_identifier(void*, size_t size, char* buffer) { @@ -1016,9 +1008,9 @@ bool STDMETHODCALLTYPE pkg_is_packaged(void*) { return XPackageIsPackagedProcess // there is no folder or no config. Wide on purpose: a game folder named outside the ANSI code page must reach the file // intact. std::string package_config() { - wchar_t env[MAX_PATH] = {}; - const DWORD n = GetEnvironmentVariableW(L"LEONIDA_GAME_DIR", env, MAX_PATH); - const std::filesystem::path dir = (n > 0 && n < MAX_PATH) ? std::filesystem::path(env) : rt::fs::game_dir(); + // A folder of MAX_PATH characters or more is ignored, as before the setting moved to the table. + std::filesystem::path dir = rt::config::path("paths.game_dir"); + if (dir.empty() || dir.native().size() >= MAX_PATH) dir = rt::fs::game_dir(); if (dir.empty()) return {}; std::ifstream f(dir / L"MicrosoftGame.Config", std::ios::binary); if (!f) return {}; @@ -1210,7 +1202,7 @@ HRESULT STDMETHODCALLTYPE game_get_title_id(void*, uint32_t* title_id) { if (!package_title_id(id)) { static std::atomic s_logged{false}; if (!s_logged.exchange(true)) - std::fprintf(stderr, "[rt] xgameruntime: XGameGetXboxTitleId: no in MicrosoftGame.Config\n"); + RT_LOG_ERROR("xgameruntime: XGameGetXboxTitleId: no in MicrosoftGame.Config\n"); return E_FAIL; } *title_id = id; @@ -1220,8 +1212,8 @@ HRESULT STDMETHODCALLTYPE game_get_title_id(void*, uint32_t* title_id) { // void XLaunchNewGame(const char* exePath, const char* args, XUserHandle defaultUser): on the console this ends the // title and starts another. Offline there is no other title to start; the call is logged and returns. void STDMETHODCALLTYPE game_launch_new(void*, const char* exe_path, const char* args, void*) { - std::fprintf(stderr, "[rt] xgameruntime: XLaunchNewGame(\"%s\", \"%s\") ignored offline\n", - exe_path ? exe_path : "", args ? args : ""); + RT_LOG_WARN("xgameruntime: XLaunchNewGame(\"%s\", \"%s\") ignored offline\n", + exe_path ? exe_path : "", args ? args : ""); } // HRESULT XLaunchRestartOnCrash(const char* args, uint32_t reserved): asks the console to restart the title after a @@ -1229,7 +1221,7 @@ void STDMETHODCALLTYPE game_launch_new(void*, const char* exe_path, const char* HRESULT STDMETHODCALLTYPE game_restart_on_crash(void*, const char*, uint32_t) { static std::atomic s_logged{false}; if (!s_logged.exchange(true)) - std::fprintf(stderr, "[rt] xgameruntime: XLaunchRestartOnCrash: no restart is registered offline\n"); + RT_LOG_WARN("xgameruntime: XLaunchRestartOnCrash: no restart is registered offline\n"); return S_OK; } diff --git a/runtime/shims/xgameruntime_gamesave.cpp b/runtime/shims/xgameruntime_gamesave.cpp index fdc5ddec3..1fdc2f774 100644 --- a/runtime/shims/xgameruntime_gamesave.cpp +++ b/runtime/shims/xgameruntime_gamesave.cpp @@ -45,6 +45,9 @@ #include #include +#include "../core/config.h" +#include "../core/log.h" + namespace { namespace fs = std::filesystem; @@ -167,10 +170,12 @@ std::string narrow(const std::wstring& w) { } fs::path save_root() { + // paths.save_dir (LEONIDA_SAVE_DIR). A folder of MAX_PATH * 2 characters or more is ignored, as before the + // setting moved to the table. + if (fs::path dir = rt::config::path("paths.save_dir"); !dir.empty() && dir.native().size() < MAX_PATH * 2) + return dir; wchar_t buffer[MAX_PATH * 2]; - DWORD n = GetEnvironmentVariableW(L"LEONIDA_SAVE_DIR", buffer, static_cast(std::size(buffer))); - if (n > 0 && n < std::size(buffer)) return fs::path(buffer); - n = GetEnvironmentVariableW(L"LOCALAPPDATA", buffer, static_cast(std::size(buffer))); + const DWORD n = GetEnvironmentVariableW(L"LOCALAPPDATA", buffer, static_cast(std::size(buffer))); if (n > 0 && n < std::size(buffer)) return fs::path(buffer) / L"Leonida" / L"saves"; return {}; } @@ -430,7 +435,7 @@ HRESULT open_provider(XUserHandle user, const char* config_id, XGameSaveProvider *out = p; static std::atomic s_logged{0}; if (s_logged.fetch_add(1) == 0) - std::fprintf(stderr, "[rt] xgamesave: offline provider for \"%s\" at %ls\n", config_id, user_dir.c_str()); + RT_LOG_INFO("xgamesave: offline provider for \"%s\" at %ls\n", config_id, user_dir.c_str()); return S_OK; } diff --git a/runtime/shims/xgameruntime_offline.cpp b/runtime/shims/xgameruntime_offline.cpp index cc7a91d21..419d0385c 100644 --- a/runtime/shims/xgameruntime_offline.cpp +++ b/runtime/shims/xgameruntime_offline.cpp @@ -41,6 +41,9 @@ #include #include +#include "../core/config.h" +#include "../core/log.h" + namespace rt::shims { void* xgameruntime_user_new_handle(); // xgameruntime_user.cpp } @@ -84,7 +87,7 @@ HRESULT answer(ClassObject* object, const GUID* begin, const GUID* end, REFIID i template HRESULT STDMETHODCALLTYPE unknown_slot(void*) { static std::atomic s_logged{false}; if (!s_logged.exchange(true)) - std::fprintf(stderr, "[rt] xgameruntime: %s slot %d (unknown in the docs) called; E_NOTIMPL\n", Class, Slot); + RT_LOG_WARN("xgameruntime: %s slot %d (unknown in the docs) called; E_NOTIMPL\n", Class, Slot); return E_NOTIMPL; } @@ -94,7 +97,7 @@ template HRESULT STDMETHODCALLTYPE unknown_slot(vo template HRESULT STDMETHODCALLTYPE offline_failure(void*) { static std::atomic s_logged{false}; if (!s_logged.exchange(true)) - std::fprintf(stderr, "[rt] xgameruntime: %s slot %d is not available offline (E_FAIL)\n", Class, Slot); + RT_LOG_WARN("xgameruntime: %s slot %d is not available offline (E_FAIL)\n", Class, Slot); return E_FAIL; } @@ -105,11 +108,7 @@ constexpr GUID kEventClass = {0xbbfbdcc7, 0xbfe7, 0x409b, {0xa5, 0xca, 0xed, 0xf std::atomic g_events{0}; bool log_every_event() { - static const bool on = [] { - char value[4] = {}; - size_t length = 0; - return getenv_s(&length, value, "LEONIDA_LOG_GAME_EVENTS") == 0 && length == 2 && value[0] == '1'; - }(); + static const bool on = rt::config::get("system.log_game_events").text == "1"; return on; } @@ -120,11 +119,11 @@ HRESULT STDMETHODCALLTYPE event_write(void*, XUserHandle, const char*, const cha if (!name) return E_INVALIDARG; const long n = g_events.fetch_add(1); if (log_every_event()) - std::fprintf(stderr, "[rt] game event %s dimensions=%s measurements=%s\n", name, dimensions ? dimensions : "", + RT_LOG_DEBUG("game event %s dimensions=%s measurements=%s\n", name, dimensions ? dimensions : "", measurements ? measurements : ""); else if (n == 0) - std::fprintf(stderr, "[rt] xgameruntime: game events are dropped offline (first: %s; " - "LEONIDA_LOG_GAME_EVENTS=1 logs them)\n", name); + RT_LOG_INFO("xgameruntime: game events are dropped offline (first: %s; " + "LEONIDA_LOG_GAME_EVENTS=1 logs them)\n", name); return S_OK; } @@ -192,9 +191,9 @@ HRESULT STDMETHODCALLTYPE ui_message_dialog_async(void*, XAsyncBlock* async, con const auto button = static_cast(default_button); if (button > 2) return E_INVALIDARG; const char* labels[] = {first, second, third}; - std::fprintf(stderr, "[rt] game dialog: \"%s\": %s [buttons: %s%s%s%s%s; answered: %s]\n", title ? title : "", - content ? content : "", first ? first : "", second ? " / " : "", second ? second : "", - third ? " / " : "", third ? third : "", labels[button] ? labels[button] : "(default)"); + RT_LOG_INFO("game dialog: \"%s\": %s [buttons: %s%s%s%s%s; answered: %s]\n", title ? title : "", + content ? content : "", first ? first : "", second ? " / " : "", second ? second : "", + third ? " / " : "", third ? third : "", labels[button] ? labels[button] : "(default)"); return XAsyncBegin(async, reinterpret_cast(static_cast(button)), &kDialogIdentity, "XGameUiShowMessageDialogAsync", dialog_provider); } @@ -208,7 +207,7 @@ HRESULT STDMETHODCALLTYPE ui_message_dialog_result(void*, XAsyncBlock* async, XG // 14: HRESULT XGameUiShowErrorDialogAsync(XAsyncBlock* async, HRESULT errorCode, const char* context) HRESULT STDMETHODCALLTYPE ui_error_dialog_async(void*, XAsyncBlock* async, HRESULT code, const char* context) { if (!async) return E_POINTER; - std::fprintf(stderr, "[rt] game error dialog: HRESULT 0x%08lX%s%s [dismissed]\n", static_cast(code), + RT_LOG_ERROR("game error dialog: HRESULT 0x%08lX%s%s [dismissed]\n", static_cast(code), context ? " context " : "", context ? context : ""); return XAsyncBegin(async, nullptr, &kErrorDialogIdentity, "XGameUiShowErrorDialogAsync", error_dialog_provider); } @@ -327,7 +326,7 @@ bool STDMETHODCALLTYPE streaming_unregister(void*) { return true; } template HRESULT STDMETHODCALLTYPE client_not_connected(void*) { static std::atomic s_logged{false}; if (!s_logged.exchange(true)) - std::fprintf(stderr, "[rt] xgameruntime: XGameStreamingImpl slot %d: no streaming client offline\n", Slot); + RT_LOG_WARN("xgameruntime: XGameStreamingImpl slot %d: no streaming client offline\n", Slot); return E_GAMESTREAMING_NOT_INITIALIZED; } static_assert((static_cast(E_GAMESTREAMING_NOT_INITIALIZED) & 0xFF) == 0, "reads as false in al"); @@ -397,11 +396,7 @@ struct XDisplayHdrModeInfo { }; bool hdr_requested() { - static const bool on = [] { - char value[4] = {}; - size_t length = 0; - return getenv_s(&length, value, "LEONIDA_HDR") == 0 && length == 2 && value[0] == '1'; - }(); + static const bool on = rt::config::get("system.hdr").text == "1"; return on; } @@ -413,8 +408,8 @@ uint32_t STDMETHODCALLTYPE display_try_enable_hdr(void*, XDisplayHdrModePreferen if (info) *info = on ? XDisplayHdrModeInfo{0.01f, 1000.0f, 1000.0f} : XDisplayHdrModeInfo{}; static std::atomic s_logged{false}; if (!s_logged.exchange(true)) - std::fprintf(stderr, "[rt] xgameruntime: XDisplayTryEnableHdrMode: HDR %s\n", - on ? "enabled (LEONIDA_HDR=1)" : "disabled (SDR output; LEONIDA_HDR=1 asks for HDR)"); + RT_LOG_INFO("xgameruntime: XDisplayTryEnableHdrMode: HDR %s\n", + on ? "enabled (LEONIDA_HDR=1)" : "disabled (SDR output; LEONIDA_HDR=1 asks for HDR)"); return static_cast(on ? XDisplayHdrModeResult::Enabled : XDisplayHdrModeResult::Disabled); } diff --git a/runtime/shims/xgameruntime_store.cpp b/runtime/shims/xgameruntime_store.cpp index 800e4083f..ff5eaebb4 100644 --- a/runtime/shims/xgameruntime_store.cpp +++ b/runtime/shims/xgameruntime_store.cpp @@ -37,6 +37,8 @@ #include #include +#include "../core/log.h" + namespace { // ---- Public GDK types (XStore.h, as the GDK reference documents them) ---- @@ -121,7 +123,7 @@ template void close_handle(std::unordered_set& set, T* h) template HRESULT STDMETHODCALLTYPE offline_failure(void*) { static std::atomic s_logged{false}; if (!s_logged.exchange(true)) - std::fprintf(stderr, "[rt] xgameruntime: XStoreImpl slot %d is not available offline (E_FAIL)\n", Slot); + RT_LOG_WARN("xgameruntime: XStoreImpl slot %d is not available offline (E_FAIL)\n", Slot); return E_FAIL; } @@ -129,7 +131,7 @@ template HRESULT STDMETHODCALLTYPE offline_failure(void*) { template HRESULT STDMETHODCALLTYPE unknown_slot(void*) { static std::atomic s_logged{false}; if (!s_logged.exchange(true)) - std::fprintf(stderr, "[rt] xgameruntime: XStoreImpl slot %d (no documented signature) called; E_NOTIMPL\n", Slot); + RT_LOG_WARN("xgameruntime: XStoreImpl slot %d (no documented signature) called; E_NOTIMPL\n", Slot); return E_NOTIMPL; } @@ -194,7 +196,7 @@ HRESULT STDMETHODCALLTYPE store_create_context(void*, XUserHandle, XStoreContext *out = new_handle(g_contexts); static std::atomic s_logged{false}; if (!s_logged.exchange(true)) - std::fprintf(stderr, "[rt] xgameruntime: XStore offline: the game license is active, no add-ons, no updates\n"); + RT_LOG_INFO("xgameruntime: XStore offline: the game license is active, no add-ons, no updates\n"); return S_OK; } diff --git a/runtime/shims/xgameruntime_user.cpp b/runtime/shims/xgameruntime_user.cpp index e32395646..1e9e90c79 100644 --- a/runtime/shims/xgameruntime_user.cpp +++ b/runtime/shims/xgameruntime_user.cpp @@ -25,12 +25,16 @@ #include #include #include +#include #include #include #include #include +#include "../core/config.h" +#include "../core/log.h" + namespace { // ---- Public GDK types (XUser.h, as the GDK reference documents them) ---- @@ -65,20 +69,17 @@ const char* gamertag() { static char tag[16] = "Player"; static std::once_flag once; std::call_once(once, [] { - size_t length = 0; // with the terminator; 0 when unset - if (getenv_s(&length, nullptr, 0, "LEONIDA_GAMERTAG") != 0 || length <= 1) return; - if (length - 1 > 15) { - std::fprintf(stderr, "[rt] xgameruntime: LEONIDA_GAMERTAG is longer than 15 characters; using \"Player\"\n"); + const std::string value = rt::config::get("system.gamertag").text; // "Player" when nothing sets it + if (value.size() > 15) { + RT_LOG_WARN("xgameruntime: LEONIDA_GAMERTAG is longer than 15 characters; using \"Player\"\n"); return; } - char value[16] = {}; - if (getenv_s(&length, value, "LEONIDA_GAMERTAG") != 0) return; - for (size_t i = 0; i + 1 < length; ++i) - if (static_cast(value[i]) < 0x20 || static_cast(value[i]) > 0x7e) { - std::fprintf(stderr, "[rt] xgameruntime: LEONIDA_GAMERTAG is not printable ASCII; using \"Player\"\n"); + for (const char c : value) + if (static_cast(c) < 0x20 || static_cast(c) > 0x7e) { + RT_LOG_WARN("xgameruntime: LEONIDA_GAMERTAG is not printable ASCII; using \"Player\"\n"); return; } - std::memcpy(tag, value, length); + std::memcpy(tag, value.c_str(), value.size() + 1); }); return tag; } @@ -265,13 +266,13 @@ HRESULT STDMETHODCALLTYPE user_get_state(void*, XUserHandle user, XUserState* st template HRESULT STDMETHODCALLTYPE unknown_slot(void*) { static std::atomic s_logged{false}; if (!s_logged.exchange(true)) - std::fprintf(stderr, "[rt] xgameruntime: XUserImpl slot %d has no public signature; answering E_NOTIMPL\n", Slot); + RT_LOG_WARN("xgameruntime: XUserImpl slot %d has no public signature; answering E_NOTIMPL\n", Slot); return E_NOTIMPL; } template uint64_t STDMETHODCALLTYPE private_slot(void*) { static std::atomic s_logged{false}; if (!s_logged.exchange(true)) - std::fprintf(stderr, "[rt] xgameruntime: XUserImpl private slot %d called; answering 0\n", Slot); + RT_LOG_WARN("xgameruntime: XUserImpl private slot %d called; answering 0\n", Slot); return 0; } @@ -281,8 +282,8 @@ template uint64_t STDMETHODCALLTYPE private_slot(void*) { template HRESULT STDMETHODCALLTYPE offline_failure(void*) { static std::atomic s_logged{false}; if (!s_logged.exchange(true)) - std::fprintf(stderr, "[rt] xgameruntime: XUserImpl slot %d is not available offline (HRESULT 0x%08lx)\n", Slot, - static_cast(Error)); + RT_LOG_WARN("xgameruntime: XUserImpl slot %d is not available offline (HRESULT 0x%08lx)\n", Slot, + static_cast(Error)); return Error; } diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp index 1e286d712..84a91c70c 100644 --- a/runtime/shims/xmem.cpp +++ b/runtime/shims/xmem.cpp @@ -33,6 +33,7 @@ #include #include +#include "../core/log.h" #include "shims.h" #include "startup_trace.h" #include "xmem.h" @@ -98,7 +99,7 @@ void __stdcall XMemFreeDefault(void* p, uint64_t attributes) { BOOL WINAPI XMemIsToolsMemAvailable() { static std::atomic warned{false}; if (!warned.exchange(true, std::memory_order_relaxed)) { - std::fprintf(stderr, "[rt] xmem: XMemIsToolsMemAvailable -> FALSE (no devkit tools memory; logged once)\n"); + RT_LOG_WARN("xmem: XMemIsToolsMemAvailable -> FALSE (no devkit tools memory; logged once)\n"); } return FALSE; } @@ -118,9 +119,8 @@ SIZE_T __stdcall XMemVirtualQuery(HANDLE process, const void* address, void* out static std::atomic warned{false}; if (!warned.exchange(true, std::memory_order_relaxed)) { - std::fprintf(stderr, - "[rt] xmem: XMemVirtualQuery: fields after MEMORY_BASIC_INFORMATION are unknown; " - "the 64-byte output is zero-filled there\n"); + RT_LOG_WARN("xmem: XMemVirtualQuery: fields after MEMORY_BASIC_INFORMATION are unknown; " + "the 64-byte output is zero-filled there\n"); } // A null handle means the current process; GetCurrentProcess() is the (HANDLE)-1 pseudo handle. @@ -146,7 +146,7 @@ BOOL __stdcall XMemGetWorkingSetStatistics(uint32_t /*kind*/, void* stats) { if (!stats) { static std::atomic warned{false}; if (!warned.exchange(true, std::memory_order_relaxed)) { - std::fprintf(stderr, "[rt] xmem: XMemGetWorkingSetStatistics(nullptr) -> FALSE\n"); + RT_LOG_WARN("xmem: XMemGetWorkingSetStatistics(nullptr) -> FALSE\n"); } return FALSE; } @@ -756,10 +756,9 @@ UINT WINAPI XMemResetWriteWatch(void* base_address, SIZE_T region_size) { BOOL WINAPI XMemTransferMemory(uint32_t type, SIZE_T size) { static std::atomic warned{false}; if (!warned.exchange(true, std::memory_order_relaxed)) { - std::fprintf(stderr, - "[rt] xmem: XMemTransferMemory(type %u, %zu bytes): a PC has no title/system memory partition; " - "returning TRUE without moving anything (logged once)\n", - type, static_cast(size)); + RT_LOG_WARN("xmem: XMemTransferMemory(type %u, %zu bytes): a PC has no title/system memory partition; " + "returning TRUE without moving anything (logged once)\n", + type, static_cast(size)); } if (rt::startup_trace::enabled()) { static std::mutex mutex; diff --git a/runtime/src/cpu_emulation.h b/runtime/src/cpu_emulation.h index fac13eeee..46950103e 100644 --- a/runtime/src/cpu_emulation.h +++ b/runtime/src/cpu_emulation.h @@ -137,6 +137,8 @@ inline uint64_t extract_bits(uint64_t src, unsigned len, unsigned idx) { #include #include +#include "../core/log.h" + namespace rt::cpu_emulation { struct Host { @@ -293,8 +295,8 @@ inline LONG CALLBACK handler(EXCEPTION_POINTERS* info) { return EXCEPTION_CONTINUE_SEARCH; } if (count(d.op).fetch_add(1, std::memory_order_relaxed) == 0) - std::fprintf(stderr, "[rt] cpu: this CPU has no %s; emulating it (first at %p)\n", name(d.op), - reinterpret_cast(c->Rip - d.length)); + RT_LOG_WARN("cpu: this CPU has no %s; emulating it (first at %p)\n", name(d.op), + reinterpret_cast(c->Rip - d.length)); return EXCEPTION_CONTINUE_EXECUTION; } diff --git a/runtime/src/host_cpu.cpp b/runtime/src/host_cpu.cpp index a49525a3e..e6276b259 100644 --- a/runtime/src/host_cpu.cpp +++ b/runtime/src/host_cpu.cpp @@ -1,12 +1,6 @@ #include "host_cpu.h" -#include - -#if defined(_WIN32) -#include -#else -#include -#endif +#include "../core/config.h" #if defined(_M_X64) || defined(__x86_64__) #if defined(_MSC_VER) @@ -67,14 +61,6 @@ std::string message(const std::vector& missing) { "macOS, set ROSETTA_ADVERTISE_AVX=1. LEONIDA_SKIP_CPU_CHECK=1 skips this check"; } -bool check_skipped() { -#if defined(_WIN32) - char v[4] = {}; - return GetEnvironmentVariableA("LEONIDA_SKIP_CPU_CHECK", v, sizeof v) == 1 && v[0] == '1'; -#else - const char* v = std::getenv("LEONIDA_SKIP_CPU_CHECK"); - return v && std::strcmp(v, "1") == 0; -#endif -} +bool check_skipped() { return rt::config::get("loader.skip_cpu_check").text == "1"; } } // namespace rt::host_cpu diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp index 098a8ee40..01d82f364 100644 --- a/runtime/src/main.cpp +++ b/runtime/src/main.cpp @@ -24,6 +24,7 @@ #include #include #include +#include #include #include @@ -33,6 +34,8 @@ #include "host_cpu.h" #include "mods.h" #include "pe_loader.h" +#include "../core/config.h" +#include "../core/log.h" #include "../shims/d3d12_trace.h" #include "../shims/d3d12_xs_device.h" #include "../shims/file_system.h" @@ -52,17 +55,57 @@ const char* binding_name(rt::Binding b) { } } +// The folder of gta6rt.exe; empty when Windows does not give its path. +std::filesystem::path program_dir() { + std::wstring self(32768, L'\0'); + const DWORD n = GetModuleFileNameW(nullptr, self.data(), static_cast(self.size())); + if (!n || n >= self.size()) return {}; + return std::filesystem::path(self.substr(0, n)).parent_path(); +} + int usage() { std::fprintf(stderr, - "usage: gta6rt --dry-run [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace FILE]\n" + "usage: gta6rt config\n" + " gta6rt --dry-run [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace FILE]\n" " gta6rt --init [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace-d3d12] [--trace FILE]\n" " gta6rt --run [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace-d3d12] [--trace FILE] [-- game arguments...]\n"); return 2; } +// Prints UTF-8 text to stdout: as wide text on a console, which shows a path the code page lacks, and as the bytes +// themselves into a pipe or a file. +void print_utf8(const std::string& text) { + const HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); + DWORD mode; + if (GetConsoleMode(out, &mode)) { + const int size = MultiByteToWideChar(CP_UTF8, 0, text.data(), static_cast(text.size()), nullptr, 0); + std::wstring wide(static_cast(size > 0 ? size : 0), L'\0'); + if (size > 0) MultiByteToWideChar(CP_UTF8, 0, text.data(), static_cast(text.size()), wide.data(), size); + std::fflush(stdout); + DWORD written; + if (WriteConsoleW(out, wide.data(), static_cast(wide.size()), &written, nullptr)) return; + } + std::fwrite(text.data(), 1, text.size(), stdout); +} + } // namespace int wmain(int argc, wchar_t** argv) { + // The settings file, before anything reads a setting (core/config.h). A file that cannot be read, or that names + // a setting that does not exist, ends the run: a misspelt setting must not pass as one that does nothing. + if (std::string error; !rt::config::load(program_dir(), &error)) { + std::fprintf(stderr, "error: %s\n", error.c_str()); + return 2; + } + // The log level (core/log.h), before the first "[rt]" line. A gta6rt that was started again to reserve the image + // range (base_reservation.h) reads the same setting; the first one already printed the warning for a value that + // is not a level. + rt::log::apply_settings(!rt::base_reservation::inherited().has_value()); + // `gta6rt config`, alone on the command line: every setting, its value and where the value comes from. + if (argc == 2 && std::wstring_view(argv[1]) == L"config") { + print_utf8(rt::config::report()); + return 0; + } std::filesystem::path image, game_dir, overlay_dir, mods_dir; uint32_t archetype_lookup_rva = 0; // --archetype-lookup RVA[,ARG]: the game's archetype lookup by hash int archetype_lookup_arg = 0; @@ -121,15 +164,11 @@ int wmain(int argc, wchar_t** argv) { }; game_dir = game_dir.empty() ? absolute_or_same(image).parent_path() : absolute_or_same(game_dir); if (!overlay_dir.empty()) overlay_dir = absolute_or_same(overlay_dir); - // LEONIDA_SHADERS too: the D3D12 device reads it at the title's first pipeline state, after it may have moved. - if (const DWORD size = GetEnvironmentVariableW(L"LEONIDA_SHADERS", nullptr, 0)) { - std::wstring shaders(size, L'\0'); - const DWORD n = GetEnvironmentVariableW(L"LEONIDA_SHADERS", shaders.data(), size); - if (n && n < size) { - shaders.resize(n); - SetEnvironmentVariableW(L"LEONIDA_SHADERS", absolute_or_same(shaders).c_str()); - } - } + // paths.shaders (LEONIDA_SHADERS, else leonida.toml) too: the D3D12 device reads it at the title's first + // pipeline state, after it may have moved. The absolute path goes into the variable, which wins over the file, + // so a relative path in either is taken from the folder gta6rt was started in. + if (const std::filesystem::path shaders = rt::config::path("paths.shaders"); !shaders.empty()) + SetEnvironmentVariableW(L"LEONIDA_SHADERS", absolute_or_same(shaders).c_str()); // An image without relocations whose range this process already uses (arm64 Wine on macOS) runs in a new // process that has the range reserved from the start (base_reservation.h); that process does not do this again. if (!rt::base_reservation::inherited()) @@ -146,28 +185,36 @@ int wmain(int argc, wchar_t** argv) { } { const leonida::mods::LoadResult mods = leonida::mods::load_mods(mods_dir); - for (const std::string& e : mods.errors) std::fprintf(stderr, "[rt] mods: skipped %s\n", e.c_str()); + for (const std::string& e : mods.errors) RT_LOG_WARN("mods: skipped %s\n", e.c_str()); for (const auto& m : mods.mods) { - std::fprintf(stderr, "[rt] mods: %s%s\n", m.name.c_str(), m.enabled ? "" : " (disabled)"); + RT_LOG_INFO("mods: %s%s\n", m.name.c_str(), m.enabled ? "" : " (disabled)"); for (const auto& sw : m.archetype_swaps) - std::fprintf(stderr, "[rt] mods: archetype %s (0x%08X) -> %s (0x%08X)\n", sw.from_name.c_str(), - sw.from, sw.to_name.c_str(), sw.to); + RT_LOG_INFO("mods: archetype %s (0x%08X) -> %s (0x%08X)\n", sw.from_name.c_str(), + sw.from, sw.to_name.c_str(), sw.to); } leonida::mods::set_active(leonida::mods::ArchetypeSwaps(mods.mods)); const leonida::mods::CameraView camera = leonida::mods::camera_of(mods.mods); leonida::mods::set_active_camera(camera); if (camera.first_person) - std::fprintf(stderr, "[rt] mods: first-person view (value %u) for %s%s\n", camera.first_person_value, - camera.contexts.empty() ? "every context" : "the listed contexts", - view_mode_getter_rva ? "" : "; not applied: no --view-mode-getter RVA for this executable"); - if (leonida::mods::active().size()) - std::fprintf(stderr, archetype_lookup_rva ? "[rt] mods: %zu archetype swap(s) loaded\n" - : "[rt] mods: %zu archetype swap(s) loaded; not applied: no --archetype-lookup RVA for " - "this executable (docs/modding.md)\n", leonida::mods::active().size()); + RT_LOG_INFO("mods: first-person view (value %u) for %s%s\n", camera.first_person_value, + camera.contexts.empty() ? "every context" : "the listed contexts", + view_mode_getter_rva ? "" : "; not applied: no --view-mode-getter RVA for this executable"); + if (leonida::mods::active().size()) { + if (archetype_lookup_rva) + RT_LOG_INFO("mods: %zu archetype swap(s) loaded\n", leonida::mods::active().size()); + else + RT_LOG_WARN("mods: %zu archetype swap(s) loaded; not applied: no --archetype-lookup RVA for " + "this executable (docs/modding.md)\n", leonida::mods::active().size()); + } } rt::d3d12_trace::set_enabled(trace_d3d12); // Slot 133 imports the title's pages; xmem commits them on first touch, so they are committed first. rt::d3d12_xs::set_placed_at_va_pages_hook(&rt::xmem::commit_physical_range); + // loader.skip_int3 (LEONIDA_SKIP_INT3), set before the trace's exception handler exists. The variable turns it on + // with any value, also 0, as before the setting moved to the table; in leonida.toml only true (or a value other + // than 0) does, so that skip_int3 = false there means off. + if (const rt::config::Value skip = rt::config::get("loader.skip_int3"); skip.is_set()) + rt::startup_trace::set_skip_int3(skip.source == rt::config::Source::Environment || skip.text != "0"); if (int trace_error = 0; !trace_file.empty() && !rt::startup_trace::open(trace_file.c_str(), &trace_error)) { std::fprintf(stderr, trace_error == EEXIST ? "error: the trace file already exists; --trace only creates a new file\n" : "error: cannot create the trace file\n"); @@ -176,12 +223,12 @@ int wmain(int argc, wchar_t** argv) { // The console's Zen 2 instructions this CPU may lack (docs/cpu_features.md): emulated on #UD. Installed after the // trace's handler so it runs first, and an emulated instruction is not recorded as an exception. if (const auto host = rt::cpu_emulation::detect_host(); !host.sse4a || !host.clzero || !host.monitorx || !host.clwb) - std::fprintf(stderr, "[rt] cpu: this CPU lacks%s%s%s%s; the game's uses are emulated (docs/cpu_features.md)\n", - host.sse4a ? "" : " SSE4a", host.clzero ? "" : " CLZERO", host.monitorx ? "" : " MONITORX", - host.clwb ? "" : " CLWB"); + RT_LOG_WARN("cpu: this CPU lacks%s%s%s%s; the game's uses are emulated (docs/cpu_features.md)\n", + host.sse4a ? "" : " SSE4a", host.clzero ? "" : " CLZERO", host.monitorx ? "" : " MONITORX", + host.clwb ? "" : " CLWB"); if (!rt::cpu_emulation::install()) - std::fprintf(stderr, "[rt] cpu: AddVectoredExceptionHandler failed (error %lu); instructions this CPU lacks " - "will stop the game\n", GetLastError()); + RT_LOG_ERROR("cpu: AddVectoredExceptionHandler failed (error %lu); instructions this CPU lacks " + "will stop the game\n", GetLastError()); try { rt::Loader loader(game_dir); @@ -192,10 +239,10 @@ int wmain(int argc, wchar_t** argv) { const auto r = leonida::hooks::hook_image_results(main_module.base, view_mode_getter_rva, &leonida::mods::override_view_mode); if (r.ok) - std::fprintf(stderr, "[rt] mods: view-mode getter at RVA 0x%X hooked: %zu direct call(s) redirected\n", - view_mode_getter_rva, r.redirected); + RT_LOG_INFO("mods: view-mode getter at RVA 0x%X hooked: %zu direct call(s) redirected\n", + view_mode_getter_rva, r.redirected); else - std::fprintf(stderr, "[rt] mods: view-mode getter at RVA 0x%X not hooked: %s\n", view_mode_getter_rva, + RT_LOG_ERROR("mods: view-mode getter at RVA 0x%X not hooked: %s\n", view_mode_getter_rva, r.error); } if (archetype_lookup_rva) { @@ -203,10 +250,10 @@ int wmain(int argc, wchar_t** argv) { main_module.base, archetype_lookup_rva, [](uint32_t hash) { return leonida::mods::active().remap(hash); }, archetype_lookup_arg); if (r.ok) - std::fprintf(stderr, "[rt] mods: archetype lookup at RVA 0x%X hooked (argument %d): %zu direct " - "call(s) redirected\n", archetype_lookup_rva, archetype_lookup_arg, r.redirected); + RT_LOG_INFO("mods: archetype lookup at RVA 0x%X hooked (argument %d): %zu direct " + "call(s) redirected\n", archetype_lookup_rva, archetype_lookup_arg, r.redirected); else - std::fprintf(stderr, "[rt] mods: archetype lookup at RVA 0x%X not hooked: %s\n", archetype_lookup_rva, + RT_LOG_ERROR("mods: archetype lookup at RVA 0x%X not hooked: %s\n", archetype_lookup_rva, r.error); } if (run) rt::process::set_command_line(image.filename().wstring(), game_args); diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index ff0693a15..48907c20c 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp @@ -16,6 +16,8 @@ #include #include +#include "../core/config.h" +#include "../core/log.h" #include "../shims/shims.h" #include "../shims/startup_trace.h" #include "base_reservation.h" @@ -523,11 +525,7 @@ size_t patch_ga_tls_reads(Module& m, uint32_t slot) { return sites; } -bool ga_tls_patch_enabled() { - char v[8] = {}; - size_t n = 0; - return !(getenv_s(&n, v, "LEONIDA_TLS_GA_PATCH") == 0 && n == 2 && v[0] == '0'); -} +bool ga_tls_patch_enabled() { return rt::config::get("loader.tls_ga_patch").text != "0"; } void uninstall_thread_block(Module& m) { if (m.tls_slot >= kMaxMappedTlsModules) return; @@ -777,8 +775,8 @@ void install_on_existing_threads(Module& m) { VirtualFree(block, 0, MEM_RELEASE); static std::atomic logged{false}; if (!logged.exchange(true)) - std::fprintf(stderr, "[rt] loader: %s: a running thread did not take its TLS block (it ended, or " - "its TLS array kept changing); mapped thread-local data is not valid on it\n", + RT_LOG_ERROR("loader: %s: a running thread did not take its TLS block (it ended, or " + "its TLS array kept changing); mapped thread-local data is not valid on it\n", m.name.c_str()); continue; } @@ -795,8 +793,8 @@ void install_on_existing_threads(Module& m) { ga_view = nullptr; static std::atomic logged_view{false}; if (!logged_view.exchange(true)) - std::fprintf(stderr, "[rt] loader: %s: a running thread did not take its /GA TLS view; " - "index-0 TLS reads in it have no block\n", + RT_LOG_ERROR("loader: %s: a running thread did not take its /GA TLS view; " + "index-0 TLS reads in it have no block\n", m.name.c_str()); } } @@ -862,7 +860,7 @@ void release_existing_blocks_of_this_thread() { try { run_callbacks(*m, DLL_THREAD_DETACH); } catch (const std::exception& e) { - std::fprintf(stderr, "[rt] loader: thread detach: %s\n", e.what()); + RT_LOG_ERROR("loader: thread detach: %s\n", e.what()); } } ExistingThreadsLock lock; @@ -891,7 +889,7 @@ void __cdecl on_host_thread_event(DWORD reason) { try { forget_ended_thread_id(); } catch (const std::exception& e) { - std::fprintf(stderr, "[rt] loader: thread attach: %s\n", e.what()); + RT_LOG_ERROR("loader: thread attach: %s\n", e.what()); } for (size_t slot = 0; slot < kMaxMappedTlsModules; ++slot) { Module* m = g_tls_slot_owners[slot].load(); @@ -901,7 +899,7 @@ void __cdecl on_host_thread_event(DWORD reason) { if (m->initialised) run_callbacks(*m, DLL_THREAD_ATTACH); } catch (const std::exception& e) { // The thread runs on without this module's TLS; later slots still get theirs. - std::fprintf(stderr, "[rt] loader: thread attach, slot %zu (%s): %s\n", slot, m->name.c_str(), + RT_LOG_ERROR("loader: thread attach, slot %zu (%s): %s\n", slot, m->name.c_str(), e.what()); } } @@ -911,7 +909,7 @@ void __cdecl on_host_thread_event(DWORD reason) { try { release_existing_blocks_of_this_thread(); } catch (const std::exception& e) { - std::fprintf(stderr, "[rt] loader: thread detach: %s\n", e.what()); + RT_LOG_ERROR("loader: thread detach: %s\n", e.what()); } for (size_t i = kMaxMappedTlsModules; i-- > 0;) { Module* m = g_tls_slot_owners[i].load(); @@ -920,7 +918,7 @@ void __cdecl on_host_thread_event(DWORD reason) { try { if (m->initialised) run_callbacks(*m, DLL_THREAD_DETACH); } catch (const std::exception& e) { - std::fprintf(stderr, "[rt] loader: thread detach, slot %zu (%s): %s\n", i, m->name.c_str(), + RT_LOG_ERROR("loader: thread detach, slot %zu (%s): %s\n", i, m->name.c_str(), e.what()); } // Released even when the callbacks threw: a leaked block would be handed to the OS loader as the @@ -1066,9 +1064,7 @@ struct RuntimeLoadScope { } // namespace Loader::Loader(std::filesystem::path game_dir) : game_dir_(std::move(game_dir)) { - std::vector compat(32768); - const DWORD n = GetEnvironmentVariableW(L"LEONIDA_COMPAT_DIR", compat.data(), static_cast(compat.size())); - if (n > 0 && n < compat.size()) compat_dir_ = std::filesystem::path(compat.data()); + compat_dir_ = rt::config::path("paths.compat_dir"); shims::add_module_lookup(this, &lookup_in_loader); shims::add_bundled_loader(this, &kBundledOps); } @@ -1086,7 +1082,7 @@ Loader::~Loader() { } catch (const std::exception& e) { // A module may have changed its callback table since attach. A destructor cannot propagate the validation // error; report it and still let DllMain release resources before the image is freed. - std::fprintf(stderr, "[rt] TLS process detach failed for %s: %s\n", m.name.c_str(), e.what()); + RT_LOG_ERROR("TLS process detach failed for %s: %s\n", m.name.c_str(), e.what()); } auto* nt = at(m.base, reinterpret_cast(m.base)->e_lfanew); if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && m.entry_rva) { @@ -1222,8 +1218,7 @@ void* Loader::load_runtime_candidate(Module* existing, const std::filesystem::pa // Win32 DONT_RESOLVE_DLL_REFERENCES (0x1) forbids resolving dependencies or running TLS/DllMain; refuse it // explicitly instead of silently performing a normal resolving + initialising load. if ((flags & DONT_RESOLVE_DLL_REFERENCES) != 0) { - std::fprintf(stderr, - "[rt] loader: LoadLibraryEx(%s, DONT_RESOLVE_DLL_REFERENCES) is not supported for bundled DLLs\n", + RT_LOG_ERROR("loader: LoadLibraryEx(%s, DONT_RESOLVE_DLL_REFERENCES) is not supported for bundled DLLs\n", display.c_str()); SetLastError(ERROR_NOT_SUPPORTED); return nullptr; @@ -1234,7 +1229,7 @@ void* Loader::load_runtime_candidate(Module* existing, const std::filesystem::pa initialise(); return static_cast(existing->base); } catch (const std::exception& e) { - std::fprintf(stderr, "[rt] loader: run-time initialise of %s failed: %s\n", display.c_str(), e.what()); + RT_LOG_ERROR("loader: run-time initialise of %s failed: %s\n", display.c_str(), e.what()); SetLastError(ERROR_DLL_INIT_FAILED); return nullptr; } @@ -1245,13 +1240,13 @@ void* Loader::load_runtime_candidate(Module* existing, const std::filesystem::pa Module& m = load(candidate); mapped = &m; initialise(); - std::fprintf(stderr, "[rt] loader: %s mapped from game_dir (run-time load)\n", m.name.c_str()); + RT_LOG_INFO("loader: %s mapped from game_dir (run-time load)\n", m.name.c_str()); return static_cast(m.base); } catch (const std::exception& e) { // load() drops a module that failed to map or bind (dependencies included); this also drops one whose // initialise() failed, so later GetModuleHandle/LoadLibrary calls don't see it. ~Loader frees it via order_. by_name_.erase(module_key(mapped ? mapped->path : candidate)); - std::fprintf(stderr, "[rt] loader: run-time load of %s failed: %s\n", display.c_str(), e.what()); + RT_LOG_ERROR("loader: run-time load of %s failed: %s\n", display.c_str(), e.what()); SetLastError(ERROR_DLL_INIT_FAILED); return nullptr; } @@ -1279,7 +1274,7 @@ void* Loader::resolve_module_export(void* module_handle, const std::string& sym, if (binding == Binding::Module) initialise(); return fn; } catch (const std::exception& e) { - std::fprintf(stderr, "[rt] loader: forwarder %s from %s failed: %s\n", it->second.c_str(), + RT_LOG_ERROR("loader: forwarder %s from %s failed: %s\n", it->second.c_str(), target->name.c_str(), e.what()); return nullptr; } @@ -1578,15 +1573,14 @@ void Loader::initialize_tls(Module& m) { if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && total && index != 0 && ga_tls_patch_enabled()) { static const DWORD ga_slot = TlsAlloc(); if (ga_slot == TLS_OUT_OF_INDEXES || ga_slot >= 64) { - std::fprintf(stderr, "[rt] loader: %s: no TlsAlloc slot below 64 for its index-0 TLS reads\n", + RT_LOG_ERROR("loader: %s: no TlsAlloc slot below 64 for its index-0 TLS reads\n", m.name.c_str()); } else { m.tls_ga_sites = patch_ga_tls_reads(m, ga_slot); if (m.tls_ga_sites) m.tls_ga_slot = ga_slot; - std::fprintf(stderr, - "[rt] loader: %s: %zu index-0 TLS reads (gs:[58h]) now read its own TLS (TlsSlots[%lu]); " - "its module TLS index is %u\n", - m.name.c_str(), m.tls_ga_sites, static_cast(ga_slot), index); + RT_LOG_INFO("loader: %s: %zu index-0 TLS reads (gs:[58h]) now read its own TLS (TlsSlots[%lu]); " + "its module TLS index is %u\n", + m.name.c_str(), m.tls_ga_sites, static_cast(ga_slot), index); } } } @@ -1733,7 +1727,7 @@ bool Loader::resolve_compat(const std::string& key, const std::string& dll, cons throw std::runtime_error("LEONIDA_COMPAT_DIR: " + path_utf8(candidate) + " exists but Windows could not " + "load it (error " + std::to_string(load_error) + ")"); compat_modules_.emplace(key, h); - std::fprintf(stderr, "[rt] compat: %s -> %s\n", dll.c_str(), path_utf8(candidate).c_str()); + RT_LOG_INFO("compat: %s -> %s\n", dll.c_str(), path_utf8(candidate).c_str()); } out = reinterpret_cast(GetProcAddress(h, by_ordinal ? MAKEINTRESOURCEA(ordinal) : name.c_str())); return true; diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index e3e4defe8..023858951 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -23,6 +23,7 @@ #include "queue_families.h" #include "resource_tiling.h" #include "xdxr_build.h" +#include "../core/log.h" #include #include @@ -2793,15 +2794,15 @@ class VulkanQueue : private QueueHolds::Holder { if (result != ReplayResult::success) { int none = static_cast(ReplayResult::success); held_failure_.compare_exchange_strong(none, static_cast(result)); - std::fprintf(stderr, "[rt] d3d12: a held ExecuteCommandLists failed when it was released (result %d); " - "nothing was submitted for it, and a Signal behind it still signals\n", + RT_LOG_ERROR("d3d12: a held ExecuteCommandLists failed when it was released (result %d); " + "nothing was submitted for it, and a Signal behind it still signals\n", static_cast(result)); } break; } case Deferred::Kind::signal: if (!submit(VK_NULL_HANDLE, op.fence, op.value)) - std::fprintf(stderr, "[rt] d3d12: a held Signal failed when it was released\n"); + RT_LOG_ERROR("d3d12: a held Signal failed when it was released\n"); break; case Deferred::Kind::marker: marker_now(op.marker_kind, op.label.c_str()); @@ -2844,8 +2845,8 @@ class VulkanQueue : private QueueHolds::Holder { ++it; continue; } - std::fprintf(stderr, "[rt] d3d12: a fence was released while a queue still held work that names it; " - "that work is dropped\n"); + RT_LOG_WARN("d3d12: a fence was released while a queue still held work that names it; " + "that work is dropped\n"); dropped.push_back(std::move(*it)); it = held_.erase(it); context_.holds().held_changed(-1); @@ -2874,10 +2875,10 @@ class VulkanQueue : private QueueHolds::Holder { if (context_.holds().pending(op.waits[i], op.wait_values[i])) value = op.wait_values[i]; std::size_t signals = 0; for (const Deferred& op : held_) signals += op.kind == Deferred::Kind::signal; - std::fprintf(stderr, "[rt] d3d12: queue destroyed with %zu held operation(s) never submitted: waits for a " - "fence value (%llu) that no Signal reached; the fence was never signaled%s\n", - held_.size(), static_cast(value), - signals ? "; CPU waits on the fences of its held Signals are completed" : ""); + RT_LOG_WARN("d3d12: queue destroyed with %zu held operation(s) never submitted: waits for a " + "fence value (%llu) that no Signal reached; the fence was never signaled%s\n", + held_.size(), static_cast(value), + signals ? "; CPU waits on the fences of its held Signals are completed" : ""); for (const Deferred& op : held_) if (op.kind == Deferred::Kind::signal) context_.cancel_fence_waits(op.fence); context_.holds().held_changed(-static_cast(held_.size())); diff --git a/runtime/src/vulkan_device_filter.h b/runtime/src/vulkan_device_filter.h index 87b02424b..25d093140 100644 --- a/runtime/src/vulkan_device_filter.h +++ b/runtime/src/vulkan_device_filter.h @@ -13,7 +13,15 @@ namespace leonida { -// The filter, lower-cased; empty when unset. +// `text` as a filter: lower-cased, which is how it is compared with a device name. +inline std::string vulkan_device_filter_of(std::string text) { + for (char& c : text) c = char(std::tolower(static_cast(c))); + return text; +} + +// The filter from the variable alone, lower-cased; empty when unset. This is what the test harnesses and tools use, +// which load no settings file. The runtime's device takes the setting vulkan.device (the variable, else leonida.toml) +// and passes it to the two-argument vulkan_device_wanted below (shims/d3d12_vulkan_device.cpp). inline std::string vulkan_device_filter() { #ifdef _MSC_VER #pragma warning(push) @@ -23,20 +31,23 @@ inline std::string vulkan_device_filter() { #ifdef _MSC_VER #pragma warning(pop) #endif - std::string out = value ? value : ""; - for (char& c : out) c = char(std::tolower(static_cast(c))); - return out; + return vulkan_device_filter_of(value ? value : ""); } -// True when `device_name` (VkPhysicalDeviceProperties::deviceName) is wanted. -inline bool vulkan_device_wanted(const char* device_name) { - const std::string filter = vulkan_device_filter(); +// True when `device_name` (VkPhysicalDeviceProperties::deviceName) is wanted by `filter`, which is lower-cased +// (vulkan_device_filter_of); an empty filter takes every device. +inline bool vulkan_device_wanted(const char* device_name, const std::string& filter) { if (filter.empty()) return true; std::string name = device_name ? device_name : ""; for (char& c : name) c = char(std::tolower(static_cast(c))); return name.find(filter) != std::string::npos; } +// The same with the filter of the variable. +inline bool vulkan_device_wanted(const char* device_name) { + return vulkan_device_wanted(device_name, vulkan_device_filter()); +} + // Microsoft is the vendor of the D3D12 translation layers Windows adds next to the real GPU (Mesa's Dozen from the // "OpenCL, OpenGL and Vulkan Compatibility Pack", and the Basic Render Driver); no native GPU driver uses it. Dozen // reports a discrete GPU, so "the last discrete device wins" took the wrapper over the native driver (#915). diff --git a/runtime/src/vulkan_present.h b/runtime/src/vulkan_present.h index 97c365b5f..d94672971 100644 --- a/runtime/src/vulkan_present.h +++ b/runtime/src/vulkan_present.h @@ -27,6 +27,7 @@ #include "vulkan_backend.h" #include "vulkan_present_compose.h" +#include "../core/log.h" // Use the original EXT spellings. They are aliases of the promoted KHR types and are available in older headers. #if defined(VK_EXT_SWAPCHAIN_MAINTENANCE_1_EXTENSION_NAME) && defined(VK_EXT_SURFACE_MAINTENANCE_1_EXTENSION_NAME) @@ -108,15 +109,30 @@ inline bool blit_unsupported_format(VkFormat format) { return format >= VK_FORMAT_BC1_RGB_UNORM_BLOCK && format <= VK_FORMAT_BC7_SRGB_BLOCK; } } +// A path as UTF-8 text, for a message. +inline std::string path_text(const std::filesystem::path& path) { + const auto text = path.u8string(); + return std::string(reinterpret_cast(text.data()), text.size()); +} } // namespace detail +// Writing presented frames to disk. The runtime fills this from the settings present.capture_dir, +// present.capture_every and present.capture_limit (LEONIDA_CAPTURE, LEONIDA_CAPTURE_EVERY, LEONIDA_CAPTURE_LIMIT); +// this header reads no setting itself. +struct PresentCapture { + std::filesystem::path dir; // the folder the frames go to, made when it is missing; empty: no capture + int every = 30; // presented frames between files; below 1 counts as 1 + int limit = 24; // files at most; below 1 counts as 1 +}; + class VulkanPresenter { public: VulkanPresenter(VulkanContext& context, PFN_vkGetInstanceProcAddr get_instance, VkInstance instance, VkPhysicalDevice physical, VkQueue queue, std::uint32_t family, VkSurfaceKHR surface, bool swapchain_maintenance1 = false, std::function extent_fn = nullptr, - std::function recreate_surface_fn = nullptr) + std::function recreate_surface_fn = nullptr, + PresentCapture capture = {}) : context_(context), instance_(instance), physical_(physical), queue_(queue), surface_(surface), maintenance1_(swapchain_maintenance1), extent_fn_(std::move(extent_fn)), recreate_surface_fn_(std::move(recreate_surface_fn)) { @@ -170,27 +186,27 @@ class VulkanPresenter { vk.vkCreateSemaphore(device, &semaphore, nullptr, &frame.acquired) != VK_SUCCESS) return; } - // LEONIDA_CAPTURE=: besides presenting, copy the swapchain image to host memory and write it out as a - // binary PPM, every LEONIDA_CAPTURE_EVERY presented frames (default 30), at most LEONIDA_CAPTURE_LIMIT of - // them (default 24). Off unless the variable is set; a capture that cannot be made shows nothing and is + // Capture (PresentCapture; LEONIDA_CAPTURE= in the runtime): besides presenting, copy the swapchain image + // to host memory and write it out as a binary PPM, every capture.every presented frames, at most + // capture.limit of them. Off unless a folder is named; a capture that cannot be made shows nothing and is // reported here instead of failing the presenter. - if (const char* dir = std::getenv("LEONIDA_CAPTURE"); dir && *dir) { - capture_dir_ = dir; + if (!capture.dir.empty()) { + capture_dir_ = std::move(capture.dir); // Create the folder: a capture run names its own output folder and should not have to make it first. std::error_code created; std::filesystem::create_directories(capture_dir_, created); capture_to_disk_ = true; capture_ = true; // the swapchain needs TRANSFER_SRC, and every frame copies into a staging buffer - if (const char* every = std::getenv("LEONIDA_CAPTURE_EVERY")) capture_every_ = std::max(1, std::atoi(every)); - if (const char* limit = std::getenv("LEONIDA_CAPTURE_LIMIT")) capture_limit_ = std::max(1, std::atoi(limit)); - std::fprintf(stderr, "[rt] present: capture on: every %d presented frame(s), at most %d, into %s\n", - capture_every_, capture_limit_, capture_dir_.c_str()); + capture_every_ = std::max(1, capture.every); + capture_limit_ = std::max(1, capture.limit); + RT_LOG_INFO("present: capture on: every %d presented frame(s), at most %d, into %s\n", + capture_every_, capture_limit_, detail::path_text(capture_dir_).c_str()); } ok_ = recreate(true, false); if (!ok_ && capture_to_disk_) { // The surface refused a TRANSFER_SRC swapchain, or the staging buffer could not be made: present // without the capture rather than not at all. - std::fprintf(stderr, "[rt] present: capture is unavailable on this surface; presenting without it\n"); + RT_LOG_WARN("present: capture is unavailable on this surface; presenting without it\n"); capture_to_disk_ = false; capture_ = false; capture_dir_.clear(); @@ -418,8 +434,8 @@ class VulkanPresenter { } if (!logged) { logged = true; - std::fprintf(stderr, "[rt] d3d12: %zu Presents are queued behind held work; this one waits for it\n", - max_deferred_presents); + RT_LOG_WARN("d3d12: %zu Presents are queued behind held work; this one waits for it\n", + max_deferred_presents); } if (should_abort()) return; std::this_thread::sleep_for(std::chrono::milliseconds(1)); @@ -448,7 +464,7 @@ class VulkanPresenter { p.has_rect ? &p.rect : nullptr, p.srgb, p.tear, p.has_planes ? &p.planes : nullptr); if (result != VK_SUCCESS) - std::fprintf(stderr, "[rt] d3d12: a Present held behind queued work failed when it was released (%d)\n", + RT_LOG_ERROR("d3d12: a Present held behind queued work failed when it was released (%d)\n", int(result)); } @@ -1112,12 +1128,10 @@ class VulkanPresenter { } char name[64]; std::snprintf(name, sizeof name, "frame_%05llu.ppm", static_cast(number)); - std::string path = capture_dir_; - if (path.back() != '/' && path.back() != '\\') path += '/'; - path += name; + const std::filesystem::path path = capture_dir_ / name; std::ofstream file(path, std::ios::binary | std::ios::trunc); if (!file) { - std::fprintf(stderr, "[rt] present: cannot write %s\n", path.c_str()); + RT_LOG_ERROR("present: cannot write %s\n", detail::path_text(path).c_str()); return; } file << "P6\n" << extent.width << ' ' << extent.height << "\n255\n"; @@ -1125,15 +1139,13 @@ class VulkanPresenter { file.close(); const double scale = 1.0 / double(texels); const double mean[3] = {sum[0] * scale, sum[1] * scale, sum[2] * scale}; - path.resize(path.size() - std::strlen(name)); - path += "index.txt"; - std::ofstream index(path, std::ios::app); + std::ofstream index(capture_dir_ / "index.txt", std::ios::app); if (index) index << "frame " << number << " format " << int(format) << " (" << capture_format_name(format) << ") extent " << extent.width << 'x' << extent.height << " mean rgb " << std::fixed << std::setprecision(2) << mean[0] << ' ' << mean[1] << ' ' << mean[2] << '\n'; ++capture_written_; - std::fprintf(stderr, "[rt] present: capture %s (%ux%u, mean rgb %.2f %.2f %.2f)\n", name, extent.width, + RT_LOG_DEBUG("present: capture %s (%ux%u, mean rgb %.2f %.2f %.2f)\n", name, extent.width, extent.height, mean[0], mean[1], mean[2]); } @@ -1216,8 +1228,8 @@ class VulkanPresenter { } if (!found && !warned_hdr_) { warned_hdr_ = true; - std::fprintf(stderr, "[rt] present: the surface has no HDR10 (ST.2084) format; HDR10 planes are converted to " - "SDR by tone mapping\n"); + RT_LOG_WARN("present: the surface has no HDR10 (ST.2084) format; HDR10 planes are converted to " + "SDR by tone mapping\n"); } } for (const VkFormat wanted : srgb ? std::array{VK_FORMAT_B8G8R8A8_SRGB, VK_FORMAT_R8G8B8A8_SRGB} @@ -1232,7 +1244,8 @@ class VulkanPresenter { if (found) break; } if (!found && srgb) { - if (!warned_srgb_) std::fprintf(stderr, "[rt] present: the surface has no sRGB 8-bit format; an sRGB back buffer is shown darker\n"); + if (!warned_srgb_) + RT_LOG_WARN("present: the surface has no sRGB 8-bit format; an sRGB back buffer is shown darker\n"); warned_srgb_ = true; for (const auto& f : formats) if ((f.format == VK_FORMAT_B8G8R8A8_UNORM || f.format == VK_FORMAT_R8G8B8A8_UNORM) && @@ -1450,7 +1463,7 @@ class VulkanPresenter { VkFormat captured_format_ = VK_FORMAT_UNDEFINED; // LEONIDA_CAPTURE: write the copies the staging buffer makes to (see finish_pending_capture()). bool capture_to_disk_ = false; - std::string capture_dir_; + std::filesystem::path capture_dir_; int capture_every_ = 30; // presented frames between files int capture_limit_ = 24; // files at most VkFence pending_capture_ = VK_NULL_HANDLE; // owns the shared staging bytes until written diff --git a/runtime/test/check_sparse_queue_family.py b/runtime/test/check_sparse_queue_family.py index 27ebc1f5d..b5e0558bf 100644 --- a/runtime/test/check_sparse_queue_family.py +++ b/runtime/test/check_sparse_queue_family.py @@ -29,7 +29,8 @@ MODE = re.compile(r"sharingMode:\s+VkSharingMode = (VK_SHARING_MODE_\w+)") COUNT = re.compile(r"queueFamilyIndexCount:\s+uint32_t = (\d+)") INDICES = re.compile(r"pQueueFamilyIndices\[(\d+)\]:\s+const uint32_t = (\d+)") -# Each of the two runs gets 30 s, so both together stay inside the CTest TIMEOUT of 65 s (runtime/CMakeLists.txt). +# Each of the two runs gets 30 s, so both together stay inside the CTest TIMEOUT of 65 s +# (runtime/cmake/d3d12_vulkan.cmake). RUN_TIMEOUT = 30 ACCESS_VIOLATION = 0xC0000005 # STATUS_ACCESS_VIOLATION, as Windows reports it in the exit code CASES = ["LAYER_MAP_COMPUTE_COPY_COMPUTE", "LAYER_MAP_COPY_COPY_COMPUTE", "LAYER_MAP_DIRECT_COPY_COMPUTE"] # sorted diff --git a/runtime/test/check_stack_reserve.cmake b/runtime/test/check_stack_reserve.cmake index 6cdca0fa1..6954b2afb 100644 --- a/runtime/test/check_stack_reserve.cmake +++ b/runtime/test/check_stack_reserve.cmake @@ -54,6 +54,6 @@ read_le("${TOOL}" ${reserve_offset} ${width} reserve) if(reserve LESS WANT) message(FATAL_ERROR "${TOOL} reserves ${reserve} bytes of stack, expected at least ${WANT}: the link option " - "from runtime/CMakeLists.txt (BUILD-1457) did not reach the linker") + "from runtime/cmake/*.cmake (BUILD-1457) did not reach the linker") endif() message(STATUS "stack reserve: ${reserve} bytes (at least ${WANT} wanted)") diff --git a/runtime/test/core_config_test.cpp b/runtime/test/core_config_test.cpp new file mode 100644 index 000000000..176eb00cb --- /dev/null +++ b/runtime/test/core_config_test.cpp @@ -0,0 +1,396 @@ +// rt::config (core/config.h): the shape of the table, the order environment > file > default, the file reader and +// what it refuses, the file load() picks, the report, and leonida.example.toml against the table. No game files. +// +// core_config_test +#include "../core/config.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(_WIN32) +#include +#endif + +namespace { + +namespace config = rt::config; + +// A key that is in the table builds and names its row. One that is not does not build (Name's constructor), which +// a test that has to build cannot show; index_of_key is what that constructor asks. +static_assert(config::Name("paths.game_dir").index() == 0); +static_assert(config::Name("input.mouse_sensitivity").index() == config::kSettingCount - 1); +static_assert(config::index_of_key("vulkan.no_such_setting") == config::kSettingCount); + +int g_failures = 0; + +void expect(bool ok, const std::string& what) { + if (ok) return; + std::fprintf(stderr, "FAIL: %s\n", what.c_str()); + ++g_failures; +} + +bool contains(std::string_view text, std::string_view part) { return text.find(part) != std::string_view::npos; } + +// Sets (value) or removes (nullptr) an environment variable of this process. +void set_env(const char* name, const char* value) { +#if defined(_WIN32) + SetEnvironmentVariableA(name, value); +#else + if (value) + setenv(name, value, 1); + else + unsetenv(name); +#endif +} + +void set_env_path(const char* name, const std::filesystem::path& value) { +#if defined(_WIN32) + std::wstring wide_name; + for (const char* c = name; *c; ++c) wide_name.push_back(static_cast(*c)); + SetEnvironmentVariableW(wide_name.c_str(), value.c_str()); +#else + setenv(name, value.c_str(), 1); +#endif +} + +void write_file(const std::filesystem::path& file, std::string_view text) { + std::ofstream out(file, std::ios::binary); + out.write(text.data(), static_cast(text.size())); +} + +// What `values` holds for `key`; "" when the file did not set it. +std::string file_value(const config::FileValues& values, std::string_view key) { + const std::size_t index = config::index_of_key(key); + if (index == config::kSettingCount) return ""; + return values[index] ? *values[index] : ""; +} + +void test_table() { + std::set keys, variables; + for (std::size_t i = 0; i < config::kSettingCount; ++i) { + const config::Setting& setting = config::kSettings[i]; + const std::string_view key = setting.key, variable = setting.variable; + const std::string name(key); + const std::size_t dot = key.find('.'); + expect(dot != std::string_view::npos && dot > 0 && dot + 1 < key.size() && + key.find('.', dot + 1) == std::string_view::npos, + name + ": a key is section.name"); + expect(!variable.empty(), name + ": has a variable"); + expect(setting.fallback != nullptr, name + ": has a default, \"\" for not set"); + expect(keys.insert(key).second, name + ": the key is in the table once"); + expect(variables.insert(variable).second, name + ": its variable belongs to no other setting"); + const auto by_key = config::Name::find(key); + const auto by_variable = config::Name::find(variable); + expect(by_key && by_key->index() == i, name + ": found by key"); + expect(by_variable && by_variable->index() == i, name + ": found by variable"); + expect(&config::Name::at(i).setting() == &setting, name + ": at() names the row"); + } + expect(!config::Name::find("vulkan.no_such_setting"), "a key that is not in the table is not found"); + expect(!config::Name::find(""), "an empty name is not found"); + expect(variables.count(config::kFileVariable) == 0, "the variable that names the file is not a setting"); + expect(std::string_view(config::source_name(config::Source::Default)) == "default" && + std::string_view(config::source_name(config::Source::File)) == "file" && + std::string_view(config::source_name(config::Source::Environment)) == "environment", + "the three sources have their names"); +} + +void test_order(const std::filesystem::path& dir) { + const auto validation = [] { return config::get("vulkan.validation"); }; + config::Value value = validation(); + expect(value.text == "0" && value.source == config::Source::Default && !value.is_set(), + "nothing set: the default"); + + const std::filesystem::path file = dir / "order.toml"; + write_file(file, "[vulkan]\nvalidation = true\n"); + std::string error; + expect(config::load_file(file, &error), "load_file reads a good file: " + error); + value = validation(); + expect(value.text == "1" && value.source == config::Source::File && value.is_set(), + "set in the file: the file's value"); + expect(config::get("vulkan.arena_mb").source == config::Source::Default, + "a setting the file leaves out keeps its default"); + + // The environment is read at each call, so a variable set after an earlier read is seen. + set_env("LEONIDA_VK_VALIDATION", "2"); + value = validation(); + expect(value.text == "2" && value.source == config::Source::Environment, "the variable wins over the file"); + set_env("LEONIDA_VK_VALIDATION", ""); + expect(validation().source == config::Source::File, "an empty variable counts as not set"); + set_env("LEONIDA_VK_VALIDATION", nullptr); + expect(validation().source == config::Source::File, "the variable removed: the file's value again"); + + config::unload(); + expect(validation().source == config::Source::Default && config::loaded_file().empty(), + "unload() forgets the file"); + + expect(config::path("paths.game_dir").empty(), "a path that is not set is empty"); + const std::filesystem::path game = dir / "game folder"; + set_env_path("LEONIDA_GAME_DIR", game); + expect(config::path("paths.game_dir") == game, "a path from the environment"); + set_env("LEONIDA_GAME_DIR", nullptr); +#if defined(_WIN32) + // UTF-8 in Value::text and the same characters back in path(): a folder named outside the ANSI code page + // reaches the reader intact. + const wchar_t wide[] = L"C:\\Spiele\\Gr\u00F6\u00DFe \u30B2\u30FC\u30E0"; + SetEnvironmentVariableW(L"LEONIDA_GAME_DIR", wide); + expect(config::get("paths.game_dir").text == + "C:\\Spiele\\Gr\xC3\xB6\xC3\x9F" "e \xE3\x82\xB2\xE3\x83\xBC\xE3\x83\xA0", + "a wide value is returned as UTF-8"); + expect(config::path("paths.game_dir").native() == wide, "a wide value comes back whole as a path"); + SetEnvironmentVariableW(L"LEONIDA_GAME_DIR", nullptr); +#endif +} + +void test_parse() { + const std::string_view good = + "\xEF\xBB\xBF# a comment, after the byte order mark Notepad writes\r\n" + "[paths]\r\n" + "game_dir = 'D:\\games\\gta6' # single quotes: as written\r\n" + "save_dir = \"D:\\\\saves \\\"one\\\"\"\r\n" + "shaders = ''\r\n" + "\r\n" + " [vulkan] # a second section\r\n" + "validation = true\r\n" + "graphics_family_only=false\r\n" + "arena_mb = 512\r\n" + "[input]\n" + "ds_trigger_gain = 1.5\n" + "[loader]\n" + "rng_seed = 0x1F\n" + "[present]\n" + "sdr_eotf = 'gamma22 # not a comment'"; // and no line break at the end + config::FileValues values; + std::string error; + expect(config::parse(good, "f.toml", &values, &error), "a file in the format is read: " + error); + const auto is = [&](std::string_view key, std::string_view want) { + const std::string got = file_value(values, key); + expect(got == want, std::string(key) + ": read \"" + got + "\", expected \"" + std::string(want) + "\""); + }; + is("paths.game_dir", "D:\\games\\gta6"); + is("paths.save_dir", "D:\\saves \"one\""); + is("paths.shaders", ""); // '' leaves a setting unset + is("vulkan.validation", "1"); + is("vulkan.graphics_family_only", "0"); + is("vulkan.arena_mb", "512"); + is("vulkan.device", ""); + is("input.ds_trigger_gain", "1.5"); + is("loader.rng_seed", "0x1F"); + is("present.sdr_eotf", "gamma22 # not a comment"); + + struct Refused { + const char* what; + const char* text; + int line; // the line the error names + const char* part; // text the error contains + }; + const Refused refused[] = { + {"an unknown section", "[nope]\n", 1, "no section [nope]"}, + {"a section with a dot", "# first\n[paths.sub]\n", 2, "no section [paths.sub]"}, + {"an unknown name", "[paths]\nnope = 1\n", 2, "no setting paths.nope"}, + {"a name of another section", "[paths]\nvalidation = true\n", 2, "no setting paths.validation"}, + {"a name set twice", "[paths]\ngame_dir = 'a'\ngame_dir = 'b'\n", 3, "paths.game_dir is set twice"}, + {"a name set twice, first to ''", "[paths]\nshaders = ''\nshaders = 'b'\n", 3, "set twice"}, + {"a section twice", "[paths]\n[vulkan]\n[paths]\n", 3, "[paths] is in the file twice"}, + {"a setting above every section", "game_dir = 'a'\n", 1, "[section]"}, + {"a single quote left open", "[paths]\ngame_dir = 'a\n", 2, "closing '"}, + {"a double quote left open", "[paths]\ngame_dir = \"a\n", 2, "closing \""}, + {"a Windows path in double quotes", "[paths]\ngame_dir = \"D:\\games\"\n", 2, "single quotes"}, + {"text without quotes", "[paths]\ngame_dir = D:\\games\n", 2, "in quotes"}, + {"True with a capital", "[vulkan]\nvalidation = True\n", 2, "in quotes"}, + {"a number that ends in a dot", "[vulkan]\narena_mb = 1.\n", 2, "in quotes"}, + {"two values", "[paths]\ngame_dir = 'a' 'b'\n", 2, "# comment"}, + {"no value", "[paths]\ngame_dir =\n", 2, "missing"}, + {"no equals sign", "[paths]\ngame_dir\n", 2, "name = value"}, + {"a section left open", "[paths\n", 1, "closing ]"}, + {"text after a section", "[paths] x\n", 1, "# comment"}, + }; + for (const Refused& r : refused) { + config::FileValues kept; + kept[0] = "kept"; + error.clear(); + const bool ok = config::parse(r.text, "f.toml", &kept, &error); + const std::string start = "f.toml:" + std::to_string(r.line) + ": "; + expect(!ok && error.rfind(start, 0) == 0 && contains(error, r.part), + std::string(r.what) + " is refused with its line; the error was \"" + error + "\""); + expect(kept[0] == "kept", std::string(r.what) + ": a refused file changes no value"); + } +} + +void test_load(const std::filesystem::path& dir) { + const auto gamertag = [] { return config::get("system.gamertag"); }; + std::string error; + expect(config::load({}, &error) && config::loaded_file().empty(), + "no program folder and no variable: nothing to read, and that is not an error"); + expect(config::load(dir, &error) && config::loaded_file().empty(), + "a program folder without leonida.toml: nothing to read"); + expect(gamertag().text == "Player" && gamertag().source == config::Source::Default, "no file: the default"); + + write_file(dir / config::kFileName, "[system]\ngamertag = 'Beside'\n"); + expect(config::load(dir, &error), "leonida.toml in the program folder is read: " + error); + expect(config::loaded_file().filename() == config::kFileName && config::loaded_file().is_absolute(), + "loaded_file() names it with its folder"); + expect(gamertag().text == "Beside" && gamertag().source == config::Source::File, + "its value is the one get() returns"); + + write_file(dir / "named.toml", "[system]\ngamertag = 'Named'\n"); + set_env_path(config::kFileVariable, dir / "named.toml"); + expect(config::load(dir, &error) && gamertag().text == "Named", + "the file the variable names is read instead of the one in the program folder: " + error); + + set_env_path(config::kFileVariable, dir / "missing.toml"); + error.clear(); + expect(!config::load(dir, &error) && contains(error, config::kFileVariable) && contains(error, "missing.toml"), + "a variable that names no file is an error that says so; the error was \"" + error + "\""); + expect(gamertag().text == "Named", "a failed load keeps the values loaded before"); + + write_file(dir / "bad.toml", "[system]\ngamer_tag = 'Typo'\n"); + set_env_path(config::kFileVariable, dir / "bad.toml"); + error.clear(); + expect(!config::load(dir, &error) && contains(error, "bad.toml:2: ") && contains(error, "system.gamer_tag"), + "a misspelt setting is an error with file and line; the error was \"" + error + "\""); + expect(gamertag().text == "Named", "a refused file keeps the values loaded before"); + + set_env(config::kFileVariable, nullptr); + config::unload(); + expect(gamertag().text == "Player", "unloaded: the default again"); +} + +// The report's line for `key`, without its line break; empty when there is none. +std::string_view report_line(std::string_view report, std::string_view key) { + while (!report.empty()) { + const std::size_t newline = report.find('\n'); + const std::string_view line = report.substr(0, newline); + report.remove_prefix(newline == std::string_view::npos ? report.size() : newline + 1); + if (line.size() > key.size() && line.substr(0, key.size()) == key && line[key.size()] == ' ') return line; + } + return {}; +} + +void test_report() { + config::unload(); + set_env("LEONIDA_GAMERTAG", "Tester"); + const std::string report = config::report(); + set_env("LEONIDA_GAMERTAG", nullptr); + + std::size_t lines = 0; + for (const char c : report) lines += c == '\n'; + expect(lines == config::kSettingCount + 1, "the report has a line for the file and one per setting"); + expect(report.rfind("settings file: none", 0) == 0, "without a file the first line says so"); + const std::string_view from_environment = report_line(report, "system.gamertag"); + expect(contains(from_environment, " environment ") && contains(from_environment, " LEONIDA_GAMERTAG ") && + from_environment.ends_with(" Tester"), + "a setting from the environment: source, variable and value; the line was \"" + + std::string(from_environment) + "\""); + const std::string_view not_set = report_line(report, "paths.game_dir"); + expect(contains(not_set, " default ") && not_set.ends_with(" (not set)"), + "a setting without a value; the line was \"" + std::string(not_set) + "\""); +} + +// The name a line of the example file sets: "name = value", or the same behind "# " (a default, shown but off). +// Empty for any other line. +std::string_view setting_name(std::string_view line, bool* commented) { + *commented = line.substr(0, 2) == "# "; + if (*commented) line.remove_prefix(2); + const auto in_name = [](char c) { return (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_'; }; + std::size_t n = 0; + while (n < line.size() && in_name(line[n])) ++n; + if (n == 0 || line.substr(n, 3) != " = ") return {}; + return line.substr(0, n); +} + +// True when `text` names `variable` as a whole word, not as the start or end of a longer name. +bool names_variable(std::string_view text, std::string_view variable) { + const auto in_name = [](char c) { return (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_'; }; + for (std::size_t at = text.find(variable); at != std::string_view::npos; at = text.find(variable, at + 1)) { + const std::size_t end = at + variable.size(); + if ((at == 0 || !in_name(text[at - 1])) && (end == text.size() || !in_name(text[end]))) return true; + } + return false; +} + +void test_example(const std::filesystem::path& file) { + std::ifstream in(file, std::ios::binary); + expect(in.is_open(), "the example file named on the command line can be opened"); + if (!in.is_open()) return; + const std::string text{std::istreambuf_iterator(in), std::istreambuf_iterator()}; + const std::string name = "leonida.example.toml"; + + config::FileValues as_written; + std::string error; + expect(config::parse(text, name, &as_written, &error), "the example is read as it is written: " + error); + expect(names_variable(text, config::kFileVariable), "the example names the variable that selects the file"); + + // With every "# name = value" line switched on, the file has to name each setting once, under its section and + // with its variable, and give it the default of the table. + std::string switched_on, section; + std::set listed; + std::string_view rest = text; + while (!rest.empty()) { + const std::size_t newline = rest.find('\n'); + std::string_view line = rest.substr(0, newline); + rest.remove_prefix(newline == std::string_view::npos ? rest.size() : newline + 1); + if (!line.empty() && line.back() == '\r') line.remove_suffix(1); + if (line.size() > 2 && line.front() == '[' && line.back() == ']') section = line.substr(1, line.size() - 2); + bool commented = false; + if (const std::string_view setting = setting_name(line, &commented); !setting.empty()) { + listed.insert(section + "." + std::string(setting)); + if (commented) line.remove_prefix(2); + } + switched_on.append(line).append("\n"); + } + config::FileValues defaults; + error.clear(); + const bool parsed = config::parse(switched_on, name, &defaults, &error); + expect(parsed, "the example is read with every setting switched on: " + error); + for (std::size_t i = 0; i < config::kSettingCount; ++i) { + const config::Setting& setting = config::kSettings[i]; + const std::string key = setting.key; + expect(listed.count(key) == 1, key + " is in the example"); + expect(names_variable(text, setting.variable), key + ": the example names " + setting.variable); + if (parsed) + expect(defaults[i].value_or("") == setting.fallback, + key + ": the example shows the default, \"" + setting.fallback + "\""); + } + expect(listed.size() == config::kSettingCount, "the example lists the settings of the table and no others"); +} + +} // namespace + +int main(int argc, char** argv) { + if (argc != 2) { + std::fprintf(stderr, "usage: core_config_test \n"); + return 2; + } + // The settings of whoever runs this must not decide its result. + for (const config::Setting& setting : config::kSettings) set_env(setting.variable, nullptr); + set_env(config::kFileVariable, nullptr); + + std::error_code failed; + const auto now = std::chrono::steady_clock::now().time_since_epoch().count(); + const std::filesystem::path dir = + std::filesystem::temp_directory_path(failed) / ("leonida_core_config_test_" + std::to_string(now)); + std::filesystem::create_directories(dir, failed); + expect(!failed, "the scratch folder can be made"); + + test_table(); + test_order(dir); + test_parse(); + test_load(dir); + test_report(); + test_example(argv[1]); + + std::filesystem::remove_all(dir, failed); + if (g_failures) { + std::fprintf(stderr, "%d check(s) failed\n", g_failures); + return 1; + } + std::puts("core_config_test: ok"); + return 0; +} diff --git a/runtime/test/core_log_test.cpp b/runtime/test/core_log_test.cpp new file mode 100644 index 000000000..84623fe60 --- /dev/null +++ b/runtime/test/core_log_test.cpp @@ -0,0 +1,298 @@ +// rt::log (core/log.h): which lines each level lets through, the "[rt] " prefix, that a line held back evaluates +// none of its arguments, a value that is not a level, and the order environment > file > default of log.level +// (LEONIDA_LOG), where an empty variable falls through to the file. No game files. +#include "../core/log.h" + +#include "../core/config.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(_WIN32) +#include +#include +#else +#include +#endif + +namespace { + +namespace config = rt::config; +namespace rtlog = rt::log; +using rtlog::Level; + +constexpr Level kLevels[] = {Level::Off, Level::Error, Level::Warn, Level::Info, Level::Debug, Level::Trace}; + +// A level is named in any case; nothing else is a level. +static_assert(rtlog::parse_level("off") == Level::Off && rtlog::parse_level("trace") == Level::Trace); +static_assert(rtlog::parse_level("WARN") == Level::Warn && rtlog::parse_level("Debug") == Level::Debug); +static_assert(!rtlog::parse_level("") && !rtlog::parse_level("warning") && !rtlog::parse_level("warn ") && + !rtlog::parse_level("1")); + +int g_failures = 0; + +void expect(bool ok, const std::string& what) { + if (ok) return; + std::fprintf(stderr, "FAIL: %s\n", what.c_str()); + ++g_failures; +} + +bool contains(std::string_view text, std::string_view part) { return text.find(part) != std::string_view::npos; } + +// Sets (value) or removes (nullptr) an environment variable of this process. +void set_env(const char* name, const char* value) { +#if defined(_WIN32) + SetEnvironmentVariableA(name, value); +#else + if (value) + setenv(name, value, 1); + else + unsetenv(name); +#endif +} + +void write_file(const std::filesystem::path& file, std::string_view text) { + std::ofstream out(file, std::ios::binary); + out.write(text.data(), static_cast(text.size())); +} + +#if defined(_WIN32) +int dup_fd(int fd) { return _dup(fd); } +int dup2_fd(int from, int to) { return _dup2(from, to); } +void close_fd(int fd) { _close(fd); } +int fd_of(std::FILE* stream) { return _fileno(stream); } +std::FILE* open_for_writing(const std::filesystem::path& file) { + std::FILE* out = nullptr; + if (_wfopen_s(&out, file.c_str(), L"wb") != 0) return nullptr; // wide: a TEMP outside the ANSI code page + return out; +} +#else +int dup_fd(int fd) { return dup(fd); } +int dup2_fd(int from, int to) { return dup2(from, to); } +void close_fd(int fd) { close(fd); } +int fd_of(std::FILE* stream) { return fileno(stream); } +std::FILE* open_for_writing(const std::filesystem::path& file) { return std::fopen(file.c_str(), "wb"); } +#endif + +// What `body` writes to stderr, without carriage returns. *redirected is false when stderr could not be sent to +// `file`; the text is then empty, which must not read as "nothing was printed". +std::string stderr_of(const std::filesystem::path& file, bool* redirected, const std::function& body) { + *redirected = false; + std::fflush(stderr); + const int stderr_fd = fd_of(stderr); + const int saved = dup_fd(stderr_fd); + std::FILE* out = open_for_writing(file); + if (out && saved >= 0) *redirected = dup2_fd(fd_of(out), stderr_fd) >= 0; + if (out) std::fclose(out); + if (*redirected) body(); + std::fflush(stderr); + if (saved >= 0) { + if (*redirected) dup2_fd(saved, stderr_fd); + close_fd(saved); + } + if (!*redirected) return {}; + std::ifstream in(file, std::ios::binary); + std::string text{std::istreambuf_iterator(in), std::istreambuf_iterator()}; + std::erase(text, '\r'); + return text; +} + +void test_levels() { + expect(rtlog::level() == rtlog::kDefaultLevel, "a program that sets no level logs at the default"); + expect(rtlog::kDefaultLevel == Level::Debug, + "the default lets every line through but trace lines, which is what was printed before the levels"); + for (const Level in_use : kLevels) { + const std::string name = rtlog::level_name(in_use); + rtlog::set_level(in_use); + expect(rtlog::level() == in_use, "set_level(" + name + ") is the level in use"); + for (const Level line : kLevels) { + const bool want = line != Level::Off && static_cast(line) <= static_cast(in_use); + expect(rtlog::enabled(line) == want, "at " + name + ", a line of level " + rtlog::level_name(line) + + (want ? " is printed" : " is held back")); + } + const auto named = rtlog::parse_level(name); + expect(named && *named == in_use, name + " is read back from its name"); + expect(contains(rtlog::kLevelList, name), "the list a warning shows names " + name); + } + rtlog::set_level(rtlog::kDefaultLevel); +} + +void test_output(const std::filesystem::path& dir) { + int evaluated = 0; + const auto number = [&](int value) { + ++evaluated; + return value; + }; + const auto all_five = [&] { + RT_LOG_ERROR("log_test: error %d\n", number(1)); + RT_LOG_WARN("log_test: warn %d\n", number(2)); + RT_LOG_INFO("log_test: info %s %d\n", "text", number(3)); + RT_LOG_DEBUG("log_test: debug %d\n", number(4)); + RT_LOG_TRACE("log_test: trace %d\n", number(5)); + RT_LOG_ERROR("log_test: no arguments\n"); + }; + struct Case { + Level in_use; + const char* text; + int evaluated; + }; + const Case cases[] = { + {Level::Off, "", 0}, + {Level::Error, "[rt] log_test: error 1\n[rt] log_test: no arguments\n", 1}, + {Level::Warn, "[rt] log_test: error 1\n[rt] log_test: warn 2\n[rt] log_test: no arguments\n", 2}, + {Level::Info, + "[rt] log_test: error 1\n[rt] log_test: warn 2\n[rt] log_test: info text 3\n" + "[rt] log_test: no arguments\n", + 3}, + {Level::Debug, + "[rt] log_test: error 1\n[rt] log_test: warn 2\n[rt] log_test: info text 3\n[rt] log_test: debug 4\n" + "[rt] log_test: no arguments\n", + 4}, + {Level::Trace, + "[rt] log_test: error 1\n[rt] log_test: warn 2\n[rt] log_test: info text 3\n[rt] log_test: debug 4\n" + "[rt] log_test: trace 5\n[rt] log_test: no arguments\n", + 5}, + }; + for (const Case& c : cases) { + const std::string name = rtlog::level_name(c.in_use); + rtlog::set_level(c.in_use); + evaluated = 0; + bool redirected = false; + const std::string text = stderr_of(dir / "output.txt", &redirected, all_five); + expect(redirected, "at " + name + ": stderr can be sent to a file"); + if (!redirected) continue; + expect(text == c.text, + "at " + name + " the lines printed are its own, each with the [rt] prefix; got \"" + text + "\""); + expect(evaluated == c.evaluated, + "at " + name + " a line held back evaluates none of its arguments (" + std::to_string(evaluated) + + " evaluated, expected " + std::to_string(c.evaluated) + ")"); + } + rtlog::set_level(rtlog::kDefaultLevel); +} + +void test_settings(const std::filesystem::path& dir) { + constexpr config::Name setting("log.level"); + const char* const variable = setting.setting().variable; + expect(std::string_view(variable) == "LEONIDA_LOG", "log.level is set by LEONIDA_LOG"); + expect(std::string_view(setting.setting().fallback) == rtlog::level_name(rtlog::kDefaultLevel), + "the default in kSettings is the default of the log"); + + // environment > file > default + std::string warning = "left over"; + const auto asked = [&] { return rtlog::level_from_settings(&warning); }; + expect(asked() == rtlog::kDefaultLevel && warning.empty(), "nothing set: the default, and no warning"); + + const std::filesystem::path file = dir / "log.toml"; + write_file(file, "[log]\nlevel = 'warn'\n"); + std::string error; + expect(config::load_file(file, &error), "a file that sets log.level is read: " + error); + expect(asked() == Level::Warn && warning.empty(), "set in the file: the file's level"); + + set_env(variable, "error"); + expect(asked() == Level::Error && warning.empty(), "the variable wins over the file"); + const std::string report = config::report(); + const std::size_t at = report.find("\nlog.level "); + std::string_view line; + if (at != std::string::npos) { + line = std::string_view(report).substr(at + 1); + line = line.substr(0, line.find('\n')); + } + expect(contains(line, " environment ") && contains(line, " LEONIDA_LOG ") && line.ends_with(" error"), + "the report (`gta6rt config`) shows log.level with its source, variable and value; the line was \"" + + std::string(line) + "\""); + set_env(variable, "TRACE"); + expect(asked() == Level::Trace && warning.empty(), "a level is named in any case"); + set_env(variable, ""); + expect(asked() == Level::Warn && warning.empty(), "an empty variable falls through to the file"); + set_env(variable, nullptr); + expect(asked() == Level::Warn && warning.empty(), "the variable removed: the file's level again"); + + // A value that is not a level: the default, and one warning that lists the levels. + set_env(variable, "loud"); + const std::string want = "log: LEONIDA_LOG=loud unknown (off, error, warn, info, debug or trace), using debug"; + Level got = asked(); + expect(got == rtlog::kDefaultLevel && warning == want, + "an unknown value gives the default and a warning that lists the levels; the warning was \"" + warning + + "\""); + expect(rtlog::level_from_settings() == rtlog::kDefaultLevel, "the warning is optional"); + set_env(variable, nullptr); + write_file(file, "[log]\nlevel = 'verbose'\n"); + expect(config::load_file(file, &error), "a file with an unknown level is still a file in the format: " + error); + got = asked(); + expect(got == rtlog::kDefaultLevel && contains(warning, "LEONIDA_LOG=verbose "), + "an unknown value from the file gives the default too and names the variable; the warning was \"" + + warning + "\""); + config::unload(); + expect(asked() == rtlog::kDefaultLevel && warning.empty(), "the file forgotten: the default again"); + + // apply_settings() makes it the level in use and prints the warning once, as a log line. + bool redirected = false; + rtlog::set_level(Level::Off); // the warning is printed although the level before was off + set_env(variable, "loud"); + std::string text = stderr_of(dir / "apply.txt", &redirected, [] { rtlog::apply_settings(); }); + expect(redirected, "stderr can be sent to a file"); + if (redirected) + expect(text == "[rt] " + want + "\n", "apply_settings() prints the warning once; got \"" + text + "\""); + expect(rtlog::level() == rtlog::kDefaultLevel, "apply_settings() with an unknown value: the default is in use"); + + rtlog::set_level(Level::Off); + text = stderr_of(dir / "apply.txt", &redirected, [] { rtlog::apply_settings(false); }); + expect(redirected && text.empty() && rtlog::level() == rtlog::kDefaultLevel, + "apply_settings(false) uses the default for an unknown value without printing; got \"" + text + "\""); + + set_env(variable, "off"); + text = stderr_of(dir / "apply.txt", &redirected, [] { + rtlog::apply_settings(); + RT_LOG_ERROR("log_test: must not be printed\n"); + }); + expect(redirected && text.empty() && rtlog::level() == Level::Off, + "LEONIDA_LOG=off: apply_settings() prints nothing and no line follows; got \"" + text + "\""); + + set_env(variable, "warn"); + text = stderr_of(dir / "apply.txt", &redirected, [] { + rtlog::apply_settings(); + RT_LOG_WARN("log_test: kept\n"); + RT_LOG_INFO("log_test: held back\n"); + }); + expect(redirected && text == "[rt] log_test: kept\n" && rtlog::level() == Level::Warn, + "LEONIDA_LOG=warn: warnings are printed, info lines are not; got \"" + text + "\""); + + set_env(variable, nullptr); + rtlog::apply_settings(); + expect(rtlog::level() == rtlog::kDefaultLevel, "nothing set: apply_settings() goes back to the default"); +} + +} // namespace + +int main() { + // The settings of whoever runs this must not decide its result. + for (const config::Setting& setting : config::kSettings) set_env(setting.variable, nullptr); + set_env(config::kFileVariable, nullptr); + + std::error_code failed; + const auto now = std::chrono::steady_clock::now().time_since_epoch().count(); + const std::filesystem::path dir = + std::filesystem::temp_directory_path(failed) / ("leonida_core_log_test_" + std::to_string(now)); + std::filesystem::create_directories(dir, failed); + expect(!failed, "the scratch folder can be made"); + + test_levels(); + test_output(dir); + test_settings(dir); + + std::filesystem::remove_all(dir, failed); + if (g_failures) { + std::fprintf(stderr, "%d check(s) failed\n", g_failures); + return 1; + } + std::puts("core_log_test: ok"); + return 0; +} diff --git a/runtime/test/d3d12_close_parity_test.cpp b/runtime/test/d3d12_close_parity_test.cpp index 0f01f261d..4e47a74c5 100644 --- a/runtime/test/d3d12_close_parity_test.cpp +++ b/runtime/test/d3d12_close_parity_test.cpp @@ -146,6 +146,9 @@ struct Case { bool warp_ok; // WARP's Close verdict, measured Known known; Recorder record; + // The case copies from a placed footprint whose offset or row pitch is not aligned: warp_ok and known are for + // a WARP that reports UnrestrictedBufferTextureCopyPitchSupported. One that does not must refuse the list. + bool unaligned_footprint = false; }; #define CALLS(...) [](Env& e) { __VA_ARGS__; return true; } @@ -216,11 +219,11 @@ std::vector cases() { {"CopyTextureRegion upload, offset 0, row pitch 256", true, match, CALLS(RECORD_COPY(subresource(e.tex.p, 0), 0, footprint(e.upload.p, 0, 256), nullptr))}, {"CopyTextureRegion upload, offset 16 (not 512-aligned)", true, stricter, - CALLS(RECORD_COPY(subresource(e.tex.p, 0), 0, footprint(e.upload.p, 16, 256), nullptr))}, + CALLS(RECORD_COPY(subresource(e.tex.p, 0), 0, footprint(e.upload.p, 16, 256), nullptr)), true}, {"CopyTextureRegion upload, offset 4 (not 512-aligned)", true, stricter, - CALLS(RECORD_COPY(subresource(e.tex.p, 0), 0, footprint(e.upload.p, 4, 256), nullptr))}, + CALLS(RECORD_COPY(subresource(e.tex.p, 0), 0, footprint(e.upload.p, 4, 256), nullptr)), true}, {"CopyTextureRegion upload, row pitch 260 (not 256-aligned)", true, stricter, - CALLS(RECORD_COPY(subresource(e.tex.p, 0), 0, footprint(e.upload.p, 0, 260), nullptr))}, + CALLS(RECORD_COPY(subresource(e.tex.p, 0), 0, footprint(e.upload.p, 0, 260), nullptr)), true}, {"CopyTextureRegion upload, row pitch 128 (shorter than a row)", false, match, CALLS(RECORD_COPY(subresource(e.tex.p, 0), 0, footprint(e.upload.p, 0, 128), nullptr))}, {"CopyTextureRegion upload, footprint format UNKNOWN", false, looser, @@ -487,6 +490,9 @@ int main() { } bool warp_ran = false; + // Whether the live WARP reports UnrestrictedBufferTextureCopyPitchSupported; an older runtime that does not know + // D3D12_FEATURE_D3D12_OPTIONS13 answers E_INVALIDARG, which counts as not reported. + bool warp_unrestricted_pitch = false; if (!hostwine::host_is_wine()) { Ref factory; Ref adapter; @@ -497,6 +503,10 @@ int main() { Env env; REQUIRE(env.init(host.p)); for (std::size_t i = 0; i < table.size(); ++i) REQUIRE(run_case(env, table[i], warp[i])); + D3D12_FEATURE_DATA_D3D12_OPTIONS13 options13{}; + warp_unrestricted_pitch = + SUCCEEDED(host->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS13, &options13, sizeof(options13))) && + options13.UnrestrictedBufferTextureCopyPitchSupported; // Nothing is executed, so nothing should remove the device; if something did, its answers are suspect. REQUIRE(host->GetDeviceRemovedReason() == S_OK); warp_ran = true; @@ -506,13 +516,20 @@ int main() { } unsigned failures = 0, matched = 0, known_stricter = 0, known_looser = 0, warp_changed = 0, skipped = 0; + unsigned aligned_only = 0; // unaligned-footprint cases a WARP without the unrestricted-pitch capability refuses std::printf("%-62s | %-10s | %-10s | %s\n", "case", "layer", "WARP", "expected"); for (std::size_t i = 0; i < table.size(); ++i) { const Case& c = table[i]; const bool live = warp_ran && warp[i] != not_run; - const char* expected = c.known == Known::match ? "match" - : c.known == Known::layer_stricter ? "layer stricter (known)" - : "layer looser (known)"; + // D3D12 wants a placed footprint's offset a multiple of 512 and its row pitch a multiple of 256 unless the + // device reports UnrestrictedBufferTextureCopyPitchSupported. A WARP that does not report it refuses the + // list (d3d10warp.dll 10.0.19041.3636 on Windows 10 22H2: Close is E_INVALIDARG), which is what the layer + // does, so the difference the table records does not exist there and the layer has to agree. + const bool aligned_only_warp = c.unaligned_footprint && live && !warp_unrestricted_pitch && FAILED(warp[i]); + const Known known = aligned_only_warp ? Known::match : c.known; + const char* expected = known == Known::match ? "match" + : known == Known::layer_stricter ? "layer stricter (known)" + : "layer looser (known)"; std::printf("%-62s | %-10s | %-10s | %s\n", c.name, text(layer[i]).c_str(), live ? text(warp[i]).c_str() : (c.warp_ok ? "(S_OK)" : "(failure)"), expected); if (layer[i] == not_run) { @@ -524,11 +541,16 @@ int main() { c.warp_ok ? "S_OK" : "a failure"); ++warp_changed; } + if (aligned_only_warp) { + std::printf(" this WARP does not report UnrestrictedBufferTextureCopyPitchSupported and refuses the " + "list, so the layer has to agree with it\n"); + ++aligned_only; + } const bool reference_ok = live ? SUCCEEDED(warp[i]) : c.warp_ok; const bool layer_ok = SUCCEEDED(layer[i]); - const bool want_layer_ok = c.known == Known::match ? reference_ok : !reference_ok; + const bool want_layer_ok = known == Known::match ? reference_ok : !reference_ok; if (layer_ok != want_layer_ok) { - if (c.known == Known::match) + if (known == Known::match) std::fprintf(stderr, "FAIL %s: layer Close %s, WARP %s\n", c.name, text(layer[i]).c_str(), reference_ok ? "succeeds" : "fails"); else @@ -536,8 +558,8 @@ int main() { ++failures; continue; } - if (c.known == Known::match) ++matched; - else if (c.known == Known::layer_stricter) ++known_stricter; + if (known == Known::match) ++matched; + else if (known == Known::layer_stricter) ++known_stricter; else ++known_looser; } const unsigned validation_errors = vk.validation_errors() - errors_before; @@ -545,6 +567,9 @@ int main() { std::fprintf(stderr, "%u Vulkan validation errors\n", validation_errors); ++failures; } + if (aligned_only) + std::printf("close parity: %u unaligned-footprint cases counted as matches, not as known layer-stricter: this " + "WARP does not report UnrestrictedBufferTextureCopyPitchSupported\n", aligned_only); std::printf("close parity: %zu cases, %u match %s, %u known layer-stricter, %u known layer-looser, %u not run, " "%u where WARP differs from the measured column, %u failures\n", table.size(), matched, warp_ran ? "WARP" : "the measured WARP column", known_stricter, known_looser, diff --git a/runtime/test/d3d12_dxr_validation_test.cpp b/runtime/test/d3d12_dxr_validation_test.cpp index 2e09a39ee..feccd22d0 100644 --- a/runtime/test/d3d12_dxr_validation_test.cpp +++ b/runtime/test/d3d12_dxr_validation_test.cpp @@ -93,6 +93,30 @@ int run_suite(ID3D12Device* base_dev, const char* name, bool check_strict_valida std::printf("%s: raytracing not supported (tier=%d), skipping\n", name, static_cast(o5.RaytracingTier)); return 77; } + // The layer reports no raytracing tier and builds XDXR records, or KHR structures with LEONIDA_RT_AS=khr. + // The KHR builds need VK_KHR_acceleration_structure, VK_KHR_deferred_host_operations and VK_KHR_ray_query. On + // a GPU without one of them (a GTX 1070 Ti with NVIDIA 582.66 has no VK_KHR_ray_query) the layer then has no + // acceleration structures at all: it answers a zero prebuild and refuses a buffer in the + // acceleration-structure state, so the buffers below cannot be made. Ask before making them. + if (check_strict_validation && o5.RaytracingTier == D3D12_RAYTRACING_TIER_NOT_SUPPORTED) { + D3D12_RAYTRACING_GEOMETRY_DESC probe_tri{}; + probe_tri.Type = D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES; + probe_tri.Flags = D3D12_RAYTRACING_GEOMETRY_FLAG_OPAQUE; + probe_tri.Triangles.VertexFormat = DXGI_FORMAT_R32G32B32_FLOAT; + probe_tri.Triangles.VertexCount = 3; + probe_tri.Triangles.VertexBuffer.StrideInBytes = 12; + D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS probe_in{}; + probe_in.Type = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL; + probe_in.DescsLayout = D3D12_ELEMENTS_LAYOUT_ARRAY; + probe_in.NumDescs = 1; + probe_in.pGeometryDescs = &probe_tri; + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO probe_info{}; + dev->GetRaytracingAccelerationStructurePrebuildInfo(&probe_in, &probe_info); + if (is_zero_prebuild(probe_info)) { + std::printf("%s: neither XDXR nor KHR acceleration structures supported, skipping\n", name); + return 77; + } + } Ref vb, inst_buf, scratch, blas_buf, tlas_buf, src_as, post_buf; if (!make_buffer(dev.p, 4096, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_FLAG_NONE, diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp index fd827f9a1..b04f5692b 100644 --- a/runtime/test/d3d12_existing_heap_test.cpp +++ b/runtime/test/d3d12_existing_heap_test.cpp @@ -260,15 +260,58 @@ int check_title_placed(ID3D12Device* device, const char* kind, void* pages, UINT return 0; } -int check_title_placed_all(ID3D12Device* device) { +// A buffer placed inside a page, as the title places small UAV buffers (64-byte aligned, found in review on an RTX +// 5090): the import starts at the page and the buffer is bound at the offset. Vulkan binds a buffer only at a multiple +// of the alignment the driver names for it, with the driver's size for it fitting behind the offset, so whether that +// works is the driver's: NVIDIA 582.66 on a GTX 1070 Ti names 256 bytes (the same as its +// minUniformBufferOffsetAlignment) and rounds the 4032 bytes up to 4096, and the layer answers with its +// ordinary-buffer fallback there. The driver is asked through the buffer the layer imports at the page's start, which +// has the same description and so the same usage; where it cannot bind 64 bytes in, the fallback is checked instead. +int check_title_placed_inside_page(ID3D12Device* device, const vktest::Device& vk, void* page) { + const char* who = "vulkan slot-133 buffer"; + constexpr UINT64 offset = 64, size = 0x1000 - offset; + void* const address = static_cast(page) + offset; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = size; + desc.Height = desc.DepthOrArraySize = desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + VkMemoryRequirements requirements{}; + { + Ref at_start; + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, page, desc, 0xFFFFFFFFu, + IID_PPV_ARGS(&at_start.p)), + S_OK); + EXPECT(at_start->GetGPUVirtualAddress() == reinterpret_cast(page)); + const VkBuffer buffer = rt::d3d12::vulkan_buffer(at_start.p); + EXPECT(buffer != VK_NULL_HANDLE); + vk.fn("vkGetBufferMemoryRequirements")(vk.device, buffer, &requirements); + } + EXPECT(requirements.alignment != 0); + const UINT64 imported = (offset + size + vk.host_pointer_alignment - 1) / vk.host_pointer_alignment * + vk.host_pointer_alignment; + if (offset % requirements.alignment == 0 && requirements.size <= imported - offset) + return check_title_placed(device, "64 bytes into a page", address, size); + Ref fallback; + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, address, desc, 0xFFFFFFFFu, IID_PPV_ARGS(&fallback.p)), + S_OK); + EXPECT(fallback.p != nullptr && fallback->GetDesc().Width == size); + EXPECT(fallback->GetGPUVirtualAddress() != reinterpret_cast(address)); + std::printf("%s: 64 bytes into a page, %llu bytes: this driver binds the buffer only at a multiple of %llu bytes " + "(its size for it: %llu), so it is not imported; ordinary-buffer fallback verified\n", + who, static_cast(size), static_cast(requirements.alignment), + static_cast(requirements.size)); + return 0; +} + +int check_title_placed_all(ID3D12Device* device, const vktest::Device& vk) { constexpr SIZE_T size = 4 * 0x10000; int failures = 0; void* pages = VirtualAlloc(nullptr, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); if (!pages) return 1; failures += check_title_placed(device, "VirtualAlloc range", pages, size); - // Inside a page, as the title places small UAV buffers (64-byte aligned, found in review on an RTX 5090): the - // import starts at the page and the buffer is bound at the offset. - failures += check_title_placed(device, "64 bytes into a page", static_cast(pages) + 64, 0x1000 - 64); + failures += check_title_placed_inside_page(device, vk, pages); VirtualFree(pages, 0, MEM_RELEASE); HANDLE section = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, DWORD(size), nullptr); void* view = section ? MapViewOfFile(section, FILE_MAP_ALL_ACCESS, 0, 0, size) : nullptr; @@ -352,7 +395,7 @@ int main() { const std::vector vulkan_cases = open_cases(ours.p); print_cases(vulkan_cases, "vulkan"); failures += check_import(ours.p, vk.host_pointer_alignment != 0); - if (vk.host_pointer_alignment) failures += check_title_placed_all(ours.p); + if (vk.host_pointer_alignment) failures += check_title_placed_all(ours.p, vk); Ref factory; if (!hostwine::host_is_wine() && SUCCEEDED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p)))) { for (const bool warp : {false, true}) { diff --git a/runtime/test/d3d12_heap_properties_test.cpp b/runtime/test/d3d12_heap_properties_test.cpp index 5d7ee942c..2d5824a07 100644 --- a/runtime/test/d3d12_heap_properties_test.cpp +++ b/runtime/test/d3d12_heap_properties_test.cpp @@ -283,6 +283,27 @@ int main() { name[c.size()] == ',' || name[c.size()] == ' ')) return true; return false; }; + // D3D12_RESOURCE_HEAP_TIER_1 lets a heap hold one resource category only, so a host at that tier refuses the + // heap of a placed case that does not set two of the three DENY flags (measured on a GTX 1070 Ti, NVIDIA + // 582.66: E_INVALIDARG from CreateHeap; WARP on the same PC reports tier 2 and accepts it). The layer + // accepts such a heap on every GPU. On a tier 1 host only that pair is excused, for the case's "created" + // value: the layer's S_OK against the host's E_INVALIDARG. + D3D12_FEATURE_DATA_D3D12_OPTIONS host_options{}; + const bool host_tier1 = + SUCCEEDED(host->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &host_options, sizeof(host_options))) && + host_options.ResourceHeapTier == D3D12_RESOURCE_HEAP_TIER_1; + std::vector mixed_heap_created; + for (const Case& c : cases()) { + const UINT deny = UINT(c.flags) & UINT(D3D12_HEAP_FLAG_DENY_BUFFERS | D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES | + D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES); + if (c.kind == Kind::placed && !(deny & (deny - 1))) // fewer than two DENY flags + mixed_heap_created.push_back(std::string(c.name) + ": created"); + } + const auto mixed_heap = [&](const std::string& name) { + for (const std::string& c : mixed_heap_created) + if (name == c) return true; + return false; + }; std::printf("heap properties: host %s (UMA %d, the layer's UMA %d)\n", host_name.c_str(), host_arch.UMA, our_arch.UMA); // A resource one side couldn't create has fewer entries: compare case by case on the names both have. @@ -311,6 +332,15 @@ int main() { ++skipped; continue; } + if (host_tier1 && mixed_heap(ours.names[i]) && a == std::uint32_t(S_OK) && + b == std::uint32_t(E_INVALIDARG)) { + std::printf("heap properties %s: not comparable on this host (resource heap tier 1 refuses a heap " + "of more than one resource category; ours 0x%llx, host 0x%llx)\n", + ours.names[i].c_str(), static_cast(a), + static_cast(b)); + ++skipped; + continue; + } ++compared; const bool same = a == b; if (verbose || !same) diff --git a/runtime/test/d3d12_m4_compute_test.cpp b/runtime/test/d3d12_m4_compute_test.cpp index c50a63b04..5d40d6118 100644 --- a/runtime/test/d3d12_m4_compute_test.cpp +++ b/runtime/test/d3d12_m4_compute_test.cpp @@ -139,7 +139,7 @@ int main() { EXPECT(rt::d3d12::bindless_set(device.p) != VK_NULL_HANDLE); // [0] four 32-bit constants (s4..s7), [1] a table of five UAVs (s8, its 32-bit VA): the console compute layout - // (D3D-448). The fixtures are built with LEONIDA_USER_DATA_SHIFT=4 (runtime/CMakeLists.txt). + // (D3D-448). The fixtures are built with LEONIDA_USER_DATA_SHIFT=4 (runtime/cmake/d3d12_vulkan.cmake). D3D12_DESCRIPTOR_RANGE uav_range{D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 5, 0, 0, 0}; D3D12_ROOT_PARAMETER params[2] = {}; params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; diff --git a/runtime/test/d3d12_set_descriptor_heaps_test.cpp b/runtime/test/d3d12_set_descriptor_heaps_test.cpp index 62ffb1ffe..84c7bb3a3 100644 --- a/runtime/test/d3d12_set_descriptor_heaps_test.cpp +++ b/runtime/test/d3d12_set_descriptor_heaps_test.cpp @@ -54,6 +54,28 @@ struct DeviceHeaps { } }; +// Sets the flags word of the RTS0 chunk in a serialized root signature: the dword at +20 of the chunk's payload, +// where rt::rootsig::parse_rts0 reads it. The container hash at bytes 4..19 is left as it was. False when the blob +// is not a DXBC container with an RTS0 chunk. +bool set_rts0_flags(std::vector& blob, std::uint32_t flags) { + const auto u32_at = [&](std::size_t off, std::uint32_t& v) { + if (off > blob.size() || blob.size() - off < 4) return false; + std::memcpy(&v, blob.data() + off, 4); + return true; + }; + std::uint32_t chunks = 0; + if (blob.size() < 32 || std::memcmp(blob.data(), "DXBC", 4) != 0 || !u32_at(28, chunks)) return false; + for (std::uint32_t i = 0; i < chunks; ++i) { + std::uint32_t off = 0, size = 0; + if (!u32_at(32 + 4 * std::size_t(i), off) || !u32_at(std::size_t(off) + 4, size)) return false; + if (std::memcmp(blob.data() + off, "RTS0", 4) != 0) continue; + if (size < 24 || blob.size() - off - 8 < size) return false; + std::memcpy(blob.data() + off + 8 + 20, &flags, 4); + return true; + } + return false; +} + bool check_single_list_cases(DeviceHeaps& ours, ID3D12DescriptorHeap* foreign_heap, DeviceHeaps* host, const std::string& host_name) { struct Case { @@ -337,8 +359,20 @@ bool check_tracking_lifetime_and_direct_indexing(DeviceHeaps& ours) { const auto di_flags = D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED | D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED; rs_desc.Desc_1_0 = {1, &p, 0, nullptr, di_flags}; - const auto blob = d3d12test::serialize_root_signature(rs_desc); - CHECK(!blob.empty()); + auto blob = d3d12test::serialize_root_signature(rs_desc); + if (blob.empty()) { + // An older host serializer does not know the two flags: d3d12.dll build 19041.3636 (Windows 10 22H2) + // answers E_INVALIDARG, "Unsupported bit-flag set (root signature flags c00)", as it does for an undefined + // bit. The layer parses the blob itself (rt::rootsig::parse_rts0) and does not check the container hash, so + // serialize the same signature without the flags and set them in the RTS0 header. What is checked below, that + // the layer keeps the flags it is given, does not depend on which serializer wrote them. + rs_desc.Desc_1_0.Flags = D3D12_ROOT_SIGNATURE_FLAG_NONE; + blob = d3d12test::serialize_root_signature(rs_desc); + CHECK(!blob.empty()); + CHECK(set_rts0_flags(blob, std::uint32_t(di_flags))); + std::printf("directly-indexed root signature flags: the host serializer refuses them (older d3d12.dll); set " + "in the RTS0 header instead\n"); + } Ptr root; CHECK(SUCCEEDED(ours.device->CreateRootSignature(0, blob.data(), blob.size(), IID_PPV_ARGS(&root.p)))); const rt::d3d12::RootArgumentLayout* layout = rt::d3d12::root_signature_layout(root.p); diff --git a/runtime/test/d3d12_subgroup_test.cpp b/runtime/test/d3d12_subgroup_test.cpp index ccc0d2aff..123586d10 100644 --- a/runtime/test/d3d12_subgroup_test.cpp +++ b/runtime/test/d3d12_subgroup_test.cpp @@ -189,7 +189,8 @@ Result run(vktest::Device& d, const std::filesystem::path& library, const leonid rt::d3d12::set_device_outer(inner, device.p); // Root signature: [0] four constants (s4..s7 in the console compute layout, D3D-448), the V# the shaders store - // through. The asm fixtures are built with LEONIDA_USER_DATA_SHIFT=4 to read it there (runtime/CMakeLists.txt). + // through. The asm fixtures are built with LEONIDA_USER_DATA_SHIFT=4 to read it there + // (runtime/cmake/d3d12_vulkan.cmake). D3D12_ROOT_PARAMETER param{}; param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; param.Constants = {0, 0, 4}; diff --git a/runtime/test/d3d12_vulkan_device_test.cpp b/runtime/test/d3d12_vulkan_device_test.cpp index 41418c538..e539e6f2f 100644 --- a/runtime/test/d3d12_vulkan_device_test.cpp +++ b/runtime/test/d3d12_vulkan_device_test.cpp @@ -1758,7 +1758,8 @@ int compare_feature_support(ID3D12Device* ours) { static_cast(ours_data.HighestShaderModel), host_hr, want); } - // 0x3 is 1.2 by number: SDKs without the 1.2 headers do not name it (runtime/CMakeLists.txt probes for that). + // 0x3 is 1.2 by number: SDKs without the 1.2 headers do not name it (runtime/cmake/windows_runtime.cmake probes + // for that). const D3D_ROOT_SIGNATURE_VERSION versions[] = {D3D_ROOT_SIGNATURE_VERSION_1_0, D3D_ROOT_SIGNATURE_VERSION_1_1, static_cast(0x3)}; UINT host_version = 0; @@ -3063,9 +3064,20 @@ struct PlacedArgs { const IID* riid = &__uuidof(ID3D12Resource); }; +// Set by placed() when the device refused the case's heap and that heap takes more than one resource category (it +// does not set two of the three DENY flags). compare_placed_reserved clears it before the host's call and reads it +// after: a host at D3D12_RESOURCE_HEAP_TIER_1 refuses such a heap. +bool g_placed_mixed_heap_refused = false; + HRESULT placed(ID3D12Device* device, const D3D12_RESOURCE_DESC* desc, const PlacedArgs& args = {}) { ID3D12Heap* heap = nullptr; - if (FAILED(device->CreateHeap(&args.heap, IID_PPV_ARGS(&heap)))) return E_UNEXPECTED; + if (FAILED(device->CreateHeap(&args.heap, IID_PPV_ARGS(&heap)))) { + const UINT deny = UINT(args.heap.Flags) & + UINT(D3D12_HEAP_FLAG_DENY_BUFFERS | D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES | + D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES); + if (!(deny & (deny - 1))) g_placed_mixed_heap_refused = true; // fewer than two DENY flags + return E_UNEXPECTED; + } void* out = nullptr; const HRESULT hr = device->CreatePlacedResource(heap, args.offset, desc, args.state, args.clear, *args.riid, args.output ? &out : nullptr); @@ -4382,28 +4394,33 @@ int compare_heap_neighbours(ID3D12Device* ours) { const char* name; InvalidCase call; bool windows10_refuses = false; + // The heap takes more than one resource category (it does not set two of the three DENY flags), which a host + // at D3D12_RESOURCE_HEAP_TIER_1 refuses. + bool mixed = false; }; static const Case cases[] = { - {"heap: alignment 0", [](ID3D12Device* d) { return heap_create(d, heap_desc_of(0)); }}, + {"heap: alignment 0", [](ID3D12Device* d) { return heap_create(d, heap_desc_of(0)); }, false, true}, {"heap: alignment 64 KiB", [](ID3D12Device* d) { return heap_create(d, heap_desc_of(D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT)); - }}, + }, false, true}, {"heap: alignment 4 MiB", [](ID3D12Device* d) { return heap_create(d, heap_desc_of(D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT, {D3D12_HEAP_TYPE_DEFAULT}, D3D12_HEAP_FLAG_NONE, D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT)); - }}, + }, false, true}, {"heap: size 1000", [](ID3D12Device* d) { return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT}, D3D12_HEAP_FLAG_NONE, 1000)); - }}, - {"heap: upload", [](ID3D12Device* d) { return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_UPLOAD})); }}, + }, false, true}, + {"heap: upload", [](ID3D12Device* d) { + return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_UPLOAD})); + }, false, true}, {"heap: readback", [](ID3D12Device* d) { return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_READBACK})); - }}, + }, false, true}, {"heap: custom write-combine L0", [](ID3D12Device* d) { return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE, D3D12_MEMORY_POOL_L0})); - }}, + }, false, true}, {"heap: ALLOW_ONLY_BUFFERS (two DENY flags)", [](ID3D12Device* d) { return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT}, D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS)); }}, @@ -4412,13 +4429,26 @@ int compare_heap_neighbours(ID3D12Device* ours) { // case above. {"heap: HARDWARE_PROTECTED", [](ID3D12Device* d) { return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT}, D3D12_HEAP_FLAG_HARDWARE_PROTECTED)); - }, true}, + }, true, true}, }; + // D3D12_RESOURCE_HEAP_TIER_1 lets a heap hold one resource category only, so a host at that tier refuses the + // cases marked mixed with E_INVALIDARG (measured on a GTX 1070 Ti, NVIDIA 582.66; WARP on the same PC reports + // tier 2 and accepts them). The layer accepts them on every GPU, as the accepted_heaps checks in main require. + // On a tier 1 host only that pair is excused: the layer's S_OK against the host's E_INVALIDARG. + D3D12_FEATURE_DATA_D3D12_OPTIONS host_options{}; + const bool host_tier1 = + SUCCEEDED(host->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &host_options, sizeof(host_options))) && + host_options.ResourceHeapTier == D3D12_RESOURCE_HEAP_TIER_1; int mismatches = 0; for (const Case& c : cases) { const HRESULT a = call_guarded(c.call, ours), b = call_guarded(c.call, host.p); if (a == b) continue; if (c.windows10_refuses && windows10_refusal(c.name, host.p, a, b)) continue; + if (c.mixed && host_tier1 && a == S_OK && b == E_INVALIDARG) { + std::printf("invalid arguments %s: not comparable on this host (resource heap tier 1 refuses a heap of " + "more than one resource category; ours 0x%08lx, host 0x%08lx)\n", c.name, a, b); + continue; + } ++mismatches; std::fprintf(stderr, "invalid arguments %s: ours 0x%08lx, host 0x%08lx\n", c.name, a, b); } @@ -4906,6 +4936,16 @@ int compare_placed_reserved(ID3D12Device* ours) { return reserved(d, desc); }}, }; + // D3D12_RESOURCE_HEAP_TIER_1 lets a heap hold one resource category only, so a host at that tier refuses the + // heap most placed cases use (D3D12_HEAP_FLAG_NONE): E_INVALIDARG from CreateHeap, measured on a GTX 1070 Ti + // (NVIDIA 582.66), where WARP on the same PC reports tier 2 and accepts it. placed() then answers E_UNEXPECTED + // before the host's CreatePlacedResource is reached, so the host has no answer to compare with. Only that is + // excused: a tier 1 host that refused the case's own heap for taking more than one category. + D3D12_FEATURE_DATA_D3D12_OPTIONS host_options{}; + const bool host_tier1 = + SUCCEEDED(host->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &host_options, sizeof(host_options))) && + host_options.ResourceHeapTier == D3D12_RESOURCE_HEAP_TIER_1; + int heap_tier_skipped = 0; const bool verbose = GetEnvironmentVariableA("LEONIDA_D3D49_VERBOSE", nullptr, 0) > 0; int mismatches = 0; for (const Case& c : cases) { @@ -4913,10 +4953,23 @@ int compare_placed_reserved(ID3D12Device* ours) { std::printf("invalid arguments %s:", c.name); std::fflush(stdout); } - const HRESULT a = call_guarded(c.call, ours), b = call_guarded(c.call, host.p); + const HRESULT a = call_guarded(c.call, ours); + g_placed_mixed_heap_refused = false; + const HRESULT b = call_guarded(c.call, host.p); + const bool host_refused_mixed_heap = g_placed_mixed_heap_refused; if (verbose) std::printf(" ours 0x%08lx host 0x%08lx\n", a, b); if (a == b) continue; if (c.windows10_refuses && windows10_refusal(c.name, host.p, a, b)) continue; + if (host_tier1 && host_refused_mixed_heap && b == E_UNEXPECTED) { + if (!heap_tier_skipped++) + std::printf("invalid arguments placed: the host is at resource heap tier 1 and refuses a heap of more " + "than one resource category; the cases that use one are not compared (first: %s)\n", + c.name); + if (verbose) + std::printf("invalid arguments %s: not comparable on this host (resource heap tier 1; ours 0x%08lx, " + "host 0x%08lx)\n", c.name, a, b); + continue; + } if (c.comparable && !c.comparable(host.p)) { std::printf("invalid arguments %s: not comparable on this host (ours 0x%08lx, host 0x%08lx)\n", c.name, a, b); @@ -4925,6 +4978,9 @@ int compare_placed_reserved(ID3D12Device* ours) { ++mismatches; std::fprintf(stderr, "invalid arguments %s: ours 0x%08lx, host 0x%08lx\n", c.name, a, b); } + if (heap_tier_skipped) + std::printf("invalid arguments placed: %d of %zu placed and reserved cases not compared on this resource heap " + "tier 1 host\n", heap_tier_skipped, std::size(cases)); return mismatches; } diff --git a/runtime/test/int3_skip_test.cpp b/runtime/test/int3_skip_test.cpp index 3c06302eb..01db36afd 100644 --- a/runtime/test/int3_skip_test.cpp +++ b/runtime/test/int3_skip_test.cpp @@ -1,5 +1,6 @@ -// LEONIDA_SKIP_INT3 (shims/startup_trace.h): with the variable set and a trace open, an int3 is logged once per -// address and stepped over, so execution continues. A separate executable because the variable is read once. +// loader.skip_int3 (LEONIDA_SKIP_INT3; shims/startup_trace.h): with set_skip_int3(true) and a trace open, an int3 is +// logged once per address and stepped over, so execution continues. gta6rt sets the switch from the setting; this +// test sets it itself. A separate executable because the switch changes what the handler does for the whole process. #include #include @@ -38,7 +39,7 @@ __declspec(noinline) void site_b(int& reached) { } // namespace int main() { - SetEnvironmentVariableW(L"LEONIDA_SKIP_INT3", L"1"); // before the first exception: the flag is read once + rt::startup_trace::set_skip_int3(true); // before the first exception wchar_t temp[MAX_PATH]; GetTempPathW(MAX_PATH, temp); const std::wstring path = std::wstring(temp) + L"int3_skip_test_" + std::to_wstring(GetCurrentProcessId()) + L".jsonl"; diff --git a/runtime/test/run_guest_draw.cmake b/runtime/test/run_guest_draw.cmake index b6584e378..a1e45f832 100644 --- a/runtime/test/run_guest_draw.cmake +++ b/runtime/test/run_guest_draw.cmake @@ -1,6 +1,6 @@ -# Runs tiny_guest_draw.exe under `gta6rt --run` (test d3d12_translated_draw_guest in CMakeLists.txt). It passes only if -# gta6rt exits 0 AND the guest printed its marker line, which it does after every pixel check: a loader that returns 0 -# without running the guest to the end, or a guest that prints and then fails, both fail here. CTest's +# Runs tiny_guest_draw.exe under `gta6rt --run` (test d3d12_translated_draw_guest in cmake/d3d12_vulkan.cmake). It +# passes only if gta6rt exits 0 AND the guest printed its marker line, which it does after every pixel check: a loader +# that returns 0 without running the guest to the end, or a guest that prints and then fails, both fail here. CTest's # PASS_REGULAR_EXPRESSION would ignore the exit code, which is why the checks are not test properties. # cmake -DGTA6RT= -DGUEST= -DFIXTURE= [-DTIMEOUT=] # -P run_guest_draw.cmake diff --git a/runtime/test/shaders/cs_buf_counter.asm b/runtime/test/shaders/cs_buf_counter.asm index 4f94e48dd..af5268034 100644 --- a/runtime/test/shaders/cs_buf_counter.asm +++ b/runtime/test/shaders/cs_buf_counter.asm @@ -11,8 +11,8 @@ ; s0 = mode: 0 append, 1 consume s[4:5] = console VA of the table's first slot (32 bytes a slot) ; slot 0 (+0x00): V#, structured buffer, stride 8, 256 records; the counter V# in +0x10 (raw, 4 bytes) ; slot 1 (+0x20): V#, raw buffer, 128 records of 8 bytes (written by consume) -; D3D12 build: runtime/CMakeLists.txt builds this with LEONIDA_USER_DATA_SHIFT=4, so in the PSO every SGPR named -; here is 4 higher (the console compute layout starts the root arguments at s4, D3D-448). The table pointer +; D3D12 build: runtime/cmake/d3d12_vulkan.cmake builds this with LEONIDA_USER_DATA_SHIFT=4, so in the PSO every SGPR +; named here is 4 higher (the console compute layout starts the root arguments at s4, D3D-448). The table pointer ; then reads s[8:9]: s8 is the table's 32-bit VA and s9 a user dword the runtime leaves zero. ; g = 64 * group + lane ; append: i = counter++ (buffer_atomic_add, glc returns the old value); record i = { g, g * 3 + 1 } diff --git a/runtime/test/shaders/cs_buf_typed.asm b/runtime/test/shaders/cs_buf_typed.asm index 7d625cf3c..fc6ac1172 100644 --- a/runtime/test/shaders/cs_buf_typed.asm +++ b/runtime/test/shaders/cs_buf_typed.asm @@ -6,8 +6,8 @@ ; translated `RWBuffer` shader reads and writes them. Run: d3d12_buffer_uav_test (a compute PSO found by the ; SHA-256 of its synthetic FSSM header, as for the other cs_ shaders). ; User data, from the root signature: [0] four 32-bit constants, [1] a descriptor table of six UAVs. RSRC2 0x808c = -; D3D12 build: runtime/CMakeLists.txt builds this with LEONIDA_USER_DATA_SHIFT=4, so in the PSO every SGPR named -; here is 4 higher (the console compute layout starts the root arguments at s4, D3D-448). The table pointer +; D3D12 build: runtime/cmake/d3d12_vulkan.cmake builds this with LEONIDA_USER_DATA_SHIFT=4, so in the PSO every SGPR +; named here is 4 higher (the console compute layout starts the root arguments at s4, D3D-448). The table pointer ; then reads s[8:9]: s8 is the table's 32-bit VA and s9 a user dword the runtime leaves zero. ; six user SGPRs and TGID_X, so the group index is s6: ; s0 = seed s1 = multiplier s[4:5] = console VA of the table's first slot (a slot is 32 bytes, a V# in its first 16) diff --git a/runtime/test/shaders/cs_m4_fill.asm b/runtime/test/shaders/cs_m4_fill.asm index d2f667ef3..76ad114a9 100644 --- a/runtime/test/shaders/cs_m4_fill.asm +++ b/runtime/test/shaders/cs_m4_fill.asm @@ -6,8 +6,8 @@ ; arguments of the next (indirect) dispatch. Run: d3d12_m4_compute_test (a compute PSO found by the SHA-256 of its ; synthetic FSSM header, as for the other cs_ shaders). ; User data, from the root signature: [0] four 32-bit constants, [1] a descriptor table of five UAVs. RSRC2 0x808c = -; D3D12 build: runtime/CMakeLists.txt builds this with LEONIDA_USER_DATA_SHIFT=4, so in the PSO every SGPR named -; here is 4 higher (the console compute layout starts the root arguments at s4, D3D-448). The table pointer +; D3D12 build: runtime/cmake/d3d12_vulkan.cmake builds this with LEONIDA_USER_DATA_SHIFT=4, so in the PSO every SGPR +; named here is 4 higher (the console compute layout starts the root arguments at s4, D3D-448). The table pointer ; then reads s[8:9]: s8 is the table's 32-bit VA and s9 a user dword the runtime leaves zero. ; six user SGPRs and TGID_X, so the group index is s6: ; s0 = seed s1 = multiplier s2 = group count of the indirect dispatch s3 = unused diff --git a/runtime/test/shaders/cs_m4_indirect.asm b/runtime/test/shaders/cs_m4_indirect.asm index d7b961c92..e85a6d4d5 100644 --- a/runtime/test/shaders/cs_m4_indirect.asm +++ b/runtime/test/shaders/cs_m4_indirect.asm @@ -6,8 +6,8 @@ ; structured buffer and the image the first dispatch wrote, and writes a raw output buffer. Run: ; d3d12_m4_compute_test. Same root signature, user data and table as cs_m4_fill (see there): ; slot 0: structured buffer (read) slot 2: R32_UINT image (read, image_load) slot 4: raw output (written) -; D3D12 build: runtime/CMakeLists.txt builds this with LEONIDA_USER_DATA_SHIFT=4, so in the PSO every SGPR named -; here is 4 higher (the console compute layout starts the root arguments at s4, D3D-448). The table pointer +; D3D12 build: runtime/cmake/d3d12_vulkan.cmake builds this with LEONIDA_USER_DATA_SHIFT=4, so in the PSO every SGPR +; named here is 4 higher (the console compute layout starts the root arguments at s4, D3D-448). The table pointer ; then reads s[8:9]: s8 is the table's 32-bit VA and s9 a user dword the runtime leaves zero. ; g = 64 * group + lane; t = image(g & 15, g >> 4); record g = { w0, w1, w2, w3 } ; out[g] = { (w0 + t) ^ w3, (w2 ^ t) + w1 } at byte offset 8 * g diff --git a/runtime/test/vk_xdxr_build_test.cpp b/runtime/test/vk_xdxr_build_test.cpp index a0b3f8b6a..a416a1e4d 100644 --- a/runtime/test/vk_xdxr_build_test.cpp +++ b/runtime/test/vk_xdxr_build_test.cpp @@ -2,7 +2,7 @@ // device the Vulkan loader picks and written to /.bin, the acceleration structure as the GPU left it, // with .json describing the scene: its address and the triangles (or instances) it was built from. // `python -I tools/xdxr_bvh.py check-build ` then validates every structure and traces rays through it -// against brute force (ctest runs both; see CMakeLists.txt). +// against brute force (ctest runs both; see cmake/vulkan_tools.cmake). // // Cases: one triangle; five (two levels); 1000 random triangles; an indexed R16 grid with a 16-byte vertex stride; // R32 indices with R32G32 vertices; a geometry transform; two geometries with an inactive (NaN) triangle; no diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index 6af7ad804..e734efec9 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -11,6 +11,7 @@ // patching this executable's own import table before the first proxy table is built (one process each). // Every device, queue, fence and resource here is a mock that records the calls it gets. No game data, no Xbox DLLs. #include "../shims/d3d12_xs_device.h" +#include "../src/frame_pacer.h" #include #include @@ -891,6 +892,129 @@ int check_xbox_slots() { #endif } +// ---- 7a. A frame-event sink on device slots 78/79/80 ---- +// +// The sink stands in front of a leonida::FramePacer on a clock that only moves when the test moves it, the way the +// presentation class is meant to stand there. Every wait below has its origin behind it or a zero timeout, so +// nothing blocks. The pacer's answers differ from the proxy's own (an interval of 0 is refused, a wait before the +// next origin times out), so each result shows which of the two answered. +struct SinkState { + leonida::FramePacer* pacer; + unsigned calls[3]; // interval, schedule, wait + void* output; // the first word of the last SetFrameIntervalX + std::uint32_t flags[3]; // the flags word of the last call of each kind + std::uint32_t timeout_ms; // of the last wait +}; + +HRESULT sink_set_frame_interval(void* context, void* output, std::uint32_t interval_us, std::uint32_t latency, + std::uint32_t flags) { + auto* state = static_cast(context); + ++state->calls[0]; + state->output = output; + state->flags[0] = flags; + return static_cast(state->pacer->set_frame_interval(interval_us, latency, flags)); +} + +HRESULT sink_schedule_frame_event(void* context, std::uint32_t event, std::uint32_t offset_us, + std::uint32_t flags) { + auto* state = static_cast(context); + ++state->calls[1]; + state->flags[1] = flags; + return static_cast(state->pacer->schedule_frame_event(event, offset_us, flags)); +} + +HRESULT sink_wait_frame_event(void* context, std::uint32_t event, std::uint32_t timeout_ms, std::uint32_t flags, + std::uint64_t* token) { + auto* state = static_cast(context); + ++state->calls[2]; + state->flags[2] = flags; + state->timeout_ms = timeout_ms; + return static_cast(state->pacer->wait_frame_event(event, timeout_ms, flags, token)); +} + +int check_frame_sink() { + constexpr std::uint32_t kPeriod = 16667; + constexpr std::uint64_t kUntouched = 0xfeedfacecafef00dull; + const HRESULT invalid_state = static_cast(leonida::pacer_hr::invalid_state); + const HRESULT timed_out = static_cast(leonida::pacer_hr::timeout); + + Mock* mock = nullptr; + void* device = make_device(mock, 9, true); // 76 PC slots: 78, 79 and 80 are all past the PC table + EXPECT(device && xs::device_frame_event_sink(device) == nullptr); + + // No sink: the proxy answers, and its wait hands a token out at once although nothing is registered. + std::uint64_t own = 0; + EXPECT(hr_of(raw(device, 80, 0, 0, 0, 0, word(&own))) == S_OK && own != 0); + + leonida::ManualFrameClock clock; + leonida::FramePacer pacer(clock); + SinkState state{}; + state.pacer = &pacer; + const xs::FrameEventSink sink{&state, &sink_set_frame_interval, &sink_schedule_frame_event, + &sink_wait_frame_event}; + // Only a device proxy takes a sink: the PC device behind it is refused, and so is a null pointer. + EXPECT(!xs::set_device_frame_event_sink(mock, &sink) && !xs::set_device_frame_event_sink(nullptr, &sink)); + EXPECT(xs::set_device_frame_event_sink(device, &sink) && xs::device_frame_event_sink(device) == &sink); + + // 80 before anything is registered: the pacer's ERROR_INVALID_STATE, and the token is left alone. + std::uint64_t token = kUntouched; + EXPECT(hr_of(raw(device, 80, 0, 0, 0, 0, word(&token))) == invalid_state && token == kUntouched); + EXPECT(state.calls[2] == 1); + + // 78 SetFrameIntervalX(output, interval_us, latency, flags): an interval of 0 is the pacer's E_INVALIDARG (the + // proxy's own answer is S_OK); a valid one sets the pacer's period, and the output and flags words arrive. + EXPECT(hr_of(raw(device, 78, 0x1234, 0, 1, 0)) == E_INVALIDARG); + EXPECT(hr_of(raw(device, 78, 0x1234, kPeriod, 1, 6)) == S_OK); + EXPECT(state.calls[0] == 2 && pacer.period_us() == kPeriod && !pacer.registered()); + EXPECT(state.output == reinterpret_cast(std::uintptr_t{0x1234}) && state.flags[0] == 6); + + // 79 ScheduleFrameEventX(event, offset_us, pEvent, flags): the event is the first word, the offset the second + // and the flags the fourth; the reserved pointer (the third word) is not passed on. + EXPECT(hr_of(raw(device, 79, 7, 0, 0x5678, 0)) == E_INVALIDARG); // not the origin event + EXPECT(hr_of(raw(device, 79, 0, kPeriod, 0x5678, 0)) == E_INVALIDARG); // an offset of a whole period + EXPECT(hr_of(raw(device, 79, 0, 0, 0x5678, 5)) == S_OK); + EXPECT(state.calls[1] == 3 && state.flags[1] == 5 && pacer.registered()); + + // 80 WaitFrameEventX(event, timeout_ms, pEvent, flags, &token) is paced now. Before the first origin a zero + // wait times out and leaves the token alone; once the clock is past the origin the wait returns a token that + // the pacer issued. The timeout is the second word and the flags the fourth. + EXPECT(hr_of(raw(device, 80, 0, 0, 0, 0, word(&token))) == timed_out && token == kUntouched); + clock.advance_us(kPeriod); + EXPECT(hr_of(raw(device, 80, 0, 250, 0x5678, 3, word(&token))) == S_OK && token == 1); + EXPECT(pacer.tokens_issued() == 1 && state.timeout_ms == 250 && state.flags[2] == 3); + + // One token per origin: a second wait in the same interval times out, the next origin gives the next token. + std::uint64_t next = kUntouched; + EXPECT(hr_of(raw(device, 80, 0, 0, 0, 0, word(&next))) == timed_out && next == kUntouched); + clock.advance_us(kPeriod); + EXPECT(hr_of(raw(device, 80, 0, 0, 0, 0, word(&next))) == S_OK && next == 2); + + // A null token pointer is refused by the proxy with E_POINTER, as without a sink; the sink is not called. + const unsigned waits = state.calls[2]; + EXPECT(hr_of(raw(device, 80, 0, 0, 0, 0, 0)) == E_POINTER && state.calls[2] == waits); + // None of the calls reached the PC device. + EXPECT(mock->calls[78] == 0 && mock->calls[79] == 0 && mock->calls[80] == 0); + + // A sink with a null function leaves that call with the proxy: the wait answers at once with a token of the + // proxy's own although the pacer's next origin has not come, and the sink's wait is not called. + const xs::FrameEventSink no_wait{&state, &sink_set_frame_interval, &sink_schedule_frame_event, nullptr}; + EXPECT(xs::set_device_frame_event_sink(device, &no_wait) && xs::device_frame_event_sink(device) == &no_wait); + std::uint64_t unpaced = 0; + EXPECT(hr_of(raw(device, 80, 0, 0, 0, 0, word(&unpaced))) == S_OK && unpaced != 0 && unpaced != own); + EXPECT(state.calls[2] == waits && pacer.tokens_issued() == 2); + + // Without a sink again the proxy answers all three: an interval of 0 is S_OK, as before. + EXPECT(xs::set_device_frame_event_sink(device, nullptr) && xs::device_frame_event_sink(device) == nullptr); + const unsigned intervals = state.calls[0]; + EXPECT(hr_of(raw(device, 78, 0, 0, 1, 0)) == S_OK && state.calls[0] == intervals); + EXPECT(hr_of(raw(device, 80, 0, 0, 0, 0, word(&unpaced))) == S_OK && unpaced != 0); + + EXPECT(release(device) == 0 && mock->refs == 0); + std::printf("%s: a frame-event sink takes device slots 78/79/80 over: the pacer's results and tokens come " + "back and a wait is paced by the clock; without one the proxy answers them itself\n", g_label); + return 0; +} + // ---- 8. Environment overrides for the Xbox device slots (one process each, read once) ---- int run_env_slots(bool valid) { @@ -945,6 +1069,113 @@ int run_env_slots(bool valid) { return 0; } +// ---- 8a. PresentX on the queue: the slot a setting names and the present sink (one process each, read once) ---- +// +// No slot is taken for PresentX by default, so each case sets the variable before the first queue call past the +// public chain. The sink is a function of this test: it records what it gets and returns what the test tells it to. +struct PresentState { + unsigned calls; + ID3D12CommandQueue* queue; + std::uint32_t plane_count; + const void* planes; + const void* params; + HRESULT result; +}; + +HRESULT sink_present_x(void* context, ID3D12CommandQueue* queue, std::uint32_t plane_count, const void* planes, + const void* params) { + auto* state = static_cast(context); + ++state->calls; + state->queue = queue; + state->plane_count = plane_count; + state->planes = planes; + state->params = params; + return state->result; +} + +int run_present_slot(bool valid) { + constexpr unsigned kSlot = 32; + // 18 is GetDesc, the last public slot: not a slot of the refused tail, so the setting is ignored. + EXPECT(SetEnvironmentVariableA("LEONIDA_XS_PRESENT_X_SLOT", valid ? "32" : "18") != FALSE); + + Mock* mock = nullptr; + void* device = make_device(mock, 9, true); + EXPECT(device && xs::device_present_sink(device) == nullptr); + void* queue = make_queue(device); // made before a sink is set + EXPECT(queue); + Mock* const queue_mock = reinterpret_cast(xs::queue_proxy_real_queue(queue)); + xs::reset_device_proxy_stats(); + + PresentState state{}; + const xs::PresentSink sink{&state, &sink_present_x}; + const std::uint64_t planes[2] = {}, params[1] = {}; + + if (!valid) { + // No slot is taken: with a sink set, the whole tail is still refused and the sink is never called. + EXPECT(xs::queue_present_x_slot() == 0); + EXPECT(xs::set_device_present_sink(device, &sink)); + for (unsigned slot = 19; slot < xs::queue_proxy_table_size(); ++slot) + EXPECT(hr_of(raw(queue, slot, 1, word(planes), word(params))) == E_NOTIMPL && + queue_mock->calls[slot] == 0); + EXPECT(state.calls == 0); + // GetDesc (18) keeps its PC method. + EXPECT(hr_of(raw(queue, 18)) == S_OK && queue_mock->calls[18] == 1); + EXPECT(xs::set_device_present_sink(device, nullptr)); + EXPECT(release(queue) == 0 && release(device) == 0 && mock->refs == 0); + std::printf("%s: a PresentX slot outside 19..127 is ignored: no slot is taken and the tail is refused\n", + g_label); + return 0; + } + + EXPECT(xs::queue_present_x_slot() == kSlot); + // No sink yet: the call is refused and the real queue is not called. + EXPECT(hr_of(raw(queue, kSlot, 1, word(planes), word(params))) == E_NOTIMPL && queue_mock->calls[kSlot] == 0); + + // Only a device proxy takes a sink: the PC device behind it is refused, and so is a null pointer. + EXPECT(!xs::set_device_present_sink(mock, &sink) && !xs::set_device_present_sink(nullptr, &sink)); + EXPECT(xs::set_device_present_sink(device, &sink) && xs::device_present_sink(device) == &sink); + + // PresentX(plane count, planes, parameters): the sink gets the real queue behind the proxy and the three words. + // The count is a UINT, so only the low half of its word arrives. + state.result = S_OK; + EXPECT(hr_of(raw(queue, kSlot, 0xdeadbeef00000002ull, word(planes), word(params))) == S_OK); + EXPECT(state.calls == 1 && state.queue == xs::queue_proxy_real_queue(queue) && state.plane_count == 2); + EXPECT(state.planes == planes && state.params == params); + // The sink's result is the title's, a failure too; null planes and parameters are passed on as they are. + const HRESULT refused = static_cast(0x887A0004); // DXGI_ERROR_UNSUPPORTED + state.result = refused; + EXPECT(hr_of(raw(queue, kSlot, 0, 0, 0)) == refused); + EXPECT(state.calls == 2 && state.plane_count == 0 && !state.planes && !state.params); + EXPECT(queue_mock->calls[kSlot] == 0 && xs::queue_slot_hits(kSlot) == 3 && + xs::queue_slot_first_call_seen(kSlot)); + + // Only the named slot is PresentX: 30, the other public number, is refused like the rest of the tail, and + // GetDesc (18) keeps its PC method. + EXPECT(hr_of(raw(queue, 30, 1, word(planes), word(params))) == E_NOTIMPL && state.calls == 2); + EXPECT(queue_mock->calls[30] == 0); + EXPECT(hr_of(raw(queue, 18)) == S_OK && queue_mock->calls[18] == 1); + + // A queue made after the sink was set reaches the same sink, with its own real queue. + void* later = make_queue(device); + EXPECT(later && later != queue); + state.result = S_OK; + EXPECT(hr_of(raw(later, kSlot, 1, word(planes), 0)) == S_OK); + EXPECT(state.calls == 3 && state.queue == xs::queue_proxy_real_queue(later) && state.plane_count == 1); + EXPECT(state.queue != xs::queue_proxy_real_queue(queue)); + + // A sink with a null function, and no sink again: refused, and the test's function is not called. + const xs::PresentSink empty{&state, nullptr}; + EXPECT(xs::set_device_present_sink(device, &empty) && xs::device_present_sink(device) == &empty); + EXPECT(hr_of(raw(queue, kSlot, 1, word(planes), 0)) == E_NOTIMPL && state.calls == 3); + EXPECT(xs::set_device_present_sink(device, nullptr) && xs::device_present_sink(device) == nullptr); + EXPECT(hr_of(raw(queue, kSlot, 1, word(planes), 0)) == E_NOTIMPL && state.calls == 3); + + EXPECT(release(later) == 0 && release(queue) == 0 && release(device) == 0 && mock->refs == 0); + std::printf("%s: queue slot %u, named by the setting, reaches the device's present sink with the real queue and " + "the title's words; without a sink it is refused\n", g_label, kSlot); + return 0; +} + // ---- 9. The refused tail and the guard region ---- int check_tail(bool want_guarded) { @@ -1245,11 +1476,14 @@ int main(int argc, char** argv) { if (argc == 2) { if (std::strcmp(argv[1], "--env-slots") == 0) return run_env_slots(true); if (std::strcmp(argv[1], "--env-slots-invalid") == 0) return run_env_slots(false); + if (std::strcmp(argv[1], "--present-slot") == 0) return run_present_slot(true); + if (std::strcmp(argv[1], "--present-slot-invalid") == 0) return run_present_slot(false); return run_fault_mode(argv[1]); } if (argc != 1) return 2; if (check_tail(true) || check_levels() || check_fence1() || check_create_failures() || check_open_shared() || - check_alloc_failures() || check_allocators() || check_xbox_slots() || check_console_command_list()) + check_alloc_failures() || check_allocators() || check_xbox_slots() || check_frame_sink() || + check_console_command_list()) return 1; std::printf("xs_proxy_mock_test: PASS (%d allocations refused on purpose)\n", g_failed_news); return 0; diff --git a/scripts/build_runtime.ps1 b/scripts/build_runtime.ps1 index 8bd74d1cf..74223638e 100644 --- a/scripts/build_runtime.ps1 +++ b/scripts/build_runtime.ps1 @@ -76,25 +76,27 @@ $configure || exit /b 1 $build || exit /b 1 "@ } else { - # Keep this list in step with runtime\CMakeLists.txt. Optional parts that need a dependency are left out here: + # Keep this list in step with runtime\cmake\windows_runtime.cmake. Parts that need a dependency are left out here: # the GameInput shim (SDL3), so controllers go through the host's GameInput.dll, if any, as without the shim. Write-Warning "CMake and Ninja weren't found (neither VS C++ CMake tools nor native PATH tools): building with cl.exe directly, without the GameInput shim (SDL3). Install CMake + Ninja or VS's CMake tools component to get it." $xtaskqueueDir = Join-Path $root "third_party\xtaskqueue" $xtaskqueueFiles = "Source\Task\TaskQueue.cpp", "Source\Task\AsyncLib.cpp", "Source\Task\ThreadPool_win32.cpp", "Source\Task\WaitTimer_win32.cpp" | ForEach-Object { "`"$xtaskqueueDir\$_`"" } - $files = "src\main.cpp", "src\host_cpu.cpp", "src\pe_loader.cpp", "shims\registry.cpp", "shims\file_system.cpp", "shims\xmem.cpp", "shims\xg_xs.cpp", "shims\acphal.cpp", "shims\d3d12_xs.cpp", "shims\d3d12_xs_device.cpp", "shims\d3d12_xs_rootsig.cpp", "shims\xgameruntime.cpp", "shims\xgameruntime_user.cpp", "shims\xgameruntime_gamesave.cpp", "shims\xgameruntime_store.cpp", "shims\xgameruntime_offline.cpp", "shims\winhttp_offline.cpp", "shims\library_loader.cpp", "shims\process.cpp", "shims\com_shim.cpp", "shims\bcrypt_rng.cpp", "shims\xapu_chad.cpp", "shims\dstorage.cpp" | ForEach-Object { "`"$src\$_`"" } + $files = "src\main.cpp", "core\config.cpp", "core\log.cpp", "src\host_cpu.cpp", "src\pe_loader.cpp", "shims\registry.cpp", "shims\file_system.cpp", "shims\xmem.cpp", "shims\xg_xs.cpp", "shims\acphal.cpp", "shims\d3d12_xs.cpp", "shims\d3d12_xs_device.cpp", "shims\d3d12_xs_rootsig.cpp", "shims\xgameruntime.cpp", "shims\xgameruntime_user.cpp", "shims\xgameruntime_gamesave.cpp", "shims\xgameruntime_store.cpp", "shims\xgameruntime_offline.cpp", "shims\winhttp_offline.cpp", "shims\library_loader.cpp", "shims\process.cpp", "shims\com_shim.cpp", "shims\bcrypt_rng.cpp", "shims\xapu_chad.cpp", "shims\dstorage.cpp" | ForEach-Object { "`"$src\$_`"" } $includes = "/I `"$src\src`" /I `"$src\shims`" /I `"$src\shims\xtaskqueue`" /I `"$xtaskqueueDir\Include`" /I `"$xtaskqueueDir\Source\Task`" /I `"$xtaskqueueDir\Source\Common`"" $opt = if ($Debug) { "/Od /MDd" } else { "/O2 /MD" } $body = @" cd /d "$out" || exit /b 1 -rem BUILD-1457: a game thread with the default stack size gets this program's reserve, and drivers compile on it. The same number as in CMakeLists.txt. -rem Keep the host base in step with runtime\CMakeLists.txt GTA6RT_HOST_BASE. +rem BUILD-1457: a game thread with the default stack size gets this program's reserve, and drivers compile on it. +rem The same number as in cmake\windows_runtime.cmake. +rem Keep the host base in step with runtime\cmake\windows_runtime.cmake GTA6RT_HOST_BASE. cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /Zi $opt /MP$jobs /DWIN32_LEAN_AND_MEAN /DNOMINMAX /DUNICODE /D_UNICODE $includes $($files -join ' ') $($xtaskqueueFiles -join ' ') /Fe:gta6rt.exe /link /OPT:NOREF /BASE:0x10000000000 /STACK:8388608 psapi.lib ole32.lib || exit /b 1 cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /MT /DWIN32_LEAN_AND_MEAN /DNOMINMAX "$src\src\tls_host.cpp" /LD /Fe:gta6rt_tls_host.dll || exit /b 1 -cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "$src\shims" "$src\shims\d3d12_xs_rootsig.cpp" "$src\shims\registry.cpp" "$src\shims\d3d12_xs.cpp" "$src\shims\d3d12_xs_device.cpp" "$src\test\root_sig_test.cpp" /Fe:root_sig_test.exe /link d3d12.lib || exit /b 1 -cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "$src\shims" "$src\shims\d3d12_xs_rootsig.cpp" "$src\shims\registry.cpp" "$src\shims\d3d12_xs.cpp" "$src\shims\d3d12_xs_device.cpp" "$src\test\device_proxy_test.cpp" /Fe:device_proxy_test.exe /link d3d12.lib dxgi.lib || exit /b 1 +cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "$src\shims" "$src\core\config.cpp" "$src\shims\d3d12_xs_rootsig.cpp" "$src\shims\registry.cpp" "$src\shims\d3d12_xs.cpp" "$src\shims\d3d12_xs_device.cpp" "$src\test\root_sig_test.cpp" /Fe:root_sig_test.exe /link d3d12.lib || exit /b 1 +cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "$src\shims" "$src\core\config.cpp" "$src\shims\d3d12_xs_rootsig.cpp" "$src\shims\registry.cpp" "$src\shims\d3d12_xs.cpp" "$src\shims\d3d12_xs_device.cpp" "$src\test\device_proxy_test.cpp" /Fe:device_proxy_test.exe /link d3d12.lib dxgi.lib || exit /b 1 cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "$src\src" "$src\test\descriptor_table_test.cpp" /Fe:descriptor_table_test.exe /link /OPT:NOREF || exit /b 1 cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "$src\src" "$src\test\command_list_test.cpp" /Fe:command_list_test.exe /link /OPT:NOREF || exit /b 1 -rem BUILD-1457: drivers compile on the checker's threads, and 1 MB of stack is too little for AMD's. The same number as in CMakeLists.txt. +rem BUILD-1457: drivers compile on the checker's threads, and 1 MB of stack is too little for AMD's. +rem The same number as in cmake\vulkan_tools.cmake. if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" "$src\test\vk_pipeline_check.cpp" /Fe:vk_pipeline_check.exe /link /STACK:8388608 || exit /b 1 if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" /I "$src\src" "$src\test\vk_texture_test.cpp" /Fe:vk_texture_test.exe || exit /b 1 if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" /I "$src\src" "$src\test\vk_sampler_test.cpp" /Fe:vk_sampler_test.exe || exit /b 1 diff --git a/scripts/first_look.ps1 b/scripts/first_look.ps1 index 6fb7ca36b..e269a4dac 100644 --- a/scripts/first_look.ps1 +++ b/scripts/first_look.ps1 @@ -55,7 +55,8 @@ $folders = @("") + $configs $rt = Find-RuntimeLoader $build $folders # A gta6rt.exe older than the runtime sources (a pull since the last build) would report the old shim table, so it # is rebuilt then too, not only when missing. -$sources = @("runtime\src", "runtime\shims", "runtime\CMakeLists.txt") | ForEach-Object { Join-Path $root $_ } | +$sources = @("runtime\src", "runtime\shims", "runtime\CMakeLists.txt", "runtime\cmake") | + ForEach-Object { Join-Path $root $_ } | Where-Object { Test-Path -LiteralPath $_ } $newest = $sources | ForEach-Object { Get-ChildItem -LiteralPath $_ -Recurse -File -ErrorAction SilentlyContinue } | Sort-Object LastWriteTimeUtc -Descending | Select-Object -First 1 diff --git a/tests/runtime_cmake.py b/tests/runtime_cmake.py new file mode 100644 index 000000000..834400f48 --- /dev/null +++ b/tests/runtime_cmake.py @@ -0,0 +1,28 @@ +"""runtime/CMakeLists.txt as one text, for the tests that check the build by reading it. + +The build file keeps its large blocks in runtime/cmake/*.cmake and includes them. ``read()`` puts the text of each +included file after its include() line, indented like that line, so a test sees every target and every add_test() of +the build in the order CMake reads them. +""" +import re +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +CMAKE_LISTS = ROOT / "runtime" / "CMakeLists.txt" + +_INCLUDE = re.compile(r'^([ \t]*)include\("\$\{CMAKE_CURRENT_SOURCE_DIR\}/(cmake/[A-Za-z0-9_.-]+\.cmake)"\)[ \t]*$') + + +def read(path=CMAKE_LISTS): + """The text of ``path`` with the file of every ``include("${CMAKE_CURRENT_SOURCE_DIR}/cmake/.cmake")`` line + inserted after that line. Included files are looked up next to ``path`` and are not expanded themselves; one that + does not exist is an error.""" + path = Path(path) + out = [] + for line in path.read_text(encoding="utf-8").splitlines(): + out.append(line) + include = _INCLUDE.match(line) + if include: + indent, part = include.group(1), path.parent / include.group(2) + out.extend(indent + inner if inner else "" for inner in part.read_text(encoding="utf-8").splitlines()) + return "\n".join(out) + "\n" diff --git a/tests/test_acphal_abi.py b/tests/test_acphal_abi.py index 828b95021..822df4e04 100644 --- a/tests/test_acphal_abi.py +++ b/tests/test_acphal_abi.py @@ -8,6 +8,8 @@ import unittest ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(ROOT, "tests")) +import runtime_cmake # noqa: E402 class TestAcpHalAbi(unittest.TestCase): @@ -92,8 +94,7 @@ def test_registry_classifies_acphal_hresult(self): def test_cmakelists_and_fallback_register_acphal(self): """CMakeLists.txt and build_runtime.ps1 must both register acphal.cpp in gta6rt.""" - with open(self.cmakelists, "r", encoding="utf-8") as f: - cmake = f.read() + cmake = runtime_cmake.read(self.cmakelists) self.assertIn("shims/acphal.cpp", cmake) self.assertIn("add_executable(acphal_test", cmake) self.assertIn("add_test(NAME acphal COMMAND acphal_test)", cmake) diff --git a/tests/test_build_runtime_fallback.py b/tests/test_build_runtime_fallback.py index 236afe91b..9ea2b4099 100644 --- a/tests/test_build_runtime_fallback.py +++ b/tests/test_build_runtime_fallback.py @@ -14,10 +14,12 @@ import unittest ROOT = Path(__file__).resolve().parents[1] -sys.path[:0] = [str(ROOT / "scripts"), str(ROOT / "runtime" / "test" / "shaders"), str(ROOT / "tools")] +sys.path[:0] = [str(ROOT / "scripts"), str(ROOT / "runtime" / "test" / "shaders"), str(ROOT / "tools"), + str(ROOT / "tests")] import check # noqa: E402 import image_fuzz # noqa: E402 import run_gpu_tests # noqa: E402 +import runtime_cmake # noqa: E402 SCRIPT = ROOT / "scripts" / "build_runtime.ps1" @@ -63,7 +65,7 @@ def test_the_fallback_builds_every_harness_a_tool_starts(self): def test_the_launcher_compiles_every_source_cmake_gives_gta6rt(self): """BUILD-680: main.cpp calls rt::fs::configure, but the fallback left out shims/file_system.cpp (LNK2019). Every source of CMake's add_executable(gta6rt ...) must be in the fallback's launcher list ($files).""" - cmake = (ROOT / "runtime" / "CMakeLists.txt").read_text(encoding="utf-8") + cmake = runtime_cmake.read() block = re.search(r"add_executable\(gta6rt\s+(.*?)\)", cmake, re.S).group(1) wanted = {item.replace("/", "\\") for item in block.split() if item.endswith(".cpp")} files = re.search(r"\$files = (.*?) \| ForEach-Object", self.body).group(1) @@ -82,7 +84,7 @@ def test_the_pipeline_checker_gets_the_stack_reserve_cmake_gives_it(self): """BUILD-1457: a driver compiles on vk_pipeline_check's threads, and AMD's Windows compiler overflows the 1 MB PE default. CMake links the checker with /STACK:; the fallback has to pass the same number on the checker's own cl line (a /link option applies to that one program).""" - cmake = (ROOT / "runtime" / "CMakeLists.txt").read_text(encoding="utf-8") + cmake = runtime_cmake.read() reserve = re.search(r"set\(LEONIDA_PIPELINE_CHECK_STACK (\d+)\)", cmake).group(1) self.assertGreaterEqual(int(reserve), 8 * 1024 * 1024) self.assertIn("target_link_options(vk_pipeline_check PRIVATE /STACK:${LEONIDA_PIPELINE_CHECK_STACK})", cmake) @@ -95,7 +97,7 @@ def test_the_loader_gets_the_stack_reserve_cmake_gives_it(self): header, and the driver compiles a pipeline's shaders on the thread that creates it. CMake links gta6rt with /STACK:; the fallback has to pass the same number, and it is the number run_entry gives the entry thread, so every game thread that asks for no size has the same room.""" - cmake = (ROOT / "runtime" / "CMakeLists.txt").read_text(encoding="utf-8") + cmake = runtime_cmake.read() reserve = re.search(r"set\(GTA6RT_STACK (\d+)\)", cmake).group(1) self.assertGreaterEqual(int(reserve), 8 * 1024 * 1024) self.assertRegex(cmake, r"target_link_options\(gta6rt PRIVATE [^)]*/STACK:\$\{GTA6RT_STACK\}\)") @@ -107,7 +109,7 @@ def test_the_loader_gets_the_stack_reserve_cmake_gives_it(self): self.assertEqual(int(megabytes) << 20, int(reserve)) def test_the_loader_gets_the_host_base_cmake_gives_it(self): - cmake = (ROOT / "runtime" / "CMakeLists.txt").read_text(encoding="utf-8") + cmake = runtime_cmake.read() base = re.search(r"set\(GTA6RT_HOST_BASE (/BASE:0x[0-9A-Fa-f]+)\)", cmake).group(1) self.assertRegex(cmake, r"target_link_options\(gta6rt PRIVATE [^)]*\$\{GTA6RT_HOST_BASE\}") lines = [line for line in self.body.splitlines() if "/Fe:gta6rt.exe" in line] diff --git a/tests/test_check_sparse_queue_family.py b/tests/test_check_sparse_queue_family.py index 630b8bbfb..98ae4f87f 100644 --- a/tests/test_check_sparse_queue_family.py +++ b/tests/test_check_sparse_queue_family.py @@ -21,6 +21,9 @@ from unittest import mock ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tests")) +import runtime_cmake # noqa: E402 + SPEC = importlib.util.spec_from_file_location("check_sparse_queue_family", ROOT / "runtime" / "test" / "check_sparse_queue_family.py") checker = importlib.util.module_from_spec(SPEC) @@ -201,7 +204,7 @@ def fake_run(argv, cwd, env, **kwargs): self.assertEqual(self.run_main(fake_run), 0) def test_both_runs_fit_the_ctest_timeout(self) -> None: - cmake = (ROOT / "runtime" / "CMakeLists.txt").read_text(encoding="utf-8") + cmake = runtime_cmake.read() limit = re.search(r"d3d12_sparse_queue_family_contract PROPERTIES[^)]*TIMEOUT (\d+)", cmake) self.assertIsNotNone(limit) self.assertLess(2 * checker.RUN_TIMEOUT, int(limit.group(1))) diff --git a/tests/test_cmake_translator_deps.py b/tests/test_cmake_translator_deps.py index 32ecb40b1..00efc84d0 100644 --- a/tests/test_cmake_translator_deps.py +++ b/tests/test_cmake_translator_deps.py @@ -16,8 +16,9 @@ from pathlib import Path ROOT = Path(__file__).resolve().parent.parent -sys.path.insert(0, str(ROOT)) +sys.path[:0] = [str(ROOT), str(ROOT / "tests")] import make_game # noqa: E402 +import runtime_cmake # noqa: E402 TOOLS = ROOT / "tools" SHADERS = ROOT / "runtime" / "test" / "shaders" @@ -73,7 +74,7 @@ def test_the_helpers_that_went_stale_are_listed(self): self.assertIn(name, listed()) def test_every_build_py_rule_depends_on_the_list(self): - text = CMAKE_LISTS.read_text(encoding="utf-8") + text = runtime_cmake.read(CMAKE_LISTS) rules = [m.group(0) for m in re.finditer(r"add_custom_command\((?:[^()]|\$<[^>]*>|\([^()]*\))*\)", text) if "test/shaders/build.py" in m.group(0)] self.assertGreaterEqual(len(rules), 8) diff --git a/tests/test_ctest_registration.py b/tests/test_ctest_registration.py index 037e4988a..583703baa 100644 --- a/tests/test_ctest_registration.py +++ b/tests/test_ctest_registration.py @@ -3,14 +3,18 @@ ``add_executable(foo_test ...)`` without an ``add_test(... COMMAND foo_test)`` builds the test but never runs it -- in ``ctest``, in the Windows runtime job or under Wine. This happened to ``d3d12_indirect_rt_test``; the only intentional exception is -``d3d12_clear_test`` (see the comment next to its target in runtime/CMakeLists.txt). +``d3d12_clear_test`` (see the comment next to its target in runtime/cmake/d3d12_vulkan.cmake). """ import os import re +import sys import unittest from pathlib import Path ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT / "tests")) +import runtime_cmake # noqa: E402 + CMAKE = Path(os.environ.get("LEONIDA_RUNTIME_CMAKE", str(ROOT / "runtime" / "CMakeLists.txt"))) SOURCE = Path(os.environ.get("LEONIDA_RUNTIME_TEST_SOURCE", str(ROOT / "runtime" / "test" / "d3d12_indirect_rt_test.cpp"))) @@ -32,7 +36,7 @@ def registered_commands(text): class CTestRegistrationTest(unittest.TestCase): @classmethod def setUpClass(cls): - cls.cmake = CMAKE.read_text(encoding="utf-8") + cls.cmake = runtime_cmake.read(CMAKE) def test_all_test_executables_have_an_add_test(self): missing = built_test_executables(self.cmake) - registered_commands(self.cmake) - NOT_IN_CTEST diff --git a/tests/test_docs_env_vars.py b/tests/test_docs_env_vars.py index a22c9729e..7217d0b1f 100644 --- a/tests/test_docs_env_vars.py +++ b/tests/test_docs_env_vars.py @@ -4,8 +4,8 @@ `runtime/README.md` documents the runtime's variables one by one, but five that the `xgameruntime` shim reads (`LEONIDA_DEVICE_TYPE` and four more) were in no document at all. This collects the variable names that appear as -string literals in `runtime/src`, `runtime/shims` and `make_game.py` and checks that each is written in some -tracked Markdown file. Sources and Markdown only: no build, no GPU, no game files. +string literals in `runtime/core`, `runtime/src`, `runtime/shims` and `make_game.py` and checks that each is written +in some tracked Markdown file. Sources and Markdown only: no build, no GPU, no game files. """ import os import re @@ -15,7 +15,7 @@ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # A variable name as a string literal: "LEONIDA_X", L"LEONIDA_X" or 'LEONIDA_X'. LITERAL = re.compile(r"""["']((?:LEONIDA|GTA6RT)_[A-Z0-9_]+)["']""") -CODE = ("runtime/src/", "runtime/shims/", "make_game.py") +CODE = ("runtime/core/", "runtime/src/", "runtime/shims/", "make_game.py") # Set by the runtime for itself, not by a person: gta6rt passes the first to the copy of itself it starts with the # image base reserved (runtime/src/base_reservation.h), and the second is a name that is only looked up to make # the CRT build its environment table (runtime/shims/process.cpp). diff --git a/tools/gen_d3d12_stubs.py b/tools/gen_d3d12_stubs.py index ad3aa9ef5..fccdf4510 100644 --- a/tools/gen_d3d12_stubs.py +++ b/tools/gen_d3d12_stubs.py @@ -4,7 +4,7 @@ its chain (except IUnknown's) with a body that reports the call once through rt::d3d12::stub() and returns E_NOTIMPL, nothing or a value-initialised result. The runtime's COM objects derive from these and override the methods they implement, so their vtables have exactly the SDK's method order and the compiler rejects a missing -method. Run at build time (runtime/CMakeLists.txt); the output is not checked in. +method. Run at build time (runtime/cmake/d3d12_vulkan.cmake); the output is not checked in. python -I tools/gen_d3d12_stubs.py --out [--header ] Interface [Interface ...] python -I tools/gen_d3d12_stubs.py --report --source ... [--header ] Interface ...