Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 49 additions & 4 deletions docs/d3d12_vulkan.md
Original file line number Diff line number Diff line change
Expand Up @@ -1067,8 +1067,52 @@ The compute path, end to end:
- **Buffers:** vertex and index views resolve to buffers by VA (arena or upload). A view that runs past its
buffer is cut at the buffer's end. An unbound vertex slot, or an indexed draw with no index buffer, reads the
arena's reserved first 64 KiB, which is kept zero (stride 0), so it gets the zeros D3D12 gives.
- **Attachments:** they move to attachment layouts through the tracker, and the draw runs in a
dynamic-rendering scope. Its layer count is the smallest layer count of the bound views.
- **Attachments:** they move to attachment layouts through the tracker. Consecutive resolved direct draws share
a dynamic-rendering scope when the prepared graphics pipeline, attachment slots/images/views/ranges/layouts,
render area and layer count match. Its layer count is the smallest layer count of the bound views. Every other
command, skipped draw, indirect draw, statistics segment endpoint or GPU helper closes the scope first. Each
draw still binds its own state and push constants; only redundant attachment dependencies and scope boundaries
are removed (D3D-REPLAY-DRAW-SCOPE-RUNS). Vulkan guarantees fixed-function depth/stencil/blend ordering in
[rasterization order](https://docs.vulkan.org/spec/latest/chapters/primsrast.html#primsrast-order) within the
scope. `replay_rendering_scope_test` checks the boundaries with CPU mocks; `vk_rendering_scope_test` checks
overlapping depth-tested and blended draws against independently calculated pixels and offers `--bench` for
CPU replay and GPU/frame timings, without game files.
Build `vk_rendering_scope_test` with CMake and run it once with `LEONIDA_VK_VALIDATION=1` for correctness,
then without validation with `--bench` for timings. It compares 1,000/10,000 draws in compatible runs of
1/4/16/64/all draws separated by global UAV barriers. Preparation and pipeline creation are outside the
measurements; `emit_ms` measures Vulkan command recording, `gpu_ms` brackets replay after draining the clears,
and `frame_ms` includes recording, submission, readback and waiting for GPU completion. Those are serialized
synthetic frame costs, not the game's FPS. Timings have no pass/fail threshold.
`--bench-mixed` adds runs of 2/3 draws split by UAV barriers, actual pipeline switches or color/depth target
switches, and direct runs interrupted by a single indirect draw. Its mixed case repeats 12 draw commands:
2 direct, switch pipeline, 3 direct, switch targets, 2 direct, 1 indirect, 3 direct, barrier, 1 direct;
a barrier separates repetitions. Both target pairs are checked against independent pixel/depth expectations.
The default correctness run also covers this mixed case. Indirect/mixed cases print `SKIP` on a device
without `drawIndirectFirstInstance`; barrier/pipeline/target benchmarks still run. The fixture uses a
hand-written triangle and is not evidence of the frequency of compatible runs in a retail workload.

`LEONIDA_RENDERING_SCOPE_STATS=1` enables aggregate-only scope diagnostics (D3D-REPLAY-SCOPE-METRICS).
The default emitter has no per-draw counter updates; a cached environment check selects an instrumented
template once per emitted list, including when device-fault checkpoints are enabled. The instrumented
emitter accumulates locally and merges once per list under a process-wide lock. Reports appear at 1/2/4/8/...
emitted lists and at normal exit if the totals have changed; abnormal termination can leave a partial report.
No identities, addresses, shader contents or title text are recorded.

- `draws` counts non-skipped application draw commands reaching emission, including indirect commands, each
counted once irrespective of GPU arguments or quad expansion. `skipped` counts dropped stateful draw
commands separately. `indirect` is a subset of `draws`; `eligible` counts direct commands allowed to carry a
scope forward (no skip, indirect arguments, helper or statistics segment endpoint).
- `scopes` counts application draw rendering scopes, excluding scopes owned by clears and other helpers.
`shared_draws = draws - scopes` counts avoided per-draw scope pairs. `max_run` is the largest number of
application draw commands in a scope; `runs` bins scopes at 1/2/3/4–7/8–15/16–63/64–255/256+ commands.
- `ends` assigns exactly one reason to each closed draw scope. For an ineligible draw the first applicable
reason is skipped/indirect/helper/statistics; otherwise pipeline identity precedes attachment/area/layer
changes. Non-draw commands use barrier/copy/clear/query/predicate/dispatch/label/other. An isolated indirect
or helper draw can end both its preceding run and its own singleton scope, so reasons count scope ends,
rather than boundary commands. `list_end` closes any remaining scope.
- Totals count CPU replay attempts across all queues, including re-emitted lists and work that later fails
to submit or complete. They measure reuse opportunities, not completed GPU draws, frame time or retail FPS.
Disable the counters and validation when collecting benchmark timings.
- **Viewport:** it is flipped (negative height), because translated vertex shaders write D3D clip coordinates;
front-face winding then matches D3D12's.
- Only the first viewport and scissor are used, and primitive restart is not modelled yet.
Expand Down Expand Up @@ -3650,8 +3694,9 @@ mapped stages/accesses, and if no single layout serves all uses, use `GENERAL` a
- Render passes: `BeginRenderPass`/`EndRenderPass` map to `vkCmdBeginRendering`/`vkCmdEndRendering` (dynamic
rendering). The `D3D12_RENDER_PASS_BEGINNING_ACCESS`/`ENDING_ACCESS` types give the load/store ops and resolve
targets. Suspending/resuming passes have no direct Vulkan equivalent; split them into two rendering scopes with
the same attachments and `LOAD`/`STORE`. If the game does not use render passes, build a rendering scope per draw
from the bound RTVs/DSV and let explicit `Clear*View` calls do the clears.
the same attachments and `LOAD`/`STORE`. Draws recorded outside explicit render passes use the bound RTVs/DSV
with `LOAD`/`STORE`; consecutive compatible direct draws share a scope as described in section 3.2.
Explicit `Clear*View` calls still do the clears and end any preceding draw scope.

### 4.4 Fences, queues and frames in flight

Expand Down
14 changes: 12 additions & 2 deletions runtime/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1993,6 +1993,7 @@ if(TARGET Vulkan::Headers)
endif()

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_rendering_scope_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 vk_console_heap_gpu_test)
add_executable(${tool} test/${tool}.cpp)
Expand Down Expand Up @@ -2079,10 +2080,10 @@ if(TARGET Vulkan::Headers)
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).
# Self-checking Vulkan tests with synthetic inputs; each exits 77 without a Vulkan device (TEST-514).
# indirect_clamp is registered next to its own add_executable above, where tests/test_ctest_registration.py
# can see it.
foreach(test vk_command_replay vk_predicated_copy vk_predicate_capture vk_queue vk_console_heap_gpu)
foreach(test vk_command_replay vk_predicated_copy vk_predicate_capture vk_queue vk_console_heap_gpu vk_rendering_scope)
add_test(NAME ${test} COMMAND ${test}_test)
set_tests_properties(${test} PROPERTIES SKIP_RETURN_CODE 77)
endforeach()
Expand Down Expand Up @@ -4660,6 +4661,15 @@ if(TARGET Vulkan::Headers)
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)
# Compatible direct draws share rendering; all non-draw/helper/query boundaries close it (no GPU or game data).
add_executable(replay_rendering_scope_test test/replay_rendering_scope_test.cpp)
target_link_libraries(replay_rendering_scope_test PRIVATE Vulkan::Headers)
if(WIN32)
target_compile_definitions(replay_rendering_scope_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
endif()
add_test(NAME replay_rendering_scope COMMAND replay_rendering_scope_test)
add_test(NAME replay_rendering_scope_stats COMMAND replay_rendering_scope_test)
set_tests_properties(replay_rendering_scope_stats PROPERTIES ENVIRONMENT "LEONIDA_RENDERING_SCOPE_STATS=1")
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)
Expand Down
1 change: 1 addition & 0 deletions runtime/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,7 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w

| variable | default | what it changes |
|---|---|---|
| `LEONIDA_RENDERING_SCOPE_STATS` | unset | *Diagnostic.* Exactly `1` enables aggregate draw rendering-scope counters in `src/vulkan_replay.h`: emitted/eligible/indirect/skipped draw commands, scopes, shared draws, run-length histogram and scope-end reasons. Counts are cumulative replay attempts, including repeated lists, rather than completed GPU work or FPS. Reports contain fixed labels and totals only, at powers of two emitted lists and normal exit. See [section 3.2](../docs/d3d12_vulkan.md#32-record-and-replay) for definitions. |
| `LEONIDA_LAZY_PIPELINES` | on | Graphics pipelines are built at their first draw. `0` builds each at `CreatePipelineState`, as before; the title creates far more pipelines at startup than it draws with. |
| `LEONIDA_LAZY_COMPUTE` | on | Compute pipelines are built at the first dispatch that names them, or earlier by the warm-up thread. `0` builds each at `CreateComputePipelineState`. |
| `LEONIDA_COMPUTE_WARMUP_MAX_BYTES` | `1048576` | The largest SPIR-V module, in bytes, the background warm-up thread (`LEONIDA_COMPUTE_WARMUP`) builds ahead of its first dispatch. Larger modules wait for that dispatch. |
Expand Down
87 changes: 87 additions & 0 deletions runtime/src/rendering_scope_stats.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
// Opt-in, aggregate-only diagnostics for application draw rendering scopes. No resource or shader identities.
#pragma once
#include <algorithm>
#include <array>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <mutex>

namespace leonida::scope_stats {
enum class End { pipeline, attachments, barrier, copy, clear, query, predicate, dispatch, label,
indirect, skipped, helper, statistics, other, list_end, count };
inline constexpr std::array end_names{"pipeline", "attachments", "barrier", "copy", "clear", "query", "predicate",
"dispatch", "label", "indirect", "skipped", "helper", "statistics", "other", "list_end"};
static_assert(end_names.size() == static_cast<unsigned>(End::count));
inline constexpr std::array run_names{"1", "2", "3", "4-7", "8-15", "16-63", "64-255", "256+"};

struct Counts {
std::uint64_t lists = 0, draws = 0, eligible = 0, indirect = 0, skipped = 0, scopes = 0, max_run = 0;
std::array<std::uint64_t, run_names.size()> runs{};
std::array<std::uint64_t, end_names.size()> ends{};

void add(const Counts& b) {
lists += b.lists; draws += b.draws; eligible += b.eligible; indirect += b.indirect; skipped += b.skipped;
scopes += b.scopes;
max_run = std::max(max_run, b.max_run);
for (unsigned i = 0; i < runs.size(); ++i) runs[i] += b.runs[i];
for (unsigned i = 0; i < ends.size(); ++i) ends[i] += b.ends[i];
}

void finish(std::uint64_t length, End reason) {
++scopes;
max_run = std::max(max_run, length);
const unsigned bucket = length <= 3 ? unsigned(length - 1) : length < 8 ? 3 : length < 16 ? 4 :
length < 64 ? 5 : length < 256 ? 6 : 7;
++runs[bucket];
++ends[static_cast<unsigned>(reason)];
}

void report(std::FILE* out = stderr) const {
// One bounded line: at most 31 unsigned 64-bit values, with fixed, non-title labels.
char line[2048];
int pos = std::snprintf(line, sizeof(line),
"[rt] rendering scopes: lists=%llu draws=%llu eligible=%llu indirect=%llu skipped=%llu scopes=%llu "
"shared_draws=%llu max_run=%llu runs=[",
ull(lists), ull(draws), ull(eligible), ull(indirect), ull(skipped), ull(scopes),
ull(draws - scopes), ull(max_run));
for (unsigned i = 0; i < runs.size(); ++i)
pos += std::snprintf(line + pos, sizeof(line) - pos, "%s%s=%llu", i ? "," : "", run_names[i], ull(runs[i]));
pos += std::snprintf(line + pos, sizeof(line) - pos, "] ends=[");
for (unsigned i = 0; i < ends.size(); ++i)
pos += std::snprintf(line + pos, sizeof(line) - pos, "%s%s=%llu", i ? "," : "", end_names[i], ull(ends[i]));
std::fprintf(out, "%s]\n", line);
}
private:
static unsigned long long ull(std::uint64_t n) { return static_cast<unsigned long long>(n); }
};

inline bool enabled() {
static const bool value = [] {
const char* env = std::getenv("LEONIDA_RENDERING_SCOPE_STATS");
return env && env[0] == '1' && env[1] == '\0';
}();
return value;
}

// Merge once per emitted list, never once per draw. A lock keeps each report internally consistent when queues
// record on different threads. Powers of two bound the log volume; normal process exit reports the final totals.
struct Totals {
std::mutex mutex;
Counts counts;
std::uint64_t last_report = 0;
void add(const Counts& part) {
const std::lock_guard<std::mutex> lock(mutex);
counts.add(part);
if ((counts.lists & (counts.lists - 1)) == 0) {
counts.report();
last_report = counts.lists;
}
}
~Totals() { if (counts.lists != last_report) counts.report(); }
};
inline void publish(const Counts& part) {
static Totals totals;
totals.add(part);
}
} // namespace leonida::scope_stats
Loading
Loading