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.

perf(gameclient): render hazard clouds through a shared sdl volume

Olcay Seyganb0e9f004bf47
diff --git a/GeneralsMD/Code/BuildFingerprint.manifest b/GeneralsMD/Code/BuildFingerprint.manifest
index 8cfd739f2..34cfb890f 100644
--- a/GeneralsMD/Code/BuildFingerprint.manifest
+++ b/GeneralsMD/Code/BuildFingerprint.manifest
@@ -2085,6 +2085,9 @@ GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrameSunShadow.cpp
GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloud.cpp
GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudEmbers.cpp
GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudEmbers.h
+GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudShared.cpp
+GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudSharedShader.cpp
+GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudSharedShader.h
GameEngineDevice/Source/PosixDevice/Render/SdlPipelineCache.cpp
GameEngineDevice/Source/PosixDevice/Render/SdlPipelineCache.h
GameEngineDevice/Source/PosixDevice/Render/SdlProgramCache.cpp
@@ -2154,6 +2157,7 @@ GameEngineDevice/Source/W3DDevice/GameClient/HazardCloud.cpp
GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudCore.cpp
GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudFlow.cpp
GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudShader.cpp
+GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudSharedModel.cpp
GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudUnsupported.cpp
GameEngineDevice/Source/W3DDevice/GameClient/HeightMap.cpp
GameEngineDevice/Source/W3DDevice/GameClient/Shaders/MotionBlur.nvv
@@ -2246,9 +2250,12 @@ Libraries/Include/Platform/D3D9PosixMath.h
Libraries/Include/Platform/DoubleClickTime.h
Libraries/Include/Platform/EngineShaderName.h
Libraries/Include/Platform/HazardCloud.h
+Libraries/Include/Platform/HazardCloudBake.h
Libraries/Include/Platform/HazardCloudCore.h
Libraries/Include/Platform/HazardCloudFlow.h
Libraries/Include/Platform/HazardCloudPolicy.h
+Libraries/Include/Platform/HazardCloudShared.h
+Libraries/Include/Platform/HazardCloudSharedModel.h
Libraries/Include/Platform/IsWindows9x.h
Libraries/Include/Platform/LoadTiming.h
Libraries/Include/Platform/MSVCCompat.h
@@ -3405,7 +3412,9 @@ Tests/test_global_new_alignment.cpp
Tests/test_glyph_rasteriser.cpp
Tests/test_ground_marks.cpp
Tests/test_harness.h
+Tests/test_hazard_cloud_bake.cpp
Tests/test_hazard_cloud_policy.cpp
+Tests/test_hazard_cloud_shared.cpp
Tests/test_hostile_map.inc
Tests/test_install_guard.sh
Tests/test_install_root.cpp
diff --git a/GeneralsMD/Code/CMakeLists.txt b/GeneralsMD/Code/CMakeLists.txt
index c6740d581..75d7e3ac7 100644
--- a/GeneralsMD/Code/CMakeLists.txt
+++ b/GeneralsMD/Code/CMakeLists.txt
@@ -1642,7 +1642,9 @@ if(ZH_PLATFORM_POSIX)
# the SDL GPU cloud backend and its runtime capability query.
target_sources(w3ddevice PRIVATE
${ZH_POSIX_RENDER_DIR}/SdlHazardCloud.cpp
- ${ZH_POSIX_RENDER_DIR}/SdlHazardCloudEmbers.cpp)
+ ${ZH_POSIX_RENDER_DIR}/SdlHazardCloudEmbers.cpp
+ ${ZH_POSIX_RENDER_DIR}/SdlHazardCloudShared.cpp
+ ${ZH_POSIX_RENDER_DIR}/SdlHazardCloudSharedShader.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
@@ -2270,6 +2272,19 @@ target_sources(test_hazard_cloud_policy PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudFlow.cpp
${CMAKE_CURRENT_SOURCE_DIR}/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudUnsupported.cpp)
+add_lib_test(test_hazard_cloud_bake)
+target_include_directories(test_hazard_cloud_bake PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/Libraries/Include)
+add_lib_test(test_hazard_cloud_shared)
+set_target_properties(test_hazard_cloud_shared PROPERTIES CXX_STANDARD 17)
+target_include_directories(test_hazard_cloud_shared PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/Libraries/Include)
+target_sources(test_hazard_cloud_shared PRIVATE
+ ${CMAKE_CURRENT_SOURCE_DIR}/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudSharedModel.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloud.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudCore.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudShader.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)
# R1, smooth motion: W3DSmoothMotion.h's blend and verdicts, header-only over WWMath.
@@ -2726,6 +2741,9 @@ target_link_libraries(fs_oracle PRIVATE wwlib wwdebug)
# SKIPPED for that step and says how many it did not check.
find_program(ZH_SPIRV_VAL spirv-val)
add_lib_test(test_shader_sdl ffvertex engineshader sdl3shadercompile)
+target_sources(test_shader_sdl PRIVATE
+ ${CMAKE_CURRENT_SOURCE_DIR}/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudShader.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudSharedShader.cpp)
# Reflect the Linux Modern water blocks against their CPU upload structures.
if(ZH_PLATFORM_LINUX)
target_link_libraries(test_shader_sdl PRIVATE spirv-cross-c)
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudEmbers.cpp b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudEmbers.cpp
index ee7640702..a77e2e9b3 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudEmbers.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudEmbers.cpp
@@ -32,7 +32,7 @@ bool fail(const char *reason)
return false;
}
-bool makeResources(SdlGpuFrame *frame, const SdlTarget &target)
+bool makeResources(SdlGpuFrame *frame)
{
gpu = frame->Device();
std::vector<unsigned char> spirv;
@@ -81,6 +81,13 @@ bool makeResources(SdlGpuFrame *frame, const SdlTarget &target)
} // namespace
+bool initialize(SdlGpuFrame *frame)
+{
+ if (failed || !frame || !frame->Device()) return false;
+ if (!pipeline && !makeResources(frame)) return false;
+ return gpu == frame->Device() || fail("the graphics device was replaced");
+}
+
bool prepare(SdlGpuFrame *frame, const SdlTarget &target,
const HazardCloud::FieldState *fields, unsigned fieldCount)
{
@@ -88,7 +95,7 @@ bool prepare(SdlGpuFrame *frame, const SdlTarget &target,
|| fieldCount > 2 || (fieldCount && !fields)) return false;
for (unsigned i = 0; i < fieldCount; ++i) {
if (!HazardCloud::emberField(fields[i])) continue;
- if (!pipeline && !makeResources(frame, target)) return false;
+ if (!initialize(frame)) return false;
if (gpu != frame->Device()) return fail("the graphics device was replaced");
}
return true;
@@ -97,22 +104,29 @@ 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 HazardCloud::FieldState *fields, unsigned fieldCount,
- float timeSeconds, SDL_GPUTexture *terrainTexture, const bool *terrainEnabled)
+ float timeSeconds, SDL_GPUTexture *terrainTexture, const bool *terrainEnabled,
+ const float *terrainDomain)
{
if (failed) return false;
if (!frame || !frame->Device() || !target.Colour || !target.Depth || !sceneDepth
|| !target.Width || !target.Height || !viewProjection || !viewport
|| fieldCount > 2 || (fieldCount && !fields) || !std::isfinite(timeSeconds))
return fail("invalid rendering inputs");
+ if (terrainDomain) {
+ HazardCloud::EmberConstants check = {};
+ if (!HazardCloud::setEmberTerrainDomain(terrainDomain, check))
+ return fail("invalid shared terrain domain");
+ }
bool active = false;
for (unsigned i = 0; i < fieldCount; ++i) {
if (!HazardCloud::emberField(fields[i])) continue;
- if (!pipeline && !makeResources(frame, target)) return false;
+ if (!initialize(frame)) return false;
if (gpu != frame->Device()) return fail("the preview graphics device was replaced");
HazardCloud::EmberConstants constants;
const unsigned emberCount = HazardCloud::emberConstants(fields[i], i,
terrainTexture && terrainEnabled && terrainEnabled[i], viewProjection, viewport,
timeSeconds, constants);
+ if (terrainDomain) HazardCloud::setEmberTerrainDomain(terrainDomain, constants);
const float pixelConstants[4] = { 1.0f / target.Width, 1.0f / target.Height, 0, 0 };
SdlRecordedDraw draw = {};
draw.Pipeline = pipeline;
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudEmbers.h b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudEmbers.h
index 1c99ea088..26c34f7d7 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudEmbers.h
+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudEmbers.h
@@ -1,4 +1,4 @@
-// Small, procedural burning particles for the isolated cloud preview only.
+// Small, procedural burning particles for nuclear hazard clouds.
// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.
#pragma once
@@ -8,11 +8,15 @@ struct SDL_GPUTexture;
namespace HazardCloud { struct FieldState; }
namespace SdlHazardCloudEmbers {
+// Compile at cloud setup, before a first nuclear field can stall a scene frame.
+bool initialize(SdlGpuFrame *frame);
// Record after the cloud composite, before a heat-distortion scene capture.
// The view/projection is the engine's row-major world-to-clip matrix; viewport
// 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.
+// terrainDomain optionally selects a shared terrain grid over world-space
+// minX,minY,maxX,maxY; otherwise terrainTexture contains the two field grids.
bool prepare(SdlGpuFrame *frame, const SdlTarget &target,
const HazardCloud::FieldState *fields, unsigned fieldCount);
@@ -20,7 +24,7 @@ bool render(SdlGpuFrame *frame, const SdlTarget &target, SDL_GPUTexture *sceneDe
const float viewProjection[16], const float viewport[6],
const HazardCloud::FieldState *fields, unsigned fieldCount,
float timeSeconds, SDL_GPUTexture *terrainTexture = nullptr,
- const bool *terrainEnabled = nullptr);
+ const bool *terrainEnabled = nullptr, const float *terrainDomain = nullptr);
bool validationPassed();
// Call after flushing and waiting for the GPU, before destroying its device.
void shutdown();
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudShared.cpp b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudShared.cpp
new file mode 100644
index 000000000..d572b9054
--- /dev/null
+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudShared.cpp
@@ -0,0 +1,599 @@
+// Shared hazard cloud volume with immutable, incrementally baked snapshots.
+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.
+#include "PreRTS.h"
+#include "Platform/HazardCloudShared.h"
+#include "Platform/HazardCloudSharedModel.h"
+#include "Platform/HazardCloudBake.h"
+#include "SdlHazardCloudSharedShader.h"
+#include "Platform/HazardCloudCore.h"
+#include "SdlGpuFrame.h"
+#include "SdlHazardCloudEmbers.h"
+#include "PosixDevice9.h"
+#include "SdlResourceMirror.h"
+#include "WW3D2/dx8wrapper.h"
+#include "WW3D2/sdl3shadercompile.h"
+#include <SDL3/SDL.h>
+#include <algorithm>
+#include <array>
+#include <cmath>
+#include <cstring>
+#include <vector>
+
+namespace HazardCloudShared {
+namespace {
+struct Constants {
+ HazardCloud::Uniforms common;
+ float minimum[4], maximum[4], grid[4], bins[4], data[4];
+};
+static_assert(sizeof(Constants) == 560, "shared cloud shader constants");
+class CameraCore final : public HazardCloud::LayerCore {
+public:
+ bool initialize() override { initialized = true; return true; }
+ bool render(const HazardCloud::Camera &) override { return false; }
+ std::uint64_t estimatedCacheBytes() const override { return 0; }
+ void shutdown() override {}
+ using LayerCore::buildUniforms;
+};
+constexpr SDL_GPUTextureFormat VolumeFormat = SDL_GPU_TEXTUREFORMAT_R16G16B16A16_FLOAT;
+constexpr SDL_GPUTextureFormat DataFormat = SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
+constexpr unsigned DataWidth = 1024;
+
+bool sceneTarget(SdlGpuFrame *frame, SdlTarget &target, std::string &error)
+{
+ auto *device = dynamic_cast<PosixDevice9 *>(DX8Wrapper::_Get_D3D_Device());
+ if (!device || device->Get_Gpu() != frame) { error = "the shared cloud GPU device was replaced"; return false; }
+ IDirect3DSurface9 *current = nullptr, *back = nullptr, *depth = nullptr;
+ device->GetRenderTarget(0,&current);
+ device->GetBackBuffer(0,0,D3DBACKBUFFER_TYPE_MONO,&back);
+ device->GetDepthStencilSurface(&depth);
+ SdlResourceMirrors *mirrors = device->Get_Mirrors();
+ target = {};
+ if (current && current == back) target = frame->Back_Buffer_Target();
+ else if (current && mirrors) {
+ D3DSURFACE_DESC description;
+ if (current->GetDesc(&description) == D3D_OK) {
+ target.Width = description.Width; target.Height = description.Height;
+ IDirect3DTexture9 *texture = nullptr;
+ if (current->GetContainer(IID_IDirect3DTexture9,reinterpret_cast<void **>(&texture)) == D3D_OK && texture) {
+ IDirect3DSurface9 *level = nullptr;
+ texture->GetSurfaceLevel(0,&level);
+ if (level == current) target.Colour = mirrors->Texture(texture,error);
+ if (level) level->Release();
+ texture->Release();
+ } else target.Colour = mirrors->Surface(current,false,error);
+ }
+ }
+ if (target.Colour && mirrors) {
+ D3DSURFACE_DESC description;
+ if (depth && mirrors->Has_Copy(depth) && depth->GetDesc(&description) == D3D_OK
+ && description.Width == target.Width && description.Height == target.Height)
+ target.Depth = mirrors->Surface(depth,true,error);
+ else target.Depth = frame->Depth_For(target.Width,target.Height);
+ }
+ if (current) current->Release();
+ if (back) back->Release();
+ if (depth) depth->Release();
+ if (!target.Colour || !target.Depth) {
+ if (error.empty()) error = "could not resolve shared cloud scene target";
+ return false;
+ }
+ return true;
+}
+}
+
+class SdlRenderer final : public Renderer {
+public:
+ SdlRenderer();
+ ~SdlRenderer() override;
+ bool initialize(std::string &error) override;
+ bool initialize(SdlGpuFrame *frame, const RendererConfig &config, std::string &error);
+ bool render(const HazardCloud::Camera &camera, const Model &model, float seconds, std::string &error) override;
+ void setTerrain(const float *heights, unsigned side) override;
+ void setHeatEnabled(bool enabled) override;
+ void setBodies(const HazardCloud::Body *bodies, unsigned count) override;
+ void reset() override;
+ void shutdown() override;
+ const RendererStats &stats() const override;
+private:
+ struct Impl;
+ std::unique_ptr<Impl> impl;
+};
+
+struct SdlRenderer::Impl {
+ SdlGpuFrame *frame = nullptr;
+ SDL_GPUDevice *gpu = nullptr;
+ RendererConfig config;
+ RendererStats statistics;
+ CameraCore cameraCore;
+ SDL_GPUShader *vertex = nullptr, *pixels[5] = {};
+ SDL_GPUGraphicsPipeline *pipelines[5] = {};
+ SDL_GPUSampler *point = nullptr, *linear = nullptr;
+ SdlTarget material = {}, low = {}, background = {};
+ struct Snapshot {
+ SdlTarget lighting = {}, sources = {}, bins = {}, indices = {}, flow = {}, terrain = {};
+ std::vector<float> terrainValues;
+ std::vector<Source> fields;
+ Bounds bounds = {};
+ Grid grid;
+ float seconds = 0;
+ unsigned activeSources = 0, terrainSide = 0;
+ bool nuclear = false;
+ std::uint64_t usedBatch = ~std::uint64_t(0);
+ } snapshots[2];
+ unsigned front = 0, pending = 1;
+ bool frontValid = false, baking = false, rebakeRequested = true;
+ BakeSlices progress;
+ long long pendingTick = -1;
+ std::vector<float> terrainValues, previousSources, lastRenderSources;
+ std::vector<HazardCloud::Body> bodies;
+ HazardCloudFlow::Flow wake;
+ unsigned terrainSide = 0;
+ bool terrainDirty = false;
+ long long lastBakeTick = -1;
+ float lastTime = -1;
+ Bounds previousBounds = {};
+ bool boundsValid = false;
+ std::uint64_t usedBatch = ~std::uint64_t(0);
+
+ void invalidate()
+ {
+ frontValid = baking = false;
+ rebakeRequested = true;
+ progress.cancel();
+ lastBakeTick = -1;
+ statistics.bakedSources = statistics.pendingSlices = 0;
+ statistics.publicationAgeSeconds = 0;
+ }
+ void constantsFor(Constants &constants, const Snapshot &snapshot) const
+ {
+ const Bounds &bounds = snapshot.bounds;
+ const Grid &grid = snapshot.grid;
+ constants.common.Scene[3] = snapshot.seconds; constants.common.Settings[0] = 1;
+ constants.common.Interaction[0] = bounds.minX; constants.common.Interaction[1] = bounds.minY;
+ constants.common.Interaction[2] = 1.0f / (bounds.maxX - bounds.minX);
+ constants.common.Interaction[3] = 1.0f / (bounds.maxY - bounds.minY);
+ constants.common.FlowSettings[0] = 1;
+ constants.common.FlowSettings[1] = HazardCloud::MaximumDisplacement;
+ constants.minimum[0] = bounds.minX; constants.minimum[1] = bounds.minY; constants.minimum[2] = bounds.minZ;
+ constants.maximum[0] = bounds.maxX; constants.maximum[1] = bounds.maxY; constants.maximum[2] = bounds.maxZ;
+ constants.grid[0] = config.volumeSide; constants.grid[1] = config.slices;
+ constants.grid[2] = 6; constants.grid[3] = config.slices / 6;
+ constants.bins[0] = grid.minX; constants.bins[1] = grid.minY;
+ constants.bins[2] = grid.cellSize; constants.bins[3] = grid.width;
+ constants.data[0] = grid.height; constants.data[1] = snapshot.fields.size();
+ constants.data[2] = snapshot.terrainSide;
+ }
+ void updateMetadataBytes()
+ {
+ statistics.metadataBytes = 0;
+ for (const auto &snapshot : snapshots) {
+ statistics.metadataBytes += std::uint64_t(snapshot.terrain.Width) * snapshot.terrain.Height * 4;
+ const SdlTarget *targets[] = {&snapshot.sources, &snapshot.bins, &snapshot.indices, &snapshot.flow};
+ for (const auto *target : targets)
+ statistics.metadataBytes += std::uint64_t(target->Width) * target->Height * 16;
+ }
+ }
+
+ void retire(SdlTarget &target)
+ {
+ if (target.Colour) frame->Release_After_Batch(target.Colour, nullptr);
+ target = {};
+ }
+ bool texture(SdlTarget &target, unsigned width, unsigned height, SDL_GPUTextureFormat format,
+ bool renderable, std::string &error)
+ {
+ if (target.Colour && target.Width == width && target.Height == height) return true;
+ SDL_GPUTextureCreateInfo info = {};
+ info.type = SDL_GPU_TEXTURETYPE_2D;
+ info.format = format;
+ info.usage = SDL_GPU_TEXTUREUSAGE_SAMPLER | (renderable ? SDL_GPU_TEXTUREUSAGE_COLOR_TARGET : 0);
+ info.width = width; info.height = height;
+ info.layer_count_or_depth = info.num_levels = 1;
+ info.sample_count = SDL_GPU_SAMPLECOUNT_1;
+ SDL_GPUTexture *made = SDL_CreateGPUTexture(gpu, &info);
+ if (!made) { error = SDL_GetError(); return false; }
+ retire(target);
+ target = {made, nullptr, width, height};
+ return true;
+ }
+ bool upload(SdlTarget &target, const std::vector<float> &values, unsigned width,
+ unsigned components, std::string &error)
+ {
+ const unsigned texels = std::max<std::size_t>(1, (values.size() + components - 1) / components);
+ const unsigned height = (texels + width - 1) / width;
+ if (!texture(target, width, height, components == 1 ? SDL_GPU_TEXTUREFORMAT_R32_FLOAT : DataFormat,
+ false, error)) return false;
+ const unsigned bytes = width * height * components * sizeof(float);
+ std::uint32_t offset = 0;
+ void *destination = frame->Upload_Space(bytes, offset);
+ std::memset(destination, 0, bytes);
+ if (!values.empty()) std::memcpy(destination, values.data(), values.size() * sizeof(float));
+ frame->Queue_Texture_Upload(target.Colour, 0, width, height, offset);
+ return true;
+ }
+ bool programs(std::string &error)
+ {
+ std::vector<unsigned char> spirv;
+ if (!SDL3_Compile_HLSL_To_SPIRV(HazardCloud::vertexShader(), true, spirv, error)
+ || !(vertex = SDL3_Create_Shader(gpu, spirv, true, error))) return false;
+ for (unsigned i = 0; i < 5; ++i) {
+ if (!SDL3_Compile_HLSL_To_SPIRV(sharedPixelShader(static_cast<ShaderPass>(i)), false, spirv, error)
+ || !(pixels[i] = SDL3_Create_Shader(gpu, spirv, false, error))) {
+ error = "shared cloud shader " + std::to_string(i) + ": " + error;
+ return false;
+ }
+ SDL_GPUColorTargetDescription colour = {};
+ colour.format = i < 3 ? VolumeFormat : static_cast<SDL_GPUTextureFormat>(SdlGpuFrame::Target_Format());
+ if (i >= 3) {
+ auto &blend = colour.blend_state;
+ blend.enable_blend = true;
+ blend.src_color_blendfactor = blend.src_alpha_blendfactor = SDL_GPU_BLENDFACTOR_ONE;
+ blend.dst_color_blendfactor = blend.dst_alpha_blendfactor = SDL_GPU_BLENDFACTOR_ONE_MINUS_SRC_ALPHA;
+ blend.color_blend_op = blend.alpha_blend_op = SDL_GPU_BLENDOP_ADD;
+ }
+ SDL_GPUGraphicsPipelineCreateInfo description = {};
+ description.vertex_shader = vertex; description.fragment_shader = pixels[i];
+ description.primitive_type = SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;
+ description.rasterizer_state.fill_mode = SDL_GPU_FILLMODE_FILL;
+ description.rasterizer_state.cull_mode = SDL_GPU_CULLMODE_NONE;
+ description.depth_stencil_state.compare_op = SDL_GPU_COMPAREOP_ALWAYS;
+ description.target_info.color_target_descriptions = &colour;
+ description.target_info.num_color_targets = 1;
+ description.target_info.has_depth_stencil_target = i >= 3;
+ description.target_info.depth_stencil_format = i >= 3
+ ? static_cast<SDL_GPUTextureFormat>(frame->Depth_Format()) : SDL_GPU_TEXTUREFORMAT_INVALID;
+ pipelines[i] = SDL_CreateGPUGraphicsPipeline(gpu, &description);
+ if (!pipelines[i]) { error = SDL_GetError(); return false; }
+ }
+ SDL_GPUSamplerCreateInfo sampler = {};
+ sampler.min_filter = sampler.mag_filter = SDL_GPU_FILTER_NEAREST;
+ sampler.mipmap_mode = SDL_GPU_SAMPLERMIPMAPMODE_NEAREST;
+ sampler.address_mode_u = sampler.address_mode_v = sampler.address_mode_w = SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
+ point = SDL_CreateGPUSampler(gpu, &sampler);
+ sampler.min_filter = sampler.mag_filter = SDL_GPU_FILTER_LINEAR;
+ linear = SDL_CreateGPUSampler(gpu, &sampler);
+ if (!point || !linear) { error = SDL_GetError(); return false; }
+ return true;
+ }
+ void draw(unsigned pass, const SdlTarget &target, SDL_GPUTexture *depth, const Constants &constants,
+ std::uint32_t vertexOffset, const HazardCloud::Camera &camera, Snapshot &snapshot,
+ unsigned slice = ~0u)
+ {
+ SdlRecordedDraw command = {};
+ command.Pipeline = pipelines[pass]; command.VertexOffset = vertexOffset; command.Count = 3;
+ command.PixelConstants = frame->Constants(1, &constants, sizeof(constants));
+ command.PixelConstantsSize = sizeof(constants);
+ command.SamplerCount = 10;
+ SDL_GPUTexture *placeholder = snapshot.sources.Colour;
+ for (unsigned i = 0; i < 10; ++i) { command.Textures[i] = placeholder; command.Samplers[i] = point; }
+ command.Textures[0] = depth;
+ command.Textures[1] = snapshot.flow.Colour;
+ command.Textures[2] = pass >= 3 ? low.Colour : placeholder;
+ command.Textures[3] = pass >= 1 ? material.Colour : placeholder;
+ command.Textures[4] = pass >= 2 ? snapshot.lighting.Colour : placeholder;
+ command.Textures[5] = pass == 4 ? background.Colour : placeholder;
+ command.Textures[6] = snapshot.terrainSide ? snapshot.terrain.Colour : placeholder;
+ command.Textures[7] = snapshot.sources.Colour; command.Textures[8] = snapshot.bins.Colour;
+ command.Textures[9] = snapshot.indices.Colour;
+ if (pass >= 1) command.Samplers[3] = linear;
+ if (pass >= 2) command.Samplers[4] = linear;
+ if (pass == 4) command.Samplers[5] = linear;
+ if (pass >= 3) {
+ std::copy(constants.common.Viewport, constants.common.Viewport + 4, command.Viewport);
+ command.Viewport[4] = camera.minZ; command.Viewport[5] = camera.maxZ;
+ command.Scissor[0] = (std::min)(camera.x,target.Width);
+ command.Scissor[1] = (std::min)(camera.y,target.Height);
+ command.Scissor[2] = (std::min)(camera.width,target.Width - command.Scissor[0]);
+ command.Scissor[3] = (std::min)(camera.height,target.Height - command.Scissor[1]);
+ } else {
+ command.Viewport[2] = target.Width; command.Viewport[3] = target.Height; command.Viewport[5] = 1;
+ command.Scissor[2] = target.Width; command.Scissor[3] = target.Height;
+ if (pass == 0 && slice != ~0u) {
+ // Preserve atlas-global SV_Position; only limit shaded pixels.
+ command.Scissor[0] = (slice % 6) * config.volumeSide;
+ command.Scissor[1] = (slice / 6) * config.volumeSide;
+ command.Scissor[2] = command.Scissor[3] = config.volumeSide;
+ }
+ }
+ frame->Set_Target(target);
+ // Injection overwrites every tile, and lighting overwrites its complete
+ // target. Clearing an atlas here would erase earlier slices in the job.
+ if (pass == 2) frame->Clear_Back_Buffer(true,false,false,0,1,0);
+ frame->Record_Draw(command);
+ snapshot.usedBatch = frame->Batch();
+ }
+};
+
+SdlRenderer::SdlRenderer() : impl(new Impl) {}
+SdlRenderer::~SdlRenderer() { shutdown(); }
+bool SdlRenderer::initialize(std::string &error)
+{
+ auto *device = dynamic_cast<PosixDevice9 *>(DX8Wrapper::_Get_D3D_Device());
+ if (!device || !device->Get_Gpu()) {
+ error = "shared clouds require the current SDL GPU device";
+ return false;
+ }
+ return initialize(device->Get_Gpu(), RendererConfig{}, error);
+}
+bool SdlRenderer::initialize(SdlGpuFrame *frame, const RendererConfig &config, std::string &error)
+{
+ shutdown();
+ if (!frame || !frame->Device() || config.volumeSide < 32 || config.volumeSide > 512
+ || config.slices < 6 || config.slices > 96 || config.slices % 6
+ || !std::isfinite(config.binCellSize) || config.binCellSize <= 0
+ || !std::isfinite(config.bakesPerSecond) || config.bakesPerSecond <= 0
+ || !config.bakeSlicesPerFrame) {
+ error = "invalid shared-volume renderer configuration"; return false;
+ }
+ impl.reset(new Impl);
+ impl->frame = frame; impl->gpu = frame->Device(); impl->config = config;
+ impl->cameraCore.setFlowDomain(-1,-1,1,1);
+ impl->cameraCore.initialize();
+ if (config.embers && !SdlHazardCloudEmbers::initialize(frame)) {
+ error = "nuclear ember initialization failed";
+ shutdown(); return false;
+ }
+ const unsigned width = config.volumeSide * 6, height = config.volumeSide * (config.slices / 6);
+ if (!impl->programs(error)
+ || !impl->texture(impl->material,width,height,VolumeFormat,true,error)
+ || !impl->texture(impl->snapshots[0].lighting,width,height,VolumeFormat,true,error)
+ || !impl->texture(impl->snapshots[1].lighting,width,height,VolumeFormat,true,error)) {
+ shutdown(); return false;
+ }
+ impl->statistics.volumeBytes = std::uint64_t(config.volumeSide) * config.volumeSide * config.slices * 24;
+ return true;
+}
+
+void SdlRenderer::setTerrain(const float *heights, unsigned side)
+{
+ if (heights && side >= 2) impl->terrainValues.assign(heights,heights + std::size_t(side) * side);
+ else impl->terrainValues.clear();
+ impl->terrainSide = impl->terrainValues.empty() ? 0 : side;
+ impl->terrainDirty = true;
+}
+void SdlRenderer::setHeatEnabled(bool enabled) { impl->config.heat = enabled; }
+void SdlRenderer::setBodies(const HazardCloud::Body *bodies, unsigned count)
+{
+ if (bodies && count) impl->bodies.assign(bodies,bodies + count);
+ else impl->bodies.clear();
+}
+void SdlRenderer::reset()
+{
+ impl->wake.reset();
+ impl->invalidate();
+ impl->lastRenderSources.clear();
+ impl->lastTime = -1;
+ impl->statistics.activeBodies = 0;
+ impl->statistics.maxDisturbance = 0;
+}
+const RendererStats &SdlRenderer::stats() const { return impl->statistics; }
+
+bool SdlRenderer::render(const HazardCloud::Camera &camera, const Model &model, float seconds, std::string &error)
+{
+ Impl &p = *impl;
+ if (!p.frame || !p.gpu || !std::isfinite(seconds)) { error = "shared-volume renderer is not initialized"; return false; }
+ SdlTarget target;
+ if (!sceneTarget(p.frame,target,error)) return false;
+ // Even resource/preflight failures must restore the scene target before
+ // the caller records Classic fallback or any subsequent scene geometry.
+ struct RestoreTarget {
+ SdlGpuFrame *frame;
+ SdlTarget target;
+ ~RestoreTarget() { frame->Set_Target(target); }
+ } restore{p.frame, target};
+ SDL_GPUTexture *depth = p.frame->Scene_Depth(target);
+ if (!target.Colour || !depth) { error = "shared-volume renderer needs readable scene depth"; return false; }
+ if (p.frame->Batch_Is_Full() && !p.frame->Flush()) { error = "could not submit scene"; return false; }
+ if (!p.texture(p.low,(target.Width + 1) / 2,(target.Height + 1) / 2,VolumeFormat,true,error)) return false;
+ Bounds bounds = model.bounds();
+ // Model bounds include the taller heat envelope; smoke needs all slices in
+ // its thin slab. Terrain extrema expand it without losing elevated support.
+ float lowZ = bounds.minZ, highZ = lowZ + 0.01f;
+ for (const auto &source : model.sources()) highZ = (std::max)(highZ,source.field.ground.z + source.field.height);
+ if (!p.terrainValues.empty()) {
+ const auto extrema = std::minmax_element(p.terrainValues.begin(),p.terrainValues.end());
+ lowZ = (std::min)(lowZ,*extrema.first);
+ float height = 0;
+ for (const auto &source : model.sources()) height = (std::max)(height,source.field.height);
+ highZ = (std::max)(highZ,*extrema.second + height);
+ }
+ bounds.minZ = lowZ; bounds.maxZ = highZ;
+ const bool domainChanged = !p.boundsValid || std::memcmp(&bounds,&p.previousBounds,sizeof(bounds)) != 0;
+ if (domainChanged) {
+ p.wake.setDomain(bounds.minX,bounds.minY,bounds.maxX,bounds.maxY);
+ p.previousBounds = bounds; p.boundsValid = true;
+ }
+ const float elapsed = p.lastTime >= 0 && seconds >= p.lastTime ? seconds - p.lastTime : 0;
+ const bool rewound = p.lastTime >= 0 && seconds < p.lastTime;
+ if (rewound) p.wake.reset();
+ if (elapsed > 0) p.wake.step(elapsed,p.bodies.empty() ? nullptr : p.bodies.data(),p.bodies.size());
+ p.statistics.activeBodies = p.wake.activeBodies();
+ p.statistics.maxDisturbance = p.wake.maxDisturbance();
+ p.lastTime = seconds;
+ if (!p.wake.valid()) { error = "shared wake simulation is invalid"; return false; }
+ const Grid grid = model.buildBins(p.config.binCellSize);
+ if (!grid.valid()) { error = "shared-volume source bins could not be represented"; return false; }
+ std::vector<float> sourceValues, binValues, indexValues;
+ sourceValues.reserve(model.sources().size() * 16);
+ p.statistics.sources = model.sources().size(); p.statistics.activeSources = 0; p.statistics.maximumBinSources = 0;
+ bool nuclear = false;
+ for (const auto &source : model.sources()) {
+ const auto &field = source.field;
+ if (source.active) { ++p.statistics.activeSources; nuclear |= field.palette >= 0.5f && field.palette < 1.5f; }
+ const float values[] = {field.ground.x,field.ground.y,field.ground.z,field.radius,
+ field.height,source.active ? field.density : 0,field.palette,field.formation,
+ field.release,source.sourceTravel,source.dissipation,source.sourceAge,field.fringe,source.seed,source.terrain ? 1.0f : 0.0f,0};
+ sourceValues.insert(sourceValues.end(),values,values + 16);
+ }
+ for (std::size_t i = 0; i + 1 < grid.offsets.size(); ++i) {
+ const unsigned count = grid.offsets[i + 1] - grid.offsets[i];
+ p.statistics.maximumBinSources = (std::max)(p.statistics.maximumBinSources,count);
+ binValues.insert(binValues.end(),{float(grid.offsets[i]),float(count),0,0});
+ }
+ for (unsigned id : grid.indices) indexValues.push_back(float(id));
+ while (indexValues.size() % 4) indexValues.push_back(0);
+ bool supportChanged = sourceValues.size() != p.previousSources.size();
+ if (!supportChanged) {
+ for (std::size_t i = 0; i < sourceValues.size(); i += 16) {
+ for (unsigned slot : {0u,1u,2u,3u,4u,6u,12u,13u,14u})
+ supportChanged |= sourceValues[i + slot] != p.previousSources[i + slot];
+ }
+ }
+ const long long bakeTick = static_cast<long long>(std::floor(double(seconds) * p.config.bakesPerSecond + 0.0001));
+ const bool pausedChange = elapsed == 0 && sourceValues != p.lastRenderSources;
+ p.rebakeRequested |= domainChanged || p.terrainDirty || supportChanged || pausedChange;
+ p.lastRenderSources = sourceValues;
+ p.previousSources = sourceValues;
+ // Moving supports, births, terrain and domain changes coalesce into the next
+ // snapshot. Never restart immutable partial work: continuous motion must
+ // still publish within ceil(slices / budget) display renders.
+ if (rewound) p.invalidate();
+ Constants constants = {};
+ float viewProjection[16];
+ if (!p.cameraCore.buildUniforms(camera,target.Width,target.Height,constants.common,viewProjection)) {
+ error = "invalid shared-volume scene camera"; return false;
+ }
+ const bool requestBake = !p.frontValid || bakeTick != p.lastBakeTick || p.rebakeRequested;
+ if (!p.baking && requestBake) {
+ auto &snapshot = p.snapshots[p.pending];
+ // Uploads precede ALL draws in a batch. A slot about to become pending
+ // may still have old front users recorded earlier in this same batch.
+ if (snapshot.usedBatch == p.frame->Batch() && !p.frame->Flush()) {
+ error = "could not submit prior shared-volume users"; return false;
+ }
+ if (!p.upload(snapshot.sources,sourceValues,DataWidth,4,error)
+ || !p.upload(snapshot.bins,binValues,DataWidth,4,error)
+ || !p.upload(snapshot.indices,indexValues,DataWidth,4,error)) return false;
+ std::vector<float> wakes(p.wake.data(),p.wake.data() + p.wake.width() * p.wake.height() * 4);
+ if (!p.upload(snapshot.flow,wakes,p.wake.width(),4,error)) return false;
+ ++p.statistics.interactionUploads;
+ snapshot.terrainValues = p.terrainValues;
+ if (p.terrainSide && !p.upload(snapshot.terrain,snapshot.terrainValues,p.terrainSide,1,error)) return false;
+ snapshot.fields = model.sources();
+ snapshot.bounds = bounds; snapshot.grid = grid; snapshot.seconds = seconds;
+ snapshot.activeSources = p.statistics.activeSources; snapshot.nuclear = nuclear;
+ snapshot.terrainSide = p.terrainSide;
+ p.terrainDirty = false;
+ p.pendingTick = bakeTick;
+ p.rebakeRequested = false;
+ p.progress.begin(p.config.slices,p.config.bakeSlicesPerFrame);
+ p.baking = true;
+ p.updateMetadataBytes();
+ }
+ std::uint32_t vertexOffset;
+ std::memset(p.frame->Stage(16,vertexOffset),0,16);
+ if (p.baking) {
+ auto &snapshot = p.snapshots[p.pending];
+ p.constantsFor(constants,snapshot);
+ unsigned written = 0;
+ // The allowance is per display render and never accumulates catch-up debt.
+ while (!p.progress.complete() && written < p.config.bakeSlicesPerFrame) {
+ p.draw(0,p.material,depth,constants,vertexOffset,camera,snapshot,p.progress.next());
+ ++written;
+ }
+ p.statistics.maxSlicesPerFrame = (std::max)(p.statistics.maxSlicesPerFrame,written);
+ if (p.progress.complete()) {
+ // Every material texel belongs to this immutable snapshot before
+ // lighting can sample neighboring slices. Only completed lighting
+ // becomes visible, with its matching source/wake/terrain metadata.
+ p.draw(1,snapshot.lighting,depth,constants,vertexOffset,camera,snapshot);
+ std::swap(p.front,p.pending);
+ p.frontValid = true; p.baking = false;
+ p.lastBakeTick = p.pendingTick;
+ ++p.statistics.bakes;
+ }
+ }
+ p.statistics.pendingSlices = p.baking ? p.progress.remaining() : 0;
+ p.statistics.bakedSources = 0;
+ p.statistics.publicationAgeSeconds = 0;
+ if (p.frontValid && p.statistics.activeSources) {
+ auto &snapshot = p.snapshots[p.front];
+ p.constantsFor(constants,snapshot);
+ p.statistics.bakedSources = snapshot.activeSources;
+ p.statistics.publicationAgeSeconds = (std::max)(0.0f,seconds - snapshot.seconds);
+ if (p.config.heat && snapshot.nuclear
+ && !p.texture(p.background,target.Width,target.Height,
+ static_cast<SDL_GPUTextureFormat>(SdlGpuFrame::Target_Format()),true,error)) return false;
+ if (p.config.embers && snapshot.nuclear) {
+ for (const auto &source : snapshot.fields) {
+ if (!source.active || !HazardCloud::emberField(source.field)) continue;
+ const float emberTime = source.sourceAge + (std::max)(0.0f,seconds - snapshot.seconds);
+ if (!std::isfinite(emberTime)
+ || !SdlHazardCloudEmbers::prepare(p.frame,target,&source.field,1)) {
+ error = "nuclear ember preflight failed";
+ return false;
+ }
+ }
+ }
+ p.draw(2,p.low,depth,constants,vertexOffset,camera,snapshot);
+ p.draw(3,target,depth,constants,vertexOffset,camera,snapshot);
+ if (p.config.embers && snapshot.nuclear) {
+ float viewport[6] = {constants.common.Viewport[0],constants.common.Viewport[1],
+ constants.common.Viewport[2],constants.common.Viewport[3],camera.minZ,camera.maxZ};
+ for (const auto &source : snapshot.fields) {
+ if (!source.active || !HazardCloud::emberField(source.field)) continue;
+ // Keep the published field's support/formation/density, while
+ // advancing billboard phase smoothly between publications.
+ const float emberTime = source.sourceAge + (std::max)(0.0f,seconds - snapshot.seconds);
+ const bool terrainEnabled = source.terrain && snapshot.terrainSide >= 2;
+ const float terrainDomain[4] = {snapshot.bounds.minX,snapshot.bounds.minY,
+ snapshot.bounds.maxX,snapshot.bounds.maxY};
+ if (!SdlHazardCloudEmbers::render(p.frame,target,depth,viewProjection,viewport,
+ &source.field,1,emberTime,snapshot.terrain.Colour,&terrainEnabled,terrainDomain)) {
+ // Preflight covered every failure condition before the cloud draw.
+ // Once scene colour is touched, report consumption to prevent
+ // a duplicate classic fallback if a backend invariant fails.
+ error = "nuclear ember recording failed after preflight";
+ }
+ }
+ }
+ if (p.config.heat && snapshot.nuclear) {
+ const std::int32_t rectangle[4] = {0,0,std::int32_t(target.Width),std::int32_t(target.Height)};
+ p.frame->Record_Blit(target.Colour,rectangle,p.background.Colour,rectangle,false);
+ p.draw(4,target,depth,constants,vertexOffset,camera,snapshot);
+ }
+ }
+ p.frame->Set_Target(target); p.usedBatch = p.frame->Batch();
+ ++p.statistics.frames;
+ return true;
+}
+
+void SdlRenderer::shutdown()
+{
+ if (!impl || !impl->frame || !impl->gpu) return;
+ Impl &p = *impl;
+ auto *device = dynamic_cast<PosixDevice9 *>(DX8Wrapper::_Get_D3D_Device());
+ // A device teardown may precede adapter destruction. Saved frame/GPU
+ // pointers then dangle and must never be dereferenced or released through.
+ if (!device || device->Get_Gpu() != p.frame || device->Get_Gpu()->Device() != p.gpu) {
+ SdlHazardCloudEmbers::abandon();
+ impl.reset(new Impl);
+ return;
+ }
+ p.frame->Flush();
+ SDL_WaitForGPUIdle(p.gpu);
+ SdlHazardCloudEmbers::shutdown();
+ SdlTarget *targets[] = {&p.material,&p.low,&p.background};
+ for (auto *target : targets) if (target->Colour) SDL_ReleaseGPUTexture(p.gpu,target->Colour);
+ for (auto &snapshot : p.snapshots) {
+ SdlTarget *snapshotTargets[] = {&snapshot.lighting,&snapshot.sources,&snapshot.bins,&snapshot.indices,&snapshot.flow,&snapshot.terrain};
+ for (auto *target : snapshotTargets) if (target->Colour) SDL_ReleaseGPUTexture(p.gpu,target->Colour);
+ }
+ for (auto *pipeline : p.pipelines) if (pipeline) SDL_ReleaseGPUGraphicsPipeline(p.gpu,pipeline);
+ for (auto *shader : p.pixels) if (shader) SDL_ReleaseGPUShader(p.gpu,shader);
+ if (p.vertex) SDL_ReleaseGPUShader(p.gpu,p.vertex);
+ if (p.point) SDL_ReleaseGPUSampler(p.gpu,p.point);
+ if (p.linear) SDL_ReleaseGPUSampler(p.gpu,p.linear);
+ impl.reset(new Impl);
+}
+bool Supported()
+{
+ return HazardCloud::Supported();
+}
+
+std::unique_ptr<Renderer> CreateRenderer()
+{
+ if (!Supported()) return nullptr;
+ return std::make_unique<SdlRenderer>();
+}
+} // namespace HazardCloudShared
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudSharedShader.cpp b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudSharedShader.cpp
new file mode 100644
index 000000000..0f1b08827
--- /dev/null
+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudSharedShader.cpp
@@ -0,0 +1,264 @@
+// Shared-grid density, formation and dissipation reuse the approved cloud shader.
+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.
+#include "SdlHazardCloudSharedShader.h"
+#include "Platform/HazardCloudCore.h"
+#include <stdexcept>
+
+namespace HazardCloudShared {
+namespace {
+std::size_t marker(const std::string &text, const char *token, std::size_t from = 0)
+{
+ const auto at = text.find(token, from);
+ if (at == std::string::npos)
+ throw std::runtime_error(std::string("production cloud shader extraction marker changed: ") + token);
+ return at;
+}
+
+void replaceOnce(std::string &text, const char *before, const char *after)
+{
+ const auto at = marker(text, before);
+ if (text.find(before, at + std::char_traits<char>::length(before)) != std::string::npos)
+ throw std::runtime_error(std::string("production cloud shader extraction marker is ambiguous: ") + before);
+ text.replace(at, std::char_traits<char>::length(before), after);
+}
+
+std::string section(const std::string &text, const char *first, const char *last)
+{
+ const auto begin = marker(text, first);
+ const auto end = marker(text, last, begin);
+ return text.substr(begin, end - begin);
+}
+}
+
+std::string sharedPixelShader(ShaderPass pass)
+{
+ const std::string original = HazardCloud::pixelShader(HazardCloud::Pass::Composite, true);
+ std::string prefix = original.substr(0, marker(original, "// Each slice has its own"));
+ const auto constantsEnd = marker(prefix, "};");
+ prefix.insert(constantsEnd, R"HLSL(
+ float4 SharedMin;
+ float4 SharedMax;
+ float4 SharedGrid;
+ float4 SharedBins;
+ float4 SharedData;
+)HLSL");
+ // A single shared support map, or the independent elevated source plane.
+ const auto groundStart = marker(prefix, "float volumeGround(");
+ const auto groundEnd = marker(prefix, "bool volumeInterval(", groundStart);
+ prefix.replace(groundStart, groundEnd - groundStart, R"HLSL(
+float volumeGround(float2 world, float4 field, float4 shape, float fringe, float identity)
+{
+ if (SharedData.z < 2.0 || identity < 0.5) return field.z - shape.x;
+ float2 uv = saturate((world - SharedMin.xy) / (SharedMax.xy - SharedMin.xy));
+ float2 p = uv * (SharedData.z - 1.0), low = floor(p), f = frac(p);
+ int2 a = (int2)low, b = min(a + 1, (int)SharedData.z - 1);
+ float ground = lerp(lerp(TerrainImage.Load(int3(a, 0)), TerrainImage.Load(int3(b.x, a.y, 0)), f.x),
+ lerp(TerrainImage.Load(int3(a.x, b.y, 0)), TerrainImage.Load(int3(b, 0)), f.x), f.y);
+ return ground;
+}
+)HLSL");
+ // Terrain-supported sources share ground and wakes at a voxel, even when
+ // their centre, age, palette and footprint differ. Keep all procedural coordinates and
+ // formation masks from production, supplying only those common inputs.
+ replaceOnce(prefix, " float4 terrain = identity < 0.5 ? Terrain0 : Terrain1;",
+ " float4 terrain = float4(SharedMin.z, SharedMax.z, SharedData.z >= 2.0 && identity >= 0.5 ? 1.0 : 0.0, 0.0);");
+ replaceOnce(prefix,
+ "float volumeDensity(float3 world, float4 field, float4 shape, float4 source, float fringe, float identity)",
+ "float sharedDensity(float3 world, float4 field, float4 shape, float4 source, float fringe, float identity, float ground, float2 displacement)");
+ replaceOnce(prefix,
+ " float ground = volumeGround(world.xy, field, float4(halfHeight, shape.yzw), fringe, identity);\n", "");
+ replaceOnce(prefix,
+ " float2 displacement = volumeInteraction(world.xy).xy;\n"
+ " displacement *= min(1.0, max(FlowSettings.y, 0.0) / max(length(displacement), 0.0001));\n", "");
+ // Broad noise only changes the veil outside the footprint. Folds and fine
+ // noise still erode the bulk, so retain their original evaluations.
+ replaceOnce(prefix, " float broad = volumeNoise(at);",
+ " float broad = 0.0;\n"
+ " [branch] if (hasVeil && outside > 0.0) broad = volumeNoise(at);");
+ replaceOnce(prefix,
+ " coverage *= lerp(1.0, 0.20 + 0.80 * smoothstep(0.20, 0.80, detail), outside);",
+ " if (hasVeil && outside > 0.0)\n"
+ " coverage *= lerp(1.0, 0.20 + 0.80 * smoothstep(0.20, 0.80, detail), outside);");
+ replaceOnce(prefix,
+ " float body = saturate(1.0 - dot(q, q) - z * z + erosion);\n",
+ " float body = saturate(1.0 - dot(q, q) - z * z + erosion);\n"
+ " if (body <= 0.0) continue;\n");
+ std::string source = prefix + R"HLSL(
+Texture2D<float4> SourceData : register(t7, space2);
+SamplerState SourceSampler : register(s7, space2);
+Texture2D<float4> BinData : register(t8, space2);
+SamplerState BinSampler : register(s8, space2);
+Texture2D<float4> IndexData : register(t9, space2);
+SamplerState IndexSampler : register(s9, space2);
+Texture2D<float4> SharedBackground : register(t5, space2);
+SamplerState SharedBackgroundSampler : register(s5, space2);
+
+float4 sourceAt(uint at) { return SourceData.Load(int3(at % 1024, at / 1024, 0)); }
+float4 binAt(uint at) { return BinData.Load(int3(at % 1024, at / 1024, 0)); }
+uint indexAt(uint at)
+{
+ uint texel = at / 4;
+ float4 ids = IndexData.Load(int3(texel % 1024, texel / 1024, 0));
+ return (uint)ids[at % 4];
+}
+float3 atlasWorld(float2 pixel)
+{
+ uint2 p = (uint2)pixel;
+ uint side = (uint)SharedGrid.x, columns = (uint)SharedGrid.z;
+ uint z = p.x / side + p.y / side * columns;
+ float3 voxel = float3(p.x % side, p.y % side, z);
+ return SharedMin.xyz + voxel / float3(side - 1, side - 1, SharedGrid.y - 1) * (SharedMax.xyz - SharedMin.xyz);
+}
+float4 sharedRead(float3 world, bool lit)
+{
+ float3 uv = (world - SharedMin.xyz) / (SharedMax.xyz - SharedMin.xyz);
+ if (any(uv < 0) || any(uv > 1)) return 0;
+ float3 voxel = saturate(uv) * float3(SharedGrid.xx - 1, SharedGrid.y - 1);
+ uint z0 = (uint)floor(voxel.z), z1 = min(z0 + 1, (uint)SharedGrid.y - 1);
+ uint columns = (uint)SharedGrid.z;
+ float2 size = SharedGrid.xx * SharedGrid.zw;
+ float2 a = (float2(z0 % columns, z0 / columns) * SharedGrid.x + voxel.xy + 0.5) / size;
+ float2 b = (float2(z1 % columns, z1 / columns) * SharedGrid.x + voxel.xy + 0.5) / size;
+ if (lit) return lerp(CacheImage1.SampleLevel(CacheSampler1, a, 0), CacheImage1.SampleLevel(CacheSampler1, b, 0), frac(voxel.z));
+ return lerp(CacheImage0.SampleLevel(CacheSampler0, a, 0), CacheImage0.SampleLevel(CacheSampler0, b, 0), frac(voxel.z));
+}
+float4 inject(float3 world)
+{
+ int2 bin = (int2)floor((world.xy - SharedBins.xy) / SharedBins.z);
+ if (any(bin < 0) || bin.x >= (int)SharedBins.w || bin.y >= (int)SharedData.x) return 0;
+ float4 range = binAt((uint)bin.x + (uint)bin.y * (uint)SharedBins.w);
+ if (range.y < 1.0) return 0;
+ float sharedGround = 0.0;
+ if (SharedData.z >= 2.0) sharedGround = volumeGround(world.xy, 0, 0, 0, 1);
+ float2 displacement = volumeInteraction(world.xy).xy;
+ displacement *= min(1.0, max(FlowSettings.y, 0.0) / max(length(displacement), 0.0001));
+ float4 result = 0;
+ // CSR lists are variable length: no fixed per-bin source limit or fallback.
+ [loop] for (uint item = 0; item < (uint)range.y; ++item) {
+ uint id = indexAt((uint)range.x + item);
+ float4 field = sourceAt(id * 4), packed = sourceAt(id * 4 + 1);
+ float4 history = sourceAt(id * 4 + 2), extra = sourceAt(id * 4 + 3);
+ float4 shape = float4(packed.x * 0.5, packed.yzw);
+ field.z += shape.x;
+ float ground = SharedData.z >= 2.0 && extra.z > 0.5 ? sharedGround : field.z - max(shape.x, 0.25);
+ float density = sharedDensity(world, field, shape, history, extra.x, extra.y, ground, displacement);
+ if (density <= 0.00001) continue;
+ uint palette = (uint)clamp(round(shape.z), 0.0, 3.0);
+ float extinction = 0.075 * min(1.8, pow(9.3 / max(shape.x, 0.25), 0.35));
+ extinction *= PaletteShadow[palette].w;
+ float coefficient = density * extinction;
+ float3 colour = PaletteShadow[palette].rgb + PaletteMain[palette].rgb * 0.84;
+ if (palette == 1) {
+ // Production's soot uses the unclamped source support plane.
+ float sootGround = SharedData.z >= 2.0 && extra.z > 0.5 ? sharedGround : field.z - shape.x;
+ float h = saturate((world.z - sootGround) / max(packed.x, 0.5));
+ float age = history.w;
+ float3 at = float3(world.xy * 0.041, h * 1.85) + float3(-0.024 * age, 0.016 * age, -0.17 * age) + float3(12.7,31.4,8.6);
+ float broad = volumeNoise(at), folds = volumeNoise(at * 2.07 + float3(6.1,17.3,4.8));
+ float soot = smoothstep(0.48,0.69,broad * 0.72 + folds * 0.28);
+ soot *= smoothstep(0.06,0.25,h) * smoothstep(0.25,1.10,density / max(shape.y,0.00001));
+ soot *= smoothstep(0.0,1.20,age) * smoothstep(0.05,0.55,shape.w) * (1.0 - 0.60 * saturate(history.z));
+ float3 charcoal = saturate(float3(0.505,0.482,0.437) + PaletteShadow[1].rgb - float3(0.115,0.085,0.030));
+ colour = lerp(colour, charcoal, soot * 0.80);
+ coefficient *= 1.0 + 0.08 * soot;
+ }
+ result.rgb += colour * coefficient * PaletteMain[palette].w;
+ result.a += coefficient;
+ }
+ return result;
+}
+float4 lightVolume(float3 world)
+{
+ float4 material = sharedRead(world, false);
+ if (material.a < 0.00001) return 0;
+ const float3 sun = float3(-0.462,-0.347,0.816);
+ float optical = sharedRead(world + sun * 2.5, false).a * 5.0;
+ optical += sharedRead(world + sun * 8.0, false).a * 10.0;
+ optical += sharedRead(world + sun * 16.0, false).a * 14.0;
+ material.rgb *= 0.12 + 0.88 * exp(-optical * 1.20);
+ return material;
+}
+float4 volumeRaymarch(float2 pixel)
+{
+ float3 origin = volumeWorldAt(pixel,0), direction = normalize(volumeWorldAt(pixel,1) - origin);
+ float3 safe = float3(abs(direction.x) < 1e-6 ? 1e-6 : direction.x,
+ abs(direction.y) < 1e-6 ? 1e-6 : direction.y, abs(direction.z) < 1e-6 ? 1e-6 : direction.z);
+ float3 a = (SharedMin.xyz - origin) / safe, b = (SharedMax.xyz - origin) / safe;
+ float3 nearAxis = min(a,b), farAxis = max(a,b);
+ float first = max(0.0,max(nearAxis.x,max(nearAxis.y,nearAxis.z)));
+ float last = min(farAxis.x,min(farAxis.y,farAxis.z));
+ float depth = SceneDepth.SampleLevel(DepthSampler,pixel * Scene.xy,0).r;
+ if (depth < 0.999999) last = min(last,max(0.0,dot(volumeWorldAt(pixel,depth) - origin,direction)));
+ if (last <= first) return 0;
+ // Fixed integration cost, independent of source count. Sampling follows the
+ // volume's occupied slab, rather than the whole scene's depth range.
+ const int steps = 96;
+ float stride = (last - first) / steps;
+ float jitter = 0.35 + volumeHash(float3(floor(pixel),17)) * 0.30;
+ float transmittance = 1; float3 radiance = 0;
+ [loop] for (int sampleIndex = 0; sampleIndex < steps; ++sampleIndex) {
+ if (transmittance < 0.015) break;
+ float3 world = origin + direction * (first + (sampleIndex + jitter) * stride);
+ float4 coefficient = sharedRead(world,true);
+ if (coefficient.a < 0.000001) continue;
+ float opacity = 1.0 - exp(-coefficient.a * stride);
+ radiance += transmittance * opacity * coefficient.rgb / coefficient.a;
+ transmittance *= 1.0 - opacity;
+ }
+ return float4(radiance,1.0 - transmittance);
+}
+)HLSL";
+ source += section(original, "float2 volumeFullPixel(", "#if CLOUD_COMPOSITE || CLOUD_HEAT_PASS");
+ source += section(original, "float volumeDepthSlope(", "#endif");
+ const std::string hot = HazardCloud::pixelShader(HazardCloud::Pass::Heat, true);
+ source += section(hot, "bool volumeHeatContains(", "bool volumeHeatDepthSafe(");
+ // Keep production's edge-aware reconstruction and exact full-resolution
+ // silhouette fallback, now sampling the shared spatial volume.
+ const auto composite = original.rfind("#else\n if (Settings.z");
+ if (composite == std::string::npos)
+ throw std::runtime_error("production cloud shader composite extraction marker changed");
+ const auto compositeEnd = marker(original, "\n#endif\n}", composite);
+ const std::string body = original.substr(composite + 6, compositeEnd - composite - 6);
+ source += "\nfloat4 main(float4 position : SV_Position) : SV_Target\n{\n";
+ if (pass == ShaderPass::Inject) source += "return inject(atlasWorld(position.xy));\n";
+ else if (pass == ShaderPass::Light) source += "return lightVolume(atlasWorld(position.xy));\n";
+ else if (pass == ShaderPass::Volume) source += "return volumeRaymarch(volumeFullPixel(position.xy));\n";
+ else if (pass == ShaderPass::Composite) source += body;
+ else source += R"HLSL(
+ float depth = SceneDepth.SampleLevel(DepthSampler,position.xy * Scene.xy,0).r;
+ float3 world = volumeWorldAt(position.xy,depth);
+ float3 origin = volumeWorldAt(position.xy,0);
+ float3 direction = normalize(volumeWorldAt(position.xy,1) - origin);
+ float limit = depth < 0.999999 ? max(0.0,dot(world - origin,direction)) : 100000.0;
+ float2 offset = 0;
+ [loop] for (uint id = 0; id < (uint)SharedData.y; ++id) {
+ float4 shapeData = sourceAt(id * 4 + 1);
+ if (shapeData.z < 0.5 || shapeData.z >= 1.5 || shapeData.y < 0.00001) continue;
+ float4 field = sourceAt(id * 4), history = sourceAt(id * 4 + 2), extra = sourceAt(id * 4 + 3);
+ float4 shape = float4(shapeData.x * 0.5,shapeData.yzw);
+ field.z += shape.x;
+ bool immersed = volumeHeatContains(world,field,shape,extra.x,extra.z);
+ offset += volumeHeatOffset(origin,direction,limit,immersed,field,shape,history,extra.x,extra.z);
+ }
+ offset *= 10.0 * clamp(Viewport.w / 800.0,0.65,1.5);
+ float magnitude = length(offset);
+ offset *= min(1.0,8.0 / max(magnitude,0.0001));
+ if (magnitude < 0.01) return 0;
+ float pixelSpan = length(volumeWorldAt(position.xy + float2(1,0),depth) - world);
+ float tolerance = max(0.65,pixelSpan * 0.75);
+ float2 slope = float2(volumeDepthSlope(position.xy,depth,float2(1,0),pixelSpan * 4.0),
+ volumeDepthSlope(position.xy,depth,float2(0,1),pixelSpan * 4.0));
+ [loop] for (int attempt = 0; attempt < 3; ++attempt) {
+ float2 pixel = clamp(position.xy + offset,Viewport.xy,Viewport.xy + Viewport.zw - 1);
+ float movedDepth = SceneDepth.SampleLevel(DepthSampler,pixel * Scene.xy,0).r;
+ float expected = depth + dot(slope,pixel - position.xy);
+ if (length(volumeWorldAt(pixel,movedDepth) - volumeWorldAt(pixel,expected)) <= tolerance)
+ return float4(SharedBackground.SampleLevel(SharedBackgroundSampler,pixel * Scene.xy,0).rgb,1);
+ offset *= 0.5;
+ }
+ return 0;
+)HLSL";
+ source += "}\n";
+ return source;
+}
+}
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudSharedShader.h b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudSharedShader.h
new file mode 100644
index 000000000..01a89b29e
--- /dev/null
+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudSharedShader.h
@@ -0,0 +1,8 @@
+// Shader programs for the shared hazard cloud volume.
+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.
+#pragma once
+#include <string>
+namespace HazardCloudShared {
+enum class ShaderPass { Inject, Light, Volume, Composite, Heat };
+std::string sharedPixelShader(ShaderPass pass);
+}
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/DX11HazardCloud.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/DX11HazardCloud.cpp
index b15f7bc67..966ca2706 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/DX11HazardCloud.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/DX11HazardCloud.cpp
@@ -2,6 +2,7 @@
// GPU backend records, drawn on the context between two of the backend's draws.
// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.
#include "Platform/HazardCloudCore.h"
+#include "Platform/HazardCloudShared.h"
#include "Common/Debug.h"
#include "dx11backend.h"
#include "dx11device.h"
@@ -583,3 +584,10 @@ std::unique_ptr<Layer> CreateLayer()
void ReleaseDevice() { releaseShared(); }
} // namespace HazardCloud
+
+namespace HazardCloudShared {
+
+bool Supported() { return false; }
+std::unique_ptr<Renderer> CreateRenderer() { return nullptr; }
+
+} // namespace HazardCloudShared
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudCore.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudCore.cpp
index 9ee008550..0651e0669 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudCore.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudCore.cpp
@@ -92,6 +92,19 @@ unsigned emberConstants(const FieldState &field, unsigned index, bool terrain,
return count;
}
+bool setEmberTerrainDomain(const float domain[4], EmberConstants &constants)
+{
+ if (!domain) return false;
+ for (unsigned i = 0; i < 4; ++i) if (!std::isfinite(domain[i])) return false;
+ const float width = domain[2] - domain[0], height = domain[3] - domain[1];
+ if (!(width > 0 && height > 0) || !std::isfinite(width) || !std::isfinite(height)
+ || !std::isfinite(1.f / width) || !std::isfinite(1.f / height)) return false;
+ constants.terrain[1] = -1;
+ constants.terrain[2] = domain[0]; constants.terrain[3] = domain[1];
+ constants.scene[2] = 1.f / width; constants.scene[3] = 1.f / height;
+ return true;
+}
+
void LayerCore::fail(const char *reason)
{
if (!failed) std::fprintf(stderr, "hazard-cloud: volumetric renderer FAIL: %s\n", reason);
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudShader.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudShader.cpp
index 57edda403..77e481f50 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudShader.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudShader.cpp
@@ -732,12 +732,15 @@ float emberGround(float2 world)
uint width, height;
TerrainHeight.GetDimensions(width, height);
float side = float(height);
- float2 uv = saturate((world - Field.xy) / max(Terrain.z * 2.0, 0.001) + 0.5);
+ bool sharedGrid = Terrain.y < 0.0;
+ float2 uv = sharedGrid ? saturate((world - Terrain.zw) * Scene.zw)
+ : saturate((world - Field.xy) / max(Terrain.z * 2.0, 0.001) + 0.5);
float2 texel = uv * (side - 1.0);
float2 lower = floor(texel), upper = min(lower + 1.0, side - 1.0);
float2 weight = frac(texel);
- float2 a = (lower + float2(Terrain.y * side, 0) + 0.5) / float2(width, height);
- float2 b = (upper + float2(Terrain.y * side, 0) + 0.5) / float2(width, height);
+ float gridOffset = sharedGrid ? 0.0 : Terrain.y * side;
+ float2 a = (lower + float2(gridOffset, 0) + 0.5) / float2(width, height);
+ float2 b = (upper + float2(gridOffset, 0) + 0.5) / float2(width, height);
float low = lerp(TerrainHeight.SampleLevel(TerrainSampler, a, 0),
TerrainHeight.SampleLevel(TerrainSampler, float2(b.x, a.y), 0), weight.x);
float high = lerp(TerrainHeight.SampleLevel(TerrainSampler, float2(a.x, b.y), 0),
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudSharedModel.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudSharedModel.cpp
new file mode 100644
index 000000000..ef3c0a958
--- /dev/null
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudSharedModel.cpp
@@ -0,0 +1,83 @@
+// Device-free source snapshots and spatial bins for shared hazard clouds.
+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.
+#include "Platform/HazardCloudSharedModel.h"
+#include "Platform/HazardCloudPolicy.h"
+
+#include <algorithm>
+#include <cmath>
+#include <limits>
+
+namespace HazardCloudShared {
+namespace { constexpr float Displacement = 18; }
+
+bool Model::setSources(const std::vector<Source> &sources, const Bounds &bounds)
+{
+ const float coordinates[] = {bounds.minX, bounds.minY, bounds.minZ,
+ bounds.maxX, bounds.maxY, bounds.maxZ};
+ for (float value : coordinates) if (!std::isfinite(value)) return false;
+ if (!(bounds.maxX > bounds.minX && bounds.maxY > bounds.minY && bounds.maxZ > bounds.minZ)
+ || !std::isfinite(bounds.maxX - bounds.minX) || !std::isfinite(bounds.maxY - bounds.minY)
+ || !std::isfinite(bounds.maxZ - bounds.minZ)
+ || sources.size() > (std::numeric_limits<std::uint32_t>::max)()) return false;
+ for (std::size_t i = 0; i < sources.size(); ++i) {
+ const auto &source = sources[i];
+ const auto &field = source.field;
+ const float finite[] = {field.palette, field.release, source.sourceAge, source.sourceTravel,
+ source.dissipation, source.seed, source.born, source.expiry};
+ for (float value : finite) if (!std::isfinite(value)) return false;
+ if (source.id != i || field.palette < 0 || field.palette > 3
+ || field.palette != std::floor(field.palette)
+ || !HazardCloudPolicy::validField(field.ground.x, field.ground.y, field.ground.z,
+ field.radius, field.height, field.density, field.formation, field.fringe, int(field.palette))
+ || field.release < 0 || field.release > 1 || source.sourceAge < 0 || source.sourceTravel < 0
+ || source.dissipation < 0 || source.dissipation > 1 || source.expiry < source.born)
+ return false;
+ }
+ values = sources;
+ domain = bounds;
+ return true;
+}
+
+Grid Model::buildBins(float cellSize) const
+{
+ Grid grid;
+ if (!std::isfinite(cellSize) || cellSize <= 0
+ || domain.maxX <= domain.minX || domain.maxY <= domain.minY) return grid;
+ grid.minX = float(std::floor(double(domain.minX) / cellSize) * cellSize);
+ grid.minY = float(std::floor(double(domain.minY) / cellSize) * cellSize);
+ const double columns = std::floor((double(domain.maxX) - grid.minX) / cellSize) + 1;
+ const double rows = std::floor((double(domain.maxY) - grid.minY) / cellSize) + 1;
+ const auto maxIndex = (std::numeric_limits<std::uint32_t>::max)();
+ if (!std::isfinite(grid.minX) || !std::isfinite(grid.minY) || columns < 1 || rows < 1
+ || columns * rows >= maxIndex) return {};
+ grid.cellSize = cellSize;
+ grid.width = static_cast<unsigned>(columns);
+ grid.height = static_cast<unsigned>(rows);
+ const std::size_t cells = std::size_t(grid.width) * grid.height;
+ grid.offsets.assign(cells + 1, 0);
+ const auto visit = [&](const Source &source, auto emit) {
+ const float reach = source.field.radius + source.field.fringe + Displacement;
+ const auto cell = [cellSize](double point, float origin, unsigned count) {
+ return static_cast<unsigned>(std::clamp(std::floor((point - origin) / cellSize), 0.0, double(count - 1)));
+ };
+ const unsigned loX = cell(double(source.field.ground.x) - reach, grid.minX, grid.width);
+ const unsigned hiX = cell(double(source.field.ground.x) + reach, grid.minX, grid.width);
+ const unsigned loY = cell(double(source.field.ground.y) - reach, grid.minY, grid.height);
+ const unsigned hiY = cell(double(source.field.ground.y) + reach, grid.minY, grid.height);
+ for (unsigned y = loY; y <= hiY; ++y)
+ for (unsigned x = loX; x <= hiX; ++x) emit(std::size_t(y) * grid.width + x);
+ };
+ std::uint64_t total = 0;
+ for (const Source &source : values) if (source.active) {
+ visit(source, [&](std::size_t cell) { ++grid.offsets[cell + 1]; ++total; });
+ if (total > maxIndex) return {};
+ }
+ for (std::size_t cell = 1; cell <= cells; ++cell) grid.offsets[cell] += grid.offsets[cell - 1];
+ grid.indices.resize(static_cast<std::size_t>(total));
+ std::vector<std::uint32_t> cursor(grid.offsets.begin(), grid.offsets.end() - 1);
+ for (const Source &source : values) if (source.active)
+ visit(source, [&](std::size_t cell) { grid.indices[cursor[cell]++] = source.id; });
+ return grid;
+}
+
+} // namespace HazardCloudShared
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudUnsupported.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudUnsupported.cpp
index a71dfadc7..cf563cf31 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudUnsupported.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudUnsupported.cpp
@@ -3,6 +3,7 @@
// The options menu asks the Modern water the same question, answered here the same way.
// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.
#include "Platform/HazardCloud.h"
+#include "Platform/HazardCloudShared.h"
#include "Platform/ModernWaterBuild.h"
namespace HazardCloud {
@@ -18,3 +19,10 @@ namespace ModernWater {
bool Supported() { return false; }
} // namespace ModernWater
+
+namespace HazardCloudShared {
+
+bool Supported() { return false; }
+std::unique_ptr<Renderer> CreateRenderer() { return nullptr; }
+
+} // namespace HazardCloudShared
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp
index 34058ac76..b253062ea 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp
@@ -63,6 +63,9 @@
#include "GameClient/Drawable.h"
#include "Platform/HazardCloudPolicy.h"
#include "Platform/HazardCloud.h"
+#include "Platform/HazardCloudShared.h"
+#include "Platform/HazardCloudSharedModel.h"
+#include <cstdio>
#include <array>
#include <memory>
#include <cmath>
@@ -866,10 +869,12 @@ static const Int FIELD_FADE_GONE = FIELD_FADE_OUT; ///< logic frames, a field
// retail keys, owner choice, grace and initial delay on every platform. Changed
// only at the sync point (fieldCloudsSupported), never in the render, because
// FieldKey ordering reads it and changing it while keys exist invalidates the map.
+static Int s_fieldRenderFrame = 0;
static bool s_fieldCloudsSupported = false;
static bool s_fieldCloudCapability = false; ///< the device's answer, asked once per device
static bool s_fieldCloudCapabilityKnown = false;
static bool fieldCloudsSupported();
+namespace { bool warmSharedClouds(); }
static const Real FIELD_OBJECT_REACH = 5.0f; ///< how near the field's centre its object stands
@@ -909,6 +914,8 @@ struct FieldState
Real cloudShown, cloudFormation, cloudGoneDensity, cloudGoneFormation, cloudRevealFrom;
Int cloudGoneAt, cloudRevealAt;
Int cloudDieFrame; ///< owner's LifetimeUpdate die frame at the last sync point, or -1
+ Real cloudTravel, cloudPeak, cloudUpdated;
+ Bool cloudHistory; ///< source history advances even outside the camera
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
@@ -947,9 +954,11 @@ static bool fieldCloudsSupported()
// The programs every layer shares are built here, on the shell map or a match's first frame,
// or the frame the style is switched: built by the first hazard instead, a program the shader
// cache lacked froze that frame for three and a half seconds of FXC.
- if (volumetric && (newDevice || !s_fieldCloudsSupported))
- if (std::unique_ptr<HazardCloud::Layer> layer = HazardCloud::CreateLayer())
+ if (volumetric && (newDevice || !s_fieldCloudsSupported)) {
+ if (HazardCloudShared::Supported()) warmSharedClouds();
+ else if (std::unique_ptr<HazardCloud::Layer> layer = HazardCloud::CreateLayer())
layer->initialize();
+ }
// A new device, or the style switched: destroy keys before changing their
// comparator's mode.
if (volumetric != s_fieldCloudsSupported) {
@@ -1111,6 +1120,27 @@ struct CloudLayer {
bool terrainValid = false;
};
std::array<CloudLayer, MaxCloudLayers> s_cloudLayers;
+std::unique_ptr<HazardCloudShared::Renderer> s_sharedCloud;
+HazardCloudShared::Model s_sharedCloudModel;
+std::map<FieldKey, HazardCloudShared::Source> s_sharedCloudFields;
+HazardCloudShared::Bounds s_sharedCloudBounds = {};
+float s_sharedTerrainChecked = -100;
+bool s_sharedTerrainValid = false, s_sharedCloudReady = false, s_sharedCloudFailed = false;
+bool warmSharedClouds()
+{
+ if (s_sharedCloud) return true;
+ if (s_sharedCloudFailed) return false;
+ auto renderer = HazardCloudShared::CreateRenderer();
+ if (!renderer) return false;
+ std::string error;
+ if (!renderer->initialize(error)) {
+ std::fprintf(stderr, "hazard-cloud: shared renderer initialization failed: %s\n", error.c_str());
+ s_sharedCloudFailed = true;
+ return false;
+ }
+ s_sharedCloud = std::move(renderer);
+ return true;
+}
unsigned s_cloudPass = 0, s_cloudDraws = 0;
struct CloudWalker { Coord3D position; HazardCloud::Body body; unsigned frame; };
std::map<ObjectID, CloudWalker> s_cloudWalkers;
@@ -1132,6 +1162,11 @@ bool modernCloudsEnabled()
void releaseCloudLayers()
{
for (auto &slot : s_cloudLayers) slot = CloudLayer{};
+ if (s_sharedCloud) s_sharedCloud->reset();
+ s_sharedCloudFields.clear();
+ s_sharedCloudReady = false;
+ s_sharedTerrainChecked = -100;
+ s_sharedTerrainValid = false;
s_cloudWalkers.clear();
s_cloudBodies.clear();
s_cloudBodyFrame = ~0u;
@@ -1226,21 +1261,19 @@ HazardCloud::Camera cloudCamera(CameraClass &camera)
return result;
}
-bool drawModernCloud(const FieldKey &key, FieldState &state, float fade, float seconds, int now,
- const HazardCloud::Camera &camera)
+bool prepareModernCloud(const FieldKey &key, FieldState &state, int now,
+ HazardCloud::FieldState &field, bool &onGround)
{
- 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);
// 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 lifetime = age + left;
const auto buildup = HazardCloudPolicy::visualBuildup(key.palette, state.radius >= 100.f, age, lifetime);
- HazardCloud::FieldState field = {};
+ 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;
+ const float ground = TheTerrainRenderObject->getDrawHeight(state.centre.x, state.centre.y);
+ onGround = state.centre.z - ground < FIELD_ON_GROUND;
if (onGround) field.ground.z = ground;
field.radius = state.radius;
field.height = 18.61f; // Approved infantry-height cloud from the shared preview.
@@ -1274,6 +1307,121 @@ bool drawModernCloud(const FieldKey &key, FieldState &state, float fade, float s
state.cloudFormation = field.formation;
if (!HazardCloudPolicy::validField(field.ground.x, field.ground.y, field.ground.z, field.radius,
field.height, field.density, field.formation, field.fringe, key.palette)) return false;
+ return true;
+}
+
+void drawSharedClouds(const AABoxClass &view, const HazardCloud::Camera &camera, float seconds, int now)
+{
+ s_sharedCloudFields.clear();
+ s_sharedCloudReady = false;
+ if (!modernCloudsEnabled() || !HazardCloudShared::Supported()) return;
+ std::vector<HazardCloudShared::Source> sources;
+ HazardCloudShared::Bounds bounds = {};
+ bool haveBounds = false;
+ for (auto &entry : s_fieldStates) {
+ const auto &key = entry.first;
+ auto &state = entry.second;
+ if (key.palette < 0) continue;
+ HazardCloudShared::Source source;
+ bool onGround = false;
+ if (!prepareModernCloud(key, state, now, source.field, onGround)) continue;
+ if (!state.cloudHistory || seconds < state.cloudUpdated) {
+ state.cloudTravel = state.cloudPeak = 0;
+ state.cloudUpdated = seconds;
+ state.cloudHistory = TRUE;
+ }
+ state.cloudTravel += (seconds - state.cloudUpdated) * source.field.release * 22.f;
+ state.cloudUpdated = seconds;
+ state.cloudPeak = (std::max)(state.cloudPeak, source.field.density);
+ source.sourceAge = (std::max)(0.f, seconds - float(state.visualBorn) / LOGICFRAMES_PER_SECOND);
+ source.sourceTravel = state.cloudTravel;
+ source.dissipation = state.cloudPeak > .0001f ? (std::max)(0.f, 1.f - source.field.density / state.cloudPeak) : 0;
+ source.terrain = onGround;
+ source.born = float(state.visualBorn) / LOGICFRAMES_PER_SECOND;
+ source.expiry = float(state.cloudDieFrame >= 0 ? state.cloudDieFrame : state.particleEnd) / LOGICFRAMES_PER_SECOND;
+ source.active = state.lifeFade * state.stealth > 0 && source.field.density > .00001f;
+ const float reach = source.field.radius + source.field.fringe + 18.f;
+ const bool visible = std::fabs(state.centre.x - view.Center.X) <= view.Extent.X + reach
+ && std::fabs(state.centre.y - view.Center.Y) <= view.Extent.Y + reach;
+ if (!visible || state.lifeFade * state.stealth <= 0) continue;
+ source.id = static_cast<unsigned>(sources.size());
+ s_sharedCloudFields.emplace(key, source);
+ sources.push_back(source);
+ const float x = source.field.ground.x, y = source.field.ground.y, z = source.field.ground.z;
+ if (!haveBounds) { bounds = {x - reach, y - reach, x + reach, y + reach, z, z + source.field.height * 2.6f}; haveBounds = true; }
+ else {
+ bounds.minX = (std::min)(bounds.minX, x - reach); bounds.maxX = (std::max)(bounds.maxX, x + reach);
+ bounds.minY = (std::min)(bounds.minY, y - reach); bounds.maxY = (std::max)(bounds.maxY, y + reach);
+ bounds.minZ = (std::min)(bounds.minZ, z); bounds.maxZ = (std::max)(bounds.maxZ, z + source.field.height * 2.6f);
+ }
+ }
+ if (!haveBounds) {
+ if (s_sharedCloud) s_sharedCloud->reset();
+ return;
+ }
+ if (!warmSharedClouds()) return;
+ // Quantization stabilizes the local volume and terrain grid as source
+ // positions drift. Distant offscreen clouds cannot dilute voxel resolution.
+ bounds.minX = std::floor(bounds.minX / 128.f) * 128.f;
+ bounds.minY = std::floor(bounds.minY / 128.f) * 128.f;
+ bounds.maxX = std::ceil(bounds.maxX / 128.f) * 128.f;
+ bounds.maxY = std::ceil(bounds.maxY / 128.f) * 128.f;
+ const bool domainChanged = bounds.minX != s_sharedCloudBounds.minX || bounds.minY != s_sharedCloudBounds.minY
+ || bounds.maxX != s_sharedCloudBounds.maxX || bounds.maxY != s_sharedCloudBounds.maxY;
+ if (!s_sharedTerrainValid || domainChanged || seconds < s_sharedTerrainChecked || seconds - s_sharedTerrainChecked >= 1.f) {
+ constexpr unsigned side = HazardCloud::TerrainGridSide;
+ std::array<float, side * side> heights;
+ s_sharedTerrainValid = true;
+ for (unsigned y = 0; y < side && s_sharedTerrainValid; ++y) for (unsigned x = 0; x < side; ++x) {
+ const float z = TheTerrainRenderObject->getDrawHeight(
+ bounds.minX + (bounds.maxX - bounds.minX) * x / (side - 1),
+ bounds.minY + (bounds.maxY - bounds.minY) * y / (side - 1));
+ if (!std::isfinite(z)) { s_sharedTerrainValid = false; break; }
+ heights[y * side + x] = z;
+ }
+ if (s_sharedTerrainValid) s_sharedCloud->setTerrain(heights.data(), side);
+ s_sharedTerrainChecked = seconds;
+ s_sharedCloudBounds = bounds;
+ }
+ if (!s_sharedTerrainValid || !s_sharedCloudModel.setSources(sources, bounds)) return;
+ std::vector<HazardCloud::Body> bodies;
+ for (const auto &body : s_cloudBodies) {
+ for (const auto &source : sources) {
+ if (!source.active) continue;
+ const auto &field = source.field;
+ const float dx = body.x - field.ground.x, dy = body.y - field.ground.y;
+ const float reach = field.radius + field.fringe + body.radius;
+ if (dx * dx + dy * dy > reach * reach) continue;
+ const float ground = source.terrain ? TheTerrainRenderObject->getDrawHeight(body.x, body.y) : field.ground.z;
+ if (std::fabs(body.z - ground) < field.height) { bodies.push_back(body); break; }
+ }
+ }
+ // The wake solver retains its 32-body work bound. Moving infantry gets the
+ // allowance before stationary bodies, which do not stir the smoke.
+ std::stable_sort(bodies.begin(), bodies.end(), [](const HazardCloud::Body &a, const HazardCloud::Body &b) {
+ return a.vx * a.vx + a.vy * a.vy > b.vx * b.vx + b.vy * b.vy;
+ });
+ if (bodies.size() > 32) bodies.resize(32);
+ s_sharedCloud->setBodies(bodies.data(), static_cast<unsigned>(bodies.size()));
+ s_sharedCloud->setHeatEnabled(TheGlobalData->m_useHeatEffects != FALSE);
+ std::string error;
+ s_sharedCloudReady = s_sharedCloud->render(camera, s_sharedCloudModel, seconds, error);
+}
+
+bool drawModernCloud(const FieldKey &key, FieldState &state, float fade, float seconds, int now,
+ const HazardCloud::Camera &camera)
+{
+ if (!modernCloudsEnabled() || key.palette < 0) return false;
+ if (HazardCloudShared::Supported()) {
+ const auto entry = s_sharedCloudFields.find(key);
+ if (entry == s_sharedCloudFields.end()) return false;
+ if (entry->second.field.density <= .00001f) return true;
+ return s_sharedCloudReady;
+ }
+ if (s_cloudDraws >= MaxCloudLayers) return false;
+ HazardCloud::FieldState field = {};
+ bool onGround = false;
+ if (!prepareModernCloud(key, state, now, field, onGround)) return false;
// A fully faded modern field is intentionally invisible. Drawing Classic
// here would flash its puddle back during buildup/cleanup boundary frames.
if (field.density <= .00001f) return true;
@@ -1496,13 +1644,14 @@ static void updateGroundFields( const std::vector<ParticleSystem *> &systems )
* draws them. Returns the puddles laid. */
static Int collectGroundFields( const AABoxClass &view, CameraClass &sceneCamera )
{
- const Int now = (Int)TheGameLogic->getFrame();
+ const Int now = s_fieldRenderFrame;
// between the last two logic ticks, as the models are, so a pulse does not step at the logic rate
const Real seconds = ((Real)now + (TheSmoothMotionActive ? TheSmoothMotionAlpha : 0.0f)) / LOGICFRAMES_PER_SECOND;
s_fieldPuddles.clear();
s_fieldDraws.clear();
beginCloudPass(now);
const HazardCloud::Camera camera = cloudCamera( sceneCamera );
+ drawSharedClouds(view, camera, seconds, now);
Int laid = 0;
for (std::map<FieldKey, FieldState>::iterator st = s_fieldStates.begin(); st != s_fieldStates.end(); ++st)
@@ -1908,6 +2057,8 @@ void W3DParticleSystemManager::invalidateGroundFields(bool fadeIn)
void W3DParticleSystemManager::releaseCloudResources()
{
releaseCloudLayers();
+ s_sharedCloud.reset();
+ s_sharedCloudFailed = false;
HazardCloud::ReleaseDevice();
// Query the replacement device at the next sync point. The helper clears
// keys before changing their ordering if support changed; unchanged support
@@ -1927,6 +2078,7 @@ void W3DParticleSystemManager::releaseGpuResources()
* render; the render's own refreshFrameView finds the view still valid. */
void W3DParticleSystemManager::takeReadsForRender( void )
{
+ s_fieldRenderFrame = (Int)TheGameLogic->getFrame();
refreshFrameView();
updateGroundFields( m_fieldSystems );
}
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/HazardCloudBake.h b/GeneralsMD/Code/Libraries/Include/Platform/HazardCloudBake.h
new file mode 100644
index 000000000..9e0180691
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/HazardCloudBake.h
@@ -0,0 +1,36 @@
+// Device-free bounded slice traversal for shared hazard cloud snapshots.
+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.
+#pragma once
+
+namespace HazardCloudShared {
+
+class BakeSlices {
+public:
+ void begin(unsigned slices, unsigned perFrame)
+ {
+ total = slices;
+ completed = 0;
+ // Each residue class contains at most perFrame slices. Visiting one
+ // class per render spreads its work over the volume's full height.
+ stride = slices && perFrame ? 1 + (slices - 1) / perFrame : 1;
+ }
+ void cancel() { total = completed = 0; stride = 1; }
+ unsigned remaining() const { return total - completed; }
+ bool complete() const { return completed == total; }
+ unsigned next()
+ {
+ if (complete()) return total;
+ unsigned ordinal = completed++;
+ for (unsigned residue = 0; residue < stride; ++residue) {
+ const unsigned count = residue < total ? 1 + (total - 1 - residue) / stride : 0;
+ if (ordinal < count) return residue + ordinal * stride;
+ ordinal -= count;
+ }
+ return total; // Unreachable for an unfinished traversal.
+ }
+
+private:
+ unsigned total = 0, completed = 0, stride = 1;
+};
+
+} // namespace HazardCloudShared
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/HazardCloudCore.h b/GeneralsMD/Code/Libraries/Include/Platform/HazardCloudCore.h
index 841a85b20..d956b87d3 100644
--- a/GeneralsMD/Code/Libraries/Include/Platform/HazardCloudCore.h
+++ b/GeneralsMD/Code/Libraries/Include/Platform/HazardCloudCore.h
@@ -70,6 +70,9 @@ unsigned emberConstants(const FieldState &field, unsigned index, bool terrain,
const float viewProjection[16], const float viewport[4],
float timeSeconds, EmberConstants &constants);
+// Use a shared world-space support map for SDL embers. Legacy constants stay intact.
+bool setEmberTerrainDomain(const float domain[4], EmberConstants &constants);
+
// Row-major 4x4 product and inverse, in the device's layout (the inverse in doubles, so a camera
// far from the origin still comes back); the reach overlay takes them too.
void multiply(const float left[16], const float right[16], float result[16]);
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/HazardCloudShared.h b/GeneralsMD/Code/Libraries/Include/Platform/HazardCloudShared.h
new file mode 100644
index 000000000..afb0cfd74
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/HazardCloudShared.h
@@ -0,0 +1,52 @@
+// SDL shared-volume hazard clouds with bounded incremental snapshot publication.
+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.
+#pragma once
+#include "Platform/HazardCloud.h"
+#include <cstdint>
+#include <memory>
+#include <string>
+namespace HazardCloudShared {
+class Model;
+struct RendererConfig {
+ unsigned volumeSide = 256;
+ unsigned slices = 24;
+ float binCellSize = 128.0f;
+ float bakesPerSecond = 20.0f;
+ // Bound injection work on every display render, including between logic
+ // updates. A complete material snapshot is lit and published atomically.
+ unsigned bakeSlicesPerFrame = 8;
+ bool heat = true;
+ bool embers = true;
+};
+struct RendererStats {
+ unsigned sources = 0, activeSources = 0, maximumBinSources = 0;
+ unsigned activeBodies = 0, interactionUploads = 0;
+ float maxDisturbance = 0;
+ unsigned bakes = 0, frames = 0;
+ // Active sources in the visible snapshot, unfinished material slices, and
+ // the largest injection allowance actually consumed since initialization.
+ unsigned bakedSources = 0, pendingSlices = 0, maxSlicesPerFrame = 0;
+ // Current simulation time minus the visible snapshot's captured time.
+ float publicationAgeSeconds = 0;
+ std::uint64_t volumeBytes = 0, metadataBytes = 0;
+};
+class Renderer {
+public:
+ virtual ~Renderer() = default;
+ virtual bool initialize(std::string &error) = 0;
+ // False guarantees no cloud draw touched scene colour; classic fallback is safe.
+ virtual bool render(const HazardCloud::Camera &camera, const Model &model, float seconds, std::string &error) = 0;
+ // Optional shared terrain grid covering the model's XY bounds. Values are
+ // absolute world heights, copied with each snapshot and its XY bounds.
+ // Only sources with terrain=true sample this grid. nullptr restores planes.
+ virtual void setTerrain(const float *heights, unsigned side) = 0;
+ virtual void setHeatEnabled(bool enabled) = 0;
+ virtual void setBodies(const HazardCloud::Body *bodies, unsigned count) = 0;
+ virtual void reset() = 0;
+ virtual void shutdown() = 0;
+ virtual const RendererStats &stats() const = 0;
+};
+// Query the current backend, including before a device exists.
+bool Supported();
+std::unique_ptr<Renderer> CreateRenderer();
+}
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/HazardCloudSharedModel.h b/GeneralsMD/Code/Libraries/Include/Platform/HazardCloudSharedModel.h
new file mode 100644
index 000000000..d57ed29f5
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/HazardCloudSharedModel.h
@@ -0,0 +1,49 @@
+// Device-free hazard cloud source snapshots and uncapped spatial bins.
+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.
+#pragma once
+
+#include "Platform/HazardCloud.h"
+#include <cstdint>
+#include <vector>
+
+namespace HazardCloudShared {
+
+struct Source {
+ std::uint32_t id = 0; // Stable vector index, including before birth and after expiry.
+ HazardCloud::FieldState field = {};
+ float sourceAge = 0, sourceTravel = 0, dissipation = 0, seed = 0;
+ float born = 0, expiry = 0; // Absolute source lifetime in seconds.
+ bool active = false;
+ bool terrain = true; // Sample the shared ground grid; false keeps this source on its plane.
+};
+
+struct Bounds {
+ float minX = 0, minY = 0, maxX = 0, maxY = 0, minZ = 0, maxZ = 0;
+};
+
+// Conservative XY support bins. Cell (x,y) owns indices[offsets[y*width+x]..
+// offsets[y*width+x+1]); offsets has width*height+1 entries. No per-cell cap.
+// The origin is anchored to integer multiples of cellSize in world space.
+struct Grid {
+ float minX = 0, minY = 0, cellSize = 0;
+ unsigned width = 0, height = 0;
+ std::vector<std::uint32_t> offsets, indices;
+ bool valid() const { return width && height && offsets.size() == std::size_t(width) * height + 1; }
+};
+
+class Model {
+public:
+ // Copies a production snapshot transactionally. IDs must equal their vector
+ // indices; invalid source data or a collapsed/nonfinite domain leaves state intact.
+ bool setSources(const std::vector<Source> &sources, const Bounds &bounds);
+ const std::vector<Source> &sources() const { return values; }
+ const Bounds &bounds() const { return domain; }
+ // Invalid cell size or unrepresentable 32-bit GPU indices return an empty grid.
+ Grid buildBins(float cellSize) const;
+
+private:
+ std::vector<Source> values;
+ Bounds domain;
+};
+
+} // namespace HazardCloudShared
diff --git a/GeneralsMD/Code/Tests/test_hazard_cloud_bake.cpp b/GeneralsMD/Code/Tests/test_hazard_cloud_bake.cpp
new file mode 100644
index 000000000..0ef7afaa2
--- /dev/null
+++ b/GeneralsMD/Code/Tests/test_hazard_cloud_bake.cpp
@@ -0,0 +1,43 @@
+// No renderer or device: exercise every supported slice count and work bound.
+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.
+#include "test_harness.h"
+#include "Platform/HazardCloudBake.h"
+#include <vector>
+
+TEST(shared_cloud_bakes_visit_every_slice_with_bounded_work)
+{
+ for (unsigned slices = 6; slices <= 96; slices += 6) {
+ for (unsigned budget = 1; budget <= 100; ++budget) {
+ HazardCloudShared::BakeSlices progress;
+ progress.begin(slices, budget);
+ std::vector<bool> seen(slices, false);
+ unsigned renders = 0, written = 0;
+ while (!progress.complete()) {
+ unsigned thisFrame = 0;
+ while (!progress.complete() && thisFrame < budget) {
+ const unsigned slice = progress.next();
+ CHECK(slice < slices && !seen[slice]);
+ seen[slice] = true;
+ ++thisFrame; ++written;
+ }
+ CHECK(thisFrame <= budget);
+ CHECK(progress.remaining() == slices - written);
+ ++renders;
+ }
+ CHECK(written == slices && renders == (slices + budget - 1) / budget);
+ CHECK(progress.next() == slices);
+ progress.begin(slices, budget);
+ progress.next();
+ progress.cancel();
+ CHECK(progress.complete() && progress.remaining() == 0);
+ progress.begin(slices, budget);
+ CHECK(progress.next() == 0); // A new generation discards partial progress.
+ }
+ }
+ HazardCloudShared::BakeSlices progress;
+ progress.begin(24, 8);
+ for (unsigned i = 0; i < 8; ++i) CHECK(progress.next() == i * 3);
+ for (unsigned i = 0; i < 8; ++i) CHECK(progress.next() == i * 3 + 1);
+ for (unsigned i = 0; i < 8; ++i) CHECK(progress.next() == i * 3 + 2);
+ CHECK(progress.complete());
+}
diff --git a/GeneralsMD/Code/Tests/test_hazard_cloud_shared.cpp b/GeneralsMD/Code/Tests/test_hazard_cloud_shared.cpp
new file mode 100644
index 000000000..028e6cd9d
--- /dev/null
+++ b/GeneralsMD/Code/Tests/test_hazard_cloud_shared.cpp
@@ -0,0 +1,188 @@
+// Device-free regression checks for shared cloud snapshots and uncapped bins.
+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.
+#include "test_harness.h"
+#include "Platform/HazardCloudShared.h"
+#include "Platform/HazardCloudSharedModel.h"
+#include "Platform/HazardCloudCore.h"
+#include <algorithm>
+#include <array>
+#include <cmath>
+#include <limits>
+#include <type_traits>
+
+namespace S = HazardCloudShared;
+namespace {
+// Same 129/257-field supports as the fork's model checks, supplied through the
+// production snapshot API instead of depending on preview lifecycle tools.
+std::vector<S::Source> fields(unsigned count, bool overlap, float radius = 30)
+{
+ std::vector<S::Source> sources(count);
+ for (unsigned i = 0; i < count; ++i) {
+ auto &source = sources[i];
+ source.id = i;
+ source.field = {{overlap ? -37.f : -123.f + float(i % 11) * 64,
+ overlap ? 123.f : -58.f + float(i / 11) * 64, 7}, radius, 18.61f, 1, float(i % 4), 1, 0, 14};
+ source.active = true;
+ source.born = 0;
+ source.expiry = 24;
+ source.sourceAge = 8;
+ }
+ return sources;
+}
+void sameSources(const std::vector<S::Source> &a, const std::vector<S::Source> &b)
+{
+ CHECK(a.size() == b.size());
+ for (std::size_t i = 0; i < a.size(); ++i) {
+ CHECK(a[i].id == b[i].id && a[i].active == b[i].active);
+ CHECK(a[i].field.density == b[i].field.density);
+ CHECK(a[i].field.formation == b[i].field.formation);
+ CHECK(a[i].field.release == b[i].field.release);
+ CHECK(a[i].sourceAge == b[i].sourceAge && a[i].sourceTravel == b[i].sourceTravel);
+ CHECK(a[i].dissipation == b[i].dissipation && a[i].seed == b[i].seed);
+ }
+}
+
+void uncappedBins()
+{
+ S::Model model;
+ auto sources = fields(257, true, 140);
+ const S::Bounds bounds = {-209, -49, 135, 295, 7, 60};
+ CHECK(model.setSources(sources, bounds));
+ const auto grid = model.buildBins(64);
+ CHECK(grid.valid());
+ CHECK(grid.minX == std::floor(model.bounds().minX / 64) * 64);
+ CHECK(grid.minY == std::floor(model.bounds().minY / 64) * 64);
+ const unsigned x = unsigned(std::floor((-37.f - grid.minX) / grid.cellSize));
+ const unsigned y = unsigned(std::floor((123.f - grid.minY) / grid.cellSize));
+ const std::size_t cell = std::size_t(y) * grid.width + x;
+ CHECK(grid.offsets[cell + 1] - grid.offsets[cell] == 257);
+ if (grid.offsets[cell + 1] - grid.offsets[cell] != 257) return;
+ for (unsigned i = 0; i < 257; ++i) CHECK(grid.indices[grid.offsets[cell] + i] == i);
+ CHECK(grid.offsets.back() == grid.indices.size());
+ for (std::size_t c = 0; c + 1 < grid.offsets.size(); ++c)
+ CHECK(grid.offsets[c + 1] - grid.offsets[c] == 257);
+ for (auto &source : sources) source.active = false;
+ CHECK(model.setSources(sources, bounds));
+ const auto empty = model.buildBins(64);
+ CHECK(empty.valid() && empty.indices.empty() && empty.offsets.back() == 0);
+}
+
+void binCoverageMatchesSupport()
+{
+ S::Model model;
+ auto sources = fields(129, false);
+ const S::Bounds bounds = {-185, -120, 579, 708, 7, 60};
+ CHECK(model.setSources(sources, bounds));
+ const auto grid = model.buildBins(48);
+ CHECK(grid.valid());
+ for (unsigned y = 0; y < grid.height; ++y) for (unsigned x = 0; x < grid.width; ++x) {
+ const std::size_t cell = std::size_t(y) * grid.width + x;
+ const float lowX = grid.minX + x * grid.cellSize, lowY = grid.minY + y * grid.cellSize;
+ const auto first = grid.indices.begin() + grid.offsets[cell];
+ const auto last = grid.indices.begin() + grid.offsets[cell + 1];
+ CHECK(std::adjacent_find(first, last) == last);
+ for (const auto &source : model.sources()) {
+ const float reach = source.field.radius + source.field.fringe + 18;
+ const bool overlaps = source.active && source.field.ground.x + reach >= lowX
+ && source.field.ground.x - reach < lowX + grid.cellSize
+ && source.field.ground.y + reach >= lowY
+ && source.field.ground.y - reach < lowY + grid.cellSize;
+ CHECK((std::find(first, last, source.id) != last) == overlaps);
+ }
+ }
+}
+
+void productionSnapshotsAreTransactional()
+{
+ auto sources = fields(129, true);
+ S::Bounds bounds = {-99, 61, 25, 185, 7, 60};
+ S::Model model;
+ CHECK(model.setSources(sources, bounds));
+ const auto captured = model.sources();
+ const auto full = model.buildBins(64);
+ CHECK(full.valid() && !full.indices.empty());
+ sources[0].active = false;
+ sources[1].terrain = false;
+ sources[1].field.ground.x += 400;
+ sources[1].field.ground.z = 80;
+ bounds.maxX += 400; bounds.maxZ += 100;
+ CHECK(model.setSources(sources,bounds));
+ CHECK(!model.sources()[0].active && !model.sources()[1].terrain);
+ CHECK(model.sources()[1].field.ground.z == 80);
+ CHECK(model.sources()[1].field.ground.x != captured[1].field.ground.x);
+ const auto moved = model.buildBins(64);
+ CHECK(moved.valid() && moved.width > full.width);
+ CHECK(std::find(moved.indices.begin(),moved.indices.end(),0) == moved.indices.end());
+ const auto stable = model.sources();
+ for (unsigned kind = 0; kind < 12; ++kind) {
+ auto bad = sources; auto badBounds = bounds;
+ switch (kind) {
+ case 0: bad[1].id = 0; break;
+ case 1: bad[1].field.ground.x = (std::numeric_limits<float>::quiet_NaN)(); break;
+ case 2: bad[1].sourceTravel = (std::numeric_limits<float>::infinity)(); break;
+ case 3: bad[1].field.palette = 1.5f; break;
+ case 4: bad[1].field.release = 2; break;
+ case 5: bad[1].dissipation = -1; break;
+ case 6: bad[1].expiry = bad[1].born - 1; break;
+ case 7: badBounds.maxX = badBounds.minX; break;
+ case 8: badBounds.minY = (std::numeric_limits<float>::quiet_NaN)(); break;
+ case 9: bad[1].field.radius = -1; break;
+ case 10: bad[1].seed = (std::numeric_limits<float>::infinity)(); break;
+ case 11: bad[1].field.density = 2; break;
+ }
+ CHECK(!model.setSources(bad,badBounds));
+ sameSources(stable,model.sources());
+ CHECK(model.bounds().maxX == bounds.maxX);
+ }
+ CHECK(model.setSources({},bounds));
+ CHECK(!model.buildBins(0).valid());
+ CHECK(!model.buildBins((std::numeric_limits<float>::quiet_NaN)()).valid());
+ const auto empty = model.buildBins(64);
+ CHECK(empty.valid() && empty.indices.empty());
+}
+
+}
+
+TEST(shared_cloud_bins_retain_257_overlapping_fields) { uncappedBins(); }
+TEST(shared_cloud_bins_cover_all_129_distributed_supports) { binCoverageMatchesSupport(); }
+TEST(shared_cloud_snapshots_are_transactional) { productionSnapshotsAreTransactional(); }
+
+TEST(shared_cloud_capability_declines_without_a_backend)
+{
+ static_assert(std::is_abstract<S::Renderer>::value, "shared renderer is a backend interface");
+ static_assert(std::has_virtual_destructor<S::Renderer>::value, "owned through the interface");
+ CHECK(!S::Supported());
+ CHECK(S::CreateRenderer() == nullptr);
+}
+
+TEST(hazard_cloud_embers_support_shared_terrain_without_changing_legacy_constants)
+{
+ const HazardCloud::FieldState field = {{40, 80, 12}, 40, 18.61f, 1, 1, 1, 0, 10};
+ float matrix[16] = {}, viewport[4] = {0, 0, 1280, 800};
+ HazardCloud::EmberConstants constants;
+ const unsigned count = HazardCloud::emberConstants(field, 1, true, matrix, viewport, 3, constants);
+ CHECK_EQ(constants.terrain[1], 1.f);
+ CHECK_EQ(constants.terrain[2], field.radius + field.fringe + HazardCloud::MaximumDisplacement);
+ const float domain[4] = {-128, 0, 384, 256};
+ CHECK(HazardCloud::setEmberTerrainDomain(domain, constants));
+ CHECK_EQ(constants.terrain[0], 1.f);
+ CHECK_EQ(constants.terrain[1], -1.f);
+ // The shared grid's world centre must sample its centre, independently of
+ // the source's position and the old per-source atlas index.
+ CHECK_EQ((128.f - constants.terrain[2]) * constants.scene[2], .5f);
+ CHECK_EQ((128.f - constants.terrain[3]) * constants.scene[3], .5f);
+ CHECK_EQ(constants.field[2], field.ground.z);
+ CHECK_EQ(constants.scene[0], 3.f);
+ CHECK_EQ(constants.scene[1], float(count));
+ const HazardCloud::EmberConstants valid = constants;
+ for (const std::array<float, 4> invalid : {
+ std::array<float, 4>{{0, 0, 0, 1}}, {{0, 0, 1, -1}},
+ {{0, 0, std::numeric_limits<float>::infinity(), 1}},
+ {{0, 0, std::numeric_limits<float>::denorm_min(), 1}}}) {
+ CHECK(!HazardCloud::setEmberTerrainDomain(invalid.data(), constants));
+ CHECK(std::equal(constants.scene, constants.scene + 4, valid.scene));
+ CHECK(std::equal(constants.terrain, constants.terrain + 4, valid.terrain));
+ }
+ CHECK(!HazardCloud::setEmberTerrainDomain(nullptr, constants));
+}
+
diff --git a/GeneralsMD/Code/Tests/test_shader_sdl.cpp b/GeneralsMD/Code/Tests/test_shader_sdl.cpp
index 3223dfd88..58d0ec476 100644
--- a/GeneralsMD/Code/Tests/test_shader_sdl.cpp
+++ b/GeneralsMD/Code/Tests/test_shader_sdl.cpp
@@ -57,6 +57,7 @@
#include <string>
#include <vector>
+#include <utility>
#include <complex>
#include <SDL3/SDL.h>
@@ -1372,3 +1373,33 @@ TEST(authored_surf_wrapper_compiles_with_original_fixed_function_fog_and_alpha)
std::string bad="not a generated combiner";const std::string saved=bad;
CHECK(!WaterShoreOverlay::WrapPixel(bad));CHECK(bad==saved);
}
+
+// Keep BaseType.h's legacy min/max macros out of the independent shader cases above.
+#include "Platform/HazardCloudCore.h"
+#include "../GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudSharedShader.h"
+// Shared clouds must retain SDL descriptor bindings on Vulkan and Metal.
+TEST(shared_cloud_programs_compile_validate_and_translate)
+{
+ using HazardCloudShared::ShaderPass;
+ const char *validator = getenv("ZH_SPIRV_VAL");
+ std::vector<std::pair<std::string, bool>> programs = {
+ {HazardCloud::vertexShader(), true},
+ {HazardCloud::emberVertexShader(true), true},
+ {HazardCloud::emberPixelShader(true), false}
+ };
+ for (unsigned pass = 0; pass < 5; ++pass)
+ programs.push_back({HazardCloudShared::sharedPixelShader(static_cast<ShaderPass>(pass)), false});
+ for (const auto &program : programs) {
+ std::vector<unsigned char> spirv;
+ std::string log, msl;
+ const bool compiled = SDL3_Compile_HLSL_To_SPIRV(program.first, program.second, spirv, log);
+ CHECK(compiled);
+ if (!compiled) { printf("shared cloud shader: %s\n", log.c_str()); continue; }
+ if (validator && *validator) CHECK(validate(validator, spirv, log));
+ else printf("SKIPPED shared cloud spirv-val: validator unavailable\n");
+ CHECK(SDL3_Translate_SPIRV_To_MSL(spirv, program.second, msl, log));
+ unsigned samplers = 0, uniforms = 0;
+ SDL3_Shader_Slots(spirv, program.second, samplers, uniforms);
+ CHECK_EQ(uniforms, program.first == HazardCloud::vertexShader() ? 0u : 1u);
+ }
+}