Repository navigation
Expand file tree
/
Copy pathvulkan_path.hpp
More file actions
3700 lines (3600 loc) · 177 KB
/
Copy pathvulkan_path.hpp
File metadata and controls
3700 lines (3600 loc) · 177 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
*/
// Vulkan (v8.1): the NGX Vulkan exports, observed on the same module copies
// the D3D12 family detours. dlssnr.hpp includes this file twice: once at
// global scope for the declarations (the Vulkan types the NGX Vulkan header
// needs, then that header), and once inside renodx::addons::dlss5::internal,
// after the D3D11 and Present paths, for the body.
//
// Facts this file depends on (dumpbin /exports, 2026-09-25):
// - the driver's NGX core (_nvngx.dll, 616.56) and the DLSS plugins
// (nvngx_dlss.dll, nvngx_dlssd.dll 310.x) export
// NVSDK_NGX_VULKAN_CreateFeature, _CreateFeature1, _EvaluateFeature and
// _ReleaseFeature. NONE exports NVSDK_NGX_VULKAN_EvaluateFeature_C: the
// SDK's static library implements it on top of _EvaluateFeature, so the
// four detours below see every Vulkan evaluate;
// - the signed NR runtime (nvngx_dlssnr.dll 310.8) exports a real Vulkan
// path: NVSDK_NGX_VULKAN_Init_Ext/_Init_Ext2, _CreateFeature/1,
// _EvaluateFeature, _ReleaseFeature and the Vulkan requirement queries,
// and launches its kernels through VK_NVX_binary_import. Only
// NVSDK_NGX_VULKAN_Init shares the stub every *_Init export has (RVA
// 0x13F50, FAIL_FeatureNotSupported);
// - NR's Vulkan Init and extension query need the VkInstance and
// VkPhysicalDevice, which ReShade's add-on API does not expose. Capture
// them at Vulkan device creation as well as from NGX Init: NGX may Init
// before its module is loaded and before the NGX detours can be attached.
#ifndef RENODX_DLSS5_VULKAN_DECLS
#define RENODX_DLSS5_VULKAN_DECLS
// The subset of vulkan_core.h (Vulkan SDK 1.4.350) the NGX Vulkan header
// and this file use, copied verbatim; the addon has no Vulkan SDK include
// path, and nvsdk_ngx_defs_vk.h expects the types to be declared already.
#ifndef VULKAN_CORE_H_
#define VULKAN_CORE_H_ 1
#define VKAPI_CALL __stdcall
#define VKAPI_PTR VKAPI_CALL
#define VK_DEFINE_HANDLE(object) typedef struct object##_T* object;
#define VK_DEFINE_NON_DISPATCHABLE_HANDLE(object) typedef struct object##_T* object;
#define VK_MAX_EXTENSION_NAME_SIZE 256U
VK_DEFINE_HANDLE(VkInstance)
VK_DEFINE_HANDLE(VkPhysicalDevice)
VK_DEFINE_HANDLE(VkDevice)
VK_DEFINE_HANDLE(VkCommandBuffer)
VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkBuffer)
VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkImage)
VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkImageView)
VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkEvent)
typedef uint32_t VkFlags;
typedef VkFlags VkImageAspectFlags;
typedef VkFlags VkImageUsageFlags;
typedef VkFlags VkBufferUsageFlags;
typedef VkFlags VkAccessFlags;
typedef VkFlags VkPipelineStageFlags;
typedef VkFlags VkDependencyFlags;
typedef int32_t VkStructureType;
typedef int32_t VkImageLayout;
typedef struct VkMemoryBarrier {
VkStructureType sType;
const void* pNext;
VkAccessFlags srcAccessMask;
VkAccessFlags dstAccessMask;
} VkMemoryBarrier;
typedef struct VkBufferMemoryBarrier {
VkStructureType sType;
const void* pNext;
VkAccessFlags srcAccessMask;
VkAccessFlags dstAccessMask;
uint32_t srcQueueFamilyIndex;
uint32_t dstQueueFamilyIndex;
VkBuffer buffer;
uint64_t offset;
uint64_t size;
} VkBufferMemoryBarrier;
typedef enum VkFormat {
VK_FORMAT_UNDEFINED = 0,
VK_FORMAT_R8G8B8A8_UNORM = 37,
VK_FORMAT_R16_SFLOAT = 76,
VK_FORMAT_R16G16_UNORM = 77,
VK_FORMAT_R16G16_SNORM = 78,
VK_FORMAT_R16G16_SFLOAT = 83,
VK_FORMAT_R16G16B16A16_SFLOAT = 97,
VK_FORMAT_R32_SFLOAT = 100,
VK_FORMAT_R32G32_SFLOAT = 103,
VK_FORMAT_R32G32B32A32_SFLOAT = 109,
VK_FORMAT_B10G11R11_UFLOAT_PACK32 = 122,
VK_FORMAT_D16_UNORM = 124,
VK_FORMAT_X8_D24_UNORM_PACK32 = 125,
VK_FORMAT_D32_SFLOAT = 126,
VK_FORMAT_D16_UNORM_S8_UINT = 128,
VK_FORMAT_D24_UNORM_S8_UINT = 129,
VK_FORMAT_D32_SFLOAT_S8_UINT = 130,
VK_FORMAT_MAX_ENUM = 0x7FFFFFFF
} VkFormat;
typedef enum VkImageAspectFlagBits {
VK_IMAGE_ASPECT_COLOR_BIT = 0x00000001,
VK_IMAGE_ASPECT_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
} VkImageAspectFlagBits;
typedef struct VkImageSubresourceRange {
VkImageAspectFlags aspectMask;
uint32_t baseMipLevel;
uint32_t levelCount;
uint32_t baseArrayLayer;
uint32_t layerCount;
} VkImageSubresourceRange;
typedef struct VkImageMemoryBarrier {
VkStructureType sType;
const void* pNext;
VkAccessFlags srcAccessMask;
VkAccessFlags dstAccessMask;
VkImageLayout oldLayout;
VkImageLayout newLayout;
uint32_t srcQueueFamilyIndex;
uint32_t dstQueueFamilyIndex;
VkImage image;
VkImageSubresourceRange subresourceRange;
} VkImageMemoryBarrier;
typedef struct VkImageMemoryBarrier2 {
VkStructureType sType;
const void* pNext;
uint64_t srcStageMask;
uint64_t srcAccessMask;
uint64_t dstStageMask;
uint64_t dstAccessMask;
VkImageLayout oldLayout;
VkImageLayout newLayout;
uint32_t srcQueueFamilyIndex;
uint32_t dstQueueFamilyIndex;
VkImage image;
VkImageSubresourceRange subresourceRange;
} VkImageMemoryBarrier2;
struct VkMemoryBarrier2;
struct VkBufferMemoryBarrier2;
typedef struct VkDependencyInfo {
VkStructureType sType;
const void* pNext;
VkDependencyFlags dependencyFlags;
uint32_t memoryBarrierCount;
const VkMemoryBarrier2* pMemoryBarriers;
uint32_t bufferMemoryBarrierCount;
const VkBufferMemoryBarrier2* pBufferMemoryBarriers;
uint32_t imageMemoryBarrierCount;
const VkImageMemoryBarrier2* pImageMemoryBarriers;
} VkDependencyInfo;
typedef void(VKAPI_PTR* PFN_vkCmdPipelineBarrier)(
VkCommandBuffer, VkPipelineStageFlags, VkPipelineStageFlags, VkDependencyFlags,
uint32_t, const VkMemoryBarrier*, uint32_t, const VkBufferMemoryBarrier*,
uint32_t, const VkImageMemoryBarrier*);
typedef void(VKAPI_PTR* PFN_vkCmdPipelineBarrier2)(VkCommandBuffer, const VkDependencyInfo*);
typedef void(VKAPI_PTR* PFN_vkCmdWaitEvents)(
VkCommandBuffer, uint32_t, const VkEvent*, VkPipelineStageFlags, VkPipelineStageFlags,
uint32_t, const VkMemoryBarrier*, uint32_t, const VkBufferMemoryBarrier*,
uint32_t, const VkImageMemoryBarrier*);
typedef void(VKAPI_PTR* PFN_vkCmdWaitEvents2)(
VkCommandBuffer, uint32_t, const VkEvent*, const VkDependencyInfo*);
typedef struct VkExtensionProperties {
char extensionName[VK_MAX_EXTENSION_NAME_SIZE];
uint32_t specVersion;
} VkExtensionProperties;
typedef void(VKAPI_PTR* PFN_vkVoidFunction)(void);
typedef PFN_vkVoidFunction(VKAPI_PTR* PFN_vkGetInstanceProcAddr)(VkInstance instance,
const char* pName);
typedef PFN_vkVoidFunction(VKAPI_PTR* PFN_vkGetDeviceProcAddr)(VkDevice device,
const char* pName);
#endif // VULKAN_CORE_H_
#include <nvsdk_ngx_vk.h>
#elif !defined(RENODX_DLSS5_VULKAN_BODY)
#define RENODX_DLSS5_VULKAN_BODY
namespace vk {
// ---------------------------------------------------------------------------
// Storage
// ---------------------------------------------------------------------------
// The device whose DLSS evaluate first arms NR. Auxiliary Vulkan device
// initialization must not replace the owner of live runtime/codec objects.
inline std::atomic<VkDevice> game_device{nullptr};
inline std::atomic<reshade::api::device*> game_api_device{nullptr};
// The game's NGX Vulkan Init or requirement query, where NR's own Init and
// the extension check get the instance and physical device from.
inline std::atomic<VkInstance> game_instance{nullptr};
inline std::atomic<VkPhysicalDevice> game_physical_device{nullptr};
inline std::atomic<VkDevice> game_init_device{nullptr};
inline std::mutex context_mutex;
inline std::unordered_map<void*, VkInstance> instances_by_dispatch;
inline std::unordered_map<VkDevice, std::pair<VkInstance, VkPhysicalDevice>> device_contexts;
inline std::unordered_map<VkDevice, reshade::api::device*> api_devices;
struct CommandList {
reshade::api::command_list* list;
reshade::api::device* device;
};
inline std::shared_mutex command_lists_mutex;
inline std::unordered_map<VkCommandBuffer, CommandList> command_lists;
// A command buffer may be submitted again until it is begun anew or freed.
// vkBeginCommandBuffer and destruction are the only proofs available here
// that an old recording cannot use an add-on object again.
inline std::mutex recorded_uses_mutex;
inline std::unordered_map<reshade::api::command_list*, std::vector<uint64_t>> recorded_uses;
inline std::unordered_map<uint64_t, uint32_t> live_recorded_uses;
inline uint64_t next_use_id = 1; // assigned under runtime_mutex
inline void TrackRecordedUse(reshade::api::command_list* list, uint64_t id) {
if (id == 0) return;
std::lock_guard lock(recorded_uses_mutex);
auto& uses = recorded_uses[list];
if (std::find(uses.begin(), uses.end(), id) != uses.end()) return;
uses.push_back(id);
++live_recorded_uses[id];
}
inline void ForgetRecordedUses(reshade::api::command_list* list) {
std::lock_guard lock(recorded_uses_mutex);
const auto found = recorded_uses.find(list);
if (found == recorded_uses.end()) return;
for (const uint64_t id : found->second) {
const auto use = live_recorded_uses.find(id);
if (use != live_recorded_uses.end() && --use->second == 0) {
live_recorded_uses.erase(use);
}
}
recorded_uses.erase(found);
}
inline bool RecordedUseComplete(uint64_t id) {
if (id == 0) return true;
std::lock_guard lock(recorded_uses_mutex);
return live_recorded_uses.find(id) == live_recorded_uses.end();
}
inline constexpr VkImageLayout kLayoutUndefined = static_cast<VkImageLayout>(0);
inline constexpr VkImageLayout kLayoutGeneral = static_cast<VkImageLayout>(1);
inline constexpr VkImageLayout kLayoutReadOnly = static_cast<VkImageLayout>(5);
inline constexpr VkImageLayout kLayoutReadOnlyOptimal = static_cast<VkImageLayout>(1000314000);
// Loader dispatch, never a first-device vkGetDeviceProcAddr function:
// injection must keep dispatching to the command buffer's current device.
inline std::atomic<PFN_vkCmdPipelineBarrier> native_barrier{nullptr};
inline PFN_vkCmdPipelineBarrier real_barrier = nullptr;
inline PFN_vkCmdPipelineBarrier2 real_barrier2 = nullptr;
inline PFN_vkCmdPipelineBarrier2 real_barrier2_khr = nullptr;
inline PFN_vkCmdWaitEvents real_wait_events = nullptr;
inline PFN_vkCmdWaitEvents2 real_wait_events2 = nullptr;
inline PFN_vkCmdWaitEvents2 real_wait_events2_khr = nullptr;
inline detour_guard::Record barrier_records[6];
inline std::mutex barrier_install_mutex;
inline std::atomic_bool barrier_install_attempted{false};
inline bool barrier_install_warned = false; // barrier_install_mutex
inline std::atomic_uint32_t barrier_observers_resolved{0};
inline std::atomic_uint32_t barrier_observers_attached{0};
inline std::atomic_bool layout_observation_complete{false};
// One slot per detoured module copy, as the D3D12 and D3D11 families have.
// The four entries share NgxSlotGuard's four records in this order.
struct Real {
void* create = nullptr;
void* create1 = nullptr;
void* evaluate = nullptr;
void* release = nullptr;
};
inline Real slot_real[kMaxNgxSlots];
inline bool slot_used[kMaxNgxSlots] = {};
inline HMODULE slot_module[kMaxNgxSlots] = {};
inline std::atomic_bool slot_noncore[kMaxNgxSlots] = {};
inline NgxSlotGuard slot_guard[kMaxNgxSlots];
inline std::unordered_set<HMODULE> refused_modules;
inline std::unordered_map<HMODULE, NgxHookRetry> failed_modules;
// Copies without a Vulkan evaluate export, checked once per image.
inline std::unordered_map<HMODULE, uint64_t> absent_modules;
inline std::atomic_bool ngx_any_hooked{false};
// Latched for the funnel (ngx_hooked, list_hooks_live) and the telemetry gate.
inline std::atomic_bool ngx_ever_hooked{false};
inline thread_local uint32_t call_depth = 0;
// Entry tallies, the first statement of every wrapper: installed is not
// entered. The one-shot "entered" lines are the log's witness of the same.
enum Entry : uint32_t { kCreate, kCreate1, kEvaluate, kRelease, kInit, kShutdown, kEntryCount };
inline constexpr const char* kEntryNames[kEntryCount] = {
"CreateFeature", "CreateFeature1", "EvaluateFeature", "ReleaseFeature", "Init", "Shutdown"};
inline std::atomic_uint64_t entered[kEntryCount] = {};
inline std::atomic_uint32_t logged_entries{0};
inline void Enter(Entry entry) {
entered[entry].fetch_add(1, std::memory_order_relaxed);
if ((logged_entries.fetch_or(1u << entry, std::memory_order_relaxed) & (1u << entry)) == 0) {
Log(reshade::log::level::info,
std::string("Vulkan NGX hook entered: ") + kEntryNames[entry]);
}
}
// NR's scratch images for one output of one game DLSS feature, at the
// output's size (NR runs 1:1 on Vulkan). Created on first use
// (EnsureSurface) and tracked per surface (`state`, ReShade usages), so a
// surface a setting adds mid-stream starts from VK_IMAGE_LAYOUT_UNDEFINED
// while the others keep their layouts. As D3D12's FinalResources:
// - original / proxy / neural: the copied output, NR's input and output;
// - work0 / work_a / work_b (v6 HDR): the linear source and the resolve
// ping-pong of a pass stack; scale the 1x1 same-frame divisor texel,
// block_mean the 32x32 pedestal means;
// - stack0 / stack1 (legacy SDR): the display-encoded ping-pong of a pass
// stack (the last pass writes the output itself);
// - look_output and the four half-resolution bands: the look stage's N'
// and its band surfaces (look_stage.hpp); look_scratch the 1x1 history
// texel a compose without the temporal filter binds (never read).
enum Surface : uint32_t {
kOriginal,
kProxy,
kNeural,
kWork0,
kWorkA,
kWorkB,
kScale,
kBlockMean,
kStack0,
kStack1,
kLookOutput,
kBandA,
kBandB,
kBandMaxA,
kBandMaxB,
kLookScratch,
kControlMask,
kSurfaceCount,
};
struct Workset {
VkImage output = nullptr;
uint32_t width = 0;
uint32_t height = 0;
reshade::api::format output_format = reshade::api::format::unknown;
reshade::api::resource images[kSurfaceCount] = {};
reshade::api::resource_view views[kSurfaceCount] = {};
reshade::api::resource_usage state[kSurfaceCount] = {};
// What the shared v6 policy reads (FrameDisplayCodec, FrameCodecDivisor,
// MakeV6Constants, ...): the same two fields D3D12's FinalResources has.
uint8_t hdr_mode = 0;
codec::SourceUnits units;
uint64_t snaps = 0;
// The feed guard's per-workset key (norm_trace::guard_probe).
uint32_t id = 0;
uint64_t use_id = 0;
uint64_t last_used = 0;
};
inline uint32_t next_workset_id = 0;
inline uint64_t next_workset_use = 1;
// One half of a pass's look history: an RGBA32_UINT storage image at the NR
// size, in GENERAL for its whole life (look_common.hlsli says why an image).
struct LookHistoryImage {
reshade::api::resource image = {};
reshade::api::resource_view view = {};
};
struct RetiredLookHistory {
LookHistoryImage buffers[2];
uint64_t use_id = 0;
};
struct RetiredNrHandle {
NVSDK_NGX_Handle* handle = nullptr;
NVSDK_NGX_Parameter* parameters = nullptr;
uint64_t use_id = 0;
};
using LookHistoryVk = BasicLookHistory<LookHistoryImage>;
// The game's Vulkan NGX features: feature id and create flags per handle,
// and for a DLSS/DLSSD feature the NR state that rides its evaluates.
struct Feature {
NVSDK_NGX_Feature id = NVSDK_NGX_Feature_Reserved_Unknown;
uint32_t create_flags = 0;
reshade::api::device* device = nullptr;
std::vector<Workset> worksets;
std::vector<Workset> retired_worksets;
// NR feature 18 per stack pass (NRPasses), created at the output size
// below; a size change retires the old handles into `retired_nr`.
NrFeatureSlot slots[kMaxNrPasses];
uint32_t nr_width = 0;
uint32_t nr_height = 0;
uint8_t nr_hdr_mode = 0;
uint64_t configuration = 0;
std::vector<RetiredNrHandle> retired_nr;
uint64_t nr_use[kMaxNrPasses] = {};
// Each pass's look history (the D3D12 slot's look_history). Replaced pairs
// wait until every command buffer that recorded them is reset or freed.
LookHistoryVk look_history[kMaxNrPasses];
std::vector<RetiredLookHistory> retired_history;
uint64_t look_history_use[kMaxNrPasses] = {};
// The stream's v6 state, as D3D12 keeps it per game feature: `ngx` carries
// the feed decision (SelectFeed) and the governor's NormStream (ngx.norm);
// `commit` is the stream's committed divisor texel, shared by all of its
// worksets like D3D12's NormStream::commit, cleared once when created.
FeatureState ngx;
reshade::api::resource commit = {};
reshade::api::resource_view commit_view = {};
bool commit_cleared = false;
};
inline std::unordered_map<const NVSDK_NGX_Handle*, Feature> features;
inline uint64_t source_generation = 0; // runtime_mutex
// A Vulkan command buffer may be begun again or freed only when it is not
// pending. That lifecycle event is the completion/discard proof for its
// readback copies; elapsed frames and a changed sentinel are not GPU fences.
// Pending slots are never read or overwritten. The sentinel distinguishes
// a completed copy from an abandoned recording only AFTER that proof.
struct ScaleSample {
bool recorded = false;
bool guarded = false;
uint32_t workset = 0;
reshade::api::command_list* recording = nullptr;
bool retired = false;
};
inline std::mutex scale_samples_mutex;
inline reshade::api::resource scale_readback = {};
inline float* scale_mapped = nullptr;
inline ScaleSample scale_samples[norm_trace::guard_probe::kSlots];
inline uint32_t scale_head = 0;
inline uint64_t scale_calls = 0;
inline std::atomic<float> divisor_last{0.f};
inline std::atomic_uint64_t divisor_reads{0};
inline std::atomic_uint64_t divisor_lost{0};
inline void RetireScaleSamples(reshade::api::command_list* cmd_list) {
std::lock_guard lock(scale_samples_mutex);
for (ScaleSample& sample : scale_samples) {
if (sample.recorded && sample.recording == cmd_list) sample.retired = true;
}
}
inline std::atomic_uint64_t dlss_evaluates{0};
inline std::atomic_uint64_t owner_mismatches{0};
// NRHookPoint=Present on Vulkan: evaluates served at the Upscaled hook point
// instead (PresentHookServes is false in a Vulkan session).
inline std::atomic_uint64_t present_fallback{0};
// The evaluates a DX11 bridge add-on re-issues on Direct3D 12 pass through
// (HookedEvaluate) while that path runs NR; the first 4 changes are logged.
// nr_off_seen_ns: SteadyNowNs of the last evaluate here with NR switched
// off, which restarts the grace window a re-enabled D3D12 path warms up in.
inline std::atomic_bool bridge_yielding{false};
inline std::atomic_uint32_t bridge_yield_changes{0};
inline std::atomic_int64_t nr_off_seen_ns{0};
// The NR runtime's device-extension requirement for feature 18 against the
// game's device: 0 unchecked, 1 satisfied or not checkable, 2 missing.
inline std::atomic_uint8_t extension_state{0};
// ---------------------------------------------------------------------------
// The game's NGX Vulkan Init and requirement queries (instance capture)
// ---------------------------------------------------------------------------
using InitFn = NVSDK_NGX_Result(NVSDK_CONV*)(
unsigned long long, const wchar_t*, VkInstance, VkPhysicalDevice, VkDevice,
NVSDK_NGX_Version);
using InitExtFn = NVSDK_NGX_Result(NVSDK_CONV*)(
unsigned long long, const wchar_t*, VkInstance, VkPhysicalDevice, VkDevice,
NVSDK_NGX_Version, const NVSDK_NGX_Parameter*);
using InitExt2Fn = NVSDK_NGX_Result(NVSDK_CONV*)(
unsigned long long, const wchar_t*, VkInstance, VkPhysicalDevice, VkDevice,
PFN_vkGetInstanceProcAddr, PFN_vkGetDeviceProcAddr, NVSDK_NGX_Version,
const NVSDK_NGX_Parameter*);
// The exported ABI is nvsdk_ngx_vk.h's NGX_SNIPPET_BUILD block (the C
// declarations, copied above): what NGX modules export, which differs from
// the application-side Init the SDK's static library implements. That block
// is compiled out of an application build, hence the local types.
//
// The core's NVSDK_NGX_VULKAN_Init_ProjectID and _Init_ProjectID_Ext exports
// have no header declaration. The SDK's static library
// (nvsdk_ngx_s.lib, NVSDK_NGX_VULKAN_Init_with_ProjectID, dumpbin /disasm
// 2026-09-25) calls _Init_ProjectID_Ext when the core exports it, else
// _Init_ProjectID when the application passed no vkGet*ProcAddr, with these
// arguments in this order (the header's Init_with_ProjectID arguments, with
// the SDK version moved before the feature info):
// _Ext: ProjectId, EngineType, EngineVersion, DataPath, Instance, PD,
// Device, GIPA, GDPA, SDKVersion, FeatureInfo
// base: ProjectId, EngineType, EngineVersion, DataPath, Instance, PD,
// Device, SDKVersion, FeatureInfo
// Every application that initializes NGX by project id (Streamline titles
// among them) reaches the core through one of the two.
using InitProjectFn = NVSDK_NGX_Result(NVSDK_CONV*)(
const char*, NVSDK_NGX_EngineType, const char*, const wchar_t*, VkInstance,
VkPhysicalDevice, VkDevice, NVSDK_NGX_Version, const NVSDK_NGX_FeatureCommonInfo*);
using InitProjectExtFn = NVSDK_NGX_Result(NVSDK_CONV*)(
const char*, NVSDK_NGX_EngineType, const char*, const wchar_t*, VkInstance,
VkPhysicalDevice, VkDevice, PFN_vkGetInstanceProcAddr, PFN_vkGetDeviceProcAddr,
NVSDK_NGX_Version, const NVSDK_NGX_FeatureCommonInfo*);
using RequirementsFn = decltype(&NVSDK_NGX_VULKAN_GetFeatureRequirements);
inline InitFn real_init = nullptr;
inline InitExtFn real_init_ext = nullptr;
inline InitExt2Fn real_init_ext2 = nullptr;
inline InitProjectFn real_init_project = nullptr;
inline InitProjectExtFn real_init_project_ext = nullptr;
inline RequirementsFn real_requirements = nullptr;
// nvsdk_ngx_vk.h declares _Shutdown(void) only under
// NGX_ENABLE_DEPRECATED_SHUTDOWN; the core still exports it.
using ShutdownVoidFn = NVSDK_NGX_Result(NVSDK_CONV*)();
using ShutdownDeviceFn = decltype(&NVSDK_NGX_VULKAN_Shutdown1);
inline ShutdownVoidFn real_shutdown = nullptr;
inline ShutdownDeviceFn real_shutdown1 = nullptr;
inline detour_guard::Record init_records[8];
inline HMODULE init_hooked_core = nullptr;
inline uint64_t init_hooked_image = 0;
inline void NoteInstance(VkInstance instance, VkPhysicalDevice physical, VkDevice device) {
if (instance == nullptr || physical == nullptr) return;
const bool first = game_instance.exchange(instance, std::memory_order_relaxed) == nullptr;
game_physical_device.store(physical, std::memory_order_relaxed);
if (device != nullptr) {
game_init_device.store(device, std::memory_order_relaxed);
std::lock_guard lock(context_mutex);
device_contexts[device] = {instance, physical};
}
if (first) {
Log(reshade::log::level::info,
"Vulkan instance and physical device captured for NR's own Vulkan Init");
}
}
// ReShade loads add-ons inside vkCreateInstance, before returning the first
// instance. Its public device API exposes VkDevice but not its instance or
// physical device. The layer's proc lookup sees the instance after creation;
// its vkCreateDevice sees the matching physical device. ReShade itself pairs
// them by the loader dispatch key, so the same association works even when a
// game creates more than one Vulkan instance/device (RDR2 does).
inline PFN_vkGetInstanceProcAddr real_layer_gipa = nullptr;
// The add-on intentionally declares only the Vulkan ABI it needs, to avoid
// pulling a second Vulkan header in beside the NGX SDK's declarations.
using LayerCreateDeviceFn = int32_t(VKAPI_PTR*)(
VkPhysicalDevice, const void*, const void*, VkDevice*);
inline LayerCreateDeviceFn real_layer_create_device = nullptr;
inline detour_guard::Record context_records[2];
inline bool context_hooks_installed = false;
inline PFN_vkVoidFunction VKAPI_CALL HookedLayerGipa(VkInstance instance, const char* name) {
if (instance != nullptr) {
std::lock_guard lock(context_mutex);
instances_by_dispatch[*reinterpret_cast<void**>(instance)] = instance;
}
return real_layer_gipa(instance, name);
}
inline int32_t VKAPI_CALL HookedLayerCreateDevice(
VkPhysicalDevice physical, const void* info, const void* allocator, VkDevice* out) {
VkInstance instance = nullptr;
if (physical != nullptr) {
std::lock_guard lock(context_mutex);
if (const auto found = instances_by_dispatch.find(*reinterpret_cast<void**>(physical));
found != instances_by_dispatch.end()) {
instance = found->second;
}
}
const int32_t result = real_layer_create_device(physical, info, allocator, out);
if (result >= 0 && out != nullptr && *out != nullptr && instance != nullptr) {
NoteInstance(instance, physical, *out);
static std::atomic_bool logged{false};
if (!logged.exchange(true)) {
Log(reshade::log::level::info,
"Vulkan device creation supplied NR context independently of NGX Init");
}
}
return result;
}
inline const detour_guard::Hook kContextHooks[] = {
{"vkGetInstanceProcAddr", reinterpret_cast<void**>(&real_layer_gipa),
reinterpret_cast<void*>(&HookedLayerGipa), &context_records[0]},
{"vkCreateDevice", reinterpret_cast<void**>(&real_layer_create_device),
reinterpret_cast<void*>(&HookedLayerCreateDevice), &context_records[1]},
};
inline void InstallContextHooks() {
if (context_hooks_installed || !hooks_enabled.load(std::memory_order_relaxed)) return;
const HMODULE layer = reshade::internal::get_reshade_module_handle();
const auto gipa = layer != nullptr
? reinterpret_cast<PFN_vkGetInstanceProcAddr>(
GetProcAddress(layer, "vkGetInstanceProcAddr"))
: nullptr;
if (gipa == nullptr) return;
real_layer_gipa = gipa;
real_layer_create_device = reinterpret_cast<LayerCreateDeviceFn>(
gipa(nullptr, "vkCreateDevice"));
if (real_layer_create_device == nullptr) return;
size_t failed = 0;
const size_t attached = detour_guard::AttachAll(kContextHooks, &failed);
if (attached != std::size(kContextHooks)) {
for (const detour_guard::Hook& hook : kContextHooks) {
if (hook.record->target != nullptr) NoteDetourRemoval(detour_guard::Detach(hook));
}
Log(reshade::log::level::warning,
"Vulkan device context hooks unavailable; NGX Init observation remains the fallback");
return;
}
context_hooks_installed = true;
}
inline std::pair<VkInstance, VkPhysicalDevice> ContextFor(VkDevice device) {
std::lock_guard lock(context_mutex);
if (const auto found = device_contexts.find(device); found != device_contexts.end()) {
return found->second;
}
// A legacy NGX Init observation is a fallback for that exact device only;
// a recreated device must not inherit another device's instance contract.
if (game_init_device.load(std::memory_order_relaxed) == device) {
return {game_instance.load(std::memory_order_relaxed),
game_physical_device.load(std::memory_order_relaxed)};
}
return {nullptr, nullptr};
}
inline NVSDK_NGX_Result NVSDK_CONV HookedInit(
unsigned long long id, const wchar_t* path, VkInstance instance,
VkPhysicalDevice physical, VkDevice device, NVSDK_NGX_Version version) {
Enter(kInit);
if (!InsideDirectCall()) NoteInstance(instance, physical, device);
return real_init(id, path, instance, physical, device, version);
}
inline NVSDK_NGX_Result NVSDK_CONV HookedInitExt(
unsigned long long id, const wchar_t* path, VkInstance instance,
VkPhysicalDevice physical, VkDevice device, NVSDK_NGX_Version version,
const NVSDK_NGX_Parameter* parameters) {
Enter(kInit);
if (!InsideDirectCall()) NoteInstance(instance, physical, device);
return real_init_ext(id, path, instance, physical, device, version, parameters);
}
inline NVSDK_NGX_Result NVSDK_CONV HookedInitExt2(
unsigned long long id, const wchar_t* path, VkInstance instance,
VkPhysicalDevice physical, VkDevice device, PFN_vkGetInstanceProcAddr gipa,
PFN_vkGetDeviceProcAddr gdpa, NVSDK_NGX_Version version,
const NVSDK_NGX_Parameter* parameters) {
Enter(kInit);
if (!InsideDirectCall()) NoteInstance(instance, physical, device);
return real_init_ext2(id, path, instance, physical, device, gipa, gdpa, version,
parameters);
}
inline NVSDK_NGX_Result NVSDK_CONV HookedInitProject(
const char* project, NVSDK_NGX_EngineType engine, const char* engine_version,
const wchar_t* path, VkInstance instance, VkPhysicalDevice physical, VkDevice device,
NVSDK_NGX_Version version, const NVSDK_NGX_FeatureCommonInfo* info) {
Enter(kInit);
if (!InsideDirectCall()) NoteInstance(instance, physical, device);
return real_init_project(project, engine, engine_version, path, instance, physical,
device, version, info);
}
inline NVSDK_NGX_Result NVSDK_CONV HookedInitProjectExt(
const char* project, NVSDK_NGX_EngineType engine, const char* engine_version,
const wchar_t* path, VkInstance instance, VkPhysicalDevice physical, VkDevice device,
PFN_vkGetInstanceProcAddr gipa, PFN_vkGetDeviceProcAddr gdpa, NVSDK_NGX_Version version,
const NVSDK_NGX_FeatureCommonInfo* info) {
Enter(kInit);
if (!InsideDirectCall()) NoteInstance(instance, physical, device);
return real_init_project_ext(project, engine, engine_version, path, instance, physical,
device, gipa, gdpa, version, info);
}
inline NVSDK_NGX_Result NVSDK_CONV HookedRequirements(
const VkInstance instance, const VkPhysicalDevice physical,
const NVSDK_NGX_FeatureDiscoveryInfo* info, NVSDK_NGX_FeatureRequirement* out) {
Enter(kInit);
if (!InsideDirectCall()) NoteInstance(instance, physical, nullptr);
return real_requirements(instance, physical, info, out);
}
// The game's NGX Vulkan Shutdown on the core (the SDK's static library calls
// _Shutdown1 when the core exports it, else _Shutdown; nvsdk_ngx_s.lib,
// NVSDK_NGX_VULKAN_ShutdownCommon): NR's runtime is shut down first.
inline void ShutdownNr(VkDevice device = nullptr);
inline NVSDK_NGX_Result NVSDK_CONV HookedShutdown() {
Enter(kShutdown);
const ngx_serial::Call ngx_turn;
if (!InsideDirectCall()) {
RuntimeLock lock(runtime_mutex);
GuardHook([] { ShutdownNr(); });
}
return real_shutdown();
}
inline NVSDK_NGX_Result NVSDK_CONV HookedShutdown1(VkDevice device) {
Enter(kShutdown);
const ngx_serial::Call ngx_turn;
if (!InsideDirectCall()) {
RuntimeLock lock(runtime_mutex);
GuardHook([&] { ShutdownNr(device); });
}
return real_shutdown1(device);
}
inline const detour_guard::Hook kInitHooks[] = {
{"NVSDK_NGX_VULKAN_Init", reinterpret_cast<void**>(&real_init),
reinterpret_cast<void*>(&HookedInit), &init_records[0]},
{"NVSDK_NGX_VULKAN_Init_Ext", reinterpret_cast<void**>(&real_init_ext),
reinterpret_cast<void*>(&HookedInitExt), &init_records[1]},
{"NVSDK_NGX_VULKAN_Init_Ext2", reinterpret_cast<void**>(&real_init_ext2),
reinterpret_cast<void*>(&HookedInitExt2), &init_records[2]},
{"NVSDK_NGX_VULKAN_GetFeatureRequirements",
reinterpret_cast<void**>(&real_requirements),
reinterpret_cast<void*>(&HookedRequirements), &init_records[3]},
{"NVSDK_NGX_VULKAN_Init_ProjectID", reinterpret_cast<void**>(&real_init_project),
reinterpret_cast<void*>(&HookedInitProject), &init_records[4]},
{"NVSDK_NGX_VULKAN_Init_ProjectID_Ext", reinterpret_cast<void**>(&real_init_project_ext),
reinterpret_cast<void*>(&HookedInitProjectExt), &init_records[5]},
{"NVSDK_NGX_VULKAN_Shutdown", reinterpret_cast<void**>(&real_shutdown),
reinterpret_cast<void*>(&HookedShutdown), &init_records[6]},
{"NVSDK_NGX_VULKAN_Shutdown1", reinterpret_cast<void**>(&real_shutdown1),
reinterpret_cast<void*>(&HookedShutdown1), &init_records[7]},
};
// ---------------------------------------------------------------------------
// The NR runtime's device-extension requirement for feature 18
// ---------------------------------------------------------------------------
// Once per session, at the first DLSS evaluate: the NR runtime names the
// device extensions feature 18 needs, and one the game's device did not
// enable cannot be added after vkCreateDevice. ReShade's add-on API has no
// enabled-extension query, so an extension is judged by one of its commands:
// vkGetDeviceProcAddr returns NULL for a command of a device extension that
// was not enabled (Vulkan spec, vkGetDeviceProcAddr behavior table). Only
// extensions outside core Vulkan 1.3 are judged - a core-promoted one's
// functionality exists whether or not its name was enabled - and an unknown
// name is logged as not checkable, never declined.
inline constexpr std::pair<const char*, const char*> kExtensionCommands[] = {
{"VK_NVX_binary_import", "vkCreateCuModuleNVX"},
{"VK_NVX_image_view_handle", "vkGetImageViewHandleNVX"},
{"VK_KHR_push_descriptor", "vkCmdPushDescriptorSetKHR"},
{"VK_KHR_external_memory_win32", "vkGetMemoryWin32HandleKHR"},
{"VK_KHR_external_semaphore_win32", "vkGetSemaphoreWin32HandleKHR"},
};
inline void CheckExtensions() {
uint8_t expected = 0;
if (!extension_state.compare_exchange_strong(expected, 1, std::memory_order_acq_rel)) {
return;
}
const VkDevice device = game_device.load(std::memory_order_relaxed);
const auto [instance, physical] = ContextFor(device);
const NgxLoaderSymbols& symbols = NgxLoaderView();
if (!symbols.nr_ready || instance == nullptr || physical == nullptr) {
// Retried at the next evaluate: the runtime loads on its own schedule.
extension_state.store(0, std::memory_order_relaxed);
static std::atomic_bool logged{false};
if (!logged.exchange(true)) {
Log(reshade::log::level::info,
std::string("NR's Vulkan device-extension requirements are not queried yet: ")
+ (!symbols.nr_ready ? "the NR runtime is not loaded"
: "the game's NGX Vulkan context was not observed"));
}
return;
}
NoteLoaderCall("vk::CheckExtensions/GetProcAddress");
const auto query =
reinterpret_cast<decltype(&NVSDK_NGX_VULKAN_GetFeatureDeviceExtensionRequirements)>(
GetProcAddress(symbols.nr_module,
"NVSDK_NGX_VULKAN_GetFeatureDeviceExtensionRequirements"));
const HMODULE loader = GetModuleHandleW(L"vulkan-1.dll");
const auto device_proc = loader == nullptr ? nullptr
: reinterpret_cast<PFN_vkGetDeviceProcAddr>(GetProcAddress(loader, "vkGetDeviceProcAddr"));
if (query == nullptr || device_proc == nullptr || device == nullptr) return;
NVSDK_NGX_FeatureDiscoveryInfo info{};
info.SDKVersion = NVSDK_NGX_Version_API;
info.FeatureID = kFeatureDlssNr;
info.Identifier.IdentifierType = NVSDK_NGX_Application_Identifier_Type_Application_Id;
info.Identifier.v.ApplicationId = kDirectApplicationId;
info.ApplicationDataPath = AddonDirectory().c_str();
uint32_t count = 0;
VkExtensionProperties* extensions = nullptr;
NVSDK_NGX_Result result = NVSDK_NGX_Result_Fail;
{
DirectCallScope direct;
result = query(instance, physical, &info, &count, &extensions);
}
if (NVSDK_NGX_FAILED(result) || (count != 0 && extensions == nullptr)) {
char text[160];
snprintf(text, sizeof(text),
"NR's Vulkan device-extension query for feature 18 returned 0x%08x;"
" NR proceeds without the check",
static_cast<uint32_t>(result));
Log(reshade::log::level::warning, text);
return;
}
std::string names;
std::string missing;
std::string unchecked;
for (uint32_t i = 0; i < count; ++i) {
const std::string name(extensions[i].extensionName);
names += (names.empty() ? "" : ", ") + name;
const auto known = std::find_if(
std::begin(kExtensionCommands), std::end(kExtensionCommands),
[&](const auto& entry) { return name == entry.first; });
if (known == std::end(kExtensionCommands)) {
unchecked += (unchecked.empty() ? "" : ", ") + name;
} else if (device_proc(device, known->second) == nullptr) {
missing += (missing.empty() ? "" : ", ") + name;
}
}
Log(reshade::log::level::info,
"NR (feature 18) on Vulkan names " + std::to_string(count)
+ " device extension(s): " + (names.empty() ? "(none)" : names)
+ (unchecked.empty() ? "" : "; core or not checkable: " + unchecked));
if (!missing.empty()) {
extension_state.store(2, std::memory_order_relaxed);
Log(reshade::log::level::warning,
"NR on Vulkan needs device extension " + missing
+ ", which the game's device did not enable; the game's image is"
" kept (vk_extension_missing)");
}
}
// ---------------------------------------------------------------------------
// The NGX Vulkan feature detours
// ---------------------------------------------------------------------------
using CreateFn = decltype(&NVSDK_NGX_VULKAN_CreateFeature);
using Create1Fn = decltype(&NVSDK_NGX_VULKAN_CreateFeature1);
using EvaluateFn = decltype(&NVSDK_NGX_VULKAN_EvaluateFeature);
using ReleaseFn = decltype(&NVSDK_NGX_VULKAN_ReleaseFeature);
// ---------------------------------------------------------------------------
// NR on Vulkan: the Upscaled hook point
// ---------------------------------------------------------------------------
//
// After the game's DLSS/DLSSD evaluate returns, NR is recorded into the same
// command buffer, as the D3D12 after path records into the game's list:
// 1. copy the DLSS output to `original` (one copy, as D3D12 makes);
// 2. legacy encode: original -> proxy, the display-range sRGB proxy NR's
// network expects (README "Normalization and transfer");
// 3. feature 18 through the signed runtime's Vulkan path (Runtime below):
// proxy -> neural, with the game's depth and motion vectors passed as
// the game handed them to DLSS (its NVSDK_NGX_Resource_VK pointers);
// 4. legacy decode: original, proxy, neural -> the DLSS output.
// SDR uses the legacy (Classic) family. HDR uses the same v6 shaders and
// normalization decisions as D3D12, including exposure, metering and the
// governor; explicit source-unit overrides are refreshed every evaluate.
//
// Layouts. DLSS writes its output as a storage image, which Vulkan allows
// only in VK_IMAGE_LAYOUT_GENERAL, and DLSS returns every buffer to the
// layout it came in (DLSS guide 3.4); ReShade maps unordered_access to
// GENERAL, so every barrier below leaves the output in GENERAL again. The
// codec's sampled descriptors are SHADER_READ_ONLY_OPTIMAL (ReShade's
// push_descriptors), so the scratch images rest there between frames.
//
// Lifetime. A workset and an NR feature belong to the game DLSS feature
// whose evaluates they ride: same command buffer, so same submission. NGX's
// ReleaseFeature "releases the feature ... and frees its memory" (DLSS guide,
// NVSDK_NGX_ReleaseFeature), so a game that releases its DLSS handle has
// completed every submission that used it, ours included, and they are
// freed there (HookedRelease). The device's teardown frees the rest:
// vkDestroyDevice requires all of the device's work to be complete.
// Runtime. Feature 18 on Vulkan runs on the signed runtime directly, as on
// D3D12: its Vulkan Init_Ext on the game's instance, physical device and
// device, then CreateFeature1 / EvaluateFeature / ReleaseFeature.
// - The game's NGX core does not serve feature 18: its
// NVSDK_NGX_VULKAN_CreateFeature1(18) returns 0xbad0000b
// (FAIL_UnableToInitializeFeature) on vk_basic, as core_create does on
// D3D12 in every field log.
// - The runtime's Vulkan Init_Ext/_Ext2 run the same caller check as its
// D3D12_Init_Ext (310.8 disassembly: GetModuleFileNameW of the caller
// must contain "nvngx.dll", else FAIL_PlatformError 0xbad00002, measured
// on vk_basic before this used LoadDirectApi). LoadDirectApi installs
// the D3D12 path's caller identity (InstallCallerIdentity) for both.
using DirectInitVkFn = InitExtFn;
struct NrRuntime {
DirectInitVkFn init = nullptr;
Create1Fn create = nullptr;
EvaluateFn evaluate = nullptr;
ReleaseFn release = nullptr;
ShutdownDeviceFn shutdown = nullptr;
VkDevice device = nullptr; // the device the runtime is initialized on
bool failed = false;
};
inline NrRuntime runtime;
struct ConfigurationFacts {
capability::Runtime runtime = capability::Runtime::UNKNOWN;
const NVSDK_NGX_Handle* source = nullptr;
uint64_t source_generation = 0;
bool ray_reconstruction = false;
capability::Geometry geometry;
stage_plan::Group group;
uint32_t recorded_passes = 0;
};
inline ConfigurationFacts configuration_facts; // runtime_mutex; recording is not GPU completion.
inline ConfigurationFacts ReadConfigurationFactsLocked() {
auto facts = configuration_facts;
if (runtime.failed) {
facts.runtime = capability::Runtime::UNAVAILABLE;
} else if (runtime.device != nullptr) {
facts.runtime = capability::Runtime::AVAILABLE;
}
return facts;
}
inline void ClearConfigurationFactsLocked() {
if (configuration_facts.source != nullptr
&& stage_source_api.load(std::memory_order_relaxed) == capability::Api::VULKAN) {
stage_source_api.store(capability::Api::UNKNOWN, std::memory_order_relaxed);
stage_source_rr.store(false, std::memory_order_relaxed);
}
configuration_facts = {};
}
// The codec programs: the legacy pair and the v6 family, all from the D3D12
// shaders compiled to SPIR-V (vk_*.comp.slang), on one push-descriptor
// layout (t0..t3 = bindings 0..3, u0/u1 = 4/5) with the 28-dword v6
// constants range (the legacy cbuffer uses its first 20).
enum Program : uint32_t {
kLegacyEncode,
kLegacyDecode,
kLinearize,
kAutoscale,
kExposureScale,
kEncodeV6,
kResolveV6,
kPedestalReduce,
kCommit,
kCommitExposure,
kProgramCount,
};
inline reshade::api::pipeline_layout codec_layout = {};
inline reshade::api::pipeline codec_programs[kProgramCount] = {};
inline bool codec_failed = false;
inline reshade::api::pipeline_layout control_mask_layout = {};
inline reshade::api::pipeline control_mask_program = {};
inline bool control_mask_pipeline_failed = false;
inline std::atomic_bool control_mask_pipeline_logged{false};
inline std::atomic_bool control_mask_version_logged{false};
inline std::atomic_bool control_mask_resource_logged{false};
inline std::atomic_bool control_mask_depth_logged{false};
inline std::atomic_bool control_mask_motion_logged{false};
inline std::atomic_bool control_mask_active_logged{false};
inline bool ControlMaskDepthFormat(VkFormat format) {
switch (format) {
case VK_FORMAT_R16_SFLOAT:
case VK_FORMAT_R32_SFLOAT:
case VK_FORMAT_D16_UNORM:
case VK_FORMAT_X8_D24_UNORM_PACK32:
case VK_FORMAT_D32_SFLOAT:
case VK_FORMAT_D16_UNORM_S8_UINT:
case VK_FORMAT_D24_UNORM_S8_UINT:
case VK_FORMAT_D32_SFLOAT_S8_UINT:
return true;
default:
return false;
}
}
// The look stage's two programs (the D3D12 look_band and look_compose, as
// vk_look_*.comp.slang) on their own layout: t0..t4 = bindings 0..4, u0..u8
// = 5..13 (u7 a storage buffer), the history images = 14/15, 35 constants.
// Without them the look is off for the session and NR runs on.
inline reshade::api::pipeline_layout look_layout = {};
inline reshade::api::pipeline look_band = {};
inline reshade::api::pipeline look_compose = {};
inline std::atomic_uint64_t nr_evaluates{0};
// Feature-18 evaluates on Vulkan: nr_evals times the passes that ran.
inline std::atomic_uint64_t nr_passes{0};
// Live feature 18 handles: the Vulkan share of active_features, which the
// funnel and the status card read.
inline std::atomic_uint32_t live_nr_features{0};
// Compute-state restore (NRVkStateRestore, v8.1; 1 Auto = default, 0 off).
// The codec binds a compute pipeline, pushes descriptors and pushes
// constants on the game's command buffer. The DLSS guide (5.2.5) makes the
// game re-bind after any NGX evaluate, but DLSS SR on Vulkan launches through
// vkCmdCuLaunchKernelNVX and measurably leaves the compute bind point intact
// (vk_basic, RENODX_E2E_VK_CANARY_REBIND=0), so a game may lean on that - the
// D3D12 line learned the same in the field (ComputeStateEnvelope). The
// compute bind point is shadowed per command buffer from ReShade's bind
// events and replayed after NR's passes. Every other stage returns on the
// first compare.
//
// Inexact by construction, counted as vk[restore_partial=] and logged once:
// - a set whose layout has dynamic descriptors: ReShade's
// bind_descriptor_tables event drops pDynamicOffsets
// (vulkan_hooks_command_list.cpp), and a replay without them is invalid
// usage, so that set is left as NR's passes left it;
// - a layout created before the addon saw it (no dynamic-set record);
// - a bind the shadow does not hold (set index >= 8, push constants past
// 256 B, more than 32 pushed writes per set, a push of a type ReShade
// does not convert).
// Pushed image descriptors replay in ReShade's layouts (sampled images
// SHADER_READ_ONLY_OPTIMAL, storage images GENERAL); the event carries no
// layout.
inline std::atomic_uint32_t state_restore{1};
inline std::atomic_uint64_t restores{0};
inline std::atomic_uint64_t restores_partial{0};
inline std::atomic_bool state_events_registered{false};
inline std::atomic_bool image_events_registered{false};
inline std::atomic_uint64_t sampled_layout_restores{0};
// Every Vulkan pipeline layout the game created, with the mask of its sets
// that hold dynamic descriptors (ReShade passes VK_DESCRIPTOR_TYPE_*_DYNAMIC
// through as the raw values 8 and 9).
inline std::mutex layouts_mutex;
inline std::unordered_map<reshade::api::device*, std::unordered_map<uint64_t, uint32_t>>
layout_dynamic_sets;
struct __declspec(uuid("6a3f1e52-8c1d-4b7e-9f2a-5d0c3b4e7a91")) ComputeShadow {
static constexpr uint32_t kSets = 8;
static constexpr uint32_t kPushDwords = 64;
static constexpr size_t kPushWrites = 32;
struct Push {
uint32_t binding;
uint32_t array_offset;
uint32_t count;
reshade::api::descriptor_type type;
std::vector<uint64_t> data;
};
struct Set {
reshade::api::pipeline_layout layout = {};
reshade::api::descriptor_table table = {}; // 0 = pushed
uint32_t order = 0; // 0 = nothing bound
std::vector<Push> pushes;