// Minimal D3D9 forwarding proxy for loading WarcraftXL without editing Wow.exe.

#include <windows.h>
#include <d3d9.h>

namespace
{
    using Create9Fn = IDirect3D9* (WINAPI*)(UINT);
    using Create9ExFn = HRESULT (WINAPI*)(UINT, IDirect3D9Ex**);

    HMODULE g_systemD3D9 = nullptr;
    Create9Fn g_create9 = nullptr;
    Create9ExFn g_create9Ex = nullptr;

    void ResolveSystemD3D9()
    {
        if (g_systemD3D9) return;
        char path[MAX_PATH] = {};
        const UINT length = GetSystemDirectoryA(path, MAX_PATH);
        if (!length || length >= MAX_PATH - 10) return;
        lstrcatA(path, "\\d3d9.dll");
        g_systemD3D9 = LoadLibraryA(path);
        if (!g_systemD3D9) return;
        g_create9 = reinterpret_cast<Create9Fn>(GetProcAddress(g_systemD3D9, "Direct3DCreate9"));
        g_create9Ex = reinterpret_cast<Create9ExFn>(GetProcAddress(g_systemD3D9, "Direct3DCreate9Ex"));
    }

    void LoadWarcraftXL()
    {
        static bool attempted = false;
        if (attempted) return;
        attempted = true;
        LoadLibraryA("WarcraftXL.dll");
    }
}

extern "C" IDirect3D9* WINAPI Direct3DCreate9(UINT sdkVersion)
{
    ResolveSystemD3D9();
    LoadWarcraftXL();
    return g_create9 ? g_create9(sdkVersion) : nullptr;
}

extern "C" HRESULT WINAPI Direct3DCreate9Ex(UINT sdkVersion, IDirect3D9Ex** output)
{
    ResolveSystemD3D9();
    LoadWarcraftXL();
    if (g_create9Ex) return g_create9Ex(sdkVersion, output);
    if (output) *output = nullptr;
    return E_NOINTERFACE;
}

// Compatibility exports referenced by the current WarcraftXL core. MoonWell
// does not enable its D3D9On12 backend, so these intentionally report no D3D12
// device and a neutral supersampling factor.
extern "C" void* WxlD3D12Device() { return nullptr; }
extern "C" void* WxlD3D12Queue() { return nullptr; }
extern "C" void WxlD3D12DrainDebug() {}
extern "C" void WxlSetSsaaFactor(float) {}
extern "C" float WxlGetSsaaFactor() { return 1.0f; }

BOOL WINAPI DllMain(HINSTANCE, DWORD, LPVOID)
{
    return TRUE;
}
