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.

refactor(clouds): gate the clouds on a renderer capability, not linux

Richard Louie Orillac38fad1e17e6
diff --git a/GeneralsMD/Code/BuildFingerprint.manifest b/GeneralsMD/Code/BuildFingerprint.manifest
index 35e4ae496..286219364 100644
--- a/GeneralsMD/Code/BuildFingerprint.manifest
+++ b/GeneralsMD/Code/BuildFingerprint.manifest
@@ -1819,7 +1819,6 @@ GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrameBatch.cpp
GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloud.cpp
GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudEmbers.cpp
GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudEmbers.h
-GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudFlow.cpp
GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudShader.cpp
GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudShader.h
GameEngineDevice/Source/PosixDevice/Render/SdlPipelineCache.cpp
@@ -1882,6 +1881,9 @@ GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DVerticalSlider.cpp
GameEngineDevice/Source/W3DDevice/GameClient/GUI/W3DGameFont.cpp
GameEngineDevice/Source/W3DDevice/GameClient/GUI/W3DGameWindow.cpp
GameEngineDevice/Source/W3DDevice/GameClient/GUI/W3DGameWindowManager.cpp
+GameEngineDevice/Source/W3DDevice/GameClient/HazardCloud.cpp
+GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudFlow.cpp
+GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudUnsupported.cpp
GameEngineDevice/Source/W3DDevice/GameClient/HeightMap.cpp
GameEngineDevice/Source/W3DDevice/GameClient/Shaders/MotionBlur.nvv
GameEngineDevice/Source/W3DDevice/GameClient/Shaders/Trees.nvp
@@ -1970,6 +1972,8 @@ Libraries/Include/Platform/D3D9Posix.h
Libraries/Include/Platform/D3D9PosixMath.h
Libraries/Include/Platform/DoubleClickTime.h
Libraries/Include/Platform/EngineShaderName.h
+Libraries/Include/Platform/HazardCloud.h
+Libraries/Include/Platform/HazardCloudFlow.h
Libraries/Include/Platform/HazardCloudPolicy.h
Libraries/Include/Platform/IsWindows9x.h
Libraries/Include/Platform/LoadTiming.h
@@ -1981,7 +1985,6 @@ Libraries/Include/Platform/PosixD3D9/d3d9types.h
Libraries/Include/Platform/RenderTypes.h
Libraries/Include/Platform/RendererName.h
Libraries/Include/Platform/SdlHazardCloud.h
-Libraries/Include/Platform/SdlHazardCloudFlow.h
Libraries/Include/Platform/SleepMilliseconds.h
Libraries/Include/Platform/StrdupAsWindows.h
Libraries/Include/rts/debug.h
diff --git a/GeneralsMD/Code/CMakeLists.txt b/GeneralsMD/Code/CMakeLists.txt
index 5834b2fe4..080e02f7c 100644
--- a/GeneralsMD/Code/CMakeLists.txt
+++ b/GeneralsMD/Code/CMakeLists.txt
@@ -1502,6 +1502,9 @@ if(ZH_PLATFORM_POSIX)
# W3DWebBrowser is the embedded browser as a COM object, which only Win32GameEngine makes; GameEngine
# has its own WebBrowser off Windows (B5).
list(FILTER W3DDEVICE_SOURCES EXCLUDE REGEX "/W3DDevice/GameClient/W3DWebBrowser\\.cpp$")
+ # The neutral cloud core is in W3DDevice on every platform. SDL supplies the
+ # POSIX factory below; the no-backend factory is compiled only without it.
+ list(FILTER W3DDEVICE_SOURCES EXCLUDE REGEX "/HazardCloudUnsupported\\.cpp$")
# ---- the movies (V1): Windows' Bink player and its Bink API on FFmpeg, the same two files -------------
# FFmpeg is built from the tarball Tools/vendor.sh keeps, into the build tree, with the Bink demuxer
@@ -1566,13 +1569,12 @@ if(ZH_PLATFORM_POSIX)
list(APPEND W3DDEVICE_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/GameEngineDevice/Source/VideoDevice/Bink/BinkVideoPlayer.cpp)
add_library(w3ddevice STATIC ${W3DDEVICE_SOURCES})
set(ZH_POSIX_RENDER_DIR ${CMAKE_CURRENT_SOURCE_DIR}/GameEngineDevice/Source/PosixDevice/Render)
- if(ZH_PLATFORM_LINUX)
- target_sources(w3ddevice PRIVATE
- ${ZH_POSIX_RENDER_DIR}/SdlHazardCloud.cpp
- ${ZH_POSIX_RENDER_DIR}/SdlHazardCloudShader.cpp
- ${ZH_POSIX_RENDER_DIR}/SdlHazardCloudFlow.cpp
- ${ZH_POSIX_RENDER_DIR}/SdlHazardCloudEmbers.cpp)
- endif()
+ # This entire device branch is ZH_PLATFORM_POSIX: Linux and macOS share
+ # the SDL GPU cloud backend and its runtime capability query.
+ target_sources(w3ddevice PRIVATE
+ ${ZH_POSIX_RENDER_DIR}/SdlHazardCloud.cpp
+ ${ZH_POSIX_RENDER_DIR}/SdlHazardCloudShader.cpp
+ ${ZH_POSIX_RENDER_DIR}/SdlHazardCloudEmbers.cpp)
set_target_properties(w3ddevice PROPERTIES CXX_STANDARD 17)
target_include_directories(w3ddevice PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/GameEngineDevice/Include
PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/Stubs ${CMAKE_CURRENT_SOURCE_DIR}/Main
@@ -2148,6 +2150,12 @@ target_include_directories(test_msvc_float_casts PRIVATE ${CMAKE_CURRENT_SOURCE_
add_lib_test(test_hazard_cloud_policy)
set_target_properties(test_hazard_cloud_policy PROPERTIES CXX_STANDARD 17)
target_include_directories(test_hazard_cloud_policy PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/Libraries/Include)
+# Exercise the neutral core and no-backend contract without SDL or a graphics
+# device, on every platform (including builds that use the SDL backend in game).
+target_sources(test_hazard_cloud_policy PRIVATE
+ ${CMAKE_CURRENT_SOURCE_DIR}/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloud.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudFlow.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudUnsupported.cpp)
add_lib_test(test_wwmath wwmath wwlib wwsaveload wwdebug)
target_include_directories(test_wwmath PRIVATE ${WW}/WWLib ${WW}/WWSaveLoad ${WW}/Wwutil)
@@ -2330,6 +2338,13 @@ endif()
# does not link (B6).
if(ZH_PLATFORM_POSIX)
target_link_libraries(test_gameengine PRIVATE posixdevice w3ddevice)
+else()
+ # FunctionLexicon pulls in OptionsMenu, which queries the cloud capability.
+ # These tests omit gameenginedevice, so use its real no-backend entry points.
+ foreach(name test_gameengine test_terrain_golden test_water_grid test_rank_ladder)
+ target_sources(${name} PRIVATE
+ ${CMAKE_CURRENT_SOURCE_DIR}/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudUnsupported.cpp)
+ endforeach()
endif()
# the well-known Dict keys and a handful of device/exe entry points live in
# GameEngineDevice, which Phase 4 ports; stand-ins until then.
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp
index 971da71e2..46e1c941a 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp
@@ -73,6 +73,7 @@
#include "GameLogic/GameLogic.h"
#include "GameLogic/ScriptEngine.h"
#include "WWDownload/Registry.h"
+#include "Platform/HazardCloud.h"
//added by saad
//used to access a messagebox that does "ok" and "cancel"
#include "GameClient/MessageBox.h"
@@ -1129,16 +1130,17 @@ static void fillCatalogWidgets( void )
if( widget == NULL )
continue;
-#if !defined(__linux__)
if (strcmp(def.iniKey, "CloudStyle") == 0)
{
- widget->winHide(TRUE);
+ // The display is initialized before the shell. Query when the menu
+ // opens so a reused layout also reflects the current device.
+ const Bool supported = HazardCloud::Supported();
+ widget->winHide(!supported);
GameWindow *label = TheWindowManager->winGetWindowFromId(
NULL, NAMEKEY("OptionsMenu.wnd:LabelCloudStyle"));
- if (label) label->winHide(TRUE);
- continue;
+ if (label) label->winHide(!supported);
+ if (!supported) continue;
}
-#endif
const Int value = clampOptionValue( def, def.get() );
@@ -1185,6 +1187,10 @@ static void readCatalogWidgets( OptionPreferences &out )
if( widget == NULL )
continue;
+ // A hidden, unfilled combo must not overwrite the player's opt-in.
+ if (strcmp(def.iniKey, "CloudStyle") == 0 && !HazardCloud::Supported())
+ continue;
+
Int value;
switch( def.kind )
{
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrame.cpp b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrame.cpp
index a68801e53..68d49ec69 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrame.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrame.cpp
@@ -183,7 +183,6 @@ SdlGpuFrame * SdlGpuFrame::Create(RenderWindow window, unsigned int width, unsig
frame->DepthFormat = SDL_GPUTextureSupportsFormat(frame->GpuDevice, SDL_GPU_TEXTUREFORMAT_D24_UNORM_S8_UINT,
SDL_GPU_TEXTURETYPE_2D, SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET)
? SDL_GPU_TEXTUREFORMAT_D24_UNORM_S8_UINT : SDL_GPU_TEXTUREFORMAT_D32_FLOAT_S8_UINT;
-#if defined(__linux__)
// Cloud clipping is optional: retain the original target-only depth format
// when no complete sampleable depth/R32F combination is supported.
if (SDL_GPUTextureSupportsFormat(frame->GpuDevice, SDL_GPU_TEXTUREFORMAT_R32_FLOAT,
@@ -199,7 +198,6 @@ SdlGpuFrame * SdlGpuFrame::Create(RenderWindow window, unsigned int width, unsig
}
}
}
-#endif
if (!frame->Create_Targets(width, height)) {
error = std::string("the back buffer: ") + SDL_GetError();
delete frame;
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrame.h b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrame.h
index bd8407b35..16eb4392a 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrame.h
+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrame.h
@@ -158,8 +158,10 @@ public:
bool Batch_Is_Full();
/// The scene depth-stencil format; colour-only passes omit that attachment.
unsigned int Depth_Format() const { return DepthFormat; }
- /// Includes sampling only when a supported Linux scene-depth format is available.
+ /// Includes sampling only when a complete scene-depth/R32F format path is available.
unsigned int Depth_Usage() const;
+ /// Device capability selected at frame creation, including the R32F resolve target.
+ bool Supports_Scene_Depth() const { return DepthSampleable; }
/// Sampleable device depth captured after opaque scene draws, once per target/frame.
/// The result is borrowed for immediate draw recording; callers must not release it.
/// Returns null when unavailable so callers can keep their existing effect.
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloud.cpp b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloud.cpp
index 7565f9c15..6af5a7075 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloud.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloud.cpp
@@ -17,7 +17,6 @@
#include <cstdio>
#include <cstdlib>
#include <cstring>
-#include <limits>
#include <string>
#include <vector>
@@ -59,12 +58,6 @@ struct SharedResources {
SdlTarget heatBackground = {};
};
SharedResources shared;
-constexpr std::array<Palette, 4> approved = {{
- {{0.769999981f, 0.939999998f, 0.550000012f}, {0.125490203f, 0.31764707f, 0.0549019612f}, 0.699999988f, 0.670000017f},
- {{0.749019623f, 0.670588255f, 0.469999999f}, {0.298039228f, 0.184313729f, 0.0705882385f}, 1.29999995f, 0.0f},
- {{0.660000026f, 0.75999999f, 1.0f}, {0.0649999976f, 0.100000001f, 0.209999993f}, 1.52999997f, 0.769999981f},
- {{0.839999974f, 0.629999995f, 1.0f}, {0.192156866f, 0.0470588244f, 0.235294119f}, 1.32000005f, 0.74000001f},
-}};
unsigned cacheSide(const FieldState &field)
{
@@ -105,8 +98,6 @@ void releaseShared(bool deviceAlive)
}
} // namespace
-const Palette &defaultPalette(unsigned index) { return approved[index < 4 ? index : 0]; }
-
struct Layer::Impl {
FieldState fieldStates[2] = {};
unsigned fieldCount = 0;
@@ -123,8 +114,8 @@ struct Layer::Impl {
unsigned flowUploads = 0;
uint64_t flowUsedBatch = ~uint64_t(0);
std::vector<Body> bodies;
- SdlHazardCloudFlow::Flow flow;
- std::array<Palette, 4> palettes = approved;
+ HazardCloudFlow::Flow flow;
+ std::array<Palette, 4> palettes = {{defaultPalette(0), defaultPalette(1), defaultPalette(2), defaultPalette(3)}};
SdlGpuFrame *frame = nullptr;
SDL_GPUDevice *gpu = nullptr;
SDL_GPUTexture *flowTexture = nullptr;
@@ -946,6 +937,7 @@ void update(float timeSeconds)
bool initialize()
{
if (initialized) return !failed;
+ if (!HazardCloud::Supported()) return false;
failed = false;
PosixDevice9 *device = static_cast<PosixDevice9 *>(DX8Wrapper::_Get_D3D_Device());
if (!device || !(frame = device->Get_Gpu()) || !(gpu = frame->Device())) {
@@ -1071,20 +1063,6 @@ unsigned Layer::activeBodies() const { return impl->flow.activeBodies(); }
float Layer::maxDisturbance() const { return impl->flow.maxDisturbance(); }
unsigned Layer::interactionUploads() const { return impl->flowUploads; }
unsigned Layer::renderedFrames() const { return impl->renderedFrames; }
-std::uint64_t Layer::estimateCacheBytes(const FieldState *fields, unsigned count)
-{
- if (count > 2 || (count && !fields)) return std::numeric_limits<std::uint64_t>::max();
- std::uint64_t result = (192u * 96u * 4u + TerrainGridSide * TerrainGridSide * 2u) * sizeof(float);
- for (unsigned i = 0; i < count; ++i) {
- if (!std::isfinite(fields[i].radius) || !std::isfinite(fields[i].fringe)
- || fields[i].radius < 0 || fields[i].fringe < 0)
- return std::numeric_limits<std::uint64_t>::max();
- if (fields[i].radius <= 0.001f || fields[i].height <= 0.002f || fields[i].density <= 0.00001f) continue;
- const std::uint64_t side = cacheSide(fields[i]);
- result += side * side * CacheSlices * 10u; // R16F density + RGBA16F light.
- }
- return result;
-}
std::uint64_t Layer::estimatedCacheBytes() const
{
std::uint64_t result = impl->flowTexture ? 192u * 96u * 4u * sizeof(float) : 0;
@@ -1096,3 +1074,27 @@ std::uint64_t Layer::estimatedCacheBytes() const
void Layer::shutdown() { impl->shutdown(); }
} // namespace SdlHazardCloud
+
+namespace HazardCloud {
+
+bool Supported()
+{
+ PosixDevice9 *device = dynamic_cast<PosixDevice9 *>(DX8Wrapper::_Get_D3D_Device());
+ SdlGpuFrame *frame = device ? device->Get_Gpu() : nullptr;
+ if (!frame || !frame->Device() || !frame->Supports_Scene_Depth()) return false;
+ const SDL_GPUTextureUsageFlags usage = SDL_GPU_TEXTUREUSAGE_COLOR_TARGET | SDL_GPU_TEXTUREUSAGE_SAMPLER;
+ return SDL_GPUTextureSupportsFormat(frame->Device(), SDL_GPU_TEXTUREFORMAT_R16G16B16A16_FLOAT,
+ SDL_GPU_TEXTURETYPE_2D, usage)
+ && SDL_GPUTextureSupportsFormat(frame->Device(), SDL_GPU_TEXTUREFORMAT_R16_FLOAT,
+ SDL_GPU_TEXTURETYPE_2D, usage)
+ && SDL_GPUTextureSupportsFormat(frame->Device(), SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT,
+ SDL_GPU_TEXTURETYPE_2D, SDL_GPU_TEXTUREUSAGE_SAMPLER);
+}
+
+std::unique_ptr<Layer> CreateLayer()
+{
+ if (!Supported()) return nullptr;
+ return std::make_unique<SdlHazardCloud::Layer>();
+}
+
+} // namespace HazardCloud
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudEmbers.cpp b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudEmbers.cpp
index 662650853..5aa275f24 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudEmbers.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudEmbers.cpp
@@ -2,7 +2,7 @@
// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.
#include "PreRTS.h"
#include "SdlHazardCloudEmbers.h"
-#include "Platform/SdlHazardCloud.h"
+#include "Platform/HazardCloud.h"
#include "WW3D2/sdl3shadercompile.h"
#include "SdlGpuFrame.h"
@@ -223,7 +223,7 @@ bool makeResources(SdlGpuFrame *frame, const SdlTarget &target)
} // namespace
bool prepare(SdlGpuFrame *frame, const SdlTarget &target,
- const SdlHazardCloud::FieldState *fields, unsigned fieldCount)
+ const HazardCloud::FieldState *fields, unsigned fieldCount)
{
if (failed || !frame || !frame->Device() || !target.Colour || !target.Depth
|| fieldCount > 2 || (fieldCount && !fields)) return false;
@@ -239,7 +239,7 @@ bool prepare(SdlGpuFrame *frame, const SdlTarget &target,
bool render(SdlGpuFrame *frame, const SdlTarget &target, SDL_GPUTexture *sceneDepth,
const float viewProjection[16], const float viewport[6],
- const SdlHazardCloud::FieldState *fields, unsigned fieldCount,
+ const HazardCloud::FieldState *fields, unsigned fieldCount,
float timeSeconds, SDL_GPUTexture *terrainTexture, const bool *terrainEnabled)
{
if (failed) return false;
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudEmbers.h b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudEmbers.h
index d3e001be0..1c99ea088 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudEmbers.h
+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudEmbers.h
@@ -5,7 +5,7 @@
class SdlGpuFrame;
struct SdlTarget;
struct SDL_GPUTexture;
-namespace SdlHazardCloud { struct FieldState; }
+namespace HazardCloud { struct FieldState; }
namespace SdlHazardCloudEmbers {
@@ -14,11 +14,11 @@ namespace SdlHazardCloudEmbers {
// contains x, y, width, height, min depth and max depth in native GPU form.
// Resources are created only when an active nuclear field first needs them.
bool prepare(SdlGpuFrame *frame, const SdlTarget &target,
- const SdlHazardCloud::FieldState *fields, unsigned fieldCount);
+ const HazardCloud::FieldState *fields, unsigned fieldCount);
bool render(SdlGpuFrame *frame, const SdlTarget &target, SDL_GPUTexture *sceneDepth,
const float viewProjection[16], const float viewport[6],
- const SdlHazardCloud::FieldState *fields, unsigned fieldCount,
+ const HazardCloud::FieldState *fields, unsigned fieldCount,
float timeSeconds, SDL_GPUTexture *terrainTexture = nullptr,
const bool *terrainEnabled = nullptr);
bool validationPassed();
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloud.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloud.cpp
new file mode 100644
index 000000000..aa3e21260
--- /dev/null
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloud.cpp
@@ -0,0 +1,46 @@
+// Backend-neutral hazard cloud palette and allocation policy.
+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.
+#include "Platform/HazardCloud.h"
+
+#include <algorithm>
+#include <array>
+#include <cmath>
+#include <limits>
+
+namespace HazardCloud {
+namespace {
+
+constexpr std::array<Palette, 4> approved = {{
+ {{0.769999981f, 0.939999998f, 0.550000012f}, {0.125490203f, 0.31764707f, 0.0549019612f}, 0.699999988f, 0.670000017f},
+ {{0.749019623f, 0.670588255f, 0.469999999f}, {0.298039228f, 0.184313729f, 0.0705882385f}, 1.29999995f, 0.0f},
+ {{0.660000026f, 0.75999999f, 1.0f}, {0.0649999976f, 0.100000001f, 0.209999993f}, 1.52999997f, 0.769999981f},
+ {{0.839999974f, 0.629999995f, 1.0f}, {0.192156866f, 0.0470588244f, 0.235294119f}, 1.32000005f, 0.74000001f},
+}};
+
+unsigned cacheSide(const FieldState &field)
+{
+ const float extent = 2.0f * (field.radius + field.fringe + 18.0f);
+ const unsigned samples = static_cast<unsigned>(std::clamp(std::ceil(extent / 2.0f) + 1.0f, 32.0f, 512.0f));
+ return (samples + 15u) & ~15u;
+}
+
+} // namespace
+
+const Palette &defaultPalette(unsigned index) { return approved[index < 4 ? index : 0]; }
+
+std::uint64_t Layer::estimateCacheBytes(const FieldState *fields, unsigned count)
+{
+ if (count > 2 || (count && !fields)) return (std::numeric_limits<std::uint64_t>::max)();
+ std::uint64_t result = (192u * 96u * 4u + TerrainGridSide * TerrainGridSide * 2u) * sizeof(float);
+ for (unsigned i = 0; i < count; ++i) {
+ if (!std::isfinite(fields[i].radius) || !std::isfinite(fields[i].fringe)
+ || fields[i].radius < 0 || fields[i].fringe < 0)
+ return (std::numeric_limits<std::uint64_t>::max)();
+ if (fields[i].radius <= 0.001f || fields[i].height <= 0.002f || fields[i].density <= 0.00001f) continue;
+ const std::uint64_t side = cacheSide(fields[i]);
+ result += side * side * 24u * 10u; // R16F density + RGBA16F light.
+ }
+ return result;
+}
+
+} // namespace HazardCloud
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudFlow.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudFlow.cpp
similarity index 87%
rename from GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudFlow.cpp
rename to GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudFlow.cpp
index ee8dba55f..e0a67ec1a 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudFlow.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudFlow.cpp
@@ -1,12 +1,12 @@
-// Persistent planar smoke transport shared by SDL hazard clouds and their preview.
+// Backend-neutral persistent planar smoke transport for hazard clouds.
// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.
-#include "Platform/SdlHazardCloudFlow.h"
+#include "Platform/HazardCloudFlow.h"
#include <algorithm>
#include <array>
#include <cmath>
-namespace SdlHazardCloudFlow {
+namespace HazardCloudFlow {
namespace {
constexpr unsigned GridWidth = 192;
@@ -27,7 +27,7 @@ struct Cell {
float clamp(float value, float lo, float hi)
{
- return std::max(lo, std::min(hi, value));
+ return (std::max)(lo, (std::min)(hi, value));
}
void limitVector(float &x, float &y, float limit)
@@ -69,8 +69,8 @@ struct Flow::Impl {
float gx = clamp((x - minX) / cellWidth - 0.5f, 0.0f, float(GridWidth - 1));
float gy = clamp((y - minY) / cellHeight - 0.5f, 0.0f, float(GridHeight - 1));
unsigned ix = static_cast<unsigned>(gx), iy = static_cast<unsigned>(gy);
- unsigned nx = std::min(ix + 1, GridWidth - 1);
- unsigned ny = std::min(iy + 1, GridHeight - 1);
+ unsigned nx = (std::min)(ix + 1, GridWidth - 1);
+ unsigned ny = (std::min)(iy + 1, GridHeight - 1);
return mix(mix(cells[iy * GridWidth + ix], cells[iy * GridWidth + nx], gx - ix),
mix(cells[ny * GridWidth + ix], cells[ny * GridWidth + nx], gx - ix), gy - iy);
}
@@ -81,8 +81,8 @@ struct Flow::Impl {
const float displacementDecay = std::exp(-1.05f * FixedStep);
// Conservative explicit diffusion after semi-Lagrangian backtracing. The
// coefficient is bounded even for accidentally tiny preview domains.
- const float diffuseX = std::min(0.12f, 4.0f * FixedStep / (cellWidth * cellWidth));
- const float diffuseY = std::min(0.12f, 4.0f * FixedStep / (cellHeight * cellHeight));
+ const float diffuseX = (std::min)(0.12f, 4.0f * FixedStep / (cellWidth * cellWidth));
+ const float diffuseY = (std::min)(0.12f, 4.0f * FixedStep / (cellHeight * cellHeight));
for (unsigned y = 0; y < GridHeight; ++y) {
for (unsigned x = 0; x < GridWidth; ++x) {
unsigned index = y * GridWidth + x;
@@ -90,9 +90,9 @@ struct Flow::Impl {
Cell next = sample(minX + (x + 0.5f) * cellWidth - old.vx * FixedStep,
minY + (y + 0.5f) * cellHeight - old.vy * FixedStep);
const Cell &left = cells[y * GridWidth + (x ? x - 1 : x)];
- const Cell &right = cells[y * GridWidth + std::min(x + 1, GridWidth - 1)];
+ const Cell &right = cells[y * GridWidth + (std::min)(x + 1, GridWidth - 1)];
const Cell &down = cells[(y ? y - 1 : y) * GridWidth + x];
- const Cell &up = cells[std::min(y + 1, GridHeight - 1) * GridWidth + x];
+ const Cell &up = cells[(std::min)(y + 1, GridHeight - 1) * GridWidth + x];
next.vx += (left.vx + right.vx - 2 * old.vx) * diffuseX
+ (down.vx + up.vx - 2 * old.vx) * diffuseY;
next.vy += (left.vy + right.vy - 2 * old.vy) * diffuseX
@@ -117,10 +117,10 @@ struct Flow::Impl {
float sideX = -directionY, sideY = directionX;
float radius = body.radius;
float extent = radius * 5.0f;
- int firstX = std::max(0, int(std::floor((body.x - extent - minX) / cellWidth)));
- int lastX = std::min(int(GridWidth) - 1, int(std::ceil((body.x + extent - minX) / cellWidth)));
- int firstY = std::max(0, int(std::floor((body.y - extent - minY) / cellHeight)));
- int lastY = std::min(int(GridHeight) - 1, int(std::ceil((body.y + extent - minY) / cellHeight)));
+ int firstX = (std::max)(0, int(std::floor((body.x - extent - minX) / cellWidth)));
+ int lastX = (std::min)(int(GridWidth) - 1, int(std::ceil((body.x + extent - minX) / cellWidth)));
+ int firstY = (std::max)(0, int(std::floor((body.y - extent - minY) / cellHeight)));
+ int lastY = (std::min)(int(GridHeight) - 1, int(std::ceil((body.y + extent - minY) / cellHeight)));
for (int y = firstY; y <= lastY; ++y) {
for (int x = firstX; x <= lastX; ++x) {
float offsetX = minX + (x + 0.5f) * cellWidth - body.x;
@@ -143,7 +143,7 @@ struct Flow::Impl {
float circulation = -sign * speed * 0.36f;
targetAlong += -vortexSide * circulation * vortex;
targetSide += vortexAlong * circulation * vortex;
- weight = std::max(weight, vortex);
+ weight = (std::max)(weight, vortex);
}
targetAlong *= BodyFlowStrength;
targetSide *= BodyFlowStrength;
@@ -165,7 +165,7 @@ struct Flow::Impl {
// Outflow vanishes smoothly at the domain edge, preventing a clamped
// sampler from carrying disturbance indefinitely beyond the field.
unsigned x = index % GridWidth, y = index / GridWidth;
- unsigned edge = std::min(std::min(x, GridWidth - 1 - x), std::min(y, GridHeight - 1 - y));
+ unsigned edge = (std::min)((std::min)(x, GridWidth - 1 - x), (std::min)(y, GridHeight - 1 - y));
if (edge < 3) {
float fade = float(edge) / 3.0f;
cell.vx *= fade; cell.vy *= fade;
@@ -189,7 +189,7 @@ struct Flow::Impl {
pixels[index * 4 + 1] = cell.dy;
pixels[index * 4 + 2] = 0;
pixels[index * 4 + 3] = 0;
- peak = std::max(peak, std::sqrt(cell.dx * cell.dx + cell.dy * cell.dy) / MaxDisplacement);
+ peak = (std::max)(peak, std::sqrt(cell.dx * cell.dx + cell.dy * cell.dy) / MaxDisplacement);
}
}
@@ -232,7 +232,7 @@ struct Flow::Impl {
if (!configured || deltaSeconds == 0) return;
std::array<Body, MaxBodies> usable = {};
bodyCount = 0;
- for (unsigned index = 0; index < std::min(count, MaxBodies); ++index) {
+ for (unsigned index = 0; index < (std::min)(count, MaxBodies); ++index) {
Body body = bodies[index];
if (!std::isfinite(body.x) || !std::isfinite(body.y) || !std::isfinite(body.z)
|| !std::isfinite(body.vx) || !std::isfinite(body.vy)
@@ -254,7 +254,7 @@ struct Flow::Impl {
}
// A stalled frame is capped instead of doing an unbounded catch-up burst.
// Normal 30/60/120 Hz callers execute the same fixed integration steps.
- remainder += std::min(deltaSeconds, 0.25f);
+ remainder += (std::min)(deltaSeconds, 0.25f);
bool advanced = false;
while (remainder + 1.0e-9 >= FixedStep) {
transport();
@@ -292,4 +292,4 @@ bool Flow::valid() const { return impl->configured && impl->healthy; }
float Flow::maxDisturbance() const { return impl->peak; }
unsigned Flow::activeBodies() const { return impl->bodyCount; }
-} // namespace SdlHazardCloudFlow
+} // namespace HazardCloudFlow
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudUnsupported.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudUnsupported.cpp
new file mode 100644
index 000000000..bbd1db647
--- /dev/null
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudUnsupported.cpp
@@ -0,0 +1,11 @@
+// Entry points for builds without a hazard cloud renderer backend.
+// Replace this implementation when adding a Direct3D 11 backend.
+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.
+#include "Platform/HazardCloud.h"
+
+namespace HazardCloud {
+
+bool Supported() { return false; }
+std::unique_ptr<Layer> CreateLayer() { return nullptr; }
+
+} // namespace HazardCloud
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp
index e26381c8e..ed6480e19 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp
@@ -51,17 +51,14 @@
#include "GameClient/ObserverCamera.h"
#include <algorithm>
#include <map>
-#if defined(__linux__)
#include "Common/ThingTemplate.h"
#include "GameClient/Drawable.h"
#include "Platform/HazardCloudPolicy.h"
-#include "Platform/SdlHazardCloud.h"
+#include "Platform/HazardCloud.h"
#include <array>
#include <memory>
#include <cmath>
-#include <algorithm>
#include <tuple>
-#endif
#ifdef _INTERNAL
// for occasional debugging...
@@ -691,38 +688,38 @@ static const Real FIELD_GAIN = 0.7f; ///< of the template's brightest colo
static const Int FIELD_FADE_IN = LOGICFRAMES_PER_SECOND / 2; ///< logic frames
static const Int FIELD_FADE_OUT = 3 * LOGICFRAMES_PER_SECOND; ///< logic frames before the field object dies
static const Int FIELD_FADE_GONE = FIELD_FADE_OUT; ///< logic frames, a field fogged over or whose object went early
+// Stable until device resources are released. FieldKey ordering must never query
+// a live device: changing its answer while keys exist would invalidate the map.
+static bool s_fieldCloudsSupported = false;
+static bool s_fieldCloudCapabilityKnown = false;
+static bool fieldCloudsSupported();
+
static const Real FIELD_OBJECT_REACH = 5.0f; ///< how near the field's centre its object stands
struct FieldKey
{
const ParticleSystemTemplate *tmpl;
Int x, y;
-#if defined(__linux__)
Int z;
Int palette;
ObjectID owner;
-#endif
bool operator<( const FieldKey &o ) const
{
-#if defined(__linux__)
- // The initial nuke emitter and its periodic radiation pulses describe
- // one hazard. Keep its age/cache when the emitter template changes.
- const bool bound = palette >= 0 && owner != INVALID_ID;
- const bool otherBound = o.palette >= 0 && o.owner != INVALID_ID;
- if (bound != otherBound) return bound < otherBound;
- if (bound) {
- if (owner != o.owner) return owner < o.owner;
- return palette < o.palette;
+ if (s_fieldCloudsSupported) {
+ // The initial nuke emitter and its periodic radiation pulses describe
+ // one hazard. Keep its age/cache when the emitter template changes.
+ const bool bound = palette >= 0 && owner != INVALID_ID;
+ const bool otherBound = o.palette >= 0 && o.owner != INVALID_ID;
+ if (bound != otherBound) return bound < otherBound;
+ if (bound) {
+ if (owner != o.owner) return owner < o.owner;
+ return palette < o.palette;
+ }
}
-#endif
if (tmpl != o.tmpl) return tmpl < o.tmpl;
if (x != o.x) return x < o.x;
-#if defined(__linux__)
if (y != o.y) return y < o.y;
- return z < o.z;
-#else
- return y < o.y;
-#endif
+ return s_fieldCloudsSupported && z < o.z;
}
};
@@ -731,12 +728,10 @@ struct FieldKey
struct FieldState
{
Int born; ///< logic frame it was first seen
-#if defined(__linux__)
Int visualBorn; ///< formation age survives fog fade changes
Real cloudShown, cloudFormation, cloudGoneDensity, cloudGoneFormation, cloudRevealFrom;
Int cloudGoneAt, cloudRevealAt;
Int cloudDieFrame; ///< owner's LifetimeUpdate die frame at the last sync point, or -1
-#endif
Int seen; ///< logic frame a system was last seen at it
ObjectID object; ///< the object whose life it fades with, or INVALID_ID
Int gone; ///< logic frame it began going out (fog, or its object gone), or -1
@@ -758,11 +753,25 @@ static const Real FIELD_STACK = 2.5f; ///< puddles' worth of cover a spot
static const Real FIELD_SATURATE = 0.6f; ///< share of the weakest channel taken out of the colour
static std::map<FieldKey, FieldState> s_fieldStates;
-#if defined(__linux__)
struct FieldSystemOwner { ObjectID object; unsigned pass; };
static std::map<ParticleSystemID, FieldSystemOwner> s_fieldSystemOwners;
static unsigned s_fieldCollectionPass = 0;
-#endif
+
+static bool fieldCloudsSupported()
+{
+ if (!s_fieldCloudCapabilityKnown) {
+ const bool supported = HazardCloud::Supported();
+ // In particular, a previously unavailable device may now have a backend.
+ // Destroy keys before changing their comparator's mode.
+ if (supported != s_fieldCloudsSupported) {
+ s_fieldStates.clear();
+ s_fieldSystemOwners.clear();
+ }
+ s_fieldCloudsSupported = supported;
+ s_fieldCloudCapabilityKnown = true;
+ }
+ return s_fieldCloudsSupported;
+}
static Bool s_fieldSkipNextFadeIn = FALSE;
/** One puddle of this frame's fields, before it is laid. */
@@ -802,11 +811,7 @@ static std::vector<FieldDraw> s_fieldDraws;
static std::vector<FieldBounds> s_fieldBounds; ///< one a field draw, in their order
/** The CLEANUP_HAZARD object with a LifetimeUpdate standing on a field's centre, if there is one. */
-#if defined(__linux__)
-static ObjectID findFieldObject( const Coord3D &centre, Int palette )
-#else
-static ObjectID findFieldObject( const Coord3D &centre )
-#endif
+static ObjectID findFieldObject( const Coord3D &centre, Int palette = -1 )
{
static NameKeyType key_LifetimeUpdate = NAMEKEY( "LifetimeUpdate" );
ObjectID found = INVALID_ID;
@@ -815,24 +820,19 @@ static ObjectID findFieldObject( const Coord3D &centre )
{
if (!obj->isKindOf( KINDOF_CLEANUP_HAZARD ))
continue;
-#if defined(__linux__)
- if (obj->isDestroyed() || obj->isEffectivelyDead())
- continue;
- if (palette >= 0 && HazardCloudPolicy::paletteForOwner(obj->getTemplate()->getName().str()) != palette)
- continue;
-#endif
+ if (s_fieldCloudsSupported) {
+ if (obj->isDestroyed() || obj->isEffectivelyDead())
+ continue;
+ if (palette >= 0 && HazardCloudPolicy::paletteForOwner(obj->getTemplate()->getName().str()) != palette)
+ continue;
+ }
const Coord3D *pos = obj->getPosition();
-#if defined(__linux__)
- if (WWMath::Fabs(pos->z - centre.z) > FIELD_OBJECT_REACH)
+ if (s_fieldCloudsSupported && WWMath::Fabs(pos->z - centre.z) > FIELD_OBJECT_REACH)
continue;
-#endif
const Real dx = pos->x - centre.x, dy = pos->y - centre.y;
const Real d = dx * dx + dy * dy;
-#if defined(__linux__)
- if ((d < best || (found == INVALID_ID && d <= best)) && obj->findUpdateModule( key_LifetimeUpdate ) != NULL)
-#else
- if (d <= best && obj->findUpdateModule( key_LifetimeUpdate ) != NULL)
-#endif
+ const bool nearer = s_fieldCloudsSupported ? (d < best || (found == INVALID_ID && d <= best)) : d <= best;
+ if (nearer && obj->findUpdateModule( key_LifetimeUpdate ) != NULL)
{
best = d;
found = obj->getID();
@@ -857,13 +857,9 @@ static inline Real midValue( const GameClientRandomVariable &v )
static Real fieldFade( FieldState &state, Int now )
{
static NameKeyType key_LifetimeUpdate = NAMEKEY( "LifetimeUpdate" );
-#if defined(__linux__)
- // An owner's real lifetime keeps Linux fields continuous between
- // sparse emitters. Other platforms retain their existing emitter grace period.
- Bool lost = (state.object == INVALID_ID && now - state.seen > FIELD_GRACE)
-#else
- Bool lost = now - state.seen > FIELD_GRACE
-#endif
+ // A capable backend follows the owner's life between sparse emitters.
+ // Otherwise retain the upstream emitter grace, including for bound owners.
+ Bool lost = ((!s_fieldCloudsSupported || state.object == INVALID_ID) && now - state.seen > FIELD_GRACE)
|| ThePartitionManager->getShroudStatusForPlayer( TheObserverCamera.getShroudPlayerIndex(), &state.centre ) != CELLSHROUD_CLEAR;
Int remaining = state.particleEnd - now;
if (!lost && state.object != INVALID_ID)
@@ -899,7 +895,6 @@ static Real fieldFade( FieldState &state, Int now )
return state.shown;
}
-#if defined(__linux__)
namespace {
// A busy battlefield has a fixed visual memory/draw budget. Fields which cannot
// be admitted keep the ordinary ground effect, including unknown mod templates.
@@ -907,7 +902,7 @@ constexpr unsigned MaxCloudLayers = 8;
constexpr std::uint64_t CloudCacheBudget = 192ull * 1024 * 1024;
struct CloudLayer {
FieldKey key = {};
- std::unique_ptr<SdlHazardCloud::Layer> renderer;
+ std::unique_ptr<HazardCloud::Layer> renderer;
unsigned used = 0;
float terrainChecked = -100;
float terrainReach = -1;
@@ -915,9 +910,9 @@ struct CloudLayer {
};
std::array<CloudLayer, MaxCloudLayers> s_cloudLayers;
unsigned s_cloudPass = 0, s_cloudDraws = 0;
-struct CloudWalker { Coord3D position; SdlHazardCloud::Body body; unsigned frame; };
+struct CloudWalker { Coord3D position; HazardCloud::Body body; unsigned frame; };
std::map<ObjectID, CloudWalker> s_cloudWalkers;
-std::vector<SdlHazardCloud::Body> s_cloudBodies;
+std::vector<HazardCloud::Body> s_cloudBodies;
unsigned s_cloudBodyFrame = ~0u;
bool isCloudMainPass()
@@ -929,7 +924,7 @@ bool isCloudMainPass()
bool modernCloudsEnabled()
{
- return TheGlobalData && TheGlobalData->m_cloudStyle == 1 && isCloudMainPass();
+ return fieldCloudsSupported() && TheGlobalData && TheGlobalData->m_cloudStyle == 1 && isCloudMainPass();
}
void releaseCloudLayers()
@@ -942,7 +937,7 @@ void releaseCloudLayers()
void beginCloudPass(unsigned now)
{
- if (!TheGlobalData || TheGlobalData->m_cloudStyle != 1) {
+ if (!fieldCloudsSupported() || !TheGlobalData || TheGlobalData->m_cloudStyle != 1) {
releaseCloudLayers();
return;
}
@@ -965,7 +960,7 @@ void updateCloudBodies(unsigned now)
|| draw->getStealthLook() != STEALTHLOOK_NONE || draw->getEffectiveOpacity() < .99f
|| ThePartitionManager->getShroudStatusForPlayer(TheObserverCamera.getShroudPlayerIndex(), &pos) != CELLSHROUD_CLEAR)
continue;
- SdlHazardCloud::Body body = {};
+ HazardCloud::Body body = {};
body.x = pos.x; body.y = pos.y; body.z = pos.z;
body.radius = std::clamp(obj->getGeometryInfo().getBoundingCircleRadius(), 1.f, 12.f);
body.height = std::clamp(obj->getGeometryInfo().getMaxHeightAbovePosition(), 4.f, 30.f);
@@ -985,10 +980,10 @@ void updateCloudBodies(unsigned now)
s_cloudBodyFrame = now;
}
-bool updateCloudTerrain(CloudLayer &slot, const SdlHazardCloud::FieldState &field, bool onGround)
+bool updateCloudTerrain(CloudLayer &slot, const HazardCloud::FieldState &field, bool onGround)
{
if (!onGround) { slot.renderer->setTerrain(0, nullptr); return true; }
- constexpr unsigned side = SdlHazardCloud::TerrainGridSide;
+ constexpr unsigned side = HazardCloud::TerrainGridSide;
std::array<float, side * side> heights;
const float reach = field.radius + field.fringe + 18.f;
float low = field.ground.z, high = field.ground.z;
@@ -997,7 +992,7 @@ bool updateCloudTerrain(CloudLayer &slot, const SdlHazardCloud::FieldState &fiel
const float z = TheTerrainRenderObject->getHeightMapHeight(field.ground.x + dx, field.ground.y + dy, NULL);
if (!std::isfinite(z)) return false;
heights[y * side + x] = z;
- low = std::min(low, z); high = std::max(high, z);
+ low = (std::min)(low, z); high = (std::max)(high, z);
}
slot.renderer->setTerrain(0, high - low > .001f ? heights.data() : nullptr);
return true;
@@ -1007,13 +1002,13 @@ bool drawModernCloud(const FieldKey &key, FieldState &state, float fade, float s
{
if (!modernCloudsEnabled() || key.palette < 0) return false;
if (s_cloudDraws >= MaxCloudLayers) return false;
- const float age = std::max(0.f, float(now - state.visualBorn) / LOGICFRAMES_PER_SECOND);
+ const float age = (std::max)(0.f, float(now - state.visualBorn) / LOGICFRAMES_PER_SECOND);
// the owner's life was read at the sync point (updateGroundFields), not beside the tick
const int remaining = state.cloudDieFrame >= 0 ? state.cloudDieFrame - now : state.particleEnd - now;
- const float left = std::max(0.f, float(remaining) / LOGICFRAMES_PER_SECOND);
+ const float left = (std::max)(0.f, float(remaining) / LOGICFRAMES_PER_SECOND);
const float lifetime = age + left;
const auto buildup = HazardCloudPolicy::visualBuildup(key.palette, state.radius >= 100.f, age, lifetime);
- SdlHazardCloud::FieldState field = {};
+ HazardCloud::FieldState field = {};
field.ground = state.centre;
const float ground = TheTerrainRenderObject->getHeightMapHeight(state.centre.x, state.centre.y, NULL);
const bool onGround = state.centre.z - ground < FIELD_ON_GROUND;
@@ -1024,7 +1019,7 @@ bool drawModernCloud(const FieldKey &key, FieldState &state, float fade, float s
field.fringe = HazardCloudPolicy::visualFringe(state.size);
field.formation = buildup.formation;
field.release = buildup.release;
- const float endFade = std::clamp(left / std::max(.1f, std::min(3.f, lifetime * .25f)), 0.f, 1.f);
+ const float endFade = std::clamp(left / (std::max)(.1f, (std::min)(3.f, lifetime * .25f)), 0.f, 1.f);
field.density = buildup.density * endFade * state.stealth;
if (state.gone >= 0) {
if (state.cloudGoneAt != state.gone) {
@@ -1064,7 +1059,7 @@ bool drawModernCloud(const FieldKey &key, FieldState &state, float fade, float s
*slot = CloudLayer{};
slot->key = key;
}
- const auto wanted = SdlHazardCloud::Layer::estimateCacheBytes(&field, 1);
+ const auto wanted = HazardCloud::Layer::estimateCacheBytes(&field, 1);
std::uint64_t used = 0;
for (const auto &other : s_cloudLayers) if (&other != slot && other.renderer) used += other.renderer->estimatedCacheBytes();
if (wanted > CloudCacheBudget) return false;
@@ -1078,8 +1073,8 @@ bool drawModernCloud(const FieldKey &key, FieldState &state, float fade, float s
*oldest = CloudLayer{};
}
if (!slot->renderer) {
- slot->renderer.reset(new SdlHazardCloud::Layer);
- if (!slot->renderer->initialize()) { slot->renderer.reset(); return false; }
+ slot->renderer = HazardCloud::CreateLayer();
+ if (!slot->renderer || !slot->renderer->initialize()) { slot->renderer.reset(); return false; }
const float reach = field.radius + field.fringe + 24.f;
slot->renderer->setFlowDomain(field.ground.x - reach, field.ground.y - reach, field.ground.x + reach, field.ground.y + reach);
}
@@ -1091,7 +1086,7 @@ bool drawModernCloud(const FieldKey &key, FieldState &state, float fade, float s
slot->terrainReach = field.radius + field.fringe;
}
if (!slot->terrainValid) return false;
- std::array<SdlHazardCloud::Body, 32> bodies;
+ std::array<HazardCloud::Body, 32> bodies;
unsigned count = 0;
for (const auto &body : s_cloudBodies) {
const float dx = body.x - field.ground.x, dy = body.y - field.ground.y;
@@ -1108,7 +1103,6 @@ bool drawModernCloud(const FieldKey &key, FieldState &state, float fade, float s
return true;
}
} // namespace
-#endif
/** This frame's fields from their systems, and each one's fade, at the sync point before the render:
* finding a field's object, its life and the fog over it read the logic (LOGIC-THREAD.md phase 3).
@@ -1119,45 +1113,41 @@ static void updateGroundFields( const std::vector<ParticleSystem *> &systems )
// An explicit cache refresh may need an immediate comparison while paused.
// Consume this once, even if this sync point has no fields, so later gameplay
// emitters always retain the normal fade-in unless explicitly refreshed again.
- const Bool skipFadeIn = s_fieldSkipNextFadeIn;
+ const bool cloudsSupported = fieldCloudsSupported();
+ const Bool skipFadeIn = cloudsSupported && s_fieldSkipNextFadeIn;
s_fieldSkipNextFadeIn = FALSE;
-#if defined(__linux__)
- ++s_fieldCollectionPass;
+ if (cloudsSupported) ++s_fieldCollectionPass;
std::map<std::tuple<Int, Int, Int, Int>, ObjectID> fieldOwners;
-#endif
// where the fields are this frame, and what each one looks like
for (size_t f = 0; f < systems.size(); ++f)
{
ParticleSystem *sys = systems[ f ];
-#if defined(__linux__)
- if (sys->getInitialDelayLeft() > 0) continue;
-#endif
+ if (cloudsSupported && sys->getInitialDelayLeft() > 0) continue;
Coord3D pos;
sys->getPosition( &pos );
-#if defined(__linux__)
- const Int palette = HazardCloudPolicy::paletteForTemplate(sys->getTemplate()->getName().str());
- const auto ownerKey = std::make_tuple(REAL_TO_INT_FLOOR(pos.x + .5f), REAL_TO_INT_FLOOR(pos.y + .5f),
- REAL_TO_INT_FLOOR(pos.z + .5f), palette);
+ Int palette = -1;
ObjectID owner = INVALID_ID;
- auto binding = s_fieldSystemOwners.find(sys->getSystemID());
- if (palette >= 0 && binding != s_fieldSystemOwners.end()) owner = binding->second.object;
- if (owner == INVALID_ID) {
- auto ownerEntry = fieldOwners.find(ownerKey);
- if (ownerEntry == fieldOwners.end()) ownerEntry = fieldOwners.emplace(ownerKey, findFieldObject(pos, palette)).first;
- owner = ownerEntry->second;
- }
- if (palette >= 0) {
- // A surviving emitter retains its hazard identity after cleanup.
- // Otherwise its last particles would create a fresh, growing cloud.
- s_fieldSystemOwners[sys->getSystemID()] = {owner, s_fieldCollectionPass};
+ if (cloudsSupported) {
+ palette = HazardCloudPolicy::paletteForTemplate(sys->getTemplate()->getName().str());
+ const auto ownerKey = std::make_tuple(REAL_TO_INT_FLOOR(pos.x + .5f), REAL_TO_INT_FLOOR(pos.y + .5f),
+ REAL_TO_INT_FLOOR(pos.z + .5f), palette);
+ auto binding = s_fieldSystemOwners.find(sys->getSystemID());
+ if (palette >= 0 && binding != s_fieldSystemOwners.end()) owner = binding->second.object;
+ if (owner == INVALID_ID) {
+ auto ownerEntry = fieldOwners.find(ownerKey);
+ if (ownerEntry == fieldOwners.end()) ownerEntry = fieldOwners.emplace(ownerKey, findFieldObject(pos, palette)).first;
+ owner = ownerEntry->second;
+ }
+ if (palette >= 0) {
+ // A surviving emitter retains its hazard identity after cleanup.
+ // Otherwise its last particles would create a fresh, growing cloud.
+ s_fieldSystemOwners[sys->getSystemID()] = {owner, s_fieldCollectionPass};
+ }
}
FieldKey key = { sys->getTemplate(), REAL_TO_INT_FLOOR( pos.x + 0.5f ), REAL_TO_INT_FLOOR( pos.y + 0.5f ),
- REAL_TO_INT_FLOOR(pos.z + .5f), palette, owner };
-#else
- FieldKey key = { sys->getTemplate(), REAL_TO_INT_FLOOR( pos.x + 0.5f ), REAL_TO_INT_FLOOR( pos.y + 0.5f ) };
-#endif
+ cloudsSupported ? REAL_TO_INT_FLOOR(pos.z + .5f) : 0, palette, owner };
const ParticleSystemInfo::EmissionVolumeType volume = sys->getEmisionVolumeType();
const Real radius = volume == ParticleSystemInfo::SPHERE ? sys->m_emissionVolume.sphere.radius
: (volume == ParticleSystemInfo::CYLINDER ? sys->m_emissionVolume.cylinder.radius : 0.0f);
@@ -1167,10 +1157,9 @@ static void updateGroundFields( const std::vector<ParticleSystem *> &systems )
life = WWMath::Max( life, (Int)p->getLifetimeLeft() );
std::map<FieldKey, FieldState>::iterator st = s_fieldStates.find( key );
-#if defined(__linux__)
// A blast FX can precede its cleanup object within the same tick. Adopt
// that unbound visual when the owner arrives rather than drawing it twice.
- if (st == s_fieldStates.end() && palette >= 0 && owner != INVALID_ID) {
+ if (cloudsSupported && st == s_fieldStates.end() && palette >= 0 && owner != INVALID_ID) {
for (auto orphan = s_fieldStates.begin(); orphan != s_fieldStates.end(); ++orphan) {
const FieldKey &old = orphan->first;
if (old.owner == INVALID_ID && old.palette == palette && old.x == key.x && old.y == key.y && old.z == key.z) {
@@ -1182,25 +1171,18 @@ static void updateGroundFields( const std::vector<ParticleSystem *> &systems )
}
}
}
-#endif
if (st == s_fieldStates.end() || st->second.seen != now)
{
if (st == s_fieldStates.end())
{
FieldState fresh = {};
fresh.born = now - (skipFadeIn ? FIELD_FADE_IN : 0);
-#if defined(__linux__)
fresh.visualBorn = fresh.born;
fresh.cloudGoneAt = -1;
fresh.cloudRevealAt = now - FIELD_FADE_IN;
fresh.cloudDieFrame = -1;
-#endif
fresh.seen = now;
-#if defined(__linux__)
- fresh.object = owner;
-#else
- fresh.object = findFieldObject( pos );
-#endif
+ fresh.object = cloudsSupported ? owner : findFieldObject( pos );
fresh.gone = -1;
fresh.goneFade = 0.0f;
fresh.shown = 0.0f;
@@ -1238,12 +1220,10 @@ static void updateGroundFields( const std::vector<ParticleSystem *> &systems )
}
st->second.stealth = sys->getStealthFade();
}
-#if defined(__linux__)
for (auto binding = s_fieldSystemOwners.begin(); binding != s_fieldSystemOwners.end();) {
if (binding->second.pass != s_fieldCollectionPass) binding = s_fieldSystemOwners.erase(binding);
else ++binding;
}
-#endif
for (std::map<FieldKey, FieldState>::iterator st = s_fieldStates.begin(); st != s_fieldStates.end(); )
{
@@ -1261,21 +1241,21 @@ static void updateGroundFields( const std::vector<ParticleSystem *> &systems )
}
++st;
}
-#if defined(__linux__)
- // The hazard clouds' owners' lifetimes and the infantry wading through them read the logic, so
- // they are taken here with the rest, not in the render beside the tick.
- static NameKeyType key_cloudLife = NAMEKEY("LifetimeUpdate");
- for (std::map<FieldKey, FieldState>::iterator st = s_fieldStates.begin(); st != s_fieldStates.end(); ++st) {
- FieldState &state = st->second;
- state.cloudDieFrame = -1;
- if (state.object == INVALID_ID || st->first.palette < 0) continue;
- Object *obj = TheGameLogic->findObjectByID(state.object);
- if (obj) if (auto *life = static_cast<LifetimeUpdate *>(obj->findUpdateModule(key_cloudLife)))
- state.cloudDieFrame = Int(life->getDieFrame());
+ if (cloudsSupported) {
+ // The hazard clouds' owners' lifetimes and the infantry wading through them read the logic, so
+ // they are taken here with the rest, not in the render beside the tick.
+ static NameKeyType key_cloudLife = NAMEKEY("LifetimeUpdate");
+ for (std::map<FieldKey, FieldState>::iterator st = s_fieldStates.begin(); st != s_fieldStates.end(); ++st) {
+ FieldState &state = st->second;
+ state.cloudDieFrame = -1;
+ if (state.object == INVALID_ID || st->first.palette < 0) continue;
+ Object *obj = TheGameLogic->findObjectByID(state.object);
+ if (obj) if (auto *life = static_cast<LifetimeUpdate *>(obj->findUpdateModule(key_cloudLife)))
+ state.cloudDieFrame = Int(life->getDieFrame());
+ }
+ if (TheGlobalData && TheGlobalData->m_cloudStyle == 1)
+ updateCloudBodies((unsigned)now);
}
- if (TheGlobalData && TheGlobalData->m_cloudStyle == 1)
- updateCloudBodies((unsigned)now);
-#endif
}
/** Lays the fields updateGroundFields found on the terrain into the field buffers; drawGroundFields
@@ -1287,9 +1267,7 @@ static Int collectGroundFields( const AABoxClass &view )
const Real seconds = ((Real)now + (TheSmoothMotionActive ? TheSmoothMotionAlpha : 0.0f)) / LOGICFRAMES_PER_SECOND;
s_fieldPuddles.clear();
s_fieldDraws.clear();
-#if defined(__linux__)
beginCloudPass(now);
-#endif
Int laid = 0;
for (std::map<FieldKey, FieldState>::iterator st = s_fieldStates.begin(); st != s_fieldStates.end(); ++st)
@@ -1306,16 +1284,13 @@ static Int collectGroundFields( const AABoxClass &view )
const Real size = state.size;
Real reach = state.radius + size;
Bool groundVolume = FALSE;
-#if defined(__linux__)
if (modernCloudsEnabled() && key.palette >= 0) {
reach = state.radius + HazardCloudPolicy::visualFringe(size) + 18.f;
groundVolume = TRUE;
}
-#endif
const Bool visible = WWMath::Fabs( state.centre.x - view.Center.X ) <= view.Extent.X + reach
&& WWMath::Fabs( state.centre.y - view.Center.Y ) <= view.Extent.Y + reach
&& (groundVolume || WWMath::Fabs( state.centre.z - view.Center.Z ) <= view.Extent.Z + reach);
-#if defined(__linux__)
if (visible) {
if (drawModernCloud(key, state, fade, seconds, now)) {
// Preserve the client's existing area-effect particle ceiling even
@@ -1327,7 +1302,6 @@ static Int collectGroundFields( const AABoxClass &view )
continue;
}
}
-#endif
FieldBatch batch;
if (!particlePresetShader( state.shader, &batch.glow ))
@@ -1664,17 +1638,17 @@ void W3DParticleSystemManager::invalidateGroundFields(bool fadeIn)
// references are already released at the end of each draw. Only this map
// persists the footprint after an emitter is removed or changes appearance.
s_fieldStates.clear();
-#if defined(__linux__)
s_fieldSystemOwners.clear();
-#endif
s_fieldSkipNextFadeIn = !fadeIn;
}
void W3DParticleSystemManager::releaseCloudResources()
{
-#if defined(__linux__)
releaseCloudLayers();
-#endif
+ // Query the replacement device at the next sync point. The helper clears
+ // keys before changing their ordering if support changed; unchanged support
+ // retains field ages/owner bindings across a resize or device reset.
+ s_fieldCloudCapabilityKnown = false;
}
/** LOGIC-THREAD.md phase 3. A system's stealth fade asks its object's drawable, and a field asks for
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/HazardCloud.h b/GeneralsMD/Code/Libraries/Include/Platform/HazardCloud.h
new file mode 100644
index 000000000..9eaa91a0e
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/HazardCloud.h
@@ -0,0 +1,94 @@
+// Backend-neutral visual-only hazard cloud renderer.
+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.
+#pragma once
+
+#include "Lib/BaseType.h"
+#include "Platform/HazardCloudFlow.h"
+#include <cstdint>
+#include <memory>
+
+namespace HazardCloud {
+
+constexpr unsigned TerrainGridSide = 129;
+
+struct FieldState {
+ Coord3D ground;
+ float radius;
+ float height; // Full world-space height above the sampled ground.
+ float density;
+ float palette; // 0 toxin, 1 radiation, 2 anthrax blue, 3 gamma purple.
+ float formation;
+ float release;
+ float fringe;
+};
+using Body = HazardCloudFlow::Body;
+struct Color { float r, g, b; };
+struct Palette {
+ Color main, shadow;
+ float brightness;
+ // 0 retains full optical density; 1 makes only the smoke invisible.
+ // Formation, footprint, wakes, heat and embers remain independent.
+ float transparency = 0.0f;
+};
+
+// Stable user-approved palette, independent of preview files or game options.
+const Palette &defaultPalette(unsigned index);
+
+// Main render thread only. Owns up to two fields with independent density,
+// lighting and infantry-wake history. Pipelines and transient scene targets are
+// shared by all layers on the same device. No scene object is registered.
+// Without a terrain grid, ground support is the field's flat ground/deck plane.
+// The support model has one height per XY position. The production adapter uses
+// terrain samples or an elevated plane; cliffs and crossing decks have no
+// dedicated validation fixture or automatic geometry fallback yet.
+class Layer {
+public:
+ Layer() = default;
+ virtual ~Layer() = default;
+ Layer(const Layer &) = delete;
+ Layer &operator=(const Layer &) = delete;
+
+ virtual bool initialize() = 0;
+ virtual void setFields(const FieldState *fields, unsigned count) = 0;
+ virtual void setBodies(const Body *bodies, unsigned count) = 0; // At most 32.
+ virtual void setFlowDomain(float minX, float minY, float maxX, float maxY) = 0;
+ // Copies TerrainGridSide squared world heights, row-major with increasing Y.
+ // Grid nodes span ground.xy +/- (radius + fringe + 18 world units), matching
+ // this field's cache domain. Refresh after changing that domain or terrain.
+ // nullptr disables terrain sampling for this field and restores its plane.
+ virtual void setTerrain(unsigned fieldIndex, const float *heights) = 0;
+ virtual void setPalette(unsigned index, const Palette &palette) = 0;
+ virtual void setInteractionEnabled(bool enabled) = 0;
+ virtual bool isInteractionEnabled() const = 0;
+ virtual void setHeatEnabled(bool enabled) = 0;
+ virtual bool isHeatEnabled() const = 0;
+ virtual void update(float timeSeconds) = 0;
+ virtual void reset() = 0; // Clears source/wake history, retaining fields and allocations.
+
+ // Call only in the main scene after opaque geometry/water. False means no
+ // cloud scene draw was recorded, so the caller may draw classic effects.
+ virtual bool render() = 0;
+ virtual bool valid() const = 0;
+ virtual unsigned activeBodies() const = 0;
+ virtual float maxDisturbance() const = 0;
+ virtual unsigned interactionUploads() const = 0;
+ virtual unsigned renderedFrames() const = 0;
+
+ // Density + lighting atlas allocations and local flow texture. Excludes
+ // shared screen scratch targets; estimate before admitting a new layer.
+ static std::uint64_t estimateCacheBytes(const FieldState *fields, unsigned count);
+ virtual std::uint64_t estimatedCacheBytes() const = 0;
+
+ // Release before the display/device is destroyed. Repeated calls are safe;
+ // releasing one layer leaves all other layers' resources and history intact.
+ virtual void shutdown() = 0;
+};
+
+// A renderer backend (SDL GPU today, Direct3D 11 later) implements Layer and
+// these two entry points. Supported() queries the current device at call time;
+// false includes calls before a usable graphics device exists. CreateLayer()
+// returns nullptr when unsupported; initialize() performs resource allocation.
+bool Supported();
+std::unique_ptr<Layer> CreateLayer();
+
+} // namespace HazardCloud
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/SdlHazardCloudFlow.h b/GeneralsMD/Code/Libraries/Include/Platform/HazardCloudFlow.h
similarity index 94%
rename from GeneralsMD/Code/Libraries/Include/Platform/SdlHazardCloudFlow.h
rename to GeneralsMD/Code/Libraries/Include/Platform/HazardCloudFlow.h
index 79cb4a446..eff0de4e9 100644
--- a/GeneralsMD/Code/Libraries/Include/Platform/SdlHazardCloudFlow.h
+++ b/GeneralsMD/Code/Libraries/Include/Platform/HazardCloudFlow.h
@@ -1,8 +1,8 @@
-// Persistent planar smoke transport for SDL hazard clouds.
+// Backend-neutral persistent planar smoke transport for hazard clouds.
// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.
#pragma once
-namespace SdlHazardCloudFlow {
+namespace HazardCloudFlow {
// World coordinates and world units per second. The caller supplies the current
// velocity, not displacement since the last rendered frame. Body order need not
@@ -57,4 +57,4 @@ private:
Impl *impl;
};
-} // namespace SdlHazardCloudFlow
+} // namespace HazardCloudFlow
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/SdlHazardCloud.h b/GeneralsMD/Code/Libraries/Include/Platform/SdlHazardCloud.h
index 10a5eef61..306c6a34d 100644
--- a/GeneralsMD/Code/Libraries/Include/Platform/SdlHazardCloud.h
+++ b/GeneralsMD/Code/Libraries/Include/Platform/SdlHazardCloud.h
@@ -1,86 +1,45 @@
-// Shared visual-only hazard cloud renderer for the Linux game and cloud preview.
+// SDL GPU implementation of the backend-neutral hazard cloud renderer.
// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.
#pragma once
-#include "Lib/BaseType.h"
-#include "Platform/SdlHazardCloudFlow.h"
-#include <cstdint>
+#include "Platform/HazardCloud.h"
namespace SdlHazardCloud {
-constexpr unsigned TerrainGridSide = 129;
+using HazardCloud::FieldState;
+using HazardCloud::Body;
+using HazardCloud::Color;
+using HazardCloud::Palette;
+using HazardCloud::TerrainGridSide;
+using HazardCloud::defaultPalette;
-struct FieldState {
- Coord3D ground;
- float radius;
- float height; // Full world-space height above the sampled ground.
- float density;
- float palette; // 0 toxin, 1 radiation, 2 anthrax blue, 3 gamma purple.
- float formation;
- float release;
- float fringe;
-};
-using Body = SdlHazardCloudFlow::Body;
-struct Color { float r, g, b; };
-struct Palette {
- Color main, shadow;
- float brightness;
- // 0 retains full optical density; 1 makes only the smoke invisible.
- // Formation, footprint, wakes, heat and embers remain independent.
- float transparency = 0.0f;
-};
-
-// Stable user-approved palette, independent of preview files or game options.
-const Palette &defaultPalette(unsigned index);
-
-// Main render thread only. Owns up to two fields with independent density,
-// lighting and infantry-wake history. Pipelines and transient scene targets are
-// shared by all layers on the same device. No scene object is registered.
-// Without a terrain grid, ground support is the field's flat ground/deck plane.
-// The support model has one height per XY position. The production adapter uses
-// terrain samples or an elevated plane; cliffs and crossing decks have no
-// dedicated validation fixture or automatic geometry fallback yet.
-class Layer {
+class Layer final : public HazardCloud::Layer {
public:
Layer();
- ~Layer();
+ ~Layer() override;
Layer(const Layer &) = delete;
Layer &operator=(const Layer &) = delete;
- bool initialize();
- void setFields(const FieldState *fields, unsigned count);
- void setBodies(const Body *bodies, unsigned count); // At most 32.
- void setFlowDomain(float minX, float minY, float maxX, float maxY);
- // Copies TerrainGridSide squared world heights, row-major with increasing Y.
- // Grid nodes span ground.xy +/- (radius + fringe + 18 world units), matching
- // this field's cache domain. Refresh after changing that domain or terrain.
- // nullptr disables terrain sampling for this field and restores its plane.
- void setTerrain(unsigned fieldIndex, const float *heights);
- void setPalette(unsigned index, const Palette &palette);
- void setInteractionEnabled(bool enabled);
- bool isInteractionEnabled() const;
- void setHeatEnabled(bool enabled);
- bool isHeatEnabled() const;
- void update(float timeSeconds);
- void reset(); // Clears source/wake history, retaining fields and allocations.
-
- // Call only in the main scene after opaque geometry/water. False means no
- // cloud scene draw was recorded, so the caller may draw classic effects.
- bool render();
- bool valid() const;
- unsigned activeBodies() const;
- float maxDisturbance() const;
- unsigned interactionUploads() const;
- unsigned renderedFrames() const;
-
- // Density + lighting atlas allocations and local flow texture. Excludes
- // shared screen scratch targets; estimate before admitting a new layer.
- static std::uint64_t estimateCacheBytes(const FieldState *fields, unsigned count);
- std::uint64_t estimatedCacheBytes() const;
-
- // Release before the display/device is destroyed. Repeated calls are safe;
- // releasing one layer leaves all other layers' resources and history intact.
- void shutdown();
+ bool initialize() override;
+ void setFields(const FieldState *fields, unsigned count) override;
+ void setBodies(const Body *bodies, unsigned count) override;
+ void setFlowDomain(float minX, float minY, float maxX, float maxY) override;
+ void setTerrain(unsigned fieldIndex, const float *heights) override;
+ void setPalette(unsigned index, const Palette &palette) override;
+ void setInteractionEnabled(bool enabled) override;
+ bool isInteractionEnabled() const override;
+ void setHeatEnabled(bool enabled) override;
+ bool isHeatEnabled() const override;
+ void update(float timeSeconds) override;
+ void reset() override;
+ bool render() override;
+ bool valid() const override;
+ unsigned activeBodies() const override;
+ float maxDisturbance() const override;
+ unsigned interactionUploads() const override;
+ unsigned renderedFrames() const override;
+ std::uint64_t estimatedCacheBytes() const override;
+ void shutdown() override;
private:
struct Impl;
diff --git a/GeneralsMD/Code/Tests/test_hazard_cloud_policy.cpp b/GeneralsMD/Code/Tests/test_hazard_cloud_policy.cpp
index ebe7857df..1edf501ab 100644
--- a/GeneralsMD/Code/Tests/test_hazard_cloud_policy.cpp
+++ b/GeneralsMD/Code/Tests/test_hazard_cloud_policy.cpp
@@ -1,8 +1,11 @@
#include "test_harness.h"
#include "Platform/HazardCloudPolicy.h"
+#include "Platform/HazardCloud.h"
+#include "Platform/HazardCloudFlow.h"
#include <initializer_list>
#include <limits>
+#include <type_traits>
using namespace HazardCloudPolicy;
@@ -117,7 +120,7 @@ TEST(hazard_cloud_fringe_covers_original_rotated_breathing_quads)
CHECK(visualFringe(50.0f) > 50.0f * std::sqrt(2.0f));
CHECK_EQ(visualFringe(-1.0f), 0.0f);
CHECK_EQ(visualFringe(std::numeric_limits<float>::infinity()), 0.0f);
- CHECK_EQ(visualFringe(std::numeric_limits<float>::max()), 0.0f);
+ CHECK_EQ(visualFringe((std::numeric_limits<float>::max)()), 0.0f);
}
TEST(hazard_cloud_admission_rejects_invalid_values_without_changing_footprints)
@@ -143,3 +146,73 @@ TEST(hazard_cloud_admission_rejects_invalid_values_without_changing_footprints)
CHECK(!validField(0, 0, 0, 80, 18, 1, 1, 0, 4));
CHECK(!validField(0, 0, 0, 1e30f, 18, 1, 1, 0, 0));
}
+
+
+// This target deliberately links the no-backend implementation on every
+// platform. It keeps the public API and device-free transport independently
+// usable when a game build has no volumetric renderer (Windows today).
+static_assert(std::is_abstract<HazardCloud::Layer>::value, "Layer must remain a backend interface");
+static_assert(std::has_virtual_destructor<HazardCloud::Layer>::value, "Layer is owned through the interface");
+static_assert(std::is_same<HazardCloud::Body, HazardCloudFlow::Body>::value, "Flow and renderer share body geometry");
+
+TEST(hazard_cloud_no_backend_reports_unavailable_and_creates_no_layer)
+{
+ CHECK(!HazardCloud::Supported());
+ CHECK(HazardCloud::CreateLayer() == nullptr);
+}
+
+TEST(hazard_cloud_neutral_palette_and_cache_policy_need_no_device)
+{
+ using HazardCloud::Layer;
+ CHECK_EQ(HazardCloud::TerrainGridSide, 129u);
+ CHECK_EQ(&HazardCloud::defaultPalette(4), &HazardCloud::defaultPalette(0));
+ for (unsigned index = 0; index < 4; ++index) {
+ const HazardCloud::Palette &palette = HazardCloud::defaultPalette(index);
+ CHECK(std::isfinite(palette.main.r) && std::isfinite(palette.shadow.r));
+ CHECK(palette.brightness > 0.0f && palette.brightness <= 2.0f);
+ CHECK(palette.transparency >= 0.0f && palette.transparency <= 1.0f);
+ }
+ HazardCloud::FieldState fields[2] = {
+ {{0, 0, 0}, 40, 18, 1, 0, 1, 0, 0},
+ {{80, 0, 0}, 80, 18, 1, 1, 1, 0, 0}
+ };
+ const std::uint64_t shared = Layer::estimateCacheBytes(nullptr, 0);
+ const std::uint64_t first = Layer::estimateCacheBytes(fields, 1);
+ const std::uint64_t second = Layer::estimateCacheBytes(fields + 1, 1);
+ CHECK(first > shared);
+ CHECK(second > first);
+ CHECK_EQ(Layer::estimateCacheBytes(fields, 2), first + second - shared);
+ const std::uint64_t rejected = (std::numeric_limits<std::uint64_t>::max)();
+ CHECK_EQ(Layer::estimateCacheBytes(nullptr, 1), rejected);
+ CHECK_EQ(Layer::estimateCacheBytes(fields, 3), rejected);
+ fields[0].radius = std::numeric_limits<float>::quiet_NaN();
+ CHECK_EQ(Layer::estimateCacheBytes(fields, 1), rejected);
+}
+
+TEST(hazard_cloud_neutral_flow_advances_and_resets_without_a_renderer)
+{
+ HazardCloudFlow::Flow flow;
+ CHECK(!flow.valid());
+ flow.setDomain(-80, -40, 80, 40);
+ CHECK(flow.valid());
+ const HazardCloud::Body body = {0, 0, 0, 30, 0, 3, 15};
+ for (unsigned step = 0; step < 30; ++step)
+ flow.step(1.0f / 60.0f, &body, 1);
+ CHECK(flow.valid());
+ CHECK_EQ(flow.activeBodies(), 1u);
+ CHECK(flow.maxDisturbance() > 0.0f && flow.maxDisturbance() <= 1.0f);
+ const float disturbance = flow.maxDisturbance();
+ flow.step(0.0f, nullptr, 0);
+ CHECK_EQ(flow.maxDisturbance(), disturbance);
+ flow.reset();
+ CHECK(flow.valid());
+ CHECK_EQ(flow.domainMinX(), -80.0f);
+ CHECK_EQ(flow.domainMaxY(), 40.0f);
+ CHECK_EQ(flow.activeBodies(), 0u);
+ CHECK_EQ(flow.maxDisturbance(), 0.0f);
+ for (unsigned slot = 0; slot < flow.width() * flow.height() * 4; ++slot)
+ if (flow.data()[slot] != 0.0f) {
+ CHECK(false);
+ break;
+ }
+}
diff --git a/GeneralsMD/Code/Tests/test_sdl_gpu_frame.cpp b/GeneralsMD/Code/Tests/test_sdl_gpu_frame.cpp
index 31575db04..3826eab74 100644
--- a/GeneralsMD/Code/Tests/test_sdl_gpu_frame.cpp
+++ b/GeneralsMD/Code/Tests/test_sdl_gpu_frame.cpp
@@ -194,7 +194,8 @@ static float depth_at(const std::vector<uint8_t> &bytes, unsigned int width, uns
static void check_scene_depth_snapshot(SdlGpuFrame *frame)
{
const SdlTarget scene = frame->Back_Buffer_Target();
- if (!(frame->Depth_Usage() & SDL_GPU_TEXTUREUSAGE_SAMPLER)) {
+ CHECK(frame->Supports_Scene_Depth() == bool(frame->Depth_Usage() & SDL_GPU_TEXTUREUSAGE_SAMPLER));
+ if (!frame->Supports_Scene_Depth()) {
CHECK(frame->Scene_Depth(scene) == NULL);
printf("sdl_gpu_frame_selfcheck: sampled depth unavailable; fallback checked\n");
return;