-
-
Notifications
You must be signed in to change notification settings - Fork 556
/
runtime.cpp
5152 lines (4398 loc) · 195 KB
/
runtime.cpp
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) 2014 Patrick Mours
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "runtime.hpp"
#include "runtime_internal.hpp"
#include "effect_parser.hpp"
#include "effect_codegen.hpp"
#include "effect_preprocessor.hpp"
#include "version.h"
#include "dll_log.hpp"
#include "dll_resources.hpp"
#include "ini_file.hpp"
#include "addon_manager.hpp"
#include "input.hpp"
#include "input_gamepad.hpp"
#include "com_ptr.hpp"
#include "platform_utils.hpp"
#include "reshade_api_object_impl.hpp"
#include <set>
#include <thread>
#include <cmath> // std::abs, std::fmod
#include <cctype> // std::toupper
#include <cwctype> // std::towlower
#include <cstdio> // std::snprintf
#include <cstdlib> // std::malloc, std::rand, std::strtod, std::strtol
#include <cstring> // std::memcpy, std::memset, std::strlen
#include <charconv> // std::to_chars
#include <algorithm> // std::all_of, std::copy_n, std::equal, std::fill_n, std::find, std::find_if, std::for_each, std::max, std::min, std::replace, std::remove, std::remove_if, std::reverse, std::search, std::sort, std::stable_sort, std::swap, std::transform
#include <fpng.h>
#include <stb_image.h>
#include <stb_image_dds.h>
#include <stb_image_write.h>
#include <stb_image_resize2.h>
#include <d3dcompiler.h>
#include <sk_hdr_png.hpp>
bool resolve_path(std::filesystem::path &path, std::error_code &ec)
{
// First convert path to an absolute path
// Ignore the working directory and instead start relative paths at the DLL location
if (path.is_relative())
path = g_reshade_base_path / path;
// Finally try to canonicalize the path too
if (std::filesystem::path canonical_path = std::filesystem::canonical(path, ec); !ec)
path = std::move(canonical_path);
else
path = path.lexically_normal();
return !ec; // The canonicalization step fails if the path does not exist
}
#if RESHADE_FX
bool resolve_preset_path(std::filesystem::path &path, std::error_code &ec)
{
ec.clear();
// First make sure the extension matches, before diving into the file system
if (const std::filesystem::path ext = path.extension();
ext != L".ini" && ext != L".txt")
return false;
// A non-existent path is valid for a new preset
// Otherwise ensure the file has a technique list, which should make it a preset
return !resolve_path(path, ec) || ini_file::load_cache(path).has({}, "Techniques");
}
static std::filesystem::path make_relative_path(const std::filesystem::path &path)
{
if (path.empty())
return path;
// Use ReShade DLL directory as base for relative paths (see 'resolve_path')
std::filesystem::path proximate_path = path.lexically_proximate(g_reshade_base_path);
if (proximate_path.native().rfind(L"..", 0) != std::wstring::npos)
return path; // Do not use relative path if preset is in a parent directory
if (proximate_path.is_relative() && !proximate_path.empty() && proximate_path.native().front() != L'.')
// Prefix preset path with dot character to better indicate it being a relative path
proximate_path = L"." / proximate_path;
return proximate_path;
}
static bool find_file(const std::vector<std::filesystem::path> &search_paths, std::filesystem::path &path)
{
std::error_code ec;
// Do not have to perform a search if the path is already absolute
if (path.is_absolute())
return std::filesystem::exists(path, ec);
for (std::filesystem::path search_path : search_paths)
{
const bool recursive_search = search_path.filename() == L"**";
if (recursive_search)
search_path.remove_filename();
if (resolve_path(search_path, ec))
{
// Append relative file path to absolute search path
if (std::filesystem::path search_sub_path = search_path / path;
std::filesystem::exists(search_sub_path, ec))
{
path = std::move(search_sub_path);
return true;
}
if (recursive_search)
{
for (const std::filesystem::directory_entry &entry : std::filesystem::recursive_directory_iterator(search_path, std::filesystem::directory_options::skip_permission_denied, ec))
{
if (!entry.is_directory(ec))
continue;
if (std::filesystem::path search_sub_path = entry / path;
std::filesystem::exists(search_sub_path, ec))
{
path = std::move(search_sub_path);
return true;
}
}
}
}
else
{
reshade::log::message(reshade::log::level::warning, "Failed to resolve search path '%s' with error code %d.", search_path.u8string().c_str(), ec.value());
}
}
return false;
}
static std::vector<std::filesystem::path> find_files(const std::vector<std::filesystem::path> &search_paths, std::initializer_list<std::filesystem::path> extensions)
{
std::error_code ec;
std::vector<std::filesystem::path> files;
std::vector<std::pair<std::filesystem::path, bool>> resolved_search_paths;
// First resolve all search paths and ensure they are all unique
for (std::filesystem::path search_path : search_paths)
{
const bool recursive_search = search_path.filename() == L"**";
if (recursive_search)
search_path.remove_filename();
if (resolve_path(search_path, ec))
{
if (const auto it = std::find_if(resolved_search_paths.begin(), resolved_search_paths.end(),
[&search_path](const std::pair<std::filesystem::path, bool> &recursive_search_path) {
return recursive_search_path.first == search_path;
});
it != resolved_search_paths.end())
it->second |= recursive_search;
else
resolved_search_paths.push_back(std::make_pair(std::move(search_path), recursive_search));
}
else
{
reshade::log::message(reshade::log::level::warning, "Failed to resolve search path '%s' with error code %d.", search_path.u8string().c_str(), ec.value());
}
}
// Then iterate through all files in those search paths and add those with a matching extension
const auto check_and_add_file = [&extensions, &ec, &files](const std::filesystem::directory_entry &entry) {
if (!entry.is_directory(ec) &&
std::find(extensions.begin(), extensions.end(), entry.path().extension()) != extensions.end())
files.emplace_back(entry); // Construct path from directory entry in-place
};
for (const std::pair<std::filesystem::path, bool> &resolved_search_path : resolved_search_paths)
{
if (resolved_search_path.second)
for (const std::filesystem::directory_entry &entry : std::filesystem::recursive_directory_iterator(resolved_search_path.first, std::filesystem::directory_options::skip_permission_denied, ec))
check_and_add_file(entry);
else
for (const std::filesystem::directory_entry &entry : std::filesystem::directory_iterator(resolved_search_path.first, std::filesystem::directory_options::skip_permission_denied, ec))
check_and_add_file(entry);
}
return files;
}
#endif
reshade::runtime::runtime(api::swapchain *swapchain, api::command_queue *graphics_queue, const std::filesystem::path &config_path, bool is_vr) :
_swapchain(swapchain),
_device(swapchain->get_device()),
_graphics_queue(graphics_queue),
_is_vr(is_vr),
_start_time(std::chrono::high_resolution_clock::now()),
_last_present_time(_start_time),
_last_frame_duration(std::chrono::milliseconds(1)),
#if RESHADE_FX
_effect_search_paths({ L".\\" }),
_texture_search_paths({ L".\\" }),
#endif
_config_path(config_path),
_screenshot_path(L".\\"),
_screenshot_name("%AppName% %Date% %Time%_%TimeMS%"), // Use a timestamp down to the millisecond because users may request more than one screenshot per-second
_screenshot_post_save_command_arguments("\"%TargetPath%\""),
_screenshot_post_save_command_working_directory(L".\\")
{
assert(swapchain != nullptr && graphics_queue != nullptr);
_device->get_property(api::device_properties::vendor_id, &_vendor_id);
_device->get_property(api::device_properties::device_id, &_device_id);
_device->get_property(api::device_properties::api_version, &_renderer_id);
switch (_device->get_api())
{
case api::device_api::d3d9:
case api::device_api::d3d10:
case api::device_api::d3d11:
case api::device_api::d3d12:
break;
case api::device_api::opengl:
_renderer_id |= 0x10000;
break;
case api::device_api::vulkan:
_renderer_id |= 0x20000;
break;
}
char device_description[256] = "";
_device->get_property(api::device_properties::description, device_description);
if (uint32_t driver_version = 0;
_device->get_property(api::device_properties::driver_version, &driver_version))
log::message(log::level::info, "Running on %s Driver %u.%u.", device_description, driver_version / 100, driver_version % 100);
else
log::message(log::level::info, "Running on %s.", device_description);
check_for_update();
// Default shortcut PrtScrn
_screenshot_key_data[0] = 0x2C;
#if RESHADE_GUI && RESHADE_FX
_timestamp_frequency = graphics_queue->get_timestamp_frequency();
#endif
#if RESHADE_GUI
init_gui();
#endif
// Ensure config path is absolute, in case an add-on created an effect runtime with a relative path
std::error_code ec;
resolve_path(_config_path, ec);
load_config();
fpng::fpng_init();
}
reshade::runtime::~runtime()
{
assert(_worker_threads.empty());
#if RESHADE_FX
assert(!_is_initialized && _techniques.empty() && _technique_sorting.empty());
#endif
#if RESHADE_GUI
// Save configuration before shutting down to ensure the current window state is written to disk
save_config();
ini_file::flush_cache(_config_path);
deinit_gui();
#endif
}
bool reshade::runtime::on_init()
{
assert(!_is_initialized);
const api::resource_desc back_buffer_desc = _device->get_resource_desc(get_back_buffer(0));
// Avoid initializing on very small swap chains (e.g. implicit swap chain in The Sims 4, which is not used to present in windowed mode)
if (back_buffer_desc.texture.width <= 16 && back_buffer_desc.texture.height <= 16)
return false;
_width = back_buffer_desc.texture.width;
_height = back_buffer_desc.texture.height;
_back_buffer_format = api::format_to_default_typed(back_buffer_desc.texture.format);
_back_buffer_samples = back_buffer_desc.texture.samples;
_back_buffer_color_space = _swapchain->get_color_space();
// Create resolve texture and copy pipeline (do this before creating effect resources, to ensure correct back buffer format is set up)
if (back_buffer_desc.texture.samples > 1
// Always use resolve texture in OpenGL to flip vertically and support sRGB + binding effect stencil
|| (_device->get_api() == api::device_api::opengl && !_is_vr)
#if RESHADE_FX
// Some effects rely on there being an alpha channel available, so create resolve texture if that is not the case
|| (_back_buffer_format == api::format::r8g8b8x8_unorm || _back_buffer_format == api::format::b8g8r8x8_unorm)
#endif
)
{
#if RESHADE_FX
switch (_back_buffer_format)
{
case api::format::r8g8b8x8_unorm:
_back_buffer_format = api::format::r8g8b8a8_unorm;
break;
case api::format::b8g8r8x8_unorm:
_back_buffer_format = api::format::b8g8r8a8_unorm;
break;
}
#endif
const bool need_copy_pipeline =
_device->get_api() == api::device_api::d3d10 ||
_device->get_api() == api::device_api::d3d11 ||
_device->get_api() == api::device_api::d3d12;
api::resource_usage usage = api::resource_usage::render_target | api::resource_usage::copy_dest | api::resource_usage::resolve_dest;
if (need_copy_pipeline)
usage |= api::resource_usage::shader_resource;
else
usage |= api::resource_usage::copy_source;
if (!_device->create_resource(
api::resource_desc(_width, _height, 1, 1, api::format_to_typeless(_back_buffer_format), 1, api::memory_heap::gpu_only, usage),
nullptr, back_buffer_desc.texture.samples == 1 ? api::resource_usage::copy_dest : api::resource_usage::resolve_dest, &_back_buffer_resolved) ||
!_device->create_resource_view(
_back_buffer_resolved,
api::resource_usage::render_target,
api::resource_view_desc(api::format_to_default_typed(_back_buffer_format, 0)),
&_back_buffer_targets.emplace_back()) ||
!_device->create_resource_view(
_back_buffer_resolved,
api::resource_usage::render_target,
api::resource_view_desc(api::format_to_default_typed(_back_buffer_format, 1)),
&_back_buffer_targets.emplace_back()))
{
log::message(log::level::error, "Failed to create resolve texture resource!");
goto exit_failure;
}
if (need_copy_pipeline)
{
if (!_device->create_resource_view(
_back_buffer_resolved,
api::resource_usage::shader_resource,
api::resource_view_desc(_back_buffer_format),
&_back_buffer_resolved_srv))
{
log::message(log::level::error, "Failed to create resolve shader resource view!");
goto exit_failure;
}
api::sampler_desc sampler_desc = {};
sampler_desc.filter = api::filter_mode::min_mag_mip_point;
sampler_desc.address_u = api::texture_address_mode::clamp;
sampler_desc.address_v = api::texture_address_mode::clamp;
sampler_desc.address_w = api::texture_address_mode::clamp;
api::pipeline_layout_param layout_params[2];
layout_params[0] = api::descriptor_range { 0, 0, 0, 1, api::shader_stage::all, 1, api::descriptor_type::sampler };
layout_params[1] = api::descriptor_range { 0, 0, 0, 1, api::shader_stage::all, 1, api::descriptor_type::shader_resource_view };
const resources::data_resource vs = resources::load_data_resource(IDR_FULLSCREEN_VS);
const resources::data_resource ps = resources::load_data_resource(IDR_COPY_PS);
api::shader_desc vs_desc = { vs.data, vs.data_size };
api::shader_desc ps_desc = { ps.data, ps.data_size };
std::vector<api::pipeline_subobject> subobjects;
subobjects.push_back({ api::pipeline_subobject_type::vertex_shader, 1, &vs_desc });
subobjects.push_back({ api::pipeline_subobject_type::pixel_shader, 1, &ps_desc });
if (!_device->create_pipeline_layout(2, layout_params, &_copy_pipeline_layout) ||
!_device->create_pipeline(_copy_pipeline_layout, static_cast<uint32_t>(subobjects.size()), subobjects.data(), &_copy_pipeline) ||
!_device->create_sampler(sampler_desc, &_copy_sampler_state))
{
log::message(log::level::error, "Failed to create copy pipeline!");
goto exit_failure;
}
}
}
#if RESHADE_FX
// Create an empty texture, which is bound to shader resource view slots with an unknown semantic (since it is not valid to bind a zero handle in Vulkan, unless the 'VK_EXT_robustness2' extension is enabled)
if (_empty_tex == 0)
{
// Use VK_FORMAT_R16_SFLOAT format, since it is mandatory according to the spec (see https://www.khronos.org/registry/vulkan/specs/1.1/html/vkspec.html#features-required-format-support)
if (!_device->create_resource(
api::resource_desc(1, 1, 1, 1, api::format::r16_float, 1, api::memory_heap::gpu_only, api::resource_usage::shader_resource),
nullptr, api::resource_usage::shader_resource, &_empty_tex))
{
log::message(log::level::error, "Failed to create empty texture resource!");
goto exit_failure;
}
_device->set_resource_name(_empty_tex, "ReShade empty texture");
if (!_device->create_resource_view(_empty_tex, api::resource_usage::shader_resource, api::resource_view_desc(api::format::r16_float), &_empty_srv))
{
log::message(log::level::error, "Failed to create empty texture shader resource view!");
goto exit_failure;
}
}
// Create effect color and stencil resource
api::format stencil_format = api::format::unknown;
{
// Find a supported stencil format with the smallest footprint (since the depth component is not used)
constexpr api::format possible_stencil_formats[] = {
api::format::s8_uint,
api::format::d16_unorm_s8_uint,
api::format::d24_unorm_s8_uint,
api::format::d32_float_s8_uint
};
for (const api::format format : possible_stencil_formats)
{
if (_device->check_format_support(format, api::resource_usage::depth_stencil))
{
stencil_format = format;
break;
}
}
}
if (add_effect_permutation(_width, _height, _back_buffer_format, stencil_format) != 0)
goto exit_failure;
_effect_permutations[0].color_space = _back_buffer_color_space;
#endif
// Create render targets for the back buffer resources
for (uint32_t i = 0, count = get_back_buffer_count(); i < count; ++i)
{
const api::resource back_buffer_resource = get_back_buffer(i);
if (!_device->create_resource_view(
back_buffer_resource,
api::resource_usage::render_target,
api::resource_view_desc(
back_buffer_desc.texture.samples > 1 ? api::resource_view_type::texture_2d_multisample : api::resource_view_type::texture_2d,
api::format_to_default_typed(back_buffer_desc.texture.format, 0), 0, 1, 0, 1),
&_back_buffer_targets.emplace_back()) ||
!_device->create_resource_view(
back_buffer_resource,
api::resource_usage::render_target,
api::resource_view_desc(
back_buffer_desc.texture.samples > 1 ? api::resource_view_type::texture_2d_multisample : api::resource_view_type::texture_2d,
api::format_to_default_typed(back_buffer_desc.texture.format, 1), 0, 1, 0, 1),
&_back_buffer_targets.emplace_back()))
{
log::message(log::level::error, "Failed to create back buffer render targets!");
goto exit_failure;
}
}
create_state_block(_device, &_app_state);
#if RESHADE_GUI
if (!init_imgui_resources())
goto exit_failure;
if (_is_vr && !init_gui_vr())
goto exit_failure;
#endif
const input::window_handle window = get_hwnd();
if (window != nullptr && !_is_vr)
_input = input::register_window(window);
else
_input.reset();
// GTK 3 enables transparency for windows, which messes with effects that do not return an alpha value, so disable that again
if (window != nullptr)
utils::set_window_transparency(window, false);
// Reset frame count to zero so effects are loaded in 'update_effects'
_frame_count = 0;
_is_initialized = true;
_last_reload_time = std::chrono::high_resolution_clock::now(); // Intentionally set to current time, so that duration to last reload is valid even when there is no reload on init
_preset_save_successful = true;
_last_screenshot_save_successful = true;
#if RESHADE_ADDON
invoke_addon_event<addon_event::init_effect_runtime>(this);
#endif
log::message(log::level::info, "Recreated runtime environment on runtime %p ('%s').", this, _config_path.u8string().c_str());
return true;
exit_failure:
#if RESHADE_FX
_device->destroy_resource(_empty_tex);
_empty_tex = {};
_device->destroy_resource_view(_empty_srv);
_empty_srv = {};
for (const effect_permutation &permutation : _effect_permutations)
{
_device->destroy_resource(permutation.color_tex);
_device->destroy_resource_view(permutation.color_srv[0]);
_device->destroy_resource_view(permutation.color_srv[1]);
_device->destroy_resource(permutation.stencil_tex);
_device->destroy_resource_view(permutation.stencil_dsv);
}
_effect_permutations.clear();
#endif
_device->destroy_pipeline(_copy_pipeline);
_copy_pipeline = {};
_device->destroy_pipeline_layout(_copy_pipeline_layout);
_copy_pipeline_layout = {};
_device->destroy_sampler(_copy_sampler_state);
_copy_sampler_state = {};
_device->destroy_resource(_back_buffer_resolved);
_back_buffer_resolved = {};
_device->destroy_resource_view(_back_buffer_resolved_srv);
_back_buffer_resolved_srv = {};
for (const api::resource_view view : _back_buffer_targets)
_device->destroy_resource_view(view);
_back_buffer_targets.clear();
destroy_state_block(_device, _app_state);
_app_state = {};
#if RESHADE_GUI
if (_is_vr)
deinit_gui_vr();
destroy_imgui_resources();
#endif
return false;
}
void reshade::runtime::on_reset()
{
if (_is_initialized)
// Update initialization state immediately, so that any effect loading still in progress can abort early
_is_initialized = false;
else
return; // Nothing to do if the runtime was already destroyed or not successfully initialized in the first place
#if RESHADE_FX
// Already performs a wait for idle, so no need to do it again before destroying resources below
destroy_effects();
_device->destroy_resource(_empty_tex);
_empty_tex = {};
_device->destroy_resource_view(_empty_srv);
_empty_srv = {};
for (const effect_permutation &permutation : _effect_permutations)
{
_device->destroy_resource(permutation.color_tex);
_device->destroy_resource_view(permutation.color_srv[0]);
_device->destroy_resource_view(permutation.color_srv[1]);
_device->destroy_resource(permutation.stencil_tex);
_device->destroy_resource_view(permutation.stencil_dsv);
}
_effect_permutations.clear();
#else
for (std::thread &thread : _worker_threads)
if (thread.joinable())
thread.join();
_worker_threads.clear();
#endif
_device->destroy_pipeline(_copy_pipeline);
_copy_pipeline = {};
_device->destroy_pipeline_layout(_copy_pipeline_layout);
_copy_pipeline_layout = {};
_device->destroy_sampler(_copy_sampler_state);
_copy_sampler_state = {};
_device->destroy_resource(_back_buffer_resolved);
_back_buffer_resolved = {};
_device->destroy_resource_view(_back_buffer_resolved_srv);
_back_buffer_resolved_srv = {};
for (const api::resource_view view : _back_buffer_targets)
_device->destroy_resource_view(view);
_back_buffer_targets.clear();
destroy_state_block(_device, _app_state);
_app_state = {};
_device->destroy_fence(_queue_sync_fence);
_queue_sync_fence = {};
_width = _height = 0;
#if RESHADE_GUI
if (_is_vr)
deinit_gui_vr();
destroy_imgui_resources();
#endif
#if RESHADE_ADDON
invoke_addon_event<addon_event::destroy_effect_runtime>(this);
#endif
log::message(log::level::info, "Destroyed runtime environment on runtime %p ('%s').", this, _config_path.u8string().c_str());
}
void reshade::runtime::on_present(api::command_queue *present_queue)
{
assert(present_queue != nullptr);
if (!_is_initialized)
return;
// If the application is presenting with a different queue than rendering, synchronize these two queues first
// This ensures that it has finished rendering before ReShade applies its own rendering
if (present_queue != _graphics_queue)
{
if (_queue_sync_fence == 0 &&
!_device->create_fence(_queue_sync_value, api::fence_flags::none, &_queue_sync_fence))
{
log::message(log::level::error, "Failed to create queue synchronization fence!");
return;
}
_queue_sync_value++;
// Signal from the queue the application is presenting with
if (present_queue->signal(_queue_sync_fence, _queue_sync_value))
// Wait on that before the immediate command list flush below
_graphics_queue->wait(_queue_sync_fence, _queue_sync_value);
}
#if RESHADE_ADDON
_is_in_present_call = true;
#endif
api::command_list *const cmd_list = _graphics_queue->get_immediate_command_list();
capture_state(cmd_list, _app_state);
uint32_t back_buffer_index = (_back_buffer_resolved != 0 ? 2 : 0) + get_current_back_buffer_index() * 2;
const api::resource back_buffer_resource = _device->get_resource_from_view(_back_buffer_targets[back_buffer_index]);
// Resolve MSAA back buffer if MSAA is active or copy when format conversion is required
if (_back_buffer_resolved != 0)
{
if (_back_buffer_samples == 1)
{
cmd_list->barrier(back_buffer_resource, api::resource_usage::present, api::resource_usage::copy_source);
cmd_list->copy_texture_region(back_buffer_resource, 0, nullptr, _back_buffer_resolved, 0, nullptr);
cmd_list->barrier(_back_buffer_resolved, api::resource_usage::copy_dest, api::resource_usage::render_target);
}
else
{
cmd_list->barrier(back_buffer_resource, api::resource_usage::present, api::resource_usage::resolve_source);
cmd_list->resolve_texture_region(back_buffer_resource, 0, nullptr, _back_buffer_resolved, 0, 0, 0, 0, _back_buffer_format);
cmd_list->barrier(_back_buffer_resolved, api::resource_usage::resolve_dest, api::resource_usage::render_target);
}
}
// Lock input so it cannot be modified by other threads while we are reading it here
std::unique_lock<std::recursive_mutex> input_lock;
if (_input != nullptr)
input_lock = _input->lock();
#if RESHADE_FX
update_effects();
if (_should_save_screenshot && _screenshot_save_before && _effects_enabled && !_effects_rendered_this_frame)
save_screenshot(" original");
if (_back_buffer_resolved != 0)
{
runtime::render_effects(cmd_list, _back_buffer_targets[0], _back_buffer_targets[1]);
}
else
{
cmd_list->barrier(back_buffer_resource, api::resource_usage::present, api::resource_usage::render_target);
runtime::render_effects(cmd_list, _back_buffer_targets[back_buffer_index], _back_buffer_targets[back_buffer_index + 1]);
cmd_list->barrier(back_buffer_resource, api::resource_usage::render_target, api::resource_usage::present);
}
#endif
if (_should_save_screenshot)
save_screenshot();
_frame_count++;
const auto current_time = std::chrono::high_resolution_clock::now();
_last_frame_duration = current_time - _last_present_time; _last_present_time = current_time;
#if RESHADE_GUI
// Draw overlay
if (_is_vr)
draw_gui_vr();
else
draw_gui();
if (_should_save_screenshot && _screenshot_save_gui && (_show_overlay
#if RESHADE_FX
|| (_preview_texture != 0 && _effects_enabled)
#endif
))
save_screenshot(" overlay");
#endif
// All screenshots were created at this point, so reset request
_should_save_screenshot = false;
// Handle keyboard shortcuts
if (!_ignore_shortcuts && _input != nullptr)
{
#if RESHADE_FX
if (_input->is_key_pressed(_effects_key_data, _force_shortcut_modifiers))
{
#if RESHADE_ADDON
if (!invoke_addon_event<addon_event::reshade_set_effects_state>(this, !_effects_enabled))
#endif
_effects_enabled = !_effects_enabled;
}
#endif
if (_input->is_key_pressed(_screenshot_key_data, _force_shortcut_modifiers))
{
_screenshot_count++;
_should_save_screenshot = true; // Remember that we want to save a screenshot next frame
}
#if RESHADE_FX
// Do not allow the following shortcuts while effects are being loaded or initialized (since they affect that state)
if (!is_loading())
{
if (_effects_enabled)
{
for (effect &effect : _effects)
{
if (!effect.rendering)
continue;
for (uniform &variable : effect.uniforms)
{
if (_input->is_key_pressed(variable.toggle_key_data, _force_shortcut_modifiers))
{
assert(variable.supports_toggle_key());
// Change to next value if the associated shortcut key was pressed
switch (variable.type.base)
{
case reshadefx::type::t_bool:
{
bool data = false;
get_uniform_value(variable, &data);
set_uniform_value(variable, !data);
break;
}
case reshadefx::type::t_int:
case reshadefx::type::t_uint:
{
int data[4] = {};
get_uniform_value(variable, data, 4);
const std::string_view ui_items = variable.annotation_as_string("ui_items");
int num_items = 0;
for (size_t offset = 0, next; (next = ui_items.find('\0', offset)) != std::string_view::npos; offset = next + 1)
num_items++;
data[0] = (data[0] + 1 >= num_items) ? 0 : data[0] + 1;
set_uniform_value(variable, data, 4);
break;
}
}
#if RESHADE_GUI
if (_auto_save_preset)
save_current_preset();
else
_preset_is_modified = true;
#endif
}
}
}
for (technique &tech : _techniques)
{
if (_input->is_key_pressed(tech.toggle_key_data, _force_shortcut_modifiers))
{
if (!tech.enabled)
enable_technique(tech);
else
disable_technique(tech);
#if RESHADE_GUI
if (_auto_save_preset)
save_current_preset();
else
_preset_is_modified = true;
#endif
}
}
}
if (_input->is_key_pressed(_reload_key_data, _force_shortcut_modifiers))
reload_effects();
if (_input->is_key_pressed(_performance_mode_key_data, _force_shortcut_modifiers))
{
_performance_mode = !_performance_mode;
save_config();
reload_effects();
}
if (const bool reversed = _input->is_key_pressed(_prev_preset_key_data, _force_shortcut_modifiers);
reversed || _input->is_key_pressed(_next_preset_key_data, _force_shortcut_modifiers))
{
// The preset shortcut key was pressed down, so start the transition
if (switch_to_next_preset(_current_preset_path.parent_path(), reversed))
save_config();
}
else
{
for (const preset_shortcut &shortcut : _preset_shortcuts)
{
if (_input->is_key_pressed(shortcut.key_data, _force_shortcut_modifiers))
{
if (switch_to_next_preset(shortcut.preset_path))
save_config();
break;
}
}
}
// Continuously update preset values while a transition is in progress
if (_is_in_preset_transition)
load_current_preset();
}
#endif
}
// Stretch main render target back into MSAA back buffer if MSAA is active or copy when format conversion is required
if (_back_buffer_resolved != 0)
{
const api::resource resources[2] = { back_buffer_resource, _back_buffer_resolved };
const api::resource_usage state_old[2] = { api::resource_usage::copy_source | api::resource_usage::resolve_source, api::resource_usage::render_target };
const api::resource_usage state_final[2] = { api::resource_usage::present, api::resource_usage::resolve_dest };
if (_device->get_api() == api::device_api::d3d10 ||
_device->get_api() == api::device_api::d3d11 ||
_device->get_api() == api::device_api::d3d12)
{
const api::resource_usage state_new[2] = { api::resource_usage::render_target, api::resource_usage::shader_resource };
cmd_list->barrier(2, resources, state_old, state_new);
cmd_list->bind_pipeline(api::pipeline_stage::all_graphics, _copy_pipeline);
cmd_list->push_descriptors(api::shader_stage::pixel, _copy_pipeline_layout, 0, api::descriptor_table_update { {}, 0, 0, 1, api::descriptor_type::sampler, &_copy_sampler_state });
cmd_list->push_descriptors(api::shader_stage::pixel, _copy_pipeline_layout, 1, api::descriptor_table_update { {}, 0, 0, 1, api::descriptor_type::shader_resource_view, &_back_buffer_resolved_srv });
const api::viewport viewport = { 0.0f, 0.0f, static_cast<float>(_width), static_cast<float>(_height), 0.0f, 1.0f };
cmd_list->bind_viewports(0, 1, &viewport);
const api::rect scissor_rect = { 0, 0, static_cast<int32_t>(_width), static_cast<int32_t>(_height) };
cmd_list->bind_scissor_rects(0, 1, &scissor_rect);
const bool srgb_write_enable = (_back_buffer_format == api::format::r8g8b8a8_unorm_srgb || _back_buffer_format == api::format::b8g8r8a8_unorm_srgb);
cmd_list->bind_render_targets_and_depth_stencil(1, &_back_buffer_targets[back_buffer_index + srgb_write_enable]);
cmd_list->draw(3, 1, 0, 0);
cmd_list->barrier(2, resources, state_new, state_final);
}
else
{
const api::resource_usage state_new[2] = { api::resource_usage::copy_dest, api::resource_usage::copy_source };
cmd_list->barrier(2, resources, state_old, state_new);
cmd_list->copy_texture_region(_back_buffer_resolved, 0, nullptr, back_buffer_resource, 0, nullptr);
cmd_list->barrier(2, resources, state_new, state_final);
}
}
#if RESHADE_ADDON
invoke_addon_event<addon_event::reshade_present>(this);
_is_in_present_call = false;
#endif
#if RESHADE_FX
_effects_rendered_this_frame = false;
#endif
// Apply previous state from application
apply_state(cmd_list, _app_state);
if (present_queue != _graphics_queue)
{
_queue_sync_value++;
if (_graphics_queue->signal(_queue_sync_fence, _queue_sync_value))
present_queue->wait(_queue_sync_fence, _queue_sync_value);
}
// Update input status
if (_input != nullptr)
_input->next_frame();
if (_input_gamepad != nullptr)
_input_gamepad->next_frame();
// Save modified INI files
if (!ini_file::flush_cache())
_preset_save_successful = false;
#if RESHADE_ADDON == 1
// Detect high network traffic
extern volatile long g_network_traffic;
static int cooldown = 0, traffic = 0;
if (cooldown-- > 0)
{
traffic += g_network_traffic > 0;
}
else
{
const bool was_enabled = addon_enabled;
addon_enabled = traffic < 10;
traffic = 0;
cooldown = 60;
#if RESHADE_FX
if (addon_enabled != was_enabled)
{
if (was_enabled)
_backup_texture_semantic_bindings = _texture_semantic_bindings;
for (const auto &info : _backup_texture_semantic_bindings)
{
if (info.second.first == _effect_color_srv[0] && info.second.second == _effect_color_srv[1])
continue;
update_texture_bindings(info.first.c_str(), addon_enabled ? info.second.first : api::resource_view { 0 }, addon_enabled ? info.second.second : api::resource_view { 0 });
}
}
#endif
}
if (std::numeric_limits<long>::max() != g_network_traffic)
g_network_traffic = 0;
#endif
}
void reshade::runtime::load_config()
{
const ini_file &config = ini_file::load_cache(_config_path);
if (config.get("INPUT", "GamepadNavigation"))
_input_gamepad = input_gamepad::load();
else
_input_gamepad.reset();
const auto config_get = [&config](const std::string §ion, const std::string &key, auto &values) {
if (config.get(section, key, values))
return true;
// Fall back to global configuration when an entry does not exist in the local configuration
return global_config().get(section, key, values);
};
config_get("INPUT", "ForceShortcutModifiers", _force_shortcut_modifiers);
config_get("INPUT", "KeyScreenshot", _screenshot_key_data);
#if RESHADE_FX
config_get("INPUT", "KeyEffects", _effects_key_data);
config_get("INPUT", "KeyNextPreset", _next_preset_key_data);
config_get("INPUT", "KeyPerformanceMode", _performance_mode_key_data);
config_get("INPUT", "KeyPreviousPreset", _prev_preset_key_data);
config_get("INPUT", "KeyReload", _reload_key_data);
config_get("GENERAL", "NoDebugInfo", _no_debug_info);
config_get("GENERAL", "NoEffectCache", _no_effect_cache);
config_get("GENERAL", "NoReloadOnInit", _no_reload_on_init);
config_get("GENERAL", "EffectSearchPaths", _effect_search_paths);
config_get("GENERAL", "PerformanceMode", _performance_mode);
config_get("GENERAL", "PreprocessorDefinitions", _global_preprocessor_definitions);
config_get("GENERAL", "SkipLoadingDisabledEffects", _effect_load_skipping);
config_get("GENERAL", "TextureSearchPaths", _texture_search_paths);
config_get("GENERAL", "IntermediateCachePath", _effect_cache_path);
config_get("GENERAL", "StartupPresetPath", _startup_preset_path);
config_get("GENERAL", "PresetPath", _current_preset_path);
config_get("GENERAL", "PresetTransitionDuration", _preset_transition_duration);
// Fall back to temp directory if cache path does not exist
std::error_code ec;
if (_effect_cache_path.empty() || !resolve_path(_effect_cache_path, ec))
{
_effect_cache_path = std::filesystem::temp_directory_path(ec) / "ReShade";
std::filesystem::create_directory(_effect_cache_path, ec);
if (ec)
log::message(log::level::error, "Failed to create effect cache directory '%s' with error code %d!", _effect_cache_path.u8string().c_str(), ec.value());
}
// Use startup preset instead of last selection
if (!_startup_preset_path.empty() && resolve_preset_path(_startup_preset_path, ec))
_current_preset_path = _startup_preset_path;
// Use default if the preset file does not exist yet
else if (!resolve_preset_path(_current_preset_path, ec))
_current_preset_path = g_reshade_base_path / L"ReShadePreset.ini";
std::vector<unsigned int> preset_key_data;
std::vector<std::filesystem::path> preset_shortcut_paths;
config_get("GENERAL", "PresetShortcutKeys", preset_key_data);
config_get("GENERAL", "PresetShortcutPaths", preset_shortcut_paths);