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
feat(w3ddevice): volumetric smoke shadows on the Direct3D 11 path
Olcay Seygan0f43b8c41902
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 149b35bd1..d2496220b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1222,6 +1222,7 @@ The whole HUD is on the hardware. Four colours carry it, and they mean the same- Scuds, rockets and falling bombs cast a shadow running along the ground.- An aircraft's shadow lands where the sun puts it, not underneath the aircraft. Every plane and helicopter in the game's own data asks for a sun "no lower than 89 degrees", so each one cast its shadow straight down and towed it along directly below itself at any height, while the tank beside it was lit by the map's real sun and threw its shadow off to the side. Aircraft now take the same sun as everything else: a helicopter's shadow slides out from under it as it climbs, and a plane's runs ahead of or behind it depending on the hour the map is set at. On a map lit by a very low sun the shadow is held to what a 30 degree sun would cast, so it does not stretch across half the screen. The flat blob shadows under missiles and bombs follow the same ray.- A big smoke cloud darkens the ground under it and fades as it does.+- Smoke and dust stand in the sunlight. A column off a burning building throws a soft shadow as thick as the smoke is: a puff of dust barely tints the sand, a black plume darkens the ground, the tanks and the houses under it and the smoke behind it. The column itself is bright on the side facing the sun and goes dark on the far side, and a cloud drifting through a building's shadow greys over with everything else in there. A cloud used to cast a round patch straight down whichever way the sun stood, and took no shade from anything. Fire casts nothing, it is light. A machine that cannot run the newer picture keeps the round patch.- The soft blob shadow for trees and scenery had never been drawn at all.- Every one of the 128 tree types casts now, plus the bushes and palms.- A tree's shadow is the tree. Trunk, crown, and the gaps between the leaves, lying along thediff --git a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.hindex 0f0d3daea..a6dfe70c9 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h@@ -199,6 +199,8 @@ public:Bool m_startAtMaxZoom; // "StartAtMaxZoom": a game opens as far out as the wheel goes, not at the map's own defaultBool m_shadowsForProps; // "ShadowsForProps": fences, rubbish, shrubs - scenery the art gave no shadow at allBool m_shadowsForParticles; // "ShadowsForParticles": big alpha-blended particle clouds drop a soft blob on the ground+ Bool m_volumetricSmokeShadows; // "VolumetricSmokeShadows": smoke and dust shade the world and themselves through the sun's map (Direct3D 11)+ Bool m_smokeFireLighting; // "SmokeFireLighting": smoke takes light from the fire beside itBool m_classicGraphics; // "ClassicGraphics": the game's own art, tile, shadows and picture; read at startupBool m_shadowMap; // "-shadowmap": draw the casters into the sun's depth buffer as wellBool m_shadowMapReport; // "-shadowmapreport": log what ended up in that buffer, once a seconddiff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleSys.h b/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleSys.hindex 25925f532..7dece37f7 100644--- a/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleSys.h+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleSys.h@@ -980,6 +980,10 @@ private:/// The particle system manager singletonextern ParticleSystemManager *TheParticleSystemManager;+/// The renderer put the smoke into the sun's map on its last frame, so the clouds already shade the+/// ground and the blob under each one would shade it twice. Written by the shadow pass.+extern Bool TheSmokeInSunMap;+class DebugDisplayInterface;extern void ParticleSystemDebugDisplay( DebugDisplayInterface *dd, void *, FILE *fp = NULL );diff --git a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cppindex 46ba84cbd..31c026d3b 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp@@ -987,6 +987,28 @@ Int parseNoParticleShadows(char *args[], int)return 1;}+/* -novolumetricsmoke: smoke and dust out of the sun's map for one run, which is the other half of+ any picture of what they shade. The blob under each cloud comes back with it, as it does on a+ machine with no Direct3D 11 device. */+Int parseNoVolumetricSmoke(char *args[], int)+{+ if (TheWritableGlobalData)+ {+ TheWritableGlobalData->m_volumetricSmokeShadows = FALSE;+ }+ return 1;+}++/* -nosmokefirelight: smoke left unlit by the fire beside it, for one run. */+Int parseNoSmokeFireLight(char *args[], int)+{+ if (TheWritableGlobalData)+ {+ TheWritableGlobalData->m_smokeFireLighting = FALSE;+ }+ return 1;+}+Int parseNoShaders(char *args[], int){if (TheWritableGlobalData)@@ -2382,6 +2404,8 @@ static CommandLineParam params[] ={ "-shadowmapreport", parseShadowMapReport },{ "-shadowmapboth", parseShadowMapBoth },{ "-noparticleshadows", parseNoParticleShadows },+ { "-novolumetricsmoke", parseNoVolumetricSmoke },+ { "-nosmokefirelight", parseNoSmokeFireLight },{ "-quickstart", parseQuickStart },/* In every build: EA kept them to Debug and Internal, so a Release run could not skip the logo or themovies. */diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cppindex 24b6afca6..5e1fca97e 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp@@ -687,6 +687,8 @@ GlobalData::GlobalData()m_startAtMaxZoom = TRUE; //open a game framed as wide as the player could zoom by handm_shadowsForProps = TRUE; //likewise: scenery with no shadow of its own gets onem_shadowsForParticles = TRUE; //on by default: the shipped INI has no entry for it+ m_volumetricSmokeShadows = TRUE;+ m_smokeFireLighting = TRUE;m_classicGraphics = FALSE;m_shadowMap = TRUE; //the sun's own shadows are what the game draws with nowm_shadowMapOnly = TRUE; //and they replace the stencil volumes rather than joining them@@ -1502,6 +1504,7 @@ void GlobalData::parseGameDataDefinition( INI* ini )if (TheWritableGlobalData->m_classicGraphics){TheWritableGlobalData->m_shadowMap = FALSE;+ TheWritableGlobalData->m_volumetricSmokeShadows = FALSE;TheWritableGlobalData->m_direct3D11PostChain = "off";}diff --git a/GeneralsMD/Code/GameEngine/Source/Common/OptionsCatalog.cpp b/GeneralsMD/Code/GameEngine/Source/Common/OptionsCatalog.cppindex 9f4d964d2..80550a656 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/OptionsCatalog.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/OptionsCatalog.cpp@@ -108,6 +108,8 @@ OPTION_BOOL_ACCESSORS( m_shadowsForProjectiles )OPTION_BOOL_ACCESSORS( m_shadowsForProps )OPTION_BOOL_ACCESSORS( m_shadowsForParticles )OPTION_BOOL_ACCESSORS( m_particleGroundBounce )+OPTION_BOOL_ACCESSORS( m_volumetricSmokeShadows )+OPTION_BOOL_ACCESSORS( m_smokeFireLighting )OPTION_BOOL_ACCESSORS( m_showSkillStrip )OPTION_BOOL_ACCESSORS( m_showSuperweaponStrip )@@ -464,6 +466,18 @@ const OptionDef TheOptionCatalog[] =OPTION_BOOL, APPLY_LIVE, 0, 1,get_m_shadowsForParticles, set_m_shadowsForParticles },+ // Smoke and dust in the sun's map: a cloud shades the ground, the units and the smoke behind it+ // by how thick it is, and darkens on its own far side. Read by the shadow pass every frame. No+ // control yet; Options.ini and -novolumetricsmoke reach it.+ { "VolumetricSmokeShadows", "", "",+ OPTION_BOOL, APPLY_LIVE, 0, 1,+ get_m_volumetricSmokeShadows, set_m_volumetricSmokeShadows },++ // Smoke lit by the fire beside it. No control yet; -nosmokefirelight turns it off for a run.+ { "SmokeFireLighting", "", "",+ OPTION_BOOL, APPLY_LIVE, 0, 1,+ get_m_smokeFireLighting, set_m_smokeFireLighting },+// -smoke and -particlebounce as settings. Both are spent on the particle system templates while// the particle manager starts, so they wait for the next launch. The command line is parsed after// this catalog loads, so either switch still wins for the one run it is given.diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cppindex 8eac9204c..7d5f9704d 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp@@ -82,6 +82,7 @@ static UnsignedInt particleTimerFrames( Real value )// the singletonParticleSystemManager *TheParticleSystemManager = NULL;+Bool TheSmokeInSunMap = FALSE;//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////@@ -2512,6 +2513,10 @@ Bool ParticleSystem::shouldCastGroundShadow( void ) constif (m_shaderType != ALPHA && m_shaderType != ALPHA_TEST)return FALSE;+ // the sun's map holds this cloud already and shades the ground under it through its own density+ if (m_shaderType == ALPHA && TheSmokeInSunMap)+ return FALSE;+if (m_isGroundAligned)return FALSE;diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cppindex f71003987..22f865869 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cpp@@ -72,6 +72,9 @@#include "GameClient/View.h"#include "Platform/RenderTypes.h"#include "Lib/Clock.h" // Clock_Ticks: QueryPerformanceCounter on Windows, a monotonic clock elsewhere+#include "GameClient/ParticleSys.h"+#include <math.h>+#include <vector>#ifdef _INTERNAL// for occasional debugging...@@ -134,6 +137,14 @@ const Real cosAngleToCare = cos ((0.2 * PI) / 180.0); //1.5 degree difference#define SHADOW_MAP_NARROWEST_TEXELS 0.9f#define SHADOW_MAP_PENUMBRA_PER_UNIT 0.01f#define SHADOW_MAP_SKY_FILL 0.12f+// The smoke in the sun's light. The strength is how dark the thickest cloud leaves the ground and+// the smoke behind it, under the solid casters' 0.45 because the sky still lights the ground under a+// cloud and the smoke itself scatters some of the sun on. The density scales the optical depth a+// particle's own alpha implies, the one the eye sees through it; a particle fainter than the+// thinnest casts nothing. Untuned: chosen from the arithmetic, not from a frame.+#define SMOKE_SHADOW_STRENGTH 0.4f+#define SMOKE_SHADOW_DENSITY 1.0f+#define SMOKE_SHADOW_THINNEST 0.02f// Whether the sun's map took this frame. The volumes read it to know whether to stand down, and it// is false on a machine with no Direct3D 11 device, which is what keeps that machine's shadows.@@ -3829,6 +3840,56 @@ DECLARE_PERF_TIMER(stencilShadows)DECLARE_PERF_TIMER(shadowVolumeUpdate)DECLARE_PERF_TIMER(shadowVolumeSubmit)+/** The smoke into the sun's light: every alpha-blended billboard particle as a soft ball, its optical+ depth the one its own alpha implies, handed to the backend's smoke map. The systems are read+ as the last client update left them, because the pass runs before the frame's particles are+ drawn. Fire is additive and casts nothing; a ground-aligned system is a decal already. Says+ whether the smoke is in the map, which is what takes the blob off the ground under each cloud;+ with the option off this is a frame with no smoke, so the backend stops reading the map. */+static Bool fillSmokeMap( void )+{+ static std::vector<Real> casters; // kept: a burning base is thousands of particles every frame+ casters.clear();++ if (TheGlobalData->m_volumetricSmokeShadows && TheParticleSystemManager != NULL)+ {+ const size_t mostCasters = 16384;+ ParticleSystemManager::ParticleSystemList &systems = TheParticleSystemManager->getAllParticleSystems();+ for (ParticleSystemManager::ParticleSystemListIt it = systems.begin();+ it != systems.end() && casters.size() < mostCasters * 5; ++it)+ {+ ParticleSystem *sys = *it;+ if (sys == NULL || sys->getShaderType() != ParticleSystemInfo::ALPHA || !sys->shouldBillboard()+ || sys->isUsingDrawables() || sys->isUsingStreak() || sys->isUsingSmudge())+ continue;+ // the heat haze's texture names start with SMUD, as W3DParticleSystemManager::doParticles tests+ if (*((UnsignedInt *)sys->getParticleTypeName().str()) == 0x44554D53)+ continue;++ // a volume particle is drawn that many layers deep, and is that much thicker to the sun+ const Real layers = (Real)sys->getVolumeParticleDepth();+ for (Particle *p = sys->getFirstParticle(); p && casters.size() < mostCasters * 5; p = p->m_systemNext)+ {+ Real alpha = p->getAlpha();+ if (alpha < SMOKE_SHADOW_THINNEST)+ continue;+ if (alpha > 0.95f)+ alpha = 0.95f;+ const Coord3D *pos = p->getPosition();+ casters.push_back( pos->x );+ casters.push_back( pos->y );+ casters.push_back( pos->z );+ casters.push_back( p->getSize() * 0.5f ); // the billboard's size is its full width+ casters.push_back( -(Real)log( 1.0f - alpha ) * layers * SMOKE_SHADOW_DENSITY );+ }+ }+ }++ const Bool held = Direct3D11_Fill_Smoke_Map( casters.empty() ? NULL : &casters[ 0 ],+ (unsigned)( casters.size() / 5 ), SMOKE_SHADOW_STRENGTH );+ return held && TheGlobalData->m_volumetricSmokeShadows;+}+/** The sun's depth pass. The casters are the ones that cast a volume today, drawn again from thesun into a depth buffer nothing samples yet, so this phase can be proved on its own: with itoff the frame is what it was, and with it on the map has the world in it and the frame is@@ -3838,12 +3899,16 @@ DECLARE_PERF_TIMER(shadowVolumeSubmit)void W3DVolumetricShadowManager::renderShadowMap( CameraClass &sceneCamera ){theShadowMapHoldsTheFrame = FALSE;+ TheSmokeInSunMap = FALSE;- if (!TheGlobalData->m_shadowMap || m_shadowList == NULL || TheTacticalView == NULL)+ if (!TheGlobalData->m_shadowMap || m_shadowList == NULL || TheTacticalView == NULL+ || !Direct3D11_Begin_Shadow_Map( SHADOW_MAP_TEXELS ))+ {+ //no Direct3D 11 device, or it refused the surface: the volumes keep the frame, and no smoke is+ //read out of a map the last frame filled+ Direct3D11_Fill_Smoke_Map( NULL, 0, 0.0f );return;-- if (!Direct3D11_Begin_Shadow_Map( SHADOW_MAP_TEXELS ))- return; //no Direct3D 11 device, or it refused the surface: the volumes keep the frame+ }#ifdef DEBUG_LOGGING// The scene timer includes this pass and cannot say so.@@ -3963,6 +4028,9 @@ void W3DVolumetricShadowManager::renderShadowMap( CameraClass &sceneCamera )Direct3D11_End_Shadow_Map();+ // The smoke goes into a map of its own through the sun the casters were just drawn with.+ TheSmokeInSunMap = fillSmokeMap();+// The frame's own camera, put back: the view, the projection and the viewport all went with the// sun. Without this everything drawn after the pass is drawn from the sun's seat, which is the// whole picture rather than a corner of it.diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cppindex 6ca6b9a1a..f2c7fd7a3 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp@@ -304,6 +304,21 @@ DX11BackendClass::DX11BackendClass()set_identity(World);set_identity(View);set_identity(Projection);+ set_identity(SceneView);+ SmokeMapSurface = NULL;+ SmokeMapTarget = NULL;+ SmokeMapTexture = NULL;+ SmokeMapSampler = NULL;+ SmokeSplatVertexShader = NULL;+ SmokeSplatPixelShader = NULL;+ SmokeSplatLayout = NULL;+ SmokeSplatBlend = NULL;+ SmokeSplatRasterizer = NULL;+ SmokeSplatInstances = NULL;+ SmokeSplatCapacity = 0;+ SmokeMapRefused = false;+ SmokeMapFilled = false;+ SmokeStrength = 0.0f;for (unsigned stage = 0; stage < DX11_BACKEND_TEXTURE_STAGES; ++stage) {set_identity(TextureTransforms[stage]);}@@ -460,6 +475,7 @@ void DX11BackendClass::Shutdown()}ShadowMapSize = 0;ShadowMapBound = false;+ Release_Smoke_Map();RenderStates.Set_Shadow_Caster_Pass(false);Note_Shadow_State_Changed();Device = NULL;@@ -588,6 +604,301 @@ void DX11BackendClass::Clear_Shadow_Parameters()Note_Shadow_State_Changed();}+/* The smoke's map. A quarter of the depth map's width is plenty: 3.5 world units a texel over the+ 1800 unit box, and nothing in a smoke cloud is that sharp. Four 32-bit channels because the third+ sum is a square, and in half floats a plume 200 units deep vanished into the rounding of a depth+ near 0.5 squared. 512 square of that is 4 MB. */+static const unsigned SMOKE_MAP_TEXELS = 512;+static const unsigned SMOKE_MAP_SLOT = DX11_BACKEND_TEXTURE_STAGES + 2; ///< t6 and s6, after the depth map's+static const unsigned SMOKE_SPLAT_FLOATS = 6; ///< per caster: sun clip x, y, z, radius, optical depth, depth spread+static const unsigned SMOKE_MOST_CASTERS = 16384;++// Each caster is a disc facing the sun, drawn as a four corner strip whose corners come from the+// vertex number, so the only buffer is the one holding the casters.+static const char SMOKE_SPLAT_VERTEX_PROGRAM[] =+ "struct Caster\n"+ "{\n"+ " float4 Centre : CENTRE;\n" // the sun's clip x, y and depth, and the radius in clip units+ " float2 Shape : SHAPE;\n" // optical depth through the middle, and the spread in depth+ "};\n"+ "struct Splat\n"+ "{\n"+ " float4 Position : SV_Position;\n"+ " float2 Corner : TEXCOORD0;\n"+ " float3 Moment : TEXCOORD1;\n"+ "};\n"+ "Splat main(Caster caster, uint corner : SV_VertexID)\n"+ "{\n"+ " Splat splat;\n"+ " splat.Corner = float2((corner & 1u) ? 1.0 : -1.0, (corner & 2u) ? 1.0 : -1.0);\n"+ " splat.Position = float4(caster.Centre.xy + splat.Corner * caster.Centre.w, 0.5, 1.0);\n"+ " splat.Moment = float3(caster.Shape.x, caster.Centre.z, caster.Shape.y);\n"+ " return splat;\n"+ "}\n";++// The three sums VOLUMETRIC_SAMPLING reads back, added up by the blend. The disc is thickest in its+// middle and thins to nothing at its rim, which is the shape every smoke sprite in the game has.+static const char SMOKE_SPLAT_PIXEL_PROGRAM[] =+ "struct Splat\n"+ "{\n"+ " float4 Position : SV_Position;\n"+ " float2 Corner : TEXCOORD0;\n"+ " float3 Moment : TEXCOORD1;\n"+ "};\n"+ "float4 main(Splat splat) : SV_Target\n"+ "{\n"+ " float rim = saturate(1.0 - dot(splat.Corner, splat.Corner));\n"+ " float thickness = splat.Moment.x * rim * rim;\n"+ " float depth = splat.Moment.y;\n"+ " float spread = splat.Moment.z;\n"+ " return float4(thickness, thickness * depth, thickness * (depth * depth + spread * spread), 0.0);\n"+ "}\n";++void DX11BackendClass::Release_Smoke_Map()+{+ IUnknown ** const held[] = {+ (IUnknown **)&SmokeMapTexture, (IUnknown **)&SmokeMapTarget, (IUnknown **)&SmokeMapSurface,+ (IUnknown **)&SmokeMapSampler, (IUnknown **)&SmokeSplatVertexShader,+ (IUnknown **)&SmokeSplatPixelShader, (IUnknown **)&SmokeSplatLayout,+ (IUnknown **)&SmokeSplatBlend, (IUnknown **)&SmokeSplatRasterizer,+ (IUnknown **)&SmokeSplatInstances,+ };+ for (unsigned index = 0; index < sizeof(held) / sizeof(held[0]); ++index) {+ if (*held[index] != NULL) {+ (*held[index])->Release();+ *held[index] = NULL;+ }+ }+ SmokeSplatCapacity = 0;+ SmokeMapRefused = false;+ SmokeMapFilled = false;+}++bool DX11BackendClass::Make_Smoke_Map()+{+ if (SmokeMapTarget != NULL) {+ return true;+ }+ if (SmokeMapRefused) {+ return false;+ }++ ID3D11Device * device = Device->Get_Device();+ const UINT wanted = D3D11_FORMAT_SUPPORT_TEXTURE2D | D3D11_FORMAT_SUPPORT_RENDER_TARGET+ | D3D11_FORMAT_SUPPORT_BLENDABLE | D3D11_FORMAT_SUPPORT_SHADER_SAMPLE;+ UINT support = 0;+ if (FAILED(device->CheckFormatSupport(DXGI_FORMAT_R32G32B32A32_FLOAT, &support))+ || (support & wanted) != wanted) {+ Note_Refusal("the device cannot blend and filter the smoke's 32-bit float map");+ SmokeMapRefused = true;+ return false;+ }++ D3D11_TEXTURE2D_DESC description;+ memset(&description, 0, sizeof(description));+ description.Width = SMOKE_MAP_TEXELS;+ description.Height = SMOKE_MAP_TEXELS;+ description.MipLevels = 1;+ description.ArraySize = 1;+ description.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;+ description.SampleDesc.Count = 1;+ description.Usage = D3D11_USAGE_DEFAULT;+ description.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;++ D3D11_SAMPLER_DESC sampler;+ memset(&sampler, 0, sizeof(sampler));+ sampler.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;+ sampler.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;+ sampler.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;+ sampler.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;+ sampler.ComparisonFunc = D3D11_COMPARISON_NEVER;+ sampler.MaxLOD = D3D11_FLOAT32_MAX;++ D3D11_BLEND_DESC blend;+ memset(&blend, 0, sizeof(blend));+ blend.RenderTarget[0].BlendEnable = TRUE;+ blend.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE;+ blend.RenderTarget[0].DestBlend = D3D11_BLEND_ONE;+ blend.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;+ blend.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;+ blend.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ONE;+ blend.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;+ blend.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;++ D3D11_RASTERIZER_DESC rasterizer;+ memset(&rasterizer, 0, sizeof(rasterizer));+ rasterizer.FillMode = D3D11_FILL_SOLID;+ rasterizer.CullMode = D3D11_CULL_NONE;+ rasterizer.DepthClipEnable = FALSE;++ const D3D11_INPUT_ELEMENT_DESC elements[] = {+ { "CENTRE", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D11_INPUT_PER_INSTANCE_DATA, 1 },+ { "SHAPE", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 16, D3D11_INPUT_PER_INSTANCE_DATA, 1 },+ };++ std::vector<unsigned char> vertex_code;+ std::vector<unsigned char> pixel_code;+ const bool made = SUCCEEDED(device->CreateTexture2D(&description, NULL, &SmokeMapSurface))+ && SUCCEEDED(device->CreateRenderTargetView(SmokeMapSurface, NULL, &SmokeMapTarget))+ && SUCCEEDED(device->CreateShaderResourceView(SmokeMapSurface, NULL, &SmokeMapTexture))+ && SUCCEEDED(device->CreateSamplerState(&sampler, &SmokeMapSampler))+ && SUCCEEDED(device->CreateBlendState(&blend, &SmokeSplatBlend))+ && SUCCEEDED(device->CreateRasterizerState(&rasterizer, &SmokeSplatRasterizer))+ && Compile_Program(SMOKE_SPLAT_VERTEX_PROGRAM, "smokesplat", VERTEX_PROFILE, vertex_code)+ && Compile_Program(SMOKE_SPLAT_PIXEL_PROGRAM, "smokesplat", PIXEL_PROFILE, pixel_code)+ && SUCCEEDED(device->CreateVertexShader(&vertex_code[0], vertex_code.size(), NULL,+ &SmokeSplatVertexShader))+ && SUCCEEDED(device->CreatePixelShader(&pixel_code[0], pixel_code.size(), NULL,+ &SmokeSplatPixelShader))+ && SUCCEEDED(device->CreateInputLayout(elements, 2, &vertex_code[0], vertex_code.size(),+ &SmokeSplatLayout));+ if (!made) {+ Note_Refusal("the device would not make the smoke's map or the program that fills it");+ Release_Smoke_Map();+ SmokeMapRefused = true;+ return false;+ }+ return true;+}++bool DX11BackendClass::Fill_Smoke_Map(const float * casters, unsigned count, float strength)+{+ if (SmokeMapFilled) {+ SmokeMapFilled = false;+ ConstantsChanged = true;+ }+ if (Device == NULL || ShadowMapBound) {+ return false;+ }+ // Nothing to draw is not a reason to make the map; whether it could be made is answered the+ // first time there is.+ if (casters == NULL || count == 0 || strength <= 0.0f) {+ return !SmokeMapRefused;+ }+ if (!Make_Smoke_Map()) {+ return false;+ }+ if (count > SMOKE_MOST_CASTERS) {+ count = SMOKE_MOST_CASTERS;+ }++ /* Into the sun's clip space through the matrix the depth pass drew with, on the CPU: the sun is+ orthographic, so a sphere's radius is the same number of clip units wherever it stands and+ the disc needs no projection of its own. How many clip units a world unit is comes off the+ matrix's own columns. */+ const float * sun = SunViewProjection;+ const float across = sqrtf(sun[0] * sun[0] + sun[4] * sun[4] + sun[8] * sun[8]);+ const float deep = sqrtf(sun[2] * sun[2] + sun[6] * sun[6] + sun[10] * sun[10]);++ SmokeSplats.resize(count * SMOKE_SPLAT_FLOATS);+ unsigned splats = 0;+ for (unsigned index = 0; index < count; ++index) {+ const float * caster = casters + index * 5;+ const float w = caster[0] * sun[3] + caster[1] * sun[7] + caster[2] * sun[11] + sun[15];+ if (w <= 0.0f || caster[3] <= 0.0f || caster[4] <= 0.0f) {+ continue;+ }+ const float x = (caster[0] * sun[0] + caster[1] * sun[4] + caster[2] * sun[8] + sun[12]) / w;+ const float y = (caster[0] * sun[1] + caster[1] * sun[5] + caster[2] * sun[9] + sun[13]) / w;+ const float z = (caster[0] * sun[2] + caster[1] * sun[6] + caster[2] * sun[10] + sun[14]) / w;+ const float radius = caster[3] * across;+ // A ball's depth along the ray spreads about half its radius either side of its middle.+ const float spread = 0.5f * caster[3] * deep;+ if (x < -1.0f - radius || x > 1.0f + radius || y < -1.0f - radius || y > 1.0f + radius+ || z < -spread || z > 1.0f + spread) {+ continue;+ }+ float * splat = &SmokeSplats[splats * SMOKE_SPLAT_FLOATS];+ splat[0] = x;+ splat[1] = y;+ splat[2] = z;+ splat[3] = radius;+ splat[4] = caster[4];+ splat[5] = spread;+ ++splats;+ }+ if (splats == 0) {+ return true;+ }++ ID3D11Device * device = Device->Get_Device();+ ID3D11DeviceContext * context = Device->Get_Context();+ if (SmokeSplatCapacity < splats) {+ if (SmokeSplatInstances != NULL) {+ SmokeSplatInstances->Release();+ SmokeSplatInstances = NULL;+ }+ SmokeSplatCapacity = 0;+ unsigned capacity = 1024;+ while (capacity < splats) {+ capacity *= 2;+ }+ D3D11_BUFFER_DESC buffer;+ memset(&buffer, 0, sizeof(buffer));+ buffer.ByteWidth = capacity * SMOKE_SPLAT_FLOATS * sizeof(float);+ buffer.Usage = D3D11_USAGE_DYNAMIC;+ buffer.BindFlags = D3D11_BIND_VERTEX_BUFFER;+ buffer.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;+ if (FAILED(device->CreateBuffer(&buffer, NULL, &SmokeSplatInstances))) {+ Note_Refusal("the device refused the smoke casters' buffer");+ SmokeSplatInstances = NULL;+ return true;+ }+ SmokeSplatCapacity = capacity;+ }+ D3D11_MAPPED_SUBRESOURCE mapped;+ if (FAILED(context->Map(SmokeSplatInstances, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped))) {+ return true;+ }+ memcpy(mapped.pData, &SmokeSplats[0], splats * SMOKE_SPLAT_FLOATS * sizeof(float));+ context->Unmap(SmokeSplatInstances, 0);++ // The map is still bound for reading from the frame before, and a view cannot be both. What the+ // frame is drawing into comes back afterwards, the way End_Shadow_Map puts it back.+ ID3D11ShaderResourceView * const none = NULL;+ context->PSSetShaderResources(SMOKE_MAP_SLOT, 1, &none);+ ID3D11RenderTargetView * const saved_target = CurrentTarget;+ const unsigned saved_width = ViewportWidth;+ const unsigned saved_height = ViewportHeight;++ const float empty[4] = { 0.0f, 0.0f, 0.0f, 0.0f };+ context->OMSetRenderTargets(1, &SmokeMapTarget, NULL);+ context->ClearRenderTargetView(SmokeMapTarget, empty);+ Set_Viewport(0, 0, SMOKE_MAP_TEXELS, SMOKE_MAP_TEXELS);++ const UINT stride = SMOKE_SPLAT_FLOATS * sizeof(float);+ const UINT offset = 0;+ context->IASetInputLayout(SmokeSplatLayout);+ context->IASetVertexBuffers(0, 1, &SmokeSplatInstances, &stride, &offset);+ context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);+ context->VSSetShader(SmokeSplatVertexShader, NULL, 0);+ context->PSSetShader(SmokeSplatPixelShader, NULL, 0);+ context->OMSetBlendState(SmokeSplatBlend, NULL, 0xffffffff);+ context->OMSetDepthStencilState(NULL, 0);+ context->RSSetState(SmokeSplatRasterizer);+ context->DrawInstanced(4, splats, 0, 0);++ Set_Render_Target(saved_target);+ if (saved_width != 0 && saved_height != 0) {+ Set_Viewport(0, 0, saved_width, saved_height);+ }+ Forget_Bindings();++ SmokeMapFilled = true;+ SmokeStrength = strength;+ ConstantsChanged = true;+ return true;+}++bool DX11BackendClass::Camera_Space_Draw() const+{+ static const float IDENTITY[16] = {+ 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f };+ // A perspective projection's third column ends in one; an orthographic one, the interface's and+ // the sun's own, ends in nought.+ return Projection[11] != 0.0f && memcmp(View, IDENTITY, sizeof(IDENTITY)) == 0;+}+/** The inverse of a four by four, by cofactors. Nothing else in the backend needed one: everyother matrix it holds arrives ready to use, and this is the one journey that goes the otherway, out of the frame's clip space and back into the world. */@@ -1723,20 +2034,30 @@ void DX11BackendClass::Upload_Constants()}}+ // A camera space draw's pixels go back to the world through the scene camera's view, not through+ // the identity it was drawn with; see SceneView in the header.+ const bool camera_space = Camera_Space_Draw();+ if (!camera_space && Projection[11] != 0.0f) {+ memcpy(SceneView, View, sizeof(View));+ }+ const float * const world_to_camera = camera_space ? SceneView : View;+if (ShadowReceiving) {if (!ShadowFromClipValid- || memcmp(ShadowFromClipView, View, sizeof(View)) != 0+ || memcmp(ShadowFromClipView, world_to_camera, sizeof(View)) != 0|| memcmp(ShadowFromClipProjection, Projection, sizeof(Projection)) != 0) {float scene_clip[16];float clip_to_world[16];- multiply(View, Projection, scene_clip);+ multiply(world_to_camera, Projection, scene_clip);if (invert(scene_clip, clip_to_world)) {multiply(clip_to_world, SunViewProjection, ShadowFromClip);- memcpy(ShadowFromClipView, View, sizeof(View));+ memcpy(ShadowFromClipView, world_to_camera, sizeof(View));memcpy(ShadowFromClipProjection, Projection, sizeof(Projection));ShadowFromClipValid = true;}}+ pixel_block.VolumeParameters[0] = SmokeMapFilled ? SmokeStrength : 0.0f;+ pixel_block.VolumeParameters[2] = camera_space ? 1.0f : 0.0f;memcpy(pixel_block.ShadowFromClip, ShadowFromClip, sizeof(pixel_block.ShadowFromClip));pixel_block.ShadowParameters[0] = (ShadowMapSize > 0)? 1.0f / static_cast<float>(ShadowMapSize) : 0.0f;@@ -1995,9 +2316,14 @@ void DX11BackendClass::Bind_State_Objects()description.MaxLOD = D3D11_FLOAT32_MAX;Device->Get_Device()->CreateSamplerState(&description, &ShadowMapSampler);}- context->PSSetShaderResources(DX11_BACKEND_TEXTURE_STAGES + 1, 1, &ShadowMapTexture);+ // The smoke's map beside it at t6 and s6, or nothing on a frame without smoke, which the+ // program never reads: its strength is zero then.+ ID3D11ShaderResourceView * const maps[2] = { ShadowMapTexture, Smoke_Map() };+ context->PSSetShaderResources(DX11_BACKEND_TEXTURE_STAGES + 1, 2, maps);if (ShadowMapSampler != NULL) {- context->PSSetSamplers(DX11_BACKEND_TEXTURE_STAGES + 1, 1, &ShadowMapSampler);+ ID3D11SamplerState * const samplers_of_maps[2] = { ShadowMapSampler, SmokeMapSampler };+ context->PSSetSamplers(DX11_BACKEND_TEXTURE_STAGES + 1, (SmokeMapSampler != NULL) ? 2 : 1,+ samplers_of_maps);}}}diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.hindex bbd35fa4a..71199a361 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h@@ -185,6 +185,16 @@ public:bool Shadow_Map_Bound() const { return ShadowMapBound; }ID3D11ShaderResourceView * Shadow_Map() const { return ShadowMapTexture; }+ // The smoke's own map over the same sun, filled once a frame after End_Shadow_Map from the sun+ // it held. A caster is five floats: its centre in world units, its radius and the optical+ // depth through its middle. Strength is how dark the thickest smoke leaves what is behind it;+ // zero casters or zero strength is a frame with no smoke in the light, and so is a frame that+ // never calls this. False when the device cannot hold the map at all (no blendable, filterable+ // four channel 32-bit float target), which the caller reads as the smoke not being in the sun's+ // light and keeps its older shade. ffshader.h, VOLUMETRIC_SAMPLING, says what the map holds.+ bool Fill_Smoke_Map(const float * casters, unsigned count, float strength);+ ID3D11ShaderResourceView * Smoke_Map() const { return SmokeMapFilled ? SmokeMapTexture : NULL; }+// What is in the map, read back through a staging copy: how much of it was drawn into and how// near the nearest thing is. A caster pass that drew nothing leaves a map that is all one// value, and no draw count tells that apart from a pass that drew the world.@@ -311,6 +321,9 @@ private:// share of the zenith colour in its own.float Sky[4];float SkyUp[4];+ // The smoke in the sun's light (VOLUMETRIC_SAMPLING): how dark the thickest smoke leaves+ // what is behind it, zero on a frame without; and in z, one for a draw in camera space.+ float VolumeParameters[4];};// A model under directional lights, drawn by generated programs.bool Normal_Mapped() const;@@ -400,6 +413,34 @@ private:float ShadowFromClipProjection[16];bool ShadowFromClipValid;+ // The sorted particles are written in camera space and drawn with an identity world and view+ // (PointGroupClass::Insert_Sorted_Billboards), so the view the backend holds for them says+ // nothing about where they are, and a shadow looked up through it lands somewhere else in the+ // world. This is the last view a perspective draw held that was not the identity, which is the+ // scene camera's: the matrix a camera space draw's pixels go back to the world through.+ float SceneView[16];+ bool Camera_Space_Draw() const;++ // The smoke's map (Fill_Smoke_Map), the program that splats the casters into it and what it+ // draws with. Made on the first fill and kept; refused for good if the device cannot.+ ID3D11Texture2D * SmokeMapSurface;+ ID3D11RenderTargetView * SmokeMapTarget;+ ID3D11ShaderResourceView * SmokeMapTexture;+ ID3D11SamplerState * SmokeMapSampler;+ ID3D11VertexShader * SmokeSplatVertexShader;+ ID3D11PixelShader * SmokeSplatPixelShader;+ ID3D11InputLayout * SmokeSplatLayout;+ ID3D11BlendState * SmokeSplatBlend;+ ID3D11RasterizerState * SmokeSplatRasterizer;+ ID3D11Buffer * SmokeSplatInstances;+ unsigned SmokeSplatCapacity;+ std::vector<float> SmokeSplats;+ bool SmokeMapRefused;+ bool SmokeMapFilled;+ float SmokeStrength;+ bool Make_Smoke_Map();+ void Release_Smoke_Map();+float MaterialAmbient[4];float MaterialDiffuse[4];float MaterialSpecular[4];diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cppindex 6ce596fa5..9121acdf8 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp@@ -322,6 +322,11 @@ void Direct3D11_Set_Shadow_Parameters(float bias, float strength, float widest_r}}+bool Direct3D11_Fill_Smoke_Map(const float * casters, unsigned count, float strength)+{+ return Active ? Backend.Fill_Smoke_Map(casters, count, strength) : false;+}+void Direct3D11_Clear_Shadow_Parameters(){if (Active) {diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.hindex 8523a5c14..557b72880 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h@@ -140,6 +140,13 @@ void Direct3D11_Set_Shadow_Parameters(float bias, float strength, float widest_rfloat sky_fill);void Direct3D11_Clear_Shadow_Parameters();+// The smoke in the sun's light, after Direct3D11_End_Shadow_Map and from the sun it drew with: five+// floats a caster (world x, y, z, radius, optical depth through its middle) and how dark the+// thickest smoke leaves what is behind it. Called every frame the map is drawn; no casters is a+// frame without smoke. False when there is no backend or the device cannot hold the map, and the+// caller keeps its older shade under the clouds.+bool Direct3D11_Fill_Smoke_Map(const float * casters, unsigned count, float strength);+// The CPU has just written this surface. The next bind of its texture fills the Direct3D 11 copy// again. A no-op when the backend is not running.void Direct3D11_Mark_Surface_Dirty(struct IDirect3DSurface9 * surface);diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime_posix.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime_posix.cppindex 0332e3b6d..291503e54 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime_posix.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime_posix.cpp@@ -71,6 +71,7 @@ bool Direct3D11_Shadow_Map_Bound() { return false; }std::string Direct3D11_Shadow_Map_Report() { return std::string("no Direct3D 11 backend"); }void Direct3D11_Set_Shadow_Parameters(float, float, float, float, float, float, float) {}void Direct3D11_Clear_Shadow_Parameters() {}+bool Direct3D11_Fill_Smoke_Map(const float *, unsigned, float) { return false; }void Direct3D11_Mark_Surface_Dirty(struct IDirect3DSurface9 *) {}void Direct3D11_Mirror_Render_Target(struct IDirect3DSurface9 *) {}diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.cppindex 6aa2b3c83..1c70c3a98 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.cpp@@ -229,7 +229,7 @@ static const char * const TERRAIN_BUMP_FUNCTION ="}\n""\n";-static void write_pixel_preamble(std::string & hlsl, bool bumped = false)+static void write_pixel_preamble(std::string & hlsl, bool bumped = false, bool volumetric = false){for (unsigned stage = 0; stage < MAXIMUM_COMBINER_STAGES; ++stage) {char line[128];@@ -267,11 +267,18 @@ static void write_pixel_preamble(std::string & hlsl, bool bumped = false)" float4 ShadowSoftness;\n"" float4 Sky;\n"" float4 SkyUp;\n";+ // The smoke's field follows them, on the Direct3D 11 text alone (VOLUMETRIC_SAMPLING).+ if (volumetric) {+ hlsl += VOLUMETRIC_CONSTANTS;+ }hlsl += "};\n";if (bumped) {hlsl += "Texture2D NormalMap : register(t4);\n";}hlsl += SHADOW_SAMPLING;+ if (volumetric) {+ hlsl += VOLUMETRIC_SAMPLING;+ }hlsl +="\n""struct Input\n"@@ -418,9 +425,9 @@ static void write_monochrome(std::string & hlsl)// matters is the one at the top, and it applies at every step, not only the last: a chain that// overflows in the middle and comes back down is a different colour with the clamps than without them.static void write_multiply_chain(std::string & hlsl, const EngineShaderEntry & entry,- bool bumped)+ bool bumped, bool volumetric){- write_pixel_preamble(hlsl, bumped);+ write_pixel_preamble(hlsl, bumped, volumetric);hlsl += " float4 current = saturate(";hlsl += entry.Opening;@@ -433,7 +440,7 @@ static void write_multiply_chain(std::string & hlsl, const EngineShaderEntry & e}// The ground is where a shadow is read, so every transcribed program that paints it takes one.- hlsl += SHADOW_APPLY;+ hlsl += volumetric ? VOLUMETRIC_SHADOW_APPLY : SHADOW_APPLY;if (!bumped) {return;@@ -532,20 +539,29 @@ bool EngineShader_Vertex_Program(EngineShaderProgram program, std::string & hlsl}}+static bool write_engine_pixel_program(EngineShaderProgram program,+ const PixelPipelineDescription & pipeline, std::string & hlsl, bool bumped, bool volumetric);+bool EngineShader_Pixel_Program(EngineShaderProgram program,const PixelPipelineDescription & pipeline, std::string & hlsl, bool bumped,CombinerShaderTarget target){- // As the vertex half: D3D11 only, and SDL3 GPU as the D3D11 text rebound.+ // As the vertex half: D3D11 only, and SDL3 GPU as the D3D11 text rebound, without the smoke the+ // SDL3 backend has no map for.if (target == COMBINER_SHADER_TARGET_D3D9) {hlsl.clear();return false;}if (target == COMBINER_SHADER_TARGET_SDL3_GPU) {- return EngineShader_Pixel_Program(program, pipeline, hlsl, bumped, COMBINER_SHADER_TARGET_D3D11)+ return write_engine_pixel_program(program, pipeline, hlsl, bumped, false)&& SDL3_Shader_Retarget(hlsl, false);}+ return write_engine_pixel_program(program, pipeline, hlsl, bumped, true);+}+static bool write_engine_pixel_program(EngineShaderProgram program,+ const PixelPipelineDescription & pipeline, std::string & hlsl, bool bumped, bool volumetric)+{hlsl.clear();if (bumped && !EngineShader_Can_Bump(program)) {return false;@@ -553,7 +569,7 @@ bool EngineShader_Pixel_Program(EngineShaderProgram program,const EngineShaderEntry * entry = entry_for(program);if (entry != NULL && entry->Opening != NULL) {- write_multiply_chain(hlsl, *entry, bumped);+ write_multiply_chain(hlsl, *entry, bumped, volumetric);}else if (program == ENGINE_SHADER_WATER_TRAPEZOID) {write_trapezoid_water(hlsl);diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.cppindex 28e298ed2..af6055488 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.cpp@@ -284,15 +284,26 @@ static void append_normal_mapped_lighting(std::string & hlsl, unsigned coordinathlsl += line;}+static bool generate_combiners(const CombinerDescription & description,+ CombinerShaderTarget target, std::string & hlsl, bool volumetric);+bool CombinerShader_Generate(const CombinerDescription & description, CombinerShaderTarget target,std::string & hlsl){// The SDL3 GPU program is the D3D11 one with its bindings rewritten, so everything below only- // ever sees the two profiles it was written for.+ // ever sees the two profiles it was written for. It goes without the smoke: its backend binds+ // nothing at t6 and uploads no field past SkyUp (SdlEnginePixelConstants).if (target == COMBINER_SHADER_TARGET_SDL3_GPU) {- return CombinerShader_Generate(description, COMBINER_SHADER_TARGET_D3D11, hlsl)+ return generate_combiners(description, COMBINER_SHADER_TARGET_D3D11, hlsl, false)&& SDL3_Shader_Retarget(hlsl, false);}+ return generate_combiners(description, target, hlsl, target == COMBINER_SHADER_TARGET_D3D11);+}++static bool generate_combiners(const CombinerDescription & description,+ CombinerShaderTarget target, std::string & hlsl, bool volumetric)+{+ volumetric = volumetric && description.ShadowReceiving;if (description.StageCount == 0 || description.StageCount > MAXIMUM_COMBINER_STAGES) {return false;}@@ -423,6 +434,9 @@ bool CombinerShader_Generate(const CombinerDescription & description, CombinerSh" float4 Sky;\n"" float4 SkyUp;\n";}+ if (volumetric) {+ hlsl += VOLUMETRIC_CONSTANTS;+ }hlsl += "};\n";if (description.NormalMapped) {hlsl += "Texture2D NormalMap : register(t4);\n";@@ -430,6 +444,9 @@ bool CombinerShader_Generate(const CombinerDescription & description, CombinerShif (description.ShadowReceiving) {hlsl += SHADOW_SAMPLING;}+ if (volumetric) {+ hlsl += VOLUMETRIC_SAMPLING;+ }}else {for (unsigned stage = 0; stage < MAXIMUM_COMBINER_STAGES; ++stage) {@@ -494,7 +511,7 @@ bool CombinerShader_Generate(const CombinerDescription & description, CombinerSh// Before the fog: a shadow is a thing in the world and the fog is between the world and the eye.if (description.ShadowReceiving) {- hlsl += SHADOW_APPLY;+ hlsl += volumetric ? VOLUMETRIC_SHADOW_APPLY : SHADOW_APPLY;}if (target == COMBINER_SHADER_TARGET_D3D11diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.hindex 3c92e2ec9..1be1f7f70 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.h+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.h@@ -204,10 +204,90 @@ const unsigned NORMAL_MAPPED_LIGHTS = 4;// gentler one took a good share of the shadow off every building while the ground beside it took// all of it, which reads as the two being lit by different suns. Full shadow from about a sixth// of white upward; only what is darker than that is protected.-#define SHADOW_APPLY \- " float shadow_lit = saturate(dot(current.rgb, float3(0.3333, 0.3333, 0.3333)) * 6.0);\n" \+#define SHADOW_LIT \+ " float shadow_lit = saturate(dot(current.rgb, float3(0.3333, 0.3333, 0.3333)) * 6.0);\n"+#define SHADOW_APPLY SHADOW_LIT \" current.rgb *= lerp(1.0, sun_reaching(input.Position), shadow_lit);\n"+// The smoke in the sun's light, for the Direct3D 11 programs only: written after SHADOW_SAMPLING,+// whose map and matrix it reads, and kept out of the SDL3 GPU text, which declares neither the+// field it adds to the constant block nor a texture at t6.+//+// The smoke has a map of its own over the same sun (DX11BackendClass::Fill_Smoke_Map). Each texel+// holds three sums over the particles the sun sees through it: their optical depth, that times+// their depth, and that times their depth squared plus their own thickness squared. Taken+// together that is the smoke along the ray as one bell curve, with an amount, a centre and a+// width, and how much of it lies between the sun and a pixel is the curve's integral up to the+// pixel's depth. A pixel under a plume gets all of it, a particle on the plume's near side gets+// a little and one on its far side most, which is the self-shading. Bilinear filtering is right+// for this map where it is wrong for a depth map: the sums of a mixture are the mixture of the+// sums.+//+// VolumeParameters.x is how dark a pixel behind the thickest smoke goes, zero on a frame with no+// smoke in the map. .z is one for a draw whose vertices are in camera space already, which is the+// particles: they take the sun's map through four wide taps, because a smoke sprite drawn twenty+// deep would otherwise pay the fifty taps the ground pays, twenty times over.+#define VOLUMETRIC_SAMPLING \+ "Texture2D SmokeMap : register(t6);\n" \+ "SamplerState SmokeSampler : register(s6);\n" \+ "\n" \+ "bool sun_point(float4 position, out float3 sun)\n" \+ "{\n" \+ " float2 ndc = float2(position.x * ShadowViewport.x * 2.0 - 1.0,\n" \+ " 1.0 - position.y * ShadowViewport.y * 2.0);\n" \+ " float4 at = mul(float4(ndc, position.z, 1.0), ShadowFromClip);\n" \+ " sun = float3(0.0, 0.0, 0.0);\n" \+ " if (at.w <= 0.0) return false;\n" \+ " at /= at.w;\n" \+ " sun = float3(0.5 * at.x + 0.5, 0.5 - 0.5 * at.y, at.z);\n" \+ " return sun.x >= 0.0 && sun.x <= 1.0 && sun.y >= 0.0 && sun.y <= 1.0;\n" \+ "}\n" \+ "\n" \+ "float smoke_reaching(float4 position)\n" \+ "{\n" \+ " float3 sun;\n" \+ " if (VolumeParameters.x <= 0.0 || !sun_point(position, sun)) return 1.0;\n" \+ " float4 sums = SmokeMap.SampleLevel(SmokeSampler, sun.xy, 0);\n" \+ " if (sums.x < 0.001) return 1.0;\n" \+ " float centre = sums.y / sums.x;\n" \+ " float width = sqrt(max(sums.z / sums.x - centre * centre, 1e-10));\n" \+ " // the bell curve's integral up to here, the logistic stand-in for the normal distribution\n" \+ " float ahead = 1.0 / (1.0 + exp(-1.702 * (sun.z - centre) / width));\n" \+ " return 1.0 - VolumeParameters.x * (1.0 - exp(-sums.x * ahead));\n" \+ "}\n" \+ "\n" \+ "float sun_reaching_coarse(float4 position)\n" \+ "{\n" \+ " float3 sun;\n" \+ " if (ShadowParameters.z <= 0.0 || !sun_point(position, sun)) return 1.0;\n" \+ " if (sun.z < 0.0 || sun.z > 1.0) return 1.0;\n" \+ " float reach = ShadowParameters.x * ShadowParameters.w * 0.5;\n" \+ " float bias = ShadowParameters.y * 2.0;\n" \+ " float blocked = 0.0;\n" \+ " blocked += (ShadowMap.SampleLevel(ShadowSampler, sun.xy + float2(-reach, -reach), 0).r + bias < sun.z) ? 1.0 : 0.0;\n" \+ " blocked += (ShadowMap.SampleLevel(ShadowSampler, sun.xy + float2( reach, -reach), 0).r + bias < sun.z) ? 1.0 : 0.0;\n" \+ " blocked += (ShadowMap.SampleLevel(ShadowSampler, sun.xy + float2(-reach, reach), 0).r + bias < sun.z) ? 1.0 : 0.0;\n" \+ " blocked += (ShadowMap.SampleLevel(ShadowSampler, sun.xy + float2( reach, reach), 0).r + bias < sun.z) ? 1.0 : 0.0;\n" \+ " return 1.0 - ShadowParameters.z * (1.0 - ShadowSoftness.w) * (blocked * 0.25);\n" \+ "}\n" \+ "\n" \+ "float light_reaching(float4 position)\n" \+ "{\n" \+ " float sun = 1.0;\n" \+ " if (VolumeParameters.z > 0.5) sun = sun_reaching_coarse(position);\n" \+ " else sun = sun_reaching(position);\n" \+ " return sun * smoke_reaching(position);\n" \+ "}\n" \+ "\n"++// The constant block's field for it, declared after SkyUp: DX11BackendClass::PixelConstantBlock.+#define VOLUMETRIC_CONSTANTS \+ " float4 VolumeParameters;\n"++// SHADOW_APPLY with the smoke in it.+#define VOLUMETRIC_SHADOW_APPLY SHADOW_LIT \+ " current.rgb *= lerp(1.0, light_reaching(input.Position), shadow_lit);\n"+// The HLSL for one description, or false when the description names an operation or an argument// this does not generate. A refusal is not a failure: the caller keeps the fixed-function path for// that draw, which is the only reason an unmeasured operation is safe to meet at run time.diff --git a/GeneralsMD/Code/Tests/test_dx11backend.cpp b/GeneralsMD/Code/Tests/test_dx11backend.cppindex fe8e9bc25..5bba55b73 100644--- a/GeneralsMD/Code/Tests/test_dx11backend.cpp+++ b/GeneralsMD/Code/Tests/test_dx11backend.cpp@@ -673,3 +673,79 @@ TEST(dx11backend_a_draw_with_nothing_bound_is_counted_as_refused)backend.Shutdown();}++// The smoke's map holds three sums under each caster: its optical depth, that times its depth in the+// sun's clip space, and that times the depth squared plus its own spread squared. The receivers+// rebuild the cloud along the ray out of exactly those, so a sum in the wrong channel, a depth+// through the wrong column of the sun's matrix or a disc off its centre is a shadow somewhere else.+//+// The sun here sees a hundred world units either side of the middle and puts depth z at+// z / 1000 + 0.5. One caster at height 100, radius 50, optical depth 2 lands in the middle texel+// with depth 0.6 and a spread of half its radius, 0.025. One outside the box draws nothing.+TEST(dx11backend_the_smoke_map_holds_each_casters_three_sums)+{+ DX11DeviceClass device;+ CHECK(device.Create_Offscreen());+ ID3D11Device * d3d = device.Get_Device();++ DX11BackendClass backend;+ CHECK(backend.Initialise(&device));++ float identity[16];+ set_identity(identity);+ float sun[16];+ set_identity(sun);+ sun[0] = 0.01f;+ sun[5] = 0.01f;+ sun[10] = 0.001f;+ sun[14] = 0.5f;+ backend.Set_Transform(D3DTS_VIEW, identity);+ backend.Set_Transform(D3DTS_PROJECTION, sun);+ CHECK(backend.Begin_Shadow_Map(64));+ backend.End_Shadow_Map();++ const float outside[5] = { 500.0f, 0.0f, 100.0f, 50.0f, 2.0f };+ CHECK(backend.Fill_Smoke_Map(outside, 1, 0.5f));+ CHECK(backend.Smoke_Map() == NULL);++ const float caster[5] = { 0.0f, 0.0f, 100.0f, 50.0f, 2.0f };+ CHECK(backend.Fill_Smoke_Map(caster, 1, 0.5f));+ ID3D11ShaderResourceView * map = backend.Smoke_Map();+ CHECK(map != NULL);+ if (map == NULL) {+ backend.Shutdown();+ return;+ }++ ID3D11Resource * resource = NULL;+ map->GetResource(&resource);+ ID3D11Texture2D * texture = static_cast<ID3D11Texture2D *>(resource);+ D3D11_TEXTURE2D_DESC description;+ texture->GetDesc(&description);+ description.Usage = D3D11_USAGE_STAGING;+ description.BindFlags = 0;+ description.CPUAccessFlags = D3D11_CPU_ACCESS_READ;+ ID3D11Texture2D * staging = NULL;+ CHECK(SUCCEEDED(d3d->CreateTexture2D(&description, NULL, &staging)));+ device.Get_Context()->CopyResource(staging, texture);++ D3D11_MAPPED_SUBRESOURCE mapped;+ CHECK(SUCCEEDED(device.Get_Context()->Map(staging, 0, D3D11_MAP_READ, 0, &mapped)));+ const float * middle = reinterpret_cast<const float *>(static_cast<const unsigned char *>(mapped.pData)+ + mapped.RowPitch * (description.Height / 2)) + (description.Width / 2) * 4;+ const float * corner = static_cast<const float *>(mapped.pData);+ printf(" middle texel %.5f %.5f %.5f %.5f\n", middle[0], middle[1], middle[2], middle[3]);+ CHECK_NEAR(middle[0], 2.0f, 0.05f);+ CHECK_NEAR(middle[1] / middle[0], 0.6f, 0.0001f);+ CHECK_NEAR(middle[2] / middle[0], 0.6f * 0.6f + 0.025f * 0.025f, 0.0001f);+ CHECK_EQ(corner[0], 0.0f);+ device.Get_Context()->Unmap(staging, 0);++ // Nothing handed over is a frame without smoke: the receivers stop reading the map.+ CHECK(backend.Fill_Smoke_Map(NULL, 0, 0.5f));+ CHECK(backend.Smoke_Map() == NULL);++ staging->Release();+ resource->Release();+ backend.Shutdown();+}diff --git a/GeneralsMD/Code/Tests/test_ffshadercompile.cpp b/GeneralsMD/Code/Tests/test_ffshadercompile.cppindex a9966e0fc..8c198ee08 100644--- a/GeneralsMD/Code/Tests/test_ffshadercompile.cpp+++ b/GeneralsMD/Code/Tests/test_ffshadercompile.cpp@@ -205,3 +205,35 @@ TEST(ffshadercompile_the_tree_shadow_program_compiles)CHECK(compiles(compile, hlsl, D3D9_PROFILE));CHECK(compiles(compile, eleven, D3D11_PROFILE));}++// A program that takes the sun's shadow takes the smoke's with it on Direct3D 11: the smoke's map at+// t6 and the field after SkyUp. The SDL3 GPU text is made from the same generator and must stay+// without both, because that backend binds no map there and uploads no such field.+TEST(ffshadercompile_a_shadow_receiving_program_reads_the_smoke_on_d3d11_only)+{+ CombinerDescription description;+ memset(&description, 0, sizeof(description));+ description.StageCount = 1;+ description.Stages[0] = one_stage(D3DTOP_MODULATE, D3DTA_TEXTURE, D3DTA_DIFFUSE,+ D3DTOP_MODULATE, D3DTA_TEXTURE, D3DTA_DIFFUSE, 0, true);+ description.ShadowReceiving = true;+ description.PixelPipeline.FogEnabled = true;++ std::string eleven;+ CHECK(CombinerShader_Generate(description, COMBINER_SHADER_TARGET_D3D11, eleven));+ CHECK(eleven.find("register(t6)") != std::string::npos);+ CHECK(eleven.find("VolumeParameters") > eleven.find("SkyUp"));+ CHECK(eleven.find("light_reaching(input.Position)") != std::string::npos);++ std::string sdl;+ CHECK(CombinerShader_Generate(description, COMBINER_SHADER_TARGET_SDL3_GPU, sdl));+ CHECK(sdl.find("SmokeMap") == std::string::npos);+ CHECK(sdl.find("VolumeParameters") == std::string::npos);++ D3DCompileFunction compile = load_compiler();+ if (compile == NULL) {+ printf(" d3dcompiler_47.dll not present, skipping the compile\n");+ return;+ }+ CHECK(compiles(compile, eleven, D3D11_PROFILE));+}