Repository navigation
Expand file tree
/
Copy pathproxy.c
More file actions
392 lines (375 loc) · 20.1 KB
/
Copy pathproxy.c
File metadata and controls
392 lines (375 loc) · 20.1 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
// dinput8.dll proxy for Total War Saga: THRONES OF BRITANNIA (empire.retail.dll 64A47C87).
// empire.retail.dll imports DINPUT8.dll, so this loads before the game's own startup code runs.
// It installs the fixes ported from the Attila mod whose code matches ToB (see AGENT_LOG.md) and forwards the real
// DirectInput exports to the system dinput8.dll. Log: tobfix.log next to this DLL.
#include <windows.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include "version.h"
#include "logtrim.h"
typedef void (*log_fn)(const char *fmt, ...);
int install_heapfix(HMODULE m, log_fn log); // heapfix.c
int install_pool(HMODULE m, log_fn log); // pool.c
void pool_lookup_thread_exit(void); // pool.c
int install_memwatch(HMODULE m, void (*trim)(void), log_fn log); // memwatch.c
int load_plugins(const wchar_t *dir, log_fn log); // plugins.c
int install_fpslog(const wchar_t *dir); // fpslog.c
void fpslog_frame(void); // fpslog.c
int install_scriptext(HMODULE m, const wchar_t *dir, void (*log)(const char *fmt, ...)); // scriptext.c
void scriptext_frame(void); // scriptext.c
static int g_scriptext_on;
static int g_late_install; // install_all runs from the DLL load notification, not DllMain
extern int g_crash_logging; // diag.c
int install_sortfix(HMODULE m, log_fn log); // sortfix.c
int install_frame(HMODULE m, log_fn log); // frame.c
extern void (*g_frame_check)(void); // frame.c
int install_campfix(HMODULE m, log_fn log); // campfix.c
void campfix_frame(void); // campfix.c
int install_x87fix(HMODULE m, log_fn log); // x87fix.c
void x87fix_frame(void); // x87fix.c
int install_memfast(HMODULE m, log_fn log); // memfast.c
int install_loopfetch(HMODULE m, log_fn log); // loopfetch.c
int install_fileio(HMODULE m, log_fn log); // fileio.c
int install_attrcache(HMODULE m, int verify, log_fn log); // attrcache.c
int install_texfix(HMODULE m, int verify, log_fn log); // texfix.c
int install_uikeep(HMODULE m, log_fn log); // uikeep.c
void diag_startup(HMODULE empire, const wchar_t *log_path, log_fn log); // diag.c
void update_check(HMODULE self, log_fn log); // update.c
int install_bridgeprobe(HMODULE m, const wchar_t *dir, log_fn log); // bridgeprobe.c (the DLSS add-on)
static HMODULE g_self;
static wchar_t g_log_path[MAX_PATH];
// One line per game start that stands out in the log: version and date.
static void log_header(void) {
trim_log(g_log_path); // past 1 MB, the oldest sessions go (players must be able to post it)
FILE *f = _wfopen(g_log_path, L"a");
if (!f) return;
SYSTEMTIME t;
GetLocalTime(&t);
fprintf(f, "\n======== Thrones of Britannia Engine Performance Fix v%s - game started %04d-%02d-%02d %02d:%02d ========\n",
MOD_VERSION_STR, t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute);
fclose(f);
}
static void wlog(const char *fmt, ...) {
if (!g_log_path[0]) return;
char buf[4096];
SYSTEMTIME t;
GetLocalTime(&t);
int n = snprintf(buf, sizeof buf, "[%02d:%02d:%02d.%03d] ", t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
va_list a;
va_start(a, fmt);
int m = vsnprintf(buf + n, sizeof buf - n - 2, fmt, a);
va_end(a);
n += m < 0 ? 0 : m < (int)sizeof buf - n - 2 ? m : (int)sizeof buf - n - 3; // a longer line is cut
buf[n++] = '\r'; buf[n++] = '\n'; // as the text-mode file had it
log_append(g_log_path, buf, n); // logtrim.h: one atomic append, no file open per line (Attila round 2)
}
// ---- dinput8 forwarding (the real DLL is loaded on first use, never inside DllMain)
static HMODULE g_real;
static FARPROC real_proc(const char *name) {
if (!g_real) {
wchar_t path[MAX_PATH];
UINT n = GetSystemDirectoryW(path, MAX_PATH); // SysWOW64 for this 32-bit game
if (n == 0 || n > MAX_PATH - 14) return NULL;
wcscat(path, L"\\dinput8.dll");
g_real = LoadLibraryW(path);
if (!g_real) return NULL;
}
return GetProcAddress(g_real, name);
}
void (*g_dev_di8_created)(void *di); // the DLSS add-on's panel filters the game's mouse while open (fgpanel.c)
HRESULT WINAPI stub_DirectInput8Create(HINSTANCE h, DWORD v, REFIID r, LPVOID *o, LPUNKNOWN u) {
typedef HRESULT(WINAPI * fn)(HINSTANCE, DWORD, REFIID, LPVOID *, LPUNKNOWN);
fn f = (fn)real_proc("DirectInput8Create");
if (f && g_dev_di8_created) {
HRESULT hr = f(h, v, r, o, u);
if (SUCCEEDED(hr) && o && *o) g_dev_di8_created(*o);
return hr;
}
return f ? f(h, v, r, o, u) : E_FAIL;
}
HRESULT WINAPI stub_DllCanUnloadNow(void) {
typedef HRESULT(WINAPI * fn)(void);
fn f = (fn)real_proc("DllCanUnloadNow");
return f ? f() : S_FALSE;
}
HRESULT WINAPI stub_DllGetClassObject(REFCLSID c, REFIID r, LPVOID *o) {
typedef HRESULT(WINAPI * fn)(REFCLSID, REFIID, LPVOID *);
fn f = (fn)real_proc("DllGetClassObject");
return f ? f(c, r, o) : E_FAIL;
}
HRESULT WINAPI stub_DllRegisterServer(void) {
typedef HRESULT(WINAPI * fn)(void);
fn f = (fn)real_proc("DllRegisterServer");
return f ? f() : E_FAIL;
}
HRESULT WINAPI stub_DllUnregisterServer(void) {
typedef HRESULT(WINAPI * fn)(void);
fn f = (fn)real_proc("DllUnregisterServer");
return f ? f() : E_FAIL;
}
// The plain-language summary after the install lines (those stay as the details for bug reports).
enum { FIX_SWITCHED_OFF = -1, FIX_INACTIVE = 0, FIX_ON = 1, FIX_PARTLY = 2 };
enum { S_HEAP, S_POOL, S_SORTS, S_X87, S_COPY, S_PREFETCH, S_FILES, S_MISSING, S_TEXTURES, S_MENUS, NFIX };
static const char *const g_fix_names[NFIX] = {
"FPS: memory allocator (heap)", "FPS: small-object pools", "FPS: render-list sorts", "FPS: x87 rounding",
"FPS: small memory copies", "FPS: render-loop prefetch", "Loading: file reading", "Loading: missing-file cache",
"Loading: battle textures", "Menus: textures stay loaded (no stutter on reopening)"};
static void log_status(const int st[NFIX]) {
int on = 0;
for (int i = 0; i < NFIX; i++) on += st[i] == FIX_ON;
if (on == NFIX)
wlog("STATUS: all %d fixes are on", NFIX);
else
wlog("STATUS: %d of %d fixes are on", on, NFIX);
for (int i = 0; i < NFIX; i++)
wlog(" %-4s %s%s", st[i] == FIX_ON ? "on" : st[i] == FIX_PARTLY ? "part" : "OFF", g_fix_names[i],
st[i] == FIX_SWITCHED_OFF ? " (switched off in tobfix.ini, or by its _off.txt file)"
: st[i] == FIX_PARTLY ? " (only part of it fits this game version)"
: st[i] == FIX_INACTIVE ? " (does not fit this game version, so it stays off; details above)" : "");
}
static int g_campfix_on, g_x87fix_on;
// Per frame (frame.c): the frame counter / fps log, the rounding fixes' safety checks.
static void frame_checks(void) {
fpslog_frame();
if (g_scriptext_on) scriptext_frame();
if (g_campfix_on) campfix_frame();
if (g_x87fix_on) x87fix_frame();
}
// tobfix.ini in the game folder (Attila's heapfix.ini / Rome 2's rome2fix.ini, the same keys where the fix is the same):
// written once with the defaults when missing, never changed by the mod after that.
static wchar_t g_ini[MAX_PATH];
static const char INI_DEFAULTS[] =
"; Thrones of Britannia Engine Performance Fix settings. 1 = on, 0 = off. Restart the game after a change.\r\n"
"; The mod writes this file once with the defaults and never changes it. Delete it to get the defaults back.\r\n"
"; (The older way still works too: an empty <name>_off.txt file in the game folder switches that fix off.)\r\n"
"\r\n"
"[fixes]\r\n"
"; FPS\r\n"
"memory_allocator=1\r\n"
"small_object_pools=1\r\n"
"render_list_sorts=1\r\n"
"campaign_rounding=1\r\n"
"x87_rounding=1\r\n"
"small_memory_copies=1\r\n"
"render_loop_prefetch=1\r\n"
"; loading\r\n"
"file_reading=1\r\n"
"missing_file_cache=1\r\n"
"battle_textures=1\r\n"
"; menus\r\n"
"menu_textures=1\r\n"
"\r\n"
"[mod]\r\n"
"; copy a newer version from the Steam Workshop into the game folder at startup\r\n"
"self_update=1\r\n"
"; record crashes in tobfix.log (EXCEPTION lines)\r\n"
"crash_logging=1\r\n"
"; load other mods' DLLs from the plugins folder in the game folder (any name, e.g. plugins\\smoke.dll)\r\n"
"plugins=1\r\n"
"\r\n"
"; The DLSS add-on has its own settings: FrameBridge\\settings.txt (F8 in game).\r\n";
static void ini_create(void) {
HANDLE h = CreateFileW(g_ini, GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); // only when missing
if (h == INVALID_HANDLE_VALUE) return;
DWORD w;
WriteFile(h, INI_DEFAULTS, sizeof INI_DEFAULTS - 1, &w, NULL);
CloseHandle(h);
}
// numbers, or on / true / yes = 1 and off / false / no = 0 (GetPrivateProfileIntW reads "on" as 0 = the fix off;
// Attila's ultrareview 2026-11-02); anything else keeps the default
static int ini_int(const wchar_t *section, const wchar_t *key, int def) {
wchar_t v[32];
if (!g_ini[0] || !GetPrivateProfileStringW(section, key, L"", v, 32, g_ini)) return def;
if ((v[0] >= L'0' && v[0] <= L'9') || v[0] == L'-') return _wtoi(v);
static const wchar_t *const yes[3] = {L"on", L"true", L"yes"}, *const no[3] = {L"off", L"false", L"no"};
for (int i = 0; i < 3; i++) {
if (!_wcsicmp(v, yes[i])) return 1;
if (!_wcsicmp(v, no[i])) return 0;
}
return def;
}
// Installs everything into the game DLL m (mapped and relocated, its own startup code not run yet).
static void install_all(HMODULE m) {
int st[NFIX] = {0};
wchar_t f[MAX_PATH];
wchar_t *name = wcsrchr(g_log_path, L'\\') - g_log_path + f + 1;
wcscpy(f, g_log_path);
#define PRESENT(n) (wcscpy(name, n), GetFileAttributesW(f) != INVALID_FILE_ATTRIBUTES)
// Switches: tobfix.ini, or (older) empty <name>_off.txt files in the game folder.
wcscpy(g_ini, f);
wcscpy(g_ini + (name - f), L"tobfix.ini");
ini_create();
#define OFF(key, file) (!ini_int(L"fixes", key, 1) || PRESENT(file))
g_crash_logging = ini_int(L"mod", L"crash_logging", 1);
diag_startup(m, g_log_path, wlog); // version, process, game build, system, settings; crash records
if (g_crash_logging) install_memwatch(m, NULL, wlog); // failed file maps / allocations and low address space logged
if (ini_int(L"mod", L"self_update", 1))
update_check(g_self, wlog); // a newer Workshop copy replaces this DLL for the next launch
else
wlog("self-update off (self_update=0 in tobfix.ini)");
// The heap must go in before the game's first allocation, which is still to come here. mimalloc frees a thread's
// state when the thread ends, so thread notifications stay on while it is installed.
if (OFF(L"memory_allocator", L"heapfix_off.txt")) {
wlog("memory_allocator switched off (tobfix.ini or heapfix_off.txt) - heap not replaced");
st[S_HEAP] = FIX_SWITCHED_OFF;
} else
st[S_HEAP] = install_heapfix(m, wlog) > 0;
if (OFF(L"small_object_pools", L"pool_off.txt")) {
wlog("small_object_pools switched off (tobfix.ini or pool_off.txt) - pool lookup not patched");
st[S_POOL] = FIX_SWITCHED_OFF;
} else
st[S_POOL] = install_pool(m, wlog) > 0;
// thread notifications: mimalloc frees a thread's state, the pools their lookup cache (pool.c) when a thread ends
if (st[S_HEAP] != FIX_ON && st[S_POOL] != FIX_ON) DisableThreadLibraryCalls(g_self);
if (OFF(L"render_list_sorts", L"sortfix_off.txt")) {
wlog("render_list_sorts switched off (tobfix.ini or sortfix_off.txt) - render-list sorts not replaced");
st[S_SORTS] = FIX_SWITCHED_OFF;
} else {
int sorts = install_sortfix(m, wlog);
st[S_SORTS] = sorts == 2 ? FIX_ON : sorts ? FIX_PARTLY : FIX_INACTIVE;
}
// Rounding: the 4 campaign blocks first (the general x87 pattern matches them too), both checked every frame.
int frame = install_frame(m, wlog), camp = 0, x87 = 0;
wchar_t dir[MAX_PATH]; // the game folder
wcscpy(dir, f);
dir[name - f - 1] = 0;
if (frame) {
g_frame_check = frame_checks; // the frame counter for the crash records / freeze watchdog, and the fps log
if (install_fpslog(dir)) wlog("frame times to fps_log.csv (fps_on.txt found; delete it to stop)");
g_scriptext_on = install_scriptext(m, dir, wlog); // only with a lua_ext folder in the game folder
}
if (!frame)
wlog("x87 rounding fixes not installed (they need the frame hook)");
else if (OFF(L"campaign_rounding", L"x87fix_off.txt") && OFF(L"x87_rounding", L"x87fix_off.txt")) {
wlog("x87 rounding fixes switched off (tobfix.ini or x87fix_off.txt) - not installed");
st[S_X87] = FIX_SWITCHED_OFF;
} else {
if (OFF(L"campaign_rounding", L"x87fix_off.txt")) wlog("campaign rounding switched off (tobfix.ini) - not installed");
else g_campfix_on = (camp = install_campfix(m, wlog)) > 0;
if (OFF(L"x87_rounding", L"x87fix_off.txt")) wlog("x87 rounding switched off (tobfix.ini) - not installed");
else g_x87fix_on = (x87 = install_x87fix(m, wlog)) > 0;
st[S_X87] = x87 > 0 && camp == 4 ? FIX_ON : x87 > 0 || camp > 0 ? FIX_PARTLY : FIX_INACTIVE;
}
if (OFF(L"small_memory_copies", L"memfast_off.txt")) {
wlog("small_memory_copies switched off (tobfix.ini or memfast_off.txt) - memcpy fast path not installed");
st[S_COPY] = FIX_SWITCHED_OFF;
} else {
int n = install_memfast(m, wlog);
st[S_COPY] = n == 2 ? FIX_ON : n ? FIX_PARTLY : FIX_INACTIVE;
}
if (OFF(L"render_loop_prefetch", L"loopfetch_off.txt")) {
wlog("render_loop_prefetch switched off (tobfix.ini or loopfetch_off.txt) - render loop prefetch not installed");
st[S_PREFETCH] = FIX_SWITCHED_OFF;
} else {
int n = install_loopfetch(m, wlog);
st[S_PREFETCH] = n == 3 ? FIX_ON : n ? FIX_PARTLY : FIX_INACTIVE;
}
// Loading: packs through the file cache and buffered save reads (fileio.c), then the missing-folder cache
// (attrcache.c), whose open hook calls fileio's.
if (OFF(L"file_reading", L"fileio_off.txt")) {
wlog("file_reading switched off (tobfix.ini or fileio_off.txt) - file I/O fix not installed");
st[S_FILES] = FIX_SWITCHED_OFF;
} else
st[S_FILES] = install_fileio(m, wlog) > 0;
if (OFF(L"missing_file_cache", L"attrcache_off.txt")) {
wlog("missing_file_cache switched off (tobfix.ini or attrcache_off.txt) - attribute cache not installed");
st[S_MISSING] = FIX_SWITCHED_OFF;
} else {
int verify = 0;
#ifdef PROFILING
verify = PRESENT(L"attrcache_verify.txt"); // answer from Windows, count where the cache would differ
#endif
st[S_MISSING] = install_attrcache(m, verify, wlog) > 0;
}
if (OFF(L"battle_textures", L"texfix_off.txt")) {
wlog("battle_textures switched off (tobfix.ini or texfix_off.txt) - texture compression not replaced");
st[S_TEXTURES] = FIX_SWITCHED_OFF;
} else {
int verify = 0;
#ifdef PROFILING
verify = PRESENT(L"texfix_verify.txt"); // the game's compressor writes, ours is compared
#endif
st[S_TEXTURES] = install_texfix(m, verify, wlog) > 0;
}
if (OFF(L"menu_textures", L"uikeep_off.txt")) {
wlog("menu_textures switched off (tobfix.ini or uikeep_off.txt) - menu textures freed when closed, as the game does");
st[S_MENUS] = FIX_SWITCHED_OFF;
} else
st[S_MENUS] = install_uikeep(m, wlog) > 0;
log_status(st);
// the DLSS add-on (Upscaling and Framegen for Thrones of Britannia): <game>\FrameBridge\ with the 64-bit helper and
// NVIDIA's DLLs; without it, or with addon=off in its settings.txt, nothing is installed. Dev builds: also
// bridgeprobe.txt (the bridge capture probe, fgbridge_on.txt; dlss/DLSS_LOG.md)
int addon = PRESENT(L"FrameBridge\\helper64.exe");
if (addon) {
char text[4096] = {0}; // (1024 missed addon=off once the add-on's comment lines grew the file; Attila)
FILE *sf = PRESENT(L"FrameBridge\\settings.txt") ? _wfopen(f, L"r") : NULL;
if (sf) { fread(text, 1, sizeof text - 1, sf); fclose(sf); }
if (strstr(text, "\naddon=off") || !strncmp(text, "addon=off", 9)) {
wlog("DLSS add-on found but switched off (addon=off in FrameBridge\\settings.txt) - the game runs with the performance fix only");
addon = 0;
}
}
#ifdef PROFILING
if (PRESENT(L"bridgeprobe.txt")) addon = 1;
#endif
if (addon) install_bridgeprobe(m, dir, wlog);
// other mods' DLLs from <game>\\plugins (plugins.c), after every fix is in
if (!ini_int(L"mod", L"plugins", 1)) wlog("plugins off (plugins=0 in tobfix.ini)");
// from the load notification (another program loaded this DLL first) Windows refuses LoadLibrary (error 1168);
// later, on a thread, the game would already be running. shortcut: not loaded then (Attila: 0 of 5 player logs)
else if (g_late_install) {
wchar_t pd[MAX_PATH];
if (swprintf(pd, MAX_PATH, L"%ls\\plugins", dir) > 0 && GetFileAttributesW(pd) != INVALID_FILE_ATTRIBUTES)
wlog("plugins NOT loaded: another program loaded dinput8.dll before the game, and Windows allows no DLL loading "
"at that point - this game start runs without the plugins folder");
} else load_plugins(dir, wlog);
}
// Something else in the process (an overlay, another hook DLL) can load dinput8.dll before the game loads
// empire.retail.dll; Windows then never runs this DllMain again. So wait for the game DLL and install when it is
// mapped, which is still before its own startup code runs (the same state as the normal path).
typedef struct { USHORT Length, MaximumLength; PWSTR Buffer; } NOTIF_STR;
typedef struct { ULONG Flags; const NOTIF_STR *FullDllName, *BaseDllName; PVOID DllBase; ULONG SizeOfImage; } NOTIF_DATA;
static PVOID g_notif_cookie;
static VOID CALLBACK on_dll_loaded(ULONG reason, const NOTIF_DATA *d, PVOID ctx) {
(void)ctx;
static const wchar_t want[] = L"empire.retail.dll";
if (reason != 1 || !d || !d->BaseDllName || d->BaseDllName->Length != sizeof want - sizeof(wchar_t)) return;
if (_wcsnicmp(d->BaseDllName->Buffer, want, d->BaseDllName->Length / sizeof(wchar_t)) != 0) return;
wlog("empire.retail.dll is loading now - installing the fixes");
g_late_install = 1;
install_all((HMODULE)d->DllBase);
}
static int wait_for_game(void) {
typedef LONG(NTAPI * reg_fn)(ULONG, VOID(CALLBACK *)(ULONG, const NOTIF_DATA *, PVOID), PVOID, PVOID *);
reg_fn reg = (reg_fn)(void *)GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "LdrRegisterDllNotification");
return reg && reg(0, on_dll_loaded, NULL, &g_notif_cookie) == 0;
}
BOOL WINAPI DllMain(HINSTANCE h, DWORD reason, LPVOID r) {
(void)r;
if (reason == DLL_THREAD_DETACH) pool_lookup_thread_exit(); // the thread's pool lookup cache (pool.c)
if (reason != DLL_PROCESS_ATTACH) return TRUE;
g_self = h;
DWORD n = GetModuleFileNameW(h, g_log_path, MAX_PATH);
wchar_t *sl = wcsrchr(g_log_path, L'\\');
// room after the folder for the longest file name used (install_all's switch files and FrameBridge\settings.txt, up
// to 24 characters + NUL)
if (n == 0 || n >= MAX_PATH || !sl || sl - g_log_path > MAX_PATH - 32) { // no log path: do nothing
DisableThreadLibraryCalls(h);
return TRUE;
}
wcscpy(sl + 1, L"tobfix.log");
log_header();
HMODULE m = GetModuleHandleW(L"empire.retail.dll");
if (m)
install_all(m);
else if (wait_for_game())
wlog("dinput8.dll was loaded before empire.retail.dll (by another program or DLL) - the fixes install when "
"the game loads it");
else {
diag_startup(NULL, g_log_path, wlog);
DisableThreadLibraryCalls(h);
}
return TRUE;
}