Repository navigation
Expand file tree
/
Copy pathdtclamp.cpp
More file actions
415 lines (396 loc) · 19.3 KB
/
Copy pathdtclamp.cpp
File metadata and controls
415 lines (396 loc) · 19.3 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
/* dtclamp.asi — High-FPS physics fix for Watch Dogs (WD1)
*
* The game calls game-side `step(this, float dt)` controller functions once
* per RENDERED frame. At >60 FPS they run too often and over-charge physics
* (sprint-turn jank, vehicle glitches, ragdoll glitches). We re-time each
* step function to a FIXED 60 Hz via a delta-time accumulator (ported from
* the WD2 fix, see Lolle2000la/watchdogs2-highfps-movement-fix).
*
* Three step functions are hooked (verified UNIQUE AOBs in Disrupt_b64.dll,
* imagebase 0x180000000, Complete Edition build):
*
* 1. Character locomotion FUN_182186090 RVA 0x2186090 slot 0xB0 dt=XMM2
* 2. Vehicle physics FUN_1821863c0 RVA 0x21863C0 standalone dt=XMM3
* 3. Ragdoll FUN_182123440 RVA 0x2123440 standalone dt=XMM1
*
* IMPORTANT: unlike WD2 (uniform dt in XMM1), WD1 passes dt in a DIFFERENT
* XMM register per function. Each hook uses its own function-pointer type so
* the dt register and argument layout match the original ABI.
*
* The Havok world itself (FUN_182128580) is ALREADY 30 Hz rate-limited and
* needs no patch. The previous single-instruction clamp (minss dt,1/30) was a
* no-op — dt at high FPS is already below 1/30.
*
* Build: x86_64-w64-mingw32-g++ -shared -O2 -o bin/dtclamp.asi dtclamp.cpp -lkernel32 -std=c++23
*/
#include <windows.h>
#include <psapi.h>
#include <cstdint>
#include <cstring>
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
static constexpr const char* DISRUPT_DLL = "Disrupt_b64.dll";
static constexpr const char* LOGFILE = "dtclamp.log";
static constexpr float FIXED_DT = 1.0f / 60.0f; // physics reference rate
static constexpr float DT_MAX = 1.0f / 30.0f; // per-frame dt clamp before accum
static constexpr int MAX_STEPS = 3; // spike guard
// ---------------------------------------------------------------------------
// AOB patterns (verified count=1 each in Disrupt_b64.dll)
// ---------------------------------------------------------------------------
// Character: push rbp; push r12; push r15; sub rsp,0x40; movaps [rsp+0x20],xmm6; mov r15,rdx; mov r12,rcx
static const std::uint8_t CHAR_PAT[] = {
0x40,0x55,0x41,0x54,0x41,0x57,0x48,0x83,0xEC,0x40,
0x0F,0x29,0x74,0x24,0x20, 0x4C,0x8B,0xFA
};
// Vehicle: mov [rsp+0x18],r8d; mov [rsp+0x10],rdx; mov [rsp+8],rcx; push r13; push r14
static const std::uint8_t VEH_PAT[] = {
0x44,0x89,0x44,0x24,0x18, 0x48,0x89,0x54,0x24,0x10,
0x48,0x89,0x4C,0x24,0x08, 0x41,0x55,0x41,0x56
};
// Ragdoll: mov [rsp+0x10],rbx; push rdi; sub rsp,0x60; mov rax,[rcx+0x310]
static const std::uint8_t RAGDOLL_PAT[] = {
0x48,0x89,0x5C,0x24,0x10, 0x57, 0x48,0x83,0xEC,0x60,
0x48,0x8B,0x81,0x10,0x03,0x00,0x00
};
// ---------------------------------------------------------------------------
// Step-function ABI types. WD1 passes dt in different XMM regs per function:
// char: (void* this, void* arg, float dt) -> dt in XMM2
// vehicle: (void* this, void* a, void* b, float dt) -> dt in XMM3
// ragdoll: (void* this, float dt) -> dt in XMM1
// ---------------------------------------------------------------------------
typedef void (__fastcall* CharStepFn)(void* this_, void* arg, float dt);
typedef void (__fastcall* VehStepFn)(void* this_, void* a, void* b, float dt);
typedef void (__fastcall* RagdollStepFn)(void* this_, float dt);
// ---------------------------------------------------------------------------
// Logging (minimal Win32 — no CRT)
// ---------------------------------------------------------------------------
static void log_msg(const char* msg) {
HANDLE h = CreateFileA(LOGFILE, GENERIC_WRITE, 0, nullptr,
OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
if (h == INVALID_HANDLE_VALUE) return;
SetFilePointer(h, 0, nullptr, FILE_END);
DWORD written;
WriteFile(h, msg, lstrlenA(msg), &written, nullptr);
CloseHandle(h);
}
static void log_hex(const char* prefix, std::uintptr_t val) {
// wsprintfA does NOT support %llX (64-bit) — it only handles %lx (32-bit).
// Convert manually so the base address logs correctly.
char buf[128];
int n = lstrlenA(prefix);
for (int i = 0; i < n; ++i) buf[i] = prefix[i];
buf[n++] = '0'; buf[n++] = 'x';
int shift = 60;
bool started = false;
for (int d = 0; d < 16; ++d, shift -= 4) {
int nib = (int)((val >> shift) & 0xF);
if (nib || started || d == 15) {
started = true;
buf[n++] = (nib < 10) ? ('0' + nib) : ('A' + nib - 10);
}
}
buf[n++] = '\n'; buf[n] = 0;
log_msg(buf);
}
static void log_int(const char* prefix, int val) {
char buf[128];
wsprintfA(buf, "%s %d\n", prefix, val);
log_msg(buf);
}
static void log_float(const char* prefix, float val) {
// Manual float->decimal (wsprintfA %f is iffy with -O2/nostartfiles);
// print as integer + 6 fractional digits.
char buf[160];
bool neg = val < 0.0f;
float a = neg ? -val : val;
int ip = (int)a;
long long frac = (long long)((a - (float)ip) * 1000000.0f);
if (frac < 0) { frac = 0; }
if (frac > 999999) { frac = 999999; }
char tmp[32];
int t = 0;
if (frac == 0) { tmp[t++] = '0'; }
else {
// strip trailing zeros
int nd = 6; long long f2 = frac;
while (nd > 1 && (f2 % 10) == 0) { f2 /= 10; nd--; }
char buf2[24]; int n2 = 0;
long long v = f2;
do { buf2[n2++] = '0' + (int)(v % 10); v /= 10; } while (v > 0);
while (n2 < nd) buf2[n2++] = '0';
for (int i = n2 - 1; i >= 0; --i) tmp[t++] = buf2[i];
}
int n = 0;
for (int i = 0; prefix[i]; ++i) buf[n++] = prefix[i];
if (neg) buf[n++] = '-';
int ip2 = ip; char ibuf[16]; int ni = 0;
if (ip2 == 0) ibuf[ni++] = '0';
while (ip2 > 0) { ibuf[ni++] = '0' + (ip2 % 10); ip2 /= 10; }
for (int i = ni - 1; i >= 0; --i) buf[n++] = ibuf[i];
buf[n++] = '.'; buf[n++] = '.';
for (int i = 0; i < t; ++i) buf[n++] = tmp[i];
buf[n++] = '\n'; buf[n] = 0;
log_msg(buf);
}
// ---------------------------------------------------------------------------
// Memory scanning / near allocation (from wd2fix.c)
// ---------------------------------------------------------------------------
static std::uint8_t* scan_module(HMODULE mod, const std::uint8_t* pat, std::size_t len, int* out_count) {
MODULEINFO mi;
if (!GetModuleInformation(GetCurrentProcess(), mod, &mi, sizeof(mi))) { *out_count = -1; return nullptr; }
std::uint8_t* base = static_cast<std::uint8_t*>(mi.lpBaseOfDll);
std::uint8_t* end = base + mi.SizeOfImage;
std::uint8_t* found = nullptr; int count = 0;
std::uint8_t* p = base;
MEMORY_BASIC_INFORMATION mbi;
while (p < end && VirtualQuery(p, &mbi, sizeof(mbi)) == sizeof(mbi)) {
std::uint8_t* regEnd = static_cast<std::uint8_t*>(mbi.BaseAddress) + mbi.RegionSize;
bool readable = (mbi.State == MEM_COMMIT) &&
(mbi.Protect & (PAGE_EXECUTE_READ|PAGE_EXECUTE_READWRITE|PAGE_READONLY|PAGE_READWRITE|PAGE_EXECUTE_WRITECOPY|PAGE_WRITECOPY)) &&
!(mbi.Protect & (PAGE_GUARD|PAGE_NOACCESS));
if (readable) {
std::uint8_t* s = static_cast<std::uint8_t*>(mbi.BaseAddress); if (s < base) s = base;
std::uint8_t* e = regEnd; if (e > end) e = end;
if ((std::size_t)(e - s) >= len) {
for (std::uint8_t* q = s; q <= e - len; ++q) {
if (q[0] == pat[0] && std::memcmp(q, pat, len) == 0) { if (!found) found = q; ++count; }
}
}
}
p = regEnd;
if (regEnd <= static_cast<std::uint8_t*>(mbi.BaseAddress)) break;
}
*out_count = count;
return found;
}
static void* alloc_near(void* target) {
SYSTEM_INFO si; GetSystemInfo(&si);
std::uintptr_t gran = si.dwAllocationGranularity;
std::uintptr_t t = reinterpret_cast<std::uintptr_t>(target);
for (int dir = 0; dir < 2; ++dir) {
for (std::uintptr_t off = gran; off < 0x78000000ULL; off += gran) {
std::uintptr_t addr = dir ? (t + off) : (t - off);
addr &= ~(gran - 1);
MEMORY_BASIC_INFORMATION mbi;
if (!VirtualQuery(reinterpret_cast<void*>(addr), &mbi, sizeof(mbi))) continue;
if (mbi.State != MEM_FREE) continue;
void* p = VirtualAlloc(reinterpret_cast<void*>(addr), 0x1000, MEM_RESERVE|MEM_COMMIT, PAGE_EXECUTE_READWRITE);
if (p) return p;
}
}
return nullptr;
}
// ---------------------------------------------------------------------------
// Per-entity accumulator tables
// ---------------------------------------------------------------------------
#define CSLOTS 8
static CRITICAL_SECTION g_accLock;
static DWORD g_armTick = 0; // re-timing disabled until armTick (level-load grace)
static constexpr DWORD GRACE_MS = 3000; // pass-through during the first 3s (spawn chains)
static struct { std::uint64_t ptr; float accum; DWORD lastTick; } g_charAcc[CSLOTS];
#define VSLOTS 256
static struct { std::uint64_t ptr; float accum; DWORD lastTick; } g_vehAcc[VSLOTS];
#define RSLOTS 256
static struct { std::uint64_t ptr; float accum; DWORD lastTick; } g_ragdollAcc[RSLOTS];
// ---- diagnostic counters (logged ~every 5s) ----
static volatile DWORD g_diagCalls[3] = {0,0,0}; // hook fire counts
static volatile DWORD g_diagSteps[3] = {0,0,0}; // accumulator steps produced
static volatile float g_diagDtSum[3] = {0,0,0}; // sum of arriving dt
static DWORD g_diagLast = 0; // last periodic-log tick
static void diag_periodic(void) {
DWORD now = GetTickCount();
if (g_diagLast == 0) { g_diagLast = now; return; }
if (now - g_diagLast < 5000) return;
DWORD dt = now - g_diagLast; g_diagLast = now;
const char* names[3] = { "char", "veh", "ragdoll" };
for (int i = 0; i < 3; ++i) {
DWORD c = g_diagCalls[i]; g_diagCalls[i] = 0;
DWORD s = g_diagSteps[i]; g_diagSteps[i] = 0;
float sum = g_diagDtSum[i]; g_diagDtSum[i] = 0.0f;
if (c == 0) continue;
char buf[192];
wsprintfA(buf, "[diag] %s calls=%u steps=%u avgDt=", names[i], c, s);
log_msg(buf);
log_float("", c ? (sum / (float)c) : 0.0f);
char buf2[128];
wsprintfA(buf2, "[diag] %s steps/call=%.3f calls/s=%.1f\n", names[i],
c ? (float)s / (float)c : 0.0f, c ? (float)c * 1000.0f / (float)dt : 0.0f);
log_msg(buf2);
}
}
// Find or allocate a slot for entity `p`, evict stale (>1s idle). Returns slot or -1.
template <typename T, int N>
static int acc_slot(T (&tbl)[N], std::uint64_t p) {
DWORD now = GetTickCount();
int slot = -1, free = -1;
for (int i = 0; i < N; ++i) {
if (tbl[i].ptr == p) { slot = i; break; }
if (free < 0 && (tbl[i].ptr == 0 || (now - tbl[i].lastTick) > 1000)) free = i;
}
if (slot < 0) slot = free;
if (slot < 0) return -1;
if (tbl[slot].ptr != p) { tbl[slot].ptr = p; tbl[slot].accum = 0.0f; }
tbl[slot].lastTick = now;
return slot;
}
// Advance `accum` by rdt, returning the number of FIXED_DT substeps (clamped).
static int advance_accum(float& accum, float rdt) {
if (rdt > DT_MAX) rdt = DT_MAX;
if (rdt < 0.0f) rdt = 0.0f;
accum += rdt;
int steps = 0;
while (accum >= FIXED_DT && steps < MAX_STEPS) {
accum -= FIXED_DT;
steps++;
}
if (steps >= MAX_STEPS) accum = 0.0f; // spike guard
return steps;
}
// ---------------------------------------------------------------------------
// Character step (player + NPCs). dt in XMM2.
// ---------------------------------------------------------------------------
static CharStepFn oCharStep = nullptr;
static bool g_inCharStep = false; // re-entrancy guard (level-load spawns re-enter)
static void myCharStep(void* this_, void* arg, float dt) {
if (!oCharStep) return;
// Level-load grace: during the first GRACE_MS the game spawns characters,
// vehicles and ragdolls in chains. Pass those calls through untouched so
// the spawn logic runs at its native rate (re-timing it freezes level load).
if (GetTickCount() < g_armTick) { oCharStep(this_, arg, dt); return; }
// Re-entrancy guard: if the original step itself (or a nested spawn) calls
// back into this hooked entry, do NOT recurse into the accumulator — pass
// the call straight through. Without this, level-load spawn chains recurse
// until the stack overflows (black screen / hang).
if (g_inCharStep) { oCharStep(this_, arg, dt); return; }
g_inCharStep = true;
InterlockedIncrement((volatile LONG*)&g_diagCalls[0]); g_diagDtSum[0] += dt;
EnterCriticalSection(&g_accLock);
int slot = acc_slot(g_charAcc, reinterpret_cast<std::uint64_t>(this_));
int steps = 0;
if (slot >= 0) steps = advance_accum(g_charAcc[slot].accum, dt);
LeaveCriticalSection(&g_accLock);
g_diagSteps[0] += (DWORD)steps;
diag_periodic();
// Re-time to 60 Hz: call the original only in FIXED_DT substeps. When
// steps==0 the accumulated dt is deferred (not consumed), which is what
// decouples the simulation rate from the render rate.
for (int s = 0; s < steps; ++s) oCharStep(this_, arg, FIXED_DT);
g_inCharStep = false;
}
// ---------------------------------------------------------------------------
// Vehicle step (all vehicles). dt in XMM3.
// ---------------------------------------------------------------------------
static VehStepFn oVehStep = nullptr;
static bool g_inVehStep = false; // re-entrancy guard
static void myVehStep(void* this_, void* a, void* b, float dt) {
if (!oVehStep) return;
if (GetTickCount() < g_armTick) { oVehStep(this_, a, b, dt); return; }
if (g_inVehStep) { oVehStep(this_, a, b, dt); return; }
g_inVehStep = true;
InterlockedIncrement((volatile LONG*)&g_diagCalls[1]); g_diagDtSum[1] += dt;
EnterCriticalSection(&g_accLock);
int slot = acc_slot(g_vehAcc, reinterpret_cast<std::uint64_t>(this_));
int steps = 0;
if (slot >= 0) steps = advance_accum(g_vehAcc[slot].accum, dt);
LeaveCriticalSection(&g_accLock);
g_diagSteps[1] += (DWORD)steps;
diag_periodic();
for (int s = 0; s < steps; ++s) oVehStep(this_, a, b, FIXED_DT);
g_inVehStep = false;
}
// ---------------------------------------------------------------------------
// Ragdoll step (all ragdolls). dt in XMM1.
// ---------------------------------------------------------------------------
static RagdollStepFn oRagdollStep = nullptr;
static bool g_inRagdollStep = false; // re-entrancy guard
static void myRagdollStep(void* this_, float dt) {
if (!oRagdollStep) return;
if (GetTickCount() < g_armTick) { oRagdollStep(this_, dt); return; }
if (g_inRagdollStep) { oRagdollStep(this_, dt); return; }
g_inRagdollStep = true;
InterlockedIncrement((volatile LONG*)&g_diagCalls[2]); g_diagDtSum[2] += dt;
EnterCriticalSection(&g_accLock);
int slot = acc_slot(g_ragdollAcc, reinterpret_cast<std::uint64_t>(this_));
int steps = 0;
if (slot >= 0) steps = advance_accum(g_ragdollAcc[slot].accum, dt);
LeaveCriticalSection(&g_accLock);
g_diagSteps[2] += (DWORD)steps;
diag_periodic();
for (int s = 0; s < steps; ++s) oRagdollStep(this_, FIXED_DT);
g_inRagdollStep = false;
}
// ---------------------------------------------------------------------------
// Install a trampoline+jump-stub hook over the prologue of a step function.
// `disp_len` = number of bytes to displace (>=5) so the jump-back lands on a
// clean instruction boundary. Builds:
// trampoline = displaced disp_len bytes + jmp [rip] back to fn+disp_len,
// jump stub = jmp [rip] to hook.
// The 5-byte E9 patch at fn overwrites the first 5 bytes; the trampoline
// reproduces the full disp_len-byte prologue so no instruction is split.
// ---------------------------------------------------------------------------
template <typename Fn>
static int install_step_hook(HMODULE mod, const std::uint8_t* pat, std::size_t len,
const char* tag, Fn hook, Fn* tramp_out, std::size_t disp_len) {
int cnt = 0;
std::uint8_t* fn = scan_module(mod, pat, len, &cnt);
if (!fn) { log_msg("[fix] "); log_msg(tag); log_msg(" anchor not found\n"); log_int(" count", cnt); return 0; }
std::uint8_t* blk = static_cast<std::uint8_t*>(alloc_near(fn));
if (!blk) { log_msg("[fix] "); log_msg(tag); log_msg(" alloc_near failed\n"); return 0; }
std::uint8_t s[64]; std::memset(s, 0x90, sizeof(s));
// Trampoline: displaced disp_len bytes + jmp [rip] back to fn+disp_len
std::memcpy(s, fn, disp_len);
s[disp_len]=0xFF; s[disp_len+1]=0x25;
*reinterpret_cast<std::int32_t*>(s+disp_len+2)=0;
*reinterpret_cast<std::uint64_t*>(s+disp_len+6)=reinterpret_cast<std::uint64_t>(fn+disp_len);
// Jump stub: jmp [rip] to hook, placed 16-byte-aligned AFTER the trampoline
// (trampoline occupies disp_len + 14 bytes: code + FF25 jmp + 8-byte addr).
const std::size_t tramp_end = disp_len + 14;
const std::size_t stub = (tramp_end + 15) & ~15;
s[stub]=0xFF; s[stub+1]=0x25;
*reinterpret_cast<std::int32_t*>(s+stub+2)=0;
*reinterpret_cast<std::uint64_t*>(s+stub+6)=reinterpret_cast<std::uint64_t>(hook);
std::memcpy(blk, s, sizeof(s));
FlushInstructionCache(GetCurrentProcess(), blk, sizeof(s));
*tramp_out = reinterpret_cast<Fn>(blk);
std::int64_t rel = reinterpret_cast<std::int64_t>(blk+stub) - reinterpret_cast<std::int64_t>(fn+5);
if (rel > 0x7fffffffLL || rel < -0x80000000LL) { log_msg("[fix] "); log_msg(tag); log_msg(" jump stub out of range\n"); return 0; }
std::uint8_t patch[5]; patch[0]=0xE9; *reinterpret_cast<std::int32_t*>(patch+1)=static_cast<std::int32_t>(rel);
DWORD op;
if (!VirtualProtect(fn,5,PAGE_EXECUTE_READWRITE,&op)) { log_msg("[fix] "); log_msg(tag); log_msg(" VProtect failed\n"); return 0; }
std::memcpy(fn, patch, 5);
VirtualProtect(fn,5,op,&op);
FlushInstructionCache(GetCurrentProcess(), fn, 5);
log_msg("[fix] "); log_msg(tag); log_msg(" hooked\n");
return 1;
}
// ---------------------------------------------------------------------------
// DtClamp plugin
// ---------------------------------------------------------------------------
class DtClamp {
public:
DtClamp() = default;
void install() {
log_msg("dtclamp.asi loaded (high-fps physics fix)\n");
InitializeCriticalSection(&g_accLock);
g_armTick = GetTickCount() + GRACE_MS; // pass-through during level load
HMODULE hDll = GetModuleHandleA(DISRUPT_DLL);
if (!hDll) { log_msg("Disrupt_b64.dll not found\n"); return; }
log_hex("Disrupt_b64.dll base", reinterpret_cast<std::uintptr_t>(hDll));
int ok = 0;
ok += install_step_hook(hDll, CHAR_PAT, sizeof(CHAR_PAT), "character step", myCharStep, &oCharStep, 6);
ok += install_step_hook(hDll, VEH_PAT, sizeof(VEH_PAT), "vehicle step", myVehStep, &oVehStep, 5);
ok += install_step_hook(hDll, RAGDOLL_PAT, sizeof(RAGDOLL_PAT), "ragdoll step", myRagdollStep, &oRagdollStep, 5);
log_int("hooks installed", ok);
if (ok == 0) log_msg("WARNING: no hooks installed\n");
log_int("grace period (ms) before re-timing", GRACE_MS);
}
};
static DtClamp g_dtclamp;
extern "C" BOOL APIENTRY DllMain([[maybe_unused]] HINSTANCE hinst, DWORD reason, [[maybe_unused]] LPVOID res) {
if (reason == DLL_PROCESS_ATTACH) {
DisableThreadLibraryCalls(hinst);
g_dtclamp.install();
}
return TRUE;
}