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(ww3d2): present direct3d 11 through a flip swap chain with tearing
Olcay Seyganb8f4a4912193
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 369fd8513..dba07e070 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -17,6 +17,7 @@ found and fixed — EA's own, not port damage.**- The picture now runs uncapped; the rules keep their own steady clock.- On a machine with two graphics chips, the game used to draw on the first one it found, which was the slow one. It now uses the dedicated card, and a match holds about 260 frames a second with the trees, the shadows and the filtering left on.- Display options has a vertical sync box. Off, the picture still runs free. On, it waits for the monitor so the frame does not tear. The box takes effect when you Accept.+- With vertical sync off, the picture really is free again. Ever since the game started drawing through Direct3D 11, fullscreen and windowed games were still held to the monitor's refresh: 164 frames a second on a 164 Hz screen, and a 60 Hz screen sat at 60 and sank into the fifties in a fight, where the old renderer had given players over 450. The same match now takes 2.3ms a frame, over 400 a second, where it was pinned at 6.1ms. Every picture is the same one it was. Vertical sync on still waits for the monitor.- A slow moment costs you a dropped frame, not a slow game.- Explosions no longer catch the picture. The first time each kind of fire, smoke or blast reached the screen, the game stopped for 25 to 60ms to prepare it, and the opening volley of a fight cost 300ms at once. That work is kept on disk and ships with the game, so it happens while the map loads, in about 3ms, and the worst frame of the same battle went from 141ms to 38ms.- The price, build time and power figures on the command bar buttons stopped costing you frames. All the buttons shared one piece of text, so every figure on the bar was lettered from scratch every frame, about 33 of them. Each now keeps its own: a battle that averaged 14ms a frame averages 11.7ms, frames slower than 60 a second went from one in six to one in a hundred, and the old renderer gets about 0.8ms back too. The money readout was lettered again every frame as well, for a number that had not changed; it is lettered when the number moves. Over a whole battle the game now letters 163 pieces of text where it lettered 68,227.diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cppindex bb8191e61..2b0ced4a1 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp@@ -1117,6 +1117,9 @@ void W3DDisplay::init( void )DEBUG_LOG(("W3DDisplay::init - multisampling: %ux\n", DX8Wrapper::Get_MultiSample_Level()));DEBUG_LOG(("W3DDisplay::init - vsync: %s\n", DX8Wrapper::Get_Requested_VSync() ? "on" : "off"));DEBUG_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 - adapter: %s\n",WW3D::Get_Render_Device_Name(WW3D::Get_Render_Device())));{@@ -2491,6 +2494,11 @@ AGAIN: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\n",TheGameLogic->getFrame(), pipelines, pipelineMS, textures, textureMS));++ long presentResult = 0;+ if( Direct3D11_Take_Present_Failure( presentResult ) )+ DEBUG_LOG(("DX11 PRESENT refused at frame %d: 0x%08X, logged once\n",+ TheGameLogic->getFrame(), (UnsignedInt)presentResult));}/* End_Render is where a lost device is noticed and reset, and that reset is the mostdiff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11device.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11device.cppindex e323db3ce..3134a5327 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11device.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11device.cpp@@ -18,6 +18,8 @@#include "dx11device.h"+#include <dxgi1_5.h>+// The back buffer is the same format the D3D9 device asks for, so a picture taken off one can be// compared against the other without a conversion standing between them.static const DXGI_FORMAT BACK_BUFFER_FORMAT = DXGI_FORMAT_B8G8R8A8_UNORM;@@ -45,6 +47,28 @@ static void release_interface(IUnknown ** object)}}+// DXGI 1.5, Windows 10 with a driver that agrees. Without it a flip model window still waits for+// the compositor, so there is nothing to gain over the blt model and the old swap chain stays.+static bool tearing_supported()+{+ IDXGIFactory1 * factory = NULL;+ if (FAILED(CreateDXGIFactory1(__uuidof(IDXGIFactory1), reinterpret_cast<void **>(&factory)))) {+ return false;+ }+ BOOL allowed = FALSE;+ IDXGIFactory5 * factory5 = NULL;+ if (SUCCEEDED(factory->QueryInterface(__uuidof(IDXGIFactory5),+ reinterpret_cast<void **>(&factory5)))) {+ if (FAILED(factory5->CheckFeatureSupport(DXGI_FEATURE_PRESENT_ALLOW_TEARING, &allowed,+ sizeof(allowed)))) {+ allowed = FALSE;+ }+ factory5->Release();+ }+ factory->Release();+ return allowed != FALSE;+}+DX11DeviceClass::DX11DeviceClass(): Device(NULL), Context(NULL)@@ -60,6 +84,8 @@ DX11DeviceClass::DX11DeviceClass(), Software(false), DebugLayerRequested(false), DebugLayerPresent(false)+ , Tearing(false)+ , LastPresentResult(S_OK){}@@ -98,6 +124,18 @@ bool DX11DeviceClass::Create_Device(bool with_swap_chain, HWND window, unsignedswap_chain.Windowed = TRUE;swap_chain.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;+ // The blt model above is composed by the desktop once a refresh whatever the sync interval, so+ // with vsync off the game still ran at exactly the monitor's rate, fullscreen included, since+ // fullscreen is this window over a mode change. The flip model with tearing allowed is the one+ // a window may present past the refresh with. It is tried first where DXGI allows tearing, and+ // a create that refuses it falls back to the blt model, which is what this always was.+ DXGI_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;+ const unsigned chain_choice_count = sizeof(chain_choices)/sizeof(chain_choices[0]);+// Hardware first, WARP second. WARP draws the same picture on a machine with no D3D11 driver,// which is what makes the device creatable on a build agent as well as on this one.const D3D_DRIVER_TYPE driver_types[] = { D3D_DRIVER_TYPE_HARDWARE, D3D_DRIVER_TYPE_WARP };@@ -113,25 +151,37 @@ bool DX11DeviceClass::Create_Device(bool with_swap_chain, HWND window, unsignedfor (unsigned index = 0; index < driver_type_count; ++index) {for (unsigned flag_index = flag_start; flag_index < flag_choice_count; ++flag_index) {- const UINT flags = flag_choices[flag_index];- const HRESULT result = Create_Device_Guarded(with_swap_chain, driver_types[index], flags,- &swap_chain);- if (FAILED(result)) {- continue;- }+ for (unsigned chain_index = chain_start; chain_index < chain_choice_count; ++chain_index) {+ const UINT flags = flag_choices[flag_index];+ const HRESULT result = Create_Device_Guarded(with_swap_chain, driver_types[index], flags,+ chain_choices[chain_index]);+ if (FAILED(result)) {+ continue;+ }- Software = (driver_types[index] == D3D_DRIVER_TYPE_WARP);- DebugLayerPresent = (flags & D3D11_CREATE_DEVICE_DEBUG) != 0;- Width = width;- Height = height;- if (!with_swap_chain) {- return true;- }- if (Create_Views()) {- return true;+ Software = (driver_types[index] == D3D_DRIVER_TYPE_WARP);+ DebugLayerPresent = (flags & D3D11_CREATE_DEVICE_DEBUG) != 0;+ Tearing = (chain_choices[chain_index] == &flip_chain);+ Width = width;+ Height = height;+ if (!with_swap_chain) {+ return true;+ }+ // 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.+ IDXGIFactory1 * factory = NULL;+ if (SUCCEEDED(SwapChain->GetParent(__uuidof(IDXGIFactory1),+ reinterpret_cast<void **>(&factory)))) {+ factory->MakeWindowAssociation(window, DXGI_MWA_NO_ALT_ENTER);+ factory->Release();+ }+ if (Create_Views()) {+ return true;+ }+ Release();+ return false;}- Release();- return false;}}@@ -246,13 +296,16 @@ void DX11DeviceClass::Release()Width = 0;Height = 0;Software = false;+ Tearing = false;}bool DX11DeviceClass::Resize(unsigned width, unsigned height){Release_Views();+ // 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;if (FAILED(SwapChain->ResizeBuffers(SWAP_CHAIN_BUFFER_COUNT, width, height,- BACK_BUFFER_FORMAT, 0))) {+ BACK_BUFFER_FORMAT, chain_flags))) {return false;}Width = width;@@ -272,7 +325,33 @@ void DX11DeviceClass::Clear(float red, float green, float blue, float alpha, boobool DX11DeviceClass::Present(unsigned present_interval){- return SUCCEEDED(SwapChain->Present(present_interval, 0));+ if (!Tearing) {+ LastPresentResult = SwapChain->Present(present_interval, 0);+ return SUCCEEDED(LastPresentResult);+ }++ // A flip model Present unbinds the back buffer from the output merger. The backend keeps its+ // own record of what is bound and sends only the difference, so whatever was bound goes back+ // on, and the next frame's first draw lands where the backend thinks it does.+ ID3D11RenderTargetView * targets[D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT] = { NULL };+ ID3D11DepthStencilView * depth = NULL;+ Context->OMGetRenderTargets(D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT, targets, &depth);++ // Tearing is only allowed with a sync interval of 0; vsync on is an ordinary flip.+ const HRESULT result = SwapChain->Present(present_interval,+ present_interval == 0 ? DXGI_PRESENT_ALLOW_TEARING : 0);++ Context->OMSetRenderTargets(D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT, targets, depth);+ for (unsigned index = 0; index < D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT; ++index) {+ if (targets[index] != NULL) {+ targets[index]->Release();+ }+ }+ if (depth != NULL) {+ depth->Release();+ }+ LastPresentResult = result;+ return SUCCEEDED(result);}HRESULT DX11DeviceClass::Device_Removed_Reason() constdiff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11device.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11device.hindex 0aa96a189..f9fecff02 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11device.h+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11device.h@@ -105,6 +105,13 @@ public:// present_interval is DXGI's sync interval: 0 for no wait, 1 for the next vertical blank.bool Present(unsigned present_interval);+ // True when the swap chain is the flip model with tearing allowed, which is the only kind the+ // compositor lets a window present faster than the monitor refreshes.+ bool Can_Tear() const { return Tearing; }++ // What the last Present returned, for the one log line a refused present is worth.+ HRESULT Last_Present_Result() const { return LastPresentResult; }+// D3DERR_DEVICELOST's replacement. S_OK while the device is usable; anything else is a driver// reset or a removed adapter and the device has to be built again from scratch.HRESULT Device_Removed_Reason() const;@@ -134,6 +141,8 @@ private:bool Software;bool DebugLayerRequested;bool DebugLayerPresent;+ bool Tearing;+ HRESULT LastPresentResult;};#endif // DX11DEVICE_Hdiff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cppindex 63d37e071..f3ced42a0 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp@@ -29,6 +29,9 @@static bool Requested = false;static bool PresentRequested = false;+// The first refused present of the session, handed out once so a frozen picture leaves one line.+static HRESULT PresentFailure = S_OK;+static bool PresentFailureReported = false;static bool VSyncRequested = false;static bool Active = false;static bool NormalMapsEnabled = true;@@ -394,6 +397,11 @@ bool Direct3D11_Present_Is_Enabled()return PresentRequested && Active;}+bool Direct3D11_Can_Tear()+{+ return Active && Device.Can_Tear();+}+bool Direct3D11_Post_Chain(const char * chain){const bool understood = DX11Post_Parse_Chain(chain, PostChain, PostChainLength);@@ -520,8 +528,20 @@ void Direct3D11_End_Scene(bool flip_frames){if (Active && flip_frames && PresentRequested) {Direct3D11_Finish_Frame();- Device.Present(VSyncRequested ? 1 : 0);+ if (!Device.Present(VSyncRequested ? 1 : 0) && PresentFailure == S_OK) {+ PresentFailure = Device.Last_Present_Result();+ }+ }+}++bool Direct3D11_Take_Present_Failure(long & result)+{+ if (PresentFailure == S_OK || PresentFailureReported) {+ return false;}+ PresentFailureReported = true;+ result = PresentFailure;+ return true;}void Direct3D11_Mirror_Stream_Source(DX11BufferTwinClass * twin, unsigned stride, unsigned offset)diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.hindex 225029c55..87270b7ab 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h@@ -149,6 +149,11 @@ void Direct3D11_Dump_Programs_To(const char * directory);void Direct3D11_Present_Enable(bool enabled);bool Direct3D11_Present_Is_Enabled();+// The swap chain is the flip model with tearing, so vsync off runs past the monitor's refresh.+bool Direct3D11_Can_Tear();+// True once, the first time a present was refused, with the HRESULT it was refused with. WW3D2+// has no logging in a shipping build, so the display asks and writes the line.+bool Direct3D11_Take_Present_Failure(long & result);// Wait for the monitor on the Direct3D 11 present. DXGI takes the interval per Present, so this// does not need a device reset the way Direct3D 9's presentation interval does.