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(dx11): multisampling with alpha-to-coverage on direct3d 11

Olcay Seygan131599f1b13a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bc6c6b45c..63235a361 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -816,6 +816,7 @@ found and fixed, EA's own, not port damage.**
- The game draws its picture through Direct3D 11 now, and falls back to the old renderer on a machine that cannot make a Direct3D 11 device. Eight views over five maps come out within one step of one colour channel of the old picture, which is the smallest difference a screen can show.
- The Direct3D 11 picture comes with its finishing passes on, no switch needed. Explosions glow past their own edges, because the battlefield is kept brighter than white until the glow is worked out; jagged edges are smoothed; and a light sharpening brings the 2003 textures back up after the smoothing. All three run over the battlefield only, before the health bars and the command bar go on top, so the lettering is untouched. In a screen of thirty inferno cannons firing the frame averaged 11.89ms with them against 11.82ms without. The antialiasing setting on the display page is for the old renderer; `-dx11post off` on the command line gives you the plain picture, and `-dx11post fxaa` picks effects one by one. The old renderer's rolling-wave sea never went missing in a real match either: both of the game's settings files turn it off, so no map ever drew it.
+- Multisampling (2x to 8x) now works on the default Direct3D 11 renderer: real edge smoothing in place of FXAA on units, buildings and wires, and fences and foliage are smoothed by alpha-to-coverage instead of stair-stepping, without thinning the trees. The High preset gives 4x, Ultra 8x; 4x costs about 0.4 ms a frame at 1080p.
- Glow on the Graphics page lights the fight now. It used to change next to nothing you could see, because the game's paint stops at white and the glow only picked up what was brighter than that. Fire, explosions, muzzle flashes and laser beams now burn past white where they land, and their light spills onto the ground and the tanks around them. Off, Low, Medium, High and Ultra set how hot and how far, and a new install starts on Medium. In one frame of a tank fight the share of the battle burning white went from 5% with the glow off to 19% on Ultra. Buildings, sky, snow and pale sand never glow at any step: a snowed-in American base with nothing firing comes out exactly as bright on Ultra as on Off. Ultra cost nothing we could measure, 4.5 to 4.8ms a frame against 4.8ms off in a screen of thirty Inferno Cannons. The old Direct3D 9 renderer gets a softer version, where only the white-hot middle of a fire or a beam blooms. Water and the markers drawn on the ground keep the colour they were painted, and a Microwave Tank's heat haze no longer puts every fire on screen out while it fires. Classic Graphics keeps 2003's look, so there only the laser halos follow the setting. The second glow box, the brightness the glow started at, is gone, and a level you saved before keeps its name.
- Fullscreen gets the Direct3D 11 picture too. The old renderer took the whole display for itself and refused the new one its window, so every fullscreen game quietly ran on Direct3D 9, and the DX9 in the corner readout was the only sign. Fullscreen is now the game's window over the monitor: alt-tab drops you on the desktop at its own brightness, and coming back puts the game's on again. A 1280x720 match on a 1920x1080 screen drew 40.7 million times without one draw refused, before and after an alt-tab.
- Moving textures move in the Direct3D 11 picture. Fountain water and tank treads stood still in it, and the fountains came out a dull grey-cyan where the old renderer drew them bright. They match the old renderer now.
diff --git a/GeneralsMD/Code/CMakeLists.txt b/GeneralsMD/Code/CMakeLists.txt
index eea88b8c8..ff7c1773f 100644
--- a/GeneralsMD/Code/CMakeLists.txt
+++ b/GeneralsMD/Code/CMakeLists.txt
@@ -2305,7 +2305,7 @@ 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_dx11backend dx11backend dx11post)
# The hazard clouds' text, which the backend compiles for DX11HazardCloud.cpp.
target_sources(test_dx11backend PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudShader.cpp)
diff --git a/GeneralsMD/Code/Data/Cinema/msaa_river.txt b/GeneralsMD/Code/Data/Cinema/msaa_river.txt
new file mode 100644
index 000000000..70aae81df
--- /dev/null
+++ b/GeneralsMD/Code/Data/Cinema/msaa_river.txt
@@ -0,0 +1,16 @@
+# Direct3D 11 multisampling proofs on Winding River over Scenarios/msaa_river.txt. Run with
+# -video 1080 1740 so this clock is the logic frame over 60 from 18 s on, and every take of
+# -msaa 0, 4 and 8 frames the same pictures. Heading 30 looks north-north-west into the map, so
+# no map edge; positive pitch is the low camera. View A holds from 3 s to 18 s, paced, for the
+# DX11 GPU frame lines.
+
+0 hud off
+3 cut 2650 700 0.5 30 10
+18 cut 2650 700 0.5 30 10
+20 shot # A: base in front, the yard's fence ring, train cars and palms beyond
+20.3 cut 2560 820 0.25 30 16
+22.5 shot # B: close on the yard's north fence with palms and train cars behind it
+22.8 cut 2700 560 0.3 30 14
+25 shot # C: the supply center, Patriot and the armour driving past
+25.3 cut 2600 760 0.8 30 0
+27.5 shot # D: the same ground at about play distance and the game's own tilt
diff --git a/GeneralsMD/Code/Data/Scenarios/msaa_river.txt b/GeneralsMD/Code/Data/Scenarios/msaa_river.txt
new file mode 100644
index 000000000..f217197ea
--- /dev/null
+++ b/GeneralsMD/Code/Data/Scenarios/msaa_river.txt
@@ -0,0 +1,39 @@
+# Direct3D 11 multisampling proofs on Winding River (Cinema/msaa_river.txt): the fenced rail yard
+# round 2460-2720, 650-900 (chain-link ring, Quonset hut, train cars, guard tower, palms inside and
+# round it), an American forward base between the two supply docks south of it, armour and Humvees
+# driving past it in three waves, Rangers walking into the yard and a Comanche going back and forth
+# over it. Nobody fights, so no smoke or fire differs between takes. Frames here count 30 a second.
+#
+# generals.exe -win -borderless -xres 1920 -yres 1080 -quickstart -noshellmap -multiInstance
+# -fps 120 -noFPSLimit -nosmoothmotion -particlecap 2500
+# -map "Maps\Winding River\Winding River.map" -autoskirmish 2 -takeover -observer
+# -side 0 FactionAmerica -side 1 FactionChina -seed 1 -scenario msaa_river -cinema msaa_river
+# -video 1080 1740 msaa -maxframes 1800 -msaa 0|4|8
+
+# the forward base between the docks
+30 spawn 0 AmericaSupplyCenter 1 2700 540
+30 spawn 0 AmericaPowerPlant 1 2560 560
+30 spawn 0 AmericaBarracks 1 2820 520
+30 spawn 0 AmericaPatriotBattery 1 2960 760
+
+# three waves of armour past the yard, south-west to north-east
+30 spawn 0 AmericaTankCrusader 4 2250 520 40
+30 spawn 0 AmericaVehicleHumvee 2 2180 470 40
+60 move 0 AmericaTankCrusader 3000 900
+60 move 0 AmericaVehicleHumvee 3000 900
+210 spawn 0 AmericaTankPaladin 3 2250 520 40
+240 move 0 AmericaTankPaladin 3000 900
+390 spawn 0 AmericaTankCrusader 3 2250 520 40
+420 move 0 AmericaTankCrusader 3000 900
+
+# Rangers walking from the base into the yard
+30 spawn 0 AmericaInfantryRanger 6 2780 600 20
+60 move 0 AmericaInfantryRanger 2560 800
+
+# a Comanche going back and forth over the yard
+30 spawn 0 AmericaVehicleComanche 1 2420 880
+60 move 0 AmericaVehicleComanche 2900 620
+240 move 0 AmericaVehicleComanche 2420 880
+420 move 0 AmericaVehicleComanche 2900 620
+600 move 0 AmericaVehicleComanche 2420 880
+780 move 0 AmericaVehicleComanche 2900 620
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/OptionsCatalog.cpp b/GeneralsMD/Code/GameEngine/Source/Common/OptionsCatalog.cpp
index 3f394ec41..32bca53a8 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/OptionsCatalog.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/OptionsCatalog.cpp
@@ -444,8 +444,8 @@ const OptionDef TheOptionCatalog[] =
// Multisampling, as an index into 0/2/4/8/16 rather than a sample count - the device offers
// those and nothing between them, so a slider would spend most of its travel on values that
- // silently round down. W3DDisplay::init hands it to the device once, and only to a Direct3D 9
- // frame: the default Direct3D 11 picture asks for no samples and smooths its edges with FXAA.
+ // silently round down. W3DDisplay::init hands it to whichever device presents, once. The
+ // Direct3D 11 scene takes it on its post-process target and drops its FXAA while it has samples.
{ "MSAA", OPT_WND( "ComboBoxMSAA" ), "GUI:MSAA",
OPTION_ENUM, APPLY_RESTART, 0, OPTION_MSAA_LEVEL_COUNT - 1,
get_m_msaaLevel, set_m_msaaLevel },
@@ -649,8 +649,8 @@ const Int TheOptionCatalogCount = (sizeof( TheOptionCatalog ) / sizeof( TheOptio
// The free rows all come on by step 3, except those that draw into the sun's shadow map: they come
// on with cast shadows at step 5, since the map is not drawn without them. Never Lower Detail is
// free on a card that holds its frame rate and is what saves one that does not, so it waits for
-// Ultra. Multisampling is read by Direct3D 9 alone and cost nothing measurable there at 8x on this
-// card, which another card may not repeat, so it rises through the middle. Under Direct3D 9
+// Ultra. Multisampling cost nothing measurable under Direct3D 9 at 8x on this card; its Direct3D
+// 11 price was never swept, so the row still rises through the middle. Under Direct3D 9
// MapLight, TeamGlow and WaterFoam are greyed and the slider leaves them; the shadow map and the
// volumetric clouds are the other renderers' alone.
//
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/DX11GpuParticles.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/DX11GpuParticles.cpp
index 733877877..e07d815d9 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/DX11GpuParticles.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/DX11GpuParticles.cpp
@@ -875,7 +875,7 @@ void Draw(unsigned shaderType, const Camera &camera)
// A mirror draws into a target and depth of its own: the particles go there as they are, with no
// fade, since the depth copy is the scene's and not the mirror's.
ID3D11RenderTargetView *target = backend->Scene_Target();
- ID3D11DepthStencilView *targetDepth = device->Get_Depth_Stencil_View();
+ ID3D11DepthStencilView *targetDepth = backend->Scene_Depth_Target();
ID3D11RenderTargetView *heldTarget = nullptr;
ID3D11DepthStencilView *heldDepth = nullptr;
ID3D11ShaderResourceView *depth = nullptr;
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/DX11HazardCloud.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/DX11HazardCloud.cpp
index 4f993fe2a..b15f7bc67 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/DX11HazardCloud.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/DX11HazardCloud.cpp
@@ -225,6 +225,8 @@ bool makeHeatCopy(ID3D11Device *device, ID3D11RenderTargetView *scene, ID3D11Res
description.MiscFlags = 0;
description.Usage = D3D11_USAGE_DEFAULT;
description.CPUAccessFlags = 0;
+ description.SampleDesc.Count = 1; // a multisampled scene is resolved into it
+ description.SampleDesc.Quality = 0;
D3D11_RENDER_TARGET_VIEW_DESC written;
scene->GetDesc(&written);
D3D11_SHADER_RESOURCE_VIEW_DESC view = {};
@@ -394,6 +396,8 @@ bool DX11Layer::render(const Camera &camera)
// carries the scene's depth, so the clouds go into it.
ID3D11RenderTargetView *scene = backend->Scene_Target();
if (!scene) return false;
+ ID3D11DepthStencilView *sceneDepth = backend->Scene_Depth_Target();
+ backend->Resolve_Scene_Depth();
ID3D11DeviceContext *context = device->Get_Context();
ID3D11ShaderResourceView *depth = device->Get_Depth_Texture();
if (!depth) return refuse("the scene has no readable depth");
@@ -532,7 +536,7 @@ bool DX11Layer::render(const Camera &camera)
context->RSSetScissorRects(1, &heatRect);
ID3D11Resource *source = nullptr;
scene->GetResource(&source);
- context->CopyResource(shared.heat, source);
+ DX11Resource_Copy_Readable(context, shared.heat, source);
source->Release();
ID3D11ShaderResourceView *const heatViews[Slots] = {
depth, flowTexture.view, shared.low.view, caches[0].lighting.view, caches[1].lighting.view,
@@ -544,7 +548,6 @@ bool DX11Layer::render(const Camera &camera)
}
unbindViews(context);
- ID3D11DepthStencilView *sceneDepth = device->Get_Depth_Stencil_View();
context->OMSetRenderTargets(1, &scene, sceneDepth);
context->RSSetViewports(viewportCount, &savedViewport);
backend->Forget_Bindings();
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp
index 70decebce..49d8d2fcc 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp
@@ -854,9 +854,7 @@ static void sizeWindowToClient( Int mode, Int width, Int height )
//=============================================================================
// GlobalData carries the whole chain by default and -dx11post replaces it, "off" included. FXAA is
-// always in the default: the Direct3D 11 swap chain takes one sample, and a multisampled scene
-// target would break the screen filters, which redirect the scene into a texture of the same size
-// and share the back buffer's depth with it.
+// always in the default, and the chain leaves it out by itself while the scene is multisampled.
static void pushDirect3D11PostChain( void )
{
// Classic graphics is the game's own picture, which is what -d3d9 draws: hard edged sprites.
@@ -1150,10 +1148,11 @@ void W3DDisplay::init( void )
// Multisampling has to be known before the device exists, and WW3D2 cannot read GlobalData, so
// the sample count is handed to it here. msaaSamplesForLevel turns the stored index into 0, 2,
// 4, 8 or 16; the device degrades an unsupported one on its own. While Direct3D 11 presents,
- // the Direct3D 9 frame is never shown, so its samples would be memory spent on nothing; the
- // Direct3D 11 frame is smoothed by the FXAA in its default chain instead.
+ // the Direct3D 9 frame is never shown, so its samples would be memory spent on nothing: the
+ // count goes to the Direct3D 11 scene instead, which drops its FXAA while it has samples.
DX8Wrapper::Set_Requested_MultiSample_Level( TheGlobalData->m_direct3D11
? 0 : msaaSamplesForLevel( TheGlobalData->m_msaaLevel ) );
+ Direct3D11_Set_Sample_Count( msaaSamplesForLevel( TheGlobalData->m_msaaLevel ) );
DX8Wrapper::Set_Requested_VSync( TheGlobalData->m_vsync != FALSE );
Direct3D11_Set_VSync( TheGlobalData->m_vsync != FALSE );
DX8Wrapper::Set_Requested_Monitor( chosenMonitor().device );
@@ -1248,8 +1247,9 @@ void W3DDisplay::init( void )
}
#endif
// multisampling is opt-in with "-msaa" / "-msaa N" and silently degrades to whatever the
- // device supports, so log what was actually granted
- DEBUG_LOG(("W3DDisplay::init - multisampling: %ux\n", DX8Wrapper::Get_MultiSample_Level()));
+ // device supports, so log what was actually granted, by whichever device presents
+ DEBUG_LOG(("W3DDisplay::init - multisampling: %ux\n", Direct3D11_Present_Is_Enabled()
+ ? Direct3D11_Sample_Count() : DX8Wrapper::Get_MultiSample_Level()));
#if defined(_WIN32)
DEBUG_LOG(("W3DDisplay::init - vsync: %s\n", DX8Wrapper::Get_Requested_VSync() ? "on" : "off"));
#else
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp
index 4f0c491a2..2114ea9c1 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp
@@ -360,6 +360,12 @@ DX11BackendClass::DX11BackendClass()
SceneDepthStale = true;
SceneDepthRefused = false;
FrameDepthCopies = 0;
+ DepthResolveVertexShader = NULL;
+ DepthResolvePixelShader = NULL;
+ DepthResolveState = NULL;
+ DepthResolveRasterizer = NULL;
+ DepthResolveStale = true;
+ DepthResolveRefused = false;
DrawEffect = DRAW_EFFECT_NONE;
memset(DrawEffectNumbers, 0, sizeof(DrawEffectNumbers));
SceneColourCopy = NULL;
@@ -603,6 +609,7 @@ void DX11BackendClass::Shutdown()
Release_Smoke_Map();
Release_Shadow_Casters();
Release_Scene_Depth();
+ Release_Depth_Resolve();
Release_Scene_Colour();
RenderStates.Set_Shadow_Caster_Pass(false);
Note_Shadow_State_Changed();
@@ -1698,6 +1705,11 @@ ID3D11RenderTargetView * DX11BackendClass::Scene_Target() const
return CurrentDepth == Device->Get_Depth_Stencil_View() ? CurrentTarget : NULL;
}
+ID3D11DepthStencilView * DX11BackendClass::Scene_Depth_Target() const
+{
+ return (CurrentTarget != NULL) ? CurrentDepth : Device->Get_Scene_Depth_View();
+}
+
/** The black and white view, the motion blur and the cross fade draw the whole scene into a target
of their own, and Draw_Effect refuses every look there; asked first, the scene keeps the heat
vision and the disabled tint for those frames instead of drawing the object plain. */
@@ -1764,10 +1776,10 @@ void DX11BackendClass::Release_Scene_Colour()
}
/** The texture the cloak's copy of the scene goes into, made at the scene target's own size and
- format and made again when a resize changes either. A multisampled target cannot be copied
- into a texture that is read by pixel, so that refuses the cloak. Asked by the scene for each
- cloaked object before it decides on the look (Takes_Draw_Effect), so a refusal is known
- before the first such object goes without its heat vision. */
+ format and made again when a resize changes either. One sample: a multisampled scene is
+ resolved into it. Asked by the scene for each cloaked object before it decides on the look
+ (Takes_Draw_Effect), so a refusal is known before the first such object goes without its heat
+ vision. */
bool DX11BackendClass::Make_Scene_Colour()
{
if (SceneColourRefused) {
@@ -1790,6 +1802,8 @@ bool DX11BackendClass::Make_Scene_Colour()
description.MiscFlags = 0;
description.Usage = D3D11_USAGE_DEFAULT;
description.CPUAccessFlags = 0;
+ description.SampleDesc.Count = 1;
+ description.SampleDesc.Quality = 0;
// Read the copy the way the scene is written, which also covers a typeless surface.
D3D11_RENDER_TARGET_VIEW_DESC written;
Device->Get_Scene_View()->GetDesc(&written);
@@ -1798,8 +1812,7 @@ bool DX11BackendClass::Make_Scene_Colour()
view.Format = written.Format;
view.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
view.Texture2D.MipLevels = 1;
- if (description.SampleDesc.Count > 1
- || FAILED(Device->Get_Device()->CreateTexture2D(&description, NULL, &SceneColourCopy))
+ if (FAILED(Device->Get_Device()->CreateTexture2D(&description, NULL, &SceneColourCopy))
|| FAILED(Device->Get_Device()->CreateShaderResourceView(SceneColourCopy, &view,
&SceneColourCopyView))) {
Note_Refusal("the device refused a copy of the scene's colour for the cloak");
@@ -1824,7 +1837,7 @@ bool DX11BackendClass::Take_Scene_Colour()
}
ID3D11Resource * source = NULL;
Device->Get_Scene_View()->GetResource(&source);
- Device->Get_Context()->CopyResource(SceneColourCopy, source);
+ DX11Resource_Copy_Readable(Device->Get_Context(), SceneColourCopy, source);
SceneColourStale = false;
++FrameDepthCopies; // counted with the depth copies, so DX11 FRAME COST sees it
source->Release();
@@ -1899,6 +1912,7 @@ void DX11BackendClass::Take_Scene_Depth()
if (SceneDepthRefused || !SoftParticlesAllowed || Device == NULL) {
return;
}
+ Resolve_Scene_Depth();
ID3D11ShaderResourceView * const source_view = Device->Get_Depth_Texture();
if (source_view == NULL) {
return;
@@ -1954,6 +1968,127 @@ unsigned DX11BackendClass::Take_Frame_Depth_Copies()
return copies;
}
+// A triangle over the whole target out of the vertex number, and each pixel's first sample written
+// as its depth. The test is ALWAYS, so the triangle's own depth never decides anything.
+static const char DEPTH_RESOLVE_VERTEX_PROGRAM[] =
+ "float4 main(uint vertex : SV_VertexID) : SV_Position\n"
+ "{\n"
+ " float2 corner = float2((vertex << 1) & 2, vertex & 2);\n"
+ " return float4(corner * float2(2.0, -2.0) + float2(-1.0, 1.0), 0.0, 1.0);\n"
+ "}\n";
+
+static const char DEPTH_RESOLVE_PIXEL_PROGRAM[] =
+ "Texture2DMS<float> SceneDepth : register(t0);\n"
+ "float main(float4 position : SV_Position) : SV_Depth\n"
+ "{\n"
+ " return SceneDepth.Load(int2(position.xy), 0);\n"
+ "}\n";
+
+bool DX11BackendClass::Make_Depth_Resolve()
+{
+ if (DepthResolvePixelShader != NULL) {
+ return true;
+ }
+ if (DepthResolveRefused) {
+ return false;
+ }
+ ID3D11Device * device = Device->Get_Device();
+
+ D3D11_DEPTH_STENCIL_DESC depth;
+ memset(&depth, 0, sizeof(depth));
+ depth.DepthEnable = TRUE;
+ depth.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
+ depth.DepthFunc = D3D11_COMPARISON_ALWAYS;
+
+ D3D11_RASTERIZER_DESC rasterizer;
+ memset(&rasterizer, 0, sizeof(rasterizer));
+ rasterizer.FillMode = D3D11_FILL_SOLID;
+ rasterizer.CullMode = D3D11_CULL_NONE;
+ rasterizer.DepthClipEnable = TRUE;
+
+ // Shader model 5: 4.0 wants the sample count in the texture's type.
+ std::vector<unsigned char> vertex_code;
+ std::vector<unsigned char> pixel_code;
+ const bool made = SUCCEEDED(device->CreateDepthStencilState(&depth, &DepthResolveState))
+ && SUCCEEDED(device->CreateRasterizerState(&rasterizer, &DepthResolveRasterizer))
+ && Compile_Program(DEPTH_RESOLVE_VERTEX_PROGRAM, "depthresolve", VERTEX_PROFILE, vertex_code)
+ && Compile_Program(DEPTH_RESOLVE_PIXEL_PROGRAM, "depthresolve", "ps_5_0", pixel_code)
+ && SUCCEEDED(device->CreateVertexShader(&vertex_code[0], vertex_code.size(), NULL,
+ &DepthResolveVertexShader))
+ && SUCCEEDED(device->CreatePixelShader(&pixel_code[0], pixel_code.size(), NULL,
+ &DepthResolvePixelShader));
+ if (!made) {
+ Note_Refusal("the device would not make the pass that resolves the multisampled scene's depth");
+ Release_Depth_Resolve();
+ DepthResolveRefused = true;
+ return false;
+ }
+ return true;
+}
+
+void DX11BackendClass::Release_Depth_Resolve()
+{
+ IUnknown ** const held[] = {
+ (IUnknown **)&DepthResolveVertexShader, (IUnknown **)&DepthResolvePixelShader,
+ (IUnknown **)&DepthResolveState, (IUnknown **)&DepthResolveRasterizer,
+ };
+ for (unsigned index = 0; index < sizeof(held) / sizeof(held[0]); ++index) {
+ if (*held[index] != NULL) {
+ (*held[index])->Release();
+ *held[index] = NULL;
+ }
+ }
+ DepthResolveRefused = false;
+ DepthResolveStale = true;
+}
+
+void DX11BackendClass::Resolve_Scene_Depth()
+{
+ if (!DepthResolveStale || !Draws_Into_Scene() || !Device->Scene_Is_Multisampled()
+ || !Make_Depth_Resolve()) {
+ return;
+ }
+ DepthResolveStale = false;
+
+ ID3D11DeviceContext * context = Device->Get_Context();
+ // The draws' viewport carries Direct3D 9's half pixel (Set_Viewport); this pass wants each
+ // pixel's own sample, so it sets a plain one and puts the draws' back afterwards.
+ D3D11_VIEWPORT saved;
+ UINT saved_count = 1;
+ context->RSGetViewports(&saved_count, &saved);
+ D3D11_VIEWPORT viewport;
+ viewport.TopLeftX = 0.0f;
+ viewport.TopLeftY = 0.0f;
+ viewport.Width = static_cast<float>(Device->Get_Width());
+ viewport.Height = static_cast<float>(Device->Get_Height());
+ viewport.MinDepth = 0.0f;
+ viewport.MaxDepth = 1.0f;
+
+ context->OMSetRenderTargets(0, NULL, Device->Get_Depth_Stencil_View());
+ context->RSSetViewports(1, &viewport);
+ context->RSSetState(DepthResolveRasterizer);
+ context->OMSetDepthStencilState(DepthResolveState, 0);
+ context->OMSetBlendState(NULL, NULL, 0xffffffff);
+ context->IASetInputLayout(NULL);
+ context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
+ context->VSSetShader(DepthResolveVertexShader, NULL, 0);
+ context->PSSetShader(DepthResolvePixelShader, NULL, 0);
+ ID3D11ShaderResourceView * samples = Device->Get_Multisampled_Depth_Texture();
+ context->PSSetShaderResources(0, 1, &samples);
+ context->Draw(3, 0);
+ // Unbound before the same surface goes back on as the scene's depth.
+ samples = NULL;
+ context->PSSetShaderResources(0, 1, &samples);
+
+ ID3D11RenderTargetView * target = Device->Get_Scene_View();
+ context->OMSetRenderTargets(1, &target, Device->Get_Scene_Depth_View());
+ if (saved_count == 1) {
+ context->RSSetViewports(1, &saved);
+ }
+ Forget_Bindings();
+ ++FrameDepthCopies;
+}
+
void DX11BackendClass::Set_Blast_Lights(const float * lights, unsigned count)
{
if (count > BLAST_LIGHT_SLOTS) {
@@ -2750,7 +2885,7 @@ void DX11BackendClass::Begin_Scene()
return;
}
- Device->Get_Context()->OMSetRenderTargets(1, &target, Device->Get_Depth_Stencil_View());
+ Device->Get_Context()->OMSetRenderTargets(1, &target, Device->Get_Scene_Depth_View());
Forget_Bindings();
Set_Viewport(0, 0, Device->Get_Width(), Device->Get_Height());
}
@@ -2828,7 +2963,7 @@ void DX11BackendClass::Set_Render_Target(ID3D11RenderTargetView * target)
ID3D11RenderTargetView * back_buffer = Device->Get_Scene_View();
if (back_buffer != NULL) {
Device->Get_Context()->OMSetRenderTargets(1, &back_buffer,
- Device->Get_Depth_Stencil_View());
+ Device->Get_Scene_Depth_View());
Forget_Bindings();
Set_Viewport(0, 0, Device->Get_Width(), Device->Get_Height());
}
@@ -2902,8 +3037,7 @@ void DX11BackendClass::Clear(bool colour, bool depth, const float colour_value[4
// target and then draws into it would otherwise clear the picture instead.
ID3D11RenderTargetView * target = (CurrentTarget != NULL)
? CurrentTarget : Device->Get_Scene_View();
- ID3D11DepthStencilView * depth_view = (CurrentTarget != NULL)
- ? CurrentDepth : Device->Get_Depth_Stencil_View();
+ ID3D11DepthStencilView * depth_view = Scene_Depth_Target();
if (colour && target != NULL) {
Device->Get_Context()->ClearRenderTargetView(target, colour_value);
@@ -2917,7 +3051,14 @@ void DX11BackendClass::Clear(bool colour, bool depth, const float colour_value[4
if (depth && depth_view != NULL) {
Device->Get_Context()->ClearDepthStencilView(depth_view,
D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
+ if (depth_view != Device->Get_Depth_Stencil_View() && CurrentTarget == NULL) {
+ // The single-sample depth too: a screen filter binds it for its own texture after this
+ // clear (Depth_For), and it still holds the last frame's resolve and stencil.
+ Device->Get_Context()->ClearDepthStencilView(Device->Get_Depth_Stencil_View(),
+ D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
+ }
SceneDepthStale = true;
+ DepthResolveStale = DepthResolveStale || CurrentTarget == NULL;
}
}
@@ -2931,6 +3072,7 @@ bool DX11BackendClass::Build_Combiner_Description(CombinerDescription & descript
RenderStates.Get_Render_State(D3DRS_ALPHATESTENABLE) != FALSE;
description.PixelPipeline.AlphaFunction = RenderStates.Get_Render_State(D3DRS_ALPHAFUNC);
description.PixelPipeline.FogEnabled = RenderStates.Get_Render_State(D3DRS_FOGENABLE) != FALSE;
+ description.PixelPipeline.AlphaToCoverage = Alpha_To_Coverage();
description.SpecularAdd = RenderStates.Get_Render_State(D3DRS_SPECULARENABLE) != FALSE;
description.StageCount = 0;
@@ -3053,8 +3195,10 @@ bool DX11BackendClass::Build_Vertex_Description(VertexPipelineDescription & desc
bool DX11BackendClass::Resolve(Pipeline & pipeline)
{
- // Nothing either description is built from has been set since the last draw resolved.
- if (!PipelineChanged && LastResolveHeld) {
+ // Nothing either description is built from has been set since the last draw resolved. Alpha to
+ // coverage is read off the target as well as the states, and a target change sets nothing.
+ if (!PipelineChanged && LastResolveHeld
+ && Memos[LastMemo].Combiner.PixelPipeline.AlphaToCoverage == Alpha_To_Coverage()) {
ResolveMemo & memo = Memos[LastMemo];
pipeline = memo.Resolved;
++memo.Use->Draws;
@@ -3560,6 +3704,7 @@ void DX11BackendClass::Forget_Last_State_Objects()
memset(LastSamplerDescriptions, 0, sizeof(LastSamplerDescriptions));
LastBlendState = NULL;
LastBlendGlow = false;
+ LastBlendCoverage = false;
LastDepthStencilState = NULL;
LastRasterizerState = NULL;
memset(LastSamplerStates, 0, sizeof(LastSamplerStates));
@@ -3567,10 +3712,20 @@ void DX11BackendClass::Forget_Last_State_Objects()
Forget_Bindings();
}
-ID3D11BlendState * DX11BackendClass::Blend_State(bool glow)
+bool DX11BackendClass::Alpha_To_Coverage() const
+{
+ const unsigned function = RenderStates.Get_Render_State(D3DRS_ALPHAFUNC);
+ return Device->Scene_Is_Multisampled() && Draws_Into_Scene() && SoftParticlesAllowed
+ && RenderStates.Get_Render_State(D3DRS_ALPHATESTENABLE) != FALSE
+ && RenderStates.Get_Render_State(D3DRS_ALPHABLENDENABLE) == FALSE
+ && (function == D3DCMP_GREATER || function == D3DCMP_GREATEREQUAL);
+}
+
+ID3D11BlendState * DX11BackendClass::Blend_State(bool glow, bool coverage)
{
D3D11_BLEND_DESC description;
RenderStates.Build_Blend_Description(description);
+ description.AlphaToCoverageEnable = coverage ? TRUE : FALSE;
if (glow) {
// The source term becomes the blend factor, which Bind_State_Objects passes as the gain.
// A float target takes a factor past one unclamped; that is the whole of the boost.
@@ -3720,10 +3875,12 @@ void DX11BackendClass::Bind_State_Objects()
// Whether the glow applies hangs on the target and the vertex format as well as the render
// states, and neither of those raises StateObjectsChanged, so it is asked every draw.
const bool glow = Additive_Glow();
- if (StateObjectsChanged || glow != LastBlendGlow || blend == NULL || depth_stencil == NULL
- || rasterizer == NULL) {
- blend = Blend_State(glow);
+ const bool coverage = Alpha_To_Coverage();
+ if (StateObjectsChanged || glow != LastBlendGlow || coverage != LastBlendCoverage || blend == NULL
+ || depth_stencil == NULL || rasterizer == NULL) {
+ blend = Blend_State(glow, coverage);
LastBlendGlow = glow;
+ LastBlendCoverage = coverage;
depth_stencil = Depth_Stencil_State();
rasterizer = Rasterizer_State();
StateObjectsChanged = blend == NULL || depth_stencil == NULL || rasterizer == NULL;
@@ -3933,6 +4090,9 @@ ID3D11ShaderResourceView * DX11BackendClass::Readable_Texture(unsigned stage,
if (TargetCopy == NULL) {
description.BindFlags = D3D11_BIND_SHADER_RESOURCE;
description.MiscFlags = 0;
+ // The multisampled scene is resolved into it.
+ description.SampleDesc.Count = 1;
+ description.SampleDesc.Quality = 0;
if (FAILED(Device->Get_Device()->CreateTexture2D(&description, NULL, &TargetCopy))) {
Note_Refusal("the device refused a copy of the render target a draw samples");
TargetCopy = NULL;
@@ -3946,7 +4106,7 @@ ID3D11ShaderResourceView * DX11BackendClass::Readable_Texture(unsigned stage,
}
}
- Device->Get_Context()->CopyResource(TargetCopy, resource);
+ DX11Resource_Copy_Readable(Device->Get_Context(), TargetCopy, resource);
return TargetCopyView;
}
@@ -4014,6 +4174,7 @@ bool DX11BackendClass::Draw_Indexed(unsigned index_count, unsigned start_index,
if (RenderStates.Get_Render_State(D3DRS_ZWRITEENABLE) != FALSE
&& (CurrentTarget == NULL || CurrentDepth == Device->Get_Depth_Stencil_View())) {
SceneDepthStale = true;
+ DepthResolveStale = DepthResolveStale || CurrentTarget == NULL;
}
if (CurrentTarget != NULL) {
++DrawsIntoTargets;
@@ -4071,6 +4232,7 @@ bool DX11BackendClass::Draw_Triangles(unsigned vertex_count, unsigned start_vert
if (RenderStates.Get_Render_State(D3DRS_ZWRITEENABLE) != FALSE
&& (CurrentTarget == NULL || CurrentDepth == Device->Get_Depth_Stencil_View())) {
SceneDepthStale = true;
+ DepthResolveStale = DepthResolveStale || CurrentTarget == NULL;
}
if (CurrentTarget != NULL) {
++DrawsIntoTargets;
@@ -4239,6 +4401,7 @@ bool DX11BackendClass::Draw_User_Strip(const void * vertices, unsigned primitive
if (RenderStates.Get_Render_State(D3DRS_ZWRITEENABLE) != FALSE
&& (CurrentTarget == NULL || CurrentDepth == Device->Get_Depth_Stencil_View())) {
SceneDepthStale = true;
+ DepthResolveStale = DepthResolveStale || CurrentTarget == NULL;
}
if (CurrentTarget != NULL) {
++DrawsIntoTargets;
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h
index 226eb920e..1cf64182b 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h
@@ -345,6 +345,19 @@ public:
// Where the scene is going now: its own target, or a screen filter's texture drawn over the
// scene's depth; NULL for a mirror or the sun's map.
ID3D11RenderTargetView * Scene_Target() const;
+ // The depth that goes with Scene_Target: the scene's own, multisampled with the scene, or the
+ // single-sample one a screen filter's texture is drawn over.
+ ID3D11DepthStencilView * Scene_Depth_Target() const;
+
+ // With a multisampled scene, its depth resolved into the device's single-sample depth buffer,
+ // which is what Get_Depth_Texture reads and what every pass reading the scene's depth samples:
+ // a full screen pass taking sample 0 of each pixel, since a depth buffer cannot be resolved the
+ // way a colour target is. Only while the draws go into the scene, and only when a clear or a
+ // draw wrote its depth since the last one; anything that reads the depth calls it first.
+ void Resolve_Scene_Depth();
+ // Makes that pass now; false when the device refuses it, and a multisampled scene without it
+ // would leave every reader of the depth an unwritten buffer (Direct3D11_Create drops to one sample).
+ bool Make_Depth_Resolve();
// The scene's target, its depth and the draws' viewport bound again after a pass that bound
// its own on the context mid-scene (the post chain's occlusion).
@@ -604,7 +617,7 @@ private:
void Bind_State_Objects();
void Release_Cached();
- ID3D11BlendState * Blend_State(bool glow);
+ ID3D11BlendState * Blend_State(bool glow, bool coverage);
ID3D11DepthStencilState * Depth_Stencil_State();
ID3D11RasterizerState * Rasterizer_State();
ID3D11SamplerState * Sampler_State(unsigned sampler);
@@ -721,6 +734,11 @@ private:
float AdditiveGain;
bool GlowDraw;
bool Additive_Glow() const;
+ // An alpha tested draw without blending into the multisampled scene covers the samples its
+ // alpha says, which smooths a leaf's or a fence's cut edge the way the samples smooth a
+ // triangle's. Never into a single-sample target, where it would only dither, never for a test
+ // that keeps the low alphas, and never under Classic, whose fences are -d3d9's hard ones.
+ bool Alpha_To_Coverage() const;
ID3D11ShaderResourceView * SceneStandIn;
// A stage samples the target the draw is going into: the heat haze, which bends a picture that
// already took its shadows, and would take them a second time.
@@ -780,6 +798,15 @@ private:
bool SceneDepthRefused; ///< the device would not make the copy; no draw fades again
unsigned FrameDepthCopies;
void Release_Scene_Depth();
+ // Resolve_Scene_Depth's pass (Make_Depth_Resolve); refused for good if the device cannot.
+ // Stale while a clear or a draw into the scene wrote the multisampled depth since the last one.
+ ID3D11VertexShader * DepthResolveVertexShader;
+ ID3D11PixelShader * DepthResolvePixelShader;
+ ID3D11DepthStencilState * DepthResolveState;
+ ID3D11RasterizerState * DepthResolveRasterizer;
+ bool DepthResolveStale;
+ bool DepthResolveRefused;
+ void Release_Depth_Resolve();
bool Make_Smoke_Map();
void Release_Smoke_Map();
@@ -1036,6 +1063,7 @@ private:
D3D11_BLEND_DESC LastBlendDescription;
ID3D11BlendState * LastBlendState;
bool LastBlendGlow;
+ bool LastBlendCoverage;
D3D11_DEPTH_STENCIL_DESC LastDepthStencilDescription;
ID3D11DepthStencilState * LastDepthStencilState;
D3D11_RASTERIZER_DESC LastRasterizerDescription;
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11device.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11device.cpp
index f1aee488c..0d2791767 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11device.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11device.cpp
@@ -88,7 +88,12 @@ DX11DeviceClass::DX11DeviceClass()
, DepthStencilView(NULL)
, DepthStencilTexture(NULL)
, DepthTexture(NULL)
+ , SceneDepthSurface(NULL)
+ , SceneDepthView(NULL)
+ , SceneDepthTexture(NULL)
, FeatureLevel(D3D_FEATURE_LEVEL_11_0)
+ , RequestedSamples(1)
+ , SampleCount(1)
, Width(0)
, Height(0)
, Software(false)
@@ -326,6 +331,24 @@ bool DX11DeviceClass::Create_Views()
return false;
}
+ // The scene's own depth at the scene's sample count, beside the single-sample one above, which
+ // with multisampling holds the scene's depth resolved for every pass that reads it. A device
+ // that refuses it draws the scene at one sample.
+ SampleCount = Granted_Sample_Count();
+ if (SampleCount > 1) {
+ depth.SampleDesc.Count = SampleCount;
+ depth_view.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DMS;
+ depth_read.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DMS;
+ if (FAILED(Device->CreateTexture2D(&depth, NULL, &SceneDepthSurface))
+ || FAILED(Device->CreateDepthStencilView(SceneDepthSurface, &depth_view, &SceneDepthView))
+ || FAILED(Device->CreateShaderResourceView(SceneDepthSurface, &depth_read, &SceneDepthTexture))) {
+ release_interface(reinterpret_cast<IUnknown **>(&SceneDepthTexture));
+ release_interface(reinterpret_cast<IUnknown **>(&SceneDepthView));
+ release_interface(reinterpret_cast<IUnknown **>(&SceneDepthSurface));
+ SampleCount = 1;
+ }
+ }
+
Context->OMSetRenderTargets(1, &BackBufferView, DepthStencilView);
D3D11_VIEWPORT viewport;
@@ -350,6 +373,9 @@ void DX11DeviceClass::Release_Views()
// Whoever lent it a scene view sized the texture behind it to the buffers that are about to go,
// so the loan ends here and the next frame asks for a new one.
SceneView = NULL;
+ release_interface(reinterpret_cast<IUnknown **>(&SceneDepthTexture));
+ release_interface(reinterpret_cast<IUnknown **>(&SceneDepthView));
+ release_interface(reinterpret_cast<IUnknown **>(&SceneDepthSurface));
release_interface(reinterpret_cast<IUnknown **>(&DepthTexture));
release_interface(reinterpret_cast<IUnknown **>(&DepthStencilView));
release_interface(reinterpret_cast<IUnknown **>(&DepthStencilTexture));
@@ -371,6 +397,36 @@ void DX11DeviceClass::Release()
Software = false;
Tearing = false;
ChainFlags = 0;
+ SampleCount = 1;
+}
+
+void DX11DeviceClass::Drop_Multisampling()
+{
+ RequestedSamples = 1;
+ SampleCount = 1;
+ release_interface(reinterpret_cast<IUnknown **>(&SceneDepthTexture));
+ release_interface(reinterpret_cast<IUnknown **>(&SceneDepthView));
+ release_interface(reinterpret_cast<IUnknown **>(&SceneDepthSurface));
+}
+
+// The most samples at or under the request that the scene's two colour formats (the post chain's
+// eight bit and half float targets) and its depth all take. Every feature level 11 device takes 4
+// and 8 for those, so 16 is the one that degrades in practice.
+unsigned DX11DeviceClass::Granted_Sample_Count() const
+{
+ const DXGI_FORMAT formats[] = { BACK_BUFFER_FORMAT, DXGI_FORMAT_R16G16B16A16_FLOAT, DEPTH_WRITE_FORMAT };
+ for (unsigned samples = 16; samples > 1; samples /= 2) {
+ bool taken = samples <= RequestedSamples;
+ for (unsigned index = 0; taken && index < sizeof(formats) / sizeof(formats[0]); ++index) {
+ UINT levels = 0;
+ taken = SUCCEEDED(Device->CheckMultisampleQualityLevels(formats[index], samples, &levels))
+ && levels > 0;
+ }
+ if (taken) {
+ return samples;
+ }
+ }
+ return 1;
}
bool DX11DeviceClass::Resize(unsigned width, unsigned height)
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11device.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11device.h
index 9d916f772..693369059 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11device.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11device.h
@@ -57,6 +57,19 @@ public:
void Request_Debug_Layer() { DebugLayerRequested = true; }
bool Has_Debug_Layer() const { return DebugLayerPresent; }
+ // Multisampling for the scene, asked for before Create: 0 or 1 is none, otherwise 2, 4, 8 or 16.
+ // The swap chain keeps one sample, because a flip chain refuses more; the scene is drawn into
+ // the post chain's multisampled target over a multisampled depth buffer, and resolved on its way
+ // to the screen. Create_Views grants the most the device offers at or under the request for the
+ // scene's colour formats and its depth together, so an unsupported count degrades rather than
+ // failing the device.
+ void Request_Sample_Count(unsigned samples) { RequestedSamples = samples; }
+ // What Create_Views granted: one when the scene is not multisampled.
+ unsigned Get_Sample_Count() const { return SampleCount; }
+ // One sample for the rest of the run, resizes included: the backend could not make the pass
+ // that resolves the multisampled depth.
+ void Drop_Multisampling();
+
// A device with a window: swap chain, back buffer, depth buffer, the lot. Width and height
// are the back buffer's, not the window's, so a borderless window and a fullscreen mode ask
// for the same thing.
@@ -78,9 +91,21 @@ public:
ID3D11Device * Get_Device() const { return Device; }
ID3D11DeviceContext * Get_Context() const { return Context; }
ID3D11RenderTargetView * Get_Back_Buffer_View() const { return BackBufferView; }
+ // The single-sample depth buffer: the swap chain's, a same-size render target's, and with
+ // multisampling the scene's depth resolved (DX11BackendClass::Resolve_Scene_Depth).
ID3D11DepthStencilView * Get_Depth_Stencil_View() const { return DepthStencilView; }
// The same surface read as a texture, for the pass that wants the frame's own depth.
ID3D11ShaderResourceView * Get_Depth_Texture() const { return DepthTexture; }
+ // The multisampled depth the scene is tested against while it goes into the post chain's
+ // multisampled target, and the same surface as a texture for the resolve. Null at one sample.
+ ID3D11ShaderResourceView * Get_Multisampled_Depth_Texture() const { return SceneDepthTexture; }
+ // True while the scene view is the multisampled one.
+ bool Scene_Is_Multisampled() const { return SceneView != NULL && SceneDepthView != NULL; }
+ // The depth that goes with Get_Scene_View.
+ ID3D11DepthStencilView * Get_Scene_Depth_View() const
+ {
+ return Scene_Is_Multisampled() ? SceneDepthView : DepthStencilView;
+ }
// Where the scene goes, which is not always the swap chain. The post-process chain hands its
// own texture's view over here at the top of every frame and the backend binds whatever it
@@ -134,6 +159,7 @@ private:
const DXGI_SWAP_CHAIN_DESC * swap_chain);
bool Create_Views();
void Release_Views();
+ unsigned Granted_Sample_Count() const;
ID3D11Device * Device;
ID3D11DeviceContext * Context;
@@ -143,8 +169,13 @@ private:
ID3D11DepthStencilView * DepthStencilView;
ID3D11Texture2D * DepthStencilTexture;
ID3D11ShaderResourceView * DepthTexture;
+ ID3D11Texture2D * SceneDepthSurface;
+ ID3D11DepthStencilView * SceneDepthView;
+ ID3D11ShaderResourceView * SceneDepthTexture;
D3D_FEATURE_LEVEL FeatureLevel;
+ unsigned RequestedSamples;
+ unsigned SampleCount;
unsigned Width;
unsigned Height;
bool Software;
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11post.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11post.cpp
index 4e117c045..2392fe7c6 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11post.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11post.cpp
@@ -19,6 +19,7 @@
#include "dx11post.h"
#include "dx11device.h"
+#include "dx11resource.h"
#include <stdio.h>
#include <string.h>
@@ -443,25 +444,34 @@ static const char * const FXAA_SHADER_BODY =
// Unsharp mask: the pixel plus what it has that a blur of its neighbours does not. The amount is
// low on purpose. This runs over the world and the world alone, but the world holds thin wires and
// aerials as well as ground, and anything stronger rings around them.
-static const char * const SHARPEN_SHADER_BODY =
- "static const float SHARPEN_AMOUNT = 0.35;\n"
- "\n"
- "float4 main(VertexOutput input) : SV_TARGET\n"
- "{\n"
- " float2 texel = TexelSize.xy;\n"
- " float4 centre = Source.Sample(Sampler, input.Texture);\n"
- " float3 left = Source.Sample(Sampler, input.Texture + float2(-texel.x, 0.0)).rgb;\n"
- " float3 right = Source.Sample(Sampler, input.Texture + float2(texel.x, 0.0)).rgb;\n"
- " float3 up = Source.Sample(Sampler, input.Texture + float2(0.0, -texel.y)).rgb;\n"
- " float3 down = Source.Sample(Sampler, input.Texture + float2(0.0, texel.y)).rgb;\n"
- " float3 neighbours = left + right + up + down;\n"
- " float3 sharpened = centre.rgb + (centre.rgb - neighbours * 0.25) * SHARPEN_AMOUNT;\n"
- " // never past the brightest or the darkest of the five: overshooting them drew a white rim\n"
- " // around every dark wreck inside a nuke's white cloud\n"
- " float3 lowest = min(centre.rgb, min(min(left, right), min(up, down)));\n"
- " float3 highest = max(centre.rgb, max(max(left, right), max(up, down)));\n"
- " return float4(clamp(sharpened, lowest, highest), centre.a);\n"
- "}\n";
+//
+// A multisampled scene has no FXAA before this, and FXAA was what softened the ground's texture
+// grain at one sample: sharpened at 0.35 the 4x ground measured half as grainy again as -msaa 0
+// (mean absolute Laplacian 36.3 against 24.1 on one crop, 58.5 against 39.9 on another). There the
+// same pass runs at -0.25, a light pull toward the neighbours, which brought five ground crops to
+// within 10% of -msaa 0.
+#define SHARPEN_SHADER_TEXT(amount) \
+ "static const float SHARPEN_AMOUNT = " amount ";\n" \
+ "\n" \
+ "float4 main(VertexOutput input) : SV_TARGET\n" \
+ "{\n" \
+ " float2 texel = TexelSize.xy;\n" \
+ " float4 centre = Source.Sample(Sampler, input.Texture);\n" \
+ " float3 left = Source.Sample(Sampler, input.Texture + float2(-texel.x, 0.0)).rgb;\n" \
+ " float3 right = Source.Sample(Sampler, input.Texture + float2(texel.x, 0.0)).rgb;\n" \
+ " float3 up = Source.Sample(Sampler, input.Texture + float2(0.0, -texel.y)).rgb;\n" \
+ " float3 down = Source.Sample(Sampler, input.Texture + float2(0.0, texel.y)).rgb;\n" \
+ " float3 neighbours = left + right + up + down;\n" \
+ " float3 sharpened = centre.rgb + (centre.rgb - neighbours * 0.25) * SHARPEN_AMOUNT;\n" \
+ " // never past the brightest or the darkest of the five: overshooting them drew a white rim\n" \
+ " // around every dark wreck inside a nuke's white cloud\n" \
+ " float3 lowest = min(centre.rgb, min(min(left, right), min(up, down)));\n" \
+ " float3 highest = max(centre.rgb, max(max(left, right), max(up, down)));\n" \
+ " return float4(clamp(sharpened, lowest, highest), centre.a);\n" \
+ "}\n"
+static const char * const SHARPEN_SHADER_BODY = SHARPEN_SHADER_TEXT("0.35");
+static const char * const SHARPEN_MULTISAMPLED_SHADER_BODY = SHARPEN_SHADER_TEXT("-0.25");
+#undef SHARPEN_SHADER_TEXT
// Ambient occlusion out of the frame's own depth, and nothing else. Every pixel asks a ring of
// neighbours how much nearer to the eye they are: at the foot of a wall half of them are in front
@@ -1002,6 +1012,7 @@ DX11PostProcessClass::DX11PostProcessClass()
: Device(NULL)
, VertexShader(NULL)
, ToneMapShader(NULL)
+ , SharpenMultisampledShader(NULL)
, BloomExtractShader(NULL)
, NearPlane(1.0f)
, FarPlane(1200.0f)
@@ -1022,6 +1033,7 @@ DX11PostProcessClass::DX11PostProcessClass()
, Height(0)
, BloomWidth(0)
, BloomHeight(0)
+ , TargetSamples(1)
, TargetsAreFloat(false)
, ShadersReady(false)
, Resolved(false)
@@ -1035,6 +1047,7 @@ DX11PostProcessClass::DX11PostProcessClass()
memset(HazeWorldFromClip, 0, sizeof(HazeWorldFromClip));
memset(PixelShaders, 0, sizeof(PixelShaders));
memset(&SceneTarget, 0, sizeof(SceneTarget));
+ memset(&SceneResolve, 0, sizeof(SceneResolve));
memset(&SceneCopy, 0, sizeof(SceneCopy));
memset(ChainTargets, 0, sizeof(ChainTargets));
memset(BloomTargets, 0, sizeof(BloomTargets));
@@ -1090,6 +1103,7 @@ void DX11PostProcessClass::Shutdown()
release_interface(reinterpret_cast<IUnknown **>(&BloomBlurShader));
release_interface(reinterpret_cast<IUnknown **>(&BloomExtractShader));
release_interface(reinterpret_cast<IUnknown **>(&ToneMapShader));
+ release_interface(reinterpret_cast<IUnknown **>(&SharpenMultisampledShader));
for (unsigned index = 0; index < DX11_POST_SIMPLE_EFFECTS; ++index) {
release_interface(reinterpret_cast<IUnknown **>(&PixelShaders[index]));
}
@@ -1165,6 +1179,8 @@ bool DX11PostProcessClass::Create_Shaders()
}
return compile_pixel_shader(compiler, device, TONE_MAP_SHADER_BODY, &ToneMapShader)
+ && compile_pixel_shader(compiler, device, SHARPEN_MULTISAMPLED_SHADER_BODY,
+ &SharpenMultisampledShader)
&& compile_pixel_shader(compiler, device, BLOOM_EXTRACT_SHADER_BODY, &BloomExtractShader)
&& compile_pixel_shader(compiler, device, BLOOM_BLUR_SHADER_BODY, &BloomBlurShader)
&& compile_pixel_shader(compiler, device, BLOOM_COMPOSITE_SHADER_BODY,
@@ -1245,7 +1261,7 @@ bool DX11PostProcessClass::Create_States()
}
bool DX11PostProcessClass::Create_Target(Target & target, unsigned width, unsigned height,
- DXGI_FORMAT format)
+ DXGI_FORMAT format, unsigned samples)
{
ID3D11Device * device = Device->Get_Device();
@@ -1256,9 +1272,10 @@ bool DX11PostProcessClass::Create_Target(Target & target, unsigned width, unsign
description.MipLevels = 1;
description.ArraySize = 1;
description.Format = format;
- description.SampleDesc.Count = 1;
+ description.SampleDesc.Count = samples;
description.Usage = D3D11_USAGE_DEFAULT;
- description.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
+ description.BindFlags = D3D11_BIND_RENDER_TARGET
+ | (samples > 1 ? 0 : D3D11_BIND_SHADER_RESOURCE);
if (FAILED(device->CreateTexture2D(&description, NULL, &target.Texture))) {
return false;
@@ -1266,13 +1283,16 @@ bool DX11PostProcessClass::Create_Target(Target & target, unsigned width, unsign
if (FAILED(device->CreateRenderTargetView(target.Texture, NULL, &target.View))) {
return false;
}
- return SUCCEEDED(device->CreateShaderResourceView(target.Texture, NULL, &target.Resource));
+ return samples > 1
+ || SUCCEEDED(device->CreateShaderResourceView(target.Texture, NULL, &target.Resource));
}
-bool DX11PostProcessClass::Create_Targets(unsigned width, unsigned height, bool floating)
+bool DX11PostProcessClass::Create_Targets(unsigned width, unsigned height, bool floating,
+ unsigned samples)
{
const DXGI_FORMAT scene_format = floating ? FLOAT_FORMAT : EIGHT_BIT_FORMAT;
- if (!Create_Target(SceneTarget, width, height, scene_format)) {
+ if (!Create_Target(SceneTarget, width, height, scene_format, samples)
+ || (samples > 1 && !Create_Target(SceneResolve, width, height, scene_format))) {
Release_Targets();
return false;
}
@@ -1300,6 +1320,7 @@ bool DX11PostProcessClass::Create_Targets(unsigned width, unsigned height, bool
Width = width;
Height = height;
+ TargetSamples = samples;
TargetsAreFloat = floating;
return true;
}
@@ -1314,6 +1335,7 @@ void DX11PostProcessClass::Release_Target(Target & target)
void DX11PostProcessClass::Release_Targets()
{
Release_Target(SceneTarget);
+ Release_Target(SceneResolve);
Release_Target(SceneCopy);
const unsigned chain_target_count = sizeof(ChainTargets) / sizeof(ChainTargets[0]);
for (unsigned index = 0; index < chain_target_count; ++index) {
@@ -1327,12 +1349,19 @@ void DX11PostProcessClass::Release_Targets()
Height = 0;
BloomWidth = 0;
BloomHeight = 0;
+ TargetSamples = 1;
TargetsAreFloat = false;
}
+unsigned DX11PostProcessClass::Scene_Samples() const
+{
+ return (Device != NULL) ? Device->Get_Sample_Count() : 1;
+}
+
bool DX11PostProcessClass::Ensure_Buffers()
{
- if (!ShadersReady || ChainLength == 0 || Device == NULL) {
+ const unsigned samples = Scene_Samples();
+ if (!ShadersReady || Device == NULL || (ChainLength == 0 && samples == 1)) {
return false;
}
@@ -1344,14 +1373,14 @@ bool DX11PostProcessClass::Ensure_Buffers()
const bool floating = Scene_Is_Float();
if (SceneTarget.View != NULL && Width == width && Height == height
- && TargetsAreFloat == floating) {
+ && TargetsAreFloat == floating && TargetSamples == samples) {
return true;
}
// A resolution change makes the old set the wrong size, and a chain that gained or lost bloom
// makes the scene target the wrong format. Both are for the rest of the run, not for a frame.
Release_Targets();
- if (!Create_Targets(width, height, floating)) {
+ if (!Create_Targets(width, height, floating, samples)) {
Release_Targets();
strcpy(Diagnostic, "post-process off: the device refused the offscreen targets");
return false;
@@ -1365,6 +1394,15 @@ ID3D11RenderTargetView * DX11PostProcessClass::Scene_View()
return Ensure_Buffers() ? SceneTarget.View : NULL;
}
+ID3D11ShaderResourceView * DX11PostProcessClass::Scene_Source()
+{
+ if (SceneResolve.Texture == NULL) {
+ return SceneTarget.Resource;
+ }
+ DX11Resource_Copy_Readable(Device->Get_Context(), SceneResolve.Texture, SceneTarget.Texture);
+ return SceneResolve.Resource;
+}
+
void DX11PostProcessClass::Begin_Frame()
{
Resolved = false;
@@ -1465,7 +1503,7 @@ bool DX11PostProcessClass::Occlude_Scene(ID3D11ShaderResourceView * depth)
Release_Target(SceneCopy);
return false;
}
- Device->Get_Context()->CopyResource(SceneCopy.Texture, SceneTarget.Texture);
+ DX11Resource_Copy_Readable(Device->Get_Context(), SceneCopy.Texture, SceneTarget.Texture);
PassSetup pass;
memset(&pass, 0, sizeof(pass));
@@ -1602,7 +1640,8 @@ void DX11PostProcessClass::Draw_Pass(const PassSetup & pass)
context->PSSetShaderResources(0, 2, no_resources);
}
-ID3D11ShaderResourceView * DX11PostProcessClass::Run_Bloom(ID3D11RenderTargetView * destination)
+ID3D11ShaderResourceView * DX11PostProcessClass::Run_Bloom(ID3D11RenderTargetView * destination,
+ ID3D11ShaderResourceView * scene)
{
const float bloom_texel_x = 1.0f / static_cast<float>(BloomWidth);
const float bloom_texel_y = 1.0f / static_cast<float>(BloomHeight);
@@ -1613,7 +1652,7 @@ ID3D11ShaderResourceView * DX11PostProcessClass::Run_Bloom(ID3D11RenderTargetVie
// The bright pass reads the full size scene and writes the quarter size target, so it is the
// one pass whose source and destination sizes differ.
pass.Shader = BloomExtractShader;
- pass.Source = SceneTarget.Resource;
+ pass.Source = scene;
pass.Destination = BloomTargets[0].View;
pass.DestinationWidth = BloomWidth;
pass.DestinationHeight = BloomHeight;
@@ -1642,7 +1681,7 @@ ID3D11ShaderResourceView * DX11PostProcessClass::Run_Bloom(ID3D11RenderTargetVie
}
pass.Shader = BloomCompositeShader;
- pass.Source = SceneTarget.Resource;
+ pass.Source = scene;
pass.Extra = BloomTargets[source].Resource;
pass.Destination = destination;
pass.DestinationWidth = Width;
@@ -1672,14 +1711,15 @@ bool DX11PostProcessClass::Finish(const DX11PostEffect * effects, unsigned count
const bool warp = (WarpCount > 0);
unsigned first = 0;
- ID3D11ShaderResourceView * source = SceneTarget.Resource;
+ ID3D11ShaderResourceView * const scene = Scene_Source();
+ ID3D11ShaderResourceView * source = scene;
if (effects[0] == DX11_POST_BLOOM) {
// Bloom is the only effect that reads the half float scene, and the frame is eight bits by
// the time it hands over. If it is also the last thing in the chain it writes the screen.
const bool alone = (count == 1) && !warp;
ID3D11RenderTargetView * bloom_destination = alone ? back_buffer : ChainTargets[0].View;
if (BloomIntensity > 0.0f) {
- source = Run_Bloom(bloom_destination);
+ source = Run_Bloom(bloom_destination, scene);
} else {
// Bloom switched off in the options: no glow, but the scene is still half floats and
// still has to come down to eight bits, the same way Copy_Through brings it down. The
@@ -1687,7 +1727,7 @@ bool DX11PostProcessClass::Finish(const DX11PostEffect * effects, unsigned count
PassSetup tone;
memset(&tone, 0, sizeof(tone));
tone.Shader = ToneMapShader;
- tone.Source = SceneTarget.Resource;
+ tone.Source = scene;
tone.Destination = bloom_destination;
tone.DestinationWidth = Width;
tone.DestinationHeight = Height;
@@ -1714,7 +1754,8 @@ bool DX11PostProcessClass::Finish(const DX11PostEffect * effects, unsigned count
pass.SourceHeight = Height;
for (unsigned index = first; index < count; ++index) {
const bool last = (index + 1 == count) && !warp;
- pass.Shader = PixelShaders[effects[index]];
+ pass.Shader = (effects[index] == DX11_POST_SHARPEN && TargetSamples > 1)
+ ? SharpenMultisampledShader : PixelShaders[effects[index]];
// The occlusion pass is the one effect that reads something other than the frame: the
// frame's own depth, which the device keeps as a texture as well as a depth buffer.
pass.Extra = (effects[index] == DX11_POST_AO) ? Device->Get_Depth_Texture() : NULL;
@@ -1741,17 +1782,18 @@ bool DX11PostProcessClass::Finish(const DX11PostEffect * effects, unsigned count
bool DX11PostProcessClass::Run_Chain()
{
- if (!Occluded) {
- return Finish(Chain, ChainLength);
- }
- // The scene took its occlusion before the particles; a chain of nothing else still has to
- // bring the scene to the screen.
+ // The scene took its occlusion before the particles, and a multisampled one has no use for
+ // FXAA; a chain of nothing else, or none at all over a multisampled scene, still has to bring
+ // the scene to the screen. Without either the chain runs as it was set, and an empty one with
+ // it, since an empty chain at one sample has no scene target to bring.
+ const bool multisampled = Scene_Samples() > 1;
DX11PostEffect effects[DX11_POST_CHAIN_LIMIT];
unsigned count = 0;
for (unsigned index = 0; index < ChainLength; ++index) {
- if (Chain[index] != DX11_POST_AO) {
- effects[count++] = Chain[index];
+ if ((Occluded && Chain[index] == DX11_POST_AO) || (multisampled && Chain[index] == DX11_POST_FXAA)) {
+ continue;
}
+ effects[count++] = Chain[index];
}
if (count == 0) {
effects[count++] = DX11_POST_COPY;
@@ -1761,7 +1803,7 @@ bool DX11PostProcessClass::Run_Chain()
bool DX11PostProcessClass::Copy_Through()
{
- if (Resolved || ChainLength == 0 || !Ensure_Buffers()) {
+ if (Resolved || !Ensure_Buffers()) {
return false;
}
@@ -1777,7 +1819,7 @@ bool DX11PostProcessClass::Copy_Through()
memset(&pass, 0, sizeof(pass));
pass.Shader = TargetsAreFloat ? ToneMapShader : PixelShaders[DX11_POST_COPY];
pass.Ungraded = true;
- pass.Source = SceneTarget.Resource;
+ pass.Source = Scene_Source();
pass.Destination = back_buffer;
pass.DestinationWidth = Width;
pass.DestinationHeight = Height;
@@ -1794,18 +1836,24 @@ void DX11PostProcessClass::Describe()
if (!ShadersReady) {
return;
}
- if (ChainLength == 0) {
+ const unsigned samples = Scene_Samples();
+ if (ChainLength == 0 && samples == 1) {
strcpy(Diagnostic, "post-process off");
return;
}
- std::string names;
+ std::string names = (ChainLength == 0) ? "copy" : "";
for (unsigned index = 0; index < ChainLength; ++index) {
if (index > 0) {
names += ",";
}
names += DX11Post_Effect_Name(Chain[index]);
}
- snprintf(Diagnostic, sizeof(Diagnostic), "post-process %s over %ux%u, scene in %s", names.c_str(),
- Width, Height, TargetsAreFloat ? "half floats" : "eight bits");
+ char multisampling[64] = "";
+ if (samples > 1) {
+ snprintf(multisampling, sizeof(multisampling), ", %ux multisampled without fxaa, sharpen softened",
+ samples);
+ }
+ snprintf(Diagnostic, sizeof(Diagnostic), "post-process %s over %ux%u, scene in %s%s", names.c_str(),
+ Width, Height, TargetsAreFloat ? "half floats" : "eight bits", multisampling);
}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11post.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11post.h
index 9b8a9b475..9ea3425db 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11post.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11post.h
@@ -65,9 +65,9 @@ enum DX11PostEffect
// screen pass and has to come out unchanged.
DX11_POST_COPY,
- // Edge antialiasing in one pass over the finished world. The Direct3D 9 device offers
- // multisampling and the swap chain here asks for one sample, so this is what the D3D11 frame
- // has against a jagged edge.
+ // Edge antialiasing in one pass over the finished world, what the D3D11 frame has against a
+ // jagged edge without multisampling. A multisampled scene leaves it out of the chain: the
+ // edges are already resolved, and FXAA over them only blurs the textures.
DX11_POST_FXAA,
// Unsharp mask. The game's textures are 2003 vintage and a 1080p window magnifies them; this
@@ -214,7 +214,9 @@ public:
void Shutdown();
// An empty chain is the whole feature turned off: Scene_View gives back nothing and the device
- // keeps drawing into the swap chain the way it always has.
+ // keeps drawing into the swap chain the way it always has. A multisampled device is the
+ // exception, since the swap chain cannot hold samples: its scene still goes into the target and
+ // reaches the screen through a copy.
void Set_Chain(const DX11PostEffect effects[DX11_POST_CHAIN_LIMIT], unsigned count);
unsigned Chain_Length() const { return ChainLength; }
@@ -308,13 +310,20 @@ private:
bool Create_Shaders();
bool Create_States();
- bool Create_Target(Target & target, unsigned width, unsigned height, DXGI_FORMAT format);
- bool Create_Targets(unsigned width, unsigned height, bool floating);
+ // A multisampled target is drawn into and resolved, never read, so it has no shader view.
+ bool Create_Target(Target & target, unsigned width, unsigned height, DXGI_FORMAT format,
+ unsigned samples = 1);
+ bool Create_Targets(unsigned width, unsigned height, bool floating, unsigned samples);
void Release_Target(Target & target);
void Release_Targets();
+ unsigned Scene_Samples() const;
bool Ensure_Buffers();
+ // The scene as a texture the passes read: the scene target itself, or with multisampling its
+ // samples resolved into SceneResolve, which is done again on every call.
+ ID3D11ShaderResourceView * Scene_Source();
bool Finish(const DX11PostEffect * effects, unsigned count);
- ID3D11ShaderResourceView * Run_Bloom(ID3D11RenderTargetView * destination);
+ ID3D11ShaderResourceView * Run_Bloom(ID3D11RenderTargetView * destination,
+ ID3D11ShaderResourceView * scene);
void Draw_Pass(const PassSetup & pass);
void Describe();
@@ -322,6 +331,7 @@ private:
ID3D11VertexShader * VertexShader;
ID3D11PixelShader * PixelShaders[DX11_POST_SIMPLE_EFFECTS];
ID3D11PixelShader * ToneMapShader;
+ ID3D11PixelShader * SharpenMultisampledShader; // the sharpen pass over a multisampled scene
ID3D11PixelShader * BloomExtractShader;
ID3D11PixelShader * BloomBlurShader;
ID3D11PixelShader * BloomCompositeShader;
@@ -340,6 +350,8 @@ private:
// turn, and they are always eight bit: the frame is back from half float by the time any of the
// one pass effects sees it.
Target SceneTarget;
+ // With multisampling, the scene target's samples resolved for the passes to read; empty without.
+ Target SceneResolve;
// The scene as Occlude_Scene found it, in its format, made at that pass's first use.
Target SceneCopy;
Target ChainTargets[2];
@@ -355,6 +367,7 @@ private:
unsigned Height;
unsigned BloomWidth;
unsigned BloomHeight;
+ unsigned TargetSamples;
bool TargetsAreFloat;
bool ShadersReady;
bool Resolved;
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11resource.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11resource.h
index 47464c17c..5873aaf5a 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11resource.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11resource.h
@@ -49,6 +49,21 @@ inline double DX11Resource_Milliseconds_Now()
return 1000.0 * static_cast<double>(counter) / static_cast<double>(frequency);
}
+// A render target copied into a single-sample texture of its size and format, for a pass that reads
+// it. CopyResource refuses a multisampled source, so the MSAA scene is resolved instead: its
+// samples averaged, which is what the screen shows of it anyway.
+inline void DX11Resource_Copy_Readable(ID3D11DeviceContext * context, ID3D11Resource * destination,
+ ID3D11Resource * source)
+{
+ D3D11_TEXTURE2D_DESC description;
+ static_cast<ID3D11Texture2D *>(source)->GetDesc(&description);
+ if (description.SampleDesc.Count > 1) {
+ context->ResolveSubresource(destination, 0, source, 0, description.Format);
+ } else {
+ context->CopyResource(destination, source);
+ }
+}
+
// DXGI_FORMAT_UNKNOWN comes back for a format with no D3D11 counterpart, which the caller has to
// treat as a refusal: a texture created as UNKNOWN is not a texture. Two of the engine's formats
// are in that class - the palettised ones, which D3D11 dropped outright.
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp
index d06683025..49d4c2ab2 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp
@@ -37,6 +37,7 @@ static bool PresentRequested = false;
static HRESULT PresentFailure = S_OK;
static bool PresentFailureReported = false;
static bool VSyncRequested = false;
+static unsigned SamplesRequested = 1;
static bool Active = false;
static DX11DeviceClass Device;
static DX11BackendClass Backend;
@@ -360,6 +361,7 @@ bool Direct3D11_Create(HWND window, unsigned width, unsigned height)
return Active;
}
+ Device.Request_Sample_Count(SamplesRequested);
if (!Device.Create(window, width, height)) {
return false;
}
@@ -377,6 +379,9 @@ bool Direct3D11_Create(HWND window, unsigned width, unsigned height)
Backend.Set_Shader_Cache_Path(cache_path.c_str());
Backend.Load_Shipped_Programs(SHIPPED_SHADER_FILE);
Backend.Set_Compile_Off_Frame(true);
+ if (Device.Get_Sample_Count() > 1 && !Backend.Make_Depth_Resolve()) {
+ Device.Drop_Multisampling();
+ }
// The chain is the one thing here that is allowed to fail without taking the backend with it:
// a machine whose compiler refuses the passes still gets the frame, just not the effect.
@@ -403,6 +408,16 @@ void Direct3D11_Release()
Active = false;
}
+void Direct3D11_Set_Sample_Count(unsigned samples)
+{
+ SamplesRequested = samples;
+}
+
+unsigned Direct3D11_Sample_Count()
+{
+ return (Active && Device.Get_Sample_Count() > 1) ? Device.Get_Sample_Count() : 0;
+}
+
bool Direct3D11_Resize(unsigned width, unsigned height)
{
if (!Active) {
@@ -733,6 +748,7 @@ void Direct3D11_Occlude_Scene()
if (!Active || !Backend.Draws_Into_Scene()) {
return;
}
+ Backend.Resolve_Scene_Depth();
bool drew = Post.Occlude_Scene(Device.Get_Depth_Texture());
// The prototype ground haze goes on at the same moment, over the occlusion and under the fire.
if (Post.Wants_Haze_Program()) {
@@ -902,6 +918,9 @@ void Direct3D11_Finish_Scene()
{
if (Active) {
stamp_gpu_frame(GPU_SCENE_END);
+ // The chain's occlusion and whatever tests against the depth over the interface read it
+ // single-sampled.
+ Backend.Resolve_Scene_Depth();
}
if (Active && Post.Run_Chain()) {
take_the_frame_to_the_screen();
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h
index 15e37d870..cdb22087d 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h
@@ -72,6 +72,11 @@ bool Direct3D11_Is_Enabled();
bool Direct3D11_Create(RenderWindow window, unsigned width, unsigned height);
void Direct3D11_Release();
+// The scene's multisampling, asked for before Create (DX11DeviceClass::Request_Sample_Count): 0 or 1
+// is none, otherwise 2 to 16. Sample_Count is what the device granted, 0 for none or no device.
+void Direct3D11_Set_Sample_Count(unsigned samples);
+unsigned Direct3D11_Sample_Count();
+
// The swap chain's buffers at a new resolution. Nothing if they already are that size.
bool Direct3D11_Resize(unsigned width, unsigned height);
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime_posix.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime_posix.cpp
index b57e77e4b..8efa270bd 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime_posix.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime_posix.cpp
@@ -41,6 +41,8 @@ void Direct3D11_Enable(bool enabled) { Requested = enabled; }
bool Direct3D11_Is_Enabled() { return Requested; }
bool Direct3D11_Create(RenderWindow, unsigned, unsigned) { return false; }
void Direct3D11_Release() {}
+void Direct3D11_Set_Sample_Count(unsigned) {}
+unsigned Direct3D11_Sample_Count() { return 0; }
bool Direct3D11_Resize(unsigned, unsigned) { return false; }
bool Direct3D11_Is_Active() { return false; }
DX11DeviceClass * Direct3D11_Device() { return NULL; }
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11water.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11water.cpp
index fac22bcdc..af42c14dd 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11water.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11water.cpp
@@ -17,6 +17,7 @@
*/
#include "dx11backend.h"
+#include "dx11resource.h"
#include "dx11water.h"
#include "Platform/WaterConstants.h"
#include "Platform/WaterFftSampling.h"
@@ -453,7 +454,7 @@ void DX11BackendClass::WaterResources::Take_Scene(DX11DeviceClass & device, ID3D
drop(Colour);
}
}
- if (Colour == NULL && description.SampleDesc.Count == 1) {
+ if (Colour == NULL) {
D3D11_RENDER_TARGET_VIEW_DESC written;
view->GetDesc(&written);
D3D11_TEXTURE2D_DESC copy = description;
@@ -462,6 +463,9 @@ void DX11BackendClass::WaterResources::Take_Scene(DX11DeviceClass & device, ID3D
copy.MiscFlags = 0;
copy.Usage = D3D11_USAGE_DEFAULT;
copy.CPUAccessFlags = 0;
+ // a multisampled scene is resolved into it
+ copy.SampleDesc.Count = 1;
+ copy.SampleDesc.Quality = 0;
D3D11_SHADER_RESOURCE_VIEW_DESC read;
memset(&read, 0, sizeof(read));
read.Format = written.Format;
@@ -474,7 +478,7 @@ void DX11BackendClass::WaterResources::Take_Scene(DX11DeviceClass & device, ID3D
}
}
if (Colour != NULL && description.MipLevels == 1) {
- context->CopyResource(Colour, source);
+ DX11Resource_Copy_Readable(context, Colour, source);
}
else if (Colour != NULL) {
context->CopySubresourceRegion(Colour, 0, 0, 0, 0, source, 0, NULL);
@@ -660,6 +664,7 @@ bool DX11BackendClass::Prepare_Water()
water.Fft = water.DrawVertex != NULL;
}
+ Resolve_Scene_Depth();
ID3D11RenderTargetView * const view = (CurrentTarget != NULL) ? CurrentTarget : Device->Get_Scene_View();
ID3D11Resource * source = CurrentTargetResource;
if (CurrentTarget == NULL) {
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.cpp
index 4e96ec9de..71929fd53 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.cpp
@@ -200,6 +200,13 @@ static bool operation_expression(FixedFunctionValue operation, const std::string
static const char * const ALPHA_LEVEL =
" float alpha_level = floor(current.a * 255.0 + 0.5);\n";
+// The sharpened alpha in place of the clip, for the two tests that keep the high alphas.
+static bool alpha_to_coverage(const PixelPipelineDescription & pipeline)
+{
+ return pipeline.AlphaToCoverage && pipeline.AlphaTestEnabled
+ && (pipeline.AlphaFunction == FF_CMP_GREATER || pipeline.AlphaFunction == FF_CMP_GREATEREQUAL);
+}
+
static bool alpha_test_expression(FixedFunctionValue function, std::string & expression)
{
switch (function) {
@@ -566,7 +573,16 @@ bool CombinerShader_Append_Pixel_Pipeline(const PixelPipelineDescription & pipel
if (!alpha_test_expression(pipeline.AlphaFunction, clip)) {
return false;
}
- if (!clip.empty()) {
+ if (alpha_to_coverage(pipeline)) {
+ // The edge half a level past the reference on the side the test keeps, so a strict and
+ // an inclusive test part where their clips do. Nothing is clipped: no coverage is no
+ // sample, depth included.
+ hlsl += (pipeline.AlphaFunction == FF_CMP_GREATER)
+ ? " float coverage_edge = (AlphaReference.x + 0.5) / 255.0;\n"
+ : " float coverage_edge = (AlphaReference.x - 0.5) / 255.0;\n";
+ hlsl += " current.a = saturate((current.a - coverage_edge) / max(fwidth(current.a), 0.0001) + 0.5);\n";
+ }
+ else if (!clip.empty()) {
hlsl += ALPHA_LEVEL;
hlsl += " " + clip;
}
@@ -577,10 +593,11 @@ bool CombinerShader_Append_Pixel_Pipeline(const PixelPipelineDescription & pipel
std::string CombinerShader_Pipeline_Key(const PixelPipelineDescription & pipeline)
{
char field[32];
- snprintf(field, sizeof(field), ":A%u,%lu,F%u",
+ snprintf(field, sizeof(field), ":A%u,%lu,F%u%s",
pipeline.AlphaTestEnabled ? 1u : 0u,
pipeline.AlphaTestEnabled ? pipeline.AlphaFunction : 0ul,
- pipeline.FogEnabled ? 1u : 0u);
+ pipeline.FogEnabled ? 1u : 0u,
+ alpha_to_coverage(pipeline) ? ",C" : "");
return field;
}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.h
index 78013950c..2f8ffc08c 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.h
@@ -74,6 +74,12 @@ struct PixelPipelineDescription
FixedFunctionValue AlphaFunction;
bool FogEnabled;
+
+ // D3D11 only: the draw goes into a multisampled scene with alpha to coverage on (a GREATER or
+ // GREATEREQUAL test, DX11BackendClass::Alpha_To_Coverage). In place of the clip the alpha is
+ // sharpened about the reference to about a pixel's width, so a cut edge covers its samples
+ // across one pixel and a mipmap's faded alpha above the reference still covers them all.
+ bool AlphaToCoverage = false;
};
struct CombinerDescription
diff --git a/GeneralsMD/Code/Tests/test_dx11backend.cpp b/GeneralsMD/Code/Tests/test_dx11backend.cpp
index 5f4f49749..259e9acbc 100644
--- a/GeneralsMD/Code/Tests/test_dx11backend.cpp
+++ b/GeneralsMD/Code/Tests/test_dx11backend.cpp
@@ -28,6 +28,7 @@
#include "test_harness.h"
#include "dx11backend.h"
+#include "dx11post.h"
#include "dx11resource.h"
#include "dx11water.h"
#include "Platform/HazardCloudCore.h"
@@ -39,6 +40,7 @@
#include <chrono>
#include <thread>
#include <vector>
+#include <windows.h>
static const unsigned TARGET_SIZE = 64;
static const DWORD BACKEND_FVF = D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_TEX2|D3DFVF_DIFFUSE;
@@ -1758,3 +1760,260 @@ TEST(dx11backend_the_modern_water_constants_are_built_from_the_registers)
WaterConstants::FillVisual(block, registers, visual);
CHECK(visual.VisualHullMeta[0][3] == 0.0f);
}
+
+// A multisampled scene the way the game draws one: four samples asked of the device, the post
+// chain's target and the scene's depth made at four, the backend drawing into them, the chain
+// resolving the colour onto the swap chain and Resolve_Scene_Depth the depth into the buffer every
+// depth reader samples. The left half is an opaque quad at depth 0.5 and has to come back as the
+// vertex colour and as 0.5. The right half is an alpha tested white quad whose alpha climbs across
+// it and a little up it (0.75 of the width, 0.25 of the height), tested GREATER than a half, so the
+// cut is a slanted line. A plain clip cuts it with no grey at all; the alpha itself taken as
+// coverage greys every pixel past the cut, which is what thinned the willows; the sharpened alpha
+// greys the pixel or two each row's cut passes through and covers the rest.
+TEST(dx11backend_a_multisampled_scene_resolves_its_colour_and_depth_and_covers_by_alpha)
+{
+ HWND window = CreateWindowExA(0, "STATIC", "dx11msaa", WS_OVERLAPPED, 0, 0, TARGET_SIZE,
+ TARGET_SIZE, NULL, NULL, GetModuleHandle(NULL), NULL);
+ CHECK(window != NULL);
+ DX11DeviceClass device;
+ device.Request_Debug_Layer();
+ device.Request_Sample_Count(4);
+ CHECK(device.Create(window, TARGET_SIZE, TARGET_SIZE));
+ CHECK_EQ(device.Get_Sample_Count(), 4u);
+ ID3D11Device * d3d = device.Get_Device();
+ ID3D11DeviceContext * context = device.Get_Context();
+
+ // No chain at all: a multisampled scene still goes into the post target and out through a copy.
+ DX11PostProcessClass post;
+ CHECK(post.Initialise(&device));
+ post.Begin_Frame();
+ device.Set_Scene_View(post.Scene_View());
+ CHECK(device.Scene_Is_Multisampled());
+
+ DX11BackendClass backend;
+ CHECK(backend.Initialise(&device));
+ backend.Begin_Scene();
+ const float black[4] = { 0.0f, 0.0f, 0.0f, 1.0f };
+ backend.Clear(true, true, black);
+
+ // White at alpha 0, 0.25, 1 and 0.75: bottom left, top left, top right, bottom right, one plane.
+ const BackendVertex halves[8] = {
+ { { -1.0f, -1.0f, 0.5f }, { 0.0f, 0.0f, 1.0f }, VERTEX_COLOUR, { 0.0f, 0.0f }, { 0.0f, 0.0f } },
+ { { -1.0f, 1.0f, 0.5f }, { 0.0f, 0.0f, 1.0f }, VERTEX_COLOUR, { 0.0f, 0.0f }, { 0.0f, 0.0f } },
+ { { 0.0f, 1.0f, 0.5f }, { 0.0f, 0.0f, 1.0f }, VERTEX_COLOUR, { 0.0f, 0.0f }, { 0.0f, 0.0f } },
+ { { 0.0f, -1.0f, 0.5f }, { 0.0f, 0.0f, 1.0f }, VERTEX_COLOUR, { 0.0f, 0.0f }, { 0.0f, 0.0f } },
+ { { 0.0f, -1.0f, 0.5f }, { 0.0f, 0.0f, 1.0f }, 0x00ffffff, { 0.0f, 0.0f }, { 0.0f, 0.0f } },
+ { { 0.0f, 1.0f, 0.5f }, { 0.0f, 0.0f, 1.0f }, 0x40ffffff, { 0.0f, 0.0f }, { 0.0f, 0.0f } },
+ { { 1.0f, 1.0f, 0.5f }, { 0.0f, 0.0f, 1.0f }, 0xffffffff, { 0.0f, 0.0f }, { 0.0f, 0.0f } },
+ { { 1.0f, -1.0f, 0.5f }, { 0.0f, 0.0f, 1.0f }, 0xbfffffff, { 0.0f, 0.0f }, { 0.0f, 0.0f } },
+ };
+ ID3D11Buffer * vertices = NULL;
+ CHECK(DX11Resource_Create_Vertex_Buffer(d3d, sizeof(halves), D3DPOOL_MANAGED, 0, halves, &vertices));
+ ID3D11Buffer * indices = NULL;
+ CHECK(DX11Resource_Create_Index_Buffer(d3d, sizeof(QUAD_INDICES), D3DPOOL_MANAGED, 0,
+ QUAD_INDICES, &indices));
+
+ configure_unlit_pass_through(backend);
+ backend.Set_Render_State(D3DRS_ZENABLE, D3DZB_TRUE);
+ backend.Set_Render_State(D3DRS_ZWRITEENABLE, TRUE);
+ backend.Set_Render_State(D3DRS_ZFUNC, D3DCMP_LESSEQUAL);
+ backend.Set_Stream_Source(vertices, sizeof(BackendVertex), 0);
+ backend.Set_Indices(indices, DXGI_FORMAT_R16_UINT);
+ CHECK(backend.Draw_Indexed_Triangles(6, 0, 0));
+ backend.Set_Render_State(D3DRS_ALPHATESTENABLE, TRUE);
+ backend.Set_Render_State(D3DRS_ALPHAREF, 0x80);
+ backend.Set_Render_State(D3DRS_ALPHAFUNC, D3DCMP_GREATER);
+ CHECK(backend.Draw_Indexed_Triangles(6, 0, 4));
+
+ backend.Resolve_Scene_Depth();
+ CHECK(post.Run_Chain());
+
+ // The colour, off the swap chain.
+ ID3D11Resource * back_buffer = NULL;
+ device.Get_Back_Buffer_View()->GetResource(&back_buffer);
+ D3D11_TEXTURE2D_DESC staging_description;
+ static_cast<ID3D11Texture2D *>(back_buffer)->GetDesc(&staging_description);
+ staging_description.Usage = D3D11_USAGE_STAGING;
+ staging_description.BindFlags = 0;
+ staging_description.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
+ staging_description.MiscFlags = 0;
+ ID3D11Texture2D * staging = NULL;
+ CHECK(SUCCEEDED(d3d->CreateTexture2D(&staging_description, NULL, &staging)));
+ context->CopyResource(staging, back_buffer);
+ D3D11_MAPPED_SUBRESOURCE mapped;
+ CHECK(SUCCEEDED(context->Map(staging, 0, D3D11_MAP_READ, 0, &mapped)));
+ const unsigned char * pixels = static_cast<const unsigned char *>(mapped.pData);
+ const unsigned char * opaque = pixels + mapped.RowPitch * (TARGET_SIZE / 2) + (TARGET_SIZE / 4) * 4;
+ CHECK_EQ(opaque[0], EXPECTED_BLUE);
+ CHECK_EQ(opaque[1], EXPECTED_GREEN);
+ CHECK_EQ(opaque[2], EXPECTED_RED);
+ // Row by row across the right half: black before the cut, white past it, grey only where it
+ // passes. Under a tenth of the way across every row is short of the reference, and past nine
+ // tenths every row is well over it.
+ unsigned grey = 0;
+ unsigned widest = 0;
+ unsigned lit_early = 0;
+ unsigned dark_late = 0;
+ for (unsigned y = TARGET_SIZE / 8; y < TARGET_SIZE * 7 / 8; ++y) {
+ unsigned row_grey = 0;
+ for (unsigned x = TARGET_SIZE / 2; x < TARGET_SIZE; ++x) {
+ const unsigned value = pixels[mapped.RowPitch * y + x * 4];
+ row_grey += (value > 8 && value < 247) ? 1u : 0u;
+ }
+ grey += row_grey;
+ widest = (row_grey > widest) ? row_grey : widest;
+ lit_early += (pixels[mapped.RowPitch * y + (TARGET_SIZE * 21 / 40) * 4] > 8) ? 1u : 0u;
+ dark_late += (pixels[mapped.RowPitch * y + (TARGET_SIZE * 39 / 40) * 4] < 247) ? 1u : 0u;
+ }
+ if (grey < 8 || widest > 2 || lit_early != 0 || dark_late != 0) {
+ printf(" alpha tested half: %u grey pixels, at most %u a row, %u lit early, %u dark late\n",
+ grey, widest, lit_early, dark_late);
+ }
+ CHECK(grey >= 8);
+ CHECK(widest <= 2);
+ CHECK_EQ(lit_early, 0u);
+ CHECK_EQ(dark_late, 0u);
+ context->Unmap(staging, 0);
+
+ // The depth, off the single-sample buffer the resolve wrote. D24: the low 24 bits.
+ ID3D11Resource * depth = NULL;
+ device.Get_Depth_Texture()->GetResource(&depth);
+ D3D11_TEXTURE2D_DESC depth_description;
+ static_cast<ID3D11Texture2D *>(depth)->GetDesc(&depth_description);
+ depth_description.Usage = D3D11_USAGE_STAGING;
+ depth_description.BindFlags = 0;
+ depth_description.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
+ depth_description.MiscFlags = 0;
+ ID3D11Texture2D * depth_staging = NULL;
+ CHECK(SUCCEEDED(d3d->CreateTexture2D(&depth_description, NULL, &depth_staging)));
+ context->CopyResource(depth_staging, depth);
+ CHECK(SUCCEEDED(context->Map(depth_staging, 0, D3D11_MAP_READ, 0, &mapped)));
+ const unsigned texel = *reinterpret_cast<const unsigned *>(static_cast<const unsigned char *>(mapped.pData)
+ + mapped.RowPitch * (TARGET_SIZE / 2) + (TARGET_SIZE / 4) * 4);
+ const float resolved = static_cast<float>(texel & 0xffffff) / 16777215.0f;
+ if (fabsf(resolved - 0.5f) > 0.001f) {
+ printf(" resolved depth %f, wanted 0.5\n", resolved);
+ }
+ CHECK(fabsf(resolved - 0.5f) <= 0.001f);
+ context->Unmap(depth_staging, 0);
+
+ depth_staging->Release();
+ depth->Release();
+ staging->Release();
+ back_buffer->Release();
+ indices->Release();
+ vertices->Release();
+ backend.Shutdown();
+ post.Shutdown();
+ device.Release();
+ DestroyWindow(window);
+}
+
+// The black and white view, the motion blur and the cross fade bind a texture the size of the screen
+// right after the frame's clear and draw the scene into it over the single-sample depth (Depth_For).
+// With multisampling the scene's clear lands on the multisampled depth, so the frame's clear has to
+// take the single-sample one too: here it holds the last frame's resolve at 0.2, and a quad at 0.5
+// drawn into the filter's texture fails the depth test and leaves the texture black without it.
+TEST(dx11backend_a_screen_filter_after_a_multisampled_clear_draws_over_a_cleared_depth)
+{
+ HWND window = CreateWindowExA(0, "STATIC", "dx11msaafilter", WS_OVERLAPPED, 0, 0, TARGET_SIZE,
+ TARGET_SIZE, NULL, NULL, GetModuleHandle(NULL), NULL);
+ CHECK(window != NULL);
+ DX11DeviceClass device;
+ device.Request_Debug_Layer();
+ device.Request_Sample_Count(4);
+ CHECK(device.Create(window, TARGET_SIZE, TARGET_SIZE));
+ CHECK_EQ(device.Get_Sample_Count(), 4u);
+ ID3D11Device * d3d = device.Get_Device();
+ ID3D11DeviceContext * context = device.Get_Context();
+
+ DX11PostProcessClass post;
+ CHECK(post.Initialise(&device));
+ post.Begin_Frame();
+ device.Set_Scene_View(post.Scene_View());
+ CHECK(device.Scene_Is_Multisampled());
+
+ DX11BackendClass backend;
+ CHECK(backend.Initialise(&device));
+ backend.Begin_Scene();
+
+ const BackendVertex near_then_middle[8] = {
+ { { -1.0f, -1.0f, 0.2f }, { 0.0f, 0.0f, 1.0f }, VERTEX_COLOUR, { 0.0f, 0.0f }, { 0.0f, 0.0f } },
+ { { -1.0f, 1.0f, 0.2f }, { 0.0f, 0.0f, 1.0f }, VERTEX_COLOUR, { 0.0f, 0.0f }, { 0.0f, 0.0f } },
+ { { 1.0f, 1.0f, 0.2f }, { 0.0f, 0.0f, 1.0f }, VERTEX_COLOUR, { 0.0f, 0.0f }, { 0.0f, 0.0f } },
+ { { 1.0f, -1.0f, 0.2f }, { 0.0f, 0.0f, 1.0f }, VERTEX_COLOUR, { 0.0f, 0.0f }, { 0.0f, 0.0f } },
+ { { -1.0f, -1.0f, 0.5f }, { 0.0f, 0.0f, 1.0f }, VERTEX_COLOUR, { 0.0f, 0.0f }, { 0.0f, 0.0f } },
+ { { -1.0f, 1.0f, 0.5f }, { 0.0f, 0.0f, 1.0f }, VERTEX_COLOUR, { 0.0f, 0.0f }, { 0.0f, 0.0f } },
+ { { 1.0f, 1.0f, 0.5f }, { 0.0f, 0.0f, 1.0f }, VERTEX_COLOUR, { 0.0f, 0.0f }, { 0.0f, 0.0f } },
+ { { 1.0f, -1.0f, 0.5f }, { 0.0f, 0.0f, 1.0f }, VERTEX_COLOUR, { 0.0f, 0.0f }, { 0.0f, 0.0f } },
+ };
+ ID3D11Buffer * vertices = NULL;
+ CHECK(DX11Resource_Create_Vertex_Buffer(d3d, sizeof(near_then_middle), D3DPOOL_MANAGED, 0,
+ near_then_middle, &vertices));
+ ID3D11Buffer * indices = NULL;
+ CHECK(DX11Resource_Create_Index_Buffer(d3d, sizeof(QUAD_INDICES), D3DPOOL_MANAGED, 0,
+ QUAD_INDICES, &indices));
+ configure_unlit_pass_through(backend);
+ backend.Set_Render_State(D3DRS_ZENABLE, D3DZB_TRUE);
+ backend.Set_Render_State(D3DRS_ZWRITEENABLE, TRUE);
+ backend.Set_Render_State(D3DRS_ZFUNC, D3DCMP_LESSEQUAL);
+ backend.Set_Stream_Source(vertices, sizeof(BackendVertex), 0);
+ backend.Set_Indices(indices, DXGI_FORMAT_R16_UINT);
+
+ // Last frame: the near quad, resolved into the single-sample depth.
+ const float black[4] = { 0.0f, 0.0f, 0.0f, 1.0f };
+ backend.Clear(true, true, black);
+ CHECK(backend.Draw_Indexed_Triangles(6, 0, 0));
+ backend.Resolve_Scene_Depth();
+
+ // This frame: the clear, then the filter's texture and the quad behind last frame's depth.
+ backend.Clear(true, true, black);
+ 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)));
+ ID3D11RenderTargetView * target_view = NULL;
+ CHECK(SUCCEEDED(d3d->CreateRenderTargetView(target, NULL, &target_view)));
+ backend.Set_Render_Target(target_view);
+ backend.Clear(true, false, black);
+ CHECK(backend.Draw_Indexed_Triangles(6, 0, 4));
+ backend.Set_Render_Target(NULL);
+
+ 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)));
+ context->CopyResource(staging, target);
+ D3D11_MAPPED_SUBRESOURCE mapped;
+ CHECK(SUCCEEDED(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(" filter texture centre bgra %02x %02x %02x %02x\n", centre[0], centre[1], centre[2],
+ centre[3]);
+ }
+ CHECK_EQ(centre[0], EXPECTED_BLUE);
+ CHECK_EQ(centre[1], EXPECTED_GREEN);
+ CHECK_EQ(centre[2], EXPECTED_RED);
+ context->Unmap(staging, 0);
+
+ staging->Release();
+ target_view->Release();
+ target->Release();
+ indices->Release();
+ vertices->Release();
+ backend.Shutdown();
+ post.Shutdown();
+ device.Release();
+ DestroyWindow(window);
+}