Skip to content
Merged
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
3 changes: 3 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ loader that maps the game's executable and resolves its imports to shims. Nothin
- The format or behaviour may already be measured in `docs/design.md`. Quote the file and offset a claim comes from,
or call it a hypothesis.
- Count over the whole corpus, not a sample: a rule that holds for 400 shaders can fail on the other 26 000.
- Frame rates of the D3D12 runtime (`d3d12/`): search [d3d12/docs/findings.md](d3d12/docs/findings.md) for the switch or
function before measuring it, and measure as [docs/measuring_fps.md](docs/measuring_fps.md) says (a switch by turns
inside one run). The variables are listed in [d3d12/docs/switches.md](d3d12/docs/switches.md).

## Test without the game first

Expand Down
701 changes: 701 additions & 0 deletions d3d12/docs/switches.md

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,9 @@ method, scope and caveats. No game data is included.

| Document | What it covers |
|---|---|
| [measuring_fps.md](measuring_fps.md) | How to measure frame rates of the D3D12 runtime (`d3d12/`): look in the findings first, turn a switch inside one run with `LEONIDA_AB`, separate runs, which log number means what, what to write before reporting a cause. |
| [d3d12/docs/findings.md](../d3d12/docs/findings.md) | What was measured of the D3D12 runtime's frame on several PCs: where a frame goes, switches by turns with their spread, what was not worth it, picture faults and what they were. |
| [d3d12/docs/switches.md](../d3d12/docs/switches.md) | The `LEONIDA_*` variables the D3D12 runtime names, made from its sources (`tools/d3d12_switches.py`): how each is read, whether `LEONIDA_AB` can turn it, the sentence of the code's comment. |
| [launcher.md](launcher.md) | The Leonida Launcher: the desktop window with navigation, a PLAY button, status line and pages; Leonida's own design, no game assets. |
| [mod-menu.md](mod-menu.md) | The in-game trainer menu drawn by the D3D12 runtime (`d3d12/`): on by default, `LEONIDA_MENU=0` turns it off; single player only, nothing online. |
| [lua-modding.md](lua-modding.md) | Lua 5.4 mods in the D3D12 runtime: a folder in `mods\` with the same `mod.json` the mod manager lists, and a script next to it. |
Expand Down
86 changes: 86 additions & 0 deletions docs/measuring_fps.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
# Measuring frame rates of the D3D12 runtime

How to find out whether a change or a switch moves the frame of the Rust D3D12 runtime (`d3d12/`), and how not to fool
yourself. It is about method; the measurements are in [d3d12/docs/findings.md](../d3d12/docs/findings.md) and the list
of switches in [d3d12/docs/switches.md](../d3d12/docs/switches.md).

## 1. Look first

Search [findings.md](../d3d12/docs/findings.md) for the switch or the function you have in mind, on a fresh `main`.
Many switches have been measured there, with the card, the scene, the method and the spread. `LEONIDA_COPYBACK_ELIDE`, for one,
has an entry that says "not usable here".

## 2. Turn the switch inside one run

`LEONIDA_AB=<seconds>,<switch>[,<switch>..]` turns switches on and off every so many seconds while the title runs, so
both sides are measured in one scene, at one cache temperature, beside the same programs
([`ab.rs`](../d3d12/crates/leonida-gpu/src/ab.rs)):

- It needs a build with `diagnostics` (the one `d3d12/scripts/build-nvidia.ps1` makes) and more than one second a phase.
- Up to eight switches; switch number *n* is on in the phases whose number has bit *n*, so every combination comes round.
- Give it to the launcher: `-More @{LEONIDA_AB='4,LEONIDA_STORE_BESIDE'}`. `play-nvidia.ps1` removes the `LEONIDA_*`
variables of the window it starts in (four paths aside), so `$env:LEONIDA_AB = ...` before it is lost without a word.
The same goes for every variable of section 5.
- More than eight names, or a phase of one second or less, and there is no A/B at all, again without a word. Look for
the `A/B phase` lines in the log.
- A switch named there no longer goes by its own variable. Only switches the code reads that way follow it; for any
other name the phases are logged and nothing changes, so check the name in [switches.md](../d3d12/docs/switches.md)
or the code before you believe a "no difference".
- Not every switch may be turned in play: `findings.md` has one that ends the title (`LEONIDA_ASYNC_SUBMIT`).
- Each phase ends with a line `A/B phase <n> bits <b> on [...]`: frames, mean, median, p90, draws a frame, the card's
idle and busy time a frame and the submitting thread's work a frame. The first second of a phase is left out.

Phases of 3.5 to 4 s worked in the runs of `findings.md` (one PC, one save: "about measuring there"). The idle camera
there goes round views of about 24 s with different draw counts, so phases of 15 s measured the views, not the switch. Standing, `findings.md` cuts the phases into stretches where the draw count
jumps, leaves out the first phase of a stretch and fits a level for each stretch; walking, the switch of bit *b*
has runs of 2^*b* phases off and 2^*b* on: each pair of neighbouring runs gives one difference, and their mean is the effect. Give the effect **with its standard error**. The scripts it names for this (`ab_pair.py`, `ab_eff.py`) are not in
the repository.

The standard errors in `findings.md` are mostly 0.2 to 0.6 ms for a standing run of some minutes (up to 0.94) and 1 to
2 ms for a walking one (up to 2.24). Two separate
runs of one setting differed by 7 ms in one of its tables (75.0 and 82.1 ms).

## 3. When only separate runs will do

A change of code, or a switch that cannot be turned in play, needs separate runs:

- The same save for every start. The title rewrites its autosave, so keep a copy and put it back before each start
(and the player's own back afterwards).
- Alternate (A B B A), in one sitting, with a throwaway run first: on one PC the first measured run after a
warm-up came out slowest in both of two series (seen once, 2026-11-30, not in `findings.md`, not explained).
- After a translator change, or on a new build, play a while first. Until its pipelines are made, a run measures that.
- The same programs in the background, and nothing heavy beside it: no compiler, no test suite. `findings.md` has one build at 16.2 to 17.3
and then 12.8 frames a second; what had changed was the programs that start with Windows.
- Check every run for the state you think it was in: it reached the world, it did not stay in the menu, it did not end early. One that
stayed in the menu showed 60 throughout (seen once, 2026-11-30).
- With two runs a side, do not claim a difference smaller than the spread between runs of the same side.

## 4. Which number means what

- **Frame time, not only frames a second.** The line `leonida_gpu::host: <n> fps, <ms> ms/frame (...)` counts rendered
frames. With frame generation the screen shows more; say which you mean, or measure with `-NoFrameGen`.
- Report the median and a low percentile, and leave the menu and the loading out.
- **A sum over all threads is not a part of the frame.** "All threads", "list calls ... ms", the process's CPU time and
a whole-process profile add up work that runs side by side. They can exceed the frame many times over.
- **A thread that waits because it has nothing to do costs nothing.** The relay line says its thread waits "beside the
submitting thread"; what other threads lost to it is in the line about *settles*.
- Draws "left out on purpose" are not missing pipelines; the line gives both counts.
- The frame stands at the longest of its walls (the card, the submitting thread, the title). Work taken off another one
does not show. Cards and CPUs differ: say the card, driver, CPU, memory, profile, resolution, scene and commit.

## 5. Where a frame goes

All in builds with `diagnostics`; each costs something, so do not read frame rates from the same run.

| Tool | What it answers |
|---|---|
| `LEONIDA_TIMELINE=<file>` (with `LEONIDA_TIMELINE_AT`, `LEONIDA_TIMELINE_FRAMES`) | A trace of a few frames for `chrome://tracing` or Perfetto, and a text summary with **the chain of work and waits each present came out of**: the tool for "what does the frame wait for". |
| `LEONIDA_PROFILE=<from>,<to>,<ms>,<file>` (with `LEONIDA_PROFILE_ONLY=<thread name>`) | Stack samples by thread, waits included, from inside the process. Always with `LEONIDA_PROFILE_ONLY` and a thread of the runtime: without it the busiest threads are taken, the title's among them, and `findings.md` has a run that a walk of a title's stack ended. For those, use the timeline. |
| `LEONIDA_GPU_TIMING=1` with `LEONIDA_D3D12_DRED=1` | The commands' time on the card. The launcher sets `LEONIDA_D3D12_DRED` to `faults`, which is not enough, so give both. Each list is then submitted on its own and `LEONIDA_LATE_WAIT` is off: good for which command costs what, not for how long the frame is. |

## 6. Before you report a cause

1. Write the prediction and what would refute it before the run.
2. Say **MEASURED** (with *n*), **READ IN CODE** or **ASSUMED**.
3. Try to refute it: if this were the cause, what else would have to be true? Is it on the submitting thread's chain?
4. Post numbers only: no logs, captures, shader or pipeline names that are not already in the repository, addresses of the title, or other game data.
176 changes: 176 additions & 0 deletions tests/test_d3d12_switches.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
"""tools/d3d12_switches.py: which LEONIDA_* names of the D3D12 runtime it finds and what it says of each.

python -I tests/test_d3d12_switches.py

Sources written by hand here; the last test runs on the repository's own. No build, no GPU, no game files.
"""
import contextlib
import io
import os
import re
import sys
import tempfile
import unittest

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(ROOT, "tools"))
import d3d12_switches as ds # noqa: E402

GPU = "d3d12/crates/leonida-gpu/src/"
SOURCE = """//! A module. `LEONIDA_FAST=1`: the quick way; off by default. Another sentence.
/// Whether the old way is kept
/// (`LEONIDA_OLD_WAY=0`: not).
fn old() -> bool { crate::toggled!("LEONIDA_OLD_WAY") }
fn fast() -> bool { crate::asked!("LEONIDA_FAST") }
fn slow() -> bool { crate::switch::on("LEONIDA_SLOW") }
fn size() -> u64 {
std::env::var(
"LEONIDA_SIZE_MB").unwrap().parse().unwrap()
}
#[cfg(test)]
mod other;
fn after() { std::env::var_os("LEONIDA_AFTER_OUTLINE"); }
#[cfg(test)]
mod tests {
fn t() { std::env::var("LEONIDA_TEST_CHILD"); }
}
fn last() { std::env::var("LEONIDA_LAST"); }
"""


class CollectTest(unittest.TestCase):
def setUp(self):
self.found = ds.collect({GPU + "a.rs": SOURCE}, launcher=" LEONIDA_FAST = '1'\n", findings="x `LEONIDA_SLOW` y")

def kind(self, name):
return ds.kind(self.found[name]["uses"], name)

def test_the_kind_is_told_from_how_the_name_is_read(self):
self.assertEqual(self.kind("LEONIDA_OLD_WAY"), "on, `0` turns it off")
self.assertEqual(self.kind("LEONIDA_FAST"), "off unless set and not `0`")
self.assertEqual(self.kind("LEONIDA_SLOW"), "off unless set and not `0`")
self.assertEqual(self.kind("LEONIDA_SIZE_MB"), "see the code")

def test_only_a_name_the_ab_macros_take_is_marked_for_ab(self):
self.assertTrue(self.found["LEONIDA_OLD_WAY"]["ab"])
self.assertTrue(self.found["LEONIDA_FAST"]["ab"])
self.assertFalse(self.found["LEONIDA_SLOW"]["ab"])

def test_test_modules_are_told_from_code_after_them_and_from_outline_modules(self):
self.assertFalse(self.found["LEONIDA_TEST_CHILD"]["read"])
self.assertTrue(self.found["LEONIDA_AFTER_OUTLINE"]["read"])
self.assertTrue(self.found["LEONIDA_LAST"]["read"])

def test_a_test_file_is_all_tests(self):
found = ds.collect({GPU + "x_tests.rs": 'fn f() { std::env::var("LEONIDA_ONLY_HERE"); }'})
self.assertTrue(found["LEONIDA_ONLY_HERE"]["tests"])

def test_the_sentence_that_names_it_is_taken_over_line_ends(self):
self.assertEqual(self.found["LEONIDA_OLD_WAY"]["said"], "Whether the old way is kept (`LEONIDA_OLD_WAY=0`: not).")
self.assertEqual(self.found["LEONIDA_FAST"]["said"], "`LEONIDA_FAST=1`: the quick way; off by default.")

def test_launcher_and_findings_are_marked(self):
self.assertTrue(self.found["LEONIDA_FAST"]["launcher"])
self.assertFalse(self.found["LEONIDA_SLOW"]["launcher"])
self.assertTrue(self.found["LEONIDA_SLOW"]["findings"])

def test_a_longer_name_is_not_taken_for_a_shorter_one(self):
self.assertEqual(ds.sentence("`LEONIDA_FAST_N` is a count.", "LEONIDA_FAST"), "")

def test_a_prefix_is_not_a_name(self):
self.assertEqual(ds.NAME.findall("`LEONIDA_VIPATCH_`<name> and LEONIDA_X"), ["LEONIDA_X"])

def test_every_way_the_launcher_assigns_is_seen(self):
names = ["LEONIDA_A1", "LEONIDA_A2", "LEONIDA_A3", "LEONIDA_A4", "LEONIDA_A5", "LEONIDA_A6"]
source = "\n".join(f'v("{n}")' for n in names)
launcher = ("$settings = @{ LEONIDA_A1 = '1'; LEONIDA_A2 = '1' }\n $settings.LEONIDA_A3 = '1'\n"
"if ($settings.LEONIDA_A4 -eq '1') { }\n# LEONIDA_A5 = '1'\n$env:LEONIDA_A6 = '1'\n")
found = ds.collect({GPU + "a.rs": source}, launcher=launcher)
self.assertEqual([n for n in names if found[n]["launcher"]],
["LEONIDA_A1", "LEONIDA_A2", "LEONIDA_A3", "LEONIDA_A6"])

def test_a_switch_read_by_turns_elsewhere_is_for_ab_and_of_no_known_kind(self):
source = """fn a() { leonida_gpu::switched("LEONIDA_HLE") }
const SWITCH: &str = "LEONIDA_BY_CONST";
fn b() { if let Some(on) = crate::ab::pick(SWITCH) { } }
const SWITCH: &str = "LEONIDA_NOT_AB";
fn wide(switch: &'static str) -> bool {
if let Some(on) = crate::ab::pick(switch) { return on; }
false
}
fn c() { wide("LEONIDA_BY_FN"); narrow("LEONIDA_OTHER_FN") }
const NAMES: [&str; 2] = ["LEONIDA_L_A", "LEONIDA_L_B"];
fn d() { NAMES.iter().map(|name| crate::ab::bit(name)) }
fn e() { asked_for!("LEONIDA_BY_MACRO") }
"""
found = ds.collect({GPU + "a.rs": source})
self.assertEqual({n for n, e in found.items() if e["ab"]},
{"LEONIDA_HLE", "LEONIDA_BY_CONST", "LEONIDA_BY_FN", "LEONIDA_L_A", "LEONIDA_L_B", "LEONIDA_BY_MACRO"})
self.assertEqual(ds.kind(found["LEONIDA_HLE"]["uses"], "LEONIDA_HLE"), "see the code")

def test_a_brace_in_a_raw_string_does_not_end_a_test_module(self):
source = '#[cfg(all(test, windows))]\nmod tests {\n const S: &str = r#"\nvoid main() {\n}\n"#;\n' \
' fn f() { v("LEONIDA_AFTER_RAW") }\n}\nfn g() { v("LEONIDA_REAL") }\n'
found = ds.collect({GPU + "a.rs": source})
self.assertFalse(found["LEONIDA_AFTER_RAW"]["read"])
self.assertTrue(found["LEONIDA_REAL"]["read"])

def test_an_outline_test_module_is_tests(self):
found = ds.collect({GPU + "a.rs": "#[cfg(test)]\nmod bench;\n", GPU + "a/bench.rs": 'v("LEONIDA_B1")',
GPU + "b/bench.rs": 'v("LEONIDA_B2")'})
self.assertFalse(found["LEONIDA_B1"]["read"])
self.assertTrue(found["LEONIDA_B2"]["read"])

def test_a_name_only_in_a_comment_is_not_listed_as_read_and_a_placeholder_not_at_all(self):
found = ds.collect({GPU + "a.rs": "// `LEONIDA_OLD` was a switch once.\n// `LEONIDA_X` is any.\n"})
self.assertFalse(found["LEONIDA_OLD"]["read"])
self.assertNotIn("LEONIDA_X", found)
self.assertNotIn("| `LEONIDA_OLD`", ds.page(found))
self.assertEqual(ds.difference(found, "| `LEONIDA_OLD` | x"), ([], ["LEONIDA_OLD"]))

def test_a_piece_of_a_sentence_that_says_nothing_is_not_taken(self):
self.assertEqual(ds.sentence("The joined lists (a pool of them: `LEONIDA_J`, 48). Next.", "LEONIDA_J"),
"The joined lists (a pool of them: `LEONIDA_J`, 48).")
self.assertEqual(ds.sentence("`LEONIDA_J`.", "LEONIDA_J"), "")

def test_a_launcher_value_is_never_copied(self):
found = ds.collect({GPU + "a.rs": 'x("LEONIDA_LIST")'}, launcher="LEONIDA_LIST = 'a long value'")
self.assertTrue(found["LEONIDA_LIST"]["launcher"])
self.assertNotIn("a long value", ds.page(found))


class PageTest(unittest.TestCase):
def test_cells_do_not_break_the_table(self):
found = ds.collect({GPU + "a.rs": '/// `LEONIDA_WAY=<a>|<b>`: one of two.\nfn f() { v("LEONIDA_WAY"); }'})
row = next(line for line in ds.page(found).splitlines() if line.startswith("| `LEONIDA_WAY`"))
self.assertEqual(len(re.findall(r"(?<!\\)\|", row)), 8)

def test_a_page_has_no_difference_from_the_sources_it_was_made_of(self):
found = ds.collect({GPU + "a.rs": SOURCE})
self.assertEqual(ds.difference(found, ds.page(found)), ([], []))

def test_a_name_added_or_gone_is_told(self):
text = ds.page(ds.collect({GPU + "a.rs": 'v("LEONIDA_GONE")\nv("LEONIDA_KEPT")'}))
now = ds.collect({GPU + "a.rs": 'v("LEONIDA_KEPT")\nv("LEONIDA_NEW")'})
self.assertEqual(ds.difference(now, text), (["LEONIDA_NEW"], ["LEONIDA_GONE"]))


class CommandTest(unittest.TestCase):
def test_the_repository_is_listed_and_an_unwritable_path_is_one_line(self):
with tempfile.TemporaryDirectory() as tmp:
out, err = io.StringIO(), io.StringIO()
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
code = ds.main(["--out", os.path.join(tmp, "page.md")])
bad = ds.main(["--out", os.path.join(tmp, "none", "page.md")])
same = ds.main(["--check", os.path.join(tmp, "page.md")])
self.assertEqual((code, bad, same), (0, 2, 0), err.getvalue())
self.assertEqual(len(err.getvalue().splitlines()), 1)
with open(os.path.join(tmp, "page.md"), "rb") as f:
data = f.read()
self.assertNotIn(b"\r", data)
# A moved folder must not turn the list into an empty one.
self.assertGreater(data.count(b"| `LEONIDA_"), 300)


if __name__ == "__main__":
unittest.main()
4 changes: 4 additions & 0 deletions tools/d3d12_run_fps.py
Original file line number Diff line number Diff line change
Expand Up @@ -252,4 +252,8 @@ def main(argv=None) -> int:


if __name__ == "__main__":
try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
sys.stdout.reconfigure(errors="replace")
except (AttributeError, ValueError, OSError):
pass
sys.exit(main())
Loading