forked from praydog/REFramework
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathREFramework.cpp
More file actions
2511 lines (1986 loc) · 85.2 KB
/
REFramework.cpp
File metadata and controls
2511 lines (1986 loc) · 85.2 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
#include <chrono>
#include <filesystem>
#include <fstream>
#include <windows.h>
#include <ShlObj.h>
#include <initguid.h>
#include <Dbt.h>
#include <spdlog/sinks/basic_file_sink.h>
// minhook, used for AllocateBuffer
extern "C" {
#include <../buffer.h>
};
#include <imgui.h>
#include <imgui_freetype.h>
#include <ImGuizmo.h>
#include <imnodes.h>
#include "re2-imgui/af_faprolight.hpp"
#include "re2-imgui/font_robotomedium.hpp"
#include "re2-imgui/imgui_impl_dx11.h"
#include "re2-imgui/imgui_impl_dx12.h"
#include "re2-imgui/imgui_impl_win32.h"
#include "utility/Module.hpp"
#include "utility/Patch.hpp"
#include "utility/Scan.hpp"
#include "utility/Thread.hpp"
#include "Mods.hpp"
#include "mods/LooseFileLoader.hpp"
#include "mods/PluginLoader.hpp"
#include "mods/VR.hpp"
#include "sdk/REGlobals.hpp"
#include "sdk/Application.hpp"
#include "sdk/SDK.hpp"
#include "ExceptionHandler.hpp"
#include "LicenseStrings.hpp"
#include "mods/REFrameworkConfig.hpp"
#include "mods/IntegrityCheckBypass.hpp"
#include "CommitHash.autogenerated"
#include "REFramework.hpp"
namespace fs = std::filesystem;
using namespace std::literals;
extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
DEFINE_GUID(GUID_DEVINTERFACE_HID, 0x4D1E55B2L, 0xF16F, 0x11CF, 0x88, 0xCB, 0x00, 0x11, 0x11, 0x00, 0x00, 0x30);
DEFINE_GUID(XUSB_INTERFACE_CLASS_GUID, 0xEC87F1E3, 0xC13B, 0x4100, 0xB5, 0xF7, 0x8B, 0x84, 0xD5, 0x42, 0x60, 0xCB);
std::unique_ptr<REFramework> g_framework{};
void REFramework::hook_monitor() {
if (m_do_not_hook_d3d_count.load() > 0) {
// Wait until nothing important is happening
m_last_present_time = std::chrono::steady_clock::now() + std::chrono::seconds(5);
m_last_chance_time = std::chrono::steady_clock::now() + std::chrono::seconds(1);
m_has_last_chance = true;
return;
}
if (!m_hook_monitor_mutex.try_lock()) {
// If this happens then we can assume execution is going as planned
// so we can just reset the times so we dont break something
m_last_present_time = std::chrono::steady_clock::now() + std::chrono::seconds(5);
m_last_chance_time = std::chrono::steady_clock::now() + std::chrono::seconds(1);
m_has_last_chance = true;
return;
}
// Take ownership of the mutex with adopt_lock
std::lock_guard _{ m_hook_monitor_mutex, std::adopt_lock };
if (g_framework == nullptr) {
return;
}
const auto now = std::chrono::steady_clock::now();
auto& d3d11 = get_d3d11_hook();
auto& d3d12 = get_d3d12_hook();
const auto renderer_type = get_renderer_type();
if (d3d11 == nullptr || d3d12 == nullptr
|| (renderer_type == REFramework::RendererType::D3D11 && d3d11 != nullptr && !d3d11->is_inside_present())
|| (renderer_type == REFramework::RendererType::D3D12 && d3d12 != nullptr && !d3d12->is_inside_present()))
{
// check if present time is more than 5 seconds ago
if (now - m_last_present_time > std::chrono::seconds(5)) {
if (m_has_last_chance) {
// the purpose of this is to make sure that the game is not frozen
// e.g. if we are debugging the game, so we don't rehook anything on accident
m_has_last_chance = false;
m_last_chance_time = now;
spdlog::info("Last chance encountered for hooking");
}
if (!m_has_last_chance && now - m_last_chance_time > std::chrono::seconds(1)) {
spdlog::info("Sending rehook request for D3D");
// hook_d3d12 always gets called first.
if (m_is_d3d11) {
hook_d3d11();
} else {
hook_d3d12();
}
// so we don't immediately go and hook it again
// add some additional time to it to give it some leeway
m_last_present_time = std::chrono::steady_clock::now() + std::chrono::seconds(5);
m_last_message_time = std::chrono::steady_clock::now() + std::chrono::seconds(5);
m_last_chance_time = std::chrono::steady_clock::now() + std::chrono::seconds(1);
m_has_last_chance = true;
}
} else {
m_last_chance_time = std::chrono::steady_clock::now();
m_has_last_chance = true;
}
if (m_initialized && m_wnd != 0 && now - m_last_message_time > std::chrono::seconds(5)) {
if (m_windows_message_hook != nullptr && m_windows_message_hook->is_hook_intact()) {
spdlog::info("Windows message hook is still intact, ignoring...");
m_last_message_time = now;
m_last_sendmessage_time = now;
m_sent_message = false;
return;
}
// send dummy message to window to check if our hook is still intact
if (!m_sent_message) {
spdlog::info("Sending initial message hook test");
auto proc = (WNDPROC)GetWindowLongPtr(m_wnd, GWLP_WNDPROC);
if (proc != nullptr) {
const auto ret = CallWindowProc(proc, m_wnd, WM_NULL, 0, 0);
spdlog::info("Hook test message sent");
}
m_last_sendmessage_time = std::chrono::steady_clock::now();
m_sent_message = true;
} else if (now - m_last_sendmessage_time > std::chrono::seconds(1)) {
spdlog::info("Sending reinitialization request for message hook");
// if we don't get a message for 5 seconds, assume the hook is broken
//m_initialized = false; // causes the hook to be re-initialized next frame
m_message_hook_requested = true;
m_last_message_time = std::chrono::steady_clock::now() + std::chrono::seconds(5);
m_last_present_time = std::chrono::steady_clock::now() + std::chrono::seconds(5);
m_sent_message = false;
}
} else {
m_sent_message = false;
}
}
}
typedef struct _LDR_DLL_UNLOADED_NOTIFICATION_DATA {
ULONG Flags; //Reserved.
PCUNICODE_STRING FullDllName; //The full path name of the DLL module.
PCUNICODE_STRING BaseDllName; //The base file name of the DLL module.
PVOID DllBase; //A pointer to the base address for the DLL in memory.
ULONG SizeOfImage; //The size of the DLL image, in bytes.
} LDR_DLL_UNLOADED_NOTIFICATION_DATA, *PLDR_DLL_UNLOADED_NOTIFICATION_DATA;
typedef struct _LDR_DLL_LOADED_NOTIFICATION_DATA {
ULONG Flags; //Reserved.
PCUNICODE_STRING FullDllName; //The full path name of the DLL module.
PCUNICODE_STRING BaseDllName; //The base file name of the DLL module.
PVOID DllBase; //A pointer to the base address for the DLL in memory.
ULONG SizeOfImage; //The size of the DLL image, in bytes.
} LDR_DLL_LOADED_NOTIFICATION_DATA, *PLDR_DLL_LOADED_NOTIFICATION_DATA;
typedef union _LDR_DLL_NOTIFICATION_DATA {
LDR_DLL_LOADED_NOTIFICATION_DATA Loaded;
LDR_DLL_UNLOADED_NOTIFICATION_DATA Unloaded;
} LDR_DLL_NOTIFICATION_DATA, *PLDR_DLL_NOTIFICATION_DATA;
using PLDR_DLL_NOTIFICATION_FUNCTION = void (*)(
ULONG NotificationReason,
PLDR_DLL_NOTIFICATION_DATA NotificationData,
PVOID Context
);
using LdrRegisterDllNotification_t = NTSTATUS (*) (
ULONG Flags,
PLDR_DLL_NOTIFICATION_FUNCTION NotificationFunction,
PVOID Context,
PVOID *Cookie
);
#define LDR_DLL_NOTIFICATION_REASON_LOADED 1
#define LDR_DLL_NOTIFICATION_REASON_UNLOADED 2
std::optional<std::filesystem::path> g_current_game_path{};
bool g_success_made_ldr_notification{false};
void CALLBACK ldr_notification_callback(
ULONG NotificationReason,
PLDR_DLL_NOTIFICATION_DATA NotificationData,
PVOID Context
)
try {
// From what I can tell, the PEB entries get filled in by the time this is called
// so we're good.
if (NotificationReason == LDR_DLL_NOTIFICATION_REASON_LOADED) {
if (NotificationData->Loaded.BaseDllName != nullptr && NotificationData->Loaded.BaseDllName->Buffer != nullptr) {
std::wstring base_dll_name = NotificationData->Loaded.BaseDllName->Buffer;
std::wstring lower_base_dll_name = base_dll_name;
std::transform(lower_base_dll_name.begin(), lower_base_dll_name.end(), lower_base_dll_name.begin(), ::towlower);
spdlog::info("LdrRegisterDllNotification: Loaded: {}", utility::narrow(base_dll_name));
if (lower_base_dll_name.find(L"sl.dlss_g.dll") != std::wstring::npos) {
spdlog::info("LdrRegisterDllNotification: Detected DLSS DLL loaded");
D3D12Hook::hook_streamline((HMODULE)NotificationData->Loaded.DllBase);
}
}
if (g_current_game_path && NotificationData->Loaded.FullDllName != nullptr && NotificationData->Loaded.FullDllName->Buffer != nullptr) {
std::wstring full_dll_name = NotificationData->Loaded.FullDllName->Buffer;
std::filesystem::path full_dll_path = full_dll_name;
if (full_dll_path.parent_path() == *g_current_game_path) {
spdlog::info("LdrRegisterDllNotification: DLL loaded from game directory: {}", utility::narrow(full_dll_name));
#if defined(DD2) || defined(MHRISE) || TDB_VER >= 74
utility::spoof_module_paths_in_exe_dir();
#endif
}
} else {
spdlog::info("LdrRegisterDllNotification: DLL loaded from unknown location");
}
}
} catch (const std::exception& e) {
spdlog::error("ldr_notification_callback: Exception occurred: {}", e.what());
} catch(...) {
spdlog::error("ldr_notification_callback: Unknown exception occurred");
}
REFramework::REFramework(HMODULE reframework_module)
: m_game_module{GetModuleHandle(0)}
, m_logger{spdlog::basic_logger_mt("REFramework", (get_persistent_dir("re2_framework_log.txt")).string(), true)}
{
s_reframework_module = reframework_module;
std::scoped_lock __{m_startup_mutex};
spdlog::set_default_logger(m_logger);
spdlog::flush_on(spdlog::level::info);
if (s_fallback_appdata) {
spdlog::warn("Failed to write to current directory, falling back to appdata folder");
}
spdlog::info("REFramework entry");
spdlog::info("Commit hash: {}", REF_COMMIT_HASH);
spdlog::info("Tag: {}", REF_TAG);
spdlog::info("Commits past tag: {}", REF_COMMITS_PAST_TAG);
spdlog::info("Branch: {}", REF_BRANCH);
spdlog::info("Total commits: {}", REF_TOTAL_COMMITS);
spdlog::info("Build date: {}", REF_BUILD_DATE);
spdlog::info("Build time: {}", REF_BUILD_TIME);
spdlog::info("Game name: {}", REFramework::get_game_name());
const auto module_size = *utility::get_module_size(m_game_module);
spdlog::info("Game Module Addr: {:x}", (uintptr_t)m_game_module);
spdlog::info("Game Module Size: {:x}", module_size);
if (auto current_game_path = utility::get_module_pathw(m_game_module); current_game_path.has_value()) {
g_current_game_path = *current_game_path;
g_current_game_path = g_current_game_path->parent_path();
spdlog::info("Current game path: {}", utility::narrow(g_current_game_path->c_str()));
}
// preallocate some memory for minhook to mitigate failures (temporarily at least... this should in theory fail when too many hooks are made)
// but, 64 slots should be enough for now.
// so... TODO: modify minhook to use absolute jumps when failing to allocate memory nearby
const auto halfway_module = (uintptr_t)m_game_module + (module_size / 2);
const auto pre_allocated_buffer = (uintptr_t)AllocateBuffer((LPVOID)halfway_module); // minhook function
spdlog::info("Preallocated buffer: {:x}", pre_allocated_buffer);
IntegrityCheckBypass::fix_virtual_protect();
IMGUI_CHECKVERSION();
ImGui::CreateContext();
#ifdef DEBUG
spdlog::set_level(spdlog::level::debug);
#endif
// Create the typedef for RtlGetVersion
typedef LONG (*RtlGetVersionFunc)(PRTL_OSVERSIONINFOW);
const auto ntdll = GetModuleHandle("ntdll.dll");
if (ntdll != nullptr) {
// Manually get RtlGetVersion
auto rtl_get_version = (RtlGetVersionFunc)GetProcAddress(ntdll, "RtlGetVersion");
if (rtl_get_version != nullptr) {
spdlog::info("Getting OS version information...");
// Create an initial log that prints out the user's Windows OS version information
// With the major and minor version numbers
// Using RtlGetVersion()
OSVERSIONINFOW os_version_info{};
ZeroMemory(&os_version_info, sizeof(OSVERSIONINFOW));
os_version_info.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
os_version_info.dwMajorVersion = 0;
os_version_info.dwMinorVersion = 0;
os_version_info.dwBuildNumber = 0;
os_version_info.dwPlatformId = 0;
if (rtl_get_version(&os_version_info) != 0) {
spdlog::info("RtlGetVersion() failed");
} else {
// Log the Windows version information
spdlog::info("OS Version Information");
spdlog::info("\tMajor Version: {}", os_version_info.dwMajorVersion);
spdlog::info("\tMinor Version: {}", os_version_info.dwMinorVersion);
spdlog::info("\tBuild Number: {}", os_version_info.dwBuildNumber);
spdlog::info("\tPlatform Id: {}", os_version_info.dwPlatformId);
spdlog::info("Disclaimer: REFramework does not send this information to the developers or any other third party.");
spdlog::info("This information is only used to help with the development of REFramework.");
}
} else {
spdlog::info("RtlGetVersion() not found");
}
// Do this at least once before setting up our callback.
#if defined(DD2) || defined(MHRISE) || TDB_VER >= 74
// Pre-emptively copy all DLL files in the current game directory into our _storage_ directory.
if (g_current_game_path.has_value()) {
const auto dest_path = *g_current_game_path / "_storage_";
fs::create_directories(dest_path);
if (std::filesystem::exists(dest_path)) try {
std::error_code directory_ec{};
// Locate all DLL files in the current game directory
for (const auto& entry : fs::directory_iterator(*g_current_game_path, directory_ec)) try {
const auto entry_path = entry.path();
if (entry.is_regular_file() && entry_path.extension() == ".dll") {
spdlog::info("Copying DLL file: {}", entry_path.filename().string());
spdlog::info(" Full path: {}", entry_path.string());
const auto final_dest = dest_path / entry_path.filename().string();
spdlog::info(" Destination: {}", final_dest.string());
std::error_code ec{};
fs::copy_file(entry_path, final_dest, fs::copy_options::overwrite_existing, ec);
// check if error occurred
if (ec) {
spdlog::error("Failed to copy DLL file: {}", ec.message());
}
ec.clear();
}
} catch (const std::filesystem::filesystem_error& e) {
spdlog::error("Failed to copy DLL file: {}", e.what());
} catch (const std::exception& e) {
spdlog::error("Failed to copy DLL file: {}", e.what());
} catch(...) {
spdlog::error("Failed to copy DLL file: unknown exception occurred");
}
if (directory_ec) {
spdlog::error("An error occurred while traversing the game directory: {}", directory_ec.message());
}
// Copy the D3D12/D3D12Core.dll file from the current game directory into our _storage_ directory with the same subdirectory structure.
const auto d3d12_path = *g_current_game_path / "D3D12" / "D3D12Core.dll";
if (std::filesystem::exists(d3d12_path)) try {
spdlog::info("Copying D3D12Core.dll file");
fs::create_directories(dest_path / "D3D12");
if (std::filesystem::exists(d3d12_path)) {
spdlog::info("Copying D3D12Core.dll file");
std::error_code ec{};
fs::copy_file(d3d12_path, dest_path / "D3D12" / "D3D12Core.dll", fs::copy_options::overwrite_existing, ec);
if (ec) {
spdlog::error("Failed to copy D3D12Core.dll file: {}", ec.message());
}
ec.clear();
}
} catch (const std::filesystem::filesystem_error& e) {
spdlog::error("Failed to copy D3D12Core.dll file: {}", e.what());
} catch (const std::exception& e) {
spdlog::error("Failed to copy D3D12Core.dll file: {}", e.what());
} catch(...) {
spdlog::error("Failed to copy D3D12Core.dll file: unknown exception occurred");
}
} catch (const std::filesystem::filesystem_error& e) {
spdlog::error("An error occurred while copying DLL files: {}", e.what());
} catch (const std::exception& e) {
spdlog::error("An error occurred while copying DLL files: {}", e.what());
} catch(...) {
spdlog::error("An error occurred while copying DLL files: unknown exception occurred");
} else {
spdlog::error("Failed to create storage directory");
}
}
utility::spoof_module_paths_in_exe_dir();
#endif
// Register our LdrRegisterDllNotification callback
spdlog::info("Registering LdrRegisterDllNotification callback...");
const auto ldr_register_dll_notification = (LdrRegisterDllNotification_t)GetProcAddress(ntdll, "LdrRegisterDllNotification");
if (ldr_register_dll_notification != nullptr) {
PVOID cookie = nullptr;
g_success_made_ldr_notification = NT_SUCCESS(ldr_register_dll_notification(0, ldr_notification_callback, nullptr, &cookie));
if (g_success_made_ldr_notification) {
spdlog::info("LdrRegisterDllNotification callback registered successfully");
} else {
spdlog::info("LdrRegisterDllNotification callback failed to register");
}
} else {
spdlog::info("LdrRegisterDllNotification not found");
}
} else {
spdlog::info("ntdll.dll not found");
}
// wait for the game to load (WTF MHRISE??)
// once this is done, we can assume the process is unpacked.
#if defined (REENGINE_PACKED)
auto now = std::chrono::steady_clock::now();
std::chrono::steady_clock::time_point next_log = now;
while (GetModuleHandleA("d3d12.dll") == nullptr) {
now = std::chrono::steady_clock::now();
if (now >= next_log) {
spdlog::info("[REFramework] Waiting for D3D12...");
next_log = now + 1s;
}
Sleep(50);
}
while (LoadLibraryA("d3d12.dll") == nullptr) {
if (now >= next_log) {
spdlog::info("[REFramework] Waiting for D3D12...");
next_log = now + 1s;
}
}
spdlog::info("D3D12 loaded");
#endif
#if defined(MHRISE) || defined(DD2) || TDB_VER >= 74
utility::load_module_from_current_directory(L"openvr_api.dll");
utility::load_module_from_current_directory(L"openxr_loader.dll");
LoadLibraryA("dxgi.dll");
LoadLibraryA("d3d11.dll");
if (!g_success_made_ldr_notification) {
utility::spoof_module_paths_in_exe_dir();
}
#endif
#if defined(RE8)
auto startup_lookup_thread = std::make_unique<std::thread>([this]() {
// Fixes a crash on some machines when starting the game
// This one has nothing to do with integrity checks
// it has something to do with the Agility SDK and pipeline state.
uint32_t times_searched = 0;
auto startup_patch_addr = utility::scan(m_game_module, "40 53 57 48 83 ec 28 48 83 b9 ? ? ? ? 00");
while (!startup_patch_addr) {
startup_patch_addr = utility::scan(m_game_module, "40 53 57 48 83 ec 28 48 83 b9 ? ? ? ? 00");
if (times_searched++ > 10) {
spdlog::error("Failed to find startup patch address");
return;
}
}
if (startup_patch_addr) {
spdlog::info("Found startup patch at {:x}", *startup_patch_addr);
static auto permanent_patch = Patch::create(*startup_patch_addr, {0xC3});
} else {
spdlog::info("Couldn't find RE8 crash fix patch location!");
}
});
startup_lookup_thread->detach();
#endif
#if defined(REENGINE_AT)
utility::ThreadSuspender suspender{};
IntegrityCheckBypass::ignore_application_entries();
#if defined(RE8) || defined(RE4) || defined(SF6)
// Also done on RE4 because some of the scans are the same.
IntegrityCheckBypass::immediate_patch_re8();
#endif
#if defined(RE4) || defined(SF6)
// Fixes new code added in RE4 only.
IntegrityCheckBypass::immediate_patch_re4();
#endif
#if defined(DD2) || TDB_VER >= 74
// Fixes new code added in DD2 only. Maybe >= TDB73 too. Probably will change.
IntegrityCheckBypass::immediate_patch_dd2();
#endif
// Seen in SF6
IntegrityCheckBypass::remove_stack_destroyer();
suspender.resume();
#endif
// Load the plugins early right after executable unpacking
PluginLoader::get()->early_init();
// Wait for TDB and render device to be initialized before allowing D3D hooking
const auto start_time = std::chrono::high_resolution_clock::now();
while (true) {
try {
if (sdk::VM::get() != nullptr) {
break;
}
} catch(...) {
}
if (std::chrono::high_resolution_clock::now() - start_time > std::chrono::seconds(30)) {
spdlog::error("Timed out waiting for VM to initialize.");
throw std::runtime_error("Timed out waiting for VM to initialize.");
}
//std::this_thread::sleep_for(std::chrono::milliseconds(100));
std::this_thread::yield();
}
spdlog::info("VM initialized, waiting for renderer to initialize...");
sdk::RETypeDefinition* renderer_t = nullptr;
sdk::renderer::Renderer* renderer = nullptr;
bool found_renderer = false;
bool renderer_has_render_frame_fn = false;
if (sdk::RETypeDB::get() != nullptr) {
auto& loader = LooseFileLoader::get(); // Initialize this really early
auto &integrity_bypass = IntegrityCheckBypass::get_shared_instance();
const auto config_path = get_persistent_dir(REFrameworkConfig::REFRAMEWORK_CONFIG_NAME.data()).string();
if (fs::exists(utility::widen(config_path))) {
utility::Config cfg{ config_path };
loader->on_config_load(cfg);
integrity_bypass->on_config_load(cfg);
}
if (loader->is_enabled()) {
loader->hook();
}
}
while (true) try {
const auto tdb = sdk::RETypeDB::get();
if (tdb == nullptr) {
spdlog::error("TypeDB not found");
break;
}
// We have to manually look through the types because get_FullName
// will crash if we call it this early, which is used in get_type(name)
if (renderer_t == nullptr) {
for (auto i = 0; i < tdb->get_num_types(); ++i) {
const auto t = tdb->get_type(i);
if (t == nullptr || t->get_name() == nullptr || t->get_namespace() == nullptr) {
continue;
}
if (std::string_view{t->get_name()} == "Renderer" && std::string_view{t->get_namespace()} == "via.render") {
spdlog::info("Renderer type found manually @ {:x}", (uintptr_t)t);
renderer_t = t;
break;
}
}
}
if (renderer_t == nullptr) {
spdlog::error("Renderer type not found");
break;
}
renderer_has_render_frame_fn = renderer_t->get_method("get_RenderFrame") != nullptr;
const auto renderer_has_instance = renderer_t->get_method("hasInstance");
if (renderer_has_instance == nullptr) {
spdlog::error("Renderer::hasInstance not found");
break;
}
if (renderer_has_instance->get_function() == nullptr) {
continue;
}
const auto has_instance = renderer_has_instance->call<bool>(nullptr, nullptr); // static
if (!has_instance) {
std::this_thread::yield();
continue;
}
renderer = sdk::renderer::get_renderer();
if (renderer != nullptr) {
found_renderer = true;
break;
}
spdlog::info("waiting for renderer");
std::this_thread::sleep_for(std::chrono::milliseconds(100));
} catch(...) {
spdlog::warn("Exception occurred while waiting for renderer");
continue;
}
spdlog::info("Found renderer @ {:x} (type: {:x}), waiting for first frame...", (uintptr_t)renderer, (uintptr_t)renderer_t);
bool valid_render_frame = false;
if (renderer_has_render_frame_fn) {
spdlog::info("Renderer has get_RenderFrame function");
} else {
spdlog::info("Renderer does not have get_RenderFrame function");
}
while (renderer_has_render_frame_fn) try {
// This function is static so its fine if renderer is null.
const auto render_frame = renderer->get_render_frame();
if (!render_frame.has_value()) {
spdlog::warn("Render frame property not found");
break;
}
if (*render_frame > 0) {
spdlog::info("Render frame: {}", *render_frame);
valid_render_frame = true;
break;
}
std::this_thread::yield();
} catch(...) {
//spdlog::warn("Exception occurred while waiting for render frame");
continue;
}
// If all is good, we can immediately hook D3D12 very early
// else, defer to the hook monitor if anything in the chain failed
if (valid_render_frame) {
// We can guaranteed hook at this point
std::scoped_lock _{m_hook_monitor_mutex};
hook_d3d12();
}
std::scoped_lock _{m_hook_monitor_mutex};
m_last_present_time = std::chrono::steady_clock::now();
m_last_message_time = std::chrono::steady_clock::now();
m_d3d_monitor_thread = std::make_unique<std::jthread>([this](std::stop_token stop_token) {
while (!stop_token.stop_requested() && !m_terminating) {
this->hook_monitor();
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
});
}
bool REFramework::hook_d3d11() {
//if (m_d3d11_hook == nullptr) {
m_d3d11_hook.reset();
m_d3d11_hook = std::make_unique<D3D11Hook>();
m_d3d11_hook->on_present([this](D3D11Hook& hook) { on_frame_d3d11(); });
m_d3d11_hook->on_post_present([this](D3D11Hook& hook) { on_post_present_d3d11(); });
m_d3d11_hook->on_resize_buffers([this](D3D11Hook& hook) { on_reset(); });
//}
// Making sure D3D12 is not hooked
if (!m_is_d3d12) {
if (m_d3d11_hook->hook()) {
spdlog::info("Hooked DirectX 11");
m_valid = true;
m_is_d3d11 = true;
return true;
}
// We make sure to no unhook any unwanted hooks if D3D11 didn't get hooked properly
if (m_d3d11_hook->unhook()) {
spdlog::info("D3D11 unhooked!");
} else {
spdlog::info("Cannot unhook D3D11, this might crash.");
}
m_valid = false;
m_is_d3d11 = false;
return false;
}
return false;
}
bool REFramework::hook_d3d12() {
// windows 7?
if (LoadLibraryA("d3d12.dll") == nullptr) {
spdlog::info("d3d12.dll not found, user is probably running Windows 7.");
spdlog::info("Falling back to hooking D3D11.");
m_is_d3d12 = false;
return hook_d3d11();
}
//if (m_d3d12_hook == nullptr) {
m_d3d12_hook.reset();
m_d3d12_hook = std::make_unique<D3D12Hook>();
m_d3d12_hook->on_present([this](D3D12Hook& hook) { on_frame_d3d12(); });
m_d3d12_hook->on_post_present([this](D3D12Hook& hook) { on_post_present_d3d12(); });
m_d3d12_hook->on_resize_buffers([this](D3D12Hook& hook) { on_reset(); });
m_d3d12_hook->on_resize_target([this](D3D12Hook& hook) { on_reset(); });
//}
//m_d3d12_hook->on_create_swap_chain([this](D3D12Hook& hook) { m_d3d12.command_queue = m_d3d12_hook->get_command_queue(); });
// Making sure D3D11 is not hooked
if (!m_is_d3d11) {
if (m_d3d12_hook->hook()) {
spdlog::info("Hooked DirectX 12");
m_valid = true;
m_is_d3d12 = true;
return true;
}
// We make sure to no unhook any unwanted hooks if D3D12 didn't get hooked properly
if (m_d3d12_hook->unhook()) {
spdlog::info("D3D12 Unhooked!");
} else {
spdlog::info("Cannot unhook D3D12, this might crash.");
}
m_valid = false;
m_is_d3d12 = false;
// Try to hook d3d11 instead
return hook_d3d11();
}
return false;
}
REFramework::~REFramework() {
spdlog::info("REFramework shutting down...");
m_terminating = true;
m_d3d_monitor_thread->request_stop();
if (m_d3d_monitor_thread->joinable()) {
m_d3d_monitor_thread->join();
}
m_d3d_monitor_thread.reset();
if (m_is_d3d11) {
deinit_d3d11();
}
if (m_is_d3d12) {
deinit_d3d12();
}
ImGui_ImplWin32_Shutdown();
if (m_initialized) {
ImGui::DestroyContext();
}
}
void REFramework::run_imgui_frame(bool from_present) {
std::scoped_lock _{ m_imgui_mtx };
m_has_frame = false;
if (!m_initialized) {
return;
}
const bool is_init_ok = m_error.empty() && m_game_data_initialized;
consume_input();
init_fonts();
ImGui_ImplWin32_NewFrame();
// from_present is so we don't accidentally
// run script/game code within the present thread.
if (is_init_ok && !from_present) {
// Run mod frame callbacks.
m_mods->on_pre_imgui_frame();
}
ImGui::NewFrame();
if (!from_present) {
call_on_frame();
}
draw_ui();
m_last_draw_ui = m_draw_ui;
IMGUIZMO_NAMESPACE::BeginFrame();
ImGui::EndFrame();
ImGui::Render();
m_has_frame = true;
if (!from_present && m_wants_save_config) {
save_config();
m_wants_save_config = false;
}
}
// D3D11 Draw funciton
void REFramework::on_frame_d3d11() {
std::scoped_lock _{ m_imgui_mtx };
spdlog::debug("on_frame (D3D11)");
m_renderer_type = RendererType::D3D11;
if (!m_initialized) {
if (!initialize()) {
return;
}
spdlog::info("REFramework initialized");
m_initialized = true;
return;
}
if (m_message_hook_requested) {
initialize_windows_message_hook();
}
auto device = m_d3d11_hook->get_device();
if (device == nullptr) {
spdlog::error("D3D11 device was null when it shouldn't be, returning...");
m_initialized = false;
return;
}
bool is_init_ok = m_error.empty() && m_game_data_initialized;
if (is_init_ok) {
// Write default config once if it doesn't exist.
if (!std::exchange(m_created_default_cfg, true)) {
if (!fs::exists({utility::widen(get_persistent_dir(REFrameworkConfig::REFRAMEWORK_CONFIG_NAME.data()).string())})) {
save_config();
}
}
}
is_init_ok = first_frame_initialize();
if (!m_has_frame) {
if (!is_init_ok) {
init_fonts();
invalidate_device_objects();
ImGui_ImplDX11_NewFrame();
// hooks don't run until after initialization, so we just render the imgui window while initalizing.
run_imgui_frame(true);
} else {
return;
}
} else {
invalidate_device_objects();
ImGui_ImplDX11_NewFrame();
}
if (is_init_ok) {
m_mods->on_present();
}
ComPtr<ID3D11DeviceContext> context{};
float clear_color[]{0.0f, 0.0f, 0.0f, 0.0f};
m_d3d11_hook->get_device()->GetImmediateContext(&context);
context->ClearRenderTargetView(m_d3d11.blank_rt_rtv.Get(), clear_color);
// Only render this if VR is running.
// TODO: Instead use this as an SRV to render to the back buffer so we don't render twice.
if (VR::get()->is_hmd_active()) {
context->ClearRenderTargetView(m_d3d11.rt_rtv.Get(), clear_color);
context->OMSetRenderTargets(1, m_d3d11.rt_rtv.GetAddressOf(), NULL);
ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
}
// Set the back buffer to be the render target.
context->OMSetRenderTargets(1, m_d3d11.bb_rtv.GetAddressOf(), nullptr);
ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
if (is_init_ok) {
m_mods->on_post_frame();
}
}
void REFramework::on_post_present_d3d11() {
if (!m_error.empty() || !m_initialized || !m_game_data_initialized) {
if (m_last_present_time <= std::chrono::steady_clock::now()){
m_last_present_time = std::chrono::steady_clock::now();
}
return;
}
for (auto& mod : m_mods->get_mods()) {
mod->on_post_present();
}
if (m_last_present_time <= std::chrono::steady_clock::now()){
m_last_present_time = std::chrono::steady_clock::now();
}
}
// D3D12 Draw funciton
void REFramework::on_frame_d3d12() {
std::scoped_lock _{ m_imgui_mtx };
m_renderer_type = RendererType::D3D12;
auto command_queue = m_d3d12_hook->get_command_queue();
//spdlog::debug("on_frame (D3D12)");
if (!m_initialized) {
if (!initialize()) {
return;
}
spdlog::info("REFramework initialized");
m_initialized = true;
return;
}
if (command_queue == nullptr) {
spdlog::error("Null Command Queue");
return;
}
if (m_message_hook_requested) {
initialize_windows_message_hook();
}
auto device = m_d3d12_hook->get_device();
if (device == nullptr) {
spdlog::error("D3D12 Device was null when it shouldn't be, returning...");
m_initialized = false;
return;
}
bool is_init_ok = m_error.empty() && m_game_data_initialized;
if (is_init_ok) {
// Write default config once if it doesn't exist.
if (!std::exchange(m_created_default_cfg, true)) {
if (!fs::exists({utility::widen(get_persistent_dir(REFrameworkConfig::REFRAMEWORK_CONFIG_NAME.data()).string())})) {
save_config();
}
}
}
auto do_per_frame_thing = [&]() {
ImGui::GetIO().BackendRendererUserData = m_d3d12.imgui_backend_datas[0];
const auto prev_cleanup = m_wants_device_object_cleanup;
invalidate_device_objects();
ImGui_ImplDX12_NewFrame();
ImGui::GetIO().BackendRendererUserData = m_d3d12.imgui_backend_datas[1];
m_wants_device_object_cleanup = prev_cleanup;
invalidate_device_objects();
ImGui_ImplDX12_NewFrame();
};