Zero Hour rebuilt from EA's source: x64, Direct3D 11, VS2022/CMake, ~60 original bugs fixed, an AI that builds a base. Bring your own game.
C++ cmakecnccommand-and-conquercppdirectx11game-enginegame-preservationgeneralsrtssage-enginex64zero-hour
perf(w3ddevice): constant rings, gpu timer, no idle d3d9 work
Olcay Seygan962c2c47bdac
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cppindex fcd2adacd..54488f88f 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp@@ -541,6 +541,8 @@ W3DDisplay::~W3DDisplay()twinBuffers, twinBytes / 1024,texturesMirrored, texturesReused, texturesRefused,pipelines, drawsMade, drawsRefused));+ if( Direct3D11_Is_Active() )+ DEBUG_LOG(("-dx11 constants: %s\n", Direct3D11_Constant_Path()));unsigned programsShipped = 0;unsigned programsHeld = 0;Direct3D11_Program_Statistics( programsShipped, programsHeld );@@ -1235,8 +1237,9 @@ void W3DDisplay::init( void )#endifDEBUG_LOG(("W3DDisplay::init - present: %s\n", DX8Wrapper::Is_Flip_Present() ? "flip" : "discard"));if (Direct3D11_Present_Is_Enabled())- DEBUG_LOG(("W3DDisplay::init - dx11 swap chain: %s\n",- Direct3D11_Can_Tear() ? "flip, tearing allowed" : "blt, held to the refresh"));+ DEBUG_LOG(("W3DDisplay::init - dx11 swap chain: %s%s\n",+ Direct3D11_Can_Tear() ? "flip, tearing allowed" : "blt, held to the refresh",+ Direct3D11_Has_Frame_Wait() ? ", the frame waits for room in its queue" : ""));DEBUG_LOG(("W3DDisplay::init - adapter: %s\n",WW3D::Get_Render_Device_Name(WW3D::Get_Render_Device())));{@@ -2753,10 +2756,21 @@ AGAIN:double textureMS = 0.0;unsigned textures = 0;unsigned depthCopies = 0;- Direct3D11_Take_Frame_Cost( pipelineMS, pipelines, textureMS, textures, depthCopies );+ unsigned constantWrites = 0;+ unsigned constantRenames = 0;+ Direct3D11_Take_Frame_Cost( pipelineMS, pipelines, textureMS, textures, depthCopies,+ constantWrites, constantRenames );if( pipelineMS + textureMS > DX11_FRAME_COST_REPORT_MS )- DEBUG_LOG(("DX11 FRAME COST frame %d: %u pipelines built in %.1f ms, %u textures copied in %.1f ms, %u soft particle depth copies\n",- TheGameLogic->getFrame(), pipelines, pipelineMS, textures, textureMS, depthCopies));+ DEBUG_LOG(("DX11 FRAME COST frame %d: %u pipelines built in %.1f ms, %u textures copied in %.1f ms, %u soft particle depth copies, %u constant writes, %u renames\n",+ TheGameLogic->getFrame(), pipelines, pipelineMS, textures, textureMS, depthCopies,+ constantWrites, constantRenames));++ /* Once a second in a match, what the GPU's own clock says the frames cost and how+ long it sat idle between them: busy well under 100% beside a low frame rate is a+ frame held up on the CPU side, not by the card. */+ const char *gpuReport = Direct3D11_Take_GPU_Report();+ if( gpuReport && TheGameLogic->isInGame() && !TheGameLogic->isInShellGame() )+ DEBUG_LOG(("DX11 GPU frame %d: %s\n", TheGameLogic->getFrame(), gpuReport));long presentResult = 0;if( Direct3D11_Take_Present_Failure( presentResult ) )diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DSmudge.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DSmudge.cppindex 657fde4fa..b97b59cc2 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DSmudge.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DSmudge.cpp@@ -291,7 +291,9 @@ Bool W3DSmudgeManager::testHardwareSupport(void)//not worth bothering with index/vertex buffers.pDev->SetFVF(D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX1);- DX8Wrapper::_Draw_DX8_Primitive_UP(D3DPT_TRIANGLESTRIP, 2, v, sizeof(_TRANS_LIT_TEX_VERTEX));+ // Both quads are read back off the Direct3D 9 target, so they go to that device even while+ // Direct3D 11 presents.+ DX8Wrapper::_Draw_DX8_Primitive_UP(D3DPT_TRIANGLESTRIP, 2, v, sizeof(_TRANS_LIT_TEX_VERTEX), true);UnsignedInt refData[BLOCK_SIZE*BLOCK_SIZE];memset(refData,0,sizeof(refData));@@ -312,7 +314,7 @@ Bool W3DSmudgeManager::testHardwareSupport(void)v[2].color = 0xffffffff;v[3].color = 0xffffffff;- DX8Wrapper::_Draw_DX8_Primitive_UP(D3DPT_TRIANGLESTRIP, 2, v, sizeof(_TRANS_LIT_TEX_VERTEX));+ DX8Wrapper::_Draw_DX8_Primitive_UP(D3DPT_TRIANGLESTRIP, 2, v, sizeof(_TRANS_LIT_TEX_VERTEX), true);bufSize=copyRect((unsigned char *)testData,sizeof(testData),0,0,BLOCK_SIZE,BLOCK_SIZE);if (!bufSize)diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cppindex 8b2f3f825..ed60c8985 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp@@ -2107,7 +2107,10 @@ void WaterRenderObjClass::drawSea(RenderInfoClass & rinfo)D3DXMatrixTranspose(&matWorldViewProj, &matWorldViewProj);m_pDev->SetVertexShaderConstantF(CV_WORLDVIEWPROJ_0, (const float*)&matWorldViewProj, 4); //pass transform matrix into shader- m_pDev->DrawIndexedPrimitive(D3DPT_TRIANGLESTRIP,0,0,m_numVertices,0,m_numIndices);+ // Nobody sees a Direct3D 9 draw while Direct3D 11 presents; renderWaterMesh skips its own+ // the same way, and this patch has no Direct3D 11 draw beside it.+ if (!Direct3D11_Present_Is_Enabled())+ m_pDev->DrawIndexedPrimitive(D3DPT_TRIANGLESTRIP,0,0,m_numVertices,0,m_numIndices);}}// DX8Wrapper::Set_DX8_Render_State(D3DRS_FILLMODE,D3DFILL_SOLID);@@ -2163,7 +2166,8 @@ void WaterRenderObjClass::drawSea(RenderInfoClass & rinfo)DX8Wrapper::_Set_DX8_Transform(D3DTS_WORLD, *(Matrix4x4*)&matTemp);- m_pDev->DrawIndexedPrimitive(D3DPT_TRIANGLESTRIP,0,0,m_numVertices,0,m_numIndices);+ if (!Direct3D11_Present_Is_Enabled())+ m_pDev->DrawIndexedPrimitive(D3DPT_TRIANGLESTRIP,0,0,m_numVertices,0,m_numIndices);}}W3DShaderManager::resetShader(W3DShaderManager::ST_SHROUD_TEXTURE);diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cppindex 3279da297..1a3710939 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp@@ -203,9 +203,10 @@ DX11BackendClass::DX11BackendClass(), IndexBuffer(NULL), IndexFormat(DXGI_FORMAT_R16_UINT), MaterialPower(0.0f)- , VertexConstantBuffer(NULL)- , PixelConstantBuffer(NULL)- , EngineConstantBuffer(NULL)+ , OffsetContext(NULL)+ , FrameConstantWrites(0)+ , FrameConstantRenames(0)+ , ConstantPath(""), VertexProgram(ENGINE_SHADER_NONE), PixelProgram(ENGINE_SHADER_NONE), UserBuffer(NULL)@@ -262,6 +263,9 @@ DX11BackendClass::DX11BackendClass()memset(Memos, 0, sizeof(Memos));LastMemo = 0;NextMemo = 0;+ memset(&VertexConstantRing, 0, sizeof(VertexConstantRing));+ memset(&PixelConstantRing, 0, sizeof(PixelConstantRing));+ memset(&EngineConstantRing, 0, sizeof(EngineConstantRing));Forget_Last_State_Objects();memset(&HeldVertexConstants, 0, sizeof(HeldVertexConstants));memset(&HeldPixelConstants, 0, sizeof(HeldPixelConstants));@@ -360,24 +364,97 @@ bool DX11BackendClass::Initialise(DX11DeviceClass * device)PixelConstantsHeld = false;EngineConstantsHeld = false;+ // The rings want both halves of 11.1: binding at an offset, and a constant buffer mapped without+ // a discard. The 11.0 runtime refuses the question, and an old driver answers no to either.+ D3D11_FEATURE_DATA_D3D11_OPTIONS options;+ memset(&options, 0, sizeof(options));+ ConstantPath = "one entry a kind, a discard every write: no 11.1 offset binding";+ if (SUCCEEDED(Device->Get_Device()->CheckFeatureSupport(D3D11_FEATURE_D3D11_OPTIONS, &options,+ sizeof(options)))+ && options.ConstantBufferOffsetting && options.MapNoOverwriteOnDynamicConstantBuffer) {+ Device->Get_Context()->QueryInterface(__uuidof(ID3D11DeviceContext1),+ reinterpret_cast<void **>(&OffsetContext));+ }++ auto create_rings = [this]() {+ return Create_Constant_Ring(VertexConstantRing, sizeof(VertexConstantBlock))+ && Create_Constant_Ring(PixelConstantRing, sizeof(PixelConstantBlock))+ && Create_Constant_Ring(EngineConstantRing, sizeof(EngineConstants));+ };+ if (OffsetContext != NULL) {+ if (create_rings()) {+ ConstantPath = "a 4 MB ring a kind, written NO_OVERWRITE and bound at offsets";+ return true;+ }+ // A driver that says yes to offsets can still refuse a constant buffer this large, and+ // losing the Direct3D 11 frame over it would be the wrong trade: the one-entry rings below+ // are how every write went before the rings.+ Release_Constant_Ring(VertexConstantRing);+ Release_Constant_Ring(PixelConstantRing);+ Release_Constant_Ring(EngineConstantRing);+ OffsetContext->Release();+ OffsetContext = NULL;+ ConstantPath = "one entry a kind, a discard every write: the device refused a 4 MB ring";+ }+ return create_rings();+}++// A ring's size. A heavy frame writes about three thousand blocks across the three rings, a+// kilobyte to two and a half each, so four megabytes a ring holds most of a frame and wraps about+// once a frame where every write used to discard.+static const unsigned CONSTANT_RING_BYTES = 4u << 20;+// An offset and a count are both in whole sixteen-constant steps of sixteen bytes a constant.+static const unsigned CONSTANT_BYTES = 16;+static const unsigned CONSTANT_ENTRY_ALIGNMENT = 16 * CONSTANT_BYTES;++bool DX11BackendClass::Create_Constant_Ring(ConstantRing & ring, unsigned block_bytes)+{+ ring.EntryBytes = (block_bytes + CONSTANT_ENTRY_ALIGNMENT - 1) & ~(CONSTANT_ENTRY_ALIGNMENT - 1);+ ring.Bytes = (OffsetContext != NULL)+ ? (CONSTANT_RING_BYTES / ring.EntryBytes) * ring.EntryBytes : ring.EntryBytes;+ // Full, so the first write discards: the buffer has never been mapped.+ ring.Next = ring.Bytes;+ ring.Current = 0;+D3D11_BUFFER_DESC description;memset(&description, 0, sizeof(description));- description.ByteWidth = sizeof(VertexConstantBlock);+ description.ByteWidth = ring.Bytes;description.Usage = D3D11_USAGE_DYNAMIC;description.BindFlags = D3D11_BIND_CONSTANT_BUFFER;description.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;+ return SUCCEEDED(Device->Get_Device()->CreateBuffer(&description, NULL, &ring.Buffer));+}- if (FAILED(Device->Get_Device()->CreateBuffer(&description, NULL, &VertexConstantBuffer))) {+// NO_OVERWRITE is the promise that nothing a queued draw reads is written, which holds because a+// write only ever lands past every entry written since the last discard. A failed Map leaves the+// ring where it was, so a retry neither skips a discard nor writes over an entry in flight.+bool DX11BackendClass::Write_Constants(ConstantRing & ring, const void * block, unsigned bytes)+{+ const bool wraps = ring.Next + ring.EntryBytes > ring.Bytes;+ const unsigned offset = wraps ? 0 : ring.Next;+ ID3D11DeviceContext * context = Device->Get_Context();+ D3D11_MAPPED_SUBRESOURCE mapped;+ if (FAILED(context->Map(ring.Buffer, 0,+ wraps ? D3D11_MAP_WRITE_DISCARD : D3D11_MAP_WRITE_NO_OVERWRITE, 0, &mapped))) {return false;}-- description.ByteWidth = sizeof(PixelConstantBlock);- if (FAILED(Device->Get_Device()->CreateBuffer(&description, NULL, &PixelConstantBuffer))) {- return false;+ memcpy(static_cast<unsigned char *>(mapped.pData) + offset, block, bytes);+ context->Unmap(ring.Buffer, 0);+ ring.Current = offset;+ ring.Next = offset + ring.EntryBytes;+ ++FrameConstantWrites;+ if (wraps) {+ ++FrameConstantRenames;}+ return true;+}- description.ByteWidth = sizeof(EngineConstants);- return SUCCEEDED(Device->Get_Device()->CreateBuffer(&description, NULL, &EngineConstantBuffer));+void DX11BackendClass::Release_Constant_Ring(ConstantRing & ring)+{+ if (ring.Buffer != NULL) {+ ring.Buffer->Release();+ }+ memset(&ring, 0, sizeof(ring));}void DX11BackendClass::Release_Cached()@@ -443,17 +520,12 @@ void DX11BackendClass::Shutdown()}Release_Cached();- if (EngineConstantBuffer != NULL) {- EngineConstantBuffer->Release();- EngineConstantBuffer = NULL;- }- if (PixelConstantBuffer != NULL) {- PixelConstantBuffer->Release();- PixelConstantBuffer = NULL;- }- if (VertexConstantBuffer != NULL) {- VertexConstantBuffer->Release();- VertexConstantBuffer = NULL;+ Release_Constant_Ring(EngineConstantRing);+ Release_Constant_Ring(PixelConstantRing);+ Release_Constant_Ring(VertexConstantRing);+ if (OffsetContext != NULL) {+ OffsetContext->Release();+ OffsetContext = NULL;}if (UserBuffer != NULL) {UserBuffer->Release();@@ -2376,17 +2448,12 @@ const char * DX11BackendClass::Pipeline_Report(unsigned index)void DX11BackendClass::Upload_Constants(){- ID3D11DeviceContext * context = Device->Get_Context();- D3D11_MAPPED_SUBRESOURCE mapped;-// A transcribed program reads the engine's own register bank instead of the block below, so// that bank goes up only on the draws that take one.if (VertexProgram != ENGINE_SHADER_NONE&& (!EngineConstantsHeld|| memcmp(HeldEngineConstants, EngineConstants, sizeof(EngineConstants)) != 0)- && SUCCEEDED(context->Map(EngineConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped))) {- memcpy(mapped.pData, EngineConstants, sizeof(EngineConstants));- context->Unmap(EngineConstantBuffer, 0);+ && Write_Constants(EngineConstantRing, EngineConstants, sizeof(EngineConstants))) {memcpy(HeldEngineConstants, EngineConstants, sizeof(EngineConstants));EngineConstantsHeld = true;}@@ -2408,9 +2475,6 @@ void DX11BackendClass::Upload_Constants()void DX11BackendClass::Upload_Vertex_Constants(){- ID3D11DeviceContext * context = Device->Get_Context();- D3D11_MAPPED_SUBRESOURCE mapped;-VertexConstantBlock vertex_block;memset(&vertex_block, 0, sizeof(vertex_block));@@ -2468,9 +2532,7 @@ void DX11BackendClass::Upload_Vertex_Constants()if (!VertexConstantsHeld|| memcmp(&HeldVertexConstants, &vertex_block, sizeof(vertex_block)) != 0) {VertexConstantsHeld = false;- if (SUCCEEDED(context->Map(VertexConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped))) {- memcpy(mapped.pData, &vertex_block, sizeof(vertex_block));- context->Unmap(VertexConstantBuffer, 0);+ if (Write_Constants(VertexConstantRing, &vertex_block, sizeof(vertex_block))) {HeldVertexConstants = vertex_block;VertexConstantsHeld = true;}@@ -2479,9 +2541,6 @@ void DX11BackendClass::Upload_Vertex_Constants()void DX11BackendClass::Upload_Pixel_Constants(){- ID3D11DeviceContext * context = Device->Get_Context();- D3D11_MAPPED_SUBRESOURCE mapped;-PixelConstantBlock pixel_block;memset(&pixel_block, 0, sizeof(pixel_block));RenderStates.Get_Texture_Factor(pixel_block.TextureFactor);@@ -2584,9 +2643,7 @@ void DX11BackendClass::Upload_Pixel_Constants()if (!PixelConstantsHeld|| memcmp(&HeldPixelConstants, &pixel_block, sizeof(pixel_block)) != 0) {PixelConstantsHeld = false;- if (SUCCEEDED(context->Map(PixelConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped))) {- memcpy(mapped.pData, &pixel_block, sizeof(pixel_block));- context->Unmap(PixelConstantBuffer, 0);+ if (Write_Constants(PixelConstantRing, &pixel_block, sizeof(pixel_block))) {HeldPixelConstants = pixel_block;PixelConstantsHeld = true;}@@ -2733,9 +2790,9 @@ ID3D11SamplerState * DX11BackendClass::Sampler_State(unsigned sampler)return state;}-ID3D11Buffer * DX11BackendClass::Vertex_Constants() const+const DX11BackendClass::ConstantRing & DX11BackendClass::Vertex_Constants() const{- return (VertexProgram != ENGINE_SHADER_NONE) ? EngineConstantBuffer : VertexConstantBuffer;+ return (VertexProgram != ENGINE_SHADER_NONE) ? EngineConstantRing : VertexConstantRing;}void DX11BackendClass::Forget_Bindings()@@ -2899,18 +2956,36 @@ void DX11BackendClass::Bind_Pipeline(const Pipeline & pipeline, ID3D11Buffer * vcontext->VSSetShader(pipeline.VertexShader, NULL, 0);Bound.VertexShader = pipeline.VertexShader;}- ID3D11Buffer * vertex_constants = Vertex_Constants();- if (!known || vertex_constants != Bound.VertexConstants) {- context->VSSetConstantBuffers(0, 1, &vertex_constants);- Bound.VertexConstants = vertex_constants;+ // Each block at the entry its last write went to, which a draw that wrote nothing still reads.+ // The window is the entry: a program declares at most the block, which the entry holds.+ const ConstantRing & vertex_constants = Vertex_Constants();+ if (!known || vertex_constants.Buffer != Bound.VertexConstants+ || vertex_constants.Current != Bound.VertexConstantsOffset) {+ if (OffsetContext != NULL) {+ const UINT first = vertex_constants.Current / CONSTANT_BYTES;+ const UINT count = vertex_constants.EntryBytes / CONSTANT_BYTES;+ OffsetContext->VSSetConstantBuffers1(0, 1, &vertex_constants.Buffer, &first, &count);+ } else {+ context->VSSetConstantBuffers(0, 1, &vertex_constants.Buffer);+ }+ Bound.VertexConstants = vertex_constants.Buffer;+ Bound.VertexConstantsOffset = vertex_constants.Current;}if (!known || pipeline.PixelShader != Bound.PixelShader) {context->PSSetShader(pipeline.PixelShader, NULL, 0);Bound.PixelShader = pipeline.PixelShader;}- if (!known || PixelConstantBuffer != Bound.PixelConstants) {- context->PSSetConstantBuffers(0, 1, &PixelConstantBuffer);- Bound.PixelConstants = PixelConstantBuffer;+ if (!known || PixelConstantRing.Buffer != Bound.PixelConstants+ || PixelConstantRing.Current != Bound.PixelConstantsOffset) {+ if (OffsetContext != NULL) {+ const UINT first = PixelConstantRing.Current / CONSTANT_BYTES;+ const UINT count = PixelConstantRing.EntryBytes / CONSTANT_BYTES;+ OffsetContext->PSSetConstantBuffers1(0, 1, &PixelConstantRing.Buffer, &first, &count);+ } else {+ context->PSSetConstantBuffers(0, 1, &PixelConstantRing.Buffer);+ }+ Bound.PixelConstants = PixelConstantRing.Buffer;+ Bound.PixelConstantsOffset = PixelConstantRing.Current;}Bound.Known = true;}@@ -3339,3 +3414,11 @@ void DX11BackendClass::Take_Frame_Build_Cost(double & milliseconds, unsigned & pFrameBuildMilliseconds = 0.0;FrameBuildCount = 0;}++void DX11BackendClass::Take_Frame_Constant_Writes(unsigned & writes, unsigned & renames)+{+ writes = FrameConstantWrites;+ renames = FrameConstantRenames;+ FrameConstantWrites = 0;+ FrameConstantRenames = 0;+}diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.hindex 4c7e24600..8a090f0fb 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h@@ -52,6 +52,7 @@#include "ffshader.h"#include "ffvertex.h"+#include <d3d11_1.h>#include <d3d9.h>#include <map>#include <string.h>@@ -291,6 +292,15 @@ public:// this is the stutter a new effect costs on the frame it first appears.void Take_Frame_Build_Cost(double & milliseconds, unsigned & pipelines);+ // The constant blocks written since the last call, and how many of those writes discarded their+ // buffer, which is a rename in the driver. With offsets a rename is a ring wrapping; without+ // them every write is one.+ void Take_Frame_Constant_Writes(unsigned & writes, unsigned & renames);+ // Which way the constant blocks go up, and why, for the log line Initialise owes: the rings, or+ // one entry a kind because the device has no offset binding or refused a ring that size.+ const char * Constant_Path() const { return ConstantPath; }+ bool Constant_Offsets() const { return OffsetContext != NULL; }+// 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.@@ -427,9 +437,28 @@ private:bool Draw_Indexed(unsigned index_count, unsigned start_index, unsigned base_vertex,D3D11_PRIMITIVE_TOPOLOGY topology);+ // A dynamic constant buffer the blocks of one kind are written into one after another, each at+ // the next free entry with NO_OVERWRITE, and bound at that entry's offset. Only a write that+ // finds the ring full discards it and starts again at zero, so a frame of thousands of writes+ // renames a few times instead of once a write. Each kind has its own ring because a discard+ // throws away everything in the buffer: in a shared one the block a skipped write left behind+ // would be gone. Without offset binding the ring is one entry long and every write discards,+ // which is how every write went before.+ struct ConstantRing+ {+ ID3D11Buffer * Buffer;+ unsigned EntryBytes; ///< the block rounded up to the 256 bytes an offset moves in+ unsigned Bytes; ///< the whole buffer, a whole number of entries+ unsigned Next; ///< where the next write goes; Bytes makes it discard+ unsigned Current; ///< where the last write went, which is what the draws read+ };+ bool Create_Constant_Ring(ConstantRing & ring, unsigned block_bytes);+ bool Write_Constants(ConstantRing & ring, const void * block, unsigned bytes);+ void Release_Constant_Ring(ConstantRing & ring);+// 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;+ const ConstantRing & Vertex_Constants() const;void Bind_State_Objects();void Release_Cached();@@ -583,23 +612,33 @@ private:};Light Lights[MAXIMUM_VERTEX_LIGHTS];- ID3D11Buffer * VertexConstantBuffer;- ID3D11Buffer * PixelConstantBuffer;+ ConstantRing VertexConstantRing;+ ConstantRing PixelConstantRing;- // The engine's own constant bank and the buffer it is uploaded through. It replaces the+ // The engine's own constant bank and the ring 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;+ ConstantRing EngineConstantRing;float EngineConstants[ENGINE_SHADER_CONSTANTS][4];+ // The context's 11.1 face, which binds a constant buffer at an offset. Null when the runtime or+ // the driver cannot bind at an offset or map a constant buffer without discarding it; the rings+ // are then one entry long and bound whole.+ ID3D11DeviceContext1 * OffsetContext;+ unsigned FrameConstantWrites;+ unsigned FrameConstantRenames;+ const char * ConstantPath;+// What each constant buffer already holds.//- // Upload_Constants runs on every draw and each Map asks for D3D11_MAP_WRITE_DISCARD, which is- // the driver being told to hand back a fresh region: three renames a draw, thousands of draws a- // frame, and NtGdiDdDDICreateAllocation sitting in a steady-state profile where nothing should- // be allocating at all. Most draws in a row change none of this - the transforms, the material- // and the lights are set once for a whole batch - so the block is built into a local, compared- // against the copy here, and written through only when it differs.+ // Upload_Constants runs on every draw, and a write used to be a Map with+ // D3D11_MAP_WRITE_DISCARD, the driver being told to hand back a fresh region: three renames a+ // draw, thousands of draws a frame, and NtGdiDdDDICreateAllocation sitting in a steady-state+ // profile where nothing should be allocating at all. The rings above took the renames out of+ // the writes that remain. Most draws in a row change none of this - the transforms, the+ // material and the lights are set once for a whole batch - so the block is built into a local,+ // compared against the copy here, and written through only when it differs. A draw that+ // writes nothing binds the entry the last write went to.//// The setters do flag the blocks now (ConstantsChanged below), but only to skip building them.// The byte compare still decides the write: a flag says something was set, often to the value@@ -845,8 +884,10 @@ private:D3D11_PRIMITIVE_TOPOLOGY Topology;ID3D11VertexShader * VertexShader;ID3D11Buffer * VertexConstants;+ UINT VertexConstantsOffset;ID3D11PixelShader * PixelShader;ID3D11Buffer * PixelConstants;+ UINT PixelConstantsOffset;};ContextBindings Bound;void Bind_Pipeline(const Pipeline & pipeline, ID3D11Buffer * vertices, UINT stride,diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11device.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11device.cppindex c058031d5..f1aee488c 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11device.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11device.cpp@@ -40,7 +40,14 @@ static const DXGI_FORMAT DEPTH_READ_FORMAT = DXGI_FORMAT_R24_UNORM_X8_TYPELESS;// still run the Direct3D 9 device.static const D3D_FEATURE_LEVEL REQUESTED_FEATURE_LEVELS[] = { D3D_FEATURE_LEVEL_11_0 };-static const UINT SWAP_CHAIN_BUFFER_COUNT = 2;+// Three, so a flip chain always has a buffer to draw into while one is on screen and one waits for+// its turn there; with two, a frame finished early stalls on the one the compositor still holds.+static const UINT SWAP_CHAIN_BUFFER_COUNT = 3;++// How many presented frames may be queued ahead of the screen on the waitable flip chain+// (Wait_For_Frame). Two keeps the GPU fed across a long CPU frame and adds one frame of latency at+// most.+static const UINT MAXIMUM_FRAME_LATENCY = 2;static void release_interface(IUnknown ** object){@@ -88,6 +95,8 @@ DX11DeviceClass::DX11DeviceClass(), DebugLayerRequested(false), DebugLayerPresent(false), Tearing(false)+ , ChainFlags(0)+ , FrameLatencyWaitable(NULL), LastPresentResult(S_OK){}@@ -135,9 +144,14 @@ bool DX11DeviceClass::Create_Device(bool with_swap_chain, HWND window, unsignedDXGI_SWAP_CHAIN_DESC flip_chain = swap_chain;flip_chain.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;flip_chain.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING;- const DXGI_SWAP_CHAIN_DESC * chain_choices[] = { &flip_chain, &swap_chain };- const unsigned chain_start = (with_swap_chain && tearing_supported()) ? 0u : 1u;+ // The same flip chain with its queue held by a wait at the top of the frame (Wait_For_Frame)+ // rather than inside Present. Windows 8.1 and later; a create that refuses it keeps the flip+ // chain without the wait, because the blt model would take the tearing with it.+ DXGI_SWAP_CHAIN_DESC waitable_chain = flip_chain;+ waitable_chain.Flags |= DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT;+ const DXGI_SWAP_CHAIN_DESC * chain_choices[] = { &waitable_chain, &flip_chain, &swap_chain };const unsigned chain_choice_count = sizeof(chain_choices)/sizeof(chain_choices[0]);+ const unsigned chain_start = (with_swap_chain && tearing_supported()) ? 0u : chain_choice_count - 1;// Hardware first, WARP second. WARP draws the same picture on a machine with no D3D11 driver,// which is what makes the device creatable on a build agent as well as on this one.@@ -166,10 +180,18 @@ bool DX11DeviceClass::Create_Device(bool with_swap_chain, HWND window, unsignedconst unsigned flag_choice_count = sizeof(flag_choices)/sizeof(flag_choices[0]);+ // Every Direct3D 11 call this process makes is on the main thread: the texture loader thread+ // only fills Direct3D 9 surfaces the main thread locked, the job pool's skin, billboard and+ // particle work writes plain memory between a lock and an unlock taken outside it, the video+ // writer thread only writes the pipe, and the hardware cursor thread only touches the Direct3D 9+ // device. So the device is spared its own locking. The Direct3D 9 device is made without+ // D3DCREATE_MULTITHREADED for the same reason.+ const UINT thread_flags = D3D11_CREATE_DEVICE_SINGLETHREADED;+for (unsigned index = 0; index < driver_type_count; ++index) {for (unsigned flag_index = flag_start; flag_index < flag_choice_count; ++flag_index) {for (unsigned chain_index = chain_start; chain_index < chain_choice_count; ++chain_index) {- const UINT flags = flag_choices[flag_index];+ const UINT flags = flag_choices[flag_index] | thread_flags;// The NULL driver has no swap chain to make (ZH_DX11_DRIVER=null, above).const bool null_driver = (driver_types[index] == D3D_DRIVER_TYPE_NULL);const HRESULT result = Create_Device_Guarded(with_swap_chain && !null_driver,@@ -180,12 +202,24 @@ bool DX11DeviceClass::Create_Device(bool with_swap_chain, HWND window, unsignedSoftware = (driver_types[index] == D3D_DRIVER_TYPE_WARP);DebugLayerPresent = (flags & D3D11_CREATE_DEVICE_DEBUG) != 0;- Tearing = !null_driver && (chain_choices[chain_index] == &flip_chain);+ Tearing = !null_driver && (chain_choices[chain_index] != &swap_chain);+ ChainFlags = chain_choices[chain_index]->Flags;Width = width;Height = height;if (!with_swap_chain) {return true;}+ // Asked for on the interface the flag belongs to; with the waitable flag the+ // device's own SetMaximumFrameLatency is not read. A wrapper dxgi.dll may hand back+ // a chain without this interface, and then the frame simply does not wait.+ IDXGISwapChain2 * waitable = NULL;+ if (SwapChain != NULL && chain_choices[chain_index] == &waitable_chain+ && SUCCEEDED(SwapChain->QueryInterface(__uuidof(IDXGISwapChain2),+ reinterpret_cast<void **>(&waitable)))) {+ waitable->SetMaximumFrameLatency(MAXIMUM_FRAME_LATENCY);+ FrameLatencyWaitable = waitable->GetFrameLatencyWaitableObject();+ waitable->Release();+ }// DXGI answers Alt+Enter on its own by taking the chain to exclusive fullscreen,// behind the game's back. A flip chain presenting with tearing is refused there// and the picture freezes, and the game already has its own fullscreen.@@ -325,6 +359,10 @@ void DX11DeviceClass::Release_Views()void DX11DeviceClass::Release(){Release_Views();+ if (FrameLatencyWaitable != NULL) {+ CloseHandle(FrameLatencyWaitable);+ FrameLatencyWaitable = NULL;+ }release_interface(reinterpret_cast<IUnknown **>(&SwapChain));release_interface(reinterpret_cast<IUnknown **>(&Context));release_interface(reinterpret_cast<IUnknown **>(&Device));@@ -332,16 +370,17 @@ void DX11DeviceClass::Release()Height = 0;Software = false;Tearing = false;+ ChainFlags = 0;}bool DX11DeviceClass::Resize(unsigned width, unsigned height){Release_Views();// With no swap chain (ZH_DX11_DRIVER=null) the views alone are the buffers, made again below.- // ResizeBuffers has to be handed the flags the chain was made with, or it refuses.- const UINT chain_flags = Tearing ? DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING : 0;+ // ResizeBuffers has to be handed the flags the chain was made with, or it refuses: the waitable+ // flag in particular can be neither added nor taken away here.if (SwapChain != NULL && FAILED(SwapChain->ResizeBuffers(SWAP_CHAIN_BUFFER_COUNT, width, height,- BACK_BUFFER_FORMAT, chain_flags))) {+ BACK_BUFFER_FORMAT, ChainFlags))) {return false;}Width = width;@@ -394,6 +433,18 @@ bool DX11DeviceClass::Present(unsigned present_interval)return SUCCEEDED(result);}+bool DX11DeviceClass::Wait_For_Frame(unsigned timeout_milliseconds)+{+ // Only a present that returned S_OK queued a frame. An occluded one (a minimised or hidden+ // window) or a failed one (a removed device, an invalid call) queued nothing, so nothing will+ // leave the queue to signal the wait, and every frame would sit out the whole limit. The first+ // frame finds the S_OK the device starts with and waits, which keeps waits and presents paired.+ if (FrameLatencyWaitable == NULL || LastPresentResult != S_OK) {+ return true;+ }+ return WaitForSingleObject(FrameLatencyWaitable, timeout_milliseconds) == WAIT_OBJECT_0;+}+HRESULT DX11DeviceClass::Device_Removed_Reason() const{return Device->GetDeviceRemovedReason();diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11device.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11device.hindex 85a7f1933..9d916f772 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11device.h+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11device.h@@ -111,6 +111,13 @@ public:// compositor lets a window present faster than the monitor refreshes.bool Can_Tear() const { return Tearing; }+ // Wait, before a frame is built, until the waitable flip chain has room for it in its queue+ // (MAXIMUM_FRAME_LATENCY in the .cpp). Once a presented frame and no more, or the count the wait+ // keeps drifts. Returns at once on a chain without the wait (the blt model, an older Windows) and+ // after an occluded present; false only when the limit ran out first.+ bool Wait_For_Frame(unsigned timeout_milliseconds);+ bool Has_Frame_Wait() const { return FrameLatencyWaitable != NULL; }+// What the last Present returned, for the one log line a refused present is worth.HRESULT Last_Present_Result() const { return LastPresentResult; }@@ -144,6 +151,8 @@ private:bool DebugLayerRequested;bool DebugLayerPresent;bool Tearing;+ UINT ChainFlags; // what the chain was made with, which ResizeBuffers must repeat+ HANDLE FrameLatencyWaitable; // the waitable chain's handle, closed by ReleaseHRESULT LastPresentResult;};diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cppindex 59ea43fa2..45cbf8277 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp@@ -20,6 +20,8 @@#include "dx11runtime.h"#include <map>+#include <stdio.h>+#include <string.h>#include <string>#include "dx11backend.h"@@ -72,6 +74,275 @@ static const EngineShaderRecord & engine_shader_record(const void * shader)return (entry != EngineShaders.end()) ? entry->second : UNKNOWN;}+// The GPU's own clock over every presented frame, read back without ever waiting for it. A ring of+// GPU_TIMING_SLOTS disjoint brackets, each around four timestamps: the frame's first Begin_Scene since+// the last flip (so the water's reflection pass, which comes before the shadow map, counts as+// shadow), the end of the sun's depth map, the entry to Finish_Scene (the world is drawn, the post+// chain and the interface are not) and the last thing before Present. Once a frame the oldest closed+// bracket is asked for its answer with DONOTFLUSH; one still unanswered when its slot comes round+// again is dropped, and so is one the driver says the clock jumped in. Five queries a frame, cheap+// enough for every build; Direct3D11_Take_GPU_Report sums them.+enum GpuStamp { GPU_FRAME_BEGIN, GPU_SHADOW_END, GPU_SCENE_END, GPU_FRAME_END, GPU_STAMPS };+enum { GPU_TIMING_SLOTS = 4 };++struct GpuTimingSlot+{+ ID3D11Query * Clock; // D3D11_QUERY_TIMESTAMP_DISJOINT around the stamps+ ID3D11Query * Stamps[GPU_STAMPS];+ bool Issued[GPU_STAMPS];+ bool Pending; // closed, not read back yet+ unsigned Frame;+};+static GpuTimingSlot GpuSlots[GPU_TIMING_SLOTS];+static bool GpuTiming = false;+static bool FrameOpen = false; // a Begin_Scene since the last flip+static unsigned FrameNumber = 0; // flips so far; frame n writes slot n % GPU_TIMING_SLOTS++// What the frames read back since the last report add up to.+struct GpuTotals+{+ unsigned Frames;+ unsigned Samples;+ unsigned DroppedBusy;+ unsigned DroppedDisjoint;+ unsigned BubblePairs;+ unsigned WaitTimeouts;+ unsigned long long ConstantWrites;+ unsigned long long ConstantRenames;+ double FrameMs;+ double FrameMaxMs;+ double ShadowMs;+ double SceneMs;+ double PostMs;+ double BubbleMs;+ double WaitMs;+};+static GpuTotals GpuWindow;+static LARGE_INTEGER GpuWindowStart;+// The last frame read back, for the gap between its end and the next one's start.+static bool HaveLastGpuFrame = false;+static unsigned LastGpuFrame = 0;+static UINT64 LastGpuFrameEnd = 0;++static const double GPU_REPORT_INTERVAL_MS = 1000.0;+// The longest the top of a frame waits for room in the swap chain's queue. Two queued frames at+// 20 Hz fit in it; anything past it is a queue that will not drain (a window the compositor stopped+// taking frames from), and the frame goes ahead rather than holding the logic with it.+static const unsigned FRAME_WAIT_LIMIT_MS = 100;++static double elapsed_ms(const LARGE_INTEGER & from, const LARGE_INTEGER & to)+{+ static LARGE_INTEGER frequency = { 0 };+ if (frequency.QuadPart == 0) {+ QueryPerformanceFrequency(&frequency);+ }+ return (double)(to.QuadPart - from.QuadPart) * 1000.0 / (double)frequency.QuadPart;+}++static void release_query(ID3D11Query *& query)+{+ if (query != NULL) {+ query->Release();+ query = NULL;+ }+}++static void release_gpu_timing()+{+ for (unsigned slot = 0; slot < GPU_TIMING_SLOTS; ++slot) {+ release_query(GpuSlots[slot].Clock);+ for (unsigned stamp = 0; stamp < GPU_STAMPS; ++stamp) {+ release_query(GpuSlots[slot].Stamps[stamp]);+ }+ GpuSlots[slot].Pending = false;+ }+ GpuTiming = false;+ FrameOpen = false;+ HaveLastGpuFrame = false;+}++// A driver that refuses a timestamp query leaves the frame untimed and nothing else.+static void create_gpu_timing()+{+ ID3D11Device * device = Device.Get_Device();+ const D3D11_QUERY_DESC clock = { D3D11_QUERY_TIMESTAMP_DISJOINT, 0 };+ const D3D11_QUERY_DESC stamp = { D3D11_QUERY_TIMESTAMP, 0 };+ GpuTiming = true;+ for (unsigned slot = 0; slot < GPU_TIMING_SLOTS && GpuTiming; ++slot) {+ GpuTiming = SUCCEEDED(device->CreateQuery(&clock, &GpuSlots[slot].Clock));+ for (unsigned index = 0; index < GPU_STAMPS && GpuTiming; ++index) {+ GpuTiming = SUCCEEDED(device->CreateQuery(&stamp, &GpuSlots[slot].Stamps[index]));+ }+ }+ if (!GpuTiming) {+ release_gpu_timing();+ }+}++// The oldest closed bracket, if the GPU has answered it. Never waits and never flushes: an answer+// that is not there yet is asked for again next frame.+static void read_oldest_gpu_frame()+{+ ID3D11DeviceContext * context = Device.Get_Context();+ for (unsigned age = GPU_TIMING_SLOTS; age > 0; --age) {+ GpuTimingSlot & slot = GpuSlots[(FrameNumber - age) % GPU_TIMING_SLOTS];+ if (!slot.Pending) {+ continue;+ }+ D3D11_QUERY_DATA_TIMESTAMP_DISJOINT clock;+ if (context->GetData(slot.Clock, &clock, sizeof(clock), D3D11_ASYNC_GETDATA_DONOTFLUSH) != S_OK) {+ return;+ }+ UINT64 stamps[GPU_STAMPS];+ for (unsigned index = 0; index < GPU_STAMPS; ++index) {+ if (slot.Issued[index] && context->GetData(slot.Stamps[index], &stamps[index],+ sizeof(stamps[index]), D3D11_ASYNC_GETDATA_DONOTFLUSH) != S_OK) {+ return;+ }+ }+ slot.Pending = false;+ if (clock.Disjoint) {+ GpuWindow.DroppedDisjoint++;+ HaveLastGpuFrame = false;+ return;+ }+ // A frame with no shadow map spent nothing on one, and a frame that never reached+ // Finish_Scene (a menu, a loading screen) was scene to the end.+ if (!slot.Issued[GPU_SHADOW_END]) {+ stamps[GPU_SHADOW_END] = stamps[GPU_FRAME_BEGIN];+ }+ if (!slot.Issued[GPU_SCENE_END]) {+ stamps[GPU_SCENE_END] = stamps[GPU_FRAME_END];+ }+ const double ms_per_tick = 1000.0 / (double)clock.Frequency;+ const double frame_ms = (double)(stamps[GPU_FRAME_END] - stamps[GPU_FRAME_BEGIN]) * ms_per_tick;+ GpuWindow.Samples++;+ GpuWindow.FrameMs += frame_ms;+ if (frame_ms > GpuWindow.FrameMaxMs) {+ GpuWindow.FrameMaxMs = frame_ms;+ }+ GpuWindow.ShadowMs += (double)(stamps[GPU_SHADOW_END] - stamps[GPU_FRAME_BEGIN]) * ms_per_tick;+ GpuWindow.SceneMs += (double)(stamps[GPU_SCENE_END] - stamps[GPU_SHADOW_END]) * ms_per_tick;+ GpuWindow.PostMs += (double)(stamps[GPU_FRAME_END] - stamps[GPU_SCENE_END]) * ms_per_tick;+ // The GPU sat idle from the last frame's end to this one's start: the frame it had to wait for.+ if (HaveLastGpuFrame && slot.Frame == LastGpuFrame + 1 && stamps[GPU_FRAME_BEGIN] >= LastGpuFrameEnd) {+ GpuWindow.BubbleMs += (double)(stamps[GPU_FRAME_BEGIN] - LastGpuFrameEnd) * ms_per_tick;+ GpuWindow.BubblePairs++;+ }+ HaveLastGpuFrame = true;+ LastGpuFrame = slot.Frame;+ LastGpuFrameEnd = stamps[GPU_FRAME_END];+ return;+ }+}++static void stamp_gpu_frame(GpuStamp stamp)+{+ if (!GpuTiming || !FrameOpen) {+ return;+ }+ GpuTimingSlot & slot = GpuSlots[FrameNumber % GPU_TIMING_SLOTS];+ // The first of each per frame: a second view (the observer's split) draws its own shadow map and+ // finishes its own scene, and those count with what follows them.+ if (!slot.Issued[stamp]) {+ Device.Get_Context()->End(slot.Stamps[stamp]);+ slot.Issued[stamp] = true;+ }+}++// The top of a presented frame, its first Begin_Scene since the last flip. The swap chain's queue is+// waited on here, before the frame is built, and the GPU's clock starts.+static void begin_frame()+{+ if (PresentRequested) {+ LARGE_INTEGER before;+ LARGE_INTEGER after;+ QueryPerformanceCounter(&before);+ if (!Device.Wait_For_Frame(FRAME_WAIT_LIMIT_MS)) {+ GpuWindow.WaitTimeouts++;+ }+ QueryPerformanceCounter(&after);+ GpuWindow.WaitMs += elapsed_ms(before, after);+ }+ FrameOpen = true;+ if (!GpuTiming) {+ return;+ }+ read_oldest_gpu_frame();+ GpuTimingSlot & slot = GpuSlots[FrameNumber % GPU_TIMING_SLOTS];+ if (slot.Pending) {+ slot.Pending = false;+ GpuWindow.DroppedBusy++;+ }+ ID3D11DeviceContext * context = Device.Get_Context();+ context->Begin(slot.Clock);+ context->End(slot.Stamps[GPU_FRAME_BEGIN]);+ for (unsigned index = 0; index < GPU_STAMPS; ++index) {+ slot.Issued[index] = (index == GPU_FRAME_BEGIN);+ }+ slot.Frame = FrameNumber;+}++// The flip: the last stamp and the bracket close, and the next Begin_Scene opens a new frame.+static void end_frame()+{+ if (GpuTiming && FrameOpen) {+ stamp_gpu_frame(GPU_FRAME_END);+ GpuTimingSlot & slot = GpuSlots[FrameNumber % GPU_TIMING_SLOTS];+ Device.Get_Context()->End(slot.Clock);+ slot.Pending = true;+ }+ FrameOpen = false;+ FrameNumber++;+ GpuWindow.Frames++;+}++const char * Direct3D11_Take_GPU_Report()+{+ if (!Active) {+ return NULL;+ }+ LARGE_INTEGER now;+ QueryPerformanceCounter(&now);+ if (GpuWindowStart.QuadPart == 0) {+ GpuWindowStart = now;+ return NULL;+ }+ const double wall_ms = elapsed_ms(GpuWindowStart, now);+ if (wall_ms < GPU_REPORT_INTERVAL_MS) {+ return NULL;+ }++ const GpuTotals & window = GpuWindow;+ const double samples = (window.Samples > 0) ? (double)window.Samples : 1.0;+ const double frames = (window.Frames > 0) ? (double)window.Frames : 1.0;+ const double seconds = wall_ms / 1000.0;+ static char line[512];+ snprintf(line, sizeof(line),+ "%.1f fps | gpu frame avg %.2f max %.2f ms | shadow %.2f scene %.2f post+ui %.2f ms | bubble %.2f ms"+ " | busy %.0f%% | %u samples, dropped %u busy %u disjoint | latency wait %.2f ms a frame, %u timed out"+ " | %.0f constant writes/s, %.0f renames/s",+ window.Frames / seconds, window.FrameMs / samples, window.FrameMaxMs,+ window.ShadowMs / samples, window.SceneMs / samples, window.PostMs / samples,+ (window.BubblePairs > 0) ? window.BubbleMs / window.BubblePairs : 0.0,+ 100.0 * window.FrameMs / wall_ms, window.Samples, window.DroppedBusy, window.DroppedDisjoint,+ window.WaitMs / frames, window.WaitTimeouts,+ (double)window.ConstantWrites / seconds, (double)window.ConstantRenames / seconds);+ memset(&GpuWindow, 0, sizeof(GpuWindow));+ GpuWindowStart = now;+ return line;+}++bool Direct3D11_Has_Frame_Wait()+{+ return Active && Device.Has_Frame_Wait();+}++const char * Direct3D11_Constant_Path()+{+ return Active ? Backend.Constant_Path() : "";+}+void Direct3D11_Enable(bool enabled){Requested = enabled;@@ -111,6 +382,7 @@ bool Direct3D11_Create(HWND window, unsigned width, unsigned height)Post.Set_Chain(PostChain, PostChainLength);}+ create_gpu_timing();Active = true;return true;}@@ -120,6 +392,7 @@ void Direct3D11_Release()if (!Active) {return;}+ release_gpu_timing();Post.Shutdown();Device.Set_Scene_View(NULL);Backend.Shutdown();@@ -311,6 +584,7 @@ void Direct3D11_End_Shadow_Map(){if (Active) {Backend.End_Shadow_Map();+ stamp_gpu_frame(GPU_SHADOW_END);}}@@ -509,6 +783,9 @@ static void take_the_frame_to_the_screen()// The chain binds its own shaders, states and views on the context the backend's draws use.void Direct3D11_Finish_Scene(){+ if (Active) {+ stamp_gpu_frame(GPU_SCENE_END);+ }if (Active && Post.Run_Chain()) {take_the_frame_to_the_screen();}@@ -526,6 +803,11 @@ void Direct3D11_Finish_Frame()void Direct3D11_Begin_Scene(){if (Active) {+ // A frame draws the water's reflection and then itself, a Begin_Scene each, and only the+ // first of them is the top of the frame.+ if (!FrameOpen) {+ begin_frame();+ }// Before the backend binds anything: the scene goes wherever this says it goes, and a frame// that asked for a chain and could not have one falls back to the swap chain here rather// than half way through.@@ -688,15 +970,17 @@ void Direct3D11_Release_Frame_Copies()void Direct3D11_End_Scene(bool flip_frames){- if (Active && flip_frames && PresentRequested) {+ if (!Active || !flip_frames) {+ return;+ }+ if (PresentRequested) {Direct3D11_Finish_Frame();- if (!Device.Present(VSyncRequested ? 1 : 0) && PresentFailure == S_OK) {- PresentFailure = Device.Last_Present_Result();- }}- if (Active && flip_frames) {- Backend.Save_Shader_Cache_If_Due();+ end_frame();+ if (PresentRequested && !Device.Present(VSyncRequested ? 1 : 0) && PresentFailure == S_OK) {+ PresentFailure = Device.Last_Present_Result();}+ Backend.Save_Shader_Cache_If_Due();}bool Direct3D11_Take_Present_Failure(long & result)@@ -897,14 +1181,21 @@ void Direct3D11_Program_Statistics(unsigned & shipped, unsigned & held)}void Direct3D11_Take_Frame_Cost(double & pipeline_milliseconds, unsigned & pipelines,- double & texture_milliseconds, unsigned & textures, unsigned & depth_copies)+ double & texture_milliseconds, unsigned & textures, unsigned & depth_copies,+ unsigned & constant_writes, unsigned & constant_renames){pipeline_milliseconds = 0.0;pipelines = 0;depth_copies = 0;+ constant_writes = 0;+ constant_renames = 0;if (Active) {Backend.Take_Frame_Build_Cost(pipeline_milliseconds, pipelines);depth_copies = Backend.Take_Frame_Depth_Copies();+ Backend.Take_Frame_Constant_Writes(constant_writes, constant_renames);+ // the frame cost line prints only past its threshold; the once a second line takes every frame+ GpuWindow.ConstantWrites += constant_writes;+ GpuWindow.ConstantRenames += constant_renames;}DX11Texture_Take_Frame_Cost(texture_milliseconds, textures);}diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.hindex 8c3f8e732..cf005a5aa 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h@@ -345,9 +345,26 @@ void Direct3D11_Statistics(unsigned & pipelines_built, unsigned long long & drawvoid Direct3D11_Program_Statistics(unsigned & shipped, unsigned & held);// What the frame since the last call spent building pipelines and copying textures, and how many-// of each, and how many times the soft particles copied the scene's depth. Taking it resets it.+// of each, how many times the soft particles copied the scene's depth, and how many constant blocks+// were written and how many of those writes renamed their buffer. Taking it resets it.void Direct3D11_Take_Frame_Cost(double & pipeline_milliseconds, unsigned & pipelines,- double & texture_milliseconds, unsigned & textures, unsigned & depth_copies);+ double & texture_milliseconds, unsigned & textures, unsigned & depth_copies,+ unsigned & constant_writes, unsigned & constant_renames);++// One line for the log once a second, null in between: the frame rate, the GPU's own time for a+// presented frame (average and worst, split into shadow map, world, and post chain with interface),+// the GPU's idle gap between two frames, busy as GPU time over wall time, how many frames were read+// back and how many were dropped, the time the top of the frame waited for the swap chain's queue,+// and the constant writes and renames a second. Timestamp queries read back a few frames late and+// never waited on, so it costs the frame nothing it can measure. Taking it resets it.+const char * Direct3D11_Take_GPU_Report();++// The swap chain holds its queue with a wait at the top of the frame rather than inside Present.+bool Direct3D11_Has_Frame_Wait();++// How the backend writes its constant blocks (DX11BackendClass::Constant_Path), for the shutdown+// report. Empty with no backend.+const char * Direct3D11_Constant_Path();// 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.diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime_posix.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime_posix.cppindex ea0e1d905..d8d0f967f 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime_posix.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime_posix.cpp@@ -167,14 +167,20 @@ void Direct3D11_Program_Statistics(unsigned & shipped, unsigned & held)held = 0;}void Direct3D11_Take_Frame_Cost(double & pipeline_milliseconds, unsigned & pipelines,- double & texture_milliseconds, unsigned & textures, unsigned & depth_copies)+ double & texture_milliseconds, unsigned & textures, unsigned & depth_copies,+ unsigned & constant_writes, unsigned & constant_renames){pipeline_milliseconds = 0.0;pipelines = 0;texture_milliseconds = 0.0;textures = 0;depth_copies = 0;+ constant_writes = 0;+ constant_renames = 0;}+const char * Direct3D11_Take_GPU_Report() { return NULL; }+bool Direct3D11_Has_Frame_Wait() { return false; }+const char * Direct3D11_Constant_Path() { return ""; }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,diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11twin.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11twin.cppindex 5801a9563..6b9dae7ee 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11twin.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11twin.cpp@@ -149,7 +149,11 @@ void * DX11BufferLockClass::Begin(DX11BufferTwinClass * twin, void * d3d9_memoryD3D9Memory = d3d9_memory;ByteOffset = byte_offset;ByteCount = byte_count == 0 ? Twin->Byte_Count() - byte_offset : byte_count;- Discard = (lock_flags & D3DLOCK_DISCARD) != 0;+ // A lock with neither flag is a discard on a dynamic buffer, the way DX11Resource_Translate_Lock+ // reads it. Mapped NO_OVERWRITE it wrote over vertices a draw from the last pass could still be+ // reading: the edging and the sea patch write their whole buffer with flags 0, the tank tracks+ // a run from the start of theirs.+ Discard = (lock_flags & (D3DLOCK_DISCARD | D3DLOCK_NOOVERWRITE)) != D3DLOCK_NOOVERWRITE;CopyToD3D9 = copy_to_d3d9;Mapped = false;diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8indexbuffer.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8indexbuffer.cppindex 04364ee23..264f2fb32 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8indexbuffer.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8indexbuffer.cpp@@ -487,6 +487,13 @@ void DynamicIBAccessClass::_Deinit()//// ----------------------------------------------------------------------------+// The shared dynamic index buffer goes to its twin alone while Direct3D 11 presents, for the reason+// on the vertex buffer's copy of this in dx8vertexbuffer.cpp.+static bool d3d9_reads_dynamic_buffer(DX8IndexBufferClass* buffer)+{+ return !Direct3D11_Present_Is_Enabled() || buffer->Get_DX11_Twin()==NULL;+}+DynamicIBAccessClass::WriteLockClass::WriteLockClass(DynamicIBAccessClass* ib_access_):DynamicIBAccess(ib_access_)@@ -503,20 +510,17 @@ DynamicIBAccessClass::WriteLockClass::WriteLockClass(DynamicIBAccessClass* ib_acbreak;}DX8_Assert();- DX8_ErrorCode(- static_cast<DX8IndexBufferClass*>(DynamicIBAccess->IndexBuffer)->Get_DX8_Index_Buffer()->Lock(- DynamicIBAccess->IndexBufferOffset*sizeof(WORD),- 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,- !Direct3D11_Present_Is_Enabled());+ DX8IndexBufferClass* buffer=static_cast<DX8IndexBufferClass*>(DynamicIBAccess->IndexBuffer);+ const bool d3d9_reads=d3d9_reads_dynamic_buffer(buffer);+ const unsigned lock_flags=!DynamicIBAccess->IndexBufferOffset ? D3DLOCK_DISCARD : D3DLOCK_NOOVERWRITE;+ const unsigned byte_offset=DynamicIBAccess->IndexBufferOffset*sizeof(WORD);+ const unsigned byte_count=DynamicIBAccess->Get_Index_Count()*sizeof(WORD);+ Indices=NULL;+ if (d3d9_reads) {+ DX8_ErrorCode(buffer->Get_DX8_Index_Buffer()->Lock(byte_offset,byte_count,(void**)&Indices,lock_flags));+ }+ void* mirror=DX11Lock.Begin(buffer->Get_DX11_Twin(),Indices,byte_offset,byte_count,lock_flags,d3d9_reads);if (mirror) Indices=(unsigned short*)mirror;}break;@@ -538,7 +542,9 @@ DynamicIBAccessClass::WriteLockClass::~WriteLockClass()if (static_cast<DX8IndexBufferClass*>(DynamicIBAccess->IndexBuffer)->Get_DX8_Index_Buffer()==NULL) break;DX8_Assert();DX11Lock.End();- DX8_ErrorCode(static_cast<DX8IndexBufferClass*>(DynamicIBAccess->IndexBuffer)->Get_DX8_Index_Buffer()->Unlock());+ if (d3d9_reads_dynamic_buffer(static_cast<DX8IndexBufferClass*>(DynamicIBAccess->IndexBuffer))) {+ DX8_ErrorCode(static_cast<DX8IndexBufferClass*>(DynamicIBAccess->IndexBuffer)->Get_DX8_Index_Buffer()->Unlock());+ }break;case BUFFER_TYPE_DYNAMIC_SORTING:break;diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8vertexbuffer.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8vertexbuffer.cppindex 183999236..22d206e9a 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8vertexbuffer.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8vertexbuffer.cpp@@ -936,6 +936,16 @@ void DynamicVBAccessClass::Allocate_Sorting_Dynamic_Buffer()}// ----------------------------------------------------------------------------++// While Direct3D 11 presents, Direct3D 9 skips every indexed draw, so the shared dynamic buffer is+// written into its twin alone and the Direct3D 9 copy is never locked; that lock and unlock were a+// driver round trip several hundred times a frame for bytes nothing read. A buffer the twin was+// refused for keeps its Direct3D 9 lock, which is then the only memory there is to write.+static bool d3d9_reads_dynamic_buffer(DX8VertexBufferClass* buffer)+{+ return !Direct3D11_Present_Is_Enabled() || buffer->Get_DX11_Twin()==NULL;+}+static int dx8_lock;DynamicVBAccessClass::WriteLockClass::WriteLockClass(DynamicVBAccessClass* dynamic_vb_access_):@@ -968,20 +978,19 @@ DynamicVBAccessClass::WriteLockClass::WriteLockClass(DynamicVBAccessClass* dynam}DX8_Assert();- // Lock with discard contents if the buffer offset is zero- DX8_ErrorCode(static_cast<DX8VertexBufferClass*>(DynamicVBAccess->VertexBuffer)->Get_DX8_Vertex_Buffer()->Lock(- DynamicVBAccess->VertexBufferOffset*_DynamicDX8VertexBuffer->FVF_Info().Get_FVF_Size(),- 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,- !Direct3D11_Present_Is_Enabled());+ DX8VertexBufferClass* buffer=static_cast<DX8VertexBufferClass*>(DynamicVBAccess->VertexBuffer);+ const bool d3d9_reads=d3d9_reads_dynamic_buffer(buffer);+ // Lock with discard contents if the buffer offset is zero+ const unsigned lock_flags=!DynamicVBAccess->VertexBufferOffset ? D3DLOCK_DISCARD : D3DLOCK_NOOVERWRITE;+ const unsigned byte_offset=DynamicVBAccess->VertexBufferOffset*buffer->FVF_Info().Get_FVF_Size();+ const unsigned byte_count=DynamicVBAccess->Get_Vertex_Count()*buffer->FVF_Info().Get_FVF_Size();+ Vertices=NULL;+ if (d3d9_reads) {+ DX8_ErrorCode(buffer->Get_DX8_Vertex_Buffer()->Lock(byte_offset,byte_count,(void**)&Vertices,+ D3DLOCK_NOSYSLOCK|lock_flags));+ }+ void* mirror=DX11Lock.Begin(buffer->Get_DX11_Twin(),Vertices,byte_offset,byte_count,lock_flags,d3d9_reads);if (mirror) Vertices=(VertexFormatXYZNDUV2*)mirror;}break;@@ -1012,7 +1021,9 @@ DynamicVBAccessClass::WriteLockClass::~WriteLockClass()if (static_cast<DX8VertexBufferClass*>(DynamicVBAccess->VertexBuffer)->Get_DX8_Vertex_Buffer()==NULL) break;DX8_Assert();DX11Lock.End();- DX8_ErrorCode(static_cast<DX8VertexBufferClass*>(DynamicVBAccess->VertexBuffer)->Get_DX8_Vertex_Buffer()->Unlock());+ if (d3d9_reads_dynamic_buffer(static_cast<DX8VertexBufferClass*>(DynamicVBAccess->VertexBuffer))) {+ DX8_ErrorCode(static_cast<DX8VertexBufferClass*>(DynamicVBAccess->VertexBuffer)->Get_DX8_Vertex_Buffer()->Unlock());+ }break;case BUFFER_TYPE_DYNAMIC_SORTING:break;diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cppindex 2049d9112..9c001632c 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp@@ -206,11 +206,13 @@ void DX8Wrapper::_Set_DX8_Render_Target(IDirect3DSurface9 * render_target, IDire}void DX8Wrapper::_Draw_DX8_Primitive_UP(D3DPRIMITIVETYPE type, unsigned primitive_count,- const void * vertices, unsigned stride)+ const void * vertices, unsigned stride, bool d3d9_reads_back){- // Drawn on Direct3D 9 whichever device presents: the smudge test reads this draw back.- Flush_Deferred_D3D9_State();- DX8CALL(DrawPrimitiveUP(type, primitive_count, vertices, stride));+ if (!Direct3D11_Present_Is_Enabled() || d3d9_reads_back) {+ Flush_Deferred_D3D9_State();+ Open_D3D9_Scene();+ DX8CALL(DrawPrimitiveUP(type, primitive_count, vertices, stride));+ }if (type == D3DPT_TRIANGLESTRIP) {Direct3D11_Draw_User_Strip(vertices, primitive_count, stride);}@@ -342,6 +344,7 @@ D3DMATERIAL9 DX8Wrapper::PendingMaterialValue;unsigned DX8Wrapper::PendingLights = 0;unsigned DX8Wrapper::PendingLightEnables = 0;D3DLIGHT9 DX8Wrapper::PendingLightValues[4];+bool DX8Wrapper::D3D9SceneOpen = false;bool DX8Wrapper::IsDeviceLost;int DX8Wrapper::ZBias;float DX8Wrapper::ZNear;@@ -1147,6 +1150,8 @@ bool DX8Wrapper::Reset_Device(bool reload_assets)RenderResult hr=_Get_D3D_Device()->TestCooperativeLevel();if (hr != D3DERR_DEVICELOST ){ DX8CALL_HRES(Reset(&_PresentParameters),hr)+ // A reset ends any scene the device had open.+ D3D9SceneOpen=false;if (hr != D3D_OK)return false; //reset failed.}@@ -1176,6 +1181,7 @@ void DX8Wrapper::Release_Device(void)// So that no pending bit outlives this device and is sent to the next one.Flush_Deferred_D3D9_State();+ D3D9SceneOpen=false;// The device made every shader in the combiner cache and outliving it is not something they// can do. Nothing recompiles them: the next draw asks the cache again and it is empty.@@ -2270,6 +2276,13 @@ void DX8_Assert()DX8_THREAD_ASSERT();}+void DX8Wrapper::Open_D3D9_Scene()+{+ if (D3D9SceneOpen) return;+ DX8CALL(BeginScene());+ D3D9SceneOpen=true;+}+void DX8Wrapper::Begin_Scene(void){DX8_THREAD_ASSERT();@@ -2277,8 +2290,12 @@ void DX8Wrapper::Begin_Scene(void)#if ENABLE_EMBEDDED_BROWSERDX8WebBrowser::Update();#endif-- DX8CALL(BeginScene());++ // With Direct3D 11 presenting, the smudge test's two quads are what is left for the Direct3D 9+ // device to draw, and those begin its scene themselves.+ if (!Direct3D11_Present_Is_Enabled()) {+ Open_D3D9_Scene();+ }Direct3D11_Begin_Scene();#if defined(_WIN32)@@ -2289,7 +2306,10 @@ void DX8Wrapper::Begin_Scene(void)void DX8Wrapper::End_Scene(bool flip_frames){DX8_THREAD_ASSERT();- DX8CALL(EndScene());+ if (D3D9SceneOpen) {+ DX8CALL(EndScene());+ D3D9SceneOpen=false;+ }Direct3D11_End_Scene(flip_frames);#if defined(_WIN32)@@ -2419,6 +2439,13 @@ void DX8Wrapper::Clear(bool clear_color, bool clear_z_stencil, const Vector3 &co{DX8_THREAD_ASSERT();+ // Nothing reads a cleared Direct3D 9 target while Direct3D 11 presents: the smudge test reads back+ // only the corner its own quad covers.+ if (Direct3D11_Present_Is_Enabled()) {+ Direct3D11_Mirror_Clear(clear_color, clear_z_stencil, color.X, color.Y, color.Z, dest_alpha);+ return;+ }+// If we try to clear a stencil buffer which is not there, the entire call will fail// KJM fixed this to get format from back buffer (incase render to texture is used)/*bool has_stencil = ( _PresentParameters.AutoDepthStencilFormat == D3DFMT_D15S1 ||@@ -2880,8 +2907,8 @@ void DX8Wrapper::Draw(// When Direct3D 11 owns the window, the Direct3D 9 frame is never shown and nothing// reads its pixels back, so drawing it is only GPU time. Most of the state for it is// deferred as well (Defer_D3D9_State) and sent only before the probe's sampled draws.- // _Draw_DX8_Primitive_UP keeps its D3D9 draw, because the smudge hardware test draws- // with it and reads the D3D9 target back.+ // _Draw_DX8_Primitive_UP keeps its D3D9 draw for the smudge hardware test alone,+ // which reads the D3D9 target back.if (!Direct3D11_Present_Is_Enabled()) {DX8CALL(DrawIndexedPrimitive((D3DPRIMITIVETYPE)primitive_type,@@ -3084,6 +3111,11 @@ void DX8Wrapper::Apply_Render_State_Changes()SNAPSHOT_SAY(("DX8 - apply view matrix\n"));_Set_DX8_Transform(D3DTS_VIEW,render_state.view);}+ // The streams and the indices are sent to Direct3D 9 only for its own indexed draws, which it+ // skips while Direct3D 11 presents, and nothing reads either back off the device. The draws that+ // set their own buffers behind this wrapper's back (water, shadows, snow) set them on the device+ // themselves.+ const bool d3d9_draws_indexed=!Direct3D11_Present_Is_Enabled();if (render_state_changed&VERTEX_BUFFER_CHANGED) {SNAPSHOT_SAY(("DX8 - apply vb change\n"));for (i=0;i<MAX_VERTEX_STREAMS;++i) {@@ -3091,11 +3123,13 @@ void DX8Wrapper::Apply_Render_State_Changes()switch (render_state.vertex_buffer_types[i]) {//->Type()) {case BUFFER_TYPE_DX8:case BUFFER_TYPE_DYNAMIC_DX8:- DX8CALL(SetStreamSource(- i,- static_cast<DX8VertexBufferClass*>(render_state.vertex_buffers[i])->Get_DX8_Vertex_Buffer(),- 0, // OffsetInBytes, D3D9's extra parameter- render_state.vertex_buffers[i]->FVF_Info().Get_FVF_Size()));+ if (d3d9_draws_indexed) {+ DX8CALL(SetStreamSource(+ i,+ static_cast<DX8VertexBufferClass*>(render_state.vertex_buffers[i])->Get_DX8_Vertex_Buffer(),+ 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.@@ -3120,7 +3154,9 @@ void DX8Wrapper::Apply_Render_State_Changes()WWASSERT(0);}} else {- DX8CALL(SetStreamSource(i,NULL,0,0));+ if (d3d9_draws_indexed) {+ DX8CALL(SetStreamSource(i,NULL,0,0));+ }if (i==0) {Direct3D11_Mirror_Stream_Source(NULL,0,0);}@@ -3135,8 +3171,10 @@ void DX8Wrapper::Apply_Render_State_Changes()case BUFFER_TYPE_DX8:case BUFFER_TYPE_DYNAMIC_DX8:// 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()));+ if (d3d9_draws_indexed) {+ 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();@@ -3149,7 +3187,9 @@ void DX8Wrapper::Apply_Render_State_Changes()}}else {- DX8CALL(SetIndices(NULL));+ if (d3d9_draws_indexed) {+ DX8CALL(SetIndices(NULL));+ }Direct3D11_Mirror_Indices(NULL);DX8_RECORD_INDEX_BUFFER_CHANGE();}@@ -5617,6 +5657,7 @@ void DX8Wrapper::Draw_Owned_Triangles(unsigned first_index, unsigned triangle_coconst unsigned index_count=as_strip ? (triangle_count+2) : (triangle_count*3);Flush_Deferred_D3D9_State();+ Open_D3D9_Scene();DX8CALL(DrawIndexedPrimitive(as_strip ? D3DPT_TRIANGLESTRIP : D3DPT_TRIANGLELIST,0, // BaseVertexIndex: the stream offset already moved the vertices@@ -5641,6 +5682,7 @@ void DX8Wrapper::Draw_Owned_Points(unsigned first_vertex, unsigned point_count)if (point_count==0) return;Flush_Deferred_D3D9_State();+ Open_D3D9_Scene();DX8CALL(DrawPrimitive(D3DPT_POINTLIST, first_vertex, point_count));// No mirror: the Direct3D 11 backend resolves triangles out of the fixed-function state anddiff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.hindex 805086d16..6bd0a3eae 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.h+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.h@@ -690,8 +690,12 @@ public:// 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.+ //+ // While Direct3D 11 presents, Direct3D 9 draws one only for a caller that reads the Direct3D 9+ // target back afterwards, which is what d3d9_reads_back says: the smudge hardware test. Every+ // other quad would cost a full flush of the deferred state and a draw nobody sees.static void _Draw_DX8_Primitive_UP(D3DPRIMITIVETYPE type, unsigned primitive_count,- const void * vertices, unsigned stride);+ const void * vertices, unsigned stride, bool d3d9_reads_back = false);static void _Copy_DX8_Rects(IDirect3DSurface9* pSourceSurface,@@ -1033,6 +1037,11 @@ protected:static unsigned PendingLightEnables;static D3DLIGHT9 PendingLightValues[4];+ // While Direct3D 11 presents, the Direct3D 9 scene is begun by the first draw that still goes to+ // that device, not by Begin_Scene, and End_Scene ends it only if one was begun.+ static void Open_D3D9_Scene();+ static bool D3D9SceneOpen;+static unsigned long FrameCount;static DX8Caps* CurrentCaps;diff --git a/GeneralsMD/Code/Tests/test_dx11backend.cpp b/GeneralsMD/Code/Tests/test_dx11backend.cppindex a7a05a023..88613d6d9 100644--- a/GeneralsMD/Code/Tests/test_dx11backend.cpp+++ b/GeneralsMD/Code/Tests/test_dx11backend.cpp@@ -368,6 +368,122 @@ TEST(dx11backend_the_same_state_resolves_to_one_pipeline)backend.Shutdown();}+// The vertex block goes into a ring of 4096 one-kilobyte entries, so 5000 draws with a world matrix+// each wrap it once, and the draw after them reads an entry written NO_OVERWRITE past the discard.+// Every one of the 5000 puts the quad off the target; the last puts it back over the whole of it.+// A wrap that bound the wrong entry, or wrote into the allocation the discard threw away, draws+// that last quad off the target too and the centre stays the clear colour. Then the bindings are+// forgotten and the same draw is made again with nothing changed: no block is written, and only a+// rebind at the entry the last write went to puts the quad back.+TEST(dx11backend_a_wrapped_constant_ring_draws_with_the_latest_block)+{+ const unsigned OFF_TARGET_DRAWS = 5000;++ DX11DeviceClass device;+ device.Request_Debug_Layer();+ CHECK(device.Create_Offscreen());+ ID3D11Device * d3d = device.Get_Device();++ DX11BackendClass backend;+ CHECK(backend.Initialise(&device));++ D3D11_TEXTURE2D_DESC target_description;+ memset(&target_description, 0, sizeof(target_description));+ target_description.Width = TARGET_SIZE;+ target_description.Height = TARGET_SIZE;+ target_description.MipLevels = 1;+ target_description.ArraySize = 1;+ target_description.Format = DXGI_FORMAT_B8G8R8A8_UNORM;+ target_description.SampleDesc.Count = 1;+ target_description.Usage = D3D11_USAGE_DEFAULT;+ target_description.BindFlags = D3D11_BIND_RENDER_TARGET;++ ID3D11Texture2D * target = NULL;+ CHECK(SUCCEEDED(d3d->CreateTexture2D(&target_description, NULL, &target)));++ D3D11_TEXTURE2D_DESC staging_description = target_description;+ staging_description.Usage = D3D11_USAGE_STAGING;+ staging_description.BindFlags = 0;+ staging_description.CPUAccessFlags = D3D11_CPU_ACCESS_READ;++ ID3D11Texture2D * staging = NULL;+ CHECK(SUCCEEDED(d3d->CreateTexture2D(&staging_description, NULL, &staging)));++ ID3D11RenderTargetView * target_view = NULL;+ CHECK(SUCCEEDED(d3d->CreateRenderTargetView(target, NULL, &target_view)));++ const float clear_colour[4] = { 0.0f, 1.0f, 0.0f, 1.0f };+ device.Get_Context()->OMSetRenderTargets(1, &target_view, NULL);++ backend.Set_Viewport(0, 0, TARGET_SIZE, TARGET_SIZE);+ configure_unlit_pass_through(backend);++ ID3D11Buffer * vertices = NULL;+ CHECK(DX11Resource_Create_Vertex_Buffer(d3d, sizeof(QUAD_VERTICES), D3DPOOL_MANAGED, 0,+ QUAD_VERTICES, &vertices));++ ID3D11Buffer * indices = NULL;+ CHECK(DX11Resource_Create_Index_Buffer(d3d, sizeof(QUAD_INDICES), D3DPOOL_MANAGED, 0,+ QUAD_INDICES, &indices));++ backend.Set_Stream_Source(vertices, sizeof(BackendVertex), 0);+ backend.Set_Indices(indices, DXGI_FORMAT_R16_UINT);++ // Clip x from 2 up, a hair further each draw so every block differs from the one before.+ float world[16];+ for (unsigned draw = 0; draw < OFF_TARGET_DRAWS; ++draw) {+ set_identity(world);+ world[12] = 3.0f + 0.0001f * static_cast<float>(draw);+ backend.Set_Transform(D3DTS_WORLD, world);+ CHECK(backend.Draw_Indexed_Triangles(6, 0, 0));+ }++ for (unsigned pass = 0; pass < 2; ++pass) {+ device.Get_Context()->ClearRenderTargetView(target_view, clear_colour);+ if (pass == 0) {+ set_identity(world);+ backend.Set_Transform(D3DTS_WORLD, world);+ } else {+ backend.Forget_Bindings();+ }+ CHECK(backend.Draw_Indexed_Triangles(6, 0, 0));++ device.Get_Context()->CopyResource(staging, target);+ D3D11_MAPPED_SUBRESOURCE mapped;+ CHECK(SUCCEEDED(device.Get_Context()->Map(staging, 0, D3D11_MAP_READ, 0, &mapped)));+ const unsigned char * centre = static_cast<const unsigned char *>(mapped.pData)+ + mapped.RowPitch * (TARGET_SIZE / 2) + (TARGET_SIZE / 2) * 4;+ if (centre[0] != EXPECTED_BLUE) {+ printf(" pass %u centre pixel bgra %02x %02x %02x %02x\n",+ pass, centre[0], centre[1], centre[2], centre[3]);+ }+ CHECK_EQ(centre[0], EXPECTED_BLUE);+ CHECK_EQ(centre[1], EXPECTED_GREEN);+ CHECK_EQ(centre[2], EXPECTED_RED);+ device.Get_Context()->Unmap(staging, 0);+ }++ // One vertex block a draw before the second pass, which writes none, and one pixel block. A+ // ring renames on its first write and on each wrap: the vertex ring twice, the pixel ring once.+ // Without offsets every write is a rename.+ unsigned writes = 0;+ unsigned renames = 0;+ backend.Take_Frame_Constant_Writes(writes, renames);+ CHECK_EQ(writes, OFF_TARGET_DRAWS + 2);+ if (backend.Constant_Offsets()) {+ CHECK_EQ(renames, 3u);+ } else {+ CHECK_EQ(renames, writes);+ }++ indices->Release();+ vertices->Release();+ target_view->Release();+ staging->Release();+ target->Release();+ backend.Shutdown();+}+// The sorted smoke billboards carry a fire's glow in their normals, and the backend adds it to what// the stages made. The quad's normal is (0, 0, 1), so with the glow on the blue channel goes to full// and the other two keep the vertex colour; the glow is its own pipeline and turning it off goes