Skip to content

d3d12: post-divide NDC dot-product corner selection and exact fourth corner for rectangle lists (RT-RECT-LIST-CORNER) - #2478

Open
lixonik wants to merge 3 commits into
ProjectLeonida:mainfrom
lixonik:rt-rect-list-corner
Open

lixonik wants to merge 3 commits into
ProjectLeonida:mainfrom
lixonik:rt-rect-list-corner

Conversation

@lixonik

@lixonik lixonik commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Fixes the rectangle-list fourth-corner selection and reconstruction in runtime/src/rect_list_geometry.h for package RT-RECT-LIST-CORNER (#2464 Part B; builds on @kevincommits's numerical analysis in #1608 (comment)).

Root cause removed

  1. Post-divide NDC dot-product corner rule: Previously, rect_list_geometry() picked the corner opposite the longest edge using pre-divide clip-space squared lengths dx^2 + dy^2. That failed on:
    • thin axis-aligned strips (aspect > ~4100:1, where dx^2 + dy^2 == dx^2 in float32 breaks the tie-break and flips the rectangle);
    • large uniform w (e.g., w = 1e20, where dx^2 + dy^2 overflows to +Inf);
    • differing w across vertices (where pre-divide distances pick the wrong corner).
      Computing post-divide NDC (x/w, y/w) and selecting the vertex with the minimum signed incident-edge dot product (equivalently max dot(e_in, e_out), unordered >= so NaN / w == 0 deterministically falls back to v1) is algebraically identical to opposite-the-longest-side by the law of cosines for all triangles (including rotated rectangles, near-square, obtuse/acute, and degenerate) while keeping exact 0.0 dot product at any axis-aligned right angle.
  2. Bit-exact non-drifting fourth corner: Replaces (((v0 + v1) + v2) - corner) - corner with direct (other_a, other_b, corner) selection and per-component bit-equality checks (OpBitcast + OpIEqual), preserving axis-aligned coordinates and constant/flat attributes bit-exact (0 ULP drift) while keeping the documented clip-space other_a + other_b - corner rule uniformly for Position and all interpolants (docs/d3d12_vulkan.md).
  3. Orthogonal to runtime: preamble-only flat scan, safe type lookups, and portable CPU test for rect_list_geometry #1970: Leaves the preamble SPIR-V parser and the for (const Corners& c : corners) loop header intact (git merge-tree with runtime: preamble-only flat scan, safe type lookups, and portable CPU test for rect_list_geometry #1970 is conflict-free).

Testing

  • Negative control on unmodified main (ec91d695c): d3d12_rect_list_corner_test fails on 7 corner-rule cases (w=1e20 corner v2: 2080/4096 off plane; differing w=(1.875,1,1) corner v0 & w=(1,1,1.875) corner v2: 2080/4096 missed each; thin strip 5000:1 corner v2 & v1: 2048/4096 missed each; flat non-dyadic exact: 4096/4096 pixels drifted; differing w=(1.875,1,1) flat color: 2080/4096 missed).
  • With this PR (220aa322e):
    • ctest -R "^(d3d12_rect_list_corner|indirect_topology_and_stats)$": 2/2 passed (d3d12_rect_list_corner_test: all 17 cases passed, 0.27 s).
    • python -I tests/test_ctest_registration.py -v: 6/6 passed.
    • python -I scripts/check_no_game_data.py ... and git diff --check: clean.
  • GPUs tested: NVIDIA GeForce RTX 5070 12 GB, driver 610.88, Vulkan 1.4.341, Windows 11, MSVC 19.44 (VK_LAYER_KHRONOS_validation not installed locally; d3d12_rect_list_corner_test is self-contained without llvm-mc and skips with 77 when geometryShader or Vulkan is unavailable).

AI-assisted (Antigravity, Gemini).

…ts (RT-RECT-LIST-CORNER)

Select the right-angle corner in post-divide NDC (x/w, y/w) via the minimum
signed edge dot product (law-of-cosines equivalent to opposite the longest
side, without float32 squared-length tie-break loss on thin axis-aligned
strips or pre-divide overflow/distortion when w is large or differs across
vertices). Compute the fourth corner bit-exact whenever either non-corner
vertex matches the corner (zero ULP drift on axis-aligned grid coordinates
and constant/flat attributes) and extrapolate linearly in NDC and 1/w when
w differs with positive 1/w4.

Adds self-contained GPU regression test d3d12_rect_list_corner_test covering
w != 1, large w = 1e20, differing w, 5000:1 thin strips, near-square, rotated
45-degree rectangles, bit-exact non-dyadic constant attributes, and degenerate
triangles.
@djrolfes

Copy link
Copy Markdown
Contributor

Independent Linux/Wine + NVIDIA check at head 4283e3ffa (merged cleanly onto origin/main c0201a806 alongside #2480, #2477, #2476, #2474).

  • Environment: Linux 7.2.15, wine-11.22, clang-cl + xwin cross-build, NVIDIA GeForce RTX 3070 Ti 8 GB, driver 620.73.04, Ryzen 7 5800X, 32 GB RAM. No game files.
  • CTest: d3d12_rect_list_corner passed (6.31 s) on RTX 3070 Ti under Wine.

AI-assisted.

@MoonEyes

Copy link
Copy Markdown
Collaborator

Tested for #2464 as Aslanek asked: unit tests and a game run on my machine; CI ignored for now as asked.

RUN pr2478-court | 2026-11-27 | MoonEyes | AI-assisted: Claude Code (Claude Opus 5.5)
BASE:        main ec91d695c + PR #2478 (head 4283e3ffa), merged locally without conflict, nothing pushed | shaders: main's own translation
MACHINE:     RTX 4060 8 GB, desktop, only GPU, display attached | NVIDIA 610.88 | Windows 11 Pro 26300 | Ryzen 5 3600 | 32 GB | Windows GPU timeout at the default (2 s)
RECIPE:      short recipe: docs/running.md Windows NVIDIA recipe, pipeline cache warm, 330 s cap, scripted button presses from 60 s | build RelWithDebInfo, only the PR's targets built
TESTS:
  - d3d12_rect_list_corner_test (new, ctest d3d12_rect_list_corner): pass on the PR | fails on main: yes (new test built with the PR's CMakeLists on top of main's sources: exit 1, 2080 of 4096 pixels off the exact constant)
GAME:        session=1 at 105 s | world entered at 160 s | last window >= 1 img/s ends at 235 s | 0 frames after world entry + 240 s | end: stopped by my local stall guard at 241 s (no new frame line for 180 s), not by the cap | device loss: no (no fault report) | private RAM max 17301 MB
COMPARED TO: w77 (main ec91d695c, same short recipe): session=1 at 145 s, world at 195 s, last window >= 1 img/s at 293 s, private RAM max 16043 MB, ended by the time limit (337 s)
             w79 (main, same short recipe): world at 200 s, last window >= 1 img/s at 286 s, private RAM max 16583 MB, ended by the time limit (350 s)
             one run each (n=1); on main the spread of world entry on this recipe is about 165 to 200 s, so no conclusion on timings
VERDICT:     new test passes and fails on main; game reached the world, stopped by the stall guard, no device loss; inconclusive for the game (n=1)

Reading (marked):

  • MEASURED: the display stops after the world is entered (75 s after world entry for the last window >= 1 img/s here; 98 s on w77, 86 s on w79). Present on main too, not caused by this PR (finding Coordinating who works on what (continued from #14) #1608 (comment)).
  • MEASURED: the run was ended by my local stall guard, not by a crash or a device loss. A stall guard end is not comparable with the time-limit end of the main runs; compare the last-window figure, not the end time. I do not attribute the stop to this PR.

Limits: one machine, one run for the PR, one run for each main witness.

AI-assisted (Claude Code, Claude Opus 5.5)

@MoonEyes

Copy link
Copy Markdown
Collaborator

Review of head 4283e3f (read against main 43a9d56, which contains ec91d69). The game run is in my RUN above. I suggest splitting this PR into two:

Ready to merge on its own: picking the corner in NDC with the dot product (I checked that it matches "longest side" through the law of cosines) and copying the vertices bit for bit. Both look sound to me.

Needs a source or a separate PR:

  1. runtime/src/rect_list_geometry.h:273-287: when w differs, the fourth corner is extrapolated in NDC and in 1/w. docs/d3d12_vulkan.md:3112 still says the hardware uses "v2 + v3 - v1 for the position and every interpolant", and this PR keeps that line while its new text in the bullet just below describes the NDC and 1/w rule, so the doc now states both. I found no hardware measurement behind the new rule, so the test checks behaviour that the PR itself defines. Could you either drop this path from the PR or point to a console reference that confirms it?
  2. runtime/src/rect_list_geometry.h:281-283: when 1/w4 <= 0, the position falls back to w4 = 1, but the attributes stay linearly extrapolated in clip space. Position and attributes then follow two different models. The differing w=(1,2,2) case (d3d12_rect_list_corner_test.cpp:253) uses a constant colour, so it checks coverage but not how varying attributes are extrapolated.

Minor points:

AI-assisted (Claude Code, Claude Opus 5.5)

…ry (RT-RECT-LIST-CORNER)

Addresses review feedback on ProjectLeonida#2478:
- Drop the unmeasured NDC + 1/w differing-w fourth-corner extrapolation and w4=1 fallback, keeping the documented clip-space other_a + other_b - corner rule (with bit-exact component selection) uniformly for Position and all attributes.
- Restore the original range-based corners loop so rect_list_geometry.h merges cleanly with ProjectLeonida#1970.
- Update d3d12_rect_list_corner_test cases and header comment to match.
@lixonik

lixonik commented Nov 27, 2026

Copy link
Copy Markdown
Contributor Author

@MoonEyes Thanks for the thorough review and testing! Addressed all four points in 220aa322e:

  1. Dropped the unmeasured NDC + 1/w fourth-corner path (and its 1/w4 <= 0 -> w4 = 1 fallback): rect_list_geometry() now applies exact_fourth(other_a, other_b, corner) uniformly to both Position and every interpolant, matching docs/d3d12_vulkan.md (v2 + v3 - v1) with no mixed position/attribute model and a much smaller SPIR-V body. Updated docs/d3d12_vulkan.md to note that differing-w fourth-corner behavior beyond v2 + v3 - v1 is unmeasured on console hardware.
  2. Conflict-free with runtime: preamble-only flat scan, safe type lookups, and portable CPU test for rect_list_geometry #1970: Restored for (const Corners& c : corners) verbatim; verified git merge-tree against runtime: preamble-only flat scan, safe type lookups, and portable CPU test for rect_list_geometry #1970 exits 0 with no conflicts.
  3. Updated d3d12_rect_list_corner_test.cpp: Removed the stale case-7 tile note from the header comment and updated the differing-w cases to w = (1.875, 1, 1) (corner v0) and w = (1, 1, 1.875) (corner v2), where pre-divide clip-space lengths on main pick the wrong corner while post-divide NDC picks the right corner and clip-space other_a + other_b - corner produces positive w4 = 0.125.

Re-tested on RTX 5070 (Windows 11, driver 610.88, Vulkan 1.4.341, VK_LAYER_KHRONOS_validation not installed locally):

  • Negative control on unmodified main (rect_list_geometry.h): 7/17 cases fail (w=1e20, both differing-w solid cases, both 5000:1 thin strips, flat non-dyadic exact, and differing-w flat color).
  • With 220aa322e: d3d12_rect_list_corner (17/17 cases, 0.27 s) and indirect_topology_and_stats (0.03 s) both pass; test_ctest_registration.py (6/6) and check_no_game_data.py clean.

AI-assisted (Antigravity, Gemini).

@timbot103

Copy link
Copy Markdown
Contributor

Reviewed at head 220aa322e on Windows 11 (MSVC 2022 19.44) with dual-GPU Vulkan validation (LEONIDA_VK_VALIDATION=1, Vulkan SDK 1.4.363.0).

Verification

  • Built d3d12_rect_list_corner_test.
  • d3d12_rect_list_corner_test (LEONIDA_VK_VALIDATION=1): all 17 corner-rule cases passed with 0 validation errors on both NVIDIA GeForce RTX 5080 (616.64) and AMD Radeon(TM) Graphics (25.10.30.02).

Notes (non-blocking)

  • Post-divide NDC dot-product corner selection, winding/provoking-vertex preservation across all three permutations, and clip-space other_a + other_b - corner synthesis (rect_list_geometry.h:191-194, 245-267) look clean and address the earlier 1/w review note.
  • Minor docs note (docs/d3d12_vulkan.md:3113; rect_list_geometry.h:221-243): The doc states degenerate/zero-W inputs fall back to the first vertex, but the shader divides by w without a zero-W guard (e.g., (2,1,0), (0,0,1), (0.5,0.5,1) yields (-Inf,-Inf,+Inf) selecting vertex 2 under IEEE infinities, and Vulkan leaves division by zero unspecified; collinear (-1,0,1) also selects the middle vertex). Either guard zero-W explicitly or qualify the doc statement.

Approve.

AI-assisted review + local MSVC/dual-GPU verification.

@tiguan26 tiguan26 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving. Merged onto current main (431ceba) with no conflicts, cross-built (clang-cl 19 + xwin) and ran under Wine 11.22 on llvmpipe: d3d12_rect_list_corner passes, and so does the existing d3d12_rect_list (the console's rectangle and quad lists through the translated vs_m15 / ps_m15), so the rewrite keeps the real translated draws right. As a negative check I built the new test against main's rect_list_geometry.h: it fails, starting with the w=1e20 case drawing the wrong colour (corner v2: pixel (0,0) got 0.5,0.125,0.25,0.5).

I checked the math rather than the comment. With s_k the dot of the two edges at vertex k as the code forms them, the law of cosines gives s_k = c_k^2 - (a^2 + b^2 + c^2)/2, where c_k is the side opposite k: the sum term is the same for all three vertices, so the largest s_k is exactly the vertex opposite the longest side, as the comment says, without the old squared-length comparisons' tie losses. The unordered compares send NaN (w == 0) to v1 as documented. exact_fourth is right per component: if a component of one non-corner vertex equals the corner's bits, a + b - c is exactly the other vertex's value, so returning it bit for bit only removes rounding. The other_a / other_b picks give (v2, v3), (v1, v3), (v1, v2) for corners v1, v2, v3, and the emitted triangles are unchanged. The new opcode numbers (OpBitcast 124, OpFDiv 136, OpIEqual 170, OpFUnordGreaterThanEqual 191) are right.

One thing worth stating in the docs line, not a blocker: the corner is now chosen in post-divide NDC rather than clip-space x/y. That only changes the choice when the three w differ, which a screen-space rectangle shouldn't have, but it is a behaviour change for such input.

AI-assisted (Claude Code, Claude Opus 5.5).

@zmasi

zmasi commented Nov 28, 2026

Copy link
Copy Markdown
Contributor

VERIFY-2478-VEGA20-RADV: the same 17-case d3d12_rect_list_corner fixture gave 7 failures on main 33db04a70 and 17/17 passes on 220aa322e merged with that main, under Wine on gfx906 / RADV Mesa 26.0.8. All draws completed; Red was a pixel mismatch, not a build or feature skip.

On main, each 5,000:1 strip missed 2,048 of 4,096 pixels. Each differing-w corner case missed 2,080, and the uniform large-w case had 2,080 off-plane pixels. A constant non-dyadic color drifted in 1,024 pixels at uniform w; it was bit-exact on the merge. The adjacent d3d12_rect_list readbacks passed on both trees.

Captured geometry modules matched the corresponding main and merged emitters byte for byte. The CPU topology/statistics control also passed on both. Khronos synchronization validation was active: zero validation errors or sync hazards across the four hardware runs. Synthetic only.

AI-assisted.

@timbot103 timbot103 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Static audit of 220aa322e only. No builds, tests, or GPU runs were performed for this review. The emitted vertex order preserves the first vertex for flat shading and keeps the documented homogeneous fourth-corner reconstruction.

  • runtime/src/rect_list_geometry.h:225 divides by W before enforcing the fallback in docs/d3d12_vulkan.md:3113. Clip-space (x, y, w) values (1/8, 1/4, 0), (-1/2, 0, 1), and (0, 1/2, 1) yield (-Inf, -Inf, +Inf) on IEEE division and select v3. Base selects v1 and emits no geometry below NDC Y = 0. Please guard signed zero before dividing and add a mixed-W coverage case. The all-zero-W fixture at runtime/test/d3d12_rect_list_corner_test.cpp:276 cannot distinguish the corner choices, and the collinear fixture selects the middle vertex, so the general degenerate-fallback wording also needs qualification.
  • runtime/src/rect_list_geometry.h:231 can overflow the products even with finite NDC. With clip-space XY (1, 1), (0, 0), (1, -1) and common w = 2^-65, separate float32 operations can produce (-Inf, NaN, -Inf) and pick v1 over the right angle at v2. A common power-of-two scale on projected XY before forming the edges would preserve the ordering and keep the products finite for this case.

AI-assisted.

@lixonik

lixonik commented Nov 29, 2026

Copy link
Copy Markdown
Contributor Author

@timbot103 I reproduced both corner-selection issues on the current head 220aa322e471cbfb2fd90ba711341163a1f9302d. On RTX 5070 (NVIDIA 610.88, Windows 10, Vulkan validation 1.4.363.1), I captured the six positions emitted by the generated geometry shader in each case. Both mixed signed-zero-W cases and the large finite-NDC case with the axes swapped emitted the wrong corner in all three fresh runs. Plain main 02944d4ca1 and main with a local correction each passed all six cases in three fresh runs.

The local correction selects v1 for zero or non-finite W or non-finite projection. For large finite projected coordinates it scales both axes by the same power of two before calculating the edge dot products. The correction is still local because GitHub rejected the push under its commit-email protection. The new D3D12 raster assertions still need a CTest run with Windows SDK 10.0.26100 or newer.

AI-assisted. Codex (GPT-6).

@lixonik

lixonik commented Nov 29, 2026

Copy link
Copy Markdown
Contributor Author

I also ran the D3D12 raster fixture on RTX 5070 (610.88) with Khronos validation. I used the same extended fixture in both builds, with the pinned Agility SDK headers and a static CRT on Windows 10/MSVC 19.29.

  • Current public head 220aa322e471cbfb2fd90ba711341163a1f9302d: 17/18 cases passed. The mixed-zero-W draw wrote 85 pixels below NDC Y = 0, where the target should stay clear.
  • With the local correction: 18/18 passed, including the mixed-zero-W draw.

The permanent raster case checks positive zero. Negative zero and the large finite-NDC inputs were checked by capturing geometry-stage output in the separate probe above. The correction is still local.

AI-assisted. Codex (GPT-6).

@lixonik

lixonik commented Nov 29, 2026

Copy link
Copy Markdown
Contributor Author

Pushed the corner-selection fix from the checks above as 2171766479 (re-committed with my GitHub noreply address so the fork accepts the push).

python -I scripts/check_no_game_data.py: passed. git merge-tree --write-tree main HEAD: clean against ef32995848.

AI-assisted (Antigravity, Gemini).

@OreoFR

OreoFR commented Nov 29, 2026

Copy link
Copy Markdown
Contributor

Verified by OreoFR — READY

  • Base: main ef32995 + this PR (head 2171766) merged with --no-ff
  • Red (main + only this PR's tests): d3d12_rect_list_corner fails on main in 7 cases. Examples: w=1e20 corner v2: 2080 of 4096 pixels off plane, the two differing-w fills, the two 5000:1 thin strips, and the two exact-constant cases. The test's CMake registration was kept for the red run. The new mixed W with zero case passes on main as well, since main also falls back to v1 there. It guards against the regression found on 220aa32 rather than reproducing a main bug.
  • Green (merge): d3d12_rect_list_corner passes (18 cases); ctest (Ninja RelWithDebInfo, all targets, gta6rt launchers excluded) on main + this PR alone: 498 tests, new failures vs main: none (main alone: 497 tests, 1 failure: xbox_present, which fails here too)
  • gta6rt.exe links without the XMA decoder (LEONIDA_CARGO=OFF, LEONIDA_XMA2_DECODER_LIB empty), main + this PR; imports unchanged vs main (655 functions, no new DLL, no WS2_32)
  • Diff read (new commit 2171766): no issue. Checked the following:
    • The power-of-two scale keeps every edge dot product finite: coordinates above 2^60 are brought down to about 2^60, so a product is at most about 2^123.
    • Any zero, non-finite or NaN w, or a non-finite projected coordinate, selects v1. NaN bits compare above the infinity bits in the unsigned max.
    • The ordered compares give a first-wins tie order (v1, then v2, then v3), and at most one of at_v2/at_v3 is set.
    • The doc paragraph matches the code.
  • Other runs: Matches my red/green on 220aa32 (same 7 cases) and zmasi's VEGA20 result. The new head addresses the signed-zero-w case lixonik reproduced after timbot103's audit.
  • Machine: Windows 11, Intel Core Ultra 7 155H, RTX 4070 Laptop 8 GB, NVIDIA 621.40, Python 3.12.10, MSVC 19.44

AI-assisted (Claude Code, Claude Opus 5.5), run for OreoFR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants