Zero Hour rebuilt from EA's source: x64, Direct3D 11, VS2022/CMake, ~60 original bugs fixed, an AI that builds a base. Bring your own game.
C++ cmakecnccommand-and-conquercppdirectx11game-enginegame-preservationgeneralsrtssage-enginex64zero-hour
feat(clouds): add volumetric hazard cloud effects on linux
Richard Louie Orilla88a47f29f98c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 39304666c..bc156ca2c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2340,3 +2340,16 @@ The whole HUD is on the hardware. Four colours carry it, and they mean the same- Internet play. LAN works: two separate PCs have played each other on one network. Matches over the internet wait on Reforged's own lobby server, which is still on paper.- A frame through Direct3D 11 still costs a little more than it does through the old renderer: 7.6ms against 6.3ms in a screen full of inferno cannon fire. `-d3d9` on the command line puts the old renderer back on its own.- You need to own the game; no game data ships here.++## Volumetric hazard clouds on Linux (2026-10-18)++- Cloud style appears on the Graphics page, with live Classic / Volumetric+ choices. The shared demo renderer now draws the game's toxin, beta, gamma and+ nuclear fields using the approved colors, actual hazard radii and lifetimes.+- Low smoke follows terrain and responds visually to passing infantry. Nuclear+ fields fade in across their full area, with darker billows, rising embers and+ heat distortion. The renderer has bounded caches and preserves Classic effects+ when a field cannot be admitted; gameplay damage and simulation are unchanged.+- The preview has per-cloud color, brightness and transparency controls, with+ structures, props and baseline water for judging visibility. The approved preset+ uses 67% toxin, 77% beta and 74% gamma transparency; nuclear remains at 0%.diff --git a/GeneralsMD/Code/BuildFingerprint.manifest b/GeneralsMD/Code/BuildFingerprint.manifestindex 48589592b..b11a9d8b3 100644--- a/GeneralsMD/Code/BuildFingerprint.manifest+++ b/GeneralsMD/Code/BuildFingerprint.manifest@@ -1816,10 +1816,17 @@ GameEngineDevice/Source/PosixDevice/Render/SdlCreationLog.hGameEngineDevice/Source/PosixDevice/Render/SdlGpuFrame.cppGameEngineDevice/Source/PosixDevice/Render/SdlGpuFrame.hGameEngineDevice/Source/PosixDevice/Render/SdlGpuFrameBatch.cpp+GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloud.cpp+GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudEmbers.cpp+GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudEmbers.h+GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudFlow.cpp+GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudShader.cpp+GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudShader.hGameEngineDevice/Source/PosixDevice/Render/SdlPipelineCache.cppGameEngineDevice/Source/PosixDevice/Render/SdlPipelineCache.hGameEngineDevice/Source/PosixDevice/Render/SdlProgramCache.cppGameEngineDevice/Source/PosixDevice/Render/SdlProgramCache.h+GameEngineDevice/Source/PosixDevice/Render/SdlRenderMatrix.hGameEngineDevice/Source/PosixDevice/Render/SdlResourceMirror.cppGameEngineDevice/Source/PosixDevice/Render/SdlResourceMirror.hGameEngineDevice/Source/SdlDevice/Common/SdlDisplays.cpp@@ -1963,6 +1970,7 @@ Libraries/Include/Platform/D3D9Posix.hLibraries/Include/Platform/D3D9PosixMath.hLibraries/Include/Platform/DoubleClickTime.hLibraries/Include/Platform/EngineShaderName.h+Libraries/Include/Platform/HazardCloudPolicy.hLibraries/Include/Platform/IsWindows9x.hLibraries/Include/Platform/LoadTiming.hLibraries/Include/Platform/MSVCCompat.h@@ -1972,6 +1980,8 @@ Libraries/Include/Platform/PosixD3D9/d3d9caps.hLibraries/Include/Platform/PosixD3D9/d3d9types.hLibraries/Include/Platform/RenderTypes.hLibraries/Include/Platform/RendererName.h+Libraries/Include/Platform/SdlHazardCloud.h+Libraries/Include/Platform/SdlHazardCloudFlow.hLibraries/Include/Platform/SleepMilliseconds.hLibraries/Include/Platform/StrdupAsWindows.hLibraries/Include/rts/debug.h@@ -3067,6 +3077,7 @@ Tests/test_gametext_csf.cppTests/test_global_new_alignment.cppTests/test_glyph_rasteriser.cppTests/test_harness.h+Tests/test_hazard_cloud_policy.cppTests/test_hostile_map.incTests/test_install_guard.shTests/test_install_root.cpp@@ -3275,6 +3286,18 @@ Tools/CRCDiff/misc.hTools/CRCDiff/row.htmlTools/CRCDiff/style.cssTools/CRCDiff/top.html+Tools/CloudPreviewColorPanel.cpp+Tools/CloudPreviewColorPanel.h+Tools/CloudPreviewColors.cpp+Tools/CloudPreviewColors.h+Tools/CloudPreviewFlow.cpp+Tools/CloudPreviewFlow.h+Tools/CloudPreviewScene.cpp+Tools/CloudPreviewScene.h+Tools/CloudPreviewSources.cpp+Tools/CloudPreviewSources.h+Tools/CloudPreviewVolume.cpp+Tools/CloudPreviewVolume.hTools/Compress/Compress.cppTools/Compress/Compress.dspTools/DebugWindow/DebugWindow.cpp@@ -3924,6 +3947,13 @@ Tools/buildVersionUpdate/buildVersionUpdate.cppTools/buildVersionUpdate/buildVersionUpdate.dspTools/cheat_check.pyTools/china_beacon.py+Tools/cloud_preview.cpp+Tools/cloud_preview/generate_map.py+Tools/cloud_preview/presets/pre-tuning.ini+Tools/cloud_preview/presets/preferred.ini+Tools/cloud_preview/runtime-check.md+Tools/cloud_preview/test_colors.cpp+Tools/cloud_preview/test_flow.cppTools/control_client.pyTools/d3d9posix_check.pyTools/diplomacy_layout.py@@ -3940,6 +3970,7 @@ Tools/gdi-font-metrics-header.pyTools/gdi-font-metrics.ps1Tools/generals-icon.pyTools/gentrigtables.py+Tools/hazard-cloud-check.pyTools/include_case_check.pyTools/install-guard.shTools/license-headers.pydiff --git a/GeneralsMD/Code/CMakeLists.txt b/GeneralsMD/Code/CMakeLists.txtindex 30f6c550c..ffa520ab8 100644--- a/GeneralsMD/Code/CMakeLists.txt+++ b/GeneralsMD/Code/CMakeLists.txt@@ -1398,6 +1398,9 @@ if(ZH_PLATFORM_POSIX)# ---- posixd3d9: the device, in the place d3d9.lib has on Windows -----------------------------------file(GLOB_RECURSE POSIXD3D9_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/GameEngineDevice/Source/PosixDevice/Render/*.cpp)+ # Hazard clouds bridge the scene and SDL device; keep that bridge above the+ # D3D compatibility library so low-level device tests stay independent.+ list(FILTER POSIXD3D9_SOURCES EXCLUDE REGEX "/SdlHazardCloud[^/]*\\.cpp$")add_library(posixd3d9 STATIC ${POSIXD3D9_SOURCES})set_target_properties(posixd3d9 PROPERTIES CXX_STANDARD 17)target_include_directories(posixd3d9 PUBLIC ${ZH_POSIX_D3D9_INCLUDE})@@ -1562,6 +1565,14 @@ if(ZH_PLATFORM_POSIX)# BinkVideoPlayer.cpp, unchanged: W3DGameClient makes it on every platform, so it lives with w3ddevicelist(APPEND W3DDEVICE_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/GameEngineDevice/Source/VideoDevice/Bink/BinkVideoPlayer.cpp)add_library(w3ddevice STATIC ${W3DDEVICE_SOURCES})+ set(ZH_POSIX_RENDER_DIR ${CMAKE_CURRENT_SOURCE_DIR}/GameEngineDevice/Source/PosixDevice/Render)+ if(ZH_PLATFORM_LINUX)+ target_sources(w3ddevice PRIVATE+ ${ZH_POSIX_RENDER_DIR}/SdlHazardCloud.cpp+ ${ZH_POSIX_RENDER_DIR}/SdlHazardCloudShader.cpp+ ${ZH_POSIX_RENDER_DIR}/SdlHazardCloudFlow.cpp+ ${ZH_POSIX_RENDER_DIR}/SdlHazardCloudEmbers.cpp)+ endif()set_target_properties(w3ddevice PROPERTIES CXX_STANDARD 17)target_include_directories(w3ddevice PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/GameEngineDevice/IncludePRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/Stubs ${CMAKE_CURRENT_SOURCE_DIR}/Main@@ -1952,6 +1963,35 @@ if(ZH_PLATFORM_POSIX)DEPENDS ${ZH_OVERLAY_INPUTS} ${CMAKE_CURRENT_SOURCE_DIR}/Tools/stage-overlay.shCOMMENT "Staging the fork's overlay (P1)" VERBATIM)add_custom_target(zh_overlay ALL DEPENDS ${CMAKE_BINARY_DIR}/overlay.staged)+ # An isolated, harmless effects scene. This target shares the real client/renderer+ # libraries, but its entry point, scene controller and map never enter generals.+ find_package(Python3 COMPONENTS Interpreter QUIET)+ if(ZH_PLATFORM_LINUX AND Python3_Interpreter_FOUND)+ set(ZH_CLOUD_PREVIEW_DIR ${CMAKE_BINARY_DIR}/cloud-preview)+ set(ZH_CLOUD_PREVIEW_MAP ${ZH_CLOUD_PREVIEW_DIR}/overlay/Maps/CloudPreview/CloudPreview.map)+ add_custom_command(OUTPUT ${ZH_CLOUD_PREVIEW_MAP}+ COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/Tools/cloud_preview/generate_map.py+ ${ZH_CLOUD_PREVIEW_MAP} --inspection-yard+ DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/Tools/cloud_preview/generate_map.py+ COMMENT "Generating the cloud preview's inspection yard" VERBATIM)+ add_custom_target(cloud_preview_map DEPENDS ${ZH_CLOUD_PREVIEW_MAP})+ add_executable(cloud_preview EXCLUDE_FROM_ALL+ ${CMAKE_CURRENT_SOURCE_DIR}/Tools/cloud_preview.cpp+ ${CMAKE_CURRENT_SOURCE_DIR}/Tools/CloudPreviewScene.cpp+ ${CMAKE_CURRENT_SOURCE_DIR}/Tools/CloudPreviewSources.cpp+ ${CMAKE_CURRENT_SOURCE_DIR}/Tools/CloudPreviewVolume.cpp+ ${CMAKE_CURRENT_SOURCE_DIR}/Tools/CloudPreviewFlow.cpp+ ${CMAKE_CURRENT_SOURCE_DIR}/Tools/CloudPreviewColors.cpp+ ${CMAKE_CURRENT_SOURCE_DIR}/Tools/CloudPreviewColorPanel.cpp)+ set_target_properties(cloud_preview PROPERTIES CXX_STANDARD 17)+ target_include_directories(cloud_preview PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/Main ${GENERATED})+ target_compile_definitions(cloud_preview PRIVATE+ CLOUD_PREVIEW_DIRECTORY="${ZH_CLOUD_PREVIEW_DIR}"+ CLOUD_PREVIEW_GAME_OVERLAY="${CMAKE_BINARY_DIR}/overlay")+ target_link_libraries(cloud_preview PRIVATE sdldevice installroot)+ add_dependencies(cloud_preview zh_overlay cloud_preview_map)+ endif()+add_custom_command(OUTPUT ${CMAKE_BINARY_DIR}/overlay-dev.stagedCOMMAND ${CMAKE_CURRENT_SOURCE_DIR}/Tools/stage-overlay.sh ${CMAKE_CURRENT_SOURCE_DIR}/Data ""@@ -2133,6 +2173,10 @@ endfunction()add_lib_test(test_msvc_float_casts)target_include_directories(test_msvc_float_casts PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/Libraries/Include)+add_lib_test(test_hazard_cloud_policy)+set_target_properties(test_hazard_cloud_policy PROPERTIES CXX_STANDARD 17)+target_include_directories(test_hazard_cloud_policy PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/Libraries/Include)+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.diff --git a/GeneralsMD/Code/Data/Patch.str b/GeneralsMD/Code/Data/Patch.strindex 831c6b77e..f8e1212c0 100644--- a/GeneralsMD/Code/Data/Patch.str+++ b/GeneralsMD/Code/Data/Patch.str@@ -1182,6 +1182,22 @@ CONTROLBAR:Demo_ToolTipGLAScienceRebelAmbush"Allows you to create a surprise ambush of Rebels anywhere \n \n Rank 1: 4 Rebels \n Rank 2: 6 Rebels \n Rank 3: 10 Rebels \n \n Deploy from: Command Center"END+GUI:CloudStyle+"Cloud style"+END++GUI:CloudStyle0+"Classic"+END++GUI:CloudStyle1+"Volumetric"+END++TOOLTIP:CloudStyle+"Classic uses the original toxin and radiation effects. Volumetric adds moving smoke, darker nuclear haze and heat shimmer. Applied when you Accept."+END+LAN:ErrorModMismatch"This game runs different mods. The host's mods: %s. Start the game with the same mods, in the same order, to join."ENDdiff --git a/GeneralsMD/Code/Data/Window/Menus/OptionsMenuClassic.wnd b/GeneralsMD/Code/Data/Window/Menus/OptionsMenuClassic.wndindex cb3cab3d0..48ac0d342 100644--- a/GeneralsMD/Code/Data/Window/Menus/OptionsMenuClassic.wnd+++ b/GeneralsMD/Code/Data/Window/Menus/OptionsMenuClassic.wnd@@ -5245,6 +5245,294 @@ WINDOWIMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0;END+ CHILD+ WINDOW+ WINDOWTYPE = STATICTEXT;+ SCREENRECT = UPPERLEFT: 530 350, BOTTOMRIGHT: 754 374, CREATIONRESOLUTION: 800 600;+ NAME = "OptionsMenu.wnd:LabelCloudStyle";+ TOOLTIPTEXT = "TOOLTIP:CloudStyle";+ STATUS = ENABLED;+ STYLE = STATICTEXT+MOUSETRACK;+ SYSTEMCALLBACK = "[None]";+ INPUTCALLBACK = "[None]";+ TOOLTIPCALLBACK = "[None]";+ DRAWCALLBACK = "[None]";+ FONT = NAME: "Arial", SIZE: 14, BOLD: 0;+ HEADERTEMPLATE = "MinorTitle";+ TOOLTIPDELAY = -1;+ TEXT = "GUI:CloudStyle";+ TEXTCOLOR = ENABLED: 255 255 255 255, ENABLEDBORDER: 0 0 0 255,+ DISABLED: 192 192 192 255, DISABLEDBORDER: 64 64 64 255,+ HILITE: 128 128 255 255, HILITEBORDER: 0 0 128 255;+ ENABLEDDRAWDATA = IMAGE: NoImage, COLOR: 0 0 0 0, BORDERCOLOR: 0 0 0 0,+ IMAGE: NoImage, COLOR: 255 255 255 255, BORDERCOLOR: 255 255 255 255,+ IMAGE: NoImage, COLOR: 255 255 255 255, BORDERCOLOR: 255 255 255 255,+ IMAGE: NoImage, COLOR: 255 255 255 255, BORDERCOLOR: 255 255 255 255,+ IMAGE: NoImage, COLOR: 255 255 255 255, BORDERCOLOR: 255 255 255 255,+ IMAGE: NoImage, COLOR: 255 255 255 255, BORDERCOLOR: 255 255 255 255,+ IMAGE: NoImage, COLOR: 255 255 255 255, BORDERCOLOR: 255 255 255 255,+ IMAGE: NoImage, COLOR: 255 255 255 255, BORDERCOLOR: 255 255 255 255,+ IMAGE: NoImage, COLOR: 255 255 255 255, BORDERCOLOR: 255 255 255 255;+ DISABLEDDRAWDATA = IMAGE: NoImage, COLOR: 64 64 64 255, BORDERCOLOR: 192 192 192 255,+ IMAGE: NoImage, COLOR: 255 255 255 255, BORDERCOLOR: 255 255 255 255,+ IMAGE: NoImage, COLOR: 255 255 255 255, BORDERCOLOR: 255 255 255 255,+ IMAGE: NoImage, COLOR: 255 255 255 255, BORDERCOLOR: 255 255 255 255,+ IMAGE: NoImage, COLOR: 255 255 255 255, BORDERCOLOR: 255 255 255 255,+ IMAGE: NoImage, COLOR: 255 255 255 255, BORDERCOLOR: 255 255 255 255,+ IMAGE: NoImage, COLOR: 255 255 255 255, BORDERCOLOR: 255 255 255 255,+ IMAGE: NoImage, COLOR: 255 255 255 255, BORDERCOLOR: 255 255 255 255,+ IMAGE: NoImage, COLOR: 255 255 255 255, BORDERCOLOR: 255 255 255 255;+ HILITEDRAWDATA = IMAGE: NoImage, COLOR: 0 128 0 255, BORDERCOLOR: 128 255 128 255,+ IMAGE: NoImage, COLOR: 255 255 255 255, BORDERCOLOR: 255 255 255 255,+ IMAGE: NoImage, COLOR: 255 255 255 255, BORDERCOLOR: 255 255 255 255,+ IMAGE: NoImage, COLOR: 255 255 255 255, BORDERCOLOR: 255 255 255 255,+ IMAGE: NoImage, COLOR: 255 255 255 255, BORDERCOLOR: 255 255 255 255,+ IMAGE: NoImage, COLOR: 255 255 255 255, BORDERCOLOR: 255 255 255 255,+ IMAGE: NoImage, COLOR: 255 255 255 255, BORDERCOLOR: 255 255 255 255,+ IMAGE: NoImage, COLOR: 255 255 255 255, BORDERCOLOR: 255 255 255 255,+ IMAGE: NoImage, COLOR: 255 255 255 255, BORDERCOLOR: 255 255 255 255;+ STATICTEXTDATA = CENTERED: 0;+ END+ CHILD+ WINDOW+ WINDOWTYPE = COMBOBOX;+ SCREENRECT = UPPERLEFT: 536 374, BOTTOMRIGHT: 760 398, CREATIONRESOLUTION: 800 600;+ NAME = "OptionsMenu.wnd:ComboBoxCloudStyle";+ TOOLTIPTEXT = "TOOLTIP:CloudStyle";+ STATUS = ENABLED+IMAGE;+ STYLE = MOUSETRACK+COMBOBOX;+ SYSTEMCALLBACK = "[None]";+ INPUTCALLBACK = "[None]";+ TOOLTIPCALLBACK = "[None]";+ DRAWCALLBACK = "[None]";+ FONT = NAME: "Arial", SIZE: 10, BOLD: 0;+ HEADERTEMPLATE = "ComboBoxEntry";+ TOOLTIPDELAY = -1;+ TEXTCOLOR = ENABLED: 254 254 254 255, ENABLEDBORDER: 0 0 0 255,+ DISABLED: 192 192 192 255, DISABLEDBORDER: 64 64 64 255,+ HILITE: 128 128 255 255, HILITEBORDER: 0 0 128 255;+ ENABLEDDRAWDATA = IMAGE: NoImage, COLOR: 255 0 0 255, BORDERCOLOR: 255 128 128 255,+ IMAGE: NoImage, COLOR: 47 55 168 255, BORDERCOLOR: 254 254 254 255,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0;+ DISABLEDDRAWDATA = IMAGE: NoImage, COLOR: 128 128 128 255, BORDERCOLOR: 192 192 192 255,+ IMAGE: NoImage, COLOR: 192 192 192 255, BORDERCOLOR: 254 254 254 255,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0;+ HILITEDRAWDATA = IMAGE: NoImage, COLOR: 0 255 0 255, BORDERCOLOR: 0 128 0 255,+ IMAGE: ListBoxHiliteSelectedItemLeftEnd, COLOR: 254 254 254 255, BORDERCOLOR: 0 128 0 255,+ IMAGE: ListBoxHiliteSelectedItemRightEnd, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: ListBoxHiliteSelectedItemRepeatingCenter, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: ListBoxHiliteSelectedItemSmallRepeatingCenter, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0;+ COMBOBOXDATA = ISEDITABLE: 0,+ MAXCHARS: 16,+ MAXDISPLAY: 5,+ ASCIIONLY: 0,+ LETTERSANDNUMBERS: 0;+ COMBOBOXDROPDOWNBUTTONENABLEDDRAWDATA = IMAGE: VSliderDownButtonEnabled, COLOR: 255 0 0 255, BORDERCOLOR: 255 128 128 255,+ IMAGE: VSliderDownButtonHiliteSelected, COLOR: 255 255 0 255, BORDERCOLOR: 254 254 254 255,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0;+ COMBOBOXDROPDOWNBUTTONDISABLEDDRAWDATA = IMAGE: VSliderDownButtonDisabled, COLOR: 128 128 128 255, BORDERCOLOR: 192 192 192 255,+ IMAGE: NoImage, COLOR: 192 192 192 255, BORDERCOLOR: 128 128 128 255,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0;+ COMBOBOXDROPDOWNBUTTONHILITEDRAWDATA = IMAGE: VSliderDownButtonHilite, COLOR: 0 255 0 255, BORDERCOLOR: 0 128 0 255,+ IMAGE: VSliderDownButtonHiliteSelected, COLOR: 255 255 0 255, BORDERCOLOR: 254 254 254 255,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0;+ COMBOBOXEDITBOXENABLEDDRAWDATA = IMAGE: TextEntryEnabledLeftEnd, COLOR: 255 0 0 255, BORDERCOLOR: 255 128 128 255,+ IMAGE: TextEntryEnabledRightEnd, COLOR: 255 255 0 255, BORDERCOLOR: 254 254 254 255,+ IMAGE: TextEntryEnabledRepeatingCenter, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: TextEntryEnabledSmallRepeatingCenter, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0;+ COMBOBOXEDITBOXDISABLEDDRAWDATA = IMAGE: TextEntryDisabledLeftEnd, COLOR: 128 128 128 255, BORDERCOLOR: 0 0 0 255,+ IMAGE: TextEntryDisabledRightEnd, COLOR: 192 192 192 255, BORDERCOLOR: 254 254 254 255,+ IMAGE: TextEntryDisabledRepeatingCenter, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: TextEntryDisabledSmallRepeatingCenter, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0;+ COMBOBOXEDITBOXHILITEDRAWDATA = IMAGE: TextEntryHiliteLeftEnd, COLOR: 0 255 0 255, BORDERCOLOR: 0 128 0 255,+ IMAGE: TextEntryHiliteRightEnd, COLOR: 254 254 254 255, BORDERCOLOR: 0 128 0 255,+ IMAGE: TextEntryHiliteRepeatingCenter, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: TextEntryHiliteSmallRepeatingCenter, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0;+ COMBOBOXLISTBOXENABLEDDRAWDATA = IMAGE: BlackSquare, COLOR: 0 0 0 255, BORDERCOLOR: 49 55 168 255,+ IMAGE: ListBoxHiliteItemLeftEnd, COLOR: 255 255 0 255, BORDERCOLOR: 254 254 254 255,+ IMAGE: ListBoxHiliteItemRightEnd, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: ListBoxHiliteItemRepeatingCenter, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: ListBoxHiliteItemSmallRepeatingCenter, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0;+ COMBOBOXLISTBOXDISABLEDDRAWDATA = IMAGE: BlackSquare, COLOR: 0 0 0 255, BORDERCOLOR: 49 55 168 255,+ IMAGE: NoImage, COLOR: 192 192 192 255, BORDERCOLOR: 254 254 254 255,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0;+ COMBOBOXLISTBOXHILITEDRAWDATA = IMAGE: BlackSquare, COLOR: 0 0 0 255, BORDERCOLOR: 49 55 168 255,+ IMAGE: ListBoxHiliteSelectedItemLeftEnd, COLOR: 254 254 254 255, BORDERCOLOR: 0 128 0 255,+ IMAGE: ListBoxHiliteSelectedItemRightEnd, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: ListBoxHiliteSelectedItemRepeatingCenter, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: ListBoxHiliteSelectedItemSmallRepeatingCenter, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0;+ LISTBOXENABLEDUPBUTTONDRAWDATA = IMAGE: VSliderUpButtonEnabled, COLOR: 255 0 0 255, BORDERCOLOR: 255 128 128 255,+ IMAGE: VSliderUpButtonHiliteSelected, COLOR: 255 255 0 255, BORDERCOLOR: 254 254 254 255,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0;+ LISTBOXDISABLEDUPBUTTONDRAWDATA = IMAGE: VSliderUpButtonDisabled, COLOR: 128 128 128 255, BORDERCOLOR: 192 192 192 255,+ IMAGE: NoImage, COLOR: 192 192 192 255, BORDERCOLOR: 254 254 254 255,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0;+ LISTBOXHILITEUPBUTTONDRAWDATA = IMAGE: VSliderUpButtonHilite, COLOR: 0 255 0 255, BORDERCOLOR: 0 128 0 255,+ IMAGE: VSliderUpButtonHiliteSelected, COLOR: 254 254 254 255, BORDERCOLOR: 0 128 0 255,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0;+ LISTBOXENABLEDDOWNBUTTONDRAWDATA = IMAGE: VSliderDownButtonEnabled, COLOR: 255 0 0 255, BORDERCOLOR: 255 128 128 255,+ IMAGE: VSliderDownButtonHiliteSelected, COLOR: 255 255 0 255, BORDERCOLOR: 254 254 254 255,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0;+ LISTBOXDISABLEDDOWNBUTTONDRAWDATA = IMAGE: VSliderDownButtonDisabled, COLOR: 128 128 128 255, BORDERCOLOR: 192 192 192 255,+ IMAGE: NoImage, COLOR: 192 192 192 255, BORDERCOLOR: 254 254 254 255,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0;+ LISTBOXHILITEDOWNBUTTONDRAWDATA = IMAGE: VSliderDownButtonHilite, COLOR: 0 255 0 255, BORDERCOLOR: 0 128 0 255,+ IMAGE: VSliderDownButtonHiliteSelected, COLOR: 254 254 254 255, BORDERCOLOR: 0 128 0 255,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0;+ LISTBOXENABLEDSLIDERDRAWDATA = IMAGE: NoImage, COLOR: 168 255 12 0, BORDERCOLOR: 47 55 168 255,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0;+ LISTBOXDISABLEDSLIDERDRAWDATA = IMAGE: NoImage, COLOR: 128 128 128 0, BORDERCOLOR: 148 112 0 255,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0;+ LISTBOXHILITESLIDERDRAWDATA = IMAGE: NoImage, COLOR: 0 255 0 0, BORDERCOLOR: 49 55 168 255,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0;+ SLIDERTHUMBENABLEDDRAWDATA = IMAGE: ScrollBarThumbEnabled, COLOR: 255 4 0 0, BORDERCOLOR: 255 243 28 255,+ IMAGE: ScrollBarThumbHiliteSelected, COLOR: 255 255 0 255, BORDERCOLOR: 254 254 254 255,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0;+ SLIDERTHUMBDISABLEDDRAWDATA = IMAGE: ScrollBarThumbDisabled, COLOR: 128 128 128 255, BORDERCOLOR: 192 192 192 255,+ IMAGE: NoImage, COLOR: 192 192 192 255, BORDERCOLOR: 254 254 254 255,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0;+ SLIDERTHUMBHILITEDRAWDATA = IMAGE: ScrollBarThumbHilite, COLOR: 0 255 0 255, BORDERCOLOR: 0 128 0 255,+ IMAGE: ScrollBarThumbHiliteSelected, COLOR: 254 254 254 255, BORDERCOLOR: 0 128 0 255,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0,+ IMAGE: NoImage, COLOR: 255 255 255 0, BORDERCOLOR: 255 255 255 0;+ ENDENDALLCHILDRENENDCHILDdiff --git a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.hindex 75b72c8b4..9faac30b0 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h@@ -320,6 +320,7 @@ public:Bool m_shadowsForParticles; // "ShadowsForParticles": big alpha-blended particle clouds drop a soft blob on the groundBool m_volumetricSmokeShadows; // "VolumetricSmokeShadows": smoke and dust shade the world and themselves through the sun's map (Direct3D 11)Bool m_smokeFireLighting; // "SmokeFireLighting": smoke takes light from the fire beside it+ Int m_cloudStyle; // "CloudStyle": 0 = Classic, 1 = Volumetric (Linux)Bool m_explosionDebrisTrails; // "DebrisTrails": blasts throw smoke-trailing fragments and burning shrapnelInt m_shadowQuality; // "ShadowQuality": the sun's depth map at 1024, 2048 or 4096 texels a side (Direct3D 11)Bool m_classicGraphics; // "ClassicGraphics": the game's own art, tile, shadows and picture; read at startupdiff --git a/GeneralsMD/Code/GameEngine/Include/Common/OptionsCatalog.h b/GeneralsMD/Code/GameEngine/Include/Common/OptionsCatalog.hindex d25720c45..762c73c8f 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/OptionsCatalog.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/OptionsCatalog.h@@ -143,6 +143,9 @@ enum { TEXTURE_FILTER_MODE_COUNT = 3 };// stores the level; the thickness each level stands for is in OptionsCatalog.cpp.enum { SMOKE_LEVEL_COUNT = 3 };+// Classic is the original hazard effect; Volumetric is the Linux toxin/radiation cloud.+enum { CLOUD_STYLE_COUNT = 2 };+// Shadow quality is the size of the sun's depth map, low, medium and high: 1024, 2048 and 4096// texels a side (W3DVolumetricShadow.cpp, renderShadowMap). Medium is the size the map always had.enum { SHADOW_QUALITY_COUNT = 3 };diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleSys.h b/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleSys.hindex af04b8282..50ec11cd1 100644--- a/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleSys.h+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleSys.h@@ -757,6 +757,7 @@ public:void trigger (void) { m_burstDelayLeft = 0; m_delayLeft = 0;}void setInitialDelay( UnsignedInt delay ) { m_delayLeft = delay; m_initialDelaySet = TRUE; }+ UnsignedInt getInitialDelayLeft() const { return m_delayLeft; }/// the name of the particles; a reference, as the renderer asks it of every system several times/// a frame and a copy is an atomic increment and decrement eachdiff --git a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cppindex 17de244b2..a6da87088 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp@@ -971,6 +971,7 @@ GlobalData::GlobalData()m_shadowsForParticles = TRUE; //on by default: the shipped INI has no entry for itm_volumetricSmokeShadows = TRUE;m_smokeFireLighting = TRUE;+ m_cloudStyle = 1; // approved volumetric hazard clouds unless Classic is explicitly selectedm_explosionDebrisTrails = TRUE;m_shadowQuality = 1; //medium, the 2048 map the shadows always hadm_classicGraphics = FALSE;diff --git a/GeneralsMD/Code/GameEngine/Source/Common/OptionsCatalog.cpp b/GeneralsMD/Code/GameEngine/Source/Common/OptionsCatalog.cppindex ff06cb47e..48c78fd8a 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/OptionsCatalog.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/OptionsCatalog.cpp@@ -107,6 +107,7 @@ OPTION_INT_ACCESSORS( m_windowMode )OPTION_INT_ACCESSORS( m_fullscreenScaling )OPTION_INT_ACCESSORS( m_msaaLevel )OPTION_BOOL_ACCESSORS( m_vsync )+OPTION_INT_ACCESSORS( m_cloudStyle )OPTION_BOOL_ACCESSORS( m_classicGraphics )OPTION_INT_ACCESSORS( m_lightingStyle )OPTION_INT_ACCESSORS( m_healthBarMode )@@ -413,6 +414,11 @@ const OptionDef TheOptionCatalog[] =OPTION_BOOL, APPLY_DEVICE_RESET, 0, 1,get_m_vsync, set_m_vsync },+ // Client appearance only; hazard area, lifetime and damage remain unchanged.+ { "CloudStyle", OPT_WND( "ComboBoxCloudStyle" ), "GUI:CloudStyle",+ OPTION_ENUM, APPLY_LIVE, 0, CLOUD_STYLE_COUNT - 1,+ get_m_cloudStyle, set_m_cloudStyle },+// Classic or Reforged. Classic is the picture the game shipped with: its own textures, EA's// ground tile, no normal maps, the stencil shadows and no post effects. The upscaled archives// are mounted before GlobalData exists, so Win32BIGFileSystem reads this key out of Options.inidiff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cppindex a266a705b..971da71e2 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp@@ -1129,6 +1129,17 @@ static void fillCatalogWidgets( void )if( widget == NULL )continue;+#if !defined(__linux__)+ if (strcmp(def.iniKey, "CloudStyle") == 0)+ {+ widget->winHide(TRUE);+ GameWindow *label = TheWindowManager->winGetWindowFromId(+ NULL, NAMEKEY("OptionsMenu.wnd:LabelCloudStyle"));+ if (label) label->winHide(TRUE);+ continue;+ }+#endif+const Int value = clampOptionValue( def, def.get() );switch( def.kind )diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DParticleSys.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DParticleSys.hindex 59c4498ab..3bf4fa7d3 100644--- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DParticleSys.h+++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DParticleSys.h@@ -52,6 +52,11 @@ public:~W3DParticleSystemManager();virtual void reset();+ /// Forget only cached contamination footprints; all particle systems remain alive.+ /// With fadeIn=false, fields collected on the next render appear immediately,+ /// including while logic is paused. Later fields retain their normal fade-in.+ void invalidateGroundFields(bool fadeIn = true);+ static void releaseCloudResources(); // Before display/device teardown or reset.virtual void doParticles(RenderInfoClass &rinfo);virtual void queueParticleRender();///< returns the number of particles shown on screen per framediff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrame.cpp b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrame.cppindex b78d2328e..a68801e53 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrame.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrame.cpp@@ -64,6 +64,20 @@ static const char GAMMA_PIXEL_HLSL[] =" return float4(entry(colour.r, 0), entry(colour.g, 1), entry(colour.b, 2), colour.a);\n""}\n";+// Resolve sampled device depth through a colour-only pass. This avoids reading+// a depth attachment while it is bound for writing and works across SDL backends.+static const char SCENE_DEPTH_PIXEL_HLSL[] =+ "Texture2D<float> SceneDepth : register(t0, space2);\n"+ "SamplerState DepthSampler : register(s0, space2);\n"+ "float main([[vk::location(0)]] float2 uv : TEXCOORD0) : SV_Target0\n"+ "{ return SceneDepth.SampleLevel(DepthSampler, uv, 0.0); }\n";++unsigned int SdlGpuFrame::Depth_Usage() const+{+ return SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET+ | (DepthSampleable ? SDL_GPU_TEXTUREUSAGE_SAMPLER : 0);+}+bool Sdl_Gamma_Is_Identity(const uint16_t (*ramp)[256]){if (ramp == NULL) {@@ -169,6 +183,23 @@ SdlGpuFrame * SdlGpuFrame::Create(RenderWindow window, unsigned int width, unsigframe->DepthFormat = SDL_GPUTextureSupportsFormat(frame->GpuDevice, SDL_GPU_TEXTUREFORMAT_D24_UNORM_S8_UINT,SDL_GPU_TEXTURETYPE_2D, SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET)? SDL_GPU_TEXTUREFORMAT_D24_UNORM_S8_UINT : SDL_GPU_TEXTUREFORMAT_D32_FLOAT_S8_UINT;+#if defined(__linux__)+ // Cloud clipping is optional: retain the original target-only depth format+ // when no complete sampleable depth/R32F combination is supported.+ if (SDL_GPUTextureSupportsFormat(frame->GpuDevice, SDL_GPU_TEXTUREFORMAT_R32_FLOAT,+ SDL_GPU_TEXTURETYPE_2D, SDL_GPU_TEXTUREUSAGE_COLOR_TARGET | SDL_GPU_TEXTUREUSAGE_SAMPLER)) {+ const SDL_GPUTextureFormat formats[] = {+ SDL_GPU_TEXTUREFORMAT_D24_UNORM_S8_UINT, SDL_GPU_TEXTUREFORMAT_D32_FLOAT_S8_UINT };+ for (unsigned int i = 0; i < 2; ++i) {+ if (SDL_GPUTextureSupportsFormat(frame->GpuDevice, formats[i], SDL_GPU_TEXTURETYPE_2D,+ SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET | SDL_GPU_TEXTUREUSAGE_SAMPLER)) {+ frame->DepthFormat = formats[i];+ frame->DepthSampleable = true;+ break;+ }+ }+ }+#endifif (!frame->Create_Targets(width, height)) {error = std::string("the back buffer: ") + SDL_GetError();delete frame;@@ -207,6 +238,10 @@ SdlGpuFrame::~SdlGpuFrame()if (GammaPixel != NULL) SDL_ReleaseGPUShader(GpuDevice, GammaPixel);if (RampTexture != NULL) SDL_ReleaseGPUTexture(GpuDevice, RampTexture);if (PointSampler != NULL) SDL_ReleaseGPUSampler(GpuDevice, PointSampler);+ if (SceneDepthPipeline) SDL_ReleaseGPUGraphicsPipeline(GpuDevice, SceneDepthPipeline);+ if (SceneDepthVertex) SDL_ReleaseGPUShader(GpuDevice, SceneDepthVertex);+ if (SceneDepthPixel) SDL_ReleaseGPUShader(GpuDevice, SceneDepthPixel);+ if (SceneDepthSampler) SDL_ReleaseGPUSampler(GpuDevice, SceneDepthSampler);if (Window != NULL) SDL_ReleaseWindowFromGPUDevice(GpuDevice, Window);SDL_DestroyGPUDevice(GpuDevice);}@@ -226,7 +261,7 @@ bool SdlGpuFrame::Create_Targets(unsigned int width, unsigned int height)BackBuffer = SDL_CreateGPUTexture(GpuDevice, &info);FrontCopy = SDL_CreateGPUTexture(GpuDevice, &info);info.format = (SDL_GPUTextureFormat)DepthFormat;- info.usage = SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET;+ info.usage = Depth_Usage();DepthStencil = SDL_CreateGPUTexture(GpuDevice, &info);BackWidth = width;BackHeight = height;@@ -235,6 +270,9 @@ bool SdlGpuFrame::Create_Targets(unsigned int width, unsigned int height)void SdlGpuFrame::Release_Targets(){+ for (const SceneDepthSnapshot &snapshot : SceneDepthSnapshots)+ if (snapshot.Texture) SDL_ReleaseGPUTexture(GpuDevice, snapshot.Texture);+ SceneDepthSnapshots.clear();if (BackBuffer != NULL) SDL_ReleaseGPUTexture(GpuDevice, BackBuffer);if (DepthStencil != NULL) SDL_ReleaseGPUTexture(GpuDevice, DepthStencil);if (FrontCopy != NULL) SDL_ReleaseGPUTexture(GpuDevice, FrontCopy);@@ -245,11 +283,137 @@ void SdlGpuFrame::Release_Targets()DisplayTexture = NULL; // made again at the new size by the next offscreen Present}+void SdlGpuFrame::Invalidate_Scene_Depth(SDL_GPUTexture *colour, SDL_GPUTexture *depth)+{+ for (SceneDepthSnapshot &snapshot : SceneDepthSnapshots)+ if ((colour && snapshot.Source.Colour == colour) || (depth && snapshot.Source.Depth == depth))+ snapshot.Ready = false;+}++void SdlGpuFrame::Refresh_Scene_Depth()+{+ ++SceneDepthFrame;+ for (SceneDepthSnapshot &snapshot : SceneDepthSnapshots) snapshot.Ready = false;+}++SDL_GPUTexture *SdlGpuFrame::Scene_Depth(const SdlTarget &source)+{+ if (!DepthSampleable || !source.Colour || !source.Depth || !source.Width || !source.Height+ || !Create_Scene_Depth_Pipeline()) return NULL;+ SceneDepthSnapshot *snapshot = NULL;+ for (SceneDepthSnapshot &candidate : SceneDepthSnapshots)+ if (candidate.Source.Colour == source.Colour && candidate.Source.Depth == source.Depth+ && candidate.Source.Width == source.Width && candidate.Source.Height == source.Height) {+ snapshot = &candidate;+ break;+ }+ if (!snapshot) {+ SDL_GPUTextureCreateInfo info = {};+ info.type = SDL_GPU_TEXTURETYPE_2D;+ info.format = SDL_GPU_TEXTUREFORMAT_R32_FLOAT;+ info.usage = SDL_GPU_TEXTUREUSAGE_COLOR_TARGET | SDL_GPU_TEXTUREUSAGE_SAMPLER;+ info.width = source.Width;+ info.height = source.Height;+ info.layer_count_or_depth = info.num_levels = 1;+ SceneDepthSnapshot fresh = {};+ fresh.Source = source;+ fresh.Texture = SDL_CreateGPUTexture(GpuDevice, &info);+ if (!fresh.Texture) return NULL;+ if (SceneDepthSnapshots.size() == 8) {+ size_t oldest = 0;+ for (size_t i = 1; i < SceneDepthSnapshots.size(); ++i)+ if (SceneDepthSnapshots[i].UsedFrame < SceneDepthSnapshots[oldest].UsedFrame) oldest = i;+ DeadTextures.push_back(SceneDepthSnapshots[oldest].Texture);+ SceneDepthSnapshots[oldest] = fresh;+ snapshot = &SceneDepthSnapshots[oldest];+ } else {+ SceneDepthSnapshots.push_back(fresh);+ snapshot = &SceneDepthSnapshots.back();+ }+ }+ if (!snapshot->Ready) {+ Command command = {};+ command.IsDepthSnapshot = true;+ command.BlitSource = source.Depth;+ command.BlitDestination = snapshot->Texture;+ command.Rect[2] = source.Width;+ command.Rect[3] = source.Height;+ Commands.push_back(command);+ snapshot->Ready = true;+ }+ snapshot->UsedFrame = SceneDepthFrame;+ return snapshot->Texture;+}++bool SdlGpuFrame::Create_Scene_Depth_Pipeline()+{+ if (SceneDepthPipeline && SceneDepthSampler) return true;+ std::string log;+ if (!SceneDepthVertex) {+ std::vector<unsigned char> spirv;+ if (!SDL3_Compile_HLSL_To_SPIRV(GAMMA_VERTEX_HLSL, true, spirv, log)+ || !(SceneDepthVertex = SDL3_Create_Shader(GpuDevice, spirv, true, log))) {+ fprintf(stderr, "SdlGpuFrame: scene depth vertex: %s\n", log.c_str());+ return false;+ }+ }+ if (!SceneDepthPixel) {+ std::vector<unsigned char> spirv;+ if (!SDL3_Compile_HLSL_To_SPIRV(SCENE_DEPTH_PIXEL_HLSL, false, spirv, log)+ || !(SceneDepthPixel = SDL3_Create_Shader(GpuDevice, spirv, false, log))) {+ fprintf(stderr, "SdlGpuFrame: scene depth pixel: %s\n", log.c_str());+ return false;+ }+ }+ if (!SceneDepthPipeline) {+ SDL_GPUColorTargetDescription target = {};+ target.format = SDL_GPU_TEXTUREFORMAT_R32_FLOAT;+ SDL_GPUGraphicsPipelineCreateInfo info = {};+ info.vertex_shader = SceneDepthVertex;+ info.fragment_shader = SceneDepthPixel;+ info.primitive_type = SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;+ info.rasterizer_state.fill_mode = SDL_GPU_FILLMODE_FILL;+ info.rasterizer_state.cull_mode = SDL_GPU_CULLMODE_NONE;+ info.target_info.color_target_descriptions = ⌖+ info.target_info.num_color_targets = 1;+ SceneDepthPipeline = SDL_CreateGPUGraphicsPipeline(GpuDevice, &info);+ }+ if (!SceneDepthSampler) {+ 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;+ SceneDepthSampler = SDL_CreateGPUSampler(GpuDevice, &sampler);+ }+ if (!SceneDepthPipeline || !SceneDepthSampler)+ fprintf(stderr, "SdlGpuFrame: scene depth resolve: %s\n", SDL_GetError());+ return SceneDepthPipeline && SceneDepthSampler;+}++bool SdlGpuFrame::Resolve_Scene_Depth(SDL_GPUCommandBuffer *commands, SDL_GPUTexture *source,+ SDL_GPUTexture *destination, unsigned int width, unsigned int height)+{+ SDL_GPUColorTargetInfo colour = {};+ colour.texture = destination;+ colour.load_op = SDL_GPU_LOADOP_DONT_CARE;+ colour.store_op = SDL_GPU_STOREOP_STORE;+ SDL_GPURenderPass *pass = SDL_BeginGPURenderPass(commands, &colour, 1, NULL);+ if (!pass) return false;+ SDL_BindGPUGraphicsPipeline(pass, SceneDepthPipeline);+ const SDL_GPUTextureSamplerBinding binding = { source, SceneDepthSampler };+ SDL_BindGPUFragmentSamplers(pass, 0, &binding, 1);+ const SDL_GPUViewport viewport = { 0, 0, (float)width, (float)height, 0, 1 };+ SDL_SetGPUViewport(pass, &viewport);+ SDL_DrawGPUPrimitives(pass, 3, 1, 0, 0);+ SDL_EndGPURenderPass(pass);+ return true;+}+bool SdlGpuFrame::Resize(unsigned int width, unsigned int height){// What is recorded runs first: the GPU copies count the uploads it carries as done. The current// target named the old back buffer; the device sets it again before its next draw.- Flush();+ if (!width || !height || !Flush()) return false;TargetSet = false;Release_Targets();return Create_Targets(width, height);@@ -257,6 +421,8 @@ bool SdlGpuFrame::Resize(unsigned int width, unsigned int height)void SdlGpuFrame::Clear_Back_Buffer(bool colour, bool depth, bool stencil, uint32_t argb, float z, uint32_t stencil_value){+ const SdlTarget target = TargetSet ? CurrentTarget : Back_Buffer_Target();+ Invalidate_Scene_Depth(colour ? target.Colour : NULL, depth ? target.Depth : NULL);if (!colour && !depth && !stencil) {return;}@@ -633,10 +799,12 @@ bool SdlGpuFrame::Present(const uint16_t (*ramp)[256])}const bool submitted = Submit_Offscreen(commands);End_Batch();+ Refresh_Scene_Depth();return submitted && ok && DisplayTexture != NULL;}const bool submitted = Submit(commands);End_Batch();+ Refresh_Scene_Depth();return submitted && ok;}@@ -651,6 +819,7 @@ bool SdlGpuFrame::Present_To(SDL_GPUTexture * target, unsigned int width, unsignok = Present_Into(commands, target, width, height, BACK_BUFFER_FORMAT, ramp) && ok;const bool submitted = Submit(commands);End_Batch();+ Refresh_Scene_Depth();return submitted && ok;}diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrame.h b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrame.hindex 6bca8483d..bd8407b35 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrame.h+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrame.h@@ -49,8 +49,8 @@ struct SDL_GPUShader;struct SDL_GPUTexture;struct SDL_Window;-/// Where a pass draws: a colour texture of Target_Format() and a depth-stencil of Depth_Format(), the-/// same size. The back buffer is one; a render-target surface's GPU texture is another (A3d).+/// Where a pass draws: a colour texture of Target_Format() and an optional depth-stencil+/// of Depth_Format(), the same size. Cloud caches have colour attachments only.struct SdlTarget{SDL_GPUTexture * Colour;@@ -79,6 +79,9 @@ struct SdlRecordedDrawuint32_t SamplerCount;SDL_GPUTexture * Textures[MAXIMUM_SAMPLERS];SDL_GPUSampler * Samplers[MAXIMUM_SAMPLERS];+ uint32_t VertexSamplerCount;+ SDL_GPUTexture * VertexTextures[MAXIMUM_SAMPLERS];+ SDL_GPUSampler * VertexSamplers[MAXIMUM_SAMPLERS];float Viewport[6]; ///< x, y, width, height, min depth, max depth: as the GPU takes itint32_t Scissor[4]; ///< x, y, width, heightuint32_t StencilReference;@@ -153,8 +156,14 @@ public:/// Whether the batch has grown enough that the next draw should flush first: its staged and uploaded bytes,/// or its draws (BatchDrawLimit). Counts the flushes the draw limit asks for.bool Batch_Is_Full();- /// The depth-stencil's SDL_GPUTextureFormat. Every pass has it attached.+ /// The scene depth-stencil format; colour-only passes omit that attachment.unsigned int Depth_Format() const { return DepthFormat; }+ /// Includes sampling only when a supported Linux scene-depth format is available.+ unsigned int Depth_Usage() const;+ /// Sampleable device depth captured after opaque scene draws, once per target/frame.+ /// The result is borrowed for immediate draw recording; callers must not release it.+ /// Returns null when unavailable so callers can keep their existing effect.+ SDL_GPUTexture * Scene_Depth(const SdlTarget &source);/// Flush, then the back buffer to the window through the gamma ramp (null: none, a straight blit).bool Present(const uint16_t (*ramp)[256]);@@ -270,6 +279,24 @@ private:SDL_GPUTexture * DepthStencil;SDL_GPUTexture * FrontCopy; ///< the last presented picturebool Copy_To_Front(struct SDL_GPUCommandBuffer * commands);+ bool DepthSampleable = false;+ struct SceneDepthSnapshot {+ SdlTarget Source;+ SDL_GPUTexture * Texture;+ bool Ready;+ uint64_t UsedFrame;+ };+ std::vector<SceneDepthSnapshot> SceneDepthSnapshots;+ uint64_t SceneDepthFrame = 0;+ SDL_GPUShader * SceneDepthVertex = NULL;+ SDL_GPUShader * SceneDepthPixel = NULL;+ SDL_GPUGraphicsPipeline * SceneDepthPipeline = NULL;+ SDL_GPUSampler * SceneDepthSampler = NULL;+ void Refresh_Scene_Depth();+ void Invalidate_Scene_Depth(SDL_GPUTexture *colour, SDL_GPUTexture *depth);+ bool Create_Scene_Depth_Pipeline();+ bool Resolve_Scene_Depth(struct SDL_GPUCommandBuffer *commands, SDL_GPUTexture *source,+ SDL_GPUTexture *destination, unsigned int width, unsigned int height);unsigned int DepthFormat; ///< an SDL_GPUTextureFormat: D24S8 where there is one, else D32S8unsigned int BackWidth;unsigned int BackHeight;@@ -282,6 +309,7 @@ private:bool IsRect; ///< a clear draw over Rect, not a load operationint32_t Rect[4]; ///< x, y, width, heightuint32_t Target; ///< into Targets: where a clear or draw goes+ bool IsDepthSnapshot; ///< depth sampled into an independent R32F targetbool IsBlit; ///< a copy between textures, Rect to BlitRectSDL_GPUTexture * BlitSource;SDL_GPUTexture * BlitDestination;diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrameBatch.cpp b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrameBatch.cppindex fb824ca26..967ed57f9 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrameBatch.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrameBatch.cpp@@ -114,6 +114,8 @@ void SdlGpuFrame::Clear_Rect(int x, int y, int width, int height, bool colour, bif ((!colour && !depth && !stencil) || width <= 0 || height <= 0) {return;}+ const SdlTarget target = TargetSet ? CurrentTarget : Back_Buffer_Target();+ Invalidate_Scene_Depth(colour ? target.Colour : NULL, depth ? target.Depth : NULL);Command command;memset(&command, 0, sizeof(command));command.IsRect = true;@@ -204,7 +206,18 @@ void SdlGpuFrame::Record_Draw(const SdlRecordedDraw & draw)void SdlGpuFrame::Release_After_Batch(SDL_GPUTexture * texture, SDL_GPUBuffer * buffer){- if (texture != NULL) DeadTextures.push_back(texture);+ if (texture != NULL) {+ // Drop identities before SDL can recycle a source handle. Recorded users+ // retain their textures through this batch's deferred release queue.+ for (size_t i = SceneDepthSnapshots.size(); i-- > 0;) {+ const SceneDepthSnapshot &snapshot = SceneDepthSnapshots[i];+ if (snapshot.Source.Colour == texture || snapshot.Source.Depth == texture) {+ if (snapshot.Texture) DeadTextures.push_back(snapshot.Texture);+ SceneDepthSnapshots.erase(SceneDepthSnapshots.begin() + i);+ }+ }+ DeadTextures.push_back(texture);+ }if (buffer != NULL) DeadBuffers.push_back(buffer);}@@ -343,7 +356,10 @@ bool SdlGpuFrame::Begin_Pass(SDL_GPUCommandBuffer * commands, const SdlTarget &depth.store_op = SDL_GPU_STOREOP_STORE;depth.stencil_load_op = clear_stencil ? SDL_GPU_LOADOP_CLEAR : SDL_GPU_LOADOP_LOAD;depth.stencil_store_op = SDL_GPU_STOREOP_STORE;- *pass = SDL_BeginGPURenderPass(commands, &colour, 1, &depth);+ // SDL requires an absent attachment's descriptor to be null, rather than+ // a descriptor containing a null texture (cloud caches are colour-only).+ *pass = SDL_BeginGPURenderPass(commands, target.Colour ? &colour : NULL, target.Colour ? 1 : 0,+ target.Depth ? &depth : NULL);return *pass != NULL;}@@ -385,7 +401,7 @@ SDL_GPUTexture * SdlGpuFrame::Depth_For(unsigned int width, unsigned int height)SDL_zero(info);info.type = SDL_GPU_TEXTURETYPE_2D;info.format = (SDL_GPUTextureFormat)DepthFormat;- info.usage = SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET;+ info.usage = Depth_Usage();info.width = width;info.height = height;info.layer_count_or_depth = 1;@@ -401,6 +417,7 @@ SDL_GPUTexture * SdlGpuFrame::Depth_For(unsigned int width, unsigned int height)void SdlGpuFrame::Record_Blit(SDL_GPUTexture * source, const int32_t source_rect[4], SDL_GPUTexture * destination,const int32_t destination_rect[4], bool linear){+ Invalidate_Scene_Depth(destination, NULL);Command command;memset(&command, 0, sizeof(command));command.IsBlit = true;@@ -434,15 +451,16 @@ bool SdlGpuFrame::Record_Passes(SDL_GPUCommandBuffer * commands, SDL_GPUBuffer *for (size_t i = 0; i <= Commands.size(); ++i) {const bool end = i == Commands.size();const Command * command = end ? NULL : &Commands[i];- const bool whole_clear = !end && !command->IsDraw && !command->IsRect && !command->IsBlit;+ const bool transfer = !end && (command->IsBlit || command->IsDepthSnapshot);+ const bool whole_clear = !end && !command->IsDraw && !command->IsRect && !transfer;// A pass ends at a blit, at a whole-target clear, at a change of target, and at the end.- if (pass != NULL && (end || command->IsBlit || whole_clear || command->Target != pass_target)) {+ if (pass != NULL && (end || transfer || whole_clear || command->Target != pass_target)) {SDL_EndGPURenderPass(pass);pass = NULL;}// A waiting clear whose target is not the next thing drawn into gets a pass of its own.- if (pending && (end || command->IsBlit || command->Target != pending_target)) {+ if (pending && (end || transfer || command->Target != pending_target)) {if (!Begin_Pass(commands, Targets[pending_target], clear_colour, clear_depth, clear_stencil, argb, z,stencil_value, &pass)) {return false;@@ -454,6 +472,11 @@ bool SdlGpuFrame::Record_Passes(SDL_GPUCommandBuffer * commands, SDL_GPUBuffer *if (end) {break;}+ if (command->IsDepthSnapshot) {+ if (!Resolve_Scene_Depth(commands, command->BlitSource, command->BlitDestination,+ (unsigned int)command->Rect[2], (unsigned int)command->Rect[3])) return false;+ continue;+ }if (command->IsBlit) {SDL_GPUBlitInfo blit;SDL_zero(blit);@@ -558,6 +581,16 @@ bool SdlGpuFrame::Record_Passes(SDL_GPUCommandBuffer * commands, SDL_GPUBuffer *}SDL_BindGPUFragmentSamplers(pass, 0, bindings, draw.SamplerCount);}+ if (draw.VertexSamplerCount > 0 && (last == NULL || last->VertexSamplerCount != draw.VertexSamplerCount+ || memcmp(last->VertexTextures, draw.VertexTextures, sizeof(draw.VertexTextures[0]) * draw.VertexSamplerCount) != 0+ || memcmp(last->VertexSamplers, draw.VertexSamplers, sizeof(draw.VertexSamplers[0]) * draw.VertexSamplerCount) != 0)) {+ SDL_GPUTextureSamplerBinding bindings[SdlRecordedDraw::MAXIMUM_SAMPLERS];+ for (uint32_t slot = 0; slot < draw.VertexSamplerCount; ++slot) {+ bindings[slot].texture = draw.VertexTextures[slot];+ bindings[slot].sampler = draw.VertexSamplers[slot];+ }+ SDL_BindGPUVertexSamplers(pass, 0, bindings, draw.VertexSamplerCount);+ }if (draw.VertexConstantsSize != 0 && draw.VertexConstants != pushed_vertex) {SDL_PushGPUVertexUniformData(commands, 0, &ConstantBytes[draw.VertexConstants], draw.VertexConstantsSize);pushed_vertex = draw.VertexConstants;diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloud.cpp b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloud.cppnew file mode 100644index 000000000..67c5b989a--- /dev/null+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloud.cpp@@ -0,0 +1,1112 @@+// Shared world-space hazard clouds; game and isolated preview use one renderer.+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.+#include "PreRTS.h"+#include "Platform/SdlHazardCloud.h"+#include "SdlHazardCloudShader.h"+#include "SdlHazardCloudEmbers.h"+#include "WW3D2/dx8wrapper.h"+#include "WW3D2/sdl3shadercompile.h"+#include "PosixDevice9.h"+#include "SdlGpuFrame.h"+#include "SdlRenderMatrix.h"+#include "SdlResourceMirror.h"+#include <SDL3/SDL.h>+#include <algorithm>+#include <array>+#include <cmath>+#include <cstdio>+#include <cstdlib>+#include <cstring>+#include <limits>+#include <string>+#include <vector>++namespace SdlHazardCloud {+namespace {+const float Steps = 96.0f;+const float MaximumDisplacement = 18.0f;+const unsigned MaximumBodies = 32;+const SDL_GPUTextureFormat LowTargetFormat = SDL_GPU_TEXTUREFORMAT_R16G16B16A16_FLOAT;+const SDL_GPUTextureUsageFlags LowTargetUsage = SDL_GPU_TEXTUREUSAGE_COLOR_TARGET | SDL_GPU_TEXTUREUSAGE_SAMPLER;+const SDL_GPUTextureFormat DensityTargetFormat = SDL_GPU_TEXTUREFORMAT_R16_FLOAT;+const unsigned CacheSlices = 24;+const unsigned CacheColumns = 6;+const unsigned CacheRows = CacheSlices / CacheColumns;+struct FieldCache {+ SdlTarget density = {};+ SdlTarget lighting = {};+ unsigned side = 0;+};+struct SharedResources {+ SdlGpuFrame *frame = nullptr;+ SDL_GPUDevice *gpu = nullptr;+ unsigned users = 0;+ SDL_GPUShader *vertexShader = nullptr;+ SDL_GPUShader *pixelShader = nullptr;+ SDL_GPUShader *compositePixelShader = nullptr;+ SDL_GPUShader *heatPixelShader = nullptr;+ SDL_GPUShader *densityPixelShader = nullptr;+ SDL_GPUShader *lightingPixelShader = nullptr;+ SDL_GPUGraphicsPipeline *volumePipeline = nullptr;+ SDL_GPUGraphicsPipeline *compositePipeline = nullptr;+ SDL_GPUGraphicsPipeline *heatPipeline = nullptr;+ SDL_GPUGraphicsPipeline *densityPipeline = nullptr;+ SDL_GPUGraphicsPipeline *lightingPipeline = nullptr;+ SDL_GPUSampler *depthSampler = nullptr;+ SDL_GPUSampler *flowSampler = nullptr;+ SDL_GPUSampler *cacheSampler = nullptr;+ SdlTarget lowTarget = {};+ SdlTarget heatBackground = {};+};+SharedResources shared;+constexpr std::array<Palette, 4> approved = {{+ {{0.769999981f, 0.939999998f, 0.550000012f}, {0.125490203f, 0.31764707f, 0.0549019612f}, 0.699999988f, 0.670000017f},+ {{0.749019623f, 0.670588255f, 0.469999999f}, {0.298039228f, 0.184313729f, 0.0705882385f}, 1.29999995f, 0.0f},+ {{0.660000026f, 0.75999999f, 1.0f}, {0.0649999976f, 0.100000001f, 0.209999993f}, 1.52999997f, 0.769999981f},+ {{0.839999974f, 0.629999995f, 1.0f}, {0.192156866f, 0.0470588244f, 0.235294119f}, 1.32000005f, 0.74000001f},+}};++unsigned cacheSide(const FieldState &field)+{+ const float extent = 2.0f * (field.radius + field.fringe + MaximumDisplacement);+ const unsigned samples = static_cast<unsigned>(std::clamp(std::ceil(extent / 2.0f) + 1.0f, 32.0f, 512.0f));+ return (samples + 15u) & ~15u;+}++void releaseShared(bool deviceAlive)+{+ if (deviceAlive && shared.frame && shared.gpu) {+ if (shared.lowTarget.Colour) shared.frame->Release_After_Batch(shared.lowTarget.Colour, nullptr);+ if (shared.heatBackground.Colour) shared.frame->Release_After_Batch(shared.heatBackground.Colour, nullptr);+ // Last layer only: pipelines cannot retire through Release_After_Batch.+ shared.frame->Flush();+ SDL_WaitForGPUIdle(shared.gpu);+ SdlHazardCloudEmbers::shutdown();+ if (shared.vertexShader) SDL_ReleaseGPUShader(shared.gpu, shared.vertexShader);+ if (shared.pixelShader) SDL_ReleaseGPUShader(shared.gpu, shared.pixelShader);+ if (shared.compositePixelShader) SDL_ReleaseGPUShader(shared.gpu, shared.compositePixelShader);+ if (shared.heatPixelShader) SDL_ReleaseGPUShader(shared.gpu, shared.heatPixelShader);+ if (shared.densityPixelShader) SDL_ReleaseGPUShader(shared.gpu, shared.densityPixelShader);+ if (shared.lightingPixelShader) SDL_ReleaseGPUShader(shared.gpu, shared.lightingPixelShader);+ if (shared.volumePipeline) SDL_ReleaseGPUGraphicsPipeline(shared.gpu, shared.volumePipeline);+ if (shared.compositePipeline) SDL_ReleaseGPUGraphicsPipeline(shared.gpu, shared.compositePipeline);+ if (shared.heatPipeline) SDL_ReleaseGPUGraphicsPipeline(shared.gpu, shared.heatPipeline);+ if (shared.densityPipeline) SDL_ReleaseGPUGraphicsPipeline(shared.gpu, shared.densityPipeline);+ if (shared.lightingPipeline) SDL_ReleaseGPUGraphicsPipeline(shared.gpu, shared.lightingPipeline);+ if (shared.depthSampler) SDL_ReleaseGPUSampler(shared.gpu, shared.depthSampler);+ if (shared.flowSampler) SDL_ReleaseGPUSampler(shared.gpu, shared.flowSampler);+ if (shared.cacheSampler) SDL_ReleaseGPUSampler(shared.gpu, shared.cacheSampler);+ } else {+ // The device owns native allocations; after its destruction only forget+ // our stale handles, never call through a dangling GPU/frame pointer.+ SdlHazardCloudEmbers::abandon();+ }+ shared = {};+}+} // namespace++const Palette &defaultPalette(unsigned index) { return approved[index < 4 ? index : 0]; }++struct Layer::Impl {+ FieldState fieldStates[2] = {};+ unsigned fieldCount = 0;+ float sourceTravel[2] = {}, sourceAge[2] = {}, peakDensity[2] = {};+ float simulationTime = 0;+ bool hasSimulationTime = false;+ bool initialized = false;+ bool interactionEnabled = true;+ bool heatEnabled = true;+ bool flowDirty = true;+ bool failed = false;+ bool explicitDomain = false;+ unsigned renderedFrames = 0;+ unsigned flowUploads = 0;+ uint64_t flowUsedBatch = ~uint64_t(0);+ std::vector<Body> bodies;+ SdlHazardCloudFlow::Flow flow;+ std::array<Palette, 4> palettes = approved;+ SdlGpuFrame *frame = nullptr;+ SDL_GPUDevice *gpu = nullptr;+ SDL_GPUTexture *flowTexture = nullptr;+ SDL_GPUTexture *terrainTexture = nullptr;+ std::vector<float> terrainPixels = std::vector<float>(TerrainGridSide * TerrainGridSide * 2, 0.0f);+ bool terrainEnabled[2] = {};+ float terrainMin[2] = {}, terrainMax[2] = {};+ bool terrainDirty = false;+ FieldCache fieldCaches[2];+ SdlHazardCloudUniforms cachedInputs = {};+ bool cachedInputsValid = false;+ unsigned cachedFlowUploads = 0;+ unsigned cacheUpdates = 0;+ unsigned cacheBakes = 0;++void fail(const char *reason)+{+ if (!failed) std::fprintf(stderr, "cloud-preview: volumetric renderer FAIL: %s\n", reason);+ failed = true;+}++bool makeResources()+{+ std::vector<unsigned char> spirv;+ std::string log;+ if (!SDL3_Compile_HLSL_To_SPIRV(SdlHazardCloudVertexShader(), true, spirv, log)+ || !(shared.vertexShader = SDL3_Create_Shader(gpu, spirv, true, log))) {+ fail(("vertex shader: " + log).c_str());+ return false;+ }+ if (!SDL3_Compile_HLSL_To_SPIRV(SdlHazardCloudPixelShader(false), false, spirv, log)+ || !(shared.pixelShader = SDL3_Create_Shader(gpu, spirv, false, log))) {+ fail(("volume shader: " + log).c_str());+ return false;+ }+ if (!SDL3_Compile_HLSL_To_SPIRV(SdlHazardCloudPixelShader(true), false, spirv, log)+ || !(shared.compositePixelShader = SDL3_Create_Shader(gpu, spirv, false, log))) {+ fail(("volume composite shader: " + log).c_str());+ return false;+ }+ if (!SDL3_Compile_HLSL_To_SPIRV(SdlHazardCloudHeatShader(), false, spirv, log)+ || !(shared.heatPixelShader = SDL3_Create_Shader(gpu, spirv, false, log))) {+ fail(("volume heat shader: " + log).c_str());+ return false;+ }+ if (!SDL3_Compile_HLSL_To_SPIRV(SdlHazardCloudCacheShader(false), false, spirv, log)+ || !(shared.densityPixelShader = SDL3_Create_Shader(gpu, spirv, false, log))) {+ fail(("volume density cache shader: " + log).c_str());+ return false;+ }+ if (!SDL3_Compile_HLSL_To_SPIRV(SdlHazardCloudCacheShader(true), false, spirv, log)+ || !(shared.lightingPixelShader = SDL3_Create_Shader(gpu, spirv, false, log))) {+ fail(("volume lighting cache shader: " + log).c_str());+ return false;+ }+ if (!SDL_GPUTextureSupportsFormat(gpu, LowTargetFormat, SDL_GPU_TEXTURETYPE_2D, LowTargetUsage)) {+ fail("RGBA16F cloud rendering and texture sampling are unavailable");+ return false;+ }+ if (!SDL_GPUTextureSupportsFormat(gpu, DensityTargetFormat, SDL_GPU_TEXTURETYPE_2D, LowTargetUsage)) {+ fail("R16F cloud density rendering and texture sampling are unavailable");+ return false;+ }+ SDL_GPUColorTargetDescription target = {};+ target.format = LowTargetFormat;+ SDL_GPUGraphicsPipelineCreateInfo description = {};+ description.vertex_shader = shared.vertexShader;+ description.fragment_shader = shared.pixelShader;+ 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;+ // The volume clips its ray against the sampled opaque scene depth. Its+ // fullscreen proxy neither tests nor modifies the real depth attachment.+ description.depth_stencil_state.compare_op = SDL_GPU_COMPAREOP_ALWAYS;+ description.depth_stencil_state.enable_depth_test = false;+ description.depth_stencil_state.enable_depth_write = false;+ description.target_info.color_target_descriptions = ⌖+ description.target_info.num_color_targets = 1;+ // The low pass owns only a colour target. Its shader reads the captured+ // full-resolution depth and writes premultiplied radiance without blending.+ shared.volumePipeline = SDL_CreateGPUGraphicsPipeline(gpu, &description);+ if (!shared.volumePipeline) { fail(SDL_GetError()); return false; }+ target.format = static_cast<SDL_GPUTextureFormat>(SdlGpuFrame::Target_Format());+ target.blend_state.enable_blend = true;+ target.blend_state.src_color_blendfactor = SDL_GPU_BLENDFACTOR_ONE;+ target.blend_state.dst_color_blendfactor = SDL_GPU_BLENDFACTOR_ONE_MINUS_SRC_ALPHA;+ target.blend_state.color_blend_op = SDL_GPU_BLENDOP_ADD;+ target.blend_state.src_alpha_blendfactor = SDL_GPU_BLENDFACTOR_ONE;+ target.blend_state.dst_alpha_blendfactor = SDL_GPU_BLENDFACTOR_ONE_MINUS_SRC_ALPHA;+ target.blend_state.alpha_blend_op = SDL_GPU_BLENDOP_ADD;+ description.fragment_shader = shared.compositePixelShader;+ description.target_info.has_depth_stencil_target = true;+ description.target_info.depth_stencil_format = static_cast<SDL_GPUTextureFormat>(frame->Depth_Format());+ shared.compositePipeline = SDL_CreateGPUGraphicsPipeline(gpu, &description);+ if (!shared.compositePipeline) { fail(SDL_GetError()); return false; }+ description.fragment_shader = shared.heatPixelShader;+ shared.heatPipeline = SDL_CreateGPUGraphicsPipeline(gpu, &description);+ if (!shared.heatPipeline) { fail(SDL_GetError()); return false; }+ target = {};+ target.format = DensityTargetFormat;+ description.fragment_shader = shared.densityPixelShader;+ description.target_info.has_depth_stencil_target = false;+ description.target_info.depth_stencil_format = SDL_GPU_TEXTUREFORMAT_INVALID;+ shared.densityPipeline = SDL_CreateGPUGraphicsPipeline(gpu, &description);+ if (!shared.densityPipeline) { fail(SDL_GetError()); return false; }+ target.format = LowTargetFormat;+ description.fragment_shader = shared.lightingPixelShader;+ shared.lightingPipeline = SDL_CreateGPUGraphicsPipeline(gpu, &description);+ if (!shared.lightingPipeline) { fail(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;+ shared.depthSampler = SDL_CreateGPUSampler(gpu, &sampler);+ // Float32 linear filtering is optional on some backends. The volume shader+ // performs bilinear interpolation explicitly using this point sampler.+ shared.flowSampler = SDL_CreateGPUSampler(gpu, &sampler);+ // The atlas shader clamps XY to individual slice texel centres before the+ // bilinear lookup; it interpolates Z explicitly between adjacent slices.+ sampler.min_filter = sampler.mag_filter = SDL_GPU_FILTER_LINEAR;+ shared.cacheSampler = SDL_CreateGPUSampler(gpu, &sampler);+ if (!shared.depthSampler || !shared.flowSampler || !shared.cacheSampler) {+ fail(SDL_GetError());+ return false;+ }+ return true;+}++bool makeFlowTexture()+{+ const SDL_GPUTextureFormat flowFormat = SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;+ const SDL_GPUTextureUsageFlags flowUsage = SDL_GPU_TEXTUREUSAGE_SAMPLER;+ if (!SDL_GPUTextureSupportsFormat(gpu, flowFormat, SDL_GPU_TEXTURETYPE_2D, flowUsage)) {+ fail("RGBA32F interaction texture sampling is unavailable");+ return false;+ }+ SDL_GPUTextureCreateInfo flowDescription = {};+ flowDescription.type = SDL_GPU_TEXTURETYPE_2D;+ flowDescription.format = flowFormat;+ flowDescription.usage = flowUsage;+ flowDescription.width = flow.width();+ flowDescription.height = flow.height();+ flowDescription.layer_count_or_depth = flowDescription.num_levels = 1;+ flowTexture = SDL_CreateGPUTexture(gpu, &flowDescription);+ if (!flowTexture) {+ fail(SDL_GetError());+ return false;+ }+ return true;+}++bool resizeLowTarget(unsigned width, unsigned height)+{+ const unsigned lowWidth = width / 2 + width % 2;+ const unsigned lowHeight = height / 2 + height % 2;+ if (shared.lowTarget.Colour && shared.lowTarget.Width == lowWidth && shared.lowTarget.Height == lowHeight) return true;+ SDL_GPUTextureCreateInfo description = {};+ description.type = SDL_GPU_TEXTURETYPE_2D;+ description.format = LowTargetFormat;+ description.usage = LowTargetUsage;+ description.width = lowWidth;+ description.height = lowHeight;+ description.layer_count_or_depth = description.num_levels = 1;+ description.sample_count = SDL_GPU_SAMPLECOUNT_1;+ SDL_GPUTexture *texture = SDL_CreateGPUTexture(gpu, &description);+ if (!texture) { fail(SDL_GetError()); return false; }+ // Recorded passes retain the old texture until this batch is submitted;+ // SDL then keeps it alive until the GPU has finished those users.+ if (shared.lowTarget.Colour) frame->Release_After_Batch(shared.lowTarget.Colour, nullptr);+ shared.lowTarget = { texture, nullptr, lowWidth, lowHeight };+ return true;+}++bool prepareHeatBackground(const SdlTarget &target)+{+ if (!shared.heatBackground.Colour || shared.heatBackground.Width != target.Width || shared.heatBackground.Height != target.Height) {+ SDL_GPUTextureCreateInfo description = {};+ description.type = SDL_GPU_TEXTURETYPE_2D;+ description.format = static_cast<SDL_GPUTextureFormat>(SdlGpuFrame::Target_Format());+ description.usage = LowTargetUsage;+ description.width = target.Width;+ description.height = target.Height;+ description.layer_count_or_depth = description.num_levels = 1;+ description.sample_count = SDL_GPU_SAMPLECOUNT_1;+ SDL_GPUTexture *texture = SDL_CreateGPUTexture(gpu, &description);+ if (!texture) { fail(SDL_GetError()); return false; }+ if (shared.heatBackground.Colour) frame->Release_After_Batch(shared.heatBackground.Colour, nullptr);+ shared.heatBackground = { texture, nullptr, target.Width, target.Height };+ }+ return true;+}++void captureHeatBackground(const SdlTarget &target)+{+ // Capture the actual scene at this draw, not a possibly earlier pre-water+ // snapshot. The queued blit separates attachment writes from shader reads;+ // it requires neither a readback nor an extra GPU submission/wait.+ const int32_t rectangle[4] = { 0, 0, static_cast<int32_t>(target.Width), static_cast<int32_t>(target.Height) };+ frame->Record_Blit(target.Colour, rectangle, shared.heatBackground.Colour, rectangle, false);+}++void retireCache(FieldCache &cache)+{+ if (cache.density.Colour) frame->Release_After_Batch(cache.density.Colour, nullptr);+ if (cache.lighting.Colour) frame->Release_After_Batch(cache.lighting.Colour, nullptr);+ cache = {};+}++bool resizeFieldCache(unsigned index)+{+ const FieldState &field = fieldStates[index];+ const float extent = 2.0f * (field.radius + field.fringe + MaximumDisplacement);+ // Include both domain boundaries, retain at most two world units between+ // grid nodes, and round the dimension up to a small allocation granularity.+ const unsigned side = cacheSide(field);+ FieldCache &cache = fieldCaches[index];+ if (cache.side == side && cache.density.Colour && cache.lighting.Colour) return true;+ SDL_GPUTextureCreateInfo description = {};+ description.type = SDL_GPU_TEXTURETYPE_2D;+ description.format = DensityTargetFormat;+ description.usage = LowTargetUsage;+ description.width = side * CacheColumns;+ description.height = side * CacheRows;+ description.layer_count_or_depth = description.num_levels = 1;+ description.sample_count = SDL_GPU_SAMPLECOUNT_1;+ SDL_GPUTexture *density = SDL_CreateGPUTexture(gpu, &description);+ if (!density) { fail(SDL_GetError()); return false; }+ description.format = LowTargetFormat;+ SDL_GPUTexture *lighting = SDL_CreateGPUTexture(gpu, &description);+ if (!lighting) {+ fail(SDL_GetError());+ SDL_ReleaseGPUTexture(gpu, density);+ return false;+ }+ retireCache(cache);+ cache.density = { density, nullptr, description.width, description.height };+ cache.lighting = { lighting, nullptr, description.width, description.height };+ cache.side = side;+ cachedInputsValid = false;+ std::fprintf(stderr, "cloud-preview: volume-cache field=%u grid=%ux%ux%u atlas=%ux%u spacing=%.3f\n",+ index, side, side, CacheSlices, description.width, description.height, extent / (side - 1));+ return true;+}++void bindCachedTextures(SdlRecordedDraw &draw, bool density)+{+ for (unsigned i = 0; i < 2; ++i) {+ SDL_GPUTexture *texture = density ? fieldCaches[i].density.Colour : fieldCaches[i].lighting.Colour;+ // An inactive/unallocated field never samples its cache. Still bind a+ // valid 2D texture, with a point sampler for the RGBA32F placeholder.+ draw.Textures[3 + i] = texture ? texture : flowTexture;+ draw.Samplers[3 + i] = texture ? shared.cacheSampler : shared.flowSampler;+ }+}++bool prepareCaches(SdlHazardCloudUniforms &uniforms, SDL_GPUTexture *sceneDepth,+ uint32_t vertexOffset, const SdlTarget &restoreTarget)+{+ bool active[2] = {};+ float *grids[] = { uniforms.Cache0, uniforms.Cache1 };+ for (unsigned i = 0; i < fieldCount; ++i) {+ const FieldState &field = fieldStates[i];+ active[i] = field.radius > 0.001f && field.height > 0.002f && field.density > 0.00001f;+ if (!active[i]) continue;+ if (!resizeFieldCache(i)) return false;+ grids[i][0] = grids[i][1] = static_cast<float>(fieldCaches[i].side);+ grids[i][2] = static_cast<float>(CacheSlices);+ grids[i][3] = static_cast<float>(CacheColumns);+ }+ // Exclude all view-dependent values from the cache key. Orbiting, zooming,+ // resizing or drawing a paused frame can reuse the same world-space volume.+ SdlHazardCloudUniforms inputs = uniforms;+ std::fill(inputs.WorldFromClip, inputs.WorldFromClip + 16, 0.0f);+ std::fill(inputs.CameraPosition, inputs.CameraPosition + 4, 0.0f);+ std::fill(inputs.Viewport, inputs.Viewport + 4, 0.0f);+ inputs.Scene[0] = inputs.Scene[1] = inputs.Scene[2] = 0;+ inputs.Settings[1] = inputs.Settings[3] = 0;+ std::fill(inputs.CachePass, inputs.CachePass + 4, 0.0f);+ // Preview-only stress measurement: include full cache construction in every+ // rendered frame, even when rendering outruns simulation. This bounds the+ // cost when other effects leave only one render per simulation update.+ static const bool forceRebuild = []() {+ const char *value = std::getenv("ZH_CLOUD_PREVIEW_REBUILD_EVERY_FRAME");+ return value && value[0] == '1';+ }();+ if (!forceRebuild && cachedInputsValid && cachedFlowUploads == flowUploads+ && std::memcmp(&inputs, &cachedInputs, sizeof(inputs)) == 0) return true;++ bool rebuilt = false;+ for (unsigned i = 0; i < fieldCount; ++i) {+ if (!active[i]) continue;+ const FieldCache &cache = fieldCaches[i];+ SdlHazardCloudUniforms bake = uniforms;+ bake.CachePass[0] = static_cast<float>(i);+ SdlRecordedDraw draw = {};+ draw.Pipeline = shared.densityPipeline;+ draw.VertexOffset = vertexOffset;+ draw.Count = 3;+ draw.PixelConstants = frame->Constants(1, &bake, sizeof(bake));+ draw.PixelConstantsSize = sizeof(bake);+ // Shader reflection can retain declared atlas bindings even when this+ // variant does not read them. Supply all five slots, with harmless+ // placeholders that never alias the density attachment being written.+ draw.SamplerCount = 5;+ bindTerrain(draw);+ draw.Textures[0] = sceneDepth;+ draw.Samplers[0] = shared.depthSampler;+ draw.Textures[1] = flowTexture;+ draw.Samplers[1] = shared.flowSampler;+ for (unsigned slot = 2; slot < 5; ++slot) {+ draw.Textures[slot] = flowTexture;+ draw.Samplers[slot] = shared.flowSampler;+ }+ draw.Viewport[2] = static_cast<float>(cache.density.Width);+ draw.Viewport[3] = static_cast<float>(cache.density.Height);+ draw.Viewport[5] = 1;+ draw.Scissor[2] = static_cast<int32_t>(cache.density.Width);+ draw.Scissor[3] = static_cast<int32_t>(cache.density.Height);+ frame->Set_Target(cache.density);+ frame->Clear_Back_Buffer(true, false, false, 0, 1.0f, 0);+ frame->Record_Draw(draw);++ // Switching targets ends the density-writing pass before the lighting+ // pass reads it. The later camera pass similarly reads completed light.+ draw.Pipeline = shared.lightingPipeline;+ draw.SamplerCount = 5;+ bindTerrain(draw);+ draw.Textures[2] = flowTexture;+ draw.Samplers[2] = shared.flowSampler;+ bindCachedTextures(draw, true);+ frame->Set_Target(cache.lighting);+ frame->Clear_Back_Buffer(true, false, false, 0, 1.0f, 0);+ frame->Record_Draw(draw);+ ++cacheBakes;+ rebuilt = true;+ }+ frame->Set_Target(restoreTarget);+ cachedInputs = inputs;+ cachedFlowUploads = flowUploads;+ cachedInputsValid = true;+ if (rebuilt) ++cacheUpdates;+ return true;+}++bool uploadTerrain()+{+ if (!terrainEnabled[0] && !terrainEnabled[1]) return true;+ if (!terrainTexture) {+ SDL_GPUTextureCreateInfo info = {};+ info.type = SDL_GPU_TEXTURETYPE_2D;+ info.format = SDL_GPU_TEXTUREFORMAT_R32_FLOAT;+ info.usage = SDL_GPU_TEXTUREUSAGE_SAMPLER;+ info.width = TerrainGridSide * 2;+ info.height = TerrainGridSide;+ info.layer_count_or_depth = info.num_levels = 1;+ if (!SDL_GPUTextureSupportsFormat(gpu, info.format, info.type, info.usage)+ || !(terrainTexture = SDL_CreateGPUTexture(gpu, &info))) {+ fail("terrain height texture is unavailable");+ return false;+ }+ terrainDirty = true;+ }+ if (!terrainDirty) return true;+ // Uploads precede every recorded draw in a batch; flush this layer's old+ // readers before replacing heights, just as for its independent flow map.+ if (flowUsedBatch == frame->Batch() && !frame->Flush()) {+ fail("could not submit preceding terrain texture users");+ return false;+ }+ const uint32_t bytes = static_cast<uint32_t>(terrainPixels.size() * sizeof(float));+ uint32_t offset = 0;+ std::memcpy(frame->Upload_Space(bytes, offset), terrainPixels.data(), bytes);+ frame->Queue_Texture_Upload(terrainTexture, 0, TerrainGridSide * 2, TerrainGridSide, offset);+ terrainDirty = false;+ cachedInputsValid = false;+ return true;+}++void bindTerrain(SdlRecordedDraw &draw)+{+ draw.SamplerCount = 7;+ draw.Textures[5] = flowTexture;+ draw.Samplers[5] = shared.flowSampler;+ draw.Textures[6] = terrainTexture ? terrainTexture : flowTexture;+ draw.Samplers[6] = shared.flowSampler;+}++bool uploadFlow()+{+ if (!flowDirty) return true;+ if (!flow.valid()) {+ fail("interaction simulation produced invalid state");+ return false;+ }+ // Batch uploads run before all its draws. Submit any already-recorded user+ // before replacing the texture, otherwise that draw would read a later step.+ // Level-zero upload cycling then protects users in earlier submitted batches.+ if (flowUsedBatch == frame->Batch() && !frame->Flush()) {+ fail("could not submit preceding interaction texture users");+ return false;+ }+ const uint32_t bytes = flow.width() * flow.height() * 4 * sizeof(float);+ uint32_t offset = 0;+ std::memcpy(frame->Upload_Space(bytes, offset), flow.data(), bytes);+ frame->Queue_Texture_Upload(flowTexture, 0, flow.width(), flow.height(), offset);+ flowDirty = false;+ ++flowUploads;+ return true;+}++bool resolveSceneTarget(PosixDevice9 *device, SdlTarget &target)+{+ IDirect3DSurface9 *current = nullptr, *back = nullptr, *depth = nullptr;+ device->GetRenderTarget(0, ¤t);+ device->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &back);+ device->GetDepthStencilSurface(&depth);+ SdlResourceMirrors *mirrors = device->Get_Mirrors();+ std::string reason;+ 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;+ // The main scene can be an engine-owned postprocessing texture.+ // Its surface and texture share one GPU allocation, so resolve the+ // texture's existing mirror rather than creating a separate surface.+ 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, reason);+ if (level) level->Release();+ texture->Release();+ } else {+ target.Colour = mirrors->Surface(current, false, reason);+ }+ }+ }+ if (target.Colour && mirrors) {+ D3DSURFACE_DESC description;+ // Explicit depth surfaces already used by opaque scene draws have a+ // mirror. The implicit depth surface is owned by SdlGpuFrame instead;+ // the device also borrows its size-matched depth for intermediate targets.+ // Read only a known explicit mirror, never allocate an empty depth here.+ 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, reason);+ 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 || !target.Width || !target.Height) {+ fail(reason.empty() ? "could not resolve the current scene colour/depth target" : reason.c_str());+ return false;+ }+ return true;+}++void heatScissor(const float viewProjection[16], const D3DVIEWPORT9 &viewport,+ const SdlTarget &target, int32_t rectangle[4])+{+ const float left = static_cast<float>(std::min(viewport.X, target.Width));+ const float top = static_cast<float>(std::min(viewport.Y, target.Height));+ const float right = left + std::min(viewport.Width, target.Width - static_cast<unsigned>(left));+ const float bottom = top + std::min(viewport.Height, target.Height - static_cast<unsigned>(top));+ rectangle[0] = static_cast<int32_t>(left);+ rectangle[1] = static_cast<int32_t>(top);+ rectangle[2] = static_cast<int32_t>(right - left);+ rectangle[3] = static_cast<int32_t>(bottom - top);+ float minX = 1.0e30f, minY = 1.0e30f, maxX = -1.0e30f, maxY = -1.0e30f;+ bool found = false;+ for (unsigned i = 0; i < fieldCount; ++i) {+ const FieldState &field = fieldStates[i];+ if (field.palette < 0.5f || field.palette >= 1.5f || field.radius <= 0.001f+ || field.height <= 0.002f || field.density <= 0.00001f) continue;+ found = true;+ const float radius = field.radius + field.fringe + MaximumDisplacement;+ for (unsigned corner = 0; corner < 8; ++corner) {+ const float world[4] = {+ field.ground.x + (corner & 1 ? radius : -radius),+ field.ground.y + (corner & 2 ? radius : -radius),+ (terrainEnabled[i] ? (corner & 4 ? terrainMax[i] : terrainMin[i]) : field.ground.z)+ + (corner & 4 ? field.height * 2.6f : 0.0f), 1.0f+ };+ float clip[4] = {};+ for (unsigned column = 0; column < 4; ++column)+ for (unsigned row = 0; row < 4; ++row)+ clip[column] += world[row] * viewProjection[row * 4 + column];+ // A box crossing the near plane cannot be bounded by projecting+ // only its corners. Keep the full viewport for that unusual view.+ if (!std::isfinite(clip[0]) || !std::isfinite(clip[1])+ || !std::isfinite(clip[2]) || !std::isfinite(clip[3])+ || clip[3] <= 0.00001f || clip[2] <= 0.00001f) return;+ const float x = viewport.X + 0.5f + (clip[0] / clip[3] + 1.0f) * viewport.Width * 0.5f;+ const float y = viewport.Y + 0.5f + (1.0f - clip[1] / clip[3]) * viewport.Height * 0.5f;+ minX = std::min(minX, x); maxX = std::max(maxX, x);+ minY = std::min(minY, y); maxY = std::max(maxY, y);+ }+ }+ if (!found) { rectangle[2] = rectangle[3] = 0; return; }+ // Two pixels of conservative rasterization slack keep the projected+ // envelope intact at viewport edges and odd framebuffer dimensions.+ const float boundedLeft = std::clamp(std::floor(minX) - 2.0f, left, right);+ const float boundedTop = std::clamp(std::floor(minY) - 2.0f, top, bottom);+ const float boundedRight = std::clamp(std::ceil(maxX) + 2.0f, left, right);+ const float boundedBottom = std::clamp(std::ceil(maxY) + 2.0f, top, bottom);+ rectangle[0] = static_cast<int32_t>(boundedLeft);+ rectangle[1] = static_cast<int32_t>(boundedTop);+ rectangle[2] = static_cast<int32_t>(std::max(0.0f, boundedRight - boundedLeft));+ rectangle[3] = static_cast<int32_t>(std::max(0.0f, boundedBottom - boundedTop));+}++bool renderVolume()+{+ if (!initialized || failed || !fieldCount) return false;+ bool active = false;+ for (unsigned i = 0; i < fieldCount; ++i)+ active = active || (fieldStates[i].radius > 0.001f && fieldStates[i].height > 0.002f+ && fieldStates[i].density > 0.00001f);+ if (!active) return false;+ PosixDevice9 *device = static_cast<PosixDevice9 *>(DX8Wrapper::_Get_D3D_Device());+ if (!device || device->Get_Gpu() != frame) {+ fail("the preview graphics device was replaced");+ return false;+ }+ // The scene's normal pass can target an intermediate texture. Resolve that+ // actual colour/depth pair, rather than assuming it is the final back buffer.+ // Reflection and custom passes are excluded by the Render callback below.+ SdlTarget target;+ if (!resolveSceneTarget(device, target)) return false;+ if (!resizeLowTarget(target.Width, target.Height)) return false;+ if (frame->Batch_Is_Full() && !frame->Flush()) {+ fail("could not submit preceding scene draws");+ return false;+ }+ if (!uploadFlow() || !uploadTerrain()) return false;+ SDL_GPUTexture *sceneDepth = frame->Scene_Depth(target);+ if (!sceneDepth) {+ fail("sampleable scene depth is unavailable; volume clipping cannot run");+ return false;+ }+ D3DMATRIX view, projection;+ D3DVIEWPORT9 viewport;+ if (device->GetTransform(D3DTS_VIEW, &view) != D3D_OK+ || device->GetTransform(D3DTS_PROJECTION, &projection) != D3D_OK+ || device->GetViewport(&viewport) != D3D_OK || !viewport.Width || !viewport.Height) {+ fail("could not read the scene camera");+ return false;+ }+ SdlHazardCloudUniforms uniforms = {};+ float viewProjection[16], inverseView[16];+ multiply(&view._11, &projection._11, viewProjection);+ if (!render_inverse(viewProjection, uniforms.WorldFromClip)+ || !render_inverse(&view._11, inverseView)) {+ fail("scene camera has a singular transform");+ return false;+ }+ const float depthRange = viewport.MaxZ - viewport.MinZ;+ if (depthRange <= 1.0e-8f) {+ fail("scene camera has an empty depth range");+ return false;+ }+ for (unsigned column = 0; column < 4; ++column) {+ const float row = uniforms.WorldFromClip[8 + column] / depthRange;+ uniforms.WorldFromClip[12 + column] -= viewport.MinZ * row;+ uniforms.WorldFromClip[8 + column] = row;+ }+ for (unsigned i = 0; i < 3; ++i) uniforms.CameraPosition[i] = inverseView[12 + i];+ uniforms.CameraPosition[3] = 1;+ uniforms.Viewport[0] = static_cast<float>(viewport.X) + 0.5f;+ uniforms.Viewport[1] = static_cast<float>(viewport.Y) + 0.5f;+ uniforms.Viewport[2] = static_cast<float>(viewport.Width);+ uniforms.Viewport[3] = static_cast<float>(viewport.Height);+ uniforms.Scene[0] = 1.0f / target.Width;+ uniforms.Scene[1] = 1.0f / target.Height;+ uniforms.Scene[2] = 1;+ uniforms.Scene[3] = simulationTime;+ float *fields[] = { uniforms.Field0, uniforms.Field1 };+ float *shapes[] = { uniforms.Shape0, uniforms.Shape1 };+ float *sources[] = { uniforms.Source0, uniforms.Source1 };+ bool hotField = false;+ for (unsigned i = 0; i < fieldCount; ++i) {+ const FieldState &field = fieldStates[i];+ hotField = hotField || (field.palette >= 0.5f && field.palette < 1.5f+ && field.radius > 0.001f && field.height > 0.002f && field.density > 0.00001f);+ fields[i][0] = field.ground.x;+ fields[i][1] = field.ground.y;+ fields[i][2] = field.ground.z + field.height * 0.5f;+ fields[i][3] = field.radius;+ shapes[i][0] = field.height * 0.5f;+ shapes[i][1] = field.density;+ shapes[i][2] = field.palette;+ shapes[i][3] = field.formation;+ uniforms.Footprints[i] = field.fringe;+ sources[i][0] = field.release;+ sources[i][1] = sourceTravel[i];+ sources[i][2] = peakDensity[i] > 0.0001f+ ? std::max(0.0f, 1.0f - field.density / peakDensity[i]) : 0.0f;+ sources[i][3] = sourceAge[i];+ }+ float *terrain[] = { uniforms.Terrain0, uniforms.Terrain1 };+ for (unsigned i = 0; i < 2; ++i) {+ terrain[i][0] = terrainMin[i];+ terrain[i][1] = terrainMax[i];+ terrain[i][2] = terrainEnabled[i] ? 1.0f : 0.0f;+ }+ uniforms.Settings[0] = static_cast<float>(fieldCount);+ // Keep palette values in the cache key: live edits must refresh lighting+ // even while the source, infantry and simulation clock are paused.+ for (unsigned i = 0; i < 4; ++i) {+ const auto &palette = palettes[i];+ uniforms.PaletteMain[i][0] = palette.main.r;+ uniforms.PaletteMain[i][1] = palette.main.g;+ uniforms.PaletteMain[i][2] = palette.main.b;+ uniforms.PaletteMain[i][3] = palette.brightness;+ uniforms.PaletteShadow[i][0] = palette.shadow.r;+ uniforms.PaletteShadow[i][1] = palette.shadow.g;+ uniforms.PaletteShadow[i][2] = palette.shadow.b;+ uniforms.PaletteShadow[i][3] = 1.0f - palette.transparency;+ }+ // Visible hot-air refraction only for the warm nuclear palette.+ // This is a preview material control; it never changes a gameplay hazard.+ uniforms.Settings[1] = heatEnabled && hotField ? 10.0f : 0.0f;+ uniforms.Settings[2] = 1;+ uniforms.Settings[3] = Steps;+ uniforms.Interaction[0] = flow.domainMinX();+ uniforms.Interaction[1] = flow.domainMinY();+ uniforms.Interaction[2] = 1.0f / (flow.domainMaxX() - flow.domainMinX());+ uniforms.Interaction[3] = 1.0f / (flow.domainMaxY() - flow.domainMinY());+ uniforms.FlowSettings[0] = interactionEnabled ? 1.0f : 0.0f;+ uniforms.FlowSettings[1] = MaximumDisplacement;++ // Complete all potentially failing material allocations before recording+ // a visible scene draw. The adapter can safely fall back to classic clouds.+ if (uniforms.Settings[1] > 0 && !prepareHeatBackground(target)) return false;+ if (!SdlHazardCloudEmbers::prepare(frame, target, fieldStates, fieldCount)) {+ fail("could not prepare nuclear embers");+ return false;+ }+ uint32_t vertexOffset = 0;+ std::memset(frame->Stage(16, vertexOffset), 0, 16);+ if (!prepareCaches(uniforms, sceneDepth, vertexOffset, target)) return false;+ SdlRecordedDraw draw = {};+ draw.Pipeline = shared.volumePipeline;+ // The common batch binds a vertex buffer even for SV_VertexID shaders.+ // Supply a valid unused allocation; the fullscreen triangle needs no mesh.+ draw.VertexOffset = vertexOffset;+ draw.Count = 3;+ draw.PixelConstants = frame->Constants(1, &uniforms, sizeof(uniforms));+ draw.PixelConstantsSize = sizeof(uniforms);+ draw.SamplerCount = 5;+ bindTerrain(draw);+ draw.Textures[0] = sceneDepth;+ draw.Samplers[0] = shared.depthSampler;+ draw.Textures[1] = flowTexture;+ draw.Samplers[1] = shared.flowSampler;+ // Slot 2 is only sampled by the composite. It must not alias the low target+ // while this pass writes that target, even though the low shader ignores it.+ draw.Textures[2] = flowTexture;+ draw.Samplers[2] = shared.flowSampler;+ bindCachedTextures(draw, false);+ draw.Viewport[2] = static_cast<float>(shared.lowTarget.Width);+ draw.Viewport[3] = static_cast<float>(shared.lowTarget.Height);+ draw.Viewport[5] = 1;+ draw.Scissor[2] = static_cast<int32_t>(shared.lowTarget.Width);+ draw.Scissor[3] = static_cast<int32_t>(shared.lowTarget.Height);+ frame->Set_Target(shared.lowTarget);+ frame->Clear_Back_Buffer(true, false, false, 0, 1.0f, 0);+ frame->Record_Draw(draw);++ // Target changes close the low-resolution pass before the composite samples+ // it. Both draws keep the original camera/depth uniforms; only the low pass's+ // raster viewport changes. No extra submission or GPU wait is necessary.+ draw.Pipeline = shared.compositePipeline;+ draw.SamplerCount = 5;+ bindTerrain(draw);+ draw.Textures[2] = shared.lowTarget.Colour;+ draw.Samplers[2] = shared.depthSampler;+ std::copy(uniforms.Viewport, uniforms.Viewport + 4, draw.Viewport);+ draw.Viewport[4] = viewport.MinZ;+ draw.Viewport[5] = viewport.MaxZ;+ draw.Scissor[0] = static_cast<int32_t>(viewport.X);+ draw.Scissor[1] = static_cast<int32_t>(viewport.Y);+ draw.Scissor[2] = std::min(viewport.Width, target.Width - std::min(viewport.X, target.Width));+ draw.Scissor[3] = std::min(viewport.Height, target.Height - std::min(viewport.Y, target.Height));+ frame->Set_Target(target);+ frame->Record_Draw(draw);+ SdlHazardCloudEmbers::render(frame, target, sceneDepth, viewProjection, draw.Viewport,+ fieldStates, fieldCount, simulationTime, terrainTexture, terrainEnabled);+ if (uniforms.Settings[1] > 0) {+ SdlRecordedDraw heatDraw = draw;+ heatScissor(viewProjection, viewport, target, heatDraw.Scissor);+ if (heatDraw.Scissor[2] > 0 && heatDraw.Scissor[3] > 0) {+ // Include the smoke and embers in the refraction. Warping only the+ // background makes heat disappear under a dense cloud's opacity.+ captureHeatBackground(target);+ heatDraw.Pipeline = shared.heatPipeline;+ heatDraw.SamplerCount = 7;+ heatDraw.Textures[5] = shared.heatBackground.Colour;+ heatDraw.Samplers[5] = shared.cacheSampler;+ frame->Record_Draw(heatDraw);+ }+ }+ flowUsedBatch = frame->Batch();+ // Recorded state is private to this draw. The next engine draw rebinds its+ // own pipeline, samplers and uniforms without any D3D9 state restoration.+ if (++renderedFrames == 1)+ std::fprintf(stderr, "cloud-preview: volumetric draw active; world-space density, "+ "scene-depth clipping, half-resolution %ux%u with depth-aware composite, %.0f ray steps\n",+ shared.lowTarget.Width, shared.lowTarget.Height, Steps);+ return true;+}+void setFields(const FieldState *values, unsigned count)+{+ if (count > 2 || (count && !values)) {+ fail("invalid cloud lifecycle field list");+ return;+ }+ for (unsigned i = 0; i < count; ++i) {+ const FieldState &field = values[i];+ if (!std::isfinite(field.ground.x) || !std::isfinite(field.ground.y)+ || !std::isfinite(field.ground.z) || !std::isfinite(field.radius)+ || !std::isfinite(field.height) || !std::isfinite(field.density)+ || !std::isfinite(field.palette) || !std::isfinite(field.formation)+ || !std::isfinite(field.release) || !std::isfinite(field.fringe)+ || field.fringe < 0 || field.radius < 0 || field.height < 0+ || field.density < 0 || field.palette < 0 || field.palette > 3+ || field.formation < 0 || field.formation > 1 || field.release < 0 || field.release > 1) {+ fail("invalid cloud lifecycle field state");+ return;+ }+ }+ if (!explicitDomain && count) {+ float minX = values[0].ground.x, maxX = minX;+ float minY = values[0].ground.y, maxY = minY;+ for (unsigned i = 0; i < count; ++i) {+ const float radius = std::max(1.0f, values[i].radius + values[i].fringe + MaximumDisplacement);+ minX = std::min(minX, values[i].ground.x - radius);+ maxX = std::max(maxX, values[i].ground.x + radius);+ minY = std::min(minY, values[i].ground.y - radius);+ maxY = std::max(maxY, values[i].ground.y + radius);+ }+ if (flow.domainMinX() != minX || flow.domainMaxX() != maxX+ || flow.domainMinY() != minY || flow.domainMaxY() != maxY) {+ flow.setDomain(minX, minY, maxX, maxY);+ flowDirty = true;+ }+ }+ fieldCount = count;+ for (unsigned i = 0; i < count; ++i) {+ fieldStates[i] = values[i];+ peakDensity[i] = std::max(peakDensity[i], values[i].density);+ }+}++void reset()+{+ flow.reset();+ flowDirty = true;+ for (unsigned i = 0; i < 2; ++i) {+ sourceTravel[i] = sourceAge[i] = peakDensity[i] = 0;+ }+}++void setBodies(const Body *values, unsigned count)+{+ if (count > MaximumBodies || (count && !values)) {+ fail("invalid infantry interaction body list");+ return;+ }+ for (unsigned i = 0; i < count; ++i) {+ const Body &body = values[i];+ if (!std::isfinite(body.x) || !std::isfinite(body.y) || !std::isfinite(body.z)+ || !std::isfinite(body.vx) || !std::isfinite(body.vy)+ || !std::isfinite(body.radius) || !std::isfinite(body.height)+ || body.radius <= 0 || body.height <= 0) {+ fail("invalid infantry interaction body");+ return;+ }+ }+ if (count) bodies.assign(values, values + count);+ else bodies.clear();+}++void setInteractionEnabled(bool value)+{+ if (interactionEnabled == value) return;+ interactionEnabled = value;+ flow.reset();+ flowDirty = true;+}+++void setHeatEnabled(bool value) { heatEnabled = value; }++void update(float timeSeconds)+{+ if (!std::isfinite(timeSeconds) || timeSeconds < 0) {+ fail("invalid simulation time");+ return;+ }+ const float elapsed = hasSimulationTime ? timeSeconds - simulationTime : 0.0f;+ simulationTime = timeSeconds;+ hasSimulationTime = true;+ if (elapsed < 0) {+ reset();+ } else if (elapsed > 0 && !failed) {+ for (unsigned i = 0; i < fieldCount; ++i) {+ sourceAge[i] += elapsed;+ sourceTravel[i] += elapsed * fieldStates[i].release * 22.0f;+ }+ // Appearance only controls drawing. Keep the same wake history while+ // the original effects are shown, so toggling back is an in-place A/B.+ if (interactionEnabled) {+ flow.step(elapsed, bodies.empty() ? nullptr : bodies.data(),+ static_cast<unsigned>(bodies.size()));+ if (!flow.valid()) fail("interaction simulation produced invalid state");+ flowDirty = true;+ }+ }+}++++bool initialize()+{+ if (initialized) return !failed;+ failed = false;+ PosixDevice9 *device = static_cast<PosixDevice9 *>(DX8Wrapper::_Get_D3D_Device());+ if (!device || !(frame = device->Get_Gpu()) || !(gpu = frame->Device())) {+ fail("an SDL graphics device is required");+ return false;+ }+ if (shared.users && (shared.frame != frame || shared.gpu != gpu)) {+ fail("existing cloud layers belong to a different graphics device");+ frame = nullptr;+ gpu = nullptr;+ return false;+ }+ if (!shared.users) {+ shared.frame = frame;+ shared.gpu = gpu;+ if (!makeResources()) {+ releaseShared(true);+ frame = nullptr;+ gpu = nullptr;+ return false;+ }+ }+ ++shared.users;+ initialized = true;+ if (!makeFlowTexture()) { shutdown(); return false; }+ if (!explicitDomain && !fieldCount) flow.setDomain(-400, -220, 400, 220);+ flowDirty = true;+ return true;+}++void shutdown()+{+ if (!initialized) return;+ PosixDevice9 *device = static_cast<PosixDevice9 *>(DX8Wrapper::_Get_D3D_Device());+ const bool alive = device && device->Get_Gpu() == frame;+ if (alive) {+ for (FieldCache &cache : fieldCaches) retireCache(cache);+ if (flowTexture) frame->Release_After_Batch(flowTexture, nullptr);+ if (terrainTexture) frame->Release_After_Batch(terrainTexture, nullptr);+ }+ for (FieldCache &cache : fieldCaches) cache = {};+ flowTexture = terrainTexture = nullptr;+ terrainDirty = terrainEnabled[0] || terrainEnabled[1];+ initialized = false;+ if (shared.users) --shared.users;+ if (!shared.users) releaseShared(alive);+ std::fprintf(stderr, "cloud-preview: volume-cache rebuilds=%u field-bakes=%u rendered-frames=%u\n",+ cacheUpdates, cacheBakes, renderedFrames);+ frame = nullptr;+ gpu = nullptr;+ cachedInputsValid = false;+ cachedInputs = {};+ cachedFlowUploads = cacheUpdates = cacheBakes = 0;+ renderedFrames = flowUploads = 0;+ flowUsedBatch = ~uint64_t(0);+ flowDirty = true;+ hasSimulationTime = false;+ bodies.clear();+ reset();+}+};++Layer::Layer() : impl(new Impl) {}+Layer::~Layer() { shutdown(); delete impl; }+bool Layer::initialize() { return impl->initialize(); }+void Layer::setFields(const FieldState *fields, unsigned count) { impl->setFields(fields, count); }+void Layer::setBodies(const Body *bodies, unsigned count) { impl->setBodies(bodies, count); }+void Layer::setFlowDomain(float minX, float minY, float maxX, float maxY)+{+ impl->flow.setDomain(minX, minY, maxX, maxY);+ impl->explicitDomain = true;+ impl->flowDirty = true;+ if (!impl->flow.valid()) impl->fail("invalid interaction simulation domain");+}+void Layer::setTerrain(unsigned index, const float *heights)+{+ if (index >= 2) { impl->fail("invalid terrain field index"); return; }+ if (!heights) {+ impl->terrainEnabled[index] = false;+ impl->terrainMin[index] = impl->terrainMax[index] = 0;+ return;+ }+ float minimum = heights[0], maximum = heights[0];+ for (unsigned i = 0; i < TerrainGridSide * TerrainGridSide; ++i) {+ if (!std::isfinite(heights[i]) || std::abs(heights[i]) > 100000.0f) {+ impl->fail("invalid terrain height");+ return;+ }+ minimum = std::min(minimum, heights[i]);+ maximum = std::max(maximum, heights[i]);+ }+ bool changed = !impl->terrainEnabled[index];+ for (unsigned y = 0; y < TerrainGridSide; ++y) {+ float *destination = impl->terrainPixels.data() + y * TerrainGridSide * 2 + index * TerrainGridSide;+ const float *source = heights + y * TerrainGridSide;+ changed = changed || std::memcmp(destination, source, TerrainGridSide * sizeof(float)) != 0;+ std::copy(source, source + TerrainGridSide, destination);+ }+ impl->terrainEnabled[index] = true;+ impl->terrainMin[index] = minimum;+ impl->terrainMax[index] = maximum;+ impl->terrainDirty = impl->terrainDirty || changed;+}+void Layer::setPalette(unsigned index, const Palette &palette)+{+ const float values[] = { palette.main.r, palette.main.g, palette.main.b,+ palette.shadow.r, palette.shadow.g, palette.shadow.b, palette.brightness, palette.transparency };+ if (index >= 4) { impl->fail("invalid palette index"); return; }+ for (unsigned i = 0; i < 8; ++i)+ if (!std::isfinite(values[i]) || values[i] < 0 || values[i] > (i == 6 ? 2 : 1)) {+ impl->fail("invalid palette value");+ return;+ }+ impl->palettes[index] = palette;+}+void Layer::setInteractionEnabled(bool value) { impl->setInteractionEnabled(value); }+bool Layer::isInteractionEnabled() const { return impl->interactionEnabled; }+void Layer::setHeatEnabled(bool value) { impl->setHeatEnabled(value); }+bool Layer::isHeatEnabled() const { return impl->heatEnabled; }+void Layer::update(float seconds) { impl->update(seconds); }+void Layer::reset() { impl->reset(); }+bool Layer::render() { return impl->renderVolume(); }+bool Layer::valid() const { return impl->initialized && !impl->failed && impl->flow.valid(); }+unsigned Layer::activeBodies() const { return impl->flow.activeBodies(); }+float Layer::maxDisturbance() const { return impl->flow.maxDisturbance(); }+unsigned Layer::interactionUploads() const { return impl->flowUploads; }+unsigned Layer::renderedFrames() const { return impl->renderedFrames; }+std::uint64_t Layer::estimateCacheBytes(const FieldState *fields, unsigned count)+{+ if (count > 2 || (count && !fields)) return std::numeric_limits<std::uint64_t>::max();+ std::uint64_t result = (192u * 96u * 4u + TerrainGridSide * TerrainGridSide * 2u) * sizeof(float);+ for (unsigned i = 0; i < count; ++i) {+ if (!std::isfinite(fields[i].radius) || !std::isfinite(fields[i].fringe)+ || fields[i].radius < 0 || fields[i].fringe < 0)+ return std::numeric_limits<std::uint64_t>::max();+ if (fields[i].radius <= 0.001f || fields[i].height <= 0.002f || fields[i].density <= 0.00001f) continue;+ const std::uint64_t side = cacheSide(fields[i]);+ result += side * side * CacheSlices * 10u; // R16F density + RGBA16F light.+ }+ return result;+}+std::uint64_t Layer::estimatedCacheBytes() const+{+ std::uint64_t result = impl->flowTexture ? 192u * 96u * 4u * sizeof(float) : 0;+ if (impl->terrainTexture) result += TerrainGridSide * TerrainGridSide * 2u * sizeof(float);+ for (const FieldCache &cache : impl->fieldCaches)+ result += std::uint64_t(cache.side) * cache.side * CacheSlices * 10u;+ return result;+}+void Layer::shutdown() { impl->shutdown(); }++} // namespace SdlHazardClouddiff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudEmbers.cpp b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudEmbers.cppnew file mode 100644index 000000000..58d1e3152--- /dev/null+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudEmbers.cpp@@ -0,0 +1,336 @@+// Sparse nuclear embers. No assets, gameplay particles or damage are involved.+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.+#include "PreRTS.h"+#include "SdlHazardCloudEmbers.h"+#include "Platform/SdlHazardCloud.h"+#include "WW3D2/sdl3shadercompile.h"+#include "SdlGpuFrame.h"++#include <SDL3/SDL.h>+#include <algorithm>+#include <cmath>+#include <cstdio>+#include <cstring>+#include <string>+#include <vector>++namespace SdlHazardCloudEmbers {+namespace {++constexpr unsigned MinimumEmbers = 24;+constexpr unsigned MaximumEmbers = 96;+constexpr float ReferenceEmberRadius = 250.0f;+SDL_GPUDevice *gpu = nullptr;+SDL_GPUShader *vertexShader = nullptr;+SDL_GPUShader *pixelShader = nullptr;+SDL_GPUGraphicsPipeline *pipeline = nullptr;+SDL_GPUSampler *depthSampler = nullptr;+bool failed = false;+unsigned renderedFrames = 0;++struct VertexConstants {+ float viewProjection[16];+ float viewport[4];+ float field[4];+ float shape[4];+ float scene[4];+ float terrain[4]; // enabled, field index, sampled domain radius, reserved+};+static_assert(sizeof(VertexConstants) == 144, "ember shader constant layout");++bool fail(const char *reason)+{+ if (!failed) std::fprintf(stderr, "hazard-cloud: nuclear embers FAIL: %s\n", reason);+ failed = true;+ return false;+}++const char *vertexSource = R"HLSL(+Texture2D<float> TerrainHeight : register(t0, space0);+SamplerState TerrainSampler : register(s0, space0);+cbuffer EmberConstants : register(b0, space1)+{+ row_major float4x4 ViewProjection;+ float4 Viewport;+ float4 Field;+ float4 Shape;+ float4 Scene;+ float4 Terrain;+};+struct EmberVertex {+ float4 position : SV_Position;+ float2 local : TEXCOORD0;+ float2 glow : TEXCOORD1;+};+float emberHash(float seed)+{+ float3 p = frac(float3(seed, seed + 1.0, seed + 2.0) * 0.1031);+ p += dot(p, p.yzx + 33.33);+ return frac((p.x + p.y) * p.z);+}+float emberGround(float2 world)+{+ if (Terrain.x < 0.5) return Field.z;+ 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);+ 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 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),+ TerrainHeight.SampleLevel(TerrainSampler, b, 0), weight.x);+ return lerp(low, high, weight.y);+}+EmberVertex main(uint vertex : SV_VertexID)+{+ uint particle = vertex / 6;+ uint corner = vertex % 6;+ float2 local;+ if (corner == 0 || corner == 3) local = float2(-1, -1);+ else if (corner == 1) local = float2(1, -1);+ else if (corner == 2 || corner == 4) local = float2(1, 1);+ else local = float2(-1, 1);++ float seed = float(particle) * 13.61 + Field.x * 0.21 + Field.y * 0.37;+ float random = emberHash(seed + 7.0);+ float lifetime = 3.4 + emberHash(seed + 2.0) * 2.8;+ float age = frac(Scene.x / lifetime + emberHash(seed + 19.0));+ // One anchor per equal-area radial stratum, separated by the golden angle.+ // Slight jitter breaks the spiral's regularity without random clustering.+ // Field.w includes the cloud's visual fringe. Its whole footprint ignites+ // together; formation controls opacity rather than moving sparks outward.+ float rotation = emberHash(Field.x * 0.21 + Field.y * 0.37 + 3.0) * 6.2831853;+ float angle = float(particle) * 2.39996323 + rotation+ + (emberHash(seed + 11.0) - 0.5) * 0.12;+ float stratum = (float(particle) + 0.35 + emberHash(seed + 1.0) * 0.30) / max(Scene.y, 1.0);+ float radius = sqrt(stratum) * Field.w;+ float2 origin = Field.xy + float2(cos(angle), sin(angle)) * radius;+ float2 drift = float2(sin(age * 5.0 + seed), cos(age * 4.0 + seed * 0.7));+ drift *= (2.0 + random * 5.0) * age;+ drift += float2(3.0, -1.0) * age * age;+ float height = Shape.x * (0.36 + age * (1.8 + random * 0.6));+ float3 world = float3(origin + drift, emberGround(origin + drift) + height);+ float4 clip = mul(float4(world, 1), ViewProjection);+ float4 upClip = mul(float4(world + float3(0, 0, 1), 1), ViewProjection);+ float2 up = (upClip.xy / max(upClip.w, 0.0001) - clip.xy / max(clip.w, 0.0001))+ * Viewport.zw * float2(0.5, -0.5);+ up = dot(up, up) > 0.00001 ? normalize(up) : float2(0, -1);+ float2 across = float2(-up.y, up.x);+ // The bright core is roughly 1-2 pixels across at the default view, with+ // a softer orange halo and a short tail pointing down its rising path.+ float zoom = clamp(sqrt(max(Viewport.z * Viewport.w, 1.0) / 1024000.0), 0.8, 1.7);+ float2 extent = float2(2.3 + random * 1.1, 3.0 + random * 2.5) * zoom;+ float2 pixelOffset = across * local.x * extent.x + up * local.y * extent.y;+ clip.xy += pixelOffset * float2(2, -2) / max(Viewport.zw, float2(1, 1)) * clip.w;+ float fade = smoothstep(0.0, 0.14, age) * (1.0 - smoothstep(0.58, 1.0, age));+ fade *= saturate(Shape.y * 1.6) * smoothstep(0.02, 0.28, Shape.z);+ fade *= lerp(0.58, 1.0, random) * lerp(0.55, 1.0, smoothstep(0.5, 1.1, height / Shape.x));+ // Keep the outer annulus legible. Only the last few percent of outward+ // drift die away, so the soft cloud fringe does not become a hard spark ring.+ float edgeRadius = length(world.xy - Field.xy) / max(Field.w, 0.001);+ fade *= (1.0 - 0.40 * smoothstep(0.88, 1.0, edgeRadius))+ * (1.0 - smoothstep(1.0, 1.055, edgeRadius));+ EmberVertex output;+ output.position = clip;+ output.local = local;+ output.glow = float2(fade, random);+ return output;+}+)HLSL";++const char *pixelSource = R"HLSL(+Texture2D<float> SceneDepth : register(t0, space2);+SamplerState DepthSampler : register(s0, space2);+cbuffer EmberPixelConstants : register(b0, space3) { float4 Scene; };+struct EmberVertex {+ float4 position : SV_Position;+ float2 local : TEXCOORD0;+ float2 glow : TEXCOORD1;+};+float4 main(EmberVertex input) : SV_Target+{+ float depth = SceneDepth.SampleLevel(DepthSampler, input.position.xy * Scene.xy, 0);+ // Use the same captured opaque depth as the volume: terrain and infantry+ // hide sparks behind them, while this pass never writes the scene depth.+ clip(depth - input.position.z + 0.0000005);+ float2 corePoint = (input.local - float2(0, 0.30)) * float2(1, 1.6);+ float squared = dot(corePoint, corePoint);+ float core = exp2(-squared * 12.0);+ float halo = exp2(-squared * 3.0);+ float tail = (1.0 - smoothstep(0.10, 0.34, abs(input.local.x)))+ * smoothstep(-1.0, -0.30, input.local.y)+ * (1.0 - smoothstep(-0.18, 0.30, input.local.y));+ float edge = (1.0 - smoothstep(0.80, 1.0, abs(input.local.x)))+ * (1.0 - smoothstep(0.85, 1.0, abs(input.local.y)));+ float3 warm = lerp(float3(1.0, 0.21, 0.025), float3(1.0, 0.43, 0.08), input.glow.y);+ float3 light = float3(1.0, 0.80, 0.43) * core * 0.95 + warm * (halo * 0.30 + tail * 0.17);+ return float4(light * input.glow.x * edge, 0);+}+)HLSL";++bool makeResources(SdlGpuFrame *frame, const SdlTarget &target)+{+ gpu = frame->Device();+ std::vector<unsigned char> spirv;+ std::string log;+ if (!SDL3_Compile_HLSL_To_SPIRV(vertexSource, true, spirv, log)+ || !(vertexShader = SDL3_Create_Shader(gpu, spirv, true, log)))+ return fail(("vertex shader: " + log).c_str());+ if (!SDL3_Compile_HLSL_To_SPIRV(pixelSource, false, spirv, log)+ || !(pixelShader = SDL3_Create_Shader(gpu, spirv, false, log)))+ return fail(("pixel shader: " + log).c_str());+ SDL_GPUColorTargetDescription colour = {};+ colour.format = static_cast<SDL_GPUTextureFormat>(SdlGpuFrame::Target_Format());+ colour.blend_state.enable_blend = true;+ colour.blend_state.src_color_blendfactor = SDL_GPU_BLENDFACTOR_ONE;+ colour.blend_state.dst_color_blendfactor = SDL_GPU_BLENDFACTOR_ONE;+ colour.blend_state.color_blend_op = SDL_GPU_BLENDOP_ADD;+ colour.blend_state.src_alpha_blendfactor = SDL_GPU_BLENDFACTOR_ZERO;+ colour.blend_state.dst_alpha_blendfactor = SDL_GPU_BLENDFACTOR_ONE;+ colour.blend_state.alpha_blend_op = SDL_GPU_BLENDOP_ADD;+ SDL_GPUGraphicsPipelineCreateInfo description = {};+ description.vertex_shader = vertexShader;+ description.fragment_shader = pixelShader;+ 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.depth_stencil_state.enable_depth_test = false;+ description.depth_stencil_state.enable_depth_write = false;+ description.target_info.color_target_descriptions = &colour;+ description.target_info.num_color_targets = 1;+ description.target_info.has_depth_stencil_target = true;+ // Clouds render only into the main scene. Its implicit and mirrored depth+ // surfaces use the frame's scene format, independently of shadow targets.+ description.target_info.depth_stencil_format = static_cast<SDL_GPUTextureFormat>(frame->Depth_Format());+ pipeline = SDL_CreateGPUGraphicsPipeline(gpu, &description);+ if (!pipeline) return fail(SDL_GetError());+ 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;+ depthSampler = SDL_CreateGPUSampler(gpu, &sampler);+ if (!depthSampler) return fail(SDL_GetError());+ std::fprintf(stderr, "hazard-cloud: nuclear embers initialized (24-96 GPU billboards over the full nuclear footprint)\n");+ return true;+}++} // namespace++bool prepare(SdlGpuFrame *frame, const SdlTarget &target,+ const SdlHazardCloud::FieldState *fields, unsigned fieldCount)+{+ if (failed || !frame || !frame->Device() || !target.Colour || !target.Depth+ || fieldCount > 2 || (fieldCount && !fields)) return false;+ for (unsigned i = 0; i < fieldCount; ++i) {+ const auto &field = fields[i];+ if (field.palette < 0.5f || field.palette >= 1.5f || field.density <= 0.00001f+ || field.radius <= 0.001f || field.height <= 0.002f || field.formation <= 0.02f) continue;+ if (!pipeline && !makeResources(frame, target)) return false;+ if (gpu != frame->Device()) return fail("the graphics device was replaced");+ }+ return true;+}++bool render(SdlGpuFrame *frame, const SdlTarget &target, SDL_GPUTexture *sceneDepth,+ const float viewProjection[16], const float viewport[6],+ const SdlHazardCloud::FieldState *fields, unsigned fieldCount,+ float timeSeconds, SDL_GPUTexture *terrainTexture, const bool *terrainEnabled)+{+ 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");+ bool active = false;+ for (unsigned i = 0; i < fieldCount; ++i) {+ const auto &field = fields[i];+ if (field.palette < 0.5f || field.palette >= 1.5f || field.density <= 0.00001f+ || field.radius <= 0.001f || field.height <= 0.002f || field.formation <= 0.02f) continue;+ if (!pipeline && !makeResources(frame, target)) return false;+ if (gpu != frame->Device()) return fail("the preview graphics device was replaced");+ const float footprintRadius = field.radius + field.fringe;+ const float areaRatio = footprintRadius * footprintRadius+ / (ReferenceEmberRadius * ReferenceEmberRadius);+ // Match particle density to visible area: 64 at the comparison size,+ // fewer for cannon residue and at most 96 for the large missile field.+ const unsigned emberCount = static_cast<unsigned>(std::clamp(+ std::round(64.0f * areaRatio / 8.0f) * 8.0f,+ static_cast<float>(MinimumEmbers), static_cast<float>(MaximumEmbers)));+ VertexConstants constants = {};+ std::copy(viewProjection, viewProjection + 16, constants.viewProjection);+ std::copy(viewport, viewport + 4, constants.viewport);+ constants.field[0] = field.ground.x;+ constants.field[1] = field.ground.y;+ constants.field[2] = field.ground.z;+ constants.field[3] = footprintRadius;+ constants.shape[0] = field.height;+ constants.shape[1] = field.density;+ constants.shape[2] = field.formation;+ constants.scene[0] = timeSeconds;+ constants.scene[1] = static_cast<float>(emberCount);+ constants.terrain[0] = terrainTexture && terrainEnabled && terrainEnabled[i] ? 1.0f : 0.0f;+ constants.terrain[1] = static_cast<float>(i);+ constants.terrain[2] = footprintRadius + 18.0f;+ const float pixelConstants[4] = { 1.0f / target.Width, 1.0f / target.Height, 0, 0 };+ SdlRecordedDraw draw = {};+ draw.Pipeline = pipeline;+ // SV_VertexID creates each billboard; the common batch still binds a+ // valid staging buffer even though this pipeline has no vertex inputs.+ std::memset(frame->Stage(16, draw.VertexOffset), 0, 16);+ draw.Count = emberCount * 6;+ draw.VertexConstants = frame->Constants(0, &constants, sizeof(constants));+ draw.VertexConstantsSize = sizeof(constants);+ draw.PixelConstants = frame->Constants(1, pixelConstants, sizeof(pixelConstants));+ draw.PixelConstantsSize = sizeof(pixelConstants);+ draw.VertexSamplerCount = 1;+ draw.VertexTextures[0] = terrainTexture ? terrainTexture : sceneDepth;+ draw.VertexSamplers[0] = depthSampler;+ draw.SamplerCount = 1;+ draw.Textures[0] = sceneDepth;+ draw.Samplers[0] = depthSampler;+ std::copy(viewport, viewport + 6, draw.Viewport);+ draw.Scissor[0] = static_cast<int32_t>(std::clamp(viewport[0], 0.0f, static_cast<float>(target.Width)));+ draw.Scissor[1] = static_cast<int32_t>(std::clamp(viewport[1], 0.0f, static_cast<float>(target.Height)));+ draw.Scissor[2] = static_cast<int32_t>(std::min(viewport[2], static_cast<float>(target.Width - draw.Scissor[0])));+ draw.Scissor[3] = static_cast<int32_t>(std::min(viewport[3], static_cast<float>(target.Height - draw.Scissor[1])));+ frame->Set_Target(target);+ frame->Record_Draw(draw);+ active = true;+ }+ if (active) ++renderedFrames;+ return true;+}++bool validationPassed() { return !failed; }++void shutdown()+{+ if (gpu) {+ if (pipeline) SDL_ReleaseGPUGraphicsPipeline(gpu, pipeline);+ if (depthSampler) SDL_ReleaseGPUSampler(gpu, depthSampler);+ if (vertexShader) SDL_ReleaseGPUShader(gpu, vertexShader);+ if (pixelShader) SDL_ReleaseGPUShader(gpu, pixelShader);+ }+ if (renderedFrames) std::fprintf(stderr, "hazard-cloud: nuclear embers rendered-frames=%u status=%s\n",+ renderedFrames, failed ? "FAIL" : "OK");+ abandon();+}++void abandon()+{+ gpu = nullptr;+ vertexShader = pixelShader = nullptr;+ pipeline = nullptr;+ depthSampler = nullptr;+ renderedFrames = 0;+ failed = false;+}++} // namespace SdlHazardCloudEmbersdiff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudEmbers.h b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudEmbers.hnew file mode 100644index 000000000..d3e001be0--- /dev/null+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudEmbers.h@@ -0,0 +1,30 @@+// Small, procedural burning particles for the isolated cloud preview only.+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.+#pragma once++class SdlGpuFrame;+struct SdlTarget;+struct SDL_GPUTexture;+namespace SdlHazardCloud { struct FieldState; }++namespace SdlHazardCloudEmbers {++// 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.+bool prepare(SdlGpuFrame *frame, const SdlTarget &target,+ const SdlHazardCloud::FieldState *fields, unsigned fieldCount);++bool render(SdlGpuFrame *frame, const SdlTarget &target, SDL_GPUTexture *sceneDepth,+ const float viewProjection[16], const float viewport[6],+ const SdlHazardCloud::FieldState *fields, unsigned fieldCount,+ float timeSeconds, SDL_GPUTexture *terrainTexture = nullptr,+ const bool *terrainEnabled = nullptr);+bool validationPassed();+// Call after flushing and waiting for the GPU, before destroying its device.+void shutdown();+// Forget handles only when their owning device was already destroyed.+void abandon();++}diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudFlow.cpp b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudFlow.cppnew file mode 100644index 000000000..ee8dba55f--- /dev/null+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudFlow.cpp@@ -0,0 +1,295 @@+// Persistent planar smoke transport shared by SDL hazard clouds and their preview.+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.+#include "Platform/SdlHazardCloudFlow.h"++#include <algorithm>+#include <array>+#include <cmath>++namespace SdlHazardCloudFlow {+namespace {++constexpr unsigned GridWidth = 192;+constexpr unsigned GridHeight = 96;+constexpr unsigned CellCount = GridWidth * GridHeight;+constexpr unsigned MaxBodies = 32;+constexpr float FixedStep = 1.0f / 60.0f;+constexpr float MaxDisplacement = 18.0f;+constexpr float MaxVelocity = 60.0f;+constexpr float MaxInfantrySpeed = 120.0f;+// Keep transported billows visible at the preview's normal tactical zoom.+constexpr float BodyFlowStrength = 2.2f;++struct Cell {+ float vx, vy;+ float dx, dy;+};++float clamp(float value, float lo, float hi)+{+ return std::max(lo, std::min(hi, value));+}++void limitVector(float &x, float &y, float limit)+{+ float squared = x * x + y * y;+ if (squared > limit * limit) {+ float scale = limit / std::sqrt(squared);+ x *= scale;+ y *= scale;+ }+}++Cell mix(const Cell &a, const Cell &b, float weight)+{+ return {+ a.vx + (b.vx - a.vx) * weight,+ a.vy + (b.vy - a.vy) * weight,+ a.dx + (b.dx - a.dx) * weight,+ a.dy + (b.dy - a.dy) * weight+ };+}++} // namespace++struct Flow::Impl {+ std::array<Cell, CellCount> cells = {};+ std::array<Cell, CellCount> transported = {};+ std::array<float, CellCount * 4> pixels = {};+ float minX = 0, minY = 0, maxX = 1, maxY = 1;+ float cellWidth = 1.0f / GridWidth, cellHeight = 1.0f / GridHeight;+ double remainder = 0;+ bool configured = false;+ bool healthy = true;+ float peak = 0;+ unsigned bodyCount = 0;++ Cell sample(float x, float y)+ {+ float gx = clamp((x - minX) / cellWidth - 0.5f, 0.0f, float(GridWidth - 1));+ float gy = clamp((y - minY) / cellHeight - 0.5f, 0.0f, float(GridHeight - 1));+ unsigned ix = static_cast<unsigned>(gx), iy = static_cast<unsigned>(gy);+ unsigned nx = std::min(ix + 1, GridWidth - 1);+ unsigned ny = std::min(iy + 1, GridHeight - 1);+ return mix(mix(cells[iy * GridWidth + ix], cells[iy * GridWidth + nx], gx - ix),+ mix(cells[ny * GridWidth + ix], cells[ny * GridWidth + nx], gx - ix), gy - iy);+ }++ void transport()+ {+ const float velocityDecay = std::exp(-1.25f * FixedStep);+ const float displacementDecay = std::exp(-1.05f * FixedStep);+ // Conservative explicit diffusion after semi-Lagrangian backtracing. The+ // coefficient is bounded even for accidentally tiny preview domains.+ const float diffuseX = std::min(0.12f, 4.0f * FixedStep / (cellWidth * cellWidth));+ const float diffuseY = std::min(0.12f, 4.0f * FixedStep / (cellHeight * cellHeight));+ for (unsigned y = 0; y < GridHeight; ++y) {+ for (unsigned x = 0; x < GridWidth; ++x) {+ unsigned index = y * GridWidth + x;+ const Cell &old = cells[index];+ Cell next = sample(minX + (x + 0.5f) * cellWidth - old.vx * FixedStep,+ minY + (y + 0.5f) * cellHeight - old.vy * FixedStep);+ const Cell &left = cells[y * GridWidth + (x ? x - 1 : x)];+ const Cell &right = cells[y * GridWidth + std::min(x + 1, GridWidth - 1)];+ const Cell &down = cells[(y ? y - 1 : y) * GridWidth + x];+ const Cell &up = cells[std::min(y + 1, GridHeight - 1) * GridWidth + x];+ next.vx += (left.vx + right.vx - 2 * old.vx) * diffuseX+ + (down.vx + up.vx - 2 * old.vx) * diffuseY;+ next.vy += (left.vy + right.vy - 2 * old.vy) * diffuseX+ + (down.vy + up.vy - 2 * old.vy) * diffuseY;+ next.vx *= velocityDecay;+ next.vy *= velocityDecay;+ next.dx = next.dx * displacementDecay + next.vx * FixedStep;+ next.dy = next.dy * displacementDecay + next.vy * FixedStep;+ transported[index] = next;+ }+ }+ }++ void injectBody(const Body &body)+ {+ float speed = std::sqrt(body.vx * body.vx + body.vy * body.vy);+ // Only motion injects flow. Standing infantry leave the smoke unchanged;+ // this simulation never subtracts density around a body or its wake.+ if (speed <= 0.02f) return;+ float directionX = body.vx / speed;+ float directionY = body.vy / speed;+ float sideX = -directionY, sideY = directionX;+ float radius = body.radius;+ float extent = radius * 5.0f;+ int firstX = std::max(0, int(std::floor((body.x - extent - minX) / cellWidth)));+ int lastX = std::min(int(GridWidth) - 1, int(std::ceil((body.x + extent - minX) / cellWidth)));+ int firstY = std::max(0, int(std::floor((body.y - extent - minY) / cellHeight)));+ int lastY = std::min(int(GridHeight) - 1, int(std::ceil((body.y + extent - minY) / cellHeight)));+ for (int y = firstY; y <= lastY; ++y) {+ for (int x = firstX; x <= lastX; ++x) {+ float offsetX = minX + (x + 0.5f) * cellWidth - body.x;+ float offsetY = minY + (y + 0.5f) * cellHeight - body.y;+ float along = (offsetX * directionX + offsetY * directionY) / radius;+ float side = (offsetX * sideX + offsetY * sideY) / radius;+ Cell &cell = transported[y * GridWidth + x];++ float shoulder = std::exp(-along * along / 2.25f - side * side / 2.89f);+ float shoulderSide = side / std::sqrt(side * side + 0.20f);+ float targetAlong = speed * 0.20f * shoulder;+ float targetSide = speed * 0.58f * shoulderSide * shoulder;+ float weight = shoulder;+ // A mirrored pair of vortices rolls the displaced smoke into the+ // wake. The transported field persists after the infantry pass.+ for (int sign = -1; sign <= 1; sign += 2) {+ float vortexAlong = along + 1.8f;+ float vortexSide = side - sign * 0.95f;+ float vortex = std::exp(-(vortexAlong * vortexAlong + vortexSide * vortexSide) / 1.82f);+ float circulation = -sign * speed * 0.36f;+ targetAlong += -vortexSide * circulation * vortex;+ targetSide += vortexAlong * circulation * vortex;+ weight = std::max(weight, vortex);+ }+ targetAlong *= BodyFlowStrength;+ targetSide *= BodyFlowStrength;+ float response = 1.0f - std::exp(-10.0f * weight * FixedStep);+ float desiredX = directionX * targetAlong + sideX * targetSide;+ float desiredY = directionY * targetAlong + sideY * targetSide;+ cell.vx += (desiredX - cell.vx) * response;+ cell.vy += (desiredY - cell.vy) * response;+ }+ }+ }++ void finishStep()+ {+ for (unsigned index = 0; index < CellCount; ++index) {+ Cell &cell = transported[index];+ limitVector(cell.vx, cell.vy, MaxVelocity);+ limitVector(cell.dx, cell.dy, MaxDisplacement);+ // Outflow vanishes smoothly at the domain edge, preventing a clamped+ // sampler from carrying disturbance indefinitely beyond the field.+ unsigned x = index % GridWidth, y = index / GridWidth;+ unsigned edge = std::min(std::min(x, GridWidth - 1 - x), std::min(y, GridHeight - 1 - y));+ if (edge < 3) {+ float fade = float(edge) / 3.0f;+ cell.vx *= fade; cell.vy *= fade;+ cell.dx *= fade; cell.dy *= fade;+ }+ }+ cells.swap(transported);+ }++ void publish()+ {+ peak = 0;+ for (unsigned index = 0; index < CellCount; ++index) {+ Cell &cell = cells[index];+ if (!std::isfinite(cell.vx) || !std::isfinite(cell.vy)+ || !std::isfinite(cell.dx) || !std::isfinite(cell.dy)) {+ healthy = false;+ cell = {};+ }+ pixels[index * 4 + 0] = cell.dx;+ pixels[index * 4 + 1] = cell.dy;+ pixels[index * 4 + 2] = 0;+ pixels[index * 4 + 3] = 0;+ peak = std::max(peak, std::sqrt(cell.dx * cell.dx + cell.dy * cell.dy) / MaxDisplacement);+ }+ }++ void setDomain(float newMinX, float newMinY, float newMaxX, float newMaxY)+ {+ bool usable = std::isfinite(newMinX) && std::isfinite(newMinY)+ && std::isfinite(newMaxX) && std::isfinite(newMaxY)+ && newMaxX - newMinX >= 2.0f && newMaxY - newMinY >= 2.0f+ && newMaxX - newMinX < 100000.0f && newMaxY - newMinY < 100000.0f;+ if (!usable) {+ configured = false;+ reset();+ healthy = false;+ return;+ }+ minX = newMinX; minY = newMinY; maxX = newMaxX; maxY = newMaxY;+ cellWidth = (maxX - minX) / GridWidth;+ cellHeight = (maxY - minY) / GridHeight;+ configured = true;+ reset();+ }++ void reset()+ {+ cells.fill({});+ transported.fill({});+ pixels.fill(0.0f);+ remainder = 0;+ healthy = true;+ peak = 0;+ bodyCount = 0;+ }++ void step(float deltaSeconds, const Body *bodies, unsigned count)+ {+ if (!std::isfinite(deltaSeconds) || deltaSeconds < 0 || (count && !bodies)) {+ healthy = false;+ return;+ }+ if (!configured || deltaSeconds == 0) return;+ std::array<Body, MaxBodies> usable = {};+ bodyCount = 0;+ for (unsigned index = 0; index < std::min(count, MaxBodies); ++index) {+ Body body = bodies[index];+ if (!std::isfinite(body.x) || !std::isfinite(body.y) || !std::isfinite(body.z)+ || !std::isfinite(body.vx) || !std::isfinite(body.vy)+ || !std::isfinite(body.radius) || !std::isfinite(body.height)+ || body.radius <= 0 || body.height <= 0) {+ healthy = false;+ continue;+ }+ body.radius = clamp(body.radius, 1.0f, 24.0f);+ // Repositioning an NPC must not launch a supersonic wake or leave a+ // swept trail across the entire map. Begin locally at its new position.+ if (std::abs(body.vx) > MaxInfantrySpeed || std::abs(body.vy) > MaxInfantrySpeed+ || body.vx * body.vx + body.vy * body.vy > MaxInfantrySpeed * MaxInfantrySpeed)+ body.vx = body.vy = 0;+ float extent = body.radius * 5.0f;+ if (body.x + extent < minX || body.x - extent > maxX+ || body.y + extent < minY || body.y - extent > maxY) continue;+ usable[bodyCount++] = body;+ }+ // A stalled frame is capped instead of doing an unbounded catch-up burst.+ // Normal 30/60/120 Hz callers execute the same fixed integration steps.+ remainder += std::min(deltaSeconds, 0.25f);+ bool advanced = false;+ while (remainder + 1.0e-9 >= FixedStep) {+ transport();+ for (unsigned index = 0; index < bodyCount; ++index) injectBody(usable[index]);+ finishStep();+ remainder -= FixedStep;+ advanced = true;+ }+ if (advanced) publish();+ }++};++Flow::Flow() : impl(new Impl) {}+Flow::~Flow() { delete impl; }++void Flow::setDomain(float minX, float minY, float maxX, float maxY)+{+ impl->setDomain(minX, minY, maxX, maxY);+}+void Flow::reset() { impl->reset(); }+void Flow::step(float deltaSeconds, const Body *bodies, unsigned count)+{+ impl->step(deltaSeconds, bodies, count);+}++unsigned Flow::width() const { return GridWidth; }+unsigned Flow::height() const { return GridHeight; }+float Flow::domainMinX() const { return impl->minX; }+float Flow::domainMinY() const { return impl->minY; }+float Flow::domainMaxX() const { return impl->maxX; }+float Flow::domainMaxY() const { return impl->maxY; }+const float *Flow::data() const { return impl->pixels.data(); }+bool Flow::valid() const { return impl->configured && impl->healthy; }+float Flow::maxDisturbance() const { return impl->peak; }+unsigned Flow::activeBodies() const { return impl->bodyCount; }++} // namespace SdlHazardCloudFlowdiff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudShader.cpp b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudShader.cppnew file mode 100644index 000000000..07e356f28--- /dev/null+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudShader.cpp@@ -0,0 +1,711 @@+// Shared bounded world-space density integrated along each camera ray.+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.+#include "SdlHazardCloudShader.h"++std::string SdlHazardCloudVertexShader()+{+ return R"HLSL(+float4 main(uint vertex : SV_VertexID) : SV_Position+{+ float2 uv = float2((vertex << 1) & 2, vertex & 2);+ return float4(uv * float2(2, -2) + float2(-1, 1), 0, 1);+}+)HLSL";+}++static std::string cloudShader(int pass)+{+ return std::string(pass == 1 ? "#define CLOUD_COMPOSITE 1\n" : "#define CLOUD_COMPOSITE 0\n")+ + "#define CLOUD_HEAT_PASS " + std::to_string(pass == 4 ? 1 : 0) + "\n"+ + "#define CLOUD_CACHE_PASS " + std::to_string(pass == 2 || pass == 3 ? pass - 1 : 0) + "\n" + R"HLSL(+Texture2D<float> SceneDepth : register(t0, space2);+SamplerState DepthSampler : register(s0, space2);+Texture2D<float4> InteractionField : register(t1, space2);+SamplerState InteractionSampler : register(s1, space2);+#if CLOUD_COMPOSITE+Texture2D<float4> CloudImage : register(t2, space2);+SamplerState CloudSampler : register(s2, space2);+#endif+#if CLOUD_HEAT_PASS+Texture2D<float4> HeatBackground : register(t5, space2);+SamplerState HeatSampler : register(s5, space2);+#endif+Texture2D<float4> CacheImage0 : register(t3, space2);+SamplerState CacheSampler0 : register(s3, space2);+Texture2D<float4> CacheImage1 : register(t4, space2);+SamplerState CacheSampler1 : register(s4, space2);+Texture2D<float> TerrainImage : register(t6, space2);+SamplerState TerrainSampler : register(s6, space2);++cbuffer SdlHazardCloudConstants : register(b0, space3)+{+ row_major float4x4 WorldFromClip;+ float4 CameraPosition;+ float4 Viewport;+ float4 Scene;+ float4 Field0;+ float4 Field1;+ float4 Shape0;+ float4 Shape1;+ float4 Footprints;+ float4 Source0;+ float4 Source1;+ float4 Settings;+ float4 Interaction;+ float4 FlowSettings;+ float4 Cache0;+ float4 Cache1;+ float4 CachePass;+ float4 PaletteMain[4];+ float4 PaletteShadow[4];+ float4 Terrain0;+ float4 Terrain1;+};++float volumeHash(float3 p)+{+ p = frac(p * 0.1031);+ p += dot(p, p.yzx + 33.33);+ return frac((p.x + p.y) * p.z);+}++float volumeNoise(float3 p)+{+ float3 cell = floor(p);+ float3 f = frac(p);+ f = f * f * (3.0 - 2.0 * f);+ float a = lerp(volumeHash(cell), volumeHash(cell + float3(1, 0, 0)), f.x);+ float b = lerp(volumeHash(cell + float3(0, 1, 0)), volumeHash(cell + float3(1, 1, 0)), f.x);+ float c = lerp(volumeHash(cell + float3(0, 0, 1)), volumeHash(cell + float3(1, 0, 1)), f.x);+ float d = lerp(volumeHash(cell + float3(0, 1, 1)), volumeHash(cell + float3(1, 1, 1)), f.x);+ return lerp(lerp(a, b, f.y), lerp(c, d, f.y), f.z);+}++float4 volumeInteraction(float2 world)+{+ if (FlowSettings.x < 0.5) return float4(0, 0, 0, 0);+ float2 uv = (world - Interaction.xy) * Interaction.zw;+ if (any(uv < 0.0) || any(uv > 1.0)) return float4(0, 0, 0, 0);+ uint width, height;+ InteractionField.GetDimensions(width, height);+ float2 size = float2(width, height);+ float2 texel = uv * size - 0.5;+ float2 lower = floor(texel);+ float2 weight = frac(texel);+ // RGBA32F linear filtering is not universal. The preview binds a point+ // sampler and interpolates four texel centres explicitly instead.+ float2 a = (clamp(lower, float2(0, 0), size - 1.0) + 0.5) / size;+ float2 b = (clamp(lower + 1.0, float2(0, 0), size - 1.0) + 0.5) / size;+ float4 top = lerp(InteractionField.SampleLevel(InteractionSampler, a, 0),+ InteractionField.SampleLevel(InteractionSampler, float2(b.x, a.y), 0), weight.x);+ float4 bottom = lerp(InteractionField.SampleLevel(InteractionSampler, float2(a.x, b.y), 0),+ InteractionField.SampleLevel(InteractionSampler, b, 0), weight.x);+ return lerp(top, bottom, weight.y);+}++float3 volumeWorldAt(float2 pixel, float depth)+{+ float2 uv = (pixel - Viewport.xy) / max(Viewport.zw, float2(1, 1));+ float4 world = mul(float4(uv * float2(2, -2) + float2(-1, 1), depth, 1), WorldFromClip);+ float w = abs(world.w) < 0.000001 ? (world.w < 0 ? -0.000001 : 0.000001) : world.w;+ return world.xyz / w;+}++// Terrain grids include both support boundaries and are packed side by side.+// Point samples with explicit bilinear interpolation also work on devices that+// cannot linearly filter R32F. Disabled fields retain the approved planar path.+float volumeGround(float2 world, float4 field, float4 shape, float fringe, float identity)+{+ float4 terrain = identity < 0.5 ? Terrain0 : Terrain1;+ if (terrain.z < 0.5) return field.z - shape.x;+ uint width, height;+ TerrainImage.GetDimensions(width, height);+ float side = float(height);+ float radius = field.w + fringe + FlowSettings.y;+ float2 uv = saturate((world - field.xy + radius) / max(radius * 2.0, 0.001));+ float2 texel = uv * (side - 1.0);+ float2 lower = floor(texel), weight = frac(texel);+ float2 upper = min(lower + 1.0, side - 1.0);+ float2 offset = float2(identity < 0.5 ? 0.0 : side, 0.0);+ float2 size = float2(width, height);+ float2 a = (lower + offset + 0.5) / size;+ float2 b = (upper + offset + 0.5) / size;+ float top = lerp(TerrainImage.SampleLevel(TerrainSampler, a, 0),+ TerrainImage.SampleLevel(TerrainSampler, float2(b.x, a.y), 0), weight.x);+ float bottom = lerp(TerrainImage.SampleLevel(TerrainSampler, float2(a.x, b.y), 0),+ TerrainImage.SampleLevel(TerrainSampler, b, 0), weight.x);+ return lerp(top, bottom, weight.y);+}++bool volumeInterval(float3 origin, float3 direction, float4 field, float4 shape, float fringe, float identity, float sceneLimit,+ out float first, out float last)+{+ first = last = 0.0;+ if (field.w <= 0.001 || shape.x <= 0.001 || shape.y <= 0.00001) return false;+ float margin = FlowSettings.x > 0.5 ? max(FlowSettings.y, 0.0) : 0.0;+ float3 extent = float3(field.w + fringe + margin, field.w + fringe + margin, shape.x);+ float3 safeDirection = float3(+ abs(direction.x) < 0.000001 ? (direction.x < 0 ? -0.000001 : 0.000001) : direction.x,+ abs(direction.y) < 0.000001 ? (direction.y < 0 ? -0.000001 : 0.000001) : direction.y,+ abs(direction.z) < 0.000001 ? (direction.z < 0 ? -0.000001 : 0.000001) : direction.z);+ float3 low = field.xyz - extent;+ float3 high = field.xyz + extent;+ float4 terrain = identity < 0.5 ? Terrain0 : Terrain1;+ if (terrain.z > 0.5) {+ low.z = terrain.x;+ high.z = terrain.y + shape.x * 2.0;+ }+ float3 lo = (low - origin) / safeDirection;+ float3 hi = (high - origin) / safeDirection;+ float3 nearAxis = min(lo, hi);+ float3 farAxis = max(lo, hi);+ first = max(0.0, max(nearAxis.x, max(nearAxis.y, nearAxis.z)));+ last = min(sceneLimit, min(farAxis.x, min(farAxis.y, farAxis.z)));+ return last > first;+}++// Smooth, overlapping density lobes, evaluated in 3D rather than drawn as+// sprites. Jittered cells distribute billows at a stable world size; their tops+// vary independently so the gas has no single dome or flat opaque ceiling.+float volumeBillows(float2 p, float h, float erosion)+{+ float2 cell = floor(p);+ float largest = 0.0, total = 0.0;+ [unroll] for (int y = -1; y <= 1; ++y) {+ [unroll] for (int x = -1; x <= 1; ++x) {+ float2 c = cell + float2(x, y);+ float a = volumeHash(float3(c, 3.7));+ float b = volumeHash(float3(c, 19.1));+ float2 centre = c + float2(0.10 + a * 0.80, 0.10 + b * 0.80);+ float distance = length(p - centre);+ // The existing compact-support factor is exactly zero here.+ // Skip the remaining hash and lobe math without changing support.+ if (distance >= 1.09) continue;+ float k = volumeHash(float3(c, 43.4));+ float2 q = (p - centre) / (0.55 + k * 0.50);+ float z = (h - (0.18 + a * 0.26)) / (0.28 + b * 0.27);+ float body = saturate(1.0 - dot(q, q) - z * z + erosion);+ body *= sqrt(body);+ // A cell outside this 3x3 neighborhood is at least 1.10 cells+ // away. Keep eroded/expanded lobes compact before that boundary+ // so changing the neighborhood cannot reveal a density seam.+ body *= 1.0 - smoothstep(0.95, 1.09, distance);+ largest = max(largest, body);+ total += body;+ }+ }+ return largest * 0.55 + total * 0.45;+}++// The hazard radius controls readable coverage. The separate soft fringe matches+// the original renderer's textured puddles, which extend beyond their centres.+float volumeDensity(float3 world, float4 field, float4 shape, float4 source, float fringe, float identity)+{+ if (field.w <= 0.001 || shape.y <= 0.00001) return 0.0;+ float halfHeight = max(shape.x, 0.25);+ float ground = volumeGround(world.xy, field, float4(halfHeight, shape.yzw), fringe, identity);+ float h = (world.z - ground) / (2.0 * halfHeight);+ if (h <= 0.0 || h >= 1.0) return 0.0;+ float2 local = world.xy - field.xy;+ float radius = length(local);+ float outerRadius = field.w + fringe;+ if (radius >= outerRadius + FlowSettings.y) return 0.0;++ float heightWeight = 1.0 - 0.65 * smoothstep(0.40, 1.0, h);+ float2 displacement = volumeInteraction(world.xy).xy;+ displacement *= min(1.0, max(FlowSettings.y, 0.0) / max(length(displacement), 0.0001));+ float2 advected = local - displacement * heightWeight;+ float movingRadius = length(advected);++ // These masks are independent of procedural detail. Reject only exactly+ // zero contributions, retaining the full veil and the original billow math.+ float coverage = 1.0 - smoothstep(field.w, max(field.w + 1.0, outerRadius), radius);+ float outside = smoothstep(field.w * 0.95, max(field.w + 1.0, outerRadius), radius);+ float veil = 0.70 * (1.0 - smoothstep(0.18, 0.55, h));+ float bulkEdge = 1.0 - smoothstep(field.w * 0.78, field.w + fringe * 0.68, movingRadius);+ float front = field.w * lerp(0.12, 1.0, sqrt(saturate(shape.w))) + fringe * 0.68 * shape.w;+ float formation = 1.0 - smoothstep(max(0.0, front - 18.0), front + 12.0, movingRadius);+ float topFade = 1.0 - smoothstep(0.90, 1.0, h);+ bool hasBulk = bulkEdge > 0.0 && formation > 0.0 && topFade > 0.0;+ bool hasVeil = coverage > 0.0 && veil > 0.0;+ if (!hasBulk && !hasVeil) return 0.0;+ if (!hasBulk && outside == 0.0) {+ // Inside the footprint, the veil has no procedural modulation.+ float density = (coverage * veil) * shape.y;+ density *= smoothstep(0.0, 0.045, h);+ return density;+ }++ float time = source.w;+ // Nuclear residue fades in over the entire field; it does not transport+ // billows outward from a central emitter like a toxin release.+ bool nuclear = shape.z >= 0.5 && shape.z < 1.5;+ float expansion = nuclear ? 1.0 : exp(-min(source.y / max(field.w + fringe, 1.0) * 0.35, 0.5));++ // World-sized billows: a large bomb has more curls, never one enlarged blob.+ // Vertical coordinates retain several folds inside the infantry-height slab.+ float3 at = float3((field.xy + advected * expansion) * 0.048, h * 1.6);+ at += float3(identity * 9.7, identity * 3.1, identity * 13.2);+ at.xy += float2(-0.030, 0.018) * time + float2(0.048, -0.040) * time * h;+ at.z -= time * 0.12;+ float curlX = volumeNoise(at * 0.57 + float3(4.2, 1.7, time * 0.025)) - 0.5;+ float curlY = volumeNoise(at * 0.57 + float3(1.3, 8.1, -time * 0.020)) - 0.5;+ at += float3(curlX, curlY, (curlX - curlY) * 0.55) * 0.85;+ float broad = volumeNoise(at);+ float folds = volumeNoise(at * 2.03 + float3(7.1, 3.7, 11.3));+ float fine = volumeNoise(at * 4.09 + float3(11.7, 8.3, 2.1));+ float detail = broad * 0.56 + folds * 0.30 + fine * 0.14;++ // A shallow continuous veil makes the whole hazard legible, even between+ // billows or while they are forming. Infantry advect the curls, not this+ // coverage mask, so their wakes cannot suggest a safe hole in the hazard.+ coverage *= lerp(1.0, 0.20 + 0.80 * smoothstep(0.20, 0.80, detail), outside);++ // Volume height is independent of the horizontal footprint. Individual+ // rolling tops replace the old ellipsoid and its shrinking ground contact.+ float bulk = 0.0;+ if (hasBulk) {+ float erosion = (folds - 0.5) * 0.55 + (fine - 0.5) * 0.20 - source.z * 0.14;+ float billow = volumeBillows(at.xy, h, erosion) * 0.72+ + volumeBillows(at.xy * 0.58 + float2(17.3, 29.1), h, erosion * 0.75) * 0.46;+ bulk = billow * bulkEdge * formation * 2.30 * topFade;+ }+ float density = (coverage * veil + bulk) * shape.y;+ // Soft ground contact and a naturally broken upper surface; no actor capsule+ // cutout, pressure rim, or artificial ring is added to the density.+ density *= smoothstep(0.0, 0.045, h);+ return density;+}++// Each slice has its own texel-centred XY rectangle. Clamp to the last texel+// centre before hardware bilinear filtering, so adjacent atlas slices cannot+// bleed into one another. Interpolate Z explicitly between two slices.+float4 volumeCacheRead(float3 world, float4 field, float4 shape, float fringe, float4 grid, float identity)+{+ if (shape.x <= 0.001 || shape.y <= 0.00001 || grid.z < 2.0) return float4(0, 0, 0, 0);+ float radius = field.w + fringe + FlowSettings.y;+ float ground = volumeGround(world.xy, field, shape, fringe, identity);+ float3 uv = (world - float3(field.xy - radius, ground))+ / float3(radius * 2.0, radius * 2.0, shape.x * 2.0);+ if (any(uv < 0.0) || any(uv > 1.0)) return float4(0, 0, 0, 0);+ float3 voxel = saturate(uv) * (grid.xyz - 1.0);+ uint z0 = (uint)floor(voxel.z), z1 = min(z0 + 1, (uint)grid.z - 1);+ uint columns = (uint)grid.w, rows = ((uint)grid.z + columns - 1) / columns;+ float2 atlasSize = grid.xy * float2(columns, rows);+ float2 tile0 = float2(z0 % columns, z0 / columns) * grid.xy;+ float2 tile1 = float2(z1 % columns, z1 / columns) * grid.xy;+ float2 uv0 = (tile0 + voxel.xy + 0.5) / atlasSize;+ float2 uv1 = (tile1 + voxel.xy + 0.5) / atlasSize;+ // Bind resources globally: this HLSL compiler emits invalid SPIR-V stores+ // for resource-valued function parameters, even though HLSL accepts them.+ float4 a, b;+ if (identity < 0.5) {+ a = CacheImage0.SampleLevel(CacheSampler0, uv0, 0);+ b = CacheImage0.SampleLevel(CacheSampler0, uv1, 0);+ } else {+ a = CacheImage1.SampleLevel(CacheSampler1, uv0, 0);+ b = CacheImage1.SampleLevel(CacheSampler1, uv1, 0);+ }+ return lerp(a, b, frac(voxel.z));+}++float4 volumeCached(float3 world, float4 field, float4 shape, float fringe, float identity)+{+ if (identity < 0.5)+ return volumeCacheRead(world, field, shape, fringe, Cache0, identity);+ return volumeCacheRead(world, field, shape, fringe, Cache1, identity);+}++float volumeExtinction(float4 shape)+{+ return 0.075 * min(1.8, pow(9.3 / max(shape.x, 0.25), 0.35));+}++uint volumePalette(float palette)+{+ return (uint)clamp(floor(palette + 0.5), 0.0, 3.0);+}++float3 volumeScattered(float palette, float sunlight)+{+ uint index = volumePalette(palette);+ return PaletteShadow[index].rgb + PaletteMain[index].rgb * (0.12 + 0.88 * sunlight) * 0.84;+}++// RGB holds scattered-light coefficient, A holds extinction. Integrating the+// sum still mixes overlapping clouds in world space rather than sorting layers.+void volumeSample(float3 world, float4 field, float4 shape, float4 source, float fringe, float identity,+ inout float optical, inout float3 light)+{+ float4 coefficients = volumeCached(world, field, shape, fringe, identity);+ optical += coefficients.a;+ light += coefficients.rgb;+}++#if CLOUD_CACHE_PASS+float4 volumeBuildCache(float2 pixel)+{+ float identity = CachePass.x;+ float4 field = identity < 0.5 ? Field0 : Field1;+ float4 shape = identity < 0.5 ? Shape0 : Shape1;+ float4 source = identity < 0.5 ? Source0 : Source1;+ float fringe = identity < 0.5 ? Footprints.x : Footprints.y;+ float4 grid = identity < 0.5 ? Cache0 : Cache1;+ uint2 texel = (uint2)floor(pixel), dimensions = (uint2)grid.xy;+ uint slice = texel.x / dimensions.x + (texel.y / dimensions.y) * (uint)grid.w;+ if (slice >= (uint)grid.z) return float4(0, 0, 0, 0);+ float3 voxel = float3(texel.x % dimensions.x, texel.y % dimensions.y, slice);+ float radius = field.w + fringe + FlowSettings.y;+ float3 world = float3(field.xy - radius, field.z - shape.x)+ + voxel / (grid.xyz - 1.0) * float3(radius * 2.0, radius * 2.0, shape.x * 2.0);+ float4 terrain = identity < 0.5 ? Terrain0 : Terrain1;+ if (terrain.z > 0.5)+ world.z = volumeGround(world.xy, field, shape, fringe, identity)+ + voxel.z / (grid.z - 1.0) * shape.x * 2.0;+#if CLOUD_CACHE_PASS == 1+ return float4(volumeDensity(world, field, shape, source, fringe, identity), 0, 0, 1);+#else+ float density = volumeCached(world, field, shape, fringe, identity).r;+ if (density < 0.001) return float4(0, 0, 0, 0);+ const float3 sun = float3(-0.462, -0.347, 0.816);+ float scale = max(shape.x, 0.25) / 9.3;+ float optical = volumeCached(world + sun * (2.5 * scale), field, shape, fringe, identity).r * 5.0;+ optical += volumeCached(world + sun * (8.0 * scale), field, shape, fringe, identity).r * 10.0;+ optical += volumeCached(world + sun * (16.0 * scale), field, shape, fringe, identity).r * 14.0;+ // Change optical thickness without changing the cloud's footprint, billows+ // or source history. The same multiplier softens its internal shadows.+ float extinction = volumeExtinction(shape) * PaletteShadow[volumePalette(shape.z)].w;+ float sunlight = exp(-optical * extinction * scale * 1.20);+ float coefficient = density * extinction;+ if (shape.z >= 0.5 && shape.z < 1.5) {+ // Nuclear smoke carries rolling charcoal billows above the warm ground+ // haze. Bake their optical properties here, so they cost no additional+ // camera-ray samples and share the existing hazard support and height.+ float h = saturate((world.z - volumeGround(world.xy, field, shape, fringe, identity))+ / max(shape.x * 2.0, 0.5));+ float age = source.w;+ float3 at = float3(world.xy * 0.041, h * 1.85);+ at += float3(-0.024 * age, 0.016 * age, -0.17 * age);+ at += float3(12.7, 31.4, 8.6);+ float broad = volumeNoise(at);+ float 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);+ // Retain the amber veil and lighter billow rims. The plume's own+ // density still determines coverage, formation front, and dissipation.+ soot *= smoothstep(0.06, 0.25, h);+ soot *= 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);+ soot *= 1.0 - 0.60 * saturate(source.z);+ float sootLight = sqrt(saturate(sunlight));+ float3 charcoal = float3(0.055, 0.052, 0.047)+ + float3(0.45, 0.43, 0.39) * sootLight;+ // Offset the approved neutral charcoal with the shadow color. Avoid+ // dividing by its small default channels, which would amplify blue+ // edits into clipped, luminous billows instead of a usable tint.+ charcoal = saturate(charcoal + (PaletteShadow[1].rgb - float3(0.115, 0.085, 0.030)));+ float3 scattered = lerp(volumeScattered(shape.z, sunlight), charcoal, soot * 0.80);+ coefficient *= 1.0 + 0.08 * soot;+ return float4(scattered * coefficient * PaletteMain[1].w, coefficient);+ }+ return float4(volumeScattered(shape.z, sunlight) * coefficient * PaletteMain[volumePalette(shape.z)].w, coefficient);+#endif+}+#endif++void volumeIntegrate(float3 origin, float3 direction, float first, float last,+ bool include0, bool include1, int steps, float jitter,+ inout float3 radiance, inout float transmittance)+{+ if (last <= first || transmittance < 0.015) return;+ float stride = (last - first) / float(steps);+ [loop] for (int sampleIndex = 0; sampleIndex < 96; ++sampleIndex) {+ if (sampleIndex >= steps || transmittance < 0.015) break;+ float3 world = origin + direction * (first + (float(sampleIndex) + jitter) * stride);+ float optical = 0.0;+ float3 light = float3(0, 0, 0);+ if (include0) volumeSample(world, Field0, Shape0, Source0, Footprints.x, 0.0, optical, light);+ if (include1) volumeSample(world, Field1, Shape1, Source1, Footprints.y, 1.0, optical, light);+ if (optical < 0.000001) continue;+ float opacity = 1.0 - exp(-optical * stride);+ radiance += transmittance * opacity * light / optical;+ transmittance *= 1.0 - opacity;+ }+}++float4 volumeRaymarch(float2 pixel)+{+ if (Settings.z < 0.5 || Scene.z < 0.5 || Settings.x < 0.5) return float4(0, 0, 0, 0);+ // Starting on the near plane works for perspective and orthographic views,+ // including a camera inside the cloud. Depth clips the ray itself, so smoke+ // in front of an infantryman remains visible while smoke behind him does not.+ float3 origin = volumeWorldAt(pixel, 0.0);+ float3 farPoint = volumeWorldAt(pixel, 1.0);+ float3 direction = normalize(farPoint - origin);+ float sceneDepth = SceneDepth.SampleLevel(DepthSampler, pixel * Scene.xy, 0).r;+ float sceneLimit = 100000.0;+ if (sceneDepth < 0.999999) {+ float3 opaqueWorld = volumeWorldAt(pixel, sceneDepth);+ sceneLimit = max(0.0, dot(opaqueWorld - origin, direction));+ }+ float near0, far0, near1, far1;+ bool hit0 = volumeInterval(origin, direction, Field0, Shape0, Footprints.x, 0.0, sceneLimit, near0, far0);+ bool hit1 = volumeInterval(origin, direction, Field1, Shape1, Footprints.y, 1.0, sceneLimit, near1, far1);+ hit1 = hit1 && Settings.x > 1.5;+ if (!hit0 && !hit1) return float4(0, 0, 0, 0);+ if (!hit0) { near0 = 100001.0; far0 = 0.0; }+ if (!hit1) { near1 = 100001.0; far1 = 0.0; }++ float jitter = 0.35 + volumeHash(float3(floor(pixel), 17.0)) * 0.30;+ float3 radiance = float3(0, 0, 0);+ float transmittance = 1.0;+ int singleSteps = (int)clamp(Settings.w * 0.5, 32.0, 96.0);+ // A hill broadens the conservative Z interval without making the local+ // cloud thicker. Spend more samples there so the thin occupied parts do+ // not disappear between steps. Flat/deck fields keep their exact budget.+ float terrainScale = 1.0;+ if (hit0 && Terrain0.z > 0.5)+ terrainScale = max(terrainScale, 1.0 + max(0.0, Terrain0.y - Terrain0.x)+ / max(Shape0.x * 2.0, 0.5));+ if (hit1 && Terrain1.z > 0.5)+ terrainScale = max(terrainScale, 1.0 + max(0.0, Terrain1.y - Terrain1.x)+ / max(Shape1.x * 2.0, 0.5));+ if (terrainScale > 1.0)+ singleSteps = (int)min(96.0, ceil(float(singleSteps) * terrainScale));+ if (hit0 && hit1 && min(far0, far1) > max(near0, near1)) {+ float first = min(near0, near1);+ float last = max(far0, far1);+ float longest = max(far0 - near0, far1 - near1);+ // Matching slabs need the same sample spacing as a single field.+ // Increase the budget only as their combined interval grows, while+ // still summing both fields' density and light at every sample.+ int jointSteps = (int)clamp(ceil(float(singleSteps) * ((last - first) / longest)),+ float(singleSteps), 96.0);+ volumeIntegrate(origin, direction, first, last, true, true, jointSteps, jitter, radiance, transmittance);+ } else if (near0 <= near1) {+ volumeIntegrate(origin, direction, near0, far0, true, false, singleSteps, jitter, radiance, transmittance);+ volumeIntegrate(origin, direction, near1, far1, false, true, singleSteps, jitter, radiance, transmittance);+ } else {+ volumeIntegrate(origin, direction, near1, far1, false, true, singleSteps, jitter, radiance, transmittance);+ volumeIntegrate(origin, direction, near0, far0, true, false, singleSteps, jitter, radiance, transmittance);+ }+ float opacity = 1.0 - transmittance;+ // Premultiplied radiance can be interpolated without dark fringes. The+ // composite uses ONE/INVSRCALPHA; density and lighting remain unchanged.+ return float4(radiance, opacity);+}++float2 volumeFullPixel(float2 lowPixel)+{+ // Each half-resolution texel represents one exact full-resolution pixel.+ // Clamp the final sample for odd target sizes, retaining the camera's+ // original viewport and depth coordinates in both passes.+ return min(floor(lowPixel) * 2.0 + 1.5, round(1.0 / Scene.xy) - 0.5);+}++#if CLOUD_COMPOSITE || CLOUD_HEAT_PASS+float volumeDepthSlope(float2 pixel, float depth, float2 axis, float maximumStep)+{+ float before = depth - SceneDepth.SampleLevel(DepthSampler, (pixel - axis) * Scene.xy, 0).r;+ float after = SceneDepth.SampleLevel(DepthSampler, (pixel + axis) * Scene.xy, 0).r - depth;+ // Pick the neighbor on the same surface. At a thin silhouette both sides+ // can cross an edge: discard large jumps instead of extending that edge as+ // a plane. Device depth is affine across a rasterized surface triangle.+ float slope = abs(before) < abs(after) ? before : after;+ float distance = length(volumeWorldAt(pixel, depth + slope) - volumeWorldAt(pixel, depth));+ return distance <= maximumStep ? slope : 0.0;+}+#endif++#if CLOUD_HEAT_PASS+bool volumeHeatContains(float3 world, float4 field, float4 shape, float fringe, float identity)+{+ if (shape.z < 0.5 || shape.z >= 1.5 || shape.y <= 0.00001 || field.w <= 0.001)+ return false;+ float ground = volumeGround(world.xy, field, shape, fringe, identity);+ float2 local = world.xy - field.xy;+ float radius = field.w + fringe;+ return dot(local, local) <= radius * radius+ && world.z >= ground - 0.65 && world.z <= ground + shape.x * 5.2;+}++float2 volumeHeatOffset(float3 origin, float3 direction, float limit, bool immersed,+ float4 field, float4 shape, float4 source, float fringe, float identity)+{+ // Palette 1 identifies nuclear heat. Green toxin, blue anthrax and purple+ // gamma have no refraction, even when their volume caches are reused.+ if (shape.z < 0.5 || shape.z >= 1.5 || shape.y <= 0.00001) return float2(0, 0);+ float4 heatField = field;+ float4 heatShape = shape;+ heatShape.x *= 2.6;+ heatField.z += heatShape.x - shape.x; // same ground, gently rising hot air+ float first, last;+ // Use one continuous warp through an immersed unit and its surroundings.+ // Stopping the wave at the unit's depth gives its silhouette a different+ // displacement from the adjacent ground, leaving a doubled edge.+ float waveLimit = immersed ? 100000.0 : limit;+ if (!volumeInterval(origin, direction, heatField, heatShape, fringe, identity, waveLimit, first, last))+ return float2(0, 0);+ float3 world = origin + direction * ((first + last) * 0.5);+ float h = saturate((world.z - volumeGround(world.xy, field, shape, fringe, identity))+ / (heatShape.x * 2.0));+ float radial = 1.0 - smoothstep(field.w * 0.45, field.w + fringe * 0.65, length(world.xy - field.xy));+ float heightFade = 1.0 - smoothstep(0.35, 1.0, h);+ float path = saturate((last - first) / max(shape.x * 2.0, 1.0));+ float strength = radial * heightFade * path * saturate(shape.y)+ * lerp(0.45, 1.0, shape.w) * (0.72 + 0.28 * source.x);+ if (strength <= 0.001) return float2(0, 0);+ // The midpoint of a ray through a flat slab has nearly constant Z. Use a+ // vertical curtain through the field centre for phase, so the visible folds+ // actually travel upward through the air instead of merely flickering.+ float horizontal = dot(direction.xy, direction.xy);+ float curtain = dot(field.xy - origin.xy, direction.xy) / max(horizontal, 0.0001);+ float2 curtainXY = origin.xy + direction.xy * curtain;+ float waveZ = horizontal > 0.0001+ ? origin.z + direction.z * curtain - volumeGround(curtainXY, field, shape, fringe, identity)+ : world.y - field.y;+ float2 local = world.xy - field.xy;+ float turbulence = volumeNoise(float3(local * 0.055, waveZ * 0.10 - source.w * 0.5)) * 2.0 - 1.0;+ // Broad lateral variation keeps immersed silhouettes from being stretched+ // by a sharply changing displacement across just a few screen pixels.+ float phase = waveZ * 0.17 - source.w * 3.4 + 0.9 * sin(dot(local, float2(0.028, 0.015)));+ float2 ripple = float2(+ 0.80 * sin(phase + turbulence * 0.5) + 0.20 * sin(phase * 1.41 + local.x * 0.025 + 1.7),+ 0.22 * cos(phase * 1.21 + local.y * 0.025) + 0.10 * turbulence);+ return ripple * strength;+}++bool volumeHeatDepthSafe(float2 displaced, float2 pixel, float depth, float2 slope, float tolerance,+ uint immersed)+{+ // Validate all four bilinear colour taps against the local depth plane.+ // An immersed unit and the ground in the same hot field may refract across+ // their shared silhouette. Foreground objects outside it remain protected.+ float2 lower = floor(displaced - 0.5) + 0.5;+ [unroll] for (int y = 0; y < 2; ++y) {+ [unroll] for (int x = 0; x < 2; ++x) {+ float2 tap = clamp(lower + float2(x, y), Viewport.xy, Viewport.xy + Viewport.zw - 1.0);+ float actual = SceneDepth.SampleLevel(DepthSampler, tap * Scene.xy, 0).r;+ float expected = depth + dot(slope, tap - pixel);+ float3 actualWorld = volumeWorldAt(tap, actual);+ float difference = length(actualWorld - volumeWorldAt(tap, expected));+ if (difference > tolerance) {+ bool sharedHotAir = ((immersed & 1u) != 0+ && volumeHeatContains(actualWorld, Field0, Shape0, Footprints.x, 0.0))+ || ((immersed & 2u) != 0+ && volumeHeatContains(actualWorld, Field1, Shape1, Footprints.y, 1.0));+ if (!sharedHotAir) return false;+ }+ }+ }+ return true;+}++float4 volumeHeatColour(float2 pixel, float depth, float3 opaqueWorld, float2 slope, float tolerance)+{+ if (Settings.y <= 0.0) return float4(0, 0, 0, 0);+ float3 origin = volumeWorldAt(pixel, 0.0);+ float3 direction = normalize(volumeWorldAt(pixel, 1.0) - origin);+ float limit = depth < 0.999999 ? max(0.0, dot(opaqueWorld - origin, direction)) : 100000.0;+ uint immersed = volumeHeatContains(opaqueWorld, Field0, Shape0, Footprints.x, 0.0) ? 1u : 0u;+ if (Settings.x > 1.5 && volumeHeatContains(opaqueWorld, Field1, Shape1, Footprints.y, 1.0)) immersed |= 2u;+ float2 offset = volumeHeatOffset(origin, direction, limit, (immersed & 1u) != 0,+ Field0, Shape0, Source0, Footprints.x, 0.0);+ if (Settings.x > 1.5)+ offset += volumeHeatOffset(origin, direction, limit, (immersed & 2u) != 0,+ Field1, Shape1, Source1, Footprints.y, 1.0);+ offset *= Settings.y * 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 float4(0, 0, 0, 0);+ // Near a silhouette, try a smaller bend rather than pull foreground pixels+ // into the haze or impose a broad undistorted border around the infantry.+ [loop] for (int attempt = 0; attempt < 3; ++attempt) {+ float2 displaced = clamp(pixel + offset, Viewport.xy, Viewport.xy + Viewport.zw - 1.0);+ if (volumeHeatDepthSafe(displaced, pixel, depth, slope, tolerance, immersed)) {+ float3 refracted = HeatBackground.SampleLevel(HeatSampler, displaced * Scene.xy, 0).rgb;+ return float4(refracted, 1.0);+ }+ offset *= 0.5;+ }+ return float4(0, 0, 0, 0);+}+#endif++float4 main(float4 position : SV_Position) : SV_Target+{+#if CLOUD_HEAT_PASS+ if (Settings.z < 0.5 || Scene.z < 0.5 || Settings.x < 0.5 || Settings.y <= 0.0)+ return float4(0, 0, 0, 0);+ float depth = SceneDepth.SampleLevel(DepthSampler, position.xy * Scene.xy, 0).r;+ float3 world = volumeWorldAt(position.xy, depth);+ 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));+ return volumeHeatColour(position.xy, depth, world, slope, tolerance);+#elif CLOUD_CACHE_PASS+ return volumeBuildCache(position.xy);+#elif !CLOUD_COMPOSITE+ return volumeRaymarch(volumeFullPixel(position.xy));+#else+ if (Settings.z < 0.5 || Scene.z < 0.5 || Settings.x < 0.5) return float4(0, 0, 0, 0);+ uint width, height;+ CloudImage.GetDimensions(width, height);+ float2 size = float2(width, height);+ float2 grid = (position.xy - 1.5) * 0.5;+ // An odd target has a final sample only one pixel from its predecessor.+ // Select that exact sample on the final row/column rather than blending it.+ float2 fullSize = round(1.0 / Scene.xy);+ if (position.x >= fullSize.x - 0.5) grid.x = size.x - 1.0;+ if (position.y >= fullSize.y - 0.5) grid.y = size.y - 1.0;+ float2 lower = floor(grid);+ float2 fraction = frac(grid);+ float centreDepth = SceneDepth.SampleLevel(DepthSampler, position.xy * Scene.xy, 0).r;+ float3 centreWorld = volumeWorldAt(position.xy, centreDepth);+ float pixelSpan = length(volumeWorldAt(position.xy + float2(1, 0), centreDepth) - centreWorld);+ float tolerance = max(0.65, pixelSpan * 0.75);+ float2 slope = float2(+ volumeDepthSlope(position.xy, centreDepth, float2(1, 0), pixelSpan * 4.0),+ volumeDepthSlope(position.xy, centreDepth, float2(0, 1), pixelSpan * 4.0));+ float4 result = float4(0, 0, 0, 0);+ float total = 0.0;+ [unroll] for (int y = 0; y < 2; ++y) {+ [unroll] for (int x = 0; x < 2; ++x) {+ float2 texel = clamp(lower + float2(x, y), float2(0, 0), size - 1.0);+ float2 tapPixel = volumeFullPixel(texel);+ float tapDepth = SceneDepth.SampleLevel(DepthSampler, tapPixel * Scene.xy, 0).r;+ // Compare distance along the current ray, not nonlinear device Z.+ // Never interpolate smoke clipped at an unrelated foreground body+ // into the background, or background smoke across an infantryman.+ float expectedDepth = centreDepth + dot(slope, tapPixel - position.xy);+ float difference = length(volumeWorldAt(tapPixel, tapDepth) - volumeWorldAt(tapPixel, expectedDepth));+ float weight = (x ? fraction.x : 1.0 - fraction.x) * (y ? fraction.y : 1.0 - fraction.y);+ weight *= difference <= tolerance ? 1.0 : 0.0;+ result += CloudImage.SampleLevel(CloudSampler, (texel + 0.5) / size, 0) * weight;+ total += weight;+ }+ }+ // A thin silhouette may be absent from all four low-resolution samples.+ // Integrate that pixel at full resolution rather than blur through it.+ if (total < 0.001) return volumeRaymarch(position.xy);+ return result / total;+#endif+}+)HLSL";+}++std::string SdlHazardCloudPixelShader(bool composite)+{+ return cloudShader(composite ? 1 : 0);+}++std::string SdlHazardCloudCacheShader(bool lighting)+{+ return cloudShader(lighting ? 3 : 2);+}++std::string SdlHazardCloudHeatShader()+{+ return cloudShader(4);+}diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudShader.h b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudShader.hnew file mode 100644index 000000000..4f9ffa389--- /dev/null+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudShader.h@@ -0,0 +1,40 @@+// Shared GPU material for preview and production hazard clouds.+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.+#ifndef SDL_HAZARD_CLOUD_SHADER_H+#define SDL_HAZARD_CLOUD_SHADER_H++#include <string>++// Matches the fragment shader's b0 exactly; all matrices retain the renderer's+// row-major convention. The preview and game use the same constant contract.+struct SdlHazardCloudUniforms {+ float WorldFromClip[16];+ float CameraPosition[4];+ float Viewport[4]; // origin including half pixel, width, height+ float Scene[4]; // inverse target size, depth available, seconds+ float Field0[4]; // world centre XYZ, horizontal radius+ float Field1[4];+ float Shape0[4]; // half height, density gain, palette, formation+ float Shape1[4];+ float Footprints[4]; // field 0/1 fringe beyond hazard radius, reserved ZW+ float Source0[4]; // release, outward travel, dissipation, source age+ float Source1[4];+ float Settings[4]; // active fields, nuclear heat pixels, enabled, maximum steps+ float Interaction[4]; // world origin XY, inverse world width/height+ float FlowSettings[4]; // enabled, maximum displacement, reserved, reserved+ float Cache0[4]; // voxel counts XYZ, atlas slice columns+ float Cache1[4];+ float CachePass[4]; // field index for cache construction, reserved YZW+ float PaletteMain[4][4]; // per-palette main RGB, overall brightness+ float PaletteShadow[4][4]; // per-palette shadow RGB, optical thickness multiplier+ float Terrain0[4]; // minimum ground Z, maximum ground Z, enabled, reserved+ float Terrain1[4];+};+static_assert(sizeof(SdlHazardCloudUniforms) == 480, "hazard volume uniform layout");++std::string SdlHazardCloudVertexShader();+std::string SdlHazardCloudPixelShader(bool composite = false);+std::string SdlHazardCloudCacheShader(bool lighting);+std::string SdlHazardCloudHeatShader();++#endifdiff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlRenderMatrix.h b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlRenderMatrix.hnew file mode 100644index 000000000..68c1a91a2--- /dev/null+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlRenderMatrix.h@@ -0,0 +1,45 @@+// Render-only row-major matrix operations. No simulation arithmetic uses this header.+#pragma once+#include <math.h>++static void multiply(const float left[16], const float right[16], float result[16])+{+ for (unsigned row = 0; row < 4; ++row) {+ for (unsigned column = 0; column < 4; ++column) {+ float sum = 0.0f;+ for (unsigned index = 0; index < 4; ++index) {+ sum += left[row * 4 + index] * right[index * 4 + column];+ }+ result[row * 4 + column] = sum;+ }+ }+}++// Visual-only inverse for reconstructing render positions from depth. Double intermediates keep+// distant camera translations stable; this does not reach simulation or replay arithmetic.+static bool render_inverse(const float source[16], float result[16])+{+ double rows[4][8];+ for (unsigned r = 0; r < 4; ++r)+ for (unsigned c = 0; c < 8; ++c)+ rows[r][c] = c < 4 ? source[r * 4 + c] : (c - 4 == r ? 1.0 : 0.0);+ for (unsigned c = 0; c < 4; ++c) {+ unsigned pivot = c;+ for (unsigned r = c + 1; r < 4; ++r)+ if (fabs(rows[r][c]) > fabs(rows[pivot][c])) pivot = r;+ if (!isfinite(rows[pivot][c]) || fabs(rows[pivot][c]) < 1e-15) return false;+ for (unsigned k = 0; k < 8; ++k) {+ const double saved = rows[c][k]; rows[c][k] = rows[pivot][k]; rows[pivot][k] = saved;+ }+ const double scale = rows[c][c];+ for (unsigned k = 0; k < 8; ++k) rows[c][k] /= scale;+ for (unsigned r = 0; r < 4; ++r) {+ if (r == c) continue;+ const double factor = rows[r][c];+ for (unsigned k = 0; k < 8; ++k) rows[r][k] -= factor * rows[c][k];+ }+ }+ for (unsigned r = 0; r < 4; ++r)+ for (unsigned c = 0; c < 4; ++c) result[r * 4 + c] = (float)rows[r][c + 4];+ return true;+}diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlResourceMirror.cpp b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlResourceMirror.cppindex b44f93dd1..9b774db5f 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlResourceMirror.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlResourceMirror.cpp@@ -366,7 +366,7 @@ SDL_GPUTexture * SdlResourceMirrors::Surface(IDirect3DSurface9 * surface, bool dSDL_zero(info);info.type = SDL_GPU_TEXTURETYPE_2D;info.format = (SDL_GPUTextureFormat)(depth ? Frame->Depth_Format() : SdlGpuFrame::Target_Format());- info.usage = depth ? SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET+ info.usage = depth ? Frame->Depth_Usage(): (SDL_GPU_TEXTUREUSAGE_COLOR_TARGET | SDL_GPU_TEXTUREUSAGE_SAMPLER);info.width = desc.Width;info.height = desc.Height;diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cppindex 441284435..adf2e774b 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp@@ -486,6 +486,7 @@ static unsigned long long s_smoothPasses = 0;W3DDisplay::~W3DDisplay(){+ W3DParticleSystemManager::releaseCloudResources();// R1: how each captured model was treated per tick, for the snap rules' tuning.{const unsigned long long *counts = SmoothMotion_Counts();@@ -692,6 +693,7 @@ void Reset_D3D_Device(bool active){if (TheDisplay && WW3D::Is_Initted() && !TheDisplay->getWindowed()){+ W3DParticleSystemManager::releaseCloudResources();// On Windows nothing owns the display exclusively under either renderer, so leaving loses no// device: the window covering the monitor goes, and comes back with the game.#if defined(_WIN32)@@ -877,6 +879,7 @@ Bool W3DDisplay::setDisplayMode( UnsignedInt xres, UnsignedInt yres, UnsignedInt// would stay on a window covering the display.//const Bool wasWindowed = getWindowed();+ W3DParticleSystemManager::releaseCloudResources();const Int wasMode = wasWindowed? ( ApplicationIsBorderless ? WINDOW_MODE_BORDERLESS : WINDOW_MODE_WINDOWED ): WINDOW_MODE_FULLSCREEN;diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cppindex d9d5b4dce..e26381c8e 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp@@ -51,6 +51,17 @@#include "GameClient/ObserverCamera.h"#include <algorithm>#include <map>+#if defined(__linux__)+#include "Common/ThingTemplate.h"+#include "GameClient/Drawable.h"+#include "Platform/HazardCloudPolicy.h"+#include "Platform/SdlHazardCloud.h"+#include <array>+#include <memory>+#include <cmath>+#include <algorithm>+#include <tuple>+#endif#ifdef _INTERNAL// for occasional debugging...@@ -686,11 +697,32 @@ struct FieldKey{const ParticleSystemTemplate *tmpl;Int x, y;+#if defined(__linux__)+ Int z;+ Int palette;+ ObjectID owner;+#endifbool operator<( const FieldKey &o ) const{+#if defined(__linux__)+ // The initial nuke emitter and its periodic radiation pulses describe+ // one hazard. Keep its age/cache when the emitter template changes.+ const bool bound = palette >= 0 && owner != INVALID_ID;+ const bool otherBound = o.palette >= 0 && o.owner != INVALID_ID;+ if (bound != otherBound) return bound < otherBound;+ if (bound) {+ if (owner != o.owner) return owner < o.owner;+ return palette < o.palette;+ }+#endifif (tmpl != o.tmpl) return tmpl < o.tmpl;if (x != o.x) return x < o.x;+#if defined(__linux__)+ if (y != o.y) return y < o.y;+ return z < o.z;+#elsereturn y < o.y;+#endif}};@@ -699,6 +731,12 @@ struct FieldKeystruct FieldState{Int born; ///< logic frame it was first seen+#if defined(__linux__)+ Int visualBorn; ///< formation age survives fog fade changes+ Real cloudShown, cloudFormation, cloudGoneDensity, cloudGoneFormation, cloudRevealFrom;+ Int cloudGoneAt, cloudRevealAt;+ Int cloudDieFrame; ///< owner's LifetimeUpdate die frame at the last sync point, or -1+#endifInt seen; ///< logic frame a system was last seen at itObjectID object; ///< the object whose life it fades with, or INVALID_IDInt gone; ///< logic frame it began going out (fog, or its object gone), or -1@@ -720,6 +758,12 @@ static const Real FIELD_STACK = 2.5f; ///< puddles' worth of cover a spotstatic const Real FIELD_SATURATE = 0.6f; ///< share of the weakest channel taken out of the colourstatic std::map<FieldKey, FieldState> s_fieldStates;+#if defined(__linux__)+struct FieldSystemOwner { ObjectID object; unsigned pass; };+static std::map<ParticleSystemID, FieldSystemOwner> s_fieldSystemOwners;+static unsigned s_fieldCollectionPass = 0;+#endif+static Bool s_fieldSkipNextFadeIn = FALSE;/** One puddle of this frame's fields, before it is laid. */struct FieldPuddle@@ -758,7 +802,11 @@ static std::vector<FieldDraw> s_fieldDraws;static std::vector<FieldBounds> s_fieldBounds; ///< one a field draw, in their order/** The CLEANUP_HAZARD object with a LifetimeUpdate standing on a field's centre, if there is one. */+#if defined(__linux__)+static ObjectID findFieldObject( const Coord3D ¢re, Int palette )+#elsestatic ObjectID findFieldObject( const Coord3D ¢re )+#endif{static NameKeyType key_LifetimeUpdate = NAMEKEY( "LifetimeUpdate" );ObjectID found = INVALID_ID;@@ -767,10 +815,24 @@ static ObjectID findFieldObject( const Coord3D ¢re ){if (!obj->isKindOf( KINDOF_CLEANUP_HAZARD ))continue;+#if defined(__linux__)+ if (obj->isDestroyed() || obj->isEffectivelyDead())+ continue;+ if (palette >= 0 && HazardCloudPolicy::paletteForOwner(obj->getTemplate()->getName().str()) != palette)+ continue;+#endifconst Coord3D *pos = obj->getPosition();+#if defined(__linux__)+ if (WWMath::Fabs(pos->z - centre.z) > FIELD_OBJECT_REACH)+ continue;+#endifconst Real dx = pos->x - centre.x, dy = pos->y - centre.y;const Real d = dx * dx + dy * dy;+#if defined(__linux__)+ if ((d < best || (found == INVALID_ID && d <= best)) && obj->findUpdateModule( key_LifetimeUpdate ) != NULL)+#elseif (d <= best && obj->findUpdateModule( key_LifetimeUpdate ) != NULL)+#endif{best = d;found = obj->getID();@@ -795,7 +857,13 @@ static inline Real midValue( const GameClientRandomVariable &v )static Real fieldFade( FieldState &state, Int now ){static NameKeyType key_LifetimeUpdate = NAMEKEY( "LifetimeUpdate" );+#if defined(__linux__)+ // An owner's real lifetime keeps Linux fields continuous between+ // sparse emitters. Other platforms retain their existing emitter grace period.+ Bool lost = (state.object == INVALID_ID && now - state.seen > FIELD_GRACE)+#elseBool lost = now - state.seen > FIELD_GRACE+#endif|| ThePartitionManager->getShroudStatusForPlayer( TheObserverCamera.getShroudPlayerIndex(), &state.centre ) != CELLSHROUD_CLEAR;Int remaining = state.particleEnd - now;if (!lost && state.object != INVALID_ID)@@ -831,20 +899,265 @@ static Real fieldFade( FieldState &state, Int now )return state.shown;}+#if defined(__linux__)+namespace {+// A busy battlefield has a fixed visual memory/draw budget. Fields which cannot+// be admitted keep the ordinary ground effect, including unknown mod templates.+constexpr unsigned MaxCloudLayers = 8;+constexpr std::uint64_t CloudCacheBudget = 192ull * 1024 * 1024;+struct CloudLayer {+ FieldKey key = {};+ std::unique_ptr<SdlHazardCloud::Layer> renderer;+ unsigned used = 0;+ float terrainChecked = -100;+ float terrainReach = -1;+ bool terrainValid = false;+};+std::array<CloudLayer, MaxCloudLayers> s_cloudLayers;+unsigned s_cloudPass = 0, s_cloudDraws = 0;+struct CloudWalker { Coord3D position; SdlHazardCloud::Body body; unsigned frame; };+std::map<ObjectID, CloudWalker> s_cloudWalkers;+std::vector<SdlHazardCloud::Body> s_cloudBodies;+unsigned s_cloudBodyFrame = ~0u;++bool isCloudMainPass()+{+ return !ShaderClass::Is_Backface_Culling_Inverted()+ && W3DDisplay::m_3DScene+ && W3DDisplay::m_3DScene->getCustomPassMode() == SCENE_PASS_DEFAULT;+}++bool modernCloudsEnabled()+{+ return TheGlobalData && TheGlobalData->m_cloudStyle == 1 && isCloudMainPass();+}++void releaseCloudLayers()+{+ for (auto &slot : s_cloudLayers) slot = CloudLayer{};+ s_cloudWalkers.clear();+ s_cloudBodies.clear();+ s_cloudBodyFrame = ~0u;+}++void beginCloudPass(unsigned now)+{+ if (!TheGlobalData || TheGlobalData->m_cloudStyle != 1) {+ releaseCloudLayers();+ return;+ }+ // A water reflection/custom pass must not evict main-view caches or wakes.+ if (!modernCloudsEnabled()) return;+ ++s_cloudPass;+ s_cloudDraws = 0;+}++void updateCloudBodies(unsigned now)+{+ if (s_cloudBodyFrame == now) return;+ s_cloudBodies.clear();+ for (Object *obj = TheGameLogic->getFirstObject(); obj; obj = obj->getNextObject()) {+ if (!obj->isKindOf(KINDOF_INFANTRY) || obj->isDestroyed() || obj->isEffectivelyDead()) continue;+ Drawable *draw = obj->getDrawable();+ const Coord3D &pos = *obj->getPosition();+ // Invisible infantry must not disclose themselves through a smoke wake.+ if (!draw || draw->isDrawableEffectivelyHidden() || draw->getFullyObscuredByShroud()+ || draw->getStealthLook() != STEALTHLOOK_NONE || draw->getEffectiveOpacity() < .99f+ || ThePartitionManager->getShroudStatusForPlayer(TheObserverCamera.getShroudPlayerIndex(), &pos) != CELLSHROUD_CLEAR)+ continue;+ SdlHazardCloud::Body body = {};+ body.x = pos.x; body.y = pos.y; body.z = pos.z;+ body.radius = std::clamp(obj->getGeometryInfo().getBoundingCircleRadius(), 1.f, 12.f);+ body.height = std::clamp(obj->getGeometryInfo().getMaxHeightAbovePosition(), 4.f, 30.f);+ auto old = s_cloudWalkers.find(obj->getID());+ if (old != s_cloudWalkers.end() && now > old->second.frame && now - old->second.frame <= LOGICFRAMES_PER_SECOND / 2) {+ const float dt = float(now - old->second.frame) / LOGICFRAMES_PER_SECOND;+ body.vx = (pos.x - old->second.position.x) / dt;+ body.vy = (pos.y - old->second.position.y) / dt;+ if (body.vx * body.vx + body.vy * body.vy > 100.f * 100.f) body.vx = body.vy = 0;+ }+ s_cloudWalkers[obj->getID()] = {pos, body, now};+ s_cloudBodies.push_back(body);+ }+ for (auto it = s_cloudWalkers.begin(); it != s_cloudWalkers.end();) {+ if (it->second.frame != now) it = s_cloudWalkers.erase(it); else ++it;+ }+ s_cloudBodyFrame = now;+}++bool updateCloudTerrain(CloudLayer &slot, const SdlHazardCloud::FieldState &field, bool onGround)+{+ if (!onGround) { slot.renderer->setTerrain(0, nullptr); return true; }+ constexpr unsigned side = SdlHazardCloud::TerrainGridSide;+ std::array<float, side * side> heights;+ const float reach = field.radius + field.fringe + 18.f;+ float low = field.ground.z, high = field.ground.z;+ for (unsigned y = 0; y < side; ++y) for (unsigned x = 0; x < side; ++x) {+ const float dx = -reach + 2 * reach * x / (side - 1), dy = -reach + 2 * reach * y / (side - 1);+ const float z = TheTerrainRenderObject->getHeightMapHeight(field.ground.x + dx, field.ground.y + dy, NULL);+ if (!std::isfinite(z)) return false;+ heights[y * side + x] = z;+ low = std::min(low, z); high = std::max(high, z);+ }+ slot.renderer->setTerrain(0, high - low > .001f ? heights.data() : nullptr);+ return true;+}++bool drawModernCloud(const FieldKey &key, FieldState &state, float fade, float seconds, int now)+{+ 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);+ SdlHazardCloud::FieldState field = {};+ field.ground = state.centre;+ const float ground = TheTerrainRenderObject->getHeightMapHeight(state.centre.x, state.centre.y, NULL);+ const bool onGround = state.centre.z - ground < FIELD_ON_GROUND;+ if (onGround) field.ground.z = ground;+ field.radius = state.radius;+ field.height = 18.61f; // Approved infantry-height cloud from the shared preview.+ field.palette = float(key.palette);+ field.fringe = HazardCloudPolicy::visualFringe(state.size);+ field.formation = buildup.formation;+ field.release = buildup.release;+ const float endFade = std::clamp(left / std::max(.1f, std::min(3.f, lifetime * .25f)), 0.f, 1.f);+ field.density = buildup.density * endFade * state.stealth;+ if (state.gone >= 0) {+ if (state.cloudGoneAt != state.gone) {+ state.cloudGoneAt = state.gone;+ state.cloudGoneDensity = state.cloudShown;+ state.cloudGoneFormation = state.cloudFormation;+ }+ // Do not let a young cloud keep thickening after it becomes hidden or+ // its owner is removed. Fade from the last actually shown appearance.+ field.density = state.cloudGoneDensity * std::clamp(1.f - float(now - state.gone) / FIELD_FADE_GONE, 0.f, 1.f);+ field.formation = state.cloudGoneFormation;+ field.release = 0;+ } else {+ if (state.cloudGoneAt >= 0) {+ state.cloudRevealAt = now;+ state.cloudRevealFrom = state.cloudShown;+ state.cloudGoneAt = -1;+ }+ const float reveal = std::clamp(float(now - state.cloudRevealAt) / FIELD_FADE_IN, 0.f, 1.f);+ field.density = state.cloudRevealFrom + (field.density - state.cloudRevealFrom) * reveal;+ }+ state.cloudShown = field.density;+ 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;+ // 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;+ CloudLayer *slot = nullptr;+ for (auto &candidate : s_cloudLayers)+ if (candidate.renderer && !(key < candidate.key) && !(candidate.key < key)) { slot = &candidate; break; }+ if (!slot) {+ for (auto &candidate : s_cloudLayers) if (!candidate.renderer) { slot = &candidate; break; }+ if (!slot) for (auto &candidate : s_cloudLayers)+ if (candidate.used != s_cloudPass && (!slot || candidate.used < slot->used)) slot = &candidate;+ if (!slot) return false;+ *slot = CloudLayer{};+ slot->key = key;+ }+ const auto wanted = SdlHazardCloud::Layer::estimateCacheBytes(&field, 1);+ std::uint64_t used = 0;+ for (const auto &other : s_cloudLayers) if (&other != slot && other.renderer) used += other.renderer->estimatedCacheBytes();+ if (wanted > CloudCacheBudget) return false;+ while (used > CloudCacheBudget - wanted) {+ CloudLayer *oldest = nullptr;+ for (auto &other : s_cloudLayers)+ if (&other != slot && other.renderer && other.used != s_cloudPass+ && (!oldest || other.used < oldest->used)) oldest = &other;+ if (!oldest) return false;+ used -= oldest->renderer->estimatedCacheBytes();+ *oldest = CloudLayer{};+ }+ if (!slot->renderer) {+ slot->renderer.reset(new SdlHazardCloud::Layer);+ if (!slot->renderer->initialize()) { slot->renderer.reset(); return false; }+ const float reach = field.radius + field.fringe + 24.f;+ slot->renderer->setFlowDomain(field.ground.x - reach, field.ground.y - reach, field.ground.x + reach, field.ground.y + reach);+ }+ slot->renderer->setFields(&field, 1);+ if (seconds < slot->terrainChecked || seconds - slot->terrainChecked >= 1.f+ || slot->terrainReach != field.radius + field.fringe) {+ slot->terrainValid = updateCloudTerrain(*slot, field, onGround);+ slot->terrainChecked = seconds;+ slot->terrainReach = field.radius + field.fringe;+ }+ if (!slot->terrainValid) return false;+ std::array<SdlHazardCloud::Body, 32> bodies;+ unsigned count = 0;+ for (const auto &body : s_cloudBodies) {+ const float dx = body.x - field.ground.x, dy = body.y - field.ground.y;+ const float reach = field.radius + field.fringe + body.radius;+ const float localGround = onGround ? TheTerrainRenderObject->getHeightMapHeight(body.x, body.y, NULL) : field.ground.z;+ if (dx * dx + dy * dy <= reach * reach && std::fabs(body.z - localGround) < field.height)+ if (count < bodies.size()) bodies[count++] = body;+ }+ slot->renderer->setBodies(bodies.data(), count);+ slot->renderer->update(seconds);+ slot->used = s_cloudPass;+ if (!slot->renderer->render()) return false;+ ++s_cloudDraws;+ return true;+}+} // namespace+#endif+/** This frame's fields from their systems, and each one's fade, at the sync point before the render:* finding a field's object, its life and the fog over it read the logic (LOGIC-THREAD.md phase 3).* `systems` is every isGroundField system in list order, empty ones too. */static void updateGroundFields( const std::vector<ParticleSystem *> &systems ){const Int now = (Int)TheGameLogic->getFrame();+ // An explicit cache refresh may need an immediate comparison while paused.+ // Consume this once, even if this sync point has no fields, so later gameplay+ // emitters always retain the normal fade-in unless explicitly refreshed again.+ const Bool skipFadeIn = s_fieldSkipNextFadeIn;+ s_fieldSkipNextFadeIn = FALSE;+#if defined(__linux__)+ ++s_fieldCollectionPass;+ std::map<std::tuple<Int, Int, Int, Int>, ObjectID> fieldOwners;+#endif// where the fields are this frame, and what each one looks likefor (size_t f = 0; f < systems.size(); ++f){ParticleSystem *sys = systems[ f ];+#if defined(__linux__)+ if (sys->getInitialDelayLeft() > 0) continue;+#endif+Coord3D pos;sys->getPosition( &pos );+#if defined(__linux__)+ const Int palette = HazardCloudPolicy::paletteForTemplate(sys->getTemplate()->getName().str());+ const auto ownerKey = std::make_tuple(REAL_TO_INT_FLOOR(pos.x + .5f), REAL_TO_INT_FLOOR(pos.y + .5f),+ REAL_TO_INT_FLOOR(pos.z + .5f), palette);+ ObjectID owner = INVALID_ID;+ auto binding = s_fieldSystemOwners.find(sys->getSystemID());+ if (palette >= 0 && binding != s_fieldSystemOwners.end()) owner = binding->second.object;+ if (owner == INVALID_ID) {+ auto ownerEntry = fieldOwners.find(ownerKey);+ if (ownerEntry == fieldOwners.end()) ownerEntry = fieldOwners.emplace(ownerKey, findFieldObject(pos, palette)).first;+ owner = ownerEntry->second;+ }+ if (palette >= 0) {+ // A surviving emitter retains its hazard identity after cleanup.+ // Otherwise its last particles would create a fresh, growing cloud.+ s_fieldSystemOwners[sys->getSystemID()] = {owner, s_fieldCollectionPass};+ }+ FieldKey key = { sys->getTemplate(), REAL_TO_INT_FLOOR( pos.x + 0.5f ), REAL_TO_INT_FLOOR( pos.y + 0.5f ),+ REAL_TO_INT_FLOOR(pos.z + .5f), palette, owner };+#elseFieldKey key = { sys->getTemplate(), REAL_TO_INT_FLOOR( pos.x + 0.5f ), REAL_TO_INT_FLOOR( pos.y + 0.5f ) };+#endifconst ParticleSystemInfo::EmissionVolumeType volume = sys->getEmisionVolumeType();const Real radius = volume == ParticleSystemInfo::SPHERE ? sys->m_emissionVolume.sphere.radius: (volume == ParticleSystemInfo::CYLINDER ? sys->m_emissionVolume.cylinder.radius : 0.0f);@@ -854,14 +1167,40 @@ static void updateGroundFields( const std::vector<ParticleSystem *> &systems )life = WWMath::Max( life, (Int)p->getLifetimeLeft() );std::map<FieldKey, FieldState>::iterator st = s_fieldStates.find( key );+#if defined(__linux__)+ // A blast FX can precede its cleanup object within the same tick. Adopt+ // that unbound visual when the owner arrives rather than drawing it twice.+ if (st == s_fieldStates.end() && palette >= 0 && owner != INVALID_ID) {+ for (auto orphan = s_fieldStates.begin(); orphan != s_fieldStates.end(); ++orphan) {+ const FieldKey &old = orphan->first;+ if (old.owner == INVALID_ID && old.palette == palette && old.x == key.x && old.y == key.y && old.z == key.z) {+ FieldState adopted = orphan->second;+ adopted.object = owner;+ s_fieldStates.erase(orphan);+ st = s_fieldStates.emplace(key, adopted).first;+ break;+ }+ }+ }+#endifif (st == s_fieldStates.end() || st->second.seen != now){if (st == s_fieldStates.end()){- FieldState fresh;- fresh.born = now;+ FieldState fresh = {};+ fresh.born = now - (skipFadeIn ? FIELD_FADE_IN : 0);+#if defined(__linux__)+ fresh.visualBorn = fresh.born;+ fresh.cloudGoneAt = -1;+ fresh.cloudRevealAt = now - FIELD_FADE_IN;+ fresh.cloudDieFrame = -1;+#endiffresh.seen = now;+#if defined(__linux__)+ fresh.object = owner;+#elsefresh.object = findFieldObject( pos );+#endiffresh.gone = -1;fresh.goneFade = 0.0f;fresh.shown = 0.0f;@@ -899,6 +1238,12 @@ static void updateGroundFields( const std::vector<ParticleSystem *> &systems )}st->second.stealth = sys->getStealthFade();}+#if defined(__linux__)+ for (auto binding = s_fieldSystemOwners.begin(); binding != s_fieldSystemOwners.end();) {+ if (binding->second.pass != s_fieldCollectionPass) binding = s_fieldSystemOwners.erase(binding);+ else ++binding;+ }+#endiffor (std::map<FieldKey, FieldState>::iterator st = s_fieldStates.begin(); st != s_fieldStates.end(); ){@@ -916,6 +1261,21 @@ static void updateGroundFields( const std::vector<ParticleSystem *> &systems )}++st;}+#if defined(__linux__)+ // The hazard clouds' owners' lifetimes and the infantry wading through them read the logic, so+ // they are taken here with the rest, not in the render beside the tick.+ static NameKeyType key_cloudLife = NAMEKEY("LifetimeUpdate");+ for (std::map<FieldKey, FieldState>::iterator st = s_fieldStates.begin(); st != s_fieldStates.end(); ++st) {+ FieldState &state = st->second;+ state.cloudDieFrame = -1;+ if (state.object == INVALID_ID || st->first.palette < 0) continue;+ Object *obj = TheGameLogic->findObjectByID(state.object);+ if (obj) if (auto *life = static_cast<LifetimeUpdate *>(obj->findUpdateModule(key_cloudLife)))+ state.cloudDieFrame = Int(life->getDieFrame());+ }+ if (TheGlobalData && TheGlobalData->m_cloudStyle == 1)+ updateCloudBodies((unsigned)now);+#endif}/** Lays the fields updateGroundFields found on the terrain into the field buffers; drawGroundFields@@ -927,6 +1287,9 @@ static Int collectGroundFields( const AABoxClass &view )const Real seconds = ((Real)now + (TheSmoothMotionActive ? TheSmoothMotionAlpha : 0.0f)) / LOGICFRAMES_PER_SECOND;s_fieldPuddles.clear();s_fieldDraws.clear();+#if defined(__linux__)+ beginCloudPass(now);+#endifInt laid = 0;for (std::map<FieldKey, FieldState>::iterator st = s_fieldStates.begin(); st != s_fieldStates.end(); ++st)@@ -941,10 +1304,30 @@ static Int collectGroundFields( const AABoxClass &view )// a field off screen is still collected, as its puddles dim the ones it overlaps on screenconst Real size = state.size;- const Real reach = state.radius + size;+ Real reach = state.radius + size;+ Bool groundVolume = FALSE;+#if defined(__linux__)+ if (modernCloudsEnabled() && key.palette >= 0) {+ reach = state.radius + HazardCloudPolicy::visualFringe(size) + 18.f;+ groundVolume = TRUE;+ }+#endifconst Bool visible = WWMath::Fabs( state.centre.x - view.Center.X ) <= view.Extent.X + reach&& WWMath::Fabs( state.centre.y - view.Center.Y ) <= view.Extent.Y + reach- && WWMath::Fabs( state.centre.z - view.Center.Z ) <= view.Extent.Z + reach;+ && (groundVolume || WWMath::Fabs( state.centre.z - view.Center.Z ) <= view.Extent.Z + reach);+#if defined(__linux__)+ if (visible) {+ if (drawModernCloud(key, state, fade, seconds, now)) {+ // Preserve the client's existing area-effect particle ceiling even+ // though the replacement does not build the old puddle geometry.+ const Real spread = state.radius / size;+ laid += WWMath::Clamp_Int((Int)ceilf(FIELD_COVER * spread * spread), 1, FIELD_MAX_PUDDLES);+ if (state.color.red >= state.color.green && state.color.red >= state.color.blue)+ laid += WWMath::Clamp_Int((Int)(state.radius / FIELD_BUBBLE_SPACING), 1, FIELD_MAX_BUBBLES);+ continue;+ }+ }+#endifFieldBatch batch;if (!particlePresetShader( state.shader, &batch.glow ))@@ -1244,6 +1627,7 @@ W3DParticleSystemManager::W3DParticleSystemManager()W3DParticleSystemManager::~W3DParticleSystemManager(){+ releaseCloudResources();delete m_pointGroup;// W3DDisplay::m_3DScene->Remove_Render_Object( m_streakLine );@@ -1270,7 +1654,27 @@ void W3DParticleSystemManager::reset()m_frameView.clear();m_fieldSystems.clear();m_sunMapCasters.clear();- s_fieldStates.clear(); // the object IDs it holds belong to the game that ended+ invalidateGroundFields(); // the object IDs it holds belong to the game that ended+}++void W3DParticleSystemManager::invalidateGroundFields(bool fadeIn)+{+ releaseCloudResources();+ // Ground draw buffers are rebuilt by the next collect/draw; their texture+ // references are already released at the end of each draw. Only this map+ // persists the footprint after an emitter is removed or changes appearance.+ s_fieldStates.clear();+#if defined(__linux__)+ s_fieldSystemOwners.clear();+#endif+ s_fieldSkipNextFadeIn = !fadeIn;+}++void W3DParticleSystemManager::releaseCloudResources()+{+#if defined(__linux__)+ releaseCloudLayers();+#endif}/** LOGIC-THREAD.md phase 3. A system's stealth fade asks its object's drawable, and a field asks fordiff --git a/GeneralsMD/Code/Libraries/Include/Platform/HazardCloudPolicy.h b/GeneralsMD/Code/Libraries/Include/Platform/HazardCloudPolicy.hnew file mode 100644index 000000000..893d3991a--- /dev/null+++ b/GeneralsMD/Code/Libraries/Include/Platform/HazardCloudPolicy.h@@ -0,0 +1,116 @@+#pragma once++#include <cmath>++// Client-only recognition and shaping. Gameplay supplies the radius and lifetime;+// an unrecognized effect remains on its existing particle path.+namespace HazardCloudPolicy {++inline bool sameName(const char *a, const char *b)+{+ if (!a || !b) return false;+ while (*a && *b) {+ unsigned char ac = static_cast<unsigned char>(*a++);+ unsigned char bc = static_cast<unsigned char>(*b++);+ if (ac >= 'A' && ac <= 'Z') ac += 'a' - 'A';+ if (bc >= 'A' && bc <= 'Z') bc += 'a' - 'A';+ if (ac != bc) return false;+ }+ return *a == *b;+}++// Palette indices are shared with the approved preview: toxin, nuclear, beta, gamma.+inline int paletteForTemplate(const char *name)+{+ static const char *const names[][3] = {+ {"PoisonFieldSmall", "PoisonFieldMedium", "PoisonFieldLarge"},+ {"RadiationFieldSmall", "RadiationFieldMedium", "RadiationFieldLarge"},+ {"AnthraxFieldSmall", "AnthraxFieldMedium", "AnthraxFieldLarge"},+ {"GC_Chem_AnthraxGammaFieldSmall", "GC_Chem_AnthraxFieldGammaMedium",+ "GC_Chem_AnthraxFieldGammaLarge"}+ };+ for (int palette = 0; palette < 4; ++palette)+ for (int size = 0; size < 3; ++size)+ if (sameName(name, names[palette][size])) return palette;+ return sameName(name, "NukeRadiationInitial") ? 1 : -1;+}++// The caller must additionally require CLEANUP_HAZARD and a live LifetimeUpdate.+// Owner names are object templates, not the particle or weapon names.+inline int paletteForOwner(const char *name)+{+ static const struct { const char *name; int palette; } owners[] = {+ {"PoisonFieldSmall", 0}, {"PoisonFieldMedium", 0}, {"PoisonFieldLarge", 0},+ {"RadiationFieldSmall", 1}, {"RadiationFieldMedium", 1}, {"RadiationFieldLarge", 1},+ {"NukeRadiationFieldWeapon", 1}, {"Nuke_RadiationFieldSmall", 1},+ {"PoisonFieldUpgradedSmall", 2}, {"PoisonFieldUpgradedMedium", 2},+ {"PoisonFieldUpgradedLarge", 2}, {"PoisonFieldAnthraxBomb", 2},+ {"Chem_PoisonFieldGammaSmall", 3}, {"Chem_PoisonFieldGammaMedium", 3},+ {"Chem_PoisonFieldGammaLarge", 3}, {"GC_Chem_PoisonFieldGammaSmall", 3},+ {"GC_Chem_PoisonFieldGammaMedium", 3}, {"GC_Chem_PoisonFieldGammaLarge", 3},+ {"PoisonFieldAnthraxGammaBomb", 3}+ };+ for (const auto &owner : owners)+ if (sameName(name, owner.name)) return owner.palette;+ return -1;+}++inline float smoothProgress(float age, float duration)+{+ const float progress = age <= 0.0f ? 0.0f : age >= duration ? 1.0f : age / duration;+ return progress * progress * (3.0f - 2.0f * progress);+}++struct Buildup {+ float formation; // Radial buildup for toxin; always full footprint for nuclear.+ float density; // Multiply by the runtime's existing life/visibility fade.+ float release;+};++inline Buildup visualBuildup(int palette, bool largeNuclear, float ageSeconds,+ float lifetimeSeconds)+{+ const bool nuclear = palette == 1;+ const Buildup hidden = {nuclear ? 1.0f : 0.0f, 0.0f, 0.0f};+ if (palette < 0 || palette > 3 || !std::isfinite(ageSeconds)+ || !std::isfinite(lifetimeSeconds) || ageSeconds < 0.0f || lifetimeSeconds <= 0.0f)+ return hidden;+ if (ageSeconds >= lifetimeSeconds) return {1.0f, 0.0f, 0.0f};++ // Small radiation fields live only a few seconds. Never let a decorative+ // buildup spend most of their actual damaging lifetime nearly invisible.+ const float nominal = nuclear && largeNuclear ? 6.0f : 3.0f;+ const float quarterLife = lifetimeSeconds * 0.25f;+ const float ramp = quarterLife < nominal ? quarterLife : nominal;+ if (!(ramp > 0.0f)) return hidden;+ const float progress = smoothProgress(ageSeconds, ramp);+ const float densityRamp = ramp < 0.6f ? ramp : 0.6f;+ return {nuclear ? 1.0f : progress,+ nuclear ? progress : smoothProgress(ageSeconds, densityRamp),+ ageSeconds < ramp ? 1.0f - 0.65f * progress : 0.0f};+}++inline float visualFringe(float halfLifePuddleSize)+{+ if (!std::isfinite(halfLifePuddleSize) || halfLifePuddleSize < 0.0f) return 0.0f;+ const float fringe = std::sqrt(2.0f) * 1.04f * halfLifePuddleSize;+ return std::isfinite(fringe) ? fringe : 0.0f;+}++inline bool validField(float x, float y, float z, float radius, float height,+ float density, float formation, float fringe, int palette)+{+ if (palette < 0 || palette > 3 || !std::isfinite(x) || !std::isfinite(y)+ || !std::isfinite(z) || !std::isfinite(radius) || !std::isfinite(height)+ || !std::isfinite(density) || !std::isfinite(formation) || !std::isfinite(fringe)+ || radius <= 0.0f || height <= 0.0f || density < 0.0f || density > 1.0f+ || formation < 0.0f || formation > 1.0f || fringe < 0.0f)+ return false;+ const float reach = radius + fringe;+ // Guard operations used by support bounds and radial distance evaluation.+ return std::isfinite(reach * reach) && std::isfinite(x - reach)+ && std::isfinite(x + reach) && std::isfinite(y - reach)+ && std::isfinite(y + reach) && std::isfinite(z + height * 2.6f);+}++} // namespace HazardCloudPolicydiff --git a/GeneralsMD/Code/Libraries/Include/Platform/SdlHazardCloud.h b/GeneralsMD/Code/Libraries/Include/Platform/SdlHazardCloud.hnew file mode 100644index 000000000..10a5eef61--- /dev/null+++ b/GeneralsMD/Code/Libraries/Include/Platform/SdlHazardCloud.h@@ -0,0 +1,90 @@+// Shared visual-only hazard cloud renderer for the Linux game and cloud preview.+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.+#pragma once++#include "Lib/BaseType.h"+#include "Platform/SdlHazardCloudFlow.h"+#include <cstdint>++namespace SdlHazardCloud {++constexpr unsigned TerrainGridSide = 129;++struct FieldState {+ Coord3D ground;+ float radius;+ float height; // Full world-space height above the sampled ground.+ float density;+ float palette; // 0 toxin, 1 radiation, 2 anthrax blue, 3 gamma purple.+ float formation;+ float release;+ float fringe;+};+using Body = SdlHazardCloudFlow::Body;+struct Color { float r, g, b; };+struct Palette {+ Color main, shadow;+ float brightness;+ // 0 retains full optical density; 1 makes only the smoke invisible.+ // Formation, footprint, wakes, heat and embers remain independent.+ float transparency = 0.0f;+};++// Stable user-approved palette, independent of preview files or game options.+const Palette &defaultPalette(unsigned index);++// Main render thread only. Owns up to two fields with independent density,+// lighting and infantry-wake history. Pipelines and transient scene targets are+// shared by all layers on the same device. No scene object is registered.+// Without a terrain grid, ground support is the field's flat ground/deck plane.+// The support model has one height per XY position. The production adapter uses+// terrain samples or an elevated plane; cliffs and crossing decks have no+// dedicated validation fixture or automatic geometry fallback yet.+class Layer {+public:+ Layer();+ ~Layer();+ Layer(const Layer &) = delete;+ Layer &operator=(const Layer &) = delete;++ bool initialize();+ void setFields(const FieldState *fields, unsigned count);+ void setBodies(const Body *bodies, unsigned count); // At most 32.+ void setFlowDomain(float minX, float minY, float maxX, float maxY);+ // Copies TerrainGridSide squared world heights, row-major with increasing Y.+ // Grid nodes span ground.xy +/- (radius + fringe + 18 world units), matching+ // this field's cache domain. Refresh after changing that domain or terrain.+ // nullptr disables terrain sampling for this field and restores its plane.+ void setTerrain(unsigned fieldIndex, const float *heights);+ void setPalette(unsigned index, const Palette &palette);+ void setInteractionEnabled(bool enabled);+ bool isInteractionEnabled() const;+ void setHeatEnabled(bool enabled);+ bool isHeatEnabled() const;+ void update(float timeSeconds);+ void reset(); // Clears source/wake history, retaining fields and allocations.++ // Call only in the main scene after opaque geometry/water. False means no+ // cloud scene draw was recorded, so the caller may draw classic effects.+ bool render();+ bool valid() const;+ unsigned activeBodies() const;+ float maxDisturbance() const;+ unsigned interactionUploads() const;+ unsigned renderedFrames() const;++ // Density + lighting atlas allocations and local flow texture. Excludes+ // shared screen scratch targets; estimate before admitting a new layer.+ static std::uint64_t estimateCacheBytes(const FieldState *fields, unsigned count);+ std::uint64_t estimatedCacheBytes() const;++ // Release before the display/device is destroyed. Repeated calls are safe;+ // releasing one layer leaves all other layers' resources and history intact.+ void shutdown();++private:+ struct Impl;+ Impl *impl;+};++} // namespace SdlHazardClouddiff --git a/GeneralsMD/Code/Libraries/Include/Platform/SdlHazardCloudFlow.h b/GeneralsMD/Code/Libraries/Include/Platform/SdlHazardCloudFlow.hnew file mode 100644index 000000000..79cb4a446--- /dev/null+++ b/GeneralsMD/Code/Libraries/Include/Platform/SdlHazardCloudFlow.h@@ -0,0 +1,60 @@+// Persistent planar smoke transport for SDL hazard clouds.+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.+#pragma once++namespace SdlHazardCloudFlow {++// World coordinates and world units per second. The caller supplies the current+// velocity, not displacement since the last rendered frame. Body order need not+// be stable. Z and height retain body geometry; the flow simulation is planar.+struct Body {+ float x, y, z;+ float vx, vy;+ float radius, height;+};++// Each field owns independent grids and integration history. No graphics device+// or game-state dependency is needed to create, advance, or destroy a flow.+class Flow {+public:+ Flow();+ ~Flow();+ Flow(const Flow &) = delete;+ Flow &operator=(const Flow &) = delete;++ // Covers the texture edges, with cells sampled at their centres. Setting a+ // domain resets all flow. reset() preserves the domain and clears history.+ void setDomain(float minX, float minY, float maxX, float maxY);+ void reset();++ // Fixed 1/60-second steps with a capped catch-up interval. Empty input heals+ // the existing wake; zero delta freezes it. Invalid bodies are ignored and+ // reported by valid(); infantry velocities above the limit are warps.+ // At most the first 32 supplied bodies are considered.+ void step(float deltaSeconds, const Body *bodies, unsigned count);++ unsigned width() const;+ unsigned height() const;+ float domainMinX() const;+ float domainMinY() const;+ float domainMaxX() const;+ float domainMaxY() const;++ // Row-major RGBA32F, X varies fastest. R/G contain accumulated world+ // displacement; sample smoke noise at world.xy - RG. B/A stay zero so flow+ // does not carve holes or rings. The shader applies height falloff. Values+ // stay valid until this instance's next step/reset/setDomain or destruction.+ // Displacement magnitude is bounded to 18 units.+ const float *data() const;++ // Render diagnostics only, never authoritative gameplay state.+ bool valid() const;+ float maxDisturbance() const; // Displacement magnitude divided by 18 units.+ unsigned activeBodies() const;++private:+ struct Impl;+ Impl *impl;+};++} // namespace SdlHazardCloudFlowdiff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cppindex 6c545abe9..7ff3ea5b1 100644--- a/GeneralsMD/Code/Tests/test_gameengine.cpp+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp@@ -15127,6 +15127,39 @@ TEST(order_lines_are_a_live_check_box_that_starts_on)TheWritableGlobalData = saved;}+TEST(cloud_style_defaults_to_volumetric_and_preserves_an_explicit_classic_choice)+{+ GlobalData *saved = TheWritableGlobalData;+ GlobalData *scratch = NEW GlobalData;+ TheWritableGlobalData = scratch;+ const OptionDef *cloud = findOptionDef("CloudStyle");+ CHECK(cloud != NULL);+ if (cloud) {+ UserPreferences pref;+ CHECK_EQ(scratch->m_cloudStyle, 1);+ CHECK_EQ(cloud->kind, OPTION_ENUM);+ CHECK_EQ(cloud->apply, APPLY_LIVE);+ CHECK_EQ(cloud->lo, 0);+ CHECK_EQ(cloud->hi, 1);+ CHECK_STR(cloud->widgetName, "OptionsMenu.wnd:ComboBoxCloudStyle");+ // The cloud appearance is independent of the existing smoke-shadow option.+ scratch->m_volumetricSmokeShadows = FALSE;+ loadOptionsFromPreferences(pref);+ CHECK_EQ(cloud->get(), 1);+ pref["CloudStyle"] = "0";+ loadOptionsFromPreferences(pref);+ CHECK_EQ(cloud->get(), 0);+ saveOptionsToPreferences(pref);+ CHECK_STR(pref["CloudStyle"].str(), "0");+ pref["CloudStyle"] = "1";+ loadOptionsFromPreferences(pref);+ CHECK_EQ(cloud->get(), 1);+ CHECK(!scratch->m_volumetricSmokeShadows);+ }+ delete scratch;+ TheWritableGlobalData = saved;+}+TEST(option_catalog_round_trips_every_key_through_options_ini){/* Every row has to survive the trip out to Options.ini and back, at both ends of its range.diff --git a/GeneralsMD/Code/Tests/test_hazard_cloud_policy.cpp b/GeneralsMD/Code/Tests/test_hazard_cloud_policy.cppnew file mode 100644index 000000000..ebe7857df--- /dev/null+++ b/GeneralsMD/Code/Tests/test_hazard_cloud_policy.cpp@@ -0,0 +1,145 @@+#include "test_harness.h"+#include "Platform/HazardCloudPolicy.h"++#include <initializer_list>+#include <limits>++using namespace HazardCloudPolicy;++TEST(hazard_cloud_recognizes_only_known_particle_templates)+{+ const char *const names[][3] = {+ {"PoisonFieldSmall", "PoisonFieldMedium", "PoisonFieldLarge"},+ {"RadiationFieldSmall", "RadiationFieldMedium", "RadiationFieldLarge"},+ {"AnthraxFieldSmall", "AnthraxFieldMedium", "AnthraxFieldLarge"},+ {"GC_Chem_AnthraxGammaFieldSmall", "GC_Chem_AnthraxFieldGammaMedium",+ "GC_Chem_AnthraxFieldGammaLarge"}+ };+ for (int palette = 0; palette < 4; ++palette)+ for (const char *name : names[palette]) CHECK_EQ(paletteForTemplate(name), palette);+ CHECK_EQ(paletteForTemplate("NukeRadiationInitial"), 1);+ CHECK_EQ(paletteForTemplate("poisonfieldLARGE"), 0);+ for (const char *name : {static_cast<const char *>(nullptr), "", "PoisonFieldLargeExtra", "MyRadiationFieldLarge",+ "GC_Chem_AnthraxFieldGammaSmall", "ToxinTankPuddle", "NukeMushroomStem",+ "ToxinSpray", "PoisonFieldAnthraxBomb"})+ CHECK_EQ(paletteForTemplate(name), -1);+}++TEST(hazard_cloud_matches_actual_hazard_object_names)+{+ CHECK_EQ(paletteForOwner("PoisonFieldMedium"), 0);+ CHECK_EQ(paletteForOwner("PoisonFieldUpgradedLarge"), 2);+ CHECK_EQ(paletteForOwner("PoisonFieldAnthraxBomb"), 2);+ CHECK_EQ(paletteForOwner("PoisonFieldAnthraxGammaBomb"), 3);+ CHECK_EQ(paletteForOwner("NukeRadiationFieldWeapon"), 1);+ CHECK_EQ(paletteForOwner("Nuke_RadiationFieldSmall"), 1);+ for (const char *name : {"RadiationFieldSmall", "RadiationFieldMedium", "RadiationFieldLarge"})+ CHECK_EQ(paletteForOwner(name), 1);+ for (const char *name : {"Chem_PoisonFieldGammaSmall", "Chem_PoisonFieldGammaMedium",+ "Chem_PoisonFieldGammaLarge", "GC_Chem_PoisonFieldGammaSmall",+ "GC_Chem_PoisonFieldGammaMedium", "GC_Chem_PoisonFieldGammaLarge"})+ CHECK_EQ(paletteForOwner(name), 3);+ for (const char *name : {static_cast<const char *>(nullptr), "", "NukeRadiationInitial", "AnthraxFieldLarge",+ "GC_Chem_AnthraxGammaFieldSmall", "GLAVehicleToxinTruck", "Chem_GLAScudStorm",+ "LargePoisonFieldWeapon", "PoisonFieldMediumCustom"})+ CHECK_EQ(paletteForOwner(name), -1);+}++TEST(hazard_cloud_nuclear_fades_in_across_its_full_footprint)+{+ for (float age : {0.0f, 0.1f, 1.0f, 3.0f, 6.0f, 12.0f}) {+ const Buildup nuclear = visualBuildup(1, true, age, 30.0f);+ CHECK_EQ(nuclear.formation, 1.0f);+ CHECK(nuclear.density >= 0.0f && nuclear.density <= 1.0f);+ CHECK(nuclear.release >= 0.0f && nuclear.release <= 1.0f);+ }+ CHECK_NEAR(visualBuildup(1, true, 3.0f, 30.0f).density, 0.5f, 0.00001f);+ CHECK_NEAR(visualBuildup(1, true, 3.0f, 30.0f).release, 0.675f, 0.00001f);+ CHECK_EQ(visualBuildup(1, true, 6.0f, 30.0f).density, 1.0f);+ CHECK_EQ(visualBuildup(1, true, 6.0f, 30.0f).release, 0.0f);+ CHECK_EQ(visualBuildup(1, false, 3.0f, 30.0f).density, 1.0f);+}++TEST(hazard_cloud_toxin_formation_and_release_preserve_palette_identity)+{+ for (int palette : {0, 2, 3}) {+ const Buildup beginning = visualBuildup(palette, false, 0.0f, 30.0f);+ const Buildup middle = visualBuildup(palette, false, 1.5f, 30.0f);+ const Buildup formed = visualBuildup(palette, false, 3.0f, 30.0f);+ CHECK_EQ(beginning.formation, 0.0f);+ CHECK_EQ(beginning.density, 0.0f);+ CHECK_EQ(beginning.release, 1.0f);+ CHECK_NEAR(middle.formation, 0.5f, 0.00001f);+ CHECK_EQ(middle.density, 1.0f);+ CHECK_EQ(formed.formation, 1.0f);+ CHECK_EQ(formed.density, 1.0f);+ CHECK_EQ(formed.release, 0.0f);+ CHECK_NEAR(visualBuildup(palette, true, 1.5f, 30.0f).formation,+ middle.formation, 0.00001f); // Large-nuclear flag must not slow toxin.+ }+}++TEST(hazard_cloud_short_lifetimes_have_a_visible_lingering_phase)+{+ for (float lifetime : {0.04f, 0.5f, 2.5f, 10.0f, 30.0f, 180.0f})+ for (int palette = 0; palette < 4; ++palette) {+ const Buildup formed = visualBuildup(palette, true, lifetime * 0.25f, lifetime);+ CHECK_EQ(formed.formation, 1.0f);+ CHECK_EQ(formed.density, 1.0f);+ CHECK_EQ(formed.release, 0.0f);+ CHECK_EQ(visualBuildup(palette, true, lifetime, lifetime).density, 0.0f);+ CHECK_EQ(visualBuildup(palette, true, lifetime + 1.0f, lifetime).density, 0.0f);+ }+ CHECK(visualBuildup(1, false, 0.3f, 2.5f).density > 0.4f);+}++TEST(hazard_cloud_invalid_buildup_is_hidden_and_finite)+{+ const float nan = std::numeric_limits<float>::quiet_NaN();+ const float inf = std::numeric_limits<float>::infinity();+ for (int palette : {-1, 0, 1, 4})+ for (float value : {-1.0f, nan, inf}) {+ const Buildup badAge = visualBuildup(palette, true, value, 30.0f);+ const Buildup badLife = visualBuildup(palette, true, 1.0f, value);+ CHECK_EQ(badAge.density, 0.0f);+ CHECK_EQ(badLife.density, 0.0f);+ CHECK(std::isfinite(badAge.formation));+ CHECK(std::isfinite(badLife.formation));+ }+ CHECK_EQ(visualBuildup(1, true, 0.0f, 0.0f).density, 0.0f);+ CHECK_EQ(visualBuildup(-1, true, 1.0f, 30.0f).density, 0.0f);+}++TEST(hazard_cloud_fringe_covers_original_rotated_breathing_quads)+{+ CHECK_EQ(visualFringe(0.0f), 0.0f);+ CHECK_NEAR(visualFringe(42.82f), std::sqrt(2.0f) * 1.04f * 42.82f, 0.000001f);+ CHECK(visualFringe(50.0f) > 50.0f * std::sqrt(2.0f));+ CHECK_EQ(visualFringe(-1.0f), 0.0f);+ CHECK_EQ(visualFringe(std::numeric_limits<float>::infinity()), 0.0f);+ CHECK_EQ(visualFringe(std::numeric_limits<float>::max()), 0.0f);+}++TEST(hazard_cloud_admission_rejects_invalid_values_without_changing_footprints)+{+ CHECK(validField(-100.0f, 200.0f, 30.0f, 300.0f, 18.0f, 1.0f, 1.0f, 89.0f, 2));+ CHECK(validField(0.0f, 0.0f, 0.0f, 7.5f, 18.0f, 0.0f, 0.0f, 0.0f, 3));+ const float good[] = {0.0f, 0.0f, 30.0f, 80.0f, 18.0f, 1.0f, 1.0f, 63.0f};+ for (int slot = 0; slot < 8; ++slot)+ for (float invalid : {std::numeric_limits<float>::quiet_NaN(),+ std::numeric_limits<float>::infinity()}) {+ float values[8];+ for (int i = 0; i < 8; ++i) values[i] = i == slot ? invalid : good[i];+ CHECK(!validField(values[0], values[1], values[2], values[3], values[4],+ values[5], values[6], values[7], 0));+ }+ CHECK(!validField(0, 0, 0, 0, 18, 1, 1, 0, 0));+ CHECK(!validField(0, 0, 0, 80, 0, 1, 1, 0, 0));+ CHECK(!validField(0, 0, 0, 80, 18, -0.1f, 1, 0, 0));+ CHECK(!validField(0, 0, 0, 80, 18, 1.1f, 1, 0, 0));+ CHECK(!validField(0, 0, 0, 80, 18, 1, 1.1f, 0, 0));+ CHECK(!validField(0, 0, 0, 80, 18, 1, 1, -1, 0));+ CHECK(!validField(0, 0, 0, 80, 18, 1, 1, 0, -1));+ CHECK(!validField(0, 0, 0, 80, 18, 1, 1, 0, 4));+ CHECK(!validField(0, 0, 0, 1e30f, 18, 1, 1, 0, 0));+}diff --git a/GeneralsMD/Code/Tests/test_sdl_gpu_frame.cpp b/GeneralsMD/Code/Tests/test_sdl_gpu_frame.cppindex a0c05ccbc..31575db04 100644--- a/GeneralsMD/Code/Tests/test_sdl_gpu_frame.cpp+++ b/GeneralsMD/Code/Tests/test_sdl_gpu_frame.cpp@@ -30,6 +30,9 @@// - Any GPU but this one. Exits 77, and ctest reports it skipped, where SDL has no GPU device.#include "SdlGpuFrame.h"+#include "../Libraries/Source/WWVegas/WW3D2/sdl3shadercompile.h"+#include <cmath>+#include <cstring>#include <SDL3/SDL.h>@@ -44,6 +47,207 @@ static int failures = 0;static const unsigned int WIDTH = 64;static const unsigned int HEIGHT = 48;+// Cloud caches and their half-resolution ray pass have colour attachments only.+// Exercise their recorded clear path and switching back to the scene attachment:+// passing a depth descriptor whose texture is null crashes SDL's validation path.+static void check_colour_only_target(SdlGpuFrame *frame)+{+ SDL_GPUTextureCreateInfo info = {};+ info.type = SDL_GPU_TEXTURETYPE_2D;+ info.format = (SDL_GPUTextureFormat)SdlGpuFrame::Target_Format();+ info.usage = SDL_GPU_TEXTUREUSAGE_COLOR_TARGET | SDL_GPU_TEXTUREUSAGE_SAMPLER;+ info.width = WIDTH;+ info.height = HEIGHT;+ info.layer_count_or_depth = info.num_levels = 1;+ SDL_GPUTexture *texture = SDL_CreateGPUTexture(frame->Device(), &info);+ CHECK(texture != NULL);+ if (!texture) return;++ const SdlTarget colour_only = { texture, NULL, WIDTH, HEIGHT };+ frame->Set_Target(colour_only);+ frame->Clear_Back_Buffer(true, false, false, 0xFF123456u, 1.0f, 0);+ std::vector<uint8_t> pixels;+ CHECK(frame->Read_Back(texture, WIDTH, HEIGHT, pixels));+ CHECK(pixels.size() == WIDTH * HEIGHT * 4);+ for (size_t i = 0; i + 3 < pixels.size(); i += 4)+ CHECK(pixels[i] == 0x56 && pixels[i + 1] == 0x34+ && pixels[i + 2] == 0x12 && pixels[i + 3] == 0xFF);++ // Both clears are pending in one batch: changing targets must close the+ // colour-only pass and retain the scene's normal depth/stencil attachment.+ frame->Clear_Back_Buffer(true, false, false, 0xFFABCDEFu, 1.0f, 0);+ frame->Set_Target(frame->Back_Buffer_Target());+ frame->Clear_Back_Buffer(true, true, true, 0xFF102030u, 0.5f, 7);+ CHECK(frame->Read_Back(texture, WIDTH, HEIGHT, pixels));+ CHECK(pixels.size() == WIDTH * HEIGHT * 4 && pixels[0] == 0xEF+ && pixels[1] == 0xCD && pixels[2] == 0xAB && pixels[3] == 0xFF);+ CHECK(frame->Read_Back(frame->Back_Buffer(), WIDTH, HEIGHT, pixels));+ CHECK(pixels.size() == WIDTH * HEIGHT * 4 && pixels[0] == 0x30+ && pixels[1] == 0x20 && pixels[2] == 0x10 && pixels[3] == 0xFF);+ SDL_ReleaseGPUTexture(frame->Device(), texture);+ printf("sdl_gpu_frame_selfcheck: colour-only attachment clear/readback and scene target restoration checked\n");+}++// Rasterize actual object depth independently of the capture. The optional+// vertex texture path also exercises the height sampling used by cloud embers.+class DepthObject+{+public:+ SDL_GPUShader *Vertex = NULL, *Pixel = NULL;+ SDL_GPUGraphicsPipeline *Pipeline = NULL;+ SDL_GPUSampler *Sampler = NULL;+ SdlGpuFrame *Frame;+ explicit DepthObject(SdlGpuFrame *frame, bool vertexTexture = false) : Frame(frame)+ {+ const char *vertex =+ "cbuffer Object : register(b0, space1) { float4 Depth; };\n"+ "float4 main(uint id : SV_VertexID) : SV_Position {\n"+ "float2 p = id == 0 ? float2(-0.75,-0.75) : (id == 1 ? float2(0.75,-0.75) : float2(0,0.75));\n"+ "return float4(p,Depth.x,1); }\n";+ if (vertexTexture) {+ vertex =+ "Texture2D<float> Height : register(t0, space0);\n"+ "SamplerState HeightSampler : register(s0, space0);\n"+ "float4 main(uint id : SV_VertexID) : SV_Position {\n"+ "float2 p = id == 0 ? float2(-0.75,-0.75) : (id == 1 ? float2(0.75,-0.75) : float2(0,0.75));\n"+ "return float4(p, Height.SampleLevel(HeightSampler,float2(0.5,0.5),0),1); }\n";+ }+ const char *pixel = "float4 main() : SV_Target0 { return float4(0.8,0.2,0.1,1); }\n";+ std::vector<unsigned char> spirv;+ std::string error;+ CHECK(SDL3_Compile_HLSL_To_SPIRV(vertex, true, spirv, error));+ Vertex = SDL3_Create_Shader(frame->Device(), spirv, true, error);+ CHECK(Vertex != NULL);+ CHECK(SDL3_Compile_HLSL_To_SPIRV(pixel, false, spirv, error));+ Pixel = SDL3_Create_Shader(frame->Device(), spirv, false, error);+ CHECK(Pixel != NULL);+ if (!Vertex || !Pixel) return;+ SDL_GPUColorTargetDescription colour = {};+ colour.format = (SDL_GPUTextureFormat)SdlGpuFrame::Target_Format();+ SDL_GPUGraphicsPipelineCreateInfo info = {};+ info.vertex_shader = Vertex;+ info.fragment_shader = Pixel;+ info.primitive_type = SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;+ info.rasterizer_state.fill_mode = SDL_GPU_FILLMODE_FILL;+ info.rasterizer_state.cull_mode = SDL_GPU_CULLMODE_NONE;+ info.depth_stencil_state.enable_depth_test = true;+ info.depth_stencil_state.enable_depth_write = true;+ info.depth_stencil_state.compare_op = SDL_GPU_COMPAREOP_LESS;+ info.target_info.color_target_descriptions = &colour;+ info.target_info.num_color_targets = 1;+ info.target_info.has_depth_stencil_target = true;+ info.target_info.depth_stencil_format = (SDL_GPUTextureFormat)frame->Depth_Format();+ Pipeline = SDL_CreateGPUGraphicsPipeline(frame->Device(), &info);+ CHECK(Pipeline != NULL);+ if (vertexTexture) {+ 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;+ Sampler = SDL_CreateGPUSampler(frame->Device(), &sampler);+ CHECK(Sampler != NULL);+ }+ }+ ~DepthObject()+ {+ Frame->Flush();+ if (Pipeline) SDL_ReleaseGPUGraphicsPipeline(Frame->Device(), Pipeline);+ if (Sampler) SDL_ReleaseGPUSampler(Frame->Device(), Sampler);+ if (Vertex) SDL_ReleaseGPUShader(Frame->Device(), Vertex);+ if (Pixel) SDL_ReleaseGPUShader(Frame->Device(), Pixel);+ }+ void Draw(const SdlTarget &target, float depth, SDL_GPUTexture *height = NULL)+ {+ if (!Pipeline || (height && !Sampler)) return;+ Frame->Set_Target(target);+ SdlRecordedDraw draw = {};+ draw.Pipeline = Pipeline;+ draw.Count = 3;+ memset(Frame->Stage(16, draw.VertexOffset), 0, 16);+ const float values[4] = { depth, 0, 0, 0 };+ draw.VertexConstants = Frame->Constants(0, values, sizeof(values));+ if (height) {+ draw.VertexSamplerCount = 1;+ draw.VertexTextures[0] = height;+ draw.VertexSamplers[0] = Sampler;+ } else {+ draw.VertexConstantsSize = sizeof(values);+ }+ draw.Viewport[2] = (float)target.Width;+ draw.Viewport[3] = (float)target.Height;+ draw.Viewport[5] = 1;+ draw.Scissor[2] = target.Width;+ draw.Scissor[3] = target.Height;+ Frame->Record_Draw(draw);+ }+};++static float depth_at(const std::vector<uint8_t> &bytes, unsigned int width, unsigned int x, unsigned int y)+{+ float value = -1;+ const size_t offset = ((size_t)y * width + x) * sizeof(float);+ if (offset + sizeof(float) <= bytes.size()) memcpy(&value, &bytes[offset], sizeof(value));+ return value;+}++static void check_scene_depth_snapshot(SdlGpuFrame *frame)+{+ const SdlTarget scene = frame->Back_Buffer_Target();+ if (!(frame->Depth_Usage() & SDL_GPU_TEXTUREUSAGE_SAMPLER)) {+ CHECK(frame->Scene_Depth(scene) == NULL);+ printf("sdl_gpu_frame_selfcheck: sampled depth unavailable; fallback checked\n");+ return;+ }+ frame->Set_Target(scene);+ frame->Clear_Back_Buffer(true, true, true, 0xFF000000u, 0.8f, 0);+ DepthObject object(frame);+ object.Draw(scene, 0.25f);+ SDL_GPUTexture *snapshot = frame->Scene_Depth(scene);+ CHECK(snapshot != NULL);+ if (!snapshot) return;+ std::vector<uint8_t> bytes;+ CHECK(frame->Read_Back(snapshot, WIDTH, HEIGHT, bytes));+ CHECK(std::fabs(depth_at(bytes, WIDTH, WIDTH / 2, HEIGHT / 2) - 0.25f) < 0.00001f);+ CHECK(std::fabs(depth_at(bytes, WIDTH, 0, 0) - 0.8f) < 0.00001f);+ CHECK(frame->Scene_Depth(scene) == snapshot);++ SDL_GPUTextureCreateInfo info = {};+ info.type = SDL_GPU_TEXTURETYPE_2D;+ info.format = (SDL_GPUTextureFormat)SdlGpuFrame::Target_Format();+ info.usage = SDL_GPU_TEXTUREUSAGE_COLOR_TARGET | SDL_GPU_TEXTUREUSAGE_SAMPLER;+ info.width = WIDTH; info.height = HEIGHT;+ info.layer_count_or_depth = info.num_levels = 1;+ SDL_GPUTexture *colour = SDL_CreateGPUTexture(frame->Device(), &info);+ CHECK(colour != NULL);+ if (colour) {+ const SdlTarget intermediate = { colour, frame->Depth_For(WIDTH, HEIGHT), WIDTH, HEIGHT };+ frame->Set_Target(intermediate);+ frame->Clear_Back_Buffer(true, true, true, 0xFF000000u, 1.0f, 0);+ DepthObject sampled(frame, true);+ sampled.Draw(intermediate, 0, snapshot);+ SDL_GPUTexture *sampled_depth = frame->Scene_Depth(intermediate);+ CHECK(sampled_depth != NULL);+ if (sampled_depth) CHECK(frame->Read_Back(sampled_depth, WIDTH, HEIGHT, bytes));+ CHECK(std::fabs(depth_at(bytes, WIDTH, WIDTH / 2, HEIGHT / 2) - 0.25f) < 0.00001f);+ CHECK(std::fabs(depth_at(bytes, WIDTH, 0, 0) - 1.0f) < 0.00001f);+ frame->Set_Target(scene);+ frame->Release_After_Batch(colour, NULL);+ }+ frame->Clear_Back_Buffer(false, true, true, 0, 0.6f, 0);+ CHECK(frame->Read_Back(frame->Scene_Depth(scene), WIDTH, HEIGHT, bytes));+ CHECK(std::fabs(depth_at(bytes, WIDTH, WIDTH / 2, HEIGHT / 2) - 0.6f) < 0.00001f);+ CHECK(frame->Present(NULL));+ object.Draw(scene, 0.1f);+ CHECK(frame->Read_Back(frame->Scene_Depth(scene), WIDTH, HEIGHT, bytes));+ CHECK(std::fabs(depth_at(bytes, WIDTH, WIDTH / 2, HEIGHT / 2) - 0.1f) < 0.00001f);+ CHECK(frame->Resize(WIDTH, HEIGHT));+ frame->Clear_Back_Buffer(true, true, true, 0, 0.4f, 0);+ CHECK(frame->Read_Back(frame->Scene_Depth(frame->Back_Buffer_Target()), WIDTH, HEIGHT, bytes));+ CHECK(std::fabs(depth_at(bytes, WIDTH, WIDTH / 2, HEIGHT / 2) - 0.4f) < 0.00001f);+ printf("sdl_gpu_frame_selfcheck: scene/object depth, vertex texture, target/frame/clear invalidation and resize checked\n");+}+// B, G, R and A of pixel (x, y) in the gamma test's picture: no two pixels alike, no channel alike.static void pattern(unsigned int x, unsigned int y, uint8_t out[4]){@@ -93,6 +297,8 @@ int main()return 77;}printf("sdl_gpu_frame_selfcheck: %s\n", SDL_GetGPUDeviceDriver(frame->Device()));+ check_colour_only_target(frame);+ check_scene_depth_snapshot(frame);// A colour clear: D3DCOLOR 0x80402010 is A 0x80, R 0x40, G 0x20, B 0x10.frame->Clear_Back_Buffer(true, true, true, 0x80402010u, 1.0f, 0);diff --git a/GeneralsMD/Code/Tools/CloudPreviewColorPanel.cpp b/GeneralsMD/Code/Tools/CloudPreviewColorPanel.cppnew file mode 100644index 000000000..2f0fd9813--- /dev/null+++ b/GeneralsMD/Code/Tools/CloudPreviewColorPanel.cpp@@ -0,0 +1,407 @@+// Dependency-free color controls for the standalone cloud preview.+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.+#include "CloudPreviewColorPanel.h"+#include "CloudPreviewColors.h"++#include "Common/UnicodeString.h"+#include "GameClient/Display.h"+#include "GameClient/DisplayStringManager.h"+#include "GameClient/GameFont.h"+#include "GameClient/GameWindow.h"+#include "GameClient/GameWindowManager.h"+#include "SdlDevice/GameClient/SdlInput.h"++// Legacy engine headers expose these macros; keep them out of the panel's+// standard-library calls without changing shared headers.+#undef min+#undef max++#include <algorithm>+#include <array>+#include <cmath>+#include <cstdio>+#include <string>++namespace CloudPreviewColorPanel {+namespace {++constexpr float Left = 16.f, Top = 16.f, Width = 320.f;+constexpr int SliderCount = 5;+constexpr float FirstTrack = 274.f, SliderStep = 38.f;+constexpr float ActionsTop = FirstTrack + SliderStep * (SliderCount - 1) + 22.f;+constexpr float Height = ActionsTop + 114.f;+constexpr float TrackLeft = 23.f, TrackWidth = 274.f;+constexpr unsigned PaletteOrder[] = {0, 2, 3, 1};+constexpr const char *PaletteLabels[] = {"Toxin", "Toxin beta", "Toxin gamma", "Nuclear"};+constexpr unsigned Ink = 0xffe8eef2, Muted = 0xffa5b5c2, Accent = 0xff87c9d7;++GameWindow *overlay = nullptr;+bool shown = true;+bool shadowSelected = false;+unsigned selection = 0;+int previewRequest = -1;+int activeSlider = -1;+Uint32 ownedButtons = 0;+float scale = 1.f, mouseX = -1.f, mouseY = -1.f;+std::string localStatus;++struct Label {+ DisplayString *display = nullptr;+ std::string value;+ int fontSize = 0;+ bool bold = false;+ int x = 0, y = 0;+ unsigned color = Ink;+};+std::array<Label, 32> labels;+unsigned labelCount = 0;++float clamp(float value, float low = 0.f, float high = 1.f)+{+ return std::max(low, std::min(high, value));+}++unsigned byte(float value)+{+ return static_cast<unsigned>(std::lround(clamp(value) * 255.f));+}++unsigned color(const CloudPreviewColors::Color &value)+{+ return 0xff000000u | (byte(value.r) << 16) | (byte(value.g) << 8) | byte(value.b);+}++bool hit(float x, float y, float left, float top, float width, float height)+{+ return x >= left && x < left + width && y >= top && y < top + height;+}++bool inside(float x, float y)+{+ return hit(x, y, Left, Top, Width, Height);+}++bool over(float x, float y, float width, float height)+{+ return hit(mouseX, mouseY, Left + x, Top + y, width, height);+}++void releaseSlider()+{+ if (activeSlider >= 0) SDL_CaptureMouse(false);+ activeSlider = -1;+}++void refreshScale()+{+ if (!TheDisplay) return;+ scale = std::min(1.f, std::min(TheDisplay->getWidth() / (Width + 32.f),+ TheDisplay->getHeight() / (Height + 32.f)));+ scale = std::max(.1f, scale);+ if (overlay) {+ overlay->winSetPosition(int(std::lround(Left * scale)), int(std::lround(Top * scale)));+ overlay->winSetSize(int(std::lround(Width * scale)), int(std::lround(Height * scale)));+ }+}++void updateMouse(float x, float y)+{+ refreshScale();+ // SDL reports window coordinates; the game draws in backbuffer pixels.+ int windowWidth = 0, windowHeight = 0;+ if (SDL_Window *window = SdlInput_gameWindow())+ SDL_GetWindowSize(window, &windowWidth, &windowHeight);+ const float pixelX = TheDisplay && windowWidth > 0+ ? float(TheDisplay->getWidth()) / windowWidth : 1.f;+ const float pixelY = TheDisplay && windowHeight > 0+ ? float(TheDisplay->getHeight()) / windowHeight : 1.f;+ mouseX = x * pixelX / scale;+ mouseY = y * pixelY / scale;+}++float trackY(int row)+{+ return Top + FirstTrack + SliderStep * row;+}++void updateSlider(int row)+{+ CloudPreviewColors::Palette palette = CloudPreviewColors::get(selection);+ CloudPreviewColors::Color &selected = shadowSelected ? palette.shadow : palette.main;+ float *component = row == 0 ? &selected.r : row == 1 ? &selected.g+ : row == 2 ? &selected.b : row == 3 ? &palette.brightness : &palette.transparency;+ const float fraction = clamp((mouseX - Left - TrackLeft) / TrackWidth);+ // RGB controls land on shareable bytes; brightness/transparency use 1% steps.+ const float value = row == 3 ? std::round(fraction * 200.f) / 100.f+ : row == 4 ? std::round(fraction * 100.f) / 100.f : std::round(fraction * 255.f) / 255.f;+ if (*component != value) {+ *component = value;+ CloudPreviewColors::set(selection, palette);+ localStatus.clear();+ }+}++void rect(float x, float y, float width, float height, unsigned fill)+{+ if (width <= 0.f || height <= 0.f) return;+ const int left = int(std::lround((Left + x) * scale));+ const int top = int(std::lround((Top + y) * scale));+ const int right = int(std::lround((Left + x + width) * scale));+ const int bottom = int(std::lround((Top + y + height) * scale));+ TheDisplay->drawFillRect(left, top, std::max(1, right - left), std::max(1, bottom - top), fill);+}++void text(float x, float y, const std::string &value, unsigned ink = Ink,+ int pointSize = 11, bool bold = false, bool centered = false, float width = 0.f)+{+ if (labelCount >= labels.size()) return;+ Label &label = labels[labelCount++];+ if (!label.display) label.display = TheDisplayStringManager->newDisplayString();+ if (!label.display) return;+ const int size = std::max(7, int(std::lround(pointSize * scale)));+ if (label.fontSize != size || label.bold != bold) {+ label.display->setFont(TheFontLibrary->getFont(AsciiString("Arial"), size, bold));+ label.fontSize = size;+ label.bold = bold;+ }+ if (label.value != value) {+ UnicodeString translated;+ translated.translate(AsciiString(value.c_str()));+ label.display->setText(translated);+ label.value = value;+ }+ label.x = int(std::lround((Left + x) * scale));+ if (centered) label.x += (int(std::lround(width * scale)) - label.display->getWidth()) / 2;+ label.y = int(std::lround((Top + y) * scale));+ label.color = ink;+}++void button(float x, float y, float width, float height, const char *label,+ bool selected = false, bool primary = false)+{+ const bool hover = over(x, y, width, height);+ rect(x, y, width, height, selected || primary ? 0xff60828f : 0xff455561);+ rect(x + 1, y + 1, width - 2, height - 2,+ selected ? 0xff304a57 : hover ? 0xff354653 : primary ? 0xff283f4a : 0xff242f3a);+ text(x, y + (height - 16.f) * .5f - 1.f, label,+ selected || primary ? 0xffdbf2f5 : Ink, 10, selected, true, width);+}++void draw(GameWindow *, WinInstanceData *)+{+ if (!shown || !TheDisplay || !TheDisplayStringManager || !TheFontLibrary) return;+ refreshScale();+ labelCount = 0;+ // Rectangles share a single engine batch. Text is queued and drawn only once+ // the geometry is flushed, preserving both renderer state and overlay order.+ TheDisplay->beginBatch2D();+ rect(4, 5, Width, Height, 0x66000000);+ rect(0, 0, Width, Height, 0xfa18212a);+ rect(0, 0, Width, 3, Accent);+ rect(0, Height - 1, Width, 1, 0xff455562);+ text(16, 13, "Cloud colors", Ink, 16, true);+ button(244, 12, 60, 25, "Hide P");+ text(16, 39, "VOLUMETRIC COLORS", Muted, 9);++ for (unsigned index = 0; index < 4; ++index) {+ const float x = 16.f + 148.f * (index % 2);+ const float y = 60.f + 34.f * (index / 2);+ const unsigned palette = PaletteOrder[index];+ button(x, y, 140, 28, PaletteLabels[index], selection == palette);+ rect(x + 9, y + 10, 8, 8, color(CloudPreviewColors::get(palette).main));+ }+ button(16, 132, 288, 28, "SHOW SCENE", false, true);++ const CloudPreviewColors::Palette &palette = CloudPreviewColors::get(selection);+ const CloudPreviewColors::Color &selected = shadowSelected ? palette.shadow : palette.main;+ button(16, 174, 140, 28, "Main", !shadowSelected);+ button(164, 174, 140, 28, "Shadow", shadowSelected);+ rect(133, 182, 14, 12, color(palette.main));+ rect(281, 182, 14, 12, color(palette.shadow));++ const unsigned red = byte(selected.r), green = byte(selected.g), blue = byte(selected.b);+ const unsigned swatchInk = .2126f * red + .7152f * green + .0722f * blue > 145.f+ ? 0xff101820 : 0xfff6f8fc;+ rect(16, 212, 288, 27, color(selected));+ char hex[16], rgb[32];+ std::snprintf(hex, sizeof(hex), "#%02X%02X%02X", red, green, blue);+ std::snprintf(rgb, sizeof(rgb), "RGB %u, %u, %u", red, green, blue);+ text(25, 217, hex, swatchInk, 11, true);+ text(145, 218, rgb, swatchInk, 10);++ const char *names[] = {"Red", "Green", "Blue", "Brightness", "Transparency (more = clearer)"};+ const unsigned accents[] = {0xffdf9394, 0xff9dca8b, 0xff92b7e2, 0xffc9c8a7, Accent};+ const float values[] = {selected.r, selected.g, selected.b, palette.brightness, palette.transparency};+ for (int row = 0; row < SliderCount; ++row) {+ const float fraction = clamp(values[row] / (row == 3 ? 2.f : 1.f));+ const float y = trackY(row) - Top;+ const float knob = TrackLeft + fraction * TrackWidth;+ char amount[16];+ std::snprintf(amount, sizeof(amount), row >= 3 ? "%d%%" : "%d",+ int(std::lround(values[row] * (row >= 3 ? 100.f : 255.f))));+ text(16, y - 23, names[row], Ink, 10);+ text(251, y - 23, amount, accents[row], 10, true, true, 53);+ rect(TrackLeft, y - 3, TrackWidth, 6, 0xff3b4a58);+ rect(TrackLeft, y - 3, fraction * TrackWidth, 6, accents[row]);+ if (activeSlider == row) rect(knob - 7, y - 9, 14, 18, 0x607fc3d3);+ rect(knob - 4, y - 7, 8, 14, 0xffeef3f7);+ rect(knob - 2, y - 4, 4, 8, accents[row]);+ }++ button(16, ActionsTop, 140, 28, "Reset palette");+ button(164, ActionsTop, 140, 28, "Save all", false, true);+ button(16, ActionsTop + 34, 140, 28, "Load saved");+ button(164, ActionsTop + 34, 140, 28, "Copy all");+ const std::string status = localStatus.empty() ? CloudPreviewColors::lastStatus() : localStatus;+ text(16, ActionsTop + 72, status.empty() ? "Drag sliders to change the selected cloud." : status.substr(0, 43),+ 0xffb4c9b8, 9);+ text(16, ActionsTop + 94, "P hide panel Space pause B replay", Muted, 9);+ TheDisplay->endBatch2D();+ for (unsigned i = 0; i < labelCount; ++i) {+ Label &label = labels[i];+ if (label.display) label.display->draw(label.x, label.y, label.color, 0x00000000);+ }+}++WindowMsgHandledType system(GameWindow *window, UnsignedInt message, WindowMsgData, WindowMsgData)+{+ // A map reset may destroy the overlay before ordinary host teardown.+ if (message == GWM_DESTROY && window == overlay) overlay = nullptr;+ return MSG_IGNORED;+}++} // namespace++bool initialize()+{+ if (overlay) return true;+ if (!TheWindowManager || !TheDisplay || !TheDisplayStringManager || !TheFontLibrary) return false;+ overlay = TheWindowManager->winCreate(nullptr,+ WIN_STATUS_ENABLED | WIN_STATUS_ABOVE | WIN_STATUS_NO_INPUT | WIN_STATUS_NO_FOCUS,+ int(Left), int(Top), int(Width), int(Height), system, nullptr);+ if (!overlay) return false;+ overlay->winSetDrawFunc(draw);+ overlay->winHide(!shown);+ refreshScale();+ return true;+}++void shutdown()+{+ releaseSlider();+ ownedButtons = 0;+ if (overlay && TheWindowManager) TheWindowManager->winDestroy(overlay);+ overlay = nullptr;+ for (Label &label : labels) {+ if (label.display && TheDisplayStringManager)+ TheDisplayStringManager->freeDisplayString(label.display);+ label = {};+ }+ labelCount = 0;+ previewRequest = -1;+}++bool handle(const SDL_Event &event)+{+ if ((event.type == SDL_EVENT_KEY_DOWN || event.type == SDL_EVENT_KEY_UP)+ && event.key.key == SDLK_P) {+ if (event.type == SDL_EVENT_KEY_DOWN && !event.key.repeat) setVisible(!shown);+ return true;+ }+ if (event.type == SDL_EVENT_WINDOW_FOCUS_LOST) {+ releaseSlider();+ ownedButtons = 0;+ return false;+ }+ // A button belongs to the surface that handled its press. Check release+ // ownership even while hidden: Hide/P may hide the panel during a click.+ // Likewise, a map drag released over the panel must reach the game.+ if (event.type == SDL_EVENT_MOUSE_BUTTON_UP) {+ const Uint32 button = event.button.button > 0 && event.button.button <= 32+ ? Uint32(1) << (event.button.button - 1) : 0;+ const bool consumed = (ownedButtons & button) != 0;+ ownedButtons &= ~button;+ if (consumed && event.button.button == SDL_BUTTON_LEFT) releaseSlider();+ return consumed;+ }+ if (!shown) return false;+ if (event.type == SDL_EVENT_MOUSE_MOTION) {+ updateMouse(event.motion.x, event.motion.y);+ if (activeSlider >= 0) { updateSlider(activeSlider); return true; }+ if (ownedButtons) return true;+ if (event.motion.state) return false;+ return inside(mouseX, mouseY);+ }+ if (event.type == SDL_EVENT_MOUSE_WHEEL) {+ updateMouse(event.wheel.mouse_x, event.wheel.mouse_y);+ return inside(mouseX, mouseY);+ }+ if (event.type != SDL_EVENT_MOUSE_BUTTON_DOWN) return false;+ updateMouse(event.button.x, event.button.y);+ if (!inside(mouseX, mouseY)) return false;+ if (event.button.button > 0 && event.button.button <= 32)+ ownedButtons |= Uint32(1) << (event.button.button - 1);+ if (event.button.button != SDL_BUTTON_LEFT) return true;+ if (over(244, 12, 60, 25)) { setVisible(false); return true; }+ for (unsigned index = 0; index < 4; ++index) {+ if (over(16.f + 148.f * (index % 2), 60.f + 34.f * (index / 2), 140, 28)) {+ selectPalette(PaletteOrder[index]);+ return true;+ }+ }+ if (over(16, 132, 288, 28)) { previewRequest = int(selection); return true; }+ if (over(16, 174, 140, 28)) { shadowSelected = false; releaseSlider(); return true; }+ if (over(164, 174, 140, 28)) { shadowSelected = true; releaseSlider(); return true; }+ for (int row = 0; row < SliderCount; ++row) {+ if (hit(mouseX, mouseY, Left + 16, trackY(row) - 12, Width - 32, 25)) {+ activeSlider = row;+ SDL_CaptureMouse(true);+ updateSlider(row);+ return true;+ }+ }+ if (over(16, ActionsTop, 140, 28)) {+ CloudPreviewColors::reset(selection);+ localStatus.clear();+ } else if (over(164, ActionsTop, 140, 28)) {+ CloudPreviewColors::save();+ localStatus.clear();+ } else if (over(16, ActionsTop + 34, 140, 28)) {+ CloudPreviewColors::load();+ localStatus.clear();+ } else if (over(164, ActionsTop + 34, 140, 28)) {+ const std::string exported = CloudPreviewColors::exportText();+ localStatus = SDL_SetClipboardText(exported.c_str())+ ? "All colors copied. Paste them into the chat."+ : "Clipboard unavailable. Use Save all instead.";+ }+ return true;+}++bool visible() { return shown; }++void setVisible(bool value)+{+ shown = value;+ releaseSlider();+ if (overlay) overlay->winHide(!shown);+}++unsigned selectedPalette() { return selection; }++void selectPalette(unsigned palette)+{+ if (palette >= 4) return;+ selection = palette;+ releaseSlider();+ localStatus.clear();+}++int takePreviewRequest()+{+ const int requested = previewRequest;+ previewRequest = -1;+ return requested;+}++} // namespace CloudPreviewColorPaneldiff --git a/GeneralsMD/Code/Tools/CloudPreviewColorPanel.h b/GeneralsMD/Code/Tools/CloudPreviewColorPanel.hnew file mode 100644index 000000000..b45819959--- /dev/null+++ b/GeneralsMD/Code/Tools/CloudPreviewColorPanel.h@@ -0,0 +1,25 @@+// Color controls for the isolated cloud preview, not the production game UI.+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.+#pragma once++#include <SDL3/SDL.h>++namespace CloudPreviewColorPanel {++// Installs a GameWindow overlay, drawn after the 3D scene by the existing UI+// renderer. Call after the preview scene initializes and before engine teardown.+bool initialize();+void shutdown();++// Call before forwarding events to the game. Consumes panel mouse input and P.+bool handle(const SDL_Event &event);+bool visible();+void setVisible(bool value);+unsigned selectedPalette();+void selectPalette(unsigned palette);++// The controller owns scene changes; a selection alone does not restart a scene.+// Returns the requested palette (0 toxin, 1 nuclear, 2 beta, 3 gamma), or -1.+int takePreviewRequest();++} // namespace CloudPreviewColorPaneldiff --git a/GeneralsMD/Code/Tools/CloudPreviewColors.cpp b/GeneralsMD/Code/Tools/CloudPreviewColors.cppnew file mode 100644index 000000000..76bf93368--- /dev/null+++ b/GeneralsMD/Code/Tools/CloudPreviewColors.cpp@@ -0,0 +1,332 @@+// Editable palettes and explicit persistence for the isolated cloud preview.+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.+#include "CloudPreviewColors.h"++#include <array>+#include <cerrno>+#include <cmath>+#include <cstdio>+#include <cstring>+#include <filesystem>+#include <fstream>+#include <iomanip>+#include <limits>+#include <locale>+#include <sstream>+#include <vector>++#include <unistd.h>++namespace CloudPreviewColors {+namespace {++// User-approved palette, preserved in cloud_preview/presets/preferred.ini.+constexpr std::array<Palette, 4> defaults = {{+ {{0.769999981f, 0.939999998f, 0.550000012f}, {0.125490203f, 0.31764707f, 0.0549019612f}, 0.699999988f, 0.670000017f},+ {{0.749019623f, 0.670588255f, 0.469999999f}, {0.298039228f, 0.184313729f, 0.0705882385f}, 1.29999995f, 0.f},+ {{0.660000026f, 0.75999999f, 1.0f}, {0.0649999976f, 0.100000001f, 0.209999993f}, 1.52999997f, 0.769999981f},+ {{0.839999974f, 0.629999995f, 1.0f}, {0.192156866f, 0.0470588244f, 0.235294119f}, 1.32000005f, 0.74000001f},+}};+constexpr const char *names[] = {"toxin", "nuclear", "toxin_beta", "toxin_gamma"};+constexpr unsigned displayOrder[] = {0, 2, 3, 1};+std::array<Palette, 4> palettes = defaults;+std::string path;+std::string status = "Default cloud colors";+unsigned currentRevision = 0;++bool equal(const Color &a, const Color &b)+{+ return a.r == b.r && a.g == b.g && a.b == b.b;+}++bool equal(const Palette &a, const Palette &b)+{+ return equal(a.main, b.main) && equal(a.shadow, b.shadow) && a.brightness == b.brightness+ && a.transparency == b.transparency;+}++bool bounded(float value, float maximum)+{+ return std::isfinite(value) && value >= 0 && value <= maximum;+}++bool valid(const Color &c)+{+ return bounded(c.r, 1) && bounded(c.g, 1) && bounded(c.b, 1);+}++bool valid(const Palette &p)+{+ return valid(p.main) && valid(p.shadow) && bounded(p.brightness, 2) && bounded(p.transparency, 1);+}++std::string trim(const std::string &text)+{+ const auto first = text.find_first_not_of(" \t\r\n");+ if (first == std::string::npos)+ return {};+ return text.substr(first, text.find_last_not_of(" \t\r\n") - first + 1);+}++bool number(const std::string &text, float &value)+{+ std::istringstream in(text);+ in.imbue(std::locale::classic());+ if (!(in >> value))+ return false;+ in >> std::ws;+ return in.eof() && std::isfinite(value);+}++bool color(const std::string &text, Color &result)+{+ std::string input = text;+ for (char &c : input)+ if (c == ',')+ c = ' ';+ std::istringstream in(input);+ in.imbue(std::locale::classic());+ if (!(in >> result.r >> result.g >> result.b))+ return false;+ in >> std::ws;+ return in.eof() && valid(result);+}++std::string hex(const Color &c)+{+ char result[8];+ std::snprintf(result, sizeof(result), "#%02X%02X%02X",+ unsigned(std::lround(c.r * 255)), unsigned(std::lround(c.g * 255)),+ unsigned(std::lround(c.b * 255)));+ return result;+}++bool failLoad(const std::string &reason, unsigned line = 0)+{+ status = "Colors not loaded: " + reason;+ if (line)+ status += " (line " + std::to_string(line) + ")";+ return false;+}++} // namespace++const Palette &get(unsigned index)+{+ return palettes[index < palettes.size() ? index : 0];+}++void set(unsigned index, const Palette &palette)+{+ if (index >= palettes.size() || !valid(palette)) {+ status = "Edit rejected: RGB/transparency 0-1, brightness 0-2";+ return;+ }+ if (!equal(palettes[index], palette)) {+ palettes[index] = palette;+ ++currentRevision;+ }+ status = std::string("Edited ") + names[index] + " (not saved)";+}++void reset(unsigned index)+{+ if (index >= palettes.size()) {+ status = "Color reset rejected: unknown palette";+ return;+ }+ set(index, defaults[index]);+ status = std::string("Reset ") + names[index] + " (not saved)";+}++unsigned revision() { return currentRevision; }+std::string lastStatus() { return status; }+std::string savePath() { return path; }++bool initialize(const std::string &userDir)+{+ palettes = defaults;+ ++currentRevision;+ path.clear();+ if (userDir.empty()) {+ status = "Color file unavailable: empty preview directory";+ return false;+ }+ path = (std::filesystem::path(userDir) / "cloud-colors.ini").string();+ std::error_code error;+ const bool exists = std::filesystem::exists(path, error);+ if (error)+ return failLoad(error.message());+ if (!exists) {+ status = "Default cloud colors (no saved file yet)";+ return true;+ }+ return load();+}++std::string exportText()+{+ std::ostringstream out;+ out.imbue(std::locale::classic());+ out << "; Isolated cloud preview colors. RGB values are linear shader values.\n"+ "; Main and shadow RGB: 0-1. Brightness: 0-2. Hex comments are rounded.\n"+ "; Transparency: 0-1, higher is clearer; 0 keeps full smoke density.\n"+ "version = 2\n";+ out << std::setprecision(std::numeric_limits<float>::max_digits10);+ for (unsigned index : displayOrder) {+ const Palette &p = palettes[index];+ out << "\n[" << names[index] << "]\n";+ out << "main = " << p.main.r << ", " << p.main.g << ", " << p.main.b+ << " ; " << hex(p.main) << "\n";+ out << "shadow = " << p.shadow.r << ", " << p.shadow.g << ", " << p.shadow.b+ << " ; " << hex(p.shadow) << "\n";+ out << "brightness = " << p.brightness << "\n";+ out << "transparency = " << p.transparency << "\n";+ }+ return out.str();+}++bool save()+{+ if (path.empty()) {+ status = "Colors not saved: no preview directory";+ return false;+ }+ // The temporary file shares its destination directory, so rename replaces+ // the previous complete palette atomically. mkstemp cannot follow a stale+ // temporary-file symlink and is safe for two running preview processes.+ std::string temporary = path + ".tmp-XXXXXX";+ std::vector<char> temporaryName(temporary.begin(), temporary.end());+ temporaryName.push_back('\0');+ const int file = mkstemp(temporaryName.data());+ if (file < 0) {+ status = std::string("Colors not saved: ") + std::strerror(errno);+ return false;+ }+ const std::string text = exportText();+ size_t written = 0;+ int failure = 0;+ while (written < text.size()) {+ const ssize_t count = write(file, text.data() + written, text.size() - written);+ if (count < 0 && errno == EINTR)+ continue;+ if (count <= 0) {+ failure = count < 0 ? errno : EIO;+ break;+ }+ written += static_cast<size_t>(count);+ }+ if (!failure && fsync(file) != 0)+ failure = errno;+ if (close(file) != 0 && !failure)+ failure = errno;+ if (!failure && std::rename(temporaryName.data(), path.c_str()) != 0)+ failure = errno;+ if (failure) {+ std::remove(temporaryName.data());+ status = std::string("Colors not saved: ") + std::strerror(failure);+ return false;+ }+ status = "Saved all four cloud palettes";+ return true;+}++bool load()+{+ if (path.empty())+ return failLoad("no preview directory");+ std::ifstream file(path);+ file.imbue(std::locale::classic());+ if (!file)+ return failLoad("cannot open cloud-colors.ini");++ // Parse into an independent snapshot; malformed input never applies only+ // part of a palette, nor silently resets the user's other cloud colors.+ auto parsed = defaults;+ // Version 1 predates transparency and must retain its original appearance,+ // independently of later preferred defaults. Version 2 requires the field.+ for (auto &palette : parsed) palette.transparency = 0.f;+ unsigned fields[4] = {};+ unsigned sections = 0;+ int section = -1;+ unsigned version = 0;+ unsigned lineNumber = 0;+ std::string line;+ while (std::getline(file, line)) {+ ++lineNumber;+ if (lineNumber > 256 || line.size() > 1024)+ return failLoad("file exceeds palette format limits", lineNumber);+ line = trim(line.substr(0, line.find_first_of(";#")));+ if (line.empty())+ continue;+ if (line.front() == '[') {+ if (line.back() != ']')+ return failLoad("malformed section", lineNumber);+ const std::string name = trim(line.substr(1, line.size() - 2));+ section = -1;+ for (unsigned i = 0; i < 4; ++i)+ if (name == names[i])+ section = static_cast<int>(i);+ if (section < 0)+ return failLoad("unknown palette " + name, lineNumber);+ if (sections & (1u << section))+ return failLoad("duplicate palette " + name, lineNumber);+ sections |= 1u << section;+ continue;+ }+ const auto assignment = line.find('=');+ if (assignment == std::string::npos)+ return failLoad("expected key = value", lineNumber);+ const std::string key = trim(line.substr(0, assignment));+ const std::string value = trim(line.substr(assignment + 1));+ if (section < 0) {+ if (key != "version" || (value != "1" && value != "2") || version)+ return failLoad("expected one version = 1 or 2 header", lineNumber);+ version = value == "2" ? 2 : 1;+ continue;+ }+ unsigned flag = 0;+ bool accepted = false;+ if (key == "main") {+ flag = 1;+ accepted = color(value, parsed[section].main);+ } else if (key == "shadow") {+ flag = 2;+ accepted = color(value, parsed[section].shadow);+ } else if (key == "brightness") {+ flag = 4;+ accepted = number(value, parsed[section].brightness)+ && bounded(parsed[section].brightness, 2);+ } else if (key == "transparency") {+ if (version != 2)+ return failLoad("transparency requires version 2", lineNumber);+ flag = 8;+ accepted = number(value, parsed[section].transparency)+ && bounded(parsed[section].transparency, 1);+ } else {+ return failLoad("unknown key " + key, lineNumber);+ }+ if (fields[section] & flag)+ return failLoad("duplicate key " + key, lineNumber);+ if (!accepted)+ return failLoad("invalid " + key + " value", lineNumber);+ fields[section] |= flag;+ }+ if (file.bad())+ return failLoad("file read failed");+ if (!version || sections != 15)+ return failLoad("version 1 or 2 and all four palettes are required");+ for (unsigned i = 0; i < 4; ++i)+ if (fields[i] != (version == 2 ? 15u : 7u))+ return failLoad(std::string("missing values in ") + names[i]);+ bool changed = false;+ for (unsigned i = 0; i < 4; ++i)+ changed |= !equal(palettes[i], parsed[i]);+ palettes = parsed;+ if (changed)+ ++currentRevision;+ status = "Loaded all four cloud palettes";+ return true;+}++} // namespace CloudPreviewColorsdiff --git a/GeneralsMD/Code/Tools/CloudPreviewColors.h b/GeneralsMD/Code/Tools/CloudPreviewColors.hnew file mode 100644index 000000000..f5bcdbfbe--- /dev/null+++ b/GeneralsMD/Code/Tools/CloudPreviewColors.h@@ -0,0 +1,32 @@+// Editable palettes and explicit persistence for the isolated cloud preview.+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.+#pragma once++#include <string>++namespace CloudPreviewColors {++// Palette IDs match the volume shader: toxin, nuclear, beta, gamma.+struct Color { float r, g, b; };+struct Palette { Color main, shadow; float brightness; float transparency = 0.f; };++// RGB channels are linear shader values in [0, 1]; brightness is in [0, 2].+// Transparency is in [0, 1]: 0 keeps full smoke density, 1 clears it.+// Invalid edits are rejected without changing the palette. Invalid get IDs+// return toxin. set/reset never write a file or modify any game setting.+const Palette &get(unsigned index);+void set(unsigned index, const Palette &palette);+void reset(unsigned index);+unsigned revision();++// Start with the user-approved preview palettes, then load an existing file.+// An absent file is normal and is not created. A malformed file leaves all+// defaults intact and returns false. The caller owns the user directory.+bool initialize(const std::string &userDir);+bool save(); // Explicit, atomic replacement of cloud-colors.ini.+bool load(); // Transactional reload; version 1 defaults transparency to zero.+std::string exportText(); // Complete reproducible INI suitable for a clipboard.+std::string lastStatus();+std::string savePath();++} // namespace CloudPreviewColorsdiff --git a/GeneralsMD/Code/Tools/CloudPreviewFlow.cpp b/GeneralsMD/Code/Tools/CloudPreviewFlow.cppnew file mode 100644index 000000000..9cd993214--- /dev/null+++ b/GeneralsMD/Code/Tools/CloudPreviewFlow.cpp@@ -0,0 +1,37 @@+// Compatibility singleton for the isolated cloud preview and its CPU checks.+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.+#include "CloudPreviewFlow.h"++namespace CloudPreviewFlow {+namespace {++SdlHazardCloudFlow::Flow &previewFlow()+{+ static SdlHazardCloudFlow::Flow flow;+ return flow;+}++} // namespace++void setDomain(float minX, float minY, float maxX, float maxY)+{+ previewFlow().setDomain(minX, minY, maxX, maxY);+}+void reset() { previewFlow().reset(); }+void step(float deltaSeconds, const Body *bodies, unsigned count)+{+ previewFlow().step(deltaSeconds, bodies, count);+}++unsigned width() { return previewFlow().width(); }+unsigned height() { return previewFlow().height(); }+float domainMinX() { return previewFlow().domainMinX(); }+float domainMinY() { return previewFlow().domainMinY(); }+float domainMaxX() { return previewFlow().domainMaxX(); }+float domainMaxY() { return previewFlow().domainMaxY(); }+const float *data() { return previewFlow().data(); }+bool valid() { return previewFlow().valid(); }+float maxDisturbance() { return previewFlow().maxDisturbance(); }+unsigned activeBodies() { return previewFlow().activeBodies(); }++} // namespace CloudPreviewFlowdiff --git a/GeneralsMD/Code/Tools/CloudPreviewFlow.h b/GeneralsMD/Code/Tools/CloudPreviewFlow.hnew file mode 100644index 000000000..b559755db--- /dev/null+++ b/GeneralsMD/Code/Tools/CloudPreviewFlow.h@@ -0,0 +1,43 @@+// Compatibility interface for the isolated preview's shared SDL smoke flow.+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.+#pragma once++#include "Platform/SdlHazardCloudFlow.h"++namespace CloudPreviewFlow {++// World coordinates and world units per second. The caller supplies the current+// velocity, not a displacement since the last rendered frame. Body order need+// not be stable. Z and height retain the scene's body geometry; flow is planar.+using Body = SdlHazardCloudFlow::Body;++// Covers the texture edges, with cells sampled at their centres. Changing the+// domain resets all flow. reset() preserves the domain and clears its history.+void setDomain(float minX, float minY, float maxX, float maxY);+void reset();++// Uses fixed 1/60-second steps and a capped catch-up interval. Empty input heals+// the existing wake. A zero delta freezes it. Invalid bodies are ignored and+// reported by valid(); velocities too large for infantry are treated as warps.+void step(float deltaSeconds, const Body *bodies, unsigned count);++unsigned width();+unsigned height();+float domainMinX();+float domainMinY();+float domainMaxX();+float domainMaxY();++// Row-major RGBA32F, X varies fastest. R/G are accumulated world displacement;+// sample the smoke noise at world.xy - RG. B/A are reserved and always zero:+// this field moves smoke without carving body-shaped holes or density rings.+// Shader applies the height falloff. Data stays valid until the next+// step/reset/setDomain. Displacement magnitude is bounded to 18 units.+const float *data();++// Cheap diagnostics for the preview's automated checks; not gameplay state.+bool valid();+float maxDisturbance(); // Maximum displacement magnitude divided by 18 units.+unsigned activeBodies();++} // namespace CloudPreviewFlowdiff --git a/GeneralsMD/Code/Tools/CloudPreviewScene.cpp b/GeneralsMD/Code/Tools/CloudPreviewScene.cppnew file mode 100644index 000000000..023066d24--- /dev/null+++ b/GeneralsMD/Code/Tools/CloudPreviewScene.cpp@@ -0,0 +1,673 @@+// Harmless toxin/radiation scene using the production W3D particle and unit paths.+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.+#include "PreRTS.h"+#include "CloudPreviewScene.h"+#include "CloudPreviewVolume.h"+#include "CloudPreviewFlow.h"+#include "CloudPreviewSources.h"+#include "Common/DrawModule.h"+#include "GameClient/Drawable.h"+#include "WWMath/obbox.h"++#include "Common/Player.h"+#include "Common/PlayerList.h"+#include "Common/Team.h"+#include "Common/ThingFactory.h"+#include "Common/ThingTemplate.h"+#include "GameClient/ControlBar.h"+#include "GameClient/InGameUI.h"+#include "GameClient/ParticleSys.h"+#include "W3DDevice/GameClient/W3DParticleSys.h"+#include "W3DDevice/GameClient/W3DDisplay.h"+#include "W3DDevice/GameClient/W3DScene.h"+#include "WW3D2/assetmgr.h"+#include "WW3D2/rendobj.h"+#include "WWMath/aabox.h"+#include "WWMath/matrix3d.h"+#include "GameClient/View.h"+#include "GameLogic/AI.h"+#include "GameLogic/AIPathfind.h"+#include "GameLogic/GameLogic.h"+#include "GameLogic/Module/AIUpdate.h"+#include "GameLogic/Module/BehaviorModule.h"+#include "GameLogic/Module/BodyModule.h"+#include "GameLogic/Module/CreateModule.h"+#include "GameLogic/Object.h"+#include "GameLogic/PartitionManager.h"+#include "GameLogic/TerrainLogic.h"+#include "GameLogic/VictoryConditions.h"++#include <algorithm>+#include <cmath>+#include <cstdio>+#include <cstring>+#include <vector>++namespace CloudPreviewScene {+namespace {++const unsigned FIELD_COUNT = 2;+const unsigned UNIT_COUNT = 4;+const unsigned REPORT_INTERVAL = 5 * LOGICFRAMES_PER_SECOND;+const unsigned MOTION_GRACE = 3 * LOGICFRAMES_PER_SECOND;+const unsigned EMITTER_LIFETIME = 60 * LOGICFRAMES_PER_SECOND;+const Real FIELD_RADIUS = 115.0f;+const Real FIELD_OFFSET = 155.0f;+const Real WALK_HALF_WIDTH = 330.0f;+const Real ARRIVE_RADIUS = 12.0f;++struct Field {+ const char *name;+ ParticleSystemID id;+ Coord3D position;+ unsigned lastParticleFrame;+ Real radius;+};++struct Walker {+ ObjectID id;+ Coord3D endpoints[2];+ Coord3D previous;+ Real health;+ Real height;+ Real radius;+ Real distance;+ unsigned destination;+ unsigned turns;+ unsigned enteredFields;+};++Field fields[FIELD_COUNT] = {+ { "PoisonFieldLarge", INVALID_PARTICLE_SYSTEM_ID, {} },+ { "RadiationFieldLarge", INVALID_PARTICLE_SYSTEM_ID, {} }+};+Walker walkers[UNIT_COUNT] = {};+bool initialized = false;+Appearance appearance = Appearance::Volumetric;+bool failed = false;+unsigned styleStartFrame = 0;+unsigned startFrame = 0;+unsigned lastFrame = ~0u;+unsigned lastReport = 0;+Real infantryHeight = 13.0f;+unsigned activeFieldCount = FIELD_COUNT;+std::vector<RenderObjClass *> scenery;++void fail(const char *reason)+{+ if (!failed)+ std::fprintf(stderr, "cloud-preview: validation FAIL: %s\n", reason);+ failed = true;+}++Real distanceSquared(const Coord3D &a, const Coord3D &b)+{+ const Real x = a.x - b.x, y = a.y - b.y;+ return x * x + y * y;+}++Coord3D groundPosition(Real x, Real y)+{+ Coord3D position;+ position.set(x, y, TheTerrainLogic->getGroundHeight(x, y));+ return position;+}++void clearScenery()+{+ for (RenderObjClass *object : scenery) {+ object->Remove();+ object->Release_Ref();+ }+ scenery.clear();+}++bool createScenery(const Coord3D ¢re)+{+ if (!WW3DAssetManager::Get_Instance() || !W3DDisplay::m_3DScene) return false;+ struct Sample { const char *model; float x, y, angle; bool betweenLanes; };+ const Sample samples[] = {+ // Buildings sit beyond the walking lanes. Their different heights let+ // the haze cover walls while taller rooflines remain readable.+ {"CBBrnShed", -175, 105, .12f, false},+ {"CBNShack", 0, 94, -.16f, false},+ {"CBNRiverHo", 175, 105, -.08f, false},+ // The comparison centers and central source have low props beneath the+ // cloud. These models never become gameplay objects or path obstacles.+ {"PMCrates01", -155, 0, 0, true},+ {"PMCrates01", 155, 0, 0, true},+ {"PMCrates01", 0, -32, 0, true},+ {"PMBarrel01", -178, 0, 0, true},+ {"PMBarrel01", 178, 0, 0, true},+ {"PMBarrel01", -22, -32, 0, true},+ };+ for (const Sample &sample : samples) {+ RenderObjClass *object = WW3DAssetManager::Get_Instance()->Create_Render_Obj(sample.model);+ if (!object) {+ std::fprintf(stderr, "cloud-preview: inspection model missing: %s\n", sample.model);+ return false;+ }+ AABoxClass bounds;+ object->Get_Obj_Space_Bounding_Box(bounds);+ // Keep actual model bounds clear of all four unchanged walking lanes.+ // Small props occupy the gaps, with six world units maximum half-width+ // in Y. Authored building scale remains unchanged behind the routes.+ const float cosine = std::cos(sample.angle), sine = std::sin(sample.angle);+ const float extentY = std::abs(sine) * bounds.Extent.X + std::abs(cosine) * bounds.Extent.Y;+ const float scale = sample.betweenLanes ? std::min(1.0f, 6.0f / std::max(extentY, .001f)) : 1.0f;+ const float centerX = scale * (cosine * bounds.Center.X - sine * bounds.Center.Y);+ const float centerY = scale * (sine * bounds.Center.X + cosine * bounds.Center.Y);+ const float centerTargetY = centre.y + (sample.betweenLanes ? sample.y+ : std::max(sample.y, 48.0f + 20.0f + extentY));+ const float x = centre.x + sample.x - centerX;+ const float y = centerTargetY - centerY;+ const float ground = TheTerrainLogic->getGroundHeight(centre.x + sample.x, centerTargetY);+ Matrix3D transform(1);+ transform.Rotate_Z(sample.angle);+ transform.Scale(scale);+ transform.Set_Translation(Vector3(x, y, ground - scale * (bounds.Center.Z - bounds.Extent.Z)));+ object->Set_Transform(transform);+ object->Set_Force_Visible(true);+ W3DDisplay::m_3DScene->Add_Render_Object(object);+ scenery.push_back(object);+ std::fprintf(stderr, "cloud-preview: inspection prop=%s centre=(%.1f,%.1f) height=%.1f render-only=1\n",+ sample.model, centre.x + sample.x, centerTargetY, scale * bounds.Extent.Z * 2);+ }+ std::fprintf(stderr, "cloud-preview: inspection yard props=%zu; all four walking lanes remain clear\n", scenery.size());+ return true;+}++void report()+{+ unsigned moving = 0, visits = 0, turns = 0, particles = 0, groundParticles = 0;+ Real health = 0.0f, originalHealth = 0.0f, travelled = 0.0f;+ for (unsigned i = 0; i < FIELD_COUNT; ++i) {+ ParticleSystem *system = TheParticleSystemManager->findParticleSystem(fields[i].id);+ if (system) {+ groundParticles += system->getParticleCount();+ particles += system->getParticleCount();+ }+ }+ for (unsigned i = 0; i < UNIT_COUNT; ++i) {+ const Walker &walker = walkers[i];+ Object *object = TheGameLogic->findObjectByID(walker.id);+ if (object && object->getBodyModule()) health += object->getBodyModule()->getHealth();+ originalHealth += walker.health;+ travelled += walker.distance;+ if (walker.distance > 3.0f) ++moving;+ visits += (walker.enteredFields & 1u) + ((walker.enteredFields >> 1u) & 1u);+ turns += walker.turns;+ }+ std::fprintf(stderr,+ "cloud-preview: frame=%u fields=%u particles=%u units=%u moving=%u "+ "health=%.1f/%.1f travelled=%.1f field-visits=%u/8 turns=%u ground-particles=%u "+ "damage-mode=disabled interaction=%s wake=%.3f bodies=%u cloud-height=%.2f scenario=%s phase=%s style=%s status=%s\n",+ TheGameLogic->getFrame() - startFrame, activeFieldCount, particles, UNIT_COUNT,+ moving, health, originalHealth, travelled, visits, turns, groundParticles,+ CloudPreviewVolume::isInteractionEnabled() ? "on" : "off",+ CloudPreviewVolume::maxDisturbance(), CloudPreviewVolume::activeBodies(), infantryHeight,+ scenarioName(), scenarioPhase(), appearanceName(), failed ? "FAIL" : "OK");+}++bool createField(Field &field);++void invalidateGroundFields(bool fadeIn = false)+{+ // This executable always uses the W3D manager. Refresh only its footprints:+ // a manager reset would also erase a bomb's in-progress release particles.+ static_cast<W3DParticleSystemManager *>(TheParticleSystemManager)->invalidateGroundFields(fadeIn);+}++bool clearField(Field &field)+{+ bool removed = false;+ if (ParticleSystem *system = TheParticleSystemManager->findParticleSystem(field.id)) {+ system->deleteInstance();+ removed = true;+ }+ field.id = INVALID_PARTICLE_SYSTEM_ID;+ return removed;+}++void clearFields()+{+ for (Field &field : fields) clearField(field);+ invalidateGroundFields();+}++void updateFields(bool immediate = false)+{+ CloudPreviewSources::Field source[FIELD_COUNT] = {};+ activeFieldCount = CloudPreviewSources::getFields(source, FIELD_COUNT);+ bool refresh = immediate;+ for (unsigned f = 0; f < FIELD_COUNT; ++f) {+ Field &field = fields[f];+ if (appearance == Appearance::Volumetric || f >= activeFieldCount || source[f].volume.density <= 0) {+ refresh = clearField(field) || refresh;+ continue;+ }+ const auto &state = source[f];+ field.name = state.particleTemplate;+ field.radius = state.originalRadius;+ if (distanceSquared(field.position, state.volume.ground) > 0.0001f) refresh = true;+ field.position = state.volume.ground;+ ParticleSystem *ground = TheParticleSystemManager->findParticleSystem(field.id);+ if (!ground) {+ if (!createField(field)) {+ fail("could not create appearance field");+ continue;+ }+ ground = TheParticleSystemManager->findParticleSystem(field.id);+ if (getScenario() != Scenario::Comparison) {+ // Ground fields are drawn from their emitter descriptor, not+ // individual sprites. Preserve the renderer's authored puddle+ // size before removing particle lifetime from its fade clock.+ // This lets the harmless source timeline own fade-in/out while+ // retaining the game's texture, palette, scatter and bubbling.+ auto mid = [](const GameClientRandomVariable &v) {+ return .5f * (v.getMinimumValue() + v.getMaximumValue());+ };+ const Real half = .5f * mid(ground->m_lifetime);+ const Real rate = mid(ground->m_sizeRate);+ const Real damping = mid(ground->m_sizeRateDamping);+ const Real growth = damping < 1 ? rate * (1 - std::pow(damping, half)) / (1 - damping) : rate * half;+ const Real size = std::max(1.0f, mid(ground->m_startSize) + growth);+ ground->m_startSize.setRange(size, size);+ ground->m_sizeRate.setRange(0, 0);+ ground->m_lifetime.setRange(0, 0);+ ground->stop();+ refresh = true;+ }+ }+ ground->setPosition(&field.position);+ // The production objectless ground-field fade is remaining / 3 seconds.+ // Two frames keep a stopped descriptor alive through the engine update.+ const unsigned lifetime = getScenario() == Scenario::Comparison ? EMITTER_LIFETIME+ : std::max(2u, static_cast<unsigned>(std::ceil(state.volume.density * 3 * LOGICFRAMES_PER_SECOND)));+ ground->setFiniteSystemLifetime(lifetime);+ }+ if (refresh) invalidateGroundFields();+}++void applyCloudStyle()+{+ CloudPreviewVolume::setEnabled(appearance == Appearance::Volumetric);+ styleStartFrame = TheGameLogic->getFrame();+ clearFields();+ updateFields(true);+ std::fprintf(stderr, "cloud-preview: appearance=%s (preview only)\n", appearanceName());+}++bool createField(Field &field)+{+ const ParticleSystemTemplate *tmpl = TheParticleSystemManager->findTemplate(field.name);+ if (!tmpl) return false;+ // This directly creates client particles. No weapon, FXList, OCL or hazard+ // object is fired, so the preview has no contamination damage mechanism.+ ParticleSystem *system = TheParticleSystemManager->createParticleSystem(tmpl, FALSE);+ if (!system) return false;+ field.id = system->getSystemID();+ field.lastParticleFrame = TheGameLogic->getFrame();+ if (system->getPriority() != AREA_EFFECT || !system->m_isGroundAligned+ || (system->getEmisionVolumeType() != ParticleSystemInfo::SPHERE+ && system->getEmisionVolumeType() != ParticleSystemInfo::CYLINDER)) {+ std::fprintf(stderr, "cloud-preview: incompatible field template '%s'\n", field.name);+ return false;+ }+ system->setPosition(&field.position);+ // Retail fields normally receive this radius from their weapon's FX caller.+ // A bare visual emitter must set it itself, on the instance only.+ system->setEmissionVolumeSphereRadius(field.radius);+ system->setEmissionVolumeCylinderRadius(field.radius);+ system->setFiniteSystemLifetime(EMITTER_LIFETIME);+ system->setInitialDelay(0);+ system->setSaveable(FALSE);+ system->start();+ system->trigger();+ std::fprintf(stderr,+ "cloud-preview: visual field=%s id=%d texture=%s type=%d priority=%d "+ "ground-aligned=%d radius=%.1f position=(%.1f,%.1f,%.1f) gameplay-hazard=none\n",+ field.name, static_cast<int>(field.id), system->getParticleTypeName().str(),+ static_cast<int>(system->m_particleType), static_cast<int>(system->getPriority()),+ static_cast<int>(system->m_isGroundAligned), field.radius,+ field.position.x, field.position.y, field.position.z);+ return true;+}++// The preview is client-only. Read the scaled model bounds once, falling back+// to authored collision geometry if the model has not produced bounds yet.+Real visibleInfantryHeight(Object *object)+{+ const GeometryInfo &geometry = object->getGeometryInfo();+ Real result = geometry.getMaxHeightAbovePosition() + geometry.getMaxHeightBelowPosition();+ Real modelHeight = 0;+ if (Drawable *drawable = object->getDrawable()) {+ for (DrawModule **module = drawable->getDrawModules(); module && *module; ++module) {+ const ObjectDrawInterface *draw = (*module)->getObjectDrawInterface();+ OBBoxClass box;+ if (draw && draw->clientOnly_getRenderObjBoundBox(&box)) {+ Vector3 extent;+ box.Compute_Axis_Aligned_Extent(&extent);+ const Real height = 2.0f * extent.Z;+ if (std::isfinite(height) && height >= 5.0f && height <= 60.0f)+ modelHeight = std::max(modelHeight, height);+ }+ }+ }+ if (modelHeight > 0) result = modelHeight;+ return std::max(5.0f, std::min(result, 60.0f));+}++bool createWalker(unsigned index, const ThingTemplate *tmpl, Team *team, const Coord3D ¢re)+{+ Walker &walker = walkers[index];+ const Real lane = (static_cast<Real>(index) - 1.5f) * 32.0f;+ walker.endpoints[0] = groundPosition(centre.x - WALK_HALF_WIDTH, centre.y + lane);+ walker.endpoints[1] = groundPosition(centre.x + WALK_HALF_WIDTH, centre.y + lane);+ const unsigned origin = index & 1u;+ Object *object = TheThingFactory->newObject(tmpl, team,+ MAKE_OBJECT_STATUS_MASK(OBJECT_STATUS_NO_ATTACK));+ if (!object) return false;+ walker.id = object->getID();+ object->setPosition(&walker.endpoints[origin]);+ object->setOrientation(origin ? 3.14159265f : 0.0f);+ object->setStatus(MAKE_OBJECT_STATUS_MASK(OBJECT_STATUS_UNSELECTABLE));+ AIUpdateInterface *ai = object->getAI();+ BodyModuleInterface *body = object->getBodyModule();+ if (!ai || !body) return false;+ for (unsigned endpoint = 0; endpoint < 2; ++endpoint) {+ if (!TheAI->pathfinder()->validMovementPosition(object->getCrusherLevel() > 0,+ object->getLayer(), ai->getLocomotorSet(), &walker.endpoints[endpoint])) {+ std::fprintf(stderr, "cloud-preview: unit %u endpoint %u is not traversable\n",+ index, endpoint);+ return false;+ }+ }+ body->setIndestructible(TRUE);+ for (BehaviorModule **module = object->getBehaviorModules(); *module; ++module) {+ if (CreateModuleInterface *create = (*module)->getCreate()) create->onBuildComplete();+ }+ team->setActive();+ TheAI->pathfinder()->addObjectToPathfindMap(object);+ ai->setAttitude(AI_PASSIVE);+ walker.health = body->getHealth();+ walker.height = visibleInfantryHeight(object);+ walker.radius = std::max(2.0f, object->getGeometryInfo().getBoundingCircleRadius());+ infantryHeight = std::max(infantryHeight, walker.height);+ std::fprintf(stderr, "cloud-preview: walker=%u rendered-height=%.2f interaction-radius=%.2f\n",+ index, walker.height, walker.radius);+ walker.previous = *object->getPosition();+ walker.destination = 1u - origin;+ ai->aiMoveToPosition(&walker.endpoints[walker.destination], CMD_FROM_SCRIPT);+ std::fprintf(stderr,+ "cloud-preview: walker=%u id=%d template=%s health=%.1f passive=1 no-attack=1 "+ "indestructible=1 route=(%.1f,%.1f)-(%.1f,%.1f)\n",+ index, static_cast<int>(walker.id), tmpl->getName().str(), walker.health,+ walker.endpoints[0].x, walker.endpoints[0].y, walker.endpoints[1].x, walker.endpoints[1].y);+ return true;+}++} // namespace++Appearance getAppearance() { return appearance; }++const char *appearanceName()+{+ switch (appearance) {+ case Appearance::Original: return "original";+ case Appearance::Volumetric: return "volumetric";+ }+ return "unknown";+}++void setAppearance(Appearance selected)+{+ if (appearance == selected) return;+ appearance = selected;+ if (initialized) applyCloudStyle();+}++void setScenario(Scenario selected)+{+ if (initialized) {+ clearFields();+ styleStartFrame = TheGameLogic->getFrame();+ }+ CloudPreviewSources::select(selected);+ if (initialized) updateFields(true);+}+Scenario getScenario() { return CloudPreviewSources::selected(); }+const char *scenarioName() { return CloudPreviewSources::name(); }+const char *scenarioPhase() { return CloudPreviewSources::phase(); }+void replayScenario()+{+ if (initialized) {+ clearFields();+ styleStartFrame = TheGameLogic->getFrame();+ }+ CloudPreviewSources::replay();+ if (initialized) updateFields(true);+}+void setLooping(bool value) { CloudPreviewSources::setLooping(value); }+bool isLooping() { return CloudPreviewSources::isLooping(); }++bool initialize()+{+ if (initialized) return !failed;+ failed = false;+ for (unsigned i = 0; i < UNIT_COUNT; ++i) walkers[i].id = INVALID_ID;+ if (!TheGameLogic || !TheGameLogic->isInGame() || TheGameLogic->isInShellGame()+ || !TheTerrainLogic || !ThePartitionManager || !ThePlayerList || !TheThingFactory+ || !TheParticleSystemManager || !TheTacticalView || !TheAI || !TheAI->pathfinder()) {+ fail("scene initialized before map/session subsystems were ready");+ return false;+ }+ const ThingTemplate *infantry = TheThingFactory->findTemplate("AmericaInfantryRanger", FALSE);+ if (!infantry) {+ fail("AmericaInfantryRanger template missing from mounted game data");+ return false;+ }+ for (unsigned i = 0; i < FIELD_COUNT; ++i) {+ const ParticleSystemTemplate *tmpl = TheParticleSystemManager->findTemplate(fields[i].name);+ if (!tmpl) {+ std::fprintf(stderr, "cloud-preview: missing field template '%s'\n", fields[i].name);+ fail("required retail contamination template unavailable");+ return false;+ }+ }+ Region3D extent;+ TheTerrainLogic->getExtent(&extent);+ const Real width = extent.hi.x - extent.lo.x, height = extent.hi.y - extent.lo.y;+ if (width < 900.0f || height < 600.0f) {+ std::fprintf(stderr,+ "cloud-preview: scene readiness frame=%u loading=%d extent=(%.1f,%.1f)-(%.1f,%.1f)\n",+ TheGameLogic->getFrame(), static_cast<int>(TheGameLogic->isLoadingMap()),+ extent.lo.x, extent.lo.y, extent.hi.x, extent.hi.y);+ fail("preview map is too small for the two cloud fields and walking routes");+ return false;+ }+ const Coord3D centre = groundPosition((extent.lo.x + extent.hi.x) * 0.5f,+ (extent.lo.y + extent.hi.y) * 0.5f);+ Player *player = ThePlayerList->getLocalPlayer();+ Team *team = player->getDefaultTeam();++ // The executable owns this dedicated session. Remove the skirmish startup+ // structures/units without death weapons, then retain only our samples.+ if (TheVictoryConditions) TheVictoryConditions->setVictoryConditions(0);+ for (Object *object = TheGameLogic->getFirstObject(); object; ) {+ Object *next = object->getNextObject();+ TheGameLogic->destroyObject(object);+ object = next;+ }+ TheParticleSystemManager->reset();+ TheParticleSystemManager->setLocalPlayerIndex(player->getPlayerIndex());+ ThePartitionManager->revealMapForPlayerPermanently(player->getPlayerIndex());+ ThePartitionManager->refreshShroudForLocalPlayer();+ TheTacticalView->setAngleAndPitchToDefault();+ TheTacticalView->lookAt(¢re);+ TheTacticalView->setZoomToHeight(520.0f);+ if (TheControlBar) TheControlBar->switchControlBarStage(CONTROL_BAR_STAGE_HIDDEN);+ if (TheInGameUI) {+ // Camera pan/rotate/zoom also uses this input gate. Sample units are+ // unselectable and cannot attack, so leave camera input available.+ TheInGameUI->setInputEnabled(TRUE);+ TheInGameUI->setSuperweaponDisplayEnabledByScript(FALSE);+ }++ startFrame = TheGameLogic->getFrame();+ lastReport = startFrame;+ infantryHeight = 0;+ lastFrame = ~0u;+ initialized = true; // Partial construction is also cleaned by shutdown().+ if (!createScenery(centre)) {+ fail("could not create inspection-yard scenery");+ return false;+ }+ for (unsigned i = 0; i < FIELD_COUNT; ++i) {+ fields[i].position = groundPosition(centre.x + (i ? FIELD_OFFSET : -FIELD_OFFSET), centre.y);+ fields[i].id = INVALID_PARTICLE_SYSTEM_ID;+ }+ for (unsigned i = 0; i < UNIT_COUNT; ++i) {+ if (!createWalker(i, infantry, team, centre)) {+ fail("could not create a walking preview unit");+ return false;+ }+ }+ if (!CloudPreviewVolume::initialize(fields[0].position, fields[1].position)) {+ fail("could not initialize the isolated volume renderer");+ return false;+ }+ CloudPreviewVolume::setInfantryHeight(infantryHeight);+ if (!CloudPreviewSources::initialize(centre, infantryHeight)) {+ fail("could not initialize source scenarios");+ return false;+ }+ applyCloudStyle();+ std::fprintf(stderr,+ "cloud-preview: initialized centre=(%.1f,%.1f) extent=(%.1f,%.1f)-(%.1f,%.1f) "+ "field-radius=%.1f damage-simulation=absent\n",+ centre.x, centre.y, extent.lo.x, extent.lo.y, extent.hi.x, extent.hi.y, FIELD_RADIUS);+ report();+ return !failed;+}++void update()+{+ if (!initialized || !TheGameLogic || !TheParticleSystemManager) return;+ const unsigned frame = TheGameLogic->getFrame();+ if (frame == lastFrame) return;+ if (frame < startFrame) {+ fail("preview session was reset while its scene was active");+ return;+ }+ const Real dt = lastFrame != ~0u && frame > lastFrame+ ? static_cast<Real>(frame - lastFrame) / LOGICFRAMES_PER_SECOND : 0.0f;+ lastFrame = frame;+ CloudPreviewFlow::Body bodies[UNIT_COUNT] = {};+ unsigned bodyCount = 0;+ if (appearance == Appearance::Volumetric && frame - styleStartFrame >= MOTION_GRACE+ && !CloudPreviewVolume::validationPassed())+ fail("volume rendering or scene-depth capture failed");+ for (unsigned i = 0; i < FIELD_COUNT; ++i) {+ // Source fields deliberately use stopped descriptors for the production+ // terrain renderer; only the steady comparison needs sprite starvation+ // checks. The source controller owns field creation and expiry below.+ if (appearance == Appearance::Volumetric || getScenario() != Scenario::Comparison) continue;+ ParticleSystem *system = TheParticleSystemManager->findParticleSystem(fields[i].id);+ if (!system || system->isDestroyed()) {+ fail("a preview particle system disappeared");+ continue;+ }+ // Keep this exact instance alive. The field renderer reads this remaining+ // lifetime when there is deliberately no gameplay hazard object to follow.+ system->setFiniteSystemLifetime(EMITTER_LIFETIME);+ // The ground renderer draws a stable procedural footprint and can limit+ // an emitter to one live particle. A normal gap between its death and+ // the next burst is not a missing field; require sustained starvation.+ if (system->getParticleCount() > 0) fields[i].lastParticleFrame = frame;+ if (frame - fields[i].lastParticleFrame > 2 * LOGICFRAMES_PER_SECOND)+ fail("a preview field is not emitting particles");+ }+ for (unsigned i = 0; i < UNIT_COUNT; ++i) {+ Walker &walker = walkers[i];+ Object *object = TheGameLogic->findObjectByID(walker.id);+ if (!object || object->isDestroyed() || !object->getBodyModule()) {+ fail("a walking preview unit disappeared");+ continue;+ }+ if (std::fabs(object->getBodyModule()->getHealth() - walker.health) > 0.01f)+ fail("preview unit health changed");+ const Coord3D &position = *object->getPosition();+ walker.distance += std::sqrt(distanceSquared(position, walker.previous));+ CloudPreviewFlow::Body &body = bodies[bodyCount++];+ body.x = position.x; body.y = position.y; body.z = position.z;+ body.radius = walker.radius; body.height = walker.height;+ if (dt > 0) {+ body.vx = (position.x - walker.previous.x) / dt;+ body.vy = (position.y - walker.previous.y) / dt;+ // A teleport must not inject an unbounded impulse into a visual wake.+ if (body.vx * body.vx + body.vy * body.vy > 100.0f * 100.0f)+ body.vx = body.vy = 0;+ }+ walker.previous = position;+ for (unsigned f = 0; f < FIELD_COUNT; ++f) {+ if (distanceSquared(position, fields[f].position) <= FIELD_RADIUS * FIELD_RADIUS)+ walker.enteredFields |= 1u << f;+ }+ if (distanceSquared(position, walker.endpoints[walker.destination]) <= ARRIVE_RADIUS * ARRIVE_RADIUS) {+ walker.destination ^= 1u;+ ++walker.turns;+ if (AIUpdateInterface *ai = object->getAI())+ ai->aiMoveToPosition(&walker.endpoints[walker.destination], CMD_FROM_SCRIPT);+ }+ }+ CloudPreviewVolume::setBodies(bodies, bodyCount);+ CloudPreviewSources::update(dt);+ if (!CloudPreviewSources::valid()) fail("source scenario validation failed");+ updateFields();+ CloudPreviewVolume::update(static_cast<float>(frame - startFrame) / LOGICFRAMES_PER_SECOND);+ for (Object *object = TheGameLogic->getFirstObject(); object; object = object->getNextObject()) {+ if (!object->isDestroyed() && object->isKindOf(KINDOF_CLEANUP_HAZARD))+ fail("unexpected gameplay hazard object exists in preview");+ }+ if (TheControlBar) TheControlBar->switchControlBarStage(CONTROL_BAR_STAGE_HIDDEN);+ if (frame - lastReport >= REPORT_INTERVAL) {+ lastReport = frame;+ report();+ }+}++bool validationPassed()+{+ if (!initialized || !TheGameLogic || !TheParticleSystemManager) return false;+ update();+ if (!CloudPreviewVolume::validationPassed()) fail("volume renderer did not pass validation");+ if (TheGameLogic->getFrame() - startFrame >= MOTION_GRACE) {+ for (unsigned i = 0; i < UNIT_COUNT; ++i)+ if (walkers[i].distance <= 3.0f) fail("a preview unit did not move after three seconds");+ }+ report();+ return !failed;+}++void shutdown()+{+ CloudPreviewSources::shutdown();+ CloudPreviewVolume::shutdown();+ clearScenery();+ if (!initialized) return;+ if (TheParticleSystemManager) {+ clearFields();+ }+ if (TheGameLogic) {+ for (unsigned i = 0; i < UNIT_COUNT; ++i) {+ if (walkers[i].id == INVALID_ID) continue;+ if (Object *object = TheGameLogic->findObjectByID(walkers[i].id))+ TheGameLogic->destroyObject(object);+ }+ }+ std::memset(walkers, 0, sizeof(walkers));+ initialized = false;+}++} // namespace CloudPreviewScenediff --git a/GeneralsMD/Code/Tools/CloudPreviewScene.h b/GeneralsMD/Code/Tools/CloudPreviewScene.hnew file mode 100644index 000000000..ca2c3c66a--- /dev/null+++ b/GeneralsMD/Code/Tools/CloudPreviewScene.h@@ -0,0 +1,43 @@+// Standalone cloud preview scene; never linked into the game executable.+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.+#pragma once++namespace CloudPreviewScene {++// Call once after a real, non-shell map session has finished loading. Requires+// the ordinary logic, terrain, players, pathfinder, particles and tactical view.+// Replaces that preview session's initial objects with harmless visual samples,+// four unobstructed infantry routes, and render-only structures/props. The map's+// inspection pond is ordinary renderer water, without gameplay water damage.+bool initialize();++// Preview-only comparison; also valid before initialize(). Never saves a setting.+enum class Appearance { Original, Volumetric };+void setAppearance(Appearance appearance);+Appearance getAppearance();+const char *appearanceName();++enum class Scenario {+ Comparison, Tractor, AnthraxBomb, AnthraxGamma, ToxinBuilding,+ NuclearMissile, NuclearCannon, NuclearReactor+};+void setScenario(Scenario scenario);+Scenario getScenario();+const char *scenarioName();+const char *scenarioPhase();+void replayScenario();+void setLooping(bool enabled);+bool isLooping();++// Call before the host's normal engine update. Repeated calls on the same logic+// frame are harmless. The engine remains responsible for simulation/rendering.+void update();++// Reports particle presence, intact unit health and (after three seconds) motion.+// Closing an interactive preview before it has had time to move is permitted.+bool validationPassed();++// Call while engine subsystems still exist, before their teardown.+void shutdown();++} // namespace CloudPreviewScenediff --git a/GeneralsMD/Code/Tools/CloudPreviewSources.cpp b/GeneralsMD/Code/Tools/CloudPreviewSources.cppnew file mode 100644index 000000000..b7dc1c167--- /dev/null+++ b/GeneralsMD/Code/Tools/CloudPreviewSources.cpp@@ -0,0 +1,413 @@+// Source choreography for the harmless cloud-preview laboratory.+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.+#include "PreRTS.h"+#include "CloudPreviewSources.h"+#include "CloudPreviewVolume.h"+#include "GameClient/InGameUI.h"+#include "GameClient/ParticleSys.h"+#include "W3DDevice/GameClient/W3DDisplay.h"+#include "W3DDevice/GameClient/W3DScene.h"+#include "WW3D2/assetmgr.h"+#include "WW3D2/hanim.h"+#include "WW3D2/htree.h"+#include "WW3D2/rendobj.h"+#include "WWMath/matrix3d.h"+#include <algorithm>+#include <cmath>+#include <cstdio>+#include <cstring>+#include <map>+#include <string>+#include <strings.h>+#include <vector>++namespace CloudPreviewSources {+namespace {+using Scenario = CloudPreviewScene::Scenario;+struct Definition {+ const char *name;+ const char *model;+ const char *rubble;+ const char *particleTemplate;+ float radius, palette, buildup, linger, dissipate;+};+// Radii are the retail field radii. Timing is deliberately compressed for the+// inspection loop; these values never replace a gameplay weapon or lifetime.+const Definition definitions[] = {+ {"Cloud comparison", nullptr, nullptr, nullptr, 115, 0, 0, 0, 0},+ {"Toxin Tractor / Contaminate", "UVToxinTrk", nullptr, "PoisonFieldMedium", 80, 0, 8, 10, 6},+ {"Anthrax Bomb", "AVBomber_B", nullptr, "AnthraxFieldLarge", 300, 2, 5, 12, 7},+ {"Dr. Thrax / Gamma Bomb", "AVBomber_B", nullptr, "GC_Chem_AnthraxFieldGammaLarge", 300, 3, 5, 12, 7},+ {"Dr. Thrax / SCUD Storm destruction", "UBScudStrm", "UBScudStrm_E", "PoisonFieldMedium", 80, 0, 3, 12, 7},+ {"Nuclear missile", "NBNRocket", nullptr, "RadiationFieldLarge", 200, 1, 6, 12, 8},+ {"Nuclear cannon", "NVNukeCn", nullptr, "RadiationFieldMedium", 50, 1, 3, 10, 6},+ {"Nuclear reactor destruction", "NBPwrPlant", "NBPwrPlant_E", "RadiationFieldMedium", 50, 1, 3, 12, 7}+};+float sourceFringes[sizeof(definitions) / sizeof(definitions[0])] = {};+float comparisonFringes[2] = {};+std::map<std::string, float> templateFringes;+Scenario scenario = Scenario::Comparison;+Coord3D centre = {};+float fullHeight = 18.0f, age = 0, nextSpray = 0;+bool ready = false, healthy = true, looping = true, released = false, delayedBurst = false;+RenderObjClass *prop = nullptr, *projectile = nullptr;+std::vector<ParticleSystemID> effects;+Field fields[2] = {};+unsigned fieldCount = 0;+const float Arrival = 2.0f;++const Definition &definition() { return definitions[static_cast<unsigned>(scenario)]; }+float smooth(float value) { value = std::clamp(value, 0.0f, 1.0f); return value * value * (3 - 2 * value); }+void fail(const char *reason, const char *asset)+{+ if (healthy) std::fprintf(stderr, "cloud-preview: source FAIL: %s: %s\n", reason, asset);+ healthy = false;+}++float cacheTemplateFringe(const char *name)+{+ const auto cached = templateFringes.find(name);+ if (cached != templateFringes.end()) return cached->second;+ const ParticleSystemTemplate *tmpl = TheParticleSystemManager+ ? TheParticleSystemManager->findTemplate(name) : nullptr;+ if (!tmpl) { fail("footprint particle template missing", name); return 0; }+ // The template's info base is protected. A temporary unstarted instance+ // exposes the same loaded values without changing the engine's public API.+ ParticleSystem *sample = TheParticleSystemManager->createParticleSystem(tmpl, FALSE);+ if (!sample) { fail("footprint particle descriptor creation failed", name); return 0; }+ sample->stop();+ const auto midpoint = [](const GameClientRandomVariable &value) {+ return 0.5f * (value.getMinimumValue() + value.getMaximumValue());+ };+ // Match collectGroundFields' half-life puddle size, using the loaded values+ // after INI overlays and frame-rate conversion. Each scattered centre can+ // reach the hazard radius; its rotated square extends sqrt(2) half-sizes+ // farther, including the renderer's maximum 4% breathing expansion. This+ // conservative visual fringe is separate from the unchanged hazard radius.+ const float halfLife = 0.5f * midpoint(sample->m_lifetime);+ const float rate = midpoint(sample->m_sizeRate);+ const float damping = midpoint(sample->m_sizeRateDamping);+ const float growth = damping < 1.0f+ ? rate * (1.0f - std::pow(damping, halfLife)) / (1.0f - damping) : rate * halfLife;+ const float halfSize = std::max(midpoint(sample->m_startSize) + growth, 1.0f);+ sample->deleteInstance();+ const float fringe = std::sqrt(2.0f) * 1.04f * halfSize;+ if (!std::isfinite(fringe) || fringe < 0) {+ fail("invalid original particle footprint", name);+ return 0;+ }+ templateFringes.emplace(name, fringe);+ std::fprintf(stderr, "cloud-preview: footprint template=%s puddle-half-size=%.2f fringe=%.2f\n",+ name, halfSize, fringe);+ return fringe;+}++void removeProp(RenderObjClass *&object)+{+ if (object) { object->Remove(); object->Release_Ref(); object = nullptr; }+}+void clearVisuals()+{+ removeProp(prop); removeProp(projectile);+ if (TheParticleSystemManager) for (ParticleSystemID id : effects)+ if (ParticleSystem *system = TheParticleSystemManager->findParticleSystem(id))+ // destroy() only stops emission; deleteInstance() also removes all+ // live particles, so replay/switching is clean even while paused.+ system->deleteInstance();+ effects.clear();+}++bool propPartMatches(const char *name, const char *mask, bool numbered)+{+ if (!name) return false;+ // Mesh names include their model prefix, e.g. NVNUKECN.MUZZLEFX01.+ if (const char *separator = std::strrchr(name, '.')) name = separator + 1;+ const size_t length = std::strlen(mask);+ if (strncasecmp(name, mask, length) != 0) return false;+ const char *suffix = name + length;+ if (!*suffix) return true;+ if (!numbered) return false;+ // WeaponMuzzleFlash names expand to numbered bones in W3DModelDraw.+ for (; *suffix; ++suffix) if (*suffix < '0' || *suffix > '9') return false;+ return true;+}++void setPropBranchHidden(RenderObjClass *object, bool hidden)+{+ object->Set_Hidden(hidden);+ for (int i = 0; i < object->Get_Num_Sub_Objects(); ++i)+ if (RenderObjClass *part = object->Get_Sub_Object(i)) {+ setPropBranchHidden(part, hidden);+ part->Release_Ref();+ }+}++void setPropPartHidden(RenderObjClass *object, const char *mask, bool hidden, bool numbered = false)+{+ const HTreeClass *tree = object->Get_HTree();+ std::vector<int> roots;+ if (tree) for (int bone = 1; bone < tree->Num_Pivots(); ++bone)+ if (propPartMatches(tree->Get_Bone_Name(bone), mask, numbered)) roots.push_back(bone);++ // Authored HideSubObject also controls meshes attached below that mesh's+ // bone. Use the pointer overload: Get_Num_Sub_Objects spans every LOD, so+ // treating its index as a LOD-zero index can address the wrong attachment.+ const int count = object->Get_Num_Sub_Objects();+ for (int i = 0; i < count; ++i)+ if (RenderObjClass *part = object->Get_Sub_Object(i)) {+ if (tree && propPartMatches(part->Get_Name(), mask, numbered)) {+ const int bone = object->Get_Sub_Object_Bone_Index(part);+ if (bone > 0 && bone < tree->Num_Pivots()) roots.push_back(bone);+ }+ part->Release_Ref();+ }++ for (int i = 0; i < count; ++i)+ if (RenderObjClass *part = object->Get_Sub_Object(i)) {+ bool matched = propPartMatches(part->Get_Name(), mask, numbered);+ int bone = object->Get_Sub_Object_Bone_Index(part);+ for (int depth = 0; !matched && tree && bone > 0+ && bone < tree->Num_Pivots() && depth < tree->Num_Pivots(); ++depth) {+ matched = std::find(roots.begin(), roots.end(), bone) != roots.end();+ if (!matched) bone = tree->Get_Parent_Index(bone);+ }+ if (matched) setPropBranchHidden(part, hidden);+ else if (part->Get_Num_Sub_Objects()) setPropPartHidden(part, mask, hidden, numbered);+ part->Release_Ref();+ }+}++RenderObjClass *makeProp(const char *model)+{+ if (!model) return nullptr;+ RenderObjClass *object = WW3DAssetManager::Get_Instance()->Create_Render_Obj(model);+ if (!object) { fail("model missing", model); return nullptr; }+ object->Set_Force_Visible(true);+ if (std::strcmp(model, "UVToxinTrk") == 0) {+ setPropPartHidden(object, "Turret", false);+ setPropPartHidden(object, "TurretUP01", true);+ setPropPartHidden(object, "TurretUP02", true);+ }+ if (std::strcmp(model, "NVNukeCn") == 0) {+ setPropPartHidden(object, "TURRET01", false);+ setPropPartHidden(object, "TURRETFRONT", true);+ setPropPartHidden(object, "TURRETBACK", true);+ // The source explosion is rendered separately; no weapon fires this+ // prop, so its muzzle flash must stay hidden for the entire scenario.+ setPropPartHidden(object, "MuzzleFX", true, true);+ }+ W3DDisplay::m_3DScene->Add_Render_Object(object);+ return object;+}+void place(RenderObjClass *object, float x, float y, float z, float angle = 0, bool downward = false)+{+ if (!object) return;+ Matrix3D transform(1);+ transform.Rotate_Z(angle);+ if (downward) transform.Rotate_X(3.14159265f);+ transform.Set_Translation(Vector3(x, y, z));+ object->Set_Transform(transform);+}+void emit(const char *particle, float z = 0, float x = 0, float y = 0, float angle = 0)+{+ const ParticleSystemTemplate *tmpl = TheParticleSystemManager->findTemplate(particle);+ if (!tmpl) { fail("particle template missing", particle); return; }+ ParticleSystem *system = TheParticleSystemManager->createParticleSystem(tmpl, FALSE);+ if (!system) { fail("particle creation failed", particle); return; }+ Coord3D position = centre; position.x += x; position.y += y; position.z += z;+ Matrix3D transform(1); transform.Rotate_Z(angle);+ transform.Set_Translation(Vector3(position.x, position.y, position.z));+ system->setLocalTransform(&transform);+ system->setSaveable(FALSE);+ // Keep authored particle motion, emission and lifetime. Only an accidentally+ // perpetual emitter is bounded; the entire scenario owns and cleans it up.+ if (system->isSystemForever()) system->setFiniteSystemLifetime(1);+ system->start(); system->trigger();+ effects.push_back(system->getSystemID());+}+void nuclearBurst(bool large)+{+ const char *largeNames[] = {"NukeFlare", "NukeMushroomExplosion", "NukeMushroomCloudRing",+ "NukeRing", "NukeBlastWave", "NukeShockwaveInverted", "NukeMushroomStem",+ "NukeShockwave", "NukeMushroomRing"};+ const char *smallNames[] = {"NukeCannonFlare", "NukeCannonMushroomExplosion", "NukeCannonMushroomCloudRing",+ "NukeCannonRing", "NukeCannonBlastWave", "NukeCannonShockwaveInverted", "NukeCannonMushroomStem",+ "NukeCannonShockwave", "NukeCannonMushroomRing"};+ for (unsigned i = 0; i < 9; ++i) emit(large ? largeNames[i] : smallNames[i]);+}+void release()+{+ released = true;+ switch (scenario) {+ case Scenario::AnthraxBomb:+ removeProp(prop);+ emit("AnthraxBombExplosion"); emit("AnthraxBombSpray"); emit("AnthraxBombLenzflare");+ break;+ case Scenario::AnthraxGamma:+ removeProp(prop);+ emit("AnthraxGammaBombExplosion"); emit("AnthraxGammaBombSpray"); emit("AnthraxGammaBombLenzflare");+ break;+ case Scenario::ToxinBuilding:+ removeProp(prop); prop = makeProp(definition().rubble);+ emit("BombTruckHEBioExplosionArms", 2); emit("BombTruckHEBioLenzFlare", 10);+ emit("BombTruckHEBioShockwave", 1);+ break;+ case Scenario::NuclearMissile: removeProp(prop); nuclearBurst(true); break;+ case Scenario::NuclearCannon: removeProp(projectile); nuclearBurst(false); break;+ case Scenario::NuclearReactor:+ removeProp(prop); prop = makeProp(definition().rubble); nuclearBurst(false); break;+ default: break;+ }+ std::fprintf(stderr, "cloud-preview: source-release scenario=%s visual-only=1\n", definition().name);+}+void updateProps()+{+ float approach = smooth(age / Arrival);+ if (scenario == Scenario::AnthraxBomb || scenario == Scenario::AnthraxGamma)+ place(prop, centre.x, centre.y, centre.z + 260 * (1 - approach) + 5, 0, true);+ else if (scenario == Scenario::NuclearMissile)+ place(prop, centre.x, centre.y, centre.z + 350 * (1 - approach) + 10, 0, true);+ else if (scenario == Scenario::Tractor) {+ place(prop, centre.x, centre.y - 35, centre.z, 1.57079633f);+ if (prop) {+ int turret = prop->Get_Bone_Index("Turret");+ if (turret > 0) {+ Matrix3D turn(1);+ turn.Rotate_Z(std::max(0.0f, std::min(age - Arrival, definition().buildup)) * 3.2f - 1.57079633f);+ prop->Capture_Bone(turret); prop->Control_Bone(turret, turn);+ }+ }+ }+ else if (scenario == Scenario::NuclearCannon) {+ place(prop, centre.x - 180, centre.y - 65, centre.z, .35f);+ place(projectile, centre.x - 180 * (1 - approach), centre.y - 65 * (1 - approach),+ centre.z + 12 + std::sin(approach * 3.14159265f) * 150, .35f);+ } else place(prop, centre.x, centre.y, centre.z);+}+void updateVolume()+{+ CloudPreviewVolume::FieldState state[2] = {};+ if (scenario == Scenario::Comparison) {+ for (unsigned i = 0; i < 2; ++i) {+ state[i].ground = centre; state[i].ground.x += i ? 155 : -155;+ state[i].radius = 115; state[i].height = fullHeight;+ state[i].density = state[i].formation = 1; state[i].palette = float(i);+ state[i].fringe = comparisonFringes[i];+ fields[i] = {state[i], i ? "RadiationFieldLarge" : "PoisonFieldLarge", 115, 60};+ }+ fieldCount = 2;+ CloudPreviewVolume::setFields(state, fieldCount);+ return;+ }+ const Definition &d = definition();+ float t = age - Arrival;+ float formation = smooth(t / d.buildup);+ float decay = smooth((t - d.buildup - d.linger) / d.dissipate);+ state[0].ground = centre;+ state[0].radius = d.radius;+ state[0].height = fullHeight;+ state[0].density = smooth(t / .6f) * (1 - decay);+ state[0].palette = d.palette; state[0].formation = formation;+ state[0].release = t >= 0 && t < d.buildup ? 1 - 0.65f * formation : 0;+ state[0].fringe = sourceFringes[static_cast<unsigned>(scenario)];+ fields[0] = {state[0], d.particleTemplate, d.radius,+ std::max(0.0f, Arrival + d.buildup + d.linger + d.dissipate - age)};+ if (d.palette >= 0.5f && d.palette < 1.5f) {+ // Fallout appears gradually across the entire footprint, rather than+ // advancing from the impact point like toxin. Keep the original-effect+ // descriptor above on its existing clock for an unchanged comparison.+ state[0].density = formation * (1 - decay);+ state[0].formation = 1;+ }+ fieldCount = 1;+ CloudPreviewVolume::setFields(state, fieldCount);+}+} // namespace++unsigned getFields(Field *out, unsigned capacity)+{+ if (!out) return 0;+ const unsigned count = std::min(capacity, fieldCount);+ std::copy_n(fields, count, out);+ return count;+}++bool initialize(const Coord3D &position, float height)+{+ centre = position; fullHeight = height; ready = true; healthy = true;+ templateFringes.clear();+ comparisonFringes[0] = cacheTemplateFringe("PoisonFieldLarge");+ comparisonFringes[1] = cacheTemplateFringe("RadiationFieldLarge");+ for (unsigned i = 1; i < sizeof(definitions) / sizeof(definitions[0]); ++i)+ sourceFringes[i] = cacheTemplateFringe(definitions[i].particleTemplate);+ if (!healthy) { ready = false; return false; }+ replay();+ return healthy;+}+void shutdown() { clearVisuals(); fieldCount = 0; ready = false; }+void replay()+{+ age = nextSpray = 0; released = delayedBurst = false;+ if (!ready) return;+ clearVisuals();+ CloudPreviewVolume::resetFlow();+ prop = makeProp(definition().model);+ if (scenario == Scenario::NuclearCannon) {+ projectile = makeProp("AVTankShel");+ if (prop) if (HAnimClass *animation = WW3DAssetManager::Get_Instance()->Get_HAnim("NVNukeCn.NVNukeCn")) {+ prop->Set_Animation(animation, float(animation->Get_Num_Frames() - 1), RenderObjClass::ANIM_MODE_MANUAL);+ animation->Release_Ref();+ }+ }+ updateProps(); updateVolume();+ std::fprintf(stderr, "cloud-preview: source-replay scenario=%s loop=%d\n", name(), int(looping));+ if (TheInGameUI) {+ UnicodeString message; message.translate(AsciiString(name()));+ TheInGameUI->message(message);+ }+}+void select(Scenario value)+{+ if (static_cast<unsigned>(value) >= sizeof(definitions) / sizeof(definitions[0])) return;+ scenario = value; replay();+}+Scenario selected() { return scenario; }+const char *name() { return definition().name; }+const char *phase()+{+ if (scenario == Scenario::Comparison) return "steady clouds";+ if (age < Arrival) return "approach / ready";+ float t = age - Arrival;+ if (t < definition().buildup) return scenario == Scenario::Tractor ? "spraying / buildup" : "release / buildup";+ if (t < definition().buildup + definition().linger) return "lingering";+ if (t < definition().buildup + definition().linger + definition().dissipate) return "dissipating";+ return "clear / B to replay";+}+void update(float deltaSeconds)+{+ if (!ready || scenario == Scenario::Comparison || deltaSeconds <= 0) return;+ age += deltaSeconds;+ float t = age - Arrival;+ if (t >= 0 && !released) release();+ if (scenario == Scenario::Tractor && t >= 0 && t < definition().buildup && t >= nextSpray) {+ // The nozzle's outward particles are from the game's own template.+ // Rotating the source around the tank illustrates Contaminate's sweep.+ float angle = t * 3.2f;+ emit("ToxinSpray", 12, std::cos(angle) * 8, -35 + std::sin(angle) * 8, angle);+ nextSpray = t + .12f;+ }+ if (scenario == Scenario::ToxinBuilding && t >= .1f && !delayedBurst) {+ emit("BombTruckHEBioExplosionTrailArms", 25); delayedBurst = true;+ }+ updateProps(); updateVolume();+ if (looping && t > definition().buildup + definition().linger + definition().dissipate + 2)+ replay();+ // Finished effects are engine-owned; keep our cleanup list small in long runs.+ effects.erase(std::remove_if(effects.begin(), effects.end(), [](ParticleSystemID id) {+ return !TheParticleSystemManager->findParticleSystem(id);+ }), effects.end());+}+void setLooping(bool value) { looping = value; }+bool isLooping() { return looping; }+bool valid() { return healthy; }+} // namespace CloudPreviewSourcesdiff --git a/GeneralsMD/Code/Tools/CloudPreviewSources.h b/GeneralsMD/Code/Tools/CloudPreviewSources.hnew file mode 100644index 000000000..3f098cecb--- /dev/null+++ b/GeneralsMD/Code/Tools/CloudPreviewSources.h@@ -0,0 +1,29 @@+// Visual source events for the isolated preview; no weapons or gameplay objects.+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.+#pragma once+#include "CloudPreviewScene.h"+#include "CloudPreviewVolume.h"+struct Coord3D;+namespace CloudPreviewSources {+struct Field {+ CloudPreviewVolume::FieldState volume;+ const char *particleTemplate;+ float originalRadius;+ float secondsLeft;+};++// Copies the current source fields, returning the number written (at most two).+// Comparison fields keep 60 seconds available; source fields count down to clear.+unsigned getFields(Field *out, unsigned capacity);+bool initialize(const Coord3D ¢re, float infantryHeight);+void shutdown();+void update(float deltaSeconds);+void select(CloudPreviewScene::Scenario scenario);+CloudPreviewScene::Scenario selected();+const char *name();+const char *phase();+void replay();+void setLooping(bool enabled);+bool isLooping();+bool valid();+}diff --git a/GeneralsMD/Code/Tools/CloudPreviewVolume.cpp b/GeneralsMD/Code/Tools/CloudPreviewVolume.cppnew file mode 100644index 000000000..64813401d--- /dev/null+++ b/GeneralsMD/Code/Tools/CloudPreviewVolume.cpp@@ -0,0 +1,157 @@+// Isolated preview scene adapter; material and simulation code are shared.+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.+#include "PreRTS.h"+#include "CloudPreviewVolume.h"+#include "CloudPreviewColors.h"+#include "W3DDevice/GameClient/W3DDisplay.h"+#include "W3DDevice/GameClient/W3DScene.h"+#include "WW3D2/rendobj.h"+#include "WW3D2/rinfo.h"+#include "WW3D2/shader.h"+#include "WW3D2/ww3d.h"+#include "WWMath/aabox.h"+#include "WWMath/sphere.h"+#include <algorithm>+#include <cmath>+#include <cstdio>++namespace CloudPreviewVolume {+namespace {+constexpr float MaximumDisplacement = 18.0f;+SdlHazardCloud::Layer layer;+FieldState fieldStates[2] = {};+unsigned fieldCount = 0;+bool enabled = false, everEnabled = false, failed = false;++void renderVolume()+{+ for (unsigned i = 0; i < 4; ++i) {+ const auto &p = CloudPreviewColors::get(i);+ layer.setPalette(i, {{p.main.r, p.main.g, p.main.b},+ {p.shadow.r, p.shadow.g, p.shadow.b}, p.brightness, p.transparency});+ }+ layer.render();+}++class VolumeRenderObject : public RenderObjClass+{+public:+ VolumeRenderObject() { Set_Force_Visible(true); }+ RenderObjClass *Clone() const override { return new VolumeRenderObject; }+ int Class_ID() const override { return CLASSID_LAST + 47; }+ const char *Get_Name() const override { return "CloudPreviewVolume"; }+ void fieldsChanged() { Invalidate_Cached_Bounding_Volumes(); }+ void Get_Obj_Space_Bounding_Box(AABoxClass &box) const override+ {+ if (!fieldCount) {+ box.Center.Set(0, 0, 0);+ box.Extent.Set(1, 1, 1);+ return;+ }+ Vector3 low, high;+ for (unsigned i = 0; i < fieldCount; ++i) {+ const FieldState &field = fieldStates[i];+ const float radius = field.radius + field.fringe + MaximumDisplacement;+ const Vector3 fieldLow(field.ground.x - radius, field.ground.y - radius, field.ground.z);+ const float visibleHeight = field.height+ * (field.palette >= 0.5f && field.palette < 1.5f ? 2.9f : 1.0f);+ const Vector3 fieldHigh(field.ground.x + radius, field.ground.y + radius,+ field.ground.z + visibleHeight);+ if (!i) { low = fieldLow; high = fieldHigh; }+ else for (unsigned axis = 0; axis < 3; ++axis) {+ low[axis] = std::min(low[axis], fieldLow[axis]);+ high[axis] = std::max(high[axis], fieldHigh[axis]);+ }+ }+ box.Center = (low + high) * 0.5f;+ box.Extent = (high - low) * 0.5f;+ }+ void Get_Obj_Space_Bounding_Sphere(SphereClass &sphere) const override+ {+ AABoxClass box;+ Get_Obj_Space_Bounding_Box(box);+ sphere.Center = box.Center;+ sphere.Radius = box.Extent.Length();+ }+ void Render(RenderInfoClass &) override+ {+ if (!enabled || failed || !W3DDisplay::m_3DScene) return;+ if (ShaderClass::Is_Backface_Culling_Inverted()+ || W3DDisplay::m_3DScene->getCustomPassMode() != SCENE_PASS_DEFAULT) return;+ if (WW3D::Are_Static_Sort_Lists_Enabled()) {+ // The scene flushes opaque terrain/NPC geometry before static lists.+ // Level 1 is their last bin, keeping the capture after other statics.+ WW3D::Add_To_Static_Sort_List(this, 1);+ return;+ }+ renderVolume();+ }+};+VolumeRenderObject *renderObject = nullptr;++} // namespace++bool initialize(const Coord3D &toxin, const Coord3D &radiation)+{+ if (renderObject) return validationPassed();+ failed = false;+ enabled = everEnabled = false;+ if (!W3DDisplay::m_3DScene || !layer.initialize()) return false;+ layer.setInteractionEnabled(true);+ layer.setHeatEnabled(true);+ const float centreX = (toxin.x + radiation.x) * 0.5f;+ const float centreY = (toxin.y + radiation.y) * 0.5f;+ layer.setFlowDomain(centreX - 400.0f, centreY - 220.0f, centreX + 400.0f, centreY + 220.0f);+ const FieldState initial[] = {+ {toxin, 115.0f, 13.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f},+ {radiation, 115.0f, 13.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f}+ };+ setFields(initial, 2);+ layer.reset();+ if (!layer.valid()) { layer.shutdown(); return false; }+ renderObject = new VolumeRenderObject;+ W3DDisplay::m_3DScene->Add_Render_Object(renderObject);+ std::fprintf(stderr, "cloud-preview: shared volumetric renderer initialized (no particle sprites)\n");+ return true;+}+void setEnabled(bool value) { enabled = value; everEnabled = everEnabled || value; }+void setFields(const FieldState *fields, unsigned count)+{+ layer.setFields(fields, count);+ if (count > 2 || (count && !fields)) return;+ fieldCount = count;+ for (unsigned i = 0; i < count; ++i) fieldStates[i] = fields[i];+ if (renderObject) renderObject->fieldsChanged();+}+void setInfantryHeight(float height)+{+ if (!std::isfinite(height) || height <= 0) { failed = true; return; }+ for (unsigned i = 0; i < fieldCount; ++i) fieldStates[i].height = height;+ layer.setFields(fieldStates, fieldCount);+ if (renderObject) renderObject->fieldsChanged();+}+void resetFlow() { layer.reset(); }+void setBodies(const CloudPreviewFlow::Body *bodies, unsigned count) { layer.setBodies(bodies, count); }+void setInteractionEnabled(bool value) { layer.setInteractionEnabled(value); }+bool isInteractionEnabled() { return layer.isInteractionEnabled(); }+void setHeatEnabled(bool value) { layer.setHeatEnabled(value); }+bool isHeatEnabled() { return layer.isHeatEnabled(); }+void update(float timeSeconds) { layer.update(timeSeconds); }+unsigned activeBodies() { return layer.activeBodies(); }+float maxDisturbance() { return layer.maxDisturbance(); }+unsigned interactionUploads() { return layer.interactionUploads(); }+bool validationPassed()+{+ return renderObject && !failed && layer.valid() && (!everEnabled || layer.renderedFrames() > 0);+}+void shutdown()+{+ enabled = false;+ if (renderObject) {+ renderObject->Remove();+ renderObject->Release_Ref();+ renderObject = nullptr;+ }+ layer.shutdown();+}+} // namespace CloudPreviewVolumediff --git a/GeneralsMD/Code/Tools/CloudPreviewVolume.h b/GeneralsMD/Code/Tools/CloudPreviewVolume.hnew file mode 100644index 000000000..99ac28af9--- /dev/null+++ b/GeneralsMD/Code/Tools/CloudPreviewVolume.h@@ -0,0 +1,38 @@+// Preview scene adapter for the shared production hazard-cloud renderer.+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.+#pragma once++#include "CloudPreviewFlow.h"+#include "Platform/SdlHazardCloud.h"+#include "Lib/BaseType.h"++namespace CloudPreviewVolume {++using FieldState = SdlHazardCloud::FieldState;++// Positions are ground-level centres. Requires a loaded W3D scene and SDL GPU.+bool initialize(const Coord3D &toxin, const Coord3D &radiation);+void setEnabled(bool enabled);+// Copies up to two live fields without reallocating/resetting the flow domain.+// Zero radius/height/density and an empty list represent an inactive source.+void setFields(const FieldState *fields, unsigned count);+// Restart wakes and source animation when replaying/reconfiguring a scenario.+void resetFlow();+// World-space full height, normally measured from the preview infantry model.+void setInfantryHeight(float height);+// At most four preview infantry; values are copied until the next update.+void setBodies(const CloudPreviewFlow::Body *bodies, unsigned count);+void setInteractionEnabled(bool enabled);+bool isInteractionEnabled();+// Heat distortion applies only to nuclear fields in the volumetric preview.+void setHeatEnabled(bool enabled);+bool isHeatEnabled();+void update(float timeSeconds);+unsigned activeBodies();+float maxDisturbance();+unsigned interactionUploads();+bool validationPassed();+// Release before the game client, scene and graphics device are destroyed.+void shutdown();++}diff --git a/GeneralsMD/Code/Tools/cloud_preview.cpp b/GeneralsMD/Code/Tools/cloud_preview.cppnew file mode 100644index 000000000..8a8a6ee24--- /dev/null+++ b/GeneralsMD/Code/Tools/cloud_preview.cpp@@ -0,0 +1,479 @@+// A separate executable using the production platform bootstrap and game renderer.+// Renaming only this translation unit's entry/factory keeps the normal game unchanged.+#define main CloudPreviewPlatformMain+#define CreateGameEngine CloudPreviewOriginalFactory+#include "../Main/PosixMain.cpp"+#undef CreateGameEngine+#undef main++#include "CloudPreviewScene.h"+#include "CloudPreviewVolume.h"+#include "CloudPreviewColors.h"+#include "CloudPreviewColorPanel.h"+#include "Common/GlobalData.h"+#include "GameClient/Display.h"+#include "GameClient/MapUtil.h"+#include "GameClient/View.h"+#include "GameLogic/GameLogic.h"+#include "SdlDevice/GameClient/SdlInput.h"++#include <cstring>+#include <filesystem>+#include <fstream>+#include <stdexcept>++extern void GameEngine_startSkirmish(Int numPlayers);++namespace {+bool previewStarted = false;+bool previewValid = false;+CloudPreviewScene::Appearance previewAppearance = CloudPreviewScene::Appearance::Volumetric;+CloudPreviewScene::Scenario previewScenario = CloudPreviewScene::Scenario::Tractor;+unsigned previewFrameLimit = 0;+bool previewInteraction = true;+bool previewHeat = true;+bool previewLooping = true;+bool previewColorPanel = true;++struct ScenarioChoice+{+ const char *argument;+ CloudPreviewScene::Scenario scenario;+ SDL_Keycode key;+};++const ScenarioChoice scenarioChoices[] = {+ { "comparison", CloudPreviewScene::Scenario::Comparison, SDLK_F1 },+ { "tractor", CloudPreviewScene::Scenario::Tractor, SDLK_F2 },+ { "anthrax", CloudPreviewScene::Scenario::AnthraxBomb, SDLK_F3 },+ { "gamma", CloudPreviewScene::Scenario::AnthraxGamma, SDLK_F4 },+ { "toxin-building", CloudPreviewScene::Scenario::ToxinBuilding, SDLK_F5 },+ { "nuke", CloudPreviewScene::Scenario::NuclearMissile, SDLK_F6 },+ { "nuke-cannon", CloudPreviewScene::Scenario::NuclearCannon, SDLK_F7 },+ { "reactor", CloudPreviewScene::Scenario::NuclearReactor, SDLK_F8 }+};+constexpr unsigned scenarioCount = sizeof(scenarioChoices) / sizeof(scenarioChoices[0]);++unsigned scenarioPalette()+{+ using Scenario = CloudPreviewScene::Scenario;+ switch (CloudPreviewScene::getScenario()) {+ case Scenario::AnthraxBomb: return 2;+ case Scenario::AnthraxGamma: return 3;+ case Scenario::NuclearMissile:+ case Scenario::NuclearCannon:+ case Scenario::NuclearReactor: return 1;+ default: return 0;+ }+}++void showPaletteScene(unsigned palette)+{+ using Scenario = CloudPreviewScene::Scenario;+ const Scenario scenarios[] = {Scenario::Tractor, Scenario::NuclearMissile,+ Scenario::AnthraxBomb, Scenario::AnthraxGamma};+ if (palette >= 4) return;+ CloudPreviewScene::setAppearance(CloudPreviewScene::Appearance::Volumetric);+ if (CloudPreviewScene::getScenario() != scenarios[palette])+ CloudPreviewScene::setScenario(scenarios[palette]);+ else if (std::strncmp(CloudPreviewScene::scenarioPhase(), "clear", 5) == 0)+ CloudPreviewScene::replayScenario();+ // Show Scene plays the selected source. Ordinary edits preserve pause and+ // source timing, so artists can inspect an exact frame while tuning colors.+ if (TheGameLogic && TheGameLogic->isGamePaused()) TheGameLogic->setGamePaused(FALSE, FALSE);+}++CloudPreviewScene::Scenario parseScenario(const std::string &value)+{+ for (const ScenarioChoice &choice : scenarioChoices)+ if (value == choice.argument) return choice.scenario;+ throw std::runtime_error("invalid scenario: " + value+ + "; choose comparison, tractor, anthrax, gamma, toxin-building, nuke, nuke-cannon, or reactor");+}++bool isScenarioKey(SDL_Keycode key)+{+ if (key == SDLK_LEFTBRACKET || key == SDLK_RIGHTBRACKET || key == SDLK_B || key == SDLK_L)+ return true;+ for (const ScenarioChoice &choice : scenarioChoices)+ if (key == choice.key) return true;+ return false;+}++void handleScenarioKey(SDL_Keycode key)+{+ const auto previous = CloudPreviewScene::getScenario();+ if (key == SDLK_B) {+ CloudPreviewScene::replayScenario();+ } else if (key == SDLK_L) {+ CloudPreviewScene::setLooping(!CloudPreviewScene::isLooping());+ } else if (key == SDLK_LEFTBRACKET || key == SDLK_RIGHTBRACKET) {+ unsigned index = 0;+ for (; index < scenarioCount; ++index)+ if (scenarioChoices[index].scenario == CloudPreviewScene::getScenario()) break;+ index = key == SDLK_RIGHTBRACKET ? (index + 1) % scenarioCount+ : (index + scenarioCount - 1) % scenarioCount;+ CloudPreviewScene::setScenario(scenarioChoices[index].scenario);+ } else {+ for (const ScenarioChoice &choice : scenarioChoices)+ if (key == choice.key) { CloudPreviewScene::setScenario(choice.scenario); break; }+ }+ if (previous != CloudPreviewScene::getScenario()) CloudPreviewColorPanel::selectPalette(scenarioPalette());+}++void updatePreviewTitle()+{+ if (SDL_Window *window = SdlInput_gameWindow()) {+ const std::string title = std::string(CloudPreviewScene::scenarioName())+ + " | " + CloudPreviewScene::scenarioPhase()+ + " | " + CloudPreviewScene::appearanceName()+ + (CloudPreviewScene::isLooping() ? " | Loop ON" : " | Loop OFF")+ + (CloudPreviewVolume::isInteractionEnabled() ? " | Volume wakes ON" : " | Volume wakes OFF")+ + (CloudPreviewVolume::isHeatEnabled() ? " | H: nuclear heat ON" : " | H: nuclear heat OFF")+ + " | P: colors | F1-F8/[]: scene | 1/2/C: appearance | B: replay L: loop | Space: pause Esc: close";+ SDL_SetWindowTitle(window, title.c_str());+ }+}++class CloudPreviewEngine : public SdlGameEngine+{+public:+ explicit CloudPreviewEngine(const WindowRequest &request) : SdlGameEngine(request) {}+ void init(int argc, char **argv) override+ {+ SdlGameEngine::init(argc, argv);+ // Use the indexed user-map name directly. The game's -map short-path+ // expander is designed for relative names and strips a POSIX root slash.+ AsciiString map = TheMapCache->getUserMapDir();+ map.concat("\\CloudPreview\\CloudPreview.map");+ const MapMetaData *metadata = TheMapCache->findMap(map);+ if (!metadata || !metadata->m_isMultiplayer) {+ std::fprintf(stderr, "cloud_preview: generated preview map was not registered: %s\n", map.str());+ setQuitting(TRUE);+ return;+ }+ TheWritableGlobalData->m_mapName = map;+ TheWritableGlobalData->m_autoSkirmishPlayers = 2;+ TheWritableGlobalData->m_showNetBox = FALSE;+ TheWritableGlobalData->m_healthBarMode = 0;+ GameEngine_startSkirmish(2);+ startupTime = SDL_GetTicks();+ }+ ~CloudPreviewEngine() override+ {+ previewValid = previewStarted && CloudPreviewScene::validationPassed();+ CloudPreviewColorPanel::shutdown();+ CloudPreviewScene::shutdown();+ }++ void update() override+ {+ // The game's -maxframes ends the match and clears its objects before+ // teardown. Stop our host directly, while the live scene can be checked.+ if (previewStarted && previewFrameLimit && TheGameLogic->getFrame() >= previewFrameLimit) {+ setQuitting(TRUE);+ return;+ }+ // MSG_NEW_GAME sets the mode before the deferred map load. Wait for the+ // first completed logic tick so terrain, players and pathfinding exist.+ if (!previewStarted && TheGameLogic && TheGameLogic->isInGame()+ && !TheGameLogic->isInShellGame() && !TheGameLogic->isLoadingMap()+ && TheGameLogic->getFrame() > 0) {+ // This executable owns its two-field scene and A/B controls. Keep its+ // Classic side independent of the normal game's saved cloud setting.+ TheWritableGlobalData->m_cloudStyle = 0;+ CloudPreviewScene::setScenario(previewScenario);+ // Scene and appearance are independent startup choices. Every+ // source supports the original and volumetric appearances.+ CloudPreviewScene::setAppearance(previewAppearance);+ CloudPreviewScene::setLooping(previewLooping);+ previewStarted = CloudPreviewScene::initialize();+ if (!previewStarted) {+ std::fprintf(stderr, "cloud_preview: scene initialization failed\n");+ setQuitting(TRUE);+ return;+ }+ CloudPreviewVolume::setInteractionEnabled(previewInteraction);+ CloudPreviewVolume::setHeatEnabled(previewHeat);+ if (!CloudPreviewColorPanel::initialize()) {+ std::fprintf(stderr, "cloud_preview: color panel initialization failed\n");+ previewStarted = false;+ setQuitting(TRUE);+ return;+ }+ CloudPreviewColorPanel::selectPalette(scenarioPalette());+ CloudPreviewColorPanel::setVisible(previewColorPanel);+ updatePreviewTitle();+ }+ // Check readiness first: a slow but successful synchronous map load must+ // not be mistaken for a startup that is still stuck in the menus.+ if (!previewStarted && SDL_GetTicks() - startupTime > 30000) {+ std::fprintf(stderr, "cloud_preview: timed out waiting for the preview map\n");+ setQuitting(TRUE);+ return;+ }+ if (previewStarted) {+ CloudPreviewScene::update();+ // Scenario phases change with logic time, but the title must also+ // refresh while paused and after a scene is selected in that state.+ const Uint64 now = SDL_GetTicks();+ if (now - lastTitleUpdate >= 1000) {+ updatePreviewTitle();+ lastTitleUpdate = now;+ }+ }+ SdlGameEngine::update();+ }++ void serviceWindowsOS() override+ {+ if (!(SDL_WasInit(SDL_INIT_VIDEO) & SDL_INIT_VIDEO)) return;+ SDL_Event event;+ while (SDL_PollEvent(&event)) {+ if (previewStarted && CloudPreviewColorPanel::handle(event)) {+ const int palette = CloudPreviewColorPanel::takePreviewRequest();+ if (palette >= 0) showPaletteScene(static_cast<unsigned>(palette));+ updatePreviewTitle();+ continue;+ }+ if (event.type == SDL_EVENT_QUIT || event.type == SDL_EVENT_WINDOW_CLOSE_REQUESTED) {+ setQuitting(TRUE);+ } else if (event.type == SDL_EVENT_WINDOW_FOCUS_GAINED) {+ setIsActive(TRUE);+ } else if (event.type == SDL_EVENT_WINDOW_FOCUS_LOST) {+ setIsActive(FALSE);+ } else if ((event.type == SDL_EVENT_KEY_DOWN || event.type == SDL_EVENT_KEY_UP)+ && (event.key.key == SDLK_ESCAPE || event.key.key == SDLK_SPACE)) {+ if (event.type == SDL_EVENT_KEY_DOWN && !event.key.repeat) {+ if (event.key.key == SDLK_ESCAPE) setQuitting(TRUE);+ else if (previewStarted)+ TheGameLogic->setGamePaused(!TheGameLogic->isGamePaused(), FALSE);+ }+ } else if (previewStarted+ && (event.type == SDL_EVENT_KEY_DOWN || event.type == SDL_EVENT_KEY_UP)+ && isScenarioKey(event.key.key)) {+ if (event.type == SDL_EVENT_KEY_DOWN && !event.key.repeat) {+ handleScenarioKey(event.key.key);+ updatePreviewTitle();+ }+ } else if (previewStarted+ && (event.type == SDL_EVENT_KEY_DOWN || event.type == SDL_EVENT_KEY_UP)+ && (event.key.key == SDLK_1 || event.key.key == SDLK_2+ || event.key.key == SDLK_3 || event.key.key == SDLK_C)) {+ if (event.type == SDL_EVENT_KEY_DOWN && !event.key.repeat) {+ using Appearance = CloudPreviewScene::Appearance;+ Appearance appearance = CloudPreviewScene::getAppearance();+ if (event.key.key == SDLK_1) appearance = Appearance::Original;+ else if (event.key.key == SDLK_2 || event.key.key == SDLK_3)+ appearance = Appearance::Volumetric;+ else appearance = appearance == Appearance::Original+ ? Appearance::Volumetric : Appearance::Original;+ CloudPreviewScene::setAppearance(appearance);+ updatePreviewTitle();+ }+ } else if (previewStarted+ && (event.type == SDL_EVENT_KEY_DOWN || event.type == SDL_EVENT_KEY_UP)+ && (event.key.key == SDLK_Q || event.key.key == SDLK_E+ || event.key.key == SDLK_R || event.key.key == SDLK_F12+ || event.key.key == SDLK_I || event.key.key == SDLK_H)) {+ if (event.type == SDL_EVENT_KEY_DOWN && !event.key.repeat) {+ // Handle inspection directly so it also works while the+ // game's paused input path is suppressing normal commands.+ if (event.key.key == SDLK_I) {+ CloudPreviewVolume::setInteractionEnabled(!CloudPreviewVolume::isInteractionEnabled());+ updatePreviewTitle();+ } else if (event.key.key == SDLK_H) {+ CloudPreviewVolume::setHeatEnabled(!CloudPreviewVolume::isHeatEnabled());+ updatePreviewTitle();+ } else if (event.key.key == SDLK_F12) {+ if (TheDisplay) TheDisplay->takeScreenShot();+ } else if (TheTacticalView) {+ if (event.key.key == SDLK_R) {+ TheTacticalView->setAngleAndPitchToDefault();+ TheTacticalView->setZoomToHeight(520.0f);+ } else {+ const Real delta = event.key.key == SDLK_Q ? -0.785398163f : 0.785398163f;+ TheTacticalView->setAngle(TheTacticalView->getAngle() + delta);+ }+ }+ }+ } else {+ SdlInput_dispatch(event);+ }+ }+ }+private:+ Uint64 startupTime = 0;+ Uint64 lastTitleUpdate = 0;+};++unsigned positiveNumber(const std::string &value, unsigned low, unsigned high)+{+ char *end = nullptr;+ const unsigned long n = std::strtoul(value.c_str(), &end, 10);+ if (value.empty() || *end || n < low || n > high)+ throw std::runtime_error("invalid number: " + value);+ return static_cast<unsigned>(n);+}++void printHelp()+{+ std::puts(+ "Isolated toxin and radiation preview with volumetric smoke.\n"+ "Usage: cloud_preview [--data ZERO_HOUR_FOLDER] [--user-dir FOLDER]\n"+ " [--width N] [--height N] [--frames N] [--screenshot-frame N]\n"+ " [--scenario NAME] [--no-loop]\n"+ " [--classic | --volumetric] [--no-interaction] [--no-heat]\n"+ " [--no-color-panel] [--hidden | --offscreen]\n\n"+ "Four passive infantry walk through visual-only contamination fields.\n"+ "The tractor release scenario is the default; scenarios loop unless --no-loop is set.\n"+ "--scenario: comparison | tractor | anthrax | gamma | toxin-building | nuke | nuke-cannon | reactor\n"+ "F1: comparison | F2: toxin tractor | F3: anthrax bomb | F4: anthrax gamma\n"+ "F5: toxin building | F6: nuclear missile | F7: nuclear cannon | F8: nuclear reactor\n"+ "[/]: previous/next scenario | B: replay release | L: toggle looping\n"+ "Volumetric smoke is the default. --classic uses the game's original effects;\n"+ "--volumetric selects the new volumes. Both appearances work in every scene.\n"+ "Appearance options keep --scenario (default: tractor).\n"+ "1: original effects | 2: volumetric smoke | C: toggle appearance | 3: alias for 2\n"+ "Appearance changes preserve the current scene and release phase; new scenes keep the appearance.\n"+ "Both appearances switch immediately, even while paused.\n"+ "I: toggle volumetric infantry wakes | Q/E: orbit 45 degrees | R: reset orientation/zoom\n"+ "H: toggle heat distortion for nuclear volumetric clouds (on by default)\n"+ "--no-heat starts with nuclear heat distortion off for comparison\n"+ "P: show/hide RGB, Brightness and Transparency controls for all four cloud types\n"+ "Color panel: Show scene, Reset palette, Save all, Load saved, Copy all\n"+ "Saved palettes load from cloud-colors.ini in the preview user folder. No automatic saves.\n"+ "F12: screenshot (also while paused) | --no-interaction starts with wakes off\n"+ "Arrows: pan | wheel: zoom | middle mouse: rotate | Space: pause | Esc: close\n"+ "Game assets are read from the existing installation. Logs and BMP screenshots\n"+ "go to the separate cloud-preview/user folder beside this build.\n"+ "Preview controls are independent of the game's Cloud style setting.\n"+ "--frames counts engine logic frames (60 per second).");+}++// This does not ask EarlyOptions for a user directory: that function caches the first+// directory it sees, and the engine must see the preview's isolated directory first.+std::filesystem::path playerRegistry(const std::string &taskHome)+{+ const char *forced = std::getenv("ZH_USER_DATA_DIR");+ if (forced && *forced) return std::filesystem::path(forced) / "Registry.ini";+ const char *xdg = std::getenv("XDG_DATA_HOME");+ const std::filesystem::path base = xdg && *xdg ? std::filesystem::path(xdg)+ : std::filesystem::path(taskHome) / ".local/share";+ return base / "Command and Conquer Generals Zero Hour Data/Registry.ini";+}++// Preserve only the optional base-game location; no personal settings or saves are copied.+void copyBaseGameLocation(const std::filesystem::path &original, const std::filesystem::path &preview)+{+ if (std::filesystem::exists(preview)) return;+ std::ifstream input(original);+ std::string line, location;+ while (std::getline(input, line)) {+ const size_t equals = line.find('=');+ if (equals == std::string::npos) continue;+ std::string key = line.substr(0, equals);+ const size_t first = key.find_first_not_of(" \t\r");+ if (first == std::string::npos) continue;+ key = key.substr(first, key.find_last_not_of(" \t\r") - first + 1);+ if (strcasecmp(key.c_str(), "Generals\\InstallPath") == 0) location = line;+ }+ if (!location.empty()) {+ std::ofstream output(preview);+ output << location << '\n';+ if (!output) throw std::runtime_error("cannot write preview's base-game location");+ }+}+} // namespace++GameEngine *CreateGameEngine()+{+ return NEW CloudPreviewEngine(s_windowRequest);+}++int main(int argc, char **argv)+{+ try {+ std::string data;+ std::filesystem::path userDir = std::filesystem::path(CLOUD_PREVIEW_DIRECTORY) / "user";+ unsigned width = 1280, height = 800, frames = 0, screenshot = 0;+ bool hidden = false, offscreen = false;+ for (int i = 1; i < argc; ++i) {+ const std::string arg = argv[i];+ const auto value = [&]() -> std::string {+ if (++i == argc) throw std::runtime_error("missing value after " + arg);+ return argv[i];+ };+ if (arg == "--help" || arg == "-h") { printHelp(); return 0; }+ else if (arg == "--data") data = std::filesystem::absolute(value()).string();+ else if (arg == "--user-dir") userDir = std::filesystem::absolute(value());+ else if (arg == "--width") width = positiveNumber(value(), 640, 7680);+ else if (arg == "--height") height = positiveNumber(value(), 480, 4320);+ else if (arg == "--frames") frames = positiveNumber(value(), 1, 10000000);+ else if (arg == "--screenshot-frame") screenshot = positiveNumber(value(), 1, 10000000);+ else if (arg == "--scenario") previewScenario = parseScenario(value());+ else if (arg == "--no-loop") previewLooping = false;+ else if (arg == "--classic") previewAppearance = CloudPreviewScene::Appearance::Original;+ else if (arg == "--volumetric") previewAppearance = CloudPreviewScene::Appearance::Volumetric;+ else if (arg == "--no-interaction") previewInteraction = false;+ else if (arg == "--no-heat") previewHeat = false;+ else if (arg == "--no-color-panel") previewColorPanel = false;+ else if (arg == "--hidden") hidden = true;+ else if (arg == "--offscreen") offscreen = true;+ else throw std::runtime_error("unknown argument: " + arg);+ }+ if (screenshot && frames && screenshot >= frames)+ throw std::runtime_error("--screenshot-frame must be earlier than --frames");+ char homeBuffer[4096];+ const std::string taskHome = findHomeDirectory(homeBuffer, sizeof(homeBuffer)) ? homeBuffer : "";+ const std::filesystem::path originalRegistry = playerRegistry(taskHome);+ PosixInstallRequest request = {};+ request.insideAppBundle = true; // Enable the existing Steam/known-location search.+ request.home = taskHome;+ request.registryFile = originalRegistry.string();+ request.chooser = nullptr;+ if (!data.empty()) request.arguments = { "-root", data };+ PosixInstallChoice choice;+ if (!PosixChooseInstallRoot(request, choice))+ throw std::runtime_error("game assets not found; pass --data followed by your Zero Hour folder");+ data = choice.root;+ const PosixInstallCheck check = PosixCheckInstallFolderWith(data, {}, originalRegistry.string());+ if (check != INSTALL_OK) throw std::runtime_error(PosixInstallCheckMessage(check, data));+ std::filesystem::create_directories(userDir);+ if (!CloudPreviewColors::initialize(userDir.string()))+ std::fprintf(stderr, "cloud_preview: %s; using default colors\n", CloudPreviewColors::lastStatus().c_str());+ std::fprintf(stderr, "cloud_preview: palette file %s\n", CloudPreviewColors::savePath().c_str());+ copyBaseGameLocation(originalRegistry, userDir / "Registry.ini");+ // Release builds index user maps, but do not discover new loose standard+ // maps from an overlay. Keep this generated fixture in our own user root.+ const std::filesystem::path mapPath = userDir / "Maps/CloudPreview/CloudPreview.map";+ std::filesystem::create_directories(mapPath.parent_path());+ std::filesystem::copy_file(std::filesystem::path(CLOUD_PREVIEW_DIRECTORY)+ / "overlay/Maps/CloudPreview/CloudPreview.map", mapPath,+ std::filesystem::copy_options::overwrite_existing);+ if (setenv("ZH_USER_DATA_DIR", userDir.c_str(), 1) != 0)+ throw std::runtime_error("cannot select preview data directory");+ std::vector<std::string> arguments = {+ argv[0], "-root", data,+ "-overlay", std::string(CLOUD_PREVIEW_DIRECTORY) + "/overlay",+ "-overlay", CLOUD_PREVIEW_GAME_OVERLAY,+ "-win", "-xres", std::to_string(width), "-yres", std::to_string(height),+ "-quickstart", "-noshellmap", "-noaudio", "-multiInstance",+ "-takeover", "-observer", "-side", "0", "FactionAmerica",+ "-side", "1", "FactionChina", "-seed", "7", "-fps", "60"+ };+ if (hidden) arguments.push_back("-hiddenwindow");+ if (offscreen) arguments.push_back("-offscreen");+ previewFrameLimit = frames;+ if (screenshot) { arguments.push_back("-screenshot"); arguments.push_back(std::to_string(screenshot)); }+ std::vector<char *> raw;+ for (std::string &arg : arguments) raw.push_back(arg.data());+ raw.push_back(nullptr);+ std::fprintf(stderr, "cloud_preview: assets %s\ncloud_preview: data %s\n", data.c_str(), userDir.c_str());+ const int result = CloudPreviewPlatformMain(static_cast<int>(arguments.size()), raw.data());+ return result ? result : (previewValid ? 0 : 1);+ } catch (const std::exception &error) {+ std::fprintf(stderr, "cloud_preview: %s\n", error.what());+ return 1;+ }+}diff --git a/GeneralsMD/Code/Tools/cloud_preview/generate_map.py b/GeneralsMD/Code/Tools/cloud_preview/generate_map.pynew file mode 100644index 000000000..a47f86aa0--- /dev/null+++ b/GeneralsMD/Code/Tools/cloud_preview/generate_map.py@@ -0,0 +1,259 @@+#!/usr/bin/env python3+"""Write the isolated cloud preview's flat fixture or water inspection yard.++Only Python's standard library is needed. The CkMp layout follows the engine's+RandomMapGenerator.cpp; the two invisible start waypoints let the ordinary map+cache recognize a two-player map. The default fixture has no buildings, units,+water, scenery, resource objects, or map scripts. The preview executable owns+its harmless props and walkers; --inspection-yard adds only a real water polygon+and a lowered pond bed, keeping the source positions and walking lanes flat.++Usage: generate_map.py /path/to/overlay/Maps/CloudPreview/CloudPreview.map --inspection-yard++Playable bounds are [0, 1280] on both axes, with centre (640, 640, 37.5).+The surrounding 20-cell border uses the same flat terrain.+"""++from contextlib import contextmanager+from pathlib import Path+import argparse+import math+import struct+++PLAYABLE_CELLS = 128+BORDER_CELLS = 20+HEIGHT_BYTE = 60+WATER_LEVEL = 37 # PolygonTrigger stores integer world Z; dry ground is 37.5.+++def yard_height(x, y):+ """Rounded pond bed; every sample outside its footprint stays exactly flat.++ The four walking lanes remain at y=592/624/656/688. The highest wet bank is+ y=565, leaving a dry margin below the closest lane. World height is byte*.625.+ """+ # Signed distance to a rounded rectangle centered on the lower half of the+ # inspection view. A broad bank exposes shallow water, deep water and shore.+ qx = abs(x - 640.0) - 285.0+ qy = abs(y - 472.5) - 37.5+ distance = math.hypot(max(qx, 0.0), max(qy, 0.0)) + min(max(qx, qy), 0.0) - 55.0+ depth = max(0.0, min(1.0, -distance / 32.0))+ depth = depth * depth * (3.0 - 2.0 * depth)+ return HEIGHT_BYTE - round(44.0 * depth)+++def write_water(writer):+ # PolygonTrigger::WritePolygonTriggersDataChunk v4: count, name, layer,+ # ID, water byte, river byte, river-start integer, count, XYZ integer points.+ # The polygon extends a little beyond the depression. Real terrain/depth+ # clipping defines the shoreline rather than exposing a straight water edge.+ points = ((335, 360), (945, 360), (1000, 415), (1000, 530),+ (945, 585), (335, 585), (280, 530), (280, 415))+ writer.integer(1)+ writer.ascii("CloudInspectionPond")+ writer.ascii("Cloud preview water")+ writer.integer(1)+ writer.body.extend(bytes((1, 0))) # Real water, not a river or trigger zone.+ writer.integer(0)+ writer.integer(len(points))+ for x, y in points:+ for value in (x, y, WATER_LEVEL):+ writer.integer(value)+++class MapWriter:+ def __init__(self):+ self.body = bytearray()+ self.names = {}++ def name_id(self, name):+ if name not in self.names:+ self.names[name] = len(self.names) + 1+ return self.names[name]++ def integer(self, value):+ self.body.extend(struct.pack("<i", value))++ def real(self, value):+ self.body.extend(struct.pack("<f", value))++ def ascii(self, value):+ encoded = value.encode("ascii")+ self.body.extend(struct.pack("<H", len(encoded)))+ self.body.extend(encoded)++ @contextmanager+ def chunk(self, name, version):+ self.body.extend(struct.pack("<IH", self.name_id(name), version))+ size_offset = len(self.body)+ self.integer(0)+ yield+ struct.pack_into("<i", self.body, size_offset, len(self.body) - size_offset - 4)++ def dictionary(self, entries):+ self.body.extend(struct.pack("<H", len(entries)))+ for key, value in entries.items():+ if isinstance(value, bool):+ value_type = 0+ elif isinstance(value, int):+ value_type = 1+ elif isinstance(value, str):+ value_type = 3+ else:+ raise TypeError("unsupported map dictionary value: %r" % value)+ self.integer((self.name_id(key) << 8) | value_type)+ if value_type == 0:+ self.body.append(int(value))+ elif value_type == 1:+ self.integer(value)+ else:+ self.ascii(value)++ def finish(self):+ output = bytearray(b"CkMp")+ output.extend(struct.pack("<i", len(self.names)))+ for name, name_id in self.names.items():+ encoded = name.encode("ascii")+ output.append(len(encoded))+ output.extend(encoded)+ output.extend(struct.pack("<I", name_id))+ output.extend(self.body)+ return output+++def write_sides(writer):+ # Retain the ordinary skirmish side names, which GameLogic resolves when it+ # builds the preview's occupied, driverless slots.+ factions = (+ "Civilian", "America", "China", "GLA", "AmericaAirForceGeneral",+ "AmericaLaserGeneral", "AmericaSuperWeaponGeneral", "ChinaTankGeneral",+ "ChinaNukeGeneral", "ChinaInfantryGeneral", "GLADemolitionGeneral",+ "GLAToxinGeneral", "GLAStealthGeneral",+ )+ sides = [("", "", "Neutral")]+ for faction in factions:+ name = "PlyrCivilian" if faction == "Civilian" else "Skirmish" + faction+ sides.append((name, "Faction" + faction, name))++ with writer.chunk("SidesList", 3):+ writer.integer(len(sides))+ for name, faction, display_name in sides:+ writer.dictionary({+ "playerName": name,+ "playerIsHuman": False,+ "playerDisplayName": display_name,+ "playerFaction": faction,+ "playerAllies": "",+ "playerEnemies": "",+ })+ writer.integer(0) # No build list.+ writer.integer(len(sides))+ for name, _, _ in sides:+ writer.dictionary({+ "teamName": "team" + name,+ "teamOwner": name,+ "teamIsSingleton": True,+ })+ with writer.chunk("PlayerScriptsList", 1):+ for _ in sides:+ with writer.chunk("ScriptList", 1):+ pass+++def write_waypoint(writer, number, x, y):+ name = "Player_%d_Start" % number+ with writer.chunk("Object", 3):+ for value in (x, y, 0.0, 0.0):+ writer.real(value)+ writer.integer(0)+ writer.ascii("*Waypoints/Waypoint")+ writer.dictionary({+ "objectInitialHealth": 100,+ "objectEnabled": True,+ "objectPowered": True,+ "objectRecruitableAI": True,+ "originalOwner": "team",+ "uniqueID": name,+ "objectLayer": "Start Points",+ "waypointID": number,+ "objectDestructible": True,+ "objectSellable": True,+ "objectRepairable": True,+ "waypointName": name,+ })+++def build_map(inspection_yard=False):+ writer = MapWriter()+ width = PLAYABLE_CELLS + 2 * BORDER_CELLS+ area = width * width++ with writer.chunk("HeightMapData", 4):+ for value in (width, width, BORDER_CELLS, 1, PLAYABLE_CELLS, PLAYABLE_CELLS, area):+ writer.integer(value)+ if inspection_yard:+ writer.body.extend(yard_height((x - BORDER_CELLS) * 10, (y - BORDER_CELLS) * 10)+ for y in range(width) for x in range(width))+ else:+ # Kept byte-for-byte compatible with flat runtime test fixtures.+ writer.body.extend(bytes([HEIGHT_BYTE]) * area)++ with writer.chunk("BlendTileData", 6):+ writer.integer(area)+ # Four source tiles, with four quadrants per tile, tile a 2x2 sheet.+ tiles = [(((x // 2) % 2 + 2 * ((y // 2) % 2)) << 2) + 2 * (y & 1) + (x & 1)+ for y in range(width) for x in range(width)]+ writer.body.extend(struct.pack("<%dh" % area, *tiles))+ writer.body.extend(bytes(area * 2 * 3)) # No blend, extra blend, or cliff indices.+ for value in (4, 1, 1, 1, 0, 4, 2, 0):+ writer.integer(value)+ writer.ascii("DirtType1")+ writer.integer(0) # No edge tiles.+ writer.integer(0) # No edge texture classes.++ with writer.chunk("WorldInfo", 1):+ writer.dictionary({"weather": 0, "compression": 0})+ write_sides(writer)++ with writer.chunk("ObjectsList", 3):+ write_waypoint(writer, 1, 180.0, 180.0)+ write_waypoint(writer, 2, 1100.0, 1100.0)+ with writer.chunk("PolygonTriggers", 4):+ if inspection_yard:+ write_water(writer)+ else:+ writer.integer(0)++ with writer.chunk("GlobalLighting", 3):+ writer.integer(2) # TIME_OF_DAY_AFTERNOON.+ for _ in range(4):+ # The same neutral daylight in every time slot, for consistent comparison.+ for ambient, diffuse in ((0.45, 0.55), (0.50, 0.50)):+ for value in (ambient, ambient, ambient, diffuse, diffuse, diffuse, -0.5, 0.5, -1.0):+ writer.real(value)+ # Two inactive terrain lights, then two inactive object lights.+ for _ in range(4):+ for value in (0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0):+ writer.real(value)++ with writer.chunk("WaypointsList", 1):+ writer.integer(0)+ return writer.finish()+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("output", type=Path, help="Destination CloudPreview.map path")+ parser.add_argument("--inspection-yard", action="store_true",+ help="Add the preview pond; leave default harness fixtures flat")+ args = parser.parse_args()+ args.output.parent.mkdir(parents=True, exist_ok=True)+ args.output.write_bytes(build_map(args.inspection_yard))+ description = "pond inspection yard" if args.inspection_yard else "flat fixture"+ print("Wrote %s (%s; 1280 x 1280 world units; centre 640,640,37.5)"+ % (args.output, description))+++if __name__ == "__main__":+ main()diff --git a/GeneralsMD/Code/Tools/cloud_preview/presets/pre-tuning.ini b/GeneralsMD/Code/Tools/cloud_preview/presets/pre-tuning.ininew file mode 100644index 000000000..6a6f669d5--- /dev/null+++ b/GeneralsMD/Code/Tools/cloud_preview/presets/pre-tuning.ini@@ -0,0 +1,23 @@+; Isolated cloud preview colors. RGB values are linear shader values.+; Main and shadow RGB: 0-1. Brightness: 0-2. Hex comments are rounded.+version = 1++[toxin]+main = 0.769999981, 0.939999998, 0.550000012 ; #C4F08C+shadow = 0.0949999988, 0.150000006, 0.0350000001 ; #182609+brightness = 1++[toxin_beta]+main = 0.660000026, 0.75999999, 1 ; #A8C2FF+shadow = 0.0649999976, 0.100000001, 0.209999993 ; #111A36+brightness = 1++[toxin_gamma]+main = 0.839999974, 0.629999995, 1 ; #D6A1FF+shadow = 0.150000006, 0.0599999987, 0.200000003 ; #260F33+brightness = 1++[nuclear]+main = 0.779999971, 0.689999998, 0.469999999 ; #C7B078+shadow = 0.115000002, 0.0850000009, 0.0299999993 ; #1D1608+brightness = 1diff --git a/GeneralsMD/Code/Tools/cloud_preview/presets/preferred.ini b/GeneralsMD/Code/Tools/cloud_preview/presets/preferred.ininew file mode 100644index 000000000..62a02d9e3--- /dev/null+++ b/GeneralsMD/Code/Tools/cloud_preview/presets/preferred.ini@@ -0,0 +1,28 @@+; Isolated cloud preview colors. RGB values are linear shader values.+; Main and shadow RGB: 0-1. Brightness: 0-2. Hex comments are rounded.+; Transparency: 0-1, higher is clearer; 0 keeps full smoke density.+version = 2++[toxin]+main = 0.769999981, 0.939999998, 0.550000012 ; #C4F08C+shadow = 0.125490203, 0.31764707, 0.0549019612 ; #20510E+brightness = 0.699999988+transparency = 0.670000017++[toxin_beta]+main = 0.660000026, 0.75999999, 1 ; #A8C2FF+shadow = 0.0649999976, 0.100000001, 0.209999993 ; #111A36+brightness = 1.52999997+transparency = 0.769999981++[toxin_gamma]+main = 0.839999974, 0.629999995, 1 ; #D6A1FF+shadow = 0.192156866, 0.0470588244, 0.235294119 ; #310C3C+brightness = 1.32000005+transparency = 0.74000001++[nuclear]+main = 0.749019623, 0.670588255, 0.469999999 ; #BFAB78+shadow = 0.298039228, 0.184313729, 0.0705882385 ; #4C2F12+brightness = 1.29999995+transparency = 0diff --git a/GeneralsMD/Code/Tools/cloud_preview/runtime-check.md b/GeneralsMD/Code/Tools/cloud_preview/runtime-check.mdnew file mode 100644index 000000000..bc022362a--- /dev/null+++ b/GeneralsMD/Code/Tools/cloud_preview/runtime-check.md@@ -0,0 +1,127 @@+# Production hazard cloud checks++[`hazard-cloud-check.py`](../hazard-cloud-check.py) runs the actual Linux `generals`+executable against real hazard objects. It requires a built executable, its runtime+overlay, Python 3 and a prepared retail file-link root. Each case gets a separate+profile and fixture overlay; the harness does not change the normal player profile+or retail data. Hazard weapons and damage remain active. The harmless preview's+choreography and health protection are not part of these runs.++Run the commands below from the repository root, using the build directory for+the revision under review. A configured Linux Release build with existing+dependencies can build the required targets explicitly:++```sh+cmake --build build-linux --target generals zh_overlay+```++The production game does not require the `cloud_preview` executable or inspection+map. The harness calls the existing preview map generator directly for its private+flat fixtures. See the [cloud guide](../../../../docs/cloud-preview.md) for preview+builds, controls and standalone CPU tests.++## Prepare a retail file-link root++The `--root` argument is a prepared file-link directory, distinct from the raw+installation. Retain one using the existing+[`replay-check.sh`](../replay-check.sh) harness:++```sh+GeneralsMD/Code/Tools/replay-check.sh \+ --generals "$PWD/build-linux/generals" \+ --data "/path/to/game-data" \+ --seeds "0" --keep+```++Replace `/path/to/game-data` with the parent directory containing `zerohour/`.+That directory contains the Zero Hour retail data, with the base Generals data+under `zerohour/ZH_Generals` as expected by this harness. This `--data` layout+differs from the preview executable's `--data`, which names the Zero Hour folder+itself.++The replay harness creates fresh directories and links each retail file into a+temporary root, stages a private overlay, and runs its headless replay checks. It+checks the retail files before and after the run. `--keep` retains the work+directory and prints `kept: /tmp/replay-check.XXXXXX, and the logs ...` (or a path+beneath `TMPDIR`). Use that directory's `root` subdirectory for the cloud checks:++```sh+CLOUD_TEST_ROOT="/tmp/replay-check.REPLACE/root"+```++Replace the example with the printed path. The prepared root and its linked retail+files must remain available for the cloud runs. Inspect the replay harness's own+verdict separately; retaining a directory is not evidence that its checks passed.+Do not use the raw installation as `--root` or copy private game assets into Git.++## Run the production fixtures++Choose a new output directory for each run and run only one GPU workload at a+time. The harness selects the Vulkan backend, so a working Vulkan device/driver+and the built SDL renderer are required even though its windows are offscreen.++```sh+python3 GeneralsMD/Code/Tools/hazard-cloud-check.py \+ --generals build-linux/generals \+ --root "$CLOUD_TEST_ROOT" \+ --overlay build-linux/overlay \+ --out build-linux/cloud-preview/production-check \+ --live --crc-pair --gpu-debug+```++Add `--prepare-only` to create fixtures, isolated profiles and command manifests+without launching the game. A `prepared_only` summary records preparation, not+executed runtime or GPU checks. Both modes require the executable, prepared root+and overlay paths to exist. Use a different output directory for the subsequent+runtime run.++Repeated `--case` arguments select individual fixtures; omitting them runs all+seven. Runs are sequential. The cases cover:++| Case | Expected behavior |+| --- | --- |+| `palettes` | Toxin, beta, gamma and nuclear fields use their palettes; infantry cross the toxin field while damage remains active. |+| `nuclear` | Initial radiation particles and a live large radiation owner share one identity and a 200-unit hazard radius. |+| `overlap` | Two intersecting toxin fields, whose owners are 120 units apart, keep distinct volume layers. |+| `hillside` | Toxin and radiation follow the Twilight Flame slope through the volumetric path. |+| `water` | Hazards near the Tournament Island shoreline render with the unchanged baseline water surface; inspect the capture for shoreline overlap. |+| `budget` | Nine overlapping hazards admit eight volumes and retain Classic fallback for the extra field. |+| `lifecycle` | Short-lived radiation expires normally; surviving particles keep the same identity without restarting cloud formation. |++`--crc-pair` repeats the palette fixture in Classic mode and compares game-state+CRCs at the same logic frame. It tests appearance independence on this build;+it does not establish determinism across different platforms or executables.++`--live` uses the local control socket to switch CloudStyle through the game+console, captures both appearances, saves active fields, then relaunches and checks+save restoration. Its manifests also record the mode persisted in Options.ini.+The harness chooses a local port automatically; `--port` selects one explicitly.+`--timeout` bounds unattended runs and control-socket startup, defaulting to 180+seconds. Individual live actions also have their own shorter timeouts.++## Inspect results and remaining limits++`summary.json` and per-case `manifest.json` files retain commands, executable/input+hashes, diagnostic records, checks and screenshot paths. Engine logs and GPU+validation output remain beside them. Treat failed checks and missing-assets/GPU+failures as unresolved; inspect the corresponding logs before rerunning in a new+directory.++Flat fixtures register their generated map only in their private overlays.+Vision aircraft reveal fixture cells through normal gameplay visibility and are+immune to the ground hazards. Hiding the displayed shroud alone does not reveal+the cells to hazard FX.++Review captures for appearance, terrain contact, field overlap, nuclear heat and+embers, and infantry wakes. Exercise hidden/stealthed infantry and camera movement+when reviewing those visibility paths. Check Classic fallback and live switching+with the baseline water surface. The height-map fixture does not cover cliffs or crossing+decks; the overlap fixture does not cover exactly coincident same-palette owners.+Resource allocation failure is not injected by these fixtures.++Passing checks establish the listed runtime behaviors and same-build CRC+consistency. They do not score image quality or measure full-battle performance.+For performance comparisons, record GPU/driver, resolution, map/save, camera,+graphics settings, build/executable hashes and frame-time distributions under+comparable conditions. Keep private assets, saves and generated captures outside+the proposed commits.diff --git a/GeneralsMD/Code/Tools/cloud_preview/test_colors.cpp b/GeneralsMD/Code/Tools/cloud_preview/test_colors.cppnew file mode 100644index 000000000..36be8cf53--- /dev/null+++ b/GeneralsMD/Code/Tools/cloud_preview/test_colors.cpp@@ -0,0 +1,287 @@+// Standalone CPU checks for the isolated preview's editable color palettes.+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.+#include "CloudPreviewColors.h"++#ifdef NDEBUG+#undef NDEBUG+#endif+#include <array>+#include <cassert>+#include <cmath>+#include <cstdio>+#include <filesystem>+#include <fstream>+#include <iterator>+#include <limits>+#include <string>+#include <vector>++#include <unistd.h>++namespace C = CloudPreviewColors;+namespace fs = std::filesystem;++namespace {++struct TemporaryDirectory {+ fs::path path;+ TemporaryDirectory()+ {+ std::string pattern = (fs::temp_directory_path() / "cloud-colors-test-XXXXXX").string();+ std::vector<char> buffer(pattern.begin(), pattern.end());+ buffer.push_back('\0');+ const char *result = mkdtemp(buffer.data());+ assert(result);+ path = result;+ }+ ~TemporaryDirectory() { fs::remove_all(path); }+};++std::string read(const fs::path &path)+{+ std::ifstream file(path);+ assert(file);+ return {std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()};+}++void write(const fs::path &path, const std::string &text)+{+ std::ofstream file(path);+ file << text;+ assert(file.good());+}++bool equal(const C::Color &a, const C::Color &b)+{+ return a.r == b.r && a.g == b.g && a.b == b.b;+}++bool equal(const C::Palette &a, const C::Palette &b)+{+ return equal(a.main, b.main) && equal(a.shadow, b.shadow) && a.brightness == b.brightness+ && a.transparency == b.transparency;+}++std::array<C::Palette, 4> snapshot()+{+ return {{C::get(0), C::get(1), C::get(2), C::get(3)}};+}++void expectSnapshot(const std::array<C::Palette, 4> &expected)+{+ for (unsigned i = 0; i < 4; ++i)+ assert(equal(C::get(i), expected[i]));+}++std::string replace(std::string text, const std::string &from, const std::string &to)+{+ const auto found = text.find(from);+ assert(found != std::string::npos);+ text.replace(found, from.size(), to);+ return text;+}++std::string versionOne(std::string text)+{+ text = replace(text, "version = 2", "version = 1");+ for (auto at = text.find("transparency = "); at != std::string::npos; at = text.find("transparency = "))+ text.erase(at, text.find('\n', at) - at + 1);+ return text;+}++} // namespace++int main()+{+ TemporaryDirectory temporary;+ const fs::path directory = temporary.path / "preview colors";+ fs::create_directory(directory);+ assert(!C::save());+ assert(!C::load());+ assert(C::initialize(directory.string()));+ assert(C::savePath() == (directory / "cloud-colors.ini").string());+ assert(!fs::exists(C::savePath()));+ const std::array<C::Palette, 4> expectedDefaults = {{+ {{0.769999981f, 0.939999998f, 0.550000012f}, {0.125490203f, 0.31764707f, 0.0549019612f}, 0.699999988f, 0.670000017f},+ {{0.749019623f, 0.670588255f, 0.469999999f}, {0.298039228f, 0.184313729f, 0.0705882385f}, 1.29999995f, 0.f},+ {{0.660000026f, 0.75999999f, 1.0f}, {0.0649999976f, 0.100000001f, 0.209999993f}, 1.52999997f, 0.769999981f},+ {{0.839999974f, 0.629999995f, 1.0f}, {0.192156866f, 0.0470588244f, 0.235294119f}, 1.32000005f, 0.74000001f},+ }};+ expectSnapshot(expectedDefaults);+ assert(equal(C::get(500), C::get(0)));+ assert(!C::load());+ expectSnapshot(expectedDefaults);+ std::puts("PASS exact approved palettes; missing file creates nothing and changes nothing");++ C::Palette edit = {{0, 1, std::nextafter(0.4f, 1.0f)}, {0.123456791f, 0.75f, 0.5f}, 2, 0.375f};+ C::set(0, edit);+ const unsigned editedRevision = C::revision();+ C::set(0, edit);+ assert(C::revision() == editedRevision);+ edit.transparency = std::nextafter(0.4f, 1.0f);+ C::set(0, edit);+ assert(C::revision() == editedRevision + 1); // Transparency-only changes reach the renderer.+ edit.main.r = 0.25f;+ edit.brightness = 0;+ edit.transparency = 1;+ C::set(1, edit);+ edit.main.g = 0.333333343f;+ edit.brightness = 0.765432119f;+ edit.transparency = 0.654321134f;+ C::set(2, edit);+ edit.shadow.b = std::nextafter(1.0f, 0.0f);+ edit.transparency = 0;+ C::set(3, edit);+ const auto edited = snapshot();+ const std::string exported = C::exportText();+ assert(exported.find("version = 2\n") != std::string::npos);+ assert(exported.find("transparency = 1\n") != std::string::npos);+ assert(exported.find("transparency = 0\n") != std::string::npos);+ assert(exported.find("[toxin]") < exported.find("[toxin_beta]"));+ assert(exported.find("[toxin_beta]") < exported.find("[toxin_gamma]"));+ assert(exported.find("[toxin_gamma]") < exported.find("[nuclear]"));+ assert(exported.find("; #") != std::string::npos);+ assert(!fs::exists(C::savePath()));+ assert(C::save());+ assert(read(C::savePath()) == exported);+ for (unsigned i = 0; i < 4; ++i)+ C::reset(i);+ expectSnapshot(expectedDefaults);+ assert(read(C::savePath()) == exported); // Reset is not an implicit save.+ assert(C::load());+ expectSnapshot(edited);+ const unsigned loadedRevision = C::revision();+ assert(C::load());+ assert(C::revision() == loadedRevision);+ assert(C::initialize(directory.string()));+ expectSnapshot(edited);+ assert(read(C::savePath()) == exported);+ std::puts("PASS explicit save/reload and startup load preserve every float exactly; reset never writes");++ C::reset(2);+ auto resetSelected = edited;+ resetSelected[2] = expectedDefaults[2];+ expectSnapshot(resetSelected);+ assert(C::get(2).transparency == 0.769999981f);+ C::set(2, edited[2]);+ expectSnapshot(edited);+ const std::string legacy = versionOne(exported);+ write(C::savePath(), legacy);+ assert(C::load());+ auto upgraded = edited;+ for (auto &palette : upgraded) palette.transparency = 0;+ expectSnapshot(upgraded);+ assert(read(C::savePath()) == legacy); // Loading old palettes never rewrites them.+ assert(C::initialize(directory.string()));+ expectSnapshot(upgraded);+ assert(C::save());+ assert(read(C::savePath()).find("version = 2\n") != std::string::npos);+ assert(C::load());+ expectSnapshot(upgraded);+ write(C::savePath(), exported);+ assert(C::load());+ expectSnapshot(edited);+ std::puts("PASS version 1 palettes load with zero transparency; selected reset and explicit version 2 upgrade preserve other colors");++ const unsigned revision = C::revision();+ for (float invalid : {-0.001f, 1.001f, std::numeric_limits<float>::infinity(),+ std::numeric_limits<float>::quiet_NaN()}) {+ auto bad = edited[0];+ bad.main.g = invalid;+ C::set(0, bad);+ bad = edited[0];+ bad.shadow.b = invalid;+ C::set(0, bad);+ bad = edited[0];+ bad.transparency = invalid;+ C::set(0, bad);+ expectSnapshot(edited);+ }+ for (float invalid : {-0.01f, 2.001f, std::numeric_limits<float>::infinity(),+ std::numeric_limits<float>::quiet_NaN()}) {+ auto bad = edited[0];+ bad.brightness = invalid;+ C::set(0, bad);+ expectSnapshot(edited);+ }+ C::set(500, edit);+ C::reset(500);+ expectSnapshot(edited);+ assert(C::revision() == revision);+ assert(read(C::savePath()) == exported);+ std::puts("PASS invalid edits, NaN, infinities and invalid palette IDs cannot affect live colors");++ // Make an early valid edit, then damage the last palette. Rejection must+ // retain every live palette, including the early section that parsed OK.+ const std::string altered = replace(exported, "main = 0, 1,", "main = 0.5, 1,");+ const std::string brightnessLine = "brightness = 0\n";+ const std::string transparencyLine = "transparency = 1\n";+ const std::vector<std::string> badFiles = {+ replace(altered, "version = 2", "version = 3"),+ replace(altered, "version = 2", ""),+ replace(altered, "version = 2", "version = 2\nversion = 2"),+ replace(altered, "version = 2", "version = 1"), // New fields require the new version.+ replace(altered, "[nuclear]", "[unknown]"),+ replace(altered, "[nuclear]", "[toxin]"),+ replace(altered, brightnessLine, ""),+ replace(altered, brightnessLine, "brightness = nan\n"),+ replace(altered, brightnessLine, "brightness = inf\n"),+ replace(altered, brightnessLine, "brightness = -0.01\n"),+ replace(altered, brightnessLine, "brightness = 2.01\n"),+ replace(altered, brightnessLine, "brightness = 1 trailing\n"),+ replace(altered, brightnessLine, "brightness = 1\nbrightness = 1\n"),+ replace(altered, brightnessLine, "glow = 1\n"),+ replace(altered, transparencyLine, ""),+ replace(altered, transparencyLine, "transparency = nan\n"),+ replace(altered, transparencyLine, "transparency = inf\n"),+ replace(altered, transparencyLine, "transparency = -0.01\n"),+ replace(altered, transparencyLine, "transparency = 1.01\n"),+ replace(altered, transparencyLine, "transparency = 0.5 trailing\n"),+ replace(altered, transparencyLine, "transparency = 0.5\ntransparency = 0.5\n"),+ replace(altered, "main = 0.25, 1,", "main = nan, 1,"),+ replace(altered, "main = 0.25, 1,", "main = 0.25, 1.01,"),+ replace(altered, "main = 0.25, 1,", "main = 0.25, -0.01,"),+ replace(altered, "main = 0.25, 1,", "main = 0.25, 1e300,"),+ altered + "\nmalformed\n",+ };+ for (const auto &badFile : badFiles) {+ write(C::savePath(), badFile);+ assert(!C::load());+ expectSnapshot(edited);+ assert(C::revision() == revision);+ assert(read(C::savePath()) == badFile);+ assert(C::lastStatus().find("not loaded") != std::string::npos);+ }+ assert(!C::initialize(directory.string()));+ expectSnapshot(expectedDefaults);+ assert(read(C::savePath()) == badFiles.back());+ std::puts("PASS malformed/partial/out-of-range files are rejected transactionally and never overwritten");++ assert(C::save());+ assert(read(C::savePath()) == C::exportText());+ unsigned fileCount = 0;+ for (const auto &entry : fs::directory_iterator(directory)) {+ assert(entry.path().filename() == "cloud-colors.ini");+ ++fileCount;+ }+ assert(fileCount == 1); // Successful save leaves no temporary files.++ fs::remove(C::savePath());+ fs::create_directory(C::savePath()); // A rename failure must clean up.+ write(fs::path(C::savePath()) / "keep.txt", "preserve this");+ assert(!C::save());+ assert(read(fs::path(C::savePath()) / "keep.txt") == "preserve this");+ fileCount = 0;+ for (const auto &entry : fs::directory_iterator(directory)) {+ assert(entry.path().filename() == "cloud-colors.ini");+ ++fileCount;+ }+ assert(fileCount == 1);+ assert(C::initialize((temporary.path / "missing parent").string()));+ assert(!C::save());+ assert(!fs::exists(temporary.path / "missing parent"));+ assert(!C::initialize(""));+ assert(!C::save());+ std::puts("PASS atomic saves replace complete files and failures preserve data without temporary residue");+ std::puts("Cloud preview color checks passed.");+}diff --git a/GeneralsMD/Code/Tools/cloud_preview/test_flow.cpp b/GeneralsMD/Code/Tools/cloud_preview/test_flow.cppnew file mode 100644index 000000000..e24e80347--- /dev/null+++ b/GeneralsMD/Code/Tools/cloud_preview/test_flow.cpp@@ -0,0 +1,155 @@+// Standalone CPU checks for the isolated cloud preview's infantry wakes.+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.+#include "CloudPreviewFlow.h"++// These executable checks must also run in release builds.+#ifdef NDEBUG+#undef NDEBUG+#endif+#include <algorithm>+#include <cassert>+#include <chrono>+#include <cmath>+#include <cstdio>+#include <limits>+#include <vector>++namespace F = CloudPreviewFlow;++namespace {++unsigned valueCount()+{+ return F::width() * F::height() * 4;+}++std::vector<float> snapshot()+{+ return {F::data(), F::data() + valueCount()};+}++void checkBounds()+{+ assert(F::valid());+ for (unsigned i = 0; i < valueCount(); i += 4) {+ const float *pixel = F::data() + i;+ for (unsigned channel = 0; channel < 4; ++channel)+ assert(std::isfinite(pixel[channel]));+ assert(std::hypot(pixel[0], pixel[1]) <= 18.001f);+ // Flow must only transport smoke, never clear a body-shaped hole or+ // add a compressed ring. The reserved texture channels stay exact zero.+ assert(pixel[2] == 0 && pixel[3] == 0);+ }+}++void initialize()+{+ F::setDomain(300, 500, 1000, 780);+}++std::vector<float> runPath(float hz, float speed = 35.0f)+{+ initialize();+ for (unsigned i = 0; i < 3 * hz; ++i) {+ float time = (i + 1) / hz;+ F::Body body = {450 + time * speed, 640, 0, speed, 0, 6, 22};+ F::step(1.0f / hz, &body, 1);+ }+ checkBounds();+ return snapshot();+}++} // namespace++int main()+{+ auto start = std::chrono::steady_clock::now();+ initialize();+ for (unsigned i = 0; i < 60; ++i)+ F::step(1.0f / 60, nullptr, 0);+ assert(F::maxDisturbance() == 0);+ assert(std::all_of(F::data(), F::data() + valueCount(), [](float value) { return value == 0; }));+ std::puts("PASS empty field stays exactly zero");++ F::Body resting = {500, 640, 0, 0, 0, 6, 22};+ for (unsigned i = 0; i < 60; ++i)+ F::step(1.0f / 60, &resting, 1);+ assert(std::all_of(F::data(), F::data() + valueCount(), [](float value) { return value == 0; }));+ assert(F::maxDisturbance() == 0);+ std::puts("PASS resting body leaves every field channel exactly zero");++ auto at30 = runPath(30);+ float movingPeak = F::maxDisturbance();+ assert(movingPeak * 18 > 4 && movingPeak * 18 < 6);+ auto beforePause = snapshot();+ F::step(0, nullptr, 0);+ assert(beforePause == snapshot());+ std::puts("PASS moving infantry displace smoke; zero-delta freezes an active wake exactly");+ for (unsigned i = 0; i < 3 * 60; ++i)+ F::step(1.0f / 60, nullptr, 0);+ float after3 = F::maxDisturbance();+ for (unsigned i = 0; i < 3 * 60; ++i)+ F::step(1.0f / 60, nullptr, 0);+ float after6 = F::maxDisturbance();+ // Momentum continues transporting smoke briefly after the actor passes;+ // most displacement should settle in three seconds, then nearly vanish.+ assert(after3 < movingPeak * 0.25f);+ assert(after6 < movingPeak * 0.015f);+ std::printf("PASS wake displacement heals: initial %.5f, +3s %.5f, +6s %.5f world units\n",+ movingPeak * 18, after3 * 18, after6 * 18);++ auto at60 = runPath(60);+ auto at120 = runPath(120);+ double norm = 0, error30 = 0, error120 = 0;+ for (unsigned i = 0; i < valueCount(); ++i) {+ norm += std::abs(at60[i]);+ error30 += std::abs(at30[i] - at60[i]);+ error120 += std::abs(at120[i] - at60[i]);+ }+ assert(norm > 0);+ std::printf("Frame-rate path-relative L1 difference: 30 vs 60 %.3f%%, 120 vs 60 %.3f%%\n",+ 100 * error30 / norm, 100 * error120 / norm);+ assert(error30 / norm < 0.12);+ assert(error120 / norm < 0.001);+ std::puts("PASS equivalent path across frame rates");++ runPath(60, 20);+ float infantryDisplacement = F::maxDisturbance() * 18;+ std::printf("Typical infantry speed: 20 world units/s produces %.5f units of displacement\n",+ infantryDisplacement);+ assert(infantryDisplacement > 2 && infantryDisplacement < 4);++ initialize();+ F::Body teleported = {750, 640, 0, 50000, 0, 6, 22};+ F::step(1.0f / 30, &teleported, 1);+ for (unsigned i = 0; i < valueCount(); i += 4)+ assert(F::data()[i] == 0 && F::data()[i + 1] == 0);+ checkBounds();+ F::step(100, nullptr, 0);+ checkBounds();+ F::Body invalid = resting;+ invalid.x = std::numeric_limits<float>::quiet_NaN();+ F::step(1.0f / 30, &invalid, 1);+ assert(!F::valid());+ F::reset();+ assert(F::valid() && F::maxDisturbance() == 0 && F::activeBodies() == 0);+ std::puts("PASS teleport rejection, bounded stalled frame, invalid-input reporting and reset");++ // Four opposing paths exercise overlapping injections and solver bounds.+ initialize();+ for (unsigned i = 0; i < 600; ++i) {+ float time = i / 60.0f;+ F::Body bodies[4] = {+ {450 + 35 * time, 624, 0, 35, 0, 6, 22},+ {850 - 35 * time, 630, 0, -35, 0, 6, 22},+ {450 + 35 * time, 650, 0, 35, 0, 6, 22},+ {850 - 35 * time, 656, 0, -35, 0, 6, 22}+ };+ F::step(1.0f / 60, bodies, 4);+ if (i % 60 == 0) checkBounds();+ }+ assert(F::activeBodies() == 4);+ checkBounds();+ auto elapsed = std::chrono::duration<double>(std::chrono::steady_clock::now() - start).count();+ std::printf("PASS four crossing infantry remain finite and bounded; full test %.3fs\n", elapsed);+}diff --git a/GeneralsMD/Code/Tools/hazard-cloud-check.py b/GeneralsMD/Code/Tools/hazard-cloud-check.pynew file mode 100644index 000000000..b61041320--- /dev/null+++ b/GeneralsMD/Code/Tools/hazard-cloud-check.py@@ -0,0 +1,476 @@+#!/usr/bin/env python3+"""Exercise production hazard clouds with private profiles, real objects and the generals executable.++Installs nothing. All cases run sequentially. A prepared game-data root and built+runtime overlay are required. --prepare-only writes fixtures and commands without+starting the game. Screenshots are retained for visual review, not treated as proof+that the appearance is correct.+"""+import argparse+import hashlib+import importlib.util+import json+import math+import os+from pathlib import Path+import re+import shutil+import socket+import struct+import subprocess+import time++from control_client import Control, ControlError++HERE = Path(__file__).resolve().parent+FLAT_MAP = "Maps/HazardCloudCheck/HazardCloudCheck.map"+PALETTES = """# Real cleanup hazards run their ordinary weapons, lifetime and damage.+30 spawn 0 PoisonFieldMedium 1 500 500+30 spawn 0 PoisonFieldUpgradedMedium 1 780 500+30 spawn 0 Chem_PoisonFieldGammaMedium 1 500 780+30 spawn 0 RadiationFieldMedium 1 780 780+45 spawn 0 AmericaInfantryRanger 4 350 500 12+60 move 0 AmericaInfantryRanger 670 500+"""+CASES = {+ "palettes": dict(map=FLAT_MAP, camera=(640, 640), shot=360, stop=420,+ palettes=[0, 1, 2, 3], fixture=PALETTES),+ "nuclear": dict(map=FLAT_MAP, camera=(640, 640), shot=540, stop=660, palettes=[1],+ fixture="""# A live radiation owner plus the nuclear initial plume share one support.+30 spawn 0 RadiationFieldLarge 1 640 640+31 particles 0 NukeRadiationInitial 1 640 640+"""),+ "overlap": dict(map=FLAT_MAP, camera=(640, 640), shot=360, stop=420, palettes=[0],+ fixture="""# Intersecting hazards with different owners must retain independent volumes.+30 spawn 0 PoisonFieldMedium 1 580 640+30 spawn 0 PoisonFieldMedium 1 700 640+45 spawn 0 AmericaInfantryRanger 4 430 640 12+60 move 0 AmericaInfantryRanger 850 640+"""),+ "hillside": dict(map="Maps/Twilight Flame/Twilight Flame.map", camera=(1130, 3775),+ shot=360, stop=420, palettes=[0, 1], fixture="""# The documented toxinslope mound falls 15–17 units at its rim.+30 spawn 0 PoisonFieldLarge 1 1075 3775+30 spawn 0 RadiationFieldMedium 1 1250 3775+"""),+ "water": dict(map="Maps/Tournament Island/Tournament Island.map", camera=(480, 1050),+ shot=360, stop=420, palettes=[0, 1], fixture="""# Existing shoreline inspection position uses the baseline water renderer.+30 spawn 0 PoisonFieldMedium 1 480 1050+30 spawn 0 RadiationFieldMedium 1 620 1050+30 spawn 0 AmericaVehicleComanche 1 600 1000+60 move 0 AmericaVehicleComanche 300 1000+"""),+ "budget": dict(map=FLAT_MAP, camera=(640, 640), shot=360, stop=420, palettes=[0],+ fixture="30 spawn 0 PoisonFieldMedium 9 640 640 80\n"),+ "lifecycle": dict(map=FLAT_MAP, camera=(640, 640), shot=150, stop=480, palettes=[1],+ fixture="30 spawn 0 RadiationFieldSmall 1 640 640\n"),+}+OPTIONS = """Resolution = 1280 800+StaticGameLOD = Custom+IdealStaticGameLOD = High+DynamicLOD = no+TextureReduction = 0+TextureFilter = 2+Anisotropy = 8+ShadowQuality = 1+UseShadowVolumes = yes+UseShadowVolumesForSkins = yes+UseShadowDecals = yes+ShadowsForProps = yes+ShadowsForProjectiles = yes+ShadowsForParticles = yes+ShowTrees = yes+ShowSoftWaterEdge = yes+UseCloudMap = yes+UseLightMap = yes+MaxParticleCount = 3000+ExtraAnimations = yes+SmoothMotion = no+ShowNetBox = no+VSync = no+MSAA = 0+"""+ERROR = re.compile(r"Validation Error|VUID-|hazard-cloud[^\n]*(?:FAIL|failed)|shader[^\n]*(?:compilation failed|compile failed)", re.I)+REPORT = re.compile(r"^hazard-cloud(?P<fallback>-fallback)?: (?P<body>frame=\d+ .*)$", re.M)+CRC = re.compile(r"HEADLESS CRC AT LIMIT:\s*(.*?)\s+at frame (\d+)")+++def digest(path):+ return hashlib.sha256(path.read_bytes()).hexdigest()+++def write_json(path, value):+ path.write_text(json.dumps(value, indent=2) + "\n")+++def records(text):+ result = []+ for match in REPORT.finditer(text):+ row = dict(re.findall(r"(\w+)=([^ ]+)", match["body"]))+ row["fallback"] = bool(match["fallback"])+ for key in ("frame", "owner", "palette", "bodies", "cache"):+ if key in row:+ row[key] = int(row[key])+ for key in ("radius", "fringe", "age", "left", "density", "formation"):+ if key in row:+ row[key] = float(row[key])+ result.append(row)+ return result+++def map_crc(data):+ # Common/crc.h: rotate the 32-bit accumulator then add each byte.+ value = 0+ for byte in data:+ value = (((value << 1) | (value >> 31)) + byte) & 0xffffffff+ return value+++def write_flat_map(overlay):+ spec = importlib.util.spec_from_file_location("hazard_fixture_map", HERE / "cloud_preview/generate_map.py")+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ data = module.build_map()+ path = overlay / FLAT_MAP+ path.parent.mkdir(parents=True)+ path.write_bytes(data)+ # Release builds do not discover loose standard maps. Register only this+ # private fixture; the retail root and its MapCache.ini are never modified.+ (overlay / "Maps/MapCache.ini").write_text(f"""MapCache maps_5Chazardcloudcheck_5Chazardcloudcheck_2Emap+ fileSize = {len(data)}+ fileCRC = {map_crc(data)}+ timestampLo = 0+ timestampHi = 0+ isOfficial = yes+ isMultiplayer = yes+ numPlayers = 2+ extentMin = X:0 Y:0 Z:0+ extentMax = X:1280 Y:1280 Z:0+ nameLookupTag =+ Player_1_Start = X:180 Y:180 Z:0+ Player_2_Start = X:1100 Y:1100 Z:0+END+""")+++def prepare(args, name, case, style=1, live=False, user=None, load=None):+ out = args.out / name+ out.mkdir()+ if user is None:+ user = out / "user"+ user.mkdir()+ (user / "Options.ini").write_text(OPTIONS + f"CloudStyle = {style}\n")+ overlay = out / "overlay"+ overlay.mkdir()+ for entry in args.overlay.iterdir():+ if entry.name not in ("Maps", "Scenarios"):+ (overlay / entry.name).symlink_to(entry, target_is_directory=entry.is_dir())+ (overlay / "Scenarios").mkdir()+ # The ordinary hazard FX and fade policy query real cell visibility. Turning+ # off the displayed shroud does not reveal those cells. Airborne scouts keep+ # each field visible without taking its ground-only hazard damage.+ centres = re.findall(r"^\d+ spawn 0 \S*(?:PoisonField|RadiationField)\S* \d+ (\d+) (\d+)", case["fixture"], re.M)+ vision = "".join(f"5 spawn 0 AmericaVehicleComanche 1 {x} {y}\n" for x, y in dict.fromkeys(centres))+ (overlay / "Scenarios/hazard_check.txt").write_text(vision + case["fixture"])+ if case["map"] == FLAT_MAP:+ write_flat_map(overlay)+ elif (args.overlay / "Maps").exists():+ (overlay / "Maps").symlink_to(args.overlay / "Maps", target_is_directory=True)+ prefix = "hazard_" + name.replace("-", "_") + "_"+ command = [str(args.generals), "-root", str(args.root), "-overlay", str(overlay),+ "-offscreen", "-multiInstance", "-noaudio", "-win", "-xres", "1280", "-yres", "800",+ "-msaa", "0", "-quickstart", "-noshellmap", "-nologo", "-novideo", "-noFPSLimit", "-noshroud",+ "-camera", *map(str, case["camera"]), "-logPrefix", prefix]+ if load:+ command += ["-loadsave", load]+ else:+ command += ["-map", case["map"], "-autoskirmish", "2", "-takeover", "-seed", "1",+ "-side", "0", "FactionAmerica", "-side", "1", "FactionChina", "-observer",+ "-scenario", "hazard_check"]+ if live:+ command += ["-control", str(args.port)]+ else:+ command += ["-turbo", "-screenshot", str(case["shot"]), "-maxframes", str(case["stop"])]+ overrides = {"ZH_USER_DATA_DIR": str(user), "ZH_UNATTENDED": "1", "ZH_AUDIO_BACKEND": "null",+ "SDL_GPU_DRIVER": "vulkan", "ZH_OFFSCREEN_HZ": "0", "ZH_CLOUD_REPORT": "1"}+ if args.gpu_debug:+ overrides["ZH_GPU_DEBUG"] = "1"+ manifest = dict(case=name, command=command, environment=overrides, cloud_style=style,+ exe_sha256=digest(args.generals), options_sha256=digest(user / "Options.ini"),+ scenario_sha256=digest(overlay / "Scenarios/hazard_check.txt"),+ prepared_only=args.prepare_only, user=str(user), log_prefix=prefix, load=load)+ if case["map"] == FLAT_MAP:+ manifest["map_sha256"] = digest(overlay / FLAT_MAP)+ write_json(out / "manifest.json", manifest)+ return out, user, manifest+++def environment(manifest):+ env = dict(os.environ)+ for key in ("ZH_GPU_DEBUG", "ZH_CLOUD_PREVIEW_REBUILD_EVERY_FRAME", "ZH_GPU_TIMING"):+ env.pop(key, None)+ env.update(manifest["environment"])+ return env+++def finish(args, out, user, manifest, process):+ manifest["returncode"] = process.returncode+ log_name = manifest["log_prefix"] + "DebugLogFile.txt"+ # Packaged launches put logs in the isolated profile; development launches+ # may still write beside the executable. Prefer this run's private logs.+ for engine in (user / "Logs" / log_name, args.generals.parent / log_name):+ if engine.is_file():+ shutil.copyfile(engine, out / "engine.log")+ break+ text = (out / "run.log").read_text(errors="replace")+ engine_text = (out / "engine.log").read_text(errors="replace") if (out / "engine.log").exists() else ""+ manifest["diagnostics"] = records(text)+ manifest["errors"] = ERROR.findall(text)+ manifest["scenario_errors"] = [line for line in engine_text.splitlines()+ if "SCENARIO:" in line and any(term in line for term in ("refused", "no template", "cannot open", "no particle"))+ and "0 lines refused" not in line and not re.search(r"\b0 refused\b", line)]+ manifest["crc"] = [dict(crc=m[1], frame=int(m[2])) for m in CRC.finditer(engine_text)]+ manifest["screenshots"] = [dict(path=str(p), sha256=digest(p)) for p in sorted(user.rglob("sshot*.bmp"))]+ manifest["checks"] = []+ def check(name, condition):+ manifest["checks"].append(dict(name=name, passed=bool(condition)))+ check("process exited successfully", process.returncode == 0)+ check("no GPU/shader validation errors", not manifest["errors"])+ check("all production fixture actions accepted", not manifest["scenario_errors"])+ if not manifest["load"]:+ check("production scenario loaded", bool(re.search(r"SCENARIO: loaded .*?, [1-9]\d* actions, 0 lines refused", engine_text)))+ return check+++def assert_clouds(check, manifest, case, style):+ rows = manifest["diagnostics"]+ active = [r for r in rows if not r["fallback"]]+ expected = set(case["palettes"])+ if style == 0:+ check("Classic emits no volumetric draws", not active)+ check("Classic retains the original hazard path", expected <= {r.get("palette") for r in rows if r.get("reason") == "classic"})+ return+ check("all requested palettes reached the production renderer", expected <= {r.get("palette") for r in active})+ check("fields are finite and bounded", bool(active) and all(+ all(math.isfinite(r.get(k, math.nan)) for k in ("radius", "fringe", "age", "left", "density", "formation"))+ and r["radius"] > 0 and r["fringe"] >= 0 and 0 <= r["density"] <= 1 and 0 <= r["formation"] <= 1+ for r in active))+ check("nuclear fades across its full footprint", all(r["formation"] == 1 for r in active if r["palette"] == 1))+ if manifest["case"] == "budget":+ check("only the expected budget fallback occurred", all(r.get("reason") == "budget" for r in rows if r["fallback"]))+ by_frame = {}+ for r in active:+ by_frame.setdefault(r["frame"], set()).add(r["owner"])+ check("eight owners admitted without exceeding the layer limit", bool(by_frame) and max(map(len, by_frame.values())) == 8)+ check("additional hazards retain the Classic fallback", any(r.get("reason") == "budget" for r in rows))+ else:+ check("all visible hazards stay volumetric", not any(r["fallback"] for r in rows))+ if manifest["case"] == "nuclear":+ check("initial and lingering nuclear systems share one owner", len({r["owner"] for r in active}) == 1)+ check("nuclear support preserves the 200-unit hazard radius", bool(active) and all(abs(r["radius"] - 200) < .01 for r in active))+ if manifest["case"] == "overlap":+ by_frame = {}+ for r in active:+ by_frame.setdefault(r["frame"], set()).add(r["owner"])+ check("overlapping owners retain distinct fields", any(len(v) >= 2 for v in by_frame.values()))+ if manifest["case"] == "hillside":+ check("uneven terrain uses the volumetric path", not any(r.get("reason") == "nonplanar" for r in rows))+ if manifest["case"] == "lifecycle":+ samples = sorted({r["frame"]: r for r in active}.values(), key=lambda r: r["frame"])+ check("expired particles preserve one hazard identity", len(samples) >= 2 and len({r["owner"] for r in active}) == 1)+ check("cloud age does not restart after expiry", len(samples) >= 2 and all(b["age"] >= a["age"] for a, b in zip(samples, samples[1:])))+ peak = max(range(len(samples)), key=lambda i: samples[i]["density"]) if samples else 0+ check("short-lived nuclear field fades without rebounding", peak + 1 < len(samples)+ and all(b["density"] <= a["density"] for a, b in zip(samples[peak:], samples[peak+1:])))+++def run_case(args, name, case, style=1):+ out, user, manifest = prepare(args, name, case, style)+ if args.prepare_only:+ return manifest+ start = time.monotonic()+ with (out / "run.log").open("w") as log:+ process = subprocess.Popen(manifest["command"], cwd=out, env=environment(manifest), stdout=log, stderr=subprocess.STDOUT)+ try:+ process.wait(timeout=args.timeout)+ except subprocess.TimeoutExpired:+ process.kill()+ process.wait()+ manifest["timeout"] = True+ manifest["elapsed_seconds"] = time.monotonic() - start+ check = finish(args, out, user, manifest, process)+ check("reached the requested logic frame", any(r["frame"] == case["stop"] for r in manifest["crc"]))+ check("one screenshot captured", len(manifest["screenshots"]) == 1)+ assert_clouds(check, manifest, case, style)+ write_json(out / "manifest.json", manifest)+ print(name, "PASS" if all(c["passed"] for c in manifest["checks"]) else "FAIL", flush=True)+ return manifest+++def connect(process, port, timeout):+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if process.poll() is not None:+ raise RuntimeError("game exited before opening its control socket")+ try:+ return Control(port, timeout=5)+ except (OSError, ControlError):+ time.sleep(.1)+ raise TimeoutError("control socket did not open")+++def send(game, command):+ reply = game.send(command)+ if not reply.get("ok"):+ raise RuntimeError(f"{command}: {reply}")+ return reply+++def wait_frame(game, frame, timeout=45):+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ status = game.status()+ if status.get("inGame") and status["frame"] >= frame:+ return status+ time.sleep(.025)+ raise TimeoutError(f"game did not reach frame {frame}")+++def console(game, line):+ send(game, "key KEY_TICK")+ for char in line:+ send(game, "key KEY_SPACE" if char == " " else "key KEY_" + char.upper())+ send(game, "key KEY_ENTER")+ send(game, "key KEY_TICK")+++def capture(game, user, target, timeout=10):+ before = {p: p.stat().st_mtime_ns for p in user.rglob("sshot*.bmp")}+ send(game, "screenshot")+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ new = [p for p in user.rglob("sshot*.bmp") if p.stat().st_mtime_ns != before.get(p)]+ if new:+ path = sorted(new)[0]+ with path.open("rb") as bitmap:+ header = bitmap.read(6)+ if len(header) == 6 and header[:2] == b"BM" and path.stat().st_size == struct.unpack("<I", header[2:])[0]:+ shutil.copyfile(path, target)+ return+ time.sleep(.05)+ raise TimeoutError("requested screenshot did not arrive")+++def live_session(args, name, case, user=None, load=None):+ out, user, manifest = prepare(args, name, case, live=True, user=user, load=load)+ if args.prepare_only:+ return manifest, user+ game = None+ with (out / "run.log").open("w") as log:+ process = subprocess.Popen(manifest["command"], cwd=out, env=environment(manifest), stdout=log, stderr=subprocess.STDOUT)+ try:+ game = connect(process, args.port, args.timeout)+ status = wait_frame(game, 120 if not load else 1)+ start = status["frame"]+ wait_frame(game, start + 90)+ if load:+ capture(game, user, out / "restored.bmp")+ manifest["restored_frame"] = game.status()["frame"]+ else:+ capture(game, user, out / "volumetric-before.bmp")+ console(game, "set cloudstyle 0")+ classic = game.status()["frame"]+ wait_frame(game, classic + 150)+ capture(game, user, out / "classic.bmp")+ console(game, "set cloudstyle 1")+ modern = game.status()["frame"]+ wait_frame(game, modern + 150)+ capture(game, user, out / "volumetric-after.bmp")+ manifest["classic_interval"] = [classic + 30, modern - 30]+ manifest["modern_after"] = modern + 30+ manifest["save_frame"] = game.status()["frame"]+ send(game, "save hazard-cloud-check")+ manifest["save_files"] = [str(p) for p in user.rglob("hazard-cloud-check.sav")]+ except (OSError, RuntimeError, TimeoutError) as exc:+ manifest["exception"] = str(exc)+ finally:+ if game:+ try:+ send(game, "quit")+ except (OSError, ControlError):+ pass+ game.close()+ try:+ process.wait(timeout=10)+ except subprocess.TimeoutExpired:+ process.kill()+ process.wait()+ check = finish(args, out, user, manifest, process)+ check("control actions completed", "exception" not in manifest)+ active = [r for r in manifest["diagnostics"] if not r["fallback"]]+ if load:+ check("save restored live hazard objects", set(case["palettes"]) <= {r["palette"] for r in active})+ check("restored screenshot captured", (out / "restored.bmp").is_file())+ else:+ first, last = manifest.get("classic_interval", [0, 0])+ middle = [r for r in manifest["diagnostics"] if first <= r["frame"] <= last]+ check("live Classic removes volume draws", last > first and not any(not r["fallback"] for r in middle))+ check("live Classic preserves the original hazard path", any(r.get("reason") == "classic" for r in middle))+ check("switching back restores active hazards", any(r["frame"] >= manifest.get("modern_after", math.inf) for r in active))+ check("live choice persisted", bool(re.search(r"^CloudStyle\s*=\s*1\s*$", (user / "Options.ini").read_text(), re.M)))+ check("save file written", bool(manifest.get("save_files")))+ write_json(out / "manifest.json", manifest)+ print(name, "PASS" if all(c["passed"] for c in manifest["checks"]) else "FAIL", flush=True)+ return manifest, user+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ for name in ("generals", "root", "overlay", "out"):+ parser.add_argument("--" + name, type=Path, required=True)+ parser.add_argument("--case", choices=list(CASES), action="append", help="repeat to select cases; default all")+ parser.add_argument("--live", action="store_true", help="also test live Classic switching and save/reload")+ parser.add_argument("--crc-pair", action="store_true", help="repeat palettes in Classic and require equal game-state CRC")+ parser.add_argument("--gpu-debug", action="store_true")+ parser.add_argument("--prepare-only", action="store_true")+ parser.add_argument("--timeout", type=int, default=180)+ parser.add_argument("--port", type=int)+ args = parser.parse_args()+ if args.timeout <= 0 or (args.port is not None and not 0 < args.port < 65536):+ parser.error("timeout must be positive and port must be between 1 and 65535")+ for name in ("generals", "root", "overlay", "out"):+ setattr(args, name, getattr(args, name).resolve())+ if not args.generals.is_file() or not args.root.is_dir() or not args.overlay.is_dir():+ parser.error("the executable, prepared data root and overlay must already exist")+ if args.port is None:+ with socket.socket() as probe:+ probe.bind(("127.0.0.1", 0))+ args.port = probe.getsockname()[1]+ args.out.mkdir(parents=True, exist_ok=False)+ results = []+ for name in dict.fromkeys(args.case or CASES):+ results.append(run_case(args, name, CASES[name]))+ if args.crc_pair:+ modern = next((r for r in results if r["case"] == "palettes"), None)+ if modern is None:+ modern = run_case(args, "palettes", CASES["palettes"])+ results.append(modern)+ classic = run_case(args, "palettes-classic", CASES["palettes"], 0)+ if not args.prepare_only:+ classic["checks"].append(dict(name="Classic and Volumetric preserve the same game-state CRC", passed=bool(modern["crc"]) and modern["crc"] == classic["crc"]))+ write_json(args.out / "palettes-classic/manifest.json", classic)+ results.append(classic)+ if args.live:+ live, user = live_session(args, "live", CASES["palettes"])+ results.append(live)+ if args.prepare_only or live.get("save_files"):+ loaded, _ = live_session(args, "load", CASES["palettes"], user, "hazard-cloud-check")+ results.append(loaded)+ summary = dict(prepared_only=args.prepare_only, results=results)+ summary["passed"] = args.prepare_only or all(all(c["passed"] for c in r.get("checks", [])) for r in results)+ write_json(args.out / "summary.json", summary)+ print(json.dumps(dict(summary=str(args.out / "summary.json"), passed=summary["passed"], prepared_only=args.prepare_only)))+ return 0 if summary["passed"] else 1+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/GeneralsMD/Code/Tools/optionsmenu_layout.py b/GeneralsMD/Code/Tools/optionsmenu_layout.pyindex ccb4a55da..a86cf2bc8 100644--- a/GeneralsMD/Code/Tools/optionsmenu_layout.py+++ b/GeneralsMD/Code/Tools/optionsmenu_layout.py@@ -165,6 +165,8 @@ NEW_CONTROLS = [(COMBO, "ComboBoxFullscreenScaling", None),(CHECK, "CheckVSync", "GUI:VSync"),(CHECK, "CheckClassicGraphics", "GUI:ClassicGraphics"),+ (LABEL, "LabelCloudStyle", "GUI:CloudStyle"),+ (COMBO, "ComboBoxCloudStyle", None),(LABEL, "LabelMSAA", "GUI:MSAA"),(COMBO, "ComboBoxMSAA", None),(LABEL, "LabelBloom", "GUI:Bloom"),@@ -338,7 +340,8 @@ GROUP_LAYOUT = [setting("LabelLightingStyle", "ComboBoxLightingStyle"),setting("LabelBloom", "ComboBoxBloom"),("check", "CheckGroundLighting"),- ("check", "CheckHeatEffects")])]),+ ("check", "CheckHeatEffects"),+ setting("LabelCloudStyle", "ComboBoxCloudStyle")])]),("PageEffects", [("GUI:OptionsGroupShadows",@@ -919,6 +922,16 @@ def selfcheck():% (os.path.basename(LAYOUT), ADVANCED))problems.extend(overlaps(layout))+ # Hazard appearance is a Graphics setting, independent of particle thickness.+ graphics = layout.find("PageGraphics")+ cloud_label = layout.find("LabelCloudStyle")+ cloud = layout.find("ComboBoxCloudStyle")+ if graphics and cloud_label and cloud:+ if cloud not in graphics.children or cloud_label not in graphics.children:+ problems.append("CloudStyle must be on the Graphics page")+ if cloud_label.rect[1] != cloud.rect[1] - ROW_HEIGHT:+ problems.append("CloudStyle label must sit above its combo box")+for problem in problems:print("optionsmenu: %s" % problem)if problems:diff --git a/docs/cloud-preview.md b/docs/cloud-preview.mdnew file mode 100644index 000000000..2d9437b62--- /dev/null+++ b/docs/cloud-preview.md@@ -0,0 +1,480 @@+# Isolated toxin and radiation preview++`cloud_preview` is a separate development executable using the current game renderer,+particle definitions, terrain, and animated infantry. It opens a small inspection yard+with the Toxin Tractor's Contaminate release selected by default. Eight scenes cover+cloud comparisons and individual toxin or radiation sources. Four Rangers walk+through the clouds. All releases are visual only: source vehicles, buildings, bombs,+and missiles are render models, without their gameplay objects. The preview does not+fire weapons, activate special powers, execute object-creation lists, or create+gameplay hazards. The infantry remain passive, unable to attack, and indestructible;+their health is checked against its initial value.++The yard includes low structures, crates and barrels inside or along cloud edges,+plus a shallow pond beneath their near edge. This makes it possible to judge+building silhouettes, ground visibility, shoreline coverage and the baseline water surface+through the smoke. Scenery uses render-only models; the four walking lanes remain+clear and dry. The pond uses the unchanged baseline water renderer. The production runtime harness uses a separate flat fixture.++Volumetric smoke is the default in this executable. Each source keeps its full field+radius, centre, and infantry-height bounds throughout the sequence. As the release+begins, a thin veil covers the full footprint. Toxin and anthrax billows build outward+inside it; nuclear smoke gradually fades in across the entire area, without a+spreading front. Nuclear missile fallout takes six seconds to form after impact;+cannon and reactor fallout take three. The source then lets the smoke linger and+fade. Formation changes the density inside the fixed bounds rather than expanding+the radius, moving the centre, or raising the height. The renderer marches the camera+ray through that density,+accumulating light and opacity. It uses the opaque scene's depth to stop at terrain+and infantry, and samples density toward the light to shade the cloud's own interior.+The cloud's top is set to the infantry's measured model height, with authored collision+height as a fallback. Procedural noise uses world-space sizes, so a larger field+contains more billows instead of stretching one shape. Curling motion and rolling+tops animate the density, with outward source transport for toxin/anthrax. Lighter green, blue, purple, and+warm radiation palettes retain their colour in shadow through scattered fill light.+Where fields overlap, their density and light contributions are integrated together+along the view ray. A small persistent+flow field responds to the infantry's actual positions and velocities: movement+stirs the smoke's density into side curls and a trailing flow that gradually settles.+The response is weighted by height. Infantry have no surrounding clear bubble or+dense rim; smoke can remain in front of them and ordinary scene depth handles their+visible surfaces. Standing still injects no disturbance. Wakes move the billows but+leave the thin coverage veil in place, so infantry do not carve apparently safe holes+through the reference hazard footprint.++This is a local interaction model with planar flow and decay, not a full 3D fluid+solver. It affects smoke appearance; it does not push or damage the infantry.++Nuclear volumes mix charcoal-grey billows into a darker amber haze and shed sparse+orange-gold embers. Broad heat ripples rise through the air, bending both the cloud+contours and the scenery and infantry inside them. The distortion builds with the+release and fades with the field. Green toxin, blue anthrax, and purple gamma retain+their existing appearance. Press H to compare nuclear heat on/off, including while+paused, or start with `--no-heat`. H controls only refraction; the charcoal smoke and+embers remain. All three additions apply only to volumetric mode; original game+effects remain the original reference.++The shimmer samples a private copy of scene colour taken after cloud and ember+rendering, so dense smoke cannot hide the distortion. Displacement is capped at+eight pixels. Four-tap depth checks allow an immersed unit's silhouette to bend+with the surrounding haze when both surfaces lie within the same nuclear field.+The warp uses a continuous air interval and broad lateral waves across those+silhouettes, rather than changing at the unit's surface. Foreground objects outside+the field still retain+the depth guard. The hot-air envelope reaches 2.6 times the+cloud height; the smoke itself keeps its infantry-height bounds. No bubble or rim+is added around units. Animation uses simulation time and freezes on pause. The+original explosion and fire particles draw afterward and are not refracted.++Charcoal patches are baked into the existing nuclear lighting cache, retaining the+amber coverage veil and the source's formation and dissipation. Each active nuclear+field adds 24–96 GPU-generated ember billboards with small glowing cores, short tails,+upward drift, and gradual fading. Evenly spaced, slightly jittered anchors fill the+whole circular footprint, including its visual fringe, with a gentle fade at the+outermost edge. Counts scale with visible area: 64 in comparison, 96 for the+missile, and 24 for cannon/reactor fallout. Formation controls their opacity without+contracting their radius. They rise above the smoke to at most 2.76 times+its height, respect opaque scene depth, and require no new texture assets or+gameplay particle objects. Cleared fields and original mode draw no embers.++Two appearances are available in every scene:++| Appearance | What it shows |+| --- | --- |+| Original | The current game's field templates and colours for the selected toxin, anthrax, or radiation source |+| Volumetric | World-space density rendered by ray marching, with opaque-depth intersections and internal shadowing |++Keys 1, 2, and C change the cloud appearance within the current scene. They keep+the exact release phase, source model and release particles, infantry positions,+and stored volumetric wake. Selecting another scene keeps the chosen appearance.+Use 1 and 2 for a direct original/volumetric comparison, including while paused.+Key 3 remains an alias for volumetric smoke for compatibility with earlier previews.++The volume renderer, shaders, embers and flow live in the shared+`SdlHazardCloud` implementation. The normal Linux game exposes **Cloud style:+Classic / Volumetric** on the Graphics page. This executable retains its+own harmless scenes, A/B controls and palette editor; its Classic comparison is+independent of the normal game's saved cloud setting. Production fields read actual+gameplay radii and lifetimes and support terrain-following ground heights.++## Live color controls++The color panel opens with the demo. Press **P** to hide or show it. It has independent+palettes for **Toxin**, **Toxin beta** (blue), **Toxin gamma** (purple), and **Nuclear**.+Choose a palette, then drag the RGB sliders for its **Main** or **Shadow** color.+The swatch shows the rounded hex and RGB values; brightness ranges from 0 to 200%.+Each palette also has **Transparency**, from 0 to 100%. Zero uses the original+optical thickness; increasing it makes the cloud easier to see through, and 100%+hides its smoke. This changes optical thickness and self-shadowing without shrinking the+footprint or changing its source timing, formation or infantry wakes. Nuclear+heat and embers remain independent; use H to compare heat distortion separately.+Main controls the lit color, Shadow controls the shade (including nuclear charcoal+billows), and Brightness affects the whole cloud. These are material colors, so+the rendered result also depends on the cloud's lighting and transparency.++The preview and normal Linux game use these approved defaults. The table shows+rounded labels; the exact linear RGB, brightness and transparency floats are in+[preferred.ini](../GeneralsMD/Code/Tools/cloud_preview/presets/preferred.ini) and the+matching compiled palettes. Preserve those floats when editing or exporting; do+not reconstruct them from the hex labels.++| Cloud | Main | Shadow | Brightness | Transparency |+| --- | --- | --- | --- | --- |+| Toxin | `#C4F08C` | `#20510E` | 70% | 67% |+| Toxin beta | `#A8C2FF` | `#111A36` | 153% | 77% |+| Toxin gamma | `#D6A1FF` | `#310C3C` | 132% | 74% |+| Nuclear | `#BFAB78` | `#4C2F12` | 130% | 0% |++A valid existing preview preset loads automatically at startup. If the file is+absent, the preview uses its compiled defaults without creating a preset. A+malformed startup file reports an error and leaves those defaults intact; a failed+manual reload keeps the currently active palettes. The normal game always uses+its approved compiled defaults independently of preview files. **Reset palette**+applies those defaults to the selected palette; **Save all** keeps the result for+later preview runs.++Palette selection alone leaves the scene alone. **Show scene** opens that palette's+source in volumetric mode and resumes playback so the cloud can form. The scene+keys F2–F8 select the corresponding palette when changing scenes. Use **Space** to+freeze a useful frame: colors still update immediately while paused, without+replaying the release or changing infantry positions. Original mode remains the+unchanged game reference; edited colors appear when switching back to volumetric.++- **Reset palette** restores that palette's user-approved colors, brightness and+ transparency from the table above.+- **Save all** writes all four palettes to `cloud-colors.ini` in the preview user+ directory, by default `build-linux/cloud-preview/user/cloud-colors.ini`.+- **Load saved** reloads that file. Saved palettes also load automatically at startup.+- **Copy all** places the complete palette settings on the clipboard. Paste them+ into a text file to share colors and transparency; the text is a complete preset.++Edits and resets are live but are not saved automatically. Saving explicitly replaces+the previous preset atomically; invalid files are rejected without partially applying+their contents. The file preserves exact floating-point colors, while its hex comments+are rounded for readability. Different `--user-dir` profiles keep separate presets.+`--no-color-panel` starts with the panel hidden; P can still open it.+New exports use version 2 and include `transparency = 0..1` in every palette.+Existing version 1 presets load with zero transparency, preserving their appearance.++Versioned presets are kept in+`GeneralsMD/Code/Tools/cloud_preview/presets/preferred.ini` and+`GeneralsMD/Code/Tools/cloud_preview/presets/pre-tuning.ini`. The first contains+the approved defaults above; the second preserves the colors from before tuning.+To compare the earlier colors, copy `pre-tuning.ini` to a separate preview profile+as `cloud-colors.ini`, then launch with `--user-dir` pointing to that profile.+This leaves the preferred preset in the normal preview profile intact.++The editor uses the existing in-game UI renderer and adds no dependency. Palette+changes refresh cached lighting, including paused views. Procedural cloud shapes,+hazard coverage, formation, infantry interaction, heat eligibility, and ember behavior+stay unchanged.++The palette persistence checks can be run without opening the game:++```sh+mkdir -p build-linux/cloud-preview+g++ -std=c++17 -O2 -Wall -Wextra -Werror -IGeneralsMD/Code/Tools \+ GeneralsMD/Code/Tools/cloud_preview/test_colors.cpp \+ GeneralsMD/Code/Tools/CloudPreviewColors.cpp \+ -o build-linux/cloud-preview/test_colors+./build-linux/cloud-preview/test_colors+```++These cover exact default colors and save/load roundtrips, startup loading, invalid+edits and preset files, and failed saves preserving the previous preset. Tests use+temporary directories and do not change the preview's saved colors.++For a live UI check, pause each palette's scene and compare transparency at 0%,+50% and 100%. Confirm that Reset restores the approved values, Original effects+stay unchanged, and nuclear heat/embers remain independent of smoke transparency.+Exercise sliders and buttons at 640 × 480 and 800 × 600, including+hiding the panel during a drag. Save, copy, reload and restart with an isolated+`--user-dir`; compare the complete exported floats after each step. Retain captures+and GPU validation logs for the executable being reviewed.++## Rendering cost++The volume is integrated into a half-width, half-height RGBA16F target, so the main+ray pass evaluates one quarter as many pixels. A full-resolution composite blends+premultiplied light and opacity, checking the opaque depth of each sample. Local+surface slopes keep ordinary terrain from being mistaken for a silhouette. Samples+across an object edge are rejected; if none match, that pixel is ray marched at full+resolution to retain thin infantry silhouettes. Odd target dimensions retain their+last row and column. The scratch target is reused and replaced safely on size changes.++Density and internal lighting are evaluated into a world-space volume cache+before the camera ray pass. Each field uses 24 height slices, stored as a 2D atlas,+with horizontal sample spacing of at most two world units for the current scenes.+One pass builds density; another evaluates the same three sunlight samples and+stores scattered light and extinction. Camera rays interpolate these cached values+instead of repeating procedural noise and sunlight calculations at every step.+The full hazard footprint, source formation, palettes, height, and infantry flow+remain in use. Grid interpolation adds slight smoothing to the smallest details.+Density evaluation also skips billow cells beyond their support and calculations+whose masks contribute exactly zero.++The cache refreshes when simulation time, source state, field geometry, palette,+or infantry flow changes. Paused views and additional rendered frames reuse it;+camera motion still gets a fresh depth-clipped ray pass. Atlases are reused until+their size changes, with old textures retired after their recorded GPU users.+Atlas storage depends on the field dimensions. Production admission allows eight+visible layers within a 192 MiB atlas-cache budget, with Classic fallback for+fields that cannot be admitted. Shared screen scratch targets are outside that+budget. The preview owns at most two fields in a layer; the game assigns layers+to independently recognized hazard owners.++Heat adds one GPU colour copy and a small pass restricted to the projected hot-air+envelope. Keeping it separate lets the cloud ray/composite shaders retain their lower+cost. It does not add ray-march steps or rebuild the volume cache. The colour image+is reused (about 3.9 MiB at 1280 × 800); toxin-only scenes, cleared fields, offscreen+nuclear fields, and heat-off comparisons skip the copy. No CPU readback or extra+GPU wait is introduced.++Nuclear charcoal colouring adds two noise samples per lighting-cache voxel, with+no additional camera-ray samples. Embers add one small draw per active nuclear+field and no particle simulation or texture allocation.++The preview's two comparison fields share a 48–96 sample ray budget based on the+length of their combined interval. Coincident intervals use 48 samples instead of+doubling the work; intervals spanning twice the distance use 96. Both fields'+extinction and light are still accumulated together at each sample.++Measure the current build with the engine's existing timer from the repository+root. Use a new profile and stop other GPU workloads before each run:++```sh+mkdir -p build-linux/cloud-preview+ZH_UNATTENDED=1 ZH_OFFSCREEN_HZ=0 ZH_GPU_TIMING=12,1200 \+ ZH_CLOUD_PREVIEW_REBUILD_EVERY_FRAME=1 \+ ./build-linux/cloud_preview --scenario comparison --offscreen --frames 2400 \+ --no-color-panel \+ --user-dir "$PWD/build-linux/cloud-preview/perf-check" \+ > build-linux/cloud-preview/perf-check.log 2>&1+```++This excludes display pacing and begins timing twelve seconds after the first+Present. Keep shader compilation, captures and other setup outside the measured+window. Omit `ZH_CLOUD_PREVIEW_REBUILD_EVERY_FRAME` for ordinary cache reuse; with+it set, every rendered frame rebuilds the volume cache, including frames without+a new simulation step. The switch affects the shared renderer in both executables+and should be unset for ordinary play. Shutdown statistics report cache rebuilds,+field bakes and rendered frames.++For comparisons, build each revision in its own checkout/build directory and use+separate preview profiles with identical palettes. Record revision and executable+hash, compiler/build settings, GPU/driver, resolution, scenario, camera, profile+contents, heat and interaction settings, timing window and frame-time distribution.+Run revisions sequentially under comparable conditions. Preview timings include the+whole isolated scene; they do not predict a crowded battle's frame rate. Measure+representative gameplay separately with the same map/save, camera and settings.++## Field footprint++The field radius is the retail hazard radius listed below, or 115 units in the+comparison scene. It remains fixed during formation, lingering, and dissipation.+The original ground renderer scatters textured puddles within that radius; each+puddle can visibly extend beyond its centre. The volumetric renderer therefore uses+a separate soft fringe to cover that visible reach without changing the reference+hazard radius.++The fringe comes from the loaded particle template, including INI overlays and+frame-rate conversion. It follows the original ground renderer's half-life puddle+size and adds `sqrt(2) × 1.04 × puddle half-size` beyond the field radius. This accounts+for the rotated square's diagonal and its maximum four-percent breathing expansion.+It is a conservative visual extent, not an increase in gameplay coverage. The veil+fades through that fringe, and billows soften toward it. The cloud's maximum height+stays tied to the infantry model independently of the horizontal footprint.++## Source scenes++| Key | `--scenario` | Source and field |+| --- | --- | --- |+| F1 | `comparison` | Steady toxin on the left and radiation on the right, each with a 115-unit preview radius |+| F2 | `tractor` | Toxin Tractor / Contaminate: green toxin, 80-unit radius; the default scene |+| F3 | `anthrax` | Anthrax Bomb: blue anthrax, 300-unit radius |+| F4 | `gamma` | Dr. Thrax's Gamma Bomb: purple anthrax, 300-unit radius |+| F5 | `toxin-building` | Dr. Thrax's SCUD Storm destruction: green toxin, 80-unit radius |+| F6 | `nuke` | Nuclear missile impact: radiation, 200-unit radius |+| F7 | `nuke-cannon` | Nuclear cannon shell impact: radiation, 50-unit radius |+| F8 | `reactor` | Nuclear reactor destruction: radiation, 50-unit radius |++The source scenes use retail field radii, source models, and individual release+particle templates. For example, the tractor uses `UVToxinTrk` and `ToxinSpray`;+the bombs use `AVBomber_B` with the `AnthraxBomb*` or `AnthraxGammaBomb*` particles;+and the nuclear scenes reuse the `Nuke*` or `NukeCannon*` explosion particles.+The lingering fields use the selected appearance with green toxin, blue anthrax,+purple gamma, and radiation palettes. Original mode selects the retail field template+for that source; volumetric mode uses the preview's density renderer. The visible+source release and its timing are shared across both appearances.++The building example is specifically `Chem_GLAScudStorm`, whose retail death+behaviours create `OCL_PoisonFieldMedium` and play+`WeaponFX_BombTruckHighExplosiveBioBombDetonation`. The preview uses its `UBScudStrm`+and `UBScudStrm_E` models and the individual `BombTruckHEBio*` release particles;+it never executes that OCL or the building's death logic. Its green pool matches this+source; this is not a claim that every Dr. Thrax building emits toxin when destroyed.++The sequence is isolated choreography for inspection, with compressed timings of+roughly half a minute per loop (about 25–35 seconds, with the cannon shorter).+It is not a simulation of retail weapon timing or damage lifetime. In the game,+Contaminate's lingering field is created after spraying stops and its lifetime+depends on spray duration; the bomb fields last 60 seconds, while the selected+building and radiation pools last 30 seconds. Here every source visibly builds up,+lingers, and dissipates, then repeats unless looping is disabled. Comparison mode+keeps both fields formed for appearance and infantry-motion inspection.++## Build and launch++Run these commands from the repository root, using an already configured Linux+Release build with its existing dependencies:++```sh+cmake --build build-linux --target cloud_preview+./build-linux/cloud_preview+```++To select a source and watch one release through dissipation:++```sh+./build-linux/cloud_preview --scenario anthrax --no-loop+```++To select an appearance at startup:++```sh+./build-linux/cloud_preview --classic+./build-linux/cloud_preview --volumetric+./build-linux/cloud_preview --volumetric --no-interaction+./build-linux/cloud_preview --scenario comparison --no-heat+./build-linux/cloud_preview --scenario gamma --classic --no-loop+```++`--classic` and `--volumetric` select the appearance of the chosen+`--scenario`, or the tractor when no source is specified. Use `--scenario comparison`+for the steady two-field view. `--no-loop` leaves the scene clear after its release;+press B to replay it or L to enable looping.++The target is excluded from the default build. Python 3, used only to generate the+inspection map, must already be available when CMake configures the target. If the+target is absent, inspect the existing CMake configuration and dependencies before+reconfiguring; a normal game build does not build or verify the preview. Shared+`SdlHazardCloud` implementation units belong to `w3ddevice`; CMake excludes them+from the low-level `posixd3d9` library. Preview controller and editor units are linked+only into `cloud_preview`.++The executable reads the same original game assets as the game;+it finds the saved installation or searches the existing known/Steam locations.+If discovery fails, specify the Zero Hour folder containing `INIZH.big`:++```sh+./build-linux/cloud_preview --data "/path/to/Command & Conquer Generals - Zero Hour"+```++Keep the original Generals data adjacent or in `ZH_Generals`, as with the normal game.+A separate Generals location saved in the player's registry is carried into a new+preview profile when needed.++## Controls++| Input | Action |+| --- | --- |+| F1–F8 | Select the scene listed above |+| [ / ] | Previous / next scene |+| B | Replay the current release |+| L | Toggle automatic looping |+| 1 | Original game effects in the current scene |+| 2 | Volumetric smoke in the current scene |+| 3 | Alias for 2, retained for compatibility |+| C | Toggle Original ↔ Volumetric without restarting the release |+| I | Toggle infantry wakes in volumetric smoke |+| H | Toggle nuclear heat shimmer in volumetric smoke |+| P | Show/hide the live cloud color panel |+| Arrow keys or screen edges | Pan |+| Mouse wheel | Zoom |+| Q / E | Orbit by −45° / +45°, including while paused |+| R | Reset orientation and zoom to the initial height, including while paused |+| Middle mouse drag | Rotate and tilt |+| Middle mouse click | Reset orientation |+| Space | Pause/resume |+| F12 | Save a BMP screenshot, including while paused |+| Escape or window close | Exit |++The default window is 1280 × 800; `--width` and `--height` select another size.+The ordinary command bar is hidden and the walking units cannot be selected.+The window title shows the scene, release phase, appearance, looping, and volumetric wakes.+Switching between original and volumetric smoke is immediate, including while paused.+For a fixed-time comparison, pause with Space, select an appearance with 1/2 or C,+orbit with Q/E, and capture each view with F12. Changing the appearance keeps the+scene paused at the same release phase. R restores the initial orientation and zoom.++## Isolation and verification++The executable keeps its generated map, preferences, logs, and screenshots beneath+`build-linux/cloud-preview/user`. `--user-dir` selects another preview directory.+The installed archives remain read-only. The normal game shares the volume renderer+and shader, but does not link the preview controller, source choreography, entry point+or color editor, and does not depend on the preview's generated map.++For a bounded rendered comparison check without opening a visible window:++```sh+mkdir -p build-linux/cloud-preview+./build-linux/cloud_preview --scenario comparison --offscreen \+ --frames 4800 --screenshot-frame 4200 \+ --user-dir "$PWD/build-linux/cloud-preview/check" \+ > build-linux/cloud-preview/check.log 2>&1+```++This runs for 4800 engine logic frames; wall time depends on rendering. `--hidden` can be used+instead of `--offscreen` to exercise a hidden window. Captures are `sshotNNN.bmp`+in the chosen preview directory. The renderer remains active in both modes.++The controller reports particle counts, unit health, distance travelled, visits to+both fields, turnarounds, cloud height, and interaction strength every five seconds.+Volumetric density, GPU embers, and source-scene ground footprints are rendered+separately and are not represented by the particle count. The controller checks that+no gameplay hazard exists and health stays at its initial value. A failed+check or failed startup returns a nonzero exit status. In comparison mode, a complete+crossing is eight field visits (two per infantry); after a full lap the turnaround+count is at least four. Select a different `--scenario` to inspect that source's+release and lifecycle.++The flow model also has standalone CPU checks for wake decay, pause, frame-rate+consistency, teleports, invalid inputs, and overlapping infantry. Using the existing+C++ compiler from the repository root:++```sh+mkdir -p build-linux/cloud-preview+g++ -std=c++17 -O2 -Wall -Wextra -Werror -IGeneralsMD/Code/Tools \+ -IGeneralsMD/Code/Libraries/Include \+ GeneralsMD/Code/Tools/cloud_preview/test_flow.cpp \+ GeneralsMD/Code/Tools/CloudPreviewFlow.cpp \+ GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudFlow.cpp \+ -o build-linux/cloud-preview/test-flow+./build-linux/cloud-preview/test-flow+```++In comparison mode, the original appearance uses `PoisonFieldLarge` and+`RadiationFieldLarge` through the production ground-field rendering path. Those+preview instances have a 115-unit emission radius and an extended lifetime so they+stay available for inspection. Each source scene selects its corresponding retail+field template and follows the preview's formation, lingering, and dissipation timing.+Volumetric mode uses its own world-space+ray-march pass rather than smoke billboards. Switching appearances preserves the+source sequence and does not add gameplay hazards or change infantry damage protection.++Source-scene ground descriptors retain the authored puddle size, texture, colour,+scatter, and bubbling while the preview timeline controls their fade. An explicit+W3D ground-cache refresh lets the preview replace these footprints while paused+without resetting release particles. Classic retains the authored ground effects;+the preview additionally refreshes their footprints for paused A/B changes.++For production integration checks, follow the+[hazard runtime guide](../GeneralsMD/Code/Tools/cloud_preview/runtime-check.md).+It prepares private fixtures for the actual game executable and deliberately uses+real damaging hazards. Preview health protection and compressed choreography do+not enter those tests or normal gameplay. The guide covers the four palettes,+owner continuity, overlap, terrain, water, budget fallback, lifecycle, live mode+switching, persistence and save restoration. Review generated logs and captures+for the exact build being proposed; these fixtures do not score visual quality+or establish full-battle performance.diff --git a/docs/linux.md b/docs/linux.mdnew file mode 100644index 000000000..2825fd37c--- /dev/null+++ b/docs/linux.md@@ -0,0 +1,53 @@+# Linux hazard clouds++On Linux, **Options → Graphics → Cloud style** selects **Classic** or **Volumetric**. Volumetric is the default; switching applies+live and persists as `CloudStyle = 0` or `CloudStyle = 1` in Options.ini. The choice+is independent of the existing particle and smoke-shadow settings. Other platforms keep their+existing ground fields and hide this selector.++The game shares its volume renderer with the [isolated preview](cloud-preview.md).+Approved green toxin, blue beta, purple gamma and amber nuclear palettes use+transparency defaults of 67%, 77%, 74% and 0%, respectively. The exact linear RGB,+brightness and transparency values are retained in+[preferred.ini](../GeneralsMD/Code/Tools/cloud_preview/presets/preferred.ini) and the+matching compiled defaults. Preview palette files affect only the preview.+Increasing transparency reduces optical thickness and self-shadowing; 100% hides+smoke while nuclear heat and embers remain visible.++Supported effects read their actual emission radius and hazard lifetime. Toxin+billows form outward; nuclear haze fades into its full footprint. Formation is+capped to one quarter of short hazard lifetimes. Visible infantry stir the smoke;+hidden, stealthed or shrouded infantry contribute no new wakes. These effects do+not change damage, weapons, movement, gameplay RNG or simulation state.++The client admits at most eight visible cloud layers within a 192 MiB atlas-cache+budget. Over-budget fields, unknown effects and unavailable GPU resources keep+Classic fallback. Rendering runs after opaque geometry and water in the main+scene; reflection and custom passes leave the main-view cloud caches and wakes+alone. Caches and wakes reset on map or device changes.++The support model follows height-map terrain or an elevated plane. Cliffs and+crossing decks have no dedicated production fixture or automatic geometry+fallback; one height per XY sample cannot represent multiple support surfaces+within a field. The overlap fixture separates its owners: position-based emitter+association cannot distinguish exactly coincident owners of the same palette.++From an already configured Linux Release build with existing dependencies:++```sh+cmake --build build-linux --target generals cloud_preview \+ test_hazard_cloud_policy test_gameengine+ctest --test-dir build-linux --output-on-failure \+ -R '^(test_hazard_cloud_policy|test_gameengine)$'+```++`cloud_preview` is excluded from the default build and is available only when+Python 3 was found at configuration. The game does not depend on its scene+controller, palette editor or generated inspection map. See the+[preview guide](cloud-preview.md) for controls and standalone CPU checks, and the+[production runtime guide](../GeneralsMD/Code/Tools/cloud_preview/runtime-check.md)+for preparing a retail file-link root with `replay-check.sh --keep` and running+real hazard fixtures. The runtime harness records executable/input hashes, logs,+CRCs and captures in each new output directory. Inspect the captures and measure+representative scenes separately: a passing harness does not establish image+quality, crowded-battle performance or Windows/macOS runtime compatibility.diff --git a/docs/porting/windows-impact.md b/docs/porting/windows-impact.mdindex 41d429e33..16da4f9e2 100644--- a/docs/porting/windows-impact.md+++ b/docs/porting/windows-impact.md@@ -443,3 +443,19 @@ These do not belong to one change.| **The first Windows build after A1 will fail on `make -k`-shaped grounds, not on flags.** | **Windows, 2026-09-27: it happened and is fixed.** W2: 63 errors, then 19 more once ATL was in (W2). A1's macOS branch is additive, but A1 also proved that `wwdebug`, `wwutil` and `compression` do not compile under clang at all. Nothing about that touches Windows — and it does mean that the next person to diff the two platforms is comparing a working build against a build that stops in its first library. Do not read that as a regression. || **A `Debug` or `_INTERNAL` build of this tree does not compile on x64, and did not before this port started.** | **Windows, 2026-09-29: done for x64 Debug; `_INTERNAL` not built.** The build and what it then found are fixed: a Debug CI run on the Windows CI VM (`windows-ci.ps1 -Config Debug`): the build, ctest 50 of 50 with order_cameos_selfcheck skipped (no numpy there), the GPU tests, and E1 0@1200 playing back to 0xE5C34BF3, Release's pin. Before that, as found on 2026-09-27: `windows-ci.ps1 -Config Debug` on 2026-09-27 stops in `wwdebug` at `Debug.h:244`. A port change spelled `SimpleProfiler`'s four counters `Int64`, which wwdebug's files do not declare; `__int64` was the compiler's own. Only wwdebug compiles `DEBUG_PROFILE`, because only it lacks `RELEASE_DEBUG_LOGGING`. Three Debug-only test links fail too: `GameEngineDebug.lib` (gametext_csf, test_premain_strings, test_premain_unicode), `debugdebug.lib` (test_debug), and `DebugLog` (test_wwdownload). The fix is in this tree now. `GameCommon.h:59` defines `DUMP_PERF_STATS` in every `_DEBUG` or `_INTERNAL` build. `PerfTimer.h` compiled `GetPrecisionTimer` under that define, and its body was an `__asm RDTSC` block — `USE_QPF` was never defined, so the assembly was the live branch, not the dead one. This project is x64 only (`CMakeLists.txt:48-52` refuses anything else) and **MSVC does not accept `__asm` on x64 at all**. `-DPERF_TIMERS=ON` reaches the same code in a Release build. Found by B2, which has replaced the block with the clock shim, so the configurations should build again — but nobody has confirmed either the breakage or the fix on a Windows machine, and the conclusion rests on reading the preprocessor rather than on a compiler's answer. **It also means an early claim that "every remaining `__asm` block is inside `#if 0`" was wrong**; it has been corrected. The only other `__asm` in the tree, `WWMath/vp.cpp`, is expanded solely inside `#if defined(__ICL)` and is genuinely dead. || **`#pragma pack` layout is assumed, not measured, on MSVC.** | **Windows, 2026-09-27: checked.** The B4 and L1 `sizeof`/`offsetof` asserts compile under MSVC (rows 208, 248, 267). B4 adds `sizeof`/`offsetof` asserts. They will be checked by a clang build only. If MSVC disagrees on any packed struct, the asserts fire there and the build fails loudly — which is the good outcome, but it happens on someone else's machine, later. |++## Linux hazard cloud proposal (2026-10-19)++The production volume implementation and preview target compile on Linux. The+new particle recognition, owner/lifetime tracking, terrain caches and infantry+wakes are enabled only on Linux. Other platforms retain their original ground+fields; shared option metadata and no-op resource hooks still compile there.+`SdlRenderMatrix.h` is a small, pure matrix helper. Scene-depth capture and+vertex texture bindings are generic prerequisites; no other rendering feature is included. Windows and+macOS compilation and runtime validation remain open.++The independent review restored non-Linux field-key grouping, owner selection,+emitter grace periods and initial-delay behavior. An `unifdef` MSVC/macOS view+comparison against reference/3.1.0 confirms that the key, owner lookup and fade+function bodies retain their original source after preprocessing. This textual+check does not establish compiler or runtime compatibility.