C++
#pragma comment(linker, "/EXPORT:GetFileVersionInfoA=C:\\Windows\\System32\\version.GetFileVersionInfoA")
#pragma comment(linker, "/EXPORT:GetFileVersionInfoByHandle=C:\\Windows\\System32\\version.GetFileVersionInfoByHandle")
#pragma comment(linker, "/EXPORT:GetFileVersionInfoExA=C:\\Windows\\System32\\version.GetFileVersionInfoExA")
#pragma comment(linker, "/EXPORT:GetFileVersionInfoExW=C:\\Windows\\System32\\version.GetFileVersionInfoExW")
#pragma comment(linker, "/EXPORT:GetFileVersionInfoSizeA=C:\\Windows\\System32\\version.GetFileVersionInfoSizeA")
#pragma comment(linker, "/EXPORT:GetFileVersionInfoSizeExA=C:\\Windows\\System32\\version.GetFileVersionInfoSizeExA")
#pragma comment(linker, "/EXPORT:GetFileVersionInfoSizeExW=C:\\Windows\\System32\\version.GetFileVersionInfoSizeExW")
#pragma comment(linker, "/EXPORT:GetFileVersionInfoSizeW=C:\\Windows\\System32\\version.GetFileVersionInfoSizeW")
#pragma comment(linker, "/EXPORT:GetFileVersionInfoW=C:\\Windows\\System32\\version.GetFileVersionInfoW")
#pragma comment(linker, "/EXPORT:VerFindFileA=C:\\Windows\\System32\\version.VerFindFileA")
#pragma comment(linker, "/EXPORT:VerFindFileW=C:\\Windows\\System32\\version.VerFindFileW")
#pragma comment(linker, "/EXPORT:VerInstallFileA=C:\\Windows\\System32\\version.VerInstallFileA")
#pragma comment(linker, "/EXPORT:VerInstallFileW=C:\\Windows\\System32\\version.VerInstallFileW")
#pragma comment(linker, "/EXPORT:VerLanguageNameA=C:\\Windows\\System32\\version.VerLanguageNameA")
#pragma comment(linker, "/EXPORT:VerLanguageNameW=C:\\Windows\\System32\\version.VerLanguageNameW")
#pragma comment(linker, "/EXPORT:VerQueryValueA=C:\\Windows\\System32\\version.VerQueryValueA")
#pragma comment(linker, "/EXPORT:VerQueryValueW=C:\\Windows\\System32\\version.VerQueryValueW")

#include <windows.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

#ifndef _M_X64
#error "此工具仅支持 x64 (QQ飞车端游为64位客户端)"
#endif

static const int    FPS_TARGET = 120000;
static const int    ENGINE_MIN_RATE = 30000;
static const int    ENGINE_MAX_RATE = 120000;
static const int    MAINTAIN_GATE = 60000;
static const DWORD  TICK_INTERVAL_MS = 500;
static const DWORD  POLL_INTERVAL_MS = 100;
static const DWORD  AUTO_STOP_MINUTES = 0;
static const UINT   MAGIC_WPARAM = 0x51535031u;
static const LPARAM MAGIC_LPARAM = 1;

static const wchar_t* GAME_EXE = L"GameApp.exe";
static const wchar_t* ENGINE_MODULE = L"Top-Kart.dll";
static const wchar_t* TICK_MSG_NAME = L"QQFC.OfficialFrameUnlock.O2.Tick";

static const char* ANCHOR_LUA_USER = "Userdata/AnalyzeRecord.lua";
static const char* ANCHOR_LUA_ROOT = "res/lua54root.lua";
static const char* FRAME_API_NAMES[3] = {
    "GetClientFrameRateCfg", "SetClientFrameRateCfg", "IsFullScreenMode"
};
static const char* LUA_ANCHOR_SHOP[3] = {
    "Win_GetCurScreen", "RestoreShopEquip", "EquipPlayerWithNewItems"
};
static const char* LUA_SELECT_NAMES[5] = {
    "QQFCOfficialFrameSelectLow", "QQFCOfficialFrameSelectMiddle",
    "QQFCOfficialFrameSelectHigh", "QQFCOfficialFrameSelectExtreme",
    "QQFCOfficialFrameSelectManual"
};

struct FrameCfg {
    int mn;
    int mx;
    int step;
    int cur;
};
struct FrameAnchors {
    SIZE_T globalA;
    SIZE_T globalB;
    int    offA;
    int    offB;
    int    offC;
    int    writeOnly;
};

static HMODULE  g_hMod = NULL;
static HMODULE  g_hEngine = NULL;
static HWND     g_Wnd = NULL;
static DWORD    g_MainTID = 0;
static HHOOK    g_Hook = NULL;
static UINT     g_TickMsg = 0;
static volatile LONG g_PostGate = 0;

static SIZE_T   g_P1 = 0;
static SIZE_T   g_Exec = 0;
static FrameAnchors g_Fa = {};
static bool     g_FrameReady = false;

static SIZE_T   g_LuaState = 0;
static bool     g_InTick = false;
static bool     g_InProgress = false;
static volatile bool g_GiveUp = false;
static volatile bool g_Stop = false;
static int      g_Preference = 0;
static FrameCfg g_OrigCfg = {};
static bool     g_HaveBackup = false;
static int      g_LastMax = 0;
static SIZE_T   g_AppliedThis = 0;
static SIZE_T   g_HolderId = 0;
static SIZE_T   g_AppliedHolder = 0;

static SIZE_T   g_LuaPushCC = 0;
static SIZE_T   g_LuaSetGl = 0;
static bool     g_UiOff = false;
static HANDLE   g_ScriptH = INVALID_HANDLE_VALUE;
static wchar_t  g_ScriptPathW[2 * MAX_PATH] = {};
static char     g_ScriptRelA[MAX_PATH] = {};
static char     g_ScriptAbsA[2 * MAX_PATH] = {};
static int      g_UiExecMode = -1;
static DWORD    g_UiRefused = 0;

static wchar_t  g_GameDir[MAX_PATH] = {};

static bool Rd(SIZE_T addr, void* buf, SIZE_T n) {
    SIZE_T got = 0;
    if (!addr) return false;
    if (!ReadProcessMemory(GetCurrentProcess(), (LPCVOID)addr, buf, n, &got))
        return false;
    return got == n;
}
static bool RdPtr(SIZE_T addr, SIZE_T* out) { return Rd(addr, out, sizeof(SIZE_T)); }

struct Mod {
    BYTE* base;
    IMAGE_NT_HEADERS* nt;
};

static bool ModOpen(BYTE* base, Mod* m) {
    if (!base) return false;
    if (*(WORD*)base != 0x5A4D) return false;
    LONG lfa = *(LONG*)(base + 0x3C);
    if ((ULONG32)(lfa - 0x40) > 0xFC0) return false;
    IMAGE_NT_HEADERS* nt = (IMAGE_NT_HEADERS*)(base + lfa);
    if (nt->Signature != 0x00004550) return false;
    if (nt->FileHeader.Machine != 0x8664) return false;
    if (nt->OptionalHeader.Magic != 0x020B) return false;
    WORD ns = nt->FileHeader.NumberOfSections;
    if (ns == 0 || ns > 0x40) return false;
    ULONGLONG soi = nt->OptionalHeader.SizeOfImage;
    if (soi < 0x100000 || soi > 0x20000000) return false;
    m->base = base; m->nt = nt;
    return true;
}
static IMAGE_SECTION_HEADER* Secs(const Mod& m) { return IMAGE_FIRST_SECTION(m.nt); }
static WORD                 SecN(const Mod& m) { return m.nt->FileHeader.NumberOfSections; }
static DWORD                Soi(const Mod& m) { return (DWORD)m.nt->OptionalHeader.SizeOfImage; }

static bool RvaInSection(const Mod& m, DWORD rva, DWORD size, DWORD needFlags) {
    if (rva >= Soi(m)) return false;
    IMAGE_SECTION_HEADER* s = Secs(m);
    for (WORD i = 0; i < SecN(m); i++, s++) {
        DWORD va = s->VirtualAddress, vs = s->Misc.VirtualSize;
        if (rva < va) continue;
        if (rva - va > vs) continue;
        if (size > va + vs - rva) continue;
        if ((s->Characteristics & needFlags) == needFlags) return true;
    }
    return false;
}

static DWORD FindStringRva(const Mod& m, const char* needle) {
    size_t len = strlen(needle);
    if (len == 0) return 0;
    IMAGE_SECTION_HEADER* s = Secs(m);
    for (WORD i = 0; i < SecN(m); i++, s++) {
        if ((s->Characteristics & 0xE2000000u) != 0x40000000u) continue;
        DWORD va = s->VirtualAddress, vs = s->Misc.VirtualSize;
        if (va >= Soi(m)) return 0;
        if (vs > Soi(m) - va) return 0;
        if (vs < (DWORD)(len + 1)) continue;
        BYTE* start = m.base + va;
        for (DWORD off = 0; off + len + 1 <= vs; off++) {
            if (memcmp(start + off, needle, len + 1) == 0)
                return va + off;
        }
    }
    return 0;
}

static bool ScanLuaEntry(BYTE* base, SIZE_T* outP1, SIZE_T* outExec) {
    Mod m;
    if (!ModOpen(base, &m)) return false;

    DWORD a1 = FindStringRva(m, ANCHOR_LUA_USER);
    DWORD a2 = FindStringRva(m, ANCHOR_LUA_ROOT);
    if (!a1 || !a2) return false;

    int   cntA = 0, cntB = 0;
    DWORD p1a = 0, exA = 0, p1b = 0, exB = 0;

    IMAGE_SECTION_HEADER* s = Secs(m);
    for (WORD i = 0; i < SecN(m); i++, s++) {
        if (!(s->Characteristics & 0x20000000u)) continue;
        DWORD va = s->VirtualAddress, vs = s->Misc.VirtualSize;
        if (va >= Soi(m) || vs > Soi(m) - va || vs < 0x30) continue;
        BYTE* sec = m.base + va;
        for (DWORD p = 0x12; p + 0x18 <= vs; p++) {
            BYTE* q = sec + p;
            if (q[0] != 0x48 || q[1] != 0x8D || q[2] != 0x15) continue;
            int32_t disp; memcpy(&disp, q + 3, 4);
            DWORD target = va + p + 7 + (int64_t)disp;

            if (target == a1 && p >= 7
                && q[-7] == 0x48 && q[-6] == 0x8B && q[-5] == 0x0D
                && q[7] == 0x45 && q[8] == 0x33 && q[9] == 0xC9
                && q[10] == 0x45 && q[11] == 0x33 && q[12] == 0xC0
                && q[13] == 0xE8) {
                int32_t d2;  memcpy(&d2, q - 4, 4);
                int32_t rel; memcpy(&rel, q + 14, 4);
                cntA++;
                p1a = va + p + (int64_t)d2;
                exA = va + p + 0x12 + (int64_t)rel;
            }
            else if (target == a2 && p >= 0x12
                && q[-0x12] == 0x48 && q[-0x11] == 0x8B && q[-0x10] == 0x05
                && q[-0x0B] == 0x48 && q[-0x0A] == 0x85 && q[-9] == 0xC0
                && q[-8] == 0x74
                && q[-6] == 0x45 && q[-5] == 0x33 && q[-4] == 0xC9
                && q[-3] == 0x45 && q[-2] == 0x33 && q[-1] == 0xC0
                && q[7] == 0x48 && q[8] == 0x8B && q[9] == 0xC8
                && q[10] == 0xE8) {
                int32_t d2;  memcpy(&d2, q - 0x0F, 4);
                int32_t rel; memcpy(&rel, q + 11, 4);
                cntB++;
                p1b = va + p - 0x0B + (int64_t)d2;
                exB = va + p + 0x0F + (int64_t)rel;
            }
        }
    }
    if (cntA != 1 || cntB != 1) return false;
    if (p1a != p1b || exA != exB) return false;
    if (p1a >= Soi(m) || Soi(m) - p1a < 8)    return false;
    if (exA >= Soi(m) || Soi(m) - exA < 0x20)  return false;
    if (!RvaInSection(m, p1a, 8, 0xC0000000u)) return false;
    if (!RvaInSection(m, exA, 0x20, 0x60000000u)) return false;

    *outP1 = (SIZE_T)m.base + p1a;
    *outExec = (SIZE_T)m.base + exA;
    return true;
}

static bool FuncRange(const Mod& m, DWORD fnRva, DWORD* pEnd) {
    const IMAGE_DATA_DIRECTORY* d = &m.nt->OptionalHeader.DataDirectory[3];
    if (!d->VirtualAddress || !d->Size) return false;
    if (d->Size % sizeof(IMAGE_RUNTIME_FUNCTION_ENTRY)) return false;
    if (d->VirtualAddress >= Soi(m) || d->Size > Soi(m) - d->VirtualAddress) return false;
    IMAGE_RUNTIME_FUNCTION_ENTRY* rf =
        (IMAGE_RUNTIME_FUNCTION_ENTRY*)(m.base + d->VirtualAddress);
    DWORD n = d->Size / sizeof(IMAGE_RUNTIME_FUNCTION_ENTRY);
    for (DWORD i = 0; i < n; i++) {
        if (rf[i].BeginAddress == fnRva && rf[i].EndAddress > fnRva
            && rf[i].EndAddress - fnRva <= 0x1000) {
            if (!RvaInSection(m, fnRva, rf[i].EndAddress - fnRva, 0x60000000u))
                return false;
            *pEnd = rf[i].EndAddress;
            return true;
        }
    }
    return false;
}

struct S1Hit {
    DWORD globalB;  int offB;  int offC;  DWORD atRva;  int fnIdx;
};

static bool DecRipLoad(const Mod& m, DWORD p, DWORD end,
    int* reg, DWORD* target, int* len) {
    if (p + 7 > end) return false;
    BYTE* q = m.base + p;
    BYTE b = q[0];
    if ((b & 0xF8) != 0x48 || q[1] != 0x8B) return false;
    BYTE rm = q[2];
    if ((rm & 0xC7) != 0x05) return false;
    *reg = ((b & 0x04) ? 8 : 0) + ((rm >> 3) & 7);
    int32_t d; memcpy(&d, q + 3, 4);
    *target = (DWORD)((int64_t)p + 7 + d);
    *len = 7;
    return true;
}

static bool DecLeaBase(const Mod& m, DWORD p, DWORD end,
    int* dst, int* base, int32_t* disp, int* len) {
    if (p + 4 > end) return false;
    BYTE* q = m.base + p;
    BYTE b = q[0];
    if ((b & 0xF8) != 0x48 || q[1] != 0x8D) return false;
    BYTE rm = q[2];
    int mod = rm >> 6, rmb = rm & 7, hdr = 3;
    if (rmb == 4) {
        BYTE sib = q[3];
        if (((sib >> 3) & 7) != 4) return false;
        rmb = sib & 7;
        hdr = 4;
    }
    if (mod == 0 || mod == 3) return false;
    if (mod == 1) {
        if (p + hdr + 1 > end) return false;
        int8_t d8; memcpy(&d8, q + hdr, 1); *disp = d8; *len = hdr + 1;
    }
    else {
        if (p + hdr + 4 > end) return false;
        memcpy(disp, q + hdr, 4); *len = hdr + 4;
    }
    *dst = ((b & 0x04) ? 8 : 0) + ((rm >> 3) & 7);
    *base = ((b & 0x01) ? 8 : 0) + rmb;
    return true;
}

static bool DecMovRegMem(const Mod& m, DWORD p, DWORD end,
    int* dst, int* base, int* len) {
    if (p + 3 > end) return false;
    BYTE* q = m.base + p;
    BYTE b = q[0];
    if ((b & 0xF8) != 0x48 || q[1] != 0x8B) return false;
    BYTE rm = q[2];
    int rmb = rm & 7, hdr = 3;
    if ((rm >> 6) != 0) return false;
    if (rmb == 4) {
        if (p + 4 > end) return false;
        BYTE sib = q[3];
        if (((sib >> 3) & 7) != 4) return false;
        if ((sib & 7) == 5) return false;
        rmb = sib & 7; hdr = 4;
    }
    else if (rmb == 5) {
        return false;
    }
    *dst = ((b & 0x04) ? 8 : 0) + ((rm >> 3) & 7);
    *base = ((b & 0x01) ? 8 : 0) + rmb;
    *len = hdr;
    return true;
}

static bool DecMovRegReg(const Mod& m, DWORD p, DWORD end,
    int* dst, int* src, int* len) {
    if (p + 3 > end) return false;
    BYTE* q = m.base + p;
    BYTE b = q[0];
    if ((b & 0xF8) != 0x48 || q[1] != 0x8B) return false;
    BYTE rm = q[2];
    if ((rm >> 6) != 3) return false;
    *dst = ((b & 0x04) ? 8 : 0) + ((rm >> 3) & 7);
    *src = ((b & 0x01) ? 8 : 0) + (rm & 7);
    *len = 3;
    return true;
}

static bool DecIndCall(const Mod& m, DWORD p, DWORD end,
    int* base, int32_t* disp, int* len) {
    if (p + 3 > end) return false;
    BYTE* q = m.base + p;
    int off = (q[0] == 0x41) ? 1 : 0;
    if (q[off] != 0xFF) return false;
    BYTE rm = q[off + 1];
    if (((rm >> 3) & 7) != 2) return false;
    int mod = rm >> 6, rmb = rm & 7, hdr = off + 2;
    if (rmb == 4) {
        if (p + hdr + 1 > end) return false;
        BYTE sib = q[hdr];
        if (((sib >> 3) & 7) != 4) return false;
        if (mod == 0 && (sib & 7) == 5) return false;
        rmb = sib & 7; hdr += 1;
    }
    if (mod == 0 || mod == 3) return false;
    if (mod == 1) {
        if (p + hdr + 1 > end) return false;
        int8_t d8; memcpy(&d8, q + hdr, 1); *disp = d8; *len = hdr + 1;
    }
    else {
        if (p + hdr + 4 > end) return false;
        memcpy(disp, q + hdr, 4); *len = hdr + 4;
    }
    *base = (off ? 8 : 0) + rmb;
    return true;
}

static bool FindRcxSet(const Mod& m, DWORD from, DWORD to, int regB) {
    for (DWORD p = from; p + 3 <= to; p++) {
        int dst, src, len;
        if (DecMovRegReg(m, p, to, &dst, &src, &len) && dst == 1 && src == regB)
            return true;
    }
    return false;
}

static bool ScanGetAnchors(const Mod& m, DWORD beg, DWORD end,
    DWORD* gAOut, int* offAOut) {
    int n1 = 0, n2 = 0; DWORD gA = 0; int oA = 0;
    for (DWORD p = beg; p + 7 <= end; p++) {
        BYTE* q = m.base + p;
        if (q[0] == 0x48 && q[1] == 0x8B && q[2] == 0x1D) {
            int32_t d; memcpy(&d, q + 3, 4);
            DWORD t = (DWORD)((int64_t)p + 7 + d);
            if (t < Soi(m)) { n1++; gA = t; }
        }
        if (q[0] == 0x48 && q[1] == 0x8D && q[2] == 0x93) {
            int32_t d; memcpy(&d, q + 3, 4);
            n2++; oA = d;
        }
    }
    if (n1 == 1 && n2 == 1) { *gAOut = gA; *offAOut = oA; return true; }

    DWORD cand[4]; int coff[4]; int nc = 0;
    for (DWORD p = beg; p + 7 <= end && nc < 4; p++) {
        int reg, len; DWORD t;
        if (!DecRipLoad(m, p, end, &reg, &t, &len)) continue;
        if (t >= Soi(m)) continue;
        for (DWORD k = p + (DWORD)len; k + 4 <= end && k < p + (DWORD)len + 0x20; k++) {
            int d, bs, ln; int32_t dsp;
            if (DecLeaBase(m, k, end, &d, &bs, &dsp, &ln) && bs == reg) {
                if ((DWORD)(dsp - 0x10) <= 0x7FFFF0u && (dsp & 3) == 0) {
                    bool dup = false;
                    for (int i = 0; i < nc; i++) if (cand[i] == t) dup = true;
                    if (!dup) { cand[nc] = t; coff[nc] = dsp; nc++; }
                }
                break;
            }
        }
    }
    if (nc == 1) {
        *gAOut = cand[0]; *offAOut = coff[0]; return true;
    }
    return false;
}

static void ScanS1Structural(const Mod& m, DWORD beg, DWORD end,
    S1Hit* hits, int* nHits, int cap, int fnIdx) {
    for (DWORD p = beg; p + 7 <= end; p++) {
        int regA, len0; DWORD gB;
        if (!DecRipLoad(m, p, end, &regA, &gB, &len0)) continue;
        if (gB >= Soi(m)) continue;

        DWORD j = p + (DWORD)len0;
        if (j + 5 <= end && regA < 8) {
            BYTE* q = m.base + j;
            if (q[0] == 0x48 && q[1] == 0x85
                && q[2] == (BYTE)(0xC0 | (regA << 3) | regA)
                && q[3] == 0x74) {
                j += 5;
            }
        }

        int regB = -1, offB = 0; DWORD posAfterLea = j;
        for (DWORD k = j; k + 4 <= end && k < j + 0x18; k++) {
            int d, bs, ln; int32_t dsp;
            if (DecLeaBase(m, k, end, &d, &bs, &dsp, &ln) && bs == regA) {
                regB = d; offB = dsp; posAfterLea = k + (DWORD)ln; break;
            }
        }
        if (regB < 0) { regB = regA; offB = 0; posAfterLea = j; }

        int regC = -1; DWORD posV = 0;
        for (DWORD k = posAfterLea; k + 3 <= end && k < posAfterLea + 0x18; k++) {
            int d, bs, ln;
            if (DecMovRegMem(m, k, end, &d, &bs, &ln) && bs == regB) {
                regC = d; posV = k + (DWORD)ln; break;
            }
        }
        if (regC < 0) continue;

        for (DWORD k = posV; k + 3 <= end && k < posV + 0x14; k++) {
            int bs, ln; int32_t dsp;
            if (!DecIndCall(m, k, end, &bs, &dsp, &ln)) continue;
            if (bs != regC) continue;
            if (k - p > 0x38) break;
            bool rcxOk = (regB == 1) || FindRcxSet(m, j, k, regB);
            if (!rcxOk) continue;
            bool dup = false;
            for (int t = 0; t < *nHits; t++) if (hits[t].atRva == k) { dup = true; break; }
            if (!dup && *nHits < cap) {
                hits[*nHits].globalB = gB; hits[*nHits].offB = offB;
                hits[*nHits].offC = dsp;  hits[*nHits].atRva = k;
                hits[*nHits].fnIdx = fnIdx; (*nHits)++;
            }
            break;
        }
    }
}

static int CollectCalls(const Mod& m, DWORD beg, DWORD end,
    DWORD* outs, int cap) {
    int n = 0;
    for (DWORD p = beg; p + 5 <= end && n < cap; p++) {
        BYTE* q = m.base + p;
        if (q[0] != 0xE8 && q[0] != 0xE9) continue;
        int32_t rel; memcpy(&rel, q + 1, 4);
        int64_t t = (int64_t)p + 5 + rel;
        if (t < 0 || t >= (int64_t)Soi(m)) continue;
        DWORD tva = (DWORD)t;
        bool dup = false;
        for (int i = 0; i < n; i++) if (outs[i] == tva) { dup = true; break; }
        if (!dup) outs[n++] = tva;
    }
    return n;
}

struct RegSiteInfo {
    DWORD fn;     int fnLen;
    DWORD call1;  DWORD call2;
    int    shape;
};

static bool ExtractRegisteredFn(const Mod& m, BYTE* q, DWORD leaRva,
    RegSiteInfo* out) {
    int32_t d;
    RegSiteInfo si = {};
    if (leaRva >= 7
        && q[-7] == 0x4C && q[-6] == 0x8D && q[-5] == 0x05
        && q[7] == 0x48 && q[8] == 0x8B
        && (q[9] == 0xCB || q[9] == 0xCF)
        && q[10] == 0xE8) {
        memcpy(&d, q - 4, 4);
        si.fn = (DWORD)(leaRva + (int64_t)d); si.fnLen = 0x10;
        memcpy(&d, q + 0xB, 4);
        si.call1 = (DWORD)(leaRva + 0xF + (int64_t)d);
        si.shape = 1;
    }
    else if (leaRva >= 0x0A
        && q[-0x0A] == 0x4C && q[-9] == 0x8D && q[-8] == 0x05
        && q[-3] == 0x48 && q[-2] == 0x8B
        && (q[-1] == 0xCB || q[-1] == 0xCF)
        && q[7] == 0xE8) {
        memcpy(&d, q - 7, 4);
        si.fn = (DWORD)(leaRva - 3 + (int64_t)d); si.fnLen = 0x20;
        memcpy(&d, q + 8, 4);
        si.call1 = (DWORD)(leaRva + 0xC + (int64_t)d);
        si.shape = 2;
    }
    else if (leaRva >= 0x12
        && q[-0x12] == 0x48 && q[-0x11] == 0x8D && q[-0x10] == 0x15
        && q[-0x0B] == 0x45 && q[-0x0A] == 0x33 && q[-9] == 0xC0
        && q[-8] == 0xE8
        && q[-3] == 0x48 && q[-2] == 0x8B && q[-1] == 0x0F
        && q[7] == 0xE8) {
        memcpy(&d, q - 0xF, 4);
        si.fn = (DWORD)(leaRva - 0xB + (int64_t)d); si.fnLen = 0x20;
        memcpy(&d, q - 7, 4);
        si.call1 = (DWORD)(leaRva - 3 + (int64_t)d);
        memcpy(&d, q + 8, 4);
        si.call2 = (DWORD)(leaRva + 0xC + (int64_t)d);
        si.shape = 3;
    }
    else {
        return false;
    }
    if (!si.fn || !RvaInSection(m, si.fn, si.fnLen, 0x60000000u)) return false;
    if (si.call1 && !RvaInSection(m, si.call1, 0x10, 0x60000000u)) return false;
    if (si.call2 && !RvaInSection(m, si.call2, 0x10, 0x60000000u)) return false;
    *out = si;
    return true;
}

static bool ScanFrameApi(BYTE* base, FrameAnchors* out, RegSiteInfo* sites) {
    Mod m;
    if (!ModOpen(base, &m)) return false;

    DWORD fnRva[3], fnEnd[3];
    for (int i = 0; i < 3; i++) {
        DWORD nameRva = FindStringRva(m, FRAME_API_NAMES[i]);
        if (!nameRva) return false;

        int cnt = 0; DWORD leaRva = 0; BYTE* leaQ = NULL;
        IMAGE_SECTION_HEADER* s = Secs(m);
        for (WORD k = 0; k < SecN(m); k++, s++) {
            if (!(s->Characteristics & 0x20000000u)) continue;
            DWORD va = s->VirtualAddress, vs = s->Misc.VirtualSize;
            if (va >= Soi(m) || vs > Soi(m) - va || vs < 0x1E) continue;
            BYTE* sec = m.base + va;
            for (DWORD p = 0x12; p + 7 <= vs; p++) {
                BYTE* q = sec + p;
                if (q[0] != 0x48 || q[1] != 0x8D || q[2] != 0x15) continue;
                int32_t d; memcpy(&d, q + 3, 4);
                if ((DWORD)(va + p + 7 + (int64_t)d) == nameRva) {
                    cnt++; leaRva = va + p; leaQ = q;
                }
            }
        }
        if (cnt != 1 || !leaQ) {
            return false;
        }
        if (!ExtractRegisteredFn(m, leaQ, leaRva, &sites[i])) {
            return false;
        }
        fnRva[i] = sites[i].fn;
        if (!FuncRange(m, fnRva[i], &fnEnd[i])) {
            return false;
        }
    }

    DWORD gA = 0; int oA = 0;
    if (!ScanGetAnchors(m, fnRva[0], fnEnd[0], &gA, &oA)) {
        return false;
    }
    if ((DWORD)(oA - 0x10) > 0x7FFFF0u || (oA & 3)) return false;
    if (!RvaInSection(m, gA, 8, 0xC0000000u)) return false;

    const int MAXFN = 24;
    DWORD fns[MAXFN], fnEnds[MAXFN]; int fnDepth[MAXFN], gARefsFn[MAXFN];
    int fnCount = 1;
    fns[0] = fnRva[1]; fnEnds[0] = fnEnd[1]; fnDepth[0] = 0; gARefsFn[0] = 0;

    S1Hit hits[16]; int nHits = 0;

    for (int qi = 0; qi < fnCount && qi < MAXFN; qi++) {
        DWORD fb = fns[qi], fe = fnEnds[qi];

        int gAHere = 0;
        for (DWORD p = fb; p + 7 <= fe; p++) {
            int reg, len; DWORD t;
            if (DecRipLoad(m, p, fe, &reg, &t, &len) && t == gA) gAHere++;
        }
        gARefsFn[qi] = gAHere;

        ScanS1Structural(m, fb, fe, hits, &nHits, 16, qi);

        if (fnDepth[qi] < 2 && fnCount < MAXFN) {
            DWORD calls[24]; int nc = CollectCalls(m, fb, fe, calls, 24);
            for (int ci = 0; ci < nc && fnCount < MAXFN; ci++) {
                bool dup = false;
                for (int t = 0; t < fnCount; t++)
                    if (fns[t] == calls[ci]) { dup = true; break; }
                if (dup) continue;
                DWORD ce;
                if (!FuncRange(m, calls[ci], &ce)) continue;
                fns[fnCount] = calls[ci]; fnEnds[fnCount] = ce;
                fnDepth[fnCount] = fnDepth[qi] + 1; gARefsFn[fnCount] = 0;
                fnCount++;
            }
        }
    }

    ScanS1Structural(m, fnRva[0], fnEnd[0], hits, &nHits, 16, -2);

    int  valid[16], nv = 0;
    for (int i = 0; i < nHits && nv < 16; i++) {
        int ob = hits[i].offB, oc = hits[i].offC;
        if ((DWORD)ob > 0x1000u || (ob & 7)) continue;
        if ((DWORD)(oc - 1) > 0xFFFu || (oc & 7)) continue;
        if (!RvaInSection(m, hits[i].globalB, 8, 0xC0000000u)) continue;
        valid[nv++] = i;
    }
    int r1 = 0, idx1 = -1, r2 = 0, idx2 = -1;
    for (int v = 0; v < nv; v++) {
        int i = valid[v];
        int fi = hits[i].fnIdx;
        if (fi >= 0 && gARefsFn[fi] > 0) { r1++; idx1 = i; }
        else if (fi == 0) { r2++; idx2 = i; }
    }
    int pick = -1;
    if (r1 == 1) pick = idx1;
    else if (r1 == 0 && r2 == 1) pick = idx2;
    else if (nv == 1) pick = valid[0];
    else if (r1 > 1 || (r1 == 0 && r2 > 1) || nv > 1) {
        return false;
    }

    if (pick >= 0) {
        DWORD gB = hits[pick].globalB;
        int   oB = hits[pick].offB, oC = hits[pick].offC;
        out->globalA = (SIZE_T)m.base + gA;
        out->globalB = (SIZE_T)m.base + gB;
        out->offA = oA; out->offB = oB; out->offC = oC; out->writeOnly = 0;
        return true;
    }

    out->globalA = (SIZE_T)m.base + gA;
    out->globalB = 0; out->offB = 0; out->offC = 0; out->offA = oA;
    out->writeOnly = 1;
    return true;
}

static bool FindRegSite(const Mod& m, const char* name, RegSiteInfo* out) {
    DWORD nameRva = FindStringRva(m, name);
    if (!nameRva) return false;
    int cnt = 0; DWORD leaRva = 0; BYTE* leaQ = NULL;
    IMAGE_SECTION_HEADER* s = Secs(m);
    for (WORD k = 0; k < SecN(m); k++, s++) {
        if (!(s->Characteristics & 0x20000000u)) continue;
        DWORD va = s->VirtualAddress, vs = s->Misc.VirtualSize;
        if (va >= Soi(m) || vs > Soi(m) - va || vs < 0x1E) continue;
        BYTE* sec = m.base + va;
        for (DWORD p = 0x12; p + 7 <= vs; p++) {
            BYTE* q = sec + p;
            if (q[0] != 0x48 || q[1] != 0x8D || q[2] != 0x15) continue;
            int32_t d; memcpy(&d, q + 3, 4);
            if ((DWORD)(va + p + 7 + (int64_t)d) == nameRva) {
                cnt++; leaRva = va + p; leaQ = q;
            }
        }
    }
    if (cnt != 1 || !leaQ) return false;
    return ExtractRegisteredFn(m, leaQ, leaRva, out);
}

static bool DigRegistrar(const Mod& m, DWORD regRva, DWORD* pPcc, DWORD* pSgl) {
    DWORD end = 0;
    if (!FuncRange(m, regRva, &end)) return false;
    DWORD size = end - regRva;
    if (size < 0x14 || size > 0x800) return false;
    BYTE* b = m.base + regRva;
    for (DWORD p = 0; p + 8 <= size; p++) {
        if (b[p] != 0x4C || b[p + 1] != 0x89 || b[p + 2] != 0xC2) continue;
        for (DWORD t = p + 3; t + 5 <= size && t <= p + 10; t++) {
            if (b[t] != 0xE8) continue;
            bool hasXor = false;
            for (DWORD x = p + 3; x + 3 <= t; x++)
                if (b[x] == 0x45 && b[x + 1] == 0x33 && b[x + 2] == 0xC0) {
                    hasXor = true; break;
                }
            if (!hasXor) continue;
            int32_t d; memcpy(&d, b + t + 1, 4);
            int64_t tgt = (int64_t)regRva + t + 5 + d;
            if (tgt < 0 || (DWORD)tgt >= Soi(m)) continue;
            if (!RvaInSection(m, (DWORD)tgt, 0x20, 0x60000000u)) continue;
            DWORD e1 = 0;
            if (!FuncRange(m, (DWORD)tgt, &e1) || e1 - (DWORD)tgt < 0x20)
                continue;
            for (DWORD u = t + 5; u + 5 <= size && u <= t + 0x25; u++) {
                if (b[u] != 0xE8) continue;
                int32_t d2; memcpy(&d2, b + u + 1, 4);
                int64_t t2 = (int64_t)regRva + u + 5 + d2;
                if (t2 < 0 || (DWORD)t2 >= Soi(m)) continue;
                if ((DWORD)t2 == (DWORD)tgt) continue;
                if (!RvaInSection(m, (DWORD)t2, 0x20, 0x60000000u)) continue;
                DWORD e2 = 0;
                if (!FuncRange(m, (DWORD)t2, &e2) || e2 - (DWORD)t2 < 0x20)
                    continue;
                *pPcc = (DWORD)tgt;
                *pSgl = (DWORD)t2;
                return true;
            }
        }
    }
    return false;
}

static bool ScanRegMech(BYTE* base, const RegSiteInfo* frameSites) {
    Mod m;
    if (!ModOpen(base, &m)) return false;

    DWORD reg[2] = { 0, 0 };  int hasReg[2] = { 0, 0 };
    DWORD pcc[2] = { 0, 0 }, sgl[2] = { 0, 0 };
    int hasPcc[2] = { 0, 0 }, hasSgl[2] = { 0, 0 };

    for (int group = 0; group < 2; group++) {
        for (int i = 0; i < 3; i++) {
            RegSiteInfo si = {};
            if (group == 0) {
                si = frameSites[i];
            }
            else if (!FindRegSite(m, LUA_ANCHOR_SHOP[i], &si)) {
                continue;
            }
            if (si.shape == 3) {
                if (!hasPcc[group]) { pcc[group] = si.call1; hasPcc[group] = 1; }
                else if (pcc[group] != si.call1) hasPcc[group] = -1;
                if (!hasSgl[group]) { sgl[group] = si.call2; hasSgl[group] = 1; }
                else if (sgl[group] != si.call2) hasSgl[group] = -1;
            }
            else if (si.call1) {
                if (!hasReg[group]) { reg[group] = si.call1; hasReg[group] = 1; }
                else if (reg[group] != si.call1) hasReg[group] = -1;
            }
        }
    }

    DWORD pccRva = 0, sglRva = 0;
    int pick = -1;
    for (int group = 0; group < 2; group++)
        if (hasPcc[group] == 1 && hasSgl[group] == 1) { pick = group; break; }
    if (pick >= 0) {
        pccRva = pcc[pick]; sglRva = sgl[pick];
    }
    else {
        int rg = -1;
        for (int group = 0; group < 2; group++)
            if (hasReg[group] == 1) { rg = group; break; }
        if (rg < 0) {
            return false;
        }
        if (!DigRegistrar(m, reg[rg], &pccRva, &sglRva)) {
            return false;
        }
    }

    g_LuaPushCC = (SIZE_T)base + pccRva;
    g_LuaSetGl = (SIZE_T)base + sglRva;
    return true;
}

static bool LocateCfg(SIZE_T L, SIZE_T* pStruct, FrameCfg* snap,
    SIZE_T* pThis, SIZE_T* pMethod, SIZE_T* pHolder) {
    if (!g_FrameReady || g_GiveUp) return false;
    if (GetCurrentThreadId() != g_MainTID) return false;

    SIZE_T mgr = 0, wit = 0;
    if (!RdPtr(g_P1, &mgr) || !mgr) return false;
    if (!RdPtr(mgr, &wit) || wit != L) return false;

    SIZE_T holder = 0, parent = 0, thisp = 0, method = 0;
    if (!RdPtr(g_Fa.globalA, &holder) || !holder) return false;
    if (g_Fa.globalB) {
        if (!RdPtr(g_Fa.globalB, &parent) || !parent) return false;
        thisp = parent + (SIZE_T)(intptr_t)g_Fa.offB;
    }

    SIZE_T cfgp = holder + (SIZE_T)(intptr_t)g_Fa.offA;
    *pStruct = cfgp; *pThis = thisp; *pHolder = holder;

    MEMORY_BASIC_INFORMATION mbi;
    if (!VirtualQuery((LPCVOID)cfgp, &mbi, sizeof(mbi))) return false;
    if (mbi.State != MEM_COMMIT) return false;
    if (mbi.Protect & PAGE_GUARD) return false;
    if (mbi.Type != MEM_PRIVATE) return false;
    if ((SIZE_T)mbi.AllocationBase > cfgp) return false;
    if (((SIZE_T)mbi.BaseAddress - cfgp) + mbi.RegionSize < 0x10) return false;

    FrameCfg cfg;
    if (!Rd(cfgp, &cfg, sizeof(cfg))) return false;
    if (cfg.mn < ENGINE_MIN_RATE) return false;
    if (cfg.mx < cfg.mn || cfg.mx > ENGINE_MAX_RATE) return false;
    if (cfg.step < 1 || cfg.step > 1000) return false;
    if ((ENGINE_MAX_RATE - cfg.mn) % cfg.step != 0) return false;
    if (cfg.cur < cfg.mn || cfg.cur > ENGINE_MAX_RATE) return false;
    *snap = cfg;

    if (thisp) {
        SIZE_T fn0 = 0;
        if (!RdPtr(thisp, &fn0) || !fn0) return false;
        if (!RdPtr(fn0 + (SIZE_T)(intptr_t)g_Fa.offC, &method) || !method) return false;
        MEMORY_BASIC_INFORMATION mbi;
        if (!VirtualQuery((LPCVOID)method, &mbi, sizeof(mbi))) return false;
        if (mbi.State != MEM_COMMIT) return false;
        if (mbi.Type != MEM_IMAGE) return false;
        if (mbi.Protect & PAGE_GUARD) return false;
        if (mbi.Protect != PAGE_EXECUTE && mbi.Protect != PAGE_EXECUTE_READ) return false;
    }
    *pMethod = method;

    if (g_HolderId != holder) {
        g_HolderId = holder;
        g_HaveBackup = false;
    }
    return true;
}

typedef void(__cdecl* EngineCommitFn)(SIZE_T thisPtr, int arg);

static bool NativeApply(SIZE_T L, int rate) {
    if (g_InProgress) return false;
    if ((unsigned)(rate - ENGINE_MIN_RATE) >
        (unsigned)(ENGINE_MAX_RATE - ENGINE_MIN_RATE)) {
        return false;
    }

    SIZE_T st = 0, thisp = 0, method = 0, holder = 0;
    FrameCfg cfg;
    if (!LocateCfg(L, &st, &cfg, &thisp, &method, &holder)) return false;

    if (rate < cfg.mn) return false;
    int rem = (rate - cfg.mn) % cfg.step;
    if (rem) {
        rate -= rem;
        if (rate < cfg.mn) return false;
    }

    if (!g_HaveBackup || g_LastMax != cfg.mx) {
        g_OrigCfg = cfg;
        g_HaveBackup = true;
    }

    int newMax = ENGINE_MAX_RATE;

    g_InProgress = true;
    bool ok = false;
    int* pMax = (int*)(st + 4);
    int* pCur = (int*)(st + 0xC);
    *pMax = newMax;
    *pCur = rate;
    if (method) ((EngineCommitFn)method)(thisp, 0);

    FrameCfg chk;
    if (Rd(st, &chk, sizeof(chk)) && chk.cur == rate && chk.mx == newMax) {
        ok = true;
    }
    else {
        *pMax = cfg.mx;
        *pCur = cfg.cur;
        if (method) ((EngineCommitFn)method)(thisp, 0);
        FrameCfg chk2;
        if (!Rd(st, &chk2, sizeof(chk2)) || chk2.cur != cfg.cur || chk2.mx != cfg.mx)
            g_GiveUp = true;
    }
    g_InProgress = false;

    if (ok) {
        g_Preference = rate;
        g_LastMax = newMax;
        g_AppliedThis = thisp;
        g_AppliedHolder = g_HolderId;
    }
    return ok;
}

static bool Maintain(SIZE_T L) {
    if (g_InProgress) return true;
    if (g_Preference <= MAINTAIN_GATE) return true;

    SIZE_T st = 0, thisp = 0, method = 0, holder = 0;
    FrameCfg cfg;
    if (!LocateCfg(L, &st, &cfg, &thisp, &method, &holder)) return false;

    bool valueChanged = (cfg.cur != g_Preference) || (cfg.mx < g_Preference);
    bool migrated = (g_AppliedHolder != g_HolderId)
        || (thisp && g_AppliedThis != thisp);
    if (!valueChanged && !migrated) return true;

    int target = g_Preference;
    if (!migrated && valueChanged &&
        cfg.cur >= ENGINE_MIN_RATE && cfg.cur <= ENGINE_MAX_RATE) {
        target = cfg.cur;
    }
    return NativeApply(L, target);
}

typedef int(__cdecl* LuaCFn)(SIZE_T L);
typedef void(__cdecl* RegFn)(SIZE_T L, const char* name, SIZE_T fn);
typedef void(__cdecl* PushCCFn)(SIZE_T L, SIZE_T fn, int n);
typedef void(__cdecl* SetGlFn)(SIZE_T L, const char* name);
typedef int(__cdecl* ExecFn)(SIZE_T mgr, const char* path, int a3, int a4);

static void RestoreCeilingOnly(SIZE_T L) {
    SIZE_T st = 0, thisp = 0, method = 0, holder = 0;
    FrameCfg cfg;
    if (!LocateCfg(L, &st, &cfg, &thisp, &method, &holder)) return;
    if (cfg.mx >= ENGINE_MAX_RATE) return;
    int* pMax = (int*)(st + 4);
    int  old = cfg.mx;
    *pMax = ENGINE_MAX_RATE;
    FrameCfg chk;
    if (!Rd(st, &chk, sizeof(chk)) || chk.mx != ENGINE_MAX_RATE || chk.cur != cfg.cur) {
        *pMax = old;
        return;
    }
    g_LastMax = ENGINE_MAX_RATE;
}

static void ApplyFromLua(SIZE_T L, int rate) {
    if (GetCurrentThreadId() != g_MainTID) return;
    SIZE_T mgr = 0, wit = 0;
    if (!RdPtr(g_P1, &mgr) || !mgr) return;
    if (!RdPtr(mgr, &wit) || wit != L) return;
    if (rate == 0) {
        g_Preference = 0;
        RestoreCeilingOnly(L);
        return;
    }
    g_Preference = rate;
    if (!g_InProgress) NativeApply(L, rate);
}

static int LuaSelectSafe(SIZE_T L, int rate) {
    __try { ApplyFromLua(L, rate); }
    __except (EXCEPTION_EXECUTE_HANDLER) {
    }
    return 0;
}
static int LuaSelectLow(SIZE_T L) { return LuaSelectSafe(L, 30000); }
static int LuaSelectMiddle(SIZE_T L) { return LuaSelectSafe(L, 38450); }
static int LuaSelectHigh(SIZE_T L) { return LuaSelectSafe(L, 60000); }
static int LuaSelectExtreme(SIZE_T L) { return LuaSelectSafe(L, 120000); }
static int LuaSelectManual(SIZE_T L) { return LuaSelectSafe(L, 0); }

static const char LUA_UI_SCRIPT[] = R"QQFC(-- QQFC official client 120 FPS tier, session-local (v4 native companion)
local ok,e=pcall(function()
if rawget(_G,"QQFCStandaloneStudio")==nil then
if rawget(_G,"QQFCOfficialFrameUI")==nil then
QQFCOfficialFrameUI=true
QQFCOfficialFrameRates={}
local N=QQFCOfficialFrameRates
local bindings=setmetatable({},{__mode="k"})
local installed,busy=false,false
local popup="UI.ZhenlvDlgPop"
local custom="UI.ZhenlvCustomDlg"
local whole=custom..".CurLabel.ZhenlvEdit1"
local fraction=custom..".CurLabel.ZhenlvEdit2"
local baseGet,baseSet,setWrapper
local preferred
local SELECT={
    [30000]="QQFCOfficialFrameSelectLow",
    [38450]="QQFCOfficialFrameSelectMiddle",
    [60000]="QQFCOfficialFrameSelectHigh",
    [120000]="QQFCOfficialFrameSelectExtreme",
}
local function session()
    return rawget(_G,"QQFCOfficialFrameUI")==true and rawget(_G,"QQFCStandaloneStudio")==nil
end
local function log(message)
    if type(DreamlandLog)=="function" then pcall(DreamlandLog,"[QQFC OfficialFrameRate] "..message) end
end
local function sync_cache(c)
    local dialog=UI and UI.children and UI.children.SysSettingsDlg
    local cached=dialog and dialog._FrameRate
    if type(cached)=="table" and type(c)=="table" then
        for _,key in ipairs({"m_iMinFrameRate","m_iMaxFrameRate","m_iFrameStep","m_iCurrentFrameRate"}) do
            cached[key]=c[key]
        end
        cached.m_iMaxFrameRate=120000
    end
end
local function cached_cfg()
    if type(baseGet)~="function" then return nil end
    local c=baseGet()
    if type(c)~="table" then return nil end
    return c
end
local function install_globals()
    if type(GetClientFrameRateCfg)~="function" or type(SetClientFrameRateCfg)~="function" then
        return false
    end
    if not setWrapper then
        setWrapper=function(rate,...)
            if not session() then return baseSet(rate,...) end
            local values=table.pack(baseSet(rate,...))
            local c=cached_cfg()
            if c then sync_cache(c) end
            return table.unpack(values,1,values.n)
        end
    end
    if SetClientFrameRateCfg~=setWrapper then
        baseSet=SetClientFrameRateCfg
        SetClientFrameRateCfg=setWrapper
    end
    if not baseGet then baseGet=GetClientFrameRateCfg end
    return true
end
local function configuration()
    if type(baseGet)~="function" then return end
    local c=baseGet()
    if type(c)~="table" then return end
    for _,key in ipairs({"m_iMinFrameRate","m_iMaxFrameRate","m_iFrameStep","m_iCurrentFrameRate"}) do
        local v=c[key]
        if type(v)~="number" or v~=v or v%1~=0 then return end
    end
    if c.m_iMinFrameRate<30000 or c.m_iMaxFrameRate>120000 or c.m_iMinFrameRate>=c.m_iMaxFrameRate or
        c.m_iFrameStep<=0 or (c.m_iMaxFrameRate-c.m_iMinFrameRate)%c.m_iFrameStep~=0 or
        c.m_iCurrentFrameRate<c.m_iMinFrameRate or c.m_iCurrentFrameRate>c.m_iMaxFrameRate then return end
    return c
end
local function bind(widget,key,make)
    if type(widget)~="table" or type(widget[key])~="function" then return false end
    local saved=bindings[widget]
    if not saved then saved={};bindings[widget]=saved end
    if saved[key] and widget[key]==saved[key] then return true end
    saved[key]=make(widget[key]);widget[key]=saved[key];return true
end
local function after(original,update)
    return function(...)
        local values=table.pack(original(...))
        pcall(update)
        return table.unpack(values,1,values.n)
    end
end
local function digits(path)
    local text=Win_GetText(path)
    if type(text)~="string" or #text>6 or not text:match("^%d+$") then return end
    return tonumber(text)
end
local function normalize(focus,decimal)
    if busy then return end
    local c=configuration();if not c then return end
    busy=true
    local ok,why=pcall(function()
        local x,y=digits(whole),digits(fraction)
        local minimum=math.ceil(c.m_iMinFrameRate/1000)
        local maximum=math.floor(c.m_iMaxFrameRate/1000)
        if focus and not decimal and (not x or x<minimum) then x=minimum;Win_SetText(whole,tostring(x)) end
        if x and x>maximum then x=maximum;Win_SetText(whole,tostring(x));y=0;Win_SetText(fraction,"00") end
        if decimal and focus and not y then y=0;Win_SetText(fraction,"00") end
        if decimal and y and y>99 then y=99;Win_SetText(fraction,"99") end
        if decimal and focus and y then Win_SetText(fraction,string.format("%02d",y)) end
        if x and y and x*1000+y*10>c.m_iMaxFrameRate then
            y=math.max(0,math.min(99,math.floor((c.m_iMaxFrameRate-x*1000)/10)))
            Win_SetText(fraction,string.format("%02d",y))
        end
    end)
    busy=false
    if not ok then log("custom input rejected: "..tostring(why)) end
end
function N.Select(rate)
    preferred=rate
    if type(baseSet)=="function" then
        local ok,er=pcall(baseSet,rate)
        if not ok then log("engine set failed: "..tostring(er)) end
    end
    local name=SELECT[rate] or "QQFCOfficialFrameSelectManual"
    local f=rawget(_G,name)
    if type(f)=="function" then
        local ok,er=pcall(f)
        if not ok then log("native select failed: "..tostring(er)) end
    end
    local c=cached_cfg()
    if c then sync_cache(c) end
    return true
end
function N.Install()
    if not session() or not install_globals() then return false end
    local children=UI and UI.children
    local p=children and children.ZhenlvDlgPop
    local d=children and children.ZhenlvCustomDlg
    local label=d and d.children and d.children.CurLabel
    local a=label and label.children and label.children.ZhenlvEdit1
    local b=label and label.children and label.children.ZhenlvEdit2
    local button=d and d.children and d.children.okbtn
    if not p or not p.children or not p.children.extremelyhigh or not d or not a or not b or not button then return false end
    for _,name in ipairs({"Win_GetText","Win_SetText","Win_GetRect","Win_SetBackPic","Win_SetRectAll","Win_ShowWidget","Win_RelativePos","Win_EndWidget"}) do
        if type(_G[name])~="function" then return false end
    end
    local ready=bind(p,"OnSelfShow",function(original)return after(original,function()
        local c=configuration();if not c or c.m_iMaxFrameRate<120000 then return end
        local rect=Win_GetRect("UI.SysSettingsDlg.page_display.downBk_ScrollView.list.Btn_Zhenlv")
        if type(rect)~="table" or type(rect.x)~="number" or type(rect.y)~="number" then return end
        Win_SetBackPic(popup,"res/uires/navigation/ZhenlvDlg/zhenlvbetabk.png")
        Win_SetRectAll(popup,rect.x+80,rect.y-85,111,125)
        Win_ShowWidget(popup..".high",true)
        Win_ShowWidget(popup..".extremelyhigh",true)
        Win_RelativePos(popup..".custom",15,90)
    end)end)
    for _,preset in ipairs({{"low",30000},{"middle",38450},{"high",60000},{"extremelyhigh",120000}}) do
        local rate=preset[2]
        ready=bind(p.children[preset[1]],"OnCheck",function(original)return function(state,previous,...)
            local c=configuration()
            if not c or c.m_iMaxFrameRate<120000 then return original(state,previous,...) end
            local ok,er=pcall(function()
                if state==1 and state~=previous and p._show==false and N.Select(rate) then
                    Win_ShowWidget("UI.SysSettingsDlg.page_display.downBk_ScrollView.list.Num_Zhenlv",true)
                end
            end)
            if not ok then log("preset check failed: "..tostring(er)) end
        end end) and ready
    end
    ready=bind(d,"OnSelfShow",function(original)return after(original,function()
        local c=configuration();if not c then return end
        if Model and Model.CommonModel then Model.CommonModel.m_iMaxFrameRate=c.m_iMaxFrameRate/1000 end
        Win_SetText(custom..".CurLabel",string.format("%.2f-%.2f",c.m_iMinFrameRate/1000,c.m_iMaxFrameRate/1000))
    end)end) and ready
    for _,entry in ipairs({{a,"OnValueChange",false,false},{a,"OnLostFocus",true,false},
        {b,"OnValueChange",false,true},{b,"OnLostFocus",true,true}}) do
        local focus,decimal=entry[3],entry[4]
        ready=bind(entry[1],entry[2],function(original)return function(...)
            if not configuration() then return original(...) end
            normalize(focus,decimal)
        end end) and ready
    end
    ready=bind(button,"OnClick",function(original)return function(...)
        local c=configuration();if not c then return original(...) end
        local ok,er=pcall(function()
            local x,y=digits(whole),digits(fraction)
            if x and y and y<=99 then
                local rate=math.max(c.m_iMinFrameRate,math.min(c.m_iMaxFrameRate,x*1000+y*10))
                rate=c.m_iMinFrameRate+math.floor((rate-c.m_iMinFrameRate)/c.m_iFrameStep)*c.m_iFrameStep
                N.Select(rate)
            end
            Win_EndWidget(custom,true)
            Win_ShowWidget("UI.SysSettingsDlg.page_display.downBk_ScrollView.list.Num_Zhenlv",true)
        end)
        if not ok then log("custom apply failed: "..tostring(er)) end
    end end) and ready
    if ready and not installed then
        log("native 120 FPS menu enabled; session-local graphics preference")
    end
    installed=ready;return ready
end
function N.Tick()
    if not preferred then
        local c=configuration()
        if c and c.m_iCurrentFrameRate>60000 then preferred=c.m_iCurrentFrameRate end
    end
    local ready=N.Install()
    if not session() then return ready end
    if preferred then
        local c=cached_cfg()
        if c then sync_cache(c) end
    end
    return ready
end
log("companion loaded; session-local graphics preference")
end
end
end)
if not ok and type(DreamlandLog)=="function" then
    pcall(DreamlandLog,"[QQFC OfficialFrameRate] "..tostring(e))
end
local frameOk,frameError=pcall(function()
    local f=rawget(_G,"QQFCOfficialFrameRates")
    if f then f.Tick() end
end)
if not frameOk and type(DreamlandLog)=="function" then
    pcall(DreamlandLog,"[QQFC OfficialFrameRate] "..tostring(frameError))
end
)QQFC";

static bool WriteUiScript() {
    if (!g_GameDir[0]) {
        return false;
    }
    wchar_t dir1[2 * MAX_PATH], dir2[2 * MAX_PATH];
    swprintf(dir1, 2 * MAX_PATH, L"%s\\userdata", g_GameDir);
    CreateDirectoryW(dir1, NULL);
    swprintf(dir2, 2 * MAX_PATH, L"%s\\QQFCOfficialShopPreview", dir1);
    CreateDirectoryW(dir2, NULL);

    size_t len = sizeof(LUA_UI_SCRIPT) - 1;
    for (int attempt = 0; attempt < 4; attempt++) {
        char rel[MAX_PATH];
        snprintf(rel, MAX_PATH,
            "userdata/QQFCOfficialShopPreview/%lu-%lu-%u.lua",
            GetCurrentProcessId(), GetTickCount(), 0u);
        wchar_t relW[MAX_PATH];
        if (!MultiByteToWideChar(CP_UTF8, 0, rel, -1, relW, MAX_PATH)) return false;
        wchar_t abs[2 * MAX_PATH];
        swprintf(abs, 2 * MAX_PATH, L"%s\\%s", g_GameDir, relW);

        HANDLE h = CreateFileW(abs, GENERIC_WRITE, FILE_SHARE_READ, NULL,
            CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);
        if (h == INVALID_HANDLE_VALUE) {
            DWORD err = GetLastError();
            if (err == ERROR_FILE_EXISTS) continue;
            return false;
        }
        DWORD wrote = 0;
        BOOL wok = WriteFile(h, LUA_UI_SCRIPT, (DWORD)len, &wrote, NULL);
        FlushFileBuffers(h);
        CloseHandle(h);
        if (!wok || wrote != (DWORD)len) {
            DeleteFileW(abs);
            return false;
        }

        HANDLE h2 = CreateFileW(abs, GENERIC_READ, FILE_SHARE_READ, NULL,
            OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
        if (h2 == INVALID_HANDLE_VALUE) {
            return false;
        }
        BYTE* buf = (BYTE*)malloc(len + 1);
        if (!buf) { CloseHandle(h2); return false; }
        DWORD got = 0;
        BOOL rok = ReadFile(h2, buf, (DWORD)len + 1, &got, NULL);
        bool ok = rok && got == (DWORD)len && memcmp(buf, LUA_UI_SCRIPT, len) == 0;
        free(buf);
        if (!ok) {
            CloseHandle(h2);
            DeleteFileW(abs);
            return false;
        }
        memcpy(g_ScriptPathW, abs, (wcslen(abs) + 1) * sizeof(wchar_t));
        memcpy(g_ScriptRelA, rel, strlen(rel) + 1);
        if (!WideCharToMultiByte(CP_ACP, 0, abs, -1, g_ScriptAbsA,
            (int)sizeof(g_ScriptAbsA), NULL, NULL)) {
            CloseHandle(h2);
            DeleteFileW(abs);
            return false;
        }
        g_ScriptH = h2;
        return true;
    }
    return false;
}

static void RegisterLuaNatives(SIZE_T L) {
    static const LuaCFn fns[5] = {
        LuaSelectLow, LuaSelectMiddle, LuaSelectHigh, LuaSelectExtreme, LuaSelectManual
    };
    for (int i = 0; i < 5; i++) {
        ((PushCCFn)g_LuaPushCC)(L, reinterpret_cast<SIZE_T>(fns[i]), 0);
        ((SetGlFn)g_LuaSetGl)(L, LUA_SELECT_NAMES[i]);
    }
}

static void UiInjectCleanup() {
    if (g_ScriptH != INVALID_HANDLE_VALUE) {
        CloseHandle(g_ScriptH);
        g_ScriptH = INVALID_HANDLE_VALUE;
    }
    if (g_ScriptPathW[0]) {
        DeleteFileW(g_ScriptPathW);
        g_ScriptPathW[0] = 0;
    }
    g_ScriptRelA[0] = 0;
}

static void UiScriptStep(SIZE_T mgr, SIZE_T L) {
    if (g_UiOff) return;
    if (!g_Exec || !g_LuaPushCC || !g_LuaSetGl) {
        g_UiOff = true;
        return;
    }
    if (g_ScriptH == INVALID_HANDLE_VALUE) {
        if (!WriteUiScript()) { g_UiOff = true; return; }
    }

    __try {
        RegisterLuaNatives(L);
    }
    __except (EXCEPTION_EXECUTE_HANDLER) {
        g_UiOff = true;
        return;
    }

    int  order[4] = { g_UiExecMode, 0, 1, 2 };
    bool won = false;
    volatile bool switched = false;
    wchar_t oldCwd[MAX_PATH] = {};
    __try {
        for (int i = 0; i < 4 && !won; i++) {
            int mode = order[i];
            if (mode < 0) continue;
            bool dup = false;
            for (int j = 0; j < i; j++)
                if (order[j] == mode) { dup = true; break; }
            if (dup) continue;

            const char* path = (mode == 1) ? g_ScriptAbsA : g_ScriptRelA;
            if (mode == 2) {
                DWORD noc = GetCurrentDirectoryW(MAX_PATH, oldCwd);
                if (noc && noc < MAX_PATH && lstrcmpiW(oldCwd, g_GameDir) != 0)
                    switched = SetCurrentDirectoryW(g_GameDir);
                if (!switched) continue;
            }
            int r = ((ExecFn)g_Exec)(mgr, path, 0, 0);
            if (switched) { SetCurrentDirectoryW(oldCwd); switched = false; }
            if (r == 0) {
                g_UiExecMode = mode;
                won = true;
                g_UiRefused = 0;
            }
        }
    }
    __except (EXCEPTION_EXECUTE_HANDLER) {
        if (switched) SetCurrentDirectoryW(oldCwd);
        g_UiOff = true;
        return;
    }
    if (!won) {
        if (++g_UiRefused > 20) {
            g_UiOff = true;
        }
    }
}

static void Tick() {
    if (GetCurrentThreadId() != g_MainTID) return;
    if (g_GiveUp || !g_FrameReady) return;

    SIZE_T mgr = 0, L = 0;
    if (!RdPtr(g_P1, &mgr) || !mgr) return;
    if (!RdPtr(mgr, &L) || !L) return;

    g_LuaState = L;
    g_InTick = true;
    if (g_Preference == 0) {
        NativeApply(L, FPS_TARGET);
    }
    else {
        Maintain(L);
    }
    UiScriptStep(mgr, L);
    g_InTick = false;
    g_LuaState = 0;
}

static LRESULT CALLBACK GetMsgProc(int code, WPARAM wParam, LPARAM lParam) {
    if (code >= 0 && wParam == PM_REMOVE) {
        MSG* m = (MSG*)lParam;
        if (m->hwnd == g_Wnd && m->message == g_TickMsg
            && m->wParam == MAGIC_WPARAM && m->lParam == MAGIC_LPARAM) {
            if (InterlockedCompareExchange(&g_PostGate, -1, 1) == 1) {
                m->message = 0;
                m->wParam = 0;
                m->lParam = 0;
                __try {
                    Tick();
                }
                __except (EXCEPTION_EXECUTE_HANDLER) {
                    g_GiveUp = true;
                    g_InProgress = false;
                    g_InTick = false;
                    g_LuaState = 0;
                }
                InterlockedExchange(&g_PostGate, 0);
            }
        }
    }
    return CallNextHookEx(g_Hook, code, wParam, lParam);
}

static BOOL CALLBACK FindWnd(HWND hwnd, LPARAM) {
    DWORD pid = 0;
    GetWindowThreadProcessId(hwnd, &pid);
    if (pid != GetCurrentProcessId()) return TRUE;
    if (!IsWindowVisible(hwnd)) return TRUE;
    if (GetWindow(hwnd, GW_OWNER) != NULL) return TRUE;
    RECT rc;
    if (!GetClientRect(hwnd, &rc)) return TRUE;
    if ((rc.bottom - rc.top) < 600) return TRUE;
    if ((rc.right - rc.left) < 400) return TRUE;
    g_Wnd = hwnd;
    return FALSE;
}

static DWORD WINAPI Worker(LPVOID) {
    DWORD tStart = GetTickCount();

    wchar_t path[MAX_PATH];
    DWORD n = GetModuleFileNameW(NULL, path, MAX_PATH);
    if (n && n < MAX_PATH - 1) {
        wchar_t* p = path + n;
        while (p > path && p[-1] != L'\\') p--;
        if (p > path) {
            size_t len = (size_t)(p - path);
            if (len < MAX_PATH) { memcpy(g_GameDir, path, len * 2); g_GameDir[len] = 0; }
        }
    }
    g_TickMsg = RegisterWindowMessageW(TICK_MSG_NAME);
    if (!g_TickMsg) goto cleanup;

    {
        bool scanned = false;
        DWORD lastPost = GetTickCount();

        for (;;) {
            if (g_Stop || g_GiveUp) break;
            if (AUTO_STOP_MINUTES && GetTickCount() - tStart >
                AUTO_STOP_MINUTES * 60000u) {
                break;
            }

            if (!g_Hook) {
                if (!g_Wnd || !IsWindow(g_Wnd)) {
                    g_Wnd = NULL;
                    if (!scanned) {
                        HMODULE h = GetModuleHandleW(ENGINE_MODULE);
                        if (h) {
                            g_hEngine = h;
                            SIZE_T p1 = 0, ex = 0;
                            if (ScanLuaEntry((BYTE*)h, &p1, &ex)) {
                                g_P1 = p1; g_Exec = ex;
                                FrameAnchors fa;
                                RegSiteInfo sites[3] = {};
                                if (ScanFrameApi((BYTE*)h, &fa, sites)) {
                                    g_Fa = fa;
                                    g_FrameReady = true;
                                    if (!ScanRegMech((BYTE*)h, sites)) {
                                        g_UiOff = true;
                                    }
                                }
                                else {
                                    break;
                                }
                            }
                            else {
                                break;
                            }
                            scanned = true;
                        }
                    }
                    if (g_Stop || g_GiveUp) break;
                    EnumWindows(FindWnd, 0);
                    if (g_Wnd) {
                        g_MainTID = GetWindowThreadProcessId(g_Wnd, NULL);
                        g_Hook = SetWindowsHookExW(WH_GETMESSAGE, GetMsgProc,
                            g_hMod, g_MainTID);
                        if (!g_Hook) {
                            break;
                        }
                    }
                }
            }
            else {
                if (IsWindow(g_Wnd)) {
                    DWORD now = GetTickCount();
                    if (now - lastPost >= TICK_INTERVAL_MS) {
                        lastPost = now;
                        if (!g_GiveUp && g_Wnd) {
                            if (InterlockedCompareExchange(&g_PostGate, 1, 0) == 0) {
                                if (!PostMessageW(g_Wnd, g_TickMsg,
                                    MAGIC_WPARAM, MAGIC_LPARAM))
                                    InterlockedExchange(&g_PostGate, 0);
                            }
                        }
                    }
                }
                else {
                    UnhookWindowsHookEx(g_Hook);
                    g_Hook = NULL;
                    g_Wnd = NULL;
                    g_MainTID = 0;
                }
            }
            Sleep(POLL_INTERVAL_MS);
        }
    }

cleanup:
    if (g_Hook) { UnhookWindowsHookEx(g_Hook); g_Hook = NULL; }
    Sleep(300);
    UiInjectCleanup();
    return 0;
}

BOOL APIENTRY DllMain(HMODULE hModule, DWORD reason, LPVOID) {
    switch (reason) {
    case DLL_PROCESS_ATTACH: {
        g_hMod = hModule;
        DisableThreadLibraryCalls(hModule);

        wchar_t exe[MAX_PATH];
        DWORD n = GetModuleFileNameW(NULL, exe, MAX_PATH);
        if (!n || n >= MAX_PATH - 1) return TRUE;
        wchar_t* p = exe + n;
        while (p > exe && p[-1] != L'\\') p--;
        if (p == exe || lstrcmpiW(p, GAME_EXE) != 0) return TRUE;

        HANDLE h = CreateThread(NULL, 0, Worker, NULL, 0, NULL);
        if (h) CloseHandle(h);
        break;
    }
    case DLL_PROCESS_DETACH:
        g_Stop = true;
        if (g_Hook) { UnhookWindowsHookEx(g_Hook); g_Hook = NULL; }
        UiInjectCleanup();
        break;
    default:
        break;
    }
    return TRUE;
}