Skip to content

Zero Hour rebuilt from EA's source: x64, Direct3D 11, VS2022/CMake, ~60 original bugs fixed, an AI that builds a base. Bring your own game.

build(ww3d2): bind D3DX9 at runtime and prove a native D3D9 device

Olcay Seyganb850b24cd568
diff --git a/GeneralsMD/Code/CMakeLists.txt b/GeneralsMD/Code/CMakeLists.txt
index 173fa0d2c..139736431 100644
--- a/GeneralsMD/Code/CMakeLists.txt
+++ b/GeneralsMD/Code/CMakeLists.txt
@@ -263,6 +263,14 @@ target_include_directories(dx8_smoke PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/Librari
target_link_directories(dx8_smoke PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/Libraries/DirectX/Lib)
target_link_libraries(dx8_smoke PRIVATE d3d8 user32)
+# RENDERER-ROADMAP.md phase 1 checkpoint: the same proof without the translating
+# dll. d3d9.h and d3d9.lib come from the Windows SDK, so this target must not see
+# Libraries/DirectX/Include - d3d8.h would shadow nothing here, but keeping the two
+# header sets apart is what makes the native path native.
+add_executable(dx9_smoke ${WW}/WW3D2/test_dx9_smoke.cpp ${WW}/WW3D2/d3dx9runtime.cpp)
+target_include_directories(dx9_smoke PRIVATE ${WW}/WW3D2)
+target_link_libraries(dx9_smoke PRIVATE d3d9 user32)
+
# ===========================================================================
# Phase 2 - remaining support libs. None of these touch DX8.
# ===========================================================================
@@ -631,6 +639,9 @@ add_custom_command(TARGET dx8_smoke POST_BUILD
add_dependencies(dx8_smoke d3d8to9)
add_test(NAME dx8_smoke COMMAND dx8_smoke)
add_test(NAME dx8_smoke_d3d12 COMMAND dx8_smoke -d3d12)
+# dx9_smoke deliberately does not get d3d8.dll copied next to it: it calls
+# Direct3DCreate9 itself and a translating dll would hide whether that worked.
+add_test(NAME dx9_smoke COMMAND dx9_smoke)
# bink_smoke validates the hand-reconstructed Bink ABI against the real
# BINKW32.DLL the game ships - it loads that DLL by path, so it does not link
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/d3dx9math.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/d3dx9math.h
new file mode 100644
index 000000000..02bda7b29
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/d3dx9math.h
@@ -0,0 +1,148 @@
+/*
+** Command & Conquer Generals Zero Hour(tm)
+** Copyright 2025 Electronic Arts Inc.
+**
+** This program is free software: you can redistribute it and/or modify
+** it under the terms of the GNU General Public License as published by
+** the Free Software Foundation, either version 3 of the License, or
+** (at your option) any later version.
+**
+** This program is distributed in the hope that it will be useful,
+** but WITHOUT ANY WARRANTY; without even the implied warranty of
+** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+** GNU General Public License for more details.
+**
+** You should have received a copy of the GNU General Public License
+** along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+// The D3DX vector and matrix types for the native Direct3D 9 renderer.
+// RENDERER-ROADMAP.md phase 1.
+//
+// d3dx8math.h cannot come along, because it includes d3dx8.h, which includes d3d8.h,
+// and the whole point of the phase is that d3d8.h is gone. The types themselves owe
+// nothing to either header: they are floats with constructors. So they are declared
+// here, laid out exactly as the D3DX ones are, and the eight functions the engine calls
+// that are not inline come out of d3dx9_43.dll beside the texture and shader ones.
+//
+// Binding rather than reimplementing is deliberate. D3DXVec4Transform and D3DXVec4Dot
+// reach GameLogic through BezierSegment, which DumbProjectileBehavior steers a shell
+// with, so their arithmetic is part of the network and replay CRC. A hand-written 4x4
+// inverse or transform would be a rounding difference nobody could see until a replay
+// diverged. D3DXVec4Dot and D3DXMatrixIdentity are the two the DirectX SDK inlined, so
+// those two are written out here, matching d3dx8math.inl term for term.
+
+#ifndef D3DX9MATH_H
+#define D3DX9MATH_H
+
+#include <d3d9.h>
+
+#define D3DX_PI ((FLOAT)3.141592654f)
+
+struct D3DXVECTOR3 : public D3DVECTOR
+{
+public:
+ D3DXVECTOR3() {}
+ D3DXVECTOR3(FLOAT x_value, FLOAT y_value, FLOAT z_value)
+ {
+ x = x_value;
+ y = y_value;
+ z = z_value;
+ }
+
+ operator FLOAT * () { return &x; }
+ operator const FLOAT * () const { return &x; }
+};
+
+struct D3DXVECTOR4
+{
+public:
+ D3DXVECTOR4() {}
+ D3DXVECTOR4(FLOAT x_value, FLOAT y_value, FLOAT z_value, FLOAT w_value)
+ : x(x_value), y(y_value), z(z_value), w(w_value) {}
+
+ operator FLOAT * () { return &x; }
+ operator const FLOAT * () const { return &x; }
+
+ FLOAT x;
+ FLOAT y;
+ FLOAT z;
+ FLOAT w;
+};
+
+struct D3DXMATRIX : public D3DMATRIX
+{
+public:
+ D3DXMATRIX() {}
+ D3DXMATRIX(FLOAT m11, FLOAT m12, FLOAT m13, FLOAT m14,
+ FLOAT m21, FLOAT m22, FLOAT m23, FLOAT m24,
+ FLOAT m31, FLOAT m32, FLOAT m33, FLOAT m34,
+ FLOAT m41, FLOAT m42, FLOAT m43, FLOAT m44)
+ {
+ _11 = m11; _12 = m12; _13 = m13; _14 = m14;
+ _21 = m21; _22 = m22; _23 = m23; _24 = m24;
+ _31 = m31; _32 = m32; _33 = m33; _34 = m34;
+ _41 = m41; _42 = m42; _43 = m43; _44 = m44;
+ }
+
+ operator FLOAT * () { return &_11; }
+ operator const FLOAT * () const { return &_11; }
+
+ FLOAT & operator()(UINT row, UINT column) { return m[row][column]; }
+ FLOAT operator()(UINT row, UINT column) const { return m[row][column]; }
+};
+
+typedef HRESULT (WINAPI * D3DXMatrixInverseFunction)(D3DXMATRIX * out, FLOAT * determinant,
+ const D3DXMATRIX * matrix);
+
+typedef D3DXMATRIX * (WINAPI * D3DXMatrixBinaryFunction)(D3DXMATRIX * out,
+ const D3DXMATRIX * left, const D3DXMATRIX * right);
+
+typedef D3DXMATRIX * (WINAPI * D3DXMatrixUnaryFunction)(D3DXMATRIX * out,
+ const D3DXMATRIX * matrix);
+
+typedef D3DXMATRIX * (WINAPI * D3DXMatrixTripleFunction)(D3DXMATRIX * out,
+ FLOAT first, FLOAT second, FLOAT third);
+
+typedef D3DXMATRIX * (WINAPI * D3DXMatrixAngleFunction)(D3DXMATRIX * out, FLOAT angle);
+
+typedef D3DXVECTOR4 * (WINAPI * D3DXVec4TransformFunction)(D3DXVECTOR4 * out,
+ const D3DXVECTOR4 * vector, const D3DXMATRIX * matrix);
+
+typedef D3DXVECTOR4 * (WINAPI * D3DXVec3TransformFunction)(D3DXVECTOR4 * out,
+ const D3DXVECTOR3 * vector, const D3DXMATRIX * matrix);
+
+// D3DXMatrixInverse returns null when the matrix is singular, so its result is not
+// interchangeable with the others and it keeps its own signature.
+extern D3DXMatrixInverseFunction D3DXMatrixInverse;
+extern D3DXMatrixBinaryFunction D3DXMatrixMultiply;
+extern D3DXMatrixUnaryFunction D3DXMatrixTranspose;
+extern D3DXMatrixTripleFunction D3DXMatrixScaling;
+extern D3DXMatrixTripleFunction D3DXMatrixTranslation;
+extern D3DXMatrixAngleFunction D3DXMatrixRotationZ;
+extern D3DXVec4TransformFunction D3DXVec4Transform;
+extern D3DXVec3TransformFunction D3DXVec3Transform;
+
+// These eight are bound by Bind_D3DX9_Runtime in d3dx9runtime.h, along with the texture
+// and shader entry points: one place decides whether D3DX9 is present, and one answer
+// covers all of it. Every pointer is null until it succeeds.
+
+// The two the DirectX SDK inlined, copied from d3dx8math.inl so the arithmetic that
+// reaches a replay CRC is the arithmetic that always reached it.
+inline FLOAT D3DXVec4Dot(const D3DXVECTOR4 * left, const D3DXVECTOR4 * right)
+{
+ return left->x * right->x + left->y * right->y + left->z * right->z + left->w * right->w;
+}
+
+inline D3DXMATRIX * D3DXMatrixIdentity(D3DXMATRIX * out)
+{
+ out->m[0][1] = out->m[0][2] = out->m[0][3] =
+ out->m[1][0] = out->m[1][2] = out->m[1][3] =
+ out->m[2][0] = out->m[2][1] = out->m[2][3] =
+ out->m[3][0] = out->m[3][1] = out->m[3][2] = 0.0f;
+
+ out->m[0][0] = out->m[1][1] = out->m[2][2] = out->m[3][3] = 1.0f;
+ return out;
+}
+
+#endif // D3DX9MATH_H
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/d3dx9runtime.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/d3dx9runtime.cpp
new file mode 100644
index 000000000..c44749e6d
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/d3dx9runtime.cpp
@@ -0,0 +1,203 @@
+/*
+** Command & Conquer Generals Zero Hour(tm)
+** Copyright 2025 Electronic Arts Inc.
+**
+** This program is free software: you can redistribute it and/or modify
+** it under the terms of the GNU General Public License as published by
+** the Free Software Foundation, either version 3 of the License, or
+** (at your option) any later version.
+**
+** This program is distributed in the hope that it will be useful,
+** but WITHOUT ANY WARRANTY; without even the implied warranty of
+** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+** GNU General Public License for more details.
+**
+** You should have received a copy of the GNU General Public License
+** along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "d3dx9runtime.h"
+#include "d3dx9math.h"
+
+#include <stdio.h>
+
+D3DXAssembleShaderFunction D3DXAssembleShader = NULL;
+D3DXDisassembleShaderFunction D3DXDisassembleShader = NULL;
+D3DXCreateTextureFunction D3DXCreateTexture = NULL;
+D3DXCreateCubeTextureFunction D3DXCreateCubeTexture = NULL;
+D3DXCreateVolumeTextureFunction D3DXCreateVolumeTexture = NULL;
+D3DXCreateTextureFromFileExFunction D3DXCreateTextureFromFileExA = NULL;
+D3DXFilterTextureFunction D3DXFilterTexture = NULL;
+D3DXLoadSurfaceFromSurfaceFunction D3DXLoadSurfaceFromSurface = NULL;
+D3DXGetFVFVertexSizeFunction D3DXGetFVFVertexSize = NULL;
+
+D3DXMatrixInverseFunction D3DXMatrixInverse = NULL;
+D3DXMatrixBinaryFunction D3DXMatrixMultiply = NULL;
+D3DXMatrixUnaryFunction D3DXMatrixTranspose = NULL;
+D3DXMatrixTripleFunction D3DXMatrixScaling = NULL;
+D3DXMatrixTripleFunction D3DXMatrixTranslation = NULL;
+D3DXMatrixAngleFunction D3DXMatrixRotationZ = NULL;
+D3DXVec4TransformFunction D3DXVec4Transform = NULL;
+D3DXVec3TransformFunction D3DXVec3Transform = NULL;
+
+// The last D3DX9 release, and the one d3d8to9 binds, so a machine that runs this fork
+// today already has it. There is no fallback to an earlier d3dx9_NN.dll on purpose:
+// the earlier ones differ in behaviour, and a renderer that silently landed on one
+// would be the hardest kind of bug to see.
+static const char D3DX9_MODULE_NAME[] = "d3dx9_43.dll";
+
+static HMODULE D3DX9Module = NULL;
+static bool BindAttempted = false;
+static bool BindSucceeded = false;
+
+static void release_module(void);
+
+struct ErrorName
+{
+ HRESULT Result;
+ const char * Name;
+};
+
+// Every code the renderer's own paths return. D3DERR values are D3D_OK plus the
+// Direct3D facility, so they cannot be written as plain integers here.
+static const ErrorName ERROR_NAMES[] =
+{
+ { D3D_OK, "D3D_OK" },
+ { D3DERR_DEVICELOST, "D3DERR_DEVICELOST" },
+ { D3DERR_DEVICENOTRESET, "D3DERR_DEVICENOTRESET" },
+ { D3DERR_DRIVERINTERNALERROR, "D3DERR_DRIVERINTERNALERROR" },
+ { D3DERR_INVALIDCALL, "D3DERR_INVALIDCALL" },
+ { D3DERR_INVALIDDEVICE, "D3DERR_INVALIDDEVICE" },
+ { D3DERR_NOTAVAILABLE, "D3DERR_NOTAVAILABLE" },
+ { D3DERR_NOTFOUND, "D3DERR_NOTFOUND" },
+ { D3DERR_OUTOFVIDEOMEMORY, "D3DERR_OUTOFVIDEOMEMORY" },
+ { D3DERR_TOOMANYOPERATIONS, "D3DERR_TOOMANYOPERATIONS" },
+ { D3DERR_UNSUPPORTEDTEXTUREFILTER, "D3DERR_UNSUPPORTEDTEXTUREFILTER" },
+ { D3DERR_WRONGTEXTUREFORMAT, "D3DERR_WRONGTEXTUREFORMAT" },
+ { E_OUTOFMEMORY, "E_OUTOFMEMORY" },
+ { E_INVALIDARG, "E_INVALIDARG" },
+ { E_FAIL, "E_FAIL" }
+};
+
+static const int ERROR_NAME_COUNT = sizeof(ERROR_NAMES) / sizeof(ERROR_NAMES[0]);
+static const int ERROR_TEXT_SIZE = 32;
+
+static char UnknownErrorText[ERROR_TEXT_SIZE] = "";
+
+bool Bind_D3DX9_Runtime(void)
+{
+ if (BindAttempted) {
+ return BindSucceeded;
+ }
+ BindAttempted = true;
+
+ D3DX9Module = LoadLibraryA(D3DX9_MODULE_NAME);
+ if (D3DX9Module == NULL) {
+ return false;
+ }
+
+ D3DXAssembleShader = (D3DXAssembleShaderFunction)
+ GetProcAddress(D3DX9Module, "D3DXAssembleShader");
+ D3DXDisassembleShader = (D3DXDisassembleShaderFunction)
+ GetProcAddress(D3DX9Module, "D3DXDisassembleShader");
+ D3DXCreateTexture = (D3DXCreateTextureFunction)
+ GetProcAddress(D3DX9Module, "D3DXCreateTexture");
+ D3DXCreateCubeTexture = (D3DXCreateCubeTextureFunction)
+ GetProcAddress(D3DX9Module, "D3DXCreateCubeTexture");
+ D3DXCreateVolumeTexture = (D3DXCreateVolumeTextureFunction)
+ GetProcAddress(D3DX9Module, "D3DXCreateVolumeTexture");
+ D3DXCreateTextureFromFileExA = (D3DXCreateTextureFromFileExFunction)
+ GetProcAddress(D3DX9Module, "D3DXCreateTextureFromFileExA");
+ D3DXFilterTexture = (D3DXFilterTextureFunction)
+ GetProcAddress(D3DX9Module, "D3DXFilterTexture");
+ D3DXLoadSurfaceFromSurface = (D3DXLoadSurfaceFromSurfaceFunction)
+ GetProcAddress(D3DX9Module, "D3DXLoadSurfaceFromSurface");
+ D3DXGetFVFVertexSize = (D3DXGetFVFVertexSizeFunction)
+ GetProcAddress(D3DX9Module, "D3DXGetFVFVertexSize");
+
+ D3DXMatrixInverse = (D3DXMatrixInverseFunction)
+ GetProcAddress(D3DX9Module, "D3DXMatrixInverse");
+ D3DXMatrixMultiply = (D3DXMatrixBinaryFunction)
+ GetProcAddress(D3DX9Module, "D3DXMatrixMultiply");
+ D3DXMatrixTranspose = (D3DXMatrixUnaryFunction)
+ GetProcAddress(D3DX9Module, "D3DXMatrixTranspose");
+ D3DXMatrixScaling = (D3DXMatrixTripleFunction)
+ GetProcAddress(D3DX9Module, "D3DXMatrixScaling");
+ D3DXMatrixTranslation = (D3DXMatrixTripleFunction)
+ GetProcAddress(D3DX9Module, "D3DXMatrixTranslation");
+ D3DXMatrixRotationZ = (D3DXMatrixAngleFunction)
+ GetProcAddress(D3DX9Module, "D3DXMatrixRotationZ");
+ D3DXVec4Transform = (D3DXVec4TransformFunction)
+ GetProcAddress(D3DX9Module, "D3DXVec4Transform");
+ D3DXVec3Transform = (D3DXVec3TransformFunction)
+ GetProcAddress(D3DX9Module, "D3DXVec3Transform");
+
+ BindSucceeded = D3DXAssembleShader != NULL
+ && D3DXDisassembleShader != NULL
+ && D3DXCreateTexture != NULL
+ && D3DXCreateCubeTexture != NULL
+ && D3DXCreateVolumeTexture != NULL
+ && D3DXCreateTextureFromFileExA != NULL
+ && D3DXFilterTexture != NULL
+ && D3DXLoadSurfaceFromSurface != NULL
+ && D3DXGetFVFVertexSize != NULL
+ && D3DXMatrixInverse != NULL
+ && D3DXMatrixMultiply != NULL
+ && D3DXMatrixTranspose != NULL
+ && D3DXMatrixScaling != NULL
+ && D3DXMatrixTranslation != NULL
+ && D3DXMatrixRotationZ != NULL
+ && D3DXVec4Transform != NULL
+ && D3DXVec3Transform != NULL;
+
+ if (!BindSucceeded) {
+ release_module();
+ }
+ return BindSucceeded;
+}
+
+void Unbind_D3DX9_Runtime(void)
+{
+ release_module();
+ BindAttempted = false;
+ BindSucceeded = false;
+}
+
+static void release_module(void)
+{
+ D3DXAssembleShader = NULL;
+ D3DXDisassembleShader = NULL;
+ D3DXCreateTexture = NULL;
+ D3DXCreateCubeTexture = NULL;
+ D3DXCreateVolumeTexture = NULL;
+ D3DXCreateTextureFromFileExA = NULL;
+ D3DXFilterTexture = NULL;
+ D3DXLoadSurfaceFromSurface = NULL;
+ D3DXGetFVFVertexSize = NULL;
+
+ D3DXMatrixInverse = NULL;
+ D3DXMatrixMultiply = NULL;
+ D3DXMatrixTranspose = NULL;
+ D3DXMatrixScaling = NULL;
+ D3DXMatrixTranslation = NULL;
+ D3DXMatrixRotationZ = NULL;
+ D3DXVec4Transform = NULL;
+ D3DXVec3Transform = NULL;
+
+ if (D3DX9Module != NULL) {
+ FreeLibrary(D3DX9Module);
+ D3DX9Module = NULL;
+ }
+}
+
+const char * Get_D3D_Error_String(HRESULT result)
+{
+ for (int index = 0; index < ERROR_NAME_COUNT; ++index) {
+ if (ERROR_NAMES[index].Result == result) {
+ return ERROR_NAMES[index].Name;
+ }
+ }
+ _snprintf(UnknownErrorText, ERROR_TEXT_SIZE, "0x%08lx", (unsigned long)result);
+ UnknownErrorText[ERROR_TEXT_SIZE - 1] = '\0';
+ return UnknownErrorText;
+}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/d3dx9runtime.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/d3dx9runtime.h
new file mode 100644
index 000000000..4b4690956
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/d3dx9runtime.h
@@ -0,0 +1,133 @@
+/*
+** Command & Conquer Generals Zero Hour(tm)
+** Copyright 2025 Electronic Arts Inc.
+**
+** This program is free software: you can redistribute it and/or modify
+** it under the terms of the GNU General Public License as published by
+** the Free Software Foundation, either version 3 of the License, or
+** (at your option) any later version.
+**
+** This program is distributed in the hope that it will be useful,
+** but WITHOUT ANY WARRANTY; without even the implied warranty of
+** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+** GNU General Public License for more details.
+**
+** You should have received a copy of the GNU General Public License
+** along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+// D3DX9 for the native Direct3D 9 renderer. RENDERER-ROADMAP.md phase 1.
+//
+// The Windows SDK ships d3d9.h and d3d9.lib but no D3DX9: that library only ever
+// came with the DirectX SDK, which was retired in 2012. Seventeen of its entry points
+// are still wanted, nine here and eight more in d3dx9math.h, so they are bound out of
+// d3dx9_43.dll at startup, which is what d3d8to9 does today (d3d8to9.cpp:224) and
+// therefore a dependency this fork already ships with rather than a new one.
+//
+// The names match the D3DX9 entry points so the call sites in dx8wrapper.cpp,
+// TerrainTex.cpp and W3DWater.cpp read the way they always did. Every pointer is
+// null until Bind_D3DX9_Runtime succeeds, so nothing may call one before that.
+
+#ifndef D3DX9RUNTIME_H
+#define D3DX9RUNTIME_H
+
+#include <d3d9.h>
+
+// D3DX filter and default values, from the DirectX SDK's d3dx9tex.h. They are plain
+// constants: the DLL reads them, it does not define them.
+#define D3DX_DEFAULT ((UINT)-1)
+#define D3DX_FILTER_NONE (1 << 0)
+#define D3DX_FILTER_POINT (2 << 0)
+#define D3DX_FILTER_LINEAR (3 << 0)
+#define D3DX_FILTER_TRIANGLE (4 << 0)
+#define D3DX_FILTER_BOX (5 << 0)
+
+typedef interface ID3DXBuffer * LPD3DXBUFFER;
+typedef interface ID3DXInclude * LPD3DXINCLUDE;
+
+DECLARE_INTERFACE_(ID3DXBuffer, IUnknown)
+{
+ STDMETHOD(QueryInterface)(THIS_ REFIID iid, LPVOID * ppv) PURE;
+ STDMETHOD_(ULONG, AddRef)(THIS) PURE;
+ STDMETHOD_(ULONG, Release)(THIS) PURE;
+ STDMETHOD_(LPVOID, GetBufferPointer)(THIS) PURE;
+ STDMETHOD_(DWORD, GetBufferSize)(THIS) PURE;
+};
+
+struct D3DXMACRO
+{
+ LPCSTR Name;
+ LPCSTR Definition;
+};
+
+struct D3DXIMAGE_INFO
+{
+ UINT Width;
+ UINT Height;
+ UINT Depth;
+ UINT MipLevels;
+ D3DFORMAT Format;
+ D3DRESOURCETYPE ResourceType;
+ DWORD ImageFileFormat;
+};
+
+typedef HRESULT (WINAPI * D3DXAssembleShaderFunction)(LPCSTR source, UINT source_length,
+ const D3DXMACRO * defines, LPD3DXINCLUDE include, DWORD flags,
+ LPD3DXBUFFER * shader, LPD3DXBUFFER * errors);
+
+typedef HRESULT (WINAPI * D3DXDisassembleShaderFunction)(const DWORD * shader, BOOL colour_code,
+ LPCSTR comments, LPD3DXBUFFER * disassembly);
+
+typedef HRESULT (WINAPI * D3DXCreateTextureFunction)(LPDIRECT3DDEVICE9 device,
+ UINT width, UINT height, UINT mip_levels, DWORD usage, D3DFORMAT format, D3DPOOL pool,
+ LPDIRECT3DTEXTURE9 * texture);
+
+typedef HRESULT (WINAPI * D3DXCreateCubeTextureFunction)(LPDIRECT3DDEVICE9 device,
+ UINT edge_length, UINT mip_levels, DWORD usage, D3DFORMAT format, D3DPOOL pool,
+ LPDIRECT3DCUBETEXTURE9 * texture);
+
+typedef HRESULT (WINAPI * D3DXCreateVolumeTextureFunction)(LPDIRECT3DDEVICE9 device,
+ UINT width, UINT height, UINT depth, UINT mip_levels, DWORD usage, D3DFORMAT format,
+ D3DPOOL pool, LPDIRECT3DVOLUMETEXTURE9 * texture);
+
+typedef HRESULT (WINAPI * D3DXCreateTextureFromFileExFunction)(LPDIRECT3DDEVICE9 device,
+ LPCSTR file_name, UINT width, UINT height, UINT mip_levels, DWORD usage, D3DFORMAT format,
+ D3DPOOL pool, DWORD filter, DWORD mip_filter, D3DCOLOR colour_key, D3DXIMAGE_INFO * info,
+ PALETTEENTRY * palette, LPDIRECT3DTEXTURE9 * texture);
+
+typedef HRESULT (WINAPI * D3DXFilterTextureFunction)(LPDIRECT3DBASETEXTURE9 texture,
+ const PALETTEENTRY * palette, UINT source_level, DWORD filter);
+
+typedef HRESULT (WINAPI * D3DXLoadSurfaceFromSurfaceFunction)(LPDIRECT3DSURFACE9 destination,
+ const PALETTEENTRY * destination_palette, const RECT * destination_rect,
+ LPDIRECT3DSURFACE9 source, const PALETTEENTRY * source_palette, const RECT * source_rect,
+ DWORD filter, D3DCOLOR colour_key);
+
+typedef UINT (WINAPI * D3DXGetFVFVertexSizeFunction)(DWORD fvf);
+
+extern D3DXAssembleShaderFunction D3DXAssembleShader;
+extern D3DXDisassembleShaderFunction D3DXDisassembleShader;
+extern D3DXCreateTextureFunction D3DXCreateTexture;
+extern D3DXCreateCubeTextureFunction D3DXCreateCubeTexture;
+extern D3DXCreateVolumeTextureFunction D3DXCreateVolumeTexture;
+extern D3DXCreateTextureFromFileExFunction D3DXCreateTextureFromFileExA;
+extern D3DXFilterTextureFunction D3DXFilterTexture;
+extern D3DXLoadSurfaceFromSurfaceFunction D3DXLoadSurfaceFromSurface;
+extern D3DXGetFVFVertexSizeFunction D3DXGetFVFVertexSize;
+
+// Loads d3dx9_43.dll and resolves all seventeen entry points, this header's and
+// d3dx9math.h's. Returns false and leaves every pointer null if the DLL is missing or
+// any one of them is not exported, so a caller that checks the return value never has
+// to check the pointers. Calling it a second time is free and reports the first call.
+bool Bind_D3DX9_Runtime(void);
+
+// Frees the DLL and nulls every pointer, so the next Bind_D3DX9_Runtime tries again.
+// Belongs beside the device teardown, since nothing may call a D3DX entry point after it.
+void Unbind_D3DX9_Runtime(void);
+
+// d3dx9_43.dll does not export D3DXGetErrorStringA, which dx8wrapper.cpp's two error
+// loggers used. This names the D3DERR and D3D_OK codes the renderer actually returns
+// and falls back to the raw hex for anything else. Never returns null.
+const char * Get_D3D_Error_String(HRESULT result);
+
+#endif // D3DX9RUNTIME_H
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/test_dx9_smoke.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/test_dx9_smoke.cpp
new file mode 100644
index 000000000..19f0e3dd1
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/test_dx9_smoke.cpp
@@ -0,0 +1,376 @@
+// Native Direct3D 9 checkpoint for RENDERER-ROADMAP.md phase 1. test_dx8_smoke.cpp
+// proves the D3D8 path through our d3d8to9 d3d8.dll; this one calls Direct3DCreate9
+// itself, with no translating DLL anywhere, and answers the questions that decide
+// whether the phase-1 rename is a rename or a rewrite:
+//
+// 1. a device comes up with the game's own present parameters (dx8wrapper.cpp);
+// 2. d3dx9_43.dll binds and its assembler still takes ps.1.1 / vs.1.1 source, which
+// is what W3DWater.cpp hands D3DXAssembleShader three times at runtime;
+// 3. a vs.1.1 shader survives the D3D8-to-D3D9 round trip - disassemble, fix the two
+// rules D3D9 tightened, reassemble - which is how the shipped Trees.vso and
+// wave.vso will have to be loaded;
+// 4. the D3D8 calls with no D3D9 counterpart have working replacements:
+// D3DTSS sampler states -> SetSamplerState, CopyRects -> UpdateSurface,
+// CreateImageSurface -> CreateOffscreenPlainSurface, D3DRS_ZBIAS -> D3DRS_DEPTHBIAS.
+//
+// "DX9 smoke OK" means pass. Every failure prints what it was doing first.
+
+#include <windows.h>
+#include <d3d9.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "d3dx9runtime.h"
+#include "d3dx9math.h"
+
+static const int WINDOW_EDGE = 64;
+static const int BACK_BUFFER_WIDTH = 640;
+static const int BACK_BUFFER_HEIGHT = 480;
+static const int RENDER_TARGET_EDGE = 256;
+static const int SAMPLE_PIXEL_OFFSET = 10;
+static const int BYTES_PER_PIXEL = 4;
+static const BYTE CLEAR_RED = 64;
+static const BYTE CLEAR_GREEN = 0;
+static const BYTE CLEAR_BLUE = 128;
+static const BYTE CHANNEL_TOLERANCE = 16;
+static const float MAX_DEPTH = 1.0f;
+static const float DEPTH_BIAS = 0.0001f;
+static const DWORD MAX_ANISOTROPY = 4;
+
+// The river shader out of W3DWater.cpp, unchanged. It is the real thing the game
+// assembles at runtime, so it is the right thing to ask the D3D9 assembler about.
+static const char RIVER_PIXEL_SHADER[] =
+ "ps.1.1\n"
+ "tex t0\n"
+ "tex t1\n"
+ "tex t2\n"
+ "tex t3\n"
+ "mul r0.rgb, v0, t0\n"
+ "mov r0.a, t0\n"
+ "mul r1, t1, t2\n"
+ "add r1.rgb, r1, t3\n"
+ "mul r1.rgb, r1, v0.a\n"
+ "+mul r0.a, r0, t3\n"
+ "add r0.rgb, r0, r1\n";
+
+// A vs.1.1 shader written the way the shipped .vso files were, and the same shader
+// after the repairs D3D9 forces. Three rules changed under D3D8, and this shader
+// breaks all of them: the vertex declaration travelled beside the shader as a DWORD
+// array instead of dcl statements, a register could be read before it was written,
+// and an m*x* instruction could name its destination as its own first source.
+static const char LEGACY_VERTEX_SHADER[] =
+ "vs.1.1\n"
+ "m4x4 r0, r0, c0\n"
+ "mov oPos, r0\n"
+ "mov oD0, v5\n";
+
+static const char REPAIRED_VERTEX_SHADER[] =
+ "vs.1.1\n"
+ "dcl_position v0\n" // built from the DWORD declaration the caller passes alongside
+ "dcl_color v5\n"
+ "mov r0, c0\n" // every temp and output register written before it is read
+ "mov r1, c0\n"
+ "mov r1, r0\n" // m4x4's first source moved off its destination
+ "m4x4 r0, r1, c0\n"
+ "mov oPos, r0\n"
+ "mov oD0, v5\n";
+
+static const D3DVERTEXELEMENT9 POSITION_AND_COLOUR_DECLARATION[] =
+{
+ { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 },
+ { 0, 12, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 0 },
+ D3DDECL_END()
+};
+
+template <typename Interface> class Owned
+{
+public:
+ Owned() : Pointer(NULL) {}
+ ~Owned() { if (Pointer != NULL) Pointer->Release(); }
+ void Take(Interface * pointer) { Pointer = pointer; }
+ Interface ** operator&() { return &Pointer; }
+ Interface * operator->() const { return Pointer; }
+ operator Interface *() const { return Pointer; }
+
+private:
+ Owned(const Owned &);
+ Owned & operator=(const Owned &);
+
+ Interface * Pointer;
+};
+
+class BoundD3DX9Runtime
+{
+public:
+ BoundD3DX9Runtime() : Bound(Bind_D3DX9_Runtime()) {}
+ ~BoundD3DX9Runtime() { if (Bound) Unbind_D3DX9_Runtime(); }
+ bool Is_Bound() const { return Bound; }
+
+private:
+ BoundD3DX9Runtime(const BoundD3DX9Runtime &);
+ BoundD3DX9Runtime & operator=(const BoundD3DX9Runtime &);
+
+ bool Bound;
+};
+
+class OwnedWindow
+{
+public:
+ OwnedWindow(const char * className, DWORD style, int width, int height)
+ {
+ WNDCLASSA windowClass = {0};
+ windowClass.lpfnWndProc = DefWindowProcA;
+ windowClass.hInstance = GetModuleHandleA(NULL);
+ windowClass.lpszClassName = className;
+ RegisterClassA(&windowClass);
+ Handle = CreateWindowA(className, "dx9smoke", style, 0, 0, width, height,
+ NULL, NULL, windowClass.hInstance, NULL);
+ }
+ ~OwnedWindow() { if (Handle != NULL) DestroyWindow(Handle); }
+ HWND Get() const { return Handle; }
+
+private:
+ OwnedWindow(const OwnedWindow &);
+ OwnedWindow & operator=(const OwnedWindow &);
+
+ HWND Handle;
+};
+
+static bool channel_is_near(BYTE actual, BYTE expected)
+{
+ const int difference = (int)actual - (int)expected;
+ return difference <= (int)CHANNEL_TOLERANCE && difference >= -(int)CHANNEL_TOLERANCE;
+}
+
+int main()
+{
+ Owned<IDirect3D9> direct3D;
+ direct3D.Take(Direct3DCreate9(D3D_SDK_VERSION));
+ if (direct3D == NULL) {
+ printf("FAIL: Direct3DCreate9 returned NULL\n");
+ return 1;
+ }
+
+ D3DADAPTER_IDENTIFIER9 adapter;
+ if (SUCCEEDED(direct3D->GetAdapterIdentifier(D3DADAPTER_DEFAULT, 0, &adapter))) {
+ printf("adapter: %s\n", adapter.Description);
+ }
+
+ OwnedWindow window("dx9smoke", WS_OVERLAPPEDWINDOW, WINDOW_EDGE, WINDOW_EDGE);
+ if (window.Get() == NULL) {
+ printf("FAIL: CreateWindow\n");
+ return 1;
+ }
+
+ D3DDISPLAYMODE displayMode;
+ if (FAILED(direct3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &displayMode))) {
+ printf("FAIL: GetAdapterDisplayMode\n");
+ return 1;
+ }
+
+ // dx8wrapper.cpp's own choices: windowed, discard, auto depth, mixed vertex processing,
+ // plus the lockable back buffer that lets the clear be read back.
+ D3DPRESENT_PARAMETERS present = {0};
+ present.BackBufferWidth = BACK_BUFFER_WIDTH;
+ present.BackBufferHeight = BACK_BUFFER_HEIGHT;
+ present.Windowed = TRUE;
+ present.SwapEffect = D3DSWAPEFFECT_DISCARD;
+ present.BackBufferFormat = displayMode.Format;
+ present.hDeviceWindow = window.Get();
+ present.EnableAutoDepthStencil = TRUE;
+ present.AutoDepthStencilFormat = D3DFMT_D16;
+ present.Flags = D3DPRESENTFLAG_LOCKABLE_BACKBUFFER;
+
+ Owned<IDirect3DDevice9> device;
+ HRESULT created = direct3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, window.Get(),
+ D3DCREATE_MIXED_VERTEXPROCESSING, &present, &device);
+ if (FAILED(created) || device == NULL) {
+ printf("FAIL: CreateDevice hr=0x%08lx\n", (unsigned long)created);
+ return 1;
+ }
+ printf("device: native Direct3D 9, no translating dll\n");
+
+ if (FAILED(device->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER,
+ D3DCOLOR_XRGB(CLEAR_RED, CLEAR_GREEN, CLEAR_BLUE), MAX_DEPTH, 0))) {
+ printf("FAIL: Clear\n");
+ return 1;
+ }
+
+ // Read the cleared back buffer back, so a runtime that created a device and painted
+ // nothing does not pass.
+ {
+ Owned<IDirect3DSurface9> backBuffer;
+ if (FAILED(device->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &backBuffer))) {
+ printf("FAIL: GetBackBuffer\n");
+ return 1;
+ }
+ D3DLOCKED_RECT locked;
+ if (FAILED(backBuffer->LockRect(&locked, NULL, D3DLOCK_READONLY))) {
+ printf("FAIL: the back buffer is not lockable\n");
+ return 1;
+ }
+ const BYTE * pixel = (const BYTE *)locked.pBits
+ + SAMPLE_PIXEL_OFFSET * locked.Pitch + SAMPLE_PIXEL_OFFSET * BYTES_PER_PIXEL;
+ const bool holdsClearColour = channel_is_near(pixel[0], CLEAR_BLUE)
+ && channel_is_near(pixel[1], CLEAR_GREEN)
+ && channel_is_near(pixel[2], CLEAR_RED);
+ printf("back buffer pixel (b,g,r) = (%u,%u,%u)\n", pixel[0], pixel[1], pixel[2]);
+ backBuffer->UnlockRect();
+ if (!holdsClearColour) {
+ printf("FAIL: the back buffer does not hold the clear colour (%u,%u,%u)\n",
+ CLEAR_RED, CLEAR_GREEN, CLEAR_BLUE);
+ return 1;
+ }
+ }
+
+ // The D3D8 calls that have no D3D9 counterpart, each in its replacement form.
+ if (FAILED(device->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR))
+ || FAILED(device->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR))
+ || FAILED(device->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_LINEAR))
+ || FAILED(device->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_WRAP))
+ || FAILED(device->SetSamplerState(0, D3DSAMP_MAXANISOTROPY, MAX_ANISOTROPY))) {
+ printf("FAIL: the D3DTSS filter and address states did not move to SetSamplerState\n");
+ return 1;
+ }
+ const float depthBias = DEPTH_BIAS;
+ if (FAILED(device->SetRenderState(D3DRS_DEPTHBIAS, *(const DWORD *)&depthBias))) {
+ printf("FAIL: D3DRS_ZBIAS has no working D3DRS_DEPTHBIAS replacement\n");
+ return 1;
+ }
+ {
+ Owned<IDirect3DTexture9> renderTexture;
+ Owned<IDirect3DSurface9> renderSurface;
+ Owned<IDirect3DSurface9> readback;
+ if (FAILED(device->CreateTexture(RENDER_TARGET_EDGE, RENDER_TARGET_EDGE, 1,
+ D3DUSAGE_RENDERTARGET, present.BackBufferFormat, D3DPOOL_DEFAULT, &renderTexture, NULL))
+ || FAILED(renderTexture->GetSurfaceLevel(0, &renderSurface))
+ || FAILED(device->CreateOffscreenPlainSurface(RENDER_TARGET_EDGE, RENDER_TARGET_EDGE,
+ present.BackBufferFormat, D3DPOOL_SYSTEMMEM, &readback, NULL))) {
+ printf("FAIL: CreateImageSurface has no working CreateOffscreenPlainSurface replacement\n");
+ return 1;
+ }
+ // CopyRects is gone; GetRenderTargetData is the render-target-to-system-memory half of it.
+ if (FAILED(device->GetRenderTargetData(renderSurface, readback))) {
+ printf("FAIL: CopyRects has no working GetRenderTargetData replacement\n");
+ return 1;
+ }
+ }
+ printf("replacements: sampler states, depth bias, offscreen surface, render-target readback\n");
+
+ // d3dx9runtime.cpp is what the renderer will bind, so the test binds the same thing
+ // rather than a copy of it: a missing entry point fails here before it fails in a match.
+ BoundD3DX9Runtime d3dx9;
+ if (!d3dx9.Is_Bound()) {
+ printf("FAIL: d3dx9_43.dll did not bind; all seventeen entry points are phase 1 dependencies\n");
+ return 1;
+ }
+ printf("d3dx9: all seventeen entry points bound out of d3dx9_43.dll\n");
+
+ // The math entry points are declared by hand in d3dx9math.h, so their calling
+ // convention is a guess until something calls one. A stdcall/cdecl mismatch
+ // unbalances the stack rather than returning a wrong number, so this runs the
+ // bezier basis matrix out of BezierSegment.cpp through the transform that
+ // DumbProjectileBehavior's shell arc depends on, and checks the answer.
+ {
+ const D3DXMATRIX bezierBasis(
+ -1.0f, 3.0f, -3.0f, 1.0f,
+ 3.0f, -6.0f, 3.0f, 0.0f,
+ -3.0f, 3.0f, 0.0f, 0.0f,
+ 1.0f, 0.0f, 0.0f, 0.0f);
+ const D3DXVECTOR4 unitTime(1.0f, 1.0f, 1.0f, 1.0f);
+ D3DXVECTOR4 transformed(0.0f, 0.0f, 0.0f, 0.0f);
+ D3DXVec4Transform(&transformed, &unitTime, &bezierBasis);
+
+ // Each output component is the sum of one column, and the columns of this
+ // matrix sum to 0, 0, 0 and 1.
+ const bool transformIsRight = transformed.x == 0.0f && transformed.y == 0.0f
+ && transformed.z == 0.0f && transformed.w == 1.0f;
+ const FLOAT dot = D3DXVec4Dot(&unitTime, &unitTime);
+ printf("d3dx9 math: basis transform = (%g,%g,%g,%g), unit dot = %g\n",
+ transformed.x, transformed.y, transformed.z, transformed.w, dot);
+ if (!transformIsRight || dot != 4.0f) {
+ printf("FAIL: the hand-declared D3DX math signatures do not match the DLL\n");
+ return 1;
+ }
+ }
+
+ // The water pixel shader, assembled and created exactly as W3DWater.cpp does it.
+ {
+ Owned<ID3DXBuffer> compiled;
+ Owned<ID3DXBuffer> errors;
+ HRESULT assembled = D3DXAssembleShader(RIVER_PIXEL_SHADER, (UINT)strlen(RIVER_PIXEL_SHADER),
+ NULL, NULL, 0, &compiled, &errors);
+ if (FAILED(assembled) || compiled == NULL) {
+ printf("FAIL: the river ps.1.1 shader did not assemble: %s\n",
+ errors != NULL ? (const char *)errors->GetBufferPointer() : "no error text");
+ return 1;
+ }
+ Owned<IDirect3DPixelShader9> pixelShader;
+ HRESULT loaded = device->CreatePixelShader((const DWORD *)compiled->GetBufferPointer(), &pixelShader);
+ if (FAILED(loaded)) {
+ printf("FAIL: CreatePixelShader on the river shader hr=0x%08lx\n", (unsigned long)loaded);
+ return 1;
+ }
+ printf("ps.1.1: the river shader assembles and loads on a native D3D9 device\n");
+ }
+
+ // The .vso route. A shipped vertex shader arrives as D3D8 bytecode, so WW3D2 will have
+ // to disassemble it, repair the assembly text and reassemble it, which is what
+ // d3d8to9_device.cpp:1400 onward does. Both halves are checked here: that the legacy
+ // form really is refused, so none of that work is defensive, and that the repaired form
+ // loads. The disassembler is checked on the way through, since the repair has nothing
+ // to read without it.
+ {
+ Owned<ID3DXBuffer> rejected;
+ Owned<ID3DXBuffer> errors;
+ const HRESULT legacyAssembled = D3DXAssembleShader(LEGACY_VERTEX_SHADER,
+ (UINT)strlen(LEGACY_VERTEX_SHADER), NULL, NULL, 0, &rejected, &errors);
+ if (SUCCEEDED(legacyAssembled)) {
+ printf("FAIL: the D3D9 assembler took a vs.1.1 shader with no dcl statements, an\n"
+ " uninitialised register read and an m4x4 aliasing its own destination.\n"
+ " One of those rules is not enforced, so the repair list is wrong.\n");
+ return 1;
+ }
+ printf("vs.1.1: the legacy form is refused, as it must be\n");
+
+ Owned<ID3DXBuffer> compiled;
+ Owned<ID3DXBuffer> repairErrors;
+ const HRESULT repairedAssembled = D3DXAssembleShader(REPAIRED_VERTEX_SHADER,
+ (UINT)strlen(REPAIRED_VERTEX_SHADER), NULL, NULL, 0, &compiled, &repairErrors);
+ if (FAILED(repairedAssembled) || compiled == NULL) {
+ printf("FAIL: the repaired vs.1.1 shader did not assemble: %s\n",
+ repairErrors != NULL ? (const char *)repairErrors->GetBufferPointer() : "no error text");
+ return 1;
+ }
+
+ Owned<IDirect3DVertexShader9> vertexShader;
+ const HRESULT loaded = device->CreateVertexShader(
+ (const DWORD *)compiled->GetBufferPointer(), &vertexShader);
+ if (FAILED(loaded)) {
+ printf("FAIL: CreateVertexShader on the repaired shader hr=0x%08lx\n", (unsigned long)loaded);
+ return 1;
+ }
+
+ Owned<ID3DXBuffer> disassembly;
+ if (FAILED(D3DXDisassembleShader((const DWORD *)compiled->GetBufferPointer(), FALSE, NULL, &disassembly))
+ || disassembly == NULL) {
+ printf("FAIL: D3DXDisassembleShader, which the repair pass reads its input from\n");
+ return 1;
+ }
+
+ Owned<IDirect3DVertexDeclaration9> declaration;
+ if (FAILED(device->CreateVertexDeclaration(POSITION_AND_COLOUR_DECLARATION, &declaration))) {
+ printf("FAIL: CreateVertexDeclaration, which replaces the D3D8 declaration array\n");
+ return 1;
+ }
+ printf("vs.1.1: the repaired form assembles, loads and declares\n");
+ }
+
+ if (FAILED(device->Present(NULL, NULL, NULL, NULL))) {
+ printf("FAIL: Present\n");
+ return 1;
+ }
+
+ printf("DX9 smoke OK\n");
+ return 0;
+}