Repository navigation
Expand file tree
/
Copy pathpresent_path.hpp
More file actions
6133 lines (5999 loc) · 322 KB
/
Copy pathpresent_path.hpp
File metadata and controls
6133 lines (5999 loc) · 322 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2026
* SPDX-License-Identifier: MIT
*/
// The Present hook point (NRHookPoint=2, rc11).
//
// Included by dlssnr.hpp INSIDE namespace internal, just after
// d3d11_bridge.hpp, so it sees the whole D3D12 pipeline it drives. It is not
// a standalone header and must never be included anywhere else.
//
// Why. The Upscaled hook point enhances the game's DLSS output before the
// game's own post-processing, tone map and UI; field users compared it with
// a mod that runs NR on the swapchain and asked for that look. Here NR runs
// on the back buffer at ReShade's present event: after the game has drawn
// everything, before ReShade's effects and overlay (dxgi_swapchain.cpp
// on_present invokes the `present` add-on event, then present_effect_runtime,
// then flushes the immediate command list; the queue's lock is held
// throughout).
//
// What runs, per present:
//
// 1. the back buffer's encoding comes from the swapchain's colour space
// (NRPresentEncoding overrides it): sRGB is SDR (the legacy codec, as a
// DLSS output in an 8/10-bit format), scRGB is linear with 80 nits = 1.0,
// HDR10 is PQ with BT.2020 primaries (the v6 linearize converts to
// BT.709 and the commit converts back, shader Encoding 4). HLG or an
// unknown space is not served: the present declines present_format and
// the DLSS evaluates run the Upscaled hook point instead;
// 2. the guides are the game's DLSS motion vectors and depth, COPIED at its
// evaluate (CapturePresentGuides, on the game's list, into addon-owned
// clones) because by the present the game may have reused them. A
// capture carries a generation stamp (serial), its present clock, its
// contract, and a tracker marker; the present takes the newest capture
// whose recording was submitted and whose copies it can order itself
// after without deadlocking (the tracker's exact (fence, value) proofs,
// submission::UseSubmissionTokens): a proof on the present queue's own
// fence becomes a queue Wait, a proof on another queue's fence must
// already be complete (see "Cross-queue captures" below).
// NRPresentGuides=Never, or Optional
// when no capture matches (no DLSS, a stale or differently shaped one),
// uses neutral guides instead: zero motion and depth 0 with
// DepthInverted - the whole frame static and at infinity;
// 3. the after path itself - ProcessInline, the codec, the look stage, the
// working resolution - records into the addon's own list from a ring of
// eight (kPresentRing), reading a parameter block the addon fills (Color = Output = the
// back buffer, the guides above), with PresentTarget saying what differs:
// the back buffer rests in PRESENT, its workset is keyed by the
// swapchain (the buffers rotate), its units are the colour space's;
// 4. the list executes on the present queue (unwrapped: ReShade's queue
// proxy is not reachable from the event, and the queue detour tracks the
// native submit the same way), after ReShade's immediate list is
// flushed so earlier add-on work keeps its order, and a ring fence
// proves each slot's completion before the slot is reused (a present
// that finds its slot busy waits for it, bounded: kPresentSlotWaitMs).
//
// Frame generation. DLSS-G can present several frames per game frame
// (Silent Hill 2 field log: 10987 presents against 2533 evaluates), and at
// ReShade's present a generated frame and a real one carry no marker. What
// the path can use is DLSS-G's declared MultiFrameCount + 1, when observed
// for this stream, with the capture cadence as a fallback. A present that
// finds a capture it has not used yet follows a new game frame; others repeat it.
// NRPresentFrames=0 (default) runs NR on every present - motion scaled by
// 1/multiplier once the cadence says frame generation - and 1 runs it on the
// first present after each new capture only (present_repeat), so the
// generated frames are shown without NR. The cadence counts every present
// while a fresh capture exists, over windows of at least one second and
// 16 game frames. Two consistent windows establish a new multiplier;
// a hitch discards the partial window. NRPresentFgSource=2 keeps the old
// timing rule. Which policy runs, the multiplier and the measured
// cadence are logged when frame generation starts, stops or changes.
//
// Stability under frame generation (v8.0.3, FH6 2026-09-25: "frame
// generation now causes massive flickering with present mode"). Under
// NRPresentFrames=0 the player must never see NR switch on and off between
// presents, and NR's history must not restart on a transient gap. Four
// v8.0.2 causes, ranked by FH6's log: the ring of three declined 17 % of
// all presents (25-45 % while DLSS-G ran) and sent them out raw between NR
// presents (kPresentRing); those declines were left out of the cadence,
// which flipped the frame generation verdict and the motion scale every
// second or two (the old timing rule); a capture could overwrite the only
// complete one while newer ones were in flight, and the present fell to
// neutral guides and back with a history reset each way
// (NextPresentCaptureSet); and a fixed 8-present age made the last complete
// capture stale under high multipliers (kPresentGuideMaxAge).
// present[gaps=] counts what is left.
//
// Cross-queue captures (v8.0.2, FH6 dump 2026-09-25). Streamline DLSS-G
// presents on its own thread and on an extra high-priority direct queue it
// creates, while the game evaluates DLSS - where the capture copies are
// recorded - on its own queue, one frame ahead of the present. The game's
// queue already waits on the GPU for DLSS-G's queue to consume the previous
// frame's inputs, and DLSS-G signals that only after the present. A queue
// Wait on the present queue for the newest capture's token therefore closes
// a cycle: the present queue waits for the game's queue, which waits for the
// present queue. Both stop at the first Present frame, the GPU idles, and
// the game freezes or its hang watchdog kills it (FH6: hang55, 22 s; every
// field "Present mode crash" was a frame-generation title). So a token on
// another queue's fence is never waited for on the GPU: its capture is taken
// only once the fence reports it complete on the CPU, else the newest older
// complete capture is (neutral guides, or present_no_guides under Required,
// when none is), counted in present[in_flight=] and logged once. Under
// DLSS-G that pairs the present of game frame N-1 with frame N-1's guides,
// which is also the right pairing. A token on the present queue's own
// tracker fence keeps the queue Wait: the queue's order already puts the
// capture's Signal ahead of it, so it can never wait for work behind itself
// (a single-queue game, KCD2).
//
// Starvation. When ReShade stops delivering presents while NGX keeps
// evaluating (synthetic_tick_active: 250 ms without a present), nothing would
// run NR at all; once kPresentStarvedEvaluates evaluates in a row have seen
// no present, the evaluate hooks run the Upscaled hook point instead,
// counted in present[starved=] and logged once per episode. The present
// event restamps the present clock when this path returns (dlssnr.hpp
// OnPresent), so the path's own NR feature create is never a gap.
//
// Direct3D 11 (the native route, DX11Source). The same path runs through
// the Direct3D 11 bridge (d3d11_bridge.hpp RunBridge): the parameter block
// above stands in for the game's DLSS block, the back buffer crosses to the
// bridge's private D3D12 device through a shared twin as a DLSS output does
// (its twin rests in UAV, which the bridge tells the PresentTarget), and NR's
// result is copied back into the back buffer before ReShade's effects. The
// guides are copied at the game's D3D11 evaluate (CapturePresentGuides11) on
// its immediate context, the context that also runs the present's bridge
// copies, so the context orders every capture before the presents that read
// it: no marker and no queue wait. The foreign route (a third-party tool's
// D3D12 evaluates) and DX11Source=off are not served here: the first keeps
// the Upscaled hook point for the tool's evaluates, the second keeps the
// addon inert, and either is logged once.
inline constexpr uint32_t kPresentGuidesOptional = 0;
inline constexpr uint32_t kPresentGuidesRequired = 1;
inline constexpr uint32_t kPresentGuidesNever = 2;
// Present command lists in flight at once (v8.0.3; 3 through v8.0.2). A
// present whose slot the GPU has not finished cannot run NR, and under frame
// generation the present thread runs ahead of a GPU busy with NR on every
// present: FH6 (DLSS-G 2x, 4K, NR ~6 ms per present) sent 1789 of 10264
// presents to the screen raw, 25-45 % in the windows DLSS-G ran, interleaved
// with NR presents - the "massive flicker". The harness shape (4 presents per
// game frame on DLSS-G's queue shape, 4K) declined every 4th present with a
// ring of 3. Eight slots cover DXGI's frame latency plus 4x frame
// generation's burst; past that the present waits for its slot (below).
inline constexpr uint32_t kPresentRing = 8;
static_assert(kPresentRing <= kControlMaskDepthProofRingSize);
// The bounded CPU wait for the next slot, on the present thread under
// ReShade's queue lock. The slot was submitted kPresentRing presents earlier
// on this queue, which executes in order, so it completes as soon as the GPU
// is within kPresentRing - 1 presents of the CPU; DXGI's own frame-latency
// throttle blocks the same thread in the real Present for the same reason, so
// the wait moves that throttle rather than adding one. 100 ms (six 60 Hz
// frames) means the queue is not progressing (a wait on a CPU signal this
// thread owes): that present skips NR as before (present_busy,
// present[slot_timeouts=]), and presents stop waiting until a slot is free
// on its own, so a stuck queue costs one timeout, not one per present.
inline constexpr DWORD kPresentSlotWaitMs = 100;
inline constexpr uintptr_t kPresentGuideMarkerPrefix = 0xFFFF'0000'0000'0000ull;
inline bool IsPresentGuideMarker(const void* marker) {
return (reinterpret_cast<uintptr_t>(marker) & kPresentGuideMarkerPrefix) == kPresentGuideMarkerPrefix;
}
// A capture older than this many game frames (presents times the stream's
// frame generation multiplier) AND older than kPresentGuideMaxAgeNs no longer
// describes the image (a menu or a loading screen without DLSS). Through
// v8.0.2 it was 8 presents whatever the cadence: under 4x frame generation,
// with the newest capture in flight on the game's queue, the last complete
// one is 8-12 presents old, and before the cadence says frame generation
// (its first full second) the multiplier is still 1. The harness at 12
// presents per game frame ran 573 of 1448 presents without guides that way.
inline constexpr uint64_t kPresentGuideMaxAge = 8;
inline constexpr int64_t kPresentGuideMaxAgeNs = 250'000'000;
inline constexpr uint32_t kPresentLogCap = 16;
inline std::atomic_uint64_t present_frames_seen{0};
// Pre-FG NR passes (RunPresentPreFg and fg_service::Record), each a unit of the
// verdict's `seen` like an evaluate, ending in exactly one terminal
// (ProcessInline's success or decline). Every other unit of a pre-FG
// session is ineligible - the presents (kPresentPreFg), the DLSS-G
// evaluates (kNgxNotDlssEvaluation), the game's DLSS (kPresentHook) - so
// until rc4 its verdict read eligible=0 and its card "Starting..." while NR
// ran (Resonance v8.5.0-rc1: 3773 evaluates, eligible 0).
inline std::atomic_uint64_t present_prefg_attempts{0};
inline std::atomic_uint64_t present_guides_real{0};
inline std::atomic_uint64_t present_guides_neutral{0};
inline std::atomic_uint64_t present_captures{0};
inline std::atomic_uint64_t present_capture_busy{0};
inline std::atomic_uint64_t present_guide_waits{0};
// Presents that passed over a newer capture another queue had not finished
// (Cross-queue captures above).
inline std::atomic_uint64_t present_guides_in_flight{0};
inline std::atomic_uint64_t present_starved_fallbacks{0};
inline std::atomic_uint64_t present_format_fallbacks{0};
inline std::atomic<float> present_cadence{1.f};
// The flicker a player sees (v8.0.3): presents of a stream that already ran
// NR which reached the screen without it, whatever the reason.
inline std::atomic_uint64_t present_gaps{0};
// Presents that waited on the CPU for their ring slot, and waits that timed
// out (kPresentSlotWaitMs).
inline std::atomic_uint64_t present_slot_waits{0};
inline std::atomic_uint64_t present_slot_timeouts{0};
// Temporal history restarts the path asked for (a guide source switch), and
// frame generation verdict changes.
inline std::atomic_uint64_t present_history_resets{0};
inline std::atomic_uint64_t present_fg_flips{0};
// Presents per game frame the motion scale divides by (1 = no frame
// generation).
inline std::atomic_uint32_t present_fg_multiplier{1};
// The latest DLSS-G declaration, observed even when NRPresentPreFg=0 or
// pre-FG processing falls back. Identity pointers are compared only and are
// never dereferenced. Shape/device matching is used only for an unambiguous
// presenting stream; another matching swapchain keeps timing as fallback.
struct PresentFgDeclaration {
const void* device = nullptr;
uint32_t width = 0;
uint32_t height = 0;
uint32_t multiplier = 0;
int64_t observed_ns = 0;
uint64_t observed_present = 0;
};
inline PresentFgDeclaration present_fg_declaration;
// Set by a slot wait that timed out, cleared by a present that found its
// slot free: a queue that stopped costs one timeout. Under runtime_mutex.
inline bool present_slot_wait_off = false;
// Before frame generation (v8.1.0, RunPresentPreFg below). NRPresentPreFg:
// 1 (default) Auto - NR runs on DLSS-G's input whenever a DLSS-G evaluate is
// seen and can be served, once per game frame with the HUD composite - 2 the
// same with two NR passes whenever a HUD-less frame is tagged (no composite),
// and 0 every present, as through v8.0.3.
inline constexpr uint32_t kPresentPreFgOff = 0;
// How long a served pre-FG frame keeps the presents from running NR: 0.1 s
// or two game frames' presents at the SERVED frame's multiplier, whichever
// lasts longer. A host hitch over 0.1 s must not enhance a frame twice.
// Latch the multiplier at the successful evaluate: timing-only overrides
// may still say 1x on the first served 4x frame, and later timing changes
// must not shrink that frame's hold. At 4x, a stopped DLSS-G hands NR back
// after max(0.1 s, 8 presents), counted at its new presentation cadence.
inline constexpr int64_t kPresentPreFgHoldNs = 100'000'000;
inline constexpr uint64_t kPresentPreFgHoldFrames = 2;
// The original direct-list contract. On a compute list NGX's shader inputs
// use NON_PIXEL_SHADER_RESOURCE alone: PIXEL_SHADER_RESOURCE is illegal on
// that queue. This still relies on the integration handing NGX shader-read
// inputs; the harness checks both contracts, not a real DLSS-G implementation.
inline constexpr D3D12_RESOURCE_STATES kPresentPreFgInputState =
D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
// Game frames NR ran on before DLSS-G, its NR passes there (back buffer and
// HUD-less stand-in), DLSS-G evaluates seen, and the ones it could not serve.
inline std::atomic_uint64_t present_prefg_frames{0};
inline std::atomic_uint64_t present_prefg_passes{0};
inline std::atomic_uint64_t present_prefg_evaluates{0};
inline std::atomic_uint64_t present_prefg_fallbacks{0};
// v8.5.0-rc2, observe-only: served game frames whose HUD-less had another
// storage format than the frame, that were recorded on a compute list, and
// that were served while other D3D12 swapchains presented. Each is a shape
// v8.5 serves without a field log behind it.
inline std::atomic_uint64_t present_prefg_mixed_format{0};
inline std::atomic_uint64_t present_prefg_compute{0};
inline std::atomic_uint64_t present_prefg_multi_stream{0};
// v8.5.0-rc5: served game frames whose swapchain had another device face than
// DLSS-G's frame (RunPresentPreFg's matcher), and the DLSS evaluates that ran
// the Upscaled hook point because pre-FG could not serve frame generation.
inline std::atomic_uint64_t present_prefg_foreign_face{0};
inline std::atomic_uint64_t present_prefg_upscaled{0};
// v8.5.0-rc5. While DLSS-G interpolates, the presents cannot stand in for
// pre-FG: a game whose generated frames never pass ReShade's swapchain showed
// NR on one displayed frame in three (Wuthering Waves v8.5.0-rc1: 398 presents
// seen, all real, at 3x; pre-FG fell back on every game frame). After this
// many game frames in a row pre-FG could not serve for a reason of the frame's
// shape (kPresentPreFgMisses; not NR's own declines, which the Upscaled path
// meets too), the DLSS evaluates run the Upscaled hook point - v7's path, which
// DLSS-G interpolates from on every frame it makes - and the presents run none,
// until pre-FG could serve this many in a row again. NRPresentPreFg=0 keeps
// the presents: the user chose them. Under runtime_mutex, except the flag.
inline constexpr uint32_t kPresentPreFgMissFrames = 30;
inline constexpr uint32_t kPresentPreFgMisses = 2 | 8 | 16 | 32 | 128 | 1024;
inline uint32_t present_prefg_miss_streak = 0;
inline uint32_t present_prefg_clear_streak = 0;
inline uint32_t present_prefg_episodes_logged = 0;
// Under runtime_mutex: the last successful pre-FG frame's clocks and
// multiplier, plus the swapchain's target and size from its last present.
inline int64_t present_prefg_served_ns = 0;
inline uint64_t present_prefg_served_presents = 0;
inline uint32_t present_prefg_served_multiplier = 1;
inline PresentTarget present_prefg_target;
inline uint32_t present_prefg_target_multiplier = 1;
inline uint32_t present_prefg_width = 0;
inline uint32_t present_prefg_height = 0;
// The two pre-FG NR streams' keys in present_streams (never dereferenced).
inline const uint8_t present_prefg_keys[2] = {};
// Under runtime_mutex: NR's copy of DLSS-G's HUDLess (at rest in the selected
// input state), and the game's HUDLess it stands in for this
// game frame, so the frame's later evaluates (MultiFrameIndex 2..n) get it
// too.
inline ID3D12Resource* present_prefg_hudless = nullptr;
inline D3D12_RESOURCE_STATES present_prefg_hudless_state = kPresentPreFgInputState;
inline ID3D12Resource* present_prefg_hudless_source = nullptr;
inline const void* present_prefg_hudless_device = nullptr;
// v8.1.0, the one-pass HUD composite (shaders/prefg_compose.cs_5_1.hlsl):
// with a HUD-less frame NR runs once, on the stand-in, and the real frame is
// recomposed from it with the game's HUD kept. NRPresentPreFg=2 forces the
// two-pass path (NR on the stand-in and on the back buffer). 3 (v8.5.0-rc4)
// is Auto as it was through rc3: a frame whose mask is not a HUD (above
// kPresentPreFgHudShare) runs the two passes. Auto (1) gives such a frame
// the residual composite instead, one pass, when it differs from its HUD-less
// frame by grain everywhere but a HUD-sized share; a frame that differs by
// more over a larger share (a menu over most of the screen, a tone map after
// the UI) is ambiguous and runs the two passes, as through rc3
// (shaders/prefg_compose.cs_5_1.hlsl).
inline constexpr uint32_t kPresentPreFgTwoPass = 2;
inline constexpr uint32_t kPresentPreFgHudTwoPass = 3;
// Served frames the GPU measured as grain above the HUD share under Auto,
// which took the residual (read late, like prefg_hud_permille).
inline std::atomic_uint64_t present_prefg_residual{0};
// The difference mask's tolerance in the encoded domain: half an 8-bit step
// (1 / 510), so a HUD pixel one 8-bit step off the scene is HUD while 10-bit
// and FP16 rounding (under 1 / 1023, relative above 1) is not.
inline constexpr float kPresentPreFgEpsilon = 1.f / 510.f;
// Above this share of HUD pixels the mask is not a HUD: a HUD covers a few
// percent of the screen (the harness rectangle is 4 %), while grain or a tone
// map after the UI makes nearly every pixel differ (the harness grain arm:
// all of them). 25 % sits far from both; a frame above it runs two passes.
inline constexpr float kPresentPreFgHudShare = 0.25f;
// Measurements at or below the share, in a row, before the mask path is
// trusted again after one above it (which leaves at once). Before the first
// measurement arrives (a few game frames) the path is two-pass, the
// conservative one; the first clean measurement trusts it.
inline constexpr uint32_t kPresentPreFgCleanFrames = 30;
// Descriptor sets and stats slots in rotation. Reuse requires the tracked
// recording to be discarded and its submissions complete; queue depth or
// elapsed frames are not lifetime proof. Every use writes fresh views, so
// recycled game-resource addresses never retain a stale descriptor.
inline constexpr uint32_t kPresentPreFgComposeSets = 16;
inline constexpr uint32_t kPresentPreFgComposeDescriptors = 6;
inline constexpr uint32_t kPresentPreFgComposeDepthNullSrv = kPresentPreFgComposeSets * kPresentPreFgComposeDescriptors;
inline constexpr uint32_t kPresentPreFgComposeMotionNullSrv = kPresentPreFgComposeDepthNullSrv + 1;
inline constexpr uint32_t kPresentPreFgComposeDepthProofNullCbv = kPresentPreFgComposeMotionNullSrv + 1;
// Per slot: [HUD pixels, serial, grain-sized pixels] (the shader's Stats).
inline constexpr uint32_t kPresentPreFgStatsWords = 3;
// Under runtime_mutex. The composite's objects, made in the world (device
// face) of the list that first ran it; a list of another world makes a new
// heap and keeps the old one until shutdown (it may still be in flight).
struct PreFgCompose {
const ID3D12Device* device = nullptr; // compared only
ID3D12DescriptorHeap* heap = nullptr;
uint32_t descriptor_size = 0;
ID3D12Resource* output = nullptr; // the recomposed frame, UAV at rest
ID3D12Resource* stats = nullptr; // kPresentPreFgStatsWords per slot, COMMON at rest
ID3D12Resource* zero = nullptr; // upload: one slot's zero words
ID3D12Resource* readback = nullptr; // persistently mapped
const uint32_t* readback_data = nullptr;
uint32_t serial = 0; // game frames composed
uint32_t read_serial = 0; // the newest measurement read
uint32_t clean_frames = 0;
uint8_t slot_mode[kPresentPreFgComposeSets] = {}; // the shader mode each slot measured
bool one_pass = false; // the mask path is trusted
bool exceeded = false; // a mask measurement was ever above the share
bool unavailable = false; // the PSO could not be made: two passes for the session
};
inline PreFgCompose present_prefg_compose;
// Without submission proofs, old heaps stay alive until present-path teardown.
inline std::vector<ID3D12DescriptorHeap*> present_prefg_old_heaps;
inline ID3D12PipelineState* present_prefg_compose_pso = nullptr;
// Game frames served on the two-pass path (a HUD-less frame whose composite
// could not run or whose mask read as more than HUD), and the latest HUD
// share the composite measured (mask or UI alpha), in 1/1000.
inline std::atomic_uint64_t present_prefg_two_pass{0};
inline std::atomic_uint32_t present_prefg_hud_permille{0};
// The last present ran no NR because a pre-FG frame served it (the status
// card's "NR once per game frame, before frame generation").
// Evaluates since the last present (PresentTakesEvaluate).
inline std::atomic_uint32_t present_unpresented_evaluates{0};
inline constexpr uint32_t kPresentStarvedEvaluates = 3;
// Raised by a present whose swapchain cannot be served, lowered by one that
// can; while it is up the evaluates run the Upscaled hook point.
inline std::atomic_bool present_unusable{false};
// The steady clock of the last present the path was selected for, 0 once
// RetireIdlePresentPath released what it held.
inline std::atomic<int64_t> present_served_ns{0};
// The presenting display's Windows SDR white level in nits (0 = unknown),
// polled about once a second outside runtime_mutex.
inline std::atomic<float> present_sdr_white{0.f};
inline std::atomic<int64_t> present_sdr_white_polled_ns{0};
// v8.5.0-rc8 (PLAN_SETUP_MATRIX.md F4): an upstream RenoDX mod's Game
// Brightness in nits (0 = none), polled with the Windows level. A RenoDX
// HDR mod puts the game's diffuse white at its ToneMapGameNits; the Windows
// SDR level is the white of SDR content under HDR, which such a frame never
// uses. Onimusha rc5 at Present: 223 nits from the Windows slider against
// the mod's 100, NR's input a stop and more too dark (the black-level
// report). Every RenoDX mod stores it in ReShade.ini [renodx-preset1]: the
// mod starts each session on preset 1 and does not store a switch
// (utils/settings.hpp preset_index). Taken only while a RenoDX module
// other than this add-on is loaded (renodx_mod_loaded, the module scan in
// InstallHooks: an uninstalled mod leaves its ini section behind), with its
// tone mapper on (ToneMapType 0 is the game's own) and the value in
// 48-10000; any signal absent, the Windows level stays the source.
// NRPresentWhiteSource=1 keeps the Windows level; NRPresentWhiteNits > 0
// outranks both.
inline std::atomic<float> present_mod_white{0.f};
inline std::atomic_bool renodx_mod_loaded{false};
// The white source the last HDR present logged, and its nits.
inline std::atomic<const char*> present_white_logged{nullptr};
inline std::atomic<float> present_white_logged_nits{0.f};
struct PresentBaseFrame {
const void* source = nullptr; // The game owns its SR output; identity only.
std::pair<uint64_t, uint64_t> recording;
ID3D12GraphicsCommandList* native_list = nullptr; // Identity only.
uint64_t swapchain_epoch = 0;
const void* backbuffer = nullptr;
uint64_t sequence = 0;
uint64_t source_generation = 0;
uint64_t source_resource_generation = 0;
uint64_t configuration = 0;
uint64_t queue_entry = 0;
bool source_ready = false;
bool sealed = false;
bool attempted = false;
};
struct PresentGuideSet {
bool mixed_predecessor = false;
ID3D12Resource* motion = nullptr;
ID3D12Resource* depth = nullptr;
const void* device_identity = nullptr;
const NVSDK_NGX_Handle* source_handle = nullptr; // compared only
output_framerate::OutputIdentity output;
// 0 = never captured.
uint64_t serial = 0;
uint64_t comparison_request = 0; // F5 request whose inline pass was bypassed
// present_generation and the steady clock at the capture.
uint64_t captured_at = 0;
int64_t captured_ns = 0;
// The ring fence value of the last present that read it.
uint64_t read_value = 0;
// A tracker use no other object has: its submissions are this capture's.
const void* marker = nullptr;
// F5 still needs queue identity after a completed recording is pruned.
// Keep one exact fence/value; multiple producing fences are ambiguous.
// This remains fixed size even if the game replays a recording repeatedly.
FenceRef completed_fence;
uint64_t completed_value = 0;
bool completed_multiple_queues = false;
PresentBaseFrame base_frame;
// The capture's guide contract (dims, subrects, motion scale, flags, the
// game's Reset) and the DLSS output it describes.
FeatureState contract;
uint32_t output_width = 0;
uint32_t output_height = 0;
// A Direct3D 11 capture (CapturePresentGuides11) fills these instead of
// the D3D12 clones, and only a present of its own API reads it.
ID3D11Texture2D* motion11 = nullptr;
ID3D11Texture2D* depth11 = nullptr;
bool d3d11 = false;
};
struct PresentSlot {
ID3D12CommandAllocator* allocator = nullptr;
ID3D12GraphicsCommandList* list = nullptr;
uint64_t value = 0;
ID3D12Resource* control_mask_depth_proof = nullptr;
uint32_t* control_mask_depth_proof_value = nullptr;
};
// One ring per device face (NGX records in the world of its list, so the
// lists are made on the face NR's runtime was initialized on).
struct PresentRing {
ID3D12Device* device = nullptr;
ID3D12CommandQueue* queue = nullptr;
ID3D12Fence* fence = nullptr;
uint64_t submitted = 0;
bool handoff_wait_timed_out = false;
PresentSlot slots[kPresentRing];
};
// One NR stream per swapchain: its temporal history is the NR feature
// registered under Handle(), an address no NGX handle can have (the
// Streamline path keys its synthetic streams the same way; never
// dereferenced).
struct PresentStream {
output_framerate::OutputIdentity output;
present_frame_policy::Clock base_frame_clock;
bool base_history_unbound = false;
PresentEditReuseMonitor edit_reuse_monitor;
uint64_t base_frame_attempt = 0;
// Only this swapchain's current, submitted, final full-surface copy can
// supply the ordinary x2 route. The identity expires with its buffers.
uint64_t base_frame_epoch = 0;
// Identity-only target inventory. Do not retain DXGI buffers across resize.
std::vector<const void*> mixed_buffers;
const void* mixed_queue = nullptr;
ID3D12CommandQueue* mixed_submission_queue = nullptr; // compared only
const void* mixed_source = nullptr;
const void* mixed_output = nullptr;
std::shared_ptr<ID3D12Resource> mixed_source_resource;
std::pair<uint64_t, uint64_t> mixed_recording;
const void* mixed_copy_target = nullptr;
const void* mixed_copy_marker = nullptr;
FenceRef mixed_copy_fence;
uint64_t mixed_copy_value = 0;
bool mixed_copy_ambiguous = false;
const void* mixed_write_marker = nullptr;
FenceRef mixed_write_fence;
uint64_t mixed_write_value = 0;
std::pair<uint64_t, uint64_t> mixed_write_recording;
bool mixed_write_ambiguous = false;
bool mixed_write_foreign = false;
uint32_t mixed_width = 0;
uint32_t mixed_height = 0;
DXGI_FORMAT mixed_format = DXGI_FORMAT_UNKNOWN;
const void* mixed_device = nullptr;
const void* mixed_consumed_source = nullptr;
uint64_t mixed_consumed_generation = 0;
uint64_t mixed_source_generation = 0;
uint64_t mixed_configuration = 0;
uint64_t mixed_history_epoch = 0;
uint64_t mixed_capture = 0;
uint64_t mixed_source_tick = 0;
uint32_t mixed_sources = 0;
stage_plan::Plan mixed_plan;
uint8_t handle_key = 0;
uint8_t neutral_handle_key = 0;
const NVSDK_NGX_Handle* Handle(bool neutral_model = false) const {
return reinterpret_cast<const NVSDK_NGX_Handle*>(neutral_model ? &neutral_handle_key : &handle_key);
}
bridge::OwnedParameters parameters;
ID3D12Resource* neutral_motion = nullptr;
ID3D12Resource* neutral_depth = nullptr;
ID3D11Texture2D* neutral_motion11 = nullptr;
ID3D11Texture2D* neutral_depth11 = nullptr;
uint64_t consumed_serial = 0;
bool real_guides = false;
const NVSDK_NGX_Handle* history_guide_source = nullptr; // compared only
uint64_t history_guide_generation = 0;
::renodx::dlss5::PresentCadence fg_cadence;
const void* device_identity = nullptr;
// The device behind a Streamline proxy that ReShade took for the native
// device (StreamlineBaseIdentity), or null. Compared only.
const void* streamline_identity = nullptr;
uint32_t backbuffer_width = 0;
uint32_t backbuffer_height = 0;
DXGI_FORMAT backbuffer_format = DXGI_FORMAT_UNKNOWN;
PresentTarget prefg_target;
bool prefg_target_valid = false;
bool d3d11 = false;
uint64_t cadence_captures = 0;
const NVSDK_NGX_Handle* cadence_source = nullptr; // compared only
int64_t cadence_source_ns = 0;
int64_t cadence_ambiguous_until_ns = 0;
// Whole-number presentation multiplier, not a noisy instantaneous ratio.
uint32_t fg_multiplier = 1;
// Presents this stream ran NR on (present[gaps=] counts the ones after
// the first that did not).
uint64_t nr_presents = 0;
uint64_t native_route_id = 0;
const void* native_output_identity = nullptr;
const NVSDK_NGX_Handle* native_fg_handle = nullptr;
uint64_t native_options_revision = 0;
std::optional<bool> native_options_enabled;
fg::xefg::OrdinaryPresentReceipt ordinary_color;
uint64_t ordinary_color_guide_serial = 0;
submission::QueueOrderProof ordinary_color_order;
struct NativeColour {
struct Write {
std::shared_ptr<submission::RecordingStatus> recording;
submission::QueueOrderProof retired_order;
uint64_t serial = 0;
bool comparable = false;
bool rollback_recorded = false;
std::shared_ptr<submission::RecordingStatus> replacement;
uint64_t replacement_serial = 0;
};
output_framerate::OutputIdentity output;
const void* backbuffer = nullptr;
uint64_t guide_serial = 0;
std::pair<uint64_t, uint64_t> recording;
const void* marker = nullptr;
uint64_t serial = 0;
bool accepted = false;
FenceRef retired_fence;
uint64_t retired_value = 0;
std::shared_ptr<submission::RecordingStatus> recording_status;
bool rollback_recorded = false;
std::vector<Write> writes;
} native_color;
struct ColourOverwrite {
uint64_t guide_serial = 0;
const void* backbuffer = nullptr;
std::shared_ptr<submission::RecordingStatus> recording;
submission::QueueOrderProof retired_order;
};
std::vector<ColourOverwrite> colour_overwrites;
};
struct PresentRetired {
IUnknown* object = nullptr;
const void* key = nullptr;
GpuLease lease;
bool tracker_proof = false;
};
inline PresentRing present_ring;
inline PresentGuideSet present_guide_sets[kPresentGuideSets];
inline uint64_t present_capture_serial = 0;
inline std::unordered_map<const void*, PresentStream> present_streams;
inline uint64_t present_base_epoch_serial = 0;
struct OrdinaryPresentOwnerState {
fg::xefg::OrdinaryPresentAttempt attempt;
fg::xefg::OrdinaryPresentReceipt receipt;
output_framerate::OutputIdentity output;
uintptr_t swapchain = 0;
uintptr_t backbuffer = 0;
uintptr_t sdk_owner = 0;
uint64_t sdk_call = 0;
bool producer_conflict = false;
};
inline std::unordered_map<const void*, OrdinaryPresentOwnerState> ordinary_present_attempts;
inline uint64_t ordinary_present_attempt_serial = 0;
inline thread_local std::vector<fg::xefg::OrdinaryPresentAttempt> ordinary_present_event_attempts;
inline void ConfigureOrdinaryPresentOwner();
inline void ResetPresentStreamHistory(PresentStream* stream, uint32_t reason);
// Caller holds runtime_mutex. Ending a color receipt has no GPU lifetime effect.
inline void InvalidateOrdinaryPresentAttemptsLocked(uintptr_t swapchain = 0) {
std::erase_if(ordinary_present_attempts, [&](const auto& entry) {
const auto& [owner, state] = entry;
return swapchain == 0 || reinterpret_cast<uintptr_t>(owner) == swapchain
|| state.swapchain == swapchain || state.output.swapchain == swapchain;
});
std::erase_if(ordinary_present_event_attempts, [&](const auto& attempt) {
const auto found = ordinary_present_attempts.find(reinterpret_cast<const void*>(attempt.owner));
return found == ordinary_present_attempts.end() || found->second.attempt != attempt;
});
}
inline fg::xefg::OrdinaryPresentAttempt BeginOrdinaryPresentAttempt(
reshade::api::command_queue* queue, reshade::api::swapchain* swapchain) {
ConfigureOrdinaryPresentOwner();
if (queue == nullptr || swapchain == nullptr || queue->get_device() != swapchain->get_device()
|| swapchain->get_device() == nullptr || swapchain->get_device()->get_api() != reshade::api::device_api::d3d12
|| swapchain->get_back_buffer_count() == 0) return {};
const auto backbuffer = swapchain->get_current_back_buffer();
const auto native_backbuffer = reinterpret_cast<uintptr_t>(renodx::utils::directx::NativeIdentity(
reinterpret_cast<IUnknown*>(backbuffer.handle)));
const auto native_swapchain = reinterpret_cast<uintptr_t>(renodx::utils::directx::NativeIdentity(
reinterpret_cast<IUnknown*>(swapchain->get_native())));
const auto output = output_framerate::MatchPresentOutput(reinterpret_cast<uintptr_t>(swapchain), backbuffer.handle);
RuntimeLock lock(runtime_mutex);
const fg::xefg::OrdinaryPresentAttempt attempt{reinterpret_cast<uintptr_t>(swapchain), ++ordinary_present_attempt_serial};
ordinary_present_attempts[swapchain] = {.attempt = attempt, .output = output,
.swapchain = native_swapchain, .backbuffer = native_backbuffer};
std::erase_if(ordinary_present_event_attempts, [&](const auto& previous) {
const auto found = ordinary_present_attempts.find(reinterpret_cast<const void*>(previous.owner));
return found == ordinary_present_attempts.end() || found->second.attempt != previous;
});
ordinary_present_event_attempts.push_back(attempt);
return attempt;
}
inline void EndOrdinaryPresentAttempt(fg::xefg::OrdinaryPresentAttempt attempt, HRESULT status = S_OK) noexcept {
if (!attempt) return;
RuntimeLock lock(runtime_mutex);
const auto found = ordinary_present_attempts.find(reinterpret_cast<const void*>(attempt.owner));
if (found != ordinary_present_attempts.end() && found->second.attempt == attempt) {
if (status != S_OK && found->second.receipt.executed) {
if (const auto stream = present_streams.find(reinterpret_cast<const void*>(attempt.owner)); stream != present_streams.end()) {
ResetPresentStreamHistory(&stream->second, kResetRecovery);
if (stream->second.ordinary_color.attempt == attempt) {
stream->second.ordinary_color.group_complete = false;
}
}
}
ordinary_present_attempts.erase(found);
}
std::erase(ordinary_present_event_attempts, attempt);
}
inline fg::xefg::OrdinaryPresentAttempt CurrentOrdinaryPresentAttempt(const void* swapchain) {
const auto found = std::find_if(ordinary_present_event_attempts.rbegin(), ordinary_present_event_attempts.rend(),
[&](const auto& attempt) { return attempt.owner == reinterpret_cast<uintptr_t>(swapchain); });
return found != ordinary_present_event_attempts.rend() ? *found : fg::xefg::OrdinaryPresentAttempt{};
}
inline fg::xefg::OrdinaryPresentAttempt FindOrdinaryPresentAttempt(uintptr_t swapchain, uintptr_t backbuffer) noexcept {
RuntimeLock lock(runtime_mutex);
fg::xefg::OrdinaryPresentAttempt attempt;
for (const auto& [owner, state] : ordinary_present_attempts) {
if ((backbuffer != 0 && state.backbuffer != backbuffer)
|| (backbuffer == 0 && state.swapchain != swapchain && state.output.swapchain != swapchain)) continue;
if (attempt) return {};
attempt = state.attempt;
}
return attempt;
}
// Snapshot while this private generation is still open. The tracker exposes
// its first reservation separately; a later ring Signal cannot repair it.
inline void SnapshotOrdinaryPresentProof(fg::xefg::OrdinaryPresentReceipt* receipt) {
std::vector<submission::RecordingBlocker> recordings;
submission::InspectRecordedWork([&](uint64_t list, uint64_t generation, const submission::Generation&) {
return receipt->submission.recording == std::pair{list, generation};
}, &recordings);
if (recordings.size() != 1) return;
const auto& recording = recordings.front();
const auto& first = recording.first_submission;
receipt->first_execute = recording.first_execute;
receipt->first_state = first.state;
receipt->first_fence = reinterpret_cast<uintptr_t>(first.fence.fence);
receipt->first_value = first.value;
receipt->first_completed_value = first.completed_value;
const auto healthy = [](const submission::SubmissionFact& fact) {
return fact.value != 0 && (fact.state == submission::SubmissionProofState::kInFlight
|| fact.state == submission::SubmissionProofState::kComplete);
};
receipt->proofs_healthy = recording.first_execute != 0 && recording.unreserved_submissions == 0
&& healthy(first) && !recording.submissions.empty()
&& std::ranges::all_of(recording.submissions, healthy);
receipt->proofs_complete = receipt->proofs_healthy && std::ranges::all_of(recording.submissions, [](const auto& fact) {
return fact.state == submission::SubmissionProofState::kComplete;
});
}
// The ring still owns this fence. Copy completion facts before it is released;
// no receipt retains the fence or extends allocator/resource residency.
inline void RefreshOrdinaryPresentCompletionLocked() {
if (present_ring.fence == nullptr) return;
const auto completed = present_ring.fence->GetCompletedValue();
for (auto& [_, state] : ordinary_present_attempts) {
auto& receipt = state.receipt;
if (receipt.submission.fence != reinterpret_cast<uintptr_t>(present_ring.fence)) continue;
receipt.submission.completed_value = completed;
if (completed == UINT64_MAX) {
receipt.proofs_healthy = false;
} else if (receipt.proofs_healthy && receipt.submission.signaled && completed >= receipt.submission.fence_value) {
receipt.proofs_complete = true;
}
}
}
// Recording order cannot prove which BB write executes last. Retain each
// generation so its actual queue receipt can order it against the owned color.
inline void ObserveOrdinaryPresentProducerLocked(const void* output, ID3D12GraphicsCommandList* list) {
for (auto& [_, state] : ordinary_present_attempts) {
if (state.receipt.executed && state.backbuffer == reinterpret_cast<uintptr_t>(output)) {
state.producer_conflict = true;
}
}
for (auto& [_, stream] : present_streams) {
const uint64_t ordinary_version = (stream.ordinary_color.backbuffer == reinterpret_cast<uintptr_t>(output)
? stream.ordinary_color_guide_serial : 0);
const bool native_write = stream.native_color.backbuffer == output && !stream.native_color.writes.empty();
const uint64_t native_version = (native_write ? stream.native_color.guide_serial : 0);
std::erase_if(stream.colour_overwrites, [&](const auto& write) {
return (!(write.guide_serial == stream.ordinary_color_guide_serial
&& write.backbuffer == reinterpret_cast<const void*>(stream.ordinary_color.backbuffer))
&& !(write.guide_serial == stream.native_color.guide_serial && write.backbuffer == stream.native_color.backbuffer))
|| (write.recording->closed.load() && !write.recording->submitted.load());
});
std::shared_ptr<submission::RecordingStatus> recording;
for (const auto [version, owned] : {std::pair{ordinary_version, ordinary_version != 0}, std::pair{native_version, native_write}}) {
if (!owned) continue;
if (recording == nullptr) {
recording = submission::ObserveRecording(list);
}
if (std::ranges::none_of(stream.colour_overwrites, [&](const auto& write) {
return write.guide_serial == version && write.backbuffer == output && write.recording == recording;
})) {
stream.colour_overwrites.push_back({.guide_serial = version, .backbuffer = output, .recording = recording});
submission::TrackUse(list, output, submission::UseKind::kOutputColor, {.resource = output, .subresource = 0});
submission::TrackUse(list, recording.get());
}
}
}
}
// The raw detours only inspect the specific native lists that carry an
// open SR-to-backbuffer proof. Unrelated draws never enter runtime_mutex.
inline bool IsPresentSourceList(ID3D12GraphicsCommandList* list) {
return list != nullptr && !SuppressCommandStateObservation()
&& std::ranges::any_of(present_source_lists, [list](const auto& watched) {
return watched.load(std::memory_order_acquire) == list;
});
}
inline void ClearPresentSource(PresentGuideSet* set, bool forget_output = false) {
if (forget_output && set->serial == 0) {
const output_framerate::SourceIdentity source{.handle = reinterpret_cast<uintptr_t>(set->source_handle),
.generation = set->base_frame.source_generation,
.device = reinterpret_cast<uintptr_t>(set->device_identity),
.resource = reinterpret_cast<uintptr_t>(set->base_frame.source),
.resource_generation = set->base_frame.source_resource_generation};
output_framerate::ForgetSourceOutput(source.handle, &source);
}
present_source_lists[set - present_guide_sets].store(nullptr, std::memory_order_release);
set->base_frame = {};
}
inline void ReleasePresentQueueOrder() {
observed_present_queue.store(nullptr, std::memory_order_release);
present_queue_order.store({}, std::memory_order_release);
}
inline bool WantsPresentBaseFrames() {
return enabled.load(std::memory_order_relaxed)
&& hook_point.load(std::memory_order_relaxed) == kHookPresent
&& edit_reuse_enabled.load(std::memory_order_relaxed)
&& present_frames.load(std::memory_order_relaxed) == 1
&& stack_passes.load(std::memory_order_relaxed) == 1;
}
inline bool ObservesPresentBaseFrames() {
return enabled.load(std::memory_order_relaxed)
&& hook_point.load(std::memory_order_relaxed) == kHookPresent;
}
inline bool ObservesAdaptiveSourceDelivery() {
const auto hook = hook_point.load(std::memory_order_relaxed);
if (!enabled.load(std::memory_order_relaxed) || !nr_adaptive_enabled.load(std::memory_order_relaxed)
|| (hook != kHookRender && hook != kHookUpscaled)) return false;
const auto plan = RequestedStagePlan();
return plan.valid && !plan.mixed && plan.group_count == 1;
}
// One observed FG-only stream. Interleaved identities restart admission;
// equal-size views remain ambiguous until exactly one swapchain matches.
// Only identity comparisons use these pointers, under runtime_mutex.
struct AutoFgObservation {
const void* device = nullptr;
uint32_t width = 0;
uint32_t height = 0;
// Concrete, as the pre-FG owner matcher compares it: a same-size window
// in another format (HDR10 beside SDR) is not this frame's stream.
DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN;
uint64_t evaluates = 0;
int64_t last_ns = 0;
const void* swapchain = nullptr;
};
inline AutoFgObservation auto_fg_observation;
// Last admitted owner for a nonblocking Present observation. It is compared
// only; RunPresentPath revalidates the locked state before recording work.
inline std::vector<PresentRetired> present_retired;
// Under runtime_mutex: an evaluate fallback episode is logged once.
inline bool present_fallback_episode = false;
// Inline fallback may already be recorded for a future presented image.
// Resuming presents or clearing the starvation counter does not prove that
// image is untouched. F5 must establish a new bypassed frame first.
inline bool present_inline_fallback_pending = false;
inline uint32_t present_logged_lines = 0;
// runtime_mutex; one bounded handoff per target, never a frame scheduler.
inline const char* mixed_present_status = "disabled";
inline uint64_t mixed_present_submitted = 0;
inline uint64_t mixed_present_rejected = 0;
inline uint64_t mixed_present_copy_serial = 0;
inline uint64_t mixed_present_write_serial = 0;
inline FenceRef mixed_present_last_fence;
inline uint64_t mixed_present_last_value = 0;
inline void LogPresent(reshade::log::level level, const std::string& message) {
if (present_logged_lines >= kPresentLogCap) return;
++present_logged_lines;
Log(level, "Present hook point: " + message
+ (present_logged_lines == kPresentLogCap
? " (further Present hook point lines are not logged)"
: ""));
}
// Caller holds runtime_mutex. Retirement, like every other addon object:
// released once the tracker proves no recording can reach it.
template <typename T>
inline void RetirePresentResource(T** resource) {
if (*resource == nullptr) return;
present_retired.push_back(
{*resource, *resource, AcquireGpuLease(),
queue_tracking_active.load(std::memory_order_relaxed)});
*resource = nullptr;
}
inline void DrainPresentRetired() {
for (auto it = present_retired.begin(); it != present_retired.end();) {
if (it->tracker_proof ? submission::ResourceReleasable(it->key)
: !it->lease.empty()
&& QueryGpuLease(it->lease) != GpuLeaseState::kPending) {
it->object->Release();
it = present_retired.erase(it);
} else {
++it;
}
}
}
// Our own queue signal follows every submission, including any guide waits.
// A removed device cannot execute the recording again. Caller holds
// runtime_mutex, which keeps the ring and its submitted value together.
inline bool PresentRingComplete() {
return present_ring.fence == nullptr
? present_ring.submitted == 0
: present_ring.fence->GetCompletedValue() >= present_ring.submitted;
}
// Default retirement polls. An explicit Provider handoff may wait once for
// this owner's submitted work. A timeout keeps the entire ring and guide
// read values intact, and later attempts poll until GPU completion.
// Caller holds runtime_mutex.
inline bool ReleasePresentRing(bool wait_for_handoff = false) {
RefreshOrdinaryPresentCompletionLocked();
// This pool always resets a slot before recording its next submission.
// Retiring it ends future replay now; the fence still owns every in-flight
// reference and must complete before any list or allocator is released.
for (PresentSlot& slot : present_ring.slots) {
submission::DiscardOwnedRecording(slot.list, submission::RecordingOwner::kOrdinaryPresent);
}
if (!PresentRingComplete() && wait_for_handoff && !present_ring.handoff_wait_timed_out) {
const auto started_ns = SteadyNowNs();
const auto before = present_ring.fence != nullptr ? present_ring.fence->GetCompletedValue() : 0;
std::vector<submission::RecordingBlocker> blockers;
submission::InspectRecordedWork([](uint64_t, uint64_t, const auto& generation) {
return generation.owner == submission::RecordingOwner::kOrdinaryPresent;
}, &blockers);
LogRecordedWorkBlockers("ordinary Present handoff before wait", blockers);
if (present_ring.fence != nullptr) {
if (HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr)) {
if (SUCCEEDED(present_ring.fence->SetEventOnCompletion(present_ring.submitted, event))) {
WaitForSingleObject(event, kPresentSlotWaitMs);
}
CloseHandle(event);
}
}
present_ring.handoff_wait_timed_out = !PresentRingComplete();
std::ostringstream message;
message << "ordinary Present handoff wait: queue=" << present_ring.queue << ", fence=" << present_ring.fence
<< ", required=" << present_ring.submitted << ", completed_before=" << before
<< ", completed_after=" << (present_ring.fence != nullptr ? present_ring.fence->GetCompletedValue() : 0)
<< ", duration_ms=" << (SteadyNowNs() - started_ns) / 1e6
<< ", timed_out=" << present_ring.handoff_wait_timed_out;
Log(reshade::log::level::info, message.str());
}
RefreshOrdinaryPresentCompletionLocked();
if (!PresentRingComplete()) return false;
for (PresentSlot& slot : present_ring.slots) {
if (slot.list != nullptr) submission::OnCommandListDestroyed(slot.list);
ReleaseCom(slot.list);
ReleaseCom(slot.allocator);
if (slot.control_mask_depth_proof_value != nullptr) {
slot.control_mask_depth_proof->Unmap(0, nullptr);
}
ReleaseCom(slot.control_mask_depth_proof);
}
ReleaseCom(present_ring.fence);
ReleaseCom(present_ring.queue);
ReleaseCom(present_ring.device);
present_ring = {};
// The fence the sets' read values name is gone with it.
for (PresentGuideSet& set : present_guide_sets) set.read_value = 0;
return true;
}
// Caller holds runtime_mutex.
inline bool EnsurePresentRing(ID3D12Device* face) {
if (present_ring.device == face && present_ring.fence != nullptr) return true;
if (!ReleasePresentRing()) return false;
// RENODX_NR_TEST_FAIL_PRESENT_RING=<n>: the first n builds fail, so the
// lane that covers the fallback (present_switch) can produce it.
static uint32_t test_failures_left = [] {
char buffer[16] = {};
size_t length = 0;
if (getenv_s(&length, buffer, sizeof(buffer), "RENODX_NR_TEST_FAIL_PRESENT_RING") != 0
|| length == 0) {
return 0u;
}
return static_cast<uint32_t>(strtoul(buffer, nullptr, 10));
}();
bool built = test_failures_left == 0;
if (!built) --test_failures_left;
built = built
&& SUCCEEDED(face->CreateFence(
0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&present_ring.fence)));
for (PresentSlot& slot : present_ring.slots) {
built = built
&& SUCCEEDED(face->CreateCommandAllocator(
D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&slot.allocator)))
&& SUCCEEDED(face->CreateCommandList(
0, D3D12_COMMAND_LIST_TYPE_DIRECT, slot.allocator, nullptr,
IID_PPV_ARGS(&slot.list)))
&& SUCCEEDED(slot.list->Close());
}
if (!built) {
ReleasePresentRing();
LogPresent(reshade::log::level::error,
"the present command list ring could not be created");
return false;
}
face->AddRef();
present_ring.device = face;
// A rebuild waits for the old ring, so more than one per device is a cost
// worth seeing in a field log.
static uint32_t builds = 0;
LogPresent(reshade::log::level::info,
"present command list ring built (" + std::to_string(++builds) + ")");
return true;
}