D3D12.X: XCL_PIXEL_HISTORY (which draw writes a pixel) and XCL_SKIP_PS (leave out draws by pixel shader) #3509

Open
CharlyRien wants to merge 1 commit from upstream-pr/3509 into main
CharlyRien commented 2026-11-30 06:11:50 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by CharlyRien on 2026-11-30T06:11:50Z.


Two diagnostic switches to find which draw writes a wrong pixel. PIX and Nsight frame captures do not replay a title running under XCL, so we could not use their pixel history. These switches do the same job inside the process. Both are off by default. Unset, each one costs a draw one cached check.

What is in it

  • XCL_PIXEL_HISTORY=<x>,<y>[,<s>[,<frames>]] (d3d12x/pixel_history.rs, new).
    • It starts at the first present s seconds (default 0) or more after the first one, and follows frames frames (default 1, at most 8).
    • Around each draw on a direct list (direct and indirect draws), it copies one texel before and after the draw into a readback buffer: the texel at pixel x, y of the presented picture in each bound render target that has the picture's shape. Each copy is a 1×1 CopyTextureRegion between a RENDER_TARGET → COPY_SOURCE transition and its way back.
    • The point is mapped by each target's own size (its RTV's mip), so half- and quarter-size targets are followed too. A target counts as having the picture's shape when its aspect ratio is within 1 % and it is at least an eighth of the picture's width.
    • Six presents later, the values are read back and logged (see below).
    • Related switches:
      • XCL_PIXEL_HISTORY_SPACE=<w>x<h>: the size of the picture that x, y are given in (default 3840x2160).
      • XCL_PIXEL_HISTORY_ALSO=<x>,<y>[;<x>,<y>]: up to 3 more points.
      • XCL_PIXEL_HISTORY_CROP=<w>,<h>[,<n>]: a second round of as many frames. In it, only the draws whose pipeline changed a point in the first round also copy a w×h crop around the point after themselves. The crops of the draws that change the point are written as BMPs (pixel-history/<frame>_<event>_<ps>_p<point>rt<slot>.bmp next to xcl.log, at most n a frame, default 200).
      • XCL_PIXEL_HISTORY_SLOTS: the readback slots of a round (default 131072 slots of 512 bytes).
  • XCL_SKIP_PS=<hash>,<hash>: leaves out the draws (direct and indirect) whose console pixel shader has one of these hashes, the way XCL_SKIP_CS leaves out dispatches, and counts them in the log. Use it to confirm that the draw the history found is the one at fault.
  • Hooks: bind.rs (draw, indexed draw, ExecuteIndirect, dispatch), real.rs (RTV mip / slice, the pipeline's blend state, console VS / PS hashes kept while either switch is set), present.rs (one call at each present).
  • A README paragraph in the diagnostics list.

Reading the output (grep -a "pixel history" xcl.log)

  • XCL_PIXEL_HISTORY: points [...] of a WxH present, N frames from S s after the first present, ...: the settings, read once.
  • pixel history r1: point 0 (x, y) -> target 0x… sub S WxH format F at (tx, ty): once per target. It shows where the point landed in that target.
  • pixel history r1: f<frame> ev <seq> list 0x… #<i> [indirect ]draw vs <hash> ps <hash> pso 0x… p<k> rt<n> WxH fmt F at (tx, ty): (before) [raw] -> (after) [raw]; <blend state of that slot>: one line per draw that changed the texel. The values are decoded (RGBA8 / BGRA8, RGBA16 float, R11G11B10, R10G10B10A2, R32 float), with the raw bytes in brackets. Read the lines in (frame, list, #i) order. The last change before the present, on the scene's target, tells which draw wrote the final value, and the blend state tells how.
  • pixel history r1: f… list 0x… p<k> rt<n> …: changed BETWEEN draws #a (ev …) and #b (ev …): … -> …; dispatches between: #i cs <hash>, …: the texel changed between two draws of one list. This means a compute pass (named by its cs), a clear, a copy or a resolve wrote it.
  • pixel history r1 done: … events (… draws), … slots used; … changes by draws, … between draws, … copies not done (list not run yet); targets not followed: … by shape, … by format, … multisampled, … other; … slots full, … crops full; … crops written: the round's summary. "Copies not done" are copies whose list had not run by the readout (their slots still hold a 0xA5 sentinel). They are counted, not read.
  • With _CROP, an r2 round follows with the same lines, and its crops are written.

Measured use. On the retail title, a pose in front of a window where one diagonal half of the glass turns black. One run with two points (one on the dark half, one control) and one frame per round, plus 64×64 crops. The history named the depth-of-field composite, an indirect draw blending SRC_ALPHA / INV_SRC_ALPHA, as the draw that set the texel to RGB 0. It also showed the DoF downsample writing RGB 0 at every watched point. XCL_SKIP_PS on the composite's pixel shader then gave a clean window. That led to #3281's case: a R9G9B9E5 view placed over an R32_UINT texture. Report: https://github.com/xcl-dev/xcl/pull/3281#issuecomment-7269873202. That run used an earlier form of this tool, in which the start could also be counted from a busy-draws heuristic. This PR keeps only seconds after the first present, which does not depend on the title.

Numbers from that run (RTX 3090):

  • Round 1: 5635 events (664 draws on direct lists, the rest dispatches) and 1720 slots used. It logged 19 changes by draws and 1 between draws, with 0 copies not done. Targets not followed: 28 by shape, 305 by format.
  • Round 2: 1600 crops of 32 KiB were allocated and 15 were written.
  • The log line of each round came about 7 s after its first frame. At that pose the title ran at about one present a second, and the 2 s activity lines kept 1–2 presents through both rounds. One 2 s window at the start of round 1 had about half the usual draws (4790 against about 9000), which did not happen around round 2. We did not look further into it.

Cost

  • Off (the default): a draw's hook loads one atomic for the history and makes one cached check for XCL_SKIP_PS; a dispatch's hook loads the same atomic. The hooks at pipeline creation, RTV creation and present check cached values only. Nothing is allocated. A test checks that the hooks do not even look at the command list when the switch is unset.
  • On, outside the followed frames: the same per draw, plus one map entry per translated graphics pipeline (its blend state and shader hashes) and per RTV (its mip and slice).
  • On, in the followed frames: each draw on a direct list records, before itself and again after, one barrier batch to COPY_SOURCE, one 1×1 copy per followed target and point, and one barrier batch back. Round 2 adds one crop copy per point for the draws of the pipelines that matter. Recording also takes a few locks per draw (the round's session and the maps).
  • Memory: 64 MiB of readback memory a round with the default slots, plus at most 256 MiB for the crops. These buffers are kept until the process ends, because a list recorded in a round may still run after the readout.

Tested

  • Hardware: RTX 3090 (driver 616.56), Ryzen 9 5950X, Windows 11, rustc 1.100.0, release build, on main d52ff48c + this commit (89523904).
  • cargo test --release -p xcl --lib -- pixel_history:: skip_ps_tests::: 6 passed, 0 failed, 0 ignored. The 6 tests are:
    • pixel_history_settings_parse: the switches' parsing, including rejected values.
    • unset_pixel_history_changes_nothing: unset, no round, no session, no map, and a draw's hooks do not touch the list (a dangling pointer in the test).
    • points_map_by_each_targets_own_size: mapping a point to full, half, quarter and 2560x1440 targets; other shapes refused; crop placement at the edges.
    • followed_formats_decode_and_others_fail_closed.
    • skip_ps_hashes_parse_and_unset_skips_nothing.
    • gpu_a_targets_texel_is_read_before_and_after_a_draw: on the default adapter, else WARP. A texel copied before and after a "draw" (a clear) between the same barriers reads back as both values; an unreached slot still holds the sentinel; a crop around the point holds the new value and turns into a BMP.
  • In game: the run described above, on the same tool, rebased here onto main without other changes than the start time, the doc comments and the log text.
  • Read, CI: "Build and test (Windows, no GPU)" passed on this head.

Regression run
Same machine as under Tested, same title, 60 s each (the scripts/smoke.ps1 default), both through main d52ff48's scripts/smoke.ps1, XCL_PREPARE=0, the same scripted A presses (XCL_PRESS_A_AT), XCL_PIXEL_HISTORY and XCL_SKIP_PS unset. Each run started from its own copy of the same shader cache, made by another main commit, so cold for both.

main d52ff48:

xcl-smoke v1
commit: d52ff48caade1f5350d513bfffd370396dadfeb6
gpu: NVIDIA GeForce RTX 3090
title: 16b5e5d4
seconds: 60
exit: 0x0
frames shown: 517 (PresentX 517)
presents per 2 s (last 3): 61 60 61
device removals: 0
crashes: 0
peak commit: 15968 MB

this head 8952390 (main d52ff48 + this commit):

xcl-smoke v1
commit: 895239041462ab51c15be990cbd63dd0838e5dac
gpu: NVIDIA GeForce RTX 3090
title: 16b5e5d4
seconds: 60
exit: 0x0
frames shown: 554 (PresentX 554)
presents per 2 s (last 3): 61 61 60
device removals: 0
crashes: 0
peak commit: 16424 MB
  • Measured: no device removal and no crash in either run, both ended by themselves (exit 0x0). The head shows 554 frames against main's 517 (107.2 %; the check wants at least 80 %), peak commit 16,424 MB against 15,968 MB (102.9 %; at most 125 %). Last three 2 s slices: head 61 61 60, main 61 60 61 presents. 60 s covers the start of the title, not a long stay in its world.

Not tested

  • A title run of this exact head with the switches set: the in-game run above used the earlier form of the tool on our lab tree.
  • AMD and Intel GPUs, other NVIDIA generations, and other titles.
  • What the tool leaves out, by design (so nothing was tested there):
    • Multisampled render targets and depth buffers are not followed; they are counted in the summary. A copy out of a depth buffer must take its whole subresource, which is too costly per draw.
    • Formats other than the ones listed above are not followed either.
    • UAV writes (compute, or pixel shaders writing UAVs) show up only as a BETWEEN line. Copying around a dispatch would need the target's state, which is not known there.
    • Mesh-shader draws (DispatchMesh) and draws on bundles are not followed, and XCL_SKIP_PS does not apply to them.
    • Frames are counted at PresentX on the recording side, so lists recorded before the round's first present are not followed. In the run above, the round saw 664 draws of the roughly 4500 per frame that the activity lines count. We did not check which of these causes accounts for the rest.
    • Points are mapped by each target's size. A target drawn at a dynamic resolution (a viewport smaller than the target) would be mapped wrongly.
    • The order of events is the recording order within a list. Across lists, the log does not give the GPU's execution order.
    • The extra barriers per draw can hide a race. A defect that goes away while the history runs is a finding in itself.

AI use
AI use: the tool, its tests, the in-game run, the smoke runs and this description were done with Claude Code (Claude Opus 5.5), checked and posted by me.

🤖 Generated with Claude Code

<!-- greyfinch-sync:ivall/xcl:issue:5560058617 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3509). Originally posted by [CharlyRien](https://github.com/CharlyRien) on 2026-11-30T06:11:50Z. --- Two diagnostic switches to find which draw writes a wrong pixel. PIX and Nsight frame captures do not replay a title running under XCL, so we could not use their pixel history. These switches do the same job inside the process. Both are off by default. Unset, each one costs a draw one cached check. **What is in it** - `XCL_PIXEL_HISTORY=<x>,<y>[,<s>[,<frames>]]` (`d3d12x/pixel_history.rs`, new). - It starts at the first present `s` seconds (default 0) or more after the first one, and follows `frames` frames (default 1, at most 8). - Around each draw on a direct list (direct and indirect draws), it copies one texel before and after the draw into a readback buffer: the texel at pixel `x`, `y` of the presented picture in each bound render target that has the picture's shape. Each copy is a 1×1 `CopyTextureRegion` between a RENDER_TARGET → COPY_SOURCE transition and its way back. - The point is mapped by each target's own size (its RTV's mip), so half- and quarter-size targets are followed too. A target counts as having the picture's shape when its aspect ratio is within 1 % and it is at least an eighth of the picture's width. - Six presents later, the values are read back and logged (see below). - Related switches: - `XCL_PIXEL_HISTORY_SPACE=<w>x<h>`: the size of the picture that `x`, `y` are given in (default 3840x2160). - `XCL_PIXEL_HISTORY_ALSO=<x>,<y>[;<x>,<y>]`: up to 3 more points. - `XCL_PIXEL_HISTORY_CROP=<w>,<h>[,<n>]`: a second round of as many frames. In it, only the draws whose pipeline changed a point in the first round also copy a `w`×`h` crop around the point after themselves. The crops of the draws that change the point are written as BMPs (`pixel-history/<frame>_<event>_<ps>_p<point>rt<slot>.bmp` next to `xcl.log`, at most `n` a frame, default 200). - `XCL_PIXEL_HISTORY_SLOTS`: the readback slots of a round (default 131072 slots of 512 bytes). - `XCL_SKIP_PS=<hash>,<hash>`: leaves out the draws (direct and indirect) whose console pixel shader has one of these hashes, the way `XCL_SKIP_CS` leaves out dispatches, and counts them in the log. Use it to confirm that the draw the history found is the one at fault. - Hooks: `bind.rs` (draw, indexed draw, ExecuteIndirect, dispatch), `real.rs` (RTV mip / slice, the pipeline's blend state, console VS / PS hashes kept while either switch is set), `present.rs` (one call at each present). - A README paragraph in the diagnostics list. **Reading the output** (`grep -a "pixel history" xcl.log`) - `XCL_PIXEL_HISTORY: points [...] of a WxH present, N frames from S s after the first present, ...`: the settings, read once. - `pixel history r1: point 0 (x, y) -> target 0x… sub S WxH format F at (tx, ty)`: once per target. It shows where the point landed in that target. - `pixel history r1: f<frame> ev <seq> list 0x… #<i> [indirect ]draw vs <hash> ps <hash> pso 0x… p<k> rt<n> WxH fmt F at (tx, ty): (before) [raw] -> (after) [raw]; <blend state of that slot>`: one line per draw that **changed** the texel. The values are decoded (RGBA8 / BGRA8, RGBA16 float, R11G11B10, R10G10B10A2, R32 float), with the raw bytes in brackets. Read the lines in (frame, list, `#i`) order. The last change before the present, on the scene's target, tells which draw wrote the final value, and the blend state tells how. - `pixel history r1: f… list 0x… p<k> rt<n> …: changed BETWEEN draws #a (ev …) and #b (ev …): … -> …; dispatches between: #i cs <hash>, …`: the texel changed between two draws of one list. This means a compute pass (named by its `cs`), a clear, a copy or a resolve wrote it. - `pixel history r1 done: … events (… draws), … slots used; … changes by draws, … between draws, … copies not done (list not run yet); targets not followed: … by shape, … by format, … multisampled, … other; … slots full, … crops full; … crops written`: the round's summary. "Copies not done" are copies whose list had not run by the readout (their slots still hold a 0xA5 sentinel). They are counted, not read. - With `_CROP`, an `r2` round follows with the same lines, and its crops are written. **Measured use.** On the retail title, a pose in front of a window where one diagonal half of the glass turns black. One run with two points (one on the dark half, one control) and one frame per round, plus 64×64 crops. The history named the depth-of-field composite, an indirect draw blending SRC_ALPHA / INV_SRC_ALPHA, as the draw that set the texel to RGB 0. It also showed the DoF downsample writing RGB 0 at every watched point. `XCL_SKIP_PS` on the composite's pixel shader then gave a clean window. That led to #3281's case: a R9G9B9E5 view placed over an R32_UINT texture. Report: https://github.com/xcl-dev/xcl/pull/3281#issuecomment-7269873202. That run used an earlier form of this tool, in which the start could also be counted from a busy-draws heuristic. This PR keeps only seconds after the first present, which does not depend on the title. Numbers from that run (RTX 3090): - Round 1: 5635 events (664 draws on direct lists, the rest dispatches) and 1720 slots used. It logged 19 changes by draws and 1 between draws, with 0 copies not done. Targets not followed: 28 by shape, 305 by format. - Round 2: 1600 crops of 32 KiB were allocated and 15 were written. - The log line of each round came about 7 s after its first frame. At that pose the title ran at about one present a second, and the 2 s activity lines kept 1–2 presents through both rounds. One 2 s window at the start of round 1 had about half the usual draws (4790 against about 9000), which did not happen around round 2. We did not look further into it. **Cost** - Off (the default): a draw's hook loads one atomic for the history and makes one cached check for `XCL_SKIP_PS`; a dispatch's hook loads the same atomic. The hooks at pipeline creation, RTV creation and present check cached values only. Nothing is allocated. A test checks that the hooks do not even look at the command list when the switch is unset. - On, outside the followed frames: the same per draw, plus one map entry per translated graphics pipeline (its blend state and shader hashes) and per RTV (its mip and slice). - On, in the followed frames: each draw on a direct list records, before itself and again after, one barrier batch to COPY_SOURCE, one 1×1 copy per followed target and point, and one barrier batch back. Round 2 adds one crop copy per point for the draws of the pipelines that matter. Recording also takes a few locks per draw (the round's session and the maps). - Memory: 64 MiB of readback memory a round with the default slots, plus at most 256 MiB for the crops. These buffers are kept until the process ends, because a list recorded in a round may still run after the readout. **Tested** - Hardware: RTX 3090 (driver 616.56), Ryzen 9 5950X, Windows 11, rustc 1.100.0, release build, on `main` d52ff48c + this commit (89523904). - `cargo test --release -p xcl --lib -- pixel_history:: skip_ps_tests::`: 6 passed, 0 failed, 0 ignored. The 6 tests are: - `pixel_history_settings_parse`: the switches' parsing, including rejected values. - `unset_pixel_history_changes_nothing`: unset, no round, no session, no map, and a draw's hooks do not touch the list (a dangling pointer in the test). - `points_map_by_each_targets_own_size`: mapping a point to full, half, quarter and 2560x1440 targets; other shapes refused; crop placement at the edges. - `followed_formats_decode_and_others_fail_closed`. - `skip_ps_hashes_parse_and_unset_skips_nothing`. - `gpu_a_targets_texel_is_read_before_and_after_a_draw`: on the default adapter, else WARP. A texel copied before and after a "draw" (a clear) between the same barriers reads back as both values; an unreached slot still holds the sentinel; a crop around the point holds the new value and turns into a BMP. - In game: the run described above, on the same tool, rebased here onto `main` without other changes than the start time, the doc comments and the log text. - Read, CI: "Build and test (Windows, no GPU)" passed on this head. **Regression run** Same machine as under **Tested**, same title, 60 s each (the `scripts/smoke.ps1` default), both through `main` `d52ff48`'s `scripts/smoke.ps1`, `XCL_PREPARE=0`, the same scripted A presses (`XCL_PRESS_A_AT`), `XCL_PIXEL_HISTORY` and `XCL_SKIP_PS` unset. Each run started from its own copy of the same shader cache, made by another `main` commit, so cold for both. `main` `d52ff48`: ``` xcl-smoke v1 commit: d52ff48caade1f5350d513bfffd370396dadfeb6 gpu: NVIDIA GeForce RTX 3090 title: 16b5e5d4 seconds: 60 exit: 0x0 frames shown: 517 (PresentX 517) presents per 2 s (last 3): 61 60 61 device removals: 0 crashes: 0 peak commit: 15968 MB ``` this head `8952390` (`main` `d52ff48` + this commit): ``` xcl-smoke v1 commit: 895239041462ab51c15be990cbd63dd0838e5dac gpu: NVIDIA GeForce RTX 3090 title: 16b5e5d4 seconds: 60 exit: 0x0 frames shown: 554 (PresentX 554) presents per 2 s (last 3): 61 61 60 device removals: 0 crashes: 0 peak commit: 16424 MB ``` - Measured: no device removal and no crash in either run, both ended by themselves (exit 0x0). The head shows 554 frames against `main`'s 517 (107.2 %; the check wants at least 80 %), peak commit 16,424 MB against 15,968 MB (102.9 %; at most 125 %). Last three 2 s slices: head 61 61 60, `main` 61 60 61 presents. 60 s covers the start of the title, not a long stay in its world. **Not tested** - A title run of this exact head with the switches set: the in-game run above used the earlier form of the tool on our lab tree. - AMD and Intel GPUs, other NVIDIA generations, and other titles. - What the tool leaves out, by design (so nothing was tested there): - Multisampled render targets and depth buffers are not followed; they are counted in the summary. A copy out of a depth buffer must take its whole subresource, which is too costly per draw. - Formats other than the ones listed above are not followed either. - UAV writes (compute, or pixel shaders writing UAVs) show up only as a BETWEEN line. Copying around a dispatch would need the target's state, which is not known there. - Mesh-shader draws (`DispatchMesh`) and draws on bundles are not followed, and `XCL_SKIP_PS` does not apply to them. - Frames are counted at PresentX on the recording side, so lists recorded before the round's first present are not followed. In the run above, the round saw 664 draws of the roughly 4500 per frame that the activity lines count. We did not check which of these causes accounts for the rest. - Points are mapped by each target's size. A target drawn at a dynamic resolution (a viewport smaller than the target) would be mapped wrongly. - The order of events is the recording order within a list. Across lists, the log does not give the GPU's execution order. - The extra barriers per draw can hide a race. A defect that goes away while the history runs is a finding in itself. **AI use** AI use: the tool, its tests, the in-game run, the smoke runs and this description were done with Claude Code (Claude Opus 5.5), checked and posted by me. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Aniseto commented 2026-11-30 12:05:57 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Aniseto on 2026-11-30T12:05:57Z.


Ran the pixel-history and pixel-shader skip tests at 89523904 on an NVIDIA Blackwell desktop part.

System

  • GPU: NVIDIA GeForce RTX 5070 Ti (Blackwell, 32-lane waves only, mesh shaders), driver 32.0.16.2140 (621.40)
  • CPU: Intel Core i5-12400F, 64 GB RAM
  • OS: Windows 11 Pro build 26200 x64
  • Toolchain: rustc 1.100.0 (0ef1bc386 2026-11-09), MSVC 14.44.35207, DXC 1.9.2609.5
  • Build: debug

Results

  • XCL_ADAPTER=NVIDIA cargo test -p xcl --lib pixel_history:: -- --test-threads=1: 5 passed, 0 failed, 0 ignored.
  • XCL_ADAPTER=NVIDIA cargo test -p xcl --lib skip_ps_tests:: -- --test-threads=1: 1 passed, 0 failed, 0 ignored.

What this adds
All six tests pass, including the check that with the switches unset a draw's hooks do not even look at the command list. The author ran the same six in release; this adds a debug run on driver 32.0.16.2140 from a second NVIDIA card. No title A/B with XCL_PIXEL_HISTORY or XCL_SKIP_PS was made here.

Not tested
A retail title with the switches set, a paired smoke run, the full workspace suite, AMD and Intel GPUs, native wave64 hosts, Wine, release profile, game data.

AI-assisted (OpenCode), model: DeepSeek V4.1 Flash Free - ran the commands above on this machine and wrote this report; no game data was used.

<!-- greyfinch-sync:ivall/xcl:comment:7277943175 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3509#issuecomment-7277943175). Originally posted by [Aniseto](https://github.com/Aniseto) on 2026-11-30T12:05:57Z. --- Ran the pixel-history and pixel-shader skip tests at `89523904` on an NVIDIA Blackwell desktop part. **System** - GPU: NVIDIA GeForce RTX 5070 Ti (Blackwell, 32-lane waves only, mesh shaders), driver 32.0.16.2140 (621.40) - CPU: Intel Core i5-12400F, 64 GB RAM - OS: Windows 11 Pro build 26200 x64 - Toolchain: rustc 1.100.0 (0ef1bc386 2026-11-09), MSVC 14.44.35207, DXC 1.9.2609.5 - Build: debug **Results** - `XCL_ADAPTER=NVIDIA cargo test -p xcl --lib pixel_history:: -- --test-threads=1`: 5 passed, 0 failed, 0 ignored. - `XCL_ADAPTER=NVIDIA cargo test -p xcl --lib skip_ps_tests:: -- --test-threads=1`: 1 passed, 0 failed, 0 ignored. **What this adds** All six tests pass, including the check that with the switches unset a draw's hooks do not even look at the command list. The author ran the same six in release; this adds a debug run on driver 32.0.16.2140 from a second NVIDIA card. No title A/B with `XCL_PIXEL_HISTORY` or `XCL_SKIP_PS` was made here. **Not tested** A retail title with the switches set, a paired smoke run, the full workspace suite, AMD and Intel GPUs, native wave64 hosts, Wine, release profile, game data. AI-assisted (OpenCode), model: **DeepSeek V4.1 Flash Free** - ran the commands above on this machine and wrote this report; no game data was used.
Foniass commented 2026-12-01 08:54:51 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-01T08:54:51Z.


merge-check
base: 7d86c5d2b7
head: 8952390414
merge: clean
build: cargo build --workspace -> ok
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2902 passed, 0 failed, 51 ignored; SKIPPED: 28 (20 no wave64, 2 no d3d12SDKLayers.dll, 1 no D3D12 debug layer, 1 no heap windows, 1 cannot disable the driver cache, 3 others; the same set as on main); failing: none
review: read the whole diff (new pixel_history.rs +914, real.rs +54, bind.rs +18, README, present.rs, mod.rs). Findings: (1) two independent diagnostics in one 1,006-line PR with no reason given for going past 800; XCL_SKIP_PS (~70 lines in real.rs / bind.rs) splits off cleanly, and the _CROP round could follow. (2) Cost when off: bind.rs ~4183 evaluates with(this, |s| s.pso) (a lock plus a state lookup) on every indexed draw before pixel_history::before checks ROUND, so "unset, a draw's hooks load one atomic" doesn't hold on that path; unset_pixel_history_changes_nothing calls before() directly and misses it. Checking ROUND first, or reusing the PSO already read for gpu_profile, would fix it. (3) With XCL_PIXEL_HISTORY_ALSO, bound_targets pushes one Target per point with the same resource and subresource and copy_texels (~410 / ~431) puts them all in one ResourceBarrier call, transitioning the same subresource RENDER_TARGET -> COPY_SOURCE more than once, which the debug layer rejects; deduplicate by (resource, subresource). (4) real.rs ~8268 records shader hashes only when XCL_TRACE_FRAME is unset, so XCL_SKIP_PS silently does nothing while it's set. Readout is timed (6 presents) with no fence, acceptable for a diagnostic given the sentinel. Fine: off by default, parsing and limits, 512 / 256-aligned slot offsets and row pitch, readback buffers kept until the process ends, per-mip point mapping, the GPU test uses skip_test, and "Not tested" is honest that the in-game run used an earlier form.
performance: 60 s smoke of a retail title, main 7d86c5d2 vs this merge (4b1b9daa): 1663 -> 1669 frames shown (100 %; last presents per 2 s: 60 60 60), peak commit 17153 -> 17723 MB, 0 device removals, 0 crashes.
verdict: not yet: 1,006 lines with two separate diagnostics and no reason given for passing 800 (split off XCL_SKIP_PS); and the off path still takes a lock per indexed draw (finding 2). Findings 3 and 4 are bugs in the opt-in paths
hardware / tool and model: RTX 5070 Ti (driver 621.14), Ryzen 7 7800X3D, Windows 11 26300 / Claude Code with Claude Opus 5.5

AI-written and posted by Foniass without a human check of each point.

<!-- greyfinch-sync:ivall/xcl:comment:7305952031 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3509#issuecomment-7305952031). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-01T08:54:51Z. --- merge-check base: 7d86c5d2b7845695031eeea1327aa81b6c439323 head: 895239041462ab51c15be990cbd63dd0838e5dac merge: clean build: cargo build --workspace -> ok tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2902 passed, 0 failed, 51 ignored; SKIPPED: 28 (20 no wave64, 2 no d3d12SDKLayers.dll, 1 no D3D12 debug layer, 1 no heap windows, 1 cannot disable the driver cache, 3 others; the same set as on main); failing: none review: read the whole diff (new `pixel_history.rs` +914, `real.rs` +54, `bind.rs` +18, README, `present.rs`, `mod.rs`). Findings: (1) two independent diagnostics in one 1,006-line PR with no reason given for going past 800; `XCL_SKIP_PS` (~70 lines in `real.rs` / `bind.rs`) splits off cleanly, and the `_CROP` round could follow. (2) Cost when off: `bind.rs` ~4183 evaluates `with(this, |s| s.pso)` (a lock plus a state lookup) on every indexed draw before `pixel_history::before` checks `ROUND`, so "unset, a draw's hooks load one atomic" doesn't hold on that path; `unset_pixel_history_changes_nothing` calls `before()` directly and misses it. Checking `ROUND` first, or reusing the PSO already read for `gpu_profile`, would fix it. (3) With `XCL_PIXEL_HISTORY_ALSO`, `bound_targets` pushes one `Target` per point with the same resource and subresource and `copy_texels` (~410 / ~431) puts them all in one `ResourceBarrier` call, transitioning the same subresource RENDER_TARGET -> COPY_SOURCE more than once, which the debug layer rejects; deduplicate by (resource, subresource). (4) `real.rs` ~8268 records shader hashes only when `XCL_TRACE_FRAME` is unset, so `XCL_SKIP_PS` silently does nothing while it's set. Readout is timed (6 presents) with no fence, acceptable for a diagnostic given the sentinel. Fine: off by default, parsing and limits, 512 / 256-aligned slot offsets and row pitch, readback buffers kept until the process ends, per-mip point mapping, the GPU test uses `skip_test`, and "Not tested" is honest that the in-game run used an earlier form. performance: 60 s smoke of a retail title, main 7d86c5d2 vs this merge (4b1b9daa): 1663 -> 1669 frames shown (100 %; last presents per 2 s: 60 60 60), peak commit 17153 -> 17723 MB, 0 device removals, 0 crashes. verdict: not yet: 1,006 lines with two separate diagnostics and no reason given for passing 800 (split off `XCL_SKIP_PS`); and the off path still takes a lock per indexed draw (finding 2). Findings 3 and 4 are bugs in the opt-in paths hardware / tool and model: RTX 5070 Ti (driver 621.14), Ryzen 7 7800X3D, Windows 11 26300 / Claude Code with Claude Opus 5.5 AI-written and posted by Foniass without a human check of each point.
Foniass commented 2026-12-01 10:06:00 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-01T10:06:00Z.


Triage (#1607) – head 8952390

Only XCL_SKIP_PS overlaps #1827 (XCL_DEBUG_SKIP_SHADERS); both leave out draws by the console shader hash from real::pso_shaders. #1827 matches VS or PS but fills those hashes only with XCL_TRACE_FRAME or the profilers. Here pixel_history::keeps_shaders fills them whenever XCL_SKIP_PS is set. The pixel-history tool itself has no counterpart.
Default cost checked: unset, before / after load one atomic and the creation hooks return on on(). No problems found in the diff.
At about 1000 lines, the description should say why it cannot be split (for example, XCL_SKIP_PS on its own).
Recommendation: keep open.

AI review: Claude Code (Claude Opus 5.5), diffs read only, not built or run; not checked by a human.

<!-- greyfinch-sync:ivall/xcl:comment:7307666951 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3509#issuecomment-7307666951). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-01T10:06:00Z. --- **Triage (#1607)** – head 8952390 Only `XCL_SKIP_PS` overlaps #1827 (`XCL_DEBUG_SKIP_SHADERS`); both leave out draws by the console shader hash from `real::pso_shaders`. #1827 matches VS or PS but fills those hashes only with `XCL_TRACE_FRAME` or the profilers. Here `pixel_history::keeps_shaders` fills them whenever `XCL_SKIP_PS` is set. The pixel-history tool itself has no counterpart. Default cost checked: unset, `before` / `after` load one atomic and the creation hooks return on `on()`. No problems found in the diff. At about 1000 lines, the description should say why it cannot be split (for example, `XCL_SKIP_PS` on its own). Recommendation: keep open. AI review: Claude Code (Claude Opus 5.5), diffs read only, not built or run; not checked by a human.
bmjask commented 2026-12-02 09:44:51 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T09:44:51Z.

Code review location: crates/xcl/src/hle/d3d12x/pixel_history.rs; line 410

@@ -0,0 +1,914 @@
+//! `XCL_PIXEL_HISTORY=<x>,<y>[,<s>[,<frames>]]` (diagnostic): which draw writes a pixel.
+//!
+//! PIX and Nsight frame captures do not replay a title under XCL, so this answers "which draw
+//! wrote this pixel" in the process. `x`, `y` are pixels of the presented picture
+//! (`XCL_PIXEL_HISTORY_SPACE=<w>x<h>`, default 3840x2160). `frames` frames (default 1, 8 at
+//! most) are followed, from the first present `s` seconds (default 0) or more after the first one.
+//! `XCL_PIXEL_HISTORY_ALSO=<x>,<y>[;<x>,<y>]` adds up to 3 more points.
+//!
+//! In those frames every draw (direct and indirect) on a direct list copies, before and after
+//! itself, the texel at each point of each bound render target into a readback buffer (1×1
+//! CopyTextureRegion between a RENDER_TARGET → COPY_SOURCE transition and its way back). A
+//! target is followed when it has the present's shape (within 1 %, an eighth of its width at
+//! least): the point is mapped by the target's own size (its RTV's mip). `GAP` presents later
+//! the values are read back and one line is logged per draw that CHANGED a texel – frame, event,
+//! console VS / PS, the target, the value before and after decoded, the pipeline's blend state
+//! for that slot – and one line per change between two draws of a list (a dispatch, a clear or
+//! a copy in between: the dispatches' CS are named).
+//!
+//! Formats followed: R8G8B8A8 and B8G8R8A8 (all three types), R16G16B16A16 (float or
+//! typeless read as float), R11G11B10_FLOAT, R10G10B10A2, R32 (float or typeless read as float).
+//! Other targets, multisampled ones, and depth buffers (a copy of a depth buffer must take its
+//! whole subresource) are not followed and counted as such. UAV writes are seen only as a change
+//! between two draws.
+//!
+//! `XCL_PIXEL_HISTORY_CROP=<w>,<h>[,<per frame>]`: a second round of as many frames follows the
+//! first, in which the draws whose pipeline changed a point in the first round also copy a
+//! `w`×`h` crop of the target around it after themselves; the crops of draws that changed the
+//! point are written (`pixel-history/<frame>_<event>_<ps>_p<point>rt<slot>.bmp` in the logs
+//! folder, decoded as the target dump does: NaN and infinities white), `per frame` of them at
+//! most (default 200).
+//!
+//! The readback buffers (`XCL_PIXEL_HISTORY_SLOTS` slots of 512 bytes, default 131072: 64 MiB of
+//! system memory a round, plus the crops' at most 256 MiB) are kept to the end of the process (a
+//! list recorded in a round may run after its readout).
+//!
+//! Cost: unset, a draw's hooks load one atomic and return, and the hooks at pipeline and view
+//! creation check one cached value; nothing is created. Set, outside the followed frames, the same
+//! for draws, and each translated graphics pipeline and render target view is noted in a map. In
+//! the followed frames, each draw on a direct list records two barriers and one 1×1 copy per
+//! followed target and point before itself, and the same after (plus a crop copy in round 2).
+
+use std::collections::{HashMap, HashSet};
+use std::ffi::c_void;
+use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
+use std::sync::{Mutex, OnceLock};
+use std::time::Instant;
+
+use windows::core::Interface;
+use windows::Win32::Graphics::Direct3D12::*;
+use windows::Win32::Graphics::Dxgi::Common::*;
+
+/// a copy's place in a readback buffer (D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT)
+const SLOT: u64 = 512;
+/// what a slot holds before a copy reached it
+const SENTINEL: u8 = 0xA5;
+/// presents between a round's last frame and its readout
+const GAP: u64 = 6;
+/// frames a round follows, at most
+const FRAMES_MOST: u64 = 8;
+/// points followed, at most (`XCL_PIXEL_HISTORY` and `_ALSO`)
+const POINTS_MOST: usize = 4;
+/// crop buffer of a round, at most
+const CROP_BYTES_MOST: u64 = 256 << 20;
+
+/// The switches, read once (`config`).
+#[derive(Clone, Debug, PartialEq)]
+pub(super) struct Config {
+    /// in the present's pixels
+    points: Vec<(u32, u32)>,
+    /// seconds after the first present the first round starts
+    after: f64,
+    /// frames a round follows
+    frames: u64,
+    /// the present's size the points are given in
+    space: (u32, u32),
+    /// (width, height, crops written a frame)
+    crop: Option<(u32, u32, usize)>,
+    /// readback slots of a round
+    slots: u32,
+}
+
+/// `<a><sep><b>` as two numbers.
+fn pair(s: &str, sep: char) -> Option<(u32, u32)> {
+    let (a, b) = s.split_once(sep)?;
+    Some((a.trim().parse().ok()?, b.trim().parse().ok()?))
+}
+
+/// The switches' values (`v`: `XCL_PIXEL_HISTORY`, then `_ALSO`, `_SPACE`, `_CROP`, `_SLOTS`).
+fn parse(v: &str, also: Option<&str>, space: Option<&str>, crop: Option<&str>, slots: Option<&str>) -> Result<Config, String> {
+    let f: Vec<&str> = v.split(',').map(str::trim).collect();
+    if f.len() < 2 || f.len() > 4 {
+        return Err("not <x>,<y>[,<s>[,<frames>]]".into());
+    }
+    let mut points = vec![(f[0].parse().map_err(|_| format!("x {:?} is not a number", f[0]))?, f[1].parse().map_err(|_| format!("y {:?} is not a number", f[1]))?)];
+    let after = match f.get(2) {
+        None | Some(&"") => 0.0,
+        Some(s) => s.parse::<f64>().ok().filter(|s| s.is_finite() && *s >= 0.0).ok_or_else(|| format!("{s:?} is not seconds"))?,
+    };
+    let frames = match f.get(3) {
+        None => 1,
+        Some(s) => s.parse::<u64>().map_err(|_| format!("frames {s:?} is not a number"))?.clamp(1, FRAMES_MOST),
+    };
+    for p in also.unwrap_or("").split(';').map(str::trim).filter(|p| !p.is_empty()) {
+        points.push(pair(p, ',').ok_or_else(|| format!("XCL_PIXEL_HISTORY_ALSO point {p:?} is not <x>,<y>"))?);
+    }
+    points.truncate(POINTS_MOST);
+    let space = match space {
+        Some(s) => pair(s, 'x').filter(|&(w, h)| w > 0 && h > 0).ok_or_else(|| format!("XCL_PIXEL_HISTORY_SPACE={s:?} is not <w>x<h>"))?,
+        None => (3840, 2160),
+    };
+    if let Some(&(x, y)) = points.iter().find(|&&(x, y)| x >= space.0 || y >= space.1) {
+        return Err(format!("point ({x}, {y}) is outside the {}x{} present (XCL_PIXEL_HISTORY_SPACE)", space.0, space.1));
+    }
+    let crop = match crop {
+        None => None,
+        Some(c) => {
+            let p: Vec<&str> = c.split(',').map(str::trim).collect();
+            let n = |s: &str| s.parse::<u32>().ok().filter(|&n| (1..=256).contains(&n));
+            match (p.len(), p.first().and_then(|s| n(s)), p.get(1).and_then(|s| n(s))) {
+                (2 | 3, Some(w), Some(h)) => Some((w, h, p.get(2).map_or(Some(200), |s| s.parse().ok()).ok_or_else(|| format!("XCL_PIXEL_HISTORY_CROP={c:?}: crops a frame not a number"))?)),
+                _ => return Err(format!("XCL_PIXEL_HISTORY_CROP={c:?} is not <w>,<h>[,<per frame>] (1..256)")),
+            }
+        }
+    };
+    let slots = match slots {
+        Some(s) => s.parse::<u32>().ok().filter(|n| (1024..=1 << 20).contains(n)).ok_or_else(|| format!("XCL_PIXEL_HISTORY_SLOTS={s:?} is not 1024..1048576"))?,
+        None => 131072,
+    };
+    Ok(Config { points, after, frames, space, crop, slots })
+}
+
+/// The switches, read and logged once; None when `XCL_PIXEL_HISTORY` is unset or not valid.
+pub(super) fn config() -> Option<&'static Config> {
+    static C: OnceLock<Option<Config>> = OnceLock::new();
+    C.get_or_init(|| {
+        let v = std::env::var("XCL_PIXEL_HISTORY").ok()?;
+        let e = |k: &str| std::env::var(k).ok();
+        match parse(&v, e("XCL_PIXEL_HISTORY_ALSO").as_deref(), e("XCL_PIXEL_HISTORY_SPACE").as_deref(), e("XCL_PIXEL_HISTORY_CROP").as_deref(), e("XCL_PIXEL_HISTORY_SLOTS").as_deref()) {
+            Ok(c) => {
+                crate::xlog_info!(
+                    "D3D12.X: XCL_PIXEL_HISTORY: points {:?} of a {}x{} present, {} frames from {:.1} s after the first present, {} readback slots{}",
+                    c.points, c.space.0, c.space.1, c.frames, c.after, c.slots, c.crop.map_or(String::new(), |(w, h, n)| format!(", then {w}x{h} crops ({n} a frame at most)"))
+                );
+                Some(c)
+            }
+            Err(e) => {
+                crate::xlog_warn!("D3D12.X: XCL_PIXEL_HISTORY={v:?}: {e}: no pixel history");
+                None
+            }
+        }
+    })
+    .as_ref()
+}
+
+/// Whether `XCL_PIXEL_HISTORY` is set (and valid).
+pub(super) fn on() -> bool {
+    config().is_some()
+}
+
+/// Whether translated graphics pipelines keep their console VS / PS hashes (`real::pso_shaders`).
+pub(super) fn keeps_shaders() -> bool {
+    on() || super::real::skip_ps_on()
+}
+
+/// Bytes of a texel of a followed format; None: not followed.
+fn texel_bytes(fmt: i32) -> Option<usize> {
+    match fmt {
+        9 | 10 => Some(8),
+        23 | 24 | 26 | 27 | 28 | 29 | 39 | 41 | 87 | 90 | 91 => Some(4),
+        _ => None,
+    }
+}
+
+/// A texel of a followed format as its channels (R, G, B[, A]).
+pub(super) fn decode(fmt: i32, t: &[u8]) -> Option<Vec<f32>> {
+    if t.len() < texel_bytes(fmt)? {
+        return None;
+    }
+    let w = u32::from_le_bytes([t[0], t[1], t[2], t[3]]);
+    let half = |i: usize| super::present::half_float(u16::from_le_bytes([t[i], t[i + 1]]));
+    let u8s = |i: usize| t[i] as f32 / 255.0;
+    Some(match fmt {
+        9 | 10 => vec![half(0), half(2), half(4), half(6)],
+        23 | 24 => vec![(w & 1023) as f32 / 1023.0, (w >> 10 & 1023) as f32 / 1023.0, (w >> 20 & 1023) as f32 / 1023.0, (w >> 30) as f32 / 3.0],
+        26 => vec![super::present::small_float(w & 0x7FF, 6), super::present::small_float(w >> 11 & 0x7FF, 6), super::present::small_float(w >> 22, 5)],
+        27..=29 => vec![u8s(0), u8s(1), u8s(2), u8s(3)],
+        87 | 90 | 91 => vec![u8s(2), u8s(1), u8s(0), u8s(3)],
+        39 | 41 => vec![f32::from_bits(w)],
+        _ => return None,
+    })
+}
+
+/// A texel for the log: its channels decoded, then its raw bytes (high byte first).
+fn decoded_text(fmt: i32, t: &[u8]) -> String {
+    let raw: String = t.iter().rev().map(|b| format!("{b:02x}")).collect();
+    match decode(fmt, t) {
+        Some(c) => format!("({}) [{raw}]", c.iter().map(|v| format!("{v:.4}")).collect::<Vec<_>>().join(", ")),
+        None => format!("[{raw}]"),
+    }
+}
+
+/// Point `p` of a `space` present in a target of `size`: None when the target has not the
+/// present's shape (within 1 %) or is narrower than an eighth of it.
+pub(super) fn map_point(p: (u32, u32), space: (u32, u32), size: (u32, u32)) -> Option<(u32, u32)> {
+    let ((pw, ph), (tw, th)) = (space, size);
+    if pw == 0 || ph == 0 || tw == 0 || th == 0 || p.0 >= pw || p.1 >= ph {
+        return None;
+    }
+    let (a, b) = (tw as u64 * ph as u64, th as u64 * pw as u64);
+    if a.abs_diff(b) * 100 > b || tw as u64 * 8 < pw as u64 {
+        return None;
+    }
+    let m = |v: u32, from: u32, to: u32| (((v as u64 * 2 + 1) * to as u64 / (2 * from as u64)) as u32).min(to - 1);
+    Some((m(p.0, pw, tw), m(p.1, ph, th)))
+}
+
+/// The top-left corner of a `c` crop of a `size` target around `at` (inside the target).
+fn crop_origin(at: (u32, u32), c: (u32, u32), size: (u32, u32)) -> ((u32, u32), (u32, u32)) {
+    let (w, h) = (c.0.min(size.0), c.1.min(size.1));
+    ((at.0.saturating_sub(w / 2).min(size.0 - w), at.1.saturating_sub(h / 2).min(size.1 - h)), (w, h))
+}
+
+/// RTV handle → (mip, first array slice) its view names
+static RTV_VIEWS: Mutex<Option<HashMap<usize, (u32, u32)>>> = Mutex::new(None);
+
+/// A render target view was made (`real::dev_create_rtv`).
+pub(super) unsafe fn note_rtv(handle: usize, desc: Option<&D3D12_RENDER_TARGET_VIEW_DESC>) {
+    if !on() {
+        return;
+    }
+    let v = desc.map_or((0, 0), |d| match d.ViewDimension {
+        D3D12_RTV_DIMENSION_TEXTURE2D => (d.Anonymous.Texture2D.MipSlice, 0),
+        D3D12_RTV_DIMENSION_TEXTURE2DARRAY => (d.Anonymous.Texture2DArray.MipSlice, d.Anonymous.Texture2DArray.FirstArraySlice),
+        _ => (u32::MAX, 0),
+    });
+    RTV_VIEWS.lock().unwrap().get_or_insert_with(HashMap::new).insert(handle, v);
+}
+
+/// translated graphics pipeline → blend state of each render target slot
+static BLENDS: Mutex<Option<HashMap<usize, Vec<String>>>> = Mutex::new(None);
+
+/// A translated graphics pipeline was made (`real::translated_graphics_pso_once`): its blend
+/// state, for the change lines.
+pub(super) fn note_pipeline(pso: usize, blend: &D3D12_BLEND_DESC) {
+    if !on() {
+        return;
+    }
+    let v = (0..8).map(|k| super::targets::blend_text(&blend.RenderTarget[if blend.IndependentBlendEnable.as_bool() { k } else { 0 }])).collect();
+    BLENDS.lock().unwrap().get_or_insert_with(HashMap::new).insert(pso, v);
+}
+
+/// A readback buffer.
+struct Rb(ID3D12Resource);
+// (the device's objects are free-threaded)
+unsafe impl Send for Rb {}
+
+/// Where a crop copy lands in the crop buffer, and what of the target it holds.
+#[derive(Clone, Copy)]
+struct Crop {
+    offset: u64,
+    origin: (u32, u32),
+    size: (u32, u32),
+    pitch: u32,
+}
+
+/// One point in one target of a draw: the slots of its texel before and after the draw.
+struct Entry {
+    point: u8,
+    rt: u8,
+    res: usize,
+    fmt: i32,
+    size: (u32, u32),
+    at: (u32, u32),
+    sub: u32,
+    before: u32,
+    after: u32,
+    crop: Option<Crop>,
+}
+
+/// A draw or dispatch recorded during a round, in its list's order (`index`).
+struct Event {
+    seq: u64,
+    frame: u64,
+    list: usize,
+    index: u32,
+    /// a dispatch (no copies), else a draw
+    dispatch: bool,
+    indirect: bool,
+    pso: usize,
+    shaders: (u64, u64),
+    entries: Vec<Entry>,
+}
+
+/// Targets and copies left out during a round, for its summary line.
+#[derive(Default)]
+struct Skipped {
+    shape: u64,
+    format: u64,
+    multisampled: u64,
+    other: u64,
+    slots_full: u64,
+    crops_full: u64,
+}
+
+/// A round's buffers and events, from its first draw to its readout.
+struct Session {
+    round: u32,
+    rb: Rb,
+    /// (buffer, bytes a crop, crops it holds)
+    crops: Option<(Rb, u64, u32)>,
+    next: u32,
+    next_crop: u32,
+    events: Vec<Event>,
+    index: HashMap<usize, u32>,
+    skipped: Skipped,
+}
+
+/// the round being recorded (0: none)
+static ROUND: AtomicU32 = AtomicU32::new(0);
+/// the frame being recorded (PresentX count)
+static FRAME: AtomicU64 = AtomicU64::new(0);
+static SEQ: AtomicU64 = AtomicU64::new(0);
+static SESSION: Mutex<Option<Session>> = Mutex::new(None);
+/// the pipelines whose draws take crops in round 2
+static CROP_PSOS: Mutex<Option<HashSet<usize>>> = Mutex::new(None);
+/// readback buffers of past rounds: kept, a list of theirs may still run
+static RETIRED: Mutex<Vec<Rb>> = Mutex::new(Vec::new());
+
+/// A readback buffer of `bytes`, in COPY_DEST; `fill`: every byte `SENTINEL`.
+unsafe fn readback(dev: &ID3D12Device, bytes: u64, fill: bool) -> Option<Rb> {
+    let mut rb: Option<ID3D12Resource> = None;
+    dev.CreateCommittedResource(
+        &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() },
+        D3D12_HEAP_FLAG_NONE,
+        &D3D12_RESOURCE_DESC {
+            Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
+            Width: bytes,
+            Height: 1,
+            DepthOrArraySize: 1,
+            MipLevels: 1,
+            SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
+            Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
+            ..Default::default()
+        },
+        D3D12_RESOURCE_STATE_COPY_DEST,
+        None,
+        &mut rb,
+    )
+    .ok()?;
+    let rb = rb?;
+    if fill {
+        let mut p: *mut c_void = std::ptr::null_mut();
+        rb.Map(0, None, Some(&mut p)).ok()?;
+        if p.is_null() {
+            return None;
+        }
+        std::ptr::write_bytes(p as *mut u8, SENTINEL, bytes as usize);
+        rb.Unmap(0, None);
+    }
+    Some(Rb(rb))
+}
+
+/// Round `round`'s session, its buffers made on `list`'s device.
+unsafe fn new_session(c: &Config, round: u32, list: &ID3D12GraphicsCommandList) -> Option<Session> {
+    let mut dev: Option<ID3D12Device> = None;
+    list.GetDevice(&mut dev).ok()?;
+    let dev = dev?;
+    let rb = readback(&dev, c.slots as u64 * SLOT, true)?;
+    let crops = match (round, c.crop) {
+        (2, Some((w, h, per_frame))) => {
+            let each = ((w as u64 * 8).next_multiple_of(256) * h as u64).next_multiple_of(SLOT);
+            let n = ((per_frame as u64 * 4).max(64) * c.frames * c.points.len() as u64).min(CROP_BYTES_MOST / each).max(1);
+            readback(&dev, n * each, false).map(|b| (b, each, n as u32))
+        }
+        _ => None,
+    };
+    crate::xlog_info!("D3D12.X: pixel history: round {round} records from frame {} ({} slots{})", FRAME.load(Ordering::Relaxed), c.slots,
+        crops.as_ref().map_or(String::new(), |(_, each, n)| format!(", {n} crops of {each} bytes")));
+    Some(Session { round, rb, crops, next: 0, next_crop: 0, events: Vec::new(), index: HashMap::new(), skipped: Skipped::default() })
+}
+
+/// A legacy transition of one subresource (the resource not AddRef'd).
+unsafe fn transition(res: &ID3D12Resource, sub: u32, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) -> D3D12_RESOURCE_BARRIER {
+    D3D12_RESOURCE_BARRIER {
+        Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
+        Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
+        Anonymous: D3D12_RESOURCE_BARRIER_0 {
+            Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { pResource: std::mem::transmute_copy(res), Subresource: sub, StateBefore: before, StateAfter: after }),
+        },
+    }
+}
+
+/// A target followed by a draw: the resource (AddRef'd) and where its point is.
+pub(super) struct Target {
+    res: ID3D12Resource,
+    point: u8,
+    rt: u8,
+    fmt: i32,
+    size: (u32, u32),
+    at: (u32, u32),
+    sub: u32,
+}
+
+/// Copies of `at` (1×1, or a `crop`) of each target into `rb`, at `offsets`, all inside one
+/// RENDER_TARGET → COPY_SOURCE → RENDER_TARGET pair of barriers.
+unsafe fn copy_texels(list: &ID3D12GraphicsCommandList, rb: &ID3D12Resource, targets: &[(&Target, u64, Option<Crop>)]) {
+    if targets.is_empty() {
+        return;
+    }
+    let to: Vec<_> = targets.iter().map(|(t, _, _)| transition(&t.res, t.sub, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE)).collect();

copy_texels issues one RENDER_TARGET->COPY_SOURCE (and back) transition per Target, and bound_targets makes one Target per point for the same (resource, subresource). So with two or more points, one ResourceBarrier batch transitions the same subresource twice, and the second StateBefore is already wrong. With XCL_PIXEL_HISTORY=1900,700 and XCL_PIXEL_HISTORY_ALSO=2000,500 (the two-point setup used in game), each followed target gets [RT->CS, RT->CS] then [CS->RT, CS->RT]. That's a debug-layer error, and on stricter drivers corrupted state or device removal, while trying to diagnose a rendering bug. The GPU test also passes the same t twice (texel plus crop). Deduplicating barriers by (res, sub) would fix it.

<!-- greyfinch-sync:ivall/xcl:review-comment:4767608785 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3509#discussion_r4767608785). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T09:44:51Z. **Code review location:** `crates/xcl/src/hle/d3d12x/pixel_history.rs`; line 410 ~~~~diff @@ -0,0 +1,914 @@ +//! `XCL_PIXEL_HISTORY=<x>,<y>[,<s>[,<frames>]]` (diagnostic): which draw writes a pixel. +//! +//! PIX and Nsight frame captures do not replay a title under XCL, so this answers "which draw +//! wrote this pixel" in the process. `x`, `y` are pixels of the presented picture +//! (`XCL_PIXEL_HISTORY_SPACE=<w>x<h>`, default 3840x2160). `frames` frames (default 1, 8 at +//! most) are followed, from the first present `s` seconds (default 0) or more after the first one. +//! `XCL_PIXEL_HISTORY_ALSO=<x>,<y>[;<x>,<y>]` adds up to 3 more points. +//! +//! In those frames every draw (direct and indirect) on a direct list copies, before and after +//! itself, the texel at each point of each bound render target into a readback buffer (1×1 +//! CopyTextureRegion between a RENDER_TARGET → COPY_SOURCE transition and its way back). A +//! target is followed when it has the present's shape (within 1 %, an eighth of its width at +//! least): the point is mapped by the target's own size (its RTV's mip). `GAP` presents later +//! the values are read back and one line is logged per draw that CHANGED a texel – frame, event, +//! console VS / PS, the target, the value before and after decoded, the pipeline's blend state +//! for that slot – and one line per change between two draws of a list (a dispatch, a clear or +//! a copy in between: the dispatches' CS are named). +//! +//! Formats followed: R8G8B8A8 and B8G8R8A8 (all three types), R16G16B16A16 (float or +//! typeless read as float), R11G11B10_FLOAT, R10G10B10A2, R32 (float or typeless read as float). +//! Other targets, multisampled ones, and depth buffers (a copy of a depth buffer must take its +//! whole subresource) are not followed and counted as such. UAV writes are seen only as a change +//! between two draws. +//! +//! `XCL_PIXEL_HISTORY_CROP=<w>,<h>[,<per frame>]`: a second round of as many frames follows the +//! first, in which the draws whose pipeline changed a point in the first round also copy a +//! `w`×`h` crop of the target around it after themselves; the crops of draws that changed the +//! point are written (`pixel-history/<frame>_<event>_<ps>_p<point>rt<slot>.bmp` in the logs +//! folder, decoded as the target dump does: NaN and infinities white), `per frame` of them at +//! most (default 200). +//! +//! The readback buffers (`XCL_PIXEL_HISTORY_SLOTS` slots of 512 bytes, default 131072: 64 MiB of +//! system memory a round, plus the crops' at most 256 MiB) are kept to the end of the process (a +//! list recorded in a round may run after its readout). +//! +//! Cost: unset, a draw's hooks load one atomic and return, and the hooks at pipeline and view +//! creation check one cached value; nothing is created. Set, outside the followed frames, the same +//! for draws, and each translated graphics pipeline and render target view is noted in a map. In +//! the followed frames, each draw on a direct list records two barriers and one 1×1 copy per +//! followed target and point before itself, and the same after (plus a crop copy in round 2). + +use std::collections::{HashMap, HashSet}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; +use std::sync::{Mutex, OnceLock}; +use std::time::Instant; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; + +/// a copy's place in a readback buffer (D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT) +const SLOT: u64 = 512; +/// what a slot holds before a copy reached it +const SENTINEL: u8 = 0xA5; +/// presents between a round's last frame and its readout +const GAP: u64 = 6; +/// frames a round follows, at most +const FRAMES_MOST: u64 = 8; +/// points followed, at most (`XCL_PIXEL_HISTORY` and `_ALSO`) +const POINTS_MOST: usize = 4; +/// crop buffer of a round, at most +const CROP_BYTES_MOST: u64 = 256 << 20; + +/// The switches, read once (`config`). +#[derive(Clone, Debug, PartialEq)] +pub(super) struct Config { + /// in the present's pixels + points: Vec<(u32, u32)>, + /// seconds after the first present the first round starts + after: f64, + /// frames a round follows + frames: u64, + /// the present's size the points are given in + space: (u32, u32), + /// (width, height, crops written a frame) + crop: Option<(u32, u32, usize)>, + /// readback slots of a round + slots: u32, +} + +/// `<a><sep><b>` as two numbers. +fn pair(s: &str, sep: char) -> Option<(u32, u32)> { + let (a, b) = s.split_once(sep)?; + Some((a.trim().parse().ok()?, b.trim().parse().ok()?)) +} + +/// The switches' values (`v`: `XCL_PIXEL_HISTORY`, then `_ALSO`, `_SPACE`, `_CROP`, `_SLOTS`). +fn parse(v: &str, also: Option<&str>, space: Option<&str>, crop: Option<&str>, slots: Option<&str>) -> Result<Config, String> { + let f: Vec<&str> = v.split(',').map(str::trim).collect(); + if f.len() < 2 || f.len() > 4 { + return Err("not <x>,<y>[,<s>[,<frames>]]".into()); + } + let mut points = vec![(f[0].parse().map_err(|_| format!("x {:?} is not a number", f[0]))?, f[1].parse().map_err(|_| format!("y {:?} is not a number", f[1]))?)]; + let after = match f.get(2) { + None | Some(&"") => 0.0, + Some(s) => s.parse::<f64>().ok().filter(|s| s.is_finite() && *s >= 0.0).ok_or_else(|| format!("{s:?} is not seconds"))?, + }; + let frames = match f.get(3) { + None => 1, + Some(s) => s.parse::<u64>().map_err(|_| format!("frames {s:?} is not a number"))?.clamp(1, FRAMES_MOST), + }; + for p in also.unwrap_or("").split(';').map(str::trim).filter(|p| !p.is_empty()) { + points.push(pair(p, ',').ok_or_else(|| format!("XCL_PIXEL_HISTORY_ALSO point {p:?} is not <x>,<y>"))?); + } + points.truncate(POINTS_MOST); + let space = match space { + Some(s) => pair(s, 'x').filter(|&(w, h)| w > 0 && h > 0).ok_or_else(|| format!("XCL_PIXEL_HISTORY_SPACE={s:?} is not <w>x<h>"))?, + None => (3840, 2160), + }; + if let Some(&(x, y)) = points.iter().find(|&&(x, y)| x >= space.0 || y >= space.1) { + return Err(format!("point ({x}, {y}) is outside the {}x{} present (XCL_PIXEL_HISTORY_SPACE)", space.0, space.1)); + } + let crop = match crop { + None => None, + Some(c) => { + let p: Vec<&str> = c.split(',').map(str::trim).collect(); + let n = |s: &str| s.parse::<u32>().ok().filter(|&n| (1..=256).contains(&n)); + match (p.len(), p.first().and_then(|s| n(s)), p.get(1).and_then(|s| n(s))) { + (2 | 3, Some(w), Some(h)) => Some((w, h, p.get(2).map_or(Some(200), |s| s.parse().ok()).ok_or_else(|| format!("XCL_PIXEL_HISTORY_CROP={c:?}: crops a frame not a number"))?)), + _ => return Err(format!("XCL_PIXEL_HISTORY_CROP={c:?} is not <w>,<h>[,<per frame>] (1..256)")), + } + } + }; + let slots = match slots { + Some(s) => s.parse::<u32>().ok().filter(|n| (1024..=1 << 20).contains(n)).ok_or_else(|| format!("XCL_PIXEL_HISTORY_SLOTS={s:?} is not 1024..1048576"))?, + None => 131072, + }; + Ok(Config { points, after, frames, space, crop, slots }) +} + +/// The switches, read and logged once; None when `XCL_PIXEL_HISTORY` is unset or not valid. +pub(super) fn config() -> Option<&'static Config> { + static C: OnceLock<Option<Config>> = OnceLock::new(); + C.get_or_init(|| { + let v = std::env::var("XCL_PIXEL_HISTORY").ok()?; + let e = |k: &str| std::env::var(k).ok(); + match parse(&v, e("XCL_PIXEL_HISTORY_ALSO").as_deref(), e("XCL_PIXEL_HISTORY_SPACE").as_deref(), e("XCL_PIXEL_HISTORY_CROP").as_deref(), e("XCL_PIXEL_HISTORY_SLOTS").as_deref()) { + Ok(c) => { + crate::xlog_info!( + "D3D12.X: XCL_PIXEL_HISTORY: points {:?} of a {}x{} present, {} frames from {:.1} s after the first present, {} readback slots{}", + c.points, c.space.0, c.space.1, c.frames, c.after, c.slots, c.crop.map_or(String::new(), |(w, h, n)| format!(", then {w}x{h} crops ({n} a frame at most)")) + ); + Some(c) + } + Err(e) => { + crate::xlog_warn!("D3D12.X: XCL_PIXEL_HISTORY={v:?}: {e}: no pixel history"); + None + } + } + }) + .as_ref() +} + +/// Whether `XCL_PIXEL_HISTORY` is set (and valid). +pub(super) fn on() -> bool { + config().is_some() +} + +/// Whether translated graphics pipelines keep their console VS / PS hashes (`real::pso_shaders`). +pub(super) fn keeps_shaders() -> bool { + on() || super::real::skip_ps_on() +} + +/// Bytes of a texel of a followed format; None: not followed. +fn texel_bytes(fmt: i32) -> Option<usize> { + match fmt { + 9 | 10 => Some(8), + 23 | 24 | 26 | 27 | 28 | 29 | 39 | 41 | 87 | 90 | 91 => Some(4), + _ => None, + } +} + +/// A texel of a followed format as its channels (R, G, B[, A]). +pub(super) fn decode(fmt: i32, t: &[u8]) -> Option<Vec<f32>> { + if t.len() < texel_bytes(fmt)? { + return None; + } + let w = u32::from_le_bytes([t[0], t[1], t[2], t[3]]); + let half = |i: usize| super::present::half_float(u16::from_le_bytes([t[i], t[i + 1]])); + let u8s = |i: usize| t[i] as f32 / 255.0; + Some(match fmt { + 9 | 10 => vec![half(0), half(2), half(4), half(6)], + 23 | 24 => vec![(w & 1023) as f32 / 1023.0, (w >> 10 & 1023) as f32 / 1023.0, (w >> 20 & 1023) as f32 / 1023.0, (w >> 30) as f32 / 3.0], + 26 => vec![super::present::small_float(w & 0x7FF, 6), super::present::small_float(w >> 11 & 0x7FF, 6), super::present::small_float(w >> 22, 5)], + 27..=29 => vec![u8s(0), u8s(1), u8s(2), u8s(3)], + 87 | 90 | 91 => vec![u8s(2), u8s(1), u8s(0), u8s(3)], + 39 | 41 => vec![f32::from_bits(w)], + _ => return None, + }) +} + +/// A texel for the log: its channels decoded, then its raw bytes (high byte first). +fn decoded_text(fmt: i32, t: &[u8]) -> String { + let raw: String = t.iter().rev().map(|b| format!("{b:02x}")).collect(); + match decode(fmt, t) { + Some(c) => format!("({}) [{raw}]", c.iter().map(|v| format!("{v:.4}")).collect::<Vec<_>>().join(", ")), + None => format!("[{raw}]"), + } +} + +/// Point `p` of a `space` present in a target of `size`: None when the target has not the +/// present's shape (within 1 %) or is narrower than an eighth of it. +pub(super) fn map_point(p: (u32, u32), space: (u32, u32), size: (u32, u32)) -> Option<(u32, u32)> { + let ((pw, ph), (tw, th)) = (space, size); + if pw == 0 || ph == 0 || tw == 0 || th == 0 || p.0 >= pw || p.1 >= ph { + return None; + } + let (a, b) = (tw as u64 * ph as u64, th as u64 * pw as u64); + if a.abs_diff(b) * 100 > b || tw as u64 * 8 < pw as u64 { + return None; + } + let m = |v: u32, from: u32, to: u32| (((v as u64 * 2 + 1) * to as u64 / (2 * from as u64)) as u32).min(to - 1); + Some((m(p.0, pw, tw), m(p.1, ph, th))) +} + +/// The top-left corner of a `c` crop of a `size` target around `at` (inside the target). +fn crop_origin(at: (u32, u32), c: (u32, u32), size: (u32, u32)) -> ((u32, u32), (u32, u32)) { + let (w, h) = (c.0.min(size.0), c.1.min(size.1)); + ((at.0.saturating_sub(w / 2).min(size.0 - w), at.1.saturating_sub(h / 2).min(size.1 - h)), (w, h)) +} + +/// RTV handle → (mip, first array slice) its view names +static RTV_VIEWS: Mutex<Option<HashMap<usize, (u32, u32)>>> = Mutex::new(None); + +/// A render target view was made (`real::dev_create_rtv`). +pub(super) unsafe fn note_rtv(handle: usize, desc: Option<&D3D12_RENDER_TARGET_VIEW_DESC>) { + if !on() { + return; + } + let v = desc.map_or((0, 0), |d| match d.ViewDimension { + D3D12_RTV_DIMENSION_TEXTURE2D => (d.Anonymous.Texture2D.MipSlice, 0), + D3D12_RTV_DIMENSION_TEXTURE2DARRAY => (d.Anonymous.Texture2DArray.MipSlice, d.Anonymous.Texture2DArray.FirstArraySlice), + _ => (u32::MAX, 0), + }); + RTV_VIEWS.lock().unwrap().get_or_insert_with(HashMap::new).insert(handle, v); +} + +/// translated graphics pipeline → blend state of each render target slot +static BLENDS: Mutex<Option<HashMap<usize, Vec<String>>>> = Mutex::new(None); + +/// A translated graphics pipeline was made (`real::translated_graphics_pso_once`): its blend +/// state, for the change lines. +pub(super) fn note_pipeline(pso: usize, blend: &D3D12_BLEND_DESC) { + if !on() { + return; + } + let v = (0..8).map(|k| super::targets::blend_text(&blend.RenderTarget[if blend.IndependentBlendEnable.as_bool() { k } else { 0 }])).collect(); + BLENDS.lock().unwrap().get_or_insert_with(HashMap::new).insert(pso, v); +} + +/// A readback buffer. +struct Rb(ID3D12Resource); +// (the device's objects are free-threaded) +unsafe impl Send for Rb {} + +/// Where a crop copy lands in the crop buffer, and what of the target it holds. +#[derive(Clone, Copy)] +struct Crop { + offset: u64, + origin: (u32, u32), + size: (u32, u32), + pitch: u32, +} + +/// One point in one target of a draw: the slots of its texel before and after the draw. +struct Entry { + point: u8, + rt: u8, + res: usize, + fmt: i32, + size: (u32, u32), + at: (u32, u32), + sub: u32, + before: u32, + after: u32, + crop: Option<Crop>, +} + +/// A draw or dispatch recorded during a round, in its list's order (`index`). +struct Event { + seq: u64, + frame: u64, + list: usize, + index: u32, + /// a dispatch (no copies), else a draw + dispatch: bool, + indirect: bool, + pso: usize, + shaders: (u64, u64), + entries: Vec<Entry>, +} + +/// Targets and copies left out during a round, for its summary line. +#[derive(Default)] +struct Skipped { + shape: u64, + format: u64, + multisampled: u64, + other: u64, + slots_full: u64, + crops_full: u64, +} + +/// A round's buffers and events, from its first draw to its readout. +struct Session { + round: u32, + rb: Rb, + /// (buffer, bytes a crop, crops it holds) + crops: Option<(Rb, u64, u32)>, + next: u32, + next_crop: u32, + events: Vec<Event>, + index: HashMap<usize, u32>, + skipped: Skipped, +} + +/// the round being recorded (0: none) +static ROUND: AtomicU32 = AtomicU32::new(0); +/// the frame being recorded (PresentX count) +static FRAME: AtomicU64 = AtomicU64::new(0); +static SEQ: AtomicU64 = AtomicU64::new(0); +static SESSION: Mutex<Option<Session>> = Mutex::new(None); +/// the pipelines whose draws take crops in round 2 +static CROP_PSOS: Mutex<Option<HashSet<usize>>> = Mutex::new(None); +/// readback buffers of past rounds: kept, a list of theirs may still run +static RETIRED: Mutex<Vec<Rb>> = Mutex::new(Vec::new()); + +/// A readback buffer of `bytes`, in COPY_DEST; `fill`: every byte `SENTINEL`. +unsafe fn readback(dev: &ID3D12Device, bytes: u64, fill: bool) -> Option<Rb> { + let mut rb: Option<ID3D12Resource> = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: bytes, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut rb, + ) + .ok()?; + let rb = rb?; + if fill { + let mut p: *mut c_void = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut p)).ok()?; + if p.is_null() { + return None; + } + std::ptr::write_bytes(p as *mut u8, SENTINEL, bytes as usize); + rb.Unmap(0, None); + } + Some(Rb(rb)) +} + +/// Round `round`'s session, its buffers made on `list`'s device. +unsafe fn new_session(c: &Config, round: u32, list: &ID3D12GraphicsCommandList) -> Option<Session> { + let mut dev: Option<ID3D12Device> = None; + list.GetDevice(&mut dev).ok()?; + let dev = dev?; + let rb = readback(&dev, c.slots as u64 * SLOT, true)?; + let crops = match (round, c.crop) { + (2, Some((w, h, per_frame))) => { + let each = ((w as u64 * 8).next_multiple_of(256) * h as u64).next_multiple_of(SLOT); + let n = ((per_frame as u64 * 4).max(64) * c.frames * c.points.len() as u64).min(CROP_BYTES_MOST / each).max(1); + readback(&dev, n * each, false).map(|b| (b, each, n as u32)) + } + _ => None, + }; + crate::xlog_info!("D3D12.X: pixel history: round {round} records from frame {} ({} slots{})", FRAME.load(Ordering::Relaxed), c.slots, + crops.as_ref().map_or(String::new(), |(_, each, n)| format!(", {n} crops of {each} bytes"))); + Some(Session { round, rb, crops, next: 0, next_crop: 0, events: Vec::new(), index: HashMap::new(), skipped: Skipped::default() }) +} + +/// A legacy transition of one subresource (the resource not AddRef'd). +unsafe fn transition(res: &ID3D12Resource, sub: u32, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) -> D3D12_RESOURCE_BARRIER { + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { pResource: std::mem::transmute_copy(res), Subresource: sub, StateBefore: before, StateAfter: after }), + }, + } +} + +/// A target followed by a draw: the resource (AddRef'd) and where its point is. +pub(super) struct Target { + res: ID3D12Resource, + point: u8, + rt: u8, + fmt: i32, + size: (u32, u32), + at: (u32, u32), + sub: u32, +} + +/// Copies of `at` (1×1, or a `crop`) of each target into `rb`, at `offsets`, all inside one +/// RENDER_TARGET → COPY_SOURCE → RENDER_TARGET pair of barriers. +unsafe fn copy_texels(list: &ID3D12GraphicsCommandList, rb: &ID3D12Resource, targets: &[(&Target, u64, Option<Crop>)]) { + if targets.is_empty() { + return; + } + let to: Vec<_> = targets.iter().map(|(t, _, _)| transition(&t.res, t.sub, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE)).collect(); ~~~~ --- `copy_texels` issues one RENDER_TARGET->COPY_SOURCE (and back) transition per Target, and `bound_targets` makes one Target per point for the same (resource, subresource). So with two or more points, one ResourceBarrier batch transitions the same subresource twice, and the second StateBefore is already wrong. With XCL_PIXEL_HISTORY=1900,700 and XCL_PIXEL_HISTORY_ALSO=2000,500 (the two-point setup used in game), each followed target gets [RT->CS, RT->CS] then [CS->RT, CS->RT]. That's a debug-layer error, and on stricter drivers corrupted state or device removal, while trying to diagnose a rendering bug. The GPU test also passes the same `t` twice (texel plus crop). Deduplicating barriers by (res, sub) would fix it.
bmjask commented 2026-12-02 09:44:51 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T09:44:51Z.

Code review location: crates/xcl/src/hle/d3d12x/pixel_history.rs; line 641

@@ -0,0 +1,914 @@
+//! `XCL_PIXEL_HISTORY=<x>,<y>[,<s>[,<frames>]]` (diagnostic): which draw writes a pixel.
+//!
+//! PIX and Nsight frame captures do not replay a title under XCL, so this answers "which draw
+//! wrote this pixel" in the process. `x`, `y` are pixels of the presented picture
+//! (`XCL_PIXEL_HISTORY_SPACE=<w>x<h>`, default 3840x2160). `frames` frames (default 1, 8 at
+//! most) are followed, from the first present `s` seconds (default 0) or more after the first one.
+//! `XCL_PIXEL_HISTORY_ALSO=<x>,<y>[;<x>,<y>]` adds up to 3 more points.
+//!
+//! In those frames every draw (direct and indirect) on a direct list copies, before and after
+//! itself, the texel at each point of each bound render target into a readback buffer (1×1
+//! CopyTextureRegion between a RENDER_TARGET → COPY_SOURCE transition and its way back). A
+//! target is followed when it has the present's shape (within 1 %, an eighth of its width at
+//! least): the point is mapped by the target's own size (its RTV's mip). `GAP` presents later
+//! the values are read back and one line is logged per draw that CHANGED a texel – frame, event,
+//! console VS / PS, the target, the value before and after decoded, the pipeline's blend state
+//! for that slot – and one line per change between two draws of a list (a dispatch, a clear or
+//! a copy in between: the dispatches' CS are named).
+//!
+//! Formats followed: R8G8B8A8 and B8G8R8A8 (all three types), R16G16B16A16 (float or
+//! typeless read as float), R11G11B10_FLOAT, R10G10B10A2, R32 (float or typeless read as float).
+//! Other targets, multisampled ones, and depth buffers (a copy of a depth buffer must take its
+//! whole subresource) are not followed and counted as such. UAV writes are seen only as a change
+//! between two draws.
+//!
+//! `XCL_PIXEL_HISTORY_CROP=<w>,<h>[,<per frame>]`: a second round of as many frames follows the
+//! first, in which the draws whose pipeline changed a point in the first round also copy a
+//! `w`×`h` crop of the target around it after themselves; the crops of draws that changed the
+//! point are written (`pixel-history/<frame>_<event>_<ps>_p<point>rt<slot>.bmp` in the logs
+//! folder, decoded as the target dump does: NaN and infinities white), `per frame` of them at
+//! most (default 200).
+//!
+//! The readback buffers (`XCL_PIXEL_HISTORY_SLOTS` slots of 512 bytes, default 131072: 64 MiB of
+//! system memory a round, plus the crops' at most 256 MiB) are kept to the end of the process (a
+//! list recorded in a round may run after its readout).
+//!
+//! Cost: unset, a draw's hooks load one atomic and return, and the hooks at pipeline and view
+//! creation check one cached value; nothing is created. Set, outside the followed frames, the same
+//! for draws, and each translated graphics pipeline and render target view is noted in a map. In
+//! the followed frames, each draw on a direct list records two barriers and one 1×1 copy per
+//! followed target and point before itself, and the same after (plus a crop copy in round 2).
+
+use std::collections::{HashMap, HashSet};
+use std::ffi::c_void;
+use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
+use std::sync::{Mutex, OnceLock};
+use std::time::Instant;
+
+use windows::core::Interface;
+use windows::Win32::Graphics::Direct3D12::*;
+use windows::Win32::Graphics::Dxgi::Common::*;
+
+/// a copy's place in a readback buffer (D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT)
+const SLOT: u64 = 512;
+/// what a slot holds before a copy reached it
+const SENTINEL: u8 = 0xA5;
+/// presents between a round's last frame and its readout
+const GAP: u64 = 6;
+/// frames a round follows, at most
+const FRAMES_MOST: u64 = 8;
+/// points followed, at most (`XCL_PIXEL_HISTORY` and `_ALSO`)
+const POINTS_MOST: usize = 4;
+/// crop buffer of a round, at most
+const CROP_BYTES_MOST: u64 = 256 << 20;
+
+/// The switches, read once (`config`).
+#[derive(Clone, Debug, PartialEq)]
+pub(super) struct Config {
+    /// in the present's pixels
+    points: Vec<(u32, u32)>,
+    /// seconds after the first present the first round starts
+    after: f64,
+    /// frames a round follows
+    frames: u64,
+    /// the present's size the points are given in
+    space: (u32, u32),
+    /// (width, height, crops written a frame)
+    crop: Option<(u32, u32, usize)>,
+    /// readback slots of a round
+    slots: u32,
+}
+
+/// `<a><sep><b>` as two numbers.
+fn pair(s: &str, sep: char) -> Option<(u32, u32)> {
+    let (a, b) = s.split_once(sep)?;
+    Some((a.trim().parse().ok()?, b.trim().parse().ok()?))
+}
+
+/// The switches' values (`v`: `XCL_PIXEL_HISTORY`, then `_ALSO`, `_SPACE`, `_CROP`, `_SLOTS`).
+fn parse(v: &str, also: Option<&str>, space: Option<&str>, crop: Option<&str>, slots: Option<&str>) -> Result<Config, String> {
+    let f: Vec<&str> = v.split(',').map(str::trim).collect();
+    if f.len() < 2 || f.len() > 4 {
+        return Err("not <x>,<y>[,<s>[,<frames>]]".into());
+    }
+    let mut points = vec![(f[0].parse().map_err(|_| format!("x {:?} is not a number", f[0]))?, f[1].parse().map_err(|_| format!("y {:?} is not a number", f[1]))?)];
+    let after = match f.get(2) {
+        None | Some(&"") => 0.0,
+        Some(s) => s.parse::<f64>().ok().filter(|s| s.is_finite() && *s >= 0.0).ok_or_else(|| format!("{s:?} is not seconds"))?,
+    };
+    let frames = match f.get(3) {
+        None => 1,
+        Some(s) => s.parse::<u64>().map_err(|_| format!("frames {s:?} is not a number"))?.clamp(1, FRAMES_MOST),
+    };
+    for p in also.unwrap_or("").split(';').map(str::trim).filter(|p| !p.is_empty()) {
+        points.push(pair(p, ',').ok_or_else(|| format!("XCL_PIXEL_HISTORY_ALSO point {p:?} is not <x>,<y>"))?);
+    }
+    points.truncate(POINTS_MOST);
+    let space = match space {
+        Some(s) => pair(s, 'x').filter(|&(w, h)| w > 0 && h > 0).ok_or_else(|| format!("XCL_PIXEL_HISTORY_SPACE={s:?} is not <w>x<h>"))?,
+        None => (3840, 2160),
+    };
+    if let Some(&(x, y)) = points.iter().find(|&&(x, y)| x >= space.0 || y >= space.1) {
+        return Err(format!("point ({x}, {y}) is outside the {}x{} present (XCL_PIXEL_HISTORY_SPACE)", space.0, space.1));
+    }
+    let crop = match crop {
+        None => None,
+        Some(c) => {
+            let p: Vec<&str> = c.split(',').map(str::trim).collect();
+            let n = |s: &str| s.parse::<u32>().ok().filter(|&n| (1..=256).contains(&n));
+            match (p.len(), p.first().and_then(|s| n(s)), p.get(1).and_then(|s| n(s))) {
+                (2 | 3, Some(w), Some(h)) => Some((w, h, p.get(2).map_or(Some(200), |s| s.parse().ok()).ok_or_else(|| format!("XCL_PIXEL_HISTORY_CROP={c:?}: crops a frame not a number"))?)),
+                _ => return Err(format!("XCL_PIXEL_HISTORY_CROP={c:?} is not <w>,<h>[,<per frame>] (1..256)")),
+            }
+        }
+    };
+    let slots = match slots {
+        Some(s) => s.parse::<u32>().ok().filter(|n| (1024..=1 << 20).contains(n)).ok_or_else(|| format!("XCL_PIXEL_HISTORY_SLOTS={s:?} is not 1024..1048576"))?,
+        None => 131072,
+    };
+    Ok(Config { points, after, frames, space, crop, slots })
+}
+
+/// The switches, read and logged once; None when `XCL_PIXEL_HISTORY` is unset or not valid.
+pub(super) fn config() -> Option<&'static Config> {
+    static C: OnceLock<Option<Config>> = OnceLock::new();
+    C.get_or_init(|| {
+        let v = std::env::var("XCL_PIXEL_HISTORY").ok()?;
+        let e = |k: &str| std::env::var(k).ok();
+        match parse(&v, e("XCL_PIXEL_HISTORY_ALSO").as_deref(), e("XCL_PIXEL_HISTORY_SPACE").as_deref(), e("XCL_PIXEL_HISTORY_CROP").as_deref(), e("XCL_PIXEL_HISTORY_SLOTS").as_deref()) {
+            Ok(c) => {
+                crate::xlog_info!(
+                    "D3D12.X: XCL_PIXEL_HISTORY: points {:?} of a {}x{} present, {} frames from {:.1} s after the first present, {} readback slots{}",
+                    c.points, c.space.0, c.space.1, c.frames, c.after, c.slots, c.crop.map_or(String::new(), |(w, h, n)| format!(", then {w}x{h} crops ({n} a frame at most)"))
+                );
+                Some(c)
+            }
+            Err(e) => {
+                crate::xlog_warn!("D3D12.X: XCL_PIXEL_HISTORY={v:?}: {e}: no pixel history");
+                None
+            }
+        }
+    })
+    .as_ref()
+}
+
+/// Whether `XCL_PIXEL_HISTORY` is set (and valid).
+pub(super) fn on() -> bool {
+    config().is_some()
+}
+
+/// Whether translated graphics pipelines keep their console VS / PS hashes (`real::pso_shaders`).
+pub(super) fn keeps_shaders() -> bool {
+    on() || super::real::skip_ps_on()
+}
+
+/// Bytes of a texel of a followed format; None: not followed.
+fn texel_bytes(fmt: i32) -> Option<usize> {
+    match fmt {
+        9 | 10 => Some(8),
+        23 | 24 | 26 | 27 | 28 | 29 | 39 | 41 | 87 | 90 | 91 => Some(4),
+        _ => None,
+    }
+}
+
+/// A texel of a followed format as its channels (R, G, B[, A]).
+pub(super) fn decode(fmt: i32, t: &[u8]) -> Option<Vec<f32>> {
+    if t.len() < texel_bytes(fmt)? {
+        return None;
+    }
+    let w = u32::from_le_bytes([t[0], t[1], t[2], t[3]]);
+    let half = |i: usize| super::present::half_float(u16::from_le_bytes([t[i], t[i + 1]]));
+    let u8s = |i: usize| t[i] as f32 / 255.0;
+    Some(match fmt {
+        9 | 10 => vec![half(0), half(2), half(4), half(6)],
+        23 | 24 => vec![(w & 1023) as f32 / 1023.0, (w >> 10 & 1023) as f32 / 1023.0, (w >> 20 & 1023) as f32 / 1023.0, (w >> 30) as f32 / 3.0],
+        26 => vec![super::present::small_float(w & 0x7FF, 6), super::present::small_float(w >> 11 & 0x7FF, 6), super::present::small_float(w >> 22, 5)],
+        27..=29 => vec![u8s(0), u8s(1), u8s(2), u8s(3)],
+        87 | 90 | 91 => vec![u8s(2), u8s(1), u8s(0), u8s(3)],
+        39 | 41 => vec![f32::from_bits(w)],
+        _ => return None,
+    })
+}
+
+/// A texel for the log: its channels decoded, then its raw bytes (high byte first).
+fn decoded_text(fmt: i32, t: &[u8]) -> String {
+    let raw: String = t.iter().rev().map(|b| format!("{b:02x}")).collect();
+    match decode(fmt, t) {
+        Some(c) => format!("({}) [{raw}]", c.iter().map(|v| format!("{v:.4}")).collect::<Vec<_>>().join(", ")),
+        None => format!("[{raw}]"),
+    }
+}
+
+/// Point `p` of a `space` present in a target of `size`: None when the target has not the
+/// present's shape (within 1 %) or is narrower than an eighth of it.
+pub(super) fn map_point(p: (u32, u32), space: (u32, u32), size: (u32, u32)) -> Option<(u32, u32)> {
+    let ((pw, ph), (tw, th)) = (space, size);
+    if pw == 0 || ph == 0 || tw == 0 || th == 0 || p.0 >= pw || p.1 >= ph {
+        return None;
+    }
+    let (a, b) = (tw as u64 * ph as u64, th as u64 * pw as u64);
+    if a.abs_diff(b) * 100 > b || tw as u64 * 8 < pw as u64 {
+        return None;
+    }
+    let m = |v: u32, from: u32, to: u32| (((v as u64 * 2 + 1) * to as u64 / (2 * from as u64)) as u32).min(to - 1);
+    Some((m(p.0, pw, tw), m(p.1, ph, th)))
+}
+
+/// The top-left corner of a `c` crop of a `size` target around `at` (inside the target).
+fn crop_origin(at: (u32, u32), c: (u32, u32), size: (u32, u32)) -> ((u32, u32), (u32, u32)) {
+    let (w, h) = (c.0.min(size.0), c.1.min(size.1));
+    ((at.0.saturating_sub(w / 2).min(size.0 - w), at.1.saturating_sub(h / 2).min(size.1 - h)), (w, h))
+}
+
+/// RTV handle → (mip, first array slice) its view names
+static RTV_VIEWS: Mutex<Option<HashMap<usize, (u32, u32)>>> = Mutex::new(None);
+
+/// A render target view was made (`real::dev_create_rtv`).
+pub(super) unsafe fn note_rtv(handle: usize, desc: Option<&D3D12_RENDER_TARGET_VIEW_DESC>) {
+    if !on() {
+        return;
+    }
+    let v = desc.map_or((0, 0), |d| match d.ViewDimension {
+        D3D12_RTV_DIMENSION_TEXTURE2D => (d.Anonymous.Texture2D.MipSlice, 0),
+        D3D12_RTV_DIMENSION_TEXTURE2DARRAY => (d.Anonymous.Texture2DArray.MipSlice, d.Anonymous.Texture2DArray.FirstArraySlice),
+        _ => (u32::MAX, 0),
+    });
+    RTV_VIEWS.lock().unwrap().get_or_insert_with(HashMap::new).insert(handle, v);
+}
+
+/// translated graphics pipeline → blend state of each render target slot
+static BLENDS: Mutex<Option<HashMap<usize, Vec<String>>>> = Mutex::new(None);
+
+/// A translated graphics pipeline was made (`real::translated_graphics_pso_once`): its blend
+/// state, for the change lines.
+pub(super) fn note_pipeline(pso: usize, blend: &D3D12_BLEND_DESC) {
+    if !on() {
+        return;
+    }
+    let v = (0..8).map(|k| super::targets::blend_text(&blend.RenderTarget[if blend.IndependentBlendEnable.as_bool() { k } else { 0 }])).collect();
+    BLENDS.lock().unwrap().get_or_insert_with(HashMap::new).insert(pso, v);
+}
+
+/// A readback buffer.
+struct Rb(ID3D12Resource);
+// (the device's objects are free-threaded)
+unsafe impl Send for Rb {}
+
+/// Where a crop copy lands in the crop buffer, and what of the target it holds.
+#[derive(Clone, Copy)]
+struct Crop {
+    offset: u64,
+    origin: (u32, u32),
+    size: (u32, u32),
+    pitch: u32,
+}
+
+/// One point in one target of a draw: the slots of its texel before and after the draw.
+struct Entry {
+    point: u8,
+    rt: u8,
+    res: usize,
+    fmt: i32,
+    size: (u32, u32),
+    at: (u32, u32),
+    sub: u32,
+    before: u32,
+    after: u32,
+    crop: Option<Crop>,
+}
+
+/// A draw or dispatch recorded during a round, in its list's order (`index`).
+struct Event {
+    seq: u64,
+    frame: u64,
+    list: usize,
+    index: u32,
+    /// a dispatch (no copies), else a draw
+    dispatch: bool,
+    indirect: bool,
+    pso: usize,
+    shaders: (u64, u64),
+    entries: Vec<Entry>,
+}
+
+/// Targets and copies left out during a round, for its summary line.
+#[derive(Default)]
+struct Skipped {
+    shape: u64,
+    format: u64,
+    multisampled: u64,
+    other: u64,
+    slots_full: u64,
+    crops_full: u64,
+}
+
+/// A round's buffers and events, from its first draw to its readout.
+struct Session {
+    round: u32,
+    rb: Rb,
+    /// (buffer, bytes a crop, crops it holds)
+    crops: Option<(Rb, u64, u32)>,
+    next: u32,
+    next_crop: u32,
+    events: Vec<Event>,
+    index: HashMap<usize, u32>,
+    skipped: Skipped,
+}
+
+/// the round being recorded (0: none)
+static ROUND: AtomicU32 = AtomicU32::new(0);
+/// the frame being recorded (PresentX count)
+static FRAME: AtomicU64 = AtomicU64::new(0);
+static SEQ: AtomicU64 = AtomicU64::new(0);
+static SESSION: Mutex<Option<Session>> = Mutex::new(None);
+/// the pipelines whose draws take crops in round 2
+static CROP_PSOS: Mutex<Option<HashSet<usize>>> = Mutex::new(None);
+/// readback buffers of past rounds: kept, a list of theirs may still run
+static RETIRED: Mutex<Vec<Rb>> = Mutex::new(Vec::new());
+
+/// A readback buffer of `bytes`, in COPY_DEST; `fill`: every byte `SENTINEL`.
+unsafe fn readback(dev: &ID3D12Device, bytes: u64, fill: bool) -> Option<Rb> {
+    let mut rb: Option<ID3D12Resource> = None;
+    dev.CreateCommittedResource(
+        &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() },
+        D3D12_HEAP_FLAG_NONE,
+        &D3D12_RESOURCE_DESC {
+            Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
+            Width: bytes,
+            Height: 1,
+            DepthOrArraySize: 1,
+            MipLevels: 1,
+            SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
+            Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
+            ..Default::default()
+        },
+        D3D12_RESOURCE_STATE_COPY_DEST,
+        None,
+        &mut rb,
+    )
+    .ok()?;
+    let rb = rb?;
+    if fill {
+        let mut p: *mut c_void = std::ptr::null_mut();
+        rb.Map(0, None, Some(&mut p)).ok()?;
+        if p.is_null() {
+            return None;
+        }
+        std::ptr::write_bytes(p as *mut u8, SENTINEL, bytes as usize);
+        rb.Unmap(0, None);
+    }
+    Some(Rb(rb))
+}
+
+/// Round `round`'s session, its buffers made on `list`'s device.
+unsafe fn new_session(c: &Config, round: u32, list: &ID3D12GraphicsCommandList) -> Option<Session> {
+    let mut dev: Option<ID3D12Device> = None;
+    list.GetDevice(&mut dev).ok()?;
+    let dev = dev?;
+    let rb = readback(&dev, c.slots as u64 * SLOT, true)?;
+    let crops = match (round, c.crop) {
+        (2, Some((w, h, per_frame))) => {
+            let each = ((w as u64 * 8).next_multiple_of(256) * h as u64).next_multiple_of(SLOT);
+            let n = ((per_frame as u64 * 4).max(64) * c.frames * c.points.len() as u64).min(CROP_BYTES_MOST / each).max(1);
+            readback(&dev, n * each, false).map(|b| (b, each, n as u32))
+        }
+        _ => None,
+    };
+    crate::xlog_info!("D3D12.X: pixel history: round {round} records from frame {} ({} slots{})", FRAME.load(Ordering::Relaxed), c.slots,
+        crops.as_ref().map_or(String::new(), |(_, each, n)| format!(", {n} crops of {each} bytes")));
+    Some(Session { round, rb, crops, next: 0, next_crop: 0, events: Vec::new(), index: HashMap::new(), skipped: Skipped::default() })
+}
+
+/// A legacy transition of one subresource (the resource not AddRef'd).
+unsafe fn transition(res: &ID3D12Resource, sub: u32, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) -> D3D12_RESOURCE_BARRIER {
+    D3D12_RESOURCE_BARRIER {
+        Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
+        Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
+        Anonymous: D3D12_RESOURCE_BARRIER_0 {
+            Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { pResource: std::mem::transmute_copy(res), Subresource: sub, StateBefore: before, StateAfter: after }),
+        },
+    }
+}
+
+/// A target followed by a draw: the resource (AddRef'd) and where its point is.
+pub(super) struct Target {
+    res: ID3D12Resource,
+    point: u8,
+    rt: u8,
+    fmt: i32,
+    size: (u32, u32),
+    at: (u32, u32),
+    sub: u32,
+}
+
+/// Copies of `at` (1×1, or a `crop`) of each target into `rb`, at `offsets`, all inside one
+/// RENDER_TARGET → COPY_SOURCE → RENDER_TARGET pair of barriers.
+unsafe fn copy_texels(list: &ID3D12GraphicsCommandList, rb: &ID3D12Resource, targets: &[(&Target, u64, Option<Crop>)]) {
+    if targets.is_empty() {
+        return;
+    }
+    let to: Vec<_> = targets.iter().map(|(t, _, _)| transition(&t.res, t.sub, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE)).collect();
+    list.ResourceBarrier(&to);
+    for (t, offset, crop) in targets {
+        let ((x, y), (w, h), pitch) = match crop {
+            Some(c) => (c.origin, c.size, c.pitch),
+            None => (t.at, (1, 1), 256),
+        };
+        let dst = D3D12_TEXTURE_COPY_LOCATION {
+            pResource: std::mem::transmute_copy(rb),
+            Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
+            Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
+                PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT {
+                    Offset: *offset,
+                    Footprint: D3D12_SUBRESOURCE_FOOTPRINT { Format: DXGI_FORMAT(t.fmt), Width: w, Height: h, Depth: 1, RowPitch: pitch },
+                },
+            },
+        };
+        let src = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&t.res), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: t.sub } };
+        let b = D3D12_BOX { left: x, top: y, front: 0, right: x + w, bottom: y + h, back: 1 };
+        list.CopyTextureRegion(&dst, 0, 0, 0, &src, Some(&b));
+    }
+    let back: Vec<_> = targets.iter().map(|(t, _, _)| transition(&t.res, t.sub, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET)).collect();
+    list.ResourceBarrier(&back);
+}
+
+/// The targets bound on `this` that `c`'s points fall in, and counts of those left out.
+unsafe fn bound_targets(this: *mut c_void, c: &Config, skipped: &mut Skipped) -> Vec<Target> {
+    let mut out = Vec::new();
+    let views = RTV_VIEWS.lock().unwrap().as_ref().map(|m| super::list_x::bound_render_targets(this).into_iter().map(|h| (h, m.get(&h).copied().unwrap_or((0, 0)))).collect::<Vec<_>>()).unwrap_or_default();
+    for (k, (h, (mip, slice))) in views.into_iter().enumerate() {
+        let Some(r) = super::present::rtv_resource(h) else { continue };
+        let Some(res) = ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).cloned() else { continue };
+        let d = res.GetDesc();
+        if d.SampleDesc.Count > 1 {
+            skipped.multisampled += 1;
+            continue;
+        }
+        if d.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || mip == u32::MAX || mip >= d.MipLevels as u32 || slice >= d.DepthOrArraySize as u32 {
+            skipped.other += 1;
+            continue;
+        }
+        if texel_bytes(d.Format.0).is_none() {
+            skipped.format += 1;
+            continue;
+        }
+        let size = (((d.Width >> mip) as u32).max(1), (d.Height >> mip).max(1));
+        for (p, &pt) in c.points.iter().enumerate() {
+            match map_point(pt, c.space, size) {
+                Some(at) => out.push(Target { res: res.clone(), point: p as u8, rt: k as u8, fmt: d.Format.0, size, at, sub: mip + slice * d.MipLevels as u32 }),
+                None => skipped.shape += 1,
+            }
+        }
+    }
+    out
+}
+
+/// What `before` copied, for `after`.
+pub(super) struct Pending {
+    round: u32,
+    pso: usize,
+    indirect: bool,
+    targets: Vec<(Target, u32)>,
+}
+
+/// The next event's place in `list` (1, 2, …).
+fn next_index(s: &mut Session, list: usize) -> u32 {
+    let i = s.index.entry(list).or_default();
+    *i += 1;
+    *i
+}
+
+/// Before a draw on `this` with pipeline `pso` (the title's or the one it resolves to): the
+/// texels of its targets, while a round records. None (nothing done) otherwise.
+pub(super) unsafe fn before(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usize, indirect: bool) -> Option<Pending> {
+    let round = ROUND.load(Ordering::Relaxed);
+    if round == 0 {
+        return None;
+    }
+    let c = config()?;
+    if list.GetType() != D3D12_COMMAND_LIST_TYPE_DIRECT {
+        return None;
+    }
+    let mut g = SESSION.lock().unwrap();
+    if g.as_ref().is_none_or(|s| s.round != round) {
+        if let Some(old) = g.take() {
+            RETIRED.lock().unwrap().push(old.rb);
+        }
+        *g = Some(new_session(c, round, list).or_else(|| {
+            crate::xlog_warn!("D3D12.X: pixel history: no readback buffer – off");
+            ROUND.store(0, Ordering::Relaxed);
+            None
+        })?);
+    }
+    let s = g.as_mut()?;
+    let targets = bound_targets(this, c, &mut s.skipped);
+    if targets.is_empty() {
+        return Some(Pending { round, pso, indirect, targets: Vec::new() });
+    }
+    if s.next as usize + 2 * targets.len() > c.slots as usize {
+        s.skipped.slots_full += targets.len() as u64;
+        return Some(Pending { round, pso, indirect, targets: Vec::new() });
+    }
+    let first = s.next;
+    s.next += targets.len() as u32;
+    let copies: Vec<_> = targets.iter().enumerate().map(|(k, t)| (t, (first + k as u32) as u64 * SLOT, None)).collect();
+    copy_texels(list, &s.rb.0, &copies);
+    drop(copies);
+    Some(Pending { round, pso, indirect, targets: targets.into_iter().enumerate().map(|(k, t)| (t, first + k as u32)).collect() })
+}
+
+/// After the draw `before` saw: its targets' texels again (and crops in round 2), noted as an event.
+pub(super) unsafe fn after(this: *mut c_void, list: &ID3D12GraphicsCommandList, p: Option<Pending>) {
+    let Some(p) = p else { return };
+    let Some(c) = config() else { return };
+    let mut g = SESSION.lock().unwrap();
+    let Some(s) = g.as_mut().filter(|s| s.round == p.round) else { return };
+    let key = super::pso_async::resolve(p.pso);
+    let shaders = super::real::pso_shaders(key).or_else(|| super::real::pso_shaders(p.pso)).unwrap_or((0, 0));
+    let crop_this = s.crops.is_some() && CROP_PSOS.lock().unwrap().as_ref().is_some_and(|m| m.contains(&key));
+    let mut entries = Vec::new();
+    if !p.targets.is_empty() && s.next as usize + p.targets.len() <= c.slots as usize {
+        let first = s.next;
+        s.next += p.targets.len() as u32;
+        let mut copies = Vec::new();
+        let mut crops = Vec::new();
+        for (k, (t, b)) in p.targets.iter().enumerate() {
+            let after = first + k as u32;
+            copies.push((t, after as u64 * SLOT, None));
+            let mut crop = None;
+            if let (true, Some((w, h, _)), Some((_, each, n))) = (crop_this, c.crop, s.crops.as_ref()) {
+                if s.next_crop < *n {
+                    let (origin, size) = crop_origin(t.at, (w, h), t.size);
+                    let pitch = (size.0 as u64 * texel_bytes(t.fmt).unwrap_or(8) as u64).next_multiple_of(256) as u32;
+                    crop = Some(Crop { offset: s.next_crop as u64 * each, origin, size, pitch });
+                    s.next_crop += 1;
+                    crops.push((t, crop.unwrap().offset, crop));
+                } else {
+                    s.skipped.crops_full += 1;
+                }
+            }
+            entries.push(Entry { point: t.point, rt: t.rt, res: t.res.as_raw() as usize, fmt: t.fmt, size: t.size, at: t.at, sub: t.sub, before: *b, after, crop });
+        }
+        copy_texels(list, &s.rb.0, &copies);
+        if let Some((crb, _, _)) = s.crops.as_ref() {
+            copy_texels(list, &crb.0, &crops);
+        }
+    } else if !p.targets.is_empty() {
+        s.skipped.slots_full += p.targets.len() as u64;
+    }
+    let index = next_index(s, this as usize);
+    s.events.push(Event { seq: SEQ.fetch_add(1, Ordering::Relaxed), frame: FRAME.load(Ordering::Relaxed), list: this as usize, index, dispatch: false, indirect: p.indirect, pso: key, shaders, entries });
+}
+
+/// A dispatch on `this` with pipeline `pso`: an event of the list (no copies).
+pub(super) fn note_dispatch(this: *mut c_void, pso: usize) {
+    let round = ROUND.load(Ordering::Relaxed);
+    if round == 0 {
+        return;
+    }
+    let mut g = SESSION.lock().unwrap();
+    let Some(s) = g.as_mut().filter(|s| s.round == round) else { return };
+    let shaders = super::real::pso_shaders(pso).unwrap_or((0, 0));
+    let index = next_index(s, this as usize);
+    s.events.push(Event { seq: SEQ.fetch_add(1, Ordering::Relaxed), frame: FRAME.load(Ordering::Relaxed), list: this as usize, index, dispatch: true, indirect: false, pso, shaders, entries: Vec::new() });
+}
+
+/// Where the history is, moved on at each present.
+#[derive(Debug, PartialEq)]
+enum Phase {
+    /// before the first round
+    Wait,
+    /// a round records draws until that present
+    Record { round: u32, until: u64 },
+    /// a round's lists run; read out at that present
+    Drain { round: u32, at: u64 },
+    Done,
+}
+
+/// The presents' clock: the first present and where the history is.
+struct Clock {
+    t0: Instant,
+    phase: Phase,
+}
+
+static CLOCK: Mutex<Option<Clock>> = Mutex::new(None);
+
+/// The title presented (`present::present_x_frame`; `frames` presents so far).
+pub(super) fn frame_end(frames: u64) {
+    let Some(c) = config() else { return };
+    FRAME.store(frames, Ordering::Relaxed);
+    let mut g = CLOCK.lock().unwrap();
+    let k = g.get_or_insert_with(|| Clock { t0: Instant::now(), phase: Phase::Wait });
+    let since = k.t0.elapsed().as_secs_f64();
+    match k.phase {
+        Phase::Wait => {
+            if since >= c.after {
+                crate::xlog_info!("D3D12.X: pixel history: frames {frames}..{} at {since:.1} s after the first present, points {:?} of a {}x{} present", frames + c.frames - 1, c.points, c.space.0, c.space.1);
+                k.phase = Phase::Record { round: 1, until: frames + c.frames };
+                ROUND.store(1, Ordering::Relaxed);
+            }
+        }
+        Phase::Record { round, until } if frames >= until => {
+            ROUND.store(0, Ordering::Relaxed);
+            k.phase = Phase::Drain { round, at: frames + GAP };
+        }
+        Phase::Drain { round, at } if frames >= at => {
+            let session = SESSION.lock().unwrap().take();
+            let changed = session.map(|s| unsafe { read_out(c, s) }).unwrap_or_default();
+            if round == 1 && c.crop.is_some() && !changed.is_empty() {
+                *CROP_PSOS.lock().unwrap() = Some(changed);
+                k.phase = Phase::Record { round: 2, until: frames + c.frames };
+                ROUND.store(2, Ordering::Relaxed);
+            } else {
+                k.phase = Phase::Done;
+            }
+        }
+        _ => {}
+    }
+}
+
+/// Whether no copy reached these bytes (their list had not run at the readout).
+fn is_sentinel(b: &[u8]) -> bool {
+    b.iter().all(|&x| x == SENTINEL)
+}
+
+/// Logs a round's changes, `GAP` presents after its last frame (copies whose list had not run
+/// yet are counted, not read); returns the pipelines that changed a point.
+unsafe fn read_out(c: &Config, mut s: Session) -> HashSet<usize> {
+    let mut changed_psos = HashSet::new();
+    let mut p: *mut c_void = std::ptr::null_mut();
+    if s.rb.0.Map(0, None, Some(&mut p)).is_err() || p.is_null() {
+        crate::xlog_warn!("D3D12.X: pixel history: round {} not read (Map failed)", s.round);

When Map fails in read_out, only s.rb goes to RETIRED and the round-2 crop buffer (s.crops) is dropped. The session-replacement path in before() (~495) also retires only old.rb. That breaks the rule that buffers are kept because a list recorded in the round may still run. With XCL_PIXEL_HISTORY_CROP set, if Map fails or a stale session is replaced, the crop ID3D12Resource is released while recorded or re-executed lists still CopyTextureRegion into it, so the GPU writes into a freed resource (device removal or memory corruption).

<!-- greyfinch-sync:ivall/xcl:review-comment:4767608797 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3509#discussion_r4767608797). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T09:44:51Z. **Code review location:** `crates/xcl/src/hle/d3d12x/pixel_history.rs`; line 641 ~~~~diff @@ -0,0 +1,914 @@ +//! `XCL_PIXEL_HISTORY=<x>,<y>[,<s>[,<frames>]]` (diagnostic): which draw writes a pixel. +//! +//! PIX and Nsight frame captures do not replay a title under XCL, so this answers "which draw +//! wrote this pixel" in the process. `x`, `y` are pixels of the presented picture +//! (`XCL_PIXEL_HISTORY_SPACE=<w>x<h>`, default 3840x2160). `frames` frames (default 1, 8 at +//! most) are followed, from the first present `s` seconds (default 0) or more after the first one. +//! `XCL_PIXEL_HISTORY_ALSO=<x>,<y>[;<x>,<y>]` adds up to 3 more points. +//! +//! In those frames every draw (direct and indirect) on a direct list copies, before and after +//! itself, the texel at each point of each bound render target into a readback buffer (1×1 +//! CopyTextureRegion between a RENDER_TARGET → COPY_SOURCE transition and its way back). A +//! target is followed when it has the present's shape (within 1 %, an eighth of its width at +//! least): the point is mapped by the target's own size (its RTV's mip). `GAP` presents later +//! the values are read back and one line is logged per draw that CHANGED a texel – frame, event, +//! console VS / PS, the target, the value before and after decoded, the pipeline's blend state +//! for that slot – and one line per change between two draws of a list (a dispatch, a clear or +//! a copy in between: the dispatches' CS are named). +//! +//! Formats followed: R8G8B8A8 and B8G8R8A8 (all three types), R16G16B16A16 (float or +//! typeless read as float), R11G11B10_FLOAT, R10G10B10A2, R32 (float or typeless read as float). +//! Other targets, multisampled ones, and depth buffers (a copy of a depth buffer must take its +//! whole subresource) are not followed and counted as such. UAV writes are seen only as a change +//! between two draws. +//! +//! `XCL_PIXEL_HISTORY_CROP=<w>,<h>[,<per frame>]`: a second round of as many frames follows the +//! first, in which the draws whose pipeline changed a point in the first round also copy a +//! `w`×`h` crop of the target around it after themselves; the crops of draws that changed the +//! point are written (`pixel-history/<frame>_<event>_<ps>_p<point>rt<slot>.bmp` in the logs +//! folder, decoded as the target dump does: NaN and infinities white), `per frame` of them at +//! most (default 200). +//! +//! The readback buffers (`XCL_PIXEL_HISTORY_SLOTS` slots of 512 bytes, default 131072: 64 MiB of +//! system memory a round, plus the crops' at most 256 MiB) are kept to the end of the process (a +//! list recorded in a round may run after its readout). +//! +//! Cost: unset, a draw's hooks load one atomic and return, and the hooks at pipeline and view +//! creation check one cached value; nothing is created. Set, outside the followed frames, the same +//! for draws, and each translated graphics pipeline and render target view is noted in a map. In +//! the followed frames, each draw on a direct list records two barriers and one 1×1 copy per +//! followed target and point before itself, and the same after (plus a crop copy in round 2). + +use std::collections::{HashMap, HashSet}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; +use std::sync::{Mutex, OnceLock}; +use std::time::Instant; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; + +/// a copy's place in a readback buffer (D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT) +const SLOT: u64 = 512; +/// what a slot holds before a copy reached it +const SENTINEL: u8 = 0xA5; +/// presents between a round's last frame and its readout +const GAP: u64 = 6; +/// frames a round follows, at most +const FRAMES_MOST: u64 = 8; +/// points followed, at most (`XCL_PIXEL_HISTORY` and `_ALSO`) +const POINTS_MOST: usize = 4; +/// crop buffer of a round, at most +const CROP_BYTES_MOST: u64 = 256 << 20; + +/// The switches, read once (`config`). +#[derive(Clone, Debug, PartialEq)] +pub(super) struct Config { + /// in the present's pixels + points: Vec<(u32, u32)>, + /// seconds after the first present the first round starts + after: f64, + /// frames a round follows + frames: u64, + /// the present's size the points are given in + space: (u32, u32), + /// (width, height, crops written a frame) + crop: Option<(u32, u32, usize)>, + /// readback slots of a round + slots: u32, +} + +/// `<a><sep><b>` as two numbers. +fn pair(s: &str, sep: char) -> Option<(u32, u32)> { + let (a, b) = s.split_once(sep)?; + Some((a.trim().parse().ok()?, b.trim().parse().ok()?)) +} + +/// The switches' values (`v`: `XCL_PIXEL_HISTORY`, then `_ALSO`, `_SPACE`, `_CROP`, `_SLOTS`). +fn parse(v: &str, also: Option<&str>, space: Option<&str>, crop: Option<&str>, slots: Option<&str>) -> Result<Config, String> { + let f: Vec<&str> = v.split(',').map(str::trim).collect(); + if f.len() < 2 || f.len() > 4 { + return Err("not <x>,<y>[,<s>[,<frames>]]".into()); + } + let mut points = vec![(f[0].parse().map_err(|_| format!("x {:?} is not a number", f[0]))?, f[1].parse().map_err(|_| format!("y {:?} is not a number", f[1]))?)]; + let after = match f.get(2) { + None | Some(&"") => 0.0, + Some(s) => s.parse::<f64>().ok().filter(|s| s.is_finite() && *s >= 0.0).ok_or_else(|| format!("{s:?} is not seconds"))?, + }; + let frames = match f.get(3) { + None => 1, + Some(s) => s.parse::<u64>().map_err(|_| format!("frames {s:?} is not a number"))?.clamp(1, FRAMES_MOST), + }; + for p in also.unwrap_or("").split(';').map(str::trim).filter(|p| !p.is_empty()) { + points.push(pair(p, ',').ok_or_else(|| format!("XCL_PIXEL_HISTORY_ALSO point {p:?} is not <x>,<y>"))?); + } + points.truncate(POINTS_MOST); + let space = match space { + Some(s) => pair(s, 'x').filter(|&(w, h)| w > 0 && h > 0).ok_or_else(|| format!("XCL_PIXEL_HISTORY_SPACE={s:?} is not <w>x<h>"))?, + None => (3840, 2160), + }; + if let Some(&(x, y)) = points.iter().find(|&&(x, y)| x >= space.0 || y >= space.1) { + return Err(format!("point ({x}, {y}) is outside the {}x{} present (XCL_PIXEL_HISTORY_SPACE)", space.0, space.1)); + } + let crop = match crop { + None => None, + Some(c) => { + let p: Vec<&str> = c.split(',').map(str::trim).collect(); + let n = |s: &str| s.parse::<u32>().ok().filter(|&n| (1..=256).contains(&n)); + match (p.len(), p.first().and_then(|s| n(s)), p.get(1).and_then(|s| n(s))) { + (2 | 3, Some(w), Some(h)) => Some((w, h, p.get(2).map_or(Some(200), |s| s.parse().ok()).ok_or_else(|| format!("XCL_PIXEL_HISTORY_CROP={c:?}: crops a frame not a number"))?)), + _ => return Err(format!("XCL_PIXEL_HISTORY_CROP={c:?} is not <w>,<h>[,<per frame>] (1..256)")), + } + } + }; + let slots = match slots { + Some(s) => s.parse::<u32>().ok().filter(|n| (1024..=1 << 20).contains(n)).ok_or_else(|| format!("XCL_PIXEL_HISTORY_SLOTS={s:?} is not 1024..1048576"))?, + None => 131072, + }; + Ok(Config { points, after, frames, space, crop, slots }) +} + +/// The switches, read and logged once; None when `XCL_PIXEL_HISTORY` is unset or not valid. +pub(super) fn config() -> Option<&'static Config> { + static C: OnceLock<Option<Config>> = OnceLock::new(); + C.get_or_init(|| { + let v = std::env::var("XCL_PIXEL_HISTORY").ok()?; + let e = |k: &str| std::env::var(k).ok(); + match parse(&v, e("XCL_PIXEL_HISTORY_ALSO").as_deref(), e("XCL_PIXEL_HISTORY_SPACE").as_deref(), e("XCL_PIXEL_HISTORY_CROP").as_deref(), e("XCL_PIXEL_HISTORY_SLOTS").as_deref()) { + Ok(c) => { + crate::xlog_info!( + "D3D12.X: XCL_PIXEL_HISTORY: points {:?} of a {}x{} present, {} frames from {:.1} s after the first present, {} readback slots{}", + c.points, c.space.0, c.space.1, c.frames, c.after, c.slots, c.crop.map_or(String::new(), |(w, h, n)| format!(", then {w}x{h} crops ({n} a frame at most)")) + ); + Some(c) + } + Err(e) => { + crate::xlog_warn!("D3D12.X: XCL_PIXEL_HISTORY={v:?}: {e}: no pixel history"); + None + } + } + }) + .as_ref() +} + +/// Whether `XCL_PIXEL_HISTORY` is set (and valid). +pub(super) fn on() -> bool { + config().is_some() +} + +/// Whether translated graphics pipelines keep their console VS / PS hashes (`real::pso_shaders`). +pub(super) fn keeps_shaders() -> bool { + on() || super::real::skip_ps_on() +} + +/// Bytes of a texel of a followed format; None: not followed. +fn texel_bytes(fmt: i32) -> Option<usize> { + match fmt { + 9 | 10 => Some(8), + 23 | 24 | 26 | 27 | 28 | 29 | 39 | 41 | 87 | 90 | 91 => Some(4), + _ => None, + } +} + +/// A texel of a followed format as its channels (R, G, B[, A]). +pub(super) fn decode(fmt: i32, t: &[u8]) -> Option<Vec<f32>> { + if t.len() < texel_bytes(fmt)? { + return None; + } + let w = u32::from_le_bytes([t[0], t[1], t[2], t[3]]); + let half = |i: usize| super::present::half_float(u16::from_le_bytes([t[i], t[i + 1]])); + let u8s = |i: usize| t[i] as f32 / 255.0; + Some(match fmt { + 9 | 10 => vec![half(0), half(2), half(4), half(6)], + 23 | 24 => vec![(w & 1023) as f32 / 1023.0, (w >> 10 & 1023) as f32 / 1023.0, (w >> 20 & 1023) as f32 / 1023.0, (w >> 30) as f32 / 3.0], + 26 => vec![super::present::small_float(w & 0x7FF, 6), super::present::small_float(w >> 11 & 0x7FF, 6), super::present::small_float(w >> 22, 5)], + 27..=29 => vec![u8s(0), u8s(1), u8s(2), u8s(3)], + 87 | 90 | 91 => vec![u8s(2), u8s(1), u8s(0), u8s(3)], + 39 | 41 => vec![f32::from_bits(w)], + _ => return None, + }) +} + +/// A texel for the log: its channels decoded, then its raw bytes (high byte first). +fn decoded_text(fmt: i32, t: &[u8]) -> String { + let raw: String = t.iter().rev().map(|b| format!("{b:02x}")).collect(); + match decode(fmt, t) { + Some(c) => format!("({}) [{raw}]", c.iter().map(|v| format!("{v:.4}")).collect::<Vec<_>>().join(", ")), + None => format!("[{raw}]"), + } +} + +/// Point `p` of a `space` present in a target of `size`: None when the target has not the +/// present's shape (within 1 %) or is narrower than an eighth of it. +pub(super) fn map_point(p: (u32, u32), space: (u32, u32), size: (u32, u32)) -> Option<(u32, u32)> { + let ((pw, ph), (tw, th)) = (space, size); + if pw == 0 || ph == 0 || tw == 0 || th == 0 || p.0 >= pw || p.1 >= ph { + return None; + } + let (a, b) = (tw as u64 * ph as u64, th as u64 * pw as u64); + if a.abs_diff(b) * 100 > b || tw as u64 * 8 < pw as u64 { + return None; + } + let m = |v: u32, from: u32, to: u32| (((v as u64 * 2 + 1) * to as u64 / (2 * from as u64)) as u32).min(to - 1); + Some((m(p.0, pw, tw), m(p.1, ph, th))) +} + +/// The top-left corner of a `c` crop of a `size` target around `at` (inside the target). +fn crop_origin(at: (u32, u32), c: (u32, u32), size: (u32, u32)) -> ((u32, u32), (u32, u32)) { + let (w, h) = (c.0.min(size.0), c.1.min(size.1)); + ((at.0.saturating_sub(w / 2).min(size.0 - w), at.1.saturating_sub(h / 2).min(size.1 - h)), (w, h)) +} + +/// RTV handle → (mip, first array slice) its view names +static RTV_VIEWS: Mutex<Option<HashMap<usize, (u32, u32)>>> = Mutex::new(None); + +/// A render target view was made (`real::dev_create_rtv`). +pub(super) unsafe fn note_rtv(handle: usize, desc: Option<&D3D12_RENDER_TARGET_VIEW_DESC>) { + if !on() { + return; + } + let v = desc.map_or((0, 0), |d| match d.ViewDimension { + D3D12_RTV_DIMENSION_TEXTURE2D => (d.Anonymous.Texture2D.MipSlice, 0), + D3D12_RTV_DIMENSION_TEXTURE2DARRAY => (d.Anonymous.Texture2DArray.MipSlice, d.Anonymous.Texture2DArray.FirstArraySlice), + _ => (u32::MAX, 0), + }); + RTV_VIEWS.lock().unwrap().get_or_insert_with(HashMap::new).insert(handle, v); +} + +/// translated graphics pipeline → blend state of each render target slot +static BLENDS: Mutex<Option<HashMap<usize, Vec<String>>>> = Mutex::new(None); + +/// A translated graphics pipeline was made (`real::translated_graphics_pso_once`): its blend +/// state, for the change lines. +pub(super) fn note_pipeline(pso: usize, blend: &D3D12_BLEND_DESC) { + if !on() { + return; + } + let v = (0..8).map(|k| super::targets::blend_text(&blend.RenderTarget[if blend.IndependentBlendEnable.as_bool() { k } else { 0 }])).collect(); + BLENDS.lock().unwrap().get_or_insert_with(HashMap::new).insert(pso, v); +} + +/// A readback buffer. +struct Rb(ID3D12Resource); +// (the device's objects are free-threaded) +unsafe impl Send for Rb {} + +/// Where a crop copy lands in the crop buffer, and what of the target it holds. +#[derive(Clone, Copy)] +struct Crop { + offset: u64, + origin: (u32, u32), + size: (u32, u32), + pitch: u32, +} + +/// One point in one target of a draw: the slots of its texel before and after the draw. +struct Entry { + point: u8, + rt: u8, + res: usize, + fmt: i32, + size: (u32, u32), + at: (u32, u32), + sub: u32, + before: u32, + after: u32, + crop: Option<Crop>, +} + +/// A draw or dispatch recorded during a round, in its list's order (`index`). +struct Event { + seq: u64, + frame: u64, + list: usize, + index: u32, + /// a dispatch (no copies), else a draw + dispatch: bool, + indirect: bool, + pso: usize, + shaders: (u64, u64), + entries: Vec<Entry>, +} + +/// Targets and copies left out during a round, for its summary line. +#[derive(Default)] +struct Skipped { + shape: u64, + format: u64, + multisampled: u64, + other: u64, + slots_full: u64, + crops_full: u64, +} + +/// A round's buffers and events, from its first draw to its readout. +struct Session { + round: u32, + rb: Rb, + /// (buffer, bytes a crop, crops it holds) + crops: Option<(Rb, u64, u32)>, + next: u32, + next_crop: u32, + events: Vec<Event>, + index: HashMap<usize, u32>, + skipped: Skipped, +} + +/// the round being recorded (0: none) +static ROUND: AtomicU32 = AtomicU32::new(0); +/// the frame being recorded (PresentX count) +static FRAME: AtomicU64 = AtomicU64::new(0); +static SEQ: AtomicU64 = AtomicU64::new(0); +static SESSION: Mutex<Option<Session>> = Mutex::new(None); +/// the pipelines whose draws take crops in round 2 +static CROP_PSOS: Mutex<Option<HashSet<usize>>> = Mutex::new(None); +/// readback buffers of past rounds: kept, a list of theirs may still run +static RETIRED: Mutex<Vec<Rb>> = Mutex::new(Vec::new()); + +/// A readback buffer of `bytes`, in COPY_DEST; `fill`: every byte `SENTINEL`. +unsafe fn readback(dev: &ID3D12Device, bytes: u64, fill: bool) -> Option<Rb> { + let mut rb: Option<ID3D12Resource> = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: bytes, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut rb, + ) + .ok()?; + let rb = rb?; + if fill { + let mut p: *mut c_void = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut p)).ok()?; + if p.is_null() { + return None; + } + std::ptr::write_bytes(p as *mut u8, SENTINEL, bytes as usize); + rb.Unmap(0, None); + } + Some(Rb(rb)) +} + +/// Round `round`'s session, its buffers made on `list`'s device. +unsafe fn new_session(c: &Config, round: u32, list: &ID3D12GraphicsCommandList) -> Option<Session> { + let mut dev: Option<ID3D12Device> = None; + list.GetDevice(&mut dev).ok()?; + let dev = dev?; + let rb = readback(&dev, c.slots as u64 * SLOT, true)?; + let crops = match (round, c.crop) { + (2, Some((w, h, per_frame))) => { + let each = ((w as u64 * 8).next_multiple_of(256) * h as u64).next_multiple_of(SLOT); + let n = ((per_frame as u64 * 4).max(64) * c.frames * c.points.len() as u64).min(CROP_BYTES_MOST / each).max(1); + readback(&dev, n * each, false).map(|b| (b, each, n as u32)) + } + _ => None, + }; + crate::xlog_info!("D3D12.X: pixel history: round {round} records from frame {} ({} slots{})", FRAME.load(Ordering::Relaxed), c.slots, + crops.as_ref().map_or(String::new(), |(_, each, n)| format!(", {n} crops of {each} bytes"))); + Some(Session { round, rb, crops, next: 0, next_crop: 0, events: Vec::new(), index: HashMap::new(), skipped: Skipped::default() }) +} + +/// A legacy transition of one subresource (the resource not AddRef'd). +unsafe fn transition(res: &ID3D12Resource, sub: u32, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) -> D3D12_RESOURCE_BARRIER { + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { pResource: std::mem::transmute_copy(res), Subresource: sub, StateBefore: before, StateAfter: after }), + }, + } +} + +/// A target followed by a draw: the resource (AddRef'd) and where its point is. +pub(super) struct Target { + res: ID3D12Resource, + point: u8, + rt: u8, + fmt: i32, + size: (u32, u32), + at: (u32, u32), + sub: u32, +} + +/// Copies of `at` (1×1, or a `crop`) of each target into `rb`, at `offsets`, all inside one +/// RENDER_TARGET → COPY_SOURCE → RENDER_TARGET pair of barriers. +unsafe fn copy_texels(list: &ID3D12GraphicsCommandList, rb: &ID3D12Resource, targets: &[(&Target, u64, Option<Crop>)]) { + if targets.is_empty() { + return; + } + let to: Vec<_> = targets.iter().map(|(t, _, _)| transition(&t.res, t.sub, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE)).collect(); + list.ResourceBarrier(&to); + for (t, offset, crop) in targets { + let ((x, y), (w, h), pitch) = match crop { + Some(c) => (c.origin, c.size, c.pitch), + None => (t.at, (1, 1), 256), + }; + let dst = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(rb), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: *offset, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { Format: DXGI_FORMAT(t.fmt), Width: w, Height: h, Depth: 1, RowPitch: pitch }, + }, + }, + }; + let src = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&t.res), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: t.sub } }; + let b = D3D12_BOX { left: x, top: y, front: 0, right: x + w, bottom: y + h, back: 1 }; + list.CopyTextureRegion(&dst, 0, 0, 0, &src, Some(&b)); + } + let back: Vec<_> = targets.iter().map(|(t, _, _)| transition(&t.res, t.sub, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET)).collect(); + list.ResourceBarrier(&back); +} + +/// The targets bound on `this` that `c`'s points fall in, and counts of those left out. +unsafe fn bound_targets(this: *mut c_void, c: &Config, skipped: &mut Skipped) -> Vec<Target> { + let mut out = Vec::new(); + let views = RTV_VIEWS.lock().unwrap().as_ref().map(|m| super::list_x::bound_render_targets(this).into_iter().map(|h| (h, m.get(&h).copied().unwrap_or((0, 0)))).collect::<Vec<_>>()).unwrap_or_default(); + for (k, (h, (mip, slice))) in views.into_iter().enumerate() { + let Some(r) = super::present::rtv_resource(h) else { continue }; + let Some(res) = ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).cloned() else { continue }; + let d = res.GetDesc(); + if d.SampleDesc.Count > 1 { + skipped.multisampled += 1; + continue; + } + if d.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || mip == u32::MAX || mip >= d.MipLevels as u32 || slice >= d.DepthOrArraySize as u32 { + skipped.other += 1; + continue; + } + if texel_bytes(d.Format.0).is_none() { + skipped.format += 1; + continue; + } + let size = (((d.Width >> mip) as u32).max(1), (d.Height >> mip).max(1)); + for (p, &pt) in c.points.iter().enumerate() { + match map_point(pt, c.space, size) { + Some(at) => out.push(Target { res: res.clone(), point: p as u8, rt: k as u8, fmt: d.Format.0, size, at, sub: mip + slice * d.MipLevels as u32 }), + None => skipped.shape += 1, + } + } + } + out +} + +/// What `before` copied, for `after`. +pub(super) struct Pending { + round: u32, + pso: usize, + indirect: bool, + targets: Vec<(Target, u32)>, +} + +/// The next event's place in `list` (1, 2, …). +fn next_index(s: &mut Session, list: usize) -> u32 { + let i = s.index.entry(list).or_default(); + *i += 1; + *i +} + +/// Before a draw on `this` with pipeline `pso` (the title's or the one it resolves to): the +/// texels of its targets, while a round records. None (nothing done) otherwise. +pub(super) unsafe fn before(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usize, indirect: bool) -> Option<Pending> { + let round = ROUND.load(Ordering::Relaxed); + if round == 0 { + return None; + } + let c = config()?; + if list.GetType() != D3D12_COMMAND_LIST_TYPE_DIRECT { + return None; + } + let mut g = SESSION.lock().unwrap(); + if g.as_ref().is_none_or(|s| s.round != round) { + if let Some(old) = g.take() { + RETIRED.lock().unwrap().push(old.rb); + } + *g = Some(new_session(c, round, list).or_else(|| { + crate::xlog_warn!("D3D12.X: pixel history: no readback buffer – off"); + ROUND.store(0, Ordering::Relaxed); + None + })?); + } + let s = g.as_mut()?; + let targets = bound_targets(this, c, &mut s.skipped); + if targets.is_empty() { + return Some(Pending { round, pso, indirect, targets: Vec::new() }); + } + if s.next as usize + 2 * targets.len() > c.slots as usize { + s.skipped.slots_full += targets.len() as u64; + return Some(Pending { round, pso, indirect, targets: Vec::new() }); + } + let first = s.next; + s.next += targets.len() as u32; + let copies: Vec<_> = targets.iter().enumerate().map(|(k, t)| (t, (first + k as u32) as u64 * SLOT, None)).collect(); + copy_texels(list, &s.rb.0, &copies); + drop(copies); + Some(Pending { round, pso, indirect, targets: targets.into_iter().enumerate().map(|(k, t)| (t, first + k as u32)).collect() }) +} + +/// After the draw `before` saw: its targets' texels again (and crops in round 2), noted as an event. +pub(super) unsafe fn after(this: *mut c_void, list: &ID3D12GraphicsCommandList, p: Option<Pending>) { + let Some(p) = p else { return }; + let Some(c) = config() else { return }; + let mut g = SESSION.lock().unwrap(); + let Some(s) = g.as_mut().filter(|s| s.round == p.round) else { return }; + let key = super::pso_async::resolve(p.pso); + let shaders = super::real::pso_shaders(key).or_else(|| super::real::pso_shaders(p.pso)).unwrap_or((0, 0)); + let crop_this = s.crops.is_some() && CROP_PSOS.lock().unwrap().as_ref().is_some_and(|m| m.contains(&key)); + let mut entries = Vec::new(); + if !p.targets.is_empty() && s.next as usize + p.targets.len() <= c.slots as usize { + let first = s.next; + s.next += p.targets.len() as u32; + let mut copies = Vec::new(); + let mut crops = Vec::new(); + for (k, (t, b)) in p.targets.iter().enumerate() { + let after = first + k as u32; + copies.push((t, after as u64 * SLOT, None)); + let mut crop = None; + if let (true, Some((w, h, _)), Some((_, each, n))) = (crop_this, c.crop, s.crops.as_ref()) { + if s.next_crop < *n { + let (origin, size) = crop_origin(t.at, (w, h), t.size); + let pitch = (size.0 as u64 * texel_bytes(t.fmt).unwrap_or(8) as u64).next_multiple_of(256) as u32; + crop = Some(Crop { offset: s.next_crop as u64 * each, origin, size, pitch }); + s.next_crop += 1; + crops.push((t, crop.unwrap().offset, crop)); + } else { + s.skipped.crops_full += 1; + } + } + entries.push(Entry { point: t.point, rt: t.rt, res: t.res.as_raw() as usize, fmt: t.fmt, size: t.size, at: t.at, sub: t.sub, before: *b, after, crop }); + } + copy_texels(list, &s.rb.0, &copies); + if let Some((crb, _, _)) = s.crops.as_ref() { + copy_texels(list, &crb.0, &crops); + } + } else if !p.targets.is_empty() { + s.skipped.slots_full += p.targets.len() as u64; + } + let index = next_index(s, this as usize); + s.events.push(Event { seq: SEQ.fetch_add(1, Ordering::Relaxed), frame: FRAME.load(Ordering::Relaxed), list: this as usize, index, dispatch: false, indirect: p.indirect, pso: key, shaders, entries }); +} + +/// A dispatch on `this` with pipeline `pso`: an event of the list (no copies). +pub(super) fn note_dispatch(this: *mut c_void, pso: usize) { + let round = ROUND.load(Ordering::Relaxed); + if round == 0 { + return; + } + let mut g = SESSION.lock().unwrap(); + let Some(s) = g.as_mut().filter(|s| s.round == round) else { return }; + let shaders = super::real::pso_shaders(pso).unwrap_or((0, 0)); + let index = next_index(s, this as usize); + s.events.push(Event { seq: SEQ.fetch_add(1, Ordering::Relaxed), frame: FRAME.load(Ordering::Relaxed), list: this as usize, index, dispatch: true, indirect: false, pso, shaders, entries: Vec::new() }); +} + +/// Where the history is, moved on at each present. +#[derive(Debug, PartialEq)] +enum Phase { + /// before the first round + Wait, + /// a round records draws until that present + Record { round: u32, until: u64 }, + /// a round's lists run; read out at that present + Drain { round: u32, at: u64 }, + Done, +} + +/// The presents' clock: the first present and where the history is. +struct Clock { + t0: Instant, + phase: Phase, +} + +static CLOCK: Mutex<Option<Clock>> = Mutex::new(None); + +/// The title presented (`present::present_x_frame`; `frames` presents so far). +pub(super) fn frame_end(frames: u64) { + let Some(c) = config() else { return }; + FRAME.store(frames, Ordering::Relaxed); + let mut g = CLOCK.lock().unwrap(); + let k = g.get_or_insert_with(|| Clock { t0: Instant::now(), phase: Phase::Wait }); + let since = k.t0.elapsed().as_secs_f64(); + match k.phase { + Phase::Wait => { + if since >= c.after { + crate::xlog_info!("D3D12.X: pixel history: frames {frames}..{} at {since:.1} s after the first present, points {:?} of a {}x{} present", frames + c.frames - 1, c.points, c.space.0, c.space.1); + k.phase = Phase::Record { round: 1, until: frames + c.frames }; + ROUND.store(1, Ordering::Relaxed); + } + } + Phase::Record { round, until } if frames >= until => { + ROUND.store(0, Ordering::Relaxed); + k.phase = Phase::Drain { round, at: frames + GAP }; + } + Phase::Drain { round, at } if frames >= at => { + let session = SESSION.lock().unwrap().take(); + let changed = session.map(|s| unsafe { read_out(c, s) }).unwrap_or_default(); + if round == 1 && c.crop.is_some() && !changed.is_empty() { + *CROP_PSOS.lock().unwrap() = Some(changed); + k.phase = Phase::Record { round: 2, until: frames + c.frames }; + ROUND.store(2, Ordering::Relaxed); + } else { + k.phase = Phase::Done; + } + } + _ => {} + } +} + +/// Whether no copy reached these bytes (their list had not run at the readout). +fn is_sentinel(b: &[u8]) -> bool { + b.iter().all(|&x| x == SENTINEL) +} + +/// Logs a round's changes, `GAP` presents after its last frame (copies whose list had not run +/// yet are counted, not read); returns the pipelines that changed a point. +unsafe fn read_out(c: &Config, mut s: Session) -> HashSet<usize> { + let mut changed_psos = HashSet::new(); + let mut p: *mut c_void = std::ptr::null_mut(); + if s.rb.0.Map(0, None, Some(&mut p)).is_err() || p.is_null() { + crate::xlog_warn!("D3D12.X: pixel history: round {} not read (Map failed)", s.round); ~~~~ --- When Map fails in `read_out`, only `s.rb` goes to RETIRED and the round-2 crop buffer (`s.crops`) is dropped. The session-replacement path in `before()` (~495) also retires only `old.rb`. That breaks the rule that buffers are kept because a list recorded in the round may still run. With XCL_PIXEL_HISTORY_CROP set, if Map fails or a stale session is replaced, the crop ID3D12Resource is released while recorded or re-executed lists still CopyTextureRegion into it, so the GPU writes into a freed resource (device removal or memory corruption).
bmjask commented 2026-12-02 09:44:51 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T09:44:51Z.

Code review location: crates/xcl/src/hle/d3d12x/bind.rs; line 4268

@@ -4253,6 +4264,12 @@ unsafe fn graphics_bound(this: *mut c_void) -> Option<(ID3D12GraphicsCommandList
     if super::present::trace_frame() {
         trace_ui_draw(this, pso, real, false);
     }
+    // `XCL_SKIP_PS`: left out as a skipped draw
+    if super::real::skip_named_ps(real) {

The new XCL_SKIP_PS early return in graphics_bound skips the draw without calling list_x::note_dropped_draw(this), unlike the other skip paths in the same function (pipeline unresolved, bind_abi_resolved Err). If the named PS's draws sit inside an occlusion query (common for world geometry), the query resolves as 0 samples, the title occlusion-culls objects, and new artifacts appear. That defeats the switch's purpose of confirming a skipped draw is the culprit.

<!-- greyfinch-sync:ivall/xcl:review-comment:4767608815 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3509#discussion_r4767608815). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T09:44:51Z. **Code review location:** `crates/xcl/src/hle/d3d12x/bind.rs`; line 4268 ~~~~diff @@ -4253,6 +4264,12 @@ unsafe fn graphics_bound(this: *mut c_void) -> Option<(ID3D12GraphicsCommandList if super::present::trace_frame() { trace_ui_draw(this, pso, real, false); } + // `XCL_SKIP_PS`: left out as a skipped draw + if super::real::skip_named_ps(real) { ~~~~ --- The new XCL_SKIP_PS early return in `graphics_bound` skips the draw without calling `list_x::note_dropped_draw(this)`, unlike the other skip paths in the same function (pipeline unresolved, bind_abi_resolved Err). If the named PS's draws sit inside an occlusion query (common for world geometry), the query resolves as 0 samples, the title occlusion-culls objects, and new artifacts appear. That defeats the switch's purpose of confirming a skipped draw is the culprit.
bmjask commented 2026-12-02 09:44:51 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T09:44:51Z.

Review: COMMENTED


Review of 89523904: 4 finding(s). 3 are inline. These are on lines outside the diff:

crates/xcl/src/hle/d3d12x/real.rs:10035: PSO_SHADERS gained || pixel_history::keeps_shaders() only in translated_graphics_pso_once. The two-pass GS path (here) and the MS path (~9956) still record hashes only when gpu_times is on, and neither calls note_pipeline. With XCL_SKIP_PS=, if that PS also appears in a geometry-shader (two-pass) pipeline, pso_shaders(real) returns None and those draws are silently not skipped, and the history logs them as "vs 0 ps 0". The user concludes the shader isn't at fault. One predicate for keeping hashes, used at every PSO_SHADERS insertion, would fix it.


These findings come from an AI-assisted review (Claude Code) and focus on correctness. Each is a candidate; please check it before acting on it.

<!-- greyfinch-sync:ivall/xcl:review:6148328430 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3509#pullrequestreview-6148328430). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T09:44:51Z. **Review:** COMMENTED --- Review of `89523904`: 4 finding(s). 3 are inline. These are on lines outside the diff: **`crates/xcl/src/hle/d3d12x/real.rs:10035`**: PSO_SHADERS gained `|| pixel_history::keeps_shaders()` only in `translated_graphics_pso_once`. The two-pass GS path (here) and the MS path (~9956) still record hashes only when gpu_times is on, and neither calls `note_pipeline`. With XCL_SKIP_PS=<hash>, if that PS also appears in a geometry-shader (two-pass) pipeline, `pso_shaders(real)` returns None and those draws are silently not skipped, and the history logs them as "vs 0 ps 0". The user concludes the shader isn't at fault. One predicate for keeping hashes, used at every PSO_SHADERS insertion, would fix it. --- _These findings come from an AI-assisted review (Claude Code) and focus on correctness. Each is a candidate; please check it before acting on it._
bmjask commented 2026-12-02 14:12:29 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T14:12:29Z.


@Prime1997 could you take a look at this one for review and merge? My automated review notes are above, if any.

<!-- greyfinch-sync:ivall/xcl:comment:7348164194 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3509#issuecomment-7348164194). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T14:12:29Z. --- @Prime1997 could you take a look at this one for review and merge? My automated review notes are above, if any.
Pipodi commented 2026-12-03 01:28:11 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Pipodi on 2026-12-03T01:28:11Z.


merge-check
base: 078358a058
head: 8952390414
merge: clean (git merge --no-ff onto 078358a0, merge 00906810; README.md +17, d3d12x/pixel_history.rs +914 new, real.rs +54/-1, bind.rs +18, present.rs +2/-1, mod.rs +1)
build: cargo build --workspace -> ok
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 3012 passed, 0 failed, 52 ignored; failing: none (SKIPPED 25: 22 no wave64, 2 no heap windows, 1 cannot disable the driver cache). The six new tests ran and passed (pixel_history::tests::* including gpu_a_targets_texel_is_read_before_and_after_a_draw on the RTX 4090, and real::skip_ps_tests::skip_ps_hashes_parse_and_unset_skips_nothing).title run: retail title on NVIDIA GeForce RTX 4090, no save, into the in-engine intro cutscenes, 420 s (ended by XCL_RUN_SECONDS), XCL_PIXEL_HISTORY and XCL_SKIP_PS unset (the default path), same env and frame presses as a run of main 078358a0 on this machine earlier tonight. This PR: 340 s in the cutscenes (from the first 2 s window with over 5000 dispatches, at 100 s, to the end), 2.03 presents/s there (690 presents), 2582 presents in the run, 0 device removals, 0 crashes (exit 0x0), peak video memory 21391 MB local, peak private 43.6 GB; no pixel-history or skip line in the log. Main 078358a0: 334 s (from 99 s), 2.03 presents/s, 2614 presents, 0 removals, exit 0x0, 21546 MB local, 43.6 GB. It passed the warm gate on its first attempt. Title binary = merge result + local scripted-press commits (input only) and two local log-only diagnostics.
review: read the whole diff. 1) Size: 1,006 lines with two independent diagnostics, and the description gives no reason it cannot be split, which CONTRIBUTING asks for over ~800 lines; XCL_SKIP_PS (real.rs skip_ps_list / hash_list / skip_named_ps and its two hooks in bind.rs) is self-contained and splits off cleanly, as the first check said. 2) Confirmed by reading (not run under the debug layer): copy_texels builds one barrier per entry, and bound_targets pushes one Target per point for the same resource and subresource, so with XCL_PIXEL_HISTORY_ALSO (or one target bound in two slots) a single ResourceBarrier call transitions the same subresource RENDER_TARGET -> COPY_SOURCE twice (the second one's StateBefore is already wrong), and the same on the way back. The PR's own GPU test does this too: line ~892 passes the same t twice ((&t, SLOT, None) and the crop) to one copy_texels. It passes on a release device, but the debug layer rejects it; deduplicate the barriers by (resource, subresource). 3) real.rs ~8312 still records PSO_SHADERS only when XCL_TRACE_FRAME is unset, so with both set XCL_SKIP_PS silently skips nothing and the history logs vs/ps 0. 4) Off-path cost: emit_prepared_indexed_draw evaluates with(this, |s| s.pso) (state map lookup plus the list's state mutex) for pixel_history::before on every indexed draw before before looks at ROUND; the description's "a draw's hook loads one atomic" holds for before itself, not this call site, and unset_pixel_history_changes_nothing does not cover it. The gpu_profile::begin line above already reads the same value; reuse it. 5) Minor: the readout trusts 6 presents with no fence, so a list running at that moment can be read half-written (the sentinel only catches untouched slots); the GPU test spins on GetCompletedValue with no time limit. Fine: off by default (before / note_dispatch return on one atomic, the creation hooks on a cached on()), parsing and limits, slot and row-pitch alignment, per-mip point mapping, retired readback buffers kept, lock order (SESSION -> RTV_VIEWS / CROP_PSOS / PSO_SHADERS; CLOCK -> SESSION -> BLENDS / RETIRED) has no cycle.
performance: default path measured: cutscene presents/s 2.03 vs 2.03 on main 078358a0, peak video memory 21391 vs 21546 MB, peak private 43.6 vs 43.6 GB. Per draw when off: one atomic and one cached check, plus the extra state lookup on indexed draws (finding 4). The opt-in path was not run here.
verdict: not yet: split off XCL_SKIP_PS or say in the description why the 1,006 lines cannot be split (CONTRIBUTING, over ~800), and fix the duplicate transition of one subresource in a barrier batch (finding 2, also in the PR's GPU test); findings 3 and 4 are small and could go with it. The default path is clean on the retail title.
hardware / tool and model: NVIDIA GeForce RTX 4090 24 GB, driver 621.40; Intel Core i9-13900K, 32 GB; Windows 11 build 26300; rustc 1.100.0, debug (suite) / release (title run); Claude Code, Claude Opus 5.5

<!-- greyfinch-sync:ivall/xcl:comment:7364376924 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3509#issuecomment-7364376924). Originally posted by [Pipodi](https://github.com/Pipodi) on 2026-12-03T01:28:11Z. --- merge-check base: 078358a058f7ba5d16690dba8dc4e55d2c88ae0a head: 895239041462ab51c15be990cbd63dd0838e5dac merge: clean (`git merge --no-ff` onto 078358a0, merge 00906810; README.md +17, d3d12x/pixel_history.rs +914 new, real.rs +54/-1, bind.rs +18, present.rs +2/-1, mod.rs +1) build: cargo build --workspace -> ok tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 3012 passed, 0 failed, 52 ignored; failing: none (SKIPPED 25: 22 no wave64, 2 no heap windows, 1 cannot disable the driver cache). The six new tests ran and passed (`pixel_history::tests::*` including `gpu_a_targets_texel_is_read_before_and_after_a_draw` on the RTX 4090, and `real::skip_ps_tests::skip_ps_hashes_parse_and_unset_skips_nothing`).title run: retail title on NVIDIA GeForce RTX 4090, no save, into the in-engine intro cutscenes, 420 s (ended by XCL_RUN_SECONDS), `XCL_PIXEL_HISTORY` and `XCL_SKIP_PS` unset (the default path), same env and frame presses as a run of main 078358a0 on this machine earlier tonight. This PR: 340 s in the cutscenes (from the first 2 s window with over 5000 dispatches, at 100 s, to the end), 2.03 presents/s there (690 presents), 2582 presents in the run, 0 device removals, 0 crashes (exit 0x0), peak video memory 21391 MB local, peak private 43.6 GB; no pixel-history or skip line in the log. Main 078358a0: 334 s (from 99 s), 2.03 presents/s, 2614 presents, 0 removals, exit 0x0, 21546 MB local, 43.6 GB. It passed the warm gate on its first attempt. Title binary = merge result + local scripted-press commits (input only) and two local log-only diagnostics. review: read the whole diff. 1) Size: 1,006 lines with two independent diagnostics, and the description gives no reason it cannot be split, which CONTRIBUTING asks for over ~800 lines; `XCL_SKIP_PS` (real.rs `skip_ps_list` / `hash_list` / `skip_named_ps` and its two hooks in bind.rs) is self-contained and splits off cleanly, as the first check said. 2) Confirmed by reading (not run under the debug layer): `copy_texels` builds one barrier per entry, and `bound_targets` pushes one `Target` per point for the same resource and subresource, so with `XCL_PIXEL_HISTORY_ALSO` (or one target bound in two slots) a single `ResourceBarrier` call transitions the same subresource RENDER_TARGET -> COPY_SOURCE twice (the second one's StateBefore is already wrong), and the same on the way back. The PR's own GPU test does this too: line ~892 passes the same `t` twice (`(&t, SLOT, None)` and the crop) to one `copy_texels`. It passes on a release device, but the debug layer rejects it; deduplicate the barriers by (resource, subresource). 3) `real.rs` ~8312 still records `PSO_SHADERS` only when `XCL_TRACE_FRAME` is unset, so with both set `XCL_SKIP_PS` silently skips nothing and the history logs vs/ps 0. 4) Off-path cost: `emit_prepared_indexed_draw` evaluates `with(this, |s| s.pso)` (state map lookup plus the list's state mutex) for `pixel_history::before` on every indexed draw before `before` looks at `ROUND`; the description's "a draw's hook loads one atomic" holds for `before` itself, not this call site, and `unset_pixel_history_changes_nothing` does not cover it. The `gpu_profile::begin` line above already reads the same value; reuse it. 5) Minor: the readout trusts 6 presents with no fence, so a list running at that moment can be read half-written (the sentinel only catches untouched slots); the GPU test spins on `GetCompletedValue` with no time limit. Fine: off by default (`before` / `note_dispatch` return on one atomic, the creation hooks on a cached `on()`), parsing and limits, slot and row-pitch alignment, per-mip point mapping, retired readback buffers kept, lock order (SESSION -> RTV_VIEWS / CROP_PSOS / PSO_SHADERS; CLOCK -> SESSION -> BLENDS / RETIRED) has no cycle. performance: default path measured: cutscene presents/s 2.03 vs 2.03 on main 078358a0, peak video memory 21391 vs 21546 MB, peak private 43.6 vs 43.6 GB. Per draw when off: one atomic and one cached check, plus the extra state lookup on indexed draws (finding 4). The opt-in path was not run here. verdict: not yet: split off `XCL_SKIP_PS` or say in the description why the 1,006 lines cannot be split (CONTRIBUTING, over ~800), and fix the duplicate transition of one subresource in a barrier batch (finding 2, also in the PR's GPU test); findings 3 and 4 are small and could go with it. The default path is clean on the retail title. hardware / tool and model: NVIDIA GeForce RTX 4090 24 GB, driver 621.40; Intel Core i9-13900K, 32 GB; Windows 11 build 26300; rustc 1.100.0, debug (suite) / release (title run); Claude Code, Claude Opus 5.5
This pull request cannot be merged automatically due to conflicts.
Merge manually to resolve the conflicts.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin 'upstream-pr/3509:upstream-pr/3509'
git switch 'upstream-pr/3509'

Merge

Merge the changes and update on Forgejo.

Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.

git switch 'main'
git merge --no-ff 'upstream-pr/3509'
git switch 'upstream-pr/3509'
git rebase 'main'
git switch 'main'
git merge --ff-only 'upstream-pr/3509'
git switch 'upstream-pr/3509'
git rebase 'main'
git switch 'main'
git merge --no-ff 'upstream-pr/3509'
git switch 'main'
git merge --squash 'upstream-pr/3509'
git switch 'main'
git merge --ff-only 'upstream-pr/3509'
git switch 'main'
git merge 'upstream-pr/3509'
git push origin 'main'
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
xcl-dev/xcl!3509
No description provided.