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.
C++ cmakecnccommand-and-conquercppdirectx11game-enginegame-preservationgeneralsrtssage-enginex64zero-hour
fix(ww3d2): the D3D11 frame is drawn where Direct3D 9 draws it
Olcay Seygan77e99fa4f308
diff --git a/GeneralsMD/Code/CMakeLists.txt b/GeneralsMD/Code/CMakeLists.txtindex c745850de..1792d20b2 100644--- a/GeneralsMD/Code/CMakeLists.txt+++ b/GeneralsMD/Code/CMakeLists.txt@@ -700,6 +700,9 @@ add_lib_test(test_dx11state dx11state)add_lib_test(test_dx11layout dx11layout)add_lib_test(test_ffvertex ffvertex)add_lib_test(test_ffvertexcompile ffvertex)+# The generated vertex program run against the fixed-function pipeline it replaces, on a real+# Direct3D 9 device. It skips itself on a machine with no device rather than failing.+add_lib_test(test_ffvertexd3d9 ffvertex d3d9 user32)add_lib_test(test_ffshadercompile ffshader)add_lib_test(test_dx11pipeline dx11device dx11state dx11layout ffshader ffvertex)add_lib_test(test_dx11resource dx11resource dx11device)@@ -707,6 +710,9 @@ add_lib_test(test_engineshader engineshader)add_lib_test(test_dx11backend dx11backend)add_lib_test(test_dx11twin dx11twin dx11device)add_lib_test(test_dx11texture dx11texture dx11device user32)+# Both runtimes in one binary, so where a triangle edge lands is a measurement rather than a reading+# of two sets of documentation that describe the same thing in different words.+add_lib_test(test_pixelcentre dx11backend dx11resource dx11device d3d9 user32)add_lib_test(test_wwdownload wwdownload)target_include_directories(test_wwdownload PRIVATE ${WW}/WWDownload)diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cppindex 3ac00d1b8..e54a01083 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp@@ -999,13 +999,11 @@ void W3DDisplay::init( void )WW3D::Enable_Static_Sort_Lists(true);WW3D::Set_Thumbnail_Enabled(false);// The bias is half a pixel taken off every 2D vertex, and it makes text look good on Direct3D 9- // because a pixel's centre sits at an integer screen coordinate there. Direct3D 10 onwards puts- // it at a half-integer, so the same half moves the whole 2D layer off the pixel grid it was- // snapped to: measured against the Direct3D 9 frame, the command bar came back 82 levels a pixel- // apart and lined up again when shifted back. Off while the D3D11 backend is presenting.- // Read from the option rather than from Direct3D11_Present_Is_Enabled(), which is not set until- // the device is created a few lines below this one.- WW3D::Set_Screen_UV_Bias( TheGlobalData->m_direct3D11Present ? FALSE : TRUE );+ // because a pixel's centre sits at an integer screen coordinate there. It stays on under the+ // Direct3D 11 backend as well: that backend shifts its viewport half a pixel instead, so a+ // vertex lands where Direct3D 9 lands it and the bias means the same thing on both. Turning it+ // off there as well was tried, and with the viewport shift in place it moves the 2D layer twice.+ WW3D::Set_Screen_UV_Bias( TRUE );WW3D::Set_Texture_Bitdepth(32);setWindowed( TheGlobalData->m_windowed );diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cppindex f94c83d0d..924f76746 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp@@ -671,9 +671,20 @@ void DX11BackendClass::Set_Render_Target(ID3D11RenderTargetView * target)void DX11BackendClass::Set_Viewport(unsigned x, unsigned y, unsigned width, unsigned height){+ // Half a pixel to the right and down, which is the whole of the difference between where+ // Direct3D 9 draws a triangle and where Direct3D 11 draws the same one. D3D9 tests coverage at+ // a pixel's integer coordinate and D3D10 onwards at the half-integer, so an edge that D3D9 puts+ // at screen x 32.25 covers column 32 there and column 31 here. Every account of this is written+ // about screen space quads and texel alignment; it is the projected geometry that carries the+ // error into a whole frame, and moving the viewport is the only place that catches the generated+ // programs and the transcribed .vso shaders in one edit.+ //+ // test_pixelcentre draws that edge on both runtimes in one binary and reads back the column.+ // Take this out and it says 32 against 31.+ const float PIXEL_CENTRE_OFFSET = 0.5f;D3D11_VIEWPORT viewport;- viewport.TopLeftX = static_cast<float>(x);- viewport.TopLeftY = static_cast<float>(y);+ viewport.TopLeftX = static_cast<float>(x) + PIXEL_CENTRE_OFFSET;+ viewport.TopLeftY = static_cast<float>(y) + PIXEL_CENTRE_OFFSET;viewport.Width = static_cast<float>(width);viewport.Height = static_cast<float>(height);viewport.MinDepth = 0.0f;@@ -1048,9 +1059,11 @@ void DX11BackendClass::Upload_Constants()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.+ // D3DRS_ALPHAREF is an eight bit level and it goes up as one, not as a fraction: the generated+ // clip rounds the pixel's alpha to a level first, because that is the comparison Direct3D 9 made+ // and comparing fractions instead moves every alpha tested edge by up to half a level.pixel_block.AlphaReference[0] =- static_cast<float>(RenderStates.Get_Render_State(D3DRS_ALPHAREF) & 0xff) / 255.0f;+ static_cast<float>(RenderStates.Get_Render_State(D3DRS_ALPHAREF) & 0xff);if (SUCCEEDED(context->Map(PixelConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped))) {memcpy(mapped.pData, &pixel_block, sizeof(pixel_block));diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.cppindex bb0fb15b0..63c6d2404 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.cpp@@ -163,11 +163,21 @@ static bool operation_expression(DWORD operation, const std::string & argument0,}// 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";+// argument is negative, which turns each comparison into one subtraction.+//+// Both sides of that subtraction are whole levels. Direct3D 9's alpha test compared the eight bit+// alpha about to be written against an eight bit reference, so the comparison this replaces is an+// integer one, and doing it in floats moves every alpha tested edge in the frame by up to half a+// level. On a quad whose alpha runs from nothing to full across 64 pixels, tested at reference 128,+// Direct3D 9 keeps from column 32 and the float comparison kept from 33 - one pixel along every+// foliage edge there is, and the views that carry the most of them are the ones that were still+// outside the margin. test_pixelcentre draws exactly that quad on both runtimes.+//+// Rounding to a level first also makes the strict comparisons and the two equalities exact. A+// strict greater is one whole level further along; an equality is a level either side rather than+// the guessed tolerance this used to carry.+static const char * const ALPHA_LEVEL =+ " float alpha_level = floor(current.a * 255.0 + 0.5);\n";static bool alpha_test_expression(DWORD function, std::string & expression){@@ -176,20 +186,22 @@ static bool alpha_test_expression(DWORD function, std::string & expression)expression = "clip(-1.0);\n";return true;case D3DCMP_LESS:+ expression = "clip(AlphaReference.x - alpha_level - 1.0);\n";+ return true;case D3DCMP_LESSEQUAL:- expression = "clip(AlphaReference.x - current.a);\n";+ expression = "clip(AlphaReference.x - alpha_level);\n";return true;case D3DCMP_GREATER:+ expression = "clip(alpha_level - AlphaReference.x - 1.0);\n";+ return true;case D3DCMP_GREATEREQUAL:- expression = "clip(current.a - AlphaReference.x);\n";+ expression = "clip(alpha_level - AlphaReference.x);\n";return true;case D3DCMP_EQUAL:- expression = std::string("clip(") + ALPHA_EQUALITY_TOLERANCE- + " - abs(current.a - AlphaReference.x));\n";+ expression = "clip(0.5 - abs(alpha_level - AlphaReference.x));\n";return true;case D3DCMP_NOTEQUAL:- expression = std::string("clip(abs(current.a - AlphaReference.x) - ")- + ALPHA_EQUALITY_TOLERANCE + ");\n";+ expression = "clip(abs(alpha_level - AlphaReference.x) - 0.5);\n";return true;case D3DCMP_ALWAYS:// Nothing to write: every pixel survives, which is what no alpha test at all means.@@ -372,6 +384,7 @@ bool CombinerShader_Append_Pixel_Pipeline(const PixelPipelineDescription & pipelreturn false;}if (!clip.empty()) {+ hlsl += ALPHA_LEVEL;hlsl += " " + clip;}}diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffvertex.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffvertex.cppindex 843207e90..19f5f5394 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffvertex.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffvertex.cpp@@ -30,31 +30,30 @@ static const DWORD TEXTURE_TRANSFORM_COUNT_MASK = 0x07;// has 256 float4 registers and this uses fewer than 70 of them, so the layout is written for// reading rather than for packing. Everything after the texture matrices is derived from where// they end, because how many there are follows MAXIMUM_VERTEX_STAGES.-static const unsigned REGISTERS_PER_MATRIX = 4;-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_MATRICES = 12;-static const unsigned REGISTER_MATERIAL_AMBIENT =- REGISTER_TEXTURE_MATRICES + MAXIMUM_VERTEX_STAGES * REGISTERS_PER_MATRIX;-static const unsigned REGISTER_MATERIAL_DIFFUSE = REGISTER_MATERIAL_AMBIENT + 1;-static const unsigned REGISTER_MATERIAL_SPECULAR = REGISTER_MATERIAL_AMBIENT + 2;-static const unsigned REGISTER_MATERIAL_EMISSIVE = REGISTER_MATERIAL_AMBIENT + 3;-static const unsigned REGISTER_MATERIAL_POWER = REGISTER_MATERIAL_AMBIENT + 4;-static const unsigned REGISTER_GLOBAL_AMBIENT = REGISTER_MATERIAL_AMBIENT + 5;-static const unsigned REGISTER_FOG_PARAMETERS = REGISTER_MATERIAL_AMBIENT + 6;-// The reciprocal of the viewport's width and height, which is all a pre-transformed vertex needs:-// its position is already in pixels and the shader has to put it back into clip space. It sits-// before the lights because the D3D11 block declares only as many lights as the description has,-// and anything after them would move with that count.-static const unsigned REGISTER_VIEWPORT = REGISTER_MATERIAL_AMBIENT + 7;-static const unsigned REGISTER_LIGHTS = REGISTER_MATERIAL_AMBIENT + 8;--// 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;+// The numbers themselves are in ffvertex.h, because anything driving the D3D9 program from outside+// has to fill the same registers. These are the short names this file reads them by.+//+// The viewport's reciprocal sits before the lights because the D3D11 block declares only as many+// lights as the description has, and anything after them would move with that count. 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_MATRIX = VERTEX_REGISTERS_PER_MATRIX;+static const unsigned REGISTER_WORLD_VIEW_PROJECTION = VERTEX_REGISTER_WORLD_VIEW_PROJECTION;+static const unsigned REGISTER_WORLD_VIEW = VERTEX_REGISTER_WORLD_VIEW;+static const unsigned REGISTER_NORMAL_TRANSFORM = VERTEX_REGISTER_NORMAL_TRANSFORM;+static const unsigned REGISTER_TEXTURE_MATRICES = VERTEX_REGISTER_TEXTURE_MATRICES;+static const unsigned REGISTER_MATERIAL_AMBIENT = VERTEX_REGISTER_MATERIAL_AMBIENT;+static const unsigned REGISTER_MATERIAL_DIFFUSE = VERTEX_REGISTER_MATERIAL_DIFFUSE;+static const unsigned REGISTER_MATERIAL_SPECULAR = VERTEX_REGISTER_MATERIAL_SPECULAR;+static const unsigned REGISTER_MATERIAL_EMISSIVE = VERTEX_REGISTER_MATERIAL_EMISSIVE;+static const unsigned REGISTER_MATERIAL_POWER = VERTEX_REGISTER_MATERIAL_POWER;+static const unsigned REGISTER_GLOBAL_AMBIENT = VERTEX_REGISTER_GLOBAL_AMBIENT;+static const unsigned REGISTER_FOG_PARAMETERS = VERTEX_REGISTER_FOG_PARAMETERS;+static const unsigned REGISTER_VIEWPORT = VERTEX_REGISTER_VIEWPORT;+static const unsigned REGISTER_LIGHTS = VERTEX_REGISTER_LIGHTS;+static const unsigned REGISTERS_PER_LIGHT = VERTEX_REGISTERS_PER_LIGHT;static bool has_normal(DWORD fvf){@@ -398,14 +397,13 @@ static bool generate_pretransformed(const VertexPipelineDescription & descriptio" Output output;\n"" float reciprocal_w = (input.Position.w == 0.0) ? 1.0 : input.Position.w;\n"" float w = 1.0 / reciprocal_w;\n"- // Direct3D 9 puts a pixel's centre at an integer screen coordinate and Direct3D 10 onwards- // puts it at a half-integer, so a screen space quad written for one lands half a pixel off- // under the other. Every such quad in this engine already carries D3D9's own -0.5, which is- // what aligns a texel with a pixel there; the half added back here cancels it. Miss it and- // the quad samples exactly between two texels, linear filtering averages them, and the whole- // scene comes back softened - 42% of the local contrast on Alpine Assault, with the command- // bar beside it sharp because the bar is drawn after the composite rather than through it.- " float2 normalised = (input.Position.xy + 0.5) * ViewportInverse.xy;\n"+ // Straight into clip space with no half-pixel of its own. D3D9 and D3D11 disagree about+ // where a pixel's centre is and every screen space quad in this engine carries D3D9's own+ // -0.5 for it, but the correction belongs to the whole frame rather than to this path:+ // DX11BackendClass::Set_Viewport shifts the viewport half a pixel and every draw comes out+ // where Direct3D 9 puts it, the transcribed .vso programs included. Adding a half here as+ // well was tried and measured - Alpine Assault went from 5.99% to 9.51% with both.+ " float2 normalised = input.Position.xy * ViewportInverse.xy;\n"" output.Position = float4((normalised.x * 2.0 - 1.0) * w,\n"" (1.0 - normalised.y * 2.0) * w, input.Position.z * w, w);\n";diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffvertex.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffvertex.hindex 7ff6140d1..dedfbad5d 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffvertex.h+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffvertex.h@@ -52,6 +52,28 @@ const unsigned MAXIMUM_VERTEX_STAGES = 4;// three, and every register past this one is a register the D3D9 profile does not have to spare.const unsigned MAXIMUM_VERTEX_LIGHTS = 4;+// Where each constant sits in the D3D9 profile's register file, which is what+// SetVertexShaderConstantF is given. The D3D11 profile puts the same values in one constant buffer+// in this order instead, so the two halves of the generator share the layout and nothing else.+// Public because anything driving the D3D9 program from outside has to fill the same registers, and+// a layout agreed by two files that cannot see each other is a layout that drifts.+const unsigned VERTEX_REGISTERS_PER_MATRIX = 4;+const unsigned VERTEX_REGISTER_WORLD_VIEW_PROJECTION = 0;+const unsigned VERTEX_REGISTER_WORLD_VIEW = 4;+const unsigned VERTEX_REGISTER_NORMAL_TRANSFORM = 8;+const unsigned VERTEX_REGISTER_TEXTURE_MATRICES = 12;+const unsigned VERTEX_REGISTER_MATERIAL_AMBIENT =+ VERTEX_REGISTER_TEXTURE_MATRICES + MAXIMUM_VERTEX_STAGES * VERTEX_REGISTERS_PER_MATRIX;+const unsigned VERTEX_REGISTER_MATERIAL_DIFFUSE = VERTEX_REGISTER_MATERIAL_AMBIENT + 1;+const unsigned VERTEX_REGISTER_MATERIAL_SPECULAR = VERTEX_REGISTER_MATERIAL_AMBIENT + 2;+const unsigned VERTEX_REGISTER_MATERIAL_EMISSIVE = VERTEX_REGISTER_MATERIAL_AMBIENT + 3;+const unsigned VERTEX_REGISTER_MATERIAL_POWER = VERTEX_REGISTER_MATERIAL_AMBIENT + 4;+const unsigned VERTEX_REGISTER_GLOBAL_AMBIENT = VERTEX_REGISTER_MATERIAL_AMBIENT + 5;+const unsigned VERTEX_REGISTER_FOG_PARAMETERS = VERTEX_REGISTER_MATERIAL_AMBIENT + 6;+const unsigned VERTEX_REGISTER_VIEWPORT = VERTEX_REGISTER_MATERIAL_AMBIENT + 7;+const unsigned VERTEX_REGISTER_LIGHTS = VERTEX_REGISTER_MATERIAL_AMBIENT + 8;+const unsigned VERTEX_REGISTERS_PER_LIGHT = 6;+struct VertexLightDescription{// D3DLIGHT_DIRECTIONAL, D3DLIGHT_POINT or D3DLIGHT_SPOT.diff --git a/GeneralsMD/Code/Tests/test_d3d9device.h b/GeneralsMD/Code/Tests/test_d3d9device.hnew file mode 100644index 000000000..295287a58--- /dev/null+++ b/GeneralsMD/Code/Tests/test_d3d9device.h@@ -0,0 +1,152 @@+/*+** 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 Direct3D 9 device with a small offscreen render target and no visible window, for tests that+// have to ask the runtime the game is being ported away from what it actually does. Reading the+// D3D11 documentation against the D3D9 documentation settles nothing where the two describe the+// same thing in different words, which is most of the places a frame can go wrong.+//+// Nothing here is fatal on a machine without a device. Create returns false and the test says so+// and passes: a build host with no GPU is not a broken renderer.++#ifndef TEST_D3D9DEVICE_H+#define TEST_D3D9DEVICE_H++#include <d3d9.h>+#include <string.h>++inline void D3D9Test_Set_Identity(D3DMATRIX & matrix)+{+ memset(&matrix, 0, sizeof(matrix));+ matrix._11 = 1.0f;+ matrix._22 = 1.0f;+ matrix._33 = 1.0f;+ matrix._44 = 1.0f;+}++class D3D9OffscreenDevice+{+public:+ D3D9OffscreenDevice()+ : Interface(NULL), Device(NULL), Target(NULL), Readback(NULL), Window(NULL), Size(0)+ {+ }++ ~D3D9OffscreenDevice()+ {+ if (Readback != NULL) {+ Readback->Release();+ }+ if (Target != NULL) {+ Target->Release();+ }+ if (Device != NULL) {+ Device->Release();+ }+ if (Interface != NULL) {+ Interface->Release();+ }+ if (Window != NULL) {+ DestroyWindow(Window);+ }+ }++ // Software vertex processing on a HAL device, so a vertex shader runs wherever the test runs+ // and the fixed-function pipeline beside it is the runtime's own.+ bool Create(unsigned size)+ {+ Size = size;+ Interface = Direct3DCreate9(D3D_SDK_VERSION);+ if (Interface == NULL) {+ return false;+ }++ Window = CreateWindowA("STATIC", "d3d9test", WS_OVERLAPPED, 0, 0, 8, 8,+ NULL, NULL, NULL, NULL);+ if (Window == NULL) {+ return false;+ }++ D3DPRESENT_PARAMETERS parameters;+ memset(¶meters, 0, sizeof(parameters));+ parameters.Windowed = TRUE;+ parameters.SwapEffect = D3DSWAPEFFECT_DISCARD;+ parameters.BackBufferFormat = D3DFMT_X8R8G8B8;+ parameters.BackBufferWidth = size;+ parameters.BackBufferHeight = size;+ parameters.hDeviceWindow = Window;++ if (FAILED(Interface->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, Window,+ D3DCREATE_SOFTWARE_VERTEXPROCESSING, ¶meters, &Device))) {+ return false;+ }+ if (FAILED(Device->CreateRenderTarget(size, size, D3DFMT_A8R8G8B8,+ D3DMULTISAMPLE_NONE, 0, FALSE, &Target, NULL))) {+ return false;+ }+ if (FAILED(Device->CreateOffscreenPlainSurface(size, size, D3DFMT_A8R8G8B8,+ D3DPOOL_SYSTEMMEM, &Readback, NULL))) {+ return false;+ }+ return SUCCEEDED(Device->SetRenderTarget(0, Target));+ }++ IDirect3DDevice9 * Get_Device() const+ {+ return Device;+ }++ unsigned Get_Size() const+ {+ return Size;+ }++ // Copies the target back and hands out one pixel as blue, green, red.+ bool Read_Pixel(unsigned x, unsigned y, unsigned char colour[3])+ {+ if (FAILED(Device->GetRenderTargetData(Target, Readback))) {+ return false;+ }+ D3DLOCKED_RECT locked;+ if (FAILED(Readback->LockRect(&locked, NULL, D3DLOCK_READONLY))) {+ return false;+ }+ const unsigned char * pixel = static_cast<const unsigned char *>(locked.pBits)+ + locked.Pitch * y + x * 4;+ colour[0] = pixel[0];+ colour[1] = pixel[1];+ colour[2] = pixel[2];+ Readback->UnlockRect();+ return true;+ }++ bool Clear(D3DCOLOR colour)+ {+ return SUCCEEDED(Device->Clear(0, NULL, D3DCLEAR_TARGET, colour, 1.0f, 0));+ }++private:+ IDirect3D9 * Interface;+ IDirect3DDevice9 * Device;+ IDirect3DSurface9 * Target;+ IDirect3DSurface9 * Readback;+ HWND Window;+ unsigned Size;+};++#endif // TEST_D3D9DEVICE_Hdiff --git a/GeneralsMD/Code/Tests/test_ffshader.cpp b/GeneralsMD/Code/Tests/test_ffshader.cppindex 95433c4bb..4b94d9a3e 100644--- a/GeneralsMD/Code/Tests/test_ffshader.cpp+++ b/GeneralsMD/Code/Tests/test_ffshader.cpp@@ -324,7 +324,8 @@ TEST(ffshader_the_alpha_test_is_a_clip_on_d3d11_and_nothing_on_d3d9)std::string eleven;CHECK(CombinerShader_Generate(description, COMBINER_SHADER_TARGET_D3D11, eleven));- CHECK(contains(eleven, "clip(current.a - AlphaReference.x);"));+ CHECK(contains(eleven, "float alpha_level = floor(current.a * 255.0 + 0.5);"));+ CHECK(contains(eleven, "clip(alpha_level - AlphaReference.x);"));std::string nine;CHECK(CombinerShader_Generate(description, COMBINER_SHADER_TARGET_D3D9, nine));@@ -332,9 +333,11 @@ TEST(ffshader_the_alpha_test_is_a_clip_on_d3d11_and_nothing_on_d3d9)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.+// clip throws a pixel away when its argument is negative, so each comparison is one subtraction, and+// both sides of it are whole levels because that is what Direct3D 9 compared. A strict comparison+// is a whole level further along and an equality is half a level either side; comparing fractions+// instead moved every alpha tested edge in the frame, which test_pixelcentre measures on the two+// runtimes directly.TEST(ffshader_each_alpha_comparison_becomes_its_own_clip){CombinerDescription description;@@ -346,13 +349,19 @@ TEST(ffshader_each_alpha_comparison_becomes_its_own_clip)std::string hlsl;+ // A strict less keeps a level below the reference and no higher, so the subtraction carries the+ // whole level that separates it from the less-or-equal beside it.description.PixelPipeline.AlphaFunction = D3DCMP_LESS;CHECK(CombinerShader_Generate(description, COMBINER_SHADER_TARGET_D3D11, hlsl));- CHECK(contains(hlsl, "clip(AlphaReference.x - current.a);"));+ CHECK(contains(hlsl, "clip(AlphaReference.x - alpha_level - 1.0);"));++ description.PixelPipeline.AlphaFunction = D3DCMP_LESSEQUAL;+ CHECK(CombinerShader_Generate(description, COMBINER_SHADER_TARGET_D3D11, hlsl));+ CHECK(contains(hlsl, "clip(AlphaReference.x - alpha_level);"));description.PixelPipeline.AlphaFunction = D3DCMP_EQUAL;CHECK(CombinerShader_Generate(description, COMBINER_SHADER_TARGET_D3D11, hlsl));- CHECK(contains(hlsl, "abs(current.a - AlphaReference.x)"));+ CHECK(contains(hlsl, "clip(0.5 - abs(alpha_level - AlphaReference.x));"));description.PixelPipeline.AlphaFunction = D3DCMP_NEVER;CHECK(CombinerShader_Generate(description, COMBINER_SHADER_TARGET_D3D11, hlsl));diff --git a/GeneralsMD/Code/Tests/test_ffvertex.cpp b/GeneralsMD/Code/Tests/test_ffvertex.cppindex 1efc256a5..64fcaabad 100644--- a/GeneralsMD/Code/Tests/test_ffvertex.cpp+++ b/GeneralsMD/Code/Tests/test_ffvertex.cpp@@ -301,12 +301,13 @@ TEST(ffvertex_puts_a_pretransformed_vertex_back_into_clip_space)CHECK(contains(hlsl, "output.TexCoord0 = input.TexCoord0;"));CHECK(contains(hlsl, "output.Diffuse = input.Diffuse;"));- // D3D9's pixel centre is at an integer screen coordinate and D3D11's at a half-integer, so the- // half these quads already carry for D3D9 has to be given back. Without it the composite quad- // samples the scene texture exactly between two texels and the whole frame comes back softened:- // 42% of Alpine Assault's local contrast, with the command bar sharp beside it because the bar- // is drawn straight to the back buffer rather than through the composite.- CHECK(contains(hlsl, "(input.Position.xy + 0.5) * ViewportInverse.xy"));+ // No half pixel of its own. D3D9's pixel centre is at an integer screen coordinate and D3D11's+ // at a half-integer, and these quads carry D3D9's -0.5 for it, but the backend answers that by+ // shifting its viewport rather than by editing one path: a correction written here reaches the+ // generated programs and misses the transcribed .vso ones, and applied in both places it moves+ // the 2D layer twice. Alpine Assault measured 9.51% with both and 5.99% with neither.+ CHECK(contains(hlsl, "float2 normalised = input.Position.xy * ViewportInverse.xy;"));+ CHECK(!contains(hlsl, "input.Position.xy + 0.5"));// The one thing it must not do is transform a position that is already transformed.CHECK(!contains(hlsl, "WorldViewProjection)"));diff --git a/GeneralsMD/Code/Tests/test_ffvertexd3d9.cpp b/GeneralsMD/Code/Tests/test_ffvertexd3d9.cppnew file mode 100644index 000000000..3409aa42b--- /dev/null+++ b/GeneralsMD/Code/Tests/test_ffvertexd3d9.cpp@@ -0,0 +1,470 @@+/*+** 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 vertex program against the fixed-function pipeline it replaces, on one Direct3D 9+// device, one draw each, comparing the pixels that come out.+//+// This is the vertex half of what -ffshader measures for the pixel half, and it exists because+// nothing else can tell a generator that follows the documented formula from a device that does+// something else. Reading the two against each other proves only that the code matches the book.+//+// The frame the D3D11 backend draws is still a few percent from the Direct3D 9 one, and fitting a+// line through the two frames channel by channel puts the whole of that difference on lit meshes:+// terrain comes back at 0.954 of Direct3D 9's value, the command bar at exactly 1.000, and the+// buildings at 0.825 with a lift of nearly six levels at black. Everything a picture can say about+// that has been said. These tests are the next instrument.+//+// A machine with no Direct3D 9 device passes them by saying so; that is a test host without a GPU,+// not a failure of the generator.++#include "test_harness.h"++#include "ffvertex.h"+#include "test_d3d9device.h"++#include <d3d9.h>+#include <d3dcommon.h>+#include <math.h>+#include <stdio.h>+#include <string.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 unsigned TARGET_SIZE = 64;++// Two paths that agree to within a level are the same arithmetic quantised twice. The fixed+// function runs wherever the driver runs it and the generated program runs in the software vertex+// processor, so the last bit of a colour is not a claim either of them makes.+static const int LEVEL_TOLERANCE = 2;++// Which of a light's six registers ffvertex reads for a directional one. The order it declares+// them in is position, direction, diffuse, specular, attenuation, spot.+static const unsigned LIGHT_DIRECTION = 1;+static const unsigned LIGHT_DIFFUSE = 2;++// Nothing here turns the specular on, so the exponent only has to be a value both paths agree is+// not zero: D3D9 refuses a material power of zero on some drivers and the shader raises to it.+static const float MATERIAL_POWER = 1.0f;++// One quad already in clip space, so the world, view and projection matrices are free to be+// anything the test wants without moving it off the screen.+struct LitVertex+{+ float Position[3];+ float Normal[3];+ float TexCoord[2];+};++static const LitVertex QUAD[4] = {+ { { -1.0f, -1.0f, 0.5f }, { 0.0f, 0.0f, 1.0f }, { 0.0f, 0.0f } },+ { { -1.0f, 1.0f, 0.5f }, { 0.0f, 0.0f, 1.0f }, { 0.0f, 0.0f } },+ { { 1.0f, 1.0f, 0.5f }, { 0.0f, 0.0f, 1.0f }, { 0.0f, 0.0f } },+ { { 1.0f, -1.0f, 0.5f }, { 0.0f, 0.0f, 1.0f }, { 0.0f, 0.0f } }+};++static const DWORD QUAD_FVF = D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_TEX1;++// Everything both draws share: no texture, the vertex colour straight through, no depth test.+static void configure_common(IDirect3DDevice9 * device)+{+ device->SetRenderState(D3DRS_ZENABLE, D3DZB_FALSE);+ device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);+ device->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);+ device->SetRenderState(D3DRS_SPECULARENABLE, FALSE);+ device->SetRenderState(D3DRS_COLORVERTEX, FALSE);+ device->SetRenderState(D3DRS_FOGENABLE, FALSE);+ device->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);+ device->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_DIFFUSE);+ device->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);+ device->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_DIFFUSE);+ device->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE);+ device->SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_DISABLE);+}++static void set_material(IDirect3DDevice9 * device, const float ambient[4], const float diffuse[4],+ const float emissive[4], float power)+{+ D3DMATERIAL9 material;+ memset(&material, 0, sizeof(material));+ memcpy(&material.Ambient, ambient, sizeof(float) * 4);+ memcpy(&material.Diffuse, diffuse, sizeof(float) * 4);+ memcpy(&material.Emissive, emissive, sizeof(float) * 4);+ material.Power = power;+ device->SetMaterial(&material);+}++static D3DCompileFunction load_compiler()+{+ HMODULE module = LoadLibraryA(COMPILER_MODULE);+ if (module == NULL) {+ return NULL;+ }+ return reinterpret_cast<D3DCompileFunction>(GetProcAddress(module, "D3DCompile"));+}++// A matrix goes into the register file exactly as D3D9 stores it, four registers a row, because the+// generated program declares every matrix row_major and multiplies a row vector by it.+static void set_matrix(IDirect3DDevice9 * device, unsigned first_register, const D3DMATRIX & source)+{+ device->SetVertexShaderConstantF(first_register, reinterpret_cast<const float *>(&source),+ VERTEX_REGISTERS_PER_MATRIX);+}++static void multiply(const D3DMATRIX & left, const D3DMATRIX & right, D3DMATRIX & result)+{+ const float * a = reinterpret_cast<const float *>(&left);+ const float * b = reinterpret_cast<const float *>(&right);+ float * out = reinterpret_cast<float *>(&result);+ for (unsigned row = 0; row < 4; ++row) {+ for (unsigned column = 0; column < 4; ++column) {+ float sum = 0.0f;+ for (unsigned term = 0; term < 4; ++term) {+ sum += a[row * 4 + term] * b[term * 4 + column];+ }+ out[row * 4 + column] = sum;+ }+ }+}++// D3D9's row-vector rotation about x. Its inverse is the same rotation by the negative angle, which+// is how the test builds a world and a view that cancel: the geometry lands where it started while+// every normal and every light direction still goes the long way round.+static void set_rotation_x(D3DMATRIX & matrix, float radians)+{+ D3D9Test_Set_Identity(matrix);+ matrix._22 = cosf(radians);+ matrix._23 = sinf(radians);+ matrix._32 = -sinf(radians);+ matrix._33 = cosf(radians);+}++// The direction half of what DX11BackendClass::Upload_Constants does to a light before it reaches+// the shader: D3D9 carries a light through the view matrix once per light and lights in camera+// space, so a direction left in world space lights the wrong side of everything.+static void transform_direction(const float source[3], const D3DMATRIX & matrix, float result[4])+{+ const float * m = reinterpret_cast<const float *>(&matrix);+ for (unsigned column = 0; column < 4; ++column) {+ result[column] = source[0] * m[column] + source[1] * m[4 + column]+ + source[2] * m[8 + column];+ }+}++// A directional light as the map files describe one: the way the light travels, in world space,+// with a colour. Every light in the dumped building pipeline is one of these.+struct DirectionalLight+{+ float Direction[3];+ float Diffuse[4];+};++// Everything both draws are given. The world and the view are kept orthonormal on purpose, so the+// normal transform is the world-view matrix itself and the test is about the lighting rather than+// about who inverts a matrix.+struct LitScene+{+ D3DMATRIX World;+ D3DMATRIX View;+ float MaterialAmbient[4];+ float MaterialDiffuse[4];+ float MaterialEmissive[4];+ float GlobalAmbient[4];+ unsigned LightCount;+ DirectionalLight Lights[MAXIMUM_VERTEX_LIGHTS];+};++static const unsigned COLOUR_LEVELS = 255;++// The scene ambient reaches the fixed function as a packed colour and the shader as four floats, so+// the two only agree if the floats are levels to begin with. Every global ambient in this file is.+static DWORD to_packed_colour(const float colour[4])+{+ return D3DCOLOR_ARGB(+ static_cast<unsigned>(colour[3] * COLOUR_LEVELS + 0.5f),+ static_cast<unsigned>(colour[0] * COLOUR_LEVELS + 0.5f),+ static_cast<unsigned>(colour[1] * COLOUR_LEVELS + 0.5f),+ static_cast<unsigned>(colour[2] * COLOUR_LEVELS + 0.5f));+}++static VertexPipelineDescription describe(const LitScene & scene)+{+ VertexPipelineDescription description;+ memset(&description, 0, sizeof(description));+ description.FVF = QUAD_FVF;+ description.LightingEnabled = true;+ description.SpecularEnabled = false;+ description.ColourVertexEnabled = false;+ description.DiffuseMaterialSource = D3DMCS_MATERIAL;+ description.AmbientMaterialSource = D3DMCS_MATERIAL;+ description.EmissiveMaterialSource = D3DMCS_MATERIAL;+ description.SpecularMaterialSource = D3DMCS_MATERIAL;+ description.LightCount = scene.LightCount;+ for (unsigned index = 0; index < scene.LightCount; ++index) {+ description.Lights[index].Type = D3DLIGHT_DIRECTIONAL;+ }+ description.StageCount = 1;+ description.Stages[0].TextureCoordinateIndex = 0;+ description.Stages[0].TextureTransformFlags = D3DTTFF_DISABLE;+ description.FogEnabled = false;+ return description;+}++static void clear_target(IDirect3DDevice9 * device)+{+ device->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_ARGB(255, 0, 255, 0), 1.0f, 0);+ configure_common(device);+}++static bool draw_quad(IDirect3DDevice9 * device)+{+ if (FAILED(device->BeginScene())) {+ return false;+ }+ const HRESULT drawn = device->DrawPrimitiveUP(D3DPT_TRIANGLEFAN, 2, QUAD, sizeof(LitVertex));+ device->EndScene();+ return SUCCEEDED(drawn);+}++static bool draw_fixed_function(D3D9OffscreenDevice & fixture, const LitScene & scene,+ unsigned char colour[3])+{+ IDirect3DDevice9 * device = fixture.Get_Device();+ D3DMATRIX identity;+ D3D9Test_Set_Identity(identity);++ clear_target(device);+ device->SetTransform(D3DTS_WORLD, &scene.World);+ device->SetTransform(D3DTS_VIEW, &scene.View);+ device->SetTransform(D3DTS_PROJECTION, &identity);+ device->SetRenderState(D3DRS_LIGHTING, TRUE);+ device->SetRenderState(D3DRS_AMBIENT, to_packed_colour(scene.GlobalAmbient));+ device->SetRenderState(D3DRS_AMBIENTMATERIALSOURCE, D3DMCS_MATERIAL);+ device->SetRenderState(D3DRS_DIFFUSEMATERIALSOURCE, D3DMCS_MATERIAL);+ device->SetRenderState(D3DRS_EMISSIVEMATERIALSOURCE, D3DMCS_MATERIAL);+ set_material(device, scene.MaterialAmbient, scene.MaterialDiffuse, scene.MaterialEmissive,+ MATERIAL_POWER);++ for (unsigned index = 0; index < MAXIMUM_VERTEX_LIGHTS; ++index) {+ if (index >= scene.LightCount) {+ device->LightEnable(index, FALSE);+ continue;+ }+ D3DLIGHT9 light;+ memset(&light, 0, sizeof(light));+ light.Type = D3DLIGHT_DIRECTIONAL;+ memcpy(&light.Diffuse, scene.Lights[index].Diffuse, sizeof(float) * 4);+ light.Direction.x = scene.Lights[index].Direction[0];+ light.Direction.y = scene.Lights[index].Direction[1];+ light.Direction.z = scene.Lights[index].Direction[2];+ device->SetLight(index, &light);+ device->LightEnable(index, TRUE);+ }++ device->SetVertexShader(NULL);+ device->SetFVF(QUAD_FVF);+ if (!draw_quad(device)) {+ return false;+ }+ return fixture.Read_Pixel(TARGET_SIZE / 2, TARGET_SIZE / 2, colour);+}++// Compiles the generated program and hands back the shader, or NULL with the compiler's own words+// printed. The caller owns what comes back.+static IDirect3DVertexShader9 * build_shader(IDirect3DDevice9 * device,+ D3DCompileFunction compile, const std::string & hlsl)+{+ ID3DBlob * code = NULL;+ ID3DBlob * errors = NULL;+ const HRESULT compiled = compile(hlsl.c_str(), hlsl.size(), "ffvertex", NULL, NULL,+ ENTRY_POINT, D3D9_PROFILE, 0, 0, &code, &errors);+ if (errors != NULL) {+ printf(" %s\n", static_cast<const char *>(errors->GetBufferPointer()));+ errors->Release();+ }+ if (FAILED(compiled) || code == NULL) {+ return NULL;+ }++ IDirect3DVertexShader9 * shader = NULL;+ const HRESULT created = device->CreateVertexShader(+ static_cast<const DWORD *>(code->GetBufferPointer()), &shader);+ code->Release();+ return SUCCEEDED(created) ? shader : NULL;+}++static bool draw_generated(D3D9OffscreenDevice & fixture, D3DCompileFunction compile,+ const LitScene & scene, unsigned char colour[3])+{+ IDirect3DDevice9 * device = fixture.Get_Device();++ std::string hlsl;+ if (!VertexShader_Generate(describe(scene), VERTEX_SHADER_TARGET_D3D9, hlsl)) {+ return false;+ }+ IDirect3DVertexShader9 * shader = build_shader(device, compile, hlsl);+ if (shader == NULL) {+ return false;+ }++ clear_target(device);++ D3DMATRIX world_view;+ multiply(scene.World, scene.View, world_view);+ set_matrix(device, VERTEX_REGISTER_WORLD_VIEW_PROJECTION, world_view);+ set_matrix(device, VERTEX_REGISTER_WORLD_VIEW, world_view);+ set_matrix(device, VERTEX_REGISTER_NORMAL_TRANSFORM, world_view);++ device->SetVertexShaderConstantF(VERTEX_REGISTER_MATERIAL_AMBIENT, scene.MaterialAmbient, 1);+ device->SetVertexShaderConstantF(VERTEX_REGISTER_MATERIAL_DIFFUSE, scene.MaterialDiffuse, 1);+ device->SetVertexShaderConstantF(VERTEX_REGISTER_MATERIAL_EMISSIVE, scene.MaterialEmissive, 1);+ const float power[4] = { MATERIAL_POWER, 0.0f, 0.0f, 0.0f };+ device->SetVertexShaderConstantF(VERTEX_REGISTER_MATERIAL_POWER, power, 1);+ device->SetVertexShaderConstantF(VERTEX_REGISTER_GLOBAL_AMBIENT, scene.GlobalAmbient, 1);+ const float no_fog[4] = { 0.0f, 0.0f, 0.0f, 0.0f };+ device->SetVertexShaderConstantF(VERTEX_REGISTER_FOG_PARAMETERS, no_fog, 1);++ for (unsigned index = 0; index < scene.LightCount; ++index) {+ float fields[VERTEX_REGISTERS_PER_LIGHT][4];+ memset(fields, 0, sizeof(fields));+ transform_direction(scene.Lights[index].Direction, scene.View, fields[LIGHT_DIRECTION]);+ memcpy(fields[LIGHT_DIFFUSE], scene.Lights[index].Diffuse, sizeof(float) * 4);+ device->SetVertexShaderConstantF(+ VERTEX_REGISTER_LIGHTS + index * VERTEX_REGISTERS_PER_LIGHT,+ &fields[0][0], VERTEX_REGISTERS_PER_LIGHT);+ }++ device->SetFVF(QUAD_FVF);+ device->SetVertexShader(shader);+ const bool drawn = draw_quad(device);+ device->SetVertexShader(NULL);+ shader->Release();++ return drawn && fixture.Read_Pixel(TARGET_SIZE / 2, TARGET_SIZE / 2, colour);+}++// Runs one scene both ways and reports what came back. A machine with no device or no compiler+// says so and the test passes; that is a test host without a GPU, not a broken generator.+static void compare(const LitScene & scene)+{+ D3D9OffscreenDevice fixture;+ if (!fixture.Create(TARGET_SIZE)) {+ printf(" no Direct3D 9 device on this machine - skipped\n");+ return;+ }+ D3DCompileFunction compile = load_compiler();+ if (compile == NULL) {+ printf(" no %s on this machine - skipped\n", COMPILER_MODULE);+ return;+ }++ unsigned char fixed_function[3] = { 0, 0, 0 };+ unsigned char generated[3] = { 0, 0, 0 };+ CHECK(draw_fixed_function(fixture, scene, fixed_function));+ CHECK(draw_generated(fixture, compile, scene, generated));++ printf(" fixed function bgr %u,%u,%u generated bgr %u,%u,%u\n",+ fixed_function[0], fixed_function[1], fixed_function[2],+ generated[0], generated[1], generated[2]);++ for (unsigned channel = 0; channel < 3; ++channel) {+ const int difference = static_cast<int>(generated[channel])+ - static_cast<int>(fixed_function[channel]);+ CHECK(difference >= -LEVEL_TOLERANCE && difference <= LEVEL_TOLERANCE);+ }+}++static LitScene plain_scene()+{+ LitScene scene;+ memset(&scene, 0, sizeof(scene));+ D3D9Test_Set_Identity(scene.World);+ D3D9Test_Set_Identity(scene.View);++ // Every value differs from every other one, so a channel read in the wrong order comes back as a+ // wrong answer rather than a lucky one.+ const float material_ambient[4] = { 0.4f, 0.3f, 0.2f, 1.0f };+ const float material_diffuse[4] = { 0.9f, 0.8f, 0.7f, 1.0f };+ const float material_emissive[4] = { 0.05f, 0.05f, 0.05f, 0.0f };+ const float global_ambient[4] = { 60.0f / COLOUR_LEVELS, 40.0f / COLOUR_LEVELS,+ 20.0f / COLOUR_LEVELS, 1.0f };+ memcpy(scene.MaterialAmbient, material_ambient, sizeof(material_ambient));+ memcpy(scene.MaterialDiffuse, material_diffuse, sizeof(material_diffuse));+ memcpy(scene.MaterialEmissive, material_emissive, sizeof(material_emissive));+ memcpy(scene.GlobalAmbient, global_ambient, sizeof(global_ambient));+ return scene;+}++TEST(ffvertexd3d9_the_generated_program_lights_a_quad_like_the_fixed_function_does)+{+ LitScene scene = plain_scene();++ // One light coming at the quad from straight in front, so the whole face is lit and the answer+ // is a flat colour rather than a gradient.+ scene.LightCount = 1;+ scene.Lights[0].Direction[2] = -1.0f;+ const float diffuse[4] = { 0.25f, 0.5f, 0.75f, 1.0f };+ memcpy(scene.Lights[0].Diffuse, diffuse, sizeof(diffuse));++ compare(scene);+}++// The building pipeline the D3D11 backend dumps out of a real match, drawn twice. Its key is+// 274:100:0,0,0,0:L3:L3:L3 - the position, normal and one coordinate set that FVF 274 is, lighting+// on with the specular and the vertex colour off, all four material sources reading the material,+// and three directional lights. Nothing else in the frame is shaded by more of the pipeline than+// this, and the buildings are where the residual sits: fitting a line through the two frames puts+// terrain at 0.954 of Direct3D 9's value and models at 0.825 with a lift of nearly six levels.+//+// The world and the view here cancel, so the quad is where it was, but every normal goes through+// the pair and every light direction goes through the view alone. A light left in world space+// lights the wrong side of this.+TEST(ffvertexd3d9_the_building_pipeline_lights_a_quad_like_the_fixed_function_does)+{+ const float ROTATION = 0.7f;++ LitScene scene = plain_scene();+ set_rotation_x(scene.World, ROTATION);+ set_rotation_x(scene.View, -ROTATION);++ scene.LightCount = 3;++ // A key light down and forward, a fill from the left, and a rim from behind and below, which is+ // as close to three unlike directions as one quad can be given.+ const float key_direction[3] = { 0.0f, -0.6f, -0.8f };+ const float key_diffuse[4] = { 0.6f, 0.55f, 0.5f, 1.0f };+ memcpy(scene.Lights[0].Direction, key_direction, sizeof(key_direction));+ memcpy(scene.Lights[0].Diffuse, key_diffuse, sizeof(key_diffuse));++ const float fill_direction[3] = { 0.8f, 0.0f, -0.6f };+ const float fill_diffuse[4] = { 0.2f, 0.25f, 0.3f, 1.0f };+ memcpy(scene.Lights[1].Direction, fill_direction, sizeof(fill_direction));+ memcpy(scene.Lights[1].Diffuse, fill_diffuse, sizeof(fill_diffuse));++ const float rim_direction[3] = { -0.5f, 0.5f, 0.707f };+ const float rim_diffuse[4] = { 0.15f, 0.1f, 0.05f, 1.0f };+ memcpy(scene.Lights[2].Direction, rim_direction, sizeof(rim_direction));+ memcpy(scene.Lights[2].Diffuse, rim_diffuse, sizeof(rim_diffuse));++ compare(scene);+}diff --git a/GeneralsMD/Code/Tests/test_pixelcentre.cpp b/GeneralsMD/Code/Tests/test_pixelcentre.cppnew file mode 100644index 000000000..08130a22c--- /dev/null+++ b/GeneralsMD/Code/Tests/test_pixelcentre.cpp@@ -0,0 +1,369 @@+/*+** 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/>.+*/++// Where an edge lands, on both runtimes, from the same numbers: the edge a triangle's coverage+// makes, and the edge an alpha test cuts. Both are answered by drawing on a Direct3D 9 device and+// through DX11BackendClass in one binary and reading the pixels back.+//+// Direct3D 9 and Direct3D 10 onwards disagree about where a pixel's centre is, and every account of+// that disagreement is written about screen space quads and texel alignment. The engine's screen+// space quads are handled: they carry D3D9's own -0.5 and the generated program gives the half back.+// What no document here has ever established is whether ordinary projected geometry moves as well,+// and that is the question the residual now turns on. Splitting a frame by surface fits a line+// through the two pictures and gets a slope of 1.000 on the command bar, 0.954 on terrain and 0.825+// on models: contrast lost in proportion to how much detail a surface carries, which is what a+// picture sampled half a pixel away from where it was drawn looks like.+//+// So this asks instead of arguing. One quad, its right and bottom edges at screen 32.25 by+// arithmetic neither runtime is allowed a say in, rasterised once by each. The last pixel each edge+// covers is the answer, and it was 32 against 31: the whole frame, not the screen space quads.+// Moving the D3D11 viewport half a pixel takes Alpine Assault from 5.99% away from the Direct3D 9+// frame to 1%.++#include "test_harness.h"++#include "dx11backend.h"+#include "dx11resource.h"+#include "test_d3d9device.h"++#include <stdio.h>+#include <string.h>++static const unsigned TARGET_SIZE = 64;++// A quarter of a pixel past a pixel boundary, so neither runtime is answering a tie. Direct3D 9+// samples a pixel at its integer coordinate and covers pixel 32; Direct3D 11 samples at the+// half-integer and stops at 31 unless its viewport carries the half.+static const float EDGE_SCREEN = 32.25f;+static const float EDGE_CLIP_X = EDGE_SCREEN * 2.0f / TARGET_SIZE - 1.0f;++// Screen y runs down and clip y runs up, so the bottom edge of the quad is the one that lands at+// screen y 32.25. Both axes are measured because the offset has a sign and a viewport carries two+// of them; getting y backwards moves the frame a whole pixel rather than none.+static const float EDGE_CLIP_Y = 1.0f - EDGE_SCREEN * 2.0f / TARGET_SIZE;++// Anything that is not the clear colour is covered. The clear is green and the quad is red, so one+// channel decides it.+static const unsigned char COVERAGE_THRESHOLD = 0x80;++static const DWORD QUAD_COLOUR = 0xffff0000;++struct EdgeVertex+{+ float Position[3];+ float Normal[3];+ DWORD Diffuse;+ float TexCoord0[2];+ float TexCoord1[2];+};++static const DWORD EDGE_FVF = D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_DIFFUSE | D3DFVF_TEX2;++// A rectangle hanging off the top-left corner of the target and ending at EDGE_CLIP_X across and+// EDGE_CLIP_Y down. It starts outside the frame on purpose: an edge that lands exactly on row zero+// is a tie between two fill rules and this test is not about fill rules. Both runtimes get these+// numbers unchanged, every matrix in the test being the identity, so nothing between the vertex and+// the rasteriser can move an edge.+static const float OUTSIDE = 1.2f;++static const EdgeVertex EDGE_QUAD[4] = {+ { { -OUTSIDE, OUTSIDE, 0.5f }, { 0.0f, 0.0f, 1.0f }, QUAD_COLOUR, { 0.0f, 0.0f }, { 0.0f, 0.0f } },+ { { EDGE_CLIP_X, OUTSIDE, 0.5f }, { 0.0f, 0.0f, 1.0f }, QUAD_COLOUR, { 0.0f, 0.0f }, { 0.0f, 0.0f } },+ { { EDGE_CLIP_X, EDGE_CLIP_Y, 0.5f }, { 0.0f, 0.0f, 1.0f }, QUAD_COLOUR, { 0.0f, 0.0f }, { 0.0f, 0.0f } },+ { { -OUTSIDE, EDGE_CLIP_Y, 0.5f }, { 0.0f, 0.0f, 1.0f }, QUAD_COLOUR, { 0.0f, 0.0f }, { 0.0f, 0.0f } }+};++static const unsigned short EDGE_INDICES[6] = { 0, 1, 2, 0, 2, 3 };++// The second question needs a quad that covers the target with its alpha running from nothing on the+// left to full on the right, so an alpha test cuts it somewhere in the middle and the column it cuts+// at is the threshold read back in pixels. Eight of the sixty-six pipelines a Flash Effect frame+// builds carry an alpha test, and all eight are the greater-or-equal one.+static const DWORD ALPHA_TEST_REFERENCE = 128;++static const EdgeVertex ALPHA_QUAD[4] = {+ { { -1.0f, 1.0f, 0.5f }, { 0.0f, 0.0f, 1.0f }, 0x00ff0000, { 0.0f, 0.0f }, { 0.0f, 0.0f } },+ { { 1.0f, 1.0f, 0.5f }, { 0.0f, 0.0f, 1.0f }, 0xffff0000, { 0.0f, 0.0f }, { 0.0f, 0.0f } },+ { { 1.0f, -1.0f, 0.5f }, { 0.0f, 0.0f, 1.0f }, 0xffff0000, { 0.0f, 0.0f }, { 0.0f, 0.0f } },+ { { -1.0f, -1.0f, 0.5f }, { 0.0f, 0.0f, 1.0f }, 0x00ff0000, { 0.0f, 0.0f }, { 0.0f, 0.0f } }+};++// One line of the target, read out of whichever runtime drew it, as blue, green, red.+typedef unsigned char TargetLine[TARGET_SIZE][3];++// The index of the last covered pixel along a line of the target, or -1 if none of it is covered.+// The line is read through a stride, so one function reads a row and a column both.+static int last_covered(const unsigned char * line, unsigned stride)+{+ int last = -1;+ for (unsigned step = 0; step < TARGET_SIZE; ++step) {+ // bgra, so red is the third byte.+ if (line[step * stride + 2] >= COVERAGE_THRESHOLD) {+ last = static_cast<int>(step);+ }+ }+ return last;+}++static int first_covered(const TargetLine line)+{+ for (unsigned step = 0; step < TARGET_SIZE; ++step) {+ if (line[step][2] >= COVERAGE_THRESHOLD) {+ return static_cast<int>(step);+ }+ }+ return -1;+}++static bool direct3d9_draw(const EdgeVertex quad[4], bool alpha_test, TargetLine row,+ TargetLine column)+{+ D3D9OffscreenDevice fixture;+ if (!fixture.Create(TARGET_SIZE)) {+ return false;+ }+ IDirect3DDevice9 * device = fixture.Get_Device();++ D3DMATRIX identity;+ D3D9Test_Set_Identity(identity);++ fixture.Clear(D3DCOLOR_ARGB(255, 0, 255, 0));+ device->SetTransform(D3DTS_WORLD, &identity);+ device->SetTransform(D3DTS_VIEW, &identity);+ device->SetTransform(D3DTS_PROJECTION, &identity);+ device->SetRenderState(D3DRS_ZENABLE, D3DZB_FALSE);+ device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);+ device->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);+ device->SetRenderState(D3DRS_LIGHTING, FALSE);+ device->SetRenderState(D3DRS_MULTISAMPLEANTIALIAS, FALSE);+ device->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);+ device->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_DIFFUSE);+ device->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);+ device->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_DIFFUSE);+ device->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE);+ device->SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_DISABLE);+ device->SetRenderState(D3DRS_ALPHATESTENABLE, alpha_test ? TRUE : FALSE);+ device->SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_GREATEREQUAL);+ device->SetRenderState(D3DRS_ALPHAREF, ALPHA_TEST_REFERENCE);+ device->SetVertexShader(NULL);+ device->SetFVF(EDGE_FVF);++ if (FAILED(device->BeginScene())) {+ return false;+ }+ const HRESULT drawn = device->DrawIndexedPrimitiveUP(D3DPT_TRIANGLELIST, 0, 4, 2,+ EDGE_INDICES, D3DFMT_INDEX16, quad, sizeof(EdgeVertex));+ device->EndScene();+ if (FAILED(drawn)) {+ return false;+ }++ // Row zero for anything that varies across the target and column zero for anything that varies+ // down it, both of them lines the quads cover whatever the two runtimes decide.+ for (unsigned step = 0; step < TARGET_SIZE; ++step) {+ if (!fixture.Read_Pixel(step, 0, row[step])) {+ return false;+ }+ }+ for (unsigned step = 0; step < TARGET_SIZE; ++step) {+ if (!fixture.Read_Pixel(0, step, column[step])) {+ return false;+ }+ }+ return true;+}++// The same draw through the backend the engine drives, set up the way it sets an unlit pass through+// up: no lighting, the vertex colour selected, nothing bound.+static void configure_unlit(DX11BackendClass & backend)+{+ float identity[16];+ memset(identity, 0, sizeof(identity));+ identity[0] = 1.0f;+ identity[5] = 1.0f;+ identity[10] = 1.0f;+ identity[15] = 1.0f;+ 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);++ 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(EDGE_FVF);+}++static bool direct3d11_draw(const EdgeVertex quad[4], bool alpha_test, TargetLine row,+ TargetLine column)+{+ DX11DeviceClass device;+ if (!device.Create_Offscreen()) {+ return false;+ }+ ID3D11Device * d3d = device.Get_Device();++ DX11BackendClass backend;+ if (!backend.Initialise(&device)) {+ return false;+ }++ 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;++ 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 * target = NULL;+ ID3D11Texture2D * staging = NULL;+ ID3D11RenderTargetView * target_view = NULL;+ ID3D11Buffer * vertices = NULL;+ ID3D11Buffer * indices = NULL;+ bool read = false;++ if (SUCCEEDED(d3d->CreateTexture2D(&target_description, NULL, &target))+ && SUCCEEDED(d3d->CreateTexture2D(&staging_description, NULL, &staging))+ && SUCCEEDED(d3d->CreateRenderTargetView(target, NULL, &target_view))+ && DX11Resource_Create_Vertex_Buffer(d3d, sizeof(EdgeVertex) * 4, D3DPOOL_MANAGED, 0,+ quad, &vertices)+ && DX11Resource_Create_Index_Buffer(d3d, sizeof(EDGE_INDICES), D3DPOOL_MANAGED, 0,+ EDGE_INDICES, &indices)) {++ 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(backend);+ backend.Set_Render_State(D3DRS_ALPHATESTENABLE, alpha_test ? TRUE : FALSE);+ backend.Set_Render_State(D3DRS_ALPHAFUNC, D3DCMP_GREATEREQUAL);+ backend.Set_Render_State(D3DRS_ALPHAREF, ALPHA_TEST_REFERENCE);+ backend.Set_Stream_Source(vertices, sizeof(EdgeVertex), 0);+ backend.Set_Indices(indices, DXGI_FORMAT_R16_UINT);++ if (backend.Draw_Indexed_Triangles(6, 0, 0)) {+ device.Get_Context()->CopyResource(staging, target);+ D3D11_MAPPED_SUBRESOURCE mapped;+ if (SUCCEEDED(device.Get_Context()->Map(staging, 0, D3D11_MAP_READ, 0, &mapped))) {+ const unsigned char * corner = static_cast<const unsigned char *>(mapped.pData);+ for (unsigned step = 0; step < TARGET_SIZE; ++step) {+ memcpy(row[step], corner + step * 4, 3);+ memcpy(column[step], corner + step * mapped.RowPitch, 3);+ }+ device.Get_Context()->Unmap(staging, 0);+ read = true;+ }+ }+ }++ if (indices != NULL) {+ indices->Release();+ }+ if (vertices != NULL) {+ vertices->Release();+ }+ if (target_view != NULL) {+ target_view->Release();+ }+ if (staging != NULL) {+ staging->Release();+ }+ if (target != NULL) {+ target->Release();+ }+ backend.Shutdown();+ return read;+}++TEST(pixelcentre_the_two_runtimes_cover_the_same_pixels)+{+ TargetLine nine_row;+ TargetLine nine_column;+ TargetLine eleven_row;+ TargetLine eleven_column;++ if (!direct3d9_draw(EDGE_QUAD, false, nine_row, nine_column)+ || !direct3d11_draw(EDGE_QUAD, false, eleven_row, eleven_column)) {+ printf(" no Direct3D 9 or Direct3D 11 device on this machine - skipped\n");+ return;+ }++ const int nine_across = last_covered(&nine_row[0][0], 3);+ const int nine_down = last_covered(&nine_column[0][0], 3);+ const int eleven_across = last_covered(&eleven_row[0][0], 3);+ const int eleven_down = last_covered(&eleven_column[0][0], 3);++ printf(" edge at screen %.2f: Direct3D 9 covers to %d,%d and Direct3D 11 to %d,%d\n",+ EDGE_SCREEN, nine_across, nine_down, eleven_across, eleven_down);++ CHECK_EQ(eleven_across, nine_across);+ CHECK_EQ(eleven_down, nine_down);+}++// The alpha test, which the generated pixel program turns into a clip because D3D11 has no alpha+// test of its own. Direct3D 9 compared the eight bit alpha that was about to be written; the clip+// compares a float, and where those two disagree is a one pixel band along every alpha tested edge+// in the frame - which is where the difference that is left lives. Eight of the sixty-six pipelines+// a Flash Effect frame builds carry one, and that view is one of the three still outside the margin.+TEST(pixelcentre_the_two_runtimes_cut_the_same_pixels)+{+ TargetLine nine_row;+ TargetLine nine_column;+ TargetLine eleven_row;+ TargetLine eleven_column;++ if (!direct3d9_draw(ALPHA_QUAD, true, nine_row, nine_column)+ || !direct3d11_draw(ALPHA_QUAD, true, eleven_row, eleven_column)) {+ printf(" no Direct3D 9 or Direct3D 11 device on this machine - skipped\n");+ return;+ }++ const int nine_cut = first_covered(nine_row);+ const int eleven_cut = first_covered(eleven_row);++ printf(" alpha reference %u: Direct3D 9 keeps from column %d, Direct3D 11 from %d\n",+ ALPHA_TEST_REFERENCE, nine_cut, eleven_cut);++ CHECK_EQ(eleven_cut, nine_cut);+}diff --git a/dx11-check.ps1 b/dx11-check.ps1index 23b40a6a7..c39a5e037 100644--- a/dx11-check.ps1+++ b/dx11-check.ps1@@ -19,7 +19,14 @@# The views are tree-check.ps1's, for the same reason it has them: they are the eight positions in# UI-MAP.md that between them frame terrain, trees, water, roads, shadows and the command bar.-param([double]$Margin = 1.0)+# -Map narrows the run to the views whose map name contains it, for the middle of a hunt where one+# view answers the question and eight of them is twenty-four launches. The table in+# RENDERER-ROADMAP.md is only ever written from a full run.+#+# -BackendNoise takes the repeated pair through the Direct3D 11 backend instead, which answers a+# different question: the printed floor is Direct3D 9 against itself, and a backend with a+# repeatability of its own would be measured against a floor that cannot see it.+param([double]$Margin = 1.0, [string]$Map = '', [switch]$BackendNoise)Add-Type -AssemblyName System.Drawing$run = Join-Path $PSScriptRoot "GeneralsMD\Run"@@ -88,13 +95,21 @@ function DiffPct($a, $b) {return [Math]::Round(100.0 * $apart / $total, 2)}+if ($Map -ne '') { $cases = @($cases | Where-Object { $_.map -like "*$Map*" }) }+if ($cases.Count -eq 0) { throw "no view matches -Map $Map" }+$fail = 0foreach ($c in $cases) {$tag = ($c.map -replace '[^A-Za-z]','') + "_$($c.x)_$($c.f)"$nine = Shoot $c "d3d9a_$tag" @()- $again = Shoot $c "d3d9b_$tag" @()$eleven = Shoot $c "dx11_$tag" @('-dx11present')- $noise = DiffPct $nine $again+ if ($BackendNoise) {+ $again = Shoot $c "dx11b_$tag" @('-dx11present')+ $noise = DiffPct $eleven $again+ } else {+ $again = Shoot $c "d3d9b_$tag" @()+ $noise = DiffPct $nine $again+ }$signal = DiffPct $nine $eleven$verdict = if ($signal -le ($noise + $Margin)) { 'ok' } else { 'DIFFERENT' }if ($verdict -ne 'ok') { $fail++ }