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.

feat(w3d): native Direct3D 11 backend behind the D3D9 seam

Olcay Seyganbfb60e1729f6
diff --git a/GeneralsMD/Code/CMakeLists.txt b/GeneralsMD/Code/CMakeLists.txt
index 2d029485c..038591c8f 100644
--- a/GeneralsMD/Code/CMakeLists.txt
+++ b/GeneralsMD/Code/CMakeLists.txt
@@ -205,6 +205,59 @@ set_target_properties(ffshader PROPERTIES CXX_STANDARD 17)
target_include_directories(ffshader PUBLIC ${WW}/WW3D2)
target_link_libraries(ffshader PUBLIC d3d9)
+# ---- ffvertex -------------------------------------------------------------
+# The other half of the same job: the fixed-function vertex pipeline as HLSL. It
+# generates for both profiles so the D3D9 form can be compared against the pipeline
+# it replaces before the D3D11 one is trusted.
+add_library(ffvertex STATIC ${WW}/WW3D2/ffvertex.cpp)
+set_target_properties(ffvertex PROPERTIES CXX_STANDARD 17)
+target_include_directories(ffvertex PUBLIC ${WW}/WW3D2)
+target_link_libraries(ffvertex PUBLIC d3d9)
+
+# ---- dx11device -----------------------------------------------------------
+# The Direct3D 11 device, its swap chain and the views on it: the bottom of phase 2.
+# Its own library for the same reason ffshader is, and for one more - it links d3d11
+# and dxgi, and nothing else in the tree does yet. The test creates a real device.
+add_library(dx11device STATIC ${WW}/WW3D2/dx11device.cpp)
+set_target_properties(dx11device PROPERTIES CXX_STANDARD 17)
+target_include_directories(dx11device PUBLIC ${WW}/WW3D2)
+target_link_libraries(dx11device PUBLIC d3d11 dxgi)
+
+# ---- dx11state ------------------------------------------------------------
+# D3D9's render states turned into D3D11's three state objects. Pure translation,
+# no device, so the whole table is checked by a test rather than looked at on screen.
+add_library(dx11state STATIC ${WW}/WW3D2/dx11state.cpp)
+set_target_properties(dx11state PROPERTIES CXX_STANDARD 17)
+target_include_directories(dx11state PUBLIC ${WW}/WW3D2)
+target_link_libraries(dx11state PUBLIC d3d9 d3d11)
+
+# ---- dx11layout -----------------------------------------------------------
+# A D3D9 flexible vertex format read out as a D3D11 input layout. The vertex buffers
+# keep the bytes they have; this is what tells D3D11 where the fields are.
+add_library(dx11layout STATIC ${WW}/WW3D2/dx11layout.cpp)
+set_target_properties(dx11layout PROPERTIES CXX_STANDARD 17)
+target_include_directories(dx11layout PUBLIC ${WW}/WW3D2)
+target_link_libraries(dx11layout PUBLIC d3d9 d3d11)
+
+# ---- dx11resource ---------------------------------------------------------
+# The buffers and textures: D3D9's formats, pools and lock flags read as D3D11's
+# formats, usages and map types. Half a table and half what the device will accept,
+# so the test checks the table and then hands the results to a real device.
+add_library(dx11resource STATIC ${WW}/WW3D2/dx11resource.cpp)
+set_target_properties(dx11resource PROPERTIES CXX_STANDARD 17)
+target_include_directories(dx11resource PUBLIC ${WW}/WW3D2)
+target_link_libraries(dx11resource PUBLIC d3d9 d3d11)
+
+# ---- dx11backend ----------------------------------------------------------
+# The renderer itself: the engine's D3D9-shaped calls taken as they are and resolved
+# into a D3D11 pipeline at the moment of the draw. Ties the five pieces above
+# together, which is why it is the last of them and the one with a drawing test.
+add_library(dx11backend STATIC ${WW}/WW3D2/dx11backend.cpp)
+set_target_properties(dx11backend PROPERTIES CXX_STANDARD 17)
+target_include_directories(dx11backend PUBLIC ${WW}/WW3D2)
+target_link_libraries(dx11backend PUBLIC dx11device dx11state dx11layout dx11resource
+ ffshader ffvertex)
+
# ---- ww3d2 (renderer core) ------------------------------------------------
# wwshade is header-only here on purpose: no .dsp links wwshade.lib and its
# shd*bump* sources need shdpp/NVASM-generated headers. Revisit at exe link.
@@ -222,7 +275,7 @@ add_library(ww3d2 STATIC
${WW}/WW3D2/dx8polygonrenderer.cpp ${WW}/WW3D2/dx8renderer.cpp ${WW}/WW3D2/dx8rendererdebugger.cpp
${WW}/WW3D2/dx8texman.cpp ${WW}/WW3D2/dx8vertexbuffer.cpp ${WW}/WW3D2/dx8webbrowser.cpp
${WW}/WW3D2/dx8wrapper.cpp ${WW}/WW3D2/dynamesh.cpp ${WW}/WW3D2/ffprobe.cpp
- ${WW}/WW3D2/font3d.cpp
+ ${WW}/WW3D2/ffshadercache.cpp ${WW}/WW3D2/dx11runtime.cpp ${WW}/WW3D2/font3d.cpp
${WW}/WW3D2/formconv.cpp ${WW}/WW3D2/hanim.cpp ${WW}/WW3D2/hanimmgr.cpp
${WW}/WW3D2/hcanim.cpp ${WW}/WW3D2/hlod.cpp ${WW}/WW3D2/hmdldef.cpp
${WW}/WW3D2/hmorphanim.cpp ${WW}/WW3D2/hrawanim.cpp ${WW}/WW3D2/htree.cpp
@@ -260,7 +313,7 @@ target_include_directories(ww3d2
# D3DX9 has no import library anywhere and is bound at runtime instead: see
# WW3D2/d3dx9runtime.h. vfw32 is FramGrab.cpp writing AVIs.
target_link_libraries(ww3d2
- PUBLIC d3d9 dxguid vfw32 d3dx9runtime
+ PUBLIC d3d9 dxguid vfw32 d3dx9runtime ffshader dx11backend
PRIVATE wwlib wwmath wwdebug wwsaveload)
# dx8webbrowser.cpp is the one file /MP cannot have: MSVC rejects #import under
# multi-process compilation (C2813) and finds the directive by a lexical scan, so
@@ -614,6 +667,15 @@ target_include_directories(test_ww3d2 PRIVATE
${WW}/WW3D2 ${WW}/WWLib ${WW}/WWMath ${WW}/WWDebug ${WW}/WWSaveLoad ${WW}/Wwutil)
add_lib_test(test_ffshader ffshader)
+add_lib_test(test_dx11device dx11device)
+add_lib_test(test_dx11state dx11state)
+add_lib_test(test_dx11layout dx11layout)
+add_lib_test(test_ffvertex ffvertex)
+add_lib_test(test_ffvertexcompile ffvertex)
+add_lib_test(test_ffshadercompile ffshader)
+add_lib_test(test_dx11pipeline dx11device dx11state dx11layout ffshader ffvertex)
+add_lib_test(test_dx11resource dx11resource dx11device)
+add_lib_test(test_dx11backend dx11backend)
add_lib_test(test_wwdownload wwdownload)
target_include_directories(test_wwdownload PRIVATE ${WW}/WWDownload)
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h
index 06ee0438c..8e10afe56 100644
--- a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h
+++ b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h
@@ -122,6 +122,8 @@ public:
///< is derived from it and is what the device layer reads.
Int m_msaaLevel; ///< multisampling, as an index into the levels the options menu offers
Bool m_fixedFunctionProbe; ///< -ffprobe: count the fixed-function combinations the frame actually uses
+ Bool m_combinerShaders; ///< -ffshader: draw with generated pixel shaders instead of the stage combiners
+ Bool m_direct3D11; ///< -dx11: render through the native Direct3D 11 backend
Int m_xResolution;
Int m_yResolution;
Int m_maxShellScreens; ///< this many shells layouts can be loaded at once
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp
index 32c1df0fa..d57220aa9 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp
@@ -1346,6 +1346,32 @@ Int parseFixedFunctionProbe(char *args[], int num)
return 1;
}
+/* -ffshader: draw with generated pixel shaders instead of the texture stage combiners.
+ *
+ * The other half of -ffprobe, and RENDERER-ROADMAP.md phase 2's way of proving a generator
+ * before anything is carried to a second backend: D3D11 has no combiners, so what they compute
+ * has to be written as a shader, and a shader that runs on the existing D3D9 device can be
+ * compared against the pipeline it replaces with tree-check.ps1. A draw whose description the
+ * generator refuses stays on the fixed-function path, and one that brought its own pixel shader
+ * is left alone. The counts go to the log at shutdown. */
+Int parseDirect3D11(char *args[], int num)
+{
+ if (TheWritableGlobalData)
+ {
+ TheWritableGlobalData->m_direct3D11 = TRUE;
+ }
+ return 1;
+}
+
+Int parseCombinerShaders(char *args[], int num)
+{
+ if (TheWritableGlobalData)
+ {
+ TheWritableGlobalData->m_combinerShaders = TRUE;
+ }
+ return 1;
+}
+
/* -camera <x> <y>: point the camera at one map position and leave it there.
*
* -screenshot only made a picture; it could not say of what. The camera starts at the local
@@ -2102,6 +2128,8 @@ static CommandLineParam params[] =
{ "-screenshot", parseScreenShot },
{ "-msaa", parseMSAA },
{ "-ffprobe", parseFixedFunctionProbe },
+ { "-ffshader", parseCombinerShaders },
+ { "-dx11", parseDirect3D11 },
{ "-autocamera", parseAutoCamera },
{ "-camera", parseCameraLook },
{ "-tracemove", parseTraceMove },
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp
index ee60b1c50..4d3f56643 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp
@@ -647,6 +647,8 @@ GlobalData::GlobalData()
m_windowMode = WINDOW_MODE_FULLSCREEN;
m_msaaLevel = 0;
m_fixedFunctionProbe = FALSE;
+ m_combinerShaders = FALSE;
+ m_direct3D11 = FALSE;
m_xResolution = 800;
m_yResolution = 600;
m_maxShellScreens = 0;
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp
index 144b866f1..957e74abe 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp
@@ -47,6 +47,8 @@ static void drawFramerateBar(void);
#include "Common/OptionsCatalog.h"
#include "dx8wrapper.h"
#include "ffprobe.h"
+#include "ffshadercache.h"
+#include "dx11runtime.h"
#include "Common/PerfTimer.h"
#include "Common/FileSystem.h"
#include "Common/LocalFileSystem.h"
@@ -432,6 +434,34 @@ W3DDisplay::W3DDisplay()
W3DDisplay::~W3DDisplay()
{
+ // What -ffshader did, written from here because WW3D2 is built without RELEASE_DEBUG_LOGGING
+ // and its own WWDEBUG_SAY does not exist in a shipping build. Before W3D shuts down, which is
+ // where the cache is released.
+ if( CombinerShaders_Are_Enabled() )
+ {
+ unsigned compiled = 0;
+ unsigned refusedDescriptions = 0;
+ unsigned long long shadedDraws = 0;
+ unsigned long long refusedDraws = 0;
+ CombinerShaderCache_Statistics( compiled, refusedDescriptions, shadedDraws, refusedDraws );
+ DEBUG_LOG(("-ffshader: %u programs compiled, %u descriptions refused; %I64u draws shaded, "
+ "%I64u left on the fixed-function path\n",
+ compiled, refusedDescriptions, shadedDraws, refusedDraws));
+ }
+
+ // Same reason as above: WW3D2 has no logging in a shipping build, and a -dx11 run that made no
+ // device at all would otherwise look exactly like one that made a device nothing drew through.
+ if( Direct3D11_Is_Enabled() )
+ {
+ unsigned pipelines = 0;
+ unsigned long long drawsMade = 0;
+ unsigned long long drawsRefused = 0;
+ Direct3D11_Statistics( pipelines, drawsMade, drawsRefused );
+ DEBUG_LOG(("-dx11: device %s; %u pipelines built, %I64u draws made, %I64u refused\n",
+ Direct3D11_Is_Active() ? "created" : "REFUSED",
+ pipelines, drawsMade, drawsRefused));
+ }
+
// get rid of the debug display
delete m_debugDisplay;
@@ -926,8 +956,10 @@ void W3DDisplay::init( void )
// 4, 8 or 16; the device degrades an unsupported one on its own.
DX8Wrapper::Set_Requested_MultiSample_Level( msaaSamplesForLevel( TheGlobalData->m_msaaLevel ) );
- // Same reason: WW3D2 cannot see GlobalData, so -ffprobe is pushed in from here.
+ // Same reason: WW3D2 cannot see GlobalData, so -ffprobe and -ffshader are pushed in from here.
FixedFunctionProbe_Enable( TheGlobalData->m_fixedFunctionProbe != FALSE );
+ CombinerShaders_Enable( TheGlobalData->m_combinerShaders != FALSE );
+ Direct3D11_Enable( TheGlobalData->m_direct3D11 != FALSE );
// Same problem, same answer: the filter table is built the moment the device exists and WW3D2
// cannot see GlobalData, so the player's texture filtering goes in here. Nothing in the game
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/d3dx9runtime.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/d3dx9runtime.cpp
index 03ca6764f..497886c17 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/d3dx9runtime.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/d3dx9runtime.cpp
@@ -22,6 +22,7 @@
#include <stdio.h>
D3DXAssembleShaderFunction D3DXAssembleShader = NULL;
+D3DXCompileShaderFunction D3DXCompileShader = NULL;
D3DXDisassembleShaderFunction D3DXDisassembleShader = NULL;
D3DXCreateTextureFunction D3DXCreateTexture = NULL;
D3DXCreateCubeTextureFunction D3DXCreateCubeTexture = NULL;
@@ -98,6 +99,8 @@ bool Bind_D3DX9_Runtime(void)
D3DXAssembleShader = (D3DXAssembleShaderFunction)
GetProcAddress(D3DX9Module, "D3DXAssembleShader");
+ D3DXCompileShader = (D3DXCompileShaderFunction)
+ GetProcAddress(D3DX9Module, "D3DXCompileShader");
D3DXDisassembleShader = (D3DXDisassembleShaderFunction)
GetProcAddress(D3DX9Module, "D3DXDisassembleShader");
D3DXCreateTexture = (D3DXCreateTextureFunction)
@@ -133,6 +136,7 @@ bool Bind_D3DX9_Runtime(void)
GetProcAddress(D3DX9Module, "D3DXVec3Transform");
BindSucceeded = D3DXAssembleShader != NULL
+ && D3DXCompileShader != NULL
&& D3DXDisassembleShader != NULL
&& D3DXCreateTexture != NULL
&& D3DXCreateCubeTexture != NULL
@@ -166,6 +170,7 @@ void Unbind_D3DX9_Runtime(void)
static void release_module(void)
{
D3DXAssembleShader = NULL;
+ D3DXCompileShader = NULL;
D3DXDisassembleShader = NULL;
D3DXCreateTexture = NULL;
D3DXCreateCubeTexture = NULL;
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/d3dx9runtime.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/d3dx9runtime.h
index 3ec8db94b..e8cbc3348 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/d3dx9runtime.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/d3dx9runtime.h
@@ -75,6 +75,13 @@ typedef HRESULT (WINAPI * D3DXAssembleShaderFunction)(LPCSTR source, UINT source
const D3DXMACRO * defines, LPD3DXINCLUDE include, DWORD flags,
LPD3DXBUFFER * shader, LPD3DXBUFFER * errors);
+// The HLSL compiler. ffshader.cpp writes the fixed-function stages out as HLSL and this is what
+// turns that into something a device will take; the constant table is not asked for, because the
+// generated shader's registers are fixed by the generator rather than looked up.
+typedef HRESULT (WINAPI * D3DXCompileShaderFunction)(LPCSTR source, UINT source_length,
+ const D3DXMACRO * defines, LPD3DXINCLUDE include, LPCSTR entry_point, LPCSTR profile,
+ DWORD flags, LPD3DXBUFFER * shader, LPD3DXBUFFER * errors, void ** constant_table);
+
typedef HRESULT (WINAPI * D3DXDisassembleShaderFunction)(const DWORD * shader, BOOL colour_code,
LPCSTR comments, LPD3DXBUFFER * disassembly);
@@ -106,6 +113,7 @@ typedef HRESULT (WINAPI * D3DXLoadSurfaceFromSurfaceFunction)(LPDIRECT3DSURFACE9
typedef UINT (WINAPI * D3DXGetFVFVertexSizeFunction)(DWORD fvf);
extern D3DXAssembleShaderFunction D3DXAssembleShader;
+extern D3DXCompileShaderFunction D3DXCompileShader;
extern D3DXDisassembleShaderFunction D3DXDisassembleShader;
extern D3DXCreateTextureFunction D3DXCreateTexture;
extern D3DXCreateCubeTextureFunction D3DXCreateCubeTexture;
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp
new file mode 100644
index 000000000..95297b740
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp
@@ -0,0 +1,755 @@
+/*
+** 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 "dx11backend.h"
+
+#include "dx11layout.h"
+
+#include <d3dcommon.h>
+#include <stdio.h>
+#include <string.h>
+#include <windows.h>
+
+typedef HRESULT (WINAPI *D3DCompileFunction)(LPCVOID source_data, SIZE_T source_size,
+ LPCSTR source_name, const D3D_SHADER_MACRO * defines, ID3DInclude * include,
+ LPCSTR entry_point, LPCSTR target, UINT flags1, UINT flags2, ID3DBlob ** code,
+ ID3DBlob ** error_messages);
+
+// d3dcompiler_47.dll ships with Windows. Binding it by hand rather than linking it keeps a machine
+// without it running the Direct3D 9 device instead of failing to start.
+static const char * const COMPILER_MODULE = "d3dcompiler_47.dll";
+static const char * const ENTRY_POINT = "main";
+static const char * const VERTEX_PROFILE = "vs_4_0";
+static const char * const PIXEL_PROFILE = "ps_4_0";
+
+// The whole constant block the generated vertex shader reads, always uploaded in full. A shader
+// generated for fewer lights declares a prefix of this, and a constant buffer larger than what a
+// shader declares is legal, so one buffer serves every program.
+struct VertexConstantBlock
+{
+ float WorldViewProjection[16];
+ float WorldView[16];
+ float NormalTransform[16];
+ float TextureMatrix0[16];
+ float TextureMatrix1[16];
+ float MaterialAmbient[4];
+ float MaterialDiffuse[4];
+ float MaterialSpecular[4];
+ float MaterialEmissive[4];
+ float MaterialPower[4];
+ float GlobalAmbient[4];
+ float FogParameters[4];
+ float LightFields[MAXIMUM_VERTEX_LIGHTS][6][4];
+};
+
+struct PixelConstantBlock
+{
+ float TextureFactor[4];
+ float FogColour[4];
+ float AlphaReference[4];
+};
+
+static D3DCompileFunction compiler_function()
+{
+ static D3DCompileFunction compiler = NULL;
+ static bool attempted = false;
+ if (!attempted) {
+ attempted = true;
+ HMODULE module = LoadLibraryA(COMPILER_MODULE);
+ if (module != NULL) {
+ compiler = reinterpret_cast<D3DCompileFunction>(GetProcAddress(module, "D3DCompile"));
+ }
+ }
+ return compiler;
+}
+
+static void set_identity(float matrix[16])
+{
+ memset(matrix, 0, sizeof(float) * 16);
+ matrix[0] = 1.0f;
+ matrix[5] = 1.0f;
+ matrix[10] = 1.0f;
+ matrix[15] = 1.0f;
+}
+
+// Row major throughout, the way D3D9 stores a matrix and the way the generated shaders declare one.
+static void multiply(const float left[16], const float right[16], float result[16])
+{
+ for (unsigned row = 0; row < 4; ++row) {
+ for (unsigned column = 0; column < 4; ++column) {
+ float sum = 0.0f;
+ for (unsigned index = 0; index < 4; ++index) {
+ sum += left[row * 4 + index] * right[index * 4 + column];
+ }
+ result[row * 4 + column] = sum;
+ }
+ }
+}
+
+// A normal is transformed by the inverse transpose of the upper three by three, not by the matrix
+// itself. With a uniform scale the two differ only by a factor that normalize removes, but the
+// engine scales models unevenly and a normal carried through the matrix itself comes out pointing
+// off the surface, which is a lighting error that looks like a modelling error.
+static void inverse_transpose(const float source[16], float result[16])
+{
+ const float a = source[0], b = source[1], c = source[2];
+ const float d = source[4], e = source[5], f = source[6];
+ const float g = source[8], h = source[9], i = source[10];
+
+ const float determinant = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g);
+
+ set_identity(result);
+ if (determinant == 0.0f) {
+ return;
+ }
+ const float scale = 1.0f / determinant;
+
+ // The inverse is the adjugate over the determinant; transposing it is the same as reading the
+ // cofactors along the rows instead of down the columns, which is what this does.
+ result[0] = (e * i - f * h) * scale;
+ result[1] = (f * g - d * i) * scale;
+ result[2] = (d * h - e * g) * scale;
+ result[4] = (c * h - b * i) * scale;
+ result[5] = (a * i - c * g) * scale;
+ result[6] = (b * g - a * h) * scale;
+ result[8] = (b * f - c * e) * scale;
+ result[9] = (c * d - a * f) * scale;
+ result[10] = (a * e - b * d) * scale;
+}
+
+DX11BackendClass::DX11BackendClass()
+ : Device(NULL)
+ , VertexFormat(0)
+ , StreamBuffer(NULL)
+ , StreamStride(0)
+ , StreamOffset(0)
+ , IndexBuffer(NULL)
+ , IndexFormat(DXGI_FORMAT_R16_UINT)
+ , MaterialPower(0.0f)
+ , VertexConstantBuffer(NULL)
+ , PixelConstantBuffer(NULL)
+ , PipelinesBuilt(0)
+ , DrawsMade(0)
+ , DrawsRefused(0)
+{
+ memset(StageStates, 0, sizeof(StageStates));
+ memset(Textures, 0, sizeof(Textures));
+ memset(Lights, 0, sizeof(Lights));
+ memset(MaterialAmbient, 0, sizeof(MaterialAmbient));
+ memset(MaterialDiffuse, 0, sizeof(MaterialDiffuse));
+ memset(MaterialSpecular, 0, sizeof(MaterialSpecular));
+ memset(MaterialEmissive, 0, sizeof(MaterialEmissive));
+
+ set_identity(World);
+ set_identity(View);
+ set_identity(Projection);
+
+ // The device's own defaults, so a stage nobody has written to is a stage that is off.
+ for (unsigned stage = 0; stage < DX11_BACKEND_TEXTURE_STAGES; ++stage) {
+ StageStates[stage][D3DTSS_COLOROP] = (stage == 0) ? D3DTOP_MODULATE : D3DTOP_DISABLE;
+ StageStates[stage][D3DTSS_ALPHAOP] = (stage == 0) ? D3DTOP_SELECTARG1 : D3DTOP_DISABLE;
+ StageStates[stage][D3DTSS_COLORARG1] = D3DTA_TEXTURE;
+ StageStates[stage][D3DTSS_COLORARG2] = D3DTA_CURRENT;
+ StageStates[stage][D3DTSS_ALPHAARG1] = D3DTA_TEXTURE;
+ StageStates[stage][D3DTSS_ALPHAARG2] = D3DTA_CURRENT;
+ StageStates[stage][D3DTSS_TEXCOORDINDEX] = stage;
+ }
+}
+
+DX11BackendClass::~DX11BackendClass()
+{
+ Shutdown();
+}
+
+bool DX11BackendClass::Initialise(DX11DeviceClass * device)
+{
+ Device = device;
+
+ D3D11_BUFFER_DESC description;
+ memset(&description, 0, sizeof(description));
+ description.ByteWidth = sizeof(VertexConstantBlock);
+ description.Usage = D3D11_USAGE_DYNAMIC;
+ description.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
+ description.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
+
+ if (FAILED(Device->Get_Device()->CreateBuffer(&description, NULL, &VertexConstantBuffer))) {
+ return false;
+ }
+
+ description.ByteWidth = sizeof(PixelConstantBlock);
+ return SUCCEEDED(Device->Get_Device()->CreateBuffer(&description, NULL, &PixelConstantBuffer));
+}
+
+void DX11BackendClass::Release_Cached()
+{
+ for (std::map<std::string, Pipeline>::iterator entry = Pipelines.begin();
+ entry != Pipelines.end(); ++entry) {
+ entry->second.VertexShader->Release();
+ entry->second.PixelShader->Release();
+ entry->second.Layout->Release();
+ }
+ Pipelines.clear();
+
+ for (std::map<std::string, ID3D11BlendState *>::iterator entry = BlendStates.begin();
+ entry != BlendStates.end(); ++entry) {
+ entry->second->Release();
+ }
+ BlendStates.clear();
+
+ for (std::map<std::string, ID3D11DepthStencilState *>::iterator entry
+ = DepthStencilStates.begin(); entry != DepthStencilStates.end(); ++entry) {
+ entry->second->Release();
+ }
+ DepthStencilStates.clear();
+
+ for (std::map<std::string, ID3D11RasterizerState *>::iterator entry = RasterizerStates.begin();
+ entry != RasterizerStates.end(); ++entry) {
+ entry->second->Release();
+ }
+ RasterizerStates.clear();
+
+ for (std::map<std::string, ID3D11SamplerState *>::iterator entry = SamplerStates.begin();
+ entry != SamplerStates.end(); ++entry) {
+ entry->second->Release();
+ }
+ SamplerStates.clear();
+}
+
+void DX11BackendClass::Shutdown()
+{
+ Release_Cached();
+
+ if (PixelConstantBuffer != NULL) {
+ PixelConstantBuffer->Release();
+ PixelConstantBuffer = NULL;
+ }
+ if (VertexConstantBuffer != NULL) {
+ VertexConstantBuffer->Release();
+ VertexConstantBuffer = NULL;
+ }
+ Device = NULL;
+}
+
+void DX11BackendClass::Set_Render_State(D3DRENDERSTATETYPE state, DWORD value)
+{
+ RenderStates.Set_Render_State(state, value);
+}
+
+void DX11BackendClass::Set_Texture_Stage_State(unsigned stage, D3DTEXTURESTAGESTATETYPE state,
+ DWORD value)
+{
+ if (stage < DX11_BACKEND_TEXTURE_STAGES && static_cast<unsigned>(state) < DX11_BACKEND_STAGE_STATES) {
+ StageStates[stage][state] = value;
+ }
+}
+
+void DX11BackendClass::Set_Sampler_State(unsigned sampler, D3DSAMPLERSTATETYPE state, DWORD value)
+{
+ if (sampler < DX11_BACKEND_TEXTURE_STAGES) {
+ Samplers[sampler].Set_Sampler_State(state, value);
+ }
+}
+
+void DX11BackendClass::Set_Texture(unsigned stage, ID3D11ShaderResourceView * texture)
+{
+ if (stage < DX11_BACKEND_TEXTURE_STAGES) {
+ Textures[stage] = texture;
+ }
+}
+
+void DX11BackendClass::Set_Vertex_Format(DWORD fvf)
+{
+ VertexFormat = fvf;
+}
+
+void DX11BackendClass::Set_Stream_Source(ID3D11Buffer * buffer, unsigned stride, unsigned offset)
+{
+ StreamBuffer = buffer;
+ StreamStride = stride;
+ StreamOffset = offset;
+}
+
+void DX11BackendClass::Set_Indices(ID3D11Buffer * buffer, DXGI_FORMAT format)
+{
+ IndexBuffer = buffer;
+ IndexFormat = format;
+}
+
+void DX11BackendClass::Set_Transform(D3DTRANSFORMSTATETYPE state, const float matrix[16])
+{
+ switch (state) {
+ case D3DTS_WORLD: memcpy(World, matrix, sizeof(World)); break;
+ case D3DTS_VIEW: memcpy(View, matrix, sizeof(View)); break;
+ case D3DTS_PROJECTION: memcpy(Projection, matrix, sizeof(Projection)); break;
+ default: break;
+ }
+}
+
+void DX11BackendClass::Set_Material(const float ambient[4], const float diffuse[4],
+ const float specular[4], const float emissive[4], float power)
+{
+ memcpy(MaterialAmbient, ambient, sizeof(MaterialAmbient));
+ memcpy(MaterialDiffuse, diffuse, sizeof(MaterialDiffuse));
+ memcpy(MaterialSpecular, specular, sizeof(MaterialSpecular));
+ memcpy(MaterialEmissive, emissive, sizeof(MaterialEmissive));
+ MaterialPower = power;
+}
+
+void DX11BackendClass::Set_Light(unsigned index, DWORD type, const float position[4],
+ const float direction[4], const float diffuse[4], const float specular[4],
+ const float attenuation[4], const float spot[4])
+{
+ if (index >= MAXIMUM_VERTEX_LIGHTS) {
+ return;
+ }
+
+ Light & light = Lights[index];
+ light.Enabled = true;
+ light.Type = type;
+ memcpy(light.Position, position, sizeof(light.Position));
+ memcpy(light.Direction, direction, sizeof(light.Direction));
+ memcpy(light.Diffuse, diffuse, sizeof(light.Diffuse));
+ memcpy(light.Specular, specular, sizeof(light.Specular));
+ memcpy(light.Attenuation, attenuation, sizeof(light.Attenuation));
+ memcpy(light.Spot, spot, sizeof(light.Spot));
+}
+
+void DX11BackendClass::Disable_Light(unsigned index)
+{
+ if (index < MAXIMUM_VERTEX_LIGHTS) {
+ Lights[index].Enabled = false;
+ }
+}
+
+void DX11BackendClass::Set_Viewport(unsigned x, unsigned y, unsigned width, unsigned height)
+{
+ D3D11_VIEWPORT viewport;
+ viewport.TopLeftX = static_cast<float>(x);
+ viewport.TopLeftY = static_cast<float>(y);
+ viewport.Width = static_cast<float>(width);
+ viewport.Height = static_cast<float>(height);
+ viewport.MinDepth = 0.0f;
+ viewport.MaxDepth = 1.0f;
+ Device->Get_Context()->RSSetViewports(1, &viewport);
+}
+
+void DX11BackendClass::Clear(bool colour, bool depth, const float colour_value[4])
+{
+ if (colour && Device->Get_Back_Buffer_View() != NULL) {
+ Device->Get_Context()->ClearRenderTargetView(Device->Get_Back_Buffer_View(), colour_value);
+ }
+ if (depth && Device->Get_Depth_Stencil_View() != NULL) {
+ Device->Get_Context()->ClearDepthStencilView(Device->Get_Depth_Stencil_View(),
+ D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
+ }
+}
+
+bool DX11BackendClass::Build_Combiner_Description(CombinerDescription & description) const
+{
+ memset(&description, 0, sizeof(description));
+
+ // The alpha test and the fog are pipeline state under D3D9 and shader instructions here, so
+ // they are read off the render states and handed to the generator as part of the program.
+ description.PixelPipeline.AlphaTestEnabled =
+ RenderStates.Get_Render_State(D3DRS_ALPHATESTENABLE) != FALSE;
+ description.PixelPipeline.AlphaFunction = RenderStates.Get_Render_State(D3DRS_ALPHAFUNC);
+ description.PixelPipeline.FogEnabled = RenderStates.Get_Render_State(D3DRS_FOGENABLE) != FALSE;
+
+ description.StageCount = 0;
+ for (unsigned stage = 0; stage < MAXIMUM_COMBINER_STAGES; ++stage) {
+ if (StageStates[stage][D3DTSS_COLOROP] == D3DTOP_DISABLE) {
+ break;
+ }
+
+ CombinerStage & target = description.Stages[stage];
+ target.ColourOperation = StageStates[stage][D3DTSS_COLOROP];
+ target.ColourArgument0 = StageStates[stage][D3DTSS_COLORARG0];
+ target.ColourArgument1 = StageStates[stage][D3DTSS_COLORARG1];
+ target.ColourArgument2 = StageStates[stage][D3DTSS_COLORARG2];
+ target.AlphaOperation = StageStates[stage][D3DTSS_ALPHAOP];
+ target.AlphaArgument0 = StageStates[stage][D3DTSS_ALPHAARG0];
+ target.AlphaArgument1 = StageStates[stage][D3DTSS_ALPHAARG1];
+ target.AlphaArgument2 = StageStates[stage][D3DTSS_ALPHAARG2];
+ target.TextureCoordinateIndex = StageStates[stage][D3DTSS_TEXCOORDINDEX];
+ target.TextureBound = Textures[stage] != NULL;
+ description.StageCount = stage + 1;
+ }
+ return description.StageCount > 0;
+}
+
+bool DX11BackendClass::Build_Vertex_Description(VertexPipelineDescription & description) const
+{
+ memset(&description, 0, sizeof(description));
+ description.FVF = VertexFormat;
+ description.LightingEnabled = RenderStates.Get_Render_State(D3DRS_LIGHTING) != FALSE;
+ description.SpecularEnabled = RenderStates.Get_Render_State(D3DRS_SPECULARENABLE) != FALSE;
+ description.ColourVertexEnabled = RenderStates.Get_Render_State(D3DRS_COLORVERTEX) != FALSE;
+ description.DiffuseMaterialSource = RenderStates.Get_Render_State(D3DRS_DIFFUSEMATERIALSOURCE);
+ description.AmbientMaterialSource = RenderStates.Get_Render_State(D3DRS_AMBIENTMATERIALSOURCE);
+ description.EmissiveMaterialSource = RenderStates.Get_Render_State(D3DRS_EMISSIVEMATERIALSOURCE);
+ description.SpecularMaterialSource = RenderStates.Get_Render_State(D3DRS_SPECULARMATERIALSOURCE);
+
+ // The lights have to be contiguous in the shader, so an enabled light after a disabled one
+ // moves down. Which register a light ends up in is the shader's business and the constants
+ // are packed to match below.
+ description.LightCount = 0;
+ for (unsigned index = 0; index < MAXIMUM_VERTEX_LIGHTS; ++index) {
+ if (Lights[index].Enabled) {
+ description.Lights[description.LightCount].Type = Lights[index].Type;
+ ++description.LightCount;
+ }
+ }
+
+ description.StageCount = 0;
+ for (unsigned stage = 0; stage < MAXIMUM_VERTEX_STAGES; ++stage) {
+ if (StageStates[stage][D3DTSS_COLOROP] == D3DTOP_DISABLE) {
+ break;
+ }
+ description.Stages[stage].TextureCoordinateIndex = StageStates[stage][D3DTSS_TEXCOORDINDEX];
+ description.Stages[stage].TextureTransformFlags =
+ StageStates[stage][D3DTSS_TEXTURETRANSFORMFLAGS];
+ description.StageCount = stage + 1;
+ }
+
+ description.FogEnabled = RenderStates.Get_Render_State(D3DRS_FOGENABLE) != FALSE;
+ description.FogVertexMode = RenderStates.Get_Render_State(D3DRS_FOGVERTEXMODE);
+ return true;
+}
+
+bool DX11BackendClass::Resolve(Pipeline & pipeline)
+{
+ VertexPipelineDescription vertex_description;
+ CombinerDescription combiner_description;
+ if (!Build_Vertex_Description(vertex_description)
+ || !Build_Combiner_Description(combiner_description)) {
+ return false;
+ }
+
+ char format[32];
+ snprintf(format, sizeof(format), "|%lu", VertexFormat);
+ const std::string key = VertexShader_Key(vertex_description)
+ + CombinerShader_Key(combiner_description) + format;
+
+ std::map<std::string, Pipeline>::const_iterator existing = Pipelines.find(key);
+ if (existing != Pipelines.end()) {
+ pipeline = existing->second;
+ return true;
+ }
+
+ D3DCompileFunction compiler = compiler_function();
+ if (compiler == NULL) {
+ return false;
+ }
+
+ std::string vertex_hlsl;
+ std::string pixel_hlsl;
+ if (!VertexShader_Generate(vertex_description, VERTEX_SHADER_TARGET_D3D11, vertex_hlsl)
+ || !CombinerShader_Generate(combiner_description, COMBINER_SHADER_TARGET_D3D11,
+ pixel_hlsl)) {
+ return false;
+ }
+
+ D3D11_INPUT_ELEMENT_DESC elements[MAXIMUM_LAYOUT_ELEMENTS];
+ unsigned element_count = 0;
+ unsigned stride = 0;
+ if (!DX11Layout_From_FVF(VertexFormat, elements, element_count, stride)) {
+ return false;
+ }
+
+ ID3DBlob * vertex_code = NULL;
+ ID3DBlob * pixel_code = NULL;
+ if (FAILED(compiler(vertex_hlsl.c_str(), vertex_hlsl.size(), "ffvertex", NULL, NULL,
+ ENTRY_POINT, VERTEX_PROFILE, 0, 0, &vertex_code, NULL))) {
+ return false;
+ }
+ if (FAILED(compiler(pixel_hlsl.c_str(), pixel_hlsl.size(), "ffshader", NULL, NULL,
+ ENTRY_POINT, PIXEL_PROFILE, 0, 0, &pixel_code, NULL))) {
+ vertex_code->Release();
+ return false;
+ }
+
+ Pipeline built;
+ built.VertexShader = NULL;
+ built.PixelShader = NULL;
+ built.Layout = NULL;
+
+ ID3D11Device * device = Device->Get_Device();
+ const bool created = SUCCEEDED(device->CreateVertexShader(vertex_code->GetBufferPointer(),
+ vertex_code->GetBufferSize(), NULL, &built.VertexShader))
+ && SUCCEEDED(device->CreatePixelShader(pixel_code->GetBufferPointer(),
+ pixel_code->GetBufferSize(), NULL, &built.PixelShader))
+ && SUCCEEDED(device->CreateInputLayout(elements, element_count,
+ vertex_code->GetBufferPointer(), vertex_code->GetBufferSize(), &built.Layout));
+
+ pixel_code->Release();
+ vertex_code->Release();
+
+ if (!created) {
+ if (built.Layout != NULL) {
+ built.Layout->Release();
+ }
+ if (built.PixelShader != NULL) {
+ built.PixelShader->Release();
+ }
+ if (built.VertexShader != NULL) {
+ built.VertexShader->Release();
+ }
+ return false;
+ }
+
+ Pipelines[key] = built;
+ ++PipelinesBuilt;
+ pipeline = built;
+ return true;
+}
+
+void DX11BackendClass::Upload_Constants()
+{
+ ID3D11DeviceContext * context = Device->Get_Context();
+
+ VertexConstantBlock vertex_block;
+ memset(&vertex_block, 0, sizeof(vertex_block));
+
+ float world_view[16];
+ multiply(World, View, world_view);
+ multiply(world_view, Projection, vertex_block.WorldViewProjection);
+ memcpy(vertex_block.WorldView, world_view, sizeof(world_view));
+ inverse_transpose(world_view, vertex_block.NormalTransform);
+ set_identity(vertex_block.TextureMatrix0);
+ set_identity(vertex_block.TextureMatrix1);
+
+ memcpy(vertex_block.MaterialAmbient, MaterialAmbient, sizeof(MaterialAmbient));
+ memcpy(vertex_block.MaterialDiffuse, MaterialDiffuse, sizeof(MaterialDiffuse));
+ memcpy(vertex_block.MaterialSpecular, MaterialSpecular, sizeof(MaterialSpecular));
+ memcpy(vertex_block.MaterialEmissive, MaterialEmissive, sizeof(MaterialEmissive));
+ vertex_block.MaterialPower[0] = MaterialPower;
+
+ const DWORD ambient = RenderStates.Get_Render_State(D3DRS_AMBIENT);
+ vertex_block.GlobalAmbient[0] = static_cast<float>((ambient >> 16) & 0xff) / 255.0f;
+ vertex_block.GlobalAmbient[1] = static_cast<float>((ambient >> 8) & 0xff) / 255.0f;
+ vertex_block.GlobalAmbient[2] = static_cast<float>(ambient & 0xff) / 255.0f;
+ vertex_block.GlobalAmbient[3] = static_cast<float>((ambient >> 24) & 0xff) / 255.0f;
+
+ // The fog start, end and density, in the order the generated shader reads them. D3D9 carries
+ // all three as floats inside a DWORD render state.
+ const DWORD fog_start = RenderStates.Get_Render_State(D3DRS_FOGSTART);
+ const DWORD fog_end = RenderStates.Get_Render_State(D3DRS_FOGEND);
+ const DWORD fog_density = RenderStates.Get_Render_State(D3DRS_FOGDENSITY);
+ memcpy(&vertex_block.FogParameters[0], &fog_start, sizeof(float));
+ memcpy(&vertex_block.FogParameters[1], &fog_end, sizeof(float));
+ memcpy(&vertex_block.FogParameters[2], &fog_density, sizeof(float));
+
+ // Packed the way the shader declares them, and only the enabled ones, in order: the shader was
+ // generated from the same walk.
+ unsigned slot = 0;
+ for (unsigned index = 0; index < MAXIMUM_VERTEX_LIGHTS; ++index) {
+ if (!Lights[index].Enabled) {
+ continue;
+ }
+ memcpy(vertex_block.LightFields[slot][0], Lights[index].Position, sizeof(float) * 4);
+ memcpy(vertex_block.LightFields[slot][1], Lights[index].Direction, sizeof(float) * 4);
+ memcpy(vertex_block.LightFields[slot][2], Lights[index].Diffuse, sizeof(float) * 4);
+ memcpy(vertex_block.LightFields[slot][3], Lights[index].Specular, sizeof(float) * 4);
+ memcpy(vertex_block.LightFields[slot][4], Lights[index].Attenuation, sizeof(float) * 4);
+ memcpy(vertex_block.LightFields[slot][5], Lights[index].Spot, sizeof(float) * 4);
+ ++slot;
+ }
+
+ D3D11_MAPPED_SUBRESOURCE mapped;
+ if (SUCCEEDED(context->Map(VertexConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped))) {
+ memcpy(mapped.pData, &vertex_block, sizeof(vertex_block));
+ context->Unmap(VertexConstantBuffer, 0);
+ }
+
+ PixelConstantBlock pixel_block;
+ memset(&pixel_block, 0, sizeof(pixel_block));
+ RenderStates.Get_Texture_Factor(pixel_block.TextureFactor);
+
+ const DWORD fog_colour = RenderStates.Get_Render_State(D3DRS_FOGCOLOR);
+ pixel_block.FogColour[0] = static_cast<float>((fog_colour >> 16) & 0xff) / 255.0f;
+ pixel_block.FogColour[1] = static_cast<float>((fog_colour >> 8) & 0xff) / 255.0f;
+ pixel_block.FogColour[2] = static_cast<float>(fog_colour & 0xff) / 255.0f;
+ pixel_block.FogColour[3] = static_cast<float>((fog_colour >> 24) & 0xff) / 255.0f;
+
+ // D3DRS_ALPHAREF is an eight bit value and the shader compares a float.
+ pixel_block.AlphaReference[0] =
+ static_cast<float>(RenderStates.Get_Render_State(D3DRS_ALPHAREF) & 0xff) / 255.0f;
+
+ if (SUCCEEDED(context->Map(PixelConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped))) {
+ memcpy(mapped.pData, &pixel_block, sizeof(pixel_block));
+ context->Unmap(PixelConstantBuffer, 0);
+ }
+}
+
+ID3D11BlendState * DX11BackendClass::Blend_State()
+{
+ D3D11_BLEND_DESC description;
+ RenderStates.Build_Blend_Description(description);
+
+ const std::string key(reinterpret_cast<const char *>(&description), sizeof(description));
+ std::map<std::string, ID3D11BlendState *>::const_iterator existing = BlendStates.find(key);
+ if (existing != BlendStates.end()) {
+ return existing->second;
+ }
+
+ ID3D11BlendState * state = NULL;
+ if (FAILED(Device->Get_Device()->CreateBlendState(&description, &state))) {
+ return NULL;
+ }
+ BlendStates[key] = state;
+ return state;
+}
+
+ID3D11DepthStencilState * DX11BackendClass::Depth_Stencil_State()
+{
+ D3D11_DEPTH_STENCIL_DESC description;
+ RenderStates.Build_Depth_Stencil_Description(description);
+
+ const std::string key(reinterpret_cast<const char *>(&description), sizeof(description));
+ std::map<std::string, ID3D11DepthStencilState *>::const_iterator existing
+ = DepthStencilStates.find(key);
+ if (existing != DepthStencilStates.end()) {
+ return existing->second;
+ }
+
+ ID3D11DepthStencilState * state = NULL;
+ if (FAILED(Device->Get_Device()->CreateDepthStencilState(&description, &state))) {
+ return NULL;
+ }
+ DepthStencilStates[key] = state;
+ return state;
+}
+
+ID3D11RasterizerState * DX11BackendClass::Rasterizer_State()
+{
+ D3D11_RASTERIZER_DESC description;
+ RenderStates.Build_Rasterizer_Description(description);
+
+ const std::string key(reinterpret_cast<const char *>(&description), sizeof(description));
+ std::map<std::string, ID3D11RasterizerState *>::const_iterator existing
+ = RasterizerStates.find(key);
+ if (existing != RasterizerStates.end()) {
+ return existing->second;
+ }
+
+ ID3D11RasterizerState * state = NULL;
+ if (FAILED(Device->Get_Device()->CreateRasterizerState(&description, &state))) {
+ return NULL;
+ }
+ RasterizerStates[key] = state;
+ return state;
+}
+
+ID3D11SamplerState * DX11BackendClass::Sampler_State(unsigned sampler)
+{
+ D3D11_SAMPLER_DESC description;
+ Samplers[sampler].Build_Sampler_Description(description);
+
+ const std::string key(reinterpret_cast<const char *>(&description), sizeof(description));
+ std::map<std::string, ID3D11SamplerState *>::const_iterator existing = SamplerStates.find(key);
+ if (existing != SamplerStates.end()) {
+ return existing->second;
+ }
+
+ ID3D11SamplerState * state = NULL;
+ if (FAILED(Device->Get_Device()->CreateSamplerState(&description, &state))) {
+ return NULL;
+ }
+ SamplerStates[key] = state;
+ return state;
+}
+
+void DX11BackendClass::Bind_State_Objects()
+{
+ ID3D11DeviceContext * context = Device->Get_Context();
+
+ context->OMSetBlendState(Blend_State(), NULL, 0xffffffff);
+ context->OMSetDepthStencilState(Depth_Stencil_State(), RenderStates.Get_Stencil_Reference());
+ context->RSSetState(Rasterizer_State());
+
+ ID3D11SamplerState * samplers[DX11_BACKEND_TEXTURE_STAGES];
+ for (unsigned sampler = 0; sampler < DX11_BACKEND_TEXTURE_STAGES; ++sampler) {
+ samplers[sampler] = Sampler_State(sampler);
+ }
+ context->PSSetSamplers(0, DX11_BACKEND_TEXTURE_STAGES, samplers);
+ context->PSSetShaderResources(0, DX11_BACKEND_TEXTURE_STAGES, Textures);
+}
+
+bool DX11BackendClass::Draw_Indexed_Triangles(unsigned index_count, unsigned start_index,
+ unsigned base_vertex)
+{
+ Pipeline pipeline;
+ if (StreamBuffer == NULL || IndexBuffer == NULL || !Resolve(pipeline)) {
+ ++DrawsRefused;
+ return false;
+ }
+
+ ID3D11DeviceContext * context = Device->Get_Context();
+ Upload_Constants();
+ Bind_State_Objects();
+
+ const UINT stride = StreamStride;
+ const UINT offset = StreamOffset;
+ context->IASetInputLayout(pipeline.Layout);
+ context->IASetVertexBuffers(0, 1, &StreamBuffer, &stride, &offset);
+ context->IASetIndexBuffer(IndexBuffer, IndexFormat, 0);
+ context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
+ context->VSSetShader(pipeline.VertexShader, NULL, 0);
+ context->VSSetConstantBuffers(0, 1, &VertexConstantBuffer);
+ context->PSSetShader(pipeline.PixelShader, NULL, 0);
+ context->PSSetConstantBuffers(0, 1, &PixelConstantBuffer);
+ context->DrawIndexed(index_count, start_index, base_vertex);
+
+ ++DrawsMade;
+ return true;
+}
+
+bool DX11BackendClass::Draw_Triangles(unsigned vertex_count, unsigned start_vertex)
+{
+ Pipeline pipeline;
+ if (StreamBuffer == NULL || !Resolve(pipeline)) {
+ ++DrawsRefused;
+ return false;
+ }
+
+ ID3D11DeviceContext * context = Device->Get_Context();
+ Upload_Constants();
+ Bind_State_Objects();
+
+ const UINT stride = StreamStride;
+ const UINT offset = StreamOffset;
+ context->IASetInputLayout(pipeline.Layout);
+ context->IASetVertexBuffers(0, 1, &StreamBuffer, &stride, &offset);
+ context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
+ context->VSSetShader(pipeline.VertexShader, NULL, 0);
+ context->VSSetConstantBuffers(0, 1, &VertexConstantBuffer);
+ context->PSSetShader(pipeline.PixelShader, NULL, 0);
+ context->PSSetConstantBuffers(0, 1, &PixelConstantBuffer);
+ context->Draw(vertex_count, start_vertex);
+
+ ++DrawsMade;
+ return true;
+}
+
+void DX11BackendClass::Statistics(unsigned & pipelines_built, unsigned long long & draws_made,
+ unsigned long long & draws_refused) const
+{
+ pipelines_built = PipelinesBuilt;
+ draws_made = DrawsMade;
+ draws_refused = DrawsRefused;
+}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h
new file mode 100644
index 000000000..fa1309df8
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h
@@ -0,0 +1,184 @@
+/*
+** 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 Direct3D 11 renderer, driven the way the engine drives a Direct3D 9 device.
+**
+** The engine sets one thing at a time and then draws: a render state, a texture stage state, a
+** texture, a transform, a stream, and eventually a DrawIndexedPrimitive. There are 236 places that
+** do it and 5600 calls between them, and rewriting those into something D3D11 shaped is not a
+** phase, it is a different program. So this takes the calls as they are and resolves them at the
+** moment of the draw, which is the only moment where everything needed to build a D3D11 pipeline is
+** known at once.
+**
+** Resolving means five things. The render states become the three state objects, the sampler
+** states become sampler objects, the texture stage states become a pixel shader that ffshader
+** generates, the lighting and transform states become a vertex shader that ffvertex generates, and
+** the flexible vertex format becomes an input layout. All five are cached on the description they
+** came from, because the engine sets the same handful of combinations over and over: -ffprobe
+** counted 42 distinct stage programs across four maps, and the state objects are fewer still.
+**
+** What this is not is a Direct3D 9 device. It answers no COM interface, it is not handed to
+** anything that expects one, and there is no D3D9 runtime underneath it: the calls have D3D9's
+** names because the engine's calls have D3D9's names, and that is where the resemblance stops.
+*/
+
+#ifndef DX11BACKEND_H
+#define DX11BACKEND_H
+
+#include "dx11device.h"
+#include "dx11state.h"
+#include "ffshader.h"
+#include "ffvertex.h"
+
+#include <d3d9.h>
+#include <map>
+#include <string>
+
+// The engine never binds more than two textures at once, which is what -ffprobe measured and what
+// ffshader will generate for. A third is a draw this refuses rather than draws wrongly.
+const unsigned DX11_BACKEND_TEXTURE_STAGES = 2;
+
+// D3DTSS_CONSTANT is the highest texture stage state at 32, so the block is indexed by the state
+// itself and has to reach one past it.
+const unsigned DX11_BACKEND_STAGE_STATES = 33;
+
+class DX11BackendClass
+{
+public:
+ DX11BackendClass();
+ ~DX11BackendClass();
+
+ // device is borrowed, not owned: whoever created it outlives this.
+ bool Initialise(DX11DeviceClass * device);
+ void Shutdown();
+
+ // The setters, named for the D3D9 calls the engine makes. None of them touches the device;
+ // they write into the shadow state that Draw resolves.
+ void Set_Render_State(D3DRENDERSTATETYPE state, DWORD value);
+ void Set_Texture_Stage_State(unsigned stage, D3DTEXTURESTAGESTATETYPE state, DWORD value);
+ void Set_Sampler_State(unsigned sampler, D3DSAMPLERSTATETYPE state, DWORD value);
+ void Set_Texture(unsigned stage, ID3D11ShaderResourceView * texture);
+ void Set_Vertex_Format(DWORD fvf);
+ void Set_Stream_Source(ID3D11Buffer * buffer, unsigned stride, unsigned offset);
+ void Set_Indices(ID3D11Buffer * buffer, DXGI_FORMAT format);
+
+ // The three transforms the generated vertex shader reads. D3D9 keeps world, view and
+ // projection apart and multiplies them itself; the shader wants the products, so they are
+ // multiplied here when one of them changes rather than once per draw.
+ void Set_Transform(D3DTRANSFORMSTATETYPE state, const float matrix[16]);
+
+ // Everything the fixed-function vertex pipeline needs that is not a render state: the material
+ // colours and the lights. A light set here is on; Disable_Light takes it off again.
+ void Set_Material(const float ambient[4], const float diffuse[4], const float specular[4],
+ const float emissive[4], float power);
+ void Set_Light(unsigned index, DWORD type, const float position[4], const float direction[4],
+ const float diffuse[4], const float specular[4], const float attenuation[4],
+ const float spot[4]);
+ void Disable_Light(unsigned index);
+
+ void Set_Viewport(unsigned x, unsigned y, unsigned width, unsigned height);
+ void Clear(bool colour, bool depth, const float colour_value[4]);
+
+ // The two draws. Both resolve the shadow state into a pipeline first, and both return false
+ // when some part of that state has no D3D11 answer, which leaves the draw undone rather than
+ // drawn wrongly.
+ bool Draw_Indexed_Triangles(unsigned index_count, unsigned start_index, unsigned base_vertex);
+ bool Draw_Triangles(unsigned vertex_count, unsigned start_vertex);
+
+ // How many pipelines were built and how many draws were refused, which is the same pair
+ // -ffshader reports and the same thing it is for: a backend that silently refuses half the
+ // draws looks like a renderer with a lot missing and no error anywhere.
+ void Statistics(unsigned & pipelines_built, unsigned long long & draws_made,
+ unsigned long long & draws_refused) const;
+
+private:
+ DX11BackendClass(const DX11BackendClass &);
+ DX11BackendClass & operator=(const DX11BackendClass &);
+
+ struct Pipeline
+ {
+ ID3D11VertexShader * VertexShader;
+ ID3D11PixelShader * PixelShader;
+ ID3D11InputLayout * Layout;
+ };
+
+ bool Resolve(Pipeline & pipeline);
+ bool Build_Vertex_Description(VertexPipelineDescription & description) const;
+ bool Build_Combiner_Description(CombinerDescription & description) const;
+ void Upload_Constants();
+ void Bind_State_Objects();
+ void Release_Cached();
+
+ ID3D11BlendState * Blend_State();
+ ID3D11DepthStencilState * Depth_Stencil_State();
+ ID3D11RasterizerState * Rasterizer_State();
+ ID3D11SamplerState * Sampler_State(unsigned sampler);
+
+ DX11DeviceClass * Device;
+
+ DX11StateBlockClass RenderStates;
+ DX11SamplerBlockClass Samplers[DX11_BACKEND_TEXTURE_STAGES];
+ DWORD StageStates[DX11_BACKEND_TEXTURE_STAGES][DX11_BACKEND_STAGE_STATES];
+ ID3D11ShaderResourceView * Textures[DX11_BACKEND_TEXTURE_STAGES];
+
+ DWORD VertexFormat;
+ ID3D11Buffer * StreamBuffer;
+ unsigned StreamStride;
+ unsigned StreamOffset;
+ ID3D11Buffer * IndexBuffer;
+ DXGI_FORMAT IndexFormat;
+
+ float World[16];
+ float View[16];
+ float Projection[16];
+
+ float MaterialAmbient[4];
+ float MaterialDiffuse[4];
+ float MaterialSpecular[4];
+ float MaterialEmissive[4];
+ float MaterialPower;
+
+ struct Light
+ {
+ bool Enabled;
+ DWORD Type;
+ float Position[4];
+ float Direction[4];
+ float Diffuse[4];
+ float Specular[4];
+ float Attenuation[4];
+ float Spot[4];
+ };
+ Light Lights[MAXIMUM_VERTEX_LIGHTS];
+
+ ID3D11Buffer * VertexConstantBuffer;
+ ID3D11Buffer * PixelConstantBuffer;
+
+ std::map<std::string, Pipeline> Pipelines;
+ std::map<std::string, ID3D11BlendState *> BlendStates;
+ std::map<std::string, ID3D11DepthStencilState *> DepthStencilStates;
+ std::map<std::string, ID3D11RasterizerState *> RasterizerStates;
+ std::map<std::string, ID3D11SamplerState *> SamplerStates;
+
+ unsigned PipelinesBuilt;
+ unsigned long long DrawsMade;
+ unsigned long long DrawsRefused;
+};
+
+#endif // DX11BACKEND_H
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11device.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11device.cpp
new file mode 100644
index 000000000..6a6b7475f
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11device.cpp
@@ -0,0 +1,247 @@
+/*
+** 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 "dx11device.h"
+
+// The back buffer is the same format the D3D9 device asks for, so a picture taken off one can be
+// compared against the other without a conversion standing between them.
+static const DXGI_FORMAT BACK_BUFFER_FORMAT = DXGI_FORMAT_B8G8R8A8_UNORM;
+
+// D24S8 is what the D3D9 device settles on, and the stencil half is not spare: the shadow volumes
+// are drawn with it.
+static const DXGI_FORMAT DEPTH_STENCIL_FORMAT = DXGI_FORMAT_D24_UNORM_S8_UINT;
+
+// Feature level 11_0 is the floor. Below it there are no compute shaders and no unordered access
+// views, which is most of what phase 2 is being done for, and a machine that cannot reach it can
+// still run the Direct3D 9 device.
+static const D3D_FEATURE_LEVEL REQUESTED_FEATURE_LEVELS[] = { D3D_FEATURE_LEVEL_11_0 };
+
+static const UINT SWAP_CHAIN_BUFFER_COUNT = 2;
+
+static void release_interface(IUnknown ** object)
+{
+ if (*object != NULL) {
+ (*object)->Release();
+ *object = NULL;
+ }
+}
+
+DX11DeviceClass::DX11DeviceClass()
+ : Device(NULL)
+ , Context(NULL)
+ , SwapChain(NULL)
+ , BackBufferView(NULL)
+ , DepthStencilView(NULL)
+ , DepthStencilTexture(NULL)
+ , FeatureLevel(D3D_FEATURE_LEVEL_11_0)
+ , Width(0)
+ , Height(0)
+ , Software(false)
+ , DebugLayerRequested(false)
+ , DebugLayerPresent(false)
+{
+}
+
+DX11DeviceClass::~DX11DeviceClass()
+{
+ Release();
+}
+
+bool DX11DeviceClass::Create(HWND window, unsigned width, unsigned height)
+{
+ return Create_Device(true, window, width, height);
+}
+
+bool DX11DeviceClass::Create_Offscreen()
+{
+ return Create_Device(false, NULL, 0, 0);
+}
+
+bool DX11DeviceClass::Create_Device(bool with_swap_chain, HWND window, unsigned width,
+ unsigned height)
+{
+ DXGI_SWAP_CHAIN_DESC swap_chain;
+ ZeroMemory(&swap_chain, sizeof(swap_chain));
+ swap_chain.BufferCount = SWAP_CHAIN_BUFFER_COUNT;
+ swap_chain.BufferDesc.Width = width;
+ swap_chain.BufferDesc.Height = height;
+ swap_chain.BufferDesc.Format = BACK_BUFFER_FORMAT;
+ swap_chain.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
+ swap_chain.OutputWindow = window;
+ swap_chain.SampleDesc.Count = 1;
+ swap_chain.SampleDesc.Quality = 0;
+
+ // The game asks for a windowed device and resizes the window itself for a borderless one, so
+ // DXGI is never asked to take the display mode. A real fullscreen mode is SetFullscreenState
+ // afterwards, which is a decision for whoever owns the window and not for this.
+ swap_chain.Windowed = TRUE;
+ swap_chain.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
+
+ // Hardware first, WARP second. WARP draws the same picture on a machine with no D3D11 driver,
+ // which is what makes the device creatable on a build agent as well as on this one.
+ const D3D_DRIVER_TYPE driver_types[] = { D3D_DRIVER_TYPE_HARDWARE, D3D_DRIVER_TYPE_WARP };
+ const unsigned driver_type_count = sizeof(driver_types)/sizeof(driver_types[0]);
+
+ // With the layer asked for, try it first and fall back to the same driver type without it. A
+ // machine without the graphics tools feature refuses the create outright, and a refusal there
+ // must not be a refusal to make a device at all.
+ const UINT flag_choices[] = { D3D11_CREATE_DEVICE_DEBUG, 0 };
+ const unsigned flag_start = DebugLayerRequested ? 0u : 1u;
+
+ const unsigned flag_choice_count = sizeof(flag_choices)/sizeof(flag_choices[0]);
+
+ for (unsigned index = 0; index < driver_type_count; ++index) {
+ for (unsigned flag_index = flag_start; flag_index < flag_choice_count; ++flag_index) {
+ const UINT flags = flag_choices[flag_index];
+ HRESULT result;
+ if (with_swap_chain) {
+ result = D3D11CreateDeviceAndSwapChain(NULL, driver_types[index], NULL, flags,
+ REQUESTED_FEATURE_LEVELS,
+ sizeof(REQUESTED_FEATURE_LEVELS)/sizeof(D3D_FEATURE_LEVEL),
+ D3D11_SDK_VERSION, &swap_chain, &SwapChain, &Device, &FeatureLevel, &Context);
+ }
+ else {
+ result = D3D11CreateDevice(NULL, driver_types[index], NULL, flags,
+ REQUESTED_FEATURE_LEVELS,
+ sizeof(REQUESTED_FEATURE_LEVELS)/sizeof(D3D_FEATURE_LEVEL),
+ D3D11_SDK_VERSION, &Device, &FeatureLevel, &Context);
+ }
+
+ if (FAILED(result)) {
+ continue;
+ }
+
+ Software = (driver_types[index] == D3D_DRIVER_TYPE_WARP);
+ DebugLayerPresent = (flags & D3D11_CREATE_DEVICE_DEBUG) != 0;
+ Width = width;
+ Height = height;
+ if (!with_swap_chain) {
+ return true;
+ }
+ if (Create_Views()) {
+ return true;
+ }
+ Release();
+ return false;
+ }
+ }
+
+ Release();
+ return false;
+}
+
+bool DX11DeviceClass::Create_Views()
+{
+ ID3D11Texture2D * back_buffer = NULL;
+ if (FAILED(SwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D),
+ reinterpret_cast<void **>(&back_buffer)))) {
+ return false;
+ }
+
+ const HRESULT view_result = Device->CreateRenderTargetView(back_buffer, NULL, &BackBufferView);
+ back_buffer->Release();
+ if (FAILED(view_result)) {
+ return false;
+ }
+
+ D3D11_TEXTURE2D_DESC depth;
+ ZeroMemory(&depth, sizeof(depth));
+ depth.Width = Width;
+ depth.Height = Height;
+ depth.MipLevels = 1;
+ depth.ArraySize = 1;
+ depth.Format = DEPTH_STENCIL_FORMAT;
+ depth.SampleDesc.Count = 1;
+ depth.Usage = D3D11_USAGE_DEFAULT;
+ depth.BindFlags = D3D11_BIND_DEPTH_STENCIL;
+
+ if (FAILED(Device->CreateTexture2D(&depth, NULL, &DepthStencilTexture))) {
+ return false;
+ }
+ if (FAILED(Device->CreateDepthStencilView(DepthStencilTexture, NULL, &DepthStencilView))) {
+ return false;
+ }
+
+ Context->OMSetRenderTargets(1, &BackBufferView, DepthStencilView);
+
+ D3D11_VIEWPORT viewport;
+ viewport.TopLeftX = 0.0f;
+ viewport.TopLeftY = 0.0f;
+ viewport.Width = static_cast<float>(Width);
+ viewport.Height = static_cast<float>(Height);
+ viewport.MinDepth = 0.0f;
+ viewport.MaxDepth = 1.0f;
+ Context->RSSetViewports(1, &viewport);
+ return true;
+}
+
+void DX11DeviceClass::Release_Views()
+{
+ if (Context != NULL) {
+ // ResizeBuffers refuses while anything still references a back buffer, and the context's
+ // own output merger binding counts as a reference.
+ ID3D11RenderTargetView * no_target = NULL;
+ Context->OMSetRenderTargets(1, &no_target, NULL);
+ }
+ release_interface(reinterpret_cast<IUnknown **>(&DepthStencilView));
+ release_interface(reinterpret_cast<IUnknown **>(&DepthStencilTexture));
+ release_interface(reinterpret_cast<IUnknown **>(&BackBufferView));
+}
+
+void DX11DeviceClass::Release()
+{
+ Release_Views();
+ release_interface(reinterpret_cast<IUnknown **>(&SwapChain));
+ release_interface(reinterpret_cast<IUnknown **>(&Context));
+ release_interface(reinterpret_cast<IUnknown **>(&Device));
+ Width = 0;
+ Height = 0;
+ Software = false;
+}
+
+bool DX11DeviceClass::Resize(unsigned width, unsigned height)
+{
+ Release_Views();
+ if (FAILED(SwapChain->ResizeBuffers(SWAP_CHAIN_BUFFER_COUNT, width, height,
+ BACK_BUFFER_FORMAT, 0))) {
+ return false;
+ }
+ Width = width;
+ Height = height;
+ return Create_Views();
+}
+
+void DX11DeviceClass::Clear(float red, float green, float blue, float alpha, bool clear_depth)
+{
+ const float colour[4] = { red, green, blue, alpha };
+ Context->ClearRenderTargetView(BackBufferView, colour);
+ if (clear_depth) {
+ Context->ClearDepthStencilView(DepthStencilView,
+ D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
+ }
+}
+
+bool DX11DeviceClass::Present(unsigned present_interval)
+{
+ return SUCCEEDED(SwapChain->Present(present_interval, 0));
+}
+
+HRESULT DX11DeviceClass::Device_Removed_Reason() const
+{
+ return Device->GetDeviceRemovedReason();
+}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11device.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11device.h
new file mode 100644
index 000000000..5d56ca761
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11device.h
@@ -0,0 +1,120 @@
+/*
+** 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 Direct3D 11 device, its swap chain and the two views that hang off it.
+**
+** This is the bottom of RENDERER-ROADMAP.md's phase 2 and it knows nothing about the game: a
+** device, a back buffer, a depth buffer, a clear and a present. Everything above it - the state
+** translation, the combiner programs -ffshader generates, the two .vso rewrites - is built on this
+** and can be written against a device that already exists rather than one being designed at the
+** same time.
+**
+** It creates on hardware and falls back to WARP, and it can be created with no window at all,
+** which is what lets a test run it: a device with no swap chain has no back buffer and cannot
+** present, and Create_Offscreen says so by refusing both.
+**
+** Nothing here is bound to D3D9's rules. A D3D11 device is not lost by an alt-tab, so there is no
+** TestCooperativeLevel and no Reset_Device; a resize is DXGI's ResizeBuffers and the views are
+** rebuilt around it. A device is removed rather than lost, which is a driver reset or a removed
+** adapter, and Device_Removed_Reason reports it.
+*/
+
+#ifndef DX11DEVICE_H
+#define DX11DEVICE_H
+
+#include <d3d11.h>
+
+class DX11DeviceClass
+{
+public:
+ DX11DeviceClass();
+ ~DX11DeviceClass();
+
+ // Ask for the validation layer on the next Create. It reports every misuse D3D11 otherwise
+ // answers by drawing nothing - a vertex buffer bound at the wrong stride, an input layout that
+ // does not match the shader's signature, a constant buffer too small for what the shader
+ // declares - and there is no other way to be told about any of them. It needs the graphics
+ // tools feature installed; without it the create is refused and this falls back to a device
+ // without it, so asking is always safe.
+ void Request_Debug_Layer() { DebugLayerRequested = true; }
+ bool Has_Debug_Layer() const { return DebugLayerPresent; }
+
+ // A device with a window: swap chain, back buffer, depth buffer, the lot. Width and height
+ // are the back buffer's, not the window's, so a borderless window and a fullscreen mode ask
+ // for the same thing.
+ bool Create(HWND window, unsigned width, unsigned height);
+
+ // A device with no window. It draws into whatever render target is given to it and cannot
+ // present. Tests use it, and so does anything that wants a device before there is a window.
+ bool Create_Offscreen();
+
+ void Release();
+
+ bool Is_Created() const { return Device != NULL; }
+ bool Has_Swap_Chain() const { return SwapChain != NULL; }
+
+ // True when the adapter was created by WARP rather than by a driver. The picture is the same
+ // and the speed is not, so anything measuring frame time has to know which one it got.
+ bool Is_Software() const { return Software; }
+
+ ID3D11Device * Get_Device() const { return Device; }
+ ID3D11DeviceContext * Get_Context() const { return Context; }
+ ID3D11RenderTargetView * Get_Back_Buffer_View() const { return BackBufferView; }
+ ID3D11DepthStencilView * Get_Depth_Stencil_View() const { return DepthStencilView; }
+
+ unsigned Get_Width() const { return Width; }
+ unsigned Get_Height() const { return Height; }
+
+ // Rebuilds the swap chain's buffers and the two views around them. DXGI refuses to resize
+ // while a view still holds a back buffer, so both views go first.
+ bool Resize(unsigned width, unsigned height);
+
+ void Clear(float red, float green, float blue, float alpha, bool clear_depth);
+
+ // present_interval is DXGI's sync interval: 0 for no wait, 1 for the next vertical blank.
+ bool Present(unsigned present_interval);
+
+ // D3DERR_DEVICELOST's replacement. S_OK while the device is usable; anything else is a driver
+ // reset or a removed adapter and the device has to be built again from scratch.
+ HRESULT Device_Removed_Reason() const;
+
+private:
+ DX11DeviceClass(const DX11DeviceClass &);
+ DX11DeviceClass & operator=(const DX11DeviceClass &);
+
+ bool Create_Device(bool with_swap_chain, HWND window, unsigned width, unsigned height);
+ bool Create_Views();
+ void Release_Views();
+
+ ID3D11Device * Device;
+ ID3D11DeviceContext * Context;
+ IDXGISwapChain * SwapChain;
+ ID3D11RenderTargetView * BackBufferView;
+ ID3D11DepthStencilView * DepthStencilView;
+ ID3D11Texture2D * DepthStencilTexture;
+
+ D3D_FEATURE_LEVEL FeatureLevel;
+ unsigned Width;
+ unsigned Height;
+ bool Software;
+ bool DebugLayerRequested;
+ bool DebugLayerPresent;
+};
+
+#endif // DX11DEVICE_H
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11layout.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11layout.cpp
new file mode 100644
index 000000000..cc174941e
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11layout.cpp
@@ -0,0 +1,121 @@
+/*
+** 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 "dx11layout.h"
+
+#include <string.h>
+
+// A D3DCOLOR is a packed BGRA byte quad, which is exactly what DXGI calls B8G8R8A8_UNORM. Handing
+// D3D11 R8G8B8A8 instead swaps red and blue in every vertex colour in the game, and the picture it
+// makes is plausible enough to argue about.
+static const DXGI_FORMAT VERTEX_COLOUR_FORMAT = DXGI_FORMAT_B8G8R8A8_UNORM;
+
+// The two bits per set that D3DFVF_TEXCOORDSIZE writes start here.
+static const unsigned TEXTURE_COORDINATE_SIZE_SHIFT = 16;
+static const DWORD TEXTURE_COORDINATE_SIZE_MASK = 0x03;
+
+static const DXGI_FORMAT FLOAT_FORMATS[] = {
+ DXGI_FORMAT_R32_FLOAT,
+ DXGI_FORMAT_R32G32_FLOAT,
+ DXGI_FORMAT_R32G32B32_FLOAT,
+ DXGI_FORMAT_R32G32B32A32_FLOAT
+};
+
+// D3D9 packs the size of coordinate set n into two bits, and the four codes are not in the order
+// anybody would guess: 0 means two floats, 1 means three, 2 means four and 3 means one.
+static unsigned texture_coordinate_float_count(DWORD fvf, unsigned set)
+{
+ const DWORD code = (fvf >> (TEXTURE_COORDINATE_SIZE_SHIFT + set * 2)) & TEXTURE_COORDINATE_SIZE_MASK;
+ switch (code) {
+ case 0: return 2;
+ case 1: return 3;
+ case 2: return 4;
+ default: return 1;
+ }
+}
+
+static void append_element(D3D11_INPUT_ELEMENT_DESC elements[MAXIMUM_LAYOUT_ELEMENTS],
+ unsigned & element_count, const char * semantic, unsigned semantic_index, DXGI_FORMAT format,
+ unsigned & offset, unsigned size)
+{
+ D3D11_INPUT_ELEMENT_DESC & element = elements[element_count];
+ element.SemanticName = semantic;
+ element.SemanticIndex = semantic_index;
+ element.Format = format;
+ element.InputSlot = 0;
+ element.AlignedByteOffset = offset;
+ element.InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
+ element.InstanceDataStepRate = 0;
+
+ ++element_count;
+ offset += size;
+}
+
+bool DX11Layout_From_FVF(DWORD fvf, D3D11_INPUT_ELEMENT_DESC elements[MAXIMUM_LAYOUT_ELEMENTS],
+ unsigned & element_count, unsigned & stride)
+{
+ memset(elements, 0, sizeof(D3D11_INPUT_ELEMENT_DESC) * MAXIMUM_LAYOUT_ELEMENTS);
+ element_count = 0;
+ stride = 0;
+
+ unsigned offset = 0;
+
+ const DWORD position = fvf & D3DFVF_POSITION_MASK;
+ if (position == D3DFVF_XYZ) {
+ append_element(elements, element_count, "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT,
+ offset, 12);
+ }
+ else if (position == D3DFVF_XYZRHW) {
+ // A pre-transformed vertex. The 2D passes use it and its w is already divided, so it
+ // keeps all four floats and the vertex shader passes it through untouched.
+ append_element(elements, element_count, "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT,
+ offset, 16);
+ }
+ else {
+ // Every other D3DFVF_POSITION_MASK value is a blend-weight form the engine never fills.
+ return false;
+ }
+
+ if ((fvf & D3DFVF_NORMAL) != 0) {
+ append_element(elements, element_count, "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT,
+ offset, 12);
+ }
+ if ((fvf & D3DFVF_PSIZE) != 0) {
+ append_element(elements, element_count, "PSIZE", 0, DXGI_FORMAT_R32_FLOAT, offset, 4);
+ }
+ if ((fvf & D3DFVF_DIFFUSE) != 0) {
+ append_element(elements, element_count, "COLOR", 0, VERTEX_COLOUR_FORMAT, offset, 4);
+ }
+ if ((fvf & D3DFVF_SPECULAR) != 0) {
+ append_element(elements, element_count, "COLOR", 1, VERTEX_COLOUR_FORMAT, offset, 4);
+ }
+
+ const unsigned set_count = (fvf & D3DFVF_TEXCOUNT_MASK) >> D3DFVF_TEXCOUNT_SHIFT;
+ if (set_count > MAXIMUM_TEXTURE_COORDINATE_SETS) {
+ return false;
+ }
+
+ for (unsigned set = 0; set < set_count; ++set) {
+ const unsigned float_count = texture_coordinate_float_count(fvf, set);
+ append_element(elements, element_count, "TEXCOORD", set,
+ FLOAT_FORMATS[float_count - 1], offset, float_count * 4);
+ }
+
+ stride = offset;
+ return true;
+}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11layout.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11layout.h
new file mode 100644
index 000000000..40401fb58
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11layout.h
@@ -0,0 +1,58 @@
+/*
+** 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/>.
+*/
+
+/*
+** A D3D9 flexible vertex format, read out as a D3D11 input layout.
+**
+** The vertex buffers the engine fills do not change in phase 2: the same bytes in the same order,
+** written by the same code, because every one of them is filled by hand through a struct in
+** dx8fvf.h and rewriting that is a rewrite of the mesh system. What changes is that D3D11 has no
+** idea what an FVF is. It wants the layout spelled out, one element per field, with a semantic, a
+** format and a byte offset, and it wants that description to have been validated against the
+** vertex shader that will read it.
+**
+** So this walks the FVF in the order D3D9 packs it - position, blend weights, normal, point size,
+** diffuse, specular, then the texture coordinates - and writes the elements out. The offsets it
+** produces are the offsets the structs in dx8fvf.h already have, which is the property worth
+** testing: get one wrong and every vertex is read at the wrong place with no error anywhere.
+**
+** The texture coordinate sizes are not all two floats. DX8_FVF_XYZNDUV1TG3 carries a two-float
+** set and three three-float ones for the tangent frame, and DX8_FVF_XYZNUV2DMAP has a one, a four
+** and a two. The D3DFVF_TEXCOORDSIZE bits say which, and reading them is not optional.
+*/
+
+#ifndef DX11LAYOUT_H
+#define DX11LAYOUT_H
+
+#include <d3d9.h>
+#include <d3d11.h>
+
+// D3D9 allows eight texture coordinate sets and the engine's widest format uses four.
+const unsigned MAXIMUM_TEXTURE_COORDINATE_SETS = 8;
+
+// Position, blend weights, normal, point size, diffuse, specular and the coordinate sets.
+const unsigned MAXIMUM_LAYOUT_ELEMENTS = 6 + MAXIMUM_TEXTURE_COORDINATE_SETS;
+
+// Fills elements with the layout the FVF describes and says how many it wrote; stride comes back
+// as the vertex size in bytes, which is what IASetVertexBuffers wants and what DX8Wrapper's own
+// Get_FVF_Vertex_Size has been working out from the same bits. A format naming no position, or
+// one whose coordinate sets run past the array, is refused rather than half described.
+bool DX11Layout_From_FVF(DWORD fvf, D3D11_INPUT_ELEMENT_DESC elements[MAXIMUM_LAYOUT_ELEMENTS],
+ unsigned & element_count, unsigned & stride);
+
+#endif // DX11LAYOUT_H
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11resource.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11resource.cpp
new file mode 100644
index 000000000..69d0ffe05
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11resource.cpp
@@ -0,0 +1,249 @@
+/*
+** 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 "dx11resource.h"
+
+#include <string.h>
+
+DXGI_FORMAT DX11Resource_Translate_Format(D3DFORMAT format)
+{
+ switch (format) {
+ // D3D9 names a colour most significant byte first and DXGI names it least significant first,
+ // so an A8R8G8B8 and a B8G8R8A8 are the same four bytes in the same order under two spellings.
+ case D3DFMT_A8R8G8B8: return DXGI_FORMAT_B8G8R8A8_UNORM;
+ case D3DFMT_X8R8G8B8: return DXGI_FORMAT_B8G8R8A8_UNORM;
+ case D3DFMT_R5G6B5: return DXGI_FORMAT_B5G6R5_UNORM;
+ case D3DFMT_A1R5G5B5: return DXGI_FORMAT_B5G5R5A1_UNORM;
+ case D3DFMT_X1R5G5B5: return DXGI_FORMAT_B5G5R5A1_UNORM;
+ case D3DFMT_A4R4G4B4: return DXGI_FORMAT_B4G4R4A4_UNORM;
+ case D3DFMT_A8: return DXGI_FORMAT_A8_UNORM;
+
+ // A luminance texture is one channel read into all three, which D3D11 has no format for. The
+ // channel survives as red and the spreading becomes a swizzle in whatever samples it.
+ case D3DFMT_L8: return DXGI_FORMAT_R8_UNORM;
+
+ // The block compressed formats are the same blocks under different names. DXT2 and DXT4 are
+ // DXT3 and DXT5 with the colour premultiplied by the alpha, which is a property of the data
+ // rather than of the format, so they share a DXGI name with the ones they premultiply.
+ case D3DFMT_DXT1: return DXGI_FORMAT_BC1_UNORM;
+ case D3DFMT_DXT2: return DXGI_FORMAT_BC2_UNORM;
+ case D3DFMT_DXT3: return DXGI_FORMAT_BC2_UNORM;
+ case D3DFMT_DXT4: return DXGI_FORMAT_BC3_UNORM;
+ case D3DFMT_DXT5: return DXGI_FORMAT_BC3_UNORM;
+
+ case D3DFMT_D16: return DXGI_FORMAT_D16_UNORM;
+ case D3DFMT_D24S8: return DXGI_FORMAT_D24_UNORM_S8_UINT;
+ case D3DFMT_D24X8: return DXGI_FORMAT_D24_UNORM_S8_UINT;
+ case D3DFMT_D32: return DXGI_FORMAT_D32_FLOAT;
+
+ // D3DFMT_P8 and D3DFMT_A8P8 are palettised, and D3D11 has no palette anywhere. A texture in
+ // one of these has to be expanded before it arrives, which is the loader's job, so saying so
+ // here is better than handing back a format that would draw the indices as grey.
+ default: return DXGI_FORMAT_UNKNOWN;
+ }
+}
+
+bool DX11Resource_Format_Needs_Swizzle(D3DFORMAT format)
+{
+ switch (format) {
+ // The X formats become formats with an alpha channel, and whatever is in those bits is now
+ // meaningful where D3D9 ignored it.
+ case D3DFMT_X8R8G8B8:
+ case D3DFMT_X1R5G5B5:
+ // A luminance channel arrives as red and has to be spread.
+ case D3DFMT_L8:
+ return true;
+ default:
+ return false;
+ }
+}
+
+bool DX11Resource_Translate_Usage(D3DPOOL pool, DWORD d3d9_usage, D3D11_USAGE & usage,
+ UINT & cpu_access_flags, UINT & bind_flags)
+{
+ usage = D3D11_USAGE_DEFAULT;
+ cpu_access_flags = 0;
+ bind_flags = 0;
+
+ if ((d3d9_usage & D3DUSAGE_RENDERTARGET) != 0) {
+ bind_flags |= D3D11_BIND_RENDER_TARGET;
+ }
+ if ((d3d9_usage & D3DUSAGE_DEPTHSTENCIL) != 0) {
+ bind_flags |= D3D11_BIND_DEPTH_STENCIL;
+ }
+
+ // A render target or a depth buffer is written by the device and cannot be anything but a
+ // default-usage resource, whatever pool D3D9 was asked for.
+ if (bind_flags != 0) {
+ return pool == D3DPOOL_DEFAULT;
+ }
+
+ if (pool == D3DPOOL_SYSTEMMEM) {
+ // System memory is where D3D9 puts a surface the CPU reads back out of, and D3D11's
+ // staging usage is the only one that can be both read and written by the CPU. It cannot
+ // be bound to the pipeline at all, which is the same restriction from the other side.
+ usage = D3D11_USAGE_STAGING;
+ cpu_access_flags = D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE;
+ return true;
+ }
+
+ if ((d3d9_usage & D3DUSAGE_DYNAMIC) != 0) {
+ usage = D3D11_USAGE_DYNAMIC;
+ cpu_access_flags = D3D11_CPU_ACCESS_WRITE;
+ return true;
+ }
+
+ // Everything else - the managed pool and the default pool without the dynamic bit - is a
+ // resource the CPU fills once and the device reads from then on.
+ return pool == D3DPOOL_MANAGED || pool == D3DPOOL_DEFAULT;
+}
+
+bool DX11Resource_Translate_Lock(DWORD lock_flags, D3D11_USAGE usage, D3D11_MAP & map_type)
+{
+ if ((lock_flags & D3DLOCK_DISCARD) != 0) {
+ // Throwing the contents away and writing the whole thing again is what the dynamic vertex
+ // buffers do every frame, and it is the only map a dynamic resource can take without
+ // waiting for the device to finish reading the old contents.
+ map_type = D3D11_MAP_WRITE_DISCARD;
+ return usage == D3D11_USAGE_DYNAMIC;
+ }
+
+ if ((lock_flags & D3DLOCK_NOOVERWRITE) != 0) {
+ map_type = D3D11_MAP_WRITE_NO_OVERWRITE;
+ return usage == D3D11_USAGE_DYNAMIC;
+ }
+
+ if ((lock_flags & D3DLOCK_READONLY) != 0) {
+ map_type = D3D11_MAP_READ;
+ return usage == D3D11_USAGE_STAGING;
+ }
+
+ // No flags at all. On a staging resource that is a read and a write, which is what the
+ // readback surfaces want; on a dynamic one there is nothing to read, so it is a discard.
+ if (usage == D3D11_USAGE_STAGING) {
+ map_type = D3D11_MAP_READ_WRITE;
+ return true;
+ }
+ if (usage == D3D11_USAGE_DYNAMIC) {
+ map_type = D3D11_MAP_WRITE_DISCARD;
+ return true;
+ }
+
+ // A default-usage resource cannot be mapped at all. D3D9 would have allowed the lock and
+ // stalled; refusing says so instead of hiding a stall.
+ map_type = D3D11_MAP_READ;
+ return false;
+}
+
+static bool create_buffer(ID3D11Device * device, unsigned byte_width, D3DPOOL pool,
+ DWORD d3d9_usage, const void * initial_data, UINT bind_flag, ID3D11Buffer ** buffer)
+{
+ *buffer = NULL;
+
+ D3D11_USAGE usage = D3D11_USAGE_DEFAULT;
+ UINT cpu_access_flags = 0;
+ UINT bind_flags = 0;
+ if (!DX11Resource_Translate_Usage(pool, d3d9_usage, usage, cpu_access_flags, bind_flags)) {
+ return false;
+ }
+
+ // A staging buffer is bound to nothing; anything else is bound as the kind of buffer it is.
+ D3D11_BUFFER_DESC description;
+ memset(&description, 0, sizeof(description));
+ description.ByteWidth = byte_width;
+ description.Usage = usage;
+ description.BindFlags = (usage == D3D11_USAGE_STAGING) ? 0 : bind_flag;
+ description.CPUAccessFlags = cpu_access_flags;
+
+ D3D11_SUBRESOURCE_DATA data;
+ memset(&data, 0, sizeof(data));
+ data.pSysMem = initial_data;
+
+ return SUCCEEDED(device->CreateBuffer(&description,
+ (initial_data != NULL) ? &data : NULL, buffer));
+}
+
+bool DX11Resource_Create_Vertex_Buffer(ID3D11Device * device, unsigned byte_width,
+ D3DPOOL pool, DWORD d3d9_usage, const void * initial_data, ID3D11Buffer ** buffer)
+{
+ return create_buffer(device, byte_width, pool, d3d9_usage, initial_data,
+ D3D11_BIND_VERTEX_BUFFER, buffer);
+}
+
+bool DX11Resource_Create_Index_Buffer(ID3D11Device * device, unsigned byte_width,
+ D3DPOOL pool, DWORD d3d9_usage, const void * initial_data, ID3D11Buffer ** buffer)
+{
+ return create_buffer(device, byte_width, pool, d3d9_usage, initial_data,
+ D3D11_BIND_INDEX_BUFFER, buffer);
+}
+
+bool DX11Resource_Create_Texture(ID3D11Device * device, unsigned width, unsigned height,
+ unsigned mip_levels, D3DFORMAT format, D3DPOOL pool, DWORD d3d9_usage,
+ ID3D11Texture2D ** texture, ID3D11ShaderResourceView ** view)
+{
+ *texture = NULL;
+ *view = NULL;
+
+ const DXGI_FORMAT dxgi_format = DX11Resource_Translate_Format(format);
+ if (dxgi_format == DXGI_FORMAT_UNKNOWN) {
+ return false;
+ }
+
+ D3D11_USAGE usage = D3D11_USAGE_DEFAULT;
+ UINT cpu_access_flags = 0;
+ UINT bind_flags = 0;
+ if (!DX11Resource_Translate_Usage(pool, d3d9_usage, usage, cpu_access_flags, bind_flags)) {
+ return false;
+ }
+
+ // Anything the device can read is bound as a shader resource as well as whatever else it is.
+ // A staging texture is bound to nothing and a depth buffer cannot be sampled through the same
+ // format it is written with, so neither gets the bit.
+ const bool sampleable = (usage != D3D11_USAGE_STAGING)
+ && ((bind_flags & D3D11_BIND_DEPTH_STENCIL) == 0);
+ if (sampleable) {
+ bind_flags |= D3D11_BIND_SHADER_RESOURCE;
+ }
+
+ D3D11_TEXTURE2D_DESC description;
+ memset(&description, 0, sizeof(description));
+ description.Width = width;
+ description.Height = height;
+ description.MipLevels = mip_levels;
+ description.ArraySize = 1;
+ description.Format = dxgi_format;
+ description.SampleDesc.Count = 1;
+ description.Usage = usage;
+ description.BindFlags = bind_flags;
+ description.CPUAccessFlags = cpu_access_flags;
+
+ if (FAILED(device->CreateTexture2D(&description, NULL, texture))) {
+ return false;
+ }
+
+ if (!sampleable) {
+ return true;
+ }
+
+ if (FAILED(device->CreateShaderResourceView(*texture, NULL, view))) {
+ (*texture)->Release();
+ *texture = NULL;
+ return false;
+ }
+ return true;
+}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11resource.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11resource.h
new file mode 100644
index 000000000..d31758dee
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11resource.h
@@ -0,0 +1,76 @@
+/*
+** 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 buffers and the textures, made the D3D11 way from the D3D9 arguments the engine passes.
+**
+** Three vocabularies have to be translated and none of them is a rename. A surface format is a
+** D3DFORMAT naming its channels most significant first and a DXGI_FORMAT naming them least
+** significant first, so the letters come out reversed and two of them have no counterpart at all.
+** A pool and a usage flag are one concept in D3D9 - where the memory lives and who writes it - and
+** in D3D11 they are a usage plus a CPU access mask plus a bind flag, all three of which have to
+** agree or the create is refused. And a lock flag is a map type, where D3D9's "no flags" means two
+** different things depending on where the resource lives.
+**
+** What is not translated is the bytes. Every vertex buffer in the engine is filled through a struct
+** in dx8fvf.h and every texture through the same loader, and none of that changes: dx11layout says
+** where the fields are and this says how the memory is asked for.
+*/
+
+#ifndef DX11RESOURCE_H
+#define DX11RESOURCE_H
+
+#include <d3d9.h>
+#include <d3d11.h>
+
+// DXGI_FORMAT_UNKNOWN comes back for a format with no D3D11 counterpart, which the caller has to
+// treat as a refusal: a texture created as UNKNOWN is not a texture. Two of the engine's formats
+// are in that class - the palettised ones, which D3D11 dropped outright.
+DXGI_FORMAT DX11Resource_Translate_Format(D3DFORMAT format);
+
+// True where the translation loses something the caller may care about. D3DFMT_X8R8G8B8 becomes a
+// format with an alpha channel it is meant to ignore, and D3DFMT_L8 becomes a single red channel
+// that a shader has to spread across three, which is a shader's job and not this one's.
+bool DX11Resource_Format_Needs_Swizzle(D3DFORMAT format);
+
+// How the resource is stored and who may write it. A pool and the usage bits go in; the usage, the
+// CPU access mask and the misc flags come out. Returns false for a combination D3D11 cannot
+// express, rather than picking the nearest one.
+bool DX11Resource_Translate_Usage(D3DPOOL pool, DWORD d3d9_usage, D3D11_USAGE & usage,
+ UINT & cpu_access_flags, UINT & bind_flags);
+
+// A D3DLOCK_* set, read as a map type. D3D9's zero means read and write where the resource can be
+// read and write only where it cannot, so the usage has to be known to answer.
+bool DX11Resource_Translate_Lock(DWORD lock_flags, D3D11_USAGE usage, D3D11_MAP & map_type);
+
+// The two buffer creates, which differ only in a bind flag. initial_data may be null for a buffer
+// that is filled later, and a buffer with no initial data cannot be immutable.
+bool DX11Resource_Create_Vertex_Buffer(ID3D11Device * device, unsigned byte_width,
+ D3DPOOL pool, DWORD d3d9_usage, const void * initial_data, ID3D11Buffer ** buffer);
+
+bool DX11Resource_Create_Index_Buffer(ID3D11Device * device, unsigned byte_width,
+ D3DPOOL pool, DWORD d3d9_usage, const void * initial_data, ID3D11Buffer ** buffer);
+
+// A texture and, unless it is a staging one, the shader resource view that reads it. D3D9 hands
+// out one object for both; D3D11 wants the view created alongside and bound separately, and a
+// texture without one cannot be sampled however correct its contents are.
+bool DX11Resource_Create_Texture(ID3D11Device * device, unsigned width, unsigned height,
+ unsigned mip_levels, D3DFORMAT format, D3DPOOL pool, DWORD d3d9_usage,
+ ID3D11Texture2D ** texture, ID3D11ShaderResourceView ** view);
+
+#endif // DX11RESOURCE_H
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp
new file mode 100644
index 000000000..3a12475e2
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp
@@ -0,0 +1,143 @@
+/*
+** 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 "dx11runtime.h"
+
+#include "dx11backend.h"
+#include "dx11device.h"
+
+static bool Requested = false;
+static bool Active = false;
+static DX11DeviceClass Device;
+static DX11BackendClass Backend;
+
+void Direct3D11_Enable(bool enabled)
+{
+ Requested = enabled;
+}
+
+bool Direct3D11_Is_Enabled()
+{
+ return Requested;
+}
+
+bool Direct3D11_Create(HWND window, unsigned width, unsigned height)
+{
+ if (!Requested || Active) {
+ return Active;
+ }
+
+ if (!Device.Create(window, width, height)) {
+ return false;
+ }
+ if (!Backend.Initialise(&Device)) {
+ Device.Release();
+ return false;
+ }
+
+ Active = true;
+ return true;
+}
+
+void Direct3D11_Release()
+{
+ if (!Active) {
+ return;
+ }
+ Backend.Shutdown();
+ Device.Release();
+ Active = false;
+}
+
+bool Direct3D11_Is_Active()
+{
+ return Active;
+}
+
+DX11DeviceClass * Direct3D11_Device()
+{
+ return Active ? &Device : NULL;
+}
+
+DX11BackendClass * Direct3D11_Backend()
+{
+ return Active ? &Backend : NULL;
+}
+
+void Direct3D11_Mirror_Render_State(unsigned state, unsigned value)
+{
+ if (Active) {
+ Backend.Set_Render_State(static_cast<D3DRENDERSTATETYPE>(state), value);
+ }
+}
+
+void Direct3D11_Mirror_Texture_Stage_State(unsigned stage, unsigned state, unsigned value)
+{
+ if (Active) {
+ Backend.Set_Texture_Stage_State(stage, static_cast<D3DTEXTURESTAGESTATETYPE>(state), value);
+ }
+}
+
+void Direct3D11_Mirror_Sampler_State(unsigned sampler, unsigned state, unsigned value)
+{
+ if (Active) {
+ Backend.Set_Sampler_State(sampler, static_cast<D3DSAMPLERSTATETYPE>(state), value);
+ }
+}
+
+void Direct3D11_Mirror_Transform(unsigned transform, const float matrix[16])
+{
+ if (Active) {
+ Backend.Set_Transform(static_cast<D3DTRANSFORMSTATETYPE>(transform), matrix);
+ }
+}
+
+void Direct3D11_Mirror_Material(const float ambient[4], const float diffuse[4],
+ const float specular[4], const float emissive[4], float power)
+{
+ if (Active) {
+ Backend.Set_Material(ambient, diffuse, specular, emissive, power);
+ }
+}
+
+void Direct3D11_Mirror_Light(unsigned index, unsigned type, const float position[4],
+ const float direction[4], const float diffuse[4], const float specular[4],
+ const float attenuation[4], const float spot[4])
+{
+ if (Active) {
+ Backend.Set_Light(index, type, position, direction, diffuse, specular, attenuation, spot);
+ }
+}
+
+void Direct3D11_Mirror_Light_Disabled(unsigned index)
+{
+ if (Active) {
+ Backend.Disable_Light(index);
+ }
+}
+
+void Direct3D11_Statistics(unsigned & pipelines_built, unsigned long long & draws_made,
+ unsigned long long & draws_refused)
+{
+ pipelines_built = 0;
+ draws_made = 0;
+ draws_refused = 0;
+ if (Active) {
+ Backend.Statistics(pipelines_built, draws_made, draws_refused);
+ }
+}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h
new file mode 100644
index 000000000..ddff4a9b4
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h
@@ -0,0 +1,83 @@
+/*
+** 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 one Direct3D 11 device and backend the process has, and the switch that asks for them.
+**
+** WW3D2 cannot see GlobalData, so -dx11 arrives the way -msaa and -ffshader do: pushed in from
+** W3DDisplay::init before the device is made. Asking for it is not the same as getting it - a
+** machine with no Direct3D 11 driver and no WARP has neither - so Is_Active answers what actually
+** happened rather than what was asked for, and everything that branches on the backend branches on
+** that.
+**
+** RENDERER-ROADMAP.md's phase 2 is not finished while this is here: the engine still reaches the
+** Direct3D 9 device directly from 236 places, and until those go through DX8Wrapper a -dx11 run
+** has a backend that only the wrapper's own state calls reach. Enable_Reports says how far that
+** has got on any given run rather than leaving it to be guessed.
+*/
+
+#ifndef DX11RUNTIME_H
+#define DX11RUNTIME_H
+
+#include <windows.h>
+
+class DX11BackendClass;
+class DX11DeviceClass;
+
+// Asked for on the command line, before any device exists.
+void Direct3D11_Enable(bool enabled);
+bool Direct3D11_Is_Enabled();
+
+// Built once the window and its size are known. False means the machine could not make one, and
+// the caller carries on with Direct3D 9 rather than failing to start.
+bool Direct3D11_Create(HWND window, unsigned width, unsigned height);
+void Direct3D11_Release();
+
+// True only between a successful Create and the Release that follows it.
+bool Direct3D11_Is_Active();
+
+DX11DeviceClass * Direct3D11_Device();
+DX11BackendClass * Direct3D11_Backend();
+
+// The state the wrapper is setting on the Direct3D 9 device, copied into the backend as it goes.
+// Cheap enough to be unconditional - a comparison against a bool and a return when there is no
+// backend - and it is what makes a -dx11 run's backend hold the same state the frame was drawn
+// with, which is the thing every later step is measured against. Declared here rather than on
+// DX11BackendClass so dx8wrapper.h does not have to include the D3D11 headers.
+void Direct3D11_Mirror_Render_State(unsigned state, unsigned value);
+void Direct3D11_Mirror_Texture_Stage_State(unsigned stage, unsigned state, unsigned value);
+void Direct3D11_Mirror_Sampler_State(unsigned sampler, unsigned state, unsigned value);
+
+// The rest of what the fixed-function vertex pipeline reads. The matrix is sixteen floats in the
+// order D3D9 stores them, which is by rows; the material is five colours and a power; a light is
+// the six four-float fields ffvertex declares, and a null one disables that index.
+void Direct3D11_Mirror_Transform(unsigned transform, const float matrix[16]);
+void Direct3D11_Mirror_Material(const float ambient[4], const float diffuse[4],
+ const float specular[4], const float emissive[4], float power);
+void Direct3D11_Mirror_Light(unsigned index, unsigned type, const float position[4],
+ const float direction[4], const float diffuse[4], const float specular[4],
+ const float attenuation[4], const float spot[4]);
+void Direct3D11_Mirror_Light_Disabled(unsigned index);
+
+// What the run did, for the log: how many pipelines were built and how many draws the backend
+// refused. A backend that refuses most of the draws looks like a renderer with a lot missing and
+// says nothing about it otherwise.
+void Direct3D11_Statistics(unsigned & pipelines_built, unsigned long long & draws_made,
+ unsigned long long & draws_refused);
+
+#endif // DX11RUNTIME_H
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11state.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11state.cpp
new file mode 100644
index 000000000..331b7efd1
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11state.cpp
@@ -0,0 +1,354 @@
+/*
+** 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 "dx11state.h"
+
+#include <string.h>
+
+// D3DCOLORWRITEENABLE_RED and its three neighbours are the same four bits D3D11 uses, in the same
+// order, so the mask carries across unchanged and only its width has to be trimmed.
+static const DWORD COLOUR_WRITE_MASK = 0x0f;
+
+// D3D9 measures the depth bias in units of the depth buffer's smallest representable value and
+// takes it as a float in a DWORD; D3D11 takes an integer count of those units. The engine only
+// ever sets small multiples, so the conversion is a rounded scale rather than a format change.
+static const float DEPTH_BIAS_UNIT_SCALE = 16777216.0f;
+
+D3D11_BLEND DX11State_Translate_Blend(DWORD d3d9_blend)
+{
+ switch (d3d9_blend) {
+ case D3DBLEND_ZERO: return D3D11_BLEND_ZERO;
+ case D3DBLEND_ONE: return D3D11_BLEND_ONE;
+ case D3DBLEND_SRCCOLOR: return D3D11_BLEND_SRC_COLOR;
+ case D3DBLEND_INVSRCCOLOR: return D3D11_BLEND_INV_SRC_COLOR;
+ case D3DBLEND_SRCALPHA: return D3D11_BLEND_SRC_ALPHA;
+ case D3DBLEND_INVSRCALPHA: return D3D11_BLEND_INV_SRC_ALPHA;
+ case D3DBLEND_DESTALPHA: return D3D11_BLEND_DEST_ALPHA;
+ case D3DBLEND_INVDESTALPHA: return D3D11_BLEND_INV_DEST_ALPHA;
+ case D3DBLEND_DESTCOLOR: return D3D11_BLEND_DEST_COLOR;
+ case D3DBLEND_INVDESTCOLOR: return D3D11_BLEND_INV_DEST_COLOR;
+ case D3DBLEND_SRCALPHASAT: return D3D11_BLEND_SRC_ALPHA_SAT;
+ case D3DBLEND_BLENDFACTOR: return D3D11_BLEND_BLEND_FACTOR;
+ case D3DBLEND_INVBLENDFACTOR: return D3D11_BLEND_INV_BLEND_FACTOR;
+ default: return D3D11_BLEND_ONE;
+ }
+}
+
+D3D11_BLEND_OP DX11State_Translate_Blend_Operation(DWORD d3d9_operation)
+{
+ switch (d3d9_operation) {
+ case D3DBLENDOP_ADD: return D3D11_BLEND_OP_ADD;
+ case D3DBLENDOP_SUBTRACT: return D3D11_BLEND_OP_SUBTRACT;
+ case D3DBLENDOP_REVSUBTRACT: return D3D11_BLEND_OP_REV_SUBTRACT;
+ case D3DBLENDOP_MIN: return D3D11_BLEND_OP_MIN;
+ case D3DBLENDOP_MAX: return D3D11_BLEND_OP_MAX;
+ default: return D3D11_BLEND_OP_ADD;
+ }
+}
+
+D3D11_COMPARISON_FUNC DX11State_Translate_Comparison(DWORD d3d9_comparison)
+{
+ switch (d3d9_comparison) {
+ case D3DCMP_NEVER: return D3D11_COMPARISON_NEVER;
+ case D3DCMP_LESS: return D3D11_COMPARISON_LESS;
+ case D3DCMP_EQUAL: return D3D11_COMPARISON_EQUAL;
+ case D3DCMP_LESSEQUAL: return D3D11_COMPARISON_LESS_EQUAL;
+ case D3DCMP_GREATER: return D3D11_COMPARISON_GREATER;
+ case D3DCMP_NOTEQUAL: return D3D11_COMPARISON_NOT_EQUAL;
+ case D3DCMP_GREATEREQUAL: return D3D11_COMPARISON_GREATER_EQUAL;
+ case D3DCMP_ALWAYS: return D3D11_COMPARISON_ALWAYS;
+ default: return D3D11_COMPARISON_LESS_EQUAL;
+ }
+}
+
+D3D11_STENCIL_OP DX11State_Translate_Stencil_Operation(DWORD d3d9_operation)
+{
+ switch (d3d9_operation) {
+ case D3DSTENCILOP_KEEP: return D3D11_STENCIL_OP_KEEP;
+ case D3DSTENCILOP_ZERO: return D3D11_STENCIL_OP_ZERO;
+ case D3DSTENCILOP_REPLACE: return D3D11_STENCIL_OP_REPLACE;
+ case D3DSTENCILOP_INCRSAT: return D3D11_STENCIL_OP_INCR_SAT;
+ case D3DSTENCILOP_DECRSAT: return D3D11_STENCIL_OP_DECR_SAT;
+ case D3DSTENCILOP_INVERT: return D3D11_STENCIL_OP_INVERT;
+ case D3DSTENCILOP_INCR: return D3D11_STENCIL_OP_INCR;
+ case D3DSTENCILOP_DECR: return D3D11_STENCIL_OP_DECR;
+ default: return D3D11_STENCIL_OP_KEEP;
+ }
+}
+
+D3D11_CULL_MODE DX11State_Translate_Cull_Mode(DWORD d3d9_cull_mode)
+{
+ // Both APIs call a clockwise triangle the front one by default, so the winding needs no
+ // flipping and D3D11_RASTERIZER_DESC::FrontCounterClockwise stays false. D3D9 names the side
+ // it throws away and D3D11 names it the other way round, which is the whole difference.
+ switch (d3d9_cull_mode) {
+ case D3DCULL_NONE: return D3D11_CULL_NONE;
+ case D3DCULL_CW: return D3D11_CULL_FRONT;
+ case D3DCULL_CCW: return D3D11_CULL_BACK;
+ default: return D3D11_CULL_BACK;
+ }
+}
+
+D3D11_FILL_MODE DX11State_Translate_Fill_Mode(DWORD d3d9_fill_mode)
+{
+ // D3D9's D3DFILL_POINT has no D3D11 equivalent. Nothing in the engine sets it - the point
+ // sprites go through D3DRS_POINTSPRITEENABLE, not through the fill mode - so it draws solid.
+ switch (d3d9_fill_mode) {
+ case D3DFILL_WIREFRAME: return D3D11_FILL_WIREFRAME;
+ default: return D3D11_FILL_SOLID;
+ }
+}
+
+DX11StateBlockClass::DX11StateBlockClass()
+{
+ Reset_To_Defaults();
+}
+
+void DX11StateBlockClass::Reset_To_Defaults()
+{
+ memset(RenderStates, 0, sizeof(RenderStates));
+
+ RenderStates[D3DRS_ZENABLE] = D3DZB_TRUE;
+ RenderStates[D3DRS_ZWRITEENABLE] = TRUE;
+ RenderStates[D3DRS_ZFUNC] = D3DCMP_LESSEQUAL;
+ RenderStates[D3DRS_FILLMODE] = D3DFILL_SOLID;
+ RenderStates[D3DRS_CULLMODE] = D3DCULL_CCW;
+ RenderStates[D3DRS_ALPHABLENDENABLE] = FALSE;
+ RenderStates[D3DRS_SRCBLEND] = D3DBLEND_ONE;
+ RenderStates[D3DRS_DESTBLEND] = D3DBLEND_ZERO;
+ RenderStates[D3DRS_BLENDOP] = D3DBLENDOP_ADD;
+ RenderStates[D3DRS_COLORWRITEENABLE] = COLOUR_WRITE_MASK;
+ RenderStates[D3DRS_ALPHATESTENABLE] = FALSE;
+ RenderStates[D3DRS_ALPHAFUNC] = D3DCMP_ALWAYS;
+ RenderStates[D3DRS_ALPHAREF] = 0;
+ RenderStates[D3DRS_STENCILENABLE] = FALSE;
+ RenderStates[D3DRS_STENCILFUNC] = D3DCMP_ALWAYS;
+ RenderStates[D3DRS_STENCILFAIL] = D3DSTENCILOP_KEEP;
+ RenderStates[D3DRS_STENCILZFAIL] = D3DSTENCILOP_KEEP;
+ RenderStates[D3DRS_STENCILPASS] = D3DSTENCILOP_KEEP;
+ RenderStates[D3DRS_STENCILREF] = 0;
+ RenderStates[D3DRS_STENCILMASK] = 0xffffffff;
+ RenderStates[D3DRS_STENCILWRITEMASK] = 0xffffffff;
+ RenderStates[D3DRS_TEXTUREFACTOR] = 0xffffffff;
+ RenderStates[D3DRS_CLIPPING] = TRUE;
+ RenderStates[D3DRS_MULTISAMPLEANTIALIAS] = TRUE;
+}
+
+void DX11StateBlockClass::Set_Render_State(D3DRENDERSTATETYPE state, DWORD value)
+{
+ if (static_cast<unsigned>(state) < RENDER_STATE_COUNT) {
+ RenderStates[state] = value;
+ }
+}
+
+DWORD DX11StateBlockClass::Get_Render_State(D3DRENDERSTATETYPE state) const
+{
+ if (static_cast<unsigned>(state) < RENDER_STATE_COUNT) {
+ return RenderStates[state];
+ }
+ return 0;
+}
+
+void DX11StateBlockClass::Build_Blend_Description(D3D11_BLEND_DESC & description) const
+{
+ memset(&description, 0, sizeof(description));
+
+ // One render target and no independent blending: the engine has never drawn into more than one
+ // at a time, and every multi-pass effect it has is a second draw rather than a second target.
+ description.AlphaToCoverageEnable = FALSE;
+ description.IndependentBlendEnable = FALSE;
+
+ D3D11_RENDER_TARGET_BLEND_DESC & target = description.RenderTarget[0];
+ target.BlendEnable = (RenderStates[D3DRS_ALPHABLENDENABLE] != FALSE) ? TRUE : FALSE;
+ target.SrcBlend = DX11State_Translate_Blend(RenderStates[D3DRS_SRCBLEND]);
+ target.DestBlend = DX11State_Translate_Blend(RenderStates[D3DRS_DESTBLEND]);
+ target.BlendOp = DX11State_Translate_Blend_Operation(RenderStates[D3DRS_BLENDOP]);
+
+ // D3D9 blends the alpha channel with the colour terms unless D3DRS_SEPARATEALPHABLENDENABLE
+ // says otherwise, and nothing in the engine sets that, so the alpha terms are the colour ones.
+ target.SrcBlendAlpha = target.SrcBlend;
+ target.DestBlendAlpha = target.DestBlend;
+ target.BlendOpAlpha = target.BlendOp;
+
+ target.RenderTargetWriteMask =
+ static_cast<UINT8>(RenderStates[D3DRS_COLORWRITEENABLE] & COLOUR_WRITE_MASK);
+}
+
+void DX11StateBlockClass::Build_Depth_Stencil_Description(D3D11_DEPTH_STENCIL_DESC & description) const
+{
+ memset(&description, 0, sizeof(description));
+
+ description.DepthEnable = (RenderStates[D3DRS_ZENABLE] != D3DZB_FALSE) ? TRUE : FALSE;
+ description.DepthWriteMask = (RenderStates[D3DRS_ZWRITEENABLE] != FALSE)
+ ? D3D11_DEPTH_WRITE_MASK_ALL : D3D11_DEPTH_WRITE_MASK_ZERO;
+ description.DepthFunc = DX11State_Translate_Comparison(RenderStates[D3DRS_ZFUNC]);
+
+ description.StencilEnable = (RenderStates[D3DRS_STENCILENABLE] != FALSE) ? TRUE : FALSE;
+ description.StencilReadMask = static_cast<UINT8>(RenderStates[D3DRS_STENCILMASK]);
+ description.StencilWriteMask = static_cast<UINT8>(RenderStates[D3DRS_STENCILWRITEMASK]);
+
+ // D3D9 has one set of stencil operations and applies it to whichever side survived the cull;
+ // D3D11 always has two. Both sides get the same operations, which is what the two-sided
+ // stencil render states would be for and the engine sets none of them.
+ D3D11_DEPTH_STENCILOP_DESC face;
+ face.StencilFailOp = DX11State_Translate_Stencil_Operation(RenderStates[D3DRS_STENCILFAIL]);
+ face.StencilDepthFailOp = DX11State_Translate_Stencil_Operation(RenderStates[D3DRS_STENCILZFAIL]);
+ face.StencilPassOp = DX11State_Translate_Stencil_Operation(RenderStates[D3DRS_STENCILPASS]);
+ face.StencilFunc = DX11State_Translate_Comparison(RenderStates[D3DRS_STENCILFUNC]);
+ description.FrontFace = face;
+ description.BackFace = face;
+}
+
+void DX11StateBlockClass::Build_Rasterizer_Description(D3D11_RASTERIZER_DESC & description) const
+{
+ memset(&description, 0, sizeof(description));
+
+ description.FillMode = DX11State_Translate_Fill_Mode(RenderStates[D3DRS_FILLMODE]);
+ description.CullMode = DX11State_Translate_Cull_Mode(RenderStates[D3DRS_CULLMODE]);
+ description.FrontCounterClockwise = FALSE;
+
+ float depth_bias = 0.0f;
+ memcpy(&depth_bias, &RenderStates[D3DRS_DEPTHBIAS], sizeof(depth_bias));
+ description.DepthBias = static_cast<INT>(depth_bias * DEPTH_BIAS_UNIT_SCALE);
+
+ float slope_bias = 0.0f;
+ memcpy(&slope_bias, &RenderStates[D3DRS_SLOPESCALEDEPTHBIAS], sizeof(slope_bias));
+ description.SlopeScaledDepthBias = slope_bias;
+
+ description.DepthClipEnable = (RenderStates[D3DRS_CLIPPING] != FALSE) ? TRUE : FALSE;
+ description.ScissorEnable = FALSE;
+ description.MultisampleEnable = (RenderStates[D3DRS_MULTISAMPLEANTIALIAS] != FALSE) ? TRUE : FALSE;
+ description.AntialiasedLineEnable =
+ (RenderStates[D3DRS_ANTIALIASEDLINEENABLE] != FALSE) ? TRUE : FALSE;
+}
+
+D3D11_TEXTURE_ADDRESS_MODE DX11State_Translate_Address_Mode(DWORD d3d9_address_mode)
+{
+ switch (d3d9_address_mode) {
+ case D3DTADDRESS_WRAP: return D3D11_TEXTURE_ADDRESS_WRAP;
+ case D3DTADDRESS_MIRROR: return D3D11_TEXTURE_ADDRESS_MIRROR;
+ case D3DTADDRESS_CLAMP: return D3D11_TEXTURE_ADDRESS_CLAMP;
+ case D3DTADDRESS_BORDER: return D3D11_TEXTURE_ADDRESS_BORDER;
+ case D3DTADDRESS_MIRRORONCE: return D3D11_TEXTURE_ADDRESS_MIRROR_ONCE;
+ default: return D3D11_TEXTURE_ADDRESS_WRAP;
+ }
+}
+
+D3D11_FILTER DX11State_Translate_Filter(DWORD minification, DWORD magnification, DWORD mip)
+{
+ // One anisotropic filter makes the sampler anisotropic whatever the other two say, which is
+ // what the device does with the same three states.
+ if (minification == D3DTEXF_ANISOTROPIC || magnification == D3DTEXF_ANISOTROPIC) {
+ return D3D11_FILTER_ANISOTROPIC;
+ }
+
+ // D3D11_FILTER is three bits in one number: bit 4 for the minification, bit 2 for the
+ // magnification, bit 0 for the mip, each set when that filter is linear. Writing it this way
+ // rather than as eight named constants is what keeps the three D3D9 states visible.
+ const bool minify_linear = (minification == D3DTEXF_LINEAR);
+ const bool magnify_linear = (magnification == D3DTEXF_LINEAR);
+ const bool mip_linear = (mip == D3DTEXF_LINEAR);
+
+ unsigned bits = 0;
+ if (minify_linear) {
+ bits |= 0x10;
+ }
+ if (magnify_linear) {
+ bits |= 0x04;
+ }
+ if (mip_linear) {
+ bits |= 0x01;
+ }
+ return static_cast<D3D11_FILTER>(bits);
+}
+
+DX11SamplerBlockClass::DX11SamplerBlockClass()
+{
+ Reset_To_Defaults();
+}
+
+void DX11SamplerBlockClass::Reset_To_Defaults()
+{
+ memset(SamplerStates, 0, sizeof(SamplerStates));
+
+ SamplerStates[D3DSAMP_ADDRESSU] = D3DTADDRESS_WRAP;
+ SamplerStates[D3DSAMP_ADDRESSV] = D3DTADDRESS_WRAP;
+ SamplerStates[D3DSAMP_ADDRESSW] = D3DTADDRESS_WRAP;
+ SamplerStates[D3DSAMP_MAGFILTER] = D3DTEXF_POINT;
+ SamplerStates[D3DSAMP_MINFILTER] = D3DTEXF_POINT;
+ SamplerStates[D3DSAMP_MIPFILTER] = D3DTEXF_NONE;
+ SamplerStates[D3DSAMP_MAXANISOTROPY] = 1;
+}
+
+void DX11SamplerBlockClass::Set_Sampler_State(D3DSAMPLERSTATETYPE state, DWORD value)
+{
+ if (static_cast<unsigned>(state) < SAMPLER_STATE_COUNT) {
+ SamplerStates[state] = value;
+ }
+}
+
+DWORD DX11SamplerBlockClass::Get_Sampler_State(D3DSAMPLERSTATETYPE state) const
+{
+ if (static_cast<unsigned>(state) < SAMPLER_STATE_COUNT) {
+ return SamplerStates[state];
+ }
+ return 0;
+}
+
+void DX11SamplerBlockClass::Build_Sampler_Description(D3D11_SAMPLER_DESC & description) const
+{
+ memset(&description, 0, sizeof(description));
+
+ description.Filter = DX11State_Translate_Filter(SamplerStates[D3DSAMP_MINFILTER],
+ SamplerStates[D3DSAMP_MAGFILTER], SamplerStates[D3DSAMP_MIPFILTER]);
+ description.AddressU = DX11State_Translate_Address_Mode(SamplerStates[D3DSAMP_ADDRESSU]);
+ description.AddressV = DX11State_Translate_Address_Mode(SamplerStates[D3DSAMP_ADDRESSV]);
+ description.AddressW = DX11State_Translate_Address_Mode(SamplerStates[D3DSAMP_ADDRESSW]);
+
+ // D3D9 takes the bias as a float in a DWORD.
+ memcpy(&description.MipLODBias, &SamplerStates[D3DSAMP_MIPMAPLODBIAS],
+ sizeof(description.MipLODBias));
+
+ description.MaxAnisotropy = static_cast<UINT>(SamplerStates[D3DSAMP_MAXANISOTROPY]);
+ description.ComparisonFunc = D3D11_COMPARISON_NEVER;
+
+ // D3DSAMP_MAXMIPLEVEL is the most detailed level the sampler may use, which is D3D11's minimum
+ // LOD. There is no D3D9 state for the other end, so it stays open.
+ description.MinLOD = static_cast<float>(SamplerStates[D3DSAMP_MAXMIPLEVEL]);
+ description.MaxLOD = D3D11_FLOAT32_MAX;
+
+ const DWORD border = SamplerStates[D3DSAMP_BORDERCOLOR];
+ description.BorderColor[0] = static_cast<float>((border >> 16) & 0xff) / 255.0f;
+ description.BorderColor[1] = static_cast<float>((border >> 8) & 0xff) / 255.0f;
+ description.BorderColor[2] = static_cast<float>(border & 0xff) / 255.0f;
+ description.BorderColor[3] = static_cast<float>((border >> 24) & 0xff) / 255.0f;
+}
+
+UINT DX11StateBlockClass::Get_Stencil_Reference() const
+{
+ return static_cast<UINT>(RenderStates[D3DRS_STENCILREF]);
+}
+
+void DX11StateBlockClass::Get_Texture_Factor(float factor[4]) const
+{
+ const DWORD packed = RenderStates[D3DRS_TEXTUREFACTOR];
+ factor[0] = static_cast<float>((packed >> 16) & 0xff) / 255.0f;
+ factor[1] = static_cast<float>((packed >> 8) & 0xff) / 255.0f;
+ factor[2] = static_cast<float>(packed & 0xff) / 255.0f;
+ factor[3] = static_cast<float>((packed >> 24) & 0xff) / 255.0f;
+}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11state.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11state.h
new file mode 100644
index 000000000..8751678e9
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11state.h
@@ -0,0 +1,113 @@
+/*
+** 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/>.
+*/
+
+/*
+** Direct3D 9 render states, turned into the three Direct3D 11 state objects.
+**
+** D3D9 sets one state at a time and the device sorts it out; D3D11 has no such thing. It takes a
+** blend state, a depth stencil state and a rasteriser state, each an immutable object created up
+** front from a descriptor, and a draw binds all three. So the wrapper keeps every render state
+** the engine sets in a block of its own and builds the descriptors from it when something is about
+** to be drawn.
+**
+** Three groups of D3D9 state have no D3D11 object to go into and are not this file's business.
+** The alpha test and the fog are gone from the pipeline entirely and become shader instructions,
+** which is why -ffshader's generator has to grow them. Lighting, the material sources and the
+** vertex blend are the fixed-function vertex pipeline, which becomes a vertex shader. And
+** D3DRS_TEXTUREFACTOR and D3DRS_STENCILREF are not descriptor fields at all: they are values
+** passed at bind time, so they are read off the block rather than built into an object.
+**
+** This deliberately holds no device. It is a translation from one set of numbers to another and it
+** is tested as one, which is the only way this many enumerations get checked at all.
+*/
+
+#ifndef DX11STATE_H
+#define DX11STATE_H
+
+#include <d3d9.h>
+#include <d3d11.h>
+
+// The engine sets more render states than D3D11 has anywhere to put, and the highest of them is
+// well under this. Indexing the block by the D3DRENDERSTATETYPE itself keeps the setter free of a
+// switch that would have to name every state twice.
+const unsigned RENDER_STATE_COUNT = 256;
+
+class DX11StateBlockClass
+{
+public:
+ DX11StateBlockClass();
+
+ // Every state the D3D9 device would have started with, so a block that is never written to
+ // describes the same pipeline the D3D9 device describes on the frame it is created.
+ void Reset_To_Defaults();
+
+ void Set_Render_State(D3DRENDERSTATETYPE state, DWORD value);
+ DWORD Get_Render_State(D3DRENDERSTATETYPE state) const;
+
+ void Build_Blend_Description(D3D11_BLEND_DESC & description) const;
+ void Build_Depth_Stencil_Description(D3D11_DEPTH_STENCIL_DESC & description) const;
+ void Build_Rasterizer_Description(D3D11_RASTERIZER_DESC & description) const;
+
+ // Not descriptor fields: the stencil reference is an argument to OMSetDepthStencilState and
+ // the texture factor is a shader constant, so both come off the block at bind time.
+ UINT Get_Stencil_Reference() const;
+ void Get_Texture_Factor(float factor[4]) const;
+
+private:
+ DWORD RenderStates[RENDER_STATE_COUNT];
+};
+
+// D3D9 sets a sampler one state at a time the way it sets a render state; D3D11 wants a sampler
+// state object built from a descriptor. The engine sets seven of the fourteen, and the three
+// filters are one field in D3D11 rather than three, so the combination has to be worked out rather
+// than copied across.
+const unsigned SAMPLER_STATE_COUNT = 16;
+
+class DX11SamplerBlockClass
+{
+public:
+ DX11SamplerBlockClass();
+
+ void Reset_To_Defaults();
+
+ void Set_Sampler_State(D3DSAMPLERSTATETYPE state, DWORD value);
+ DWORD Get_Sampler_State(D3DSAMPLERSTATETYPE state) const;
+
+ void Build_Sampler_Description(D3D11_SAMPLER_DESC & description) const;
+
+private:
+ DWORD SamplerStates[SAMPLER_STATE_COUNT];
+};
+
+// D3D9's three filter states become one D3D11_FILTER. Anisotropic on either the minification or
+// the magnification filter makes the whole thing anisotropic, which is what the device does; every
+// other combination is a bit each for minify, magnify and mip.
+D3D11_FILTER DX11State_Translate_Filter(DWORD minification, DWORD magnification, DWORD mip);
+D3D11_TEXTURE_ADDRESS_MODE DX11State_Translate_Address_Mode(DWORD d3d9_address_mode);
+
+// The individual translations, exposed because each one is a table a test can walk end to end.
+// An unrecognised value returns the D3D11 default rather than refusing: a render state the engine
+// never sets to that value cannot be proved either way, and a default draws something.
+D3D11_BLEND DX11State_Translate_Blend(DWORD d3d9_blend);
+D3D11_BLEND_OP DX11State_Translate_Blend_Operation(DWORD d3d9_operation);
+D3D11_COMPARISON_FUNC DX11State_Translate_Comparison(DWORD d3d9_comparison);
+D3D11_STENCIL_OP DX11State_Translate_Stencil_Operation(DWORD d3d9_operation);
+D3D11_CULL_MODE DX11State_Translate_Cull_Mode(DWORD d3d9_cull_mode);
+D3D11_FILL_MODE DX11State_Translate_Fill_Mode(DWORD d3d9_fill_mode);
+
+#endif // DX11STATE_H
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11twin.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11twin.cpp
new file mode 100644
index 000000000..0bfd2d60f
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11twin.cpp
@@ -0,0 +1,95 @@
+/*
+** 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 "dx11twin.h"
+
+#include "dx11device.h"
+#include "dx11resource.h"
+#include "dx11runtime.h"
+
+#include <d3d11.h>
+
+// The pool and usage the twin asks dx11resource for. Managed with no usage bits is a
+// default-usage buffer the CPU never maps, which is what UpdateSubresource wants; the engine's own
+// D3DUSAGE_DYNAMIC is a D3D9 memory-placement choice and does not have to be repeated here.
+static const D3DPOOL TWIN_POOL = D3DPOOL_MANAGED;
+static const DWORD TWIN_USAGE = 0;
+
+DX11BufferTwinClass::DX11BufferTwinClass(unsigned char * mirror, unsigned byte_count,
+ ID3D11Buffer * buffer)
+ :
+ Mirror_Bytes(mirror),
+ Byte_Total(byte_count),
+ D3D11Buffer(buffer)
+{
+}
+
+DX11BufferTwinClass::~DX11BufferTwinClass()
+{
+ delete [] Mirror_Bytes;
+ D3D11Buffer->Release();
+}
+
+void DX11BufferTwinClass::Upload(unsigned byte_offset, unsigned byte_count)
+{
+ if (byte_count == 0) {
+ byte_count = Byte_Total - byte_offset;
+ }
+ if (byte_count == 0) {
+ return;
+ }
+
+ D3D11_BOX box;
+ box.left = byte_offset;
+ box.right = byte_offset + byte_count;
+ box.top = 0;
+ box.bottom = 1;
+ box.front = 0;
+ box.back = 1;
+
+ Direct3D11_Device()->Get_Context()->UpdateSubresource(D3D11Buffer, 0, &box,
+ Mirror_Bytes + byte_offset, 0, 0);
+}
+
+static DX11BufferTwinClass * create(unsigned byte_count, bool index_buffer)
+{
+ if (!Direct3D11_Is_Active()) {
+ return NULL;
+ }
+
+ ID3D11Device * device = Direct3D11_Device()->Get_Device();
+ ID3D11Buffer * buffer = NULL;
+ const bool made = index_buffer
+ ? DX11Resource_Create_Index_Buffer(device, byte_count, TWIN_POOL, TWIN_USAGE, NULL, &buffer)
+ : DX11Resource_Create_Vertex_Buffer(device, byte_count, TWIN_POOL, TWIN_USAGE, NULL, &buffer);
+ if (!made) {
+ return NULL;
+ }
+
+ return new DX11BufferTwinClass(new unsigned char[byte_count], byte_count, buffer);
+}
+
+DX11BufferTwinClass * DX11Twin_Create_Vertex_Buffer(unsigned byte_count)
+{
+ return create(byte_count, false);
+}
+
+DX11BufferTwinClass * DX11Twin_Create_Index_Buffer(unsigned byte_count)
+{
+ return create(byte_count, true);
+}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11twin.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11twin.h
new file mode 100644
index 000000000..c1a513115
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11twin.h
@@ -0,0 +1,67 @@
+/*
+** 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 Direct3D 11 copy of a vertex or index buffer, and the heap block both copies are written
+** through.
+**
+** A D3D9 buffer is created write-only, so nothing can read back what the engine put in it and there
+** is no way to build the D3D11 copy after the fact. The twin solves that by moving the write: when
+** one exists, a lock hands out the twin's own heap block rather than the D3D9 pointer, and the
+** unlock writes that range into both buffers. The D3D9 side is byte for byte what it was without
+** the twin, so a -dx11 run draws the same frame it would have drawn; the difference is that the
+** D3D11 buffer now holds the same bytes and a draw can go through the backend.
+**
+** Twins exist only while Direct3D11_Is_Active, so the factory answers null on an ordinary run and
+** every caller carries the null through to the old path.
+*/
+
+#ifndef DX11TWIN_H
+#define DX11TWIN_H
+
+struct ID3D11Buffer;
+
+class DX11BufferTwinClass
+{
+public:
+ DX11BufferTwinClass(unsigned char * mirror, unsigned byte_count, ID3D11Buffer * buffer);
+ ~DX11BufferTwinClass();
+
+ // The block a lock hands out. Offsets into it are byte offsets into the buffer.
+ unsigned char * Mirror() const { return Mirror_Bytes; }
+ unsigned Byte_Count() const { return Byte_Total; }
+ ID3D11Buffer * Buffer() const { return D3D11Buffer; }
+
+ // Copy one range of the mirror into the D3D11 buffer. A count of zero means to the end, which
+ // is what D3D9's own lock means by it.
+ void Upload(unsigned byte_offset, unsigned byte_count);
+
+private:
+ DX11BufferTwinClass(const DX11BufferTwinClass &);
+ DX11BufferTwinClass & operator=(const DX11BufferTwinClass &);
+
+ unsigned char * Mirror_Bytes;
+ unsigned Byte_Total;
+ ID3D11Buffer * D3D11Buffer;
+};
+
+// Null unless there is a live D3D11 device and it took the buffer.
+DX11BufferTwinClass * DX11Twin_Create_Vertex_Buffer(unsigned byte_count);
+DX11BufferTwinClass * DX11Twin_Create_Index_Buffer(unsigned byte_count);
+
+#endif // DX11TWIN_H
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp
index 828c84060..dac95a184 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp
@@ -73,6 +73,8 @@
#include <stdio.h>
#include "d3dx9runtime.h"
#include "ffprobe.h"
+#include "ffshadercache.h"
+#include "dx11runtime.h"
#include "pot.h"
#include "wwprofile.h"
#include "ffactory.h"
@@ -455,8 +457,11 @@ bool DX8Wrapper::Init(void * hwnd, bool lite)
void DX8Wrapper::Shutdown(void)
{
- // Before the device goes, because the inventory is read off it.
+ // Before the device goes: the inventory is read off it, and the device owns every shader the
+ // combiner cache compiled.
FixedFunctionProbe_Dump("ffprobe.txt");
+ CombinerShaderCache_Release();
+ Direct3D11_Release();
if (D3DDevice) {
@@ -842,6 +847,10 @@ void DX8Wrapper::Release_Device(void)
{
if (D3DDevice) {
+ // The device made every shader in the combiner cache and outliving it is not something they
+ // can do. Nothing recompiles them: the next draw asks the cache again and it is empty.
+ CombinerShaderCache_Release();
+
if (_RTTDepthBuffer) { _RTTDepthBuffer->Release(); _RTTDepthBuffer = NULL; }
for (int a=0;a<MAX_TEXTURE_STAGES;++a)
@@ -1270,6 +1279,17 @@ bool DX8Wrapper::Set_Render_Device(int dev, int width, int height, int bits, int
WWDEBUG_SAY(("Reset/Create_Device done, reset_device=%d, restore_assets=%d\n", reset_device, restore_assets));
+ // -dx11 builds the Direct3D 11 device beside the Direct3D 9 one rather than instead of it.
+ // Phase 2 of RENDERER-ROADMAP.md is not finished: 236 places still call the D3D9 device
+ // directly, so taking it away would be a black screen rather than a second backend. What this
+ // gets is a device and a backend that the wrapper's own state calls reach, and a count at
+ // shutdown of how much of the frame that turned out to be.
+ if (Direct3D11_Is_Enabled() && !Direct3D11_Is_Active()) {
+ const bool created = Direct3D11_Create((HWND)_Hwnd,
+ _PresentParameters.BackBufferWidth, _PresentParameters.BackBufferHeight);
+ WWDEBUG_SAY(("-dx11: Direct3D 11 device %s\n", created ? "created" : "refused"));
+ }
+
return ret;
}
@@ -2243,6 +2263,70 @@ void DX8Wrapper::Draw_Sorting_IB_VB(
//
// ----------------------------------------------------------------------------
+// The constant register the generated shader reads D3DRS_TEXTUREFACTOR out of. The generator
+// writes register(c0) into the HLSL, so the two have to agree and nothing else may use it while a
+// generated shader is bound.
+static const UINT COMBINER_TEXTURE_FACTOR_REGISTER = 0;
+
+// -ffshader only: puts a generated pixel shader in place of the texture stage combiners for the
+// length of one draw call, and takes it off again however the draw ends.
+//
+// Bound and unbound around each draw rather than left in place, because the next draw may be one
+// the generator refuses and a shader left bound would take that draw over without saying so. A
+// draw that brought its own pixel shader - the six W3DShaderManager builds - is left alone: those
+// are already programmable and are not what this replaces.
+class CombinerShaderBinding
+{
+public:
+ explicit CombinerShaderBinding(IDirect3DDevice9 * device)
+ : Device(device), Bound(false)
+ {
+ if (!CombinerShaders_Are_Enabled() || Device == NULL) {
+ return;
+ }
+
+ IDirect3DPixelShader9 * existing = NULL;
+ Device->GetPixelShader(&existing);
+ if (existing != NULL) {
+ existing->Release();
+ return;
+ }
+
+ CombinerDescription description;
+ CombinerShaderCache_Read_Device(Device, description);
+ IDirect3DPixelShader9 * generated = CombinerShaderCache_Get(Device, description);
+ if (generated == NULL) {
+ return;
+ }
+
+ DWORD texture_factor = 0;
+ Device->GetRenderState(D3DRS_TEXTUREFACTOR, &texture_factor);
+ const float factor[4] = {
+ ((texture_factor >> 16) & 0xff) / 255.0f,
+ ((texture_factor >> 8) & 0xff) / 255.0f,
+ ( texture_factor & 0xff) / 255.0f,
+ ((texture_factor >> 24) & 0xff) / 255.0f
+ };
+ Device->SetPixelShaderConstantF(COMBINER_TEXTURE_FACTOR_REGISTER, factor, 1);
+ Device->SetPixelShader(generated);
+ Bound = true;
+ }
+
+ ~CombinerShaderBinding()
+ {
+ if (Bound) {
+ Device->SetPixelShader(NULL);
+ }
+ }
+
+private:
+ CombinerShaderBinding(const CombinerShaderBinding &);
+ CombinerShaderBinding & operator=(const CombinerShaderBinding &);
+
+ IDirect3DDevice9 * Device;
+ bool Bound;
+};
+
void DX8Wrapper::Draw(
unsigned primitive_type,
unsigned short start_index,
@@ -2264,6 +2348,10 @@ void DX8Wrapper::Draw(
FixedFunctionProbe_Record(D3DDevice);
}
+ // -ffshader only. Binds the generated shader for this one draw and takes it off again on every
+ // path out, including the early return below and Draw_Sorting_IB_VB's own draws.
+ CombinerShaderBinding combiner_shader(D3DDevice);
+
// Debug feature to disable triangle drawing...
if (!_Is_Triangle_Draw_Enabled()) return;
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.h
index a01e1d256..5b3c397f0 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.h
@@ -59,6 +59,7 @@
#include "vector4.h"
#include "cpudetect.h"
#include "dx8caps.h"
+#include "dx11runtime.h"
#include "texture.h"
#include "dx8vertexbuffer.h"
@@ -830,6 +831,7 @@ WWINLINE void DX8Wrapper::_Set_DX8_Transform(D3DTRANSFORMSTATETYPE transform,con
SNAPSHOT_SAY(("DX8 - SetTransform %d [%f,%f,%f,%f][%f,%f,%f,%f][%f,%f,%f,%f][%f,%f,%f,%f]\n",transform,m[0][0],m[0][1],m[0][2],m[0][3],m[1][0],m[1][1],m[1][2],m[1][3],m[2][0],m[2][1],m[2][2],m[2][3],m[3][0],m[3][1],m[3][2],m[3][3]));
DX8_RECORD_MATRIX_CHANGE();
DX8CALL(SetTransform(transform,(D3DMATRIX*)&m));
+ Direct3D11_Mirror_Transform(transform, (const float*)&DX8Transforms[transform]);
}
}
@@ -846,6 +848,7 @@ WWINLINE void DX8Wrapper::_Set_DX8_Transform(D3DTRANSFORMSTATETYPE transform,con
SNAPSHOT_SAY(("DX8 - SetTransform %d [%f,%f,%f,%f][%f,%f,%f,%f][%f,%f,%f,%f]\n",transform,m[0][0],m[0][1],m[0][2],m[0][3],m[1][0],m[1][1],m[1][2],m[1][3],m[2][0],m[2][1],m[2][2],m[2][3]));
DX8_RECORD_MATRIX_CHANGE();
DX8CALL(SetTransform(transform,(D3DMATRIX*)&m));
+ Direct3D11_Mirror_Transform(transform, (const float*)&DX8Transforms[transform]);
}
}
@@ -911,6 +914,11 @@ WWINLINE void DX8Wrapper::Set_DX8_Material(const D3DMATERIAL9* mat)
WWASSERT(mat);
SNAPSHOT_SAY(("DX8 - SetMaterial\n"));
DX8CALL(SetMaterial(mat));
+
+ // D3DCOLORVALUE is four floats in red, green, blue, alpha order, which is the order the
+ // generated shader reads them, so each one goes across as it stands.
+ Direct3D11_Mirror_Material((const float*)&mat->Ambient, (const float*)&mat->Diffuse,
+ (const float*)&mat->Specular, (const float*)&mat->Emissive, mat->Power);
}
WWINLINE void DX8Wrapper::Set_DX8_Light(int index, D3DLIGHT9* light)
@@ -921,11 +929,24 @@ WWINLINE void DX8Wrapper::Set_DX8_Light(int index, D3DLIGHT9* light)
DX8CALL(LightEnable(index,TRUE));
CurrentDX8LightEnables[index]=true;
SNAPSHOT_SAY(("DX8 - SetLight %d\n",index));
+
+ // D3DLIGHT9 keeps the position and the direction as three floats each and the attenuation
+ // and the cone as loose scalars; ffvertex reads six four-float fields, so they are packed
+ // here rather than in the backend, which never sees a D3DLIGHT9.
+ const float position[4] = { light->Position.x, light->Position.y, light->Position.z, 1.0f };
+ const float direction[4] = { light->Direction.x, light->Direction.y, light->Direction.z, 0.0f };
+ const float attenuation[4] = { light->Attenuation0, light->Attenuation1,
+ light->Attenuation2, light->Range };
+ const float spot[4] = { cosf(light->Theta * 0.5f), cosf(light->Phi * 0.5f),
+ light->Falloff, 0.0f };
+ Direct3D11_Mirror_Light(index, light->Type, position, direction,
+ (const float*)&light->Diffuse, (const float*)&light->Specular, attenuation, spot);
}
else if (CurrentDX8LightEnables[index]) {
DX8_RECORD_LIGHT_CHANGE();
CurrentDX8LightEnables[index]=false;
DX8CALL(LightEnable(index,FALSE));
+ Direct3D11_Mirror_Light_Disabled(index);
SNAPSHOT_SAY(("DX8 - DisableLight %d\n",index));
}
}
@@ -947,6 +968,7 @@ WWINLINE void DX8Wrapper::Set_DX8_Render_State(D3DRENDERSTATETYPE state, unsigne
RenderStates[state]=value;
DX8CALL(SetRenderState( state, value ));
+ Direct3D11_Mirror_Render_State(state, value);
DX8_RECORD_RENDER_STATE_CHANGE();
}
@@ -977,6 +999,7 @@ WWINLINE void DX8Wrapper::Set_DX8_Texture_Stage_State(unsigned stage, D3DTEXTURE
TextureStageStates[stage][(unsigned int)state]=value;
DX8CALL(SetTextureStageState( stage, state, value ));
+ Direct3D11_Mirror_Texture_Stage_State(stage, state, value);
DX8_RECORD_TEXTURE_STAGE_STATE_CHANGE();
}
@@ -1004,6 +1027,7 @@ WWINLINE void DX8Wrapper::Set_DX8_Texture_Stage_State(unsigned stage, D3DSAMPLER
SamplerStates[stage][(unsigned int)state]=value;
DX8CALL(SetSamplerState( stage, state, value ));
+ Direct3D11_Mirror_Sampler_State(stage, state, value);
DX8_RECORD_TEXTURE_STAGE_STATE_CHANGE();
}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffprobe.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffprobe.cpp
index 5cbeb43c6..f13f2204f 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffprobe.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffprobe.cpp
@@ -58,6 +58,7 @@ static const size_t PIXEL_RENDER_STATE_COUNT = sizeof(PIXEL_RENDER_STATES)/sizeo
typedef std::vector<DWORD> Combination;
static bool _Enabled = false;
+static bool _CombinerShadersEnabled = false;
static std::map<Combination, unsigned> _Counts;
static std::map<IDirect3DPixelShader9 *, unsigned> _PixelShaderIds;
static unsigned long long _DrawsSeen = 0;
@@ -72,6 +73,16 @@ bool FixedFunctionProbe_Is_Enabled()
return _Enabled;
}
+void CombinerShaders_Enable(bool enabled)
+{
+ _CombinerShadersEnabled = enabled;
+}
+
+bool CombinerShaders_Are_Enabled()
+{
+ return _CombinerShadersEnabled;
+}
+
void FixedFunctionProbe_Record(IDirect3DDevice9 * device)
{
if (!_Enabled || device == NULL) {
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffprobe.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffprobe.h
index 6cac87c10..4dede1fc4 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffprobe.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffprobe.h
@@ -38,6 +38,12 @@
void FixedFunctionProbe_Enable(bool enabled);
bool FixedFunctionProbe_Is_Enabled();
+// Off unless -ffshader was given. Replaces the texture stage combiners with a generated pixel
+// shader for every draw the generator will take, which is what phase 2 compares against the
+// fixed-function pipeline before carrying any of it to a second backend.
+void CombinerShaders_Enable(bool enabled);
+bool CombinerShaders_Are_Enabled();
+
// One draw call's worth: reads the stage combiners and the pixel-affecting render states off the
// device and counts the combination.
void FixedFunctionProbe_Record(IDirect3DDevice9 * device);
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.cpp
index ea8853b10..8df5cf4bd 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.cpp
@@ -29,6 +29,24 @@ static const char * const TEXTURE_FACTOR_REGISTER = "c0";
// to whatever the argument turned out to be.
static const DWORD ARGUMENT_SELECT_MASK = D3DTA_SELECTMASK;
+// The low half of D3DTSS_TEXCOORDINDEX is the coordinate set; the high half is a generation mode.
+static const DWORD COORDINATE_SET_MASK = 0xffff;
+
+// The shader declares two coordinate sets, which is every one the four measured maps ask for. A
+// third is a refusal rather than a shader that samples a register it never declared.
+static const unsigned DECLARED_COORDINATE_SETS = 2;
+
+// Which texture coordinate register a stage reads. Only the coordinate set is read; a generation
+// mode is a vertex-side job and the vertex pipeline is still the fixed-function one, so a generated
+// coordinate has already been generated by the time it arrives here. Routing a generating stage to
+// its own stage register instead is the other reading of the documentation and it was measured:
+// on Flash Effect at frame 400 it takes the difference against the fixed-function frame from 0.25%
+// to 0.81%, so the set is what the device means.
+static unsigned coordinate_register(DWORD texture_coordinate_index)
+{
+ return static_cast<unsigned>(texture_coordinate_index & COORDINATE_SET_MASK);
+}
+
// "current" is initialised to the diffuse colour, which is what the device gives D3DTA_CURRENT at
// stage 0, so the two need no distinguishing here.
static bool argument_expression(DWORD argument, std::string & expression)
@@ -98,7 +116,46 @@ static bool operation_expression(DWORD operation, const std::string & argument0,
}
}
-bool CombinerShader_Generate(const CombinerDescription & description, std::string & hlsl)
+// D3D11 has no alpha test, so the comparison becomes a clip. clip() throws the pixel away when its
+// argument is negative, which turns each comparison into one subtraction. The two that ask about
+// equality need a tolerance, and there is no exactly right one: a D3D9 alpha test compared eight
+// bit integers and this compares floats, so half a step of eight bit precision is the tolerance
+// used and it is a choice rather than a translation.
+static const char * const ALPHA_EQUALITY_TOLERANCE = "0.00196";
+
+static bool alpha_test_expression(DWORD function, std::string & expression)
+{
+ switch (function) {
+ case D3DCMP_NEVER:
+ expression = "clip(-1.0);\n";
+ return true;
+ case D3DCMP_LESS:
+ case D3DCMP_LESSEQUAL:
+ expression = "clip(AlphaReference.x - current.a);\n";
+ return true;
+ case D3DCMP_GREATER:
+ case D3DCMP_GREATEREQUAL:
+ expression = "clip(current.a - AlphaReference.x);\n";
+ return true;
+ case D3DCMP_EQUAL:
+ expression = std::string("clip(") + ALPHA_EQUALITY_TOLERANCE
+ + " - abs(current.a - AlphaReference.x));\n";
+ return true;
+ case D3DCMP_NOTEQUAL:
+ expression = std::string("clip(abs(current.a - AlphaReference.x) - ")
+ + ALPHA_EQUALITY_TOLERANCE + ");\n";
+ return true;
+ case D3DCMP_ALWAYS:
+ // Nothing to write: every pixel survives, which is what no alpha test at all means.
+ expression.clear();
+ return true;
+ default:
+ return false;
+ }
+}
+
+bool CombinerShader_Generate(const CombinerDescription & description, CombinerShaderTarget target,
+ std::string & hlsl)
{
if (description.StageCount == 0 || description.StageCount > MAXIMUM_COMBINER_STAGES) {
return false;
@@ -110,12 +167,19 @@ bool CombinerShader_Generate(const CombinerDescription & description, std::strin
char line[256];
if (source.TextureBound) {
- // D3DTSS_TEXCOORDINDEX carries the generation mode in its high bits and the coordinate
- // set in its low ones. Only the set is read here: every generation mode the game uses
- // is a transform the vertex stage has already applied by the time a coordinate arrives.
- const unsigned coordinate_set = source.TextureCoordinateIndex & 0xffff;
- snprintf(line, sizeof(line), " texel = tex2D(Sampler%u, input.TexCoord%u);\n",
- stage, coordinate_set);
+ const unsigned register_index = coordinate_register(source.TextureCoordinateIndex);
+ if (register_index >= DECLARED_COORDINATE_SETS) {
+ return false;
+ }
+ if (target == COMBINER_SHADER_TARGET_D3D11) {
+ snprintf(line, sizeof(line),
+ " texel = Texture%u.Sample(Sampler%u, input.TexCoord%u);\n",
+ stage, stage, register_index);
+ }
+ else {
+ snprintf(line, sizeof(line), " texel = tex2D(Sampler%u, input.TexCoord%u);\n",
+ stage, register_index);
+ }
}
else {
// What a stage with no texture bound gives D3DTA_TEXTURE is not something this can
@@ -148,32 +212,96 @@ bool CombinerShader_Generate(const CombinerDescription & description, std::strin
return false;
}
- body += " current.rgb = " + colour_expression + ".rgb;\n";
- body += " current.a = " + alpha_expression + ".a;\n";
+ // Every stage of the fixed-function combiner writes a clamped result, and the next stage
+ // reads that clamped value out of D3DTA_CURRENT. A shader that carries the raw arithmetic
+ // forward instead comes out brighter wherever MODULATE2X, MODULATE4X, ADD or MULTIPLYADD
+ // left a term above one, and darker where SUBTRACT or ADDSIGNED went below zero.
+ body += " current.rgb = saturate(" + colour_expression + ").rgb;\n";
+ body += " current.a = saturate(" + alpha_expression + ").a;\n";
}
- hlsl =
- "// Generated from a fixed-function texture stage description. See ffshader.h.\n"
- "sampler2D Sampler0 : register(s0);\n"
- "sampler2D Sampler1 : register(s1);\n"
- "float4 TextureFactor : register(";
- hlsl += TEXTURE_FACTOR_REGISTER;
+ // The full input signature is declared whether the program reads it or not. Trimming it to
+ // what the body names is the obvious economy and it was measured: on Flash Effect at frame 400
+ // it takes the difference against the fixed-function frame from 0.25% to 1.20%. Why a program
+ // that reads no diffuse colour draws differently for having declared one is not understood.
+ hlsl = "// Generated from a fixed-function texture stage description. See ffshader.h.\n";
+ if (target == COMBINER_SHADER_TARGET_D3D11) {
+ // A texture and the sampler that reads it are separate objects here, and the texture
+ // factor is a constant buffer field rather than a register.
+ hlsl +=
+ "Texture2D Texture0 : register(t0);\n"
+ "Texture2D Texture1 : register(t1);\n"
+ "SamplerState Sampler0 : register(s0);\n"
+ "SamplerState Sampler1 : register(s1);\n"
+ "cbuffer CombinerConstants : register(b0)\n"
+ "{\n"
+ " float4 TextureFactor;\n"
+ " float4 FogColour;\n"
+ " float4 AlphaReference;\n"
+ "};\n";
+ }
+ else {
+ hlsl +=
+ "sampler2D Sampler0 : register(s0);\n"
+ "sampler2D Sampler1 : register(s1);\n"
+ "float4 TextureFactor : register(";
+ hlsl += TEXTURE_FACTOR_REGISTER;
+ hlsl += ");\n";
+ }
hlsl +=
- ");\n"
"\n"
"struct Input\n"
- "{\n"
+ "{\n";
+
+ // Shader model 4 links the two stages by register slot, not by name, and it assigns those
+ // slots in declaration order. A vertex shader whose output opens with SV_Position and closes
+ // with the fog factor puts the diffuse colour in the second slot; a pixel shader that declares
+ // neither puts it in the first, and D3D11 refuses the draw with a linkage error naming COLOR
+ // and TEXCOORD. So the D3D11 input structure is ffvertex's output structure, member for
+ // member, whether this program reads all of it or not. ps_2_0 has no such rule.
+ if (target == COMBINER_SHADER_TARGET_D3D11) {
+ hlsl += " float4 Position : SV_Position;\n";
+ }
+ hlsl +=
" float4 Diffuse : COLOR0;\n"
" float4 Specular : COLOR1;\n"
" float2 TexCoord0 : TEXCOORD0;\n"
- " float2 TexCoord1 : TEXCOORD1;\n"
+ " float2 TexCoord1 : TEXCOORD1;\n";
+ if (target == COMBINER_SHADER_TARGET_D3D11) {
+ hlsl += " float Fog : FOG;\n";
+ }
+ hlsl +=
"};\n"
- "\n"
- "float4 main(Input input) : COLOR\n"
+ "\n";
+ hlsl += (target == COMBINER_SHADER_TARGET_D3D11)
+ ? "float4 main(Input input) : SV_Target\n"
+ : "float4 main(Input input) : COLOR\n";
+ hlsl +=
"{\n"
" float4 texel;\n"
" float4 current = input.Diffuse;\n";
hlsl += body;
+
+ if (target == COMBINER_SHADER_TARGET_D3D11) {
+ // The fog is applied after the combiners and before the alpha test, which is the order the
+ // D3D9 pipeline applies them in. The factor is the weight of the unfogged colour, so one
+ // is no fog, and it never touches the alpha - a fogged pixel is the same shape as an
+ // unfogged one.
+ if (description.PixelPipeline.FogEnabled) {
+ hlsl += " current.rgb = lerp(FogColour.rgb, current.rgb, saturate(input.Fog));\n";
+ }
+
+ if (description.PixelPipeline.AlphaTestEnabled) {
+ std::string clip;
+ if (!alpha_test_expression(description.PixelPipeline.AlphaFunction, clip)) {
+ return false;
+ }
+ if (!clip.empty()) {
+ hlsl += " " + clip;
+ }
+ }
+ }
+
hlsl +=
" return current;\n"
"}\n";
@@ -197,9 +325,18 @@ std::string CombinerShader_Key(const CombinerDescription & description)
source.AlphaOperation, source.AlphaArgument0,
source.AlphaArgument1, source.AlphaArgument2);
key += field;
- snprintf(field, sizeof(field), ",%lu,%u",
- source.TextureCoordinateIndex & 0xffff, source.TextureBound ? 1u : 0u);
+ snprintf(field, sizeof(field), ",%u,%u",
+ coordinate_register(source.TextureCoordinateIndex), source.TextureBound ? 1u : 0u);
key += field;
}
+
+ // The alpha test and the fog change the program on the D3D11 profile. They are in the key on
+ // both, which costs a D3D9 cache entry that generates the same text as another and buys one
+ // cache that is right for either profile.
+ snprintf(field, sizeof(field), ":A%u,%lu,F%u",
+ description.PixelPipeline.AlphaTestEnabled ? 1u : 0u,
+ description.PixelPipeline.AlphaTestEnabled ? description.PixelPipeline.AlphaFunction : 0ul,
+ description.PixelPipeline.FogEnabled ? 1u : 0u);
+ key += field;
return key;
}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.h
index 6859f3fd8..5a3255839 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.h
@@ -60,16 +60,45 @@ struct CombinerStage
};
// What a draw asks the combiners to compute. Stages past StageCount are not read.
+// The two pieces of the D3D9 pixel pipeline that are neither texture stages nor shader
+// instructions. D3D9 applies both around a bound pixel shader and D3D11 has neither, so they are
+// part of the program on one profile and absent from it on the other. The alpha reference and the
+// fog colour are not here: they are uniforms, and two draws differing only in one are one program.
+struct PixelPipelineDescription
+{
+ bool AlphaTestEnabled;
+
+ // D3DCMP_*, the comparison the surviving alpha has to pass.
+ DWORD AlphaFunction;
+
+ bool FogEnabled;
+};
+
struct CombinerDescription
{
CombinerStage Stages[MAXIMUM_COMBINER_STAGES];
unsigned StageCount;
+
+ // Only read when generating for D3D11. On D3D9 the device still applies both itself around a
+ // bound pixel shader, and generating them there would apply each of them twice.
+ PixelPipelineDescription PixelPipeline;
};
// The HLSL for one description, or false when the description names an operation or an argument
// this does not generate. A refusal is not a failure: the caller keeps the fixed-function path for
// that draw, which is the only reason an unmeasured operation is safe to meet at run time.
-bool CombinerShader_Generate(const CombinerDescription & description, std::string & hlsl);
+// Which profile the generated text is for. ps_2_0 and ps_4_0 are not the same language: a sampler
+// is a sampler2D read with tex2D in one and a Texture2D beside a SamplerState read with Sample in
+// the other, the output semantic is COLOR against SV_Target, and the texture factor is a constant
+// register against a constant buffer. The arithmetic between them is the same text.
+enum CombinerShaderTarget
+{
+ COMBINER_SHADER_TARGET_D3D9,
+ COMBINER_SHADER_TARGET_D3D11
+};
+
+bool CombinerShader_Generate(const CombinerDescription & description, CombinerShaderTarget target,
+ std::string & hlsl);
// The description two draws share iff they can share a compiled shader. Stages past StageCount are
// zeroed, so two descriptions that differ only in a stage nobody reads compare equal.
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshadercache.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshadercache.cpp
new file mode 100644
index 000000000..2d876cbcd
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshadercache.cpp
@@ -0,0 +1,153 @@
+/*
+** 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 "ffshadercache.h"
+
+#include "d3dx9runtime.h"
+
+#include <map>
+#include <string.h>
+#include <string>
+
+// ps_2_0 rather than ps_1_1: the generated arithmetic is written as HLSL and a two-stage combiner
+// with a dot product does not fit the older model's instruction set. Every card that runs this
+// fork has it, and a card that does not fails the compile and keeps the fixed-function path.
+static const char * const COMPILE_PROFILE = "ps_2_0";
+static const char * const COMPILE_ENTRY_POINT = "main";
+
+static std::map<std::string, IDirect3DPixelShader9 *> _Shaders;
+static unsigned _Compiled = 0;
+static unsigned _RefusedDescriptions = 0;
+static unsigned long long _ShadedDraws = 0;
+static unsigned long long _RefusedDraws = 0;
+
+void CombinerShaderCache_Read_Device(IDirect3DDevice9 * device, CombinerDescription & description)
+{
+ // Zeroed whole, so the alpha test and fog fields are off rather than whatever the caller's
+ // stack held. On the D3D9 profile they generate nothing either way, but they are in the cache
+ // key, and a key built out of uninitialised memory is a cache that never hits.
+ memset(&description, 0, sizeof(description));
+
+ description.StageCount = 0;
+ for (unsigned stage = 0; stage < MAXIMUM_COMBINER_STAGES; ++stage) {
+ DWORD colour_operation = D3DTOP_DISABLE;
+ device->GetTextureStageState(stage, D3DTSS_COLOROP, &colour_operation);
+ if (colour_operation == D3DTOP_DISABLE) {
+ return;
+ }
+
+ CombinerStage & target = description.Stages[stage];
+ target.ColourOperation = colour_operation;
+ device->GetTextureStageState(stage, D3DTSS_COLORARG0, &target.ColourArgument0);
+ device->GetTextureStageState(stage, D3DTSS_COLORARG1, &target.ColourArgument1);
+ device->GetTextureStageState(stage, D3DTSS_COLORARG2, &target.ColourArgument2);
+ device->GetTextureStageState(stage, D3DTSS_ALPHAOP, &target.AlphaOperation);
+ device->GetTextureStageState(stage, D3DTSS_ALPHAARG0, &target.AlphaArgument0);
+ device->GetTextureStageState(stage, D3DTSS_ALPHAARG1, &target.AlphaArgument1);
+ device->GetTextureStageState(stage, D3DTSS_ALPHAARG2, &target.AlphaArgument2);
+ device->GetTextureStageState(stage, D3DTSS_TEXCOORDINDEX, &target.TextureCoordinateIndex);
+
+ IDirect3DBaseTexture9 * texture = NULL;
+ device->GetTexture(stage, &texture);
+ target.TextureBound = texture != NULL;
+ if (texture != NULL) {
+ texture->Release();
+ }
+
+ description.StageCount = stage + 1;
+ }
+
+ // A third live stage is a description the generator refuses anyway, but it has to be seen as
+ // three rather than silently truncated to two, or the wrong shader is handed back for it.
+ DWORD third_stage_operation = D3DTOP_DISABLE;
+ device->GetTextureStageState(MAXIMUM_COMBINER_STAGES, D3DTSS_COLOROP, &third_stage_operation);
+ if (third_stage_operation != D3DTOP_DISABLE) {
+ description.StageCount = MAXIMUM_COMBINER_STAGES + 1;
+ }
+}
+
+IDirect3DPixelShader9 * CombinerShaderCache_Get(IDirect3DDevice9 * device,
+ const CombinerDescription & description)
+{
+ const std::string key = CombinerShader_Key(description);
+ const std::map<std::string, IDirect3DPixelShader9 *>::const_iterator known = _Shaders.find(key);
+ if (known != _Shaders.end()) {
+ if (known->second != NULL) {
+ ++_ShadedDraws;
+ }
+ else {
+ ++_RefusedDraws;
+ }
+ return known->second;
+ }
+
+ std::string hlsl;
+ if (!CombinerShader_Generate(description, COMBINER_SHADER_TARGET_D3D9, hlsl)) {
+ _Shaders[key] = NULL;
+ ++_RefusedDescriptions;
+ ++_RefusedDraws;
+ return NULL;
+ }
+
+ LPD3DXBUFFER compiled = NULL;
+ LPD3DXBUFFER errors = NULL;
+ const HRESULT result = D3DXCompileShader(hlsl.c_str(), (UINT)hlsl.size(), NULL, NULL,
+ COMPILE_ENTRY_POINT, COMPILE_PROFILE, 0, &compiled, &errors, NULL);
+ if (errors != NULL) {
+ errors->Release();
+ }
+
+ IDirect3DPixelShader9 * shader = NULL;
+ if (SUCCEEDED(result) && compiled != NULL) {
+ device->CreatePixelShader((const DWORD *)compiled->GetBufferPointer(), &shader);
+ }
+ if (compiled != NULL) {
+ compiled->Release();
+ }
+
+ _Shaders[key] = shader;
+ if (shader != NULL) {
+ ++_Compiled;
+ ++_ShadedDraws;
+ }
+ else {
+ ++_RefusedDescriptions;
+ ++_RefusedDraws;
+ }
+ return shader;
+}
+
+void CombinerShaderCache_Release()
+{
+ for (std::map<std::string, IDirect3DPixelShader9 *>::iterator entry = _Shaders.begin();
+ entry != _Shaders.end(); ++entry) {
+ if (entry->second != NULL) {
+ entry->second->Release();
+ }
+ }
+ _Shaders.clear();
+}
+
+void CombinerShaderCache_Statistics(unsigned & compiled, unsigned & refused_descriptions,
+ unsigned long long & shaded_draws, unsigned long long & refused_draws)
+{
+ compiled = _Compiled;
+ refused_descriptions = _RefusedDescriptions;
+ shaded_draws = _ShadedDraws;
+ refused_draws = _RefusedDraws;
+}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshadercache.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshadercache.h
new file mode 100644
index 000000000..9d0fd66ae
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshadercache.h
@@ -0,0 +1,55 @@
+/*
+** 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 generated combiner shaders, compiled once and kept.
+**
+** ffshader.cpp writes a texture stage description out as HLSL; this compiles it and hands the same
+** shader back for every draw that asks for the same description. Twenty-eight programs were
+** measured over four maps, so the cache is small and never grows during a match once the frame has
+** been through its passes.
+**
+** Reading the description off the device at every draw is what the caller does, because a call site
+** that set its own stage states never went through DX8Wrapper's cache. That is the slow half and
+** it is deliberate: this exists to be compared against the fixed-function pipeline, not to be fast.
+*/
+
+#ifndef FFSHADERCACHE_H
+#define FFSHADERCACHE_H
+
+#include "ffshader.h"
+
+// The description the device is currently configured for, read back off it. StageCount is zero
+// when stage 0's colour operation is D3DTOP_DISABLE, which is the device drawing untextured.
+void CombinerShaderCache_Read_Device(IDirect3DDevice9 * device, CombinerDescription & description);
+
+// The compiled shader for a description, compiling it the first time it is asked for. NULL when
+// the generator refuses the description or the compile fails, and the caller then leaves the draw
+// on the fixed-function path.
+IDirect3DPixelShader9 * CombinerShaderCache_Get(IDirect3DDevice9 * device,
+ const CombinerDescription & description);
+
+// Hands every compiled shader back. The device owns them, so this has to run before it goes.
+void CombinerShaderCache_Release();
+
+// What the cache did, for the log line at shutdown: how many programs it compiled, how many
+// descriptions it refused, and how many draws each of those was.
+void CombinerShaderCache_Statistics(unsigned & compiled, unsigned & refused_descriptions,
+ unsigned long long & shaded_draws, unsigned long long & refused_draws);
+
+#endif
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffvertex.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffvertex.cpp
new file mode 100644
index 000000000..5d4809041
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffvertex.cpp
@@ -0,0 +1,501 @@
+/*
+** 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 "ffvertex.h"
+
+#include <stdio.h>
+
+// The high half of D3DTSS_TEXCOORDINDEX is the generation mode and the low half the coordinate set.
+static const DWORD COORDINATE_SET_MASK = 0xffff;
+
+// D3DTTFF_PROJECTED sits above the count, which is the low three bits.
+static const DWORD TEXTURE_TRANSFORM_COUNT_MASK = 0x07;
+
+// The constant registers the D3D9 profile uses, in the order they are declared. A vs_2_0 shader
+// has 256 float4 registers and this uses 34 of them, so the layout is written for reading rather
+// than for packing.
+static const unsigned REGISTER_WORLD_VIEW_PROJECTION = 0;
+static const unsigned REGISTER_WORLD_VIEW = 4;
+static const unsigned REGISTER_NORMAL_TRANSFORM = 8;
+static const unsigned REGISTER_TEXTURE_MATRIX_0 = 12;
+static const unsigned REGISTER_TEXTURE_MATRIX_1 = 16;
+static const unsigned REGISTER_MATERIAL_AMBIENT = 20;
+static const unsigned REGISTER_MATERIAL_DIFFUSE = 21;
+static const unsigned REGISTER_MATERIAL_SPECULAR = 22;
+static const unsigned REGISTER_MATERIAL_EMISSIVE = 23;
+static const unsigned REGISTER_MATERIAL_POWER = 24;
+static const unsigned REGISTER_GLOBAL_AMBIENT = 25;
+static const unsigned REGISTER_FOG_PARAMETERS = 26;
+static const unsigned REGISTER_LIGHTS = 27;
+
+// Six registers a light, the same six whatever type it is: where it is, which way it points, its
+// diffuse and specular colours, its three attenuation terms with its range, and its cone. A
+// directional light reads two of them and a spot light reads all six, and the layout stays uniform
+// so the register a light starts at is a multiplication rather than a running total over types.
+static const unsigned REGISTERS_PER_LIGHT = 6;
+
+static bool has_normal(DWORD fvf)
+{
+ return (fvf & D3DFVF_NORMAL) != 0;
+}
+
+static bool has_diffuse(DWORD fvf)
+{
+ return (fvf & D3DFVF_DIFFUSE) != 0;
+}
+
+static bool is_pretransformed(DWORD fvf)
+{
+ return (fvf & D3DFVF_POSITION_MASK) == D3DFVF_XYZRHW;
+}
+
+static unsigned texture_coordinate_set_count(DWORD fvf)
+{
+ return (fvf & D3DFVF_TEXCOUNT_MASK) >> D3DFVF_TEXCOUNT_SHIFT;
+}
+
+// A material source resolves to a constant or to a vertex colour. D3DMCS_COLOR1 reads the diffuse
+// vertex colour, and only where the format carries one and D3DRS_COLORVERTEX allows it: D3D9 falls
+// back to the material in both of those cases rather than reading a register that is not there.
+// D3DMCS_COLOR2 is the specular vertex colour, which no format in the game carries, so a
+// description asking for it is refused rather than quietly given the material instead.
+static bool material_source_expression(DWORD source, const char * material_constant,
+ const VertexPipelineDescription & description, std::string & expression)
+{
+ switch (source) {
+ case D3DMCS_MATERIAL:
+ expression = material_constant;
+ return true;
+
+ case D3DMCS_COLOR1:
+ if (has_diffuse(description.FVF) && description.ColourVertexEnabled) {
+ expression = "input.Diffuse";
+ }
+ else {
+ expression = material_constant;
+ }
+ return true;
+
+ default:
+ return false;
+ }
+}
+
+static void append_light(std::string & body, unsigned index, DWORD type)
+{
+ char line[1024];
+
+ snprintf(line, sizeof(line),
+ " {\n"
+ " float3 to_light;\n"
+ " float attenuation;\n");
+ body += line;
+
+ if (type == D3DLIGHT_DIRECTIONAL) {
+ // A directional light's direction is the way the light travels, so the vector towards it
+ // is the negative of it and there is nothing to attenuate.
+ snprintf(line, sizeof(line),
+ " to_light = -normalize(Light%uDirection.xyz);\n"
+ " attenuation = 1.0;\n", index);
+ body += line;
+ }
+ else {
+ // A point light and a spot light share the distance and the attenuation; the spot's cone
+ // is the extra term below.
+ snprintf(line, sizeof(line),
+ " float3 offset = Light%uPosition.xyz - view_position.xyz;\n"
+ " float distance = length(offset);\n"
+ " to_light = offset / max(distance, 0.0001);\n"
+ " attenuation = 1.0 / max(Light%uAttenuation.x + Light%uAttenuation.y * distance"
+ " + Light%uAttenuation.z * distance * distance, 0.0001);\n"
+ " attenuation *= step(distance, Light%uAttenuation.w);\n",
+ index, index, index, index, index);
+ body += line;
+ }
+
+ if (type == D3DLIGHT_SPOT) {
+ // D3D9's cone is a smooth falloff between the inner and the outer cosine raised to the
+ // falloff power. Light%uSpot carries cos(theta/2), cos(phi/2) and the falloff.
+ snprintf(line, sizeof(line),
+ " float spot_cosine = dot(-to_light, normalize(Light%uDirection.xyz));\n"
+ " attenuation *= pow(saturate((spot_cosine - Light%uSpot.y)"
+ " / max(Light%uSpot.x - Light%uSpot.y, 0.0001)), Light%uSpot.z);\n",
+ index, index, index, index, index);
+ body += line;
+ }
+
+ snprintf(line, sizeof(line),
+ " float lambert = max(dot(view_normal, to_light), 0.0);\n"
+ " diffuse_light += Light%uDiffuse.rgb * lambert * attenuation;\n",
+ index);
+ body += line;
+
+ // The specular term is Blinn's half vector, which is what D3D9's fixed-function pipeline uses
+ // with D3DRS_LOCALVIEWER off - and the engine never turns it on.
+ snprintf(line, sizeof(line),
+ " float3 half_vector = normalize(to_light + float3(0.0, 0.0, 1.0));\n"
+ " float highlight = pow(max(dot(view_normal, half_vector), 0.0), MaterialPower.x);\n"
+ " specular_light += Light%uSpecular.rgb * highlight * attenuation"
+ " * step(0.0001, lambert);\n"
+ " }\n", index);
+ body += line;
+}
+
+static bool append_texture_coordinates(std::string & body,
+ const VertexPipelineDescription & description)
+{
+ for (unsigned stage = 0; stage < description.StageCount; ++stage) {
+ const VertexStageDescription & source = description.Stages[stage];
+ const DWORD generation = source.TextureCoordinateIndex & ~COORDINATE_SET_MASK;
+ const unsigned set = source.TextureCoordinateIndex & COORDINATE_SET_MASK;
+
+ char line[1024];
+ switch (generation) {
+ case D3DTSS_TCI_PASSTHRU:
+ if (set >= texture_coordinate_set_count(description.FVF)) {
+ // The format does not carry the set the stage is asking for. D3D9 reads zeroes;
+ // refusing says so instead of drawing something that looks nearly right.
+ return false;
+ }
+ snprintf(line, sizeof(line), " float4 generated%u = float4(input.TexCoord%u, 0.0, 1.0);\n",
+ stage, set);
+ break;
+
+ case D3DTSS_TCI_CAMERASPACEPOSITION:
+ snprintf(line, sizeof(line), " float4 generated%u = float4(view_position.xyz, 1.0);\n",
+ stage);
+ break;
+
+ case D3DTSS_TCI_CAMERASPACENORMAL:
+ snprintf(line, sizeof(line), " float4 generated%u = float4(view_normal, 1.0);\n",
+ stage);
+ break;
+
+ case D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR:
+ snprintf(line, sizeof(line),
+ " float4 generated%u = float4(reflect(normalize(view_position.xyz), view_normal), 1.0);\n",
+ stage);
+ break;
+
+ default:
+ return false;
+ }
+ body += line;
+
+ const DWORD transform_count = source.TextureTransformFlags & TEXTURE_TRANSFORM_COUNT_MASK;
+ if (transform_count != D3DTTFF_DISABLE) {
+ snprintf(line, sizeof(line), " generated%u = mul(generated%u, TextureMatrix%u);\n",
+ stage, stage, stage);
+ body += line;
+
+ if ((source.TextureTransformFlags & D3DTTFF_PROJECTED) != 0) {
+ // A projected transform divides by the last coordinate the count named, which for
+ // every projected stage the game sets is the third.
+ snprintf(line, sizeof(line),
+ " generated%u.xy /= max(generated%u.z, 0.0001);\n", stage, stage);
+ body += line;
+ }
+ }
+
+ snprintf(line, sizeof(line), " output.TexCoord%u = generated%u.xy;\n", stage, stage);
+ body += line;
+ }
+ return true;
+}
+
+static void append_constants_d3d9(std::string & hlsl, const VertexPipelineDescription & description)
+{
+ // Long enough for the widest block written below. A short buffer here truncates the last
+ // declaration rather than failing, and the compiler then reports a syntax error on the line
+ // after it, which says nothing about where the fault is.
+ char line[1024];
+ // row_major for the reason the D3D11 block gives: a D3D9 matrix is stored by rows and HLSL
+ // assumes columns.
+ snprintf(line, sizeof(line),
+ "row_major float4x4 WorldViewProjection : register(c%u);\n"
+ "row_major float4x4 WorldView : register(c%u);\n"
+ "row_major float4x4 NormalTransform : register(c%u);\n"
+ "row_major float4x4 TextureMatrix0 : register(c%u);\n"
+ "row_major float4x4 TextureMatrix1 : register(c%u);\n",
+ REGISTER_WORLD_VIEW_PROJECTION, REGISTER_WORLD_VIEW, REGISTER_NORMAL_TRANSFORM,
+ REGISTER_TEXTURE_MATRIX_0, REGISTER_TEXTURE_MATRIX_1);
+ hlsl += line;
+
+ snprintf(line, sizeof(line),
+ "float4 MaterialAmbient : register(c%u);\n"
+ "float4 MaterialDiffuse : register(c%u);\n"
+ "float4 MaterialSpecular : register(c%u);\n"
+ "float4 MaterialEmissive : register(c%u);\n"
+ "float4 MaterialPower : register(c%u);\n"
+ "float4 GlobalAmbient : register(c%u);\n"
+ "float4 FogParameters : register(c%u);\n",
+ REGISTER_MATERIAL_AMBIENT, REGISTER_MATERIAL_DIFFUSE, REGISTER_MATERIAL_SPECULAR,
+ REGISTER_MATERIAL_EMISSIVE, REGISTER_MATERIAL_POWER, REGISTER_GLOBAL_AMBIENT,
+ REGISTER_FOG_PARAMETERS);
+ hlsl += line;
+
+ for (unsigned index = 0; index < description.LightCount; ++index) {
+ const unsigned base = REGISTER_LIGHTS + index * REGISTERS_PER_LIGHT;
+ snprintf(line, sizeof(line),
+ "float4 Light%uPosition : register(c%u);\n"
+ "float4 Light%uDirection : register(c%u);\n"
+ "float4 Light%uDiffuse : register(c%u);\n"
+ "float4 Light%uSpecular : register(c%u);\n"
+ "float4 Light%uAttenuation : register(c%u);\n"
+ "float4 Light%uSpot : register(c%u);\n",
+ index, base, index, base + 1, index, base + 2,
+ index, base + 3, index, base + 4, index, base + 5);
+ hlsl += line;
+ }
+}
+
+static void append_constants_d3d11(std::string & hlsl,
+ const VertexPipelineDescription & description)
+{
+ // row_major, because every matrix the engine has is a D3D9 matrix and D3D9 stores a matrix by
+ // rows. HLSL's default is by columns, so without this each one arrives transposed and the
+ // whole world is drawn through the wrong basis - which is not subtly wrong, it is a screen with
+ // nothing recognisable on it.
+ hlsl +=
+ "cbuffer VertexPipeline : register(b0)\n"
+ "{\n"
+ " row_major float4x4 WorldViewProjection;\n"
+ " row_major float4x4 WorldView;\n"
+ " row_major float4x4 NormalTransform;\n"
+ " row_major float4x4 TextureMatrix0;\n"
+ " row_major float4x4 TextureMatrix1;\n"
+ " float4 MaterialAmbient;\n"
+ " float4 MaterialDiffuse;\n"
+ " float4 MaterialSpecular;\n"
+ " float4 MaterialEmissive;\n"
+ " float4 MaterialPower;\n"
+ " float4 GlobalAmbient;\n"
+ " float4 FogParameters;\n";
+
+ for (unsigned index = 0; index < description.LightCount; ++index) {
+ char line[1024];
+ snprintf(line, sizeof(line),
+ " float4 Light%uPosition;\n"
+ " float4 Light%uDirection;\n"
+ " float4 Light%uDiffuse;\n"
+ " float4 Light%uSpecular;\n"
+ " float4 Light%uAttenuation;\n"
+ " float4 Light%uSpot;\n",
+ index, index, index, index, index, index);
+ hlsl += line;
+ }
+ hlsl += "};\n";
+}
+
+bool VertexShader_Generate(const VertexPipelineDescription & description,
+ VertexShaderTarget target, std::string & hlsl)
+{
+ if (description.StageCount > MAXIMUM_VERTEX_STAGES
+ || description.LightCount > MAXIMUM_VERTEX_LIGHTS) {
+ return false;
+ }
+
+ // Lighting needs a normal to light. D3D9 lights a vertex with no normal as though the normal
+ // were zero, which is black, and no draw in the game asks for that.
+ if (description.LightingEnabled && !has_normal(description.FVF)) {
+ return false;
+ }
+
+ // A pre-transformed vertex has been through all of this already. The 2D passes draw that way
+ // and a generated shader for one would be a transform applied twice.
+ if (is_pretransformed(description.FVF)) {
+ return false;
+ }
+
+ for (unsigned index = 0; index < description.LightCount; ++index) {
+ const DWORD type = description.Lights[index].Type;
+ if (type != D3DLIGHT_DIRECTIONAL && type != D3DLIGHT_POINT && type != D3DLIGHT_SPOT) {
+ return false;
+ }
+ }
+
+ std::string body;
+ body +=
+ " float4 model_position = float4(input.Position, 1.0);\n"
+ " float4 view_position = mul(model_position, WorldView);\n";
+
+ if (has_normal(description.FVF)) {
+ body += " float3 view_normal = normalize(mul(float4(input.Normal, 0.0), NormalTransform).xyz);\n";
+ }
+ else {
+ // Nothing reads it, but the coordinate generation modes name it and a shader that declares
+ // it unconditionally is one branch fewer here. The compiler drops it when it is unused.
+ body += " float3 view_normal = float3(0.0, 0.0, 1.0);\n";
+ }
+
+ if (!append_texture_coordinates(body, description)) {
+ return false;
+ }
+
+ if (description.LightingEnabled) {
+ body += " float3 diffuse_light = GlobalAmbient.rgb;\n";
+ body += " float3 specular_light = float3(0.0, 0.0, 0.0);\n";
+ for (unsigned index = 0; index < description.LightCount; ++index) {
+ append_light(body, index, description.Lights[index].Type);
+ }
+
+ std::string diffuse;
+ std::string ambient;
+ std::string emissive;
+ if (!material_source_expression(description.DiffuseMaterialSource, "MaterialDiffuse",
+ description, diffuse)
+ || !material_source_expression(description.AmbientMaterialSource, "MaterialAmbient",
+ description, ambient)
+ || !material_source_expression(description.EmissiveMaterialSource, "MaterialEmissive",
+ description, emissive)) {
+ return false;
+ }
+
+ body += " output.Diffuse.rgb = saturate(" + diffuse + ".rgb * diffuse_light + "
+ + ambient + ".rgb * GlobalAmbient.rgb + " + emissive + ".rgb);\n";
+ body += " output.Diffuse.a = " + diffuse + ".a;\n";
+
+ if (description.SpecularEnabled) {
+ std::string specular;
+ if (!material_source_expression(description.SpecularMaterialSource, "MaterialSpecular",
+ description, specular)) {
+ return false;
+ }
+ body += " output.Specular = float4(saturate(" + specular
+ + ".rgb * specular_light), 0.0);\n";
+ }
+ else {
+ body += " output.Specular = float4(0.0, 0.0, 0.0, 0.0);\n";
+ }
+ }
+ else {
+ // With D3DRS_LIGHTING off the diffuse colour is the vertex colour where there is one and
+ // white where there is not, which is what an unlit draw with no colour comes out as.
+ if (has_diffuse(description.FVF)) {
+ body += " output.Diffuse = input.Diffuse;\n";
+ }
+ else {
+ body += " output.Diffuse = float4(1.0, 1.0, 1.0, 1.0);\n";
+ }
+ body += " output.Specular = float4(0.0, 0.0, 0.0, 0.0);\n";
+ }
+
+ if (description.FogEnabled) {
+ // FogParameters carries the start, the end and the density; the mode picks which two of
+ // them are read. D3D9's factor is the weight of the unfogged colour, so 1 is no fog.
+ switch (description.FogVertexMode) {
+ case D3DFOG_LINEAR:
+ body += " output.Fog = saturate((FogParameters.y - view_position.z)"
+ " / max(FogParameters.y - FogParameters.x, 0.0001));\n";
+ break;
+ case D3DFOG_EXP:
+ body += " output.Fog = saturate(exp(-FogParameters.z * view_position.z));\n";
+ break;
+ case D3DFOG_EXP2:
+ body += " output.Fog = saturate(exp(-FogParameters.z * FogParameters.z"
+ " * view_position.z * view_position.z));\n";
+ break;
+ default:
+ return false;
+ }
+ }
+ else {
+ body += " output.Fog = 1.0;\n";
+ }
+
+ const bool for_d3d11 = (target == VERTEX_SHADER_TARGET_D3D11);
+
+ hlsl = "// Generated from a fixed-function vertex pipeline description. See ffvertex.h.\n";
+ if (for_d3d11) {
+ append_constants_d3d11(hlsl, description);
+ }
+ else {
+ append_constants_d3d9(hlsl, description);
+ }
+
+ hlsl +=
+ "\n"
+ "struct Input\n"
+ "{\n"
+ " float3 Position : POSITION;\n"
+ " float3 Normal : NORMAL;\n"
+ " float4 Diffuse : COLOR0;\n"
+ " float2 TexCoord0 : TEXCOORD0;\n"
+ " float2 TexCoord1 : TEXCOORD1;\n"
+ "};\n"
+ "\n"
+ "struct Output\n"
+ "{\n";
+ hlsl += for_d3d11 ? " float4 Position : SV_Position;\n" : " float4 Position : POSITION;\n";
+ hlsl +=
+ " float4 Diffuse : COLOR0;\n"
+ " float4 Specular : COLOR1;\n"
+ " float2 TexCoord0 : TEXCOORD0;\n"
+ " float2 TexCoord1 : TEXCOORD1;\n";
+ hlsl += for_d3d11 ? " float Fog : FOG;\n" : " float Fog : FOG;\n";
+ hlsl +=
+ "};\n"
+ "\n"
+ "Output main(Input input)\n"
+ "{\n"
+ " Output output;\n";
+ hlsl += body;
+
+ // The stages that were not generated still have an output to fill, or the structure carries
+ // whatever was on the stack and the pixel shader samples it.
+ for (unsigned stage = description.StageCount; stage < MAXIMUM_VERTEX_STAGES; ++stage) {
+ char line[128];
+ snprintf(line, sizeof(line), " output.TexCoord%u = float2(0.0, 0.0);\n", stage);
+ hlsl += line;
+ }
+
+ hlsl +=
+ " output.Position = mul(model_position, WorldViewProjection);\n"
+ " return output;\n"
+ "}\n";
+ return true;
+}
+
+std::string VertexShader_Key(const VertexPipelineDescription & description)
+{
+ std::string key;
+ char field[64];
+
+ snprintf(field, sizeof(field), "%lu:%u%u%u:%lu,%lu,%lu,%lu",
+ description.FVF, description.LightingEnabled ? 1u : 0u,
+ description.SpecularEnabled ? 1u : 0u, description.ColourVertexEnabled ? 1u : 0u,
+ description.DiffuseMaterialSource, description.AmbientMaterialSource,
+ description.EmissiveMaterialSource, description.SpecularMaterialSource);
+ key += field;
+
+ for (unsigned index = 0; index < description.LightCount; ++index) {
+ snprintf(field, sizeof(field), ":L%lu", description.Lights[index].Type);
+ key += field;
+ }
+
+ for (unsigned stage = 0; stage < description.StageCount; ++stage) {
+ snprintf(field, sizeof(field), ":T%lu,%lu", description.Stages[stage].TextureCoordinateIndex,
+ description.Stages[stage].TextureTransformFlags);
+ key += field;
+ }
+
+ snprintf(field, sizeof(field), ":F%u,%lu", description.FogEnabled ? 1u : 0u,
+ description.FogEnabled ? description.FogVertexMode : 0ul);
+ key += field;
+ return key;
+}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffvertex.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffvertex.h
new file mode 100644
index 000000000..78a0fa41d
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffvertex.h
@@ -0,0 +1,121 @@
+/*
+** 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 fixed-function vertex pipeline, written out as HLSL.
+**
+** ffshader.h does this for the pixel half. This is the other half and it is the larger one: the
+** transform, the vertex lighting, the texture coordinate generation and the fog factor all live in
+** the fixed-function vertex pipeline, and D3D11 has none of it.
+**
+** What the game actually asks for was counted rather than assumed, the same way the combiners
+** were. Three light types, two material sources, four coordinate generation modes and texture
+** transforms with a count and an optional projection. Everything outside that list is refused
+** rather than approximated, and a refusal is visible - the draw stays on the pipeline it was on -
+** where a wrong approximation is a picture nobody can explain.
+**
+** It generates for both profiles on purpose. Asked for D3D9 it writes a vs_2_0-shaped shader with
+** float4 constant registers and a POSITION output, which can be bound on the existing device and
+** compared against the fixed-function pipeline it replaces, one frame each. Asked for D3D11 it
+** writes the same body against a constant buffer with an SV_Position output. The comparison is
+** the whole reason phase 2 is being done in this order.
+*/
+
+#ifndef FFVERTEX_H
+#define FFVERTEX_H
+
+#include <d3d9.h>
+
+#include <string>
+
+// The engine's widest vertex format carries four coordinate sets and its texture stage code never
+// looks past two, so two is what a generated shader writes and a third is a refusal.
+const unsigned MAXIMUM_VERTEX_STAGES = 2;
+
+// D3D9 allows eight simultaneous lights. The scenes measured never light a draw with more than
+// three, and every register past this one is a register the D3D9 profile does not have to spare.
+const unsigned MAXIMUM_VERTEX_LIGHTS = 4;
+
+struct VertexLightDescription
+{
+ // D3DLIGHT_DIRECTIONAL, D3DLIGHT_POINT or D3DLIGHT_SPOT.
+ DWORD Type;
+};
+
+struct VertexStageDescription
+{
+ // D3DTSS_TEXCOORDINDEX whole: the generation mode in the high half, the coordinate set in the
+ // low one. Unlike the pixel half, both matter here - generating the coordinate is this
+ // shader's job now.
+ DWORD TextureCoordinateIndex;
+
+ // D3DTSS_TEXTURETRANSFORMFLAGS: a count of how many coordinates the texture matrix produces,
+ // optionally with D3DTTFF_PROJECTED. D3DTTFF_DISABLE means the matrix is not applied at all.
+ DWORD TextureTransformFlags;
+};
+
+struct VertexPipelineDescription
+{
+ // The flexible vertex format the draw is reading, which says whether there is a normal and
+ // whether there is a vertex colour to read D3DMCS_COLOR out of.
+ DWORD FVF;
+
+ bool LightingEnabled;
+ bool SpecularEnabled;
+
+ // D3DRS_COLORVERTEX. With it off the vertex colour is ignored whatever the material sources
+ // say, which is how a lit draw with a colour in its vertices still comes out unlit by it.
+ bool ColourVertexEnabled;
+
+ // D3DMCS_MATERIAL or D3DMCS_COLOR, one each. D3DMCS_COLOR2 is the specular vertex colour and
+ // nothing in the game selects it.
+ DWORD DiffuseMaterialSource;
+ DWORD AmbientMaterialSource;
+ DWORD EmissiveMaterialSource;
+ DWORD SpecularMaterialSource;
+
+ unsigned LightCount;
+ VertexLightDescription Lights[MAXIMUM_VERTEX_LIGHTS];
+
+ unsigned StageCount;
+ VertexStageDescription Stages[MAXIMUM_VERTEX_STAGES];
+
+ bool FogEnabled;
+
+ // D3DRS_FOGVERTEXMODE: D3DFOG_LINEAR, D3DFOG_EXP or D3DFOG_EXP2. D3DFOG_NONE with the fog
+ // enabled is table fog, which is the pixel half's business and not this one's.
+ DWORD FogVertexMode;
+};
+
+// Which profile the generated text is for. The two differ in the output semantic and in how the
+// constants are declared; the arithmetic between them is the same text.
+enum VertexShaderTarget
+{
+ VERTEX_SHADER_TARGET_D3D9,
+ VERTEX_SHADER_TARGET_D3D11
+};
+
+bool VertexShader_Generate(const VertexPipelineDescription & description,
+ VertexShaderTarget target, std::string & hlsl);
+
+// Two descriptions with the same key generate the same text, so the key is what a cache is built
+// on. It carries no matrix, no colour and no light direction: those are constants the draw
+// uploads, not shapes of the program.
+std::string VertexShader_Key(const VertexPipelineDescription & description);
+
+#endif // FFVERTEX_H
diff --git a/GeneralsMD/Code/Tests/test_dx11backend.cpp b/GeneralsMD/Code/Tests/test_dx11backend.cpp
new file mode 100644
index 000000000..84e3ed3b9
--- /dev/null
+++ b/GeneralsMD/Code/Tests/test_dx11backend.cpp
@@ -0,0 +1,375 @@
+/*
+** 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 backend driven the way the engine drives a device: set a transform, set a stage state, set a
+// stream, draw. Nothing here builds a shader or a state object by hand, because the point is that
+// the engine does not either.
+//
+// What it checks is the colour that lands in the render target, which is the only thing that tells
+// the whole chain apart from a chain that merely runs: a transform applied on the wrong side, a
+// vertex colour read as the wrong format, a combiner argument crossed, all of them draw something.
+
+#include "test_harness.h"
+
+#include "dx11backend.h"
+#include "dx11resource.h"
+
+#include <string.h>
+
+static const unsigned TARGET_SIZE = 64;
+static const DWORD BACKEND_FVF = D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_TEX2|D3DFVF_DIFFUSE;
+
+// All four bytes different, so a channel read in the wrong order is a wrong answer rather than a
+// lucky one. D3DCOLOR order is alpha, red, green, blue.
+static const DWORD VERTEX_COLOUR = 0xff112233;
+static const unsigned char EXPECTED_BLUE = 0x33;
+static const unsigned char EXPECTED_GREEN = 0x22;
+static const unsigned char EXPECTED_RED = 0x11;
+
+struct BackendVertex
+{
+ float Position[3];
+ float Normal[3];
+ DWORD Diffuse;
+ float TexCoord0[2];
+ float TexCoord1[2];
+};
+
+static void set_identity(float matrix[16])
+{
+ memset(matrix, 0, sizeof(float) * 16);
+ matrix[0] = 1.0f;
+ matrix[5] = 1.0f;
+ matrix[10] = 1.0f;
+ matrix[15] = 1.0f;
+}
+
+// A quad already in clip space, drawn as two triangles the way every mesh in the engine is.
+static const BackendVertex QUAD_VERTICES[4] = {
+ { { -1.0f, -1.0f, 0.5f }, { 0.0f, 0.0f, 1.0f }, VERTEX_COLOUR, { 0.0f, 0.0f }, { 0.0f, 0.0f } },
+ { { -1.0f, 1.0f, 0.5f }, { 0.0f, 0.0f, 1.0f }, VERTEX_COLOUR, { 0.0f, 0.0f }, { 0.0f, 0.0f } },
+ { { 1.0f, 1.0f, 0.5f }, { 0.0f, 0.0f, 1.0f }, VERTEX_COLOUR, { 0.0f, 0.0f }, { 0.0f, 0.0f } },
+ { { 1.0f, -1.0f, 0.5f }, { 0.0f, 0.0f, 1.0f }, VERTEX_COLOUR, { 0.0f, 0.0f }, { 0.0f, 0.0f } }
+};
+
+static const unsigned short QUAD_INDICES[6] = { 0, 1, 2, 0, 2, 3 };
+
+// Sets the backend up the way an unlit textureless draw is set up, and leaves it ready to draw.
+static void configure_unlit_pass_through(DX11BackendClass & backend)
+{
+ float identity[16];
+ set_identity(identity);
+ backend.Set_Transform(D3DTS_WORLD, identity);
+ backend.Set_Transform(D3DTS_VIEW, identity);
+ backend.Set_Transform(D3DTS_PROJECTION, identity);
+
+ backend.Set_Render_State(D3DRS_LIGHTING, FALSE);
+ backend.Set_Render_State(D3DRS_COLORVERTEX, TRUE);
+ backend.Set_Render_State(D3DRS_DIFFUSEMATERIALSOURCE, D3DMCS_COLOR1);
+ backend.Set_Render_State(D3DRS_AMBIENTMATERIALSOURCE, D3DMCS_MATERIAL);
+ backend.Set_Render_State(D3DRS_EMISSIVEMATERIALSOURCE, D3DMCS_MATERIAL);
+ backend.Set_Render_State(D3DRS_SPECULARMATERIALSOURCE, D3DMCS_MATERIAL);
+ backend.Set_Render_State(D3DRS_ZENABLE, D3DZB_FALSE);
+ backend.Set_Render_State(D3DRS_ZWRITEENABLE, FALSE);
+ backend.Set_Render_State(D3DRS_CULLMODE, D3DCULL_NONE);
+ backend.Set_Render_State(D3DRS_ALPHABLENDENABLE, FALSE);
+
+ // One stage, selecting the diffuse colour, with nothing bound: the combiner that hands the
+ // vertex colour through untouched.
+ backend.Set_Texture_Stage_State(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
+ backend.Set_Texture_Stage_State(0, D3DTSS_COLORARG1, D3DTA_DIFFUSE);
+ backend.Set_Texture_Stage_State(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
+ backend.Set_Texture_Stage_State(0, D3DTSS_ALPHAARG1, D3DTA_DIFFUSE);
+ backend.Set_Texture_Stage_State(0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_PASSTHRU);
+ backend.Set_Texture_Stage_State(0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE);
+ backend.Set_Texture_Stage_State(1, D3DTSS_COLOROP, D3DTOP_DISABLE);
+ backend.Set_Texture_Stage_State(1, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
+
+ backend.Set_Vertex_Format(BACKEND_FVF);
+}
+
+TEST(dx11backend_a_draw_set_up_the_d3d9_way_lands_in_the_render_target)
+{
+ DX11DeviceClass device;
+ device.Request_Debug_Layer();
+ CHECK(device.Create_Offscreen());
+ ID3D11Device * d3d = device.Get_Device();
+
+ DX11BackendClass backend;
+ CHECK(backend.Initialise(&device));
+
+ D3D11_TEXTURE2D_DESC target_description;
+ memset(&target_description, 0, sizeof(target_description));
+ target_description.Width = TARGET_SIZE;
+ target_description.Height = TARGET_SIZE;
+ target_description.MipLevels = 1;
+ target_description.ArraySize = 1;
+ target_description.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
+ target_description.SampleDesc.Count = 1;
+ target_description.Usage = D3D11_USAGE_DEFAULT;
+ target_description.BindFlags = D3D11_BIND_RENDER_TARGET;
+
+ ID3D11Texture2D * target = NULL;
+ CHECK(SUCCEEDED(d3d->CreateTexture2D(&target_description, NULL, &target)));
+
+ D3D11_TEXTURE2D_DESC staging_description = target_description;
+ staging_description.Usage = D3D11_USAGE_STAGING;
+ staging_description.BindFlags = 0;
+ staging_description.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
+
+ ID3D11Texture2D * staging = NULL;
+ CHECK(SUCCEEDED(d3d->CreateTexture2D(&staging_description, NULL, &staging)));
+
+ ID3D11RenderTargetView * target_view = NULL;
+ CHECK(SUCCEEDED(d3d->CreateRenderTargetView(target, NULL, &target_view)));
+
+ const float clear_colour[4] = { 0.0f, 1.0f, 0.0f, 1.0f };
+ device.Get_Context()->ClearRenderTargetView(target_view, clear_colour);
+ device.Get_Context()->OMSetRenderTargets(1, &target_view, NULL);
+
+ backend.Set_Viewport(0, 0, TARGET_SIZE, TARGET_SIZE);
+ configure_unlit_pass_through(backend);
+
+ // The buffers, asked for the way the engine asks: a managed vertex buffer filled once and a
+ // managed index buffer beside it.
+ ID3D11Buffer * vertices = NULL;
+ CHECK(DX11Resource_Create_Vertex_Buffer(d3d, sizeof(QUAD_VERTICES), D3DPOOL_MANAGED, 0,
+ QUAD_VERTICES, &vertices));
+
+ ID3D11Buffer * indices = NULL;
+ CHECK(DX11Resource_Create_Index_Buffer(d3d, sizeof(QUAD_INDICES), D3DPOOL_MANAGED, 0,
+ QUAD_INDICES, &indices));
+
+ backend.Set_Stream_Source(vertices, sizeof(BackendVertex), 0);
+ backend.Set_Indices(indices, DXGI_FORMAT_R16_UINT);
+
+ CHECK(backend.Draw_Indexed_Triangles(6, 0, 0));
+
+ device.Get_Context()->CopyResource(staging, target);
+
+ D3D11_MAPPED_SUBRESOURCE mapped;
+ CHECK(SUCCEEDED(device.Get_Context()->Map(staging, 0, D3D11_MAP_READ, 0, &mapped)));
+
+ const unsigned char * centre = static_cast<const unsigned char *>(mapped.pData)
+ + mapped.RowPitch * (TARGET_SIZE / 2) + (TARGET_SIZE / 2) * 4;
+ if (centre[0] != EXPECTED_BLUE) {
+ printf(" centre pixel bgra %02x %02x %02x %02x\n",
+ centre[0], centre[1], centre[2], centre[3]);
+ }
+ CHECK_EQ(centre[0], EXPECTED_BLUE);
+ CHECK_EQ(centre[1], EXPECTED_GREEN);
+ CHECK_EQ(centre[2], EXPECTED_RED);
+
+ // The quad covers the target, so a corner says the same thing. A transform applied on the
+ // wrong side leaves the centre right and the corners green.
+ const unsigned char * corner = static_cast<const unsigned char *>(mapped.pData);
+ CHECK_EQ(corner[0], EXPECTED_BLUE);
+ CHECK_EQ(corner[2], EXPECTED_RED);
+
+ device.Get_Context()->Unmap(staging, 0);
+
+ unsigned pipelines = 0;
+ unsigned long long made = 0;
+ unsigned long long refused = 0;
+ backend.Statistics(pipelines, made, refused);
+ CHECK_EQ(pipelines, 1u);
+ CHECK_EQ(made, 1ull);
+ CHECK_EQ(refused, 0ull);
+
+ indices->Release();
+ vertices->Release();
+ target_view->Release();
+ staging->Release();
+ target->Release();
+ backend.Shutdown();
+}
+
+// The same state twice is one pipeline, and a changed stage program is a second. The engine sets
+// the same handful of combinations thousands of times a frame, so a cache that missed would compile
+// a shader per draw and the frame time would be the symptom rather than the picture.
+TEST(dx11backend_the_same_state_resolves_to_one_pipeline)
+{
+ DX11DeviceClass device;
+ CHECK(device.Create_Offscreen());
+
+ DX11BackendClass backend;
+ CHECK(backend.Initialise(&device));
+
+ ID3D11Buffer * vertices = NULL;
+ CHECK(DX11Resource_Create_Vertex_Buffer(device.Get_Device(), sizeof(QUAD_VERTICES),
+ D3DPOOL_MANAGED, 0, QUAD_VERTICES, &vertices));
+
+ ID3D11Buffer * indices = NULL;
+ CHECK(DX11Resource_Create_Index_Buffer(device.Get_Device(), sizeof(QUAD_INDICES),
+ D3DPOOL_MANAGED, 0, QUAD_INDICES, &indices));
+
+ backend.Set_Viewport(0, 0, TARGET_SIZE, TARGET_SIZE);
+ configure_unlit_pass_through(backend);
+ backend.Set_Stream_Source(vertices, sizeof(BackendVertex), 0);
+ backend.Set_Indices(indices, DXGI_FORMAT_R16_UINT);
+
+ CHECK(backend.Draw_Indexed_Triangles(6, 0, 0));
+ CHECK(backend.Draw_Indexed_Triangles(6, 0, 0));
+
+ unsigned pipelines = 0;
+ unsigned long long made = 0;
+ unsigned long long refused = 0;
+ backend.Statistics(pipelines, made, refused);
+ CHECK_EQ(pipelines, 1u);
+ CHECK_EQ(made, 2ull);
+
+ // A different combiner program is a different pipeline.
+ backend.Set_Texture_Stage_State(0, D3DTSS_COLOROP, D3DTOP_MODULATE);
+ backend.Set_Texture_Stage_State(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
+ CHECK(backend.Draw_Indexed_Triangles(6, 0, 0));
+
+ backend.Statistics(pipelines, made, refused);
+ CHECK_EQ(pipelines, 2u);
+ CHECK_EQ(refused, 0ull);
+
+ indices->Release();
+ vertices->Release();
+ backend.Shutdown();
+}
+
+// The alpha test, which on D3D11 is a clip inside the generated pixel shader rather than anything
+// the pipeline does. The vertices carry an alpha of 0xff, so a reference above it cuts the whole
+// quad away and the target keeps the colour it was cleared to. Get the comparison backwards and
+// this passes at every reference, which is why the test is run at both ends.
+TEST(dx11backend_the_alpha_test_cuts_the_pixels_the_comparison_rejects)
+{
+ DX11DeviceClass device;
+ device.Request_Debug_Layer();
+ CHECK(device.Create_Offscreen());
+ ID3D11Device * d3d = device.Get_Device();
+
+ DX11BackendClass backend;
+ CHECK(backend.Initialise(&device));
+
+ D3D11_TEXTURE2D_DESC target_description;
+ memset(&target_description, 0, sizeof(target_description));
+ target_description.Width = TARGET_SIZE;
+ target_description.Height = TARGET_SIZE;
+ target_description.MipLevels = 1;
+ target_description.ArraySize = 1;
+ target_description.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
+ target_description.SampleDesc.Count = 1;
+ target_description.Usage = D3D11_USAGE_DEFAULT;
+ target_description.BindFlags = D3D11_BIND_RENDER_TARGET;
+
+ ID3D11Texture2D * target = NULL;
+ CHECK(SUCCEEDED(d3d->CreateTexture2D(&target_description, NULL, &target)));
+
+ D3D11_TEXTURE2D_DESC staging_description = target_description;
+ staging_description.Usage = D3D11_USAGE_STAGING;
+ staging_description.BindFlags = 0;
+ staging_description.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
+
+ ID3D11Texture2D * staging = NULL;
+ CHECK(SUCCEEDED(d3d->CreateTexture2D(&staging_description, NULL, &staging)));
+
+ ID3D11RenderTargetView * target_view = NULL;
+ CHECK(SUCCEEDED(d3d->CreateRenderTargetView(target, NULL, &target_view)));
+
+ ID3D11Buffer * vertices = NULL;
+ CHECK(DX11Resource_Create_Vertex_Buffer(d3d, sizeof(QUAD_VERTICES), D3DPOOL_MANAGED, 0,
+ QUAD_VERTICES, &vertices));
+
+ ID3D11Buffer * indices = NULL;
+ CHECK(DX11Resource_Create_Index_Buffer(d3d, sizeof(QUAD_INDICES), D3DPOOL_MANAGED, 0,
+ QUAD_INDICES, &indices));
+
+ backend.Set_Viewport(0, 0, TARGET_SIZE, TARGET_SIZE);
+ configure_unlit_pass_through(backend);
+ backend.Set_Stream_Source(vertices, sizeof(BackendVertex), 0);
+ backend.Set_Indices(indices, DXGI_FORMAT_R16_UINT);
+
+ // The vertices carry an opaque alpha, so half is a reference it is above. The two comparisons
+ // below therefore disagree about every pixel in the quad, which is what makes this a pair
+ // rather than one measurement: a clip written the wrong way round passes one of them.
+ backend.Set_Render_State(D3DRS_ALPHATESTENABLE, TRUE);
+ backend.Set_Render_State(D3DRS_ALPHAREF, 0x80);
+
+ backend.Set_Render_State(D3DRS_ALPHAFUNC, D3DCMP_LESS);
+
+ const float clear_colour[4] = { 0.0f, 1.0f, 0.0f, 1.0f };
+ device.Get_Context()->ClearRenderTargetView(target_view, clear_colour);
+ device.Get_Context()->OMSetRenderTargets(1, &target_view, NULL);
+ CHECK(backend.Draw_Indexed_Triangles(6, 0, 0));
+
+ device.Get_Context()->CopyResource(staging, target);
+ D3D11_MAPPED_SUBRESOURCE mapped;
+ CHECK(SUCCEEDED(device.Get_Context()->Map(staging, 0, D3D11_MAP_READ, 0, &mapped)));
+ const unsigned char * cut = static_cast<const unsigned char *>(mapped.pData)
+ + mapped.RowPitch * (TARGET_SIZE / 2) + (TARGET_SIZE / 2) * 4;
+ CHECK_EQ(cut[1], 0xff);
+ CHECK_EQ(cut[0], 0x00);
+ device.Get_Context()->Unmap(staging, 0);
+
+ // The same reference, the opposite comparison: now every pixel passes.
+ device.Get_Context()->ClearRenderTargetView(target_view, clear_colour);
+ backend.Set_Render_State(D3DRS_ALPHAFUNC, D3DCMP_GREATEREQUAL);
+ CHECK(backend.Draw_Indexed_Triangles(6, 0, 0));
+
+ device.Get_Context()->CopyResource(staging, target);
+ CHECK(SUCCEEDED(device.Get_Context()->Map(staging, 0, D3D11_MAP_READ, 0, &mapped)));
+ const unsigned char * kept = static_cast<const unsigned char *>(mapped.pData)
+ + mapped.RowPitch * (TARGET_SIZE / 2) + (TARGET_SIZE / 2) * 4;
+ CHECK_EQ(kept[0], EXPECTED_BLUE);
+ CHECK_EQ(kept[2], EXPECTED_RED);
+ device.Get_Context()->Unmap(staging, 0);
+
+ // The comparison is part of the program and the reference is not, so two comparisons are two
+ // pipelines and the reference could have changed between them for free.
+ unsigned pipelines = 0;
+ unsigned long long made = 0;
+ unsigned long long refused = 0;
+ backend.Statistics(pipelines, made, refused);
+ CHECK_EQ(pipelines, 2u);
+ CHECK_EQ(made, 2ull);
+
+ indices->Release();
+ vertices->Release();
+ target_view->Release();
+ staging->Release();
+ target->Release();
+ backend.Shutdown();
+}
+
+// A draw with no stream bound is refused rather than attempted. D3D9 would have drawn nothing and
+// said nothing; a count that goes up is the difference between a missing pass and a silent one.
+TEST(dx11backend_a_draw_with_nothing_bound_is_counted_as_refused)
+{
+ DX11DeviceClass device;
+ CHECK(device.Create_Offscreen());
+
+ DX11BackendClass backend;
+ CHECK(backend.Initialise(&device));
+ configure_unlit_pass_through(backend);
+
+ CHECK(!backend.Draw_Indexed_Triangles(6, 0, 0));
+
+ unsigned pipelines = 0;
+ unsigned long long made = 0;
+ unsigned long long refused = 0;
+ backend.Statistics(pipelines, made, refused);
+ CHECK_EQ(made, 0ull);
+ CHECK_EQ(refused, 1ull);
+
+ backend.Shutdown();
+}
diff --git a/GeneralsMD/Code/Tests/test_dx11device.cpp b/GeneralsMD/Code/Tests/test_dx11device.cpp
new file mode 100644
index 000000000..1b25ff58d
--- /dev/null
+++ b/GeneralsMD/Code/Tests/test_dx11device.cpp
@@ -0,0 +1,145 @@
+/*
+** 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 Direct3D 11 device, created for real. A renderer test that cannot make a device proves
+// nothing about one, and D3D11 makes this cheap where D3D9 does not: a device needs no window and
+// WARP draws the same picture without a driver, so this runs in a batch and on a machine with no
+// display as well as on the one it was written on.
+//
+// Everything phase 2 builds sits on this, so the things checked here are the ones a mistake in
+// would be found much later and much further away: that a device with no swap chain refuses to
+// present rather than faulting, that a resize leaves the views pointing at the new buffers, and
+// that a released device is a device that can be created again.
+
+#include "test_harness.h"
+
+#include "dx11device.h"
+
+// Two sizes, neither of them the other's multiple, so a resize that quietly kept the old numbers
+// reads as a failure rather than as an accident that matched.
+static const unsigned FIRST_WIDTH = 320;
+static const unsigned FIRST_HEIGHT = 240;
+static const unsigned SECOND_WIDTH = 512;
+static const unsigned SECOND_HEIGHT = 288;
+
+// A window nothing shows. A swap chain needs an HWND and a message-pumped window would make this
+// a manual test; a hidden one is enough for DXGI to build buffers against.
+static HWND make_hidden_window()
+{
+ static const char * const CLASS_NAME = "CnCGeneralsZHDX11DeviceTest";
+
+ WNDCLASSA window_class;
+ ZeroMemory(&window_class, sizeof(window_class));
+ window_class.lpfnWndProc = DefWindowProcA;
+ window_class.hInstance = GetModuleHandleA(NULL);
+ window_class.lpszClassName = CLASS_NAME;
+ RegisterClassA(&window_class);
+
+ return CreateWindowExA(0, CLASS_NAME, CLASS_NAME, WS_OVERLAPPEDWINDOW, 0, 0,
+ FIRST_WIDTH, FIRST_HEIGHT, NULL, NULL, GetModuleHandleA(NULL), NULL);
+}
+
+TEST(dx11device_creates_a_device_with_no_window_at_all)
+{
+ DX11DeviceClass device;
+ CHECK(device.Create_Offscreen());
+ CHECK(device.Is_Created());
+ CHECK(device.Get_Device() != NULL);
+ CHECK(device.Get_Context() != NULL);
+
+ // No window, no swap chain, and therefore no back buffer to draw into or show.
+ CHECK(!device.Has_Swap_Chain());
+ CHECK(device.Get_Back_Buffer_View() == NULL);
+
+ CHECK_EQ(device.Device_Removed_Reason(), S_OK);
+}
+
+TEST(dx11device_releasing_leaves_it_creatable_again)
+{
+ DX11DeviceClass device;
+ CHECK(device.Create_Offscreen());
+ device.Release();
+ CHECK(!device.Is_Created());
+ CHECK(device.Get_Device() == NULL);
+
+ CHECK(device.Create_Offscreen());
+ CHECK(device.Is_Created());
+}
+
+TEST(dx11device_creates_a_swap_chain_and_both_views)
+{
+ HWND window = make_hidden_window();
+ CHECK(window != NULL);
+
+ DX11DeviceClass device;
+ CHECK(device.Create(window, FIRST_WIDTH, FIRST_HEIGHT));
+ CHECK(device.Has_Swap_Chain());
+ CHECK(device.Get_Back_Buffer_View() != NULL);
+ CHECK(device.Get_Depth_Stencil_View() != NULL);
+ CHECK_EQ(device.Get_Width(), FIRST_WIDTH);
+ CHECK_EQ(device.Get_Height(), FIRST_HEIGHT);
+
+ // A clear and a present with no wait: the two calls every frame makes whatever else it does.
+ device.Clear(0.0f, 0.0f, 0.0f, 1.0f, true);
+ CHECK(device.Present(0));
+
+ device.Release();
+ DestroyWindow(window);
+}
+
+TEST(dx11device_a_resize_rebuilds_the_views_around_the_new_buffers)
+{
+ HWND window = make_hidden_window();
+ CHECK(window != NULL);
+
+ DX11DeviceClass device;
+ CHECK(device.Create(window, FIRST_WIDTH, FIRST_HEIGHT));
+
+ CHECK(device.Resize(SECOND_WIDTH, SECOND_HEIGHT));
+ CHECK_EQ(device.Get_Width(), SECOND_WIDTH);
+ CHECK_EQ(device.Get_Height(), SECOND_HEIGHT);
+
+ // The view has to be looking at the buffer the resize produced. Comparing the pointer against
+ // the one from before says nothing - the allocator hands the same address back often enough
+ // that the check passes for the wrong reason - so this asks the texture underneath how big it
+ // is. A view left over from before the resize reports the old size here.
+ CHECK(device.Get_Back_Buffer_View() != NULL);
+ CHECK(device.Get_Depth_Stencil_View() != NULL);
+
+ ID3D11Resource * target = NULL;
+ device.Get_Back_Buffer_View()->GetResource(&target);
+ CHECK(target != NULL);
+
+ ID3D11Texture2D * target_texture = NULL;
+ CHECK(SUCCEEDED(target->QueryInterface(__uuidof(ID3D11Texture2D),
+ reinterpret_cast<void **>(&target_texture))));
+
+ D3D11_TEXTURE2D_DESC description;
+ target_texture->GetDesc(&description);
+ CHECK_EQ(description.Width, SECOND_WIDTH);
+ CHECK_EQ(description.Height, SECOND_HEIGHT);
+
+ target_texture->Release();
+ target->Release();
+
+ device.Clear(0.0f, 0.0f, 0.0f, 1.0f, true);
+ CHECK(device.Present(0));
+
+ device.Release();
+ DestroyWindow(window);
+}
diff --git a/GeneralsMD/Code/Tests/test_dx11layout.cpp b/GeneralsMD/Code/Tests/test_dx11layout.cpp
new file mode 100644
index 000000000..a94505c22
--- /dev/null
+++ b/GeneralsMD/Code/Tests/test_dx11layout.cpp
@@ -0,0 +1,185 @@
+/*
+** 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/>.
+*/
+
+// Every vertex format the engine names, turned into a D3D11 input layout and checked against the
+// bytes the structs in dx8fvf.h already lay down. An offset that is wrong by four reads every
+// vertex at the wrong place and reports nothing: no error, no warning, a picture made of noise.
+//
+// The strides here are counted off those structs by hand rather than taken from the code under
+// test, which is the point of writing them down.
+
+#include "test_harness.h"
+
+#include "dx11layout.h"
+
+#include <string.h>
+
+// The formats, spelled out rather than included: dx8fvf.h drags in the rest of WW3D2 and this test
+// links one translation unit. They are the enum in dx8fvf.h, value for value.
+static const DWORD FVF_XYZ = D3DFVF_XYZ;
+static const DWORD FVF_XYZN = D3DFVF_XYZ|D3DFVF_NORMAL;
+static const DWORD FVF_XYZDUV1 = D3DFVF_XYZ|D3DFVF_TEX1|D3DFVF_DIFFUSE;
+static const DWORD FVF_XYZNDUV2 = D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_TEX2|D3DFVF_DIFFUSE;
+static const DWORD FVF_XYZNDCUBEMAP = D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_DIFFUSE;
+static const DWORD FVF_XYZNDUV1TG3 = D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_DIFFUSE|D3DFVF_TEX4
+ |D3DFVF_TEXCOORDSIZE2(0)|D3DFVF_TEXCOORDSIZE3(1)|D3DFVF_TEXCOORDSIZE3(2)|D3DFVF_TEXCOORDSIZE3(3);
+static const DWORD FVF_XYZNUV2DMAP = D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_TEX3
+ |D3DFVF_TEXCOORDSIZE1(0)|D3DFVF_TEXCOORDSIZE4(1)|D3DFVF_TEXCOORDSIZE2(2);
+
+static bool semantic_is(const D3D11_INPUT_ELEMENT_DESC & element, const char * name, unsigned index)
+{
+ return strcmp(element.SemanticName, name) == 0 && element.SemanticIndex == index;
+}
+
+TEST(dx11layout_a_position_only_format_is_one_element_of_twelve_bytes)
+{
+ D3D11_INPUT_ELEMENT_DESC elements[MAXIMUM_LAYOUT_ELEMENTS];
+ unsigned count = 0;
+ unsigned stride = 0;
+ CHECK(DX11Layout_From_FVF(FVF_XYZ, elements, count, stride));
+ CHECK_EQ(count, 1u);
+ CHECK_EQ(stride, 12u);
+ CHECK(semantic_is(elements[0], "POSITION", 0));
+ CHECK_EQ(elements[0].Format, DXGI_FORMAT_R32G32B32_FLOAT);
+ CHECK_EQ(elements[0].AlignedByteOffset, 0u);
+}
+
+TEST(dx11layout_position_and_normal_pack_back_to_back)
+{
+ D3D11_INPUT_ELEMENT_DESC elements[MAXIMUM_LAYOUT_ELEMENTS];
+ unsigned count = 0;
+ unsigned stride = 0;
+ CHECK(DX11Layout_From_FVF(FVF_XYZN, elements, count, stride));
+ CHECK_EQ(count, 2u);
+ CHECK_EQ(stride, 24u);
+ CHECK(semantic_is(elements[1], "NORMAL", 0));
+ CHECK_EQ(elements[1].AlignedByteOffset, 12u);
+}
+
+// DX8_FVF_XYZNDUV2 is the one format DynamicVBAccessClass hands out, so it is the one every
+// dynamic buffer in the game is filled through.
+TEST(dx11layout_the_dynamic_buffer_format_lays_out_as_its_struct_does)
+{
+ D3D11_INPUT_ELEMENT_DESC elements[MAXIMUM_LAYOUT_ELEMENTS];
+ unsigned count = 0;
+ unsigned stride = 0;
+ CHECK(DX11Layout_From_FVF(FVF_XYZNDUV2, elements, count, stride));
+ CHECK_EQ(count, 5u);
+ CHECK_EQ(stride, 44u);
+
+ CHECK(semantic_is(elements[0], "POSITION", 0));
+ CHECK_EQ(elements[0].AlignedByteOffset, 0u);
+ CHECK(semantic_is(elements[1], "NORMAL", 0));
+ CHECK_EQ(elements[1].AlignedByteOffset, 12u);
+ CHECK(semantic_is(elements[2], "COLOR", 0));
+ CHECK_EQ(elements[2].AlignedByteOffset, 24u);
+ CHECK(semantic_is(elements[3], "TEXCOORD", 0));
+ CHECK_EQ(elements[3].AlignedByteOffset, 28u);
+ CHECK(semantic_is(elements[4], "TEXCOORD", 1));
+ CHECK_EQ(elements[4].AlignedByteOffset, 36u);
+}
+
+// A D3DCOLOR is packed blue, green, red, alpha. R8G8B8A8 compiles, draws, and swaps red and blue
+// in every vertex colour in the game, which is why this is checked rather than assumed.
+TEST(dx11layout_a_vertex_colour_is_bgra_not_rgba)
+{
+ D3D11_INPUT_ELEMENT_DESC elements[MAXIMUM_LAYOUT_ELEMENTS];
+ unsigned count = 0;
+ unsigned stride = 0;
+ CHECK(DX11Layout_From_FVF(FVF_XYZDUV1, elements, count, stride));
+ CHECK_EQ(count, 3u);
+ CHECK_EQ(stride, 24u);
+ CHECK(semantic_is(elements[1], "COLOR", 0));
+ CHECK_EQ(elements[1].Format, DXGI_FORMAT_B8G8R8A8_UNORM);
+}
+
+TEST(dx11layout_a_format_with_no_texture_coordinates_has_none)
+{
+ D3D11_INPUT_ELEMENT_DESC elements[MAXIMUM_LAYOUT_ELEMENTS];
+ unsigned count = 0;
+ unsigned stride = 0;
+ CHECK(DX11Layout_From_FVF(FVF_XYZNDCUBEMAP, elements, count, stride));
+ CHECK_EQ(count, 3u);
+ CHECK_EQ(stride, 28u);
+}
+
+// The two formats whose coordinate sets are not two floats each. Reading the size bits is what
+// this is for: without them the tangent frame's three-float sets are read as two and everything
+// after the first one is at the wrong offset.
+TEST(dx11layout_the_tangent_frame_format_reads_its_coordinate_sizes)
+{
+ D3D11_INPUT_ELEMENT_DESC elements[MAXIMUM_LAYOUT_ELEMENTS];
+ unsigned count = 0;
+ unsigned stride = 0;
+ CHECK(DX11Layout_From_FVF(FVF_XYZNDUV1TG3, elements, count, stride));
+ CHECK_EQ(count, 7u);
+ CHECK_EQ(stride, 72u);
+
+ CHECK(semantic_is(elements[3], "TEXCOORD", 0));
+ CHECK_EQ(elements[3].Format, DXGI_FORMAT_R32G32_FLOAT);
+ CHECK_EQ(elements[3].AlignedByteOffset, 28u);
+
+ CHECK(semantic_is(elements[4], "TEXCOORD", 1));
+ CHECK_EQ(elements[4].Format, DXGI_FORMAT_R32G32B32_FLOAT);
+ CHECK_EQ(elements[4].AlignedByteOffset, 36u);
+
+ CHECK(semantic_is(elements[6], "TEXCOORD", 3));
+ CHECK_EQ(elements[6].AlignedByteOffset, 60u);
+}
+
+TEST(dx11layout_the_displacement_map_format_reads_a_one_a_four_and_a_two)
+{
+ D3D11_INPUT_ELEMENT_DESC elements[MAXIMUM_LAYOUT_ELEMENTS];
+ unsigned count = 0;
+ unsigned stride = 0;
+ CHECK(DX11Layout_From_FVF(FVF_XYZNUV2DMAP, elements, count, stride));
+ CHECK_EQ(count, 5u);
+ CHECK_EQ(stride, 52u);
+
+ CHECK_EQ(elements[2].Format, DXGI_FORMAT_R32_FLOAT);
+ CHECK_EQ(elements[2].AlignedByteOffset, 24u);
+ CHECK_EQ(elements[3].Format, DXGI_FORMAT_R32G32B32A32_FLOAT);
+ CHECK_EQ(elements[3].AlignedByteOffset, 28u);
+ CHECK_EQ(elements[4].Format, DXGI_FORMAT_R32G32_FLOAT);
+ CHECK_EQ(elements[4].AlignedByteOffset, 44u);
+}
+
+// A pre-transformed vertex keeps all four floats and its w is already divided. The 2D passes are
+// drawn this way and there is no transform to apply to them.
+TEST(dx11layout_a_pretransformed_position_keeps_four_floats)
+{
+ D3D11_INPUT_ELEMENT_DESC elements[MAXIMUM_LAYOUT_ELEMENTS];
+ unsigned count = 0;
+ unsigned stride = 0;
+ CHECK(DX11Layout_From_FVF(D3DFVF_XYZRHW|D3DFVF_DIFFUSE|D3DFVF_TEX1, elements, count, stride));
+ CHECK_EQ(count, 3u);
+ CHECK_EQ(stride, 28u);
+ CHECK_EQ(elements[0].Format, DXGI_FORMAT_R32G32B32A32_FLOAT);
+}
+
+// A format the engine never fills is refused outright. Half a layout is a buffer read at the
+// wrong stride, and that is worse than a draw that does not happen.
+TEST(dx11layout_refuses_a_format_with_no_position)
+{
+ D3D11_INPUT_ELEMENT_DESC elements[MAXIMUM_LAYOUT_ELEMENTS];
+ unsigned count = 0;
+ unsigned stride = 0;
+ CHECK(!DX11Layout_From_FVF(D3DFVF_DIFFUSE|D3DFVF_TEX1, elements, count, stride));
+ CHECK_EQ(count, 0u);
+ CHECK_EQ(stride, 0u);
+}
diff --git a/GeneralsMD/Code/Tests/test_dx11pipeline.cpp b/GeneralsMD/Code/Tests/test_dx11pipeline.cpp
new file mode 100644
index 000000000..3c5b30860
--- /dev/null
+++ b/GeneralsMD/Code/Tests/test_dx11pipeline.cpp
@@ -0,0 +1,421 @@
+/*
+** 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 whole translation, drawn.
+//
+// Every other test in this set checks one piece against what it should say: the state block against
+// the three descriptions, the layout against the offsets, the generators against the text they
+// write. All of them can pass while the pieces refuse to work together, because the thing that
+// joins them is D3D11's own validation - an input layout has to match the vertex shader's input
+// signature, a pixel shader's inputs have to be a subset of what the vertex shader wrote, and none
+// of that is visible in any single one of the descriptions.
+//
+// So this builds a device, generates both shaders from descriptions the game produces, builds the
+// input layout out of the flexible vertex format the dynamic buffers use, builds the three state
+// objects out of the render states, draws a quad through the lot and reads the pixel back. The
+// colour that comes out is the vertex colour that went in, which is what an unlit pass-through
+// draw means.
+
+#include "test_harness.h"
+
+#include "dx11device.h"
+#include "dx11layout.h"
+#include "dx11state.h"
+#include "ffshader.h"
+#include "ffvertex.h"
+
+#include <d3dcommon.h>
+#include <d3d11sdklayers.h>
+#include <stdlib.h>
+#include <string.h>
+#include <windows.h>
+
+typedef HRESULT (WINAPI *D3DCompileFunction)(LPCVOID source_data, SIZE_T source_size,
+ LPCSTR source_name, const D3D_SHADER_MACRO * defines, ID3DInclude * include,
+ LPCSTR entry_point, LPCSTR target, UINT flags1, UINT flags2, ID3DBlob ** code,
+ ID3DBlob ** error_messages);
+
+static const char * const COMPILER_MODULE = "d3dcompiler_47.dll";
+static const char * const ENTRY_POINT = "main";
+static const char * const VERTEX_PROFILE = "vs_4_0";
+static const char * const PIXEL_PROFILE = "ps_4_0";
+
+static const unsigned TARGET_WIDTH = 64;
+static const unsigned TARGET_HEIGHT = 64;
+
+// Packed the way a D3DCOLOR is: alpha, red, green, blue, most significant byte first. All four
+// bytes differ so that a channel read in the wrong order is a wrong answer rather than a lucky one,
+// which a symmetric colour would hide.
+static const DWORD VERTEX_COLOUR = 0xff112233;
+static const unsigned char EXPECTED_BLUE = 0x33;
+static const unsigned char EXPECTED_GREEN = 0x22;
+static const unsigned char EXPECTED_RED = 0x11;
+static const unsigned char EXPECTED_ALPHA = 0xff;
+
+static const DWORD PIPELINE_FVF = D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_TEX2|D3DFVF_DIFFUSE;
+
+// The constant buffer ffvertex declares for a description with no lights: five matrices and seven
+// float4s, in that order.
+struct VertexConstants
+{
+ float WorldViewProjection[16];
+ float WorldView[16];
+ float NormalTransform[16];
+ float TextureMatrix0[16];
+ float TextureMatrix1[16];
+ float MaterialAmbient[4];
+ float MaterialDiffuse[4];
+ float MaterialSpecular[4];
+ float MaterialEmissive[4];
+ float MaterialPower[4];
+ float GlobalAmbient[4];
+ float FogParameters[4];
+};
+
+struct PixelConstants
+{
+ float TextureFactor[4];
+};
+
+// One vertex of DX8_FVF_XYZNDUV2, which is the format every dynamic buffer in the game is filled
+// through, laid out here exactly as dx11layout says it is.
+struct PipelineVertex
+{
+ float Position[3];
+ float Normal[3];
+ DWORD Diffuse;
+ float TexCoord0[2];
+ float TexCoord1[2];
+};
+
+static void set_identity(float matrix[16])
+{
+ memset(matrix, 0, sizeof(float) * 16);
+ matrix[0] = 1.0f;
+ matrix[5] = 1.0f;
+ matrix[10] = 1.0f;
+ matrix[15] = 1.0f;
+}
+
+// What the validation layer has to say, if it is there. Its messages go to the debugger by
+// default, which a test run from a script never sees, so they are pulled out of the queue and
+// printed. Silence here means the layer found nothing, not that it was not asked.
+static void print_validation_messages(ID3D11Device * device)
+{
+ ID3D11InfoQueue * queue = NULL;
+ if (FAILED(device->QueryInterface(__uuidof(ID3D11InfoQueue),
+ reinterpret_cast<void **>(&queue)))) {
+ return;
+ }
+
+ const UINT64 count = queue->GetNumStoredMessages();
+ for (UINT64 index = 0; index < count; ++index) {
+ SIZE_T length = 0;
+ queue->GetMessage(index, NULL, &length);
+
+ D3D11_MESSAGE * message = static_cast<D3D11_MESSAGE *>(malloc(length));
+ if (SUCCEEDED(queue->GetMessage(index, message, &length))) {
+ printf(" validation: %s\n", message->pDescription);
+ }
+ free(message);
+ }
+ queue->Release();
+}
+
+static D3DCompileFunction load_compiler()
+{
+ HMODULE module = LoadLibraryA(COMPILER_MODULE);
+ if (module == NULL) {
+ return NULL;
+ }
+ return reinterpret_cast<D3DCompileFunction>(GetProcAddress(module, "D3DCompile"));
+}
+
+static ID3DBlob * compile(D3DCompileFunction compiler, const std::string & hlsl,
+ const char * profile)
+{
+ ID3DBlob * code = NULL;
+ ID3DBlob * errors = NULL;
+ const HRESULT result = compiler(hlsl.c_str(), hlsl.size(), "pipeline", NULL, NULL,
+ ENTRY_POINT, profile, 0, 0, &code, &errors);
+
+ if (FAILED(result) && errors != NULL) {
+ printf(" %s: %s\n", profile, static_cast<const char *>(errors->GetBufferPointer()));
+ }
+ if (errors != NULL) {
+ errors->Release();
+ }
+ return SUCCEEDED(result) ? code : NULL;
+}
+
+// An unlit draw with one pass-through coordinate set: the shape most of the game's draws are.
+static VertexPipelineDescription unlit_vertex_description()
+{
+ VertexPipelineDescription description;
+ memset(&description, 0, sizeof(description));
+ description.FVF = PIPELINE_FVF;
+ description.ColourVertexEnabled = true;
+ description.DiffuseMaterialSource = D3DMCS_COLOR1;
+ description.AmbientMaterialSource = D3DMCS_MATERIAL;
+ description.EmissiveMaterialSource = D3DMCS_MATERIAL;
+ description.SpecularMaterialSource = D3DMCS_MATERIAL;
+ description.StageCount = 1;
+ description.Stages[0].TextureCoordinateIndex = D3DTSS_TCI_PASSTHRU;
+ description.Stages[0].TextureTransformFlags = D3DTTFF_DISABLE;
+ description.FogVertexMode = D3DFOG_NONE;
+ return description;
+}
+
+// SELECTARG1 on the diffuse colour with nothing bound: the combiner that hands the vertex colour
+// straight through, so what lands in the render target is what was put in the vertex.
+static CombinerDescription diffuse_combiner_description()
+{
+ CombinerDescription description;
+ memset(&description, 0, sizeof(description));
+ description.StageCount = 1;
+ description.Stages[0].ColourOperation = D3DTOP_SELECTARG1;
+ description.Stages[0].ColourArgument1 = D3DTA_DIFFUSE;
+ description.Stages[0].ColourArgument2 = D3DTA_CURRENT;
+ description.Stages[0].AlphaOperation = D3DTOP_SELECTARG1;
+ description.Stages[0].AlphaArgument1 = D3DTA_DIFFUSE;
+ description.Stages[0].AlphaArgument2 = D3DTA_CURRENT;
+ description.Stages[0].TextureCoordinateIndex = 0;
+ description.Stages[0].TextureBound = false;
+ return description;
+}
+
+TEST(dx11pipeline_a_generated_program_draws_the_vertex_colour_it_was_given)
+{
+ D3DCompileFunction compiler = load_compiler();
+ if (compiler == NULL) {
+ printf(" d3dcompiler_47.dll not present, skipping\n");
+ return;
+ }
+
+ DX11DeviceClass device;
+ device.Request_Debug_Layer();
+ CHECK(device.Create_Offscreen());
+ ID3D11Device * d3d = device.Get_Device();
+ ID3D11DeviceContext * context = device.Get_Context();
+
+ // The target to draw into, and the staging copy the result is read out of. A default-usage
+ // texture cannot be mapped, which is why there are two.
+ D3D11_TEXTURE2D_DESC target_description;
+ memset(&target_description, 0, sizeof(target_description));
+ target_description.Width = TARGET_WIDTH;
+ target_description.Height = TARGET_HEIGHT;
+ target_description.MipLevels = 1;
+ target_description.ArraySize = 1;
+ target_description.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
+ target_description.SampleDesc.Count = 1;
+ target_description.Usage = D3D11_USAGE_DEFAULT;
+ target_description.BindFlags = D3D11_BIND_RENDER_TARGET;
+
+ ID3D11Texture2D * target = NULL;
+ CHECK(SUCCEEDED(d3d->CreateTexture2D(&target_description, NULL, &target)));
+
+ D3D11_TEXTURE2D_DESC staging_description = target_description;
+ staging_description.Usage = D3D11_USAGE_STAGING;
+ staging_description.BindFlags = 0;
+ staging_description.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
+
+ ID3D11Texture2D * staging = NULL;
+ CHECK(SUCCEEDED(d3d->CreateTexture2D(&staging_description, NULL, &staging)));
+
+ ID3D11RenderTargetView * target_view = NULL;
+ CHECK(SUCCEEDED(d3d->CreateRenderTargetView(target, NULL, &target_view)));
+
+ std::string vertex_hlsl;
+ std::string pixel_hlsl;
+ CHECK(VertexShader_Generate(unlit_vertex_description(), VERTEX_SHADER_TARGET_D3D11, vertex_hlsl));
+ CHECK(CombinerShader_Generate(diffuse_combiner_description(), COMBINER_SHADER_TARGET_D3D11,
+ pixel_hlsl));
+
+ ID3DBlob * vertex_code = compile(compiler, vertex_hlsl, VERTEX_PROFILE);
+ ID3DBlob * pixel_code = compile(compiler, pixel_hlsl, PIXEL_PROFILE);
+ CHECK(vertex_code != NULL);
+ CHECK(pixel_code != NULL);
+
+ ID3D11VertexShader * vertex_shader = NULL;
+ ID3D11PixelShader * pixel_shader = NULL;
+ CHECK(SUCCEEDED(d3d->CreateVertexShader(vertex_code->GetBufferPointer(),
+ vertex_code->GetBufferSize(), NULL, &vertex_shader)));
+ CHECK(SUCCEEDED(d3d->CreatePixelShader(pixel_code->GetBufferPointer(),
+ pixel_code->GetBufferSize(), NULL, &pixel_shader)));
+
+ // The layout has to match the vertex shader's input signature, and CreateInputLayout is where
+ // D3D11 says so. This is the one call that checks dx11layout against ffvertex.
+ D3D11_INPUT_ELEMENT_DESC elements[MAXIMUM_LAYOUT_ELEMENTS];
+ unsigned element_count = 0;
+ unsigned stride = 0;
+ CHECK(DX11Layout_From_FVF(PIPELINE_FVF, elements, element_count, stride));
+ CHECK_EQ(stride, sizeof(PipelineVertex));
+
+ ID3D11InputLayout * layout = NULL;
+ CHECK(SUCCEEDED(d3d->CreateInputLayout(elements, element_count,
+ vertex_code->GetBufferPointer(), vertex_code->GetBufferSize(), &layout)));
+
+ // A quad covering the target, already in clip space, which the identity transforms below leave
+ // where it is.
+ const PipelineVertex vertices[4] = {
+ { { -1.0f, -1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f }, VERTEX_COLOUR, { 0.0f, 0.0f }, { 0.0f, 0.0f } },
+ { { -1.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f }, VERTEX_COLOUR, { 0.0f, 0.0f }, { 0.0f, 0.0f } },
+ { { 1.0f, -1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f }, VERTEX_COLOUR, { 0.0f, 0.0f }, { 0.0f, 0.0f } },
+ { { 1.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f }, VERTEX_COLOUR, { 0.0f, 0.0f }, { 0.0f, 0.0f } }
+ };
+
+ D3D11_BUFFER_DESC vertex_buffer_description;
+ memset(&vertex_buffer_description, 0, sizeof(vertex_buffer_description));
+ vertex_buffer_description.ByteWidth = sizeof(vertices);
+ vertex_buffer_description.Usage = D3D11_USAGE_IMMUTABLE;
+ vertex_buffer_description.BindFlags = D3D11_BIND_VERTEX_BUFFER;
+
+ D3D11_SUBRESOURCE_DATA vertex_data;
+ memset(&vertex_data, 0, sizeof(vertex_data));
+ vertex_data.pSysMem = vertices;
+
+ ID3D11Buffer * vertex_buffer = NULL;
+ CHECK(SUCCEEDED(d3d->CreateBuffer(&vertex_buffer_description, &vertex_data, &vertex_buffer)));
+
+ VertexConstants vertex_constants;
+ memset(&vertex_constants, 0, sizeof(vertex_constants));
+ set_identity(vertex_constants.WorldViewProjection);
+ set_identity(vertex_constants.WorldView);
+ set_identity(vertex_constants.NormalTransform);
+ set_identity(vertex_constants.TextureMatrix0);
+ set_identity(vertex_constants.TextureMatrix1);
+
+ D3D11_BUFFER_DESC constant_buffer_description;
+ memset(&constant_buffer_description, 0, sizeof(constant_buffer_description));
+ constant_buffer_description.ByteWidth = sizeof(VertexConstants);
+ constant_buffer_description.Usage = D3D11_USAGE_IMMUTABLE;
+ constant_buffer_description.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
+
+ D3D11_SUBRESOURCE_DATA constant_data;
+ memset(&constant_data, 0, sizeof(constant_data));
+ constant_data.pSysMem = &vertex_constants;
+
+ ID3D11Buffer * vertex_constant_buffer = NULL;
+ CHECK(SUCCEEDED(d3d->CreateBuffer(&constant_buffer_description, &constant_data,
+ &vertex_constant_buffer)));
+
+ PixelConstants pixel_constants;
+ memset(&pixel_constants, 0, sizeof(pixel_constants));
+
+ constant_buffer_description.ByteWidth = sizeof(PixelConstants);
+ constant_data.pSysMem = &pixel_constants;
+
+ ID3D11Buffer * pixel_constant_buffer = NULL;
+ CHECK(SUCCEEDED(d3d->CreateBuffer(&constant_buffer_description, &constant_data,
+ &pixel_constant_buffer)));
+
+ // The render states this draw would have set under D3D9, translated. No depth buffer is bound,
+ // so the depth test is off; the quad is drawn from both sides so its winding cannot decide the
+ // answer.
+ DX11StateBlockClass states;
+ states.Set_Render_State(D3DRS_ZENABLE, D3DZB_FALSE);
+ states.Set_Render_State(D3DRS_ZWRITEENABLE, FALSE);
+ states.Set_Render_State(D3DRS_CULLMODE, D3DCULL_NONE);
+
+ D3D11_BLEND_DESC blend_description;
+ D3D11_DEPTH_STENCIL_DESC depth_description;
+ D3D11_RASTERIZER_DESC rasterizer_description;
+ states.Build_Blend_Description(blend_description);
+ states.Build_Depth_Stencil_Description(depth_description);
+ states.Build_Rasterizer_Description(rasterizer_description);
+
+ ID3D11BlendState * blend_state = NULL;
+ ID3D11DepthStencilState * depth_state = NULL;
+ ID3D11RasterizerState * rasterizer_state = NULL;
+ CHECK(SUCCEEDED(d3d->CreateBlendState(&blend_description, &blend_state)));
+ CHECK(SUCCEEDED(d3d->CreateDepthStencilState(&depth_description, &depth_state)));
+ CHECK(SUCCEEDED(d3d->CreateRasterizerState(&rasterizer_description, &rasterizer_state)));
+
+ // Green, which the draw never produces, so a centre pixel that is still green is a draw that
+ // did not happen rather than one that produced the wrong colour.
+ const float clear_colour[4] = { 0.0f, 1.0f, 0.0f, 1.0f };
+ context->ClearRenderTargetView(target_view, clear_colour);
+ context->OMSetRenderTargets(1, &target_view, NULL);
+
+ D3D11_VIEWPORT viewport;
+ viewport.TopLeftX = 0.0f;
+ viewport.TopLeftY = 0.0f;
+ viewport.Width = static_cast<float>(TARGET_WIDTH);
+ viewport.Height = static_cast<float>(TARGET_HEIGHT);
+ viewport.MinDepth = 0.0f;
+ viewport.MaxDepth = 1.0f;
+ context->RSSetViewports(1, &viewport);
+
+ const UINT offset = 0;
+ const UINT vertex_stride = stride;
+ context->IASetInputLayout(layout);
+ context->IASetVertexBuffers(0, 1, &vertex_buffer, &vertex_stride, &offset);
+ context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
+ context->VSSetShader(vertex_shader, NULL, 0);
+ context->VSSetConstantBuffers(0, 1, &vertex_constant_buffer);
+ context->PSSetShader(pixel_shader, NULL, 0);
+ context->PSSetConstantBuffers(0, 1, &pixel_constant_buffer);
+ context->OMSetBlendState(blend_state, NULL, 0xffffffff);
+ context->OMSetDepthStencilState(depth_state, states.Get_Stencil_Reference());
+ context->RSSetState(rasterizer_state);
+ context->Draw(4, 0);
+
+ context->CopyResource(staging, target);
+ print_validation_messages(d3d);
+
+ D3D11_MAPPED_SUBRESOURCE mapped;
+ CHECK(SUCCEEDED(context->Map(staging, 0, D3D11_MAP_READ, 0, &mapped)));
+
+ // The middle of the target, read as the four bytes a B8G8R8A8 pixel is.
+ const unsigned char * row = static_cast<const unsigned char *>(mapped.pData)
+ + mapped.RowPitch * (TARGET_HEIGHT / 2);
+ const unsigned char * pixel = row + (TARGET_WIDTH / 2) * 4;
+ if (pixel[0] != EXPECTED_BLUE || pixel[2] != EXPECTED_RED) {
+ printf(" centre pixel bgra %02x %02x %02x %02x\n", pixel[0], pixel[1], pixel[2], pixel[3]);
+ printf("---- vertex ----\n%s---- pixel ----\n%s----\n", vertex_hlsl.c_str(),
+ pixel_hlsl.c_str());
+ }
+ CHECK_EQ(pixel[0], EXPECTED_BLUE);
+ CHECK_EQ(pixel[1], EXPECTED_GREEN);
+ CHECK_EQ(pixel[2], EXPECTED_RED);
+ CHECK_EQ(pixel[3], EXPECTED_ALPHA);
+
+ // The quad covers the whole target, so a corner has to say the same thing. A draw that covered
+ // only part of it would pass at the centre and be wrong everywhere else, which is what a
+ // mistranslated position or a dropped triangle looks like.
+ const unsigned char * corner = static_cast<const unsigned char *>(mapped.pData);
+ CHECK_EQ(corner[0], EXPECTED_BLUE);
+ CHECK_EQ(corner[2], EXPECTED_RED);
+
+ context->Unmap(staging, 0);
+
+ pixel_constant_buffer->Release();
+ vertex_constant_buffer->Release();
+ vertex_buffer->Release();
+ rasterizer_state->Release();
+ depth_state->Release();
+ blend_state->Release();
+ layout->Release();
+ pixel_shader->Release();
+ vertex_shader->Release();
+ pixel_code->Release();
+ vertex_code->Release();
+ target_view->Release();
+ staging->Release();
+ target->Release();
+}
diff --git a/GeneralsMD/Code/Tests/test_dx11resource.cpp b/GeneralsMD/Code/Tests/test_dx11resource.cpp
new file mode 100644
index 000000000..858fd40cc
--- /dev/null
+++ b/GeneralsMD/Code/Tests/test_dx11resource.cpp
@@ -0,0 +1,231 @@
+/*
+** 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 buffers and textures, translated and then actually created.
+//
+// Half of this is a table and is checked as one. The other half is D3D11 refusing combinations
+// that look reasonable - a dynamic buffer with no CPU write access, a staging texture bound as a
+// shader resource, a render target in anything but the default pool - and the only way to know the
+// translation produces legal ones is to hand them to a device and see.
+
+#include "test_harness.h"
+
+#include "dx11device.h"
+#include "dx11resource.h"
+
+static const unsigned BUFFER_BYTES = 4096;
+static const unsigned TEXTURE_SIZE = 32;
+static const unsigned ONE_MIP_LEVEL = 1;
+
+TEST(dx11resource_a_d3d9_colour_format_reverses_into_its_dxgi_name)
+{
+ // D3D9 names the channels most significant byte first, DXGI least significant first, so the
+ // same four bytes are an A8R8G8B8 in one and a B8G8R8A8 in the other.
+ CHECK_EQ(DX11Resource_Translate_Format(D3DFMT_A8R8G8B8), DXGI_FORMAT_B8G8R8A8_UNORM);
+ CHECK_EQ(DX11Resource_Translate_Format(D3DFMT_X8R8G8B8), DXGI_FORMAT_B8G8R8A8_UNORM);
+ CHECK_EQ(DX11Resource_Translate_Format(D3DFMT_R5G6B5), DXGI_FORMAT_B5G6R5_UNORM);
+ CHECK_EQ(DX11Resource_Translate_Format(D3DFMT_A1R5G5B5), DXGI_FORMAT_B5G5R5A1_UNORM);
+ CHECK_EQ(DX11Resource_Translate_Format(D3DFMT_A4R4G4B4), DXGI_FORMAT_B4G4R4A4_UNORM);
+ CHECK_EQ(DX11Resource_Translate_Format(D3DFMT_A8), DXGI_FORMAT_A8_UNORM);
+}
+
+// DXT2 and DXT4 are DXT3 and DXT5 with the colour already multiplied by the alpha. That is a
+// property of the bytes, not of the layout, so they share a DXGI name with the format they
+// premultiply and nothing about the blocks changes.
+TEST(dx11resource_the_compressed_formats_map_onto_four_block_types)
+{
+ CHECK_EQ(DX11Resource_Translate_Format(D3DFMT_DXT1), DXGI_FORMAT_BC1_UNORM);
+ CHECK_EQ(DX11Resource_Translate_Format(D3DFMT_DXT2), DXGI_FORMAT_BC2_UNORM);
+ CHECK_EQ(DX11Resource_Translate_Format(D3DFMT_DXT3), DXGI_FORMAT_BC2_UNORM);
+ CHECK_EQ(DX11Resource_Translate_Format(D3DFMT_DXT4), DXGI_FORMAT_BC3_UNORM);
+ CHECK_EQ(DX11Resource_Translate_Format(D3DFMT_DXT5), DXGI_FORMAT_BC3_UNORM);
+}
+
+// D3D11 has no palette. A palettised texture has to be expanded before it gets here, and saying
+// so is better than handing back a format that would draw the indices as shades of grey.
+TEST(dx11resource_a_palettised_format_has_no_translation)
+{
+ CHECK_EQ(DX11Resource_Translate_Format(D3DFMT_P8), DXGI_FORMAT_UNKNOWN);
+ CHECK_EQ(DX11Resource_Translate_Format(D3DFMT_A8P8), DXGI_FORMAT_UNKNOWN);
+}
+
+// Two translations lose something the caller has to know about: an X format gains an alpha channel
+// that used to be ignored, and a luminance texture arrives with its one channel in red.
+TEST(dx11resource_the_lossy_translations_say_so)
+{
+ CHECK(DX11Resource_Format_Needs_Swizzle(D3DFMT_X8R8G8B8));
+ CHECK(DX11Resource_Format_Needs_Swizzle(D3DFMT_L8));
+ CHECK_EQ(DX11Resource_Translate_Format(D3DFMT_L8), DXGI_FORMAT_R8_UNORM);
+
+ CHECK(!DX11Resource_Format_Needs_Swizzle(D3DFMT_A8R8G8B8));
+ CHECK(!DX11Resource_Format_Needs_Swizzle(D3DFMT_DXT5));
+}
+
+TEST(dx11resource_a_pool_and_a_usage_bit_become_a_usage_and_an_access_mask)
+{
+ D3D11_USAGE usage = D3D11_USAGE_DEFAULT;
+ UINT cpu_access = 0;
+ UINT bind = 0;
+
+ // The managed pool is a resource the CPU fills once and the device reads from then on.
+ CHECK(DX11Resource_Translate_Usage(D3DPOOL_MANAGED, 0, usage, cpu_access, bind));
+ CHECK_EQ(usage, D3D11_USAGE_DEFAULT);
+ CHECK_EQ(cpu_access, 0u);
+
+ // The dynamic bit is the one the vertex buffers are refilled through every frame.
+ CHECK(DX11Resource_Translate_Usage(D3DPOOL_DEFAULT, D3DUSAGE_DYNAMIC|D3DUSAGE_WRITEONLY,
+ usage, cpu_access, bind));
+ CHECK_EQ(usage, D3D11_USAGE_DYNAMIC);
+ CHECK_EQ(cpu_access, (UINT)D3D11_CPU_ACCESS_WRITE);
+
+ // System memory is where a surface the CPU reads back out of lives, and staging is the only
+ // D3D11 usage the CPU can both read and write.
+ CHECK(DX11Resource_Translate_Usage(D3DPOOL_SYSTEMMEM, 0, usage, cpu_access, bind));
+ CHECK_EQ(usage, D3D11_USAGE_STAGING);
+ CHECK_EQ(cpu_access, (UINT)(D3D11_CPU_ACCESS_READ|D3D11_CPU_ACCESS_WRITE));
+
+ // A render target is written by the device wherever D3D9 said to put it.
+ CHECK(DX11Resource_Translate_Usage(D3DPOOL_DEFAULT, D3DUSAGE_RENDERTARGET,
+ usage, cpu_access, bind));
+ CHECK_EQ(usage, D3D11_USAGE_DEFAULT);
+ CHECK_EQ(bind, (UINT)D3D11_BIND_RENDER_TARGET);
+
+ // And it cannot live anywhere else, which D3D9 would have allowed and then ignored.
+ CHECK(!DX11Resource_Translate_Usage(D3DPOOL_MANAGED, D3DUSAGE_RENDERTARGET,
+ usage, cpu_access, bind));
+}
+
+// D3D9's lock flags say what the caller intends; D3D11's map types say what the resource allows,
+// and the two only line up for some pairings. D3DLOCK_DISCARD on a resource that is not dynamic
+// is the one that would silently stall under D3D9.
+TEST(dx11resource_a_lock_flag_is_only_a_map_type_where_the_usage_allows_it)
+{
+ D3D11_MAP map_type = D3D11_MAP_READ;
+
+ CHECK(DX11Resource_Translate_Lock(D3DLOCK_DISCARD, D3D11_USAGE_DYNAMIC, map_type));
+ CHECK_EQ(map_type, D3D11_MAP_WRITE_DISCARD);
+
+ CHECK(DX11Resource_Translate_Lock(D3DLOCK_NOOVERWRITE, D3D11_USAGE_DYNAMIC, map_type));
+ CHECK_EQ(map_type, D3D11_MAP_WRITE_NO_OVERWRITE);
+
+ CHECK(DX11Resource_Translate_Lock(D3DLOCK_READONLY, D3D11_USAGE_STAGING, map_type));
+ CHECK_EQ(map_type, D3D11_MAP_READ);
+
+ CHECK(!DX11Resource_Translate_Lock(D3DLOCK_DISCARD, D3D11_USAGE_DEFAULT, map_type));
+ CHECK(!DX11Resource_Translate_Lock(D3DLOCK_READONLY, D3D11_USAGE_DYNAMIC, map_type));
+}
+
+// D3D9's "no flags" means read and write on a surface that can be read and write only on one that
+// cannot, so the same argument has two answers.
+TEST(dx11resource_no_lock_flags_means_two_different_things)
+{
+ D3D11_MAP map_type = D3D11_MAP_READ;
+
+ CHECK(DX11Resource_Translate_Lock(0, D3D11_USAGE_STAGING, map_type));
+ CHECK_EQ(map_type, D3D11_MAP_READ_WRITE);
+
+ CHECK(DX11Resource_Translate_Lock(0, D3D11_USAGE_DYNAMIC, map_type));
+ CHECK_EQ(map_type, D3D11_MAP_WRITE_DISCARD);
+
+ // A default-usage resource cannot be mapped at all.
+ CHECK(!DX11Resource_Translate_Lock(0, D3D11_USAGE_DEFAULT, map_type));
+}
+
+// The half a table cannot answer: whether D3D11 accepts what the translation produced. Each of
+// these is a combination the engine asks for.
+TEST(dx11resource_the_device_accepts_what_the_translation_produces)
+{
+ DX11DeviceClass device;
+ device.Request_Debug_Layer();
+ CHECK(device.Create_Offscreen());
+ ID3D11Device * d3d = device.Get_Device();
+
+ ID3D11Buffer * dynamic_vertices = NULL;
+ CHECK(DX11Resource_Create_Vertex_Buffer(d3d, BUFFER_BYTES, D3DPOOL_DEFAULT,
+ D3DUSAGE_DYNAMIC|D3DUSAGE_WRITEONLY, NULL, &dynamic_vertices));
+ CHECK(dynamic_vertices != NULL);
+
+ ID3D11Buffer * static_indices = NULL;
+ CHECK(DX11Resource_Create_Index_Buffer(d3d, BUFFER_BYTES, D3DPOOL_MANAGED, 0, NULL,
+ &static_indices));
+ CHECK(static_indices != NULL);
+
+ ID3D11Texture2D * texture = NULL;
+ ID3D11ShaderResourceView * view = NULL;
+ CHECK(DX11Resource_Create_Texture(d3d, TEXTURE_SIZE, TEXTURE_SIZE, ONE_MIP_LEVEL,
+ D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, 0, &texture, &view));
+ CHECK(texture != NULL);
+
+ // A texture the device can read needs the view as well. D3D9 handed out one object for both
+ // and a texture without a view here cannot be sampled however right its contents are.
+ CHECK(view != NULL);
+
+ ID3D11Texture2D * compressed = NULL;
+ ID3D11ShaderResourceView * compressed_view = NULL;
+ CHECK(DX11Resource_Create_Texture(d3d, TEXTURE_SIZE, TEXTURE_SIZE, ONE_MIP_LEVEL,
+ D3DFMT_DXT5, D3DPOOL_MANAGED, 0, &compressed, &compressed_view));
+ CHECK(compressed != NULL);
+ CHECK(compressed_view != NULL);
+
+ // A staging texture is the readback path and is bound to nothing, so it has no view.
+ ID3D11Texture2D * staging = NULL;
+ ID3D11ShaderResourceView * staging_view = NULL;
+ CHECK(DX11Resource_Create_Texture(d3d, TEXTURE_SIZE, TEXTURE_SIZE, ONE_MIP_LEVEL,
+ D3DFMT_A8R8G8B8, D3DPOOL_SYSTEMMEM, 0, &staging, &staging_view));
+ CHECK(staging != NULL);
+ CHECK(staging_view == NULL);
+
+ // A palettised texture is refused rather than created as something else.
+ ID3D11Texture2D * palettised = NULL;
+ ID3D11ShaderResourceView * palettised_view = NULL;
+ CHECK(!DX11Resource_Create_Texture(d3d, TEXTURE_SIZE, TEXTURE_SIZE, ONE_MIP_LEVEL,
+ D3DFMT_P8, D3DPOOL_MANAGED, 0, &palettised, &palettised_view));
+ CHECK(palettised == NULL);
+
+ staging->Release();
+ compressed_view->Release();
+ compressed->Release();
+ view->Release();
+ texture->Release();
+ static_indices->Release();
+ dynamic_vertices->Release();
+}
+
+// The thing the dynamic vertex buffers do every frame: throw the contents away and write the whole
+// buffer again. It is the one path in the engine where a wrong map type costs a stall a frame
+// rather than a wrong picture, so nothing on screen would ever show it.
+TEST(dx11resource_a_dynamic_buffer_takes_the_discarding_map)
+{
+ DX11DeviceClass device;
+ device.Request_Debug_Layer();
+ CHECK(device.Create_Offscreen());
+
+ ID3D11Buffer * buffer = NULL;
+ CHECK(DX11Resource_Create_Vertex_Buffer(device.Get_Device(), BUFFER_BYTES, D3DPOOL_DEFAULT,
+ D3DUSAGE_DYNAMIC|D3DUSAGE_WRITEONLY, NULL, &buffer));
+
+ D3D11_MAP map_type = D3D11_MAP_READ;
+ CHECK(DX11Resource_Translate_Lock(D3DLOCK_DISCARD, D3D11_USAGE_DYNAMIC, map_type));
+
+ D3D11_MAPPED_SUBRESOURCE mapped;
+ CHECK(SUCCEEDED(device.Get_Context()->Map(buffer, 0, map_type, 0, &mapped)));
+ CHECK(mapped.pData != NULL);
+ device.Get_Context()->Unmap(buffer, 0);
+
+ buffer->Release();
+}
diff --git a/GeneralsMD/Code/Tests/test_dx11state.cpp b/GeneralsMD/Code/Tests/test_dx11state.cpp
new file mode 100644
index 000000000..abfee22f1
--- /dev/null
+++ b/GeneralsMD/Code/Tests/test_dx11state.cpp
@@ -0,0 +1,269 @@
+/*
+** 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 render state translation, walked end to end. Every one of these is a pair of numbers that
+// look nothing like each other, a mistake in one is a single wrong-looking pass somewhere in a
+// frame, and there is no way to read a rasteriser state object back out of D3D11 and see what it
+// says. So the table is checked here rather than on screen.
+
+#include "test_harness.h"
+
+#include "dx11state.h"
+
+// The states the engine actually sets, taken from -ffprobe's dump rather than from the header: the
+// most used blend pair in the game is SRCALPHA over INVSRCALPHA, and the second is ONE over
+// INVSRCALPHA.
+static const DWORD MEASURED_SOURCE_BLEND = D3DBLEND_SRCALPHA;
+static const DWORD MEASURED_DESTINATION_BLEND = D3DBLEND_INVSRCALPHA;
+
+TEST(dx11state_a_fresh_block_describes_the_device_d3d9_starts_with)
+{
+ DX11StateBlockClass block;
+
+ D3D11_DEPTH_STENCIL_DESC depth;
+ block.Build_Depth_Stencil_Description(depth);
+ CHECK_EQ(depth.DepthEnable, TRUE);
+ CHECK_EQ(depth.DepthWriteMask, D3D11_DEPTH_WRITE_MASK_ALL);
+ CHECK_EQ(depth.DepthFunc, D3D11_COMPARISON_LESS_EQUAL);
+ CHECK_EQ(depth.StencilEnable, FALSE);
+
+ D3D11_BLEND_DESC blend;
+ block.Build_Blend_Description(blend);
+ CHECK_EQ(blend.RenderTarget[0].BlendEnable, FALSE);
+ CHECK_EQ(blend.RenderTarget[0].RenderTargetWriteMask, 0x0f);
+
+ D3D11_RASTERIZER_DESC raster;
+ block.Build_Rasterizer_Description(raster);
+ CHECK_EQ(raster.FillMode, D3D11_FILL_SOLID);
+ CHECK_EQ(raster.CullMode, D3D11_CULL_BACK);
+ CHECK_EQ(raster.FrontCounterClockwise, FALSE);
+}
+
+TEST(dx11state_the_blend_the_game_uses_most_translates)
+{
+ DX11StateBlockClass block;
+ block.Set_Render_State(D3DRS_ALPHABLENDENABLE, TRUE);
+ block.Set_Render_State(D3DRS_SRCBLEND, MEASURED_SOURCE_BLEND);
+ block.Set_Render_State(D3DRS_DESTBLEND, MEASURED_DESTINATION_BLEND);
+
+ D3D11_BLEND_DESC blend;
+ block.Build_Blend_Description(blend);
+ CHECK_EQ(blend.RenderTarget[0].BlendEnable, TRUE);
+ CHECK_EQ(blend.RenderTarget[0].SrcBlend, D3D11_BLEND_SRC_ALPHA);
+ CHECK_EQ(blend.RenderTarget[0].DestBlend, D3D11_BLEND_INV_SRC_ALPHA);
+ CHECK_EQ(blend.RenderTarget[0].BlendOp, D3D11_BLEND_OP_ADD);
+
+ // D3D9 blends alpha with the colour terms unless told otherwise, and it is never told
+ // otherwise here, so a description whose alpha terms drifted apart is wrong.
+ CHECK_EQ(blend.RenderTarget[0].SrcBlendAlpha, blend.RenderTarget[0].SrcBlend);
+ CHECK_EQ(blend.RenderTarget[0].DestBlendAlpha, blend.RenderTarget[0].DestBlend);
+}
+
+TEST(dx11state_every_blend_factor_has_a_translation)
+{
+ CHECK_EQ(DX11State_Translate_Blend(D3DBLEND_ZERO), D3D11_BLEND_ZERO);
+ CHECK_EQ(DX11State_Translate_Blend(D3DBLEND_ONE), D3D11_BLEND_ONE);
+ CHECK_EQ(DX11State_Translate_Blend(D3DBLEND_SRCCOLOR), D3D11_BLEND_SRC_COLOR);
+ CHECK_EQ(DX11State_Translate_Blend(D3DBLEND_INVSRCCOLOR), D3D11_BLEND_INV_SRC_COLOR);
+ CHECK_EQ(DX11State_Translate_Blend(D3DBLEND_SRCALPHA), D3D11_BLEND_SRC_ALPHA);
+ CHECK_EQ(DX11State_Translate_Blend(D3DBLEND_INVSRCALPHA), D3D11_BLEND_INV_SRC_ALPHA);
+ CHECK_EQ(DX11State_Translate_Blend(D3DBLEND_DESTALPHA), D3D11_BLEND_DEST_ALPHA);
+ CHECK_EQ(DX11State_Translate_Blend(D3DBLEND_INVDESTALPHA), D3D11_BLEND_INV_DEST_ALPHA);
+ CHECK_EQ(DX11State_Translate_Blend(D3DBLEND_DESTCOLOR), D3D11_BLEND_DEST_COLOR);
+ CHECK_EQ(DX11State_Translate_Blend(D3DBLEND_INVDESTCOLOR), D3D11_BLEND_INV_DEST_COLOR);
+ CHECK_EQ(DX11State_Translate_Blend(D3DBLEND_SRCALPHASAT), D3D11_BLEND_SRC_ALPHA_SAT);
+}
+
+TEST(dx11state_every_comparison_has_a_translation)
+{
+ CHECK_EQ(DX11State_Translate_Comparison(D3DCMP_NEVER), D3D11_COMPARISON_NEVER);
+ CHECK_EQ(DX11State_Translate_Comparison(D3DCMP_LESS), D3D11_COMPARISON_LESS);
+ CHECK_EQ(DX11State_Translate_Comparison(D3DCMP_EQUAL), D3D11_COMPARISON_EQUAL);
+ CHECK_EQ(DX11State_Translate_Comparison(D3DCMP_LESSEQUAL), D3D11_COMPARISON_LESS_EQUAL);
+ CHECK_EQ(DX11State_Translate_Comparison(D3DCMP_GREATER), D3D11_COMPARISON_GREATER);
+ CHECK_EQ(DX11State_Translate_Comparison(D3DCMP_NOTEQUAL), D3D11_COMPARISON_NOT_EQUAL);
+ CHECK_EQ(DX11State_Translate_Comparison(D3DCMP_GREATEREQUAL), D3D11_COMPARISON_GREATER_EQUAL);
+ CHECK_EQ(DX11State_Translate_Comparison(D3DCMP_ALWAYS), D3D11_COMPARISON_ALWAYS);
+}
+
+TEST(dx11state_every_stencil_operation_has_a_translation)
+{
+ CHECK_EQ(DX11State_Translate_Stencil_Operation(D3DSTENCILOP_KEEP), D3D11_STENCIL_OP_KEEP);
+ CHECK_EQ(DX11State_Translate_Stencil_Operation(D3DSTENCILOP_ZERO), D3D11_STENCIL_OP_ZERO);
+ CHECK_EQ(DX11State_Translate_Stencil_Operation(D3DSTENCILOP_REPLACE), D3D11_STENCIL_OP_REPLACE);
+ CHECK_EQ(DX11State_Translate_Stencil_Operation(D3DSTENCILOP_INCRSAT), D3D11_STENCIL_OP_INCR_SAT);
+ CHECK_EQ(DX11State_Translate_Stencil_Operation(D3DSTENCILOP_DECRSAT), D3D11_STENCIL_OP_DECR_SAT);
+ CHECK_EQ(DX11State_Translate_Stencil_Operation(D3DSTENCILOP_INVERT), D3D11_STENCIL_OP_INVERT);
+ CHECK_EQ(DX11State_Translate_Stencil_Operation(D3DSTENCILOP_INCR), D3D11_STENCIL_OP_INCR);
+ CHECK_EQ(DX11State_Translate_Stencil_Operation(D3DSTENCILOP_DECR), D3D11_STENCIL_OP_DECR);
+}
+
+// The shadow volumes are the reason the stencil half of the depth buffer is there, and they are
+// the one thing in the game that sets every stencil state at once. This is that pass.
+TEST(dx11state_the_shadow_volume_stencil_pass_translates_whole)
+{
+ DX11StateBlockClass block;
+ block.Set_Render_State(D3DRS_STENCILENABLE, TRUE);
+ block.Set_Render_State(D3DRS_STENCILFUNC, D3DCMP_ALWAYS);
+ block.Set_Render_State(D3DRS_STENCILFAIL, D3DSTENCILOP_KEEP);
+ block.Set_Render_State(D3DRS_STENCILZFAIL, D3DSTENCILOP_INCR);
+ block.Set_Render_State(D3DRS_STENCILPASS, D3DSTENCILOP_KEEP);
+ block.Set_Render_State(D3DRS_STENCILREF, 1);
+ block.Set_Render_State(D3DRS_STENCILMASK, 0xff);
+ block.Set_Render_State(D3DRS_STENCILWRITEMASK, 0xff);
+ block.Set_Render_State(D3DRS_ZWRITEENABLE, FALSE);
+
+ D3D11_DEPTH_STENCIL_DESC depth;
+ block.Build_Depth_Stencil_Description(depth);
+ CHECK_EQ(depth.StencilEnable, TRUE);
+ CHECK_EQ(depth.StencilReadMask, 0xff);
+ CHECK_EQ(depth.StencilWriteMask, 0xff);
+ CHECK_EQ(depth.DepthWriteMask, D3D11_DEPTH_WRITE_MASK_ZERO);
+ CHECK_EQ(depth.FrontFace.StencilDepthFailOp, D3D11_STENCIL_OP_INCR);
+ CHECK_EQ(depth.FrontFace.StencilFunc, D3D11_COMPARISON_ALWAYS);
+
+ // D3D9 applies one set of operations to whichever side survived the cull, so both D3D11 faces
+ // have to carry it. A back face left at its defaults keeps the stencil untouched on that side.
+ CHECK_EQ(depth.BackFace.StencilDepthFailOp, D3D11_STENCIL_OP_INCR);
+
+ // The reference is a bind argument, not a field of the description.
+ CHECK_EQ(block.Get_Stencil_Reference(), 1u);
+}
+
+// D3D9 names the side it throws away, D3D11 names the side it keeps, and both call a clockwise
+// triangle the front one. Getting this backwards turns every model inside out, which is the kind
+// of mistake that is obvious on screen and impossible to find in a diff.
+TEST(dx11state_culling_keeps_the_same_side_it_kept_under_d3d9)
+{
+ CHECK_EQ(DX11State_Translate_Cull_Mode(D3DCULL_NONE), D3D11_CULL_NONE);
+ CHECK_EQ(DX11State_Translate_Cull_Mode(D3DCULL_CCW), D3D11_CULL_BACK);
+ CHECK_EQ(DX11State_Translate_Cull_Mode(D3DCULL_CW), D3D11_CULL_FRONT);
+}
+
+TEST(dx11state_wireframe_survives_and_point_fill_does_not)
+{
+ CHECK_EQ(DX11State_Translate_Fill_Mode(D3DFILL_SOLID), D3D11_FILL_SOLID);
+ CHECK_EQ(DX11State_Translate_Fill_Mode(D3DFILL_WIREFRAME), D3D11_FILL_WIREFRAME);
+
+ // D3D11 has no point fill. Nothing in the engine asks for one, and drawing solid is a picture
+ // where refusing the state object would be a black screen.
+ CHECK_EQ(DX11State_Translate_Fill_Mode(D3DFILL_POINT), D3D11_FILL_SOLID);
+}
+
+TEST(dx11state_the_colour_write_mask_carries_across_unchanged)
+{
+ DX11StateBlockClass block;
+ block.Set_Render_State(D3DRS_COLORWRITEENABLE,
+ D3DCOLORWRITEENABLE_RED | D3DCOLORWRITEENABLE_ALPHA);
+
+ D3D11_BLEND_DESC blend;
+ block.Build_Blend_Description(blend);
+ CHECK_EQ(blend.RenderTarget[0].RenderTargetWriteMask,
+ D3D11_COLOR_WRITE_ENABLE_RED | D3D11_COLOR_WRITE_ENABLE_ALPHA);
+}
+
+// D3DRS_TEXTUREFACTOR is a packed ARGB colour and the shader wants four floats in RGBA order. The
+// tree shadow pass reads it for its colour and its alpha both, so a swapped pair there is a shadow
+// of the wrong colour rather than a compile error.
+TEST(dx11state_the_texture_factor_unpacks_argb_into_rgba)
+{
+ DX11StateBlockClass block;
+ block.Set_Render_State(D3DRS_TEXTUREFACTOR, 0x20406080);
+
+ float factor[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
+ block.Get_Texture_Factor(factor);
+ CHECK_NEAR(factor[0], 0x40 / 255.0f, 0.0001f);
+ CHECK_NEAR(factor[1], 0x60 / 255.0f, 0.0001f);
+ CHECK_NEAR(factor[2], 0x80 / 255.0f, 0.0001f);
+ CHECK_NEAR(factor[3], 0x20 / 255.0f, 0.0001f);
+}
+
+// D3D9's three filter states are one D3D11_FILTER, and the mapping is a bit each rather than a
+// name each. The two the engine sets on almost every draw are point everywhere and linear
+// everywhere; the third is the anisotropic one the detail setting turns on.
+TEST(dx11state_the_three_filter_states_become_one_filter)
+{
+ CHECK_EQ(DX11State_Translate_Filter(D3DTEXF_POINT, D3DTEXF_POINT, D3DTEXF_NONE),
+ D3D11_FILTER_MIN_MAG_MIP_POINT);
+ CHECK_EQ(DX11State_Translate_Filter(D3DTEXF_LINEAR, D3DTEXF_LINEAR, D3DTEXF_LINEAR),
+ D3D11_FILTER_MIN_MAG_MIP_LINEAR);
+ CHECK_EQ(DX11State_Translate_Filter(D3DTEXF_LINEAR, D3DTEXF_LINEAR, D3DTEXF_POINT),
+ D3D11_FILTER_MIN_MAG_LINEAR_MIP_POINT);
+ CHECK_EQ(DX11State_Translate_Filter(D3DTEXF_POINT, D3DTEXF_LINEAR, D3DTEXF_NONE),
+ D3D11_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT);
+
+ // One anisotropic state makes the whole sampler anisotropic, whatever the other two say.
+ CHECK_EQ(DX11State_Translate_Filter(D3DTEXF_ANISOTROPIC, D3DTEXF_POINT, D3DTEXF_NONE),
+ D3D11_FILTER_ANISOTROPIC);
+}
+
+TEST(dx11state_every_address_mode_has_a_translation)
+{
+ CHECK_EQ(DX11State_Translate_Address_Mode(D3DTADDRESS_WRAP), D3D11_TEXTURE_ADDRESS_WRAP);
+ CHECK_EQ(DX11State_Translate_Address_Mode(D3DTADDRESS_MIRROR), D3D11_TEXTURE_ADDRESS_MIRROR);
+ CHECK_EQ(DX11State_Translate_Address_Mode(D3DTADDRESS_CLAMP), D3D11_TEXTURE_ADDRESS_CLAMP);
+ CHECK_EQ(DX11State_Translate_Address_Mode(D3DTADDRESS_BORDER), D3D11_TEXTURE_ADDRESS_BORDER);
+ CHECK_EQ(DX11State_Translate_Address_Mode(D3DTADDRESS_MIRRORONCE),
+ D3D11_TEXTURE_ADDRESS_MIRROR_ONCE);
+}
+
+// The sampler the terrain sets: linear everywhere, clamped in both directions so the edge of a tile
+// does not fetch the far side of it.
+TEST(dx11state_a_clamped_linear_sampler_translates_whole)
+{
+ DX11SamplerBlockClass sampler;
+ sampler.Set_Sampler_State(D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
+ sampler.Set_Sampler_State(D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
+ sampler.Set_Sampler_State(D3DSAMP_MIPFILTER, D3DTEXF_LINEAR);
+ sampler.Set_Sampler_State(D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP);
+ sampler.Set_Sampler_State(D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP);
+
+ D3D11_SAMPLER_DESC description;
+ sampler.Build_Sampler_Description(description);
+ CHECK_EQ(description.Filter, D3D11_FILTER_MIN_MAG_MIP_LINEAR);
+ CHECK_EQ(description.AddressU, D3D11_TEXTURE_ADDRESS_CLAMP);
+ CHECK_EQ(description.AddressV, D3D11_TEXTURE_ADDRESS_CLAMP);
+
+ // D3DSAMP_ADDRESSW is never set for a two dimensional texture and keeps its default.
+ CHECK_EQ(description.AddressW, D3D11_TEXTURE_ADDRESS_WRAP);
+}
+
+// A fresh sampler block is the device D3D9 starts with: point filtering, no mip filter, wrapping.
+TEST(dx11state_a_fresh_sampler_block_is_the_d3d9_default_sampler)
+{
+ DX11SamplerBlockClass sampler;
+
+ D3D11_SAMPLER_DESC description;
+ sampler.Build_Sampler_Description(description);
+ CHECK_EQ(description.Filter, D3D11_FILTER_MIN_MAG_MIP_POINT);
+ CHECK_EQ(description.AddressU, D3D11_TEXTURE_ADDRESS_WRAP);
+ CHECK_EQ(description.MaxAnisotropy, 1u);
+}
+
+// A state above the block's range is one D3D11 has nowhere to put anyway. Writing it must not
+// walk off the end of the array, and reading it back reads zero rather than whatever was there.
+TEST(dx11state_a_state_outside_the_block_is_dropped_not_written_past_the_end)
+{
+ DX11StateBlockClass block;
+ const D3DRENDERSTATETYPE beyond = static_cast<D3DRENDERSTATETYPE>(RENDER_STATE_COUNT + 8);
+ block.Set_Render_State(beyond, 0x1234);
+ CHECK_EQ(block.Get_Render_State(beyond), 0u);
+
+ // Nothing in range moved.
+ CHECK_EQ(block.Get_Render_State(D3DRS_ZFUNC), (DWORD)D3DCMP_LESSEQUAL);
+}
diff --git a/GeneralsMD/Code/Tests/test_ffshader.cpp b/GeneralsMD/Code/Tests/test_ffshader.cpp
index f66a7e087..f58b84473 100644
--- a/GeneralsMD/Code/Tests/test_ffshader.cpp
+++ b/GeneralsMD/Code/Tests/test_ffshader.cpp
@@ -49,19 +49,34 @@ static bool contains(const std::string & text, const char * fragment)
return text.find(fragment) != std::string::npos;
}
-// 22.8% of every draw call measured: one stage, SELECTARG1 on the texture, coordinate set 2.
+// 22.8% of every draw call measured: one stage, SELECTARG1 on the texture, and a coordinate index
+// of 0x20000 - D3DTSS_TCI_CAMERASPACEPOSITION. The vertex pipeline computes the coordinate and
+// leaves it in the asking stage's register, which for stage 0 is TexCoord0.
TEST(ffshader_the_most_used_combination_selects_the_texture)
{
CombinerDescription description;
description.StageCount = 1;
description.Stages[0] = one_stage(D3DTOP_SELECTARG1, D3DTA_TEXTURE, D3DTA_CURRENT,
- D3DTOP_SELECTARG1, D3DTA_TEXTURE, D3DTA_CURRENT, 131072 | 2, true);
+ D3DTOP_SELECTARG1, D3DTA_TEXTURE, D3DTA_CURRENT, D3DTSS_TCI_CAMERASPACEPOSITION, true);
std::string hlsl;
- CHECK(CombinerShader_Generate(description, hlsl));
- CHECK(contains(hlsl, "texel = tex2D(Sampler0, input.TexCoord2)"));
- CHECK(contains(hlsl, "current.rgb = texel.rgb"));
- CHECK(contains(hlsl, "current.a = texel.a"));
+ CHECK(CombinerShader_Generate(description, COMBINER_SHADER_TARGET_D3D9, hlsl));
+ CHECK(contains(hlsl, "texel = tex2D(Sampler0, input.TexCoord0)"));
+ CHECK(contains(hlsl, "current.rgb = saturate(texel).rgb"));
+ CHECK(contains(hlsl, "current.a = saturate(texel).a"));
+}
+
+// The shader declares two coordinate sets, which is every one the measured maps use. A third is a
+// refusal, not a sample out of a register the shader never declared.
+TEST(ffshader_refuses_a_coordinate_set_it_does_not_declare)
+{
+ CombinerDescription description;
+ description.StageCount = 1;
+ description.Stages[0] = one_stage(D3DTOP_SELECTARG1, D3DTA_TEXTURE, D3DTA_CURRENT,
+ D3DTOP_SELECTARG1, D3DTA_TEXTURE, D3DTA_CURRENT, 2, true);
+
+ std::string hlsl;
+ CHECK(!CombinerShader_Generate(description, COMBINER_SHADER_TARGET_D3D9, hlsl));
}
// The second most used: MODULATE of the texture against the diffuse colour.
@@ -73,9 +88,9 @@ TEST(ffshader_modulate_multiplies_texture_by_diffuse)
D3DTOP_MODULATE, D3DTA_TEXTURE, D3DTA_DIFFUSE, 0, true);
std::string hlsl;
- CHECK(CombinerShader_Generate(description, hlsl));
- CHECK(contains(hlsl, "(texel * input.Diffuse).rgb"));
- CHECK(contains(hlsl, "(texel * input.Diffuse).a"));
+ CHECK(CombinerShader_Generate(description, COMBINER_SHADER_TARGET_D3D9, hlsl));
+ CHECK(contains(hlsl, "saturate((texel * input.Diffuse)).rgb"));
+ CHECK(contains(hlsl, "saturate((texel * input.Diffuse)).a"));
}
// A stage with nothing bound still reads D3DTA_TEXTURE, and the generator has to put something
@@ -88,11 +103,31 @@ TEST(ffshader_an_unbound_stage_samples_opaque_white)
D3DTOP_SELECTARG1, D3DTA_TEXTURE, D3DTA_CURRENT, 0, false);
std::string hlsl;
- CHECK(CombinerShader_Generate(description, hlsl));
+ CHECK(CombinerShader_Generate(description, COMBINER_SHADER_TARGET_D3D9, hlsl));
CHECK(contains(hlsl, "texel = float4(1.0, 1.0, 1.0, 1.0)"));
CHECK(!contains(hlsl, "tex2D"));
}
+// Every program declares the full input signature, including registers it never reads. The tree
+// shadow pass is the case that settled it: black texture factor for the colour, the texture's own
+// alpha against the factor's for the alpha, no diffuse and no specular anywhere in it, drawn with
+// Trees.vso bound. Cutting the signature down to what the body names took Flash Effect at frame
+// 400 from 0.25% different against the fixed-function frame to 1.20%.
+TEST(ffshader_declares_the_full_input_signature)
+{
+ CombinerDescription description;
+ description.StageCount = 1;
+ description.Stages[0] = one_stage(D3DTOP_SELECTARG1, D3DTA_TFACTOR, D3DTA_DIFFUSE,
+ D3DTOP_MODULATE, D3DTA_TEXTURE, D3DTA_TFACTOR, 0, true);
+
+ std::string hlsl;
+ CHECK(CombinerShader_Generate(description, COMBINER_SHADER_TARGET_D3D9, hlsl));
+ CHECK(contains(hlsl, "float4 Diffuse : COLOR0;"));
+ CHECK(contains(hlsl, "float4 Specular : COLOR1;"));
+ CHECK(contains(hlsl, "float2 TexCoord0 : TEXCOORD0;"));
+ CHECK(contains(hlsl, "float2 TexCoord1 : TEXCOORD1;"));
+}
+
// The two-stage shroud pass: MULTIPLYADD against an alpha-replicated texture factor, then
// DOTPRODUCT3. This is the only measured combination that uses either operation.
TEST(ffshader_two_stages_with_multiplyadd_and_dotproduct)
@@ -106,7 +141,7 @@ TEST(ffshader_two_stages_with_multiplyadd_and_dotproduct)
D3DTOP_SELECTARG1, D3DTA_TEXTURE, D3DTA_CURRENT, 1, false);
std::string hlsl;
- CHECK(CombinerShader_Generate(description, hlsl));
+ CHECK(CombinerShader_Generate(description, COMBINER_SHADER_TARGET_D3D9, hlsl));
CHECK(contains(hlsl, "(input.Diffuse + texel * (TextureFactor).aaaa)"));
CHECK(contains(hlsl, "saturate(dot("));
}
@@ -122,9 +157,9 @@ TEST(ffshader_argument_modifiers_replicate_before_complementing)
D3DTOP_SELECTARG1, D3DTA_TEXTURE | D3DTA_COMPLEMENT, D3DTA_CURRENT, 0, true);
std::string hlsl;
- CHECK(CombinerShader_Generate(description, hlsl));
- CHECK(contains(hlsl, "(1.0 - (texel).aaaa).rgb"));
- CHECK(contains(hlsl, "(1.0 - texel).a"));
+ CHECK(CombinerShader_Generate(description, COMBINER_SHADER_TARGET_D3D9, hlsl));
+ CHECK(contains(hlsl, "saturate((1.0 - (texel).aaaa)).rgb"));
+ CHECK(contains(hlsl, "saturate((1.0 - texel)).a"));
}
// An operation the generator does not write has to be refused, not guessed at: the caller keeps
@@ -137,7 +172,7 @@ TEST(ffshader_refuses_an_operation_it_does_not_generate)
D3DTOP_SELECTARG1, D3DTA_TEXTURE, D3DTA_CURRENT, 0, true);
std::string hlsl;
- CHECK(!CombinerShader_Generate(description, hlsl));
+ CHECK(!CombinerShader_Generate(description, COMBINER_SHADER_TARGET_D3D9, hlsl));
}
TEST(ffshader_refuses_more_stages_than_the_game_uses)
@@ -148,7 +183,7 @@ TEST(ffshader_refuses_more_stages_than_the_game_uses)
D3DTOP_SELECTARG1, D3DTA_TEXTURE, D3DTA_CURRENT, 0, true);
std::string hlsl;
- CHECK(!CombinerShader_Generate(description, hlsl));
+ CHECK(!CombinerShader_Generate(description, COMBINER_SHADER_TARGET_D3D9, hlsl));
}
// Two descriptions that differ only in a stage past StageCount are one shader, or the cache holds
@@ -169,21 +204,157 @@ TEST(ffshader_the_key_ignores_stages_nobody_reads)
CHECK_STR(CombinerShader_Key(first).c_str(), CombinerShader_Key(second).c_str());
}
-// The coordinate generation mode rides in the high bits of D3DTSS_TEXCOORDINDEX and the coordinate
-// set in the low ones. Keying on the whole word would compile the same program twice.
+// A generating D3DTSS_TEXCOORDINDEX still reads the coordinate set its low half names, whatever
+// stage it sits on. The other reading of the documentation, routing such a stage to its own stage
+// register, was tried on the device: Flash Effect at frame 400 went from 0.25% different against
+// the fixed-function frame to 0.81%.
+TEST(ffshader_a_generated_coordinate_still_reads_the_set_it_names)
+{
+ CombinerDescription description;
+ description.StageCount = 2;
+ description.Stages[0] = one_stage(D3DTOP_SELECTARG1, D3DTA_TEXTURE, D3DTA_CURRENT,
+ D3DTOP_SELECTARG1, D3DTA_TEXTURE, D3DTA_CURRENT, 0, true);
+ description.Stages[1] = one_stage(D3DTOP_MODULATE, D3DTA_TEXTURE, D3DTA_CURRENT,
+ D3DTOP_MODULATE, D3DTA_TEXTURE, D3DTA_CURRENT, 131072, true);
+
+ std::string hlsl;
+ CHECK(CombinerShader_Generate(description, COMBINER_SHADER_TARGET_D3D9, hlsl));
+ CHECK(contains(hlsl, "tex2D(Sampler1, input.TexCoord0)"));
+ CHECK(!contains(hlsl, "tex2D(Sampler1, input.TexCoord1)"));
+}
+
+// Two stages that differ only in a generation mode are one program. Keying on the whole word
+// would compile it twice.
TEST(ffshader_the_key_reads_the_coordinate_set_not_the_generation_mode)
{
CombinerDescription plain;
plain.StageCount = 1;
plain.Stages[0] = one_stage(D3DTOP_MODULATE, D3DTA_TEXTURE, D3DTA_DIFFUSE,
- D3DTOP_MODULATE, D3DTA_TEXTURE, D3DTA_DIFFUSE, 1, true);
+ D3DTOP_MODULATE, D3DTA_TEXTURE, D3DTA_DIFFUSE, 0, true);
CombinerDescription generated = plain;
- generated.Stages[0].TextureCoordinateIndex = 131072 | 1;
+ generated.Stages[0].TextureCoordinateIndex = 131072;
CHECK_STR(CombinerShader_Key(plain).c_str(), CombinerShader_Key(generated).c_str());
}
+// Every stage of the device's combiner writes a clamped result and the next stage reads that.
+// Without the clamp a MODULATE2X above one carries the overflow forward and the frame comes out
+// brighter than the fixed-function pipeline draws it.
+TEST(ffshader_each_stage_clamps_before_the_next_one_reads_it)
+{
+ CombinerDescription description;
+ description.StageCount = 1;
+ description.Stages[0] = one_stage(D3DTOP_MODULATE2X, D3DTA_TEXTURE, D3DTA_DIFFUSE,
+ D3DTOP_MODULATE2X, D3DTA_TEXTURE, D3DTA_DIFFUSE, 0, true);
+
+ std::string hlsl;
+ CHECK(CombinerShader_Generate(description, COMBINER_SHADER_TARGET_D3D9, hlsl));
+ CHECK(contains(hlsl, "current.rgb = saturate((texel * input.Diffuse * 2.0)).rgb"));
+ CHECK(contains(hlsl, "current.a = saturate((texel * input.Diffuse * 2.0)).a"));
+}
+
+// D3D11 has no alpha test, so the comparison becomes a clip and the clip is part of the program.
+// D3D9 still applies its own around a bound pixel shader, so generating one there would apply the
+// test twice and cut a second set of pixels out of an already cut hole.
+TEST(ffshader_the_alpha_test_is_a_clip_on_d3d11_and_nothing_on_d3d9)
+{
+ CombinerDescription description;
+ memset(&description, 0, sizeof(description));
+ description.StageCount = 1;
+ description.Stages[0] = one_stage(D3DTOP_SELECTARG1, D3DTA_TEXTURE, D3DTA_CURRENT,
+ D3DTOP_SELECTARG1, D3DTA_TEXTURE, D3DTA_CURRENT, 0, true);
+ description.PixelPipeline.AlphaTestEnabled = true;
+ description.PixelPipeline.AlphaFunction = D3DCMP_GREATEREQUAL;
+
+ std::string eleven;
+ CHECK(CombinerShader_Generate(description, COMBINER_SHADER_TARGET_D3D11, eleven));
+ CHECK(contains(eleven, "clip(current.a - AlphaReference.x);"));
+
+ std::string nine;
+ CHECK(CombinerShader_Generate(description, COMBINER_SHADER_TARGET_D3D9, nine));
+ CHECK(!contains(nine, "clip("));
+ CHECK(!contains(nine, "AlphaReference"));
+}
+
+// clip throws a pixel away when its argument is negative, so each comparison is one subtraction.
+// The two about equality need a tolerance, which is a choice: D3D9 compared eight bit integers and
+// this compares floats.
+TEST(ffshader_each_alpha_comparison_becomes_its_own_clip)
+{
+ CombinerDescription description;
+ memset(&description, 0, sizeof(description));
+ description.StageCount = 1;
+ description.Stages[0] = one_stage(D3DTOP_SELECTARG1, D3DTA_TEXTURE, D3DTA_CURRENT,
+ D3DTOP_SELECTARG1, D3DTA_TEXTURE, D3DTA_CURRENT, 0, true);
+ description.PixelPipeline.AlphaTestEnabled = true;
+
+ std::string hlsl;
+
+ description.PixelPipeline.AlphaFunction = D3DCMP_LESS;
+ CHECK(CombinerShader_Generate(description, COMBINER_SHADER_TARGET_D3D11, hlsl));
+ CHECK(contains(hlsl, "clip(AlphaReference.x - current.a);"));
+
+ description.PixelPipeline.AlphaFunction = D3DCMP_EQUAL;
+ CHECK(CombinerShader_Generate(description, COMBINER_SHADER_TARGET_D3D11, hlsl));
+ CHECK(contains(hlsl, "abs(current.a - AlphaReference.x)"));
+
+ description.PixelPipeline.AlphaFunction = D3DCMP_NEVER;
+ CHECK(CombinerShader_Generate(description, COMBINER_SHADER_TARGET_D3D11, hlsl));
+ CHECK(contains(hlsl, "clip(-1.0);"));
+
+ // D3DCMP_ALWAYS keeps every pixel, which is the same program as no alpha test at all.
+ description.PixelPipeline.AlphaFunction = D3DCMP_ALWAYS;
+ CHECK(CombinerShader_Generate(description, COMBINER_SHADER_TARGET_D3D11, hlsl));
+ CHECK(!contains(hlsl, "clip("));
+}
+
+// The fog weights the unfogged colour, so a factor of one is no fog, and it never touches the
+// alpha: a fogged pixel is the same shape as an unfogged one.
+TEST(ffshader_the_fog_blends_the_colour_and_leaves_the_alpha)
+{
+ CombinerDescription description;
+ memset(&description, 0, sizeof(description));
+ description.StageCount = 1;
+ description.Stages[0] = one_stage(D3DTOP_SELECTARG1, D3DTA_TEXTURE, D3DTA_CURRENT,
+ D3DTOP_SELECTARG1, D3DTA_TEXTURE, D3DTA_CURRENT, 0, true);
+ description.PixelPipeline.FogEnabled = true;
+
+ std::string eleven;
+ CHECK(CombinerShader_Generate(description, COMBINER_SHADER_TARGET_D3D11, eleven));
+ CHECK(contains(eleven, "current.rgb = lerp(FogColour.rgb, current.rgb, saturate(input.Fog));"));
+ CHECK(!contains(eleven, "current.a = lerp"));
+
+ std::string nine;
+ CHECK(CombinerShader_Generate(description, COMBINER_SHADER_TARGET_D3D9, nine));
+ CHECK(!contains(nine, "FogColour"));
+}
+
+// The key decides what the cache hands back, so two programs that differ only in the alpha test
+// must not share one.
+TEST(ffshader_the_key_separates_a_tested_program_from_an_untested_one)
+{
+ CombinerDescription plain;
+ memset(&plain, 0, sizeof(plain));
+ plain.StageCount = 1;
+ plain.Stages[0] = one_stage(D3DTOP_SELECTARG1, D3DTA_TEXTURE, D3DTA_CURRENT,
+ D3DTOP_SELECTARG1, D3DTA_TEXTURE, D3DTA_CURRENT, 0, true);
+
+ CombinerDescription tested = plain;
+ tested.PixelPipeline.AlphaTestEnabled = true;
+ tested.PixelPipeline.AlphaFunction = D3DCMP_GREATEREQUAL;
+
+ CombinerDescription fogged = plain;
+ fogged.PixelPipeline.FogEnabled = true;
+
+ CHECK_NE(CombinerShader_Key(plain), CombinerShader_Key(tested));
+ CHECK_NE(CombinerShader_Key(plain), CombinerShader_Key(fogged));
+ CHECK_NE(CombinerShader_Key(tested), CombinerShader_Key(fogged));
+
+ // The reference is a uniform, so two draws differing only in it are one program.
+ CHECK_STR(CombinerShader_Key(tested).c_str(), CombinerShader_Key(tested).c_str());
+}
+
// Every distinct program -ffprobe found has to come out of the generator, or the fixed-function
// path stays alive for the ones it refuses and D3D11 has nothing to run them on.
TEST(ffshader_generates_every_measured_combination)
@@ -245,7 +416,7 @@ TEST(ffshader_generates_every_measured_combination)
}
std::string hlsl;
- CHECK(CombinerShader_Generate(description, hlsl));
+ CHECK(CombinerShader_Generate(description, COMBINER_SHADER_TARGET_D3D9, hlsl));
CHECK(contains(hlsl, "float4 main(Input input) : COLOR"));
CHECK(contains(hlsl, "return current;"));
}
diff --git a/GeneralsMD/Code/Tests/test_ffshadercompile.cpp b/GeneralsMD/Code/Tests/test_ffshadercompile.cpp
new file mode 100644
index 000000000..22db7d15e
--- /dev/null
+++ b/GeneralsMD/Code/Tests/test_ffshadercompile.cpp
@@ -0,0 +1,204 @@
+/*
+** 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/>.
+*/
+
+// Every combiner program the game asks for, compiled.
+//
+// The running game compiles these for ps_2_0 and refuses the draw when one will not build, so the
+// D3D9 half is proved every time -ffshader runs. ps_4_0 is not: nothing has ever handed one of
+// these to the D3D11 compiler, and the two profiles disagree about more than the number after the
+// underscore - sampler declarations, the COLOR output semantic, and what may be written to a
+// register. This finds that out here rather than on the day the D3D11 backend first draws.
+//
+// The descriptions are -ffprobe's, measured across Flash Effect, Golden Oasis, ForgottenForestZH
+// and Alpine Assault.
+
+#include "test_harness.h"
+
+#include "ffshader.h"
+
+#include <d3dcommon.h>
+#include <string.h>
+#include <windows.h>
+
+typedef HRESULT (WINAPI *D3DCompileFunction)(LPCVOID source_data, SIZE_T source_size,
+ LPCSTR source_name, const D3D_SHADER_MACRO * defines, ID3DInclude * include,
+ LPCSTR entry_point, LPCSTR target, UINT flags1, UINT flags2, ID3DBlob ** code,
+ ID3DBlob ** error_messages);
+
+static const char * const COMPILER_MODULE = "d3dcompiler_47.dll";
+static const char * const ENTRY_POINT = "main";
+static const char * const D3D9_PROFILE = "ps_2_0";
+static const char * const D3D11_PROFILE = "ps_4_0";
+
+static D3DCompileFunction load_compiler()
+{
+ HMODULE module = LoadLibraryA(COMPILER_MODULE);
+ if (module == NULL) {
+ return NULL;
+ }
+ return reinterpret_cast<D3DCompileFunction>(GetProcAddress(module, "D3DCompile"));
+}
+
+static bool compiles(D3DCompileFunction compile, const std::string & hlsl, const char * profile)
+{
+ ID3DBlob * code = NULL;
+ ID3DBlob * errors = NULL;
+ const HRESULT result = compile(hlsl.c_str(), hlsl.size(), "ffshader", NULL, NULL,
+ ENTRY_POINT, profile, 0, 0, &code, &errors);
+
+ if (FAILED(result) && errors != NULL) {
+ printf(" %s: %s\n", profile, static_cast<const char *>(errors->GetBufferPointer()));
+ }
+ if (code != NULL) {
+ code->Release();
+ }
+ if (errors != NULL) {
+ errors->Release();
+ }
+ return SUCCEEDED(result);
+}
+
+static CombinerStage one_stage(DWORD colour_operation, DWORD colour_argument1,
+ DWORD colour_argument2, DWORD alpha_operation, DWORD alpha_argument1, DWORD alpha_argument2,
+ DWORD coordinate_index, bool texture_bound)
+{
+ CombinerStage stage;
+ memset(&stage, 0, sizeof(stage));
+ stage.ColourOperation = colour_operation;
+ stage.ColourArgument1 = colour_argument1;
+ stage.ColourArgument2 = colour_argument2;
+ stage.AlphaOperation = alpha_operation;
+ stage.AlphaArgument1 = alpha_argument1;
+ stage.AlphaArgument2 = alpha_argument2;
+ stage.TextureCoordinateIndex = coordinate_index;
+ stage.TextureBound = texture_bound;
+ return stage;
+}
+
+// The operations -ffprobe found, one program each, so a refusal names the operation that broke.
+static const DWORD MEASURED_OPERATIONS[] = {
+ D3DTOP_SELECTARG1, D3DTOP_SELECTARG2, D3DTOP_MODULATE, D3DTOP_MODULATE2X, D3DTOP_MODULATE4X,
+ D3DTOP_ADD, D3DTOP_ADDSIGNED, D3DTOP_SUBTRACT, D3DTOP_DOTPRODUCT3
+};
+
+TEST(ffshadercompile_every_operation_compiles_on_both_profiles)
+{
+ D3DCompileFunction compile = load_compiler();
+ if (compile == NULL) {
+ printf(" d3dcompiler_47.dll not present, skipping\n");
+ return;
+ }
+
+ const size_t operation_count = sizeof(MEASURED_OPERATIONS)/sizeof(MEASURED_OPERATIONS[0]);
+ for (size_t index = 0; index < operation_count; ++index) {
+ CombinerDescription description;
+ description.StageCount = 1;
+ description.Stages[0] = one_stage(MEASURED_OPERATIONS[index], D3DTA_TEXTURE, D3DTA_DIFFUSE,
+ MEASURED_OPERATIONS[index], D3DTA_TEXTURE, D3DTA_DIFFUSE, 0, true);
+
+ std::string hlsl;
+ std::string eleven;
+ CHECK(CombinerShader_Generate(description, COMBINER_SHADER_TARGET_D3D9, hlsl));
+ CHECK(CombinerShader_Generate(description, COMBINER_SHADER_TARGET_D3D11, eleven));
+ CHECK(compiles(compile, hlsl, D3D9_PROFILE));
+ CHECK(compiles(compile, eleven, D3D11_PROFILE));
+ }
+}
+
+// The two-stage shroud pass: MULTIPLYADD against an alpha-replicated texture factor, then
+// DOTPRODUCT3. It is the widest program the generator writes and the only one using either
+// operation, so it is the one most likely to say something different on ps_4_0.
+TEST(ffshadercompile_the_widest_measured_program_compiles)
+{
+ D3DCompileFunction compile = load_compiler();
+ if (compile == NULL) {
+ printf(" d3dcompiler_47.dll not present, skipping\n");
+ return;
+ }
+
+ CombinerDescription description;
+ description.StageCount = 2;
+ description.Stages[0] = one_stage(D3DTOP_MULTIPLYADD, D3DTA_TEXTURE, D3DTA_DIFFUSE,
+ D3DTOP_SELECTARG1, D3DTA_TEXTURE, D3DTA_CURRENT, 0, true);
+ description.Stages[0].ColourArgument0 = D3DTA_TFACTOR | D3DTA_ALPHAREPLICATE;
+ description.Stages[1] = one_stage(D3DTOP_DOTPRODUCT3, D3DTA_TEXTURE, D3DTA_CURRENT,
+ D3DTOP_MODULATE, D3DTA_TEXTURE, D3DTA_CURRENT, 1, true);
+
+ std::string hlsl;
+ std::string eleven;
+ CHECK(CombinerShader_Generate(description, COMBINER_SHADER_TARGET_D3D9, hlsl));
+ CHECK(CombinerShader_Generate(description, COMBINER_SHADER_TARGET_D3D11, eleven));
+ CHECK(compiles(compile, hlsl, D3D9_PROFILE));
+ CHECK(compiles(compile, eleven, D3D11_PROFILE));
+}
+
+// The alpha test and the fog exist only on the D3D11 profile, where they are shader instructions
+// rather than pipeline state. Every comparison is generated here, because a clip that will not
+// compile is a pass that silently stays on the pipeline it was on.
+TEST(ffshadercompile_every_alpha_comparison_and_the_fog_compile)
+{
+ D3DCompileFunction compile = load_compiler();
+ if (compile == NULL) {
+ printf(" d3dcompiler_47.dll not present, skipping\n");
+ return;
+ }
+
+ static const DWORD COMPARISONS[] = {
+ D3DCMP_NEVER, D3DCMP_LESS, D3DCMP_EQUAL, D3DCMP_LESSEQUAL,
+ D3DCMP_GREATER, D3DCMP_NOTEQUAL, D3DCMP_GREATEREQUAL, D3DCMP_ALWAYS
+ };
+ const size_t comparison_count = sizeof(COMPARISONS)/sizeof(COMPARISONS[0]);
+
+ for (size_t index = 0; index < comparison_count; ++index) {
+ CombinerDescription description;
+ memset(&description, 0, sizeof(description));
+ description.StageCount = 1;
+ description.Stages[0] = one_stage(D3DTOP_MODULATE, D3DTA_TEXTURE, D3DTA_DIFFUSE,
+ D3DTOP_MODULATE, D3DTA_TEXTURE, D3DTA_DIFFUSE, 0, true);
+ description.PixelPipeline.AlphaTestEnabled = true;
+ description.PixelPipeline.AlphaFunction = COMPARISONS[index];
+ description.PixelPipeline.FogEnabled = true;
+
+ std::string hlsl;
+ CHECK(CombinerShader_Generate(description, COMBINER_SHADER_TARGET_D3D11, hlsl));
+ CHECK(compiles(compile, hlsl, D3D11_PROFILE));
+ }
+}
+
+// The tree shadow pass reads the texture factor for its colour and its alpha both, and reads no
+// varying but one coordinate set. Under ps_4_0 an unread input is still a declared one.
+TEST(ffshadercompile_the_tree_shadow_program_compiles)
+{
+ D3DCompileFunction compile = load_compiler();
+ if (compile == NULL) {
+ printf(" d3dcompiler_47.dll not present, skipping\n");
+ return;
+ }
+
+ CombinerDescription description;
+ description.StageCount = 1;
+ description.Stages[0] = one_stage(D3DTOP_SELECTARG1, D3DTA_TFACTOR, D3DTA_DIFFUSE,
+ D3DTOP_MODULATE, D3DTA_TEXTURE, D3DTA_TFACTOR, 0, true);
+
+ std::string hlsl;
+ std::string eleven;
+ CHECK(CombinerShader_Generate(description, COMBINER_SHADER_TARGET_D3D9, hlsl));
+ CHECK(CombinerShader_Generate(description, COMBINER_SHADER_TARGET_D3D11, eleven));
+ CHECK(compiles(compile, hlsl, D3D9_PROFILE));
+ CHECK(compiles(compile, eleven, D3D11_PROFILE));
+}
diff --git a/GeneralsMD/Code/Tests/test_ffvertex.cpp b/GeneralsMD/Code/Tests/test_ffvertex.cpp
new file mode 100644
index 000000000..cb1c97413
--- /dev/null
+++ b/GeneralsMD/Code/Tests/test_ffvertex.cpp
@@ -0,0 +1,326 @@
+/*
+** 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 fixed-function vertex pipeline written out as HLSL. What is checked here is the shape of
+// the program - which term is present, which register it reads, which case is refused - because
+// that is what a description decides. Whether the arithmetic matches the device is a question for
+// a picture, and the generator exists in the D3D9 form so that picture can be taken.
+
+#include "test_harness.h"
+
+#include "ffvertex.h"
+
+#include <string.h>
+
+static const DWORD FVF_XYZNDUV2 = D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_TEX2|D3DFVF_DIFFUSE;
+static const DWORD FVF_XYZUV1 = D3DFVF_XYZ|D3DFVF_TEX1;
+
+static bool contains(const std::string & text, const char * fragment)
+{
+ return text.find(fragment) != std::string::npos;
+}
+
+// Everything off: no lighting, no fog, one pass-through coordinate set. This is the shape most of
+// the game's draws are, and every other test starts from it.
+static VertexPipelineDescription plain_description()
+{
+ VertexPipelineDescription description;
+ memset(&description, 0, sizeof(description));
+ description.FVF = FVF_XYZNDUV2;
+ description.LightingEnabled = false;
+ description.SpecularEnabled = false;
+ description.ColourVertexEnabled = true;
+ description.DiffuseMaterialSource = D3DMCS_COLOR1;
+ description.AmbientMaterialSource = D3DMCS_MATERIAL;
+ description.EmissiveMaterialSource = D3DMCS_MATERIAL;
+ description.SpecularMaterialSource = D3DMCS_MATERIAL;
+ description.LightCount = 0;
+ description.StageCount = 1;
+ description.Stages[0].TextureCoordinateIndex = D3DTSS_TCI_PASSTHRU | 0;
+ description.Stages[0].TextureTransformFlags = D3DTTFF_DISABLE;
+ description.FogEnabled = false;
+ description.FogVertexMode = D3DFOG_NONE;
+ return description;
+}
+
+TEST(ffvertex_an_unlit_draw_carries_the_vertex_colour_through)
+{
+ std::string hlsl;
+ CHECK(VertexShader_Generate(plain_description(), VERTEX_SHADER_TARGET_D3D9, hlsl));
+ CHECK(contains(hlsl, "output.Diffuse = input.Diffuse;"));
+ CHECK(contains(hlsl, "output.Position = mul(model_position, WorldViewProjection);"));
+
+ // Nothing lit means nothing to light with.
+ CHECK(!contains(hlsl, "diffuse_light"));
+ CHECK(!contains(hlsl, "Light0Diffuse"));
+}
+
+// A format with no colour in it and lighting off is white, not black and not whatever the last
+// draw left in the register.
+TEST(ffvertex_an_unlit_draw_with_no_vertex_colour_is_white)
+{
+ VertexPipelineDescription description = plain_description();
+ description.FVF = FVF_XYZUV1;
+
+ std::string hlsl;
+ CHECK(VertexShader_Generate(description, VERTEX_SHADER_TARGET_D3D9, hlsl));
+ CHECK(contains(hlsl, "output.Diffuse = float4(1.0, 1.0, 1.0, 1.0);"));
+}
+
+TEST(ffvertex_a_directional_light_needs_no_attenuation)
+{
+ VertexPipelineDescription description = plain_description();
+ description.LightingEnabled = true;
+ description.LightCount = 1;
+ description.Lights[0].Type = D3DLIGHT_DIRECTIONAL;
+
+ std::string hlsl;
+ CHECK(VertexShader_Generate(description, VERTEX_SHADER_TARGET_D3D9, hlsl));
+ CHECK(contains(hlsl, "to_light = -normalize(Light0Direction.xyz);"));
+ CHECK(contains(hlsl, "attenuation = 1.0;"));
+ CHECK(contains(hlsl, "diffuse_light += Light0Diffuse.rgb"));
+
+ // A directional light has no distance, so its attenuation and its cone are never read. Both
+ // are still declared: the register layout is the same six for every light whatever its type,
+ // so a light's first register is a multiplication rather than a running total.
+ CHECK(!contains(hlsl, "Light0Attenuation.x + Light0Attenuation.y"));
+ CHECK(!contains(hlsl, "spot_cosine"));
+ CHECK(contains(hlsl, "float4 Light0Attenuation : register("));
+}
+
+TEST(ffvertex_a_point_light_attenuates_and_stops_at_its_range)
+{
+ VertexPipelineDescription description = plain_description();
+ description.LightingEnabled = true;
+ description.LightCount = 1;
+ description.Lights[0].Type = D3DLIGHT_POINT;
+
+ std::string hlsl;
+ CHECK(VertexShader_Generate(description, VERTEX_SHADER_TARGET_D3D9, hlsl));
+ CHECK(contains(hlsl, "Light0Attenuation.x + Light0Attenuation.y * distance"));
+ CHECK(contains(hlsl, "step(distance, Light0Attenuation.w)"));
+
+ // A point light has no cone, so the cone terms are declared and never read.
+ CHECK(!contains(hlsl, "spot_cosine"));
+}
+
+TEST(ffvertex_a_spot_light_adds_the_cone_to_the_point_light_terms)
+{
+ VertexPipelineDescription description = plain_description();
+ description.LightingEnabled = true;
+ description.LightCount = 1;
+ description.Lights[0].Type = D3DLIGHT_SPOT;
+
+ std::string hlsl;
+ CHECK(VertexShader_Generate(description, VERTEX_SHADER_TARGET_D3D9, hlsl));
+ CHECK(contains(hlsl, "step(distance, Light0Attenuation.w)"));
+ CHECK(contains(hlsl, "spot_cosine"));
+ CHECK(contains(hlsl, "Light0Spot.z"));
+}
+
+// D3DMCS_COLOR1 reads the diffuse vertex colour, but only where the format carries one and
+// D3DRS_COLORVERTEX allows it. D3D9 falls back to the material in both of those cases and so does
+// this, which is a fallback rather than a refusal because the device makes it silently too.
+TEST(ffvertex_a_colour_material_source_falls_back_to_the_material)
+{
+ VertexPipelineDescription lit = plain_description();
+ lit.LightingEnabled = true;
+ lit.LightCount = 1;
+ lit.Lights[0].Type = D3DLIGHT_DIRECTIONAL;
+ lit.DiffuseMaterialSource = D3DMCS_COLOR1;
+
+ std::string with_colour;
+ CHECK(VertexShader_Generate(lit, VERTEX_SHADER_TARGET_D3D9, with_colour));
+ CHECK(contains(with_colour, "input.Diffuse.rgb * diffuse_light"));
+
+ // The same description with D3DRS_COLORVERTEX off.
+ lit.ColourVertexEnabled = false;
+ std::string without_colour;
+ CHECK(VertexShader_Generate(lit, VERTEX_SHADER_TARGET_D3D9, without_colour));
+ CHECK(contains(without_colour, "MaterialDiffuse.rgb * diffuse_light"));
+
+ // And with the colour allowed but absent from the format.
+ lit.ColourVertexEnabled = true;
+ lit.FVF = D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_TEX1;
+ std::string without_format;
+ CHECK(VertexShader_Generate(lit, VERTEX_SHADER_TARGET_D3D9, without_format));
+ CHECK(contains(without_format, "MaterialDiffuse.rgb * diffuse_light"));
+}
+
+// The three generation modes the game uses, each of which is a different vector. These are the
+// terms that make an environment map look like an environment map, and there is no reading of the
+// picture that says which one produced it.
+TEST(ffvertex_each_coordinate_generation_mode_produces_its_own_vector)
+{
+ VertexPipelineDescription description = plain_description();
+
+ description.Stages[0].TextureCoordinateIndex = D3DTSS_TCI_CAMERASPACEPOSITION;
+ std::string position;
+ CHECK(VertexShader_Generate(description, VERTEX_SHADER_TARGET_D3D9, position));
+ CHECK(contains(position, "generated0 = float4(view_position.xyz, 1.0)"));
+
+ description.Stages[0].TextureCoordinateIndex = D3DTSS_TCI_CAMERASPACENORMAL;
+ std::string normal;
+ CHECK(VertexShader_Generate(description, VERTEX_SHADER_TARGET_D3D9, normal));
+ CHECK(contains(normal, "generated0 = float4(view_normal, 1.0)"));
+
+ description.Stages[0].TextureCoordinateIndex = D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR;
+ std::string reflection;
+ CHECK(VertexShader_Generate(description, VERTEX_SHADER_TARGET_D3D9, reflection));
+ CHECK(contains(reflection, "reflect(normalize(view_position.xyz), view_normal)"));
+}
+
+TEST(ffvertex_a_texture_matrix_is_applied_and_a_projected_one_divides)
+{
+ VertexPipelineDescription description = plain_description();
+ description.Stages[0].TextureTransformFlags = D3DTTFF_COUNT2;
+
+ std::string plain_matrix;
+ CHECK(VertexShader_Generate(description, VERTEX_SHADER_TARGET_D3D9, plain_matrix));
+ CHECK(contains(plain_matrix, "generated0 = mul(generated0, TextureMatrix0);"));
+ CHECK(!contains(plain_matrix, "generated0.xy /="));
+
+ description.Stages[0].TextureTransformFlags = D3DTTFF_COUNT3 | D3DTTFF_PROJECTED;
+ std::string projected;
+ CHECK(VertexShader_Generate(description, VERTEX_SHADER_TARGET_D3D9, projected));
+ CHECK(contains(projected, "generated0 = mul(generated0, TextureMatrix0);"));
+ CHECK(contains(projected, "generated0.xy /= max(generated0.z, 0.0001);"));
+}
+
+TEST(ffvertex_the_three_fog_modes_each_write_their_own_factor)
+{
+ VertexPipelineDescription description = plain_description();
+ description.FogEnabled = true;
+
+ description.FogVertexMode = D3DFOG_LINEAR;
+ std::string linear;
+ CHECK(VertexShader_Generate(description, VERTEX_SHADER_TARGET_D3D9, linear));
+ CHECK(contains(linear, "FogParameters.y - view_position.z"));
+
+ description.FogVertexMode = D3DFOG_EXP;
+ std::string exponential;
+ CHECK(VertexShader_Generate(description, VERTEX_SHADER_TARGET_D3D9, exponential));
+ CHECK(contains(exponential, "exp(-FogParameters.z * view_position.z)"));
+
+ description.FogVertexMode = D3DFOG_EXP2;
+ std::string squared;
+ CHECK(VertexShader_Generate(description, VERTEX_SHADER_TARGET_D3D9, squared));
+ CHECK(contains(squared, "FogParameters.z * FogParameters.z"));
+
+ // With the fog off the factor is one, which is the weight of the unfogged colour.
+ description.FogEnabled = false;
+ std::string none;
+ CHECK(VertexShader_Generate(description, VERTEX_SHADER_TARGET_D3D9, none));
+ CHECK(contains(none, "output.Fog = 1.0;"));
+}
+
+// A stage the description does not reach still has an output. Left unwritten it carries whatever
+// was on the stack, and the pixel shader samples a texture with it.
+TEST(ffvertex_a_stage_that_was_not_generated_is_still_written)
+{
+ VertexPipelineDescription description = plain_description();
+ description.StageCount = 1;
+
+ std::string hlsl;
+ CHECK(VertexShader_Generate(description, VERTEX_SHADER_TARGET_D3D9, hlsl));
+ CHECK(contains(hlsl, "output.TexCoord1 = float2(0.0, 0.0);"));
+}
+
+// The two profiles differ in the output semantic and in how the constants are declared, and in
+// nothing else. That is what makes the D3D9 form a check on the D3D11 one.
+TEST(ffvertex_the_two_profiles_differ_only_where_they_have_to)
+{
+ const VertexPipelineDescription description = plain_description();
+
+ std::string nine;
+ std::string eleven;
+ CHECK(VertexShader_Generate(description, VERTEX_SHADER_TARGET_D3D9, nine));
+ CHECK(VertexShader_Generate(description, VERTEX_SHADER_TARGET_D3D11, eleven));
+
+ CHECK(contains(nine, "row_major float4x4 WorldViewProjection : register(c0);"));
+ CHECK(contains(nine, "float4 Position : POSITION;"));
+ CHECK(!contains(nine, "cbuffer"));
+
+ CHECK(contains(eleven, "cbuffer VertexPipeline : register(b0)"));
+ CHECK(contains(eleven, "float4 Position : SV_Position;"));
+ CHECK(!contains(eleven, "register(c0)"));
+
+ // The arithmetic is the same text in both.
+ CHECK(contains(nine, "output.Position = mul(model_position, WorldViewProjection);"));
+ CHECK(contains(eleven, "output.Position = mul(model_position, WorldViewProjection);"));
+}
+
+TEST(ffvertex_refuses_what_it_cannot_generate)
+{
+ // A pre-transformed vertex has been through the pipeline already.
+ VertexPipelineDescription pretransformed = plain_description();
+ pretransformed.FVF = D3DFVF_XYZRHW|D3DFVF_DIFFUSE|D3DFVF_TEX1;
+ std::string hlsl;
+ CHECK(!VertexShader_Generate(pretransformed, VERTEX_SHADER_TARGET_D3D9, hlsl));
+
+ // Lighting with no normal to light.
+ VertexPipelineDescription unlit_format = plain_description();
+ unlit_format.FVF = D3DFVF_XYZ|D3DFVF_TEX1;
+ unlit_format.LightingEnabled = true;
+ CHECK(!VertexShader_Generate(unlit_format, VERTEX_SHADER_TARGET_D3D9, hlsl));
+
+ // A pass-through set the vertex format does not carry.
+ VertexPipelineDescription missing_set = plain_description();
+ missing_set.FVF = D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_TEX1;
+ missing_set.Stages[0].TextureCoordinateIndex = D3DTSS_TCI_PASSTHRU | 1;
+ CHECK(!VertexShader_Generate(missing_set, VERTEX_SHADER_TARGET_D3D9, hlsl));
+
+ // More lights than there are registers for.
+ VertexPipelineDescription too_many = plain_description();
+ too_many.LightingEnabled = true;
+ too_many.LightCount = MAXIMUM_VERTEX_LIGHTS + 1;
+ CHECK(!VertexShader_Generate(too_many, VERTEX_SHADER_TARGET_D3D9, hlsl));
+
+ // More stages than the pixel half will read.
+ VertexPipelineDescription too_many_stages = plain_description();
+ too_many_stages.StageCount = MAXIMUM_VERTEX_STAGES + 1;
+ CHECK(!VertexShader_Generate(too_many_stages, VERTEX_SHADER_TARGET_D3D9, hlsl));
+
+ // D3DMCS_COLOR2 is the specular vertex colour and no format in the game carries one. Handing
+ // back the material instead would draw something, and it would be the wrong thing quietly.
+ VertexPipelineDescription specular_source = plain_description();
+ specular_source.LightingEnabled = true;
+ specular_source.LightCount = 1;
+ specular_source.Lights[0].Type = D3DLIGHT_DIRECTIONAL;
+ specular_source.DiffuseMaterialSource = D3DMCS_COLOR2;
+ CHECK(!VertexShader_Generate(specular_source, VERTEX_SHADER_TARGET_D3D9, hlsl));
+}
+
+// The key is what a cache is built on, so two descriptions that generate the same text have to
+// share one and two that do not have to differ.
+TEST(ffvertex_the_key_follows_the_shape_and_not_the_constants)
+{
+ const VertexPipelineDescription plain = plain_description();
+
+ VertexPipelineDescription lit = plain;
+ lit.LightingEnabled = true;
+ lit.LightCount = 1;
+ lit.Lights[0].Type = D3DLIGHT_DIRECTIONAL;
+
+ VertexPipelineDescription point_lit = lit;
+ point_lit.Lights[0].Type = D3DLIGHT_POINT;
+
+ CHECK_NE(VertexShader_Key(plain), VertexShader_Key(lit));
+ CHECK_NE(VertexShader_Key(lit), VertexShader_Key(point_lit));
+ CHECK_STR(VertexShader_Key(plain).c_str(), VertexShader_Key(plain_description()).c_str());
+}
diff --git a/GeneralsMD/Code/Tests/test_ffvertexcompile.cpp b/GeneralsMD/Code/Tests/test_ffvertexcompile.cpp
new file mode 100644
index 000000000..ea3780011
--- /dev/null
+++ b/GeneralsMD/Code/Tests/test_ffvertexcompile.cpp
@@ -0,0 +1,211 @@
+/*
+** 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/>.
+*/
+
+// Does the generated text compile.
+//
+// test_ffvertex.cpp checks the shape of the program - which term is there, which register it
+// reads - and every one of those checks passes on text that no compiler would accept. A missing
+// declaration, a swizzle off the end of a float3, a semantic the profile does not have: all of
+// them look like correct strings. So this hands the generator's output to the real HLSL compiler,
+// both profiles, every description the game is known to ask for, and reports what it says.
+//
+// It compiles with D3DCompile out of d3dcompiler_47.dll, which ships with Windows. A machine
+// without it skips rather than fails: the check is worth having where it can run and it is not
+// worth making the suite unrunnable somewhere else.
+
+#include "test_harness.h"
+
+#include "ffvertex.h"
+
+#include <d3dcommon.h>
+#include <string.h>
+#include <windows.h>
+
+typedef HRESULT (WINAPI *D3DCompileFunction)(LPCVOID source_data, SIZE_T source_size,
+ LPCSTR source_name, const D3D_SHADER_MACRO * defines, ID3DInclude * include,
+ LPCSTR entry_point, LPCSTR target, UINT flags1, UINT flags2, ID3DBlob ** code,
+ ID3DBlob ** error_messages);
+
+static const char * const COMPILER_MODULE = "d3dcompiler_47.dll";
+static const char * const ENTRY_POINT = "main";
+static const char * const D3D9_PROFILE = "vs_3_0";
+static const char * const D3D11_PROFILE = "vs_4_0";
+
+static D3DCompileFunction load_compiler()
+{
+ HMODULE module = LoadLibraryA(COMPILER_MODULE);
+ if (module == NULL) {
+ return NULL;
+ }
+ return reinterpret_cast<D3DCompileFunction>(GetProcAddress(module, "D3DCompile"));
+}
+
+// Compiles and, when the compiler refuses, prints what it said. A test that only reports "did not
+// compile" leaves the next person running fxc by hand to find out why.
+static bool compiles(D3DCompileFunction compile, const std::string & hlsl, const char * profile)
+{
+ ID3DBlob * code = NULL;
+ ID3DBlob * errors = NULL;
+ const HRESULT result = compile(hlsl.c_str(), hlsl.size(), "ffvertex", NULL, NULL,
+ ENTRY_POINT, profile, 0, 0, &code, &errors);
+
+ if (FAILED(result) && errors != NULL) {
+ printf(" %s: %s\n", profile, static_cast<const char *>(errors->GetBufferPointer()));
+ }
+ if (code != NULL) {
+ code->Release();
+ }
+ if (errors != NULL) {
+ errors->Release();
+ }
+ return SUCCEEDED(result);
+}
+
+static VertexPipelineDescription plain_description()
+{
+ VertexPipelineDescription description;
+ memset(&description, 0, sizeof(description));
+ description.FVF = D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_TEX2|D3DFVF_DIFFUSE;
+ description.ColourVertexEnabled = true;
+ description.DiffuseMaterialSource = D3DMCS_COLOR1;
+ description.AmbientMaterialSource = D3DMCS_MATERIAL;
+ description.EmissiveMaterialSource = D3DMCS_MATERIAL;
+ description.SpecularMaterialSource = D3DMCS_MATERIAL;
+ description.StageCount = 1;
+ description.Stages[0].TextureCoordinateIndex = D3DTSS_TCI_PASSTHRU;
+ description.Stages[0].TextureTransformFlags = D3DTTFF_DISABLE;
+ description.FogVertexMode = D3DFOG_NONE;
+ return description;
+}
+
+// One entry per shape the game is known to produce, so a refusal names the shape that broke.
+struct CompileCase
+{
+ const char * Name;
+ bool LightingEnabled;
+ bool SpecularEnabled;
+ unsigned LightCount;
+ DWORD LightType;
+ DWORD TextureCoordinateIndex;
+ DWORD TextureTransformFlags;
+ bool FogEnabled;
+ DWORD FogVertexMode;
+};
+
+static const CompileCase COMPILE_CASES[] = {
+ { "unlit pass-through", false, false, 0, 0,
+ D3DTSS_TCI_PASSTHRU, D3DTTFF_DISABLE, false, D3DFOG_NONE },
+ { "one directional light", true, false, 1, D3DLIGHT_DIRECTIONAL,
+ D3DTSS_TCI_PASSTHRU, D3DTTFF_DISABLE, false, D3DFOG_NONE },
+ { "three directional lights",true, false, 3, D3DLIGHT_DIRECTIONAL,
+ D3DTSS_TCI_PASSTHRU, D3DTTFF_DISABLE, false, D3DFOG_NONE },
+ { "point light", true, false, 1, D3DLIGHT_POINT,
+ D3DTSS_TCI_PASSTHRU, D3DTTFF_DISABLE, false, D3DFOG_NONE },
+ { "spot light", true, false, 1, D3DLIGHT_SPOT,
+ D3DTSS_TCI_PASSTHRU, D3DTTFF_DISABLE, false, D3DFOG_NONE },
+ { "specular highlight", true, true, 1, D3DLIGHT_DIRECTIONAL,
+ D3DTSS_TCI_PASSTHRU, D3DTTFF_DISABLE, false, D3DFOG_NONE },
+ { "camera space position", false, false, 0, 0,
+ D3DTSS_TCI_CAMERASPACEPOSITION, D3DTTFF_COUNT2, false, D3DFOG_NONE },
+ { "camera space normal", false, false, 0, 0,
+ D3DTSS_TCI_CAMERASPACENORMAL, D3DTTFF_DISABLE, false, D3DFOG_NONE },
+ { "reflection vector", false, false, 0, 0,
+ D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR, D3DTTFF_DISABLE, false, D3DFOG_NONE },
+ { "projected transform", false, false, 0, 0,
+ D3DTSS_TCI_CAMERASPACEPOSITION, D3DTTFF_COUNT3|D3DTTFF_PROJECTED, false, D3DFOG_NONE },
+ { "linear fog", false, false, 0, 0,
+ D3DTSS_TCI_PASSTHRU, D3DTTFF_DISABLE, true, D3DFOG_LINEAR },
+ { "exponential fog", false, false, 0, 0,
+ D3DTSS_TCI_PASSTHRU, D3DTTFF_DISABLE, true, D3DFOG_EXP },
+ { "squared exponential fog", false, false, 0, 0,
+ D3DTSS_TCI_PASSTHRU, D3DTTFF_DISABLE, true, D3DFOG_EXP2 }
+};
+
+static VertexPipelineDescription description_for(const CompileCase & compile_case)
+{
+ VertexPipelineDescription description = plain_description();
+ description.LightingEnabled = compile_case.LightingEnabled;
+ description.SpecularEnabled = compile_case.SpecularEnabled;
+ description.LightCount = compile_case.LightCount;
+ for (unsigned index = 0; index < compile_case.LightCount; ++index) {
+ description.Lights[index].Type = compile_case.LightType;
+ }
+ description.Stages[0].TextureCoordinateIndex = compile_case.TextureCoordinateIndex;
+ description.Stages[0].TextureTransformFlags = compile_case.TextureTransformFlags;
+ description.FogEnabled = compile_case.FogEnabled;
+ description.FogVertexMode = compile_case.FogVertexMode;
+ return description;
+}
+
+TEST(ffvertexcompile_every_shape_the_game_produces_compiles_on_both_profiles)
+{
+ D3DCompileFunction compile = load_compiler();
+ if (compile == NULL) {
+ printf(" d3dcompiler_47.dll not present, skipping\n");
+ return;
+ }
+
+ const size_t case_count = sizeof(COMPILE_CASES)/sizeof(COMPILE_CASES[0]);
+ for (size_t index = 0; index < case_count; ++index) {
+ const CompileCase & compile_case = COMPILE_CASES[index];
+ const VertexPipelineDescription description = description_for(compile_case);
+
+ std::string nine;
+ std::string eleven;
+ CHECK(VertexShader_Generate(description, VERTEX_SHADER_TARGET_D3D9, nine));
+ CHECK(VertexShader_Generate(description, VERTEX_SHADER_TARGET_D3D11, eleven));
+
+ if (!compiles(compile, nine, D3D9_PROFILE)) {
+ printf(" case refused on %s: %s\n", D3D9_PROFILE, compile_case.Name);
+ CHECK(false);
+ }
+ if (!compiles(compile, eleven, D3D11_PROFILE)) {
+ printf(" case refused on %s: %s\n", D3D11_PROFILE, compile_case.Name);
+ CHECK(false);
+ }
+ }
+}
+
+// Two stages, each generating a different way, which is the terrain's shape and the widest program
+// the generator writes.
+TEST(ffvertexcompile_a_two_stage_program_compiles)
+{
+ D3DCompileFunction compile = load_compiler();
+ if (compile == NULL) {
+ printf(" d3dcompiler_47.dll not present, skipping\n");
+ return;
+ }
+
+ VertexPipelineDescription description = plain_description();
+ description.LightingEnabled = true;
+ description.LightCount = 2;
+ description.Lights[0].Type = D3DLIGHT_DIRECTIONAL;
+ description.Lights[1].Type = D3DLIGHT_POINT;
+ description.StageCount = 2;
+ description.Stages[0].TextureCoordinateIndex = D3DTSS_TCI_PASSTHRU;
+ description.Stages[0].TextureTransformFlags = D3DTTFF_DISABLE;
+ description.Stages[1].TextureCoordinateIndex = D3DTSS_TCI_CAMERASPACENORMAL;
+ description.Stages[1].TextureTransformFlags = D3DTTFF_COUNT2;
+
+ std::string nine;
+ std::string eleven;
+ CHECK(VertexShader_Generate(description, VERTEX_SHADER_TARGET_D3D9, nine));
+ CHECK(VertexShader_Generate(description, VERTEX_SHADER_TARGET_D3D11, eleven));
+ CHECK(compiles(compile, nine, D3D9_PROFILE));
+ CHECK(compiles(compile, eleven, D3D11_PROFILE));
+}