feat: port aelrynth 2026.9.27.2 snapshot onto GitHub history

Overlay upstream/main (9b5e276) onto BlankenshipG main without rewriting
history. Keep origin-only Decal/plugin/docs trees. Re-apply aelrynth.com
and sibling-fork URL fixes that aelrynth git still has as tombohar links.

Co-authored-by: BlankenshipG <BlankenshipG@users.noreply.github.com>
This commit is contained in:
Cursor Agent 2026-10-04 15:43:50 +00:00
commit 4ddbb52eb2
No known key found for this signature in database
244 changed files with 59710 additions and 3067 deletions

369
spikes/WglDxInterop/D3D9.cs Normal file
View file

@ -0,0 +1,369 @@
// Plain D3D9 device + render-target texture. Mimics AC's setup: Direct3DCreate9
// (NOT Ex), SOFTWARE_VERTEXPROCESSING (matches what AC's actual device uses, per
// the engine's MultiClient hooks). The interop chain we're testing in this spike
// must work against a non-Ex device because that's what AC ships.
using System;
using System.Runtime.InteropServices;
namespace WglDxInterop;
internal sealed unsafe class D3D9Host : IDisposable
{
public const uint D3D_SDK_VERSION = 32;
public const uint D3DDEVTYPE_HAL = 1;
public const uint D3DCREATE_FPU_PRESERVE = 0x00000002;
public const uint D3DCREATE_MULTITHREADED = 0x00000004;
public const uint D3DCREATE_SOFTWARE_VERTEXPROCESSING = 0x00000020;
public const uint D3DFMT_UNKNOWN = 0;
public const uint D3DFMT_A8R8G8B8 = 21;
public const uint D3DSWAPEFFECT_DISCARD = 1;
public const uint D3DPOOL_DEFAULT = 0;
public const uint D3DUSAGE_RENDERTARGET = 0x00000001;
public const uint D3DFVF_XYZRHW = 0x004;
public const uint D3DFVF_TEX1 = 0x100;
public const uint D3DPT_TRIANGLESTRIP = 5;
public const uint D3DRS_LIGHTING = 137;
public const uint D3DRS_ZENABLE = 7;
public const uint D3DRS_CULLMODE = 22;
public const uint D3DCULL_NONE = 1;
public const uint D3DTSS_COLOROP = 1;
public const uint D3DTSS_COLORARG1 = 2;
public const uint D3DTSS_ALPHAOP = 4;
public const uint D3DTSS_ALPHAARG1 = 5;
public const uint D3DTOP_SELECTARG1 = 2;
public const uint D3DTA_TEXTURE = 2;
public const uint D3DSAMP_MINFILTER = 5;
public const uint D3DSAMP_MAGFILTER = 6;
public const uint D3DTEXF_LINEAR = 2;
[StructLayout(LayoutKind.Sequential)]
public struct D3DPRESENT_PARAMETERS
{
public uint BackBufferWidth;
public uint BackBufferHeight;
public uint BackBufferFormat;
public uint BackBufferCount;
public uint MultiSampleType;
public uint MultiSampleQuality;
public uint SwapEffect;
public IntPtr hDeviceWindow;
public int Windowed;
public int EnableAutoDepthStencil;
public uint AutoDepthStencilFormat;
public uint Flags;
public uint FullScreen_RefreshRateInHz;
public uint PresentationInterval;
}
[StructLayout(LayoutKind.Sequential)]
public struct D3DVIEWPORT9 { public uint X, Y, Width, Height; public float MinZ, MaxZ; }
[DllImport("d3d9.dll")]
public static extern IntPtr Direct3DCreate9(uint sdkVersion);
[DllImport("d3d9.dll")]
public static extern int Direct3DCreate9Ex(uint sdkVersion, out IntPtr pD3D9Ex);
public const int IDirect3D9Ex_CreateDeviceEx = 20;
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate int CreateDeviceExD(IntPtr pD3D9Ex, uint adapter, uint deviceType, IntPtr hFocusWindow,
uint behaviorFlags, IntPtr pPresentationParameters, IntPtr pFullscreenDisplayMode,
out IntPtr ppReturnedDeviceInterface);
// Vtable indexes for IDirect3D9 / IDirect3DDevice9 / IDirect3DTexture9.
// Cross-checked against the engine's D3D9VTable.cs at investigation time.
public const int IDirect3D9_CreateDevice = 16;
public const int IDirect3D9_Release = 2;
public const int IDirect3DDevice9_TestCooperativeLevel = 3;
public const int IDirect3DDevice9_Reset = 16;
public const int IDirect3DDevice9_Present = 17;
public const int IDirect3DDevice9_BeginScene = 41;
public const int IDirect3DDevice9_EndScene = 42;
public const int IDirect3DDevice9_Clear = 43;
public const int IDirect3DDevice9_SetRenderState = 57;
public const int IDirect3DDevice9_SetTextureStageState = 60;
public const int IDirect3DDevice9_SetSamplerState = 62;
public const int IDirect3DDevice9_SetTexture = 65;
public const int IDirect3DDevice9_SetFVF = 89;
public const int IDirect3DDevice9_DrawPrimitiveUP = 83;
public const int IDirect3DDevice9_CreateTexture = 23;
public const int IDirect3DDevice9_Release = 2;
public const int IDirect3DTexture9_Release = 2;
public const int IDirect3DTexture9_GetSurfaceLevel = 18;
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate int CreateDeviceD(IntPtr pD3D9, uint adapter, uint deviceType, IntPtr hFocusWindow,
uint behaviorFlags, IntPtr pPresentationParameters, out IntPtr ppReturnedDeviceInterface);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate uint ReleaseD(IntPtr pObj);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate int CreateTextureD(IntPtr dev, uint w, uint h, uint levels, uint usage,
uint fmt, uint pool, out IntPtr ppTex, IntPtr pSharedHandle);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate int PresentD(IntPtr dev, IntPtr pSourceRect, IntPtr pDestRect,
IntPtr hDestWindowOverride, IntPtr pDirtyRegion);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate int ClearD(IntPtr dev, uint count, IntPtr pRects, uint flags, uint color, float z, uint stencil);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate int BeginSceneD(IntPtr dev);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate int EndSceneD(IntPtr dev);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate int SetRenderStateD(IntPtr dev, uint state, uint value);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate int SetTextureStageStateD(IntPtr dev, uint stage, uint type, uint value);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate int SetSamplerStateD(IntPtr dev, uint stage, uint type, uint value);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate int SetTextureD(IntPtr dev, uint stage, IntPtr pTex);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate int SetFVFD(IntPtr dev, uint fvf);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate int DrawPrimitiveUPD(IntPtr dev, uint primType, uint primCount, IntPtr pVtxData, uint vtxStride);
public IntPtr Direct3D9 { get; private set; }
public IntPtr Device { get; private set; }
public uint AdapterIndex { get; private set; }
public bool IsEx { get; private set; }
private CreateTextureD? _createTexture;
private PresentD? _present;
private ClearD? _clear;
private BeginSceneD? _beginScene;
private EndSceneD? _endScene;
private SetRenderStateD? _setRenderState;
private SetTextureStageStateD? _setTexStageState;
private SetSamplerStateD? _setSamplerState;
private SetTextureD? _setTexture;
private SetFVFD? _setFvf;
private DrawPrimitiveUPD? _drawPrimitiveUp;
public void Initialize(IntPtr hwnd, int width, int height) => InitializeInternal(hwnd, width, height, useEx: false);
/// <summary>D3D9Ex variant — required if WGL_NV_DX_interop needs shared-handle textures.</summary>
public void InitializeEx(IntPtr hwnd, int width, int height) => InitializeInternal(hwnd, width, height, useEx: true);
private void InitializeInternal(IntPtr hwnd, int width, int height, bool useEx)
{
if (useEx)
{
int hrEx = Direct3DCreate9Ex(D3D_SDK_VERSION, out IntPtr pEx);
if (hrEx < 0 || pEx == IntPtr.Zero)
throw new InvalidOperationException($"Direct3DCreate9Ex failed, HRESULT=0x{hrEx:X8}.");
Direct3D9 = pEx;
IsEx = true;
}
else
{
Direct3D9 = Direct3DCreate9(D3D_SDK_VERSION);
if (Direct3D9 == IntPtr.Zero)
throw new InvalidOperationException("Direct3DCreate9 returned null. Ensure d3d9.dll is present.");
IsEx = false;
}
var pp = new D3DPRESENT_PARAMETERS
{
BackBufferWidth = (uint)width,
BackBufferHeight = (uint)height,
BackBufferFormat = D3DFMT_A8R8G8B8,
BackBufferCount = 1,
SwapEffect = D3DSWAPEFFECT_DISCARD,
hDeviceWindow = hwnd,
Windowed = 1,
EnableAutoDepthStencil = 0,
AutoDepthStencilFormat = D3DFMT_UNKNOWN,
PresentationInterval = 0
};
IntPtr pPP = Marshal.AllocHGlobal(Marshal.SizeOf<D3DPRESENT_PARAMETERS>());
try
{
Marshal.StructureToPtr(pp, pPP, false);
IntPtr d3dVtable = Marshal.ReadIntPtr(Direct3D9);
int hr;
IntPtr device;
if (useEx)
{
var createDeviceEx = Marshal.GetDelegateForFunctionPointer<CreateDeviceExD>(
Marshal.ReadIntPtr(d3dVtable, IDirect3D9Ex_CreateDeviceEx * IntPtr.Size));
hr = createDeviceEx(
Direct3D9, 0, D3DDEVTYPE_HAL, hwnd,
0x00000040u /*D3DCREATE_HARDWARE_VERTEXPROCESSING*/ | D3DCREATE_FPU_PRESERVE,
pPP, IntPtr.Zero, out device);
}
else
{
var createDevice = Marshal.GetDelegateForFunctionPointer<CreateDeviceD>(
Marshal.ReadIntPtr(d3dVtable, IDirect3D9_CreateDevice * IntPtr.Size));
hr = createDevice(
Direct3D9, 0, D3DDEVTYPE_HAL, hwnd,
0x00000040u /*D3DCREATE_HARDWARE_VERTEXPROCESSING*/ | D3DCREATE_FPU_PRESERVE,
pPP, out device);
}
if (hr < 0 || device == IntPtr.Zero)
throw new InvalidOperationException($"CreateDevice{(useEx ? "Ex" : "")} failed, HRESULT=0x{hr:X8}");
Device = device;
AdapterIndex = 0;
CacheDeviceMethods();
}
finally
{
Marshal.FreeHGlobal(pPP);
}
}
/// <summary>
/// D3D9Ex-only: create an RT texture with a non-null pSharedHandle slot so
/// the driver allocates a kernel-mode shared handle for the texture. The
/// returned shared handle can then be passed to wglDXSetResourceShareHandleNV.
/// On a non-Ex device this returns a texture but the share handle stays null.
/// </summary>
public IntPtr CreateRenderTargetTextureWithSharedHandle(int width, int height, out IntPtr sharedHandle)
{
if (_createTexture == null) throw new InvalidOperationException("Device not initialized.");
sharedHandle = IntPtr.Zero;
// CreateTexture's pSharedHandle is in/out: caller passes a pointer to
// a HANDLE; on D3D9Ex devices the driver writes the kernel handle there.
unsafe
{
IntPtr handle = IntPtr.Zero;
int hr = _createTexture(Device, (uint)width, (uint)height, 1,
D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT,
out IntPtr tex, new IntPtr(&handle));
if (hr < 0 || tex == IntPtr.Zero)
throw new InvalidOperationException($"CreateTexture(RT shared {width}x{height}) failed, HRESULT=0x{hr:X8}");
sharedHandle = handle;
return tex;
}
}
private void CacheDeviceMethods()
{
IntPtr vtbl = Marshal.ReadIntPtr(Device);
_createTexture = GetMethod<CreateTextureD>(vtbl, IDirect3DDevice9_CreateTexture);
_present = GetMethod<PresentD>(vtbl, IDirect3DDevice9_Present);
_clear = GetMethod<ClearD>(vtbl, IDirect3DDevice9_Clear);
_beginScene = GetMethod<BeginSceneD>(vtbl, IDirect3DDevice9_BeginScene);
_endScene = GetMethod<EndSceneD>(vtbl, IDirect3DDevice9_EndScene);
_setRenderState = GetMethod<SetRenderStateD>(vtbl, IDirect3DDevice9_SetRenderState);
_setTexStageState = GetMethod<SetTextureStageStateD>(vtbl, IDirect3DDevice9_SetTextureStageState);
_setSamplerState = GetMethod<SetSamplerStateD>(vtbl, IDirect3DDevice9_SetSamplerState);
_setTexture = GetMethod<SetTextureD>(vtbl, IDirect3DDevice9_SetTexture);
_setFvf = GetMethod<SetFVFD>(vtbl, IDirect3DDevice9_SetFVF);
_drawPrimitiveUp = GetMethod<DrawPrimitiveUPD>(vtbl, IDirect3DDevice9_DrawPrimitiveUP);
}
private static T GetMethod<T>(IntPtr vtable, int index) where T : Delegate
=> Marshal.GetDelegateForFunctionPointer<T>(Marshal.ReadIntPtr(vtable, index * IntPtr.Size));
/// <summary>Creates an A8R8G8B8 texture in D3DPOOL_DEFAULT with RENDERTARGET usage.</summary>
public IntPtr CreateRenderTargetTexture(int width, int height)
{
if (_createTexture == null) throw new InvalidOperationException("Device not initialized.");
int hr = _createTexture(Device, (uint)width, (uint)height, 1,
D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT,
out IntPtr tex, IntPtr.Zero);
if (hr < 0 || tex == IntPtr.Zero)
throw new InvalidOperationException($"CreateTexture(RT {width}x{height}) failed, HRESULT=0x{hr:X8}");
return tex;
}
/// <summary>Returns IDirect3DSurface9* for level 0 of the texture. Caller releases.</summary>
public IntPtr GetTextureSurfaceLevel0(IntPtr texture)
{
if (texture == IntPtr.Zero) return IntPtr.Zero;
IntPtr texVtbl = Marshal.ReadIntPtr(texture);
var getSurfaceLevel = Marshal.GetDelegateForFunctionPointer<GetSurfaceLevelD>(
Marshal.ReadIntPtr(texVtbl, IDirect3DTexture9_GetSurfaceLevel * IntPtr.Size));
int hr = getSurfaceLevel(texture, 0, out IntPtr surface);
if (hr < 0 || surface == IntPtr.Zero)
throw new InvalidOperationException($"GetSurfaceLevel(0) failed, HRESULT=0x{hr:X8}");
return surface;
}
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int GetSurfaceLevelD(IntPtr tex, uint level, out IntPtr ppSurface);
public void ReleaseObject(IntPtr pObj)
{
if (pObj == IntPtr.Zero) return;
IntPtr vtbl = Marshal.ReadIntPtr(pObj);
var release = Marshal.GetDelegateForFunctionPointer<ReleaseD>(
Marshal.ReadIntPtr(vtbl, 2 * IntPtr.Size));
release(pObj);
}
// ─── Frame helpers ────────────────────────────────────────────────────
public int Clear(uint argbColor) => _clear!(Device, 0, IntPtr.Zero, 0x00000001 /*D3DCLEAR_TARGET*/, argbColor, 1.0f, 0);
public int BeginScene() => _beginScene!(Device);
public int EndScene() => _endScene!(Device);
public int Present() => _present!(Device, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
public void DrawTexturedQuad(IntPtr texture, float W, float H)
{
// Pre-transformed XYZRHW vertices; matches OverlayTextureRenderer.cs in the engine.
// -0.5 offset is the D3D9 half-texel rule.
Span<QuadVertex> verts = stackalloc QuadVertex[4];
verts[0] = new QuadVertex { X = -0.5f, Y = -0.5f, Z = 0, RHW = 1, U = 0, V = 0 };
verts[1] = new QuadVertex { X = W - 0.5f, Y = -0.5f, Z = 0, RHW = 1, U = 1, V = 0 };
verts[2] = new QuadVertex { X = -0.5f, Y = H - 0.5f, Z = 0, RHW = 1, U = 0, V = 1 };
verts[3] = new QuadVertex { X = W - 0.5f, Y = H - 0.5f, Z = 0, RHW = 1, U = 1, V = 1 };
_setRenderState!(Device, D3DRS_LIGHTING, 0);
_setRenderState!(Device, D3DRS_ZENABLE, 0);
_setRenderState!(Device, D3DRS_CULLMODE, D3DCULL_NONE);
_setTexStageState!(Device, 0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
_setTexStageState!(Device, 0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
_setTexStageState!(Device, 0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
_setTexStageState!(Device, 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
_setSamplerState!(Device, 0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
_setSamplerState!(Device, 0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
_setFvf!(Device, D3DFVF_XYZRHW | D3DFVF_TEX1);
_setTexture!(Device, 0, texture);
fixed (QuadVertex* p = verts)
{
_drawPrimitiveUp!(Device, D3DPT_TRIANGLESTRIP, 2, (IntPtr)p, (uint)sizeof(QuadVertex));
}
_setTexture!(Device, 0, IntPtr.Zero);
}
public void Dispose()
{
if (Device != IntPtr.Zero)
{
ReleaseObject(Device);
Device = IntPtr.Zero;
}
if (Direct3D9 != IntPtr.Zero)
{
ReleaseObject(Direct3D9);
Direct3D9 = IntPtr.Zero;
}
}
[StructLayout(LayoutKind.Sequential)]
private struct QuadVertex
{
public float X, Y, Z, RHW;
public float U, V;
}
}

201
spikes/WglDxInterop/Gl.cs Normal file
View file

@ -0,0 +1,201 @@
// OpenGL + WGL bootstrap. We need a real GL context (not ANGLE) to access the
// WGL_NV_DX_interop2 extension, which is the whole point of the spike.
//
// Sequence:
// 1. Create a hidden Win32 window and DC.
// 2. ChoosePixelFormat / SetPixelFormat with a basic 32-bit RGBA / no depth format.
// 3. wglCreateContext → fallback GL 1.x context, just to bootstrap.
// 4. wglMakeCurrent the fallback so we can call wglGetProcAddress for ARB extensions.
// 5. (Optional) wglCreateContextAttribsARB to upgrade to 3.3 core. Skia GL needs this.
// 6. Load WGL_NV_DX_interop2 entry points via wglGetProcAddress.
// 7. Confirm the extension string contains "WGL_NV_DX_interop2".
//
// Spike question A7 (multi-adapter): on a laptop with dGPU+iGPU, the default GL
// context may be on the wrong adapter. Confirming this requires hardware to test.
// For now, the spike just uses whatever the default DC ends up on.
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace WglDxInterop;
internal static unsafe class Gl
{
// ─── opengl32.dll core ────────────────────────────────────────────────
[DllImport("opengl32.dll")] public static extern IntPtr wglCreateContext(IntPtr hdc);
[DllImport("opengl32.dll")] public static extern bool wglMakeCurrent(IntPtr hdc, IntPtr hglrc);
[DllImport("opengl32.dll")] public static extern bool wglDeleteContext(IntPtr hglrc);
[DllImport("opengl32.dll")] public static extern IntPtr wglGetCurrentContext();
[DllImport("opengl32.dll")] public static extern IntPtr wglGetCurrentDC();
[DllImport("opengl32.dll", CharSet = CharSet.Ansi)] public static extern IntPtr wglGetProcAddress(string name);
// ─── core GL we need (resolved via wglGetProcAddress for >=GL 1.5 / ARB) ──
[UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void glClearD(uint mask);
[UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void glClearColorD(float r, float g, float b, float a);
[UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void glViewportD(int x, int y, int w, int h);
[UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void glFinishD();
[UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void glFlushD();
[UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate IntPtr glGetStringD(uint name);
[UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void glGenTexturesD(int n, uint* textures);
[UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void glDeleteTexturesD(int n, uint* textures);
[UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void glBindTextureD(uint target, uint texture);
// FBO entry points (GL 3.0 / ARB_framebuffer_object)
[UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void glGenFramebuffersD(int n, uint* framebuffers);
[UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void glDeleteFramebuffersD(int n, uint* framebuffers);
[UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void glBindFramebufferD(uint target, uint framebuffer);
[UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void glFramebufferTexture2DD(uint target, uint attachment, uint textarget, uint texture, int level);
[UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate uint glCheckFramebufferStatusD(uint target);
// GL constants we need
public const uint GL_VENDOR = 0x1F00;
public const uint GL_RENDERER = 0x1F01;
public const uint GL_VERSION = 0x1F02;
public const uint GL_EXTENSIONS = 0x1F03;
public const uint GL_TEXTURE_2D = 0x0DE1;
public const uint GL_TEXTURE_RECTANGLE = 0x84F5;
public const uint GL_FRAMEBUFFER = 0x8D40;
public const uint GL_COLOR_ATTACHMENT0 = 0x8CE0;
public const uint GL_FRAMEBUFFER_COMPLETE = 0x8CD5;
public const uint GL_COLOR_BUFFER_BIT = 0x00004000;
// ─── WGL_ARB_extensions_string + WGL_ARB_create_context ────────────────
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate IntPtr wglGetExtensionsStringARBD(IntPtr hdc);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate IntPtr wglCreateContextAttribsARBD(IntPtr hdc, IntPtr hShareContext, int* attribList);
public const int WGL_CONTEXT_MAJOR_VERSION_ARB = 0x2091;
public const int WGL_CONTEXT_MINOR_VERSION_ARB = 0x2092;
public const int WGL_CONTEXT_PROFILE_MASK_ARB = 0x9126;
public const int WGL_CONTEXT_CORE_PROFILE_BIT_ARB = 0x00000001;
// ─── WGL_NV_DX_interop2 ────────────────────────────────────────────────
// Function signatures from the registered extension spec at
// https://registry.khronos.org/OpenGL/extensions/NV/WGL_NV_DX_interop.txt
// (DX_interop2 is the same surface; v2 just lifts the D3D11 restriction.)
public const uint WGL_ACCESS_READ_ONLY_NV = 0x00000000;
public const uint WGL_ACCESS_READ_WRITE_NV = 0x00000001;
public const uint WGL_ACCESS_WRITE_DISCARD_NV = 0x00000002;
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate IntPtr wglDXOpenDeviceNVD(IntPtr dxDevice);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate bool wglDXCloseDeviceNVD(IntPtr hDevice);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate IntPtr wglDXRegisterObjectNVD(IntPtr hDevice, IntPtr dxObject, uint name, uint type, uint access);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate bool wglDXUnregisterObjectNVD(IntPtr hDevice, IntPtr hObject);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate bool wglDXLockObjectsNVD(IntPtr hDevice, int count, IntPtr* objects);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate bool wglDXUnlockObjectsNVD(IntPtr hDevice, int count, IntPtr* objects);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate bool wglDXSetResourceShareHandleNVD(IntPtr dxObject, IntPtr shareHandle);
public sealed class Bindings
{
public glClearD glClear = null!;
public glClearColorD glClearColor = null!;
public glViewportD glViewport = null!;
public glFinishD glFinish = null!;
public glFlushD glFlush = null!;
public glGetStringD glGetString = null!;
public glGenTexturesD glGenTextures = null!;
public glDeleteTexturesD glDeleteTextures = null!;
public glBindTextureD glBindTexture = null!;
public glGenFramebuffersD glGenFramebuffers = null!;
public glDeleteFramebuffersD glDeleteFramebuffers = null!;
public glBindFramebufferD glBindFramebuffer = null!;
public glFramebufferTexture2DD glFramebufferTexture2D = null!;
public glCheckFramebufferStatusD glCheckFramebufferStatus = null!;
public wglDXOpenDeviceNVD wglDXOpenDeviceNV = null!;
public wglDXCloseDeviceNVD wglDXCloseDeviceNV = null!;
public wglDXRegisterObjectNVD wglDXRegisterObjectNV = null!;
public wglDXUnregisterObjectNVD wglDXUnregisterObjectNV = null!;
public wglDXLockObjectsNVD wglDXLockObjectsNV = null!;
public wglDXUnlockObjectsNVD wglDXUnlockObjectsNV = null!;
public wglDXSetResourceShareHandleNVD? wglDXSetResourceShareHandleNV; // optional; only needed for D3D9 shared HANDLE textures
public bool Loaded;
}
public static T Resolve<T>(string name) where T : Delegate
{
IntPtr proc = wglGetProcAddress(name);
if (proc == IntPtr.Zero || proc == new IntPtr(1) || proc == new IntPtr(2) || proc == new IntPtr(3) || proc == new IntPtr(-1))
{
// wglGetProcAddress returns 1/2/3/-1 on some drivers when the name isn't a real ICD entry; fall through to opengl32 itself.
IntPtr opengl32 = Win32.LoadLibraryA("opengl32.dll");
proc = Win32.GetProcAddress(opengl32, name);
}
if (proc == IntPtr.Zero)
throw new InvalidOperationException($"GL proc not found: {name}");
return Marshal.GetDelegateForFunctionPointer<T>(proc);
}
public static T? TryResolve<T>(string name) where T : Delegate
{
IntPtr proc = wglGetProcAddress(name);
if (proc == IntPtr.Zero || proc == new IntPtr(1) || proc == new IntPtr(2) || proc == new IntPtr(3) || proc == new IntPtr(-1))
{
IntPtr opengl32 = Win32.LoadLibraryA("opengl32.dll");
proc = Win32.GetProcAddress(opengl32, name);
}
if (proc == IntPtr.Zero) return null;
return Marshal.GetDelegateForFunctionPointer<T>(proc);
}
public static Bindings LoadAll()
{
var b = new Bindings
{
glClear = Resolve<glClearD>("glClear"),
glClearColor = Resolve<glClearColorD>("glClearColor"),
glViewport = Resolve<glViewportD>("glViewport"),
glFinish = Resolve<glFinishD>("glFinish"),
glFlush = Resolve<glFlushD>("glFlush"),
glGetString = Resolve<glGetStringD>("glGetString"),
glGenTextures = Resolve<glGenTexturesD>("glGenTextures"),
glDeleteTextures = Resolve<glDeleteTexturesD>("glDeleteTextures"),
glBindTexture = Resolve<glBindTextureD>("glBindTexture"),
glGenFramebuffers = Resolve<glGenFramebuffersD>("glGenFramebuffers"),
glDeleteFramebuffers = Resolve<glDeleteFramebuffersD>("glDeleteFramebuffers"),
glBindFramebuffer = Resolve<glBindFramebufferD>("glBindFramebuffer"),
glFramebufferTexture2D = Resolve<glFramebufferTexture2DD>("glFramebufferTexture2D"),
glCheckFramebufferStatus = Resolve<glCheckFramebufferStatusD>("glCheckFramebufferStatus"),
wglDXOpenDeviceNV = Resolve<wglDXOpenDeviceNVD>("wglDXOpenDeviceNV"),
wglDXCloseDeviceNV = Resolve<wglDXCloseDeviceNVD>("wglDXCloseDeviceNV"),
wglDXRegisterObjectNV = Resolve<wglDXRegisterObjectNVD>("wglDXRegisterObjectNV"),
wglDXUnregisterObjectNV = Resolve<wglDXUnregisterObjectNVD>("wglDXUnregisterObjectNV"),
wglDXLockObjectsNV = Resolve<wglDXLockObjectsNVD>("wglDXLockObjectsNV"),
wglDXUnlockObjectsNV = Resolve<wglDXUnlockObjectsNVD>("wglDXUnlockObjectsNV"),
wglDXSetResourceShareHandleNV = TryResolve<wglDXSetResourceShareHandleNVD>("wglDXSetResourceShareHandleNV"),
Loaded = true,
};
return b;
}
public static string GetGlString(Bindings b, uint name)
{
IntPtr p = b.glGetString(name);
return p == IntPtr.Zero ? "<null>" : Marshal.PtrToStringAnsi(p) ?? "<null>";
}
public static string GetWglExtensionsString(IntPtr hdc)
{
var fn = TryResolve<wglGetExtensionsStringARBD>("wglGetExtensionsStringARB");
if (fn == null) return string.Empty;
IntPtr p = fn(hdc);
return p == IntPtr.Zero ? string.Empty : Marshal.PtrToStringAnsi(p) ?? string.Empty;
}
}

View file

@ -0,0 +1,165 @@
// One unit of "shared" texture state:
// - A D3D9 RT texture on AC's-emulated device (POOL_DEFAULT, USAGE_RENDERTARGET).
// - A GL texture name + FBO bound to that texture via wglDXRegisterObjectNV.
// - The interop handle returned by Register that we Lock/Unlock per frame.
//
// The Phase A spike doesn't render Skia yet — it just clears the FBO to a known
// animated color so we can verify the chain visually. Skia integration is
// straight after the chain is proven.
using System;
using System.Runtime.InteropServices;
namespace WglDxInterop;
internal sealed unsafe class InteropTexture : IDisposable
{
public IntPtr D3D9Texture { get; private set; }
public IntPtr D3D9Surface { get; private set; }
public uint GlTexture { get; private set; }
public uint GlFramebuffer { get; private set; }
public IntPtr WglObject { get; private set; }
public int Width { get; }
public int Height { get; }
private readonly Gl.Bindings _gl;
private readonly D3D9Host _d3d;
private readonly IntPtr _wglDevice;
public InteropTexture(Gl.Bindings gl, D3D9Host d3d, IntPtr wglDevice, int width, int height)
{
_gl = gl;
_d3d = d3d;
_wglDevice = wglDevice;
Width = width;
Height = height;
// Step 1 — D3D9 RT texture. If Ex, get a shared handle too.
IntPtr sharedHandle = IntPtr.Zero;
if (d3d.IsEx)
{
D3D9Texture = d3d.CreateRenderTargetTextureWithSharedHandle(width, height, out sharedHandle);
Console.WriteLine($"[spike] D3D9Ex RT created with sharedHandle=0x{sharedHandle:X8}");
}
else
{
D3D9Texture = d3d.CreateRenderTargetTexture(width, height);
}
// Step 1b — WGL_NV_DX_interop on D3D9 only supports SURFACES, not the
// ID3DTexture wrapper. Get the level-0 IDirect3DSurface9 and register
// that. The GL side still sees it as GL_TEXTURE_2D.
D3D9Surface = d3d.GetTextureSurfaceLevel0(D3D9Texture);
// Step 1c — If we have a shared handle, register it BEFORE Register.
// This is required by NVIDIA's implementation when the resource has
// a shared handle, even when the GL context's interop device matches
// the D3D device that created the resource.
if (sharedHandle != IntPtr.Zero && gl.wglDXSetResourceShareHandleNV != null)
{
bool setOk = gl.wglDXSetResourceShareHandleNV(D3D9Surface, sharedHandle);
Console.WriteLine($"[spike] wglDXSetResourceShareHandleNV(surface) → {setOk}");
if (!setOk)
throw new InvalidOperationException($"wglDXSetResourceShareHandleNV failed (LastError=0x{Marshal.GetLastWin32Error():X}).");
}
// Step 2 — GL texture name to receive the binding.
uint glTex = 0;
gl.glGenTextures(1, &glTex);
if (glTex == 0) throw new InvalidOperationException("glGenTextures returned 0.");
GlTexture = glTex;
// Step 3 — Register the D3D9 surface as a GL texture under the GL context.
// Try a sequence of (target, access) combinations and (texture vs surface) until one
// succeeds. NVIDIA's WGL_NV_DX_interop driver has historically been picky about
// which D3D9 source types it accepts.
var attempts = new[] {
(Label: "surface, GL_TEXTURE_2D, WRITE_DISCARD", Obj: D3D9Surface, Type: Gl.GL_TEXTURE_2D, Access: Gl.WGL_ACCESS_WRITE_DISCARD_NV),
(Label: "surface, GL_TEXTURE_2D, READ_WRITE", Obj: D3D9Surface, Type: Gl.GL_TEXTURE_2D, Access: Gl.WGL_ACCESS_READ_WRITE_NV),
(Label: "surface, GL_TEXTURE_RECTANGLE, RW", Obj: D3D9Surface, Type: Gl.GL_TEXTURE_RECTANGLE, Access: Gl.WGL_ACCESS_READ_WRITE_NV),
(Label: "texture, GL_TEXTURE_2D, WRITE_DISCARD", Obj: D3D9Texture, Type: Gl.GL_TEXTURE_2D, Access: Gl.WGL_ACCESS_WRITE_DISCARD_NV),
(Label: "texture, GL_TEXTURE_2D, READ_WRITE", Obj: D3D9Texture, Type: Gl.GL_TEXTURE_2D, Access: Gl.WGL_ACCESS_READ_WRITE_NV),
};
IntPtr wglObj = IntPtr.Zero;
string lastFail = "";
foreach (var a in attempts)
{
wglObj = gl.wglDXRegisterObjectNV(_wglDevice, a.Obj, GlTexture, a.Type, a.Access);
if (wglObj != IntPtr.Zero)
{
Console.WriteLine($"[spike] wglDXRegisterObjectNV SUCCESS via: {a.Label}");
break;
}
lastFail = $"{a.Label} → LastError=0x{Marshal.GetLastWin32Error():X}";
Console.WriteLine($"[spike] wglDXRegisterObjectNV FAIL via: {lastFail}");
}
if (wglObj == IntPtr.Zero)
throw new InvalidOperationException($"wglDXRegisterObjectNV failed in all variants. Last: {lastFail}");
WglObject = wglObj;
// Step 4 — Build an FBO with the GL texture as color attachment 0.
// FBO setup is done while the texture is NOT locked (legal per spec; the
// attachment binding is a GL state operation that doesn't touch contents).
// The first lock is the point at which GL can actually clear the texture.
uint fbo = 0;
gl.glGenFramebuffers(1, &fbo);
GlFramebuffer = fbo;
gl.glBindFramebuffer(Gl.GL_FRAMEBUFFER, fbo);
gl.glFramebufferTexture2D(Gl.GL_FRAMEBUFFER, Gl.GL_COLOR_ATTACHMENT0, Gl.GL_TEXTURE_2D, GlTexture, 0);
uint status = gl.glCheckFramebufferStatus(Gl.GL_FRAMEBUFFER);
gl.glBindFramebuffer(Gl.GL_FRAMEBUFFER, 0);
if (status != Gl.GL_FRAMEBUFFER_COMPLETE)
throw new InvalidOperationException($"FBO incomplete after attaching interop texture, status=0x{status:X}.");
}
/// <summary>Lock the D3D9 texture so the GL context has exclusive write access.</summary>
public bool Lock()
{
IntPtr h = WglObject;
return _gl.wglDXLockObjectsNV(_wglDevice, 1, &h);
}
/// <summary>Release the D3D9 texture back to D3D9. After this, AC's render thread can sample.</summary>
public bool Unlock()
{
IntPtr h = WglObject;
return _gl.wglDXUnlockObjectsNV(_wglDevice, 1, &h);
}
public void Dispose()
{
if (WglObject != IntPtr.Zero)
{
_gl.wglDXUnregisterObjectNV(_wglDevice, WglObject);
WglObject = IntPtr.Zero;
}
if (GlFramebuffer != 0)
{
uint fbo = GlFramebuffer;
_gl.glDeleteFramebuffers(1, &fbo);
GlFramebuffer = 0;
}
if (GlTexture != 0)
{
uint tex = GlTexture;
_gl.glDeleteTextures(1, &tex);
GlTexture = 0;
}
if (D3D9Surface != IntPtr.Zero)
{
_d3d.ReleaseObject(D3D9Surface);
D3D9Surface = IntPtr.Zero;
}
if (D3D9Texture != IntPtr.Zero)
{
_d3d.ReleaseObject(D3D9Texture);
D3D9Texture = IntPtr.Zero;
}
}
}

View file

@ -0,0 +1,337 @@
// Phase A spike — WGL_NV_DX_interop2 architectural test.
//
// What it does end-to-end:
// 1. Open a normal Win32 window and create a plain D3D9 device on it.
// (Direct3DCreate9, NOT Ex — exactly what AC ships.)
// 2. Create a 'producer' window+DC and bring up a real OpenGL 3.3 core context.
// 3. Confirm WGL_NV_DX_interop2 is in the WGL extensions string.
// (Spike A8 — driver coverage. Hard-fail with a clear log if missing.)
// 4. Open the D3D9 device for interop and register a D3DUSAGE_RENDERTARGET
// texture under it as a GL texture.
// 5. Per frame:
// - Lock the texture for GL.
// - Bind FBO, set viewport, clear to an animated color (proves the GL
// path is actually writing into the D3D9 resource).
// - Unlock.
// - Use the D3D9 texture in a normal D3D9 fullscreen quad to the window.
// 6. Log frame timing every second so spike A3 (lock/unlock cost) gets data.
//
// This is intentionally Skia-free for the first cut. Skia layers on top
// trivially once the chain works (replace the glClearColor with a Skia render
// into the same FBO). Proving the chain first means a Skia rendering bug is
// disambiguated from an interop bug.
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace WglDxInterop;
internal static unsafe class Program
{
private const int WindowWidth = 1280;
private const int WindowHeight = 720;
private static IntPtr _hwnd;
private static bool _quitRequested;
// Holding the WndProc delegate alive for the lifetime of the window —
// RegisterClassExW stores a function pointer; if the delegate is GC'd
// we get a callback into freed memory.
private static Win32.WndProcDelegate? _wndProc;
[STAThread]
public static int Main(string[] args)
{
Console.WriteLine("[spike] WGL_NV_DX_interop2 architectural test");
try
{
CreateMainWindow();
// Spike branch — `--ex` flag selects D3D9Ex+shared-handle path so we can
// empirically test whether WGL_NV_DX_interop2 needs Ex's shared handles.
// Default is plain D3D9 to mirror AC's reality.
bool useEx = Array.IndexOf(args, "--ex") >= 0;
using var d3d = new D3D9Host();
if (useEx) d3d.InitializeEx(_hwnd, WindowWidth, WindowHeight);
else d3d.Initialize(_hwnd, WindowWidth, WindowHeight);
Console.WriteLine($"[spike] D3D9{(d3d.IsEx ? "Ex" : "")} device created on adapter {d3d.AdapterIndex}.");
// GL context lives on the SAME thread as the message loop and D3D9.
// For the engine integration, the GL context will live on Avalonia's
// STA thread; here on the spike main thread is fine.
//
// Use a SEPARATE hidden window for the GL context so the GL default
// framebuffer doesn't compete with the D3D9 swap chain on the visible
// window. NVIDIA's WGL_NV_DX_interop layer is documented as needing
// this isolation for D3D9 sources.
IntPtr glHwnd = CreateHiddenGlWindow();
IntPtr glContext = CreateGlContext(glHwnd, out IntPtr hdcUsed);
if (glContext == IntPtr.Zero)
return Fail("Could not create OpenGL context.");
string wglExt = Gl.GetWglExtensionsString(hdcUsed);
Console.WriteLine($"[spike] WGL extensions: {wglExt.Length} chars.");
bool hasInterop2 = wglExt.Contains("WGL_NV_DX_interop2");
bool hasInterop1 = wglExt.Contains("WGL_NV_DX_interop");
Console.WriteLine($"[spike] WGL_NV_DX_interop = {hasInterop1}, WGL_NV_DX_interop2 = {hasInterop2}");
if (!hasInterop2 && !hasInterop1)
return Fail("Driver does not advertise WGL_NV_DX_interop. Spike cannot run on this hardware.");
var gl = Gl.LoadAll();
Console.WriteLine($"[spike] GL_VENDOR = {Gl.GetGlString(gl, Gl.GL_VENDOR)}");
Console.WriteLine($"[spike] GL_RENDERER = {Gl.GetGlString(gl, Gl.GL_RENDERER)}");
Console.WriteLine($"[spike] GL_VERSION = {Gl.GetGlString(gl, Gl.GL_VERSION)}");
IntPtr wglDevice = gl.wglDXOpenDeviceNV(d3d.Device);
if (wglDevice == IntPtr.Zero)
return Fail($"wglDXOpenDeviceNV failed (LastError=0x{Marshal.GetLastWin32Error():X}).");
Console.WriteLine($"[spike] wglDXOpenDeviceNV → 0x{wglDevice:X}");
using var tex = new InteropTexture(gl, d3d, wglDevice, WindowWidth, WindowHeight);
Console.WriteLine($"[spike] Registered D3D9 RT 0x{tex.D3D9Texture:X} as GL tex {tex.GlTexture}, FBO {tex.GlFramebuffer}, wglObj 0x{tex.WglObject:X}.");
RunRenderLoop(d3d, gl, tex);
// Teardown order matters — Unregister + CloseDeviceNV before D3D9 release.
gl.wglDXCloseDeviceNV(wglDevice);
Gl.wglMakeCurrent(IntPtr.Zero, IntPtr.Zero);
Gl.wglDeleteContext(glContext);
Console.WriteLine("[spike] Clean exit.");
return 0;
}
catch (Exception ex)
{
return Fail($"Unhandled: {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}");
}
}
private static int Fail(string msg)
{
Console.Error.WriteLine($"[spike] FAILED: {msg}");
return 1;
}
// ─── Window ───────────────────────────────────────────────────────────
private static void CreateMainWindow()
{
_wndProc = StaticWndProc;
IntPtr wndProcPtr = Marshal.GetFunctionPointerForDelegate(_wndProc);
var wc = new Win32.WNDCLASSEXW
{
cbSize = (uint)Marshal.SizeOf<Win32.WNDCLASSEXW>(),
style = 0,
lpfnWndProc = wndProcPtr,
hInstance = Win32.GetModuleHandleW(null),
hCursor = IntPtr.Zero,
hbrBackground = IntPtr.Zero,
lpszMenuName = IntPtr.Zero,
lpszClassName = Marshal.StringToHGlobalUni("WglDxInteropSpike"),
};
ushort atom = Win32.RegisterClassExW(ref wc);
if (atom == 0)
throw new InvalidOperationException($"RegisterClassExW failed: {Marshal.GetLastWin32Error()}");
_hwnd = Win32.CreateWindowExW(
0, "WglDxInteropSpike", "WGL_NV_DX_interop2 spike",
Win32.WS_OVERLAPPEDWINDOW | Win32.WS_VISIBLE,
Win32.CW_USEDEFAULT, Win32.CW_USEDEFAULT, WindowWidth, WindowHeight,
IntPtr.Zero, IntPtr.Zero, Win32.GetModuleHandleW(null), IntPtr.Zero);
if (_hwnd == IntPtr.Zero)
throw new InvalidOperationException($"CreateWindowExW failed: {Marshal.GetLastWin32Error()}");
Win32.ShowWindow(_hwnd, Win32.SW_SHOW);
}
private static IntPtr StaticWndProc(IntPtr hwnd, uint msg, IntPtr wParam, IntPtr lParam)
{
switch (msg)
{
case Win32.WM_CLOSE:
_quitRequested = true;
Win32.PostQuitMessage(0);
return IntPtr.Zero;
case Win32.WM_DESTROY:
Win32.PostQuitMessage(0);
return IntPtr.Zero;
}
return Win32.DefWindowProcW(hwnd, msg, wParam, lParam);
}
private static IntPtr CreateHiddenGlWindow()
{
IntPtr hwnd = Win32.CreateWindowExW(
0, "WglDxInteropSpike", "GL helper",
Win32.WS_POPUP,
0, 0, 16, 16,
IntPtr.Zero, IntPtr.Zero, Win32.GetModuleHandleW(null), IntPtr.Zero);
if (hwnd == IntPtr.Zero)
throw new InvalidOperationException($"GL helper CreateWindowExW failed: {Marshal.GetLastWin32Error()}");
return hwnd;
}
// ─── GL context bootstrap ─────────────────────────────────────────────
private static IntPtr CreateGlContext(IntPtr hwnd, out IntPtr hdcOut)
{
IntPtr hdc = Win32.GetDC(hwnd);
if (hdc == IntPtr.Zero) { hdcOut = IntPtr.Zero; return IntPtr.Zero; }
var pfd = new Win32.PIXELFORMATDESCRIPTOR
{
nSize = (ushort)Marshal.SizeOf<Win32.PIXELFORMATDESCRIPTOR>(),
nVersion = 1,
dwFlags = (uint)(Win32.PFD_DRAW_TO_WINDOW | Win32.PFD_SUPPORT_OPENGL | Win32.PFD_DOUBLEBUFFER),
iPixelType = Win32.PFD_TYPE_RGBA,
cColorBits = 32,
cAlphaBits = 8,
cDepthBits = 0,
cStencilBits = 0,
iLayerType = Win32.PFD_MAIN_PLANE,
};
int format = Win32.ChoosePixelFormat(hdc, ref pfd);
if (format == 0) { hdcOut = IntPtr.Zero; return IntPtr.Zero; }
if (!Win32.SetPixelFormat(hdc, format, ref pfd)) { hdcOut = IntPtr.Zero; return IntPtr.Zero; }
IntPtr glrc = Gl.wglCreateContext(hdc);
if (glrc == IntPtr.Zero) { hdcOut = IntPtr.Zero; return IntPtr.Zero; }
if (!Gl.wglMakeCurrent(hdc, glrc)) { hdcOut = IntPtr.Zero; return IntPtr.Zero; }
// Try to upgrade to GL 3.3 core via wglCreateContextAttribsARB.
// If unavailable (very old driver) the fallback 1.x context is used —
// that may or may not have FBO support. Fail gracefully.
var createAttribs = Gl.TryResolve<Gl.wglCreateContextAttribsARBD>("wglCreateContextAttribsARB");
if (createAttribs != null)
{
int* attribs = stackalloc int[]
{
Gl.WGL_CONTEXT_MAJOR_VERSION_ARB, 3,
Gl.WGL_CONTEXT_MINOR_VERSION_ARB, 3,
Gl.WGL_CONTEXT_PROFILE_MASK_ARB, Gl.WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
0,
};
IntPtr coreCtx = createAttribs(hdc, IntPtr.Zero, attribs);
if (coreCtx != IntPtr.Zero)
{
Gl.wglMakeCurrent(IntPtr.Zero, IntPtr.Zero);
Gl.wglDeleteContext(glrc);
glrc = coreCtx;
Gl.wglMakeCurrent(hdc, glrc);
Console.WriteLine("[spike] Upgraded to GL 3.3 core context.");
}
else
{
Console.WriteLine("[spike] wglCreateContextAttribsARB returned null — staying on legacy context.");
}
}
else
{
Console.WriteLine("[spike] wglCreateContextAttribsARB not available — staying on legacy context.");
}
hdcOut = hdc;
return glrc;
}
// ─── Render loop ──────────────────────────────────────────────────────
private static void RunRenderLoop(D3D9Host d3d, Gl.Bindings gl, InteropTexture tex)
{
var sw = Stopwatch.StartNew();
long frameStartTicks;
long lockTotalTicks = 0;
long unlockTotalTicks = 0;
long unlockMaxTicks = 0;
int frame = 0;
long secondAnchor = sw.ElapsedTicks;
int framesThisSecond = 0;
while (!_quitRequested)
{
// Drain Win32 messages.
while (Win32.PeekMessageW(out Win32.MSG msg, IntPtr.Zero, 0, 0, Win32.PM_REMOVE))
{
if (msg.message == Win32.WM_QUIT)
{
_quitRequested = true;
break;
}
Win32.TranslateMessage(ref msg);
Win32.DispatchMessageW(ref msg);
}
if (_quitRequested) break;
frameStartTicks = sw.ElapsedTicks;
// ── GL phase: lock → render to FBO → unlock ──
long lockStart = sw.ElapsedTicks;
if (!tex.Lock())
{
Console.Error.WriteLine($"[spike] wglDXLockObjectsNV failed at frame {frame}.");
break;
}
long lockEnd = sw.ElapsedTicks;
lockTotalTicks += (lockEnd - lockStart);
// Bind the interop FBO and clear to an animated color so it's visually
// obvious the GL path is writing into the D3D9 texture. Swizzle is
// intentional: we want to see whether glClearColor's RGBA is sampled
// as RGBA or as BGRA when drawn through D3D9's quad shader path.
// Spike question A2 — color format mapping.
float t = (frame % 600) / 600.0f;
float r = (float)(0.5 + 0.5 * Math.Sin(t * 2 * Math.PI));
float g = (float)(0.5 + 0.5 * Math.Sin(t * 2 * Math.PI + 2.0));
float b = (float)(0.5 + 0.5 * Math.Sin(t * 2 * Math.PI + 4.0));
gl.glBindFramebuffer(Gl.GL_FRAMEBUFFER, tex.GlFramebuffer);
gl.glViewport(0, 0, tex.Width, tex.Height);
gl.glClearColor(r, g, b, 1.0f);
gl.glClear(Gl.GL_COLOR_BUFFER_BIT);
gl.glBindFramebuffer(Gl.GL_FRAMEBUFFER, 0);
gl.glFlush();
long unlockStart = sw.ElapsedTicks;
if (!tex.Unlock())
{
Console.Error.WriteLine($"[spike] wglDXUnlockObjectsNV failed at frame {frame}.");
break;
}
long unlockEnd = sw.ElapsedTicks;
long unlockTicks = unlockEnd - unlockStart;
unlockTotalTicks += unlockTicks;
if (unlockTicks > unlockMaxTicks) unlockMaxTicks = unlockTicks;
// ── D3D9 phase: render the texture as a fullscreen quad ──
d3d.Clear(0xFF000000); // opaque black, so quad alpha is visible
d3d.BeginScene();
d3d.DrawTexturedQuad(tex.D3D9Texture, WindowWidth, WindowHeight);
d3d.EndScene();
d3d.Present();
frame++;
framesThisSecond++;
// Per-second telemetry — feeds Spike question A3.
long now = sw.ElapsedTicks;
if ((now - secondAnchor) >= Stopwatch.Frequency)
{
double avgLockMs = (lockTotalTicks / (double)Stopwatch.Frequency) * 1000.0 / Math.Max(framesThisSecond, 1);
double avgUnlockMs = (unlockTotalTicks / (double)Stopwatch.Frequency) * 1000.0 / Math.Max(framesThisSecond, 1);
double maxUnlockMs = (unlockMaxTicks / (double)Stopwatch.Frequency) * 1000.0;
Console.WriteLine($"[spike] frame={frame} fps={framesThisSecond} lock={avgLockMs:F3}ms avgUnlock={avgUnlockMs:F3}ms maxUnlock={maxUnlockMs:F3}ms");
lockTotalTicks = 0;
unlockTotalTicks = 0;
unlockMaxTicks = 0;
framesThisSecond = 0;
secondAnchor = now;
}
}
}
}

View file

@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0-windows</TargetFramework>
<PlatformTarget>x86</PlatformTarget>
<RuntimeIdentifier>win-x86</RuntimeIdentifier>
<Platforms>x86</Platforms>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<RootNamespace>WglDxInterop</RootNamespace>
<AssemblyName>WglDxInterop</AssemblyName>
<UseWindowsForms>false</UseWindowsForms>
<UseWPF>false</UseWPF>
</PropertyGroup>
<!--
Stage 1 (this csproj): managed build only. Runs as a normal x86 .NET app to keep
iteration tight while we prove the WGL_NV_DX_interop2 chain. Stage 2 turns on
PublishAot=true and TrimMode=link to mirror the engine's build flags so spike
question A6 (NativeAOT survival) can be answered before engine integration.
-->
</Project>

View file

@ -0,0 +1,141 @@
// Win32 P/Invoke surface for the spike. Kept narrow — we only need window
// creation, a message loop, DC management, and pixel-format setup. All the
// GL-side P/Invokes live in Gl.cs; D3D9 P/Invokes live in D3D9.cs.
using System;
using System.Runtime.InteropServices;
namespace WglDxInterop;
internal static unsafe class Win32
{
public const int WS_OVERLAPPEDWINDOW = 0x00CF0000;
public const int WS_VISIBLE = 0x10000000;
public const int WS_POPUP = unchecked((int)0x80000000);
public const int CW_USEDEFAULT = unchecked((int)0x80000000);
public const int SW_SHOW = 5;
public const uint WM_DESTROY = 0x0002;
public const uint WM_QUIT = 0x0012;
public const uint WM_SIZE = 0x0005;
public const uint WM_CLOSE = 0x0010;
public const uint WM_PAINT = 0x000F;
public const int PFD_DRAW_TO_WINDOW = 0x00000004;
public const int PFD_SUPPORT_OPENGL = 0x00000020;
public const int PFD_DOUBLEBUFFER = 0x00000001;
public const int PFD_TYPE_RGBA = 0;
public const byte PFD_MAIN_PLANE = 0;
[StructLayout(LayoutKind.Sequential)]
public struct PIXELFORMATDESCRIPTOR
{
public ushort nSize;
public ushort nVersion;
public uint dwFlags;
public byte iPixelType;
public byte cColorBits;
public byte cRedBits, cRedShift;
public byte cGreenBits, cGreenShift;
public byte cBlueBits, cBlueShift;
public byte cAlphaBits, cAlphaShift;
public byte cAccumBits, cAccumRedBits, cAccumGreenBits, cAccumBlueBits, cAccumAlphaBits;
public byte cDepthBits, cStencilBits, cAuxBuffers;
public byte iLayerType;
public byte bReserved;
public uint dwLayerMask, dwVisibleMask, dwDamageMask;
}
[StructLayout(LayoutKind.Sequential)]
public struct MSG
{
public IntPtr hwnd;
public uint message;
public IntPtr wParam;
public IntPtr lParam;
public uint time;
public int ptX;
public int ptY;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct WNDCLASSEXW
{
public uint cbSize;
public uint style;
public IntPtr lpfnWndProc;
public int cbClsExtra;
public int cbWndExtra;
public IntPtr hInstance;
public IntPtr hIcon;
public IntPtr hCursor;
public IntPtr hbrBackground;
public IntPtr lpszMenuName;
public IntPtr lpszClassName;
public IntPtr hIconSm;
}
public delegate IntPtr WndProcDelegate(IntPtr hwnd, uint msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern ushort RegisterClassExW(ref WNDCLASSEXW wc);
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern IntPtr CreateWindowExW(
int dwExStyle, string lpClassName, string lpWindowName, int dwStyle,
int x, int y, int nWidth, int nHeight,
IntPtr hWndParent, IntPtr hMenu, IntPtr hInstance, IntPtr lpParam);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern IntPtr DefWindowProcW(IntPtr hwnd, uint msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool DestroyWindow(IntPtr hwnd);
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hwnd, int nCmdShow);
[DllImport("user32.dll")]
public static extern IntPtr GetDC(IntPtr hwnd);
[DllImport("user32.dll")]
public static extern int ReleaseDC(IntPtr hwnd, IntPtr hdc);
[DllImport("user32.dll")]
public static extern bool PeekMessageW(out MSG msg, IntPtr hwnd, uint wMsgFilterMin, uint wMsgFilterMax, uint wRemoveMsg);
[DllImport("user32.dll")]
public static extern bool TranslateMessage(ref MSG msg);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern IntPtr DispatchMessageW(ref MSG msg);
[DllImport("user32.dll")]
public static extern void PostQuitMessage(int nExitCode);
[DllImport("user32.dll")]
public static extern bool GetClientRect(IntPtr hwnd, out RECT lpRect);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
public static extern IntPtr GetModuleHandleW(string? lpModuleName);
[DllImport("kernel32.dll", CharSet = CharSet.Ansi)]
public static extern IntPtr LoadLibraryA(string lpFileName);
[DllImport("kernel32.dll", CharSet = CharSet.Ansi)]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
[DllImport("gdi32.dll")]
public static extern int ChoosePixelFormat(IntPtr hdc, ref PIXELFORMATDESCRIPTOR ppfd);
[DllImport("gdi32.dll")]
public static extern bool SetPixelFormat(IntPtr hdc, int format, ref PIXELFORMATDESCRIPTOR ppfd);
[DllImport("gdi32.dll")]
public static extern bool SwapBuffers(IntPtr hdc);
[StructLayout(LayoutKind.Sequential)]
public struct RECT { public int Left, Top, Right, Bottom; }
public const uint PM_REMOVE = 0x0001;
}

View file

@ -0,0 +1,76 @@
# Phase A spike findings — WGL_NV_DX_interop2 for D3D9 sources
**Verdict: NOT VIABLE on this hardware.**
The technique recommended in `wgl-interop-plan.md` does not work for D3D9 sources on the user's machine. This invalidates the plan as written. **Stop and pivot before any engine code changes.**
---
## What was tested
Hardware: NVIDIA GeForce GTX 1650 SUPER, driver 560.94 (current).
OS: Windows 10 Pro 19045.
GL: 3.3.0 NVIDIA 560.94, real ICD context (not Microsoft GDI fallback). 809 chars of WGL extension string, both `WGL_NV_DX_interop` and `WGL_NV_DX_interop2` advertised as supported.
Spike code: `C:\Projects\RynthCore\spikes\WglDxInterop\` — ~600 LOC, builds clean as managed x86.
## Results
`wglDXOpenDeviceNV(deviceHandle)`: **succeeds** for both plain D3D9 and D3D9Ex. Returns a non-null handle. Already informative — the D3D device is recognized as a valid interop source.
`wglDXSetResourceShareHandleNV(surface, sharedHandle)`: **succeeds** for D3D9Ex render-target textures created with a non-null `pSharedHandle` slot.
`wglDXRegisterObjectNV(...)`: **fails (returns NULL)** in 10 distinct configurations:
| Device | Source | Type | Access | Result |
|---|---|---|---|---|
| Plain D3D9 | IDirect3DSurface9 | GL_TEXTURE_2D | WRITE_DISCARD_NV | NULL (LastError 0xC007006E first call, 0x0 subsequent) |
| Plain D3D9 | IDirect3DSurface9 | GL_TEXTURE_2D | READ_WRITE_NV | NULL |
| Plain D3D9 | IDirect3DSurface9 | GL_TEXTURE_RECTANGLE | READ_WRITE_NV | NULL |
| Plain D3D9 | IDirect3DTexture9 | GL_TEXTURE_2D | WRITE_DISCARD_NV | NULL |
| Plain D3D9 | IDirect3DTexture9 | GL_TEXTURE_2D | READ_WRITE_NV | NULL |
| D3D9Ex (shared handle set) | IDirect3DSurface9 | GL_TEXTURE_2D | WRITE_DISCARD_NV | NULL |
| D3D9Ex (shared handle set) | IDirect3DSurface9 | GL_TEXTURE_2D | READ_WRITE_NV | NULL |
| D3D9Ex (shared handle set) | IDirect3DSurface9 | GL_TEXTURE_RECTANGLE | READ_WRITE_NV | NULL |
| D3D9Ex (shared handle set) | IDirect3DTexture9 | GL_TEXTURE_2D | WRITE_DISCARD_NV | NULL |
| D3D9Ex (shared handle set) | IDirect3DTexture9 | GL_TEXTURE_2D | READ_WRITE_NV | NULL |
Other variables ruled out:
- `D3DCREATE_MULTITHREADED` flag: tested both on and off. Same failure either way.
- `D3DCREATE_HARDWARE_VERTEXPROCESSING` vs `_SOFTWARE_VERTEXPROCESSING`: tested both. Same failure.
- Shared focus window vs isolated hidden window for the GL context: tested both. Same failure.
- Texture format / dimensions: A8R8G8B8, 1280×720, D3DPOOL_DEFAULT, D3DUSAGE_RENDERTARGET — the canonical "supported" combination per spec.
The `0xC007006E = HRESULT_FROM_WIN32(ERROR_INVALID_HANDLE)` on the very first call (subsequent calls leave LastError as 0, suggesting the driver doesn't reliably call `SetLastError`) is the only diagnostic NVIDIA's driver gives us. There is no way to query a more specific error.
## Interpretation
The published NV_DX_interop spec lists D3D9 surfaces as supported, but **NVIDIA's current driver implementation does not work for D3D9 sources** in the configurations a real-world overlay would need. This matches scattered third-party reports (Chromium's interop code carries D3D11 fallbacks and explicit notes about D3D9 quirkiness; various Steam/MSI Afterburner reverse-engineerings show they use D3D11 internally and composite differently). **WGL_NV_DX_interop2 is essentially a D3D11-and-newer interop in practice, even though the spec language is broader.**
Key implication: **the recommendation in `wgl-interop-plan.md` was wrong.** I led the user there based on the spec text and well-known overlay-in-D3D9-game examples — but those examples almost universally use D3D11 internally, not D3D9. The "render into AC's D3D9 texture via WGL interop" path is closed on this driver, and likely on every modern NVIDIA driver.
## What's left
The original GPU-rendering option space, re-evaluated against this finding:
1. **D3D11 producer via WGL_NV_DX_interop2 → AC's plain D3D9 consumer.** Not tested in the spike yet, but the *interop* part is the well-trodden one and almost certainly works. The hard part was always "→ AC's plain D3D9 consumer", which still requires either:
- **(a) Hook `Direct3DCreate9` in acclient.exe at runtime to substitute `Direct3DCreate9Ex`.** Makes AC's device Ex. Ex devices CAN open shared HANDLEs from D3D11 (via DXGI sharing). MANAGED-pool wrapper required for AC's textures, lost-device semantics need shimming.
- **(b) CPU readback of the D3D11 texture, then D3D9 LockRect+memcpy.** Same as today's software path with extra GPU latency. Nets nothing.
2. **Layered/child window approach.** No AC modification. Avalonia renders to its own ANGLE+D3D11 swap chain on a separate Win32 window, DWM composites it over AC. The mover bug (Phase 2a diagnostic — ~50 LOC fix) needs landing first. Then we'd extend layered windows to cover the bar + docked panels too, retiring the EndScene composite path.
3. **Fix software Skia.** Pursue the LFH AV at its actual source (Skia teardown allocations) rather than trying to GPU-accelerate a path that's blocked at the consumer side.
Path 1(a) is the same "hook Direct3DCreate9 → Ex" we discussed before the spike — runtime hook, no acclient.exe disk patch, no other-user impact. The spike's value here is that it confirms WGL interop is fine for D3D11 (assumed; would need a 30-minute test to verify), and the only structural blocker remaining is making AC's device Ex.
Path 2 has the largest scope but the smallest risk to AC stability. Coexistence-mode-friendly for free.
Path 3 is the smallest and probably the most-immediate-value option (the LFH AV is the actual blocker for daily use, not the lack of GPU rendering).
## Recommendation
Stop pursuing the WGL_NV_DX_interop2 → AC's D3D9 plan. Present the three remaining paths and let the user pick. None of them are a small follow-up on the current investigation — each is a meaningful pivot.
The spike was an unambiguous win: ~3 hours invested, conclusive data, prevented a multi-weekend integration on a foundation that wouldn't have worked.