Repository navigation
Expand file tree
/
Copy pathscreenshot.hpp
More file actions
5835 lines (5655 loc) · 282 KB
/
Copy pathscreenshot.hpp
File metadata and controls
5835 lines (5655 loc) · 282 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
*/
// One-shot NR screenshot pair of ONE final presentation image, copied before
// and after its NR pass. Inline DLSS textures are not display screenshots:
// the game's downstream exposure, tone map and UI cannot be reconstructed
// from them. The present path temporarily supplies the comparison for F5.
// A separate diagnostic mode copies an evaluated model input/output pair;
// those files explicitly exclude the game's later processing and display UI.
//
// Design contract (v2.7 rewrite): the feature must be inert while idle. The
// present path never touches D3D12 objects, user32 (beyond the one hotkey
// poll), std::filesystem, or the heap on behalf of this feature until the user
// arms it. Concretely:
// - No QueryInterface and no command queue anywhere in this file. GPU
// completion is proven by the submission tracker (submission_tracker.hpp):
// every copy is a tracked use of its readback on the list that records
// it, and a capture settles once no recording holding one of its
// readbacks can still execute (rc11, TIME-01/03). A present proves
// nothing: a generated frame presents between the evaluate and its
// submit, and an unrelated list completes first. Only a session without
// the queue hook falls back to a fence-completed lease (gpu_lease.hpp)
// acquired once the capture frame has presented - a poll of
// ID3D12Fence::GetCompletedValue, never a CPU wait - and to the
// present-generation delay (kSettlePresents) for queues without a
// tracked fence.
// - Every readback is stamped at creation (kUnwrittenStamp): a stamp still
// there when the worker reads it is a copy the GPU never ran, and the
// capture is refused (counted) instead of written as a black pair.
// - The render/evaluate thread only creates two addon-owned READBACK heap
// buffers (Prepare stage). No filesystem calls there either.
// - Readback mapping, display coding, PNG/JPEG encoding, and file IO run on a
// dedicated worker thread (created lazily on the first hand-off). The
// present thread only moves a finished capture into the worker's job slot.
// - runtime_mutex (dlssnr.hpp) is never held across any of that work. This
// module has its own state_mutex; the only legal ordering is
// runtime_mutex -> state_mutex -> job_mutex (state_mutex -> the
// submission tracker's mutex for TrackUse and ReadbacksReleasable), and
// the worker takes job_mutex alone.
// - The worker is detached and never joined: Shutdown runs under the DLL
// loader lock (DllMain PROCESS_DETACH), where joining any running thread
// deadlocks. Shutdown drains owned state and raises shutdown_requested;
// the worker exits on its own and the process reclaims it at exit.
//
// Compatibility notes (v4.1.5): the files carry no alpha - HDR intermediates
// routinely carry alpha 0/NaN, and an alpha-respecting viewer composites
// those to a fully black image. The pair may be cropped to
// the engine-declared output subrect when the DLSS output resource is larger
// than what the engine actually renders (black-margin titles).
#pragma once
#include "brand.h"
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cmath>
#include <condition_variable>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <cctype>
#include <array>
#include <deque>
#include <memory>
#include <filesystem>
#include <fstream>
#include <limits>
#include <mutex>
#include <optional>
#include <span>
#include <string>
#include <string_view>
#include <stdexcept>
#include <thread>
#include <utility>
#include <vector>
#include <d3d12.h>
#include <d3d11_4.h>
#include <include/reshade.hpp>
#include "../../utils/path.hpp"
#include "../../utils/png.hpp"
#include "gpu_lease.hpp"
#include "submission_tracker.hpp"
#include "control_mask_capture.hpp"
#if defined(NR_NEXUS_DEV_CONTROL)
#include <iomanip>
#include <sstream>
#include "report_bundle.hpp"
#include "version.h"
#endif
#if defined(NR_NEXUS_DEV_CONTROL) && defined(NR_NEXUS_TEST_XEFG_PRESENT_PROBE)
#include "nr_xefg_present_probe.hpp"
#endif
namespace renodx::addons::dlss5::screenshot {
enum class RequestKind : uint32_t { FINAL_PRESENTATION, PRE_FG_SERVICE
#if defined(NR_NEXUS_DEV_CONTROL)
, INLINE_RESTORE_ROI, FG_CONSUMER_ROI
#endif
#if defined(NR_NEXUS_DEV_CONTROL) && defined(NR_NEXUS_TEST_XEFG_PRESENT_PROBE)
, XEFG_PRESENT_ROI
#endif
};
enum class SourceMode : uint32_t { kAuto = 0, kFinalPresent = 1, kEvaluatedBuffer = 2 };
inline std::atomic_uint32_t source_mode = 0;
// Set only by an explicit producer contract identifying a separate host
// presentation window. An absent/unknown contract keeps the final frame.
inline std::atomic_bool separate_presentation = false;
// Independent P0 switch; frozen into PendingCapture at PrepareCapture.
inline std::atomic_bool stage_planes_enabled = false;
enum class HdrCaptureMode { COMMIT_CORE, MODEL_TRACE };
struct CaptureRect {
uint32_t x = 0, y = 0, width = 0, height = 0;
};
#if defined(NR_NEXUS_DEV_CONTROL)
struct FgConsumerContext {
uintptr_t feature_handle = 0;
uintptr_t parameters_identity = 0;
uint32_t module_slot = 0;
uint32_t mfg_index = 0;
bool mfg_index_available = false;
// Screenshot retirement clock only; this is not an FG source frame token.
uint64_t present_generation = 0;
// Derived from the selected typed input at Begin, never supplied as proof by a caller.
uintptr_t input_resource_identity = 0;
DXGI_FORMAT input_format = DXGI_FORMAT_UNKNOWN;
uint32_t input_width = 0, input_height = 0;
CaptureRect roi;
};
struct FgConsumerStatus {
std::string capture_id;
const char* status = "idle";
std::string reason;
uint64_t serial = 0;
};
#if defined(NR_NEXUS_TEST_XEFG_PRESENT_PROBE)
struct XefgCaptureRequest {
std::filesystem::path directory;
std::string capture_id;
std::array<CaptureRect, 2> rois{};
uint64_t retirement_generation = 0;
};
struct XefgCaptureStatus {
std::string capture_id;
const char* status = "idle";
std::string reason;
uint32_t recorded = 0, written = 0, blocked = 0;
uint64_t last_serial = 0;
bool drained = true;
};
struct XefgPresentCapture {
XefgCaptureRequest request;
xefg_present_probe::CopyContext context;
std::array<D3D12_PLACED_SUBRESOURCE_FOOTPRINT, 2> footprints{};
std::array<uint64_t, 2> bytes{};
bool api_returned = false;
HRESULT api_result = E_PENDING;
};
#endif
struct InlineRestoreContext {
bool d3d11_bridge = false, mixed = false, present = false;
bool preparing = false, warmup = false, reset_sent = false;
bool upscaled = false, api_returned = false, ngx_succeeded = false;
uint32_t group_begin = 0, stack = 0, pass = 0;
uint32_t work_width = 0, work_height = 0, output_width = 0, output_height = 0;
CaptureRect output_rect;
uint32_t hdr_mode = 0, codec = 0, ngx_result = 0, reset_reasons = 0;
DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN;
uint64_t evaluation_sequence = 0, source_generation = 0, present_generation = 0;
bool tail_inputs_aligned = false;
uint64_t model_evaluation_index = 0, source_feature = 0;
};
inline bool InlineRestoreEligible(const InlineRestoreContext& context) {
return context.d3d11_bridge && !context.mixed && !context.present && !context.preparing
&& !context.warmup && !context.reset_sent && context.reset_reasons == 0
&& context.upscaled && context.api_returned && context.ngx_succeeded
&& context.group_begin == 0 && context.stack == 1 && context.pass == 0
&& context.work_width == 3840 && context.work_height == 2160
&& context.output_width == 3840 && context.output_height == 2160
&& context.output_rect.x == 0 && context.output_rect.y == 0
&& context.output_rect.width == 3840 && context.output_rect.height == 2160
&& context.hdr_mode == 0 && context.codec == 2 && context.format == DXGI_FORMAT_R16G16B16A16_UNORM;
}
inline bool BridgeModelStagesEligible(const InlineRestoreContext& context) {
return context.d3d11_bridge && !context.mixed && !context.present && !context.preparing
&& !context.warmup && !context.reset_sent && context.reset_reasons == 0
&& context.upscaled && context.api_returned && context.ngx_succeeded
&& context.group_begin == 0 && context.stack == 1 && context.pass == 0
&& context.work_width != 0 && context.work_height != 0
&& context.work_width <= context.output_width && context.work_height <= context.output_height
&& (context.work_width != context.output_width || context.work_height != context.output_height)
&& context.output_rect.x == 0 && context.output_rect.y == 0
&& context.output_rect.width == context.output_width && context.output_rect.height == context.output_height
&& context.evaluation_sequence != 0 && context.source_generation != 0 && context.source_feature != 0
&& context.hdr_mode == 0 && context.codec == 2 && context.format == DXGI_FORMAT_R16G16B16A16_UNORM;
}
inline constexpr std::array<const char*, 7> kBridgeModelStageNames{
"original", "proxy", "neural", "post_compose", "post_look", "post_resolve", "post_restore"};
struct InlineRestoreStatus {
std::string capture_id;
const char* status = "idle";
std::string reason;
uint64_t serial = 0;
};
inline constexpr uint32_t MAX_INLINE_TAIL_FRAMES = 48;
inline constexpr CaptureRect INLINE_FLOOR_RECT{.x = 1936, .y = 1106, .width = 152, .height = 48};
inline constexpr CaptureRect INLINE_TAIL_RECT{.x = 960, .y = 768, .width = 320, .height = 128};
struct InlinePlaneSpec {
const char* name;
DXGI_FORMAT format;
CaptureRect rect;
uint32_t source_width = 3840;
uint32_t source_height = 2160;
};
inline std::span<const InlinePlaneSpec> InlinePlanes(bool tail) {
static constexpr InlinePlaneSpec floor_planes[]{
{"original", DXGI_FORMAT_R16G16B16A16_UNORM, INLINE_FLOOR_RECT},
{"post_resolve", DXGI_FORMAT_R16G16B16A16_UNORM, INLINE_FLOOR_RECT},
{"restore_blocks", DXGI_FORMAT_R32G32B32A32_FLOAT, {60, 34, 6, 3}, 120, 68},
{"post_restore", DXGI_FORMAT_R16G16B16A16_UNORM, INLINE_FLOOR_RECT}};
static constexpr InlinePlaneSpec tail_planes[]{
{"original", DXGI_FORMAT_R16G16B16A16_UNORM, INLINE_TAIL_RECT},
{"nr_model", DXGI_FORMAT_R16G16B16A16_FLOAT, INLINE_TAIL_RECT},
{"post_resolve", DXGI_FORMAT_R16G16B16A16_UNORM, INLINE_TAIL_RECT},
{"post_restore", DXGI_FORMAT_R16G16B16A16_UNORM, INLINE_TAIL_RECT},
{"depth", DXGI_FORMAT_R32_FLOAT, INLINE_TAIL_RECT}};
if (tail) return tail_planes;
return floor_planes;
}
#endif
struct HdrCapturePlan {
HdrCaptureMode mode = HdrCaptureMode::MODEL_TRACE;
CaptureRect roi;
bool sequence = false;
};
inline CaptureRect HdrPlaneRect(const HdrCapturePlan& plan, const char* name,
uint32_t full_width, uint32_t full_height) {
if (name == nullptr) return {};
const std::string_view plane(name);
if (plane == "hdr_block_statistics") {
if (!plan.sequence && plan.mode == HdrCaptureMode::COMMIT_CORE) {
return {.width = (full_width + 31) / 32, .height = (full_height + 31) / 32};
}
if (full_width == 0 || full_height == 0 || plan.roi.width == 0 || plan.roi.height == 0
|| static_cast<uint64_t>(plan.roi.x) + plan.roi.width > full_width
|| static_cast<uint64_t>(plan.roi.y) + plan.roi.height > full_height) return {};
const uint32_t grid_max_x = (full_width - 1) / 32;
const uint32_t grid_max_y = (full_height - 1) / 32;
// commit: block_pos=(pixel+0.5)/32-0.5, b0=clamp(floor(block_pos)), b1=min(b0+1).
// Preserve every loaded neighbour, including the zero-weight edge loads.
const uint32_t first_x = std::min(plan.roi.x >= 16 ? (plan.roi.x - 16) / 32 : 0, grid_max_x);
const uint32_t first_y = std::min(plan.roi.y >= 16 ? (plan.roi.y - 16) / 32 : 0, grid_max_y);
const uint32_t last_pixel_x = plan.roi.x + plan.roi.width - 1;
const uint32_t last_pixel_y = plan.roi.y + plan.roi.height - 1;
const uint32_t last_x = std::min((last_pixel_x >= 16 ? (last_pixel_x - 16) / 32 : 0) + 1, grid_max_x);
const uint32_t last_y = std::min((last_pixel_y >= 16 ? (last_pixel_y - 16) / 32 : 0) + 1, grid_max_y);
return {.x = first_x, .y = first_y, .width = last_x - first_x + 1, .height = last_y - first_y + 1};
}
if (!plan.sequence && plan.mode == HdrCaptureMode::COMMIT_CORE
&& (plane == "hdr_original_linear" || plane == "hdr_pre_commit"
|| plane == "hdr_post_pedestal_linear" || plane == "hdr_encoded_float"
|| plane == "packed_final")) {
return {.width = full_width, .height = full_height};
}
return plan.roi;
}
// Output files (dlssnr.hpp persists them; frozen when a request arms).
// NRScreenshotFormat: 0 PNG, 1 JPEG, 2 both. NRScreenshotLayout: 0 the
// pair, 1 the pair plus one side-by-side file (NR off | NR on) - one upload.
// NRScreenshotJpegQuality 80-100; NRScreenshotMaxMB caps each JPEG
// (0 = no cap; 10 is Discord's upload limit without Nitro).
enum class FileFormat : uint32_t { kPng = 0, kJpeg = 1, kPngAndJpeg = 2 };
inline std::atomic_uint32_t file_format = 0;
inline std::atomic_uint32_t layout = 0;
inline std::atomic_uint32_t jpeg_quality = 95;
inline std::atomic_uint32_t max_megabytes = 10;
inline constexpr bool HasSeparatePresentationContract(
uint32_t version, uint32_t provider, uint32_t host, uint32_t cadence) {
return version == 1u && provider == 0x444C3546u && host == 1u && cadence == 1u;
}
inline constexpr SourceMode ResolveSource(uint32_t mode, bool separate) {
return mode == static_cast<uint32_t>(SourceMode::kEvaluatedBuffer)
|| (mode == static_cast<uint32_t>(SourceMode::kAuto) && separate)
? SourceMode::kEvaluatedBuffer : SourceMode::kFinalPresent;
}
namespace internal {
// Fallback for queues without a tracked completion fence: presents that must
// pass after the copies were recorded before the readback buffers are
// mapped. Matches the retire-settle window the resource-release path uses;
// with fences the lease replaces this age rule.
constexpr uint64_t kSettlePresents = 4;
// Presents a capture with exact proofs waits for them before it gives up on
// delivery. The proof needs the recording list submitted, completed AND
// reset, and an engine resets a list only when its allocator comes round
// again (2-3 frames, 4 presents each under 4x frame generation). Giving up
// cancels the files only: the buffers stay retained until their own proof.
constexpr uint64_t kExactSettlePresents = 240;
// Written into every readback at creation; the copy overwrites it (its first
// row starts at offset 0). Still there when the worker reads the buffer =
// the GPU never ran the copy. As float data these are NaN payloads; as
// 8-bit data, four exact pixel values in sequence.
constexpr uint32_t kUnwrittenStamp[4] = {0x7FC0DEADu, 0x7FC0BEEFu, 0x7FC0CAFEu, 0x7FC0F00Du};
// Presents an armed capture may wait without a single DLSS evaluation before
// it disarms itself (~10 s at 60 fps). Without this, F5 pressed during a
// loading screen or with NR off fires much later on the first evaluate -
// typically a black frame the user cannot make sense of.
constexpr uint32_t kArmTimeoutPresents = 600;
constexpr char kLogPrefix[] = NR_NEXUS_NAME;
constexpr UINT64 MAX_STAGE_READBACK_BYTES = 512ull * 1024ull * 1024ull;
constexpr size_t MAX_STAGE_PLANES = 24;
// Cover delayed exact completion/recording retirement; byte budgets remain independent.
constexpr size_t MAX_HDR_IN_FLIGHT = 16;
constexpr uint64_t MAX_HDR_TEMPORARY_BYTES = 256ull * 1024 * 1024;
constexpr uint64_t MAX_HDR_CPU_EXPORT_BYTES = 8ull * 1024 * 1024;
inline std::atomic_uint64_t aggregate_bytes = 0;
inline std::atomic_uint64_t aggregate_peak_bytes = 0;
inline std::atomic_uint64_t readback_reserved_bytes = 0, readback_peak_bytes = 0;
inline std::atomic_uint64_t temporary_reserved_bytes = 0, temporary_peak_bytes = 0;
inline std::atomic_uint64_t cpu_reserved_bytes = 0, cpu_peak_bytes = 0;
inline std::atomic_uint32_t hdr_live_sets = 0;
struct CaptureReservation {
bool holds_hdr_slot = false;
uint64_t bytes = 0;
uint64_t temporary_bytes = 0, cpu_bytes = 0;
~CaptureReservation() {
readback_reserved_bytes.fetch_sub(bytes);
temporary_reserved_bytes.fetch_sub(temporary_bytes);
cpu_reserved_bytes.fetch_sub(cpu_bytes);
aggregate_bytes.fetch_sub(bytes + temporary_bytes + cpu_bytes);
if (holds_hdr_slot) hdr_live_sets.fetch_sub(1);
}
bool ReserveCategory(std::atomic_uint64_t* counter, std::atomic_uint64_t* peak_counter,
uint64_t limit, uint64_t amount) {
auto current = counter->load();
do {
if (amount > limit || current > limit - amount) return false;
} while (!counter->compare_exchange_weak(current, current + amount));
auto category_peak = peak_counter->load();
while (category_peak < current + amount && !peak_counter->compare_exchange_weak(category_peak, current + amount)) {}
const uint64_t total = aggregate_bytes.fetch_add(amount) + amount;
auto peak = aggregate_peak_bytes.load();
while (peak < total && !aggregate_peak_bytes.compare_exchange_weak(peak, total)) {}
return true;
}
bool Reserve(uint64_t amount) {
if (!ReserveCategory(&readback_reserved_bytes, &readback_peak_bytes, MAX_STAGE_READBACK_BYTES, amount)) return false;
bytes += amount; return true;
}
bool ReserveTemporary(uint64_t amount) {
if (!ReserveCategory(&temporary_reserved_bytes, &temporary_peak_bytes, MAX_HDR_TEMPORARY_BYTES, amount)) return false;
temporary_bytes += amount; return true;
}
bool ReserveCpu(uint64_t amount) {
if (!ReserveCategory(&cpu_reserved_bytes, &cpu_peak_bytes, MAX_HDR_CPU_EXPORT_BYTES, amount)) return false;
cpu_bytes += amount; return true;
}
};
// Raw float32 RGBA diagnostic planes captured alongside the PNG pair:
// the sRGB proxy the NR model actually sees, and the resolved linear work
// surface before the commit. PNGs cannot establish exposure/units; these
// dumps (plus the sidecar meta) can.
struct DiagnosticPlane {
std::string name;
ID3D12Resource* readback = nullptr;
uint32_t width = 0;
uint32_t height = 0;
D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{};
UINT64 total_bytes = 0;
DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN;
bool recorded = false;
std::string error;
GpuLease submission_proof;
CaptureRect source_rect;
CaptureRect copy_rect;
uint32_t source_width = 0, source_height = 0;
uint32_t full_width = 0, full_height = 0;
bool region_copy = false;
bool required = false;
bool explicitly_skipped = false;
uintptr_t source_identity = 0;
DXGI_FORMAT source_format = DXGI_FORMAT_UNKNOWN;
#if defined(NR_NEXUS_DEV_CONTROL)
std::pair<uint64_t, uint64_t> recording;
#endif
};
#if defined(NR_NEXUS_DEV_CONTROL)
struct InlineRestoreFrame {
InlineRestoreContext context;
std::pair<uint64_t, uint64_t> recording;
std::shared_ptr<submission::RecordingStatus> recording_status;
uint64_t bridge_submission = 0;
bool bridge_submitted = false, copyback_queued = false, sealed = false;
bool reduce_recorded = false, apply_recorded = false, reduce_unshaped = false;
uint32_t restore_mode = 0;
float gate = 0.f;
size_t first_plane = 0;
bool look_shaped = false, look_stability_recorded = false;
uint32_t look_width = 0, look_height = 0;
};
struct InlineRestoreCapture : InlineRestoreFrame {
std::filesystem::path output_directory;
std::string capture_id;
uint64_t request_id = 0;
uint64_t deadline_ms = 0;
uint32_t tail_frame_count = 0;
std::vector<InlineRestoreFrame> frames;
};
struct FgConsumerCapture {
std::filesystem::path output_directory;
std::string capture_id;
uint64_t deadline_ms = 0;
FgConsumerContext context;
std::pair<uint64_t, uint64_t> recording;
std::shared_ptr<submission::RecordingStatus> recording_status;
uintptr_t backbuffer_identity = 0, hudless_identity = 0, output_identity = 0;
DXGI_FORMAT backbuffer_format = DXGI_FORMAT_UNKNOWN;
uint32_t backbuffer_width = 0, backbuffer_height = 0;
DXGI_FORMAT output_format = DXGI_FORMAT_UNKNOWN;
uint32_t output_width = 0, output_height = 0;
std::array<D3D12_PLACED_SUBRESOURCE_FOOTPRINT, 2> output_footprints;
std::array<uint64_t, 2> output_plane_bytes{};
D3D12_PLACED_SUBRESOURCE_FOOTPRINT output_footprint{};
uint64_t output_bytes = 0;
bool input_hudless = false;
bool api_returned = false, api_succeeded = false;
uint32_t api_result = 0;
std::string reason;
};
inline std::span<const InlineRestoreFrame> InlineFrames(const InlineRestoreCapture& capture) {
if (capture.tail_frame_count != 0) return capture.frames;
return {&static_cast<const InlineRestoreFrame&>(capture), 1};
}
inline std::string InlinePlaneName(bool tail, const InlineRestoreFrame& frame, const char* name) {
if (!tail) return name;
return "f" + std::to_string(frame.context.evaluation_sequence) + "_" + name;
}
#endif
struct OutputOptions {
FileFormat format = FileFormat::kPng;
bool side_by_side = false;
uint32_t jpeg_quality = 95;
uint32_t max_megabytes = 10;
};
struct NativeReceiver {
std::shared_ptr<CaptureReservation> reservation;
ID3D11DeviceContext* context = nullptr;
ID3D11Texture2D* staging = nullptr;
ID3D11Texture2D* source = nullptr;
ID3D11Query* event = nullptr;
CaptureRect rect;
DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN;
uint64_t bytes = 0;
std::atomic_bool completed = false;
std::string error;
~NativeReceiver() {
if (event != nullptr) event->Release();
if (staging != nullptr) staging->Release();
if (source != nullptr) source->Release();
if (context != nullptr) context->Release();
}
bool Poll() {
if (completed) return true;
if (context == nullptr || event == nullptr) return false;
ID3D11Multithread* guard = nullptr;
context->QueryInterface(IID_PPV_ARGS(&guard));
if (guard != nullptr) guard->Enter();
BOOL done = FALSE;
const HRESULT result = context->GetData(event, &done, sizeof(done), D3D11_ASYNC_GETDATA_DONOTFLUSH);
if (guard != nullptr) { guard->Leave(); guard->Release(); }
completed = result == S_OK && done;
if (FAILED(result)) error = "native_receiver_query_failed";
return completed;
}
};
struct PreFgRole {
bool recorded = false;
bool model_evaluated = false;
uint32_t hdr_mode = 0;
uint32_t passes = 0;
uint32_t requested_passes = 0;
bool norm_scale_required = false;
uint64_t epoch = 0;
};
struct PendingCapture {
RequestKind request_kind = RequestKind::FINAL_PRESENTATION;
#if defined(NR_NEXUS_DEV_CONTROL)
std::optional<InlineRestoreCapture> inline_restore;
std::optional<InlineRestoreFrame> bridge_model_stages;
std::optional<FgConsumerCapture> fg_consumer;
#if defined(NR_NEXUS_TEST_XEFG_PRESENT_PROBE)
std::optional<XefgPresentCapture> xefg_present;
std::shared_ptr<xefg_present_probe::CopyPacket> xefg_copy;
#endif
#endif
uint64_t service_serial = 0;
uint64_t restore_config_epoch = 0;
bool service_sealed = false;
bool restoration_required = false;
bool restoration_verified = false;
uintptr_t restoration_original_identity = 0;
uintptr_t restoration_parameter_identity = 0;
PreFgRole backbuffer_role;
PreFgRole hudless_role;
bool hudless_present = false;
bool compose_attempted = false;
bool compose_used = false;
uint32_t compose_serial = 0;
uint64_t compose_area = 0;
uint32_t compose_mode = 0;
uint32_t compose_hud_limit = 0;
bool compose_residual = false;
bool compose_statistics_verified = false;
bool fg_inputs_verified = false;
std::optional<HdrCapturePlan> hdr_plan;
std::shared_ptr<CaptureReservation> reservation;
uint64_t temporary_bytes = 0;
uint64_t cpu_export_bytes = 0;
uint64_t cpu_row_bytes = 0;
bool required_planes_complete = true;
bool sequence_contract_validated = false;
std::shared_ptr<NativeReceiver> native_receiver;
bool native_receiver_required = false;
uint32_t full_width = 0, full_height = 0;
bool stage_planes = false;
std::vector<ID3D12Resource*> temporary_resources;
bool completion_proven = false;
bool metadata_only = false;
uint64_t completion_generation = 0;
UINT64 allocated_bytes = 0;
size_t rejected_planes = 0;
std::string rejection_meta;
bool model_diagnostic = false;
ID3D12GraphicsCommandList* model_recording_list = nullptr; // identity only
OutputOptions output;
ID3D12Resource* pre_nr_readback = nullptr;
ID3D12Resource* nr_output_readback = nullptr;
std::vector<DiagnosticPlane> planes;
std::string meta; // sidecar .meta.txt content (divisor, encoding, meter)
D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{};
UINT64 total_bytes = 0;
UINT row_pitch = 0;
// Captured subrect: engines can render into a subrect of a larger DLSS
// output resource; width/height are the CROP dimensions written to the PNG,
// while the footprint/row_pitch still describe the full resource rows.
uint32_t crop_x = 0;
uint32_t crop_y = 0;
uint32_t width = 0;
uint32_t height = 0;
DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN;
uint8_t hdr_mode = 0; // 0 = SDR, 1 = linear HDR, 2 = PQ HDR
float linear_unit_nits = 80.f; // scRGB: 1.0 is 80 nits, never scene exposure
uint64_t timestamp_ms = 0; // filename stem components; paths are only built
uint64_t serial = 0; // on the worker so Prepare never touches the fs
uint64_t creation_generation = 0; // present_generation when recorded
// The proof is chosen once, at the capture frame's first present
// (`lease_taken`, stamped `lease_generation`): `exact` when the queue hook
// is live, which settles on the tracker alone; otherwise the lease, taken
// then and empty when no queue fence exists, and a fence that never
// advances (present-starved session) settles on the bounded fallback.
GpuLease lease;
uint64_t lease_generation = 0;
bool lease_taken = false;
bool exact = false;
bool ready = false; // both copies have been recorded
bool aborted = false;
bool pre_recorded = false;
GpuLease pre_submission_proof;
GpuLease post_submission_proof;
};
// Counted degraded outcomes (telemetry screenshot[...]): captures cancelled
// on a timeout, captures refused because a copy never ran, and buffer sets
// retained for want of a proof (superseded, cancelled or refused).
inline std::atomic_uint64_t captures_cancelled = 0;
inline std::atomic_uint64_t captures_unexecuted = 0;
inline std::atomic_uint64_t retained_sets = 0;
inline std::atomic_bool capture_requested = false;
inline std::atomic<RequestKind> requested_kind = RequestKind::FINAL_PRESENTATION;
inline std::atomic<SourceMode> requested_source = SourceMode::kFinalPresent;
inline std::atomic_uint32_t capture_serial = 0;
inline std::atomic_bool shutdown_requested = false;
inline std::atomic_bool hotkey_was_down = false;
// Presents counted while armed without any evaluate having recorded a pair.
inline std::atomic_uint32_t presents_while_armed = 0;
inline std::atomic_bool requires_passthrough_frame = false;
inline std::atomic_uint64_t request_id = 0;
// The file settings as they stood when the request armed; state_mutex.
inline OutputOptions requested_output;
inline std::atomic_bool stage_busy = false;
inline std::atomic_bool worker_busy = false;
// pending is guarded by state_mutex; has_pending mirrors pending.has_value()
// so the idle present path stays a single atomic load.
inline std::mutex state_mutex;
inline std::optional<PendingCapture> pending;
#if defined(NR_NEXUS_DEV_CONTROL)
inline std::atomic_bool inline_restore_active = false;
inline std::atomic_uint64_t inline_restore_request_id = 0;
inline std::optional<InlineRestoreCapture> requested_inline_restore;
inline InlineRestoreStatus inline_restore_status;
inline std::optional<FgConsumerCapture> requested_fg_consumer;
inline FgConsumerStatus fg_consumer_status;
#if defined(NR_NEXUS_TEST_XEFG_PRESENT_PROBE)
inline std::optional<XefgCaptureRequest> xefg_request;
inline XefgCaptureStatus xefg_status;
inline bool xefg_recording_reserved = false, xefg_gate_owned = false;
#endif
#endif
inline std::optional<HdrCapturePlan> configured_hdr_plan;
inline std::deque<PendingCapture> hdr_in_flight;
enum class SequenceOutcome { ACCEPTED, DROPPED, INVALID, CANCELLED, RESIZE, WRITTEN };
struct SequenceFrame { uint64_t generation = 0; SequenceOutcome outcome = SequenceOutcome::DROPPED; };
struct SequenceState {
bool active = false;
uint64_t id = 0;
std::string contract_signature;
HdrCapturePlan plan;
uint64_t next_generation = 0;
uint32_t attempted = 0;
uint32_t full_width = 0, full_height = 0;
DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN;
std::array<SequenceFrame, 120> frames{};
};
inline SequenceState sequence;
inline std::atomic_bool has_pending = false;
// The last capture that ended, however it ended, and the files it wrote: the
// issue report (report_flow.hpp) bundles exactly these and states why a
// capture is missing. `outcome`: "written", "write_failed", "aborted",
// "not_ready", "gpu_unconfirmed" (a settle timeout cancelled it), "exception".
// finished_serial is the serial of `finished` and rises monotonically.
// Lock order: state_mutex -> finished_mutex; readers take finished_mutex alone.
struct FinishedCapture {
uint64_t serial = 0;
const char* outcome = "none";
bool model_diagnostic = false;
#if defined(NR_NEXUS_DEV_CONTROL)
std::string reason;
#endif
// The pair's lossless files when PNG was written, else its JPEGs.
std::filesystem::path pre_image, post_image, meta; // empty when not written
};
inline std::mutex finished_mutex;
inline FinishedCapture finished;
inline std::atomic_uint64_t finished_serial = 0;
inline void PublishFinished(FinishedCapture record) noexcept {
try {
std::scoped_lock lock(finished_mutex);
const uint64_t serial = record.serial;
if (serial < finished.serial) return;
finished = std::move(record);
finished_serial.store(serial, std::memory_order_release);
} catch (...) {
}
}
// Buffers from evaluates that were superseded within the same capture-frame
// (the capture re-records on every DLSS-family evaluate so the LAST one wins).
// They share the frame's command list, so they are released at the same settle
// window as the final capture rather than immediately. This owns the ENTIRE
// superseded buffer set - the PNG pair AND every diagnostic plane: replacing
// `pending` used to destroy the old planes vector without releasing its raw
// COM readback pointers, leaking every re-recorded plane (a 4K FP16 plane is
// ~63 MiB; v6 audit issue 13).
struct RetiredCaptureBuffers {
#if defined(NR_NEXUS_DEV_CONTROL) && defined(NR_NEXUS_TEST_XEFG_PRESENT_PROBE)
std::shared_ptr<xefg_present_probe::CopyPacket> xefg_copy;
#endif
std::shared_ptr<CaptureReservation> reservation;
std::shared_ptr<NativeReceiver> native_receiver;
std::vector<ID3D12Resource*> temporary_resources;
bool stage_planes = false;
ID3D12Resource* pre_nr_readback = nullptr;
ID3D12Resource* nr_output_readback = nullptr;
std::vector<DiagnosticPlane> planes;
void Release() {
if (pre_nr_readback != nullptr) pre_nr_readback->Release();
if (nr_output_readback != nullptr) nr_output_readback->Release();
for (DiagnosticPlane& plane : planes) {
if (plane.readback != nullptr) plane.readback->Release();
}
pre_nr_readback = nullptr;
nr_output_readback = nullptr;
planes.clear();
for (auto* resource : temporary_resources) resource->Release();
temporary_resources.clear();
reservation.reset();
native_receiver.reset();
#if defined(NR_NEXUS_DEV_CONTROL) && defined(NR_NEXUS_TEST_XEFG_PRESENT_PROBE)
xefg_copy.reset();
#endif
}
// Takes ownership of a cancelled PendingCapture's raw buffers for
// retention (unproven GPU completion: release happens on the set's own
// tracker proof, or without the queue hook behind the next proven settle,
// never on a timeout).
void Take(PendingCapture&& capture) {
reservation = std::move(capture.reservation);
native_receiver = std::move(capture.native_receiver);
#if defined(NR_NEXUS_DEV_CONTROL) && defined(NR_NEXUS_TEST_XEFG_PRESENT_PROBE)
xefg_copy = std::move(capture.xefg_copy);
#endif
temporary_resources = std::move(capture.temporary_resources);
stage_planes = capture.stage_planes;
pre_nr_readback = capture.pre_nr_readback;
nr_output_readback = capture.nr_output_readback;
planes = std::move(capture.planes);
capture.pre_nr_readback = nullptr;
capture.nr_output_readback = nullptr;
capture.planes.clear();
}
};
inline std::vector<RetiredCaptureBuffers> retired_buffers;
// Refused captures of a session without the queue hook: the GPU may still
// run their copies, so they are never released (worker-owned).
inline std::vector<RetiredCaptureBuffers> held_unexecuted;
// True when no recording that copies into one of the set's readbacks can
// still execute or replay (a PendingCapture or a RetiredCaptureBuffers).
template <typename Buffers>
inline bool ReadbacksReleasable(const Buffers& buffers) {
#if defined(NR_NEXUS_DEV_CONTROL) && defined(NR_NEXUS_TEST_XEFG_PRESENT_PROBE)
if (buffers.xefg_copy && !buffers.xefg_copy->IsRetired()) return false;
#endif
if (buffers.native_receiver && buffers.native_receiver->context != nullptr && !buffers.native_receiver->completed.load()) return false;
if (!submission::ResourceReleasable(buffers.pre_nr_readback)
|| !submission::ResourceReleasable(buffers.nr_output_readback)) {
return false;
}
for (const DiagnosticPlane& plane : buffers.planes) {
if (!submission::ResourceReleasable(plane.readback)) return false;
}
for (auto* resource : buffers.temporary_resources) {
if (!submission::ResourceReleasable(resource)) return false;
}
return true;
}
// Worker hand-off slot. Guarded by job_mutex; the worker moves the job out
// under the lock and processes it outside.
inline std::mutex job_mutex;
inline std::condition_variable job_signal;
inline std::optional<PendingCapture> job;
inline std::deque<PendingCapture> hdr_jobs;
inline std::atomic_uint32_t outstanding_jobs = 0;
inline std::atomic_bool worker_started = false;
#if defined(NR_NEXUS_DEV_CONTROL) && defined(NR_NEXUS_TEST_XEFG_PRESENT_PROBE)
inline std::atomic_bool xefg_control_pending = false;
// Caller holds state_mutex. A closed request releases only its own gate.
inline bool XefgDrainedLocked() {
return !xefg_recording_reserved && !pending && hdr_in_flight.empty() && !worker_busy.load()
&& outstanding_jobs.load() == 0 && retained_sets.load() == 0;
}
inline void ReleaseXefgGateIfDrained() {
std::scoped_lock lock(state_mutex);
if (xefg_gate_owned && !xefg_request && XefgDrainedLocked()) {
stage_busy.store(false);
xefg_gate_owned = false;
}
}
#endif
inline std::atomic_bool sequence_manifest_dirty = false;
inline std::atomic_bool sequence_manifest_busy = false;
inline std::atomic_bool sequence_manifest_failed = false;
// One coalescing mailbox, never a per-Present IO queue. Called with state_mutex held.
inline void QueueSequenceManifest() {
if (sequence.id == 0) return;
{
std::scoped_lock lock(job_mutex);
sequence_manifest_dirty.store(true);
}
job_signal.notify_one();
}
inline void SafeLog(reshade::log::level level, const std::string& message) {
if (shutdown_requested.load(std::memory_order_acquire)) return;
reshade::log::message(level, (std::string(kLogPrefix) + ": " + message).c_str());
}
// std::filesystem::path::string() throws for characters the ANSI code page
// cannot represent; logging must never throw.
inline std::string PathToLogString(const std::filesystem::path& path) {
try {
return path.string();
} catch (...) {
}
try {
const std::wstring wide = path.wstring();
std::string lossy;
lossy.reserve(wide.size());
for (wchar_t c : wide) lossy.push_back(static_cast<char>(c));
return lossy;
} catch (...) {
return "<unprintable path>";
}
}
inline void ReleaseReadbacks(PendingCapture& capture) {
if (capture.pre_nr_readback != nullptr) capture.pre_nr_readback->Release();
if (capture.nr_output_readback != nullptr) capture.nr_output_readback->Release();
capture.pre_nr_readback = nullptr;
capture.nr_output_readback = nullptr;
for (DiagnosticPlane& plane : capture.planes) {
if (plane.readback != nullptr) plane.readback->Release();
}
capture.planes.clear();
for (auto* resource : capture.temporary_resources) resource->Release();
capture.temporary_resources.clear();
capture.reservation.reset();
capture.native_receiver.reset();
#if defined(NR_NEXUS_DEV_CONTROL) && defined(NR_NEXUS_TEST_XEFG_PRESENT_PROBE)
capture.xefg_copy.reset();
#endif
}
// Shared readback-buffer allocator for the PNG pair and the float planes.
inline bool MakeReadbackBuffer(
ID3D12Device* device,
UINT64 bytes,
ID3D12Resource** result,
bool initialize_stamp = true) {
D3D12_HEAP_PROPERTIES heap{};
heap.Type = D3D12_HEAP_TYPE_READBACK;
D3D12_RESOURCE_DESC buffer{};
buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
buffer.Width = bytes;
buffer.Height = 1;
buffer.DepthOrArraySize = 1;
buffer.MipLevels = 1;
buffer.SampleDesc.Count = 1;
buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
if (FAILED(device->CreateCommittedResource(
&heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COPY_DEST,
nullptr, IID_PPV_ARGS(result)))) {
return false;
}
if (!initialize_stamp) return true;
// kUnwrittenStamp. A READBACK buffer maps for CPU writes too; nothing has
// been recorded against it yet.
const D3D12_RANGE nothing_read{0, 0};
void* mapped = nullptr;
if (SUCCEEDED((*result)->Map(0, ¬hing_read, &mapped)) && mapped != nullptr) {
const D3D12_RANGE written{
0, static_cast<SIZE_T>(std::min<UINT64>(sizeof(kUnwrittenStamp), bytes))};
std::memcpy(mapped, kUnwrittenStamp, written.End);
(*result)->Unmap(0, &written);
}
return true;
}
inline uint64_t ReadbackAllocationBytes(ID3D12Device* device, uint64_t bytes) {
D3D12_RESOURCE_DESC desc{};
desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
desc.Width = bytes; desc.Height = 1; desc.DepthOrArraySize = 1;
desc.MipLevels = 1; desc.SampleDesc.Count = 1; desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
return device->GetResourceAllocationInfo(0, 1, &desc).SizeInBytes;
}
// The stamp is intact: the copy into this mapped readback never ran.
inline bool Unwritten(const void* mapped, UINT64 bytes) {
return std::memcmp(mapped, kUnwrittenStamp,
static_cast<size_t>(std::min<UINT64>(sizeof(kUnwrittenStamp), bytes)))
== 0;
}
// ---------------------------------------------------------------------------
// PNG byte plumbing: chunks and a stored-block zlib stream. WIC compresses
// the image data (EncodeImageFiles); these write the chunks this module owns
// byte for byte, the iCCP profile, and the fallback PNG when WIC is absent.
inline void AppendPngBe32(std::vector<uint8_t>& bytes, uint32_t value) {
bytes.push_back(static_cast<uint8_t>((value >> 24) & 0xff));
bytes.push_back(static_cast<uint8_t>((value >> 16) & 0xff));
bytes.push_back(static_cast<uint8_t>((value >> 8) & 0xff));
bytes.push_back(static_cast<uint8_t>(value & 0xff));
}
inline uint32_t ReadBe32(const uint8_t* bytes) {
return (static_cast<uint32_t>(bytes[0]) << 24) | (static_cast<uint32_t>(bytes[1]) << 16)
| (static_cast<uint32_t>(bytes[2]) << 8) | bytes[3];
}
inline uint32_t PngCrc32(const uint8_t* data, size_t size) {
uint32_t crc = 0xffffffffu;
for (size_t i = 0; i < size; ++i) {
crc ^= data[i];
for (uint32_t bit = 0; bit < 8; ++bit)
crc = (crc >> 1) ^ (0xedb88320u & (-(crc & 1u)));
}
return ~crc;
}
inline uint32_t PngAdler32(const uint8_t* data, size_t size) {
uint32_t a = 1;
uint32_t b = 0;
for (size_t i = 0; i < size; ++i) {
a = (a + data[i]) % 65521u;
b = (b + a) % 65521u;
}
return (b << 16) | a;
}
inline void AppendPngChunk(
std::vector<uint8_t>& png,
const char type[4],
const std::vector<uint8_t>& payload) {
AppendPngBe32(png, static_cast<uint32_t>(payload.size()));
const size_t type_offset = png.size();
png.insert(png.end(), type, type + 4);
png.insert(png.end(), payload.begin(), payload.end());
AppendPngBe32(png, PngCrc32(png.data() + type_offset, 4 + payload.size()));
}
inline std::vector<uint8_t> ZlibStored(const uint8_t* data, size_t size) {
std::vector<uint8_t> zlib = {0x78, 0x01};
zlib.reserve(size + size / 65535 * 5 + 16);
size_t offset = 0;
do {
const size_t block_size = std::min<size_t>(65535, size - offset);
zlib.push_back(offset + block_size == size ? 1u : 0u);
const uint16_t length = static_cast<uint16_t>(block_size);
const uint16_t inverse = static_cast<uint16_t>(~length);
zlib.push_back(static_cast<uint8_t>(length & 0xff));
zlib.push_back(static_cast<uint8_t>(length >> 8));
zlib.push_back(static_cast<uint8_t>(inverse & 0xff));
zlib.push_back(static_cast<uint8_t>(inverse >> 8));
zlib.insert(zlib.end(), data + offset, data + offset + block_size);
offset += block_size;
} while (offset < size);
AppendPngBe32(zlib, PngAdler32(data, size));
return zlib;
}
// ---------------------------------------------------------------------------
// Readback decoding.
inline float HalfToFloat(uint16_t bits) {
const uint32_t sign = (bits & 0x8000u) << 16;
const uint32_t exponent = (bits >> 10) & 0x1fu;
const uint32_t mantissa = bits & 0x3ffu;
uint32_t value = 0;
if (exponent == 0) {
if (mantissa != 0) {
float result = std::ldexp(static_cast<float>(mantissa), -24);
return (sign != 0 ? -result : result);
}
value = sign;
} else if (exponent == 31) {
value = sign | 0x7f800000u | (mantissa << 13);
} else {
value = sign | ((exponent + (127 - 15)) << 23) | (mantissa << 13);
}
float result = 0.f;
std::memcpy(&result, &value, sizeof(result));
return result;
}
inline uint32_t DiagnosticPixelBytes(DXGI_FORMAT format) {
switch (format) {