forked from crosire/reshade
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dll_main.cpp
859 lines (678 loc) · 30.4 KB
/
dll_main.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
/*
* Copyright (C) 2014 Patrick Mours. All rights reserved.
* License: https://github.com/crosire/reshade#license
*/
#include "dll_log.hpp"
#include "hook_manager.hpp"
#include "version.h"
#include <Psapi.h>
#include <Windows.h>
HMODULE g_module_handle = nullptr;
std::filesystem::path g_reshade_dll_path;
std::filesystem::path g_target_executable_path;
extern std::filesystem::path get_system_path()
{
static std::filesystem::path system_path;
if (system_path.empty())
{
WCHAR buf[4096];
if (0 == GetEnvironmentVariableW(L"RESHADE_MODULE_PATH_OVERRIDE", buf, ARRAYSIZE(buf)))
// First try environment variable, use system directory if it does not exist or is empty
GetSystemDirectoryW(buf, ARRAYSIZE(buf));
if (system_path = buf; system_path.has_stem())
system_path += L'\\'; // Always convert to directory path (with a trailing slash)
if (system_path.is_relative())
system_path = g_target_executable_path.parent_path() / system_path;
system_path = system_path.lexically_normal();
}
return system_path;
}
static inline std::filesystem::path get_module_path(HMODULE module)
{
WCHAR buf[4096];
return GetModuleFileNameW(module, buf, ARRAYSIZE(buf)) ? buf : L"";
}
#ifdef RESHADE_TEST_APPLICATION
# include "d3d9/runtime_d3d9.hpp"
# include "d3d11/runtime_d3d11.hpp"
# include "d3d12/runtime_d3d12.hpp"
# include "opengl/runtime_gl.hpp"
# include "vulkan/runtime_vk.hpp"
# if RESHADE_D3D12ON7
# include <D3D12Downlevel.h>
# endif
# ifdef NDEBUG
#define HCHECK(exp) exp
# else
#define HCHECK(exp) assert(SUCCEEDED(exp))
# endif
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR lpCmdLine, int nCmdShow)
{
using namespace reshade;
g_module_handle = hInstance;
g_reshade_dll_path = get_module_path(nullptr);
g_target_executable_path = get_module_path(nullptr);
log::open(std::filesystem::path(g_reshade_dll_path).replace_extension(".log"));
hooks::register_module("user32.dll");
static UINT s_resize_w = 0, s_resize_h = 0;
// Register window class
WNDCLASS wc = { sizeof(wc) };
wc.hInstance = hInstance;
wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
wc.lpszClassName = TEXT("Test");
wc.lpfnWndProc =
[](HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) -> LRESULT {
switch (Msg)
{
case WM_DESTROY:
PostQuitMessage(EXIT_SUCCESS);
break;
case WM_SIZE:
s_resize_w = LOWORD(lParam);
s_resize_h = HIWORD(lParam);
break;
}
return DefWindowProc(hWnd, Msg, wParam, lParam);
};
RegisterClass(&wc);
// Create and show window instance
const HWND window_handle = CreateWindow(
wc.lpszClassName, TEXT("ReShade ") TEXT(VERSION_STRING_FILE) TEXT(" by crosire"), WS_OVERLAPPEDWINDOW,
0, 0, 1024, 800, nullptr, nullptr, hInstance, nullptr);
if (window_handle == nullptr)
return 0;
ShowWindow(window_handle, nCmdShow);
// Avoid resize caused by 'ShowWindow' call
s_resize_w = 0;
s_resize_h = 0;
MSG msg = {};
#pragma region D3D9 Implementation
if (strstr(lpCmdLine, "-d3d9"))
{
const auto d3d9_module = LoadLibrary(TEXT("d3d9.dll"));
assert(d3d9_module != nullptr);
hooks::register_module("d3d9.dll");
D3DPRESENT_PARAMETERS pp = {};
pp.SwapEffect = D3DSWAPEFFECT_DISCARD;
pp.hDeviceWindow = window_handle;
pp.Windowed = true;
pp.PresentationInterval = D3DPRESENT_INTERVAL_ONE;
// Initialize Direct3D 9
com_ptr<IDirect3D9> d3d(Direct3DCreate9(D3D_SDK_VERSION), true);
com_ptr<IDirect3DDevice9> device;
HCHECK(d3d->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, window_handle, D3DCREATE_HARDWARE_VERTEXPROCESSING, &pp, &device));
while (msg.message != WM_QUIT)
{
while (msg.message != WM_QUIT &&
PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE))
DispatchMessage(&msg);
if (s_resize_w != 0)
{
pp.BackBufferWidth = s_resize_w;
pp.BackBufferHeight = s_resize_h;
HCHECK(device->Reset(&pp));
s_resize_w = s_resize_h = 0;
}
HCHECK(device->Clear(0, nullptr, D3DCLEAR_TARGET, 0xFF7F7F7F, 0, 0));
HCHECK(device->Present(nullptr, nullptr, nullptr, nullptr));
}
reshade::hooks::uninstall();
FreeLibrary(d3d9_module);
return static_cast<int>(msg.wParam);
}
#pragma endregion
#pragma region D3D11 Implementation
if (strstr(lpCmdLine, "-d3d11"))
{
const auto dxgi_module = LoadLibrary(TEXT("dxgi.dll"));
const auto d3d11_module = LoadLibrary(TEXT("d3d11.dll"));
assert(dxgi_module != nullptr);
assert(d3d11_module != nullptr);
hooks::register_module("dxgi.dll");
hooks::register_module("d3d11.dll");
// Initialize Direct3D 11
com_ptr<ID3D11Device> device;
com_ptr<ID3D11DeviceContext> immediate_context;
com_ptr<IDXGISwapChain> swapchain;
{ DXGI_SWAP_CHAIN_DESC desc = {};
desc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
desc.SampleDesc = { 1, 0 };
desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
desc.BufferCount = 1;
desc.OutputWindow = window_handle;
desc.Windowed = true;
desc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
HCHECK(D3D11CreateDeviceAndSwapChain(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, D3D11_CREATE_DEVICE_DEBUG, nullptr, 0, D3D11_SDK_VERSION, &desc, &swapchain, &device, nullptr, &immediate_context));
}
com_ptr<ID3D11Texture2D> backbuffer;
HCHECK(swapchain->GetBuffer(0, IID_PPV_ARGS(&backbuffer)));
com_ptr<ID3D11RenderTargetView> target;
HCHECK(device->CreateRenderTargetView(backbuffer.get(), nullptr, &target));
while (msg.message != WM_QUIT)
{
while (msg.message != WM_QUIT &&
PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE))
DispatchMessage(&msg);
if (s_resize_w != 0)
{
target.reset();
backbuffer.reset();
HCHECK(swapchain->ResizeBuffers(1, s_resize_w, s_resize_h, DXGI_FORMAT_UNKNOWN, 0));
HCHECK(swapchain->GetBuffer(0, IID_PPV_ARGS(&backbuffer)));
HCHECK(device->CreateRenderTargetView(backbuffer.get(), nullptr, &target));
s_resize_w = s_resize_h = 0;
}
const float color[4] = { 0.5f, 0.5f, 0.5f, 1.0f };
immediate_context->ClearRenderTargetView(target.get(), color);
HCHECK(swapchain->Present(1, 0));
}
reshade::hooks::uninstall();
FreeLibrary(dxgi_module);
FreeLibrary(d3d11_module);
return static_cast<int>(msg.wParam);
}
#pragma endregion
#pragma region D3D12 Implementation
if (strstr(lpCmdLine, "-d3d12"))
{
const auto dxgi_module = LoadLibrary(TEXT("dxgi.dll"));
const auto d3d12_module = LoadLibrary(TEXT("d3d12.dll"));
assert(dxgi_module != nullptr);
assert(d3d12_module != nullptr);
hooks::register_module("dxgi.dll");
hooks::register_module("d3d12.dll");
// Enable D3D debug layer if it is available
{ com_ptr<ID3D12Debug> debug_iface;
if (SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&debug_iface))))
debug_iface->EnableDebugLayer();
}
// Initialize Direct3D 12
com_ptr<ID3D12Device> device;
com_ptr<ID3D12CommandQueue> command_queue;
com_ptr<IDXGISwapChain3> swapchain;
com_ptr<ID3D12Resource> backbuffers[3];
com_ptr<ID3D12DescriptorHeap> rtv_heap;
com_ptr<ID3D12CommandAllocator> cmd_alloc;
com_ptr<ID3D12GraphicsCommandList> cmd_lists[3];
HCHECK(D3D12CreateDevice(nullptr, D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&device)));
# if RESHADE_D3D12ON7
// Check if this device was created using d3d12on7 on Windows 7
// See https://microsoft.github.io/DirectX-Specs/d3d/D3D12onWin7.html for more information
com_ptr<ID3D12DeviceDownlevel> downlevel;
const bool is_d3d12on7 = SUCCEEDED(device->QueryInterface(&downlevel));
# else
const bool is_d3d12on7 = false;
# endif
{ D3D12_COMMAND_QUEUE_DESC desc = { D3D12_COMMAND_LIST_TYPE_DIRECT };
HCHECK(device->CreateCommandQueue(&desc, IID_PPV_ARGS(&command_queue)));
}
const UINT num_buffers = is_d3d12on7 ? 1 : ARRAYSIZE(backbuffers);
if (!is_d3d12on7)
{
// DXGI has not been updated for d3d12on7, so cannot use swap chain created from D3D12 device there
DXGI_SWAP_CHAIN_DESC1 desc = {};
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
desc.SampleDesc = { 1, 0 };
desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
desc.BufferCount = num_buffers;
desc.Scaling = DXGI_SCALING_STRETCH;
desc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
com_ptr<IDXGIFactory2> dxgi_factory;
com_ptr<IDXGISwapChain1> dxgi_swapchain;
HCHECK(CreateDXGIFactory2(DXGI_CREATE_FACTORY_DEBUG, IID_PPV_ARGS(&dxgi_factory)));
HCHECK(dxgi_factory->CreateSwapChainForHwnd(command_queue.get(), window_handle, &desc, nullptr, nullptr, &dxgi_swapchain));
HCHECK(dxgi_swapchain->QueryInterface(&swapchain));
}
{ D3D12_DESCRIPTOR_HEAP_DESC desc = { D3D12_DESCRIPTOR_HEAP_TYPE_RTV };
desc.NumDescriptors = num_buffers;
HCHECK(device->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&rtv_heap)));
}
const UINT rtv_handle_size = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
HCHECK(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&cmd_alloc)));
resize_buffers:
D3D12_CPU_DESCRIPTOR_HANDLE rtv_handle = rtv_heap->GetCPUDescriptorHandleForHeapStart();
for (UINT i = 0; i < num_buffers; ++i, rtv_handle.ptr += rtv_handle_size)
{
if (!is_d3d12on7)
{
HCHECK(swapchain->GetBuffer(i, IID_PPV_ARGS(&backbuffers[i])));
}
else
{
RECT window_rect = {};
GetClientRect(window_handle, &window_rect);
D3D12_RESOURCE_DESC desc = { D3D12_RESOURCE_DIMENSION_TEXTURE2D };
desc.Width = window_rect.right - window_rect.left;
desc.Height = window_rect.bottom - window_rect.top;
desc.DepthOrArraySize = desc.MipLevels = 1;
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
desc.SampleDesc = { 1, 0 };
desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
D3D12_HEAP_PROPERTIES props = { D3D12_HEAP_TYPE_DEFAULT };
// Create a fake back buffer resource for d3d12on7
HCHECK(device->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&backbuffers[i])));
}
device->CreateRenderTargetView(backbuffers[i].get(), nullptr, rtv_handle);
HCHECK(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, cmd_alloc.get(), nullptr, IID_PPV_ARGS(&cmd_lists[i])));
D3D12_RESOURCE_BARRIER barrier = { D3D12_RESOURCE_BARRIER_TYPE_TRANSITION };
barrier.Transition.pResource = backbuffers[i].get();
barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_PRESENT;
barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET;
cmd_lists[i]->ResourceBarrier(1, &barrier);
const float color[4] = { 0.5f, 0.5f, 0.5f, 1.0f };
cmd_lists[i]->ClearRenderTargetView(rtv_handle, color, 0, nullptr);
barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET;
barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PRESENT;
cmd_lists[i]->ResourceBarrier(1, &barrier);
HCHECK(cmd_lists[i]->Close());
}
while (msg.message != WM_QUIT)
{
while (msg.message != WM_QUIT &&
PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE))
DispatchMessage(&msg);
if (s_resize_w != 0)
{
// Clean up current resources referencing the back buffer
for (auto &ptr : cmd_lists)
ptr.reset();
for (auto &ptr : backbuffers)
ptr.reset();
if (!is_d3d12on7)
HCHECK(swapchain->ResizeBuffers(num_buffers, s_resize_w, s_resize_h, DXGI_FORMAT_UNKNOWN, 0));
s_resize_w = s_resize_h = 0;
goto resize_buffers; // Re-create command lists
}
const UINT swap_index = is_d3d12on7 ? 0 : swapchain->GetCurrentBackBufferIndex();
ID3D12CommandList *const cmd_list = cmd_lists[swap_index].get();
command_queue->ExecuteCommandLists(1, &cmd_list);
# if RESHADE_D3D12ON7
if (is_d3d12on7)
{
// Create a dummy list to pass into present
com_ptr<ID3D12GraphicsCommandList> dummy_list;
HCHECK(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, cmd_alloc.get(), nullptr, IID_PPV_ARGS(&dummy_list)));
com_ptr<ID3D12CommandQueueDownlevel> queue_downlevel;
HCHECK(command_queue->QueryInterface(&queue_downlevel));
// Windows 7 present path does not have a DXGI swap chain
HCHECK(queue_downlevel->Present(dummy_list.get(), backbuffers[swap_index].get(), window_handle, D3D12_DOWNLEVEL_PRESENT_FLAG_WAIT_FOR_VBLANK));
}
else
# endif
// Synchronization is handled in "runtime_d3d12::on_present"
HCHECK(swapchain->Present(1, 0));
}
reshade::hooks::uninstall();
FreeLibrary(dxgi_module);
FreeLibrary(d3d12_module);
return static_cast<int>(msg.wParam);
}
#pragma endregion
#pragma region OpenGL Implementation
if (strstr(lpCmdLine, "-opengl"))
{
const auto opengl_module = LoadLibrary(TEXT("opengl32.dll"));
assert(opengl_module != nullptr);
hooks::register_module("opengl32.dll");
// Initialize OpenGL
const HDC hdc = GetDC(window_handle);
PIXELFORMATDESCRIPTOR pfd = { sizeof(pfd), 1 };
pfd.dwFlags = PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 32;
SetPixelFormat(hdc, ChoosePixelFormat(hdc, &pfd), &pfd);
const HGLRC hglrc1 = wglCreateContext(hdc);
if (hglrc1 == nullptr)
return 0;
wglMakeCurrent(hdc, hglrc1);
// Create an OpenGL 4.3 context
const int attribs[] = {
0x2091 /*WGL_CONTEXT_MAJOR_VERSION_ARB*/, 4,
0x2092 /*WGL_CONTEXT_MINOR_VERSION_ARB*/, 3,
0 // Terminate list
};
const HGLRC hglrc2 = reinterpret_cast<HGLRC(WINAPI*)(HDC, HGLRC, const int *)>(
wglGetProcAddress("wglCreateContextAttribsARB"))(hdc, nullptr, attribs);
if (hglrc2 == nullptr)
return 0;
wglMakeCurrent(nullptr, nullptr);
wglDeleteContext(hglrc1);
wglMakeCurrent(hdc, hglrc2);
while (msg.message != WM_QUIT)
{
while (msg.message != WM_QUIT &&
PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE))
DispatchMessage(&msg);
if (s_resize_w != 0)
{
glViewport(0, 0, s_resize_w, s_resize_h);
s_resize_w = s_resize_h = 0;
}
glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
wglSwapLayerBuffers(hdc, WGL_SWAP_MAIN_PLANE);
}
wglMakeCurrent(nullptr, nullptr);
wglDeleteContext(hglrc2);
reshade::hooks::uninstall();
FreeLibrary(opengl_module);
return static_cast<int>(msg.wParam);
}
#pragma endregion
#pragma region Vulkan Implementation
# define VK_CHECK(exp) { const VkResult res = (exp); assert(res == VK_SUCCESS); }
# define VK_CALL_CMD(name, device, ...) reinterpret_cast<PFN_##name>(vkGetDeviceProcAddr(device, #name))(__VA_ARGS__)
# define VK_CALL_DEV(name, device, ...) reinterpret_cast<PFN_##name>(vkGetDeviceProcAddr(device, #name))(device, __VA_ARGS__)
# define VK_CALL_INS(name, instance, ...) reinterpret_cast<PFN_##name>(vkGetInstanceProcAddr(instance, #name))(__VA_ARGS__)
if (strstr(lpCmdLine, "-vulkan"))
{
const auto vulkan_module = LoadLibrary(TEXT("vulkan-1.dll"));
assert(vulkan_module != nullptr);
hooks::register_module("vulkan-1.dll");
VkDevice device = VK_NULL_HANDLE;
VkInstance instance = VK_NULL_HANDLE;
VkSurfaceKHR surface = VK_NULL_HANDLE;
VkSwapchainKHR swapchain = VK_NULL_HANDLE;
VkPhysicalDevice physical_device = VK_NULL_HANDLE;
{ VkApplicationInfo app_info { VK_STRUCTURE_TYPE_APPLICATION_INFO };
app_info.apiVersion = VK_API_VERSION_1_0;
app_info.pApplicationName = "ReShade Test Application";
app_info.applicationVersion = VERSION_MAJOR * 10000 + VERSION_MINOR * 100 + VERSION_REVISION;
const char *const enabled_layers[] = {
# if VK_HEADER_VERSION >= 106
"VK_LAYER_KHRONOS_validation"
# else
"VK_LAYER_LUNARG_standard_validation"
# endif
};
const char *const enabled_extensions[] = {
VK_KHR_SURFACE_EXTENSION_NAME,
VK_KHR_WIN32_SURFACE_EXTENSION_NAME,
VK_EXT_DEBUG_REPORT_EXTENSION_NAME
};
VkInstanceCreateInfo create_info { VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO };
create_info.pApplicationInfo = &app_info;
create_info.enabledLayerCount = ARRAYSIZE(enabled_layers);
create_info.ppEnabledLayerNames = enabled_layers;
create_info.enabledExtensionCount = ARRAYSIZE(enabled_extensions);
create_info.ppEnabledExtensionNames = enabled_extensions;
VK_CHECK(VK_CALL_INS(vkCreateInstance, VK_NULL_HANDLE, &create_info, nullptr, &instance));
}
// Pick the first physical device.
uint32_t num_physical_devices = 1;
VK_CHECK(VK_CALL_INS(vkEnumeratePhysicalDevices, instance, instance, &num_physical_devices, &physical_device));
// Pick the first queue with graphics support.
uint32_t queue_family_index = 0, num_queue_families = 0;
VK_CALL_INS(vkGetPhysicalDeviceQueueFamilyProperties, instance, physical_device, &num_queue_families, nullptr);
std::vector<VkQueueFamilyProperties> queue_families(num_queue_families);
VK_CALL_INS(vkGetPhysicalDeviceQueueFamilyProperties, instance, physical_device, &num_queue_families, queue_families.data());
for (uint32_t index = 0; index < num_queue_families && (queue_families[index].queueFlags & VK_QUEUE_GRAPHICS_BIT) == 0; ++index)
queue_family_index = index;
{ VkDeviceQueueCreateInfo queue_info { VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO };
queue_info.queueCount = 1;
queue_info.queueFamilyIndex = queue_family_index;
float queue_priority = 1.0f;
queue_info.pQueuePriorities = &queue_priority;
const char *const enabled_layers[] = {
# if VK_HEADER_VERSION >= 106
"VK_LAYER_KHRONOS_validation"
# else
"VK_LAYER_LUNARG_standard_validation"
# endif
};
const char *const enabled_extensions[] = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
VkDeviceCreateInfo create_info { VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO };
create_info.queueCreateInfoCount = 1;
create_info.pQueueCreateInfos = &queue_info;
create_info.enabledLayerCount = ARRAYSIZE(enabled_layers);
create_info.ppEnabledLayerNames = enabled_layers;
create_info.enabledExtensionCount = ARRAYSIZE(enabled_extensions);
create_info.ppEnabledExtensionNames = enabled_extensions;
VK_CHECK(VK_CALL_INS(vkCreateDevice, instance, physical_device, &create_info, nullptr, &device));
}
{ VkWin32SurfaceCreateInfoKHR create_info { VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR };
create_info.hinstance = hInstance;
create_info.hwnd = window_handle;
VK_CHECK(VK_CALL_INS(vkCreateWin32SurfaceKHR, instance, instance, &create_info, nullptr, &surface));
// Check presentation support to make validation layers happy
VkBool32 supported = VK_FALSE;
VK_CHECK(VK_CALL_INS(vkGetPhysicalDeviceSurfaceSupportKHR, instance, physical_device, queue_family_index, surface, &supported));
assert(VK_FALSE != supported);
}
VkQueue queue = VK_NULL_HANDLE;
VK_CALL_DEV(vkGetDeviceQueue, device, queue_family_index, 0, &queue);
VkCommandPool cmd_alloc = VK_NULL_HANDLE;
std::vector<VkCommandBuffer> cmd_list;
{ VkCommandPoolCreateInfo create_info { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO };
create_info.queueFamilyIndex = queue_family_index;
VK_CHECK(VK_CALL_DEV(vkCreateCommandPool, device, &create_info, nullptr, &cmd_alloc));
}
const auto resize_swapchain = [&](VkSwapchainKHR old_swapchain = VK_NULL_HANDLE) {
uint32_t num_present_modes = 0, num_surface_formats = 0;
VK_CALL_INS(vkGetPhysicalDeviceSurfaceFormatsKHR, instance, physical_device, surface, &num_surface_formats, nullptr);
VK_CALL_INS(vkGetPhysicalDeviceSurfacePresentModesKHR, instance, physical_device, surface, &num_present_modes, nullptr);
std::vector<VkPresentModeKHR> present_modes(num_present_modes);
std::vector<VkSurfaceFormatKHR> surface_formats(num_surface_formats);
VK_CALL_INS(vkGetPhysicalDeviceSurfaceFormatsKHR, instance, physical_device, surface, &num_surface_formats, surface_formats.data());
VK_CALL_INS(vkGetPhysicalDeviceSurfacePresentModesKHR, instance, physical_device, surface, &num_present_modes, present_modes.data());
VkSurfaceCapabilitiesKHR capabilities = {};
VK_CALL_INS(vkGetPhysicalDeviceSurfaceCapabilitiesKHR, instance, physical_device, surface, &capabilities);
VkSwapchainCreateInfoKHR create_info { VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR };
create_info.surface = surface;
create_info.minImageCount = 3;
create_info.imageFormat = surface_formats[0].format;
create_info.imageColorSpace = surface_formats[0].colorSpace;
create_info.imageExtent = capabilities.currentExtent;
create_info.imageArrayLayers = 1;
create_info.imageUsage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
create_info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
create_info.preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
create_info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
create_info.presentMode = present_modes[0];
create_info.clipped = VK_TRUE;
create_info.oldSwapchain = old_swapchain;
VK_CHECK(VK_CALL_DEV(vkCreateSwapchainKHR, device, &create_info, nullptr, &swapchain));
if (old_swapchain != VK_NULL_HANDLE)
VK_CALL_DEV(vkDestroySwapchainKHR, device, old_swapchain, nullptr);
VK_CALL_DEV(vkFreeCommandBuffers, device, cmd_alloc, uint32_t(cmd_list.size()), cmd_list.data());
uint32_t num_swapchain_images = 0;
VK_CHECK(VK_CALL_DEV(vkGetSwapchainImagesKHR, device, swapchain, &num_swapchain_images, nullptr));
std::vector<VkImage> swapchain_images(num_swapchain_images);
VK_CHECK(VK_CALL_DEV(vkGetSwapchainImagesKHR, device, swapchain, &num_swapchain_images, swapchain_images.data()));
cmd_list.resize(num_swapchain_images);
{ VkCommandBufferAllocateInfo alloc_info { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO };
alloc_info.commandPool = cmd_alloc;
alloc_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
alloc_info.commandBufferCount = num_swapchain_images;
VK_CHECK(VK_CALL_DEV(vkAllocateCommandBuffers, device, &alloc_info, cmd_list.data()));
}
for (uint32_t i = 0; i < num_swapchain_images; ++i)
{
VkCommandBufferBeginInfo begin_info { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO };
begin_info.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT;
VK_CHECK(VK_CALL_CMD(vkBeginCommandBuffer, device, cmd_list[i], &begin_info));
const VkImageSubresourceRange range = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 };
VkImageMemoryBarrier transition { VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER };
transition.srcAccessMask = 0;
transition.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
transition.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
transition.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
transition.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
transition.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
transition.image = swapchain_images[i];
transition.subresourceRange = range;
VK_CALL_CMD(vkCmdPipelineBarrier, device, cmd_list[i], VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 0, nullptr, 0, nullptr, 1, &transition);
const VkClearColorValue color = { 0.5f, 0.5f, 0.5f, 1.0f };
VK_CALL_CMD(vkCmdClearColorImage, device, cmd_list[i], swapchain_images[i], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &color, 1, &range);
transition.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
transition.dstAccessMask = 0;
transition.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
transition.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
VK_CALL_CMD(vkCmdPipelineBarrier, device, cmd_list[i], VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 0, nullptr, 0, nullptr, 1, &transition);
VK_CHECK(VK_CALL_CMD(vkEndCommandBuffer, device, cmd_list[i]));
}
};
resize_swapchain();
VkSemaphore sem_acquire = VK_NULL_HANDLE;
VkSemaphore sem_present = VK_NULL_HANDLE;
{ VkSemaphoreCreateInfo create_info { VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO };
VK_CHECK(VK_CALL_DEV(vkCreateSemaphore, device, &create_info, nullptr, &sem_acquire));
VK_CHECK(VK_CALL_DEV(vkCreateSemaphore, device, &create_info, nullptr, &sem_present));
}
while (true)
{
while (msg.message != WM_QUIT &&
PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE))
DispatchMessage(&msg);
if (msg.message == WM_QUIT)
break;
if (s_resize_w != 0)
{
resize_swapchain(swapchain);
s_resize_w = s_resize_h = 0;
}
uint32_t swapchain_image_index = 0;
VkResult present_res = VK_CALL_DEV(vkAcquireNextImageKHR, device, swapchain, UINT64_MAX, sem_acquire, VK_NULL_HANDLE, &swapchain_image_index);
if (present_res == VK_SUCCESS)
{
VkSubmitInfo submit_info { VK_STRUCTURE_TYPE_SUBMIT_INFO };
submit_info.waitSemaphoreCount = 1;
VkPipelineStageFlags wait_mask = VK_PIPELINE_STAGE_TRANSFER_BIT;
submit_info.pWaitDstStageMask = &wait_mask;
submit_info.pWaitSemaphores = &sem_acquire;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &cmd_list[swapchain_image_index];
submit_info.signalSemaphoreCount = 1;
submit_info.pSignalSemaphores = &sem_present;
VK_CHECK(VK_CALL_CMD(vkQueueSubmit, device, queue, 1, &submit_info, VK_NULL_HANDLE));
VkPresentInfoKHR present_info { VK_STRUCTURE_TYPE_PRESENT_INFO_KHR };
present_info.waitSemaphoreCount = 1;
present_info.pWaitSemaphores = &sem_present;
present_info.swapchainCount = 1;
present_info.pSwapchains = &swapchain;
present_info.pImageIndices = &swapchain_image_index;
present_res = VK_CALL_CMD(vkQueuePresentKHR, device, queue, &present_info);
}
// Ignore out of date errors during presentation, since swapchain will be recreated on next minimize/maximize event anyway
if (present_res != VK_SUBOPTIMAL_KHR && present_res != VK_ERROR_OUT_OF_DATE_KHR)
VK_CHECK(present_res);
}
// Wait for all GPU work to finish before destroying objects
VK_CALL_DEV(vkDeviceWaitIdle, device);
VK_CALL_DEV(vkDestroySemaphore, device, sem_acquire, nullptr);
VK_CALL_DEV(vkDestroySemaphore, device, sem_present, nullptr);
VK_CALL_DEV(vkFreeCommandBuffers, device, cmd_alloc, uint32_t(cmd_list.size()), cmd_list.data());
VK_CALL_DEV(vkDestroyCommandPool, device, cmd_alloc, nullptr);
VK_CALL_DEV(vkDestroySwapchainKHR, device, swapchain, nullptr);
VK_CALL_INS(vkDestroySurfaceKHR, instance, instance, surface, nullptr);
VK_CALL_INS(vkDestroyDevice, instance, device, nullptr);
VK_CALL_INS(vkDestroyInstance, instance, instance, nullptr);
reshade::hooks::uninstall();
FreeLibrary(vulkan_module);
return static_cast<int>(msg.wParam);
}
#pragma endregion
return EXIT_FAILURE;
}
#else
# ifndef NDEBUG
#include <DbgHelp.h>
static PVOID g_exception_handler_handle = nullptr;
# endif
// Export special symbol to identify modules as ReShade instances
extern "C" __declspec(dllexport) const char *ReShadeVersion = VERSION_STRING_PRODUCT;
BOOL APIENTRY DllMain(HMODULE hModule, DWORD fdwReason, LPVOID)
{
using namespace reshade;
switch (fdwReason)
{
case DLL_PROCESS_ATTACH:
g_module_handle = hModule;
g_reshade_dll_path = get_module_path(hModule);
g_target_executable_path = get_module_path(nullptr);
log::open(std::filesystem::path(g_reshade_dll_path).replace_extension(".log"));
# ifdef WIN64
LOG(INFO) << "Initializing crosire's ReShade version '" VERSION_STRING_FILE "' (64-bit) built on '" VERSION_DATE " " VERSION_TIME "' loaded from " << g_reshade_dll_path << " into " << g_target_executable_path << " ...";
# else
LOG(INFO) << "Initializing crosire's ReShade version '" VERSION_STRING_FILE "' (32-bit) built on '" VERSION_DATE " " VERSION_TIME "' loaded from " << g_reshade_dll_path << " into " << g_target_executable_path << " ...";
# endif
# ifndef NDEBUG
g_exception_handler_handle = AddVectoredExceptionHandler(1, [](PEXCEPTION_POINTERS ex) -> LONG {
// Ignore debugging exceptions
if (const DWORD code = ex->ExceptionRecord->ExceptionCode;
code == CONTROL_C_EXIT || code == 0x406D1388 /* SetThreadName */ ||
code == DBG_PRINTEXCEPTION_C || code == DBG_PRINTEXCEPTION_WIDE_C)
goto continue_search;
// Create dump with exception information for the first 100 occurrences
if (static unsigned int dump_index = 0;
++dump_index < 100)
{
// Call into the original "LoadLibrary" directly, to avoid failing memory corruption checks
extern HMODULE WINAPI HookLoadLibraryA(LPCSTR lpFileName);
const auto ll = reshade::hooks::call(HookLoadLibraryA);
if (ll == nullptr)
goto continue_search;
const auto dbghelp = ll("dbghelp.dll");
if (dbghelp == nullptr)
goto continue_search;
const auto dbghelp_write_dump = reinterpret_cast<BOOL(WINAPI *)(HANDLE, DWORD, HANDLE, MINIDUMP_TYPE, PMINIDUMP_EXCEPTION_INFORMATION, PMINIDUMP_USER_STREAM_INFORMATION, PMINIDUMP_CALLBACK_INFORMATION)>(
GetProcAddress(dbghelp, "MiniDumpWriteDump"));
if (dbghelp_write_dump == nullptr)
goto continue_search;
char dump_name[] = "exception_00.dmp";
dump_name[10] = '0' + static_cast<char>(dump_index / 10);
dump_name[11] = '0' + static_cast<char>(dump_index % 10);
const HANDLE file = CreateFileA(dump_name, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (file == INVALID_HANDLE_VALUE)
goto continue_search;
MINIDUMP_EXCEPTION_INFORMATION info;
info.ThreadId = GetCurrentThreadId();
info.ExceptionPointers = ex;
info.ClientPointers = FALSE;
dbghelp_write_dump(GetCurrentProcess(), GetCurrentProcessId(), file, MiniDumpNormal, &info, nullptr, nullptr);
CloseHandle(file);
}
continue_search:
return EXCEPTION_CONTINUE_SEARCH;
});
# endif
// Check if another ReShade instance was already loaded into the process
if (HMODULE modules[1024]; K32EnumProcessModules(GetCurrentProcess(), modules, sizeof(modules), &fdwReason)) // Use kernel32 variant which is available in DllMain
{
for (DWORD i = 0; i < std::min<DWORD>(fdwReason / sizeof(HMODULE), ARRAYSIZE(modules)); ++i)
{
if (modules[i] != hModule && GetProcAddress(modules[i], "ReShadeVersion") != nullptr)
{
LOG(WARN) << "Another ReShade instance was already loaded from " << get_module_path(modules[i]) << "! Aborting initialization ...";
return FALSE; // Make the "LoadLibrary" call that loaded this instance fail
}
}
}
hooks::register_module("user32.dll");
hooks::register_module("ws2_32.dll");
hooks::register_module(get_system_path() / "d2d1.dll");
hooks::register_module(get_system_path() / "d3d9.dll");
hooks::register_module(get_system_path() / "d3d10.dll");
hooks::register_module(get_system_path() / "d3d10_1.dll");
hooks::register_module(get_system_path() / "d3d11.dll");
hooks::register_module(get_system_path() / "d3d12.dll");
hooks::register_module(get_system_path() / "dxgi.dll");
hooks::register_module(get_system_path() / "opengl32.dll");
// Do not register Vulkan hooks, since Vulkan layering mechanism is used instead
LOG(INFO) << "Initialized.";
break;
case DLL_PROCESS_DETACH:
LOG(INFO) << "Exiting ...";
hooks::uninstall();
# ifndef NDEBUG
RemoveVectoredExceptionHandler(g_exception_handler_handle);
# endif
LOG(INFO) << "Finished exiting.";
break;
}
return TRUE;
}
#endif