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(ww3d2): draw the game through the Direct3D 11 backend

Olcay Seyganef8303a9e42a
diff --git a/GeneralsMD/Code/CMakeLists.txt b/GeneralsMD/Code/CMakeLists.txt
index 038591c8f..c745850de 100644
--- a/GeneralsMD/Code/CMakeLists.txt
+++ b/GeneralsMD/Code/CMakeLists.txt
@@ -214,6 +214,16 @@ set_target_properties(ffvertex PROPERTIES CXX_STANDARD 17)
target_include_directories(ffvertex PUBLIC ${WW}/WW3D2)
target_link_libraries(ffvertex PUBLIC d3d9)
+# ---- engineshader ---------------------------------------------------------
+# The shipped .vso and .pso files transcribed as HLSL, for the draws that bind one
+# of the engine's own shaders and set no fixed-function state a generator could read.
+# Its own library for the same reason ffvertex is: string building over an enum, and
+# the test compiles what it writes without a device anywhere near it.
+add_library(engineshader STATIC ${WW}/WW3D2/engineshader.cpp)
+set_target_properties(engineshader PROPERTIES CXX_STANDARD 17)
+target_include_directories(engineshader PUBLIC ${WW}/WW3D2)
+target_link_libraries(engineshader PUBLIC ffshader)
+
# ---- 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
@@ -248,6 +258,24 @@ set_target_properties(dx11resource PROPERTIES CXX_STANDARD 17)
target_include_directories(dx11resource PUBLIC ${WW}/WW3D2)
target_link_libraries(dx11resource PUBLIC d3d9 d3d11)
+# ---- dx11twin -------------------------------------------------------------
+# The D3D11 copy of a vertex or index buffer and the heap block both copies are
+# written through. A D3D9 buffer is write-only, so the copy cannot be built after
+# the fact and the lock has to be moved instead; the test proves the same bytes end
+# up on both sides.
+add_library(dx11twin STATIC ${WW}/WW3D2/dx11twin.cpp)
+set_target_properties(dx11twin PROPERTIES CXX_STANDARD 17)
+target_include_directories(dx11twin PUBLIC ${WW}/WW3D2)
+target_link_libraries(dx11twin PUBLIC dx11resource d3d11)
+
+# ---- dx11texture ----------------------------------------------------------
+# The D3D11 copy of a texture the engine already built in D3D9, read back off the
+# managed original at the first bind and kept on it as private data.
+add_library(dx11texture STATIC ${WW}/WW3D2/dx11texture.cpp)
+set_target_properties(dx11texture PROPERTIES CXX_STANDARD 17)
+target_include_directories(dx11texture PUBLIC ${WW}/WW3D2)
+target_link_libraries(dx11texture PUBLIC dx11resource d3d9 d3d11 dxguid)
+
# ---- 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
@@ -256,7 +284,7 @@ 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)
+ engineshader ffshader ffvertex)
# ---- ww3d2 (renderer core) ------------------------------------------------
# wwshade is header-only here on purpose: no .dsp links wwshade.lib and its
@@ -313,7 +341,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 ffshader dx11backend
+ PUBLIC d3d9 dxguid vfw32 d3dx9runtime ffshader dx11backend dx11twin dx11texture
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
@@ -675,7 +703,10 @@ 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_engineshader engineshader)
add_lib_test(test_dx11backend dx11backend)
+add_lib_test(test_dx11twin dx11twin dx11device)
+add_lib_test(test_dx11texture dx11texture dx11device user32)
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 8e10afe56..e4eb1c950 100644
--- a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h
+++ b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h
@@ -124,6 +124,8 @@ public:
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
+ Bool m_direct3D11Present; ///< -dx11present: show that backend's frame instead of Direct3D 9's
+ AsciiString m_direct3D11DumpPath; ///< -dx11dump: where to write each generated program
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 d57220aa9..d3551b0d2 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp
@@ -1363,6 +1363,38 @@ Int parseDirect3D11(char *args[], int num)
return 1;
}
+/* -dx11present: put the Direct3D 11 frame on the screen, and read screenshots back from it.
+ *
+ * Implies -dx11. Without it the backend draws into a back buffer nothing ever shows, which is
+ * how both renderers can run in the same frame while phase 2 is unfinished; with it the window
+ * and the .bmp are the D3D11 picture, so tree-check.ps1 can photograph one against the other.
+ * A frame the backend refuses parts of is a frame with those parts missing - that is the point
+ * of looking. */
+/* -dx11dump <directory>: write every program the Direct3D 11 backend generates into that
+ * directory as it is built, named by the order it was built in with the state it came from on
+ * its first line. Implies -dx11. A generated program that draws the wrong thing cannot be read
+ * any other way: the state is a key and the key is not the code. */
+Int parseDirect3D11Dump(char *args[], int num)
+{
+ if (num > 1 && TheWritableGlobalData)
+ {
+ TheWritableGlobalData->m_direct3D11 = TRUE;
+ TheWritableGlobalData->m_direct3D11DumpPath = args[1];
+ return 2;
+ }
+ return 1;
+}
+
+Int parseDirect3D11Present(char *args[], int num)
+{
+ if (TheWritableGlobalData)
+ {
+ TheWritableGlobalData->m_direct3D11 = TRUE;
+ TheWritableGlobalData->m_direct3D11Present = TRUE;
+ }
+ return 1;
+}
+
Int parseCombinerShaders(char *args[], int num)
{
if (TheWritableGlobalData)
@@ -2130,6 +2162,8 @@ static CommandLineParam params[] =
{ "-ffprobe", parseFixedFunctionProbe },
{ "-ffshader", parseCombinerShaders },
{ "-dx11", parseDirect3D11 },
+ { "-dx11present", parseDirect3D11Present },
+ { "-dx11dump", parseDirect3D11Dump },
{ "-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 4d3f56643..254015c19 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp
@@ -649,6 +649,8 @@ GlobalData::GlobalData()
m_fixedFunctionProbe = FALSE;
m_combinerShaders = FALSE;
m_direct3D11 = FALSE;
+ m_direct3D11Present = FALSE;
+ m_direct3D11DumpPath.clear();
m_xResolution = 800;
m_yResolution = 600;
m_maxShellScreens = 0;
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DProjectedShadow.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DProjectedShadow.cpp
index 1642ac59f..ea5755ded 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DProjectedShadow.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DProjectedShadow.cpp
@@ -112,6 +112,13 @@ struct SHADOW_DECAL_VERTEX //vertex structure passed to D3D
LPDIRECT3DVERTEXBUFFER9 shadowDecalVertexBufferD3D=NULL; ///<D3D vertex buffer
LPDIRECT3DINDEXBUFFER9 shadowDecalIndexBufferD3D=NULL; ///<D3D index buffer
+
+//The Direct3D 11 copies of the two above, and of the two the volumetric shadows own, which the
+//terrain-projected pass borrows. See W3DVolumetricShadow.cpp for why these are held by hand.
+DX11BufferTwinClass *shadowDecalVertexTwin=NULL;
+DX11BufferTwinClass *shadowDecalIndexTwin=NULL;
+extern DX11BufferTwinClass *shadowVertexTwin;
+extern DX11BufferTwinClass *shadowIndexTwin;
int nShadowDecalVertsInBuf=0; //model vetices in vertex buffer
int nShadowDecalStartBatchVertex=0;
int nShadowDecalIndicesInBuf=0; //model vetices in vertex buffer
@@ -300,6 +307,8 @@ Bool W3DProjectedShadowManager::ReAcquireResources(void)
)))
return FALSE;
+ shadowDecalIndexTwin = Direct3D11_Twin_Index_Buffer(SHADOW_DECAL_INDEX_SIZE*sizeof(WORD), true);
+
if (shadowDecalVertexBufferD3D == NULL)
{ // Create vertex buffer
@@ -313,6 +322,9 @@ Bool W3DProjectedShadowManager::ReAcquireResources(void)
NULL // pSharedHandle, D3D9's extra parameter, reserved and always null
)))
return FALSE;
+
+ shadowDecalVertexTwin = Direct3D11_Twin_Vertex_Buffer(
+ SHADOW_DECAL_VERTEX_SIZE*sizeof(SHADOW_DECAL_VERTEX), true);
}
return TRUE;
@@ -328,6 +340,10 @@ void W3DProjectedShadowManager::ReleaseResources(void)
shadowDecalVertexBufferD3D->Release();
shadowDecalIndexBufferD3D=NULL;
shadowDecalVertexBufferD3D=NULL;
+ delete shadowDecalIndexTwin;
+ delete shadowDecalVertexTwin;
+ shadowDecalIndexTwin=NULL;
+ shadowDecalVertexTwin=NULL;
}
void W3DProjectedShadowManager::invalidateCachedLightPositions(void)
@@ -408,18 +424,31 @@ Int W3DProjectedShadowManager::renderProjectedTerrainShadow(W3DProjectedShadow *
Int numVerts = vertsPerRow *vertsPerColumn; //number of terrain vertices
+ DX11BufferLockClass vertexLock;
+ const UnsignedInt vertexStride = sizeof(SHADOW_VOLUME_VERTEX);
+ UnsignedInt vertexOffset;
+ UnsignedInt vertexFlags;
if (nShadowVertsInBuf > (SHADOW_VERTEX_SIZE-numVerts)) //check if room for model verts
{ //flush the buffer by drawing the contents and re-locking again
- if (shadowVertexBufferD3D->Lock(0,numVerts*sizeof(SHADOW_VOLUME_VERTEX),(void**)&pvVertices,D3DLOCK_DISCARD) != D3D_OK)
+ vertexOffset=0;
+ vertexFlags=D3DLOCK_DISCARD;
+ if (shadowVertexBufferD3D->Lock(0,numVerts*vertexStride,(void**)&pvVertices,D3DLOCK_DISCARD) != D3D_OK)
return 0;
nShadowVertsInBuf=0;
nShadowStartBatchVertex=0;
}
else
- { if (shadowVertexBufferD3D->Lock(nShadowVertsInBuf*sizeof(SHADOW_VOLUME_VERTEX),numVerts*sizeof(SHADOW_VOLUME_VERTEX), (void**)&pvVertices,D3DLOCK_NOOVERWRITE) != D3D_OK)
+ { vertexOffset=nShadowVertsInBuf*vertexStride;
+ vertexFlags=D3DLOCK_NOOVERWRITE;
+ if (shadowVertexBufferD3D->Lock(vertexOffset,numVerts*vertexStride, (void**)&pvVertices,D3DLOCK_NOOVERWRITE) != D3D_OK)
return 0;
}
+ void *vertexTarget = vertexLock.Begin(shadowVertexTwin, pvVertices, vertexOffset,
+ numVerts*vertexStride, vertexFlags);
+ if (vertexTarget != NULL)
+ pvVertices = (SHADOW_VOLUME_VERTEX *)vertexTarget;
+
if(pvVertices)
{
//insert each cell's bottom/left edge vertex
@@ -437,22 +466,35 @@ Int W3DProjectedShadowManager::renderProjectedTerrainShadow(W3DProjectedShadow *
}
}
+ vertexLock.End();
shadowVertexBufferD3D->Unlock();
Int numIndex=(endX - startX) * (endY-startY)*6; //6 indices per terrain cell (2 triangles).
+ DX11BufferLockClass indexLock;
+ UnsignedInt indexOffset;
+ UnsignedInt indexFlags;
if (nShadowIndicesInBuf > (SHADOW_INDEX_SIZE-numIndex)) //check if room for model verts
{ //flush the buffer by drawing the contents and re-locking again
+ indexOffset=0;
+ indexFlags=D3DLOCK_DISCARD;
if (shadowIndexBufferD3D->Lock(0,numIndex*sizeof(short),(void**)&pvIndices,D3DLOCK_DISCARD) != D3D_OK)
return 0;
nShadowIndicesInBuf=0;
nShadowStartBatchIndex=0;
}
else
- { if (shadowIndexBufferD3D->Lock(nShadowIndicesInBuf*sizeof(short),numIndex*sizeof(short), (void**)&pvIndices,D3DLOCK_NOOVERWRITE) != D3D_OK)
+ { indexOffset=nShadowIndicesInBuf*sizeof(short);
+ indexFlags=D3DLOCK_NOOVERWRITE;
+ if (shadowIndexBufferD3D->Lock(indexOffset,numIndex*sizeof(short), (void**)&pvIndices,D3DLOCK_NOOVERWRITE) != D3D_OK)
return 0;
}
+ void *indexTarget = indexLock.Begin(shadowIndexTwin, pvIndices, indexOffset,
+ numIndex*sizeof(short), indexFlags);
+ if (indexTarget != NULL)
+ pvIndices = (UnsignedShort *)indexTarget;
+
if(pvIndices)
{ //fill each cell's vertex indices
Int rowStart;
@@ -497,44 +539,47 @@ Int W3DProjectedShadowManager::renderProjectedTerrainShadow(W3DProjectedShadow *
}
}
+ indexLock.End();
shadowIndexBufferD3D->Unlock();
// D3D9 takes the base vertex index on the draw call, not here.
m_pDev->SetIndices(shadowIndexBufferD3D);
-
+ Direct3D11_Mirror_Indices(shadowIndexTwin);
+
m_pDev->SetTransform(D3DTS_WORLD,(_D3DMATRIX *)&mWorld);
+ Direct3D11_Mirror_Transform(D3DTS_WORLD,(const float *)&mWorld);
- m_pDev->SetStreamSource(0,shadowVertexBufferD3D,0,sizeof(SHADOW_VOLUME_VERTEX));
- m_pDev->SetFVF(SHADOW_VOLUME_FVF);
+ m_pDev->SetStreamSource(0,shadowVertexBufferD3D,0,vertexStride);
+ Direct3D11_Mirror_Stream_Source(shadowVertexTwin, vertexStride, 0);
+ DX8Wrapper::Set_Vertex_Format(SHADOW_VOLUME_FVF);
Int numPolys = (endX - startX)*(endY - startY)*2; //2 triangles per cell
- m_pDev->SetRenderState(D3DRS_ALPHATESTENABLE, TRUE); //should reject background pixels
- m_pDev->SetRenderState( D3DRS_STENCILENABLE, TRUE );
- m_pDev->SetRenderState( D3DRS_STENCILFUNC, D3DCMP_ALWAYS );
- m_pDev->SetRenderState( D3DRS_STENCILREF, 0x1 );
- m_pDev->SetRenderState( D3DRS_STENCILMASK, 0xffffffff );
- m_pDev->SetRenderState( D3DRS_STENCILWRITEMASK,0xffffffff );
- m_pDev->SetRenderState( D3DRS_STENCILZFAIL, D3DSTENCILOP_KEEP );
- m_pDev->SetRenderState( D3DRS_STENCILFAIL, D3DSTENCILOP_KEEP );
- m_pDev->SetRenderState( D3DRS_STENCILPASS, D3DSTENCILOP_INCR );
-
-// m_pDev->SetRenderState( D3DRS_ALPHABLENDENABLE, FALSE ); //useful to see bounds
- m_pDev->SetRenderState( D3DRS_LIGHTING, FALSE);
- m_pDev->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_DESTCOLOR);
- m_pDev->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_ZERO );
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_ALPHATESTENABLE, TRUE); //should reject background pixels
+ DX8Wrapper::Set_DX8_Render_State( D3DRS_STENCILENABLE, TRUE );
+ DX8Wrapper::Set_DX8_Render_State( D3DRS_STENCILFUNC, D3DCMP_ALWAYS );
+ DX8Wrapper::Set_DX8_Render_State( D3DRS_STENCILREF, 0x1 );
+ DX8Wrapper::Set_DX8_Render_State( D3DRS_STENCILMASK, 0xffffffff );
+ DX8Wrapper::Set_DX8_Render_State( D3DRS_STENCILWRITEMASK,0xffffffff );
+ DX8Wrapper::Set_DX8_Render_State( D3DRS_STENCILZFAIL, D3DSTENCILOP_KEEP );
+ DX8Wrapper::Set_DX8_Render_State( D3DRS_STENCILFAIL, D3DSTENCILOP_KEEP );
+ DX8Wrapper::Set_DX8_Render_State( D3DRS_STENCILPASS, D3DSTENCILOP_INCR );
+
+ DX8Wrapper::Set_DX8_Render_State( D3DRS_LIGHTING, FALSE);
+ DX8Wrapper::Set_DX8_Render_State( D3DRS_SRCBLEND, D3DBLEND_DESTCOLOR);
+ DX8Wrapper::Set_DX8_Render_State( D3DRS_DESTBLEND, D3DBLEND_ZERO );
+
-
if (DX8Wrapper::_Is_Triangle_Draw_Enabled())
{
Debug_Statistics::Record_DX8_Polys_And_Vertices(numPolys,numVerts,ShaderClass::_PresetOpaqueShader);
m_pDev->DrawIndexedPrimitive(D3DPT_TRIANGLELIST,nShadowStartBatchVertex,0,numVerts,nShadowStartBatchIndex,numPolys);
+ Direct3D11_Draw_Indexed_Triangles(numIndex,nShadowStartBatchIndex,nShadowStartBatchVertex);
}
- m_pDev->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE); //should reject background pixels
- m_pDev->SetRenderState( D3DRS_STENCILENABLE, FALSE );
-// m_pDev->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE );
- m_pDev->SetRenderState( D3DRS_LIGHTING, TRUE);
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_ALPHATESTENABLE, FALSE); //should reject background pixels
+ DX8Wrapper::Set_DX8_Render_State( D3DRS_STENCILENABLE, FALSE );
+ DX8Wrapper::Set_DX8_Render_State( D3DRS_LIGHTING, TRUE);
nShadowVertsInBuf += numVerts;
nShadowStartBatchVertex=nShadowVertsInBuf;
@@ -751,10 +796,14 @@ void W3DProjectedShadowManager::flushDecals(W3DShadowTexture *texture, ShadowTyp
// D3D9 takes the base vertex index on the draw call, not here.
m_pDev->SetIndices(shadowDecalIndexBufferD3D);
+ Direct3D11_Mirror_Indices(shadowDecalIndexTwin);
+
m_pDev->SetTransform(D3DTS_WORLD,(_D3DMATRIX *)&mWorld);
+ Direct3D11_Mirror_Transform(D3DTS_WORLD,(const float *)&mWorld);
m_pDev->SetStreamSource(0,shadowDecalVertexBufferD3D,0,sizeof(SHADOW_DECAL_VERTEX));
- m_pDev->SetFVF(SHADOW_DECAL_FVF);
+ Direct3D11_Mirror_Stream_Source(shadowDecalVertexTwin, sizeof(SHADOW_DECAL_VERTEX), 0);
+ DX8Wrapper::Set_Vertex_Format(SHADOW_DECAL_FVF);
//Hard Shadows using stencil
/* m_pDev->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_ZERO);
@@ -776,6 +825,8 @@ void W3DProjectedShadowManager::flushDecals(W3DShadowTexture *texture, ShadowTyp
{
Debug_Statistics::Record_DX8_Polys_And_Vertices(nShadowDecalPolysInBatch,nShadowDecalVertsInBatch,ShaderClass::_PresetOpaqueShader);
m_pDev->DrawIndexedPrimitive(D3DPT_TRIANGLELIST,nShadowDecalStartBatchVertex,0,nShadowDecalVertsInBatch,nShadowDecalStartBatchIndex,nShadowDecalPolysInBatch);
+ Direct3D11_Draw_Indexed_Triangles(nShadowDecalPolysInBatch*3,nShadowDecalStartBatchIndex,
+ nShadowDecalStartBatchVertex);
}
// m_pDev->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE); //should reject background pixels
@@ -1024,10 +1075,16 @@ void W3DProjectedShadowManager::queueDecal(W3DProjectedShadow *shadow)
SHADOW_DECAL_VERTEX* pvVertices;
UnsignedShort *pvIndices;
+ DX11BufferLockClass vertexLock;
+ const UnsignedInt vertexStride = sizeof(SHADOW_DECAL_VERTEX);
+ UnsignedInt vertexOffset;
+ UnsignedInt vertexFlags;
if (nShadowDecalVertsInBuf > (SHADOW_DECAL_VERTEX_SIZE-numVerts)) //check if room for model verts
{ //flush the buffer by drawing the contents and re-locking again
flushDecals(shadow->m_shadowTexture[0], shadow->m_type);
- if (shadowDecalVertexBufferD3D->Lock(0,numVerts*sizeof(SHADOW_DECAL_VERTEX),(void**)&pvVertices,D3DLOCK_DISCARD) != D3D_OK)
+ vertexOffset=0;
+ vertexFlags=D3DLOCK_DISCARD;
+ if (shadowDecalVertexBufferD3D->Lock(0,numVerts*vertexStride,(void**)&pvVertices,D3DLOCK_DISCARD) != D3D_OK)
return;
nShadowDecalStartBatchVertex=0;
@@ -1036,10 +1093,17 @@ void W3DProjectedShadowManager::queueDecal(W3DProjectedShadow *shadow)
nShadowDecalVertsInBuf=0;
}
else
- { if (shadowDecalVertexBufferD3D->Lock(nShadowDecalVertsInBuf*sizeof(SHADOW_DECAL_VERTEX),numVerts*sizeof(SHADOW_DECAL_VERTEX), (void**)&pvVertices,D3DLOCK_NOOVERWRITE) != D3D_OK)
+ { vertexOffset=nShadowDecalVertsInBuf*vertexStride;
+ vertexFlags=D3DLOCK_NOOVERWRITE;
+ if (shadowDecalVertexBufferD3D->Lock(vertexOffset,numVerts*vertexStride, (void**)&pvVertices,D3DLOCK_NOOVERWRITE) != D3D_OK)
return;
}
+ void *vertexTarget = vertexLock.Begin(shadowDecalVertexTwin, pvVertices, vertexOffset,
+ numVerts*vertexStride, vertexFlags);
+ if (vertexTarget != NULL)
+ pvVertices = (SHADOW_DECAL_VERTEX *)vertexTarget;
+
//code to deal with rotated shadows based on sun direction, fix this later. For now shadow rotates with object rotation.
//shadow->m_shadowTexture[0]->getDecalUVAxis(&uVector,&vVector);
//uVector *= 20.0f/dx;//shadow->m_decalRadius; //scale texture to fit object
@@ -1094,12 +1158,18 @@ void W3DProjectedShadowManager::queueDecal(W3DProjectedShadow *shadow)
}
}
+ vertexLock.End();
shadowDecalVertexBufferD3D->Unlock();
+ DX11BufferLockClass indexLock;
+ UnsignedInt indexOffset;
+ UnsignedInt indexFlags;
if (nShadowDecalIndicesInBuf > (SHADOW_DECAL_INDEX_SIZE-numIndex)) //check if room for model verts
{ //flush the buffer by drawing the contents and re-locking again
flushDecals(shadow->m_shadowTexture[0], shadow->m_type);
+ indexOffset=0;
+ indexFlags=D3DLOCK_DISCARD;
if (shadowDecalIndexBufferD3D->Lock(0,numIndex*sizeof(short),(void**)&pvIndices,D3DLOCK_DISCARD) != D3D_OK)
return;
@@ -1109,10 +1179,17 @@ void W3DProjectedShadowManager::queueDecal(W3DProjectedShadow *shadow)
nShadowDecalIndicesInBuf=0;
}
else
- { if (shadowDecalIndexBufferD3D->Lock(nShadowDecalIndicesInBuf*sizeof(short),numIndex*sizeof(short), (void**)&pvIndices,D3DLOCK_NOOVERWRITE) != D3D_OK)
+ { indexOffset=nShadowDecalIndicesInBuf*sizeof(short);
+ indexFlags=D3DLOCK_NOOVERWRITE;
+ if (shadowDecalIndexBufferD3D->Lock(indexOffset,numIndex*sizeof(short), (void**)&pvIndices,D3DLOCK_NOOVERWRITE) != D3D_OK)
return;
}
+ void *indexTarget = indexLock.Begin(shadowDecalIndexTwin, pvIndices, indexOffset,
+ numIndex*sizeof(short), indexFlags);
+ if (indexTarget != NULL)
+ pvIndices = (UnsignedShort *)indexTarget;
+
try {
if(pvIndices)
{ //fill each cell's vertex indices
@@ -1120,7 +1197,7 @@ void W3DProjectedShadowManager::queueDecal(W3DProjectedShadow *shadow)
for (j=startY,rowStart=0; j<endY; j++,rowStart+=vertsPerRow)
{
for (i=rowStart,k=startX; k<endX; i++,k++)
- {
+ {
///@todo: fix the winding order in heightmap to be in strip order like above!
if (hmap->getFlipState(k,j))
{ pvIndices[0]=i+1+nShadowDecalVertsInBatch;
@@ -1146,6 +1223,7 @@ void W3DProjectedShadowManager::queueDecal(W3DProjectedShadow *shadow)
} catch(...) {
IndexBufferExceptionFunc();
}
+ indexLock.End();
shadowDecalIndexBufferD3D->Unlock();
Int numPolys = (endX - startX)*(endY - startY)*2; //2 triangles per cell
@@ -1200,10 +1278,16 @@ void W3DProjectedShadowManager::queueSimpleDecal(W3DProjectedShadow *shadow)
SHADOW_DECAL_VERTEX* pvVertices;
UnsignedShort *pvIndices;
+ DX11BufferLockClass vertexLock;
+ const UnsignedInt vertexStride = sizeof(SHADOW_DECAL_VERTEX);
+ UnsignedInt vertexOffset;
+ UnsignedInt vertexFlags;
if (nShadowDecalVertsInBuf > (SHADOW_DECAL_VERTEX_SIZE-numVerts)) //check if room for model verts
{ //flush the buffer by drawing the contents and re-locking again
flushDecals(shadow->m_shadowTexture[0], shadow->m_type);
- if (shadowDecalVertexBufferD3D->Lock(0,numVerts*sizeof(SHADOW_DECAL_VERTEX),(void**)&pvVertices,D3DLOCK_DISCARD) != D3D_OK)
+ vertexOffset=0;
+ vertexFlags=D3DLOCK_DISCARD;
+ if (shadowDecalVertexBufferD3D->Lock(0,numVerts*vertexStride,(void**)&pvVertices,D3DLOCK_DISCARD) != D3D_OK)
return;
nShadowDecalStartBatchVertex=0;
@@ -1212,10 +1296,17 @@ void W3DProjectedShadowManager::queueSimpleDecal(W3DProjectedShadow *shadow)
nShadowDecalVertsInBuf=0;
}
else
- { if (shadowDecalVertexBufferD3D->Lock(nShadowDecalVertsInBuf*sizeof(SHADOW_DECAL_VERTEX),numVerts*sizeof(SHADOW_DECAL_VERTEX), (void**)&pvVertices,D3DLOCK_NOOVERWRITE) != D3D_OK)
+ { vertexOffset=nShadowDecalVertsInBuf*vertexStride;
+ vertexFlags=D3DLOCK_NOOVERWRITE;
+ if (shadowDecalVertexBufferD3D->Lock(vertexOffset,numVerts*vertexStride, (void**)&pvVertices,D3DLOCK_NOOVERWRITE) != D3D_OK)
return;
}
+ void *vertexTarget = vertexLock.Begin(shadowDecalVertexTwin, pvVertices, vertexOffset,
+ numVerts*vertexStride, vertexFlags);
+ if (vertexTarget != NULL)
+ pvVertices = (SHADOW_DECAL_VERTEX *)vertexTarget;
+
objPos.Z=groundHeight; //force decal to ground level
objPos += groundNormal * 1.0f; //offset decal slightly above terrain to reduce z-fighting.
Vector3 vertex;
@@ -1259,12 +1350,18 @@ void W3DProjectedShadowManager::queueSimpleDecal(W3DProjectedShadow *shadow)
pvVertices++;
}
+ vertexLock.End();
shadowDecalVertexBufferD3D->Unlock();
+ DX11BufferLockClass indexLock;
+ UnsignedInt indexOffset;
+ UnsignedInt indexFlags;
if (nShadowDecalIndicesInBuf > (SHADOW_DECAL_INDEX_SIZE-numIndex)) //check if room for model verts
{ //flush the buffer by drawing the contents and re-locking again
flushDecals(shadow->m_shadowTexture[0],shadow->m_type);
+ indexOffset=0;
+ indexFlags=D3DLOCK_DISCARD;
if (shadowDecalIndexBufferD3D->Lock(0,numIndex*sizeof(short),(void**)&pvIndices,D3DLOCK_DISCARD) != D3D_OK)
return;
@@ -1274,10 +1371,17 @@ void W3DProjectedShadowManager::queueSimpleDecal(W3DProjectedShadow *shadow)
nShadowDecalIndicesInBuf=0;
}
else
- { if (shadowDecalIndexBufferD3D->Lock(nShadowDecalIndicesInBuf*sizeof(short),numIndex*sizeof(short), (void**)&pvIndices,D3DLOCK_NOOVERWRITE) != D3D_OK)
+ { indexOffset=nShadowDecalIndicesInBuf*sizeof(short);
+ indexFlags=D3DLOCK_NOOVERWRITE;
+ if (shadowDecalIndexBufferD3D->Lock(indexOffset,numIndex*sizeof(short), (void**)&pvIndices,D3DLOCK_NOOVERWRITE) != D3D_OK)
return;
}
+ void *indexTarget = indexLock.Begin(shadowDecalIndexTwin, pvIndices, indexOffset,
+ numIndex*sizeof(short), indexFlags);
+ if (indexTarget != NULL)
+ pvIndices = (UnsignedShort *)indexTarget;
+
try {
if(pvIndices)
{ pvIndices[0]=nShadowDecalVertsInBatch;
@@ -1293,6 +1397,7 @@ void W3DProjectedShadowManager::queueSimpleDecal(W3DProjectedShadow *shadow)
IndexBufferExceptionFunc();
}
+ indexLock.End();
shadowDecalIndexBufferD3D->Unlock();
Int numPolys = 2; //2 triangles per decal
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cpp
index d17dddf93..61e972781 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cpp
@@ -114,6 +114,14 @@ struct SHADOW_STATIC_VOLUME_VERTEX //vertex structure passed to D3D
LPDIRECT3DVERTEXBUFFER9 shadowVertexBufferD3D=NULL; ///<D3D vertex buffer
LPDIRECT3DINDEXBUFFER9 shadowIndexBufferD3D=NULL; ///<D3D index buffer
+
+//The Direct3D 11 copies of those two, null on a run without -dx11. These buffers are made with
+//CreateVertexBuffer straight on the device rather than through DX8VertexBufferClass, so they get
+//none of the mirroring that class does and the twins are held here instead. A write-only D3D9
+//buffer cannot be read back, so the lock is redirected into the twin's own heap block and the
+//unlock writes it into both - which is what DX11BufferLockClass is for.
+DX11BufferTwinClass *shadowVertexTwin=NULL;
+DX11BufferTwinClass *shadowIndexTwin=NULL;
int nShadowVertsInBuf=0; //model vetices in vertex buffer
int nShadowStartBatchVertex=0;
int nShadowIndicesInBuf=0; //model vetices in vertex buffer
@@ -1521,17 +1529,29 @@ void W3DVolumetricShadow::RenderMeshVolume(Int meshIndex, Int lightIndex, const
Matrix4x4 mWorld(*meshXform);
///@todo: W3D always does transpose on all of matrix sets. Slow??? Better to hack view matrix.
- m_pDev->SetTransform(D3DTS_WORLD,(_D3DMATRIX *)&mWorld.Transpose());
-
+ //
+ // Set on the device rather than through DX8Wrapper on purpose. The wrapper's setter writes its
+ // own DX8Transforms copy, which Apply_Render_State_Changes and _Get_DX8_Transform both read,
+ // and this pass sets a world matrix per mesh and never puts the old one back. The Direct3D 11
+ // backend is told separately, which is all it needs.
+ Matrix4x4 mWorldTransposed = mWorld.Transpose();
+ m_pDev->SetTransform(D3DTS_WORLD,(_D3DMATRIX *)&mWorldTransposed);
+ Direct3D11_Mirror_Transform(D3DTS_WORLD,(const float *)&mWorldTransposed);
+
W3DBufferManager::W3DVertexBufferSlot *vbSlot=m_shadowVolumeVB[lightIndex][ meshIndex ];
if (!vbSlot)
return;
+ const UnsignedInt vertexSize = vbSlot->m_VB->m_DX8VertexBuffer->FVF_Info().Get_FVF_Size();
if (vbSlot->m_VB->m_DX8VertexBuffer->Get_DX8_Vertex_Buffer() != lastActiveVertexBuffer)
{ lastActiveVertexBuffer=vbSlot->m_VB->m_DX8VertexBuffer->Get_DX8_Vertex_Buffer();
- m_pDev->SetStreamSource(0,lastActiveVertexBuffer,0,
- vbSlot->m_VB->m_DX8VertexBuffer->FVF_Info().Get_FVF_Size()); //12 bytes per vertex.
+ m_pDev->SetStreamSource(0,lastActiveVertexBuffer,0,vertexSize); //12 bytes per vertex.
}
+ // The stream is set behind DX8Wrapper's back above, so the Direct3D 11 backend is told about it
+ // here. Unconditionally, not only when the buffer changes: the backend's stream is set by
+ // everything else that draws between two shadow volumes.
+ Direct3D11_Mirror_Stream_Source(vbSlot->m_VB->m_DX8VertexBuffer->Get_DX11_Twin(), vertexSize, 0);
+
DEBUG_ASSERTCRASH(vbSlot->m_size >= numVerts,("Overflowing Shadow Vertex Buffer Slot"));
W3DBufferManager::W3DIndexBufferSlot *ibSlot=m_shadowVolumeIB[lightIndex][ meshIndex ];
@@ -1542,11 +1562,13 @@ void W3DVolumetricShadow::RenderMeshVolume(Int meshIndex, Int lightIndex, const
// D3D9 takes the base vertex index on the draw call, not here.
m_pDev->SetIndices(ibSlot->m_IB->m_DX8IndexBuffer->Get_DX8_Index_Buffer());
+ Direct3D11_Mirror_Indices(ibSlot->m_IB->m_DX8IndexBuffer->Get_DX11_Twin());
if (DX8Wrapper::_Is_Triangle_Draw_Enabled())
{
Debug_Statistics::Record_DX8_Polys_And_Vertices(numPolys,numVerts,ShaderClass::_PresetOpaqueShader);
m_pDev->DrawIndexedPrimitive(D3DPT_TRIANGLELIST,vbSlot->m_start,0,numVerts,ibSlot->m_start,numPolys);
+ Direct3D11_Draw_Indexed_Triangles(numIndex,ibSlot->m_start,vbSlot->m_start);
}
}
@@ -1583,17 +1605,33 @@ void W3DVolumetricShadow::RenderDynamicMeshVolume(Int meshIndex, Int lightIndex,
return;
+ DX11BufferLockClass vertexLock;
+ const UnsignedInt vertexStride = sizeof(SHADOW_DYNAMIC_VOLUME_VERTEX);
+ UnsignedInt vertexOffset;
+ UnsignedInt vertexFlags;
if (nShadowVertsInBuf > (SHADOW_VERTEX_SIZE-numVerts)) //check if room for model verts
{ //flush the buffer by drawing the contents and re-locking again
- if (shadowVertexBufferD3D->Lock(0,numVerts*sizeof(SHADOW_DYNAMIC_VOLUME_VERTEX),(void**)&pvVertices,D3DLOCK_DISCARD) != D3D_OK)
+ vertexOffset=0;
+ vertexFlags=D3DLOCK_DISCARD;
+ if (shadowVertexBufferD3D->Lock(0,numVerts*vertexStride,(void**)&pvVertices,D3DLOCK_DISCARD) != D3D_OK)
return;
nShadowVertsInBuf=0;
nShadowStartBatchVertex=0;
}
else
- { if (shadowVertexBufferD3D->Lock(nShadowVertsInBuf*sizeof(SHADOW_DYNAMIC_VOLUME_VERTEX),numVerts*sizeof(SHADOW_DYNAMIC_VOLUME_VERTEX), (void**)&pvVertices,D3DLOCK_NOOVERWRITE) != D3D_OK)
+ { vertexOffset=nShadowVertsInBuf*vertexStride;
+ vertexFlags=D3DLOCK_NOOVERWRITE;
+ if (shadowVertexBufferD3D->Lock(vertexOffset,numVerts*vertexStride, (void**)&pvVertices,D3DLOCK_NOOVERWRITE) != D3D_OK)
return;
}
+
+ // From here the fill writes into the twin's own block instead of the D3D9 pointer, and the
+ // unlock below copies that range into both. Without a twin Begin answers null and the fill
+ // carries on writing where it always did.
+ void *vertexTarget = vertexLock.Begin(shadowVertexTwin, pvVertices, vertexOffset,
+ numVerts*vertexStride, vertexFlags);
+ if (vertexTarget != NULL)
+ pvVertices = (SHADOW_DYNAMIC_VOLUME_VERTEX *)vertexTarget;
#ifdef SV_DEBUG
srand(0x1345465);
#endif
@@ -1611,20 +1649,32 @@ void W3DVolumetricShadow::RenderDynamicMeshVolume(Int meshIndex, Int lightIndex,
#endif
}
+ vertexLock.End();
shadowVertexBufferD3D->Unlock();
+ DX11BufferLockClass indexLock;
+ UnsignedInt indexOffset;
+ UnsignedInt indexFlags;
if (nShadowIndicesInBuf > (SHADOW_INDEX_SIZE-numIndex)) //check if room for model verts
{ //flush the buffer by drawing the contents and re-locking again
+ indexOffset=0;
+ indexFlags=D3DLOCK_DISCARD;
if (shadowIndexBufferD3D->Lock(0,numIndex*sizeof(short),(void**)&pvIndices,D3DLOCK_DISCARD) != D3D_OK)
return;
nShadowIndicesInBuf=0;
nShadowStartBatchIndex=0;
}
else
- { if (shadowIndexBufferD3D->Lock(nShadowIndicesInBuf*sizeof(short),numIndex*sizeof(short), (void**)&pvIndices,D3DLOCK_NOOVERWRITE) != D3D_OK)
+ { indexOffset=nShadowIndicesInBuf*sizeof(short);
+ indexFlags=D3DLOCK_NOOVERWRITE;
+ if (shadowIndexBufferD3D->Lock(indexOffset,numIndex*sizeof(short), (void**)&pvIndices,D3DLOCK_NOOVERWRITE) != D3D_OK)
return;
}
+ void *indexTarget = indexLock.Begin(shadowIndexTwin, pvIndices, indexOffset,
+ numIndex*sizeof(short), indexFlags);
+ if (indexTarget != NULL)
+ pvIndices = (UnsignedShort *)indexTarget;
try {
if(pvIndices)
@@ -1636,24 +1686,30 @@ void W3DVolumetricShadow::RenderDynamicMeshVolume(Int meshIndex, Int lightIndex,
IndexBufferExceptionFunc();
}
+ indexLock.End();
shadowIndexBufferD3D->Unlock();
// D3D9 takes the base vertex index on the draw call, not here.
m_pDev->SetIndices(shadowIndexBufferD3D);
-
+ Direct3D11_Mirror_Indices(shadowIndexTwin);
+
Matrix4x4 mWorld(*meshXform);
+ Matrix4x4 mWorldTransposed = mWorld.Transpose();
- m_pDev->SetTransform(D3DTS_WORLD,(_D3DMATRIX *)&mWorld.Transpose());
+ m_pDev->SetTransform(D3DTS_WORLD,(_D3DMATRIX *)&mWorldTransposed);
+ Direct3D11_Mirror_Transform(D3DTS_WORLD,(const float *)&mWorldTransposed);
if (shadowVertexBufferD3D != lastActiveVertexBuffer)
- { m_pDev->SetStreamSource(0,shadowVertexBufferD3D,0,sizeof(SHADOW_DYNAMIC_VOLUME_VERTEX));
+ { m_pDev->SetStreamSource(0,shadowVertexBufferD3D,0,vertexStride);
lastActiveVertexBuffer = shadowVertexBufferD3D;
}
+ Direct3D11_Mirror_Stream_Source(shadowVertexTwin, vertexStride, 0);
if (DX8Wrapper::_Is_Triangle_Draw_Enabled())
{
Debug_Statistics::Record_DX8_Polys_And_Vertices(numPolys,numVerts,ShaderClass::_PresetOpaqueShader);
m_pDev->DrawIndexedPrimitive(D3DPT_TRIANGLELIST,nShadowStartBatchVertex,0,numVerts,nShadowStartBatchIndex,numPolys);
+ Direct3D11_Draw_Indexed_Triangles(numIndex,nShadowStartBatchIndex,nShadowStartBatchVertex);
}
nShadowVertsInBuf += numVerts;
@@ -3640,40 +3696,38 @@ void W3DVolumetricShadowManager::renderStencilShadows( void )
//draw polygons like this is very inefficient but for only 2 triangles, it's
//not worth bothering with index/vertex buffers.
- m_pDev->SetFVF(D3DFVF_XYZRHW | D3DFVF_DIFFUSE);
+ DX8Wrapper::Set_Vertex_Format(D3DFVF_XYZRHW | D3DFVF_DIFFUSE);
// Use alpha blending to draw the transparent shadow
- m_pDev->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE );
-// m_pDev->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_SRCALPHA );
-// m_pDev->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA );
- m_pDev->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_DESTCOLOR);
- m_pDev->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_ZERO );
+ DX8Wrapper::Set_DX8_Render_State( D3DRS_ALPHABLENDENABLE, TRUE );
+ DX8Wrapper::Set_DX8_Render_State( D3DRS_SRCBLEND, D3DBLEND_DESTCOLOR);
+ DX8Wrapper::Set_DX8_Render_State( D3DRS_DESTBLEND, D3DBLEND_ZERO );
// Set stencil states
- m_pDev->SetRenderState( D3DRS_ZENABLE, TRUE );
- m_pDev->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
+ DX8Wrapper::Set_DX8_Render_State( D3DRS_ZENABLE, TRUE );
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_ZFUNC, D3DCMP_ALWAYS);
// Only write where stencil val >= 1 (count indicates # of shadows that
// overlap that pixel)
- m_pDev->SetRenderState( D3DRS_STENCILENABLE, TRUE );
- m_pDev->SetRenderState( D3DRS_STENCILFUNC, D3DCMP_LESSEQUAL ); //reference value is less or equal to stencil
- m_pDev->SetRenderState( D3DRS_STENCILPASS, D3DSTENCILOP_KEEP );
+ DX8Wrapper::Set_DX8_Render_State( D3DRS_STENCILENABLE, TRUE );
+ DX8Wrapper::Set_DX8_Render_State( D3DRS_STENCILFUNC, D3DCMP_LESSEQUAL ); //reference value is less or equal to stencil
+ DX8Wrapper::Set_DX8_Render_State( D3DRS_STENCILPASS, D3DSTENCILOP_KEEP );
//Upper bits of stencil could be used for storing occluded models which are player colored. So we mask out those
//pixels and only use the lower bits for shadow calculations.
- m_pDev->SetRenderState( D3DRS_STENCILMASK, ~TheW3DShadowManager->getStencilShadowMask());
- m_pDev->SetRenderState( D3DRS_STENCILREF, 0x1 );
+ DX8Wrapper::Set_DX8_Render_State( D3DRS_STENCILMASK, ~TheW3DShadowManager->getStencilShadowMask());
+ DX8Wrapper::Set_DX8_Render_State( D3DRS_STENCILREF, 0x1 );
- m_pDev->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_FLAT);
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_SHADEMODE, D3DSHADE_FLAT);
if (DX8Wrapper::_Is_Triangle_Draw_Enabled())
- m_pDev->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, sizeof(_TRANSLITVERTEX));
+ DX8Wrapper::_Draw_DX8_Primitive_UP(D3DPT_TRIANGLESTRIP, 2, v, sizeof(_TRANSLITVERTEX));
- m_pDev->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_GOURAUD);
- m_pDev->SetRenderState( D3DRS_ALPHABLENDENABLE, FALSE );
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_SHADEMODE, D3DSHADE_GOURAUD);
+ DX8Wrapper::Set_DX8_Render_State( D3DRS_ALPHABLENDENABLE, FALSE );
// turn off the stencil buffer
- m_pDev->SetRenderState( D3DRS_STENCILENABLE, FALSE );
+ DX8Wrapper::Set_DX8_Render_State( D3DRS_STENCILENABLE, FALSE );
} // end renderStencilShadows
@@ -3730,36 +3784,36 @@ void W3DVolumetricShadowManager::renderShadows( Bool forceStencilFill )
DX8Wrapper::Apply_Render_State_Changes(); //force update of view and projection matrices
// turn off z writing
- m_pDev->SetRenderState(D3DRS_ZFUNC, D3DCMP_LESSEQUAL);
- m_pDev->SetRenderState( D3DRS_ZENABLE, TRUE );
- m_pDev->SetRenderState(D3DRS_ZWRITEENABLE , FALSE);
- m_pDev->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
- m_pDev->SetRenderState(D3DRS_FOGENABLE, FALSE);
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_ZFUNC, D3DCMP_LESSEQUAL);
+ DX8Wrapper::Set_DX8_Render_State( D3DRS_ZENABLE, TRUE );
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_ZWRITEENABLE , FALSE);
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_ALPHATESTENABLE, FALSE);
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_FOGENABLE, FALSE);
// setup the TMU to default
- m_pDev->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_FLAT);
- m_pDev->SetRenderState(D3DRS_LIGHTING, FALSE);
- m_pDev->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
- m_pDev->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
- m_pDev->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_SELECTARG2);
- m_pDev->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_DISABLE );
- m_pDev->SetTextureStageState( 0, D3DTSS_TEXCOORDINDEX, 0 );
-
- m_pDev->SetTextureStageState( 1, D3DTSS_COLOROP, D3DTOP_DISABLE);
- m_pDev->SetTextureStageState( 1, D3DTSS_ALPHAOP, D3DTOP_DISABLE );
- m_pDev->SetTextureStageState( 1, D3DTSS_TEXCOORDINDEX, 1 );
- m_pDev->SetTexture(0,NULL);
- m_pDev->SetTexture(1,NULL);
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_SHADEMODE, D3DSHADE_FLAT);
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_LIGHTING, FALSE);
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_COLOROP, D3DTOP_SELECTARG2);
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_ALPHAOP, D3DTOP_DISABLE );
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_TEXCOORDINDEX, 0 );
+
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_COLOROP, D3DTOP_DISABLE);
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_ALPHAOP, D3DTOP_DISABLE );
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_TEXCOORDINDEX, 1 );
+ DX8Wrapper::Set_DX8_Texture(0,NULL);
+ DX8Wrapper::Set_DX8_Texture(1,NULL);
DWORD oldColorWriteEnable=0x12345678;
#ifdef SV_DEBUG
- m_pDev->SetRenderState(D3DRS_ALPHABLENDENABLE , TRUE);
- m_pDev->SetRenderState( D3DRS_STENCILENABLE, FALSE );
- m_pDev->SetRenderState( D3DRS_SRCBLEND, /*D3DBLEND_DESTCOLOR*/D3DBLEND_ONE );
- m_pDev->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_ZERO );
- m_pDev->SetRenderState(D3DRS_ZFUNC, D3DCMP_LESSEQUAL);
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_ALPHABLENDENABLE , TRUE);
+ DX8Wrapper::Set_DX8_Render_State( D3DRS_STENCILENABLE, FALSE );
+ DX8Wrapper::Set_DX8_Render_State( D3DRS_SRCBLEND, /*D3DBLEND_DESTCOLOR*/D3DBLEND_ONE );
+ DX8Wrapper::Set_DX8_Render_State( D3DRS_DESTBLEND, D3DBLEND_ZERO );
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_ZFUNC, D3DCMP_LESSEQUAL);
#else
//disable writes to color buffer
if (DX8Wrapper::Get_Current_Caps()->Get_DX8_Caps().PrimitiveMiscCaps & D3DPMISCCAPS_COLORWRITEENABLE)
@@ -3768,11 +3822,11 @@ void W3DVolumetricShadowManager::renderShadows( Bool forceStencilFill )
}
else
{ //device does not support disabling writes to color buffer so fake it through alpha blending
- m_pDev->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_ZERO );
- m_pDev->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_ONE );
- m_pDev->SetRenderState(D3DRS_ALPHABLENDENABLE , TRUE);
+ DX8Wrapper::Set_DX8_Render_State( D3DRS_SRCBLEND, D3DBLEND_ZERO );
+ DX8Wrapper::Set_DX8_Render_State( D3DRS_DESTBLEND, D3DBLEND_ONE );
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_ALPHABLENDENABLE , TRUE);
}
- m_pDev->SetRenderState( D3DRS_STENCILENABLE, TRUE );
+ DX8Wrapper::Set_DX8_Render_State( D3DRS_STENCILENABLE, TRUE );
#endif
//Any pixels with stencil already set to 128 contains a potential occluder. If this pixels also has any of the player
//color stencil bits also set, it means that it's an occluded player color and we need to NOT render shadows here. We
@@ -3780,21 +3834,21 @@ void W3DVolumetricShadowManager::renderShadows( Bool forceStencilFill )
//If the value of just the potential occluder bit is >= than the combined bits, then we know none of the player color
//bits were set and it's okay to render shadow.
if (TheW3DShadowManager->getStencilShadowMask() == 0x80808080)
- m_pDev->SetRenderState( D3DRS_STENCILFUNC, D3DCMP_NOTEQUAL ); //in this mode, MSB indicates occluded player pixels.
+ DX8Wrapper::Set_DX8_Render_State( D3DRS_STENCILFUNC, D3DCMP_NOTEQUAL ); //in this mode, MSB indicates occluded player pixels.
else
- m_pDev->SetRenderState( D3DRS_STENCILFUNC, D3DCMP_GREATEREQUAL ); //in this mode, multiple bits indicate occluded player pixels.
- m_pDev->SetRenderState( D3DRS_STENCILREF, 0x80808080 ); //isolate MSB, it's used to indicate pixels containing potential occluders.
- m_pDev->SetRenderState( D3DRS_STENCILMASK, TheW3DShadowManager->getStencilShadowMask()); //isolate upper bits containing PotentialOccluderBit|PlayerColorBits
- m_pDev->SetRenderState( D3DRS_STENCILWRITEMASK,0xffffffff );
- m_pDev->SetRenderState( D3DRS_STENCILZFAIL, D3DSTENCILOP_KEEP );
- m_pDev->SetRenderState( D3DRS_STENCILFAIL, D3DSTENCILOP_KEEP );
- m_pDev->SetRenderState( D3DRS_STENCILPASS, D3DSTENCILOP_INCR );
+ DX8Wrapper::Set_DX8_Render_State( D3DRS_STENCILFUNC, D3DCMP_GREATEREQUAL ); //in this mode, multiple bits indicate occluded player pixels.
+ DX8Wrapper::Set_DX8_Render_State( D3DRS_STENCILREF, 0x80808080 ); //isolate MSB, it's used to indicate pixels containing potential occluders.
+ DX8Wrapper::Set_DX8_Render_State( D3DRS_STENCILMASK, TheW3DShadowManager->getStencilShadowMask()); //isolate upper bits containing PotentialOccluderBit|PlayerColorBits
+ DX8Wrapper::Set_DX8_Render_State( D3DRS_STENCILWRITEMASK,0xffffffff );
+ DX8Wrapper::Set_DX8_Render_State( D3DRS_STENCILZFAIL, D3DSTENCILOP_KEEP );
+ DX8Wrapper::Set_DX8_Render_State( D3DRS_STENCILFAIL, D3DSTENCILOP_KEEP );
+ DX8Wrapper::Set_DX8_Render_State( D3DRS_STENCILPASS, D3DSTENCILOP_INCR );
- m_pDev->SetFVF(SHADOW_DYNAMIC_VOLUME_FVF);
+ DX8Wrapper::Set_Vertex_Format(SHADOW_DYNAMIC_VOLUME_FVF);
- m_pDev->SetRenderState(D3DRS_CULLMODE,D3DCULL_CW);
-// m_pDev->SetRenderState(D3DRS_ZBIAS,1); ///@todo: See if this helps or makes things worse.
- //m_pDev->SetRenderState(D3DRS_FILLMODE,D3DFILL_WIREFRAME);
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_CULLMODE,D3DCULL_CW);
+// DX8Wrapper::Set_DX8_Render_State(D3DRS_ZBIAS,1); ///@todo: See if this helps or makes things worse.
+ //DX8Wrapper::Set_DX8_Render_State(D3DRS_FILLMODE,D3DFILL_WIREFRAME);
lastActiveVertexBuffer=NULL; //reset
@@ -3839,7 +3893,7 @@ void W3DVolumetricShadowManager::renderShadows( Bool forceStencilFill )
}
// Set vertex format to that used by static shadow volumes
- m_pDev->SetFVF(W3DBufferManager::getDX8Format(W3DBufferManager::VBM_FVF_XYZ));
+ DX8Wrapper::Set_Vertex_Format(W3DBufferManager::getDX8Format(W3DBufferManager::VBM_FVF_XYZ));
//Empty queue of static shadow volumes to render.
W3DBufferManager::W3DVertexBuffer *nextVb;
@@ -3856,14 +3910,14 @@ void W3DVolumetricShadowManager::renderShadows( Bool forceStencilFill )
}
// change the stencil op to decrement
- m_pDev->SetRenderState( D3DRS_STENCILPASS, D3DSTENCILOP_DECRSAT);
+ DX8Wrapper::Set_DX8_Render_State( D3DRS_STENCILPASS, D3DSTENCILOP_DECRSAT);
//
// invert normals of shadow volumes so we can decrement in the
// stencil buffer and render
//
- m_pDev->SetRenderState(D3DRS_CULLMODE,D3DCULL_CCW);
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_CULLMODE,D3DCULL_CCW);
for (nextVb=TheW3DBufferManager->getNextVertexBuffer(NULL,W3DBufferManager::VBM_FVF_XYZ);nextVb != NULL; nextVb=TheW3DBufferManager->getNextVertexBuffer(nextVb,W3DBufferManager::VBM_FVF_XYZ))
{
@@ -3875,7 +3929,7 @@ void W3DVolumetricShadowManager::renderShadows( Bool forceStencilFill )
}
}
- m_pDev->SetFVF(SHADOW_DYNAMIC_VOLUME_FVF);
+ DX8Wrapper::Set_Vertex_Format(SHADOW_DYNAMIC_VOLUME_FVF);
//flush any dynamic shadow volumes
shadowDynamicTask=m_dynamicShadowVolumesToRender;
while (shadowDynamicTask)
@@ -3891,9 +3945,9 @@ void W3DVolumetricShadowManager::renderShadows( Bool forceStencilFill )
nextVb->m_renderTaskList=NULL;
}
- m_pDev->SetRenderState(D3DRS_CULLMODE,D3DCULL_CW);
-// m_pDev->SetRenderState(D3DRS_ZBIAS,0); ///@todo: See if this helps or makes things worse.
- //m_pDev->SetRenderState(D3DRS_FILLMODE,D3DFILL_SOLID);
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_CULLMODE,D3DCULL_CW);
+// DX8Wrapper::Set_DX8_Render_State(D3DRS_ZBIAS,0); ///@todo: See if this helps or makes things worse.
+ //DX8Wrapper::Set_DX8_Render_State(D3DRS_FILLMODE,D3DFILL_SOLID);
if (oldColorWriteEnable != 0x12345678)
@@ -3907,9 +3961,9 @@ void W3DVolumetricShadowManager::renderShadows( Bool forceStencilFill )
// if (numRenderedShadows)
renderStencilShadows();
- m_pDev->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_GOURAUD);
- m_pDev->SetRenderState(D3DRS_ALPHABLENDENABLE , FALSE);
- m_pDev->SetRenderState(D3DRS_LIGHTING, FALSE);
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_SHADEMODE, D3DSHADE_GOURAUD);
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_ALPHABLENDENABLE , FALSE);
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_LIGHTING, FALSE);
DX8Wrapper::Invalidate_Cached_Render_States();
}
@@ -4032,6 +4086,10 @@ void W3DVolumetricShadowManager::ReleaseResources(void)
shadowVertexBufferD3D->Release();
shadowIndexBufferD3D=NULL;
shadowVertexBufferD3D=NULL;
+ delete shadowIndexTwin;
+ delete shadowVertexTwin;
+ shadowIndexTwin=NULL;
+ shadowVertexTwin=NULL;
if (TheW3DBufferManager)
{ TheW3DBufferManager->ReleaseResources();
invalidateCachedLightPositions(); //vertex buffers need to be refilled.
@@ -4058,6 +4116,8 @@ Bool W3DVolumetricShadowManager::ReAcquireResources(void)
)))
return FALSE;
+ shadowIndexTwin = Direct3D11_Twin_Index_Buffer(SHADOW_INDEX_SIZE*sizeof(WORD), true);
+
if (shadowVertexBufferD3D == NULL)
{ // Create vertex buffer
@@ -4071,6 +4131,9 @@ Bool W3DVolumetricShadowManager::ReAcquireResources(void)
NULL // pSharedHandle, D3D9's extra parameter, reserved and always null
)))
return FALSE;
+
+ shadowVertexTwin = Direct3D11_Twin_Vertex_Buffer(
+ SHADOW_VERTEX_SIZE*sizeof(SHADOW_DYNAMIC_VOLUME_VERTEX), true);
}
if (TheW3DBufferManager)
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp
index 957e74abe..978d33708 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp
@@ -456,10 +456,72 @@ W3DDisplay::~W3DDisplay()
unsigned pipelines = 0;
unsigned long long drawsMade = 0;
unsigned long long drawsRefused = 0;
+ unsigned twinBuffers = 0;
+ unsigned long long twinBytes = 0;
+ unsigned texturesMirrored = 0;
+ unsigned texturesReused = 0;
+ unsigned texturesRefused = 0;
Direct3D11_Statistics( pipelines, drawsMade, drawsRefused );
- DEBUG_LOG(("-dx11: device %s; %u pipelines built, %I64u draws made, %I64u refused\n",
+ Direct3D11_Twin_Statistics( twinBuffers, twinBytes );
+ Direct3D11_Texture_Statistics( texturesMirrored, texturesReused, texturesRefused );
+ DEBUG_LOG(("-dx11: device %s; %u buffers mirrored (%I64u KB); %u textures mirrored, "
+ "%u reused, %u refused; %u pipelines built, %I64u draws made, %I64u refused\n",
Direct3D11_Is_Active() ? "created" : "REFUSED",
+ twinBuffers, twinBytes / 1024,
+ texturesMirrored, texturesReused, texturesRefused,
pipelines, drawsMade, drawsRefused));
+
+ unsigned long long noBuffer = 0;
+ unsigned long long noStage = 0;
+ unsigned long long noLayout = 0;
+ unsigned long long noProgram = 0;
+ unsigned long long noObject = 0;
+ unsigned long long foreignShader = 0;
+ unsigned long long noTexture = 0;
+ Direct3D11_Refusals( noBuffer, noStage, noLayout, noProgram, noObject, foreignShader,
+ noTexture );
+ DEBUG_LOG(("-dx11 refusals: %I64u no buffer, %I64u no texture stage, %I64u no input layout, "
+ "%I64u no program, %I64u no device object, %I64u engine shader bound, "
+ "%I64u unmirrored texture\n",
+ noBuffer, noStage, noLayout, noProgram, noObject, foreignShader, noTexture));
+
+ // The distinct states behind those counts. There are a few dozen at most - the engine sets
+ // the same handful over and over - and each one names what is missing from the picture.
+ const unsigned refusedCount = Direct3D11_Refused_Description_Count();
+ for( unsigned refused = 0; refused < refusedCount; refused++ )
+ DEBUG_LOG(("-dx11 refused: %s\n", Direct3D11_Refused_Description( refused )));
+
+ if( Direct3D11_Texture_First_Refusal()[0] != '\0' )
+ DEBUG_LOG(("-dx11 texture: %s\n", Direct3D11_Texture_First_Refusal()));
+
+ unsigned long long targetsBound = 0;
+ unsigned long long targetsRestored = 0;
+ unsigned long long drawsIntoTargets = 0;
+ Direct3D11_Target_Statistics( targetsBound, targetsRestored, drawsIntoTargets );
+ DEBUG_LOG(("-dx11 targets: %I64u binds, %I64u restores, %I64u draws landed in a texture\n",
+ targetsBound, targetsRestored, drawsIntoTargets));
+
+ if( Direct3D11_Diagnostic()[0] != '\0' )
+ DEBUG_LOG(("-dx11 note: %s\n", Direct3D11_Diagnostic()));
+
+ const unsigned traceCount = Direct3D11_Target_Trace_Count();
+ for( unsigned trace = 0; trace < traceCount; trace++ )
+ DEBUG_LOG(("-dx11 target trace: %s\n", Direct3D11_Target_Trace( trace )));
+
+ const unsigned pipelineCount = Direct3D11_Pipeline_Report_Count();
+ for( unsigned pipeline = 0; pipeline < pipelineCount; pipeline++ )
+ DEBUG_LOG(("-dx11 drew: %s\n", Direct3D11_Pipeline_Report( pipeline )));
+
+ const unsigned foreignCount = Direct3D11_Foreign_Report_Count();
+ for( unsigned foreign = 0; foreign < foreignCount; foreign++ )
+ DEBUG_LOG(("-dx11 foreign: %s\n", Direct3D11_Foreign_Report( foreign )));
+
+ const unsigned noteCount = Direct3D11_Texture_Note_Count();
+ for( unsigned note = 0; note < noteCount; note++ )
+ DEBUG_LOG(("-dx11 16bit: %s\n", Direct3D11_Texture_Note( note )));
+
+ if( Direct3D11_First_Compiler_Error()[0] != '\0' )
+ DEBUG_LOG(("-dx11 compiler: %s\n", Direct3D11_First_Compiler_Error()));
}
// get rid of the debug display
@@ -960,6 +1022,8 @@ void W3DDisplay::init( void )
FixedFunctionProbe_Enable( TheGlobalData->m_fixedFunctionProbe != FALSE );
CombinerShaders_Enable( TheGlobalData->m_combinerShaders != FALSE );
Direct3D11_Enable( TheGlobalData->m_direct3D11 != FALSE );
+ Direct3D11_Present_Enable( TheGlobalData->m_direct3D11Present != FALSE );
+ Direct3D11_Dump_Programs_To( TheGlobalData->m_direct3D11DumpPath.str() );
// 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
@@ -3524,6 +3588,43 @@ static void saveScreenShot(void)
done = true;
}
+ // With -dx11present the picture on the screen is the Direct3D 11 one, so that is what a
+ // screenshot has to be: reading the D3D9 back buffer here would photograph a frame nobody saw
+ // and quietly compare the old renderer against itself. This runs before End_Render, while the
+ // D3D11 back buffer still holds the frame.
+ if (Direct3D11_Present_Is_Enabled())
+ {
+ unsigned captureWidth = 0;
+ unsigned captureHeight = 0;
+ unsigned capturePitch = 0;
+ unsigned char *captured =
+ Direct3D11_Capture_Back_Buffer(captureWidth, captureHeight, capturePitch);
+ if (captured != NULL)
+ {
+ char *rows = NEW char[3*captureWidth*captureHeight];
+ for (unsigned row = 0; row < captureHeight; row++)
+ {
+ // Bottom row first, which is the order a .bmp stores them.
+ const unsigned char *in = captured + (captureHeight-1-row)*capturePitch;
+ char *out = rows + row*captureWidth*3;
+ for (unsigned column = 0; column < captureWidth; column++)
+ {
+ out[column*3+0] = (char)in[column*4+0];
+ out[column*3+1] = (char)in[column*4+1];
+ out[column*3+2] = (char)in[column*4+2];
+ }
+ }
+ CreateBMPFile(pathname, rows, captureWidth, captureHeight);
+ delete [] rows;
+ Direct3D11_Release_Capture(captured);
+
+ UnicodeString dx11FileName;
+ dx11FileName.translate(leafname);
+ TheInGameUI->message(TheGameText->fetch("GUI:ScreenCapture"), dx11FileName.str());
+ }
+ return;
+ }
+
RECT bounds;
IDirect3DSurface9 *fb = captureBackBuffer();
if (fb != NULL)
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DScene.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DScene.cpp
index 2ec17f78c..a0b85b728 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DScene.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DScene.cpp
@@ -1283,7 +1283,10 @@ void renderStenciledPlayerColor( UnsignedInt color, UnsignedInt stencilRef, Bool
//draw polygons like this is very inefficient but for only 2 triangles, it's
//not worth bothering with index/vertex buffers.
- m_pDev->SetFVF(D3DFVF_XYZRHW | D3DFVF_DIFFUSE);
+ // Through the wrapper rather than on the device: _Draw_DX8_Primitive_UP mirrors the strip into
+ // the Direct3D 11 backend, which reads the format the wrapper last set and would otherwise
+ // build the layout out of whatever the previous pass left behind.
+ DX8Wrapper::Set_Vertex_Format(D3DFVF_XYZRHW | D3DFVF_DIFFUSE);
// Set stencil states
DX8Wrapper::Set_DX8_Render_State(D3DRS_STENCILENABLE, TRUE );
@@ -1329,7 +1332,7 @@ void renderStenciledPlayerColor( UnsignedInt color, UnsignedInt stencilRef, Bool
}
if (DX8Wrapper::_Is_Triangle_Draw_Enabled())
- m_pDev->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, sizeof(_TRANSLITVERTEX));
+ DX8Wrapper::_Draw_DX8_Primitive_UP(D3DPT_TRIANGLESTRIP, 2, v, sizeof(_TRANSLITVERTEX));
// turn off the stencil buffer
DX8Wrapper::Set_DX8_Render_State(D3DRS_STENCILENABLE, FALSE );
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DShaderManager.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DShaderManager.cpp
index 4f4d5ddd9..757f8076f 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DShaderManager.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DShaderManager.cpp
@@ -92,6 +92,27 @@
// should take a second is over in a few milliseconds. Exactly one filter fades at a time, so one
// shared wall clock gate paces all of them.
//
+// The .vso and .pso files ship as bytecode, so their source exists only inside the translator.
+// Under -dx11dump each one is written next to the generated programs, which is what rewriting them
+// for Direct3D 11 has to read.
+static void dumpEngineShaderSource( const char *path, const std::string &source )
+{
+ if( TheGlobalData == NULL || TheGlobalData->m_direct3D11DumpPath.isEmpty() || source.empty() )
+ return;
+
+ const char *name = strrchr( path, '\\' );
+ name = (name != NULL) ? name + 1 : path;
+
+ char file[512];
+ sprintf( file, "%s/%s.asm", TheGlobalData->m_direct3D11DumpPath.str(), name );
+
+ FILE *out = fopen( file, "wb" );
+ if( out == NULL )
+ return;
+ fwrite( source.data(), 1, source.size(), out );
+ fclose( out );
+}
+
static Bool fadeStepDue( void )
{
static UnsignedInt lastMs = 0;
@@ -110,8 +131,8 @@ public:
///do any custom resetting necessary to bring W3D in sync.
virtual void reset(void) {
ShaderClass::Invalidate();
- DX8Wrapper::_Get_D3D_Device()->SetTexture(0, NULL);
- DX8Wrapper::_Get_D3D_Device()->SetTexture(1, NULL);};
+ DX8Wrapper::Set_DX8_Texture(0, NULL);
+ DX8Wrapper::Set_DX8_Texture(1, NULL);};
virtual Int init(void) = 0; ///<perform any one time initialization and validation
virtual Int shutdown(void) { return TRUE;}; ///<release resources used by shader
protected:
@@ -259,9 +280,8 @@ static void drawBloomQuad(Real x, Real y, Real w, Real h,
v[3].p = D3DXVECTOR4(x - 0.5f, y - 0.5f, 0.0f, 1.0f); v[3].u = u0; v[3].v = v0;
for (Int i = 0; i < 4; i++) v[i].color = color;
- LPDIRECT3DDEVICE9 pDev = DX8Wrapper::_Get_D3D_Device();
- pDev->SetFVF(D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX1);
- pDev->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, sizeof(_TRANS_LIT_TEX_VERTEX));
+ DX8Wrapper::Set_Vertex_Format(D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX1);
+ DX8Wrapper::_Draw_DX8_Primitive_UP(D3DPT_TRIANGLESTRIP, 2, v, sizeof(_TRANS_LIT_TEX_VERTEX));
}
/** Bright pass, blur, additive composite. Called with the back buffer as the render target and
@@ -284,21 +304,21 @@ static void renderBloom(IDirect3DTexture9 *sceneTexture, Real x, Real y, Real w,
//sunlit sand from popping in and out of the effect as the camera moves.
const Int t = bloomThreshold();
DX8Wrapper::_Set_DX8_Render_Target(s_bloomSurface[0], NULL); //no depth buffer: none of this is depth tested
- pDev->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
- pDev->SetRenderState(D3DRS_TEXTUREFACTOR, D3DCOLOR_ARGB(255, t, t, t));
- pDev->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SUBTRACT);
- pDev->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
- pDev->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_TFACTOR);
- pDev->SetTexture(0, sceneTexture);
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_ALPHABLENDENABLE, FALSE);
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_TEXTUREFACTOR, D3DCOLOR_ARGB(255, t, t, t));
+ DX8Wrapper::Set_DX8_Texture_Stage_State(0, D3DTSS_COLOROP, D3DTOP_SUBTRACT);
+ DX8Wrapper::Set_DX8_Texture_Stage_State(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
+ DX8Wrapper::Set_DX8_Texture_Stage_State(0, D3DTSS_COLORARG2, D3DTA_TFACTOR);
+ DX8Wrapper::Set_DX8_Texture(0, sceneTexture);
drawBloomQuad(0.0f, 0.0f, (Real)s_bloomWidth, (Real)s_bloomHeight, u0, v0, u1, v1, 0xffffffff);
//Blur: two 4-tap box passes ping-ponging between the targets, the second one twice as wide.
//Each tap is a quarter weight carried in the diffuse colour, the first writing and the other
//three adding, so the four average out.
- pDev->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE);
- pDev->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
- pDev->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ONE);
- pDev->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE);
+ DX8Wrapper::Set_DX8_Texture_Stage_State(0, D3DTSS_COLOROP, D3DTOP_MODULATE);
+ DX8Wrapper::Set_DX8_Texture_Stage_State(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_SRCBLEND, D3DBLEND_ONE);
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_DESTBLEND, D3DBLEND_ONE);
for (Int pass = 0; pass < 2; pass++)
{
const Int src = pass & 1;
@@ -306,12 +326,12 @@ static void renderBloom(IDirect3DTexture9 *sceneTexture, Real x, Real y, Real w,
const Real ox = (pass ? 3.5f : 1.5f) / (Real)s_bloomWidth;
const Real oy = (pass ? 3.5f : 1.5f) / (Real)s_bloomHeight;
DX8Wrapper::_Set_DX8_Render_Target(s_bloomSurface[dst], NULL);
- pDev->SetTexture(0, s_bloomTexture[src]);
+ DX8Wrapper::Set_DX8_Texture(0, s_bloomTexture[src]);
for (Int tap = 0; tap < 4; tap++)
{
const Real sx = (tap & 1) ? ox : -ox;
const Real sy = (tap & 2) ? oy : -oy;
- pDev->SetRenderState(D3DRS_ALPHABLENDENABLE, tap != 0);
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_ALPHABLENDENABLE, tap != 0);
drawBloomQuad(0.0f, 0.0f, (Real)s_bloomWidth, (Real)s_bloomHeight,
sx, sy, 1.0f + sx, 1.0f + sy, 0x40404040);
}
@@ -320,12 +340,12 @@ static void renderBloom(IDirect3DTexture9 *sceneTexture, Real x, Real y, Real w,
//Composite: add the blurred highlights back over the scene.
const Int i = bloomIntensity() * 255 / 100;
DX8Wrapper::_Set_DX8_Render_Target(oldTarget, oldDepth);
- pDev->SetTexture(0, s_bloomTexture[0]); //the second blur pass wrote target 0
- pDev->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
+ DX8Wrapper::Set_DX8_Texture(0, s_bloomTexture[0]); //the second blur pass wrote target 0
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_ALPHABLENDENABLE, TRUE);
drawBloomQuad(x, y, w, h, 0.0f, 0.0f, 1.0f, 1.0f, D3DCOLOR_ARGB(255, i, i, i));
- pDev->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
- pDev->SetTexture(0, NULL);
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_ALPHABLENDENABLE, FALSE);
+ DX8Wrapper::Set_DX8_Texture(0, NULL);
oldTarget->Release();
if (oldDepth) oldDepth->Release();
}
@@ -380,7 +400,6 @@ Bool ScreenDefaultFilter::postRender(enum FilterModes mode, Coord2D &scrollDelta
if (!tex) return false;
if (!set(mode)) return false;
- LPDIRECT3DDEVICE9 pDev=DX8Wrapper::_Get_D3D_Device();
struct _TRANS_LIT_TEX_VERTEX {
D3DXVECTOR4 p;
@@ -391,7 +410,7 @@ Bool ScreenDefaultFilter::postRender(enum FilterModes mode, Coord2D &scrollDelta
Int xpos, ypos, width, height;
- DX8Wrapper::_Get_D3D_Device()->SetTexture(0,tex); //previously rendered frame inside this texture
+ DX8Wrapper::Set_DX8_Texture(0,tex); //previously rendered frame inside this texture
TheTacticalView->getOrigin(&xpos,&ypos);
width=TheTacticalView->getWidth();
height=TheTacticalView->getHeight();
@@ -415,9 +434,9 @@ Bool ScreenDefaultFilter::postRender(enum FilterModes mode, Coord2D &scrollDelta
//draw polygons like this is very inefficient but for only 2 triangles, it's
//not worth bothering with index/vertex buffers.
- pDev->SetFVF(D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX1);
+ DX8Wrapper::Set_Vertex_Format(D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX1);
- pDev->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, sizeof(_TRANS_LIT_TEX_VERTEX));
+ DX8Wrapper::_Draw_DX8_Primitive_UP(D3DPT_TRIANGLESTRIP, 2, v, sizeof(_TRANS_LIT_TEX_VERTEX));
//v[3] is the top left corner of the viewport inside the scene texture, v[0] the bottom right
if (bloomIntensity() > 0)
@@ -452,7 +471,7 @@ Int ScreenDefaultFilter::set(enum FilterModes mode)
void ScreenDefaultFilter::reset(void)
{
- DX8Wrapper::_Get_D3D_Device()->SetTexture(0,NULL); //previously rendered frame inside this texture
+ DX8Wrapper::Set_DX8_Texture(0,NULL); //previously rendered frame inside this texture
DX8Wrapper::Invalidate_Cached_Render_States();
}
@@ -530,7 +549,6 @@ Bool ScreenBWFilter::postRender(enum FilterModes mode, Coord2D &scrollDelta,Bool
if (!tex) return false;
if (!set(mode)) return false;
- LPDIRECT3DDEVICE9 pDev=DX8Wrapper::_Get_D3D_Device();
struct _TRANS_LIT_TEX_VERTEX {
D3DXVECTOR4 p;
@@ -541,7 +559,7 @@ Bool ScreenBWFilter::postRender(enum FilterModes mode, Coord2D &scrollDelta,Bool
Int xpos, ypos, width, height;
- DX8Wrapper::_Get_D3D_Device()->SetTexture(0,tex); //previously rendered frame inside this texture
+ DX8Wrapper::Set_DX8_Texture(0,tex); //previously rendered frame inside this texture
TheTacticalView->getOrigin(&xpos,&ypos);
width=TheTacticalView->getWidth();
height=TheTacticalView->getHeight();
@@ -565,9 +583,9 @@ Bool ScreenBWFilter::postRender(enum FilterModes mode, Coord2D &scrollDelta,Bool
//draw polygons like this is very inefficient but for only 2 triangles, it's
//not worth bothering with index/vertex buffers.
- pDev->SetFVF(D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX1);
+ DX8Wrapper::Set_Vertex_Format(D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX1);
- pDev->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, sizeof(_TRANS_LIT_TEX_VERTEX));
+ DX8Wrapper::_Draw_DX8_Primitive_UP(D3DPT_TRIANGLESTRIP, 2, v, sizeof(_TRANS_LIT_TEX_VERTEX));
reset();
return true;
@@ -575,8 +593,6 @@ Bool ScreenBWFilter::postRender(enum FilterModes mode, Coord2D &scrollDelta,Bool
Int ScreenBWFilter::set(enum FilterModes mode)
{
- HRESULT hr;
-
if (mode > FM_NULL_MODE)
{ //rendering a quad with redirected rendering surface tinted by pixel shader
@@ -625,7 +641,7 @@ Int ScreenBWFilter::set(enum FilterModes mode)
DX8Wrapper::Set_DX8_Render_State(D3DRS_ZWRITEENABLE,FALSE);
DX8Wrapper::Apply_Render_State_Changes(); //force update of view and projection matrices
- hr=DX8Wrapper::_Get_D3D_Device()->SetPixelShader(m_dwBWPixelShader);
+ DX8Wrapper::Set_Pixel_Shader(m_dwBWPixelShader);
DX8Wrapper::_Get_D3D_Device()->SetPixelShaderConstantF(0, D3DXVECTOR4(0.3f, 0.59f, 0.11f, 1.0f), 1);
D3DXVECTOR4 color(1.0f,1.0f,1.0f,1.0f); //multiply color
@@ -670,8 +686,8 @@ Int ScreenBWFilter::set(enum FilterModes mode)
void ScreenBWFilter::reset(void)
{
- DX8Wrapper::_Get_D3D_Device()->SetTexture(0,NULL); //previously rendered frame inside this texture
- DX8Wrapper::_Get_D3D_Device()->SetPixelShader(0); //turn off pixel shader
+ DX8Wrapper::Set_DX8_Texture(0,NULL); //previously rendered frame inside this texture
+ DX8Wrapper::Set_Pixel_Shader(0); //turn off pixel shader
DX8Wrapper::Invalidate_Cached_Render_States();
}
@@ -719,7 +735,6 @@ Bool ScreenBWFilterDOT3::postRender(enum FilterModes mode, Coord2D &scrollDelta,
if (!tex) return false;
if (!set(mode)) return false;
- LPDIRECT3DDEVICE9 pDev=DX8Wrapper::_Get_D3D_Device();
struct _TRANS_LIT_TEX_VERTEX {
D3DXVECTOR4 p;
@@ -756,7 +771,7 @@ Bool ScreenBWFilterDOT3::postRender(enum FilterModes mode, Coord2D &scrollDelta,
//draw polygons like this is very inefficient but for only 2 triangles, it's
//not worth bothering with index/vertex buffers.
- pDev->SetFVF(D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX1);
+ DX8Wrapper::Set_Vertex_Format(D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX1);
//Draw B&W version first
if (DX8Wrapper::Get_Current_Caps()->Support_Dot3())
@@ -778,9 +793,9 @@ Bool ScreenBWFilterDOT3::postRender(enum FilterModes mode, Coord2D &scrollDelta,
DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_COLOROP, D3DTOP_MODULATE);
}
- DX8Wrapper::_Get_D3D_Device()->SetTexture(0,tex); //previously rendered frame inside this texture
+ DX8Wrapper::Set_DX8_Texture(0,tex); //previously rendered frame inside this texture
- pDev->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, sizeof(_TRANS_LIT_TEX_VERTEX));
+ DX8Wrapper::_Draw_DX8_Primitive_UP(D3DPT_TRIANGLESTRIP, 2, v, sizeof(_TRANS_LIT_TEX_VERTEX));
//Draw normal view blended by current fade level
ShaderClass::Invalidate(); //reset DOT3 blend from above.
@@ -791,7 +806,7 @@ Bool ScreenBWFilterDOT3::postRender(enum FilterModes mode, Coord2D &scrollDelta,
//replace texture alpha with vertex alpha
DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG2);
- pDev->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, sizeof(_TRANS_LIT_TEX_VERTEX));
+ DX8Wrapper::_Draw_DX8_Primitive_UP(D3DPT_TRIANGLESTRIP, 2, v, sizeof(_TRANS_LIT_TEX_VERTEX));
reset();
return true;
@@ -854,7 +869,7 @@ Int ScreenBWFilterDOT3::set(enum FilterModes mode)
void ScreenBWFilterDOT3::reset(void)
{
- DX8Wrapper::_Get_D3D_Device()->SetTexture(0,NULL); //previously rendered frame inside this texture
+ DX8Wrapper::Set_DX8_Texture(0,NULL); //previously rendered frame inside this texture
DX8Wrapper::Invalidate_Cached_Render_States();
}
@@ -981,7 +996,6 @@ Bool ScreenCrossFadeFilter::postRender(enum FilterModes mode, Coord2D &scrollDel
if (!tex) return false;
if (!set(mode)) return false;
- LPDIRECT3DDEVICE9 pDev=DX8Wrapper::_Get_D3D_Device();
struct _TRANS_LIT_TEX_VERTEX {
D3DXVECTOR4 p;
@@ -995,9 +1009,9 @@ Bool ScreenCrossFadeFilter::postRender(enum FilterModes mode, Coord2D &scrollDel
Int xpos, ypos, width, height;
Real radius = 0.0f;
- DX8Wrapper::_Get_D3D_Device()->SetTexture(0,tex); //previously rendered frame inside this texture
+ DX8Wrapper::Set_DX8_Texture(0,tex); //previously rendered frame inside this texture
if (mode == FM_VIEW_CROSSFADE_CIRCLE)
- { DX8Wrapper::_Get_D3D_Device()->SetTexture(1,m_fadePatternTexture->Peek_D3D_Texture());
+ { DX8Wrapper::Set_DX8_Texture(1,m_fadePatternTexture->Peek_D3D_Texture());
//Use the current fade level to scale the mask texture, for other modes the texture
//comes pre-scaled so doesn't require uv scaling.
radius = (1.0f-m_curFadeValue)*2.0f;
@@ -1041,12 +1055,12 @@ Bool ScreenCrossFadeFilter::postRender(enum FilterModes mode, Coord2D &scrollDel
//draw polygons like this is very inefficient but for only 2 triangles, it's
//not worth bothering with index/vertex buffers.
- pDev->SetFVF(D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX2);
+ DX8Wrapper::Set_Vertex_Format(D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX2);
// m_pDev->SetTextureStageState(0,D3DSAMP_MAGFILTER,D3DTEXF_POINT);
// m_pDev->SetTextureStageState(0,D3DSAMP_MINFILTER,D3DTEXF_POINT);
- pDev->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, sizeof(_TRANS_LIT_TEX_VERTEX));
+ DX8Wrapper::_Draw_DX8_Primitive_UP(D3DPT_TRIANGLESTRIP, 2, v, sizeof(_TRANS_LIT_TEX_VERTEX));
reset();
return true;
@@ -1093,7 +1107,7 @@ void ScreenCrossFadeFilter::reset(void)
{
DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_COLOROP, D3DTOP_DISABLE );
DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_ALPHAOP, D3DTOP_DISABLE );
- DX8Wrapper::_Get_D3D_Device()->SetTexture(0,NULL); //previously rendered frame inside this texture
+ DX8Wrapper::Set_DX8_Texture(0,NULL); //previously rendered frame inside this texture
DX8Wrapper::Invalidate_Cached_Render_States();
}
@@ -1150,7 +1164,6 @@ Bool ScreenMotionBlurFilter::postRender(enum FilterModes mode, Coord2D &scrollDe
if (!tex) return false;
if (!set(mode)) return false;
- LPDIRECT3DDEVICE9 pDev=DX8Wrapper::_Get_D3D_Device();
Bool continueEffect = true;
struct _TRANS_LIT_TEX_VERTEX {
@@ -1162,7 +1175,7 @@ Bool ScreenMotionBlurFilter::postRender(enum FilterModes mode, Coord2D &scrollDe
Int xpos, ypos, width, height;
- DX8Wrapper::_Get_D3D_Device()->SetTexture(0,tex); //previously rendered frame inside this texture
+ DX8Wrapper::Set_DX8_Texture(0,tex); //previously rendered frame inside this texture
TheTacticalView->getOrigin(&xpos,&ypos);
width=TheTacticalView->getWidth();
height=TheTacticalView->getHeight();
@@ -1196,7 +1209,7 @@ Bool ScreenMotionBlurFilter::postRender(enum FilterModes mode, Coord2D &scrollDe
//draw polygons like this is very inefficient but for only 2 triangles, it's
//not worth bothering with index/vertex buffers.
DX8Wrapper::Apply_Render_State_Changes();
- pDev->SetFVF(D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX1);
+ DX8Wrapper::Set_Vertex_Format(D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX1);
Coord2D center;
center.x = 0.5f;
@@ -1260,10 +1273,10 @@ Bool ScreenMotionBlurFilter::postRender(enum FilterModes mode, Coord2D &scrollDe
v[i].v = ((v[i].v-center.y)*factor) + center.y;
}
}
- pDev->SetTextureStageState(0,D3DTSS_ALPHAARG1, D3DTA_CURRENT);
- pDev->SetTextureStageState(0,D3DTSS_ALPHAARG2, D3DTA_TEXTURE);
- pDev->SetTextureStageState(0,D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
- pDev->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, sizeof(_TRANS_LIT_TEX_VERTEX));
+ DX8Wrapper::Set_DX8_Texture_Stage_State(0,D3DTSS_ALPHAARG1, D3DTA_CURRENT);
+ DX8Wrapper::Set_DX8_Texture_Stage_State(0,D3DTSS_ALPHAARG2, D3DTA_TEXTURE);
+ DX8Wrapper::Set_DX8_Texture_Stage_State(0,D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
+ DX8Wrapper::_Draw_DX8_Primitive_UP(D3DPT_TRIANGLESTRIP, 2, v, sizeof(_TRANS_LIT_TEX_VERTEX));
DX8Wrapper::Set_DX8_Render_State(D3DRS_ALPHABLENDENABLE,true);
DX8Wrapper::Apply_Render_State_Changes();
@@ -1291,7 +1304,7 @@ Bool ScreenMotionBlurFilter::postRender(enum FilterModes mode, Coord2D &scrollDe
v[i].v = ((v[i].v-center.y)*factor) + center.y;
}
}
- pDev->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, sizeof(_TRANS_LIT_TEX_VERTEX));
+ DX8Wrapper::_Draw_DX8_Primitive_UP(D3DPT_TRIANGLESTRIP, 2, v, sizeof(_TRANS_LIT_TEX_VERTEX));
}
}
@@ -1363,7 +1376,7 @@ Int ScreenMotionBlurFilter::set(enum FilterModes mode)
void ScreenMotionBlurFilter::reset(void)
{
- DX8Wrapper::_Get_D3D_Device()->SetTexture(0,NULL); //previously rendered frame inside this texture
+ DX8Wrapper::Set_DX8_Texture(0,NULL); //previously rendered frame inside this texture
DX8Wrapper::Invalidate_Cached_Render_States();
}
@@ -1787,8 +1800,8 @@ void TerrainShader2Stage::reset(void)
ShaderClass::Invalidate();
//Free references to textures
- DX8Wrapper::_Get_D3D_Device()->SetTexture(0, NULL);
- DX8Wrapper::_Get_D3D_Device()->SetTexture(1, NULL);
+ DX8Wrapper::Set_DX8_Texture(0, NULL);
+ DX8Wrapper::Set_DX8_Texture(1, NULL);
DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE);
DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_PASSTHRU|0);
@@ -1867,7 +1880,7 @@ Int TerrainShader2Stage::set(Int pass)
switch (pass)
{
case 0:
- DX8Wrapper::_Get_D3D_Device()->SetTexture(0, W3DShaderManager::getShaderTexture(0)->Peek_D3D_Texture());
+ DX8Wrapper::Set_DX8_Texture(0, W3DShaderManager::getShaderTexture(0)->Peek_D3D_Texture());
DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP);
DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP);
@@ -1882,7 +1895,7 @@ Int TerrainShader2Stage::set(Int pass)
DX8Wrapper::Set_DX8_Render_State(D3DRS_ALPHABLENDENABLE,false);
break;
case 1:
- DX8Wrapper::_Get_D3D_Device()->SetTexture(0, W3DShaderManager::getShaderTexture(1)->Peek_D3D_Texture());
+ DX8Wrapper::Set_DX8_Texture(0, W3DShaderManager::getShaderTexture(1)->Peek_D3D_Texture());
DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP);
DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP);
@@ -1931,7 +1944,7 @@ Int TerrainShader2Stage::set(Int pass)
if (W3DShaderManager::getCurrentShader() == W3DShaderManager::ST_TERRAIN_BASE_NOISE12)
{
//setup cloud pass
- DX8Wrapper::_Get_D3D_Device()->SetTexture(0, W3DShaderManager::getShaderTexture(2)->Peek_D3D_Texture());
+ DX8Wrapper::Set_DX8_Texture(0, W3DShaderManager::getShaderTexture(2)->Peek_D3D_Texture());
updateNoise1(((D3DXMATRIX*)&curView),&inv); //update curView with texture matrix
DX8Wrapper::_Set_DX8_Transform(D3DTS_TEXTURE0, curView);
@@ -1940,7 +1953,7 @@ Int TerrainShader2Stage::set(Int pass)
DX8Wrapper::Set_DX8_Texture_Stage_State(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
//setup noise pass
- DX8Wrapper::_Get_D3D_Device()->SetTexture(1, W3DShaderManager::getShaderTexture(3)->Peek_D3D_Texture());
+ DX8Wrapper::Set_DX8_Texture(1, W3DShaderManager::getShaderTexture(3)->Peek_D3D_Texture());
updateNoise2(((D3DXMATRIX*)&curView),&inv);
DX8Wrapper::_Set_DX8_Transform(D3DTS_TEXTURE1, curView);
@@ -1964,7 +1977,7 @@ Int TerrainShader2Stage::set(Int pass)
// Now setup the texture pipeline.
if (W3DShaderManager::getCurrentShader() == W3DShaderManager::ST_TERRAIN_BASE_NOISE1)
{ //setup cloud pass
- DX8Wrapper::_Get_D3D_Device()->SetTexture(0, W3DShaderManager::getShaderTexture(2)->Peek_D3D_Texture());
+ DX8Wrapper::Set_DX8_Texture(0, W3DShaderManager::getShaderTexture(2)->Peek_D3D_Texture());
updateNoise1(((D3DXMATRIX*)&curView),&inv); //update curView with texture matrix
DX8Wrapper::Set_DX8_Texture_Stage_State(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
DX8Wrapper::Set_DX8_Texture_Stage_State(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
@@ -1972,7 +1985,7 @@ Int TerrainShader2Stage::set(Int pass)
else
{
//setup noise pass
- DX8Wrapper::_Get_D3D_Device()->SetTexture(0, W3DShaderManager::getShaderTexture(3)->Peek_D3D_Texture());
+ DX8Wrapper::Set_DX8_Texture(0, W3DShaderManager::getShaderTexture(3)->Peek_D3D_Texture());
updateNoise2(((D3DXMATRIX*)&curView),&inv); //update curView with texture matrix
DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DSAMP_MINFILTER, D3DTEXF_POINT);
DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
@@ -2040,8 +2053,8 @@ Int TerrainShader8Stage::set(Int pass)
DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DSAMP_MIPFILTER, D3DTEXF_LINEAR);
}
- DX8Wrapper::_Get_D3D_Device()->SetTexture(0, W3DShaderManager::getShaderTexture(0)->Peek_D3D_Texture());
- DX8Wrapper::_Get_D3D_Device()->SetTexture(1, W3DShaderManager::getShaderTexture(1)->Peek_D3D_Texture());
+ DX8Wrapper::Set_DX8_Texture(0, W3DShaderManager::getShaderTexture(0)->Peek_D3D_Texture());
+ DX8Wrapper::Set_DX8_Texture(1, W3DShaderManager::getShaderTexture(1)->Peek_D3D_Texture());
DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_COLOROP, D3DTOP_MODULATE);
DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_TEXCOORDINDEX, 0);
@@ -2135,8 +2148,8 @@ void TerrainShader8Stage::reset(void)
DX8Wrapper::Set_DX8_Texture_Stage_State( 4, D3DTSS_COLOROP, D3DTOP_DISABLE);
DX8Wrapper::Set_DX8_Texture_Stage_State( 4, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
- DX8Wrapper::_Get_D3D_Device()->SetTexture(0, NULL);
- DX8Wrapper::_Get_D3D_Device()->SetTexture(1, NULL);
+ DX8Wrapper::Set_DX8_Texture(0, NULL);
+ DX8Wrapper::Set_DX8_Texture(1, NULL);
DX8Wrapper::Invalidate_Cached_Render_States();
}
@@ -2161,7 +2174,7 @@ Int TerrainShaderPixelShader::shutdown(void)
}
Int TerrainShaderPixelShader::init( void )
-{
+{
Int res;
#ifdef DISABLE_PIXEL_SHADERS
return false;
@@ -2218,8 +2231,8 @@ Int TerrainShaderPixelShader::set(Int pass)
DX8Wrapper::Apply_Render_State_Changes();
//setup base pass
- DX8Wrapper::_Get_D3D_Device()->SetTexture(0, W3DShaderManager::getShaderTexture(0)->Peek_D3D_Texture());
- DX8Wrapper::_Get_D3D_Device()->SetTexture(1, W3DShaderManager::getShaderTexture(1)->Peek_D3D_Texture());
+ DX8Wrapper::Set_DX8_Texture(0, W3DShaderManager::getShaderTexture(0)->Peek_D3D_Texture());
+ DX8Wrapper::Set_DX8_Texture(1, W3DShaderManager::getShaderTexture(1)->Peek_D3D_Texture());
DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP);
DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP);
@@ -2269,9 +2282,9 @@ Int TerrainShaderPixelShader::set(Int pass)
{ //full shader
DX8Wrapper::Set_DX8_Texture_Stage_State(3, D3DSAMP_ADDRESSU, D3DTADDRESS_WRAP);
DX8Wrapper::Set_DX8_Texture_Stage_State(3, D3DSAMP_ADDRESSV, D3DTADDRESS_WRAP);
- DX8Wrapper::_Get_D3D_Device()->SetTexture(2, W3DShaderManager::getShaderTexture(2)->Peek_D3D_Texture());
- DX8Wrapper::_Get_D3D_Device()->SetTexture(3, W3DShaderManager::getShaderTexture(3)->Peek_D3D_Texture());
- DX8Wrapper::_Get_D3D_Device()->SetPixelShader(m_dwBaseNoise2PixelShader);
+ DX8Wrapper::Set_DX8_Texture(2, W3DShaderManager::getShaderTexture(2)->Peek_D3D_Texture());
+ DX8Wrapper::Set_DX8_Texture(3, W3DShaderManager::getShaderTexture(3)->Peek_D3D_Texture());
+ DX8Wrapper::Set_Pixel_Shader(m_dwBaseNoise2PixelShader);
DX8Wrapper::Set_DX8_Texture_Stage_State(2, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
DX8Wrapper::Set_DX8_Texture_Stage_State(2, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
@@ -2291,18 +2304,18 @@ Int TerrainShaderPixelShader::set(Int pass)
}
else
{ //single noise texture shader
- DX8Wrapper::_Get_D3D_Device()->SetPixelShader(m_dwBaseNoise1PixelShader);
+ DX8Wrapper::Set_Pixel_Shader(m_dwBaseNoise1PixelShader);
if (W3DShaderManager::getCurrentShader() == W3DShaderManager::ST_TERRAIN_BASE_NOISE1)
{ //cloud map
- DX8Wrapper::_Get_D3D_Device()->SetTexture(2, W3DShaderManager::getShaderTexture(2)->Peek_D3D_Texture());
+ DX8Wrapper::Set_DX8_Texture(2, W3DShaderManager::getShaderTexture(2)->Peek_D3D_Texture());
terrainShader2Stage.updateNoise1(((D3DXMATRIX*)&curView),&inv); //update curView with texture matrix
DX8Wrapper::Set_DX8_Texture_Stage_State(2, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
DX8Wrapper::Set_DX8_Texture_Stage_State(2, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
}
else
{ //light map
- DX8Wrapper::_Get_D3D_Device()->SetTexture(2, W3DShaderManager::getShaderTexture(3)->Peek_D3D_Texture());
+ DX8Wrapper::Set_DX8_Texture(2, W3DShaderManager::getShaderTexture(3)->Peek_D3D_Texture());
terrainShader2Stage.updateNoise2(((D3DXMATRIX*)&curView),&inv); //update curView with texture matrix
DX8Wrapper::Set_DX8_Texture_Stage_State(2, D3DSAMP_MINFILTER, D3DTEXF_POINT);
DX8Wrapper::Set_DX8_Texture_Stage_State(2, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
@@ -2312,7 +2325,7 @@ Int TerrainShaderPixelShader::set(Int pass)
}
else
{ //just base texturing
- DX8Wrapper::_Get_D3D_Device()->SetPixelShader(m_dwBasePixelShader);
+ DX8Wrapper::Set_Pixel_Shader(m_dwBasePixelShader);
}
return TRUE;
@@ -2320,13 +2333,13 @@ Int TerrainShaderPixelShader::set(Int pass)
void TerrainShaderPixelShader::reset(void)
{
- DX8Wrapper::_Get_D3D_Device()->SetTexture(2,NULL); //release reference to any texture
- DX8Wrapper::_Get_D3D_Device()->SetTexture(3,NULL); //release reference to any texture
+ DX8Wrapper::Set_DX8_Texture(2,NULL); //release reference to any texture
+ DX8Wrapper::Set_DX8_Texture(3,NULL); //release reference to any texture
- DX8Wrapper::_Get_D3D_Device()->SetPixelShader(0); //turn off pixel shader
+ DX8Wrapper::Set_Pixel_Shader(0); //turn off pixel shader
- DX8Wrapper::_Get_D3D_Device()->SetTexture(0, NULL);
- DX8Wrapper::_Get_D3D_Device()->SetTexture(1, NULL);
+ DX8Wrapper::Set_DX8_Texture(0, NULL);
+ DX8Wrapper::Set_DX8_Texture(1, NULL);
DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE);
DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_PASSTHRU|0);
@@ -2397,7 +2410,7 @@ Int CloudTextureShader::set(Int stage)
DX8Wrapper::Set_DX8_Texture_Stage_State( stage, D3DTSS_ALPHAARG2, D3DTA_CURRENT );
DX8Wrapper::Set_DX8_Texture_Stage_State( stage, D3DTSS_ALPHAOP, D3DTOP_MODULATE );
- DX8Wrapper::_Get_D3D_Device()->SetTexture(stage, W3DShaderManager::getShaderTexture(stage)->Peek_D3D_Texture());
+ DX8Wrapper::Set_DX8_Texture(stage, W3DShaderManager::getShaderTexture(stage)->Peek_D3D_Texture());
m_stageOfSet=stage;
return TRUE;
@@ -2406,7 +2419,7 @@ Int CloudTextureShader::set(Int stage)
void CloudTextureShader::reset(void)
{
//Free reference to texture
- DX8Wrapper::_Get_D3D_Device()->SetTexture(m_stageOfSet, NULL);
+ DX8Wrapper::Set_DX8_Texture(m_stageOfSet, NULL);
//Turn off texture projection
DX8Wrapper::Set_DX8_Texture_Stage_State( m_stageOfSet, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE);
DX8Wrapper::Set_DX8_Texture_Stage_State( m_stageOfSet, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_PASSTHRU|m_stageOfSet);
@@ -2455,7 +2468,7 @@ Int RoadShaderPixelShader::shutdown(void)
}
Int RoadShaderPixelShader::init( void )
-{
+{
Int res;
//this shader will also use the 2Stage shader for some of the passes so initialize it too.
@@ -2535,7 +2548,7 @@ Int RoadShaderPixelShader::set(Int pass)
DX8Wrapper::Set_Texture(1,W3DShaderManager::getShaderTexture(1));
DX8Wrapper::Set_Texture(2,W3DShaderManager::getShaderTexture(2));
- DX8Wrapper::_Get_D3D_Device()->SetPixelShader(m_dwBaseNoise2PixelShader);
+ DX8Wrapper::Set_Pixel_Shader(m_dwBaseNoise2PixelShader);
DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
@@ -2559,7 +2572,7 @@ Int RoadShaderPixelShader::set(Int pass)
void RoadShaderPixelShader::reset(void)
{
- DX8Wrapper::_Get_D3D_Device()->SetPixelShader(0); //turn off pixel shader
+ DX8Wrapper::Set_Pixel_Shader(0); //turn off pixel shader
DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE);
DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_PASSTHRU|0);
@@ -3008,7 +3021,6 @@ static void rttComplain( const char *why )
/*Draws 2 triangles covering the viewport given the current render states*/
void W3DShaderManager::drawViewport(Int color)
{
- LPDIRECT3DDEVICE9 pDev=DX8Wrapper::_Get_D3D_Device();
struct _TRANS_LIT_TEX_VERTEX {
D3DXVECTOR4 p;
@@ -3042,9 +3054,9 @@ void W3DShaderManager::drawViewport(Int color)
//draw polygons like this is very inefficient but for only 2 triangles, it's
//not worth bothering with index/vertex buffers.
- pDev->SetFVF(D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX1);
+ DX8Wrapper::Set_Vertex_Format(D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX1);
- pDev->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, sizeof(_TRANS_LIT_TEX_VERTEX));
+ DX8Wrapper::_Draw_DX8_Primitive_UP(D3DPT_TRIANGLESTRIP, 2, v, sizeof(_TRANS_LIT_TEX_VERTEX));
}
// W3DShaderManager::startRenderToTexture =======================================================
@@ -3296,8 +3308,11 @@ HRESULT W3DShaderManager::LoadAndCreateD3DPixelShader(const char* strFilePath, I
// The bytecode was compiled for D3D8 and does not load on a D3D9 device untouched;
// see d3d8shadertranslate.h for what has to be repaired and why.
- const HRESULT hr = Create_Translated_Pixel_Shader(DX8Wrapper::_Get_D3D_Device(), pShader, shader);
+ std::string source;
+ const HRESULT hr = Create_Translated_Pixel_Shader(DX8Wrapper::_Get_D3D_Device(), pShader, shader,
+ &source);
HeapFree(GetProcessHeap(), 0, (void*)pShader);
+ dumpEngineShaderSource(strFilePath, source);
if (FAILED(hr))
{
@@ -3305,6 +3320,11 @@ HRESULT W3DShaderManager::LoadAndCreateD3DPixelShader(const char* strFilePath, I
strFilePath, (unsigned long)hr));
return E_FAIL;
}
+
+ // Nothing transcribes a .pso yet, so this registration buys one thing: a refused draw can say
+ // which shader it was refused for instead of only that it was one of them.
+ Direct3D11_Register_Engine_Shader(*shader, strFilePath);
+
return S_OK;
}
@@ -3318,9 +3338,11 @@ HRESULT W3DShaderManager::LoadAndCreateD3DVertexShader(const char* strFilePath,
if (pShader == NULL)
return E_FAIL;
+ std::string source;
const HRESULT hr = Create_Translated_Vertex_Shader(DX8Wrapper::_Get_D3D_Device(),
- pDeclaration, pShader, shader, declaration);
+ pDeclaration, pShader, shader, declaration, &source);
HeapFree(GetProcessHeap(), 0, (void*)pShader);
+ dumpEngineShaderSource(strFilePath, source);
if (FAILED(hr))
{
@@ -3329,6 +3351,10 @@ HRESULT W3DShaderManager::LoadAndCreateD3DVertexShader(const char* strFilePath,
return E_FAIL;
}
+ // The Direct3D 11 backend has a hand-written HLSL copy of some of these; the pointer is what
+ // tells a later bind which file it is looking at.
+ Direct3D11_Register_Engine_Shader(*shader, strFilePath);
+
return S_OK;
}
@@ -3529,8 +3555,8 @@ void FlatTerrainShader2Stage::reset(void)
ShaderClass::Invalidate();
//Free references to textures
- DX8Wrapper::_Get_D3D_Device()->SetTexture(0, NULL);
- DX8Wrapper::_Get_D3D_Device()->SetTexture(1, NULL);
+ DX8Wrapper::Set_DX8_Texture(0, NULL);
+ DX8Wrapper::Set_DX8_Texture(1, NULL);
DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE);
DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_PASSTHRU|0);
@@ -3575,7 +3601,7 @@ Int FlatTerrainShader2Stage::set(Int pass)
DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
if (W3DShaderManager::getShaderTexture(0)) {
- DX8Wrapper::_Get_D3D_Device()->SetTexture(0, W3DShaderManager::getShaderTexture(0)->Peek_D3D_Texture());
+ DX8Wrapper::Set_DX8_Texture(0, W3DShaderManager::getShaderTexture(0)->Peek_D3D_Texture());
DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_COLORARG2, D3DTA_CURRENT );
DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_COLOROP, D3DTOP_MODULATE );
@@ -3677,7 +3703,7 @@ Int FlatTerrainShader2Stage::set(Int pass)
//clouds always need bilinear filtering
DX8Wrapper::Set_DX8_Texture_Stage_State(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
DX8Wrapper::Set_DX8_Texture_Stage_State(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
- DX8Wrapper::_Get_D3D_Device()->SetTexture(0, W3DShaderManager::getShaderTexture(2)->Peek_D3D_Texture());
+ DX8Wrapper::Set_DX8_Texture(0, W3DShaderManager::getShaderTexture(2)->Peek_D3D_Texture());
//setup noise pass
@@ -3697,14 +3723,14 @@ Int FlatTerrainShader2Stage::set(Int pass)
DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DSAMP_ADDRESSU, D3DTADDRESS_WRAP);
DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DSAMP_ADDRESSV, D3DTADDRESS_WRAP);
- DX8Wrapper::_Get_D3D_Device()->SetTexture(1, W3DShaderManager::getShaderTexture(3)->Peek_D3D_Texture());
+ DX8Wrapper::Set_DX8_Texture(1, W3DShaderManager::getShaderTexture(3)->Peek_D3D_Texture());
} //ST_TERRAIN_BASE_NOISE12
else
{ //only 1 noise or cloud texture
// Now setup the texture pipeline.
if (W3DShaderManager::getCurrentShader() == W3DShaderManager::ST_FLAT_TERRAIN_BASE_NOISE1)
{ //setup cloud pass
- DX8Wrapper::_Get_D3D_Device()->SetTexture(0, W3DShaderManager::getShaderTexture(2)->Peek_D3D_Texture());
+ DX8Wrapper::Set_DX8_Texture(0, W3DShaderManager::getShaderTexture(2)->Peek_D3D_Texture());
terrainShader2Stage.updateNoise1(((D3DXMATRIX*)&curView),&inv); //update curView with texture matrix
DX8Wrapper::Set_DX8_Texture_Stage_State(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
DX8Wrapper::Set_DX8_Texture_Stage_State(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
@@ -3712,7 +3738,7 @@ Int FlatTerrainShader2Stage::set(Int pass)
else
{
//setup noise pass
- DX8Wrapper::_Get_D3D_Device()->SetTexture(0, W3DShaderManager::getShaderTexture(3)->Peek_D3D_Texture());
+ DX8Wrapper::Set_DX8_Texture(0, W3DShaderManager::getShaderTexture(3)->Peek_D3D_Texture());
terrainShader2Stage.updateNoise2(((D3DXMATRIX*)&curView),&inv); //update curView with texture matrix
DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DSAMP_MINFILTER, D3DTEXF_POINT);
DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
@@ -3756,13 +3782,12 @@ Int FlatTerrainShaderPixelShader::shutdown(void)
}
Int FlatTerrainShaderPixelShader::init( void )
-{
+{
Int res;
#ifdef DISABLE_PIXEL_SHADERS
return false;
#endif
-
//this shader will also use the 2Stage shader for some of the passes so initialize it too.
if ((res=W3DShaderManager::getChipset()) >= DC_GENERIC_PIXEL_SHADER_1_1)
{
@@ -3896,7 +3921,7 @@ Int FlatTerrainShaderPixelShader::set(Int pass)
DX8Wrapper::Set_DX8_Texture_Stage_State( curStage, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP);
DX8Wrapper::Set_DX8_Texture_Stage_State( curStage, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
DX8Wrapper::Set_DX8_Texture_Stage_State( curStage, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
- DX8Wrapper::_Get_D3D_Device()->SetTexture(curStage, shroud->getShroudTexture()->Peek_D3D_Texture());
+ DX8Wrapper::Set_DX8_Texture(curStage, shroud->getShroudTexture()->Peek_D3D_Texture());
curStage++;
if (curStage==1) curStage++;
}
@@ -3917,7 +3942,7 @@ Int FlatTerrainShaderPixelShader::set(Int pass)
DX8Wrapper::Set_DX8_Texture_Stage_State(curStage, D3DSAMP_ADDRESSU, D3DTADDRESS_WRAP);
DX8Wrapper::Set_DX8_Texture_Stage_State(curStage, D3DSAMP_ADDRESSV, D3DTADDRESS_WRAP);
- DX8Wrapper::_Get_D3D_Device()->SetTexture(curStage, W3DShaderManager::getShaderTexture(2)->Peek_D3D_Texture());
+ DX8Wrapper::Set_DX8_Texture(curStage, W3DShaderManager::getShaderTexture(2)->Peek_D3D_Texture());
terrainShader2Stage.updateNoise1(((D3DXMATRIX*)&curView),&inv); //update curView with texture matrix
DX8Wrapper::_Set_DX8_Transform((D3DTRANSFORMSTATETYPE )(D3DTS_TEXTURE0+curStage), *((Matrix4x4*)&curView));
DX8Wrapper::Set_DX8_Texture_Stage_State(curStage, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
@@ -3944,7 +3969,7 @@ Int FlatTerrainShaderPixelShader::set(Int pass)
DX8Wrapper::Set_DX8_Texture_Stage_State(curStage, D3DSAMP_ADDRESSU, D3DTADDRESS_WRAP);
DX8Wrapper::Set_DX8_Texture_Stage_State(curStage, D3DSAMP_ADDRESSV, D3DTADDRESS_WRAP);
- DX8Wrapper::_Get_D3D_Device()->SetTexture(curStage, W3DShaderManager::getShaderTexture(3)->Peek_D3D_Texture());
+ DX8Wrapper::Set_DX8_Texture(curStage, W3DShaderManager::getShaderTexture(3)->Peek_D3D_Texture());
terrainShader2Stage.updateNoise2(((D3DXMATRIX*)&curView),&inv); //update curView with texture matrix
DX8Wrapper::_Set_DX8_Transform((D3DTRANSFORMSTATETYPE )(D3DTS_TEXTURE0+curStage), *((Matrix4x4*)&curView));
DX8Wrapper::Set_DX8_Texture_Stage_State(curStage, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
@@ -3954,29 +3979,29 @@ Int FlatTerrainShaderPixelShader::set(Int pass)
if (curStage==1) curStage++;
}
if (curStage<2) {
- DX8Wrapper::_Get_D3D_Device()->SetPixelShader(m_dwBase0PixelShader);
+ DX8Wrapper::Set_Pixel_Shader(m_dwBase0PixelShader);
} else if (curStage==2) {
- DX8Wrapper::_Get_D3D_Device()->SetPixelShader(m_dwBasePixelShader);
+ DX8Wrapper::Set_Pixel_Shader(m_dwBasePixelShader);
} else if (curStage==3) {
- DX8Wrapper::_Get_D3D_Device()->SetPixelShader(m_dwBaseNoise1PixelShader);
+ DX8Wrapper::Set_Pixel_Shader(m_dwBaseNoise1PixelShader);
}else if (curStage==4) {
- DX8Wrapper::_Get_D3D_Device()->SetPixelShader(m_dwBaseNoise2PixelShader);
+ DX8Wrapper::Set_Pixel_Shader(m_dwBaseNoise2PixelShader);
}
- DX8Wrapper::_Get_D3D_Device()->SetRenderState(D3DRS_ALPHABLENDENABLE, false);
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_ALPHABLENDENABLE, false);
DX8Wrapper::Apply_Render_State_Changes();
- DX8Wrapper::_Get_D3D_Device()->SetTexture(curStage, W3DShaderManager::getShaderTexture(3)->Peek_D3D_Texture());
+ DX8Wrapper::Set_DX8_Texture(curStage, W3DShaderManager::getShaderTexture(3)->Peek_D3D_Texture());
return TRUE;
}
void FlatTerrainShaderPixelShader::reset(void)
{
- DX8Wrapper::_Get_D3D_Device()->SetTexture(2,NULL); //release reference to any texture
- DX8Wrapper::_Get_D3D_Device()->SetTexture(3,NULL); //release reference to any texture
+ DX8Wrapper::Set_DX8_Texture(2,NULL); //release reference to any texture
+ DX8Wrapper::Set_DX8_Texture(3,NULL); //release reference to any texture
- DX8Wrapper::_Get_D3D_Device()->SetPixelShader(0); //turn off pixel shader
+ DX8Wrapper::Set_Pixel_Shader(0); //turn off pixel shader
- DX8Wrapper::_Get_D3D_Device()->SetTexture(0, NULL);
- DX8Wrapper::_Get_D3D_Device()->SetTexture(1, NULL);
+ DX8Wrapper::Set_DX8_Texture(0, NULL);
+ DX8Wrapper::Set_DX8_Texture(1, NULL);
DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE);
DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_PASSTHRU|0);
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DSmudge.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DSmudge.cpp
index 2400c5d9b..4d210dd93 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DSmudge.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DSmudge.cpp
@@ -288,7 +288,7 @@ Bool W3DSmudgeManager::testHardwareSupport(void)
//not worth bothering with index/vertex buffers.
pDev->SetFVF(D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX1);
- pDev->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, sizeof(_TRANS_LIT_TEX_VERTEX));
+ DX8Wrapper::_Draw_DX8_Primitive_UP(D3DPT_TRIANGLESTRIP, 2, v, sizeof(_TRANS_LIT_TEX_VERTEX));
DWORD refData[BLOCK_SIZE*BLOCK_SIZE];
memset(refData,0,sizeof(refData));
@@ -309,7 +309,7 @@ Bool W3DSmudgeManager::testHardwareSupport(void)
v[2].color = 0xffffffff;
v[3].color = 0xffffffff;
- pDev->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, sizeof(_TRANS_LIT_TEX_VERTEX));
+ DX8Wrapper::_Draw_DX8_Primitive_UP(D3DPT_TRIANGLESTRIP, 2, v, sizeof(_TRANS_LIT_TEX_VERTEX));
bufSize=copyRect((unsigned char *)testData,sizeof(testData),0,0,BLOCK_SIZE,BLOCK_SIZE);
if (!bufSize)
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DSnow.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DSnow.cpp
index 7ecfd181a..64e308e0d 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DSnow.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DSnow.cpp
@@ -54,6 +54,19 @@ W3DSnowManager::~W3DSnowManager()
ReleaseResources();
}
+// Direct3D 11 has no point sprites at all: the fixed-function primitive that expands one vertex
+// into a screen-aligned quad was taken out of the API, and the replacement is a geometry shader the
+// backend does not have. The snow already carries a second path that builds those quads on the CPU
+// and draws them through DX8Wrapper, so a presenting D3D11 run takes that one and gets its snow.
+static Bool snowUsesPointSprites(void)
+{
+ if (Direct3D11_Present_Is_Enabled())
+ return FALSE;
+
+ return TheWeatherSetting->m_usePointSprites
+ && DX8Wrapper::Get_Current_Caps()->Support_PointSprites();
+}
+
void W3DSnowManager::init( void )
{
SnowManager::init();
@@ -81,7 +94,7 @@ Bool W3DSnowManager::ReAcquireResources(void)
if (!TheWeatherSetting->m_snowEnabled)
return TRUE; //no need for resources if snow is disabled.
- if (TheWeatherSetting->m_usePointSprites && DX8Wrapper::Get_Current_Caps()->Support_PointSprites())
+ if (snowUsesPointSprites())
{
LPDIRECT3DDEVICE9 m_pDev=DX8Wrapper::_Get_D3D_Device();
@@ -331,7 +344,7 @@ void W3DSnowManager::render(RenderInfoClass &rinfo)
if (!TheWeatherSetting->m_snowEnabled || !m_isVisible)
return;
- Int usePointSprites = DX8Wrapper::Get_Current_Caps()->Support_PointSprites() && TheWeatherSetting->m_usePointSprites;
+ Int usePointSprites = snowUsesPointSprites();
//make sure the noise table is powers of 2 in dimensions.
WWASSERT(ISPOW2(SNOW_NOISE_X) && ISPOW2(SNOW_NOISE_Y));
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTreeBuffer.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTreeBuffer.cpp
index d0beaaad7..289da259f 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTreeBuffer.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTreeBuffer.cpp
@@ -1966,10 +1966,10 @@ void W3DTreeBuffer::drawTreeBuffers(Bool shadowPass)
// unswayed and black, their shadows draw unflattened on top of them, and the buffer,
// the draw call and the matrix all look right while it happens.
dev->SetVertexDeclaration(m_treeVertexDeclaration);
- dev->SetVertexShader(m_dwTreeVertexShader);
- dev->SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, 0);
- dev->SetTextureStageState(1, D3DTSS_TEXCOORDINDEX, 1);
- dev->SetTextureStageState(1, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE);
+ DX8Wrapper::Set_Vertex_Shader(m_dwTreeVertexShader);
+ DX8Wrapper::Set_DX8_Texture_Stage_State(0, D3DTSS_TEXCOORDINDEX, 0);
+ DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DTSS_TEXCOORDINDEX, 1);
+ DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE);
}
if (shadowPass) {
//
@@ -1980,21 +1980,21 @@ void W3DTreeBuffer::drawTreeBuffers(Bool shadowPass)
// These go in behind DX8Wrapper's back, the way the shroud stage above does, so the
// caller ends drawing with Invalidate_Cached_Render_States.
//
- dev->SetRenderState(D3DRS_TEXTUREFACTOR, (D3DCOLOR)(TREE_SHADOW_ALPHA<<24));
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_TEXTUREFACTOR, (D3DCOLOR)(TREE_SHADOW_ALPHA<<24));
//
// ShaderClass sets the alpha test to 0x60 for the tree pass, where alpha comes straight
// off the texture. Here it is that alpha scaled down to the shadow's own opacity, so
// every pixel in the crown would fail the same test and the shadow would be nothing at
// all. Test near zero instead: what is being rejected is the gaps between leaves.
//
- dev->SetRenderState(D3DRS_ALPHAREF, TREE_SHADOW_ALPHAREF);
- dev->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
- dev->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
- dev->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE);
- dev->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
- dev->SetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_TFACTOR);
- dev->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE);
- dev->SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_ALPHAREF, TREE_SHADOW_ALPHAREF);
+ DX8Wrapper::Set_DX8_Texture_Stage_State(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
+ DX8Wrapper::Set_DX8_Texture_Stage_State(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
+ DX8Wrapper::Set_DX8_Texture_Stage_State(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE);
+ DX8Wrapper::Set_DX8_Texture_Stage_State(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
+ DX8Wrapper::Set_DX8_Texture_Stage_State(0, D3DTSS_ALPHAARG2, D3DTA_TFACTOR);
+ DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DTSS_COLOROP, D3DTOP_DISABLE);
+ DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
}
DX8Wrapper::Draw_Triangles( 0, m_curNumTreeIndices[bNdx]/3, 0, m_curNumTreeVertices[bNdx]);
}
@@ -2300,14 +2300,14 @@ void W3DTreeBuffer::drawTrees(CameraClass * camera, RefRenderObjListIterator *pD
shadowMat._43 += TREE_SHADOW_LIFT * shadowMat._33;
shadowMat._44 += TREE_SHADOW_LIFT * shadowMat._34;
D3DXMatrixTranspose( &shadowMat, &shadowMat );
- DX8Wrapper::_Get_D3D_Device()->SetVertexShaderConstantF( 4, (const float*)&shadowMat, 4 );
+ DX8Wrapper::Set_Vertex_Shader_Constant( 4, &shadowMat, 4 );
// c8 is the entry a tree with no sway reads, c9 and up are the sway types.
Vector4 flat(stretchX, stretchY, -1.0f, 0);
- DX8Wrapper::_Get_D3D_Device()->SetVertexShaderConstantF( 8, (const float*)&flat, 1 );
+ DX8Wrapper::Set_Vertex_Shader_Constant( 8, &flat, 1 );
for (i=0; i<MAX_SWAY_TYPES; i++) {
Vector4 flatSway(stretchX + swayFactor[i].X, stretchY + swayFactor[i].Y, -1.0f, 0);
- DX8Wrapper::_Get_D3D_Device()->SetVertexShaderConstantF( 9+i, (const float*)&flatSway, 1 );
+ DX8Wrapper::Set_Vertex_Shader_Constant( 9+i, &flatSway, 1 );
}
DX8Wrapper::Set_Shader(treeShadowShader);
@@ -2333,7 +2333,7 @@ void W3DTreeBuffer::drawTrees(CameraClass * camera, RefRenderObjListIterator *pD
D3DXMatrixTranspose( &mat, &mat );
// c4 - Composite World-View-Projection Matrix
- DX8Wrapper::_Get_D3D_Device()->SetVertexShaderConstantF( 4, (const float*)&mat, 4 );
+ DX8Wrapper::Set_Vertex_Shader_Constant( 4, &mat, 4 );
//
// The matrix the trees are about to be drawn with, checked against the one the device is
@@ -2365,12 +2365,12 @@ void W3DTreeBuffer::drawTrees(CameraClass * camera, RefRenderObjListIterator *pD
}
}
Vector4 noSway(0,0,0,0);
- DX8Wrapper::_Get_D3D_Device()->SetVertexShaderConstantF( 8, (const float*)&noSway, 1 );
+ DX8Wrapper::Set_Vertex_Shader_Constant( 8, &noSway, 1 );
// c8 - c8+MAX_SWAY_TYPES - the sway amount.
for (i=0; i<MAX_SWAY_TYPES; i++) {
Vector4 sway4(swayFactor[i].X, swayFactor[i].Y, swayFactor[i].Z, 0);
- DX8Wrapper::_Get_D3D_Device()->SetVertexShaderConstantF( 9+i, (const float*)&sway4, 1 );
+ DX8Wrapper::Set_Vertex_Shader_Constant( 9+i, &sway4, 1 );
}
W3DShroud *shroud;
@@ -2384,16 +2384,16 @@ void W3DTreeBuffer::drawTrees(CameraClass * camera, RefRenderObjListIterator *pD
xoffset = -(float)shroud->getDrawOriginX() + width;
yoffset = -(float)shroud->getDrawOriginY() + height;
Vector4 offset(xoffset, yoffset, 0, 0);
- DX8Wrapper::_Get_D3D_Device()->SetVertexShaderConstantF( 32, (const float*)&offset, 1 );
+ DX8Wrapper::Set_Vertex_Shader_Constant( 32, &offset, 1 );
width = 1.0f/(width*shroud->getTextureWidth());
height = 1.0f/(height*shroud->getTextureHeight());
offset.Set(width, height, 1, 1);
- DX8Wrapper::_Get_D3D_Device()->SetVertexShaderConstantF( 33, (const float*)&offset, 1 );
+ DX8Wrapper::Set_Vertex_Shader_Constant( 33, &offset, 1 );
} else {
Vector4 offset(0,0,0,0);
- DX8Wrapper::_Get_D3D_Device()->SetVertexShaderConstantF( 32, (const float*)&offset, 1 );
- DX8Wrapper::_Get_D3D_Device()->SetVertexShaderConstantF( 33, (const float*)&offset, 1 );
+ DX8Wrapper::Set_Vertex_Shader_Constant( 32, &offset, 1 );
+ DX8Wrapper::Set_Vertex_Shader_Constant( 33, &offset, 1 );
}
DX8Wrapper::Set_Vertex_Shader(m_dwTreeVertexShader);
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp
index c5d249148..8ecd041a9 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp
@@ -46,6 +46,7 @@
#include "light.h"
#include "d3dx9math.h"
#include "d3d8shadertranslate.h"
+#include "dx11twin.h"
#include "simplevec.h"
#include "mesh.h"
#include "matinfo.h"
@@ -122,6 +123,22 @@ typedef VertexFormatXYZDUV2 MaterMeshVertexFormat;
// Converts a FLOAT to a DWORD for use in SetRenderState() calls
static inline DWORD F2DW( FLOAT f ) { return *((DWORD*)&f); }
+//The Direct3D 11 copies of m_vertexBufferD3D and m_indexBufferD3D, null on a run without -dx11.
+//Both members are created with CreateVertexBuffer/CreateIndexBuffer straight on the device rather
+//than through DX8VertexBufferClass, so they get none of the mirroring that class does. The wave
+//grid and the mesh water share the two members and so share these two twins; whichever of the pair
+//is built last owns them.
+static DX11BufferTwinClass *waterVertexTwin=NULL;
+static DX11BufferTwinClass *waterIndexTwin=NULL;
+
+static void releaseWaterTwins(void)
+{
+ delete waterVertexTwin;
+ waterVertexTwin=NULL;
+ delete waterIndexTwin;
+ waterIndexTwin=NULL;
+}
+
#define DRAW_WATER_WAKES
/// @todo: Fix clipping of objects that intersect the mirror surface
//#define CLIP_GEOMETRY_TO_PLANE // this enables clipping of objects that intersect the mirror surfaces
@@ -250,7 +267,7 @@ void WaterRenderObjClass::setupJbaWaterShader(void)
DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_ALPHAOP, D3DTOP_ADD );
if (!m_riverAlphaEdge->Is_Initialized())
m_riverAlphaEdge->Init();
- DX8Wrapper::_Get_D3D_Device()->SetTexture(3,m_riverAlphaEdge->Peek_D3D_Texture());
+ DX8Wrapper::Set_DX8_Texture(3,m_riverAlphaEdge->Peek_D3D_Texture());
DX8Wrapper::Set_DX8_Texture_Stage_State(3, D3DSAMP_ADDRESSU, D3DTADDRESS_WRAP);
DX8Wrapper::Set_DX8_Texture_Stage_State(3, D3DSAMP_ADDRESSV, D3DTADDRESS_WRAP);
DX8Wrapper::Set_DX8_Texture_Stage_State(0, D3DTSS_TEXCOORDINDEX, 0);
@@ -262,11 +279,11 @@ void WaterRenderObjClass::setupJbaWaterShader(void)
if (m_riverWaterPixelShader && doSparkles) {
if (!m_waterSparklesTexture->Is_Initialized())
m_waterSparklesTexture->Init();
- DX8Wrapper::_Get_D3D_Device()->SetTexture(1,m_waterSparklesTexture->Peek_D3D_Texture());
+ DX8Wrapper::Set_DX8_Texture(1,m_waterSparklesTexture->Peek_D3D_Texture());
if (!m_waterNoiseTexture->Is_Initialized())
m_waterNoiseTexture->Init();
- DX8Wrapper::_Get_D3D_Device()->SetTexture(2,m_waterNoiseTexture->Peek_D3D_Texture());
+ DX8Wrapper::Set_DX8_Texture(2,m_waterNoiseTexture->Peek_D3D_Texture());
DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DSAMP_ADDRESSU, D3DTADDRESS_WRAP);
DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DSAMP_ADDRESSV, D3DTADDRESS_WRAP);
@@ -291,17 +308,17 @@ void WaterRenderObjClass::setupJbaWaterShader(void)
DX8Wrapper::_Set_DX8_Transform(D3DTS_TEXTURE2, *(Matrix4x4*)&destMatrix);
}
- m_pDev->SetSamplerState( 0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR );
- m_pDev->SetSamplerState( 0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR );
- m_pDev->SetSamplerState( 1, D3DSAMP_MINFILTER, D3DTEXF_LINEAR );
- m_pDev->SetSamplerState( 1, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR );
- m_pDev->SetSamplerState( 2, D3DSAMP_MINFILTER, D3DTEXF_LINEAR );
- m_pDev->SetSamplerState( 2, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR );
- m_pDev->SetSamplerState( 3, D3DSAMP_MINFILTER, D3DTEXF_LINEAR );
- m_pDev->SetSamplerState( 3, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR );
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR );
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR );
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DSAMP_MINFILTER, D3DTEXF_LINEAR );
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR );
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 2, D3DSAMP_MINFILTER, D3DTEXF_LINEAR );
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 2, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR );
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 3, D3DSAMP_MINFILTER, D3DTEXF_LINEAR );
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 3, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR );
if (m_riverWaterPixelShader){
DX8Wrapper::_Get_D3D_Device()->SetPixelShaderConstantF(0, D3DXVECTOR4(REFLECTION_FACTOR, REFLECTION_FACTOR, REFLECTION_FACTOR, 1.0f), 1);
- DX8Wrapper::_Get_D3D_Device()->SetPixelShader(m_riverWaterPixelShader);
+ DX8Wrapper::Set_Pixel_Shader(m_riverWaterPixelShader);
}
}
@@ -697,6 +714,10 @@ HRESULT WaterRenderObjClass::generateVertexBuffer( Int sizeX, Int sizeY, Int ver
NULL // pSharedHandle, D3D9's extra parameter, reserved and always null
)))
return hr;
+
+ delete waterVertexTwin;
+ waterVertexTwin=Direct3D11_Twin_Vertex_Buffer(m_numVertices*vertexSize,
+ (usage & D3DUSAGE_DYNAMIC)!=0);
}
m_vertexBufferD3DOffset=0;
@@ -708,12 +729,17 @@ HRESULT WaterRenderObjClass::generateVertexBuffer( Int sizeX, Int sizeY, Int ver
if (FAILED(hr=m_vertexBufferD3D->Lock
(
0,
- m_numVertices*sizeof(SEA_PATCH_VERTEX),
+ m_numVertices*sizeof(SEA_PATCH_VERTEX),
(void**)&pVertices,
0//D3DLOCK_DISCARD
)))
return hr;
+ DX11BufferLockClass vertexLock;
+ if (void *mirror=vertexLock.Begin(waterVertexTwin, pVertices, 0,
+ m_numVertices*sizeof(SEA_PATCH_VERTEX), 0))
+ pVertices=(SEA_PATCH_VERTEX*)mirror;
+
Int x,z;
for (z=0; z<sizeY; z++)
{
@@ -730,6 +756,8 @@ HRESULT WaterRenderObjClass::generateVertexBuffer( Int sizeX, Int sizeY, Int ver
}
}
+ vertexLock.End();
+
if (FAILED(hr=m_vertexBufferD3D->Unlock())) return hr;
return S_OK;
@@ -764,15 +792,22 @@ HRESULT WaterRenderObjClass::generateIndexBuffer(Int sizeX, Int sizeY)
)))
return hr;
+ delete waterIndexTwin;
+ waterIndexTwin=Direct3D11_Twin_Index_Buffer((m_numIndices+2)*sizeof(WORD), false);
+
if (FAILED(hr=m_indexBufferD3D->Lock
(
- 0,
- m_numIndices*sizeof(WORD),
+ 0,
+ m_numIndices*sizeof(WORD),
(void**)&pIndices,
0
)))
return hr;
+ DX11BufferLockClass indexLock;
+ if (void *mirror=indexLock.Begin(waterIndexTwin, pIndices, 0, m_numIndices*sizeof(WORD), 0))
+ pIndices=(WORD*)mirror;
+
Int i,j,k;
for (i=0,j=0,k=0; i<m_numIndices; j++)
@@ -833,6 +868,8 @@ HRESULT WaterRenderObjClass::generateIndexBuffer(Int sizeX, Int sizeY)
s_toggle=!s_toggle;
}
*/
+ indexLock.End();
+
if (FAILED(hr=m_indexBufferD3D->Unlock())) return hr;
return S_OK;
@@ -849,6 +886,7 @@ void WaterRenderObjClass::ReleaseResources(void)
REF_PTR_RELEASE(m_pReflectionTexture);
SAFE_RELEASE(m_vertexBufferD3D);
SAFE_RELEASE(m_indexBufferD3D);
+ releaseWaterTwins();
if (m_waterTrackSystem)
m_waterTrackSystem->ReleaseResources();
@@ -971,6 +1009,7 @@ void WaterRenderObjClass::ReAcquireResources(void)
if (hr==0) {
hr = DX8Wrapper::_Get_D3D_Device()->CreatePixelShader((DWORD*)compiledShader->GetBufferPointer(), &m_riverWaterPixelShader);
compiledShader->Release();
+ Direct3D11_Register_Engine_Shader(m_riverWaterPixelShader, "river water ps.1.1");
}
shader =
"ps.1.1\n \
@@ -984,6 +1023,7 @@ void WaterRenderObjClass::ReAcquireResources(void)
if (hr==0) {
hr = DX8Wrapper::_Get_D3D_Device()->CreatePixelShader((DWORD*)compiledShader->GetBufferPointer(), &m_waterPixelShader);
compiledShader->Release();
+ Direct3D11_Register_Engine_Shader(m_waterPixelShader, "environment water ps.1.1");
}
shader =
"ps.1.1\n \
@@ -999,6 +1039,7 @@ void WaterRenderObjClass::ReAcquireResources(void)
if (hr==0) {
hr = DX8Wrapper::_Get_D3D_Device()->CreatePixelShader((DWORD*)compiledShader->GetBufferPointer(), &m_trapezoidWaterPixelShader);
compiledShader->Release();
+ Direct3D11_Register_Engine_Shader(m_trapezoidWaterPixelShader, "trapezoid water ps.1.1");
}
}
@@ -1250,6 +1291,7 @@ void WaterRenderObjClass::enableWaterGrid(Bool state)
//Release existing grid data
SAFE_RELEASE(m_vertexBufferD3D);
SAFE_RELEASE(m_indexBufferD3D);
+ releaseWaterTwins();
//Create new grid data
if (FAILED(generateIndexBuffer(m_gridCellsX+1,m_gridCellsY+1)))
@@ -1918,57 +1960,57 @@ void WaterRenderObjClass::drawSea(RenderInfoClass & rinfo)
DX8Wrapper::_Get_DX8_Transform(D3DTS_PROJECTION, *(Matrix4x4*)&matProj);
//default setup from Kenny's demo
- m_pDev->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
- m_pDev->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
- m_pDev->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE);
- m_pDev->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_DISABLE );
- m_pDev->SetTextureStageState( 0, D3DTSS_TEXCOORDINDEX, 0 );
-
- m_pDev->SetTextureStageState( 1, D3DTSS_COLORARG1, D3DTA_TEXTURE );
- m_pDev->SetTextureStageState( 1, D3DTSS_COLORARG2, D3DTA_CURRENT );
- m_pDev->SetTextureStageState( 1, D3DTSS_COLOROP, D3DTOP_MODULATE);
- m_pDev->SetTextureStageState( 1, D3DTSS_ALPHAOP, D3DTOP_DISABLE );
- m_pDev->SetTextureStageState( 1, D3DTSS_TEXCOORDINDEX, 1 );
-
- m_pDev->SetTextureStageState( 2, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE);
- m_pDev->SetTextureStageState( 2, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_PASSTHRU|2);
-
- m_pDev->SetTextureStageState( 3, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE);
- m_pDev->SetTextureStageState( 3, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_PASSTHRU|3);
-
-// m_pDev->SetSamplerState( 0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR );
-// m_pDev->SetSamplerState( 0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR );
-// m_pDev->SetSamplerState( 0, D3DSAMP_MIPFILTER, D3DTEXF_POINT );
-
-// m_pDev->SetSamplerState( 1, D3DSAMP_MINFILTER, D3DTEXF_POINT );
-// m_pDev->SetSamplerState( 1, D3DSAMP_MAGFILTER, D3DTEXF_POINT );
-// m_pDev->SetSamplerState( 1, D3DSAMP_MIPFILTER, D3DTEXF_NONE );
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_COLOROP, D3DTOP_MODULATE);
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_ALPHAOP, D3DTOP_DISABLE );
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_TEXCOORDINDEX, 0 );
+
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_COLORARG1, D3DTA_TEXTURE );
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_COLORARG2, D3DTA_CURRENT );
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_COLOROP, D3DTOP_MODULATE);
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_ALPHAOP, D3DTOP_DISABLE );
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_TEXCOORDINDEX, 1 );
+
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 2, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE);
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 2, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_PASSTHRU|2);
+
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 3, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE);
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 3, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_PASSTHRU|3);
+
+// DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR );
+// DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR );
+// DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DSAMP_MIPFILTER, D3DTEXF_POINT );
+
+// DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DSAMP_MINFILTER, D3DTEXF_POINT );
+// DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DSAMP_MAGFILTER, D3DTEXF_POINT );
+// DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DSAMP_MIPFILTER, D3DTEXF_NONE );
//end of default setup
- m_pDev->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_WRAP);
- m_pDev->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_WRAP);
- m_pDev->SetRenderState( D3DRS_WRAP0, D3DWRAP_U | D3DWRAP_V);
+ DX8Wrapper::Set_DX8_Texture_Stage_State(0, D3DSAMP_ADDRESSU, D3DTADDRESS_WRAP);
+ DX8Wrapper::Set_DX8_Texture_Stage_State(0, D3DSAMP_ADDRESSV, D3DTADDRESS_WRAP);
+ DX8Wrapper::Set_DX8_Render_State( D3DRS_WRAP0, D3DWRAP_U | D3DWRAP_V);
- m_pDev->SetSamplerState(1, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP);
- m_pDev->SetSamplerState(1, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP);
+ DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP);
+ DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP);
- m_pDev->SetTexture( 0, m_pBumpTexture[m_iBumpFrame]);
+ DX8Wrapper::Set_DX8_Texture( 0, m_pBumpTexture[m_iBumpFrame]);
#ifdef MIPMAP_BUMP_TEXTURE
- m_pDev->SetSamplerState( 0, D3DSAMP_MIPFILTER, D3DTEXF_POINT );
- m_pDev->SetSamplerState( 0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR );
- m_pDev->SetSamplerState( 0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR );
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DSAMP_MIPFILTER, D3DTEXF_POINT );
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR );
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR );
#endif
- m_pDev->SetTextureStageState( 1, D3DTSS_BUMPENVMAT00, F2DW(m_fBumpScale) );
- m_pDev->SetTextureStageState( 1, D3DTSS_BUMPENVMAT01, F2DW(0.0f) );
- m_pDev->SetTextureStageState( 1, D3DTSS_BUMPENVMAT10, F2DW(0.0f) );
- m_pDev->SetTextureStageState( 1, D3DTSS_BUMPENVMAT11, F2DW(m_fBumpScale) );
- m_pDev->SetTextureStageState( 1, D3DTSS_BUMPENVLSCALE, F2DW(1.0f) );
- m_pDev->SetTextureStageState( 1, D3DTSS_BUMPENVLOFFSET, F2DW(0.0f) );
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_BUMPENVMAT00, F2DW(m_fBumpScale) );
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_BUMPENVMAT01, F2DW(0.0f) );
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_BUMPENVMAT10, F2DW(0.0f) );
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_BUMPENVMAT11, F2DW(m_fBumpScale) );
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_BUMPENVLSCALE, F2DW(1.0f) );
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_BUMPENVLOFFSET, F2DW(0.0f) );
- m_pDev->SetTextureStageState( 2, D3DTSS_COLOROP, D3DTOP_DISABLE );
- m_pDev->SetTextureStageState( 2, D3DTSS_ALPHAOP, D3DTOP_DISABLE );
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 2, D3DTSS_COLOROP, D3DTOP_DISABLE );
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 2, D3DTSS_ALPHAOP, D3DTOP_DISABLE );
- m_pDev->SetRenderState(D3DRS_ZWRITEENABLE , FALSE);
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_ZWRITEENABLE , FALSE);
D3DXMATRIX mat;
memset(&mat,0,sizeof(D3DXMATRIX));
@@ -1988,19 +2030,19 @@ void WaterRenderObjClass::drawSea(RenderInfoClass & rinfo)
// shader's dcl_ inputs read zero out of a stream the current FVF describes differently.
m_pDev->SetVertexDeclaration(m_waveVertexDeclaration);
m_pDev->SetVertexShader(m_dwWaveVertexShader);
- m_pDev->SetPixelShader(m_dwWavePixelShader);
+ DX8Wrapper::Set_Pixel_Shader(m_dwWavePixelShader);
// Make reflection brighter to compensate for darker coloring on sea floor
-// m_pDev->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_ONE );
-// m_pDev->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_SRCCOLOR );
+// DX8Wrapper::Set_DX8_Render_State( D3DRS_SRCBLEND, D3DBLEND_ONE );
+// DX8Wrapper::Set_DX8_Render_State( D3DRS_DESTBLEND, D3DBLEND_SRCCOLOR );
- m_pDev->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_SRCALPHA );
- m_pDev->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA );
+ DX8Wrapper::Set_DX8_Render_State( D3DRS_SRCBLEND, D3DBLEND_SRCALPHA );
+ DX8Wrapper::Set_DX8_Render_State( D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA );
- m_pDev->SetRenderState(D3DRS_ALPHABLENDENABLE , TRUE);
- m_pDev->SetTexture( 1, m_pReflectionTexture->Peek_D3D_Texture());
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_ALPHABLENDENABLE , TRUE);
+ DX8Wrapper::Set_DX8_Texture( 1, m_pReflectionTexture->Peek_D3D_Texture());
-// m_pDev->SetRenderState(D3DRS_FILLMODE,D3DFILL_WIREFRAME);//LORENZEN
+// DX8Wrapper::Set_DX8_Render_State(D3DRS_FILLMODE,D3DFILL_WIREFRAME);//LORENZEN
Int patchX,patchY,startX,startY;
@@ -2033,35 +2075,35 @@ void WaterRenderObjClass::drawSea(RenderInfoClass & rinfo)
m_pDev->DrawIndexedPrimitive(D3DPT_TRIANGLESTRIP,0,0,m_numVertices,0,m_numIndices);
}
}
-// m_pDev->SetRenderState(D3DRS_FILLMODE,D3DFILL_SOLID);
- m_pDev->SetRenderState(D3DRS_ALPHABLENDENABLE , FALSE);
- m_pDev->SetTexture( 0, NULL); //release reference to bump texture
- m_pDev->SetTexture( 1, NULL); //release reference to reflection texture
- m_pDev->SetTexture( 2, NULL); //release reference to reflection texture
+// DX8Wrapper::Set_DX8_Render_State(D3DRS_FILLMODE,D3DFILL_SOLID);
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_ALPHABLENDENABLE , FALSE);
+ DX8Wrapper::Set_DX8_Texture( 0, NULL); //release reference to bump texture
+ DX8Wrapper::Set_DX8_Texture( 1, NULL); //release reference to reflection texture
+ DX8Wrapper::Set_DX8_Texture( 2, NULL); //release reference to reflection texture
- m_pDev->SetTextureStageState( 0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE);
- m_pDev->SetTextureStageState( 0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_PASSTHRU|0);
- m_pDev->SetTextureStageState( 1, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE);
- m_pDev->SetTextureStageState( 1, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_PASSTHRU|1);
- m_pDev->SetRenderState(D3DRS_ZWRITEENABLE , TRUE);
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE);
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_PASSTHRU|0);
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE);
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_PASSTHRU|1);
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_ZWRITEENABLE , TRUE);
- m_pDev->SetSamplerState(1, D3DSAMP_ADDRESSU, D3DTADDRESS_WRAP);
- m_pDev->SetSamplerState(1, D3DSAMP_ADDRESSV, D3DTADDRESS_WRAP);
+ DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DSAMP_ADDRESSU, D3DTADDRESS_WRAP);
+ DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DSAMP_ADDRESSV, D3DTADDRESS_WRAP);
- m_pDev->SetRenderState( D3DRS_WRAP0, 0); //turn off texture wrapping
+ DX8Wrapper::Set_DX8_Render_State( D3DRS_WRAP0, 0); //turn off texture wrapping
- m_pDev->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_DISABLE );
- m_pDev->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_DISABLE );
- m_pDev->SetTextureStageState( 1, D3DTSS_COLOROP, D3DTOP_DISABLE );
- m_pDev->SetTextureStageState( 1, D3DTSS_ALPHAOP, D3DTOP_DISABLE );
- m_pDev->SetTextureStageState( 2, D3DTSS_COLOROP, D3DTOP_DISABLE );
- m_pDev->SetTextureStageState( 2, D3DTSS_ALPHAOP, D3DTOP_DISABLE );
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_COLOROP, D3DTOP_DISABLE );
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_ALPHAOP, D3DTOP_DISABLE );
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_COLOROP, D3DTOP_DISABLE );
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_ALPHAOP, D3DTOP_DISABLE );
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 2, D3DTSS_COLOROP, D3DTOP_DISABLE );
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 2, D3DTSS_ALPHAOP, D3DTOP_DISABLE );
//Restore old transforms
DX8Wrapper::_Set_DX8_Transform(D3DTS_VIEW, *(Matrix4x4*)&matView);
DX8Wrapper::_Set_DX8_Transform(D3DTS_PROJECTION, *(Matrix4x4*)&matProj);
- m_pDev->SetPixelShader(0); //turn off pixel shader
+ DX8Wrapper::Set_Pixel_Shader(0); //turn off pixel shader
m_pDev->SetVertexShader(NULL); //turn off custom vertex shader
m_pDev->SetFVF(DX8_FVF_XYZDUV1);
@@ -2399,16 +2441,24 @@ void WaterRenderObjClass::renderWaterMesh(void)
#endif
MaterMeshVertexFormat *vb;
+ DX11BufferLockClass vertexLock;
+ const unsigned lockBytes=mx*my*sizeof(MaterMeshVertexFormat);
if (m_vertexBufferD3DOffset < m_numVertices)
{ //we have room in current VB, append new verts
- if(m_vertexBufferD3D->Lock(m_vertexBufferD3DOffset*sizeof(MaterMeshVertexFormat),mx*my*sizeof(MaterMeshVertexFormat),(void**)&vb,D3DLOCK_NOOVERWRITE) != D3D_OK)
+ if(m_vertexBufferD3D->Lock(m_vertexBufferD3DOffset*sizeof(MaterMeshVertexFormat),lockBytes,(void**)&vb,D3DLOCK_NOOVERWRITE) != D3D_OK)
return;
+ if (void *mirror=vertexLock.Begin(waterVertexTwin, vb,
+ m_vertexBufferD3DOffset*sizeof(MaterMeshVertexFormat), lockBytes,
+ D3DLOCK_NOOVERWRITE))
+ vb=(MaterMeshVertexFormat*)mirror;
}
else
{ //ran out of room in last VB, request a substitute VB.
- if(m_vertexBufferD3D->Lock(0,mx*my*sizeof(MaterMeshVertexFormat),(void**)&vb,D3DLOCK_DISCARD) != D3D_OK)
+ if(m_vertexBufferD3D->Lock(0,lockBytes,(void**)&vb,D3DLOCK_DISCARD) != D3D_OK)
return;
m_vertexBufferD3DOffset=0; //reset start of page to first vertex
+ if (void *mirror=vertexLock.Begin(waterVertexTwin, vb, 0, lockBytes, D3DLOCK_DISCARD))
+ vb=(MaterMeshVertexFormat*)mirror;
}
Int diffuse;
diffuse = setting->waterDiffuse&0x00ffffff;
@@ -2474,6 +2524,8 @@ void WaterRenderObjClass::renderWaterMesh(void)
}
}
+ vertexLock.End();
+
m_vertexBufferD3D->Unlock();
Matrix3D tm(Transform);
@@ -2510,12 +2562,15 @@ void WaterRenderObjClass::renderWaterMesh(void)
#endif
-// m_pDev->SetRenderState(D3DRS_ZFUNC,D3DCMP_ALWAYS); //used to display grid under map.
+// DX8Wrapper::Set_DX8_Render_State(D3DRS_ZFUNC,D3DCMP_ALWAYS); //used to display grid under map.
// D3D9 takes the base vertex index on the draw call, not here.
m_pDev->SetIndices(m_indexBufferD3D);
m_pDev->SetStreamSource(0,m_vertexBufferD3D,0,sizeof(MaterMeshVertexFormat));
- m_pDev->SetFVF(WATER_MESH_FVF);
+ DX8Wrapper::Set_Vertex_Format(WATER_MESH_FVF);
+
+ Direct3D11_Mirror_Stream_Source(waterVertexTwin,sizeof(MaterMeshVertexFormat),0);
+ Direct3D11_Mirror_Indices(waterIndexTwin);
if (TheTerrainRenderObject->getShroud() && !m_trapezoidWaterPixelShader)
@@ -2532,19 +2587,24 @@ void WaterRenderObjClass::renderWaterMesh(void)
//Shroud shader uses z-compare of EQUAL which wouldn't work on water because it doesn't
//write to the zbuffer. Change to LESSEQUAL.
- DX8Wrapper::_Get_D3D_Device()->SetRenderState(D3DRS_ZFUNC, D3DCMP_LESSEQUAL);
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_ZFUNC, D3DCMP_LESSEQUAL);
m_pDev->DrawIndexedPrimitive(D3DPT_TRIANGLESTRIP,m_vertexBufferD3DOffset,0,mx*my,0,m_numIndices-2);
- DX8Wrapper::_Get_D3D_Device()->SetRenderState(D3DRS_ZFUNC, D3DCMP_EQUAL);
+ Direct3D11_Draw_Indexed_Strip(m_numIndices,0,m_vertexBufferD3DOffset);
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_ZFUNC, D3DCMP_EQUAL);
W3DShaderManager::resetShader(W3DShaderManager::ST_SHROUD_TEXTURE);
}
else
+ {
m_pDev->DrawIndexedPrimitive(D3DPT_TRIANGLESTRIP,m_vertexBufferD3DOffset,0,mx*my,0,m_numIndices-2);
-
+ Direct3D11_Draw_Indexed_Strip(m_numIndices,0,m_vertexBufferD3DOffset);
+ }
+
+
Debug_Statistics::Record_DX8_Polys_And_Vertices(m_numIndices-2,mx*my,ShaderClass::_PresetOpaqueShader);
-// m_pDev->SetRenderState(D3DRS_FILLMODE,D3DFILL_SOLID);
+// DX8Wrapper::Set_DX8_Render_State(D3DRS_FILLMODE,D3DFILL_SOLID);
- if (m_trapezoidWaterPixelShader) DX8Wrapper::_Get_D3D_Device()->SetPixelShader(NULL);
+ if (m_trapezoidWaterPixelShader) DX8Wrapper::Set_Pixel_Shader(NULL);
m_vertexBufferD3DOffset += mx*my; //advance past vertices already in buffer
@@ -3011,22 +3071,22 @@ void WaterRenderObjClass::drawRiverWater(PolygonTrigger *pTrig)
if (TheWaterTransparency->m_additiveBlend)
DX8Wrapper::Set_DX8_Render_State(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA );
- if (m_riverWaterPixelShader) DX8Wrapper::_Get_D3D_Device()->SetPixelShader(m_riverWaterPixelShader);
+ if (m_riverWaterPixelShader) DX8Wrapper::Set_Pixel_Shader(m_riverWaterPixelShader);
DWORD cull;
DX8Wrapper::_Get_D3D_Device()->GetRenderState(D3DRS_CULLMODE, &cull);
- DX8Wrapper::_Get_D3D_Device()->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_CULLMODE, D3DCULL_NONE);
if (wireframeForDebug) {
- DX8Wrapper::_Get_D3D_Device()->SetRenderState(D3DRS_FILLMODE,D3DFILL_WIREFRAME);
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_FILLMODE,D3DFILL_WIREFRAME);
}
DX8Wrapper::Draw_Triangles( 0,rectangleCount*2, 0, (rectangleCount+1)*2);
if (wireframeForDebug) {
- DX8Wrapper::_Get_D3D_Device()->SetRenderState(D3DRS_FILLMODE,D3DFILL_SOLID);
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_FILLMODE,D3DFILL_SOLID);
}
- if (m_riverWaterPixelShader) DX8Wrapper::_Get_D3D_Device()->SetPixelShader(NULL);
+ if (m_riverWaterPixelShader) DX8Wrapper::Set_Pixel_Shader(NULL);
//restore blend mode to what W3D expects.
if (TheWaterTransparency->m_additiveBlend)
@@ -3034,7 +3094,7 @@ void WaterRenderObjClass::drawRiverWater(PolygonTrigger *pTrig)
// the shroud is in the vertex colour now - see applyShroudToRiverDiffuse. The second pass that
// used to apply it here darkened the banks twice.
- DX8Wrapper::_Get_D3D_Device()->SetRenderState(D3DRS_CULLMODE, cull);
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_CULLMODE, cull);
}
@@ -3066,7 +3126,7 @@ void WaterRenderObjClass::setupFlatWaterShader(void)
W3DShaderManager::setShader(W3DShaderManager::ST_SHROUD_TEXTURE, 3);
//Shroud shader uses z-compare of EQUAL which wouldn't work on water because it doesn't
//write to the zbuffer. Change to LESSEQUAL.
- DX8Wrapper::_Get_D3D_Device()->SetRenderState(D3DRS_ZFUNC, D3DCMP_LESSEQUAL);
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_ZFUNC, D3DCMP_LESSEQUAL);
}
else
{ //Assume no shroud, so stage 3 will be "NULL" texture but using actual white because
@@ -3077,7 +3137,7 @@ void WaterRenderObjClass::setupFlatWaterShader(void)
surface->DrawPixel(0,0,0xffffffff);
REF_PTR_RELEASE(surface);
}
- DX8Wrapper::_Get_D3D_Device()->SetTexture(3,m_whiteTexture->Peek_D3D_Texture());
+ DX8Wrapper::Set_DX8_Texture(3,m_whiteTexture->Peek_D3D_Texture());
}
}
@@ -3092,12 +3152,12 @@ void WaterRenderObjClass::setupFlatWaterShader(void)
if (!m_waterSparklesTexture->Is_Initialized())
m_waterSparklesTexture->Init();
- DX8Wrapper::_Get_D3D_Device()->SetTexture(1,m_waterSparklesTexture->Peek_D3D_Texture());
+ DX8Wrapper::Set_DX8_Texture(1,m_waterSparklesTexture->Peek_D3D_Texture());
if (!m_waterNoiseTexture->Is_Initialized())
m_waterNoiseTexture->Init();
- DX8Wrapper::_Get_D3D_Device()->SetTexture(2,m_waterNoiseTexture->Peek_D3D_Texture());
+ DX8Wrapper::Set_DX8_Texture(2,m_waterNoiseTexture->Peek_D3D_Texture());
DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DSAMP_ADDRESSU, D3DTADDRESS_WRAP);
DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DSAMP_ADDRESSV, D3DTADDRESS_WRAP);
@@ -3122,15 +3182,15 @@ void WaterRenderObjClass::setupFlatWaterShader(void)
DX8Wrapper::_Set_DX8_Transform(D3DTS_TEXTURE2, *(Matrix4x4*)&destMatrix);
}
- m_pDev->SetSamplerState( 0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR );
- m_pDev->SetSamplerState( 0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR );
- m_pDev->SetSamplerState( 1, D3DSAMP_MINFILTER, D3DTEXF_LINEAR );
- m_pDev->SetSamplerState( 1, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR );
- m_pDev->SetSamplerState( 2, D3DSAMP_MINFILTER, D3DTEXF_LINEAR );
- m_pDev->SetSamplerState( 2, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR );
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR );
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR );
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DSAMP_MINFILTER, D3DTEXF_LINEAR );
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR );
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 2, D3DSAMP_MINFILTER, D3DTEXF_LINEAR );
+ DX8Wrapper::Set_DX8_Texture_Stage_State( 2, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR );
if (m_trapezoidWaterPixelShader){
DX8Wrapper::_Get_D3D_Device()->SetPixelShaderConstantF(0, D3DXVECTOR4(REFLECTION_FACTOR, REFLECTION_FACTOR, REFLECTION_FACTOR, 1.0f), 1);
- DX8Wrapper::_Get_D3D_Device()->SetPixelShader(m_trapezoidWaterPixelShader);
+ DX8Wrapper::Set_Pixel_Shader(m_trapezoidWaterPixelShader);
}
}
@@ -3381,7 +3441,7 @@ void WaterRenderObjClass::drawTrapezoidWater(Vector3 points[4])
DWORD cull;
DX8Wrapper::_Get_D3D_Device()->GetRenderState(D3DRS_CULLMODE, &cull);
- DX8Wrapper::_Get_D3D_Device()->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_CULLMODE, D3DCULL_NONE);
@@ -3410,14 +3470,14 @@ void WaterRenderObjClass::drawTrapezoidWater(Vector3 points[4])
if (false) {
- DX8Wrapper::_Get_D3D_Device()->SetRenderState(D3DRS_FILLMODE,D3DFILL_WIREFRAME);
- m_pDev->SetRenderState(D3DRS_ALPHABLENDENABLE , false);
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_FILLMODE,D3DFILL_WIREFRAME);
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_ALPHABLENDENABLE , false);
DX8Wrapper::Draw_Triangles( 0,rectangleCount*2, 0, (rectangleCount+1)*2);
- m_pDev->SetRenderState(D3DRS_ALPHABLENDENABLE , true);
- DX8Wrapper::_Get_D3D_Device()->SetRenderState(D3DRS_FILLMODE,D3DFILL_SOLID);
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_ALPHABLENDENABLE , true);
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_FILLMODE,D3DFILL_SOLID);
}
- if (m_riverWaterPixelShader) DX8Wrapper::_Get_D3D_Device()->SetPixelShader(NULL);
+ if (m_riverWaterPixelShader) DX8Wrapper::Set_Pixel_Shader(NULL);
//Restore alpha blend to default values since we may have changed them to feather edges.
if (!TheWaterTransparency->m_additiveBlend)
{ DX8Wrapper::Set_DX8_Render_State(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA );
@@ -3434,23 +3494,23 @@ void WaterRenderObjClass::drawTrapezoidWater(Vector3 points[4])
if (m_trapezoidWaterPixelShader)
{ //shroud was applied in stage3 of main pass so just need to restore state here.
W3DShaderManager::resetShader(W3DShaderManager::ST_SHROUD_TEXTURE);
- DX8Wrapper::_Get_D3D_Device()->SetTexture(3,NULL); //free possible reference to shroud texture
- DX8Wrapper::_Get_D3D_Device()->SetRenderState(D3DRS_ZFUNC, D3DCMP_EQUAL);
+ DX8Wrapper::Set_DX8_Texture(3,NULL); //free possible reference to shroud texture
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_ZFUNC, D3DCMP_EQUAL);
}
else
{ //do second pass to apply the shroud on water plane for cards that can't do it in main pass.
W3DShaderManager::setTexture(0,TheTerrainRenderObject->getShroud()->getShroudTexture());
W3DShaderManager::setShader(W3DShaderManager::ST_SHROUD_TEXTURE, 0);
- DX8Wrapper::_Get_D3D_Device()->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_CULLMODE, D3DCULL_NONE);
//Shroud shader uses z-compare of EQUAL which wouldn't work on water because it doesn't
//write to the zbuffer. Change to LESSEQUAL.
- DX8Wrapper::_Get_D3D_Device()->SetRenderState(D3DRS_ZFUNC, D3DCMP_LESSEQUAL);
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_ZFUNC, D3DCMP_LESSEQUAL);
DX8Wrapper::Draw_Triangles( 0,rectangleCount*2, 0, (rectangleCount+1)*2);
- DX8Wrapper::_Get_D3D_Device()->SetRenderState(D3DRS_ZFUNC, D3DCMP_EQUAL);
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_ZFUNC, D3DCMP_EQUAL);
W3DShaderManager::resetShader(W3DShaderManager::ST_SHROUD_TEXTURE);
}
}
- DX8Wrapper::_Get_D3D_Device()->SetRenderState(D3DRS_CULLMODE, cull);
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_CULLMODE, cull);
}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/d3d8shadertranslate.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/d3d8shadertranslate.cpp
index b3518d6b3..619c071d9 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/d3d8shadertranslate.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/d3d8shadertranslate.cpp
@@ -135,7 +135,7 @@ static size_t instruction_count_of(const std::string & source, const char * coun
}
HRESULT Create_Translated_Pixel_Shader(IDirect3DDevice9 * device, const DWORD * function,
- IDirect3DPixelShader9 ** shader)
+ IDirect3DPixelShader9 ** shader, std::string * translated_source)
{
if (device == NULL || function == NULL || shader == NULL) {
return D3DERR_INVALIDCALL;
@@ -177,6 +177,10 @@ HRESULT Create_Translated_Pixel_Shader(IDirect3DDevice9 * device, const DWORD *
std::regex("(add)([_satxd248]*) (r[0-9][\\.wxyz]*), ((1-|)[crtv][0-9][\\.wxyz_abdis2]*), (-)(c[0-9][\\.wxyz]*)(_bx2|_bias|_x2|_d[zbwa]|)(?![_\\.wxyz])"),
"sub$2 $3, $4, $7$8");
+ if (translated_source != NULL) {
+ *translated_source = source;
+ }
+
ID3DXBuffer * assembly = NULL;
ID3DXBuffer * errors = NULL;
result = D3DXAssembleShader(source.data(), static_cast<UINT>(source.size()), NULL, NULL, 0,
@@ -195,7 +199,7 @@ HRESULT Create_Translated_Pixel_Shader(IDirect3DDevice9 * device, const DWORD *
HRESULT Create_Translated_Vertex_Shader(IDirect3DDevice9 * device, const DWORD * d3d8_declaration,
const DWORD * function, IDirect3DVertexShader9 ** shader,
- IDirect3DVertexDeclaration9 ** vertex_declaration)
+ IDirect3DVertexDeclaration9 ** vertex_declaration, std::string * translated_source)
{
if (device == NULL || d3d8_declaration == NULL || function == NULL
|| shader == NULL || vertex_declaration == NULL) {
@@ -379,6 +383,10 @@ HRESULT Create_Translated_Vertex_Shader(IDirect3DDevice9 * device, const DWORD *
}
}
+ if (translated_source != NULL) {
+ *translated_source = source;
+ }
+
ID3DXBuffer * assembly = NULL;
ID3DXBuffer * errors = NULL;
result = D3DXAssembleShader(source.data(), static_cast<UINT>(source.size()), NULL, NULL, 0,
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/d3d8shadertranslate.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/d3d8shadertranslate.h
index faf404125..ae425a01b 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/d3d8shadertranslate.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/d3d8shadertranslate.h
@@ -43,6 +43,7 @@
#define D3D8SHADERTRANSLATE_H
#include <d3d9.h>
+#include <string>
// The D3D8 vertex declaration tokens, so the declaration arrays the engine already
// writes keep compiling. D3D9 has no such tokens; Create_Translated_Vertex_Shader
@@ -80,9 +81,12 @@
#define D3DVSDT_SHORT4 0x07
// Translates ps_1_x bytecode compiled for D3D8 and creates the shader. Returns
-// D3DERR_INVALIDCALL for anything that is not ps_1_0 to ps_1_4.
+// D3DERR_INVALIDCALL for anything that is not ps_1_0 to ps_1_4. translated_source, when given,
+// comes back holding the assembly the shader was built from: the .vso and .pso files ship as
+// bytecode and this is the only place their source exists, which is what anything rewriting them
+// for another API has to read.
HRESULT Create_Translated_Pixel_Shader(IDirect3DDevice9 * device, const DWORD * function,
- IDirect3DPixelShader9 ** shader);
+ IDirect3DPixelShader9 ** shader, std::string * translated_source = NULL);
// Translates vs_1_x bytecode and its D3D8 declaration array, and creates both the shader
// and the D3D9 vertex declaration that has to be bound with it. Either output may come
@@ -90,6 +94,6 @@ HRESULT Create_Translated_Pixel_Shader(IDirect3DDevice9 * device, const DWORD *
// to release.
HRESULT Create_Translated_Vertex_Shader(IDirect3DDevice9 * device, const DWORD * d3d8_declaration,
const DWORD * function, IDirect3DVertexShader9 ** shader,
- IDirect3DVertexDeclaration9 ** vertex_declaration);
+ IDirect3DVertexDeclaration9 ** vertex_declaration, std::string * translated_source = NULL);
#endif // D3D8SHADERTRANSLATE_H
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp
index 95297b740..298cae9ad 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp
@@ -19,6 +19,7 @@
#include "dx11backend.h"
#include "dx11layout.h"
+#include "dx11resource.h"
#include <d3dcommon.h>
#include <stdio.h>
@@ -45,8 +46,7 @@ struct VertexConstantBlock
float WorldViewProjection[16];
float WorldView[16];
float NormalTransform[16];
- float TextureMatrix0[16];
- float TextureMatrix1[16];
+ float TextureMatrix[MAXIMUM_VERTEX_STAGES][16];
float MaterialAmbient[4];
float MaterialDiffuse[4];
float MaterialSpecular[4];
@@ -54,9 +54,20 @@ struct VertexConstantBlock
float MaterialPower[4];
float GlobalAmbient[4];
float FogParameters[4];
+ // One over the viewport's width and height, for the pre-transformed draws. It goes before the
+ // lights because the generated block declares only as many lights as the state has.
+ float ViewportInverse[4];
float LightFields[MAXIMUM_VERTEX_LIGHTS][6][4];
};
+// The three stage counts are one count in three headers. The block above is copied wholesale out
+// of the backend's own texture transforms, the generated pixel shader declares one sampler per
+// texture the backend binds, and a mismatch is a silent overrun rather than a build failure.
+static_assert(MAXIMUM_VERTEX_STAGES == DX11_BACKEND_TEXTURE_STAGES,
+ "ffvertex declares one texture matrix per stage and the backend uploads one per stage");
+static_assert(MAXIMUM_COMBINER_STAGES == DX11_BACKEND_TEXTURE_STAGES,
+ "ffshader declares one sampler per stage and the backend binds one per stage");
+
struct PixelConstantBlock
{
float TextureFactor[4];
@@ -143,12 +154,35 @@ DX11BackendClass::DX11BackendClass()
, MaterialPower(0.0f)
, VertexConstantBuffer(NULL)
, PixelConstantBuffer(NULL)
+ , EngineConstantBuffer(NULL)
+ , VertexProgram(ENGINE_SHADER_NONE)
+ , PixelProgram(ENGINE_SHADER_NONE)
+ , UserBuffer(NULL)
+ , UserBufferBytes(0)
, PipelinesBuilt(0)
+ , TracedUserStrip(false)
+ , MaskWhileTargeted(0)
+ , TargetsBound(0)
+ , TargetsRestored(0)
+ , DrawsIntoTargets(0)
+ , CurrentTarget(NULL)
+ , CurrentDepth(NULL)
, DrawsMade(0)
, DrawsRefused(0)
+ , RefusedNoBuffer(0)
+ , RefusedNoStage(0)
+ , RefusedNoLayout(0)
+ , RefusedNoProgram(0)
+ , RefusedNoObject(0)
+ , RefusedForeignShader(0)
+ , RefusedNoTexture(0)
+ , ForeignPixelShader(false)
+ , ForeignVertexShader(false)
{
memset(StageStates, 0, sizeof(StageStates));
memset(Textures, 0, sizeof(Textures));
+ memset(EngineConstants, 0, sizeof(EngineConstants));
+ memset(MissingTexture, 0, sizeof(MissingTexture));
memset(Lights, 0, sizeof(Lights));
memset(MaterialAmbient, 0, sizeof(MaterialAmbient));
memset(MaterialDiffuse, 0, sizeof(MaterialDiffuse));
@@ -158,6 +192,11 @@ DX11BackendClass::DX11BackendClass()
set_identity(World);
set_identity(View);
set_identity(Projection);
+ for (unsigned stage = 0; stage < DX11_BACKEND_TEXTURE_STAGES; ++stage) {
+ set_identity(TextureTransforms[stage]);
+ }
+ ViewportWidth = 1;
+ ViewportHeight = 1;
// 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) {
@@ -192,7 +231,12 @@ bool DX11BackendClass::Initialise(DX11DeviceClass * device)
}
description.ByteWidth = sizeof(PixelConstantBlock);
- return SUCCEEDED(Device->Get_Device()->CreateBuffer(&description, NULL, &PixelConstantBuffer));
+ if (FAILED(Device->Get_Device()->CreateBuffer(&description, NULL, &PixelConstantBuffer))) {
+ return false;
+ }
+
+ description.ByteWidth = sizeof(EngineConstants);
+ return SUCCEEDED(Device->Get_Device()->CreateBuffer(&description, NULL, &EngineConstantBuffer));
}
void DX11BackendClass::Release_Cached()
@@ -223,6 +267,16 @@ void DX11BackendClass::Release_Cached()
}
RasterizerStates.clear();
+ for (std::map<unsigned long long, ID3D11DepthStencilView *>::iterator entry
+ = TargetDepths.begin(); entry != TargetDepths.end(); ++entry) {
+ if (entry->second != NULL) {
+ entry->second->Release();
+ }
+ }
+ TargetDepths.clear();
+ CurrentTarget = NULL;
+ CurrentDepth = NULL;
+
for (std::map<std::string, ID3D11SamplerState *>::iterator entry = SamplerStates.begin();
entry != SamplerStates.end(); ++entry) {
entry->second->Release();
@@ -234,6 +288,10 @@ void DX11BackendClass::Shutdown()
{
Release_Cached();
+ if (EngineConstantBuffer != NULL) {
+ EngineConstantBuffer->Release();
+ EngineConstantBuffer = NULL;
+ }
if (PixelConstantBuffer != NULL) {
PixelConstantBuffer->Release();
PixelConstantBuffer = NULL;
@@ -242,6 +300,11 @@ void DX11BackendClass::Shutdown()
VertexConstantBuffer->Release();
VertexConstantBuffer = NULL;
}
+ if (UserBuffer != NULL) {
+ UserBuffer->Release();
+ UserBuffer = NULL;
+ UserBufferBytes = 0;
+ }
Device = NULL;
}
@@ -277,6 +340,65 @@ void DX11BackendClass::Set_Vertex_Format(DWORD fvf)
VertexFormat = fvf;
}
+void DX11BackendClass::Set_Pixel_Program(EngineShaderProgram program, bool bound,
+ const char * file_name)
+{
+ PixelProgram = bound ? program : ENGINE_SHADER_NONE;
+ ForeignPixelShader = bound && program == ENGINE_SHADER_NONE;
+ ForeignPixelName = ForeignPixelShader ? file_name : "";
+}
+
+void DX11BackendClass::Set_Vertex_Program(EngineShaderProgram program, bool bound,
+ const char * file_name)
+{
+ VertexProgram = bound ? program : ENGINE_SHADER_NONE;
+ ForeignVertexShader = bound && program == ENGINE_SHADER_NONE;
+ ForeignVertexName = ForeignVertexShader ? file_name : "";
+}
+
+// Named by whichever half has no program, and by both when neither does.
+void DX11BackendClass::Note_Foreign_Refusal()
+{
+ std::string which = ForeignVertexShader ? ForeignVertexName : std::string();
+ if (ForeignPixelShader) {
+ if (!which.empty()) {
+ which += " with ";
+ }
+ which += ForeignPixelName;
+ }
+ ++ForeignRefusals[which];
+}
+
+unsigned DX11BackendClass::Foreign_Report_Count() const
+{
+ return (unsigned)ForeignRefusals.size();
+}
+
+const char * DX11BackendClass::Foreign_Report(unsigned index)
+{
+ std::map<std::string, unsigned long long>::const_iterator entry = ForeignRefusals.begin();
+ for (unsigned step = 0; step < index && entry != ForeignRefusals.end(); ++step) {
+ ++entry;
+ }
+ if (entry == ForeignRefusals.end()) {
+ return "";
+ }
+
+ char tail[64];
+ snprintf(tail, sizeof(tail), " -> %llu draws", entry->second);
+ ReportLine = entry->first + tail;
+ return ReportLine.c_str();
+}
+
+void DX11BackendClass::Set_Vertex_Program_Constant(unsigned first_register, const float * values,
+ unsigned count)
+{
+ if (first_register + count > ENGINE_SHADER_CONSTANTS) {
+ return;
+ }
+ memcpy(EngineConstants[first_register], values, sizeof(float) * 4 * count);
+}
+
void DX11BackendClass::Set_Stream_Source(ID3D11Buffer * buffer, unsigned stride, unsigned offset)
{
StreamBuffer = buffer;
@@ -296,7 +418,12 @@ void DX11BackendClass::Set_Transform(D3DTRANSFORMSTATETYPE state, const float ma
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;
+ default:
+ if (state >= D3DTS_TEXTURE0
+ && state < D3DTS_TEXTURE0 + (int)DX11_BACKEND_TEXTURE_STAGES) {
+ memcpy(TextureTransforms[state - D3DTS_TEXTURE0], matrix, sizeof(float) * 16);
+ }
+ break;
}
}
@@ -336,6 +463,181 @@ void DX11BackendClass::Disable_Light(unsigned index)
}
}
+void DX11BackendClass::Set_Texture_Missing(unsigned stage, bool missing)
+{
+ if (stage < DX11_BACKEND_TEXTURE_STAGES) {
+ MissingTexture[stage] = missing;
+ }
+}
+
+// A stage only matters while its colour operation is on: the engine leaves textures bound at stages
+// it has switched off, and refusing for one of those would refuse most of the frame.
+bool DX11BackendClass::Any_Missing_Texture() const
+{
+ for (unsigned stage = 0; stage < DX11_BACKEND_TEXTURE_STAGES; ++stage) {
+ if (StageStates[stage][D3DTSS_COLOROP] == D3DTOP_DISABLE) {
+ break;
+ }
+ if (MissingTexture[stage]) {
+ return true;
+ }
+ }
+ return false;
+}
+
+void DX11BackendClass::Set_Dump_Directory(const char * directory)
+{
+ DumpDirectory = directory == NULL ? "" : directory;
+}
+
+// The key has characters a file name cannot carry, so it becomes the file's first line and the
+// name is a number. Both programs of one pipeline go in one file, in the order they run.
+void DX11BackendClass::Dump_Program(const std::string & key, const std::string & vertex_hlsl,
+ const std::string & pixel_hlsl)
+{
+ if (DumpDirectory.empty()) {
+ return;
+ }
+
+ char path[512];
+ snprintf(path, sizeof(path), "%s/pipeline%03u.hlsl", DumpDirectory.c_str(), PipelinesBuilt);
+ FILE * file = fopen(path, "wb");
+ if (file == NULL) {
+ return;
+ }
+
+ fprintf(file, "// state: %s\n\n// ---- vertex ----\n%s\n// ---- pixel ----\n%s\n",
+ key.c_str(), vertex_hlsl.c_str(), pixel_hlsl.c_str());
+ fclose(file);
+}
+
+void DX11BackendClass::Begin_Scene()
+{
+ // A scene can begin with a render target already set: the water's reflection and the shadow
+ // projector both set theirs and then call WW3D::Begin_Render, and forcing the back buffer here
+ // sent the reflection scene, and its clear, over the picture that was already drawn.
+ if (CurrentTarget != NULL) {
+ return;
+ }
+
+ ID3D11RenderTargetView * target = Device->Get_Back_Buffer_View();
+ if (target == NULL) {
+ return;
+ }
+
+ Device->Get_Context()->OMSetRenderTargets(1, &target, Device->Get_Depth_Stencil_View());
+ Set_Viewport(0, 0, Device->Get_Width(), Device->Get_Height());
+}
+
+ID3D11DepthStencilView * DX11BackendClass::Depth_For(unsigned width, unsigned height)
+{
+ // A target the size of the back buffer shares the back buffer's depth, because that is what
+ // the Direct3D 9 device does: the screen filters redirect the scene into a texture and hand
+ // SetRenderTarget the depth surface the frame's Begin_Render already cleared. Made separately
+ // here, nothing ever cleared it, every triangle in the scene failed the depth test, and the
+ // texture the composite sampled held its clear colour and nothing else - a black world under a
+ // live command bar, which is what the bloom looked like for two sessions.
+ if (width == Device->Get_Width() && height == Device->Get_Height()) {
+ return Device->Get_Depth_Stencil_View();
+ }
+
+ const unsigned long long key = (static_cast<unsigned long long>(width) << 32) | height;
+ std::map<unsigned long long, ID3D11DepthStencilView *>::const_iterator existing
+ = TargetDepths.find(key);
+ if (existing != TargetDepths.end()) {
+ return existing->second;
+ }
+
+ ID3D11Texture2D * texture = NULL;
+ ID3D11ShaderResourceView * unused = NULL;
+ if (!DX11Resource_Create_Texture(Device->Get_Device(), width, height, 1, D3DFMT_D24S8,
+ D3DPOOL_DEFAULT, D3DUSAGE_DEPTHSTENCIL, &texture, &unused)) {
+ Note_Refusal("the device refused a depth buffer for a render target");
+ TargetDepths[key] = NULL;
+ return NULL;
+ }
+
+ ID3D11DepthStencilView * view = NULL;
+ if (FAILED(Device->Get_Device()->CreateDepthStencilView(texture, NULL, &view))) {
+ Note_Refusal("the device refused a depth view for a render target");
+ view = NULL;
+ }
+ else {
+ // A new depth texture holds whatever the driver left in it, which reads as everything being
+ // nearer than anything about to be drawn. Nothing else clears this one: the engine's own
+ // clear goes to whichever surface Direct3D 9 has bound, and this surface has no D3D9 twin.
+ Device->Get_Context()->ClearDepthStencilView(view,
+ D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
+ }
+ texture->Release();
+
+ TargetDepths[key] = view;
+ return view;
+}
+
+// The last few target changes rather than the first few: the first are the loading screen's, and
+// the question is which target the scene itself is drawn into.
+void DX11BackendClass::Trace_Target(const char * what, unsigned width, unsigned height)
+{
+ char line[80];
+ if (width == 0) {
+ snprintf(line, sizeof(line), "%s after %llu draws", what, DrawsMade);
+ }
+ else {
+ snprintf(line, sizeof(line), "%s %ux%u after %llu draws", what, width, height, DrawsMade);
+ }
+ TargetTrace.push_back(line);
+ if (TargetTrace.size() > TARGET_TRACE_LIMIT) {
+ TargetTrace.erase(TargetTrace.begin());
+ }
+}
+
+void DX11BackendClass::Set_Render_Target(ID3D11RenderTargetView * target)
+{
+ if (target == NULL) {
+ ++TargetsRestored;
+ Trace_Target("back buffer", 0, 0);
+ CurrentTarget = NULL;
+ CurrentDepth = NULL;
+ ID3D11RenderTargetView * back_buffer = Device->Get_Back_Buffer_View();
+ if (back_buffer != NULL) {
+ Device->Get_Context()->OMSetRenderTargets(1, &back_buffer,
+ Device->Get_Depth_Stencil_View());
+ Set_Viewport(0, 0, Device->Get_Width(), Device->Get_Height());
+ }
+ return;
+ }
+
+ ID3D11Resource * resource = NULL;
+ target->GetResource(&resource);
+ if (resource == NULL) {
+ return;
+ }
+
+ unsigned width = 0;
+ unsigned height = 0;
+ ID3D11Texture2D * texture = NULL;
+ if (SUCCEEDED(resource->QueryInterface(__uuidof(ID3D11Texture2D), (void **)&texture))) {
+ D3D11_TEXTURE2D_DESC description;
+ texture->GetDesc(&description);
+ width = description.Width;
+ height = description.Height;
+ texture->Release();
+ }
+ resource->Release();
+
+ if (width == 0 || height == 0) {
+ return;
+ }
+
+ ++TargetsBound;
+ Trace_Target("texture", width, height);
+ CurrentTarget = target;
+ CurrentDepth = Depth_For(width, height);
+ Device->Get_Context()->OMSetRenderTargets(1, &CurrentTarget, CurrentDepth);
+ Set_Viewport(0, 0, width, height);
+}
+
void DX11BackendClass::Set_Viewport(unsigned x, unsigned y, unsigned width, unsigned height)
{
D3D11_VIEWPORT viewport;
@@ -346,15 +648,25 @@ void DX11BackendClass::Set_Viewport(unsigned x, unsigned y, unsigned width, unsi
viewport.MinDepth = 0.0f;
viewport.MaxDepth = 1.0f;
Device->Get_Context()->RSSetViewports(1, &viewport);
+
+ ViewportWidth = (width == 0) ? 1 : width;
+ ViewportHeight = (height == 0) ? 1 : height;
}
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);
+ // Whatever the draws are landing in is what a clear clears; a pass that clears its own render
+ // target and then draws into it would otherwise clear the picture instead.
+ ID3D11RenderTargetView * target = (CurrentTarget != NULL)
+ ? CurrentTarget : Device->Get_Back_Buffer_View();
+ ID3D11DepthStencilView * depth_view = (CurrentTarget != NULL)
+ ? CurrentDepth : Device->Get_Depth_Stencil_View();
+
+ if (colour && target != NULL) {
+ Device->Get_Context()->ClearRenderTargetView(target, colour_value);
}
- if (depth && Device->Get_Depth_Stencil_View() != NULL) {
- Device->Get_Context()->ClearDepthStencilView(Device->Get_Depth_Stencil_View(),
+ if (depth && depth_view != NULL) {
+ Device->Get_Context()->ClearDepthStencilView(depth_view,
D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
}
}
@@ -415,9 +727,14 @@ bool DX11BackendClass::Build_Vertex_Description(VertexPipelineDescription & desc
}
}
+ // With a pixel shader bound the colour operations mean nothing - the shader replaces the
+ // combiners and reads whatever coordinate sets it likes - so the walk cannot stop at a
+ // disabled one. The water leaves stages one to three disabled and samples all four.
+ const bool every_stage = PixelProgram != ENGINE_SHADER_NONE;
+
description.StageCount = 0;
for (unsigned stage = 0; stage < MAXIMUM_VERTEX_STAGES; ++stage) {
- if (StageStates[stage][D3DTSS_COLOROP] == D3DTOP_DISABLE) {
+ if (!every_stage && StageStates[stage][D3DTSS_COLOROP] == D3DTOP_DISABLE) {
break;
}
description.Stages[stage].TextureCoordinateIndex = StageStates[stage][D3DTSS_TEXCOORDINDEX];
@@ -435,53 +752,102 @@ bool DX11BackendClass::Resolve(Pipeline & pipeline)
{
VertexPipelineDescription vertex_description;
CombinerDescription combiner_description;
+ const bool built_combiners = Build_Combiner_Description(combiner_description);
if (!Build_Vertex_Description(vertex_description)
- || !Build_Combiner_Description(combiner_description)) {
+ || (!built_combiners && PixelProgram == ENGINE_SHADER_NONE)) {
+ // Stage zero's colour operation is disabled, so there is no texture stage to write a
+ // program from. A transcribed pixel program does not need one: it is the combiners. There
+ // is no key yet at this point.
+ ++RefusedNoStage;
return false;
}
char format[32];
snprintf(format, sizeof(format), "|%lu", VertexFormat);
- const std::string key = VertexShader_Key(vertex_description)
- + CombinerShader_Key(combiner_description) + format;
+
+ // A transcribed program is the whole half it replaces: the fixed-function description says
+ // nothing about it and two draws with the same shader and different stage state are the same
+ // program, so its name replaces that description in the key rather than joining it. The alpha
+ // test and the fog stay in the pixel one, because they are still written into the program.
+ const std::string vertex_key = (VertexProgram != ENGINE_SHADER_NONE)
+ ? std::string(EngineShader_Name(VertexProgram))
+ : VertexShader_Key(vertex_description);
+ const std::string pixel_key = (PixelProgram != ENGINE_SHADER_NONE)
+ ? EngineShader_Name(PixelProgram)
+ + CombinerShader_Pipeline_Key(combiner_description.PixelPipeline)
+ : CombinerShader_Key(combiner_description);
+ const std::string key = vertex_key + pixel_key + format;
std::map<std::string, Pipeline>::const_iterator existing = Pipelines.find(key);
if (existing != Pipelines.end()) {
pipeline = existing->second;
+ Record_Use(key);
return true;
}
+ std::map<std::string, unsigned>::const_iterator refused = RefusedPipelines.find(key);
+ if (refused != RefusedPipelines.end()) {
+ Refuse(key, static_cast<RefusalReason>(refused->second));
+ return false;
+ }
D3DCompileFunction compiler = compiler_function();
if (compiler == NULL) {
+ Refuse(key, REFUSED_NO_PROGRAM);
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)) {
+ const bool wrote_vertex = (VertexProgram != ENGINE_SHADER_NONE)
+ ? EngineShader_Vertex_Program(VertexProgram, vertex_hlsl)
+ : VertexShader_Generate(vertex_description, VERTEX_SHADER_TARGET_D3D11, vertex_hlsl);
+ if (!wrote_vertex) {
+ Note_Refusal("the vertex half would not generate this description");
+ Refuse(key, REFUSED_NO_PROGRAM);
+ return false;
+ }
+ const bool wrote_pixel = (PixelProgram != ENGINE_SHADER_NONE)
+ ? EngineShader_Pixel_Program(PixelProgram, combiner_description.PixelPipeline, pixel_hlsl)
+ : CombinerShader_Generate(combiner_description, COMBINER_SHADER_TARGET_D3D11, pixel_hlsl);
+ if (!wrote_pixel) {
+ Note_Refusal("the pixel half would not generate this description");
+ Refuse(key, REFUSED_NO_PROGRAM);
return false;
}
+ Dump_Program(key, vertex_hlsl, pixel_hlsl);
+
D3D11_INPUT_ELEMENT_DESC elements[MAXIMUM_LAYOUT_ELEMENTS];
unsigned element_count = 0;
unsigned stride = 0;
if (!DX11Layout_From_FVF(VertexFormat, elements, element_count, stride)) {
+ Refuse(key, REFUSED_NO_LAYOUT);
return false;
}
ID3DBlob * vertex_code = NULL;
ID3DBlob * pixel_code = NULL;
+ ID3DBlob * errors = NULL;
if (FAILED(compiler(vertex_hlsl.c_str(), vertex_hlsl.size(), "ffvertex", NULL, NULL,
- ENTRY_POINT, VERTEX_PROFILE, 0, 0, &vertex_code, NULL))) {
+ ENTRY_POINT, VERTEX_PROFILE, 0, 0, &vertex_code, &errors))) {
+ Record_Compiler_Error("ffvertex", errors);
+ Refuse(key, REFUSED_NO_PROGRAM);
return false;
}
+ if (errors != NULL) {
+ errors->Release();
+ errors = NULL;
+ }
if (FAILED(compiler(pixel_hlsl.c_str(), pixel_hlsl.size(), "ffshader", NULL, NULL,
- ENTRY_POINT, PIXEL_PROFILE, 0, 0, &pixel_code, NULL))) {
+ ENTRY_POINT, PIXEL_PROFILE, 0, 0, &pixel_code, &errors))) {
+ Record_Compiler_Error("ffshader", errors);
vertex_code->Release();
+ Refuse(key, REFUSED_NO_PROGRAM);
return false;
}
+ if (errors != NULL) {
+ errors->Release();
+ }
Pipeline built;
built.VertexShader = NULL;
@@ -509,15 +875,70 @@ bool DX11BackendClass::Resolve(Pipeline & pipeline)
if (built.VertexShader != NULL) {
built.VertexShader->Release();
}
+ Note_Refusal("the device would not make the shaders or the input layout");
+ Refuse(key, REFUSED_NO_OBJECT);
return false;
}
Pipelines[key] = built;
++PipelinesBuilt;
pipeline = built;
+ Record_Use(key);
return true;
}
+void DX11BackendClass::Record_Use(const std::string & key)
+{
+ PipelineUse & use = PipelineUses[key];
+ if (use.Draws++ != 0) {
+ return;
+ }
+
+ use.TextureWidth = 0;
+ use.TextureHeight = 0;
+ if (Textures[0] == NULL) {
+ return;
+ }
+
+ ID3D11Resource * resource = NULL;
+ Textures[0]->GetResource(&resource);
+ if (resource == NULL) {
+ return;
+ }
+
+ ID3D11Texture2D * texture = NULL;
+ if (SUCCEEDED(resource->QueryInterface(__uuidof(ID3D11Texture2D), (void **)&texture))) {
+ D3D11_TEXTURE2D_DESC description;
+ texture->GetDesc(&description);
+ use.TextureWidth = description.Width;
+ use.TextureHeight = description.Height;
+ texture->Release();
+ }
+ resource->Release();
+}
+
+unsigned DX11BackendClass::Pipeline_Report_Count() const
+{
+ return (unsigned)PipelineUses.size();
+}
+
+const char * DX11BackendClass::Pipeline_Report(unsigned index)
+{
+ std::map<std::string, PipelineUse>::const_iterator entry = PipelineUses.begin();
+ for (unsigned step = 0; step < index && entry != PipelineUses.end(); ++step) {
+ ++entry;
+ }
+ if (entry == PipelineUses.end()) {
+ return "";
+ }
+
+ char tail[96];
+ snprintf(tail, sizeof(tail), " -> %llu draws, stage 0 texture %ux%u",
+ entry->second.Draws, entry->second.TextureWidth, entry->second.TextureHeight);
+ ReportLine = entry->first + tail;
+ return ReportLine.c_str();
+}
+
void DX11BackendClass::Upload_Constants()
{
ID3D11DeviceContext * context = Device->Get_Context();
@@ -530,8 +951,10 @@ void DX11BackendClass::Upload_Constants()
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);
+ vertex_block.ViewportInverse[0] = 1.0f / static_cast<float>(ViewportWidth);
+ vertex_block.ViewportInverse[1] = 1.0f / static_cast<float>(ViewportHeight);
+
+ memcpy(vertex_block.TextureMatrix, TextureTransforms, sizeof(vertex_block.TextureMatrix));
memcpy(vertex_block.MaterialAmbient, MaterialAmbient, sizeof(MaterialAmbient));
memcpy(vertex_block.MaterialDiffuse, MaterialDiffuse, sizeof(MaterialDiffuse));
@@ -576,6 +999,14 @@ void DX11BackendClass::Upload_Constants()
context->Unmap(VertexConstantBuffer, 0);
}
+ // A transcribed program reads the engine's own register bank instead of the block above, so
+ // that bank goes up only on the draws that take one.
+ if (VertexProgram != ENGINE_SHADER_NONE
+ && SUCCEEDED(context->Map(EngineConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped))) {
+ memcpy(mapped.pData, EngineConstants, sizeof(EngineConstants));
+ context->Unmap(EngineConstantBuffer, 0);
+ }
+
PixelConstantBlock pixel_block;
memset(&pixel_block, 0, sizeof(pixel_block));
RenderStates.Get_Texture_Factor(pixel_block.TextureFactor);
@@ -609,6 +1040,10 @@ ID3D11BlendState * DX11BackendClass::Blend_State()
ID3D11BlendState * state = NULL;
if (FAILED(Device->Get_Device()->CreateBlendState(&description, &state))) {
+ // A null blend state is not a refused draw: the draw goes ahead with the default state,
+ // which blends nothing, so a pass that was multiplying itself into the frame buffer paints
+ // over it instead. That is invisible in every count, hence the line.
+ Note_Refusal("the device refused a blend state");
return NULL;
}
BlendStates[key] = state;
@@ -629,6 +1064,7 @@ ID3D11DepthStencilState * DX11BackendClass::Depth_Stencil_State()
ID3D11DepthStencilState * state = NULL;
if (FAILED(Device->Get_Device()->CreateDepthStencilState(&description, &state))) {
+ Note_Refusal("the device refused a depth stencil state");
return NULL;
}
DepthStencilStates[key] = state;
@@ -649,6 +1085,7 @@ ID3D11RasterizerState * DX11BackendClass::Rasterizer_State()
ID3D11RasterizerState * state = NULL;
if (FAILED(Device->Get_Device()->CreateRasterizerState(&description, &state))) {
+ Note_Refusal("the device refused a rasterizer state");
return NULL;
}
RasterizerStates[key] = state;
@@ -668,12 +1105,18 @@ ID3D11SamplerState * DX11BackendClass::Sampler_State(unsigned sampler)
ID3D11SamplerState * state = NULL;
if (FAILED(Device->Get_Device()->CreateSamplerState(&description, &state))) {
+ Note_Refusal("the device refused a sampler state");
return NULL;
}
SamplerStates[key] = state;
return state;
}
+ID3D11Buffer * DX11BackendClass::Vertex_Constants() const
+{
+ return (VertexProgram != ENGINE_SHADER_NONE) ? EngineConstantBuffer : VertexConstantBuffer;
+}
+
void DX11BackendClass::Bind_State_Objects()
{
ID3D11DeviceContext * context = Device->Get_Context();
@@ -692,9 +1135,39 @@ void DX11BackendClass::Bind_State_Objects()
bool DX11BackendClass::Draw_Indexed_Triangles(unsigned index_count, unsigned start_index,
unsigned base_vertex)
+{
+ return Draw_Indexed(index_count, start_index, base_vertex,
+ D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
+}
+
+bool DX11BackendClass::Draw_Indexed_Strip(unsigned index_count, unsigned start_index,
+ unsigned base_vertex)
+{
+ return Draw_Indexed(index_count, start_index, base_vertex,
+ D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
+}
+
+bool DX11BackendClass::Draw_Indexed(unsigned index_count, unsigned start_index,
+ unsigned base_vertex, D3D11_PRIMITIVE_TOPOLOGY topology)
{
Pipeline pipeline;
- if (StreamBuffer == NULL || IndexBuffer == NULL || !Resolve(pipeline)) {
+ if (StreamBuffer == NULL || IndexBuffer == NULL) {
+ ++RefusedNoBuffer;
+ ++DrawsRefused;
+ return false;
+ }
+ if (ForeignPixelShader || ForeignVertexShader) {
+ Note_Foreign_Refusal();
+ ++RefusedForeignShader;
+ ++DrawsRefused;
+ return false;
+ }
+ if (Any_Missing_Texture()) {
+ ++RefusedNoTexture;
+ ++DrawsRefused;
+ return false;
+ }
+ if (!Resolve(pipeline)) {
++DrawsRefused;
return false;
}
@@ -708,21 +1181,42 @@ bool DX11BackendClass::Draw_Indexed_Triangles(unsigned index_count, unsigned sta
context->IASetInputLayout(pipeline.Layout);
context->IASetVertexBuffers(0, 1, &StreamBuffer, &stride, &offset);
context->IASetIndexBuffer(IndexBuffer, IndexFormat, 0);
- context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
+ context->IASetPrimitiveTopology(topology);
context->VSSetShader(pipeline.VertexShader, NULL, 0);
- context->VSSetConstantBuffers(0, 1, &VertexConstantBuffer);
+ ID3D11Buffer * vertex_constants = Vertex_Constants();
+ context->VSSetConstantBuffers(0, 1, &vertex_constants);
context->PSSetShader(pipeline.PixelShader, NULL, 0);
context->PSSetConstantBuffers(0, 1, &PixelConstantBuffer);
context->DrawIndexed(index_count, start_index, base_vertex);
++DrawsMade;
+ if (CurrentTarget != NULL) {
+ ++DrawsIntoTargets;
+ MaskWhileTargeted |= RenderStates.Get_Render_State(D3DRS_COLORWRITEENABLE);
+ }
return true;
}
bool DX11BackendClass::Draw_Triangles(unsigned vertex_count, unsigned start_vertex)
{
Pipeline pipeline;
- if (StreamBuffer == NULL || !Resolve(pipeline)) {
+ if (StreamBuffer == NULL) {
+ ++RefusedNoBuffer;
+ ++DrawsRefused;
+ return false;
+ }
+ if (ForeignPixelShader || ForeignVertexShader) {
+ Note_Foreign_Refusal();
+ ++RefusedForeignShader;
+ ++DrawsRefused;
+ return false;
+ }
+ if (Any_Missing_Texture()) {
+ ++RefusedNoTexture;
+ ++DrawsRefused;
+ return false;
+ }
+ if (!Resolve(pipeline)) {
++DrawsRefused;
return false;
}
@@ -737,15 +1231,278 @@ bool DX11BackendClass::Draw_Triangles(unsigned vertex_count, unsigned start_vert
context->IASetVertexBuffers(0, 1, &StreamBuffer, &stride, &offset);
context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
context->VSSetShader(pipeline.VertexShader, NULL, 0);
- context->VSSetConstantBuffers(0, 1, &VertexConstantBuffer);
+ ID3D11Buffer * vertex_constants = Vertex_Constants();
+ context->VSSetConstantBuffers(0, 1, &vertex_constants);
context->PSSetShader(pipeline.PixelShader, NULL, 0);
context->PSSetConstantBuffers(0, 1, &PixelConstantBuffer);
context->Draw(vertex_count, start_vertex);
++DrawsMade;
+ if (CurrentTarget != NULL) {
+ ++DrawsIntoTargets;
+ MaskWhileTargeted |= RenderStates.Get_Render_State(D3DRS_COLORWRITEENABLE);
+ }
return true;
}
+// What is actually in the texture bound at a stage, read back through a staging copy. A draw that
+// samples a texture nobody filled looks exactly like a draw that never happened, and no count tells
+// them apart. This costs a full stall and is only ever called once.
+std::string DX11BackendClass::Texture_Average(unsigned stage)
+{
+ if (stage >= DX11_BACKEND_TEXTURE_STAGES || Textures[stage] == NULL) {
+ return "no texture";
+ }
+
+ ID3D11Resource * resource = NULL;
+ Textures[stage]->GetResource(&resource);
+ if (resource == NULL) {
+ return "no resource";
+ }
+
+ ID3D11Texture2D * texture = NULL;
+ if (FAILED(resource->QueryInterface(__uuidof(ID3D11Texture2D), (void **)&texture))) {
+ resource->Release();
+ return "not a 2D texture";
+ }
+
+ D3D11_TEXTURE2D_DESC description;
+ texture->GetDesc(&description);
+ description.Usage = D3D11_USAGE_STAGING;
+ description.BindFlags = 0;
+ description.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
+ description.MiscFlags = 0;
+ description.MipLevels = 1;
+
+ ID3D11Texture2D * staging = NULL;
+ if (FAILED(Device->Get_Device()->CreateTexture2D(&description, NULL, &staging))) {
+ texture->Release();
+ resource->Release();
+ return "no staging copy";
+ }
+
+ Device->Get_Context()->CopySubresourceRegion(staging, 0, 0, 0, 0, resource, 0, NULL);
+
+ std::string answer = "unreadable";
+ D3D11_MAPPED_SUBRESOURCE mapped;
+ if (SUCCEEDED(Device->Get_Context()->Map(staging, 0, D3D11_MAP_READ, 0, &mapped))) {
+ double blue = 0.0, green = 0.0, red = 0.0, alpha = 0.0;
+ const unsigned pixels = description.Width * description.Height;
+ for (unsigned row = 0; row < description.Height; ++row) {
+ const unsigned char * line = (const unsigned char *)mapped.pData + row * mapped.RowPitch;
+ for (unsigned column = 0; column < description.Width; ++column) {
+ blue += line[column * 4 + 0];
+ green += line[column * 4 + 1];
+ red += line[column * 4 + 2];
+ alpha += line[column * 4 + 3];
+ }
+ }
+ Device->Get_Context()->Unmap(staging, 0);
+
+ char line[128];
+ snprintf(line, sizeof(line), "%ux%u average rgba %.0f,%.0f,%.0f,%.0f",
+ description.Width, description.Height, red / pixels, green / pixels, blue / pixels,
+ alpha / pixels);
+ answer = line;
+ }
+
+ staging->Release();
+ texture->Release();
+ resource->Release();
+ return answer;
+}
+
+// The screen-space quads the engine draws with DrawPrimitiveUP - the filter that puts the rendered
+// scene back on the screen, the smudges, the shadow volume's darkening pass - come as four
+// vertices in a strip and no buffer at all. D3D11 has no equivalent, so they are copied into a
+// dynamic buffer the backend owns and drawn as a list, which is also what turns the strip's
+// alternating winding into triangles.
+bool DX11BackendClass::Draw_User_Strip(const void * vertices, unsigned primitive_count,
+ unsigned stride)
+{
+ if (vertices == NULL || primitive_count == 0 || stride == 0) {
+ return false;
+ }
+
+ Pipeline pipeline;
+ if (ForeignPixelShader || ForeignVertexShader) {
+ Note_Foreign_Refusal();
+ ++RefusedForeignShader;
+ ++DrawsRefused;
+ return false;
+ }
+ if (Any_Missing_Texture()) {
+ ++RefusedNoTexture;
+ ++DrawsRefused;
+ return false;
+ }
+
+ // Not the first quad of the run: that one is the loading screen's, drawn before anything has
+ // been rendered into the texture it samples, and reading it back proves nothing.
+ const unsigned long long DRAWS_BEFORE_TRACING = 50000;
+ const DWORD SCREEN_QUAD_FVF = D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX1;
+ if (!TracedUserStrip && DrawsMade > DRAWS_BEFORE_TRACING && Textures[0] != NULL
+ && VertexFormat == SCREEN_QUAD_FVF) {
+ TracedUserStrip = true;
+ const float * corner = static_cast<const float *>(vertices);
+ char line[192];
+ snprintf(line, sizeof(line),
+ "quad %.0f,%.0f fvf %lu viewport %ux%u, colour write %lu, into targets %lu, stage 0 %s",
+ corner[0], corner[1], VertexFormat, ViewportWidth, ViewportHeight,
+ (unsigned long)RenderStates.Get_Render_State(D3DRS_COLORWRITEENABLE),
+ (unsigned long)MaskWhileTargeted, Texture_Average(0).c_str());
+ Diagnostic = line;
+ }
+
+ const unsigned list_vertex_count = primitive_count * 3;
+ const unsigned byte_count = list_vertex_count * stride;
+ if (!Reserve_User_Buffer(byte_count)) {
+ ++RefusedNoBuffer;
+ ++DrawsRefused;
+ return false;
+ }
+
+ ID3D11DeviceContext * context = Device->Get_Context();
+ D3D11_MAPPED_SUBRESOURCE mapped;
+ if (FAILED(context->Map(UserBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped))) {
+ ++RefusedNoBuffer;
+ ++DrawsRefused;
+ return false;
+ }
+
+ const unsigned char * source = static_cast<const unsigned char *>(vertices);
+ unsigned char * destination = static_cast<unsigned char *>(mapped.pData);
+ for (unsigned primitive = 0; primitive < primitive_count; ++primitive) {
+ // A strip alternates winding: the odd triangle takes its first two vertices the other way
+ // round, which is what keeps every triangle facing the same way.
+ const unsigned order[3] = {
+ (primitive % 2 == 0) ? primitive : primitive + 1,
+ (primitive % 2 == 0) ? primitive + 1 : primitive,
+ primitive + 2 };
+ for (unsigned corner = 0; corner < 3; ++corner) {
+ memcpy(destination + (primitive * 3 + corner) * stride,
+ source + order[corner] * stride, stride);
+ }
+ }
+ context->Unmap(UserBuffer, 0);
+
+ // The pipeline is resolved after the copy so a refusal does not leave a mapped buffer behind.
+ if (!Resolve(pipeline)) {
+ ++DrawsRefused;
+ return false;
+ }
+
+ Upload_Constants();
+ Bind_State_Objects();
+
+ const UINT vertex_stride = stride;
+ const UINT offset = 0;
+ context->IASetInputLayout(pipeline.Layout);
+ context->IASetVertexBuffers(0, 1, &UserBuffer, &vertex_stride, &offset);
+ context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
+ context->VSSetShader(pipeline.VertexShader, NULL, 0);
+ ID3D11Buffer * vertex_constants = Vertex_Constants();
+ context->VSSetConstantBuffers(0, 1, &vertex_constants);
+ context->PSSetShader(pipeline.PixelShader, NULL, 0);
+ context->PSSetConstantBuffers(0, 1, &PixelConstantBuffer);
+ context->Draw(list_vertex_count, 0);
+
+ ++DrawsMade;
+ if (CurrentTarget != NULL) {
+ ++DrawsIntoTargets;
+ MaskWhileTargeted |= RenderStates.Get_Render_State(D3DRS_COLORWRITEENABLE);
+ }
+ return true;
+}
+
+bool DX11BackendClass::Reserve_User_Buffer(unsigned byte_count)
+{
+ if (UserBuffer != NULL && UserBufferBytes >= byte_count) {
+ return true;
+ }
+
+ if (UserBuffer != NULL) {
+ UserBuffer->Release();
+ UserBuffer = NULL;
+ UserBufferBytes = 0;
+ }
+
+ if (!DX11Resource_Create_Vertex_Buffer(Device->Get_Device(), byte_count, D3DPOOL_DEFAULT,
+ D3DUSAGE_DYNAMIC, NULL, &UserBuffer)) {
+ Note_Refusal("the device refused the buffer the screen quads are copied into");
+ return false;
+ }
+ UserBufferBytes = byte_count;
+ return true;
+}
+
+// The first thing the compiler complained about, kept whole. A generated program that will not
+// compile is a defect in the generator, and the message names the line of it.
+void DX11BackendClass::Record_Compiler_Error(const char * which, ID3DBlob * errors)
+{
+ if (!CompilerError.empty()) {
+ return;
+ }
+ CompilerError = which;
+ CompilerError += ": ";
+ if (errors != NULL) {
+ CompilerError.append((const char *)errors->GetBufferPointer(), errors->GetBufferSize());
+ errors->Release();
+ }
+ else {
+ CompilerError += "no message";
+ }
+}
+
+unsigned DX11BackendClass::Refused_Description_Count() const
+{
+ return (unsigned)RefusedPipelines.size();
+}
+
+const char * DX11BackendClass::Refused_Description(unsigned index) const
+{
+ std::map<std::string, unsigned>::const_iterator entry = RefusedPipelines.begin();
+ for (unsigned step = 0; step < index && entry != RefusedPipelines.end(); ++step) {
+ ++entry;
+ }
+ return entry == RefusedPipelines.end() ? "" : entry->first.c_str();
+}
+
+// The first refusal that was not the compiler's doing, in the same field the compiler's message
+// uses: a generator that declines a description and a device that declines the program it produced
+// are different defects and the count alone tells them apart from nothing.
+void DX11BackendClass::Note_Refusal(const char * reason)
+{
+ if (CompilerError.empty()) {
+ CompilerError = reason;
+ }
+}
+
+void DX11BackendClass::Refuse(const std::string & key, RefusalReason reason)
+{
+ RefusedPipelines[key] = reason;
+ switch (reason) {
+ case REFUSED_NO_STAGE: ++RefusedNoStage; break;
+ case REFUSED_NO_LAYOUT: ++RefusedNoLayout; break;
+ case REFUSED_NO_PROGRAM: ++RefusedNoProgram; break;
+ case REFUSED_NO_OBJECT: ++RefusedNoObject; break;
+ }
+}
+
+void DX11BackendClass::Refusals(unsigned long long & no_buffer, unsigned long long & no_stage,
+ unsigned long long & no_layout, unsigned long long & no_program,
+ unsigned long long & no_object, unsigned long long & foreign_shader,
+ unsigned long long & no_texture) const
+{
+ no_buffer = RefusedNoBuffer;
+ no_stage = RefusedNoStage;
+ no_layout = RefusedNoLayout;
+ no_program = RefusedNoProgram;
+ no_object = RefusedNoObject;
+ foreign_shader = RefusedForeignShader;
+ no_texture = RefusedNoTexture;
+}
+
void DX11BackendClass::Statistics(unsigned & pipelines_built, unsigned long long & draws_made,
unsigned long long & draws_refused) const
{
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h
index fa1309df8..281daab6e 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h
@@ -43,16 +43,19 @@
#include "dx11device.h"
#include "dx11state.h"
+#include "engineshader.h"
#include "ffshader.h"
#include "ffvertex.h"
#include <d3d9.h>
#include <map>
#include <string>
+#include <vector>
-// 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;
+// Two everywhere except the water, which binds four: the river texture, the sparkles, the noise
+// and the shroud. This is what ffshader and ffvertex generate for, and a fifth is a draw this
+// refuses rather than draws wrongly.
+const unsigned DX11_BACKEND_TEXTURE_STAGES = 4;
// 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.
@@ -74,7 +77,24 @@ public:
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);
+
+ // The engine bound a texture at this stage that has no D3D11 copy - a render target it drew
+ // into, most often. Sampling white there paints a full screen quad over the frame, so a draw
+ // that reads one is refused instead.
+ void Set_Texture_Missing(unsigned stage, bool missing);
void Set_Vertex_Format(DWORD fvf);
+
+ // One of the engine's own D3D9 shaders is bound. Most of the shipped .vso and .pso files have
+ // no D3D11 counterpart, so a draw made while one is bound is refused and counted apart; the
+ // ones engineshader transcribes are named instead and the draw takes that program. The file
+ // name comes with it because a refusal count says how much is missing and only the name says
+ // which shader has to be written next.
+ void Set_Pixel_Program(EngineShaderProgram program, bool bound, const char * file_name);
+ void Set_Vertex_Program(EngineShaderProgram program, bool bound, const char * file_name);
+
+ // The engine's own float4 shader constant bank, as it sets it. The transcribed programs index
+ // it by the same register number the SetVertexShaderConstantF call used.
+ void Set_Vertex_Program_Constant(unsigned first_register, const float * values, unsigned count);
void Set_Stream_Source(ID3D11Buffer * buffer, unsigned stride, unsigned offset);
void Set_Indices(ID3D11Buffer * buffer, DXGI_FORMAT format);
@@ -92,21 +112,83 @@ public:
const float spot[4]);
void Disable_Light(unsigned index);
+ // Write every program this builds to a file in this directory, named by the state it was built
+ // from. A generated program that draws the wrong thing is unreadable from the outside: the
+ // description is a key, and the key is not the code.
+ void Set_Dump_Directory(const char * directory);
+
+ // Binds the swap chain's back buffer and depth buffer and sets the viewport over the whole of
+ // it. D3D11 keeps no default target: without this every draw is complete, legal, and lands
+ // nowhere. Called at the start of each scene rather than once, because a resize replaces both
+ // views and nothing tells the backend when that happens.
+ void Begin_Scene();
+
void Set_Viewport(unsigned x, unsigned y, unsigned width, unsigned height);
void Clear(bool colour, bool depth, const float colour_value[4]);
+ // Draw into a texture instead of into the back buffer. A null target goes back to the back
+ // buffer. D3D11 wants the depth buffer to match the target's size, so one is made for each
+ // size a target comes in and kept; the engine uses two or three of them in a match.
+ void Set_Render_Target(ID3D11RenderTargetView * target);
+
// 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);
+ // The same indexed draw over a triangle strip, which is how the water lays out both of its
+ // grids. A strip drawn as a list reads three indices where the strip meant one triangle and
+ // paints a third of the surface in torn triangles, so the topology cannot be assumed.
+ bool Draw_Indexed_Strip(unsigned index_count, unsigned start_index, unsigned base_vertex);
+
+ // A triangle strip handed over as vertices rather than as a buffer, which is how the engine
+ // draws every screen-space quad it has.
+ bool Draw_User_Strip(const void * vertices, unsigned primitive_count, unsigned stride);
+
// 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;
+ // Why the refusals happened, in the order Draw checks them: no buffer bound, no texture stage
+ // enabled, a vertex format with no input layout, and a program the generator or the compiler
+ // would not produce. "Half the draws are refused" is not a finding; which half is.
+ void Refusals(unsigned long long & no_buffer, unsigned long long & no_stage,
+ unsigned long long & no_layout, unsigned long long & no_program,
+ unsigned long long & no_object, unsigned long long & foreign_shader,
+ unsigned long long & no_texture) const;
+
+ // The distinct states that were refused, as the keys they were cached under, and whatever the
+ // shader compiler said about the first one it rejected. A count says how much is missing; the
+ // key says what, and it is the only thing that does.
+ unsigned Refused_Description_Count() const;
+ const char * Refused_Description(unsigned index) const;
+
+ // What each pipeline that did draw actually painted with: how many draws took it, and the size
+ // of the texture bound at stage zero the first time one did. A count of draws made says the
+ // picture was drawn; it does not say what was drawn into it, and a ground that comes out white
+ // looks exactly like a ground that came out right from every other number here.
+ unsigned Pipeline_Report_Count() const;
+ const char * Pipeline_Report(unsigned index);
+
+ // The shipped shaders the refused draws had bound, and how many draws each cost. This is the
+ // list of what engineshader still has to transcribe, in the order worth doing it.
+ unsigned Foreign_Report_Count() const;
+ const char * Foreign_Report(unsigned index);
+
+ // How many times the draws were sent into a texture instead of the back buffer, and how many
+ // landed there. A scene that comes back black usually means a target was set and not unset.
+ void Target_Statistics(unsigned long long & bound, unsigned long long & restored,
+ unsigned long long & draws) const
+ { bound = TargetsBound; restored = TargetsRestored; draws = DrawsIntoTargets; }
+ const char * Diagnostic_Line() const { return Diagnostic.c_str(); }
+ unsigned Target_Trace_Count() const { return (unsigned)TargetTrace.size(); }
+ const char * Target_Trace(unsigned index) const
+ { return (index < TargetTrace.size()) ? TargetTrace[index].c_str() : ""; }
+ const char * First_Compiler_Error() const { return CompilerError.c_str(); }
+
private:
DX11BackendClass(const DX11BackendClass &);
DX11BackendClass & operator=(const DX11BackendClass &);
@@ -122,6 +204,14 @@ private:
bool Build_Vertex_Description(VertexPipelineDescription & description) const;
bool Build_Combiner_Description(CombinerDescription & description) const;
void Upload_Constants();
+
+ // Both indexed draws land here; only the topology differs.
+ bool Draw_Indexed(unsigned index_count, unsigned start_index, unsigned base_vertex,
+ D3D11_PRIMITIVE_TOPOLOGY topology);
+
+ // Which bank the vertex half is reading: the engine's own registers while a transcribed
+ // program is bound, the generated block otherwise.
+ ID3D11Buffer * Vertex_Constants() const;
void Bind_State_Objects();
void Release_Cached();
@@ -147,6 +237,15 @@ private:
float World[16];
float View[16];
float Projection[16];
+ // The per-stage texture transforms. Two of them, because ffvertex writes two and the game sets
+ // no more than two stages in any state the probe counted. These are what turn a camera space
+ // position into the cloud shadow's coordinates, and with an identity in their place the whole
+ // terrain samples one texel of it.
+ float TextureTransforms[DX11_BACKEND_TEXTURE_STAGES][16];
+
+ // What the viewport is, so a pre-transformed vertex can be put back into clip space.
+ unsigned ViewportWidth;
+ unsigned ViewportHeight;
float MaterialAmbient[4];
float MaterialDiffuse[4];
@@ -170,7 +269,57 @@ private:
ID3D11Buffer * VertexConstantBuffer;
ID3D11Buffer * PixelConstantBuffer;
+ // The engine's own constant bank and the buffer it is uploaded through. It replaces the
+ // generated vertex block at slot zero while a transcribed program is bound, because that
+ // program reads registers and not the fixed-function fields.
+ ID3D11Buffer * EngineConstantBuffer;
+ float EngineConstants[ENGINE_SHADER_CONSTANTS][4];
+ EngineShaderProgram VertexProgram;
+ EngineShaderProgram PixelProgram;
+
+ // Where the screen quads are copied to, grown to fit and never shrunk.
+ ID3D11Buffer * UserBuffer;
+ unsigned UserBufferBytes;
+ bool Reserve_User_Buffer(unsigned byte_count);
+
std::map<std::string, Pipeline> Pipelines;
+ // The state combinations that could not be built. A refusal costs two HLSL generations and two
+ // D3DCompile calls, and the states that produce one are produced again on the next frame by the
+ // same object: a scene with a hundred and thirty of them a frame spent a second a frame
+ // compiling shaders it had already failed to compile.
+ std::map<std::string, unsigned> RefusedPipelines;
+
+ // What a pipeline drew with, kept beside the pipeline itself rather than in it, because a draw
+ // holds a copy of the pipeline and would be updating the copy.
+ struct PipelineUse
+ {
+ unsigned long long Draws;
+ unsigned TextureWidth;
+ unsigned TextureHeight;
+ };
+ std::map<std::string, PipelineUse> PipelineUses;
+ std::string ReportLine;
+ void Record_Use(const std::string & key);
+
+ // Where the draws are landing. Null means the device's own back buffer and depth buffer.
+ // The first few target changes, in order, with the draw count at each one. Which target is
+ // bound when the scene is drawn is the whole question and no total answers it.
+ static const unsigned TARGET_TRACE_LIMIT = 24;
+ std::vector<std::string> TargetTrace;
+ void Trace_Target(const char * what, unsigned width, unsigned height);
+ bool TracedUserStrip;
+ DWORD MaskWhileTargeted;
+ std::string Diagnostic;
+ std::string Texture_Average(unsigned stage);
+
+ unsigned long long TargetsBound;
+ unsigned long long TargetsRestored;
+ unsigned long long DrawsIntoTargets;
+ ID3D11RenderTargetView * CurrentTarget;
+ ID3D11DepthStencilView * CurrentDepth;
+ std::map<unsigned long long, ID3D11DepthStencilView *> TargetDepths;
+ ID3D11DepthStencilView * Depth_For(unsigned width, unsigned height);
+
std::map<std::string, ID3D11BlendState *> BlendStates;
std::map<std::string, ID3D11DepthStencilState *> DepthStencilStates;
std::map<std::string, ID3D11RasterizerState *> RasterizerStates;
@@ -179,6 +328,38 @@ private:
unsigned PipelinesBuilt;
unsigned long long DrawsMade;
unsigned long long DrawsRefused;
+ enum RefusalReason { REFUSED_NO_STAGE, REFUSED_NO_LAYOUT, REFUSED_NO_PROGRAM,
+ REFUSED_NO_OBJECT };
+
+ void Refuse(const std::string & key, RefusalReason reason);
+ void Record_Compiler_Error(const char * which, ID3DBlob * errors);
+ void Note_Refusal(const char * reason);
+ bool Any_Missing_Texture() const;
+ void Dump_Program(const std::string & key, const std::string & vertex_hlsl,
+ const std::string & pixel_hlsl);
+
+ std::string CompilerError;
+ std::string DumpDirectory;
+
+ unsigned long long RefusedNoBuffer;
+ unsigned long long RefusedNoStage;
+ unsigned long long RefusedNoLayout;
+ unsigned long long RefusedNoProgram;
+ unsigned long long RefusedNoObject;
+ unsigned long long RefusedForeignShader;
+ unsigned long long RefusedNoTexture;
+
+ bool MissingTexture[DX11_BACKEND_TEXTURE_STAGES];
+ bool ForeignPixelShader;
+ bool ForeignVertexShader;
+ std::string ForeignPixelName;
+ std::string ForeignVertexName;
+
+ // Which shipped shader the refusals are on, counted by file name. Nothing else says it: the
+ // refusal happens before there is a pipeline key, so the state that would describe the draw is
+ // never built.
+ std::map<std::string, unsigned long long> ForeignRefusals;
+ void Note_Foreign_Refusal();
};
#endif // DX11BACKEND_H
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp
index 3a12475e2..c9c907ce9 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp
@@ -18,13 +18,40 @@
#include "dx11runtime.h"
+#include <map>
+#include <string>
+
#include "dx11backend.h"
#include "dx11device.h"
+#include "dx11texture.h"
+#include "dx11twin.h"
static bool Requested = false;
+static bool PresentRequested = false;
static bool Active = false;
static DX11DeviceClass Device;
static DX11BackendClass Backend;
+static unsigned TwinBuffers = 0;
+static unsigned long long TwinBytes = 0;
+static std::string DumpDirectory;
+
+// Which shipped shader each created Direct3D 9 shader came from. Registered at load, read at every
+// bind. It outlives the shaders themselves, which cost the map an entry each and nothing else: the
+// engine loads ten of them once and releases them when the game ends.
+struct EngineShaderRecord
+{
+ EngineShaderProgram Program;
+ std::string FileName;
+};
+static std::map<const void *, EngineShaderRecord> EngineShaders;
+
+static const EngineShaderRecord & engine_shader_record(const void * shader)
+{
+ static const EngineShaderRecord UNKNOWN = { ENGINE_SHADER_NONE, "an unregistered shader" };
+
+ std::map<const void *, EngineShaderRecord>::const_iterator entry = EngineShaders.find(shader);
+ return (entry != EngineShaders.end()) ? entry->second : UNKNOWN;
+}
void Direct3D11_Enable(bool enabled)
{
@@ -50,6 +77,7 @@ bool Direct3D11_Create(HWND window, unsigned width, unsigned height)
return false;
}
+ Backend.Set_Dump_Directory(DumpDirectory.c_str());
Active = true;
return true;
}
@@ -131,6 +159,357 @@ void Direct3D11_Mirror_Light_Disabled(unsigned index)
}
}
+static DX11BufferTwinClass * count_twin(DX11BufferTwinClass * twin, unsigned byte_count)
+{
+ if (twin != NULL) {
+ TwinBuffers++;
+ TwinBytes += byte_count;
+ }
+ return twin;
+}
+
+DX11BufferTwinClass * Direct3D11_Twin_Vertex_Buffer(unsigned byte_count, bool dynamic)
+{
+ if (!Active) {
+ return NULL;
+ }
+ return count_twin(
+ DX11Twin_Create_Vertex_Buffer(Device.Get_Device(), Device.Get_Context(), byte_count,
+ dynamic),
+ byte_count);
+}
+
+DX11BufferTwinClass * Direct3D11_Twin_Index_Buffer(unsigned byte_count, bool dynamic)
+{
+ if (!Active) {
+ return NULL;
+ }
+ return count_twin(
+ DX11Twin_Create_Index_Buffer(Device.Get_Device(), Device.Get_Context(), byte_count,
+ dynamic),
+ byte_count);
+}
+
+void Direct3D11_Mirror_Texture(unsigned stage, struct IDirect3DBaseTexture9 * texture)
+{
+ if (!Active) {
+ return;
+ }
+ ID3D11ShaderResourceView * view = texture == NULL
+ ? NULL
+ : DX11Texture_Mirror(Device.Get_Device(), Device.Get_Context(), texture);
+ Backend.Set_Texture(stage, view);
+ Backend.Set_Texture_Missing(stage, texture != NULL && view == NULL);
+}
+
+void Direct3D11_Mirror_Render_Target(struct IDirect3DSurface9 * surface)
+{
+ if (!Active) {
+ return;
+ }
+ Backend.Set_Render_Target(DX11Texture_Target(Device.Get_Device(), Device.Get_Context(),
+ surface));
+}
+
+void Direct3D11_Mirror_Surface_Copy(struct IDirect3DSurface9 * destination,
+ struct IDirect3DSurface9 * source, const struct tagRECT * source_rectangle,
+ const struct tagPOINT * destination_point)
+{
+ if (!Active) {
+ return;
+ }
+ DX11Texture_Update(Device.Get_Device(), Device.Get_Context(), destination, source,
+ source_rectangle, destination_point);
+}
+
+void Direct3D11_Texture_Statistics(unsigned & textures_made, unsigned & textures_reused,
+ unsigned & textures_refused)
+{
+ DX11Texture_Statistics(textures_made, textures_reused, textures_refused);
+}
+
+const char * Direct3D11_Texture_First_Refusal()
+{
+ return DX11Texture_First_Refusal();
+}
+
+unsigned Direct3D11_Texture_Note_Count()
+{
+ return DX11Texture_Note_Count();
+}
+
+const char * Direct3D11_Texture_Note(unsigned index)
+{
+ return DX11Texture_Note(index);
+}
+
+void Direct3D11_Dump_Programs_To(const char * directory)
+{
+ DumpDirectory = directory == NULL ? "" : directory;
+ if (Active) {
+ Backend.Set_Dump_Directory(DumpDirectory.c_str());
+ }
+}
+
+void Direct3D11_Present_Enable(bool enabled)
+{
+ PresentRequested = enabled;
+}
+
+bool Direct3D11_Present_Is_Enabled()
+{
+ return PresentRequested && Active;
+}
+
+void Direct3D11_Begin_Scene()
+{
+ if (Active) {
+ Backend.Begin_Scene();
+ }
+}
+
+void Direct3D11_Mirror_Clear(bool colour, bool depth, float red, float green, float blue,
+ float alpha)
+{
+ if (Active) {
+ const float value[4] = { red, green, blue, alpha };
+ Backend.Clear(colour, depth, value);
+ }
+}
+
+unsigned char * Direct3D11_Capture_Back_Buffer(unsigned & width, unsigned & height,
+ unsigned & pitch)
+{
+ width = 0;
+ height = 0;
+ pitch = 0;
+ if (!Active || Device.Get_Back_Buffer_View() == NULL) {
+ return NULL;
+ }
+
+ ID3D11Resource * back_buffer = NULL;
+ Device.Get_Back_Buffer_View()->GetResource(&back_buffer);
+
+ D3D11_TEXTURE2D_DESC description;
+ ((ID3D11Texture2D *)back_buffer)->GetDesc(&description);
+ description.Usage = D3D11_USAGE_STAGING;
+ description.BindFlags = 0;
+ description.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
+ description.MiscFlags = 0;
+ // A multisampled back buffer cannot be copied into a single-sample staging texture, and this
+ // swap chain never asks for one, so the copy below is the whole of it.
+ description.SampleDesc.Count = 1;
+ description.SampleDesc.Quality = 0;
+
+ ID3D11Texture2D * staging = NULL;
+ if (FAILED(Device.Get_Device()->CreateTexture2D(&description, NULL, &staging))) {
+ back_buffer->Release();
+ return NULL;
+ }
+
+ Device.Get_Context()->CopyResource(staging, back_buffer);
+
+ D3D11_MAPPED_SUBRESOURCE mapped;
+ unsigned char * pixels = NULL;
+ if (SUCCEEDED(Device.Get_Context()->Map(staging, 0, D3D11_MAP_READ, 0, &mapped))) {
+ width = description.Width;
+ height = description.Height;
+ pitch = description.Width * 4;
+ pixels = new unsigned char[pitch * height];
+ for (unsigned row = 0; row < height; ++row) {
+ memcpy(pixels + row * pitch,
+ (const unsigned char *)mapped.pData + row * mapped.RowPitch, pitch);
+ }
+ Device.Get_Context()->Unmap(staging, 0);
+ }
+
+ staging->Release();
+ back_buffer->Release();
+ return pixels;
+}
+
+void Direct3D11_Release_Capture(unsigned char * pixels)
+{
+ delete [] pixels;
+}
+
+void Direct3D11_End_Scene(bool flip_frames)
+{
+ if (Active && flip_frames && PresentRequested) {
+ Device.Present(0);
+ }
+}
+
+void Direct3D11_Mirror_Stream_Source(DX11BufferTwinClass * twin, unsigned stride, unsigned offset)
+{
+ if (Active) {
+ Backend.Set_Stream_Source(twin ? twin->Buffer() : NULL, stride, offset);
+ }
+}
+
+void Direct3D11_Mirror_Indices(DX11BufferTwinClass * twin)
+{
+ if (Active) {
+ Backend.Set_Indices(twin ? twin->Buffer() : NULL, DXGI_FORMAT_R16_UINT);
+ }
+}
+
+void Direct3D11_Mirror_Vertex_Format(unsigned fvf)
+{
+ if (Active) {
+ Backend.Set_Vertex_Format(fvf);
+ }
+}
+
+void Direct3D11_Mirror_Pixel_Shader(const void * shader)
+{
+ if (Active) {
+ const EngineShaderRecord & record = engine_shader_record(shader);
+ Backend.Set_Pixel_Program(record.Program, shader != NULL, record.FileName.c_str());
+ }
+}
+
+void Direct3D11_Register_Engine_Shader(const void * shader, const char * file_path)
+{
+ if (shader == NULL || file_path == NULL) {
+ return;
+ }
+
+ // The whole path, not the file name alone, so a report line reads the way the loader's own
+ // argument does and can be grepped for as it stands.
+ EngineShaderRecord record;
+ record.Program = EngineShader_From_File(file_path);
+ record.FileName = file_path;
+ EngineShaders[shader] = record;
+}
+
+void Direct3D11_Mirror_Vertex_Shader(const void * shader)
+{
+ if (Active) {
+ const EngineShaderRecord & record = engine_shader_record(shader);
+ Backend.Set_Vertex_Program(record.Program, shader != NULL, record.FileName.c_str());
+ }
+}
+
+void Direct3D11_Mirror_Vertex_Shader_Constant(unsigned first_register, const float * values,
+ unsigned count)
+{
+ if (Active) {
+ Backend.Set_Vertex_Program_Constant(first_register, values, count);
+ }
+}
+
+bool Direct3D11_Draw_Indexed_Triangles(unsigned index_count, unsigned start_index,
+ unsigned base_vertex)
+{
+ if (!Active) {
+ return false;
+ }
+ return Backend.Draw_Indexed_Triangles(index_count, start_index, base_vertex);
+}
+
+bool Direct3D11_Draw_Indexed_Strip(unsigned index_count, unsigned start_index,
+ unsigned base_vertex)
+{
+ if (!Active) {
+ return false;
+ }
+ return Backend.Draw_Indexed_Strip(index_count, start_index, base_vertex);
+}
+
+bool Direct3D11_Draw_User_Strip(const void * vertices, unsigned primitive_count, unsigned stride)
+{
+ if (!Active) {
+ return false;
+ }
+ return Backend.Draw_User_Strip(vertices, primitive_count, stride);
+}
+
+void Direct3D11_Twin_Statistics(unsigned & buffers_made, unsigned long long & bytes_made)
+{
+ buffers_made = TwinBuffers;
+ bytes_made = TwinBytes;
+}
+
+void Direct3D11_Refusals(unsigned long long & no_buffer, unsigned long long & no_stage,
+ unsigned long long & no_layout, unsigned long long & no_program,
+ unsigned long long & no_object, unsigned long long & foreign_shader,
+ unsigned long long & no_texture)
+{
+ no_buffer = 0;
+ no_stage = 0;
+ no_layout = 0;
+ no_program = 0;
+ no_object = 0;
+ foreign_shader = 0;
+ no_texture = 0;
+ if (Active) {
+ Backend.Refusals(no_buffer, no_stage, no_layout, no_program, no_object, foreign_shader,
+ no_texture);
+ }
+}
+
+unsigned Direct3D11_Refused_Description_Count()
+{
+ return Active ? Backend.Refused_Description_Count() : 0;
+}
+
+const char * Direct3D11_Refused_Description(unsigned index)
+{
+ return Active ? Backend.Refused_Description(index) : "";
+}
+
+void Direct3D11_Target_Statistics(unsigned long long & bound, unsigned long long & restored,
+ unsigned long long & draws)
+{
+ bound = 0;
+ restored = 0;
+ draws = 0;
+ if (Active) {
+ Backend.Target_Statistics(bound, restored, draws);
+ }
+}
+
+const char * Direct3D11_Diagnostic()
+{
+ return Active ? Backend.Diagnostic_Line() : "";
+}
+
+unsigned Direct3D11_Target_Trace_Count()
+{
+ return Active ? Backend.Target_Trace_Count() : 0;
+}
+
+const char * Direct3D11_Target_Trace(unsigned index)
+{
+ return Active ? Backend.Target_Trace(index) : "";
+}
+
+unsigned Direct3D11_Pipeline_Report_Count()
+{
+ return Active ? Backend.Pipeline_Report_Count() : 0;
+}
+
+const char * Direct3D11_Pipeline_Report(unsigned index)
+{
+ return Active ? Backend.Pipeline_Report(index) : "";
+}
+
+unsigned Direct3D11_Foreign_Report_Count()
+{
+ return Active ? Backend.Foreign_Report_Count() : 0;
+}
+
+const char * Direct3D11_Foreign_Report(unsigned index)
+{
+ return Active ? Backend.Foreign_Report(index) : "";
+}
+
+const char * Direct3D11_First_Compiler_Error()
+{
+ return Active ? Backend.First_Compiler_Error() : "";
+}
+
void Direct3D11_Statistics(unsigned & pipelines_built, unsigned long long & draws_made,
unsigned long long & draws_refused)
{
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h
index ddff4a9b4..a3c82b0de 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h
@@ -37,6 +37,7 @@
#include <windows.h>
class DX11BackendClass;
+class DX11BufferTwinClass;
class DX11DeviceClass;
// Asked for on the command line, before any device exists.
@@ -74,10 +75,145 @@ void Direct3D11_Mirror_Light(unsigned index, unsigned type, const float position
const float attenuation[4], const float spot[4]);
void Direct3D11_Mirror_Light_Disabled(unsigned index);
+// The Direct3D 11 copy of a vertex or index buffer the engine is about to create, or null on an
+// ordinary run. The buffer classes own what comes back and free it with themselves.
+DX11BufferTwinClass * Direct3D11_Twin_Vertex_Buffer(unsigned byte_count, bool dynamic);
+DX11BufferTwinClass * Direct3D11_Twin_Index_Buffer(unsigned byte_count, bool dynamic);
+
+// The texture bound to a stage. The Direct3D 11 copy is built from the Direct3D 9 texture on the
+// first bind and kept on it, so nothing in the loaders has to know this exists.
+void Direct3D11_Mirror_Texture(unsigned stage, struct IDirect3DBaseTexture9 * texture);
+
+// Send the draws into the copy of whatever texture this surface belongs to. A null surface, or one
+// with no texture behind it, is the back buffer.
+void Direct3D11_Mirror_Render_Target(struct IDirect3DSurface9 * surface);
+
+// One of the engine's surface copies, carried into the copy of the destination texture. This is
+// how a default-pool texture the CPU cannot read - the shroud - reaches D3D11 at all.
+void Direct3D11_Mirror_Surface_Copy(struct IDirect3DSurface9 * destination,
+ struct IDirect3DSurface9 * source, const struct tagRECT * source_rectangle,
+ const struct tagPOINT * destination_point);
+
+// The frame, alongside Direct3D 9's own. Begin binds the back buffer and the viewport, Clear
+// takes the same arguments DX8Wrapper::Clear was given, and End presents only when the run asked
+// to see the Direct3D 11 picture - otherwise the frame is drawn into a back buffer nothing shows,
+// which is what makes it safe to leave both paths running.
+void Direct3D11_Begin_Scene();
+void Direct3D11_Mirror_Clear(bool colour, bool depth, float red, float green, float blue,
+ float alpha);
+void Direct3D11_End_Scene(bool flip_frames);
+
+// -dx11present: show the Direct3D 11 frame in the window instead of Direct3D 9's, and read
+// screenshots back from it. Without it nothing on screen changes when -dx11 is passed.
+// -dx11dump: write every generated program to this directory as it is built.
+void Direct3D11_Dump_Programs_To(const char * directory);
+
+void Direct3D11_Present_Enable(bool enabled);
+bool Direct3D11_Present_Is_Enabled();
+
+// The back buffer as it stands, in the eight-bit blue-green-red-alpha order the screenshot writer
+// wants, top row first. Has to be called before the present that discards it. Null when there is
+// nothing to read; what comes back is freed with Direct3D11_Release_Capture and nothing else.
+unsigned char * Direct3D11_Capture_Back_Buffer(unsigned & width, unsigned & height,
+ unsigned & pitch);
+void Direct3D11_Release_Capture(unsigned char * pixels);
+
+// The buffers and the vertex format a draw is about to read, mirrored as DX8Wrapper binds them.
+// A null twin unbinds, which is what a stream with no buffer means. Index buffers in this engine
+// are 16-bit without exception, so the format is not a parameter.
+void Direct3D11_Mirror_Stream_Source(DX11BufferTwinClass * twin, unsigned stride, unsigned offset);
+void Direct3D11_Mirror_Indices(DX11BufferTwinClass * twin);
+void Direct3D11_Mirror_Vertex_Format(unsigned fvf);
+
+// Whether the engine has one of its own Direct3D 9 shaders bound. The backend generates its own
+// programs out of the fixed-function state, so a draw made with a shipped .vso or .pso is a draw it
+// has no equivalent for: it refuses that one rather than drawing the fixed-function approximation,
+// which is how the terrain came out white instead of missing. The exceptions are the shaders
+// engineshader transcribes, which is why the vertex half is mirrored by pointer: the pointer is the
+// only thing that says which file a bound shader came from.
+void Direct3D11_Mirror_Pixel_Shader(const void * shader);
+void Direct3D11_Mirror_Vertex_Shader(const void * shader);
+
+// The engine loaded a shader out of the big archives and the device made it. Registering it here
+// is what lets a later bind name it; a shader that is never registered is foreign, which is the
+// state everything was in before this existed.
+void Direct3D11_Register_Engine_Shader(const void * shader, const char * file_path);
+
+// The float4 register bank the engine's own shaders read, mirrored as DX8Wrapper sets it.
+void Direct3D11_Mirror_Vertex_Shader_Constant(unsigned first_register, const float * values,
+ unsigned count);
+
+// The draw, made alongside the Direct3D 9 one rather than instead of it: phase 2 is finished when
+// the D3D11 picture can replace the D3D9 one, and until then both have to be able to produce it.
+// False means the backend could not resolve a pipeline for this state and drew nothing, which is
+// counted and reported rather than asserted.
+bool Direct3D11_Draw_Indexed_Triangles(unsigned index_count, unsigned start_index,
+ unsigned base_vertex);
+
+// The same draw over a triangle strip, which is the topology both water grids are indexed for.
+bool Direct3D11_Draw_Indexed_Strip(unsigned index_count, unsigned start_index,
+ unsigned base_vertex);
+
+// How many twins the run made and what they cost in video memory, counted as they are created. A
+// -dx11 run that mirrors nothing draws exactly like one that mirrors everything until the draws
+// move over, so the count is the only thing that says the buffers went across.
+void Direct3D11_Twin_Statistics(unsigned & buffers_made, unsigned long long & bytes_made);
+
+// The same for textures: how many were copied, how many binds reused a copy, and how many could
+// not be copied.
+void Direct3D11_Texture_Statistics(unsigned & textures_made, unsigned & textures_reused,
+ unsigned & textures_refused);
+const char * Direct3D11_Texture_First_Refusal();
+
+// One line per sixteen bit colour texture copied, naming its size and the average colour of its top
+// level. The terrain atlas is one of these, and its average is what says whether the copy holds
+// the ground.
+unsigned Direct3D11_Texture_Note_Count();
+const char * Direct3D11_Texture_Note(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);
+// The refusals split by cause: no buffer bound, no texture stage enabled, a vertex format with no
+// input layout, and a program that could not be generated or compiled.
+void Direct3D11_Refusals(unsigned long long & no_buffer, unsigned long long & no_stage,
+ unsigned long long & no_layout, unsigned long long & no_program,
+ unsigned long long & no_object, unsigned long long & foreign_shader,
+ unsigned long long & no_texture);
+
+// The distinct refused states, as the keys the backend cached them under, and the first thing the
+// shader compiler objected to. Both are strings for the log and nothing else reads them.
+unsigned Direct3D11_Refused_Description_Count();
+const char * Direct3D11_Refused_Description(unsigned index);
+
+// The same listing for the pipelines that did draw, with the draws each took and the size of the
+// texture bound at stage zero the first time it was taken.
+// How many times a texture was bound as the render target, and how many draws landed in one.
+void Direct3D11_Target_Statistics(unsigned long long & bound, unsigned long long & restored,
+ unsigned long long & draws);
+
+// A screen-space quad handed over as vertices rather than as a buffer. Returns false when the
+// backend refused it, the way the other draw mirrors do.
+bool Direct3D11_Draw_User_Strip(const void * vertices, unsigned primitive_count, unsigned stride);
+
+// One line about the first screen-space quad drawn: where it was, and what was in the texture it
+// sampled. Empty when none was drawn.
+const char * Direct3D11_Diagnostic();
+
+// The first few target changes in order, each with the draw count when it happened.
+unsigned Direct3D11_Target_Trace_Count();
+const char * Direct3D11_Target_Trace(unsigned index);
+
+unsigned Direct3D11_Pipeline_Report_Count();
+const char * Direct3D11_Pipeline_Report(unsigned index);
+
+// One line per shipped shader the refused draws had bound, with what each cost. This is the list
+// of what is still to be transcribed, and nothing else in the run names them.
+unsigned Direct3D11_Foreign_Report_Count();
+const char * Direct3D11_Foreign_Report(unsigned index);
+const char * Direct3D11_First_Compiler_Error();
+
#endif // DX11RUNTIME_H
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11state.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11state.cpp
index 331b7efd1..22a11c716 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11state.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11state.cpp
@@ -49,6 +49,25 @@ D3D11_BLEND DX11State_Translate_Blend(DWORD d3d9_blend)
}
}
+// D3D11 refuses a colour factor in either alpha slot: CreateBlendState fails outright for a
+// SrcBlendAlpha of DEST_COLOR, and a failed create leaves the draw with no blend state at all,
+// which is the default one - no blending. D3D9 has no such rule and takes the colour factor's
+// alpha channel, so that is what each of these maps to. The terrain's cloud pass sets
+// D3DBLEND_DESTCOLOR, and with the create failing it stopped multiplying the ground and painted
+// over it instead.
+static D3D11_BLEND alpha_equivalent(D3D11_BLEND blend)
+{
+ switch (blend) {
+ case D3D11_BLEND_SRC_COLOR: return D3D11_BLEND_SRC_ALPHA;
+ case D3D11_BLEND_INV_SRC_COLOR: return D3D11_BLEND_INV_SRC_ALPHA;
+ case D3D11_BLEND_DEST_COLOR: return D3D11_BLEND_DEST_ALPHA;
+ case D3D11_BLEND_INV_DEST_COLOR: return D3D11_BLEND_INV_DEST_ALPHA;
+ case D3D11_BLEND_SRC1_COLOR: return D3D11_BLEND_SRC1_ALPHA;
+ case D3D11_BLEND_INV_SRC1_COLOR: return D3D11_BLEND_INV_SRC1_ALPHA;
+ default: return blend;
+ }
+}
+
D3D11_BLEND_OP DX11State_Translate_Blend_Operation(DWORD d3d9_operation)
{
switch (d3d9_operation) {
@@ -180,9 +199,10 @@ void DX11StateBlockClass::Build_Blend_Description(D3D11_BLEND_DESC & description
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;
+ // says otherwise, and nothing in the engine sets that, so the alpha terms are the colour ones
+ // with a colour factor read as its own alpha channel.
+ target.SrcBlendAlpha = alpha_equivalent(target.SrcBlend);
+ target.DestBlendAlpha = alpha_equivalent(target.DestBlend);
target.BlendOpAlpha = target.BlendOp;
target.RenderTargetWriteMask =
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11texture.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11texture.cpp
new file mode 100644
index 000000000..4008d17cb
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11texture.cpp
@@ -0,0 +1,466 @@
+/*
+** 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 "dx11texture.h"
+
+#include "dx11resource.h"
+
+#include <d3d9.h>
+#include <d3d11.h>
+#include <stdio.h>
+#include <string.h>
+#include <string>
+#include <vector>
+
+// Where the copy and the refusal are kept on the D3D9 texture. The view goes in as an IUnknown,
+// which makes D3D9 release it when the texture goes; the refusal is one byte, because a refusal has
+// nothing to hold on to and still has to be remembered.
+// {2E2E9C21-1B2A-4C7E-9E2F-1D0B7E9A5C01}
+static const GUID DX11_TEXTURE_VIEW =
+ { 0x2e2e9c21, 0x1b2a, 0x4c7e, { 0x9e, 0x2f, 0x1d, 0x0b, 0x7e, 0x9a, 0x5c, 0x01 } };
+// {2E2E9C22-1B2A-4C7E-9E2F-1D0B7E9A5C01}
+static const GUID DX11_TEXTURE_REFUSED =
+ { 0x2e2e9c22, 0x1b2a, 0x4c7e, { 0x9e, 0x2f, 0x1d, 0x0b, 0x7e, 0x9a, 0x5c, 0x01 } };
+// The render target view over the same copy, for a texture the engine draws into.
+// {2E2E9C23-1B2A-4C7E-9E2F-1D0B7E9A5C01}
+static const GUID DX11_TEXTURE_TARGET =
+ { 0x2e2e9c23, 0x1b2a, 0x4c7e, { 0x9e, 0x2f, 0x1d, 0x0b, 0x7e, 0x9a, 0x5c, 0x01 } };
+
+// Why the first texture that could not be copied could not be copied. A count of refusals says
+// how much of the picture is missing its texture; this says what to fix.
+static std::string RefusalReason;
+
+static void note_refusal(const char * reason)
+{
+ if (RefusalReason.empty()) {
+ RefusalReason = reason;
+ }
+}
+
+static std::vector<std::string> Notes;
+
+static unsigned Mirrored = 0;
+static unsigned Refused = 0;
+static unsigned Reused = 0;
+
+// D3DFMT_X8R8G8B8 has no alpha and its bytes hold whatever the loader left there. Read as
+// B8G8R8A8 those bytes are the alpha channel, and a texture whose alpha reads as zero is a texture
+// that draws nothing. The rows are copied with the alpha forced opaque rather than translated to
+// an alpha-less DXGI format, because there is no B8G8R8X8 that a shader resource view will take on
+// every driver.
+static void copy_rows_opaque(unsigned char * destination, unsigned destination_pitch,
+ const unsigned char * source, unsigned source_pitch, unsigned width, unsigned height)
+{
+ for (unsigned row = 0; row < height; ++row) {
+ const unsigned char * in = source + row * source_pitch;
+ unsigned char * out = destination + row * destination_pitch;
+ for (unsigned column = 0; column < width; ++column) {
+ out[column * 4 + 0] = in[column * 4 + 0];
+ out[column * 4 + 1] = in[column * 4 + 1];
+ out[column * 4 + 2] = in[column * 4 + 2];
+ out[column * 4 + 3] = 0xff;
+ }
+ }
+}
+
+// The three sixteen bit colour formats. Their DXGI names exist and a device will create a texture
+// in one, and then a shader resource view over it is refused or samples nothing on drivers that
+// never had to support them: they were legal in D3D9 and optional from D3D11 on. The terrain atlas
+// is A1R5G5B5, and this is the difference between a textured ground and a white one. Expanding to
+// eight bits a channel costs twice the memory for those few textures and asks nothing of the
+// driver.
+static bool is_sixteen_bit_colour(D3DFORMAT format)
+{
+ return format == D3DFMT_A1R5G5B5 || format == D3DFMT_R5G6B5 || format == D3DFMT_A4R4G4B4;
+}
+
+static void expand_sixteen_bit(unsigned char * destination, unsigned destination_pitch,
+ const unsigned char * source, unsigned source_pitch, unsigned width, unsigned height,
+ D3DFORMAT format)
+{
+ for (unsigned row = 0; row < height; ++row) {
+ const unsigned short * in = (const unsigned short *)(source + row * source_pitch);
+ unsigned char * out = destination + row * destination_pitch;
+ for (unsigned column = 0; column < width; ++column) {
+ const unsigned short pixel = in[column];
+ unsigned blue = 0, green = 0, red = 0, alpha = 0xff;
+ switch (format) {
+ case D3DFMT_A1R5G5B5:
+ blue = ((pixel ) & 0x1f) * 255 / 31;
+ green = ((pixel >> 5) & 0x1f) * 255 / 31;
+ red = ((pixel >> 10) & 0x1f) * 255 / 31;
+ alpha = ((pixel >> 15) & 0x01) * 255;
+ break;
+ case D3DFMT_R5G6B5:
+ blue = ((pixel ) & 0x1f) * 255 / 31;
+ green = ((pixel >> 5) & 0x3f) * 255 / 63;
+ red = ((pixel >> 11) & 0x1f) * 255 / 31;
+ break;
+ default: // D3DFMT_A4R4G4B4
+ blue = ((pixel ) & 0x0f) * 255 / 15;
+ green = ((pixel >> 4) & 0x0f) * 255 / 15;
+ red = ((pixel >> 8) & 0x0f) * 255 / 15;
+ alpha = ((pixel >> 12) & 0x0f) * 255 / 15;
+ break;
+ }
+ out[column * 4 + 0] = (unsigned char)blue;
+ out[column * 4 + 1] = (unsigned char)green;
+ out[column * 4 + 2] = (unsigned char)red;
+ out[column * 4 + 3] = (unsigned char)alpha;
+ }
+ }
+}
+
+static bool upload_levels(ID3D11DeviceContext * context, ID3D11Texture2D * destination,
+ IDirect3DTexture9 * source, D3DFORMAT format, unsigned level_count)
+{
+ const bool force_opaque = (format == D3DFMT_X8R8G8B8);
+ const bool expand = is_sixteen_bit_colour(format);
+
+ for (unsigned level = 0; level < level_count; ++level) {
+ D3DSURFACE_DESC level_description;
+ if (FAILED(source->GetLevelDesc(level, &level_description))) {
+ return false;
+ }
+
+ D3DLOCKED_RECT locked;
+ if (FAILED(source->LockRect(level, &locked, NULL, D3DLOCK_READONLY))) {
+ return false;
+ }
+
+ if (expand) {
+ const unsigned pitch = level_description.Width * 4;
+ std::vector<unsigned char> expanded(pitch * level_description.Height);
+ expand_sixteen_bit(&expanded[0], pitch, (const unsigned char *)locked.pBits,
+ locked.Pitch, level_description.Width, level_description.Height, format);
+ context->UpdateSubresource(destination, level, NULL, &expanded[0], pitch, 0);
+ }
+ else if (force_opaque) {
+ const unsigned pitch = level_description.Width * 4;
+ std::vector<unsigned char> opaque(pitch * level_description.Height);
+ copy_rows_opaque(&opaque[0], pitch, (const unsigned char *)locked.pBits, locked.Pitch,
+ level_description.Width, level_description.Height);
+ context->UpdateSubresource(destination, level, NULL, &opaque[0], pitch, 0);
+ }
+ else {
+ context->UpdateSubresource(destination, level, NULL, locked.pBits, locked.Pitch, 0);
+ }
+
+ source->UnlockRect(level);
+ }
+
+ return true;
+}
+
+// The average colour of the texture's top level, read the same way the copy read it. A count of
+// mirrored textures says nothing about what is in them; this says whether the atlas that draws the
+// ground holds the ground or holds white.
+static void note_average_colour(IDirect3DTexture9 * texture, const D3DSURFACE_DESC & description,
+ unsigned level_count)
+{
+ D3DLOCKED_RECT locked;
+ if (FAILED(texture->LockRect(0, &locked, NULL, D3DLOCK_READONLY))) {
+ return;
+ }
+
+ const unsigned pitch = description.Width * 4;
+ std::vector<unsigned char> expanded(pitch * description.Height);
+ expand_sixteen_bit(&expanded[0], pitch, (const unsigned char *)locked.pBits, locked.Pitch,
+ description.Width, description.Height, description.Format);
+ texture->UnlockRect(0);
+
+ double blue = 0.0, green = 0.0, red = 0.0, alpha = 0.0;
+ const unsigned pixels = description.Width * description.Height;
+ for (unsigned pixel = 0; pixel < pixels; ++pixel) {
+ blue += expanded[pixel * 4 + 0];
+ green += expanded[pixel * 4 + 1];
+ red += expanded[pixel * 4 + 2];
+ alpha += expanded[pixel * 4 + 3];
+ }
+
+ char line[192];
+ sprintf(line, "%ux%u format %u levels %u average rgba %.0f,%.0f,%.0f,%.0f",
+ description.Width, description.Height, (unsigned)description.Format, level_count,
+ red / pixels, green / pixels, blue / pixels, alpha / pixels);
+ Notes.push_back(line);
+}
+
+// Everything that decides whether this texture can be mirrored at all, in the order that answers
+// cheapest first.
+static bool can_mirror(IDirect3DTexture9 * texture, D3DSURFACE_DESC & description)
+{
+ if (FAILED(texture->GetLevelDesc(0, &description))) {
+ note_refusal("the D3D9 texture would not describe its top level");
+ return false;
+ }
+ // A default-pool texture that is not a render target cannot be locked and nothing writes it
+ // through D3D11 either, so there is nothing to copy and nothing that would fill the copy. A
+ // render target is the other way round: it holds nothing worth reading now, and D3D11 fills it
+ // itself once the pass that draws into it is routed.
+ if (DX11Resource_Translate_Format(description.Format) == DXGI_FORMAT_UNKNOWN) {
+ note_refusal("the format has no DXGI counterpart");
+ return false;
+ }
+ return true;
+}
+
+static ID3D11ShaderResourceView * build(ID3D11Device * device, ID3D11DeviceContext * context,
+ IDirect3DBaseTexture9 * texture)
+{
+ IDirect3DTexture9 * two_dimensional = NULL;
+ if (FAILED(texture->QueryInterface(IID_IDirect3DTexture9, (void **)&two_dimensional))) {
+ note_refusal("not a two dimensional texture");
+ return NULL;
+ }
+
+ D3DSURFACE_DESC description;
+ if (!can_mirror(two_dimensional, description)) {
+ two_dimensional->Release();
+ return NULL;
+ }
+
+ // A render target is made empty, with one level and the render target bind, and is filled by
+ // whatever draws into it. A default-pool texture is made empty too: D3D9 will not let it be
+ // read back, and the engine fills it by copying a system memory surface over it, which is
+ // mirrored by DX11Texture_Update. Everything else is copied out of the D3D9 texture as it
+ // stands.
+ const bool render_target = (description.Usage & D3DUSAGE_RENDERTARGET) != 0;
+ const bool empty = render_target || description.Pool == D3DPOOL_DEFAULT;
+ const unsigned level_count = empty ? 1 : two_dimensional->GetLevelCount();
+ const D3DFORMAT copy_format = is_sixteen_bit_colour(description.Format)
+ ? D3DFMT_A8R8G8B8
+ : description.Format;
+
+ ID3D11Texture2D * copy = NULL;
+ ID3D11ShaderResourceView * view = NULL;
+ const bool created = DX11Resource_Create_Texture(device, description.Width, description.Height,
+ level_count, copy_format,
+ empty ? D3DPOOL_DEFAULT : D3DPOOL_MANAGED,
+ render_target ? D3DUSAGE_RENDERTARGET : 0,
+ &copy, &view);
+ if (!created) {
+ note_refusal("the D3D11 device refused a texture of that size, format or mip count");
+ two_dimensional->Release();
+ return NULL;
+ }
+
+ if (empty) {
+ copy->Release();
+ two_dimensional->Release();
+ return view;
+ }
+
+ const bool uploaded = upload_levels(context, copy, two_dimensional, description.Format,
+ level_count);
+
+ if (uploaded && is_sixteen_bit_colour(description.Format)) {
+ note_average_colour(two_dimensional, description, level_count);
+ }
+
+ copy->Release();
+ two_dimensional->Release();
+
+ if (!uploaded) {
+ note_refusal("a level of the D3D9 texture would not lock");
+ view->Release();
+ return NULL;
+ }
+
+ return view;
+}
+
+ID3D11ShaderResourceView * DX11Texture_Mirror(ID3D11Device * device, ID3D11DeviceContext * context,
+ IDirect3DBaseTexture9 * texture)
+{
+ ID3D11ShaderResourceView * view = NULL;
+ DWORD size = sizeof(view);
+ if (SUCCEEDED(texture->GetPrivateData(DX11_TEXTURE_VIEW, &view, &size))) {
+ // GetPrivateData on an IUnknown adds a reference for the caller and the texture keeps its
+ // own, so this one is handed straight back.
+ view->Release();
+ ++Reused;
+ return view;
+ }
+
+ unsigned char refused = 0;
+ size = sizeof(refused);
+ if (SUCCEEDED(texture->GetPrivateData(DX11_TEXTURE_REFUSED, &refused, &size))) {
+ return NULL;
+ }
+
+ view = build(device, context, texture);
+ if (view == NULL) {
+ const unsigned char marker = 1;
+ texture->SetPrivateData(DX11_TEXTURE_REFUSED, &marker, sizeof(marker), 0);
+ ++Refused;
+ return NULL;
+ }
+
+ texture->SetPrivateData(DX11_TEXTURE_VIEW, view, sizeof(view), D3DSPD_IUNKNOWN);
+ view->Release();
+ ++Mirrored;
+ return view;
+}
+
+bool DX11Texture_Update(ID3D11Device * device, ID3D11DeviceContext * context,
+ IDirect3DSurface9 * destination, IDirect3DSurface9 * source, const RECT * source_rectangle,
+ const POINT * destination_point)
+{
+ if (destination == NULL || source == NULL) {
+ return false;
+ }
+
+ IDirect3DTexture9 * texture = NULL;
+ if (FAILED(destination->GetContainer(IID_IDirect3DTexture9, (void **)&texture))
+ || texture == NULL) {
+ return false;
+ }
+
+ ID3D11ShaderResourceView * view = DX11Texture_Mirror(device, context, texture);
+ texture->Release();
+ if (view == NULL) {
+ return false;
+ }
+
+ D3DSURFACE_DESC source_description;
+ if (FAILED(source->GetDesc(&source_description))) {
+ return false;
+ }
+
+ const unsigned left = (source_rectangle != NULL) ? source_rectangle->left : 0;
+ const unsigned top = (source_rectangle != NULL) ? source_rectangle->top : 0;
+ const unsigned width = (source_rectangle != NULL)
+ ? (unsigned)(source_rectangle->right - source_rectangle->left)
+ : source_description.Width;
+ const unsigned height = (source_rectangle != NULL)
+ ? (unsigned)(source_rectangle->bottom - source_rectangle->top)
+ : source_description.Height;
+ if (width == 0 || height == 0) {
+ return false;
+ }
+
+ D3DLOCKED_RECT locked;
+ if (FAILED(source->LockRect(&locked, source_rectangle, D3DLOCK_READONLY))) {
+ note_refusal("the surface being copied from would not lock");
+ return false;
+ }
+
+ ID3D11Resource * resource = NULL;
+ view->GetResource(&resource);
+ if (resource == NULL) {
+ source->UnlockRect();
+ return false;
+ }
+
+ D3D11_BOX box;
+ box.left = (destination_point != NULL) ? destination_point->x : left;
+ box.top = (destination_point != NULL) ? destination_point->y : top;
+ box.front = 0;
+ box.right = box.left + width;
+ box.bottom = box.top + height;
+ box.back = 1;
+
+ // The copy was expanded to eight bits a channel when it was made, so the update has to be
+ // expanded the same way or the rows land at the wrong stride in the wrong format.
+ if (is_sixteen_bit_colour(source_description.Format)) {
+ const unsigned pitch = width * 4;
+ std::vector<unsigned char> expanded(pitch * height);
+ expand_sixteen_bit(&expanded[0], pitch, (const unsigned char *)locked.pBits, locked.Pitch,
+ width, height, source_description.Format);
+ context->UpdateSubresource(resource, 0, &box, &expanded[0], pitch, 0);
+ }
+ else {
+ context->UpdateSubresource(resource, 0, &box, locked.pBits, locked.Pitch, 0);
+ }
+
+ resource->Release();
+ source->UnlockRect();
+ return true;
+}
+
+ID3D11RenderTargetView * DX11Texture_Target(ID3D11Device * device, ID3D11DeviceContext * context,
+ IDirect3DSurface9 * surface)
+{
+ if (surface == NULL) {
+ return NULL;
+ }
+
+ // The surface the engine hands over is a level of a texture, and the copy lives on the texture.
+ // A surface with no texture behind it is the device's own back buffer, which the backend has
+ // already.
+ IDirect3DTexture9 * texture = NULL;
+ if (FAILED(surface->GetContainer(IID_IDirect3DTexture9, (void **)&texture)) || texture == NULL) {
+ return NULL;
+ }
+
+ ID3D11RenderTargetView * target = NULL;
+ DWORD size = sizeof(target);
+ if (SUCCEEDED(texture->GetPrivateData(DX11_TEXTURE_TARGET, &target, &size))) {
+ target->Release();
+ texture->Release();
+ return target;
+ }
+
+ ID3D11ShaderResourceView * view = DX11Texture_Mirror(device, context, texture);
+ if (view == NULL) {
+ texture->Release();
+ return NULL;
+ }
+
+ ID3D11Resource * resource = NULL;
+ view->GetResource(&resource);
+ if (resource == NULL) {
+ texture->Release();
+ return NULL;
+ }
+
+ if (FAILED(device->CreateRenderTargetView(resource, NULL, &target))) {
+ note_refusal("the D3D11 device would not make a render target view of the copy");
+ resource->Release();
+ texture->Release();
+ return NULL;
+ }
+ resource->Release();
+
+ texture->SetPrivateData(DX11_TEXTURE_TARGET, target, sizeof(target), D3DSPD_IUNKNOWN);
+ target->Release();
+ texture->Release();
+ return target;
+}
+
+void DX11Texture_Statistics(unsigned & mirrored, unsigned & reused, unsigned & refused)
+{
+ mirrored = Mirrored;
+ reused = Reused;
+ refused = Refused;
+}
+
+const char * DX11Texture_First_Refusal()
+{
+ return RefusalReason.c_str();
+}
+
+unsigned DX11Texture_Note_Count()
+{
+ return (unsigned)Notes.size();
+}
+
+const char * DX11Texture_Note(unsigned index)
+{
+ return (index < Notes.size()) ? Notes[index].c_str() : "";
+}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11texture.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11texture.h
new file mode 100644
index 000000000..a2aa8ac5a
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11texture.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 Direct3D 11 copy of a texture the engine already built in Direct3D 9.
+**
+** Textures are not buffers. A vertex buffer is write-only and had to have its write moved, but a
+** managed texture can be read back level by level, and every path that produces one - the .dds and
+** .tga loaders, the procedural surfaces, the shroud - has finished writing before anything binds
+** it. So the copy is made at the moment of the first bind and from the D3D9 texture itself, which
+** costs one read of each level once and needs no hook in any of the loaders.
+**
+** The copy is kept on the D3D9 texture as private data, so it is released when that texture is,
+** and a texture that cannot be mirrored - a render target, a format D3D11 does not name - is
+** marked as such and not tried again.
+*/
+
+#ifndef DX11TEXTURE_H
+#define DX11TEXTURE_H
+
+struct IDirect3DBaseTexture9;
+struct IDirect3DSurface9;
+struct ID3D11Device;
+struct ID3D11DeviceContext;
+struct ID3D11ShaderResourceView;
+struct ID3D11RenderTargetView;
+
+// The view for this texture, built on the first call and returned from the texture itself after
+// that. Null when the texture cannot be mirrored, which is remembered so the next bind is free.
+// The view is owned by the D3D9 texture; the caller borrows it.
+ID3D11ShaderResourceView * DX11Texture_Mirror(ID3D11Device * device, ID3D11DeviceContext * context,
+ IDirect3DBaseTexture9 * texture);
+
+// Carry one of the engine's surface copies into the copy of the destination texture. A
+// default-pool texture - the shroud is one - cannot be read back through D3D9, so its copy is made
+// empty and filled here, from the system memory surface the engine copies over it.
+bool DX11Texture_Update(ID3D11Device * device, ID3D11DeviceContext * context,
+ IDirect3DSurface9 * destination, IDirect3DSurface9 * source,
+ const struct tagRECT * source_rectangle, const struct tagPOINT * destination_point);
+
+// The render target view over the copy of the texture this surface is a level of, built on the
+// first call and kept on that texture with the shader resource view. Null when the surface has no
+// texture behind it, which is the device's own back buffer.
+ID3D11RenderTargetView * DX11Texture_Target(ID3D11Device * device, ID3D11DeviceContext * context,
+ IDirect3DSurface9 * surface);
+
+// For the run's report: how many textures were copied, how many binds found the copy already on
+// the texture, and how many could not be copied at all.
+void DX11Texture_Statistics(unsigned & mirrored, unsigned & reused, unsigned & refused);
+
+// Why the first refused texture was refused. Empty when none was.
+const char * DX11Texture_First_Refusal();
+
+// One line for each copy made from a sixteen bit colour texture, naming its size, its mip count and
+// the average colour of its top level. There are a handful of these in a match - the terrain
+// atlas, the alpha edge - and a white average is the difference between a textured ground and the
+// white one, which no count of mirrored textures can tell apart.
+unsigned DX11Texture_Note_Count();
+const char * DX11Texture_Note(unsigned index);
+
+#endif // DX11TEXTURE_H
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11twin.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11twin.cpp
index 0bfd2d60f..7f2cee810 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11twin.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11twin.cpp
@@ -18,24 +18,27 @@
#include "dx11twin.h"
-#include "dx11device.h"
#include "dx11resource.h"
-#include "dx11runtime.h"
#include <d3d11.h>
+#include <string.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;
+// What the twin asks dx11resource for. A buffer the engine fills once becomes a default-usage
+// buffer the CPU never maps, written with UpdateSubresource; one it refills every frame keeps
+// D3D9's own dynamic usage and is mapped, for the reason on Upload.
+static const D3DPOOL STATIC_POOL = D3DPOOL_MANAGED;
+static const DWORD STATIC_USAGE = 0;
+static const D3DPOOL DYNAMIC_POOL = D3DPOOL_DEFAULT;
+static const DWORD DYNAMIC_USAGE = D3DUSAGE_DYNAMIC|D3DUSAGE_WRITEONLY;
DX11BufferTwinClass::DX11BufferTwinClass(unsigned char * mirror, unsigned byte_count,
- ID3D11Buffer * buffer)
+ ID3D11Buffer * buffer, ID3D11DeviceContext * context, bool dynamic)
:
Mirror_Bytes(mirror),
Byte_Total(byte_count),
- D3D11Buffer(buffer)
+ D3D11Buffer(buffer),
+ Context(context),
+ Dynamic(dynamic)
{
}
@@ -45,7 +48,7 @@ DX11BufferTwinClass::~DX11BufferTwinClass()
D3D11Buffer->Release();
}
-void DX11BufferTwinClass::Upload(unsigned byte_offset, unsigned byte_count)
+void DX11BufferTwinClass::Upload(unsigned byte_offset, unsigned byte_count, bool discard)
{
if (byte_count == 0) {
byte_count = Byte_Total - byte_offset;
@@ -54,6 +57,19 @@ void DX11BufferTwinClass::Upload(unsigned byte_offset, unsigned byte_count)
return;
}
+ if (Dynamic) {
+ // NO_OVERWRITE promises the range being written is one no outstanding draw reads, which is
+ // the same promise the engine already made to D3D9 when it passed D3DLOCK_NOOVERWRITE.
+ const D3D11_MAP map_type = discard ? D3D11_MAP_WRITE_DISCARD : D3D11_MAP_WRITE_NO_OVERWRITE;
+ D3D11_MAPPED_SUBRESOURCE mapped;
+ if (SUCCEEDED(Context->Map(D3D11Buffer, 0, map_type, 0, &mapped))) {
+ memcpy((unsigned char *)mapped.pData + byte_offset, Mirror_Bytes + byte_offset,
+ byte_count);
+ Context->Unmap(D3D11Buffer, 0);
+ }
+ return;
+ }
+
D3D11_BOX box;
box.left = byte_offset;
box.right = byte_offset + byte_count;
@@ -62,34 +78,72 @@ void DX11BufferTwinClass::Upload(unsigned byte_offset, unsigned byte_count)
box.front = 0;
box.back = 1;
- Direct3D11_Device()->Get_Context()->UpdateSubresource(D3D11Buffer, 0, &box,
- Mirror_Bytes + byte_offset, 0, 0);
+ Context->UpdateSubresource(D3D11Buffer, 0, &box, Mirror_Bytes + byte_offset, 0, 0);
}
-static DX11BufferTwinClass * create(unsigned byte_count, bool index_buffer)
+static DX11BufferTwinClass * create(ID3D11Device * device, ID3D11DeviceContext * context,
+ unsigned byte_count, bool dynamic, bool index_buffer)
{
- if (!Direct3D11_Is_Active()) {
- return NULL;
- }
+ const D3DPOOL pool = dynamic ? DYNAMIC_POOL : STATIC_POOL;
+ const DWORD usage = dynamic ? DYNAMIC_USAGE : STATIC_USAGE;
- 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);
+ ? DX11Resource_Create_Index_Buffer(device, byte_count, pool, usage, NULL, &buffer)
+ : DX11Resource_Create_Vertex_Buffer(device, byte_count, pool, usage, NULL, &buffer);
if (!made) {
return NULL;
}
- return new DX11BufferTwinClass(new unsigned char[byte_count], byte_count, buffer);
+ return new DX11BufferTwinClass(new unsigned char[byte_count], byte_count, buffer, context,
+ dynamic);
+}
+
+DX11BufferTwinClass * DX11Twin_Create_Vertex_Buffer(ID3D11Device * device,
+ ID3D11DeviceContext * context, unsigned byte_count, bool dynamic)
+{
+ return create(device, context, byte_count, dynamic, false);
+}
+
+DX11BufferTwinClass * DX11Twin_Create_Index_Buffer(ID3D11Device * device,
+ ID3D11DeviceContext * context, unsigned byte_count, bool dynamic)
+{
+ return create(device, context, byte_count, dynamic, true);
+}
+
+DX11BufferLockClass::DX11BufferLockClass()
+ :
+ Twin(NULL),
+ D3D9Memory(NULL),
+ ByteOffset(0),
+ ByteCount(0),
+ Discard(false)
+{
}
-DX11BufferTwinClass * DX11Twin_Create_Vertex_Buffer(unsigned byte_count)
+void * DX11BufferLockClass::Begin(DX11BufferTwinClass * twin, void * d3d9_memory,
+ unsigned byte_offset, unsigned byte_count, unsigned lock_flags)
{
- return create(byte_count, false);
+ Twin = twin;
+ if (Twin == NULL) {
+ return NULL;
+ }
+
+ D3D9Memory = d3d9_memory;
+ ByteOffset = byte_offset;
+ ByteCount = byte_count == 0 ? Twin->Byte_Count() - byte_offset : byte_count;
+ Discard = (lock_flags & D3DLOCK_DISCARD) != 0;
+
+ return Twin->Mirror() + ByteOffset;
}
-DX11BufferTwinClass * DX11Twin_Create_Index_Buffer(unsigned byte_count)
+void DX11BufferLockClass::End()
{
- return create(byte_count, true);
+ if (Twin == NULL) {
+ return;
+ }
+
+ memcpy(D3D9Memory, Twin->Mirror() + ByteOffset, ByteCount);
+ Twin->Upload(ByteOffset, ByteCount, Discard);
+ Twin = NULL;
}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11twin.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11twin.h
index c1a513115..98275734b 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11twin.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11twin.h
@@ -27,19 +27,24 @@
** 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.
+** Nothing here asks whether Direct3D 11 is running. The device and its context arrive as
+** arguments, which keeps the file testable against an offscreen device; dx11runtime answers null
+** for the buffers on an ordinary run, and every caller carries that null through to the old path.
*/
#ifndef DX11TWIN_H
#define DX11TWIN_H
struct ID3D11Buffer;
+struct ID3D11Device;
+struct ID3D11DeviceContext;
class DX11BufferTwinClass
{
public:
- DX11BufferTwinClass(unsigned char * mirror, unsigned byte_count, ID3D11Buffer * buffer);
+ // Takes the mirror block and the buffer; the context is borrowed and outlives the twin.
+ DX11BufferTwinClass(unsigned char * mirror, unsigned byte_count, ID3D11Buffer * buffer,
+ ID3D11DeviceContext * context, bool dynamic);
~DX11BufferTwinClass();
// The block a lock hands out. Offsets into it are byte offsets into the buffer.
@@ -49,7 +54,13 @@ public:
// 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);
+ //
+ // A static buffer is written with UpdateSubresource; a dynamic one is mapped, because a partial
+ // UpdateSubresource cannot rename the buffer and so waits for every draw still reading it. The
+ // engine locks its dynamic buffers several hundred times a frame, and that wait was a second a
+ // frame on Tournament Desert. discard is D3D9's own D3DLOCK_DISCARD, passed through: it says
+ // the rest of the buffer is not worth keeping, which is what lets the driver rename.
+ void Upload(unsigned byte_offset, unsigned byte_count, bool discard);
private:
DX11BufferTwinClass(const DX11BufferTwinClass &);
@@ -58,10 +69,41 @@ private:
unsigned char * Mirror_Bytes;
unsigned Byte_Total;
ID3D11Buffer * D3D11Buffer;
+ ID3D11DeviceContext * Context;
+ bool Dynamic;
};
-// 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);
+// Null when the device refused the buffer. The caller owns what comes back. dynamic is the
+// engine's own USAGE_DYNAMIC for this buffer and decides how an upload is written.
+DX11BufferTwinClass * DX11Twin_Create_Vertex_Buffer(ID3D11Device * device,
+ ID3D11DeviceContext * context, unsigned byte_count, bool dynamic);
+DX11BufferTwinClass * DX11Twin_Create_Index_Buffer(ID3D11Device * device,
+ ID3D11DeviceContext * context, unsigned byte_count, bool dynamic);
+
+/*
+** One redirected lock, held for as long as the buffer's own lock object is.
+**
+** Begin answers the pointer the lock should hand out, or null when there is no twin and the caller
+** keeps the D3D9 pointer it already has. End writes the range into the D3D9 memory and then into
+** the D3D11 buffer, and has to run before the D3D9 unlock while that pointer is still mapped.
+*/
+class DX11BufferLockClass
+{
+public:
+ DX11BufferLockClass();
+
+ // lock_flags is the D3DLOCK_* set the caller handed Direct3D 9, so the upload can be written
+ // the same way the D3D9 lock was.
+ void * Begin(DX11BufferTwinClass * twin, void * d3d9_memory, unsigned byte_offset,
+ unsigned byte_count, unsigned lock_flags);
+ void End();
+
+private:
+ DX11BufferTwinClass * Twin;
+ void * D3D9Memory;
+ unsigned ByteOffset;
+ unsigned ByteCount;
+ bool Discard;
+};
#endif // DX11TWIN_H
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8indexbuffer.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8indexbuffer.cpp
index 00bba4e57..65ddae30c 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8indexbuffer.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8indexbuffer.cpp
@@ -41,6 +41,7 @@
#include "dx8indexbuffer.h"
#include "dx8wrapper.h"
#include "dx8caps.h"
+#include "dx11runtime.h"
#include "sphere.h"
#include "thread.h"
#include "wwmemlog.h"
@@ -202,6 +203,11 @@ IndexBufferClass::WriteLockClass::WriteLockClass(IndexBufferClass* index_buffer_
index_buffer->Get_Index_Count()*sizeof(WORD),
(void**)&indices,
flags));
+ {
+ void* mirror=dx11_lock.Begin(
+ static_cast<DX8IndexBufferClass*>(index_buffer)->Get_DX11_Twin(),indices,0,0,flags);
+ if (mirror) indices=(unsigned short*)mirror;
+ }
break;
case BUFFER_TYPE_SORTING:
indices=static_cast<SortingIndexBufferClass*>(index_buffer)->index_buffer;
@@ -224,6 +230,7 @@ IndexBufferClass::WriteLockClass::~WriteLockClass()
case BUFFER_TYPE_DX8:
if (static_cast<DX8IndexBufferClass*>(index_buffer)->index_buffer==NULL) break;
DX8_Assert();
+ dx11_lock.End();
DX8_ErrorCode(static_cast<DX8IndexBufferClass*>(index_buffer)->index_buffer->Unlock());
break;
case BUFFER_TYPE_SORTING:
@@ -258,6 +265,15 @@ IndexBufferClass::AppendLockClass::AppendLockClass(IndexBufferClass* index_buffe
index_range*sizeof(unsigned short),
(void**)&indices,
0));
+ {
+ void* mirror=dx11_lock.Begin(
+ static_cast<DX8IndexBufferClass*>(index_buffer)->Get_DX11_Twin(),
+ indices,
+ start_index*sizeof(unsigned short),
+ index_range*sizeof(unsigned short),
+ 0); // Default (no) flags, as above
+ if (mirror) indices=(unsigned short*)mirror;
+ }
break;
case BUFFER_TYPE_SORTING:
indices=static_cast<SortingIndexBufferClass*>(index_buffer)->index_buffer+start_index;
@@ -277,6 +293,7 @@ IndexBufferClass::AppendLockClass::~AppendLockClass()
case BUFFER_TYPE_DX8:
if (static_cast<DX8IndexBufferClass*>(index_buffer)->index_buffer==NULL) break;
DX8_Assert();
+ dx11_lock.End();
DX8_ErrorCode(static_cast<DX8IndexBufferClass*>(index_buffer)->index_buffer->Unlock());
break;
case BUFFER_TYPE_SORTING:
@@ -302,6 +319,7 @@ DX8IndexBufferClass::DX8IndexBufferClass(unsigned short index_count_,UsageType u
WWASSERT(index_count);
index_buffer=NULL;
scratch_indices=NULL;
+ dx11_twin=NULL;
// Same as the vertex buffer: no render device, no D3D buffer. See Create_Vertex_Buffer.
if (DX8Wrapper::_Get_D3D_Device() == NULL) {
@@ -309,6 +327,8 @@ DX8IndexBufferClass::DX8IndexBufferClass(unsigned short index_count_,UsageType u
return;
}
+ dx11_twin=Direct3D11_Twin_Index_Buffer(sizeof(WORD)*index_count,(usage&USAGE_DYNAMIC)!=0);
+
unsigned usage_flags=
D3DUSAGE_WRITEONLY|
((usage&USAGE_DYNAMIC) ? D3DUSAGE_DYNAMIC : 0)|
@@ -363,6 +383,7 @@ DX8IndexBufferClass::~DX8IndexBufferClass()
{
if (index_buffer) index_buffer->Release();
if (scratch_indices) delete [] scratch_indices;
+ if (dx11_twin) delete dx11_twin;
}
// ----------------------------------------------------------------------------
@@ -460,6 +481,15 @@ DynamicIBAccessClass::WriteLockClass::WriteLockClass(DynamicIBAccessClass* ib_ac
DynamicIBAccess->Get_Index_Count()*sizeof(WORD),
(void**)&Indices,
!DynamicIBAccess->IndexBufferOffset ? D3DLOCK_DISCARD : D3DLOCK_NOOVERWRITE));
+ {
+ void* mirror=DX11Lock.Begin(
+ static_cast<DX8IndexBufferClass*>(DynamicIBAccess->IndexBuffer)->Get_DX11_Twin(),
+ Indices,
+ DynamicIBAccess->IndexBufferOffset*sizeof(WORD),
+ DynamicIBAccess->Get_Index_Count()*sizeof(WORD),
+ !DynamicIBAccess->IndexBufferOffset ? D3DLOCK_DISCARD : D3DLOCK_NOOVERWRITE);
+ if (mirror) Indices=(unsigned short*)mirror;
+ }
break;
case BUFFER_TYPE_DYNAMIC_SORTING:
Indices=static_cast<SortingIndexBufferClass*>(DynamicIBAccess->IndexBuffer)->index_buffer;
@@ -477,6 +507,7 @@ DynamicIBAccessClass::WriteLockClass::~WriteLockClass()
switch (DynamicIBAccess->Get_Type()) {
case BUFFER_TYPE_DYNAMIC_DX8:
DX8_Assert();
+ DX11Lock.End();
DX8_ErrorCode(static_cast<DX8IndexBufferClass*>(DynamicIBAccess->IndexBuffer)->Get_DX8_Index_Buffer()->Unlock());
break;
case BUFFER_TYPE_DYNAMIC_SORTING:
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8indexbuffer.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8indexbuffer.h
index 572dd8eb1..957588971 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8indexbuffer.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8indexbuffer.h
@@ -47,6 +47,7 @@
#include "wwdebug.h"
#include "refcount.h"
#include "sphere.h"
+#include "dx11twin.h"
class DX8Wrapper;
class SortingRendererClass;
@@ -80,6 +81,7 @@ public:
{
IndexBufferClass* index_buffer;
unsigned short* indices;
+ DX11BufferLockClass dx11_lock;
public:
WriteLockClass(IndexBufferClass* index_buffer, int flags=0);
~WriteLockClass();
@@ -91,6 +93,7 @@ public:
{
IndexBufferClass* index_buffer;
unsigned short* indices;
+ DX11BufferLockClass dx11_lock;
public:
AppendLockClass(IndexBufferClass* index_buffer,unsigned start_index, unsigned index_range);
~AppendLockClass();
@@ -144,7 +147,8 @@ public:
class WriteLockClass
{
DynamicIBAccessClass* DynamicIBAccess;
- unsigned short* Indices;
+ unsigned short* Indices;
+ DX11BufferLockClass DX11Lock;
public:
WriteLockClass(DynamicIBAccessClass* ib_access);
~WriteLockClass();
@@ -188,9 +192,14 @@ public:
// and costs a heap block that nothing ever reads.
inline unsigned short* Get_Scratch_Indices() { return scratch_indices; }
+ // The Direct3D 11 copy of this buffer, or null on a run without -dx11. A lock hands out the
+ // twin's mirror instead of the D3D9 pointer; see dx11twin.h.
+ inline DX11BufferTwinClass* Get_DX11_Twin() { return dx11_twin; }
+
private:
IDirect3DIndexBuffer9* index_buffer; // actual dx8 index buffer
unsigned short* scratch_indices; // used instead when there is no device
+ DX11BufferTwinClass* dx11_twin; // the Direct3D 11 copy, null without -dx11
};
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8vertexbuffer.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8vertexbuffer.cpp
index a14dad509..72e10576f 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8vertexbuffer.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8vertexbuffer.cpp
@@ -43,6 +43,7 @@
#include "dx8wrapper.h"
#include "dx8fvf.h"
#include "dx8caps.h"
+#include "dx11runtime.h"
#include "thread.h"
#include "wwmemlog.h"
#include "d3dx9runtime.h"
@@ -184,6 +185,11 @@ VertexBufferClass::WriteLockClass::WriteLockClass(VertexBufferClass* VertexBuffe
0,
(void**)&Vertices,
flags)); //flags
+ {
+ void* mirror=DX11Lock.Begin(
+ static_cast<DX8VertexBufferClass*>(VertexBuffer)->Get_DX11_Twin(),Vertices,0,0,flags);
+ if (mirror) Vertices=mirror;
+ }
break;
case BUFFER_TYPE_SORTING:
Vertices=static_cast<SortingVertexBufferClass*>(VertexBuffer)->VertexBuffer;
@@ -206,6 +212,7 @@ VertexBufferClass::WriteLockClass::~WriteLockClass()
#endif
DX8_Assert();
if (static_cast<DX8VertexBufferClass*>(VertexBuffer)->Get_DX8_Vertex_Buffer()==NULL) break;
+ DX11Lock.End();
DX8_ErrorCode(static_cast<DX8VertexBufferClass*>(VertexBuffer)->Get_DX8_Vertex_Buffer()->Unlock());
break;
case BUFFER_TYPE_SORTING:
@@ -256,6 +263,15 @@ VertexBufferClass::AppendLockClass::AppendLockClass(VertexBufferClass* VertexBuf
index_range*VertexBuffer->FVF_Info().Get_FVF_Size(),
(void**)&Vertices,
0)); // Default (no) flags
+ {
+ void* mirror=DX11Lock.Begin(
+ static_cast<DX8VertexBufferClass*>(VertexBuffer)->Get_DX11_Twin(),
+ Vertices,
+ start_index*VertexBuffer->FVF_Info().Get_FVF_Size(),
+ index_range*VertexBuffer->FVF_Info().Get_FVF_Size(),
+ 0); // Default (no) flags, as above
+ if (mirror) Vertices=mirror;
+ }
break;
case BUFFER_TYPE_SORTING:
Vertices=static_cast<SortingVertexBufferClass*>(VertexBuffer)->VertexBuffer+start_index;
@@ -278,6 +294,7 @@ VertexBufferClass::AppendLockClass::~AppendLockClass()
WWDEBUG_SAY(("VertexBuffer->Unlock()\n"));
#endif
if (static_cast<DX8VertexBufferClass*>(VertexBuffer)->Get_DX8_Vertex_Buffer()==NULL) break;
+ DX11Lock.End();
DX8_ErrorCode(static_cast<DX8VertexBufferClass*>(VertexBuffer)->Get_DX8_Vertex_Buffer()->Unlock());
break;
case BUFFER_TYPE_SORTING:
@@ -418,6 +435,7 @@ DX8VertexBufferClass::~DX8VertexBufferClass()
#endif
if (VertexBuffer) VertexBuffer->Release();
if (ScratchVertices) delete [] ScratchVertices;
+ if (DX11Twin) delete DX11Twin;
}
// ----------------------------------------------------------------------------
@@ -430,6 +448,7 @@ void DX8VertexBufferClass::Create_Vertex_Buffer(UsageType usage)
{
DX8_THREAD_ASSERT();
WWASSERT(!VertexBuffer);
+ DX11Twin=NULL;
#ifdef VERTEX_BUFFER_LOG
StringClass fvf_name;
@@ -454,6 +473,8 @@ void DX8VertexBufferClass::Create_Vertex_Buffer(UsageType usage)
return;
}
ScratchVertices=NULL;
+ DX11Twin=Direct3D11_Twin_Vertex_Buffer(FVF_Info().Get_FVF_Size()*VertexCount,
+ (usage&USAGE_DYNAMIC)!=0);
unsigned usage_flags=
D3DUSAGE_WRITEONLY|
@@ -886,6 +907,15 @@ DynamicVBAccessClass::WriteLockClass::WriteLockClass(DynamicVBAccessClass* dynam
DynamicVBAccess->Get_Vertex_Count()*DynamicVBAccess->VertexBuffer->FVF_Info().Get_FVF_Size(),
(void**)&Vertices,
D3DLOCK_NOSYSLOCK | (!DynamicVBAccess->VertexBufferOffset ? D3DLOCK_DISCARD : D3DLOCK_NOOVERWRITE)));
+ {
+ void* mirror=DX11Lock.Begin(
+ static_cast<DX8VertexBufferClass*>(DynamicVBAccess->VertexBuffer)->Get_DX11_Twin(),
+ Vertices,
+ DynamicVBAccess->VertexBufferOffset*DynamicVBAccess->VertexBuffer->FVF_Info().Get_FVF_Size(),
+ DynamicVBAccess->Get_Vertex_Count()*DynamicVBAccess->VertexBuffer->FVF_Info().Get_FVF_Size(),
+ !DynamicVBAccess->VertexBufferOffset ? D3DLOCK_DISCARD : D3DLOCK_NOOVERWRITE);
+ if (mirror) Vertices=(VertexFormatXYZNDUV2*)mirror;
+ }
break;
case BUFFER_TYPE_DYNAMIC_SORTING:
Vertices=static_cast<SortingVertexBufferClass*>(DynamicVBAccess->VertexBuffer)->VertexBuffer;
@@ -912,6 +942,7 @@ DynamicVBAccessClass::WriteLockClass::~WriteLockClass()
*/
#endif
DX8_Assert();
+ DX11Lock.End();
DX8_ErrorCode(static_cast<DX8VertexBufferClass*>(DynamicVBAccess->VertexBuffer)->Get_DX8_Vertex_Buffer()->Unlock());
break;
case BUFFER_TYPE_DYNAMIC_SORTING:
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8vertexbuffer.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8vertexbuffer.h
index 19a90c738..9f6fc1e71 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8vertexbuffer.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8vertexbuffer.h
@@ -48,6 +48,7 @@
#include "wwdebug.h"
#include "refcount.h"
#include "dx8fvf.h"
+#include "dx11twin.h"
const unsigned dynamic_fvf_type=D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_TEX2|D3DFVF_DIFFUSE;
@@ -99,6 +100,7 @@ public:
class WriteLockClass : public VertexBufferLockClass
{
+ DX11BufferLockClass DX11Lock;
public:
WriteLockClass(VertexBufferClass* vertex_buffer, int flags=0);
~WriteLockClass();
@@ -106,6 +108,7 @@ public:
class AppendLockClass : public VertexBufferLockClass
{
+ DX11BufferLockClass DX11Lock;
public:
AppendLockClass(VertexBufferClass* vertex_buffer,unsigned start_index, unsigned index_range);
~AppendLockClass();
@@ -176,6 +179,7 @@ public:
{
DynamicVBAccessClass* DynamicVBAccess;
VertexFormatXYZNDUV2 * Vertices;
+ DX11BufferLockClass DX11Lock;
public:
WriteLockClass(DynamicVBAccessClass* vb_access);
~WriteLockClass();
@@ -229,6 +233,10 @@ public:
// DX8IndexBufferClass::Get_Scratch_Indices for why a run with no picture still fills buffers.
unsigned char* Get_Scratch_Vertices() { return ScratchVertices; }
+ // The Direct3D 11 copy of this buffer, or null on a run without -dx11. A lock hands out the
+ // twin's mirror instead of the D3D9 pointer; see dx11twin.h.
+ DX11BufferTwinClass* Get_DX11_Twin() { return DX11Twin; }
+
void Copy(const Vector3* loc, unsigned first_vertex, unsigned count);
void Copy(const Vector3* loc, const Vector2* uv, unsigned first_vertex, unsigned count);
void Copy(const Vector3* loc, const Vector3* norm, unsigned first_vertex, unsigned count);
@@ -239,6 +247,7 @@ public:
protected:
IDirect3DVertexBuffer9* VertexBuffer;
unsigned char* ScratchVertices; // used instead when there is no device
+ DX11BufferTwinClass* DX11Twin; // the Direct3D 11 copy, null without -dx11
void Create_Vertex_Buffer(UsageType usage);
};
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp
index dac95a184..eb0a3d8a1 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp
@@ -169,6 +169,19 @@ void DX8Wrapper::_Set_DX8_Render_Target(IDirect3DSurface9 * render_target, IDire
{
DX8CALL(SetRenderTarget(PRIMARY_RENDER_TARGET,render_target));
DX8CALL(SetDepthStencilSurface(depth_buffer));
+ // Every render target the engine sets passes through here, the device's own back buffer
+ // included; the backend works out which is which from whether the surface has a texture behind
+ // it.
+ Direct3D11_Mirror_Render_Target(render_target);
+}
+
+void DX8Wrapper::_Draw_DX8_Primitive_UP(D3DPRIMITIVETYPE type, unsigned primitive_count,
+ const void * vertices, unsigned stride)
+{
+ DX8CALL(DrawPrimitiveUP(type, primitive_count, vertices, stride));
+ if (type == D3DPT_TRIANGLESTRIP) {
+ Direct3D11_Draw_User_Strip(vertices, primitive_count, stride);
+ }
}
// D3D9 has no CopyRects. Which call replaces it depends on where the two surfaces live,
@@ -248,6 +261,13 @@ void DX8Wrapper::_Copy_DX8_Rects(
Non_Fatal_Log_DX8_ErrorCode(hr,__FILE__,__LINE__);
return;
}
+
+ // The same copy into the D3D11 twin of whatever texture the destination belongs to. It
+ // reads the source surface rather than the destination, because a default-pool destination
+ // is exactly the one D3D9 will not let anything read back.
+ const POINT destination_point={destination_rect.left,destination_rect.top};
+ Direct3D11_Mirror_Surface_Copy(pDestinationSurface,pSourceSurface,&source_rect,
+ &destination_point);
}
}
IDirect3DBaseTexture9 * DX8Wrapper::Textures[MAX_TEXTURE_STAGES];
@@ -1907,6 +1927,7 @@ void DX8Wrapper::Begin_Scene(void)
#endif
DX8CALL(BeginScene());
+ Direct3D11_Begin_Scene();
DX8WebBrowser::Update();
}
@@ -1915,6 +1936,7 @@ void DX8Wrapper::End_Scene(bool flip_frames)
{
DX8_THREAD_ASSERT();
DX8CALL(EndScene());
+ Direct3D11_End_Scene(flip_frames);
DX8WebBrowser::Render(0);
@@ -2061,6 +2083,7 @@ void DX8Wrapper::Clear(bool clear_color, bool clear_z_stencil, const Vector3 &co
{
DX8CALL(Clear(0, NULL, flags, Convert_Color(color,dest_alpha), z, stencil));
}
+ Direct3D11_Mirror_Clear(clear_color, clear_z_stencil, color.X, color.Y, color.Z, dest_alpha);
}
void DX8Wrapper::Set_Viewport(CONST D3DVIEWPORT9* pViewport)
@@ -2443,6 +2466,16 @@ void DX8Wrapper::Draw(
vertex_count,
start_index+render_state.iba_offset,
polygon_count));
+
+ // The same draw through the Direct3D 11 backend, into its own back buffer. Only
+ // triangle lists go: a strip or a fan would need its indices rebuilt, and the
+ // engine's own strips are already lists by the time they reach here.
+ if (primitive_type==D3DPT_TRIANGLELIST) {
+ Direct3D11_Draw_Indexed_Triangles(
+ polygon_count*3,
+ start_index+render_state.iba_offset,
+ render_state.index_base_offset+render_state.vba_offset);
+ }
}
break;
case BUFFER_TYPE_SORTING:
@@ -2628,6 +2661,14 @@ void DX8Wrapper::Apply_Render_State_Changes()
0, // OffsetInBytes, D3D9's extra parameter
render_state.vertex_buffers[i]->FVF_Info().Get_FVF_Size()));
DX8_RECORD_VERTEX_BUFFER_CHANGE();
+ // The backend reads one stream. Streams above the first carry the skinning
+ // and shadow data the .vso files take, and nothing generated consumes them yet.
+ if (i==0) {
+ Direct3D11_Mirror_Stream_Source(
+ static_cast<DX8VertexBufferClass*>(render_state.vertex_buffers[i])->Get_DX11_Twin(),
+ render_state.vertex_buffers[i]->FVF_Info().Get_FVF_Size(),
+ 0);
+ }
{
// If the VB format is FVF, set the FVF as a vertex shader
unsigned fvf=render_state.vertex_buffers[i]->FVF_Info().Get_FVF();
@@ -2644,6 +2685,9 @@ void DX8Wrapper::Apply_Render_State_Changes()
}
} else {
DX8CALL(SetStreamSource(i,NULL,0,0));
+ if (i==0) {
+ Direct3D11_Mirror_Stream_Source(NULL,0,0);
+ }
DX8_RECORD_VERTEX_BUFFER_CHANGE();
}
}
@@ -2657,6 +2701,8 @@ void DX8Wrapper::Apply_Render_State_Changes()
// The base vertex index that used to travel here now goes on the draw call.
DX8CALL(SetIndices(
static_cast<DX8IndexBufferClass*>(render_state.index_buffer)->Get_DX8_Index_Buffer()));
+ Direct3D11_Mirror_Indices(
+ static_cast<DX8IndexBufferClass*>(render_state.index_buffer)->Get_DX11_Twin());
DX8_RECORD_INDEX_BUFFER_CHANGE();
break;
case BUFFER_TYPE_SORTING:
@@ -2668,6 +2714,7 @@ void DX8Wrapper::Apply_Render_State_Changes()
}
else {
DX8CALL(SetIndices(NULL));
+ Direct3D11_Mirror_Indices(NULL);
DX8_RECORD_INDEX_BUFFER_CHANGE();
}
}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.h
index 5b3c397f0..43c22fcdf 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.h
@@ -447,6 +447,13 @@ public:
// which is what the D3D8 call meant by it too.
static void _Set_DX8_Render_Target(IDirect3DSurface9 * render_target, IDirect3DSurface9 * depth_buffer);
+ // Every screen-space quad in the game is a four vertex triangle strip drawn straight off the
+ // stack, and there are thirteen of them: the filter that puts the rendered scene back on the
+ // screen, the smudges, the shadow volume's darkening pass. They went to the device directly
+ // and so were invisible to any second backend; this is the one place they pass through.
+ static void _Draw_DX8_Primitive_UP(D3DPRIMITIVETYPE type, unsigned primitive_count,
+ const void * vertices, unsigned stride);
+
static void _Copy_DX8_Rects(
IDirect3DSurface9* pSourceSurface,
CONST RECT* pSourceRectsArray,
@@ -779,12 +786,15 @@ WWINLINE void DX8Wrapper::Set_Vertex_Format(DWORD fvf)
Vertex_Shader=NULL;
DX8CALL(SetVertexShader(NULL));
DX8CALL(SetFVF(Vertex_Format));
+ Direct3D11_Mirror_Vertex_Shader(NULL);
+ Direct3D11_Mirror_Vertex_Format(Vertex_Format);
}
WWINLINE void DX8Wrapper::Set_Vertex_Shader(IDirect3DVertexShader9 * vertex_shader)
{
Vertex_Shader=vertex_shader;
DX8CALL(SetVertexShader(Vertex_Shader));
+ Direct3D11_Mirror_Vertex_Shader(vertex_shader);
}
WWINLINE void DX8Wrapper::Set_Pixel_Shader(IDirect3DPixelShader9 * pixel_shader)
@@ -794,12 +804,19 @@ WWINLINE void DX8Wrapper::Set_Pixel_Shader(IDirect3DPixelShader9 * pixel_shader)
Pixel_Shader=pixel_shader;
DX8CALL(SetPixelShader(Pixel_Shader));
+ Direct3D11_Mirror_Pixel_Shader(pixel_shader);
}
WWINLINE void DX8Wrapper::Set_Vertex_Shader_Constant(int reg, const void* data, int count)
{
int memsize=sizeof(Vector4)*count;
+ // Ahead of the comparison below, not behind it. Invalidate_Cached_Render_States zeroes this
+ // cache without zeroing the device, so a set that writes zeros after one of those is skipped
+ // here while the device really does hold zeros - and the backend, which is not reset by that
+ // call, would keep whatever it was last told.
+ Direct3D11_Mirror_Vertex_Shader_Constant((unsigned)reg, (const float*)data, (unsigned)count);
+
// may be incorrect if shaders are created and destroyed dynamically
if (memcmp(data, &Vertex_Shader_Constants[reg],memsize)==0) return;
@@ -1046,6 +1063,7 @@ WWINLINE void DX8Wrapper::Set_DX8_Texture(unsigned int stage, IDirect3DBaseTextu
Textures[stage] = texture;
if (Textures[stage]) Textures[stage]->AddRef();
DX8CALL(SetTexture(stage, texture));
+ Direct3D11_Mirror_Texture(stage, texture);
DX8_RECORD_TEXTURE_CHANGE();
}
@@ -1344,9 +1362,11 @@ WWINLINE void DX8Wrapper::Set_Projection_Transform_With_Z_Bias(const Matrix4x4&
tmp_zbias*=1.0f / (ZFar - ZNear);
tmp[2][2]-=tmp_zbias*tmp[3][2];
DX8CALL(SetTransform(D3DTS_PROJECTION,(D3DMATRIX*)&tmp));
+ Direct3D11_Mirror_Transform(D3DTS_PROJECTION,(const float*)&tmp);
}
else {
DX8CALL(SetTransform(D3DTS_PROJECTION,(D3DMATRIX*)&ProjectionMatrix));
+ Direct3D11_Mirror_Transform(D3DTS_PROJECTION,(const float*)&ProjectionMatrix);
}
}
@@ -1364,6 +1384,7 @@ WWINLINE void DX8Wrapper::Set_DX8_ZBias(int zbias)
tmp_zbias*=1.0f / (ZFar - ZNear);
tmp[2][2]-=tmp_zbias*tmp[3][2];
DX8CALL(SetTransform(D3DTS_PROJECTION,(D3DMATRIX*)&tmp));
+ Direct3D11_Mirror_Transform(D3DTS_PROJECTION,(const float*)&tmp);
}
else {
// D3D8's D3DRS_ZBIAS took a level from 0 to 16; D3D9's D3DRS_DEPTHBIAS takes a
@@ -1395,6 +1416,7 @@ WWINLINE void DX8Wrapper::Set_Transform(D3DTRANSFORMSTATETYPE transform,const Ma
ZFar=0.0f;
ZNear=0.0f;
DX8CALL(SetTransform(D3DTS_PROJECTION,(D3DMATRIX*)&ProjectionMatrix));
+ Direct3D11_Mirror_Transform(D3DTS_PROJECTION,(const float*)&ProjectionMatrix);
}
break;
default:
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.cpp
new file mode 100644
index 000000000..bb3769493
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.cpp
@@ -0,0 +1,378 @@
+/*
+** 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 "engineshader.h"
+
+#include <stdio.h>
+#include <string.h>
+
+/*
+** The terrain and the roads are eight variations on one program: a base colour, and then a chain of
+** things multiplied into it. Written out of the -dx11dump disassembly, one line of ps_1_1 each:
+**
+** terrain.pso lrp r0, v0.w, t1, t0 ; mul r0, r0, v0
+** terrainnoise.pso the same, then mul r0, r0, t2
+** terrainnoise2.pso the same, then mul r0, r0, t3
+** fterrain.pso mul r0, t1, t0 ; mul r0, r0, v0
+** fterrain0.pso mov r0, t1 ; mul r0, r0, v0
+** fterrainnoise.pso fterrain, then mul r0, r0, t2
+** fterrainnoise2.pso the same, then mul r0, r0, t3
+** roadnoise2.pso mul r0, t0, t1 ; mul r0, r0, t2 ; mul r0, r0, v0
+**
+** lrp dest, a, b, c is c + a * (b - c), so v0.w weights the second layer over the first: that is
+** the terrain blending one ground texture into the next by the alpha in its own vertices. The road
+** one multiplies the vertex colour in last rather than second, which is the same arithmetic until a
+** term saturates.
+*/
+static const char * const TERRAIN_CHAIN[] = { "input.Diffuse", NULL };
+static const char * const TERRAIN_NOISE_CHAIN[] = { "input.Diffuse", "texel2", NULL };
+static const char * const TERRAIN_NOISE_2_CHAIN[] = { "input.Diffuse", "texel2", "texel3", NULL };
+static const char * const ROAD_NOISE_2_CHAIN[] = { "texel2", "input.Diffuse", NULL };
+
+static const char * const TERRAIN_OPENING = "lerp(texel0, texel1, input.Diffuse.a)";
+static const char * const FLAT_TERRAIN_OPENING = "texel1 * texel0";
+static const char * const FLAT_TERRAIN_BASE_OPENING = "texel1";
+static const char * const ROAD_NOISE_2_OPENING = "texel0 * texel1";
+
+// One entry per shipped shader this can write. The file name is the whole key: the engine loads
+// each of them from a fixed path and there is exactly one shader per file. Opening and Chain are
+// set for the multiply-chain programs above and null for the ones written out by hand.
+struct EngineShaderEntry
+{
+ EngineShaderProgram Program;
+ const char * FileName;
+ const char * Name;
+ const char * Opening;
+ const char * const * Chain;
+};
+
+static const EngineShaderEntry ENGINE_SHADERS[] = {
+ { ENGINE_SHADER_TREES, "trees.vso", "engine:trees", NULL, NULL },
+ { ENGINE_SHADER_WATER_TRAPEZOID, "trapezoid water ps.1.1", "engine:trapezoidwater",
+ NULL, NULL },
+ { ENGINE_SHADER_WATER_RIVER, "river water ps.1.1", "engine:riverwater", NULL, NULL },
+ { ENGINE_SHADER_TERRAIN, "terrain.pso", "engine:terrain",
+ TERRAIN_OPENING, TERRAIN_CHAIN },
+ { ENGINE_SHADER_TERRAIN_NOISE, "terrainnoise.pso", "engine:terrainnoise",
+ TERRAIN_OPENING, TERRAIN_NOISE_CHAIN },
+ { ENGINE_SHADER_TERRAIN_NOISE_2, "terrainnoise2.pso", "engine:terrainnoise2",
+ TERRAIN_OPENING, TERRAIN_NOISE_2_CHAIN },
+ { ENGINE_SHADER_FLAT_TERRAIN, "fterrain.pso", "engine:flatterrain",
+ FLAT_TERRAIN_OPENING, TERRAIN_CHAIN },
+ { ENGINE_SHADER_FLAT_TERRAIN_BASE, "fterrain0.pso", "engine:flatterrainbase",
+ FLAT_TERRAIN_BASE_OPENING, TERRAIN_CHAIN },
+ { ENGINE_SHADER_FLAT_TERRAIN_NOISE, "fterrainnoise.pso", "engine:flatterrainnoise",
+ FLAT_TERRAIN_OPENING, TERRAIN_NOISE_CHAIN },
+ { ENGINE_SHADER_FLAT_TERRAIN_NOISE_2, "fterrainnoise2.pso", "engine:flatterrainnoise2",
+ FLAT_TERRAIN_OPENING, TERRAIN_NOISE_2_CHAIN },
+ { ENGINE_SHADER_ROAD_NOISE_2, "roadnoise2.pso", "engine:roadnoise2",
+ ROAD_NOISE_2_OPENING, ROAD_NOISE_2_CHAIN }
+};
+
+static const unsigned ENGINE_SHADER_COUNT = sizeof(ENGINE_SHADERS) / sizeof(ENGINE_SHADERS[0]);
+
+static const EngineShaderEntry * entry_for(EngineShaderProgram program)
+{
+ for (unsigned entry = 0; entry < ENGINE_SHADER_COUNT; ++entry) {
+ if (ENGINE_SHADERS[entry].Program == program) {
+ return &ENGINE_SHADERS[entry];
+ }
+ }
+ return NULL;
+}
+
+// The declaration every transcribed vertex program opens with. The constant bank is the engine's
+// own float4 registers, so the shader indexes them by the same number the SetVertexShaderConstantF
+// call used and the transcription reads like the assembly it came from.
+static void write_preamble(std::string & hlsl)
+{
+ char line[128];
+ snprintf(line, sizeof(line), "cbuffer EngineConstants : register(b0)\n{\n float4 c[%u];\n};\n\n",
+ ENGINE_SHADER_CONSTANTS);
+ hlsl += line;
+}
+
+// ffvertex's output structure, member for member. See the file comment for why it cannot differ.
+static void write_output_structure(std::string & hlsl)
+{
+ hlsl +=
+ "struct Output\n"
+ "{\n"
+ " float4 Position : SV_Position;\n"
+ " float4 Diffuse : COLOR0;\n"
+ " float4 Specular : COLOR1;\n"
+ " float2 TexCoord0 : TEXCOORD0;\n"
+ " float2 TexCoord1 : TEXCOORD1;\n"
+ " float Fog : FOG;\n"
+ "};\n"
+ "\n";
+}
+
+/*
+** Trees.vso, transcribed from the vs_1_1 the translator disassembles:
+**
+** dcl_position v0, dcl_blendweight v1, dcl_blendindices v2, dcl_texcoord v7
+** mov r2, v1.wwzw ; a float3 input reads w as one, so this is (1, 1, v1.z, 1)
+** add r2, v0, -r2 ; r2.z is the vertex height above the tree's own base
+** mov a0.x, v1 ; the sway type, rounded
+** mov r0, c8[a0.x] ; c8 is the no-sway slot, c9 to c18 the ten breezes
+** mad r1, r2.zzzw, r0, v0
+** m4x4 oPos, r1, c4
+** mov r2, v1.yyyw
+** mul oD0, v2, r2 ; the tree's lit shade, with the vertex alpha kept
+** mov oT0, v7
+** add r1, v0, c32
+** mul oT1, r1, c33 ; the shroud coordinate
+**
+** The declaration beside it (W3DTreeBuffer::initData) puts position in register 0, the normal slot
+** in 1 and the D3DCOLOR in 2, which is the byte layout of DX8_FVF_XYZNDUV1. Nothing in the tree
+** vertex is a normal: nx is the sway type, ny the shade the push-aside left, nz the base height.
+**
+** oFog is never written, so the fog factor is one and the trees are drawn unfogged, which is what
+** the Direct3D 9 device does with this shader bound.
+*/
+static void write_trees(std::string & hlsl)
+{
+ write_preamble(hlsl);
+ hlsl +=
+ "struct Input\n"
+ "{\n"
+ " float3 Position : POSITION;\n"
+ " float3 Sway : NORMAL;\n"
+ " float4 Diffuse : COLOR0;\n"
+ " float2 TexCoord0 : TEXCOORD0;\n"
+ "};\n"
+ "\n";
+ write_output_structure(hlsl);
+ hlsl +=
+ "Output main(Input input)\n"
+ "{\n"
+ " Output output;\n"
+ " int sway_type = (int)(input.Sway.x + 0.5);\n"
+ " float height = input.Position.z - input.Sway.z;\n"
+ " float4 swayed = float4(height * c[8 + sway_type].xyz + input.Position, 1.0);\n"
+ " output.Position = float4(dot(swayed, c[4]), dot(swayed, c[5]),\n"
+ " dot(swayed, c[6]), dot(swayed, c[7]));\n"
+ " output.Diffuse = input.Diffuse * float4(input.Sway.yyy, 1.0);\n"
+ " output.Specular = float4(0.0, 0.0, 0.0, 0.0);\n"
+ " output.TexCoord0 = input.TexCoord0;\n"
+ " output.TexCoord1 = ((float4(input.Position, 1.0) + c[32]) * c[33]).xy;\n"
+ " output.Fog = 1.0;\n"
+ " return output;\n"
+ "}\n";
+}
+
+// ffshader's declarations, member for member and in the same order, so a transcribed pixel program
+// is bound with the same constant buffer, the same textures and the same samplers as a generated
+// one. Reading fewer of them than are declared costs nothing.
+static void write_pixel_preamble(std::string & hlsl)
+{
+ for (unsigned stage = 0; stage < MAXIMUM_COMBINER_STAGES; ++stage) {
+ char line[128];
+ snprintf(line, sizeof(line),
+ "Texture2D Texture%u : register(t%u);\n"
+ "SamplerState Sampler%u : register(s%u);\n",
+ stage, stage, stage, stage);
+ hlsl += line;
+ }
+
+ hlsl +=
+ "cbuffer CombinerConstants : register(b0)\n"
+ "{\n"
+ " float4 TextureFactor;\n"
+ " float4 FogColour;\n"
+ " float4 AlphaReference;\n"
+ "};\n"
+ "\n"
+ "struct Input\n"
+ "{\n"
+ " float4 Position : SV_Position;\n"
+ " float4 Diffuse : COLOR0;\n"
+ " float4 Specular : COLOR1;\n";
+
+ for (unsigned stage = 0; stage < MAXIMUM_COMBINER_STAGES; ++stage) {
+ char line[64];
+ snprintf(line, sizeof(line), " float2 TexCoord%u : TEXCOORD%u;\n", stage, stage);
+ hlsl += line;
+ }
+
+ hlsl +=
+ " float Fog : FOG;\n"
+ "};\n"
+ "\n"
+ "float4 main(Input input) : SV_Target\n"
+ "{\n";
+
+ for (unsigned stage = 0; stage < MAXIMUM_COMBINER_STAGES; ++stage) {
+ char line[128];
+ snprintf(line, sizeof(line),
+ " float4 texel%u = Texture%u.Sample(Sampler%u, input.TexCoord%u);\n",
+ stage, stage, stage, stage);
+ hlsl += line;
+ }
+}
+
+/*
+** The trapezoid water, the ps.1.1 W3DWater assembles for every flat water body:
+**
+** tex t0 ; the water texture
+** tex t1 ; white highlights on black
+** tex t2 ; the same highlights, tiled harder, on the camera space position
+** tex t3 ; the shroud, or white where there is none
+** mul r0, v0, t0
+** mad r0.rgb, t1, t2, r0
+** mul r0.rgb, r0, t3
+**
+** Every ps_1_1 instruction clamps its result to zero and one, which is the saturate on each line.
+** The alpha is the vertex alpha times the water texture's and the shroud never touches it: a
+** shrouded stretch of water is dark, not transparent.
+*/
+static void write_trapezoid_water(std::string & hlsl)
+{
+ write_pixel_preamble(hlsl);
+ hlsl +=
+ " float4 current = saturate(input.Diffuse * texel0);\n"
+ " current.rgb = saturate(texel1.rgb * texel2.rgb + current.rgb);\n"
+ " current.rgb = saturate(current.rgb * texel3.rgb);\n";
+}
+
+/*
+** The river water, the same four stages with the sparkles kept apart from the base colour:
+**
+** mul r0.rgb, v0, t0 ; the water, tinted by the vertex colour
+** mov r0.a, t0 ; the vertex alpha carries the shroud and must not fade the water
+** mul r1, t1, t2
+** add r1.rgb, r1, t3
+** mul r1.rgb, r1, v0.a ; the sparkles and the edge glow do get darkened by the shroud
+** +mul r0.a, r0, t3
+** add r0.rgb, r0, r1
+**
+** The + pairs that alpha instruction with the colour one above it, so it reads r0.a as the previous
+** line left it and writes the shroud's alpha into it.
+*/
+static void write_river_water(std::string & hlsl)
+{
+ write_pixel_preamble(hlsl);
+ hlsl +=
+ " float4 current;\n"
+ " current.rgb = saturate(input.Diffuse.rgb * texel0.rgb);\n"
+ " current.a = saturate(texel0.a * texel3.a);\n"
+ " float3 sparkle = saturate(texel1.rgb * texel2.rgb);\n"
+ " sparkle = saturate(sparkle + texel3.rgb);\n"
+ " sparkle = saturate(sparkle * input.Diffuse.a);\n"
+ " current.rgb = saturate(current.rgb + sparkle);\n";
+}
+
+// Every ps_1_1 instruction clamps its result to zero and one, so each step saturates and not only
+// the last: a chain that overflows in the middle and comes back down is a different colour with the
+// clamps than without them.
+static void write_multiply_chain(std::string & hlsl, const EngineShaderEntry & entry)
+{
+ write_pixel_preamble(hlsl);
+
+ hlsl += " float4 current = saturate(";
+ hlsl += entry.Opening;
+ hlsl += ");\n";
+
+ for (const char * const * step = entry.Chain; *step != NULL; ++step) {
+ hlsl += " current = saturate(current * ";
+ hlsl += *step;
+ hlsl += ");\n";
+ }
+}
+
+static char lowered(char character)
+{
+ return (character >= 'A' && character <= 'Z') ? (char)(character - 'A' + 'a') : character;
+}
+
+// The last path component, lowered, compared against the table. The engine writes its paths with
+// backslashes and mixed case, and neither is worth carrying into the table.
+EngineShaderProgram EngineShader_From_File(const char * file_path)
+{
+ if (file_path == NULL) {
+ return ENGINE_SHADER_NONE;
+ }
+
+ const char * name = file_path;
+ for (const char * step = file_path; *step != '\0'; ++step) {
+ if (*step == '\\' || *step == '/') {
+ name = step + 1;
+ }
+ }
+
+ for (unsigned entry = 0; entry < ENGINE_SHADER_COUNT; ++entry) {
+ const char * wanted = ENGINE_SHADERS[entry].FileName;
+ const char * found = name;
+ while (*wanted != '\0' && lowered(*found) == *wanted) {
+ ++wanted;
+ ++found;
+ }
+ if (*wanted == '\0' && *found == '\0') {
+ return ENGINE_SHADERS[entry].Program;
+ }
+ }
+ return ENGINE_SHADER_NONE;
+}
+
+bool EngineShader_Vertex_Program(EngineShaderProgram program, std::string & hlsl)
+{
+ hlsl.clear();
+ switch (program) {
+ case ENGINE_SHADER_TREES:
+ write_trees(hlsl);
+ return true;
+ default:
+ return false;
+ }
+}
+
+bool EngineShader_Pixel_Program(EngineShaderProgram program,
+ const PixelPipelineDescription & pipeline, std::string & hlsl)
+{
+ hlsl.clear();
+
+ const EngineShaderEntry * entry = entry_for(program);
+ if (entry != NULL && entry->Opening != NULL) {
+ write_multiply_chain(hlsl, *entry);
+ }
+ else if (program == ENGINE_SHADER_WATER_TRAPEZOID) {
+ write_trapezoid_water(hlsl);
+ }
+ else if (program == ENGINE_SHADER_WATER_RIVER) {
+ write_river_water(hlsl);
+ }
+ else {
+ return false;
+ }
+
+ if (!CombinerShader_Append_Pixel_Pipeline(pipeline, hlsl)) {
+ return false;
+ }
+
+ hlsl +=
+ " return current;\n"
+ "}\n";
+ return true;
+}
+
+const char * EngineShader_Name(EngineShaderProgram program)
+{
+ const EngineShaderEntry * entry = entry_for(program);
+ return (entry != NULL) ? entry->Name : "engine:none";
+}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.h
new file mode 100644
index 000000000..b301576cc
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.h
@@ -0,0 +1,91 @@
+/*
+** 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 engine's own shaders, rewritten as HLSL.
+**
+** ffvertex and ffshader generate a program out of fixed-function state. Six draws a frame do not
+** use fixed-function state at all: they load a shipped .vso or .pso out of the big archives and
+** bind it, and the state that would describe them is not set. Those are the last draws the
+** Direct3D 11 backend refuses, and no generator can write them, because the program is the shipped
+** bytecode and nothing else says what it does.
+**
+** So it is transcribed by hand, once, from the assembly d3d8shadertranslate hands back. The .vso
+** files ship compiled and their source is not in this tree; -dx11dump writes what the translator
+** disassembled next to the generated programs, and that disassembly is what each function below is
+** a line-for-line reading of. The reading is written into the comment above each one so the next
+** person can check it against the same dump rather than decoding vs_1_1 again.
+**
+** The output structure is ffvertex's, member for member. Shader model 4 links the stages by slot
+** in declaration order, so a program that writes a different set of members links against nothing
+** the pixel half generates.
+*/
+
+#ifndef ENGINESHADER_H
+#define ENGINESHADER_H
+
+#include "ffshader.h"
+
+#include <string>
+
+// The engine sets its shader constants as float4 registers, the way D3D9 takes them, and the
+// backend mirrors the whole bank rather than tracking which register belongs to which program.
+// This is DX8Wrapper's MAX_VERTEX_SHADER_CONSTANTS; the two have to agree or the mirror writes
+// past the buffer the shader declares.
+const unsigned ENGINE_SHADER_CONSTANTS = 96;
+
+// Which of the engine's own shaders a draw has bound. A shader that is not one of these has no
+// D3D11 counterpart, and a draw made with it is refused rather than drawn wrongly. The water's
+// third shader, the environment-mapped one, is not here: it is the only shipped program that uses
+// texbem, and nothing in the measured maps binds it.
+enum EngineShaderProgram
+{
+ ENGINE_SHADER_NONE = 0,
+ ENGINE_SHADER_TREES,
+ ENGINE_SHADER_WATER_TRAPEZOID,
+ ENGINE_SHADER_WATER_RIVER,
+ ENGINE_SHADER_TERRAIN,
+ ENGINE_SHADER_TERRAIN_NOISE,
+ ENGINE_SHADER_TERRAIN_NOISE_2,
+ ENGINE_SHADER_FLAT_TERRAIN,
+ ENGINE_SHADER_FLAT_TERRAIN_BASE,
+ ENGINE_SHADER_FLAT_TERRAIN_NOISE,
+ ENGINE_SHADER_FLAT_TERRAIN_NOISE_2,
+ ENGINE_SHADER_ROAD_NOISE_2
+};
+
+// The name the engine loaded the shader under: a path for the ones that ship as files
+// ("shaders\\Trees.vso"), and the name the registration passes for the ones the water assembles
+// from text at run time. The comparison is on the last path component and it ignores case.
+EngineShaderProgram EngineShader_From_File(const char * file_path);
+
+// The program as HLSL for the D3D11 profile. False for ENGINE_SHADER_NONE, for a program of the
+// other kind, and for anything whose transcription is not written yet, which keeps that draw a
+// refusal.
+bool EngineShader_Vertex_Program(EngineShaderProgram program, std::string & hlsl);
+
+// The pixel half. The alpha test and the fog come from the render state and are written into the
+// program the way ffshader writes them, because D3D9 applies both around a bound pixel shader and
+// D3D11 applies neither.
+bool EngineShader_Pixel_Program(EngineShaderProgram program,
+ const PixelPipelineDescription & pipeline, std::string & hlsl);
+
+// What the pipeline cache keys this program under and what the dump calls its file.
+const char * EngineShader_Name(EngineShaderProgram program);
+
+#endif // ENGINESHADER_H
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.cpp
index 8df5cf4bd..bb0fb15b0 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.cpp
@@ -106,6 +106,52 @@ static bool operation_expression(DWORD operation, const std::string & argument0,
case D3DTOP_LERP:
expression = "lerp(" + argument2 + ", " + argument1 + ", " + argument0 + ")";
return true;
+ case D3DTOP_ADDSIGNED2X:
+ expression = "((" + argument1 + " + " + argument2 + " - 0.5) * 2.0)";
+ return true;
+ case D3DTOP_ADDSMOOTH:
+ expression = "(" + argument1 + " + " + argument2 + " - " + argument1 + " * " + argument2
+ + ")";
+ return true;
+
+ // The four alpha blends differ only in where the blending alpha comes from, and the terrain
+ // uses three of them: the ground layers are blended by the vertex alpha and the noise layers by
+ // the alpha carried in the stage before them.
+ case D3DTOP_BLENDDIFFUSEALPHA:
+ expression = "lerp(" + argument2 + ", " + argument1 + ", input.Diffuse.a)";
+ return true;
+ case D3DTOP_BLENDTEXTUREALPHA:
+ expression = "lerp(" + argument2 + ", " + argument1 + ", texel.a)";
+ return true;
+ case D3DTOP_BLENDFACTORALPHA:
+ expression = "lerp(" + argument2 + ", " + argument1 + ", TextureFactor.a)";
+ return true;
+ case D3DTOP_BLENDCURRENTALPHA:
+ expression = "lerp(" + argument2 + ", " + argument1 + ", current.a)";
+ return true;
+
+ // Premultiplied: the first argument already carries its own alpha, so it is added rather than
+ // interpolated and only the second is faded out.
+ case D3DTOP_BLENDTEXTUREALPHAPM:
+ expression = "(" + argument1 + " + " + argument2 + " * (1.0 - texel.a))";
+ return true;
+
+ // The four modulate-and-add operations, which write a colour built from one argument's alpha
+ // and the other's colour. D3D9 leaves the alpha channel of the result undefined for these and
+ // the engine does not read it, so the alpha here is whatever the arithmetic produces.
+ case D3DTOP_MODULATEALPHA_ADDCOLOR:
+ expression = "(" + argument1 + " + " + argument1 + ".a * " + argument2 + ")";
+ return true;
+ case D3DTOP_MODULATECOLOR_ADDALPHA:
+ expression = "(" + argument1 + " * " + argument2 + " + " + argument1 + ".a)";
+ return true;
+ case D3DTOP_MODULATEINVALPHA_ADDCOLOR:
+ expression = "((1.0 - " + argument1 + ".a) * " + argument2 + " + " + argument1 + ")";
+ return true;
+ case D3DTOP_MODULATEINVCOLOR_ADDALPHA:
+ expression = "((1.0 - " + argument1 + ") * " + argument2 + " + " + argument1 + ".a)";
+ return true;
+
case D3DTOP_DOTPRODUCT3:
// The device works on signed values here and saturates the result into all four channels.
expression = "saturate(dot((" + argument1 + ").rgb * 2.0 - 1.0, ("
@@ -204,10 +250,18 @@ bool CombinerShader_Generate(const CombinerDescription & description, CombinerSh
}
std::string colour_expression;
- std::string alpha_expression;
if (!operation_expression(source.ColourOperation, colour_argument0, colour_argument1,
- colour_argument2, colour_expression)
- || !operation_expression(source.AlphaOperation, alpha_argument0, alpha_argument1,
+ colour_argument2, colour_expression)) {
+ return false;
+ }
+
+ // A stage may disable its alpha operation while its colour operation runs on: the alpha
+ // channel then keeps whatever the stage before it left there. D3D9 says so in one line and
+ // the terrain relies on it, blending its ground layers by an alpha two stages older than
+ // the colour being written.
+ std::string alpha_expression = "current";
+ if (source.AlphaOperation != D3DTOP_DISABLE
+ && !operation_expression(source.AlphaOperation, alpha_argument0, alpha_argument1,
alpha_argument2, alpha_expression)) {
return false;
}
@@ -228,11 +282,15 @@ bool CombinerShader_Generate(const CombinerDescription & description, CombinerSh
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.
+ for (unsigned stage = 0; stage < MAXIMUM_COMBINER_STAGES; ++stage) {
+ char line[128];
+ snprintf(line, sizeof(line),
+ "Texture2D Texture%u : register(t%u);\n"
+ "SamplerState Sampler%u : register(s%u);\n",
+ stage, stage, stage, stage);
+ hlsl += line;
+ }
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"
@@ -241,10 +299,12 @@ bool CombinerShader_Generate(const CombinerDescription & description, CombinerSh
"};\n";
}
else {
- hlsl +=
- "sampler2D Sampler0 : register(s0);\n"
- "sampler2D Sampler1 : register(s1);\n"
- "float4 TextureFactor : register(";
+ for (unsigned stage = 0; stage < MAXIMUM_COMBINER_STAGES; ++stage) {
+ char line[64];
+ snprintf(line, sizeof(line), "sampler2D Sampler%u : register(s%u);\n", stage, stage);
+ hlsl += line;
+ }
+ hlsl += "float4 TextureFactor : register(";
hlsl += TEXTURE_FACTOR_REGISTER;
hlsl += ");\n";
}
@@ -264,9 +324,12 @@ bool CombinerShader_Generate(const CombinerDescription & description, CombinerSh
}
hlsl +=
" float4 Diffuse : COLOR0;\n"
- " float4 Specular : COLOR1;\n"
- " float2 TexCoord0 : TEXCOORD0;\n"
- " float2 TexCoord1 : TEXCOORD1;\n";
+ " float4 Specular : COLOR1;\n";
+ for (unsigned stage = 0; stage < MAXIMUM_COMBINER_STAGES; ++stage) {
+ char line[64];
+ snprintf(line, sizeof(line), " float2 TexCoord%u : TEXCOORD%u;\n", stage, stage);
+ hlsl += line;
+ }
if (target == COMBINER_SHADER_TARGET_D3D11) {
hlsl += " float Fog : FOG;\n";
}
@@ -282,24 +345,9 @@ bool CombinerShader_Generate(const CombinerDescription & description, CombinerSh
" 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;
- }
- }
+ if (target == COMBINER_SHADER_TARGET_D3D11
+ && !CombinerShader_Append_Pixel_Pipeline(description.PixelPipeline, hlsl)) {
+ return false;
}
hlsl +=
@@ -308,6 +356,38 @@ bool CombinerShader_Generate(const CombinerDescription & description, CombinerSh
return true;
}
+// 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.
+bool CombinerShader_Append_Pixel_Pipeline(const PixelPipelineDescription & pipeline,
+ std::string & hlsl)
+{
+ if (pipeline.FogEnabled) {
+ hlsl += " current.rgb = lerp(FogColour.rgb, current.rgb, saturate(input.Fog));\n";
+ }
+
+ if (pipeline.AlphaTestEnabled) {
+ std::string clip;
+ if (!alpha_test_expression(pipeline.AlphaFunction, clip)) {
+ return false;
+ }
+ if (!clip.empty()) {
+ hlsl += " " + clip;
+ }
+ }
+ return true;
+}
+
+std::string CombinerShader_Pipeline_Key(const PixelPipelineDescription & pipeline)
+{
+ char field[32];
+ snprintf(field, sizeof(field), ":A%u,%lu,F%u",
+ pipeline.AlphaTestEnabled ? 1u : 0u,
+ pipeline.AlphaTestEnabled ? pipeline.AlphaFunction : 0ul,
+ pipeline.FogEnabled ? 1u : 0u);
+ return field;
+}
+
std::string CombinerShader_Key(const CombinerDescription & description)
{
std::string key;
@@ -333,10 +413,6 @@ std::string CombinerShader_Key(const CombinerDescription & description)
// 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;
+ key += CombinerShader_Pipeline_Key(description.PixelPipeline);
return key;
}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.h
index 5a3255839..4e5783c9a 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.h
@@ -39,9 +39,10 @@
#include <string>
-// Two is what the game uses. The generator refuses a description with more rather than emitting a
-// shader nobody has compared against anything.
-const unsigned MAXIMUM_COMBINER_STAGES = 2;
+// Two is what the game uses everywhere except the water, which sets four: the river texture, the
+// sparkles, the noise and the shroud. The generator refuses a description with more rather than
+// emitting a shader nobody has compared against anything.
+const unsigned MAXIMUM_COMBINER_STAGES = 4;
// One texture stage, in the terms D3D8 set it in. Arguments carry D3DTA_COMPLEMENT and
// D3DTA_ALPHAREPLICATE the way the device does; the generator applies both.
@@ -104,4 +105,15 @@ bool CombinerShader_Generate(const CombinerDescription & description, CombinerSh
// zeroed, so two descriptions that differ only in a stage nobody reads compare equal.
std::string CombinerShader_Key(const CombinerDescription & description);
+// The alpha test and the fog written into the program, applied to a float4 named current in the
+// order the D3D9 pipeline applies them. Public because a hand-written pixel program has to apply
+// them too: D3D9 does both around a bound pixel shader and D3D11 does neither. False when the
+// comparison function is not one this writes.
+bool CombinerShader_Append_Pixel_Pipeline(const PixelPipelineDescription & pipeline,
+ std::string & hlsl);
+
+// The same two, as the part of a key they account for. Two draws differing in either are two
+// programs on the D3D11 profile whatever else they share.
+std::string CombinerShader_Pipeline_Key(const PixelPipelineDescription & pipeline);
+
#endif
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffvertex.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffvertex.cpp
index 5d4809041..9febbf127 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffvertex.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffvertex.cpp
@@ -27,21 +27,28 @@ static const DWORD COORDINATE_SET_MASK = 0xffff;
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.
+// 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_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;
+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
@@ -168,12 +175,17 @@ static bool append_texture_coordinates(std::string & body,
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;
+ // The format does not carry the set the stage is asking for, which the engine does
+ // on purpose: a shadow quad has a texture stage on and no coordinates in its
+ // vertices. D3D9 reads zeroes there, so this does too. Refusing instead left 202
+ // draws a match out of the picture.
+ snprintf(line, sizeof(line),
+ " float4 generated%u = float4(0.0, 0.0, 0.0, 1.0);\n", stage);
+ }
+ else {
+ snprintf(line, sizeof(line),
+ " float4 generated%u = float4(input.TexCoord%u, 0.0, 1.0);\n", stage, set);
}
- snprintf(line, sizeof(line), " float4 generated%u = float4(input.TexCoord%u, 0.0, 1.0);\n",
- stage, set);
break;
case D3DTSS_TCI_CAMERASPACEPOSITION:
@@ -229,13 +241,16 @@ static void append_constants_d3d9(std::string & hlsl, const VertexPipelineDescri
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);
+ "row_major float4x4 NormalTransform : register(c%u);\n",
+ REGISTER_WORLD_VIEW_PROJECTION, REGISTER_WORLD_VIEW, REGISTER_NORMAL_TRANSFORM);
hlsl += line;
+ for (unsigned stage = 0; stage < MAXIMUM_VERTEX_STAGES; ++stage) {
+ snprintf(line, sizeof(line), "row_major float4x4 TextureMatrix%u : register(c%u);\n",
+ stage, REGISTER_TEXTURE_MATRICES + stage * REGISTERS_PER_MATRIX);
+ hlsl += line;
+ }
+
snprintf(line, sizeof(line),
"float4 MaterialAmbient : register(c%u);\n"
"float4 MaterialDiffuse : register(c%u);\n"
@@ -243,10 +258,11 @@ static void append_constants_d3d9(std::string & hlsl, const VertexPipelineDescri
"float4 MaterialEmissive : register(c%u);\n"
"float4 MaterialPower : register(c%u);\n"
"float4 GlobalAmbient : register(c%u);\n"
- "float4 FogParameters : register(c%u);\n",
+ "float4 FogParameters : register(c%u);\n"
+ "float4 ViewportInverse : 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);
+ REGISTER_FOG_PARAMETERS, REGISTER_VIEWPORT);
hlsl += line;
for (unsigned index = 0; index < description.LightCount; ++index) {
@@ -276,16 +292,23 @@ static void append_constants_d3d11(std::string & hlsl,
"{\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"
+ " row_major float4x4 NormalTransform;\n";
+
+ for (unsigned stage = 0; stage < MAXIMUM_VERTEX_STAGES; ++stage) {
+ char matrix[64];
+ snprintf(matrix, sizeof(matrix), " row_major float4x4 TextureMatrix%u;\n", stage);
+ hlsl += matrix;
+ }
+
+ hlsl +=
" float4 MaterialAmbient;\n"
" float4 MaterialDiffuse;\n"
" float4 MaterialSpecular;\n"
" float4 MaterialEmissive;\n"
" float4 MaterialPower;\n"
" float4 GlobalAmbient;\n"
- " float4 FogParameters;\n";
+ " float4 FogParameters;\n"
+ " float4 ViewportInverse;\n";
for (unsigned index = 0; index < description.LightCount; ++index) {
char line[1024];
@@ -302,6 +325,112 @@ static void append_constants_d3d11(std::string & hlsl,
hlsl += "};\n";
}
+// The coordinate sets the vertex format actually carries. Direct3D 9 let a shader declare an
+// input the format did not supply; D3D11 refuses the input layout for it.
+static void append_input_coordinate_sets(std::string & hlsl, unsigned coordinate_sets)
+{
+ for (unsigned set = 0; set < coordinate_sets && set < MAXIMUM_VERTEX_STAGES; ++set) {
+ char line[64];
+ snprintf(line, sizeof(line), " float2 TexCoord%u : TEXCOORD%u;\n", set, set);
+ hlsl += line;
+ }
+}
+
+// What every generated vertex program writes, whatever it was generated from. Shader model 4
+// links the stages by slot in declaration order, so this structure and ffshader's input structure
+// are one thing in two files: a program that writes a different set links against nothing.
+static void append_output_structure(std::string & hlsl, bool for_d3d11)
+{
+ hlsl +=
+ "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";
+
+ for (unsigned stage = 0; stage < MAXIMUM_VERTEX_STAGES; ++stage) {
+ char line[64];
+ snprintf(line, sizeof(line), " float2 TexCoord%u : TEXCOORD%u;\n", stage, stage);
+ hlsl += line;
+ }
+
+ hlsl +=
+ " float Fog : FOG;\n"
+ "};\n"
+ "\n";
+}
+
+// The whole program for a pre-transformed vertex. D3D9 takes x and y as pixels inside the
+// viewport, z as the depth it will write and the fourth float as the reciprocal of w; clip space
+// wants the opposite of all four, so the position is mapped back and multiplied by w, which is what
+// keeps the texture coordinates perspective correct on the rare quad whose w is not one.
+static bool generate_pretransformed(const VertexPipelineDescription & description,
+ VertexShaderTarget target, std::string & hlsl)
+{
+ const bool for_d3d11 = (target == VERTEX_SHADER_TARGET_D3D11);
+ const unsigned coordinate_sets = texture_coordinate_set_count(description.FVF);
+
+ 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"
+ " float4 Position : POSITION;\n";
+ if (has_diffuse(description.FVF)) {
+ hlsl += " float4 Diffuse : COLOR0;\n";
+ }
+ append_input_coordinate_sets(hlsl, coordinate_sets);
+ hlsl +=
+ "};\n"
+ "\n";
+ append_output_structure(hlsl, for_d3d11);
+ hlsl +=
+ "Output main(Input input)\n"
+ "{\n"
+ " Output output;\n"
+ " float reciprocal_w = (input.Position.w == 0.0) ? 1.0 : input.Position.w;\n"
+ " float w = 1.0 / reciprocal_w;\n"
+ " 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";
+
+ for (unsigned stage = 0; stage < MAXIMUM_VERTEX_STAGES; ++stage) {
+ const unsigned set = (stage < description.StageCount)
+ ? (description.Stages[stage].TextureCoordinateIndex & COORDINATE_SET_MASK)
+ : 0;
+ char line[128];
+ if (stage < description.StageCount && set < coordinate_sets) {
+ snprintf(line, sizeof(line), " output.TexCoord%u = input.TexCoord%u;\n", stage, set);
+ }
+ else {
+ snprintf(line, sizeof(line), " output.TexCoord%u = float2(0.0, 0.0);\n", stage);
+ }
+ hlsl += line;
+ }
+
+ if (has_diffuse(description.FVF)) {
+ hlsl += " output.Diffuse = input.Diffuse;\n";
+ }
+ else {
+ hlsl += " output.Diffuse = float4(1.0, 1.0, 1.0, 1.0);\n";
+ }
+
+ hlsl +=
+ " output.Specular = float4(0.0, 0.0, 0.0, 0.0);\n"
+ " output.Fog = 1.0;\n"
+ " return output;\n"
+ "}\n";
+ return true;
+}
+
bool VertexShader_Generate(const VertexPipelineDescription & description,
VertexShaderTarget target, std::string & hlsl)
{
@@ -316,10 +445,13 @@ bool VertexShader_Generate(const VertexPipelineDescription & description,
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.
+ // A pre-transformed vertex has been through the transform, the lighting and the coordinate
+ // generation already: its position is in pixels, its colour is in the vertex, and D3D9 reads
+ // the texture coordinates straight out of the format whatever the stage's generation mode
+ // says. All the shader has to do is put the pixels back into clip space, so it is written
+ // here whole rather than sharing the body below.
if (is_pretransformed(description.FVF)) {
- return false;
+ return generate_pretransformed(description, target, hlsl);
}
for (unsigned index = 0; index < description.LightCount; ++index) {
@@ -428,29 +560,33 @@ bool VertexShader_Generate(const VertexPipelineDescription & description,
append_constants_d3d9(hlsl, description);
}
+ // The input signature carries exactly what the vertex format carries, and no more. Direct3D 9
+ // let a shader declare an input the format did not supply and read zeroes out of it; D3D11
+ // refuses the input layout outright, which is a draw that does not happen rather than a draw
+ // that looks slightly wrong - 62534 of them in two minutes of Tournament Desert, which is every
+ // model in the game. What the format leaves out is filled in below with the value the fixed
+ // function pipeline would have used.
+ const unsigned coordinate_sets = texture_coordinate_set_count(description.FVF);
+
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";
+ // Position stays three floats even for a pretransformed format, where the layout element has
+ // four: the extra one is the reciprocal homogeneous w and the body does not read it.
+ hlsl += " float3 Position : POSITION;\n";
+ if (has_normal(description.FVF)) {
+ hlsl += " float3 Normal : NORMAL;\n";
+ }
+ if (has_diffuse(description.FVF)) {
+ hlsl += " float4 Diffuse : COLOR0;\n";
+ }
+ append_input_coordinate_sets(hlsl, coordinate_sets);
hlsl +=
"};\n"
- "\n"
+ "\n";
+ append_output_structure(hlsl, for_d3d11);
+ hlsl +=
"Output main(Input input)\n"
"{\n"
" Output output;\n";
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffvertex.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffvertex.h
index 78a0fa41d..7ff6140d1 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffvertex.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffvertex.h
@@ -43,9 +43,10 @@
#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;
+// The engine's widest vertex format carries four coordinate sets and the water uses all four
+// stages: the river texture, the sparkles, the noise generated from the camera space position, and
+// the shroud. Everything else in the game sets two. A fifth is a refusal.
+const unsigned MAXIMUM_VERTEX_STAGES = 4;
// 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.
diff --git a/GeneralsMD/Code/Tests/test_dx11state.cpp b/GeneralsMD/Code/Tests/test_dx11state.cpp
index abfee22f1..d1a2cd47c 100644
--- a/GeneralsMD/Code/Tests/test_dx11state.cpp
+++ b/GeneralsMD/Code/Tests/test_dx11state.cpp
@@ -74,6 +74,25 @@ TEST(dx11state_the_blend_the_game_uses_most_translates)
CHECK_EQ(blend.RenderTarget[0].DestBlendAlpha, blend.RenderTarget[0].DestBlend);
}
+TEST(dx11state_a_colour_factor_becomes_its_alpha_channel_in_the_alpha_slots)
+{
+ // The terrain's cloud pass multiplies itself into the frame buffer with D3DBLEND_DESTCOLOR.
+ // D3D11 refuses a colour factor in SrcBlendAlpha or DestBlendAlpha outright - CreateBlendState
+ // fails, the draw then runs with the default state, and the pass paints over the ground
+ // instead of darkening it. D3D9 reads the factor's own alpha channel, so these do too.
+ DX11StateBlockClass block;
+ block.Set_Render_State(D3DRS_ALPHABLENDENABLE, TRUE);
+ block.Set_Render_State(D3DRS_SRCBLEND, D3DBLEND_DESTCOLOR);
+ block.Set_Render_State(D3DRS_DESTBLEND, D3DBLEND_INVSRCCOLOR);
+
+ D3D11_BLEND_DESC blend;
+ block.Build_Blend_Description(blend);
+ CHECK_EQ(blend.RenderTarget[0].SrcBlend, D3D11_BLEND_DEST_COLOR);
+ CHECK_EQ(blend.RenderTarget[0].DestBlend, D3D11_BLEND_INV_SRC_COLOR);
+ CHECK_EQ(blend.RenderTarget[0].SrcBlendAlpha, D3D11_BLEND_DEST_ALPHA);
+ CHECK_EQ(blend.RenderTarget[0].DestBlendAlpha, D3D11_BLEND_INV_SRC_ALPHA);
+}
+
TEST(dx11state_every_blend_factor_has_a_translation)
{
CHECK_EQ(DX11State_Translate_Blend(D3DBLEND_ZERO), D3D11_BLEND_ZERO);
diff --git a/GeneralsMD/Code/Tests/test_dx11texture.cpp b/GeneralsMD/Code/Tests/test_dx11texture.cpp
new file mode 100644
index 000000000..8c7100700
--- /dev/null
+++ b/GeneralsMD/Code/Tests/test_dx11texture.cpp
@@ -0,0 +1,278 @@
+/*
+** 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 Direct3D 9 texture, made and then read back.
+//
+// This needs both devices, because the whole point of the file under test is that it reads a
+// texture out of one API and writes it into the other. The D3D9 device is created the way
+// test_dx9_smoke creates one; a machine with no D3D9 device at all reports the tests as skipped
+// rather than failing, since there is nothing to check there.
+//
+// What has to hold is that the pixels arrive unchanged, that a second bind of the same texture
+// finds the copy instead of making another, and that an X8R8G8B8 texture - whose unused byte the
+// loaders leave at whatever it happens to be - comes out opaque rather than invisible.
+
+#include "test_harness.h"
+
+#include "dx11device.h"
+#include "dx11texture.h"
+
+#include <d3d9.h>
+#include <d3d11.h>
+#include <windows.h>
+#include <string.h>
+
+static const unsigned TEXTURE_SIZE = 8;
+static const unsigned ONE_LEVEL = 1;
+static const unsigned char TRANSPARENT_UNUSED_BYTE = 0x00;
+
+// The D3D9 device the copy is read from, plus the window it needs, torn down together.
+class Direct3D9Fixture
+{
+public:
+ Direct3D9Fixture() : Window(NULL), Direct3D(NULL), Device(NULL) {}
+
+ ~Direct3D9Fixture()
+ {
+ if (Device != NULL) {
+ Device->Release();
+ }
+ if (Direct3D != NULL) {
+ Direct3D->Release();
+ }
+ if (Window != NULL) {
+ DestroyWindow(Window);
+ }
+ }
+
+ bool Create()
+ {
+ Window = CreateWindowExA(0, "STATIC", "dx11texture", WS_OVERLAPPED, 0, 0, 64, 64, NULL,
+ NULL, GetModuleHandle(NULL), NULL);
+ if (Window == NULL) {
+ return false;
+ }
+
+ Direct3D = Direct3DCreate9(D3D_SDK_VERSION);
+ if (Direct3D == NULL) {
+ return false;
+ }
+
+ D3DDISPLAYMODE display_mode;
+ if (FAILED(Direct3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &display_mode))) {
+ return false;
+ }
+
+ D3DPRESENT_PARAMETERS present;
+ memset(&present, 0, sizeof(present));
+ present.BackBufferWidth = 64;
+ present.BackBufferHeight = 64;
+ present.Windowed = TRUE;
+ present.SwapEffect = D3DSWAPEFFECT_DISCARD;
+ present.BackBufferFormat = display_mode.Format;
+ present.hDeviceWindow = Window;
+
+ return SUCCEEDED(Direct3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, Window,
+ D3DCREATE_SOFTWARE_VERTEXPROCESSING, &present, &Device));
+ }
+
+ IDirect3DDevice9 * Get() { return Device; }
+
+private:
+ Direct3D9Fixture(const Direct3D9Fixture &);
+ Direct3D9Fixture & operator=(const Direct3D9Fixture &);
+
+ HWND Window;
+ IDirect3D9 * Direct3D;
+ IDirect3DDevice9 * Device;
+};
+
+// A managed texture with a known pattern in it, which is what every loader in the engine produces.
+static IDirect3DTexture9 * filled_texture(IDirect3DDevice9 * device, D3DFORMAT format,
+ unsigned char unused_byte)
+{
+ IDirect3DTexture9 * texture = NULL;
+ if (FAILED(device->CreateTexture(TEXTURE_SIZE, TEXTURE_SIZE, ONE_LEVEL, 0, format,
+ D3DPOOL_MANAGED, &texture, NULL))) {
+ return NULL;
+ }
+
+ D3DLOCKED_RECT locked;
+ if (FAILED(texture->LockRect(0, &locked, NULL, 0))) {
+ texture->Release();
+ return NULL;
+ }
+
+ for (unsigned row = 0; row < TEXTURE_SIZE; ++row) {
+ unsigned char * out = (unsigned char *)locked.pBits + row * locked.Pitch;
+ for (unsigned column = 0; column < TEXTURE_SIZE; ++column) {
+ out[column * 4 + 0] = (unsigned char)column; // blue
+ out[column * 4 + 1] = (unsigned char)row; // green
+ out[column * 4 + 2] = (unsigned char)(row + column); // red
+ out[column * 4 + 3] = unused_byte;
+ }
+ }
+ texture->UnlockRect(0);
+
+ return texture;
+}
+
+// The copy, level zero, through a staging texture - the only way to see what UpdateSubresource put
+// in a default-usage texture.
+static bool read_back(DX11DeviceClass & device, ID3D11ShaderResourceView * view,
+ unsigned char * out, unsigned out_pitch)
+{
+ ID3D11Resource * resource = NULL;
+ view->GetResource(&resource);
+
+ D3D11_TEXTURE2D_DESC description;
+ ((ID3D11Texture2D *)resource)->GetDesc(&description);
+ description.Usage = D3D11_USAGE_STAGING;
+ description.BindFlags = 0;
+ description.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
+
+ ID3D11Texture2D * staging = NULL;
+ if (FAILED(device.Get_Device()->CreateTexture2D(&description, NULL, &staging))) {
+ resource->Release();
+ return false;
+ }
+
+ device.Get_Context()->CopyResource(staging, resource);
+
+ D3D11_MAPPED_SUBRESOURCE mapped;
+ const bool mapped_ok =
+ SUCCEEDED(device.Get_Context()->Map(staging, 0, D3D11_MAP_READ, 0, &mapped));
+ if (mapped_ok) {
+ for (unsigned row = 0; row < TEXTURE_SIZE; ++row) {
+ memcpy(out + row * out_pitch, (const unsigned char *)mapped.pData + row * mapped.RowPitch,
+ out_pitch);
+ }
+ device.Get_Context()->Unmap(staging, 0);
+ }
+
+ staging->Release();
+ resource->Release();
+ return mapped_ok;
+}
+
+TEST(dx11texture_a_managed_texture_arrives_pixel_for_pixel)
+{
+ Direct3D9Fixture d3d9;
+ if (!d3d9.Create()) {
+ printf("skip: no Direct3D 9 device on this machine\n");
+ return;
+ }
+
+ DX11DeviceClass d3d11;
+ CHECK(d3d11.Create_Offscreen());
+
+ IDirect3DTexture9 * texture = filled_texture(d3d9.Get(), D3DFMT_A8R8G8B8, 0x80);
+ CHECK(texture != NULL);
+
+ ID3D11ShaderResourceView * view =
+ DX11Texture_Mirror(d3d11.Get_Device(), d3d11.Get_Context(), texture);
+ CHECK(view != NULL);
+
+ unsigned char pixels[TEXTURE_SIZE * TEXTURE_SIZE * 4];
+ CHECK(read_back(d3d11, view, pixels, TEXTURE_SIZE * 4));
+
+ for (unsigned row = 0; row < TEXTURE_SIZE; ++row) {
+ for (unsigned column = 0; column < TEXTURE_SIZE; ++column) {
+ const unsigned char * pixel = pixels + row * TEXTURE_SIZE * 4 + column * 4;
+ CHECK_EQ(pixel[0], (unsigned char)column);
+ CHECK_EQ(pixel[1], (unsigned char)row);
+ CHECK_EQ(pixel[2], (unsigned char)(row + column));
+ CHECK_EQ(pixel[3], 0x80);
+ }
+ }
+
+ texture->Release();
+}
+
+// The second bind of a texture has to find the copy on it. Without that the whole texture is read
+// and uploaded again on every bind, which is several hundred times a frame.
+TEST(dx11texture_a_second_bind_finds_the_copy)
+{
+ Direct3D9Fixture d3d9;
+ if (!d3d9.Create()) {
+ printf("skip: no Direct3D 9 device on this machine\n");
+ return;
+ }
+
+ DX11DeviceClass d3d11;
+ CHECK(d3d11.Create_Offscreen());
+
+ IDirect3DTexture9 * texture = filled_texture(d3d9.Get(), D3DFMT_A8R8G8B8, 0xff);
+ CHECK(texture != NULL);
+
+ unsigned mirrored_before = 0;
+ unsigned reused_before = 0;
+ unsigned refused_before = 0;
+ DX11Texture_Statistics(mirrored_before, reused_before, refused_before);
+
+ ID3D11ShaderResourceView * first =
+ DX11Texture_Mirror(d3d11.Get_Device(), d3d11.Get_Context(), texture);
+ ID3D11ShaderResourceView * second =
+ DX11Texture_Mirror(d3d11.Get_Device(), d3d11.Get_Context(), texture);
+ CHECK(first != NULL);
+ CHECK(first == second);
+
+ unsigned mirrored_after = 0;
+ unsigned reused_after = 0;
+ unsigned refused_after = 0;
+ DX11Texture_Statistics(mirrored_after, reused_after, refused_after);
+ CHECK_EQ(mirrored_after - mirrored_before, 1u);
+ CHECK_EQ(reused_after - reused_before, 1u);
+
+ texture->Release();
+}
+
+// X8R8G8B8 has no alpha channel and the byte where DXGI reads one holds whatever the loader left.
+// Left alone, a texture whose unused byte is zero is a texture that draws nothing at all.
+TEST(dx11texture_an_alphaless_format_comes_out_opaque)
+{
+ Direct3D9Fixture d3d9;
+ if (!d3d9.Create()) {
+ printf("skip: no Direct3D 9 device on this machine\n");
+ return;
+ }
+
+ DX11DeviceClass d3d11;
+ CHECK(d3d11.Create_Offscreen());
+
+ IDirect3DTexture9 * texture =
+ filled_texture(d3d9.Get(), D3DFMT_X8R8G8B8, TRANSPARENT_UNUSED_BYTE);
+ CHECK(texture != NULL);
+
+ ID3D11ShaderResourceView * view =
+ DX11Texture_Mirror(d3d11.Get_Device(), d3d11.Get_Context(), texture);
+ CHECK(view != NULL);
+
+ unsigned char pixels[TEXTURE_SIZE * TEXTURE_SIZE * 4];
+ CHECK(read_back(d3d11, view, pixels, TEXTURE_SIZE * 4));
+
+ for (unsigned row = 0; row < TEXTURE_SIZE; ++row) {
+ for (unsigned column = 0; column < TEXTURE_SIZE; ++column) {
+ const unsigned char * pixel = pixels + row * TEXTURE_SIZE * 4 + column * 4;
+ CHECK_EQ(pixel[0], (unsigned char)column);
+ CHECK_EQ(pixel[3], 0xff);
+ }
+ }
+
+ texture->Release();
+}
diff --git a/GeneralsMD/Code/Tests/test_dx11twin.cpp b/GeneralsMD/Code/Tests/test_dx11twin.cpp
new file mode 100644
index 000000000..02834f991
--- /dev/null
+++ b/GeneralsMD/Code/Tests/test_dx11twin.cpp
@@ -0,0 +1,198 @@
+/*
+** 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 moved lock.
+//
+// The engine writes its vertices and indices once, into a write-only D3D9 buffer that nothing can
+// read back, so the only chance to build the D3D11 copy is while the write is happening. What has
+// to hold is that the D3D9 side ends up byte for byte what it would have been without the twin and
+// the D3D11 side ends up holding the same thing. Both sides are read back here: the D3D9 one is a
+// heap block standing in for the mapped pointer, and the D3D11 one comes back through a staging
+// buffer, which is the only way to see what UpdateSubresource actually wrote.
+
+#include "test_harness.h"
+
+#include "dx11device.h"
+#include "dx11twin.h"
+
+#include <d3d9.h>
+#include <d3d11.h>
+#include <string.h>
+
+static const unsigned BUFFER_BYTES = 256;
+static const unsigned RANGE_OFFSET = 64;
+static const unsigned RANGE_BYTES = 32;
+static const unsigned char UNWRITTEN_BYTE = 0xCD;
+
+// What UpdateSubresource left in the buffer. A default-usage buffer cannot be mapped, so the read
+// goes through a staging copy of it.
+static bool read_back(DX11DeviceClass & device, ID3D11Buffer * buffer, unsigned char * out,
+ unsigned byte_count)
+{
+ D3D11_BUFFER_DESC desc;
+ memset(&desc, 0, sizeof(desc));
+ desc.ByteWidth = byte_count;
+ desc.Usage = D3D11_USAGE_STAGING;
+ desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
+
+ ID3D11Buffer * staging = NULL;
+ if (FAILED(device.Get_Device()->CreateBuffer(&desc, NULL, &staging))) {
+ return false;
+ }
+
+ device.Get_Context()->CopyResource(staging, buffer);
+
+ D3D11_MAPPED_SUBRESOURCE mapped;
+ const bool mapped_ok =
+ SUCCEEDED(device.Get_Context()->Map(staging, 0, D3D11_MAP_READ, 0, &mapped));
+ if (mapped_ok) {
+ memcpy(out, mapped.pData, byte_count);
+ device.Get_Context()->Unmap(staging, 0);
+ }
+
+ staging->Release();
+ return mapped_ok;
+}
+
+// Without -dx11 there is no twin, and a lock that asks for one has to come back with nothing so
+// every caller keeps the pointer D3D9 gave it. Ending a lock that never began is the same path a
+// buffer takes on an ordinary run, several thousand times a frame.
+TEST(dx11twin_a_lock_without_a_twin_hands_back_nothing)
+{
+ unsigned char d3d9_memory[BUFFER_BYTES];
+ memset(d3d9_memory, UNWRITTEN_BYTE, sizeof(d3d9_memory));
+
+ DX11BufferLockClass lock;
+ CHECK(lock.Begin(NULL, d3d9_memory, 0, 0, 0) == NULL);
+ lock.End();
+
+ CHECK_EQ(d3d9_memory[0], UNWRITTEN_BYTE);
+}
+
+// A whole-buffer write, which is what a mesh does once when it loads. Zero for the count means to
+// the end, the way D3D9's own lock reads it.
+TEST(dx11twin_a_whole_buffer_write_lands_on_both_sides)
+{
+ DX11DeviceClass device;
+ device.Request_Debug_Layer();
+ CHECK(device.Create_Offscreen());
+
+ DX11BufferTwinClass * twin =
+ DX11Twin_Create_Vertex_Buffer(device.Get_Device(), device.Get_Context(), BUFFER_BYTES, false);
+ CHECK(twin != NULL);
+
+ unsigned char d3d9_memory[BUFFER_BYTES];
+ memset(d3d9_memory, UNWRITTEN_BYTE, sizeof(d3d9_memory));
+
+ DX11BufferLockClass lock;
+ unsigned char * write = (unsigned char *)lock.Begin(twin, d3d9_memory, 0, 0, 0);
+ CHECK(write == twin->Mirror());
+ for (unsigned i = 0; i < BUFFER_BYTES; ++i) {
+ write[i] = (unsigned char)i;
+ }
+ lock.End();
+
+ unsigned char d3d11_memory[BUFFER_BYTES];
+ CHECK(read_back(device, twin->Buffer(), d3d11_memory, BUFFER_BYTES));
+
+ for (unsigned i = 0; i < BUFFER_BYTES; ++i) {
+ CHECK_EQ(d3d9_memory[i], (unsigned char)i);
+ CHECK_EQ(d3d11_memory[i], (unsigned char)i);
+ }
+
+ delete twin;
+}
+
+// The dynamic buffers, which are refilled hundreds of times a frame and are the reason the upload
+// has two shapes. A partial UpdateSubresource cannot rename the buffer, so it waits for every draw
+// still reading it; mapping with D3D9's own DISCARD and NOOVERWRITE does not. What has to hold is
+// that the second, non-discarding write leaves the first one intact, because that is exactly what
+// the engine assumes when it fills one dynamic buffer in batches and draws between them.
+TEST(dx11twin_a_dynamic_buffer_keeps_what_a_no_overwrite_write_did_not_touch)
+{
+ DX11DeviceClass device;
+ device.Request_Debug_Layer();
+ CHECK(device.Create_Offscreen());
+
+ DX11BufferTwinClass * twin =
+ DX11Twin_Create_Vertex_Buffer(device.Get_Device(), device.Get_Context(), BUFFER_BYTES, true);
+ CHECK(twin != NULL);
+
+ unsigned char d3d9_memory[BUFFER_BYTES];
+ memset(d3d9_memory, UNWRITTEN_BYTE, sizeof(d3d9_memory));
+
+ DX11BufferLockClass first;
+ memset(first.Begin(twin, d3d9_memory, 0, RANGE_BYTES, D3DLOCK_DISCARD), 0x11, RANGE_BYTES);
+ first.End();
+
+ DX11BufferLockClass second;
+ memset(second.Begin(twin, d3d9_memory + RANGE_OFFSET, RANGE_OFFSET, RANGE_BYTES,
+ D3DLOCK_NOOVERWRITE), 0x22, RANGE_BYTES);
+ second.End();
+
+ unsigned char d3d11_memory[BUFFER_BYTES];
+ CHECK(read_back(device, twin->Buffer(), d3d11_memory, BUFFER_BYTES));
+
+ for (unsigned i = 0; i < RANGE_BYTES; ++i) {
+ CHECK_EQ(d3d11_memory[i], 0x11);
+ CHECK_EQ(d3d11_memory[RANGE_OFFSET + i], 0x22);
+ CHECK_EQ(d3d9_memory[i], 0x11);
+ CHECK_EQ(d3d9_memory[RANGE_OFFSET + i], 0x22);
+ }
+
+ delete twin;
+}
+
+// An append lock, which is how the terrain and the dynamic buffers fill one region at a time. The
+// pointer starts at the offset, and everything outside the range is left as it was - a twin that
+// uploaded the whole buffer on every partial write would still draw correctly and would cost the
+// bandwidth of the entire buffer per lock.
+TEST(dx11twin_a_ranged_write_touches_only_its_range)
+{
+ DX11DeviceClass device;
+ device.Request_Debug_Layer();
+ CHECK(device.Create_Offscreen());
+
+ DX11BufferTwinClass * twin =
+ DX11Twin_Create_Index_Buffer(device.Get_Device(), device.Get_Context(), BUFFER_BYTES, false);
+ CHECK(twin != NULL);
+
+ memset(twin->Mirror(), 0, BUFFER_BYTES);
+ twin->Upload(0, 0, false);
+
+ unsigned char d3d9_memory[BUFFER_BYTES];
+ memset(d3d9_memory, UNWRITTEN_BYTE, sizeof(d3d9_memory));
+
+ DX11BufferLockClass lock;
+ unsigned char * write =
+ (unsigned char *)lock.Begin(twin, d3d9_memory + RANGE_OFFSET, RANGE_OFFSET, RANGE_BYTES, 0);
+ CHECK(write == twin->Mirror() + RANGE_OFFSET);
+ memset(write, 0x7F, RANGE_BYTES);
+ lock.End();
+
+ unsigned char d3d11_memory[BUFFER_BYTES];
+ CHECK(read_back(device, twin->Buffer(), d3d11_memory, BUFFER_BYTES));
+
+ for (unsigned i = 0; i < BUFFER_BYTES; ++i) {
+ const bool in_range = i >= RANGE_OFFSET && i < RANGE_OFFSET + RANGE_BYTES;
+ CHECK_EQ(d3d9_memory[i], in_range ? 0x7F : UNWRITTEN_BYTE);
+ CHECK_EQ(d3d11_memory[i], in_range ? 0x7F : 0x00);
+ }
+
+ delete twin;
+}
diff --git a/GeneralsMD/Code/Tests/test_engineshader.cpp b/GeneralsMD/Code/Tests/test_engineshader.cpp
new file mode 100644
index 000000000..9ac7cbb99
--- /dev/null
+++ b/GeneralsMD/Code/Tests/test_engineshader.cpp
@@ -0,0 +1,349 @@
+/*
+** 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 transcribed engine shaders: what they say, and whether the compiler takes them.
+//
+// A transcription has no generator to argue with - it is one hand-written program per shipped
+// file - so what is worth pinning is the reading of the assembly rather than the shape of the
+// text. Each check below names the instruction it came from, so a term that turns out wrong on
+// screen can be traced back to the line of vs_1_1 it was read out of.
+//
+// The compile check loads D3DCompile out of d3dcompiler_47.dll, which ships with Windows; a
+// machine without it skips rather than fails.
+
+#include "test_harness.h"
+
+#include "engineshader.h"
+
+#include <d3dcommon.h>
+#include <string>
+#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 bool contains(const std::string & text, const char * fragment)
+{
+ return text.find(fragment) != std::string::npos;
+}
+
+// Everything off, which is what the water draws with: no alpha test and no fog.
+static PixelPipelineDescription plain_pipeline()
+{
+ PixelPipelineDescription pipeline;
+ memset(&pipeline, 0, sizeof(pipeline));
+ return pipeline;
+}
+
+TEST(engineshader_names_a_shader_by_its_file_whatever_case_the_path_is_in)
+{
+ CHECK(EngineShader_From_File("shaders\\Trees.vso") == ENGINE_SHADER_TREES);
+ CHECK(EngineShader_From_File("SHADERS/TREES.VSO") == ENGINE_SHADER_TREES);
+ CHECK(EngineShader_From_File("Trees.vso") == ENGINE_SHADER_TREES);
+ CHECK(EngineShader_From_File("trapezoid water ps.1.1") == ENGINE_SHADER_WATER_TRAPEZOID);
+ CHECK(EngineShader_From_File("river water ps.1.1") == ENGINE_SHADER_WATER_RIVER);
+ CHECK(EngineShader_From_File("shaders\\terrainnoise2.pso") == ENGINE_SHADER_TERRAIN_NOISE_2);
+ CHECK(EngineShader_From_File("shaders\\fterrain0.pso") == ENGINE_SHADER_FLAT_TERRAIN_BASE);
+ CHECK(EngineShader_From_File("shaders\\roadnoise2.pso") == ENGINE_SHADER_ROAD_NOISE_2);
+}
+
+// Every program the table names has to write something, or a draw that binds it is refused with a
+// name that says it is covered.
+TEST(engineshader_writes_every_program_it_names)
+{
+ static const EngineShaderProgram PIXEL_PROGRAMS[] = {
+ ENGINE_SHADER_WATER_TRAPEZOID, ENGINE_SHADER_WATER_RIVER,
+ ENGINE_SHADER_TERRAIN, ENGINE_SHADER_TERRAIN_NOISE, ENGINE_SHADER_TERRAIN_NOISE_2,
+ ENGINE_SHADER_FLAT_TERRAIN, ENGINE_SHADER_FLAT_TERRAIN_BASE,
+ ENGINE_SHADER_FLAT_TERRAIN_NOISE, ENGINE_SHADER_FLAT_TERRAIN_NOISE_2,
+ ENGINE_SHADER_ROAD_NOISE_2
+ };
+
+ for (unsigned index = 0; index < sizeof(PIXEL_PROGRAMS) / sizeof(PIXEL_PROGRAMS[0]); ++index) {
+ std::string hlsl;
+ CHECK(EngineShader_Pixel_Program(PIXEL_PROGRAMS[index], plain_pipeline(), hlsl));
+ CHECK(contains(hlsl, "return current;"));
+ }
+}
+
+// The shaders with no transcription yet stay foreign, which is what keeps a draw that binds one a
+// refusal instead of a draw with the wrong program.
+TEST(engineshader_has_no_program_for_a_shader_nobody_transcribed)
+{
+ CHECK(EngineShader_From_File("shaders\\wave.vso") == ENGINE_SHADER_NONE);
+ CHECK(EngineShader_From_File("shaders\\monochrome.pso") == ENGINE_SHADER_NONE);
+ CHECK(EngineShader_From_File("environment water ps.1.1") == ENGINE_SHADER_NONE);
+ CHECK(EngineShader_From_File("Treesomething.vso") == ENGINE_SHADER_NONE);
+ CHECK(EngineShader_From_File(NULL) == ENGINE_SHADER_NONE);
+
+ std::string hlsl;
+ CHECK(!EngineShader_Vertex_Program(ENGINE_SHADER_NONE, hlsl));
+ CHECK(!EngineShader_Pixel_Program(ENGINE_SHADER_NONE, plain_pipeline(), hlsl));
+}
+
+// The two halves are not interchangeable: asking for the tree program as a pixel shader, or a water
+// one as a vertex shader, is a mistake the caller has to be told about rather than a program.
+TEST(engineshader_keeps_the_two_halves_apart)
+{
+ std::string hlsl;
+ CHECK(!EngineShader_Pixel_Program(ENGINE_SHADER_TREES, plain_pipeline(), hlsl));
+ CHECK(!EngineShader_Vertex_Program(ENGINE_SHADER_WATER_TRAPEZOID, hlsl));
+ CHECK(!EngineShader_Vertex_Program(ENGINE_SHADER_WATER_RIVER, hlsl));
+}
+
+// mul r0, v0, t0 ; mad r0.rgb, t1, t2, r0 ; mul r0.rgb, r0, t3, with every ps_1_1 result clamped.
+// The shroud multiplies the colour and never the alpha: shrouded water is dark, not transparent.
+TEST(engineshader_adds_the_sparkles_and_then_shrouds_the_trapezoid_water)
+{
+ std::string hlsl;
+ CHECK(EngineShader_Pixel_Program(ENGINE_SHADER_WATER_TRAPEZOID, plain_pipeline(), hlsl));
+ CHECK(contains(hlsl, "float4 current = saturate(input.Diffuse * texel0);"));
+ CHECK(contains(hlsl, "current.rgb = saturate(texel1.rgb * texel2.rgb + current.rgb);"));
+ CHECK(contains(hlsl, "current.rgb = saturate(current.rgb * texel3.rgb);"));
+}
+
+// The river keeps its sparkles apart from the base colour and darkens only those by the vertex
+// alpha, which is where the shroud rides. The co-issued +mul is what puts the shroud in the alpha.
+TEST(engineshader_darkens_only_the_river_waters_sparkles_by_the_vertex_alpha)
+{
+ std::string hlsl;
+ CHECK(EngineShader_Pixel_Program(ENGINE_SHADER_WATER_RIVER, plain_pipeline(), hlsl));
+ CHECK(contains(hlsl, "current.rgb = saturate(input.Diffuse.rgb * texel0.rgb);"));
+ CHECK(contains(hlsl, "current.a = saturate(texel0.a * texel3.a);"));
+ CHECK(contains(hlsl, "sparkle = saturate(sparkle * input.Diffuse.a);"));
+ CHECK(contains(hlsl, "current.rgb = saturate(current.rgb + sparkle);"));
+}
+
+// D3D9 applies the alpha test and the fog around a bound pixel shader and D3D11 applies neither, so
+// a transcription that leaves them out draws water through the fog at full strength.
+TEST(engineshader_writes_the_alpha_test_and_the_fog_into_a_water_program)
+{
+ PixelPipelineDescription pipeline = plain_pipeline();
+ pipeline.FogEnabled = true;
+ pipeline.AlphaTestEnabled = true;
+ pipeline.AlphaFunction = D3DCMP_GREATEREQUAL;
+
+ std::string hlsl;
+ CHECK(EngineShader_Pixel_Program(ENGINE_SHADER_WATER_TRAPEZOID, pipeline, hlsl));
+ CHECK(contains(hlsl, "lerp(FogColour.rgb, current.rgb, saturate(input.Fog))"));
+ CHECK(contains(hlsl, "AlphaReference"));
+}
+
+// lrp r0, v0.w, t1, t0 is t0 + v0.w * (t1 - t0), so the vertex alpha is the weight of the second
+// layer. Reading it the other way round paints every blended ground tile inside out.
+TEST(engineshader_blends_the_terrains_second_layer_by_the_vertex_alpha)
+{
+ std::string hlsl;
+ CHECK(EngineShader_Pixel_Program(ENGINE_SHADER_TERRAIN, plain_pipeline(), hlsl));
+ CHECK(contains(hlsl, "float4 current = saturate(lerp(texel0, texel1, input.Diffuse.a));"));
+ CHECK(contains(hlsl, "current = saturate(current * input.Diffuse);"));
+
+ // The preamble samples all four stages whatever the program reads, so what says this one stops
+ // at two layers is that neither of the other two is multiplied in.
+ CHECK(!contains(hlsl, "current * texel2"));
+ CHECK(!contains(hlsl, "current * texel3"));
+}
+
+// The three noise variants are the same program with one and then two more multiplies: the cloud
+// shadow at stage two and the shroud at stage three.
+TEST(engineshader_adds_one_stage_per_noise_variant)
+{
+ std::string plain;
+ std::string noise;
+ std::string noise_two;
+ CHECK(EngineShader_Pixel_Program(ENGINE_SHADER_TERRAIN, plain_pipeline(), plain));
+ CHECK(EngineShader_Pixel_Program(ENGINE_SHADER_TERRAIN_NOISE, plain_pipeline(), noise));
+ CHECK(EngineShader_Pixel_Program(ENGINE_SHADER_TERRAIN_NOISE_2, plain_pipeline(), noise_two));
+
+ CHECK(!contains(plain, "current * texel2"));
+ CHECK(contains(noise, "current = saturate(current * texel2);"));
+ CHECK(!contains(noise, "current * texel3"));
+ CHECK(contains(noise_two, "current = saturate(current * texel2);"));
+ CHECK(contains(noise_two, "current = saturate(current * texel3);"));
+}
+
+// The flat terrain multiplies its two layers instead of blending them, and fterrain0 reads only the
+// second: t1 with no t0 at all.
+TEST(engineshader_multiplies_the_flat_terrains_layers)
+{
+ std::string flat;
+ std::string base;
+ CHECK(EngineShader_Pixel_Program(ENGINE_SHADER_FLAT_TERRAIN, plain_pipeline(), flat));
+ CHECK(EngineShader_Pixel_Program(ENGINE_SHADER_FLAT_TERRAIN_BASE, plain_pipeline(), base));
+ CHECK(contains(flat, "float4 current = saturate(texel1 * texel0);"));
+ CHECK(contains(base, "float4 current = saturate(texel1);"));
+}
+
+// The road multiplies the vertex colour in last where the terrain does it second. Same arithmetic
+// until a term saturates, and ps_1_1 saturates every one.
+TEST(engineshader_leaves_the_roads_vertex_colour_until_last)
+{
+ std::string hlsl;
+ CHECK(EngineShader_Pixel_Program(ENGINE_SHADER_ROAD_NOISE_2, plain_pipeline(), hlsl));
+ CHECK(contains(hlsl,
+ " float4 current = saturate(texel0 * texel1);\n"
+ " current = saturate(current * texel2);\n"
+ " current = saturate(current * input.Diffuse);\n"));
+}
+
+// Four samplers and four coordinate sets, the same ones ffshader declares, because the backend
+// binds one set of textures whichever half wrote the program.
+TEST(engineshader_declares_the_four_stages_the_water_samples)
+{
+ std::string hlsl;
+ CHECK(EngineShader_Pixel_Program(ENGINE_SHADER_WATER_RIVER, plain_pipeline(), hlsl));
+ for (unsigned stage = 0; stage < MAXIMUM_COMBINER_STAGES; ++stage) {
+ char sampler[64];
+ snprintf(sampler, sizeof(sampler), "Texture%u.Sample(Sampler%u, input.TexCoord%u)",
+ stage, stage, stage);
+ CHECK(contains(hlsl, sampler));
+ }
+}
+
+// m4x4 oPos, r1, c4 is four dot products against four consecutive registers, and the engine
+// transposes the matrix before it uploads it for exactly that reason.
+TEST(engineshader_puts_the_tree_through_four_dot_products_against_c4)
+{
+ std::string hlsl;
+ CHECK(EngineShader_Vertex_Program(ENGINE_SHADER_TREES, hlsl));
+ CHECK(contains(hlsl, "dot(swayed, c[4])"));
+ CHECK(contains(hlsl, "dot(swayed, c[5])"));
+ CHECK(contains(hlsl, "dot(swayed, c[6])"));
+ CHECK(contains(hlsl, "dot(swayed, c[7])"));
+}
+
+// mov a0.x, v1 then mov r0, c8[a0.x]: the sway type rides in the normal slot's x, and c8 is the
+// entry a tree with no sway reads. mad r1, r2.zzzw, r0, v0 scales that by the height above the
+// tree's own base, which r2.z holds.
+TEST(engineshader_leans_a_tree_by_its_height_above_its_own_base)
+{
+ std::string hlsl;
+ CHECK(EngineShader_Vertex_Program(ENGINE_SHADER_TREES, hlsl));
+ CHECK(contains(hlsl, "int sway_type = (int)(input.Sway.x + 0.5);"));
+ CHECK(contains(hlsl, "float height = input.Position.z - input.Sway.z;"));
+ CHECK(contains(hlsl, "height * c[8 + sway_type].xyz + input.Position"));
+}
+
+// mov r2, v1.yyyw then mul oD0, v2, r2: the shade multiplies the colour and leaves the alpha,
+// because a float3 input reads its w as one. Getting that swizzle wrong is a tree whose leaves
+// have the crown's shading in their alpha and no gaps between them.
+TEST(engineshader_shades_the_tree_colour_and_leaves_its_alpha_alone)
+{
+ std::string hlsl;
+ CHECK(EngineShader_Vertex_Program(ENGINE_SHADER_TREES, hlsl));
+ CHECK(contains(hlsl, "output.Diffuse = input.Diffuse * float4(input.Sway.yyy, 1.0);"));
+}
+
+// add r1, v0, c32 then mul oT1, r1, c33, with the shroud's origin in c32 and its texel size in
+// c33. This is the second coordinate set and the only thing that reads it is the shroud stage.
+TEST(engineshader_builds_the_shroud_coordinate_from_c32_and_c33)
+{
+ std::string hlsl;
+ CHECK(EngineShader_Vertex_Program(ENGINE_SHADER_TREES, hlsl));
+ CHECK(contains(hlsl, "((float4(input.Position, 1.0) + c[32]) * c[33]).xy"));
+}
+
+// The pixel half is still generated by ffshader, and shader model 4 links the two by slot in
+// declaration order. A transcription that writes a different set of members links against nothing.
+TEST(engineshader_writes_the_output_structure_ffvertex_writes)
+{
+ std::string hlsl;
+ CHECK(EngineShader_Vertex_Program(ENGINE_SHADER_TREES, hlsl));
+ CHECK(contains(hlsl, "float4 Position : SV_Position;"));
+ CHECK(contains(hlsl, "float4 Diffuse : COLOR0;"));
+ CHECK(contains(hlsl, "float4 Specular : COLOR1;"));
+ CHECK(contains(hlsl, "float2 TexCoord0 : TEXCOORD0;"));
+ CHECK(contains(hlsl, "float2 TexCoord1 : TEXCOORD1;"));
+ CHECK(contains(hlsl, "float Fog : FOG;"));
+}
+
+// The input has to be the byte layout of DX8_FVF_XYZNDUV1, because that is what the tree vertex
+// buffer holds and what dx11layout builds the input layout from. CreateInputLayout refuses a
+// program whose inputs the layout does not have.
+TEST(engineshader_reads_the_vertex_the_tree_buffer_actually_holds)
+{
+ std::string hlsl;
+ CHECK(EngineShader_Vertex_Program(ENGINE_SHADER_TREES, hlsl));
+ CHECK(contains(hlsl, "float3 Position : POSITION;"));
+ CHECK(contains(hlsl, "float3 Sway : NORMAL;"));
+ CHECK(contains(hlsl, "float4 Diffuse : COLOR0;"));
+ CHECK(contains(hlsl, "float2 TexCoord0 : TEXCOORD0;"));
+}
+
+// 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 * name,
+ const char * profile)
+{
+ ID3DBlob * code = NULL;
+ ID3DBlob * errors = NULL;
+ const HRESULT result = compile(hlsl.c_str(), hlsl.size(), name, NULL, NULL,
+ ENTRY_POINT, profile, 0, 0, &code, &errors);
+
+ if (FAILED(result) && errors != NULL) {
+ printf(" %s: %s\n", name, static_cast<const char *>(errors->GetBufferPointer()));
+ }
+ if (code != NULL) {
+ code->Release();
+ }
+ if (errors != NULL) {
+ errors->Release();
+ }
+ return SUCCEEDED(result);
+}
+
+TEST(engineshader_writes_programs_the_compiler_accepts)
+{
+ HMODULE module = LoadLibraryA(COMPILER_MODULE);
+ if (module == NULL) {
+ printf(" %s is not on this machine, skipping the compile\n", COMPILER_MODULE);
+ return;
+ }
+
+ D3DCompileFunction compile =
+ reinterpret_cast<D3DCompileFunction>(GetProcAddress(module, "D3DCompile"));
+ CHECK(compile != NULL);
+ if (compile == NULL) {
+ return;
+ }
+
+ std::string trees;
+ CHECK(EngineShader_Vertex_Program(ENGINE_SHADER_TREES, trees));
+ CHECK(compiles(compile, trees, EngineShader_Name(ENGINE_SHADER_TREES), VERTEX_PROFILE));
+
+ PixelPipelineDescription pipeline = plain_pipeline();
+ pipeline.FogEnabled = true;
+ pipeline.AlphaTestEnabled = true;
+ pipeline.AlphaFunction = D3DCMP_GREATER;
+
+ std::string trapezoid;
+ CHECK(EngineShader_Pixel_Program(ENGINE_SHADER_WATER_TRAPEZOID, pipeline, trapezoid));
+ CHECK(compiles(compile, trapezoid, EngineShader_Name(ENGINE_SHADER_WATER_TRAPEZOID),
+ PIXEL_PROFILE));
+
+ std::string river;
+ CHECK(EngineShader_Pixel_Program(ENGINE_SHADER_WATER_RIVER, pipeline, river));
+ CHECK(compiles(compile, river, EngineShader_Name(ENGINE_SHADER_WATER_RIVER), PIXEL_PROFILE));
+}
diff --git a/GeneralsMD/Code/Tests/test_ffshader.cpp b/GeneralsMD/Code/Tests/test_ffshader.cpp
index f58b84473..95433c4bb 100644
--- a/GeneralsMD/Code/Tests/test_ffshader.cpp
+++ b/GeneralsMD/Code/Tests/test_ffshader.cpp
@@ -162,6 +162,61 @@ TEST(ffshader_argument_modifiers_replicate_before_complementing)
CHECK(contains(hlsl, "saturate((1.0 - texel)).a"));
}
+// The terrain blends its ground layers by the vertex alpha and its noise layers by the alpha the
+// stage before them left in current. Both were refusals until the operations below existed, and a
+// refused terrain draw is a hole where the ground is.
+TEST(ffshader_blends_by_diffuse_and_by_current_alpha)
+{
+ CombinerDescription description;
+ memset(&description, 0, sizeof(description));
+ description.StageCount = 2;
+ description.Stages[0] = one_stage(D3DTOP_BLENDDIFFUSEALPHA, D3DTA_TEXTURE, D3DTA_CURRENT,
+ D3DTOP_SELECTARG1, D3DTA_TEXTURE, D3DTA_CURRENT, 0, true);
+ description.Stages[1] = one_stage(D3DTOP_BLENDCURRENTALPHA, D3DTA_TEXTURE, D3DTA_CURRENT,
+ D3DTOP_SELECTARG1, D3DTA_TEXTURE, D3DTA_CURRENT, 1, true);
+
+ std::string hlsl;
+ CHECK(CombinerShader_Generate(description, COMBINER_SHADER_TARGET_D3D11, hlsl));
+ CHECK(contains(hlsl, "lerp(current, texel, input.Diffuse.a)"));
+ CHECK(contains(hlsl, "lerp(current, texel, current.a)"));
+}
+
+// A stage that disables only its alpha operation keeps the alpha it was handed. Refusing these
+// cost the whole terrain: every one of its blending stages leaves the alpha alone.
+TEST(ffshader_a_disabled_alpha_operation_keeps_the_alpha_it_was_given)
+{
+ CombinerDescription description;
+ memset(&description, 0, sizeof(description));
+ description.StageCount = 1;
+ description.Stages[0] = one_stage(D3DTOP_MODULATE, D3DTA_TEXTURE, D3DTA_CURRENT,
+ D3DTOP_DISABLE, D3DTA_TEXTURE, D3DTA_CURRENT, 0, true);
+
+ std::string hlsl;
+ CHECK(CombinerShader_Generate(description, COMBINER_SHADER_TARGET_D3D11, hlsl));
+ CHECK(contains(hlsl, "current.a = saturate(current).a;"));
+}
+
+// The rest of the blending family, so that a stage program built out of any of them is written
+// rather than refused. What each one computes is D3D9's own definition and nothing here chooses.
+TEST(ffshader_writes_every_blending_operation_the_device_had)
+{
+ static const DWORD operations[] = {
+ D3DTOP_ADDSIGNED2X, D3DTOP_ADDSMOOTH, D3DTOP_BLENDTEXTUREALPHA, D3DTOP_BLENDFACTORALPHA,
+ D3DTOP_BLENDTEXTUREALPHAPM, D3DTOP_MODULATEALPHA_ADDCOLOR, D3DTOP_MODULATECOLOR_ADDALPHA,
+ D3DTOP_MODULATEINVALPHA_ADDCOLOR, D3DTOP_MODULATEINVCOLOR_ADDALPHA };
+
+ for (unsigned index = 0; index < sizeof(operations) / sizeof(operations[0]); ++index) {
+ CombinerDescription description;
+ memset(&description, 0, sizeof(description));
+ description.StageCount = 1;
+ description.Stages[0] = one_stage(operations[index], D3DTA_TEXTURE, D3DTA_DIFFUSE,
+ D3DTOP_SELECTARG1, D3DTA_TEXTURE, D3DTA_CURRENT, 0, true);
+
+ std::string hlsl;
+ CHECK(CombinerShader_Generate(description, COMBINER_SHADER_TARGET_D3D11, hlsl));
+ }
+}
+
// An operation the generator does not write has to be refused, not guessed at: the caller keeps
// that draw on the fixed-function path, which is the only reason meeting one is safe.
TEST(ffshader_refuses_an_operation_it_does_not_generate)
diff --git a/GeneralsMD/Code/Tests/test_ffvertex.cpp b/GeneralsMD/Code/Tests/test_ffvertex.cpp
index cb1c97413..ddbf98784 100644
--- a/GeneralsMD/Code/Tests/test_ffvertex.cpp
+++ b/GeneralsMD/Code/Tests/test_ffvertex.cpp
@@ -265,13 +265,42 @@ TEST(ffvertex_the_two_profiles_differ_only_where_they_have_to)
CHECK(contains(eleven, "output.Position = mul(model_position, WorldViewProjection);"));
}
-TEST(ffvertex_refuses_what_it_cannot_generate)
+TEST(ffvertex_puts_a_pretransformed_vertex_back_into_clip_space)
{
- // A pre-transformed vertex has been through the pipeline already.
+ // The screen-space quads - the filter that puts the rendered scene back on the screen, the
+ // smudges - come in with x and y already in pixels. D3D9 takes them as they are; D3D11 has no
+ // such thing, so the program divides by the viewport and does not touch the world transform.
VertexPipelineDescription pretransformed = plain_description();
pretransformed.FVF = D3DFVF_XYZRHW|D3DFVF_DIFFUSE|D3DFVF_TEX1;
+
+ std::string hlsl;
+ CHECK(VertexShader_Generate(pretransformed, VERTEX_SHADER_TARGET_D3D11, hlsl));
+ CHECK(contains(hlsl, "float4 Position : POSITION;"));
+ CHECK(contains(hlsl, "input.Position.xy * ViewportInverse.xy"));
+ CHECK(contains(hlsl, "output.TexCoord0 = input.TexCoord0;"));
+ CHECK(contains(hlsl, "output.Diffuse = input.Diffuse;"));
+
+ // The one thing it must not do is transform a position that is already transformed.
+ CHECK(!contains(hlsl, "WorldViewProjection)"));
+}
+
+TEST(ffvertex_reads_zero_for_a_coordinate_set_the_format_lacks)
+{
+ // The shadow quads keep a texture stage on and carry no texture coordinates at all. D3D9
+ // reads zeroes there and draws them; refusing left 202 draws a match out of the picture.
+ VertexPipelineDescription missing_set = plain_description();
+ missing_set.FVF = D3DFVF_XYZ|D3DFVF_NORMAL;
+ missing_set.Stages[0].TextureCoordinateIndex = D3DTSS_TCI_PASSTHRU | 0;
+
+ std::string hlsl;
+ CHECK(VertexShader_Generate(missing_set, VERTEX_SHADER_TARGET_D3D11, hlsl));
+ CHECK(contains(hlsl, "float4 generated0 = float4(0.0, 0.0, 0.0, 1.0);"));
+ CHECK(!contains(hlsl, "input.TexCoord0"));
+}
+
+TEST(ffvertex_refuses_what_it_cannot_generate)
+{
std::string hlsl;
- CHECK(!VertexShader_Generate(pretransformed, VERTEX_SHADER_TARGET_D3D9, hlsl));
// Lighting with no normal to light.
VertexPipelineDescription unlit_format = plain_description();
@@ -279,12 +308,6 @@ TEST(ffvertex_refuses_what_it_cannot_generate)
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;
diff --git a/dx11-check.ps1 b/dx11-check.ps1
new file mode 100644
index 000000000..da31984cb
--- /dev/null
+++ b/dx11-check.ps1
@@ -0,0 +1,103 @@
+# Photograph the same frame of the same match twice, once through Direct3D 9 and once through the
+# Direct3D 11 backend, and count the pixels between them.
+#
+# This is RENDERER-ROADMAP.md phase 2's exit measurement. Everything else about the backend is a
+# count - buffers mirrored, pipelines built, draws made and refused - and a run can have all of
+# those right and still draw the wrong picture: the white terrain had a correct atlas, a correct
+# program and a correct draw count for two sessions. Only two pictures of one frame settle it.
+#
+# All three shots come from one exe. -dx11present is the only difference between them, so a view
+# that comes back apart is the backend and not a build, a map or a seed.
+#
+# Three shots, not two. The instrument has noise of its own: particles advance per rendered frame,
+# and two runs of one unchanged binary come back up to 3.66% apart on Flash Effect. A single D3D9
+# against D3D11 pair therefore cannot say whether four percent is the backend or the smoke, so each
+# view is photographed twice through Direct3D 9 as well and the pair's own disagreement is printed
+# beside the signal. A view passes when the backend is no further from Direct3D 9 than Direct3D 9
+# is from itself, plus the margin.
+#
+# 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)
+
+Add-Type -AssemblyName System.Drawing
+$run = Join-Path $PSScriptRoot "GeneralsMD\Run"
+$shots = "$env:USERPROFILE\Documents\Command and Conquer Generals Zero Hour Data"
+$tmp = Join-Path $env:TEMP "dx11check"
+if (-not (Test-Path $tmp)) { $null = New-Item -ItemType Directory $tmp }
+
+$cases = @(
+ @{map='Flash Effect'; x='1200'; y='945'; f=400},
+ @{map='Flash Effect'; x='1816'; y='1861'; f=1200},
+ @{map='Flash Effect'; x='1378'; y='1384'; f=2400},
+ @{map='ForgottenForestZH'; x='1620'; y='1470'; f=600},
+ @{map='ForgottenForestZH'; x='1543'; y='1636'; f=1800},
+ @{map='Golden Oasis'; x='2643'; y='3580'; f=900},
+ @{map='Alpine Assault'; x='760'; y='920'; f=700},
+ @{map='Killing Fields'; x='1024'; y='1024'; f=1500}
+)
+
+# -msaa 0 for tree-check.ps1's reason: a multisampled back buffer cannot be read back, the capture
+# falls through to a desktop grab, and whatever window is over the game lands in the .bmp. The shot
+# folder is emptied first so an empty one is a stated failure rather than the previous view's file.
+function Shoot($c, $tag, $extra) {
+ Get-ChildItem "$shots\sshot*.bmp" -ErrorAction SilentlyContinue | Remove-Item -Force
+ $arguments = @('-win','-xres','1280','-yres','720','-quickstart','-noshellmap','-multiInstance',
+ '-msaa','0','-map',"`"Maps\$($c.map)\$($c.map).map`"",'-autoskirmish','4','-aidiff','easy',
+ '-seed','5','-maxframes',($c.f+80),'-screenshot',$c.f,'-camera',$c.x,$c.y,
+ '-logPrefix',"dx11chk_$tag`_") + $extra
+ try {
+ $process = Start-Process (Join-Path $run 'generals.exe') -ArgumentList $arguments -WorkingDirectory $run -PassThru
+ $null = $process.WaitForExit(900000)
+ }
+ finally {
+ Get-Process -Name generals -ErrorAction SilentlyContinue | Stop-Process -Force
+ }
+ $file = Get-ChildItem "$shots\sshot*.bmp" -ErrorAction SilentlyContinue |
+ Sort-Object LastWriteTime | Select-Object -Last 1
+ if ($null -eq $file) { throw "no screenshot for $tag" }
+ $image = [System.Drawing.Image]::FromFile($file.FullName)
+ $out = "$tmp\dx11chk_$tag.png"
+ $image.Save($out, [System.Drawing.Imaging.ImageFormat]::Png)
+ $image.Dispose()
+ return $out
+}
+
+# Every fourth pixel of every other row, counting the ones more than 40 apart in summed channels.
+# The same measure tree-check.ps1 uses, so the two numbers are comparable.
+function DiffPct($a, $b) {
+ $ia = New-Object System.Drawing.Bitmap($a)
+ $ib = New-Object System.Drawing.Bitmap($b)
+ $w = $ia.Width; $h = [Math]::Min($ia.Height, 520)
+ $apart = 0; $total = 0
+ for ($y = 0; $y -lt $h; $y += 2) {
+ for ($x = 0; $x -lt $w; $x += 2) {
+ $pa = $ia.GetPixel($x, $y); $pb = $ib.GetPixel($x, $y)
+ $d = [Math]::Abs($pa.R - $pb.R) + [Math]::Abs($pa.G - $pb.G) + [Math]::Abs($pa.B - $pb.B)
+ $total++
+ if ($d -gt 40) { $apart++ }
+ }
+ }
+ $ia.Dispose(); $ib.Dispose()
+ return [Math]::Round(100.0 * $apart / $total, 2)
+}
+
+$fail = 0
+foreach ($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
+ $signal = DiffPct $nine $eleven
+ $verdict = if ($signal -le ($noise + $Margin)) { 'ok' } else { 'DIFFERENT' }
+ if ($verdict -ne 'ok') { $fail++ }
+ "{0,-20} cam {1,5},{2,-5} frame {3,-5} noise {4,5}% dx11 {5,5}% {6}" -f `
+ $c.map, $c.x, $c.y, $c.f, $noise, $signal, $verdict
+}
+"---"
+"pictures in $tmp"
+if ($fail -eq 0) { "all $($cases.Count) views are within $Margin% of their own noise" }
+else { "$fail of $($cases.Count) views are further than $Margin% past their own noise" }
+exit $fail