Compare commits

...
Author SHA1 Message Date
poli0981andClaude Fable 5.2 9acf48766a feat(overlay): the Overlay reads what a hooked game tells its upscaler, only while the Agent asks - DLSSOptions chained into the evaluation, the rest of the FSR upscale descriptor, FSR's own memory; no new patch site; each session's request its own; a gate that refuses a camera's position anywhere in code loaded into a game (Advanced B PR-3, D111/D114/D115/D116)
fl_adv_fields.h is the one place a vendor struct's extra members are read: sl::DLSSOptions at the struct version
that carries each member, ffxDispatchDescUpscale on the ffx-api route, the upscaler's memory query after the vendor
answered OK. The detours consult one process-local flag the watchdog copies from FlControlBlock.advancedRequested;
with it at 0 nothing more is read and region 5 is never written.

"On" is a request, not a 1: a value no session of the ring used before. The watchdog starts its summaries afresh at
a request it has not seen and names it in every publication (FlAdvancedState.request, the word that was reserved0);
ShmRingReader.AdvancedState returns only a publication that names its own. A second session of a game that kept
running no longer reads the first one's ranges and counts.

tools/overlay-fields-check.ps1 (build.ps1 gate): every member read is on tools/overlay-allowed-fields.txt and every
name there is read; no alias; no listed member read elsewhere in the Overlay or the Vulkan layer; a camera's
position, axes and matrices named nowhere, whatever the list says; sl::Constants and the frame-generation prepare
descriptor never copied or measured.

Measured (the header's functions, the Overlay's flags, 20 M calls x 3): +22.3-23.2 ns per ffx UPSCALE dispatch,
+9.5-11.7 ns per evaluation that chains DLSSOptions, +4.3-6.1 ns per memory query while asked; inside the bench's
noise when not asked.

ctest 33/33 (fl_adv_fields; fl_guard: every byte of region 5 zero until asked on a target that sends everything,
the exact values when asked, untouched after an off, a count that starts again at the next request).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 00:55:08 +07:00
21 changed files with 1581 additions and 53 deletions

No files matched your search

+16
View File
@@ -55,6 +55,22 @@ numeric core and does not move; the heading is the full version — corrected 20
the component inside the game does exactly what it did before. **A game that is running when you update must be
restarted before FrameLedger measures it again**, as after every update.
- **The component inside a game can read what the game tells its upscaler — and only when asked.** For a game
FrameLedger injects into, and only while the agent asks for it (nothing asks yet: that is the next pull request,
and then only with Advanced metrics on), the calls FrameLedger already intercepts are read a little further: the
options a game hands DLSS with each evaluation (output size, presets, exposure, three switches), what it hands
FSR with each upscale (sharpening, the jitter's size, exposure, the depth range, the field of view as a range,
flags, the frame time it reports), and FSR's own memory when the game itself asks for it. **No new hook**, and
with the request off the same code as before runs: a test injects into a window that sends all of it and finds
the new memory region empty to the last byte. **Never the camera's position, its axes or its matrices** — a
build check now refuses those names anywhere in the code loaded into a game (`tools/overlay-fields-check.ps1`).
Many games set their DLSS options through a call that cannot be intercepted, and will show nothing here.
Measured cost while asked: 22–23 billionths of a second per frame for FSR, 10–12 for DLSS; not measurable when
not asked.
- **A second session of a game that kept running starts its summaries afresh.** The ranges and counts kept inside the
game belong to the session that asked for them: each session asks with a request of its own, and the agent reads
only what answers it.
### Changed
- **The agent's processor budget says what was measured.** The specification promised that the capture agent uses
+4 -1
View File
@@ -174,7 +174,10 @@ tools/ # accuracy-check, changelog-check, chokepoint-che
# agent-cost (D110, 2026-11-11: a developer tool, not a gate - what the shipped
# Agent costs per second of session, Advanced metrics off and on),
# nvapi-readonly-check (D108, 2026-11-11: every NVAPI call of the bridge is on
# nvapi-allowed-calls.txt, and none there writes or identifies)
# nvapi-allowed-calls.txt, and none there writes or identifies),
# overlay-fields-check (D116, 2026-11-12: every member of a vendor's struct the
# Overlay reads for Advanced metrics is in fl_adv_fields.h and on
# overlay-allowed-fields.txt; a camera's position, axes and matrices nowhere)
# (six names added 2026-10-04)
# (PowerShell). This line used to name three, one of which
# — resx-audit — ~~does not exist~~ exists since 2026-09-13 with
+10
View File
@@ -489,6 +489,16 @@ function Invoke-ProjectGates {
Invoke-Checked 'nvapi-readonly-check (self-test)' { & $nvapiTool -SelfTest }
Invoke-Checked 'nvapi-readonly-check' { & $nvapiTool -RepoRoot $repo }
# 2026-11-12 (D116): the same for the code loaded into a game. Advanced metrics, train B, reads more members of
# the vendors' structs than the frame record ever needed, and the same structs hold where the player's camera is.
# Every such read is in one header, each member on tools/overlay-allowed-fields.txt in both directions; a camera's
# position, axes and matrices are named nowhere in the Overlay or the Vulkan layer, whatever the list says. Text
# only.
Write-Step 'overlay-fields-check'
$fieldsTool = Join-Path $repo 'tools/overlay-fields-check.ps1'
Invoke-Checked 'overlay-fields-check (self-test)' { & $fieldsTool -SelfTest }
Invoke-Checked 'overlay-fields-check' { & $fieldsTool -RepoRoot $repo }
Write-Step 'docs-split-check'
$splitTool = Join-Path $repo 'tools/docs-split-check.ps1'
Invoke-Checked 'docs-split-check (self-test)' { & $splitTool -SelfTest }
+16 -7
View File
@@ -74,7 +74,7 @@ struct alignas(64) FlControlBlock { // Agent-written
uint32_t overlayEnabled; // @8 in-game overlay draw toggle (v1.1)
uint32_t guardTicks; // @12 completed guard evaluations, NOT a timer
uint32_t logFlushRequested; // @16 a COUNTER: bumped by the Agent at session end; the watchdog flushes the native log on a change (17_HOOK_ENGINE §Native logging, 2026-09-06)
uint32_t advancedRequested; // @20 1 while this session records Advanced metrics (D111); written 0 or 1 at attach, either way
uint32_t advancedRequested; // @20 0, or this session's request for Advanced metrics (D111): non-zero, new to this ring; written at attach, either way
uint32_t reserved[10]; // @24..63 must be zero
};
@@ -101,17 +101,26 @@ static_assert(FL_SHM_DISPLAY_OFFSET == 0xC0 && FL_SHM_ADVANCED_OFFSET == 0x100 &
```
**Region 5 — what a hooked game told its upscaler (layout 5, 2026-11-11; Advanced metrics train B, owner decisions
D111 and D113; written by nobody until the Overlay of 0.1.0-beta.40).** `18_GPU_VENDOR_APIS` §Train B is the design.
D111 and D113; written by the Overlay's watchdog since 0.1.0-beta.40).** `18_GPU_VENDOR_APIS` §Train B is the design.
What the region is, as a contract between the two sides:
- **Off means zero.** `FlControlBlock.advancedRequested` is the Agent's word that this session records Advanced
metrics — written 0 or 1 at attach, either way, because the control block outlives a session
- **Off means nothing is read and nothing is written.** `FlControlBlock.advancedRequested` is the Agent's word that
this session records Advanced metrics — written at attach, either way, because the control block outlives a session
(`ShmRingReader.SetAdvancedRequested`). While it is 0 the Overlay reads no field and installs no hook beyond what
it did before, and writes nothing here: the region is zero from end to end, and `validMask == 0` means "nothing
was read", never "the game used none of it".
it did before, and writes nothing here: a ring nobody ever asked is zero from end to end (`fl_guard` checks every
byte, with a target that sends everything), and `validMask == 0` means "nothing was read", never "the game used
none of it".
- **"On" is a request, not a 1** *(2026-11-12)*. A game outlives a session, and so do the summaries the Overlay keeps
inside it — a range, a count, a mask of what was ever seen. So the word is a value no session of this ring used
before (above the word as it stands and above the request the region last answered; never 0), the watchdog starts
its summaries afresh at a value it has not seen, and every publication names the request it answers
(`FlAdvancedState.request`, the word that was `reserved0`). The reader returns only a publication that names the
value it wrote: what a second session of the same game finds in the region before the first tick is the first
session's, and is not read. After an "off" the region keeps its last publication, untouched.
- **One writer, once a second.** The detours keep process-local accumulators; the watchdog copies them here at its
tick. No game thread writes the region, so the seqlock has a single writer: `seq` odd, the fields, `seq` even.
- **The reader keeps its last consistent copy** (`ShmRingReader.AdvancedState`): null until something was published;
- **The reader keeps its last consistent copy** (`ShmRingReader.AdvancedState`): null until something was published
for its request;
the same copy while `seq` has not moved, without copying 1472 bytes again; and that copy still when the writer is
inside on every attempt — a watchdog killed with its process leaves `seq` odd for good, and what it published
before is still what the game said.
+1
View File
@@ -410,6 +410,7 @@ Seven self-test cases, both directions; `./tools/notice-check.ps1 -Fix` writes a
14. `tools/changelog-check.ps1 -SelfTest` — nine cases, five expected RED. The live half needs a pull request's changed-file list and is supplied by `ci.yml`
14b. `tools/release-notes.ps1 -SelfTest` — five cases over a fixture changelog (a dated and an undated section, a missing one, a prefix that must not match, an empty one), and since beta.24 three over a temporary tree: a version with its own `docs/changelog/<version>.md` is read from it, one without from `CHANGELOG.md`, a prefix of a file name is not that file. The live half needs a tag's version and runs in `release.yml`, where a missing or empty section is a red release (P4 PR-5)
14e. **`tools/nvapi-readonly-check.ps1 -SelfTest`, then live** (owner decision D108, 2026-11-11) — every `NvAPI_*` call in `src/native/FrameLedger.NvapiBridge/src/fl_nvapi_bridge.cpp`, the one translation unit that links `nvapi64.lib` into a shipped binary, is on `tools/nvapi-allowed-calls.txt` and every name there is called; a name that sets, saves, restores, deletes, registers, resets, enables, disables or controls something is red **even when the list names it**, and so is one that returns an identifier (D104) — three reads the verb rule would refuse are exempt by name, each with its reason. Comments and string literals are taken out first, so a setter named in the comment that says it is never called is not a call. Seventeen self-test cases, both directions. Text only: it runs with or without the native build. `18_GPU_VENDOR_APIS` §Runtime policy's "never call a setter", which was a sentence until the bridge went from fourteen calls to forty-four
14f. **`tools/overlay-fields-check.ps1 -SelfTest`, then live** (owner decision D116, 2026-11-12) — the same for the code loaded into a game: every member of a vendor's struct the Overlay reads for Advanced metrics is read in ONE header, `src/native/FrameLedger.Overlay/include/fl_adv_fields.h`, through parameters with fixed names, and is on `tools/overlay-allowed-fields.txt`; every name there is read; the parameters are not aliased and `->` reaches nothing but `desc` and the Overlay's own `region`; no other Overlay or Vulkan-layer source reads a listed member; **a camera's position, axes and matrices** (`cameraPos`, `cameraUp`, `cameraRight`, `cameraFwd`, the five matrices, `cameraPinholeOffset`, `cameraPosition`, `cameraForward`) **are named nowhere in those sources and not on the list, whatever the list says**; and neither `sl::Constants` nor `ffxDispatchDescFrameGenerationPrepareV2` is copied by value or measured with `sizeof`. Comments and string literals are taken out first. Nineteen self-test cases, both directions. Text only. It reads names, not types — which struct version carries a member is `17_HOOK_ENGINE` §Which struct version carries which field and ctest `fl_adv_fields`
14d. **`tools/docs-split-check.ps1 -SelfTest`, then live** (beta.24, owner decision D66) — `CHANGELOG.md` holds no released section beside `[Unreleased]`; each `docs/changelog/<version>.md` holds one `## ` heading, its own `## [<version>] - date`, and no relative link (the App renders release notes as `CHANGELOG.md`); `CHANGELOG.md` and the files under `docs/changelog/`, and `docs/HANDOFF.md` and the files under `docs/handoff/` — and since PR-5 `docs/20_OPEN_QUESTIONS.md` and `docs/open-questions/`, `docs/spike-notes.md` and `docs/spike-notes/` — name each other in both directions. Eleven self-test cases, both directions
14c. **`tools/buildid-check.ps1 -SelfTest`** (beta.18) — eight cases, both directions: a binary built from a dirty tree (`-dirty`, or the short form's `+`), one with no id, a missing one, and an expected id that is dirty or not an id are red. The live half needs the release's clean-checkout id and runs in `release.yml` over the published tree (§Release-time token substitution)
15. `tools/resx-audit.ps1` — ~~**skipped loudly; it does not exist, and no `.resx` file does either**~~ **built 2026-09-13 (P3 PR-2)**: `-SelfTest` first (11 fixture cases, both directions), then the live pass over every `Strings.resx` family under `src/` — key sets equal across en/vi/ja, `Safety_*` in `ja` marked for review or signed, `Strings.Designer.cs` current with `tools/resx-gen.ps1`. A tree with no family is red (`09_I18N` §Translation workflow)
+4 -4
View File
@@ -194,11 +194,11 @@ Every hook must be listed here with a purpose. Anything not on this list is not
|---|---|
| NGX: `NVSDK_NGX_D3D11/D3D12/VULKAN_CreateFeature`, `EvaluateFeature`, `ReleaseFeature` | Which NGX feature is *actually created and evaluated per frame*: SuperSampling (DLSS), RayReconstruction (DLSS-D), FrameGeneration (DLSS-G) |
| NGX parameter accessors (`NVSDK_NGX_Parameter_SetI/GetI/SetUI`) — **exported by `sl.common.dll` only; see below** | `Width`/`Height` (render) vs `OutWidth`/`OutHeight` (output), `PerfQualityValue` (quality preset), sharpness |
| ✅ Streamline: `slEvaluateFeature` · ⏳ `slInit`, `slSetFeatureLoaded`, `slSetConstants`, `slGetFeatureRequirements` | Feature set actually active when the game goes through SL rather than NGX directly (`kFeatureDLSS`, `DLSS_G`, `DLSS_RR`, `Reflex`, `NIS`; since beta.34 `kFeatureDLSS_NR` — DLSS 5's neural rendering, its own fact bit and family `FL_HOOK_SL_NEURAL_RENDERING`, D84; rule 4: the `feature` argument of the API hooked, nothing else). **Built 2026-08-09**, identity only: one MinHook detour on `sl.interposer.dll!slEvaluateFeature`, resolved **module-scoped** and installed lazily by the watchdog. Sets `FL_MEASURED_UPSCALER` + `FL_HOOK_UPSCALER_IDENTITY`; decodes `kFeatureDLSS`/`kFeatureNIS` and reports `FL_UPSCALER_UNKNOWN` for anything else. **Never `FL_UPSCALER_NONE`** — a Streamline-only writer cannot see FFX, XeSS or NGX-direct, and `NONE` is the only one of the three states that may be aggregated as a negative |
| ✅ Streamline: `slEvaluateFeature` · ⏳ `slInit`, `slSetFeatureLoaded`, `slSetConstants`, `slGetFeatureRequirements` | Feature set actually active when the game goes through SL rather than NGX directly (`kFeatureDLSS`, `DLSS_G`, `DLSS_RR`, `Reflex`, `NIS`; since beta.34 `kFeatureDLSS_NR` — DLSS 5's neural rendering, its own fact bit and family `FL_HOOK_SL_NEURAL_RENDERING`, D84; rule 4: the `feature` argument of the API hooked, nothing else). **Built 2026-08-09**, identity only: one MinHook detour on `sl.interposer.dll!slEvaluateFeature`, resolved **module-scoped** and installed lazily by the watchdog. Sets `FL_MEASURED_UPSCALER` + `FL_HOOK_UPSCALER_IDENTITY`; decodes `kFeatureDLSS`/`kFeatureNIS` and reports `FL_UPSCALER_UNKNOWN` for anything else. **Never `FL_UPSCALER_NONE`** — a Streamline-only writer cannot see FFX, XeSS or NGX-direct, and `NONE` is the only one of the three states that may be aggregated as a negative. **Since 0.1.0-beta.40 (Advanced metrics train B, D111), and only while the Agent asks** (`FlControlBlock.advancedRequested`): the `sl::DLSSOptions` a title chains into `inputs` — the struct the quality mode is read from — is read further: `outputWidth`/`outputHeight`, `preExposure`, `exposureScale`, `colorBuffersHDR`, the five presets of version 1, and where the struct's own `structVersion` proves them present `ultraQualityPreset` and `useAutoExposure` (≥ 2) and `alphaUpscalingEnabled` (≥ 3) — §Which struct version carries which field. Rule 4: more members of the same argument of the same call; `fl_adv_fields.h` is the one place, `tools/overlay-fields-check.ps1` holds it. No new patch site. **Measured** (the header's own functions, `/O2 /guard:cf /Qspectre /MT`, 20 M calls × 3): +9.5–11.7 ns per evaluation that chains the options while asked; with the word at 0, one relaxed load and a branch not taken — below what the bench resolves. Most titles set these through `slDLSSSetOptions`, which is not an export, and read N/A (train D) |
| ✅ Streamline: `slSetTag` — **and, since 2026-09-05, every tag's TYPE** (`slTagCensus`; a HUD-less / UI tag marks the present `FL_FG_DLSS_G`, rule 4: the same argument) | The **global** resource tags, where a title states the size of the buffer it is upscaling *from*: `kBufferTypeScalingInputColor`'s extent → `renderW/H` — **or, since 2026-09-05, the size the tagged `sl::Resource` declares when the extent is zero** (`TagSize` in `fl_sl_inputs.h`, shared by all three tag routes; GUID-checked; a Resource declaring no size is still the honest unknown). **Built 2026-08-15** (`FL_HOOK_UPSCALER_PARAMS`), and it is an ALTERNATIVE to the local tags in `slEvaluateFeature`'s `inputs`, not a layer over them — `sl_core_api.h:258` says global and local tags "do NOT interact", so a title using one yields nothing from the other and both are read. Published only on a frame where an evaluation was also seen, because a tag is viewport state that outlives any one frame. This row was MISSING from this table while the hook shipped, which is the gap the banner above now names |
| ✅ Streamline: `slSetTagForFrame` — **and every tag's TYPE, as above** | The same global tags through **Streamline 2.8's frame-based entry point**, which deprecates `slSetTag`: `(const FrameToken&, const ViewportHandle&, const ResourceTag*, uint32_t, CommandBuffer*)` — the token first, then exactly `slSetTag`'s list, handed to the same tag walk. **Built 2026-09-04** (`FL_HOOK_UPSCALER_PARAMS`, its own trampoline; the family is now **published when whole** — once every tag export the loaded interposer has is patched — because publishing on the first row entitled records the second was not yet producing, 38 of 41 on the fixture: the ffx leaves' #110 defect again, fixed the same way). Measured need: Dying Light: The Beast (SL 2.8.0) published `Dlss` identity on every batch and the params bit on none across three captures, because a 2.8 title that tags per frame never calls the deprecated export. The token is not read; the frame count stays with `slGetNewFrameToken`. The installer picks this detour by SYMBOL (`kSymbolSlSetTagForFrame`, bound to the row by `static_assert`), not by family, since the two rows share a family bit and differ in signature |
| ✅ **FidelityFX ffx-api: `ffxDispatch` on the FOUR modules a game calls** — `amd_fidelityfx_dx12.dll` (SDK 1.1.x monolith), `amd_fidelityfx_upscaler_dx12.dll`, `amd_fidelityfx_framegeneration_dx12.dll`, **and `amd_fidelityfx_loader_dx12.dll`** (added the evening of 2026-09-04: three loader-shipping titles at FSR produced zero dispatches at any leaf export, so the loader is where their calls arrive) · ⏳ FSR 3.0 host route `ffx_fsr3_x64.dll!ffxFsr3ContextDispatchUpscale` / `ffxFsr3DispatchFrameGeneration` · ~~`ffxFsr2ContextCreate`~~ · ~~`ffxCreateContext`~~ | **Built 2026-09-04** (`HANDOFF` item 7c). One observer behind three trampolines reads the DESCRIPTOR the title passed — head type first, body only after the type matched a constant from the vendored MIT headers (`third_party/fidelityfx/`, tag v2.3.0): **UPSCALE** → identity (`FSR3` from the monolith, `FSR_UNVERSIONED` from the 2.x upscaler DLL, which hosts FSR 3.1 and FSR 4 behind one type) + `renderSize` → `renderW/H` (quality and sharpness `0xFF`: the dispatch carries neither — *since beta.25 the quality byte is the mode the `ffxQuery` row below names for the dispatched size, `0xFF` when none does*) + one COUNT; **PREPARE / PREPARE_V2** → `frameID` counted on a *new* index only — this vendor's `slGetNewFrameToken`, the `fgEvaluations` producer once a title has ever prepared, with the UPSCALE count as the fallback for a title that never does; **FRAMEGENERATION** → `fgMode = FSR_FG` on that present. Rule 4: the argument of the API we hooked, never `context`, `pNext`, a command list or a resource. **Why all four:** a UE5 title ships the two leaves with no loader and calls their exports; a loader-shipping title calls the loader's export and the signed loader reaches its providers through an object, not the leaves' exports (measured: Dying Light: The Beast, KCD2, Wukong). The morning's "never the loader" rested on the export tables alone and was reversed by the run. What guards against a loader that DID re-enter a leaf's export is the K = 1 control with all four hooked and the consumer's `frames/upscale-drained`, both of which read 2× in that case. `ffxCreateContext` is deliberately NOT a row — nothing it carries fills a field the dispatch does not, and its honest family would collide with `slEvaluateFeature`'s under the installer's equality binding. The family is compound (`IDENTITY \| PARAMS \| FG_EVALUATIONS`), pinned by `static_assert`s that also bind the leaf table to the rows both ways and refuse the loader as a row. Streamline keeps precedence for the count once it has ever issued a token, so every §S31-validated title is byte-identical. Second count: the consumer prints `frames/upscale-drained`, the AMD `tokens/batch`. **FSR 3.0 — BUILT 2026-09-05 as a fifth AMD target:** `ffx_fsr3_x64.dll!ffxFsr3ContextDispatchUpscale` (Cyberpunk's copy; named export, its own descriptor, vendored from tag **`fsr3-v3.0.4`** — the tag whose twelve `ffxFsr3*` declarations match the shipped module, not the `v1.1.4` first named). Rule 4: the detour reads `renderSize` of the descriptor the title passed and nothing else — never the context, a resource or the command list; the offset is pinned to a literal (1256) so a re-vendoring that moved it fails to compile. Same family and publish point as the four rows (`PublishFfxFamilyIfWhole` waits for a loaded host too), keyed by module in the installer; identity `FSR3` as a fact. `ffxFsr3DispatchFrameGeneration` is deliberately not a row (§H11 carries the reversal condition); the `ffx_fsr3upscaler_x64.dll` leaf is the pre-committed alternative if the facade reads silent (row B2) — never both, or `frames/upscale-drained` reads 2.00 |
| ✅ **FidelityFX ffx-api: `ffxQuery` on the same four modules** (beta.25, owner decision D65) — `amd_fidelityfx_dx12.dll`, `amd_fidelityfx_upscaler_dx12.dll`, `amd_fidelityfx_framegeneration_dx12.dll`, `amd_fidelityfx_loader_dx12.dll` | **Built 2026-10-19.** The mode an FSR title runs at reaches the vendor only as an argument of `ffxQuery` — "what render size (`…GETRENDERRESOLUTIONFROMQUALITYMODE`, `0x00010003`) or ratio (`…GETUPSCALERATIOFROMQUALITYMODE`, `0x00010002`) does this mode give at this display size?" — asked before the title sizes its targets; the per-frame dispatch carries the size alone. The detour calls the original FIRST, exactly once, and only when it returned `FFX_API_RETURN_OK` reads the descriptor's type, display size and mode and the values the vendor wrote through the title's own out pointers, into a five-slot table (one per `FfxApiUpscaleQualityMode`); the `ffxDispatch` UPSCALE arm names the ONE mode whose kept answer fits the dispatched `renderSize` (and `upscaleSize`, where stated) as `0x10 + mode` in `upscalerQuality`, else `0xFF` (`03_METRICS` §Upscaling). **Rule 4:** the arguments of the API we hooked — the descriptor the title passed and the out values of that same call — never `context`, a resource or anything the title did not hand the hooked export; nothing of the title's is written, and every read is under the hook's SEH guard. Both query layouts and type ids are pinned to literals by `static_assert`s, identical at SDK v1.1.4 and v2.3.0. **Its own family**, `FL_HOOK_UPSCALER_QUALITY` (bit 11 of `hooksInstalledMask`, mirrored in `FlHookFamily` and `HookFamilies`): `InstallByFamily` binds a row by equality, and the query entitles no measured field by itself — the byte rides under `FL_MEASURED_UPSCALER_PARAMS` from the dispatch arm — so the bit says only that the query was hooked, which tells "never asked" from "could not have seen it ask". Published like the dispatch family, once every loaded leaf is patched (`PublishFfxQueryFamilyIfWhole`); the FSR 3.0 host has no `ffxQuery` and no row (`static_assert`). A loader that passes a query on to a leaf's export refreshes one kept answer twice; nothing is counted, so nothing is counted twice. **Measured overhead** (a copy of the two bodies, `/O2 /guard:cf /Qspectre /MT`, 20 M calls × 3 runs, every slot holding both a size and a ratio — the worst case): 7.6–8.2 ns added per UPSCALE dispatch, i.e. per application frame, and 1.6 ns per query beside the trampoline; the per-present path gains one load. Harness: `--ffx-query sizes|ratios`; `fl_guard` "FSR's quality mode". |
| ✅ **FidelityFX ffx-api: `ffxDispatch` on the FOUR modules a game calls** — `amd_fidelityfx_dx12.dll` (SDK 1.1.x monolith), `amd_fidelityfx_upscaler_dx12.dll`, `amd_fidelityfx_framegeneration_dx12.dll`, **and `amd_fidelityfx_loader_dx12.dll`** (added the evening of 2026-09-04: three loader-shipping titles at FSR produced zero dispatches at any leaf export, so the loader is where their calls arrive) · ⏳ FSR 3.0 host route `ffx_fsr3_x64.dll!ffxFsr3ContextDispatchUpscale` / `ffxFsr3DispatchFrameGeneration` · ~~`ffxFsr2ContextCreate`~~ · ~~`ffxCreateContext`~~ | **Built 2026-09-04** (`HANDOFF` item 7c). One observer behind three trampolines reads the DESCRIPTOR the title passed — head type first, body only after the type matched a constant from the vendored MIT headers (`third_party/fidelityfx/`, tag v2.3.0): **UPSCALE** → identity (`FSR3` from the monolith, `FSR_UNVERSIONED` from the 2.x upscaler DLL, which hosts FSR 3.1 and FSR 4 behind one type) + `renderSize` → `renderW/H` (quality and sharpness `0xFF`: the dispatch carries neither — *since beta.25 the quality byte is the mode the `ffxQuery` row below names for the dispatched size, `0xFF` when none does*) + one COUNT; **PREPARE / PREPARE_V2** → `frameID` counted on a *new* index only — this vendor's `slGetNewFrameToken`, the `fgEvaluations` producer once a title has ever prepared, with the UPSCALE count as the fallback for a title that never does; **FRAMEGENERATION** → `fgMode = FSR_FG` on that present. Rule 4: the argument of the API we hooked, never `context`, `pNext`, a command list or a resource. **Why all four:** a UE5 title ships the two leaves with no loader and calls their exports; a loader-shipping title calls the loader's export and the signed loader reaches its providers through an object, not the leaves' exports (measured: Dying Light: The Beast, KCD2, Wukong). The morning's "never the loader" rested on the export tables alone and was reversed by the run. What guards against a loader that DID re-enter a leaf's export is the K = 1 control with all four hooked and the consumer's `frames/upscale-drained`, both of which read 2× in that case. `ffxCreateContext` is deliberately NOT a row — nothing it carries fills a field the dispatch does not, and its honest family would collide with `slEvaluateFeature`'s under the installer's equality binding. The family is compound (`IDENTITY \| PARAMS \| FG_EVALUATIONS`), pinned by `static_assert`s that also bind the leaf table to the rows both ways and refuse the loader as a row. Streamline keeps precedence for the count once it has ever issued a token, so every §S31-validated title is byte-identical. Second count: the consumer prints `frames/upscale-drained`, the AMD `tokens/batch`. **FSR 3.0 — BUILT 2026-09-05 as a fifth AMD target:** `ffx_fsr3_x64.dll!ffxFsr3ContextDispatchUpscale` (Cyberpunk's copy; named export, its own descriptor, vendored from tag **`fsr3-v3.0.4`** — the tag whose twelve `ffxFsr3*` declarations match the shipped module, not the `v1.1.4` first named). Rule 4: the detour reads `renderSize` of the descriptor the title passed and nothing else — never the context, a resource or the command list; the offset is pinned to a literal (1256) so a re-vendoring that moved it fails to compile. Same family and publish point as the four rows (`PublishFfxFamilyIfWhole` waits for a loaded host too), keyed by module in the installer; identity `FSR3` as a fact. `ffxFsr3DispatchFrameGeneration` is deliberately not a row (§H11 carries the reversal condition); the `ffx_fsr3upscaler_x64.dll` leaf is the pre-committed alternative if the facade reads silent (row B2) — never both, or `frames/upscale-drained` reads 2.00. **Since 0.1.0-beta.40 (Advanced metrics train B, D111), and only while the Agent asks:** the UPSCALE arm reads the rest of `ffxDispatchDescUpscale` — `enableSharpening`, `sharpness`, `jitterOffset`, `preExposure`, `cameraNear`, `cameraFar`, `cameraFovAngleVertical`, `flags`, `reset`, `frameTimeDelta` — into process-local summaries (an "ever seen" mask, a largest magnitude, a lowest and highest, a count and a sum; one module's dispatches are counted, so a dispatch that reaches the loader and a leaf is one). Never on the FSR 3.0 host's legacy descriptor, which is vouched for through `renderSize` and no further; never a PREPARE descriptor's camera arrays (`tools/overlay-fields-check.ps1` refuses their names anywhere in the Overlay). `cameraNear`/`cameraFar`/`cameraFovAngleVertical` are the depth range and the field of view, not where the camera is; the field of view is kept as a session's range, never a series (D114). **Measured** (as the row above): +22–23 ns per UPSCALE dispatch, i.e. per application frame, while asked; ≤ 0.7 ns, inside the bench's noise, with the word at 0 |
| ✅ **FidelityFX ffx-api: `ffxQuery` on the same four modules** (beta.25, owner decision D65) — `amd_fidelityfx_dx12.dll`, `amd_fidelityfx_upscaler_dx12.dll`, `amd_fidelityfx_framegeneration_dx12.dll`, `amd_fidelityfx_loader_dx12.dll` | **Built 2026-10-19.** The mode an FSR title runs at reaches the vendor only as an argument of `ffxQuery` — "what render size (`…GETRENDERRESOLUTIONFROMQUALITYMODE`, `0x00010003`) or ratio (`…GETUPSCALERATIOFROMQUALITYMODE`, `0x00010002`) does this mode give at this display size?" — asked before the title sizes its targets; the per-frame dispatch carries the size alone. The detour calls the original FIRST, exactly once, and only when it returned `FFX_API_RETURN_OK` reads the descriptor's type, display size and mode and the values the vendor wrote through the title's own out pointers, into a five-slot table (one per `FfxApiUpscaleQualityMode`); the `ffxDispatch` UPSCALE arm names the ONE mode whose kept answer fits the dispatched `renderSize` (and `upscaleSize`, where stated) as `0x10 + mode` in `upscalerQuality`, else `0xFF` (`03_METRICS` §Upscaling). **Rule 4:** the arguments of the API we hooked — the descriptor the title passed and the out values of that same call — never `context`, a resource or anything the title did not hand the hooked export; nothing of the title's is written, and every read is under the hook's SEH guard. Both query layouts and type ids are pinned to literals by `static_assert`s, identical at SDK v1.1.4 and v2.3.0. **Its own family**, `FL_HOOK_UPSCALER_QUALITY` (bit 11 of `hooksInstalledMask`, mirrored in `FlHookFamily` and `HookFamilies`): `InstallByFamily` binds a row by equality, and the query entitles no measured field by itself — the byte rides under `FL_MEASURED_UPSCALER_PARAMS` from the dispatch arm — so the bit says only that the query was hooked, which tells "never asked" from "could not have seen it ask". Published like the dispatch family, once every loaded leaf is patched (`PublishFfxQueryFamilyIfWhole`); the FSR 3.0 host has no `ffxQuery` and no row (`static_assert`). A loader that passes a query on to a leaf's export refreshes one kept answer twice; nothing is counted, so nothing is counted twice. **Measured overhead** (a copy of the two bodies, `/O2 /guard:cf /Qspectre /MT`, 20 M calls × 3 runs, every slot holding both a size and a ratio — the worst case): 7.6–8.2 ns added per UPSCALE dispatch, i.e. per application frame, and 1.6 ns per query beside the trampoline; the per-present path gains one load. Harness: `--ffx-query sizes|ratios`; `fl_guard` "FSR's quality mode". **Since 0.1.0-beta.40 (Advanced metrics train B, D111), and only while the Agent asks:** when the query the vendor answered OK is the upscaler's memory — `FFX_API_QUERY_DESC_TYPE_UPSCALE_GPU_MEMORY_USAGE` (`0x00010008`, ffx-api 1.1.2) or `…_V2` (`0x00010009`, 2.0) — the `FfxApiEffectMemoryUsage` it wrote through the title's own out-pointer is kept (total and aliasable bytes), one module's queries counted. Only a title that asks is answered: FrameLedger never calls `ffxQuery` itself. The frame-generation memory queries (`0x00020007`, `0x0002000b`) are not read. +4.3–6.1 ns per such query while asked. Harness: `--ffx-memory-query v1|v2`; `fl_guard` "region 5 stays empty until the Agent asks". |
| ~~XeSS: `xessD3D12CreateContext`, `xessD3D12Init`, `xessD3D12Execute`~~ **Closed at the census by licence, 2026-09-04** (`20_OPEN_QUESTIONS` §Scope decisions, `18_GPU_VENDOR_APIS` §Intel XeSS SDK): no hook on any `libxess*.dll` export *(corrected 2026-10-04)* | ~~`outputResolution`, `qualitySetting`, XeSS version; `xess_fg` variants for XeFG~~ |
| ✅ **Application frames per present** (`fgEvaluations`) — **`sl.interposer.dll!slGetNewFrameToken` since 2026-09-03** | Native vs Displayed frame counts at Tier 1 — see `03_METRICS` §Frame Generation. **The producer is the frame-token export**: Streamline hands a title one token per application frame and the title must ask; the detour counts distinct tokens between two presents (pointer changes, nothing dereferenced), `FL_HOOK_FG_EVALUATIONS` is its family, and it installs on every Streamline 2 title including the ones that evaluate nothing through `slEvaluateFeature`. Rule 4: the out-parameter of an API we hooked. Premise and its gate in `03_METRICS`; pre-committed table in `20_OPEN_QUESTIONS` §S31. *The row as it stood before:* ~~NGX/SL/FFX/XeSS FG feature evaluations per present. **Built 2026-08-15 for Streamline, and MEASURED TO YIELD NOTHING ON THAT ROUTE**~~ — `slEvaluateFeature(kFeatureDLSS_G)` is never called by Cyberpunk 2077 (0 across ~14,000 batches, four FG settings), so this row installs, is honest, and counts zero; see `docs/HANDOFF.md` item 3. Built on the detour that was already there: `kFeatureDLSS_G` contributes to a saturating COUNT in the same word the feature bits live in (`fl_sl_seen.h`) rather than to a bit, because a bit collapses several evaluations between two presents into one — and under multi-frame generation that is the common case, not the edge. The row's family is therefore compound (`FL_HOOK_UPSCALER_IDENTITY \| FL_HOOK_FG_EVALUATIONS`), pinned by a `static_assert` because `hookinventory-check` reads that column as an opaque identifier. **Counts EVALUATIONS, not generated frames** — the 2026-08-14 owner ruling; the multiplier lives in `sl::DLSSGOptions`, which is only reachable by the route §2b refused. ~~Non-NVIDIA FG vendors are **deferred with a written rationale**: `amd_fidelityfx_framegeneration_dx12.dll` 3.1.5 exports only the five generic `ffx*` entry points, identical to five sibling modules, so identity is in the arguments and we have no headers~~ — **AMD has a producer since 2026-09-04** (the FidelityFX row above: the PREPARE dispatch's `frameID`, or the UPSCALE count on a title that never prepares, feeds `fgEvaluations` when Streamline has never issued a token); Intel stays at the census (`20_OPEN_QUESTIONS` §Scope decisions, by licence); the FSR 3.0 host DLL's UPSCALE (`ffxFsr3ContextDispatchUpscale`, since 2026-09-05) counts like an ffx-api UPSCALE when neither Streamline nor a PREPARE has spoken |
@@ -804,7 +804,7 @@ verification a dev-machine-only affair before:
- **WARP** (`D3D_DRIVER_TYPE_WARP`) — a software rasteriser, so no adapter is required.
- **`CreateSwapChainForComposition`** — no `HWND`, so no dependency on a window station or an interactive session.
Current modes: `--probe-vtable` (§H4, ctest `fl_vtable_indices`), `--probe-proxy` (§H5, ctest `fl_proxy_swapchain`), `--probe-unhook` (§H7, ctest `fl_unhook_preserves_foreign`), `--probe-cost` (NFR-1, measurement only), **`--probe-frames`** (ctest `fl_frame_identity` — what counts as a frame, against `GetLastPresentCount`), **`--probe-d3d12`** (ctest `fl_d3d12_acquisition` — device → command queue → swapchain), `--present N`, `--hold N`, **`--real`** and **`--plus-ui K``**, **`--vulkan --hold-presenting N`** (P1 item 3, real loader, exit 77 = cannot run here) and **`--opengl --hold-presenting N`** (P1 item 4, gdi32 `SwapBuffers` on a hidden window, Microsoft's generic renderer — runs on CI). *(Added 2026-10-04, each with its own ctest: `--probe-d3d12-vtable`, `--probe-dxr`, `--probe-dxr-inputs`, `--probe-upscaler-resolve`, `--probe-sl-abi`, `--probe-ffx-resolve`, `--probe-sl-inputs`, `--probe-sl-seen`, `--probe-dxgi-count`; and the `--hold-presenting-*` injection fixtures with `--load` / `--load-after-ms`.)*
Current modes: `--probe-vtable` (§H4, ctest `fl_vtable_indices`), `--probe-proxy` (§H5, ctest `fl_proxy_swapchain`), `--probe-unhook` (§H7, ctest `fl_unhook_preserves_foreign`), `--probe-cost` (NFR-1, measurement only), **`--probe-frames`** (ctest `fl_frame_identity` — what counts as a frame, against `GetLastPresentCount`), **`--probe-d3d12`** (ctest `fl_d3d12_acquisition` — device → command queue → swapchain), `--present N`, `--hold N`, **`--real`** and **`--plus-ui K``**, **`--vulkan --hold-presenting N`** (P1 item 3, real loader, exit 77 = cannot run here) and **`--opengl --hold-presenting N`** (P1 item 4, gdi32 `SwapBuffers` on a hidden window, Microsoft's generic renderer — runs on CI). *(Added 2026-10-04, each with its own ctest: `--probe-d3d12-vtable`, `--probe-dxr`, `--probe-dxr-inputs`, `--probe-upscaler-resolve`, `--probe-sl-abi`, `--probe-ffx-resolve`, `--probe-sl-inputs`, `--probe-sl-seen`, `--probe-dxgi-count`; and the `--hold-presenting-*` injection fixtures with `--load` / `--load-after-ms`.)* *(Added 2026-11-12, Advanced metrics train B: `--probe-adv-fields`, ctest `fl_adv_fields` — `fl_adv_fields.h` alone: a struct of a lower version is not read past its end, the vendors' sentinels never leave as values, the summaries, the publication, a new request starting afresh; and `--advanced` / `--ffx-memory-query v1|v2`, which make the `--hold-presenting-upscaled` and `--hold-presenting-ffx` fixtures send what Advanced metrics reads.)*
> **Every present here used to carry `DXGI_PRESENT_TEST`, which submits nothing.** Measured: 500 of them leave `GetLastPresentCount` at 0 while 37 real presents move it by 37. "N presents → N records" was therefore satisfiable only by a writer counting non-frames. `--real` issues real presents; the test-present path is kept as a named mode because it is what an alt-tabbed title actually runs.
+10 -2
View File
@@ -727,9 +727,16 @@ What the catalog marks `HookedCall` and `NewHook`. Planned the day train A shipp
planning, the design reviewed against the code before it was approved.
- **D111 — off means off inside the game too.** The Agent writes one word of the control block
(`advancedRequested`, 0 or 1, unconditionally at attach) when the session records Advanced metrics. The Overlay
(`advancedRequested`, ~~0 or 1~~ 0 or that session's request, unconditionally at attach) when the session records Advanced metrics. The Overlay
reads a new field, and installs a new hook, only while it is set; with the option off it hooks and reads exactly
what 0.1.0-beta.39's does.
**Built 2026-11-12 (0.1.0-beta.40, PR-3), with one thing the plan did not have:** "on" is not a 1 but a
*request* — a value no session of that ring used before. A game outlives a session, and the Overlay's summaries
with it; a second session of a game that kept running would have read the first one's field of view and counts.
The watchdog starts its summaries afresh at a request it has not seen and names the request in every publication;
the Agent reads only what answers its own (`07_IPC` §Region 5). The detours consult one process-local flag, the
watchdog is the region's one writer, and `fl_guard` shows the off half on a target that sends everything: every
byte of the region zero until asked, untouched after an "off", a count that starts again at the next request.
- **D113 — three releases, because a new patch site cannot be proven in CI.** A crash in a game under the user-mode
anti-cheat exception's trial ends that exception for good (D38), and every release already means restarting the
game. **beta.40**: more fields of calls *already* hooked — `sl::DLSSOptions` where the game chains it into
@@ -745,7 +752,8 @@ planning, the design reviewed against the code before it was approved.
carries which field): the table from the upstream tags, not the one header in the tree.
- **D116 — "never the camera" is a build check**, as "never a setter" is (D108): `tools/overlay-fields-check.ps1` —
every read of a vendor struct in one header, each allowed member named and used, the camera's names refused
anywhere in the Overlay and the Vulkan layer, no copy of `sl::Constants` by value.
anywhere in the Overlay and the Vulkan layer, no copy of `sl::Constants` by value. *(Built 2026-11-12:
twenty-eight members on `tools/overlay-allowed-fields.txt`; `12_BUILD` gate 14f.)*
- **What will read N/A, and says why.** Many titles set their DLSS options through `slDLSSSetOptions`, which is not
an export (train D), so `sl.dlss.*` is filled only for a title that passes its options with the evaluate call.
`slGetFeatureVersion` and `slGetFeatureRequirements` are calls a game makes while starting.
@@ -49,6 +49,7 @@ public sealed unsafe class ShmRingReader : IDisposable
private bool _disposed;
private FlAdvancedState? _advanced;
private uint _advancedSeq;
private uint _advancedRequest;
private ShmRingReader(MemoryMappedFile mmf, MemoryMappedViewAccessor view, byte* basePtr, uint capacity)
{
@@ -335,20 +336,40 @@ public sealed unsafe class ShmRingReader : IDisposable
/// <summary>
/// Says whether the session this ring belongs to records Advanced metrics (owner decision D111; layout 5). Written
/// either way: the control block outlives a session, so "off" is a 0 that is stored, never a word that is left
/// alone - a 1 from the session before would be a request nobody made. While it is 0 the Overlay reads and hooks
/// alone - a request from the session before would be one nobody made. While it is 0 the Overlay reads and hooks
/// exactly what it did before the option existed.
/// </summary>
/// <remarks>
/// <b>"On" is a request of this session's own, not a 1.</b> A game outlives a session, and so do the summaries the
/// Overlay keeps inside it - a range, a count, a mask of what was ever seen. The value written is one no session of
/// this ring used: above the word as it stands and above the request the region last answered. The Overlay starts
/// its summaries afresh at a value it has not seen, and <see cref="AdvancedState"/> returns only a publication that
/// names this value - so a second session of the same game never reads the first one's field of view.
/// </remarks>
public void SetAdvancedRequested(bool requested)
{
ObjectDisposedException.ThrowIf(_disposed, this);
var control = (FlControlBlock*)(_base + ShmLayout.ControlOffset);
Volatile.Write(ref control->AdvancedRequested, requested ? 1u : 0u);
var region = (FlAdvancedState*)(_base + ShmLayout.AdvancedOffset);
uint request = 0u;
if (requested)
{
// The region's word is read without its lock: any value it ever held is one to stay clear of, and the
// watchdog only ever stores values this word held.
uint used = Math.Max(Volatile.Read(ref control->AdvancedRequested), Volatile.Read(ref region->Request));
request = used == uint.MaxValue ? 1u : used + 1u;
}
_advancedRequest = request;
_advanced = null;
_advancedSeq = 0u;
Volatile.Write(ref control->AdvancedRequested, request);
}
/// <summary>
/// Region 5 (layout 5, Advanced metrics train B): what the hooked game told its upscaler, as the Overlay's
/// watchdog last published it - or null while it has published nothing, which is every ring whose session does not
/// record Advanced metrics.
/// watchdog last published it <b>for this reader's request</b> - or null while it has published nothing for it, which
/// is every ring whose session does not record Advanced metrics, and the first second of one that does.
/// </summary>
/// <remarks>
/// <para>
@@ -369,9 +390,9 @@ public sealed unsafe class ShmRingReader : IDisposable
for (int attempt = 0; attempt < DisplayStateAttempts; attempt++)
{
uint before = Volatile.Read(ref region->Seq);
if (before == 0u || (_advanced is not null && before == _advancedSeq))
if (_advancedRequest == 0u || before == 0u || (_advanced is not null && before == _advancedSeq))
{
return _advanced; // never published, or nothing newer than the copy held
return _advanced; // never asked, never published, or nothing newer than the copy held
}
if ((before & 1u) != 0u)
@@ -383,6 +404,11 @@ public sealed unsafe class ShmRingReader : IDisposable
Interlocked.MemoryBarrier();
if (Volatile.Read(ref region->Seq) == before)
{
if (copy.Request != _advancedRequest)
{
return _advanced; // the session before's, in a game that kept running: not this one's
}
_advanced = copy;
_advancedSeq = before;
return copy;
+11 -6
View File
@@ -664,9 +664,11 @@ public unsafe struct FlControlBlock
public uint LogFlushRequested;
/// <summary>
/// 1 while the session this ring belongs to records Advanced metrics, 0 otherwise (owner decision D111). Written
/// unconditionally at attach - the block outlives a session. While it is 0 the Overlay reads and hooks exactly what it
/// did before the option existed, and region 5 stays zero.
/// 0 while the session this ring belongs to does not record Advanced metrics; otherwise that session's request, a
/// non-zero value no session of this ring used before (owner decision D111). Written unconditionally at attach - the
/// block outlives a session. While it is 0 the Overlay reads and hooks exactly what it did before the option
/// existed and writes nothing to region 5; a value it has not seen starts its summaries afresh, and every
/// publication names the request it answers (<see cref="FlAdvancedState.Request"/>).
/// </summary>
public uint AdvancedRequested;
@@ -765,7 +767,7 @@ public enum FlAdvancedValid : uint
/// <summary>
/// Region 5 — Overlay-written by its watchdog, once a second, <b>only while <see cref="FlControlBlock.AdvancedRequested"/>
/// is 1</b> (layout 5, 2026-11-11, Advanced metrics train B): what a hooked game told its upscaler, read from the arguments
/// is not 0</b> (layout 5, 2026-11-11, Advanced metrics train B): what a hooked game told its upscaler, read from the arguments
/// of calls the Overlay hooks. Sized once for the three releases of the train: a member a later release fills is here
/// and stays zero until then.
/// </summary>
@@ -800,8 +802,11 @@ public unsafe struct FlAdvancedState
/// <summary>Publications (wraps).</summary>
public uint Samples;
/// <summary>Must be zero.</summary>
public uint Reserved0;
/// <summary>
/// The <see cref="FlControlBlock.AdvancedRequested"/> this publication answers. A reader keeps a publication only
/// when this is the value it wrote: anything else is what the session before left in a game that kept running.
/// </summary>
public uint Request;
/// <summary>QueryPerformanceCounter at the last publication.</summary>
public ulong SampleQpc;
@@ -0,0 +1,407 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
// What a hooked game told its upscaler, beyond what the frame record carries
// (Advanced metrics, train B; 18_GPU_VENDOR_APIS §Train B; fl_shm.h region 5).
//
// THE ONE PLACE A VENDOR STRUCT'S EXTRA MEMBERS ARE READ (owner decision D116).
// Every member this file reads is named in tools/overlay-allowed-fields.txt, and
// tools/overlay-fields-check.ps1 fails the build when a member is read here that
// is not on that list, or is on it and not read. The reads go through three
// parameters with fixed names, which is what makes that checkable:
//
// o const sl::DLSSOptions& chained into slEvaluateFeature's inputs
// d const ffxDispatchDescUpscale& the descriptor of an ffx upscale dispatch
// m const FfxApiEffectMemoryUsage& what ffxQuery wrote, after it answered OK
// q the memory query's descriptor (its out-pointer), and `desc`, its header (its type)
//
// RULE 4. Each is an argument of a call the Overlay hooks, or what that call wrote
// through an out-pointer the game gave it. Nothing else is dereferenced: no
// resource, no command list, no callback, and never a camera's position, axes or
// matrices (the gate refuses those names anywhere in the Overlay).
//
// WHICH VERSION CARRIES WHICH MEMBER (owner decision D115; 17_HOOK_ENGINE §Which
// struct version carries which field). sl::DLSSOptions grew twice; a member is
// read only at the struct version that introduced it, because the game's struct
// ends where ITS version ends. ffxDispatchDescUpscale has had one declaration in
// every ffx-api release, so all of it may be read - on the ffx-api route only,
// never on the FSR 3.0 host's legacy descriptor.
//
// RULE 5. Everything a detour calls here is a handful of relaxed atomic
// operations on one process-local, cache-aligned struct: no allocation, no lock,
// no call out. Publish() runs on the watchdog, never on a game thread.
//
// SENTINELS AND VENDOR ZEROS never leave this file as values: Streamline's
// INVALID_FLOAT is FLT_MAX and its INVALID_UINT all-ones, a Boolean has a third
// state, and preset 0 is "default". See the encoding notes on FlAdvancedState.
#ifndef FRAMELEDGER_FL_ADV_FIELDS_H
#define FRAMELEDGER_FL_ADV_FIELDS_H
#include <atomic>
#include <bit>
#include <cstdint>
#include <fl_shm.h>
#include <sl.h>
// After sl.h, as fl_sl_inputs.h explains: sl_dlss.h has no includes of its own.
#include <ffx_api.h>
#include <ffx_upscale.h>
#include <sl_dlss.h>
namespace fl::adv {
// A float a detour may keep: finite, and not a vendor's "nobody set this". The
// test is on the magnitude's bits: everything below FLT_MAX passes, and FLT_MAX
// itself (Streamline's INVALID_FLOAT), both infinities and every NaN do not.
inline bool Usable(float v) noexcept {
return (std::bit_cast<uint32_t>(v) & 0x7FFFFFFFu) < 0x7F7FFFFFu;
}
inline float Magnitude(float v) noexcept {
return std::bit_cast<float>(std::bit_cast<uint32_t>(v) & 0x7FFFFFFFu);
}
// The highest / lowest value seen, kept as float bits. A compare-exchange only
// when the value is a new extreme, which after the first frames is almost never.
inline void KeepMax(std::atomic<uint32_t>& slot, float v) noexcept {
const uint32_t bits = std::bit_cast<uint32_t>(v);
uint32_t seen = slot.load(std::memory_order_relaxed);
while (seen == FL_ADV_FLOAT_NONE || std::bit_cast<float>(seen) < v) {
if (slot.compare_exchange_weak(seen, bits, std::memory_order_relaxed)) {
break;
}
}
}
inline void KeepMin(std::atomic<uint32_t>& slot, float v) noexcept {
const uint32_t bits = std::bit_cast<uint32_t>(v);
uint32_t seen = slot.load(std::memory_order_relaxed);
while (seen == FL_ADV_FLOAT_NONE || std::bit_cast<float>(seen) > v) {
if (slot.compare_exchange_weak(seen, bits, std::memory_order_relaxed)) {
break;
}
}
}
// OR bits into a word only when one of them is new: a flag every frame carries
// costs a load, not a locked instruction.
inline void NoteBits(std::atomic<uint32_t>& slot, uint32_t bits) noexcept {
if ((slot.load(std::memory_order_relaxed) & bits) != bits) {
slot.fetch_or(bits, std::memory_order_relaxed);
}
}
// sl::Boolean PLUS ONE, or 0 for its third state ("invalid": the game set nothing).
inline uint8_t BooleanPlusOne(sl::Boolean b) noexcept {
return (b == sl::Boolean::eFalse || b == sl::Boolean::eTrue) ? static_cast<uint8_t>(static_cast<uint8_t>(b) + 1u)
: uint8_t{0};
}
// sl::DLSSPreset PLUS ONE, or 0 for a value a byte cannot carry.
inline uint8_t PresetPlusOne(sl::DLSSPreset p) noexcept {
const auto v = static_cast<uint32_t>(p);
return v < 0xFFu ? static_cast<uint8_t>(v + 1u) : uint8_t{0};
}
// A bool as the vendor's C struct stores it, read as the byte it is: any other
// read of a byte that is neither 0 nor 1 is undefined.
inline bool ByteIsSet(const bool& field) noexcept {
return *reinterpret_cast<const unsigned char*>(&field) != 0u;
}
// What the detours accumulate between two publications. Process-local; one
// instance, in the Overlay, which aligns it to a cache line of its own (on the
// variable, not here: an aligned struct is a padded struct, and /W4 says so).
// Counts wrap, as the region's do.
struct Accumulators {
std::atomic<uint32_t> validMask{0u}; // FlAdvancedValid
// sl::DLSSOptions, as last seen
std::atomic<uint32_t> dlssStructVersion{0u};
std::atomic<uint32_t> dlssOptionsSeen{0u};
std::atomic<uint32_t> dlssOutputWidth{0u};
std::atomic<uint32_t> dlssOutputHeight{0u};
std::atomic<uint32_t> dlssPreExposureBits{FL_ADV_FLOAT_NONE};
std::atomic<uint32_t> dlssExposureScaleBits{FL_ADV_FLOAT_NONE};
std::atomic<uint64_t> dlssPresets{0u}; // six bytes, DLAA in the lowest
std::atomic<uint32_t> dlssBooleans{0u}; // three bytes: HDR input, auto-exposure, alpha upscaling
// the ffx upscale dispatch
std::atomic<uint32_t> ffxOwner{0u}; // leaf + 1 of the module whose dispatches are counted
std::atomic<uint32_t> ffxDispatches{0u};
std::atomic<uint32_t> ffxSharpenSeen{0u};
std::atomic<uint32_t> ffxSharpnessMinBits{FL_ADV_FLOAT_NONE};
std::atomic<uint32_t> ffxSharpnessMaxBits{FL_ADV_FLOAT_NONE};
std::atomic<uint32_t> ffxJitterMaxXBits{FL_ADV_FLOAT_NONE};
std::atomic<uint32_t> ffxJitterMaxYBits{FL_ADV_FLOAT_NONE};
std::atomic<uint32_t> ffxPreExposureMinBits{FL_ADV_FLOAT_NONE};
std::atomic<uint32_t> ffxPreExposureMaxBits{FL_ADV_FLOAT_NONE};
std::atomic<uint32_t> ffxNearBits{FL_ADV_FLOAT_NONE};
std::atomic<uint32_t> ffxFarBits{FL_ADV_FLOAT_NONE};
std::atomic<uint32_t> ffxFovMinBits{FL_ADV_FLOAT_NONE};
std::atomic<uint32_t> ffxFovMaxBits{FL_ADV_FLOAT_NONE};
std::atomic<uint32_t> ffxFlagsSeen{0u};
std::atomic<uint32_t> ffxResets{0u};
std::atomic<uint32_t> ffxFrameTimeCount{0u}; // drained by Publish
std::atomic<uint64_t> ffxFrameTimeSumUs{0u}; // drained by Publish
// the ffx upscaler's own memory, as the last answered query gave it
std::atomic<uint64_t> ffxMemoryTotalBytes{0u};
std::atomic<uint64_t> ffxMemoryAliasableBytes{0u};
std::atomic<uint32_t> ffxMemoryQueries{0u};
std::atomic<uint32_t> ffxMemoryOwner{0u}; // leaf + 1 of the module whose answered queries are counted
};
// Whether `leaf` is the module whose calls a summary counts: the first one seen, and
// from then on only it. A title that goes through the loader has the same call
// arrive at two hooked modules; a count is a count of calls and not of hooks.
inline bool Owns(std::atomic<uint32_t>& ownerSlot, uint32_t leaf) noexcept {
const uint32_t me = leaf + 1u;
uint32_t owner = ownerSlot.load(std::memory_order_relaxed);
if (owner == 0u && ownerSlot.compare_exchange_strong(owner, me, std::memory_order_relaxed)) {
owner = me;
}
return owner == me;
}
// sl::DLSSOptions, chained into slEvaluateFeature's inputs. The caller has already
// matched the struct's GUID and found its version at least 1 (fl_sl_inputs.h).
inline void ObserveDlssOptions(const sl::DLSSOptions& o, Accumulators& a) noexcept {
const size_t version = o.structVersion;
if (version < sl::kStructVersion1) {
return;
}
a.dlssStructVersion.store(version > 0xFFFFu ? 0xFFFFu : static_cast<uint32_t>(version), std::memory_order_relaxed);
a.dlssOptionsSeen.fetch_add(1u, std::memory_order_relaxed);
// Version 1's members. A size the game left at INVALID_UINT, or one no display has, is "not given".
const uint32_t w = o.outputWidth;
const uint32_t h = o.outputHeight;
const bool sized = w != 0u && h != 0u && w <= 0xFFFFu && h <= 0xFFFFu;
a.dlssOutputWidth.store(sized ? w : 0u, std::memory_order_relaxed);
a.dlssOutputHeight.store(sized ? h : 0u, std::memory_order_relaxed);
a.dlssPreExposureBits.store(Usable(o.preExposure) ? std::bit_cast<uint32_t>(o.preExposure) : FL_ADV_FLOAT_NONE,
std::memory_order_relaxed);
a.dlssExposureScaleBits.store(Usable(o.exposureScale) ? std::bit_cast<uint32_t>(o.exposureScale)
: FL_ADV_FLOAT_NONE,
std::memory_order_relaxed);
uint64_t presets = static_cast<uint64_t>(PresetPlusOne(o.dlaaPreset)) |
(static_cast<uint64_t>(PresetPlusOne(o.qualityPreset)) << 8) |
(static_cast<uint64_t>(PresetPlusOne(o.balancedPreset)) << 16) |
(static_cast<uint64_t>(PresetPlusOne(o.performancePreset)) << 24) |
(static_cast<uint64_t>(PresetPlusOne(o.ultraPerformancePreset)) << 32);
uint32_t booleans = BooleanPlusOne(o.colorBuffersHDR);
// Version 2 added two members; a version-1 struct ends before them.
if (version >= sl::kStructVersion2) {
presets |= static_cast<uint64_t>(PresetPlusOne(o.ultraQualityPreset)) << 40;
booleans |= static_cast<uint32_t>(BooleanPlusOne(o.useAutoExposure)) << 8;
}
// Version 3 added one.
if (version >= sl::kStructVersion3) {
booleans |= static_cast<uint32_t>(BooleanPlusOne(o.alphaUpscalingEnabled)) << 16;
}
a.dlssPresets.store(presets, std::memory_order_relaxed);
a.dlssBooleans.store(booleans, std::memory_order_relaxed);
NoteBits(a.validMask, FL_ADV_VALID_DLSS_OPTIONS);
}
// The ffx upscale dispatch, beyond the two sizes the frame record already has.
//
// ONE MODULE'S DISPATCHES ARE COUNTED (Owns): the first module seen owns the
// accumulators and the other's calls are passed over.
inline void ObserveFfxUpscale(uint32_t leaf, const ffxDispatchDescUpscale& d, Accumulators& a) noexcept {
if (!Owns(a.ffxOwner, leaf)) {
return;
}
a.ffxDispatches.fetch_add(1u, std::memory_order_relaxed);
const bool sharpening = ByteIsSet(d.enableSharpening);
NoteBits(a.ffxSharpenSeen, sharpening ? 2u : 1u);
if (sharpening && Usable(d.sharpness)) {
KeepMin(a.ffxSharpnessMinBits, d.sharpness);
KeepMax(a.ffxSharpnessMaxBits, d.sharpness);
}
if (Usable(d.jitterOffset.x) && Usable(d.jitterOffset.y)) {
KeepMax(a.ffxJitterMaxXBits, Magnitude(d.jitterOffset.x));
KeepMax(a.ffxJitterMaxYBits, Magnitude(d.jitterOffset.y));
}
if (Usable(d.preExposure)) {
KeepMin(a.ffxPreExposureMinBits, d.preExposure);
KeepMax(a.ffxPreExposureMaxBits, d.preExposure);
}
if (Usable(d.cameraNear)) {
a.ffxNearBits.store(std::bit_cast<uint32_t>(d.cameraNear), std::memory_order_relaxed);
}
if (Usable(d.cameraFar)) {
a.ffxFarBits.store(std::bit_cast<uint32_t>(d.cameraFar), std::memory_order_relaxed);
}
// The field of view as a range (owner decision D114): the lowest and the highest, never a series.
if (Usable(d.cameraFovAngleVertical) && d.cameraFovAngleVertical > 0.0f) {
KeepMin(a.ffxFovMinBits, d.cameraFovAngleVertical);
KeepMax(a.ffxFovMaxBits, d.cameraFovAngleVertical);
}
if (d.flags != 0u) {
NoteBits(a.ffxFlagsSeen, d.flags);
}
if (ByteIsSet(d.reset)) {
a.ffxResets.fetch_add(1u, std::memory_order_relaxed);
}
// Milliseconds, as the game reports them. A value outside (0, 10 s) is not a frame time.
if (Usable(d.frameTimeDelta) && d.frameTimeDelta > 0.0f && d.frameTimeDelta < 10000.0f) {
a.ffxFrameTimeCount.fetch_add(1u, std::memory_order_relaxed);
a.ffxFrameTimeSumUs.fetch_add(static_cast<uint64_t>(d.frameTimeDelta * 1000.0f), std::memory_order_relaxed);
}
NoteBits(a.validMask, FL_ADV_VALID_FFX_UPSCALE);
}
// The upscaler's own memory, from the struct an answered ffxQuery wrote.
inline void ObserveFfxMemory(const FfxApiEffectMemoryUsage& m, Accumulators& a) noexcept {
a.ffxMemoryTotalBytes.store(m.totalUsageInBytes, std::memory_order_relaxed);
a.ffxMemoryAliasableBytes.store(m.aliasableUsageInBytes, std::memory_order_relaxed);
a.ffxMemoryQueries.fetch_add(1u, std::memory_order_relaxed);
NoteBits(a.validMask, FL_ADV_VALID_FFX_MEMORY);
}
// An ffxQuery the vendor answered OK: when it is the upscaler's memory query, either
// version, what it wrote through the game's own out-pointer is kept. Every other
// query type is passed over with only its header's type read. One module's
// queries are counted, as one module's dispatches are.
inline void ObserveFfxMemoryQuery(uint32_t leaf, const ffxQueryDescHeader* desc, Accumulators& a) noexcept {
if (desc == nullptr) {
return;
}
const FfxApiEffectMemoryUsage* usage = nullptr;
if (desc->type == FFX_API_QUERY_DESC_TYPE_UPSCALE_GPU_MEMORY_USAGE) {
const auto& q = *reinterpret_cast<const ffxQueryDescUpscaleGetGPUMemoryUsage*>(desc);
usage = q.gpuMemoryUsageUpscaler;
} else if (desc->type == FFX_API_QUERY_DESC_TYPE_UPSCALE_GPU_MEMORY_USAGE_V2) {
const auto& q = *reinterpret_cast<const ffxQueryDescUpscaleGetGPUMemoryUsageV2*>(desc);
usage = q.gpuMemoryUsageUpscaler;
}
if (usage != nullptr && Owns(a.ffxMemoryOwner, leaf)) {
ObserveFfxMemory(*usage, a);
}
}
// A NEW REQUEST: the summaries start afresh, so a session's ranges, masks and
// counts are its own and not those of the session before it in the same game.
// THE WATCHDOG'S. A detour running beside it loses nothing that matters: what it
// stores is of the call it is in, which belongs to the request that is starting.
// The two owners stay - which module's calls are counted is a fact about the
// process, not about a session.
inline void Reset(Accumulators& a) noexcept {
const auto relaxed = std::memory_order_relaxed;
a.validMask.store(0u, relaxed);
a.dlssStructVersion.store(0u, relaxed);
a.dlssOptionsSeen.store(0u, relaxed);
a.dlssOutputWidth.store(0u, relaxed);
a.dlssOutputHeight.store(0u, relaxed);
a.dlssPreExposureBits.store(FL_ADV_FLOAT_NONE, relaxed);
a.dlssExposureScaleBits.store(FL_ADV_FLOAT_NONE, relaxed);
a.dlssPresets.store(0u, relaxed);
a.dlssBooleans.store(0u, relaxed);
a.ffxDispatches.store(0u, relaxed);
a.ffxSharpenSeen.store(0u, relaxed);
a.ffxSharpnessMinBits.store(FL_ADV_FLOAT_NONE, relaxed);
a.ffxSharpnessMaxBits.store(FL_ADV_FLOAT_NONE, relaxed);
a.ffxJitterMaxXBits.store(FL_ADV_FLOAT_NONE, relaxed);
a.ffxJitterMaxYBits.store(FL_ADV_FLOAT_NONE, relaxed);
a.ffxPreExposureMinBits.store(FL_ADV_FLOAT_NONE, relaxed);
a.ffxPreExposureMaxBits.store(FL_ADV_FLOAT_NONE, relaxed);
a.ffxNearBits.store(FL_ADV_FLOAT_NONE, relaxed);
a.ffxFarBits.store(FL_ADV_FLOAT_NONE, relaxed);
a.ffxFovMinBits.store(FL_ADV_FLOAT_NONE, relaxed);
a.ffxFovMaxBits.store(FL_ADV_FLOAT_NONE, relaxed);
a.ffxFlagsSeen.store(0u, relaxed);
a.ffxResets.store(0u, relaxed);
a.ffxFrameTimeCount.store(0u, relaxed);
a.ffxFrameTimeSumUs.store(0u, relaxed);
a.ffxMemoryTotalBytes.store(0u, relaxed);
a.ffxMemoryAliasableBytes.store(0u, relaxed);
a.ffxMemoryQueries.store(0u, relaxed);
}
// Copies the accumulators into region 5, under the request they answer. THE
// WATCHDOG'S, and only the watchdog's: one writer, so the seqlock is odd -> stores
// -> even with no compare-exchange. The frame-time pair is drained, so each
// publication carries the dispatches since the last one.
inline void Publish(Accumulators& a, FlAdvancedState* region, uint32_t request, uint64_t qpc) noexcept {
if (region == nullptr) {
return;
}
const auto put32 = [](uint32_t& field, uint32_t value) noexcept {
std::atomic_ref<uint32_t>{field}.store(value, std::memory_order_relaxed);
};
const auto put64 = [](uint64_t& field, uint64_t value) noexcept {
std::atomic_ref<uint64_t>{field}.store(value, std::memory_order_relaxed);
};
const auto put8 = [](uint8_t& field, uint8_t value) noexcept {
std::atomic_ref<uint8_t>{field}.store(value, std::memory_order_relaxed);
};
const auto relaxed = std::memory_order_relaxed;
std::atomic_ref<uint32_t> seq{region->seq};
const uint32_t odd = seq.load(relaxed) | 1u;
seq.store(odd, std::memory_order_release);
put32(region->validMask, a.validMask.load(relaxed));
put32(region->request, request);
put64(region->sampleQpc, qpc);
put32(region->dlssStructVersion, a.dlssStructVersion.load(relaxed));
put32(region->dlssOptionsSeen, a.dlssOptionsSeen.load(relaxed));
put32(region->dlssOutputWidth, a.dlssOutputWidth.load(relaxed));
put32(region->dlssOutputHeight, a.dlssOutputHeight.load(relaxed));
put32(region->dlssPreExposureBits, a.dlssPreExposureBits.load(relaxed));
put32(region->dlssExposureScaleBits, a.dlssExposureScaleBits.load(relaxed));
const uint64_t presets = a.dlssPresets.load(relaxed);
for (uint32_t i = 0; i < 6u; ++i) {
put8(region->dlssPresets[i], static_cast<uint8_t>(presets >> (8u * i)));
}
const uint32_t booleans = a.dlssBooleans.load(relaxed);
put8(region->dlssColorBuffersHdr, static_cast<uint8_t>(booleans));
put8(region->dlssAutoExposure, static_cast<uint8_t>(booleans >> 8));
put8(region->dlssAlphaUpscaling, static_cast<uint8_t>(booleans >> 16));
put32(region->ffxDispatches, a.ffxDispatches.load(relaxed));
put32(region->ffxSharpenSeen, a.ffxSharpenSeen.load(relaxed));
put32(region->ffxSharpnessMinBits, a.ffxSharpnessMinBits.load(relaxed));
put32(region->ffxSharpnessMaxBits, a.ffxSharpnessMaxBits.load(relaxed));
put32(region->ffxJitterMaxXBits, a.ffxJitterMaxXBits.load(relaxed));
put32(region->ffxJitterMaxYBits, a.ffxJitterMaxYBits.load(relaxed));
put32(region->ffxPreExposureMinBits, a.ffxPreExposureMinBits.load(relaxed));
put32(region->ffxPreExposureMaxBits, a.ffxPreExposureMaxBits.load(relaxed));
put32(region->ffxNearBits, a.ffxNearBits.load(relaxed));
put32(region->ffxFarBits, a.ffxFarBits.load(relaxed));
put32(region->ffxFovMinBits, a.ffxFovMinBits.load(relaxed));
put32(region->ffxFovMaxBits, a.ffxFovMaxBits.load(relaxed));
put32(region->ffxFlagsSeen, a.ffxFlagsSeen.load(relaxed));
put32(region->ffxResets, a.ffxResets.load(relaxed));
const uint64_t sumUs = a.ffxFrameTimeSumUs.exchange(0u, relaxed);
put32(region->ffxFrameTimeCount, a.ffxFrameTimeCount.exchange(0u, relaxed));
put32(region->ffxFrameTimeSumUs, sumUs > 0xFFFFFFFFull ? 0xFFFFFFFFu : static_cast<uint32_t>(sumUs));
put64(region->ffxMemoryTotalBytes, a.ffxMemoryTotalBytes.load(relaxed));
put64(region->ffxMemoryAliasableBytes, a.ffxMemoryAliasableBytes.load(relaxed));
put32(region->ffxMemoryQueries, a.ffxMemoryQueries.load(relaxed));
std::atomic_ref<uint32_t> samples{region->samples};
samples.store(samples.load(relaxed) + 1u, relaxed);
seq.store(odd + 1u, std::memory_order_release);
}
} // namespace fl::adv
#endif // FRAMELEDGER_FL_ADV_FIELDS_H
@@ -99,6 +99,10 @@ struct ScanResult {
// was eMaxPerformance; that is 1 in the numbering this byte carries.)
uint8_t quality = 0xFFu;
bool qualityFound = false;
// The first readable sl::DLSSOptions of the walk - the struct `quality` came from - or null. Advanced metrics
// (fl_adv_fields.h) reads the rest of it, and only while the Agent asked; this walk reads `mode` and nothing more.
const sl::DLSSOptions* options = nullptr;
};
// DLSSMode -> the byte fl_shm.h carries. Never 0, for any input.
@@ -234,7 +238,8 @@ inline ScanResult FindScalingInputExtent(const sl::BaseStructure** inputs, uint3
// the one these headers describe -- which is what makes matching
// on `>=` correct here rather than optimistic. The struct is
// kStructVersion3 today and grew by appending.
out.quality = QualityFromMode(static_cast<const sl::DLSSOptions*>(s)->mode);
out.options = static_cast<const sl::DLSSOptions*>(s);
out.quality = QualityFromMode(out.options->mode);
out.qualityFound = true;
}
}
+49 -2
View File
@@ -46,6 +46,7 @@
#include <cstdio>
#include <cstring>
#include <fl_ac_rules.h>
#include <fl_adv_fields.h>
#include <fl_d3d12_vtable.h>
#include <fl_dxgi_count.h>
#include <fl_dxgi_vtable.h>
@@ -445,6 +446,16 @@ struct SwapChainSlot {
// Region 4 (fl_shm.h, layout 4, beta.10): set in InitThread beside g_state, written only through PublishDisplay.
FlDisplayState* g_display = nullptr;
// ADVANCED METRICS (fl_shm.h region 5, layout 5; owner decision D111). `g_advancedRequested` is the watchdog's copy of
// FlControlBlock::advancedRequested, and the ONLY thing a detour consults: while it is 0 no hook reads one member more
// than it did before the option existed, and the watchdog never writes the region. `g_adv` is what the detours
// accumulate (fl_adv_fields.h); `g_advanced` is the region, written by the watchdog alone. `g_advancedSeen` is the
// watchdog's own: the last non-zero request it acted on, so that a new one starts the summaries afresh.
FlAdvancedState* g_advanced = nullptr;
std::atomic<uint32_t> g_advancedRequested{0u};
uint32_t g_advancedSeen = 0u;
alignas(64) fl::adv::Accumulators g_adv;
// Which chain region 4 describes: the largest back buffer, and one silent for 2 s gives way (fl_shm.h §Region 4).
std::atomic<uint32_t> g_displayChain{0};
std::atomic<uint64_t> g_displayArea{0};
@@ -1690,6 +1701,12 @@ sl::Result STDMETHODCALLTYPE Hook_SlEvaluateFeature(sl::Feature feature, const s
if (scan.qualityFound) {
g_dlssQuality.store(scan.quality, std::memory_order_release);
}
// The rest of the options the title chained (output size, presets, exposure, the three Booleans) -
// Advanced metrics, and only while the Agent asked for them (D111). The same struct of the same
// argument, read at the version it declares (fl_adv_fields.h).
if (scan.options != nullptr && g_advancedRequested.load(std::memory_order_relaxed) != 0u) {
fl::adv::ObserveDlssOptions(*scan.options, g_adv);
}
}
})
// ALWAYS exactly once, on every path including the fault path, with every
@@ -1799,10 +1816,14 @@ void NoteFfxExtent(const FfxApiDimensions2D& size) noexcept {
// The answer one query returned, kept for the dispatch arm. Read only after the vendor answered OK; a mode, a size or a
// ratio the byte or the match cannot carry is not kept.
void ObserveFfxQuery(const ffxQueryDescHeader* desc) noexcept {
void ObserveFfxQuery(uint32_t leaf, const ffxQueryDescHeader* desc) noexcept {
if (desc == nullptr) {
return;
}
// The upscaler's own memory, when the title asks for it - Advanced metrics, only while the Agent asked (D111).
if (g_advancedRequested.load(std::memory_order_relaxed) != 0u) {
fl::adv::ObserveFfxMemoryQuery(leaf, desc, g_adv);
}
if (desc->type == FFX_API_QUERY_DESC_TYPE_UPSCALE_GETRENDERRESOLUTIONFROMQUALITYMODE) {
const auto* q = reinterpret_cast<const ffxQueryDescUpscaleGetRenderResolutionFromQualityMode*>(desc);
if (q->qualityMode >= kFfxQualityModes || q->pOutRenderWidth == nullptr || q->pOutRenderHeight == nullptr) {
@@ -1887,6 +1908,13 @@ void ObserveFfxDispatch(uint32_t leaf, const ffxDispatchDescHeader* desc) noexce
std::memory_order_release);
g_ffxUpscaleLeaf.store(leaf + 1u, std::memory_order_relaxed);
g_ffxSeen.fetch_add(fl::slseen::kCountOne, std::memory_order_relaxed);
// The rest of the same descriptor (sharpening, jitter, exposure, the depth range, the field of view, flags,
// the frame time) - Advanced metrics, only while the Agent asked (D111). Not on the FSR 3.0 host's route:
// its legacy descriptor is vouched for through renderSize and no further (17_HOOK_ENGINE §Which struct
// version carries which field).
if (g_advancedRequested.load(std::memory_order_relaxed) != 0u) {
fl::adv::ObserveFfxUpscale(leaf, *up, g_adv);
}
break;
}
case FFX_API_DISPATCH_DESC_TYPE_FRAMEGENERATION_PREPARE:
@@ -1974,7 +2002,7 @@ ffxReturnCode_t Hook_FfxQueryT(ffxContext* context, ffxQueryDescHeader* desc) {
const ffxReturnCode_t rc = g_origFfxQuery[Leaf](context, desc);
FL_HOOK_GUARD({
if (rc == FFX_API_RETURN_OK && MayObserve()) {
ObserveFfxQuery(desc);
ObserveFfxQuery(Leaf, desc);
}
})
return rc;
@@ -2649,6 +2677,24 @@ DWORD WatchdogLoop() noexcept {
FlushLog();
}
// ADVANCED METRICS (owner decision D111; fl_shm.h region 5). The Agent's word, copied to the flag the detours
// read; and, only while it is set, what they accumulated copied into the region. This thread is the region's
// one writer. With the word at 0 nothing more is read in any hook and the region is never touched. A request
// not seen before is a new session's: the summaries start afresh BEFORE the detours are let in, so a range or
// a count never spans two sessions of a game that kept running.
std::atomic_ref<uint32_t> advancedReq{g_control->advancedRequested};
const uint32_t advancedNow = advancedReq.load(std::memory_order_acquire);
if (advancedNow != 0u && advancedNow != g_advancedSeen) {
fl::adv::Reset(g_adv);
g_advancedSeen = advancedNow;
}
g_advancedRequested.store(advancedNow != 0u ? 1u : 0u, std::memory_order_relaxed);
if (advancedNow != 0u) {
LARGE_INTEGER advancedQpc{};
QueryPerformanceCounter(&advancedQpc);
fl::adv::Publish(g_adv, g_advanced, advancedNow, static_cast<uint64_t>(advancedQpc.QuadPart));
}
// The in-process stop, for a title that is NOT presenting (menu, hung,
// alt-tabbed) -- the case the present path cannot reach. Same order as the
// Agent's stop: before any install.
@@ -3545,6 +3591,7 @@ DWORD WINAPI InitThread(LPVOID) noexcept {
g_state = reinterpret_cast<FlWriterState*>(static_cast<unsigned char*>(g_base) + FL_SHM_WRITER_OFFSET);
g_control = reinterpret_cast<FlControlBlock*>(static_cast<unsigned char*>(g_base) + FL_SHM_CONTROL_OFFSET);
g_display = reinterpret_cast<FlDisplayState*>(static_cast<unsigned char*>(g_base) + FL_SHM_DISPLAY_OFFSET);
g_advanced = reinterpret_cast<FlAdvancedState*>(static_cast<unsigned char*>(g_base) + FL_SHM_ADVANCED_OFFSET);
// The supervision clock starts HERE, when the mapping is published -- not at
// first present. 07_IPC is explicit that a capture side no Agent ever adopts
// is inert from the beginning rather than enjoying a grace window.
+18 -9
View File
@@ -829,11 +829,15 @@ struct alignas(64) FlControlBlock {
// last acted on, so the Agent never has to clear anything in a block it is the
// sole writer of. Took reserved[0]; additive, no layout bump.
uint32_t logFlushRequested; // @16
// ADVANCED METRICS REQUESTED (2026-11-11, owner decision D111). 1 while the session this ring belongs to records
// Advanced metrics, 0 otherwise - and the Agent writes it UNCONDITIONALLY at attach, before its first guard
// result, because this block outlives a session and a value left by the last one would be a request nobody
// made. While it is 0 the Overlay reads no field and installs no hook beyond what it did before the option
// existed, and region 5 stays zero. Took reserved[0]; additive within the block.
// ADVANCED METRICS REQUESTED (2026-11-11, owner decision D111). 0 while the session this ring belongs to does not
// record Advanced metrics; otherwise THAT SESSION'S REQUEST, a non-zero value no session of this ring used before
// - and the Agent writes it UNCONDITIONALLY at attach, before its first guard result, because this block outlives
// a session and a value left by the last one would be a request nobody made. While it is 0 the Overlay reads no
// field and installs no hook beyond what it did before the option existed, and writes nothing to region 5. A
// value the watchdog has not seen before is a NEW request: the summaries start afresh, so a session's ranges and
// counts are its own, and every publication names the request it answers (FlAdvancedState::request) - which is
// how a reader tells its session's region from the one the session before left. Took reserved[0]; additive
// within the block.
uint32_t advancedRequested; // @20
uint32_t reserved[10]; // @24..63 must be zero
};
@@ -901,9 +905,14 @@ struct alignas(64) FlDisplayState {
// (CLAUDE.md rule 4), by the rule of 17_HOOK_ENGINE §Which struct version carries which field: a member is read only
// where the upstream tags prove the game's struct has it.
//
// OFF MEANS OFF (D111). Nothing here is written, and nothing more is read in any hook, unless
// FlControlBlock.advancedRequested is 1. A ring whose session does not record Advanced metrics has this region zero
// from end to end, and `validMask` zero says "nothing was read" - never "the game used none of it".
// OFF MEANS OFF (D111). Nothing here is written, and nothing more is read in any hook, while
// FlControlBlock.advancedRequested is 0. A ring nobody ever asked has this region zero from end to end, and
// `validMask` zero says "nothing was read" - never "the game used none of it".
//
// A PUBLICATION ANSWERS ONE REQUEST (2026-11-12). The game outlives a session, and so would a range or a count kept
// inside it: the watchdog starts its summaries afresh at a request it has not seen, and `request` names the one a
// publication answers. After an "off" the region keeps its last publication, untouched - a reader that asks again
// reads nothing until one names ITS request.
//
// ONE WRITER, ONCE A SECOND. The detours keep process-local accumulators (relaxed atomics); the WATCHDOG copies them
// here at its 1 Hz tick. No game thread writes this region, so the seqlock has a single writer and needs no
@@ -950,7 +959,7 @@ struct alignas(64) FlAdvancedState {
uint32_t seq; // @0 seqlock: odd while the watchdog is inside, +2 per publication
uint32_t validMask; // @4 FlAdvancedValid
uint32_t samples; // @8 publications (wraps)
uint32_t reserved0; // @12 must be zero
uint32_t request; // @12 the FlControlBlock::advancedRequested this publication answers
uint64_t sampleQpc; // @16 QueryPerformanceCounter at the last publication
uint32_t reservedHeader[10]; // @24..63 must be zero
+241
View File
@@ -16,6 +16,8 @@
#include <windows.h>
#include <algorithm>
#include <atomic>
#include <bit>
#include <catch2/catch_test_macros.hpp>
#include <catch2/reporters/catch_reporter_event_listener.hpp>
#include <catch2/reporters/catch_reporter_registrars.hpp>
@@ -6639,3 +6641,242 @@ TEST_CASE("D33 -- the excepted family's module loading late does not stop the Ov
DeleteFileW(decoy.c_str());
RemoveDirectoryW(dir.c_str());
}
// ===========================================================================
// Advanced metrics, train B (0.1.0-beta.40; owner decisions D111 and D115): region 5.
//
// THE CLAIM IS THE OFF HALF. That the Overlay can read a few more members of a descriptor it already reads is a small
// thing; that it reads NONE of them while the Agent has not asked is what the owner decided, and no test of the header
// alone can show it - the gate is a word in the control block, consulted in the detours of an injected DLL. So each
// case below runs a target that SENDS everything (--advanced, the memory query) and looks at the region with the word
// at zero first.
// ===========================================================================
namespace {
// What hook-harness sends under --advanced (main.cpp, kAdv*) and what the ffx stub answers the memory query with
// (stub_ffx_leaf.inl). Stated again rather than shared: a value changed on one side alone must fail here.
constexpr uint32_t kAdvDlssOutputW = 2560u;
constexpr uint32_t kAdvDlssOutputH = 1440u;
constexpr float kAdvDlssPreExposure = 1.5f;
constexpr float kAdvDlssExposureScale = 0.75f;
constexpr float kAdvFfxSharpness = 0.35f;
constexpr float kAdvFfxPreExposure = 1.25f;
constexpr float kAdvFfxNear = 0.1f;
constexpr float kAdvFfxFar = 1000.0f;
constexpr float kAdvFfxFovLow = 0.9f;
constexpr float kAdvFfxFovHigh = 1.1f;
constexpr uint32_t kAdvFfxFrameTimeUs = 16000u;
constexpr uint64_t kAdvMemoryTotal = 123456789ull;
constexpr uint64_t kAdvMemoryAliasable = 23456789ull;
fl::FlAdvancedState* RegionFive(const MappedRing& r) {
return reinterpret_cast<fl::FlAdvancedState*>(static_cast<unsigned char*>(r.base) + FL_SHM_ADVANCED_OFFSET);
}
// Every byte of the region, not the fields a test thought to name.
bool RegionFiveIsZero(const MappedRing& r) {
const auto* p = static_cast<const unsigned char*>(r.base) + FL_SHM_ADVANCED_OFFSET;
for (size_t i = 0; i < sizeof(fl::FlAdvancedState); ++i) {
if (p[i] != 0u) {
return false;
}
}
return true;
}
// A consistent copy of region 5 that answers `request`, the way the Agent takes one - waited for (bounded), because
// the watchdog publishes once a second: newer than `afterSamples`, and carrying every bit of `wantMask`.
bool ReadAdvanced(const MappedRing& r, uint32_t request, fl::FlAdvancedState& out, uint32_t afterSamples = 0u,
uint32_t wantMask = 0u) {
fl::FlAdvancedState* region = RegionFive(r);
for (int i = 0; i < 200; ++i) {
++r.ctl->guardTicks;
std::atomic_ref<uint32_t> seq{region->seq};
const uint32_t before = seq.load(std::memory_order_acquire);
if (before != 0u && (before & 1u) == 0u) {
fl::FlAdvancedState copy{};
std::memcpy(&copy, region, sizeof(copy));
std::atomic_thread_fence(std::memory_order_seq_cst);
if (seq.load(std::memory_order_acquire) == before && copy.request == request &&
copy.samples > afterSamples && (copy.validMask & wantMask) == wantMask) {
out = copy;
return true;
}
}
Sleep(50);
}
return false;
}
void SetAdvancedRequest(const MappedRing& r, uint32_t request) {
std::atomic_ref<uint32_t>{r.ctl->advancedRequested}.store(request, std::memory_order_release);
}
// Keeps the supervision clock alive for `ms`, the way a session's loop does.
void TickFor(const MappedRing& r, int ms) {
for (int waited = 0; waited < ms; waited += 50) {
++r.ctl->guardTicks;
Sleep(50);
}
}
uint32_t BitsOf(float v) {
return std::bit_cast<uint32_t>(v);
}
// What 0.1.0-beta.41 and beta.42 fill: declared now, written by nothing in this release.
bool LaterGroupsAreZero(const fl::FlAdvancedState& a) {
bool zero = a.ffxFgConfigures == 0u && a.ffxFgEnabledSeen == 0u && a.ffxFgFlagsSeen == 0u &&
a.slConstantsCalls == 0u && a.slResets == 0u && a.slFlagsSeenTrue == 0u && a.slFlagsSeenFalse == 0u;
for (uint32_t i = 0; i < FL_ADV_FEATURE_SLOTS * FL_ADV_FEATURE_WORDS; ++i) {
zero = zero && a.features[i] == 0u;
}
return zero;
}
} // namespace
TEST_CASE("region 5 stays empty until the Agent asks, then carries what an FSR title told its upscaler, per request",
"[guard][inject][shm][advanced]") {
// ONE TARGET, FOUR STRETCHES, because the claims are about transitions: not asked -> asked -> not asked -> asked
// again. The target sends the same thing throughout - every extra member of the UPSCALE descriptor and a memory
// query before each dispatch - so whatever differs between two stretches is the Overlay's doing.
Child child;
REQUIRE(StartHarness(child, L"--real --ffx-topology 2x --advanced --ffx-memory-query v2 --hold-presenting-ffx 60"));
ResetFake();
g.modules = {"kernel32.dll"};
g.scanSet = {child.pi.dwProcessId};
REQUIRE(GuardedInjectWithSources(child.pi.dwProcessId, FL_OVERLAY_DLL, FakeSources()).Allowed());
MappedRing r;
REQUIRE(OpenRingFor(child.pi.dwProcessId, r));
REQUIRE(WaitForIdentityHook(r.st));
REQUIRE(WaitForHookFamily(r.st, static_cast<uint32_t>(fl::FL_HOOK_UPSCALER_QUALITY))); // ffxQuery is hooked
// ---- 1. NOT ASKED. Three watchdog ticks with both hooks live and the target sending everything.
const std::uint64_t atHooks = r.st->writeIndex;
TickFor(r, 3200);
INFO("writeIndex " << r.st->writeIndex << " (was " << atHooks << ") status " << r.st->status << " faults "
<< r.st->faultCount);
REQUIRE(r.st->writeIndex > atHooks + 30u); // the hooks ran: this is not a target that sent nothing
CHECK(r.ctl->advancedRequested == 0u);
CHECK(RegionFiveIsZero(r));
// ---- 2. ASKED. Within a tick or two the region answers THIS request with what the descriptor carried.
SetAdvancedRequest(r, 7u);
fl::FlAdvancedState a{};
REQUIRE(ReadAdvanced(r, 7u, a, 0u, fl::FL_ADV_VALID_FFX_UPSCALE | fl::FL_ADV_VALID_FFX_MEMORY));
// A few seconds of it, so the count is one a restart can be told from.
for (int i = 0; i < 20 && a.ffxDispatches < 300u; ++i) {
REQUIRE(ReadAdvanced(r, 7u, a, a.samples, fl::FL_ADV_VALID_FFX_UPSCALE | fl::FL_ADV_VALID_FFX_MEMORY));
}
INFO("mask 0x" << std::hex << a.validMask << std::dec << " dispatches " << a.ffxDispatches << " queries "
<< a.ffxMemoryQueries << " frameTime " << a.ffxFrameTimeCount << "/" << a.ffxFrameTimeSumUs
<< " samples " << a.samples);
REQUIRE(a.ffxDispatches >= 300u);
CHECK((a.validMask & fl::FL_ADV_VALID_DLSS_OPTIONS) == 0u); // an FSR title chains no DLSSOptions
CHECK(a.dlssOptionsSeen == 0u);
CHECK(a.sampleQpc != 0u);
CHECK(a.ffxSharpenSeen == 2u); // bit 1: seen ON, and never off
CHECK(a.ffxSharpnessMinBits == BitsOf(kAdvFfxSharpness));
CHECK(a.ffxSharpnessMaxBits == BitsOf(kAdvFfxSharpness));
CHECK(a.ffxJitterMaxXBits == BitsOf(0.3f)); // the largest magnitude of -0.25 and 0.3
CHECK(a.ffxJitterMaxYBits == BitsOf(0.4f)); // ... and of 0.4 and -0.1
CHECK(a.ffxPreExposureMinBits == BitsOf(kAdvFfxPreExposure));
CHECK(a.ffxPreExposureMaxBits == BitsOf(kAdvFfxPreExposure));
CHECK(a.ffxNearBits == BitsOf(kAdvFfxNear));
CHECK(a.ffxFarBits == BitsOf(kAdvFfxFar));
CHECK(a.ffxFovMinBits == BitsOf(kAdvFfxFovLow)); // a range, never a series (D114)
CHECK(a.ffxFovMaxBits == BitsOf(kAdvFfxFovHigh));
CHECK(a.ffxFlagsSeen == (1u << 2)); // FFX_UPSCALE_FLAG_NON_LINEAR_COLOR_PQ, the one flag the target sets
CHECK(a.ffxResets == 0u);
// The frame time: what was dispatched since the publication before, each one the 16 ms the target states.
CHECK(a.ffxFrameTimeCount != 0u);
CHECK(a.ffxFrameTimeSumUs == a.ffxFrameTimeCount * kAdvFfxFrameTimeUs);
// The memory the stub wrote through the target's own pointer - and counted once per query, though the loader
// hands the same query on to the leaf and both are hooked.
CHECK(a.ffxMemoryTotalBytes == kAdvMemoryTotal);
CHECK(a.ffxMemoryAliasableBytes == kAdvMemoryAliasable);
CHECK(a.ffxMemoryQueries != 0u);
CHECK(a.ffxMemoryQueries <= a.ffxDispatches + 2u);
CHECK(LaterGroupsAreZero(a));
// ---- 3. NOT ASKED AGAIN. Nothing more is read, and nothing more is written: the region is what it was.
SetAdvancedRequest(r, 0u);
TickFor(r, 2200); // the watchdog has seen the zero
fl::FlAdvancedState held{};
std::memcpy(&held, RegionFive(r), sizeof(held));
TickFor(r, 2500);
CHECK(std::memcmp(&held, RegionFive(r), sizeof(held)) == 0);
CHECK((held.seq & 1u) == 0u);
CHECK(held.request == 7u); // still naming the request it answered, which is how the next reader knows
// ---- 4. A SECOND SESSION of a target that kept running: a request the Overlay has not seen. Its first
// publication is its own - a count that starts again, not the three hundred and more of the session before.
SetAdvancedRequest(r, 8u);
fl::FlAdvancedState b{};
REQUIRE(ReadAdvanced(r, 8u, b));
INFO("second request: dispatches " << b.ffxDispatches << " samples " << b.samples << " after " << held.samples);
CHECK(b.samples > held.samples);
CHECK(b.ffxDispatches < 300u);
REQUIRE(ReadAdvanced(r, 8u, b, b.samples, fl::FL_ADV_VALID_FFX_UPSCALE | fl::FL_ADV_VALID_FFX_MEMORY));
CHECK(b.ffxFovMinBits == BitsOf(kAdvFfxFovLow));
CHECK(b.ffxMemoryTotalBytes == kAdvMemoryTotal);
CHECK(r.st->faultCount == 0u);
CHECK(r.st->status == fl::FL_STATUS_READY);
}
TEST_CASE("region 5 carries the DLSS options a title chains into its evaluation, and only while asked",
"[guard][inject][shm][advanced]") {
Child child;
REQUIRE(StartHarness(child, L"--real --advanced --hold-presenting-upscaled 30"));
ResetFake();
g.modules = {"kernel32.dll"};
g.scanSet = {child.pi.dwProcessId};
REQUIRE(GuardedInjectWithSources(child.pi.dwProcessId, FL_OVERLAY_DLL, FakeSources()).Allowed());
MappedRing r;
REQUIRE(OpenRingFor(child.pi.dwProcessId, r));
REQUIRE(WaitForIdentityHook(r.st));
// Not asked: the evaluation is hooked, the options are chained into every one, and none of it is kept.
const std::uint64_t atHooks = r.st->writeIndex;
TickFor(r, 2500);
REQUIRE(r.st->writeIndex > atHooks + 30u);
CHECK(RegionFiveIsZero(r));
SetAdvancedRequest(r, 1u);
fl::FlAdvancedState a{};
REQUIRE(ReadAdvanced(r, 1u, a, 0u, fl::FL_ADV_VALID_DLSS_OPTIONS));
INFO("mask 0x" << std::hex << a.validMask << std::dec << " version " << a.dlssStructVersion << " seen "
<< a.dlssOptionsSeen << " output " << a.dlssOutputWidth << "x" << a.dlssOutputHeight);
CHECK(a.validMask == static_cast<uint32_t>(fl::FL_ADV_VALID_DLSS_OPTIONS)); // no ffx call in this target
CHECK(a.dlssStructVersion == 3u); // the version these headers declare, which is what entitles the tail
CHECK(a.dlssOptionsSeen != 0u);
CHECK(a.dlssOutputWidth == kAdvDlssOutputW);
CHECK(a.dlssOutputHeight == kAdvDlssOutputH);
CHECK(a.dlssPreExposureBits == BitsOf(kAdvDlssPreExposure));
CHECK(a.dlssExposureScaleBits == BitsOf(kAdvDlssExposureScale));
// Presets as the vendor's value PLUS ONE, so the vendor's own 0 ("default") is told from "not read": DLAA K (11),
// Quality J (10), Balanced default (0), Performance M (13), Ultra Performance L (12), Ultra Quality default (0).
CHECK(a.dlssPresets[0] == 12u);
CHECK(a.dlssPresets[1] == 11u);
CHECK(a.dlssPresets[2] == 1u);
CHECK(a.dlssPresets[3] == 14u);
CHECK(a.dlssPresets[4] == 13u);
CHECK(a.dlssPresets[5] == 1u);
// Booleans likewise: eFalse is 1, eTrue 2.
CHECK(a.dlssColorBuffersHdr == 1u);
CHECK(a.dlssAutoExposure == 2u);
CHECK(a.dlssAlphaUpscaling == 2u);
CHECK(a.ffxDispatches == 0u);
CHECK(a.ffxSharpnessMinBits == FL_ADV_FLOAT_NONE); // a float nobody saw is "none", never 0.0
CHECK(a.ffxMemoryQueries == 0u);
CHECK(LaterGroupsAreZero(a));
CHECK(r.st->faultCount == 0u);
CHECK(r.st->status == fl::FL_STATUS_READY);
}
+1 -1
View File
@@ -113,7 +113,7 @@ int main() {
FL_ADV_FIELD(seq);
FL_ADV_FIELD(validMask);
FL_ADV_FIELD(samples);
FL_ADV_FIELD(reserved0);
FL_ADV_FIELD(request);
FL_ADV_FIELD(sampleQpc);
FL_ADV_FIELD(reservedHeader);
FL_ADV_FIELD(dlssStructVersion);
@@ -140,6 +140,12 @@ add_test(NAME fl_ffx_resolve COMMAND hook-harness --probe-ffx-resolve)
# could only approximate these shapes. Here they are exact and cost microseconds.
add_test(NAME fl_sl_inputs COMMAND hook-harness --probe-sl-inputs)
# fl_adv_fields.h (Advanced metrics, train B): the members a hooked call's struct carries beyond what the frame
# record holds. A unit probe for the same reason as fl_sl_inputs, and one more: the property that matters most -
# a struct of an OLDER version than the vendored header declares must not have its tail read (owner decision D115,
# 17_HOOK_ENGINE §Which struct version carries which field) - needs a struct no fixture title can be made to send.
add_test(NAME fl_adv_fields COMMAND hook-harness --probe-adv-fields)
# The word RecordPresent drains. Its FIELD BOUNDARIES are static_asserts inside
# fl_sl_seen.h -- integer algebra, checked in every TU that includes the header, so
# no test can forget them and a 16-million-iteration loop proving a carry cannot go
+385 -13
View File
@@ -112,6 +112,15 @@
// tagged 1280x720 extent is Quality's answer, so the record must name Quality and nothing else.
// --ffx-no-prepare drop the PREPARE dispatch: the frame-generation-OFF shape, where
// the Overlay must count UPSCALE dispatches instead
// --advanced send what Advanced metrics reads (train B, 0.1.0-beta.40): --hold-presenting-upscaled chains an
// sl::DLSSOptions into slEvaluateFeature's inputs, --hold-presenting-ffx fills the rest of the
// UPSCALE descriptor (sharpening, jitter, exposure, depth range, field of view, flags, frame time).
// The values are the kAdv* constants below; the injected fl_guard cases assert them
// --ffx-memory-query v1|v2
// before every UPSCALE, ask the entry module ffxQuery how much memory the upscaler holds, in
// the descriptor of ffx-api 1.1.2 (v1) or 2.0 (v2); the stub answers kAdvMemory*
// --probe-adv-fields
// fl_adv_fields.h alone: versions, sentinels, summaries, the publication (ctest fl_adv_fields)
//
// This list was incomplete for several modes before 2026-08-15 and is not the
// authority: the strcmp chain in main() is. Kept in step because a reader looking
@@ -131,6 +140,7 @@
#include <vector>
#include "dxr_raygen_dxil.h"
#include "fl_adv_fields.h"
#include "fl_d3d12_vtable.h"
#include "fl_dxgi_count.h"
#include "fl_dxgi_vtable.h"
@@ -1982,6 +1992,268 @@ bool ProbeSlInputs() {
return g_failures == 0;
}
// fl_adv_fields.h - what a hooked game told its upscaler (Advanced metrics, train B) - against the shapes a title can
// send. A UNIT PROBE, as --probe-sl-inputs is: what matters here is a struct of an OLDER VERSION than these headers
// declare, whose tail must not be read (owner decision D115), and the vendors' own sentinels and zeros, which must
// never leave the header as values. No fixture title can be made to send a version-1 DLSSOptions; this can.
bool ProbeAdvFields() {
g_failures = 0;
const auto bitsOf = [](float v) { return std::bit_cast<uint32_t>(v); };
Check(fl::adv::Usable(1.0f) && fl::adv::Usable(0.0f) && fl::adv::Usable(-12.5f), "ordinary values are usable");
Check(!fl::adv::Usable(sl::INVALID_FLOAT), "Streamline's INVALID_FLOAT - FLT_MAX - is nobody's value");
Check(!fl::adv::Usable(std::bit_cast<float>(0x7F800000u)) && !fl::adv::Usable(std::bit_cast<float>(0x7FC00000u)) &&
!fl::adv::Usable(std::bit_cast<float>(0xFF800000u)),
"an infinity of either sign and a NaN are not usable");
// --- sl::DLSSOptions at the version these headers declare -----------------------------------------------------
{
fl::adv::Accumulators a;
sl::DLSSOptions opts;
opts.mode = sl::DLSSMode::eMaxQuality;
opts.outputWidth = 3840;
opts.outputHeight = 2160;
opts.preExposure = 1.5f;
opts.exposureScale = 0.25f;
opts.colorBuffersHDR = sl::Boolean::eTrue;
opts.dlaaPreset = sl::DLSSPreset::eDefault;
opts.qualityPreset = sl::DLSSPreset::ePresetK;
opts.ultraQualityPreset = sl::DLSSPreset::ePresetJ;
opts.useAutoExposure = sl::Boolean::eFalse;
opts.alphaUpscalingEnabled = sl::Boolean::eTrue;
fl::adv::ObserveDlssOptions(opts, a);
Check(a.validMask.load() == fl::FL_ADV_VALID_DLSS_OPTIONS && a.dlssOptionsSeen.load() == 1u,
"the group is marked read");
Check(a.dlssStructVersion.load() == sl::kStructVersion3, "the version the struct declared is kept");
Check(a.dlssOutputWidth.load() == 3840u && a.dlssOutputHeight.load() == 2160u, "the output size is kept");
Check(a.dlssPreExposureBits.load() == bitsOf(1.5f) && a.dlssExposureScaleBits.load() == bitsOf(0.25f),
"the exposure pair is kept as float bits");
const uint64_t p = a.dlssPresets.load();
Check((p & 0xFFu) == 1u, "preset eDefault is 0 at the vendor's and 1 here: zero stays 'not read'");
Check(((p >> 8) & 0xFFu) == static_cast<uint32_t>(sl::DLSSPreset::ePresetK) + 1u,
"a preset is its value plus one");
Check(((p >> 40) & 0xFFu) == static_cast<uint32_t>(sl::DLSSPreset::ePresetJ) + 1u,
"version 2's sixth preset is read at version 3");
const uint32_t b = a.dlssBooleans.load();
Check((b & 0xFFu) == 2u && ((b >> 8) & 0xFFu) == 1u && ((b >> 16) & 0xFFu) == 2u,
"a Boolean is its value plus one: true 2, false 1");
}
// --- THE TAIL OF AN OLDER STRUCT IS NOT READ (D115) ------------------------------------------------------------
{
// A title built against Streamline 2.0 allocates fourteen members. What lies where version 2 and 3 put
// theirs is the title's own memory; here it is loud values, so a read of them would show.
fl::adv::Accumulators a;
sl::DLSSOptions v1;
v1.structVersion = sl::kStructVersion1;
v1.ultraQualityPreset = sl::DLSSPreset::ePresetM;
v1.useAutoExposure = sl::Boolean::eTrue;
v1.alphaUpscalingEnabled = sl::Boolean::eTrue;
fl::adv::ObserveDlssOptions(v1, a);
Check(((a.dlssPresets.load() >> 40) & 0xFFu) == 0u, "a version-1 struct's sixth preset is not read");
Check((a.dlssBooleans.load() >> 8) == 0u, "nor its auto-exposure, nor its alpha upscaling");
Check((a.dlssBooleans.load() & 0xFFu) == 2u,
"while version 1's own members are (colorBuffersHDR defaults to true)");
fl::adv::Accumulators a2;
sl::DLSSOptions v2 = v1;
v2.structVersion = sl::kStructVersion2;
fl::adv::ObserveDlssOptions(v2, a2);
Check(((a2.dlssPresets.load() >> 40) & 0xFFu) == static_cast<uint32_t>(sl::DLSSPreset::ePresetM) + 1u &&
((a2.dlssBooleans.load() >> 8) & 0xFFu) == 2u,
"a version-2 struct's two members are read");
Check((a2.dlssBooleans.load() >> 16) == 0u, "and version 3's alpha upscaling still is not");
fl::adv::Accumulators a0;
sl::DLSSOptions v0 = v1;
v0.structVersion = 0;
fl::adv::ObserveDlssOptions(v0, a0);
Check(a0.validMask.load() == 0u && a0.dlssOptionsSeen.load() == 0u,
"a struct declaring no version is not read at all");
}
// --- sentinels and vendor zeros never become values --------------------------------------------------------------
{
fl::adv::Accumulators a;
sl::DLSSOptions unset; // outputWidth/Height default to INVALID_UINT
unset.preExposure = sl::INVALID_FLOAT;
unset.exposureScale = std::bit_cast<float>(0x7FC00000u);
unset.colorBuffersHDR = sl::Boolean::eInvalid;
unset.qualityPreset = static_cast<sl::DLSSPreset>(100000u);
fl::adv::ObserveDlssOptions(unset, a);
Check(a.dlssOutputWidth.load() == 0u && a.dlssOutputHeight.load() == 0u,
"INVALID_UINT is 'not given', never a size");
Check(a.dlssPreExposureBits.load() == FL_ADV_FLOAT_NONE && a.dlssExposureScaleBits.load() == FL_ADV_FLOAT_NONE,
"INVALID_FLOAT and a NaN are 'no value'");
Check((a.dlssBooleans.load() & 0xFFu) == 0u, "a Boolean in its third state is 'not read'");
Check(((a.dlssPresets.load() >> 8) & 0xFFu) == 0u,
"a preset a byte cannot carry is 'not read', not a truncated one");
sl::DLSSOptions half;
half.outputWidth = 1920; // a width with no height is not a size
fl::adv::ObserveDlssOptions(half, a);
Check(a.dlssOutputWidth.load() == 0u, "half a size is no size");
}
// --- the ffx upscale dispatch
// ------------------------------------------------------------------------------------------
{
fl::adv::Accumulators a;
ffxDispatchDescUpscale d{};
d.header.type = FFX_API_DISPATCH_DESC_TYPE_UPSCALE;
d.enableSharpening = true;
d.sharpness = 0.5f;
d.jitterOffset = {-0.375f, 0.25f};
d.preExposure = 1.0f;
d.cameraNear = 0.1f;
d.cameraFar = 5000.0f;
d.cameraFovAngleVertical = 1.0f;
d.frameTimeDelta = 16.5f;
d.flags = FFX_UPSCALE_FLAG_NON_LINEAR_COLOR_PQ;
fl::adv::ObserveFfxUpscale(1u, d, a);
d.sharpness = 0.8f;
d.jitterOffset = {0.125f, -0.4375f};
d.cameraFovAngleVertical = 0.6f; // the player aimed: a narrower field of view
d.frameTimeDelta = 8.25f;
d.reset = true;
d.flags = FFX_UPSCALE_FLAG_DRAW_DEBUG_VIEW;
fl::adv::ObserveFfxUpscale(1u, d, a);
Check(a.validMask.load() == fl::FL_ADV_VALID_FFX_UPSCALE && a.ffxDispatches.load() == 2u,
"two dispatches, counted");
Check(a.ffxSharpenSeen.load() == 2u && a.ffxSharpnessMinBits.load() == bitsOf(0.5f) &&
a.ffxSharpnessMaxBits.load() == bitsOf(0.8f),
"sharpening seen on, its strength as a range");
Check(a.ffxJitterMaxXBits.load() == bitsOf(0.375f) && a.ffxJitterMaxYBits.load() == bitsOf(0.4375f),
"the jitter is the largest magnitude on each axis, whatever its sign");
Check(a.ffxFovMinBits.load() == bitsOf(0.6f) && a.ffxFovMaxBits.load() == bitsOf(1.0f),
"the field of view is a range - lowest and highest - not a last value (D114)");
Check(a.ffxNearBits.load() == bitsOf(0.1f) && a.ffxFarBits.load() == bitsOf(5000.0f),
"the depth range is kept");
Check(a.ffxFlagsSeen.load() == (FFX_UPSCALE_FLAG_NON_LINEAR_COLOR_PQ | FFX_UPSCALE_FLAG_DRAW_DEBUG_VIEW),
"flags are every bit any dispatch carried");
Check(a.ffxResets.load() == 1u, "a reset is counted");
Check(a.ffxFrameTimeCount.load() == 2u && a.ffxFrameTimeSumUs.load() == 16500u + 8250u,
"the frame time is a count and a sum in microseconds");
// The same dispatch arriving at a second hooked module - a loader in front of the leaf - is passed over.
fl::adv::ObserveFfxUpscale(3u, d, a);
Check(a.ffxDispatches.load() == 2u && a.ffxResets.load() == 1u,
"one module's dispatches are counted, not one per hook");
// Sharpening off: its strength is whatever the title left there, and is not kept.
fl::adv::Accumulators off;
ffxDispatchDescUpscale quiet{};
quiet.sharpness = 0.9f;
quiet.jitterOffset = {std::bit_cast<float>(0x7FC00000u), 0.5f};
quiet.cameraFovAngleVertical = -1.0f;
quiet.frameTimeDelta = 0.0f;
fl::adv::ObserveFfxUpscale(0u, quiet, off);
Check(off.ffxSharpenSeen.load() == 1u && off.ffxSharpnessMaxBits.load() == FL_ADV_FLOAT_NONE,
"sharpening seen off, and no strength kept for it");
Check(off.ffxJitterMaxYBits.load() == FL_ADV_FLOAT_NONE, "a jitter with a NaN in it is not half-kept");
Check(off.ffxFovMinBits.load() == FL_ADV_FLOAT_NONE, "a field of view that is not positive is not one");
Check(off.ffxFrameTimeCount.load() == 0u, "a frame time of zero is not a frame time");
Check(off.ffxFlagsSeen.load() == 0u && off.ffxResets.load() == 0u, "nothing is invented");
}
// --- the ffx upscaler's memory, both query versions
// ------------------------------------------------------------------
{
fl::adv::Accumulators a;
FfxApiEffectMemoryUsage usage{};
usage.totalUsageInBytes = 300ull * 1024ull * 1024ull;
usage.aliasableUsageInBytes = 40ull * 1024ull * 1024ull;
ffxQueryDescUpscaleGetGPUMemoryUsage q1{};
q1.header.type = FFX_API_QUERY_DESC_TYPE_UPSCALE_GPU_MEMORY_USAGE;
q1.gpuMemoryUsageUpscaler = &usage;
fl::adv::ObserveFfxMemoryQuery(1u, &q1.header, a);
Check(a.validMask.load() == fl::FL_ADV_VALID_FFX_MEMORY && a.ffxMemoryQueries.load() == 1u &&
a.ffxMemoryTotalBytes.load() == usage.totalUsageInBytes &&
a.ffxMemoryAliasableBytes.load() == usage.aliasableUsageInBytes,
"the answer the query wrote is kept");
usage.totalUsageInBytes = 512ull * 1024ull * 1024ull;
ffxQueryDescUpscaleGetGPUMemoryUsageV2 q2{};
q2.header.type = FFX_API_QUERY_DESC_TYPE_UPSCALE_GPU_MEMORY_USAGE_V2;
q2.gpuMemoryUsageUpscaler = &usage;
fl::adv::ObserveFfxMemoryQuery(1u, &q2.header, a);
Check(a.ffxMemoryQueries.load() == 2u && a.ffxMemoryTotalBytes.load() == usage.totalUsageInBytes,
"version 2 of the query is read the same way");
q1.gpuMemoryUsageUpscaler = nullptr;
fl::adv::ObserveFfxMemoryQuery(1u, &q1.header, a);
fl::adv::ObserveFfxMemoryQuery(1u, nullptr, a);
ffxQueryDescUpscaleGetUpscaleRatioFromQualityMode other{};
other.header.type = FFX_API_QUERY_DESC_TYPE_UPSCALE_GETUPSCALERATIOFROMQUALITYMODE;
fl::adv::ObserveFfxMemoryQuery(1u, &other.header, a);
Check(a.ffxMemoryQueries.load() == 2u,
"a null out-pointer, a null descriptor and another query are passed over");
// The loader's shape: the same query arrives at a second hooked module. One module's queries are counted.
q1.gpuMemoryUsageUpscaler = &usage;
fl::adv::ObserveFfxMemoryQuery(3u, &q1.header, a);
Check(a.ffxMemoryQueries.load() == 2u, "the same query seen at a second module is not a second query");
}
// --- the watchdog's publication
// ----------------------------------------------------------------------------------------
{
fl::adv::Accumulators a;
auto* region = new fl::FlAdvancedState{};
fl::adv::Publish(a, nullptr, 1u, 1u); // a ring that mapped no region: nothing to write, nothing to fault on
sl::DLSSOptions opts;
opts.outputWidth = 2560;
opts.outputHeight = 1440;
fl::adv::ObserveDlssOptions(opts, a);
ffxDispatchDescUpscale d{};
d.frameTimeDelta = 10.0f;
fl::adv::ObserveFfxUpscale(0u, d, a);
fl::adv::Publish(a, region, 41u, 777u);
Check(region->seq == 2u && region->samples == 1u && region->sampleQpc == 777u,
"one publication: the lock even, at two");
Check(region->validMask == (fl::FL_ADV_VALID_DLSS_OPTIONS | fl::FL_ADV_VALID_FFX_UPSCALE),
"what was read is marked");
Check(region->dlssOutputWidth == 2560u && region->dlssOutputHeight == 1440u && region->dlssPresets[0] == 1u &&
region->dlssColorBuffersHdr == 2u,
"the DLSS group lands where fl_shm.h puts it");
Check(region->ffxDispatches == 1u && region->ffxFrameTimeCount == 1u && region->ffxFrameTimeSumUs == 10000u,
"the ffx group lands, with the frame time of this interval");
Check(region->ffxSharpnessMinBits == FL_ADV_FLOAT_NONE && region->ffxFovMaxBits == FL_ADV_FLOAT_NONE,
"a float nobody saw is the 'none' pattern, never 0.0");
Check(region->request == 41u, "a publication names the request it answers");
fl::adv::Publish(a, region, 41u, 778u);
Check(region->seq == 4u && region->samples == 2u, "a second publication: plus two");
Check(region->ffxFrameTimeCount == 0u && region->ffxFrameTimeSumUs == 0u && region->ffxDispatches == 1u,
"the frame-time pair is drained by each publication; the counts are not");
bool untouched = region->ffxFgConfigures == 0u && region->slConstantsCalls == 0u;
for (uint32_t i = 0; i < FL_ADV_FEATURE_SLOTS * FL_ADV_FEATURE_WORDS; ++i) {
untouched = untouched && region->features[i] == 0u;
}
Check(untouched, "what a later release fills stays zero");
// A NEW REQUEST: a second session of a game that kept running. Its summaries are its own.
fl::adv::Reset(a);
fl::adv::Publish(a, region, 42u, 779u);
Check(region->request == 42u && region->seq == 6u && region->samples == 3u,
"the next session's publication carries the next request; the lock and the count go on");
Check(region->validMask == 0u && region->ffxDispatches == 0u && region->ffxFlagsSeen == 0u &&
region->ffxFovMinBits == FL_ADV_FLOAT_NONE && region->ffxMemoryTotalBytes == 0u &&
region->dlssOptionsSeen == 0u && region->dlssOutputWidth == 0u,
"and nothing of the session before: no mask, no count, no range, no size");
delete region;
}
return g_failures == 0;
}
// The word RecordPresent drains: features in the low byte, the frame-generation
// count above them.
//
@@ -2417,12 +2689,26 @@ using StubSetTagForFrameFn = sl::Result(STDMETHODCALLTYPE*)(const void*, const s
const sl::ResourceTag*, uint32_t, sl::CommandBuffer*);
using StubEvaluateFn = sl::Result(STDMETHODCALLTYPE*)(sl::Feature, const void*, const void*, uint32_t, void*);
// WHAT --advanced SENDS. One value of each kind Advanced metrics keeps, none of them a default of the vendor's
// structs, so a region that carries them was read off the argument. guard_test.cpp states the same numbers.
constexpr uint32_t kAdvDlssOutputW = 2560u;
constexpr uint32_t kAdvDlssOutputH = 1440u;
constexpr float kAdvDlssPreExposure = 1.5f;
constexpr float kAdvDlssExposureScale = 0.75f;
constexpr float kAdvFfxSharpness = 0.35f;
constexpr float kAdvFfxPreExposure = 1.25f;
constexpr float kAdvFfxNear = 0.1f;
constexpr float kAdvFfxFar = 1000.0f;
constexpr float kAdvFfxFovLow = 0.9f; // radians; the two alternate, frame by frame
constexpr float kAdvFfxFovHigh = 1.1f;
constexpr float kAdvFfxFrameTimeMs = 16.0f;
using StubTokenFn = sl::Result(STDMETHODCALLTYPE*)(sl::FrameToken*&, const uint32_t*);
alignas(16) unsigned char g_dummyFrameToken[64]{};
int HoldPresentingUpscaled(Gfx& g, int seconds, bool real, sl::Feature feature, bool tagForFrame, bool wholeResource,
bool dlssgInputs) {
bool dlssgInputs, bool advanced) {
if (!HaveD3D11(g, "the upscaled hold")) {
return 1;
}
@@ -2499,6 +2785,28 @@ int HoldPresentingUpscaled(Gfx& g, int seconds, bool real, sl::Feature feature,
wholeResource ? "whole resource, Resource size" : "extent", kTaggedRenderW, kTaggedRenderH,
tagForFrame ? "slSetTagForFrame (Streamline 2.8, frame-based)" : "slSetTag",
dlssgInputs ? ", beside depth, motion vectors, HUD-less and UI (the DLSS-G inputs)" : "");
// --advanced: the options a title that configures DLSS through the evaluation chains into `inputs`, at the
// version these headers declare. Not every title does - most call slDLSSSetOptions, which has no export - and
// without the flag this hold stays the shape it always was: inputs = nullptr.
sl::DLSSOptions options;
options.mode = sl::DLSSMode::eMaxQuality;
options.outputWidth = kAdvDlssOutputW;
options.outputHeight = kAdvDlssOutputH;
options.preExposure = kAdvDlssPreExposure;
options.exposureScale = kAdvDlssExposureScale;
options.colorBuffersHDR = sl::Boolean::eFalse;
options.useAutoExposure = sl::Boolean::eTrue;
options.alphaUpscalingEnabled = sl::Boolean::eTrue;
options.dlaaPreset = sl::DLSSPreset::ePresetK;
options.qualityPreset = sl::DLSSPreset::ePresetJ;
options.performancePreset = sl::DLSSPreset::ePresetM;
options.ultraPerformancePreset = sl::DLSSPreset::ePresetL;
const sl::BaseStructure* advancedInputs[] = {&options};
if (advanced) {
std::printf(" --advanced: an sl::DLSSOptions (version %zu, output %ux%u) chained into every evaluation\n",
options.structVersion, kAdvDlssOutputW, kAdvDlssOutputH);
}
std::fflush(stdout);
const ULONGLONG until = GetTickCount64() + static_cast<ULONGLONG>(seconds) * 1000ULL;
@@ -2515,7 +2823,7 @@ int HoldPresentingUpscaled(Gfx& g, int seconds, bool real, sl::Feature feature,
}
// ONE EVALUATION PER PRESENT, which is what a real upscaled title does
// and what makes the drained record's identity checkable frame by frame.
eval(feature, g_dummyFrameToken, nullptr, 0, nullptr);
eval(feature, g_dummyFrameToken, advanced ? advancedInputs : nullptr, advanced ? 1u : 0u, nullptr);
++evaluated;
g.swapChain->Present(0, flags);
++presented;
@@ -2661,6 +2969,30 @@ using PfnFsr3DispatchUpscale = decltype(&fsr3host::ffxFsr3ContextDispatchUpscale
// What --ffx-query asks before each UPSCALE: nothing, the render size each mode gives, or each mode's ratio.
enum class FfxQuery { None, Sizes, Ratios };
// What --ffx-memory-query asks before each UPSCALE: nothing, or the upscaler's memory in one of its two descriptors.
enum class FfxMemoryQuery { None, V1, V2 };
// The way a title with a memory overlay asks: a struct of its own, handed over by pointer, filled by the vendor.
// Nothing here reads the answer - what the Overlay kept of it is what the test asserts.
void AskMemory(PfnFfxQuery query, FfxMemoryQuery what) {
FfxApiEffectMemoryUsage usage{};
if (what == FfxMemoryQuery::V1) {
ffxQueryDescUpscaleGetGPUMemoryUsage q{};
q.header.type = FFX_API_QUERY_DESC_TYPE_UPSCALE_GPU_MEMORY_USAGE;
q.gpuMemoryUsageUpscaler = &usage;
query(nullptr, &q.header);
} else if (what == FfxMemoryQuery::V2) {
ffxQueryDescUpscaleGetGPUMemoryUsageV2 q{};
q.header.type = FFX_API_QUERY_DESC_TYPE_UPSCALE_GPU_MEMORY_USAGE_V2;
q.maxRenderSize.width = kTaggedRenderW;
q.maxRenderSize.height = kTaggedRenderH;
q.maxUpscaleSize.width = 1920u;
q.maxUpscaleSize.height = 1080u;
q.gpuMemoryUsageUpscaler = &usage;
query(nullptr, &q.header);
}
}
// Every mode, at the display the UPSCALE descriptor states -- the way a settings menu enumerates them. The answers
// are written through the descriptors' own pointers; nothing here checks them, because the Overlay's reading of them
// is what the test asserts.
@@ -2690,7 +3022,7 @@ void AskQuality(PfnFfxQuery query, FfxQuery what) {
}
int HoldPresentingFfx(Gfx& g, int seconds, bool real, int presentsPerEval, FfxTopology topology, bool prepare,
FfxQuery ask) {
FfxQuery ask, bool advanced, FfxMemoryQuery askMemory) {
if (!HaveD3D11(g, "--hold-presenting-ffx")) {
return 1;
}
@@ -2765,11 +3097,12 @@ int HoldPresentingFfx(Gfx& g, int seconds, bool real, int presentsPerEval, FfxTo
return 1;
}
// The quality query goes where the UPSCALE goes: the same module a title sizes its targets through.
const auto query = upEntry != nullptr && ask != FfxQuery::None
const bool asksAnything = ask != FfxQuery::None || askMemory != FfxMemoryQuery::None;
const auto query = upEntry != nullptr && asksAnything
? reinterpret_cast<PfnFfxQuery>(reinterpret_cast<void*>(GetProcAddress(upEntry, "ffxQuery")))
: nullptr;
if (ask != FfxQuery::None && query == nullptr) {
Check(false, "the UPSCALE entry module exports ffxQuery for --ffx-query");
if (asksAnything && query == nullptr) {
Check(false, "the UPSCALE entry module exports ffxQuery for --ffx-query and --ffx-memory-query");
return 1;
}
// The pre-V2 PREPARE is the 1.1.x monolith's, on both topologies that use it.
@@ -2787,6 +3120,13 @@ int HoldPresentingFfx(Gfx& g, int seconds, bool real, int presentsPerEval, FfxTo
k > 1 ? " + one FRAMEGENERATION" : "");
std::printf(" renderSize %ux%u on every UPSCALE%s\n", kTaggedRenderW, kTaggedRenderH,
prepare ? " and PREPARE" : "");
if (advanced) {
std::printf(" --advanced: sharpening, jitter, exposure, depth range, field of view, flags and frame time on "
"every UPSCALE\n");
}
if (askMemory != FfxMemoryQuery::None) {
std::printf(" --ffx-memory-query %s before every UPSCALE\n", askMemory == FfxMemoryQuery::V1 ? "v1" : "v2");
}
std::fflush(stdout);
// Built from the vendored structs, so the fixture and the detour agree about the
@@ -2797,6 +3137,16 @@ int HoldPresentingFfx(Gfx& g, int seconds, bool real, int presentsPerEval, FfxTo
up.renderSize.height = kTaggedRenderH;
up.upscaleSize.width = 1920u;
up.upscaleSize.height = 1080u;
if (advanced) {
// The members that do not change with the frame; the jitter and the field of view are set in the loop.
up.enableSharpening = true;
up.sharpness = kAdvFfxSharpness;
up.preExposure = kAdvFfxPreExposure;
up.cameraNear = kAdvFfxNear;
up.cameraFar = kAdvFfxFar;
up.frameTimeDelta = kAdvFfxFrameTimeMs;
up.flags = FFX_UPSCALE_FLAG_NON_LINEAR_COLOR_PQ;
}
// PREPARE in the shape each generation sends -- V2 for SDK 2.x, the original type
// for the 1.1.x monolith -- built in the V2 struct either way, because the two
@@ -2824,9 +3174,20 @@ int HoldPresentingFfx(Gfx& g, int seconds, bool real, int presentsPerEval, FfxTo
uint64_t frameId = 0;
while (GetTickCount64() < until) {
++frameId;
if (query != nullptr) {
if (query != nullptr && ask != FfxQuery::None) {
AskQuality(query, ask);
}
if (query != nullptr && askMemory != FfxMemoryQuery::None) {
AskMemory(query, askMemory);
}
if (advanced) {
// A sub-pixel jitter that changes sign, and a field of view that moves between two values, as a zoom
// does: what is kept is the largest magnitude of the one and the range of the other.
const bool odd = (frameId & 1u) != 0u;
up.jitterOffset.x = odd ? -0.25f : 0.3f;
up.jitterOffset.y = odd ? 0.4f : -0.1f;
up.cameraFovAngleVertical = odd ? kAdvFfxFovLow : kAdvFfxFovHigh;
}
if (dispatchHost != nullptr) {
dispatchHost(nullptr, &hostUp);
} else {
@@ -3018,6 +3379,8 @@ int main(int argc, char** argv) {
FfxTopology ffxTopology = FfxTopology::Loader;
bool ffxPrepare = true;
FfxQuery ffxQuery = FfxQuery::None;
bool advancedInputs = false;
auto ffxMemoryQuery = FfxMemoryQuery::None;
bool slTagForFrame = false;
bool slTagWholeResource = false;
bool slTagDlssgInputs = false;
@@ -3055,6 +3418,10 @@ int main(int argc, char** argv) {
ffxQuery = std::strcmp(q, "sizes") == 0 ? FfxQuery::Sizes
: std::strcmp(q, "ratios") == 0 ? FfxQuery::Ratios
: FfxQuery::None;
} else if (std::strcmp(argv[i], "--advanced") == 0) {
advancedInputs = true;
} else if (std::strcmp(argv[i], "--ffx-memory-query") == 0 && i + 1 < argc) {
ffxMemoryQuery = std::strcmp(argv[++i], "v1") == 0 ? FfxMemoryQuery::V1 : FfxMemoryQuery::V2;
} else if (std::strcmp(argv[i], "--sl-tag-for-frame") == 0) {
slTagForFrame = true;
} else if (std::strcmp(argv[i], "--sl-tag-whole-resource") == 0) {
@@ -3096,12 +3463,14 @@ int main(int argc, char** argv) {
std::strcmp(argv[i], "--present-interval-ms") == 0 || std::strcmp(argv[i], "--presents-per-eval") == 0 ||
std::strcmp(argv[i], "--ffx-topology") == 0 || std::strcmp(argv[i], "--ffx-no-prepare") == 0 ||
std::strcmp(argv[i], "--ffx-query") == 0 || std::strcmp(argv[i], "--sl-tag-for-frame") == 0 ||
std::strcmp(argv[i], "--advanced") == 0 || std::strcmp(argv[i], "--ffx-memory-query") == 0 ||
std::strcmp(argv[i], "--sl-tag-whole-resource") == 0 ||
std::strcmp(argv[i], "--sl-tag-dlssg-inputs") == 0 || std::strcmp(argv[i], "--load") == 0 ||
std::strcmp(argv[i], "--load-after-ms") == 0) {
if (std::strcmp(argv[i], "--plus-ui") == 0 || std::strcmp(argv[i], "--present-interval-ms") == 0 ||
std::strcmp(argv[i], "--presents-per-eval") == 0 || std::strcmp(argv[i], "--ffx-topology") == 0 ||
std::strcmp(argv[i], "--ffx-query") == 0 || std::strcmp(argv[i], "--load") == 0) {
std::strcmp(argv[i], "--ffx-query") == 0 || std::strcmp(argv[i], "--ffx-memory-query") == 0 ||
std::strcmp(argv[i], "--load") == 0) {
++i;
}
if (std::strcmp(argv[i], "--load-after-ms") == 0) {
@@ -3115,13 +3484,13 @@ int main(int argc, char** argv) {
ok = HoldPresentingFg(g, std::atoi(argv[++i]), real, presentsPerEval) == 0 && ok;
ranSomething = true;
} else if (std::strcmp(argv[i], "--hold-presenting-ffx") == 0 && i + 1 < argc) {
ok = HoldPresentingFfx(g, std::atoi(argv[++i]), real, presentsPerEval, ffxTopology, ffxPrepare, ffxQuery) ==
0 &&
ok = HoldPresentingFfx(g, std::atoi(argv[++i]), real, presentsPerEval, ffxTopology, ffxPrepare, ffxQuery,
advancedInputs, ffxMemoryQuery) == 0 &&
ok;
ranSomething = true;
} else if (std::strcmp(argv[i], "--hold-presenting-upscaled") == 0 && i + 1 < argc) {
ok = HoldPresentingUpscaled(g, std::atoi(argv[++i]), real, sl::kFeatureDLSS, slTagForFrame,
slTagWholeResource, slTagDlssgInputs) == 0 &&
slTagWholeResource, slTagDlssgInputs, advancedInputs) == 0 &&
ok;
ranSomething = true;
} else if (std::strcmp(argv[i], "--hold-presenting-upscaled-unknown") == 0 && i + 1 < argc) {
@@ -3131,7 +3500,7 @@ int main(int argc, char** argv) {
// never report FL_UPSCALER_NONE, which is the only state that may be
// aggregated as a negative. 0xF00D is not a Streamline feature.
ok = HoldPresentingUpscaled(g, std::atoi(argv[++i]), real, static_cast<sl::Feature>(0xF00Du), slTagForFrame,
slTagWholeResource, slTagDlssgInputs) == 0 &&
slTagWholeResource, slTagDlssgInputs, advancedInputs) == 0 &&
ok;
ranSomething = true;
} else if (std::strcmp(argv[i], "--hold-presenting-upscaled-nr") == 0 && i + 1 < argc) {
@@ -3139,7 +3508,7 @@ int main(int argc, char** argv) {
// once per present. It is not an upscaler: the record must say UNKNOWN for the upscaler, as for any id
// that names none, and carry FL_FEAT_SL_NEURAL_RENDERING rather than FL_FEAT_SL_UNDECODED.
ok = HoldPresentingUpscaled(g, std::atoi(argv[++i]), real, sl::kFeatureDLSS_NR, slTagForFrame,
slTagWholeResource, slTagDlssgInputs) == 0 &&
slTagWholeResource, slTagDlssgInputs, advancedInputs) == 0 &&
ok;
ranSomething = true;
} else if (std::strcmp(argv[i], "--probe-upscaler-resolve") == 0) {
@@ -3151,6 +3520,9 @@ int main(int argc, char** argv) {
} else if (std::strcmp(argv[i], "--probe-sl-inputs") == 0) {
ok = ProbeSlInputs() && ok;
ranSomething = true;
} else if (std::strcmp(argv[i], "--probe-adv-fields") == 0) {
ok = ProbeAdvFields() && ok;
ranSomething = true;
} else if (std::strcmp(argv[i], "--probe-sl-seen") == 0) {
ok = ProbeSlSeen() && ok;
ranSomething = true;
@@ -148,6 +148,22 @@ FFX_API_ENTRY ffxReturnCode_t ffxQuery(ffxContext* context, ffxQueryDescHeader*
*q->pOutUpscaleRatio = kRatios[q->qualityMode];
return FFX_API_RETURN_OK;
}
// THE UPSCALER'S MEMORY (Advanced metrics, train B), in both descriptors: two fixed numbers no real context
// would report, written through the caller's own pointer - which is where the Overlay reads them after this
// returns, and only while the Agent asked. guard_test.cpp states the same two.
if (desc->type == FFX_API_QUERY_DESC_TYPE_UPSCALE_GPU_MEMORY_USAGE ||
desc->type == FFX_API_QUERY_DESC_TYPE_UPSCALE_GPU_MEMORY_USAGE_V2) {
FfxApiEffectMemoryUsage* usage =
desc->type == FFX_API_QUERY_DESC_TYPE_UPSCALE_GPU_MEMORY_USAGE
? reinterpret_cast<ffxQueryDescUpscaleGetGPUMemoryUsage*>(desc)->gpuMemoryUsageUpscaler
: reinterpret_cast<ffxQueryDescUpscaleGetGPUMemoryUsageV2*>(desc)->gpuMemoryUsageUpscaler;
if (usage == nullptr) {
return FFX_API_RETURN_ERROR_PARAMETER;
}
usage->totalUsageInBytes = 123456789ull;
usage->aliasableUsageInBytes = 23456789ull;
return FFX_API_RETURN_OK;
}
return FFX_API_RETURN_OK;
}
@@ -271,13 +271,56 @@ public sealed class ShmRingReaderTests
ring.Control->AdvancedRequested.Should().Be(0u, "off is a zero that is written");
reader.SetAdvancedRequested(true);
ring.Control->AdvancedRequested.Should().Be(1u);
ring.Control->AdvancedRequested.Should().Be(1u, "the first request of a ring nobody asked before");
ring.Control->UnhookRequested.Should().Be(0u, "asking for more readings is not the safety stop");
ring.Control->PauseRequested.Should().Be(0u);
ring.Control->LogFlushRequested.Should().Be(0u);
ring.Control->GuardTicks.Should().Be(0u);
}
[Fact]
public unsafe void EachSessionAsksWithARequestOfItsOwnAndReadsOnlyWhatAnswersIt()
{
// A game outlives a session, and the Overlay's summaries with it. Three sessions on one ring: the first asks and
// is answered; the second does not ask; the third asks again - with a value neither the word nor the region ever
// held - and must not read the first one's publication, which is still lying in the region.
int pid = FakePid();
using var ring = new FakeRing(pid);
using (ShmRingReader? first = ShmRingReader.TryAttach(pid, _buildId, out _))
{
first!.SetAdvancedRequested(true);
ring.Control->AdvancedRequested.Should().Be(1u);
ring.Advanced->Request = 1u;
ring.Advanced->FfxDispatches = 500u;
ring.Advanced->Seq = 2u;
first.AdvancedState.Should().BeOfType<FlAdvancedState>().Which.FfxDispatches.Should().Be(500u);
}
using (ShmRingReader? second = ShmRingReader.TryAttach(pid, _buildId, out _))
{
second!.SetAdvancedRequested(false);
ring.Control->AdvancedRequested.Should().Be(0u);
second.AdvancedState.Should().BeNull("a session that did not ask reads nothing, whatever the region holds");
}
using ShmRingReader? third = ShmRingReader.TryAttach(pid, _buildId, out _);
third!.SetAdvancedRequested(true);
ring.Control->AdvancedRequested.Should().Be(2u, "above the request the region last answered, though the word was 0");
third.AdvancedState.Should().BeNull("what is in the region answers the first session's request");
ring.Advanced->Seq = 3u;
ring.Advanced->Request = 2u;
ring.Advanced->FfxDispatches = 7u;
ring.Advanced->Seq = 4u;
third.AdvancedState.Should().BeOfType<FlAdvancedState>().Which.FfxDispatches.Should().Be(7u);
// And the value that would wrap to "off" is never written.
ring.Control->AdvancedRequested = uint.MaxValue;
third.SetAdvancedRequested(true);
ring.Control->AdvancedRequested.Should().Be(1u);
}
[Fact]
public unsafe void TheAdvancedRegionReadsNullUntilPublishedThenItsLastConsistentCopy()
{
@@ -286,6 +329,8 @@ public sealed class ShmRingReaderTests
using ShmRingReader? reader = ShmRingReader.TryAttach(pid, _buildId, out _);
reader!.AdvancedState.Should().BeNull("a region nobody published is not a game that used nothing");
reader.SetAdvancedRequested(true);
ring.Advanced->Request = ring.Control->AdvancedRequested;
// One publication, as the watchdog writes it: odd, the fields, even.
ring.Advanced->Seq = 1u;
+51
View File
@@ -0,0 +1,51 @@
# Every member of a vendor's struct that the Overlay reads for Advanced metrics - the whole of what a hooked game's
# arguments give up beyond the frame record (docs/18_GPU_VENDOR_APIS.md section Train B; owner decisions D111, D115 and
# D116, 2026-11-11).
#
# tools/overlay-fields-check.ps1 holds src/native/FrameLedger.Overlay/include/fl_adv_fields.h to this list in both
# directions, on every build: a member read there that is not here is red, and a name here that the header no longer
# reads is red. A camera's position, axes or matrices are red even when they are listed - so one cannot be let in by
# adding a line to this file.
#
# One `Struct::member` per line. To add a read: find the release of the vendor's SDK that introduced the member and add
# it to the table in docs/17_HOOK_ENGINE.md section "Which struct version carries which field" (D115) - a member is read
# only at a struct version proven to carry it - then add its name here, and say in the pull request what it tells and
# why it is an argument of a call the Overlay hooks (rule 4).
# sl::DLSSOptions, chained into slEvaluateFeature's inputs (parameter `o`)
sl::DLSSOptions::structVersion
sl::DLSSOptions::outputWidth
sl::DLSSOptions::outputHeight
sl::DLSSOptions::preExposure
sl::DLSSOptions::exposureScale
sl::DLSSOptions::colorBuffersHDR
sl::DLSSOptions::dlaaPreset
sl::DLSSOptions::qualityPreset
sl::DLSSOptions::balancedPreset
sl::DLSSOptions::performancePreset
sl::DLSSOptions::ultraPerformancePreset
# ... from struct version 2
sl::DLSSOptions::ultraQualityPreset
sl::DLSSOptions::useAutoExposure
# ... from struct version 3
sl::DLSSOptions::alphaUpscalingEnabled
# ffxDispatchDescUpscale, the descriptor of an ffx-api upscale dispatch (parameter `d`). The two cameraX members are
# the depth range and the vertical field of view - numbers a settings menu shows - not where the camera is.
ffxDispatchDescUpscale::enableSharpening
ffxDispatchDescUpscale::sharpness
ffxDispatchDescUpscale::jitterOffset
ffxDispatchDescUpscale::preExposure
ffxDispatchDescUpscale::cameraNear
ffxDispatchDescUpscale::cameraFar
ffxDispatchDescUpscale::cameraFovAngleVertical
ffxDispatchDescUpscale::flags
ffxDispatchDescUpscale::reset
ffxDispatchDescUpscale::frameTimeDelta
# The upscaler's memory query: the header's type, the game's out-pointer in either version of the descriptor
# (parameter `q`), and what ffxQuery wrote through it after answering OK (parameter `m`)
ffxQueryDescHeader::type
ffxQueryDescUpscaleGetGPUMemoryUsage::gpuMemoryUsageUpscaler
FfxApiEffectMemoryUsage::totalUsageInBytes
FfxApiEffectMemoryUsage::aliasableUsageInBytes
+251
View File
@@ -0,0 +1,251 @@
# SPDX-License-Identifier: GPL-3.0-only
# Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
#Requires -Version 7.0
<#
.SYNOPSIS
Every member of a vendor's struct the Overlay reads for Advanced metrics is on a committed list, and a camera's
position, axes and matrices are read nowhere in the code loaded into a game.
.DESCRIPTION
CLAUDE.md rule 4 lets the Overlay read the arguments of the calls it hooks. Advanced metrics, train B (owner
decisions D111-D116, 2026-11-11) reads more of them than the frame record ever needed - and the same structs,
a few members further on, hold where the player's camera is and which way it looks. "We read the sharpness and
not the camera" is a sentence a reviewer would be asked to check by reading a 2,700-line file; this checks it.
WHAT IT HOLDS:
1. The reads are in ONE header, src/native/FrameLedger.Overlay/include/fl_adv_fields.h, through parameters with
fixed names - `o` (sl::DLSSOptions), `d` (ffxDispatchDescUpscale), `m` (FfxApiEffectMemoryUsage), `q` (the
memory query's descriptor) and `desc` (a query's header). Every member read through them is on
tools/overlay-allowed-fields.txt, and every name on that list is read.
2. Those parameters are not aliased: each of the four letters appears only as `x.member` or where it is
declared, and `->` is applied to nothing but `desc` and the Overlay's own `region`. So a member cannot be
read under a name this check does not look at.
3. No other source of the Overlay or the Vulkan layer reads a member the list names (the names every struct
has - structVersion, type, flags, reset - apart): the header is the one place.
4. A camera's position, axes and matrices are named NOWHERE in the Overlay's or the Vulkan layer's code, and
not on the list either - whatever the list says. The names are Streamline's (sl::Constants) and
FidelityFX's (the frame-generation prepare descriptor).
5. Neither of the two structs that hold them is copied whole or measured: no variable of the type, no
sizeof - a copy of the struct is a copy of the camera.
Rules 4 and 5 judge the code and the list, so the way to let a camera in is not "add a line to the text file".
WHAT IT DOES NOT DO. It reads names, not types: it cannot see a member reached by pointer arithmetic or a struct
copied with memcpy, and no code here does either. It does not know which struct version carries a member -
docs/17_HOOK_ENGINE.md section "Which struct version carries which field" does, and ctest fl_adv_fields checks
that a struct of a lower version is not read past its end. It does not look at the tools and tests, which are
not loaded into a game.
-SelfTest proves every rule in both directions on in-memory sources.
#>
[CmdletBinding()]
param(
[string]$RepoRoot = (Split-Path $PSScriptRoot -Parent),
[switch]$SelfTest
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
# The header's parameters and the struct each one is. `q` is either version of the memory query: one member, one name.
$script:Parameter = [ordered]@{
o = 'sl::DLSSOptions'
d = 'ffxDispatchDescUpscale'
m = 'FfxApiEffectMemoryUsage'
q = 'ffxQueryDescUpscaleGetGPUMemoryUsage'
desc = 'ffxQueryDescHeader'
}
# Where a camera is and which way it looks: sl::Constants' members, then the frame-generation prepare descriptor's.
# Exact tokens - cameraNear, cameraFar, cameraFOV, cameraAspectRatio and cameraFovAngleVertical are numbers a settings
# menu shows, and are not these.
$script:Camera = @(
'cameraPos', 'cameraUp', 'cameraRight', 'cameraFwd', 'cameraViewToClip', 'clipToCameraView', 'clipToLensClip',
'clipToPrevClip', 'prevClipToClip', 'cameraPinholeOffset',
'cameraPosition', 'cameraForward'
)
# The two structs that hold one.
$script:CameraStruct = @('sl::Constants', 'ffxDispatchDescFrameGenerationPrepareV2')
# Member names every struct has. The header's reads of them are held to the list like any other; what rule 3 cannot do
# is refuse them elsewhere, where they are members of the Overlay's own structs and of descriptors read since 0.1.0.
$script:SharedMember = @('structVersion', 'type', 'flags', 'reset')
# A C++ source without its comments and string literals: a camera named in the comment that says it is never read is
# not a read.
function Get-Code([string]$Source) {
$code = [regex]::Replace($Source, '/\*.*?\*/', ' ', 'Singleline')
$code = [regex]::Replace($code, '//[^\r\n]*', ' ')
return [regex]::Replace($code, '"(\\.|[^"\\\r\n])*"', '""')
}
# The names of the list, and what is wrong with the list itself.
function Read-AllowedList([string]$Text) {
$names = [System.Collections.Generic.List[string]]::new()
$problems = [System.Collections.Generic.List[string]]::new()
$number = 0
foreach ($raw in ($Text -split "`r?`n")) {
$number++
$line = $raw.Trim()
if ($line.Length -eq 0 -or $line.StartsWith('#')) { continue }
if ($line -cnotmatch '^[A-Za-z_][\w:]*::[A-Za-z_]\w*$') { $problems.Add("the list's line $number is not one Struct::member: '$line'"); continue }
if ($names.Contains($line)) { $problems.Add("the list names $line twice"); continue }
$names.Add($line)
}
return @{ Names = @($names); Problems = @($problems) }
}
# The members the header reads, as Struct::member, and where a parameter is used in a way rule 2 refuses.
function Get-HeaderRead([string]$Code) {
$reads = [System.Collections.Generic.SortedSet[string]]::new([StringComparer]::Ordinal)
$problems = [System.Collections.Generic.List[string]]::new()
foreach ($m in [regex]::Matches($Code, '(?<![\w.>:])(o|d|m|q)\b(\s*\.\s*([A-Za-z_]\w*))?')) {
$name = $m.Groups[1].Value
if ($m.Groups[3].Success) {
[void]$reads.Add("$($script:Parameter[$name])::$($m.Groups[3].Value)")
continue
}
# Not a member access: it may only be the parameter's own declaration - `Type& o,` or `const auto& q =`.
$before = $Code.Substring([Math]::Max(0, $m.Index - 8), [Math]::Min(8, $m.Index))
$after = $Code.Substring($m.Index + $m.Length, [Math]::Min(4, $Code.Length - $m.Index - $m.Length))
if ($before -cnotmatch '&\s*$' -or $after -cnotmatch '^\s*[,)=]') {
$problems.Add("the header uses the parameter '$name' other than as $name.member: an alias is a member read under a name nobody checks")
}
}
foreach ($m in [regex]::Matches($Code, '(?<![\w.>:])([A-Za-z_]\w*)\s*->\s*([A-Za-z_]\w*)')) {
$name = $m.Groups[1].Value
if ($name -ceq 'desc') { [void]$reads.Add("$($script:Parameter['desc'])::$($m.Groups[2].Value)") }
elseif ($name -cne 'region') { $problems.Add("the header reads '$name->$($m.Groups[2].Value)': only 'desc' and the Overlay's own 'region' are reached through a pointer") }
}
return @{ Reads = @($reads); Problems = @($problems) }
}
# $Others: file name -> source, for every Overlay and Vulkan-layer source but the header.
function Test-Field([string]$Header, [string]$ListText, [hashtable]$Others) {
$problems = [System.Collections.Generic.List[string]]::new()
$list = Read-AllowedList $ListText
foreach ($p in $list.Problems) { $problems.Add($p) }
$allowed = $list.Names
$headerCode = Get-Code $Header
$read = Get-HeaderRead $headerCode
foreach ($p in $read.Problems) { $problems.Add($p) }
if ($read.Reads.Count -eq 0) { $problems.Add('no member read was found in the header: the check read the wrong file, or nothing') }
foreach ($name in $read.Reads) {
if ($allowed -cnotcontains $name) { $problems.Add("the header reads $name, which the list does not allow") }
}
foreach ($name in $allowed) {
if ($read.Reads -cnotcontains $name) { $problems.Add("the list allows $name, which the header does not read") }
$member = $name.Substring($name.LastIndexOf('::') + 2)
if ($script:Camera -ccontains $member) { $problems.Add("$name is where a camera is or looks: never read (rule 4), whatever the list says") }
}
$members = @($allowed | ForEach-Object { $_.Substring($_.LastIndexOf('::') + 2) } | Where-Object { $script:SharedMember -cnotcontains $_ } | Sort-Object -Unique)
$sources = @{ 'the header' = $headerCode }
foreach ($key in $Others.Keys) { $sources[$key] = Get-Code $Others[$key] }
foreach ($key in ($sources.Keys | Sort-Object)) {
$code = $sources[$key]
foreach ($token in $script:Camera) {
if ($code -cmatch "(?<!\w)$token(?!\w)") { $problems.Add("$key names $token - where a camera is or looks is read nowhere in code loaded into a game (rule 4)") }
}
foreach ($struct in $script:CameraStruct) {
$bare = [regex]::Escape($struct)
if ($code -cmatch "sizeof\s*\(\s*$bare\s*\)") { $problems.Add("$key measures ${struct}: the struct holds a camera, and is neither measured nor copied") }
if ($code -cmatch "(?<![\w:])$bare\s+[A-Za-z_]\w*\s*[;={\[]") { $problems.Add("$key declares a $struct by value: a copy of the struct is a copy of the camera") }
}
if ($key -cne 'the header') {
foreach ($member in $members) {
if ($code -cmatch "(\.|->)\s*$member(?!\w)") { $problems.Add("$key reads a member named ${member}: the extra members of a vendor's struct are read in fl_adv_fields.h and nowhere else") }
}
}
}
return , @($problems)
}
if ($SelfTest) {
$failed = 0
$goodHeader = @'
// d.cameraPosition is never read, nor o.cameraPos.
inline void ObserveA(const sl::DLSSOptions& o, Accumulators& a) noexcept {
a.w.store(o.outputWidth); /* nor
d.cameraUp */
a.v.store(o . structVersion);
}
inline void ObserveB(uint32_t leaf, const ffxDispatchDescUpscale& d, Accumulators& a) noexcept {
Log("d.cameraRight");
a.j.store(d.jitterOffset.x + d.jitterOffset.y + d.cameraNear);
}
inline void ObserveC(const FfxApiEffectMemoryUsage& m, Accumulators& a) noexcept { a.t.store(m.totalUsageInBytes); }
inline void ObserveD(const ffxQueryDescHeader* desc, Accumulators& a) noexcept {
if (desc == nullptr) { return; }
if (desc->type == 1) {
const auto& q = *reinterpret_cast<const ffxQueryDescUpscaleGetGPUMemoryUsage*>(desc);
ObserveC(*q.gpuMemoryUsageUpscaler, a);
}
}
inline void Publish(Accumulators& a, FlAdvancedState* region) noexcept { region->samples = a.n.load(); }
'@
$goodList = "# a comment`nsl::DLSSOptions::outputWidth`nsl::DLSSOptions::structVersion`n`nffxDispatchDescUpscale::jitterOffset`nffxDispatchDescUpscale::cameraNear`nFfxApiEffectMemoryUsage::totalUsageInBytes`nffxQueryDescHeader::type`nffxQueryDescUpscaleGetGPUMemoryUsage::gpuMemoryUsageUpscaler`n"
$goodOther = @{ 'dllmain.cpp' = "void Hook() { if (up->renderSize.width != 0 && desc->type == 3 && c.flags != 0) { fl::adv::ObserveB(leaf, *up, g_adv); } }`n// prep->cameraPosition is never read`nconst auto* prep = reinterpret_cast<const ffxDispatchDescFrameGenerationPrepareV2*>(desc);`nstatic_assert(offsetof(ffxDispatchDescFrameGenerationPrepareV2, renderSize) == 48);" }
$cases = @(
@{ Name = 'a header whose reads are the list passes, with a camera named only in comments and strings'; Header = $goodHeader; List = $goodList; Other = $goodOther; Expect = 0 },
@{ Name = 'a member the list does not allow FAILS'; Header = $goodHeader + "`ninline void X(const ffxDispatchDescUpscale& d) { Keep(d.sharpness); }"; List = $goodList; Other = $goodOther; Expect = 1 },
@{ Name = 'a name on the list that nothing reads FAILS'; Header = $goodHeader; List = $goodList + "ffxDispatchDescUpscale::sharpness`n"; Other = $goodOther; Expect = 1 },
@{ Name = 'a camera position read in the header FAILS twice: not allowed, and named'; Header = $goodHeader + "`ninline void X(const ffxDispatchDescUpscale& d) { Keep(d.cameraPosition[0]); }"; List = $goodList; Other = $goodOther; Expect = 2 },
@{ Name = 'a camera position FAILS even when it is listed and read'; Header = $goodHeader + "`ninline void X(const ffxDispatchDescUpscale& d) { Keep(d.cameraPosition[0]); }"; List = $goodList + "ffxDispatchDescUpscale::cameraPosition`n"; Other = $goodOther; Expect = 2 },
@{ Name = 'a camera matrix named in another Overlay source FAILS'; Header = $goodHeader; List = $goodList; Other = @{ 'dllmain.cpp' = 'void Hook(const sl::Constants* c) { Keep(c->cameraViewToClip); }' }; Expect = 1 },
@{ Name = 'a camera axis named in the Vulkan layer FAILS'; Header = $goodHeader; List = $goodList; Other = @{ 'layer.cpp' = 'float x = k.cameraFwd.x;' }; Expect = 1 },
@{ Name = 'the depth range and the field of view are not a camera position'; Header = $goodHeader; List = $goodList; Other = @{ 'dllmain.cpp' = 'float n = cameraNearOf(c); float f = k_cameraFar; float v = cameraFOV; float r = cameraAspectRatio; float w = cameraFovAngleVertical;' }; Expect = 0 },
@{ Name = 'an alias of a parameter FAILS'; Header = $goodHeader + "`ninline void X(const sl::DLSSOptions& o) { const auto& x = o; Keep(x.mode); }"; List = $goodList; Other = $goodOther; Expect = 1 },
@{ Name = 'a parameter passed on whole FAILS'; Header = $goodHeader + "`ninline void X(const ffxDispatchDescUpscale& d) { Other(d); }"; List = $goodList; Other = $goodOther; Expect = 1 },
@{ Name = 'a member read through another pointer FAILS'; Header = $goodHeader + "`ninline void X(const ffxDispatchDescUpscale* up) { Keep(up->sharpness); }"; List = $goodList; Other = $goodOther; Expect = 1 },
@{ Name = 'a listed member read outside the header FAILS'; Header = $goodHeader; List = $goodList; Other = @{ 'dllmain.cpp' = 'void Hook() { Keep(up->jitterOffset.x); }' }; Expect = 1 },
@{ Name = 'a member every struct has, read outside the header, passes'; Header = $goodHeader; List = $goodList; Other = @{ 'dllmain.cpp' = 'void Hook() { Keep(s->structVersion + h.type); }' }; Expect = 0 },
@{ Name = 'sizeof of the struct that holds the camera FAILS'; Header = $goodHeader; List = $goodList; Other = @{ 'dllmain.cpp' = 'static_assert(sizeof(sl::Constants) == 444);' }; Expect = 1 },
@{ Name = 'a copy of the struct that holds the camera FAILS'; Header = $goodHeader; List = $goodList; Other = @{ 'dllmain.cpp' = 'void Hook(const void* p) { ffxDispatchDescFrameGenerationPrepareV2 copy = *Prep(p); (void)copy; }' }; Expect = 1 },
@{ Name = 'a pointer to it, and offsetof into it, pass'; Header = $goodHeader; List = $goodList; Other = $goodOther; Expect = 0 },
@{ Name = 'a name listed twice FAILS'; Header = $goodHeader; List = $goodList + "sl::DLSSOptions::outputWidth`n"; Other = $goodOther; Expect = 1 },
@{ Name = 'a line that is not one Struct::member FAILS'; Header = $goodHeader; List = $goodList + "sl::DLSSOptions::outputWidth # the size`n"; Other = $goodOther; Expect = 1 },
@{ Name = 'a header with no read at all FAILS'; Header = '// o.outputWidth is somewhere else'; List = "# nothing`n"; Other = $goodOther; Expect = 1 }
)
foreach ($c in $cases) {
$problems = Test-Field $c.Header $c.List $c.Other
$ok = $problems.Count -eq $c.Expect
Write-Host (" {0,-4} {1}{2}" -f ($(if ($ok) { 'ok' } else { 'FAIL' })), $c.Name, ($(if (-not $ok) { " -> $($problems.Count): $($problems -join '; ')" } else { '' })))
if (-not $ok) { $failed++ }
}
if ($failed -gt 0) { Write-Host "overlay-fields-check self-test FAILED ($failed)" -ForegroundColor Red; exit 1 }
Write-Host "overlay-fields-check self-test: $($cases.Count) cases, both directions" -ForegroundColor Green
exit 0
}
$headerPath = Join-Path $RepoRoot 'src/native/FrameLedger.Overlay/include/fl_adv_fields.h'
$listPath = Join-Path $RepoRoot 'tools/overlay-allowed-fields.txt'
foreach ($path in $headerPath, $listPath) {
if (-not (Test-Path -LiteralPath $path)) { Write-Host "OVERLAY FIELDS CHECK FAILED: $path is missing" -ForegroundColor Red; exit 1 }
}
$others = @{}
foreach ($dir in 'src/native/FrameLedger.Overlay', 'src/native/FrameLedger.VkLayer') {
$root = Join-Path $RepoRoot $dir
if (-not (Test-Path -LiteralPath $root)) { Write-Host "OVERLAY FIELDS CHECK FAILED: $root is missing" -ForegroundColor Red; exit 1 }
foreach ($file in Get-ChildItem -LiteralPath $root -Recurse -File -Include '*.cpp', '*.h', '*.inl') {
if ($file.FullName -eq (Resolve-Path -LiteralPath $headerPath).Path) { continue }
$others[[IO.Path]::GetRelativePath($RepoRoot, $file.FullName).Replace('\', '/')] = Get-Content -LiteralPath $file.FullName -Raw
}
}
if ($others.Count -eq 0) { Write-Host 'OVERLAY FIELDS CHECK FAILED: no Overlay or Vulkan-layer source was found beside the header' -ForegroundColor Red; exit 1 }
$headerText = Get-Content -LiteralPath $headerPath -Raw
$problems = Test-Field $headerText (Get-Content -LiteralPath $listPath -Raw) $others
if ($problems.Count -gt 0) {
Write-Host 'OVERLAY FIELDS CHECK FAILED:' -ForegroundColor Red
foreach ($p in $problems) { Write-Host " - $p" -ForegroundColor Red }
exit 1
}
$count = (Get-HeaderRead (Get-Code $headerText)).Reads.Count
Write-Host "overlay-fields-check OK - the Overlay reads $count members of the vendors' structs for Advanced metrics, each on the list; no camera position, axis or matrix in $($others.Count + 1) sources" -ForegroundColor Green
exit 0