Skip to content

Zero Hour rebuilt from EA's source: x64, Direct3D 11, VS2022/CMake, ~60 original bugs fixed, an AI that builds a base. Bring your own game.

feat(water): add modern water rendering and preview on linux

Richard Louie Orillad8d1e21b774e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 39304666c..ae74c4750 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,17 @@ found and fixed — EA's own, not port damage.**
---
+## Modern water on Linux
+
+- Water rolls in waves with sunlight following the crests into the shallows.
+ Shores redirect waves along their banks and gather foam; vessels leave wakes.
+- Modern water preserves map-authored depth and opacity, matches material rules
+ to the effective water color and texture, and adds pollution and bubbles only
+ to matching water. Choose Classic to keep the previous surface.
+- A standalone editor uses the game's water renderer and material rules. Invalid
+ saved colors leave the current colors intact; default exports protect the
+ loaded rule file. Explicit export destinations remain available.
+
## A rank ladder for every army
- Three chevrons are now a whole army's ladder. An American unit climbs 28 promotions from E-1 Private to General of the Army, a Chinese one 19 from Private to General, a GLA one 20 from Recruit to Supreme Liberator. Every unit starts unranked with a bare health bar and no bonus; from the first promotion on, each grade wears its own insignia beside the health bar and floats it up over the unit's head the moment it is earned. Hover the portrait for the rank's name and how far the next one is: "Next rank 340/420 XP".
diff --git a/GeneralsMD/Code/BuildFingerprint.manifest b/GeneralsMD/Code/BuildFingerprint.manifest
index 48589592b..619688a9a 100644
--- a/GeneralsMD/Code/BuildFingerprint.manifest
+++ b/GeneralsMD/Code/BuildFingerprint.manifest
@@ -202,6 +202,7 @@ Data/INI/MappedImages/HandCreated/ReforgedRanksChina.ini
Data/INI/MappedImages/HandCreated/ReforgedRanksGLA.ini
Data/INI/MappedImages/HandCreated/ReforgedRanksTurkiye.ini
Data/INI/MappedImages/HandCreated/ReforgedRanksUSA.ini
+Data/INI/ModernWater.ini
Data/INI/ObjectCreationListReforged.ini
Data/INI/ParticleSystemReforged.ini
Data/INI/PlayerTemplateReforged.ini
@@ -1966,6 +1967,8 @@ Libraries/Include/Platform/EngineShaderName.h
Libraries/Include/Platform/IsWindows9x.h
Libraries/Include/Platform/LoadTiming.h
Libraries/Include/Platform/MSVCCompat.h
+Libraries/Include/Platform/ModernWaterConfig.h
+Libraries/Include/Platform/ModernWaterMaterial.h
Libraries/Include/Platform/MsvcFloatCasts.h
Libraries/Include/Platform/PosixD3D9/d3d9.h
Libraries/Include/Platform/PosixD3D9/d3d9caps.h
@@ -1974,6 +1977,48 @@ Libraries/Include/Platform/RenderTypes.h
Libraries/Include/Platform/RendererName.h
Libraries/Include/Platform/SleepMilliseconds.h
Libraries/Include/Platform/StrdupAsWindows.h
+Libraries/Include/Platform/WaterBedMaterial.h
+Libraries/Include/Platform/WaterBowLift.h
+Libraries/Include/Platform/WaterBowRefinement.h
+Libraries/Include/Platform/WaterBowShoulder.h
+Libraries/Include/Platform/WaterCoastalCrest.h
+Libraries/Include/Platform/WaterCoastalDomain.h
+Libraries/Include/Platform/WaterCoastalIncident.h
+Libraries/Include/Platform/WaterCoastalPresentation.h
+Libraries/Include/Platform/WaterCoastalRender.h
+Libraries/Include/Platform/WaterCoastalSurf.h
+Libraries/Include/Platform/WaterCoastalView.h
+Libraries/Include/Platform/WaterFftFiltering.h
+Libraries/Include/Platform/WaterFftGeometry.h
+Libraries/Include/Platform/WaterFftSampling.h
+Libraries/Include/Platform/WaterFftSpectrum.h
+Libraries/Include/Platform/WaterFoamEnvironment.h
+Libraries/Include/Platform/WaterFoamHistory.h
+Libraries/Include/Platform/WaterFoamParticlePolicy.h
+Libraries/Include/Platform/WaterFoamShading.h
+Libraries/Include/Platform/WaterFoamWindow.h
+Libraries/Include/Platform/WaterHullContact.h
+Libraries/Include/Platform/WaterHullContactFoam.h
+Libraries/Include/Platform/WaterHullModel.h
+Libraries/Include/Platform/WaterHullPoseCache.h
+Libraries/Include/Platform/WaterHullVisual.h
+Libraries/Include/Platform/WaterHullVisualLayout.h
+Libraries/Include/Platform/WaterObstacleIndex.h
+Libraries/Include/Platform/WaterOpticalContext.h
+Libraries/Include/Platform/WaterOpticalModel.h
+Libraries/Include/Platform/WaterProjectedMesh.h
+Libraries/Include/Platform/WaterShoreFoam.h
+Libraries/Include/Platform/WaterShoreHistory.h
+Libraries/Include/Platform/WaterShoreOverlay.h
+Libraries/Include/Platform/WaterShoreSource.h
+Libraries/Include/Platform/WaterShoreSupport.h
+Libraries/Include/Platform/WaterSurfaceModel.h
+Libraries/Include/Platform/WaterTerrainCulling.h
+Libraries/Include/Platform/WaterVesselMotion.h
+Libraries/Include/Platform/WaterVesselWaves.h
+Libraries/Include/Platform/WaterWaveCage.h
+Libraries/Include/Platform/WaterWaveCageMesh.h
+Libraries/Include/Platform/WaterWaveCageShader.h
Libraries/Include/rts/debug.h
Libraries/Include/rts/profile.h
Libraries/Lib/.gitignore
@@ -2980,6 +3025,14 @@ Main/resource.h
RTS.dsp
RTS.dsw
Stubs/NullAudioManager.h
+Tests/WaterBowShoulderTest.h
+Tests/WaterCoastalCapacityTest.h
+Tests/WaterCoastalDomainTest.h
+Tests/WaterCoastalFootprintTest.h
+Tests/WaterCoastalViewTest.h
+Tests/WaterHullContactFoamTest.h
+Tests/WaterTerrainCullingTest.h
+Tests/WaterWaveCageTest.h
Tests/arch_diff/arch_probe.cpp
Tests/arch_diff/known_differences.txt
Tests/arch_diff/run_arch_diff.sh
@@ -3079,6 +3132,7 @@ Tests/test_map_ini_rollback.inc
Tests/test_miles_miniaudio.cpp
Tests/test_milesaudiomanager.cpp
Tests/test_minimap_input.inc
+Tests/test_modern_water_config.cpp
Tests/test_msvc_float_casts.cpp
Tests/test_observer_camera.inc
Tests/test_pixelcentre.cpp
@@ -3109,6 +3163,7 @@ Tests/test_user_data_guard.cpp
Tests/test_userfolders.cpp
Tests/test_w3dlayout.cpp
Tests/test_water_grid.cpp
+Tests/test_water_preview_preset.cpp
Tests/test_water_tracks.cpp
Tests/test_widechar_crc_gate.cpp
Tests/test_widechar_file.cpp
@@ -3667,6 +3722,8 @@ Tools/WW3D/pluglib/win.h
Tools/WW3D/pluglib/wwfile.h
Tools/WW3D/pluglib/wwmath.cpp
Tools/WW3D/pluglib/wwmath.h
+Tools/WaterPreviewColorPanel.h
+Tools/WaterPreviewPreset.h
Tools/WorldBuilder/WorldBuilder.dsp
Tools/WorldBuilder/include/AutoEdgeOutTool.h
Tools/WorldBuilder/include/BaseBuildProps.h
@@ -4112,6 +4169,7 @@ Tools/versionUpdate/versionUpdate.cpp
Tools/versionUpdate/versionUpdate.dsp
Tools/vfx_tune.py
Tools/water_grid_oracle_extract.py
+Tools/water_preview.cpp
Tools/widechar_check.py
Tools/widechar_check_allow.txt
Tools/windows_view_diff.py
diff --git a/GeneralsMD/Code/CMakeLists.txt b/GeneralsMD/Code/CMakeLists.txt
index 30f6c550c..32b4d4ad7 100644
--- a/GeneralsMD/Code/CMakeLists.txt
+++ b/GeneralsMD/Code/CMakeLists.txt
@@ -1452,6 +1452,18 @@ if(ZH_PLATFORM_POSIX)
add_test(NAME posix_gpu_draw_selfcheck COMMAND posix_gpu_draw_selfcheck)
set_tests_properties(posix_gpu_draw_selfcheck PROPERTIES SKIP_RETURN_CODE 77)
+ if(ZH_PLATFORM_LINUX)
+ # Dedicated water material editor: the same device, FFT and shader as the game.
+ add_executable(water_preview EXCLUDE_FROM_ALL
+ ${CMAKE_CURRENT_SOURCE_DIR}/Tools/water_preview.cpp)
+ set_target_properties(water_preview PROPERTIES CXX_STANDARD 17)
+ target_include_directories(water_preview PRIVATE
+ ${CMAKE_CURRENT_SOURCE_DIR}/GameEngineDevice/Source/PosixDevice/Render
+ ${WW}/WW3D2 ${ZH_POSIX_D3D9_INCLUDE})
+ target_link_libraries(water_preview PRIVATE posixd3d9 SDL3::SDL3-static)
+ # Preserve the original proposal's build-target name for existing local workflows.
+ endif()
+
# A3b's harness: the device's draws on this machine's GPU against FFReference, scenario by scenario,
# with two armed controls that must fail (77 without a GPU).
add_executable(ffref_gpu_selfcheck ${CMAKE_CURRENT_SOURCE_DIR}/Tests/test_ffref_gpu.cpp)
@@ -1952,6 +1964,10 @@ if(ZH_PLATFORM_POSIX)
DEPENDS ${ZH_OVERLAY_INPUTS} ${CMAKE_CURRENT_SOURCE_DIR}/Tools/stage-overlay.sh
COMMENT "Staging the fork's overlay (P1)" VERBATIM)
add_custom_target(zh_overlay ALL DEPENDS ${CMAKE_BINARY_DIR}/overlay.staged)
+ if(TARGET water_preview)
+ add_dependencies(water_preview zh_overlay)
+ endif()
+
add_custom_command(
OUTPUT ${CMAKE_BINARY_DIR}/overlay-dev.staged
COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/Tools/stage-overlay.sh ${CMAKE_CURRENT_SOURCE_DIR}/Data ""
@@ -2159,6 +2175,15 @@ target_include_directories(test_wwutil PRIVATE ${WW}/Wwutil ${WW}/WWLib ${WW}/WW
# Lib/Clock.h is header-only and links nothing, so this runs on both platforms from day one -
# which matters, because the macOS half of that header is the half nobody has ever executed.
add_lib_test(test_clock)
+if(ZH_PLATFORM_LINUX)
+ add_lib_test(test_water_preview_preset)
+ set_target_properties(test_water_preview_preset PROPERTIES CXX_STANDARD 17)
+ target_include_directories(test_water_preview_preset PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/Tools)
+endif()
+add_lib_test(test_modern_water_config)
+set_target_properties(test_modern_water_config PROPERTIES CXX_STANDARD 17)
+target_compile_definitions(test_modern_water_config PRIVATE
+ MODERN_WATER_INI_PATH="${CMAKE_CURRENT_SOURCE_DIR}/Data/INI/ModernWater.ini")
if(ZH_PLATFORM_WINDOWS)
target_link_libraries(test_clock PRIVATE winmm) # Clock.h's Windows half: timeGetTime, timeBeginPeriod (W2)
endif()
@@ -2560,6 +2585,10 @@ target_link_libraries(fs_oracle PRIVATE wwlib wwdebug)
# SKIPPED for that step and says how many it did not check.
find_program(ZH_SPIRV_VAL spirv-val)
add_lib_test(test_shader_sdl ffvertex engineshader sdl3shadercompile)
+# Reflect the Linux Modern water blocks against their CPU upload structures.
+if(ZH_PLATFORM_LINUX)
+ target_link_libraries(test_shader_sdl PRIVATE spirv-cross-c)
+endif()
if(ZH_SPIRV_VAL)
set_tests_properties(test_shader_sdl PROPERTIES ENVIRONMENT "ZH_SPIRV_VAL=${ZH_SPIRV_VAL}")
endif()
diff --git a/GeneralsMD/Code/Data/INI/ModernWater.ini b/GeneralsMD/Code/Data/INI/ModernWater.ini
new file mode 100644
index 000000000..5b516d5f0
--- /dev/null
+++ b/GeneralsMD/Code/Data/INI/ModernWater.ini
@@ -0,0 +1,24 @@
+; Modern water material rules. Classic water keeps the map's original settings.
+; A rule matches ANY listed color AND ANY listed texture (case-insensitive basename).
+; Add Color and Texture entries to extend the lists. First matching enabled rule wins.
+; Keep separate rules when only specific color/texture pairs should match.
+; ReplacementColor is display RGB, Brightness is 0.1..1, Pollution is 0..1.
+; Optional fields default to Brightness=1, Pollution=0, Bubbles=No, Enabled=Yes.
+; Missing/invalid file uses this built-in default; invalid files log the error line.
+; An empty/comment-only file disables every rule. Enabled=No disables one rule.
+; This file is read only: the game never regenerates or overwrites custom edits.
+
+ModernWaterRule PollutedWater
+ MatchColors
+ Color = R:50 G:75 B:50
+ End
+
+ MatchTextures
+ Texture = TSWater03.tga
+ End
+
+ ReplacementColor = R:45 G:58 B:11
+ Brightness = 0.67
+ Pollution = 0.80
+ Bubbles = Yes
+End
diff --git a/GeneralsMD/Code/Data/Patch.str b/GeneralsMD/Code/Data/Patch.str
index 831c6b77e..029161a0d 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:WaterStyle
+"Water style"
+END
+
+GUI:WaterStyle0
+"Classic"
+END
+
+GUI:WaterStyle1
+"Modern"
+END
+
+TOOLTIP:WaterStyle
+"Classic uses the original water, sparkles, reflections and wakes. Modern adds waves, shoreline detail and hull foam. 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."
END
diff --git a/GeneralsMD/Code/Data/Window/Menus/OptionsMenuClassic.wnd b/GeneralsMD/Code/Data/Window/Menus/OptionsMenuClassic.wnd
index cb3cab3d0..5626fbd86 100644
--- a/GeneralsMD/Code/Data/Window/Menus/OptionsMenuClassic.wnd
+++ b/GeneralsMD/Code/Data/Window/Menus/OptionsMenuClassic.wnd
@@ -5199,6 +5199,294 @@ WINDOW
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:LabelWaterStyle";
+ TOOLTIPTEXT = "TOOLTIP:WaterStyle";
+ 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:WaterStyle";
+ 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:ComboBoxWaterStyle";
+ TOOLTIPTEXT = "TOOLTIP:WaterStyle";
+ 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;
+ END
+ CHILD
WINDOW
WINDOWTYPE = CHECKBOX;
SCREENRECT = UPPERLEFT: 40 350, BOTTOMRIGHT: 264 374, CREATIONRESOLUTION: 800 600;
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h
index 75b72c8b4..b3de03051 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 ground
Bool m_volumetricSmokeShadows; // "VolumetricSmokeShadows": smoke and dust shade the world and themselves through the sun's map (Direct3D 11)
Bool m_smokeFireLighting; // "SmokeFireLighting": smoke takes light from the fire beside it
+ Int m_waterStyle; // "WaterStyle": 0 = Classic, 1 = Modern (SDL); applied between render frames
Bool m_explosionDebrisTrails; // "DebrisTrails": blasts throw smoke-trailing fragments and burning shrapnel
Int 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 startup
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/OptionsCatalog.h b/GeneralsMD/Code/GameEngine/Include/Common/OptionsCatalog.h
index d25720c45..024f13f02 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 surface; Modern is the SDL wave and optical surface.
+enum { WATER_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/Water.h b/GeneralsMD/Code/GameEngine/Include/GameClient/Water.h
index 339a00ae8..0a83579f9 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameClient/Water.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/Water.h
@@ -126,5 +126,9 @@ extern WaterSetting WaterSettings[ TIME_OF_DAY_COUNT ];
extern OVERRIDE<WaterTransparencySetting> TheWaterTransparency;
+// Render-only material rules. The map's legacy settings remain owned by Classic water.
+void loadModernWaterSettings();
+void getModernWaterMaterial(Real color[4], Real parameters[4]);
+
#endif // __WATER_H_
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp
index b20581e92..c0e176da6 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp
@@ -1100,6 +1100,11 @@ void GameEngine::init( int argc, char *argv[] )
// read the water settings from INI (must do prior to initing GameClient, apparently)
ini.load( AsciiString( "Data\\INI\\Default\\Water.ini" ), INI_LOAD_OVERWRITE, &xferCRC );
ini.load( AsciiString( "Data\\INI\\Water.ini" ), INI_LOAD_OVERWRITE, &xferCRC );
+ // Visual material rules have their own parser, shared with the standalone preview.
+ // They do not change gameplay state or the legacy map WaterTransparency values.
+#if defined(__linux__)
+ loadModernWaterSettings();
+#endif
ini.load( AsciiString( "Data\\INI\\Default\\Weather.ini" ), INI_LOAD_OVERWRITE, &xferCRC );
ini.load( AsciiString( "Data\\INI\\Weather.ini" ), INI_LOAD_OVERWRITE, &xferCRC );
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp
index 17de244b2..fcce322a9 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 it
m_volumetricSmokeShadows = TRUE;
m_smokeFireLighting = TRUE;
+ m_waterStyle = 1; // keep modern water for existing Options.ini files
m_explosionDebrisTrails = TRUE;
m_shadowQuality = 1; //medium, the 2048 map the shadows always had
m_classicGraphics = FALSE;
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/OptionsCatalog.cpp b/GeneralsMD/Code/GameEngine/Source/Common/OptionsCatalog.cpp
index ff06cb47e..13b7e8317 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_waterStyle )
OPTION_BOOL_ACCESSORS( m_classicGraphics )
OPTION_INT_ACCESSORS( m_lightingStyle )
OPTION_INT_ACCESSORS( m_healthBarMode )
@@ -413,6 +414,12 @@ const OptionDef TheOptionCatalog[] =
OPTION_BOOL, APPLY_DEVICE_RESET, 0, 1,
get_m_vsync, set_m_vsync },
+ // Water selects a complete surface path, including geometry and reflections. The water
+ // object applies it at the next frame boundary, including while the options menu is paused.
+ { "WaterStyle", OPT_WND( "ComboBoxWaterStyle" ), "GUI:WaterStyle",
+ OPTION_ENUM, APPLY_LIVE, 0, WATER_STYLE_COUNT - 1,
+ get_m_waterStyle, set_m_waterStyle },
+
// 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.ini
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/FileSystem.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/FileSystem.cpp
index 089eb4478..3e7a23d5c 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/System/FileSystem.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/FileSystem.cpp
@@ -551,6 +551,10 @@ Bool FileSystem::isForkOwnedPath(const AsciiString& filename)
return TRUE;
if (starts("data\\ini\\mappedimages\\handcreated\\reforged") && ends(".ini"))
return TRUE;
+#if defined(__linux__)
+ if (p == "data\\ini\\modernwater.ini")
+ return TRUE;
+#endif
return p == "data\\patch.str"
|| starts("data\\turkish\\") || starts("data\\german\\")
|| starts("art\\textures\\reforged")
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp
index a266a705b..b8a4371df 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,15 @@ static void fillCatalogWidgets( void )
if( widget == NULL )
continue;
+#if !defined(__linux__)
+ // Modern water is provided by the Linux renderer.
+ if (strcmp(def.iniKey, "WaterStyle") == 0) {
+ widget->winHide(TRUE);
+ GameWindow *label=TheWindowManager->winGetWindowFromId(NULL,NAMEKEY("OptionsMenu.wnd:LabelWaterStyle"));
+ if (label) label->winHide(TRUE);
+ continue;
+ }
+#endif
const Int value = clampOptionValue( def, def.get() );
switch( def.kind )
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Water.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/Water.cpp
index 4584810f5..73a52877a 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/Water.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/Water.cpp
@@ -32,11 +32,89 @@
#include "GameClient/Water.h"
#include "Common/INI.h"
+#include "Common/FileSystem.h"
+#include "Common/file.h"
+#include "Platform/ModernWaterConfig.h"
+
+#include <cstdio>
// GLOBALS ////////////////////////////////////////////////////////////////////////////////////////
WaterSetting WaterSettings[ TIME_OF_DAY_COUNT ];
OVERRIDE<WaterTransparencySetting> TheWaterTransparency = NULL;
+namespace {
+struct ModernWaterSettings {
+ ModernWaterConfig::Rules rules = ModernWaterConfig::Defaults();
+ ModernWaterConfig::Material material;
+ ModernWaterConfig::Color mapColor;
+ std::string mapTexture;
+ bool resolved = false;
+};
+
+ModernWaterSettings &modernWaterSettings()
+{
+ static ModernWaterSettings settings;
+ return settings;
+}
+}
+
+void loadModernWaterSettings()
+{
+ ModernWaterSettings &settings = modernWaterSettings();
+ settings.rules = ModernWaterConfig::Defaults();
+ settings.resolved = false;
+ const char *path = "Data\\INI\\ModernWater.ini";
+ File *file = TheFileSystem->openFile(path, File::READ | File::BINARY);
+ if (!file) {
+ fprintf(stderr, "ModernWater: %s is absent; using built-in material rules\n", path);
+ return;
+ }
+ const Int size = file->size();
+ if (size < 0 || size > 1024 * 1024) {
+ file->close();
+ fprintf(stderr, "ModernWater: invalid configuration size; using built-in material rules\n");
+ return;
+ }
+ std::string contents(size, '\0');
+ const bool complete = size == 0 || file->read(&contents[0], size) == size;
+ file->close();
+ std::string error;
+ if (!complete || !ModernWaterConfig::Parse(contents, settings.rules, error)) {
+ fprintf(stderr, "ModernWater: %s: %s; using built-in material rules\n", path,
+ complete ? error.c_str() : "incomplete read");
+ return;
+ }
+ fprintf(stderr, "ModernWater: loaded %u material rules from %s\n", unsigned(settings.rules.size()), path);
+}
+
+void getModernWaterMaterial(Real color[4], Real parameters[4])
+{
+ ModernWaterSettings &settings = modernWaterSettings();
+ const RGBColor &authored = TheWaterTransparency->m_standingWaterColor;
+ const ModernWaterConfig::Color mapColor = ModernWaterConfig::ByteColor(authored.red, authored.green, authored.blue);
+ const std::string mapTexture = TheWaterTransparency->m_standingWaterTexture.str();
+ // Compare the effective values, not the override object's address: save restoration and
+ // match reset can reuse an allocation. A new map must never inherit a prior material.
+ if (!settings.resolved || settings.mapColor.r != mapColor.r || settings.mapColor.g != mapColor.g ||
+ settings.mapColor.b != mapColor.b || settings.mapTexture != mapTexture) {
+ settings.mapColor = mapColor;
+ settings.mapTexture = mapTexture;
+ settings.material = ModernWaterConfig::Resolve(settings.rules, mapColor, mapTexture);
+ settings.resolved = true;
+ DEBUG_LOG(("ModernWater: map color %d,%d,%d texture %s -> %s\n", mapColor.r, mapColor.g,
+ mapColor.b, mapTexture.c_str(), settings.material.ruleName.empty() ? "authored tint" : settings.material.ruleName.c_str()));
+ }
+ const ModernWaterConfig::Material &material = settings.material;
+ color[0] = material.color.r / 255.0f;
+ color[1] = material.color.g / 255.0f;
+ color[2] = material.color.b / 255.0f;
+ color[3] = material.brightness;
+ parameters[0] = material.tintAmount;
+ parameters[1] = material.pollution;
+ parameters[2] = material.bubbles ? 1.0f : 0.0f;
+ parameters[3] = 0.0f;
+}
+
// PRIVATE DATA ///////////////////////////////////////////////////////////////////////////////////
const FieldParse WaterSetting::m_waterSettingFieldParseTable[] =
{
diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DModelDraw.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DModelDraw.h
index 6ace497c5..b404ca778 100644
--- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DModelDraw.h
+++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DModelDraw.h
@@ -393,6 +393,10 @@ public:
virtual void smoothMotionCapture(UnsignedInt clientFrame, Bool marked);
virtual void smoothMotionApply(Real alpha);
virtual void smoothMotionRestore();
+ // Read-only time of the displayed transform, for client effects that estimate motion.
+ Real clientOnly_getRenderMotionSamplePhase() const {
+ return m_smoothMotion.Applied && m_smoothMotion.Model == m_renderObject ? TheSmoothMotionAlpha : 1.0f;
+ }
// this method must ONLY be called from the client, NEVER From the logic, not even indirectly.
virtual Bool clientOnly_getRenderObjInfo(Coord3D* pos, Real* boundingSphereRadius, Matrix3D* transform) const;
diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DParticleSys.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DParticleSys.h
index 59c4498ab..11365e131 100644
--- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DParticleSys.h
+++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DParticleSys.h
@@ -107,6 +107,9 @@ private:
{
ParticleSystem * system;
Real fade; ///< ParticleSystem::getStealthFade, above zero
+#if defined(__linux__)
+ ObjectID owner; ///< vessel foam's attached object at the sync point
+#endif
};
void refreshFrameView( void );
diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DWater.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DWater.h
index 9778db941..d61bfebb4 100644
--- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DWater.h
+++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DWater.h
@@ -31,6 +31,8 @@
#ifndef __W3DWater_H_
#define __W3DWater_H_
+#include <vector>
+
#include "always.h"
#include "rendobj.h"
#include "w3d_file.h"
@@ -44,6 +46,20 @@
#include "Common/Snapshot.h"
#include "GameLogic/WaterGridMotion.h"
#include "Platform/RenderTypes.h"
+#include "Platform/WaterOpticalContext.h"
+#include "Platform/WaterProjectedMesh.h"
+#include "Platform/WaterHullVisual.h"
+#include "Platform/WaterHullVisualLayout.h"
+#include "Platform/WaterBowRefinement.h"
+#include "Platform/WaterObstacleIndex.h"
+#include "Platform/WaterHullModel.h"
+#include "Platform/WaterHullPoseCache.h"
+#include "Platform/WaterVesselMotion.h"
+#include "Platform/WaterFoamHistory.h"
+#include "Platform/WaterShoreSource.h"
+#include "Platform/WaterCoastalRender.h"
+
+class MeshModelClass;
#include <vector>
@@ -119,6 +135,8 @@ public:
Real getWaterHeight(Real x, Real y); ///<return water height at given point - for use by WB.
void replaceSkyboxTexture(const AsciiString& oldTexName, const AsciiString& newTextName);
+ Bool hasModernVesselFoam(UnsignedInt objectID) const; ///< replacement was submitted for this hull in the current render frame
+ Bool isModernWaterMirrorForOwner(UnsignedInt objectID) const; ///< owner's surface foam must not reflect back into the same water plane
protected:
DX8IndexBufferClass *m_indexBuffer; ///<indices defining quad
@@ -194,6 +212,98 @@ protected:
TextureClass *m_riverTexture;
TextureClass *m_whiteTexture; ///< a texture containing only white used for NULL pixel shader stages.
TextureClass *m_waterNoiseTexture;
+ Bool m_useModernWater = FALSE; // active render style; synchronized before mirror/surface draws
+ TextureClass *m_modernHeightTexture = NULL;
+ TextureClass *m_modernBedTexture = NULL;
+ Real m_modernWaveTime = 0.0f;
+ Int m_modernMeshCells = 32;
+ Real m_modernMeshMorph = 0.0f;
+ Int m_modernProjectedColumns=160,m_modernProjectedRows=90;
+ Int m_modernProjectedWidth=1280,m_modernProjectedHeight=720;
+ WaterBowRefinement::Admissions m_modernBowAdmissions;
+ uintptr_t m_modernBowPatchOwner=0;
+ unsigned m_modernBowPatchPart=0;
+ size_t m_modernBowVertices=0,m_modernBowTriangles=0,m_modernBowRegions=0,m_modernBowDenied=0,m_modernBowRejected=0;
+ size_t m_modernProjectedVertices=0,m_modernProjectedTriangles=0,m_modernProjectedFallbacks=0,m_modernRetainedVertices=0;
+ size_t m_modernProjectedBudget=60000,m_modernProjectedEvaluations=0;
+ Bool m_modernProjectedCacheEnabled=TRUE;
+ Bool m_modernProfileEnabled=FALSE;
+ struct ModernWaterProfile {
+ double render=0,setup=0,hulls=0,obstacles=0,mesh=0,fill=0,submit=0;
+ double fieldSample=0,dampingSample=0,waveSample=0,cacheSample=0;
+ size_t frames=0,vertices=0,triangles=0,patches=0,patchObstacles=0;
+ size_t attempts=0,hits=0,misses=0,samples=0,wavePoints=0;
+ } m_modernProfile;
+ struct ModernProjectedSample { Real height,damping,obstacle,hullFreeObstacle,offshore,fftDamping,exposure; };
+ std::unordered_map<WaterProjectedMesh::WorldKey,ModernProjectedSample,WaterProjectedMesh::WorldHash> m_modernProjectedSamples;
+ Vector3 m_modernCamera;
+ CameraClass *m_modernRenderCamera = NULL;
+ struct ModernWaterObstacle {
+ Vector3 position; Real radius,height,major,minor,cosine,sine; Bool box,hasHull=FALSE;
+ };
+ std::vector<ModernWaterObstacle> m_modernObstacles, m_modernPatchObstacles;
+ WaterObstacleIndex::Grid m_modernObstacleIndex;
+ std::vector<WaterObstacleIndex::Influence> m_modernObstacleInfluences;
+ struct ModernHullCache {
+ RenderObjClass *model=NULL; // retained until eviction/reset; pointer identity cannot be reused
+ UnsignedInt objectID=0, lastUse=0;
+ WaterHullPoseCache::Cache poses;
+ std::vector<MeshModelClass*> slicedModels; // retained even if an HLOD replaces a child
+ WaterHullPoseCache::Cache visualPoses;
+ std::vector<MeshModelClass*> visualModels;
+ WaterHullVisual::Packet visual={};
+ UnsignedInt visualTraceFrame=~0u;
+ WaterHullModel::Polygon polygon,contact;
+ Real forwardSign=1.0f;
+ WaterVesselMotion::State motion;
+ };
+ std::vector<ModernHullCache> m_modernHullCache;
+ std::vector<WaterHullModel::Hull> m_modernHulls,m_modernContactHulls;
+ std::vector<WaterHullVisual::Packet> m_modernVisualHulls;
+ std::vector<UnsignedInt> m_modernHullObjectIDs;
+ UnsignedInt m_modernHullSerial=0;
+ UnsignedInt m_modernHullTraceLines=0;
+ UnsignedInt m_modernVisualHullTraceLines=0;
+ UnsignedInt m_modernVesselStateTraceFrame=~0u, m_modernVesselStateTraceLines=0;
+ WaterFoamHistory::History m_modernFoamHistory;
+ WaterShoreHistory::History m_modernShoreHistory;
+ WaterShoreSource::Batch m_modernShoreSource;
+ uint64_t m_modernShoreRevision=1, m_modernShoreAttempted=0;
+ Bool m_modernShoreReady=FALSE;
+ WaterCoastalDomain::Domain m_modernCoastalDomain;
+ uint64_t m_modernCoastalRevision=0;
+ Bool m_modernCoastalReady=FALSE,m_modernCoastalViewReady=FALSE;
+ WaterShoreHistory::Mapping m_modernCoastalMapping={};
+ Real m_modernCoastalViewLevel=0;
+ std::vector<WaterCoastalSurf::Lookup> m_modernCoastalLookup;
+ unsigned m_modernFoamDrawFrame=~0u;
+ std::vector<UnsignedInt> m_modernFoamDrawObjectIDs;
+ struct ModernFoamTexture {
+ Real level=0,timestamp=-1;
+ TextureClass *texture=NULL;
+ WaterFoamHistory::Mapping mapping;
+ unsigned channels=0; // bit0 vessel RGB, bit1 coast A, bit2 second direction tile
+ unsigned textureWidth=0,textureHeight=0;
+ Bool valid=FALSE;
+ };
+ std::vector<ModernFoamTexture> m_modernFoamTextures;
+
+ std::vector<UnsignedByte> m_modernHeights;
+ Int m_modernHeightWidth = 0, m_modernHeightHeight = 0, m_modernHeightSide = 0;
+ Int m_modernHeightBorder = -1;
+ const void *m_modernHeightMap = NULL, *m_modernHeightData = NULL;
+ Real m_modernOpticalLevel = 0.0f;
+ struct ModernOpticalTexture {
+ Real level; TextureClass *texture;
+ TextureClass *waveCage=NULL;
+ std::vector<UnsignedByte> waveCageSupport; // same quantized alpha sampled by the shader
+ std::vector<UnsignedByte> ocean;
+ WaterOpticalContext::Field shoreContext; // retained CPU source data, independent of texture upload success
+ Real oceanExtent=0.0f;
+ };
+ std::vector<ModernOpticalTexture> m_modernOpticalTextures;
+ std::vector<WaterOpticalContext::Polygon> m_modernOpticalPolygons;
+ Bool m_modernOpticalPolygonsValid = FALSE;
IDirect3DPixelShader9 * m_waterPixelShader; ///<D3D pixel shader.
IDirect3DPixelShader9 * m_riverWaterPixelShader; ///<D3D pixel shader.
IDirect3DPixelShader9 * m_trapezoidWaterPixelShader; ///<D3D pixel shader
@@ -237,8 +347,27 @@ protected:
///bounding box of frustum clipped polygon plane
Bool getClippedWaterPlane(CameraClass *cam, AABoxClass *box);
- void setupFlatWaterShader(void);
+ void setupFlatWaterShader(Bool heightCorrection=FALSE,Bool waveCage=FALSE);
void setupJbaWaterShader(void);
+ void synchronizeWaterStyle(void);
+ void registerWaterStyleShaders(void);
+ void setupModernWaterShader(Bool river,Bool heightCorrection=FALSE,Bool waveCage=FALSE);
+ void updateModernWaterTextures(void);
+ void updateModernWaterHulls(void);
+ void clearModernWaterHulls(Bool admissions=TRUE);
+ void clearModernWaterFoam(Bool history=TRUE);
+ void bindModernWaterFoam(Real level,Bool river);
+ void bindModernWaterCoastal(Real level,Bool river);
+ void invalidateModernWaterShore(void);
+ void updateModernWaterShore(void);
+ Real modernHullDamping(Real x,Real y,Real level) const;
+ Bool modernHasHull(UnsignedInt objectID) const;
+ void clearModernWaterOpticalTextures(void);
+ void refreshModernWaterOpticalPolygons(void);
+ TextureClass *modernWaterOpticalTexture(Real level);
+ void drawModernWaterPatch(const Vector3 points[4], Bool river, Real riverStart = 0, Real riverEnd = 1);
+ Real modernWaterDamping(Real x, Real y, Real z, Real offshore=0.0f, Real *obstacleAttenuation=NULL, Real *terrainDepth=NULL, Real *hullFreeDamping=NULL, Real *hullFreeObstacle=NULL) const;
+ Bool m_renderingMirror = FALSE; ///< prevents a water draw sampling the mirror being written
void cleanupJbaWaterShader(void);
//Methods used for GeForce3 specific water
diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DWaterTracks.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DWaterTracks.h
index 26f5cd69a..201fb2d5c 100644
--- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DWaterTracks.h
+++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DWaterTracks.h
@@ -69,6 +69,7 @@ protected:
waveType m_type; ///<used for render state sorting (set this to texture pointer for now).
Int m_x; ///<vertex count
Int m_y; ///<vertex count
+ Bool m_authoredSource; ///< loaded from .wak; explicit optional surf-replacement tag
Bool m_bound; ///<object is bound to owner and accepts new edges
Vector2 m_startPos; ///<starting position of wave
// Vector2 m_endPos; ///<ending position of wave
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/PosixDevice9.cpp b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/PosixDevice9.cpp
index 8ce8811c1..ebc955756 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/PosixDevice9.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/PosixDevice9.cpp
@@ -167,6 +167,7 @@ PosixDevice9::PosixDevice9(PosixDirect3D9 *adapter, RenderWindow window, const D
PosixDevice9::~PosixDevice9()
{
+ Shore_End();
Release_Surfaces();
for (int index = 0; index < SAMPLER_COUNT; ++index) {
Posix_Bind(Textures[index], (IDirect3DBaseTexture9 *)NULL);
@@ -504,6 +505,7 @@ RenderResult PosixDevice9::CreateAdditionalSwapChain(D3DPRESENT_PARAMETERS *, ID
RenderResult PosixDevice9::Reset(D3DPRESENT_PARAMETERS *parameters)
{
+ Shore_End();
if (parameters == NULL || parameters->BackBufferWidth == 0 || parameters->BackBufferHeight == 0) {
return D3DERR_INVALIDCALL;
}
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/PosixDevice9.h b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/PosixDevice9.h
index fc94a89a0..9d9f4584b 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/PosixDevice9.h
+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/PosixDevice9.h
@@ -46,6 +46,10 @@
#include "Platform/RenderTypes.h"
#include "Platform/D3D9Posix.h"
+#include "Platform/WaterShoreOverlay.h"
+#include "Platform/WaterCoastalRender.h"
+#include "Platform/WaterHullVisualLayout.h"
+#include <memory>
#include <atomic>
#include <map>
@@ -61,6 +65,8 @@ struct CombinerDescription;
struct VertexPipelineDescription;
struct SdlVertexConstants;
struct SdlPixelConstants;
+struct SdlWaterPixelConstants;
+struct SdlWaterVisualPixelConstants;
/// AddRef and Release for one of the interfaces, counted as COM counts.
template <class Interface>
@@ -159,11 +165,22 @@ public:
STREAM_COUNT = 16,
RENDER_TARGET_COUNT = 4,
VERTEX_SHADER_CONSTANT_COUNT = 256,
- PIXEL_SHADER_CONSTANT_COUNT = 32
+ // Existing water uses c0-c175; exact mesh metadata is c176-c183, c184-c191
+ // remains spare, and c192-c895 supplies the three bounded fragment packet blocks.
+ PIXEL_SHADER_CONSTANT_COUNT = WaterHullVisualLayout::PixelRegisterCount
};
PosixDevice9(PosixDirect3D9 *adapter, RenderWindow window, const D3DPRESENT_PARAMETERS &parameters);
+ // Render-only explicit metadata: never infers .wak ownership from texture names.
+ bool Coastal_Bind(uint64_t revision,const WaterCoastalDomain::Domain &domain,
+ const WaterShoreHistory::Mapping &mapping,double level,const std::vector<WaterCoastalSurf::Lookup> &lookup);
+ void Coastal_End() { CoastalActive=false; }
+ void Shore_Begin(bool enabled);
+ void Shore_End();
+ void Shore_Patch(const WaterShoreOverlay::Quad *patch);
+ void Shore_Track(const WaterShoreOverlay::Quad *track);
+
// What the resource code (PosixDevice9Resources.cpp) reads.
const D3DPRESENT_PARAMETERS & Get_Present_Parameters() const { return Parameters; }
RenderWindow Get_Window() const { return Window; }
@@ -230,6 +247,9 @@ public:
bool Build_Vertex_Description(VertexPipelineDescription &description, std::string *refusal = NULL) const;
/// The two constant blocks, packed to match the descriptions above.
void Build_Constants(SdlVertexConstants &vertex, SdlPixelConstants &pixel) const;
+ void Build_Water_Constants(const SdlPixelConstants &pixel, SdlWaterPixelConstants &water) const;
+ void Build_Water_Visual_Constants(const SdlWaterPixelConstants &water, SdlWaterVisualPixelConstants &visual) const;
+ bool Water_Foam_History_Available() const;
/// Makes the implicit back buffer (and depth surface, when the present parameters ask for one) from
/// the present parameters, and binds them as render target 0 and the depth surface. CreateDevice and
@@ -326,6 +346,20 @@ public:
RenderResult SetPixelShaderConstantF(unsigned int start, const float *data, unsigned int count) override;
protected:
+ bool CoastalActive=false;
+ uint64_t CoastalRevision=0,CoastalViewRevision=0;
+ WaterShoreHistory::Mapping CoastalMapping={};
+ double CoastalLevel=0;
+ struct ShoreRegion {
+ WaterShoreOverlay::Quad patch;
+ WaterShoreOverlay::View view;
+ float terrain[4];
+ std::shared_ptr<IDirect3DBaseTexture9> height, optical;
+ };
+ bool ShoreActive=false, ShoreHasPatch=false, ShoreHasTrack=false;
+ WaterShoreOverlay::Quad ShorePatch, ShoreTrack;
+ std::vector<ShoreRegion> ShoreRegions; // <=128; COM refs released at scope end/reset/destruction
+
~PosixDevice9() override;
/// Drops every implicit surface and every render target and depth binding. Reset and the destructor.
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/PosixDevice9Draw.cpp b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/PosixDevice9Draw.cpp
index 05412095d..0c2be34b3 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/PosixDevice9Draw.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/PosixDevice9Draw.cpp
@@ -35,14 +35,67 @@
#include "engineshader.h"
#include "ffshader.h"
#include "ffvertex.h"
+#include "Platform/WaterFftSampling.h"
+#include "Platform/WaterFoamHistory.h"
#include <SDL3/SDL.h>
#include <math.h>
+#include <cmath>
#include <set>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
+#if defined(__linux__)
+#include <execinfo.h> // bounded opt-in CPU attribution; no GPU queries/readbacks
+#endif
+
+bool PosixDevice9::Coastal_Bind(uint64_t revision,const WaterCoastalDomain::Domain &domain,
+ const WaterShoreHistory::Mapping &mapping,double level,const std::vector<WaterCoastalSurf::Lookup> &lookup)
+{
+ Coastal_End();
+ const char *option=getenv("ZH_WATER_SURF_GPU");
+ if(!Gpu || !option || strcmp(option,"1")!=0 || !revision || domain.Nodes().empty())return false;
+ if(CoastalRevision!=revision || !Gpu->Coastal_Surf_Domain(0,revision)) {
+ if(!Gpu->Install_Coastal_Surf(revision,domain.Nodes(),domain.Grid().spacing))return false;
+ CoastalRevision=revision;CoastalViewRevision=0;
+ }
+ if(CoastalViewRevision!=revision || CoastalLevel!=level || !WaterCoastalView::SameMapping(mapping,CoastalMapping)) {
+ if(!Gpu->Set_Coastal_Surf_View(revision,mapping,level,lookup))return false;
+ CoastalViewRevision=revision;CoastalMapping=mapping;CoastalLevel=level;
+ }
+ CoastalActive=true;return true;
+}
+bool PosixWaterCoastalBind(IDirect3DDevice9 *d,uint64_t r,const WaterCoastalDomain::Domain &domain,
+ const WaterShoreHistory::Mapping &mapping,double level,const std::vector<WaterCoastalSurf::Lookup> &lookup)
+{return d && static_cast<PosixDevice9*>(d)->Coastal_Bind(r,domain,mapping,level,lookup);}
+void PosixWaterCoastalEnd(IDirect3DDevice9 *d){if(d)static_cast<PosixDevice9*>(d)->Coastal_End();}
+
+void PosixDevice9::Shore_Begin(bool enabled)
+{
+ Shore_End();
+ const char *option=getenv("ZH_WATER_SHORE_FOAM");
+ ShoreActive=enabled && (!option || strcmp(option,"0")!=0);
+}
+void PosixDevice9::Shore_End()
+{
+ Coastal_End();
+ ShoreActive=ShoreHasPatch=ShoreHasTrack=false;ShoreRegions.clear();
+}
+void PosixDevice9::Shore_Patch(const WaterShoreOverlay::Quad *patch)
+{
+ ShoreHasPatch=ShoreActive && patch && WaterShoreOverlay::Convex(*patch);
+ if(ShoreHasPatch) ShorePatch=*patch;
+}
+void PosixDevice9::Shore_Track(const WaterShoreOverlay::Quad *track)
+{
+ ShoreHasTrack=ShoreActive && track && WaterShoreOverlay::Convex(*track);
+ if(ShoreHasTrack) ShoreTrack=*track;
+}
+void PosixWaterShoreBegin(IDirect3DDevice9 *d,bool e) {if(d) static_cast<PosixDevice9*>(d)->Shore_Begin(e);}
+void PosixWaterShoreEnd(IDirect3DDevice9 *d) {if(d) static_cast<PosixDevice9*>(d)->Shore_End();}
+void PosixWaterShorePatch(IDirect3DDevice9 *d,const WaterShoreOverlay::Quad *q) {if(d) static_cast<PosixDevice9*>(d)->Shore_Patch(q);}
+void PosixWaterShoreTrack(IDirect3DDevice9 *d,const WaterShoreOverlay::Quad *q) {if(d) static_cast<PosixDevice9*>(d)->Shore_Track(q);}
//-------------------------------------------------------------------------------------------------
// D3D9's initial state, from its documentation of each state. A float state holds its float's bits.
@@ -328,6 +381,35 @@ static void transform_point(const float source[3], const float matrix[16], float
}
}
+// Visual-only inverse for reconstructing the water surface from depth. Double intermediates keep
+// distant camera translations stable; this does not reach simulation or replay arithmetic.
+static bool water_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;
+}
+
static void transform_direction(const float source[3], const float matrix[16], float result[4])
{
for (unsigned column = 0; column < 4; ++column) {
@@ -441,6 +523,83 @@ void PosixDevice9::Build_Constants(SdlVertexConstants &vertex, SdlPixelConstants
pixel.AlphaReference[0] = (float)(RenderStates[D3DRS_ALPHAREF] & 0xFF);
}
+bool PosixDevice9::Water_Foam_History_Available() const
+{
+ // History is an optional CPU-authored image. Never turn a stale stage binding, attachment,
+ // invalid mapping or preceding ocean's atlas into a required input of another water draw.
+ if (PixelShaderConstants[1][1] > 0.5f || PixelShaderConstants[89][0] <= 0.5f
+ || Textures[14] == NULL || Textures[14]->GetType() != D3DRTYPE_TEXTURE) return false;
+ for (unsigned int c = 0; c < 4; ++c)
+ if (!std::isfinite(PixelShaderConstants[88][c]) || !std::isfinite(PixelShaderConstants[89][c])) return false;
+ if (PixelShaderConstants[88][2] <= 0 || PixelShaderConstants[88][3] <= 0 || PixelShaderConstants[89][2] <= 0) return false;
+ const float flags=PixelShaderConstants[89][0];
+ if(flags>7 || std::floor(flags)!=flags || (static_cast<unsigned>(flags)&3u)==0u) return false;
+ D3DSURFACE_DESC desc;
+ if(static_cast<IDirect3DTexture9 *>(Textures[14])->GetLevelDesc(0,&desc)!=D3D_OK
+ || desc.Width==0 || desc.Height==0 || (desc.Usage&D3DUSAGE_RENDERTARGET)!=0) return false;
+ // The packed format has two equal logical tiles; malformed/stale bindings must not
+ // reinterpret a middle row as a history/direction boundary. Legacy atlases remain valid.
+ return (static_cast<unsigned>(flags)&4u)==0u || (desc.Height%2==0
+ && desc.Width<=WaterFoamHistory::MaxAtlasSide && desc.Height<=2*WaterFoamHistory::MaxAtlasSide);
+}
+
+void PosixDevice9::Build_Water_Constants(const SdlPixelConstants &pixel_constants, SdlWaterPixelConstants &water) const
+{
+ memset(&water, 0, sizeof(water));
+ water.Combiner = pixel_constants;
+ float view_projection[16], inverse_view[16];
+ multiply(&Transforms[D3DTS_VIEW]._11, &Transforms[D3DTS_PROJECTION]._11, view_projection);
+ if (!water_inverse(view_projection, water.WorldFromClip)
+ || !water_inverse(&Transforms[D3DTS_VIEW]._11, inverse_view)) {
+ memset(water.WorldFromClip, 0, sizeof(water.WorldFromClip));
+ memset(inverse_view, 0, sizeof(inverse_view));
+ for (unsigned i = 0; i < 4; ++i) water.WorldFromClip[i * 5] = inverse_view[i * 5] = 1.0f;
+ }
+ water.CameraPosition[0] = inverse_view[12];
+ water.CameraPosition[1] = inverse_view[13];
+ water.CameraPosition[2] = inverse_view[14];
+ // Both SV_Position.z and sampled scene depth include the viewport's depth range. Compose its
+ // inverse into the unprojection so custom MinZ/MaxZ use the same shader path as the normal range.
+ const float depth_range = Viewport.MaxZ - Viewport.MinZ;
+ if (depth_range > 1.0e-8f) {
+ for (unsigned int column = 0; column < 4; ++column) {
+ const float z_row = water.WorldFromClip[8 + column] / depth_range;
+ water.WorldFromClip[12 + column] -= Viewport.MinZ * z_row;
+ water.WorldFromClip[8 + column] = z_row;
+ }
+ }
+ water.Viewport[0] = (float)Viewport.X + 0.5f;
+ water.Viewport[1] = (float)Viewport.Y + 0.5f;
+ water.Viewport[2] = (float)Viewport.Width;
+ water.Viewport[3] = (float)Viewport.Height;
+ memcpy(water.WaterParameters, PixelShaderConstants[1], sizeof(water.WaterParameters));
+ memcpy(water.ReflectionArea, PixelShaderConstants[2], sizeof(water.ReflectionArea));
+ memcpy(water.SunDirection, PixelShaderConstants[3], sizeof(water.SunDirection));
+ memcpy(water.SunColour, PixelShaderConstants[4], sizeof(water.SunColour));
+ memcpy(water.TerrainParameters, PixelShaderConstants[5], sizeof(water.TerrainParameters));
+ memcpy(water.OpticalParameters, PixelShaderConstants[6], sizeof(water.OpticalParameters));
+ memcpy(water.HullParameters, PixelShaderConstants[7], sizeof(water.HullParameters));
+ memcpy(water.HullData, PixelShaderConstants[8], sizeof(water.HullData));
+ memcpy(water.ContactHullData, PixelShaderConstants[96], sizeof(water.ContactHullData));
+ memcpy(water.FoamFillLights, PixelShaderConstants[90], sizeof(water.FoamFillLights));
+ memcpy(water.MaterialColor, PixelShaderConstants[ModernWaterMaterial::RegisterColor], sizeof(water.MaterialColor));
+ memcpy(water.MaterialParameters, PixelShaderConstants[ModernWaterMaterial::RegisterParameters], sizeof(water.MaterialParameters));
+ if (Water_Foam_History_Available()) {
+ memcpy(water.FoamHistoryArea, PixelShaderConstants[88], sizeof(water.FoamHistoryArea));
+ memcpy(water.FoamHistoryParameters, PixelShaderConstants[89], sizeof(water.FoamHistoryParameters));
+ }
+ // River draws must never inherit a preceding ocean draw's hull field.
+ if (water.WaterParameters[1] > 0.5f) water.HullParameters[0] = 0;
+}
+
+void PosixDevice9::Build_Water_Visual_Constants(const SdlWaterPixelConstants &water, SdlWaterVisualPixelConstants &visual) const
+{
+ visual.Water=water;
+ memcpy(visual.VisualHullMeta,PixelShaderConstants[WaterHullVisualLayout::MetadataRegister],sizeof(visual.VisualHullMeta));
+ // River and empty hull draws must not activate a preceding ocean's packet metadata.
+ if(water.HullParameters[0]<=0) memset(visual.VisualHullMeta,0,sizeof(visual.VisualHullMeta));
+}
+
//-------------------------------------------------------------------------------------------------
// The draws (A3c): recorded on the GPU with a window, nothing without one.
//-------------------------------------------------------------------------------------------------
@@ -818,18 +977,64 @@ RenderResult PosixDevice9::Gpu_Draw(const DrawCall &call)
Refuse_Draw(refusal);
return D3D_OK;
}
+ // The dedicated generated water vertex path deliberately avoids arbitrary engine-program
+ // pairing. Only this path may bind native FFT textures to the vertex stage.
+ const bool fft_requested = pixel_engine == ENGINE_SHADER_WATER_TRAPEZOID
+ && vertex_engine == ENGINE_SHADER_NONE && !vertex.LightingEnabled
+ && PixelShaderConstants[6][2] > 0.5f && PixelShaderConstants[6][3] > 0.5f
+ && WaterFftSampling::Enabled();
+ bool fft_water = fft_requested && Gpu->Prepare_Ocean(PixelShaderConstants[1][0]*WaterFftSampling::TimeScale);
+ const SdlProgram *fft_vertex = fft_water ? &Programs->Water_Vertex_Program(vertex) : NULL;
+ if (fft_vertex && fft_vertex->Shader == NULL) fft_water = false;
const SdlProgram &vertex_program = vertex_engine != ENGINE_SHADER_NONE
- ? Programs->Engine_Vertex_Program(vertex_engine) : Programs->Vertex_Program(vertex);
- const SdlProgram &pixel_program = pixel_engine != ENGINE_SHADER_NONE
- ? Programs->Engine_Pixel_Program(pixel_engine, combiner.PixelPipeline) : Programs->Pixel_Program(combiner);
- if (vertex_program.Shader == NULL || pixel_program.Shader == NULL) {
+ ? Programs->Engine_Vertex_Program(vertex_engine)
+ : fft_water ? *fft_vertex : Programs->Vertex_Program(vertex);
+ const SdlProgram *pixel_program = pixel_engine != ENGINE_SHADER_NONE
+ ? &Programs->Engine_Pixel_Program(pixel_engine, combiner.PixelPipeline) : &Programs->Pixel_Program(combiner);
+ const SdlProgram *legacy_pixel_program=pixel_program;
+ const ShoreRegion *shore_region=NULL;
+ SDL_GPUTexture *shore_depth=NULL;
+ bool shore_overlay=false;
+ if(ShoreActive && ShoreHasTrack && pixel_engine==ENGINE_SHADER_NONE && vertex_engine==ENGINE_SHADER_NONE
+ && RenderStates[D3DRS_FILLMODE]==D3DFILL_SOLID && !RenderStates[D3DRS_ZWRITEENABLE] && RenderStates[D3DRS_ALPHABLENDENABLE]
+ && RenderStates[D3DRS_SRCBLEND]==D3DBLEND_SRCALPHA && RenderStates[D3DRS_DESTBLEND]==D3DBLEND_INVSRCALPHA
+ && !combiner.ShadowReceiving && !combiner.SoftParticle && !combiner.DrawEffect && !combiner.SmokeGlow
+ && combiner.StageCount<=2) {
+ WaterShoreOverlay::View view;
+ view.colour=reinterpret_cast<std::uintptr_t>(target.Colour);view.depth=reinterpret_cast<std::uintptr_t>(target.Depth);
+ view.width=target.Width;view.height=target.Height;
+ shore_depth=Gpu->Ready_Water_Depth(target,view.capture);
+ SdlPixelConstants unused={};SdlWaterPixelConstants water;Build_Water_Constants(unused,water);
+ memcpy(view.worldFromClip,water.WorldFromClip,sizeof(view.worldFromClip));
+ memcpy(view.viewport,water.Viewport,sizeof(view.viewport));
+ if(shore_depth) for(const ShoreRegion &region:ShoreRegions) {
+ if(WaterShoreOverlay::SameView(view,region.view) && WaterShoreOverlay::Contains(region.patch,ShoreTrack)) {
+ // Upload failures are optional-feature failures. Keep the original .wak draw intact.
+ SDL_GPUTexture *height=Mirrors->Texture(region.height.get(),refusal);
+ SDL_GPUTexture *optical=Mirrors->Texture(region.optical.get(),refusal);
+ if(height && optical && height!=target.Colour && height!=target.Depth && optical!=target.Colour && optical!=target.Depth) {
+ const SdlProgram &candidate=Programs->Shore_Pixel_Program(combiner);
+ if(candidate.Shader) {pixel_program=&candidate;shore_region=&region;shore_overlay=true;}
+ }
+ break;
+ }
+ }
+ }
+ if (vertex_program.Shader == NULL || pixel_program->Shader == NULL) {
Refuse_Draw(vertex_program.Shader == NULL ? "a vertex program refused" : "a pixel program refused");
return D3D_OK;
}
- if (pixel_program.SamplerSlots > SdlRecordedDraw::MAXIMUM_SAMPLERS || vertex_program.SamplerSlots != 0) {
+ if (pixel_program->SamplerSlots > SdlRecordedDraw::MAXIMUM_SAMPLERS
+ || vertex_program.SamplerSlots > (fft_water ? 4u : 0u)) {
Refuse_Draw("more sampler slots than a draw binds");
return D3D_OK;
}
+ const bool modern_water_pixel=pixel_engine==ENGINE_SHADER_WATER_TRAPEZOID || pixel_engine==ENGINE_SHADER_WATER_RIVER;
+ if(!Sdl_Draw_Uniform_Buffers_Supported(fft_water,modern_water_pixel,
+ vertex_program.UniformBuffers,pixel_program->UniformBuffers)) {
+ Refuse_Draw("uniform blocks without an explicit draw binding");
+ return D3D_OK;
+ }
// Every pass has the frame's depth-stencil, so every pipeline has its format; a draw with no depth
// surface bound has D3D9's answer instead, depth and stencil off.
const RenderUInt32 *states = RenderStates;
@@ -841,8 +1046,18 @@ RenderResult PosixDevice9::Gpu_Draw(const DrawCall &call)
without_depth[D3DRS_STENCILENABLE] = 0;
states = without_depth;
}
+ // The modern flat-water shader already refracts and attenuates the scene. The legacy
+ // destination-alpha mask would blend the unattenuated riverbed into it a second time.
+ RenderUInt32 water_states[RENDER_STATE_COUNT];
+ if (pixel_engine == ENGINE_SHADER_WATER_TRAPEZOID && states[D3DRS_SRCBLEND] == D3DBLEND_DESTALPHA
+ && states[D3DRS_DESTBLEND] == D3DBLEND_INVDESTALPHA) {
+ memcpy(water_states, states, sizeof(water_states));
+ water_states[D3DRS_SRCBLEND] = D3DBLEND_SRCALPHA;
+ water_states[D3DRS_DESTBLEND] = D3DBLEND_INVSRCALPHA;
+ states = water_states;
+ }
SdlPipelineKey key;
- if (!Sdl_Pipeline_Key(states, call.Type, vertex_program.Shader, pixel_program.Shader, FVF,
+ if (!Sdl_Pipeline_Key(states, call.Type, vertex_program.Shader, pixel_program->Shader, FVF,
SdlGpuFrame::Target_Format(), Gpu->Depth_Format(), key, refusal)) {
Refuse_Draw("the pipeline: " + refusal);
return D3D_OK;
@@ -851,6 +1066,11 @@ RenderResult PosixDevice9::Gpu_Draw(const DrawCall &call)
SdlRecordedDraw draw;
memset(&draw, 0, sizeof(draw));
draw.Pipeline = Pipelines->Pipeline(key);
+ if(!draw.Pipeline && shore_overlay) {
+ shore_overlay=false;pixel_program=legacy_pixel_program;
+ if(Sdl_Pipeline_Key(states,call.Type,vertex_program.Shader,pixel_program->Shader,FVF,
+ SdlGpuFrame::Target_Format(),Gpu->Depth_Format(),key,refusal)) draw.Pipeline=Pipelines->Pipeline(key);
+ }
phases.Mark("pipeline");
if (draw.Pipeline == NULL) {
Refuse_Draw("the GPU refused a pipeline");
@@ -873,25 +1093,116 @@ RenderResult PosixDevice9::Gpu_Draw(const DrawCall &call)
const bool stage_vertices = user || is_dynamic(vertex_buffer);
const bool stage_indices = call.Indexed && (fan || is_dynamic(index_buffer));
const unsigned int index_size = (call.Indexed && index_buffer->format() == D3DFMT_INDEX32) ? 4 : 2;
+ const bool water_draw = pixel_engine == ENGINE_SHADER_WATER_TRAPEZOID || pixel_engine == ENGINE_SHADER_WATER_RIVER;
+ SDL_GPUTexture *water_background = water_draw ? Gpu->Water_Background(target) : NULL;
+ SDL_GPUTexture *water_depth = water_draw ? Gpu->Water_Depth(target) : NULL;
+ bool water_history = water_draw && Water_Foam_History_Available();
+ bool coastal_view=water_draw && fft_water && CoastalActive && water_depth
+ && PixelShaderConstants[1][1]<.5f && PixelShaderConstants[6][3]>.5f
+ && Gpu->Prepare_Coastal_Surf_From_Ocean(CoastalRevision,PixelShaderConstants[1][0])
+ && Gpu->Prepare_Coastal_Surf_View(CoastalRevision);
+ SDL_GPUTexture *coastal_texture=coastal_view?Gpu->Coastal_Surf_View(CoastalRevision,CoastalLevel):NULL;
+ SDL_GPUSampler *coastal_sampler=coastal_view?Gpu->Coastal_Surf_View_Sampler(CoastalRevision,CoastalLevel):NULL;
+ coastal_view=coastal_view && coastal_texture && coastal_sampler
+ && coastal_texture!=target.Colour && coastal_texture!=target.Depth;
+ draw.VertexSamplerCount = vertex_program.SamplerSlots;
+ for (unsigned int slot = 0; slot < draw.VertexSamplerCount && slot < 3; ++slot) {
+ draw.VertexTextures[slot] = Gpu->Ocean_Map(slot * 2);
+ draw.VertexSamplers[slot] = Gpu->Ocean_Sampler();
+ }
// The GPU copies. Bringing one up to date can flush the batch, which leaves the ones already asked
// for marked as used by the batch before: so ask again until a round flushes nothing.
for (int round = 0; round < 3; ++round) {
const uint64_t batch = Gpu->Batch();
++phases.Rounds;
- draw.SamplerCount = pixel_program.SamplerSlots;
- for (unsigned int slot = 0; slot < pixel_program.SamplerSlots; ++slot) {
- const int texture_stage = pixel_program.SlotTexture[slot];
- const int sampler_stage = pixel_program.SlotSampler[slot];
+ draw.SamplerCount = pixel_program->SamplerSlots;
+ for (unsigned int slot = 0; slot < pixel_program->SamplerSlots; ++slot) {
+ const int texture_stage = pixel_program->SlotTexture[slot];
+ const int sampler_stage = pixel_program->SlotSampler[slot];
+ if (water_draw && texture_stage==15) {
+ draw.Textures[slot]=coastal_view?coastal_texture:Mirrors->White();
+ draw.Samplers[slot]=coastal_view?coastal_sampler:Samplers->Sampler(SamplerStates[0]);
+ if(!draw.Textures[slot] || !draw.Samplers[slot])return D3D_OK;
+ continue;
+ }
+ if (water_draw && texture_stage >= 8 && texture_stage < 14) {
+ draw.Textures[slot] = fft_water ? Gpu->Ocean_Map(texture_stage - 8) : Mirrors->White();
+ draw.Samplers[slot] = fft_water ? Gpu->Ocean_Sampler() : Samplers->Sampler(SamplerStates[0]);
+ if (!draw.Textures[slot] || !draw.Samplers[slot]) return D3D_OK;
+ continue;
+ }
if (texture_stage < 0 || texture_stage >= SAMPLER_COUNT || sampler_stage < 0 || sampler_stage >= SAMPLER_COUNT) {
Refuse_Draw("a program slot past the device's stages");
return D3D_OK;
}
- IDirect3DBaseTexture9 *texture = Textures[texture_stage];
+ IDirect3DBaseTexture9 *texture = water_draw && texture_stage == 14 && !water_history ? NULL : Textures[texture_stage];
+ if(shore_region && pixel_program!=legacy_pixel_program && texture_stage==2) texture=shore_region->height.get();
+ if(shore_region && pixel_program!=legacy_pixel_program && texture_stage==4) texture=shore_region->optical.get();
double since = phases.Now();
- draw.Textures[slot] = texture != NULL ? Mirrors->Texture(texture, refusal) : Mirrors->White();
+ draw.Textures[slot] = shore_region && pixel_program!=legacy_pixel_program && texture_stage==6
+ ? (shore_depth ? shore_depth : Mirrors->White())
+ : water_draw && texture_stage == 5
+ ? (water_background ? water_background : Mirrors->White())
+ : water_draw && texture_stage == 6
+ ? (water_depth ? water_depth : Mirrors->White())
+ : (texture != NULL ? Mirrors->Texture(texture, refusal) : Mirrors->White());
phases.Part(0, since);
- if (draw.Textures[slot] != NULL && draw.Textures[slot] == target.Colour) {
+ if (water_draw && texture_stage == 14 && (draw.Textures[slot] == NULL
+ || draw.Textures[slot] == target.Colour || draw.Textures[slot] == target.Depth)) {
+ // Failure of an optional history upload must retain the working water fallback.
+ water_history = false;
+ draw.Textures[slot] = Mirrors->White();
+ }
+ if(shore_region && pixel_program!=legacy_pixel_program && (texture_stage==2||texture_stage==4||texture_stage==6)
+ && (!draw.Textures[slot]||draw.Textures[slot]==target.Colour||draw.Textures[slot]==target.Depth)) {
+ shore_overlay=false;draw.Textures[slot]=Mirrors->White();
+ }
+ if (draw.Textures[slot] != NULL && (draw.Textures[slot] == target.Colour || draw.Textures[slot] == target.Depth)) {
+ // Metadata only, at the rejected draw; the refusal remains in force.
+ // Four events/process maximum. Never use this evidence run for performance comparisons.
+ const char *aliasTrace=getenv("ZH_GPU_TARGET_ALIAS_TRACE");
+ static unsigned aliasTraceCount=0;
+ if(aliasTrace && strcmp(aliasTrace,"1")==0 && aliasTraceCount<4) {
+ ++aliasTraceCount;
+ D3DSURFACE_DESC td={},rt={},ds={};
+ if(texture && texture->GetType()==D3DRTYPE_TEXTURE)
+ static_cast<IDirect3DTexture9*>(texture)->GetLevelDesc(0,&td);
+ if(RenderTargets[0]) RenderTargets[0]->GetDesc(&rt);
+ if(DepthStencil) DepthStencil->GetDesc(&ds);
+ IDirect3DTexture9 *targetContainer=NULL;
+ if(RenderTargets[0]) RenderTargets[0]->GetContainer(IID_IDirect3DTexture9,(void**)&targetContainer);
+ fprintf(stderr,"target-alias: event=%u present=%u recorded=%u batch=%llu round=%d role=%s slot=%u texture_stage=%d sampler_stage=%d fvf=0x%x primitive_type=%u primitives=%u indexed=%d user_vertices=%d stride=%u\n",
+ aliasTraceCount,PresentCount,DrawsRecorded,(unsigned long long)Gpu->Batch(),round,
+ water_draw?"water":(shore_overlay?"shore-overlay":"ordinary"),slot,texture_stage,sampler_stage,
+ (unsigned)FVF,(unsigned)call.Type,call.PrimitiveCount,(int)call.Indexed,(int)user,stride);
+ fprintf(stderr,"target-alias-program: vs=%.*s ps=%.*s vertex_engine=%d pixel_engine=%d fft=%d shore=%d\n",
+ 256,vertex_program.Key.c_str(),256,pixel_program->Key.c_str(),vertex_engine,pixel_engine,(int)fft_water,(int)shore_overlay);
+ fprintf(stderr,"target-alias-gpu: sample=%p colour=%p depth=%p aliases_colour=%d aliases_depth=%d target_size=%ux%u background=%p water_depth=%p shore_depth=%p\n",
+ (void*)draw.Textures[slot],(void*)target.Colour,(void*)target.Depth,
+ (int)(draw.Textures[slot]==target.Colour),(int)(draw.Textures[slot]==target.Depth),target.Width,target.Height,
+ (void*)water_background,(void*)water_depth,(void*)shore_depth);
+ fprintf(stderr,"target-alias-d3d: texture=%p target=%p target_container=%p container_is_texture=%d backbuffer=%d depth_surface=%p texture_desc=%ux%u/%u/0x%x target_desc=%ux%u/%u/0x%x depth_desc=%ux%u/%u/0x%x\n",
+ (void*)texture,(void*)RenderTargets[0],(void*)targetContainer,(int)(targetContainer && targetContainer==texture),
+ (int)(RenderTargets[0]==BackBuffer),(void*)DepthStencil,
+ td.Width,td.Height,(unsigned)td.Format,(unsigned)td.Usage,rt.Width,rt.Height,(unsigned)rt.Format,(unsigned)rt.Usage,
+ ds.Width,ds.Height,(unsigned)ds.Format,(unsigned)ds.Usage);
+ if(targetContainer) targetContainer->Release();
+ const RenderUInt32 noStage[TEXTURE_STAGE_STATE_COUNT]={};
+ const RenderUInt32 *ts=texture_stage<TEXTURE_STAGE_COUNT ? TextureStageStates[texture_stage] : noStage;
+ fprintf(stderr,"target-alias-state: colour_op=%u args=%u,%u,%u alpha_op=%u args=%u,%u,%u z=%u/%u blend=%u/%u/%u colour_write=0x%x shadow=%d soft_particle=%d draw_effect=%d smoke_glow=%d\n",
+ (unsigned)ts[D3DTSS_COLOROP],(unsigned)ts[D3DTSS_COLORARG0],(unsigned)ts[D3DTSS_COLORARG1],(unsigned)ts[D3DTSS_COLORARG2],
+ (unsigned)ts[D3DTSS_ALPHAOP],(unsigned)ts[D3DTSS_ALPHAARG0],(unsigned)ts[D3DTSS_ALPHAARG1],(unsigned)ts[D3DTSS_ALPHAARG2],
+ (unsigned)states[D3DRS_ZENABLE],(unsigned)states[D3DRS_ZWRITEENABLE],(unsigned)states[D3DRS_ALPHABLENDENABLE],
+ (unsigned)states[D3DRS_SRCBLEND],(unsigned)states[D3DRS_DESTBLEND],(unsigned)states[D3DRS_COLORWRITEENABLE],
+ (int)combiner.ShadowReceiving,(int)combiner.SoftParticle,(int)combiner.DrawEffect,(int)combiner.SmokeGlow);
+#if defined(__linux__)
+ void *stack[16];const int count=backtrace(stack,16);
+ fprintf(stderr,"target-alias-stack: begin event=%u frames=%d\n",aliasTraceCount,count);fflush(stderr);
+ backtrace_symbols_fd(stack,count,2);
+ fprintf(stderr,"target-alias-stack: end event=%u\n",aliasTraceCount);
+#endif
+ }
// Undefined in D3D9, and an error on SDL3 GPU: the pass would read what it writes.
Refuse_Draw("sampling the render target it draws into");
return D3D_OK;
@@ -901,13 +1212,45 @@ RenderResult PosixDevice9::Gpu_Draw(const DrawCall &call)
return D3D_OK;
}
since = phases.Now();
- draw.Samplers[slot] = Samplers->Sampler(SamplerStates[sampler_stage]);
+ RenderUInt32 water_sampler[SAMPLER_STATE_COUNT];
+ const RenderUInt32 *sampler_states = SamplerStates[sampler_stage];
+ if ((water_draw && (texture_stage == 2 || texture_stage == 4 || texture_stage == 5 || texture_stage == 6 || texture_stage == 7 || texture_stage == 14))
+ || (shore_region && pixel_program!=legacy_pixel_program && (texture_stage==2||texture_stage==4||texture_stage==6))) {
+ memcpy(water_sampler, sampler_states, sizeof(water_sampler));
+ sampler_states = water_sampler;
+ water_sampler[D3DSAMP_ADDRESSU] = water_sampler[D3DSAMP_ADDRESSV]
+ = texture_stage == 7 ? D3DTADDRESS_WRAP : D3DTADDRESS_CLAMP;
+ water_sampler[D3DSAMP_MINFILTER] = water_sampler[D3DSAMP_MAGFILTER]
+ = texture_stage == 6 ? D3DTEXF_POINT : D3DTEXF_LINEAR;
+ water_sampler[D3DSAMP_MIPFILTER] = texture_stage == 7 ? D3DTEXF_LINEAR : D3DTEXF_NONE;
+ }
+ draw.Samplers[slot] = Samplers->Sampler(sampler_states);
phases.Part(1, since);
if (draw.Samplers[slot] == NULL) {
Refuse_Draw("the sampler: " + Samplers->Refusal());
return D3D_OK;
}
}
+ if (draw.VertexSamplerCount > 3) {
+ // The cage reads the same terrain resource as pixel stage 2. Resolve it
+ // inside this retry loop: updating a mirror can flush the current batch.
+ const double texture_since=phases.Now();
+ draw.VertexTextures[3]=Textures[2] ? Mirrors->Texture(Textures[2],refusal) : Mirrors->White();
+ phases.Part(0,texture_since);
+ if (!draw.VertexTextures[3]) { Refuse_Draw("the vertex terrain texture: "+refusal);return D3D_OK; }
+ if (draw.VertexTextures[3]==target.Colour || draw.VertexTextures[3]==target.Depth) {
+ Refuse_Draw("sampling the render target as vertex terrain");return D3D_OK;
+ }
+ RenderUInt32 terrain_sampler[SAMPLER_STATE_COUNT];
+ memcpy(terrain_sampler,SamplerStates[2],sizeof(terrain_sampler));
+ terrain_sampler[D3DSAMP_ADDRESSU]=terrain_sampler[D3DSAMP_ADDRESSV]=D3DTADDRESS_CLAMP;
+ terrain_sampler[D3DSAMP_MINFILTER]=terrain_sampler[D3DSAMP_MAGFILTER]=D3DTEXF_LINEAR;
+ terrain_sampler[D3DSAMP_MIPFILTER]=D3DTEXF_NONE;
+ const double sampler_since=phases.Now();
+ draw.VertexSamplers[3]=Samplers->Sampler(terrain_sampler);
+ phases.Part(1,sampler_since);
+ if (!draw.VertexSamplers[3]) { Refuse_Draw("the vertex terrain sampler: "+Samplers->Refusal());return D3D_OK; }
+ }
const double buffers_since = phases.Now();
if (!stage_vertices) {
draw.VertexBuffer = Mirrors->Buffer(vertex_buffer, vertex_buffer->storage(), refusal);
@@ -960,7 +1303,7 @@ RenderResult PosixDevice9::Gpu_Draw(const DrawCall &call)
if (index < call.MinVertex || index >= call.MinVertex + call.VertexCount) {
fprintf(stderr, "PosixDevice9: a draw reads index %u outside MinVertex %u + VertexCount %u (start index %u, "
"%u primitives, base vertex %d, programs %s | %s)\n", index, call.MinVertex, call.VertexCount,
- call.StartIndex, call.PrimitiveCount, call.BaseVertex, vertex_program.Key.c_str(), pixel_program.Key.c_str());
+ call.StartIndex, call.PrimitiveCount, call.BaseVertex, vertex_program.Key.c_str(), pixel_program->Key.c_str());
abort();
}
}
@@ -1040,7 +1383,7 @@ RenderResult PosixDevice9::Gpu_Draw(const DrawCall &call)
draw.Count = reads;
}
- Trace_Draw_If_Asked(call, vertex_program.Key + " | " + pixel_program.Key,
+ Trace_Draw_If_Asked(call, vertex_program.Key + " | " + pixel_program->Key,
vertex_buffer, stride);
if (Capture_Is_Asked()) {
// The signature: both programs' keys, and the pipeline key's bytes (the pipeline's states, formats
@@ -1057,10 +1400,10 @@ RenderResult PosixDevice9::Gpu_Draw(const DrawCall &call)
char pipeline[40];
snprintf(pipeline, sizeof(pipeline), " | pipeline %016llx", (unsigned long long)hash);
unsigned int sampled = 0;
- for (unsigned int slot = 0; slot < pixel_program.SamplerSlots; ++slot) {
- sampled |= 1u << pixel_program.SlotTexture[slot];
+ for (unsigned int slot = 0; slot < pixel_program->SamplerSlots; ++slot) {
+ sampled |= 1u << pixel_program->SlotTexture[slot];
}
- Capture_Draw(call, vertex_program.Key + " | " + pixel_program.Key + pipeline, stride, reads, sampled,
+ Capture_Draw(call, vertex_program.Key + " | " + pixel_program->Key + pipeline, stride, reads, sampled,
target.Width, target.Height);
}
@@ -1079,14 +1422,76 @@ RenderResult PosixDevice9::Gpu_Draw(const DrawCall &call)
draw.VertexConstants = Gpu->Constants(0, &vertex_constants, sizeof(vertex_constants));
draw.VertexConstantsSize = sizeof(vertex_constants);
}
- if (pixel_program.UniformBuffers != 0 && pixel_engine != ENGINE_SHADER_NONE) {
+ if (pixel_program->UniformBuffers != 0 &&
+ (pixel_engine == ENGINE_SHADER_WATER_TRAPEZOID || pixel_engine == ENGINE_SHADER_WATER_RIVER)) {
+ SdlWaterPixelConstants water;
+ Build_Water_Constants(pixel_constants, water);
+ if (fft_water && !Textures[2]) water.TerrainParameters[3]=0.0f;
+ water.SceneParameters[0] = water_background ? 1.0f : 0.0f;
+ water.SceneParameters[1] = 1.0f / (float)target.Width;
+ water.SceneParameters[2] = 1.0f / (float)target.Height;
+ water.SceneParameters[3] = water_depth ? 1.0f : 0.0f;
+ water.FftParameters[0] = fft_water ? 1.0f : 0.0f;
+ water.FftParameters[1] = fft_water && WaterVesselWaves::Enabled() ? 1.0f : 0.0f;
+ if (!water_history) water.FoamHistoryParameters[0] = 0.0f;
+ if(coastal_view) {
+ water.CoastalArea[0]=float(CoastalMapping.originX);water.CoastalArea[1]=float(CoastalMapping.originY);
+ water.CoastalArea[2]=float(CoastalMapping.widthWorld);water.CoastalArea[3]=float(CoastalMapping.heightWorld);
+ water.CoastalParams[0]=1;water.CoastalParams[1]=float(CoastalLevel);
+ water.CoastalParams[2]=float(Gpu->Coastal_Surf_View_Time(CoastalRevision,CoastalLevel));
+ water.CoastalParams[3]=PixelShaderConstants[1][0];
+ if(getenv("ZH_WATER_SURF_TRACE")) {
+ static double last=-1;
+ if(floor(last)!=floor(water.CoastalParams[3])) {
+ last=water.CoastalParams[3];
+ fprintf(stderr,"water-surf-draw: time=%.3f sampled=%.3f revision=%llu nodes=%u history=%llu views=%llu sets=%llu level=%.3f area=(%.1f,%.1f,%.1f,%.1f)\n",
+ last,water.CoastalParams[2],(unsigned long long)CoastalRevision,Gpu->Coastal_Surf_Nodes(CoastalRevision),
+ (unsigned long long)Gpu->Coastal_Surf_Updates(),(unsigned long long)Gpu->Coastal_Surf_View_Updates(),
+ (unsigned long long)Gpu->Coastal_Surf_View_Sets(),CoastalLevel,CoastalMapping.originX,CoastalMapping.originY,
+ CoastalMapping.widthWorld,CoastalMapping.heightWorld);
+ }
+ }
+ }
+ if(pixel_program->UniformBuffers==4) {
+ SdlWaterVisualPixelConstants visual;
+ Build_Water_Visual_Constants(water,visual);
+ draw.PixelConstants=Gpu->Constants(1,&visual,sizeof(visual));
+ draw.PixelConstantsSize=sizeof(visual);
+ for(unsigned block=0;block<WaterHullVisualLayout::BlockCount;++block) {
+ const unsigned first=WaterHullVisualLayout::PacketRegister+WaterHullVisualLayout::BlockOffset(block);
+ const unsigned bytes=WaterHullVisualLayout::BlockRegisters(block)*16;
+ draw.PixelWaterConstants[block]=Gpu->Constants(1,PixelShaderConstants[first],bytes,block+1);
+ draw.PixelWaterConstantsSize[block]=bytes;
+ }
+ } else {
+ draw.PixelConstants = Gpu->Constants(1, &water, sizeof(water));
+ draw.PixelConstantsSize = sizeof(water);
+ }
+ if (fft_water) {
+ // The generated water vertex program reads precisely the same per-draw hulls and
+ // water time as its pixel program. Alias the recorded bytes so a later object's
+ // constants cannot change already queued displacement or its matching normals.
+ draw.VertexWaterConstants = draw.PixelConstants;
+ draw.VertexWaterConstantsSize = sizeof(SdlWaterPixelConstants);
+ }
+ }
+ else if(pixel_program->UniformBuffers!=0 && shore_region && pixel_program!=legacy_pixel_program) {
+ SdlShorePixelConstants shore={};shore.Combiner=pixel_constants;
+ memcpy(shore.WorldFromClip,shore_region->view.worldFromClip,sizeof(shore.WorldFromClip));
+ memcpy(shore.Viewport,shore_region->view.viewport,sizeof(shore.Viewport));
+ memcpy(shore.Terrain,shore_region->terrain,sizeof(shore.Terrain));
+ shore.Scene[1]=1.0f/target.Width;shore.Scene[2]=1.0f/target.Height;shore.Scene[3]=shore_overlay?1.0f:0.0f;
+ shore.Surface[0]=ShoreTrack.level;shore.Surface[1]=ShoreTrack.level+1.5f;shore.Surface[2]=1;
+ draw.PixelConstants=Gpu->Constants(1,&shore,sizeof(shore));draw.PixelConstantsSize=sizeof(shore);
+ }
+ else if (pixel_program->UniformBuffers != 0 && pixel_engine != ENGINE_SHADER_NONE) {
SdlEnginePixelConstants engine_constants;
memset(&engine_constants, 0, sizeof(engine_constants));
engine_constants.Combiner = pixel_constants;
draw.PixelConstants = Gpu->Constants(1, &engine_constants, sizeof(engine_constants));
draw.PixelConstantsSize = sizeof(engine_constants);
}
- else if (pixel_program.UniformBuffers != 0) {
+ else if (pixel_program->UniformBuffers != 0) {
draw.PixelConstants = Gpu->Constants(1, &pixel_constants, sizeof(pixel_constants));
draw.PixelConstantsSize = sizeof(pixel_constants);
}
@@ -1118,6 +1523,30 @@ RenderResult PosixDevice9::Gpu_Draw(const DrawCall &call)
draw.StencilReference = RenderStates[D3DRS_STENCILREF] & 0xFF;
draw.BlendFactor = RenderStates[D3DRS_BLENDFACTOR];
Gpu->Record_Draw(draw);
+ // Latch only a genuinely accepted modern flat-water draw with the actual scene snapshot.
+ // The ledger lasts one WaterRender call, includes actual targets, and owns texture references.
+ if(ShoreActive && ShoreHasPatch && pixel_engine==ENGINE_SHADER_WATER_TRAPEZOID && water_depth
+ && PixelShaderConstants[6][2]>.5f && PixelShaderConstants[6][3]>.5f && PixelShaderConstants[5][3]>.5f
+ && PixelShaderConstants[1][1]<.5f && RenderStates[D3DRS_FILLMODE]==D3DFILL_SOLID && Textures[2] && Textures[4]) {
+ ShoreRegion region;region.patch=ShorePatch;
+ region.view.colour=reinterpret_cast<std::uintptr_t>(target.Colour);region.view.depth=reinterpret_cast<std::uintptr_t>(target.Depth);
+ region.view.width=target.Width;region.view.height=target.Height;
+ if(Gpu->Ready_Water_Depth(target,region.view.capture)==water_depth) {
+ SdlWaterPixelConstants water;Build_Water_Constants(pixel_constants,water);
+ memcpy(region.view.worldFromClip,water.WorldFromClip,sizeof(region.view.worldFromClip));
+ memcpy(region.view.viewport,water.Viewport,sizeof(region.view.viewport));
+ memcpy(region.terrain,water.TerrainParameters,sizeof(region.terrain));
+ bool found=false;
+ for(const ShoreRegion &old:ShoreRegions) if(WaterShoreOverlay::SameView(old.view,region.view)
+ && old.patch.level==region.patch.level && memcmp(old.patch.xy,region.patch.xy,sizeof(old.patch.xy))==0) {found=true;break;}
+ if(!found && ShoreRegions.size()<WaterShoreOverlay::MaxRegions) {
+ Textures[2]->AddRef();Textures[4]->AddRef();
+ region.height=std::shared_ptr<IDirect3DBaseTexture9>(Textures[2],[](IDirect3DBaseTexture9 *t){t->Release();});
+ region.optical=std::shared_ptr<IDirect3DBaseTexture9>(Textures[4],[](IDirect3DBaseTexture9 *t){t->Release();});
+ ShoreRegions.push_back(region);
+ }
+ }
+ }
++DrawsRecorded;
if (vertex_engine != ENGINE_SHADER_NONE || pixel_engine != ENGINE_SHADER_NONE) {
++EngineProgramDraws[EngineShader_Name((EngineShaderProgram)(vertex_engine != ENGINE_SHADER_NONE
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlConstants.h b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlConstants.h
index f96fe2483..52f2ae089 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlConstants.h
+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlConstants.h
@@ -35,7 +35,9 @@
#ifndef SDLCONSTANTS_H
#define SDLCONSTANTS_H
-#include "ffvertex.h" // MAXIMUM_VERTEX_STAGES, MAXIMUM_VERTEX_LIGHTS
+#include "Platform/WaterHullVisualLayout.h"
+#include "Platform/ModernWaterMaterial.h"
+#include "../../../../Libraries/Source/WWVegas/WW3D2/ffvertex.h" // MAXIMUM_VERTEX_STAGES, MAXIMUM_VERTEX_LIGHTS
struct SdlVertexConstants
{
@@ -61,6 +63,68 @@ struct SdlPixelConstants
float AlphaReference[4]; ///< .x is D3DRS_ALPHAREF as a whole level, 0 to 255
};
+// Optional authored-surf wrapper. The original fixed-function prefix is byte-identical.
+struct SdlShorePixelConstants
+{
+ SdlPixelConstants Combiner;
+ float WorldFromClip[16];
+ float Viewport[4];
+ float Terrain[4];
+ float Scene[4];
+ float Surface[4];
+};
+static_assert(sizeof(SdlShorePixelConstants)==11*16,"shore wrapper packing");
+
+// Dedicated map-water uniforms. The common prefix keeps alpha testing and fog compatible with
+// the fixed-function pipeline; the remaining fields are used only by the SDL water shader.
+struct SdlWaterPixelConstants
+{
+ SdlPixelConstants Combiner;
+ float WorldFromClip[16];
+ float CameraPosition[4];
+ float SunDirection[4];
+ float SunColour[4];
+ float Viewport[4];
+ float ReflectionArea[4];
+ float WaterParameters[4]; // animation seconds, river flag, reflection available, mirror height
+ float TerrainParameters[4]; // height texture border, world size, height scale, available
+ float SceneParameters[4]; // refraction available, inverse scene-target width/height, scene depth available
+ float OpticalParameters[4]; // authored depth/opacity, offshore context available, flat UV0 height correction available
+ float HullParameters[4]; // number of visible vessel contours, authored ambient RGB for vessel foam
+ float HullData[80][4]; // eight vessels, ten float4 registers each; runtime waterline geometry
+ float FftParameters[4]; // x: the dedicated vertex displacement and six sampled ocean maps are bound
+ float FoamHistoryArea[4]; // world origin XY, inverse world width/height; sampled at undisplaced surface XY
+ float FoamHistoryParameters[4]; // available, water level, cell world size, simulation time of atlas
+ float ContactHullData[80][4]; // optional foam-only contours; count < 3 falls back to the matching mean hull
+ float FoamFillLights[4][4]; // two direction/colour pairs; first direction.w enables the main light for foam
+ float CoastalArea[4]; // lower world origin XY and extent XY of the independent coastal view
+ float CoastalParams[4]; // valid, exact level, successful history sample time, current water time
+#define MODERN_WATER_CPP_UNIFORM(name) float name[4];
+ MODERN_WATER_MATERIAL_UNIFORMS(MODERN_WATER_CPP_UNIFORM)
+#undef MODERN_WATER_CPP_UNIFORM
+};
+static_assert(sizeof(SdlWaterPixelConstants) == WaterHullVisualLayout::VertexCommonRegisters * 16, "water uniform packing");
+static_assert(offsetof(SdlWaterPixelConstants,MaterialColor)==186*16
+ && offsetof(SdlWaterPixelConstants,MaterialParameters)==187*16,"water material tail packing");
+
+// Fragment-only extension after the shared water vertex/pixel prefix.
+struct SdlWaterVisualPixelConstants
+{
+ SdlWaterPixelConstants Water;
+ float VisualHullMeta[WaterHullVisualLayout::MaxHulls][4];
+};
+static_assert(sizeof(SdlWaterVisualPixelConstants)==WaterHullVisualLayout::FragmentCommonRegisters*16,
+ "fragment hull metadata packing");
+
+// A generator adding a block must have an explicit recording/binding path. The mesh packet
+// is the only four-block fragment layout; ordinary shaders cannot silently inherit its data.
+inline bool Sdl_Draw_Uniform_Buffers_Supported(bool water_vertex, bool water_pixel,
+ unsigned vertex_buffers, unsigned pixel_buffers)
+{
+ return vertex_buffers<=(water_vertex?2u:1u)
+ && (pixel_buffers<=1u || (water_pixel && pixel_buffers==4u));
+}
+
/// What an engine pixel program's b0 declares (A3e, engineshader.cpp's write_pixel_preamble): the Direct3D
/// 11 backend's PixelConstantBlock, field for field. The first three are SdlPixelConstants; the rest -
/// the normal mapped lights, the terrain's sun, the shadow and the sky - are unread padding from the
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrame.cpp b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrame.cpp
index b78d2328e..1b6efccb0 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrame.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrame.cpp
@@ -20,6 +20,11 @@
#include "SdlGpuFrame.h"
#include "sdl3shadercompile.h"
+#include "Platform/WaterFftSpectrum.h"
+#include "Platform/WaterCoastalSurf.h"
+#include "Platform/WaterCoastalIncident.h"
+#include "Platform/WaterCoastalView.h"
+#include <memory>
#include <SDL3/SDL.h>
@@ -64,6 +69,14 @@ static const char GAMMA_PIXEL_HLSL[] =
" return float4(entry(colour.r, 0), entry(colour.g, 1), entry(colour.b, 2), colour.a);\n"
"}\n";
+// A separate colour-only pass avoids both read/write attachment feedback and backend-specific
+// depth/stencil copy restrictions. Point sampling preserves object edges and the original depth.
+static const char WATER_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";
+
bool Sdl_Gamma_Is_Identity(const uint16_t (*ramp)[256])
{
if (ramp == NULL) {
@@ -84,6 +97,12 @@ unsigned int SdlGpuFrame::Target_Format()
return BACK_BUFFER_FORMAT;
}
+unsigned int SdlGpuFrame::Depth_Usage() const
+{
+ return SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET
+ | (DepthSampleable ? SDL_GPU_TEXTUREUSAGE_SAMPLER : 0);
+}
+
SdlGpuFrame::SdlGpuFrame() :
SerializeSubmits(false),
FlushMs(0.0),
@@ -130,7 +149,7 @@ SdlGpuFrame::SdlGpuFrame() :
RampTexture(NULL),
PointSampler(NULL)
{
- LastConstants[0] = LastConstants[1] = LastConstantsSize[0] = LastConstantsSize[1] = 0;
+ memset(LastConstants,0,sizeof(LastConstants));memset(LastConstantsSize,0,sizeof(LastConstantsSize));
memset(ClearPipelines, 0, sizeof(ClearPipelines));
InFlight[0] = InFlight[1] = NULL;
// ZH_GPU_FLUSH_LIMIT=<n>: at most n mid-frame flushes in flight (default 3); 0 lets them pile up as before
@@ -165,10 +184,30 @@ SdlGpuFrame * SdlGpuFrame::Create(RenderWindow window, unsigned int width, unsig
delete frame;
return NULL;
}
- // D24S8 is what D3D9's auto depth-stencil almost always is; Apple's GPUs have none, and take D32S8.
- frame->DepthFormat = SDL_GPUTextureSupportsFormat(frame->GpuDevice, SDL_GPU_TEXTUREFORMAT_D24_UNORM_S8_UINT,
- SDL_GPU_TEXTURETYPE_2D, SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET)
- ? SDL_GPU_TEXTUREFORMAT_D24_UNORM_S8_UINT : SDL_GPU_TEXTUREFORMAT_D32_FLOAT_S8_UINT;
+ // Prefer a sampleable stencil format for the water's GPU depth resolve. Preserve rendering on a
+ // device without one by retaining the ordinary depth target, and disabling scene-depth sampling.
+ const SDL_GPUTextureFormat depth_formats[] = {
+ SDL_GPU_TEXTUREFORMAT_D24_UNORM_S8_UINT, SDL_GPU_TEXTUREFORMAT_D32_FLOAT_S8_UINT };
+ for (unsigned int sampled = 1; frame->DepthFormat == SDL_GPU_TEXTUREFORMAT_INVALID; --sampled) {
+ const SDL_GPUTextureUsageFlags usage = SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET
+ | (sampled ? SDL_GPU_TEXTUREUSAGE_SAMPLER : 0);
+ for (unsigned int i = 0; i < 2; ++i) {
+ if (SDL_GPUTextureSupportsFormat(frame->GpuDevice, depth_formats[i], SDL_GPU_TEXTURETYPE_2D, usage)) {
+ frame->DepthFormat = depth_formats[i];
+ frame->DepthSampleable = sampled != 0;
+ break;
+ }
+ }
+ if (!sampled) break;
+ }
+ frame->DepthSampleable = frame->DepthSampleable && SDL_GPUTextureSupportsFormat(frame->GpuDevice,
+ SDL_GPU_TEXTUREFORMAT_R32_FLOAT, SDL_GPU_TEXTURETYPE_2D,
+ SDL_GPU_TEXTUREUSAGE_COLOR_TARGET | SDL_GPU_TEXTUREUSAGE_SAMPLER);
+ if (frame->DepthFormat == SDL_GPU_TEXTUREFORMAT_INVALID) {
+ error = "no supported depth/stencil render-target format";
+ delete frame;
+ return NULL;
+ }
if (!frame->Create_Targets(width, height)) {
error = std::string("the back buffer: ") + SDL_GetError();
delete frame;
@@ -193,11 +232,12 @@ SdlGpuFrame::~SdlGpuFrame()
SDL_ReleaseGPUFence(GpuDevice, FlushFences[i]);
}
FlushFences.clear();
+ Release_Coastal_Surf();
+ Release_Ocean();
Release_Targets();
Commands.clear();
End_Batch();
if (StreamBuffer != NULL) SDL_ReleaseGPUBuffer(GpuDevice, StreamBuffer);
- for (size_t i = 0; i < ScratchDepths.size(); ++i) SDL_ReleaseGPUTexture(GpuDevice, ScratchDepths[i].Texture);
for (int i = 0; i < 8; ++i) if (ClearPipelines[i] != NULL) SDL_ReleaseGPUGraphicsPipeline(GpuDevice, ClearPipelines[i]);
if (ClearVertex != NULL) SDL_ReleaseGPUShader(GpuDevice, ClearVertex);
if (ClearPixel != NULL) SDL_ReleaseGPUShader(GpuDevice, ClearPixel);
@@ -207,6 +247,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 (WaterDepthPipeline != NULL) SDL_ReleaseGPUGraphicsPipeline(GpuDevice, WaterDepthPipeline);
+ if (WaterDepthVertex != NULL) SDL_ReleaseGPUShader(GpuDevice, WaterDepthVertex);
+ if (WaterDepthPixel != NULL) SDL_ReleaseGPUShader(GpuDevice, WaterDepthPixel);
+ if (WaterDepthSampler != NULL) SDL_ReleaseGPUSampler(GpuDevice, WaterDepthSampler);
if (Window != NULL) SDL_ReleaseWindowFromGPUDevice(GpuDevice, Window);
SDL_DestroyGPUDevice(GpuDevice);
}
@@ -226,7 +270,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 +279,13 @@ bool SdlGpuFrame::Create_Targets(unsigned int width, unsigned int height)
void SdlGpuFrame::Release_Targets()
{
+ for (size_t i = 0; i < WaterSnapshots.size(); ++i) {
+ if (WaterSnapshots[i].Colour) SDL_ReleaseGPUTexture(GpuDevice, WaterSnapshots[i].Colour);
+ if (WaterSnapshots[i].Depth) SDL_ReleaseGPUTexture(GpuDevice, WaterSnapshots[i].Depth);
+ }
+ WaterSnapshots.clear();
+ for (size_t i = 0; i < ScratchDepths.size(); ++i) SDL_ReleaseGPUTexture(GpuDevice, ScratchDepths[i].Texture);
+ ScratchDepths.clear();
if (BackBuffer != NULL) SDL_ReleaseGPUTexture(GpuDevice, BackBuffer);
if (DepthStencil != NULL) SDL_ReleaseGPUTexture(GpuDevice, DepthStencil);
if (FrontCopy != NULL) SDL_ReleaseGPUTexture(GpuDevice, FrontCopy);
@@ -245,11 +296,912 @@ void SdlGpuFrame::Release_Targets()
DisplayTexture = NULL; // made again at the new size by the next offscreen Present
}
+// Private native float targets bypass the legacy BGRA texture mirror. The field is independent of
+// window dimensions: resizing scene targets keeps both its seed and paused frame unchanged.
+struct SdlGpuFrame::OceanResources
+{
+ SDL_GPUTexture *Initial[3]={}, *Ping[2][6]={}, *Maps[6]={}, *Butterfly=NULL;
+ SDL_GPUShader *Vertex=NULL, *Pixels[4]={};
+ SDL_GPUGraphicsPipeline *Pipelines[4]={};
+ SDL_GPUSampler *Point=NULL,*Linear=NULL;
+
+ bool Pass(SDL_GPUCommandBuffer *commands,unsigned int which,SDL_GPUTexture **destination,
+ SDL_GPUTexture **source,unsigned int count,const float *parameters)
+ {
+ SDL_GPUColorTargetInfo targets[6]={};
+ for(unsigned i=0;i<6;++i) {
+ targets[i].texture=destination[i];targets[i].load_op=SDL_GPU_LOADOP_DONT_CARE;
+ targets[i].store_op=SDL_GPU_STOREOP_STORE;
+ // No cycling: all prior reads were submitted first and must see their old field. SDL
+ // orders the attachment/sampler transitions on this queue without a CPU wait/readback.
+ for(unsigned j=0;j<count;++j) if(source[j]==destination[i]) return false;
+ }
+ SDL_GPURenderPass *pass=SDL_BeginGPURenderPass(commands,targets,6,NULL);
+ if(!pass) return false;
+ SDL_BindGPUGraphicsPipeline(pass,Pipelines[which]);
+ SDL_GPUTextureSamplerBinding bindings[7]={};
+ for(unsigned i=0;i<count;++i) {bindings[i].texture=source[i];bindings[i].sampler=Point;}
+ SDL_BindGPUFragmentSamplers(pass,0,bindings,count);
+ const unsigned side=which==3?WaterFftSpectrum::Resolution>>unsigned(parameters[2]):WaterFftSpectrum::Resolution;
+ const SDL_GPUViewport viewport={0,0,float(side),float(side),0,1};
+ SDL_SetGPUViewport(pass,&viewport);
+ SDL_PushGPUFragmentUniformData(commands,0,parameters,8*sizeof(float));
+ SDL_DrawGPUPrimitives(pass,3,1,0,0);
+ SDL_EndGPURenderPass(pass);
+ return true;
+ }
+};
+
+// SDL's native Vulkan mip generator uses linear blits, whose format capabilities are not
+// covered by SDL_GPUTextureSupportsFormat. An explicit four-texel average only needs the
+// same float sampler/colour/copy capabilities as the FFT itself. Existing ping targets are
+// scratch; never sample a texture attached for writing, even at a different mip level.
+static std::string Ocean_Mip_Hlsl()
+{
+ std::string source=WaterFftSpectrum::Resources(6);
+ source+="Result main(float4 position:SV_Position) { int2 p=int2(position.xy)*2; int level=(int)Parameters.z-1; Result result;\n";
+ for(unsigned i=0;i<6;++i) {
+ const std::string s=std::to_string(i);
+ source+="result.v"+s+"=(T"+s+".Load(int3(p,level))+T"+s+".Load(int3(p+int2(1,0),level))+T"+s+
+ ".Load(int3(p+int2(0,1),level))+T"+s+".Load(int3(p+int2(1,1),level)))*0.25;\n";
+ }
+ return source+"return result; }\n";
+}
+
+void SdlGpuFrame::Release_Ocean()
+{
+ if(!Ocean) return;
+ for(auto *texture:Ocean->Initial) if(texture) SDL_ReleaseGPUTexture(GpuDevice,texture);
+ for(auto &pair:Ocean->Ping) for(auto *texture:pair) if(texture) SDL_ReleaseGPUTexture(GpuDevice,texture);
+ for(auto *texture:Ocean->Maps) if(texture) SDL_ReleaseGPUTexture(GpuDevice,texture);
+ if(Ocean->Butterfly) SDL_ReleaseGPUTexture(GpuDevice,Ocean->Butterfly);
+ for(auto *pipeline:Ocean->Pipelines) if(pipeline) SDL_ReleaseGPUGraphicsPipeline(GpuDevice,pipeline);
+ for(auto *shader:Ocean->Pixels) if(shader) SDL_ReleaseGPUShader(GpuDevice,shader);
+ if(Ocean->Vertex) SDL_ReleaseGPUShader(GpuDevice,Ocean->Vertex);
+ if(Ocean->Point) SDL_ReleaseGPUSampler(GpuDevice,Ocean->Point);
+ if(Ocean->Linear) SDL_ReleaseGPUSampler(GpuDevice,Ocean->Linear);
+ delete Ocean;Ocean=NULL;OceanReady=false;
+}
+
+bool SdlGpuFrame::Fail_Ocean(const char *reason)
+{
+ if(!OceanFailed) fprintf(stderr,"SdlGpuFrame: GPU ocean unavailable; keeping analytic water: %s\n",reason);
+ OceanFailed=true;Release_Ocean();return false;
+}
+
+bool SdlGpuFrame::Create_Ocean()
+{
+ using namespace WaterFftSpectrum;
+ const SDL_GPUTextureUsageFlags usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET|SDL_GPU_TEXTUREUSAGE_SAMPLER;
+ if(!SDL_GPUTextureSupportsFormat(GpuDevice,SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT,SDL_GPU_TEXTURETYPE_2D,usage))
+ return Fail_Ocean("RGBA32F colour-target/sampler usage unsupported");
+ Ocean=new OceanResources;
+ SDL_GPUTextureCreateInfo texture={};texture.type=SDL_GPU_TEXTURETYPE_2D;
+ texture.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;texture.usage=usage;
+ texture.width=texture.height=Resolution;texture.layer_count_or_depth=texture.num_levels=1;
+ for(auto *&target:Ocean->Initial) target=SDL_CreateGPUTexture(GpuDevice,&texture);
+ for(auto &pair:Ocean->Ping) for(auto *&target:pair) target=SDL_CreateGPUTexture(GpuDevice,&texture);
+ texture.num_levels=Phases+1;
+ for(auto *&target:Ocean->Maps) target=SDL_CreateGPUTexture(GpuDevice,&texture);
+ texture.num_levels=1;texture.width=Phases;Ocean->Butterfly=SDL_CreateGPUTexture(GpuDevice,&texture);
+ for(auto *target:Ocean->Initial) if(!target) return Fail_Ocean(SDL_GetError());
+ for(auto &pair:Ocean->Ping) for(auto *target:pair) if(!target) return Fail_Ocean(SDL_GetError());
+ for(auto *target:Ocean->Maps) if(!target) return Fail_Ocean(SDL_GetError());
+ if(!Ocean->Butterfly) return Fail_Ocean(SDL_GetError());
+ SDL_GPUSamplerCreateInfo sampler={};
+ sampler.address_mode_u=sampler.address_mode_v=sampler.address_mode_w=SDL_GPU_SAMPLERADDRESSMODE_REPEAT;
+ sampler.min_filter=sampler.mag_filter=SDL_GPU_FILTER_NEAREST;sampler.mipmap_mode=SDL_GPU_SAMPLERMIPMAPMODE_NEAREST;
+ Ocean->Point=SDL_CreateGPUSampler(GpuDevice,&sampler);
+ sampler.min_filter=sampler.mag_filter=SDL_GPU_FILTER_LINEAR;
+ sampler.mipmap_mode=SDL_GPU_SAMPLERMIPMAPMODE_LINEAR;sampler.max_lod=float(Phases);
+ Ocean->Linear=SDL_CreateGPUSampler(GpuDevice,&sampler);
+ if(!Ocean->Point || !Ocean->Linear) return Fail_Ocean(SDL_GetError());
+ std::vector<unsigned char> spirv;std::string error;
+ if(!SDL3_Compile_HLSL_To_SPIRV(VertexHlsl(),true,spirv,error) ||
+ !(Ocean->Vertex=SDL3_Create_Shader(GpuDevice,spirv,true,error))) return Fail_Ocean(error.c_str());
+ const std::string pixels[4]={SpectrumHlsl(),ButterflyHlsl(),PostHlsl(),Ocean_Mip_Hlsl()};
+ SDL_GPUColorTargetDescription targets[6]={};
+ for(auto &target:targets) target.format=texture.format;
+ for(unsigned i=0;i<4;++i) {
+ if(!SDL3_Compile_HLSL_To_SPIRV(pixels[i],false,spirv,error) ||
+ !(Ocean->Pixels[i]=SDL3_Create_Shader(GpuDevice,spirv,false,error))) return Fail_Ocean(error.c_str());
+ SDL_GPUGraphicsPipelineCreateInfo pipeline={};pipeline.vertex_shader=Ocean->Vertex;pipeline.fragment_shader=Ocean->Pixels[i];
+ pipeline.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;pipeline.rasterizer_state.cull_mode=SDL_GPU_CULLMODE_NONE;
+ pipeline.rasterizer_state.fill_mode=SDL_GPU_FILLMODE_FILL;
+ pipeline.target_info.color_target_descriptions=targets;pipeline.target_info.num_color_targets=6;
+ Ocean->Pipelines[i]=SDL_CreateGPUGraphicsPipeline(GpuDevice,&pipeline);
+ if(!Ocean->Pipelines[i]) return Fail_Ocean(SDL_GetError());
+ }
+ const std::vector<float> initial=InitialSpectrum(),butterfly=Butterfly();
+ const Uint32 fieldBytes=Resolution*Resolution*4*sizeof(float),butterflyBytes=Phases*Resolution*4*sizeof(float);
+ SDL_GPUTransferBufferCreateInfo transferInfo={};transferInfo.usage=SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD;
+ transferInfo.size=fieldBytes*3+butterflyBytes;
+ SDL_GPUTransferBuffer *transfer=SDL_CreateGPUTransferBuffer(GpuDevice,&transferInfo);
+ if(!transfer) return Fail_Ocean(SDL_GetError());
+ void *mapped=SDL_MapGPUTransferBuffer(GpuDevice,transfer,false);
+ if(!mapped) {SDL_ReleaseGPUTransferBuffer(GpuDevice,transfer);return Fail_Ocean(SDL_GetError());}
+ memcpy(mapped,initial.data(),fieldBytes*3);memcpy((char*)mapped+fieldBytes*3,butterfly.data(),butterflyBytes);
+ SDL_UnmapGPUTransferBuffer(GpuDevice,transfer);
+ SDL_GPUCommandBuffer *commands=SDL_AcquireGPUCommandBuffer(GpuDevice);
+ if(!commands) {SDL_ReleaseGPUTransferBuffer(GpuDevice,transfer);return Fail_Ocean(SDL_GetError());}
+ SDL_GPUCopyPass *copy=SDL_BeginGPUCopyPass(commands);
+ if(!copy) {SDL_CancelGPUCommandBuffer(commands);SDL_ReleaseGPUTransferBuffer(GpuDevice,transfer);return Fail_Ocean(SDL_GetError());}
+ for(unsigned i=0;i<4;++i) {
+ SDL_GPUTextureTransferInfo upload={};upload.transfer_buffer=transfer;upload.offset=i*fieldBytes;
+ upload.pixels_per_row=i==3?Phases:Resolution;upload.rows_per_layer=Resolution;
+ SDL_GPUTextureRegion region={};region.texture=i==3?Ocean->Butterfly:Ocean->Initial[i];
+ region.w=upload.pixels_per_row;region.h=Resolution;region.d=1;
+ SDL_UploadToGPUTexture(copy,&upload,&region,false);
+ }
+ SDL_EndGPUCopyPass(copy);
+ const bool submitted=SerializeSubmits?Submit(commands):Submit_Flush(commands);
+ SDL_ReleaseGPUTransferBuffer(GpuDevice,transfer);
+ if(!submitted) return Fail_Ocean(SDL_GetError());
+ return true;
+}
+
+bool SdlGpuFrame::Prepare_Ocean(float time)
+{
+ if(!std::isfinite(time) || OceanFailed) return false;
+ if(OceanReady && time==OceanTime) return true;
+ // Do not mutate a field referenced by draws still sitting in the CPU batch. Ordering submissions
+ // is sufficient; waiting or reading the texture back would unnecessarily serialize every frame.
+ if((!Commands.empty() || !Uploads.empty()) && !Flush()) return Fail_Ocean("could not submit preceding draws");
+ if(!Ocean && !Create_Ocean()) return false;
+ const Uint64 started=SDL_GetTicksNS();
+ SDL_GPUCommandBuffer *commands=SDL_AcquireGPUCommandBuffer(GpuDevice);
+ if(!commands) return Fail_Ocean(SDL_GetError());
+ using namespace WaterFftSpectrum;
+ float parameters[8]={float(Resolution),time,0,0,Sizes[0],Sizes[1],Sizes[2],0};
+ bool ok=Ocean->Pass(commands,0,Ocean->Ping[0],Ocean->Initial,3,parameters);
+ unsigned ping=0;
+ for(unsigned axis=0;ok && axis<2;++axis) for(unsigned phase=0;ok && phase<Phases;++phase) {
+ SDL_GPUTexture *sources[7];for(unsigned i=0;i<6;++i) sources[i]=Ocean->Ping[ping][i];sources[6]=Ocean->Butterfly;
+ parameters[2]=float(phase);parameters[3]=float(axis);
+ ok=Ocean->Pass(commands,1,Ocean->Ping[1-ping],sources,7,parameters);ping=1-ping;
+ }
+ if(ok) ok=Ocean->Pass(commands,2,Ocean->Maps,Ocean->Ping[ping],6,parameters);
+ for(unsigned level=1;ok && level<=Phases;++level) {
+ parameters[2]=float(level);
+ ok=Ocean->Pass(commands,3,Ocean->Ping[0],Ocean->Maps,6,parameters);
+ if(!ok) break;
+ SDL_GPUCopyPass *copy=SDL_BeginGPUCopyPass(commands);
+ if(!copy) {ok=false;break;}
+ for(unsigned i=0;i<6;++i) {
+ SDL_GPUTextureLocation source={};source.texture=Ocean->Ping[0][i];
+ SDL_GPUTextureLocation destination={};destination.texture=Ocean->Maps[i];destination.mip_level=level;
+ SDL_CopyGPUTextureToTexture(copy,&source,&destination,Resolution>>level,Resolution>>level,1,false);
+ }
+ SDL_EndGPUCopyPass(copy);
+ }
+ if(!ok) {SDL_CancelGPUCommandBuffer(commands);return Fail_Ocean("could not record independent FFT passes");}
+ ok=SerializeSubmits?Submit(commands):Submit_Flush(commands);
+ FlushMs+=double(SDL_GetTicksNS()-started)/1.0e6;++Flushes;++FlushesTotal;
+ if(!ok) return Fail_Ocean(SDL_GetError());
+ OceanTime=time;OceanReady=true;++OceanUpdates;return true;
+}
+
+SDL_GPUTexture *SdlGpuFrame::Ocean_Map(unsigned int index) const
+{
+ return OceanReady && Ocean && index<6?Ocean->Maps[index]:NULL;
+}
+
+SDL_GPUSampler *SdlGpuFrame::Ocean_Sampler() const
+{
+ return OceanReady && Ocean?Ocean->Linear:NULL;
+}
+
+// Compact, camera-independent coastal history. Every native texture has fixed format
+// and extent owned here; callers cannot substitute an unverified sampler attachment.
+struct SdlGpuFrame::CoastalSurfResources
+{
+ SDL_GPUDevice *Device;
+ SDL_GPUTexture *Domain[5]={}, *State[3]={}, *Input=NULL;
+ SDL_GPUShader *Vertex=NULL, *Pixels[2]={};
+ SDL_GPUGraphicsPipeline *Pipelines[2]={},*IncidentPipeline=NULL;
+ SDL_GPUShader *IncidentPixel=NULL;
+ SDL_GPUSampler *Point=NULL;
+ WaterCoastalSurf::Clock Clock;
+ std::vector<float> Payload;
+ uint64_t Revision=0;
+ unsigned Count=0,Active=0;
+ double Spacing=0;
+ bool Ready=false;
+
+ explicit CoastalSurfResources(SDL_GPUDevice *device):Device(device) {}
+ ~CoastalSurfResources() {
+ if(IncidentPipeline) SDL_ReleaseGPUGraphicsPipeline(Device,IncidentPipeline);
+ if(IncidentPixel) SDL_ReleaseGPUShader(Device,IncidentPixel);
+ for(auto *pipeline:Pipelines) if(pipeline) SDL_ReleaseGPUGraphicsPipeline(Device,pipeline);
+ for(auto *pixel:Pixels) if(pixel) SDL_ReleaseGPUShader(Device,pixel);
+ if(Vertex) SDL_ReleaseGPUShader(Device,Vertex);
+ if(Point) SDL_ReleaseGPUSampler(Device,Point);
+ for(auto *texture:Domain) if(texture) SDL_ReleaseGPUTexture(Device,texture);
+ for(auto *texture:State) if(texture) SDL_ReleaseGPUTexture(Device,texture);
+ if(Input) SDL_ReleaseGPUTexture(Device,Input);
+ }
+ bool CreateIncident() {
+ if(IncidentPipeline) return true;
+ std::string source,error;std::vector<unsigned char> spirv;
+ if(!WaterCoastalIncident::PixelSource(source)
+ || !SDL3_Compile_HLSL_To_SPIRV(source,false,spirv,error)) return false;
+ unsigned samplers=0,uniforms=0;SDL3_Shader_Slots(spirv,false,samplers,uniforms);
+ if(samplers!=WaterCoastalIncident::SamplerCount || uniforms!=1) return false;
+ SDL_GPUShader *pixel=SDL3_Create_Shader(Device,spirv,false,error);if(!pixel) return false;
+ SDL_GPUColorTargetDescription target={};target.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
+ SDL_GPUGraphicsPipelineCreateInfo info={};info.vertex_shader=Vertex;info.fragment_shader=pixel;
+ info.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;info.rasterizer_state.cull_mode=SDL_GPU_CULLMODE_NONE;
+ info.rasterizer_state.fill_mode=SDL_GPU_FILLMODE_FILL;
+ info.target_info.color_target_descriptions=&target;info.target_info.num_color_targets=1;
+ SDL_GPUGraphicsPipeline *pipeline=SDL_CreateGPUGraphicsPipeline(Device,&info);
+ if(!pipeline){SDL_ReleaseGPUShader(Device,pixel);return false;}
+ IncidentPixel=pixel;IncidentPipeline=pipeline;return true;
+ }
+ bool IncidentPass(SDL_GPUCommandBuffer *commands,SDL_GPUTexture *const *ocean,
+ SDL_GPUSampler *oceanSampler,float time) {
+ if(!commands || !Input || !IncidentPipeline || !oceanSampler) return false;
+ SDL_GPUTextureSamplerBinding bindings[WaterCoastalIncident::SamplerCount]={};
+ for(unsigned i=0;i<4;++i) {
+ if(!Domain[i] || !ocean[i] || Domain[i]==Input || ocean[i]==Input) return false;
+ bindings[i].texture=Domain[i];bindings[i].sampler=Point;
+ bindings[4+i].texture=ocean[i];bindings[4+i].sampler=oceanSampler;
+ }
+ SDL_GPUColorTargetInfo target={};target.texture=Input;
+ target.load_op=SDL_GPU_LOADOP_DONT_CARE;target.store_op=SDL_GPU_STOREOP_STORE;
+ SDL_GPURenderPass *pass=SDL_BeginGPURenderPass(commands,&target,1,NULL);if(!pass) return false;
+ SDL_BindGPUGraphicsPipeline(pass,IncidentPipeline);
+ SDL_BindGPUFragmentSamplers(pass,0,bindings,WaterCoastalIncident::SamplerCount);
+ const SDL_GPUViewport viewport={0,0,float(WaterCoastalSurf::AtlasSide),float(WaterCoastalSurf::AtlasSide),0,1};
+ SDL_SetGPUViewport(pass,&viewport);
+ const WaterCoastalIncident::Parameters parameters{time,float(Count),0,0};
+ SDL_PushGPUFragmentUniformData(commands,0,&parameters,sizeof(parameters));
+ SDL_DrawGPUPrimitives(pass,3,1,0,0);SDL_EndGPURenderPass(pass);return true;
+ }
+ bool Pass(SDL_GPUCommandBuffer *commands,unsigned which,SDL_GPUTexture *destination,
+ SDL_GPUTexture **sources,unsigned count,const float parameters[4]) {
+ if(!commands || which>=2 || !destination || count!=(which?2u:5u)) return false;
+ for(unsigned i=0;i<count;++i) if(!sources[i] || sources[i]==destination) return false;
+ SDL_GPUColorTargetInfo target={};target.texture=destination;
+ target.load_op=SDL_GPU_LOADOP_DONT_CARE;target.store_op=SDL_GPU_STOREOP_STORE;
+ // No cycling: all older readers have already been submitted before this update.
+ SDL_GPURenderPass *pass=SDL_BeginGPURenderPass(commands,&target,1,NULL);
+ if(!pass) return false;
+ SDL_BindGPUGraphicsPipeline(pass,Pipelines[which]);
+ SDL_GPUTextureSamplerBinding bindings[5]={};
+ for(unsigned i=0;i<count;++i){bindings[i].texture=sources[i];bindings[i].sampler=Point;}
+ SDL_BindGPUFragmentSamplers(pass,0,bindings,count);
+ const SDL_GPUViewport viewport={0,0,float(WaterCoastalSurf::AtlasSide),float(WaterCoastalSurf::AtlasSide),0,1};
+ SDL_SetGPUViewport(pass,&viewport);
+ SDL_PushGPUFragmentUniformData(commands,0,parameters,4*sizeof(float));
+ SDL_DrawGPUPrimitives(pass,3,1,0,0);
+ SDL_EndGPURenderPass(pass);return true;
+ }
+};
+
+static std::string Coastal_Surf_Pixel_Source(bool diffusion)
+{
+ std::string source;
+ const unsigned count=diffusion?2:5;
+ for(unsigned i=0;i<count;++i) source+="Texture2D<float4> T"+std::to_string(i)+" : register(t"+std::to_string(i)+", space2);\n";
+ source+="cbuffer SurfParameters : register(b0, space3) { float4 Parameters; };\n";
+ source+=WaterCoastalSurf::Source();
+ if(diffusion) source+=R"SURF(
+float4 surfNeighbour(float id) {
+ if(!isfinite(id)||id<1||id>Parameters.x||id!=floor(id)) return float4(-1,0,0,-1);
+ uint at=(uint)id-1;return T0.Load(int3(at%256,at/256,0));
+}
+float4 main(float4 position:SV_Position):SV_Target0 {
+ uint2 pixel=(uint2)position.xy;uint index=pixel.y*256+pixel.x;
+ if(index>=(uint)Parameters.x) return float4(0,0,0,-1);
+ float4 centre=T0.Load(int3(pixel,0)),ids=T1.Load(int3(pixel,0));
+ uint mask=0;float4 a=0,b=0,c=0,d=0;
+ if(ids.x!=0){mask|=1;a=surfNeighbour(ids.x);}
+ if(ids.y!=0){mask|=2;b=surfNeighbour(ids.y);}
+ if(ids.z!=0){mask|=4;c=surfNeighbour(ids.z);}
+ if(ids.w!=0){mask|=8;d=surfNeighbour(ids.w);}
+ return waterSurfDiffuse(centre,a,b,c,d,mask,Parameters.z,Parameters.y);
+}
+)SURF";
+ else source+=R"SURF(
+float4 main(float4 position:SV_Position):SV_Target0 {
+ uint2 pixel=(uint2)position.xy;uint index=pixel.y*256+pixel.x;
+ if(index>=(uint)Parameters.x || Parameters.w>1.5) return float4(0,0,0,-1);
+ WaterSurfContext context;
+ context.coast=T2.Load(int3(pixel,0));context.surface=T3.Load(int3(pixel,0));
+ context.admission=T4.Load(int3(pixel,0));
+ return waterSurfAdvance(context,T1.Load(int3(pixel,0)),T0.Load(int3(pixel,0)),
+ Parameters.y,Parameters.w<.5);
+}
+)SURF";
+ return source;
+}
+
+void SdlGpuFrame::Release_Coastal_Surf()
+{
+ Release_Coastal_Surf_View();
+ if(!CoastalSurf) return;
+ // Set_Target does not retain a resource. Do not leave an owned attachment as
+ // the implicit destination of a later clear after revision replacement/clear.
+ bool owned=CurrentTarget.Colour==CoastalSurf->Input;
+ for(auto *texture:CoastalSurf->Domain) owned|=CurrentTarget.Colour==texture;
+ for(auto *texture:CoastalSurf->State) owned|=CurrentTarget.Colour==texture;
+ if(TargetSet && owned){TargetSet=false;CurrentTarget={};}
+ delete CoastalSurf;CoastalSurf=NULL;
+}
+
+bool SdlGpuFrame::Clear_Coastal_Surf()
+{
+ // A recorded draw may still reference any exposed state or domain texture.
+ if((!Commands.empty() || !Uploads.empty()) && !Flush()) return false;
+ Release_Coastal_Surf();return true;
+}
+
+bool SdlGpuFrame::Install_Coastal_Surf(uint64_t revision,
+ const std::vector<WaterCoastalSurf::Node> &nodes,double spacing)
+{
+ using namespace WaterCoastalSurf;
+ if(!revision || !ValidGraph(nodes,spacing)) return false;
+ if(nodes.empty()) return Clear_Coastal_Surf();
+ const size_t plane=size_t(MaxNodes)*4;
+ std::vector<float> payload(plane*5,0);
+ for(size_t i=0;i<nodes.size();++i) {
+ const Node &node=nodes[i];const Context &c=node.context;
+ float *world=payload.data()+i*4,*coast=payload.data()+plane+i*4;
+ float *surface=payload.data()+plane*2+i*4,*admission=payload.data()+plane*3+i*4;
+ float *neighbours=payload.data()+plane*4+i*4;
+ world[0]=node.world[0];world[1]=node.world[1];world[2]=node.world[2];
+ coast[0]=c.depth;coast[1]=c.distance;coast[2]=c.outwardX;coast[3]=c.outwardY;
+ surface[0]=c.exposure;surface[1]=c.offshore;surface[2]=c.analyticDamping;surface[3]=c.spectralDamping;
+ admission[0]=c.wet;admission[1]=c.admitted;
+ for(unsigned side=0;side<4;++side) neighbours[side]=float(node.neighbour[side]);
+ }
+ if(CoastalSurf && CoastalSurf->Revision==revision) {
+ // Revision is an immutable domain identity. Repeated binds neither clear history
+ // nor silently accept changed bytes under a stale revision.
+ return CoastalSurf->Count==nodes.size() && CoastalSurf->Spacing==spacing
+ && CoastalSurf->Payload.size()==payload.size()
+ && memcmp(CoastalSurf->Payload.data(),payload.data(),payload.size()*sizeof(float))==0;
+ }
+ const SDL_GPUTextureUsageFlags usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET|SDL_GPU_TEXTUREUSAGE_SAMPLER;
+ if(!SDL_GPUTextureSupportsFormat(GpuDevice,SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT,
+ SDL_GPU_TEXTURETYPE_2D,usage)) return false; // retain the existing water fallback
+ std::unique_ptr<CoastalSurfResources> next(new CoastalSurfResources(GpuDevice));
+ next->Revision=revision;next->Count=unsigned(nodes.size());next->Spacing=spacing;next->Payload=std::move(payload);
+ SDL_GPUTextureCreateInfo info={};info.type=SDL_GPU_TEXTURETYPE_2D;
+ info.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;info.usage=usage;
+ info.width=info.height=AtlasSide;info.layer_count_or_depth=info.num_levels=1;
+ for(auto *&texture:next->Domain) texture=SDL_CreateGPUTexture(GpuDevice,&info);
+ for(auto *&texture:next->State) texture=SDL_CreateGPUTexture(GpuDevice,&info);
+ next->Input=SDL_CreateGPUTexture(GpuDevice,&info);
+ for(auto *texture:next->Domain) if(!texture) return false;
+ for(auto *texture:next->State) if(!texture) return false;
+ if(!next->Input) return false;
+ SDL_GPUSamplerCreateInfo sampler={};
+ sampler.address_mode_u=sampler.address_mode_v=sampler.address_mode_w=SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
+ sampler.min_filter=sampler.mag_filter=SDL_GPU_FILTER_NEAREST;sampler.mipmap_mode=SDL_GPU_SAMPLERMIPMAPMODE_NEAREST;
+ next->Point=SDL_CreateGPUSampler(GpuDevice,&sampler);if(!next->Point) return false;
+ std::vector<unsigned char> spirv;std::string error;
+ if(!SDL3_Compile_HLSL_To_SPIRV(WaterFftSpectrum::VertexHlsl(),true,spirv,error)
+ || !(next->Vertex=SDL3_Create_Shader(GpuDevice,spirv,true,error))) return false;
+ for(unsigned which=0;which<2;++which) {
+ if(!SDL3_Compile_HLSL_To_SPIRV(Coastal_Surf_Pixel_Source(which!=0),false,spirv,error)) return false;
+ unsigned samplers=0,uniforms=0;SDL3_Shader_Slots(spirv,false,samplers,uniforms);
+ if(samplers!=(which?2u:5u) || uniforms!=1) return false;
+ next->Pixels[which]=SDL3_Create_Shader(GpuDevice,spirv,false,error);if(!next->Pixels[which]) return false;
+ SDL_GPUColorTargetDescription target={};target.format=info.format;
+ SDL_GPUGraphicsPipelineCreateInfo pipeline={};pipeline.vertex_shader=next->Vertex;
+ pipeline.fragment_shader=next->Pixels[which];pipeline.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;
+ pipeline.rasterizer_state.cull_mode=SDL_GPU_CULLMODE_NONE;pipeline.rasterizer_state.fill_mode=SDL_GPU_FILLMODE_FILL;
+ pipeline.target_info.color_target_descriptions=&target;pipeline.target_info.num_color_targets=1;
+ next->Pipelines[which]=SDL_CreateGPUGraphicsPipeline(GpuDevice,&pipeline);
+ if(!next->Pipelines[which]) return false;
+ }
+ const Uint32 bytes=Uint32(plane*sizeof(float));
+ SDL_GPUTransferBufferCreateInfo transferInfo={};transferInfo.usage=SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD;
+ transferInfo.size=bytes*9; // five domain, three state, one incident texture: 9 MiB maximum
+ SDL_GPUTransferBuffer *transfer=SDL_CreateGPUTransferBuffer(GpuDevice,&transferInfo);
+ if(!transfer) return false;
+ float *mapped=static_cast<float *>(SDL_MapGPUTransferBuffer(GpuDevice,transfer,false));
+ if(!mapped){SDL_ReleaseGPUTransferBuffer(GpuDevice,transfer);return false;}
+ memcpy(mapped,next->Payload.data(),bytes*5);
+ memset(mapped+plane*5,0,bytes*4);
+ for(unsigned state=0;state<3;++state) for(unsigned i=0;i<MaxNodes;++i) mapped[plane*(5+state)+i*4+3]=-1;
+ // Until the producer writes a real incident field, this valid still field cannot emit.
+ for(unsigned i=0;i<MaxNodes;++i) mapped[plane*8+i*4+3]=1;
+ SDL_UnmapGPUTransferBuffer(GpuDevice,transfer);
+ // The old resources remain intact on every allocation/compile/upload-recording failure.
+ if((!Commands.empty() || !Uploads.empty()) && !Flush()) {
+ SDL_ReleaseGPUTransferBuffer(GpuDevice,transfer);return false;
+ }
+ SDL_GPUCommandBuffer *commands=SDL_AcquireGPUCommandBuffer(GpuDevice);
+ if(!commands){SDL_ReleaseGPUTransferBuffer(GpuDevice,transfer);return false;}
+ SDL_GPUCopyPass *copy=SDL_BeginGPUCopyPass(commands);
+ if(!copy){SDL_CancelGPUCommandBuffer(commands);SDL_ReleaseGPUTransferBuffer(GpuDevice,transfer);return false;}
+ for(unsigned i=0;i<9;++i) {
+ SDL_GPUTextureTransferInfo upload={};upload.transfer_buffer=transfer;upload.offset=i*bytes;
+ upload.pixels_per_row=upload.rows_per_layer=AtlasSide;
+ SDL_GPUTextureRegion region={};region.texture=i<5?next->Domain[i]:i<8?next->State[i-5]:next->Input;
+ region.w=region.h=AtlasSide;region.d=1;SDL_UploadToGPUTexture(copy,&upload,&region,false);
+ }
+ SDL_EndGPUCopyPass(copy);
+ const bool submitted=SerializeSubmits?Submit(commands):Submit_Flush(commands);
+ SDL_ReleaseGPUTransferBuffer(GpuDevice,transfer);
+ if(!submitted) return false;
+ Release_Coastal_Surf();CoastalSurf=next.release();++CoastalSurfInstalls;
+ return true;
+}
+
+SdlTarget SdlGpuFrame::Coastal_Surf_Field_Target(uint64_t revision) const
+{
+ SdlTarget target={};
+ if(CoastalSurf && CoastalSurf->Revision==revision) {
+ target.Colour=CoastalSurf->Input;target.Width=target.Height=WaterCoastalSurf::AtlasSide;
+ }
+ return target;
+}
+
+bool SdlGpuFrame::Coastal_Surf_Field_Due(uint64_t revision,double time) const
+{
+ if(!CoastalSurf || CoastalSurf->Revision!=revision) return false;
+ const auto action=CoastalSurf->Clock.Inspect(revision,time).action;
+ return action==WaterCoastalSurf::Action::Sample || action==WaterCoastalSurf::Action::GapDecay;
+}
+
+bool SdlGpuFrame::Prepare_Coastal_Surf(uint64_t revision,double time,const SdlTarget &field)
+{
+ return Prepare_Coastal_Surf_Impl(revision,time,field,false);
+}
+
+bool SdlGpuFrame::Prepare_Coastal_Surf_From_Ocean(uint64_t revision,double time)
+{
+ return Prepare_Coastal_Surf_Impl(revision,time,Coastal_Surf_Field_Target(revision),true);
+}
+
+bool SdlGpuFrame::Prepare_Coastal_Surf_Impl(uint64_t revision,double time,const SdlTarget &field,bool fromOcean)
+{
+ using namespace WaterCoastalSurf;
+ if(!CoastalSurf || !revision || CoastalSurf->Revision!=revision
+ || field.Colour!=CoastalSurf->Input || field.Depth || field.Width!=AtlasSide || field.Height!=AtlasSide) return false;
+ const Plan plan=CoastalSurf->Clock.Inspect(revision,time);
+ if(plan.action==Action::Invalid) return false;
+ if(plan.action==Action::None) return CoastalSurf->Clock.Commit(revision,plan);
+ const bool incident=fromOcean && (plan.action==Action::Sample || plan.action==Action::GapDecay);
+ if(incident) {
+ // This is the same float multiply used by the ordinary water draw. A stale,
+ // missing, or differently phased ocean must not advance source history.
+ const float phase=float(time)*WaterFftSampling::TimeScale;
+ if(!std::isfinite(phase) || !OceanReady || !Ocean || OceanTime!=phase
+ || !Ocean->Linear || !CoastalSurf->CreateIncident()) return false;
+ for(unsigned i=0;i<4;++i) if(!Ocean->Maps[i]) return false;
+ }
+ // Includes caller writes into Input and any earlier draws sampling the current State.
+ if((!Commands.empty() || !Uploads.empty()) && !Flush()) return false;
+ SDL_GPUCommandBuffer *commands=SDL_AcquireGPUCommandBuffer(GpuDevice);if(!commands) return false;
+ const unsigned reaction=(CoastalSurf->Active+1)%3,final=(CoastalSurf->Active+2)%3;
+ SDL_GPUTexture *inputs[5]={CoastalSurf->State[CoastalSurf->Active],CoastalSurf->Input,
+ CoastalSurf->Domain[1],CoastalSurf->Domain[2],CoastalSurf->Domain[3]};
+ const float parameters[4]={float(CoastalSurf->Count),float(plan.elapsed),float(CoastalSurf->Spacing),
+ plan.action==Action::Reset?2.0f:plan.action==Action::GapDecay?1.0f:0.0f};
+ // The producer output is sampled only after ending its attachment pass. Keeping
+ // all three passes in this command buffer makes failure/clock commitment atomic.
+ bool ok=!incident || CoastalSurf->IncidentPass(commands,Ocean->Maps,Ocean->Linear,float(time));
+ if(ok) ok=CoastalSurf->Pass(commands,0,CoastalSurf->State[reaction],inputs,5,parameters);
+ unsigned next=reaction;
+ if(ok && plan.action==Action::Sample) {
+ SDL_GPUTexture *sources[2]={CoastalSurf->State[reaction],CoastalSurf->Domain[4]};
+ ok=CoastalSurf->Pass(commands,1,CoastalSurf->State[final],sources,2,parameters);next=final;
+ }
+ if(!ok){SDL_CancelGPUCommandBuffer(commands);return false;}
+ const Uint64 started=SDL_GetTicksNS();
+ ok=SerializeSubmits?Submit(commands):Submit_Flush(commands);
+ FlushMs+=double(SDL_GetTicksNS()-started)/1.0e6;++Flushes;++FlushesTotal;
+ if(!ok) return false;
+ // Commit only after every GPU write is accepted. Earlier state stays addressable on failure.
+ if(!CoastalSurf->Clock.Commit(revision,plan)){CoastalSurf->Ready=false;return false;}
+ CoastalSurf->Active=next;CoastalSurf->Ready=true;++CoastalSurfUpdates;return true;
+}
+
+SDL_GPUTexture *SdlGpuFrame::Coastal_Surf_State(uint64_t revision) const
+{
+ return CoastalSurf && CoastalSurf->Ready && CoastalSurf->Revision==revision
+ ?CoastalSurf->State[CoastalSurf->Active]:NULL;
+}
+SDL_GPUTexture *SdlGpuFrame::Coastal_Surf_Domain(unsigned index,uint64_t revision) const
+{
+ return CoastalSurf && CoastalSurf->Revision==revision && index<5?CoastalSurf->Domain[index]:NULL;
+}
+SDL_GPUSampler *SdlGpuFrame::Coastal_Surf_Sampler(uint64_t revision) const
+{
+ return CoastalSurf && CoastalSurf->Revision==revision?CoastalSurf->Point:NULL;
+}
+double SdlGpuFrame::Coastal_Surf_Time(uint64_t revision) const
+{
+ return CoastalSurf && CoastalSurf->Ready && CoastalSurf->Revision==revision?CoastalSurf->Clock.SampledTime():0;
+}
+unsigned SdlGpuFrame::Coastal_Surf_Nodes(uint64_t revision) const
+{
+ return CoastalSurf && CoastalSurf->Revision==revision?CoastalSurf->Count:0;
+}
+
+// One global view allocation set, independent of the fixed-world history atlas.
+struct SdlGpuFrame::CoastalSurfViewResources
+{
+ SDL_GPUDevice *Device;
+ SDL_GPUTexture *Ids=NULL,*Weights=NULL,*Output=NULL;
+ SDL_GPUShader *Pixel=NULL;
+ SDL_GPUGraphicsPipeline *Pipeline=NULL;
+ SDL_GPUSampler *Linear=NULL;
+ WaterCoastalView::Mapping Mapping={};
+ std::vector<WaterCoastalSurf::Lookup> Lookups;
+ uint64_t Revision=0,HistoryUpdate=0;
+ double Level=0,Time=0;
+ bool Pending=true,Ready=false;
+ explicit CoastalSurfViewResources(SDL_GPUDevice *device):Device(device) {}
+ ~CoastalSurfViewResources() {
+ if(Pipeline)SDL_ReleaseGPUGraphicsPipeline(Device,Pipeline);
+ if(Pixel)SDL_ReleaseGPUShader(Device,Pixel);
+ if(Linear)SDL_ReleaseGPUSampler(Device,Linear);
+ if(Ids)SDL_ReleaseGPUTexture(Device,Ids);
+ if(Weights)SDL_ReleaseGPUTexture(Device,Weights);
+ if(Output)SDL_ReleaseGPUTexture(Device,Output);
+ }
+};
+
+static const char *Coastal_Surf_View_Pixel_Source()
+{
+ return R"VIEW(
+Texture2D<float4> Ids:register(t0,space2);
+Texture2D<float4> Weights:register(t1,space2);
+Texture2D<float4> State:register(t2,space2);
+Texture2D<float4> World:register(t3,space2);
+cbuffer ViewParameters:register(b0,space3){float4 Parameters;};
+float4 main(float4 position:SV_Position):SV_Target0 {
+ uint2 pixel=(uint2)position.xy;
+ float4 ids=Ids.Load(int3(pixel,0)),weights=Weights.Load(int3(pixel,0));
+ if(!all(isfinite(ids))||!all(isfinite(weights))||any(weights<0)||any(weights>1)
+ ||dot(weights,float4(1,1,1,1))>1.000001)return 0;
+ float2 moments=0;
+ [unroll]for(uint i=0;i<4;++i) {
+ float id=ids[i],weight=weights[i];
+ if(weight<=0)continue;
+ if(id<1||id>Parameters.x||id!=floor(id))continue;
+ uint at=(uint)id-1;int3 cell=int3(at%256,at/256,0);
+ float4 world=World.Load(cell),state=State.Load(cell);
+ if(!all(isfinite(world))||world.z!=Parameters.y||!all(isfinite(state))
+ ||state.x<0||state.x>16||state.y<0||state.y>1024
+ ||abs(state.z)>64||state.w< -1||state.w>1.2)continue;
+ // Missing, invalid and wrong-level contributions remain zero. Never
+ // normalize surviving weights or convert density into coverage here.
+ moments+=weight*state.xy;
+ }
+ return float4(moments,0,0);
+}
+)VIEW";
+}
+
+void SdlGpuFrame::Release_Coastal_Surf_View()
+{
+ if(!CoastalSurfView)return;
+ if(TargetSet && (CurrentTarget.Colour==CoastalSurfView->Ids
+ ||CurrentTarget.Colour==CoastalSurfView->Weights||CurrentTarget.Colour==CoastalSurfView->Output)) {
+ TargetSet=false;CurrentTarget={};
+ }
+ delete CoastalSurfView;CoastalSurfView=NULL;
+}
+
+bool SdlGpuFrame::Clear_Coastal_Surf_View()
+{
+ if((!Commands.empty()||!Uploads.empty())&&!Flush())return false;
+ Release_Coastal_Surf_View();return true;
+}
+
+bool SdlGpuFrame::Set_Coastal_Surf_View(uint64_t revision,const WaterShoreHistory::Mapping &mapping,
+ double level,const std::vector<WaterCoastalSurf::Lookup> &lookups)
+{
+ using namespace WaterCoastalSurf;
+ auto fail=[&](){if(CoastalSurfView)CoastalSurfView->Ready=false;return false;};
+ if(!CoastalSurf||!revision||CoastalSurf->Revision!=revision||!WaterCoastalView::ValidMapping(mapping)
+ ||!WaterCoastalView::ValidLevel(level)
+ ||lookups.size()!=size_t(mapping.widthPixels)*mapping.heightPixels)return fail();
+ for(const Lookup &lookup:lookups) {
+ if(!ValidLookup(lookup,CoastalSurf->Count))return fail();
+ for(unsigned i=0;i<4;++i)if(lookup.node[i]) {
+ // Validate against immutable serialized domain identity, not caller labels.
+ if(CoastalSurf->Payload[(lookup.node[i]-1)*4+2]!=float(level))return fail();
+ }
+ }
+ static_assert(sizeof(Lookup)==8*sizeof(uint32_t),"lookup has exactly eight scalar channels");
+ if(CoastalSurfView && CoastalSurfView->Revision==revision && CoastalSurfView->Level==level
+ && WaterCoastalView::SameMapping(CoastalSurfView->Mapping,mapping)
+ && CoastalSurfView->Lookups.size()==lookups.size()
+ && memcmp(CoastalSurfView->Lookups.data(),lookups.data(),lookups.size()*sizeof(Lookup))==0)return true;
+ // Allocate the accepted CPU copy before changing any existing cache metadata.
+ std::vector<Lookup> accepted=lookups;
+ const bool replace=!CoastalSurfView
+ ||CoastalSurfView->Mapping.widthPixels!=mapping.widthPixels
+ ||CoastalSurfView->Mapping.heightPixels!=mapping.heightPixels;
+ std::unique_ptr<CoastalSurfViewResources> next;
+ CoastalSurfViewResources *view=CoastalSurfView;
+ if(replace) {
+ next.reset(new CoastalSurfViewResources(GpuDevice));view=next.get();
+ SDL_GPUTextureCreateInfo ti={};ti.type=SDL_GPU_TEXTURETYPE_2D;
+ ti.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
+ ti.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET|SDL_GPU_TEXTUREUSAGE_SAMPLER;
+ ti.width=mapping.widthPixels;ti.height=mapping.heightPixels;ti.layer_count_or_depth=ti.num_levels=1;
+ view->Ids=SDL_CreateGPUTexture(GpuDevice,&ti);view->Weights=SDL_CreateGPUTexture(GpuDevice,&ti);
+ view->Output=SDL_CreateGPUTexture(GpuDevice,&ti);
+ if(!view->Ids||!view->Weights||!view->Output)return fail();
+ SDL_GPUSamplerCreateInfo si={};si.min_filter=si.mag_filter=SDL_GPU_FILTER_LINEAR;
+ si.mipmap_mode=SDL_GPU_SAMPLERMIPMAPMODE_NEAREST;
+ si.address_mode_u=si.address_mode_v=si.address_mode_w=SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
+ view->Linear=SDL_CreateGPUSampler(GpuDevice,&si);if(!view->Linear)return fail();
+ std::string error;std::vector<unsigned char> spirv;
+ if(!SDL3_Compile_HLSL_To_SPIRV(Coastal_Surf_View_Pixel_Source(),false,spirv,error))return fail();
+ unsigned samplers=0,uniforms=0;SDL3_Shader_Slots(spirv,false,samplers,uniforms);
+ if(samplers!=4||uniforms!=1)return fail();
+ view->Pixel=SDL3_Create_Shader(GpuDevice,spirv,false,error);if(!view->Pixel)return fail();
+ SDL_GPUColorTargetDescription colour={};colour.format=ti.format;
+ SDL_GPUGraphicsPipelineCreateInfo pi={};pi.vertex_shader=CoastalSurf->Vertex;pi.fragment_shader=view->Pixel;
+ pi.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;pi.rasterizer_state.cull_mode=SDL_GPU_CULLMODE_NONE;
+ pi.rasterizer_state.fill_mode=SDL_GPU_FILLMODE_FILL;
+ pi.target_info.color_target_descriptions=&colour;pi.target_info.num_color_targets=1;
+ view->Pipeline=SDL_CreateGPUGraphicsPipeline(GpuDevice,&pi);if(!view->Pipeline)return fail();
+ // Old CPU draws must retain the old view until submitted before its release.
+ if((!Commands.empty()||!Uploads.empty())&&!Flush())return fail();
+ }
+ view->Revision=revision;view->Level=level;view->Mapping=mapping;
+ view->Lookups.swap(accepted);view->Pending=true;view->Ready=false;
+ if(replace){Release_Coastal_Surf_View();CoastalSurfView=next.release();}
+ ++CoastalSurfViewSets;return true;
+}
+
+bool SdlGpuFrame::Prepare_Coastal_Surf_View(uint64_t revision)
+{
+ auto fail=[&](){if(CoastalSurfView)CoastalSurfView->Ready=false;return false;};
+ if(!CoastalSurfView||!CoastalSurf||!CoastalSurf->Ready||CoastalSurfView->Revision!=revision
+ ||CoastalSurf->Revision!=revision)return fail();
+ CoastalSurfViewResources &view=*CoastalSurfView;
+ if(view.Ready&&!view.Pending&&view.HistoryUpdate==CoastalSurfUpdates)return true;
+ if((!Commands.empty()||!Uploads.empty())&&!Flush())return fail();
+ SDL_GPUTexture *state=CoastalSurf->State[CoastalSurf->Active],*world=CoastalSurf->Domain[0];
+ if(!state||!world||view.Output==state||view.Output==world||view.Output==view.Ids||view.Output==view.Weights)return fail();
+ SDL_GPUTransferBuffer *transfer=NULL;
+ const Uint32 bytes=Uint32(view.Lookups.size()*4*sizeof(float));
+ if(view.Pending) {
+ SDL_GPUTransferBufferCreateInfo ti={};ti.usage=SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD;ti.size=bytes*2;
+ transfer=SDL_CreateGPUTransferBuffer(GpuDevice,&ti);if(!transfer)return fail();
+ float *mapped=static_cast<float *>(SDL_MapGPUTransferBuffer(GpuDevice,transfer,false));
+ if(!mapped){SDL_ReleaseGPUTransferBuffer(GpuDevice,transfer);return fail();}
+ for(size_t n=0;n<view.Lookups.size();++n)for(unsigned c=0;c<4;++c) {
+ mapped[n*4+c]=float(view.Lookups[n].node[c]);
+ mapped[view.Lookups.size()*4+n*4+c]=view.Lookups[n].weight[c];
+ }
+ SDL_UnmapGPUTransferBuffer(GpuDevice,transfer);
+ }
+ SDL_GPUCommandBuffer *commands=SDL_AcquireGPUCommandBuffer(GpuDevice);
+ auto cancel=[&](){if(commands)SDL_CancelGPUCommandBuffer(commands);if(transfer)SDL_ReleaseGPUTransferBuffer(GpuDevice,transfer);return fail();};
+ if(!commands)return cancel();
+ if(view.Pending) {
+ SDL_GPUCopyPass *copy=SDL_BeginGPUCopyPass(commands);if(!copy)return cancel();
+ for(unsigned i=0;i<2;++i) {
+ SDL_GPUTextureTransferInfo upload={};upload.transfer_buffer=transfer;upload.offset=i*bytes;
+ upload.pixels_per_row=view.Mapping.widthPixels;upload.rows_per_layer=view.Mapping.heightPixels;
+ SDL_GPUTextureRegion region={};region.texture=i?view.Weights:view.Ids;
+ region.w=view.Mapping.widthPixels;region.h=view.Mapping.heightPixels;region.d=1;
+ SDL_UploadToGPUTexture(copy,&upload,&region,false);
+ }
+ SDL_EndGPUCopyPass(copy);
+ }
+ SDL_GPUColorTargetInfo target={};target.texture=view.Output;
+ target.load_op=SDL_GPU_LOADOP_DONT_CARE;target.store_op=SDL_GPU_STOREOP_STORE;
+ SDL_GPURenderPass *pass=SDL_BeginGPURenderPass(commands,&target,1,NULL);if(!pass)return cancel();
+ SDL_BindGPUGraphicsPipeline(pass,view.Pipeline);
+ SDL_GPUTextureSamplerBinding bindings[4]={{view.Ids,CoastalSurf->Point},{view.Weights,CoastalSurf->Point},
+ {state,CoastalSurf->Point},{world,CoastalSurf->Point}};
+ SDL_BindGPUFragmentSamplers(pass,0,bindings,4);
+ const SDL_GPUViewport viewport={0,0,float(view.Mapping.widthPixels),float(view.Mapping.heightPixels),0,1};
+ SDL_SetGPUViewport(pass,&viewport);
+ const float parameters[4]={float(CoastalSurf->Count),float(view.Level),0,0};
+ SDL_PushGPUFragmentUniformData(commands,0,parameters,sizeof(parameters));
+ SDL_DrawGPUPrimitives(pass,3,1,0,0);SDL_EndGPURenderPass(pass);
+ const Uint64 started=SDL_GetTicksNS();
+ const bool submitted=SerializeSubmits?Submit(commands):Submit_Flush(commands);
+ FlushMs+=double(SDL_GetTicksNS()-started)/1.0e6;++Flushes;++FlushesTotal;
+ if(transfer)SDL_ReleaseGPUTransferBuffer(GpuDevice,transfer);
+ if(!submitted)return fail();
+ view.Pending=false;view.Ready=true;view.HistoryUpdate=CoastalSurfUpdates;
+ view.Time=CoastalSurf->Clock.SampledTime();++CoastalSurfViewUpdates;return true;
+}
+
+SDL_GPUTexture *SdlGpuFrame::Coastal_Surf_View(uint64_t revision,double level) const
+{
+ return CoastalSurfView&&CoastalSurf&&CoastalSurf->Ready&&CoastalSurf->Revision==revision
+ &&CoastalSurfView->Ready&&!CoastalSurfView->Pending&&CoastalSurfView->Revision==revision
+ &&CoastalSurfView->Level==level&&CoastalSurfView->HistoryUpdate==CoastalSurfUpdates?CoastalSurfView->Output:NULL;
+}
+SDL_GPUSampler *SdlGpuFrame::Coastal_Surf_View_Sampler(uint64_t revision,double level) const
+{
+ return Coastal_Surf_View(revision,level)?CoastalSurfView->Linear:NULL;
+}
+double SdlGpuFrame::Coastal_Surf_View_Time(uint64_t revision,double level) const
+{
+ return Coastal_Surf_View(revision,level)?CoastalSurfView->Time:0;
+}
+
+void SdlGpuFrame::Invalidate_Water_Snapshots(SDL_GPUTexture *colour, SDL_GPUTexture *depth)
+{
+ for (size_t i = 0; i < WaterSnapshots.size(); ++i) {
+ WaterSnapshot &snapshot = WaterSnapshots[i];
+ if ((colour && snapshot.Source.Colour == colour) || (depth && snapshot.Source.Depth == depth)) {
+ snapshot.Ready = false;
+ }
+ }
+}
+
+void SdlGpuFrame::Refresh_Water_Snapshots()
+{
+ ++WaterFrame;
+ for (size_t i = 0; i < WaterSnapshots.size(); ++i) WaterSnapshots[i].Ready = false;
+}
+
+SdlGpuFrame::WaterSnapshot *SdlGpuFrame::Water_Snapshot(const SdlTarget &source)
+{
+ if (source.Width == 0 || source.Height == 0 || !source.Colour) return NULL;
+ WaterSnapshot *snapshot = NULL;
+ for (size_t i = 0; i < WaterSnapshots.size(); ++i) {
+ WaterSnapshot &candidate = WaterSnapshots[i];
+ 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) {
+ WaterSnapshot fresh = {};
+ fresh.Source = source;
+ SDL_GPUTextureCreateInfo info;
+ SDL_zero(info);
+ info.type = SDL_GPU_TEXTURETYPE_2D;
+ info.format = BACK_BUFFER_FORMAT;
+ info.usage = SDL_GPU_TEXTUREUSAGE_COLOR_TARGET | SDL_GPU_TEXTUREUSAGE_SAMPLER;
+ info.width = source.Width; info.height = source.Height;
+ info.layer_count_or_depth = 1; info.num_levels = 1;
+ info.sample_count = SDL_GPU_SAMPLECOUNT_1;
+ fresh.Colour = SDL_CreateGPUTexture(GpuDevice, &info);
+ if (!fresh.Colour) return NULL;
+ if (source.Depth && DepthSampleable && Create_Water_Depth_Pipeline()) {
+ info.format = SDL_GPU_TEXTUREFORMAT_R32_FLOAT;
+ fresh.Depth = SDL_CreateGPUTexture(GpuDevice, &info);
+ }
+ if (WaterSnapshots.size() == 8) {
+ // The cache is bounded even when effects continually allocate intermediate targets. Recorded
+ // draws can keep using the retired textures until this batch has been submitted.
+ size_t oldest = 0;
+ for (size_t i = 1; i < WaterSnapshots.size(); ++i)
+ if (WaterSnapshots[i].UsedFrame < WaterSnapshots[oldest].UsedFrame) oldest = i;
+ if (WaterSnapshots[oldest].Colour) DeadTextures.push_back(WaterSnapshots[oldest].Colour);
+ if (WaterSnapshots[oldest].Depth) DeadTextures.push_back(WaterSnapshots[oldest].Depth);
+ WaterSnapshots[oldest] = fresh;
+ snapshot = &WaterSnapshots[oldest];
+ }
+ else {
+ WaterSnapshots.push_back(fresh);
+ snapshot = &WaterSnapshots.back();
+ }
+ }
+ if (!snapshot->Ready) {
+ const int32_t rectangle[4] = { 0, 0, (int32_t)source.Width, (int32_t)source.Height };
+ Record_Blit(source.Colour, rectangle, snapshot->Colour, rectangle, false);
+ if (snapshot->Depth) {
+ Command command = {};
+ command.IsDepthSnapshot = true;
+ command.BlitSource = source.Depth;
+ command.BlitDestination = snapshot->Depth;
+ memcpy(command.Rect, rectangle, sizeof(rectangle));
+ Commands.push_back(command);
+ }
+ snapshot->CaptureSerial = ++WaterCaptureSerial;
+ snapshot->Ready = true;
+ }
+ snapshot->UsedFrame = WaterFrame;
+ return snapshot;
+}
+
+SDL_GPUTexture *SdlGpuFrame::Water_Background(const SdlTarget &source)
+{
+ WaterSnapshot *snapshot = Water_Snapshot(source);
+ return snapshot ? snapshot->Colour : NULL;
+}
+
+SDL_GPUTexture *SdlGpuFrame::Water_Depth(const SdlTarget &source)
+{
+ WaterSnapshot *snapshot = Water_Snapshot(source);
+ return snapshot ? snapshot->Depth : NULL;
+}
+
+SDL_GPUTexture *SdlGpuFrame::Ready_Water_Depth(const SdlTarget &source, uint64_t &serial) const
+{
+ serial = 0;
+ for (const WaterSnapshot &snapshot : WaterSnapshots) {
+ if (snapshot.Ready && snapshot.Depth && snapshot.Source.Colour == source.Colour
+ && snapshot.Source.Depth == source.Depth && snapshot.Source.Width == source.Width
+ && snapshot.Source.Height == source.Height) {
+ serial = snapshot.CaptureSerial;
+ return snapshot.Depth;
+ }
+ }
+ return NULL;
+}
+
+bool SdlGpuFrame::Create_Water_Depth_Pipeline()
+{
+ if (WaterDepthPipeline && WaterDepthSampler) return true;
+ std::string log;
+ if (!WaterDepthVertex) {
+ std::vector<unsigned char> spirv;
+ if (!SDL3_Compile_HLSL_To_SPIRV(GAMMA_VERTEX_HLSL, true, spirv, log)
+ || !(WaterDepthVertex = SDL3_Create_Shader(GpuDevice, spirv, true, log))) {
+ fprintf(stderr, "SdlGpuFrame: water depth vertex: %s\n", log.c_str());
+ return false;
+ }
+ }
+ if (!WaterDepthPixel) {
+ std::vector<unsigned char> spirv;
+ if (!SDL3_Compile_HLSL_To_SPIRV(WATER_DEPTH_PIXEL_HLSL, false, spirv, log)
+ || !(WaterDepthPixel = SDL3_Create_Shader(GpuDevice, spirv, false, log))) {
+ fprintf(stderr, "SdlGpuFrame: water depth pixel: %s\n", log.c_str());
+ return false;
+ }
+ }
+ if (!WaterDepthPipeline) {
+ SDL_GPUColorTargetDescription target = {};
+ target.format = SDL_GPU_TEXTUREFORMAT_R32_FLOAT;
+ SDL_GPUGraphicsPipelineCreateInfo info = {};
+ info.vertex_shader = WaterDepthVertex;
+ info.fragment_shader = WaterDepthPixel;
+ 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 = &target;
+ info.target_info.num_color_targets = 1;
+ WaterDepthPipeline = SDL_CreateGPUGraphicsPipeline(GpuDevice, &info);
+ }
+ if (!WaterDepthSampler) {
+ 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;
+ WaterDepthSampler = SDL_CreateGPUSampler(GpuDevice, &sampler);
+ }
+ if (!WaterDepthPipeline || !WaterDepthSampler)
+ fprintf(stderr, "SdlGpuFrame: water depth resolve: %s\n", SDL_GetError());
+ return WaterDepthPipeline && WaterDepthSampler;
+}
+
+bool SdlGpuFrame::Resolve_Water_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, WaterDepthPipeline);
+ const SDL_GPUTextureSamplerBinding binding = { source, WaterDepthSampler };
+ 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 +1209,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_Water_Snapshots(colour ? target.Colour : NULL, depth ? target.Depth : NULL);
if (!colour && !depth && !stencil) {
return;
}
@@ -579,6 +1533,7 @@ bool SdlGpuFrame::Copy_To_Front(SDL_GPUCommandBuffer * commands)
bool SdlGpuFrame::Present(const uint16_t (*ramp)[256])
{
+ Refresh_Water_Snapshots();
SDL_GPUCommandBuffer * commands = SDL_AcquireGPUCommandBuffer(GpuDevice);
if (commands == NULL) {
return false;
@@ -643,6 +1598,7 @@ bool SdlGpuFrame::Present(const uint16_t (*ramp)[256])
bool SdlGpuFrame::Present_To(SDL_GPUTexture * target, unsigned int width, unsigned int height,
const uint16_t (*ramp)[256])
{
+ Refresh_Water_Snapshots();
SDL_GPUCommandBuffer * commands = SDL_AcquireGPUCommandBuffer(GpuDevice);
if (commands == NULL) {
return false;
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrame.h b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrame.h
index 6bca8483d..e5ca7a67c 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrame.h
+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrame.h
@@ -48,6 +48,8 @@ struct SDL_GPUSampler;
struct SDL_GPUShader;
struct SDL_GPUTexture;
struct SDL_Window;
+namespace WaterCoastalSurf { struct Node; struct Lookup; }
+namespace WaterShoreHistory { struct Mapping; }
/// 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).
@@ -62,7 +64,7 @@ struct SdlTarget
/// One draw as the flush replays it, everything by value. The device's resolve fills it.
struct SdlRecordedDraw
{
- enum { MAXIMUM_SAMPLERS = 8 };
+ enum { MAXIMUM_SAMPLERS = 16, MAXIMUM_UNIFORM_SLOTS = 4, WATER_PIXEL_BLOCKS = 3 };
SDL_GPUGraphicsPipeline * Pipeline;
SDL_GPUBuffer * VertexBuffer; ///< a GPU copy, or null for the batch's staging stream
uint32_t VertexOffset; ///< bytes into it
@@ -74,11 +76,18 @@ struct SdlRecordedDraw
int32_t BaseVertex;
uint32_t VertexConstants; ///< offsets into the batch's constant bytes (Constants)
uint32_t VertexConstantsSize;
+ uint32_t VertexWaterConstants; ///< water-only b1; aliases this draw's immutable pixel constants
+ uint32_t VertexWaterConstantsSize;
uint32_t PixelConstants;
uint32_t PixelConstantsSize;
+ uint32_t PixelWaterConstants[WATER_PIXEL_BLOCKS]; ///< immutable modern-water-only PS b1..b3
+ uint32_t PixelWaterConstantsSize[WATER_PIXEL_BLOCKS]; ///< zero for every other draw
uint32_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 it
int32_t Scissor[4]; ///< x, y, width, height
uint32_t StencilReference;
@@ -143,8 +152,8 @@ public:
void Queue_Texture_Upload(SDL_GPUTexture * texture, unsigned int level, unsigned int width, unsigned int height,
uint32_t upload_offset);
/// A constant block's bytes, for stage 0 (vertex) or 1 (pixel); the same bytes as that stage's block
- /// before share its offset, so the flush pushes only a change.
- uint32_t Constants(unsigned int stage, const void * bytes, uint32_t size);
+ /// before at the same slot share its offset, so the flush pushes only a change.
+ uint32_t Constants(unsigned int stage, const void * bytes, uint32_t size, unsigned int slot=0);
void Record_Draw(const SdlRecordedDraw & draw);
/// A GPU object nothing will record again, released once the batch that may use it has gone.
void Release_After_Batch(SDL_GPUTexture * texture, SDL_GPUBuffer * buffer);
@@ -155,6 +164,8 @@ public:
bool Batch_Is_Full();
/// The depth-stencil's SDL_GPUTextureFormat. Every pass has it attached.
unsigned int Depth_Format() const { return DepthFormat; }
+ /// Sampling is optional on older devices. The selected depth format supports this complete usage.
+ unsigned int Depth_Usage() const;
/// Flush, then the back buffer to the window through the gamma ramp (null: none, a straight blit).
bool Present(const uint16_t (*ramp)[256]);
@@ -207,6 +218,61 @@ public:
/// What the last Present showed: the back buffer is copied here at each Present, so the front buffer
/// (GetFrontBufferData) is the presented picture whenever it is asked for (A3d).
SDL_GPUTexture * Front_Copy() const { return FrontCopy; }
+ /// Opaque scene before the first water draw, cached per actual colour/depth target and frame.
+ SDL_GPUTexture * Water_Background(const SdlTarget &source);
+ /// Device depth (0..1), resolved into an independent R32_FLOAT texture between render passes.
+ /// Null if sampled depth is unsupported. Never aliases the depth attachment used by water.
+ SDL_GPUTexture * Water_Depth(const SdlTarget &source);
+ /// Read-only lookup; never captures after water/overlays have already changed the scene.
+ SDL_GPUTexture * Ready_Water_Depth(const SdlTarget &source, uint64_t &serial) const;
+ /// Lazy, GPU-only Phillips spectrum/IFFT. Previous draws finish recording before maps change;
+ /// repeated paused times reuse the same field. Failure leaves the analytic water fallback usable.
+ bool Prepare_Ocean(float time);
+ SDL_GPUTexture * Ocean_Map(unsigned int index) const;
+ SDL_GPUSampler * Ocean_Sampler() const;
+ uint64_t Ocean_Updates() const { return OceanUpdates; }
+
+ /// Bounded GPU coastal history; callers install one immutable graph across all levels.
+ /// Same revision with changed bytes is rejected. Empty graphs clear the feature.
+ bool Install_Coastal_Surf(uint64_t revision,const std::vector<WaterCoastalSurf::Node> &nodes,double spacing);
+ /// Known-format RGBA32F 256x256 target owned by this frame. The caller renders the current
+ /// incident Field here, then supplies this exact target to Prepare. No arbitrary native
+ /// texture metadata is trusted; SDL offers no public texture format/dimension query.
+ SdlTarget Coastal_Surf_Field_Target(uint64_t revision) const;
+ /// Render the incident Field only for Sample/GapDecay. First/reset Prepare clears to
+ /// density=age=height=0, rate=-1; it consumes no field. Call Prepare even when not due
+ /// to observe clock advances/rewinds without repeating GPU work at paused times.
+ bool Coastal_Surf_Field_Due(uint64_t revision,double water_time) const;
+ bool Prepare_Coastal_Surf(uint64_t revision,double water_time,const SdlTarget &field);
+ /// Production path: when due, sample only an already prepared matching-phase ocean,
+ /// then record incident/reaction/diffusion atomically. Never updates the FFT itself.
+ /// On false, caller must disable coastal composition for this draw, not use stale data.
+ bool Prepare_Coastal_Surf_From_Ocean(uint64_t revision,double water_time);
+ bool Clear_Coastal_Surf();
+ /// Borrowed handles remain valid until Clear or a different successful Install. Prepare
+ /// can rotate the state handle; resolve it after Prepare for each immutable recorded draw.
+ SDL_GPUTexture * Coastal_Surf_State(uint64_t revision) const;
+ /// Domain indices: 0 world,1 coast,2 surface,3 admission,4 neighbour IDs (index+1).
+ SDL_GPUTexture * Coastal_Surf_Domain(unsigned index,uint64_t revision) const;
+ SDL_GPUSampler * Coastal_Surf_Sampler(uint64_t revision) const;
+ double Coastal_Surf_Time(uint64_t revision) const;
+ unsigned Coastal_Surf_Nodes(uint64_t revision) const;
+ uint64_t Coastal_Surf_Updates() const { return CoastalSurfUpdates; }
+ uint64_t Coastal_Surf_Installs() const { return CoastalSurfInstalls; }
+ /// One active camera-view lookup across all water levels. Set caches/validates CPU
+ /// IDs and weights; Prepare uploads changed lookup and composes density/age moments
+ /// from the current history in one submission. Missing weights stay zero.
+ bool Set_Coastal_Surf_View(uint64_t revision,const WaterShoreHistory::Mapping &mapping,
+ double level,const std::vector<WaterCoastalSurf::Lookup> &lookups);
+ bool Prepare_Coastal_Surf_View(uint64_t revision);
+ bool Clear_Coastal_Surf_View();
+ /// Only current-state, successfully submitted output is exposed; B/A are zero.
+ SDL_GPUTexture *Coastal_Surf_View(uint64_t revision,double level) const;
+ SDL_GPUSampler *Coastal_Surf_View_Sampler(uint64_t revision,double level) const;
+ double Coastal_Surf_View_Time(uint64_t revision,double level) const;
+ uint64_t Coastal_Surf_View_Sets() const { return CoastalSurfViewSets; }
+ uint64_t Coastal_Surf_View_Updates() const { return CoastalSurfViewUpdates; }
+
unsigned int Width() const { return BackWidth; }
unsigned int Height() const { return BackHeight; }
/// The back buffer's format, and so what a Present_To target has to be.
@@ -269,6 +335,46 @@ private:
SDL_GPUTexture * BackBuffer;
SDL_GPUTexture * DepthStencil;
SDL_GPUTexture * FrontCopy; ///< the last presented picture
+ struct WaterSnapshot
+ {
+ SdlTarget Source;
+ SDL_GPUTexture *Colour, *Depth;
+ bool Ready;
+ uint64_t UsedFrame;
+ uint64_t CaptureSerial;
+ };
+ std::vector<WaterSnapshot> WaterSnapshots; // at most eight; replaced resources retire with their batch
+ uint64_t WaterFrame = 0;
+ uint64_t WaterCaptureSerial = 0;
+ bool DepthSampleable = false;
+ SDL_GPUShader *WaterDepthVertex = NULL, *WaterDepthPixel = NULL;
+ SDL_GPUGraphicsPipeline *WaterDepthPipeline = NULL;
+ SDL_GPUSampler *WaterDepthSampler = NULL;
+ struct OceanResources;
+ OceanResources *Ocean = NULL;
+ bool OceanFailed = false, OceanReady = false;
+ float OceanTime = 0;
+ uint64_t OceanUpdates = 0;
+ bool Create_Ocean();
+ void Release_Ocean();
+ bool Fail_Ocean(const char *reason);
+
+ struct CoastalSurfResources;
+ CoastalSurfResources *CoastalSurf=NULL;
+ uint64_t CoastalSurfUpdates=0,CoastalSurfInstalls=0;
+ void Release_Coastal_Surf();
+ bool Prepare_Coastal_Surf_Impl(uint64_t revision,double time,const SdlTarget &field,bool from_ocean);
+ struct CoastalSurfViewResources;
+ CoastalSurfViewResources *CoastalSurfView=NULL;
+ uint64_t CoastalSurfViewSets=0,CoastalSurfViewUpdates=0;
+ void Release_Coastal_Surf_View();
+
+ WaterSnapshot *Water_Snapshot(const SdlTarget &source);
+ void Invalidate_Water_Snapshots(SDL_GPUTexture *colour, SDL_GPUTexture *depth);
+ void Refresh_Water_Snapshots();
+ bool Create_Water_Depth_Pipeline();
+ bool Resolve_Water_Depth(struct SDL_GPUCommandBuffer *commands, SDL_GPUTexture *source,
+ SDL_GPUTexture *destination, unsigned int width, unsigned int height);
bool Copy_To_Front(struct SDL_GPUCommandBuffer * commands);
unsigned int DepthFormat; ///< an SDL_GPUTextureFormat: D24S8 where there is one, else D32S8
unsigned int BackWidth;
@@ -283,6 +389,7 @@ private:
int32_t Rect[4]; ///< x, y, width, height
uint32_t Target; ///< into Targets: where a clear or draw goes
bool IsBlit; ///< a copy between textures, Rect to BlitRect
+ bool IsDepthSnapshot; ///< sampled depth to R32_FLOAT, with neither scene attachment bound
SDL_GPUTexture * BlitSource;
SDL_GPUTexture * BlitDestination;
int32_t BlitRect[4];
@@ -310,7 +417,7 @@ private:
std::vector<ArenaByte> StreamBytes;
std::vector<ArenaByte> UploadBytes;
std::vector<ArenaByte> ConstantBytes;
- uint32_t LastConstants[2], LastConstantsSize[2];
+ uint32_t LastConstants[2][SdlRecordedDraw::MAXIMUM_UNIFORM_SLOTS], LastConstantsSize[2][SdlRecordedDraw::MAXIMUM_UNIFORM_SLOTS];
std::vector<Upload> Uploads;
std::vector<SDL_GPUTexture *> DeadTextures;
std::vector<SDL_GPUBuffer *> DeadBuffers;
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrameBatch.cpp b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrameBatch.cpp
index fb824ca26..3b2e54b0d 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrameBatch.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrameBatch.cpp
@@ -96,15 +96,16 @@ void SdlGpuFrame::Queue_Texture_Upload(SDL_GPUTexture * texture, unsigned int le
Uploads.push_back(upload);
}
-uint32_t SdlGpuFrame::Constants(unsigned int stage, const void * bytes, uint32_t size)
+uint32_t SdlGpuFrame::Constants(unsigned int stage, const void * bytes, uint32_t size, unsigned int slot)
{
- if (LastConstantsSize[stage] == size && memcmp(&ConstantBytes[LastConstants[stage]], bytes, size) == 0) {
- return LastConstants[stage];
+ SDL_assert(stage<2 && slot<SdlRecordedDraw::MAXIMUM_UNIFORM_SLOTS && bytes!=NULL && size>0);
+ if (LastConstantsSize[stage][slot] == size && memcmp(&ConstantBytes[LastConstants[stage][slot]], bytes, size) == 0) {
+ return LastConstants[stage][slot];
}
uint32_t offset = 0;
memcpy(grow(ConstantBytes, size, offset), bytes, size);
- LastConstants[stage] = offset;
- LastConstantsSize[stage] = size;
+ LastConstants[stage][slot] = offset;
+ LastConstantsSize[stage][slot] = size;
return offset;
}
@@ -114,6 +115,8 @@ void SdlGpuFrame::Clear_Rect(int x, int y, int width, int height, bool colour, b
if ((!colour && !depth && !stencil) || width <= 0 || height <= 0) {
return;
}
+ const SdlTarget target = TargetSet ? CurrentTarget : Back_Buffer_Target();
+ Invalidate_Water_Snapshots(colour ? target.Colour : NULL, depth ? target.Depth : NULL);
Command command;
memset(&command, 0, sizeof(command));
command.IsRect = true;
@@ -204,13 +207,25 @@ 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) {
+ // Forget source identities before SDL can recycle their handles. A queued snapshot/draw keeps
+ // its textures alive through the same submission; SDL retires them after GPU completion.
+ for (size_t i = WaterSnapshots.size(); i-- > 0; ) {
+ const WaterSnapshot &snapshot = WaterSnapshots[i];
+ if (snapshot.Source.Colour == texture || snapshot.Source.Depth == texture) {
+ if (snapshot.Colour) DeadTextures.push_back(snapshot.Colour);
+ if (snapshot.Depth) DeadTextures.push_back(snapshot.Depth);
+ WaterSnapshots.erase(WaterSnapshots.begin() + i);
+ }
+ }
+ DeadTextures.push_back(texture);
+ }
if (buffer != NULL) DeadBuffers.push_back(buffer);
}
bool SdlGpuFrame::Batch_Is_Full()
{
- if (StreamBytes.size() + UploadBytes.size() > BATCH_LIMIT) {
+ if (StreamBytes.size() + UploadBytes.size() + ConstantBytes.size() > BATCH_LIMIT) {
return true;
}
if (BatchDrawLimit > 0 && Draws.size() >= BatchDrawLimit) {
@@ -228,7 +243,7 @@ void SdlGpuFrame::End_Batch()
StreamBytes.clear();
UploadBytes.clear();
ConstantBytes.clear();
- LastConstants[0] = LastConstants[1] = LastConstantsSize[0] = LastConstantsSize[1] = 0;
+ memset(LastConstants,0,sizeof(LastConstants));memset(LastConstantsSize,0,sizeof(LastConstantsSize));
Uploads.clear();
// The batch that could use these has been submitted: SDL keeps each until the GPU is done with it.
for (size_t i = 0; i < DeadTextures.size(); ++i) SDL_ReleaseGPUTexture(GpuDevice, DeadTextures[i]);
@@ -385,7 +400,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 +416,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_Water_Snapshots(destination, NULL);
Command command;
memset(&command, 0, sizeof(command));
command.IsBlit = true;
@@ -429,20 +445,23 @@ bool SdlGpuFrame::Record_Passes(SDL_GPUCommandBuffer * commands, SDL_GPUBuffer *
// What the pass has bound, to bind only a change. Pushed uniforms outlive a pass (SDL3 keeps them for
// the rest of the command buffer), so those are tracked for the whole batch.
const SdlRecordedDraw * last = NULL;
- uint32_t pushed_vertex = 0xFFFFFFFFu, pushed_pixel = 0xFFFFFFFFu;
+ uint32_t pushed_vertex = 0xFFFFFFFFu, pushed_water_vertex = 0xFFFFFFFFu, pushed_pixel = 0xFFFFFFFFu;
+ uint32_t pushed_water_pixel[SdlRecordedDraw::WATER_PIXEL_BLOCKS];
+ memset(pushed_water_pixel,0xFF,sizeof(pushed_water_pixel));
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 +473,11 @@ bool SdlGpuFrame::Record_Passes(SDL_GPUCommandBuffer * commands, SDL_GPUBuffer *
if (end) {
break;
}
+ if (command->IsDepthSnapshot) {
+ if (!Resolve_Water_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);
@@ -512,7 +536,8 @@ bool SdlGpuFrame::Record_Passes(SDL_GPUCommandBuffer * commands, SDL_GPUBuffer *
SDL_DrawGPUPrimitives(pass, 3, 1, 0, 0);
// Everything the draws set is the clear's now: the next draw binds it all again.
last = NULL;
- pushed_vertex = pushed_pixel = 0xFFFFFFFFu;
+ pushed_vertex = pushed_water_vertex = pushed_pixel = 0xFFFFFFFFu;
+ memset(pushed_water_pixel,0xFF,sizeof(pushed_water_pixel));
continue;
}
const SdlRecordedDraw & draw = Draws[Commands[i].Draw];
@@ -558,14 +583,34 @@ 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;
}
+ if (draw.VertexWaterConstantsSize != 0 && draw.VertexWaterConstants != pushed_water_vertex) {
+ SDL_PushGPUVertexUniformData(commands, 1, &ConstantBytes[draw.VertexWaterConstants], draw.VertexWaterConstantsSize);
+ pushed_water_vertex = draw.VertexWaterConstants;
+ }
if (draw.PixelConstantsSize != 0 && draw.PixelConstants != pushed_pixel) {
SDL_PushGPUFragmentUniformData(commands, 0, &ConstantBytes[draw.PixelConstants], draw.PixelConstantsSize);
pushed_pixel = draw.PixelConstants;
}
+ for(unsigned block=0;block<SdlRecordedDraw::WATER_PIXEL_BLOCKS;++block) {
+ if(draw.PixelWaterConstantsSize[block]!=0 && draw.PixelWaterConstants[block]!=pushed_water_pixel[block]) {
+ SDL_PushGPUFragmentUniformData(commands,block+1,&ConstantBytes[draw.PixelWaterConstants[block]],draw.PixelWaterConstantsSize[block]);
+ pushed_water_pixel[block]=draw.PixelWaterConstants[block];
+ }
+ }
if (draw.IndexSize != 0) {
SDL_DrawGPUIndexedPrimitives(pass, draw.Count, 1, draw.First, draw.BaseVertex, 0);
}
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlProgramCache.cpp b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlProgramCache.cpp
index 1a08bd6e6..dcad13e10 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlProgramCache.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlProgramCache.cpp
@@ -24,6 +24,9 @@
#include "engineshader.h"
#include "ffshader.h"
#include "ffvertex.h"
+#include "sdl3target.h"
+#include "Platform/WaterFftSampling.h"
+#include "Platform/WaterShoreOverlay.h"
#include <SDL3/SDL.h>
@@ -217,6 +220,28 @@ const SdlProgram &SdlProgramCache::Vertex_Program(const VertexPipelineDescriptio
return made;
}
+const SdlProgram &SdlProgramCache::Water_Vertex_Program(const VertexPipelineDescription &description)
+{
+ if (SdlProgram *found = WaterVertexByBytes.Find(&description, sizeof(description))) {
+ ++found->Uses;
+ return *found;
+ }
+ const std::string key = "water-fft:" + VertexShader_Key(description);
+ std::map<std::string, SdlProgram>::iterator existing = VertexPrograms.find(key);
+ if (existing != VertexPrograms.end()) {
+ ++existing->second.Uses;
+ WaterVertexByBytes.Add(&description, sizeof(description), &existing->second);
+ return existing->second;
+ }
+ std::string hlsl;
+ const bool generated = !description.LightingEnabled
+ && VertexShader_Generate(description, VERTEX_SHADER_TARGET_D3D11, hlsl)
+ && WaterFftSampling::WrapVertex(hlsl) && SDL3_Shader_Retarget(hlsl, true);
+ const SdlProgram &made = Make(VertexPrograms, key, generated, hlsl, true);
+ WaterVertexByBytes.Add(&description, sizeof(description), &VertexPrograms[key]);
+ return made;
+}
+
const SdlProgram &SdlProgramCache::Engine_Vertex_Program(int program)
{
if (SdlProgram *found = EngineVertexByBytes.Find(&program, sizeof(program))) {
@@ -283,3 +308,21 @@ const SdlProgram &SdlProgramCache::Pixel_Program(const CombinerDescription &desc
PixelByBytes.Add(&description, sizeof(description), &PixelPrograms[key]);
return made;
}
+
+// Only an explicit authored-track draw tag may select this optional variant.
+const SdlProgram &SdlProgramCache::Shore_Pixel_Program(const CombinerDescription &description)
+{
+ if (SdlProgram *found=ShorePixelByBytes.Find(&description,sizeof(description))) {
+ ++found->Uses;return *found;
+ }
+ const std::string key="shore-overlay:"+CombinerShader_Key(description);
+ std::string hlsl;
+ bool generated=!description.ShadowReceiving && !description.SoftParticle && !description.DrawEffect
+ && !description.SmokeGlow && description.StageCount<=2
+ && CombinerShader_Generate(description,COMBINER_SHADER_TARGET_D3D11,hlsl)
+ && WaterShoreOverlay::WrapPixel(hlsl);
+ if(generated) generated=SDL3_Shader_Retarget(hlsl,false);
+ const SdlProgram &made=Make(PixelPrograms,key,generated,hlsl,false);
+ ShorePixelByBytes.Add(&description,sizeof(description),&PixelPrograms[key]);
+ return made;
+}
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlProgramCache.h b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlProgramCache.h
index f4524a4d6..5f5c097a7 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlProgramCache.h
+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlProgramCache.h
@@ -70,7 +70,10 @@ public:
/// The program for the description, made the first time it is asked for. Never null: a refusal
/// comes back with a null Shader and its Refusal.
const SdlProgram &Vertex_Program(const VertexPipelineDescription &description);
+ /// Water-only GPU displacement, retaining the generated transform/fog/shroud path.
+ const SdlProgram &Water_Vertex_Program(const VertexPipelineDescription &description);
const SdlProgram &Pixel_Program(const CombinerDescription &description);
+ const SdlProgram &Shore_Pixel_Program(const CombinerDescription &description);
/// One of the engine's own programs (A3e), from D3's transcription (engineshader.cpp), keyed as the
/// Direct3D 11 backend keys it: the name, and for a pixel program the alpha test and fog written into
/// it. A refusal for a program with no transcription, or of the other stage.
@@ -105,7 +108,7 @@ private:
SdlProgram *Last = NULL;
size_t Entries = 0;
};
- ByBytes VertexByBytes, PixelByBytes, EngineVertexByBytes, EnginePixelByBytes;
+ ByBytes VertexByBytes, PixelByBytes, EngineVertexByBytes, EnginePixelByBytes, WaterVertexByBytes, ShorePixelByBytes;
SDL_GPUDevice *Device;
std::map<std::string, SdlProgram> VertexPrograms;
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlResourceMirror.cpp b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlResourceMirror.cpp
index 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 d
SDL_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/W3DParticleSys.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp
index d9d5b4dce..ba84bb73f 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp
@@ -39,6 +39,7 @@
#include "W3DDevice/GameClient/W3DSnow.h"
#include "W3DDevice/GameClient/W3DScene.h"
#include "W3DDevice/GameClient/W3DDynamicLight.h"
+#include "W3DDevice/GameClient/W3DWater.h"
#include "WW3D2/camera.h"
#include "W3DDevice/GameClient/W3DSmoothMotion.h"
#include "WW3D2/dx8wrapper.h"
@@ -50,6 +51,9 @@
#include "GameLogic/PartitionManager.h"
#include "GameClient/ObserverCamera.h"
#include <algorithm>
+#include "GameClient/GameClient.h"
+#include "GameClient/Drawable.h"
+#include "Platform/WaterFoamParticlePolicy.h"
#include <map>
#ifdef _INTERNAL
@@ -73,6 +77,28 @@ extern Real TheParticleFillMS;
extern UnsignedInt TheParticlesPastGroupLimit;
#endif
+#if defined(__linux__)
+// Modern water replaces only verified vessel-surface particles, after that hull's water draw. The
+// owner is the one the frame view took at the sync point, so the draw reads no live object.
+static Bool replaceLegacyVesselFoam(ParticleSystem *sys, ObjectID owner)
+{
+ if(!sys || !TheWaterRenderObj || !sys->getTemplate() || owner==INVALID_ID) return FALSE;
+ const Bool ordinaryGroundParticle=!sys->shouldBillboard() && !sys->isUsingDrawables() &&
+ !sys->isUsingStreak() && !sys->isUsingSmudge() && sys->getVolumeParticleDepth()==0;
+ const AsciiString name=sys->getTemplate()->getName(),texture=sys->getParticleTypeName();
+ if(!ordinaryGroundParticle || !WaterFoamParticlePolicy::KnownSurfaceFoam(name.str(),texture.str())) return FALSE;
+ const Bool mirror=ShaderClass::Is_Backface_Culling_Inverted();
+ // Keep the original admission functions for each pass. In particular, reflected
+ // hulls and spray remain intact; only same-interface surface ripples are isolated.
+ const Bool admitted=mirror?TheWaterRenderObj->isModernWaterMirrorForOwner(owner):TheWaterRenderObj->hasModernVesselFoam(owner);
+ // Simulation, emission, aging and IDs are untouched. Missing modern admission
+ // immediately restores the original particle draw.
+ return mirror?
+ WaterFoamParticlePolicy::ExcludeSelfReflection(name.str(),texture.str(),TRUE,TRUE,admitted):
+ WaterFoamParticlePolicy::Replace(name.str(),texture.str(),TRUE,TRUE,admitted,FALSE);
+}
+#endif
+
/** The preset a particle shader type draws with, and whether it names one at all. An invalid type
* leaves the point group's previous shader in place on the old path, so it does not take the
* direct one. */
@@ -1311,6 +1337,14 @@ void W3DParticleSystemManager::refreshFrameView( void )
SystemView view;
view.system = sys;
view.fade = fade;
+#if defined(__linux__)
+ view.owner = INVALID_ID;
+ if (sys->getAttachedDrawable() != INVALID_DRAWABLE_ID) {
+ const Drawable *drawable = TheGameClient->findDrawableByID(sys->getAttachedDrawable());
+ const Object *object = drawable ? drawable->getObject() : NULL;
+ if (object) view.owner = object->getID();
+ } else view.owner = sys->getAttachedObject();
+#endif
m_frameView.push_back( view );
}
@@ -1506,6 +1540,10 @@ void W3DParticleSystemManager::doParticles(RenderInfoClass &rinfo)
for (size_t v = 0; v < m_frameView.size(); ++v)
{
ParticleSystem *sys = m_frameView[ v ].system;
+#if defined(__linux__)
+ if (replaceLegacyVesselFoam(sys, m_frameView[ v ].owner))
+ continue;
+#endif
if (*((UnsignedInt *)sys->getParticleTypeName().str()) == 0x44554D53)
continue;
@@ -1597,6 +1635,10 @@ void W3DParticleSystemManager::doParticles(RenderInfoClass &rinfo)
#endif
continue;
}
+#if defined(__linux__)
+ if (replaceLegacyVesselFoam(sys, m_frameView[ v ].owner))
+ continue;
+#endif
//temporary hack that checks if texture name starts with "SMUD" - if so, we can assume it's a smudge type
if (/*sys->isUsingSmudge()*/ *((UnsignedInt *)sys->getParticleTypeName().str()) == 0x44554D53)
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp
index 420f8bc2f..15c955405 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp
@@ -34,7 +34,26 @@
// INCLUDES ///////////////////////////////////////////////////////////////////////////////////////
#include "stdio.h"
+#include <cstdlib>
+#include <chrono>
#include "Lib/Clock.h"
+#include "Platform/WaterSurfaceModel.h"
+#include "Platform/ModernWaterMaterial.h"
+#include "Platform/WaterCoastalCrest.h"
+#include "Platform/WaterShoreOverlay.h"
+#include "Platform/WaterFoamWindow.h"
+#include "Platform/WaterFoamParticlePolicy.h"
+#include "Platform/WaterHullContact.h"
+#include "Platform/WaterBedMaterial.h"
+#include "Platform/WaterFftGeometry.h"
+#include "Platform/WaterTerrainCulling.h"
+#include "Platform/WaterWaveCage.h"
+#include "Platform/WaterWaveCageMesh.h"
+#include "GameLogic/Object.h"
+#include "GameLogic/TerrainLogic.h"
+#include "GameLogic/Module/PhysicsUpdate.h"
+#include "GameClient/Drawable.h"
+#include "W3DDevice/GameClient/Module/W3DModelDraw.h"
#include "W3DDevice/GameClient/W3DWater.h"
#include "W3DDevice/GameClient/HeightMap.h"
#include "W3DDevice/GameClient/W3DShroud.h"
@@ -52,9 +71,12 @@
#include "dx11twin.h"
#include "simplevec.h"
#include "mesh.h"
+#include "meshmdl.h"
+#include "hlod.h"
#include "matinfo.h"
#include "Common/GameState.h"
+#include "Common/GameEngine.h"
#include "Common/GlobalData.h"
#include "Common/PerfTimer.h"
#include "Common/Xfer.h"
@@ -216,6 +238,8 @@ void doSkyBoxSet(Bool startDraw)
#define NOISE_FREQ (2.0f*PI/WAVE_FREQ)
#define NOISE_REPEAT_FACTOR ((float)(1.0f/(16.0f)))
+static const Real WATER_SCROLL_SPEED = 0.2f;
+static const Real AUTHORED_FPS = 30.0f;
static Bool wireframeForDebug = 0;
@@ -327,7 +351,1201 @@ void WaterRenderObjClass::setupJbaWaterShader(void)
if (m_riverWaterPixelShader){
DX8Wrapper::_Get_D3D_Device()->SetPixelShaderConstantF(0, D3DXVECTOR4(REFLECTION_FACTOR, REFLECTION_FACTOR, REFLECTION_FACTOR, 1.0f), 1);
DX8Wrapper::Set_Pixel_Shader(m_riverWaterPixelShader);
+ setupModernWaterShader(TRUE);
+ }
+}
+
+// SDL's map water composites the coloured mirror in its surface shader. Windows retains the
+// original assembly and its separate reflection pass. No texture assets or game data are changed.
+namespace {
+struct WaterHullMesh : WaterHullPoseCache::Mesh {
+ MeshModelClass *model;
+};
+static_assert(WaterHullPoseCache::MaxMeshes==WaterHullModel::MaxMeshes,"Hull pose snapshots share the collector bound");
+static Bool CollectWaterHullMeshes(RenderObjClass *object,const Vector3 &origin,float axisX,float axisY,
+ float level,float crestRise,std::vector<WaterHullMesh> &meshes,unsigned &visited,unsigned depth=0)
+{
+ if (!object || object->Is_Hidden() || object->Is_Animation_Hidden()) return TRUE;
+ if (depth>6 || ++visited>WaterHullModel::MaxMeshes) return FALSE;
+ if (object->Class_ID()==RenderObjClass::CLASSID_MESH) {
+ MeshModelClass *model=static_cast<MeshClass*>(object)->Peek_Model();
+ if (!model || model->Get_Flag(MeshGeometryClass::SKIN) || object->Is_Additive()) return TRUE;
+ const AABoxClass &bounds=object->Get_Bounding_Box();
+ if (level+crestRise<bounds.Center.Z-bounds.Extent.Z-0.01f || level>bounds.Center.Z+bounds.Extent.Z+0.01f) return TRUE;
+ if (model->Get_Vertex_Count()<=0 || model->Get_Polygon_Count()<=0) return TRUE;
+ const Matrix3D &matrix=object->Get_Transform();
+ WaterHullMesh mesh;mesh.model=model;
+ mesh.crossesMean=level>=bounds.Center.Z-bounds.Extent.Z-0.01f && level<=bounds.Center.Z+bounds.Extent.Z+0.01f;
+ mesh.identity=model;mesh.vertexArray=model->Get_Vertex_Array();mesh.triangleArray=model->Get_Polygon_Array();
+ mesh.vertexCount=model->Get_Vertex_Count();mesh.triangleCount=model->Get_Polygon_Count();
+ AABoxClass localBounds;model->Get_Bounding_Box(&localBounds);
+ const float localCenter[3]={localBounds.Center.X,localBounds.Center.Y,localBounds.Center.Z};
+ const float localExtent[3]={localBounds.Extent.X,localBounds.Extent.Y,localBounds.Extent.Z};
+ mesh.supportRadius=WaterHullPoseCache::SupportRadius(localCenter,localExtent);
+ if(!std::isfinite(mesh.supportRadius)) return FALSE;
+ for (unsigned column=0;column<4;++column) {
+ const float x=matrix[0][column]-(column==3?origin.X:0.0f);
+ const float y=matrix[1][column]-(column==3?origin.Y:0.0f);
+ mesh.transform[0][column]=x*axisX+y*axisY;
+ mesh.transform[1][column]=-x*axisY+y*axisX;
+ mesh.transform[2][column]=matrix[2][column]-(column==3?level:0.0f);
+ for (unsigned row=0;row<3;++row) {
+ if (!std::isfinite(mesh.transform[row][column]) || std::abs(mesh.transform[row][column])>1.0e6f) return FALSE;
+ }
+ }
+ if(!WaterHullPoseCache::Valid(mesh)) return FALSE;
+ meshes.push_back(mesh);
+ return TRUE;
+ }
+ if (object->Class_ID()==RenderObjClass::CLASSID_HLOD) {
+ HLodClass *hlod=static_cast<HLodClass*>(object);
+ // Retain the most detailed authored contour as visual LODs change. It is independent
+ // of deck/superstructure bounds and is never used for collision or pathfinding.
+ const int lod=hlod->Get_Lod_Count()-1;
+ if (lod>=0) for (int i=0;i<hlod->Get_Lod_Model_Count(lod);++i)
+ if (!CollectWaterHullMeshes(hlod->Peek_Lod_Model(lod,i),origin,axisX,axisY,level,crestRise,meshes,visited,depth+1)) return FALSE;
+ for (int i=0;i<hlod->Get_Additional_Model_Count();++i)
+ if (!CollectWaterHullMeshes(hlod->Peek_Additional_Model(i),origin,axisX,axisY,level,crestRise,meshes,visited,depth+1)) return FALSE;
+ return TRUE;
+ }
+ const int children=object->Get_Num_Sub_Objects();
+ if (children>(int)WaterHullModel::MaxMeshes) return FALSE;
+ for(int i=0;i<children;++i) {
+ RenderObjClass *child=object->Get_Sub_Object(i);
+ const Bool ok=CollectWaterHullMeshes(child,origin,axisX,axisY,level,crestRise,meshes,visited,depth+1);
+ REF_PTR_RELEASE(child);
+ if (!ok) return FALSE;
+ }
+ return TRUE;
+}
+static Real WaterTerrainDepth(WorldHeightMap *map,Real x,Real y,Real level)
+{
+ if(!map || map->getXExtent()<2 || map->getYExtent()<2) return 0.0f;
+ const Real mx=clamp(x/MAP_XY_FACTOR+map->getBorderSize(),0.0f,(Real)map->getXExtent()-1.001f);
+ const Real my=clamp(y/MAP_XY_FACTOR+map->getBorderSize(),0.0f,(Real)map->getYExtent()-1.001f);
+ const Int ix=(Int)mx,iy=(Int)my;const Real fx=mx-ix,fy=my-iy;
+ const Real a=map->getHeight(ix,iy)*(1-fx)+map->getHeight(ix+1,iy)*fx;
+ const Real b=map->getHeight(ix,iy+1)*(1-fx)+map->getHeight(ix+1,iy+1)*fx;
+ return level-(a*(1-fy)+b*fy)*MAP_HEIGHT_SCALE;
+}
+static WaterHullModel::Point3 WaterHullPoint(const WaterHullMesh &mesh,const Vector3 &p)
+{
+ WaterHullModel::Point3 out;
+ out.x=mesh.transform[0][0]*p.X+mesh.transform[0][1]*p.Y+mesh.transform[0][2]*p.Z+mesh.transform[0][3];
+ out.y=mesh.transform[1][0]*p.X+mesh.transform[1][1]*p.Y+mesh.transform[1][2]*p.Z+mesh.transform[1][3];
+ out.z=mesh.transform[2][0]*p.X+mesh.transform[2][1]*p.Y+mesh.transform[2][2]*p.Z+mesh.transform[2][3];
+ return out;
+}
+}
+
+void WaterRenderObjClass::clearModernWaterHulls(Bool admissions)
+{
+ if (admissions)
+ m_modernBowAdmissions.Clear();
+ for (ModernHullCache &cache : m_modernHullCache) {
+ for (MeshModelClass *mesh : cache.slicedModels)
+ REF_PTR_RELEASE(mesh);
+ for (MeshModelClass *mesh : cache.visualModels)
+ REF_PTR_RELEASE(mesh);
+ REF_PTR_RELEASE(cache.model);
+ }
+ m_modernHullCache.clear();
+ m_modernHulls.clear();
+ m_modernContactHulls.clear();
+ m_modernVisualHulls.clear();
+ m_modernHullObjectIDs.clear();
+ m_modernHullSerial = 0;
+ m_modernHullTraceLines = 0;
+ m_modernVesselStateTraceFrame = ~0u;
+ m_modernVesselStateTraceLines = 0;
+ m_modernVisualHullTraceLines = 0;
+}
+
+Bool WaterRenderObjClass::modernHasHull(UnsignedInt objectID) const
+{
+ return std::find(m_modernHullObjectIDs.begin(), m_modernHullObjectIDs.end(), objectID)
+ != m_modernHullObjectIDs.end();
+}
+
+Bool WaterRenderObjClass::hasModernVesselFoam(UnsignedInt objectID) const
+{
+#if defined(__linux__)
+ return m_useModernWater && !m_renderingMirror && m_trapezoidWaterPixelShader
+ && m_modernFoamDrawFrame == WW3D::Get_Frame_Count()
+ && std::find(m_modernFoamDrawObjectIDs.begin(), m_modernFoamDrawObjectIDs.end(), objectID)
+ != m_modernFoamDrawObjectIDs.end();
+#else
+ return FALSE;
+#endif
+}
+
+Bool WaterRenderObjClass::isModernWaterMirrorForOwner(UnsignedInt objectID) const
+{
+#if defined(__linux__)
+ if(!m_useModernWater || !m_renderingMirror || m_waterType!=WATER_TYPE_0_TRANSLUCENT || !m_trapezoidWaterPixelShader ||
+ !m_pReflectionTexture || !TheGameLogic || !TheTerrainLogic || !TheTerrainRenderObject ||
+ !TheTerrainRenderObject->getMap()) return FALSE;
+ const Object *object=TheGameLogic->findObjectByID((ObjectID)objectID);
+ if(!object || object->isDestroyed()) return FALSE;
+ Drawable *drawable=object->getDrawable();
+ if(!drawable || drawable->isDrawableEffectivelyHidden() || drawable->getFullyObscuredByShroud()) return FALSE;
+ const Coord3D &position=*object->getPosition();Real level=0.0f;
+ if(!TheTerrainLogic->isUnderwater(position.x,position.y,&level) ||
+ !WaterFoamParticlePolicy::SameMirrorSurface(true,true,level,m_reflectionLevel)) return FALSE;
+ for(DrawModule **modules=drawable->getDrawModules();modules && *modules;++modules) {
+ const ObjectDrawInterface *draw=(*modules)->getObjectDrawInterface();
+ if(!draw) continue;
+ RenderObjClass *model=((W3DModelDraw*)draw)->getRenderObject();
+ if(!model || model->Is_Hidden() || model->Is_Animation_Hidden()) continue;
+ const AABoxClass &bounds=model->Get_Bounding_Box();
+ if(level>=bounds.Center.Z-bounds.Extent.Z-0.1f && level<=bounds.Center.Z+bounds.Extent.Z+0.1f) return TRUE;
+ }
+#endif
+ return FALSE;
+}
+
+Real WaterRenderObjClass::modernHullDamping(Real x,Real y,Real level) const
+{
+ Real damping=1.0f;
+ for (size_t i=0;i<m_modernHulls.size();++i) damping=min(damping,WaterHullModel::Damping(m_modernHulls[i],x,y,level));
+ return damping;
+}
+
+void WaterRenderObjClass::updateModernWaterHulls(void)
+{
+#if defined(__linux__)
+ m_modernHulls.clear();
+ m_modernContactHulls.clear();
+ m_modernVisualHulls.clear();
+ m_modernHullObjectIDs.clear();
+ if (!TheGameLogic || !TheTerrainLogic || !TheTerrainRenderObject || !TheTerrainRenderObject->getMap()) {
+ clearModernWaterHulls();clearModernWaterFoam();return;
+ }
+ ++m_modernHullSerial;
+ const Bool visualContact=WaterHullVisual::Enabled();
+ const UnsignedInt motionFrame=TheGameLogic->getFrame();
+ const Bool motionFrozen=TheGameLogic->isGamePaused() || (TheScriptEngine &&
+ (TheScriptEngine->isTimeFrozenScript() || TheScriptEngine->isTimeFrozenDebug()));
+ // Opt-in evidence of the actual displayed transform; never drives water or simulation.
+ const char *stateTraceOption=getenv("ZH_WATER_VESSEL_STATE_TRACE");
+ const UnsignedInt renderFrame=WW3D::Get_Frame_Count();
+ const Bool traceVesselState=stateTraceOption && stateTraceOption[0]=='1' && stateTraceOption[1]=='\0' &&
+ !m_renderingMirror && m_modernVesselStateTraceLines<4096 && m_modernVesselStateTraceFrame!=renderFrame;
+ if(traceVesselState) m_modernVesselStateTraceFrame=renderFrame;
+ unsigned stateTraceRows=0;
+ struct Candidate { const Object *object; RenderObjClass *model; Real level,score,samplePhase,crestRise; Bool influenceVisible; };
+ m_modernFoamHistory.Advance(m_modernWaveTime);
+ std::vector<Candidate> candidates;
+ for (const Object *object=TheGameLogic->getFirstObject();object;object=object->getNextObject()) {
+ if (object->isDestroyed() || object->isKindOf(KINDOF_AIRCRAFT) ||
+ !(object->isKindOf(KINDOF_AIRCRAFT_CARRIER)||object->isKindOf(KINDOF_BOAT)||object->isKindOf(KINDOF_VEHICLE))) continue;
+ Drawable *drawable=object->getDrawable();
+ if (!drawable || drawable->isDrawableEffectivelyHidden() || drawable->getFullyObscuredByShroud()) continue;
+ const Coord3D &position=*object->getPosition();Real level=0.0f;
+ if (!TheTerrainLogic->isUnderwater(position.x,position.y,&level)) continue;
+ Real localOffshore=0.0f;
+ for (size_t i=0;i<m_modernOpticalTextures.size();++i)
+ if (m_modernOpticalTextures[i].level==level && !m_modernOpticalTextures[i].ocean.empty())
+ localOffshore=max(localOffshore,WaterSurfaceModel::SampleOffshore(m_modernOpticalTextures[i].ocean.data(),m_modernHeightWidth,m_modernHeightHeight,
+ position.x/MAP_XY_FACTOR+m_modernHeightBorder,position.y/MAP_XY_FACTOR+m_modernHeightBorder,MAP_XY_FACTOR).height);
+ if (localOffshore<=0.001f) continue;
+ const Real terrainDepth=WaterTerrainDepth(TheTerrainRenderObject->getMap(),position.x,position.y,level);
+ const Real crestRise=WaterHullContact::ReachableCrest(terrainDepth,WaterSurfaceModel::TerrainDamping(terrainDepth,localOffshore));
+ for (DrawModule **modules=drawable->getDrawModules();modules && *modules;++modules) {
+ const ObjectDrawInterface *draw=(*modules)->getObjectDrawInterface();
+ if (!draw) continue;
+ // All W3D object draw interfaces are W3DModelDraw implementations (also used by
+ // projected shadows and ghost snapshots); use the displayed, interpolated transform.
+ W3DModelDraw *modelDraw=(W3DModelDraw*)draw;
+ RenderObjClass *model=modelDraw->getRenderObject();
+ // Scene visibility culls the hull itself, but an offscreen vessel can still disturb
+ // visible water. Keep explicit visibility/shroud exclusions, then cull its influence.
+ if (!model || model->Is_Hidden() || model->Is_Animation_Hidden()) continue;
+ const AABoxClass &bounds=model->Get_Bounding_Box();
+ if (level<bounds.Center.Z-bounds.Extent.Z-0.01f || level>bounds.Center.Z+bounds.Extent.Z+0.01f) continue;
+ AABoxClass influence=bounds;
+ influence.Extent.X+=122.0f;influence.Extent.Y+=122.0f;
+ influence.Extent.Z+=WaterSurfaceModel::MaxDisplacement;
+ const Bool influenceVisible=!m_modernRenderCamera || !m_modernRenderCamera->Cull_Box(influence);
+ const Real dx=bounds.Center.X-m_modernCamera.X,dy=bounds.Center.Y-m_modernCamera.Y;
+ const Real radius=sqrtf(bounds.Extent.X*bounds.Extent.X+bounds.Extent.Y*bounds.Extent.Y);
+ const Real score=max(0.0f,sqrtf(dx*dx+dy*dy)-radius);
+ Candidate candidate={object,model,level,score,modelDraw->clientOnly_getRenderMotionSamplePhase(),crestRise,influenceVisible};
+ size_t insert=0;
+ while(insert<candidates.size() && (candidates[insert].score<score ||
+ (candidates[insert].score==score && candidates[insert].object->getID()<object->getID()))) ++insert;
+ if (insert<WaterFoamHistory::MaxEmitters) {
+ candidates.insert(candidates.begin()+insert,candidate);
+ if(candidates.size()>WaterFoamHistory::MaxEmitters) candidates.pop_back();
+ }
+ break;
+ }
+ }
+ for (const Candidate &candidate:candidates) {
+ const Matrix3D &matrix=candidate.model->Get_Transform();
+ const Vector3 origin=matrix.Get_Translation();
+ float axisX=matrix[0][0],axisY=matrix[1][0],axisLength=sqrtf(axisX*axisX+axisY*axisY);
+ if (!(axisLength>0.0001f)) continue;
+ axisX/=axisLength;axisY/=axisLength;
+ std::vector<WaterHullMesh> meshes;unsigned visited=0;
+ if (!CollectWaterHullMeshes(candidate.model,origin,axisX,axisY,candidate.level,candidate.crestRise,meshes,visited)) continue;
+ size_t slot=0;
+ for (;slot<m_modernHullCache.size();++slot)
+ if(m_modernHullCache[slot].model==candidate.model && m_modernHullCache[slot].objectID==(UnsignedInt)candidate.object->getID()) break;
+ if (slot==m_modernHullCache.size()) {
+ if (slot==WaterHullModel::MaxCacheEntries) {
+ slot=0;
+ for(size_t i=1;i<m_modernHullCache.size();++i) if(m_modernHullCache[i].lastUse<m_modernHullCache[slot].lastUse) slot=i;
+ for(MeshModelClass *mesh:m_modernHullCache[slot].slicedModels) REF_PTR_RELEASE(mesh);
+ for(MeshModelClass *mesh:m_modernHullCache[slot].visualModels) REF_PTR_RELEASE(mesh);
+ REF_PTR_RELEASE(m_modernHullCache[slot].model);
+ m_modernHullCache[slot]=ModernHullCache();
+ } else m_modernHullCache.push_back(ModernHullCache());
+ m_modernHullCache[slot].model=candidate.model;candidate.model->Add_Ref();
+ m_modernHullCache[slot].objectID=(UnsignedInt)candidate.object->getID();
+ }
+ ModernHullCache &cache=m_modernHullCache[slot];cache.lastUse=m_modernHullSerial;
+ if(!cache.poses.Reusable(meshes,candidate.crestRise)) {
+ cache.polygon=WaterHullModel::Polygon();cache.contact=WaterHullModel::Polygon();
+ std::vector<WaterHullModel::Point> points,contactPoints;unsigned triangles=0,contactTriangles=0;Bool valid=TRUE,contactValid=TRUE;
+ for(const WaterHullMesh &mesh:meshes) {
+ const unsigned count=mesh.model->Get_Polygon_Count();
+ // Contact-only meshes cannot consume the independent mean-waterline budget.
+ if(mesh.crossesMean && valid) {
+ if(count>WaterHullModel::MaxSliceTriangles-triangles) valid=FALSE;
+ else triangles+=count;
+ }
+ if(contactValid) {
+ if(count>WaterHullModel::MaxSliceTriangles-contactTriangles) contactValid=FALSE;
+ else contactTriangles+=count;
+ }
+ if(!valid && !contactValid) break;
+ if((!mesh.crossesMean || !valid) && !contactValid) continue;
+ const Vector3 *vertices=mesh.model->Get_Vertex_Array();
+ const TriIndex *indices=mesh.model->Get_Polygon_Array();
+ for(unsigned i=0;i<count;++i) {
+ const TriIndex &t=indices[i];
+ if(t[0]>=mesh.model->Get_Vertex_Count() || t[1]>=mesh.model->Get_Vertex_Count() || t[2]>=mesh.model->Get_Vertex_Count()) {
+ if(mesh.crossesMean) valid=FALSE;
+ contactValid=FALSE;break;
+ }
+ const WaterHullModel::Point3 a=WaterHullPoint(mesh,vertices[t[0]]),b=WaterHullPoint(mesh,vertices[t[1]]),c=WaterHullPoint(mesh,vertices[t[2]]);
+ if(mesh.crossesMean && valid && !WaterHullModel::SliceTriangle(a,b,c,points)) valid=FALSE;
+ if(contactValid && !WaterHullContact::ProjectTriangle(a,b,c,candidate.crestRise,contactPoints)) contactValid=FALSE;
+ }
+ if(!valid && !contactValid) break;
+ }
+ if(valid) {
+ cache.polygon=WaterHullModel::BuildPolygon(points);
+ if(contactValid) cache.contact=WaterHullModel::BuildPolygon(contactPoints);
+ }
+ // Keep exactly the poses that produced these contours, including an empty result.
+ // Retained children prevent identity reuse when an HLOD replaces its mesh assets.
+ for(MeshModelClass *mesh:cache.slicedModels) REF_PTR_RELEASE(mesh);
+ cache.slicedModels.clear();
+ if(cache.slicedModels.capacity()<meshes.size()) cache.slicedModels.reserve(meshes.size());
+ for(const WaterHullMesh &mesh:meshes) { mesh.model->Add_Ref();cache.slicedModels.push_back(mesh.model); }
+ cache.poses.Store(meshes,candidate.crestRise);
+ if (getenv("ZH_WATER_HULL_TRACE") && m_modernHullTraceLines<64) {
+ if(m_modernHullTraceLines==0) {
+ const Coord3D &sun=TheGlobalData->m_terrainLightPos[0];const RGBColor &colour=TheGlobalData->m_terrainDiffuse[0];
+ const RGBColor &ambient=TheGlobalData->m_terrainAmbient[0];
+ fprintf(stderr,"water-hull-light: sun=(%.5f,%.5f,%.5f) colour=(%.5f,%.5f,%.5f) ambient=(%.5f,%.5f,%.5f) camera=(%.2f,%.2f,%.2f)\n",
+ -sun.x,-sun.y,-sun.z,colour.red,colour.green,colour.blue,ambient.red,ambient.green,ambient.blue,m_modernCamera.X,m_modernCamera.Y,m_modernCamera.Z);
+ for(Int lightIndex=1;lightIndex<min(3,TheGlobalData->m_numGlobalLights);++lightIndex) {
+ const Coord3D &fill=TheGlobalData->m_terrainLightPos[lightIndex];
+ const RGBColor &diffuse=TheGlobalData->m_terrainDiffuse[lightIndex];
+ fprintf(stderr,"water-hull-fill: index=%d count=%d direction=(%.5f,%.5f,%.5f) colour=(%.5f,%.5f,%.5f)\n",
+ lightIndex,TheGlobalData->m_numGlobalLights,-fill.x,-fill.y,-fill.z,diffuse.red,diffuse.green,diffuse.blue);
+ }
+ }
+ fprintf(stderr,"water-hull: object=%u model=%s meshes=%u triangles=%u vertices=%u error=%.4f level=%.3f origin=(%.2f,%.2f,%.2f)\n",
+ unsigned(candidate.object->getID()),candidate.model->Get_Name(),unsigned(meshes.size()),triangles,
+ cache.polygon.count,cache.polygon.error,candidate.level,origin.X,origin.Y,origin.Z);
+ ++m_modernHullTraceLines;
+ }
+ cache.forwardSign=1.0f;
+ const int bow=candidate.model->Get_Bone_Index("BOWWAKE"),stern=candidate.model->Get_Bone_Index("PROPELLERWAKE");
+ if(bow>0 && stern>0) {
+ const Vector3 direction=candidate.model->Get_Bone_Transform(bow).Get_Translation()-candidate.model->Get_Bone_Transform(stern).Get_Translation();
+ cache.forwardSign=direction.X*axisX+direction.Y*axisY<0.0f?-1.0f:1.0f;
+ } else if(cache.polygon.count>=3) {
+ // Assets without wake bones use the narrower end of their actual waterline.
+ float minX=1.0e30f,maxX=-1.0e30f;
+ for(unsigned i=0;i<cache.polygon.count;++i) {minX=min(minX,cache.polygon.points[i].x);maxX=max(maxX,cache.polygon.points[i].x);}
+ float leftMin=1.0e30f,leftMax=-1.0e30f,rightMin=1.0e30f,rightMax=-1.0e30f;
+ const float band=(maxX-minX)*0.2f;
+ for(unsigned i=0;i<cache.polygon.count;++i) {
+ const WaterHullModel::Point p=cache.polygon.points[i];
+ if(p.x<minX+band) {leftMin=min(leftMin,p.y);leftMax=max(leftMax,p.y);}
+ if(p.x>maxX-band) {rightMin=min(rightMin,p.y);rightMax=max(rightMax,p.y);}
+ }
+ if(leftMax-leftMin<rightMax-rightMin) cache.forwardSign=-1.0f;
+ }
+ }
+ if(traceVesselState && stateTraceRows<8 && m_modernVesselStateTraceLines<4096) {
+ const AABoxClass &bounds=candidate.model->Get_Bounding_Box();
+ // Model names normally contain only asset identifiers. Bound and sanitize the
+ // diagnostic string so malformed names cannot create JSON/log injection.
+ char modelName[129];unsigned nameLength=0;const char *sourceName=candidate.model->Get_Name();
+ while(sourceName && nameLength<128 && sourceName[nameLength]) {
+ const unsigned char c=(unsigned char)sourceName[nameLength];
+ modelName[nameLength++]=(c>=32 && c<127 && c!='"' && c!='\\')?char(c):'_';
+ }
+ modelName[nameLength]='\0';
+ fprintf(stderr,"water-vessel-state: {\"render\":%u,\"frame\":%u,\"object\":%u,\"model\":\"%s\",\"level\":%.6g,\"origin\":[%.6g,%.6g,%.6g],\"bounds\":[[%.6g,%.6g,%.6g],[%.6g,%.6g,%.6g]],\"axis\":[%.6g,%.6g],\"mean\":[",
+ unsigned(renderFrame),unsigned(motionFrame),unsigned(candidate.object->getID()),modelName,candidate.level,
+ origin.X,origin.Y,origin.Z,bounds.Center.X-bounds.Extent.X,bounds.Center.Y-bounds.Extent.Y,bounds.Center.Z-bounds.Extent.Z,
+ bounds.Center.X+bounds.Extent.X,bounds.Center.Y+bounds.Extent.Y,bounds.Center.Z+bounds.Extent.Z,axisX,axisY);
+ for(unsigned i=0;i<cache.polygon.count && i<WaterHullModel::MaxVertices;++i)
+ fprintf(stderr,"%s[%.6g,%.6g]",i?",":"",cache.polygon.points[i].x,cache.polygon.points[i].y);
+ fprintf(stderr,"],\"contact\":[");
+ for(unsigned i=0;i<cache.contact.count && i<WaterHullModel::MaxVertices;++i)
+ fprintf(stderr,"%s[%.6g,%.6g]",i?",":"",cache.contact.points[i].x,cache.contact.points[i].y);
+ fprintf(stderr,"]}\n");
+ ++stateTraceRows;++m_modernVesselStateTraceLines;
+ }
+ if(cache.polygon.count<3) continue;
+ const PhysicsBehavior *physics=candidate.object->getPhysics();
+ WaterVesselMotion::Point initialVelocity;
+ if(physics) {
+ const Coord3D &velocity=*physics->getVelocity();
+ initialVelocity={velocity.x*LOGICFRAMES_PER_SECOND,velocity.y*LOGICFRAMES_PER_SECOND};
+ }
+ const WaterVesselMotion::State previousMotion=cache.motion;
+ const WaterVesselMotion::Point velocity=WaterVesselMotion::Update(cache.motion,{origin.X,origin.Y},
+ candidate.level,motionFrame,motionFrozen,initialVelocity,float(LOGICFRAMES_PER_SECOND),candidate.samplePhase);
+ auto packHull=[&](const WaterHullModel::Polygon &polygon,WaterHullModel::Hull &hull,float sign)->Bool {
+ if(polygon.count<3) return FALSE;
+ float minX=1.0e30f,maxX=-1.0e30f,minY=1.0e30f,maxY=-1.0e30f;
+ for(unsigned i=0;i<polygon.count;++i) {
+ const WaterHullModel::Point p=polygon.points[i];
+ minX=min(minX,p.x);maxX=max(maxX,p.x);minY=min(minY,p.y);maxY=max(maxY,p.y);
+ }
+ if(maxX-minX<2.0f || maxY-minY<1.0f) return FALSE;
+ const float centerX=(minX+maxX)*0.5f,centerY=(minY+maxY)*0.5f;
+ hull.data[0][0]=origin.X+axisX*centerX-axisY*centerY;hull.data[0][1]=origin.Y+axisY*centerX+axisX*centerY;
+ hull.data[0][2]=candidate.level;hull.data[0][3]=float(polygon.count);
+ hull.data[1][0]=axisX*sign;hull.data[1][1]=axisY*sign;
+ hull.data[1][2]=(maxX-minX)*0.5f;hull.data[1][3]=(maxY-minY)*0.5f;
+ hull.data[2][0]=velocity.x;hull.data[2][1]=velocity.y;
+ hull.data[2][2]=float((unsigned(candidate.object->getID())*2654435761U)&65535U)/65535.0f;
+ hull.data[2][3]=sqrtf(hull.data[1][2]*hull.data[1][2]+hull.data[1][3]*hull.data[1][3]);
+ hull.data[3][0]=-hull.data[1][2];hull.data[3][2]=hull.data[1][2];
+ float sternY=0.0f,bowY=0.0f;unsigned sternCount=0,bowCount=0;
+ for(unsigned i=0;i<WaterHullModel::MaxVertices;++i) {
+ const WaterHullModel::Point p=polygon.points[min(i,polygon.count-1)];
+ hull.data[4+i/2][(i%2)*2]=(p.x-centerX)*sign;
+ hull.data[4+i/2][(i%2)*2+1]=(p.y-centerY)*sign;
+ if(i<polygon.count) {
+ const float localX=(p.x-centerX)*sign,localY=(p.y-centerY)*sign;
+ if(localX<-hull.data[1][2]+0.5f) {sternY+=localY;++sternCount;}
+ if(localX>hull.data[1][2]-0.5f) {bowY+=localY;++bowCount;}
+ }
+ }
+ hull.data[3][1]=sternCount?sternY/sternCount:0.0f;
+ hull.data[3][3]=bowCount?bowY/bowCount:0.0f;
+ return TRUE;
+ };
+ WaterHullModel::Hull hull,contactHull;
+ if(!packHull(cache.polygon,hull,cache.forwardSign)) continue;
+ // The displayed model axis is stable through pitch/roll. A sliced narrow-end
+ // heuristic can reverse on a keel sliver; actual velocity selects contact ends.
+ if(!packHull(cache.contact,contactHull,1.0f)) packHull(cache.polygon,contactHull,1.0f);
+ // Keep deposition independent of the eight nearest hulls sent to the shader. Visible
+ // vessels outside the camera still leave history in world space, subject to a fixed bound.
+ const double motionDt=(double(motionFrame)-previousMotion.frame+candidate.samplePhase-previousMotion.phase)/LOGICFRAMES_PER_SECOND;
+ const double motionDx=origin.X-previousMotion.position.x,motionDy=origin.Y-previousMotion.position.y;
+ const Bool resetMotion=!previousMotion.initialized || (motionFrame<previousMotion.frame || candidate.level!=previousMotion.level ||
+ motionDx*motionDx+motionDy*motionDy>pow(max(32.0,250.0*max(0.0,motionDt)),2.0));
+ const WaterFoamHistory::Point motionPosition={origin.X,origin.Y};
+ m_modernFoamHistory.Observe((UnsignedInt)candidate.object->getID(),contactHull,m_modernWaveTime,TRUE,resetMotion,&motionPosition);
+ if(candidate.influenceVisible && m_modernHulls.size()<WaterHullModel::MaxHulls) {
+ WaterHullVisual::Packet visualPacket={};
+ if(visualContact) {
+ // A separate cache keeps the mean-water clearance, pressure and history unchanged.
+ // Only the eight admitted shader hulls collect full reachable visual geometry.
+ const float bound=WaterFftGeometry::MaxVerticalDisplacement;
+ std::vector<WaterHullMesh> visualMeshes;unsigned visualVisited=0;
+ const Bool complete=CollectWaterHullMeshes(candidate.model,origin,axisX,axisY,
+ candidate.level-bound,2.0f*bound,visualMeshes,visualVisited);
+ const Bool reusable=complete && cache.visualPoses.Reusable(visualMeshes,2.0f*bound,0.0);
+ if(!complete) {
+ cache.visual=WaterHullVisual::Packet();cache.visualPoses.Clear();
+ for(MeshModelClass *mesh:cache.visualModels) REF_PTR_RELEASE(mesh);
+ cache.visualModels.clear();
+ } else if(!reusable) {
+ WaterHullVisual::Builder builder(-bound,bound);
+ Bool valid=TRUE;unsigned inspected=0;
+ for(const WaterHullMesh &mesh:visualMeshes) {
+ const unsigned count=mesh.model->Get_Polygon_Count();
+ if(count>WaterHullModel::MaxSliceTriangles-inspected) {valid=FALSE;break;}
+ inspected+=count;
+ const Vector3 *vertices=mesh.model->Get_Vertex_Array();
+ const TriIndex *indices=mesh.model->Get_Polygon_Array();
+ for(unsigned ti=0;ti<count;++ti) {
+ const TriIndex &triangle=indices[ti];
+ if(triangle[0]>=mesh.vertexCount || triangle[1]>=mesh.vertexCount || triangle[2]>=mesh.vertexCount) {valid=FALSE;break;}
+ WaterHullVisual::Point3 p[3];
+ for(unsigned vi=0;vi<3;++vi) {
+ const auto q=WaterHullPoint(mesh,vertices[triangle[vi]]);
+ p[vi]={q.x,q.y,q.z-bound};
+ }
+ if(!builder.AddTriangle(p[0],p[1],p[2])) {valid=FALSE;break;}
+ }
+ if(!valid) break;
+ }
+ cache.visual=WaterHullVisual::Packet();
+ if(valid) builder.Finish(cache.visual);
+ // Cache even complete-but-over-budget geometry; never truncate it to fit.
+ // Exact poses are required because nearly tangent slices amplify small motion.
+ for(MeshModelClass *mesh:cache.visualModels) REF_PTR_RELEASE(mesh);
+ cache.visualModels.clear();cache.visualModels.reserve(visualMeshes.size());
+ for(const WaterHullMesh &mesh:visualMeshes) {mesh.model->Add_Ref();cache.visualModels.push_back(mesh.model);}
+ cache.visualPoses.Store(visualMeshes,2.0f*bound);
+ }
+ const float deltaX=contactHull.data[0][0]-origin.X,deltaY=contactHull.data[0][1]-origin.Y;
+ WaterHullVisual::Reframe(cache.visual,deltaX*axisX+deltaY*axisY,
+ -deltaX*axisY+deltaY*axisX,visualPacket);
+ if(getenv("ZH_WATER_HULL_TRACE") && !m_renderingMirror && m_modernVisualHullTraceLines<128 &&
+ cache.visualTraceFrame!=motionFrame && (m_modernVisualHullTraceLines<8 || motionFrame%30==0)) {
+ fprintf(stderr,"water-hull-visual: frame=%u object=%u slot=%u complete=%d reused=%d vertices=%.0f triangles=%.0f radius=%.5f valid=%.0f\n",
+ unsigned(motionFrame),unsigned(candidate.object->getID()),unsigned(m_modernHulls.size()),int(complete),int(reusable),
+ visualPacket.metadata[0],visualPacket.metadata[1],visualPacket.metadata[2],visualPacket.metadata[3]);
+ ++m_modernVisualHullTraceLines;
+ cache.visualTraceFrame=motionFrame;
+ }
+ }
+ if(visualContact) m_modernVisualHulls.push_back(visualPacket);
+ // Diagnostic only. Insert inside the selected-hull branch, before m_modernHulls.push_back.
+ // Every traversal and output is opt-in and bounded. No rendering/simulation data is mutated.
+ const char *meshTraceOption=getenv("ZH_WATER_CONTACT_MESH_DUMP");
+ if(meshTraceOption && meshTraceOption[0]=='1' && meshTraceOption[1]=='\0' && !m_renderingMirror) {
+ auto auditUnsigned=[](const char *&s,unsigned &value)->bool {
+ if(!s || *s<'0' || *s>'9') return false;
+ value=0;
+ while(*s>='0' && *s<='9') {
+ if(value>100000000U) return false;
+ value=value*10+unsigned(*s++-'0');
+ }
+ return true;
+ };
+ const char *frameList=getenv("ZH_WATER_CONTACT_MESH_FRAMES");
+ if(!frameList) frameList="201,381";
+ bool wantedFrame=false,validOptions=true;unsigned frameCount=0;
+ while(*frameList && validOptions) {
+ unsigned requested=0;
+ validOptions=++frameCount<=8 && auditUnsigned(frameList,requested);
+ wantedFrame=wantedFrame || (validOptions && requested==motionFrame);
+ if(validOptions && *frameList==',') { ++frameList;if(!*frameList) validOptions=false; }
+ else if(*frameList) validOptions=false;
+ }
+ const char *objectOption=getenv("ZH_WATER_CONTACT_MESH_OBJECT");
+ unsigned requestedObject=0;bool wantedObject=true;
+ if(objectOption) {
+ validOptions=validOptions && auditUnsigned(objectOption,requestedObject) && !*objectOption;
+ wantedObject=requestedObject==unsigned(candidate.object->getID());
+ }
+ struct AuditKey { unsigned frame,object; };
+ static AuditKey emitted[64];static unsigned emittedCount=0;
+ bool seen=false;
+ for(unsigned i=0;i<emittedCount;++i)
+ seen=seen || (emitted[i].frame==motionFrame && emitted[i].object==unsigned(candidate.object->getID()));
+ if(validOptions && wantedFrame && wantedObject && !seen && emittedCount<64) {
+ emitted[emittedCount++]={unsigned(motionFrame),unsigned(candidate.object->getID())};
+ // This diagnostic collector's temporary Z origin is mean-V. Restore mean-relative Z
+ // explicitly below. The existing cached collector and every production packet stay intact.
+ const float auditV=WaterFftGeometry::MaxVerticalDisplacement;
+ std::vector<WaterHullMesh> auditMeshes;unsigned auditVisited=0;
+ bool complete=CollectWaterHullMeshes(candidate.model,origin,axisX,axisY,
+ candidate.level-auditV,2.0f*auditV,auditMeshes,auditVisited);
+ const char *reason=complete?"ok":"collector_limit_or_invalid_pose";
+ struct AuditTriangle { WaterHullModel::Point3 p[3]; };
+ std::vector<AuditTriangle> auditTriangles;
+ if(complete) for(const WaterHullMesh &mesh:auditMeshes) {
+ const unsigned count=mesh.model->Get_Polygon_Count();
+ if(count>WaterHullModel::MaxSliceTriangles-auditTriangles.size()) {
+ complete=false;reason="triangle_limit";break;
+ }
+ const Vector3 *vertices=mesh.model->Get_Vertex_Array();
+ const TriIndex *indices=mesh.model->Get_Polygon_Array();
+ if(!vertices || !indices) { complete=false;reason="missing_arrays";break; }
+ for(unsigned ti=0;ti<count;++ti) {
+ AuditTriangle triangle;
+ for(unsigned vi=0;vi<3;++vi) {
+ if(indices[ti][vi]>=mesh.model->Get_Vertex_Count()) {
+ complete=false;reason="invalid_index";break;
+ }
+ triangle.p[vi]=WaterHullPoint(mesh,vertices[indices[ti][vi]]);
+ triangle.p[vi].z-=auditV;
+ const auto &p=triangle.p[vi];
+ if(!std::isfinite(p.x)||!std::isfinite(p.y)||!std::isfinite(p.z)||
+ fabs(p.x)>1.0e6f||fabs(p.y)>1.0e6f||fabs(p.z)>1.0e6f) {
+ complete=false;reason="invalid_vertex";break;
+ }
+ }
+ if(!complete) break;
+ auditTriangles.push_back(triangle);
+ }
+ if(!complete) break;
+ }
+ if(!complete) auditTriangles.clear(); // never present a partial soup as complete
+ char auditName[129];unsigned auditNameLength=0;const char *auditSourceName=candidate.model->Get_Name();
+ while(auditSourceName && auditNameLength<128 && auditSourceName[auditNameLength]) {
+ const unsigned char c=(unsigned char)auditSourceName[auditNameLength];
+ auditName[auditNameLength++]=(c>=32 && c<127 && c!='"' && c!='\\')?char(c):'_';
+ }
+ auditName[auditNameLength]='\0';
+ fprintf(stderr,"water-contact-mesh: {\"version\":1,\"frame\":%u,\"render\":%u,\"time\":%.9g,\"object\":%u,\"model\":\"%s\",\"complete\":%s,\"reason\":\"%s\",\"level\":%.9g,\"range\":[%.9g,%.9g],\"origin\":[%.9g,%.9g,%.9g],\"axis\":[%.9g,%.9g],\"crestCap\":%.9g,\"meshes\":%u,\"visited\":%u,\"frameSize\":[%d,%d],\"contactFrame\":[%.9g,%.9g,%.9g,%.9g],\"mean\":[",
+ unsigned(motionFrame),unsigned(renderFrame),double(m_modernWaveTime),unsigned(candidate.object->getID()),auditName,
+ complete?"true":"false",reason,double(candidate.level),double(-auditV),double(auditV),
+ double(origin.X),double(origin.Y),double(origin.Z),double(axisX),double(axisY),double(candidate.crestRise),
+ unsigned(auditMeshes.size()),auditVisited,m_modernProjectedWidth,m_modernProjectedHeight,
+ double((contactHull.data[0][0]-origin.X)*axisX+(contactHull.data[0][1]-origin.Y)*axisY),
+ double(-(contactHull.data[0][0]-origin.X)*axisY+(contactHull.data[0][1]-origin.Y)*axisX),
+ double(contactHull.data[1][2]),double(contactHull.data[1][3]));
+ for(unsigned i=0;i<cache.polygon.count;++i)
+ fprintf(stderr,"%s[%.9g,%.9g]",i?",":"",double(cache.polygon.points[i].x),double(cache.polygon.points[i].y));
+ fprintf(stderr,"],\"slab\":[");
+ for(unsigned i=0;i<cache.contact.count;++i)
+ fprintf(stderr,"%s[%.9g,%.9g]",i?",":"",double(cache.contact.points[i].x),double(cache.contact.points[i].y));
+ fprintf(stderr,"],\"camera\":");
+ if(m_modernRenderCamera) {
+ Matrix3D auditView;m_modernRenderCamera->Get_View_Matrix(&auditView);
+ const Matrix4x4 &auditProjection=m_modernRenderCamera->Get_Projection_Matrix();
+ Vector2 auditViewportMin,auditViewportMax;m_modernRenderCamera->Get_Viewport(auditViewportMin,auditViewportMax);
+ fprintf(stderr,"{\"convention\":\"column_vector\",\"viewport\":[%.9g,%.9g,%.9g,%.9g],\"view\":[",
+ double(auditViewportMin.X),double(auditViewportMin.Y),double(auditViewportMax.X),double(auditViewportMax.Y));
+ for(unsigned r=0;r<3;++r) for(unsigned c=0;c<4;++c)
+ fprintf(stderr,"%s%.9g",r||c?",":"",double(auditView[r][c]));
+ fprintf(stderr,"],\"projection\":[");
+ for(unsigned r=0;r<4;++r) for(unsigned c=0;c<4;++c)
+ fprintf(stderr,"%s%.9g",r||c?",":"",double(auditProjection[r][c]));
+ fprintf(stderr,"]}");
+ } else fprintf(stderr,"null");
+ fprintf(stderr,",\"triangles\":[");
+ for(size_t ti=0;ti<auditTriangles.size();++ti) {
+ fprintf(stderr,"%s[",ti?",":"");
+ for(unsigned vi=0;vi<3;++vi) {
+ const auto &p=auditTriangles[ti].p[vi];
+ fprintf(stderr,"%s[%.9g,%.9g,%.9g]",vi?",":"",double(p.x),double(p.y),double(p.z));
+ }
+ fprintf(stderr,"]");
+ }
+ fprintf(stderr,"]}\n");
+ }
+ }
+ m_modernHulls.push_back(hull);
+ m_modernContactHulls.push_back(contactHull);
+ m_modernHullObjectIDs.push_back((UnsignedInt)candidate.object->getID());
+ }
+ }
+#endif
+}
+
+// Foam is stored in world-space path sections. The sampled window only controls raster cost;
+// moving the camera reconstructs the same history instead of moving or forgetting that history.
+void WaterRenderObjClass::clearModernWaterFoam(Bool history)
+{
+ m_modernFoamDrawFrame = ~0u;
+ m_modernFoamDrawObjectIDs.clear();
+ for (ModernFoamTexture &field : m_modernFoamTextures) REF_PTR_RELEASE(field.texture);
+ m_modernFoamTextures.clear();
+ if (history) m_modernFoamHistory.Clear();
+}
+
+void WaterRenderObjClass::invalidateModernWaterShore(void)
+{
+ m_modernShoreHistory.Clear();
+ m_modernShoreSource.Clear();
+ m_modernShoreReady = FALSE;
+ m_modernCoastalDomain = WaterCoastalDomain::Domain();
+ m_modernCoastalRevision = 0;
+ m_modernCoastalReady = m_modernCoastalViewReady = FALSE;
+ m_modernCoastalLookup.clear();
+ if (++m_modernShoreRevision == 0) m_modernShoreRevision = 1;
+ m_modernShoreAttempted = 0;
+ for (ModernFoamTexture &field : m_modernFoamTextures) field.valid = FALSE;
+}
+
+void WaterRenderObjClass::updateModernWaterShore(void)
+{
+#if defined(__linux__)
+ if (m_modernShoreAttempted != m_modernShoreRevision) {
+ m_modernShoreAttempted = m_modernShoreRevision;
+ m_modernShoreReady = FALSE;
+ std::vector<double> levels;
+ for (const auto &polygon : m_modernOpticalPolygons) {
+ if (polygon.points.size() < 3) continue;
+ const double level = polygon.points[0].z;
+ Bool flat = TRUE;
+ for (const auto &p : polygon.points) flat = flat && fabs(double(p.z) - level) < .01;
+ if (flat && std::find(levels.begin(), levels.end(), level) == levels.end()) levels.push_back(level);
+ }
+ std::sort(levels.begin(), levels.end());
+ WaterShoreHistory::BuildResult result = WaterShoreHistory::BuildResult::Invalid;
+ if (m_modernOpticalPolygonsValid && !m_modernHeights.empty() && levels.size() <= WaterShoreHistory::MaxLevels) {
+ // Complete every level before collecting pointers: texture-vector reallocation cannot
+ // invalidate a source field, and camera order cannot choose the retained history levels.
+ for (double level : levels) modernWaterOpticalTexture(Real(level));
+ std::vector<WaterShoreSource::Level> fields;
+ for (double level : levels) for (const auto &field : m_modernOpticalTextures)
+ if (field.level == level) {
+ fields.push_back({level, &field.shoreContext});
+ break;
+ }
+ // The broader physical coast is independent of the old authored rim alpha.
+ const char *surf = getenv("ZH_WATER_SURF_GPU");
+ if (surf && strcmp(surf, "1") == 0 && fields.size() == levels.size()) {
+ WaterCoastalDomain::Domain coastal;
+ const auto status = coastal.Build(m_modernHeights.data(), m_modernHeightWidth, m_modernHeightHeight,
+ m_modernHeightBorder, MAP_XY_FACTOR, MAP_HEIGHT_SCALE, m_modernOpticalPolygons, fields);
+ if (status == WaterShoreHistory::BuildResult::Ready && !coastal.Nodes().empty()) {
+ // Process-wide identity prevents a new map/object reusing an immutable GPU revision.
+ static uint64_t nextCoastalRevision = 0;
+ if (++nextCoastalRevision == 0) ++nextCoastalRevision;
+ m_modernCoastalRevision = nextCoastalRevision;
+ m_modernCoastalDomain = std::move(coastal);
+ m_modernCoastalReady = TRUE;
+ m_modernCoastalViewReady = FALSE;
+ }
+ fprintf(stderr, "water-surf-domain: revision=%llu result=%u nodes=%u levels=%u spacing=%.3f\n",
+ (unsigned long long) m_modernCoastalRevision, unsigned(status), unsigned(m_modernCoastalDomain.Nodes().size()),
+ unsigned(fields.size()), m_modernCoastalDomain.Grid().spacing);
+ }
+ WaterShoreSource::Batch candidate;
+ if (fields.size() == levels.size()) result = candidate.Build(m_modernHeights.data(), m_modernHeightWidth,
+ m_modernHeightHeight, m_modernHeightBorder, MAP_XY_FACTOR, MAP_HEIGHT_SCALE, m_modernOpticalPolygons, fields);
+ if (result == WaterShoreHistory::BuildResult::Ready) {
+ WaterShoreHistory::Parameters settings;
+ settings.maximumRate = WaterShoreFoam::MaximumRate;
+ result = m_modernShoreHistory.Install(candidate.Grid(), candidate.Cells(), m_modernShoreRevision, m_modernWaveTime, settings);
+ if (result == WaterShoreHistory::BuildResult::Ready) {
+ m_modernShoreSource = std::move(candidate);
+ m_modernShoreReady = TRUE;
+ }
+ }
+ } else if (levels.size() > WaterShoreHistory::MaxLevels) result = WaterShoreHistory::BuildResult::TooManyLevels;
+ if (getenv("ZH_WATER_SHORE_TRACE") || !m_modernShoreReady)
+ fprintf(stderr, "water-shore-domain: revision=%llu result=%u cells=%u edges=%u levels=%u tiles=%u support_vertices=%u support_work=%u\n",
+ (unsigned long long) m_modernShoreRevision, unsigned(result), unsigned(m_modernShoreHistory.Domain().Cells().size()),
+ unsigned(m_modernShoreHistory.Domain().Edges().size()), unsigned(levels.size()),
+ unsigned(m_modernShoreSource.Support().TileCount()), unsigned(m_modernShoreSource.Support().VertexCount()),
+ unsigned(m_modernShoreSource.Support().Work()));
+ }
+ if (m_modernShoreReady && m_modernShoreHistory.ValidFor(m_modernShoreRevision)) {
+ const auto result = m_modernShoreHistory.Advance(m_modernWaveTime, m_modernShoreSource);
+ if (result == WaterShoreHistory::AdvanceResult::Invalid) m_modernShoreReady = FALSE;
+ if (result == WaterShoreHistory::AdvanceResult::Rewound)
+ for (ModernFoamTexture &field : m_modernFoamTextures) field.valid = FALSE;
+ }
+#endif
+}
+
+void WaterRenderObjClass::bindModernWaterFoam(Real level, Bool river)
+{
+#if defined(__linux__)
+ D3DXVECTOR4 area(0, 0, 0, 0), parameters(0, level, 0, m_modernWaveTime);
+ TextureClass *texture = NULL;
+ const char *enabled = getenv("ZH_WATER_FOAM_HISTORY");
+ const char *shoreEnabled = getenv("ZH_WATER_SHORE_HISTORY"), *shoreSource = getenv("ZH_WATER_SHORE_FOAM");
+ const Bool vessel = (!enabled || strcmp(enabled, "0") != 0) && m_modernFoamHistory.HasFoam();
+ const Bool coast = (!shoreEnabled || strcmp(shoreEnabled, "0") != 0) && (!shoreSource || strcmp(shoreSource, "0") != 0)
+ && m_modernShoreReady && m_modernShoreHistory.ValidFor(m_modernShoreRevision)
+ && !m_modernShoreHistory.Domain().Cells().empty();
+ const unsigned channels = ((vessel ? 1 : 0)|(coast ? 2 : 0))|((vessel || coast) ? 4 : 0);
+ if (!river && channels && m_modernRenderCamera) {
+ size_t index = 0;
+ for (; index < m_modernFoamTextures.size(); ++index) if (m_modernFoamTextures[index].level == level) break;
+ if (index == m_modernFoamTextures.size() && index < WaterOpticalContext::MaxLevels) {
+ m_modernFoamTextures.push_back(ModernFoamTexture());
+ m_modernFoamTextures.back().level = level;
+ }
+ if (index < m_modernFoamTextures.size()) {
+ ModernFoamTexture &field = m_modernFoamTextures[index];
+ const Vector2 ndc[5] = {Vector2(0, 0), Vector2(-1, -1), Vector2(1, -1), Vector2(1, 1), Vector2(-1, 1)};
+ WaterFoamWindow::Point rays[5];
+ for (unsigned i = 0; i < 5; ++i) {
+ Vector3 target;
+ m_modernRenderCamera->Un_Project(target, ndc[i]);
+ const Vector3 d = target - m_modernCamera;
+ rays[i] = {d.X, d.Y, d.Z};
+ }
+ const WaterFoamHistory::Mapping map = WaterFoamWindow::Choose({m_modernCamera.X, m_modernCamera.Y, m_modernCamera.Z}, rays, level);
+ const Bool remap = map.originX != field.mapping.originX || map.originY != field.mapping.originY ||
+ map.widthWorld != field.mapping.widthWorld || map.heightWorld != field.mapping.heightWorld
+ || map.widthPixels != field.mapping.widthPixels || map.heightPixels != field.mapping.heightPixels;
+ // At most ten uploads per elapsed water second for a stable camera. The shader ages
+ // coverage between uploads, and pause freezes both fields. Camera changes may reproject.
+ if (!field.valid || field.channels != channels || remap || m_modernWaveTime - field.timestamp >= 0.1f
+ || m_modernWaveTime < field.timestamp) {
+ std::vector<std::uint32_t> pixels, direction;
+ Bool atlas = TRUE;
+ if (vessel) atlas = m_modernFoamHistory.BuildAtlas(map, level, pixels, &direction);
+ else {
+ pixels.assign(size_t(map.widthPixels) * map.heightPixels, 0);
+ direction.assign(pixels.size(), 0);
+ }
+ if (atlas && coast) {
+ const auto &states = m_modernShoreHistory.Preview(m_modernShoreSource);
+ const WaterShoreHistory::Mapping shoreMap = {map.originX, map.originY, map.widthWorld, map.heightWorld,
+ map.widthPixels, map.heightPixels};
+ auto coverage = WaterShoreSource::Coverage;
+ atlas = WaterShoreHistory::RasterizeAlpha(m_modernShoreHistory.Domain(), states, shoreMap, level, m_modernWaveTime,
+ coverage, pixels, m_modernShoreSource.Support());
+ }
+ if (atlas) {
+ // Optional native capture evidence: report elapsed water time and the actual
+ // uploaded coverage, without reading any GPU resource back to the CPU.
+ if (getenv("ZH_WATER_FOAM_TRACE") && floor(field.timestamp) != floor(m_modernWaveTime)) {
+ unsigned covered = 0, peak = 0;
+ double total = 0;
+ for (std::uint32_t pixel : pixels) {
+ const unsigned r = (pixel >> 16) & 255;
+ covered += r > 0;
+ peak = max(peak, r);
+ total += r;
+ }
+ fprintf(stderr, "water-foam: time=%.3f level=%.3f segments=%u emitters=%u covered=%u peak=%u sum=%.0f area=(%.1f,%.1f,%.1f,%.1f)\n",
+ m_modernWaveTime, level, unsigned(m_modernFoamHistory.SegmentCount()), unsigned(m_modernFoamHistory.TrackedCount()),
+ covered, peak, total, map.originX, map.originY, map.widthWorld, map.heightWorld);
+ for (size_t h = 0; h < m_modernHulls.size(); ++h) {
+ const WaterHullModel::Hull &hull = m_modernHulls[h];
+ fprintf(stderr, "water-foam-hull: time=%.3f object=%u center=(%.2f,%.2f) half-size=(%.2f,%.2f) velocity=(%.2f,%.2f) ends=(%.2f,%.2f,%.2f,%.2f)\n",
+ m_modernWaveTime, m_modernHullObjectIDs[h], hull.data[0][0], hull.data[0][1], hull.data[1][2], hull.data[1][3],
+ hull.data[2][0], hull.data[2][1], hull.data[3][0], hull.data[3][1], hull.data[3][2], hull.data[3][3]);
+ const WaterHullModel::Hull &contact = m_modernContactHulls[h];
+ fprintf(stderr, "water-foam-contact: time=%.3f object=%u center=(%.2f,%.2f) half-size=(%.2f,%.2f) ends=(%.2f,%.2f,%.2f,%.2f)\n",
+ m_modernWaveTime, m_modernHullObjectIDs[h], contact.data[0][0], contact.data[0][1], contact.data[1][2],
+ contact.data[1][3],
+ contact.data[3][0], contact.data[3][1], contact.data[3][2], contact.data[3][3]);
+ }
+ }
+ // Merge coastal alpha before appending the direction tile: its rasterizer
+ // owns exactly the original logical window. Both tiles share one upload/lifetime.
+ pixels.insert(pixels.end(), direction.begin(), direction.end());
+ const unsigned physicalHeight = map.heightPixels * 2;
+ if (field.texture && (field.textureWidth != map.widthPixels || field.textureHeight != physicalHeight)) {
+ REF_PTR_RELEASE(field.texture);
+ field.valid = FALSE;
+ }
+ if (!field.texture) {
+ field.texture = NEW_REF(TextureClass, (map.widthPixels, physicalHeight, WW3D_FORMAT_A8R8G8B8, MIP_LEVELS_1));
+ field.textureWidth = map.widthPixels;
+ field.textureHeight = physicalHeight;
+ }
+ SurfaceClass *surface = field.texture ? field.texture->Get_Surface_Level() : NULL;
+ Int pitch = 0;
+ void * bits = surface ? surface->Lock(&pitch) : NULL;
+ const Bool uploaded = bits && pitch >= Int(map.widthPixels * 4);
+ if (uploaded)
+ for (unsigned y = 0; y < physicalHeight; ++y) memcpy((char*) bits + y * pitch,
+ pixels.data() + size_t(y) * map.widthPixels, map.widthPixels * 4);
+ if (bits) surface->Unlock();
+ if (uploaded) {
+ field.mapping = map;
+ field.timestamp = m_modernWaveTime;
+ field.channels = channels;
+ field.valid = TRUE;
+ }
+ else field.valid = FALSE; // missing surface/lock must not expose a stale or partial pair
+ REF_PTR_RELEASE(surface);
+ } else field.valid = FALSE;
+ }
+ if (field.valid) {
+ texture = field.texture;
+ area = D3DXVECTOR4(float(field.mapping.originX), float(field.mapping.originY), float(1.0 / field.mapping.widthWorld),
+ float(1.0 / field.mapping.heightWorld));
+ parameters = D3DXVECTOR4(float(field.channels), level, float(max(field.mapping.widthWorld / field.mapping.widthPixels,
+ field.mapping.heightWorld / field.mapping.heightPixels)), field.timestamp);
+ }
+ }
+ }
+ DX8Wrapper::_Get_D3D_Device()->SetPixelShaderConstantF(88, area, 1);
+ DX8Wrapper::_Get_D3D_Device()->SetPixelShaderConstantF(89, parameters, 1);
+ DX8Wrapper::Set_DX8_Texture(14, texture ? texture->Peek_D3D_Texture() : NULL);
+#endif
+}
+
+void WaterRenderObjClass::bindModernWaterCoastal(Real level, Bool river)
+{
+#if defined(__linux__)
+ auto *device = DX8Wrapper::_Get_D3D_Device();
+ PosixWaterCoastalEnd(device);
+ const char *option = getenv("ZH_WATER_SURF_GPU");
+ if (river || !option || strcmp(option, "1") != 0
+ || !m_modernCoastalReady || !m_modernRenderCamera)
+ return;
+
+ const Vector2 ndc[5] = {
+ Vector2(0, 0), Vector2(-1, -1), Vector2(1, -1), Vector2(1, 1), Vector2(-1, 1)
+ };
+ WaterFoamWindow::Point rays[5];
+ for (unsigned i = 0; i < 5; ++i) {
+ Vector3 target;
+ m_modernRenderCamera->Un_Project(target, ndc[i]);
+ const Vector3 direction = target - m_modernCamera;
+ rays[i] = {direction.X, direction.Y, direction.Z};
+ }
+ const auto window = WaterFoamWindow::Choose(
+ {
+ m_modernCamera.X, m_modernCamera.Y, m_modernCamera.Z
+ }, rays, level);
+ const WaterShoreHistory::Mapping mapping = {
+ window.originX, window.originY, window.widthWorld, window.heightWorld,
+ window.widthPixels, window.heightPixels
+ };
+ if (!m_modernCoastalViewReady || m_modernCoastalViewLevel != level
+ || !WaterCoastalView::SameMapping(mapping, m_modernCoastalMapping)) {
+ m_modernCoastalViewReady = WaterCoastalView::Build(
+ m_modernCoastalDomain, mapping, level, m_modernCoastalLookup);
+ if (m_modernCoastalViewReady) {
+ m_modernCoastalMapping = mapping;
+ m_modernCoastalViewLevel = level;
+ }
+ }
+ if (m_modernCoastalViewReady)
+ PosixWaterCoastalBind(device, m_modernCoastalRevision, m_modernCoastalDomain,
+ m_modernCoastalMapping, level, m_modernCoastalLookup);
+#endif
+}
+
+void WaterRenderObjClass::registerWaterStyleShaders(void)
+{
+#if defined(__linux__)
+ const Bool modern = m_useModernWater;
+#elif defined(_WIN32)
+ // Keep the original shader identities on Windows.
+ const Bool modern = TRUE;
+#else
+ // The SDL renderer uses explicit legacy variants outside Linux.
+ const Bool modern = FALSE;
+#endif
+ if (m_riverWaterPixelShader)
+ Direct3D11_Register_Engine_Shader(m_riverWaterPixelShader, modern
+ ? "river water ps.1.1" : "classic river water ps.1.1");
+ if (m_trapezoidWaterPixelShader)
+ Direct3D11_Register_Engine_Shader(m_trapezoidWaterPixelShader, modern
+ ? "trapezoid water ps.1.1" : "classic trapezoid water ps.1.1");
+}
+
+void WaterRenderObjClass::synchronizeWaterStyle(void)
+{
+#if defined(__linux__)
+ const Bool modern = !TheGlobalData || TheGlobalData->m_waterStyle != 0;
+ if (modern == m_useModernWater) return;
+
+ // Apply before any reflected or main-scene water draw. Existing recorded draws keep
+ // their immutable GPU programs; both styles have separate program/pipeline cache keys.
+ m_useModernWater = modern;
+ registerWaterStyleShaders();
+ clearModernWaterFoam();
+ clearModernWaterHulls();
+ invalidateModernWaterShore();
+ m_modernProjectedSamples.clear();
+ m_modernObstacles.clear();
+ m_modernPatchObstacles.clear();
+ m_modernObstacleIndex.Clear();
+ m_modernProfile = ModernWaterProfile();
+ m_modernProfileEnabled = FALSE;
+
+ // Classic clears the mirror to white; Modern clears it transparent. Bypass the
+ // stationary-camera reuse once, so neither style samples the other's background.
+ m_reflectionReused = TRUE;
+ // Keep wave time, capture/pause clock, gameplay levels and water-grid motion intact.
+#endif
+}
+
+void WaterRenderObjClass::setupModernWaterShader(Bool river, Bool heightCorrection, Bool waveCage)
+{
+#if defined(__linux__)
+ if (!m_useModernWater) return;
+ updateModernWaterTextures();
+ const Bool reflection = m_pReflectionTexture && !m_renderingMirror &&
+ m_reflectionAreaMax.X > m_reflectionAreaMin.X && m_reflectionAreaMax.Y > m_reflectionAreaMin.Y;
+ TextureClass *mirror = reflection ? m_pReflectionTexture : m_whiteTexture;
+ if (!mirror->Is_Initialized()) mirror->Init();
+ DX8Wrapper::Set_DX8_Texture(1, mirror->Peek_D3D_Texture());
+ DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP);
+ DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP);
+ DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DSAMP_MIPFILTER, D3DTEXF_NONE);
+ const D3DXVECTOR4 parameters(m_modernWaveTime,
+ river ? 1.0f : 0.0f, reflection ? 1.0f : 0.0f, m_reflectionLevel);
+ const D3DXVECTOR4 area(m_reflectionAreaMin.X, m_reflectionAreaMin.Y,
+ m_reflectionAreaMax.X, m_reflectionAreaMax.Y);
+ const Coord3D &sun = TheGlobalData->m_terrainLightPos[0];
+ const RGBColor &colour = TheGlobalData->m_terrainDiffuse[0];
+ const D3DXVECTOR4 direction(-sun.x, -sun.y, -sun.z, 0.0f);
+ const D3DXVECTOR4 light(colour.red, colour.green, colour.blue, 0.0f);
+ DX8Wrapper::_Get_D3D_Device()->SetPixelShaderConstantF(1, parameters, 1);
+ DX8Wrapper::_Get_D3D_Device()->SetPixelShaderConstantF(2, area, 1);
+ DX8Wrapper::_Get_D3D_Device()->SetPixelShaderConstantF(3, direction, 1);
+ DX8Wrapper::_Get_D3D_Device()->SetPixelShaderConstantF(4, light, 1);
+ WorldHeightMap *map = TheTerrainRenderObject ? TheTerrainRenderObject->getMap() : NULL;
+ const D3DXVECTOR4 terrain(map ? map->getBorderSize() * MAP_XY_FACTOR : 0.0f,
+ m_modernHeightSide * MAP_XY_FACTOR, 255.0f * MAP_HEIGHT_SCALE, m_modernHeightTexture ? 1.0f : 0.0f);
+ DX8Wrapper::_Get_D3D_Device()->SetPixelShaderConstantF(5, terrain, 1);
+ TextureClass *optical = river ? NULL : modernWaterOpticalTexture(m_modernOpticalLevel);
+ const D3DXVECTOR4 optics(TheWaterTransparency->m_transparentWaterDepth,
+ TheWaterTransparency->m_minWaterOpacity, optical ? 1.0f : 0.0f, heightCorrection && !river ? 1.0f : 0.0f);
+ DX8Wrapper::_Get_D3D_Device()->SetPixelShaderConstantF(6, optics, 1);
+ D3DXVECTOR4 materialColor, materialParameters;
+ getModernWaterMaterial(&materialColor.x, &materialParameters.x);
+ DX8Wrapper::_Get_D3D_Device()->SetPixelShaderConstantF(ModernWaterMaterial::RegisterColor, materialColor, 1);
+ DX8Wrapper::_Get_D3D_Device()->SetPixelShaderConstantF(ModernWaterMaterial::RegisterParameters, materialParameters, 1);
+ const RGBColor &ambient = TheGlobalData->m_terrainAmbient[0];
+ const D3DXVECTOR4 hullParameters(river ? 0.0f : float(m_modernHulls.size()), ambient.red, ambient.green, ambient.blue);
+ DX8Wrapper::_Get_D3D_Device()->SetPixelShaderConstantF(7, hullParameters, 1);
+ // Match the terrain's authored ambient + up to three directional lights. Reset all
+ // fill slots on every draw so a later one-light map cannot inherit old illumination.
+ D3DXVECTOR4 foamFillLights[4] = {D3DXVECTOR4(0, 0, 0, 0), D3DXVECTOR4(0, 0, 0, 0),
+ D3DXVECTOR4(0, 0, 0, 0), D3DXVECTOR4(0, 0, 0, 0)};
+ foamFillLights[0].w = TheGlobalData->m_numGlobalLights > 0 ? 1.0f : 0.0f;
+ for (Int lightIndex = 1; lightIndex < min(3, TheGlobalData->m_numGlobalLights); ++lightIndex) {
+ const Coord3D &position = TheGlobalData->m_terrainLightPos[lightIndex];
+ const RGBColor &diffuse = TheGlobalData->m_terrainDiffuse[lightIndex];
+ Vector3 fillDirection(-position.x, -position.y, -position.z);
+ const float magnitude = fillDirection.Length();
+ if (magnitude > 0.000001f) fillDirection /= magnitude;
+ else fillDirection = Vector3(0, 0, 0);
+ const Int slot = (lightIndex - 1) * 2;
+ foamFillLights[slot].x = fillDirection.X;
+ foamFillLights[slot].y = fillDirection.Y;
+ foamFillLights[slot].z = fillDirection.Z;
+ foamFillLights[slot + 1] = D3DXVECTOR4(diffuse.red, diffuse.green, diffuse.blue, 0);
+ }
+ DX8Wrapper::_Get_D3D_Device()->SetPixelShaderConstantF(90, &foamFillLights[0].x, 4);
+ if (!river && !m_modernHulls.empty()) {
+ DX8Wrapper::_Get_D3D_Device()->SetPixelShaderConstantF(8, &m_modernHulls[0].data[0][0],
+ m_modernHulls.size() * WaterHullModel::RegistersPerHull);
+ DX8Wrapper::_Get_D3D_Device()->SetPixelShaderConstantF(96, &m_modernContactHulls[0].data[0][0],
+ m_modernContactHulls.size() * WaterHullModel::RegistersPerHull);
+ }
+ if (WaterHullVisual::Enabled()) {
+ // Every slot is initialized, including absent hulls and river draws. The backend takes
+ // immutable draw snapshots before a different surface can replace these registers.
+ float metadata[WaterHullVisualLayout::MaxHulls][4] = {};
+ float packets[WaterHullVisualLayout::PacketRegisters][4] = {};
+ if (!river) for (unsigned h = 0; h < m_modernVisualHulls.size() && h < WaterHullVisualLayout::MaxHulls; ++h) {
+ memcpy(metadata[h], m_modernVisualHulls[h].metadata, sizeof(metadata[h]));
+ memcpy(packets[h * WaterHullVisualLayout::RegistersPerHull], m_modernVisualHulls[h].data, sizeof(m_modernVisualHulls[h].data));
+ }
+ DX8Wrapper::_Get_D3D_Device()->SetPixelShaderConstantF(WaterHullVisualLayout::MetadataRegister,
+ &metadata[0][0], WaterHullVisualLayout::MaxHulls);
+ DX8Wrapper::_Get_D3D_Device()->SetPixelShaderConstantF(WaterHullVisualLayout::PacketRegister,
+ &packets[0][0], WaterHullVisualLayout::PacketRegisters);
+ }
+ DX8Wrapper::Set_DX8_Texture(4, optical ? optical->Peek_D3D_Texture() : NULL);
+ bindModernWaterFoam(m_modernOpticalLevel, river);
+ bindModernWaterCoastal(m_modernOpticalLevel, river);
+ TextureClass *heightTexture = m_modernHeightTexture;
+ if (waveCage && !river && heightCorrection)
+ for (const ModernOpticalTexture &cached : m_modernOpticalTextures)
+ if (cached.level == m_modernOpticalLevel && cached.waveCage) {
+ heightTexture = cached.waveCage;
+ break;
+ }
+ DX8Wrapper::Set_DX8_Texture(2, heightTexture ? heightTexture->Peek_D3D_Texture() : NULL);
+ if (m_modernBedTexture) {
+ DX8Wrapper::Set_DX8_Texture(7, m_modernBedTexture->Peek_D3D_Texture());
+ // Sampling policy is local to the POSIX water draw, leaving the device's stage-7 state intact.
+ }
+ // The modern surface carries displacement damping and its original elevation in UV1.
+ // Only the new flat-patch mesh uses UV0 for a geometric height correction. Legacy grids
+ // and rivers retain their authored base UVs; stale texture matrices must not transform metadata.
+ if (heightCorrection && !river) {
+ DX8Wrapper::Set_DX8_Texture_Stage_State(0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_PASSTHRU|0);
+ DX8Wrapper::Set_DX8_Texture_Stage_State(0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE);
}
+ DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DTSS_TEXCOORDINDEX, 1);
+ DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE);
+ DX8Wrapper::Set_DX8_Texture_Stage_State(2, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP);
+ DX8Wrapper::Set_DX8_Texture_Stage_State(2, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP);
+ DX8Wrapper::Set_DX8_Texture_Stage_State(2, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
+ DX8Wrapper::Set_DX8_Texture_Stage_State(2, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
+ DX8Wrapper::Set_DX8_Texture_Stage_State(2, D3DSAMP_MIPFILTER, D3DTEXF_NONE);
+#endif
+}
+
+// Bed material detail and its mip chain are generated once and ship with the executable.
+// The terrain fallback refreshes when the map heights or dimensions change.
+void WaterRenderObjClass::updateModernWaterTextures(void)
+{
+#if defined(__linux__)
+ if (!m_modernBedTexture) {
+ const Int side=256;
+ std::vector<UnsignedInt> pixels(side*side);
+ for (Int y=0;y<side;++y) for (Int x=0;x<side;++x) pixels[y*side+x]=WaterBedMaterial::Texel(x,y,side);
+ m_modernBedTexture=NEW_REF(TextureClass,(side,side,WW3D_FORMAT_A8R8G8B8,MIP_LEVELS_ALL));
+ for (Int size=side,level=0;size>0;size/=2,++level) {
+ SurfaceClass *surface=m_modernBedTexture->Get_Surface_Level(level);
+ Int pitch; void *bits=surface->Lock(&pitch);
+ if (bits) {
+ for (Int y=0;y<size;++y) memcpy((char*)bits+y*pitch,&pixels[y*size],size*4);
+ surface->Unlock();
+ }
+ REF_PTR_RELEASE(surface);
+ if (size==1) break;
+ std::vector<UnsignedInt> mip(size*size/4);
+ for (Int y=0;y<size/2;++y) for (Int x=0;x<size/2;++x) {
+ UnsignedInt packed=0;
+ for (Int shift=0;shift<32;shift+=8) {
+ UnsignedInt sum=0;
+ for (Int j=0;j<2;++j) for (Int i=0;i<2;++i) sum+=(pixels[(2*y+j)*size+2*x+i]>>shift)&255;
+ packed|=((sum+2)/4)<<shift;
+ }
+ mip[y*(size/2)+x]=packed;
+ }
+ pixels.swap(mip);
+ }
+ }
+ WorldHeightMap *map = TheTerrainRenderObject ? TheTerrainRenderObject->getMap() : NULL;
+ if (!map || map->getXExtent()<=0 || map->getYExtent()<=0 || !map->getDataPtr()) {
+ m_modernBowAdmissions.Clear();
+ if(m_modernHeightMap || m_modernShoreReady) invalidateModernWaterShore();
+ clearModernWaterOpticalTextures();
+ REF_PTR_RELEASE(m_modernHeightTexture);
+ m_modernHeights.clear();
+ m_modernHeightWidth=0; m_modernHeightHeight=0; m_modernHeightSide=0; m_modernHeightBorder=-1;
+ m_modernHeightMap=NULL; m_modernHeightData=NULL;
+ return;
+ }
+ const Int width = map->getXExtent(), height = map->getYExtent();
+ const size_t count = (size_t)width * height;
+ const Bool sameTerrain=map == m_modernHeightMap && map->getDataPtr() == m_modernHeightData &&
+ map->getBorderSize() == m_modernHeightBorder && width == m_modernHeightWidth && height == m_modernHeightHeight &&
+ m_modernHeights.size() == count && memcmp(m_modernHeights.data(), map->getDataPtr(), count) == 0;
+ if(sameTerrain && m_modernHeightTexture) return;
+ if(!sameTerrain) invalidateModernWaterShore();
+ if(m_modernHeightMap && (m_modernHeightMap!=map || m_modernHeightData!=map->getDataPtr())) { clearModernWaterFoam();m_modernBowAdmissions.Clear(); }
+ clearModernWaterOpticalTextures();
+ m_modernHeightMap=map; m_modernHeightData=map->getDataPtr();
+ m_modernHeightBorder=map->getBorderSize();
+ m_modernHeights.assign(map->getDataPtr(), map->getDataPtr() + count);
+ if (width != m_modernHeightWidth || height != m_modernHeightHeight || !m_modernHeightTexture) {
+ REF_PTR_RELEASE(m_modernHeightTexture);
+ m_modernHeightSide = 1; while (m_modernHeightSide < max(width,height)) m_modernHeightSide *= 2;
+ m_modernHeightTexture = NEW_REF(TextureClass, (m_modernHeightSide, m_modernHeightSide, WW3D_FORMAT_A8R8G8B8, MIP_LEVELS_1));
+ }
+ m_modernHeightWidth = width; m_modernHeightHeight = height;
+ SurfaceClass *surface = m_modernHeightTexture->Get_Surface_Level();
+ Int pitch; void *bits = surface->Lock(&pitch);
+ if (bits) {
+ for (Int y = 0; y < m_modernHeightSide; ++y) for (Int x = 0; x < m_modernHeightSide; ++x) {
+ const UnsignedInt h = map->getHeight(min(x,width-1), min(y,height-1));
+ // Alpha zero makes the height-only fallback explicitly opt out of wave cages.
+ ((UnsignedInt *)((char *)bits+y*pitch))[x] = (h<<16) | (h<<8) | h;
+ }
+ surface->Unlock();
+ }
+ REF_PTR_RELEASE(surface);
+#endif
+}
+
+void WaterRenderObjClass::clearModernWaterOpticalTextures(void)
+{
+ m_modernProjectedSamples.clear();
+ m_modernObstacleIndex.Clear();
+ for (size_t i=0;i<m_modernOpticalTextures.size();++i) {
+ REF_PTR_RELEASE(m_modernOpticalTextures[i].texture);
+ REF_PTR_RELEASE(m_modernOpticalTextures[i].waveCage);
+ }
+ m_modernOpticalTextures.clear();
+}
+
+void WaterRenderObjClass::refreshModernWaterOpticalPolygons(void)
+{
+#if defined(__linux__)
+ std::vector<WaterOpticalContext::Polygon> polygons;
+ size_t points=0;
+ Bool valid=TRUE;
+ for (PolygonTrigger *trigger=PolygonTrigger::getFirstPolygonTrigger();trigger;trigger=trigger->getNext()) {
+ if (!trigger->isWaterArea() || trigger->isRiver() || trigger->getNumPoints()<3) continue;
+ if ((size_t)trigger->getNumPoints()>WaterOpticalContext::MaxPoints-points) { valid=FALSE; break; }
+ points+=trigger->getNumPoints();
+ WaterOpticalContext::Polygon polygon;
+ polygon.points.reserve(trigger->getNumPoints());
+ for (Int i=0;i<trigger->getNumPoints();++i) {
+ const ICoord3D *p=trigger->getPoint(i);
+ polygon.points.push_back({(float)p->x,(float)p->y,(float)p->z});
+ }
+ polygons.push_back(polygon);
+ }
+ if (valid!=m_modernOpticalPolygonsValid || !WaterOpticalContext::SamePolygons(polygons,m_modernOpticalPolygons)) {
+ invalidateModernWaterShore();
+ clearModernWaterOpticalTextures();
+ if(m_modernOpticalPolygonsValid) { clearModernWaterFoam();m_modernBowAdmissions.Clear(); }
+ m_modernOpticalPolygons.swap(polygons);
+ m_modernOpticalPolygonsValid=valid;
+ }
+#endif
+}
+
+TextureClass *WaterRenderObjClass::modernWaterOpticalTexture(Real level)
+{
+#if defined(__linux__)
+ if (!m_modernOpticalPolygonsValid) return NULL;
+ for (size_t i=0;i<m_modernOpticalTextures.size();++i)
+ if (m_modernOpticalTextures[i].level==level) return m_modernOpticalTextures[i].texture;
+ // Keep the first levels for this map revision. Overflow stays on the clear-water profile instead
+ // of evicting/rebuilding textures every frame on maps with many water elevations.
+ if (m_modernOpticalTextures.size()>=WaterOpticalContext::MaxLevels) return NULL;
+ m_modernOpticalTextures.push_back({level,NULL});
+ WaterOpticalContext::Field field;
+ if (!WaterOpticalContext::Build(m_modernHeights.empty()?NULL:m_modernHeights.data(),
+ m_modernHeightWidth,m_modernHeightHeight,m_modernHeightBorder,MAP_XY_FACTOR,MAP_HEIGHT_SCALE,
+ level,m_modernOpticalPolygons,field)) return NULL;
+ m_modernOpticalTextures.back().shoreContext=field;
+ TextureClass *texture=NEW_REF(TextureClass,(m_modernHeightSide,m_modernHeightSide,WW3D_FORMAT_A8R8G8B8,MIP_LEVELS_1));
+ SurfaceClass *surface=texture->Get_Surface_Level();
+ Int pitch; void *bits=surface->Lock(&pitch);
+ if (bits) {
+ for (Int y=0;y<m_modernHeightSide;++y) for (Int x=0;x<m_modernHeightSide;++x) {
+ const size_t n=(size_t)min(y,m_modernHeightHeight-1)*m_modernHeightWidth+min(x,m_modernHeightWidth-1);
+ ((UnsignedInt*)((char*)bits+y*pitch))[x]=WaterOpticalContext::Texel(field,n);
+ }
+ surface->Unlock();
+ }
+ REF_PTR_RELEASE(surface);
+ if (!bits) { REF_PTR_RELEASE(texture); return NULL; }
+ ModernOpticalTexture &cached=m_modernOpticalTextures.back();
+ cached.texture=texture;
+ const char *waveCageOption=getenv("ZH_WATER_WAVE_CAGES");
+ if(WaterFftSampling::Enabled() && (!waveCageOption || strcmp(waveCageOption,"0")!=0)) {
+ WaterWaveCage::Field cage;
+ if(WaterWaveCage::Build(m_modernHeights.data(),m_modernHeightWidth,m_modernHeightHeight,
+ m_modernHeightBorder,MAP_XY_FACTOR,MAP_HEIGHT_SCALE,level,field,cage)) {
+ TextureClass *cageTexture=NEW_REF(TextureClass,(m_modernHeightSide,m_modernHeightSide,WW3D_FORMAT_A8R8G8B8,MIP_LEVELS_1));
+ SurfaceClass *cageSurface=cageTexture?cageTexture->Get_Surface_Level():NULL;
+ Int cagePitch=0;void *cageBits=cageSurface?cageSurface->Lock(&cagePitch):NULL;
+ const Bool uploaded=cageBits && cagePitch>=m_modernHeightSide*4;
+ if(uploaded)
+ for(Int y=0;y<m_modernHeightSide;++y) for(Int x=0;x<m_modernHeightSide;++x) {
+ const size_t n=size_t(min(y,m_modernHeightHeight-1))*m_modernHeightWidth+min(x,m_modernHeightWidth-1);
+ ((UnsignedInt*)((char*)cageBits+y*cagePitch))[x]=WaterWaveCage::Texel(cage,n);
+ }
+ if(cageBits) cageSurface->Unlock();
+ REF_PTR_RELEASE(cageSurface);
+ if(uploaded) {
+ cached.waveCage=cageTexture;
+ cached.waveCageSupport.resize(cage.texels.size());
+ for(size_t n=0;n<cage.texels.size();++n) cached.waveCageSupport[n]=UnsignedByte(cage.texels[n]>>24);
+ }
+ else REF_PTR_RELEASE(cageTexture); // fall back to the original height texture, with zero support
+ }
+ }
+ cached.ocean.swap(field.ocean);
+ // Retain exactly the bytes uploaded to Texture4, including its bilinear shoreline blend.
+ Int oceanMinX=m_modernHeightWidth,oceanMinY=m_modernHeightHeight,oceanMaxX=-1,oceanMaxY=-1;
+ for (Int y=0;y<m_modernHeightHeight;++y) for (Int x=0;x<m_modernHeightWidth;++x)
+ if (cached.ocean[y*m_modernHeightWidth+x]) {
+ oceanMinX=min(oceanMinX,x);oceanMinY=min(oceanMinY,y);oceanMaxX=max(oceanMaxX,x);oceanMaxY=max(oceanMaxY,y);
+ }
+ if (oceanMaxX>=0) cached.oceanExtent=max(oceanMaxX-oceanMinX,oceanMaxY-oceanMinY)*MAP_XY_FACTOR;
+ return texture;
+#else
+ return NULL;
+#endif
}
@@ -381,6 +1599,9 @@ WaterRenderObjClass::~WaterRenderObjClass(void)
//-------------------------------------------------------------------------------------------------
WaterRenderObjClass::WaterRenderObjClass(void)
{
+#if defined(__linux__)
+ m_useModernWater = !TheGlobalData || TheGlobalData->m_waterStyle != 0;
+#endif
memset( &m_settings, 0, sizeof( m_settings ) );
m_dx=0;
m_dy=0;
@@ -406,6 +1627,7 @@ WaterRenderObjClass::WaterRenderObjClass(void)
m_dwWavePixelShader=NULL;
m_dwWaveVertexShader=NULL;
+ m_waveVertexDeclaration=NULL;
m_meshGeneration = 0;
m_drawnCellsX = 0;
m_drawnCellsY = 0;
@@ -415,8 +1637,10 @@ WaterRenderObjClass::WaterRenderObjClass(void)
m_drawnTransform.Make_Identity();
Int i=NUM_BUMP_FRAMES;
- while (i--)
+ while (i--) {
m_pBumpTexture[i]=NULL;
+ m_pBumpTexture2[i]=NULL;
+ }
m_riverVOrigin=0;
m_riverTexture=NULL;
@@ -457,7 +1681,7 @@ void WaterRenderObjClass::Get_Obj_Space_Bounding_Box(AABoxClass & box) const
//let's disable culling by making bounds huge. Let each piece do it's own cull.
Vector3 ObjSpaceCenter(0,0,0);
- Vector3 ObjSpaceExtents(50000,50000,0.001f*m_dy); //since mirror is a plane, it has no thickness. Set to m_dy/1000.
+ Vector3 ObjSpaceExtents(50000,50000,max(0.001f*m_dy,WaterSurfaceModel::MaxDisplacement)); //since mirror is a plane, it has no thickness. Set to m_dy/1000.
box.Init(ObjSpaceCenter,ObjSpaceExtents);
}
@@ -883,6 +2107,15 @@ RenderResult WaterRenderObjClass::generateIndexBuffer(Int sizeX, Int sizeY)
//-------------------------------------------------------------------------------------------------
void WaterRenderObjClass::ReleaseResources(void)
{
+ clearModernWaterFoam(FALSE);
+ // CPU admissions survive device resource refresh, including a resize while paused.
+ clearModernWaterHulls(FALSE);
+ REF_PTR_RELEASE(m_modernHeightTexture);
+ REF_PTR_RELEASE(m_modernBedTexture);
+ clearModernWaterOpticalTextures();
+ m_modernObstacles.clear();
+
+ // CPU terrain/source/history survive texture-only resize; the next update compares real geometry.
REF_PTR_RELEASE(m_indexBuffer);
@@ -1022,7 +2255,6 @@ void WaterRenderObjClass::ReAcquireResources(void)
if (hr==0) {
hr = DX8Wrapper::_Get_D3D_Device()->CreatePixelShader((RenderUInt32*)compiledShader->GetBufferPointer(), &m_riverWaterPixelShader);
compiledShader->Release();
- Direct3D11_Register_Engine_Shader(m_riverWaterPixelShader, "river water ps.1.1");
}
shader =
"ps.1.1\n \
@@ -1052,7 +2284,6 @@ void WaterRenderObjClass::ReAcquireResources(void)
if (hr==0) {
hr = DX8Wrapper::_Get_D3D_Device()->CreatePixelShader((RenderUInt32*)compiledShader->GetBufferPointer(), &m_trapezoidWaterPixelShader);
compiledShader->Release();
- Direct3D11_Register_Engine_Shader(m_trapezoidWaterPixelShader, "trapezoid water ps.1.1");
}
shader =
"ps.1.1\n \
@@ -1073,6 +2304,8 @@ void WaterRenderObjClass::ReAcquireResources(void)
}
}
+ registerWaterStyleShaders();
+
//W3D Invalidate textures after losing the device and since we peek at the textures directly, it won't
//know to reinit them for us. Do it here manually:
if (m_riverTexture && !m_riverTexture->Is_Initialized())
@@ -1264,6 +2497,15 @@ void WaterRenderObjClass::updateMapOverrides(void)
// ------------------------------------------------------------------------------------------------
void WaterRenderObjClass::reset( void )
{
+ invalidateModernWaterShore();
+ clearModernWaterFoam();
+ clearModernWaterHulls();
+ // TerrainVisual reuses this object across map lifetimes. Release per-level optical resources
+ // even if the next map happens to reuse the same terrain allocation and polygon coordinates.
+ clearModernWaterOpticalTextures();
+ m_modernOpticalPolygons.clear();
+ m_modernOpticalPolygonsValid=FALSE;
+ m_modernHeightMap=NULL; m_modernHeightData=NULL;
// the vertex animated water mesh is zeroed by TerrainLogic::reset, which owns it now
@@ -1343,6 +2585,7 @@ void WaterRenderObjClass::update( void )
// the client's pass, ahead of the draw and with no tick running: the grid the draw will read
takeGridForDraw();
+ synchronizeWaterStyle();
//
// The river scroll and the bump flipbook used to advance once per call, which is once per
// RENDER frame. That was fine when the loop was capped and wrong now that it is not, and
@@ -1360,8 +2603,6 @@ void WaterRenderObjClass::update( void )
// frame longer, and at 0.2 that is six frames a second - the eye reads that as a stutter, not
// as slow water. So the flipbook keeps its authored rate and only the scroll is scaled.
//
- const Real WATER_SCROLL_SPEED = 0.2f;
- const Real AUTHORED_FPS = 30.0f;
const Real BUMP_FRAMES_PER_SEC = AUTHORED_FPS;
{
@@ -1386,9 +2627,17 @@ void WaterRenderObjClass::update( void )
elapsedSec = 0.1f; // a level load must not jump the surface forward
// a pause or a script's time freeze stops every unit and particle; the water stops with them
- if (TheGameLogic->isGamePaused() || TheScriptEngine->isTimeFrozenScript() || TheScriptEngine->isTimeFrozenDebug())
- elapsedSec = 0.0f;
-
+ const Bool waterFrozen=TheGameLogic->isGamePaused() || TheScriptEngine->isTimeFrozenScript() || TheScriptEngine->isTimeFrozenDebug();
+ if (waterFrozen) elapsedSec = 0.0f;
+
+ m_modernWaveTime = WaterSurfaceModel::AdvanceTime(m_modernWaveTime, elapsedSec, false, false, false);
+#if defined(__linux__)
+ // Client updates are independent of water visibility and reflected render recursion.
+ // Build every level once, then advance the fixed-world source even when the camera pans away.
+ if(m_useModernWater && m_trapezoidWaterPixelShader) {
+ updateModernWaterTextures();refreshModernWaterOpticalPolygons();updateModernWaterShore();
+ }
+#endif
const Real step = elapsedSec * AUTHORED_FPS * WATER_SCROLL_SPEED;
m_riverVOrigin += 0.002f * step;
@@ -1522,7 +2771,9 @@ void WaterRenderObjClass::loadSetting( Setting *setting, TimeOfDay timeOfDay )
//-------------------------------------------------------------------------------------------------
void WaterRenderObjClass::updateRenderTargetTextures(CameraClass *cam)
{
- if (!TheTerrainRenderObject || !TheTerrainRenderObject->getMap())
+ // This render boundary also runs while the game/options menu is paused.
+ synchronizeWaterStyle();
+ if (!cam || !TheTerrainRenderObject || !TheTerrainRenderObject->getMap())
return;
if (m_waterType == WATER_TYPE_2_PVSHADER && getClippedWaterPlane(cam, NULL))
@@ -1647,7 +2898,15 @@ void WaterRenderObjClass::renderMirror(CameraClass *cam, Real level)
// Clear the backbuffer
// The sea's cloud plane fills its background; map water has no such plane, so its target is
// cleared to white, which the overlay multiplies in as no change at all.
+#if !defined(__linux__)
WW3D::Begin_Render(m_waterType == WATER_TYPE_0_TRANSLUCENT,true,WATER_REFLECTION_SKY_COLOR);
+#else
+ // Modern water supplies its own sky. Classic multiplies a white-background mirror.
+ if (m_useModernWater)
+ WW3D::Begin_Render(m_waterType == WATER_TYPE_0_TRANSLUCENT,true,Vector3(0,0,0),0.0f);
+ else
+ WW3D::Begin_Render(m_waterType == WATER_TYPE_0_TRANSLUCENT,true,WATER_REFLECTION_SKY_COLOR);
+#endif
cam->Set_Transform( reflectedTransform );
@@ -1685,7 +2944,9 @@ void WaterRenderObjClass::renderMirror(CameraClass *cam, Real level)
cam->Set_Oblique_Near_Plane(&waterSurface);
cam->Apply();
+ m_renderingMirror = TRUE;
WW3D::Render(m_parentScene,cam);
+ m_renderingMirror = FALSE;
cam->Set_Oblique_Near_Plane(NULL);
cam->Set_Transform(OldCameraMatrix); //restore original non-reflected matrix
@@ -1714,6 +2975,12 @@ void WaterRenderObjClass::renderMirror(CameraClass *cam, Real level)
* This algorithm doesn't apply to translucent water, which is rendered into a
* texture and rendered at end of scene. */
//-------------------------------------------------------------------------------------------------
+#if defined(__linux__)
+static double modernWaterProfileMilliseconds()
+{
+ return std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now().time_since_epoch()).count();
+}
+#endif
DECLARE_PERF_TIMER(Water)
void WaterRenderObjClass::Render(RenderInfoClass & rinfo)
{
@@ -1747,6 +3014,118 @@ void WaterRenderObjClass::Render(RenderInfoClass & rinfo)
return;
}
+#if defined(__linux__)
+ WaterShoreOverlay::Scope shoreScope(DX8Wrapper::_Get_D3D_Device(),
+ m_useModernWater && m_waterType==WATER_TYPE_0_TRANSLUCENT && m_trapezoidWaterPixelShader &&
+ !TheGlobalData->m_isWorldBuilder && !TheGlobalData->m_usingWaterTrackEditor);
+ m_modernProfileEnabled=m_useModernWater && std::getenv("ZH_WATER_PROFILE")!=NULL;
+ m_modernFoamDrawFrame=~0u;m_modernFoamDrawObjectIDs.clear();
+ const double profileRenderStart=m_modernProfileEnabled?modernWaterProfileMilliseconds():0;
+ RenderUInt32 oldModernCoordIndex=0,oldModernTransformFlags=0;
+ RenderUInt32 oldModernBaseCoordIndex=0,oldModernBaseTransformFlags=0;
+ IDirect3DBaseTexture9 *oldModernBed=NULL,*oldModernOptical=NULL,*oldModernFoam=NULL;
+ if (m_useModernWater) {
+ DX8Wrapper::_Get_D3D_Device()->GetTextureStageState(0,D3DTSS_TEXCOORDINDEX,&oldModernBaseCoordIndex);
+ DX8Wrapper::_Get_D3D_Device()->GetTextureStageState(0,D3DTSS_TEXTURETRANSFORMFLAGS,&oldModernBaseTransformFlags);
+ DX8Wrapper::_Get_D3D_Device()->GetTextureStageState(1,D3DTSS_TEXCOORDINDEX,&oldModernCoordIndex);
+ DX8Wrapper::_Get_D3D_Device()->GetTextureStageState(1,D3DTSS_TEXTURETRANSFORMFLAGS,&oldModernTransformFlags);
+ DX8Wrapper::_Get_D3D_Device()->GetTexture(7,&oldModernBed);
+ DX8Wrapper::_Get_D3D_Device()->GetTexture(4,&oldModernOptical);
+ DX8Wrapper::_Get_D3D_Device()->GetTexture(14,&oldModernFoam);
+ updateModernWaterTextures();
+ refreshModernWaterOpticalPolygons();
+ m_modernRenderCamera=&rinfo.Camera;
+ m_modernCamera=rinfo.Camera.Get_Position();
+ Int modernPatches=0,modernFlatPatches=0,visibleFlatPatches=0;
+ Real highestModernWater=m_level;
+ Bool hasModernWater=FALSE;
+ for (PolygonTrigger *trigger=PolygonTrigger::getFirstPolygonTrigger();trigger;trigger=trigger->getNext()) {
+ if (!trigger->isWaterArea() || trigger->getNumPoints()<3) continue;
+ modernPatches+=trigger->isRiver() ? max(0,trigger->getNumPoints()/2-1) :
+ ((trigger->getNumPoints()-1)/2);
+ if (!trigger->isRiver()) {
+ modernFlatPatches+=(trigger->getNumPoints()-1)/2;
+ // This count only controls sample reuse, never topology or density. Conservatively
+ // include every visible planar flat patch that could use the projected path.
+ for (Int k=1;k<trigger->getNumPoints()-1;k+=2) {
+ const Int corner[4]={k+2<trigger->getNumPoints()?k+2:k+1,k+1,k,0};
+ Vector3 minimum,maximum;float levels[4];
+ for (Int n=0;n<4;++n) {
+ const ICoord3D &p=*trigger->getPoint(corner[n]);levels[n]=float(p.z);
+ if (n==0) minimum=maximum=Vector3(float(p.x),float(p.y),float(p.z));
+ else { minimum.X=min(minimum.X,float(p.x));minimum.Y=min(minimum.Y,float(p.y));minimum.Z=min(minimum.Z,float(p.z));
+ maximum.X=max(maximum.X,float(p.x));maximum.Y=max(maximum.Y,float(p.y));maximum.Z=max(maximum.Z,float(p.z)); }
+ }
+ minimum.Z-=WaterSurfaceModel::MaxDisplacement;maximum.Z+=WaterSurfaceModel::MaxDisplacement;
+ minimum.X-=WaterFftGeometry::MaxHorizontalDisplacement;minimum.Y-=WaterFftGeometry::MaxHorizontalDisplacement;
+ maximum.X+=WaterFftGeometry::MaxHorizontalDisplacement;maximum.Y+=WaterFftGeometry::MaxHorizontalDisplacement;
+ if (WaterProjectedMesh::HasSingleLevel(levels) && fabsf(m_modernCamera.Z-levels[0])>WaterSurfaceModel::MaxDisplacement*2 &&
+ !rinfo.Camera.Cull_Box(AABoxClass((minimum+maximum)*0.5f,(maximum-minimum)*0.5f))) ++visibleFlatPatches;
+ }
+ }
+ for (Int point=0;point<trigger->getNumPoints();++point) {
+ const Real elevation=trigger->getPoint(point)->z;
+ if (!hasModernWater || elevation>highestModernWater) highestModernWater=elevation;
+ hasModernWater=TRUE;
+ }
+ }
+ // One map-wide subdivision count keeps all common edges welded. The authored polygon count
+ // itself is irreducible; added tessellation stays within the shared model's vertex budget.
+ for (size_t i=0;i<m_modernOpticalPolygons.size();++i) if (!m_modernOpticalPolygons[i].points.empty())
+ modernWaterOpticalTexture(m_modernOpticalPolygons[i].points[0].z);
+ updateModernWaterShore(); // same time is a no-op; also initializes before a first draw without a client update
+ // Rivers retain their old camera-height detail. Ocean interiors use a visible projected
+ // lattice and constrain boundary samples to these same morphed edge polylines.
+ const Int baseCells=WaterSurfaceModel::CellsForPatches(modernPatches);
+ const WaterSurfaceModel::MeshLOD modernLOD=WaterSurfaceModel::LODForCameraHeight(
+ baseCells,m_modernCamera.Z-highestModernWater);
+ m_modernMeshCells=modernLOD.cells;
+ m_modernMeshMorph=modernLOD.morph;
+ const size_t baseVertices=size_t(baseCells+1)*(baseCells+1);
+ const size_t retainedVertices=size_t(max(0,modernPatches-modernFlatPatches))*baseVertices;
+ const size_t available=retainedVertices<WaterSurfaceModel::VertexBudget?WaterSurfaceModel::VertexBudget-retainedVertices:0;
+ Int targetWidth,targetHeight,targetBits;bool targetWindowed;
+ WW3D::Get_Render_Target_Resolution(targetWidth,targetHeight,targetBits,targetWindowed);
+ const WaterProjectedMesh::Resolution projected=WaterProjectedMesh::ChooseResolution(targetWidth,targetHeight,modernFlatPatches,available,4u*(baseCells+1));
+ m_modernProjectedColumns=projected.columns;m_modernProjectedRows=projected.rows;
+ m_modernProjectedWidth=targetWidth;m_modernProjectedHeight=targetHeight;
+ m_modernProjectedBudget=min(size_t(60000),available/size_t(max(1,modernFlatPatches)));
+ // Per-frame reuse shares lattice vertices across flat patches/levels, while never keeping
+ // stale terrain, moving hulls, wave time or camera state from a previous render.
+ m_modernProjectedSamples.clear();
+ m_modernObstacleIndex.Clear();
+ m_modernProjectedVertices=m_modernProjectedTriangles=m_modernProjectedFallbacks=m_modernRetainedVertices=m_modernProjectedEvaluations=0;
+ m_modernProjectedCacheEnabled=visibleFlatPatches>1;
+ m_modernBowVertices=m_modernBowTriangles=m_modernBowRegions=m_modernBowDenied=m_modernBowRejected=0;
+ m_modernBowAdmissions.Begin(m_modernWaveTime);
+ double profilePhaseStart=0;
+ if (m_modernProfileEnabled) {
+ profilePhaseStart=modernWaterProfileMilliseconds();
+ m_modernProfile.setup+=profilePhaseStart-profileRenderStart;
+ }
+ updateModernWaterHulls();
+ if (m_modernProfileEnabled) {
+ const double now=modernWaterProfileMilliseconds();m_modernProfile.hulls+=now-profilePhaseStart;profilePhaseStart=now;
+ }
+ m_modernObstacles.clear();
+ if (TheGameLogic) for (const Object *object=TheGameLogic->getFirstObject();object;object=object->getNextObject()) {
+ if (object->isDestroyed() || !(object->isKindOf(KINDOF_STRUCTURE) || object->isKindOf(KINDOF_BRIDGE) || object->isKindOf(KINDOF_IMMOBILE))) continue;
+ const Coord3D &p=*object->getPosition();
+ const GeometryInfo &geometry=object->getGeometryInfo();
+ ModernWaterObstacle obstacle;
+ obstacle.position.Set(p.x,p.y,p.z);
+ obstacle.radius=geometry.getBoundingCircleRadius();
+ obstacle.height=geometry.getMaxHeightAbovePosition();
+ obstacle.box=geometry.getGeomType()==GEOMETRY_BOX;
+ obstacle.hasHull=modernHasHull((UnsignedInt)object->getID());
+ obstacle.major=geometry.getMajorRadius();obstacle.minor=geometry.getMinorRadius();
+ obstacle.cosine=cosf(object->getOrientation());obstacle.sine=sinf(object->getOrientation());
+ if (obstacle.radius>1.0f) m_modernObstacles.push_back(obstacle);
+ }
+ if (m_modernProfileEnabled) m_modernProfile.obstacles+=modernWaterProfileMilliseconds()-profilePhaseStart;
+ }
+#endif
+
switch(m_waterType)
{
case WATER_TYPE_0_TRANSLUCENT:
@@ -1889,6 +3268,29 @@ void WaterRenderObjClass::Render(RenderInfoClass & rinfo)
default:
break;
}//switch
+#if defined(__linux__)
+ if (m_useModernWater) {
+ DX8Wrapper::Set_DX8_Texture_Stage_State(0,D3DTSS_TEXCOORDINDEX,oldModernBaseCoordIndex);
+ DX8Wrapper::Set_DX8_Texture_Stage_State(0,D3DTSS_TEXTURETRANSFORMFLAGS,oldModernBaseTransformFlags);
+ DX8Wrapper::Set_DX8_Texture_Stage_State(1,D3DTSS_TEXCOORDINDEX,oldModernCoordIndex);
+ DX8Wrapper::Set_DX8_Texture_Stage_State(1,D3DTSS_TEXTURETRANSFORMFLAGS,oldModernTransformFlags);
+ DX8Wrapper::Set_DX8_Texture(7,oldModernBed);
+ if (oldModernBed) oldModernBed->Release();
+ DX8Wrapper::Set_DX8_Texture(4,oldModernOptical);
+ if (oldModernOptical) oldModernOptical->Release();
+ DX8Wrapper::Set_DX8_Texture(14,oldModernFoam);
+ if(oldModernFoam) oldModernFoam->Release();
+ m_modernBowAdmissions.End();
+ if (std::getenv("ZH_WATER_MESH_STATS")) {
+ static UnsignedInt reports=0;
+ if ((reports++%120)==0) fprintf(stderr,"[water-mesh] lattice=%dx%d projected_vertices=%zu evaluated_samples=%zu triangles=%zu retained_vertices=%zu fallbacks=%zu bow_vertices=%zu bow_triangles=%zu bow_regions=%zu bow_denied=%zu bow_rejected=%zu\n",
+ m_modernProjectedColumns,m_modernProjectedRows,m_modernProjectedVertices,m_modernProjectedEvaluations,
+ m_modernProjectedTriangles,m_modernRetainedVertices,m_modernProjectedFallbacks,
+ m_modernBowVertices,m_modernBowTriangles,m_modernBowRegions,m_modernBowDenied,m_modernBowRejected);
+ }
+ m_modernRenderCamera=NULL;
+ }
+#endif
if (TheGlobalData && TheGlobalData->m_drawSkyBox)
{ //center skybox around camera
@@ -1905,6 +3307,28 @@ void WaterRenderObjClass::Render(RenderInfoClass & rinfo)
if (m_waterTrackSystem)
m_waterTrackSystem->flush(rinfo);
+#if defined(__linux__)
+ if (m_modernProfileEnabled) {
+ m_modernProfile.render+=modernWaterProfileMilliseconds()-profileRenderStart;
+ m_modernProfile.vertices+=m_modernProjectedVertices+m_modernRetainedVertices;
+ m_modernProfile.triangles+=m_modernProjectedTriangles;
+ if (++m_modernProfile.frames>=120) {
+ const double frames=double(m_modernProfile.frames);
+ fprintf(stderr,"[water-profile] frames=%zu render_ms=%.4f setup_ms=%.4f hulls_ms=%.4f obstacles_ms=%.4f projected_mesh_ms=%.4f vertex_fill_ms=%.4f submit_ms=%.4f vertices=%.1f projected_triangles=%.1f patches=%.1f\n",
+ m_modernProfile.frames,m_modernProfile.render/frames,m_modernProfile.setup/frames,
+ m_modernProfile.hulls/frames,m_modernProfile.obstacles/frames,m_modernProfile.mesh/frames,
+ m_modernProfile.fill/frames,m_modernProfile.submit/frames,m_modernProfile.vertices/frames,
+ m_modernProfile.triangles/frames,m_modernProfile.patches/frames);
+ const double scale=m_modernProfile.samples?double(m_modernProfile.attempts)/(m_modernProfile.samples*frames):0;
+ fprintf(stderr,"[water-profile-sampled] samples=%zu field_ms=%.4f damping_ms=%.4f wave_ms=%.4f cache_ms=%.4f patch_obstacles=%.1f misses=%.1f hits=%.1f wave_points=%.1f\n",
+ m_modernProfile.samples,m_modernProfile.fieldSample*scale,m_modernProfile.dampingSample*scale,
+ m_modernProfile.waveSample*scale,m_modernProfile.cacheSample*scale,
+ m_modernProfile.patches?double(m_modernProfile.patchObstacles)/m_modernProfile.patches:0,
+ m_modernProfile.misses/frames,m_modernProfile.hits/frames,m_modernProfile.wavePoints/frames);
+ m_modernProfile=ModernWaterProfile();
+ }
+ }
+#endif
// renderWaterMesh();
// renderWaterWave();
@@ -2198,6 +3622,14 @@ void WaterRenderObjClass::renderWater(void)
points[2].Set(pt2.x, pt2.y, pt2.z);
points[3].Set(pt3.x, pt3.y, pt3.z);
+#if defined(__linux__)
+ // Modern depth intersections replace legacy tilted feather copies. Render exactly
+ // one surface at the authored elevation; duplicate layers could expose patch seams.
+ if (m_useModernWater && m_trapezoidWaterPixelShader) {
+ m_modernBowPatchOwner=reinterpret_cast<uintptr_t>(pTrig);m_modernBowPatchPart=unsigned(k);
+ drawTrapezoidWater(points); continue;
+ }
+#endif
if ( TheGlobalData->m_featherWater )
{
for (int r = 0; r < TheGlobalData->m_featherWater; ++r)
@@ -2420,6 +3852,7 @@ void WaterRenderObjClass::renderWaterMesh(void)
// the grid is TerrainLogic's, read here from the copy takeGridForDraw made at the sync point
if (!m_drawnMotionEnabled || m_drawnMesh.empty())
return; //the water grid is disabled.
+ m_modernOpticalLevel=Get_Position().Z;
//According to Nvidia there's a D3D bug that happens if you don't start with a
//new dynamic VB each frame - so we force a DISCARD by overflowing the counter.
@@ -2550,6 +3983,14 @@ void WaterRenderObjClass::renderWaterMesh(void)
#endif
vb->u2=(float)(i)*cellSizeX/BUMP_SIZE;
vb->v2=v2Offset;
+#if defined(__linux__)
+ if (m_useModernWater && m_trapezoidWaterPixelShader) {
+ Vector3 world;
+ Matrix3D::Transform_Vector(Transform,Vector3(x,y,pData->height),&world);
+ vb->u2=0.0f;
+ vb->v2=world.Z;
+ }
+#endif
//old slow code
//vb->v2=(float)(j+m_riverVOrigin/vScale )*cellSizeY/BUMP_SIZE+ 0.3f*(float)j*cellSizeY/BUMP_SIZE;
vb++;
@@ -2703,6 +4144,728 @@ Real WaterRenderObjClass::getWaterHeight(Real x, Real y)
return INVALID_WATER_HEIGHT; //point not underwater
}
+
+// Scene geometry attenuates the render mesh only. It never changes the simulation water grid.
+Real WaterRenderObjClass::modernWaterDamping(Real x, Real y, Real z, Real offshore, Real *obstacleAttenuation, Real *terrainDepth, Real *hullFreeDamping, Real *hullFreeObstacle) const
+{
+ if (obstacleAttenuation) *obstacleAttenuation=1.0f;
+ if (hullFreeObstacle) *hullFreeObstacle=1.0f;
+ if (terrainDepth) *terrainDepth=0.0f;
+ // Early zero returns remain zero for both the complete CPU fallback and the FFT envelope.
+ if (hullFreeDamping) *hullFreeDamping=0.0f;
+ WorldHeightMap *map=TheTerrainRenderObject?TheTerrainRenderObject->getMap():NULL;
+ Real damping=1.0f;
+ if (map && map->getXExtent()>1 && map->getYExtent()>1) {
+ const Real depth=WaterTerrainDepth(map,x,y,z);
+ if (terrainDepth) *terrainDepth=depth;
+ damping=WaterSurfaceModel::TerrainDamping(depth,offshore);
+ if (damping<=0.0f && !hullFreeObstacle) return 0.0f;
+ }
+ // The broad phase only omits objects whose exact narrow phase returns one. River points
+ // and failed/oversized index builds retain the original ordered full list.
+ const WaterObstacleIndex::Range candidates=offshore>0.0f?m_modernObstacleIndex.Query(x,y):WaterObstacleIndex::Range{};
+ const size_t obstacleCount=candidates.indexed?candidates.count:m_modernPatchObstacles.size();
+ for (size_t i=0;i<obstacleCount;++i) {
+ const ModernWaterObstacle &o=m_modernPatchObstacles[candidates.indexed?candidates.indices[i]:i];
+ if (z<o.position.Z-12.0f || z>o.position.Z+o.height+3.0f) continue;
+ const Real dx=x-o.position.X,dy=y-o.position.Y;
+ if (offshore>0.0f && WaterSurfaceModel::BeyondObstacleFade(dx,dy,o.radius)) continue;
+ Real obstacleDamping;
+ if (o.hasHull && offshore>0.0f) {
+ // An actual rendered waterline replaces the broad collision box offshore. Preserve
+ // the original river footprint exactly where the offshore field is zero.
+ const Real legacy=offshore<1.0f?WaterSurfaceModel::ShoreDamping(sqrtf(dx*dx+dy*dy)-o.radius):1.0f;
+ obstacleDamping=legacy+(1.0f-legacy)*offshore;
+ } else if (o.box && offshore>0.0f) {
+ const Real localX=dx*o.cosine+dy*o.sine,localY=-dx*o.sine+dy*o.cosine;
+ obstacleDamping=WaterSurfaceModel::BoxDamping(localX,localY,o.major,o.minor);
+ if (offshore<1.0f) {
+ const Real legacy=WaterSurfaceModel::ShoreDamping(sqrtf(dx*dx+dy*dy)-o.radius);
+ obstacleDamping=legacy+(obstacleDamping-legacy)*offshore;
+ }
+ } else obstacleDamping=WaterSurfaceModel::ShoreDamping(sqrtf(dx*dx+dy*dy)-o.radius);
+ // Cage displacement applies the exact rendered hull in the shader, including R0.
+ // Its independent object envelope must not inherit the legacy circular hull proxy.
+ if (hullFreeObstacle && !o.hasHull) *hullFreeObstacle=min(*hullFreeObstacle,obstacleDamping);
+ // Preserve the legacy outputs at their original early-out point while collecting
+ // the independent cage envelope through every remaining obstacle.
+ if(damping>0.0f) {
+ if (obstacleAttenuation) *obstacleAttenuation=min(*obstacleAttenuation,obstacleDamping);
+ damping=min(damping,obstacleDamping);
+ }
+ if (damping<=0.0f && !hullFreeObstacle) return 0.0f;
+ }
+ if (hullFreeDamping) *hullFreeDamping=damping;
+ if (offshore>0.0f && damping>0.0f) {
+ const Real hull=1.0f+(modernHullDamping(x,y,z)-1.0f)*offshore;
+ damping=min(damping,hull);
+ if (obstacleAttenuation) *obstacleAttenuation=min(*obstacleAttenuation,hull);
+ }
+ return damping;
+}
+
+// Render-only geometry keeps a complete analytic CPU fallback. Projected ocean interiors carry
+// optional FFT displacement metadata in the unlit normal channel; every authored edge retains the
+// same canonical analytic samples regardless of whether the GPU ocean field is available.
+void WaterRenderObjClass::drawModernWaterPatch(const Vector3 points[4], Bool river, Real riverStart, Real riverEnd)
+{
+#if defined(__linux__)
+ m_modernOpticalLevel = points[0].Z;
+ Vector3 boundsMin = points[0], boundsMax = points[0];
+ for (Int i = 1; i < 4; ++i) {
+ boundsMin.X = min(boundsMin.X, points[i].X);
+ boundsMin.Y = min(boundsMin.Y, points[i].Y);
+ boundsMin.Z = min(boundsMin.Z, points[i].Z);
+ boundsMax.X = max(boundsMax.X, points[i].X);
+ boundsMax.Y = max(boundsMax.Y, points[i].Y);
+ boundsMax.Z = max(boundsMax.Z, points[i].Z);
+ }
+ boundsMin.Z -= WaterSurfaceModel::MaxDisplacement;
+ boundsMax.Z += WaterSurfaceModel::MaxDisplacement;
+ if (!river) {
+ boundsMin.X -= WaterFftGeometry::MaxHorizontalDisplacement;
+ boundsMin.Y -= WaterFftGeometry::MaxHorizontalDisplacement;
+ boundsMax.X += WaterFftGeometry::MaxHorizontalDisplacement;
+ boundsMax.Y += WaterFftGeometry::MaxHorizontalDisplacement;
+ }
+ // Include all wave crests in culling; offscreen authored patches do not evaluate any modes.
+ if (m_modernRenderCamera && m_modernRenderCamera->Cull_Box(AABoxClass((boundsMin + boundsMax) * 0.5f, (boundsMax - boundsMin) * 0.5f))) return;
+ const ModernOpticalTexture *oceanContext = NULL;
+ if (!river && modernWaterOpticalTexture(m_modernOpticalLevel))
+ for (size_t field = 0; field < m_modernOpticalTextures.size(); ++field)
+ if (m_modernOpticalTextures[field].level == m_modernOpticalLevel) {
+ oceanContext = &m_modernOpticalTextures[field];
+ break;
+ }
+ const char *waveCageOption = getenv("ZH_WATER_WAVE_CAGES");
+ const Bool waveCageAvailable = oceanContext && oceanContext->waveCage && WaterFftSampling::Enabled()
+ && (!waveCageOption || strcmp(waveCageOption, "0") != 0);
+ const char *coastalCrestOption = getenv("ZH_WATER_COAST_CREST");
+ const Bool coastalCrestEnabled = coastalCrestOption && strcmp(coastalCrestOption, "1") == 0;
+ // Only actual exposed terrain coast in the analytic R0 region participates. No new
+ // texture/resource or gameplay height is introduced; this reuses the uploaded field bytes.
+ auto coastalCrestHeight = [&](Real x, Real y, Real offshore, Real depth, Real obstacle, Real damping) {
+ if (!coastalCrestEnabled || !WaterCoastalCrest::Eligible(river, oceanContext != NULL, offshore)
+ || depth <= WaterShoreFoam::MinDepth) return 0.0f;
+ const auto &field = oceanContext->shoreContext;
+ if (field.coast.size() != oceanContext->ocean.size() || field.exposure.size() != field.coast.size()) return 0.0f;
+ const Real gx = x / MAP_XY_FACTOR + m_modernHeightBorder, gy = y / MAP_XY_FACTOR + m_modernHeightBorder;
+ const Real support = WaterSurfaceModel::SampleOffshore(field.coast.data(), m_modernHeightWidth, m_modernHeightHeight, gx, gy,
+ MAP_XY_FACTOR).height;
+ const Real exposure = WaterSurfaceModel::SampleOffshore(field.exposure.data(), m_modernHeightWidth, m_modernHeightHeight, gx,
+ gy, MAP_XY_FACTOR).height;
+ const Real encodedObstacle = WaterCoastalCrest::EncodeObstacle(obstacle);
+ if (support <= 0 || exposure <= 0 || encodedObstacle - 0.5f / 255.0f <= damping) return 0.0f;
+ return WaterCoastalCrest::Height(WaterShoreFoam::Evaluate(x, y, m_modernWaveTime).height,
+ depth, support, exposure, encodedObstacle, damping);
+ };
+ const Int cells = m_modernMeshCells, side = cells + 1;
+ Int vertexCount = side * side;
+ WaterSurfaceModel::Point corners[4];
+ for (Int i = 0; i < 4; ++i) corners[i] = {points[i].X, points[i].Y, points[i].Z};
+ const WaterSurfaceModel::Point camera = {m_modernCamera.X, m_modernCamera.Y, m_modernCamera.Z};
+ WaterSurfaceModel::Point edges[4][WaterSurfaceModel::MeshCells + 1];
+ for (Int i = 0; i <= cells; ++i) {
+ const Real t = (Real) i / cells;
+ edges[0][i] = WaterSurfaceModel::EdgePoint(corners[0], corners[1], t, camera);
+ edges[1][i] = WaterSurfaceModel::EdgePoint(corners[1], corners[2], t, camera);
+ edges[2][i] = WaterSurfaceModel::EdgePoint(corners[3], corners[2], t, camera);
+ edges[3][i] = WaterSurfaceModel::EdgePoint(corners[0], corners[3], t, camera);
+ }
+ Real minX = points[0].X, maxX = minX, minY = points[0].Y, maxY = minY;
+ for (Int i = 1; i < 4; ++i) {
+ minX = min(minX, points[i].X);
+ maxX = max(maxX, points[i].X);
+ minY = min(minY, points[i].Y);
+ maxY = max(maxY, points[i].Y);
+ }
+ m_modernPatchObstacles.clear();
+ for (size_t i = 0; i < m_modernObstacles.size(); ++i) {
+ const ModernWaterObstacle &o = m_modernObstacles[i];
+ const Real reach = o.radius + 9.0f;
+ if (o.position.X + reach >= minX && o.position.X - reach <= maxX && o.position.Y + reach >= minY
+ && o.position.Y - reach <= maxY) m_modernPatchObstacles.push_back(o);
+ }
+ m_modernObstacleIndex.Clear();
+ m_modernObstacleInfluences.clear();
+ if (oceanContext && oceanContext->oceanExtent > 0 && m_modernPatchObstacles.size() <= WaterObstacleIndex::Grid::MaxObstacles) {
+ m_modernObstacleInfluences.reserve(m_modernPatchObstacles.size());
+ for (const ModernWaterObstacle &o : m_modernPatchObstacles)
+ m_modernObstacleInfluences.push_back({o.position.X, o.position.Y, o.radius});
+ m_modernObstacleIndex.Build(m_modernObstacleInfluences, {minX, minY, maxX, maxY});
+ }
+ Real shadeR = TheWaterTransparency->m_standingWaterColor.red;
+ Real shadeG = TheWaterTransparency->m_standingWaterColor.green;
+ Real shadeB = TheWaterTransparency->m_standingWaterColor.blue;
+
+ //If the water color is not overridden, use legacy lighting code.
+ if ( shadeR == 1.0f && shadeG == 1.0f && shadeB == 1.0f)
+ {
+ shadeR = TheGlobalData->m_terrainAmbient[0].red;
+ shadeG = TheGlobalData->m_terrainAmbient[0].green;
+ shadeB = TheGlobalData->m_terrainAmbient[0].blue;
+
+ //Add in diffuse lighting from each terrain light
+ for (Int lightIndex = 0; lightIndex < TheGlobalData->m_numGlobalLights; lightIndex++)
+ {
+ if (-TheGlobalData->m_terrainLightPos[lightIndex].z > 0)
+ {
+ shadeR += -TheGlobalData->m_terrainLightPos[lightIndex].z * TheGlobalData->m_terrainDiffuse[lightIndex].red;
+ shadeG += -TheGlobalData->m_terrainLightPos[lightIndex].z * TheGlobalData->m_terrainDiffuse[lightIndex].green;
+ shadeB += -TheGlobalData->m_terrainLightPos[lightIndex].z * TheGlobalData->m_terrainDiffuse[lightIndex].blue;
+ }
+ }
+
+ //Get water material colors
+ Real waterShadeR = (m_settings[m_tod].waterDiffuse & 0xff) / 255.0f;
+ Real waterShadeG = ((m_settings[m_tod].waterDiffuse >> 8) & 0xff) / 255.0f;
+ Real waterShadeB = ((m_settings[m_tod].waterDiffuse >> 16) & 0xff) / 255.0f;
+
+ shadeR = shadeR * waterShadeR * 255.0f;
+ shadeG = shadeG * waterShadeG * 255.0f;
+ shadeB = shadeB * waterShadeB * 255.0f;
+ }
+ else
+ {
+ shadeR = shadeR * 255.0f;
+ shadeG = shadeG * 255.0f;
+ shadeB = shadeB * 255.0f;
+
+ if (shadeR == 0 && shadeG == 0 && shadeB == 0)
+ {
+ //special case where we disable lighting
+ shadeR = 255;
+ shadeG = 255;
+ shadeB = 255;
+ }
+ }
+
+ Int diffuse = REAL_TO_INT(shadeB) | (REAL_TO_INT(shadeG) << 8) | (REAL_TO_INT(shadeR) << 16);
+
+ //Keep diffuse from lighting calculations but substitute custom alpha
+ diffuse |= m_settings[m_tod].waterDiffuse & 0xff000000; //copy alpha/opacity from ini setting
+
+ WaterProjectedMesh::Mesh projectedMesh;
+ WaterFftGeometry::SeamFade fftSeam;
+ const double profileMeshStart = m_modernProfileEnabled ? modernWaterProfileMilliseconds() : 0;
+ if (m_modernProfileEnabled) {
+ ++m_modernProfile.patches;
+ m_modernProfile.patchObstacles += m_modernPatchObstacles.size();
+ }
+ Bool projected = FALSE;
+ const float levels[4] = {points[0].Z, points[1].Z, points[2].Z, points[3].Z};
+ // Homography is defined on one plane. Authored sloped patches retain every original Z.
+ if (!river && oceanContext && oceanContext->oceanExtent > 0 && m_modernRenderCamera && WaterProjectedMesh::HasSingleLevel(levels)) {
+ WaterProjectedMesh::Projection projection;
+ Matrix3D view;
+ m_modernRenderCamera->Get_View_Matrix(&view);
+ const Matrix4x4 &clip = m_modernRenderCamera->Get_Projection_Matrix();
+ for (Int row = 0; row < 3; ++row) {
+ const Int clipRow = row == 2 ? 3 : row;
+ for (Int column = 0; column < 2; ++column) {
+ projection.matrix[row * 3 + column] = 0;
+ for (Int k = 0; k < 3; ++k) projection.matrix[row * 3 + column] += double(clip[clipRow][k]) * view[k][column];
+ }
+ projection.matrix[row * 3 + 2] = clip[clipRow][3];
+ for (Int k = 0; k < 3; ++k) projection.matrix[row * 3 + 2] += double(clip[clipRow][k]) * (double(view[k][2]) * points[0].Z + view[k][3]);
+ }
+ projection.depth = {-double(view[2][0]), -double(view[2][1]), -double(view[2][2]) * points[0].Z - view[2][3]};
+ Real nearDistance, farDistance;
+ m_modernRenderCamera->Get_Clip_Planes(nearDistance, farDistance);
+ projection.nearDistance = max(0.01f, nearDistance);
+ projection.farDistance = farDistance + WaterSurfaceModel::MaxDisplacement;
+ const Real separation = fabsf(m_modernCamera.Z - points[0].Z);
+ projection.margin = clamp(4.0f * WaterSurfaceModel::MaxDisplacement / max(separation, 1.0f), 0.12f, 0.8f);
+ WaterProjectedMesh::Point polygon[4];
+ for (Int i = 0; i < 4; ++i) polygon[i] = {points[i].X, points[i].Y};
+ std::vector<WaterProjectedMesh::BoundaryKnot> boundaryKnots;
+ boundaryKnots.reserve(4 * (cells + 1));
+ for (Int edge = 0; edge < 4; ++edge) {
+ WaterSurfaceModel::Point a = corners[edge], b = corners[(edge + 1) % 4];
+ if (a.x > b.x || (a.x == b.x && a.y > b.y)) {
+ const WaterSurfaceModel::Point swap = a;
+ a = b;
+ b = swap;
+ }
+ const double dx = double(b.x) - a.x, dy = double(b.y) - a.y, len2 = dx * dx + dy * dy;
+ if (len2 < 1e-12) continue;
+ WaterSurfaceModel::Point knot[WaterSurfaceModel::MeshCells + 1];
+ for (Int i = 0; i <= cells; ++i) knot[i] = WaterSurfaceModel::EdgePoint(a, b, Real(i) / cells, camera);
+ for (Int i = 1; i < cells; i += 2) {
+ knot[i].x = WaterSurfaceModel::MorphCoordinate(knot[i].x, knot[i - 1].x, knot[i + 1].x, m_modernMeshMorph);
+ knot[i].y = WaterSurfaceModel::MorphCoordinate(knot[i].y, knot[i - 1].y, knot[i + 1].y, m_modernMeshMorph);
+ }
+ for (Int i = 0; i <= cells; ++i) {
+ const double t = ((knot[i].x - a.x) * dx + (knot[i].y - a.y) * dy) / len2;
+ // Use the authored straight XY edge for clipping; retain the exact float knot in
+ // the final vertex. The difference is at most float interpolation roundoff.
+ boundaryKnots.push_back({{a.x + dx * t, a.y + dy * t}, edge, i, t});
+ }
+ }
+ if (separation > WaterSurfaceModel::MaxDisplacement*2 && projection.Prepare() &&
+ WaterProjectedMesh::Build(polygon, projection, {m_modernProjectedColumns, m_modernProjectedRows}, projectedMesh,
+ m_modernProjectedBudget, boundaryKnots)) {
+ projected = TRUE;
+ vertexCount = (Int) projectedMesh.vertices.size();
+ fftSeam.Prepare(polygon, projection, {m_modernProjectedColumns, m_modernProjectedRows});
+ // Optional bow detail only replaces fresh interior triangles. The same submitted
+ // contact contours drive the shader packet and its projected geometric demand.
+ // Explicit wave opt-outs must also omit work for their absent displacement field.
+ if (WaterFftSampling::Enabled() && WaterVesselWaves::Enabled()) {
+ WaterBowRefinement::View bowView;
+ bowView.projection = projection;
+ bowView.resolution = {m_modernProjectedColumns, m_modernProjectedRows};
+ bowView.width = m_modernProjectedWidth;
+ bowView.height = m_modernProjectedHeight;
+ for (Int row = 0; row < 3; ++row) {
+ bowView.verticalClip[row] = 0;
+ const Int clipRow = row == 2 ? 3 : row;
+ for (Int k = 0; k < 3; ++k) bowView.verticalClip[row] += double(clip[clipRow][k]) * view[k][2];
+ }
+ const auto patchKey = WaterBowRefinement::MakePatchKey(polygon, points[0].Z, m_modernBowPatchOwner, m_modernBowPatchPart);
+ auto prepareBow = [&](const WaterBowRefinement::Bow &bow, WaterBowRefinement::Prepared &prepared) {
+ const auto offshore = WaterSurfaceModel::SampleOffshore(oceanContext->ocean.data(), m_modernHeightWidth, m_modernHeightHeight,
+ Real(bow.centre.x) / MAP_XY_FACTOR + m_modernHeightBorder,
+ Real(bow.centre.y) / MAP_XY_FACTOR + m_modernHeightBorder, MAP_XY_FACTOR);
+ Real terrainDepth = 0;
+ const Real damping = modernWaterDamping(Real(bow.centre.x), Real(bow.centre.y), points[0].Z, offshore.height, NULL,
+ &terrainDepth);
+ const Real exposure = WaterSurfaceModel::SampleOffshore(oceanContext->shoreContext.exposure.data(),
+ m_modernHeightWidth, m_modernHeightHeight, Real(bow.centre.x) / MAP_XY_FACTOR + m_modernHeightBorder,
+ Real(bow.centre.y) / MAP_XY_FACTOR + m_modernHeightBorder, MAP_XY_FACTOR).height;
+ const Real amplitude = fftSeam.Weight(bow.centre, exposure) * WaterFftGeometry::SafeDamping(damping, terrainDepth);
+ return WaterBowRefinement::PrepareBow(bow, bowView, prepared, amplitude);
+ };
+ std::vector<size_t> hullOrder;
+ hullOrder.reserve(m_modernHulls.size());
+ for (size_t i = 0; i < m_modernHulls.size(); ++i) hullOrder.push_back(i);
+ std::sort(hullOrder.begin(), hullOrder.end(), [&](size_t a, size_t b) {
+ return m_modernHullObjectIDs[a] < m_modernHullObjectIDs[b];
+ });
+ for (size_t i : hullOrder) {
+ WaterBowRefinement::Bow bow;
+ WaterBowRefinement::Prepared prepared;
+ const auto &contact = i < m_modernContactHulls.size() ? m_modernContactHulls[i] : m_modernHulls[i];
+ if (!WaterBowRefinement::MakeBow(m_modernHullObjectIDs[i], m_modernHulls[i], contact, points[0].Z, bow) ||
+ !prepareBow(bow, prepared) || prepared.heightGate <= 0 || prepared.desiredDepth <= 0) continue;
+ if (prepared.cell.x < - WaterBowRefinement::WindowRadius || prepared.cell.y < - WaterBowRefinement::WindowRadius ||
+ prepared.cell.x > m_modernProjectedColumns + WaterBowRefinement::WindowRadius ||
+ prepared.cell.y > m_modernProjectedRows + WaterBowRefinement::WindowRadius) continue;
+ if (!WaterBowRefinement::HasRefinableDemand(projectedMesh, bowView, polygon, prepared)) continue;
+ if (!m_modernBowAdmissions.Request(patchKey, bow, m_modernProjectedBudget)) ++m_modernBowDenied;
+ }
+ std::vector<WaterBowRefinement::Active> active;
+ active.reserve(WaterBowRefinement::MaxRegions);
+ for (const auto &slot : m_modernBowAdmissions.Slots()) if (slot.occupied && slot.patch == patchKey && slot.amount > 0) {
+ WaterBowRefinement::Prepared prepared;
+ if (prepareBow(slot.bow, prepared)) active.push_back({prepared, slot.amount});
+ }
+ WaterBowRefinement::Stats bowStats;
+ const size_t bowBudget = min(size_t(65535), m_modernProjectedBudget + active.size() * WaterBowRefinement::RegionVertices);
+ WaterBowRefinement::Refine(projectedMesh, bowView, polygon, active, bowBudget, bowStats,
+ WaterBowRefinement::MaxAddedVertices - m_modernBowVertices, WaterBowRefinement::MaxAddedTriangles - m_modernBowTriangles);
+ m_modernBowVertices += bowStats.addedVertices;
+ m_modernBowTriangles += bowStats.addedTriangles;
+ m_modernBowRegions += bowStats.regions;
+ m_modernBowRejected += bowStats.rejected ? 1 : 0;
+ }
+ // Authored ocean polygons often extend beneath the entire land mass. The
+ // projected lattice covers that hidden area too; discard only triangles
+ // whose complete displaced footprint is buried, before evaluating waves,
+ // obstacles or uploading their vertices. Endpoint depths alone can miss a
+ // small pond inside a triangle, so inspect every overlapping terrain cell.
+ // Keep the original mesh for an underwater/below-terrain free camera.
+ if (m_modernCamera.Z > points[0].Z + WaterSurfaceModel::MaxDisplacement + 0.01f &&
+ WaterTerrainCulling::CameraAboveTerrain(
+ m_modernHeights.data(), m_modernHeightWidth, m_modernHeightHeight,
+ m_modernHeightBorder, MAP_XY_FACTOR, MAP_HEIGHT_SCALE,
+ m_modernCamera.X, m_modernCamera.Y, m_modernCamera.Z))
+ {
+ WaterTerrainCulling::CullDryTriangles(
+ projectedMesh, m_modernHeights.data(), m_modernHeightWidth, m_modernHeightHeight,
+ m_modernHeightBorder, MAP_XY_FACTOR, MAP_HEIGHT_SCALE, points[0].Z,
+ WaterSurfaceModel::MaxDisplacement + 0.01f,
+ WaterFftGeometry::MaxHorizontalDisplacement + 0.01f);
+ }
+
+ if (waveCageAvailable)
+ {
+ const auto depth = [&](const WaterProjectedMesh::Point &p)
+ {
+ return points[0].Z - WaterWaveCage::Height(
+ m_modernHeights.data(), m_modernHeightWidth, m_modernHeightHeight,
+ m_modernHeightBorder, MAP_XY_FACTOR, MAP_HEIGHT_SCALE, float(p.x), float(p.y));
+ };
+ const auto supported = [&](const WaterProjectedMesh::Point &p)
+ {
+ return WaterSurfaceModel::SampleOffshore(
+ oceanContext->waveCageSupport.data(), m_modernHeightWidth, m_modernHeightHeight,
+ float(p.x) / MAP_XY_FACTOR + m_modernHeightBorder,
+ float(p.y) / MAP_XY_FACTOR + m_modernHeightBorder, MAP_XY_FACTOR).height > 0.0f;
+ };
+
+ // Split only supported interior triangles at the rest waterline. The helper
+ // retains authored seams and leaves the original mesh intact if its budget fails.
+ WaterWaveCageMesh::ClipRestWaterline(projectedMesh, depth, supported);
+ }
+
+ // Waterline clipping also leaves unreferenced dry vertices behind.
+ WaterTerrainCulling::CompactVertices(projectedMesh);
+ vertexCount = (Int) projectedMesh.vertices.size();
+ m_modernProjectedVertices += vertexCount;
+ m_modernProjectedTriangles += projectedMesh.indices.size() / 3;
+ } else ++m_modernProjectedFallbacks; // Retain complete original coverage if projection is singular.
+ }
+
+ if (m_modernProfileEnabled) m_modernProfile.mesh += modernWaterProfileMilliseconds() - profileMeshStart;
+ if (projected && projectedMesh.indices.empty()) return;
+ if (!projected) m_modernRetainedVertices += vertexCount;
+ const Bool waveCage = projected && waveCageAvailable;
+ const double profileFillStart = m_modernProfileEnabled ? modernWaterProfileMilliseconds() : 0;
+ DynamicVBAccessClass vertices(BUFFER_TYPE_DYNAMIC_DX8, dynamic_fvf_type, vertexCount);
+ {
+ DynamicVBAccessClass::WriteLockClass lock(&vertices);
+ VertexFormatXYZNDUV2 *grid = lock.Get_Formatted_Vertex_Array();
+ VertexFormatXYZNDUV2 *vertex = grid;
+ W3DShroud *shroud = TheTerrainRenderObject ? TheTerrainRenderObject->getShroud() : NULL;
+ if (projected) {
+ auto makeBaseVertex = [&](const WaterSurfaceModel::Point &p, Bool boundarySample = FALSE) {
+ // Sample one in 64 vertices, with the phase rotating each render. Clock reads are
+ // absent from normal runs and sparse enough not to dominate the measured work.
+ const Bool sampled = m_modernProfileEnabled && ((m_modernProfile.attempts++ + m_modernProfile.frames) & 63) == 0;
+ double stamp = sampled ? modernWaterProfileMilliseconds() : 0;
+ const Bool share = m_modernProjectedCacheEnabled || boundarySample;
+ const WaterProjectedMesh::WorldKey key = WaterProjectedMesh::SampleKey(p.x, p.y, p.z);
+ auto cached = share ? m_modernProjectedSamples.find(key) : m_modernProjectedSamples.end();
+ if (sampled) {
+ const double now = modernWaterProfileMilliseconds();
+ m_modernProfile.cacheSample += now - stamp;
+ stamp = now;
+ ++m_modernProfile.samples;
+ }
+ ModernProjectedSample sample;
+ if (cached != m_modernProjectedSamples.end()) {
+ sample = cached->second;
+ if (m_modernProfileEnabled) ++m_modernProfile.hits;
+ } else {
+ ++m_modernProjectedEvaluations;
+ if (m_modernProfileEnabled) ++m_modernProfile.misses;
+ const WaterSurfaceModel::Sample offshore = WaterSurfaceModel::SampleOffshore(oceanContext->ocean.data(),
+ m_modernHeightWidth, m_modernHeightHeight, p.x / MAP_XY_FACTOR + m_modernHeightBorder,
+ p.y / MAP_XY_FACTOR + m_modernHeightBorder, MAP_XY_FACTOR);
+ if (sampled) {
+ const double now = modernWaterProfileMilliseconds();
+ m_modernProfile.fieldSample += now - stamp;
+ stamp = now;
+ }
+ sample.obstacle = sample.hullFreeObstacle = 1;
+ Real terrainDepth = 0, hullFreeDamping = 0;
+ sample.damping = modernWaterDamping(p.x, p.y, p.z, offshore.height, &sample.obstacle, &terrainDepth, &hullFreeDamping,
+ waveCage ? &sample.hullFreeObstacle : NULL);
+ sample.offshore = offshore.height;
+ sample.exposure = WaterSurfaceModel::SampleOffshore(oceanContext->shoreContext.exposure.data(),
+ m_modernHeightWidth, m_modernHeightHeight, p.x / MAP_XY_FACTOR + m_modernHeightBorder,
+ p.y / MAP_XY_FACTOR + m_modernHeightBorder, MAP_XY_FACTOR).height;
+ sample.fftDamping = WaterFftGeometry::SafeDamping(hullFreeDamping, terrainDepth);
+ if (sampled) {
+ const double now = modernWaterProfileMilliseconds();
+ m_modernProfile.dampingSample += now - stamp;
+ stamp = now;
+ }
+ sample.height = sample.damping > 0 ? WaterSurfaceModel::EvaluateBlendedHeight(p.x, p.y, m_modernWaveTime,
+ offshore) * sample.damping : 0;
+ sample.height += coastalCrestHeight(p.x, p.y, offshore.height, terrainDepth, sample.obstacle, sample.damping);
+ if (sampled) {
+ const double now = modernWaterProfileMilliseconds();
+ m_modernProfile.waveSample += now - stamp;
+ stamp = now;
+ }
+ if (m_modernProfileEnabled && sample.damping > 0) ++m_modernProfile.wavePoints;
+ if (share && m_modernProjectedSamples.size() < WaterSurfaceModel::VertexBudget) m_modernProjectedSamples.emplace(key, sample);
+ if (sampled) m_modernProfile.cacheSample += modernWaterProfileMilliseconds() - stamp;
+ }
+ VertexFormatXYZNDUV2 result;
+ result.x = p.x;
+ result.y = p.y;
+ result.z = p.z + sample.height;
+ // The native FFT stages apply exact hull damping to this hull-free floor/obstacle
+ // envelope. Interpolating the hull envelope itself produces triangular normals.
+ // CPU fallback height and authored edges retain the original combined damping.
+ // Connected coastal water shares the ocean's spectral phases. Optical R
+ // still controls colour and horizontal chop, not the wave family.
+ result.nx = boundarySample ? 0.0f : fftSeam.Weight({p.x, p.y}, sample.exposure);
+ result.ny = sample.fftDamping;
+ result.nz = sample.offshore;
+ result.u1 = 0;
+ result.v1 = p.y / 150.0f;
+ result.u2 = sample.damping;
+ result.v2 = p.z;
+ result.diffuse = WaterSurfaceModel::EncodeObstacleAttenuation(diffuse, boundarySample
+ || !waveCage ? sample.obstacle : sample.hullFreeObstacle);
+ return result;
+ };
+ auto interpolate = [](const VertexFormatXYZNDUV2 &a, const VertexFormatXYZNDUV2 &b, Real t) {
+ VertexFormatXYZNDUV2 value = a;
+ value.x = a.x + (b.x - a.x) * t;
+ value.y = a.y + (b.y - a.y) * t;
+ value.z = a.z + (b.z - a.z) * t;
+ value.u1 = a.u1 + (b.u1 - a.u1) * t;
+ value.v1 = a.v1 + (b.v1 - a.v1) * t;
+ value.u2 = a.u2 + (b.u2 - a.u2) * t;
+ value.v2 = a.v2 + (b.v2 - a.v2) * t;
+ value.diffuse = 0;
+ for (Int shift = 0; shift < 32; shift += 8) {
+ const Real ca = (a.diffuse >> shift) & 255, cb = (b.diffuse >> shift) & 255;
+ value.diffuse |= UnsignedInt(ca + (cb - ca) * t + 0.5f) << shift;
+ }
+ return value;
+ };
+ VertexFormatXYZNDUV2 edgeVertices[4][WaterSurfaceModel::MeshCells + 1];
+ Bool prepared[4] = {FALSE, FALSE, FALSE, FALSE};
+
+ WaterProjectedMesh::Point authored[4];
+ for (Int i = 0; i < 4; ++i) authored[i] = {points[i].X, points[i].Y};
+ auto prepareEdge = [&](Int edge) {
+ if (prepared[edge]) return;
+ WaterSurfaceModel::Point a = corners[edge], b = corners[(edge + 1) % 4];
+ if (a.x > b.x || (a.x == b.x && a.y > b.y)) {
+ const WaterSurfaceModel::Point swap = a;
+ a = b;
+ b = swap;
+ }
+ for (Int i = 0; i <= cells; ++i) edgeVertices[edge][i] = makeBaseVertex(WaterSurfaceModel::EdgePoint(a, b,
+ Real(i) / cells, camera), TRUE);
+ for (Int i = 1; i < cells; i += 2) {
+ VertexFormatXYZNDUV2 &v = edgeVertices[edge][i];
+ const VertexFormatXYZNDUV2 &lo = edgeVertices[edge][i - 1], &hi = edgeVertices[edge][i + 1];
+ v.x = WaterSurfaceModel::MorphCoordinate(v.x, lo.x, hi.x, m_modernMeshMorph);
+ v.y = WaterSurfaceModel::MorphCoordinate(v.y, lo.y, hi.y, m_modernMeshMorph);
+ v.z = WaterSurfaceModel::MorphCoordinate(v.z, lo.z, hi.z, m_modernMeshMorph);
+ v.u1 = WaterSurfaceModel::MorphCoordinate(v.u1, lo.u1, hi.u1, m_modernMeshMorph);
+ v.v1 = WaterSurfaceModel::MorphCoordinate(v.v1, lo.v1, hi.v1, m_modernMeshMorph);
+ v.u2 = WaterSurfaceModel::MorphCoordinate(v.u2, lo.u2, hi.u2, m_modernMeshMorph);
+ v.v2 = WaterSurfaceModel::MorphCoordinate(v.v2, lo.v2, hi.v2, m_modernMeshMorph);
+ v.diffuse = WaterSurfaceModel::MorphColour(v.diffuse, lo.diffuse, hi.diffuse, m_modernMeshMorph);
+ }
+ prepared[edge] = TRUE;
+ };
+ auto edgeSample = [&](Int edge, double parameter) {
+ prepareEdge(edge);
+ WaterSurfaceModel::Point a = corners[edge], b = corners[(edge + 1) % 4];
+ if (a.x > b.x || (a.x == b.x && a.y > b.y)) {
+ const WaterSurfaceModel::Point swap = a;
+ a = b;
+ b = swap;
+ }
+ const double ex = b.x - a.x, ey = b.y - a.y, len2 = ex * ex + ey * ey;
+ Int i = 0;
+ Real t = 0;
+ for (; i < cells; ++i) {
+ const VertexFormatXYZNDUV2 &lo = edgeVertices[edge][i], &hi = edgeVertices[edge][i + 1];
+ const double lt = ((lo.x - a.x) * ex + (lo.y - a.y) * ey) / len2, ht = ((hi.x - a.x) * ex + (hi.y - a.y) * ey) / len2;
+ if (parameter <= ht || i == cells - 1) {
+ t = ht > lt ? Real((parameter - lt) / (ht - lt)) : 0;
+ t = clamp(t, 0.0f, 1.0f);
+ break;
+ }
+ }
+ return interpolate(edgeVertices[edge][i], edgeVertices[edge][i + 1], t);
+ };
+ auto correctedVertex = [&](WaterProjectedMesh::Point p, const WaterProjectedMesh::BoundaryCollar &collar, Bool share = FALSE) {
+ VertexFormatXYZNDUV2 result = makeBaseVertex({Real(p.x), Real(p.y), points[0].Z}, share);
+ double correction = 0;
+ for (Int i = 0; i < collar.count; ++i) {
+ const VertexFormatXYZNDUV2 edge = edgeSample(collar.edge[i], collar.parameter[i]);
+ correction += collar.weight[i] * (edge.z - result.z);
+ }
+ result.u1 = Real(correction);
+ result.z += result.u1;
+ return result;
+ };
+ for (size_t n = 0; n < projectedMesh.vertices.size(); ++n) {
+ const WaterProjectedMesh::Vertex &p = projectedMesh.vertices[n];
+ if (p.boundary < 0) {
+ grid[n] = p.collar >= 0 ? correctedVertex(p.world,
+ projectedMesh.collars[p.collar]) : makeBaseVertex({Real(p.world.x), Real(p.world.y), points[0].Z});
+ if (p.transition >= 0) {
+ const WaterProjectedMesh::CentreTransition &transition = projectedMesh.transitions[p.transition];
+ VertexFormatXYZNDUV2 source[3];
+ for (Int i = 0; i < 3; ++i) source[i] = correctedVertex(transition.source[i],
+ WaterProjectedMesh::CollarAt(authored, transition.source[i]), TRUE);
+ double values[3];
+ for (Int i = 0; i < 3; ++i) values[i] = source[i].z;
+ const Real height = Real(WaterProjectedMesh::InterpolateCentre(transition, grid[n].z, values));
+ grid[n].u1 += height - grid[n].z;
+ grid[n].z = height;
+ }
+ continue;
+ }
+ const Int edge = p.boundary;
+ WaterSurfaceModel::Point a = corners[edge], b = corners[(edge + 1) % 4];
+ if (a.x > b.x || (a.x == b.x && a.y > b.y)) {
+ const WaterSurfaceModel::Point swap = a;
+ a = b;
+ b = swap;
+ }
+ prepareEdge(edge);
+ grid[n] = p.knot >= 0 ? edgeVertices[edge][p.knot] : edgeSample(edge, p.edgeParameter);
+ // The fragment receives the exact additional height, including coarse-edge morph.
+ const VertexFormatXYZNDUV2 analytic = makeBaseVertex({grid[n].x, grid[n].y, points[0].Z}, TRUE);
+ grid[n].u1 = grid[n].z - analytic.z;
+ grid[n].u2 = analytic.u2;
+ grid[n].diffuse = analytic.diffuse;
+ grid[n].nx = grid[n].ny = 0;
+ grid[n].nz = 1;
+ }
+ } else {
+ for (Int j = 0; j <= cells; ++j) for (Int i = 0; i <= cells; ++i) {
+ const Real u = (Real) i / cells, v = (Real) j / cells;
+ const WaterSurfaceModel::Point boundary[4] = {edges[0][i], edges[1][j], edges[2][i], edges[3][j]};
+ const WaterSurfaceModel::Point p = WaterSurfaceModel::PatchPoint(corners, boundary, u, v);
+ const WaterSurfaceModel::Sample offshore = oceanContext ? WaterSurfaceModel::SampleOffshore(
+ oceanContext->ocean.data(), m_modernHeightWidth, m_modernHeightHeight,
+ p.x / MAP_XY_FACTOR + m_modernHeightBorder, p.y / MAP_XY_FACTOR + m_modernHeightBorder,
+ MAP_XY_FACTOR) : WaterSurfaceModel::Sample{0, 0, 0};
+ Real obstacleAttenuation = 1.0f;
+ Real terrainDepth = 0;
+ const Real damping = modernWaterDamping(p.x, p.y, p.z, offshore.height, river ? NULL : &obstacleAttenuation, &terrainDepth);
+ // Broad water polygons also cover dry land. Those vertices cannot move, and evaluating
+ // all wave modes there was needlessly expensive on maps with many shallow pools.
+ WaterSurfaceModel::Sample wave = {0, 0, 0};
+ if (damping > 0.0f) {
+ if (offshore.height > 0.0f) wave.height = WaterSurfaceModel::EvaluateBlendedHeight(p.x, p.y, m_modernWaveTime, offshore);
+ else wave = WaterSurfaceModel::EvaluateBlended(p.x, p.y, m_modernWaveTime, offshore);
+ }
+ vertex->x = p.x;
+ vertex->y = p.y;
+ vertex->z = p.z + damping * wave.height
+ + coastalCrestHeight(p.x, p.y, offshore.height, terrainDepth, obstacleAttenuation, damping);
+ // The flat modern shader uses only alpha for colour/shroud. PRELIT_DIFFUSE passes RGB
+ // through unchanged, so red carries the obstacle profile independently of terrain.
+ vertex->diffuse = river ? applyShroudToRiverDiffuse(shroud, p.x, p.y, diffuse) :
+ WaterSurfaceModel::EncodeObstacleAttenuation(diffuse, obstacleAttenuation);
+ vertex->u1 = river ? (1.0f - u) * 0.5f : 0.0f;
+ vertex->v1 = river ? riverStart + (riverEnd - riverStart) * v - m_riverVOrigin : p.y / 150.0f;
+ vertex->u2 = damping;
+ vertex->v2 = p.z;
+ if (!river) {
+ vertex->nx = vertex->ny = 0.0f;
+ vertex->nz = 1.0f;
+ } else {
+ const Real nx = -wave.dx * damping, ny = -wave.dy * damping, inv = 1.0f / sqrtf(1.0f + nx * nx + ny * ny);
+ vertex->nx = nx * inv;
+ vertex->ny = ny * inv;
+ vertex->nz = inv;
+ }
+ ++vertex;
+ }
+ if (m_modernMeshMorph > 0.0f) {
+ for (Int j = 0; j <= cells; ++j) for (Int i = 0; i <= cells; ++i) {
+ if (((i|j) & 1) == 0) continue; // Coarse vertices are unchanged and safe to reuse.
+ const WaterSurfaceModel::CoarsePair pair = WaterSurfaceModel::CoarsePairForVertex(i, j, cells);
+ const VertexFormatXYZNDUV2 &a = grid[pair.first], &b = grid[pair.second];
+ VertexFormatXYZNDUV2 &v = grid[j * side + i];
+ const Real amount = m_modernMeshMorph;
+ v.x = WaterSurfaceModel::MorphCoordinate(v.x, a.x, b.x, amount);
+ v.y = WaterSurfaceModel::MorphCoordinate(v.y, a.y, b.y, amount);
+ v.z = WaterSurfaceModel::MorphCoordinate(v.z, a.z, b.z, amount);
+ v.u1 = WaterSurfaceModel::MorphCoordinate(v.u1, a.u1, b.u1, amount);
+ v.v1 = WaterSurfaceModel::MorphCoordinate(v.v1, a.v1, b.v1, amount);
+ v.u2 = WaterSurfaceModel::MorphCoordinate(v.u2, a.u2, b.u2, amount);
+ v.v2 = WaterSurfaceModel::MorphCoordinate(v.v2, a.v2, b.v2, amount);
+ v.nx = WaterSurfaceModel::MorphCoordinate(v.nx, a.nx, b.nx, amount);
+ v.ny = WaterSurfaceModel::MorphCoordinate(v.ny, a.ny, b.ny, amount);
+ v.nz = WaterSurfaceModel::MorphCoordinate(v.nz, a.nz, b.nz, amount);
+ v.diffuse = WaterSurfaceModel::MorphColour(v.diffuse, a.diffuse, b.diffuse, amount);
+ }
+ }
+ }
+ }
+ double profileSubmitStart = 0;
+ if (m_modernProfileEnabled) {
+ profileSubmitStart = modernWaterProfileMilliseconds();
+ m_modernProfile.fill += profileSubmitStart - profileFillStart;
+ }
+ Matrix3D transform(1);
+ DX8Wrapper::Set_Transform(D3DTS_WORLD, transform);
+ DX8Wrapper::Set_Vertex_Buffer(vertices);
+ DX8Wrapper::Set_Texture(0, m_riverTexture);
+ if (river) setupJbaWaterShader();
+ else setupFlatWaterShader(TRUE, waveCage);
+ RenderUInt32 cull;
+ DX8Wrapper::_Get_D3D_Device()->GetRenderState(D3DRS_CULLMODE, &cull);
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_CULLMODE, D3DCULL_NONE);
+ if (TheWaterTransparency->m_additiveBlend) DX8Wrapper::Set_DX8_Render_State(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
+ const char *debug = std::getenv("ZH_WATER_DEBUG");
+ const Bool meshDebug = wireframeForDebug || (debug && strcmp(debug, "wireframe") == 0);
+ if (meshDebug) DX8Wrapper::Set_DX8_Render_State(D3DRS_FILLMODE, D3DFILL_WIREFRAME);
+ WaterShoreOverlay::Quad shorePatch;
+ shorePatch.level = points[0].Z;
+ Bool planar = TRUE;
+ for (Int i = 0; i < 4; ++i) {
+ shorePatch.xy[i * 2] = points[i].X;
+ shorePatch.xy[i * 2 + 1] = points[i].Y;
+ planar = planar && points[i].Z == points[0].Z;
+ }
+ PosixWaterShorePatch(DX8Wrapper::_Get_D3D_Device(), !river && !meshDebug && planar ? &shorePatch : NULL);
+ // Legacy dynamic index buffers store their count in 16 bits. Keep a shared vertex grid and
+ // submit bounded row batches; even a 128-cell ocean patch cannot truncate its index count.
+ if (projected) {
+ for (size_t first = 0; first < projectedMesh.indices.size(); first += 65532) {
+ const size_t count = min(size_t(65532), projectedMesh.indices.size() - first);
+ DynamicIBAccessClass indices(BUFFER_TYPE_DYNAMIC_DX8, (Int) count);
+ {
+ DynamicIBAccessClass::WriteLockClass lock(&indices);
+ memcpy(lock.Get_Index_Array(), projectedMesh.indices.data() + first, count * sizeof(UnsignedShort));
+ }
+ DX8Wrapper::Set_Index_Buffer(indices, 0);
+ DX8Wrapper::Draw_Triangles(0, (Int) count / 3, 0, vertexCount);
+ }
+ } else {
+ const Int batchRows = WaterSurfaceModel::IndexBatchRows(cells);
+ for (Int row = 0; row < cells; row += batchRows) {
+ const Int rows = min(batchRows, cells - row), triangles = rows * cells * 2;
+ DynamicIBAccessClass indices(BUFFER_TYPE_DYNAMIC_DX8, triangles * 3);
+ {
+ DynamicIBAccessClass::WriteLockClass lock(&indices);
+ UnsignedShort *index = lock.Get_Index_Array();
+ for (Int j = row; j < row + rows; ++j) for (Int i = 0; i < cells; ++i) {
+ const Int a = j * side + i, b = a + 1, c = a + side, d = c + 1;
+ *index++ = a;
+ *index++ = d;
+ *index++ = c;
+ *index++ = a;
+ *index++ = b;
+ *index++ = d;
+ }
+ }
+ DX8Wrapper::Set_Index_Buffer(indices, 0);
+ DX8Wrapper::Draw_Triangles(0, triangles, 0, vertexCount);
+ }
+ }
+ PosixWaterShorePatch(DX8Wrapper::_Get_D3D_Device(), NULL);
+ if (meshDebug) DX8Wrapper::Set_DX8_Render_State(D3DRS_FILLMODE, D3DFILL_SOLID);
+ // Legacy water particles can be replaced only after this view has submitted the
+ // modern surface for their hull's level. Cached or offscreen hulls alone are not enough.
+ if (!river && !meshDebug) {
+ m_modernFoamDrawFrame = WW3D::Get_Frame_Count();
+ for (size_t i = 0; i < m_modernHulls.size(); ++i) if (m_modernHulls[i].data[0][2] == points[0].Z &&
+ std::find(m_modernFoamDrawObjectIDs.begin(), m_modernFoamDrawObjectIDs.end(),
+ m_modernHullObjectIDs[i]) == m_modernFoamDrawObjectIDs.end())
+ m_modernFoamDrawObjectIDs.push_back(m_modernHullObjectIDs[i]);
+ }
+ DX8Wrapper::Set_Pixel_Shader(NULL);
+ if (TheWaterTransparency->m_additiveBlend) DX8Wrapper::Set_DX8_Render_State(D3DRS_SRCBLEND, D3DBLEND_ONE);
+ if (!river && TheTerrainRenderObject->getShroud()) {
+ W3DShaderManager::resetShader(W3DShaderManager::ST_SHROUD_TEXTURE);
+ DX8Wrapper::Set_DX8_Texture(3, NULL);
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_ZFUNC, D3DCMP_EQUAL);
+ }
+ DX8Wrapper::Set_DX8_Render_State(D3DRS_CULLMODE, cull);
+ if (m_modernProfileEnabled) m_modernProfile.submit += modernWaterProfileMilliseconds() - profileSubmitStart;
+#endif
+}
+
//-------------------------------------------------------------------------------------------------
//Draw a many sided river polygon.
//-------------------------------------------------------------------------------------------------
@@ -2718,6 +4881,29 @@ void WaterRenderObjClass::drawRiverWater(PolygonTrigger *pTrig)
if (m_drawnPushed) return;
m_drawingRiver = true;
+#if defined(__linux__)
+ if (m_useModernWater && m_riverWaterPixelShader) {
+ Int inner=pTrig->getRiverStart(),outer=inner+1;
+ if (inner<0 || inner>=pTrig->getNumPoints()-1) return;
+ Vector3 previous[2];
+ Real along=0;
+ for (Int row=0;row<=rectangleCount;++row) {
+ const ICoord3D &a=*pTrig->getPoint(outer),&b=*pTrig->getPoint(inner);
+ Vector3 next[2]={Vector3(a.x,a.y,a.z),Vector3(b.x,b.y,b.z)};
+ if (row) {
+ const Real length=((next[0]-previous[0]).Length()+(next[1]-previous[1]).Length())*0.5f;
+ const Real width=max((next[1]-next[0]).Length(),1.0f);
+ Vector3 patch[4]={previous[0],previous[1],next[1],next[0]};
+ drawModernWaterPatch(patch,TRUE,along,along+length/width);
+ along+=length/width;
+ }
+ previous[0]=next[0]; previous[1]=next[1];
+ outer=(outer+1)%pTrig->getNumPoints();
+ inner=(inner+pTrig->getNumPoints()-1)%pTrig->getNumPoints();
+ }
+ return;
+ }
+#endif
//allocate 2 triangles per side with 3 indices per triangle
DynamicIBAccessClass ib_access(BUFFER_TYPE_DYNAMIC_DX8,(rectangleCount+1)*2*3);
@@ -2940,6 +5126,9 @@ void WaterRenderObjClass::drawRiverWater(PolygonTrigger *pTrig)
//-------------------------------------------------------------------------------------------------
void WaterRenderObjClass::drawReflection(Int triangleCount, Int vertexCount)
{
+#if defined(__linux__)
+ if (m_useModernWater) return; // Modern water samples the mirror in its surface shader.
+#endif
if (!m_pReflectionTexture || !m_reflectionPixelShader)
return; //the card refused a render target or a pixel shader
@@ -2996,7 +5185,7 @@ void WaterRenderObjClass::drawReflection(Int triangleCount, Int vertexCount)
ShaderClass::Invalidate(); //everything above was set behind the shader's back
}
-void WaterRenderObjClass::setupFlatWaterShader(void)
+void WaterRenderObjClass::setupFlatWaterShader(Bool heightCorrection,Bool waveCage)
{
DX8Wrapper::Set_Texture(0,m_riverTexture);
@@ -3088,6 +5277,7 @@ void WaterRenderObjClass::setupFlatWaterShader(void)
if (m_trapezoidWaterPixelShader){
DX8Wrapper::_Get_D3D_Device()->SetPixelShaderConstantF(0, D3DXVECTOR4(REFLECTION_FACTOR, REFLECTION_FACTOR, REFLECTION_FACTOR, 1.0f), 1);
DX8Wrapper::Set_Pixel_Shader(m_trapezoidWaterPixelShader);
+ setupModernWaterShader(FALSE,heightCorrection,waveCage);
}
}
@@ -3096,6 +5286,9 @@ void WaterRenderObjClass::setupFlatWaterShader(void)
//-------------------------------------------------------------------------------------------------
void WaterRenderObjClass::drawTrapezoidWater(Vector3 points[4])
{
+#if defined(__linux__)
+ if (m_useModernWater && m_trapezoidWaterPixelShader) { drawModernWaterPatch(points,FALSE); return; }
+#endif
Vector3 origin(points[0]);
Vector3 uVec1(points[1]);
Vector3 vVec1(points[3]);
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWaterTracks.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWaterTracks.cpp
index 5079216aa..46e2f3175 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWaterTracks.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWaterTracks.cpp
@@ -65,6 +65,11 @@
#include "assetmgr.h"
#include "WW3D2/dx8wrapper.h"
#include "Platform/RenderTypes.h"
+#if defined(__linux__)
+#include "Platform/WaterShoreOverlay.h"
+#endif
+#include <cstdlib>
+#include <cstring>
//#pragma optimize("", off)
@@ -157,6 +162,7 @@ WaterTracksObj::WaterTracksObj(void)
{
m_stageZeroTexture=NULL;
m_bound=false;
+ m_authoredSource=FALSE;
m_initTimeOffset=0;
}
@@ -481,6 +487,9 @@ Int WaterTracksObj::render(DX8VertexBufferClass *vertexBuffer, Int batchStart)
//First insert tail of wave:
Vector2 testPoint(waveTailOrigin);
+#if defined(__linux__)
+ const Bool hasWaterLevel=TheTerrainLogic->getWaterHandle(testPoint.X,testPoint.Y)!=NULL;
+#endif
TheTerrainLogic->isUnderwater(testPoint.X,testPoint.Y,&waterHeight);
vb->x= testPoint.X;
vb->y= testPoint.Y;
@@ -533,7 +542,18 @@ Int WaterTracksObj::render(DX8VertexBufferClass *vertexBuffer, Int batchStart)
Int idxCount=(m_y-1)*(m_x*2+2) - 2; //index count
DX8Wrapper::Set_Index_Buffer(TheWaterTracksRenderSystem->m_indexBuffer,batchStart);
+ #if defined(__linux__)
+ WaterShoreOverlay::Quad shoreTrack;shoreTrack.level=waterHeight;
+ const Vector2 corners[4]={waveTailOrigin,waveTailOrigin+m_perpDir*m_waveFinalWidth*widthFrac,
+ waveFrontOrigin+m_perpDir*m_waveFinalWidth*widthFrac,waveFrontOrigin};
+ for(Int i=0;i<4;++i){shoreTrack.xy[i*2]=corners[i].X;shoreTrack.xy[i*2+1]=corners[i].Y;}
+ PosixWaterShoreTrack(DX8Wrapper::_Get_D3D_Device(),m_authoredSource && hasWaterLevel &&
+ !TheGlobalData->m_isWorldBuilder && !TheGlobalData->m_usingWaterTrackEditor?&shoreTrack:NULL);
+#endif
DX8Wrapper::Draw_Strip(0,idxCount-2,0,m_x*m_y); //there are always n-2 primitives for n index strip.
+#if defined(__linux__)
+ PosixWaterShoreTrack(DX8Wrapper::_Get_D3D_Device(),NULL);
+#endif
return batchStart+m_x*m_y; //return new offset into unused area of vertex buffer
}
@@ -563,6 +583,7 @@ WaterTracksObj *WaterTracksRenderSystem::bindTrack(waveType type)
m_freeModules = mod->m_nextSystem;
mod->m_type=type;
+ mod->m_authoredSource=FALSE;
// put module on the used list (sorted next to similar types)
nextmod=NULL,prevmod=NULL;
@@ -936,6 +957,12 @@ void setFPMode( void );
//=============================================================================
void WaterTracksRenderSystem::flush(RenderInfoClass & rinfo)
{
+#if defined(__linux__)
+ // Developer comparison only: isolate the water-surface surf from the authored .wak
+ // overlay. Normal play keeps the overlay until its per-fragment replacement is valid.
+ const char *legacySurf=std::getenv("ZH_WATER_LEGACY_SURF");
+ if (legacySurf && std::strcmp(legacySurf,"0")==0) return;
+#endif
/** @todo: Optimize system by drawing tracks as triangle strips and use dynamic vertex buffer access.
May also try rendering all tracks with one call to W3D/D3D by grouping them by texture.
Try improving the fit to vertical surfaces like cliffs.
@@ -1137,6 +1164,7 @@ void WaterTracksRenderSystem::loadTracks(void)
flipU ^= 1; //toggle flip state
umod->init(waveTypeInfo[wtype].m_finalHeight,waveTypeInfo[wtype].m_finalWidth,startPos,endPos,waveTypeInfo[wtype].m_textureName,0);
umod->m_flipU=flipU;
+ umod->m_authoredSource=TRUE;
if (waveTypeInfo[wtype].m_secondWaveTimeOffset) //check if we need a second wave to follow
{
@@ -1145,6 +1173,7 @@ void WaterTracksRenderSystem::loadTracks(void)
{
umod->init(waveTypeInfo[wtype].m_finalHeight,waveTypeInfo[wtype].m_finalWidth,startPos,endPos,waveTypeInfo[wtype].m_textureName,waveTypeInfo[wtype].m_secondWaveTimeOffset);
umod->m_flipU = !flipU;
+ umod->m_authoredSource=TRUE;
}
}
}
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/ModernWaterConfig.h b/GeneralsMD/Code/Libraries/Include/Platform/ModernWaterConfig.h
new file mode 100644
index 000000000..0a775276d
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/ModernWaterConfig.h
@@ -0,0 +1,238 @@
+/* Shared, engine-independent material rules for the game and water preview. */
+#pragma once
+
+#include <algorithm>
+#include <cmath>
+#include <locale>
+#include <sstream>
+#include <string>
+#include <vector>
+
+namespace ModernWaterConfig {
+
+struct Color { int r, g, b; };
+inline bool operator==(Color a, Color b) { return a.r == b.r && a.g == b.g && a.b == b.b; }
+
+struct Rule {
+ std::string name;
+ std::vector<Color> colors;
+ std::vector<std::string> textures;
+ Color replacement = {255, 255, 255};
+ float brightness = 1.0f;
+ float pollution = 0.0f;
+ bool bubbles = false;
+ bool enabled = true;
+};
+typedef std::vector<Rule> Rules;
+
+inline Rules Defaults() {
+ Rule rule;
+ rule.name = "PollutedWater";
+ rule.colors.push_back(Color{50, 75, 50});
+ rule.textures.push_back("TSWater03.tga");
+ rule.replacement = Color{45, 58, 11};
+ rule.brightness = 0.67f;
+ rule.pollution = 0.80f;
+ rule.bubbles = true;
+ return Rules(1, rule);
+}
+
+// Authored RGB values are stored by the engine as normalized floats. Round once
+// to their original bytes so float representation cannot break an exact match.
+inline int ColorByte(float value) {
+ if (!std::isfinite(value) || !(value > 0.0f)) return 0;
+ if (value >= 1.0f) return 255;
+ return static_cast<int>(value * 255.0f + 0.5f);
+}
+inline Color ByteColor(float r, float g, float b) {
+ return Color{ColorByte(r), ColorByte(g), ColorByte(b)};
+}
+
+namespace Detail {
+inline std::string Lower(std::string text) {
+ for (std::size_t i = 0; i < text.size(); ++i)
+ if (text[i] >= 'A' && text[i] <= 'Z') text[i] += 'a' - 'A';
+ return text;
+}
+inline std::string Trim(const std::string &text) {
+ const std::size_t first = text.find_first_not_of(" \t\r\n");
+ if (first == std::string::npos) return std::string();
+ return text.substr(first, text.find_last_not_of(" \t\r\n") - first + 1);
+}
+inline std::string TextureBase(const std::string &texture) {
+ const std::size_t slash = texture.find_last_of("/\\");
+ return Lower(texture.substr(slash == std::string::npos ? 0 : slash + 1));
+}
+inline bool ReadColor(const std::string &text, Color &result) {
+ std::istringstream input(text);
+ input.imbue(std::locale::classic());
+ int bytes[3];
+ for (int i = 0; i < 3; ++i) {
+ char channel, colon;
+ if (!(input >> channel >> colon >> bytes[i]) || colon != ':' ||
+ (channel != "RGB"[i] && channel != "rgb"[i]) || bytes[i] < 0 || bytes[i] > 255)
+ return false;
+ }
+ input >> std::ws;
+ if (!input.eof()) return false;
+ result = Color{bytes[0], bytes[1], bytes[2]};
+ return true;
+}
+inline bool ReadUnit(const std::string &text, float minimum, float &value) {
+ std::istringstream input(text);
+ input.imbue(std::locale::classic());
+ float parsed;
+ if (!(input >> parsed) || !std::isfinite(parsed) || parsed < minimum || parsed > 1.0f)
+ return false;
+ input >> std::ws;
+ if (!input.eof()) return false;
+ value = parsed;
+ return true;
+}
+inline bool ReadBool(const std::string &text, bool &value) {
+ const std::string word = Lower(text);
+ if (word != "yes" && word != "no") return false;
+ value = word == "yes";
+ return true;
+}
+inline bool Fail(std::string &error, std::size_t line, const std::string &message) {
+ std::ostringstream output;
+ output << "line " << line << ": " << message;
+ error = output.str();
+ return false;
+}
+} // namespace Detail
+
+// File order decides overlapping rules. Both lists must match; neither is a
+// wildcard. Compare texture basenames because engine callers may pass a path.
+inline const Rule *Match(const Rules &rules, Color color, const std::string &texture) {
+ const std::string basename = Detail::TextureBase(texture);
+ for (Rules::const_iterator rule = rules.begin(); rule != rules.end(); ++rule) {
+ if (!rule->enabled || std::find(rule->colors.begin(), rule->colors.end(), color) == rule->colors.end())
+ continue;
+ for (std::size_t i = 0; i < rule->textures.size(); ++i)
+ if (!basename.empty() && Detail::TextureBase(rule->textures[i]) == basename)
+ return &*rule;
+ }
+ return NULL;
+}
+
+struct Material {
+ Color color = {255, 255, 255};
+ float brightness = 1.0f;
+ float pollution = 0.0f;
+ float tintAmount = 0.0f;
+ bool bubbles = false;
+ std::string ruleName;
+};
+
+// Resolve afresh from the effective map settings, including when leaving a
+// matched map. White is the legacy neutral multiplier, so it preserves the
+// existing blue Modern material; every other authored color keeps its tint.
+inline Material Resolve(const Rules &rules, Color mapColor, const std::string &mapTexture) {
+ Material material;
+ material.color = mapColor;
+ material.tintAmount = mapColor == Color{255, 255, 255} ? 0.0f : 1.0f;
+ if (const Rule *rule = Match(rules, mapColor, mapTexture)) {
+ material.color = rule->replacement;
+ material.brightness = rule->brightness;
+ material.pollution = rule->pollution;
+ material.tintAmount = 1.0f;
+ material.bubbles = rule->bubbles;
+ material.ruleName = rule->name;
+ }
+ return material;
+}
+
+// Parse into a temporary list: a malformed edit cannot leave half of a new
+// configuration installed. An empty/comment-only file intentionally has no
+// rules; callers use Defaults() when the file is missing or fails to parse.
+// Each declaration/assignment occupies one line; semicolons begin comments.
+inline bool Parse(const std::string &text, Rules &result, std::string &error) {
+ enum Section { Outside, InRule, InColors, InTextures } section = Outside;
+ enum Field { Colors = 1, Textures = 2, Replacement = 4, Brightness = 8,
+ Pollution = 16, Bubbles = 32, Enabled = 64 };
+ Rules parsed;
+ Rule current;
+ unsigned fields = 0;
+ std::size_t lineNumber = 0;
+ std::istringstream input(text);
+ std::string line;
+ error.clear();
+ while (std::getline(input, line)) {
+ ++lineNumber;
+ if (lineNumber == 1 && line.compare(0, 3, "\xEF\xBB\xBF") == 0) line.erase(0, 3);
+ const std::size_t comment = line.find(';');
+ if (comment != std::string::npos) line.erase(comment);
+ line = Detail::Trim(line);
+ if (line.empty()) continue;
+ const std::string lower = Detail::Lower(line);
+ if (section == Outside) {
+ std::istringstream declaration(line);
+ std::string keyword, name, extra;
+ if (!(declaration >> keyword >> name) || Detail::Lower(keyword) != "modernwaterrule" || declaration >> extra)
+ return Detail::Fail(error, lineNumber, "expected ModernWaterRule followed by one name");
+ for (std::size_t i = 0; i < parsed.size(); ++i)
+ if (Detail::Lower(parsed[i].name) == Detail::Lower(name))
+ return Detail::Fail(error, lineNumber, "duplicate rule name '" + name + "'");
+ current = Rule();
+ current.name = name;
+ fields = 0;
+ section = InRule;
+ continue;
+ }
+ if (lower == "end") {
+ if (section == InColors || section == InTextures) {
+ if ((section == InColors && current.colors.empty()) ||
+ (section == InTextures && current.textures.empty()))
+ return Detail::Fail(error, lineNumber, "match lists must not be empty");
+ section = InRule;
+ } else {
+ if ((fields & (Colors | Textures | Replacement)) != (Colors | Textures | Replacement))
+ return Detail::Fail(error, lineNumber, "rule needs MatchColors, MatchTextures and ReplacementColor");
+ parsed.push_back(current);
+ section = Outside;
+ }
+ continue;
+ }
+ if (section == InRule && (lower == "matchcolors" || lower == "matchtextures")) {
+ const unsigned field = lower == "matchcolors" ? Colors : Textures;
+ if (fields & field) return Detail::Fail(error, lineNumber, "duplicate " + line + " block");
+ fields |= field;
+ section = field == Colors ? InColors : InTextures;
+ continue;
+ }
+ const std::size_t equals = line.find('=');
+ if (equals == std::string::npos)
+ return Detail::Fail(error, lineNumber, "expected a field assignment or End");
+ const std::string key = Detail::Lower(Detail::Trim(line.substr(0, equals)));
+ const std::string value = Detail::Trim(line.substr(equals + 1));
+ if (section == InColors) {
+ Color color;
+ if (key != "color" || !Detail::ReadColor(value, color))
+ return Detail::Fail(error, lineNumber, "expected Color = R:0..255 G:0..255 B:0..255");
+ current.colors.push_back(color);
+ } else if (section == InTextures) {
+ if (key != "texture" || Detail::TextureBase(value).empty() ||
+ value.find_first_of(" \t=\"") != std::string::npos)
+ return Detail::Fail(error, lineNumber, "expected Texture = filename without spaces");
+ current.textures.push_back(value);
+ } else {
+ unsigned field = 0;
+ bool valid = false;
+ if (key == "replacementcolor") { field = Replacement; valid = Detail::ReadColor(value, current.replacement); }
+ else if (key == "brightness") { field = Brightness; valid = Detail::ReadUnit(value, 0.1f, current.brightness); }
+ else if (key == "pollution") { field = Pollution; valid = Detail::ReadUnit(value, 0.0f, current.pollution); }
+ else if (key == "bubbles") { field = Bubbles; valid = Detail::ReadBool(value, current.bubbles); }
+ else if (key == "enabled") { field = Enabled; valid = Detail::ReadBool(value, current.enabled); }
+ else return Detail::Fail(error, lineNumber, "unknown field '" + key + "'");
+ if (fields & field) return Detail::Fail(error, lineNumber, "duplicate field '" + key + "'");
+ if (!valid) return Detail::Fail(error, lineNumber, "invalid value for '" + key + "'");
+ fields |= field;
+ }
+ }
+ if (section != Outside) return Detail::Fail(error, lineNumber + 1, "unexpected end of file; missing End");
+ result.swap(parsed);
+ return true;
+}
+} // namespace ModernWaterConfig
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/ModernWaterMaterial.h b/GeneralsMD/Code/Libraries/Include/Platform/ModernWaterMaterial.h
new file mode 100644
index 000000000..b297ab190
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/ModernWaterMaterial.h
@@ -0,0 +1,86 @@
+// Authored Modern water materials. These constants do not participate in Classic rendering.
+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.
+#pragma once
+#include <string>
+
+// Keep the two native float4 declarations identical in C++ and generated HLSL.
+#define MODERN_WATER_MATERIAL_UNIFORMS(X) X(MaterialColor) X(MaterialParameters)
+
+namespace ModernWaterMaterial {
+enum : unsigned { RegisterColor=94, RegisterParameters=95, UniformRegisters=2 };
+// c94: display-space RGB, brightness. c95: tint amount, pollution amount, bubbles, reserved.
+// A zero parameter vector preserves the existing clear-water material exactly.
+inline const char *OpticalSource() {
+ return R"HLSL(
+float3 modernWaterMaterialSource(float3 original,float4 colour,float tint,float illumination,float faceLight) {
+ if(!(tint>0.0)) return original;
+ float3 display=saturate(colour.rgb),linearColour=pow(display,2.2);
+ float maximum=max(max(display.r,display.g),display.b);
+ float minimum=min(min(display.r,display.g),display.b);
+ float chroma=(maximum-minimum)/max(maximum,0.00001);
+ // Neutral authored tints attenuate the original water, preserving white as identity.
+ // Chromatic colours introduce their own suspended material instead of multiplying blue by red.
+ float3 neutral=original*pow(maximum,2.2);
+ float3 authored=linearColour*(0.08+0.92*saturate(illumination))*(0.55+1.10*saturate(faceLight));
+ return lerp(original,lerp(neutral,authored,chroma)*saturate(colour.w),saturate(tint));
+}
+float3 modernWaterMaterialHue(float3 colour) {
+ colour=saturate(colour);
+ return colour/max(max(max(colour.r,colour.g),colour.b),0.00001);
+}
+float3 modernWaterMaterialTransmission(float3 original,float3 colour,float pollution,float path,float patch) {
+ if(!(pollution>0.0)) return original;
+ // Preferential extinction follows the selected material; red and blue pollutants need no code changes.
+ float3 extinction=0.004+0.042*(1.0-modernWaterMaterialHue(colour));
+ float density=saturate(pollution)*lerp(0.78,1.0,saturate(patch));
+ return original*exp(-extinction*clamp(path,0.0,80.0)*density);
+}
+float3 modernWaterBubbleFilm(float3 colour) {
+ return 0.05+0.25*modernWaterMaterialHue(colour);
+}
+float modernWaterBubbleWeight(float pollution,float enabled,float depth) {
+ return saturate(pollution)*saturate(enabled)*smoothstep(0.1,1.0,depth);
+}
+)HLSL";
+}
+
+// Uses the Modern shader's deterministic oceanHash; no gameplay random state or simulation objects.
+inline const char *BubbleSource() {
+ return R"HLSL(
+struct ModernWaterBubbles { float2 slope; float cap; float rim; float ripple; };
+ModernWaterBubbles modernWaterBubbles(float2 p,float time,float footprint) {
+ ModernWaterBubbles result=(ModernWaterBubbles)0;
+ // Every emitter's full footprint remains inside its cell, including the expanding pop ring.
+ const float spacing=18.0;
+ float2 cell=floor(p/spacing);
+ float seed=oceanHash(cell+float2(13.1,7.7));
+ float period=4.8+seed*4.2;
+ float clock=time/period+oceanHash(cell+43.7);
+ float cycle=floor(clock);
+ float age=frac(clock)*period;
+ float emit=step(0.28,oceanHash(cell+float2(cycle*7.1,cycle*3.4)));
+ float2 centre=(cell+0.28+0.44*float2(oceanHash(cell+1.5),oceanHash(cell+71.3)))*spacing;
+ centre+=float2(sin(time*0.34+seed*23.0),cos(time*0.28+seed*15.0))*0.35;
+ float2 delta=p-centre;
+ float distance=length(delta);
+ float2 axis=delta/max(distance,0.001);
+ float radius=(0.38+seed*0.68)*smoothstep(0.0,0.9,age);
+ float live=smoothstep(0.0,0.24,age)*(1.0-smoothstep(1.24,1.42,age))*emit;
+ float aa=max(footprint*0.65,0.08);
+ float resolved=1.0-smoothstep(1.0,3.5,footprint);
+ float cap=(1.0-smoothstep(max(0.0,radius-aa),radius+aa,distance))*live*resolved;
+ result.slope=axis*(distance/max(radius,0.08))*cap*0.55;
+ result.cap=cap;
+ result.rim=exp(-pow((distance-radius)/max(aa,0.10),2.0))*live*resolved;
+ float sincePop=age-1.42;
+ float ringRadius=radius+max(0.0,sincePop)*2.3;
+ float ringLife=smoothstep(0.0,0.12,sincePop)*(1.0-smoothstep(0.35,1.20,sincePop))*emit;
+ float width=max(0.19,aa);
+ float ring=exp(-pow((distance-ringRadius)/width,2.0))*ringLife*resolved;
+ result.slope+=axis*ring*(distance-ringRadius)/width*0.16;
+ result.ripple=ring;
+ return result;
+}
+)HLSL";
+}
+}
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterBedMaterial.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterBedMaterial.h
new file mode 100644
index 000000000..57d923fd1
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterBedMaterial.h
@@ -0,0 +1,59 @@
+/* Copyright 2026. SPDX-License-Identifier: GPL-3.0-or-later */
+#pragma once
+
+#include <cmath>
+#include <cstdint>
+#include <algorithm>
+
+// Render-only, tileable material data. No external assets, global RNG state, or map mutations.
+// R: sand grain/ridges, G: rounded pebble colour, B: pebble relief, A: broad rock variation.
+// These are material signals, not a replacement albedo: the shader retains the map's terrain tint
+// and selects sand/gravel coverage from the water setting and the actual submerged terrain slope.
+namespace WaterBedMaterial {
+static constexpr float TileWorldSize = 48.0f;
+
+inline uint32_t Hash(int x, int y, uint32_t seed)
+{
+ uint32_t n = uint32_t(x) * 0x8da6b343u ^ uint32_t(y) * 0xd8163841u ^ seed;
+ n ^= n >> 16; n *= 0x7feb352du; n ^= n >> 15; n *= 0x846ca68bu; n ^= n >> 16;
+ return n;
+}
+inline float Unit(uint32_t n) { return float(n >> 8) / 16777216.0f; }
+inline float Saturate(float v) { return std::max(0.0f, std::min(1.0f, v)); }
+inline float Smooth(float v) { v = Saturate(v); return v*v*(3.0f-2.0f*v); }
+inline int Wrap(int n, int period) { return (n % period + period) % period; }
+
+inline uint32_t Texel(int x, int y, int side)
+{
+ if (side <= 0) return 0;
+ x = Wrap(x, side); y = Wrap(y, side);
+ const float u = (x + 0.5f) / side, v = (y + 0.5f) / side;
+ constexpr float tau = 6.28318530718f;
+ const float grain = Unit(Hash(x, y, 0x81a3u));
+ const float ridges = std::sin(tau * (v*15.0f + 0.22f*std::sin(tau*u*3.0f)
+ + 0.08f*std::sin(tau*(v*2.0f+u))));
+ const float sand = 0.55f + 0.10f*ridges + 0.12f*(grain-0.5f);
+
+ constexpr int cells = 24;
+ const float px = u*cells, py = v*cells;
+ const int ix = int(std::floor(px)), iy = int(std::floor(py));
+ float relief = 0.0f, pebble = sand*0.72f;
+ for (int j = -1; j <= 1; ++j) for (int i = -1; i <= 1; ++i) {
+ const uint32_t hash = Hash(Wrap(ix+i, cells), Wrap(iy+j, cells), 0x93467u);
+ const float cx = ix+i+0.2f+0.6f*Unit(hash);
+ const float cy = iy+j+0.2f+0.6f*Unit(Hash(int(hash), 7, 91));
+ const float radius = 0.25f+0.20f*Unit(Hash(int(hash), 11, 13));
+ const float dx = (px-cx)/radius, dy = (py-cy)/(radius*0.78f);
+ const float dome = std::sqrt(Saturate(1.0f-dx*dx-dy*dy));
+ if (dome > relief) {
+ relief = dome;
+ const float colour = 0.30f+0.47f*Unit(Hash(int(hash), 23, 1));
+ pebble = colour*(0.56f+0.44f*dome) + 0.06f*(grain-0.5f);
+ }
+ }
+ const float rock = Saturate(0.5f + 0.23f*std::sin(tau*(u*3.0f+v*2.0f))
+ + 0.16f*std::sin(tau*(u*7.0f-v*5.0f)) + 0.08f*std::cos(tau*(u*11.0f+v*13.0f)));
+ auto byte = [](float value) { return uint32_t(Saturate(value)*255.0f+0.5f); };
+ return (byte(rock)<<24) | (byte(sand)<<16) | (byte(pebble)<<8) | byte(relief);
+}
+}
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterBowLift.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterBowLift.h
new file mode 100644
index 000000000..3ef837e2b
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterBowLift.h
@@ -0,0 +1,47 @@
+// Positive bow pressure freed from the mean-plane hull ramp. Render-only.
+#pragma once
+#include <cmath>
+#include <algorithm>
+#include <cstdlib>
+#include <cstring>
+#include <string>
+#include "Platform/WaterFftGeometry.h"
+namespace WaterBowLift {
+inline bool Enabled() {
+ const char *value=std::getenv("ZH_WATER_BOW_LIFT");
+ // Enabled for ordinary launches; explicit non-matching values retain the diagnostic fallback.
+ return !value || std::strcmp(value,"floor")==0;
+}
+struct Field { double value=0,dx=0,dy=0; };
+// Contract: B>=0, 0<=D<=F<=1. F retains terrain/floor/obstacle clearance;
+// D also contains mean-hull clearance. Gradients are with respect to mesh parameters.
+inline Field Additional(Field bow,Field free,Field damping) {
+ if(bow.value<=0 || free.value<=damping.value)return {};
+ const double bound=WaterFftGeometry::MaxVerticalDisplacement;
+ const double q=std::tanh(bow.value/bound),limited=bound*q,derivative=1-q*q;
+ const double available=free.value-damping.value;
+ return {available*limited,(free.dx-damping.dx)*limited+available*derivative*bow.dx,
+ (free.dy-damping.dy)*limited+available*derivative*bow.dy};
+}
+inline double Foam(double addedHeight,double weight) {
+ const double bounded=(std::max)(0.0,(std::min)(1.0,addedHeight*.32));
+ return bounded*(std::max)(0.0,(std::min)(1.0,weight))*.65;
+}
+inline std::string Source() {return R"HLSL(
+// Added height is positive and consumes only the unused F-D part of the old
+// global vertical envelope. The complete height is D*L(A+B)+(F-D)*L(B).
+// Both terms stay inside the existing F*V bound; ambient/stern and XY are unchanged.
+float3 fftBowLift(float3 bow,float3 freeField,float3 dampingField) {
+ if(bow.x<=0.0 || freeField.x<=dampingField.x)return 0;
+ float q=tanh(bow.x/fftVerticalBound),limited=fftVerticalBound*q;
+ float available=freeField.x-dampingField.x;
+ return float3(available*limited,(freeField.yz-dampingField.yz)*limited+
+ available*(1.0-q*q)*bow.yz);
+}
+float fftBowLiftFoam(float addedHeight,float weight) {
+ // Reuse the existing .32 crest conversion and .65 coverage. The input is
+ // actual extra limited height, already attenuated by F-D, never raw pressure.
+ return saturate(addedHeight*0.32)*saturate(weight)*0.65;
+}
+)HLSL";}
+}
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterBowRefinement.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterBowRefinement.h
new file mode 100644
index 000000000..e79e858d1
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterBowRefinement.h
@@ -0,0 +1,388 @@
+/* Bounded render-only refinement of projected water near a submitted vessel's bow. */
+#pragma once
+#include "Platform/WaterProjectedMesh.h"
+#include "Platform/WaterHullModel.h"
+#include "Platform/WaterFftGeometry.h"
+#include "Platform/WaterVesselWaves.h"
+#include <array>
+#include <map>
+#include <limits>
+
+namespace WaterBowRefinement {
+using Point=WaterProjectedMesh::Point;
+struct Logical { int x=0,y=0; bool operator<(const Logical &b) const { return x<b.x || (x==b.x && y<b.y); } };
+struct Node { Logical logical;Point screen{},world{};int source=-1,parent=-1; };
+struct Triangle { unsigned a=0,b=0,c=0;double gate=1; };
+struct Topology { std::vector<Node> nodes;std::vector<Triangle> triangles; };
+constexpr unsigned MaxRegions=3,RegionVertices=2730,RegionTriangles=5460;
+constexpr unsigned MaxAddedVertices=MaxRegions*RegionVertices,MaxAddedTriangles=MaxRegions*RegionTriangles;
+constexpr unsigned MaxTopologyNodes=10000,MaxTopologyTriangles=19000;
+constexpr double CoreRadius=4,WindowRadius=6,AdmissionSeconds=.25;
+inline double Saturate(double x) { return (std::max)(0.0,(std::min)(1.0,x)); }
+inline double Smooth(double a,double b,double x) { const double t=Saturate((x-a)/(b-a));return t*t*(3-2*t); }
+inline bool Finite(Point p) { return std::isfinite(p.x)&&std::isfinite(p.y); }
+
+// Red subdivision with shared edge samples also represents green stitches: a zero edge
+// collapses to its canonical logical endpoint. Children target their CURRENT parents, so
+// topology birth/death converges even after a nonlinear GPU displacement/sample operation.
+// Output is atomic on rejection; independent callers may stress every edge separately.
+template<class Weight> bool Subdivide(const Topology &input,const WaterProjectedMesh::Projection &projection,
+ Weight weight,Topology &output,unsigned levels=2,bool lockBoundary=true) {
+ if(levels>2 || input.nodes.size()>MaxTopologyNodes || input.triangles.size()>MaxTopologyTriangles) return false;
+ for(const Node &n:input.nodes) if(!Finite(n.world)||!Finite(n.screen)) return false;
+ for(const Triangle &t:input.triangles) if(t.a>=input.nodes.size()||t.b>=input.nodes.size()||t.c>=input.nodes.size()||
+ !std::isfinite(t.gate)||t.gate<0||t.gate>1) return false;
+ Topology current=input;
+ std::vector<Point> targets;targets.reserve(MaxTopologyNodes);for(const Node &n:input.nodes) targets.push_back(n.screen);
+ for(unsigned level=1;level<=levels;++level) {
+ if(current.triangles.size()>MaxTopologyTriangles/4) return false;
+ struct Edge { unsigned lo=0,hi=0,count=0,node=0;double gate=1,amount=0; };
+ using Key=std::array<int,4>;std::map<Key,Edge> edges;
+ auto edgeKey=[&](unsigned a,unsigned b) {
+ if(current.nodes[b].logical<current.nodes[a].logical) std::swap(a,b);
+ const Logical x=current.nodes[a].logical,y=current.nodes[b].logical;
+ return Key{{x.x,x.y,y.x,y.y}};
+ };
+ for(const Triangle &t:current.triangles) {
+ const unsigned p[3]={t.a,t.b,t.c};
+ for(unsigned e=0;e<3;++e) {
+ unsigned a=p[e],b=p[(e+1)%3];if(current.nodes[b].logical<current.nodes[a].logical) std::swap(a,b);
+ Edge &edge=edges[edgeKey(a,b)];edge.lo=a;edge.hi=b;++edge.count;edge.gate=(std::min)(edge.gate,t.gate);
+ }
+ }
+ if(current.nodes.size()+edges.size()>MaxTopologyNodes) return false;
+ current.nodes.reserve(current.nodes.size()+edges.size());
+ for(auto &entry:edges) {
+ Edge &e=entry.second;const Node lo=current.nodes[e.lo],hi=current.nodes[e.hi];
+ Node node;node.logical={(lo.logical.x+hi.logical.x)/2,(lo.logical.y+hi.logical.y)/2};
+ const Point target={(targets[e.lo].x+targets[e.hi].x)*.5,(targets[e.lo].y+targets[e.hi].y)*.5};
+ Point finalWorld;if(!projection.Transform(target,finalWorld,true)) return false;
+ const double demand=weight(level,node.logical,finalWorld);
+ if(!std::isfinite(demand)||demand<0||demand>1) return false;
+ e.amount=(lockBoundary&&e.count==1)?0:demand*e.gate;
+ if(e.amount==0 || (lo.screen.x==hi.screen.x && lo.screen.y==hi.screen.y)) {
+ node.screen=lo.screen;node.world=lo.world;node.parent=int(e.lo);
+ } else {
+ node.screen={lo.screen.x+(hi.screen.x-lo.screen.x)*(.5*e.amount),lo.screen.y+(hi.screen.y-lo.screen.y)*(.5*e.amount)};
+ if(!projection.Transform(node.screen,node.world,true)) return false;
+ }
+ e.node=unsigned(current.nodes.size());current.nodes.push_back(node);targets.push_back(target);
+ }
+ std::vector<Triangle> triangles;triangles.reserve(current.triangles.size()*4);
+ for(const Triangle &t:current.triangles) {
+ const Edge &ab=edges.at(edgeKey(t.a,t.b)),&bc=edges.at(edgeKey(t.b,t.c)),&ca=edges.at(edgeKey(t.c,t.a));
+ // Every parent edge must open before its children gain detail. If just one edge
+ // collapses, a degenerate child's distinct logical edge can coincide with another
+ // physical edge; independently splitting it would break nonlinear displaced seams.
+ // The minimum fades all such coincident descendants to exact aliases continuously.
+ const double gate=t.gate*(std::min)({ab.amount,bc.amount,ca.amount});
+ triangles.push_back({t.a,ab.node,ca.node,gate});triangles.push_back({ab.node,t.b,bc.node,gate});
+ triangles.push_back({ca.node,bc.node,t.c,gate});triangles.push_back({ab.node,bc.node,ca.node,gate});
+ }
+ current.triangles.swap(triangles);
+ }
+ output=std::move(current);return true;
+}
+
+struct Bow {
+ unsigned id=0;double level=0;
+ bool shoulder=false;WaterBowShoulder::Contour contour{};
+ // origin is the real contact endpoint; centre is a floor/visibility probe at the end
+ // of the clearance ramp, never a second displacement anchor in front of the vessel.
+ Point origin{},centre{},forward{},hullCentre{};
+ double sigmaAlong=0,sigmaAcross=0,amplitude=0,moving=0,reach=0;
+};
+inline bool MakeBow(unsigned id,const WaterHullModel::Hull &mean,const WaterHullModel::Hull &contact,double level,Bow &out,bool shoulder=WaterBowShoulder::Enabled()) {
+ if(!std::isfinite(level)) return false;
+ const auto &h=contact.data[0][3]>=3&&contact.data[0][3]<=12?contact:mean;
+ for(unsigned row=0;row<4;++row) for(float value:h.data[row]) if(!std::isfinite(value)) return false;
+ if(h.data[0][3]<3||h.data[0][3]>12||std::abs(level-h.data[0][2])>.1) return false;
+ const double speed=std::hypot(h.data[2][0],h.data[2][1]);if(!(speed>double(.3f))) return false;
+ Bow b;b.id=id;b.level=level;b.hullCentre={h.data[0][0],h.data[0][1]};
+ b.forward={h.data[2][0]/speed,h.data[2][1]/speed};
+ const double blend=Smooth(-.25,.25,b.forward.x*h.data[1][0]+b.forward.y*h.data[1][1]);
+ const double x=h.data[3][0]+(h.data[3][2]-h.data[3][0])*blend,y=h.data[3][1]+(h.data[3][3]-h.data[3][1])*blend;
+ b.origin={b.hullCentre.x+x*h.data[1][0]-y*h.data[1][1],b.hullCentre.y+x*h.data[1][1]+y*h.data[1][0]};
+ b.centre={b.origin.x+WaterHullModel::FadeDistance*b.forward.x,b.origin.y+WaterHullModel::FadeDistance*b.forward.y};
+ const auto pressure=WaterVesselWaves::BowPressure(h.data[1][3],float(speed));
+ b.sigmaAlong=pressure.along;b.sigmaAcross=pressure.across;b.amplitude=pressure.amplitude;
+ b.moving=Smooth(.3,14,speed);b.reach=h.data[2][3]+110;
+ if(shoulder) {
+ if(!WaterBowShoulder::Prepare(h,level,pressure.along,pressure.amplitude,b.contour))return false;
+ b.shoulder=true;
+ const auto origin=WaterBowShoulder::ToWorld(b.contour,b.contour.supportCentre);
+ b.origin={origin.x,origin.y};
+ // Narrowest ridge scale in every orientation, including turning/broadside motion.
+ b.sigmaAlong=b.sigmaAcross=b.contour.width;
+ b.centre={b.origin.x+WaterBowShoulder::ShoulderOffset*b.contour.width*b.forward.x,
+ b.origin.y+WaterBowShoulder::ShoulderOffset*b.contour.width*b.forward.y};
+ }
+ if(!Finite(b.centre)||b.sigmaAlong<=0||b.sigmaAcross<=0||b.reach<=0) return false;
+ out=b;return true;
+}
+struct View { WaterProjectedMesh::Projection projection;WaterProjectedMesh::Resolution resolution;double width=0,height=0;double verticalClip[3]={}; };
+struct Prepared { Bow bow;Point screen{},cell{};double desiredDepth=0,heightGate=0; };
+inline bool PrepareBow(const Bow &bow,const View &view,Prepared &out,double safeAmplitude=1) {
+ if(!std::isfinite(view.width)||!std::isfinite(view.height)||view.width<=0||view.height<=0||
+ view.resolution.columns<2||view.resolution.rows<2||!std::isfinite(safeAmplitude)||
+ !Finite(bow.origin)||!Finite(bow.centre)||!Finite(bow.forward)||!Finite(bow.hullCentre)||
+ !std::isfinite(bow.reach)||bow.reach<=0||
+ !std::isfinite(bow.sigmaAlong)||bow.sigmaAlong<=0||!std::isfinite(bow.sigmaAcross)||bow.sigmaAcross<=0||
+ !std::isfinite(bow.amplitude)||bow.amplitude<0||
+ !std::isfinite(bow.moving)||bow.moving<0||bow.moving>1) return false;
+ Prepared p;p.bow=bow;if(!view.projection.Transform(bow.centre,p.screen)) return false;
+ const double *m=view.projection.matrix,w=m[6]*bow.centre.x+m[7]*bow.centre.y+m[8];if(w<=1e-9) return false;
+ const double j[4]={(m[0]-p.screen.x*m[6])/w*view.width*.5,(m[1]-p.screen.x*m[7])/w*view.width*.5,
+ (m[3]-p.screen.y*m[6])/w*view.height*.5,(m[4]-p.screen.y*m[7])/w*view.height*.5};
+ const Point a={bow.sigmaAlong*(j[0]*bow.forward.x+j[1]*bow.forward.y),bow.sigmaAlong*(j[2]*bow.forward.x+j[3]*bow.forward.y)};
+ const Point b={bow.sigmaAcross*(-j[0]*bow.forward.y+j[1]*bow.forward.x),bow.sigmaAcross*(-j[2]*bow.forward.y+j[3]*bow.forward.x)};
+ const double xx=a.x*a.x+b.x*b.x,yy=a.y*a.y+b.y*b.y,xy=a.x*a.y+b.x*b.y;
+ const double major=.5*(xx+yy+std::hypot(xx-yy,2*xy)),det=(a.x*b.y-a.y*b.x)*(a.x*b.y-a.y*b.x);
+ const double minor=std::sqrt((std::max)(0.0,det/(std::max)(major,1e-20)));
+ const double limit=1+view.projection.margin,step=(std::max)(limit*view.width/view.resolution.columns,limit*view.height/view.resolution.rows);
+ p.desiredDepth=(std::max)(0.0,(std::min)(2.0,std::log2(3*step/(std::max)(1.665109222*minor,1e-9))));
+ const double vzx=(view.verticalClip[0]-p.screen.x*view.verticalClip[2])/w*view.width*.5;
+ const double vzy=(view.verticalClip[1]-p.screen.y*view.verticalClip[2])/w*view.height*.5;
+ const auto probe=WaterVesselWaves::EvaluateBowPressure(
+ {float(bow.sigmaAlong),float(bow.sigmaAcross),float(bow.amplitude)},WaterHullModel::FadeDistance,0);
+ const double bound=WaterFftGeometry::MaxVerticalDisplacement;
+ const double rawProbe=bow.shoulder?WaterBowShoulder::Evaluate(bow.contour,{bow.centre.x,bow.centre.y}).value:probe.height;
+ const double height=bound*std::tanh(rawProbe/bound)*Saturate(safeAmplitude);
+ p.heightGate=Smooth(.25,1,std::hypot(vzx,vzy)*height);
+ // Keep the floor/visibility probe at +9, but center the fixed detail window on
+ // the world pressure anchor. Its inverse horizontal map can lie on either side.
+ Point anchorScreen;if(!view.projection.Transform(bow.origin,anchorScreen)) return false;
+ p.cell={(anchorScreen.x/limit+1)*view.resolution.columns*.5,(anchorScreen.y/limit+1)*view.resolution.rows*.5};
+ if(!Finite(p.cell)||!std::isfinite(p.desiredDepth)||!std::isfinite(p.heightGate)) return false;
+ out=p;return true;
+}
+inline double Demand(const Prepared &p,unsigned level,Logical at,Point world,double admission=1) {
+ if(level<1||level>2||!Finite(world)) return 0;
+ const double dx=world.x-p.bow.origin.x,dy=world.y-p.bow.origin.y;
+ const double across=(-dx*p.bow.forward.y+dy*p.bow.forward.x)/p.bow.sigmaAcross;
+ const double along=(dx*p.bow.forward.x+dy*p.bow.forward.y)/p.bow.sigmaAlong+
+ WaterVesselWaves::BowCurvature*(std::sqrt(1+across*across)-1);
+ // Bound the inverse image of the registered bow field without CPU FFT sampling.
+ // The curved normalized profile has a global Jacobian Frobenius bound L; moving
+ // by at most R can reduce its profile distance by at most R*L. Radial support
+ // expands by R as well. The existing cell crop and topology budgets stay fixed.
+ const double radius=WaterFftGeometry::MaxHorizontalDisplacement;
+ const double lipschitz=std::sqrt(1/(p.bow.sigmaAlong*p.bow.sigmaAlong)+
+ (1+WaterVesselWaves::BowCurvature*WaterVesselWaves::BowCurvature)/(p.bow.sigmaAcross*p.bow.sigmaAcross));
+ const double profile=(std::max)(0.0,std::hypot(along,across)-radius*lipschitz);
+ const double radial=(std::max)(0.0,std::hypot(world.x-p.bow.hullCentre.x,world.y-p.bow.hullCentre.y)-radius);
+ double physical=(1-Smooth(1.5,3,profile))*(1-Smooth(p.bow.reach-30,p.bow.reach,radial));
+ if(p.bow.shoulder) {
+ const auto lower=WaterBowShoulder::InverseProfileLowerBounds(p.bow.contour,{world.x,world.y},radius);
+ physical=(1-Smooth(WaterBowShoulder::ShoulderFadeStart,WaterBowShoulder::ShoulderFadeEnd,lower.x))*
+ (1-Smooth(WaterBowShoulder::ShoulderFadeStart,WaterBowShoulder::ShoulderFadeEnd,lower.y))*
+ (1-Smooth(p.bow.reach-30,p.bow.reach,radial));
+ }
+ const double cellDistance=(std::max)(std::abs(at.x*.25-p.cell.x),std::abs(at.y*.25-p.cell.y));
+ const double window=1-Smooth(3,CoreRadius,cellDistance);
+ return Smooth(0,1,p.desiredDepth-double(level-1))*p.heightGate*physical*window*Saturate(admission);
+}
+// Exact authored patch identity; no camera coordinate or transient draw index participates.
+struct PatchKey { std::array<uint32_t,12> words{};uintptr_t owner=0;unsigned part=0;
+ bool operator==(const PatchKey &b) const { return words==b.words&&owner==b.owner&&part==b.part; } };
+inline PatchKey MakePatchKey(const Point corners[4],float level,uintptr_t owner=0,unsigned part=0) {
+ PatchKey key;key.owner=owner;key.part=part;for(unsigned i=0;i<4;++i) {
+ const auto p=WaterProjectedMesh::SampleKey(float(corners[i].x),float(corners[i].y),level);
+ key.words[i*3]=p.x;key.words[i*3+1]=p.y;key.words[i*3+2]=p.z;
+ }return key;
+}
+struct Active { Prepared prepared;double amount=0; };
+class Admissions {
+public:
+ struct Slot { bool occupied=false,seen=false;PatchKey patch;Bow bow;double amount=0,previous=0; };
+private:
+ std::array<Slot,MaxRegions> slots{};double lastTime=0,step=0;bool initialized=false;
+public:
+ void Clear() { slots={};lastTime=step=0;initialized=false; }
+ void Begin(double time) {
+ if(!std::isfinite(time)) { Clear();return; }
+ if(initialized&&time<lastTime) Clear();
+ step=initialized?(std::min)(1.0,(time-lastTime)/AdmissionSeconds):0;lastTime=time;initialized=true;
+ for(auto &s:slots) { s.seen=false;s.previous=s.amount;s.amount=(std::max)(0.0,s.amount-step); }
+ }
+ // The base keeps its existing budget. A separate fixed global reserve owns local detail;
+ // this bound ensures its three regions always fit each draw's 16-bit vertex addressing.
+ static size_t WorstBaseVertices() {
+ return WaterProjectedMesh::VertexBound(192,128,4u*(WaterSurfaceModel::MeshCells+1));
+ }
+ bool Request(const PatchKey &patch,const Bow &bow,size_t patchBudget) {
+ unsigned samePatch=0;Slot *empty=nullptr;
+ for(auto &s:slots) {
+ if(!s.occupied) { if(!empty) empty=&s;continue; }
+ if(s.patch==patch) ++samePatch;
+ if(s.patch==patch&&s.bow.id==bow.id) {
+ // A teleport cannot move a live refinement window to unrelated geometry.
+ // Retire the old window, then admit the new location from zero.
+ if(std::hypot(s.bow.centre.x-bow.centre.x,s.bow.centre.y-bow.centre.y)>64) return false;
+ if(!s.seen) s.amount=(std::min)(1.0,s.previous+step);s.seen=true;s.bow=bow;return true;
+ }
+ }
+ if(!empty || patchBudget==0 || patchBudget>65535 ||
+ (std::min)(patchBudget,WorstBaseVertices())+size_t(samePatch+1)*RegionVertices>65535) return false;
+ empty->occupied=true;empty->seen=true;empty->patch=patch;empty->bow=bow;empty->amount=0;return true;
+ }
+ void End() { for(auto &s:slots) if(s.occupied&&!s.seen&&s.amount==0) s=Slot{}; }
+ const std::array<Slot,MaxRegions> &Slots() const { return slots; }
+};
+
+// Protection goes to zero before any authored FFT collar, clipped-cell topology or frustum
+// boundary can change eligibility. It is deliberately more conservative than FFT's seam fade.
+class Protection {
+ struct Line { WaterProjectedMesh::Plane world,screen;double worldScale=0,screenScale=0; };
+ std::vector<Line> lines;WaterProjectedMesh::Projection projection{};
+public:
+ bool Prepare(const Point corners[4],const View &view) {
+ lines.clear();projection=view.projection;
+ const double sx=2*(1+projection.margin)/view.resolution.columns,sy=2*(1+projection.margin)/view.resolution.rows;
+ auto add=[&](WaterProjectedMesh::Plane plane,bool world) {
+ Line e;e.world=plane;e.worldScale=world?1/(std::max)(1e-20,std::hypot(plane.a,plane.b)):0;
+ const double *m=projection.inverse;
+ e.screen={plane.a*m[0]+plane.b*m[3]+plane.c*m[6],plane.a*m[1]+plane.b*m[4]+plane.c*m[7],plane.a*m[2]+plane.b*m[5]+plane.c*m[8]};
+ const double length=std::hypot(e.screen.a*sx,e.screen.b*sy);e.screenScale=length>1e-12?1/length:0;lines.push_back(e);
+ };
+ for(unsigned i=0;i<4;++i) { const Point a=corners[i],b=corners[(i+1)%4];
+ if(std::hypot(b.x-a.x,b.y-a.y)>1e-12) add({a.y-b.y,b.x-a.x,a.x*b.y-b.x*a.y},true); }
+ add({projection.depth.a,projection.depth.b,projection.depth.c-projection.nearDistance},false);
+ add({-projection.depth.a,-projection.depth.b,projection.farDistance-projection.depth.c},false);
+ return true;
+ }
+ double Gate(Point world,Point screen,const View &view) const {
+ double gate=1;
+ for(const Line &e:lines) {
+ if(e.worldScale>0) gate=(std::min)(gate,Smooth(24,36,std::abs(WaterProjectedMesh::Distance(e.world,world))*e.worldScale));
+ if(e.screenScale>0) gate=(std::min)(gate,Smooth(4,6,std::abs(WaterProjectedMesh::Distance(e.screen,screen))*e.screenScale));
+ }
+ const double limit=1+projection.margin;
+ gate=(std::min)(gate,Smooth(2,4,(limit-std::abs(screen.x))*view.resolution.columns/(2*limit)));
+ gate=(std::min)(gate,Smooth(2,4,(limit-std::abs(screen.y))*view.resolution.rows/(2*limit)));
+ return gate;
+ }
+};
+// One extraction path is shared by admission and actual tessellation. Screen-visible hulls
+// alone are insufficient: another same-level polygon must not spend a region's reservation.
+inline bool Collect(const WaterProjectedMesh::Mesh &mesh,const View &view,const Point corners[4],
+ const std::vector<Active> &active,Topology &base,std::vector<unsigned> &sourceTriangles) {
+ if(view.resolution.columns<2||view.resolution.rows<2||mesh.indices.size()%3||active.size()>MaxRegions) return false;
+ Protection protection;protection.Prepare(corners,view);
+ base.nodes.clear();base.triangles.clear();sourceTriangles.clear();
+ std::vector<int> nodeFor(mesh.vertices.size(),-1);
+ auto eligible=[](const WaterProjectedMesh::Vertex &v) { return v.lattice>=0&&v.boundary<0&&v.knot<0&&v.transition<0&&v.collar<0; };
+ for(size_t i=0;i<mesh.indices.size();i+=3) {
+ const unsigned ids[3]={mesh.indices[i],mesh.indices[i+1],mesh.indices[i+2]};
+ for(unsigned id:ids) if(id>=mesh.vertices.size()) return false;
+ if(!eligible(mesh.vertices[ids[0]])||!eligible(mesh.vertices[ids[1]])||!eligible(mesh.vertices[ids[2]])) continue;
+ int column=view.resolution.columns,row=view.resolution.rows;
+ for(unsigned id:ids) { const int slot=mesh.vertices[id].lattice;column=(std::min)(column,slot%(view.resolution.columns+1));row=(std::min)(row,slot/(view.resolution.columns+1)); }
+ bool selected=false;
+ for(const Active &a:active) if(a.amount>0 && a.prepared.heightGate>0 && a.prepared.desiredDepth>0 &&
+ column>=std::floor(a.prepared.cell.x-WindowRadius)&&column<=std::floor(a.prepared.cell.x+WindowRadius)&&
+ row>=std::floor(a.prepared.cell.y-WindowRadius)&&row<=std::floor(a.prepared.cell.y+WindowRadius)) selected=true;
+ if(!selected) continue;
+ Triangle t;unsigned *target[3]={&t.a,&t.b,&t.c};
+ for(unsigned k=0;k<3;++k) {
+ const unsigned id=ids[k];const auto &v=mesh.vertices[id];
+ if(nodeFor[id]<0) {
+ Node n;n.source=int(id);n.world=v.world;n.logical={4*(v.lattice%(view.resolution.columns+1)),4*(v.lattice/(view.resolution.columns+1))};
+ const double limit=1+view.projection.margin;
+ n.screen={limit*(double(n.logical.x)*.5/view.resolution.columns-1),limit*(double(n.logical.y)*.5/view.resolution.rows-1)};
+ nodeFor[id]=int(base.nodes.size());base.nodes.push_back(n);
+ }
+ *target[k]=unsigned(nodeFor[id]);const Node &n=base.nodes[*target[k]];
+ t.gate=(std::min)(t.gate,protection.Gate(n.world,n.screen,view));
+ }
+ if(base.triangles.size()>=active.size()*13u*13u*2u) return false;
+ base.triangles.push_back(t);sourceTriangles.push_back(unsigned(i/3));
+ }
+ return true;
+}
+inline bool HasRefinableDemand(const WaterProjectedMesh::Mesh &mesh,const View &view,const Point corners[4],const Prepared &prepared) {
+ if(!Finite(prepared.cell)||!std::isfinite(prepared.desiredDepth)||!std::isfinite(prepared.heightGate)||
+ prepared.desiredDepth<=0||prepared.heightGate<=0) return false;
+ Topology base;std::vector<unsigned> source;
+ if(!Collect(mesh,view,corners,{{prepared,1}},base,source)) return false;
+ struct Edge { unsigned count=0;double gate=1; };
+ std::map<std::pair<unsigned,unsigned>,Edge> edges;
+ for(const Triangle &t:base.triangles) {
+ const unsigned p[3]={t.a,t.b,t.c};
+ for(unsigned i=0;i<3;++i) {
+ const auto key=std::minmax(p[i],p[(i+1)%3]);auto &edge=edges[{key.first,key.second}];
+ ++edge.count;edge.gate=(std::min)(edge.gate,t.gate);
+ }
+ }
+ for(const auto &entry:edges) {
+ if(entry.second.count!=2||entry.second.gate<=0) continue;
+ const Node &a=base.nodes[entry.first.first],&b=base.nodes[entry.first.second];
+ const Point screen={(a.screen.x+b.screen.x)*.5,(a.screen.y+b.screen.y)*.5};Point world;
+ if(!view.projection.Transform(screen,world,true)) continue;
+ if(Demand(prepared,1,{(a.logical.x+b.logical.x)/2,(a.logical.y+b.logical.y)/2},world)>0) return true;
+ }
+ return false;
+}
+struct Stats { size_t regions=0,addedVertices=0,addedTriangles=0,sourceTriangles=0;bool rejected=false; };
+inline bool Refine(WaterProjectedMesh::Mesh &mesh,const View &view,const Point corners[4],
+ const std::vector<Active> &active,size_t budget,Stats &stats,
+ size_t addedVertexBudget=MaxAddedVertices,size_t addedTriangleBudget=MaxAddedTriangles) {
+ stats={};if(active.empty()) return true;
+ if(view.resolution.columns<2||view.resolution.rows<2||!std::isfinite(view.width)||!std::isfinite(view.height)||
+ view.width<=0||view.height<=0) { stats.rejected=true;return false; }
+ if(active.size()>MaxRegions||mesh.vertices.size()>budget||mesh.indices.size()%3) { stats.rejected=true;return false; }
+ for(const Active &a:active) {
+ const Prepared &p=a.prepared;
+ if(!std::isfinite(a.amount)||a.amount<0||a.amount>1||!Finite(p.screen)||!Finite(p.cell)||
+ !std::isfinite(p.desiredDepth)||p.desiredDepth<0||p.desiredDepth>2||
+ !std::isfinite(p.heightGate)||p.heightGate<0||p.heightGate>1||
+ !Finite(p.bow.origin)||!Finite(p.bow.centre)||!Finite(p.bow.forward)||
+ !std::isfinite(p.bow.sigmaAlong)||p.bow.sigmaAlong<=0||!std::isfinite(p.bow.sigmaAcross)||p.bow.sigmaAcross<=0||
+ !std::isfinite(p.bow.amplitude)||p.bow.amplitude<0||!Finite(p.bow.hullCentre)||!std::isfinite(p.bow.reach)||p.bow.reach<=0) {
+ stats.rejected=true;return false;
+ }
+ }
+ for(uint16_t index:mesh.indices) if(index>=mesh.vertices.size()) { stats.rejected=true;return false; }
+ Topology base;std::vector<unsigned> sourceTriangles;
+ if(!Collect(mesh,view,corners,active,base,sourceTriangles)) { stats.rejected=true;return false; }
+ if(base.triangles.empty()) return true;
+ if(base.triangles.size()>active.size()*13u*13u*2u) { stats.rejected=true;return false; }
+ Topology refined;
+ const auto demand=[&](unsigned level,Logical logical,Point world) {
+ double result=0;for(const Active &a:active) result=(std::max)(result,Demand(a.prepared,level,logical,world,a.amount));return result;
+ };
+ if(!Subdivide(base,view.projection,demand,refined,2,true)) { stats.rejected=true;return false; }
+ std::vector<WaterProjectedMesh::Vertex> added;added.reserve(active.size()*RegionVertices);
+ std::vector<uint16_t> mapped(refined.nodes.size());
+ for(size_t i=0;i<refined.nodes.size();++i) {
+ const Node &n=refined.nodes[i];
+ if(n.source>=0) mapped[i]=uint16_t(n.source);
+ else if(n.parent>=0) mapped[i]=mapped[size_t(n.parent)];
+ else {
+ const size_t next=mesh.vertices.size()+added.size();
+ if(next>=budget||next>=65535||added.size()>=(std::min)(size_t(active.size()*RegionVertices),addedVertexBudget)) { stats.rejected=true;return false; }
+ WaterProjectedMesh::Vertex v;v.world=n.world;mapped[i]=uint16_t(next);added.push_back(v);
+ }
+ }
+ // No real new sample means exact original indices, attributes and shader work remain.
+ if(added.empty()) return true;
+ std::vector<uint16_t> replacement;replacement.reserve(refined.triangles.size()*3);
+ for(const Triangle &t:refined.triangles) {
+ const uint16_t a=mapped[t.a],b=mapped[t.b],c=mapped[t.c];
+ if(a==b||b==c||c==a) continue;
+ replacement.insert(replacement.end(),{a,b,c});
+ }
+ const size_t addedTriangles=replacement.size()/3-sourceTriangles.size();
+ if(addedTriangles>(std::min)(size_t(active.size()*RegionTriangles),addedTriangleBudget)) { stats.rejected=true;return false; }
+ std::vector<uint16_t> indices;indices.reserve(mesh.indices.size()+addedTriangles*3);
+ size_t selected=0;
+ for(size_t i=0;i<mesh.indices.size()/3;++i) {
+ if(selected<sourceTriangles.size()&&sourceTriangles[selected]==i) { ++selected;continue; }
+ indices.insert(indices.end(),mesh.indices.begin()+i*3,mesh.indices.begin()+i*3+3);
+ }
+ indices.insert(indices.end(),replacement.begin(),replacement.end());
+ mesh.vertices.insert(mesh.vertices.end(),added.begin(),added.end());mesh.indices.swap(indices);
+ stats.regions=active.size();stats.sourceTriangles=sourceTriangles.size();stats.addedVertices=added.size();stats.addedTriangles=addedTriangles;return true;
+}
+
+}
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterBowShoulder.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterBowShoulder.h
new file mode 100644
index 000000000..40b6f761c
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterBowShoulder.h
@@ -0,0 +1,162 @@
+/* Render-only exterior bow shoulder. No gameplay/transport state. */
+#pragma once
+#include "Platform/WaterHullModel.h"
+#include <cstdlib>
+#include <cstring>
+#include <string>
+namespace WaterBowShoulder {
+inline bool Enabled() { const char *v=std::getenv("ZH_WATER_BOW_SHOULDER");return !v||std::strcmp(v,"contour")==0; }
+#define WATER_BOW_SHOULDER_CONSTANTS(X) \
+ X(ShoulderWidthBeam,.45f) X(ShoulderWidthMin,3.0f) X(ShoulderWidthMax,12.0f) \
+ X(ShoulderOffset,.5f) X(ShoulderFadeStart,1.5f) X(ShoulderFadeEnd,3.0f)
+#define WATER_BOW_SHOULDER_CPP(name,value) constexpr double name=value;
+WATER_BOW_SHOULDER_CONSTANTS(WATER_BOW_SHOULDER_CPP)
+#undef WATER_BOW_SHOULDER_CPP
+struct Point { double x=0,y=0; };
+inline Point operator+(Point a,Point b) { return {a.x+b.x,a.y+b.y}; }
+inline Point operator-(Point a,Point b) { return {a.x-b.x,a.y-b.y}; }
+inline Point operator*(Point a,double b) { return {a.x*b,a.y*b}; }
+inline double Dot(Point a,Point b) { return a.x*b.x+a.y*b.y; }
+inline double Clamp(double x,double a,double b) { return (std::max)(a,(std::min)(b,x)); }
+inline bool Finite(Point p) { return std::isfinite(p.x)&&std::isfinite(p.y); }
+struct Field { double value=0,dx=0,dy=0; };
+inline Field Multiply(Field a,Field b) { return {a.value*b.value,a.dx*b.value+b.dx*a.value,a.dy*b.value+b.dy*a.value}; }
+// C1 compact Gaussian. Exact zero outside |x|>=3, so broad-phase rejection is supported.
+inline Field Profile(double x,Point gradient) {
+ const double a=std::abs(x);if(a>=ShoulderFadeEnd)return {};
+ const double t=Clamp((a-ShoulderFadeStart)/(ShoulderFadeEnd-ShoulderFadeStart),0,1);
+ const double fade=1-t*t*(3-2*t),e=std::exp(-x*x);
+ const double slope=e*(-2*x*fade-6*t*(1-t)/(ShoulderFadeEnd-ShoulderFadeStart)*(x<0?-1:1));
+ return {e*fade,slope*gradient.x,slope*gradient.y};
+}
+struct Contour {
+ unsigned count=0;Point points[12]{},centre{},axis{},forward{}; // vertices/forward in hull frame
+ double level=0,halfLength=0,halfBeam=0,width=0,length=0,amplitude=0,reach=0,support=0;
+ Point supportCentre{}; // continuous inset-section midpoint projected onto support plane; refinement only
+};
+inline bool Prepare(const WaterHullModel::Hull &h,double level,double length,double amplitude,Contour &out) {
+ Contour c;if(!std::isfinite(level)||!std::isfinite(length)||!std::isfinite(amplitude)||length<=0||amplitude<0)return false;
+ for(const auto &r:h.data)for(float f:r)if(!std::isfinite(f))return false;
+ if(h.data[0][3]<3||h.data[0][3]>12||h.data[0][3]!=std::floor(h.data[0][3])||std::abs(h.data[0][2]-level)>.1)return false;
+ c.count=unsigned(h.data[0][3]);c.centre={h.data[0][0],h.data[0][1]};c.axis={h.data[1][0],h.data[1][1]};
+ if(std::abs(Dot(c.axis,c.axis)-1)>.001||h.data[1][2]<0||h.data[1][3]<0||h.data[2][3]<0)return false;
+ Point velocity={h.data[2][0],h.data[2][1]};const double speed=std::hypot(velocity.x,velocity.y);if(speed<=double(.3f))return false;
+ c.forward={Dot(velocity,c.axis)/speed,(-velocity.x*c.axis.y+velocity.y*c.axis.x)/speed};
+ c.halfLength=h.data[1][2];c.halfBeam=h.data[1][3];c.level=level;c.reach=h.data[2][3]+110;
+ c.width=Clamp(c.halfBeam*ShoulderWidthBeam,ShoulderWidthMin,ShoulderWidthMax);c.length=length;c.amplitude=amplitude;
+ c.support=-1e30;double back=1e30;
+ for(unsigned i=0;i<c.count;++i) {
+ Point p={h.data[4+i/2][2*(i%2)],h.data[4+i/2][2*(i%2)+1]};c.points[i]=p;
+ const double s=Dot(p,c.forward);
+ c.support=(std::max)(c.support,s);back=(std::min)(back,s);
+ }
+ // Packets are CCW convex. Reject malformed contours; do not silently invent a footprint.
+ for(unsigned i=0;i<c.count;++i){Point e=c.points[(i+1)%c.count]-c.points[i];if(Dot(e,e)<=1e-12)return false;
+ for(unsigned j=0;j<c.count;++j){Point d=c.points[j]-c.points[i];if(e.x*d.y-e.y*d.x<-.0001)return false;}}
+ // A support vertex can jump across a flat bow under an arbitrarily small yaw.
+ // Place only the DETAIL WINDOW at the midpoint of a continuous inset cross-section.
+ // The physical field depends solely on the continuous support value, never this centre.
+ const double inset=(std::min)(c.width,(c.support-back)*.5),plane=c.support-inset;
+ if(!(inset>1e-8))return false;
+ const Point side={-c.forward.y,c.forward.x};double low=1e30,high=-1e30;
+ auto retain=[&](Point p){double y=Dot(p,side);low=(std::min)(low,y);high=(std::max)(high,y);};
+ for(unsigned i=0;i<c.count;++i){Point a=c.points[i],b=c.points[(i+1)%c.count];double da=Dot(a,c.forward)-plane,db=Dot(b,c.forward)-plane;
+ if(da==0)retain(a);if((da<0&&db>0)||(da>0&&db<0))retain(a+(b-a)*(da/(da-db)));}
+ if(low>high)return false;
+ c.supportCentre=c.forward*c.support+side*((low+high)*.5);
+ out=c;return true;
+}
+inline Point ToLocal(const Contour &c,Point p) { p=p-c.centre;return {Dot(p,c.axis),-p.x*c.axis.y+p.y*c.axis.x}; }
+inline Point ToWorld(const Contour &c,Point p) { return c.centre+Point{c.axis.x*p.x-c.axis.y*p.y,c.axis.y*p.x+c.axis.x*p.y}; }
+struct Contact { double distance=0,retreat=0;Point normal{},retreatGradient{},closest{};bool valid=false; };
+inline Contact QueryLocal(const Contour &c,Point p) {
+ Contact q;if(c.count<3||c.count>12||!Finite(p))return q;
+ double best=1e30;bool inside=true;Point selectedEdge{};
+ for(unsigned i=0;i<c.count;++i) {
+ Point a=c.points[i],edge=c.points[(i+1)%c.count]-a,from=p-a;
+ const double square=Dot(edge,edge),t=Clamp(Dot(from,edge)/(std::max)(square,1e-12),0,1);
+ const Point closest=a+edge*t,separation=p-closest;const double d=Dot(separation,separation);
+ if(d<best) {best=d;q.closest=closest;selectedEdge=edge;}
+ inside=inside&&(edge.x*from.y-edge.y*from.x>=0);
+ }
+ const double distance=std::sqrt((std::max)(best,0.0)),sign=inside?-1:1;
+ q.distance=sign*distance;
+ if(distance>1e-8)q.normal=(p-q.closest)*(sign/distance);
+ else {const double n=std::hypot(selectedEdge.x,selectedEdge.y);q.normal={selectedEdge.y/n,-selectedEdge.x/n};}
+ q.retreat=(std::max)(0.0,c.support-Dot(p,c.forward));q.retreatGradient=q.retreat>0?c.forward*(-1):Point{};q.valid=true;return q;
+}
+inline Field Evaluate(const Contour &c,Point world) {
+ if(c.count<3||c.count>12||!Finite(world)||c.width<=0||c.length<=0||c.amplitude<=0)return {};
+ const Point delta=world-c.centre;const double radius=std::hypot(delta.x,delta.y);if(radius>=c.reach)return {};
+ const Point p=ToLocal(c,world);const double extent=(ShoulderFadeEnd+ShoulderOffset)*c.width;
+ if(std::abs(p.x)>c.halfLength+extent||std::abs(p.y)>c.halfBeam+extent)return {};
+ const Contact q=QueryLocal(c,p);if(!q.valid)return {};
+ Field field=Multiply(Profile((q.distance-ShoulderOffset*c.width)/c.width,q.normal*(1/c.width)),
+ Profile(q.retreat/c.length,q.retreatGradient*(1/c.length)));
+ field.value*=c.amplitude;field.dx*=c.amplitude;field.dy*=c.amplitude;
+ const Point gradient={c.axis.x*field.dx-c.axis.y*field.dy,c.axis.y*field.dx+c.axis.x*field.dy};field.dx=gradient.x;field.dy=gradient.y;
+ const double t=Clamp((radius-(c.reach-30))/30,0,1),fade=1-t*t*(3-2*t),slope=-6*t*(1-t)/30;
+ return Multiply(field,{fade,slope*delta.x/(std::max)(radius,.001),slope*delta.y/(std::max)(radius,.001)});
+}
+// Safe lower bounds for every registered point within horizontal radius R. The signed
+// distance is 1-Lipschitz and the unit-direction support-plane retreat is 1-Lipschitz.
+// The envelope uses the sample position, avoiding closest-point tie jumps inside the hull.
+inline Point InverseProfileLowerBounds(const Contour &c,Point world,double radius) {
+ const Point p=ToLocal(c,world);const Contact q=QueryLocal(c,p);if(!q.valid)return {1e6,1e6};
+ return {(std::max)(0.0,(std::abs(q.distance-ShoulderOffset*c.width)-radius)/c.width),
+ (std::max)(0.0,c.support-Dot(p,c.forward)-radius)/c.length};
+}
+inline std::string Source() {
+ std::string s;
+#define WATER_BOW_SHOULDER_HLSL(name,value) s+="static const float " #name "=" #value ";\n";
+ WATER_BOW_SHOULDER_CONSTANTS(WATER_BOW_SHOULDER_HLSL)
+#undef WATER_BOW_SHOULDER_HLSL
+ return s+R"HLSL(
+float3 vesselShoulderProfile(float3 x) {
+ float a=abs(x.x);if(a>=ShoulderFadeEnd)return 0;
+ float t=saturate((a-ShoulderFadeStart)/(ShoulderFadeEnd-ShoulderFadeStart));
+ float fade=1.0-t*t*(3.0-2.0*t),e=exp(-x.x*x.x);
+ float slope=e*(-2.0*x.x*fade-6.0*t*(1.0-t)/(ShoulderFadeEnd-ShoulderFadeStart)*(x.x<0.0?-1.0:1.0));
+ return float3(e*fade,x.yz*slope);
+}
+// One query at the final registered XY, never a second query in the raw/stern loop.
+// CCW convex packet and unit axis are provided by the existing bounded hull collector.
+float3 vesselContourBow(float2 world,float level,int h) {
+ int base=h*10;
+ float4 position=vesselPacketRegister(base),axis=vesselPacketRegister(base+1),motion=vesselPacketRegister(base+2);
+ int count=(int)position.w;float speed=length(motion.xy);
+ if(count<3||count>12||abs(level-position.z)>0.1||speed<=0.3)return 0;
+ float2 delta=world-position.xy;float radius=length(delta),reach=motion.w+110.0;
+ if(radius>=reach)return 0;
+ float width=clamp(axis.w*ShoulderWidthBeam,ShoulderWidthMin,ShoulderWidthMax);
+ float2 p=float2(dot(delta,axis.xy),dot(delta,float2(-axis.y,axis.x)));
+ float extent=(ShoulderFadeEnd+ShoulderOffset)*width;
+ if(abs(p.x)>axis.z+extent||abs(p.y)>axis.w+extent)return 0;
+ float2 forward=float2(dot(motion.xy,axis.xy),dot(motion.xy,float2(-axis.y,axis.x)))/speed;
+ float best=1.0e30,support=-1.0e30;bool inside=true;
+ float2 closest=0,selectedEdge=0;
+ for(int j=0;j<count;++j) {
+ int next=(j+1)%count;
+ float4 pa=vesselPacketRegister(base+4+j/2),pb=vesselPacketRegister(base+4+next/2);
+ float2 a=(j&1)!=0?pa.zw:pa.xy,b=(next&1)!=0?pb.zw:pb.xy;
+ float2 edge=b-a,from=p-a;float square=max(dot(edge,edge),1.0e-12);
+ float t=saturate(dot(from,edge)/square);float2 q=a+t*edge,separation=p-q;
+ float d=dot(separation,separation);
+ if(d<best){best=d;closest=q;selectedEdge=edge;}
+ inside=inside&&(edge.x*from.y-edge.y*from.x>=0.0);support=max(support,dot(a,forward));
+ }
+ float distance=sqrt(max(best,0.0)),sign=inside?-1.0:1.0;
+ float2 normal=distance>1.0e-8?(p-closest)*(sign/distance):float2(selectedEdge.y,-selectedEdge.x)/max(length(selectedEdge),1.0e-8);
+ float3 pressure=vesselBowPressure(axis.w,speed);
+ float3 ridge=vesselShoulderProfile(float3((sign*distance-ShoulderOffset*width)/width,normal/width));
+ float retreat=max(0.0,support-dot(p,forward));
+ float3 aft=vesselShoulderProfile(float3(retreat/pressure.x,retreat>0.0?-forward/pressure.x:float2(0,0)));
+ float3 field=vwMul(ridge,aft)*pressure.z;
+ field.yz=float2(axis.x*field.y-axis.y*field.z,axis.y*field.y+axis.x*field.z);
+ float3 radial=float3(radius,delta/max(radius,0.001));
+ return vwMul(field,vwConstant(1.0)-vwSmooth(motion.w+80.0,reach,radial));
+}
+)HLSL";
+}
+#undef WATER_BOW_SHOULDER_CONSTANTS
+}
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterCoastalCrest.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterCoastalCrest.h
new file mode 100644
index 000000000..39440648b
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterCoastalCrest.h
@@ -0,0 +1,65 @@
+/* Bounded render-only nonlinear coastal crest restoration. Positive temporal mean is intentional
+ * in this experimental approximation; it is not a mass-conserving shallow-water solver. */
+#pragma once
+#include "Platform/WaterShoreFoam.h"
+namespace WaterCoastalCrest {
+using Field=WaterSurfaceModel::Sample; // value, d/dx, d/dy
+inline bool Eligible(bool river,bool context,float offshore) {return !river&&context&&offshore==0;}
+inline float EncodeObstacle(float obstacle) {
+ return float((WaterSurfaceModel::EncodeObstacleAttenuation(0,obstacle)>>16)&255)/255.0f;
+}
+inline bool Finite(const Field& f) {return std::isfinite(f.height)&&std::isfinite(f.dx)&&std::isfinite(f.dy);}
+inline Field Unit(Field f) {
+ if(f.height<=0)return {0,0,0};if(f.height>=1)return {1,0,0};return f;
+}
+inline Field Product(const Field&a,const Field&b) {
+ return {a.height*b.height,a.dx*b.height+a.height*b.dx,a.dy*b.height+a.height*b.dy};
+}
+inline Field Smooth(float a,float b,Field f) {
+ if(f.height<=a)return {0,0,0};if(f.height>=b)return {1,0,0};
+ const float t=(f.height-a)/(b-a),derivative=6*t*(1-t)/(b-a);
+ return {t*t*(3-2*t),derivative*f.dx,derivative*f.dy};
+}
+// Caller must preserve river/offshore/missing-context identity. Terrain clearance is evaluated
+// at the same point as the original envelope; this addition never lowers that original mesh.
+inline Field Correction(Field broad,Field depth,Field support,Field exposure,Field obstacle,Field damping) {
+ if(!Finite(broad)||!Finite(depth)||!Finite(support)||!Finite(exposure)||!Finite(obstacle)||!Finite(damping)
+ ||broad.height<=0||depth.height<=WaterShoreFoam::MinDepth)return {0,0,0};
+ support=Unit(support);exposure=Unit(exposure);obstacle=Unit(obstacle);damping=Unit(damping);
+ // Diffuse red is UNORM8 rounded by the existing vertex encoder. Remove half a code
+ // so restoration can never exceed the original unquantized obstacle envelope.
+ obstacle.height-=0.5f/255.0f;if(obstacle.height<=0)obstacle={0,0,0};
+ const Field gain={obstacle.height-damping.height,obstacle.dx-damping.dx,obstacle.dy-damping.dy};
+ if(gain.height<=0||support.height<=0||exposure.height<=0)return {0,0,0};
+ const float clearance=depth.height-WaterShoreFoam::MinDepth,ratio=broad.height/clearance;
+ const float q=std::tanh(ratio),dq=1-q*q,depthDerivative=q-ratio*dq;
+ const Field limited={clearance*q,dq*broad.dx+depthDerivative*depth.dx,dq*broad.dy+depthDerivative*depth.dy};
+ const Field wet=Smooth(WaterShoreFoam::MinDepth,WaterShoreFoam::WetDepth,depth);
+ const Field crest=Smooth(0,WaterShoreFoam::CrestHeight,broad);
+ return Product(Product(Product(support,exposure),Product(wet,gain)),Product(limited,crest));
+}
+inline float Height(float broad,float depth,float support,float exposure,float obstacle,float damping) {
+ return Correction({broad,0,0},{depth,0,0},{support,0,0},{exposure,0,0},{obstacle,0,0},{damping,0,0}).height;
+}
+inline std::string Source() {return R"COAST(
+float3 waterCoastUnit(float3 f) {if(f.x<=0)return 0;if(f.x>=1)return float3(1,0,0);return f;}
+float3 waterCoastProduct(float3 a,float3 b) {return float3(a.x*b.x,a.yz*b.x+a.x*b.yz);}
+float3 waterCoastSmooth(float a,float b,float3 f) {
+ if(f.x<=a)return 0;if(f.x>=b)return float3(1,0,0);
+ float t=(f.x-a)/(b-a);return float3(t*t*(3-2*t),(6*t*(1-t)/(b-a))*f.yz);
+}
+float3 waterCoastalCrest(float3 broad,float3 depth,float3 support,float3 exposure,float3 obstacle,float3 damping) {
+ if(!all(isfinite(broad))||!all(isfinite(depth))||!all(isfinite(support))||!all(isfinite(exposure))
+ ||!all(isfinite(obstacle))||!all(isfinite(damping))||broad.x<=0||depth.x<=ShoreMinDepth)return 0;
+ support=waterCoastUnit(support);exposure=waterCoastUnit(exposure);
+ obstacle=waterCoastUnit(obstacle);damping=waterCoastUnit(damping);
+ obstacle.x-=0.5/255.0;if(obstacle.x<=0)obstacle=0;
+ float3 gain=obstacle-damping;if(gain.x<=0||support.x<=0||exposure.x<=0)return 0;
+ float clearance=depth.x-ShoreMinDepth,ratio=broad.x/clearance,q=tanh(ratio),dq=1-q*q;
+ float3 limited=float3(clearance*q,dq*broad.yz+(q-ratio*dq)*depth.yz);
+ float3 wet=waterCoastSmooth(ShoreMinDepth,ShoreWetDepth,depth),crest=waterCoastSmooth(0,ShoreCrestHeight,broad);
+ return waterCoastProduct(waterCoastProduct(waterCoastProduct(support,exposure),waterCoastProduct(wet,gain)),
+ waterCoastProduct(limited,crest));
+}
+)COAST";}
+}
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterCoastalDomain.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterCoastalDomain.h
new file mode 100644
index 000000000..ba503c668
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterCoastalDomain.h
@@ -0,0 +1,202 @@
+/* Immutable physical coastal domain. No camera, simulation or map mutation. */
+#pragma once
+#include "Platform/WaterCoastalSurf.h"
+#include "Platform/WaterShoreSource.h"
+
+namespace WaterCoastalDomain {
+using Result=WaterShoreHistory::BuildResult;
+using Level=WaterShoreSource::Level;
+constexpr size_t MaxWetCells=4*WaterOpticalContext::MaxCells;
+// Conservative scan/sort, lattice and flood work units, shared across all levels.
+// A caller may supply a smaller allowance; no caller can exceed this fixed cap.
+constexpr size_t MaxBuildWork=128u*1024u*1024u;
+class Domain {
+ WaterShoreHistory::Grid grid;
+ WaterShoreHistory::Topology topology;
+ WaterShoreSupport::Domain support;
+ std::vector<WaterShoreHistory::Cell> cells;
+ std::vector<WaterCoastalSurf::Node> nodes;
+public:
+ Result Build(const uint8_t *heights,int width,int height,int border,double spacing,double heightScale,
+ const std::vector<WaterOpticalContext::Polygon>&polygons,const std::vector<Level>&inputLevels,
+ size_t workAllowance=MaxBuildWork) {
+ using namespace WaterShoreHistory;
+ if(!heights||width<2||height<2||width>WaterOpticalContext::MaxDimension||height>WaterOpticalContext::MaxDimension
+ ||size_t(width)*height>WaterOpticalContext::MaxCells||border<0||border>(width-2)/2||border>(height-2)/2
+ ||!std::isfinite(spacing)||spacing<8||spacing>128||!std::isfinite(heightScale)||heightScale<=0
+ ||polygons.size()>WaterOpticalContext::MaxPoints/3)
+ return Result::Invalid;
+ if(inputLevels.size()>WaterCoastalSurf::MaxLevels)return Result::TooManyLevels;
+ size_t points=0;
+ for(const auto &p:polygons) {
+ if(p.points.size()>WaterOpticalContext::MaxPoints-points)return Result::Invalid;
+ points+=p.points.size();
+ for(const auto &v:p.points)if(!std::isfinite(v.x)||!std::isfinite(v.y)||!std::isfinite(v.z))return Result::Invalid;
+ }
+ std::vector<Level> levels=inputLevels;
+ const size_t terrainCount=size_t(width)*height;
+ for(const auto &l:levels) {
+ if(!l.field||!std::isfinite(l.level)||double(float(l.level))!=l.level)return Result::Invalid;
+ const auto &f=*l.field;
+ if(f.ocean.size()!=terrainCount||f.shore.size()!=terrainCount||f.coast.size()!=terrainCount
+ ||f.exposure.size()!=terrainCount||f.physicalShore.size()!=terrainCount)return Result::Invalid;
+ }
+ std::sort(levels.begin(),levels.end(),[](const Level&a,const Level&b){return a.level<b.level;});
+ for(size_t i=1;i<levels.size();++i)if(levels[i-1].level==levels[i].level)return Result::Invalid;
+ size_t remaining=(std::min)(workAllowance,MaxBuildWork);
+ auto spend=[&](size_t amount){if(amount>remaining)return false;remaining-=amount;return true;};
+ // Intervals has at most three spans per input vertex. Charge its bounded sorting
+ // as well as point visits before performing a scanline, including empty polygons.
+ size_t sortPasses=0;for(size_t n=3*points+1;n>1;n=(n+1)/2)++sortPasses;
+ const size_t lineWork=1+polygons.size()+points*(4+3*sortPasses);
+ const size_t coveredWork=sortPasses+1; // upper_bound on at most three spans per vertex
+ // Build at most two bounded candidates from the same completed fine flood.
+ // Stride2 is exactly the original terrain grid, so support rectangles remain
+ // bilinear. Larger strides would cross terrain-cell boundaries and need a
+ // different support proof; they are deliberately not attempted here.
+ Domain fine,coarse;fine.grid={-border*spacing,-border*spacing,spacing*.5};
+ coarse.grid={fine.grid.originX,fine.grid.originY,spacing};
+ // Keep the existing GPU graph spacing contract; no stride2 candidate is
+ // possible when its spacing would exceed64 world units.
+ bool fineOverflow=false,coarseOverflow=spacing>64;
+ auto append=[&](Domain &candidate,bool &overflow,int x,int y,double level,
+ const WaterCoastalSurf::Node &node,uint8_t connections){
+ if(overflow)return;
+ if(candidate.cells.size()>=WaterCoastalSurf::MaxNodes){
+ overflow=true;candidate.cells.clear();candidate.nodes.clear();return;
+ }
+ candidate.cells.push_back({x,y,level,uint32_t(candidate.nodes.size()),connections});
+ candidate.nodes.push_back(node);
+ };
+ // Unlike the legacy width-epsilon sampler, exact final-row vertices remain exact.
+ // Cardinal half-cell segments stay within one bilinear terrain cell, so their
+ // height is linear: wet endpoints prove the entire cardinal segment is wet.
+ auto terrain=[&](double x,double y){
+ x=Clamp(x,0,width-1);y=Clamp(y,0,height-1);
+ const int ix=(std::min)(int(x),width-2),iy=(std::min)(int(y),height-2);
+ const double fx=x-ix,fy=y-iy;const size_t n=size_t(iy)*width+ix;
+ return float(((heights[n]*(1-fx)+heights[n+1]*fx)*(1-fy)
+ +(heights[n+width]*(1-fx)+heights[n+width+1]*fx)*fy)*heightScale);
+ };
+ const int nx=2*width-1,ny=2*height-1;
+ const size_t wetCount=size_t(nx)*ny;
+ if(wetCount>MaxWetCells)return Result::Invalid;
+ enum : uint8_t {Wet=1,PositiveX=2,PositiveY=4,Connected=8};
+ for(const Level &entry:levels) {
+ const auto &f=*entry.field;
+ // Full wet connectivity precedes shallow/distance pruning: an island coast
+ // remains exposed when its only path to the playable boundary is deep ocean.
+ // Memory is reused one level at a time; optical exposure cannot establish connectivity.
+ std::vector<uint8_t> wet(wetCount,0),columnWet(size_t(nx),0);
+ for(int y=0;y<ny;++y) {
+ if(!spend(lineWork+size_t(nx)*(1+2*coveredWork)))return Result::Invalid;
+ const double wy=fine.grid.originY+y*fine.grid.spacing;
+ const auto row=WaterShoreSource::Intervals(polygons,entry.level,wy,true);
+ if(row.empty())continue;
+ for(int x=0;x<nx;++x) {
+ const double wx=fine.grid.originX+x*fine.grid.spacing;
+ if(!WaterShoreSource::Covered(row,wx,wx)||!(terrain(x*.5,y*.5)<entry.level))continue;
+ uint8_t flags=Wet;
+ if(x+1<nx&&WaterShoreSource::Covered(row,wx,wx+fine.grid.spacing))flags|=PositiveX;
+ wet[size_t(y)*nx+x]=flags;columnWet[size_t(x)]=1;
+ }
+ }
+ for(int x=0;x<nx;++x)if(columnWet[size_t(x)]) {
+ if(!spend(lineWork+size_t(ny)*(1+coveredWork)))return Result::Invalid;
+ const auto column=WaterShoreSource::Intervals(polygons,entry.level,
+ fine.grid.originX+x*fine.grid.spacing,false);
+ for(int y=0;y+1<ny;++y) {
+ auto &flags=wet[size_t(y)*nx+x];if(!(flags&Wet))continue;
+ const double wy=fine.grid.originY+y*fine.grid.spacing;
+ if(WaterShoreSource::Covered(column,wy,wy+fine.grid.spacing))flags|=PositiveY;
+ }
+ }
+ std::vector<uint32_t> queue;queue.reserve(wetCount);
+ auto seed=[&](size_t index){
+ auto &flags=wet[index];if((flags&(Wet|Connected))!=Wet)return;
+ flags|=Connected;queue.push_back(uint32_t(index));
+ };
+ const int left=2*border,right=2*(width-border-1),top=2*border,bottom=2*(height-border-1);
+ for(int x=left;x<=right;++x){seed(size_t(top)*nx+x);seed(size_t(bottom)*nx+x);}
+ for(int y=top;y<=bottom;++y){seed(size_t(y)*nx+left);seed(size_t(y)*nx+right);}
+ for(size_t q=0;q<queue.size();++q) {
+ if(!spend(4))return Result::Invalid;
+ const size_t i=queue[q];const int x=int(i%nx),y=int(i/nx);
+ if(x+1<nx&&(wet[i]&PositiveX))seed(i+1);
+ if(x>0&&(wet[i-1]&PositiveX))seed(i-1);
+ if(y+1<ny&&(wet[i]&PositiveY))seed(i+nx);
+ if(y>0&&(wet[i-nx]&PositiveY))seed(i-nx);
+ }
+ if(!spend(wetCount))return Result::Invalid;
+ // Final-row/column source knots remain excluded to retain the existing
+ // support-tile contract. They participated in the full wet connectivity.
+ for(int y=0;y+1<ny;++y)for(int x=0;x+1<nx;++x) {
+ const uint8_t flags=wet[size_t(y)*nx+x];if(!(flags&Connected))continue;
+ const float gx=x*.5f,gy=y*.5f;
+ const float depth=float(entry.level)-terrain(gx,gy);
+ if(!(depth>.15f)||depth>=12)continue;
+ const auto distance=WaterSurfaceModel::SampleOffshore(f.physicalShore.data(),width,height,gx,gy,float(spacing));
+ // The saturated code means at least160, not exactly160. It cannot
+ // prove membership in a collar when spacing makes that collar wider.
+ if(distance.height>=1)continue;
+ const float physical=distance.height*WaterOpticalContext::PhysicalShoreRange;
+ if(physical>WaterCoastalSurf::PhysicalCoastEnd+spacing+WaterOpticalContext::PhysicalShoreRange/510)continue;
+ const auto ocean=WaterSurfaceModel::SampleOffshore(f.ocean.data(),width,height,gx,gy,float(spacing));
+ const auto exposure=WaterSurfaceModel::SampleOffshore(f.exposure.data(),width,height,gx,gy,float(spacing));
+ // Physical connectivity above remains mandatory. Within that domain,
+ // match the actual spectral support used by geometry and presentation.
+ if(exposure.height<=0)continue;
+ WaterCoastalSurf::Node node;
+ node.world[0]=float(fine.grid.originX+x*fine.grid.spacing);
+ node.world[1]=float(fine.grid.originY+y*fine.grid.spacing);node.world[2]=float(entry.level);
+ auto &c=node.context;c.depth=depth;c.distance=physical;
+ c.outwardX=distance.dx*WaterOpticalContext::PhysicalShoreRange;
+ c.outwardY=distance.dy*WaterOpticalContext::PhysicalShoreRange;
+ c.exposure=exposure.height;c.offshore=ocean.height;
+ c.analyticDamping=WaterSurfaceModel::TerrainDamping(depth,ocean.height);
+ c.spectralDamping=WaterFftGeometry::SafeDamping(c.analyticDamping,depth);
+ c.wet=c.admitted=1;
+ const uint8_t connections=uint8_t((flags&PositiveX?1:0)|(flags&PositiveY?2:0));
+ append(fine,fineOverflow,x,y,entry.level,node,connections);
+ if((x&1)==0&&(y&1)==0&&!coarseOverflow){
+ if(!spend(4))return Result::Invalid;
+ auto linked=[&](bool vertical){
+ const int ex=x+(vertical?0:2),ey=y+(vertical?2:0);
+ if(ex>=nx||ey>=ny)return false;
+ const size_t step=vertical?size_t(nx):1,start=size_t(y)*nx+x;
+ const uint8_t direction=vertical?PositiveY:PositiveX;
+ for(unsigned k=0;k<2;++k){
+ const uint8_t a=wet[start+k*step],b=wet[start+(k+1)*step];
+ if((a&(Wet|Connected|direction))!=(Wet|Connected|direction)
+ ||(b&(Wet|Connected))!=(Wet|Connected))return false;
+ }
+ return true;
+ };
+ const uint8_t links=uint8_t((linked(false)?1:0)|(linked(true)?2:0));
+ append(coarse,coarseOverflow,x/2,y/2,entry.level,node,links);
+ }
+ if(fineOverflow&&coarseOverflow)return Result::TooManyCells;
+ }
+ }
+ const unsigned selectedStride=fineOverflow?2u:1u;
+ Domain next=std::move(fineOverflow?coarse:fine);
+ const auto built=next.topology.Build(next.grid,next.cells);if(built!=Result::Ready)return built;
+ // Sorted level/y/x insertion preserves the immutable node IDs after Topology.Build.
+ if(next.topology.Cells().size()!=next.nodes.size())return Result::Invalid;
+ for(const auto &edge:next.topology.Edges()) {
+ const auto &a=next.cells[edge.a],&b=next.cells[edge.b];
+ const unsigned side=a.y==b.y?1:3,opposite=side-1;
+ next.nodes[edge.a].neighbour[side]=edge.b+1;next.nodes[edge.b].neighbour[opposite]=edge.a+1;
+ }
+ if(!WaterCoastalSurf::ValidGraph(next.nodes,next.grid.spacing))return Result::Invalid;
+ auto supportTerrain=[&](double x,double y){return terrain(x*selectedStride,y*selectedStride);};
+ if(!next.support.Build(next.grid,next.cells,width,height,polygons,supportTerrain))return Result::Invalid;
+ *this=std::move(next);return Result::Ready;
+ }
+ const WaterShoreHistory::Grid& Grid()const{return grid;}
+ const WaterShoreHistory::Topology& Topology()const{return topology;}
+ const std::vector<WaterShoreHistory::Cell>& Cells()const{return cells;}
+ const std::vector<WaterCoastalSurf::Node>& Nodes()const{return nodes;}
+ const WaterShoreSupport::Domain& Support()const{return support;}
+};
+}
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterCoastalIncident.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterCoastalIncident.h
new file mode 100644
index 000000000..1b575a68c
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterCoastalIncident.h
@@ -0,0 +1,81 @@
+/* GPU-only production-field sampler for the optional coastal history atlas. */
+#pragma once
+#include "Platform/WaterCoastalSurf.h"
+#include "Platform/WaterFftSpectrum.h"
+#include "Platform/WaterShoreFoam.h"
+#include "Platform/WaterSurfaceModel.h"
+#include <string>
+
+namespace WaterCoastalIncident {
+// Domain slots 0..3: world, coast, surface, admission. Slots 4..7 are the existing
+// ocean maps 0..3 (broad/medium displacement+derivatives), with the ocean sampler.
+// Ocean maps 4/5 are fine ripples and deliberately have no source binding.
+constexpr unsigned SamplerCount=8,UniformBytes=16;
+struct Parameters {float waterTime=0,nodeCount=0,padding0=0,padding1=0;};
+static_assert(sizeof(Parameters)==UniformBytes,"Incident uniform is one float4");
+inline const char *VertexSource(){return WaterFftSpectrum::VertexHlsl();}
+inline bool Slice(const std::string &source,const char *begin,const char *end,std::string &out){
+ const size_t a=source.find(begin),b=a==std::string::npos?std::string::npos:source.find(end,a);
+ if(a==std::string::npos||b==std::string::npos||b<=a)return false;
+ out=source.substr(a,b-a);return true;
+}
+inline bool ReplaceOnce(std::string &text,const std::string &old,const std::string &replacement){
+ const size_t at=text.find(old);if(at==std::string::npos||text.find(old,at+old.size())!=std::string::npos)return false;
+ text.replace(at,old.size(),replacement);return true;
+}
+inline bool PixelSource(std::string &result){
+ result.clear();
+ // Extract the actual production decoder and map-coordinate convention. A changed
+ // source contract fails optional creation; it cannot silently invent another ocean.
+ const std::string production=WaterFftSampling::PixelSource(false,false);
+ std::string structure,sampling,decode,legacy;
+ if(!Slice(production,"struct FftSurface {","struct FftMapSamples",structure)
+ ||!Slice(production,"struct FftMapSamples","FftSurface fftDecodeSamples(",sampling)
+ ||!Slice(production,"FftSurface fftDecodeSamples(","FftSurface fftRawSurface(",decode)
+ ||!Slice(WaterShoreFoam::Source(),"float4 waterShoreWave(","float waterShoreRate(",legacy))return false;
+ if(!ReplaceOnce(sampling,"samples.c=Texture12.SampleLevel(Sampler12,p/(13.0*fftWorldScale),lod[2]);","samples.c=0;")
+ ||!ReplaceOnce(sampling,"samples.cd=Texture13.SampleLevel(Sampler13,p/(13.0*fftWorldScale),lod[2]);","samples.cd=0;"))return false;
+ for(unsigned i=0;i<4;++i){
+ if(!ReplaceOnce(sampling,"Texture"+std::to_string(8+i),"IncidentTexture"+std::to_string(4+i))
+ ||!ReplaceOnce(sampling,"Sampler"+std::to_string(8+i),"IncidentSampler"+std::to_string(4+i)))return false;
+ }
+ std::string source;
+ for(unsigned i=0;i<SamplerCount;++i){const std::string n=std::to_string(i);
+ source+="Texture2D<float4> IncidentTexture"+n+" : register(t"+n+",space2);\n"
+ +"SamplerState IncidentSampler"+n+" : register(s"+n+",space2);\n";}
+ source+="cbuffer IncidentParameters:register(b0,space3){float4 Parameters;};\n";
+ source+=WaterFftSampling::CommonSource()+structure+sampling+decode
+ +WaterCoastalSurf::IncidentSource()+WaterCoastalSurf::Source()+legacy
+ +WaterSurfaceModel::OceanShaderSource();
+ source+=R"HLSL(
+float4 main(float4 pixel:SV_Position):SV_Target0 {
+ uint2 cell=(uint2)pixel.xy;uint index=cell.y*256+cell.x;
+ if(!all(isfinite(Parameters))||Parameters.y<0||Parameters.y>65536
+ ||floor(Parameters.y)!=Parameters.y||index>=(uint)Parameters.y)return float4(0,0,0,1);
+ float2 uv=(float2(cell)+.5)/256.0;
+ float4 world=IncidentTexture0.SampleLevel(IncidentSampler0,uv,0);
+ WaterSurfContext context;
+ context.coast=IncidentTexture1.SampleLevel(IncidentSampler1,uv,0);
+ context.surface=IncidentTexture2.SampleLevel(IncidentSampler2,uv,0);
+ context.admission=IncidentTexture3.SampleLevel(IncidentSampler3,uv,0);
+ if(!all(isfinite(world))||!waterSurfContextFinite(context)||context.admission.x<.5
+ ||context.admission.y<.5||context.surface.x<=0||context.coast.x<=.15)return float4(0,0,0,1);
+ float offshore=context.surface.y,weight=context.surface.x;
+ // Exactly the existing selected analytic components; the ocean helper retains
+ // its original warp and packet envelope. Exposed shallow water shares the FFT
+ // phase even at zero optical R. No second TimeScale, blend-weight gradient,
+ // damping derivative, vessel pressure or decorative swell enters this source.
+ float3 legacy=waterShoreWave(world.xy,Parameters.x).xyz;
+ float4 oceanSwell;waterOceanSurface(world.xy,Parameters.x,oceanSwell);
+ float4 analytic=float4(lerp(legacy,oceanSwell.xyz,offshore),1);
+ float4 spectral=waterSurfIncident(fftMapSamples(world.xy,float3(0,0,0)));
+ float4 incident=waterSurfBlend(analytic,spectral,weight);
+ // Horizontal chop still fades with optical R; a zero-chop shore must not
+ // acquire a compression breaker just because its vertical wave is spectral.
+ incident.w=lerp(1.0,spectral.w,saturate(weight*offshore));
+ return incident;
+}
+)HLSL";
+ result.swap(source);return true;
+}
+} // namespace WaterCoastalIncident
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterCoastalPresentation.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterCoastalPresentation.h
new file mode 100644
index 000000000..dee147a70
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterCoastalPresentation.h
@@ -0,0 +1,73 @@
+/* Optional coastal history presentation; no source births or gameplay state. */
+#pragma once
+#include "Platform/WaterCoastalSurf.h"
+#include <cmath>
+
+namespace WaterCoastalPresentation {
+struct Moments {float density=0,age=0;};
+inline Moments AtTime(float density,float ageMoment,float elapsed){
+ if(!std::isfinite(density)||!std::isfinite(ageMoment)||!std::isfinite(elapsed)
+ ||density<=0||density>16||ageMoment<0||ageMoment>1024||elapsed<0||elapsed>=14)return {};
+ const float age=ageMoment/density+elapsed;
+ if(!std::isfinite(age)||age>=14)return {};
+ return {float(density*std::exp(-double(elapsed)/5)),age};
+}
+inline float ModelGate(float actual,float canonical,float correction,float gx,float gy){
+ using WaterCoastalSurf::Smooth;
+ if(!std::isfinite(actual)||!std::isfinite(canonical)||!std::isfinite(correction)
+ ||!std::isfinite(gx)||!std::isfinite(gy)||actual<0||actual>1||canonical<0||canonical>1)return 0;
+ return (1-Smooth(.015f,.06f,std::abs(actual-canonical)))
+ *(1-Smooth(.02f,.15f,std::abs(correction)))*(1-Smooth(.002f,.02f,std::hypot(gx,gy)));
+}
+inline const char *Source(){return R"HLSL(
+bool waterCoastalViewValid(float4 area,float4 params,float2 position,float level,float time) {
+ if(!all(isfinite(area))||!all(isfinite(params))||!all(isfinite(position))||!isfinite(level)||!isfinite(time)
+ ||params.x<.5||any(area.zw<=0)||abs(params.y-level)>.01||abs(params.w-time)>.0001
+ ||params.z>params.w||params.z<0)return false;
+ float2 uv=(position-area.xy)/area.zw;
+ return all(uv>=0)&&all(uv<=1);
+}
+float2 waterCoastalAtTime(float2 moments,float elapsed) {
+ if(!all(isfinite(moments))||!isfinite(elapsed)||moments.x<=0||moments.x>16
+ ||moments.y<0||moments.y>1024||elapsed<0||elapsed>=14)return 0;
+ float age=moments.y/moments.x+elapsed;
+ if(!isfinite(age)||age>=14)return 0;
+ return float2(moments.x*exp(-elapsed/5.0),age);
+}
+float waterCoastalModelGate(float actual,float canonical,float correction,float2 correctionSlope) {
+ if(!all(isfinite(float4(actual,canonical,correction,0)))||!all(isfinite(correctionSlope))
+ ||actual<0||actual>1||canonical<0||canonical>1)return 0;
+ // Canonical exposure is camera independent; the vertex metadata includes the
+ // actual patch/camera FFT fade. Optical R does not select the wave family.
+ // Corrections are representation deltas, not a new breaking-wave source.
+ return (1-smoothstep(.015,.06,abs(actual-canonical)))
+ *(1-smoothstep(.02,.15,abs(correction)))*(1-smoothstep(.002,.02,length(correctionSlope)));
+}
+float waterCoastalWetGate(float rawDepth,float3 hit,float3 world,float3 view,float level,
+ float worldTerrain,float parameterTerrain,float hitTerrain,float obstacle,float hull) {
+ if(!isfinite(rawDepth)||rawDepth<0||rawDepth>=.999999||!all(isfinite(hit))
+ ||!all(isfinite(world))||!all(isfinite(view))||!isfinite(level)
+ ||!all(isfinite(float4(worldTerrain,parameterTerrain,hitTerrain,obstacle)))||!isfinite(hull))return 0;
+ // Real original raster depth only. Both the current chop location and fixed
+ // parameter must remain wet; a background sample or an above-water face cannot
+ // borrow terrain metadata as evidence of water. Keep original ordinary rims.
+ if(hit.z>min(world.z,level)-.08||dot(hit-world,view)>=-.01
+ ||worldTerrain>=min(world.z-.08,level-.15)||parameterTerrain>=level-.15)return 0;
+ // Terrain agreement is a bounded heuristic, not an object-ID reconstruction.
+ // Known moving hulls and interpolated structure damping independently reject
+ // their footprint; thin unregistered objects still require native inspection.
+ float terrainMatch=1-smoothstep(.5,1.5,abs(hit.z-hitTerrain));
+ float solid=smoothstep(.001,.1,min(saturate(obstacle),saturate(hull)));
+ return smoothstep(0,.8,world.z-hit.z)*smoothstep(.15,.8,level-worldTerrain)*terrainMatch*solid;
+}
+float waterCoastalPorousCoverage(float2 position,float footprint,float2 densityAge) {
+ if(densityAge.x<=0)return 0;
+ float coverage=waterFoamOpticalCoverage(densityAge.x);
+ // Existing static world-anchored pore material: aging changes its area, not its
+ // phase. No scrolling texture or independent oscillator impersonates a front.
+ float aged=smoothstep(.4,3.0,densityAge.y);
+ float porous=waterFoamOldCoverage(position,coverage,footprint,1.0);
+ return lerp(coverage,porous,aged)*(1-smoothstep(8,14,densityAge.y));
+}
+)HLSL";}
+} // namespace WaterCoastalPresentation
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterCoastalRender.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterCoastalRender.h
new file mode 100644
index 000000000..08f5a0207
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterCoastalRender.h
@@ -0,0 +1,9 @@
+// Render-only bridge. The device caches immutable domain/view identities; no map mutation.
+#pragma once
+#include "Platform/WaterCoastalView.h"
+#ifndef _WIN32
+class IDirect3DDevice9;
+bool PosixWaterCoastalBind(IDirect3DDevice9 *,uint64_t,const WaterCoastalDomain::Domain &,
+ const WaterShoreHistory::Mapping &,double,const std::vector<WaterCoastalSurf::Lookup> &);
+void PosixWaterCoastalEnd(IDirect3DDevice9 *);
+#endif
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterCoastalSurf.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterCoastalSurf.h
new file mode 100644
index 000000000..7f9596698
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterCoastalSurf.h
@@ -0,0 +1,275 @@
+/* Bounded render-only coastal source/history core. GPU transport is a separate owner. */
+#pragma once
+#include "Platform/WaterFftSampling.h"
+#include "Platform/WaterShoreHistory.h"
+#include <array>
+#include <cmath>
+#include <cstdint>
+#include <string>
+#include <vector>
+
+namespace WaterCoastalSurf {
+constexpr unsigned AtlasSide=256,MaxNodes=AtlasSide*AtlasSide,MaxLevels=8,MaxViewSide=512;
+constexpr double SourceTick=.1,MaximumSourceInterval=.25,Lifetime=5,Diffusivity=2;
+constexpr float MaximumRate=1.2f,PhysicalCoastFull=96,PhysicalCoastEnd=128;
+// Coordinates/heights are game world units. dt is elapsed modern-water seconds, not
+// FFT time (the native maps already contain the WaterFftSampling::TimeScale phase).
+// The field excludes fine ripples and generated vessel waves. It is a component
+// of the existing geometry, not an additional independent surf oscillator.
+struct Field {float height=0,dx=0,dy=0,compression=1;};
+struct Context {
+ float depth=0,distance=0,outwardX=0,outwardY=0;
+ float exposure=0,offshore=0,analyticDamping=0,spectralDamping=0;
+ float wet=0,admitted=0;
+};
+// Four float channels on the GPU. rate=-1 means no valid previous source sample.
+// History itself stays in the fixed mean-water parameter/world chart. Sampling
+// it at the corresponding parameter makes it follow the actual horizontal chop.
+struct State {float density=0,ageMoment=0,height=0,rate=-1;};
+inline float Clamp(float x,float a,float b){return (std::max)(a,(std::min)(b,x));}
+inline float Smooth(float a,float b,float x){const float t=Clamp((x-a)/(b-a),0,1);return t*t*(3-2*t);}
+inline bool Finite(const Field &f){return std::isfinite(f.height)&&std::isfinite(f.dx)&&std::isfinite(f.dy)&&std::isfinite(f.compression)
+ &&std::abs(f.height)<=64&&std::abs(f.dx)<=1024&&std::abs(f.dy)<=1024&&std::abs(f.compression)<=1048576;}
+inline bool Finite(const Context &c){return std::isfinite(c.depth)&&std::isfinite(c.distance)&&std::isfinite(c.outwardX)&&std::isfinite(c.outwardY)
+ &&std::isfinite(c.exposure)&&std::isfinite(c.offshore)&&std::isfinite(c.analyticDamping)&&std::isfinite(c.spectralDamping)
+ &&std::isfinite(c.wet)&&std::isfinite(c.admitted)&&std::abs(c.depth)<=1048576&&std::abs(c.distance)<=1048576
+ &&std::abs(c.outwardX)<=1024&&std::abs(c.outwardY)<=1024&&c.exposure>=0&&c.exposure<=1
+ &&c.offshore>=0&&c.offshore<=1&&c.analyticDamping>=0&&c.analyticDamping<=1
+ &&c.spectralDamping>=0&&c.spectralDamping<=1&&c.wet>=0&&c.wet<=1&&c.admitted>=0&&c.admitted<=1;}
+inline bool Finite(const State &s){return std::isfinite(s.density)&&std::isfinite(s.ageMoment)&&std::isfinite(s.height)&&std::isfinite(s.rate)
+ &&s.density>=0&&s.density<=16&&s.ageMoment>=0&&s.ageMoment<=1024&&std::abs(s.height)<=64&&s.rate>=-1&&s.rate<=MaximumRate;}
+// Incident-component indicators at fixed blend weight, excluding its gradient.
+// This is not the final mixed geometric normal/Jacobian: a static coastal transition
+// must not create a breaker from two different but spatially constant input heights.
+inline Field Blend(const Field &analytic,const Field &spectral,float weight){
+ if(!Finite(analytic)||!Finite(spectral)||!std::isfinite(weight))return {};
+ const float w=Clamp(weight,0,1);
+ return {analytic.height+(spectral.height-analytic.height)*w,
+ analytic.dx+(spectral.dx-analytic.dx)*w,analytic.dy+(spectral.dy-analytic.dy)*w,
+ 1+(spectral.compression-1)*w};
+}
+inline float Domain(const Context &c){
+ if(!Finite(c)||c.wet<.5f||c.admitted<.5f||c.exposure<=0||c.depth<=.15f||c.distance<0)return 0;
+ // This physical source domain is independent of optical A replacement validity.
+ // The depth bound makes the 128-unit distance limit a work bound, not a uniform ribbon.
+ return Smooth(.15f,.8f,c.depth)*(1-Smooth(8,12,c.depth))
+ *(1-Smooth(PhysicalCoastFull,PhysicalCoastEnd,c.distance))*Clamp(c.exposure,0,1);
+}
+inline float Rate(const Context &c,const Field &f,const State &previous,double elapsed){
+ const float domain=Domain(c);
+ if(domain<=0||!Finite(f)||!Finite(previous)||previous.rate<0||!std::isfinite(elapsed)
+ ||elapsed<=1e-6||elapsed>MaximumSourceInterval||f.height<=0)return 0;
+ const float normal=std::hypot(c.outwardX,c.outwardY),slope=std::hypot(f.dx,f.dy);
+ if(normal<=1e-8f||slope<=1e-8f)return 0;
+ const float ht=float((double(f.height)-previous.height)/elapsed);
+ // Backward temporal difference of the same broad field, on the fixed parameter
+ // chart. This is a bounded phase-direction approximation, not Eulerian fluid velocity.
+ // Positive h_t selects the growing face; the outward gradient then identifies arrival.
+ if(!(ht>0))return 0;
+ if(!std::isfinite(ht))return 0;
+ const float incoming=Smooth(0,.25f,(f.dx/slope)*(c.outwardX/normal)+(f.dy/slope)*(c.outwardY/normal));
+ const float heightBreak=Smooth(.4f,.85f,2*f.height/(std::max)(c.depth+.5f,1.0f));
+ const float compressionBreak=Smooth(.04f,.30f,1-f.compression);
+ const float breaking=(std::max)(heightBreak,compressionBreak);
+ const float damping=Clamp(c.analyticDamping+(c.spectralDamping-c.analyticDamping)*Clamp(c.exposure,0,1),0,1);
+ // Dissipation is already implied by the actual shallow-water damping. No constant
+ // source floor, camera derivative, artificial crest, or fine-ripple trigger is added.
+ const float lostEnergy=1-damping*damping;
+ return MaximumRate*domain*incoming*breaking*lostEnergy*Smooth(0,.5f,f.height)*Smooth(0,.08f,ht);
+}
+// Factored integrals S_n(x)=integral_0^1 u^n exp(-x*u) du, x<=.05;
+// the series avoids cancellation and division by tiny x in the linear-rate update.
+inline double IntegralSeries(unsigned n,double x){
+ double sum=0,term=1;
+ for(unsigned k=0;k<10;++k){sum+=term/double(n+k+1);term*=-x/double(k+1);}
+ return sum;
+}
+inline State Integrate(const State &previous,float height,float rate,double elapsed,bool source){
+ if(!Finite(previous)||!std::isfinite(height)||!std::isfinite(rate)||!std::isfinite(elapsed)||elapsed<0)return {};
+ if(elapsed<=1e-6)return previous;
+ const double x=elapsed/Lifetime,q=std::exp(-x);
+ double density=q*previous.density,age=q*(previous.ageMoment+elapsed*previous.density);
+ if(source&&elapsed<=MaximumSourceInterval){
+ const double a=Clamp(previous.rate,0,MaximumRate),b=Clamp(rate,0,MaximumRate);
+ const double j0=IntegralSeries(0,x),j1=IntegralSeries(1,x),j2=IntegralSeries(2,x);
+ const double w0=elapsed*j1,w1=elapsed*(j0-j1);
+ const double m0=elapsed*elapsed*j2,m1=elapsed*elapsed*(j1-j2);
+ density+=a*w0+b*w1;age+=a*m0+b*m1;
+ }
+ // Underflow explicitly produces zero; never evaluate inf*0 after an enormous gap.
+ if(q==0){density=0;age=0;}
+ return {float(density),float(age),height,source?Clamp(rate,0,MaximumRate):0};
+}
+inline State Advance(const Context &c,const Field &field,const State &previous,double elapsed,bool allowSource=true){
+ if(elapsed>=0&&elapsed<=1e-6&&Finite(previous))return previous;
+ if(!Finite(c)||!Finite(field)||c.wet<.5f||c.admitted<.5f||c.exposure<=0||c.depth<=.15f)return {};
+ const float rate=allowSource?Rate(c,field,previous,elapsed):0;
+ return Integrate(previous,field.height,rate,elapsed,allowSource&&elapsed<=MaximumSourceInterval);
+}
+inline float Coverage(const State &s,float porous){
+ if(!Finite(s)||!std::isfinite(porous)||s.density<=0)return 0;
+ const float age=s.ageMoment/s.density;
+ const float old=Smooth(.4f,3,age),terminal=1-Smooth(8,14,age);
+ return float(-std::expm1(-double(s.density)))*(1-old+old*Clamp(porous,0,1))*terminal;
+}
+// Immutable graph payload. Node identity is its exact level and fixed world-grid key.
+// Zero neighbour IDs mean no connection; IDs are otherwise index+1 (exact in float32).
+struct Node {
+ float world[4]={}; // mean-water x,y,exact level,unused
+ Context context;
+ uint32_t neighbour[4]={}; // -X,+X,-Y,+Y, reciprocal same-level wet segments only
+};
+inline bool ValidGraph(const std::vector<Node> &nodes,double spacing){
+ if(nodes.size()>MaxNodes||!std::isfinite(spacing)||spacing<4||spacing>64)return false;
+ std::vector<float> levels;std::vector<std::array<float,3>> keys;keys.reserve(nodes.size());
+ const unsigned opposite[4]={1,0,3,2};
+ for(unsigned i=0;i<nodes.size();++i){const Node &n=nodes[i];
+ for(float v:n.world)if(!std::isfinite(v))return false;
+ // Every installed slot is valid wet history support, including the no-birth
+ // spread margin. Otherwise diffusion could refill a slot Advance just cleared.
+ if(!Finite(n.context)||n.context.wet<.5f||n.context.admitted<.5f
+ ||n.context.exposure<=0||n.context.depth<=.15f)return false;
+ keys.push_back({n.world[2],n.world[1],n.world[0]});
+ if(std::find(levels.begin(),levels.end(),n.world[2])==levels.end())levels.push_back(n.world[2]);
+ if(levels.size()>MaxLevels)return false;
+ for(unsigned side=0;side<4;++side){const uint32_t id=n.neighbour[side];if(!id)continue;
+ if(id>nodes.size()||id==i+1)return false;
+ const Node &other=nodes[id-1];
+ if(other.world[2]!=n.world[2]||other.neighbour[opposite[side]]!=i+1)return false;
+ const double dx=other.world[0]-n.world[0],dy=other.world[1]-n.world[1];
+ const double expectedX=side==0?-spacing:side==1?spacing:0;
+ const double expectedY=side==2?-spacing:side==3?spacing:0;
+ if(std::abs(dx-expectedX)>1e-5||std::abs(dy-expectedY)>1e-5)return false;
+ }
+ }
+ std::sort(keys.begin(),keys.end());
+ if(std::adjacent_find(keys.begin(),keys.end())!=keys.end())return false;
+ return true;
+}
+inline State Diffuse(const State &centre,const std::array<State,4> &neighbours,unsigned mask,double spacing,double elapsed){
+ if(!Finite(centre)||!std::isfinite(spacing)||spacing<4||!std::isfinite(elapsed)||elapsed<0||elapsed>MaximumSourceInterval)return {};
+ const double a=Diffusivity*elapsed/(spacing*spacing);State out=centre;
+ double density=centre.density,age=centre.ageMoment;
+ for(unsigned i=0;i<4;++i)if(mask&(1u<<i)){
+ if(!Finite(neighbours[i]))return {};
+ density+=a*(neighbours[i].density-centre.density);age+=a*(neighbours[i].ageMoment-centre.ageMoment);
+ }
+ out.density=float(density);out.ageMoment=float(age);return out;
+}
+// Camera-view composition stores source indices/weights, not copied history. Rejected
+// contributions have zero weight; weights are never renormalized across a dry gap.
+struct Lookup {uint32_t node[4]={};float weight[4]={};};
+inline bool ValidLookup(const Lookup &lookup,unsigned count){
+ if(count>MaxNodes)return false;double total=0;
+ for(unsigned i=0;i<4;++i){if(lookup.node[i]>count||!std::isfinite(lookup.weight[i])||lookup.weight[i]<0
+ ||lookup.weight[i]>1||(!lookup.node[i]&&lookup.weight[i]!=0))return false;total+=lookup.weight[i];}
+ return total<=1.000001;
+}
+enum class Action {None,Reset,Sample,GapDecay,Invalid};
+struct Plan {Action action=Action::None;double time=0,elapsed=0;uint64_t tick=0;};
+class Clock {
+ bool ready=false;uint64_t revision=0,completed=0;double epoch=0,sampled=0,observed=0;
+public:
+ // Planning never advances state: commit only after all GPU writes were submitted.
+ Plan Inspect(uint64_t rev,double time)const{
+ if(!rev||!WaterShoreHistory::ValidTime(time))return {Action::Invalid};
+ if(!ready||rev!=revision||time<observed)return {Action::Reset,time,0,0};
+ const uint64_t tick=uint64_t((std::max)(0.0,std::floor((time-epoch)/SourceTick+1e-9)));
+ if(tick<=completed)return {Action::None,time,0,tick};
+ const double elapsed=time-sampled;
+ return {elapsed>MaximumSourceInterval?Action::GapDecay:Action::Sample,time,elapsed,tick};
+ }
+ bool Commit(uint64_t rev,const Plan &plan){
+ if(plan.action==Action::Invalid||!rev||!WaterShoreHistory::ValidTime(plan.time))return false;
+ const Plan expected=Inspect(rev,plan.time);
+ if(expected.action!=plan.action||expected.elapsed!=plan.elapsed||expected.tick!=plan.tick)return false;
+ observed=plan.time;
+ if(plan.action==Action::None)return true;
+ if(plan.action==Action::Reset){ready=true;revision=rev;epoch=sampled=plan.time;completed=0;}
+ else {sampled=plan.time;completed=plan.tick;}
+ return true;
+ }
+ double SampledTime()const{return sampled;}
+ void Clear(){*this=Clock();}
+};
+
+// Called after the real fftDecodeSamples/fftLimit helpers. Zeroing the fine sample
+// excludes its phase/derivatives while retaining the production broad/medium decode
+// and limiter; no duplicate Phillips equations or differently seeded spectrum exist.
+inline const char *IncidentSource(){return R"HLSL(
+float4 waterSurfIncident(FftMapSamples samples) {
+ samples.c=0;samples.cd=0;
+ FftSurface field=fftDecodeSamples(samples);
+ float3 derivative=fftLimitDerivative(field.displacement);
+ return float4(fftLimit(field.displacement).z,
+ field.derivativeX.z*derivative.z,field.derivativeY.z*derivative.z,field.incidentCompression);
+}
+)HLSL";}
+inline const char *Source(){return R"HLSL(
+struct WaterSurfContext {float4 coast;float4 surface;float4 admission;};
+// coast=(depth,physicalDistance,outwardX,outwardY)
+// surface=(exposure/spectral support,optical offshore,analyticDamping,spectralDamping)
+// admission=(wet,admitted,0,0); optical A is deliberately absent.
+bool waterSurfContextFinite(WaterSurfContext c){return all(isfinite(c.coast))&&all(isfinite(c.surface))&&all(isfinite(c.admission))
+ &&all(abs(c.coast.xy)<=1048576)&&all(abs(c.coast.zw)<=1024)&&all(c.surface>=0)&&all(c.surface<=1)
+ &&all(c.admission.xy>=0)&&all(c.admission.xy<=1);}
+bool waterSurfFieldFinite(float4 f){return all(isfinite(f))&&abs(f.x)<=64&&all(abs(f.yz)<=1024)&&abs(f.w)<=1048576;}
+float waterSurfDomain(WaterSurfContext c){
+ if(!waterSurfContextFinite(c)||c.admission.x<.5||c.admission.y<.5||c.surface.x<=0||c.coast.x<=.15||c.coast.y<0)return 0;
+ return smoothstep(.15,.8,c.coast.x)*(1-smoothstep(8,12,c.coast.x))
+ *(1-smoothstep(96,128,c.coast.y))*saturate(c.surface.x);
+}
+bool waterSurfStateFinite(float4 s){return all(isfinite(s))&&s.x>=0&&s.x<=16&&s.y>=0&&s.y<=1024&&abs(s.z)<=64&&s.w>=-1&&s.w<=1.2;}
+float4 waterSurfBlend(float4 analytic,float4 spectral,float weight){
+ if(!waterSurfFieldFinite(analytic)||!waterSurfFieldFinite(spectral)||!isfinite(weight))return float4(0,0,0,1);
+ float w=saturate(weight);return float4(analytic.xyz+(spectral.xyz-analytic.xyz)*w,1+(spectral.w-1)*w);
+}
+float waterSurfRate(WaterSurfContext c,float4 field,float4 previous,float dt){
+ float domain=waterSurfDomain(c);
+ if(domain<=0||!waterSurfFieldFinite(field)||!waterSurfStateFinite(previous)||previous.w<0||!isfinite(dt)||dt<=.000001||dt>.25||field.x<=0)return 0;
+ float n=length(c.coast.zw),slope=length(field.yz);if(n<=.00000001||slope<=.00000001)return 0;
+ float ht=(field.x-previous.z)/dt;if(!isfinite(ht)||!(ht>0))return 0;
+ float incoming=smoothstep(0,.25,dot(field.yz/slope,c.coast.zw/n));
+ float breaking=max(smoothstep(.4,.85,2*field.x/max(c.coast.x+.5,1)),smoothstep(.04,.30,1-field.w));
+ float damping=saturate(lerp(c.surface.z,c.surface.w,saturate(c.surface.x)));
+ return 1.2*domain*incoming*breaking*(1-damping*damping)*smoothstep(0,.5,field.x)*smoothstep(0,.08,ht);
+}
+float3 waterSurfIntegrals(float x){
+ float3 sum=0;float term=1;
+ [unroll]for(int k=0;k<10;++k){sum+=term/float3(k+1,k+2,k+3);term*=-x/(k+1);}
+ return sum;
+}
+float4 waterSurfIntegrate(float4 previous,float height,float rate,float dt,bool source){
+ if(!waterSurfStateFinite(previous)||!isfinite(height)||!isfinite(rate)||!isfinite(dt)||dt<0)return float4(0,0,0,-1);
+ if(dt<=.000001)return previous;
+ float x=dt/5,q=exp(-x);float density=q*previous.x,age=q*(previous.y+dt*previous.x);
+ if(source&&dt<=.25){
+ float a=clamp(previous.w,0,1.2),b=clamp(rate,0,1.2);float3 j=waterSurfIntegrals(x);
+ float w0=dt*j.y,w1=dt*(j.x-j.y),m0=dt*dt*j.z,m1=dt*dt*(j.y-j.z);
+ density+=a*w0+b*w1;age+=a*m0+b*m1;
+ }
+ if(q==0){density=0;age=0;}
+ return float4(density,age,height,source?clamp(rate,0,1.2):0);
+}
+float4 waterSurfAdvance(WaterSurfContext c,float4 field,float4 previous,float dt,bool allowSource){
+ if(dt>=0&&dt<=.000001&&waterSurfStateFinite(previous))return previous;
+ if(!waterSurfContextFinite(c)||!waterSurfFieldFinite(field)||c.admission.x<.5||c.admission.y<.5||c.surface.x<=0||c.coast.x<=.15)return float4(0,0,0,-1);
+ float rate=allowSource?waterSurfRate(c,field,previous,dt):0;
+ return waterSurfIntegrate(previous,field.x,rate,dt,allowSource&&dt<=.25);
+}
+float4 waterSurfDiffuse(float4 centre,float4 a,float4 b,float4 c,float4 d,uint mask,float spacing,float dt){
+ if(!waterSurfStateFinite(centre)||!isfinite(spacing)||spacing<4||!isfinite(dt)||dt<0||dt>.25)return float4(0,0,0,-1);
+ float amount=2*dt/(spacing*spacing);float2 value=centre.xy;
+ if(mask&1){if(!waterSurfStateFinite(a))return float4(0,0,0,-1);value+=amount*(a.xy-centre.xy);}
+ if(mask&2){if(!waterSurfStateFinite(b))return float4(0,0,0,-1);value+=amount*(b.xy-centre.xy);}
+ if(mask&4){if(!waterSurfStateFinite(c))return float4(0,0,0,-1);value+=amount*(c.xy-centre.xy);}
+ if(mask&8){if(!waterSurfStateFinite(d))return float4(0,0,0,-1);value+=amount*(d.xy-centre.xy);}
+ return float4(value,centre.zw);
+}
+float waterSurfCoverage(float4 state,float porous){
+ if(!waterSurfStateFinite(state)||!isfinite(porous)||state.x<=0)return 0;
+ float age=state.y/state.x,old=smoothstep(.4,3,age);
+ return (1-exp(-state.x))*lerp(1,saturate(porous),old)*(1-smoothstep(8,14,age));
+}
+)HLSL";}
+} // namespace WaterCoastalSurf
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterCoastalView.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterCoastalView.h
new file mode 100644
index 000000000..f2581afbd
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterCoastalView.h
@@ -0,0 +1,112 @@
+/* Bounded view-to-physical-coast interpolation. No state copying or GPU access. */
+#pragma once
+#include "Platform/WaterCoastalDomain.h"
+#include <limits>
+
+namespace WaterCoastalView {
+using Mapping=WaterShoreHistory::Mapping;
+using Lookup=WaterCoastalSurf::Lookup;
+constexpr unsigned MaxSide=WaterCoastalSurf::MaxViewSide;
+constexpr size_t MaxPixels=size_t(MaxSide)*MaxSide;
+// Helper-call allowance, not a CPU-instruction budget: one texel setup/At unit
+// plus at most four bounded Topology::Find and four Support::Allows calls. At
+// has a bounded binary search; Find/Allows bound probes or clipped vertices.
+constexpr size_t WorkPerPixel=9,MaxBuildWork=WorkPerPixel*MaxPixels;
+// Separate bounded coverage work: tile searches/corner checks/polygon edge visits.
+constexpr size_t MaxFootprintTiles=49,MaxFootprintBuildWork=64*MaxPixels;
+inline bool FitsFloat(double value){
+ const double limit=(std::numeric_limits<float>::max)();
+ return std::isfinite(value)&&value>=-limit&&value<=limit;
+}
+inline bool ExactFloat(double value){return FitsFloat(value)&&double(float(value))==value;}
+inline bool ValidLevel(double level){return ExactFloat(level);}
+inline bool ValidMapping(const Mapping&m){
+ return m.widthPixels>0&&m.heightPixels>0&&m.widthPixels<=MaxSide&&m.heightPixels<=MaxSide
+ &&ExactFloat(m.originX)&&ExactFloat(m.originY)&&ExactFloat(m.widthWorld)&&ExactFloat(m.heightWorld)
+ &&m.widthWorld>0&&m.heightWorld>0&&FitsFloat(m.originX+m.widthWorld)
+ &&FitsFloat(m.originY+m.heightWorld)&&std::isfinite(1.f/float(m.widthWorld))
+ &&std::isfinite(1.f/float(m.heightWorld));
+}
+inline bool SameMapping(const Mapping&a,const Mapping&b){
+ return a.originX==b.originX&&a.originY==b.originY&&a.widthWorld==b.widthWorld
+ &&a.heightWorld==b.heightWorld&&a.widthPixels==b.widthPixels&&a.heightPixels==b.heightPixels;
+}
+inline WaterShoreSupport::AreaResult FilterFootprint(const WaterCoastalDomain::Domain&domain,
+ const Mapping&m,double level,unsigned x,unsigned y,size_t &remaining){
+ using Result=WaterShoreSupport::AreaResult;const auto &g=domain.Grid();
+ const double dx=m.widthWorld/m.widthPixels,dy=m.heightWorld/m.heightPixels;
+ // The exact bilinear tent is centre +/- one texel spacing. Its enclosing 3x3
+ // pixel cells add half a texel of coordinate/filter margin. Clip to the chart:
+ // the presentation rejects UV outside it, and clamp only extends boundary cells.
+ const double x0=(m.originX+(x?double(x-1):0)*dx-g.originX)/g.spacing;
+ const double y0=(m.originY+(y?double(y-1):0)*dy-g.originY)/g.spacing;
+ const double x1=(m.originX+(std::min)(double(x)+2,double(m.widthPixels))*dx-g.originX)/g.spacing;
+ const double y1=(m.originY+(std::min)(double(y)+2,double(m.heightPixels))*dy-g.originY)/g.spacing;
+ if(!std::isfinite(x0)||!std::isfinite(y0)||!std::isfinite(x1)||!std::isfinite(y1)
+ ||x0<(std::numeric_limits<int32_t>::min)()||y0<(std::numeric_limits<int32_t>::min)()
+ ||x1>=(std::numeric_limits<int32_t>::max)()||y1>=(std::numeric_limits<int32_t>::max)()
+ ||x1<=x0||y1<=y0)return Result::Unsupported;
+ const int32_t loX=int32_t(std::floor(x0)),loY=int32_t(std::floor(y0));
+ const int32_t hiX=int32_t(std::ceil(x1)-1),hiY=int32_t(std::ceil(y1)-1);
+ const uint64_t nx=uint64_t(int64_t(hiX)-loX+1),ny=uint64_t(int64_t(hiY)-loY+1);
+ if(nx>MaxFootprintTiles||ny>MaxFootprintTiles||nx*ny>MaxFootprintTiles)return Result::OverBudget;
+ for(int32_t iy=loY;iy<=hiY;++iy)for(int32_t ix=loX;ix<=hiX;++ix){
+ if(!remaining)return Result::OverBudget;--remaining;
+ const auto tile=domain.Support().At(ix,iy,level,0,0);
+ const Result result=tile.CoversRectangle((std::max)(0.,x0-ix),(std::max)(0.,y0-iy),
+ (std::min)(1.,x1-ix),(std::min)(1.,y1-iy),remaining);
+ if(result!=Result::Covered)return result;
+ }
+ return Result::Covered;
+}
+// Texel centres use world=origin+(pixel+.5)*extent/count. The later shader uses
+// UV=(world-origin)/extent, with NO extra half-texel offset or flipped Y axis.
+// Float-exact metadata prevents a second rounded origin/extent in those uniforms.
+inline bool Build(const WaterCoastalDomain::Domain&domain,const Mapping&mapping,double level,
+ std::vector<Lookup>&output,size_t workAllowance=MaxBuildWork,
+ size_t footprintAllowance=MaxFootprintBuildWork){
+ if(!ValidMapping(mapping)||!ValidLevel(level))return false;
+ const size_t count=size_t(mapping.widthPixels)*mapping.heightPixels;
+ if(count*WorkPerPixel>(std::min)(workAllowance,MaxBuildWork))return false;
+ const auto &topology=domain.Topology();const auto &grid=domain.Grid();
+ const size_t nodes=domain.Nodes().size();
+ if(nodes>WaterCoastalSurf::MaxNodes||topology.Cells().size()!=nodes||!WaterShoreHistory::ValidGrid(grid))return false;
+ size_t remainingFootprint=(std::min)(footprintAllowance,MaxFootprintBuildWork);
+ std::vector<Lookup> next(count);
+ for(unsigned y=0;y<mapping.heightPixels;++y)for(unsigned x=0;x<mapping.widthPixels;++x){
+ const double wx=mapping.originX+(double(x)+.5)*mapping.widthWorld/mapping.widthPixels;
+ const double wy=mapping.originY+(double(y)+.5)*mapping.heightWorld/mapping.heightPixels;
+ const double px=(wx-grid.originX)/grid.spacing,py=(wy-grid.originY)/grid.spacing;
+ // An entirely off-domain view remains a valid empty lookup. Clamp neither
+ // coordinates nor indices: either would smear an outer row into distant water.
+ if(!std::isfinite(px)||!std::isfinite(py)||px<(std::numeric_limits<int32_t>::min)()
+ ||py<(std::numeric_limits<int32_t>::min)()||px>=(std::numeric_limits<int32_t>::max)()
+ ||py>=(std::numeric_limits<int32_t>::max)())continue;
+ const int32_t ix=int32_t(std::floor(px)),iy=int32_t(std::floor(py));
+ const double fx=px-ix,fy=py-iy;
+ const auto support=domain.Support().At(ix,iy,level,fx,fy);
+ Lookup &lookup=next[size_t(y)*mapping.widthPixels+x];
+ for(unsigned dy=0;dy<2;++dy)for(unsigned dx=0;dx<2;++dx){
+ const double weight=(dx?fx:1-fx)*(dy?fy:1-fy);
+ if(weight<=0)continue;
+ const int index=topology.Find(ix+int32_t(dx),iy+int32_t(dy),level);
+ if(index<0)continue;
+ if(size_t(index)>=nodes)return false;
+ if(!support.Allows(dx,dy))continue;
+ const float stored=float(weight);if(stored<=0)continue;
+ const unsigned corner=dy*2+dx;
+ lookup.node[corner]=uint32_t(index)+1;lookup.weight[corner]=stored;
+ }
+ // Missing/dry/wrong-level/gap contributions stay exactly zero. There is no
+ // normalization of retained weights and no nearest-node ownership shortcut.
+ if(!WaterCoastalSurf::ValidLookup(lookup,unsigned(nodes)))return false;
+ bool nonzero=false;for(unsigned c=0;c<4;++c)nonzero=nonzero||lookup.weight[c]>0;
+ if(nonzero){
+ const auto area=FilterFootprint(domain,mapping,level,x,y,remainingFootprint);
+ if(area==WaterShoreSupport::AreaResult::OverBudget)return false;
+ if(area!=WaterShoreSupport::AreaResult::Covered)lookup={};
+ }
+ }
+ output.swap(next);return true;
+}
+} // namespace WaterCoastalView
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterFftFiltering.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterFftFiltering.h
new file mode 100644
index 000000000..5605a21cb
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterFftFiltering.h
@@ -0,0 +1,60 @@
+/* Footprint filtering of the existing FFT fields. Geometry continues to use level zero. */
+#pragma once
+#include "Platform/WaterFftSpectrum.h"
+#include <array>
+#include <cstdio>
+
+namespace WaterFftFiltering {
+constexpr unsigned Levels=WaterFftSpectrum::Phases+1;
+using VarianceTable=std::array<std::array<double,WaterFftSpectrum::Cascades>,Levels>;
+
+// A mip is a box average of 2^level base texels. Integrate the energy removed from the
+// two height-slope channels, using this exact deterministic spectrum, not an unrelated
+// roughness constant. Independent forward/backward modes have additive expected power.
+inline VarianceTable UnresolvedSlopeVariance(const std::vector<float>& initial) {
+ using namespace WaterFftSpectrum;
+ VarianceTable result={};
+ if(initial.size()!=Resolution*Resolution*Cascades*4) return result;
+ for(unsigned c=0;c<Cascades;++c) for(unsigned y=0;y<Resolution;++y) for(unsigned x=0;x<Resolution;++x) {
+ const float *h=&initial[((c*Resolution+y)*Resolution+x)*4];
+ const double power=double(h[0])*h[0]+double(h[1])*h[1]+double(h[2])*h[2]+double(h[3])*h[3];
+ if(power==0) continue;
+ const double ax=Pi*(int(x)-int(Resolution/2))/Resolution,ay=Pi*(int(y)-int(Resolution/2))/Resolution;
+ const double kx=2*ax*Resolution/Sizes[c],ky=2*ay*Resolution/Sizes[c];
+ const double energy=power*(kx*kx+ky*ky);
+ for(unsigned l=1;l<Levels;++l) {
+ const unsigned width=1u<<l;
+ const double fx=ax==0?1:std::sin(width*ax)/(width*std::sin(ax));
+ const double fy=ay==0?1:std::sin(width*ay)/(width*std::sin(ay));
+ result[l][c]+=energy*(std::max)(0.0,1-fx*fx*fy*fy);
+ }
+ }
+ return result;
+}
+inline const VarianceTable &SpectrumVariance() {
+ static const VarianceTable table=UnresolvedSlopeVariance(WaterFftSpectrum::InitialSpectrum());
+ return table;
+}
+inline std::string Source() {
+ std::string source="static const float3 fftLostSlopeVariance[9]={\n";
+ const auto &table=SpectrumVariance();
+ for(unsigned l=0;l<Levels;++l) {
+ char row[192];std::snprintf(row,sizeof(row),"float3(%.9g,%.9g,%.9g)%s\n",table[l][0],table[l][1],table[l][2],l+1<Levels?",":"");
+ source+=row;
+ }
+ return source+R"HLSL(};
+float3 fftShadingLod(float footprint) {
+ float3 texels=max(footprint,0.0)*256.0/(float3(450.0,103.0,13.0)*fftWorldScale);
+ return clamp(log2(max(texels,float3(1,1,1))),0.0,8.0);
+}
+float fftShadingVariance(float3 lod) {
+ float result=0;
+ for(int c=0;c<3;++c) {
+ float level=clamp(lod[c],0.0,8.0);int low=min((int)level,7);
+ result+=lerp(fftLostSlopeVariance[low][c],fftLostSlopeVariance[low+1][c],level-low);
+ }
+ return result;
+}
+)HLSL";
+}
+}
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterFftGeometry.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterFftGeometry.h
new file mode 100644
index 000000000..6009a0324
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterFftGeometry.h
@@ -0,0 +1,83 @@
+/* Render-only metadata for replacing an analytic ocean interior with GPU FFT displacement. */
+#pragma once
+#include "Platform/WaterProjectedMesh.h"
+#include "Platform/WaterSurfaceModel.h"
+#include <cmath>
+
+namespace WaterFftGeometry {
+constexpr float MaxVerticalDisplacement=WaterSurfaceModel::OceanMaxDisplacement;
+constexpr float MaxHorizontalDisplacement=8.0f;
+constexpr float FloorClearance=0.15f;
+constexpr double InnerWorldCollar=WaterProjectedMesh::CollarWidth;
+constexpr double OuterWorldCollar=InnerWorldCollar*2.0;
+constexpr double InnerCellCollar=2.0;
+constexpr double OuterCellCollar=4.0;
+
+inline float SafeDamping(float damping,float terrainDepth) {
+ if (!std::isfinite(damping) || !std::isfinite(terrainDepth)) return 0;
+ const float floor=(terrainDepth-FloorClearance)/MaxVerticalDisplacement;
+ return (std::max)(0.0f,(std::min)(1.0f,(std::min)(damping,floor)));
+}
+inline double SmoothRange(double value,double low,double high) {
+ const double t=(std::max)(0.0,(std::min)(1.0,(value-low)/(high-low)));
+ return t*t*(3.0-2.0*t);
+}
+
+// A cell cut by an authored boundary has diameter sqrt(2) in lattice coordinates.
+// Keeping the first two cells analytic preserves every boundary knot, centre transition,
+// and source anchor. The fade then changes continuously with camera motion and resize.
+// Edge lines are transformed algebraically, so an authored endpoint at the horizon does
+// not cause a divide-by-zero or disable the entire ocean for one camera frame.
+class SeamFade {
+ struct Edge { double x,y,c,worldScale,screenX,screenY,screenC,screenScale; };
+ Edge edges[4];int count=0;
+ WaterProjectedMesh::Projection projection{};
+ bool ready=false;
+public:
+ bool Prepare(const WaterProjectedMesh::Point corners[4],
+ const WaterProjectedMesh::Projection &source,WaterProjectedMesh::Resolution resolution) {
+ count=0;ready=false;projection=source;
+ if (resolution.columns<2 || resolution.rows<2) return false;
+ const double stepX=2*(1+source.margin)/resolution.columns;
+ const double stepY=2*(1+source.margin)/resolution.rows;
+ if (!(stepX>0) || !(stepY>0) || !std::isfinite(stepX) || !std::isfinite(stepY)) return false;
+ for (int i=0;i<4;++i) {
+ auto a=corners[i],b=corners[(i+1)%4];
+ if (a.x>b.x || (a.x==b.x && a.y>b.y)) std::swap(a,b);
+ Edge edge{};edge.x=a.y-b.y;edge.y=b.x-a.x;edge.c=a.x*b.y-b.x*a.y;
+ const double length=std::sqrt(edge.x*edge.x+edge.y*edge.y);
+ if (!std::isfinite(length)) return false;
+ if (length<1e-12) continue;
+ edge.worldScale=1.0/length;
+ const double *m=source.inverse;
+ edge.screenX=edge.x*m[0]+edge.y*m[3]+edge.c*m[6];
+ edge.screenY=edge.x*m[1]+edge.y*m[4]+edge.c*m[7];
+ edge.screenC=edge.x*m[2]+edge.y*m[5]+edge.c*m[8];
+ const double screenLength=std::sqrt(edge.screenX*edge.screenX*stepX*stepX+
+ edge.screenY*edge.screenY*stepY*stepY);
+ if (!std::isfinite(screenLength) || !std::isfinite(edge.screenC)) return false;
+ // A world edge lying on the horizon has no finite projected line and cannot cut a
+ // visible finite lattice cell. Its world-space collar still remains active.
+ edge.screenScale=screenLength>1e-12?1.0/screenLength:0.0;
+ edges[count++]=edge;
+ }
+ ready=count>=3;return ready;
+ }
+ float Weight(WaterProjectedMesh::Point point,float spectralSupport) const {
+ if (!ready || !std::isfinite(spectralSupport) || spectralSupport<=0) return 0;
+ WaterProjectedMesh::Point screen;
+ if (!projection.Transform(point,screen)) return 0;
+ double worldDistance=OuterWorldCollar,cellDistance=OuterCellCollar;
+ for (int i=0;i<count;++i) {
+ const Edge &e=edges[i];
+ const double world=std::abs(e.x*point.x+e.y*point.y+e.c)*e.worldScale;
+ const double cells=e.screenScale>0?
+ std::abs(e.screenX*screen.x+e.screenY*screen.y+e.screenC)*e.screenScale:OuterCellCollar;
+ if (!std::isfinite(world) || !std::isfinite(cells)) return 0;
+ worldDistance=(std::min)(worldDistance,world);cellDistance=(std::min)(cellDistance,cells);
+ }
+ return float((std::min)(1.0f,spectralSupport)*SmoothRange(worldDistance,InnerWorldCollar,OuterWorldCollar)*
+ SmoothRange(cellDistance,InnerCellCollar,OuterCellCollar));
+ }
+};
+}
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterFftSampling.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterFftSampling.h
new file mode 100644
index 000000000..d3254a6ab
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterFftSampling.h
@@ -0,0 +1,443 @@
+// Native sampling of the three-cascade Phillips ocean described by codeagent/webgl-ocean.
+// The reference uses Y-up; the game uses Z-up. The field stays entirely on the GPU.
+#pragma once
+#include <string>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include "Platform/WaterFftGeometry.h"
+#include "Platform/WaterVesselWaves.h"
+#include "Platform/WaterFftFiltering.h"
+#include "Platform/WaterBowLift.h"
+#include "Platform/WaterWaveCageShader.h"
+#include "Platform/ModernWaterMaterial.h"
+
+namespace WaterFftSampling {
+inline bool Enabled() {
+ const char *value=std::getenv("ZH_WATER_FFT");
+ return !value || std::strcmp(value,"0")!=0;
+}
+// The reference's close water-level camera uses metre-sized waves. Generals' RTS camera
+// requires a larger render scale; scale wavelength and displacement together, not normals.
+constexpr float WorldScale=WaterFftSpectrum::WorldScale;
+constexpr float TimeScale=0.4f;
+// Both stages consume the same immutable draw snapshot. Slot zero remains the generated
+// fixed vertex block; the vessel field is water-only slot one on the vertex stage.
+inline std::string UniformSource(const char *name,unsigned slot,bool visual_hull=false) {
+ std::string source=std::string("cbuffer ")+name+" : register(b"+std::to_string(slot)+R"HLSL()
+{
+ float4 TextureFactor;
+ float4 FogColour;
+ float4 AlphaReference;
+ row_major float4x4 WorldFromClip;
+ float4 CameraPosition;
+ float4 SunDirection;
+ float4 SunColour;
+ float4 Viewport;
+ float4 ReflectionArea;
+ float4 WaterParameters;
+ float4 TerrainParameters;
+ float4 SceneParameters;
+ float4 OpticalParameters;
+ float4 HullParameters;
+ float4 HullData[80];
+ float4 FftParameters;
+ float4 FoamHistoryArea;
+ float4 FoamHistoryParameters;
+ float4 ContactHullData[80];
+ float4 FoamFillLights[4];
+ float4 CoastalArea;
+ float4 CoastalParams;
+)HLSL";
+#define MODERN_WATER_HLSL_UNIFORM(name) " float4 " #name ";\n"
+ source+=MODERN_WATER_MATERIAL_UNIFORMS(MODERN_WATER_HLSL_UNIFORM);
+#undef MODERN_WATER_HLSL_UNIFORM
+ if(visual_hull) source+=" float4 VisualHullMeta[8];\n";
+ source+="};\n";
+ if(visual_hull) source+=R"HLSL(
+cbuffer WaterVisualBlock0 : register(b1) { float4 VisualHullBlock0[256]; };
+cbuffer WaterVisualBlock1 : register(b2) { float4 VisualHullBlock1[256]; };
+cbuffer WaterVisualBlock2 : register(b3) { float4 VisualHullBlock2[192]; };
+)HLSL";
+ return source;
+}
+inline std::string CommonSource()
+{
+ char limits[256];
+ std::snprintf(limits,sizeof(limits),
+ "static const float fftVerticalBound=%.9g;\nstatic const float fftHorizontalBound=%.9g;\nstatic const float fftWorldScale=%.9g;\n",
+ double(WaterFftGeometry::MaxVerticalDisplacement),double(WaterFftGeometry::MaxHorizontalDisplacement)/1.4142135623730951,double(WorldScale));
+ return std::string(limits)+R"HLSL(
+// Smooth limits make culling/floor bounds independent of the random spectrum's extrema.
+// Each XY component is bounded by the radial limit / sqrt(2), preserving the hull-clearance
+// proof even for diagonal crests. Keep the derivative in the same model as displacement.
+float3 fftLimit(float3 d) {
+ float3 bound=float3(fftHorizontalBound,fftHorizontalBound,fftVerticalBound);
+ return bound*tanh(d/bound);
+}
+float3 fftLimitDerivative(float3 d) {
+ float3 q=tanh(d/float3(fftHorizontalBound,fftHorizontalBound,fftVerticalBound));
+ return 1.0-q*q;
+}
+// Shared physical coordinate map: generated bow pressure changes only Z, so all
+// incident/reflected XY can be resolved first without an iterative height solve.
+float2 fftHorizontalPosition(float2 p,float3 raw,float scale) {
+ return p+fftLimit(raw).xy*scale;
+}
+struct FftHorizontalRegistration { float2 position,derivativeX,derivativeY; };
+FftHorizontalRegistration fftHorizontalRegistration(float2 p,float3 raw,float3 rawX,float3 rawY,float3 scale) {
+ FftHorizontalRegistration map;
+ map.position=fftHorizontalPosition(p,raw,scale.x);
+ float2 limited=fftLimit(raw).xy,derivative=fftLimitDerivative(raw).xy;
+ map.derivativeX=float2(1,0)+rawX.xy*derivative*scale.x+limited*scale.y;
+ map.derivativeY=float2(0,1)+rawY.xy*derivative*scale.x+limited*scale.z;
+ return map;
+}
+)HLSL";
+}
+inline std::string VertexSource(bool bowLift=false,bool bowShoulder=WaterBowShoulder::Enabled())
+{
+ return std::string(R"HLSL(
+Texture2D FftDisplacement0 : register(t0);
+SamplerState FftSampler0 : register(s0);
+Texture2D FftDisplacement1 : register(t1);
+SamplerState FftSampler1 : register(s1);
+Texture2D FftDisplacement2 : register(t2);
+SamplerState FftSampler2 : register(s2);
+)HLSL")+CommonSource()+(bowLift?WaterBowLift::Source():std::string())+WaterVesselWaves::Source(true,bowShoulder)+R"HLSL(
+float3 fftRawDisplacement(float2 p) {
+ float3 a=FftDisplacement0.SampleLevel(FftSampler0,p/(450.0*fftWorldScale),0).xyz;
+ float3 b=FftDisplacement1.SampleLevel(FftSampler1,p/(103.0*fftWorldScale),0).xyz;
+ float3 c=FftDisplacement2.SampleLevel(FftSampler2,p/(13.0*fftWorldScale),0).xyz;
+ return (a.xzy*float3(-1.2,-1.2,1)+b.xzy*float3(-1.5,-1.5,1)
+ +c.xzy*float3(-1.5,-1.5,1))*fftWorldScale;
+}
+)HLSL"+(bowLift?R"HLSL(float3 fftVertexBowDisplacement(float2 p,float level,float horizontalScale,out float bowHeight) {
+ bowHeight=0;)HLSL":R"HLSL(float3 fftVertexDisplacement(float2 p,float level,float horizontalScale) {)HLSL")+R"HLSL(
+ float3 displacement=fftRawDisplacement(p);
+ if(FftParameters.y>0.5) {
+ int count=clamp((int)HullParameters.x,0,8);
+ float3 oldBow[8];
+ for(int h=0;h<count;++h) {
+ VesselReflection reflected=vesselReflection(p,level,h);
+ if(reflected.weight>0.0)
+ displacement+=vesselReflectedValue(fftRawDisplacement(reflected.samplePosition),reflected);
+ displacement.z+=vesselGeneratedWave(p,level,WaterParameters.x,h,oldBow[h]).x;
+ }
+ if()HLSL"+(bowShoulder?std::string("true"):std::string("horizontalScale!=0.0"))+R"HLSL() {
+ float2 position=fftHorizontalPosition(p,displacement,horizontalScale);
+ for(int h=0;h<count;++h)
+)HLSL"+(bowLift?R"HLSL( {float currentBow=vesselGeneratedBow(position,level,h).x;
+ displacement.z+=currentBow-oldBow[h].x;bowHeight+=currentBow;})HLSL":R"HLSL( displacement.z+=vesselGeneratedBow(position,level,h).x-oldBow[h].x;)HLSL")+R"HLSL(
+)HLSL"+(bowLift?R"HLSL( } else {for(int h=0;h<count;++h)bowHeight+=oldBow[h].x;}
+ }
+ return fftLimit(displacement);
+}
+float3 fftVertexDisplacement(float2 p,float level,float horizontalScale) {
+ float ignored;return fftVertexBowDisplacement(p,level,horizontalScale,ignored);
+}
+// Compatibility callers without mesh metadata retain their unregistered model.)HLSL":R"HLSL( }
+ }
+ return fftLimit(displacement);
+}
+// Compatibility callers without mesh metadata retain their unregistered model.)HLSL")+R"HLSL(
+float3 fftVertexDisplacement(float2 p,float level) {return fftVertexDisplacement(p,level,0.0);}
+float3 fftVertexDisplacement(float2 p) {return fftVertexDisplacement(p,WaterParameters.w);}
+)HLSL";
+}
+// Add a water-only wrapper to the generated fixed vertex program. It retains the engine's
+// original projection, shroud coordinate generation and fog after moving the actual vertex.
+inline bool WrapVertex(std::string &hlsl,bool bowLift=WaterBowLift::Enabled(),bool bowShoulder=WaterBowShoulder::Enabled())
+{
+ const std::string entry="Output main(Input input)";
+ const size_t at=hlsl.find(entry);
+ if(at==std::string::npos || hlsl.find("float3 Normal")==std::string::npos
+ || hlsl.find("float2 TexCoord1")==std::string::npos) return false;
+ hlsl.replace(at,entry.size(),"Output waterFixedVertex(Input input)");
+ hlsl+=UniformSource("WaterVertexParameters",1);
+ hlsl+=VertexSource(bowLift,bowShoulder);
+ hlsl+=WaterWaveCageShader::Source(true);
+ hlsl+=std::string(R"HLSL(
+Output main(Input input)
+{
+ float2 parameter=input.Position.xy;
+ float weight=saturate(input.Normal.x), freeDamping=saturate(input.Normal.y);
+ float offshore=saturate(input.Normal.z);
+ // Carry the same vertical phases through the shallows, while retaining the
+ // coastal restriction on horizontal chop and its terrain/obstacle clearance.
+ float horizontalWeight=weight*offshore;
+ float originalHeight=input.Position.z-input.TexCoord1.y;
+ if(weight>0.0) {
+ float damping=vesselApplyHullDamping(parameter,input.TexCoord1.y,
+ float3(freeDamping,0,0),float3(offshore,0,0)).x;
+)HLSL")+(bowLift?R"HLSL( float bowHeight;
+ float3 displacement=fftVertexBowDisplacement(parameter,input.TexCoord1.y,horizontalWeight*damping,bowHeight);
+ float lifted=fftBowLift(float3(bowHeight,0,0),float3(freeDamping,0,0),float3(damping,0,0)).x;)HLSL":R"HLSL( float3 displacement=fftVertexDisplacement(parameter,input.TexCoord1.y,horizontalWeight*damping);)HLSL")+R"HLSL(
+ WaveCage cage=waveCage(parameter,input.TexCoord1.y);
+ float cageAmount=cage.support;
+ float3 cageDisplacement=0;
+ if(cageAmount>0.0) {
+ float cageObstacle=vesselApplyHullDamping(parameter,input.TexCoord1.y,
+ float3(saturate(input.Diffuse.r),0,0),float3(1,0,0)).x;
+ if(cageObstacle>0.0)
+ cageDisplacement=waveCageFloor(parameter,input.TexCoord1.y,waveCageMap(cage,displacement)*cageObstacle);
+ }
+ input.Position.xy+=lerp(displacement.xy*(horizontalWeight*damping),cageDisplacement.xy*weight,cageAmount);
+ input.Position.z=input.TexCoord1.y+)HLSL"+(bowLift?R"HLSL(lerp(originalHeight,displacement.z*damping+lifted,weight))HLSL":R"HLSL(lerp(originalHeight,displacement.z*damping,weight))HLSL")+R"HLSL(;
+ input.Position.z=lerp(input.Position.z,input.TexCoord1.y+lerp(originalHeight,cageDisplacement.z,weight),cageAmount);
+ }
+ input.Normal=float3(0,0,1);
+ Output output=waterFixedVertex(input);
+ // TC3 is the existing shroud; TC2 and specular are unused by this water material.
+ output.TexCoord2=parameter;
+ output.Specular=float4(weight,freeDamping,originalHeight,offshore);
+ return output;
+}
+)HLSL";
+ return true;
+}
+inline std::string PixelSource(bool bowLift=false,bool bowShoulder=WaterBowShoulder::Enabled(),bool textureArray=false)
+{
+ std::string source=CommonSource()+(bowLift?WaterBowLift::Source():std::string())+WaterVesselWaves::Source(true,bowShoulder)+WaterFftFiltering::Source()+R"HLSL(
+)HLSL"+(bowLift?R"HLSL(struct FftSurface {
+ float3 bow;
+ float bowLimitedDelta;
+ float3 displacement;)HLSL":R"HLSL(struct FftSurface {
+ float3 displacement;)HLSL")+R"HLSL(
+ float3 derivativeX;
+ float3 derivativeY;
+ float compression;
+ float incidentCompression;
+ float3 contactIncident;
+ float vesselHeight;
+ float vesselCrest;
+ // Diagnostic-only outputs. Unused normal rendering removes this accumulator and the
+ // second limiter through dead-code elimination; no displacement/normal inputs change.
+ float generatedRaw;
+ float generatedHeight;
+ float3 shadingDisplacement;
+ float3 shadingDerivativeX;
+ float3 shadingDerivativeY;
+ float unresolvedSlopeVariance;
+};
+struct FftMapSamples { float4 a,ad,b,bd,c,cd; };
+FftMapSamples fftMapSamples(float2 p,float3 lod) {
+ FftMapSamples samples;
+ samples.a=Texture8.SampleLevel(Sampler8,p/(450.0*fftWorldScale),lod[0]);
+ samples.ad=Texture9.SampleLevel(Sampler9,p/(450.0*fftWorldScale),lod[0]);
+ samples.b=Texture10.SampleLevel(Sampler10,p/(103.0*fftWorldScale),lod[1]);
+ samples.bd=Texture11.SampleLevel(Sampler11,p/(103.0*fftWorldScale),lod[1]);
+ samples.c=Texture12.SampleLevel(Sampler12,p/(13.0*fftWorldScale),lod[2]);
+ samples.cd=Texture13.SampleLevel(Sampler13,p/(13.0*fftWorldScale),lod[2]);
+ return samples;
+}
+FftSurface fftDecodeSamples(FftMapSamples samples) {
+ float4 a=samples.a,ad=samples.ad,b=samples.b,bd=samples.bd,c=samples.c,cd=samples.cd;
+ // Keep the same decode operations across paired and independent shader contexts.
+ // Reassociation/FMA contraction must not make physical geometry depend on footprint.
+ precise float3 d=(a.xzy*float3(-1.2,-1.2,1)+b.xzy*float3(-1.5,-1.5,1)
+ +c.xzy*float3(-1.5,-1.5,1))*fftWorldScale;
+ // Scaling wavelength and height together leaves dimensionless derivatives unchanged.
+ precise float3 x=float3(ad.z,a.w,ad.x)*float3(-1.2,-1.2,1)
+ +float3(bd.z,b.w,bd.x)*float3(-1.5,-1.5,1)+float3(cd.z,c.w,cd.x)*float3(-1.5,-1.5,1);
+ precise float3 y=float3(a.w,ad.w,ad.y)*float3(-1.2,-1.2,1)
+ +float3(b.w,bd.w,bd.y)*float3(-1.5,-1.5,1)+float3(c.w,cd.w,cd.y)*float3(-1.5,-1.5,1);
+ FftSurface value=(FftSurface)0;
+ value.displacement=d;
+ value.derivativeX=x;
+ value.derivativeY=y;
+ // Ambient breaking follows the broad and medium incident surface. Fine ripples
+ // still displace geometry and contribute their full normals, but their short-scale
+ // compression must not turn the entire surface into whitecaps. Limit this selected
+ // surface independently: a limiter evaluated on all three cascades would let the
+ // fine displacement modulate the breaking signal even with its derivatives removed.
+ precise float2 breakingDisplacement=(a.xz*-1.2+b.xz*-1.5)*fftWorldScale;
+ precise float2 breakingX=float2(ad.z,a.w)*-1.2+float2(bd.z,b.w)*-1.5;
+ precise float2 breakingY=float2(a.w,ad.w)*-1.2+float2(b.w,bd.w)*-1.5;
+ float2 breakingLimit=fftLimitDerivative(float3(breakingDisplacement,0)).xy;
+ breakingX*=breakingLimit;
+ breakingY*=breakingLimit;
+ value.incidentCompression=(1+breakingX.x)*(1+breakingY.y)-breakingX.y*breakingY.x;
+ // Contact wash responds to the incident swell/wind waves. Reflected or generated
+ // vessel fields and fine ripples must not regenerate stationary propulsion foam.
+ // Reuse these physical samples; no extra texture fetch or vertex displacement.
+ float contactHeight=fftVerticalBound*tanh((a.y+b.y)*fftWorldScale/fftVerticalBound);
+ float contactDerivative=1.0-(contactHeight/fftVerticalBound)*(contactHeight/fftVerticalBound);
+ value.contactIncident=float3(contactHeight,(ad.xy+bd.xy)*contactDerivative);
+ return value;
+}
+FftSurface fftRawSurface(float2 p,float3 lod) {return fftDecodeSamples(fftMapSamples(p,lod));}
+FftSurface fftRawSurface(float2 p) {return fftRawSurface(p,float3(0,0,0));}
+void fftRawAndShadingSurface(float2 p,float3 lod,out FftSurface physical,out FftSurface shading) {
+ FftMapSamples samples=fftMapSamples(p,float3(0,0,0));
+ physical=fftDecodeSamples(samples);
+ shading=physical;
+ if(any(lod>0.0)) {
+ // Preserve each already resolved cascade's exact mip-zero samples. Only the
+ // unresolved pairs need another lookup; decoding and accumulation order stay identical.
+ [branch] if(lod.x>0.0) {
+ samples.a=Texture8.SampleLevel(Sampler8,p/(450.0*fftWorldScale),lod.x);
+ samples.ad=Texture9.SampleLevel(Sampler9,p/(450.0*fftWorldScale),lod.x);
+ }
+ [branch] if(lod.y>0.0) {
+ samples.b=Texture10.SampleLevel(Sampler10,p/(103.0*fftWorldScale),lod.y);
+ samples.bd=Texture11.SampleLevel(Sampler11,p/(103.0*fftWorldScale),lod.y);
+ }
+ [branch] if(lod.z>0.0) {
+ samples.c=Texture12.SampleLevel(Sampler12,p/(13.0*fftWorldScale),lod.z);
+ samples.cd=Texture13.SampleLevel(Sampler13,p/(13.0*fftWorldScale),lod.z);
+ }
+ shading=fftDecodeSamples(samples);
+ }
+}
+FftSurface fftSurface(float2 p,float level,float footprint,float3 horizontalScale) {
+ float3 shadingLod=fftShadingLod(footprint);
+ bool filtered=any(shadingLod>0.0);
+ FftSurface value,shading;
+ fftRawAndShadingSurface(p,shadingLod,value,shading);
+ float reflectionVariance=1.0;
+ float oldHeight=fftLimit(value.displacement).z;
+ // Mirroring a field around a hull changes its parameterization; a compressed mirror
+ // Jacobian alone is not a breaking wave. Preserve incident whitecaps and add only the
+ // restrained bow/wake crest signal below, while using full derivatives for the normals.
+ // fftDecodeSamples already retained the broad/medium incident compression before
+ // any hull reflection or generated vessel packet changes this full surface.
+ if(FftParameters.y>0.5) {
+ int count=clamp((int)HullParameters.x,0,8);
+ float3 oldBow[8];float oldGenerated[8];
+ for(int h=0;h<count;++h) {
+ VesselReflection reflected=vesselReflection(p,level,h);
+ if(reflected.weight>0.0) {
+ FftSurface incident,shadingIncident;
+ fftRawAndShadingSurface(reflected.samplePosition,shadingLod,incident,shadingIncident);
+ if(filtered) {
+ shading.displacement+=vesselReflectedValue(shadingIncident.displacement,reflected);
+ shading.derivativeX+=vesselReflectedDerivative(shadingIncident.displacement,shadingIncident.derivativeX,
+ shadingIncident.derivativeY,float2(1,0),reflected);
+ shading.derivativeY+=vesselReflectedDerivative(shadingIncident.displacement,shadingIncident.derivativeX,
+ shadingIncident.derivativeY,float2(0,1),reflected);
+ reflectionVariance+=reflected.weight*reflected.weight;
+ }
+ value.displacement+=vesselReflectedValue(incident.displacement,reflected);
+ value.derivativeX+=vesselReflectedDerivative(incident.displacement,incident.derivativeX,
+ incident.derivativeY,float2(1,0),reflected);
+ value.derivativeY+=vesselReflectedDerivative(incident.displacement,incident.derivativeX,
+ incident.derivativeY,float2(0,1),reflected);
+ }
+ float3 generated=vesselGeneratedWave(p,level,WaterParameters.x,h,oldBow[h]);
+)HLSL"+(bowLift?R"HLSL( oldGenerated[h]=generated.x;
+ if()HLSL"+(bowShoulder?std::string("false"):std::string("!any(horizontalScale!=0.0)"))+R"HLSL()value.bow+=oldBow[h];)HLSL":R"HLSL( oldGenerated[h]=generated.x;)HLSL")+R"HLSL(
+ if(filtered) {
+ shading.displacement.z+=generated.x;
+ shading.derivativeX.z+=generated.y;
+ shading.derivativeY.z+=generated.z;
+ }
+ value.displacement.z+=generated.x;
+ value.derivativeX.z+=generated.y;
+ value.derivativeY.z+=generated.z;
+ value.vesselCrest+=max(generated.x,0.0)*0.32;
+ value.generatedRaw+=generated.x;
+ }
+ if()HLSL"+(bowShoulder?std::string("true"):std::string("any(horizontalScale!=0.0)"))+R"HLSL() {
+ // The physical mip-zero map is shared even when reflected lighting is filtered.
+ // Retaining the original loop above preserves stern/history accumulation and
+ // permits an exact zero-chop difference, without another FFT texture sample.
+ FftHorizontalRegistration map=fftHorizontalRegistration(p,value.displacement,
+ value.derivativeX,value.derivativeY,horizontalScale);
+ for(int h=0;h<count;++h) {
+ )HLSL"+(bowLift?R"HLSL(float3 bow=vesselGeneratedBow(map.position,level,h);
+ bow.yz=float2(dot(bow.yz,map.derivativeX),dot(bow.yz,map.derivativeY));
+ value.bow+=bow;
+ float3 correction=bow-oldBow[h];)HLSL":R"HLSL(float3 correction=vesselRegisteredBowDifference(map.position,map.derivativeX,map.derivativeY,level,h,oldBow[h]);)HLSL")+R"HLSL(
+ if(filtered) {
+ shading.displacement.z+=correction.x;
+ shading.derivativeX.z+=correction.y;
+ shading.derivativeY.z+=correction.z;
+ }
+ value.displacement.z+=correction.x;
+ value.derivativeX.z+=correction.y;
+ value.derivativeY.z+=correction.z;
+ value.vesselCrest+=(max(oldGenerated[h]+correction.x,0.0)-max(oldGenerated[h],0.0))*0.32;
+ value.generatedRaw+=correction.x;
+ }
+ }
+ }
+ float3 derivative=fftLimitDerivative(value.displacement);
+ float withoutGenerated=fftVerticalBound*tanh((value.displacement.z-value.generatedRaw)/fftVerticalBound);
+)HLSL"+(bowLift?R"HLSL( // Same physical sample and phase, removing only the registered bow contribution.
+ // This diagnostic excludes the extra floor lift, which is applied with mesh damping below.
+ float withoutBow=fftVerticalBound*tanh((value.displacement.z-value.bow.x)/fftVerticalBound);
+)HLSL":std::string())+R"HLSL(
+ value.displacement=fftLimit(value.displacement);
+)HLSL"+(bowLift?R"HLSL( value.bowLimitedDelta=value.displacement.z-withoutBow;
+)HLSL":std::string())+R"HLSL(
+ value.generatedHeight=value.displacement.z-withoutGenerated;
+ value.derivativeX*=derivative;
+ value.derivativeY*=derivative;
+ if(filtered) {
+ float3 shadingLimit=fftLimitDerivative(shading.displacement);
+ value.shadingDisplacement=fftLimit(shading.displacement);
+ value.shadingDerivativeX=shading.derivativeX*shadingLimit;
+ value.shadingDerivativeY=shading.derivativeY*shadingLimit;
+ // Expected missing slope power, with local limiter attenuation. Reflected copies use
+ // an independent-energy approximation; this does not claim a full covariance solver.
+ value.unresolvedSlopeVariance=fftShadingVariance(shadingLod)*reflectionVariance*shadingLimit.z*shadingLimit.z;
+ } else {
+ value.shadingDisplacement=value.displacement;
+ value.shadingDerivativeX=value.derivativeX;
+ value.shadingDerivativeY=value.derivativeY;
+ }
+ value.vesselHeight=value.displacement.z-oldHeight;
+ value.vesselCrest=saturate(value.vesselCrest);
+ value.compression=(1+value.derivativeX.x)*(1+value.derivativeY.y)
+ -value.derivativeX.y*value.derivativeY.x;
+ return value;
+}
+// Compatibility callers without mesh metadata retain their unregistered model.
+FftSurface fftSurface(float2 p,float level,float footprint) {return fftSurface(p,level,footprint,float3(0,0,0));}
+FftSurface fftSurface(float2 p,float level) {return fftSurface(p,level,0.0);}
+FftSurface fftSurface(float2 p) {return fftSurface(p,WaterParameters.w);}
+float3 fftPressureDebug(FftSurface surface,float weight,float damping,float generatedFoam) {
+ return float3(max(surface.generatedRaw,0.0)/8.0,
+ max(surface.generatedHeight,0.0)*weight*damping/3.85,generatedFoam);
+}
+float3 fftPressureRetentionDebug(FftSurface surface,float weight,float damping,float generatedFoam) {
+ // Gaussian tails smaller than this raw height are below meaningful float subtraction
+ // resolution at the limiter. Do not mislabel their cancellation as a large red footprint.
+ if(surface.generatedRaw<=0.0001) return 0;
+ float isolated=fftVerticalBound*tanh(surface.generatedRaw/fftVerticalBound);
+ return float3(1.0-saturate(surface.generatedHeight/max(isolated,0.000001)),
+ weight*damping,generatedFoam);
+}
+)HLSL"+(bowLift?R"HLSL(float3 fftBowRetentionDebug(FftSurface surface,float weight,float freeDamping,float damping) {
+ // R: registered bow / 8 world units. G: its actual marginal final rise / V.
+ // B: available mesh envelope. Keep stern/reflected/incident height in the same limiter;
+ // an isolated tanh(bow/V) cannot measure the loss at the current FFT phase.
+ float lifted=fftBowLift(surface.bow,float3(freeDamping,0,0),float3(damping,0,0)).x;
+ return float3(max(surface.bow.x,0.0)/8.0,
+ max(damping*surface.bowLimitedDelta+lifted,0.0)*weight/fftVerticalBound,
+ weight*freeDamping);
+}
+)HLSL":std::string())+R"HLSL(
+float2 fftParameterGradient(float value,float2 px,float2 py) {
+ float det=px.x*py.y-px.y*py.x;
+ float inverse=abs(det)>0.000001?1.0/det:0.0;
+ return float2(ddx(value)*py.y-ddy(value)*px.y,ddy(value)*px.x-ddx(value)*py.x)*inverse;
+}
+)HLSL";
+ if(textureArray) {
+ // Preserve the independent-map source contract used by the coastal decoder and
+ // numerical fixtures; only the material's native binding changes.
+ std::string sampling;
+ for(unsigned layer=0;layer<6;++layer) {
+ const std::string i=std::to_string(layer),stage=std::to_string(layer+8);
+ const std::string from="Texture"+stage+".SampleLevel(Sampler"+stage+",",to="fftMap"+i+"(";
+ for(size_t at=source.find(from);at!=std::string::npos;at=source.find(from,at+to.size()))
+ source.replace(at,from.size(),to);
+ sampling+="float4 fftMap"+i+"(float2 uv,float lod) { return OceanMaps.SampleLevel(OceanSampler,float3(uv,"+i+"),lod); }\n";
+ }
+ source=sampling+source;
+ }
+ return source;
+}
+} // namespace WaterFftSampling
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterFftSpectrum.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterFftSpectrum.h
new file mode 100644
index 000000000..cc277467c
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterFftSpectrum.h
@@ -0,0 +1,170 @@
+#pragma once
+
+// Source-generated Phillips ocean, using the complex-pair packing of the fft-2d reference.
+// All coordinates here are the reference's horizontal x/z plane, before the renderer's Z-up mapping.
+#include <cmath>
+#include <algorithm>
+#include <cstdint>
+#include <string>
+#include <vector>
+
+namespace WaterFftSpectrum {
+constexpr unsigned Resolution=256, Phases=8, Cascades=3, Maps=6;
+constexpr float Sizes[Cascades]={450.0f,103.0f,13.0f};
+// Sampling and spectrum construction share one reference-to-world conversion.
+constexpr float WorldScale=20.0f;
+// World-space energy budgets for the actual seeded bands, before sampling and limiting.
+constexpr double HeightRms[Cascades]={1.50,0.75,0.18};
+// Phillips length controls spectral shape independently of propagation direction.
+// The medium/fine lengths retain the previous (2^2+2^2)/9.81 value.
+constexpr double WindLengths[Cascades]={4.0,8.0/9.81,8.0/9.81};
+constexpr double DirectionPowers[Cascades]={2.0,1.0,0.01};
+constexpr double WindDirectionX=1.0,WindDirectionY=1.0;
+constexpr double Pi=3.14159265358979323846;
+
+inline double BandRamp(double low,double high,double wavelength) {
+ const double t=(std::max)(0.0,(std::min)(1.0,(wavelength-low)/(high-low)));
+ return t*t*(3.0-2.0*t);
+}
+// Radial POWER, not amplitude. Wavelength is in world units.
+// The crossovers are 24..40 and 128..256 world units. Long swell
+// fades out over 1024..1792, before the former hard 2000-unit cutoff. The powers
+// sum to one below that upper fade; multiplying h0 by sqrt(power) applies a power
+// fade before each band is normalized. Even radial weights preserve conjugate pairs.
+inline double BandPower(unsigned cascade,double wavelength) {
+ if(cascade>=Cascades || !(wavelength>0) || !std::isfinite(wavelength)) return 0.0;
+ const double longer=BandRamp(128.0,256.0,wavelength);
+ const double shorter=1.0-BandRamp(24.0,40.0,wavelength);
+ if(cascade==0) return longer*(1.0-BandRamp(1024.0,1792.0,wavelength));
+ if(cascade==1) return 1.0-longer-shorter;
+ return shorter;
+}
+
+// Mulberry32's explicit unsigned arithmetic is reproducible, independent of gameplay randomness.
+inline float Random(uint32_t &state) {
+ uint32_t t=(state+=0x6d2b79f5u);
+ t=(t^(t>>15))*(t|1u);t^=t+(t^(t>>7))*(t|61u);
+ return float(double(t^(t>>14))/4294967296.0);
+}
+inline std::vector<float> InitialSpectrum() {
+ const unsigned n=Resolution,texels=n*n;
+ std::vector<float> noise(texels*2),result(texels*Cascades*4);
+ uint32_t seed=0;
+ for(float &v:noise) v=Random(seed);
+ const double direction2=WindDirectionX*WindDirectionX+WindDirectionY*WindDirectionY;
+ double energy[Cascades]={};
+ // A centred even-sized grid has no distinct +Nyquist partner. Omit both
+ // Nyquist axes so odd derivatives and the packed real fields stay Hermitian.
+ for(unsigned y=1;y<n;++y) for(unsigned x=1;x<n;++x) {
+ const unsigned at=y*n+x,opposite=((n-y)%n)*n+(n-x)%n;
+ const double theta=2*Pi*noise[at*2],thetaOther=2*Pi*noise[opposite*2];
+ // A random zero must not create log(0), even for a future seed/configuration.
+ const double radius=std::sqrt(-2*std::log((std::max)(double(noise[at*2+1]),1.0/4294967296.0)));
+ const double radiusOther=std::sqrt(-2*std::log((std::max)(double(noise[opposite*2+1]),1.0/4294967296.0)));
+ for(unsigned c=0;c<Cascades;++c) {
+ const double kx=2*Pi*(int(x)-int(n/2))/Sizes[c],ky=2*Pi*(int(y)-int(n/2))/Sizes[c];
+ const double k2=kx*kx+ky*ky;
+ if(k2==0) continue; // zero DC, without evaluating a singular Phillips density
+ const double power=BandPower(c,2*Pi*WorldScale/std::sqrt(k2));
+ if(power==0) continue;
+ const double length=WindLengths[c];
+ const double phillips=power*std::exp(-1/(k2*length*length))/(k2*k2);
+ const double alignment=(kx*WindDirectionX+ky*WindDirectionY)/std::sqrt(k2*direction2);
+ const double positive=std::sqrt(phillips*std::pow((std::max)(0.0,alignment),DirectionPowers[c]));
+ const double negative=std::sqrt(phillips*std::pow((std::max)(0.0,-alignment),DirectionPowers[c]));
+ float *h=&result[(c*texels+at)*4];
+ h[0]=float(radius*std::cos(theta)*positive);h[1]=float(radius*std::sin(theta)*positive);
+ h[2]=float(radiusOther*std::cos(thetaOther)*negative);h[3]=float(-radiusOther*std::sin(thetaOther)*negative);
+ for(unsigned j=0;j<4;++j) energy[c]+=double(h[j])*h[j];
+ }
+ }
+ // At each k only one propagation half-plane is populated, so Parseval height
+ // variance is exactly this sum of packed coefficient powers at every time.
+ // One positive factor per cascade preserves phase and conjugate pairing.
+ // This also normalizes angular power on the actual finite seeded lattice:
+ // no Strengths, Phillips prefactor or extra angular gain survives this step.
+ for(unsigned c=0;c<Cascades;++c) {
+ const double gain=energy[c]>0?HeightRms[c]/(WorldScale*std::sqrt(energy[c])):0;
+ for(unsigned i=0;i<texels*4;++i) {
+ float &value=result[c*texels*4+i];value=float(double(value)*gain);
+ }
+ }
+ return result;
+}
+inline std::vector<float> Butterfly() {
+ std::vector<float> result(Resolution*Phases*4);
+ auto reverse=[](unsigned v) { unsigned r=0;for(unsigned j=0;j<Phases;++j) { r=(r<<1)|(v&1);v>>=1; }return r; };
+ for(unsigned phase=0;phase<Phases;++phase) for(unsigned i=0;i<Resolution;++i) {
+ const unsigned span=1u<<phase,base=i%(span*2)<span?i:i-span;
+ const double angle=2*Pi*(i*(Resolution>>(phase+1)))/Resolution;
+ float *p=&result[(i*Phases+phase)*4];
+ p[0]=float(std::cos(angle));p[1]=float(std::sin(angle));
+ p[2]=float(phase?base:reverse(base));p[3]=float(phase?base+span:reverse(base+span));
+ }
+ return result;
+}
+inline const char *VertexHlsl() {
+ return "float4 main(uint id : SV_VertexID) : SV_Position { return float4(id==1?3.0:-1.0,id==2?3.0:-1.0,0,1); }\n";
+}
+inline std::string Resources(unsigned count) {
+ std::string source;
+ for(unsigned i=0;i<count;++i) source+="Texture2D<float4> T"+std::to_string(i)+" : register(t"+std::to_string(i)+", space2);\nSamplerState S"+std::to_string(i)+" : register(s"+std::to_string(i)+", space2);\n";
+ source+="cbuffer FftParameters : register(b0, space3) { float4 Parameters; float4 Sizes; };\n";
+ source+="struct Result {\n";
+ for(unsigned i=0;i<Maps;++i) source+="float4 v"+std::to_string(i)+" : SV_Target"+std::to_string(i)+";\n";
+ source+="};\n";
+ return source;
+}
+inline std::string SpectrumHlsl() {
+ std::string source=Resources(3);
+ source+=R"HLSL(
+float2 cmul(float2 a,float2 b) { return float2(a.x*b.x-a.y*b.y,a.x*b.y+a.y*b.x); }
+void spectrum(float4 initial,int2 pixel,float size,out float4 a,out float4 b) {
+ float2 k=6.283185307179586*(float2(pixel)-Parameters.xx*0.5)/size;
+ float lengthK=length(k);
+ a=0;b=0;
+ if(lengthK<=0.000001) return;
+ float phase=sqrt(9.81*lengthK)*Parameters.y;
+ float2 e=float2(cos(phase),sin(phase));
+ float2 h=cmul(initial.xy,e)+cmul(initial.zw,e*float2(1,-1));
+ float2 sx=0,sz=0,dx=0,dz=0,dxx=0,dxz=0,dzz=0;
+ // The centered Nyquist row/column cannot carry odd derivatives of a real periodic field.
+ if(pixel.x!=0) { sx=cmul(float2(0,k.x),h);dx=cmul(float2(0,-k.x/lengthK),h);dxx=h*k.x*k.x/lengthK; }
+ if(pixel.y!=0) { sz=cmul(float2(0,k.y),h);dz=cmul(float2(0,-k.y/lengthK),h);dzz=h*k.y*k.y/lengthK;
+ if(pixel.x!=0) dxz=h*k.x*k.y/lengthK; }
+ a=float4(dx+cmul(float2(0,1),h),dz+cmul(float2(0,1),dxz));
+ b=float4(sx+cmul(float2(0,1),sz),dxx+cmul(float2(0,1),dzz));
+}
+Result main(float4 position:SV_Position) {
+ int2 pixel=int2(position.xy);float2 uv=(float2(pixel)+0.5)/Parameters.x;Result result;
+ spectrum(T0.SampleLevel(S0,uv,0),pixel,Sizes.x,result.v0,result.v1);
+ spectrum(T1.SampleLevel(S1,uv,0),pixel,Sizes.y,result.v2,result.v3);
+ spectrum(T2.SampleLevel(S2,uv,0),pixel,Sizes.z,result.v4,result.v5);
+ return result;
+}
+)HLSL";
+ return source;
+}
+inline std::string ButterflyHlsl() {
+ std::string source=Resources(7);
+ source+=R"HLSL(
+float4 butterfly(float4 a,float4 b,float2 w) {
+ return 0.5*(a+float4(b.x*w.x-b.y*w.y,b.x*w.y+b.y*w.x,b.z*w.x-b.w*w.y,b.z*w.y+b.w*w.x));
+}
+Result main(float4 position:SV_Position) {
+ int2 pixel=int2(position.xy);bool vertical=Parameters.w>0.5;
+ float4 entry=T6.SampleLevel(S6,float2((Parameters.z+0.5)/8.0,((vertical?pixel.y:pixel.x)+0.5)/Parameters.x),0);
+ float2 a=(vertical?float2(pixel.x,entry.z):float2(entry.z,pixel.y))+0.5;
+ float2 b=(vertical?float2(pixel.x,entry.w):float2(entry.w,pixel.y))+0.5;
+ a/=Parameters.x;b/=Parameters.x;Result result;
+)HLSL";
+ for(unsigned i=0;i<Maps;++i) {const std::string s=std::to_string(i);source+="result.v"+s+"=butterfly(T"+s+".SampleLevel(S"+s+",a,0),T"+s+".SampleLevel(S"+s+",b,0),entry.xy);\n";}
+ return source+"return result; }\n";
+}
+inline std::string PostHlsl() {
+ std::string source=Resources(6);
+ source+="Result main(float4 position:SV_Position) { int2 pixel=int2(position.xy);float sign=((pixel.x+pixel.y)&1)?-1.0:1.0;float scale=sign*Parameters.x*Parameters.x;float2 uv=(float2(pixel)+0.5)/Parameters.x;Result result;\n";
+ for(unsigned i=0;i<Maps;++i) {const std::string s=std::to_string(i);source+="result.v"+s+"=T"+s+".SampleLevel(S"+s+",uv,0)*scale;\n";}
+ return source+"return result; }\n";
+}
+}
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterFoamEnvironment.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterFoamEnvironment.h
new file mode 100644
index 000000000..53feba950
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterFoamEnvironment.h
@@ -0,0 +1,171 @@
+/* Diffuse illumination of vessel foam by the existing procedural ocean sky. */
+#pragma once
+#include <array>
+#include <cmath>
+#include <cstdio>
+#include <string>
+#include <utility>
+#include <vector>
+
+namespace WaterFoamEnvironment {
+constexpr unsigned SampleCount=65536;
+constexpr unsigned BinCount=48;
+struct Vector { double x,y,z; };
+struct RGB { double r,g,b; };
+// Each row is integral(L_channel(w) * w / pi) over one angular bin.
+struct Moment { double rgb[3][3]; };
+typedef std::array<Moment,BinCount> Table;
+
+inline double Dot(Vector a,Vector b) {return a.x*b.x+a.y*b.y+a.z*b.z;}
+inline float Saturate(float x) {return x<0?0:(x>1?1:x);}
+inline float Frac(float x) {return x-std::floor(x);}
+inline float Smooth(float a,float b,float x) {x=Saturate((x-a)/(b-a));return x*x*(3-2*x);}
+inline float Lerp(float a,float b,float t) {return a+(b-a)*t;}
+inline float Hash(float x,float y) {
+ float qx=Frac(x*0.1031f),qy=Frac(y*0.1031f),qz=qx;
+ const float d=qx*(qy+33.33f)+qy*(qz+33.33f)+qz*(qx+33.33f);
+ qx+=d;qy+=d;qz+=d;
+ return Frac((qx+qy)*qz);
+}
+inline float Noise(float x,float y) {
+ const float ix=std::floor(x),iy=std::floor(y);
+ x-=ix;y-=iy;x=x*x*(3-2*x);y=y*y*(3-2*y);
+ return Lerp(Lerp(Hash(ix,iy),Hash(ix+1,iy),x),Lerp(Hash(ix,iy+1),Hash(ix+1,iy+1),x),y);
+}
+inline RGB CanonicalSky(Vector direction) {
+ // Float arithmetic mirrors oceanSky's shader operations. Its sun-relative frame is
+ // fixed: +X along the sun's azimuth, +Y toward the cloud bank. Exclude only the
+ // explicit solar halo: the authored direct light already supplies that source.
+ const float x=float(direction.x),y=float(direction.y),z=float(direction.z);
+ const float horizon=std::pow(1-Saturate(z),4.0f),denominator=0.45f+std::fabs(z);
+ const float px=x/denominator,py=y/denominator;
+ float cloud=Noise(px*2.7f+7.8f,py*2.7f+2.3f)*0.7f+Noise(px*6.1f+0.4f,py*6.1f+13.7f)*0.3f;
+ const float inverseCloudLength=1/std::sqrt(1+0.85f*0.85f);
+ const float bank=std::pow(Saturate((y+z*0.85f)*inverseCloudLength),48.0f);
+ cloud=Smooth(0.46f,0.73f,cloud)*(0.04f+1.5f*bank);
+ const float horizonBlend=Smooth(-0.12f,0.18f,z);
+ return {Lerp(0.001f,Lerp(0.016f,0.023f,horizon)+cloud*1.85f,horizonBlend),
+ Lerp(0.005f,Lerp(0.055f,0.070f,horizon)+cloud*1.96f,horizonBlend),
+ Lerp(0.010f,Lerp(0.110f,0.130f,horizon)+cloud*2.04f,horizonBlend)};
+}
+
+namespace Detail {
+struct Sample {Vector direction;RGB radiance;double azimuth;};
+struct Group {std::vector<unsigned> indices;Moment moment={};double loss=0;};
+inline void Summarize(Group &group,const std::vector<Sample> &samples) {
+ group.moment=Moment{};
+ double luminance=0;Vector moment={0,0,0};
+ for(unsigned index:group.indices) {
+ const Sample &sample=samples[index];
+ const double colour[3]={sample.radiance.r,sample.radiance.g,sample.radiance.b};
+ const double direction[3]={sample.direction.x,sample.direction.y,sample.direction.z};
+ for(unsigned channel=0;channel<3;++channel)for(unsigned axis=0;axis<3;++axis)
+ group.moment.rgb[channel][axis]+=colour[channel]*direction[axis];
+ const double value=colour[0]*0.2126+colour[1]*0.7152+colour[2]*0.0722;
+ luminance+=value;moment.x+=value*direction[0];moment.y+=value*direction[1];moment.z+=value*direction[2];
+ }
+ // Bright angular structure gets finer bins. This bound is used only for allocation;
+ // every RGB channel retains its own direction moment for the final integral.
+ group.loss=luminance-std::sqrt(Dot(moment,moment));
+}
+inline bool Split(const Group &group,const std::vector<Sample> &samples,bool azimuth,Group &a,Group &b) {
+ double low=1e30,high=-1e30;
+ for(unsigned index:group.indices) {
+ const double value=azimuth?samples[index].azimuth:samples[index].direction.z;
+ if(value<low)low=value;if(value>high)high=value;
+ }
+ const double middle=(low+high)*0.5;
+ a.indices.reserve(group.indices.size()/2+1);b.indices.reserve(group.indices.size()/2+1);
+ for(unsigned index:group.indices)
+ ((azimuth?samples[index].azimuth:samples[index].direction.z)<middle?a:b).indices.push_back(index);
+ if(a.indices.empty() || b.indices.empty())return false;
+ Summarize(a,samples);Summarize(b,samples);return true;
+}
+}
+
+template<class Sampler> inline Table Build(Sampler sampleRadiance) {
+ // Bounded startup work only. These temporary samples/groups are discarded after
+ // generating the immutable shader constants. Sampler must return finite nonnegative
+ // radiance; constant/HDR test environments use this same integration path.
+ const double pi=3.14159265358979323846,golden=pi*(3-std::sqrt(5.0));
+ std::vector<Detail::Sample> samples;samples.reserve(SampleCount);
+ std::vector<Detail::Group> groups(8);groups.reserve(BinCount);
+ for(unsigned i=0;i<SampleCount;++i) {
+ const double z=1-2*(i+0.5)/SampleCount,r=std::sqrt(1-z*z),phase=i*golden;
+ const Vector direction={r*std::cos(phase),r*std::sin(phase),z};
+ double azimuth=std::atan2(direction.y,direction.x);if(azimuth<0)azimuth+=2*pi;
+ samples.push_back({direction,sampleRadiance(direction),azimuth});
+ unsigned quadrant=unsigned(azimuth*2/pi);if(quadrant>3)quadrant=3;
+ groups[(z>=0?4:0)+quadrant].indices.push_back(i);
+ }
+ for(Detail::Group &group:groups)Detail::Summarize(group,samples);
+ while(groups.size()<BinCount) {
+ unsigned selected=0;bool found=false;
+ for(unsigned i=0;i<groups.size();++i)if(groups[i].indices.size()>1 && (!found || groups[i].loss>groups[selected].loss)) {
+ selected=i;found=true;
+ }
+ if(!found)break;
+ Detail::Group phiA,phiB,zA,zB;
+ const bool phi=Detail::Split(groups[selected],samples,true,phiA,phiB),
+ z=Detail::Split(groups[selected],samples,false,zA,zB);
+ if(!phi && !z)break;
+ if(phi && (!z || phiA.loss+phiB.loss<zA.loss+zB.loss)) {
+ groups[selected]=std::move(phiA);groups.push_back(std::move(phiB));
+ } else {groups[selected]=std::move(zA);groups.push_back(std::move(zB));}
+ }
+ Table result={};
+ for(unsigned i=0;i<groups.size();++i)for(unsigned channel=0;channel<3;++channel)for(unsigned axis=0;axis<3;++axis)
+ result[i].rgb[channel][axis]=groups[i].moment.rgb[channel][axis]*(4.0/SampleCount);
+ return result;
+}
+inline const Table &CachedTable() {
+ static const Table table=Build([](Vector direction){return CanonicalSky(direction);});
+ return table;
+}
+inline RGB Evaluate(const Table &table,Vector normal) {
+ // normal is unit length. For each channel, max(n . integral(L*w),0) is no
+ // greater than integral(L*max(n.w,0)). Thus these bins remain positive and
+ // conservatively lose energy at partially visible bins, including inverted normals.
+ // Finite-bin underestimation is intentional; do not renormalize or tint it away.
+ double value[3]={0,0,0};
+ for(const Moment &moment:table)for(unsigned channel=0;channel<3;++channel) {
+ const double *m=moment.rgb[channel],cosine=normal.x*m[0]+normal.y*m[1]+normal.z*m[2];
+ if(cosine>0)value[channel]+=cosine;
+ }
+ return {value[0],value[1],value[2]};
+}
+inline RGB Evaluate(Vector normal,Vector light,double daylight) {
+ const double x=light.x+0.00001,y=light.y,inverseLength=1/std::sqrt(x*x+y*y);
+ const Vector canonical={normal.x*x*inverseLength+normal.y*y*inverseLength,
+ -normal.x*y*inverseLength+normal.y*x*inverseLength,normal.z};
+ RGB result=Evaluate(CachedTable(),canonical);
+ const double scale=0.06+0.94*(daylight<0?0:(daylight>1?1:daylight));
+ result.r*=scale;result.g*=scale;result.b*=scale;return result;
+}
+inline const std::string &HlslSource() {
+ static const std::string source=[]() {
+ std::string result="\n// Positive per-channel moments of the canonical sky, E/pi; solar halo excluded.\n"
+ "static const float3 waterFoamSkyMoments[144]={\n";
+ char line[160];const Table &table=CachedTable();
+ for(unsigned i=0;i<BinCount;++i)for(unsigned channel=0;channel<3;++channel) {
+ const double *m=table[i].rgb[channel];
+ std::snprintf(line,sizeof(line),"float3(%.9g,%.9g,%.9g)%s\n",m[0],m[1],m[2],i+1==BinCount && channel==2?"":",");
+ result+=line;
+ }
+ result+=R"HLSL(};
+float3 waterFoamSkyIrradiance(float3 normal,float3 light,float daylight) {
+ float2 axis=normalize(light.xy+float2(0.00001,0));
+ float3 n=float3(dot(normal.xy,axis),dot(normal.xy,float2(-axis.y,axis.x)),normal.z);
+ float3 value=0;
+ [unroll] for(int i=0;i<48;++i) {
+ value+=max(float3(dot(n,waterFoamSkyMoments[i*3]),
+ dot(n,waterFoamSkyMoments[i*3+1]),dot(n,waterFoamSkyMoments[i*3+2])),float3(0,0,0));
+ }
+ return value*(0.06+0.94*saturate(daylight));
+}
+)HLSL";
+ return result;
+ }();
+ return source;
+}
+}
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterFoamHistory.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterFoamHistory.h
new file mode 100644
index 000000000..ccbd3e706
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterFoamHistory.h
@@ -0,0 +1,297 @@
+/* Render-only, world-space vessel foam. No gameplay state or water height is modified. */
+#pragma once
+#include "Platform/WaterHullModel.h"
+#include <algorithm>
+#include <cmath>
+#include <cstdint>
+#include <vector>
+
+namespace WaterFoamHistory {
+constexpr unsigned MaxSegments=1024,MaxEmitters=64,MaxAtlasSide=512;
+constexpr double DirectionWidthScale=32.0; // maximum initial lane width is30 world units
+constexpr double SampleInterval=0.25,Lifetime=24.0,MaxObservationGap=0.5;
+struct Point { double x=0,y=0; };
+struct Mapping {
+ double originX=0,originY=0,widthWorld=0,heightWorld=0;
+ unsigned widthPixels=0,heightPixels=0;
+};
+struct Sample {
+ Point center,axis,lanes[3]; // stern, port and starboard waterline
+ double width[3]={},rate[3]={};
+ double level=0,time=0,halfLength=0,halfWidth=0;
+};
+struct Segment { Sample begin,end; std::uint64_t id=0; };
+inline double Clamp(double x,double a,double b) { return (std::max)(a,(std::min)(b,x)); }
+inline double Smooth(double low,double high,double x) { const double t=Clamp((x-low)/(high-low),0,1);return t*t*(3-2*t); }
+inline bool Finite(Point p) { return std::isfinite(p.x)&&std::isfinite(p.y); }
+inline Point Mix(Point a,Point b,double t) { return {a.x+(b.x-a.x)*t,a.y+(b.y-a.y)*t}; }
+inline double Length(Point p) { return std::sqrt(p.x*p.x+p.y*p.y); }
+inline double Distance(Point a,Point b) { return Length({a.x-b.x,a.y-b.y}); }
+struct KernelIntegral { double mass=0,mean=0.5; };
+// Average compact radial quartic over a uniformly deposited line, plus its weighted
+// deposition coordinate. Multiplying mass by duration makes adjacent time sections
+// additive: each shared endpoint contributes only its own half of the radial support.
+inline KernelIntegral IntegrateKernel(double along,double perpendicularSquared,double length,double radius) {
+ if(!std::isfinite(along)||!std::isfinite(perpendicularSquared)||!std::isfinite(length)||
+ !std::isfinite(radius)||perpendicularSquared<0||length<0||radius<=0) return {};
+ const double q=1-perpendicularSquared/(radius*radius);
+ if(q<=0) return {};
+ if(length<=1.0e-10) {
+ const double kernel=q-along*along/(radius*radius);
+ return {kernel>0?kernel*kernel:0,0.5};
+ }
+ const double support=radius*std::sqrt(q);
+ const double low=(std::max)(-support,-along)/radius;
+ const double high=(std::min)(support,length-along)/radius;
+ if(low>=high) return {};
+ const double mid=(low+high)*0.5,half=(high-low)*0.5,m2=mid*mid,h2=half*half;
+ // Integrate around the interval midpoint. This avoids subtracting nearly equal
+ // antiderivatives for very short live tails or support intervals near an endpoint.
+ const double average=(std::max)(0.0,(q-m2)*(q-m2)+(-2*q+6*m2)*h2/3+h2*h2/5);
+ if(average<=0) return {};
+ const double first=q*q*mid-2*q*(mid*m2+mid*h2)
+ +mid*m2*m2+(10.0/3)*mid*m2*h2+mid*h2*h2;
+ return {Clamp((high-low)*radius/length*average,0,1),
+ Clamp((along+radius*first/average)/length,0,1)};
+}
+inline Sample Interpolate(const Sample &a,const Sample &b,double time) {
+ const double t=Clamp((time-a.time)/(b.time-a.time),0,1);Sample s=a;
+ s.center=Mix(a.center,b.center,t);s.axis=Mix(a.axis,b.axis,t);s.time=time;
+ for(unsigned i=0;i<3;++i) { s.lanes[i]=Mix(a.lanes[i],b.lanes[i],t);
+ s.width[i]=a.width[i]+(b.width[i]-a.width[i])*t;s.rate[i]=a.rate[i]+(b.rate[i]-a.rate[i])*t; }
+ return s;
+}
+inline bool MakeSample(const WaterHullModel::Hull &h,double time,Sample &s) {
+ if(!std::isfinite(time)) return false;
+ for(unsigned i=0;i<WaterHullModel::RegistersPerHull;++i)
+ for(unsigned j=0;j<4;++j) if(!std::isfinite(h.data[i][j])) return false;
+ if(h.data[0][3]<3 || h.data[0][3]>12 || h.data[1][2]<=0 || h.data[1][3]<=0 ||
+ h.data[1][2]>4096 || h.data[1][3]>4096) return false;
+ s=Sample();s.center={h.data[0][0],h.data[0][1]};s.axis={h.data[1][0],h.data[1][1]};
+ const double axisLength=Length(s.axis);if(axisLength<0.5 || axisLength>1.5) return false;
+ s.axis.x/=axisLength;s.axis.y/=axisLength;s.level=h.data[0][2];s.time=time;
+ s.halfLength=h.data[1][2];s.halfWidth=h.data[1][3];
+ const Point velocity={h.data[2][0],h.data[2][1]};const double speed=Length(velocity);
+ const double forward=Smooth(-0.25,0.25,(velocity.x*s.axis.x+velocity.y*s.axis.y)/(std::max)(speed,0.001));
+ const Point stern=Mix({h.data[3][2],h.data[3][3]},{h.data[3][0],h.data[3][1]},forward);
+ auto world=[&](Point p) { return Point{s.center.x+s.axis.x*p.x-s.axis.y*p.y,s.center.y+s.axis.y*p.x+s.axis.x*p.y}; };
+ // Intersect the actual convex contour with its central cross-section. This keeps side
+ // emission on the sliced waterline instead of the gameplay collision box.
+ const WaterHullModel::Polygon polygon=WaterHullModel::Unpack(h);
+ double low=1.0e30,high=-1.0e30;
+ for(unsigned i=0;i<polygon.count;++i) {
+ const auto a=polygon.points[i],b=polygon.points[(i+1)%polygon.count];
+ if(a.x==0) {low=(std::min)(low,double(a.y));high=(std::max)(high,double(a.y));}
+ if((a.x<0 && b.x>0)||(a.x>0 && b.x<0)) {
+ const double y=a.y+(b.y-a.y)*(-double(a.x)/(double(b.x)-a.x));
+ low=(std::min)(low,y);high=(std::max)(high,y);
+ }
+ }
+ if(low>high) return false;
+ // The extremal aft vertex can jump between transom corners as the hull pitches.
+ // Retained propulsion wash follows the transverse centre of the actual midship
+ // section, projected to the same velocity-selected aft X; contact foam still uses
+ // the exact contour. Keep the recorded path, rates and aging independent of that corner.
+ s.lanes[0]=world({stern.x,(low+high)*0.5});
+ s.lanes[1]=world({0,low});s.lanes[2]=world({0,high});
+ // Propeller churn spreads beyond a narrow hull. The sublinear term gives small
+ // boats a readable stern trail without scaling large-ship support without bound.
+ s.width[0]=Clamp(s.halfWidth*0.30+std::sqrt(s.halfWidth)*0.8,2.5,30.0);
+ s.width[1]=s.width[2]=Clamp(s.halfWidth*0.055,0.65,3.0);
+ const double response=2.0*Smooth(0.3,12.0,speed)*(0.8+0.25*std::sqrt((std::min)(speed,250.0)));
+ // The radial support area grows with width squared, while a transom source
+ // grows approximately with its span. Remove one width factor from stern dose
+ // above the six-world small-boat footprint; its existing response stays exact.
+ // Width/spreading and side wash retain their own independent contracts.
+ s.rate[0]=response*(std::min)(1.0,6.0/s.width[0]);
+ s.rate[1]=s.rate[2]=response*0.22;
+ return true;
+}
+
+class History {
+ struct Emitter { std::uint64_t id=0,seen=0;Sample observed,anchor,moving;double next=0; };
+ std::vector<Emitter> emitters;
+ std::vector<Segment> segments;
+ double now=0;std::uint64_t serial=0;bool initialized=false;
+ void Anchor(Emitter &e,const Sample &s) {
+ e.observed=e.anchor=e.moving=s;e.next=(std::floor(s.time/SampleInterval)+1)*SampleInterval;e.seen=serial;
+ }
+ static bool Active(const Sample &a,const Sample &b) {
+ if(b.time<=a.time || Distance(a.center,b.center)<=1.0e-6) return false;
+ for(unsigned i=0;i<3;++i) if(a.rate[i]+b.rate[i]>1.0e-6) return true;
+ return false;
+ }
+ bool Record(const Sample &a,const Sample &b,std::uint64_t id) {
+ if(!Active(a,b) || now-b.time>=Lifetime) return false;
+ if(segments.size()==MaxSegments) segments.erase(segments.begin());
+ segments.push_back({a,b,id});return true;
+ }
+ void RememberTail(const Emitter &e) {Record(e.anchor,e.moving,e.id);}
+public:
+ void Clear() { emitters.clear();segments.clear();now=0;serial=0;initialized=false; }
+ double Time() const { return now; }
+ size_t SegmentCount() const { return segments.size(); }
+ size_t TrackedCount() const { return emitters.size(); }
+ const std::vector<Segment> &Segments() const { return segments; }
+ bool HasFoam() const {
+ if(!segments.empty()) return true;
+ for(const Emitter &e:emitters)
+ if(Active(e.anchor,e.moving) && now-(e.anchor.time+e.moving.time)*0.5<Lifetime) return true;
+ return false;
+ }
+ bool Advance(double time) {
+ if(!std::isfinite(time)) {Clear();return false;}
+ if(initialized && time<now) Clear();
+ if(initialized && time==now) return false;
+ initialized=true;now=time;++serial;
+ segments.erase(std::remove_if(segments.begin(),segments.end(),[&](const Segment &s){return now-s.end.time>=Lifetime;}),segments.end());
+ return true;
+ }
+ bool Observe(std::uint64_t id,const WaterHullModel::Hull &h,double time,bool visible=true,bool discontinuity=false,
+ const Point *trueMotionPosition=nullptr) {
+ if(!initialized || time>now) Advance(time);
+ auto found=std::find_if(emitters.begin(),emitters.end(),[&](const Emitter &e){return e.id==id;});
+ Sample sample;
+ if(!visible || !std::isfinite(time) || time!=now || !MakeSample(h,time,sample) ||
+ (trueMotionPosition && !Finite(*trueMotionPosition))) {
+ if(found!=emitters.end()) {RememberTail(*found);emitters.erase(found);}return false;
+ }
+ // A slab's geometric center can shift as a stationary vessel pitches/rolls. Keep
+ // the actual waterline lanes, but gate new deposition on displayed translation.
+ if(trueMotionPosition) sample.center=*trueMotionPosition;
+ if(found==emitters.end()) {
+ if(emitters.size()==MaxEmitters) {
+ auto oldest=std::min_element(emitters.begin(),emitters.end(),
+ [](const Emitter &a,const Emitter &b){return a.observed.time<b.observed.time;});
+ RememberTail(*oldest);emitters.erase(oldest);
+ }
+ emitters.push_back(Emitter());Emitter &e=emitters.back();e.id=id;Anchor(e,sample);return false;
+ }
+ Emitter &e=*found;
+ if(discontinuity || sample.level!=e.observed.level) {RememberTail(e);Anchor(e,sample);return false;}
+ const double dt=time-e.observed.time;
+ if(dt<=0) return false; // Duplicate scene/reflection draws and pause cannot emit twice.
+ const double travel=Distance(sample.center,e.observed.center);
+ const double declaredSpeed=Length({h.data[2][0],h.data[2][1]});
+ // Explicit motion-reset flags are authoritative. The generous secondary guard allows
+ // accelerated native simulation to move farther per wall-clock tick without inventing
+ // a cross-map connection after a spawn/teleport or an unseen interval.
+ const double reach=(std::max)((std::max)(64.0,2*(sample.halfLength+sample.halfWidth)),
+ 8*(std::max)(250.0,declaredSpeed)*dt);
+ const double heading=sample.axis.x*e.observed.axis.x+sample.axis.y*e.observed.axis.y;
+ const double sternTravel=Distance(sample.lanes[0],e.observed.lanes[0]);
+ const double turnAllowance=2*sample.halfLength*std::sqrt((std::max)(0.0,2*(1-heading)));
+ if(dt>MaxObservationGap || e.seen+1<serial || travel>reach || heading<0 ||
+ sternTravel>travel+turnAllowance+(std::max)(16.0,sample.halfWidth*2)) {RememberTail(e);Anchor(e,sample);return false;}
+ if(travel>1.0e-6) e.moving=sample;
+ bool emitted=false;
+ while(e.next<=time+1.0e-9) {
+ const Sample next=Interpolate(e.observed,sample,e.next);
+ // Judge motion over the fixed deposition interval, not a render-to-render delta.
+ // Uninterpolated30Hz models are stationary on most120Hz render samples, while a
+ // genuinely stopped vessel has no travel over the complete section even if its
+ // filtered physics velocity has not decayed yet.
+ // Do not extend dose duration after motion stops, including the final incomplete
+ // section. Its already-visible tail is committed unchanged at the next boundary.
+ const Sample &end=e.moving.time<next.time?e.moving:next;
+ emitted=Record(e.anchor,end,id)||emitted;
+ e.anchor=next;e.next+=SampleInterval;
+ }
+ e.observed=sample;e.seen=serial;return emitted;
+ }
+ // RGBA is packed as ARGB: R=opacity, G=opacity*normalized mean age,
+ // B=opacity*fresh churn, A=0 reserved for a distinct shoreline source.
+ // Optional second tile retains the *deposited* lane orientation, not a vessel's current
+ // heading. RG hold opacity-weighted axial moments (cos2theta/sin2theta biased to0..1),
+ // B the weighted initial lane width/32, A the same opacity as the first tile's R.
+ // Axial moments combine opposite travel directions and lose confidence at crossings.
+ bool BuildAtlas(const Mapping &map,float level,std::vector<std::uint32_t> &argb,
+ std::vector<std::uint32_t> *direction=nullptr) const {
+ argb.clear();
+ if(direction) direction->clear();
+ if(!std::isfinite(map.originX)||!std::isfinite(map.originY)||!std::isfinite(map.widthWorld)||
+ !std::isfinite(map.heightWorld)||map.widthWorld<=0||map.heightWorld<=0||!std::isfinite(level)||
+ map.widthPixels<1||map.heightPixels<1||map.widthPixels>MaxAtlasSide||map.heightPixels>MaxAtlasSide) return false;
+ struct Cell {float density=0,age=0,fresh=0;};
+ struct DirectionCell {float x=0,y=0,width=0;};
+ const size_t count=size_t(map.widthPixels)*map.heightPixels;std::vector<Cell> cells(count);
+ std::vector<DirectionCell> directions(direction?count:0);
+ if(direction) direction->resize(count);
+ argb.resize(count);const double pixelX=map.widthWorld/map.widthPixels,pixelY=map.heightWorld/map.heightPixels;
+ auto rasterize=[&](const Segment &segment) {
+ if(segment.begin.level!=level || now-segment.end.time>=Lifetime) return;
+ const double duration=segment.end.time-segment.begin.time;
+ for(unsigned lane=0;lane<3;++lane) {
+ if(segment.begin.rate[lane]+segment.end.rate[lane]<=0) continue;
+ const Point a=segment.begin.lanes[lane],b=segment.end.lanes[lane],line={b.x-a.x,b.y-a.y};
+ const double length=Length(line);
+ const Point axis=length>1.0e-10?Point{line.x/length,line.y/length}:Point{1,0};
+ double ages[2],radii[2],amplitudes[2],freshness[2];
+ for(unsigned end=0;end<2;++end) {
+ const Sample &sample=end?segment.end:segment.begin;
+ const double age=Clamp(now-sample.time,0,Lifetime),initial=sample.width[lane];
+ const double spread=(lane==0?0.28:0.10)+std::sqrt(initial)*(lane==0?0.12:0.06);
+ const double aged=initial+spread*age;
+ ages[end]=age/Lifetime;radii[end]=2.5*aged;
+ amplitudes[end]=sample.rate[lane]*std::exp(-age/(lane==0?7.0:3.5))
+ *(1-Smooth(20,Lifetime,age))*initial*initial/(aged*aged);
+ freshness[end]=std::exp(-age/1.5);
+ }
+ const double radius=(std::max)(radii[0],radii[1]);
+ const int left=int(Clamp(std::floor(((std::min)(a.x,b.x)-radius-map.originX)/pixelX),0,map.widthPixels));
+ const int right=int(Clamp(std::ceil(((std::max)(a.x,b.x)+radius-map.originX)/pixelX),0,map.widthPixels));
+ const int bottom=int(Clamp(std::floor(((std::min)(a.y,b.y)-radius-map.originY)/pixelY),0,map.heightPixels));
+ const int top=int(Clamp(std::ceil(((std::max)(a.y,b.y)+radius-map.originY)/pixelY),0,map.heightPixels));
+ for(int y=bottom;y<top;++y) for(int x=left;x<right;++x) {
+ const Point p={map.originX+(x+0.5)*pixelX,map.originY+(y+0.5)*pixelY};
+ const double dx=p.x-a.x,dy=p.y-a.y,along=dx*axis.x+dy*axis.y,cross=dx*axis.y-dy*axis.x;
+ const double nearest=length>1.0e-10?Clamp(along/length,0,1):0.5;
+ const KernelIntegral kernel=IntegrateKernel(along,cross*cross,length,
+ radii[0]+(radii[1]-radii[0])*nearest);
+ if(kernel.mass<=0) continue;
+ // Endpoint decay/rates are interpolated at the kernel's mean deposition
+ // time. Age is continuous along a section; no per-pixel exponential is needed.
+ const double first=amplitudes[0]*(1-kernel.mean),last=amplitudes[1]*kernel.mean;
+ const double dose=duration*kernel.mass,density=dose*(first+last);
+ Cell &cell=cells[size_t(y)*map.widthPixels+x];
+ cell.density+=float(density);
+ cell.age+=float(dose*(first*ages[0]+last*ages[1]));
+ cell.fresh+=float(dose*(first*freshness[0]+last*freshness[1]));
+ if(direction) {
+ DirectionCell &d=directions[size_t(y)*map.widthPixels+x];
+ // A zero-length lane has no recorded path direction. Its density still
+ // contributes to the denominator, softly reducing directional confidence.
+ if(length>1.0e-6) {
+ d.x+=float(density*(axis.x*axis.x-axis.y*axis.y));
+ d.y+=float(density*(2*axis.x*axis.y));
+ }
+ d.width+=float(dose*(first*segment.begin.width[lane]+last*segment.end.width[lane]));
+ }
+ }
+ }
+ };
+ for(const Segment &segment:segments) rasterize(segment);
+ // Preview only the uncommitted time interval. This closes the newest stern gap even
+ // at high speed, without adding render-rate-dependent stamps or overlapping history.
+ // Unobserved tails remain fixed and age normally until removal/eviction commits them.
+ for(const Emitter &e:emitters)
+ if(Active(e.anchor,e.moving)) rasterize({e.anchor,e.moving,e.id});
+ for(size_t i=0;i<count;++i) {
+ const Cell &cell=cells[i];if(cell.density<=0) {argb[i]=0;continue;}
+ const double opacity=1-std::exp(-double(cell.density));
+ const unsigned r=unsigned(Clamp(opacity*255+0.5,0,255));
+ const unsigned g=unsigned(Clamp(opacity*cell.age/cell.density*255+0.5,0,255));
+ const unsigned b=unsigned(Clamp(opacity*cell.fresh/cell.density*255+0.5,0,255));
+ argb[i]=(r<<16)|(g<<8)|b;
+ if(direction) {
+ const DirectionCell &d=directions[i];
+ const unsigned dx=unsigned(Clamp(opacity*(1+Clamp(d.x/cell.density,-1,1))*127.5+0.5,0,255));
+ const unsigned dy=unsigned(Clamp(opacity*(1+Clamp(d.y/cell.density,-1,1))*127.5+0.5,0,255));
+ const unsigned width=unsigned(Clamp(opacity*d.width/cell.density/DirectionWidthScale*255+0.5,0,255));
+ (*direction)[i]=(r<<24)|(dx<<16)|(dy<<8)|width;
+ }
+ }
+ return true;
+ }
+};
+} // namespace WaterFoamHistory
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterFoamParticlePolicy.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterFoamParticlePolicy.h
new file mode 100644
index 000000000..b1f607141
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterFoamParticlePolicy.h
@@ -0,0 +1,43 @@
+#pragma once
+#include <cmath>
+
+// Only the shipped surface-wake effects are replaced. Matching an arbitrary wave texture or
+// every particle on a boat would also remove spray, weapons, smoke and mod-authored effects.
+namespace WaterFoamParticlePolicy {
+inline bool SameResource(const char *a,const char *b)
+{
+ if(!a || !b) return false;
+ while(*a && *b) {
+ const unsigned char ac=static_cast<unsigned char>(*a++),bc=static_cast<unsigned char>(*b++);
+ const unsigned char lowerA=ac>='A' && ac<='Z' ? ac+('a'-'A') : ac;
+ const unsigned char lowerB=bc>='A' && bc<='Z' ? bc+('a'-'A') : bc;
+ if(lowerA!=lowerB) return false;
+ }
+ return *a==*b;
+}
+inline bool KnownSurfaceFoam(const char *name,const char *texture)
+{
+ return (SameResource(name,"AmphibWave") && SameResource(texture,"EXWave01.tga")) ||
+ (SameResource(name,"AmphibWaveRest") && SameResource(texture,"EXShockWav.tga"));
+ // AirCarrierWaterRipples and BattleShipWaterRipples are the authored splash-ring
+ // layer. Keep them alongside modern hull foam, including on stationary ships.
+}
+inline bool Replace(const char *name,const char *texture,bool ordinaryGroundParticle,
+ bool attachedOwner,bool currentModernHull,bool mirrorPass)
+{
+ return ordinaryGroundParticle && attachedOwner && currentModernHull && !mirrorPass &&
+ KnownSurfaceFoam(name,texture);
+}
+// Surface foam belongs to the reflecting interface itself. Drawing it into that
+// interface's mirror duplicates it, even when the main view uses legacy particles.
+inline bool SameMirrorSurface(bool activeModernMirror,bool visibleWetOwner,float ownerLevel,float mirrorLevel)
+{
+ return activeModernMirror && visibleWetOwner && std::isfinite(ownerLevel) &&
+ std::isfinite(mirrorLevel) && std::abs(ownerLevel-mirrorLevel)<=0.1f;
+}
+inline bool ExcludeSelfReflection(const char *name,const char *texture,bool ordinaryGroundParticle,
+ bool attachedOwner,bool sameModernMirrorSurface)
+{
+ return ordinaryGroundParticle && attachedOwner && sameModernMirrorSurface && KnownSurfaceFoam(name,texture);
+}
+}
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterFoamShading.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterFoamShading.h
new file mode 100644
index 000000000..d56720330
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterFoamShading.h
@@ -0,0 +1,314 @@
+/* Surface shading of bounded, world-space foam history. No gameplay state is read here. */
+#pragma once
+namespace WaterFoamShading {
+inline const char *HistorySamplingSource() {
+ return R"HLSL(
+float4 waterFoamHistoryTile(float2 uv,uint tile) {
+ if(((uint)(FoamHistoryParameters.x+0.5)&4u)==0u)
+ return tile==0u?Texture14.SampleLevel(Sampler14,uv,0):float4(0,0,0,0);
+ uint width,height;Texture14.GetDimensions(width,height);
+ float2 inset=0.5/float2(max(width,1u),max(height/2u,1u));
+ // Clamp in the logical tile before packing. Sampler clamp alone would blend
+ // shore/history bytes with direction bytes at the middle of the physical texture.
+ float2 bounded=clamp(uv,inset,1.0-inset);
+ return Texture14.SampleLevel(Sampler14,float2(bounded.x,(bounded.y+tile)*0.5),0);
+}
+)HLSL";
+}
+// Separate from history/noise so the material and actual reflection filtering can be tested
+// with controlled incident radiance. Texture1/Sampler1 are the existing planar reflection.
+inline const char *MaterialSource() {
+ return R"HLSL(
+float3 waterFoamPlanarTap(float3 sky,float2 uv,float levelCoverage) {
+ // This material runs conditionally at foam pixels. Explicit mip zero avoids relying on
+ // implicit derivatives inside that branch, including its divergent shoreline boundary.
+ float3 rgb=Texture1.SampleLevel(Sampler1,saturate(uv),0.0).rgb;
+ float2 border=min(uv,1.0-uv);
+ float coverage=saturate(levelCoverage)*saturate(min(border.x,border.y)*30.0)
+ *saturate(max(rgb.r,max(rgb.g,rgb.b))*64.0);
+ // Decode each incident sample before filtering. Black clear/off-map taps contribute the
+ // rough sky instead of making a dark border around the reflected cliff or bridge.
+ return lerp(sky,pow(rgb,2.2),coverage);
+}
+float3 waterFoamPlanarReflection(float3 sky,float2 uv,float2 distortion,
+ float2 reflectionScale,float roughness,float levelCoverage) {
+ float2 radius=saturate(roughness)*0.008/max(reflectionScale,float2(0.001,0.001));
+ float2 centre=uv+distortion;
+ return waterFoamPlanarTap(sky,centre,levelCoverage)*0.4
+ +(waterFoamPlanarTap(sky,centre+float2(radius.x,0),levelCoverage)
+ +waterFoamPlanarTap(sky,centre-float2(radius.x,0),levelCoverage)
+ +waterFoamPlanarTap(sky,centre+float2(0,radius.y),levelCoverage)
+ +waterFoamPlanarTap(sky,centre-float2(0,radius.y),levelCoverage))*0.15;
+}
+float3 waterFoamRoughMaterial(float3 diffuse,float3 incidentReflection,
+ float rawFresnel,float viewCosine,float roughness) {
+ float mu=saturate(viewCosine),r=saturate(roughness);
+ float k=r*r*0.5;
+ float visibility=mu/max(mu*(1.0-k)+k,0.0001);
+ // The incident reflection has no Fresnel factor yet. Apply the existing interface
+ // Fresnel once, exchanging diffuse and reflected light rather than adding white energy.
+ return lerp(diffuse,incidentReflection,saturate(rawFresnel)*visibility);
+}
+float3 waterFoamLayer(float3 clearSurface,float3 crestDiffuse,float3 vesselMaterial,
+ float foam,float vesselFoam) {
+ // This is the existing coverage composition, shared with the regression fixture. With
+ // no vessel foam, both the clear surface and the generic crest material remain unchanged.
+ float vesselShare=saturate(vesselFoam/max(foam,0.0001));
+ float3 foamRadiance=lerp(crestDiffuse,vesselMaterial,vesselShare);
+ float foamCoverage=saturate(max(foam*0.88,vesselFoam));
+ return lerp(clearSurface,foamRadiance,foamCoverage);
+}
+// Attribute only the extra generic-material weight produced by the coastal source.
+// Both totals already include identical hull masks and crest/vessel max operations.
+float waterFoamCoastWeight(float foam,float withoutCoast,float vesselFoam) {
+ if(withoutCoast>=foam) return 0.0;
+ float generic=saturate(max(foam*0.88,vesselFoam))
+ *(1.0-saturate(vesselFoam/max(foam,0.0001)));
+ float other=saturate(max(withoutCoast*0.88,vesselFoam))
+ *(1.0-saturate(vesselFoam/max(withoutCoast,0.0001)));
+ return max(0.0,generic-other);
+}
+float3 waterFoamCoastLayer(float3 clearSurface,float3 crestDiffuse,float3 vesselMaterial,
+ float3 coastMaterial,float foam,float vesselFoam,float coastWeight) {
+ float3 original=waterFoamLayer(clearSurface,crestDiffuse,vesselMaterial,foam,vesselFoam);
+ if(coastWeight<=0.0) return original;
+ // Reassign an existing material weight: no change to total coverage, clear-water
+ // transmission or vessel share, and no extra white emission.
+ return original+coastWeight*(coastMaterial-crestDiffuse);
+}
+)HLSL";
+}
+inline const char *Source() {
+ return R"HLSL(
+// Terrain lighting is authored in the legacy display-colour space. Combine its actual
+// ambient and visible Lambertian sun first, then decode once for linear surface composition.
+float3 waterFoamIrradiance(float3 normal,float3 light,float3 ambientRGB,float3 sunRGB,float visibility) {
+ float3 illumination=ambientRGB+sunRGB*max(dot(normal,light),0.0)*visibility;
+ return pow(max(illumination,float3(0,0,0)),2.2);
+}
+// Additional authored global lights illuminate foam as they illuminate terrain. Only the main
+// sun has a scene shadow visibility term; sum the legacy display-space light once, then decode.
+float3 waterFoamIrradiance(float3 normal,float3 light,float3 ambientRGB,float3 sunRGB,float visibility,
+ float3 fillDirection1,float3 fillColour1,float3 fillDirection2,float3 fillColour2) {
+ float3 illumination=ambientRGB+sunRGB*max(dot(normal,light),0.0)*visibility;
+ illumination+=fillColour1*max(dot(normal,fillDirection1),0.0);
+ illumination+=fillColour2*max(dot(normal,fillDirection2),0.0);
+ return pow(max(illumination,float3(0,0,0)),2.2);
+}
+float3 waterFoamReplaceAmbient(float3 authoredIrradiance,float3 ambientRGB,float3 skyIrradiance,float offshore) {
+ // Retain the authored direct/fill/shadow increment exactly. Its ambient is replaced
+ // offshore, never added again; zero offshore is the exact legacy material endpoint.
+ if(offshore<=0.0) return authoredIrradiance;
+ float3 ambient=pow(max(ambientRGB,float3(0,0,0)),2.2);
+ return authoredIrradiance+(skyIrradiance-ambient)*saturate(offshore);
+}
+// Cubic bilinear value noise is concentrated around .5, not uniformly distributed. Its CDF
+// turns a threshold into area coverage rather than silently increasing the amount of foam.
+// Calibrated from 300000 independent uniform corner/coordinate samples, symmetrized about .5.
+float waterFoamNoiseRank(float value) {
+ static const float distribution[33]={
+ 0.0,0.0021533,0.0086700,0.0195933,0.0352533,0.0551733,0.0794133,0.1083450,
+ 0.1404633,0.1768117,0.2163183,0.2588083,0.3039783,0.3511833,0.3998867,0.4491767,
+ 0.5,0.5508233,0.6001133,0.6488167,0.6960217,0.7411917,0.7836817,0.8231883,
+ 0.8595367,0.8916550,0.9205867,0.9448267,0.9647467,0.9804067,0.9913300,0.9978467,1.0};
+ float scaled=saturate(value)*32.0;
+ int index=min((int)scaled,31);
+ return lerp(distribution[index],distribution[index+1],scaled-index);
+}
+// Integrate a bounded linear filter over uniform ranks. Near the two ends, adjusting the
+// cutoff by the inverse triangular area preserves coverage instead of adding an opacity floor.
+float waterFoamRankCoverage(float rank,float coverage,float width) {
+ coverage=saturate(coverage);
+ width=clamp(width,0.005,0.5);
+ float cutoff=coverage;
+ if(coverage<width) cutoff=-width+sqrt(4.0*width*coverage);
+ else if(coverage>1.0-width) cutoff=1.0+width-sqrt(4.0*width*(1.0-coverage));
+ return saturate((cutoff-rank+width)/(2.0*width));
+}
+// Filter each physical scale independently. A subpixel pore converges to its mean coverage;
+// it must not remain a bright binary speck while larger foam remnants are still resolved.
+float waterFoamCoverageBand(float2 q,float coverage,float footprint,float cellSize,float minimumWidth) {
+ coverage=saturate(coverage);
+ if(coverage<=0.0 || coverage>=1.0) return coverage;
+ float ratio=max(footprint,0.0)/cellSize;
+ float unresolved=smoothstep(0.5,1.5,ratio);
+ if(unresolved>=1.0) return coverage;
+ float rank=waterFoamNoiseRank(oceanNoise(q/cellSize));
+ float width=clamp(ratio*0.5,minimumWidth,0.5);
+ return lerp(waterFoamRankCoverage(rank,coverage,width),coverage,unresolved);
+}
+float waterFoamOpticalDepth(float coverage) {
+ // Avoid cancellation in log(1-c) at nearly empty, softly fading trail edges.
+ // Below .01, omitted terms are bounded by c^4/(4*(1-c)); relative error is
+ // less than 2.53e-7. This also avoids the GPU log subtraction error near c=.001.
+ return coverage<0.01 ? coverage*(1.0+coverage*(0.5+coverage/3.0)) : -log(1.0-coverage);
+}
+float waterFoamOpticalCoverage(float depth) {
+ return depth<0.01 ? depth*(1.0+depth*(-0.5+depth*(1.0/6.0-depth/24.0))) : 1.0-exp(-depth);
+}
+float waterFoamFreshMean(float depth) {
+ // Average *coverage*, not density, for a uniform multiplier in [.15,1.85]. The
+ // small-depth expansion uses its independent first four moments; E[m]=1.
+ if(depth<0.05) return depth*(1.0+depth*(-0.6204166667+depth*(0.2870833333-depth*0.1062250521)));
+ return 1.0-(exp(-0.15*depth)-exp(-1.85*depth))/(1.7*depth);
+}
+float2 waterFoamChurnPosition(float2 p,float time) {
+ float2 q=float2(dot(p,float2(0.8,0.6)),dot(p,float2(-0.6,0.8)))+float2(17.31,-8.67);
+ // Each shear has determinant one, so composing them stretches connected detail
+ // without accumulating/compressing its mean density. The displacement is bounded;
+ // this is local procedural churn, not transport by a simulated velocity field.
+ q.x+=0.70*sin(q.y*0.70+time*0.65);
+ q.y+=0.65*sin(q.x*0.63-time*0.47);
+ return q;
+}
+// A fresh hull collision deposits clusters, not a uniformly translucent waterline.
+// Redistribute its existing coverage at a fixed four-unit scale. The rank filter
+// preserves expected coverage and converges to that mean when the clusters are
+// unresolved. Zero source stays zero; this cannot create foam outside contact.
+float waterFoamContactPatches(float2 p,float coverage,float footprint,float time) {
+ coverage=saturate(coverage);
+ if(coverage<=0.0 || coverage>=1.0) return coverage;
+ float2 q=waterFoamChurnPosition(p/4.0,time*0.35)*4.0;
+ // Split area and within-patch coverage: large islands contain smaller pores
+ // instead of becoming smooth opaque blobs. Filter both scales independently.
+ float area=sqrt(coverage),withinPatch=coverage/area;
+ float resolvedFootprint=max(footprint,0.0)*1.7;
+ float2 fine=float2(dot(q,float2(0.28,0.96)),dot(q,float2(-0.96,0.28)))+float2(-31.7,23.2);
+ float patches=waterFoamCoverageBand(q,area,resolvedFootprint,4.0,0.18)
+ *waterFoamCoverageBand(fine,withinPatch,resolvedFootprint,1.75,0.18);
+ // Keep a dilute film between dense clusters. Pure binary islands read as beads
+ // and can saturate the downstream pore response. Both terms have the same mean,
+ // so this controls texture contrast without adding foam or extending its support.
+ return lerp(coverage,patches,0.65);
+}
+float waterFoamOldCoverage(float2 p,float coverage,float footprint,float aged) {
+ // Retain the original runtime lerp at the old-age endpoint. Replacing aged with a
+ // literal one allows different cancellation/folding and changes existing pixel bits.
+ float patchArea=lerp(1.0,sqrt(coverage),aged);
+ float withinPatch=coverage/max(patchArea,0.00001);
+ float2 coarse=float2(dot(p,float2(0.8,0.6)),dot(p,float2(-0.6,0.8)))+float2(17.31,-8.67);
+ float2 fine=float2(dot(p,float2(0.28,0.96)),dot(p,float2(-0.96,0.28)))+float2(-31.7,23.2);
+ return waterFoamCoverageBand(coarse,patchArea,footprint,1.0,0.08)
+ *waterFoamCoverageBand(fine,withinPatch,footprint,0.35,0.01);
+}
+// The world-space history remains fixed around the recorded path. Fresh foam has smoothly
+// evolving optical density rather than opaque ranked islands. Aging hands it to the existing
+// smaller remnants; neither source emission nor the older material is changed here.
+float waterFoamMicroCoverage(float2 p,float coverage,float footprint,float ageSeconds,float time) {
+ coverage=saturate(coverage);
+ if(coverage<=0.0 || coverage>=1.0) return coverage;
+ float aged=smoothstep(2.0,8.0,max(ageSeconds,0.0));
+ if(aged>=1.0) return waterFoamOldCoverage(p,coverage,footprint,aged); // exact old endpoint
+ float depth=waterFoamOpticalDepth(coverage),mean=waterFoamFreshMean(depth);
+ // 1.7 bounds the composed shear's stretch (Frobenius norm), including its most
+ // compressed direction. Unresolved detail approaches its analytic coverage average.
+ float unresolved=smoothstep(0.5,1.5,max(footprint,0.0)*1.7/4.0);
+ float fresh=mean;
+ if(unresolved<1.0) {
+ float rank=waterFoamNoiseRank(oceanNoise(waterFoamChurnPosition(p,time)/4.0));
+ fresh=lerp(waterFoamOpticalCoverage(depth*lerp(0.15,1.85,rank)),mean,unresolved);
+ }
+ if(aged<=0.0) return fresh;
+ return lerp(fresh,waterFoamOldCoverage(p,coverage,footprint,1.0),aged);
+}
+float waterFoamMicroCoverage(float2 p,float coverage,float footprint,float ageSeconds) {
+ return waterFoamMicroCoverage(p,coverage,footprint,ageSeconds,0.0);
+}
+float waterFoamMicroCoverage(float2 p,float coverage,float footprint) {
+ return waterFoamMicroCoverage(p,coverage,footprint,0.0);
+}
+// Redistribute retained history coverage into resolved remnants, rather than multiplying
+// it by another opacity mask. The 1.5-second fresh-churn lifetime sets the onset; by four
+// such lifetimes (six seconds), the old trail is fully fragmented. Fresh contact and newly
+// emitted stern foam keep their exact previous endpoint.
+float waterFoamHistoryRemnants(float2 p,float coverage,float footprint,float ageSeconds,float time) {
+ if(coverage<=0.0 || coverage>=1.0 || ageSeconds<=1.5) return coverage;
+ // Use fixed physical scales. Crossfading them avoids the rapid world-phase swimming
+ // caused by dividing world coordinates by a time-varying remnant size. Six world units
+ // is the existing small-vessel reference width; twelve keeps older carrier remnants
+ // visible at RTS distances without adding a vessel-size/heading channel to the atlas.
+ float resolvedFootprint=max(footprint,0.0)*1.7;
+ if(resolvedFootprint>=18.0) return coverage;
+ float2 q=waterFoamChurnPosition(p/6.0,time*0.35)*6.0;
+ // Split the covered area and within-patch coverage. Sparse old history must not
+ // turn into opaque white islands: each remnant still transmits underlying water.
+ // Their product keeps the same expected coverage while opening larger water gaps.
+ float area=sqrt(coverage),withinPatch=coverage/area;
+ float small=waterFoamCoverageBand(q,area,resolvedFootprint,6.0,0.08);
+ float large=waterFoamCoverageBand(q+float2(43.7,-71.3),area,resolvedFootprint,12.0,0.08);
+ float patches=lerp(small,large,smoothstep(3.0,9.0,ageSeconds))*withinPatch;
+ // Each independently filtered rank band targets the original local coverage. This
+ // conserves its uniform-rank expectation, not every finite patch's exact pixel sum.
+ return lerp(coverage,patches,smoothstep(1.5,6.0,ageSeconds));
+}
+// These moments come from the recorded path. At crossing paths the axial tensor loses
+// coherence, so no arbitrary heading is imposed. Filtering is opacity-weighted, as for age.
+float4 waterFoamRecordedDirection(float4 packed) {
+ if(packed.a<=0.0001) return 0;
+ float2 moment=clamp(2.0*packed.rg/packed.a-1.0,-1.0,1.0);
+ float coherence=length(moment);
+ float confidence=smoothstep(0.20,0.65,coherence)*smoothstep(0.02,0.08,packed.a);
+ if(confidence<=0.0) return 0;
+ float angle=0.5*atan2(moment.y,moment.x);
+ float width=clamp(packed.b/packed.a*32.0,0.0,32.0);
+ return float4(cos(angle),sin(angle),clamp(width,3.0,12.0),confidence);
+}
+float waterFoamStreakTap(float2 p,float area,float footprint,float ageSeconds,float time) {
+ float2 q=waterFoamChurnPosition(p/4.0,time*0.35)*4.0;
+ return lerp(waterFoamCoverageBand(q,area,footprint,4.0,0.08),
+ waterFoamCoverageBand(q+float2(43.7,-71.3),area,footprint,8.0,0.08),
+ smoothstep(3.0,9.0,ageSeconds));
+}
+float waterFoamHistoryStreaks(float2 p,float coverage,float footprint,float ageSeconds,
+ float time,float4 direction,float isotropic) {
+ if(coverage<=0.0 || coverage>=1.0 || ageSeconds<=1.5 || direction.w<=0.0) return isotropic;
+ float resolvedFootprint=max(footprint,0.0)*1.7;
+ float area=sqrt(coverage),withinPatch=coverage/area;
+ // Convolve calibrated *coverage* at fixed world positions. Rotating world coordinates
+ // by a varying heading would rephase the noise during turns. Symmetric offsets also
+ // make the arbitrary sign of an axial eigenvector immaterial. No velocity is invented.
+ float2 offset=direction.xy*direction.z;
+ float patches=waterFoamStreakTap(p,area,resolvedFootprint,ageSeconds,time)*0.30;
+ patches+=(waterFoamStreakTap(p-offset*0.5,area,resolvedFootprint,ageSeconds,time)
+ +waterFoamStreakTap(p+offset*0.5,area,resolvedFootprint,ageSeconds,time))*0.225;
+ patches+=(waterFoamStreakTap(p-offset,area,resolvedFootprint,ageSeconds,time)
+ +waterFoamStreakTap(p+offset,area,resolvedFootprint,ageSeconds,time))*0.125;
+ float streaks=lerp(coverage,patches*withinPatch,smoothstep(1.5,6.0,ageSeconds));
+ return lerp(isotropic,streaks,direction.w);
+}
+// Returns coverage, normalized age, and fresh churn. The atlas stores coverage-weighted
+// moments, so bilinear filtering cannot invent an old edge around newly deposited foam.
+float3 waterFoamHistory(float2 p,float level,float time,float footprint) {
+ uint channels=(uint)(FoamHistoryParameters.x+0.5);
+ if((channels&1u)==0u || abs(level-FoamHistoryParameters.y)>0.1) return 0;
+ float2 uv=(p-FoamHistoryArea.xy)*FoamHistoryArea.zw;
+ if(any(uv<0.0) || any(uv>1.0)) return 0;
+ float3 sample=waterFoamHistoryTile(uv,0u).rgb;
+ if(sample.x<0.0001) return 0;
+ float elapsed=max(0.0,time-FoamHistoryParameters.w);
+ float age=saturate(sample.y/sample.x+elapsed/24.0);
+ float churn=saturate(sample.z/sample.x)*exp(-elapsed/1.5);
+ // Coarse coverage already spreads and decays in world space. Fine breakup evolves at
+ // that same fixed position: old trails do not rotate with a vessel or retain a solid stamp.
+ float2 drift=float2(0.15,-0.08)*time;
+ float broad=oceanNoise((p+drift)*0.065);
+ float fine=oceanNoise((p-drift*0.7)*0.26+float2(broad*0.7,0));
+ float resolved=1.0/(1.0+footprint*0.20);
+ float structure=lerp(broad,broad*0.62+fine*0.38,resolved);
+ float threshold=lerp(0.20,0.67,age);
+ float broken=smoothstep(threshold-0.10,threshold+0.14,structure);
+ float coverage=sample.x*exp(-elapsed/9.0)*lerp(0.38+0.62*broken,broken,smoothstep(0.05,0.65,age));
+ float envelope=coverage;
+ coverage=waterFoamHistoryRemnants(p,coverage,footprint,age*24.0,time);
+ if((channels&4u)!=0u && age*24.0>1.5 && envelope>0.0 && footprint*1.7<18.0) {
+ float4 direction=waterFoamRecordedDirection(waterFoamHistoryTile(uv,1u));
+ coverage=waterFoamHistoryStreaks(p,envelope,footprint,age*24.0,time,direction,coverage);
+ }
+ // Fade the atlas perimeter; clipping a world window must not create a rectangular foam edge.
+ float2 border=min(uv,1.0-uv)/max(FoamHistoryArea.zw,float2(0.000001,0.000001));
+ coverage*=smoothstep(0.0,max(8.0,FoamHistoryParameters.z*3.0),min(border.x,border.y));
+ return float3(saturate(coverage),age,churn*sample.x);
+}
+)HLSL";
+}
+}
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterFoamWindow.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterFoamWindow.h
new file mode 100644
index 000000000..6be430602
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterFoamWindow.h
@@ -0,0 +1,79 @@
+/* Bounded camera window for render-only world-space foam. No simulation data is changed. */
+#pragma once
+#include "Platform/WaterFoamHistory.h"
+
+namespace WaterFoamWindow {
+struct Point { double x,y,z; };
+// Rays are the view centre followed by its four NDC corners, in world space. A low
+// horizon view falls back to a bounded window; ordinary RTS views tightly cover
+// their water-plane footprint instead of spending most atlas texels off screen.
+inline WaterFoamHistory::Mapping Choose(Point camera,const Point rays[5],double level) {
+ using namespace WaterFoamHistory;
+ auto hit=[&](Point ray) {
+ const double t=ray.z<-0.0001?Clamp((level-camera.z)/ray.z,0,8192):4096;
+ return Point{camera.x+ray.x*t,camera.y+ray.y*t,level};
+ };
+ const Point focus=hit(rays[0]);
+ double lowX=focus.x,highX=focus.x,lowY=focus.y,highY=focus.y;
+ bool bounded=camera.z>level;
+ for(unsigned i=1;i<5;++i) {
+ bounded=bounded && rays[i].z<-0.0001 && (level-camera.z)/rays[i].z<8192;
+ const Point p=hit(rays[i]);
+ lowX=(std::min)(lowX,p.x);highX=(std::max)(highX,p.x);
+ lowY=(std::min)(lowY,p.y);highY=(std::max)(highY,p.y);
+ }
+ bounded=bounded && highX-lowX<3800 && highY-lowY<3800;
+ double width=4096,height=4096,centerX=focus.x,centerY=focus.y;
+ if(bounded) {
+ width=std::ceil(Clamp((highX-lowX)*1.10+128,256,4096)/64)*64;
+ height=std::ceil(Clamp((highY-lowY)*1.10+128,256,4096)/64)*64;
+ centerX=(lowX+highX)*0.5;centerY=(lowY+highY)*0.5;
+ } else {
+ // A horizon centre ray has no nearby water hit. Centring the window on its
+ // arbitrary far point would discard the visible water below the camera. Keep
+ // the camera neighbourhood, then fit finite forward hits nearest-first. Distant
+ // hits that cannot fit are omitted from this sampled window, not from history.
+ constexpr double margin=128,step=64,maximumSpan=4096-2*margin-step;
+ struct Hit { Point point;double distance; } hits[5];unsigned count=0;
+ for(unsigned i=0;i<5;++i) {
+ if(std::abs(rays[i].z)<=0.00000001) continue;
+ const double t=(level-camera.z)/rays[i].z;
+ const Point p={camera.x+rays[i].x*t,camera.y+rays[i].y*t,level};
+ const double dx=p.x-camera.x,dy=p.y-camera.y,distance=dx*dx+dy*dy;
+ if(t<0 || !std::isfinite(t) || !std::isfinite(distance)) continue;
+ unsigned at=count;
+ while(at>0 && hits[at-1].distance>distance) { hits[at]=hits[at-1];--at; }
+ hits[at]={p,distance};++count;
+ }
+ lowX=highX=camera.x;lowY=highY=camera.y;
+ for(unsigned i=0;i<count;++i) {
+ const Point &p=hits[i].point;
+ const double lx=(std::min)(lowX,p.x),hx=(std::max)(highX,p.x);
+ const double ly=(std::min)(lowY,p.y),hy=(std::max)(highY,p.y);
+ if(hx-lx<=maximumSpan && hy-ly<=maximumSpan) {lowX=lx;highX=hx;lowY=ly;highY=hy;}
+ }
+ // Bias unused space forwards, while quantized origin limits guarantee the near
+ // footprint's margin even after snapping. This is still one fixed 512-square atlas.
+ const double forwardLength=std::hypot(rays[0].x,rays[0].y);
+ centerX=camera.x;centerY=camera.y;
+ if(std::isfinite(forwardLength) && forwardLength>0.000001) {
+ centerX+=1024*rays[0].x/forwardLength;centerY+=1024*rays[0].y/forwardLength;
+ }
+ auto origin=[&](double center,double low,double high) {
+ return Clamp(std::floor((center-2048)/step)*step,
+ std::ceil((high+margin-4096)/step)*step,std::floor((low-margin)/step)*step);
+ };
+ Mapping result;
+ result.originX=origin(centerX,lowX,highX);result.originY=origin(centerY,lowY,highY);
+ result.widthWorld=result.heightWorld=4096;
+ result.widthPixels=result.heightPixels=MaxAtlasSide;
+ return result;
+ }
+ Mapping result;
+ result.originX=std::floor((centerX-width*0.5)/(width/64))*(width/64);
+ result.originY=std::floor((centerY-height*0.5)/(height/64))*(height/64);
+ result.widthWorld=width;result.heightWorld=height;
+ result.widthPixels=result.heightPixels=MaxAtlasSide;
+ return result;
+}
+}
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterHullContact.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterHullContact.h
new file mode 100644
index 000000000..eb8c240d3
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterHullContact.h
@@ -0,0 +1,49 @@
+/* Current-mesh contact footprint within reachable crests. Never gameplay/collision geometry. */
+#pragma once
+#include "Platform/WaterHullModel.h"
+#include "Platform/WaterFftGeometry.h"
+
+namespace WaterHullContact {
+// Foam need not use the whole theoretical crest envelope. Keep its contour close to the
+// visible lower hull while respecting the same floor clearance and displacement bound.
+constexpr float ContactCrestCap=3.0f;
+inline float ReachableCrest(float terrainDepth,float terrainAttenuation=1.0f) {
+ return (std::min)(ContactCrestCap,WaterFftGeometry::MaxVerticalDisplacement*
+ WaterFftGeometry::SafeDamping(terrainAttenuation,terrainDepth));
+}
+
+// Inputs use the current displayed vessel frame, with Z relative to mean water. Clip
+// the actual triangle to the reachable slab before XY projection. Vertices inside the
+// slab matter: only slicing its two endpoint planes would miss protrusions between them.
+// The caller retains the independent mean-water contour for damping and wave deformation.
+inline bool ProjectTriangle(WaterHullModel::Point3 a,WaterHullModel::Point3 b,
+ WaterHullModel::Point3 c,float crestRise,std::vector<WaterHullModel::Point>& points) {
+ using WaterHullModel::Point3;
+ if(!std::isfinite(crestRise)||crestRise<0||crestRise>ContactCrestCap) return false;
+ Point3 input[8]={a,b,c},output[8];unsigned count=3;
+ for(unsigned i=0;i<count;++i)
+ if(!std::isfinite(input[i].x)||!std::isfinite(input[i].y)||!std::isfinite(input[i].z)) return false;
+ for(unsigned plane=0;plane<2 && count;++plane) {
+ unsigned clipped=0;
+ for(unsigned i=0;i<count;++i) {
+ const Point3 u=input[i],v=input[(i+1)%count];
+ const double du=plane?double(crestRise)-u.z:u.z,dv=plane?double(crestRise)-v.z:v.z;
+ if(du>=0) {
+ if(clipped==8) return false;
+ output[clipped++]=u;
+ }
+ if((du<0 && dv>0)||(du>0 && dv<0)) {
+ if(clipped==8) return false;
+ const double t=du/(du-dv);
+ output[clipped++]={float(u.x+(double(v.x)-u.x)*t),float(u.y+(double(v.y)-u.y)*t),
+ plane?crestRise:0.0f};
+ }
+ }
+ count=clipped;
+ for(unsigned i=0;i<count;++i) input[i]=output[i];
+ }
+ if(points.size()>WaterHullModel::MaxSlicePoints || count>WaterHullModel::MaxSlicePoints-points.size()) return false;
+ for(unsigned i=0;i<count;++i) points.push_back({input[i].x,input[i].y});
+ return true;
+}
+}
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterHullContactFoam.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterHullContactFoam.h
new file mode 100644
index 000000000..fc95b721b
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterHullContactFoam.h
@@ -0,0 +1,94 @@
+#pragma once
+#include <algorithm>
+#include <cmath>
+#include <string>
+
+// Render-only response to the undisturbed broad/medium surface at an actual hull contact.
+// This is a bounded crest/contact energy proxy, not a fluid pressure or incidence solver.
+// Caller supplies the independently limited incident height and its matching slope;
+// fine ripples, reflected waves and generated vessel waves must not enter this input.
+namespace WaterHullContactFoam {
+constexpr float HeightScale=1.6770509831248424f; // sqrt(1.50^2+.75^2), authored broad/medium RMS
+constexpr float SlopeScale=.075f; // calibrated reference near their seeded .0718 slope RMS
+constexpr float CoreRadius=.5f, OuterRadius=1.5f, MaxFilterRadius=1.5f;
+constexpr float MaximumReach=OuterRadius+MaxFilterRadius;
+
+inline float Response(float height,float slope) {
+ if(!std::isfinite(height)||!std::isfinite(slope)||slope<0) return 0;
+ const float phase=(std::max)(0.f,(std::min)(1.f,(height+HeightScale)/HeightScale));
+ const float h=(std::max)(height,0.f)/HeightScale,s=slope/SlopeScale;
+ const float energy=h*h+s*s;
+ // The large-energy form stays finite even if a finite pathological input squares to
+ // infinity; the small form avoids subtracting almost equal numbers near calm water.
+ const float response=energy<=1.f ? energy/(1.f+energy) : 1.f-1.f/(1.f+energy);
+ return phase*phase*(3.f-2.f*phase)*response;
+}
+
+// Odd primitive of the symmetric strip: 1 inside .5, cubic fade to 0 at 1.5.
+// Its total integral is two world units. Filtering averages this profile rather than
+// expanding an opaque rim, so changing footprint preserves the strip's integrated area.
+inline float Primitive(float x) {
+ const float a=std::abs(x);
+ float integral;
+ if(a<=CoreRadius) integral=a;
+ else if(a>=OuterRadius) integral=1.f;
+ else {const float u=a-CoreRadius;integral=CoreRadius+u-u*u*u+.5f*u*u*u*u;}
+ return x<0 ? -integral : integral;
+}
+inline float Band(float distance,float footprint) {
+ if(!std::isfinite(distance)||!std::isfinite(footprint)||distance<0||footprint<0) return 0;
+ const float halfWidth=(std::max)(.125f,(std::min)(MaxFilterRadius,footprint*.5f));
+ if(distance>=OuterRadius+halfWidth) return 0;
+ return (std::max)(0.f,(std::min)(1.f,
+ (Primitive(distance+halfWidth)-Primitive(distance-halfWidth))/(2.f*halfWidth)));
+}
+inline float Coverage(float distance,float footprint,float height,float slope) {
+ return Band(distance,footprint)*Response(height,slope);
+}
+// Keep small-boat contact compact. Large waterlines spread wash over a wider strip,
+// capped at four times the reference width (twelve units including the filter tail).
+inline float WidthScale(float halfBeam) {
+ return 1.f+3.f*(std::sqrt((std::max)(1.f,(std::min)(4.f,halfBeam*.125f)))-1.f);
+}
+inline float Coverage(float distance,float footprint,float height,float slope,float halfBeam) {
+ if(!std::isfinite(halfBeam)||halfBeam<0) return 0;
+ const float scale=WidthScale(halfBeam);
+ return Coverage(distance/scale,footprint/scale,height,slope);
+}
+inline const char *Source() {
+ return R"HLSL(
+// Broad/medium incident crest/contact energy only. There is no calm, speed or noise floor.
+float waterHullContactResponse(float height,float slope) {
+ if(!isfinite(height)||!isfinite(slope)||slope<0.0) return 0.0;
+ const float heightScale=1.6770509831248424, slopeScale=0.075;
+ float phase=saturate((height+heightScale)/heightScale);
+ float h=max(height,0.0)/heightScale,s=slope/slopeScale;
+ float energy=h*h+s*s;
+ float response=energy<=1.0 ? energy/(1.0+energy) : 1.0-1.0/(1.0+energy);
+ return phase*phase*(3.0-2.0*phase)*response;
+}
+float waterHullContactPrimitive(float x) {
+ float a=abs(x),integral;
+ if(a<=0.5) integral=a;
+ else if(a>=1.5) integral=1.0;
+ else {float u=a-0.5;integral=0.5+u-u*u*u+0.5*u*u*u*u;}
+ return x<0.0 ? -integral : integral;
+}
+float waterHullContactBand(float distance,float footprint) {
+ if(!isfinite(distance)||!isfinite(footprint)||distance<0.0||footprint<0.0) return 0.0;
+ float halfWidth=clamp(footprint*0.5,0.125,1.5);
+ if(distance>=1.5+halfWidth) return 0.0;
+ return saturate((waterHullContactPrimitive(distance+halfWidth)
+ -waterHullContactPrimitive(distance-halfWidth))/(2.0*halfWidth));
+}
+float waterHullContactCoverage(float distance,float footprint,float height,float slope) {
+ return waterHullContactBand(distance,footprint)*waterHullContactResponse(height,slope);
+}
+float waterHullContactCoverage(float distance,float footprint,float height,float slope,float halfBeam) {
+ if(!isfinite(halfBeam)||halfBeam<0.0) return 0.0;
+ float scale=1.0+3.0*(sqrt(clamp(halfBeam*0.125,1.0,4.0))-1.0);
+ return waterHullContactCoverage(distance/scale,footprint/scale,height,slope);
+}
+)HLSL";
+}
+}
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterHullModel.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterHullModel.h
new file mode 100644
index 000000000..3e0336383
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterHullModel.h
@@ -0,0 +1,236 @@
+/* Render-only waterline contours. Gameplay geometry and navigation never use these hulls. */
+#pragma once
+#include <algorithm>
+#include <cmath>
+#include <cstring>
+#include <string>
+#include <vector>
+#include "Platform/WaterHullContactFoam.h"
+
+namespace WaterHullModel {
+constexpr unsigned MaxHulls=8, MaxVertices=12, RegistersPerHull=10, MaxCacheEntries=64;
+constexpr unsigned MaxSlicePoints=4096, MaxSliceTriangles=8192, MaxMeshes=128;
+constexpr float FadeDistance=9.0f;
+struct Point { float x,y; };
+struct Point3 { float x,y,z; };
+struct Polygon { Point points[MaxVertices]; unsigned count=0; float error=0.0f; };
+struct Hull { float data[RegistersPerHull][4] = {}; };
+inline float Cross(Point a,Point b,Point c) { return (b.x-a.x)*(c.y-a.y)-(b.y-a.y)*(c.x-a.x); }
+inline float SegmentDistanceSquared(Point p,Point a,Point b) {
+ const float x=b.x-a.x,y=b.y-a.y;
+ const float t=(std::max)(0.0f,(std::min)(1.0f,((p.x-a.x)*x+(p.y-a.y)*y)/(std::max)(x*x+y*y,1.0e-12f)));
+ const float dx=p.x-a.x-t*x,dy=p.y-a.y-t*y;
+ return dx*dx+dy*dy;
+}
+// Coplanar triangles contribute their vertices. Tangent edges contribute their exact waterline,
+// and repeated edge hits are welded by BuildPolygon. No GPU buffer is mapped or read back.
+inline bool SliceTriangle(Point3 a,Point3 b,Point3 c,std::vector<Point>& points) {
+ const Point3 p[3]={a,b,c};
+ for (unsigned i=0;i<3;++i) {
+ const Point3 &u=p[i],&v=p[(i+1)%3];
+ if (!std::isfinite(u.x)||!std::isfinite(u.y)||!std::isfinite(u.z)) return false;
+ if (std::abs(u.z)<0.0001f) {
+ if (points.size()>=MaxSlicePoints) return false;
+ points.push_back({u.x,u.y});
+ }
+ if ((u.z<0.0f && v.z>0.0f)||(u.z>0.0f && v.z<0.0f)) {
+ if (points.size()>=MaxSlicePoints) return false;
+ const float t=u.z/(u.z-v.z);
+ points.push_back({u.x+(v.x-u.x)*t,u.y+(v.y-u.y)*t});
+ }
+ }
+ return true;
+}
+inline Polygon BuildPolygon(std::vector<Point> points) {
+ Polygon result;
+ if (points.size()<3 || points.size()>MaxSlicePoints) return result;
+ for (const Point& p:points) if (!std::isfinite(p.x)||!std::isfinite(p.y)) return result;
+ std::sort(points.begin(),points.end(),[](Point a,Point b){return a.x<b.x || (a.x==b.x && a.y<b.y);});
+ points.erase(std::unique(points.begin(),points.end(),[](Point a,Point b){return std::abs(a.x-b.x)<0.0001f && std::abs(a.y-b.y)<0.0001f;}),points.end());
+ std::vector<Point> outline(points.size()*2);
+ unsigned count=0;
+ for (Point p:points) { while(count>=2 && Cross(outline[count-2],outline[count-1],p)<=0.00001f) --count; outline[count++]=p; }
+ const unsigned lower=count;
+ for (size_t i=points.size()-1;i>0;--i) { const Point p=points[i-1]; while(count>lower && Cross(outline[count-2],outline[count-1],p)<=0.00001f) --count; outline[count++]=p; }
+ if (count<4) return result;
+ outline.resize(count-1);
+ const std::vector<Point> original=outline;
+ // Preserve the largest shape features. The measured error is retained for diagnostics/tests;
+ // the inner convex approximation never places an artificial solid footprint outside the mesh.
+ while(outline.size()>MaxVertices) {
+ size_t remove=0; float least=1.0e30f;
+ for (size_t i=0;i<outline.size();++i) {
+ const float error=SegmentDistanceSquared(outline[i],outline[(i+outline.size()-1)%outline.size()],outline[(i+1)%outline.size()]);
+ if(error<least) { least=error;remove=i; }
+ }
+ outline.erase(outline.begin()+remove);
+ }
+ result.count=(unsigned)outline.size();
+ for(unsigned i=0;i<result.count;++i) result.points[i]=outline[i];
+ for(Point p:original) {
+ float closest=1.0e30f;
+ for(unsigned i=0;i<result.count;++i) closest=(std::min)(closest,SegmentDistanceSquared(p,result.points[i],result.points[(i+1)%result.count]));
+ result.error=(std::max)(result.error,std::sqrt(closest));
+ }
+ return result;
+}
+inline float SignedDistance(Point p,const Polygon& polygon) {
+ if(polygon.count<3 || polygon.count>MaxVertices) return 1.0e6f;
+ float distance=1.0e30f; bool inside=true;
+ for(unsigned i=0;i<polygon.count;++i) {
+ const Point a=polygon.points[i],b=polygon.points[(i+1)%polygon.count];
+ distance=(std::min)(distance,SegmentDistanceSquared(p,a,b));
+ inside=inside && Cross(a,b,p)>=-0.0001f;
+ }
+ return std::sqrt(distance)*(inside?-1.0f:1.0f);
+}
+inline Polygon Unpack(const Hull& hull) {
+ Polygon p;p.count=(unsigned)(std::max)(0.0f,(std::min)(float(MaxVertices),hull.data[0][3]));
+ for(unsigned i=0;i<p.count;++i) p.points[i]={hull.data[4+i/2][(i%2)*2],hull.data[4+i/2][(i%2)*2+1]};
+ return p;
+}
+inline Point LocalPoint(const Hull& hull,float x,float y) {
+ const float dx=x-hull.data[0][0],dy=y-hull.data[0][1];
+ return {dx*hull.data[1][0]+dy*hull.data[1][1],-dx*hull.data[1][1]+dy*hull.data[1][0]};
+}
+inline float Damping(const Hull& hull,float x,float y,float level) {
+ if(std::abs(level-hull.data[0][2])>0.1f) return 1.0f;
+ const Point p=LocalPoint(hull,x,y);
+ if(std::abs(p.x)>hull.data[1][2]+FadeDistance || std::abs(p.y)>hull.data[1][3]+FadeDistance) return 1.0f;
+ const float t=(std::max)(0.0f,(std::min)(1.0f,SignedDistance(p,Unpack(hull))/FadeDistance));
+ return t*t*(3.0f-2.0f*t);
+}
+// The consuming water shader declares float4 HullData[MaxHulls*RegistersPerHull].
+inline const char *GetHlslSource() {
+ return R"HLSL(
+float2 WaterHullVertex(int baseIndex,int vertex) {
+ float4 pair=HullData[baseIndex+4+vertex/2];
+ return (vertex&1)!=0?pair.zw:pair.xy;
+}
+float WaterHullSignedDistance(float2 p,int baseIndex,int count) {
+ if(count<3 || count>12) return 1.0e6;
+ float distanceSquared=1.0e30; bool inside=true;
+ for(int i=0;i<count;++i) {
+ float2 a=WaterHullVertex(baseIndex,i),b=WaterHullVertex(baseIndex,(i+1)%count);
+ float2 edge=b-a,delta=p-a;
+ float t=saturate(dot(delta,edge)/max(dot(edge,edge),1.0e-12));
+ float2 separation=delta-t*edge;
+ distanceSquared=min(distanceSquared,dot(separation,separation));
+ inside=inside && edge.x*delta.y-edge.y*delta.x>=-0.0001;
+ }
+ return sqrt(distanceSquared)*(inside?-1.0:1.0);
+}
+)HLSL";
+}
+
+// Depends on the production oceanNoise function and HullParameters/HullData declarations.
+// Tests call this same emitted shader, so contact and moving-wake behavior cannot drift.
+inline std::string GetEffectsHlslSource(bool contactContours=false,bool visualContact=false) {
+ // Isolated legacy fixtures can omit the optional contact block. Production always uses
+ // it, with an invalid/empty contact falling back to the exact mean-waterline contour.
+ std::string source=contactContours?R"HLSL(
+float4 WaterContactRegister(int index) {
+ return ContactHullData[(index/10)*10].w>=3.0?ContactHullData[index]:HullData[index];
+}
+)HLSL":R"HLSL(
+float4 WaterContactRegister(int index) { return HullData[index]; }
+)HLSL";
+ source=std::string(WaterHullContactFoam::Source())+source;
+ source+=R"HLSL(
+float WaterContactDistance(float2 p,int index,int count) {
+ if(count<3 || count>12) return 1.0e6;
+ float closest=1.0e30; bool inside=true;
+ for(int i=0;i<count;++i) {
+ int next=(i+1)%count;
+ float4 pa=WaterContactRegister(index+4+i/2),pb=WaterContactRegister(index+4+next/2);
+ float2 a=(i&1)!=0?pa.zw:pa.xy,b=(next&1)!=0?pb.zw:pb.xy;
+ float2 edge=b-a,delta=p-a;
+ float t=saturate(dot(delta,edge)/max(dot(edge,edge),1.0e-12));
+ float2 separation=delta-t*edge;
+ closest=min(closest,dot(separation,separation));
+ inside=inside && edge.x*delta.y-edge.y*delta.x>=-0.0001;
+ }
+ return sqrt(closest)*(inside?-1.0:1.0);
+}
+
+// The hull contour anchors fresh contact foam. Only a short stern mixing region follows the
+// current motion; the independent world-space history retains the trailing path after turns.
+float3 oceanHullEffects(float2 world,float level,float time,float offshore,float waveHeight,float footprint,float waveImpact)
+{
+ float foam=0,turbulence=0,damping=1;
+ if(offshore<=0.001) return float3(0,0,1);
+ int count=clamp((int)HullParameters.x,0,8);
+ for(int h=0;h<count;++h) {
+ int index=h*10;
+ float4 meanPosition=HullData[index],meanAxis=HullData[index+1];
+ if(meanPosition.w<3 || abs(level-meanPosition.z)>0.1) continue;
+ float2 meanDelta=world-meanPosition.xy;
+ float2 meanLocal=float2(dot(meanDelta,meanAxis.xy),dot(meanDelta,float2(-meanAxis.y,meanAxis.x)));
+ if(abs(meanLocal.x)<meanAxis.z+9.0 && abs(meanLocal.y)<meanAxis.w+9.0) {
+ float t=saturate(WaterHullSignedDistance(meanLocal,index,(int)meanPosition.w)/9.0);
+ damping=min(damping,t*t*(3.0-2.0*t));
+ }
+ float4 position=WaterContactRegister(index),axis=WaterContactRegister(index+1),motion=WaterContactRegister(index+2);
+ if(position.w<3 || abs(level-position.z)>0.1) continue;
+ float2 delta=world-position.xy;
+ float2 local=float2(dot(delta,axis.xy),dot(delta,float2(-axis.y,axis.x)));
+ float speed=length(motion.xy),moving=smoothstep(0.3,18.0,speed);
+ float reach=motion.w+48.0;
+ if(dot(delta,delta)>reach*reach) continue;
+ float2 velocity=float2(dot(motion.xy,axis.xy),dot(motion.xy,float2(-axis.y,axis.x)));
+ float2 forward=velocity/max(speed,0.001),aft=-forward,side=float2(-aft.y,aft.x);
+ float blend=smoothstep(-0.25,0.25,forward.x);
+ float4 endpoints=WaterContactRegister(index+3);
+ float2 stern=lerp(endpoints.zw,endpoints.xy,blend),bow=lerp(endpoints.xy,endpoints.zw,blend);
+ float hullDistance=1.0e6;
+ if(abs(local.x)<axis.z+12.0 && abs(local.y)<axis.w+12.0) {
+ hullDistance=WaterContactDistance(local,index,(int)position.w);
+ float distance=max(hullDistance,0.0),aa=clamp(footprint*0.6,0.25,1.5);
+ float exposed=smoothstep(-aa,0.1,hullDistance);
+ float wash=oceanNoise(local*float2(0.065,0.32)+float2(-time*0.12,motion.z*9.0));
+ float flecks=oceanNoise(local*0.48+float2(time*0.08,-time*0.13));
+ // Incoming slope/contact can foam on an idle hull, but never emits propulsion wash.
+ float collision=waterHullContactResponse(waveHeight,waveImpact);
+ float sideWidth=1.0+moving*min(2.0,sqrt(max(axis.w,1.0))*0.35)+collision*1.3;
+ float rim=1.0-smoothstep(sideWidth,sideWidth+aa,distance);
+ float sideStreak=smoothstep(0.43,0.68,wash)*(0.2+0.8*smoothstep(0.25,0.65,flecks));
+ float contact=exposed*max(rim*sideStreak*moving*0.38,
+ waterHullContactCoverage(distance,footprint,waveHeight,waveImpact,axis.w));
+ float outer=1.0-smoothstep(sideWidth,sideWidth+3.5,distance);
+ // The leading waterline carries a concentrated bow impact, not an all-round halo.
+ float bowDistance=length((local-bow)/float2(max(axis.w*0.8,3.0),max(axis.w*0.9,3.0)));
+ float bowRegion=exp(-bowDistance*bowDistance*1.4);
+ float bowWidth=2.0+moving*min(7.0,3.0+sqrt(max(axis.w,1.0))*0.55);
+ float bowContact=exposed*(1.0-smoothstep(bowWidth,bowWidth+aa,distance))*bowRegion
+ *moving*(0.45+0.55*smoothstep(0.25,0.7,flecks));
+)HLSL";
+ if(visualContact) source+=" if(VisualHullMeta[h].w<0.5) {\n";
+ source+=R"HLSL( foam=max(foam,max(contact,bowContact*0.82));
+ turbulence=max(turbulence,exposed*outer*(collision*0.18+moving*0.25)+bowContact*0.4);
+)HLSL";
+ if(visualContact) source+=" }\n";
+ source+=R"HLSL( }
+ if(speed>0.3) {
+ float2 wakePoint=local-stern;
+ float along=dot(wakePoint,aft),across=dot(wakePoint,side);
+ float lengthWake=clamp(14.0+sqrt(max(axis.w,1.0))*3.0+speed*0.12,18.0,44.0);
+ float trail=smoothstep(-1.5,2.0,along)*(1.0-smoothstep(lengthWake*0.45,lengthWake,along));
+ float wakeWidth=max(1.0,axis.w*0.45)+max(along,0.0)*0.12;
+ float churn=exp(-across*across/max(wakeWidth*wakeWidth,1.0));
+ float structure=oceanNoise(float2(across*0.18,along*0.09-time*0.22)+motion.zz*9.0);
+ float broken=smoothstep(0.26,0.72,structure);
+ float threads=1.0-smoothstep(0.045,0.13,abs(oceanNoise(float2(across*0.32,along*0.07)+structure)-0.5));
+ // Broad central mixing has gaps and thin irregular strands; the aged atlas continues
+ // this field beyond the hull. No long rigidly rotating V-shaped foam strip is emitted.
+ float wake=trail*moving*churn*(broken*0.70+threads*0.42);
+ float outside=smoothstep(-0.2,0.3,hullDistance);
+ foam=max(foam,wake*outside);
+ turbulence=max(turbulence,trail*moving*churn*outside);
+ }
+ }
+ return float3(saturate(foam)*offshore,saturate(turbulence)*offshore,damping);
+}
+)HLSL";
+ return source;
+}
+}
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterHullPoseCache.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterHullPoseCache.h
new file mode 100644
index 000000000..8f4107c9e
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterHullPoseCache.h
@@ -0,0 +1,93 @@
+/* Reuse hull slices only while their source mesh poses remain geometrically close. */
+#pragma once
+#include <cmath>
+#include <cstddef>
+#include <limits>
+#include <vector>
+
+namespace WaterHullPoseCache {
+constexpr unsigned MaxMeshes=128;
+// This bounds mesh-vertex movement, NOT slice-endpoint movement: a nearly tangent
+// triangle can have an ill-conditioned plane intersection even at the exact pose.
+constexpr double MaxVertexMovement=0.01;
+struct Mesh {
+ const void *identity=nullptr,*vertexArray=nullptr,*triangleArray=nullptr;
+ unsigned vertexCount=0,triangleCount=0;
+ bool crossesMean=false;
+ double supportRadius=0;
+ float transform[3][4] = {}; // model-local vertex -> horizontal vessel frame/water-relative Z
+};
+
+inline double SupportRadius(const float center[3],const float extent[3]) {
+ double squared=0;
+ for(unsigned i=0;i<3;++i) {
+ if(!std::isfinite(center[i]) || !std::isfinite(extent[i]) || extent[i]<0)
+ return std::numeric_limits<double>::infinity();
+ // Include the offset of the AABB from the mesh origin. Get_Bounding_Box reconstructs
+ // float center/extent from min/max; pad its rounding conservatively before the norm.
+ const double reach=(std::abs(double(center[i]))+double(extent[i]))*
+ (1.0+4.0*std::numeric_limits<float>::epsilon());
+ squared+=reach*reach;
+ }
+ return std::nextafter(std::sqrt(squared),std::numeric_limits<double>::infinity());
+}
+inline bool Valid(const Mesh &mesh) {
+ if(!mesh.identity || !mesh.vertexArray || !mesh.triangleArray || !mesh.vertexCount ||
+ !mesh.triangleCount || !std::isfinite(mesh.supportRadius) || mesh.supportRadius<0) return false;
+ for(unsigned i=0;i<3;++i) for(unsigned j=0;j<4;++j)
+ if(!std::isfinite(mesh.transform[i][j])) return false;
+ return true;
+}
+inline bool SameGeometry(const Mesh &a,const Mesh &b) {
+ return a.identity==b.identity && a.vertexArray==b.vertexArray && a.triangleArray==b.triangleArray &&
+ a.vertexCount==b.vertexCount && a.triangleCount==b.triangleCount &&
+ a.crossesMean==b.crossesMean && a.supportRadius==b.supportRadius;
+}
+inline double VertexMovementBound(const Mesh &sliced,const Mesh &current) {
+ if(!Valid(sliced) || !Valid(current)) return std::numeric_limits<double>::infinity();
+ double linearSquared=0,translationSquared=0;
+ for(unsigned i=0;i<3;++i) {
+ for(unsigned j=0;j<3;++j) {
+ const double delta=double(current.transform[i][j])-sliced.transform[i][j];
+ linearSquared+=delta*delta;
+ }
+ const double delta=double(current.transform[i][3])-sliced.transform[i][3];
+ translationSquared+=delta*delta;
+ }
+ if(linearSquared==0 && translationSquared==0) return 0; // common stationary/pause case
+ const double radius=(sliced.supportRadius>current.supportRadius?sliced.supportRadius:current.supportRadius);
+ // |(A-A0)v+(t-t0)| <= ||A-A0||F*R + |t-t0|, for every mesh vertex |v|<=R.
+ return std::nextafter(std::sqrt(linearSquared)*radius+std::sqrt(translationSquared),
+ std::numeric_limits<double>::infinity());
+}
+class Cache {
+ std::vector<Mesh> sliced;
+ double slicedCrest=0;
+ bool initialized=false;
+public:
+ template<class T> bool Reusable(const std::vector<T> &current,double crest,
+ double maximumMovement=MaxVertexMovement) const {
+ if(!initialized || current.size()>MaxMeshes || current.size()!=sliced.size() ||
+ !std::isfinite(crest) || crest<0 || !std::isfinite(maximumMovement) || maximumMovement<0) return false;
+ const double crestMovement=std::abs(crest-slicedCrest);
+ if(crestMovement>maximumMovement) return false;
+ for(std::size_t i=0;i<current.size();++i) {
+ if(!SameGeometry(sliced[i],current[i]) ||
+ VertexMovementBound(sliced[i],current[i])+crestMovement>maximumMovement) return false;
+ }
+ return true;
+ }
+ template<class T> bool Store(const std::vector<T> &current,double crest) {
+ if(current.size()>MaxMeshes || !std::isfinite(crest) || crest<0) { Clear();return false; }
+ for(const Mesh &mesh:current) if(!Valid(mesh)) { Clear();return false; }
+ // Only called after slicing, never on a hit: small pose changes accumulate against
+ // this snapshot. Explicit reserve keeps capacity bounded rather than geometric growth.
+ if(sliced.capacity()<current.size()) sliced.reserve(current.size());
+ sliced.resize(current.size());
+ for(std::size_t i=0;i<current.size();++i) sliced[i]=current[i];
+ slicedCrest=crest;initialized=true;return true;
+ }
+ void Clear() { sliced.clear();slicedCrest=0;initialized=false; }
+ std::size_t Size() const { return sliced.size(); }
+};
+}
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterHullVisual.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterHullVisual.h
new file mode 100644
index 000000000..8dae7831c
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterHullVisual.h
@@ -0,0 +1,271 @@
+// Render-only contact with the actual posed mesh. Does not represent a closed solid.
+#pragma once
+#include <algorithm>
+#include <cmath>
+#include <cstddef>
+#include <cstdlib>
+#include <cstring>
+#include <limits>
+
+namespace WaterHullVisual {
+// One launch-time policy for mesh collection, packet upload and shader generation.
+// Unset selects the validated mesh path; explicit values such as 0 disable it.
+inline bool Enabled() {
+ const char *value=std::getenv("ZH_WATER_HULL_CONTACT");
+ return !value || std::strcmp(value,"mesh")==0;
+}
+constexpr unsigned MaxVertices=64, MaxTriangles=96, RegistersPerHull=88;
+constexpr unsigned MaxSourceTriangles=8192;
+// Keep every intermediate float product finite. Native vessel local coordinates
+// are hundreds of units; this is a numerical bound, not a clipping distance.
+constexpr float MaxCoordinate=1.0e12f;
+struct Point2 { float x,y; };
+struct Point3 { float x,y,z; };
+struct Packet { float data[RegistersPerHull][4]; float metadata[4]; };
+static_assert(sizeof(Packet)==(RegistersPerHull+1)*4*sizeof(float),"packed packet");
+
+inline bool Finite(float x) { return std::isfinite(x) && std::fabs(x)<=MaxCoordinate; }
+inline bool Finite(Point3 p) { return Finite(p.x)&&Finite(p.y)&&Finite(p.z); }
+inline float PackIndices(unsigned a,unsigned b,unsigned c) { return float(a+64*b+4096*c); }
+inline void UnpackIndices(unsigned p,unsigned& a,unsigned& b,unsigned& c) {
+ a=p%64; b=(p/64)%64; c=p/4096;
+}
+inline bool Integer(float x,unsigned maximum) {
+ return std::isfinite(x)&&x>=0&&x<=float(maximum)&&x==std::floor(x);
+}
+inline bool Valid(const Packet& p) {
+ if(p.metadata[3]!=1 || !Integer(p.metadata[0],MaxVertices) ||
+ !Integer(p.metadata[1],MaxTriangles) || !std::isfinite(p.metadata[2]) || p.metadata[2]<0) return false;
+ const unsigned nv=unsigned(p.metadata[0]),nt=unsigned(p.metadata[1]);
+ if((nv==0)!=(nt==0)) return false;
+ for(unsigned i=0;i<nv;++i) if(!Finite({p.data[i][0],p.data[i][1],p.data[i][2]})) return false;
+ for(unsigned i=0;i<nt;++i) {
+ const float packed=p.data[MaxVertices+i/4][i%4];
+ if(!Integer(packed,262143)) return false;
+ unsigned a,b,c;UnpackIndices(unsigned(packed),a,b,c);
+ if(a>=nv||b>=nv||c>=nv) return false;
+ }
+ return true;
+}
+inline bool RefreshRadius(Packet& p) {
+ double radius2=0;
+ for(unsigned i=0;i<unsigned(p.metadata[0]);++i) {
+ const double x=p.data[i][0],y=p.data[i][1];
+ radius2=(std::max)(radius2,x*x+y*y);
+ }
+ const double radius=std::sqrt(radius2);
+ p.metadata[2]=float(radius+(std::max)(1.0e-4,radius*2.0e-6));
+ if(p.metadata[0]==0) p.metadata[2]=0;
+ return std::isfinite(p.metadata[2]);
+}
+
+// Complete source traversal is required even after false. Finish fails atomically:
+// no truncated packet can be mistaken for a complete contour. Zero-area faces
+// carry no surface and are skipped; vertices weld only by exact float equality.
+class Builder {
+ Packet packet_{};
+ unsigned vertices_=0,triangles_=0,source_=0;
+ float lo_,hi_;
+ bool valid_;
+ unsigned Vertex(Point3 p) {
+ for(unsigned i=0;i<vertices_;++i)
+ if(packet_.data[i][0]==p.x&&packet_.data[i][1]==p.y&&packet_.data[i][2]==p.z) return i;
+ if(vertices_==MaxVertices) { valid_=false; return 0; }
+ const unsigned i=vertices_++;
+ packet_.data[i][0]=p.x==0?0:p.x; packet_.data[i][1]=p.y==0?0:p.y; packet_.data[i][2]=p.z==0?0:p.z;
+ return i;
+ }
+public:
+ Builder(float minZ,float maxZ):lo_(minZ),hi_(maxZ),valid_(Finite(minZ)&&Finite(maxZ)&&minZ<=maxZ) {}
+ bool AddTriangle(const Point3& a,const Point3& b,const Point3& c) {
+ if(!valid_) return false;
+ if(++source_>MaxSourceTriangles||!Finite(a)||!Finite(b)||!Finite(c)) {valid_=false;return false;}
+ // Reject only faces wholly outside the full reachable interval. Do not
+ // clip positions: the fragment performs the actual-height intersection.
+ if((a.z<lo_&&b.z<lo_&&c.z<lo_)||(a.z>hi_&&b.z>hi_&&c.z>hi_)) return true;
+ const double ux=double(b.x)-a.x,uy=double(b.y)-a.y,uz=double(b.z)-a.z;
+ const double vx=double(c.x)-a.x,vy=double(c.y)-a.y,vz=double(c.z)-a.z;
+ if(uy*vz-uz*vy==0 && uz*vx-ux*vz==0 && ux*vy-uy*vx==0) return true;
+ if(triangles_==MaxTriangles) {valid_=false;return false;}
+ const unsigned ia=Vertex(a),ib=Vertex(b),ic=Vertex(c);
+ if(!valid_) return false;
+ packet_.data[MaxVertices+triangles_/4][triangles_%4]=PackIndices(ia,ib,ic);++triangles_;
+ return true;
+ }
+ bool AddIndexedTriangle(const Point3* positions,std::size_t count,unsigned a,unsigned b,unsigned c) {
+ if(!positions||a>=count||b>=count||c>=count) {valid_=false;return false;}
+ return AddTriangle(positions[a],positions[b],positions[c]);
+ }
+ bool Finish(Packet& out) const {
+ Packet result{};
+ if(!valid_) {out=result;return false;}
+ result=packet_; result.metadata[0]=float(vertices_);result.metadata[1]=float(triangles_);result.metadata[3]=1;
+ if(!RefreshRadius(result)) {out=Packet{};return false;}
+ out=result;return true;
+ }
+};
+
+// Alias-safe translation from cached object origin to the existing contact frame.
+// Recompute the bound after translation; never translate a cached packet in place
+// unless that cached packet is deliberately being replaced by the caller.
+inline bool Reframe(const Packet& origin,float centerX,float centerY,Packet& out) {
+ Packet p{};
+ if(!Valid(origin)||!Finite(centerX)||!Finite(centerY)) {out=p;return false;}
+ p=origin;
+ for(unsigned i=0;i<unsigned(p.metadata[0]);++i) {
+ const double x=double(p.data[i][0])-centerX,y=double(p.data[i][1])-centerY;
+ if(std::fabs(x)>MaxCoordinate||std::fabs(y)>MaxCoordinate) {out=Packet{};return false;}
+ p.data[i][0]=float(x);p.data[i][1]=float(y);
+ }
+ if(!RefreshRadius(p)) {out=Packet{};return false;}
+ out=p;return true;
+}
+
+struct Result {
+ bool hasSegment=false,coplanar=false;
+ float distance=1.0e6f;
+ Point2 closest{},positive{},negative{};
+ float minY=0,maxY=0;
+ unsigned segmentCount=0;
+ // Span midpoint gives a symmetric longitudinal role anchor. It need not lie
+ // on a segment if disjoint surfaces share an extreme X; closest always does.
+ float positiveMinY=0,positiveMaxY=0,negativeMinY=0,negativeMaxY=0;
+};
+inline Point3 Vertex(const Packet& p,unsigned i) {return {p.data[i][0],p.data[i][1],p.data[i][2]};}
+inline bool Equal(Point2 a,Point2 b) {return a.x==b.x&&a.y==b.y;}
+inline bool Less(Point2 a,Point2 b) {return a.x<b.x||(a.x==b.x&&a.y<b.y);}
+inline void EndPoint(Result& r,Point2 p) {
+ if(p.x<r.negative.x) {r.negative=p;r.negativeMinY=r.negativeMaxY=p.y;}
+ else if(p.x==r.negative.x) {r.negativeMinY=(std::min)(r.negativeMinY,p.y);r.negativeMaxY=(std::max)(r.negativeMaxY,p.y);}
+ if(p.x>r.positive.x) {r.positive=p;r.positiveMinY=r.positiveMaxY=p.y;}
+ else if(p.x==r.positive.x) {r.positiveMinY=(std::min)(r.positiveMinY,p.y);r.positiveMaxY=(std::max)(r.positiveMaxY,p.y);}
+ r.negative.y=(r.negativeMinY+r.negativeMaxY)*0.5f;
+ r.positive.y=(r.positiveMinY+r.positiveMaxY)*0.5f;
+ r.minY=(std::min)(r.minY,p.y);r.maxY=(std::max)(r.maxY,p.y);
+}
+inline void Segment(Result& r,Point2 q,Point2 a,Point2 b) {
+ const float dx=b.x-a.x,dy=b.y-a.y,den=dx*dx+dy*dy;
+ const float t=den>0?(std::max)(0.0f,(std::min)(1.0f,((q.x-a.x)*dx+(q.y-a.y)*dy)/den)):0;
+ const Point2 closest={a.x+t*dx,a.y+t*dy};
+ const float ex=q.x-closest.x,ey=q.y-closest.y,d=std::sqrt(ex*ex+ey*ey);
+ if(!r.hasSegment) {r.closest=closest;r.distance=d;r.positive=r.negative=a;r.minY=r.maxY=a.y;
+ r.positiveMinY=r.positiveMaxY=r.negativeMinY=r.negativeMaxY=a.y;}
+ else if(d<r.distance||(d==r.distance&&Less(closest,r.closest))) {r.closest=closest;r.distance=d;}
+ EndPoint(r,a);EndPoint(r,b);r.hasSegment=true;++r.segmentCount;
+}
+// Exact plane convention (no +/-epsilon slab). Fully coplanar faces are flagged
+// and skipped: their tessellation diagonals are not physical contact edges.
+// A lone tangent vertex is an actual point intersection and uses a zero segment.
+// Result is unsigned and includes all selected rendered surfaces, not a claim of
+// exterior topology. Query height must be inside the builder's complete interval.
+inline Result Query(const Packet& p,Point3 q) {
+ Result r;
+ if(!Valid(p)||!Finite(q)) return r;
+ for(unsigned i=0;i<unsigned(p.metadata[1]);++i) {
+ unsigned ia,ib,ic;UnpackIndices(unsigned(p.data[MaxVertices+i/4][i%4]),ia,ib,ic);
+ const Point3 v[3]={Vertex(p,ia),Vertex(p,ib),Vertex(p,ic)};
+ if(v[0].z==q.z&&v[1].z==q.z&&v[2].z==q.z) {r.coplanar=true;continue;}
+ Point2 hit[3];unsigned count=0;
+ for(unsigned e=0;e<3;++e) {
+ const Point3 a=v[e],b=v[(e+1)%3];const float az=a.z-q.z,bz=b.z-q.z;
+ Point2 h{};bool have=false;
+ if(az==0) {h={a.x,a.y};have=true;}
+ else if((az<0&&bz>0)||(az>0&&bz<0)) {
+ const float t=az/(az-bz);h={a.x+t*(b.x-a.x),a.y+t*(b.y-a.y)};have=true;
+ }
+ if(have) {bool duplicate=false;for(unsigned k=0;k<count;++k) duplicate=duplicate||Equal(hit[k],h);if(!duplicate) hit[count++]=h;}
+ }
+ if(count==1) Segment(r,{q.x,q.y},hit[0],hit[0]);
+ else if(count==2) Segment(r,{q.x,q.y},hit[0],hit[1]);
+ else if(count>2) r.coplanar=true; // defensive ambiguity; never emit an internal diagonal
+ }
+ return r;
+}
+
+// The backend declares the three bounded pixel-only arrays and VisualHullMeta.
+// Test harnesses may declare them with the same names before appending Source().
+inline const char* Source() { return R"hlsl(
+float4 WaterVisualRegister(int index) {
+ if(index<256) return VisualHullBlock0[index];
+ if(index<512) return VisualHullBlock1[index-256];
+ return VisualHullBlock2[index-512];
+}
+struct WaterVisualResult {
+ float hasSegment, coplanar, distance;
+ float2 closest, positive, negative;
+ float minY, maxY;
+ int segmentCount;
+ float positiveMinY,positiveMaxY,negativeMinY,negativeMaxY;
+};
+WaterVisualResult WaterVisualEmpty() {
+ WaterVisualResult r;
+ r.hasSegment=0; r.coplanar=0; r.distance=1e6;
+ r.closest=0; r.positive=0; r.negative=0;
+ r.minY=0; r.maxY=0; r.segmentCount=0;
+ r.positiveMinY=0;r.positiveMaxY=0;r.negativeMinY=0;r.negativeMaxY=0;
+ return r;
+}
+bool WaterVisualLess(float2 a,float2 b) { return a.x<b.x || (a.x==b.x && a.y<b.y); }
+void WaterVisualEndpoint(inout WaterVisualResult r,float2 p) {
+ if(p.x<r.negative.x) {r.negative=p;r.negativeMinY=p.y;r.negativeMaxY=p.y;}
+ else if(p.x==r.negative.x) {r.negativeMinY=min(r.negativeMinY,p.y);r.negativeMaxY=max(r.negativeMaxY,p.y);}
+ if(p.x>r.positive.x) {r.positive=p;r.positiveMinY=p.y;r.positiveMaxY=p.y;}
+ else if(p.x==r.positive.x) {r.positiveMinY=min(r.positiveMinY,p.y);r.positiveMaxY=max(r.positiveMaxY,p.y);}
+ r.negative.y=(r.negativeMinY+r.negativeMaxY)*0.5;
+ r.positive.y=(r.positiveMinY+r.positiveMaxY)*0.5;
+ r.minY=min(r.minY,p.y); r.maxY=max(r.maxY,p.y);
+}
+void WaterVisualSegment(inout WaterVisualResult r,float2 q,float2 a,float2 b) {
+ float2 d=b-a; float den=dot(d,d);
+ float t=den>0?saturate(dot(q-a,d)/den):0;
+ float2 closest=a+t*d; float distance=length(q-closest);
+ if(r.hasSegment<0.5) {
+ r.closest=closest; r.distance=distance; r.positive=a; r.negative=a; r.minY=a.y; r.maxY=a.y;
+ r.positiveMinY=a.y;r.positiveMaxY=a.y;r.negativeMinY=a.y;r.negativeMaxY=a.y;
+ } else if(distance<r.distance || (distance==r.distance && WaterVisualLess(closest,r.closest))) {
+ r.closest=closest; r.distance=distance;
+ }
+ WaterVisualEndpoint(r,a); WaterVisualEndpoint(r,b); r.hasSegment=1; r.segmentCount++;
+}
+WaterVisualResult WaterVisualQuery(int hull,float3 q) {
+ WaterVisualResult r=WaterVisualEmpty();
+ if(hull<0 || hull>=8 || !all(isfinite(q)) || any(abs(q)>1e12)) return r;
+ float4 meta=VisualHullMeta[hull];
+ if(!all(isfinite(meta)) || meta.w!=1 || meta.x<0 || meta.x>64 || meta.y<0 || meta.y>96 ||
+ meta.x!=floor(meta.x) || meta.y!=floor(meta.y) || meta.z<0 || ((meta.x==0)!=(meta.y==0))) return r;
+ int nv=(int)meta.x, nt=(int)meta.y, base=hull*88;
+ [loop] for(int i=0;i<nt;++i) {
+ float packed=WaterVisualRegister(base+64+i/4)[i%4];
+ if(!isfinite(packed) || packed<0 || packed>262143 || packed!=floor(packed)) return WaterVisualEmpty();
+ int indices=(int)packed;
+ int ia=indices%64, ib=(indices/64)%64, ic=indices/4096;
+ if(ia>=nv || ib>=nv || ic>=nv) return WaterVisualEmpty();
+ float3 v[3];
+ v[0]=WaterVisualRegister(base+ia).xyz;
+ v[1]=WaterVisualRegister(base+ib).xyz;
+ v[2]=WaterVisualRegister(base+ic).xyz;
+ if(!all(isfinite(v[0])) || !all(isfinite(v[1])) || !all(isfinite(v[2])) ||
+ any(abs(v[0])>1e12) || any(abs(v[1])>1e12) || any(abs(v[2])>1e12)) return WaterVisualEmpty();
+ if(v[0].z==q.z && v[1].z==q.z && v[2].z==q.z) { r.coplanar=1; continue; }
+ float2 hit[3]; int count=0;
+ [unroll] for(int e=0;e<3;++e) {
+ float3 a=v[e],b=v[(e+1)%3]; float az=a.z-q.z,bz=b.z-q.z;
+ float2 h=0; bool have=false;
+ if(az==0) {h=a.xy;have=true;}
+ else if((az<0 && bz>0) || (az>0 && bz<0)) {
+ float t=az/(az-bz); h=a.xy+t*(b.xy-a.xy); have=true;
+ }
+ if(have) {
+ bool duplicate=false;
+ [unroll] for(int k=0;k<3;++k) if(k<count) duplicate=duplicate || all(hit[k]==h);
+ if(!duplicate) {hit[count]=h;count++;}
+ }
+ }
+ if(count==1) WaterVisualSegment(r,q.xy,hit[0],hit[0]);
+ else if(count==2) WaterVisualSegment(r,q.xy,hit[0],hit[1]);
+ else if(count>2) r.coplanar=1;
+ }
+ return r;
+}
+)hlsl"; }
+}
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterHullVisualLayout.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterHullVisualLayout.h
new file mode 100644
index 000000000..21079d4a5
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterHullVisualLayout.h
@@ -0,0 +1,28 @@
+// Bounded render-only hull mesh transport. Engine registers and native shader slots are
+// different layouts: the pixel common block extends the unchanged vertex common prefix.
+#pragma once
+namespace WaterHullVisualLayout {
+enum : unsigned {
+ MaxHulls=8, MaxVertices=64, MaxTriangles=96, RegistersPerHull=88,
+ PacketRegisters=MaxHulls*RegistersPerHull,
+ MetadataRegister=176, PacketRegister=192, PixelRegisterCount=896,
+ FragmentCommonRegisters=196, VertexCommonRegisters=188,
+ BlockCount=3, Block0Registers=256, Block1Registers=256, Block2Registers=192
+};
+constexpr unsigned BlockRegisters(unsigned block) {
+ if(block==0) return Block0Registers;
+ if(block==1) return Block1Registers;
+ if(block==2) return Block2Registers;
+ return 0;
+}
+constexpr unsigned BlockOffset(unsigned block) {
+ if(block==0) return 0;
+ if(block==1) return Block0Registers;
+ if(block==2) return Block0Registers+Block1Registers;
+ return PacketRegisters;
+}
+static_assert(RegistersPerHull==MaxVertices+MaxTriangles/4,"four packed triangle indices per float4");
+static_assert(PacketRegister+PacketRegisters==PixelRegisterCount,"bounded emulated bank");
+static_assert(Block0Registers+Block1Registers+Block2Registers==PacketRegisters,"complete packet partition");
+static_assert(VertexCommonRegisters+MaxHulls==FragmentCommonRegisters,"metadata follows original vertex prefix");
+}
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterObstacleIndex.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterObstacleIndex.h
new file mode 100644
index 000000000..27917793b
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterObstacleIndex.h
@@ -0,0 +1,85 @@
+/* Render-only broad phase. Exact shore/structure damping remains with the caller. */
+#pragma once
+#include <algorithm>
+#include <cmath>
+#include <cstddef>
+#include <cstdint>
+#include <limits>
+#include <vector>
+
+namespace WaterObstacleIndex {
+struct Influence { float x,y,radius; };
+struct Bounds { float minX,minY,maxX,maxY; };
+struct Range { const uint32_t *indices=nullptr;size_t count=0;bool indexed=false; };
+class Grid {
+public:
+ static constexpr double CellSize=64.0;
+ static constexpr size_t MaxCells=16384,MaxReferences=262144,MaxObstacles=65536;
+ void Clear() { active=false;offsets.clear();references.clear(); }
+ bool Build(const std::vector<Influence> &obstacles,Bounds bounds) {
+ Clear();
+ int lastX,lastY;
+ if (obstacles.size()>MaxObstacles || bounds.minX>bounds.maxX || bounds.minY>bounds.maxY ||
+ !Cell(bounds.minX,firstX) || !Cell(bounds.minY,firstY) || !Cell(bounds.maxX,lastX) || !Cell(bounds.maxY,lastY)) return false;
+ const int64_t width64=int64_t(lastX)-firstX+1,height64=int64_t(lastY)-firstY+1;
+ if (width64<=0 || height64<=0 || width64>int64_t(MaxCells) || height64>int64_t(MaxCells) || width64*height64>int64_t(MaxCells)) return false;
+ width=int(width64);height=int(height64);
+ struct Span { int x0,y0,x1,y1; };
+ std::vector<Span> spans;spans.reserve(obstacles.size());
+ std::vector<uint32_t> counts(size_t(width)*height,0);
+ size_t total=0;
+ for (const Influence &o:obstacles) {
+ // The exact narrow phase rejects outside float(radius+10), including its rounding.
+ // Outward nextafter makes points exactly on a cell boundary conservative too.
+ const float reach=o.radius+10.0f;
+ if (!std::isfinite(o.x) || !std::isfinite(o.y) || !std::isfinite(o.radius) || o.radius<0 || !std::isfinite(reach)) return false;
+ int x0,y0,x1,y1;
+ if (!Cell(std::nextafter(double(o.x)-reach,-std::numeric_limits<double>::infinity()),x0) ||
+ !Cell(std::nextafter(double(o.y)-reach,-std::numeric_limits<double>::infinity()),y0) ||
+ !Cell(std::nextafter(double(o.x)+reach,std::numeric_limits<double>::infinity()),x1) ||
+ !Cell(std::nextafter(double(o.y)+reach,std::numeric_limits<double>::infinity()),y1)) return false;
+ x0=(std::max)(x0,firstX);y0=(std::max)(y0,firstY);
+ x1=(std::min)(x1,lastX);y1=(std::min)(y1,lastY);
+ const size_t entries=x0<=x1 && y0<=y1 ? size_t(int64_t(x1)-x0+1)*size_t(int64_t(y1)-y0+1):0;
+ if (entries>MaxReferences-total) return false;
+ total+=entries;spans.push_back({x0,y0,x1,y1});
+ if (entries) for (int y=y0;;++y) {
+ for (int x=x0;;++x) { ++counts[size_t(y-firstY)*width+(x-firstX)];if (x==x1) break; }
+ if (y==y1) break;
+ }
+ }
+ offsets.resize(counts.size()+1);offsets[0]=0;
+ for (size_t i=0;i<counts.size();++i) offsets[i+1]=offsets[i]+counts[i];
+ references.resize(total);std::vector<uint32_t> cursor(offsets.begin(),offsets.end()-1);
+ // Iterating original indices preserves exact caller order within every bin.
+ for (size_t i=0;i<spans.size();++i) {
+ const Span &s=spans[i];if (s.x0>s.x1 || s.y0>s.y1) continue;
+ for (int y=s.y0;;++y) {
+ for (int x=s.x0;;++x) { references[cursor[size_t(y-firstY)*width+(x-firstX)]++]=uint32_t(i);if (x==s.x1) break; }
+ if (y==s.y1) break;
+ }
+ }
+ active=true;return true;
+ }
+ Range Query(float x,float y) const {
+ int cx,cy;
+ if (!active || !Cell(x,cx) || !Cell(y,cy)) return {};
+ const int64_t ix=int64_t(cx)-firstX,iy=int64_t(cy)-firstY;
+ if (ix<0 || iy<0 || ix>=width || iy>=height) return {};
+ const size_t n=size_t(iy)*width+size_t(ix),count=offsets[n+1]-offsets[n];
+ return {count?references.data()+offsets[n]:nullptr,count,true};
+ }
+ size_t ReferenceCount() const { return references.size(); }
+ size_t CellCount() const { return offsets.empty()?0:offsets.size()-1; }
+private:
+ static bool Cell(double coordinate,int &cell) {
+ if (!std::isfinite(coordinate)) return false;
+ const double value=std::floor(coordinate/CellSize);
+ if (value<double((std::numeric_limits<int>::min)()) || value>double((std::numeric_limits<int>::max)())) return false;
+ cell=int(value);return true;
+ }
+ bool active=false;
+ int firstX=0,firstY=0,width=0,height=0;
+ std::vector<uint32_t> offsets,references;
+};
+}
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterOpticalContext.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterOpticalContext.h
new file mode 100644
index 000000000..569e6a41a
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterOpticalContext.h
@@ -0,0 +1,204 @@
+/* Copyright 2026. SPDX-License-Identifier: GPL-3.0-or-later */
+#pragma once
+
+#include <algorithm>
+#include <cmath>
+#include <cstdint>
+#include <utility>
+#include <vector>
+
+// Rendering metadata only: real scene depth remains the source of refraction and intersections.
+// A broad polygon can contain both an ocean and enclosed pools, so classify its actual wet terrain.
+namespace WaterOpticalContext {
+constexpr int MaxDimension = 2048;
+constexpr size_t MaxCells = 1024u * 1024u;
+constexpr size_t MaxPoints = 65536;
+constexpr size_t MaxLevels = 8;
+// Independent physical terrain-coast distance; never packed into optical RGBA.
+constexpr float PhysicalShoreRange = 160.0f;
+struct Point { float x, y, z; };
+struct Polygon { std::vector<Point> points; };
+using Interval=std::pair<double,double>;
+// Exact scanline union, including authored edges. Shared by optical connectivity
+// and physical coastal domains so a sub-grid polygon gap never becomes a wet link.
+inline std::vector<Interval> Intervals(const std::vector<Polygon>&polygons,
+ double level,double line,bool horizontal) {
+ std::vector<Interval> spans;std::vector<double> crossings;
+ for(const auto&polygon:polygons) {
+ if(polygon.points.size()<3)continue;
+ bool same=true;for(const auto&p:polygon.points)same=same&&std::abs(double(p.z)-level)<.01;
+ if(!same)continue;
+ crossings.clear();
+ for(size_t i=0,j=polygon.points.size()-1;i<polygon.points.size();j=i++) {
+ const auto&a=polygon.points[i];const auto&b=polygon.points[j];
+ const double ax=horizontal?a.x:a.y,ay=horizontal?a.y:a.x;
+ const double bx=horizontal?b.x:b.y,by=horizontal?b.y:b.x;
+ if((ay>line)!=(by>line))crossings.push_back(ax+(line-ay)*(bx-ax)/(by-ay));
+ if(ay==line){spans.push_back({ax,ax});if(by==line)spans.push_back({(std::min)(ax,bx),(std::max)(ax,bx)});}
+ }
+ std::sort(crossings.begin(),crossings.end());
+ for(size_t i=0;i+1<crossings.size();i+=2)spans.push_back({crossings[i],crossings[i+1]});
+ }
+ std::sort(spans.begin(),spans.end());std::vector<Interval> result;
+ for(auto span:spans) {
+ if(result.empty()||span.first>result.back().second)result.push_back(span);
+ else result.back().second=(std::max)(result.back().second,span.second);
+ }
+ return result;
+}
+struct Field {
+ std::vector<uint8_t> ocean;
+ std::vector<uint8_t> shore;
+ std::vector<uint8_t> exposure; // wet region connected to the playable map boundary
+ std::vector<uint8_t> physicalShore; // 0..PhysicalShoreRange, terrain only; polygon edges are excluded
+ std::vector<uint8_t> coast; // terrain-coast replacement validity, inset from every nonzero ocean texel
+};
+inline uint32_t Texel(const Field &field,size_t n) {
+ return (uint32_t(field.coast[n])<<24)|(uint32_t(field.ocean[n])<<16)
+ |(uint32_t(field.shore[n])<<8)|uint32_t(field.exposure[n]);
+}
+
+inline float Offshore(float distance) {
+ float t = (std::max)(0.0f, (std::min)(1.0f, (distance - 30.0f) / 70.0f));
+ return t*t*(3.0f-2.0f*t);
+}
+
+inline bool SamePolygons(const std::vector<Polygon>& a, const std::vector<Polygon>& b) {
+ if (a.size() != b.size()) return false;
+ for (size_t i=0; i<a.size(); ++i) {
+ if (a[i].points.size() != b[i].points.size()) return false;
+ for (size_t j=0; j<a[i].points.size(); ++j) {
+ const Point &p=a[i].points[j], &q=b[i].points[j];
+ if (p.x!=q.x || p.y!=q.y || p.z!=q.z) return false;
+ }
+ }
+ return true;
+}
+
+inline bool Build(const uint8_t* heights, int width, int height, int border,
+ float spacing, float heightScale, float level,
+ const std::vector<Polygon>& polygons, Field& result) {
+ result.ocean.clear(); result.shore.clear(); result.exposure.clear(); result.coast.clear(); result.physicalShore.clear();
+ if (!heights || width<2 || height<2 || width>MaxDimension || height>MaxDimension ||
+ size_t(width)*height>MaxCells || border<0 || border>(width-2)/2 || border>(height-2)/2 ||
+ !std::isfinite(spacing) || spacing<=0 || !std::isfinite(heightScale) || heightScale<=0 ||
+ !std::isfinite(level) || polygons.size()>MaxPoints/3) return false;
+ size_t points=0;
+ for (const Polygon& polygon : polygons) {
+ if (polygon.points.size()>MaxPoints-points) return false;
+ points+=polygon.points.size();
+ for (const Point& p : polygon.points)
+ if (!std::isfinite(p.x) || !std::isfinite(p.y) || !std::isfinite(p.z)) return false;
+ }
+ const size_t count=size_t(width)*height;
+ enum : uint8_t {PositiveX=1,PositiveY=2};
+ std::vector<uint8_t> wet(count,0),links(count,0),wetColumn(size_t(width),0);
+ auto span = [&](int y,double from,double to) {
+ const int left=int((std::max)(0.0,(std::min)(double(width),std::ceil(from/spacing+border))));
+ const int right=int((std::max)(-1.0,(std::min)(double(width-1),std::floor(to/spacing+border))));
+ for (int x=left; x<=right; ++x) {
+ const size_t n=size_t(y)*width+x;
+ if (heights[n]*heightScale<level) { wet[n]=1;wetColumn[size_t(x)]=1; }
+ if (x<right) links[n]|=PositiveX;
+ }
+ };
+ // Scanline intervals form the union, including concave polygons and overlaps. Only flat,
+ // non-river polygons at this level enter the caller's list; different levels never connect.
+ for (int y=0;y<height;++y)
+ for (const auto &interval:Intervals(polygons,level,(y-border)*spacing,true))
+ span(y,interval.first,interval.second);
+ // Record complete covered segments once, with bounded scanline storage. The flood
+ // never scans polygons per cell, and overlapping spans can jointly cover one link.
+ for (int x=0;x<width;++x) if(wetColumn[size_t(x)])
+ for (const auto &interval:Intervals(polygons,level,(x-border)*spacing,false)) {
+ const int first=int((std::max)(0.0,(std::min)(double(height),std::ceil(interval.first/spacing+border))));
+ const int last=int((std::max)(-1.0,(std::min)(double(height-1),std::floor(interval.second/spacing+border))));
+ for(int y=first;y<last;++y)links[size_t(y)*width+x]|=PositiveY;
+ }
+ result.ocean.assign(count,0);
+ result.shore.assign(count,0);
+ std::vector<int> queue; queue.reserve(count);
+ auto seed = [&](int x,int y) {
+ const int n=y*width+x;
+ if (wet[n] && !result.ocean[n]) { result.ocean[n]=1; queue.push_back(n); }
+ };
+ // Playable boundary, not texture padding or polygon bounds, defines connection to open water.
+ for (int x=border; x<width-border; ++x) { seed(x,border); seed(x,height-border-1); }
+ for (int y=border; y<height-border; ++y) { seed(border,y); seed(width-border-1,y); }
+ for (size_t i=0; i<queue.size(); ++i) {
+ const int n=queue[i], x=n%width,y=n/width;
+ if (x>0 && (links[n-1]&PositiveX)) seed(x-1,y);
+ if (x+1<width && (links[n]&PositiveX)) seed(x+1,y);
+ if (y>0 && (links[n-width]&PositiveY)) seed(x,y-1);
+ if (y+1<height && (links[n]&PositiveY)) seed(x,y+1);
+ }
+ result.exposure=result.ocean;
+ for(uint8_t &value:result.exposure)value=value?255:0;
+ result.coast.assign(count,0);
+ result.physicalShore.assign(count,255);
+ // Two-pass chamfer distance is bounded O(cells), with diagonal distances avoiding a square
+ // shoreline fade. Grid borders are not synthetic shores; an entirely wet sea has full extent.
+ const float limit=100.0f, diagonal=spacing*1.41421356237f;
+ std::vector<float> distance(count,limit),terrainDistance(count,PhysicalShoreRange);
+ for (size_t n=0; n<count; ++n) {
+ if (!wet[n]) distance[n]=0;
+ // Authored polygon boundaries over submerged terrain are not physical coasts.
+ if (heights[n]*heightScale>=level) terrainDistance[n]=0;
+ }
+ auto relax = [&](int n,int neighbour,float step) {
+ distance[n]=(std::min)(distance[n],distance[neighbour]+step);
+ terrainDistance[n]=(std::min)(terrainDistance[n],terrainDistance[neighbour]+step);
+ };
+ for (int y=0; y<height; ++y) for (int x=0; x<width; ++x) {
+ const int n=y*width+x;
+ if (x>0) relax(n,n-1,spacing);
+ if (y>0) {
+ relax(n,n-width,spacing);
+ if (x>0) relax(n,n-width-1,diagonal);
+ if (x+1<width) relax(n,n-width+1,diagonal);
+ }
+ }
+ for (int y=height-1; y>=0; --y) for (int x=width-1; x>=0; --x) {
+ const int n=y*width+x;
+ if (x+1<width) relax(n,n+1,spacing);
+ if (y+1<height) {
+ relax(n,n+width,spacing);
+ if (x>0) relax(n,n+width-1,diagonal);
+ if (x+1<width) relax(n,n+width+1,diagonal);
+ }
+ result.physicalShore[n]=uint8_t(terrainDistance[n]/PhysicalShoreRange*255.0f+0.5f);
+ result.shore[n]=uint8_t(distance[n]/limit*255.0f+0.5f);
+ result.ocean[n]=result.ocean[n] ? uint8_t(Offshore(distance[n])*255.0f+0.5f) : 0;
+ }
+ // Analytic shore-foam validity stays inset from every nonzero-R texel. The shader
+ // also fades this fallback by the remaining analytic wave contribution when FFT
+ // phases extend into exposed shallows, and repeats the zero-R resource guard.
+ for(int y=0;y<height;++y)for(int x=0;x<width;++x) {
+ const size_t n=size_t(y)*width+x;
+ if(terrainDistance[n]>=20.0f)continue;
+ bool adjacentWet=wet[n]!=0,exposed=result.exposure[n]!=0,enclosedWet=false;
+ for(int yy=(std::max)(0,y-1);yy<=(std::min)(height-1,y+1);++yy)
+ for(int xx=(std::max)(0,x-1);xx<=(std::min)(width-1,x+1);++xx) {
+ const size_t neighbour=size_t(yy)*width+xx;
+ adjacentWet=adjacentWet || wet[neighbour]!=0;
+ exposed=exposed || (wet[neighbour] && result.exposure[neighbour]!=0);
+ enclosedWet=enclosedWet || (wet[neighbour] && result.exposure[neighbour]==0);
+ }
+ if(!adjacentWet)continue;
+ bool analytic=true;
+ for(int yy=(std::max)(0,y-1);yy<=(std::min)(height-1,y+1);++yy)
+ for(int xx=(std::max)(0,x-1);xx<=(std::min)(width-1,x+1);++xx)
+ analytic=analytic && result.ocean[size_t(yy)*width+xx]==0;
+ if(!analytic)continue;
+ // Replacement validity must include the actual crossing between a dry terrain node
+ // and the first wet one. Wet-only A would retain most of the permanent rim there.
+ // Emission is independently gated by positive terrain depth and actual scene wetness.
+ // Dry exposure supports the ordinary wet-edge transition, but must not
+ // interpolate an ocean wave into an enclosed pool across a narrow ridge.
+ if(!wet[n])result.exposure[n]=exposed&&!enclosedWet?255:0;
+ const float t=(std::max)(0.0f,(std::min)(1.0f,(terrainDistance[n]-10.0f)/10.0f));
+ result.coast[n]=uint8_t((1.0f-t*t*(3.0f-2.0f*t))*255.0f+0.5f);
+ }
+ return true;
+}
+}
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterOpticalModel.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterOpticalModel.h
new file mode 100644
index 000000000..e11b63c20
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterOpticalModel.h
@@ -0,0 +1,141 @@
+/* Water light transport shared by generated HLSL and its numerical regression checks. */
+#pragma once
+#include <algorithm>
+#include <cmath>
+
+// Keep the existing shallow-water spectrum and its standing-water path scale in one definition.
+#define WATER_OPTICAL_CONSTANTS(X) X(0.065f, 0.026f, 0.019f, 2.4f, 0.25f, 0.01f, 80.0f, 1.0e20f)
+#define WATER_OPTICAL_RAY_CONSTANTS(X) X(0.2f, 0.08f, 2.0f)
+
+// Clear/coastal and river retain their current source; ocean retains the current FFT endpoint.
+// These source-function radiances are linear RGB. River extinction remains independently defined.
+#define WATER_OPTICAL_SOURCE_PRESETS(X) X(0.002f,0.028f,0.041f, 0.002f,0.028f,0.041f, 0.002f,0.035f,0.075f, 0.08f,0.40f,1.80f)
+
+namespace WaterOpticalModel {
+struct RGB { float r,g,b; };
+#define WATER_OPTICAL_CPP_CONSTANTS(red,green,blue,standing,minDepth,minTransmission,maxExponent,maxFinite) \
+ constexpr RGB BaseExtinction={red,green,blue}; \
+ constexpr float StandingPathScale=standing,MinimumReferenceDepth=minDepth; \
+ constexpr float MinimumReferenceTransmission=minTransmission,MaximumExponent=maxExponent,MaximumFiniteInput=maxFinite;
+WATER_OPTICAL_CONSTANTS(WATER_OPTICAL_CPP_CONSTANTS)
+#undef WATER_OPTICAL_CPP_CONSTANTS
+#define WATER_OPTICAL_RAY_CPP_CONSTANTS(grazing,margin,boundScale) \
+ constexpr float RayMinimumViewZ=grazing,RaySurfaceMargin=margin,RayHeightBoundScale=boundScale;
+WATER_OPTICAL_RAY_CONSTANTS(WATER_OPTICAL_RAY_CPP_CONSTANTS)
+#undef WATER_OPTICAL_RAY_CPP_CONSTANTS
+
+// Comparisons also define a deterministic NaN/Infinity policy in both languages: NaN and negative
+// path/weights become zero, positive infinity saturates, and invalid reference depth uses 0.25.
+inline float Unit(float value) { return value>=0.0f?std::min(value,1.0f):0.0f; }
+inline float Path(float value) { return value>=0.0f?std::min(value,MaximumFiniteInput):0.0f; }
+inline float ReferenceDepth(float value) {
+ return value>=MinimumReferenceDepth?std::min(value,MaximumFiniteInput):MinimumReferenceDepth;
+}
+// Positive movement is toward the camera along its normalized view ray. A finer optical surface
+// may correct raster interpolation, but must never pass the actual scene hit or the camera. The
+// original raster surface is retained for clear water, below-surface views and invalid directions.
+inline float RayShift(float heightDelta,float viewZ,float offshoreFactor,float displacementBound,
+ float sceneRayDistance,float cameraDistance) {
+ if (!(offshoreFactor>0.0f) || !(viewZ>0.0f) || !(viewZ<=MaximumFiniteInput)
+ || !(std::abs(heightDelta)<=MaximumFiniteInput)) return 0.0f;
+ const float bound=RayHeightBoundScale*Path(displacementBound);
+ const float shift=Unit(offshoreFactor)*std::max(-bound,std::min(heightDelta,bound))
+ /std::max(viewZ,RayMinimumViewZ);
+ const float sceneLimit=std::max(Path(sceneRayDistance)-RaySurfaceMargin,0.0f);
+ const float cameraLimit=std::max(Path(cameraDistance)-RaySurfaceMargin,0.0f);
+ return std::max(-sceneLimit,std::min(shift,cameraLimit));
+}
+inline float OffshoreExtinction(float transparentDepth,float minOpacity) {
+ const float remaining=std::max(1.0f-Unit(minOpacity),MinimumReferenceTransmission);
+ return -std::log(remaining)/ReferenceDepth(transparentDepth);
+}
+inline RGB Transmission(float path,float riverBlend,float offshoreFactor,float referenceDepth,float opacity) {
+ path=Path(path);
+ const float materialPath=path*(StandingPathScale+(1.0f-StandingPathScale)*Unit(riverBlend));
+ // Authored opacity describes extinction per physical world distance. Applying the legacy
+ // standing-water multiplier to this term a second time would obscure shallow seas too much.
+ const float authored=path*Unit(offshoreFactor)*OffshoreExtinction(referenceDepth,opacity);
+ return {std::exp(-std::min(materialPath*BaseExtinction.r+authored,MaximumExponent)),
+ std::exp(-std::min(materialPath*BaseExtinction.g+authored,MaximumExponent)),
+ std::exp(-std::min(materialPath*BaseExtinction.b+authored,MaximumExponent))};
+}
+// Source-function radiances in linear RGB; these are not extinction coefficients.
+#define WATER_OPTICAL_SOURCE_CPP(clearR,clearG,clearB,riverR,riverG,riverB,oceanR,oceanG,oceanB,ambient,faceMin,faceRange) \
+ constexpr RGB ClearSource={clearR,clearG,clearB},RiverSource={riverR,riverG,riverB},OceanSource={oceanR,oceanG,oceanB}; \
+ constexpr float SourceAmbient=ambient,SourceFaceMinimum=faceMin,SourceFaceRange=faceRange;
+WATER_OPTICAL_SOURCE_PRESETS(WATER_OPTICAL_SOURCE_CPP)
+#undef WATER_OPTICAL_SOURCE_CPP
+inline float SourceOffshore(float riverBlend,float effectiveOffshore) {
+ // The caller has already excluded the river share from offshore. Cap malformed overlap;
+ // multiplying by (1-river) here would apply that gate twice at continuous transitions.
+ return std::min(Unit(effectiveOffshore),1.0f-Unit(riverBlend));
+}
+inline RGB MaterialSource(float riverBlend,float effectiveOffshore) {
+ const float river=Unit(riverBlend),offshore=SourceOffshore(river,effectiveOffshore);
+ // Convex context weights are clear=(1-river-offshore), river, and offshore. Nearshore
+ // connected water blends from clear to ocean; enclosed pools retain the clear endpoint.
+ return {ClearSource.r+(RiverSource.r-ClearSource.r)*river+(OceanSource.r-ClearSource.r)*offshore,
+ ClearSource.g+(RiverSource.g-ClearSource.g)*river+(OceanSource.g-ClearSource.g)*offshore,
+ ClearSource.b+(RiverSource.b-ClearSource.b)*river+(OceanSource.b-ClearSource.b)*offshore};
+}
+inline RGB ScatteringSource(float riverBlend,float effectiveOffshore,float daylight,float faceLight) {
+ const RGB material=MaterialSource(riverBlend,effectiveOffshore);
+ const float light=SourceAmbient+(1.0f-SourceAmbient)*Unit(daylight);
+ const float face=1.0f+SourceOffshore(riverBlend,effectiveOffshore)
+ *(SourceFaceMinimum+SourceFaceRange*Unit(faceLight)-1.0f);
+ return {material.r*light*face,material.g*light*face,material.b*light*face};
+}
+inline RGB Body(RGB scene,RGB transmission,RGB source,float caustic,float sceneAvailable) {
+ const RGB integrated={scene.r*transmission.r*caustic+source.r*(1.0f-transmission.r),
+ scene.g*transmission.g*caustic+source.g*(1.0f-transmission.g),
+ scene.b*transmission.b*caustic+source.b*(1.0f-transmission.b)};
+ const float available=Unit(sceneAvailable);
+ return {source.r+(integrated.r-source.r)*available,source.g+(integrated.g-source.g)*available,
+ source.b+(integrated.b-source.b)*available};
+}
+
+inline const char *GetHlslSource() {
+#define WATER_OPTICAL_HLSL(red,green,blue,standing,minDepth,minTransmission,maxExponent,maxFinite) \
+ "static const float WaterOpticalMaximumFiniteInput=" #maxFinite ";\n" \
+ "float WaterOpticalUnit(float v) { return v>=0.0?min(v,1.0):0.0; }\n" \
+ "float WaterOpticalPath(float v) { return v>=0.0?min(v," #maxFinite "):0.0; }\n" \
+ "float WaterOpticalOffshoreExtinction(float depth,float opacity) {\n" \
+ " float reference=depth>=" #minDepth "?min(depth," #maxFinite "):" #minDepth ";\n" \
+ " return -log(max(1.0-WaterOpticalUnit(opacity)," #minTransmission "))/reference; }\n" \
+ "float3 WaterOpticalTransmission(float path,float riverBlend,float offshoreFactor,float referenceDepth,float opacity) {\n" \
+ " path=WaterOpticalPath(path);\n" \
+ " float materialPath=path*(" #standing "+(1.0-" #standing ")*WaterOpticalUnit(riverBlend));\n" \
+ " float authored=path*WaterOpticalUnit(offshoreFactor)*WaterOpticalOffshoreExtinction(referenceDepth,opacity);\n" \
+ " float3 exponent=materialPath*float3(" #red "," #green "," #blue ")+authored;\n" \
+ " return exp(-min(exponent,float3(" #maxExponent "," #maxExponent "," #maxExponent "))); }\n"
+#define WATER_OPTICAL_RAY_HLSL(grazing,margin,boundScale) \
+ "float WaterOpticalRayShift(float heightDelta,float viewZ,float offshoreFactor,float displacementBound,float sceneRayDistance,float cameraDistance) {\n" \
+ " if (!(offshoreFactor>0.0) || !(viewZ>0.0) || !(viewZ<=WaterOpticalMaximumFiniteInput) || !(abs(heightDelta)<=WaterOpticalMaximumFiniteInput)) return 0.0;\n" \
+ " float bound=" #boundScale "*WaterOpticalPath(displacementBound);\n" \
+ " float shift=WaterOpticalUnit(offshoreFactor)*clamp(heightDelta,-bound,bound)/max(viewZ," #grazing ");\n" \
+ " float sceneLimit=max(WaterOpticalPath(sceneRayDistance)-" #margin ",0.0);\n" \
+ " float cameraLimit=max(WaterOpticalPath(cameraDistance)-" #margin ",0.0);\n" \
+ " return clamp(shift,-sceneLimit,cameraLimit); }\n"
+#define WATER_OPTICAL_SOURCE_HLSL(clearR,clearG,clearB,riverR,riverG,riverB,oceanR,oceanG,oceanB,ambient,faceMin,faceRange) \
+ "float WaterOpticalSourceOffshore(float riverBlend,float effectiveOffshore) {\n" \
+ " return min(WaterOpticalUnit(effectiveOffshore),1.0-WaterOpticalUnit(riverBlend)); }\n" \
+ "float3 WaterOpticalMaterialSource(float riverBlend,float effectiveOffshore) {\n" \
+ " float river=WaterOpticalUnit(riverBlend),offshore=WaterOpticalSourceOffshore(river,effectiveOffshore);\n" \
+ " float3 clearSource=float3(" #clearR "," #clearG "," #clearB ");\n" \
+ " float3 riverSource=float3(" #riverR "," #riverG "," #riverB ");\n" \
+ " float3 oceanSource=float3(" #oceanR "," #oceanG "," #oceanB ");\n" \
+ " return clearSource+(riverSource-clearSource)*river+(oceanSource-clearSource)*offshore; }\n" \
+ "float3 WaterOpticalScatteringSource(float riverBlend,float effectiveOffshore,float daylight,float faceLight) {\n" \
+ " float illumination=" #ambient "+(1.0-" #ambient ")*WaterOpticalUnit(daylight);\n" \
+ " float face=1.0+WaterOpticalSourceOffshore(riverBlend,effectiveOffshore)*(" #faceMin "+" #faceRange "*WaterOpticalUnit(faceLight)-1.0);\n" \
+ " return WaterOpticalMaterialSource(riverBlend,effectiveOffshore)*illumination*face; }\n" \
+ "float3 WaterOpticalBody(float3 scene,float3 transmission,float3 source,float caustic,float sceneAvailable) {\n" \
+ " return lerp(source,scene*transmission*caustic+source*(1.0-transmission),WaterOpticalUnit(sceneAvailable)); }\n"
+
+ return WATER_OPTICAL_CONSTANTS(WATER_OPTICAL_HLSL) WATER_OPTICAL_RAY_CONSTANTS(WATER_OPTICAL_RAY_HLSL)
+ WATER_OPTICAL_SOURCE_PRESETS(WATER_OPTICAL_SOURCE_HLSL);
+#undef WATER_OPTICAL_SOURCE_HLSL
+#undef WATER_OPTICAL_RAY_HLSL
+#undef WATER_OPTICAL_HLSL
+}
+}
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterProjectedMesh.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterProjectedMesh.h
new file mode 100644
index 000000000..85a297db5
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterProjectedMesh.h
@@ -0,0 +1,329 @@
+/* Render-only projected water lattice. No simulation or map data is modified. */
+#pragma once
+#include <algorithm>
+#include <cmath>
+#include <cstdint>
+#include <cstring>
+#include <unordered_map>
+#include <vector>
+
+namespace WaterProjectedMesh {
+struct Point { double x,y; };
+struct Plane { double a,b,c; };
+inline bool HasSingleLevel(const float levels[4]) {
+ if (!std::isfinite(levels[0])) return false;
+ for (int i=1;i<4;++i) if (levels[i]!=levels[0]) return false;
+ return true;
+}
+struct Projection {
+ // (clip x, clip y, clip w) = matrix * (world x, world y, 1), at the water level.
+ double matrix[9], inverse[9];
+ Plane depth;
+ double nearDistance,farDistance,margin;
+ bool Prepare() {
+ const double *m=matrix;
+ const double d=m[0]*(m[4]*m[8]-m[5]*m[7])-m[1]*(m[3]*m[8]-m[5]*m[6])+m[2]*(m[3]*m[7]-m[4]*m[6]);
+ if (!std::isfinite(d) || std::abs(d)<1e-12) return false;
+ const double adj[9]={m[4]*m[8]-m[5]*m[7],m[2]*m[7]-m[1]*m[8],m[1]*m[5]-m[2]*m[4],
+ m[5]*m[6]-m[3]*m[8],m[0]*m[8]-m[2]*m[6],m[2]*m[3]-m[0]*m[5],
+ m[3]*m[7]-m[4]*m[6],m[1]*m[6]-m[0]*m[7],m[0]*m[4]-m[1]*m[3]};
+ for (int i=0;i<9;++i) inverse[i]=adj[i]/d;
+ return nearDistance>0 && farDistance>nearDistance && margin>=0 && std::isfinite(margin);
+ }
+ bool Transform(Point p,Point &out,bool backwards=false) const {
+ const double *m=backwards?inverse:matrix;
+ const double w=m[6]*p.x+m[7]*p.y+m[8];
+ if (!std::isfinite(w) || std::abs(w)<1e-12) return false;
+ out={(m[0]*p.x+m[1]*p.y+m[2])/w,(m[3]*p.x+m[4]*p.y+m[5])/w};
+ return std::isfinite(out.x) && std::isfinite(out.y);
+ }
+};
+struct Polygon { Point points[20]; int count=0; };
+inline double Distance(const Plane &plane,Point p) { return plane.a*p.x+plane.b*p.y+plane.c; }
+inline Point Intersection(Point a,Point b,const Plane &plane) {
+ // Canonical endpoint order makes reversed shared polygon boundaries yield the same result.
+ if (a.x>b.x || (a.x==b.x && a.y>b.y)) { const Point c=a;a=b;b=c; }
+ const double da=Distance(plane,a),db=Distance(plane,b),t=da/(da-db);
+ Point p={a.x+(b.x-a.x)*t,a.y+(b.y-a.y)*t};
+ // Axis clips produce exact lattice coordinates, including at a lattice corner.
+ if (plane.b==0 && plane.a!=0) p.x=-plane.c/plane.a;
+ if (plane.a==0 && plane.b!=0) p.y=-plane.c/plane.b;
+ return p;
+}
+inline bool Clip(Polygon &polygon,const Plane &plane) {
+ if (!polygon.count) return true;
+ Polygon result;
+ Point previous=polygon.points[polygon.count-1]; double previousDistance=Distance(plane,previous);
+ for (int i=0;i<polygon.count;++i) {
+ const Point current=polygon.points[i]; const double currentDistance=Distance(plane,current);
+ if ((currentDistance>=0)!=(previousDistance>=0)) {
+ if (result.count>=20) return false;
+ result.points[result.count++]=Intersection(previous,current,plane);
+ }
+ if (currentDistance>=0) {
+ if (result.count>=20) return false;
+ result.points[result.count++]=current;
+ }
+ previous=current;previousDistance=currentDistance;
+ }
+ polygon=result;return true;
+}
+inline size_t VertexBound(int columns,int rows,size_t boundaryKnots=0) {
+ // A convex boundary crosses each lattice line at most twice. Extra slack covers frustum
+ // clipping corners and one centre per clipped cell; lattice interior vertices are shared.
+ return size_t(columns+1)*(rows+1)+6u*(columns+rows+4)+boundaryKnots;
+}
+struct Resolution { int columns,rows; };
+inline Resolution ChooseResolution(int width,int height,int flatPatches,size_t available,size_t boundaryKnots=0) {
+ Resolution r={(std::max)(8,(std::min)(192,(width+7)/8)),(std::max)(8,(std::min)(128,(height+7)/8))};
+ const size_t share=available/size_t((std::max)(1,flatPatches));
+ while (VertexBound(r.columns,r.rows,boundaryKnots)>(std::min)(size_t(60000),share) && (r.columns>2 || r.rows>2)) {
+ r.columns=(std::max)(2,r.columns/2);r.rows=(std::max)(2,r.rows/2);
+ }
+ return r;
+}
+constexpr double CollarWidth=12.0;
+struct BoundaryCollar {
+ int count=0,edge[4];double parameter[4],weight[4],fade=0;
+ void Add(int index,double parameterValue,double distanceSquared) {
+ if (distanceSquared>=CollarWidth*CollarWidth) return;
+ double t=1-std::sqrt(distanceSquared)/CollarWidth;t=t*t*(3-2*t);
+ edge[count]=index;parameter[count]=parameterValue;
+ weight[count++]=t/(distanceSquared+1e-12);fade=(std::max)(fade,t);
+ }
+ void Normalize() {
+ double sum=0;for (int i=0;i<count;++i) sum+=weight[i];
+ if (sum>0) for (int i=0;i<count;++i) weight[i]*=fade/sum;
+ }
+};
+inline BoundaryCollar CollarAt(const Point corners[4],Point p) {
+ BoundaryCollar collar;
+ for (int edge=0;edge<4;++edge) {
+ Point a=corners[edge],b=corners[(edge+1)%4];
+ if (a.x>b.x || (a.x==b.x && a.y>b.y)) std::swap(a,b);
+ const double dx=b.x-a.x,dy=b.y-a.y,len2=dx*dx+dy*dy;
+ if (len2<1e-12) continue;
+ const double t=(std::max)(0.0,(std::min)(1.0,((p.x-a.x)*dx+(p.y-a.y)*dy)/len2));
+ const double ex=p.x-a.x-dx*t,ey=p.y-a.y-dy*t;
+ collar.Add(edge,t,ex*ex+ey*ey);
+ }
+ collar.Normalize();return collar;
+}
+struct Vertex { Point world; int boundary=-1; double edgeParameter=0; int knot=-1; int transition=-1; int collar=-1; int lattice=-1; };
+struct BoundaryKnot { Point world; int boundary,index; double edgeParameter; };
+// A clipped cell always has the same centre fan, whether or not it currently contains an edge
+// knot. As clipping vanishes, its centre approaches the regular cell's diagonal and its height
+// approaches that diagonal's interpolation. The full-cell path can then omit it continuously.
+struct CentreTransition { Point source[3]; double weight[3]; double analytic; };
+inline bool NormalizeCentreWeights(double weight[3]) {
+ // Inverse-projecting a reference corner across the horizon reverses its homogeneous sign.
+ // Such a triangle does not contain the visible centre, even if its screen triangle does.
+ // Only convex interpolation preserves the displacement bound; repair roundoff, not geometry.
+ for (int i=0;i<3;++i)
+ if (!std::isfinite(weight[i]) || weight[i]<-1e-10 || weight[i]>1+1e-10) return false;
+ double sum=0;for (int i=0;i<3;++i) { weight[i]=(std::max)(0.0,(std::min)(1.0,weight[i]));sum+=weight[i]; }
+ if (!(sum>0)) return false;
+ for (int i=0;i<3;++i) weight[i]/=sum;
+ return true;
+}
+inline double InterpolateCentre(const CentreTransition &transition,double analytic,const double source[3]) {
+ const double linear=source[0]*transition.weight[0]+source[1]*transition.weight[1]+source[2]*transition.weight[2];
+ return linear+(analytic-linear)*transition.analytic;
+}
+struct Mesh { std::vector<Vertex> vertices; std::vector<uint16_t> indices; std::vector<CentreTransition> transitions; std::vector<BoundaryCollar> collars; size_t cells=0; };
+struct Key { uint64_t x,y; bool operator==(const Key &other) const { return x==other.x && y==other.y; } };
+struct Hash { size_t operator()(const Key &key) const { return size_t(key.x^(key.y+0x9e3779b97f4a7c15ull+(key.x<<6)+(key.x>>2))); } };
+struct WorldKey { uint32_t x,y,z; bool operator==(const WorldKey &o) const { return x==o.x && y==o.y && z==o.z; } };
+struct WorldHash { size_t operator()(const WorldKey &k) const { return size_t(k.x)*73856093u^size_t(k.y)*19349663u^size_t(k.z)*83492791u; } };
+inline WorldKey SampleKey(float x,float y,float z) {
+ WorldKey k;if (x==0) x=0;if (y==0) y=0;if (z==0) z=0;
+ std::memcpy(&k.x,&x,4);std::memcpy(&k.y,&y,4);std::memcpy(&k.z,&z,4);return k;
+}
+inline Key PointKey(Point p) {
+ Key key; if (p.x==0) p.x=0; if (p.y==0) p.y=0;
+ std::memcpy(&key.x,&p.x,8);std::memcpy(&key.y,&p.y,8);return key;
+}
+inline bool Build(const Point corners[4],const Projection &projection,Resolution resolution,Mesh &mesh,size_t budget=60000,const std::vector<BoundaryKnot> &knots={},bool useLatticeCache=true) {
+ mesh.vertices.clear();mesh.indices.clear();mesh.transitions.clear();mesh.collars.clear();mesh.cells=0;
+ if (resolution.columns<2 || resolution.rows<2 || VertexBound(resolution.columns,resolution.rows,knots.size())>budget || budget>65535) return false;
+ // Convex water patches (including a repeated final triangle corner) are supported.
+ // Concave authored geometry retains the legacy renderer instead of losing coverage.
+ double orientation=0;
+ for (int i=0;i<4;++i) {
+ const Point a=corners[i],b=corners[(i+1)%4],c=corners[(i+2)%4];
+ const double turn=(b.x-a.x)*(c.y-b.y)-(b.y-a.y)*(c.x-b.x);
+ if (!std::isfinite(turn)) return false;
+ if (std::abs(turn)>1e-10) { if (orientation*turn<0) return false;orientation=turn; }
+ }
+ if (orientation==0) return false;
+ struct ScreenKnot { Point screen; const BoundaryKnot *source; };
+ std::vector<ScreenKnot> screenKnots;screenKnots.reserve(knots.size());
+ for (const BoundaryKnot &k:knots) {
+ Point screen;
+ if (Distance(projection.depth,k.world)>=projection.nearDistance &&
+ Distance(projection.depth,k.world)<=projection.farDistance && projection.Transform(k.world,screen))
+ screenKnots.push_back({screen,&k});
+ }
+ Polygon footprint;for (int i=0;i<4;++i) footprint.points[footprint.count++]=corners[i];
+ if (!Clip(footprint,{projection.depth.a,projection.depth.b,projection.depth.c-projection.nearDistance}) ||
+ !Clip(footprint,{-projection.depth.a,-projection.depth.b,projection.farDistance-projection.depth.c})) return false;
+ const double limit=1+projection.margin;
+ for (int axis=0;axis<2;++axis) for (int sign:{-1,1}) {
+ const double *m=projection.matrix;
+ if (!Clip(footprint,{limit*m[6]+sign*m[axis*3],limit*m[7]+sign*m[axis*3+1],limit*m[8]+sign*m[axis*3+2]})) return false;
+ }
+ if (footprint.count<3) return true;
+ for (int i=0;i<footprint.count;++i) {
+ Point screen;if (!projection.Transform(footprint.points[i],screen)) return false;
+ footprint.points[i]=screen;
+ }
+ double area=0;for (int i=0,j=footprint.count-1;i<footprint.count;j=i++) area+=footprint.points[j].x*footprint.points[i].y-footprint.points[i].x*footprint.points[j].y;
+ if (std::abs(area)<1e-14) return true;
+ if (area<0) { std::reverse(footprint.points,footprint.points+footprint.count);area=-area; }
+ Plane boundary[20];
+ for (int i=0,j=footprint.count-1;i<footprint.count;j=i++) {
+ const Point a=footprint.points[j],b=footprint.points[i]; const double orientation=area>0?1:-1;
+ boundary[i]={orientation*(a.y-b.y),orientation*(b.x-a.x),orientation*(a.x*b.y-b.x*a.y)};
+ }
+ mesh.vertices.reserve(VertexBound(resolution.columns,resolution.rows,knots.size()));
+ mesh.indices.reserve(size_t(resolution.columns)*resolution.rows*6+18u*(resolution.columns+resolution.rows+4)+knots.size()*6);
+ std::unordered_map<Key,uint16_t,Hash> known;
+ known.reserve(useLatticeCache?6u*(resolution.columns+resolution.rows+4)+knots.size():VertexBound(resolution.columns,resolution.rows));
+ // Integer slots replace repeated hashing for exact regular lattice corners. Every clipped
+ // corner uses the same slots; genuinely new boundary intersections retain canonical keys.
+ // The switch exists for an exact reference-regression comparison, not runtime quality.
+ std::vector<int> lattice(useLatticeCache?size_t(resolution.columns+1)*(resolution.rows+1):0,-1);
+ auto append=[&](Point screen,uint16_t &index,const BoundaryKnot *knot=nullptr,int slot=-1) {
+ const int logicalSlot=slot;
+ if (!useLatticeCache) slot=-1;
+ const Key key=PointKey(screen);
+ const auto found=slot<0?known.find(key):known.end();
+ if ((slot>=0 && lattice[slot]>=0) || found!=known.end()) {
+ index=slot>=0?uint16_t(lattice[slot]):found->second;
+ if (knot) mesh.vertices[index]={knot->world,knot->boundary,knot->edgeParameter,knot->index};
+ return true;
+ }
+ Vertex vertex;vertex.lattice=logicalSlot;if (!projection.Transform(screen,vertex.world,true)) return false;
+ BoundaryCollar collar;
+ for (int edge=0;edge<4;++edge) {
+ Point a=corners[edge],b=corners[(edge+1)%4];
+ if (a.x>b.x || (a.x==b.x && a.y>b.y)) { const Point swap=a;a=b;b=swap; }
+ const double dx=b.x-a.x,dy=b.y-a.y,len2=dx*dx+dy*dy;
+ if (len2<1e-12) continue;
+ const double t=((vertex.world.x-a.x)*dx+(vertex.world.y-a.y)*dy)/len2;
+ const double cross=(vertex.world.x-a.x)*dy-(vertex.world.y-a.y)*dx;
+ const double bounded=(std::max)(0.0,(std::min)(1.0,t));
+ const double ex=vertex.world.x-a.x-dx*bounded,ey=vertex.world.y-a.y-dy*bounded;
+ collar.Add(edge,bounded,ex*ex+ey*ey);
+ if (t>=-1e-8 && t<=1+1e-8 && std::abs(cross)<1e-8*(len2+1)) {
+ vertex.boundary=edge;vertex.edgeParameter=(std::max)(0.0,(std::min)(1.0,t));
+ // Both owners reconstruct the same authored edge in canonical world order.
+ vertex.world={a.x+dx*vertex.edgeParameter,a.y+dy*vertex.edgeParameter};break;
+ }
+ }
+ if (knot) vertex={knot->world,knot->boundary,knot->edgeParameter,knot->index};
+ if (vertex.boundary<0 && collar.count) {
+ collar.Normalize();vertex.collar=int(mesh.collars.size());mesh.collars.push_back(collar);
+ }
+ if (mesh.vertices.size()>=budget) return false;
+ index=uint16_t(mesh.vertices.size());
+ if (slot>=0) lattice[slot]=index;else known.emplace(key,index);
+ mesh.vertices.push_back(vertex);return true;
+ };
+ for (int row=0;row<resolution.rows;++row) for (int column=0;column<resolution.columns;++column) {
+ const double left=limit*(2.0*column/resolution.columns-1),right=limit*(2.0*(column+1)/resolution.columns-1);
+ const double bottom=limit*(2.0*row/resolution.rows-1),top=limit*(2.0*(row+1)/resolution.rows-1);
+ const Point centre={(left+right)*0.5,(bottom+top)*0.5}; bool outside=false,inside=true;
+ for (int edge=0;edge<footprint.count;++edge) {
+ const Plane &p=boundary[edge];const double distance=Distance(p,centre);
+ const double extent=std::abs(p.a)*(right-left)*0.5+std::abs(p.b)*(top-bottom)*0.5;
+ if (distance+extent<-1e-14) { outside=true;break; }
+ if (distance-extent<=1e-14) inside=false;
+ }
+ if (outside) continue;
+ Polygon cell;
+ if (inside) { cell.count=4;cell.points[0]={left,bottom};cell.points[1]={right,bottom};cell.points[2]={right,top};cell.points[3]={left,top}; }
+ else {
+ cell=footprint;
+ if (!Clip(cell,{1,0,-left}) || !Clip(cell,{-1,0,right}) || !Clip(cell,{0,1,-bottom}) || !Clip(cell,{0,-1,top})) return false;
+ }
+ if (cell.count<3) continue;
+ if (inside) {
+ const int a=row*(resolution.columns+1)+column;
+ const int slots[4]={a,a+1,a+resolution.columns+2,a+resolution.columns+1};
+ uint16_t indices[4];for (int i=0;i<4;++i) if (!append(cell.points[i],indices[i],nullptr,slots[i])) return false;
+ mesh.indices.insert(mesh.indices.end(),{indices[0],indices[1],indices[2],indices[0],indices[2],indices[3]});
+ ++mesh.cells;continue;
+ }
+ // A retained river edge can contain several displaced knots inside one projected
+ // cell. Include the union of those knots and lattice intersections. A centre fan
+ // makes every resulting boundary segment an actual triangle edge, even if collinear.
+ struct CellPoint { Point screen;const BoundaryKnot *knot; };
+ std::vector<CellPoint> polygon;polygon.reserve(cell.count+4);
+ for (int i=0;i<cell.count;++i) {
+ const Point a=cell.points[i],b=cell.points[(i+1)%cell.count];
+ const double dx=b.x-a.x,dy=b.y-a.y,len2=dx*dx+dy*dy;
+ const BoundaryKnot *atStart=nullptr;
+ std::vector<std::pair<double,const ScreenKnot *>> between;
+ if (!inside && len2>1e-24) for (const ScreenKnot &k:screenKnots) {
+ if (k.screen.x<left-1e-12 || k.screen.x>right+1e-12 || k.screen.y<bottom-1e-12 || k.screen.y>top+1e-12) continue;
+ const double t=((k.screen.x-a.x)*dx+(k.screen.y-a.y)*dy)/len2;
+ const double cross=(k.screen.x-a.x)*dy-(k.screen.y-a.y)*dx;
+ if (std::abs(cross)>1e-12*len2) continue;
+ if (std::abs(t)<1e-12) atStart=k.source;
+ else if (t>1e-12 && t<1-1e-12) between.push_back({t,&k});
+ }
+ polygon.push_back({atStart?Point{0,0}:a,atStart});
+ if (atStart) projection.Transform(atStart->world,polygon.back().screen);
+ std::sort(between.begin(),between.end(),[](const auto &a,const auto &b) { return a.first<b.first; });
+ for (const auto &entry:between) polygon.push_back({entry.second->screen,entry.second->source});
+ }
+ auto appendClipped=[&](Point p,uint16_t &index,const BoundaryKnot *knot=nullptr) {
+ const int x=p.x==left?column:(p.x==right?column+1:-1);
+ const int y=p.y==bottom?row:(p.y==top?row+1:-1);
+ return append(p,index,knot,x>=0 && y>=0?y*(resolution.columns+1)+x:-1);
+ };
+ std::vector<uint16_t> polygonIndices(polygon.size());
+ for (size_t i=0;i<polygon.size();++i) if (!appendClipped(polygon[i].screen,polygonIndices[i],polygon[i].knot)) return false;
+ auto triangle=[&](uint16_t ia,uint16_t ib,uint16_t ic,Point a,Point b,Point c) {
+ if (std::abs((b.x-a.x)*(c.y-a.y)-(b.y-a.y)*(c.x-a.x))<1e-16) return;
+ mesh.indices.push_back(ia);mesh.indices.push_back(ib);mesh.indices.push_back(ic);
+ };
+ // The area centroid is independent of inserted knots and duplicate clipping corners.
+ // An arithmetic vertex average would jump when a knot enters or leaves this cell.
+ Point clippedCentroid={0,0};double twiceArea=0;
+ for (int i=0;i<cell.count;++i) {
+ const Point a=cell.points[i],b=cell.points[(i+1)%cell.count];
+ const double cross=a.x*b.y-b.x*a.y;
+ twiceArea+=cross;clippedCentroid.x+=(a.x+b.x)*cross;clippedCentroid.y+=(a.y+b.y)*cross;
+ }
+ if (std::abs(twiceArea)<1e-16) continue;
+ clippedCentroid.x/=3*twiceArea;clippedCentroid.y/=3*twiceArea;
+ uint16_t clippedCentroidIndex;if (!appendClipped(clippedCentroid,clippedCentroidIndex)) return false;
+ double clipped=1-std::abs(twiceArea)/(2*(right-left)*(top-bottom));
+ clipped=(std::max)(0.0,(std::min)(1.0,clipped/0.25));
+ if (clipped<1) {
+ CentreTransition transition={};transition.analytic=clipped*clipped*(3-2*clipped);
+ const bool lower=(clippedCentroid.x-left)/(right-left)>=(clippedCentroid.y-bottom)/(top-bottom);
+ const Point screen[3]={{left,bottom},lower?Point{right,bottom}:Point{left,top},{right,top}};
+ bool valid=true;for (int i=0;i<3;++i) valid=projection.Transform(screen[i],transition.source[i],true)&&valid;
+ const Point a=transition.source[0],b=transition.source[1],c=transition.source[2],p=mesh.vertices[clippedCentroidIndex].world;
+ const double determinant=(b.x-a.x)*(c.y-a.y)-(b.y-a.y)*(c.x-a.x);
+ if (valid && std::isfinite(determinant) && std::abs(determinant)>1e-20) {
+ transition.weight[1]=((p.x-a.x)*(c.y-a.y)-(p.y-a.y)*(c.x-a.x))/determinant;
+ transition.weight[2]=((b.x-a.x)*(p.y-a.y)-(b.y-a.y)*(p.x-a.x))/determinant;
+ transition.weight[0]=1-transition.weight[1]-transition.weight[2];
+ if (NormalizeCentreWeights(transition.weight)) {
+ mesh.vertices[clippedCentroidIndex].transition=int(mesh.transitions.size());mesh.transitions.push_back(transition);
+ }
+ }
+ }
+ for (size_t i=0;i<polygon.size();++i) {
+ const size_t next=(i+1)%polygon.size();
+ triangle(clippedCentroidIndex,polygonIndices[i],polygonIndices[next],clippedCentroid,polygon[i].screen,polygon[next].screen);
+ }
+ ++mesh.cells;
+ }
+ return true;
+}
+}
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterShoreFoam.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterShoreFoam.h
new file mode 100644
index 000000000..05c1d09a3
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterShoreFoam.h
@@ -0,0 +1,284 @@
+/* Render-only coastal breaking source. No fluid solver or gameplay height changes. */
+#pragma once
+#include "Platform/WaterSurfaceModel.h"
+#include <algorithm>
+#include <cmath>
+#include <cstdio>
+#include <string>
+
+namespace WaterShoreFoam {
+// The physical nearshore surface is the legacy analytic model where optical R is zero.
+// Its first three modes carry the visible broad/medium wave motion; fine ripples remain
+// in geometry and normals but cannot independently trigger this breaking source.
+constexpr unsigned ModeCount=3;
+struct Mode { float kx,ky,amplitude,omega,phase; };
+#define WATER_SHORE_MODE(kx,ky,a,w,p) {kx,ky,a,w,p},
+static constexpr Mode Modes[]={WATER_SURFACE_MODES(WATER_SHORE_MODE)};
+#undef WATER_SHORE_MODE
+struct Wave { float height=0,dx=0,dy=0,dt=0; };
+struct Front {float mask=0,residence=0;};
+struct FrontWeights {float value[ModeCount]={};};
+// Exact positive crest of sin(q)+.13*sin(2q): .52*cos(q)^2+cos(q)-.26=0.
+// The rising leading face runs from this crest to q=pi (q decreases with time).
+// Its duration/width are phase-derived, independent of render count or terrain bands.
+constexpr float FrontCrestCosine=.232009281f,FrontCrestPhase=1.336653506f;
+constexpr float FrontPhaseWidth=1.804939147f,FrontArea=.991318299f;
+constexpr float FrontPi=3.141592654f,FrontTau=6.283185307f;
+constexpr float FrontMaximumResidence=FrontPhaseWidth/Modes[0].omega;
+static_assert(ModeCount==3 && Modes[0].omega<=Modes[1].omega && Modes[0].omega<=Modes[2].omega,
+ "Update the bound if the coastal modal subset changes");
+struct Context {
+ float depth=0,shore=0,nx=0,ny=0,slope=0,exposure=0,support=0;
+};
+#define WATER_SHORE_CONSTANTS(X) \
+ X(MaximumRate,1.2f) X(FreshInterval,0.35f) X(MinDepth,0.15f) X(WetDepth,0.8f) \
+ X(IncomingCosine,0.25f) X(CrestHeight,0.5f) X(BreakStart,0.4f) X(BreakFull,0.85f) \
+ X(RockDistance,6.0f) X(SlopeStart,0.35f) X(SlopeFull,1.0f) X(ShelteredScale,0.15f)
+#define WATER_SHORE_CONSTANT(name,value) constexpr float name=value;
+WATER_SHORE_CONSTANTS(WATER_SHORE_CONSTANT)
+#undef WATER_SHORE_CONSTANT
+inline float Clamp(float x,float lo,float hi) {return (std::max)(lo,(std::min)(hi,x));}
+inline float Smooth(float a,float b,float x) {float t=Clamp((x-a)/(b-a),0,1);return t*t*(3-2*t);}
+// Normalized incoming modal energy is static per terrain context; the CPU history
+// caches it once. Keeping the sum <=1 makes the new birth rate <= the previous rate.
+inline FrontWeights IncomingWeights(float nx,float ny) {
+ FrontWeights weights;const float length=std::hypot(nx,ny);
+ if(!std::isfinite(length)||length<=1e-8f)return weights;
+ float total=0;
+ for(unsigned i=0;i<ModeCount;++i) {
+ const Mode&m=Modes[i];const float k=std::hypot(m.kx,m.ky);
+ weights.value[i]=m.amplitude*m.amplitude*Smooth(0,IncomingCosine,-(m.kx*(nx/length)+m.ky*(ny/length))/k);
+ total+=weights.value[i];
+ }
+ if(total>0)for(float&w:weights.value)w/=total;
+ return weights;
+}
+inline float FrontKernel(float sine,float cosine) {
+ if(!std::isfinite(sine)||!std::isfinite(cosine)||sine<=0)return 0;
+ const float u=Clamp((FrontCrestCosine-cosine)/(1+FrontCrestCosine),0,1);
+ return 4*u*(1-u);
+}
+// Stable definite integral on one positive rising face. Factoring sin(b)-sin(a)
+// avoids subtraction of two nearly equal antiderivatives for tiny pixel footprints.
+inline float FrontSegment(float a,float b) {
+ a=(std::max)(a,FrontCrestPhase);b=(std::min)(b,FrontPi);
+ if(b<=a)return 0;
+ const float width=b-a,middle=(a+b)*.5f,c=FrontCrestCosine;
+ return (std::max)(0.0f,4/((1+c)*(1+c))*((c-.5f)*width
+ +2*(c-1)*std::cos(middle)*std::sin(width*.5f)-.5f*std::cos(2*middle)*std::sin(width)));
+}
+inline float FrontFiltered(float sine,float cosine,float width) {
+ if(!std::isfinite(sine)||!std::isfinite(cosine)||!std::isfinite(width)||width<0)return 0;
+ // Below .001 radians the point limit differs by <.0004 even at the crest corner.
+ if(width<=.001f)return FrontKernel(sine,cosine);
+ // An arbitrarily coarse footprint approaches its period mean. At this bound
+ // omitting its residual period changes coverage by <1/4096, independent of phase.
+ if(width>=FrontTau*4096)return FrontArea/FrontTau;
+ const float periods=std::floor(width/FrontTau),remainder=width-periods*FrontTau;
+ float q=std::atan2(sine,cosine)+(periods-2*std::floor(periods*.5f))*FrontPi;
+ q-=FrontTau*std::floor(q/FrontTau);
+ const float a=q-remainder*.5f,b=q+remainder*.5f;
+ const float residual=FrontSegment(a,b)+FrontSegment(a-FrontTau,b-FrontTau)+FrontSegment(a+FrontTau,b+FrontTau);
+ return Clamp((periods*FrontArea+residual)/width,0,1);
+}
+inline Front EvaluateFront(float x,float y,float time,float nx,float ny,
+ float dxX=0,float dxY=0,float dyX=0,float dyY=0) {
+ if(!std::isfinite(x)||!std::isfinite(y)||!std::isfinite(time)
+ ||!std::isfinite(dxX)||!std::isfinite(dxY)||!std::isfinite(dyX)||!std::isfinite(dyY))return {};
+ const FrontWeights weights=IncomingWeights(nx,ny);Front front;
+ for(unsigned i=0;i<ModeCount;++i) {
+ const Mode&m=Modes[i];const float q=x*m.kx+y*m.ky-time*m.omega+m.phase;
+ if(!std::isfinite(q))return {};
+ const float width=std::abs(m.kx*dxX+m.ky*dxY)+std::abs(m.kx*dyX+m.ky*dyY);
+ const float active=weights.value[i]*FrontFiltered(std::sin(q),std::cos(q),width);
+ front.mask+=active;front.residence+=active*(FrontPhaseWidth/m.omega);
+ }
+ if(front.mask>0)front.residence/=front.mask;
+ front.mask=Clamp(front.mask,0,1);return front;
+}
+inline float FrontFresh(float rate,float residence) {
+ return std::isfinite(rate)&&std::isfinite(residence)
+ ?1-std::exp(-Clamp(rate,0,MaximumRate)*Clamp(residence,0,FrontMaximumResidence)):0;
+}
+inline float BlendFrontHistory(float legacy,float rate,float residence,float history,float support,float sceneWet,float terrainMatch) {
+ return legacy*(1-Clamp(support,0,1)*Clamp(terrainMatch,0,1))
+ +(std::max)(FrontFresh(rate,residence),Clamp(history,0,1))*Clamp(sceneWet,0,1)*Clamp(terrainMatch,0,1);
+}
+inline Wave Evaluate(float x,float y,float time) {
+ if(!std::isfinite(x)||!std::isfinite(y)||!std::isfinite(time))return {};
+ Wave value;
+ for(unsigned i=0;i<ModeCount;++i) {
+ const Mode &m=Modes[i];const float p=x*m.kx+y*m.ky-time*m.omega+m.phase;
+ if(!std::isfinite(p))return {};
+ const float s=std::sin(p),c=std::cos(p);
+ const float derivative=m.amplitude*(c+0.26f*(c*c-s*s));
+ value.height+=m.amplitude*(s+0.26f*s*c);
+ value.dx+=derivative*m.kx;value.dy+=derivative*m.ky;value.dt-=derivative*m.omega;
+ }
+ return value;
+}
+inline bool Finite(const Context &c,const Wave &w) {
+ return std::isfinite(c.depth)&&std::isfinite(c.shore)&&std::isfinite(c.nx)&&std::isfinite(c.ny)
+ &&std::isfinite(c.slope)&&std::isfinite(c.exposure)&&std::isfinite(c.support)
+ &&std::isfinite(w.height)&&std::isfinite(w.dx)&&std::isfinite(w.dy)&&std::isfinite(w.dt);
+}
+inline float Rate(const Context &c,const Wave &w) {
+ if(!Finite(c,w)||c.depth<=MinDepth||c.support<=0||w.height<=0)return 0;
+ const float normalLength=std::hypot(c.nx,c.ny),waveSlope=std::hypot(w.dx,w.dy);
+ if(!std::isfinite(normalLength)||!std::isfinite(waveSlope)||normalLength<=1e-8f||waveSlope<=1e-8f||std::abs(w.dt)<=1e-8f)return 0;
+ // Phase travel is -h_t*grad(h)/|grad(h)|^2. Positive flux approaches the coast,
+ // since the context normal points from high terrain toward open water.
+ const float cosine=(w.dt>0?1.0f:-1.0f)*((w.dx/waveSlope)*(c.nx/normalLength)+(w.dy/waveSlope)*(c.ny/normalLength));
+ const float incoming=Smooth(0,IncomingCosine,cosine);
+ const float attenuation=WaterSurfaceModel::ShoreDamping(c.depth);
+ const float beach=Smooth(BreakStart,BreakFull,2*w.height/(std::max)(c.depth+0.5f,1.0f))
+ *(1-attenuation*attenuation);
+ const float rock=1-Smooth(0,RockDistance,(std::max)(0.0f,c.shore));
+ const float steep=Smooth(SlopeStart,SlopeFull,c.slope);
+ return MaximumRate*Clamp(c.support,0,1)*Smooth(MinDepth,WetDepth,c.depth)*incoming
+ *(ShelteredScale+(1-ShelteredScale)*Clamp(c.exposure,0,1))
+ *Clamp(beach+(rock-beach)*steep,0,1)*Smooth(0,CrestHeight,w.height);
+}
+// A fallback terrain position is not evidence that the original scene pixel hit terrain.
+// This eligibility applies to replacement as well as emission, so missing/clear depth
+// preserves the previous intersection rim even during a zero-rate wave trough.
+inline bool SceneDepthEligible(float available,float rawDepth) {
+ return std::isfinite(available)&&available>0.5f&&std::isfinite(rawDepth)
+ &&rawDepth>=0.0f&&rawDepth<0.999999f;
+}
+inline float Fresh(float rate) {
+ return std::isfinite(rate)?1-std::exp(-Clamp(rate,0,MaximumRate)*FreshInterval):0;
+}
+// Rate already includes static support. Preserve object/river/missing-context fallback
+// independently of source activity; a wave trough can then genuinely remove the terrain rim.
+inline float Blend(float legacy,float rate,float support,float sceneWet,float terrainMatch) {
+ return legacy*(1-Clamp(support,0,1)*Clamp(terrainMatch,0,1))
+ +Fresh(rate)*Clamp(sceneWet,0,1)*Clamp(terrainMatch,0,1);
+}
+inline float BlendHistory(float legacy,float rate,float history,float support,float sceneWet,float terrainMatch) {
+ return legacy*(1-Clamp(support,0,1)*Clamp(terrainMatch,0,1))
+ +(std::max)(Fresh(rate),Clamp(history,0,1))*Clamp(sceneWet,0,1)*Clamp(terrainMatch,0,1);
+}
+inline std::string HistorySource() {
+ return R"HLSL(
+float waterShoreHistory(float2 p,float level,float time) {
+ // x bit0 retains vessel RGB; bit1 independently advertises coastal alpha.
+ if(((uint)(FoamHistoryParameters.x+0.5)&2u)==0u || abs(level-FoamHistoryParameters.y)>.1) return 0;
+ float2 uv=(p-FoamHistoryArea.xy)*FoamHistoryArea.zw;
+ if(any(uv<0.0)||any(uv>1.0)) return 0;
+ float coverage=saturate(waterFoamHistoryTile(uv,0u).a);
+ // Effective optical-density decay between <=0.1s uploads. Age-dependent porosity
+ // is held for that bounded interval; CPU history remains the authoritative state.
+ float elapsed=max(0.0,time-FoamHistoryParameters.w);
+ coverage=1-pow(max(1.0-coverage,1.0/65536.0),exp(-elapsed/5.0));
+ float2 border=min(uv,1.0-uv)/max(FoamHistoryArea.zw,float2(.000001,.000001));
+ return coverage*smoothstep(0.0,max(8.0,FoamHistoryParameters.z*3.0),min(border.x,border.y));
+}
+)HLSL";
+}
+inline std::string FrontSource() {
+ char constants[512];std::snprintf(constants,sizeof(constants),
+ "static const float ShoreFrontCrestCosine=%.9g,ShoreFrontCrestPhase=%.9g,ShoreFrontPhaseWidth=%.9g,ShoreFrontArea=%.9g,ShoreFrontPi=%.9g,ShoreFrontTau=%.9g,ShoreFrontMaximumResidence=%.9g;\n",
+ double(FrontCrestCosine),double(FrontCrestPhase),double(FrontPhaseWidth),double(FrontArea),double(FrontPi),double(FrontTau),double(FrontMaximumResidence));
+ std::string text=constants;
+ text+=R"HLSL(
+float waterShoreFrontKernel(float s,float c) {
+ if(!isfinite(s)||!isfinite(c)||s<=0)return 0;
+ float u=saturate((ShoreFrontCrestCosine-c)/(1+ShoreFrontCrestCosine));return 4*u*(1-u);
+}
+float waterShoreFrontSegment(float a,float b) {
+ a=max(a,ShoreFrontCrestPhase);b=min(b,ShoreFrontPi);if(b<=a)return 0;
+ float width=b-a,middle=(a+b)*.5,c=ShoreFrontCrestCosine;
+ return max(0.0,4/((1+c)*(1+c))*((c-.5)*width
+ +2*(c-1)*cos(middle)*sin(width*.5)-.5*cos(2*middle)*sin(width)));
+}
+float waterShoreFrontFiltered(float s,float c,float width) {
+ if(!isfinite(s)||!isfinite(c)||!isfinite(width)||width<0)return 0;
+ if(width<=.001)return waterShoreFrontKernel(s,c);
+ if(width>=ShoreFrontTau*4096)return ShoreFrontArea/ShoreFrontTau;
+ float periods=floor(width/ShoreFrontTau),remainder=width-periods*ShoreFrontTau;
+ float q=atan2(s,c)+(periods-2*floor(periods*.5))*ShoreFrontPi;
+ q-=ShoreFrontTau*floor(q/ShoreFrontTau);
+ float a=q-remainder*.5,b=q+remainder*.5;
+ float residual=waterShoreFrontSegment(a,b)+waterShoreFrontSegment(a-ShoreFrontTau,b-ShoreFrontTau)
+ +waterShoreFrontSegment(a+ShoreFrontTau,b+ShoreFrontTau);
+ return saturate((periods*ShoreFrontArea+residual)/width);
+}
+float waterShoreFrontFresh(float rate,float residence) {
+ return isfinite(rate)&&isfinite(residence)?1-exp(-clamp(rate,0,ShoreMaximumRate)*clamp(residence,0,ShoreFrontMaximumResidence)):0;
+}
+float waterShoreBlendFrontHistory(float legacy,float rate,float residence,float history,float support,float sceneWet,float terrainMatch) {
+ return legacy*(1-saturate(support)*saturate(terrainMatch))
+ +max(waterShoreFrontFresh(rate,residence),saturate(history))*saturate(sceneWet)*saturate(terrainMatch);
+}
+float4 waterShoreWaveFront(float2 p,float time,float2 outward,float2 parameterDx,float2 parameterDy,out float2 front) {
+ front=0;
+ if(!all(isfinite(p))||!isfinite(time)||!all(isfinite(outward))
+ ||!all(isfinite(parameterDx))||!all(isfinite(parameterDy)))return 0;
+ float normalLength=length(outward);if(!isfinite(normalLength)||normalLength<=1e-8)return waterShoreWave(p,time);
+ float2 normal=outward/normalLength;float total=0;float4 wave=0;
+)HLSL";
+ for(unsigned i=0;i<ModeCount;++i) {
+ const Mode&m=Modes[i];char line[1400];
+ std::snprintf(line,sizeof(line),
+ "{float2 k=float2(%.9g,%.9g);float q=p.x*k.x+p.y*k.y-time*%.9g+%.9g;if(!isfinite(q)){front=0;return 0;}"
+ "float s=sin(q),c=cos(q),d=%.9g*(c+.26*(c*c-s*s));wave+=float4(%.9g*(s+.26*s*c),d*k,-d*%.9g);"
+ "float weight=%.9g*smoothstep(0,ShoreIncomingCosine,-dot(k,normal)/%.9g);"
+ "float width=abs(dot(k,parameterDx))+abs(dot(k,parameterDy));float active=weight*waterShoreFrontFiltered(s,c,width);"
+ "front+=active*float2(1,ShoreFrontPhaseWidth/%.9g);total+=weight;}\n",
+ double(m.kx),double(m.ky),double(m.omega),double(m.phase),double(m.amplitude),double(m.amplitude),double(m.omega),
+ double(m.amplitude*m.amplitude),double(std::hypot(m.kx,m.ky)),double(m.omega));
+ text+=line;
+ }
+ text+="if(front.x>0)front.y/=front.x;if(total>0)front.x=saturate(front.x/total);return wave;\n}\n";
+ return text;
+}
+inline std::string Source() {
+ std::string text;
+#define WATER_SHORE_HLSL(name,value) text+="static const float Shore" #name "=" #value ";\n";
+ WATER_SHORE_CONSTANTS(WATER_SHORE_HLSL)
+#undef WATER_SHORE_HLSL
+ text+="float4 waterShoreWave(float2 p,float time) {\nif(!all(isfinite(p))||!isfinite(time)) return 0;\nfloat4 w=0;\n";
+ for(unsigned i=0;i<ModeCount;++i) {
+ const Mode &m=Modes[i];char line[700];
+ std::snprintf(line,sizeof(line),
+ "{float q=p.x*%.9g+p.y*%.9g-time*%.9g+%.9g;if(!isfinite(q))return 0;float s=sin(q),c=cos(q);float d=%.9g*(c+.26*(c*c-s*s));w+=float4(%.9g*(s+.26*s*c),d*%.9g,d*%.9g,-d*%.9g);}\n",
+ double(m.kx),double(m.ky),double(m.omega),double(m.phase),double(m.amplitude),double(m.amplitude),double(m.kx),double(m.ky),double(m.omega));
+ text+=line;
+ }
+ text+=R"HLSL(return w;
+}
+float waterShoreRate(float4 wave,float depth,float shore,float2 outward,float terrainSlope,float exposure,float support) {
+ if(!all(isfinite(wave))||!all(isfinite(float4(depth,shore,outward)))
+ ||!all(isfinite(float3(terrainSlope,exposure,support)))
+ ||depth<=ShoreMinDepth||support<=0||wave.x<=0) return 0;
+ float normalLength=length(outward),waveSlope=length(wave.yz);
+ if(!isfinite(normalLength)||!isfinite(waveSlope)||normalLength<=1e-8||waveSlope<=1e-8||abs(wave.w)<=1e-8) return 0;
+ float cosine=sign(wave.w)*dot(wave.yz/waveSlope,outward/normalLength);
+ float incoming=smoothstep(0,ShoreIncomingCosine,cosine);
+ float attenuation=saturate(depth/9.0);attenuation=attenuation*attenuation*(3-2*attenuation);
+ float beach=smoothstep(ShoreBreakStart,ShoreBreakFull,2*wave.x/max(depth+.5,1))*(1-attenuation*attenuation);
+ float rock=1-smoothstep(0,ShoreRockDistance,max(0,shore));
+ float steep=smoothstep(ShoreSlopeStart,ShoreSlopeFull,terrainSlope);
+ return ShoreMaximumRate*saturate(support)*smoothstep(ShoreMinDepth,ShoreWetDepth,depth)*incoming
+ *lerp(ShoreShelteredScale,1,saturate(exposure))*saturate(lerp(beach,rock,steep))
+ *smoothstep(0,ShoreCrestHeight,wave.x);
+}
+bool waterShoreSceneDepth(float available,float rawDepth) {
+ return isfinite(available)&&available>0.5&&isfinite(rawDepth)
+ &&rawDepth>=0.0&&rawDepth<0.999999;
+}
+float waterShoreFresh(float rate) {return isfinite(rate)?1-exp(-clamp(rate,0,ShoreMaximumRate)*ShoreFreshInterval):0;}
+float waterShoreBlendHistory(float legacy,float rate,float history,float support,float sceneWet,float terrainMatch) {
+ return legacy*(1-saturate(support)*saturate(terrainMatch))
+ +max(waterShoreFresh(rate),saturate(history))*saturate(sceneWet)*saturate(terrainMatch);
+}
+float waterShoreBlend(float legacy,float rate,float support,float sceneWet,float terrainMatch) {
+ return legacy*(1-saturate(support)*saturate(terrainMatch))
+ +waterShoreFresh(rate)*saturate(sceneWet)*saturate(terrainMatch);
+}
+)HLSL";
+ return text+FrontSource();
+}
+#undef WATER_SHORE_CONSTANTS
+}
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterShoreHistory.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterShoreHistory.h
new file mode 100644
index 000000000..981fc3ecd
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterShoreHistory.h
@@ -0,0 +1,351 @@
+/* Render-only, fixed-world coastal foam history. Source physics is supplied by the caller. */
+#pragma once
+#include <algorithm>
+#include <array>
+#include <cmath>
+#include <cstdint>
+#include <limits>
+#include <utility>
+#include <vector>
+
+namespace WaterShoreHistory {
+constexpr size_t MaxCells=65536,MaxLevels=8,MaxEdges=2*MaxCells;
+constexpr double Tick=0.1;
+constexpr uint64_t MaxCatchupTicks=8,MaxTickIndex=uint64_t(1)<<48;
+// Keep absolute double clock resolution well below a fixed tick.
+inline bool ValidTime(double time){return std::isfinite(time)&&std::abs(time)<=Tick*double(MaxTickIndex);}
+struct Parameters {double lifetime=5,diffusivity=2,maximumRate=16;};
+struct Grid {double originX=0,originY=0,spacing=5;};
+// The caller only supplies actual wet terrain cells within its bounded coastal domain.
+// Domain includes a wet-only spread margin around source cells, not dry validity-mask cells.
+struct Cell {
+ int32_t x=0,y=0;double level=0;
+ uint32_t sourceIndex=0; // opaque index into the caller's immutable, per-revision source context
+ uint8_t connections=3; // positive X/Y edges; builder proves each segment stays in the polygon union
+};
+struct State {double density=0,ageMoment=0;};
+struct Edge {uint32_t a=0,b=0;};
+inline bool Less(const Cell&a,const Cell&b) {
+ if(a.level!=b.level)return a.level<b.level;
+ if(a.y!=b.y)return a.y<b.y;
+ return a.x<b.x;
+}
+inline bool SameKey(const Cell&a,const Cell&b){return a.level==b.level&&a.x==b.x&&a.y==b.y;}
+inline double Clamp(double x,double low,double high){return (std::max)(low,(std::min)(high,x));}
+inline bool ValidGrid(const Grid&g) {
+ return std::isfinite(g.originX)&&std::isfinite(g.originY)&&std::isfinite(g.spacing)
+ &&g.spacing>=1&&g.spacing<=1024;
+}
+inline bool ValidParameters(const Parameters&p,const Grid&g) {
+ // Four-neighbour diffusion is a convex combination with >=1/2 self weight.
+ return std::isfinite(p.lifetime)&&p.lifetime>=.1&&p.lifetime<=3600
+ &&std::isfinite(p.diffusivity)&&p.diffusivity>=0&&4*p.diffusivity*Tick/(g.spacing*g.spacing)<=.5
+ &&std::isfinite(p.maximumRate)&&p.maximumRate>=0&&p.maximumRate<=1000;
+}
+struct Decay {
+ double q=1,elapsed=0,sourceDensity=0,sourceAge=0;
+ static Decay Make(double seconds,double lifetime) {
+ Decay d;d.elapsed=seconds;const double x=seconds/lifetime;
+ if(x>700){d.q=0;d.sourceDensity=lifetime;d.sourceAge=lifetime*lifetime;return d;}
+ d.q=std::exp(-x);const double oneMinus=-std::expm1(-x);
+ // Stable integral of age*exp(-age/lifetime); no cancellation at small partial dt.
+ const double moment=x<.05?x*x*(.5+x*(-1.0/3+x*(1.0/8+x*(-1.0/30+x*(1.0/144+x*(-1.0/840+x/5760))))))
+ :oneMinus-x*d.q;
+ d.sourceDensity=lifetime*oneMinus;d.sourceAge=lifetime*lifetime*moment;return d;
+ }
+ State Apply(const State&s,double rate)const {
+ // The early q==0 case also avoids 0*(large elapsed*density) becoming NaN.
+ if(q==0)return {rate*sourceDensity,rate*sourceAge};
+ return {q*s.density+rate*sourceDensity,q*(s.ageMoment+elapsed*s.density)+rate*sourceAge};
+ }
+};
+enum class BuildResult {Ready,TooManyCells,TooManyLevels,Invalid};
+// Cached interpolation ownership. Every raster sample belongs to one half-open grid
+// tile; indices retain the original dy/dx summation order and absent nodes stay -1.
+struct RasterTile {
+ int32_t x=0,y=0;double level=0;
+ std::array<int32_t,4> nodes{{-1,-1,-1,-1}};
+};
+inline bool RasterLess(const RasterTile&a,const RasterTile&b) {
+ if(a.level!=b.level)return a.level<b.level;
+ if(a.y!=b.y)return a.y<b.y;return a.x<b.x;
+}
+class Topology {
+ Grid grid;std::vector<Cell> cells;std::vector<Edge> edges;
+ std::vector<RasterTile> rasterTiles;
+ // Fixed open-address lookup: at most 1/2 occupancy, bounded allocations and no frame-time writes.
+ std::vector<uint32_t> table;static constexpr uint32_t Empty=~uint32_t(0);
+ static uint64_t Mix(uint64_t v){v^=v>>30;v*=0xbf58476d1ce4e5b9ULL;v^=v>>27;v*=0x94d049bb133111ebULL;return v^(v>>31);}
+ uint64_t Hash(int32_t x,int32_t y,double level)const {
+ // Level is located in a tiny sorted list, avoiding host-endian double byte hashing.
+ const auto at=std::lower_bound(levels.begin(),levels.end(),level);
+ const uint64_t l=uint64_t(at-levels.begin());
+ return Mix(uint64_t(uint32_t(x))|(uint64_t(uint32_t(y))<<32))^Mix(l+0x9e3779b97f4a7c15ULL);
+ }
+ std::vector<double> levels;
+public:
+ BuildResult Build(const Grid&inputGrid,const std::vector<Cell>&input) {
+ if(input.size()>MaxCells)return BuildResult::TooManyCells;
+ if(!ValidGrid(inputGrid))return BuildResult::Invalid;
+ Topology next;next.grid=inputGrid;next.cells=input;
+ for(Cell&c:next.cells) {
+ if(!std::isfinite(c.level)||!std::isfinite(inputGrid.originX+double(c.x)*inputGrid.spacing)
+ ||!std::isfinite(inputGrid.originY+double(c.y)*inputGrid.spacing))return BuildResult::Invalid;
+ if(c.level==0)c.level=0; // canonical positive zero
+ }
+ std::sort(next.cells.begin(),next.cells.end(),Less);
+ for(size_t i=0;i<next.cells.size();++i) {
+ if(i&&SameKey(next.cells[i-1],next.cells[i]))return BuildResult::Invalid;
+ if(next.levels.empty()||next.levels.back()!=next.cells[i].level)next.levels.push_back(next.cells[i].level);
+ }
+ if(next.levels.size()>MaxLevels)return BuildResult::TooManyLevels;
+ size_t size=2;while(size<2*next.cells.size())size*=2;
+ next.table.assign(size,Empty);next.edges.reserve(2*next.cells.size());
+ for(uint32_t i=0;i<next.cells.size();++i) {
+ const Cell&c=next.cells[i];size_t slot=next.Hash(c.x,c.y,c.level)&(size-1);
+ while(next.table[slot]!=Empty)slot=(slot+1)&(size-1);
+ next.table[slot]=i;
+ }
+ for(uint32_t i=0;i<next.cells.size();++i) {
+ const Cell&c=next.cells[i];int neighbour=-1;
+ if((c.connections&1)&&c.x<(std::numeric_limits<int32_t>::max)())neighbour=next.Find(c.x+1,c.y,c.level);
+ if(neighbour>=0)next.edges.push_back({i,uint32_t(neighbour)});
+ if((c.connections&2)&&c.y<(std::numeric_limits<int32_t>::max)())neighbour=next.Find(c.x,c.y+1,c.level);else neighbour=-1;
+ if(neighbour>=0)next.edges.push_back({i,uint32_t(neighbour)});
+ }
+ if(next.edges.size()>MaxEdges)return BuildResult::Invalid;
+ // Build at most four contributions per node once per geometry revision, not
+ // four hash lookups per atlas texel on every history upload.
+ next.rasterTiles.reserve(4*next.cells.size());
+ for(uint32_t i=0;i<next.cells.size();++i) {
+ const Cell&c=next.cells[i];
+ for(unsigned dy=0;dy<2;++dy)for(unsigned dx=0;dx<2;++dx) {
+ const int64_t x=int64_t(c.x)-dx,y=int64_t(c.y)-dy;
+ // Sample permits floor indices [INT_MIN,INT_MAX), with +1 neighbours.
+ if(x<(std::numeric_limits<int32_t>::min)()||y<(std::numeric_limits<int32_t>::min)()
+ ||x>=(std::numeric_limits<int32_t>::max)()||y>=(std::numeric_limits<int32_t>::max)())continue;
+ RasterTile tile;tile.x=int32_t(x);tile.y=int32_t(y);tile.level=c.level;tile.nodes[dy*2+dx]=int32_t(i);
+ next.rasterTiles.push_back(tile);
+ }
+ }
+ std::sort(next.rasterTiles.begin(),next.rasterTiles.end(),RasterLess);
+ size_t kept=0;
+ for(size_t read=0;read<next.rasterTiles.size();++read) {
+ const RasterTile tile=next.rasterTiles[read];
+ if(kept&&next.rasterTiles[kept-1].x==tile.x&&next.rasterTiles[kept-1].y==tile.y&&next.rasterTiles[kept-1].level==tile.level) {
+ for(unsigned n=0;n<4;++n)if(tile.nodes[n]>=0)next.rasterTiles[kept-1].nodes[n]=tile.nodes[n];
+ } else next.rasterTiles[kept++]=tile;
+ }
+ next.rasterTiles.resize(kept);
+ *this=std::move(next);return BuildResult::Ready;
+ }
+ int Find(int32_t x,int32_t y,double level)const {
+ if(table.empty()||!std::isfinite(level))return -1;
+ size_t slot=Hash(x,y,level)&(table.size()-1);
+ for(size_t attempts=0;attempts<table.size();++attempts) {
+ const uint32_t index=table[slot];if(index==Empty)return -1;
+ const Cell&c=cells[index];if(c.x==x&&c.y==y&&c.level==level)return int(index);
+ slot=(slot+1)&(table.size()-1);
+ }
+ return -1;
+ }
+ bool SameGeometry(const Topology&o)const {
+ if(grid.originX!=o.grid.originX||grid.originY!=o.grid.originY||grid.spacing!=o.grid.spacing||cells.size()!=o.cells.size())return false;
+ for(size_t i=0;i<cells.size();++i)if(!SameKey(cells[i],o.cells[i])||cells[i].connections!=o.cells[i].connections)return false;
+ return true;
+ }
+ const Grid& Geometry()const{return grid;}
+ const std::vector<Cell>& Cells()const{return cells;}
+ const std::vector<Edge>& Edges()const{return edges;}
+ const std::vector<RasterTile>& RasterTiles()const{return rasterTiles;}
+};
+// One full operator: exact source/decay/age integration for constant rate over dt, followed
+// by conservative reciprocal wet-neighbour diffusion. The latter is first-order in time,
+// not claimed to be an exact heat solver. Fixed global ticks make render schedules irrelevant.
+inline bool Step(const Topology&topology,const Parameters&parameters,const std::vector<State>&input,
+ const std::vector<double>&rates,double dt,std::vector<State>&decayed,std::vector<State>&output) {
+ const size_t count=topology.Cells().size();
+ if(input.size()!=count||rates.size()!=count||&input==&decayed||&input==&output||&decayed==&output
+ ||!std::isfinite(dt)||dt<0||dt>Tick+1e-12||!ValidParameters(parameters,topology.Geometry()))return false;
+ for(const State&s:input)if(!std::isfinite(s.density)||!std::isfinite(s.ageMoment)||s.density<0||s.ageMoment<0)return false;
+ const Decay decay=Decay::Make(dt,parameters.lifetime);
+ decayed.resize(count);output.resize(count);
+ for(size_t i=0;i<count;++i) {
+ const double rate=std::isfinite(rates[i])?Clamp(rates[i],0,parameters.maximumRate):0;
+ output[i]=decayed[i]=decay.Apply(input[i],rate);
+ }
+ const double amount=parameters.diffusivity*dt/(topology.Geometry().spacing*topology.Geometry().spacing);
+ for(const Edge&e:topology.Edges()) {
+ const double density=amount*(decayed[e.b].density-decayed[e.a].density);
+ const double age=amount*(decayed[e.b].ageMoment-decayed[e.a].ageMoment);
+ output[e.a].density+=density;output[e.b].density-=density;
+ output[e.a].ageMoment+=age;output[e.b].ageMoment-=age;
+ }
+ return true;
+}
+enum class AdvanceResult {Advanced,Unchanged,Rewound,GapDecayed,Invalid};
+class History {
+ Topology topology;Parameters parameters;std::vector<State> committed,preview,decayed,next;
+ std::vector<double> rates;uint64_t revision=0,completed=0;double epoch=0,observed=0;
+ bool installed=false,previewDirty=false;
+ void ClearDynamic(double time) {
+ std::fill(committed.begin(),committed.end(),State{});preview=committed;
+ epoch=observed=time;completed=0;previewDirty=false;
+ }
+ template<class Source> void Fill(Source&source,double time) {
+ std::fill(rates.begin(),rates.end(),0.0);
+ // Batch callback permits three shared temporal sin/cos pairs, not per-cell transcendental work.
+ source(time,topology.Cells().data(),topology.Cells().size(),rates.data());
+ }
+public:
+ // Exact keys + revision preserve dynamic state through device refresh and reordered source tables.
+ // A new map/terrain/polygon revision clears history even when coordinates happen to match.
+ BuildResult Install(const Grid&grid,const std::vector<Cell>&cells,uint64_t mapRevision,double time,
+ Parameters settings=Parameters()) {
+ if(!ValidTime(time)||!ValidGrid(grid)||!ValidParameters(settings,grid))return BuildResult::Invalid;
+ Topology candidate;const BuildResult result=candidate.Build(grid,cells);if(result!=BuildResult::Ready)return result;
+ const bool reuse=installed&&revision==mapRevision&&topology.SameGeometry(candidate)
+ &&settings.lifetime==parameters.lifetime&&settings.diffusivity==parameters.diffusivity&&settings.maximumRate==parameters.maximumRate;
+ topology=std::move(candidate);parameters=settings;revision=mapRevision;installed=true;
+ if(!reuse) {
+ committed.assign(cells.size(),{});preview.resize(cells.size());decayed.resize(cells.size());next.resize(cells.size());rates.resize(cells.size());ClearDynamic(time);
+ }
+ return BuildResult::Ready;
+ }
+ void Clear(){*this=History();}
+ bool ValidFor(uint64_t mapRevision)const{return installed&&mapRevision==revision;}
+ template<class Source> AdvanceResult Advance(double time,Source&source) {
+ if(!installed||!ValidTime(time))return AdvanceResult::Invalid;
+ if(time==observed)return AdvanceResult::Unchanged;
+ if(time<observed){ClearDynamic(time);return AdvanceResult::Rewound;}
+ const double ratio=(time-epoch)/Tick;
+ if(!std::isfinite(ratio)||ratio>double(MaxTickIndex))return AdvanceResult::Invalid;
+ uint64_t wanted=uint64_t(std::floor(ratio));
+ // Compare the actual fixed-clock boundaries, correcting representational division noise.
+ while(epoch+double(wanted)*Tick>time)--wanted;
+ while(wanted<MaxTickIndex&&epoch+double(wanted+1)*Tick<=time)++wanted;
+ if(wanted-completed>MaxCatchupTicks) {
+ // Preserve the last observed partial field, even if no atlas requested it yet.
+ // Only the genuinely unseen interval suppresses births and diffusion.
+ committed=Preview(source);
+ const Decay decay=Decay::Make(time-observed,parameters.lifetime);
+ for(State&s:committed)s=decay.Apply(s,0);
+ preview=committed;epoch=observed=time;completed=0;previewDirty=false;
+ return AdvanceResult::GapDecayed; // no invented births during an unseen large gap
+ }
+ while(completed<wanted) {
+ Fill(source,epoch+(double(completed)+.5)*Tick);
+ // The mathematical fixed step is Tick; subtracting large absolute timestamps
+ // would introduce an age/diffusion error and can exceed Tick by roundoff.
+ if(!Step(topology,parameters,committed,rates,Tick,decayed,next))return AdvanceResult::Invalid;
+ committed.swap(next);++completed;
+ }
+ observed=time;previewDirty=true;return AdvanceResult::Advanced;
+ }
+ template<class Source> const std::vector<State>& Preview(Source&source) {
+ if(!previewDirty)return preview;
+ const double anchor=epoch+double(completed)*Tick,partial=Clamp(observed-anchor,0,Tick);
+ if(partial<=0)preview=committed;
+ else {
+ Fill(source,(anchor+observed)*.5);
+ if(!Step(topology,parameters,committed,rates,partial,decayed,preview))preview=committed;
+ }
+ previewDirty=false;return preview;
+ }
+ const std::vector<State>& Committed()const{return committed;}
+ const Topology& Domain()const{return topology;}
+ double Time()const{return observed;}
+ double CommittedTime()const{return epoch+double(completed)*Tick;}
+};
+// Bilinear interpolation of density and age MOMENTS, never unweighted average age.
+struct UnrestrictedSupport {
+ struct Stencil {bool Allows(unsigned,unsigned)const{return true;}};
+ Stencil At(int32_t,int32_t,double,double,double)const{return {};}
+};
+template<class Support> inline State Sample(const Topology&topology,const std::vector<State>&states,double x,double y,double level,const Support&support) {
+ if(states.size()!=topology.Cells().size()||!std::isfinite(x)||!std::isfinite(y)||!std::isfinite(level))return {};
+ const Grid&g=topology.Geometry();const double px=(x-g.originX)/g.spacing,py=(y-g.originY)/g.spacing;
+ if(!std::isfinite(px)||!std::isfinite(py)||px<(std::numeric_limits<int32_t>::min)()||py<(std::numeric_limits<int32_t>::min)()
+ ||px>=(std::numeric_limits<int32_t>::max)()||py>=(std::numeric_limits<int32_t>::max)())return {};
+ const int32_t ix=int32_t(std::floor(px)),iy=int32_t(std::floor(py));const double fx=px-ix,fy=py-iy;State out;
+ const auto stencil=support.At(ix,iy,level,fx,fy);
+ for(int dy=0;dy<2;++dy)for(int dx=0;dx<2;++dx) {
+ const int index=topology.Find(ix+dx,iy+dy,level);if(index<0)continue;
+ const double weight=(dx?fx:1-fx)*(dy?fy:1-fy);
+ // Zero rejected contributions without redistributing their weight to another shore.
+ if(weight<=0 || !stencil.Allows(unsigned(dx),unsigned(dy)))continue;
+ out.density+=states[size_t(index)].density*weight;out.ageMoment+=states[size_t(index)].ageMoment*weight;
+ }
+ return out;
+}
+inline State Sample(const Topology&topology,const std::vector<State>&states,double x,double y,double level) {
+ return Sample(topology,states,x,y,level,UnrestrictedSupport{});
+}
+inline uint32_t WithAlpha(uint32_t vesselARGB,double coverage) {
+ const uint32_t alpha=std::isfinite(coverage)?uint32_t(Clamp(coverage,0,1)*255+.5):0;
+ return (vesselARGB&0x00ffffffu)|(alpha<<24);
+}
+struct Mapping {double originX=0,originY=0,widthWorld=0,heightWorld=0;unsigned widthPixels=0,heightPixels=0;};
+template<class Coverage,class Support> inline bool RasterizeAlpha(const Topology&topology,const std::vector<State>&states,
+ const Mapping&mapping,double level,double time,Coverage&coverage,std::vector<uint32_t>&vesselARGB,const Support&support) {
+ if(!std::isfinite(mapping.originX)||!std::isfinite(mapping.originY)||!std::isfinite(mapping.widthWorld)
+ ||!std::isfinite(mapping.heightWorld)||mapping.widthWorld<=0||mapping.heightWorld<=0
+ ||!std::isfinite(mapping.originX+mapping.widthWorld)||!std::isfinite(mapping.originY+mapping.heightWorld)
+ ||!mapping.widthPixels||!mapping.heightPixels||mapping.widthPixels>512||mapping.heightPixels>512
+ ||!std::isfinite(level)||!std::isfinite(time)||states.size()!=topology.Cells().size()
+ ||vesselARGB.size()!=size_t(mapping.widthPixels)*mapping.heightPixels)return false;
+ // Clear stale coast alpha everywhere without changing vessel RGB. Empty or offscreen
+ // history then costs only this linear write, not per-pixel support and hash searches.
+ for(uint32_t&pixel:vesselARGB)pixel&=0x00ffffffu;
+ struct Axis {double world=0,fraction=0;int64_t key=0;};
+ std::array<Axis,512> horizontal,vertical;
+ const Grid&g=topology.Geometry();
+ auto axis=[](std::array<Axis,512>&out,unsigned count,double origin,double extent,double gridOrigin,double spacing) {
+ for(unsigned i=0;i<count;++i) {
+ Axis&a=out[i];
+ // Preserve Sample's arithmetic, including overflow/out-of-grid rejection.
+ a.world=origin+(double(i)+.5)*extent/count;
+ const double p=(a.world-gridOrigin)/spacing;
+ if(!std::isfinite(p)||p<(std::numeric_limits<int32_t>::min)()||p>=(std::numeric_limits<int32_t>::max)()) {
+ a.key=p<(std::numeric_limits<int32_t>::min)()?(std::numeric_limits<int64_t>::min)():(std::numeric_limits<int64_t>::max)();
+ } else {a.key=int32_t(std::floor(p));a.fraction=p-double(a.key);}
+ }
+ };
+ axis(horizontal,mapping.widthPixels,mapping.originX,mapping.widthWorld,g.originX,g.spacing);
+ axis(vertical,mapping.heightPixels,mapping.originY,mapping.heightWorld,g.originY,g.spacing);
+ auto first=[](const std::array<Axis,512>&a,unsigned count,int64_t key) {
+ return unsigned(std::lower_bound(a.begin(),a.begin()+count,key,[](const Axis&v,int64_t k){return v.key<k;})-a.begin());
+ };
+ auto after=[](const std::array<Axis,512>&a,unsigned count,int64_t key) {
+ return unsigned(std::upper_bound(a.begin(),a.begin()+count,key,[](int64_t k,const Axis&v){return k<v.key;})-a.begin());
+ };
+ for(const RasterTile&tile:topology.RasterTiles()) {
+ if(tile.level!=level||tile.x<horizontal[0].key||tile.x>horizontal[mapping.widthPixels-1].key
+ ||tile.y<vertical[0].key||tile.y>vertical[mapping.heightPixels-1].key)continue;
+ bool active=false;for(int32_t node:tile.nodes)if(node>=0&&states[size_t(node)].density>0){active=true;break;}
+ if(!active)continue;
+ const unsigned x0=first(horizontal,mapping.widthPixels,tile.x),x1=after(horizontal,mapping.widthPixels,tile.x);
+ if(x0==x1)continue;
+ const unsigned y0=first(vertical,mapping.heightPixels,tile.y),y1=after(vertical,mapping.heightPixels,tile.y);
+ for(unsigned y=y0;y<y1;++y)for(unsigned x=x0;x<x1;++x) {
+ const double fx=horizontal[x].fraction,fy=vertical[y].fraction;State state;
+ const auto stencil=support.At(tile.x,tile.y,level,fx,fy);
+ for(unsigned dy=0;dy<2;++dy)for(unsigned dx=0;dx<2;++dx) {
+ const int32_t node=tile.nodes[dy*2+dx];if(node<0)continue;
+ const double weight=(dx?fx:1-fx)*(dy?fy:1-fy);
+ if(weight<=0||!stencil.Allows(dx,dy))continue;
+ state.density+=states[size_t(node)].density*weight;state.ageMoment+=states[size_t(node)].ageMoment*weight;
+ }
+ const double value=state.density>0?coverage(state,horizontal[x].world,vertical[y].world,time):0;
+ const size_t n=size_t(y)*mapping.widthPixels+x;vesselARGB[n]=WithAlpha(vesselARGB[n],value);
+ }
+ }
+ return true;
+}
+
+template<class Coverage> inline bool RasterizeAlpha(const Topology&topology,const std::vector<State>&states,
+ const Mapping&mapping,double level,double time,Coverage&coverage,std::vector<uint32_t>&vesselARGB) {
+ return RasterizeAlpha(topology,states,mapping,level,time,coverage,vesselARGB,UnrestrictedSupport{});
+}
+
+}
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterShoreOverlay.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterShoreOverlay.h
new file mode 100644
index 000000000..d894b2054
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterShoreOverlay.h
@@ -0,0 +1,140 @@
+#pragma once
+// Render-only admission for replacing authored .wak surf. No texture-name inference.
+#include <cmath>
+#include <cstdint>
+#include <cstring>
+#include <string>
+
+namespace WaterShoreOverlay {
+constexpr unsigned MaxRegions = 128;
+struct Quad { float xy[8] = {}; float level = 0; };
+struct View {
+ std::uintptr_t colour = 0, depth = 0;
+ std::uint64_t capture = 0;
+ unsigned width = 0, height = 0;
+ float worldFromClip[16] = {}, viewport[4] = {};
+};
+inline bool SameView(const View &a, const View &b) {
+ for(float f:a.worldFromClip) if(!std::isfinite(f)) return false;
+ for(float f:a.viewport) if(!std::isfinite(f)) return false;
+ if(a.viewport[2]<=0||a.viewport[3]<=0) return false;
+ return a.colour && a.depth && a.capture && a.width && a.height &&
+ a.colour==b.colour && a.depth==b.depth && a.capture==b.capture &&
+ a.width==b.width && a.height==b.height &&
+ std::memcmp(a.worldFromClip,b.worldFromClip,sizeof(a.worldFromClip))==0 &&
+ std::memcmp(a.viewport,b.viewport,sizeof(a.viewport))==0;
+}
+inline double Cross(const Quad &q, unsigned a, unsigned b, double x, double y) {
+ return (double(q.xy[b*2])-q.xy[a*2])*(y-q.xy[a*2+1])-
+ (double(q.xy[b*2+1])-q.xy[a*2+1])*(x-q.xy[a*2]);
+}
+inline bool Convex(const Quad &q) {
+ if(!std::isfinite(q.level)) return false;
+ for(float f:q.xy) if(!std::isfinite(f)) return false;
+ double orientation=0;
+ for(unsigned i=0;i<4;++i) {
+ const double c=Cross(q,i,(i+1)%4,q.xy[((i+2)%4)*2],q.xy[((i+2)%4)*2+1]);
+ if(std::abs(c)<1e-8 || (orientation!=0 && c*orientation<=0)) return false;
+ orientation=c;
+ }
+ return true;
+}
+inline bool Contains(const Quad &patch,const Quad &track) {
+ if(!Convex(patch)||!Convex(track)||patch.level!=track.level) return false;
+ const double orientation=Cross(patch,0,1,patch.xy[4],patch.xy[5]);
+ for(unsigned i=0;i<4;++i) for(unsigned j=0;j<4;++j) {
+ const double c=Cross(patch,i,(i+1)%4,track.xy[j*2],track.xy[j*2+1]);
+ if((orientation>0 && c<0)||(orientation<0 && c>0)) return false;
+ }
+ return true;
+}
+inline float Replacement(float depthAvailable,float rawDepth,float offshore,float support,float terrainDifference) {
+ if(!std::isfinite(depthAvailable)||depthAvailable<=.5f||!std::isfinite(rawDepth)||
+ rawDepth<0||rawDepth>=.999999f||!std::isfinite(offshore)||
+ !std::isfinite(support)||!std::isfinite(terrainDifference)) return 0;
+ float x=(std::abs(terrainDifference)-.5f);x=x<0?0:x>1?1:x;
+ return 1-x*x*(3-2*x);
+}
+// Append to the ordinary fixed-function D3D11 combiner, then retarget exactly once.
+// The original pixel function runs unchanged (including its fog, shroud and alpha test).
+inline bool WrapPixel(std::string &source) {
+ const std::string fields=" float4 AlphaReference;";
+ const std::string entry="float4 main(Input input) : SV_Target";
+ const std::size_t at=source.find(fields),main=source.find(entry);
+ if(at==std::string::npos||main==std::string::npos) return false;
+ source.replace(main,entry.size(),"float4 shoreOriginalPixel(Input input) : SV_Target");
+ source.insert(at+fields.size(),R"HLSL(
+ row_major float4x4 ShoreWorldFromClip;
+ float4 ShoreViewport;
+ float4 ShoreTerrain;
+ float4 ShoreScene;
+ float4 ShoreSurface;
+)HLSL");
+ source+=R"HLSL(
+Texture2D Texture4 : register(t4);
+SamplerState Sampler4 : register(s4);
+Texture2D Texture6 : register(t6);
+SamplerState Sampler6 : register(s6);
+bool shoreUnproject(float2 pixel,float d,out float3 world) {
+ float2 uv=(pixel-ShoreViewport.xy)/max(ShoreViewport.zw,1.0.xx);
+ float4 p=mul(float4(uv*float2(2,-2)+float2(-1,1),d,1),ShoreWorldFromClip);
+ world=0;
+ if(!all(isfinite(p))||abs(p.w)<1e-8) return false;
+ world=p.xyz/p.w;
+ return all(isfinite(world));
+}
+float shoreReplacement(float2 originalPixel) {
+ if(!isfinite(ShoreScene.w)||ShoreScene.w<=.5||ShoreTerrain.w<.5||ShoreSurface.z<.5) return 0;
+ float2 first=max(.5.xx,ShoreViewport.xy);
+ float2 last=min(1.0/ShoreScene.yz-.5,ShoreViewport.xy+ShoreViewport.zw-1);
+ float2 pixel=clamp(floor(originalPixel)+.5,first,last);
+ float d=Texture6.SampleLevel(Sampler6,pixel*ShoreScene.yz,0).r;
+ if(!isfinite(d)||d<0||d>=.999999) return 0;
+ float3 scene,a,b;
+ if(!shoreUnproject(pixel,d,scene)||!shoreUnproject(pixel,0,a)||!shoreUnproject(pixel,.5,b)) return 0;
+ float dz=b.z-a.z;
+ if(abs(dz)<1e-8) return 0;
+ // Reconstruct the actual elevated sprite plane. SV_Position.z includes legacy Z bias.
+ float2 plane=a.xy+(b.xy-a.xy)*((ShoreSurface.y-a.z)/dz);
+ if(!all(isfinite(plane))) return 0;
+ float2 uv=(plane+ShoreTerrain.xx+5)/max(ShoreTerrain.y,1);
+ if(any(uv<0)||any(uv>1)) return 0;
+ float4 coast=Texture4.SampleLevel(Sampler4,uv,0);
+ if(!all(isfinite(coast))) return 0;
+ float2 groundUV=(scene.xy+ShoreTerrain.xx+5)/max(ShoreTerrain.y,1);
+ if(any(groundUV<0)||any(groundUV>1)) return 0;
+ float ground=Texture2.SampleLevel(Sampler2,groundUV,0).r*ShoreTerrain.z;
+ if(!isfinite(ground)) return 0;
+ // The accepted modern patch owns this authored surf quad. R only blends wave
+ // models, and A only locates fresh breaking; neither limits that ownership.
+ // Keeping either here leaves old travelling sprites outside the source band.
+ // Actual terrain/depth checks still preserve objects and unavailable resources.
+ return 1-smoothstep(.5,1.5,abs(scene.z-ground));
+}
+float4 main(Input input) : SV_Target {
+ float4 result=shoreOriginalPixel(input);
+ result.a*=1-shoreReplacement(input.Position.xy);
+ return result;
+}
+)HLSL";
+ return true;
+}
+} // namespace WaterShoreOverlay
+
+#ifndef _WIN32
+class IDirect3DDevice9;
+// Scope is one actual WaterRender call. Null tags clear pending metadata immediately.
+void PosixWaterShoreBegin(IDirect3DDevice9 *,bool enabled);
+void PosixWaterShoreEnd(IDirect3DDevice9 *);
+void PosixWaterShorePatch(IDirect3DDevice9 *,const WaterShoreOverlay::Quad *);
+void PosixWaterShoreTrack(IDirect3DDevice9 *,const WaterShoreOverlay::Quad *);
+namespace WaterShoreOverlay {
+struct Scope {
+ IDirect3DDevice9 *device;
+ Scope(IDirect3DDevice9 *d,bool enabled):device(d){PosixWaterShoreBegin(d,enabled);}
+ ~Scope(){PosixWaterShoreEnd(device);}
+ Scope(const Scope &)=delete;
+ Scope &operator=(const Scope &)=delete;
+};
+}
+#endif
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterShoreSource.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterShoreSource.h
new file mode 100644
index 000000000..25534cedd
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterShoreSource.h
@@ -0,0 +1,194 @@
+/* Fixed-world, bounded coastal source contexts. No camera, vessel or gameplay state. */
+#pragma once
+#include "Platform/WaterShoreFoam.h"
+#include "Platform/WaterShoreHistory.h"
+#include "Platform/WaterShoreSupport.h"
+#include "Platform/WaterOpticalContext.h"
+#include <array>
+
+namespace WaterShoreSource {
+struct Level {double level=0;const WaterOpticalContext::Field *field=nullptr;};
+struct SampleContext {
+ WaterShoreFoam::Context coast;
+ WaterShoreFoam::FrontWeights frontWeights;
+ std::array<float,WaterShoreFoam::ModeCount> sine{},cosine{};
+};
+struct Context : SampleContext {std::array<SampleContext,4> quadrature;};
+using Interval=WaterOpticalContext::Interval;
+// Exact scanline union, including authored edges. Every accepted diffusion segment
+// lies entirely inside a union interval, rather than testing only its endpoints.
+using WaterOpticalContext::Intervals;
+inline bool Covered(const std::vector<Interval>&spans,double a,double b) {
+ const auto at=std::upper_bound(spans.begin(),spans.end(),a,
+ [](double x,const Interval&i){return x<i.first;});
+ return at!=spans.begin()&&(at-1)->second>=b;
+}
+inline float Height(const uint8_t*heights,int width,int height,double x,double y,double scale) {
+ x=WaterShoreHistory::Clamp(x,0,width-1.000001);y=WaterShoreHistory::Clamp(y,0,height-1.000001);
+ const int ix=int(x),iy=int(y);const double fx=x-ix,fy=y-iy;const size_t n=size_t(iy)*width+ix;
+ return float(((heights[n]*(1-fx)+heights[n+1]*fx)*(1-fy)
+ +(heights[n+width]*(1-fx)+heights[n+width+1]*fx)*fy)*scale);
+}
+inline float FieldSample(const std::vector<uint8_t>&field,int width,int x,int y,float fx,float fy) {
+ const size_t n=size_t(y)*width+x;
+ return ((field[n]*(1-fx)+field[n+1]*fx)*(1-fy)
+ +(field[n+width]*(1-fx)+field[n+width+1]*fx)*fy)/255.0f;
+}
+class Batch {
+ WaterShoreHistory::Grid grid;
+ std::vector<WaterShoreHistory::Cell> cells;
+ std::vector<Context> contexts;
+ WaterShoreSupport::Domain support;
+public:
+ WaterShoreHistory::BuildResult Build(const uint8_t*heights,int width,int height,int border,
+ double spacing,double heightScale,const std::vector<WaterOpticalContext::Polygon>&polygons,
+ const std::vector<Level>&levels) {
+ using namespace WaterShoreHistory;
+ if(!heights||width<2||height<2||width>WaterOpticalContext::MaxDimension||height>WaterOpticalContext::MaxDimension
+ ||size_t(width)*height>WaterOpticalContext::MaxCells||border<0||border>(width-2)/2||border>(height-2)/2
+ ||!std::isfinite(spacing)||spacing<2||spacing>2048||!std::isfinite(heightScale)||heightScale<=0)
+ return BuildResult::Invalid;
+ if(levels.size()>MaxLevels)return BuildResult::TooManyLevels;
+ size_t points=0;
+ for(const auto&polygon:polygons) {
+ if(polygon.points.size()>WaterOpticalContext::MaxPoints-points)return BuildResult::Invalid;
+ points+=polygon.points.size();
+ for(const auto&p:polygon.points)if(!std::isfinite(p.x)||!std::isfinite(p.y)||!std::isfinite(p.z))return BuildResult::Invalid;
+ }
+ Batch next;next.grid={-border*spacing,-border*spacing,spacing*.5};
+ std::vector<double> seen;
+ for(const Level&entry:levels) {
+ if(!entry.field||!std::isfinite(entry.level))return BuildResult::Invalid;
+ if(std::find(seen.begin(),seen.end(),entry.level)!=seen.end())return BuildResult::Invalid;
+ seen.push_back(entry.level);
+ const auto&f=*entry.field;const size_t count=size_t(width)*height;
+ if(f.ocean.size()!=count||f.shore.size()!=count||f.exposure.size()!=count||f.coast.size()!=count)return BuildResult::Invalid;
+ const size_t first=next.cells.size();
+ auto sample=[&](double px,double py) {
+ SampleContext context;
+ if(px<0||py<0||px>=width-1||py>=height-1)return context;
+ const int ix=int(px),iy=int(py);const float fx=float(px-ix),fy=float(py-iy);
+ const float terrain=Height(heights,width,height,px,py,heightScale);
+ if(!(terrain<entry.level)||FieldSample(f.ocean,width,ix,iy,fx,fy)>0)return context;
+ const double offset=5.0/spacing;
+ const float gx=(Height(heights,width,height,px+offset,py,heightScale)
+ -Height(heights,width,height,px-offset,py,heightScale))*.1f;
+ const float gy=(Height(heights,width,height,px,py+offset,heightScale)
+ -Height(heights,width,height,px,py-offset,heightScale))*.1f;
+ context.coast.depth=float(entry.level)-terrain;
+ context.coast.nx=-gx;context.coast.ny=-gy;context.coast.slope=std::hypot(gx,gy);
+ context.coast.shore=(std::min)(FieldSample(f.shore,width,ix,iy,fx,fy)*100,
+ context.coast.depth/(std::max)(context.coast.slope,.01f));
+ context.coast.support=FieldSample(f.coast,width,ix,iy,fx,fy);
+ context.coast.exposure=FieldSample(f.exposure,width,ix,iy,fx,fy);
+ context.frontWeights=WaterShoreFoam::IncomingWeights(context.coast.nx,context.coast.ny);
+ const double worldX=next.grid.originX+px*spacing,worldY=next.grid.originY+py*spacing;
+ for(unsigned mode=0;mode<WaterShoreFoam::ModeCount;++mode) {
+ const auto&m=WaterShoreFoam::Modes[mode];
+ const float phase=float(worldX)*m.kx+float(worldY)*m.ky+m.phase;
+ context.sine[mode]=std::sin(phase);context.cosine[mode]=std::cos(phase);
+ }
+ return context;
+ };
+ for(int y=0;y<2*(height-1);++y) {
+ const double worldY=next.grid.originY+y*next.grid.spacing;
+ const auto row=Intervals(polygons,entry.level,worldY,true);
+ if(row.empty())continue;
+ const std::array<std::vector<Interval>,2> quadratureRows={
+ Intervals(polygons,entry.level,worldY-next.grid.spacing*.25,true),
+ Intervals(polygons,entry.level,worldY+next.grid.spacing*.25,true)};
+ for(int x=0;x<2*(width-1);++x) {
+ const int ix=x/2,iy=y/2;const float fx=(x%2)*.5f,fy=(y%2)*.5f;
+ // Include a one-terrain-cell margin around support for wet-only spreading.
+ bool near=false;
+ for(int yy=(std::max)(0,iy-1);yy<=(std::min)(height-1,iy+2)&&!near;++yy)
+ for(int xx=(std::max)(0,ix-1);xx<=(std::min)(width-1,ix+2);++xx)
+ near=near||f.coast[size_t(yy)*width+xx]!=0;
+ if(!near||FieldSample(f.ocean,width,ix,iy,fx,fy)>0)continue;
+ const double worldX=next.grid.originX+x*next.grid.spacing;
+ if(!Covered(row,worldX,worldX))continue;
+ const float terrain=Height(heights,width,height,x*.5,y*.5,heightScale);
+ if(!(terrain<entry.level))continue;
+ if(next.cells.size()>=MaxCells)return BuildResult::TooManyCells;
+ Context context;static_cast<SampleContext&>(context)=sample(x*.5,y*.5);
+ // Fixed2x2 area quadrature captures narrow wet source bands and the
+ // nonlinear crest/incoming gates; dry/outside subnodes contribute zero.
+ // It does not expand the wet graph or connect across polygon gaps.
+ for(unsigned sy=0;sy<2;++sy)for(unsigned sx=0;sx<2;++sx) {
+ const double px=x*.5+(sx?.125:-.125),py=y*.5+(sy?.125:-.125);
+ const double qx=next.grid.originX+px*spacing;
+ if(Covered(quadratureRows[sy],qx,qx))context.quadrature[sy*2+sx]=sample(px,py);
+ }
+ const uint8_t connections=Covered(row,worldX,worldX+next.grid.spacing)?1:0;
+ next.cells.push_back({x,y,entry.level,uint32_t(next.contexts.size()),connections});
+ next.contexts.push_back(context);
+ }
+ }
+ // Cache one vertical scanline at a time, using bounded cell indices rather than
+ // scanning polygon edges once for every history node.
+ std::vector<size_t> columnOrder;
+ for(size_t i=first;i<next.cells.size();++i)columnOrder.push_back(i);
+ std::sort(columnOrder.begin(),columnOrder.end(),[&](size_t a,size_t b){return next.cells[a].x<next.cells[b].x;});
+ int previous=-1;std::vector<Interval> column;
+ for(size_t i:columnOrder) {
+ auto&cell=next.cells[i];
+ if(cell.x!=previous){previous=cell.x;column=Intervals(polygons,entry.level,next.grid.originX+cell.x*next.grid.spacing,false);}
+ const double worldY=next.grid.originY+cell.y*next.grid.spacing;
+ if(Covered(column,worldY,worldY+next.grid.spacing))cell.connections|=2;
+ }
+ }
+ auto terrain=[&](double x,double y){return Height(heights,width,height,x,y,heightScale);};
+ if(!next.support.Build(next.grid,next.cells,width,height,polygons,terrain))return BuildResult::Invalid;
+ *this=std::move(next);return BuildResult::Ready;
+ }
+ void operator()(double time,const WaterShoreHistory::Cell*nodes,size_t count,double*rates) const {
+ std::array<float,WaterShoreFoam::ModeCount> sine{},cosine{};
+ for(unsigned mode=0;mode<WaterShoreFoam::ModeCount;++mode) {
+ const float phase=-float(time)*WaterShoreFoam::Modes[mode].omega;
+ sine[mode]=std::sin(phase);cosine[mode]=std::cos(phase);
+ }
+ for(size_t i=0;i<count;++i) {
+ rates[i]=0;if(nodes[i].sourceIndex>=contexts.size())continue;
+ const Context&node=contexts[nodes[i].sourceIndex];
+ for(const SampleContext&context:node.quadrature) {
+ if(context.coast.support<=0)continue;
+ WaterShoreFoam::Wave wave;float front=0;
+ for(unsigned mode=0;mode<WaterShoreFoam::ModeCount;++mode) {
+ const auto&m=WaterShoreFoam::Modes[mode];
+ const float s=context.sine[mode]*cosine[mode]+context.cosine[mode]*sine[mode];
+ const float c=context.cosine[mode]*cosine[mode]-context.sine[mode]*sine[mode];
+ const float derivative=m.amplitude*(c+.26f*(c*c-s*s));
+ wave.height+=m.amplitude*(s+.26f*s*c);wave.dx+=derivative*m.kx;wave.dy+=derivative*m.ky;wave.dt-=derivative*m.omega;
+ front+=context.frontWeights.value[mode]*WaterShoreFoam::FrontKernel(s,c);
+ }
+ // A phase-locked birth mask only removes old-source support. No new
+ // per-cell trigonometry, graph cells, upload work or time state is added.
+ rates[i]+=.25*WaterShoreFoam::Rate(context.coast,wave)*WaterShoreFoam::Clamp(front,0,1);
+ }
+ }
+ }
+ const WaterShoreHistory::Grid&Grid()const{return grid;}
+ const std::vector<WaterShoreHistory::Cell>&Cells()const{return cells;}
+ const std::vector<Context>&Contexts()const{return contexts;}
+ const WaterShoreSupport::Domain&Support()const{return support;}
+ void Clear(){*this=Batch();}
+};
+// Density and its age moment become a porous, world-anchored surface coverage.
+// The material has no dependence on vessel heading, render count or atlas mapping.
+inline double Noise(double x,double y) {
+ auto hash=[](int64_t x,int64_t y){uint64_t h=uint64_t(x)*0x9e3779b97f4a7c15ULL^uint64_t(y)*0xbf58476d1ce4e5b9ULL;
+ h=(h^(h>>30))*0xbf58476d1ce4e5b9ULL;h=(h^(h>>27))*0x94d049bb133111ebULL;return double((h^(h>>31))&0xffffffu)/16777215.0;};
+ const int64_t ix=int64_t(std::floor(x)),iy=int64_t(std::floor(y));
+ double fx=x-ix,fy=y-iy;fx=fx*fx*(3-2*fx);fy=fy*fy*(3-2*fy);
+ return (hash(ix,iy)*(1-fx)+hash(ix+1,iy)*fx)*(1-fy)+(hash(ix,iy+1)*(1-fx)+hash(ix+1,iy+1)*fx)*fy;
+}
+inline double Coverage(const WaterShoreHistory::State&s,double x,double y,double) {
+ if(!(s.density>0)||!std::isfinite(s.density)||!std::isfinite(s.ageMoment))return 0;
+ const double age=s.ageMoment/s.density;
+ const double texture=Noise(x/7,y/7)*.7+Noise(x/2.3,y/2.3)*.3;
+ const double breakup=WaterShoreFoam::Smooth(.25f,.7f,float(texture));
+ const double aged=WaterShoreFoam::Smooth(.4f,3.0f,float(age));
+ const double terminal=1-WaterShoreFoam::Smooth(8,14,float(age));
+ return -std::expm1(-s.density)*(1-aged+aged*breakup)*terminal;
+}
+}
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterShoreSupport.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterShoreSupport.h
new file mode 100644
index 000000000..a33c83747
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterShoreSupport.h
@@ -0,0 +1,219 @@
+/* Support for history interpolation: a sample may only see a node along a wet,
+ polygon-covered segment. Original bilinear weights are never renormalized. */
+#pragma once
+#include "Platform/WaterShoreHistory.h"
+#include "Platform/WaterOpticalContext.h"
+#include <array>
+
+namespace WaterShoreSupport {
+constexpr size_t MaxTiles=4*WaterShoreHistory::MaxCells;
+constexpr size_t MaxTileVertices=128,MaxVertices=16*WaterShoreHistory::MaxCells;
+constexpr size_t MaxWork=8*1024*1024,MaxClipVertices=4*WaterOpticalContext::MaxPoints;
+enum class AreaResult {Covered,Unsupported,OverBudget};
+struct Point {double x=0,y=0;};
+struct Polygon {uint32_t first=0,count=0;};
+struct Tile {
+ int32_t x=0,y=0;double level=0;
+ std::array<float,4> heights{};
+ uint32_t first=0,count=0;
+ bool interior=false,wet=false;
+};
+inline bool Less(const Tile&a,const Tile&b) {
+ if(a.level!=b.level)return a.level<b.level;
+ if(a.y!=b.y)return a.y<b.y;return a.x<b.x;
+}
+inline bool Same(const Tile&a,const Tile&b){return a.x==b.x&&a.y==b.y&&a.level==b.level;}
+// True only when a nonempty part of an edge lies in the OPEN square.
+inline bool CrossesInterior(Point a,Point b) {
+ double low=0,high=1;
+ for(unsigned axis=0;axis<2;++axis) {
+ const double p=axis?a.y:a.x,d=axis?b.y-a.y:b.x-a.x;
+ if(d==0){if(p<=0||p>=1)return false;continue;}
+ const double u=-p/d,v=(1-p)/d;
+ low=(std::max)(low,(std::min)(u,v));high=(std::min)(high,(std::max)(u,v));
+ }
+ if(!(high>low))return false;
+ const double t=(low+high)*.5,x=a.x+(b.x-a.x)*t,y=a.y+(b.y-a.y)*t;
+ return x>0&&x<1&&y>0&&y<1;
+}
+class Domain {
+ WaterShoreHistory::Grid grid;
+ std::vector<Tile> tiles;
+ std::vector<Polygon> shapes;
+ std::vector<Point> vertices;
+ size_t work=0;
+ bool Spend(size_t amount=1){if(amount>MaxWork-work)return false;work+=amount;return true;}
+ static double Height(const Tile&t,double x,double y) {
+ return (t.heights[0]*(1-x)+t.heights[1]*x)*(1-y)
+ +(t.heights[2]*(1-x)+t.heights[3]*x)*y;
+ }
+ bool PolygonSegment(const Tile&t,Point a,Point b)const {
+ if(t.interior)return true;
+ const double dx=b.x-a.x,dy=b.y-a.y,length2=dx*dx+dy*dy;
+ // The start is an admitted source node. This limit is < 1e-9 world units.
+ if(length2<1e-24)return true;
+ std::array<std::pair<double,double>,3*MaxTileVertices> spans;
+ size_t spanCount=0;
+ for(size_t shape=t.first;shape<size_t(t.first)+t.count;++shape) {
+ const Polygon&p=shapes[shape];std::array<double,MaxTileVertices> crossings;size_t count=0;
+ for(size_t i=0,j=p.count-1;i<p.count;j=i++) {
+ const Point&v=vertices[p.first+i];const Point&u=vertices[p.first+j];
+ const double vx=v.x-a.x,vy=v.y-a.y,ux=u.x-a.x,uy=u.y-a.y;
+ double va=vx*dy-vy*dx,ua=ux*dy-uy*dx;
+ // Roundoff tolerance in normalized square coordinates, not a world-sized gap.
+ if(std::abs(va)<1e-13)va=0;if(std::abs(ua)<1e-13)ua=0;
+ const double vp=(vx*dx+vy*dy)/length2,up=(ux*dx+uy*dy)/length2;
+ if((va>0)!=(ua>0))crossings[count++]=vp+(up-vp)*(-va)/(ua-va);
+ if(va==0) {
+ spans[spanCount++]={vp,vp};
+ if(ua==0)spans[spanCount++]={(std::min)(vp,up),(std::max)(vp,up)};
+ }
+ }
+ std::sort(crossings.begin(),crossings.begin()+count);
+ for(size_t i=0;i+1<count;i+=2)spans[spanCount++]={crossings[i],crossings[i+1]};
+ }
+ std::sort(spans.begin(),spans.begin()+spanCount);
+ double covered=0;
+ for(size_t i=0;i<spanCount;++i) {
+ if(spans[i].second<-1e-12)continue;
+ if(spans[i].first>covered+1e-12)return false;
+ covered=(std::max)(covered,spans[i].second);
+ if(covered>=1-1e-12)return true;
+ }
+ return false;
+ }
+ AreaResult CoversRectangle(const Tile&t,double x0,double y0,double x1,double y1,size_t &remaining)const {
+ if(!std::isfinite(x0)||!std::isfinite(y0)||!std::isfinite(x1)||!std::isfinite(y1)
+ ||x0<0||y0<0||x1>1||y1>1||x1<=x0||y1<=y0)return AreaResult::Unsupported;
+ auto spend=[&](size_t n=1){if(n>remaining)return false;remaining-=n;return true;};
+ if(!spend(5))return AreaResult::OverBudget;
+ // A bilinear function's maximum on an axis-aligned rectangle is attained
+ // at a corner. This certifies its WHOLE area, including diagonal saddles.
+ if(!t.wet && !(Height(t,x0,y0)<t.level&&Height(t,x1,y0)<t.level
+ &&Height(t,x0,y1)<t.level&&Height(t,x1,y1)<t.level))return AreaResult::Unsupported;
+ if(t.interior)return AreaResult::Covered;
+ const double cx=(x0+x1)*.5,cy=(y0+y1)*.5,rx=1/(x1-x0),ry=1/(y1-y0);
+ for(size_t shape=t.first;shape<size_t(t.first)+t.count;++shape) {
+ if(!spend())return AreaResult::OverBudget;
+ const Polygon&p=shapes[shape];bool inside=false,crosses=false;
+ for(size_t i=0,j=p.count-1;i<p.count;j=i++) {
+ if(!spend())return AreaResult::OverBudget;
+ const Point&a=vertices[p.first+j],&b=vertices[p.first+i];
+ // Merely testing corners or polygon vertices misses thin cuts.
+ // Every segment is tested against the OPEN rectangle interior.
+ if(CrossesInterior({(a.x-x0)*rx,(a.y-y0)*ry},{(b.x-x0)*rx,(b.y-y0)*ry})) {crosses=true;break;}
+ if((a.y>cy)!=(b.y>cy))inside=inside^(cx<a.x+(cy-a.y)*(b.x-a.x)/(b.y-a.y));
+ }
+ // With no boundary entering the connected rectangle interior, one
+ // interior point fixes its membership. Single-polygon coverage is a
+ // sufficient proof; union-only seams are deliberately rejected.
+ if(!crosses&&inside)return AreaResult::Covered;
+ }
+ return AreaResult::Unsupported;
+ }
+ bool Allows(const Tile&t,unsigned corner,double x,double y)const {
+ const Point node={double(corner&1),double(corner>>1)},target={x,y};
+ if(!t.wet) {
+ // A straight segment in a half-terrain-cell square has quadratic height.
+ // Check its interior maximum too: wet endpoints can straddle a dry saddle.
+ const double h0=t.heights[corner],h1=Height(t,x,y);
+ if(!(h0<t.level&&h1<t.level))return false;
+ const double hm=Height(t,(node.x+x)*.5,(node.y+y)*.5);
+ const double a=2*(h1+h0-2*hm),b=h1-h0-a;
+ if(a<0) {
+ const double at=-b/(2*a);
+ if(at>0&&at<1&&a*at*at+b*at+h0>=t.level)return false;
+ }
+ }
+ return PolygonSegment(t,node,target);
+ }
+public:
+ struct Stencil {
+ const Domain*domain=nullptr;const Tile*tile=nullptr;double x=0,y=0;
+ bool Allows(unsigned dx,unsigned dy)const{return tile&&domain->Allows(*tile,dy*2+dx,x,y);}
+ AreaResult CoversRectangle(double x0,double y0,double x1,double y1,size_t &remaining)const {
+ return tile?domain->CoversRectangle(*tile,x0,y0,x1,y1,remaining):AreaResult::Unsupported;
+ }
+ };
+ Stencil At(int32_t x,int32_t y,double level,double fx,double fy)const {
+ Tile key;key.x=x;key.y=y;key.level=level;
+ const auto at=std::lower_bound(tiles.begin(),tiles.end(),key,Less);
+ return {this,at!=tiles.end()&&Same(*at,key)?&*at:nullptr,fx,fy};
+ }
+ template<class HeightSampler> bool Build(const WaterShoreHistory::Grid&inputGrid,
+ const std::vector<WaterShoreHistory::Cell>&cells,int width,int height,
+ const std::vector<WaterOpticalContext::Polygon>&polygons,HeightSampler sampleHeight) {
+ if(!WaterShoreHistory::ValidGrid(inputGrid)||cells.size()>WaterShoreHistory::MaxCells
+ ||width<2||height<2||width>WaterOpticalContext::MaxDimension||height>WaterOpticalContext::MaxDimension
+ ||size_t(width)*height>WaterOpticalContext::MaxCells||polygons.size()>WaterOpticalContext::MaxPoints/3)return false;
+ size_t totalPoints=0;
+ for(const auto&p:polygons) {
+ if(p.points.size()>WaterOpticalContext::MaxPoints-totalPoints)return false;totalPoints+=p.points.size();
+ for(const auto&v:p.points)if(!std::isfinite(v.x)||!std::isfinite(v.y)||!std::isfinite(v.z))return false;
+ }
+ Domain next;next.grid=inputGrid;
+ for(const auto&c:cells) {
+ if(c.x<0||c.y<0||c.x>=2*(width-1)||c.y>=2*(height-1)||!std::isfinite(c.level))return false;
+ for(int dy=-1;dy<=0;++dy)for(int dx=-1;dx<=0;++dx) {
+ if(c.x+dx<0||c.y+dy<0)continue;
+ Tile t;t.x=c.x+dx;t.y=c.y+dy;t.level=c.level;next.tiles.push_back(t);
+ }
+ }
+ std::sort(next.tiles.begin(),next.tiles.end(),Less);
+ next.tiles.erase(std::unique(next.tiles.begin(),next.tiles.end(),Same),next.tiles.end());
+ if(next.tiles.size()>MaxTiles)return false;
+ for(Tile&t:next.tiles) {
+ for(unsigned i=0;i<4;++i)t.heights[i]=sampleHeight((t.x+double(i&1))*.5,(t.y+double(i>>1))*.5);
+ t.wet=true;for(float h:t.heights){if(!std::isfinite(h))return false;t.wet=t.wet&&h<t.level;}
+ const double ox=next.grid.originX+t.x*next.grid.spacing,oy=next.grid.originY+t.y*next.grid.spacing;
+ std::vector<size_t> boundary;
+ for(size_t p=0;p<polygons.size();++p) {
+ if(!next.Spend())return false;
+ const auto&poly=polygons[p];if(poly.points.size()<3)continue;
+ bool same=true;for(const auto&v:poly.points) {
+ if(!next.Spend())return false;same=same&&std::abs(double(v.z)-t.level)<.01;
+ }
+ if(!same)continue;
+ bool inside=false,crosses=false;
+ for(size_t i=0,j=poly.points.size()-1;i<poly.points.size();j=i++) {
+ if(!next.Spend())return false;
+ const Point a={(poly.points[j].x-ox)/next.grid.spacing,(poly.points[j].y-oy)/next.grid.spacing};
+ const Point b={(poly.points[i].x-ox)/next.grid.spacing,(poly.points[i].y-oy)/next.grid.spacing};
+ crosses=crosses||CrossesInterior(a,b);
+ if((a.y>.5)!=(b.y>.5))inside=inside^(.5<a.x+(.5-a.y)*(b.x-a.x)/(b.y-a.y));
+ }
+ if(!crosses&&inside){t.interior=true;break;}
+ if(crosses)boundary.push_back(p);
+ }
+ if(t.interior)continue;
+ t.first=uint32_t(next.shapes.size());size_t tileVertices=0;
+ for(size_t p:boundary) {
+ std::vector<Point> points,scratch;
+ for(const auto&v:polygons[p].points)points.push_back({(v.x-ox)/next.grid.spacing,(v.y-oy)/next.grid.spacing});
+ // Clipping a concave polygon to a convex square may create boundary bridges;
+ // even/odd scanline intervals still represent its interior union exactly.
+ for(unsigned plane=0;plane<4&&!points.empty();++plane) {
+ scratch.clear();
+ auto distance=[&](Point v){return plane==0?v.x:plane==1?1-v.x:plane==2?v.y:1-v.y;};
+ for(size_t i=0,j=points.size()-1;i<points.size();j=i++) {
+ if(!next.Spend())return false;
+ const Point a=points[j],b=points[i];const double da=distance(a),db=distance(b);
+ if((da>=0)!=(db>=0)) {const double u=da/(da-db);scratch.push_back({a.x+(b.x-a.x)*u,a.y+(b.y-a.y)*u});}
+ if(db>=0)scratch.push_back(b);
+ if(scratch.size()>MaxClipVertices)return false;
+ }
+ points.swap(scratch);
+ }
+ if(points.size()<3)continue;
+ if(points.size()>MaxTileVertices-tileVertices||points.size()>MaxVertices-next.vertices.size())return false;
+ next.shapes.push_back({uint32_t(next.vertices.size()),uint32_t(points.size())});
+ next.vertices.insert(next.vertices.end(),points.begin(),points.end());tileVertices+=points.size();++t.count;
+ }
+ }
+ *this=std::move(next);return true;
+ }
+ size_t TileCount()const{return tiles.size();}
+ size_t VertexCount()const{return vertices.size();}
+ size_t Work()const{return work;}
+};
+}
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterSurfaceModel.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterSurfaceModel.h
new file mode 100644
index 000000000..3bc110b87
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterSurfaceModel.h
@@ -0,0 +1,340 @@
+/* Render-only water displacement. No gameplay height, collision or navigation state. */
+#pragma once
+#include <cmath>
+#include <string>
+#include <cstdint>
+
+// kx, ky (radians/world unit), amplitude (world units), angular frequency, initial phase.
+// Differing dispersion and directions ensure this cannot be represented by scrolling a static map.
+#define WATER_SURFACE_MODES(X) \
+ X(0.1093f, 0.0395f, 1.30f, 0.94f, 0.17f) \
+ X(0.1571f,-0.1264f, 0.85f, 1.24f, 2.71f) \
+ X(0.2772f, 0.1810f, 0.50f, 1.59f, 4.13f) \
+ X(-0.1524f,0.4835f, 0.24f, 1.97f, 1.39f) \
+ X(0.6856f, 0.2624f, 0.095f,2.37f, 5.21f) \
+ X(0.7915f,-0.8025f, 0.061f,2.94f, 3.47f) \
+ X(-0.5575f,1.5408f,0.038f, 3.54f, 0.83f) \
+ X(1.9218f, 0.6150f, 0.026f,3.93f, 4.79f) \
+ X(2.4708f,-1.3037f, 0.016f,4.62f, 2.02f) \
+ X(-1.7671f,3.0640f,0.011f, 5.20f, 5.91f) \
+ X(4.0647f, 1.6195f, 0.007f,5.79f, 1.12f) \
+ X(3.0073f,-4.1009f, 0.005f,6.24f, 3.86f) \
+ X(0.3507f,-0.3705f, 0.110f,1.98f, 5.31f) \
+ X(-0.4731f,-0.2409f,0.090f,2.02f, 0.93f) \
+ X(0.6419f, 0.5344f, 0.085f,2.53f, 3.81f) \
+ X(-0.3787f,0.9255f, 0.064f,2.77f, 2.19f) \
+ X(1.0774f,-0.3441f, 0.060f,2.94f, 4.67f) \
+ X(-1.1037f,-0.8015f,0.046f,3.23f, 1.87f) \
+ X(0.1158f, 1.6119f, 0.040f,3.52f, 0.43f) \
+ X(1.7408f,-0.8109f, 0.032f,3.84f, 5.63f) \
+ X(-1.3733f,1.8788f, 0.025f,4.22f, 3.03f) \
+ X(2.8292f, 0.0917f, 0.020f,4.66f, 1.71f) \
+ X(-1.2031f,-2.9508f,0.016f,4.94f, 4.37f) \
+ X(2.3156f, 3.0217f, 0.013f,5.40f, 2.57f)
+
+namespace WaterSurfaceModel {
+struct Sample { float height, dx, dy; };
+inline Sample Evaluate(float x, float y, float seconds) {
+ Sample value = {0,0,0};
+#define WATER_MODE_EVAL(kx,ky,amplitude,omega,phase) { \
+ const float p = x*kx+y*ky-seconds*omega+phase; \
+ const float s = std::sin(p), c = std::cos(p); \
+ value.height += amplitude*(s+0.13f*2.0f*s*c); \
+ const float derivative = amplitude*(c+0.26f*(c*c-s*s)); \
+ value.dx += derivative*kx; value.dy += derivative*ky; }
+ WATER_SURFACE_MODES(WATER_MODE_EVAL)
+#undef WATER_MODE_EVAL
+ return value;
+}
+// Open water has its own spectrum. Height energy is shared by several crossing swells rather
+// than concentrated into the old river's first two directions. A slowly evolving coordinate
+// warp bends the crests, and a bounded packet envelope breaks their uniform strength.
+#define WATER_OCEAN_MODES(X) \
+ X( 0.1074f, 0.0423f,1.200f,1.02f,0.31f) \
+ X( 0.1383f,-0.1092f,1.000f,1.25f,2.41f) \
+ X(-0.0729f, 0.2148f,0.900f,1.52f,4.33f) \
+ X( 0.2481f, 0.1554f,0.720f,1.75f,1.20f) \
+ X(-0.2952f, 0.1176f,0.600f,1.91f,5.17f) \
+ X( 0.1689f,-0.3501f,0.480f,2.15f,3.62f) \
+ X( 0.4443f, 0.0519f,0.360f,2.37f,0.83f) \
+ X(-0.3387f,-0.3822f,0.260f,2.49f,4.71f) \
+ X( 0.0891f, 0.6243f,0.180f,2.74f,2.07f) \
+ X( 0.6642f,-0.3291f,0.120f,3.00f,5.91f) \
+ X(-0.6801f, 0.5724f,0.085f,3.24f,1.79f) \
+ X( 0.8943f, 0.3048f,0.060f,3.51f,3.11f) \
+ X( 0.7300f, 0.3600f,0.110f,3.32f,4.61f) \
+ X( 0.9300f,-0.6400f,0.084f,3.74f,0.73f) \
+ X(-1.2400f, 0.3100f,0.062f,4.08f,2.97f) \
+ X(-0.8200f,-1.3500f,0.050f,4.47f,5.13f) \
+ X( 1.6800f, 0.5200f,0.036f,4.72f,1.87f) \
+ X( 1.4500f,-1.8000f,0.026f,5.19f,3.43f) \
+ X(-2.6300f, 0.8800f,0.020f,5.64f,0.29f) \
+ X( 0.6200f, 3.3400f,0.016f,6.02f,4.07f)
+
+struct OceanSurface { float height,dx,dy,laplacian; };
+template<bool Curvature,bool Slopes=true,bool SwellOnly=false> inline OceanSurface EvaluateOceanInternal(float x,float y,float seconds) {
+ const float q0=x*0.0241f+y*0.0157f-seconds*0.23f+0.4f;
+ const float q1=x*-0.0173f+y*0.0299f-seconds*0.19f+2.1f;
+ const float s0=std::sin(q0),c0=std::cos(q0),s1=std::sin(q1),c1=std::cos(q1);
+ const float px=x+5.0f*s0,py=y+4.0f*s1;
+ const float xx=1.0f+5.0f*c0*0.0241f,xy=5.0f*c0*0.0157f;
+ const float yx=4.0f*c1*-0.0173f,yy=1.0f+4.0f*c1*0.0299f;
+ const float q0Length2=0.0241f*0.0241f+0.0157f*0.0157f;
+ const float q1Length2=0.0173f*0.0173f+0.0299f*0.0299f;
+ const float qDot=0.0241f*-0.0173f+0.0157f*0.0299f;
+ const float lapX=-5.0f*s0*q0Length2,lapY=-4.0f*s1*q1Length2;
+ OceanSurface value={0,0,0,0};
+#define WATER_OCEAN_EVAL(kx,ky,amplitude,omega,phase) if (!SwellOnly || kx*kx+ky*ky<0.18f) { \
+ const float p=px*kx+py*ky-seconds*omega+phase; \
+ const float s=std::sin(p),c=std::cos(p); \
+ value.height+=amplitude*(s+0.16f*s*c); \
+ if (Slopes || Curvature) { \
+ const float derivative=amplitude*(c+0.16f*(c*c-s*s)); \
+ const float phaseX=kx*xx+ky*yx,phaseY=kx*xy+ky*yy; \
+ value.dx+=derivative*phaseX; value.dy+=derivative*phaseY; \
+ if (Curvature) value.laplacian+=amplitude*(-s-0.64f*s*c)*(phaseX*phaseX+phaseY*phaseY)+derivative*(kx*lapX+ky*lapY); } }
+ WATER_OCEAN_MODES(WATER_OCEAN_EVAL)
+#undef WATER_OCEAN_EVAL
+ const float envelope=0.86f+0.14f*s0*s1;
+ const float ex=0.14f*(c0*0.0241f*s1+s0*c1*-0.0173f);
+ const float ey=0.14f*(c0*0.0157f*s1+s0*c1*0.0299f);
+ const float lapEnvelope=0.14f*(-s0*s1*(q0Length2+q1Length2)+2.0f*c0*c1*qDot);
+ const float laplacian=Curvature ? value.laplacian*envelope+2.0f*(value.dx*ex+value.dy*ey)+value.height*lapEnvelope : 0.0f;
+ return {value.height*envelope,Slopes?value.dx*envelope+value.height*ex:0.0f,
+ Slopes?value.dy*envelope+value.height*ey:0.0f,laplacian};
+}
+inline OceanSurface EvaluateOceanSurface(float x,float y,float seconds) { return EvaluateOceanInternal<true>(x,y,seconds); }
+// Foam breaking and broad face lighting follow the swell curvature, rather than the much larger
+// second derivatives of tiny ripples. This subset retains exactly the full model's warp/envelope.
+inline OceanSurface EvaluateOceanSwell(float x,float y,float seconds) { return EvaluateOceanInternal<true,true,true>(x,y,seconds); }
+inline Sample EvaluateOcean(float x,float y,float seconds) {
+ // Displacement does not need curvature; the constant template branch removes its work.
+ const OceanSurface value=EvaluateOceanInternal<false>(x,y,seconds);
+ return {value.height,value.dx,value.dy};
+}
+// The fixed, unlit mesh vertex path does not consume ocean normals. Keep the same height
+// arithmetic while instantiating away derivatives; merely reading EvaluateOcean(...).height
+// still invokes its outlined full evaluator on the release compiler.
+inline float EvaluateOceanHeight(float x,float y,float seconds) {
+ return EvaluateOceanInternal<false,false>(x,y,seconds).height;
+}
+inline Sample BlendSamples(const Sample &river,const Sample &ocean,const Sample &offshore) {
+ const float blend=offshore.height<0?0:(offshore.height>1?1:offshore.height);
+ const float delta=ocean.height-river.height;
+ return {river.height+delta*blend,
+ river.dx+(ocean.dx-river.dx)*blend+delta*offshore.dx,
+ river.dy+(ocean.dy-river.dy)*blend+delta*offshore.dy};
+}
+inline Sample EvaluateBlended(float x,float y,float seconds,const Sample &offshore) {
+ if (offshore.height<=0 && offshore.dx==0 && offshore.dy==0) return Evaluate(x,y,seconds);
+ if (offshore.height>=1 && offshore.dx==0 && offshore.dy==0) return EvaluateOcean(x,y,seconds);
+ return BlendSamples(Evaluate(x,y,seconds),EvaluateOcean(x,y,seconds),offshore);
+}
+inline float EvaluateBlendedHeight(float x,float y,float seconds,const Sample &offshore) {
+ if (offshore.height<=0 && offshore.dx==0 && offshore.dy==0) return Evaluate(x,y,seconds).height;
+ if (offshore.height>=1 && offshore.dx==0 && offshore.dy==0) return EvaluateOceanHeight(x,y,seconds);
+ const float river=Evaluate(x,y,seconds).height,ocean=EvaluateOceanHeight(x,y,seconds);
+ const float blend=offshore.height<0?0:(offshore.height>1?1:offshore.height);
+ return river+(ocean-river)*blend;
+}
+// The GPU context texture repeats the last real row/column into its padding. Its texel-centre UV
+// maps to exactly these terrain-grid coordinates; derivatives here are per world unit.
+inline Sample SampleOffshore(const std::uint8_t *field,int width,int height,float gx,float gy,float spacing) {
+ if (!field || width<2 || height<2 || spacing<=0) return {0,0,0};
+ const bool clampX=gx<0 || gx>width-1,clampY=gy<0 || gy>height-1;
+ gx=gx<0?0:(gx>width-1?float(width-1):gx); gy=gy<0?0:(gy>height-1?float(height-1):gy);
+ const int ix=int(gx)<width-1?int(gx):width-2,iy=int(gy)<height-1?int(gy):height-2;
+ const float fx=gx-ix,fy=gy-iy;
+ const float a=field[iy*width+ix]/255.0f,b=field[iy*width+ix+1]/255.0f;
+ const float c=field[(iy+1)*width+ix]/255.0f,d=field[(iy+1)*width+ix+1]/255.0f;
+ return {(a+(b-a)*fx)*(1-fy)+(c+(d-c)*fx)*fy,
+ clampX?0:((b-a)*(1-fy)+(d-c)*fy)/spacing,
+ clampY?0:((c-a)*(1-fx)+(d-b)*fx)/spacing};
+}
+inline const char *OceanShaderSource() {
+#define WATER_OCEAN_HLSL(kx,ky,amplitude,omega,phase) \
+ "{ float p=dot(warped,float2(" #kx "," #ky "))-seconds*" #omega "+" #phase ";" \
+ "float s=sin(p),c=cos(p);float4 mode;mode.x=" #amplitude "*(s+0.16*s*c);" \
+ "float derivative=" #amplitude "*(c+0.16*(c*c-s*s));" \
+ "float2 phaseSlope=" #kx "*wx+" #ky "*wy;mode.yz=derivative*phaseSlope;" \
+ "mode.w=" #amplitude "*(-s-0.64*s*c)*dot(phaseSlope,phaseSlope)+derivative*dot(float2(" #kx "," #ky "),warpLaplacian);" \
+ "value+=mode;if(" #kx "*" #kx "+" #ky "*" #ky "<0.18) swell+=mode; }\n"
+ return "float4 waterOceanSurface(float2 pxy,float seconds,out float4 swell) {\n"
+ "float q0=dot(pxy,float2(0.0241,0.0157))-seconds*0.23+0.4;\n"
+ "float q1=dot(pxy,float2(-0.0173,0.0299))-seconds*0.19+2.1;\n"
+ "float s0=sin(q0),c0=cos(q0),s1=sin(q1),c1=cos(q1);\n"
+ "float2 warped=pxy+float2(5.0*s0,4.0*s1);\n"
+ "float2 wx=float2(1.0,0.0)+5.0*c0*float2(0.0241,0.0157);\n"
+ "float2 wy=float2(0.0,1.0)+4.0*c1*float2(-0.0173,0.0299);float4 value=0;swell=0;\n"
+ "float q0Length2=dot(float2(0.0241,0.0157),float2(0.0241,0.0157));\n"
+ "float q1Length2=dot(float2(-0.0173,0.0299),float2(-0.0173,0.0299));\n"
+ "float qDot=dot(float2(0.0241,0.0157),float2(-0.0173,0.0299));\n"
+ "float2 warpLaplacian=float2(-5.0*s0*q0Length2,-4.0*s1*q1Length2);\n"
+ WATER_OCEAN_MODES(WATER_OCEAN_HLSL)
+ "float envelope=0.86+0.14*s0*s1;\n"
+ "float2 envelopeSlope=0.14*(c0*s1*float2(0.0241,0.0157)+s0*c1*float2(-0.0173,0.0299));\n"
+ "float lapEnvelope=0.14*(-s0*s1*(q0Length2+q1Length2)+2.0*c0*c1*qDot);\n"
+ "float laplacian=value.w*envelope+2.0*dot(value.yz,envelopeSlope)+value.x*lapEnvelope;\n"
+ "swell=float4(swell.x*envelope,swell.yz*envelope+swell.x*envelopeSlope,"
+ "swell.w*envelope+2.0*dot(swell.yz,envelopeSlope)+swell.x*lapEnvelope);\n"
+ "return float4(value.x*envelope,value.yz*envelope+value.x*envelopeSlope,laplacian); }\n"
+ "float4 waterOceanSurface(float2 pxy,float seconds) { float4 swell;return waterOceanSurface(pxy,seconds,swell); }\n"
+ "float3 waterOceanWave(float2 pxy,float seconds) { return waterOceanSurface(pxy,seconds).xyz; }\n";
+#undef WATER_OCEAN_HLSL
+}
+inline const char *ShaderSource() {
+#define WATER_MODE_HLSL(kx,ky,amplitude,omega,phase) \
+ "{ float p=dot(pxy,float2(" #kx "," #ky "))-seconds*" #omega "+" #phase ";" \
+ "float s=sin(p), c=cos(p); value.x+=" #amplitude "*(s+0.26*s*c);" \
+ "float2 slope=" #amplitude "*(c+0.26*(c*c-s*s))*float2(" #kx "," #ky ");value.yz+=slope;" \
+ "if(" #kx "*" #kx "+" #ky "*" #ky ">=1.0) rippleSlope+=slope; }\n"
+ return "float3 waterWave(float2 pxy,float seconds,out float2 rippleSlope) { float3 value=0;rippleSlope=0;\n"
+ WATER_SURFACE_MODES(WATER_MODE_HLSL)
+ "return value; }\n"
+ "float3 waterWave(float2 pxy,float seconds) { float2 rippleSlope;return waterWave(pxy,seconds,rippleSlope); }\n";
+#undef WATER_MODE_HLSL
+}
+inline void AppendHLSL(std::string &source) { source += ShaderSource(); source += OceanShaderSource(); }
+inline float AdvanceTime(float seconds, float elapsed, bool paused, bool scriptFrozen, bool debugFrozen) {
+ if (paused || scriptFrozen || debugFrozen) return seconds;
+ return seconds + (elapsed < 0 ? 0 : (elapsed > 0.1f ? 0.1f : elapsed));
+}
+inline float ShoreDamping(float depth) {
+ float t = depth/9.0f;
+ t = t < 0 ? 0 : (t > 1 ? 1 : t);
+ return t*t*(3-2*t);
+}
+inline float BoxDamping(float x,float y,float major,float minor) {
+ const float qx=std::abs(x)-major,qy=std::abs(y)-minor;
+ const float outsideX=qx>0?qx:0,outsideY=qy>0?qy:0;
+ const float inside=qx>qy?qx:qy;
+ return ShoreDamping(std::sqrt(outsideX*outsideX+outsideY*outsideY)+(inside<0?inside:0));
+}
+inline bool BeyondObstacleFade(float dx,float dy,float radius) {
+ // A one-unit conservative margin avoids changing results at the floating-point boundary
+ // of the nine-unit fade. The bounding circle also encloses every oriented box footprint.
+ const float reach=radius+10.0f;
+ return dx*dx+dy*dy>reach*reach;
+}
+#define WATER_MODE_BOUND(kx,ky,amplitude,omega,phase) + amplitude * 1.13f
+constexpr float LegacyMaxDisplacement = 0.0f WATER_SURFACE_MODES(WATER_MODE_BOUND);
+#undef WATER_MODE_BOUND
+#define WATER_OCEAN_BOUND(kx,ky,amplitude,omega,phase) + amplitude * 1.08f
+constexpr float OceanMaxDisplacement = 0.0f WATER_OCEAN_MODES(WATER_OCEAN_BOUND);
+#undef WATER_OCEAN_BOUND
+constexpr float MaxDisplacement = OceanMaxDisplacement>LegacyMaxDisplacement?OceanMaxDisplacement:LegacyMaxDisplacement;
+inline std::uint32_t EncodeObstacleAttenuation(std::uint32_t diffuse,float attenuation) {
+ const float bounded=attenuation<0?0:(attenuation>1?1:attenuation);
+ return (diffuse&0xff00ffffu)|(std::uint32_t(bounded*255.0f+0.5f)<<16);
+}
+inline float TerrainDamping(float depth,float offshore) {
+ const float river=ShoreDamping(depth);
+ if (offshore<=0) return river;
+ const float blend=offshore>1?1:offshore;
+ float ocean=(depth-0.15f)/OceanMaxDisplacement;
+ ocean=ocean<0?0:(ocean>1?1:ocean);
+ return river+(ocean-river)*blend;
+}
+constexpr int MeshCells = 128;
+constexpr int MeshVertices = (MeshCells+1)*(MeshCells+1);
+constexpr int MeshTriangles = MeshCells*MeshCells*2;
+// This is a whole-map bound, before frustum rejection; each draw is still safely 16-bit indexed.
+// It permits 64 cells on multi-segment rivers and 128 on broad oceans, so near-camera silhouettes
+// resolve the dominant waves instead of relying on their shading to hide a sparse mesh.
+constexpr int VertexBudget = 262144;
+inline int IndexBatchRows(int cells) { return 65535/(cells*6); }
+inline int CellsForPatches(int patches) {
+ if (patches<=0) return MeshCells;
+ int cells=MeshCells;
+ while (cells>1 && static_cast<long long>(patches)*(cells+1)*(cells+1)>VertexBudget) cells/=2;
+ return cells;
+}
+// All patches use one camera-height LOD, so both sides of a shared edge change together.
+// Between two resolutions, the fine mesh morphs onto the coarse triangles before changing
+// topology. Full detail is retained below 120 world units above the highest authored water.
+struct MeshLOD { int cells; float morph; };
+constexpr float FullDetailHeight = 120.0f;
+constexpr float LODHeightRatio = 1.5f;
+constexpr int MinimumLODCells = 8;
+inline MeshLOD LODForCameraHeight(int baseCells, float height) {
+ MeshLOD lod={baseCells,0.0f};
+ const int minimum=baseCells<MinimumLODCells?baseCells:MinimumLODCells;
+ while (height>=LODHeightRatio*FullDetailHeight && lod.cells>minimum) {
+ height/=LODHeightRatio;
+ lod.cells/=2;
+ }
+ if (height>FullDetailHeight && lod.cells>minimum) {
+ const float t=(height-FullDetailHeight)/(FullDetailHeight*(LODHeightRatio-1.0f));
+ lod.morph=t*t*(3.0f-2.0f*t);
+ }
+ return lod;
+}
+// A map-wide open-water extent makes detail independent of view-frustum crossings. Keep the
+// existing river/pool LOD exactly on maps without a large ocean; the same budget and morph apply.
+inline MeshLOD LODForView(int baseCells,float height,float oceanExtent) {
+ float t=(oceanExtent-600.0f)/800.0f;
+ t=t<0?0:(t>1?1:t);
+ const float detailScale=1.0f+3.0f*t*t*(3.0f-2.0f*t);
+ return LODForCameraHeight(baseCells,height/detailScale);
+}
+// Every fine vertex is a coarse vertex or the midpoint of a coarse edge/diagonal. The same
+// a-to-d diagonal is used by the renderer's triangle indices. Endpoints are always even/even,
+// allowing an in-place morph pass without overwriting samples that another vertex still needs.
+struct CoarsePair { int first,second; };
+inline CoarsePair CoarsePairForVertex(int i,int j,int cells) {
+ const int side=cells+1,self=j*side+i;
+ if (cells<2) return {self,self};
+ const int ox=i&1,oy=j&1;
+ return {(j-oy)*side+i-ox,(j+oy)*side+i+ox};
+}
+inline float MorphCoordinate(float fine,float a,float b,float morph) {
+ if (morph<=0.0f) return fine;
+ const float coarse=(a+b)*0.5f;
+ if (morph>=1.0f) return coarse;
+ return fine+(coarse-fine)*morph;
+}
+inline std::uint32_t MorphColour(std::uint32_t fine,std::uint32_t a,std::uint32_t b,float morph) {
+ if (morph<=0.0f) return fine;
+ std::uint32_t result=0;
+ for (int shift=0;shift<32;shift+=8) {
+ const float value=MorphCoordinate(float((fine>>shift)&255),float((a>>shift)&255),float((b>>shift)&255),morph);
+ result|=std::uint32_t(value+0.5f)<<shift;
+ }
+ return result;
+}
+struct Point { float x,y,z; };
+inline Point Lerp(const Point &a, const Point &b, float t) {
+ return {a.x+(b.x-a.x)*t,a.y+(b.y-a.y)*t,a.z+(b.z-a.z)*t};
+}
+// A camera-dependent density warp moves continuously and keeps exact edge endpoints. Every patch
+// computes a shared edge in canonical endpoint order, so even reversed edges yield identical bytes.
+inline Point EdgePoint(Point a, Point b, float t, const Point &camera) {
+ if (a.x>b.x || (a.x==b.x && (a.y>b.y || (a.y==b.y && a.z>b.z)))) {
+ const Point swap=a; a=b; b=swap; t=1-t;
+ }
+ if (t<=0) return a;
+ if (t>=1) return b;
+ const float dx=b.x-a.x,dy=b.y-a.y,len2=dx*dx+dy*dy;
+ if (len2<0.0001f) return Lerp(a,b,t);
+ float focus=((camera.x-a.x)*dx+(camera.y-a.y)*dy)/len2;
+ focus=focus<0?0:(focus>1?1:focus);
+ const Point close=Lerp(a,b,focus);
+ const float ex=camera.x-close.x,ey=camera.y-close.y,ez=camera.z-close.z;
+ float radius=0.25f*std::sqrt((ex*ex+ey*ey+ez*ez)/len2);
+ radius=radius<0.025f?0.025f:(radius>0.65f?0.65f:radius);
+ const float lo=std::asinh(-focus/radius),hi=std::asinh((1-focus)/radius);
+ const float concentrated=focus+radius*std::sinh(lo+(hi-lo)*t);
+ return Lerp(a,b,0.35f*t+0.65f*concentrated);
+}
+// Coons blending preserves all four common boundary curves, including the degenerate edge of a
+// triangle. A modest warp preserves a broad uniform component, limiting stretched triangles.
+inline Point PatchPoint(const Point corners[4], const Point edges[4], float u, float v) {
+ if (v==0) return edges[0];
+ if (u==1) return edges[1];
+ if (v==1) return edges[2];
+ if (u==0) return edges[3];
+ const Point a=Lerp(edges[0],edges[2],v),b=Lerp(edges[3],edges[1],u);
+ const Point linear=Lerp(Lerp(corners[0],corners[1],u),Lerp(corners[3],corners[2],u),v);
+ return {a.x+b.x-linear.x,a.y+b.y-linear.y,a.z+b.z-linear.z};
+}
+}
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterTerrainCulling.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterTerrainCulling.h
new file mode 100644
index 000000000..ae279ed1d
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterTerrainCulling.h
@@ -0,0 +1,219 @@
+/* Render-only rejection of water triangles proven to be entirely below terrain. */
+#pragma once
+
+#include "Platform/WaterProjectedMesh.h"
+#include <limits>
+
+namespace WaterTerrainCulling
+{
+constexpr size_t MaxTriangleSamples = 1024;
+constexpr size_t MaxMeshSamples = 4u * 1024u * 1024u;
+
+// The terrain renderer triangulates each heightmap cell. Its surface can be above
+// the bilinear sample on a saddle, so require clearance over every cell corner.
+// Callers can use this to disable terrain occlusion proofs from below the ground.
+inline bool CameraAboveTerrain(
+ const uint8_t *heights, int width, int height, int border,
+ double spacing, double heightScale,
+ double cameraX, double cameraY, double cameraZ)
+{
+ if (!heights || width < 2 || height < 2 || width > 2048 || height > 2048 ||
+ border < 0 || border > (width - 2) / 2 || border > (height - 2) / 2 ||
+ !std::isfinite(spacing) || spacing <= 0 ||
+ !std::isfinite(heightScale) || heightScale <= 0 ||
+ !std::isfinite(cameraX) || !std::isfinite(cameraY) || !std::isfinite(cameraZ))
+ {
+ return false;
+ }
+
+ const double x = cameraX / spacing + border;
+ const double y = cameraY / spacing + border;
+ if (!std::isfinite(x) || !std::isfinite(y) ||
+ x < 0 || y < 0 || x > width - 1 || y > height - 1)
+ {
+ return false;
+ }
+
+ const int x0 = int(x);
+ const int y0 = int(y);
+ const int x1 = (std::min)(x0 + 1, width - 1);
+ const int y1 = (std::min)(y0 + 1, height - 1);
+ const uint8_t maximum = (std::max)(
+ (std::max)(heights[size_t(y0) * width + x0], heights[size_t(y0) * width + x1]),
+ (std::max)(heights[size_t(y1) * width + x0], heights[size_t(y1) * width + x1]));
+ const double ceiling = maximum * heightScale;
+ const double epsilon = 8 * std::numeric_limits<float>::epsilon() *
+ (std::max)(1.0, (std::max)(std::abs(ceiling), std::abs(cameraZ)));
+
+ return std::isfinite(ceiling) && cameraZ > ceiling + epsilon;
+}
+
+inline bool ValidMesh(const WaterProjectedMesh::Mesh &mesh)
+{
+ if (mesh.vertices.size() > 65536 || mesh.indices.size() % 3)
+ {
+ return false;
+ }
+
+ for (const auto &vertex : mesh.vertices)
+ {
+ if (!std::isfinite(vertex.world.x) || !std::isfinite(vertex.world.y))
+ {
+ return false;
+ }
+ }
+
+ for (uint16_t index : mesh.indices)
+ {
+ if (index >= mesh.vertices.size())
+ {
+ return false;
+ }
+ }
+
+ return true;
+}
+
+// All references in collars/transitions are world coordinates or authored edge IDs,
+// not mesh vertex indices. Retain those tables and each surviving vertex verbatim.
+inline void Install(WaterProjectedMesh::Mesh &mesh, std::vector<uint16_t> &indices)
+{
+ std::vector<int> remap(mesh.vertices.size(), -1);
+ for (uint16_t index : indices)
+ {
+ remap[index] = 0;
+ }
+
+ std::vector<WaterProjectedMesh::Vertex> vertices;
+ vertices.reserve(mesh.vertices.size());
+ for (size_t i = 0; i < remap.size(); ++i)
+ {
+ if (remap[i] == 0)
+ {
+ remap[i] = int(vertices.size());
+ vertices.push_back(mesh.vertices[i]);
+ }
+ }
+
+ for (uint16_t &index : indices)
+ {
+ index = uint16_t(remap[index]);
+ }
+
+ mesh.vertices.swap(vertices);
+ mesh.indices.swap(indices);
+}
+
+inline bool CompactVertices(WaterProjectedMesh::Mesh &mesh)
+{
+ if (!ValidMesh(mesh))
+ {
+ return false;
+ }
+
+ std::vector<uint16_t> indices = mesh.indices;
+ Install(mesh, indices);
+ return true;
+}
+
+// A bilinear terrain cell and either triangulation of that cell never fall below
+// their lowest corner. Inspect ALL corners of ALL cells overlapped by the displaced
+// triangle's bounds; sampling only the triangle endpoints can hide an interior pond.
+// The supplied displacement bounds must include every enabled surface effect.
+// Unknown/outside terrain and queries exceeding the work budget retain the triangle.
+// Invalid inputs leave the entire mesh unchanged. No partial geometry is removed.
+inline bool CullDryTriangles(
+ WaterProjectedMesh::Mesh &mesh, const uint8_t *heights,
+ int width, int height, int border, double spacing, double heightScale,
+ double level, double verticalBound, double horizontalBound)
+{
+ if (!heights || width < 2 || height < 2 || width > 2048 || height > 2048 ||
+ border < 0 || border > (width - 2) / 2 || border > (height - 2) / 2 ||
+ !std::isfinite(spacing) || spacing <= 0 ||
+ !std::isfinite(heightScale) || heightScale <= 0 || !std::isfinite(level) ||
+ !std::isfinite(verticalBound) || verticalBound < 0 ||
+ !std::isfinite(horizontalBound) || horizontalBound < 0 || !ValidMesh(mesh))
+ {
+ return false;
+ }
+
+ const double top = level + verticalBound;
+ if (!std::isfinite(top) || !std::isfinite(255 * heightScale))
+ {
+ return false;
+ }
+
+ // Vertices and shader displacement ultimately use float; include their rounding
+ // before converting bounds to grid cells and comparing terrain/water elevations.
+ const double epsilon = 8 * std::numeric_limits<float>::epsilon();
+ const double ceiling = top + epsilon *
+ (std::max)(1.0, (std::max)(std::abs(top), 255 * heightScale));
+ if (!std::isfinite(ceiling))
+ {
+ return false;
+ }
+
+ std::vector<uint16_t> indices;
+ indices.reserve(mesh.indices.size());
+ size_t work = 0;
+
+ for (size_t triangle = 0; triangle < mesh.indices.size(); triangle += 3)
+ {
+ const auto a = mesh.vertices[mesh.indices[triangle]].world;
+ const auto b = mesh.vertices[mesh.indices[triangle + 1]].world;
+ const auto c = mesh.vertices[mesh.indices[triangle + 2]].world;
+ double minX = (std::min)(a.x, (std::min)(b.x, c.x));
+ double maxX = (std::max)(a.x, (std::max)(b.x, c.x));
+ double minY = (std::min)(a.y, (std::min)(b.y, c.y));
+ double maxY = (std::max)(a.y, (std::max)(b.y, c.y));
+ const double magnitude = (std::max)(1.0, (std::max)(
+ (std::max)(std::abs(minX), std::abs(maxX)),
+ (std::max)(std::abs(minY), std::abs(maxY))));
+ const double margin = horizontalBound + epsilon * (magnitude + horizontalBound);
+
+ minX = (minX - margin) / spacing + border;
+ maxX = (maxX + margin) / spacing + border;
+ minY = (minY - margin) / spacing + border;
+ maxY = (maxY + margin) / spacing + border;
+
+ bool dry = false;
+ if (std::isfinite(minX) && std::isfinite(maxX) &&
+ std::isfinite(minY) && std::isfinite(maxY) &&
+ minX >= 0 && minY >= 0 && maxX <= width - 1 && maxY <= height - 1)
+ {
+ const int firstX = int(std::floor(minX));
+ const int lastX = int(std::ceil(maxX));
+ const int firstY = int(std::floor(minY));
+ const int lastY = int(std::ceil(maxY));
+ const size_t samples = size_t(lastX - firstX + 1) * size_t(lastY - firstY + 1);
+
+ if (samples <= MaxTriangleSamples && samples <= MaxMeshSamples - work)
+ {
+ work += samples;
+ dry = true;
+
+ for (int y = firstY; y <= lastY && dry; ++y)
+ {
+ for (int x = firstX; x <= lastX; ++x)
+ {
+ if (heights[size_t(y) * width + x] * heightScale <= ceiling)
+ {
+ dry = false;
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ if (!dry)
+ {
+ indices.insert(
+ indices.end(), mesh.indices.begin() + triangle, mesh.indices.begin() + triangle + 3);
+ }
+ }
+
+ Install(mesh, indices);
+ return true;
+}
+}
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterVesselMotion.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterVesselMotion.h
new file mode 100644
index 000000000..cd91f8e24
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterVesselMotion.h
@@ -0,0 +1,78 @@
+/* Render-only vessel motion. No gameplay position, velocity or water level is modified. */
+#pragma once
+#include <algorithm>
+#include <cmath>
+#include <cstdint>
+
+namespace WaterVesselMotion {
+constexpr float MaxSpeed=250.0f;
+constexpr float SmoothingSeconds=0.15f;
+constexpr float MaxHistorySeconds=0.5f;
+constexpr float MinimumTeleportDistance=32.0f;
+struct Point { float x=0,y=0; };
+struct State {
+ Point position,velocity;
+ float level=0,phase=1;
+ std::uint32_t frame=0;
+ bool initialized=false;
+};
+inline bool Finite(Point p) { return std::isfinite(p.x) && std::isfinite(p.y); }
+inline Point LimitVelocity(Point velocity) {
+ if (!Finite(velocity)) return {};
+ const double speed=std::sqrt(double(velocity.x)*velocity.x+double(velocity.y)*velocity.y);
+ if (speed>MaxSpeed) {
+ const double scale=MaxSpeed/speed;
+ velocity.x=float(velocity.x*scale);velocity.y=float(velocity.y*scale);
+ }
+ return velocity;
+}
+inline void Anchor(State &state,Point position,float level,std::uint32_t frame,Point velocity={},float phase=1) {
+ state.position=position;state.level=level;state.frame=frame;state.phase=phase;
+ state.velocity=LimitVelocity(velocity);state.initialized=true;
+}
+
+// The displayed transform is authoritative after the first observation, including scripted
+// movement and braking. Sample once per simulation frame, so extra renders/reflections and
+// pause do not create artificial acceleration. Callers own one state per stable model/object ID.
+// An interpolated transform represents frame-1+phase; an unblended transform uses phase=1.
+// First-render phase varies with render cadence and must be included in the elapsed sample time.
+inline Point Update(State &state,Point position,float level,std::uint32_t frame,
+ bool frozen,Point initialPhysicsVelocity,float framesPerSecond,float samplePhase=1) {
+ if (!Finite(position) || !std::isfinite(level) || !std::isfinite(framesPerSecond) || framesPerSecond<=0 ||
+ !std::isfinite(samplePhase)) {
+ state=State();return {};
+ }
+ samplePhase=(std::max)(0.0f,(std::min)(1.0f,samplePhase));
+ if (!state.initialized) {
+ Anchor(state,position,level,frame,initialPhysicsVelocity,samplePhase);return state.velocity;
+ }
+ if (level!=state.level || frame<state.frame) {
+ Anchor(state,position,level,frame,{},samplePhase);return state.velocity;
+ }
+ if (frozen || frame==state.frame) return state.velocity;
+ const double seconds=(double(frame-state.frame)+double(samplePhase)-state.phase)/framesPerSecond;
+ const double dx=double(position.x)-state.position.x,dy=double(position.y)-state.position.y;
+ const double distance=std::sqrt(dx*dx+dy*dy);
+ // A fully displayed tick followed by alpha=0 has the same sample time. Preserve its
+ // velocity only if the transform also agrees; a changed transform is a discontinuity.
+ if (seconds<=0) {
+ Anchor(state,position,level,frame,distance==0?state.velocity:Point{},samplePhase);
+ return state.velocity;
+ }
+ const double teleportDistance=(std::max)(double(MinimumTeleportDistance),double(MaxSpeed)*seconds);
+ if (distance>teleportDistance) {
+ Anchor(state,position,level,frame,{},samplePhase);return state.velocity;
+ }
+ if (seconds>MaxHistorySeconds) {
+ // Visibility can leave a cached hull unobserved. Its old displacement is no longer
+ // a useful velocity estimate, but finite current physics still gives a safe seed.
+ Anchor(state,position,level,frame,initialPhysicsVelocity,samplePhase);return state.velocity;
+ }
+ const Point measured=LimitVelocity({float(dx/seconds),float(dy/seconds)});
+ const float blend=float(1.0-std::exp(-seconds/SmoothingSeconds));
+ const Point velocity=LimitVelocity({state.velocity.x+(measured.x-state.velocity.x)*blend,
+ state.velocity.y+(measured.y-state.velocity.y)*blend});
+ Anchor(state,position,level,frame,velocity,samplePhase);
+ return state.velocity;
+}
+}
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterVesselWaves.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterVesselWaves.h
new file mode 100644
index 000000000..55c482dc4
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterVesselWaves.h
@@ -0,0 +1,306 @@
+/* Render-only vessel response. Shares the actual waterline and simulation clock with water. */
+#pragma once
+#include <string>
+#include <algorithm>
+#include <cmath>
+#include <cstdlib>
+#include <cstring>
+#include "Platform/WaterBowShoulder.h"
+
+namespace WaterVesselWaves {
+inline bool Enabled() {
+ const char *value=std::getenv("ZH_WATER_VESSEL_WAVES");
+ return !value || std::strcmp(value,"0")!=0;
+}
+// Render-only pressure response uses measured contact half-beam and velocity. Keeping these
+// constants in one list makes the CPU refinement estimate and both shader stages agree.
+#define WATER_VESSEL_BOW_CONSTANTS(X) \
+ X(BowAlongBase,6.0f) X(BowAlongBeam,1.2f) X(BowAlongMin,9.0f) X(BowAlongMax,32.0f) \
+ X(BowAcrossBase,1.5f) X(BowAcrossBeam,0.95f) X(BowAcrossMin,4.0f) X(BowAcrossMax,60.0f) \
+ X(BowHeadBeam,1.8f) X(BowHeadMin,3.0f) X(BowHeadMax,8.0f) \
+ X(BowRestSpeed,0.3f) X(BowSpeedScale,26.0f) X(BowSpeedMax,250.0f) X(BowCurvature,0.6f)
+#define WATER_VESSEL_BOW_CONSTANT(name,value) constexpr float name=value;
+WATER_VESSEL_BOW_CONSTANTS(WATER_VESSEL_BOW_CONSTANT)
+#undef WATER_VESSEL_BOW_CONSTANT
+struct BowPressureParameters { float along=0,across=0,amplitude=0; };
+struct BowPressureSample { float height=0,dAlong=0,dAcross=0; };
+inline BowPressureParameters BowPressure(float halfBeam,float speed) {
+ if(!std::isfinite(halfBeam)||!std::isfinite(speed)||halfBeam<0||speed<0) return {};
+ const float u=(std::max)(0.0f,(std::min)(speed,BowSpeedMax)-BowRestSpeed);
+ const float response=u*u/(u*u+BowSpeedScale*BowSpeedScale);
+ BowPressureParameters p;
+ p.along=(std::max)(BowAlongMin,(std::min)(BowAlongMax,BowAlongBase+BowAlongBeam*halfBeam));
+ p.across=(std::max)(BowAcrossMin,(std::min)(BowAcrossMax,BowAcrossBase+BowAcrossBeam*halfBeam));
+ p.amplitude=(std::max)(BowHeadMin,(std::min)(BowHeadMax,BowHeadBeam*std::sqrt(halfBeam)))*response;
+ return p;
+}
+inline BowPressureSample EvaluateBowPressure(const BowPressureParameters &p,float along,float across) {
+ if(!std::isfinite(p.along)||!std::isfinite(p.across)||!std::isfinite(p.amplitude)||
+ !std::isfinite(along)||!std::isfinite(across)||p.along<=0||p.across<=0||p.amplitude<=0) return {};
+ const float q=across/p.across,r=std::sqrt(1.0f+q*q);
+ const float shifted=along/p.along+BowCurvature*(r-1.0f);
+ const float h=p.amplitude*std::exp(-shifted*shifted-q*q);
+ if(h==0) return {}; // Avoid an underflowed Gaussian multiplying an extreme coordinate.
+ return {h,-2.0f*h*shifted/p.along,
+ -2.0f*h*(q+shifted*BowCurvature*q/r)/p.across};
+}
+inline std::string BowPressureSource() {
+ std::string source;
+#define WATER_VESSEL_BOW_HLSL(name,value) source+="static const float " #name "=" #value ";\n";
+ WATER_VESSEL_BOW_CONSTANTS(WATER_VESSEL_BOW_HLSL)
+#undef WATER_VESSEL_BOW_HLSL
+ return source+R"HLSL(
+float3 vesselBowPressure(float halfBeam,float speed) {
+ if(!isfinite(halfBeam)||!isfinite(speed)||halfBeam<0.0||speed<0.0) return 0;
+ float u=max(0.0,min(speed,BowSpeedMax)-BowRestSpeed);
+ float response=u*u/(u*u+BowSpeedScale*BowSpeedScale);
+ return float3(clamp(BowAlongBase+BowAlongBeam*halfBeam,BowAlongMin,BowAlongMax),
+ clamp(BowAcrossBase+BowAcrossBeam*halfBeam,BowAcrossMin,BowAcrossMax),
+ clamp(BowHeadBeam*sqrt(halfBeam),BowHeadMin,BowHeadMax)*response);
+}
+)HLSL";
+}
+#undef WATER_VESSEL_BOW_CONSTANTS
+// Reflection reaches at most 90 units from a contour; generated wakes end within 110 units.
+// The collector's existing hull-radius + 122 culling margin therefore still contains the field.
+inline std::string Source(bool contactContours=false,bool bowShoulder=WaterBowShoulder::Enabled()) {
+ // A pitching shallow keel can move a mean-slice endpoint by several world units
+ // in one frame. Generated packets follow the current reachable contact envelope;
+ // exact mean-waterline clearance and reflection below remain independent.
+ std::string source=contactContours?R"HLSL(
+float4 vesselPacketRegister(int index) {
+ int base=(index/10)*10;
+ float count=ContactHullData[base].w;
+ return count>=3.0 && count<=12.0?ContactHullData[index]:HullData[index];
+}
+)HLSL":R"HLSL(
+float4 vesselPacketRegister(int index) { return HullData[index]; }
+)HLSL";
+ return BowPressureSource()+source+R"HLSL(
+// Match WaterHullModel::Damping at the undisplaced surface parameter. The smooth nine-unit
+// clearance envelope is differentiated here, rather than after interpolation across a mesh
+// triangle; stronger reflected waves must not expose that triangle's constant damping slope.
+float3 vesselHullDamping(float2 p,float level) {
+ float3 result=float3(1,0,0);
+ int hullCount=clamp((int)HullParameters.x,0,8);
+ for(int h=0;h<hullCount;++h) {
+ int base=h*10;
+ float4 position=HullData[base],axis=HullData[base+1];
+ int count=(int)position.w;
+ if(count<3 || count>12 || abs(level-position.z)>0.1) continue;
+ float2 delta=p-position.xy;
+ float2 local=float2(dot(delta,axis.xy),dot(delta,float2(-axis.y,axis.x)));
+ if(abs(local.x)>axis.z+9.0 || abs(local.y)>axis.w+9.0) continue;
+ float best=1.0e30;float2 separation=0;
+ bool inside=true;
+ for(int j=0;j<count;++j) {
+ float4 pairA=HullData[base+4+j/2];
+ int next=(j+1)%count;
+ float4 pairB=HullData[base+4+next/2];
+ float2 a=(j&1)!=0?pairA.zw:pairA.xy,b=(next&1)!=0?pairB.zw:pairB.xy;
+ float2 edge=b-a,from=local-a;
+ float t=saturate(dot(from,edge)/max(dot(edge,edge),1.0e-12));
+ float2 q=from-t*edge;float d=dot(q,q);
+ if(d<best) {best=d;separation=q;}
+ inside=inside && edge.x*from.y-edge.y*from.x>=-0.0001;
+ }
+ if(inside) return float3(0,0,0);
+ float distance=sqrt(max(best,0.0));
+ float t=saturate(distance/9.0),value=t*t*(3.0-2.0*t);
+ if(value<result.x) {
+ float2 n=distance>0.0?separation/distance:float2(0,0);
+ float2 gradient=float2(axis.x*n.x-axis.y*n.y,axis.y*n.x+axis.x*n.y)
+ *(6.0*t*(1.0-t)/9.0);
+ result=float3(value,gradient);
+ }
+ }
+ return result;
+}
+float3 vesselHullDamping(float2 p,float level,float offshore) {
+ float3 hull=vesselHullDamping(p,level);
+ return float3(1.0+(hull.x-1.0)*offshore,hull.yz*offshore);
+}
+// Both shader stages consume the same hull-free floor/obstacle envelope and offshore metadata.
+// These are scalar+XY-gradient triples; vertex sampling supplies zero input gradients. Hull
+// clearance is independent of the optional reflected/generated-wave switch.
+float3 vesselApplyHullDamping(float2 p,float level,float3 freeDamping,float3 offshore) {
+ if(offshore.x<=0.0 || freeDamping.x<=0.0) return freeDamping;
+ float3 hull=vesselHullDamping(p,level);
+ hull=float3(1.0+(hull.x-1.0)*offshore.x,hull.yz*offshore.x+(hull.x-1.0)*offshore.yz);
+ return hull.x<freeDamping.x?hull:freeDamping;
+}
+struct VesselReflection {
+ float2 samplePosition;
+ float2 normal;
+ float2 weightGradient;
+ float weight;
+ float distance;
+ float corner;
+};
+VesselReflection vesselReflection(float2 p,float level,int h) {
+ VesselReflection v=(VesselReflection)0;
+ int base=h*10;
+ float4 position=HullData[base],axis=HullData[base+1];
+ int count=(int)position.w;
+ if(count<3 || count>12 || abs(level-position.z)>0.1) return v;
+ float range=clamp(axis.w*2.0,28.0,90.0);
+ float2 delta=p-position.xy;
+ float2 local=float2(dot(delta,axis.xy),dot(delta,float2(-axis.y,axis.x)));
+ if(abs(local.x)>axis.z+range || abs(local.y)>axis.w+range) return v;
+ float best=1.0e30,corner=0;float2 closest=0;
+ bool inside=true;
+ for(int j=0;j<count;++j) {
+ float4 pairA=HullData[base+4+j/2];
+ int next=(j+1)%count;
+ float4 pairB=HullData[base+4+next/2];
+ float2 a=(j&1)!=0?pairA.zw:pairA.xy,b=(next&1)!=0?pairB.zw:pairB.xy;
+ float2 edge=b-a,from=local-a;
+ float t=saturate(dot(from,edge)/max(dot(edge,edge),1.0e-12));
+ float2 q=a+t*edge,separation=local-q;
+ float d=dot(separation,separation);
+ if(d<best) {best=d;closest=q;corner=(t<=0.0 || t>=1.0)?1.0:0.0;}
+ inside=inside && edge.x*from.y-edge.y*from.x>=-0.0001;
+ }
+ float distance=sqrt(max(best,0.0));
+ if(inside || distance<0.0001 || distance>=range) return v;
+ float2 n=(local-closest)/distance;
+ v.normal=float2(axis.x*n.x-axis.y*n.y,axis.y*n.x+axis.x*n.y);
+ v.samplePosition=p-2.0*distance*v.normal;
+ float t=distance/range,fade=1.0-t*t*(3.0-2.0*t);
+ // A modest reflected copy of the actual incident field creates interference and standing
+ // crests beside stationary hulls. No unrelated scrolling phase is introduced.
+ v.weight=0.68*fade*fade;
+ v.weightGradient=(-1.36*fade*6.0*t*(1.0-t)/range)*v.normal;
+ v.distance=distance;v.corner=corner;
+ return v;
+}
+float2 vesselReflectVector(float2 d,float2 normal) {
+ return d-2.0*normal*dot(normal,d);
+}
+float2 vesselMirrorDerivative(float2 direction,VesselReflection v) {
+ // The closest point slides along an edge, but stays fixed in a vertex's Voronoi region.
+ return v.corner>0.5?-direction:vesselReflectVector(direction,v.normal);
+}
+float2 vesselReflectionNormalDerivative(float2 direction,VesselReflection v) {
+ return v.corner>0.5?(direction-v.normal*dot(v.normal,direction))/max(v.distance,0.0001):float2(0,0);
+}
+float3 vesselReflectedValue(float3 d,VesselReflection v) {
+ return float3(vesselReflectVector(d.xy,v.normal),d.z)*v.weight;
+}
+float3 vesselReflectedDerivative(float3 d,float3 dx,float3 dy,float2 direction,VesselReflection v) {
+ float2 mirror=vesselMirrorDerivative(direction,v);
+ float3 sampled=dx*mirror.x+dy*mirror.y;
+ float2 normalDerivative=vesselReflectionNormalDerivative(direction,v);
+ float2 horizontal=vesselReflectVector(sampled.xy,v.normal)
+ -2.0*(normalDerivative*dot(v.normal,d.xy)+v.normal*dot(normalDerivative,d.xy));
+ float3 reflected=float3(vesselReflectVector(d.xy,v.normal),d.z);
+ return float3(horizontal,sampled.z)*v.weight+reflected*dot(v.weightGradient,direction);
+}
+// A scalar and its exact world-space gradient. The packet is shared by vertex displacement
+// and pixel normals; no finite-difference texture fetches or screen-space phases are required.
+float3 vwConstant(float value) {return float3(value,0,0);}
+float3 vwMul(float3 a,float3 b) {return float3(a.x*b.x,a.yz*b.x+b.yz*a.x);}
+float3 vwExp(float3 a) {float e=exp(a.x);return float3(e,a.yz*e);}
+float3 vwSqrt(float3 a) {float root=sqrt(a.x);return float3(root,a.yz/(2.0*root));}
+float3 vwSin(float3 a) {return float3(sin(a.x),cos(a.x)*a.yz);}
+float3 vwCos(float3 a) {return float3(cos(a.x),-sin(a.x)*a.yz);}
+float3 vwSmooth(float low,float high,float3 a) {
+ float t=saturate((a.x-low)/(high-low));
+ return float3(t*t*(3.0-2.0*t),a.yz*(6.0*t*(1.0-t)/(high-low)));
+}
+float3 vwGaussian(float3 distance,float width) {
+ float3 q=distance/max(width,0.001);
+ return vwExp(-vwMul(q,q));
+}
+// A curved pressure shoulder starts on the actual contact bow. Its wings turn aft toward
+// the forebody; there is no detached forward-centred bump. The nine-unit clearance/floor
+// envelope is applied later, exactly as for all other generated surface displacement.
+float3 vesselBowPressureField(float3 along,float3 across,float3 parameters) {
+ if(parameters.x<=0.0 || parameters.y<=0.0 || parameters.z<=0.0) return 0;
+ float3 q=across/parameters.y;
+ float3 shifted=along/parameters.x+
+ (vwSqrt(vwConstant(1.0)+vwMul(q,q))-vwConstant(1.0))*BowCurvature;
+ return vwExp(-vwMul(shifted,shifted)-vwMul(q,q))*parameters.z;
+}
+)HLSL"+(bowShoulder?WaterBowShoulder::Source():std::string())+R"HLSL(// Generated crest coverage follows the physical packet and its usable displacement.
+// Illumination belongs to the diffuse foam material, not to the amount of emitted foam.
+// The caller retains the solid-hull mask and uses the same microcoverage as hull/history foam.
+float vesselGeneratedFoam(float crest,float weight,float damping) {
+ return saturate(crest)*saturate(weight)*0.65*smoothstep(0.15,0.65,saturate(damping));
+}
+float3 vesselGeneratedWave(float2 p,float level,float time,int h,out float3 bowContribution) {
+ bowContribution=0;
+ int base=h*10;
+ float4 position=vesselPacketRegister(base),axis=vesselPacketRegister(base+1),motion=vesselPacketRegister(base+2);
+ float speed=length(motion.xy);
+ if(position.w<3 || abs(level-position.z)>0.1 || speed<=0.3) return 0;
+ float2 delta=p-position.xy;
+ float radius=length(delta),reach=motion.w+110.0;
+ if(radius>=reach) return 0;
+ float moving=smoothstep(0.3,14.0,speed);
+ float2 forward=motion.xy/max(speed,0.001),aft=-forward,side=float2(-forward.y,forward.x);
+ float2 localVelocity=float2(dot(forward,axis.xy),dot(forward,float2(-axis.y,axis.x)));
+ float4 endpoints=vesselPacketRegister(base+3);
+ // Sideways drift during a sharp turn must not swap two distant endpoints in one frame.
+ // Forward/reverse retain the actual stern/bow; the blend is confined to broadside travel.
+ float forwardBlend=smoothstep(-0.25,0.25,localVelocity.x);
+ float2 sternLocal=lerp(endpoints.zw,endpoints.xy,forwardBlend);
+ float2 bowLocal=lerp(endpoints.xy,endpoints.zw,forwardBlend);
+ float2 stern=position.xy+float2(axis.x*sternLocal.x-axis.y*sternLocal.y,axis.y*sternLocal.x+axis.x*sternLocal.y);
+ float2 bow=position.xy+float2(axis.x*bowLocal.x-axis.y*bowLocal.y,axis.y*bowLocal.x+axis.x*bowLocal.y);
+ float3 along=float3(dot(p-stern,aft),aft),across=float3(dot(p-stern,side),side);
+ float lengthWake=clamp(speed*3.2+axis.w*2.0,30.0,110.0);
+ float3 trail=vwMul(vwSmooth(0.0,10.0,along),vwConstant(1.0)-vwSmooth(lengthWake*0.5,lengthWake,along));
+ float3 width=vwConstant(max(axis.w*0.35,1.0))+along*0.353553;
+ float3 ridgeA=across-width,ridgeB=across+width;
+ float ribbonWidth=clamp(axis.w*0.18+2.0,2.5,7.0);
+ // Paired divergent crests create a V behind the real stern. The transverse packet remains
+ // centred on the measured travel direction, including reverse movement.
+ float3 arms=vwMul(vwGaussian(ridgeA,ribbonWidth),vwCos(ridgeA*0.40))
+ +vwMul(vwGaussian(ridgeB,ribbonWidth),vwCos(ridgeB*0.40));
+ float3 churn=vwMul(vwGaussian(across,max(axis.w*0.55,2.0)),
+ vwSin(along*0.30+vwConstant(-time*1.15+motion.z*6.2831853)))*0.24;
+ float3 wake=vwMul(trail,arms*1.35+churn);
+ float3 bowForward=float3(dot(p-bow,forward),forward),bowAcross=float3(dot(p-bow,side),side);
+ float3 bowCrest=vesselBowPressureField(bowForward,bowAcross,vesselBowPressure(axis.w,speed));
+ float3 radial=float3(radius,delta/max(radius,0.001));
+ float3 support=vwConstant(1.0)-vwSmooth(motion.w+80.0,reach,radial);
+ bowContribution=vwMul(bowCrest,support);
+ return vwMul(wake*moving+bowCrest,support);
+}
+float3 vesselGeneratedWave(float2 p,float level,float time,int h) {
+ float3 bowContribution;
+ return vesselGeneratedWave(p,level,time,h,bowContribution);
+}
+// Bow-only world field. Keep the stern packet and its parameterization above unchanged.
+// The caller supplies the final horizontal position after every reflected XY contribution.
+float3 vesselGeneratedBow(float2 p,float level,int h) {
+)HLSL"+(bowShoulder?R"HLSL( return vesselContourBow(p,level,h);
+)HLSL":std::string())+R"HLSL( int base=h*10;
+ float4 position=vesselPacketRegister(base),axis=vesselPacketRegister(base+1),motion=vesselPacketRegister(base+2);
+ float speed=length(motion.xy);
+ if(position.w<3 || abs(level-position.z)>0.1 || speed<=0.3) return 0;
+ float2 delta=p-position.xy;
+ float radius=length(delta),reach=motion.w+110.0;
+ if(radius>=reach) return 0;
+ float2 forward=motion.xy/max(speed,0.001),side=float2(-forward.y,forward.x);
+ float2 localVelocity=float2(dot(forward,axis.xy),dot(forward,float2(-axis.y,axis.x)));
+ float4 endpoints=vesselPacketRegister(base+3);
+ float forwardBlend=smoothstep(-0.25,0.25,localVelocity.x);
+ float2 bowLocal=lerp(endpoints.xy,endpoints.zw,forwardBlend);
+ float2 bow=position.xy+float2(axis.x*bowLocal.x-axis.y*bowLocal.y,axis.y*bowLocal.x+axis.x*bowLocal.y);
+ float3 bowForward=float3(dot(p-bow,forward),forward),bowAcross=float3(dot(p-bow,side),side);
+ float3 bowCrest=vesselBowPressureField(bowForward,bowAcross,vesselBowPressure(axis.w,speed));
+ float3 radial=float3(radius,delta/max(radius,0.001));
+ float3 support=vwConstant(1.0)-vwSmooth(motion.w+80.0,reach,radial);
+ return vwMul(bowCrest,support);
+}
+float3 vesselRegisteredBowDifference(float2 position,float2 derivativeX,float2 derivativeY,
+ float level,int h,float3 oldBow) {
+ float3 bow=vesselGeneratedBow(position,level,h);
+ bow.yz=float2(dot(bow.yz,derivativeX),dot(bow.yz,derivativeY));
+ return bow-oldBow;
+}
+)HLSL";
+}
+}
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterWaveCage.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterWaveCage.h
new file mode 100644
index 000000000..45f6ae41b
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterWaveCage.h
@@ -0,0 +1,227 @@
+/* Copyright 2026. SPDX-License-Identifier: GPL-3.0-or-later */
+#pragma once
+
+#include "Platform/WaterFftGeometry.h"
+#include "Platform/WaterOpticalContext.h"
+#include <array>
+#include <algorithm>
+#include <cmath>
+#include <cstdint>
+#include <vector>
+
+// Jeschke et al., Making Procedural Water Waves Boundary-Aware (2020),
+// https://pub.ist.ac.at/~chafner/JeschkeWaveCages.pdf, Eqs. (2)-(4), Appendix B.
+// This bounded CPU adaptation uses equal tangential radii: M=rt I+(rn-rt)nn^T.
+// Thus terrain normals alone define the frame; no interpolated tangent frame is
+// needed. Cage fitting uses finitely sampled directions, not an exact collision
+// solver. The paper's final terrain projection remains necessary on curved
+// terrain, and vertex safety alone does not guarantee triangle-interior safety.
+namespace WaterWaveCage {
+constexpr float MaxRadius=WaterFftGeometry::MaxVerticalDisplacement<WaterFftGeometry::MaxHorizontalDisplacement?
+ WaterFftGeometry::MaxVerticalDisplacement:WaterFftGeometry::MaxHorizontalDisplacement;
+constexpr float TangentTolerance=.15f;
+constexpr float CoastFullRange=16.0f;
+constexpr float CoastRange=32.0f;
+constexpr unsigned FitIterations=8;
+constexpr unsigned SmoothingIterations=24;
+constexpr float SmoothingStrength=16.0f;
+
+struct Vec3 { float x=0,y=0,z=0; };
+struct TerrainSample { float height=0;Vec3 normal{0,0,1}; };
+struct Radii { float tangent=MaxRadius,normal=MaxRadius; };
+struct Field {
+ std::vector<float> tangent,normal,support;
+ std::vector<uint32_t> texels;
+};
+inline uint32_t Texel(const Field&field,size_t n){return field.texels[n];}
+inline float Dot(Vec3 a,Vec3 b){return a.x*b.x+a.y*b.y+a.z*b.z;}
+inline Vec3 Unit(Vec3 n){
+ const double length=std::sqrt(double(n.x)*n.x+double(n.y)*n.y+double(n.z)*n.z);
+ if(!std::isfinite(length)||length<=0)return {0,0,1};
+ return {float(n.x/length),float(n.y/length),float(n.z/length)};
+}
+inline float ClampRadius(float r){return (std::max)(0.0f,(std::min)(MaxRadius,r));}
+inline float SmoothRange(float a,float b,float value){
+ const float t=(std::max)(0.0f,(std::min)(1.0f,(value-a)/(b-a)));
+ return t*t*(3-2*t);
+}
+
+// The grid coordinates and clamped edge samples match the terrain texture. The
+// normal uses world offsets +/- spacing, deliberately not a cell-local bilinear
+// derivative; the renderer must use the same stencil when constructing M.
+inline float Height(const uint8_t*heights,int width,int height,int border,
+ float spacing,float heightScale,float worldX,float worldY){
+ const float gx=(std::max)(0.0f,(std::min)(float(width-1),worldX/spacing+border));
+ const float gy=(std::max)(0.0f,(std::min)(float(height-1),worldY/spacing+border));
+ const int x=int(gx),y=int(gy),x1=(std::min)(x+1,width-1),y1=(std::min)(y+1,height-1);
+ const float tx=gx-x,ty=gy-y;
+ const float a=heights[size_t(y)*width+x]*(1-tx)+heights[size_t(y)*width+x1]*tx;
+ const float b=heights[size_t(y1)*width+x]*(1-tx)+heights[size_t(y1)*width+x1]*tx;
+ return (a*(1-ty)+b*ty)*heightScale;
+}
+inline TerrainSample SampleTerrain(const uint8_t*heights,int width,int height,int border,
+ float spacing,float heightScale,float worldX,float worldY){
+ TerrainSample sample;
+ if(!heights||width<2||height<2||!std::isfinite(spacing)||spacing<=0||
+ !std::isfinite(heightScale)||heightScale<=0||!std::isfinite(worldX)||!std::isfinite(worldY))return sample;
+ sample.height=Height(heights,width,height,border,spacing,heightScale,worldX,worldY);
+ const float dx=(Height(heights,width,height,border,spacing,heightScale,worldX+spacing,worldY)-
+ Height(heights,width,height,border,spacing,heightScale,worldX-spacing,worldY))/(2*spacing);
+ const float dy=(Height(heights,width,height,border,spacing,heightScale,worldX,worldY+spacing)-
+ Height(heights,width,height,border,spacing,heightScale,worldX,worldY-spacing))/(2*spacing);
+ sample.normal=Unit({-dx,-dy,1});return sample;
+}
+
+// Eq. (2) with s=1/MaxRadius, followed by Eq. (3). This scale gives the
+// unrestricted cage unit small-signal gain. Open water bypasses Map entirely,
+// because tanh is not the identity for finite inputs. No wave phase is changed.
+inline Vec3 Map(Vec3 eta,Vec3 normal,float tangentRadius,float normalRadius){
+ const double length=std::sqrt(double(eta.x)*eta.x+double(eta.y)*eta.y+double(eta.z)*eta.z);
+ if(!std::isfinite(length)||length==0||!std::isfinite(tangentRadius)||!std::isfinite(normalRadius))return {};
+ normal=Unit(normal);const float rt=ClampRadius(tangentRadius),rn=ClampRadius(normalRadius);
+ const double scale=std::tanh(length/MaxRadius)/length;
+ const Vec3 bounded{float(eta.x*scale),float(eta.y*scale),float(eta.z*scale)};
+ const float along=Dot(normal,bounded)*(rn-rt);
+ return {rt*bounded.x+along*normal.x,rt*bounded.y+along*normal.y,rt*bounded.z+along*normal.z};
+}
+
+namespace Detail {
+inline Vec3 Cross(Vec3 a,Vec3 b){return {a.y*b.z-a.z*b.y,a.z*b.x-a.x*b.z,a.x*b.y-a.y*b.x};}
+// Four radial shells include the disk interior. The 16-point tangent rim and
+// 18 sphere directions are a bounded fitting approximation, not paper constants.
+struct Directions {
+ std::array<Vec3,16> rim;
+ std::array<Vec3,18> sphere;
+ Directions(){
+ constexpr float pi=3.14159265358979323846f;
+ for(size_t i=0;i<rim.size();++i){const float a=2*pi*float(i)/rim.size();rim[i]={std::cos(a),std::sin(a),0};}
+ sphere[0]={0,0,1};sphere[1]={0,0,-1};
+ const float z=1/std::sqrt(3.0f),r=std::sqrt(1-z*z);
+ for(int side=0;side<2;++side)for(int i=0;i<8;++i){
+ const float a=2*pi*(i+.5f*side)/8;
+ sphere[2+side*8+i]={r*std::cos(a),r*std::sin(a),side?z:-z};
+ }
+ }
+};
+inline const Directions& Samples(){static const Directions samples;return samples;}
+struct Matrix {float xx=0,yy=0,zz=0,xy=0,xz=0,yz=0;};
+inline Matrix Tensor(Vec3 n,float rt,float rn){
+ const float d=rn-rt;return {rt+d*n.x*n.x,rt+d*n.y*n.y,rt+d*n.z*n.z,d*n.x*n.y,d*n.x*n.z,d*n.y*n.z};
+}
+inline float Difference(Matrix a,Matrix b){
+ return (a.xx-b.xx)*(a.xx-b.xx)+(a.yy-b.yy)*(a.yy-b.yy)+(a.zz-b.zz)*(a.zz-b.zz)+
+ 2*((a.xy-b.xy)*(a.xy-b.xy)+(a.xz-b.xz)*(a.xz-b.xz)+(a.yz-b.yz)*(a.yz-b.yz));
+}
+inline void Add(Matrix&a,Matrix b){a.xx+=b.xx;a.yy+=b.yy;a.zz+=b.zz;a.xy+=b.xy;a.xz+=b.xz;a.yz+=b.yz;}
+inline float NormalComponent(Matrix a,Vec3 n){
+ return a.xx*n.x*n.x+a.yy*n.y*n.y+a.zz*n.z*n.z+2*(a.xy*n.x*n.y+a.xz*n.x*n.z+a.yz*n.y*n.z);
+}
+template<class Function>inline void Neighbours(size_t i,int width,int height,Function visit){
+ const int x=int(i%width),y=int(i/width);
+ if(x>0)visit(i-1);if(x+1<width)visit(i+1);if(y>0)visit(i-width);if(y+1<height)visit(i+width);
+}
+}
+
+// Tangential radii grow first with the paper's small allowed penetration. The
+// normal radius receives no additional allowance; if the tangent disk already
+// intersects curved terrain its normal radius conservatively remains zero.
+// Dry cages use the same tests with the terrain/air side reversed.
+inline Radii Fit(const uint8_t*heights,int width,int height,int border,float spacing,
+ float heightScale,float level,float worldX,float worldY,TerrainSample terrain){
+ const Vec3 n=terrain.normal;
+ const Vec3 a=Unit(Detail::Cross(std::abs(n.z)<.9f?Vec3{0,0,1}:Vec3{0,1,0},n));
+ const Vec3 b=Detail::Cross(n,a);
+ const float depth=level-terrain.height,side=depth>=0?1.0f:-1.0f;
+ const auto allowed=[&](Vec3 u,float rt,float rn,float tolerance){
+ const Vec3 p{rt*(a.x*u.x+b.x*u.y)+rn*n.x*u.z,
+ rt*(a.y*u.x+b.y*u.y)+rn*n.y*u.z,
+ rt*(a.z*u.x+b.z*u.y)+rn*n.z*u.z};
+ for(int shell=1;shell<=4;++shell){
+ const float f=shell*.25f;
+ const float floor=Height(heights,width,height,border,spacing,heightScale,worldX+p.x*f,worldY+p.y*f);
+ if(side*(level+p.z*f-floor)<-tolerance-1e-5f)return false;
+ }
+ return true;
+ };
+ const auto tangentFits=[&](float rt){
+ for(Vec3 u:Detail::Samples().rim)if(!allowed(u,rt,0,TangentTolerance))return false;
+ return true;
+ };
+ float rt=MaxRadius;
+ if(!tangentFits(rt)){
+ float low=0,high=rt;for(unsigned i=0;i<FitIterations;++i){const float mid=(low+high)*.5f;if(tangentFits(mid))low=mid;else high=mid;}rt=low;
+ }
+ // Plane clearance is an additional conservative bound, also applied after
+ // texture interpolation by the shader so rn is exactly zero at the waterline.
+ float rn=(std::min)(MaxRadius,std::abs(depth)*n.z);
+ const auto normalFits=[&](float radius){
+ for(Vec3 u:Detail::Samples().rim)if(!allowed(u,rt,0,0))return false;
+ for(Vec3 u:Detail::Samples().sphere)if(!allowed(u,rt,radius,0))return false;
+ return true;
+ };
+ if(rn>0&&!normalFits(rn)){
+ float low=0,high=rn;for(unsigned i=0;i<FitIterations;++i){const float mid=(low+high)*.5f;if(normalFits(mid))low=mid;else high=mid;}rn=low;
+ }
+ return {rt,rn};
+}
+
+inline bool Build(const uint8_t*heights,int width,int height,int border,float spacing,
+ float heightScale,float level,const WaterOpticalContext::Field&shore,Field&result){
+ result=Field{};
+ if(!heights||width<2||height<2||width>WaterOpticalContext::MaxDimension||height>WaterOpticalContext::MaxDimension||
+ size_t(width)*height>WaterOpticalContext::MaxCells||border<0||border>(width-2)/2||border>(height-2)/2||
+ !std::isfinite(spacing)||spacing<=0||!std::isfinite(heightScale)||heightScale<=0||
+ !std::isfinite(level)||!std::isfinite(255*heightScale))return false;
+ const size_t count=size_t(width)*height;
+ if(shore.physicalShore.size()!=count||shore.exposure.size()!=count)return false;
+ result.tangent.assign(count,MaxRadius);result.normal.assign(count,MaxRadius);result.support.assign(count,0);
+ result.texels.resize(count);std::vector<Vec3> normals(count,Vec3{0,0,1});std::vector<size_t> active;
+ for(int y=0;y<height;++y)for(int x=0;x<width;++x){
+ const size_t i=size_t(y)*width+x;
+ const float distance=shore.physicalShore[i]*(WaterOpticalContext::PhysicalShoreRange/255);
+ const float depth=level-heights[i]*heightScale;
+ // These support thresholds are renderer choices, not paper parameters.
+ // The exact exposed-water classification excludes pools and polygon-only
+ // boundaries; its guarded dry extension supports shoreline interpolation.
+ const float support=(shore.exposure[i]/255.0f)*(1-SmoothRange(CoastFullRange,CoastRange,distance))*
+ (1-SmoothRange(MaxRadius,2*MaxRadius,std::abs(depth)));
+ if(support<=0)continue;
+ const float worldX=(x-border)*spacing,worldY=(y-border)*spacing;
+ const auto terrain=SampleTerrain(heights,width,height,border,spacing,heightScale,worldX,worldY);
+ const auto radii=Fit(heights,width,height,border,spacing,heightScale,level,worldX,worldY,terrain);
+ normals[i]=terrain.normal;result.tangent[i]=radii.tangent;result.normal[i]=radii.normal;
+ result.support[i]=support;active.push_back(i);
+ }
+ const auto rawTangent=result.tangent,rawNormal=result.normal;
+ std::vector<float> alpha(count,1),nextTangent=result.tangent,nextNormal=result.normal;
+ for(size_t i:active){
+ const auto a=Detail::Tensor(normals[i],rawTangent[i],rawNormal[i]);float variation=0;unsigned neighbours=0;
+ Detail::Neighbours(i,width,height,[&](size_t j){variation+=Detail::Difference(a,Detail::Tensor(normals[j],rawTangent[j],rawNormal[j]));++neighbours;});
+ // Appendix B leaves alpha unspecified. This scale-invariant choice keeps
+ // already smooth cages close to their fit and smooths abrupt cage changes.
+ alpha[i]=1/(1+SmoothingStrength*variation/(neighbours*MaxRadius*MaxRadius));
+ }
+ for(unsigned iteration=0;iteration<SmoothingIterations;++iteration){
+ for(size_t i:active){
+ Detail::Matrix average;unsigned neighbours=0;
+ Detail::Neighbours(i,width,height,[&](size_t j){Detail::Add(average,Detail::Tensor(normals[j],result.tangent[j],result.normal[j]));++neighbours;});
+ // Exact isotropic-direction least squares restricted to r1=r2:
+ // rn=n^T avg(M) n; rt=(trace(avg(M))-rn)/2. Component constraints
+ // prevent smoothing from enlarging the original fitted ellipsoid.
+ const float rn=Detail::NormalComponent(average,normals[i])/neighbours;
+ const float rt=((average.xx+average.yy+average.zz)/neighbours-rn)*.5f;
+ nextTangent[i]=(std::min)(rawTangent[i],(std::max)(0.0f,(1-alpha[i])*rt+alpha[i]*rawTangent[i]));
+ nextNormal[i]=(std::min)(rawNormal[i],(std::max)(0.0f,(1-alpha[i])*rn+alpha[i]*rawNormal[i]));
+ }
+ result.tangent.swap(nextTangent);result.normal.swap(nextNormal);
+ }
+ const auto radiusByte=[](float value){return uint8_t((std::max)(0.0f,(std::min)(255.0f,std::floor(value/MaxRadius*255))));};
+ for(size_t i=0;i<count;++i){
+ // Radii round down: quantization cannot enlarge a fitted cage. In the
+ // engine's A8R8G8B8 upload, shader RGBA = terrain, rt, rn, support.
+ const uint32_t a=uint8_t(result.support[i]*255+.5f);
+ result.texels[i]=(a<<24)|(uint32_t(heights[i])<<16)|(uint32_t(radiusByte(result.tangent[i]))<<8)|radiusByte(result.normal[i]);
+ }
+ return true;
+}
+}
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterWaveCageMesh.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterWaveCageMesh.h
new file mode 100644
index 000000000..21128ea85
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterWaveCageMesh.h
@@ -0,0 +1,100 @@
+/* Copyright 2026. SPDX-License-Identifier: GPL-3.0-or-later */
+#pragma once
+#include "Platform/WaterProjectedMesh.h"
+#include <array>
+#include <unordered_map>
+
+namespace WaterWaveCageMesh {
+constexpr unsigned WaterlineIterations=16;
+// Section 8 of Jeschke et al. (2020): insert rest-waterline vertices before
+// evaluating the cage map. Samplers take a WaterProjectedMesh::Point; depth is
+// water level minus bilinear terrain height, and eligible selects cage support.
+// Authored edges, collars and transition fans are deliberately preserved. If a
+// crossed edge touches an ineligible triangle, preserve its whole connected
+// crossing chain: partially clipping that chain would introduce a T junction.
+// A chain that reaches an authored seam can therefore remain untessellated.
+// Failure is atomic. This clips sign-changing triangle edges, not sub-triangle
+// islands or multiple terrain crossings with equal-sign edge endpoints.
+template<class DepthSampler,class EligibleSampler>
+inline bool ClipRestWaterline(WaterProjectedMesh::Mesh&mesh,DepthSampler depthSampler,
+ EligibleSampler eligibleSampler,size_t maxVertices=65535){
+ using namespace WaterProjectedMesh;
+ if(maxVertices>65535||mesh.vertices.size()>maxVertices||mesh.indices.size()%3)return false;
+ const size_t triangleCount=mesh.indices.size()/3;
+ std::vector<double> depths(mesh.vertices.size());std::vector<uint8_t> eligibleVertex(mesh.vertices.size());
+ for(size_t i=0;i<mesh.vertices.size();++i){
+ const auto&v=mesh.vertices[i];
+ if(!std::isfinite(v.world.x)||!std::isfinite(v.world.y))return false;
+ depths[i]=depthSampler(v.world);if(!std::isfinite(depths[i]))return false;
+ eligibleVertex[i]=v.boundary<0&&v.collar<0&&v.transition<0&&eligibleSampler(v.world);
+ }
+ struct Edge {size_t owner[2]={0,0};unsigned count=0;int vertex=-1;};
+ std::unordered_map<uint32_t,Edge> edges;
+ constexpr uint32_t None=0xffffffffu;
+ std::vector<std::array<uint32_t,3>> crossings(triangleCount,std::array<uint32_t,3>{{None,None,None}});
+ std::vector<uint8_t> eligible(triangleCount,1);std::vector<size_t> queue;
+ const auto key=[](uint16_t a,uint16_t b){return (uint32_t((std::min)(a,b))<<16)|uint32_t((std::max)(a,b));};
+ for(size_t t=0;t<triangleCount;++t){
+ for(int corner=0;corner<3;++corner){
+ const uint16_t a=mesh.indices[t*3+corner],b=mesh.indices[t*3+(corner+1)%3];
+ if(a>=mesh.vertices.size()||b>=mesh.vertices.size()||a==b)return false;
+ eligible[t]=eligible[t]&&eligibleVertex[a];
+ if((depths[a]<0&&depths[b]>0)||(depths[b]<0&&depths[a]>0)){
+ const auto k=key(a,b);crossings[t][corner]=k;auto&e=edges[k];
+ if(e.count>=2)return false;e.owner[e.count++]=t;
+ }
+ }
+ if(!eligible[t])queue.push_back(t);
+ }
+ for(size_t head=0;head<queue.size();++head){
+ for(auto k:crossings[queue[head]])if(k!=None){
+ const auto&e=edges.find(k)->second;
+ for(unsigned owner=0;owner<e.count;++owner)if(eligible[e.owner[owner]]){
+ eligible[e.owner[owner]]=0;queue.push_back(e.owner[owner]);
+ }
+ }
+ }
+ auto vertices=mesh.vertices;std::vector<uint16_t> indices;indices.reserve(mesh.indices.size());bool valid=true;
+ const auto intersection=[&](uint16_t a,uint16_t b)->uint16_t{
+ if(depths[a]==0)return a;if(depths[b]==0)return b;
+ auto found=edges.find(key(a,b));if(found==edges.end()){valid=false;return 0;}
+ auto&e=found->second;if(e.vertex>=0)return uint16_t(e.vertex);
+ // Always evaluate in canonical endpoint order, independently of winding.
+ const uint16_t first=(std::min)(a,b),second=(std::max)(a,b);
+ const Point p=mesh.vertices[first].world,q=mesh.vertices[second].world;
+ double low=0,high=1,lowDepth=depths[first];
+ for(unsigned step=0;step<WaterlineIterations;++step){
+ const double mid=(low+high)*.5;const Point point{p.x+(q.x-p.x)*mid,p.y+(q.y-p.y)*mid};
+ const double depth=depthSampler(point);if(!std::isfinite(depth)){valid=false;return 0;}
+ if(depth==0){low=high=mid;lowDepth=0;break;}
+ if((depth>=0)==(lowDepth>=0)){low=mid;lowDepth=depth;}else high=mid;
+ }
+ const double parameter=lowDepth>=0?low:high; // round toward the wet side
+ if(vertices.size()>=maxVertices){valid=false;return 0;}
+ Vertex v;v.world={p.x+(q.x-p.x)*parameter,p.y+(q.y-p.y)*parameter};
+ e.vertex=int(vertices.size());vertices.push_back(v);return uint16_t(e.vertex);
+ };
+ const auto triangle=[&](uint16_t a,uint16_t b,uint16_t c){
+ if(a==b||b==c||c==a)return;
+ const Point pa=vertices[a].world,pb=vertices[b].world,pc=vertices[c].world;
+ if(std::abs((pb.x-pa.x)*(pc.y-pa.y)-(pb.y-pa.y)*(pc.x-pa.x))<1e-16)return;
+ indices.insert(indices.end(),{a,b,c});
+ };
+ for(size_t t=0;t<triangleCount;++t){
+ const uint16_t a=mesh.indices[t*3],b=mesh.indices[t*3+1],c=mesh.indices[t*3+2];
+ if(!eligible[t]||(depths[a]>=0&&depths[b]>=0&&depths[c]>=0)){
+ indices.insert(indices.end(),{a,b,c});continue;
+ }
+ if(depths[a]<0&&depths[b]<0&&depths[c]<0)continue;
+ uint16_t polygon[6];unsigned count=0;uint16_t previous=c;
+ for(uint16_t current:{a,b,c}){
+ const bool before=depths[previous]>=0,after=depths[current]>=0;
+ if(before!=after){polygon[count++]=intersection(previous,current);if(!valid)return false;}
+ if(after)polygon[count++]=current;
+ previous=current;
+ }
+ for(unsigned i=1;i+1<count;++i)triangle(polygon[0],polygon[i],polygon[i+1]);
+ }
+ mesh.vertices.swap(vertices);mesh.indices.swap(indices);return true;
+}
+}
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterWaveCageShader.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterWaveCageShader.h
new file mode 100644
index 000000000..e5525a074
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterWaveCageShader.h
@@ -0,0 +1,89 @@
+// Axisymmetric wave cages, adapted from Jeschke et al., CGF 2020, equations 2–3.
+// The fitted radii live beside terrain height in a per-water-level texture.
+#pragma once
+#include <string>
+namespace WaterWaveCageShader {
+inline std::string Source(bool vertex) {
+ return std::string(vertex ? R"HLSL(
+Texture2D WaveCageTerrain : register(t3);
+SamplerState WaveCageSampler : register(s3);
+float4 waveCageTexel(float2 uv) {return WaveCageTerrain.SampleLevel(WaveCageSampler,uv,0);}
+)HLSL" : R"HLSL(
+float4 waveCageTexel(float2 uv) {return Texture2.SampleLevel(Sampler2,uv,0);}
+)HLSL")+R"HLSL(
+struct WaveCage {float3 normal;float2 radii;float support;};
+float waveCageHeight(float2 p) {
+ return waveCageTexel((p+TerrainParameters.xx+5.0)/max(TerrainParameters.y,1.0)).r*TerrainParameters.z;
+}
+WaveCage waveCage(float2 p,float level) {
+ WaveCage c=(WaveCage)0;c.normal=float3(0,0,1);
+ if(TerrainParameters.w<0.5 || OpticalParameters.w<0.5 || WaterParameters.y>0.5) return c;
+ float4 packed=waveCageTexel((p+TerrainParameters.xx+5.0)/max(TerrainParameters.y,1.0));
+ c.support=packed.a;
+ if(c.support<=0.0) return c;
+ float2 gradient=float2(waveCageHeight(p+float2(10,0))-waveCageHeight(p-float2(10,0)),
+ waveCageHeight(p+float2(0,10))-waveCageHeight(p-float2(0,10)))/20.0;
+ c.normal=normalize(float3(-gradient,1));
+ float depth=level-packed.r*TerrainParameters.z;
+ c.radii=packed.gb*fftVerticalBound;
+ // Interpolation must not restore a normal radius on the actual waterline.
+ c.radii.y=min(c.radii.y,abs(depth)*c.normal.z);
+ return c;
+}
+float3 waveCageUnit(float3 eta) {
+ float lengthEta=length(eta);
+ return eta*(lengthEta>0.00001?tanh(lengthEta/fftVerticalBound)/lengthEta:1.0/fftVerticalBound);
+}
+float3 waveCageMap(WaveCage c,float3 eta) {
+ float3 u=waveCageUnit(eta);
+ return c.radii.x*u+(c.radii.y-c.radii.x)*c.normal*dot(c.normal,u);
+}
+// Complete chain rule, including spatially changing terrain axes and fitted radii.
+float3 waveCageDerivative(WaveCage c,float3 eta,float3 etaQ,float3 normalQ,float2 radiiQ) {
+ float L=length(eta),t=tanh(L/fftVerticalBound);
+ float f=L>0.00001?t/L:1.0/fftVerticalBound;
+ float3 u=eta*f;
+ float coefficient=L>0.00001?((1.0-t*t)/fftVerticalBound-f)/(L*L):0.0;
+ float3 uQ=f*etaQ+coefficient*eta*dot(eta,etaQ);
+ return radiiQ.x*u+c.radii.x*uQ+(radiiQ.y-radiiQ.x)*c.normal*dot(c.normal,u)
+ +(c.radii.y-c.radii.x)*(normalQ*dot(c.normal,u)+c.normal*(dot(normalQ,u)+dot(c.normal,uQ)));
+}
+// Finite directional fitting bounds the cage; this final local correction handles
+// bilinear terrain curvature between fitted nodes. Restrict it to the shore mapping.
+float3 waveCageFloor(float2 p,float level,float3 delta) {
+ float floorHeight=waveCageHeight(p+delta.xy)-level+0.035;
+ delta.z=min(fftVerticalBound,max(delta.z,floorHeight));
+ return delta;
+}
+)HLSL"+(vertex?std::string():std::string(R"HLSL(
+struct WaveCageSurface {float3 displacement,derivativeX,derivativeY;};
+float2 waveCageGradient(float value,float2 dx,float2 dy) {
+ float determinant=dx.x*dy.y-dx.y*dy.x;
+ return abs(determinant)>0.000001?float2(ddx(value)*dy.y-ddy(value)*dx.y,
+ ddy(value)*dx.x-ddx(value)*dy.x)/determinant:float2(0,0);
+}
+WaveCageSurface waveCageSurface(WaveCage c,float2 p,float level,float3 eta,float3 etaX,float3 etaY,
+ float3 obstacle,float2 parameterDx,float2 parameterDy) {
+ float2 nx=waveCageGradient(c.normal.x,parameterDx,parameterDy);
+ float2 ny=waveCageGradient(c.normal.y,parameterDx,parameterDy);
+ float2 nz=waveCageGradient(c.normal.z,parameterDx,parameterDy);
+ float2 rt=waveCageGradient(c.radii.x,parameterDx,parameterDy);
+ float2 rn=waveCageGradient(c.radii.y,parameterDx,parameterDy);
+ WaveCageSurface result;
+ float3 mapped=waveCageMap(c,eta);
+ result.displacement=mapped*obstacle.x;
+ result.derivativeX=waveCageDerivative(c,eta,etaX,float3(nx.x,ny.x,nz.x),float2(rt.x,rn.x))*obstacle.x+mapped*obstacle.y;
+ result.derivativeY=waveCageDerivative(c,eta,etaY,float3(nx.y,ny.y,nz.y),float2(rt.y,rn.y))*obstacle.x+mapped*obstacle.z;
+ float floorHeight=c.support>0.0 && obstacle.x>0.0?
+ waveCageHeight(p+result.displacement.xy)-level+0.035:-fftVerticalBound;
+ float2 floorSlope=waveCageGradient(floorHeight,parameterDx,parameterDy);
+ if(floorHeight>result.displacement.z) {
+ result.displacement.z=min(fftVerticalBound,floorHeight);
+ result.derivativeX.z=floorHeight<fftVerticalBound?floorSlope.x:0;
+ result.derivativeY.z=floorHeight<fftVerticalBound?floorSlope.y:0;
+ }
+ return result;
+}
+)HLSL"));
+}
+}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.cpp
index 9de0478f1..2d689aea3 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.cpp
@@ -20,8 +20,20 @@
#include "engineshader.h"
#include "ffvertex.h"
#include "sdl3target.h"
+#include "Platform/WaterSurfaceModel.h"
+#include "Platform/WaterCoastalPresentation.h"
+#include "Platform/WaterOpticalModel.h"
+#include "Platform/ModernWaterMaterial.h"
+#include "Platform/WaterHullModel.h"
+#include "Platform/WaterHullVisual.h"
+#include "Platform/WaterFftSampling.h"
+#include "Platform/WaterFoamShading.h"
+#include "Platform/WaterFoamEnvironment.h"
+#include "Platform/WaterShoreFoam.h"
+#include "Platform/WaterCoastalCrest.h"
#include <stdio.h>
+#include <stdlib.h>
#include <string.h>
/*
@@ -69,6 +81,8 @@ static const EngineShaderEntry ENGINE_SHADERS[] = {
{ ENGINE_SHADER_WATER_TRAPEZOID, "trapezoid water ps.1.1", "engine:trapezoidwater",
NULL, NULL },
{ ENGINE_SHADER_WATER_RIVER, "river water ps.1.1", "engine:riverwater", NULL, NULL },
+ { ENGINE_SHADER_WATER_CLASSIC_TRAPEZOID, "classic trapezoid water ps.1.1", "engine:classictrapezoidwater", NULL, NULL },
+ { ENGINE_SHADER_WATER_CLASSIC_RIVER, "classic river water ps.1.1", "engine:classicriverwater", NULL, NULL },
{ ENGINE_SHADER_WATER_REFLECTION, "water reflection ps.1.1", "engine:waterreflection",
NULL, NULL },
{ ENGINE_SHADER_TERRAIN, "terrain.pso", "engine:terrain",
@@ -478,6 +492,1172 @@ bool EngineShader_Vertex_Program(EngineShaderProgram program, std::string & hlsl
static bool write_engine_pixel_program(EngineShaderProgram program,
const PixelPipelineDescription & pipeline, std::string & hlsl, bool volumetric);
+// SDL map water has a dedicated, explicitly packed uniform block (SdlWaterPixelConstants).
+// Runtime-generated normal detail, terrain depth, refraction and the coloured planar reflection
+// are composed before the existing shore/shroud alpha blend. No additional assets are required.
+static void write_modern_water(std::string &hlsl, bool river)
+{
+ const char *coastalSurfOption=getenv("ZH_WATER_SURF_GPU");
+ const bool coastalSurf=!river && coastalSurfOption && strcmp(coastalSurfOption,"1")==0;
+ const bool bowLift=WaterBowLift::Enabled();
+ const bool visualContact=WaterHullVisual::Enabled();
+ const char *visualDebugOption=getenv("ZH_WATER_DEBUG");
+ const bool visualDiagnostic=visualContact && visualDebugOption &&
+ (strcmp(visualDebugOption,"contact-mesh-query")==0 || strcmp(visualDebugOption,"contact-mesh-sources")==0);
+ hlsl.clear();
+ for (unsigned stage = 0; stage < (coastalSurf?16u:15u); ++stage) {
+ char line[128];
+ snprintf(line, sizeof(line), "Texture2D Texture%u : register(t%u);\nSamplerState Sampler%u : register(s%u);\n", stage, stage, stage, stage);
+ hlsl += line;
+ }
+ hlsl += WaterFftSampling::UniformSource("CombinerConstants",0,visualContact);
+ hlsl += R"HLSL(struct Input
+{
+ float4 Position : SV_Position;
+ float4 Diffuse : COLOR0;
+ float4 Specular : COLOR1;
+)HLSL";
+ for (unsigned stage = 0; stage < MAXIMUM_COMBINER_STAGES; ++stage) {
+ char line[80];
+ snprintf(line, sizeof(line), " float2 TexCoord%u : TEXCOORD%u;\n", stage, stage);
+ hlsl += line;
+ }
+ hlsl += R"HLSL( float Fog : FOG;
+};
+// The legacy scene targets use UNORM rather than sRGB. Decode their colours for light transport,
+// then encode the composed water once before the legacy fog and shoreline blend.
+float3 waterLinear(float3 rgb) { return pow(max(rgb, float3(0, 0, 0)), 2.2); }
+float3 waterDisplay(float3 rgb) { return pow(saturate(rgb), 1.0 / 2.2); }
+float oceanHash(float2 p)
+{
+ float3 q = frac(float3(p.x, p.y, p.x) * 0.1031);
+ q += dot(q, q.yzx + 33.33);
+ return frac((q.x + q.y) * q.z);
+}
+float oceanNoise(float2 p)
+{
+ float2 cell = floor(p), f = frac(p);
+ f = f*f*(3.0-2.0*f);
+ return lerp(lerp(oceanHash(cell), oceanHash(cell+float2(1,0)), f.x),
+ lerp(oceanHash(cell+float2(0,1)), oceanHash(cell+float2(1,1)), f.x), f.y);
+}
+// Broad radiance belongs to the reflected sky direction. It therefore follows the evolving
+// surface normal instead of looking like a second texture sliding across the water plane.
+float3 oceanSky(float3 ray, float3 light, float daylight)
+{
+ float horizon = pow(1.0-saturate(ray.z), 4.0);
+ float2 sunAxis = normalize(light.xy + float2(0.00001,0));
+ float2 skyPlane = float2(dot(ray.xy,sunAxis),dot(ray.xy,float2(-sunAxis.y,sunAxis.x)))
+ / (0.45+abs(ray.z));
+ float cloud = oceanNoise(skyPlane*2.7+float2(7.8,2.3))*0.7
+ + oceanNoise(skyPlane*6.1+float2(0.4,13.7))*0.3;
+ // A single broad cloud bank lights only the facets reflecting that portion of the sky.
+ // Its direction follows the sky's sun-relative frame, independent of the camera and waves.
+ float3 cloudDirection=normalize(float3(-sunAxis.y,sunAxis.x,0.85));
+ float cloudBank=pow(saturate(dot(ray,cloudDirection)),48.0);
+ cloud = smoothstep(0.46,0.73,cloud) * (0.04+1.5*cloudBank);
+ // A finite bright part of the sky produces broken silver facets. An azimuth-uniform bright
+ // horizon instead illuminates every crest equally, making the waves look like pale stripes.
+ float3 radiance = lerp(float3(0.016,0.055,0.110),float3(0.023,0.070,0.130),horizon);
+ radiance += cloud*float3(1.85,1.96,2.04);
+ radiance += pow(saturate(dot(ray,light)),12.0)*float3(0.24,0.18,0.10);
+ // Downward reflected rays see adjacent water. Keep the horizon transition continuous, but
+ // do not extend a bright sky over the whole lower hemisphere.
+ radiance = lerp(float3(0.001,0.005,0.010),radiance,smoothstep(-0.12,0.18,ray.z));
+ return radiance * (0.06+0.94*daylight);
+}
+float3 oceanEnvironment(float3 ray,float3 light,float daylight,float roughness)
+{
+ // The unresolved ripple distribution broadens every reflected light source, including the
+ // sky. Sampling its sharp horizon/cloud field only once makes small normal changes flicker.
+ float3 tangent=normalize(cross(ray,float3(0,0,1))+float3(0.00001,0,0));
+ float3 bitangent=cross(ray,tangent);
+ float cone=max(roughness,0.22)*0.85;
+ float3 value=oceanSky(ray,light,daylight)*0.4;
+ value+=oceanSky(normalize(ray+tangent*cone),light,daylight)*0.15;
+ value+=oceanSky(normalize(ray-tangent*cone),light,daylight)*0.15;
+ value+=oceanSky(normalize(ray+bitangent*cone),light,daylight)*0.15;
+ value+=oceanSky(normalize(ray-bitangent*cone),light,daylight)*0.15;
+ return value;
+}
+float terrainHeight(float2 p)
+{
+ float2 uv = (p + TerrainParameters.xx + 5.0) / max(TerrainParameters.y, 1.0);
+ return Texture2.SampleLevel(Sampler2, uv, 0.0).r * TerrainParameters.z;
+}
+float terrainSun(float3 world, float3 light)
+{
+ float visible = 1.0;
+ if (TerrainParameters.w > 0.5) {
+ float distance = 12.0;
+ for (int i = 0; i < 6; ++i) {
+ float3 ray = world + light * distance;
+ visible = min(visible, smoothstep(-0.6, 1.2, ray.z - terrainHeight(ray.xy)));
+ distance *= 2.0;
+ }
+ }
+ return visible;
+}
+float2 pixelOffset(float2 offset, float2 dx, float2 dy)
+{
+ float determinant = dx.x * dy.y - dx.y * dy.x;
+ float inverse = abs(determinant) > 0.00001 ? 1.0 / determinant : 0.0;
+ return float2(offset.x * dy.y - offset.y * dy.x, dx.x * offset.y - dx.y * offset.x) * inverse;
+}
+float3 scenePosition(float2 pixel, float deviceDepth)
+{
+ float2 uv = (pixel - Viewport.xy) / max(Viewport.zw, float2(1, 1));
+ float4 p = mul(float4(uv * float2(2, -2) + float2(-1, 1), deviceDepth, 1), WorldFromClip);
+ return p.xyz / p.w;
+}
+// Viewport.xy already contains the legacy +0.5; these are source pixel-centre bounds.
+float2 waterScenePixel(float2 pixel)
+{
+ float2 firstPixel = max(float2(0.5, 0.5), Viewport.xy);
+ float2 lastPixel = min(1.0 / SceneParameters.yz - 0.5,
+ Viewport.xy + Viewport.zw - 1.0);
+ return clamp(pixel, firstPixel, lastPixel);
+}
+// Depth is a point-sampled independent scene snapshot, including submerged objects.
+// Preserve the existing terrain fallback when no actual scene hit is available.
+float3 bottomPosition(float2 pixel, float3 surface, float baseLevel)
+{
+ float h = TerrainParameters.w > 0.5 ? terrainHeight(surface.xy) : baseLevel - 20.0;
+ float3 fallback = float3(surface.xy, min(h, baseLevel));
+ if (SceneParameters.w < 0.5) return fallback;
+ pixel = waterScenePixel(floor(pixel) + 0.5);
+ float d = Texture6.SampleLevel(Sampler6, pixel * SceneParameters.yz, 0).r;
+ if (d >= 0.999999) return fallback;
+ return scenePosition(pixel, d);
+}
+float2 waterRefractionPixels(float opticalDepth, float3 view, float3 normal, float2 dx, float2 dy)
+{
+ float3 incident = -view;
+ float3 underwater = refract(incident, normal, 0.75);
+ // A downward ray meets a plane D below its origin at -D * ray.xy/ray.z.
+ // Subtract the incident-ray hit from the refracted-ray hit in that order.
+ // The local screen Jacobian remains the existing bounded perspective approximation.
+ float2 displacement = opticalDepth * (incident.xy / min(incident.z, -0.1)
+ - underwater.xy / min(underwater.z, -0.1));
+ float2 pixels = clamp(pixelOffset(displacement, dx, dy), float2(-8, -8), float2(8, 8));
+ return pixels * smoothstep(0.15, 2.5, opticalDepth);
+}
+struct WaterRefractionSample
+{
+ float2 pixel;
+ float3 bottom;
+ float3 colour;
+ float accepted;
+};
+// Colour reconstruction includes only taps with a real submerged scene hit.
+// Clear/invalid depth cannot use the terrain fallback as evidence for displaced colour.
+bool waterRefractionHit(float2 texel, float3 world, float3 opticalWorld, float3 view, out float3 hit)
+{
+ hit = float3(0, 0, 0);
+ float d = Texture6.SampleLevel(Sampler6, texel * SceneParameters.yz, 0).r;
+ if (!(d >= 0.0 && d < 0.999999)) return false;
+ hit = scenePosition(texel, d);
+ return hit.z <= min(world.z, opticalWorld.z) - 0.08
+ && dot(hit-world, -view) >= 0.0 && dot(hit-opticalWorld, -view) >= 0.0;
+}
+WaterRefractionSample waterRefractedScene(float2 originalPixel, float2 offset,
+ float3 world, float3 opticalWorld, float3 view, float baseLevel, float3 originalBottom)
+{
+ WaterRefractionSample result;
+ // SV_Position is a texel centre in production. Snap the fallback explicitly so it never
+ // introduces an unvalidated fractional colour footprint, including in diagnostic callers.
+ result.pixel = waterScenePixel(floor(originalPixel) + 0.5);
+ result.bottom = originalBottom;
+ result.accepted = 0.0;
+ result.colour = float3(0, 0, 0);
+ // An unavailable scene colour binds a 1x1 white placeholder, while SceneParameters.yz
+ // still describe the render target. Do not Load it at target-sized pixel coordinates.
+ // The caller uses its scattering fallback when SceneParameters.x is zero.
+ [branch] if (!(SceneParameters.x > 0.5)) return result;
+ [branch] if (SceneParameters.w > 0.5) {
+ float2 candidate = waterScenePixel(originalPixel + offset);
+ float2 lower = floor(candidate - 0.5) + 0.5;
+ float2 f = frac(candidate - 0.5);
+ float4 weights = float4((1-f.x)*(1-f.y), f.x*(1-f.y), (1-f.x)*f.y, f.x*f.y);
+ int nearest = (f.x >= 0.5 ? 1 : 0) + (f.y >= 0.5 ? 2 : 0);
+ float2 nearestTexel = waterScenePixel(lower + float2(nearest & 1, (nearest >> 1) & 1));
+ float3 nearestHit;
+ // Preserve a valid nearest scene hit for transport. A rejected colour neighbour must
+ // not switch the entire optical ray back to the original pixel: at grazing angles that
+ // discontinuously changes absorption and also contaminates neighbouring derivatives.
+ bool nearestValid = waterRefractionHit(nearestTexel, world, opticalWorld, view, nearestHit);
+ [branch] if (nearestValid) {
+ float4 validWeights = float4(0, 0, 0, 0);
+ validWeights[nearest] = weights[nearest];
+ bool completeFootprint = true;
+ [unroll] for (int i = 0; i < 4; ++i) {
+ [branch] if (i != nearest && weights[i] > 0.0) {
+ float2 texel = waterScenePixel(lower + float2(i & 1, (i >> 1) & 1));
+ float3 neighbourHit;
+ bool valid = all(texel == nearestTexel)
+ || waterRefractionHit(texel, world, opticalWorld, view, neighbourHit);
+ validWeights[i] = valid ? weights[i] : 0.0;
+ completeFootprint = completeFootprint && valid;
+ }
+ }
+ result.pixel = candidate;
+ result.bottom = nearestHit;
+ result.accepted = 1.0;
+ [branch] if (completeFootprint) {
+ result.colour = Texture5.SampleLevel(Sampler5, candidate * SceneParameters.yz, 0).rgb;
+ } else {
+ // Depth-aware bilinear reconstruction: every contributing texel has passed
+ // the same actual-depth, submerged-height and forward-plane checks. The valid
+ // nearest texel guarantees at least one quarter of the original weight.
+ float3 colour = float3(0, 0, 0);
+ [unroll] for (int i = 0; i < 4; ++i) {
+ [branch] if (validWeights[i] > 0.0) {
+ float2 texel = waterScenePixel(lower + float2(i & 1, (i >> 1) & 1));
+ colour += Texture5.Load(int3(int2(floor(texel)), 0)).rgb * validWeights[i];
+ }
+ }
+ result.colour = colour / dot(validWeights, float4(1, 1, 1, 1));
+ }
+ return result;
+ }
+ }
+ // An invalid nearest hit returns the original colour/actual bottom. An unavailable depth
+ // snapshot keeps that original colour and the caller's terrain fallback without refraction.
+ [branch] if (all(frac(result.pixel - 0.5) == 0.0))
+ result.colour = Texture5.Load(int3(int2(floor(result.pixel)), 0)).rgb;
+ else
+ result.colour = Texture5.SampleLevel(Sampler5, result.pixel * SceneParameters.yz, 0).rgb;
+ return result;
+}
+)HLSL";
+ hlsl += WaterSurfaceModel::ShaderSource();
+ hlsl += WaterSurfaceModel::OceanShaderSource();
+ hlsl += WaterOpticalModel::GetHlslSource();
+ hlsl += ModernWaterMaterial::OpticalSource();
+ hlsl += ModernWaterMaterial::BubbleSource();
+ hlsl += WaterHullModel::GetHlslSource();
+ hlsl += WaterFftSampling::PixelSource(bowLift);
+ hlsl += WaterWaveCageShader::Source(false);
+ char oceanBound[96];
+ snprintf(oceanBound, sizeof(oceanBound), "static const float oceanDisplacementBound = %.9g;\n",
+ (double)WaterSurfaceModel::OceanMaxDisplacement);
+ hlsl += oceanBound;
+ hlsl += R"HLSL(
+float terrainWaveAttenuation(float depth, float offshore)
+{
+ float shore = saturate(depth/9.0);
+ shore = shore*shore*(3.0-2.0*shore);
+ return lerp(shore, saturate((depth-0.15)/oceanDisplacementBound), offshore);
+}
+)HLSL";
+ if(visualContact) hlsl += WaterHullVisual::Source();
+ hlsl += WaterHullModel::GetEffectsHlslSource(true,visualContact);
+ if(visualContact) hlsl += R"HLSL(
+// Fresh visible contact uses the posed triangle slice at the raster surface, including
+// horizontal chop and geometric interpolation. It does not alter pressure or old wakes.
+// Shared contact material for normal shading and source-attribution diagnostics.
+// Query admission and hull accumulation remain with each caller.
+float3 oceanMeshContactFoam(WaterVisualResult contact,float2 local,float4 motion,float2 axis,
+ float speed,float moving,float collision,float time,float incomingHeight,float footprint,float waveImpact)
+{
+ float2 velocity=float2(dot(motion.xy,axis),dot(motion.xy,float2(-axis.y,axis.x)));
+ float blend=smoothstep(-0.25,0.25,velocity.x/max(speed,0.001));
+ float2 bow=lerp(contact.negative,contact.positive,blend);
+ float width=max((contact.maxY-contact.minY)*0.5,1.0);
+ float aa=clamp(footprint*0.6,0.25,1.5);
+ float wash=oceanNoise(local*float2(0.065,0.32)+float2(-time*0.12,motion.z*9.0));
+ float flecks=oceanNoise(local*0.48+float2(time*0.08,-time*0.13));
+ float sideWidth=1.0+moving*min(2.0,sqrt(width)*0.35)+collision*1.3;
+ float rim=1.0-smoothstep(sideWidth,sideWidth+aa,contact.distance);
+ float streak=smoothstep(0.43,0.68,wash)*(0.2+0.8*smoothstep(0.25,0.65,flecks));
+ // Wave contact supplies density once; the common foam material supplies fine
+ // breakup. Repeated independent birth masks previously erased most idle contact.
+ float sideFoam=max(rim*streak*moving*0.38,
+ waterHullContactCoverage(contact.distance,footprint,incomingHeight,waveImpact,width));
+ float outer=1.0-smoothstep(sideWidth,sideWidth+3.5,contact.distance);
+ float bowDistance=length((local-bow)/float2(max(width*0.8,3.0),max(width*0.9,3.0)));
+ float bowRegion=exp(-bowDistance*bowDistance*1.4);
+ float bowWidth=2.0+moving*min(7.0,3.0+sqrt(width)*0.55);
+ float bowFoam=(1.0-smoothstep(bowWidth,bowWidth+aa,contact.distance))*bowRegion
+ *moving*(0.45+0.55*smoothstep(0.25,0.7,flecks));
+ return float3(sideFoam,bowFoam*0.82,outer*(collision*0.18+moving*0.25)+bowFoam*0.4);
+}
+float2 oceanMeshHullEffects(float3 world,float level,float time,float offshore,
+ float incomingHeight,float footprint,float waveImpact)
+{
+ float foam=0.0,turbulence=0.0;
+ if(offshore<=0.001 || abs(world.z-level)>fftVerticalBound) return float2(0,0);
+ float collision=waterHullContactResponse(incomingHeight,waveImpact);
+ for(int h=0;h<clamp((int)HullParameters.x,0,8);++h) {
+ float4 meta=VisualHullMeta[h];
+ if(meta.w<0.5 || meta.y<1.0) continue;
+ int index=h*10;
+ float4 position=WaterContactRegister(index),axis=WaterContactRegister(index+1);
+ if(position.w<3.0 || abs(level-position.z)>0.1) continue;
+ float2 delta=world.xy-position.xy;
+ if(dot(delta,delta)>(meta.z+12.0)*(meta.z+12.0)) continue;
+ float4 motion=WaterContactRegister(index+2);
+ float speed=length(motion.xy),moving=smoothstep(0.3,18.0,speed);
+ // Both fresh-contact contributions are exactly zero; keep the checked geometry query for every active hull.
+ if(moving==0.0 && collision==0.0) continue;
+ float2 local=float2(dot(delta,axis.xy),dot(delta,float2(-axis.y,axis.x)));
+ WaterVisualResult contact=WaterVisualQuery(h,float3(local,world.z-level));
+ if(contact.hasSegment<0.5 || contact.distance>12.0) continue;
+ float3 effects=oceanMeshContactFoam(contact,local,motion,axis.xy,
+ speed,moving,collision,time,incomingHeight,footprint,waveImpact);
+ foam=max(foam,max(effects.x,effects.y));
+ turbulence=max(turbulence,effects.z);
+ }
+ return saturate(float2(foam,turbulence))*offshore;
+}
+)HLSL";
+ if(visualDiagnostic) hlsl += R"HLSL(
+// Diagnostic only: geometry is queried before optical eligibility. Normal effects are unchanged.
+// A nonzero red tag proves a valid source-band slice. All channels use one nearest hull.
+float4 oceanMeshHullDiagnostic(float3 world,float level,float time,float offshore,
+ float incomingHeight,float footprint,float waveImpact,int sourceMode)
+{
+ float nearestDistance=1.0e6;
+ float4 result=float4(0,0,0,1);
+ if(abs(world.z-level)>fftVerticalBound) return result;
+ for(int h=0;h<clamp((int)HullParameters.x,0,8);++h) {
+ float4 meta=VisualHullMeta[h];
+ if(meta.w<0.5 || meta.y<1.0) continue;
+ int index=h*10;
+ float4 position=WaterContactRegister(index),axis=WaterContactRegister(index+1);
+ if(position.w<3.0 || abs(level-position.z)>0.1) continue;
+ float2 delta=world.xy-position.xy;
+ if(dot(delta,delta)>(meta.z+12.0)*(meta.z+12.0)) continue;
+ float2 local=float2(dot(delta,axis.xy),dot(delta,float2(-axis.y,axis.x)));
+ WaterVisualResult contact=WaterVisualQuery(h,float3(local,world.z-level));
+ if(contact.hasSegment<0.5 || contact.distance>12.0) continue;
+ // Strict distance tie keeps the lower hull slot; all channels describe this same query.
+ if(contact.distance>=nearestDistance) continue;
+ float4 motion=WaterContactRegister(index+2);
+ float speed=length(motion.xy),moving=smoothstep(0.3,18.0,speed);
+ float collision=waterHullContactResponse(incomingHeight,waveImpact);
+ float3 effects=oceanMeshContactFoam(contact,local,motion,axis.xy,
+ speed,moving,collision,time,incomingHeight,footprint,waveImpact);
+ nearestDistance=contact.distance;
+ float taggedDistance=0.25+0.75*(1.0-saturate(contact.distance/12.0));
+ float rawSide=saturate(effects.x),rawBow=saturate(effects.y);
+ result=sourceMode==0 ? float4(taggedDistance,offshore,max(rawSide,rawBow),1.0)
+ : float4(taggedDistance,rawSide,rawBow,1.0);
+ }
+ return result;
+}
+)HLSL";
+ hlsl += WaterFoamShading::HistorySamplingSource();
+ hlsl += WaterFoamShading::Source();
+ hlsl += WaterFoamShading::MaterialSource();
+ hlsl += WaterFoamEnvironment::HlslSource();
+ hlsl += WaterShoreFoam::Source();
+ const char *coastalCrestOption=getenv("ZH_WATER_COAST_CREST");
+ const bool coastalCrest=coastalCrestOption && strcmp(coastalCrestOption,"1")==0;
+ if(coastalCrest) hlsl+=WaterCoastalCrest::Source();
+ hlsl += WaterShoreFoam::HistorySource();
+ if(coastalSurf) hlsl+=WaterCoastalPresentation::Source();
+ // Comparison switch is resolved at shader generation, never per pixel/frame.
+ const char *shoreOption=getenv("ZH_WATER_SHORE_FOAM");
+ hlsl += (!shoreOption || strcmp(shoreOption,"0")!=0)
+ ? "static const bool shoreFoamEnabled=true;\n" : "static const bool shoreFoamEnabled=false;\n";
+ hlsl += R"HLSL(
+float4 main(Input input) : SV_Target
+{
+ float2 screenUV = (input.Position.xy - Viewport.xy) / max(Viewport.zw, float2(1.0, 1.0));
+ float4 worldH = mul(float4(screenUV * float2(2.0, -2.0) + float2(-1.0, 1.0), input.Position.z, 1.0), WorldFromClip);
+ float3 world = worldH.xyz / worldH.w;
+ float2 dx = ddx(world.xy), dy = ddy(world.xy);
+ float time = WaterParameters.x;
+ float fftWeight=FftParameters.x*saturate(input.Specular.x);
+ // Horizontal chop changes world.xy. Spectral samples must remain on the original surface
+ // parameters, as the vertex stage used them, rather than swimming along the displaced mesh.
+ float2 wavePosition=FftParameters.x>0.5?input.TexCoord2:world.xy;
+ float2 parameterDx=ddx(wavePosition),parameterDy=ddy(wavePosition);
+ // Projected flat patches reuse UV0 for a render-only boundary/LOD height correction.
+ // Their original material mapping is world.xy/150. Legacy grids and rivers keep their UVs.
+ float meshCorrection=OpticalParameters.w>0.5?input.TexCoord0.x:0.0;
+ float2 materialUV=OpticalParameters.w>0.5?world.xy/150.0:input.TexCoord0;
+ float4 base = Texture0.Sample(Sampler0, materialUV);
+ float baseLevel = input.TexCoord1.y;
+ float3 bottom = bottomPosition(input.Position.xy, world, baseLevel);
+ float3 shoreSceneBottom=bottom; // un-refracted scene hit used by the guarded terrain-match heuristic
+ float depth = max(world.z - bottom.z, 0.0);
+ float3 view = normalize(CameraPosition.xyz - world + float3(0, 0, 0.00001));
+ float2 contextUV = (world.xy + TerrainParameters.xx + 5.0) / max(TerrainParameters.y, 1.0);
+ float4 opticalContext=Texture4.SampleLevel(Sampler4,contextUV,0);
+ float offshore = opticalContext.r * OpticalParameters.z * (1.0 - WaterParameters.y);
+ // The mesh and this derivative share every mode, phase, dispersion and crest harmonic.
+ // Interpolated attenuation includes shores/structures, and its product derivative is retained.
+ float2 shoreRippleSlope;
+ float3 legacyWave = waterWave(wavePosition, time, shoreRippleSlope);
+ float4 oceanSwell;
+ float4 oceanSurface = waterOceanSurface(wavePosition, time, oceanSwell);
+ float3 oceanWave = oceanSurface.xyz;
+ float3 wave = lerp(legacyWave, oceanWave, offshore);
+ FftSurface spectral=(FftSurface)0;
+ )HLSL";
+ if(bowLift) hlsl+=R"HLSL(float3 bowLiftField=0;float3 fftDampingField=float3(0,0,0);float2 fftWeightSlope=0;)HLSL";
+ else hlsl+=R"HLSL(float3 fftDampingField=float3(0,0,0);float2 fftWeightSlope=0;)HLSL";
+ hlsl+=R"HLSL(
+ float fftHorizontalWeight=0.0;
+ float2 fftHorizontalWeightSlope=0;
+ if(FftParameters.x>0.5) {
+ float freeDamping=saturate(input.Specular.y),fftOffshore=saturate(input.Specular.w);
+ fftDampingField=vesselApplyHullDamping(wavePosition,baseLevel,
+ float3(freeDamping,fftParameterGradient(freeDamping,parameterDx,parameterDy)),
+ float3(fftOffshore,fftParameterGradient(fftOffshore,parameterDx,parameterDy)));
+ fftWeightSlope=fftParameterGradient(fftWeight,parameterDx,parameterDy);
+ fftHorizontalWeight=fftWeight*fftOffshore;
+ fftHorizontalWeightSlope=fftWeightSlope*fftOffshore
+ +fftParameterGradient(fftOffshore,parameterDx,parameterDy)*fftWeight;
+ float3 horizontalScale=float3(fftHorizontalWeight*fftDampingField.x,
+ fftHorizontalWeightSlope*fftDampingField.x+fftDampingField.yz*fftHorizontalWeight);
+ )HLSL";
+ if(bowLift) hlsl+=R"HLSL(spectral=fftSurface(wavePosition,baseLevel,max(length(parameterDx),length(parameterDy)),horizontalScale);
+ bowLiftField=fftBowLift(spectral.bow,float3(freeDamping,fftParameterGradient(freeDamping,parameterDx,parameterDy)),fftDampingField);)HLSL";
+ else hlsl+=R"HLSL(spectral=fftSurface(wavePosition,baseLevel,max(length(parameterDx),length(parameterDy)),horizontalScale);)HLSL";
+ hlsl+=R"HLSL(
+ }
+ float footprint=max(length(dx),length(dy));
+ float foamFootprint=max(length(parameterDx),length(parameterDy));
+ float hullWave=lerp(wave.x,spectral.contactIncident.x,fftWeight);
+ float waveImpact=lerp(length(wave.yz),length(spectral.contactIncident.yz),fftWeight);
+ float3 hullEffects=oceanHullEffects(wavePosition,baseLevel,time,offshore,hullWave,foamFootprint,waveImpact);
+ hullEffects.x=waterFoamContactPatches(wavePosition,hullEffects.x,foamFootprint,time);
+)HLSL";
+ if(visualContact) hlsl += R"HLSL(
+ float2 meshHullEffects=oceanMeshHullEffects(world,baseLevel,time,offshore,hullWave,footprint,waveImpact);
+ meshHullEffects.x=waterFoamContactPatches(wavePosition,meshHullEffects.x,foamFootprint,time);
+ hullEffects.y=max(hullEffects.y,meshHullEffects.y);
+)HLSL";
+ hlsl += R"HLSL( float3 historyFoam=waterFoamHistory(wavePosition,baseLevel,time,foamFootprint);
+ historyFoam*=smoothstep(0.0,1.5,depth)*(1.0-WaterParameters.y);
+ float attenuation = saturate(input.TexCoord1.x);
+ // Flat water carries obstacle-only attenuation in its otherwise unused diffuse red channel.
+ // Reconstruct the terrain profile at fragment density, avoiding large triangular shading
+ // facets from differentiating the coarse mesh's interpolated shore attenuation.
+ float surfaceTerrainHeight=TerrainParameters.w>0.5?terrainHeight(world.xy):baseLevel-20.0;
+ float localTerrain = TerrainParameters.w > 0.5
+ ? terrainWaveAttenuation(baseLevel-surfaceTerrainHeight, offshore) : 1.0;
+ attenuation = lerp(attenuation, min(localTerrain, input.Diffuse.r), offshore);
+ attenuation = min(attenuation,lerp(1.0,hullEffects.z,offshore));
+ float determinant = parameterDx.x * parameterDy.y - parameterDx.y * parameterDy.x;
+ float invDet = abs(determinant) > 0.000001 ? 1.0 / determinant : 0.0;
+ float ou = ddx(offshore), ov = ddy(offshore);
+ float2 offshoreSlope = float2(ou*parameterDy.y-ov*parameterDx.y, ov*parameterDx.x-ou*parameterDy.x)*invDet;
+ wave.yz += (oceanWave.x-legacyWave.x)*offshoreSlope;
+ float du = ddx(attenuation), dv = ddy(attenuation);
+ float2 attenuationSlope = float2(du*parameterDy.y - dv*parameterDx.y, dv*parameterDx.x - du*parameterDy.x) * invDet;
+ float zu = ddx(baseLevel), zv = ddy(baseLevel);
+ float2 baseSlope = float2(zu*parameterDy.y - zv*parameterDx.y, zv*parameterDx.x - zu*parameterDy.x) * invDet;
+ float cu=ddx(meshCorrection),cv=ddy(meshCorrection);
+ float2 correctionSlope=float2(cu*parameterDy.y-cv*parameterDx.y,cv*parameterDx.x-cu*parameterDy.x)*invDet;
+ float2 slope = baseSlope + wave.yz * attenuation + wave.x * attenuationSlope + correctionSlope;
+)HLSL";
+ if(coastalCrest) hlsl += R"COAST( // All screen derivatives are evaluated before the eligibility branch. The
+ // helper then differentiates every product and the same depth-limited crest as CPU.
+ float2 coastSupportGradient=fftParameterGradient(opticalContext.a,parameterDx,parameterDy);
+ float2 coastExposureGradient=fftParameterGradient(opticalContext.b,parameterDx,parameterDy);
+ float2 coastObstacleGradient=fftParameterGradient(input.Diffuse.r,parameterDx,parameterDy);
+ float2 coastDepthGradient=baseSlope-fftParameterGradient(surfaceTerrainHeight,parameterDx,parameterDy);
+ if(OpticalParameters.z>0.5 && TerrainParameters.w>0.5 && WaterParameters.y<0.5
+ && offshore==0.0 && opticalContext.a>0.0 && opticalContext.b>0.0) {
+ float3 coastalCorrection=waterCoastalCrest(waterShoreWave(wavePosition,time).xyz,
+ float3(baseLevel-surfaceTerrainHeight,coastDepthGradient),
+ float3(opticalContext.a,coastSupportGradient),float3(opticalContext.b,coastExposureGradient),
+ float3(input.Diffuse.r,coastObstacleGradient),float3(attenuation,attenuationSlope));
+ slope+=coastalCorrection.yz;meshCorrection+=coastalCorrection.x;
+ }
+)COAST";
+ hlsl += R"HLSL( float3 normal = normalize(float3(-slope, 1.0));
+ float continuousHeight=baseLevel+wave.x*attenuation+meshCorrection;
+ WaveCage cage=waveCage(wavePosition,baseLevel);
+ float cageAmount=cage.support*FftParameters.x;
+ float2 cageAmountSlope=fftParameterGradient(cageAmount,parameterDx,parameterDy);
+ float3 cageObstacle=float3(saturate(input.Diffuse.r),fftParameterGradient(input.Diffuse.r,parameterDx,parameterDy));
+ if(cageAmount>0.0)
+ cageObstacle=vesselApplyHullDamping(wavePosition,baseLevel,cageObstacle,float3(1,0,0));
+ WaveCageSurface cagePhysical=waveCageSurface(cage,wavePosition,baseLevel,spectral.displacement,
+ spectral.derivativeX,spectral.derivativeY,cageObstacle,parameterDx,parameterDy);
+ WaveCageSurface cageShaded=waveCageSurface(cage,wavePosition,baseLevel,spectral.shadingDisplacement,
+ spectral.shadingDerivativeX,spectral.shadingDerivativeY,cageObstacle,parameterDx,parameterDy);
+ float fftCompression=1.0;
+ float fftDamping=0.0;
+ float3 resolvedNormal=normal;
+ float unresolvedSlopeVariance=0.0;
+ if(FftParameters.x>0.5) {
+ fftDamping=fftDampingField.x;
+ float2 weightSlope=fftWeightSlope;
+ float2 dampingSlope=fftDampingField.yz;
+ float horizontalWeight=fftHorizontalWeight*fftDamping;
+ float2 horizontalSlope=fftHorizontalWeightSlope*fftDamping+dampingSlope*fftHorizontalWeight;
+ float oldHeight=continuousHeight-baseLevel;
+ )HLSL";
+ if(bowLift) hlsl+=R"HLSL(float newHeight=spectral.displacement.z*fftDamping+bowLiftField.x;)HLSL";
+ else hlsl+=R"HLSL(float newHeight=spectral.displacement.z*fftDamping;)HLSL";
+ hlsl+=R"HLSL(
+ float2 newSlope=float2(spectral.derivativeX.z,spectral.derivativeY.z)*fftDamping
+ )HLSL";
+ if(bowLift) hlsl+=R"HLSL(+spectral.displacement.z*dampingSlope+bowLiftField.yz;)HLSL";
+ else hlsl+=R"HLSL(+spectral.displacement.z*dampingSlope;)HLSL";
+ hlsl+=R"HLSL(
+ float2 heightSlope=baseSlope+lerp(slope-baseSlope,newSlope,fftWeight)
+ +(newHeight-oldHeight)*weightSlope;
+ float3 tangentX=float3(1.0+spectral.derivativeX.x*horizontalWeight+spectral.displacement.x*horizontalSlope.x,
+ spectral.derivativeX.y*horizontalWeight+spectral.displacement.y*horizontalSlope.x,heightSlope.x);
+ float3 tangentY=float3(spectral.derivativeY.x*horizontalWeight+spectral.displacement.x*horizontalSlope.y,
+ 1.0+spectral.derivativeY.y*horizontalWeight+spectral.displacement.y*horizontalSlope.y,heightSlope.y);
+ float3 oldDelta=float3(spectral.displacement.xy*horizontalWeight,lerp(oldHeight,newHeight,fftWeight));
+ float3 cageDelta=float3(cagePhysical.displacement.xy*fftWeight,lerp(oldHeight,cagePhysical.displacement.z,fftWeight));
+ float3 cageX=float3(1,0,baseSlope.x)+cagePhysical.derivativeX*fftWeight
+ +float3(cagePhysical.displacement.xy,cagePhysical.displacement.z-oldHeight)*weightSlope.x;
+ float3 cageY=float3(0,1,baseSlope.y)+cagePhysical.derivativeY*fftWeight
+ +float3(cagePhysical.displacement.xy,cagePhysical.displacement.z-oldHeight)*weightSlope.y;
+ cageX.z+=(slope.x-baseSlope.x)*(1.0-fftWeight);
+ cageY.z+=(slope.y-baseSlope.y)*(1.0-fftWeight);
+ tangentX=lerp(tangentX,cageX,cageAmount)+(cageDelta-oldDelta)*cageAmountSlope.x;
+ tangentY=lerp(tangentY,cageY,cageAmount)+(cageDelta-oldDelta)*cageAmountSlope.y;
+ normal=normalize(cross(tangentX,tangentY));
+ // Filter the same displacement derivatives for reflected/direct light only. Keep
+ // level-zero geometry, refraction, contact and optical path reconstruction intact.
+ )HLSL";
+ if(bowLift) hlsl+=R"HLSL(float shadedHeight=spectral.shadingDisplacement.z*fftDamping+bowLiftField.x;)HLSL";
+ else hlsl+=R"HLSL(float shadedHeight=spectral.shadingDisplacement.z*fftDamping;)HLSL";
+ hlsl+=R"HLSL(
+ float2 shadedSlope=float2(spectral.shadingDerivativeX.z,spectral.shadingDerivativeY.z)*fftDamping
+ )HLSL";
+ if(bowLift) hlsl+=R"HLSL(+spectral.shadingDisplacement.z*dampingSlope+bowLiftField.yz;)HLSL";
+ else hlsl+=R"HLSL(+spectral.shadingDisplacement.z*dampingSlope;)HLSL";
+ hlsl+=R"HLSL(
+ float2 shadedHeightSlope=baseSlope+lerp(slope-baseSlope,shadedSlope,fftWeight)
+ +(shadedHeight-oldHeight)*weightSlope;
+ float3 shadedX=float3(1.0+spectral.shadingDerivativeX.x*horizontalWeight+spectral.shadingDisplacement.x*horizontalSlope.x,
+ spectral.shadingDerivativeX.y*horizontalWeight+spectral.shadingDisplacement.y*horizontalSlope.x,shadedHeightSlope.x);
+ float3 shadedY=float3(spectral.shadingDerivativeY.x*horizontalWeight+spectral.shadingDisplacement.x*horizontalSlope.y,
+ 1.0+spectral.shadingDerivativeY.y*horizontalWeight+spectral.shadingDisplacement.y*horizontalSlope.y,shadedHeightSlope.y);
+ float3 shadedOldDelta=float3(spectral.shadingDisplacement.xy*horizontalWeight,lerp(oldHeight,shadedHeight,fftWeight));
+ float3 shadedCageDelta=float3(cageShaded.displacement.xy*fftWeight,lerp(oldHeight,cageShaded.displacement.z,fftWeight));
+ float3 shadedCageX=float3(1,0,baseSlope.x)+cageShaded.derivativeX*fftWeight
+ +float3(cageShaded.displacement.xy,cageShaded.displacement.z-oldHeight)*weightSlope.x;
+ float3 shadedCageY=float3(0,1,baseSlope.y)+cageShaded.derivativeY*fftWeight
+ +float3(cageShaded.displacement.xy,cageShaded.displacement.z-oldHeight)*weightSlope.y;
+ shadedCageX.z+=(slope.x-baseSlope.x)*(1.0-fftWeight);
+ shadedCageY.z+=(slope.y-baseSlope.y)*(1.0-fftWeight);
+ shadedX=lerp(shadedX,shadedCageX,cageAmount)+(shadedCageDelta-shadedOldDelta)*cageAmountSlope.x;
+ shadedY=lerp(shadedY,shadedCageY,cageAmount)+(shadedCageDelta-shadedOldDelta)*cageAmountSlope.y;
+ resolvedNormal=normalize(cross(shadedX,shadedY));
+ unresolvedSlopeVariance=spectral.unresolvedSlopeVariance*fftWeight*fftWeight*fftDamping*fftDamping;
+ continuousHeight=baseLevel+lerp(oldHeight,lerp(newHeight,cagePhysical.displacement.z,cageAmount),fftWeight);
+ fftCompression=lerp(1.0,spectral.incidentCompression,saturate(input.Specular.w));
+ }
+ // Reconstruct the same continuous wave between mesh vertices for optical integration. The
+ // rendered scene bottom stays exact; using coarse triangle heights here exposes their edges
+ // through absorption on the campaign shell's deliberately shallow offshore terrain. Move on
+ // the camera ray, with a bounded correction at grazing angles, retaining raster occlusion.
+ float opticalShift = WaterOpticalRayShift(continuousHeight-world.z,
+ view.z, offshore, oceanDisplacementBound, dot(world-bottom,view), length(CameraPosition.xyz-world));
+ float3 opticalWorld = world + view*opticalShift;
+ float opticalDepth = max(opticalWorld.z-bottom.z,0.0);
+ // Floor clearance flattens the mesh at the bank, but the incident wave pattern
+ // must still catch light across the shallows. Restore its terrain-damped lighting
+ // slopes with the same spectral phases, retaining wet-edge and obstacle/hull shelter.
+ // Geometry, refraction and full offshore shading keep their original normals.
+ float shoreRippleLimit = min(smoothstep(0.0,0.75,depth),min(input.Diffuse.r,hullEffects.z));
+ float shoreRippleWeight = opticalContext.b * OpticalParameters.z * TerrainParameters.w
+ * (1.0-WaterParameters.y) * (1.0-offshore) * (1.0-cageAmount*fftWeight);
+ float2 shoreRipple = shoreRippleWeight * lerp(
+ shoreRippleSlope * max(0.0,shoreRippleLimit-max(localTerrain,attenuation)),
+ float2(spectral.shadingDerivativeX.z,spectral.shadingDerivativeY.z)
+ * max(0.0,shoreRippleLimit-max(localTerrain,fftDamping)),fftWeight);
+ float3 waveLightingNormal = resolvedNormal;
+ if(any(shoreRipple!=0.0))
+ resolvedNormal = normalize(resolvedNormal + float3(-shoreRipple*resolvedNormal.z,0.0));
+ float materialBubbleWeight=modernWaterBubbleWeight(MaterialParameters.y,MaterialParameters.z,depth);
+ ModernWaterBubbles materialBubbles=(ModernWaterBubbles)0;
+ if(materialBubbleWeight>0.0) {
+ materialBubbles=modernWaterBubbles(wavePosition,time,footprint);
+ float3 capNormal=float3(-materialBubbles.slope*materialBubbleWeight,0);
+ normal=normalize(normal+capNormal);
+ resolvedNormal=normalize(resolvedNormal+capNormal);
+ waveLightingNormal=normalize(waveLightingNormal+capNormal);
+ }
+ float3 light = normalize(SunDirection.xyz + float3(0, 0, 0.00001));
+ float nDotV = max(dot(resolvedNormal, view), 0.001);
+ float nDotL = saturate(dot(resolvedNormal, light));
+ float3 halfway = normalize(view + light + float3(0, 0, 0.00001));
+ float nDotH = saturate(dot(resolvedNormal, halfway));
+ float vDotH = saturate(dot(view, halfway));
+ float fresnel = 0.025 + 0.975 * pow(1.0 - saturate(nDotV), 5.0);
+ // Keep the bed readable at the shallow bank instead of covering it with bright sky bands.
+ fresnel = 0.025 + (fresnel - 0.025) * lerp(lerp(0.35, 1.0, smoothstep(3.0, 18.0, depth)), 1.0, offshore);
+ float variance = dot(ddx(resolvedNormal), ddx(resolvedNormal)) + dot(ddy(resolvedNormal), ddy(resolvedNormal));
+ float roughness = clamp(sqrt(lerp(0.016, 0.036, offshore) + variance * 0.24), 0.126, 0.34);
+ roughness=lerp(roughness,max(roughness,0.27),max(hullEffects.y,historyFoam.z)*0.5);
+ // Isotropic missing slope variance broadens alpha-squared (roughness^4 in this GGX
+ // convention). Removing unresolved normals must not turn the surface into a mirror.
+ if(unresolvedSlopeVariance>0.0) roughness=pow(min(1.0,pow(roughness,4.0)+0.5*unresolvedSlopeVariance),0.25);
+ float a2 = pow(roughness, 4.0);
+ float denominator = nDotH * nDotH * (a2 - 1.0) + 1.0;
+ float distribution = a2 / max(3.14159265 * denominator * denominator, 0.0000001);
+ float k = roughness * roughness * 0.5;
+ float masking = nDotV / (nDotV * (1.0 - k) + k);
+ masking *= nDotL / max(nDotL * (1.0 - k) + k, 0.0001);
+ float sunFresnel = 0.02 + 0.98 * pow(1.0 - vDotH, 5.0);
+ float sunVisible = terrainSun(world, light);
+ float3 highlight = waterLinear(SunColour.rgb) * 2.0 * (distribution * masking * sunFresnel * sunVisible / max(4.0 * nDotV, 0.001));
+ highlight = highlight / (1.0 + highlight * 0.6);
+ float daylight = saturate(max(max(SunColour.r, SunColour.g), SunColour.b));
+ // Integrate the short crossing ripples into the environment lobe. Their shared spectrum
+ // still supplies physical height, refraction normals and directional sun glints, while the
+ // broad sky follows the resolved swell surface instead of tracing every fine ripple edge.
+ float rippleResolution=0.88/(1.0+footprint*0.18);
+ float3 environmentWave=lerp(oceanSwell.xyz,oceanWave,rippleResolution);
+ float2 swellSlope=baseSlope+environmentWave.yz*attenuation+environmentWave.x*attenuationSlope+correctionSlope;
+ float3 environmentNormal=normalize(lerp(normal,normalize(float3(-swellSlope,1)),offshore));
+ environmentNormal=normalize(lerp(environmentNormal,waveLightingNormal,fftWeight));
+ if(any(shoreRipple!=0.0))
+ environmentNormal=normalize(environmentNormal+float3(-shoreRipple*environmentNormal.z,0.0));
+ // The remaining fine-slope energy is ~0.045 for this spectrum (including its packet
+ // envelope); retaining a fraction of its amplitude leaves (1-fraction^2) as roughness.
+ float environmentRoughness=sqrt(roughness*roughness+0.045*(1.0-rippleResolution*rippleResolution)*offshore*(1.0-fftWeight));
+ float3 reflectedRay = reflect(-view, environmentNormal);
+ float3 sky = lerp(float3(0.49, 0.62, 0.68), float3(0.23, 0.38, 0.48), saturate(reflectedRay.z)) * (0.06 + daylight * 0.94);
+ float2 reflectionOffset = float2((ReflectionArea.x + 1.0) * 0.5, (1.0 - ReflectionArea.w) * 0.5);
+ float2 reflectionScale = max((ReflectionArea.zw - ReflectionArea.xy) * 0.5, float2(0.001, 0.001));
+ float2 reflectionUV = (screenUV - reflectionOffset) / reflectionScale;
+ float2 distortion = pixelOffset(resolvedNormal.xy * 8.0, dx, dy) / max(Viewport.zw, float2(1, 1)) / reflectionScale;
+ float2 blur = roughness * 0.008 / reflectionScale;
+ float4 mirror = Texture1.Sample(Sampler1, saturate(reflectionUV + distortion)) * 0.5;
+ mirror += Texture1.Sample(Sampler1, saturate(reflectionUV + distortion + blur)) * 0.25;
+ mirror += Texture1.Sample(Sampler1, saturate(reflectionUV + distortion - blur)) * 0.25;
+ float2 border = min(reflectionUV, 1.0 - reflectionUV);
+ // Legacy terrain passes preserve destination alpha for shore blending, including in the
+ // mirror. Its transparent-black clear gives RGB coverage even when geometry cannot write A.
+ float mirrorCoverage = saturate(max(max(mirror.r, mirror.g), mirror.b) * 64.0);
+ float coverage = saturate(min(border.x, border.y) * 30.0) * mirrorCoverage * WaterParameters.z;
+ coverage *= 1.0 - smoothstep(0.5, 2.0, abs(baseLevel - WaterParameters.w));
+ float3 skyRadiance=waterLinear(sky);
+ if(offshore>0.0) skyRadiance=lerp(skyRadiance,oceanEnvironment(reflectedRay,light,daylight,environmentRoughness),offshore);
+ float3 reflection = lerp(skyRadiance, waterLinear(mirror.rgb), coverage);
+ // Refraction uses the actual optical depth and shared colour/depth viewport bounds.
+ float2 refractionPixels = waterRefractionPixels(opticalDepth, view, normal, dx, dy);
+ WaterRefractionSample refractedScene = waterRefractedScene(input.Position.xy, refractionPixels,
+ world, opticalWorld, view, baseLevel, bottom);
+ bottom = refractedScene.bottom;
+ float bedDepth = max(opticalWorld.z-bottom.z, 0.0);
+ float3 scene = waterLinear(refractedScene.colour);
+ // Material detail is fixed to the *actual* submerged scene position. Keep object materials,
+ // steep cliff faces, map tint, and visibility; only exposed bed terrain receives this detail.
+ float bedHeight = terrainHeight(bottom.xy);
+ float2 bedSlope = float2(terrainHeight(bottom.xy+float2(5,0))-terrainHeight(bottom.xy-float2(5,0)),
+ terrainHeight(bottom.xy+float2(0,5))-terrainHeight(bottom.xy-float2(0,5))) * 0.1;
+ float terrainMask = (1.0-smoothstep(0.6, 2.6, abs(bottom.z-bedHeight)))
+ * (1.0-smoothstep(0.5, 1.6, length(bedSlope))) * TerrainParameters.w * SceneParameters.w;
+ float2 bedUV = bottom.xy / 48.0;
+ float4 material = Texture7.Sample(Sampler7, bedUV);
+ float4 broadMaterial = Texture7.Sample(Sampler7, bedUV * 0.173 + float2(0.31,0.67));
+ float gravel = saturate(WaterParameters.y * (0.25 + 0.8*broadMaterial.a) + length(bedSlope)*0.2);
+ float detail = lerp(material.r / 0.55, material.g / 0.45, gravel);
+ float2 bedRelief = float2(Texture7.Sample(Sampler7, bedUV+float2(1.0/256.0,0)).b - Texture7.Sample(Sampler7, bedUV-float2(1.0/256.0,0)).b,
+ Texture7.Sample(Sampler7, bedUV+float2(0,1.0/256.0)).b - Texture7.Sample(Sampler7, bedUV-float2(0,1.0/256.0)).b);
+ float3 bedNormal = normalize(float3(-bedSlope - bedRelief*gravel*1.8, 1.0));
+ float bedLight = 0.7 + 0.45*saturate(dot(bedNormal, light));
+ float rockVariation = lerp(0.82, 1.12, broadMaterial.a);
+ float bedLuminance = dot(scene, float3(0.2126,0.7152,0.0722));
+ scene = lerp(scene, bedLuminance*float3(1.10,1.0,0.80), terrainMask*gravel*0.38);
+ scene *= lerp(1.0, clamp(detail*bedLight*rockVariation, 0.38, 1.65), terrainMask * 0.85);
+ // Caustics use the evolving surface curvature at the light's entry point. Keep the modulation
+ // restrained and attenuate it by depth/footprint to avoid a painted luminous network at RTS zoom.
+ float3 causticWave = waterWave(bottom.xy-light.xy/max(light.z,0.2)*bedDepth, time);
+ float causticFootprint = max(length(ddx(bottom.xy)), length(ddy(bottom.xy)));
+ float3 causticNormal = normalize(float3(-causticWave.yz*attenuation, 1));
+ float3 sunRay = refract(-light, causticNormal, 0.75);
+ float2 bend = sunRay.xy / min(sunRay.z, -0.1) * bedDepth;
+ float2 bx = ddx(bottom.xy), by = ddy(bottom.xy);
+ float2 cx = bx+ddx(bend), cy = by+ddy(bend);
+ float focused = abs(bx.x*by.y-bx.y*by.x) / max(abs(cx.x*cy.y-cx.y*cy.x),0.0001);
+ float caustic = lerp(1.0, clamp(focused, 0.82, 1.55), exp(-bedDepth*0.055)
+ * sunVisible * daylight / (1.0 + causticFootprint*0.45));
+ // Absorption follows the underwater view-ray distance, including submerged object geometry.
+ // Campaign seas can have deliberately flat, shallow terrain beneath full-size ships. Honour
+ // their authored opacity offshore, while preserving the clear optical profile at coasts and
+ // in enclosed pools. Actual scene ray length still governs submerged objects and refraction.
+ float3 transmission = WaterOpticalTransmission(length(bottom-opticalWorld), WaterParameters.y,
+ offshore, OpticalParameters.x, OpticalParameters.y);
+ // Preserve the current face-light signal, but apply it only to water's in-scattered source.
+ // Transmitted terrain/object colour must not receive a second surface-light multiplier.
+ float3 swellNormal=normalize(float3(-oceanSwell.yz*attenuation-correctionSlope,1));
+ swellNormal=normalize(lerp(swellNormal,normal,fftWeight));
+ float swellLight=saturate(dot(swellNormal,light));
+ float3 scatter=WaterOpticalScatteringSource(WaterParameters.y,offshore,daylight*sunVisible,swellLight);
+ scatter=modernWaterMaterialSource(scatter,MaterialColor,MaterialParameters.x,daylight*sunVisible,swellLight);
+ if(MaterialParameters.y>0.0) {
+ float materialPatch=oceanNoise(wavePosition*0.009+float2(time*0.008,-time*0.006));
+ transmission=modernWaterMaterialTransmission(transmission,MaterialColor.rgb,MaterialParameters.y,
+ length(bottom-opticalWorld),materialPatch);
+ }
+ float3 body=WaterOpticalBody(scene,transmission,scatter,caustic,SceneParameters.x);
+ float foamNoise = smoothstep(0.1, 0.8, lerp(wave.x,spectral.contactIncident.x,fftWeight)*0.5+0.5);
+ float edgeDistance = depth / max(length(float2(ddx(depth), ddy(depth))), 0.01);
+ float contact = (1.0 - smoothstep(0.2, 1.35, edgeDistance)) * saturate(depth * 4.0)
+ * max(TerrainParameters.w, SceneParameters.w);
+ float foam = contact * (0.25 + 0.75 * foamNoise) * (0.2 + 0.8 * daylight);
+ // Evaluate terrain derivatives outside the conditional so all neighbouring fragments
+ // participate. Their world-space gradient gives the direction toward open water.
+ float terrainDu=ddx(surfaceTerrainHeight),terrainDv=ddy(surfaceTerrainHeight);
+ float2 terrainGradient=float2(terrainDu*parameterDy.y-terrainDv*parameterDx.y,
+ terrainDv*parameterDx.x-terrainDu*parameterDy.x)*invDet;
+ float shoreRate=0.0,shoreSupport=0.0;
+ float shoreHistory=waterShoreHistory(wavePosition,baseLevel,time)*(1.0-fftWeight);
+ float shoreRetained=0.0;
+ // Same source composition with the coastal term omitted; retain this one scalar
+ // through the real masks/max operations to attribute its final material weight.
+ float foamWithoutShore=foam;
+ // Contact wash follows the arriving broad FFT face on the deformed surface.
+ // It is a bounded material approximation, not the paper's spray-particle solver.
+ float cageWash=0.0;
+ float broadSlope=length(spectral.contactIncident.yz);
+ float terrainSlope=length(terrainGradient);
+ float arrival=dot(spectral.contactIncident.yz,-terrainGradient)/max(broadSlope*terrainSlope,0.00001);
+ float cageTerrainMatch=1.0-smoothstep(0.5,1.5,abs(shoreSceneBottom.z-terrainHeight(shoreSceneBottom.xy)));
+ float cageWet=smoothstep(0.015,0.18,depth)*cageTerrainMatch*saturate(cageObstacle.x);
+ float cageContact=1.0-smoothstep(0.2,2.5,max(0.0,world.z-surfaceTerrainHeight));
+ float cageCrest=smoothstep(0.05,0.7,spectral.contactIncident.x)*smoothstep(0.0,0.35,arrival);
+ float cagePores=smoothstep(0.24,0.72,oceanNoise(world.xy*0.6));
+ cageWash=cageAmount*fftWeight*cageWet*cageContact*cageCrest*lerp(0.45,1.0,cagePores);
+ foam=max(foam*(1.0-cageAmount*fftWeight*cageTerrainMatch),cageWash*0.72);
+)HLSL";
+ if(coastalSurf) hlsl+=R"COAST(
+ float gpuCoastFoam=0.0,gpuCoastRaw=0.0,gpuCoastGate=0.0;
+ float2 gpuCoastDensityAge=0.0;
+ if(WaterParameters.y<0.5 && OpticalParameters.z>0.5 && OpticalParameters.w>0.5
+ && TerrainParameters.w>0.5 && SceneParameters.w>0.5
+ && all(isfinite(SceneParameters.yz)) && all(SceneParameters.yz>0)
+ && waterCoastalViewValid(CoastalArea,CoastalParams,wavePosition,baseLevel,time)) {
+ float2 coastUV=(wavePosition-CoastalArea.xy)/CoastalArea.zw;
+ float2 coastMoments=Texture15.SampleLevel(Sampler15,coastUV,0).rg;
+ float2 coastDensityAge=waterCoastalAtTime(coastMoments,CoastalParams.w-CoastalParams.z);
+ gpuCoastDensityAge=coastDensityAge;
+ if(coastDensityAge.x>0.0) {
+ // Source and lookup live on the original parameter chart, not chopped XY.
+ float2 parameterContextUV=(wavePosition+TerrainParameters.xx+5.0)/max(TerrainParameters.y,1.0);
+ float canonicalSupport=Texture4.SampleLevel(Sampler4,parameterContextUV,0).b;
+ float coastModelGate=waterCoastalModelGate(fftWeight,canonicalSupport,input.TexCoord0.x,correctionSlope);
+ gpuCoastRaw=waterCoastalPorousCoverage(wavePosition,foamFootprint,coastDensityAge);
+ if(coastModelGate>0.0 && gpuCoastRaw>0.0) {
+ // Reconstruct the original actual scene sample. A refracted hit or the
+ // terrain fallback cannot justify surf on an object or dry fragment.
+ float2 coastPixel=waterScenePixel(floor(input.Position.xy)+0.5);
+ float coastRawDepth=Texture6.SampleLevel(Sampler6,coastPixel*SceneParameters.yz,0).r;
+ if(waterShoreSceneDepth(SceneParameters.w,coastRawDepth)) {
+ float3 coastHit=scenePosition(coastPixel,coastRawDepth);
+ float coastHullGuard=vesselHullDamping(world.xy,baseLevel).x;
+ float coastWetGate=waterCoastalWetGate(coastRawDepth,coastHit,world,view,baseLevel,
+ surfaceTerrainHeight,terrainHeight(wavePosition),terrainHeight(coastHit.xy),input.Diffuse.r,coastHullGuard);
+ gpuCoastGate=coastModelGate*coastWetGate;
+ gpuCoastFoam=gpuCoastRaw*gpuCoastGate;
+ }
+ }
+ }
+ }
+)COAST";
+ hlsl+=R"HLSL(
+ if(shoreFoamEnabled && WaterParameters.y<0.5 && OpticalParameters.z>0.5
+ && TerrainParameters.w>0.5 && SceneParameters.w>0.5
+ && opticalContext.r==0.0 && (opticalContext.a>0.0 || shoreHistory>0.0)) {
+ // Test the original raster pixel, not the refracted candidate or bottomPosition's
+ // terrain fallback. Clear/invalid depth must keep the prior rim unchanged.
+ float2 shorePixel=waterScenePixel(floor(input.Position.xy)+0.5);
+ float shoreRawDepth=Texture6.SampleLevel(Sampler6,shorePixel*SceneParameters.yz,0).r;
+ if(waterShoreSceneDepth(SceneParameters.w,shoreRawDepth)) {
+ shoreSupport=opticalContext.a*(1.0-fftWeight);
+ float terrainDepth=max(0.0,baseLevel-surfaceTerrainHeight);
+ float terrainSlope=length(terrainGradient);
+ float shoreDistance=min(opticalContext.g*100.0,terrainDepth/max(terrainSlope,0.01));
+ // These three phases follow only the remaining analytic mesh contribution.
+ // Derivatives were evaluated outside this branch; filter their leading faces
+ // without expanding terrain/wet support or creating a permanent coast rim.
+ float2 shoreFront;
+ float4 shoreWave=waterShoreWaveFront(wavePosition,time,-terrainGradient,parameterDx,parameterDy,shoreFront);
+ shoreRate=waterShoreRate(shoreWave,terrainDepth,shoreDistance,-terrainGradient,
+ terrainSlope,opticalContext.b,shoreSupport)*shoreFront.x;
+ // Terrain matching is a heuristic: larger object/terrain separation keeps the
+ // previous rim, while thin objects and nonplanar terrain need native validation.
+ // The original real scene hit is independently required above; wetness still
+ // gates emission, and terrain metadata alone cannot paint onto a dry fragment.
+ float terrainMatch=1.0-smoothstep(0.5,1.5,
+ abs(shoreSceneBottom.z-terrainHeight(shoreSceneBottom.xy)));
+ shoreRetained=shoreHistory*smoothstep(0.0,0.8,depth)*terrainMatch;
+ foam=waterShoreBlendFrontHistory(foam,shoreRate,shoreFront.y,shoreHistory,shoreSupport,smoothstep(0.0,0.8,depth),terrainMatch);
+ foamWithoutShore*=1.0-saturate(shoreSupport)*saturate(terrainMatch);
+ }
+ }
+ // At a known hull, use its irregular wave wash instead of also drawing the generic scene
+ // intersection rim. Otherwise that continuous depth edge fills every intended foam gap.
+ foam *= lerp(1.0,hullEffects.z,offshore);
+ foamWithoutShore*=lerp(1.0,hullEffects.z,offshore);
+ // Curvature of the undamped ocean model selects breaking crests. Including attenuation in
+ // this derivative would invent bright rings around a ship's damping footprint.
+ float curvature = -oceanSwell.w;
+ float crest = smoothstep(0.045, 0.11, curvature) * smoothstep(1.0, 2.4, oceanSwell.x);
+ // A narrow band at the swell's turning slope forms a crest line, rather than filling the
+ // whole high-curvature cap with a disconnected white patch. Pixel derivatives soften its
+ // edges as this world-space band becomes smaller than a pixel at RTS distances.
+ float crestSlope=dot(oceanSwell.yz,float2(0.9304,0.3665));
+ float crestBand=1.0-smoothstep(0.025,0.085+fwidth(crestSlope)*0.65,abs(crestSlope));
+ float foamPatch = oceanNoise(world.xy*0.065 + float2(time*0.06,-time*0.025));
+ float foamBreakup = smoothstep(0.35, 0.7, oceanNoise(world.xy*0.38+float2(-time*0.13,time*0.08)));
+ float crestFoam = crest * crestBand * smoothstep(0.53, 0.76, foamPatch) * offshore
+ * foamBreakup * smoothstep(0.06, 0.25, attenuation) * (0.2+0.8*daylight);
+ // Ambient breaking follows the long/medium part of the geometry's horizontal
+ // compression. Fine ripples shape its appearance without triggering whitecaps.
+ float fftFoam=saturate(pow(max(0.0,1.2-fftCompression),7.2))
+ *smoothstep(0.15,0.65,fftDamping)*saturate(input.Specular.w)*(0.2+0.8*daylight);
+ crestFoam=lerp(crestFoam,fftFoam,fftWeight);
+ foam = max(foam, crestFoam*0.48);
+ foamWithoutShore=max(foamWithoutShore,crestFoam*0.48);
+ // Generated bow/stern crests come from the displaced mesh's physical packet. Their
+ // coverage is independent of illumination and joins the same lit surface as hull wash
+ // and history; putting it through generic crest shading dimmed this response twice.
+ float generatedFoam=vesselGeneratedFoam(spectral.vesselCrest,fftWeight,fftDamping);
+ float freshFoam=max(hullEffects.x,generatedFoam);
+ float vesselFoam=max(freshFoam,historyFoam.x);
+ // Fresh hull wash can cover an old trail. Blend its age continuously as that source
+ // becomes dominant instead of imprinting old holes into newly generated foam.
+ float foamAge=historyFoam.y*24.0*(1.0-smoothstep(0.25,1.0,
+ freshFoam/max(historyFoam.x,0.0001)));
+ // Current solid hulls mask old trails if they cross another vessel's waterline.
+ vesselFoam*=smoothstep(0.0,0.006,hullEffects.z);
+)HLSL";
+ if(visualContact) hlsl += R"HLSL(
+ // Actual triangle contact may meet the visible hull inside the mean footprint.
+ // Keep the old mask for trails and pressure foam, and merge fresh contact after it.
+ if(meshHullEffects.x>0.0) {
+ freshFoam=max(freshFoam,meshHullEffects.x);
+ vesselFoam=max(vesselFoam,meshHullEffects.x);
+ foamAge=historyFoam.y*24.0*(1.0-smoothstep(0.25,1.0,
+ freshFoam/max(historyFoam.x,0.0001)));
+ }
+)HLSL";
+ hlsl += R"HLSL()HLSL";
+ if(bowLift) hlsl+=R"HLSL( // This is foam on the additional displaced bow shoulder, not mean-plane hull wash.
+ // Its height already includes F-D; the unchanged opaque scene depth hides solid hulls.
+ float liftedBowFoam=fftBowLiftFoam(bowLiftField.x,fftWeight);
+ if(liftedBowFoam>0.0) {
+ freshFoam=max(freshFoam,liftedBowFoam);
+ vesselFoam=max(vesselFoam,liftedBowFoam);
+ foamAge=historyFoam.y*24.0*(1.0-smoothstep(0.25,1.0,freshFoam/max(historyFoam.x,0.0001)));
+ }
+ vesselFoam=waterFoamMicroCoverage(wavePosition,vesselFoam,foamFootprint,foamAge,time);)HLSL";
+ else hlsl+=R"HLSL( vesselFoam=waterFoamMicroCoverage(wavePosition,vesselFoam,foamFootprint,foamAge,time);)HLSL";
+ hlsl+=R"HLSL(
+ foam=max(foam,vesselFoam);
+ foamWithoutShore=max(foamWithoutShore,vesselFoam);
+)HLSL";
+ if(coastalSurf) hlsl+=" float gpuCoastPrevious=foam;\n foam=max(foam,gpuCoastFoam);\n";
+ hlsl+=R"HLSL(
+ float shoreMaterialWeight=waterFoamCoastWeight(foam,foamWithoutShore,vesselFoam);
+ // Analytic fine normals can face away from the eye between geometric vertices. Fresnel alone
+ // approaches one there and paints a bright band on a hidden wave face. Smith visibility
+ // smoothly removes that reflected energy while retaining the underlying water body.
+ float oceanViewCosine = saturate(dot(environmentNormal,view));
+ float environmentK=environmentRoughness*environmentRoughness*0.5;
+ float oceanViewVisibility = oceanViewCosine / max(oceanViewCosine*(1.0-environmentK)+environmentK,0.0001);
+ float environmentFresnel=0.025+0.975*pow(1.0-oceanViewCosine,5.0);
+ float visibleFresnel = lerp(fresnel,environmentFresnel*oceanViewVisibility,offshore);
+ float3 surface = lerp(body, reflection, visibleFresnel) + highlight;
+ if(materialBubbleWeight>0.0) {
+ float film=saturate(materialBubbles.rim*0.16+materialBubbles.cap*0.045+materialBubbles.ripple*0.065)*materialBubbleWeight;
+ surface=lerp(surface,modernWaterBubbleFilm(MaterialColor.rgb)*(0.12+0.88*daylight*sunVisible),film);
+ }
+ // Foam replaces transmission and the clear-water material locally. Its diffuse and rough
+ // reflected light follow the same displaced surface; neither is additive white emission.
+ float foamDiffuse=(0.22+0.78*saturate(dot(normal,light)))*(0.12+0.88*daylight);
+ float3 foamAlbedo=lerp(float3(0.67,0.73,0.71),float3(0.79,0.83,0.81),historyFoam.z);
+ // Newly deposited contact foam shares the fresh material even on a stationary
+ // ship. Turbulence alone previously left it at the older, darker endpoint.
+ float foamFreshness=max(max(historyFoam.z,hullEffects.y),1.0-smoothstep(2.0,8.0,foamAge));
+ float3 vesselAlbedo=lerp(float3(0.75,0.80,0.77),float3(0.88,0.91,0.87),foamFreshness);
+ // Preserve the authored visible directional-light increment. Offshore foam replaces
+ // its ambient with hemispherical illumination from the same sky as the water reflection.
+ float3 vesselIrradiance=waterFoamIrradiance(normal,light,HullParameters.yzw,SunColour.rgb,
+ sunVisible*FoamFillLights[0].w,FoamFillLights[0].xyz,FoamFillLights[1].rgb,
+ FoamFillLights[2].xyz,FoamFillLights[3].rgb);
+ )HLSL";
+ if(coastalSurf) hlsl+=" float3 coastAuthoredIrradiance=vesselIrradiance;\n";
+ hlsl+=R"HLSL(
+ if(vesselFoam>0.0 && offshore>0.0)
+ vesselIrradiance=waterFoamReplaceAmbient(vesselIrradiance,HullParameters.yzw,
+ waterFoamSkyIrradiance(normal,light,daylight),offshore);
+ )HLSL";
+ if(coastalSurf) hlsl+=R"COAST(
+ // Coast has its own ambient replacement, independent of vessel presence. Keep
+ // the exact previous lighting when this optional source contributes nothing.
+ float3 coastIrradiance=vesselIrradiance;
+ if(gpuCoastFoam>0.0 && offshore>0.0)
+ coastIrradiance=waterFoamReplaceAmbient(coastAuthoredIrradiance,HullParameters.yzw,
+ waterFoamSkyIrradiance(normal,light,daylight),offshore);
+)COAST";
+ hlsl+=R"HLSL(
+ float3 vesselDiffuse=waterLinear(vesselAlbedo)*vesselIrradiance;
+ float3 vesselRadiance=vesselDiffuse;
+ float3 shoreRadiance=waterLinear(foamAlbedo)*foamDiffuse;
+ if(vesselFoam>0.0 || shoreMaterialWeight>0.0) {
+ // The existing sky and planar scene remain coherent with the waves. Foam has a
+ // broader material lobe, including reflected objects; retaining sharp mirror samples
+ // here would turn its diffuse body into a glossy painted patch.
+ float foamRoughness=max(environmentRoughness,0.55);
+ float3 foamSky=waterLinear(sky);
+ if(offshore>0.0) foamSky=lerp(foamSky,
+ oceanEnvironment(reflectedRay,light,daylight,foamRoughness),offshore);
+ float foamLevelCoverage=WaterParameters.z
+ *(1.0-smoothstep(0.5,2.0,abs(baseLevel-WaterParameters.w)));
+ float3 foamReflection=waterFoamPlanarReflection(foamSky,reflectionUV,distortion,
+ reflectionScale,foamRoughness,foamLevelCoverage);
+ vesselRadiance=waterFoamRoughMaterial(vesselDiffuse,foamReflection,
+ environmentFresnel,oceanViewCosine,foamRoughness);
+ // Share the filtered incident reflection; exchange Fresnel only once.
+ if(shoreMaterialWeight>0.0)
+)HLSL";
+ hlsl+=coastalSurf
+ ? " shoreRadiance=waterFoamRoughMaterial(waterLinear(foamAlbedo)*coastIrradiance,\n"
+ : " shoreRadiance=waterFoamRoughMaterial(waterLinear(foamAlbedo)*vesselIrradiance,\n";
+ hlsl+=R"HLSL( foamReflection,environmentFresnel,oceanViewCosine,foamRoughness);
+ }
+ // Mix the lit surface contributions; independently mixing albedo and irradiance
+ // before multiplying would add cross terms where vessel and crest foam overlap.
+ if(shoreMaterialWeight>0.0)
+ surface=waterDisplay(waterFoamCoastLayer(surface,waterLinear(foamAlbedo)*foamDiffuse,
+ vesselRadiance,shoreRadiance,foam,vesselFoam,shoreMaterialWeight));
+ else
+ surface=waterDisplay(waterFoamLayer(surface,waterLinear(foamAlbedo)*foamDiffuse,
+ vesselRadiance,foam,vesselFoam));
+ float4 current;
+)HLSL";
+ if (river) {
+ hlsl += " float4 edge = Texture3.Sample(Sampler3, float2(2.0*input.TexCoord0.x, input.TexCoord0.y));\n";
+ hlsl += " current = float4(saturate(surface) * input.Diffuse.a, edge.a * saturate(depth * 2.0) * lerp(base.a, step(0.001, base.a), SceneParameters.x));\n";
+ } else {
+ hlsl += " float4 edge = Texture3.Sample(Sampler3, input.TexCoord3);\n";
+ hlsl += " current = float4(saturate(surface) * edge.rgb, saturate(depth * 2.0) * lerp(input.Diffuse.a * base.a, step(0.001, input.Diffuse.a * base.a), SceneParameters.x));\n";
+ }
+ // Developer captures isolate the actual water inputs; normal game output is unaffected.
+ const char *debug = getenv("ZH_WATER_DEBUG");
+ if(coastalSurf && debug && strcmp(debug,"coastal-surf")==0)
+ hlsl+="current=float4(gpuCoastRaw,gpuCoastGate,gpuCoastFoam,1.0);\n";
+ if(coastalSurf && debug && strcmp(debug,"coastal-density")==0)
+ hlsl+="current=float4(waterFoamOpticalCoverage(gpuCoastDensityAge.x),gpuCoastDensityAge.y/14.0,gpuCoastRaw,1.0);\n";
+ if(coastalSurf && debug && strcmp(debug,"coastal-material")==0)
+ hlsl+="current=float4(gpuCoastPrevious,max(0.0,foam-gpuCoastPrevious),shoreMaterialWeight,1.0);\n";
+ if (debug && strcmp(debug, "depth") == 0) hlsl += "current.rgb = (1.0-exp(-depth*0.04)).xxx;\n";
+ if (debug && strcmp(debug, "bed") == 0) hlsl += "current.rgb = waterDisplay(scene);\n";
+ if (debug && strcmp(debug, "reflection") == 0) hlsl += "current.rgb = waterDisplay(reflection);\n";
+ if (debug && strcmp(debug, "normal") == 0) hlsl += "current.rgb = normal*0.5+0.5;\n";
+ if (debug && strcmp(debug, "highlight") == 0) hlsl += "current.rgb = waterDisplay(highlight);\n";
+ if (debug && strcmp(debug, "offshore") == 0) hlsl += "current.rgb = offshore.xxx;\n";
+ if (debug && strcmp(debug, "wave-cage") == 0) hlsl += "current = float4(cageAmount,cage.radii.x/fftVerticalBound,cage.radii.y/fftVerticalBound,1.0);\n";
+ if (debug && strcmp(debug, "cage-wash") == 0) hlsl += "current = float4(cageWash,cageContact*cageAmount,cageCrest*cageAmount,1.0);\n";
+ if (debug && strcmp(debug, "shore-history") == 0) hlsl += "current = float4(shoreHistory,shoreRate/ShoreMaximumRate,shoreSupport,1.0);\n";
+ if (debug && strcmp(debug, "shore-history-terms") == 0) hlsl += "current = float4(shoreHistory,shoreRetained,current.a,1.0);\n";
+ if (debug && strcmp(debug, "shore") == 0) hlsl += "current.rgb = float3(shoreRate/ShoreMaximumRate,shoreSupport,opticalContext.b);\n";
+ // Opaque diagnostic removes thin-water alpha compositing from source attribution.
+ if (debug && strcmp(debug, "shore-raw") == 0) hlsl += "current = float4(shoreRate/ShoreMaximumRate,shoreSupport,opticalContext.b,1.0);\n";
+ if (debug && strcmp(debug, "shore-source-terms") == 0) hlsl += R"HLSL(
+ // Shore source attribution (M5i): R actual admitted front rate / maximum rate;
+ // G same model with a fixed-world terrain derivative / maximum rate;
+ // B fresh-front coverage after scene wetness/terrain match, in raw [0,1] units.
+ // B excludes retained history and later hull/max/material operations. It is not
+ // divided by the old .35-second cap. This code is absent from normal shaders.
+ float2 sourceTermsFront;
+ float4 sourceTermsWave=waterShoreWaveFront(wavePosition,time,-terrainGradient,
+ parameterDx,parameterDy,sourceTermsFront);
+ float2 fixedShoreGradient=float2(terrainHeight(world.xy+float2(5,0))-terrainHeight(world.xy-float2(5,0)),
+ terrainHeight(world.xy+float2(0,5))-terrainHeight(world.xy-float2(0,5)))*0.1;
+ float fixedShoreDepth=max(0.0,baseLevel-surfaceTerrainHeight),fixedShoreSlope=length(fixedShoreGradient);
+ float2 fixedShoreFront;
+ float4 fixedShoreWave=waterShoreWaveFront(wavePosition,time,-fixedShoreGradient,
+ parameterDx,parameterDy,fixedShoreFront);
+ float fixedShoreRate=waterShoreRate(fixedShoreWave,fixedShoreDepth,
+ min(opticalContext.g*100.0,fixedShoreDepth/max(fixedShoreSlope,0.01)),
+ -fixedShoreGradient,fixedShoreSlope,opticalContext.b,shoreSupport)*fixedShoreFront.x;
+ float finalShoreCoverage=waterShoreFrontFresh(shoreRate,sourceTermsFront.y)*smoothstep(0.0,0.8,depth)
+ *(1.0-smoothstep(0.5,1.5,abs(shoreSceneBottom.z-terrainHeight(shoreSceneBottom.xy))));
+ current=float4(shoreRate/ShoreMaximumRate,fixedShoreRate/ShoreMaximumRate,finalShoreCoverage,1.0);
+ // End shore source attribution. Only the opt-in diagnostic recomputes residence.
+)HLSL";
+ if (debug && strcmp(debug, "foam") == 0) hlsl += "current.rgb = float3(historyFoam.x,hullEffects.x,historyFoam.y*historyFoam.x);\n";
+ if (debug && strcmp(debug, "vessel") == 0) hlsl += "current.rgb = float3(max(0.0,-spectral.vesselHeight),max(0.0,spectral.vesselHeight),spectral.vesselCrest)*fftWeight;\n";
+ if (debug && strcmp(debug, "pressure") == 0) hlsl += "current.rgb = fftPressureDebug(spectral,fftWeight,fftDamping,generatedFoam);\n";
+ if (debug && strcmp(debug, "resolved-normal") == 0) hlsl += "current.rgb = resolvedNormal*0.5+0.5;\n";
+ if (debug && strcmp(debug, "roughness") == 0) hlsl += "current.rgb = float3(roughness,environmentRoughness,sqrt(unresolvedSlopeVariance));\n";
+ if (debug && strcmp(debug, "pressure-retention") == 0) hlsl += "current.rgb = fftPressureRetentionDebug(spectral,fftWeight,fftDamping,generatedFoam);\n";
+ // Diagnostics evaluate old and current rules at the same fragment/phase/snapshot.
+ // No extra code is emitted for normal water or any unrelated debug mode.
+ if (debug && (strcmp(debug,"footprint")==0 || strcmp(debug,"footprint-path")==0 ||
+ strcmp(debug,"footprint-colour")==0 || strcmp(debug,"footprint-reasons")==0 || strcmp(debug,"footprint-overlay")==0)) {
+ hlsl += R"HLSL(
+float2 auditOrigin=waterScenePixel(input.Position.xy);
+float2 auditCandidate=waterScenePixel(input.Position.xy+refractionPixels);
+float3 auditOriginalBottom=bottomPosition(input.Position.xy,world,baseLevel);
+float3 auditOldHit=bottomPosition(auditCandidate,world,baseLevel);
+// Exact previous M4B/M4A nearest-only selection, including its terrain fallback policy.
+float auditOldAccepted=step(auditOldHit.z,min(world.z,opticalWorld.z)-0.08)
+ *step(0.0,min(dot(auditOldHit-world,-view),dot(auditOldHit-opticalWorld,-view)));
+float2 auditOldPixel=lerp(auditOrigin,auditCandidate,auditOldAccepted);
+float3 auditOldBottom=lerp(auditOriginalBottom,auditOldHit,auditOldAccepted);
+float auditOriginalDepth=Texture6.SampleLevel(Sampler6,
+ waterScenePixel(floor(input.Position.xy)+0.5)*SceneParameters.yz,0).r;
+float auditOriginalRealHit=(SceneParameters.w>0.5 && auditOriginalDepth>=0.0 && auditOriginalDepth<0.999999)?1.0:0.0;
+float auditNewPath=length(refractedScene.bottom-opticalWorld);
+float auditOldPath=length(auditOldBottom-opticalWorld);
+)HLSL";
+ if(strcmp(debug,"footprint-overlay")==0)
+ hlsl += "current.rgb=lerp(current.rgb,float3(1,0,1),0.7*auditOldAccepted*(1.0-refractedScene.accepted));\n";
+ if(strcmp(debug,"footprint")==0)
+ hlsl += "current.rgb=float3(refractedScene.accepted,auditOldAccepted,auditOriginalRealHit);\n";
+ if(strcmp(debug,"footprint-path")==0)
+ hlsl += "current.rgb=float3(saturate((auditNewPath-auditOldPath)/16.0),saturate((auditOldPath-auditNewPath)/16.0),1.0-auditOriginalRealHit);\n";
+ if(strcmp(debug,"footprint-colour")==0)
+ hlsl += "float3 auditOldColour=Texture5.SampleLevel(Sampler5,auditOldPixel*SceneParameters.yz,0).rgb;\n"
+ "current.rgb=saturate(abs(refractedScene.colour-auditOldColour)*4.0);\n";
+ if(strcmp(debug,"footprint-reasons")==0) {
+ hlsl += R"HLSL(
+// Classify every positive-weight tap. R=unavailable/clear/invalid depth,
+// G=not below one/both water surfaces, B=not behind one/both forward planes.
+// Multiple channels may be set; they are causes present, not a guessed primary cause.
+float3 auditReasons=float3(SceneParameters.w>0.5?0.0:1.0,0,0);
+if(SceneParameters.w>0.5) {
+ float2 auditLower=floor(auditCandidate-0.5)+0.5;
+ float2 auditFraction=frac(auditCandidate-0.5);
+ float4 auditWeights=float4((1-auditFraction.x)*(1-auditFraction.y),
+ auditFraction.x*(1-auditFraction.y),(1-auditFraction.x)*auditFraction.y,
+ auditFraction.x*auditFraction.y);
+ [unroll] for(int auditTap=0;auditTap<4;++auditTap) {
+ [branch] if(auditWeights[auditTap]>0.0) {
+ float2 auditTexel=waterScenePixel(auditLower+float2(auditTap&1,(auditTap>>1)&1));
+ float auditDepth=Texture6.SampleLevel(Sampler6,auditTexel*SceneParameters.yz,0).r;
+ if(!(auditDepth>=0.0 && auditDepth<0.999999)) auditReasons.r=1.0;
+ else {
+ float3 auditHit=scenePosition(auditTexel,auditDepth);
+ if(!(auditHit.z<=min(world.z,opticalWorld.z)-0.08)) auditReasons.g=1.0;
+ if(!(dot(auditHit-world,-view)>=0.0 && dot(auditHit-opticalWorld,-view)>=0.0)) auditReasons.b=1.0;
+ }
+ }
+ }
+}
+current.rgb=auditReasons;
+)HLSL";
+ }
+ }
+}
+
+// Opt-in original-scene-depth attribution. Normal shader text remains unchanged.
+static int water_hull_depth_diagnostic()
+{
+ const char *mode=getenv("ZH_WATER_DEBUG");
+ if(mode && strcmp(mode,"contact-depth")==0) return 1;
+ if(mode && strcmp(mode,"contact-depth-masks")==0) return 2;
+ if(mode && strcmp(mode,"contact-depth-height")==0) return 3;
+ return 0;
+}
+
+static void write_water_hull_depth_diagnostic(std::string &hlsl)
+{
+ hlsl+=R"HLSL(
+// These are measurements, not new foam emission or a claim of scene object identity.
+// Read the original scene pixel once, without bottomPosition's terrain fallback and
+// without the later refraction offset. All quantities use actual raster world.xyz.
+float hullDepthValid=0.0,hullDepthWetProximity=0.0,hullDepthSupport=0.0,hullDepthRegion=0.0;
+float3 hullDepthHit=float3(0,0,0);
+if(SceneParameters.w>0.5 && all(isfinite(SceneParameters.yz))
+ && all(SceneParameters.yz>0.0) && all(isfinite(world))) {
+ float2 hullDepthPixel=waterScenePixel(floor(input.Position.xy)+0.5);
+ float hullDepthRaw=Texture6.SampleLevel(Sampler6,hullDepthPixel*SceneParameters.yz,0).r;
+ if(isfinite(hullDepthRaw) && hullDepthRaw>=0.0 && hullDepthRaw<0.999999) {
+ hullDepthHit=scenePosition(hullDepthPixel,hullDepthRaw);
+ if(all(isfinite(hullDepthHit))) {
+ hullDepthValid=1.0;
+ if(hullDepthHit.z<=world.z && dot(hullDepthHit-world,-view)>=0.0)
+ hullDepthWetProximity=saturate(1.0-length(hullDepthHit-world)/8.0);
+ }
+ }
+}
+// Known-vessel context is deliberately conservative: the union of the current mean
+// and reachable-slab footprints. It is NOT an instantaneous cross-section or hull ID.
+// A 12-unit expanded rectangle only bounds diagnostic work/display; it emits no foam.
+for(int hullDepthHull=0;hullDepthHull<clamp((int)HullParameters.x,0,8);++hullDepthHull) {
+ int hullDepthIndex=hullDepthHull*10;
+ float4 hullDepthMean=HullData[hullDepthIndex],hullDepthMeanAxis=HullData[hullDepthIndex+1];
+ float4 hullDepthSlab=WaterContactRegister(hullDepthIndex),hullDepthSlabAxis=WaterContactRegister(hullDepthIndex+1);
+ if(hullDepthMean.w<3.0 || hullDepthMean.w>12.0 || abs(baseLevel-hullDepthMean.z)>0.1) continue;
+ float2 hullDepthMeanDelta=world.xy-hullDepthMean.xy;
+ float2 hullDepthMeanLocal=float2(dot(hullDepthMeanDelta,hullDepthMeanAxis.xy),
+ dot(hullDepthMeanDelta,float2(-hullDepthMeanAxis.y,hullDepthMeanAxis.x)));
+ float2 hullDepthSlabDelta=world.xy-hullDepthSlab.xy;
+ float2 hullDepthSlabLocal=float2(dot(hullDepthSlabDelta,hullDepthSlabAxis.xy),
+ dot(hullDepthSlabDelta,float2(-hullDepthSlabAxis.y,hullDepthSlabAxis.x)));
+ bool hullDepthSlabValid=hullDepthSlab.w>=3.0 && hullDepthSlab.w<=12.0 && abs(baseLevel-hullDepthSlab.z)<=0.1;
+ bool hullDepthInMean=all(abs(hullDepthMeanLocal)<hullDepthMeanAxis.zw+12.0);
+ bool hullDepthInSlab=hullDepthSlabValid && all(abs(hullDepthSlabLocal)<hullDepthSlabAxis.zw+12.0);
+ if(!hullDepthInMean && !hullDepthInSlab) continue;
+ hullDepthRegion=1.0;
+ if(hullDepthValid>0.5) {
+ float2 hullDepthMeanHitDelta=hullDepthHit.xy-hullDepthMean.xy;
+ float2 hullDepthMeanHit=float2(dot(hullDepthMeanHitDelta,hullDepthMeanAxis.xy),
+ dot(hullDepthMeanHitDelta,float2(-hullDepthMeanAxis.y,hullDepthMeanAxis.x)));
+ float hullDepthDistance=WaterHullSignedDistance(hullDepthMeanHit,hullDepthIndex,(int)hullDepthMean.w);
+ if(hullDepthSlabValid) {
+ float2 hullDepthSlabHitDelta=hullDepthHit.xy-hullDepthSlab.xy;
+ float2 hullDepthSlabHit=float2(dot(hullDepthSlabHitDelta,hullDepthSlabAxis.xy),
+ dot(hullDepthSlabHitDelta,float2(-hullDepthSlabAxis.y,hullDepthSlabAxis.x)));
+ hullDepthDistance=min(hullDepthDistance,WaterContactDistance(hullDepthSlabHit,hullDepthIndex,(int)hullDepthSlab.w));
+ }
+ hullDepthSupport=max(hullDepthSupport,1.0-smoothstep(0.0,4.0,max(hullDepthDistance,0.0)));
+ }
+}
+// Separate likely bed hits from a surface standing above/below terrain. This is an
+// attribution heuristic: submerged rocks/other objects can pass it, so it is not ID.
+float hullDepthOffTerrain=0.0;
+if(hullDepthValid>0.5 && TerrainParameters.w>0.5) {
+ float hullDepthTerrain=terrainHeight(hullDepthHit.xy);
+ if(isfinite(hullDepthTerrain))
+ hullDepthOffTerrain=smoothstep(0.5,1.5,abs(hullDepthHit.z-hullDepthTerrain));
+}
+float hullDepthKnownConfidence=hullDepthRegion*hullDepthSupport*hullDepthOffTerrain;
+float hullDepthCandidate=hullDepthWetProximity*hullDepthKnownConfidence;
+)HLSL";
+}
+
+static void finish_water_hull_depth_diagnostic(std::string &hlsl,int mode)
+{
+ // Normal fog/alpha test has already executed. Encode raw measurements afterwards,
+ // opaque for byte attribution, without changing ordinary clipping or any normal mode.
+ if(mode==1) hlsl+=R"HLSL(
+// R: original finite real scene hit in the selected known-hull diagnostic region.
+// G: behind/below-water hit proximity, max(0,1-worldRayGap/8), in that region.
+// B: same hit agrees with conservative hull footprint and is separated from terrain.
+current=float4(hullDepthRegion*hullDepthValid,hullDepthRegion*hullDepthWetProximity,
+ hullDepthKnownConfidence,1.0);
+)HLSL";
+ else if(mode==2) hlsl+=R"HLSL(
+// R: G*B from contact-depth (a possible visible contact, NOT emitted foam).
+// G: that candidate after the old generic-rim mean-hull suppression.
+// B: that candidate after the old vessel-foam mean-solid mask, independently of G.
+current=float4(hullDepthCandidate,hullDepthCandidate*lerp(1.0,hullEffects.z,offshore),
+ hullDepthCandidate*smoothstep(0.0,0.006,hullEffects.z),1.0);
+)HLSL";
+ else hlsl+=R"HLSL(
+// R/G: actual raster-water / original valid scene-hit height relative to mean level,
+// each encoded saturate(0.5+0.5*(z-baseLevel)/fftVerticalBound). Endpoints are censored.
+// B: the same wet, near-surface, footprint/nonterrain candidate from the other modes.
+// Invalid original hits have G=0; outside the known-hull display region RGB is zero.
+current=float4(hullDepthRegion*saturate(0.5+0.5*(world.z-baseLevel)/fftVerticalBound),
+ hullDepthRegion*hullDepthValid*saturate(0.5+0.5*(hullDepthHit.z-baseLevel)/fftVerticalBound),
+ hullDepthCandidate,1.0);
+)HLSL";
+}
+
bool EngineShader_Pixel_Program(EngineShaderProgram program,
const PixelPipelineDescription & pipeline, std::string & hlsl, CombinerShaderTarget target)
{
@@ -488,6 +1668,37 @@ bool EngineShader_Pixel_Program(EngineShaderProgram program,
return false;
}
if (target == COMBINER_SHADER_TARGET_SDL3_GPU) {
+#if defined(__linux__)
+ if (program == ENGINE_SHADER_WATER_TRAPEZOID || program == ENGINE_SHADER_WATER_RIVER) {
+ write_modern_water(hlsl, program == ENGINE_SHADER_WATER_RIVER);
+ const int hullDepthDiagnostic=water_hull_depth_diagnostic();
+ if(hullDepthDiagnostic) write_water_hull_depth_diagnostic(hlsl);
+ if (!CombinerShader_Append_Pixel_Pipeline(pipeline, hlsl)) return false;
+ if(hullDepthDiagnostic) finish_water_hull_depth_diagnostic(hlsl,hullDepthDiagnostic);
+ const bool visualContact=WaterHullVisual::Enabled();
+ const char *waterDebug=getenv("ZH_WATER_DEBUG");
+ if(WaterBowLift::Enabled() && waterDebug && strcmp(waterDebug,"bow-retention")==0)
+ hlsl += "// Encode raw bow measurements after ordinary clipping/fog/alpha test.\n"
+ "current=float4(fftBowRetentionDebug(spectral,fftWeight,saturate(input.Specular.y),fftDamping),1.0);\n";
+ if(visualContact && waterDebug && strcmp(waterDebug,"contact-mesh")==0)
+ hlsl += "// Raw actual-height source, combined fresh source, and final material coverage.\ncurrent=float4(meshHullEffects.x,freshFoam,vesselFoam,1.0);\n";
+ if(visualContact && waterDebug && strcmp(waterDebug,"contact-mesh-alpha")==0)
+ hlsl += "// Raw actual-height source, final material coverage, and original compositing alpha.\ncurrent=float4(meshHullEffects.x,vesselFoam,current.a,1.0);\n";
+ if(visualContact && waterDebug && strcmp(waterDebug,"contact-material")==0)
+ hlsl += "// Lit vessel material before coverage and legacy fog/shroud composition.\ncurrent=float4(waterDisplay(vesselRadiance),1.0);\n";
+ if(visualContact && waterDebug && strcmp(waterDebug,"contact-lighting")==0)
+ hlsl += "// Surface sun cosine, actual direct-light visibility, and original fog visibility.\ncurrent=float4(saturate(dot(normal,light)),sunVisible*FoamFillLights[0].w,saturate(input.Fog),1.0);\n";
+ if(visualContact && waterDebug &&
+ (strcmp(waterDebug,"contact-mesh-query")==0 || strcmp(waterDebug,"contact-mesh-sources")==0)) {
+ // Evaluate and encode after the ordinary pipeline; no diagnostic changes normal water.
+ hlsl += strcmp(waterDebug,"contact-mesh-query")==0
+ ? "current=oceanMeshHullDiagnostic(world,baseLevel,time,offshore,hullWave,footprint,waveImpact,0);\n"
+ : "current=oceanMeshHullDiagnostic(world,baseLevel,time,offshore,hullWave,footprint,waveImpact,1);\n";
+ }
+ hlsl += " return current;\n}\n";
+ return SDL3_Shader_Retarget(hlsl, false);
+ }
+#endif // __linux__
return write_engine_pixel_program(program, pipeline, hlsl, false)
&& SDL3_Shader_Retarget(hlsl, false);
}
@@ -503,10 +1714,10 @@ static bool write_engine_pixel_program(EngineShaderProgram program,
if (entry != NULL && entry->Opening != NULL) {
write_multiply_chain(hlsl, *entry, volumetric);
}
- else if (program == ENGINE_SHADER_WATER_TRAPEZOID) {
+ else if (program == ENGINE_SHADER_WATER_TRAPEZOID || program == ENGINE_SHADER_WATER_CLASSIC_TRAPEZOID) {
write_trapezoid_water(hlsl);
}
- else if (program == ENGINE_SHADER_WATER_RIVER) {
+ else if (program == ENGINE_SHADER_WATER_RIVER || program == ENGINE_SHADER_WATER_CLASSIC_RIVER) {
write_river_water(hlsl);
}
else if (program == ENGINE_SHADER_WATER_REFLECTION) {
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.h
index 2f591f111..89acc26d4 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.h
@@ -70,7 +70,10 @@ enum EngineShaderProgram
ENGINE_SHADER_FLAT_TERRAIN_NOISE,
ENGINE_SHADER_FLAT_TERRAIN_NOISE_2,
ENGINE_SHADER_ROAD_NOISE_2,
- ENGINE_SHADER_MONOCHROME
+ ENGINE_SHADER_MONOCHROME,
+ // Explicit Classic variants keep the SDL shader cache independent of the selected water style.
+ ENGINE_SHADER_WATER_CLASSIC_TRAPEZOID,
+ ENGINE_SHADER_WATER_CLASSIC_RIVER
};
// The name the engine loaded the shader under: a path for the ones that ship as files
diff --git a/GeneralsMD/Code/Tests/WaterBowShoulderTest.h b/GeneralsMD/Code/Tests/WaterBowShoulderTest.h
new file mode 100644
index 000000000..01b2a5ef2
--- /dev/null
+++ b/GeneralsMD/Code/Tests/WaterBowShoulderTest.h
@@ -0,0 +1,63 @@
+#pragma once
+#include "Platform/WaterVesselWaves.h"
+#include <cassert>
+namespace WaterBowShoulderTest {
+namespace S=WaterBowShoulder;
+WaterHullModel::Hull hull(double speed=40,double angle=0) {
+ WaterHullModel::Hull h;h.data[0][0]=127;h.data[0][1]=-83;h.data[0][2]=4;h.data[0][3]=5;
+ h.data[1][0]=std::cos(angle);h.data[1][1]=std::sin(angle);h.data[1][2]=40;h.data[1][3]=9;
+ h.data[2][0]=speed*std::cos(angle);h.data[2][1]=speed*std::sin(angle);h.data[2][3]=42;
+ h.data[3][0]=-40;h.data[3][2]=40;
+ double p[5][2]={{-40,-9},{20,-9},{40,0},{20,9},{-40,9}};
+ for(unsigned i=0;i<5;++i){h.data[4+i/2][2*(i%2)]=p[i][0];h.data[4+i/2][2*(i%2)+1]=p[i][1];}return h;
+}
+// Larger analytic hull keeps the same normalized forebody shape; independent fixture
+// geometry, not a claim to be the exact carrier mesh or its instantaneous waterline.
+inline WaterHullModel::Hull scaledHull(double halfLength,double halfBeam,double speed=40,double angle=0) {
+ auto h=hull(speed,angle);const double sx=halfLength/40,sy=halfBeam/9;
+ h.data[1][2]=float(halfLength);h.data[1][3]=float(halfBeam);
+ h.data[2][3]=float(std::hypot(halfLength,halfBeam));
+ h.data[3][0]=float(-halfLength);h.data[3][2]=float(halfLength);
+ for(unsigned i=0;i<5;++i){h.data[4+i/2][2*(i%2)]*=float(sx);h.data[4+i/2][2*(i%2)+1]*=float(sy);}return h;
+}
+S::Contour contour(const WaterHullModel::Hull& h) {S::Contour c;const auto p=WaterVesselWaves::BowPressure(h.data[1][3],std::hypot(h.data[2][0],h.data[2][1]));const bool prepared=S::Prepare(h,4,p.along,p.amplitude,c);assert(prepared);(void)prepared;return c;}
+// Independent scalar oracle: segment distance + winding + velocity support; no production
+// query/profile/gradient calls. World packet transform intentionally expanded separately.
+double oracle(const WaterHullModel::Hull& h,double x,double y,double widthCap=12.) {
+ const double speed=std::hypot(h.data[2][0],h.data[2][1]);if(speed<=double(.3f))return 0;
+ const double dx=x-h.data[0][0],dy=y-h.data[0][1],radius=std::hypot(dx,dy),reach=h.data[2][3]+110;
+ if(radius>=reach)return 0;
+ const double px=dx*h.data[1][0]+dy*h.data[1][1],py=-dx*h.data[1][1]+dy*h.data[1][0];
+ const double fx=(h.data[2][0]*h.data[1][0]+h.data[2][1]*h.data[1][1])/speed,fy=(-h.data[2][0]*h.data[1][1]+h.data[2][1]*h.data[1][0])/speed;
+ double best=1e99,support=-1e99;bool inside=true;unsigned n=unsigned(h.data[0][3]);
+ auto vertex=[&](unsigned i,unsigned d){return double(h.data[4+i/2][2*(i%2)+d]);};
+ for(unsigned i=0;i<n;++i){unsigned k=(i+1)%n;double ax=vertex(i,0),ay=vertex(i,1),ex=vertex(k,0)-ax,ey=vertex(k,1)-ay;
+ double t=std::max(0.,std::min(1.,((px-ax)*ex+(py-ay)*ey)/(ex*ex+ey*ey)));double qx=ax+t*ex,qy=ay+t*ey,d=(px-qx)*(px-qx)+(py-qy)*(py-qy);
+ if(d<best){best=d;}inside=inside&&ex*(py-ay)-ey*(px-ax)>=0;support=std::max(support,ax*fx+ay*fy);}
+ const double beam=h.data[1][3],width=std::max(3.,std::min(widthCap,beam*double(.45f))),length=std::max(9.,std::min(32.,6+double(1.2f)*beam));
+ const double u=std::max(0.,std::min(250.,speed)-double(.3f)),amplitude=std::max(3.,std::min(8.,1.8*std::sqrt(beam)))*u*u/(u*u+26*26);
+ auto profile=[](double a){a=std::abs(a);if(a>=3)return 0.;double t=std::max(0.,std::min(1.,(a-1.5)/1.5));return std::exp(-a*a)*(1-t*t*(3-2*t));};
+ const double ridge=((inside?-1:1)*std::sqrt(best)-.5*width)/width,aft=std::max(0.,support-px*fx-py*fy)/length;
+ const double t=std::max(0.,std::min(1.,(radius-(reach-30))/30));return amplitude*profile(ridge)*profile(aft)*(1-t*t*(3-2*t));
+}
+
+// Original captured PT contact slabs at frames80/201/381, not current clock poses.
+inline WaterHullModel::Hull CapturedHull(unsigned sample) {
+ WaterHullModel::Hull h;
+ static const double meta[3][8]={
+ {2850,100,1,0,-0.796630859,0.805389404,43.5699959,8.79331398},
+ {2957.32373,101.627365,0.999879956,0.0154919038,-1.87758327,0.556955695,42.4093399,8.65352535},
+ {3137.72559,218.210144,0.527187467,0.849749029,-2.43318248,-0.390773833,41.8714218,9.2412529},
+ };
+ static const double points[3][12][2]={
+ {{-44.3667183,-2.73863411},{3.43643284,-7.74325371},{24.3135548,-7.98792601},{31.9316635,-6.89070606},{39.2081947,-4.29391861},{42.7732735,0.0232927334},{39.2874413,4.42194176},{32.0012093,7.06341076},{23.9288235,8.55384064},{11.167552,9.59870148},{1.27504039,9.19470978},{-44.3667183,2.95121074}},
+ {{-44.2869186,-7.18103313},{-9.24202156,-8.09656334},{3.95104051,-7.42917967},{34.3899384,-4.10701752},{38.6082649,-2.49652481},{40.531765,-0.06233171},{38.6690483,2.57676816},{33.8858871,4.58143282},{16.4649582,7.49637556},{-0.0597534217,9.21048737},{-17.3822479,9.02173901},{-44.2866325,7.31158113}},
+ {{-44.3046722,7.36160374},{-44.3044128,-7.56387568},{-7.98102331,-9.63191414},{-2.87246585,-9.50199986},{17.8896427,-6.07912159},{35.5311737,-2.69312334},{38.3919563,-1.40663123},{39.4381752,0.105810069},{38.3620911,1.51685262},{35.8054276,2.57435393},{-0.0340973027,7.78546333},{-20.204155,8.85059071}},
+ };
+ const auto &a=meta[sample%3];h.data[0][0]=float(a[0]+a[2]*a[4]-a[3]*a[5]);h.data[0][1]=float(a[1]+a[3]*a[4]+a[2]*a[5]);
+ h.data[0][2]=4;h.data[0][3]=12;h.data[1][0]=float(a[2]);h.data[1][1]=float(a[3]);h.data[1][2]=float(a[6]);h.data[1][3]=float(a[7]);
+ h.data[2][0]=float(40*a[2]);h.data[2][1]=float(40*a[3]);h.data[2][3]=float(std::hypot(a[6],a[7]));
+ for(unsigned i=0;i<12;++i){h.data[4+i/2][2*(i%2)]=float(points[sample%3][i][0]-a[4]);h.data[4+i/2][2*(i%2)+1]=float(points[sample%3][i][1]-a[5]);}
+ return h;
+}
+}
diff --git a/GeneralsMD/Code/Tests/WaterCoastalCapacityTest.h b/GeneralsMD/Code/Tests/WaterCoastalCapacityTest.h
new file mode 100644
index 000000000..e22c54935
--- /dev/null
+++ b/GeneralsMD/Code/Tests/WaterCoastalCapacityTest.h
@@ -0,0 +1,79 @@
+#pragma once
+#include "WaterCoastalDomainTest.h"
+#include "Platform/WaterCoastalView.h"
+namespace WaterCoastalCapacityTest {
+using WaterCoastalDomainTest::Map;
+using WaterCoastalDomainTest::Domain;
+using WaterCoastalDomainTest::Result;
+inline void Ridges(Map &m){
+ m.level=4;m.Full();for(int y=0;y<m.height;++y)for(int x=4;x<m.width;x+=8)m.heights[size_t(y)*m.width+x]=12;
+}
+inline void Check(){
+ // Actual physical coast throughout the map, not a narrowed collar or a forced
+ // optical exposure bit. Every channel reaches a playable boundary in the fine flood.
+ Map large(260,260);Ridges(large);
+ large.heights[40*260+40]=large.heights[41*260+41]=1;
+ large.heights[40*260+41]=large.heights[41*260+40]=9;
+ // A one-unit polygon gap lies in the SECOND fine link of coarse 640->650.
+ large.polygons={Map::Rect(0,0,647,2590,4),Map::Rect(648,0,2590,2590,4)};
+ if(!large.Build())return;Domain coast;CHECK(large.Install(coast)==Result::Ready);
+ CHECK(coast.Grid().spacing==10&&coast.Nodes().size()<=65536&&coast.Nodes().size()>50000);
+ CHECK(WaterCoastalSurf::ValidGraph(coast.Nodes(),10));
+ CHECK(coast.Cells().size()==coast.Nodes().size());if(coast.Cells().size()!=coast.Nodes().size())return;
+ for(size_t i=0;i<coast.Cells().size();++i){
+ const auto&c=coast.Cells()[i];const auto&n=coast.Nodes()[i];
+ CHECK(c.x>=0&&c.y>=0&&c.x<259&&c.y<259);if(c.x<0||c.y<0||c.x>=259||c.y>=259)return;
+ CHECK(n.world[0]==c.x*10&&n.world[1]==c.y*10&&n.world[2]==4);
+ CHECK(n.context.depth==4-large.heights[size_t(c.y)*260+c.x]);
+ CHECK(n.context.depth>.15&&n.context.depth<12&&n.context.distance<139);
+ }
+ const int a=coast.Topology().Find(64,80,4),b=coast.Topology().Find(65,80,4);
+ CHECK(a>=0&&b>=0);if(a<0||b<0)return;
+ CHECK((coast.Cells()[size_t(a)].connections&1)==0);
+ CHECK(coast.Nodes()[size_t(a)].neighbour[1]==0&&coast.Nodes()[size_t(b)].neighbour[0]==0);
+ CHECK(!coast.Support().At(64,80,4,1,0).Allows(0,0));
+ const auto intervals=WaterShoreSource::Intervals(large.polygons,4,800,true);
+ CHECK(WaterShoreSource::Covered(intervals,640,645));
+ CHECK(!WaterShoreSource::Covered(intervals,645,650)); // armed second-link control
+ const auto saddle=coast.Support().At(40,40,4,1,1);
+ CHECK(saddle.tile);if(!saddle.tile)return;
+ const float actual[4]={1,9,9,1};for(unsigned i=0;i<4;++i)CHECK(saddle.tile->heights[i]==actual[i]);
+ CHECK(coast.Topology().Find(40,40,4)>=0&&coast.Topology().Find(41,41,4)>=0);
+ CHECK(!saddle.Allows(0,0)); // exact terrain-cell saddle; endpoint-only coarse check fails
+ size_t work=10000;CHECK(saddle.CoversRectangle(.9,.9,1,1,work)==WaterShoreSupport::AreaResult::Covered);
+ work=10000;CHECK(saddle.CoversRectangle(0,0,1,1,work)==WaterShoreSupport::AreaResult::Unsupported);
+ for(const auto&e:coast.Topology().Edges()){
+ const auto&ca=coast.Cells()[e.a],&cb=coast.Cells()[e.b];
+ const double ha=large.heights[size_t(ca.y)*260+ca.x],hb=large.heights[size_t(cb.y)*260+cb.x];
+ CHECK(ha<4&&hb<4&&(ha+hb)*.5<4);
+ CHECK(!(ca.x==64&&cb.x==65&&ca.y==cb.y));
+ }
+ const auto signature=WaterCoastalDomainTest::Signature(coast);Domain repeat;
+ CHECK(large.Install(repeat)==Result::Ready&&WaterCoastalDomainTest::Signature(repeat)==signature);
+ CHECK(large.Install(coast,1)==Result::Invalid&&WaterCoastalDomainTest::Signature(coast)==signature);
+
+ Map widest(130,130);widest.spacing=128;widest.level=6;widest.Full();if(!widest.Build())return;
+ widest.field.physicalShore.assign(widest.field.physicalShore.size(),1); // capacity-only armed metadata
+ CHECK(widest.Install(coast)==Result::TooManyCells&&WaterCoastalDomainTest::Signature(coast)==signature);
+
+ // Count all levels together and use one deterministic stride, preserving exact
+ // level keys rather than consuming the capacity with whichever level arrived first.
+ Map multi(130,130);Ridges(multi);multi.polygons.push_back(Map::Rect(0,0,1290,1290,5));
+ if(!multi.Build())return;WaterOpticalContext::Field upper;
+ CHECK(WaterOpticalContext::Build(multi.heights.data(),130,130,0,10,1,5,multi.polygons,upper));
+ Domain levels;CHECK(levels.Build(multi.heights.data(),130,130,0,10,1,multi.polygons,{{5,&upper},{4,&multi.field}})==Result::Ready);
+ CHECK(levels.Grid().spacing==10&&levels.Nodes().size()<65536&&WaterCoastalSurf::ValidGraph(levels.Nodes(),10));
+ const int low=levels.Topology().Find(1,1,4),high=levels.Topology().Find(1,1,5);
+ CHECK(low>=0&&high>=0&&low!=high);
+ if(low>=0&&high>=0){CHECK(levels.Nodes()[size_t(low)].context.depth==4&&levels.Nodes()[size_t(high)].context.depth==5);}
+ Domain sorted;CHECK(sorted.Build(multi.heights.data(),130,130,0,10,1,multi.polygons,{{4,&multi.field},{5,&upper}})==Result::Ready);
+ CHECK(WaterCoastalDomainTest::Signature(sorted)==WaterCoastalDomainTest::Signature(levels));
+
+ // Fine maps keep their original lattice; an entirely wet sea still has no
+ // physical coast and must not gain source nodes merely to fill the atlas.
+ Map small(11,11);Ridges(small);if(!small.Build())return;Domain fine;
+ CHECK(small.Install(fine)==Result::Ready&&fine.Grid().spacing==5);
+ Map sea(260,260);sea.level=4;sea.Full();if(!sea.Build())return;Domain empty;
+ CHECK(sea.Install(empty)==Result::Ready&&empty.Nodes().empty()&&empty.Grid().spacing==5);
+}
+}
diff --git a/GeneralsMD/Code/Tests/WaterCoastalDomainTest.h b/GeneralsMD/Code/Tests/WaterCoastalDomainTest.h
new file mode 100644
index 000000000..3351b3349
--- /dev/null
+++ b/GeneralsMD/Code/Tests/WaterCoastalDomainTest.h
@@ -0,0 +1,123 @@
+#pragma once
+// Physical-domain regressions use armed optical controls and actual map geometry.
+// Included after test_harness.h; no custom runner or process exit.
+#include "Platform/WaterCoastalDomain.h"
+namespace WaterCoastalDomainTest {
+using Domain=WaterCoastalDomain::Domain;
+using Result=WaterCoastalDomain::Result;
+namespace Opt=WaterOpticalContext;
+struct Map {
+ int width,height,border=0;double spacing=10,scale=1;float level=10;
+ std::vector<uint8_t> heights;std::vector<Opt::Polygon> polygons;Opt::Field field;
+ Map(int w,int h):width(w),height(h),heights(size_t(w)*h,0){Full();}
+ static Opt::Polygon Rect(float x0,float y0,float x1,float y1,float z){return {{{x0,y0,z},{x1,y0,z},{x1,y1,z},{x0,y1,z}}};}
+ void Full(){polygons={Rect(float(-border*spacing),float(-border*spacing),float((width-border-1)*spacing),float((height-border-1)*spacing),level)};}
+ bool Build(){const bool ok=Opt::Build(heights.data(),width,height,border,float(spacing),float(scale),level,polygons,field);CHECK(ok);return ok;}
+ Result Install(Domain&d,size_t budget=WaterCoastalDomain::MaxBuildWork)const{return d.Build(heights.data(),width,height,border,spacing,scale,polygons,{{level,&field}},budget);}
+};
+inline std::vector<double> Signature(const Domain &d){
+ std::vector<double> s{d.Grid().originX,d.Grid().originY,d.Grid().spacing,double(d.Support().TileCount()),double(d.Support().VertexCount()),double(d.Support().Work())};
+ for(const auto&c:d.Cells())s.insert(s.end(),{double(c.x),double(c.y),c.level,double(c.sourceIndex),double(c.connections)});
+ for(const auto&n:d.Nodes()){
+ for(float v:n.world)s.push_back(v);
+ const auto&c=n.context;s.insert(s.end(),{c.depth,c.distance,c.outwardX,c.outwardY,c.exposure,c.offshore,c.analyticDamping,c.spectralDamping,c.wet,c.admitted});
+ for(auto id:n.neighbour)s.push_back(id);
+ }
+ for(const auto&e:d.Topology().Edges())s.insert(s.end(),{double(e.a),double(e.b)});
+ return s;
+}
+inline void Graph(const Domain &d){
+ CHECK(WaterCoastalSurf::ValidGraph(d.Nodes(),d.Grid().spacing));
+ CHECK(d.Cells().size()==d.Nodes().size()&&d.Topology().Cells().size()==d.Nodes().size());
+ if(d.Cells().size()!=d.Nodes().size()||d.Topology().Cells().size()!=d.Nodes().size())return;
+ for(size_t i=0;i<d.Cells().size();++i){
+ const auto &c=d.Cells()[i],&sorted=d.Topology().Cells()[i];
+ CHECK(c.sourceIndex==i&&sorted.sourceIndex==i&&WaterShoreHistory::SameKey(c,sorted));
+ CHECK(i==0||WaterShoreHistory::Less(d.Cells()[i-1],c));
+ const auto &n=d.Nodes()[i];CHECK(n.context.exposure>0&&n.context.exposure<=1&&n.context.wet==1&&n.context.admitted==1);
+ CHECK(n.world[0]==float(d.Grid().originX+c.x*d.Grid().spacing)&&n.world[1]==float(d.Grid().originY+c.y*d.Grid().spacing)&&n.world[2]==float(c.level));
+ CHECK(n.context.analyticDamping==WaterSurfaceModel::TerrainDamping(n.context.depth,n.context.offshore)&&n.context.spectralDamping==WaterFftGeometry::SafeDamping(n.context.analyticDamping,n.context.depth));
+ }
+}
+
+inline void Check(){
+ Map ridge(11,11);
+ for(int y=3;y<=7;++y)for(int x=3;x<=7;++x)if(x==3||x==7||y==3||y==7)ridge.heights[size_t(y)*11+x]=12;
+ if(!ridge.Build())return;Domain kept;CHECK(ridge.Install(kept)==Result::Ready);Graph(kept);
+ const auto enclosed=WaterSurfaceModel::SampleOffshore(ridge.field.exposure.data(),11,11,3.5f,5,10);
+ const auto oceanFacing=WaterSurfaceModel::SampleOffshore(ridge.field.exposure.data(),11,11,2.5f,5,10);
+ CHECK(enclosed.height==0);
+ CHECK(oceanFacing.height>.49f&&oceanFacing.height<.51f);
+ CHECK(kept.Topology().Find(7,10,10)<0);
+ CHECK(kept.Topology().Find(5,10,10)>=0);
+ CHECK(kept.Topology().Find(4,10,10)>=0);
+ for(const auto&c:kept.Cells())CHECK(!(c.x>6&&c.x<14&&c.y>6&&c.y<14));
+ for(const auto&n:kept.Nodes())CHECK(n.context.exposure==WaterSurfaceModel::SampleOffshore(
+ ridge.field.exposure.data(),11,11,n.world[0]/10,n.world[1]/10,10).height);
+
+
+ Map gap(11,11);gap.heights[5*11+6]=12;
+ gap.polygons={Map::Rect(0,0,43,100,10),Map::Rect(44,20,76,80,10)};if(!gap.Build())return;Domain separated;
+ CHECK(gap.field.exposure[4*11+5]==0);
+ for(int y=2;y<=8;++y)for(int x=5;x<=7;++x)
+ if(gap.heights[size_t(y)*11+x]<gap.level)CHECK(gap.field.exposure[size_t(y)*11+x]==0);
+ CHECK(gap.Install(separated)==Result::Ready);Graph(separated);
+ CHECK(separated.Topology().Find(10,8,10)<0);
+ CHECK(separated.Topology().Find(8,8,10)>=0);
+ for(const auto&n:separated.Nodes())CHECK(n.world[0]<=43);
+ // The union must connect when two polygons overlap BETWEEN native samples:
+ // neither polygon alone covers the complete native edge from x=40 to x=50.
+ gap.polygons={Map::Rect(0,0,46,100,10),Map::Rect(45,20,76,80,10)};
+ if(!gap.Build())return;Domain joined;CHECK(gap.field.exposure[4*11+5]==255);
+ CHECK(gap.Install(joined)==Result::Ready);Graph(joined);
+ CHECK(joined.Topology().Find(10,8,10)>=0);
+
+
+ Map island(17,17);island.level=20;island.Full();
+ for(int y=7;y<=9;++y)for(int x=7;x<=9;++x)island.heights[size_t(y)*17+x]=24;
+ if(!island.Build())return;Domain coast;CHECK(island.Install(coast)==Result::Ready);Graph(coast);
+ CHECK(coast.Topology().Find(13,16,20)>=0);
+ CHECK(!coast.Cells().empty());
+ for(const auto&c:coast.Cells())CHECK(c.x>0&&c.y>0&&c.x<32&&c.y<32);
+
+ auto layeredPolygons=island.polygons;layeredPolygons.push_back(Map::Rect(0,0,160,160,10));Opt::Field lower;
+ CHECK(Opt::Build(island.heights.data(),17,17,0,10,1,10,layeredPolygons,lower));
+ Domain layered;CHECK(layered.Build(island.heights.data(),17,17,0,10,1,layeredPolygons,{{20,&island.field},{10,&lower}})==Result::Ready);Graph(layered);
+ CHECK(std::any_of(layered.Cells().begin(),layered.Cells().end(),[](const auto&c){return c.level==10;})&&std::any_of(layered.Cells().begin(),layered.Cells().end(),[](const auto&c){return c.level==20;}));
+
+ for(double spacing:{32.,64.,128.}){
+ Map sea(130,130);sea.level=6;sea.spacing=spacing;sea.Full();if(!sea.Build())return;
+ CHECK(std::all_of(sea.field.physicalShore.begin(),sea.field.physicalShore.end(),[](uint8_t v){return v==255;}));
+ Domain empty;CHECK(sea.Install(empty)==Result::Ready&&empty.Nodes().empty());Graph(empty);
+ }
+
+
+ // Playable boundary, not the padded terrain extent, is the exposure seed.
+ Map boundary(5,5);boundary.border=1;boundary.level=10;boundary.Full();boundary.heights.assign(25,12);
+ for(int y=1;y<=3;++y)boundary.heights[size_t(y)*5+2]=0;
+ if(!boundary.Build())return;Domain boundaryDomain;CHECK(boundary.Install(boundaryDomain)==Result::Ready);
+ CHECK(boundaryDomain.Topology().Find(4,4,10)>=0);Graph(boundaryDomain);
+ Map lastRow(5,5);lastRow.heights.assign(25,12);lastRow.heights[4*5+2]=0;if(!lastRow.Build())return;Domain lastDomain;
+ CHECK(lastRow.Install(lastDomain)==Result::Ready&&lastDomain.Topology().Find(4,7,10)>=0);Graph(lastDomain);
+ Map dryEdge(5,5);dryEdge.heights.assign(25,12);dryEdge.heights[3*5+2]=0;dryEdge.heights[4*5+2]=10;if(!dryEdge.Build())return;Domain dryDomain;
+ CHECK(dryEdge.Install(dryDomain)==Result::Ready&&dryDomain.Nodes().empty());
+
+
+ // Diagonal wet endpoints in one half-cell can still straddle a dry saddle.
+ Map saddle(3,3);saddle.level=14;saddle.Full();saddle.heights={13,17,17,17,5,5,17,5,5};if(!saddle.Build())return;Domain saddleDomain;
+ CHECK(saddle.Install(saddleDomain)==Result::Ready);
+ CHECK(saddleDomain.Topology().Find(0,0,14)>=0&&saddleDomain.Topology().Find(1,1,14)>=0);
+ auto stencil=saddleDomain.Support().At(0,0,14,1,1);CHECK(!stencil.Allows(0,0));Graph(saddleDomain);
+
+ const auto before=Signature(kept);
+ CHECK(ridge.Install(kept,1)==Result::Invalid&&Signature(kept)==before);
+ auto bad=ridge.field;bad.physicalShore.pop_back();
+ CHECK(kept.Build(ridge.heights.data(),11,11,0,10,1,ridge.polygons,{{10,&bad}})==Result::Invalid&&Signature(kept)==before);
+ std::vector<Opt::Polygon> tooMany(Opt::MaxPoints/3+1);
+ CHECK(kept.Build(ridge.heights.data(),11,11,0,10,1,tooMany,{{10,&ridge.field}})==Result::Invalid&&Signature(kept)==before);
+ CHECK(kept.Build(ridge.heights.data(),11,11,0,10,1,ridge.polygons,{{10,&ridge.field},{10,&ridge.field}})==Result::Invalid&&Signature(kept)==before);
+ Map capped(260,260);capped.level=6;capped.Full();if(!capped.Build())return;capped.field.physicalShore.assign(capped.field.physicalShore.size(),1);
+ CHECK(capped.Install(kept)==Result::TooManyCells&&Signature(kept)==before);
+
+}
+}
diff --git a/GeneralsMD/Code/Tests/WaterCoastalFootprintTest.h b/GeneralsMD/Code/Tests/WaterCoastalFootprintTest.h
new file mode 100644
index 000000000..a15a3ef39
--- /dev/null
+++ b/GeneralsMD/Code/Tests/WaterCoastalFootprintTest.h
@@ -0,0 +1,72 @@
+#pragma once
+#include "Platform/WaterCoastalView.h"
+#include "WaterCoastalDomainTest.h"
+namespace WaterCoastalFootprintTest {
+using WaterCoastalDomainTest::Map;
+using WaterCoastalDomainTest::Domain;
+using WaterCoastalDomainTest::Result;
+using WaterCoastalView::Lookup;
+using Area=WaterShoreSupport::AreaResult;
+inline double Weight(const Lookup &v){double r=0;for(float w:v.weight)r+=w;return r;}
+inline bool PointIn(const WaterOpticalContext::Polygon&p,double x,double y){
+ bool in=false;for(size_t i=0,j=p.points.size()-1;i<p.points.size();j=i++){
+ const auto&a=p.points[j],&b=p.points[i];if((a.y>y)!=(b.y>y))in=in^(x<a.x+(y-a.y)*(b.x-a.x)/(b.y-a.y));
+ }return in;
+}
+inline void Check(){
+ Map gap(11,11);gap.heights[5*11+6]=12;
+ gap.polygons={Map::Rect(0,0,43,100,10),Map::Rect(44,20,76,80,10)};
+ if(!gap.Build())return;Domain domain;CHECK(gap.Install(domain)==Result::Ready);
+ const auto point=domain.Support().At(8,8,10,.6,.2);
+ CHECK(point.Allows(0,0)&&point.Allows(0,1));
+ CHECK(domain.Topology().Find(8,8,10)>=0&&domain.Topology().Find(9,8,10)<0);
+ // The centre-only lookup at (43,41) keeps original weight .4. Linear sampling
+ // at (44.25,41) then borrows .375*.4=.15 across the gap into the rejected pool.
+ const double oldBorrow=((1-.6)*(1-.2)+(1-.6)*.2)*.375;
+ CHECK(std::abs(oldBorrow-.15)<1e-14&&gap.field.exposure[4*11+5]==0);
+ std::vector<Lookup> output;
+ CHECK(WaterCoastalView::Build(domain,{20,30,48,20,24,10},10,output));CHECK(output.size()==240);
+ if(output.size()!=240)return;
+ const size_t row=5*24;
+ CHECK(std::abs(Weight(output[row+9])-1)<1e-7); // (39,41): complete wet footprint
+ CHECK(Weight(output[row+10])==0&&Weight(output[row+11])==0&&Weight(output[row+12])==0);
+ CHECK(.375*Weight(output[row+11])+.625*Weight(output[row+12])==0);
+ unsigned retained=0;for(const auto&v:output)retained+=Weight(v)>0;CHECK(retained>20);
+ const auto &retainedLookup=output[row+9];const double fx=.8,fy=.2;
+ for(unsigned dy=0;dy<2;++dy)for(unsigned dx=0;dx<2;++dx)
+ CHECK(std::abs(retainedLookup.weight[dy*2+dx]-(dx?fx:1-fx)*(dy?fy:1-fy))<3e-8);
+
+ // A thin notch has no polygon vertex inside the queried rectangle; its corners
+ // AND centre are inside the polygon. Full segment/rectangle intersection is essential.
+ WaterOpticalContext::Polygon notch{{{0,0,10},{10,0,10},{10,10,10},{2.25f,10,10},
+ {2.25f,1,10},{2.125f,1,10},{2.125f,10,10},{0,10,10}}};
+ for(double x:{2.,3.})for(double y:{2.,4.})CHECK(PointIn(notch,x,y));CHECK(PointIn(notch,2.5,3));
+ for(const auto&p:notch.points)CHECK(!(p.x>2&&p.x<3&&p.y>2&&p.y<4));
+ WaterShoreSupport::Domain support;
+ const WaterShoreHistory::Grid grid{0,0,5};
+ const std::vector<WaterShoreHistory::Cell> cells{{0,0,10,0,0}};
+ CHECK(support.Build(grid,cells,2,2,{notch},[](double,double){return 0.f;}));
+ size_t work=10000;CHECK(support.At(0,0,10,0,0).CoversRectangle(.4,.4,.6,.8,work)==Area::Unsupported);
+ work=10000;CHECK(support.At(0,0,10,0,0).CoversRectangle(.6,.4,.8,.8,work)==Area::Covered);
+ work=10000;CHECK(support.At(0,0,11,0,0).CoversRectangle(.6,.4,.8,.8,work)==Area::Unsupported);
+ // Union-only seams are explicitly conservative: no single polygon covers this
+ // rectangle even though the union does. No accidental acceptance through parity.
+ CHECK(support.Build(grid,cells,2,2,{Map::Rect(0,0,2.5,10,10),Map::Rect(2.5,0,10,10,10)},[](double,double){return 0.f;}));
+ work=10000;CHECK(support.At(0,0,10,0,0).CoversRectangle(.4,.4,.6,.8,work)==Area::Unsupported);
+
+ Map ridge(11,11);for(int y=0;y<11;++y)ridge.heights[size_t(y)*11+5]=12;
+ if(!ridge.Build())return;Domain rd;CHECK(ridge.Install(rd)==Result::Ready);
+ CHECK(rd.Topology().Find(9,8,10)>=0&&rd.Topology().Find(11,8,10)>=0); // both centres wet
+ CHECK(WaterCoastalView::Build(rd,{40,35,20,10,2,1},10,output));CHECK(output.size()==2);
+ if(output.size()!=2)return;CHECK(Weight(output[0])==0&&Weight(output[1])==0); // dry ridge between them
+
+ Map full(11,11);for(int y=0;y<11;++y)full.heights[size_t(y)*11]=12;
+ if(!full.Build())return;Domain fd;CHECK(full.Install(fd)==Result::Ready);
+ output.assign(1,Lookup{});output[0].node[0]=17;output[0].weight[0]=.75f;
+ auto preserved=[&](){return output.size()==1&&output[0].node[0]==17&&output[0].weight[0]==.75f;};
+ CHECK(!WaterCoastalView::Build(fd,{20,20,20,20,8,8},10,output,WaterCoastalView::MaxBuildWork,0)&&preserved());
+ CHECK(!WaterCoastalView::Build(fd,{-32,-32,128,128,1,1},10,output)&&preserved()); // per-footprint tile cap
+ CHECK(WaterCoastalView::Build(fd,{20,20,20,20,8,8},10,output));CHECK(output.size()==64);
+ for(const auto&v:output)CHECK(std::abs(Weight(v)-1)<1e-7);
+}
+}
diff --git a/GeneralsMD/Code/Tests/WaterCoastalViewTest.h b/GeneralsMD/Code/Tests/WaterCoastalViewTest.h
new file mode 100644
index 000000000..904ed11b9
--- /dev/null
+++ b/GeneralsMD/Code/Tests/WaterCoastalViewTest.h
@@ -0,0 +1,139 @@
+#pragma once
+// Existing test_harness.h supplies CHECK. These fixtures use real physical domains,
+// with separate expected coordinates/weights and armed rejected contributions.
+#include "Platform/WaterCoastalView.h"
+#include "WaterCoastalDomainTest.h"
+namespace WaterCoastalViewTest {
+using WaterCoastalDomainTest::Map;
+using WaterCoastalDomainTest::Domain;
+using WaterCoastalDomainTest::Result;
+using WaterCoastalView::Mapping;
+using WaterCoastalView::Lookup;
+inline double Weight(const Lookup&v){double sum=0;for(float w:v.weight)sum+=w;return sum;}
+inline bool Same(const std::vector<Lookup>&a,const std::vector<Lookup>&b){
+ if(a.size()!=b.size())return false;
+ for(size_t i=0;i<a.size();++i)for(unsigned c=0;c<4;++c)
+ if(a[i].node[c]!=b[i].node[c]||a[i].weight[c]!=b[i].weight[c])return false;
+ return true;
+}
+inline void ConstantAndCoordinates(){
+ Map map(11,11);for(int y=0;y<11;++y)map.heights[size_t(y)*11]=12;
+ if(!map.Build())return;Domain domain;CHECK(map.Install(domain)==Result::Ready);
+ // Non-square pixel/world extents expose a transposed or half-texel-shifted chart.
+ const Mapping mapping{20,20,20,30,7,9};std::vector<Lookup> lookup;
+ CHECK(WaterCoastalView::Build(domain,mapping,10,lookup));CHECK(lookup.size()==63);
+ if(lookup.size()!=63)return;
+ for(unsigned y=0;y<9;++y)for(unsigned x=0;x<7;++x){
+ const double wx=20+(x+.5)*20/7,wy=20+(y+.5)*30/9;
+ const double gx=wx/5,gy=wy/5;const int ix=int(std::floor(gx)),iy=int(std::floor(gy));
+ const double fx=gx-ix,fy=gy-iy;const auto&v=lookup[size_t(y)*7+x];
+ CHECK(std::abs((wx-20)/20-(x+.5)/7)<1e-14);
+ CHECK(std::abs((wy-20)/30-(y+.5)/9)<1e-14);
+ double density=0,ageMoment=0;
+ for(unsigned dy=0;dy<2;++dy)for(unsigned dx=0;dx<2;++dx){
+ const unsigned c=dy*2+dx;const int id=domain.Topology().Find(ix+int(dx),iy+int(dy),10);
+ const double expected=(dx?fx:1-fx)*(dy?fy:1-fy);
+ CHECK(id>=0);CHECK(v.node[c]==(expected>0&&id>=0?unsigned(id)+1:0));
+ CHECK(std::abs(v.weight[c]-expected)<3e-8);
+ density+=v.weight[c]*3.25;ageMoment+=v.weight[c]*7.5;
+ }
+ CHECK(std::abs(Weight(v)-1)<8e-8);
+ CHECK(std::abs(density-3.25)<3e-7&&std::abs(ageMoment-7.5)<6e-7);
+ }
+}
+inline void GapAndSaddle(){
+ Map map(11,11);map.heights[5*11+6]=12;
+ map.polygons={Map::Rect(0,0,43,100,10),Map::Rect(44,20,76,80,10)};
+ if(!map.Build())return;Domain domain;CHECK(map.Install(domain)==Result::Ready);
+ CHECK(map.field.exposure[4*11+5]==0); // optical connectivity also respects the authored gap
+ CHECK(domain.Topology().Find(8,8,10)>=0&&domain.Topology().Find(9,8,10)<0);
+ std::vector<Lookup> lookup;
+ // In connected polygon: retain its original half-weight, never normalize to one.
+ CHECK(WaterCoastalView::Build(domain,{42,39.5,1,1,1,1},10,lookup));
+ CHECK(lookup.size()==1);if(lookup.size()!=1)return;
+ CHECK(lookup[0].node[0]==unsigned(domain.Topology().Find(8,8,10))+1);
+ CHECK(lookup[0].weight[0]==.5f&&Weight(lookup[0])==.5);
+ for(double ox:{43.,44.}){ // target in polygon gap, then inside disconnected pool
+ CHECK(WaterCoastalView::Build(domain,{ox,39.5,1,1,1,1},10,lookup));
+ CHECK(lookup.size()==1&&Weight(lookup[0])==0);
+ }
+ Map saddle(3,3);saddle.level=14;saddle.Full();saddle.heights={13,17,17,17,5,5,17,5,5};
+ if(!saddle.Build())return;Domain sd;CHECK(saddle.Install(sd)==Result::Ready);
+ CHECK(sd.Topology().Find(0,0,14)>=0&&sd.Topology().Find(1,1,14)>=0);
+ CHECK(!sd.Support().At(0,0,14,.9,.9).Allows(0,0)); // wet endpoints, dry interior
+ CHECK(WaterCoastalView::Build(sd,{4,4,1,1,1,1},14,lookup));
+ CHECK(lookup.size()==1);if(lookup.size()!=1)return;
+ CHECK(lookup[0].node[0]==0&&lookup[0].weight[0]==0);
+ CHECK(lookup[0].node[3]==unsigned(sd.Topology().Find(1,1,14))+1);
+ CHECK(std::abs(lookup[0].weight[3]-.81)<3e-8&&std::abs(Weight(lookup[0])-.81)<3e-8);
+}
+inline void BordersAndLevels(){
+ Map map(11,11);map.border=2;map.Full();map.heights[5*11+2]=12;
+ if(!map.Build())return;Domain domain;CHECK(map.Install(domain)==Result::Ready);
+ CHECK(domain.Grid().originX==-20&&domain.Grid().originY==-20);
+ std::vector<Lookup> lookup;
+ CHECK(WaterCoastalView::Build(domain,{-20,0,10,10,4,4},10,lookup));CHECK(lookup.size()==16);
+ if(lookup.size()!=16)return;
+ for(unsigned y=0;y<4;++y)for(unsigned x=0;x<4;++x){
+ const double gx=(x+.5)*.5,gy=4+(y+.5)*.5;
+ const int ix=int(std::floor(gx)),iy=int(std::floor(gy));const auto&v=lookup[size_t(y)*4+x];
+ CHECK(std::abs(Weight(v)-1)<8e-8);
+ CHECK(v.node[0]==unsigned(domain.Topology().Find(ix,iy,10))+1);
+ }
+ CHECK(WaterCoastalView::Build(domain,{-30,0,10,10,2,2},10,lookup));
+ CHECK(lookup.size()==4);for(const auto&v:lookup)CHECK(Weight(v)==0); // no edge clamp
+ CHECK(WaterCoastalView::Build(domain,{1099511627776.,0,64,64,2,2},10,lookup));
+ for(const auto&v:lookup)CHECK(Weight(v)==0); // valid float chart, out of int32 lattice
+
+ Map levels(11,11);for(int y=0;y<11;++y)levels.heights[size_t(y)*11+3]=12;
+ levels.heights[5*11+8]=20;levels.polygons.push_back(Map::Rect(0,0,100,100,14));
+ if(!levels.Build())return;WaterOpticalContext::Field upper;
+ CHECK(WaterOpticalContext::Build(levels.heights.data(),11,11,0,10,1,14,levels.polygons,upper));
+ Domain layered;CHECK(layered.Build(levels.heights.data(),11,11,0,10,1,levels.polygons,{{14,&upper},{10,&levels.field}})==Result::Ready);
+ const int lowerId=layered.Topology().Find(5,8,10),upperId=layered.Topology().Find(5,8,14);
+ CHECK(lowerId>=0&&upperId>=0&&lowerId!=upperId);
+ const Mapping centred{24.5,39.5,1,1,1,1};
+ for(double level:{10.,14.}){
+ CHECK(WaterCoastalView::Build(layered,centred,level,lookup));CHECK(lookup.size()==1);
+ if(lookup.size()!=1)return;
+ CHECK(lookup[0].node[0]==unsigned(level==10?lowerId:upperId)+1&&lookup[0].weight[0]==1);
+ CHECK(Weight(lookup[0])==1);
+ }
+ CHECK(WaterCoastalView::Build(layered,centred,11,lookup));CHECK(lookup.size()==1&&Weight(lookup[0])==0);
+}
+inline void BoundsAndAtomicity(){
+ Domain empty;const Mapping good{0,0,64,64,1,1};
+ std::vector<Lookup> output(2);output[0].node[0]=17;output[0].weight[0]=.75f;output[1].node[3]=29;output[1].weight[3]=.25f;
+ const auto original=output;
+ CHECK(WaterCoastalView::SameMapping(good,good));
+ for(unsigned field=0;field<6;++field){Mapping changed=good;
+ if(field==0)changed.originX=1;if(field==1)changed.originY=1;if(field==2)changed.widthWorld=32;
+ if(field==3)changed.heightWorld=32;if(field==4)changed.widthPixels=2;if(field==5)changed.heightPixels=2;
+ CHECK(!WaterCoastalView::SameMapping(good,changed));
+ }
+ for(unsigned kind=0;kind<11;++kind){Mapping bad=good;
+ if(kind==0)bad.widthPixels=0;if(kind==1)bad.heightPixels=0;
+ if(kind==2)bad.widthPixels=513;if(kind==3)bad.heightPixels=513;
+ if(kind==4)bad.widthWorld=0;if(kind==5)bad.heightWorld=-1;
+ if(kind==6)bad.originX=std::numeric_limits<double>::quiet_NaN();
+ if(kind==7)bad.originY=.1; // cannot represent exact shader metadata
+ if(kind==8)bad.widthWorld=double((std::numeric_limits<float>::denorm_min)());
+ if(kind==9){bad.originX=double((std::numeric_limits<float>::max)());bad.widthWorld=bad.originX;}
+ if(kind==10)bad.heightWorld=std::numeric_limits<double>::infinity();
+ CHECK(!WaterCoastalView::ValidMapping(bad));
+ CHECK(!WaterCoastalView::Build(empty,bad,10,output)&&Same(output,original));
+ }
+ for(double badLevel:{.1,std::numeric_limits<double>::quiet_NaN(),std::numeric_limits<double>::infinity()})
+ CHECK(!WaterCoastalView::Build(empty,good,badLevel,output)&&Same(output,original));
+ CHECK(!WaterCoastalView::Build(empty,good,10,output,WaterCoastalView::WorkPerPixel-1)&&Same(output,original));
+ CHECK(WaterCoastalView::Build(empty,good,10,output,WaterCoastalView::WorkPerPixel));
+ CHECK(output.size()==1&&Weight(output[0])==0);
+ const Mapping largest{-256,-256,512,512,512,512};
+ const auto one=output;
+ CHECK(!WaterCoastalView::Build(empty,largest,10,output,WaterCoastalView::MaxBuildWork-1)&&Same(output,one));
+ CHECK(WaterCoastalView::Build(empty,largest,10,output));CHECK(output.size()==512u*512u);
+ bool allZero=true;for(const auto&v:output)for(unsigned c=0;c<4;++c)allZero=allZero&&v.node[c]==0&&v.weight[c]==0;
+ CHECK(allZero);
+}
+inline void Check(){ConstantAndCoordinates();GapAndSaddle();BordersAndLevels();BoundsAndAtomicity();}
+}
diff --git a/GeneralsMD/Code/Tests/WaterHullContactFoamTest.h b/GeneralsMD/Code/Tests/WaterHullContactFoamTest.h
new file mode 100644
index 000000000..4a3f7112f
--- /dev/null
+++ b/GeneralsMD/Code/Tests/WaterHullContactFoamTest.h
@@ -0,0 +1,100 @@
+#pragma once
+#include "Platform/WaterHullContactFoam.h"
+#include <limits>
+
+namespace WaterHullContactFoamTest {
+// Independent double scalar integrand. The production primitive is never used here.
+inline double Profile(double x) {
+ x=std::abs(x);
+ if(x<=.5)return 1;
+ if(x>=1.5)return 0;
+ const double u=(1.5-x);
+ return u*u*(3-2*u);
+}
+inline double Band(double distance,double footprint) {
+ const double half=(std::max)(.125,(std::min)(1.5,footprint*.5));
+ // Simpson quadrature with exact interval cuts at every polynomial break. Integration
+ // of each cubic piece is exact in real arithmetic and independent of its primitive.
+ double cuts[6]={distance-half,distance+half,-1.5,-.5,.5,1.5};
+ std::sort(cuts,cuts+6);double result=0;
+ for(unsigned i=0;i<5;++i) {
+ const double a=(std::max)(cuts[i],distance-half),b=(std::min)(cuts[i+1],distance+half);
+ if(b>a)result+=(b-a)*(Profile(a)+4*Profile((a+b)*.5)+Profile(b))/6;
+ }
+ return result/(2*half);
+}
+inline double Response(double height,double slope) {
+ if(!std::isfinite(height)||!std::isfinite(slope)||slope<0)return 0;
+ // Spectral energy normalization is evaluated in double, independently from the
+ // production float control flow. The reference scale is intentionally float-rounded.
+ const double H=double(WaterHullContactFoam::HeightScale),S=double(WaterHullContactFoam::SlopeScale);
+ const double phase=(std::max)(0.,(std::min)(1.,1+height/H));
+ const double crest=(std::max)(height,0.),energy=crest*crest/(H*H)+slope*slope/(S*S);
+ return (3*phase*phase-2*phase*phase*phase)*energy/(1+energy);
+}
+}
+
+TEST(water_hull_contact_foam_calm_bounds_phase_and_filtered_width)
+{
+ namespace C=WaterHullContactFoam;namespace T=WaterHullContactFoamTest;
+ double largestError=0;
+ for(float h:{-12.f,-C::HeightScale,-1.f,-.01f,0.f,.01f,.4f,C::HeightScale,4.f,12.f})
+ for(float slope:{0.f,.0001f,.01f,.04f,C::SlopeScale,.15f,.4f,2.f}) {
+ const float response=C::Response(h,slope);
+ CHECK(std::isfinite(response)&&response>=0&&response<=1);
+ CHECK_NEAR(response,T::Response(h,slope),.0000003);
+ for(float fp:{0.f,.1f,.25f,1.f,2.f,3.f,6.f,30.f})for(unsigned j=0;j<=100;++j) {
+ const float d=j*.03125f;const float band=C::Band(d,fp),coverage=C::Coverage(d,fp,h,slope);
+ largestError=(std::max)(largestError,std::abs(double(band)-T::Band(d,fp)));
+ CHECK(std::isfinite(band)&&band>=0&&band<=1&&coverage>=0&&coverage<=response);
+ CHECK_NEAR(band,T::Band(d,fp),.0000015);
+ if(d>=3)CHECK(coverage==0);
+ }
+ }
+ for(float fp:{0.f,.25f,1.f,2.f,3.f,100.f}) {
+ double area=0;const double step=6./6000;
+ for(unsigned j=0;j<6000;++j)area+=C::Band(float(std::abs(-3+(j+.5)*step)),fp)*step;
+ CHECK_NEAR(area,2.,.000006); // armed against broadening a full-strength rim with AA
+ CHECK(C::Coverage(0,fp,0,0)==0);
+ CHECK(C::Coverage(3,fp,12,2)==0);
+ }
+ CHECK_NEAR(C::Response(C::HeightScale,0),.5,.0000002); // crest survives zero slope
+ CHECK_NEAR(C::Response(0,C::SlopeScale),.5,.0000002);
+ CHECK(C::Response(-C::HeightScale,.4f)==0); // trough is not a perpetual contact band
+ CHECK(C::Coverage(1,1,C::HeightScale,0)>.24f);
+ CHECK(C::Coverage(1,1,0,C::SlopeScale)>.24f);
+ for(float beam:{0.f,4.f,8.f,16.f,32.f,54.f,1000.f}) {
+ const double scale=1+3*(std::sqrt((std::max)(1.,(std::min)(4.,double(beam)/8.)))-1);
+ for(float fp:{0.f,1.f,4.f,100.f})for(unsigned i=0;i<=192;++i) {
+ const float d=i*.0625f;
+ CHECK_NEAR(C::Coverage(d,fp,C::HeightScale,0,beam),
+ .5*T::Band(d/scale,fp/scale),.0000015);
+ if(d>=12)CHECK(C::Coverage(d,fp,12,.4f,beam)==0);
+ if(beam<=8)CHECK(C::Coverage(d,fp,1,.1f,beam)==C::Coverage(d,fp,1,.1f));
+ }
+ }
+ // Old slope-product gate drops the crest case entirely. This is a changed source,
+ // not increased material brightness or widened noise; retain the nonvacuous control.
+ const auto old=[](float h,float s){auto ramp=[](float a,float b,float x){float t=(std::max)(0.f,(std::min)(1.f,(x-a)/(b-a)));return t*t*(3-2*t);};return ramp(.04f,.4f,s)*ramp(-.8f,1.6f,h);};
+ CHECK(old(C::HeightScale,0)==0&&C::Response(C::HeightScale,0)>.49f);
+ CHECK(C::Coverage(1,1,0,C::SlopeScale)>old(0,C::SlopeScale)*.58f*8);
+ for(float invalid:{std::numeric_limits<float>::quiet_NaN(),std::numeric_limits<float>::infinity()}) {
+ CHECK(C::Response(invalid,.1f)==0&&C::Response(1,invalid)==0);
+ CHECK(C::Band(invalid,1)==0&&C::Band(1,invalid)==0);
+ }
+ CHECK(C::Band(-1,1)==0&&C::Band(1,-1)==0&&C::Response(1,-1)==0);
+ const float huge=(std::numeric_limits<float>::max)();
+ CHECK(C::Response(huge,huge)==1&&C::Band(huge,huge)==0);
+ // A travelling broad/medium-size sinusoid must have calm/trough zero intervals and
+ // crest response, not a permanent rim. Repeated frozen inputs are bit-identical.
+ unsigned active=0,empty=0;float previous=0;double largestStep=0;
+ for(unsigned i=0;i<=4096;++i) {
+ const double phase=6.283185307179586*i/4096;
+ const float h=C::HeightScale*float(std::sin(phase)),s=C::SlopeScale*float(std::abs(std::cos(phase)));
+ const float a=C::Coverage(1,1,h,s),b=C::Coverage(1,1,h,s);
+ CHECK(a==b);active+=a>.2f;empty+=a<.00001f;
+ if(i)largestStep=(std::max)(largestStep,std::abs(double(a)-previous));previous=a;
+ }
+ CHECK(active>1000&&empty>50&&largestStep<.002);
+ printf("water hull contact: independent filtered strip maximum error %.9g, phase step %.9g\n",largestError,largestStep);
+}
diff --git a/GeneralsMD/Code/Tests/WaterTerrainCullingTest.h b/GeneralsMD/Code/Tests/WaterTerrainCullingTest.h
new file mode 100644
index 000000000..25f9a8551
--- /dev/null
+++ b/GeneralsMD/Code/Tests/WaterTerrainCullingTest.h
@@ -0,0 +1,173 @@
+#pragma once
+
+#include "Platform/WaterTerrainCulling.h"
+#include <limits>
+
+namespace WaterTerrainCullingTest
+{
+using WaterProjectedMesh::Mesh;
+using WaterProjectedMesh::Point;
+
+inline Mesh Triangle(Point a, Point b, Point c)
+{
+ Mesh mesh;
+ for (Point point : {a, b, c})
+ {
+ WaterProjectedMesh::Vertex vertex;
+ vertex.world = point;
+ mesh.vertices.push_back(vertex);
+ }
+ mesh.indices = {0, 1, 2};
+ return mesh;
+}
+
+inline bool Cull(Mesh &mesh, const std::vector<uint8_t> &heights,
+ double vertical = 0, double horizontal = 0)
+{
+ return WaterTerrainCulling::CullDryTriangles(
+ mesh, heights.data(), 9, 9, 0, 1, 1, 10, vertical, horizontal);
+}
+
+inline void Check()
+{
+ std::vector<uint8_t> heights(81, 30);
+ const auto original = Triangle({1.2, 1.2}, {6.8, 1.2}, {1.2, 6.8});
+ auto dry = original;
+ CHECK(Cull(dry, heights));
+ CHECK(dry.indices.empty() && dry.vertices.empty());
+
+ // Every triangle endpoint is high; the interior grid corner contains a small pond.
+ heights[3 * 9 + 3] = 0;
+ auto pond = original;
+ CHECK(Cull(pond, heights));
+ CHECK(pond.indices == original.indices && pond.vertices.size() == 3);
+
+ // A wet corner outside the triangle but inside a crossed terrain cell must also retain it.
+ heights.assign(81, 30);
+ heights[2 * 9 + 2] = 0;
+ auto cell = Triangle({2.2, 2.2}, {2.8, 2.2}, {2.2, 2.8});
+ CHECK(Cull(cell, heights));
+ CHECK(cell.indices.size() == 3);
+
+ heights.assign(81, 30);
+ heights[2 * 9 + 4] = 0;
+ const auto shifted = Triangle({2.2, 2.2}, {2.8, 2.2}, {2.2, 2.8});
+ auto still = shifted;
+ CHECK(Cull(still, heights));
+ CHECK(still.indices.empty());
+
+ auto displaced = shifted;
+ CHECK(Cull(displaced, heights, 0, 1));
+ CHECK(displaced.indices.size() == 3);
+
+ heights.assign(81, 11);
+ auto crest = shifted;
+ CHECK(Cull(crest, heights, 1));
+ CHECK(crest.indices.size() == 3);
+
+ auto below = shifted;
+ CHECK(Cull(below, heights, .5));
+ CHECK(below.indices.empty());
+
+ heights.assign(81, 30);
+ auto outside = Triangle({-2, 2}, {-1, 2}, {-2, 3});
+ CHECK(Cull(outside, heights));
+ CHECK(outside.indices.size() == 3); // no assumption about terrain beyond the map
+
+ // Remove an unused vertex and a buried triangle while preserving winding and metadata.
+ Mesh mixed = original;
+ for (const auto &vertex : shifted.vertices)
+ mixed.vertices.push_back(vertex);
+ mixed.indices = {3, 5, 4, 0, 1, 2};
+ heights[2 * 9 + 2] = 0;
+
+ // Move the first triangle into a separate dry region.
+ mixed.vertices[0].world = {5.1, 5.1};
+ mixed.vertices[1].world = {6.1, 5.1};
+ mixed.vertices[2].world = {5.1, 6.1};
+ mixed.vertices[3].boundary = 2;
+ mixed.vertices[3].knot = 7;
+ mixed.vertices[3].edgeParameter = .25;
+ mixed.vertices[4].collar = 0;
+ mixed.vertices[5].transition = 0;
+ mixed.vertices[5].lattice = 42;
+ mixed.collars.resize(1);
+ mixed.collars[0].fade = .5;
+ mixed.transitions.resize(1);
+ mixed.transitions[0].analytic = .75;
+ mixed.cells = 12;
+ mixed.vertices.push_back(mixed.vertices[0]);
+ CHECK(Cull(mixed, heights));
+ CHECK(mixed.vertices.size() == 3 && mixed.indices == std::vector<uint16_t>({0, 2, 1}));
+ CHECK(mixed.vertices[0].boundary == 2 && mixed.vertices[0].knot == 7 &&
+ mixed.vertices[0].edgeParameter == .25);
+ CHECK(mixed.vertices[1].collar == 0 && mixed.vertices[2].transition == 0 &&
+ mixed.vertices[2].lattice == 42);
+ CHECK(mixed.collars.size() == 1 && mixed.collars[0].fade == .5 &&
+ mixed.transitions.size() == 1 && mixed.transitions[0].analytic == .75 &&
+ mixed.cells == 12);
+
+ mixed.vertices.push_back(mixed.vertices[0]);
+ CHECK(WaterTerrainCulling::CompactVertices(mixed));
+ CHECK(mixed.vertices.size() == 3);
+
+ // A single bad later triangle cannot commit removal of an earlier valid triangle.
+ auto invalid = original;
+ invalid.indices.insert(invalid.indices.end(), {0, 1, 99});
+ const auto badIndices = invalid.indices;
+ CHECK(!Cull(invalid, heights));
+ CHECK(invalid.indices == badIndices && invalid.vertices.size() == 3);
+ CHECK(!WaterTerrainCulling::CompactVertices(invalid));
+ CHECK(invalid.indices == badIndices);
+
+ invalid = original;
+ invalid.vertices[2].world.x = std::numeric_limits<double>::quiet_NaN();
+ CHECK(!Cull(invalid, heights));
+ CHECK(invalid.indices == original.indices && invalid.vertices.size() == 3);
+
+ invalid = original;
+ CHECK(!Cull(invalid, heights, -1));
+ CHECK(invalid.indices == original.indices);
+ CHECK(!WaterTerrainCulling::CullDryTriangles(invalid, nullptr, 9, 9, 0, 1, 1, 10, 0, 0));
+ CHECK(!WaterTerrainCulling::CullDryTriangles(
+ invalid, heights.data(), 9, 9, 0, 0, 1, 10, 0, 0));
+ CHECK(!WaterTerrainCulling::CullDryTriangles(
+ invalid, heights.data(), 9, 9, 5, 1, 1, 10, 0, 0));
+ CHECK(invalid.indices == original.indices && invalid.vertices.size() == 3);
+
+ // Very broad triangles retain their original coverage when a bounded query declines them.
+ std::vector<uint8_t> large(65 * 65, 30);
+ auto broad = Triangle({1, 1}, {63, 1}, {1, 63});
+ CHECK(WaterTerrainCulling::CullDryTriangles(
+ broad, large.data(), 65, 65, 0, 1, 1, 10, 0, 0));
+ CHECK(broad.indices.size() == 3);
+
+ // Map border offset, terrain spacing and encoded height scale participate in the proof.
+ auto scaled = Triangle({-.4, -.4}, {.4, -.4}, {-.4, .4});
+ CHECK(WaterTerrainCulling::CullDryTriangles(
+ scaled, heights.data(), 9, 9, 2, 2, 2, 40, 0, 0));
+ CHECK(scaled.indices.size() == 3); // low sample at encoded (2,2), world (0,0)
+
+ // A camera above a bilinear saddle can still be below one terrain triangulation.
+ heights.assign(81, 0);
+ heights[2 * 9 + 3] = 20;
+ heights[3 * 9 + 2] = 20;
+ CHECK(!WaterTerrainCulling::CameraAboveTerrain(
+ heights.data(), 9, 9, 0, 1, 1, 2.5, 2.5, 15));
+ CHECK(!WaterTerrainCulling::CameraAboveTerrain(
+ heights.data(), 9, 9, 0, 1, 1, 2.5, 2.5, 20));
+ CHECK(WaterTerrainCulling::CameraAboveTerrain(
+ heights.data(), 9, 9, 0, 1, 1, 2.5, 2.5, 21));
+ CHECK(!WaterTerrainCulling::CameraAboveTerrain(
+ heights.data(), 9, 9, 0, 1, 1, -.1, 2.5, 30));
+ CHECK(!WaterTerrainCulling::CameraAboveTerrain(
+ heights.data(), 9, 9, 0, 1, 1, 8.1, 2.5, 30));
+ CHECK(!WaterTerrainCulling::CameraAboveTerrain(
+ heights.data(), 9, 9, 0, 1, 1, 2.5, 2.5, std::numeric_limits<double>::quiet_NaN()));
+ CHECK(!WaterTerrainCulling::CameraAboveTerrain(nullptr, 9, 9, 0, 1, 1, 2.5, 2.5, 30));
+ CHECK(!WaterTerrainCulling::CameraAboveTerrain(
+ heights.data(), 9, 9, 0, 0, 1, 2.5, 2.5, 30));
+ CHECK(WaterTerrainCulling::CameraAboveTerrain(
+ heights.data(), 9, 9, 2, 2, 2, 1, 1, 41));
+}
+}
diff --git a/GeneralsMD/Code/Tests/WaterWaveCageTest.h b/GeneralsMD/Code/Tests/WaterWaveCageTest.h
new file mode 100644
index 000000000..797ace0fc
--- /dev/null
+++ b/GeneralsMD/Code/Tests/WaterWaveCageTest.h
@@ -0,0 +1,148 @@
+#pragma once
+#include "Platform/WaterWaveCage.h"
+#include "Platform/WaterWaveCageMesh.h"
+#include <limits>
+
+namespace WaterWaveCageTest {
+namespace Cage=WaterWaveCage;
+namespace Opt=WaterOpticalContext;
+struct Fixture {
+ int width,height,border=0;float spacing=2,scale=1,level=48;
+ std::vector<uint8_t> heights;Opt::Field shore;Cage::Field field;
+ Fixture(int w,int h):width(w),height(h),heights(size_t(w)*h,0){}
+ bool Build(){
+ const float x0=-border*spacing,y0=-border*spacing;
+ const float x1=(width-border-1)*spacing,y1=(height-border-1)*spacing;
+ const std::vector<Opt::Polygon> polygons={{{{x0,y0,level},{x1,y0,level},{x1,y1,level},{x0,y1,level}}}};
+ const bool optical=Opt::Build(heights.data(),width,height,border,spacing,scale,level,polygons,shore);
+ CHECK(optical);if(!optical)return false;
+ const bool cage=Cage::Build(heights.data(),width,height,border,spacing,scale,level,shore,field);CHECK(cage);return cage;
+ }
+ Cage::TerrainSample Sample(float x,float y)const{return Cage::SampleTerrain(heights.data(),width,height,border,spacing,scale,x,y);}
+};
+inline float Length(Cage::Vec3 a){return std::sqrt(Cage::Dot(a,a));}
+inline void CheckMap(){
+ using namespace Cage;
+ const Vec3 n=Unit({1,2,3});
+ for(float amplitude:{.000001f,.1f,2.f,10.f,10000.f})for(Vec3 direction:{Vec3{1,0,0},Vec3{0,1,0},Vec3{0,0,1},Unit({1,-2,3})}){
+ const Vec3 eta{direction.x*amplitude,direction.y*amplitude,direction.z*amplitude};
+ const Vec3 a=Map(eta,n,MaxRadius,.3f),b=Map({-eta.x,-eta.y,-eta.z},n,MaxRadius,.3f);
+ CHECK(std::abs(a.x+b.x)<1e-6f&&std::abs(a.y+b.y)<1e-6f&&std::abs(a.z+b.z)<1e-6f);
+ CHECK(Length(a)<=MaxRadius+1e-5f);
+ CHECK(std::abs(Dot(n,a))<=.30001f);
+ }
+ const auto zero=Map({},n,MaxRadius,MaxRadius);CHECK(Length(zero)==0);
+ const auto tiny=Map({1e-5f,0,0},{0,0,1},MaxRadius,MaxRadius);CHECK(std::abs(tiny.x-1e-5f)<1e-10f);
+ const auto finite=Map({std::numeric_limits<float>::max(),0,0},{0,0,1},MaxRadius,MaxRadius);
+ CHECK(std::isfinite(finite.x)&&finite.x<=MaxRadius);
+ CHECK(Length(Map({1,2,3},n,0,0))==0);
+ CHECK(Length(Map({std::numeric_limits<float>::infinity(),0,0},n,MaxRadius,MaxRadius))==0);
+}
+inline void CheckSlope(){
+ Fixture slope(33,17);
+ for(int y=0;y<slope.height;++y)for(int x=0;x<slope.width;++x)slope.heights[size_t(y)*slope.width+x]=uint8_t(64-x);
+ if(!slope.Build())return;
+ const auto terrain=slope.Sample(32,16);const auto expected=Cage::Unit({.5f,0,1});
+ CHECK(terrain.height==48&&std::abs(terrain.normal.x-expected.x)<1e-6f&&std::abs(terrain.normal.z-expected.z)<1e-6f);
+ const auto fractional=slope.Sample(33,15);CHECK(std::abs(fractional.height-47.5f)<1e-6f);
+ const size_t line=8*slope.width+16;
+ CHECK(slope.field.support[line]==1&&slope.field.normal[line]==0&&slope.field.tangent[line]>1);
+ const auto slide=Cage::Map({0,0,3},terrain.normal,slope.field.tangent[line],0);
+ CHECK(std::abs(slide.x)>.1f&&std::abs(slide.z)>.1f&&std::abs(Cage::Dot(slide,terrain.normal))<1e-6f);
+ // This planar terrain has an independent analytic collision oracle. Check
+ // the entire phase orbit on both sides, including the actual waterline.
+ for(int x=14;x<=22;++x){
+ const size_t i=8*slope.width+x;const auto sample=slope.Sample(x*slope.spacing,16);
+ CHECK(slope.field.support[i]>0||x<16);
+ if(slope.field.support[i]==0)continue;
+ const auto raw=Cage::Fit(slope.heights.data(),slope.width,slope.height,0,2,1,48,x*2.f,16,sample);
+ CHECK(slope.field.tangent[i]<=raw.tangent+1e-6f&&slope.field.normal[i]<=raw.normal+1e-6f);
+ for(int phase=0;phase<128;++phase){
+ const float angle=phase*6.28318530718f/128;
+ const auto displacement=Cage::Map({4*std::sin(angle),std::cos(angle*3),4*std::cos(angle)},sample.normal,
+ slope.field.tangent[i],slope.field.normal[i]);
+ const float floor=64-(x*2+displacement.x)*.5f;
+ const float clearance=48+displacement.z-floor;
+ CHECK(x>=16?clearance>=-1e-5f:clearance<=1e-5f);
+ CHECK(Length(displacement)<=Cage::MaxRadius+1e-5f);
+ }
+ }
+ bool smoothed=false;
+ for(int x=17;x<=24;++x){
+ const size_t i=8*slope.width+x;if(slope.field.support[i]==0)continue;
+ const auto raw=Cage::Fit(slope.heights.data(),slope.width,slope.height,0,2,1,48,x*2.f,16,slope.Sample(x*2.f,16));
+ smoothed=smoothed||slope.field.normal[i]<raw.normal-.0001f||slope.field.tangent[i]<raw.tangent-.0001f;
+ }
+ CHECK(smoothed);
+ for(size_t i=0;i<slope.heights.size();++i){
+ const auto texel=Cage::Texel(slope.field,i);
+ CHECK(((texel>>16)&255)==slope.heights[i]);
+ CHECK(float((texel>>8)&255)*Cage::MaxRadius/255<=slope.field.tangent[i]+1e-6f);
+ CHECK(float(texel&255)*Cage::MaxRadius/255<=slope.field.normal[i]+1e-6f);
+ CHECK(std::abs(float(texel>>24)/255-slope.field.support[i])<=.5f/255+1e-6f);
+ CHECK(slope.field.tangent[i]>=0&&slope.field.tangent[i]<=Cage::MaxRadius);
+ CHECK(slope.field.normal[i]>=0&&slope.field.normal[i]<=Cage::MaxRadius);
+ }
+ // At sub-grid waterline samples, interpolated radii alone need not vanish.
+ // The runtime plane-clearance cap restores the exact rn=0 constraint.
+ const float capped=(std::min)(1.0f,std::abs(48-terrain.height)*terrain.normal.z);CHECK(capped==0);
+}
+inline void CheckClassification(){
+ Fixture sea(17,17);sea.level=10;if(!sea.Build())return;
+ CHECK(std::all_of(sea.field.support.begin(),sea.field.support.end(),[](float value){return value==0;}));
+ CHECK(std::all_of(sea.field.tangent.begin(),sea.field.tangent.end(),[](float value){return value==Cage::MaxRadius;}));
+ Fixture pool(17,17);pool.level=10;
+ for(int y=4;y<=12;++y)for(int x=4;x<=12;++x)if(x==4||x==12||y==4||y==12)pool.heights[size_t(y)*17+x]=12;
+ if(!pool.Build())return;
+ CHECK(pool.shore.exposure[8*17+8]==0&&pool.field.support[8*17+8]==0);
+ CHECK(pool.shore.exposure[8*17+3]==255&&pool.field.support[8*17+3]>0);
+ CHECK(pool.field.support[8*17+4]==0); // guarded dry ridge between ocean and pool
+ // Failed inputs cannot leave a partially usable packed texture behind.
+ Cage::Field bad;auto broken=sea.shore;broken.exposure.pop_back();
+ CHECK(!Cage::Build(sea.heights.data(),17,17,0,2,1,10,broken,bad)&&bad.texels.empty());
+ CHECK(!Cage::Build(nullptr,17,17,0,2,1,10,sea.shore,bad));
+ CHECK(!Cage::Build(sea.heights.data(),17,17,-1,2,1,10,sea.shore,bad));
+ CHECK(!Cage::Build(sea.heights.data(),17,17,0,0,1,10,sea.shore,bad));
+ CHECK(!Cage::Build(sea.heights.data(),17,17,0,2,1,std::numeric_limits<float>::quiet_NaN(),sea.shore,bad));
+}
+inline WaterProjectedMesh::Mesh Quad(){
+ WaterProjectedMesh::Mesh mesh;
+ for(auto p:{WaterProjectedMesh::Point{0,0},WaterProjectedMesh::Point{2,0},WaterProjectedMesh::Point{2,2},WaterProjectedMesh::Point{0,2}}){
+ WaterProjectedMesh::Vertex vertex;vertex.world=p;mesh.vertices.push_back(vertex);
+ }
+ mesh.indices={0,1,2,0,2,3};return mesh;
+}
+inline void CheckMesh(){
+ using WaterWaveCageMesh::ClipRestWaterline;using Point=WaterProjectedMesh::Point;
+ const auto depth=[](Point p){return p.x-1;};const auto eligible=[](Point){return true;};
+ auto mesh=Quad();CHECK(ClipRestWaterline(mesh,depth,eligible));
+ CHECK(mesh.vertices.size()==7&&mesh.indices.size()==9);
+ int shared=-1,sharedCount=0;
+ for(size_t i=0;i<mesh.vertices.size();++i){
+ const auto&p=mesh.vertices[i].world;
+ if(std::abs(p.x-1)<1e-8&&std::abs(p.y-1)<1e-8){shared=int(i);++sharedCount;}
+ }
+ CHECK(sharedCount==1);unsigned diagonalUses=0;
+ for(size_t t=0;t<mesh.indices.size();t+=3)for(int c=0;c<3;++c){
+ const auto a=mesh.indices[t+c],b=mesh.indices[t+(c+1)%3];
+ CHECK(depth(mesh.vertices[a].world)>=0);
+ if((a==shared&&b==2)||(a==2&&b==shared))++diagonalUses;
+ }
+ CHECK(diagonalUses==2); // both owners use the same waterline intersection
+ auto protectedMesh=Quad();protectedMesh.vertices[3].boundary=0;
+ CHECK(ClipRestWaterline(protectedMesh,depth,eligible));
+ CHECK(protectedMesh.vertices.size()==4&&protectedMesh.indices==Quad().indices);
+ auto protectedCollar=Quad();protectedCollar.vertices[3].collar=0;
+ CHECK(ClipRestWaterline(protectedCollar,depth,eligible)&&protectedCollar.vertices.size()==4);
+ auto protectedTransition=Quad();protectedTransition.vertices[3].transition=0;
+ CHECK(ClipRestWaterline(protectedTransition,depth,eligible)&&protectedTransition.vertices.size()==4);
+ auto budget=Quad();CHECK(!ClipRestWaterline(budget,depth,eligible,5));
+ CHECK(budget.vertices.size()==4&&budget.indices==Quad().indices); // rollback after a partial candidate split
+ auto invalid=Quad();CHECK(!ClipRestWaterline(invalid,[](Point){return std::numeric_limits<double>::quiet_NaN();},eligible));
+ CHECK(invalid.vertices.size()==4&&invalid.indices==Quad().indices);
+ auto dry=Quad();CHECK(ClipRestWaterline(dry,[](Point){return -1.;},eligible)&&dry.indices.empty());
+ auto curved=Quad();CHECK(ClipRestWaterline(curved,[](Point p){return p.x*p.x-.9;},eligible));
+ for(size_t i=4;i<curved.vertices.size();++i)CHECK(std::abs(curved.vertices[i].world.x-std::sqrt(.9))<4e-5);
+}
+inline void Check(){CheckMap();CheckSlope();CheckClassification();CheckMesh();}
+}
diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cpp
index 6c545abe9..2dec31e77 100644
--- a/GeneralsMD/Code/Tests/test_gameengine.cpp
+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp
@@ -15127,6 +15127,32 @@ TEST(order_lines_are_a_live_check_box_that_starts_on)
TheWritableGlobalData = saved;
}
+TEST(water_style_defaults_to_modern_and_preserves_an_explicit_classic_choice)
+{
+ GlobalData *saved=TheWritableGlobalData;
+ GlobalData *scratch=NEW GlobalData;
+ TheWritableGlobalData=scratch;
+ const OptionDef *water=findOptionDef("WaterStyle");
+ CHECK(water!=NULL);
+ if (water) {
+ UserPreferences pref;
+ CHECK_EQ(scratch->m_waterStyle,1);
+ loadOptionsFromPreferences(pref);
+ CHECK_EQ(water->get(),1);
+ pref["WaterStyle"]="0";
+ loadOptionsFromPreferences(pref);
+ CHECK_EQ(water->get(),0);
+ saveOptionsToPreferences(pref);
+ CHECK_STR(pref["WaterStyle"].str(),"0");
+ pref["WaterStyle"]="1";
+ loadOptionsFromPreferences(pref);
+ CHECK_EQ(water->get(),1);
+ CHECK_EQ(water->apply,APPLY_LIVE);
+ }
+ 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_map_ini_rollback.inc b/GeneralsMD/Code/Tests/test_map_ini_rollback.inc
index 2679bbaf8..4ac968215 100644
--- a/GeneralsMD/Code/Tests/test_map_ini_rollback.inc
+++ b/GeneralsMD/Code/Tests/test_map_ini_rollback.inc
@@ -7,6 +7,7 @@
#include "Common/DamageFX.h"
#include "GameLogic/Weapon.h"
#include "GameClient/Snow.h"
+#include "GameClient/TerrainVisual.h"
// GameLogic::loadMapINI's load: unknown fields skipped, any throw stops the file there
static Bool loadMapIni( const char *name )
@@ -296,3 +297,187 @@ TEST(map_ini_refuses_extreme_snow)
TheWeatherSetting = (WeatherSetting *)ws->deleteOverrides();
remove( TEST_INI );
}
+
+namespace {
+// WaterTransparency's real INI parser notifies the terrain renderer even when
+// only water colors change. These tests load no terrain or graphics device.
+class WaterRuleTestTerrain : public TerrainVisual
+{
+public:
+ void getTerrainColorAt(Real, Real, RGBColor *) override {}
+ TerrainType *getTerrainTile(Real, Real) override { return NULL; }
+ void enableWaterGrid(Bool) override {}
+ void setTerrainTracksDetail() override {}
+ void setShoreLineDetail() override {}
+ void addFactionBib(Object *, Bool, Real) override {}
+ void removeFactionBib(Object *) override {}
+ void addFactionBibDrawable(Drawable *, Bool, Real) override {}
+ void removeFactionBibDrawable(Drawable *) override {}
+ void removeAllBibs() override {}
+ void removeBibHighlighting() override {}
+ void removeTreesAndPropsForConstruction(const Coord3D *, const GeometryInfo &, Real) override {}
+ void addProp(const ThingTemplate *, const Coord3D *, Real) override {}
+ void setRawMapHeight(const ICoord2D *, Int) override {}
+ Int getRawMapHeight(const ICoord2D *) override { return 0; }
+#ifdef DO_SEISMIC_SIMULATIONS
+ void updateSeismicSimulations() override {}
+ void addSeismicSimulation(const SeismicSimulationNode &) override {}
+#endif
+ void replaceSkyboxTextures(const AsciiString *[NumSkyboxTextures], const AsciiString *[NumSkyboxTextures]) override {}
+};
+
+const char *const WATER_RULE_TEST_INI = "test_gameengine_water_rule_tmp.ini";
+class WaterRuleTestFiles : public TestLocalFileSystem
+{
+public:
+ Bool present = FALSE;
+ File *openFile(const Char *filename, Int access = 0) override
+ {
+ if (strcmp(filename, "Data\\INI\\ModernWater.ini") == 0)
+ return present ? TestLocalFileSystem::openFile(WATER_RULE_TEST_INI, access) : NULL;
+ return TestLocalFileSystem::openFile(filename, access);
+ }
+};
+
+// The real VFS, INI loader, override chain and material cache are exercised.
+// Only the graphics callback and ModernWater.ini's backing file are replaced.
+struct WaterRuleFixture
+{
+ LocalFileSystem *savedFiles = TheLocalFileSystem;
+ ArchiveFileSystem *savedArchives = TheArchiveFileSystem;
+ GlobalData *savedGlobals = TheWritableGlobalData;
+ TerrainVisual *savedTerrain = TheTerrainVisual;
+ const WaterTransparencySetting *savedWater = TheWaterTransparency.getNonOverloadedPointer();
+ WaterRuleTestFiles files;
+ WaterRuleTestTerrain terrain;
+ WaterTransparencySetting *base = newInstance(WaterTransparencySetting);
+
+ WaterRuleFixture()
+ {
+ TheLocalFileSystem = &files;
+ TheArchiveFileSystem = NULL;
+ TheWritableGlobalData = NULL;
+ TheTerrainVisual = &terrain;
+ TheWaterTransparency = base;
+ loadModernWaterSettings(); // absent through this fixture: deterministic built-in defaults
+ }
+ ~WaterRuleFixture()
+ {
+ files.present = FALSE;
+ loadModernWaterSettings();
+ base->deleteInstance(); // also frees this test's map overrides
+ TheWaterTransparency = savedWater;
+ TheTerrainVisual = savedTerrain;
+ TheWritableGlobalData = savedGlobals;
+ TheArchiveFileSystem = savedArchives;
+ TheLocalFileSystem = savedFiles;
+ remove(TEST_INI);
+ remove(WATER_RULE_TEST_INI);
+ }
+ void resetMap()
+ {
+ TheWaterTransparency = static_cast<WaterTransparencySetting *>(base->deleteOverrides());
+ }
+ void loadRules(const char *text)
+ {
+ writeFile(WATER_RULE_TEST_INI, text);
+ files.present = TRUE;
+ loadModernWaterSettings();
+ }
+};
+
+void checkWaterMaterial(Real r, Real g, Real b, Real brightness, Real tint, Real pollution, Real bubbles)
+{
+ Real color[4], parameters[4];
+ getModernWaterMaterial(color, parameters);
+ CHECK_NEAR(color[0], r / 255.0f, .00001f);
+ CHECK_NEAR(color[1], g / 255.0f, .00001f);
+ CHECK_NEAR(color[2], b / 255.0f, .00001f);
+ CHECK_NEAR(color[3], brightness, .00001f);
+ CHECK_NEAR(parameters[0], tint, .00001f);
+ CHECK_NEAR(parameters[1], pollution, .00001f);
+ CHECK_NEAR(parameters[2], bubbles, .00001f);
+ CHECK_EQ(parameters[3], 0.0f);
+}
+}
+
+TEST(map_ini_modern_water_resolves_effective_override_without_changing_classic)
+{
+ CHECK(bootOnce());
+ WaterRuleFixture fixture;
+ checkWaterMaterial(255, 255, 255, 1, 0, 0, 0);
+ writeFile(TEST_INI,
+ "WaterTransparency\n"
+ " StandingWaterColor = R:50 G:75 B:50\n"
+ " StandingWaterTexture = TSWater03.tga\n"
+ " TransparentWaterDepth = 2.0\n"
+ " TransparentWaterMinOpacity = 0.8\n"
+ "End\n");
+ CHECK(loadMapIni(TEST_INI));
+ checkWaterMaterial(45, 58, 11, .67f, 1, .80f, 1);
+ // Resolve repeatedly through the cache; Classic still sees authored values.
+ checkWaterMaterial(45, 58, 11, .67f, 1, .80f, 1);
+ CHECK_NEAR(TheWaterTransparency->m_standingWaterColor.red, 50 / 255.0f, .00001f);
+ CHECK_NEAR(TheWaterTransparency->m_standingWaterColor.green, 75 / 255.0f, .00001f);
+ CHECK_NEAR(TheWaterTransparency->m_standingWaterColor.blue, 50 / 255.0f, .00001f);
+ CHECK_STR(TheWaterTransparency->m_standingWaterTexture.str(), "TSWater03.tga");
+ CHECK_NEAR(TheWaterTransparency->m_transparentWaterDepth, 2, .00001f);
+ CHECK_NEAR(TheWaterTransparency->m_minWaterOpacity, .8f, .00001f);
+ CHECK(TheWaterTransparency.getNonOverloadedPointer() == fixture.base);
+ CHECK_NEAR(fixture.base->m_standingWaterColor.red, 1, .00001f);
+
+ // The next map can have the same color and a different texture; the cache
+ // must notice that change even if it never rendered the reset state.
+ fixture.resetMap();
+ writeFile(TEST_INI,
+ "WaterTransparency\n"
+ " StandingWaterColor = R:50 G:75 B:50\n"
+ " StandingWaterTexture = OtherWater.tga\n"
+ "End\n");
+ CHECK(loadMapIni(TEST_INI));
+ checkWaterMaterial(50, 75, 50, 1, 1, 0, 0);
+ fixture.resetMap();
+ checkWaterMaterial(255, 255, 255, 1, 0, 0, 0);
+ writeFile(TEST_INI,
+ "WaterTransparency\n"
+ " StandingWaterColor = R:255 G:0 B:0\n"
+ " StandingWaterTexture = TSWater03.tga\n"
+ "End\n");
+ CHECK(loadMapIni(TEST_INI));
+ checkWaterMaterial(255, 0, 0, 1, 1, 0, 0);
+ fixture.resetMap();
+ checkWaterMaterial(255, 255, 255, 1, 0, 0, 0);
+}
+
+TEST(map_ini_modern_water_config_reload_replaces_cache_and_falls_back_atomically)
+{
+ CHECK(bootOnce());
+ WaterRuleFixture fixture;
+ writeFile(TEST_INI,
+ "WaterTransparency\n"
+ " StandingWaterColor = R:50 G:75 B:50\n"
+ " StandingWaterTexture = TSWater03.tga\n"
+ "End\n");
+ CHECK(loadMapIni(TEST_INI));
+ checkWaterMaterial(45, 58, 11, .67f, 1, .80f, 1);
+ const char *const custom =
+ "ModernWaterRule Custom\n"
+ " MatchColors\n Color = R:50 G:75 B:50\n End\n"
+ " MatchTextures\n Texture = TSWater03.tga\n End\n"
+ " ReplacementColor = R:120 G:10 B:20\n"
+ " Brightness = 0.5\n Pollution = 0.25\n Bubbles = No\nEnd\n";
+ fixture.loadRules(custom);
+ checkWaterMaterial(120, 10, 20, .5f, 1, .25f, 0);
+ fixture.loadRules("; intentionally disabled\n");
+ checkWaterMaterial(50, 75, 50, 1, 1, 0, 0);
+
+ // A valid first rule followed by a malformed rule cannot install a partial edit.
+ const std::string malformed = std::string(custom) + "ModernWaterRule Broken\nUnknown = 1\nEnd\n";
+ fixture.loadRules(malformed.c_str());
+ checkWaterMaterial(45, 58, 11, .67f, 1, .80f, 1);
+ fixture.loadRules(custom);
+ checkWaterMaterial(120, 10, 20, .5f, 1, .25f, 0);
+ fixture.files.present = FALSE;
+ loadModernWaterSettings();
+ checkWaterMaterial(45, 58, 11, .67f, 1, .80f, 1);
+}
diff --git a/GeneralsMD/Code/Tests/test_modern_water_config.cpp b/GeneralsMD/Code/Tests/test_modern_water_config.cpp
new file mode 100644
index 000000000..745868f3e
--- /dev/null
+++ b/GeneralsMD/Code/Tests/test_modern_water_config.cpp
@@ -0,0 +1,199 @@
+#include "test_harness.h"
+#include "Platform/ModernWaterConfig.h"
+
+#include <fstream>
+#include <iterator>
+#include <limits>
+
+using namespace ModernWaterConfig;
+
+namespace {
+const char *const sample =
+ "ModernWaterRule First\n"
+ " MatchColors\n"
+ " Color = R:50 G:75 B:50\n"
+ " Color = R:190 G:15 B:20\n"
+ " End\n"
+ " MatchTextures\n"
+ " Texture = TSWater03.tga\n"
+ " Texture = Art\\Textures\\RedWater.tga\n"
+ " End\n"
+ " ReplacementColor = R:45 G:58 B:11\n"
+ " Brightness = 0.67\n"
+ " Pollution = 0.80\n"
+ " Bubbles = Yes\n"
+ "End\n";
+
+std::string Changed(const std::string &before, const std::string &after) {
+ std::string text(sample);
+ const std::size_t position = text.find(before);
+ CHECK(position != std::string::npos);
+ if (position != std::string::npos) text.replace(position, before.size(), after);
+ return text;
+}
+
+void CheckDefaults(const Rules &rules) {
+ CHECK_EQ(rules.size(), 1u);
+ if (rules.empty()) return;
+ CHECK_STR(rules[0].name.c_str(), "PollutedWater");
+ CHECK_EQ(rules[0].colors.size(), 1u);
+ CHECK_EQ(rules[0].textures.size(), 1u);
+ CHECK(rules[0].colors[0] == (Color{50, 75, 50}));
+ CHECK_STR(rules[0].textures[0].c_str(), "TSWater03.tga");
+ CHECK(rules[0].replacement == (Color{45, 58, 11}));
+ CHECK_NEAR(rules[0].brightness, .67f, 0.00001f);
+ CHECK_NEAR(rules[0].pollution, .80f, 0.00001f);
+ CHECK(rules[0].bubbles);
+ CHECK(rules[0].enabled);
+}
+}
+
+TEST(modern_water_defaults_and_shipped_file_stay_identical)
+{
+ CheckDefaults(Defaults());
+ // Defined by CMake so the test is independent of its working directory.
+ std::ifstream file(MODERN_WATER_INI_PATH, std::ios::binary);
+ CHECK(file.good());
+ const std::string text((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
+ Rules rules;
+ std::string error;
+ CHECK(Parse(text, rules, error));
+ CHECK(error.empty());
+ CheckDefaults(rules);
+}
+
+TEST(modern_water_lists_match_cross_combinations_and_require_both)
+{
+ Rules rules;
+ std::string error;
+ CHECK(Parse(sample, rules, error));
+ CHECK_EQ(rules.size(), 1u);
+ if (rules.empty()) return;
+ for (const Color color : {Color{50, 75, 50}, Color{190, 15, 20}})
+ for (const char *texture : {"TSWater03.tga", "redwater.TGA", "ART/Textures/tsWATER03.TGA", "Art\\Textures\\REDwater.tga"})
+ CHECK(Match(rules, color, texture) == &rules[0]);
+ CHECK(Match(rules, Color{50, 76, 50}, "TSWater03.tga") == NULL);
+ CHECK(Match(rules, Color{50, 75, 50}, "Other.tga") == NULL);
+ CHECK(Match(rules, Color{50, 75, 50}, "") == NULL);
+ CHECK(Match(rules, Color{50, 75, 50}, "Art/Textures/") == NULL);
+}
+
+TEST(modern_water_rule_order_and_disable_are_explicit)
+{
+ const std::string second = Changed("First", "Second");
+ Rules rules;
+ std::string error;
+ CHECK(Parse(std::string(sample) + second, rules, error));
+ const Rule *rule = Match(rules, Color{50, 75, 50}, "TSWater03.tga");
+ CHECK(rule != NULL);
+ if (rule) CHECK_STR(rule->name.c_str(), "First");
+ CHECK(Parse(Changed(" Bubbles = Yes", " Bubbles = Yes\n Enabled = No") + second, rules, error));
+ rule = Match(rules, Color{50, 75, 50}, "TSWater03.tga");
+ CHECK(rule != NULL);
+ if (rule) CHECK_STR(rule->name.c_str(), "Second");
+ CHECK(Parse(Changed(" Bubbles = Yes", " Bubbles = Yes\n Enabled = No"), rules, error));
+ CHECK(Match(rules, Color{50, 75, 50}, "TSWater03.tga") == NULL);
+}
+
+TEST(modern_water_bad_edits_preserve_previous_rules_and_report_line)
+{
+ const std::string invalid[] = {
+ Changed("R:50", "R:-1"), Changed("R:50", "R:256"),
+ Changed("R:50", "R:50.5"), Changed("R:50", "R:9999999999999999999"),
+ Changed("G:75", "X:75"), Changed("B:50", "B:50 extra"),
+ Changed("0.67", "nan"), Changed("0.67", "inf"), Changed("0.67", "0.09"),
+ Changed("0.67", "1.01"), Changed("0.80", "-0.01"), Changed("0.80", "1.01"),
+ Changed("0.80", "0.8junk"), Changed("Bubbles = Yes", "Bubbles = Maybe"),
+ Changed("Bubbles = Yes", "Enabled = Maybe"), Changed("Bubbles = Yes", "Unknown = Yes"),
+ Changed(" Bubbles = Yes", " Bubbles = Yes\n Bubbles = No"),
+ Changed(" Texture = TSWater03.tga", " Texture = Art/Textures/"),
+ Changed(" Texture = TSWater03.tga", " Texture = Two Words.tga"),
+ Changed("MatchColors", "MatchColors = Yes"),
+ Changed("MatchColors", "MatchTextures"),
+ Changed(" ReplacementColor = R:45 G:58 B:11\n", ""),
+ Changed(" Color = R:50 G:75 B:50\n Color = R:190 G:15 B:20\n", ""),
+ Changed(" Texture = TSWater03.tga\n Texture = Art\\Textures\\RedWater.tga\n", ""),
+ std::string(sample).substr(0, std::string(sample).size() - 4),
+ std::string(sample) + Changed("First", "FIRST"),
+ std::string(sample) + "End\n",
+ std::string(sample) + "ModernWaterRule unfinished\n"
+ };
+ for (const std::string &text : invalid) {
+ Rules rules = Defaults();
+ std::string error;
+ CHECK(!Parse(text, rules, error));
+ CHECK(error.find("line ") == 0);
+ CheckDefaults(rules);
+ }
+ Rules rules = Defaults();
+ std::string error;
+ CHECK(!Parse("; comment\nModernWaterRule Broken\nBogus = 1\n", rules, error));
+ CHECK(error.find("line 3:") == 0);
+}
+
+TEST(modern_water_empty_file_is_deliberate_disable_and_syntax_handles_comments)
+{
+ Rules rules = Defaults();
+ std::string error = "old error";
+ CHECK(Parse("\xEF\xBB\xBF; disabled\r\n \t\n", rules, error));
+ CHECK(rules.empty());
+ CHECK(error.empty());
+ std::string text = Changed("ModernWaterRule First", "modernwaterrule First ; first rule");
+ text.replace(text.find("MatchColors"), 11, "matchcolors");
+ text.replace(text.find("Bubbles = Yes"), 13, "Bubbles = yEs");
+ CHECK(Parse(text, rules, error));
+ CHECK_EQ(rules.size(), 1u);
+}
+
+TEST(modern_water_optional_parameters_and_numeric_endpoints)
+{
+ Rules rules;
+ std::string error;
+ std::string text = Changed(" Brightness = 0.67\n Pollution = 0.80\n Bubbles = Yes\n", "");
+ CHECK(Parse(text, rules, error));
+ if (rules.empty()) return;
+ CHECK_EQ(rules[0].brightness, 1.0f);
+ CHECK_EQ(rules[0].pollution, 0.0f);
+ CHECK(!rules[0].bubbles);
+ CHECK(rules[0].enabled);
+ CHECK(Parse(Changed("0.67", "0.1"), rules, error));
+ CHECK(Parse(Changed("0.67", "1"), rules, error));
+ CHECK(Parse(Changed("0.80", "0"), rules, error));
+ CHECK(Parse(Changed("0.80", "1"), rules, error));
+ CHECK(Parse(Changed("ReplacementColor = R:45 G:58 B:11", "ReplacementColor = R:0 G:255 B:0"), rules, error));
+}
+
+TEST(modern_water_resolution_never_carries_pollution_to_next_map)
+{
+ const Rules rules = Defaults();
+ Material material = Resolve(rules, Color{50, 75, 50}, "TSWater03.tga");
+ CHECK(material.color == (Color{45, 58, 11}));
+ CHECK_NEAR(material.brightness, .67f, .00001f);
+ CHECK_NEAR(material.pollution, .80f, .00001f);
+ CHECK_EQ(material.tintAmount, 1.0f);
+ CHECK(material.bubbles);
+ CHECK_STR(material.ruleName.c_str(), "PollutedWater");
+
+ for (const Color color : {Color{255, 255, 255}, Color{255, 0, 0}, Color{0, 0, 0}, Color{50, 75, 50}}) {
+ material = Resolve(rules, color, "Unmatched.tga");
+ CHECK(material.color == color);
+ CHECK_EQ(material.brightness, 1.0f);
+ CHECK_EQ(material.pollution, 0.0f);
+ CHECK_EQ(material.tintAmount, color.r == 255 && color.g == 255 && color.b == 255 ? 0.0f : 1.0f);
+ CHECK(!material.bubbles);
+ CHECK(material.ruleName.empty());
+ }
+}
+
+TEST(modern_water_normalized_byte_colors_round_trip_exactly)
+{
+ for (int value = 0; value < 256; ++value) {
+ const Color color = ByteColor(value / 255.0f, value / 255.0f, value / 255.0f);
+ CHECK(color == (Color{value, value, value}));
+ }
+ const Rules rules = Defaults();
+ CHECK(Match(rules, ByteColor(50 / 255.0f, 75 / 255.0f, 50 / 255.0f), "TSWater03.tga") != NULL);
+ CHECK(ByteColor(-1, 2, .5f) == (Color{0, 255, 128}));
+ CHECK_EQ(ColorByte(std::numeric_limits<float>::quiet_NaN()), 0);
+ CHECK_EQ(ColorByte(std::numeric_limits<float>::infinity()), 0);
+}
diff --git a/GeneralsMD/Code/Tests/test_posix_draw_resolve.cpp b/GeneralsMD/Code/Tests/test_posix_draw_resolve.cpp
index 5eba9eb6c..cb39e34ab 100644
--- a/GeneralsMD/Code/Tests/test_posix_draw_resolve.cpp
+++ b/GeneralsMD/Code/Tests/test_posix_draw_resolve.cpp
@@ -41,6 +41,7 @@
#include "ffvertex.h"
#include <math.h>
+#include <stddef.h>
#include <stdio.h>
#include <string.h>
@@ -286,6 +287,234 @@ static void check_constants(PosixDevice9 *device)
CHECK(pixel.TextureFactor[0] == 1.0f && near_value(pixel.TextureFactor[1], 0x40 / 255.0)
&& pixel.TextureFactor[2] == 0.0f && near_value(pixel.TextureFactor[3], 0x80 / 255.0));
CHECK(near_value(vertex.GlobalAmbient[0], 0x33 / 255.0) && near_value(vertex.GlobalAmbient[2], 0x99 / 255.0));
+
+ // Water must reconstruct world coordinates from the same projection that drew its geometry.
+ // Check the inverse by composing it with an independently calculated view/projection product.
+ const float water_registers[6][4] = { { 12.5f, 1, 1, 0 }, { -0.8f, -0.6f, 0.9f, 0.7f },
+ { 0.2f, -0.3f, 0.8f, 0 }, { 0.7f, 0.6f, 0.5f, 0 }, { 160, 5120, 159.375f, 1 },
+ { 2.7f, 0.75f, 1.0f, 0 } };
+ device->SetPixelShaderConstantF(1, &water_registers[0][0], 6);
+ SdlWaterPixelConstants water;
+ device->Build_Water_Constants(pixel, water);
+ bool inverse = true;
+ for (int r = 0; r < 4; ++r) for (int c = 0; c < 4; ++c) {
+ double identity = 0;
+ for (int k = 0; k < 4; ++k) for (int j = 0; j < 4; ++j)
+ identity += view[r][j] * projection[j][k] * water.WorldFromClip[k * 4 + c];
+ inverse = inverse && fabs(identity - (r == c ? 1.0 : 0.0)) < 0.0001;
+ }
+ CHECK(inverse);
+ CHECK(near_value(water.CameraPosition[0], -20) && near_value(water.CameraPosition[1], 10)
+ && near_value(water.CameraPosition[2], -30));
+ CHECK(memcmp(&water.Combiner, &pixel, sizeof(pixel)) == 0);
+ CHECK(memcmp(water.WaterParameters, water_registers[0], 16) == 0);
+ CHECK(memcmp(water.ReflectionArea, water_registers[1], 16) == 0);
+ CHECK(memcmp(water.SunDirection, water_registers[2], 16) == 0);
+ CHECK(memcmp(water.SunColour, water_registers[3], 16) == 0);
+ CHECK(memcmp(water.TerrainParameters, water_registers[4], 16) == 0);
+ CHECK(memcmp(water.OpticalParameters, water_registers[5], 16) == 0);
+ // Capability-dependent FFT enablement is supplied only after native preparation succeeds,
+ // never inherited from the engine register bank or an earlier ocean draw.
+ CHECK(water.FftParameters[0]==0 && water.FftParameters[1]==0);
+ // The last vessel's last contour vertex must survive the complete register-to-uniform path.
+ // A shorter legacy pixel bank silently loses this end of the runtime hull field.
+ float hull_registers[81][4] = {};
+ hull_registers[0][0] = 8;
+ for (int r=1;r<81;++r) for (int c=0;c<4;++c) hull_registers[r][c]=float(r*4+c)+0.25f;
+ CHECK(device->SetPixelShaderConstantF(7,&hull_registers[0][0],81)==D3D_OK);
+ float standing_parameters[4]={12.5f,0,1,0};
+ device->SetPixelShaderConstantF(1,standing_parameters,1);
+ device->Build_Water_Constants(pixel,water);
+ CHECK(memcmp(water.HullParameters,hull_registers[0],16)==0);
+ CHECK(memcmp(water.HullData,hull_registers[1],sizeof(water.HullData))==0);
+ // The optional foam contour is a distinct tail, never a replacement for the mean hull used
+ // by displacement. Exercise every register, including the twelfth vertex of hull eight.
+ CHECK(sizeof(water)==188*16 && offsetof(SdlWaterPixelConstants,ContactHullData)==100*16);
+ CHECK(offsetof(SdlWaterPixelConstants,CoastalArea)==184*16 && offsetof(SdlWaterPixelConstants,CoastalParams)==185*16);
+ float contact_registers[80][4]={};
+ for(int r=0;r<80;++r)for(int c=0;c<4;++c)contact_registers[r][c]=-float(r*4+c)-0.75f;
+ CHECK(device->SetPixelShaderConstantF(96,&contact_registers[0][0],80)==D3D_OK);
+ device->Build_Water_Constants(pixel,water);
+ CHECK(memcmp(water.ContactHullData,contact_registers,sizeof(contact_registers))==0);
+ CHECK(memcmp(water.HullParameters,hull_registers[0],16)==0);
+ CHECK(memcmp(water.HullData,hull_registers[1],sizeof(water.HullData))==0);
+ // Fill lights use the old gap before contact registers. Removing lights must explicitly
+ // clear their colours/main enable so a later map or time-of-day cannot inherit illumination.
+ CHECK(offsetof(SdlWaterPixelConstants,FoamFillLights)==180*16);
+ float fill_registers[4][4]={{.6f,0,.8f,1},{.3f,.2f,.1f,0},{0,.8f,.6f,0},{.1f,.2f,.3f,0}};
+ CHECK(device->SetPixelShaderConstantF(90,&fill_registers[0][0],4)==D3D_OK);
+ device->Build_Water_Constants(pixel,water);
+ CHECK(memcmp(water.FoamFillLights,fill_registers,sizeof(fill_registers))==0);
+ CHECK(memcmp(water.ContactHullData,contact_registers,sizeof(contact_registers))==0);
+ memset(fill_registers,0,sizeof(fill_registers));fill_registers[0][3]=1;
+ CHECK(device->SetPixelShaderConstantF(90,&fill_registers[0][0],4)==D3D_OK);
+ device->Build_Water_Constants(pixel,water);CHECK(memcmp(water.FoamFillLights,fill_registers,sizeof(fill_registers))==0);
+ // Material state has explicit registers between fill lights and contact geometry.
+ // It must survive packing without borrowing light components, and clear on the next draw.
+ const float material[2][4]={{45/255.0f,58/255.0f,11/255.0f,.67f},{1,.8f,1,0}};
+ CHECK(device->SetPixelShaderConstantF(ModernWaterMaterial::RegisterColor,material[0],2)==D3D_OK);
+ device->Build_Water_Constants(pixel,water);
+ CHECK(memcmp(water.MaterialColor,material[0],16)==0 && memcmp(water.MaterialParameters,material[1],16)==0);
+ CHECK(memcmp(water.ContactHullData,contact_registers,sizeof(contact_registers))==0);
+ CHECK(memcmp(water.FoamFillLights,fill_registers,sizeof(fill_registers))==0);
+ const float clearMaterial[2][4]={};
+ CHECK(device->SetPixelShaderConstantF(ModernWaterMaterial::RegisterColor,clearMaterial[0],2)==D3D_OK);
+ device->Build_Water_Constants(pixel,water);
+ CHECK(memcmp(water.MaterialColor,clearMaterial[0],16)==0 && memcmp(water.MaterialParameters,clearMaterial[1],16)==0);
+ fill_registers[0][3]=0;CHECK(device->SetPixelShaderConstantF(90,&fill_registers[0][0],4)==D3D_OK);
+ device->Build_Water_Constants(pixel,water);CHECK(memcmp(water.FoamFillLights,fill_registers,sizeof(fill_registers))==0);
+ CHECK(device->SetPixelShaderConstantF(175,contact_registers[79],1)==D3D_OK);
+ CHECK(device->SetPixelShaderConstantF(WaterHullVisualLayout::PixelRegisterCount,contact_registers[79],1)==D3DERR_INVALIDCALL);
+ // Exact mesh transport extends the emulated bank deliberately, without moving the old
+ // 188-register native vertex prefix or copying the reserved engine-register gap into metadata.
+ using namespace WaterHullVisualLayout;
+ CHECK(PosixDevice9::PIXEL_SHADER_CONSTANT_COUNT==896);
+ CHECK(sizeof(SdlWaterVisualPixelConstants)==196*16 && offsetof(SdlWaterVisualPixelConstants,VisualHullMeta)==188*16);
+ CHECK(VertexCommonRegisters==188 && FragmentCommonRegisters==196);
+ CHECK(BlockOffset(0)==0 && BlockOffset(1)==256 && BlockOffset(2)==512);
+ CHECK(BlockRegisters(0)==256 && BlockRegisters(1)==256 && BlockRegisters(2)==192);
+ float visualMeta[8][4]={};float visualPacket[704][4]={};float reserved[8][4]={};
+ for(unsigned h=0;h<8;++h)for(unsigned c=0;c<4;++c){visualMeta[h][c]=float(h*4+c)+.5f;reserved[h][c]=-99;}
+ for(unsigned r=0;r<704;++r)for(unsigned c=0;c<4;++c)visualPacket[r][c]=float(r*4+c)+.25f;
+ CHECK(device->SetPixelShaderConstantF(176,visualMeta[0],8)==D3D_OK);
+ CHECK(device->SetPixelShaderConstantF(184,reserved[0],8)==D3D_OK);
+ CHECK(device->SetPixelShaderConstantF(192,visualPacket[0],704)==D3D_OK);
+ CHECK(device->SetPixelShaderConstantF(895,visualPacket[703],1)==D3D_OK);
+ CHECK(device->SetPixelShaderConstantF(895,visualPacket[703],2)==D3DERR_INVALIDCALL);
+ CHECK(device->SetPixelShaderConstantF(896,visualPacket[703],1)==D3DERR_INVALIDCALL);
+ SdlWaterVisualPixelConstants visual;
+ // The scene-owned native coastal tail is independent of emulated c184..191 above.
+ // Reusing a populated CPU block must clear it until a successful draw explicitly binds a view.
+ const float coastArea[4]={-32,48,256,128},coastParams[4]={1,7,24.25f,24.375f},zeroCoast[4]={};
+ memcpy(water.CoastalArea,coastArea,sizeof(coastArea));memcpy(water.CoastalParams,coastParams,sizeof(coastParams));
+ device->Build_Water_Constants(pixel,water);
+ CHECK(memcmp(water.CoastalArea,zeroCoast,sizeof(zeroCoast))==0 && memcmp(water.CoastalParams,zeroCoast,sizeof(zeroCoast))==0);
+ // A successful scene binding fills this native tail before the visual wrapper copies it.
+ memcpy(water.CoastalArea,coastArea,sizeof(coastArea));memcpy(water.CoastalParams,coastParams,sizeof(coastParams));
+ device->Build_Water_Visual_Constants(water,visual);
+ CHECK(memcmp(&visual.Water,&water,sizeof(water))==0);
+ CHECK(memcmp(visual.VisualHullMeta,visualMeta,sizeof(visualMeta))==0);
+ CHECK(memcmp(visual.Water.CoastalArea,coastArea,sizeof(coastArea))==0 && memcmp(visual.Water.CoastalParams,coastParams,sizeof(coastParams))==0);
+ // After an ocean, missing/zero metadata must replace every previously populated slot.
+ memset(visualMeta,0,sizeof(visualMeta));CHECK(device->SetPixelShaderConstantF(176,visualMeta[0],8)==D3D_OK);
+ device->Build_Water_Visual_Constants(water,visual);CHECK(memcmp(visual.VisualHullMeta,visualMeta,sizeof(visualMeta))==0);
+ // The river/empty-hull safeguard is independent of the caller remembering to clear metadata.
+ CHECK(device->SetPixelShaderConstantF(176,reserved[0],8)==D3D_OK);
+ SdlWaterPixelConstants emptyWater=water;emptyWater.HullParameters[0]=0;
+ device->Build_Water_Visual_Constants(emptyWater,visual);CHECK(memcmp(visual.VisualHullMeta,visualMeta,sizeof(visualMeta))==0);
+ CHECK(device->SetPixelShaderConstantF(176,visualMeta[0],8)==D3D_OK);
+ // Sparse unsupported layouts cannot read bindings left behind by a different draw.
+ for(unsigned vs=0;vs<5;++vs)for(unsigned ps=0;ps<6;++ps)for(unsigned wv=0;wv<2;++wv)for(unsigned wp=0;wp<2;++wp) {
+ const bool expected=(vs<=1 || (wv && vs==2)) && (ps<=1 || (wp && ps==4));
+ CHECK(Sdl_Draw_Uniform_Buffers_Supported(wv,wp,vs,ps)==expected);
+ }
+
+ // Missing/failed contact geometry is uploaded as a complete zero block. A reused uniform
+ // object must not retain any preceding contour after the engine explicitly disables it.
+ memset(contact_registers,0,sizeof(contact_registers));
+ CHECK(device->SetPixelShaderConstantF(96,&contact_registers[0][0],80)==D3D_OK);
+ device->Build_Water_Constants(pixel,water);
+ CHECK(memcmp(water.ContactHullData,contact_registers,sizeof(contact_registers))==0);
+ CHECK(memcmp(water.HullData,hull_registers[1],sizeof(water.HullData))==0);
+ // New flat meshes repurpose UV0 only when this per-draw flag reaches the shader. A legacy
+ // grid immediately following them must clear the flag while retaining all other optical data.
+ float correction_optics[4]={2.7f,.75f,1,1};
+ CHECK(device->SetPixelShaderConstantF(6,correction_optics,1)==D3D_OK);
+ device->Build_Water_Constants(pixel,water);
+ CHECK(memcmp(water.OpticalParameters,correction_optics,sizeof(correction_optics))==0);
+ correction_optics[3]=0;
+ CHECK(device->SetPixelShaderConstantF(6,correction_optics,1)==D3D_OK);
+ device->Build_Water_Constants(pixel,water);
+ CHECK(water.OpticalParameters[3]==0 && memcmp(water.OpticalParameters,water_registers[5],16)==0);
+ CHECK(device->SetPixelShaderConstantF(PosixDevice9::PIXEL_SHADER_CONSTANT_COUNT-1,
+ &hull_registers[0][0],2)==D3DERR_INVALIDCALL);
+ device->SetPixelShaderConstantF(1,water_registers[0],1);
+ device->Build_Water_Constants(pixel,water);
+ CHECK(water.HullParameters[0]==0); // river following an ocean draw cannot reuse vessel foam
+ CHECK(near_value(water.Viewport[2], 64) && near_value(water.Viewport[3], 32));
+ // Scene depth is the hardware viewport depth, including a nondefault MinZ/MaxZ. Project a known
+ // point independently and reconstruct it, as both surface and submerged-object samples must do.
+ D3DVIEWPORT9 depth_viewport;
+ device->GetViewport(&depth_viewport);
+ depth_viewport.MinZ = 0.2f;
+ depth_viewport.MaxZ = 0.85f;
+ device->SetViewport(&depth_viewport);
+ device->Build_Water_Constants(pixel, water);
+ const double world_point[4] = { 17, -9, 53, 1 };
+ double clip[4] = {};
+ for (unsigned int c = 0; c < 4; ++c)
+ for (unsigned int r = 0; r < 4; ++r)
+ for (unsigned int j = 0; j < 4; ++j) clip[c] += world_point[r] * view[r][j] * projection[j][c];
+ const double device_point[4] = { clip[0] / clip[3], clip[1] / clip[3],
+ depth_viewport.MinZ + clip[2] / clip[3] * (depth_viewport.MaxZ - depth_viewport.MinZ), 1 };
+ double reconstructed[4] = {};
+ for (unsigned int c = 0; c < 4; ++c)
+ for (unsigned int r = 0; r < 4; ++r) reconstructed[c] += device_point[r] * water.WorldFromClip[r * 4 + c];
+ for (unsigned int c = 0; c < 3; ++c) CHECK(near_value(reconstructed[c] / reconstructed[3], world_point[c]));
+ depth_viewport.MinZ = 0;
+ depth_viewport.MaxZ = 1;
+ device->SetViewport(&depth_viewport);
+ memset(&m, 0, sizeof(m));
+ device->SetTransform(D3DTS_PROJECTION, &m);
+ device->Build_Water_Constants(pixel, water);
+ bool fallback = true;
+ for (int i = 0; i < 16; ++i) fallback = fallback && water.WorldFromClip[i] == (i % 5 == 0 ? 1.0f : 0.0f);
+ CHECK(fallback);
+}
+
+static void check_foam_history_constants(PosixDevice9 *device)
+{
+ // The two new registers fit after all eight complete hulls. A stale sampler binding or
+ // missing runtime texture must never activate history on the next material or water level.
+ SdlPixelConstants pixel={};SdlWaterPixelConstants water;
+ float parameters[4]={24.5f,0,1,0};
+ float history[2][4]={{-128,64,1.0f/1024,1.0f/512},{1,7,2,24.25f}};
+ CHECK(device->SetPixelShaderConstantF(1,parameters,1)==D3D_OK);
+ CHECK(device->SetPixelShaderConstantF(88,history[0],2)==D3D_OK);
+ device->Build_Water_Constants(pixel,water);
+ CHECK(water.FoamHistoryParameters[0]==0 && !device->Water_Foam_History_Available());
+ IDirect3DTexture9 *texture=NULL,*attachment=NULL;
+ CHECK(device->CreateTexture(4,4,1,0,D3DFMT_A8R8G8B8,D3DPOOL_MANAGED,&texture,NULL)==D3D_OK);
+ CHECK(device->CreateTexture(4,4,1,D3DUSAGE_RENDERTARGET,D3DFMT_A8R8G8B8,D3DPOOL_DEFAULT,&attachment,NULL)==D3D_OK);
+ CHECK(device->SetTexture(14,texture)==D3D_OK);
+ IDirect3DBaseTexture9 *held=NULL;CHECK(device->GetTexture(14,&held)==D3D_OK && held==texture);if(held)held->Release();
+ device->Build_Water_Constants(pixel,water);
+ CHECK(device->Water_Foam_History_Available());
+ CHECK(memcmp(water.FoamHistoryArea,history[0],16)==0 && memcmp(water.FoamHistoryParameters,history[1],16)==0);
+ CHECK(water.HullData[79][3]==320.0f+3.25f); // the prior test's last vertex survived c88/c89
+ parameters[1]=1;device->SetPixelShaderConstantF(1,parameters,1);device->Build_Water_Constants(pixel,water);
+ CHECK(water.FoamHistoryParameters[0]==0 && water.HullParameters[0]==0);
+ parameters[1]=0;device->SetPixelShaderConstantF(1,parameters,1);
+ for(unsigned row=0;row<2;++row)for(unsigned c=0;c<4;++c) {
+ const float saved=history[row][c];history[row][c]=NAN;
+ device->SetPixelShaderConstantF(88,history[0],2);device->Build_Water_Constants(pixel,water);
+ CHECK(water.FoamHistoryParameters[0]==0);history[row][c]=saved;
+ }
+ for(unsigned field=0;field<3;++field) {
+ float *value=field<2?&history[0][2+field]:&history[1][2];const float saved=*value;*value=0;
+ device->SetPixelShaderConstantF(88,history[0],2);device->Build_Water_Constants(pixel,water);
+ CHECK(water.FoamHistoryParameters[0]==0);*value=saved;
+ }
+ device->SetPixelShaderConstantF(88,history[0],2);CHECK(device->SetTexture(14,attachment)==D3D_OK);
+ device->Build_Water_Constants(pixel,water);CHECK(water.FoamHistoryParameters[0]==0);
+ CHECK(device->SetTexture(14,texture)==D3D_OK);device->Build_Water_Constants(pixel,water);CHECK(water.FoamHistoryParameters[0]==1);
+ for(float flags:{2.f,3.f,5.f,6.f,7.f}) {
+ history[1][0]=flags;device->SetPixelShaderConstantF(88,history[0],2);device->Build_Water_Constants(pixel,water);
+ CHECK(device->Water_Foam_History_Available() && water.FoamHistoryParameters[0]==flags);
+ }
+ for(float flags:{4.f,8.f,5.5f}) {
+ history[1][0]=flags;device->SetPixelShaderConstantF(88,history[0],2);device->Build_Water_Constants(pixel,water);
+ CHECK(!device->Water_Foam_History_Available() && water.FoamHistoryParameters[0]==0);
+ }
+ IDirect3DTexture9 *odd=NULL;
+ CHECK(device->CreateTexture(4,3,1,0,D3DFMT_A8R8G8B8,D3DPOOL_MANAGED,&odd,NULL)==D3D_OK);
+ CHECK(device->SetTexture(14,odd)==D3D_OK);
+ history[1][0]=5;device->SetPixelShaderConstantF(88,history[0],2);CHECK(!device->Water_Foam_History_Available());
+ history[1][0]=1;device->SetPixelShaderConstantF(88,history[0],2);CHECK(device->Water_Foam_History_Available());
+ if(odd)odd->Release();
+ CHECK(device->SetTexture(14,NULL)==D3D_OK);device->Build_Water_Constants(pixel,water);CHECK(water.FoamHistoryParameters[0]==0);
+ if(texture)texture->Release();if(attachment)attachment->Release();
+ printf("posix_draw_resolve_selfcheck: history c88/c89, sampler14, invalid mapping, missing texture, river and attachment fallback checked\n");
}
int main()
@@ -302,6 +531,7 @@ int main()
check_combiner(device);
check_lights(device);
check_constants(device);
+ check_foam_history_constants(device);
device->Release();
d3d->Release();
if (failures != 0) {
diff --git a/GeneralsMD/Code/Tests/test_sdl_gpu_frame.cpp b/GeneralsMD/Code/Tests/test_sdl_gpu_frame.cpp
index a0c05ccbc..c5341caf8 100644
--- a/GeneralsMD/Code/Tests/test_sdl_gpu_frame.cpp
+++ b/GeneralsMD/Code/Tests/test_sdl_gpu_frame.cpp
@@ -30,20 +30,6843 @@
// - Any GPU but this one. Exits 77, and ctest reports it skipped, where SDL has no GPU device.
#include "SdlGpuFrame.h"
+#include "SdlConstants.h"
+#include "SdlResourceMirror.h"
+#include "PosixResources9.h"
+#include "../Libraries/Source/WWVegas/WW3D2/sdl3shadercompile.h"
+#include "../Libraries/Source/WWVegas/WW3D2/sdl3target.h"
+#include "../Libraries/Source/WWVegas/WW3D2/engineshader.h"
+#include "Platform/WaterSurfaceModel.h"
+#include "Platform/WaterOpticalModel.h"
+#include "Platform/WaterHullModel.h"
+#include "Platform/WaterHullVisual.h"
+#include <limits>
+#include "Platform/WaterFftSpectrum.h"
+#include "Platform/WaterFftSampling.h"
+#include "Platform/WaterFoamShading.h"
+#include "Platform/WaterFoamEnvironment.h"
+#include "Platform/WaterShoreFoam.h"
+#include "Platform/WaterCoastalCrest.h"
+#include "Platform/WaterCoastalSurf.h"
+#include "Platform/WaterCoastalPresentation.h"
+#include "Platform/WaterCoastalView.h"
+#include "Platform/WaterCoastalIncident.h"
+#include "Platform/WaterShoreOverlay.h"
+#include "../Libraries/Source/WWVegas/WW3D2/ffshader.h"
+#include "Platform/WaterBowRefinement.h"
+#include <complex>
#include <SDL3/SDL.h>
#include <stdio.h>
#include <stdlib.h>
+#include <math.h>
+#include <string.h>
+#include <stddef.h>
static int failures = 0;
#define CHECK(condition) \
do { if (!(condition)) { ++failures; printf("FAIL %s:%d: %s\n", __FILE__, __LINE__, #condition); } } while (0)
+// Bind the production fragment layout even when a normal-only fixture has no mesh hulls.
+static void push_empty_visual_water(SDL_GPUCommandBuffer *commands,const SdlWaterPixelConstants &water)
+{
+ if(!WaterHullVisual::Enabled()) {
+ SDL_PushGPUFragmentUniformData(commands,0,&water,sizeof(water));return;
+ }
+ SdlWaterVisualPixelConstants common={};common.Water=water;
+ SDL_PushGPUFragmentUniformData(commands,0,&common,sizeof(common));
+ const float packets[WaterHullVisualLayout::PacketRegisters][4]={};
+ for(unsigned block=0;block<WaterHullVisualLayout::BlockCount;++block)
+ SDL_PushGPUFragmentUniformData(commands,block+1,packets[WaterHullVisualLayout::BlockOffset(block)],
+ WaterHullVisualLayout::BlockRegisters(block)*16);
+}
+
static const unsigned int WIDTH = 64;
static const unsigned int HEIGHT = 48;
+// Rasterize a submerged object independently of the water capture: a triangle writes its own
+// depth, so a terrain-only estimate or a copy of the depth clear cannot satisfy the assertions.
+class DepthObject
+{
+public:
+ SDL_GPUShader *Vertex = NULL, *Pixel = NULL;
+ SDL_GPUGraphicsPipeline *Pipeline = NULL;
+ SdlGpuFrame *Frame;
+ explicit DepthObject(SdlGpuFrame *frame) : 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";
+ 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);
+ 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);
+ }
+ ~DepthObject()
+ {
+ Frame->Flush();
+ if (Pipeline) SDL_ReleaseGPUGraphicsPipeline(Frame->Device(), Pipeline);
+ if (Vertex) SDL_ReleaseGPUShader(Frame->Device(), Vertex);
+ if (Pixel) SDL_ReleaseGPUShader(Frame->Device(), Pixel);
+ }
+ void Draw(const SdlTarget &target, float depth)
+ {
+ if (!Pipeline) 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));
+ 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(SdlGpuFrame *frame)
+{
+ if (!(frame->Depth_Usage() & SDL_GPU_TEXTUREUSAGE_SAMPLER)) {
+ printf("sdl_gpu_frame_selfcheck: scene depth unavailable on this device (fallback colour still tested)\n");
+ CHECK(frame->Water_Depth(frame->Back_Buffer_Target()) == NULL);
+ return;
+ }
+ DepthObject object(frame);
+ const SdlTarget scene = frame->Back_Buffer_Target();
+ frame->Set_Target(scene);
+ frame->Clear_Back_Buffer(true, true, true, 0xFF183048, 0.9f, 0);
+ frame->Clear_Rect(0, 0, 16, 12, false, true, false, 0, 0.65f, 0);
+ uint64_t readySerial=123;
+ CHECK(frame->Ready_Water_Depth(scene,readySerial)==NULL && readySerial==0);
+ object.Draw(scene, 0.3f);
+ SDL_GPUTexture *depth = frame->Water_Depth(scene);
+ CHECK(depth != NULL && depth != scene.Depth && depth != scene.Colour);
+ CHECK(frame->Ready_Water_Depth(scene,readySerial)==depth && readySerial!=0);
+ const uint64_t originalSerial=readySerial;
+ std::vector<uint8_t> sampled;
+ CHECK(frame->Read_Back(depth, scene.Width, scene.Height, sampled));
+ CHECK(fabs(depth_at(sampled, scene.Width, 32, 24) - 0.3f) < 0.00001f);
+ CHECK(fabs(depth_at(sampled, scene.Width, 2, 2) - 0.65f) < 0.00001f);
+ CHECK(fabs(depth_at(sampled, scene.Width, 62, 46) - 0.9f) < 0.00001f);
+ std::vector<uint8_t> colour;
+ CHECK(frame->Read_Back(frame->Water_Background(scene), scene.Width, scene.Height, colour));
+ CHECK(colour[(24 * scene.Width + 32) * 4 + 2] == 204); // the same object's colour
+
+ // A later draw must not contaminate the pre-water depth, even over multiple flushes.
+ object.Draw(scene, 0.1f);
+ CHECK(frame->Ready_Water_Depth(scene,readySerial)==depth && readySerial==originalSerial);
+ CHECK(frame->Water_Depth(scene) == depth);
+ CHECK(frame->Read_Back(depth, scene.Width, scene.Height, colour));
+ CHECK(colour == sampled);
+ // No clear is needed to refresh the next frame's depth.
+ CHECK(frame->Present(NULL));
+ CHECK(frame->Ready_Water_Depth(scene,readySerial)==NULL && readySerial==0);
+ CHECK(frame->Water_Depth(scene) == depth);
+ CHECK(frame->Ready_Water_Depth(scene,readySerial)==depth && readySerial!=originalSerial);
+ CHECK(frame->Read_Back(depth, scene.Width, scene.Height, sampled));
+ CHECK(fabs(depth_at(sampled, scene.Width, 32, 24) - 0.1f) < 0.00001f);
+
+ SDL_GPUTextureCreateInfo info = {};
+ info.type = SDL_GPU_TEXTURETYPE_2D;
+ info.format = (SDL_GPUTextureFormat)frame->Depth_Format();
+ info.usage = frame->Depth_Usage();
+ info.width = 23; info.height = 17; info.layer_count_or_depth = 1; info.num_levels = 1;
+ SDL_GPUTexture *other_depth = SDL_CreateGPUTexture(frame->Device(), &info);
+ info.format = (SDL_GPUTextureFormat)frame->Target_Format();
+ info.usage = SDL_GPU_TEXTUREUSAGE_COLOR_TARGET | SDL_GPU_TEXTUREUSAGE_SAMPLER;
+ SDL_GPUTexture *other_colour = SDL_CreateGPUTexture(frame->Device(), &info);
+ CHECK(other_depth && other_colour);
+ const SdlTarget intermediate = { other_colour, other_depth, 23, 17 };
+ frame->Set_Target(intermediate);
+ frame->Clear_Back_Buffer(true, true, true, 0xFFABCDEF, 0.8f, 0);
+ CHECK(frame->Ready_Water_Depth(intermediate,readySerial)==NULL && readySerial==0);
+ object.Draw(intermediate, 0.45f);
+ SDL_GPUTexture *intermediate_depth = frame->Water_Depth(intermediate);
+ CHECK(intermediate_depth && intermediate_depth != depth);
+ CHECK(frame->Read_Back(intermediate_depth, 23, 17, colour));
+ CHECK(fabs(depth_at(colour, 23, 11, 8) - 0.45f) < 0.00001f);
+ CHECK(fabs(depth_at(colour, 23, 0, 0) - 0.8f) < 0.00001f);
+ // Returning to a source preserves its own snapshot instead of copying previously rendered water.
+ object.Draw(scene, 0.05f);
+ CHECK(frame->Read_Back(frame->Water_Depth(scene), scene.Width, scene.Height, colour));
+ CHECK(colour == sampled);
+ // Depth-only clear invalidates the pair, then release source handles with a capture still queued.
+ frame->Set_Target(intermediate);
+ frame->Clear_Back_Buffer(false, true, false, 0, 0.7f, 0);
+ CHECK(frame->Ready_Water_Depth(intermediate,readySerial)==NULL && readySerial==0);
+ CHECK(frame->Read_Back(frame->Water_Depth(intermediate), 23, 17, colour));
+ CHECK(fabs(depth_at(colour, 23, 11, 8) - 0.7f) < 0.00001f);
+ frame->Clear_Back_Buffer(true, true, true, 0xFF102030, 0.6f, 0);
+ CHECK(frame->Water_Depth(intermediate) != NULL);
+ frame->Release_After_Batch(other_colour, NULL);
+ frame->Release_After_Batch(other_depth, NULL);
+ CHECK(frame->Flush());
+ frame->Set_Target(scene);
+ CHECK(frame->Present(NULL));
+}
+
+static void check_gpu_wave_model(SdlGpuFrame *frame)
+{
+ // Execute the exact shared HLSL model on the GPU. Columns are height, dH/dx and dH/dy; rows use
+ // different positions/times, including the free-camera view and large/negative map coordinates.
+ const float fixtures[][4] = {
+ {0, 0, 0, 0}, {0, 0, 1.7f, 0}, {12, -21, 3.2f, 0}, {-80, 43, 19.4f, 0},
+ {1938, 736, 0, 0}, {1938, 736, 4.2f, 0}, {1938, 736, 67.1f, 0},
+ {4100, 3700, 13.8f, 0}, {-1900, 720, 3.6f, 0}, {736, 1938, 431.2f, 0},
+ {17, 89, 864.3f, 0}, {4096, 4096, 3600, 0} };
+ const unsigned int count = sizeof(fixtures) / sizeof(fixtures[0]);
+ const char *vertex_source =
+ "float4 main(uint id : SV_VertexID) : SV_Position {\n"
+ "return float4(id == 1 ? 3.0 : -1.0, id == 2 ? 3.0 : -1.0, 0, 1); }\n";
+ std::string pixel_source = "cbuffer Samples : register(b0, space3) { float4 Fixtures[12]; };\n";
+ pixel_source += WaterSurfaceModel::ShaderSource();
+ pixel_source += "float main(float4 position : SV_Position) : SV_Target0 {\n"
+ "float4 f=Fixtures[(uint)position.y]; return waterWave(f.xy,f.z)[(uint)position.x]; }\n";
+ std::vector<unsigned char> spirv;
+ std::string error;
+ CHECK(SDL3_Compile_HLSL_To_SPIRV(vertex_source, true, spirv, error));
+ SDL_GPUShader *vertex = SDL3_Create_Shader(frame->Device(), spirv, true, error);
+ CHECK(SDL3_Compile_HLSL_To_SPIRV(pixel_source, false, spirv, error));
+ SDL_GPUShader *pixel = SDL3_Create_Shader(frame->Device(), spirv, false, error);
+ CHECK(vertex && pixel);
+ SDL_GPUColorTargetDescription description = {};
+ description.format = SDL_GPU_TEXTUREFORMAT_R32_FLOAT;
+ SDL_GPUGraphicsPipelineCreateInfo pipeline_info = {};
+ pipeline_info.vertex_shader = vertex;
+ pipeline_info.fragment_shader = pixel;
+ pipeline_info.primitive_type = SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;
+ pipeline_info.rasterizer_state.fill_mode = SDL_GPU_FILLMODE_FILL;
+ pipeline_info.rasterizer_state.cull_mode = SDL_GPU_CULLMODE_NONE;
+ pipeline_info.target_info.color_target_descriptions = &description;
+ pipeline_info.target_info.num_color_targets = 1;
+ SDL_GPUGraphicsPipeline *pipeline = SDL_CreateGPUGraphicsPipeline(frame->Device(), &pipeline_info);
+ SDL_GPUTextureCreateInfo texture_info = {};
+ texture_info.type = SDL_GPU_TEXTURETYPE_2D;
+ texture_info.format = SDL_GPU_TEXTUREFORMAT_R32_FLOAT;
+ texture_info.usage = SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;
+ texture_info.width = 3; texture_info.height = count;
+ texture_info.layer_count_or_depth = 1; texture_info.num_levels = 1;
+ SDL_GPUTexture *target = SDL_CreateGPUTexture(frame->Device(), &texture_info);
+ CHECK(pipeline && target);
+ CHECK(frame->Flush());
+ SDL_GPUCommandBuffer *commands = SDL_AcquireGPUCommandBuffer(frame->Device());
+ CHECK(commands != NULL);
+ SDL_GPUColorTargetInfo attachment = {};
+ attachment.texture = target;
+ attachment.load_op = SDL_GPU_LOADOP_DONT_CARE;
+ attachment.store_op = SDL_GPU_STOREOP_STORE;
+ SDL_GPURenderPass *pass = SDL_BeginGPURenderPass(commands, &attachment, 1, NULL);
+ CHECK(pass != NULL);
+ SDL_BindGPUGraphicsPipeline(pass, pipeline);
+ SDL_PushGPUFragmentUniformData(commands, 0, fixtures, sizeof(fixtures));
+ SDL_DrawGPUPrimitives(pass, 3, 1, 0, 0);
+ SDL_EndGPURenderPass(pass);
+ CHECK(SDL_SubmitGPUCommandBuffer(commands));
+ std::vector<uint8_t> bytes;
+ CHECK(frame->Read_Back(target, 3, count, bytes));
+ float max_model_error = 0, max_difference_error = 0;
+ for (unsigned int i = 0; i < count; ++i) {
+ const float x = fixtures[i][0], y = fixtures[i][1], seconds = fixtures[i][2];
+ const WaterSurfaceModel::Sample cpu = WaterSurfaceModel::Evaluate(x, y, seconds);
+ const float values[3] = { cpu.height, cpu.dx, cpu.dy };
+ for (unsigned int c = 0; c < 3; ++c) {
+ const float difference = fabsf(depth_at(bytes, 3, c, i) - values[c]);
+ if (difference > max_model_error) max_model_error = difference;
+ CHECK(difference < 0.0025f); // float phase precision at large map coordinates/times
+ }
+ const float epsilon = 0.03125f;
+ const float dx = (WaterSurfaceModel::Evaluate(x + epsilon, y, seconds).height
+ - WaterSurfaceModel::Evaluate(x - epsilon, y, seconds).height) / (2 * epsilon);
+ const float dy = (WaterSurfaceModel::Evaluate(x, y + epsilon, seconds).height
+ - WaterSurfaceModel::Evaluate(x, y - epsilon, seconds).height) / (2 * epsilon);
+ const float error_x = fabsf(depth_at(bytes, 3, 1, i) - dx), error_y = fabsf(depth_at(bytes, 3, 2, i) - dy);
+ if (error_x > max_difference_error) max_difference_error = error_x;
+ if (error_y > max_difference_error) max_difference_error = error_y;
+ CHECK(error_x < 0.01f && error_y < 0.01f);
+ }
+ printf("sdl_gpu_frame_selfcheck: GPU wave height/normal consistency: max CPU model error %.7f, finite-difference slope error %.7f\n",
+ max_model_error, max_difference_error);
+ SDL_ReleaseGPUTexture(frame->Device(), target);
+ SDL_ReleaseGPUGraphicsPipeline(frame->Device(), pipeline);
+ SDL_ReleaseGPUShader(frame->Device(), vertex);
+ SDL_ReleaseGPUShader(frame->Device(), pixel);
+}
+
+static void check_gpu_ocean_wave_model(SdlGpuFrame *frame)
+{
+ // A spatially varying offshore weight exercises the derivative of the blend, not just the
+ // interpolation of two normals. Every fixture is {x,y,time,weight, dWeight/dx,dWeight/dy,0,0}.
+ const float fixtures[][8] = {
+ {0,0,0,0, 0,0,0,0}, {12,-21,3.2f,0, 0,0,0,0}, {1938,736,67.1f,0, 0,0,0,0},
+ {0,0,0,1, 0,0,0,0}, {0,0,1.7f,1, 0,0,0,0}, {3028,588,12,1, 0,0,0,0},
+ {4096,4096,3600,1, 0,0,0,0}, {-1900,720,3.6f,1, 0,0,0,0}, {17,89,864.3f,1, 0,0,0,0},
+ {0,0,0,.2f, .014f,-.011f,0,0}, {12,-21,3.2f,.5f, -.006f,.018f,0,0},
+ {-80,43,19.4f,.8f, .011f,.007f,0,0}, {1938,736,4.2f,.5f, .008f,-.012f,0,0},
+ {4100,3700,13.8f,.5f, -.009f,.004f,0,0}, {736,1938,431.2f,.9f, .002f,-.003f,0,0}
+ };
+ const unsigned int count=sizeof(fixtures)/sizeof(fixtures[0]), columns=30;
+ const float epsilon=.03125f;
+ const char *vertex_source=
+ "float4 main(uint id : SV_VertexID) : SV_Position {\n"
+ "return float4(id == 1 ? 3.0 : -1.0, id == 2 ? 3.0 : -1.0, 0, 1); }\n";
+ std::string pixel_source="cbuffer Samples : register(b0, space3) { float4 Fixtures[";
+ pixel_source+=std::to_string(count*2)+"]; };\n";
+ WaterSurfaceModel::AppendHLSL(pixel_source);
+ pixel_source+=
+ "float3 blendAt(float2 offset,float4 f,float2 gradient) {\n"
+ "float3 legacy=waterWave(f.xy+offset,f.z), ocean=waterOceanWave(f.xy+offset,f.z);\n"
+ "float weight=saturate(f.w+dot(offset,gradient));\n"
+ "float3 result=legacy+(ocean-legacy)*weight;\n"
+ "result.yz+=(ocean.x-legacy.x)*gradient; return result; }\n"
+ "float main(float4 position : SV_Position) : SV_Target0 {\n"
+ "uint row=(uint)position.y,column=(uint)position.x;\n"
+ "float4 f=Fixtures[row*2]; float2 gradient=Fixtures[row*2+1].xy;\n"
+ "if (column<3) return blendAt(float2(0,0),f,gradient)[column];\n"
+ "if (column<7) { float2 offset=column==3?float2(0.03125,0):\n"
+ "column==4?float2(-0.03125,0):column==5?float2(0,0.03125):float2(0,-0.03125);\n"
+ "return blendAt(offset,f,gradient).x; }\n"
+ "if (column<10) return waterOceanWave(f.xy,f.z)[column-7];\n"
+ "if (column<13) return waterWave(f.xy,f.z)[column-10];\n"
+ "if (column==13) return waterOceanSurface(f.xy,f.z).w;\n"
+ "if (column>=26) { float2 offset=column==26?float2(0.25,0):column==27?float2(-0.25,0):\n"
+ "column==28?float2(0,0.25):float2(0,-0.25); return waterOceanWave(f.xy+offset,f.z).x; }\n"
+ "if (column>=18) { float4 swell; waterOceanSurface(f.xy,f.z,swell);\n"
+ "if (column<22) return swell[column-18];\n"
+ "float2 step=column==22?float2(0.125,0):column==23?float2(-0.125,0):column==24?float2(0,0.125):float2(0,-0.125);\n"
+ "waterOceanSurface(f.xy+step,f.z,swell); return swell.x; }\n"
+ "float2 offset=column==14?float2(0.125,0):column==15?float2(-0.125,0):\n"
+ "column==16?float2(0,0.125):float2(0,-0.125);\n"
+ "return waterOceanWave(f.xy+offset,f.z).x; }\n";
+ std::vector<unsigned char> spirv;
+ std::string error;
+ CHECK(SDL3_Compile_HLSL_To_SPIRV(vertex_source,true,spirv,error));
+ SDL_GPUShader *vertex=SDL3_Create_Shader(frame->Device(),spirv,true,error);
+ CHECK(SDL3_Compile_HLSL_To_SPIRV(pixel_source,false,spirv,error));
+ SDL_GPUShader *pixel=SDL3_Create_Shader(frame->Device(),spirv,false,error);
+ CHECK(vertex && pixel);
+ SDL_GPUColorTargetDescription description={};
+ description.format=SDL_GPU_TEXTUREFORMAT_R32_FLOAT;
+ SDL_GPUGraphicsPipelineCreateInfo pipeline_info={};
+ pipeline_info.vertex_shader=vertex; pipeline_info.fragment_shader=pixel;
+ pipeline_info.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;
+ pipeline_info.rasterizer_state.fill_mode=SDL_GPU_FILLMODE_FILL;
+ pipeline_info.rasterizer_state.cull_mode=SDL_GPU_CULLMODE_NONE;
+ pipeline_info.target_info.color_target_descriptions=&description;
+ pipeline_info.target_info.num_color_targets=1;
+ SDL_GPUGraphicsPipeline *pipeline=SDL_CreateGPUGraphicsPipeline(frame->Device(),&pipeline_info);
+ SDL_GPUTextureCreateInfo texture_info={};
+ texture_info.type=SDL_GPU_TEXTURETYPE_2D; texture_info.format=SDL_GPU_TEXTUREFORMAT_R32_FLOAT;
+ texture_info.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;
+ texture_info.width=columns; texture_info.height=count;
+ texture_info.layer_count_or_depth=1; texture_info.num_levels=1;
+ SDL_GPUTexture *target=SDL_CreateGPUTexture(frame->Device(),&texture_info);
+ CHECK(pipeline && target);
+ CHECK(frame->Flush());
+ SDL_GPUCommandBuffer *commands=SDL_AcquireGPUCommandBuffer(frame->Device());
+ CHECK(commands != NULL);
+ SDL_GPUColorTargetInfo attachment={};
+ attachment.texture=target; attachment.load_op=SDL_GPU_LOADOP_DONT_CARE; attachment.store_op=SDL_GPU_STOREOP_STORE;
+ SDL_GPURenderPass *pass=SDL_BeginGPURenderPass(commands,&attachment,1,NULL);
+ CHECK(pass != NULL);
+ SDL_BindGPUGraphicsPipeline(pass,pipeline);
+ SDL_PushGPUFragmentUniformData(commands,0,fixtures,sizeof(fixtures));
+ SDL_DrawGPUPrimitives(pass,3,1,0,0);
+ SDL_EndGPURenderPass(pass);
+ CHECK(SDL_SubmitGPUCommandBuffer(commands));
+ std::vector<uint8_t> bytes;
+ CHECK(frame->Read_Back(target,columns,count,bytes));
+ float max_model_error=0,max_gpu_derivative_error=0,max_cpu_derivative_error=0;
+ float max_curvature_model_error=0,max_cpu_curvature_error=0,max_gpu_curvature_error=0;
+ float max_cpu_coarse_curvature_error=0,max_gpu_coarse_curvature_error=0;
+ float max_swell_model_error=0,max_swell_gradient_error=0,max_swell_laplacian_error=0;
+ unsigned int gradient_controls=0,curvature_checks=0,curvature_controls=0,curvature_refinements=0;
+ for (unsigned int i=0;i<count;++i) {
+ using namespace WaterSurfaceModel;
+ const float *f=fixtures[i];
+ const Sample legacy=Evaluate(f[0],f[1],f[2]),ocean=EvaluateOcean(f[0],f[1],f[2]);
+ const Sample offshore={f[3],f[4],f[5]};
+ const Sample blended=BlendSamples(legacy,ocean,offshore);
+ const float expected[3]={blended.height,blended.dx,blended.dy};
+ const float expected_ocean[3]={ocean.height,ocean.dx,ocean.dy};
+ for (unsigned int c=0;c<3;++c) {
+ const float a=fabsf(depth_at(bytes,columns,c,i)-expected[c]);
+ const float b=fabsf(depth_at(bytes,columns,c+7,i)-expected_ocean[c]);
+ max_model_error=fmaxf(max_model_error,fmaxf(a,b));
+ CHECK(a<.0025f && b<.0025f); // float phase precision at long elapsed times/large map positions
+ if (f[3]==0) CHECK(depth_at(bytes,columns,c,i)==depth_at(bytes,columns,c+10,i));
+ if (f[3]==1) CHECK(fabsf(depth_at(bytes,columns,c,i)-depth_at(bytes,columns,c+7,i))<.000001f);
+ }
+ auto height_at=[&](float ox,float oy) {
+ // Independent scalar interpolation deliberately does not use the analytic BlendSamples
+ // derivatives. Its central difference must recover both domain warp and blend product terms.
+ const float a=Evaluate(f[0]+ox,f[1]+oy,f[2]).height;
+ const float b=EvaluateOcean(f[0]+ox,f[1]+oy,f[2]).height;
+ const float weight=f[3]+ox*f[4]+oy*f[5];
+ return a+(b-a)*weight;
+ };
+ const float numeric_cpu[2]={(height_at(epsilon,0)-height_at(-epsilon,0))/(2*epsilon),
+ (height_at(0,epsilon)-height_at(0,-epsilon))/(2*epsilon)};
+ const float numeric_gpu[2]={(depth_at(bytes,columns,3,i)-depth_at(bytes,columns,4,i))/(2*epsilon),
+ (depth_at(bytes,columns,5,i)-depth_at(bytes,columns,6,i))/(2*epsilon)};
+ for (unsigned int c=0;c<2;++c) {
+ const float cpu_error=fabsf(numeric_cpu[c]-expected[c+1]);
+ const float gpu_error=fabsf(numeric_gpu[c]-depth_at(bytes,columns,c+1,i));
+ max_cpu_derivative_error=fmaxf(max_cpu_derivative_error,cpu_error);
+ max_gpu_derivative_error=fmaxf(max_gpu_derivative_error,gpu_error);
+ CHECK(cpu_error<.01f && gpu_error<.0125f);
+ // Armed control: omitting dWeight/dx,y must measurably break several fixtures.
+ const float wrong=(c==0?legacy.dx:legacy.dy)*(1-f[3])+(c==0?ocean.dx:ocean.dy)*f[3];
+ if (fabsf(expected[c+1]-wrong)>.008f) ++gradient_controls;
+ }
+ if (f[3]==0) {
+ const Sample endpoint=EvaluateBlended(f[0],f[1],f[2],offshore);
+ CHECK(memcmp(&legacy,&endpoint,sizeof(Sample))==0);
+ }
+ const OceanSurface surface=EvaluateOceanSurface(f[0],f[1],f[2]);
+ const float gpu_curvature=depth_at(bytes,columns,13,i);
+ const float model_error=fabsf(gpu_curvature-surface.laplacian);
+ max_curvature_model_error=fmaxf(max_curvature_model_error,model_error);
+ CHECK(model_error<.0025f);
+ const OceanSurface swell=EvaluateOceanSwell(f[0],f[1],f[2]);
+ const float expected_swell[4]={swell.height,swell.dx,swell.dy,swell.laplacian};
+ for(unsigned c=0;c<4;++c) {
+ const float difference=fabsf(depth_at(bytes,columns,18+c,i)-expected_swell[c]);
+ max_swell_model_error=fmaxf(max_swell_model_error,difference);CHECK(difference<.0025f);
+ }
+ // Height-only second differences independently exercise the warp Hessian and all packet
+ // product terms. Near-origin fixtures avoid subtractive float cancellation from long phases;
+ // large-coordinate/elapsed-time fixtures still check CPU/GPU analytic agreement above.
+ if (fabsf(f[0])<128 && fabsf(f[1])<128 && f[2]<100) {
+ const float swell_x=(depth_at(bytes,columns,22,i)-depth_at(bytes,columns,23,i))/.25f;
+ const float swell_y=(depth_at(bytes,columns,24,i)-depth_at(bytes,columns,25,i))/.25f;
+ const float swell_laplacian=(depth_at(bytes,columns,22,i)+depth_at(bytes,columns,23,i)
+ +depth_at(bytes,columns,24,i)+depth_at(bytes,columns,25,i)-4*depth_at(bytes,columns,18,i))/.015625f;
+ const float slope_error=fmaxf(fabsf(swell_x-depth_at(bytes,columns,19,i)),fabsf(swell_y-depth_at(bytes,columns,20,i)));
+ const float curvature_error=fabsf(swell_laplacian-depth_at(bytes,columns,21,i));
+ max_swell_gradient_error=fmaxf(max_swell_gradient_error,slope_error);
+ max_swell_laplacian_error=fmaxf(max_swell_laplacian_error,curvature_error);
+ CHECK(slope_error<.0015f && curvature_error<.0015f);
+ const float step=.125f;
+ // The shortest ripples make the three-point h=.125 stencil's O(h^2) truncation
+ // exceed .005 at (0,0,1.7). Use the five-point O(h^4) stencil at the same spacing,
+ // rather than weakening the bound or halving h and amplifying float cancellation.
+ // Accumulate downloaded/CPU float heights in double; both evaluators stay production float.
+ auto cpu_height_sum=[&](float h) {
+ return double(EvaluateOcean(f[0]+h,f[1],f[2]).height)
+ +EvaluateOcean(f[0]-h,f[1],f[2]).height
+ +EvaluateOcean(f[0],f[1]+h,f[2]).height
+ +EvaluateOcean(f[0],f[1]-h,f[2]).height;
+ };
+ const double cpu_near=cpu_height_sum(step),cpu_far=cpu_height_sum(2*step);
+ const double gpu_near=double(depth_at(bytes,columns,14,i))+depth_at(bytes,columns,15,i)
+ +depth_at(bytes,columns,16,i)+depth_at(bytes,columns,17,i);
+ const double gpu_far=double(depth_at(bytes,columns,26,i))+depth_at(bytes,columns,27,i)
+ +depth_at(bytes,columns,28,i)+depth_at(bytes,columns,29,i);
+ const double gpu_center=depth_at(bytes,columns,7,i);
+ const float coarse_cpu=float((cpu_near-4.0*ocean.height)/(step*step));
+ const float coarse_gpu=float((gpu_near-4.0*gpu_center)/(step*step));
+ const float numeric_cpu=float((16.0*cpu_near-cpu_far-60.0*ocean.height)/(12.0*step*step));
+ const float numeric_gpu=float((16.0*gpu_near-gpu_far-60.0*gpu_center)/(12.0*step*step));
+ const float cpu_error=fabsf(numeric_cpu-surface.laplacian);
+ const float gpu_error=fabsf(numeric_gpu-gpu_curvature);
+ const float cpu_coarse_error=fabsf(coarse_cpu-surface.laplacian);
+ const float gpu_coarse_error=fabsf(coarse_gpu-gpu_curvature);
+ max_cpu_curvature_error=fmaxf(max_cpu_curvature_error,cpu_error);
+ max_gpu_curvature_error=fmaxf(max_gpu_curvature_error,gpu_error);
+ max_cpu_coarse_curvature_error=fmaxf(max_cpu_coarse_curvature_error,cpu_coarse_error);
+ max_gpu_coarse_curvature_error=fmaxf(max_gpu_coarse_curvature_error,gpu_coarse_error);
+ CHECK(cpu_error<.005f && gpu_error<.005f);
+ if (cpu_coarse_error>.002f && gpu_coarse_error>.002f
+ && cpu_error<cpu_coarse_error*.25f && gpu_error<gpu_coarse_error*.25f) ++curvature_refinements;
+ ++curvature_checks;
+ // Armed control keeps the same warped phases and envelope, but deliberately omits their
+ // spatial derivatives. Merely adding k-squared per-mode curvature must fail this fixture.
+ const float q0=f[0]*.0241f+f[1]*.0157f-f[2]*.23f+.4f;
+ const float q1=f[0]*-.0173f+f[1]*.0299f-f[2]*.19f+2.1f;
+ const float s0=sinf(q0),s1=sinf(q1),px=f[0]+5*s0,py=f[1]+4*s1;
+ float incomplete_laplacian=0;
+#define TEST_OCEAN_UNWARPED_LAPLACIAN(kx,ky,amplitude,omega,phase) { \
+ const float p=px*(kx)+py*(ky)-f[2]*(omega)+(phase); \
+ const float s=sinf(p),c=cosf(p); \
+ incomplete_laplacian+=(amplitude)*(-s-.64f*s*c)*((kx)*(kx)+(ky)*(ky)); }
+ WATER_OCEAN_MODES(TEST_OCEAN_UNWARPED_LAPLACIAN)
+#undef TEST_OCEAN_UNWARPED_LAPLACIAN
+ incomplete_laplacian*=.86f+.14f*s0*s1;
+ if (fabsf(numeric_cpu-incomplete_laplacian)>.008f) ++curvature_controls;
+ }
+ }
+ CHECK(gradient_controls>=4);
+ CHECK(curvature_checks>=4 && curvature_controls>=4);
+ CHECK(curvature_refinements>=1); // a truncation-dominated case must improve on both CPU and GPU
+ printf("sdl_gpu_frame_selfcheck: GPU ocean/blended waves: %u fixtures, CPU model error %.7f, numerical slopes CPU %.7f GPU %.7f, gradient controls %u\n",
+ count,max_model_error,max_cpu_derivative_error,max_gpu_derivative_error,gradient_controls);
+ printf("sdl_gpu_frame_selfcheck: GPU ocean curvature: model error %.7f, fourth-order height Laplacian CPU %.7f GPU %.7f (second-order %.7f/%.7f), %u checks, %u armed controls, %u stencil improvements\n",
+ max_curvature_model_error,max_cpu_curvature_error,max_gpu_curvature_error,
+ max_cpu_coarse_curvature_error,max_gpu_coarse_curvature_error,curvature_checks,curvature_controls,curvature_refinements);
+ printf("sdl_gpu_frame_selfcheck: GPU macro swell: model error %.7f, numerical gradient %.7f Laplacian %.7f\n",
+ max_swell_model_error,max_swell_gradient_error,max_swell_laplacian_error);
+ SDL_ReleaseGPUTexture(frame->Device(),target);
+ SDL_ReleaseGPUGraphicsPipeline(frame->Device(),pipeline);
+ SDL_ReleaseGPUShader(frame->Device(),vertex);
+ SDL_ReleaseGPUShader(frame->Device(),pixel);
+}
+
+#if defined(__linux__)
+static void check_gpu_water_mesh_correction(SdlGpuFrame *frame)
+{
+ // Exercise the production water normal, including its UV0 metadata gate and fixed-function
+ // vertex transport. A zero-damped wave leaves an independently known linear correction plane.
+ // The wrapper only supplies vertices; both shader bodies below are the actual generators.
+ const unsigned width=32,height=32;
+ struct Resources {
+ SDL_GPUDevice *device;
+ SDL_GPUShader *vertices[2]={},*pixel=NULL;
+ SDL_GPUGraphicsPipeline *pipelines[2]={};
+ SDL_GPUTexture *target=NULL,*white=NULL;
+ SDL_GPUSampler *sampler=NULL;
+ ~Resources() {
+ for(unsigned i=0;i<2;++i) {
+ if(pipelines[i]) SDL_ReleaseGPUGraphicsPipeline(device,pipelines[i]);
+ if(vertices[i]) SDL_ReleaseGPUShader(device,vertices[i]);
+ }
+ if(pixel) SDL_ReleaseGPUShader(device,pixel);
+ if(target) SDL_ReleaseGPUTexture(device,target);
+ if(white) SDL_ReleaseGPUTexture(device,white);
+ if(sampler) SDL_ReleaseGPUSampler(device,sampler);
+ }
+ } resources;
+ resources.device=frame->Device();
+ const char *previous=getenv("ZH_WATER_DEBUG");
+ const bool hadDebug=previous!=NULL;
+ const std::string previousDebug=previous?previous:"";
+ CHECK(setenv("ZH_WATER_DEBUG","normal",1)==0);
+ PixelPipelineDescription pixelDescription={};std::string pixelSource;
+ const bool generated=EngineShader_Pixel_Program(ENGINE_SHADER_WATER_TRAPEZOID,pixelDescription,
+ pixelSource,COMBINER_SHADER_TARGET_SDL3_GPU);
+ if(hadDebug) CHECK(setenv("ZH_WATER_DEBUG",previousDebug.c_str(),1)==0);
+ else CHECK(unsetenv("ZH_WATER_DEBUG")==0);
+ CHECK(generated);if(!generated) return;
+ std::vector<unsigned char> spirv;std::string error;
+ bool compiled=SDL3_Compile_HLSL_To_SPIRV(pixelSource,false,spirv,error);CHECK(compiled);
+ if(!compiled) {printf("water correction pixel compile: %s\n",error.c_str());return;}
+ unsigned samplers=0,pixelUniforms=0;SDL3_Shader_Slots(spirv,false,samplers,pixelUniforms);
+ const unsigned expectedUniforms=WaterHullVisual::Enabled()?4u:1u;
+ CHECK(samplers<=16 && pixelUniforms==expectedUniforms);if(samplers>16 || pixelUniforms!=expectedUniforms) return;
+ resources.pixel=SDL3_Create_Shader(resources.device,spirv,false,error);CHECK(resources.pixel);
+ if(!resources.pixel) return;
+ for(unsigned transformed=0;transformed<2;++transformed) {
+ VertexPipelineDescription vertexDescription={};
+ vertexDescription.FVF=FF_FVF_XYZ|FF_FVF_NORMAL|FF_FVF_DIFFUSE|FF_FVF_TEX2;
+ vertexDescription.StageCount=4;
+ vertexDescription.Stages[0].TextureCoordinateIndex=0;
+ vertexDescription.Stages[0].TextureTransformFlags=transformed?FF_TTFF_COUNT2:FF_TTFF_DISABLE;
+ vertexDescription.Stages[1].TextureCoordinateIndex=1;
+ std::string vertexSource;
+ CHECK(VertexShader_Generate(vertexDescription,VERTEX_SHADER_TARGET_SDL3_GPU,vertexSource));
+ const std::string entry="Output main(Input input)";
+ const size_t entryAt=vertexSource.find(entry);CHECK(entryAt!=std::string::npos);
+ if(entryAt==std::string::npos) return;
+ vertexSource.replace(entryAt,entry.size(),"Output waterFixtureVertex(Input input)");
+ vertexSource+="\ncbuffer Fixture : register(b1, space1) { float4 Correction; };\n"
+ "Output main(uint id : SV_VertexID) { Input input;\n"
+ "input.Position=float3(id==1?3.0:-1.0,id==2?3.0:-1.0,0.5);\n"
+ "input.Normal=float3(0,0,1);input.Diffuse=float4(1,1,1,1);\n"
+ "input.TexCoord0=float2(dot(input.Position.xy,Correction.xy)+Correction.z,0);\n"
+ "input.TexCoord1=float2(0,0.5);return waterFixtureVertex(input); }\n";
+ compiled=SDL3_Compile_HLSL_To_SPIRV(vertexSource,true,spirv,error);CHECK(compiled);
+ if(!compiled) {printf("water correction vertex compile: %s\n",error.c_str());return;}
+ resources.vertices[transformed]=SDL3_Create_Shader(resources.device,spirv,true,error);
+ CHECK(resources.vertices[transformed]);if(!resources.vertices[transformed]) return;
+ SDL_GPUColorTargetDescription colour={};colour.format=(SDL_GPUTextureFormat)SdlGpuFrame::Target_Format();
+ SDL_GPUGraphicsPipelineCreateInfo info={};
+ info.vertex_shader=resources.vertices[transformed];info.fragment_shader=resources.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.target_info.color_target_descriptions=&colour;info.target_info.num_color_targets=1;
+ resources.pipelines[transformed]=SDL_CreateGPUGraphicsPipeline(resources.device,&info);
+ CHECK(resources.pipelines[transformed]);if(!resources.pipelines[transformed]) return;
+ }
+ SDL_GPUTextureCreateInfo textureInfo={};textureInfo.type=SDL_GPU_TEXTURETYPE_2D;
+ textureInfo.format=(SDL_GPUTextureFormat)SdlGpuFrame::Target_Format();textureInfo.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;
+ textureInfo.width=width;textureInfo.height=height;textureInfo.layer_count_or_depth=1;textureInfo.num_levels=1;
+ resources.target=SDL_CreateGPUTexture(resources.device,&textureInfo);
+ textureInfo.width=textureInfo.height=1;textureInfo.usage|=SDL_GPU_TEXTUREUSAGE_SAMPLER;
+ resources.white=SDL_CreateGPUTexture(resources.device,&textureInfo);
+ SDL_GPUSamplerCreateInfo samplerInfo={};samplerInfo.min_filter=samplerInfo.mag_filter=SDL_GPU_FILTER_NEAREST;
+ resources.sampler=SDL_CreateGPUSampler(resources.device,&samplerInfo);
+ CHECK(resources.target && resources.white && resources.sampler);
+ if(!resources.target || !resources.white || !resources.sampler) return;
+ SdlVertexConstants vertexConstants={};SdlWaterPixelConstants water={};
+ for(unsigned i=0;i<4;++i) {
+ vertexConstants.WorldViewProjection[i*5]=vertexConstants.WorldView[i*5]=vertexConstants.NormalTransform[i*5]=1;
+ water.WorldFromClip[i*5]=1;
+ for(unsigned stage=0;stage<MAXIMUM_VERTEX_STAGES;++stage) vertexConstants.TextureMatrix[stage][i*5]=1;
+ }
+ // A stale matrix must be harmless with metadata passthrough; the armed alternate pipeline
+ // enables it and must visibly double the correction gradient.
+ vertexConstants.TextureMatrix[0][0]=2;vertexConstants.TextureMatrix[0][8]=13;
+ water.Viewport[2]=width;water.Viewport[3]=height;water.CameraPosition[2]=10;water.SunDirection[2]=1;
+ water.SunColour[0]=water.SunColour[1]=water.SunColour[2]=1;
+ water.TerrainParameters[1]=100;water.SceneParameters[1]=water.SceneParameters[2]=1;
+ water.OpticalParameters[0]=3;water.OpticalParameters[1]=1;
+ float correction[4]={.35f,-.20f,1.25f,0};
+ CHECK(frame->Flush());unsigned renders=0;
+ auto render=[&](bool enabled,unsigned transformed) {
+ water.OpticalParameters[3]=enabled?1.0f:0.0f;
+ SDL_GPUCommandBuffer *commands=SDL_AcquireGPUCommandBuffer(resources.device);CHECK(commands);
+ SDL_GPUColorTargetInfo attachment={};attachment.texture=resources.white;
+ attachment.load_op=SDL_GPU_LOADOP_CLEAR;attachment.store_op=SDL_GPU_STOREOP_STORE;
+ attachment.clear_color.r=attachment.clear_color.g=attachment.clear_color.b=attachment.clear_color.a=1;
+ SDL_GPURenderPass *pass=SDL_BeginGPURenderPass(commands,&attachment,1,NULL);CHECK(pass);SDL_EndGPURenderPass(pass);
+ attachment.texture=resources.target;attachment.clear_color.r=attachment.clear_color.g=attachment.clear_color.b=0;
+ pass=SDL_BeginGPURenderPass(commands,&attachment,1,NULL);CHECK(pass);
+ SDL_BindGPUGraphicsPipeline(pass,resources.pipelines[transformed]);
+ SDL_GPUTextureSamplerBinding bindings[16]={};
+ for(unsigned i=0;i<samplers;++i) {bindings[i].texture=resources.white;bindings[i].sampler=resources.sampler;}
+ if(samplers) SDL_BindGPUFragmentSamplers(pass,0,bindings,samplers);
+ SDL_PushGPUVertexUniformData(commands,0,&vertexConstants,sizeof(vertexConstants));
+ SDL_PushGPUVertexUniformData(commands,1,correction,sizeof(correction));
+ push_empty_visual_water(commands,water);
+ SDL_DrawGPUPrimitives(pass,3,1,0,0);SDL_EndGPURenderPass(pass);CHECK(SDL_SubmitGPUCommandBuffer(commands));
+ std::vector<uint8_t> bytes;CHECK(frame->Read_Back(resources.target,width,height,bytes));++renders;return bytes;
+ };
+ auto checkNormal=[&](const std::vector<uint8_t>& bytes,float gx,float gy) {
+ const float inverse=1.0f/sqrtf(1+gx*gx+gy*gy);
+ const float expected[3]={.5f+.5f*inverse,.5f-.5f*gy*inverse,.5f-.5f*gx*inverse}; // BGR
+ bool correct=bytes.size()==width*height*4;
+ if(correct) for(unsigned y=4;y<height-4;++y) for(unsigned x=4;x<width-4;++x) for(unsigned c=0;c<3;++c)
+ correct &= fabsf(bytes[(y*width+x)*4+c]/255.0f-expected[c])<2.0f/255.0f;
+ CHECK(correct);
+ };
+ const auto legacy=render(false,0);checkNormal(legacy,0,0);
+ const auto corrected=render(true,0);checkNormal(corrected,correction[0],correction[1]);CHECK(corrected!=legacy);
+ correction[2]+=17;const auto offset=render(true,0);checkNormal(offset,correction[0],correction[1]);CHECK(offset==corrected);
+ const auto transformed=render(true,1);checkNormal(transformed,2*correction[0],2*correction[1]);CHECK(transformed!=corrected);
+ // Rotate projection by 90 degrees and independently invert it. A screen-space gradient used
+ // directly as a world slope now has the wrong signs/axes even though the height field is linear.
+ vertexConstants.WorldViewProjection[0]=vertexConstants.WorldViewProjection[5]=0;
+ vertexConstants.WorldViewProjection[1]=1;vertexConstants.WorldViewProjection[4]=-1;
+ water.WorldFromClip[0]=water.WorldFromClip[5]=0;water.WorldFromClip[1]=-1;water.WorldFromClip[4]=1;
+ const auto rotated=render(true,0);checkNormal(rotated,correction[0],correction[1]);
+ correction[0]=-.42f;correction[1]=.28f;
+ checkNormal(render(true,0),correction[0],correction[1]);
+ checkNormal(render(false,0),0,0);
+ printf("sdl_gpu_frame_selfcheck: GPU production water correction: %u renders; known normals, legacy gate, constant offsets, projection rotation and armed texture-transform control passed\n",renders);
+}
+#endif // __linux__
+
+static void check_gpu_water_optical_model(SdlGpuFrame *frame)
+{
+ // Execute the same light-transport function used by the generated water shader. Each row has
+ // path, river blend, offshore blend, optical reference depth, authored opacity and padding.
+ // Columns capture all three channels independently in an R32 target without display conversion.
+ const float fixtures[][8] = {
+ {0, 0, 1, 2.7f, .75f, 0, 0, 0},
+ {.25f, 0, 1, 3, 1, 0, 0, 0}, // submerged object's short ray stays much clearer than the bed
+ {10, 0, 0, 2.7f, .75f, 0, 0, 0},
+ {10, 0, .5f, 2.7f, .75f, 0, 0, 0},
+ {10, 0, 1, 2.7f, .75f, 0, 0, 0}, // mission sea optical interpretation
+ {3.2f, 0, 0, 3, 1, 0, 0, 0},
+ {3.2f, 0, .5f, 3, 1, 0, 0, 0},
+ {3.2f, 0, 1, 3, 1, 0, 0, 0}, // shell sea optical interpretation
+ {2, 1, 0, 2.7f, .75f, 0, 0, 0},
+ {2, 1, .5f, 2.7f, .75f, 0, 0, 0},
+ {2, 1, 1, 2.7f, .75f, 0, 0, 0},
+ {180, 1, 0, 3, 0, 0, 0, 0},
+ {360, 1, 0, 3, 0, 0, 0, 0}, // no old 180-world-unit plateau
+ {100000, 1, 1, 3, 1, 0, 0, 0},
+ {-4, -1, -1, -1, -1, 0, 0, 0},
+ {.5f, 2, 2, 0, 2, 0, 0, 0},
+ {10, .5f, .5f, 2.7f, .75f, 0, 0, 0},
+ {1.0e20f, 0, 0, 1.0e20f, 0, 0, 0, 0}
+ };
+ const unsigned int count = sizeof(fixtures) / sizeof(fixtures[0]);
+ const char *vertex_source =
+ "float4 main(uint id : SV_VertexID) : SV_Position {\n"
+ "return float4(id == 1 ? 3.0 : -1.0, id == 2 ? 3.0 : -1.0, 0, 1); }\n";
+ std::string pixel_source = "cbuffer Samples : register(b0, space3) { float4 Fixtures[";
+ pixel_source += std::to_string(count * 2) + "]; };\n";
+ pixel_source += WaterOpticalModel::GetHlslSource();
+ pixel_source += "float main(float4 position : SV_Position) : SV_Target0 {\n"
+ "uint row=(uint)position.y; float4 f=Fixtures[row*2];\n"
+ "return WaterOpticalTransmission(f.x,f.y,f.z,f.w,Fixtures[row*2+1].x)[(uint)position.x]; }\n";
+ std::vector<unsigned char> spirv;
+ std::string error;
+ CHECK(SDL3_Compile_HLSL_To_SPIRV(vertex_source, true, spirv, error));
+ SDL_GPUShader *vertex = SDL3_Create_Shader(frame->Device(), spirv, true, error);
+ CHECK(SDL3_Compile_HLSL_To_SPIRV(pixel_source, false, spirv, error));
+ SDL_GPUShader *pixel = SDL3_Create_Shader(frame->Device(), spirv, false, error);
+ CHECK(vertex && pixel);
+ SDL_GPUColorTargetDescription description = {};
+ description.format = SDL_GPU_TEXTUREFORMAT_R32_FLOAT;
+ SDL_GPUGraphicsPipelineCreateInfo pipeline_info = {};
+ pipeline_info.vertex_shader = vertex;
+ pipeline_info.fragment_shader = pixel;
+ pipeline_info.primitive_type = SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;
+ pipeline_info.rasterizer_state.fill_mode = SDL_GPU_FILLMODE_FILL;
+ pipeline_info.rasterizer_state.cull_mode = SDL_GPU_CULLMODE_NONE;
+ pipeline_info.target_info.color_target_descriptions = &description;
+ pipeline_info.target_info.num_color_targets = 1;
+ SDL_GPUGraphicsPipeline *pipeline = SDL_CreateGPUGraphicsPipeline(frame->Device(), &pipeline_info);
+ SDL_GPUTextureCreateInfo texture_info = {};
+ texture_info.type = SDL_GPU_TEXTURETYPE_2D;
+ texture_info.format = SDL_GPU_TEXTUREFORMAT_R32_FLOAT;
+ texture_info.usage = SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;
+ texture_info.width = 3; texture_info.height = count;
+ texture_info.layer_count_or_depth = 1; texture_info.num_levels = 1;
+ SDL_GPUTexture *target = SDL_CreateGPUTexture(frame->Device(), &texture_info);
+ CHECK(pipeline && target);
+ CHECK(frame->Flush());
+ SDL_GPUCommandBuffer *commands = SDL_AcquireGPUCommandBuffer(frame->Device());
+ CHECK(commands != NULL);
+ SDL_GPUColorTargetInfo attachment = {};
+ attachment.texture = target;
+ attachment.load_op = SDL_GPU_LOADOP_DONT_CARE;
+ attachment.store_op = SDL_GPU_STOREOP_STORE;
+ SDL_GPURenderPass *pass = SDL_BeginGPURenderPass(commands, &attachment, 1, NULL);
+ CHECK(pass != NULL);
+ SDL_BindGPUGraphicsPipeline(pass, pipeline);
+ SDL_PushGPUFragmentUniformData(commands, 0, fixtures, sizeof(fixtures));
+ SDL_DrawGPUPrimitives(pass, 3, 1, 0, 0);
+ SDL_EndGPURenderPass(pass);
+ CHECK(SDL_SubmitGPUCommandBuffer(commands));
+ std::vector<uint8_t> bytes;
+ CHECK(frame->Read_Back(target, 3, count, bytes));
+ float max_model_error = 0;
+ for (unsigned int i=0; i<count; ++i) {
+ const WaterOpticalModel::RGB cpu=WaterOpticalModel::Transmission(
+ fixtures[i][0],fixtures[i][1],fixtures[i][2],fixtures[i][3],fixtures[i][4]);
+ const float expected[3]={cpu.r,cpu.g,cpu.b};
+ for (unsigned int c=0; c<3; ++c) {
+ const float gpu=depth_at(bytes,3,c,i),difference=fabsf(gpu-expected[c]);
+ if (difference>max_model_error) max_model_error=difference;
+ CHECK(gpu>=0 && gpu<=1 && difference<0.00001f);
+ CHECK(difference<=expected[c]*0.00003f+1e-36f);
+ }
+ }
+ for (unsigned int c=0;c<3;++c) {
+ CHECK(depth_at(bytes,3,c,0)==1.0f);
+ CHECK(depth_at(bytes,3,c,1)>depth_at(bytes,3,c,7));
+ CHECK(depth_at(bytes,3,c,2)>depth_at(bytes,3,c,3) && depth_at(bytes,3,c,3)>depth_at(bytes,3,c,4));
+ CHECK(depth_at(bytes,3,c,5)>depth_at(bytes,3,c,6) && depth_at(bytes,3,c,6)>depth_at(bytes,3,c,7));
+ CHECK(depth_at(bytes,3,c,12)<depth_at(bytes,3,c,11));
+ }
+ printf("sdl_gpu_frame_selfcheck: GPU water optical transmission: %u fixtures, max CPU model error %.9f\n",count,max_model_error);
+ SDL_ReleaseGPUTexture(frame->Device(),target);
+ SDL_ReleaseGPUGraphicsPipeline(frame->Device(),pipeline);
+ SDL_ReleaseGPUShader(frame->Device(),vertex);
+ SDL_ReleaseGPUShader(frame->Device(),pixel);
+}
+
+static void check_gpu_water_optical_ray_shift(SdlGpuFrame *frame)
+{
+ // delta-height, view.z, offshore, displacement bound, actual scene ray distance, camera distance.
+ const float fixtures[][8]={
+ {2,.8f,0,7,20,100,0,0}, {2,.8f,1,7,20,100,0,0}, {-2,.8f,1,7,20,100,0,0},
+ {2,.8f,.5f,7,20,100,0,0}, {1000,.8f,1,7,20,100,0,0}, {-1000,.8f,1,7,20,100,0,0},
+ {1000,.001f,1,7,100,100,0,0}, {-1000,.001f,1,7,100,100,0,0},
+ {1,0,1,7,20,100,0,0}, {1,-.8f,1,7,20,100,0,0},
+ {-2,.8f,1,7,.25f,100,0,0}, {-2,.8f,1,7,4,100,0,0}, // near object and farther bed
+ {2,.8f,1,7,20,.3f,0,0}, {-2,.8f,1,7,.03f,100,0,0}, {2,.8f,1,7,20,.04f,0,0},
+ {2,.8f,-1,7,20,100,0,0}, {2,.8f,2,7,20,100,0,0}, {-1,.2f,.5f,7,2.25f,100,0,0},
+ {-1000,.8f,1,0,20,100,0,0}
+ };
+ const unsigned int count=sizeof(fixtures)/sizeof(fixtures[0]),columns=4;
+ const char *vertex_source=
+ "float4 main(uint id : SV_VertexID) : SV_Position {\n"
+ "return float4(id == 1 ? 3.0 : -1.0, id == 2 ? 3.0 : -1.0, 0, 1); }\n";
+ std::string pixel_source="cbuffer Samples : register(b0, space3) { float4 Fixtures[";
+ pixel_source+=std::to_string(count*2)+"]; };\n";
+ pixel_source+=WaterOpticalModel::GetHlslSource();
+ pixel_source+="float main(float4 position : SV_Position) : SV_Target0 {\n"
+ "uint row=(uint)position.y,column=(uint)position.x; float4 f=Fixtures[row*2],g=Fixtures[row*2+1];\n"
+ "float shift=WaterOpticalRayShift(f.x,f.y,f.z,f.w,g.x,g.y);\n"
+ "if (column==0) return shift;\n"
+ "if (column==1) return 5+sqrt(max(1-f.y*f.y,0))*shift;\n"
+ "if (column==2) return 12+f.y*shift;\n"
+ "return WaterOpticalTransmission(abs(g.x+shift),0,1,3,.75).r; }\n";
+ std::vector<unsigned char> spirv;
+ std::string error;
+ CHECK(SDL3_Compile_HLSL_To_SPIRV(vertex_source,true,spirv,error));
+ SDL_GPUShader *vertex=SDL3_Create_Shader(frame->Device(),spirv,true,error);
+ CHECK(SDL3_Compile_HLSL_To_SPIRV(pixel_source,false,spirv,error));
+ SDL_GPUShader *pixel=SDL3_Create_Shader(frame->Device(),spirv,false,error);
+ CHECK(vertex && pixel);
+ SDL_GPUColorTargetDescription description={};
+ description.format=SDL_GPU_TEXTUREFORMAT_R32_FLOAT;
+ SDL_GPUGraphicsPipelineCreateInfo pipeline_info={};
+ pipeline_info.vertex_shader=vertex;pipeline_info.fragment_shader=pixel;
+ pipeline_info.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;
+ pipeline_info.rasterizer_state.fill_mode=SDL_GPU_FILLMODE_FILL;
+ pipeline_info.rasterizer_state.cull_mode=SDL_GPU_CULLMODE_NONE;
+ pipeline_info.target_info.color_target_descriptions=&description;
+ pipeline_info.target_info.num_color_targets=1;
+ SDL_GPUGraphicsPipeline *pipeline=SDL_CreateGPUGraphicsPipeline(frame->Device(),&pipeline_info);
+ SDL_GPUTextureCreateInfo texture_info={};
+ texture_info.type=SDL_GPU_TEXTURETYPE_2D;texture_info.format=SDL_GPU_TEXTUREFORMAT_R32_FLOAT;
+ texture_info.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;
+ texture_info.width=columns;texture_info.height=count;
+ texture_info.layer_count_or_depth=1;texture_info.num_levels=1;
+ SDL_GPUTexture *target=SDL_CreateGPUTexture(frame->Device(),&texture_info);
+ CHECK(pipeline && target);
+ CHECK(frame->Flush());
+ SDL_GPUCommandBuffer *commands=SDL_AcquireGPUCommandBuffer(frame->Device());
+ CHECK(commands!=NULL);
+ SDL_GPUColorTargetInfo attachment={};
+ attachment.texture=target;attachment.load_op=SDL_GPU_LOADOP_DONT_CARE;attachment.store_op=SDL_GPU_STOREOP_STORE;
+ SDL_GPURenderPass *pass=SDL_BeginGPURenderPass(commands,&attachment,1,NULL);
+ CHECK(pass!=NULL);
+ SDL_BindGPUGraphicsPipeline(pass,pipeline);
+ SDL_PushGPUFragmentUniformData(commands,0,fixtures,sizeof(fixtures));
+ SDL_DrawGPUPrimitives(pass,3,1,0,0);
+ SDL_EndGPURenderPass(pass);
+ CHECK(SDL_SubmitGPUCommandBuffer(commands));
+ std::vector<uint8_t> bytes;
+ CHECK(frame->Read_Back(target,columns,count,bytes));
+ float max_error=0;
+ for (unsigned int i=0;i<count;++i) {
+ using namespace WaterOpticalModel;
+ const float *f=fixtures[i],cpu=RayShift(f[0],f[1],f[2],f[3],f[4],f[5]);
+ const float vx=sqrtf(fmaxf(1-f[1]*f[1],0));
+ const float expected[4]={cpu,5+vx*cpu,12+f[1]*cpu,Transmission(fabsf(f[4]+cpu),0,1,3,.75f).r};
+ for (unsigned int c=0;c<columns;++c) {
+ const float gpu=depth_at(bytes,columns,c,i),difference=fabsf(gpu-expected[c]);
+ max_error=fmaxf(max_error,difference);
+ CHECK(std::isfinite(gpu) && difference<.00003f);
+ }
+ const float shift=depth_at(bytes,columns,0,i),x=depth_at(bytes,columns,1,i),z=depth_at(bytes,columns,2,i);
+ CHECK(fabsf(shift)<=2*f[3]/.2f+.00001f);
+ CHECK(f[4]+shift>=fminf(f[4],RaySurfaceMargin)-.00001f);
+ CHECK(f[5]-shift>=fminf(f[5],RaySurfaceMargin)-.00001f);
+ CHECK(fabsf((x-5)*f[1]-(z-12)*vx)<.00001f);
+ if (f[2]<=0 || f[1]<=0) CHECK(shift==0 && x==5 && z==12);
+ }
+ CHECK(depth_at(bytes,columns,0,1)==2.5f && depth_at(bytes,columns,0,2)==-2.5f);
+ CHECK(depth_at(bytes,columns,0,3)==1.25f);
+ CHECK(depth_at(bytes,columns,3,10)>depth_at(bytes,columns,3,11)); // object stays clearer than the bed
+ const float wrong_object=WaterOpticalModel::Transmission(fabsf(.25f-2.5f),0,1,3,.75f).r;
+ CHECK(wrong_object<depth_at(bytes,columns,3,11)); // control catches a shift that crossed the object
+ CHECK(fabsf(depth_at(bytes,columns,0,12)-.22f)<.000001f);
+ printf("sdl_gpu_frame_selfcheck: GPU optical ray correction: %u fixtures, max CPU/coordinate error %.9f; ray, bounds, near-object control passed\n",count,max_error);
+ SDL_ReleaseGPUTexture(frame->Device(),target);
+ SDL_ReleaseGPUGraphicsPipeline(frame->Device(),pipeline);
+ SDL_ReleaseGPUShader(frame->Device(),vertex);
+ SDL_ReleaseGPUShader(frame->Device(),pixel);
+}
+
+static void check_gpu_water_hull_distance(SdlGpuFrame *frame)
+{
+ using namespace WaterHullModel;
+ const unsigned count=16,columns=4;
+ struct Uniforms { Hull hulls[MaxHulls]; float fixtures[count][4]; } uniforms={};
+ const Point rectangle[]={{-100,-20},{100,-20},{100,20},{-100,20}};
+ for(unsigned vessel=0;vessel<MaxHulls;++vessel) {
+ Hull &h=uniforms.hulls[vessel];
+ h.data[0][0]=3028;h.data[0][1]=588;h.data[0][2]=7;h.data[0][3]=vessel==7?12.0f:4.0f;
+ h.data[1][0]=vessel==0?1.0f:0.0f;h.data[1][1]=vessel==0?0.0f:-1.0f;
+ h.data[1][2]=100;h.data[1][3]=vessel==7?100.0f:20.0f;
+ for(unsigned i=0;i<MaxVertices;++i) {
+ const float angle=float(i)*6.28318530718f/MaxVertices;
+ const Point p=vessel==7?Point{100*cosf(angle),100*sinf(angle)}:rectangle[i%4];
+ h.data[4+i/2][(i%2)*2]=p.x;h.data[4+i/2][(i%2)*2+1]=p.y;
+ }
+ }
+ const Point local[]={{0,0},{0,20},{0,24.5f},{0,29},{100,0},{105,25},{-101,-21},{0,-100},
+ {0,0},{0,24.5f},{105,25},{-101,-21},{0,0},{0,110},{98,-26},{86,-50}};
+ for(unsigned i=0;i<count;++i) {
+ const unsigned index=i<8?0:i<12?3:7;
+ const Hull &h=uniforms.hulls[index];const Point p=local[i];
+ uniforms.fixtures[i][0]=h.data[0][0]+p.x*h.data[1][0]-p.y*h.data[1][1];
+ uniforms.fixtures[i][1]=h.data[0][1]+p.x*h.data[1][1]+p.y*h.data[1][0];
+ uniforms.fixtures[i][2]=float(index);
+ }
+ const char *vertexSource="float4 main(uint id : SV_VertexID) : SV_Position {return float4(id==1?3.0:-1.0,id==2?3.0:-1.0,0,1);}";
+ std::string pixelSource="cbuffer Samples : register(b0, space3) { float4 HullData[80]; float4 Fixtures[16]; };\n";
+ pixelSource+=GetHlslSource();
+ pixelSource+="float main(float4 position : SV_Position) : SV_Target { uint row=(uint)position.y,column=(uint)position.x; "
+ "float4 f=Fixtures[row]; int baseIndex=(int)f.z*10; float2 delta=f.xy-HullData[baseIndex].xy,axis=HullData[baseIndex+1].xy; "
+ "float2 local=float2(dot(delta,axis),dot(delta,float2(-axis.y,axis.x))); "
+ "float distance=WaterHullSignedDistance(local,baseIndex,(int)HullData[baseIndex].w); "
+ "if(column==0) return distance; if(column==1) return smoothstep(0,9,distance); return local[column-2]; }";
+ std::vector<unsigned char> spirv;std::string error;
+ CHECK(SDL3_Compile_HLSL_To_SPIRV(vertexSource,true,spirv,error));
+ SDL_GPUShader *vertex=SDL3_Create_Shader(frame->Device(),spirv,true,error);
+ CHECK(SDL3_Compile_HLSL_To_SPIRV(pixelSource,false,spirv,error));
+ SDL_GPUShader *pixel=SDL3_Create_Shader(frame->Device(),spirv,false,error);CHECK(vertex && pixel);
+ SDL_GPUColorTargetDescription description={};description.format=SDL_GPU_TEXTUREFORMAT_R32_FLOAT;
+ SDL_GPUGraphicsPipelineCreateInfo pipelineInfo={};
+ pipelineInfo.vertex_shader=vertex;pipelineInfo.fragment_shader=pixel;
+ pipelineInfo.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;
+ pipelineInfo.rasterizer_state.fill_mode=SDL_GPU_FILLMODE_FILL;pipelineInfo.rasterizer_state.cull_mode=SDL_GPU_CULLMODE_NONE;
+ pipelineInfo.target_info.color_target_descriptions=&description;pipelineInfo.target_info.num_color_targets=1;
+ SDL_GPUGraphicsPipeline *pipeline=SDL_CreateGPUGraphicsPipeline(frame->Device(),&pipelineInfo);
+ SDL_GPUTextureCreateInfo textureInfo={};textureInfo.type=SDL_GPU_TEXTURETYPE_2D;textureInfo.format=SDL_GPU_TEXTUREFORMAT_R32_FLOAT;
+ textureInfo.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;textureInfo.width=columns;textureInfo.height=count;
+ textureInfo.layer_count_or_depth=1;textureInfo.num_levels=1;
+ SDL_GPUTexture *target=SDL_CreateGPUTexture(frame->Device(),&textureInfo);CHECK(pipeline && target);
+ CHECK(frame->Flush());SDL_GPUCommandBuffer *commands=SDL_AcquireGPUCommandBuffer(frame->Device());CHECK(commands);
+ SDL_GPUColorTargetInfo attachment={};attachment.texture=target;attachment.load_op=SDL_GPU_LOADOP_DONT_CARE;attachment.store_op=SDL_GPU_STOREOP_STORE;
+ SDL_GPURenderPass *pass=SDL_BeginGPURenderPass(commands,&attachment,1,NULL);CHECK(pass);
+ SDL_BindGPUGraphicsPipeline(pass,pipeline);SDL_PushGPUFragmentUniformData(commands,0,&uniforms,sizeof(uniforms));
+ SDL_DrawGPUPrimitives(pass,3,1,0,0);SDL_EndGPURenderPass(pass);CHECK(SDL_SubmitGPUCommandBuffer(commands));
+ std::vector<uint8_t> bytes;CHECK(frame->Read_Back(target,columns,count,bytes));float maxError=0;
+ for(unsigned i=0;i<count;++i) {
+ const Hull &h=uniforms.hulls[(unsigned)uniforms.fixtures[i][2]];
+ const Point p=LocalPoint(h,uniforms.fixtures[i][0],uniforms.fixtures[i][1]);
+ const float cpu=SignedDistance(p,Unpack(h)),damping=Damping(h,uniforms.fixtures[i][0],uniforms.fixtures[i][1],7);
+ const float expected[]={cpu,damping,p.x,p.y};
+ for(unsigned c=0;c<4;++c) {const float e=fabsf(depth_at(bytes,columns,c,i)-expected[c]);maxError=fmaxf(maxError,e);CHECK(e<.0003f);}
+ if(i<12) { // Independent exact rectangle SDF, including outside corners and inside sign.
+ const float qx=fabsf(local[i].x)-100,qy=fabsf(local[i].y)-20;
+ const float exact=sqrtf(fmaxf(qx,0)*fmaxf(qx,0)+fmaxf(qy,0)*fmaxf(qy,0))+fminf(fmaxf(qx,qy),0);
+ CHECK(fabsf(depth_at(bytes,columns,0,i)-exact)<.0003f);
+ }
+ }
+ CHECK(depth_at(bytes,columns,0,0)<0 && depth_at(bytes,columns,0,2)>0);
+ CHECK(fabsf(depth_at(bytes,columns,1,2)-.5f)<.00001f);
+ // Last vertex matters: collapsing it measurably moves the lower-right edge of the last hull.
+ Polygon missing=Unpack(uniforms.hulls[7]);--missing.count;
+ CHECK(fabsf(SignedDistance(local[14],missing)-depth_at(bytes,columns,0,14))>2);
+ printf("sdl_gpu_frame_selfcheck: GPU hull contours: %u fixtures, max CPU/rotation error %.7f; exact rectangle, final vertex, sign and damping controls passed\n",count,maxError);
+ SDL_ReleaseGPUTexture(frame->Device(),target);SDL_ReleaseGPUGraphicsPipeline(frame->Device(),pipeline);
+ SDL_ReleaseGPUShader(frame->Device(),vertex);SDL_ReleaseGPUShader(frame->Device(),pixel);
+}
+
+// These are renderer fixtures, not injected gameplay velocities. The stable USA02 save has
+// stationary ships and no PT-boat patrol script, so it cannot validate moving-vessel integration.
+// Render the production wake function over an independently specified rectangular waterline.
+#if defined(__linux__)
+static void check_gpu_water_hull_effects(SdlGpuFrame *frame)
+{
+ using namespace WaterHullModel;
+ const unsigned samplesX=301,samplesY=81,channels=3,width=samplesX*channels;
+ struct Uniforms {
+ float hullParameters[4]; Hull hulls[MaxHulls];
+ float query[4],testBasis[4],waveInput[4]; // level,time,offshore,footprint; origin XY,forward XY; height/impact
+ Hull contactHulls[MaxHulls];
+ } uniforms={};
+ uniforms.hullParameters[0]=1;
+ uniforms.query[0]=7;uniforms.query[1]=1.25f;uniforms.query[2]=1;uniforms.query[3]=.5f;
+ uniforms.testBasis[2]=1;
+ uniforms.waveInput[0]=.75f;uniforms.waveInput[1]=.6f;
+ Hull &h=uniforms.hulls[0];
+ h.data[0][2]=7;h.data[0][3]=4;
+ h.data[1][0]=1;h.data[1][2]=20;h.data[1][3]=4;
+ h.data[2][2]=.37f;h.data[2][3]=sqrtf(20*20+4*4);
+ h.data[3][0]=-20;h.data[3][2]=20;
+ const Point rectangle[]={{-20,-4},{20,-4},{20,4},{-20,4}};
+ for(unsigned i=0;i<MaxVertices;++i) {
+ h.data[4+i/2][(i%2)*2]=rectangle[i%4].x;
+ h.data[4+i/2][(i%2)*2+1]=rectangle[i%4].y;
+ }
+ const Uniforms stationaryUniforms=uniforms;
+ PixelPipelineDescription waterPipeline={};
+ std::string waterSource;
+ CHECK(EngineShader_Pixel_Program(ENGINE_SHADER_WATER_TRAPEZOID,waterPipeline,waterSource,COMBINER_SHADER_TARGET_SDL3_GPU));
+ // Import the exact production noise dependency, not a test-only constant or copy that could
+ // hide broken animated wash. The tested effects body is also the production header emission.
+ const size_t noiseStart=waterSource.find("float oceanHash("),noiseEnd=waterSource.find("float3 oceanSky(");
+ CHECK(noiseStart!=std::string::npos && noiseEnd!=std::string::npos && noiseEnd>noiseStart);
+ if(noiseStart==std::string::npos || noiseEnd==std::string::npos || noiseEnd<=noiseStart) return;
+ const char *vertexSource="float4 main(uint id : SV_VertexID) : SV_Position {return float4(id==1?3.0:-1.0,id==2?3.0:-1.0,0,1);}";
+ std::string pixelSource="cbuffer Samples : register(b0, space3) { float4 HullParameters; float4 HullData[80]; float4 Query; float4 TestBasis; float4 WaveInput; float4 ContactHullData[80]; };\n";
+ pixelSource+=waterSource.substr(noiseStart,noiseEnd-noiseStart);
+ pixelSource+=GetHlslSource();pixelSource+=GetEffectsHlslSource(true);
+ pixelSource+="float main(float4 pixel : SV_Position) : SV_Target { "
+ "uint column=(uint)pixel.x, channel=column%3; float2 local=float2((int)(column/3)-150,(int)pixel.y-40); "
+ "float2 world=TestBasis.xy+local.x*TestBasis.zw+local.y*float2(-TestBasis.w,TestBasis.z); "
+ "return oceanHullEffects(world,Query.x,Query.y,Query.z,WaveInput.x,Query.w,WaveInput.y)[channel]; }";
+ std::vector<unsigned char> spirv;std::string error;
+ bool compiled=SDL3_Compile_HLSL_To_SPIRV(vertexSource,true,spirv,error);CHECK(compiled);
+ if(!compiled) {printf("wake vertex compile: %s\n",error.c_str());return;}
+ SDL_GPUShader *vertex=SDL3_Create_Shader(frame->Device(),spirv,true,error);
+ compiled=SDL3_Compile_HLSL_To_SPIRV(pixelSource,false,spirv,error);CHECK(compiled);
+ if(!compiled) {printf("wake pixel compile: %s\n",error.c_str());SDL_ReleaseGPUShader(frame->Device(),vertex);return;}
+ SDL_GPUShader *pixel=SDL3_Create_Shader(frame->Device(),spirv,false,error);CHECK(vertex && pixel);
+ if(!vertex || !pixel) return;
+ SDL_GPUColorTargetDescription description={};description.format=SDL_GPU_TEXTUREFORMAT_R32_FLOAT;
+ SDL_GPUGraphicsPipelineCreateInfo pipelineInfo={};pipelineInfo.vertex_shader=vertex;pipelineInfo.fragment_shader=pixel;
+ pipelineInfo.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;
+ pipelineInfo.rasterizer_state.fill_mode=SDL_GPU_FILLMODE_FILL;pipelineInfo.rasterizer_state.cull_mode=SDL_GPU_CULLMODE_NONE;
+ pipelineInfo.target_info.color_target_descriptions=&description;pipelineInfo.target_info.num_color_targets=1;
+ SDL_GPUGraphicsPipeline *pipeline=SDL_CreateGPUGraphicsPipeline(frame->Device(),&pipelineInfo);
+ SDL_GPUTextureCreateInfo textureInfo={};textureInfo.type=SDL_GPU_TEXTURETYPE_2D;textureInfo.format=SDL_GPU_TEXTUREFORMAT_R32_FLOAT;
+ textureInfo.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;textureInfo.width=width;textureInfo.height=samplesY;
+ textureInfo.layer_count_or_depth=1;textureInfo.num_levels=1;
+ SDL_GPUTexture *target=SDL_CreateGPUTexture(frame->Device(),&textureInfo);CHECK(pipeline && target);
+ if(!pipeline || !target) return;
+ CHECK(frame->Flush());unsigned renders=0;
+ auto render=[&]() {
+ SDL_GPUCommandBuffer *commands=SDL_AcquireGPUCommandBuffer(frame->Device());CHECK(commands);
+ SDL_GPUColorTargetInfo attachment={};attachment.texture=target;attachment.load_op=SDL_GPU_LOADOP_DONT_CARE;attachment.store_op=SDL_GPU_STOREOP_STORE;
+ SDL_GPURenderPass *pass=SDL_BeginGPURenderPass(commands,&attachment,1,NULL);CHECK(pass);
+ SDL_BindGPUGraphicsPipeline(pass,pipeline);SDL_PushGPUFragmentUniformData(commands,0,&uniforms,sizeof(uniforms));
+ SDL_DrawGPUPrimitives(pass,3,1,0,0);SDL_EndGPURenderPass(pass);CHECK(SDL_SubmitGPUCommandBuffer(commands));
+ std::vector<uint8_t> bytes;CHECK(frame->Read_Back(target,width,samplesY,bytes));++renders;
+ bool bounded=true;
+ for(unsigned y=0;y<samplesY;++y) for(unsigned x=0;x<width;++x) {
+ const float v=depth_at(bytes,width,x,y);bounded &= std::isfinite(v) && v>=0 && v<=1;
+ }
+ CHECK(bounded);return bytes;
+ };
+ auto value=[&](const std::vector<uint8_t>& bytes,int x,int y,unsigned channel) {
+ return depth_at(bytes,width,unsigned(x+150)*channels+channel,unsigned(y+40));
+ };
+ auto empty=[&](const std::vector<uint8_t>& bytes) {
+ bool ok=true;
+ for(int y=-40;y<=40;++y) for(int x=-150;x<=150;++x)
+ ok &= value(bytes,x,y,0)==0 && value(bytes,x,y,1)==0 && value(bytes,x,y,2)==1;
+ CHECK(ok);
+ };
+ const auto stationary=render();
+ // An idle hull needs incoming-wave impact for foam. Its thin, broken side wash cannot turn
+ // into a propulsion trail or fill the hull interior; count clean and foamy sections separately.
+ unsigned sideSamples=0,sideFoamy=0,sideClean=0;bool washBounded=true;
+ for(int y=-40;y<=40;++y) for(int x=-150;x<=150;++x) {
+ const float dx=fmaxf(fabsf(float(x))-20,0),dy=fmaxf(fabsf(float(y))-4,0);
+ const float distance=sqrtf(dx*dx+dy*dy),foam=value(stationary,x,y,0);
+ if(abs(x)<=15 && abs(y)>=5 && abs(y)<=8) {
+ ++sideSamples;if(foam>.005f)++sideFoamy;if(foam<.005f)++sideClean;
+ }
+ if(distance>=7 || (abs(x)<20 && abs(y)<4))
+ washBounded &= foam==0 && value(stationary,x,y,1)==0;
+ }
+ CHECK(washBounded && sideFoamy>8 && sideClean>sideSamples/4);
+ // A flat crest still has contact energy; calm requires both height and slope zero.
+ uniforms.waveInput[0]=WaterHullContactFoam::HeightScale;uniforms.waveInput[1]=0;
+ const auto crestContact=render();CHECK(value(crestContact,0,5,0)>.24f);
+ uniforms.waveInput[0]=-WaterHullContactFoam::HeightScale;
+ const auto troughContact=render();CHECK(value(troughContact,0,5,0)==0);
+ uniforms.waveInput[0]=0;uniforms.waveInput[1]=0;const auto calm=render();bool impactGated=true;
+ for(int y=-40;y<=40;++y)for(int x=-150;x<=150;++x)
+ impactGated &= value(calm,x,y,0)==0 && value(calm,x,y,1)==0 && value(calm,x,y,2)==value(stationary,x,y,2);
+ CHECK(impactGated);uniforms=stationaryUniforms;
+ uniforms.hulls[0].data[2][0]=.3f;const auto threshold=render();CHECK(threshold==stationary);
+ uniforms.hulls[0].data[2][0]=6.3f;const auto forward=render();
+ // Fresh turbulence stays attached to the actual stern, with a broad central region. The
+ // persistent world-space atlas now owns the long wake, so this field must remain local.
+ bool connected=true;
+ for(int behind=1;behind<=10;++behind) {
+ connected &= value(forward,-20-behind,0,1)>.05f;
+ }
+ CHECK(connected);
+ CHECK(value(forward,-35,0,1)>.1f && value(stationary,-35,0,1)==0);
+ CHECK(value(forward,-30,0,1)>.15f && value(forward,-30,12,1)<.01f && value(forward,-30,-12,1)<.01f);
+ float bowIncrease=0,sideIncrease=0;
+ for(int x=20;x<=23;++x)for(int y=-2;y<=2;++y)
+ bowIncrease=fmaxf(bowIncrease,value(forward,x,y,0)-value(stationary,x,y,0));
+ for(int x=-10;x<=10;++x)for(int y:{-5,5})
+ sideIncrease=fmaxf(sideIncrease,value(forward,x,y,0)-value(stationary,x,y,0));
+ CHECK(bowIncrease>.05f && bowIncrease>sideIncrease); // bow response is concentrated, not a uniform halo
+ bool forwardBounds=true;
+ for(int y=-40;y<=40;++y) for(int x=-150;x<=150;++x)
+ if(x<=-44 || x>=33) forwardBounds &= value(forward,x,y,0)==0 && value(forward,x,y,1)==0;
+ CHECK(forwardBounds);
+ // Heading and world translation must not move the wake relative to its actual hull. A 90deg
+ // rotation is exact in floating point, so this is sensitive to world/local velocity mistakes.
+ uniforms.hulls[0].data[0][0]=3028;uniforms.hulls[0].data[0][1]=588;
+ uniforms.hulls[0].data[1][0]=0;uniforms.hulls[0].data[1][1]=1;
+ uniforms.hulls[0].data[2][0]=0;uniforms.hulls[0].data[2][1]=6.3f;
+ uniforms.testBasis[0]=3028;uniforms.testBasis[1]=588;uniforms.testBasis[2]=0;uniforms.testBasis[3]=1;
+ const auto rotated=render();CHECK(rotated==forward);
+ uniforms=stationaryUniforms;uniforms.hulls[0].data[2][0]=-6.3f;
+ const auto reverse=render();
+ bool reversed=true;
+ for(int ahead=1;ahead<=10;++ahead) reversed &= value(reverse,20+ahead,0,1)>.05f;
+ CHECK(reversed && value(reverse,35,0,1)>.1f && value(reverse,-35,0,1)==0);
+ CHECK(value(forward,35,0,1)==0); // Armed wrong-end control: forward's bow must not emit a trail.
+ // Near sideways travel the physical wave origin blends across the hull. Foam must use the
+ // same continuous endpoint selection, instead of jumping forty units on a velocity sign flip.
+ uniforms=stationaryUniforms;uniforms.hulls[0].data[2][0]=.00001f;uniforms.hulls[0].data[2][1]=6.3f;
+ const auto broadsidePositive=render();uniforms.hulls[0].data[2][0]=-.00001f;
+ const auto broadsideNegative=render();float broadsideChange=0;
+ CHECK(value(broadsidePositive,0,-15,1)>.1f && value(broadsideNegative,0,-15,1)>.1f);
+ for(int y=-40;y<=40;++y) for(int x=-150;x<=150;++x) for(unsigned c=0;c<3;++c)
+ broadsideChange=fmaxf(broadsideChange,fabsf(value(broadsidePositive,x,y,c)-value(broadsideNegative,x,y,c)));
+ CHECK(broadsideChange<.002f);
+ // Force both endpoint choices to each old hard-selected end. This armed control must expose
+ // a large jump in exactly the atlas and travel direction used by the continuity assertion.
+ uniforms.hulls[0].data[3][0]=uniforms.hulls[0].data[3][2]=-20;const auto forcedLeft=render();
+ uniforms.hulls[0].data[3][0]=uniforms.hulls[0].data[3][2]=20;const auto forcedRight=render();
+ CHECK(value(forcedLeft,-20,-15,1)-value(forcedRight,-20,-15,1)>.1f);
+ uniforms=stationaryUniforms;uniforms.hulls[0].data[2][0]=6.3f;
+ uniforms.query[2]=0;empty(render());
+ uniforms.query[2]=1;uniforms.query[0]=7.11f;empty(render());
+ uniforms.query[0]=7;uniforms.hullParameters[0]=0;empty(render());
+ uniforms.hullParameters[0]=1;uniforms.query[2]=.25f;const auto transition=render();
+ bool blended=true;
+ for(int y=-40;y<=40;++y) for(int x=-150;x<=150;++x) for(unsigned c=0;c<3;++c)
+ blended &= fabsf(value(transition,x,y,c)-value(forward,x,y,c)*(c==2?1.0f:.25f))<.000001f;
+ CHECK(blended);
+ uniforms.query[2]=1;const auto paused=render();CHECK(paused==forward);
+ uniforms.query[1]+=1.0f;const auto animated=render();unsigned changed=0;
+ for(int y=-40;y<=40;++y) for(int x=-150;x<=150;++x)
+ if(fabsf(value(animated,x,y,0)-value(forward,x,y,0))>.005f) ++changed;
+ CHECK(changed>50);
+ uniforms=stationaryUniforms;uniforms.hulls[0].data[2][0]=60;
+ const auto capped=render();bool lengthBounded=true;
+ for(int y=-40;y<=40;++y) for(int x=-150;x<=-130;++x)
+ lengthBounded &= value(capped,x,y,0)==0 && value(capped,x,y,1)==0;
+ for(int y=-40;y<=40;++y)for(int x=-150;x<=-65;++x)
+ lengthBounded &= value(capped,x,y,0)==0 && value(capped,x,y,1)==0;
+ CHECK(lengthBounded && value(capped,-100,0,1)==0 && value(capped,-35,0,1)>2*value(forward,-35,0,1));
+ // All eight array entries are legal. Only the final hull matches this level: a truncated count
+ // or bad ten-register stride must lose the entire result, rather than accidentally pass.
+ uniforms=stationaryUniforms;uniforms.hulls[0].data[2][0]=6.3f;
+ uniforms.hulls[7]=uniforms.hulls[0];uniforms.hulls[0]=Hull();uniforms.hullParameters[0]=8;
+ const auto lastHull=render();CHECK(lastHull==forward);
+ // Contact geometry may be wider and offset from the exact mean-water slice. Construct an
+ // independent reference by moving the original mean-only fixture to that shape, then require
+ // only foam/churn to match it: the new contact path must retain the original damping field.
+ uniforms=stationaryUniforms;uniforms.hulls[0].data[2][0]=6.3f;
+ Hull contact=uniforms.hulls[0];contact.data[0][0]=3;contact.data[0][1]=7;
+ contact.data[1][3]=10;contact.data[2][3]=sqrtf(20*20+10*10);
+ for(unsigned i=0;i<MaxVertices;++i) contact.data[4+i/2][(i%2)*2+1]*=2.5f;
+ uniforms.hulls[0]=contact;const auto contactReference=render();
+ uniforms=stationaryUniforms;uniforms.hulls[0].data[2][0]=6.3f;uniforms.contactHulls[0]=contact;
+ const auto contactResult=render();bool contactMatches=true,meanDampingPreserved=true;
+ unsigned newContourFoam=0;float armedContactDifference=0;
+ for(int y=-40;y<=40;++y)for(int x=-150;x<=150;++x) {
+ for(unsigned c=0;c<2;++c) contactMatches &= value(contactResult,x,y,c)==value(contactReference,x,y,c);
+ meanDampingPreserved &= value(contactResult,x,y,2)==value(forward,x,y,2);
+ armedContactDifference=fmaxf(armedContactDifference,fabsf(value(contactResult,x,y,0)-value(forward,x,y,0)));
+ if(y>=18 && y<=20 && x>=-12 && x<=18 && value(contactResult,x,y,0)>.005f && value(forward,x,y,0)==0)
+ ++newContourFoam;
+ }
+ CHECK(contactMatches && meanDampingPreserved && newContourFoam>8 && armedContactDifference>.1f);
+ // The optional count alone controls fallback, regardless of stale remaining registers.
+ uniforms.contactHulls[0].data[0][3]=2;CHECK(render()==forward);
+ uniforms.contactHulls[0]=Hull();CHECK(render()==forward);
+ // A valid contact is paired with its mean hull index, including the last array entry. It
+ // must obey the same local-to-world rotation as an ordinary contour, and its water level.
+ uniforms.contactHulls[0]=contact;uniforms.contactHulls[7]=contact;
+ uniforms.contactHulls[0]=Hull();uniforms.hulls[7]=uniforms.hulls[0];uniforms.hulls[0]=Hull();uniforms.hullParameters[0]=8;
+ CHECK(render()==contactResult);
+ uniforms.contactHulls[7].data[0][2]=7.11f;const auto wrongContactLevel=render();bool contactLevelGated=true;
+ for(int y=-40;y<=40;++y)for(int x=-150;x<=150;++x)
+ contactLevelGated &= value(wrongContactLevel,x,y,0)==0 && value(wrongContactLevel,x,y,1)==0
+ && value(wrongContactLevel,x,y,2)==value(forward,x,y,2);
+ CHECK(contactLevelGated);
+ uniforms=stationaryUniforms;uniforms.hulls[0].data[2][0]=6.3f;uniforms.contactHulls[0]=contact;
+ for(Hull *v:{&uniforms.hulls[0],&uniforms.contactHulls[0]}) {
+ const float oldX=v->data[0][0],oldY=v->data[0][1];
+ v->data[0][0]=3028-oldY;v->data[0][1]=588+oldX;
+ v->data[1][0]=0;v->data[1][1]=1;v->data[2][0]=0;v->data[2][1]=6.3f;
+ }
+ uniforms.testBasis[0]=3028;uniforms.testBasis[1]=588;uniforms.testBasis[2]=0;uniforms.testBasis[3]=1;
+ CHECK(render()==contactResult);
+ printf("sdl_gpu_frame_selfcheck: GPU separate contact hull: shifted/wider foam matches independent mean-only reference, %u new contour foam samples, armed mean-only difference %.6f, mean damping exact, invalid/zero fallback, last hull, level and rigid transform checked\n",newContourFoam,armedContactDifference);
+ printf("sdl_gpu_frame_selfcheck: GPU production hull wash/wake: %u spatial renders, %u pixels each; thin side wash %u/%u with %u clean sections, impact gate, concentrated bow %.5f versus side %.5f, local central stern churn, speed/reverse/broadside continuity %.8f with armed snap control, rigid transform, level/offshore, pause, animation (%u foam pixels), 44-unit stern bound and final hull checked\n",renders,samplesX*samplesY,sideFoamy,sideSamples,sideClean,bowIncrease,sideIncrease,broadsideChange,changed);
+ SDL_ReleaseGPUTexture(frame->Device(),target);SDL_ReleaseGPUGraphicsPipeline(frame->Device(),pipeline);
+ SDL_ReleaseGPUShader(frame->Device(),vertex);SDL_ReleaseGPUShader(frame->Device(),pixel);
+}
+#endif // __linux__
+
+// A float readback used only by verification. Runtime FFT never reads a result back to the CPU.
+static std::vector<float> read_float_targets(SdlGpuFrame *frame,SDL_GPUTexture *const *textures,
+ unsigned count,unsigned width,unsigned height,unsigned mip=0)
+{
+ const unsigned bytes=width*height*4*sizeof(float),total=count*bytes;
+ std::vector<float> result(total/sizeof(float));
+ CHECK(frame->Flush());
+ SDL_GPUTransferBufferCreateInfo info={};info.usage=SDL_GPU_TRANSFERBUFFERUSAGE_DOWNLOAD;info.size=total;
+ SDL_GPUTransferBuffer *transfer=SDL_CreateGPUTransferBuffer(frame->Device(),&info);CHECK(transfer);
+ if(!transfer) return result;
+ SDL_GPUCommandBuffer *commands=SDL_AcquireGPUCommandBuffer(frame->Device());CHECK(commands);
+ if(!commands) {SDL_ReleaseGPUTransferBuffer(frame->Device(),transfer);return result;}
+ SDL_GPUCopyPass *copy=SDL_BeginGPUCopyPass(commands);CHECK(copy);
+ for(unsigned i=0;i<count;++i) {
+ SDL_GPUTextureRegion region={};region.texture=textures[i];region.w=width;region.h=height;region.d=1;region.mip_level=mip;
+ SDL_GPUTextureTransferInfo destination={};destination.transfer_buffer=transfer;destination.offset=i*bytes;
+ destination.pixels_per_row=width;destination.rows_per_layer=height;
+ SDL_DownloadFromGPUTexture(copy,&region,&destination);
+ }
+ SDL_EndGPUCopyPass(copy);SDL_GPUFence *fence=SDL_SubmitGPUCommandBufferAndAcquireFence(commands);CHECK(fence);
+ if(fence) {
+ CHECK(SDL_WaitForGPUFences(frame->Device(),true,&fence,1));SDL_ReleaseGPUFence(frame->Device(),fence);
+ const void *mapped=SDL_MapGPUTransferBuffer(frame->Device(),transfer,false);CHECK(mapped);
+ if(mapped) {memcpy(result.data(),mapped,total);SDL_UnmapGPUTransferBuffer(frame->Device(),transfer);}
+ }
+ SDL_ReleaseGPUTransferBuffer(frame->Device(),transfer);return result;
+}
+
+// Verify depth-aware colour filtering with an explicit independent valid-tap case table.
+#if defined(__linux__)
+static void check_gpu_water_refraction_footprint(SdlGpuFrame *frame)
+{
+ const unsigned rows=27,columns=3;
+ struct Resources {
+ SDL_GPUDevice *device;
+ SDL_GPUShader *vertex=NULL,*pixel=NULL;
+ SDL_GPUGraphicsPipeline *pipeline=NULL;
+ SDL_GPUTexture *target=NULL,*colour=NULL,*depth=NULL,*white=NULL;
+ SDL_GPUSampler *linear=NULL,*point=NULL;
+ ~Resources() {
+ if(pipeline) SDL_ReleaseGPUGraphicsPipeline(device,pipeline);
+ if(vertex) SDL_ReleaseGPUShader(device,vertex);
+ if(pixel) SDL_ReleaseGPUShader(device,pixel);
+ if(target) SDL_ReleaseGPUTexture(device,target);
+ if(colour) SDL_ReleaseGPUTexture(device,colour);
+ if(depth) SDL_ReleaseGPUTexture(device,depth);
+ if(white) SDL_ReleaseGPUTexture(device,white);
+ if(linear) SDL_ReleaseGPUSampler(device,linear);
+ if(point) SDL_ReleaseGPUSampler(device,point);
+ }
+ } r;
+ r.device=frame->Device();
+ PixelPipelineDescription pd={};std::string ps;
+ const char *oldDebug=getenv("ZH_WATER_DEBUG");const bool hadDebug=oldDebug!=NULL;
+ const std::string savedDebug=oldDebug?oldDebug:"";
+ // This isolated optical probe reserves b1 for its cases, with no hull packets.
+ const char *oldContact=getenv("ZH_WATER_HULL_CONTACT");const bool hadContact=oldContact!=NULL;
+ const std::string savedContact=oldContact?oldContact:"";
+ CHECK(setenv("ZH_WATER_HULL_CONTACT","0",1)==0);
+ CHECK(unsetenv("ZH_WATER_DEBUG")==0);
+ const bool generated=EngineShader_Pixel_Program(ENGINE_SHADER_WATER_TRAPEZOID,pd,ps,
+ COMBINER_SHADER_TARGET_SDL3_GPU);
+ if(hadDebug)CHECK(setenv("ZH_WATER_DEBUG",savedDebug.c_str(),1)==0);
+ else CHECK(unsetenv("ZH_WATER_DEBUG")==0);
+ if(hadContact)CHECK(setenv("ZH_WATER_HULL_CONTACT",savedContact.c_str(),1)==0);
+ else CHECK(unsetenv("ZH_WATER_HULL_CONTACT")==0);
+ CHECK(generated);if(!generated)return;
+ const std::string entry="float4 main(Input input)";
+ const size_t at=ps.find(entry);CHECK(at!=std::string::npos);if(at==std::string::npos)return;
+ ps.replace(at,entry.size(),"float4 unusedWaterMain(Input input)");
+ ps+=R"M4C(
+cbuffer M4cCases : register(b1, space3) { float4 M4cFixtures[27 * 3]; };
+// Armed M4A nearest-only control, retaining its corrected sign/shared viewport behaviour.
+WaterRefractionSample m4cNearestOnly(float2 originalPixel,float2 offset,float3 world,
+ float3 opticalWorld,float3 view,float3 originalBottom)
+{
+ WaterRefractionSample r;
+ float2 origin=waterScenePixel(originalPixel),candidate=waterScenePixel(originalPixel+offset);
+ float3 hit=bottomPosition(candidate,world,0);
+ float valid=step(hit.z,min(world.z,opticalWorld.z)-.08)
+ *step(0.0,min(dot(hit-world,-view),dot(hit-opticalWorld,-view)));
+ r.pixel=lerp(origin,candidate,valid);r.bottom=lerp(originalBottom,hit,valid);r.accepted=valid;
+ r.colour=Texture5.SampleLevel(Sampler5,r.pixel*SceneParameters.yz,0).rgb;
+ return r;
+}
+float4 main(float4 position:SV_Position):SV_Target0
+{
+ uint row=(uint)position.y,column=(uint)position.x;
+ float4 a=M4cFixtures[row*3],b=M4cFixtures[row*3+1],c=M4cFixtures[row*3+2];
+ float3 world=scenePosition(a.xy,0),opticalWorld=world+b.xyz*b.w;
+ float3 originalBottom=bottomPosition(a.xy,world,0);
+ WaterRefractionSample s;
+ if(c.x>.5) s=m4cNearestOnly(a.xy,a.zw,world,opticalWorld,b.xyz,originalBottom);
+ else s=waterRefractedScene(a.xy,a.zw,world,opticalWorld,b.xyz,0,originalBottom);
+ if(column==0)return float4(s.pixel,s.accepted,length(s.bottom-opticalWorld));
+ if(column==1)return float4(s.colour,1);
+ return float4(s.bottom,1);
+}
+
+)M4C";
+ const char *vs="float4 main(uint id:SV_VertexID):SV_Position { return float4(id==1?3.0:-1.0,id==2?3.0:-1.0,0,1); }";
+ std::string error;std::vector<unsigned char> spirv;
+ bool compiled=SDL3_Compile_HLSL_To_SPIRV(vs,true,spirv,error);CHECK(compiled);if(!compiled)return;
+ r.vertex=SDL3_Create_Shader(r.device,spirv,true,error);CHECK(r.vertex);if(!r.vertex)return;
+ compiled=SDL3_Compile_HLSL_To_SPIRV(ps,false,spirv,error);CHECK(compiled);
+ if(!compiled){printf("M4D production helper compile: %s\n",error.c_str());return;}
+ unsigned samplers=0,uniforms=0;SDL3_Shader_Slots(spirv,false,samplers,uniforms);
+ CHECK(samplers<=16 && uniforms==2);if(samplers>16 || uniforms!=2)return;
+ r.pixel=SDL3_Create_Shader(r.device,spirv,false,error);CHECK(r.pixel);if(!r.pixel)return;
+ SDL_GPUColorTargetDescription colourDescription={};colourDescription.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
+ SDL_GPUGraphicsPipelineCreateInfo pi={};pi.vertex_shader=r.vertex;pi.fragment_shader=r.pixel;
+ pi.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;pi.rasterizer_state.cull_mode=SDL_GPU_CULLMODE_NONE;
+ pi.target_info.color_target_descriptions=&colourDescription;pi.target_info.num_color_targets=1;
+ r.pipeline=SDL_CreateGPUGraphicsPipeline(r.device,&pi);CHECK(r.pipeline);if(!r.pipeline)return;
+ SDL_GPUTextureCreateInfo ti={};ti.type=SDL_GPU_TEXTURETYPE_2D;ti.format=colourDescription.format;
+ ti.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;ti.width=columns;ti.height=rows;ti.layer_count_or_depth=ti.num_levels=1;
+ r.target=SDL_CreateGPUTexture(r.device,&ti);CHECK(r.target);if(!r.target)return;
+ SDL_GPUSamplerCreateInfo si={};si.address_mode_u=si.address_mode_v=si.address_mode_w=SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
+ si.min_filter=si.mag_filter=SDL_GPU_FILTER_LINEAR;si.mipmap_mode=SDL_GPU_SAMPLERMIPMAPMODE_NEAREST;
+ r.linear=SDL_CreateGPUSampler(r.device,&si);si.min_filter=si.mag_filter=SDL_GPU_FILTER_NEAREST;
+ r.point=SDL_CreateGPUSampler(r.device,&si);CHECK(r.linear && r.point);if(!r.linear || !r.point)return;
+ const float offsets[rows][2]={
+ {.25f,.375f},{.25f,0},{0,.25f},{.25f,.25f},{0,0},{.75f,0},{.25f,0},
+ {.25f,0},{.25f,0},{.25f,0},{8,0},{8,8},{-.25f,-.25f},{.75f,.875f},
+ {.25f,0},{-8,0},{.25f,0},{.25f,0},{.5f,.5f},{.75f,.25f},{.25f,.75f},
+ {.75f,.375f},{.75f,.75f},{.25f,.375f},{.25f,.375f},{.75f,.875f},{.5f,.5f}
+ };
+ // Independent case truth: bit0=lower-left in texture coordinates (x,y), bit1=(x+1,y),
+ // bit2=(x,y+1), bit3=(x+1,y+1). These masks are authored, not recomputed from shader rules.
+ const unsigned validTaps[rows]={15,13,11,7,13,13,13,13,13,13,15,15,14,15,13,15,13,15,15,15,15,
+ 10,8,15,7,7,8};
+ const bool accepted[rows]={true,true,true,true,true,false,true,true,true,true,
+ true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,false,true};
+ unsigned renders=0,armedLeaks=0,checked=0,missingColourChecks=0;
+ CHECK(frame->Flush());
+ for(unsigned resize=0;resize<2;++resize) {
+ const unsigned width=40u<<resize,height=(rows*4+12)<<resize;
+ const float viewportWidth=24,viewportHeight=float(rows*4+4),lastX=27.5f,lastY=3.5f+viewportHeight-1;
+ float cases[rows][12]={};
+ for(unsigned row=0;row<rows;++row){
+ cases[row][0]=9.5f;cases[row][1]=5.5f+row*4;
+ cases[row][2]=offsets[row][0];cases[row][3]=offsets[row][1];cases[row][6]=1;
+ }
+ cases[7][7]=-.4f;cases[8][7]=.4f;
+ cases[9][4]=.8f;cases[9][6]=.6f; // below z, but in front along the raster view ray
+ cases[10][0]=lastX;cases[11][0]=lastX;cases[11][1]=lastY;
+ cases[14][4]=.6f;cases[14][6]=.8f;cases[14][7]=-.5f; // forward of raster, behind optical surface
+ cases[15][0]=4.5f;
+ ti.format=colourDescription.format;ti.usage=SDL_GPU_TEXTUREUSAGE_SAMPLER;ti.width=width;ti.height=height;
+ r.colour=SDL_CreateGPUTexture(r.device,&ti);ti.format=SDL_GPU_TEXTUREFORMAT_R32_FLOAT;
+ r.depth=SDL_CreateGPUTexture(r.device,&ti);ti.format=colourDescription.format;ti.width=ti.height=1;
+ r.white=SDL_CreateGPUTexture(r.device,&ti);CHECK(r.colour && r.depth && r.white);
+ if(!r.colour || !r.depth || !r.white)return;
+ std::vector<float> pixels(width*height*4),depth(width*height,.5f);
+ for(unsigned y=0;y<height;++y)for(unsigned x=0;x<width;++x){
+ const unsigned p=(y*width+x)*4;
+ const bool outside=x<4 || x>27 || y<3 || y>unsigned(lastY);
+ pixels[p]=outside?1.0f:float(x)/width;pixels[p+1]=outside?0.0f:float(y)/height;
+ pixels[p+2]=outside?1.0f:0.0f;pixels[p+3]=1;
+ if(outside)depth[y*width+x]=0; // even invalid off-viewport neighbours must be ignored
+ }
+ auto mark=[&](unsigned row,int dx,int dy,float d){
+ const unsigned x=unsigned(int(cases[row][0])+dx),y=unsigned(int(cases[row][1])+dy),p=(y*width+x)*4;
+ depth[y*width+x]=d;pixels[p]=pixels[p+1]=0;pixels[p+2]=1;
+ };
+ mark(1,1,0,0);mark(2,0,1,0);mark(3,1,1,0);mark(4,1,0,0);mark(5,1,0,0);
+ mark(6,1,0,1);mark(7,1,0,.02f);mark(8,1,0,.004f);mark(9,1,0,.02f);
+ mark(12,-1,-1,0);mark(14,1,0,.1f);mark(16,1,0,.0079f);mark(17,1,0,.0081f);
+ // Row21: original is clear (terrain fallback would be20 deep), nearest displaced hit
+ // is valid5 deep. Losing a colour neighbour must not switch this selected ray.
+ mark(21,0,0,1);mark(21,0,1,0);
+ // Only the nearest survives; row26 exercises the minimum possible surviving weight1/4.
+ for(unsigned row:{22u,26u}) {mark(row,0,0,0);mark(row,1,0,1);mark(row,0,1,-.1f);}
+ mark(25,1,1,0); // invalid nearest must still reject even with three valid neighbours
+ auto paint=[&](unsigned row,int dx,int dy,float d,float red,float green,float blue){
+ const unsigned x=unsigned(int(cases[row][0])+dx),y=unsigned(int(cases[row][1])+dy),p=(y*width+x)*4;
+ depth[y*width+x]=d;pixels[p]=red;pixels[p+1]=green;pixels[p+2]=blue;
+ };
+ for(unsigned row:{23u,24u}) {
+ paint(row,0,0,.2f,1,0,0);paint(row,1,0,.3f,0,1,0);
+ paint(row,0,1,.6f,0,0,1);paint(row,1,1,row==24?0.0f:.9f,1,1,1);
+ }
+ const unsigned colourBytes=unsigned(pixels.size()*sizeof(float)),depthBytes=unsigned(depth.size()*sizeof(float));
+ SDL_GPUTransferBufferCreateInfo bi={};bi.usage=SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD;bi.size=colourBytes+depthBytes+16;
+ SDL_GPUTransferBuffer *transfer=SDL_CreateGPUTransferBuffer(r.device,&bi);CHECK(transfer);if(!transfer)return;
+ unsigned char *mapped=(unsigned char*)SDL_MapGPUTransferBuffer(r.device,transfer,false);CHECK(mapped);
+ if(!mapped){SDL_ReleaseGPUTransferBuffer(r.device,transfer);return;}
+ memcpy(mapped,pixels.data(),colourBytes);memcpy(mapped+colourBytes,depth.data(),depthBytes);
+ const float white[4]={1,1,1,1};memcpy(mapped+colourBytes+depthBytes,white,sizeof(white));SDL_UnmapGPUTransferBuffer(r.device,transfer);
+ SDL_GPUCommandBuffer *upload=SDL_AcquireGPUCommandBuffer(r.device);CHECK(upload);
+ if(!upload){SDL_ReleaseGPUTransferBuffer(r.device,transfer);return;}
+ SDL_GPUCopyPass *copy=SDL_BeginGPUCopyPass(upload);CHECK(copy);
+ if(!copy){SDL_CancelGPUCommandBuffer(upload);SDL_ReleaseGPUTransferBuffer(r.device,transfer);return;}
+ SDL_GPUTexture *textures[3]={r.colour,r.depth,r.white};const unsigned uploadOffsets[3]={0,colourBytes,colourBytes+depthBytes};
+ for(unsigned i=0;i<3;++i){
+ SDL_GPUTextureTransferInfo from={};from.transfer_buffer=transfer;from.offset=uploadOffsets[i];
+ from.pixels_per_row=i==2?1:width;from.rows_per_layer=i==2?1:height;
+ SDL_GPUTextureRegion to={};to.texture=textures[i];to.w=i==2?1:width;to.h=i==2?1:height;to.d=1;
+ SDL_UploadToGPUTexture(copy,&from,&to,false);
+ }
+ SDL_EndGPUCopyPass(copy);CHECK(SDL_SubmitGPUCommandBuffer(upload));SDL_ReleaseGPUTransferBuffer(r.device,transfer);
+ SdlWaterPixelConstants water={};water.WorldFromClip[0]=viewportWidth/2;water.WorldFromClip[5]=viewportHeight/2;
+ water.WorldFromClip[10]=-10;water.WorldFromClip[15]=1;
+ water.Viewport[0]=4.5f;water.Viewport[1]=3.5f;water.Viewport[2]=viewportWidth;water.Viewport[3]=viewportHeight;
+ water.SceneParameters[0]=1;water.SceneParameters[1]=1.0f/width;water.SceneParameters[2]=1.0f/height;
+ water.TerrainParameters[1]=1;
+ auto render=[&](bool old,bool depthAvailable,bool colourAvailable){
+ for(unsigned row=0;row<rows;++row)cases[row][8]=old?1.0f:0.0f;
+ water.SceneParameters[0]=colourAvailable?1.0f:0.0f;
+ water.SceneParameters[3]=depthAvailable?1.0f:0.0f;
+ SDL_GPUCommandBuffer *commands=SDL_AcquireGPUCommandBuffer(r.device);CHECK(commands);if(!commands)return std::vector<float>();
+ SDL_GPUColorTargetInfo attachment={};attachment.texture=r.target;attachment.load_op=SDL_GPU_LOADOP_CLEAR;attachment.store_op=SDL_GPU_STOREOP_STORE;
+ SDL_GPURenderPass *pass=SDL_BeginGPURenderPass(commands,&attachment,1,NULL);CHECK(pass);
+ if(!pass){SDL_CancelGPUCommandBuffer(commands);return std::vector<float>();}
+ SDL_BindGPUGraphicsPipeline(pass,r.pipeline);SDL_GPUTextureSamplerBinding bindings[16]={};
+ for(unsigned i=0;i<samplers;++i){bindings[i].texture=i==5?(colourAvailable?r.colour:r.white):i==6?r.depth:r.white;bindings[i].sampler=i==6?r.point:r.linear;}
+ SDL_BindGPUFragmentSamplers(pass,0,bindings,samplers);
+ SDL_PushGPUFragmentUniformData(commands,0,&water,sizeof(water));SDL_PushGPUFragmentUniformData(commands,1,cases,sizeof(cases));
+ SDL_DrawGPUPrimitives(pass,3,1,0,0);SDL_EndGPURenderPass(pass);CHECK(SDL_SubmitGPUCommandBuffer(commands));++renders;
+ return read_float_targets(frame,&r.target,1,columns,rows);
+ };
+ const auto actual=render(false,true,true),old=render(true,true,true),fallback=render(false,false,true);
+ // Match production's missing-background binding: a real 1x1 white texture at slot5,
+ // while SceneParameters.yz and Viewport still describe the larger render target.
+ const auto missingColour=render(false,true,false),missingBoth=render(false,false,false);
+ CHECK(actual.size()==columns*rows*4 && old.size()==actual.size() && fallback.size()==actual.size()
+ && missingColour.size()==actual.size() && missingBoth.size()==actual.size());
+ if(actual.size()!=columns*rows*4 || old.size()!=actual.size() || fallback.size()!=actual.size()
+ || missingColour.size()!=actual.size() || missingBoth.size()!=actual.size())return;
+ // Independent acceptance/tap masks are the explicit case table. The colour oracle
+ // interpolates known pixels using those masks, never calling/copying the depth guard.
+ auto sampleColour=[&](float px,float py,unsigned channel){
+ const int x=int(std::floor(px-.5f)),y=int(std::floor(py-.5f));
+ const float fx=px-.5f-x,fy=py-.5f-y;
+ auto at=[&](int xx,int yy){xx=std::max(0,std::min(int(width)-1,xx));yy=std::max(0,std::min(int(height)-1,yy));return pixels[(yy*width+xx)*4+channel];};
+ return (at(x,y)*(1-fx)+at(x+1,y)*fx)*(1-fy)+(at(x,y+1)*(1-fx)+at(x+1,y+1)*fx)*fy;
+ };
+ auto filteredColour=[&](unsigned row,float px,float py,unsigned channel){
+ if(!accepted[row])return sampleColour(px,py,channel);
+ const int x=int(std::floor(px-.5f)),y=int(std::floor(py-.5f));
+ const double fx=double(px)-.5-x,fy=double(py)-.5-y;
+ const double weights[4]={(1-fx)*(1-fy),fx*(1-fy),(1-fx)*fy,fx*fy};
+ double value=0,weight=0;
+ for(unsigned tap=0;tap<4;++tap)if((validTaps[row]&(1u<<tap)) && weights[tap]>0) {
+ const int xx=std::max(4,std::min(27,x+int(tap&1))),
+ yy=std::max(3,std::min(int(lastY),y+int(tap>>1)));
+ value+=weights[tap]*pixels[(yy*width+xx)*4+channel];weight+=weights[tap];
+ }
+ CHECK(weight>=.25);return float(value/weight);
+ };
+ for(unsigned row=0;row<rows;++row){
+ const float *f=cases[row],*got=&actual[row*columns*4],*missing=&fallback[row*columns*4];
+ const float px=accepted[row]?std::max(4.5f,std::min(lastX,f[0]+f[2])):f[0];
+ const float py=accepted[row]?std::max(3.5f,std::min(lastY,f[1]+f[3])):f[1];
+ CHECK(std::abs(got[0]-px)<2e-6f && std::abs(got[1]-py)<2e-6f && got[2]==float(accepted[row]));
+ CHECK(missing[0]==f[0] && missing[1]==f[1] && missing[2]==0);
+ for(unsigned c=0;c<3;++c){
+ CHECK(std::abs(got[4+c]-filteredColour(row,px,py,c))<3e-6f);
+ CHECK(std::abs(missing[4+c]-sampleColour(f[0],f[1],c))<3e-6f);
+ }
+ const unsigned nx=unsigned(std::floor(px)),ny=unsigned(std::floor(py));
+ const float bottom[3]={nx+.5f-16.5f,3.5f+viewportHeight/2-(ny+.5f),-10*depth[ny*width+nx]};
+ const float world[3]={f[0]-16.5f,3.5f+viewportHeight/2-f[1],0};
+ float distance2=0,fallbackDistance2=0;
+ for(unsigned c=0;c<3;++c){
+ CHECK(std::abs(got[8+c]-bottom[c])<3e-5f);
+ const float optical=world[c]+f[4+c]*f[7],difference=bottom[c]-optical;
+ distance2+=difference*difference;
+ const float originalFallback=c==2?-20.0f:world[c];
+ CHECK(std::abs(missing[8+c]-originalFallback)<3e-5f);
+ const float fallbackDifference=originalFallback-optical;fallbackDistance2+=fallbackDifference*fallbackDifference;
+ }
+ CHECK(std::abs(got[3]-std::sqrt(distance2))<3e-5f);
+ CHECK(std::abs(missing[3]-std::sqrt(fallbackDistance2))<3e-5f);++checked;
+ for(unsigned noDepth=0;noDepth<2;++noDepth){
+ const float *noColour=&(noDepth?missingBoth:missingColour)[row*columns*4];
+ CHECK(noColour[0]==f[0] && noColour[1]==f[1] && noColour[2]==0);
+ float expectedDistance2=0;
+ for(unsigned c=0;c<3;++c){
+ CHECK(noColour[4+c]==0); // unused: caller uses its material scattering fallback
+ const float originalDepth=depth[unsigned(f[1])*width+unsigned(f[0])];
+ const float originalHit=c==2?((noDepth || originalDepth>=.999999f)?-20.0f:-10*originalDepth):world[c];
+ CHECK(std::abs(noColour[8+c]-originalHit)<3e-5f);
+ const float difference=originalHit-(world[c]+f[4+c]*f[7]);
+ expectedDistance2+=difference*difference;
+ }
+ CHECK(std::abs(noColour[3]-std::sqrt(expectedDistance2))<3e-5f);++missingColourChecks;
+ }
+ }
+ // Old nearest-only sampling leaks unsafe blue. M4d keeps the actual selected ray
+ // while dropping that blue. The previous whole-footprint M4c also fails these accepts.
+ for(unsigned row:{1u,2u,3u,6u,7u,8u,9u,12u,14u,16u,21u,22u,26u}){
+ CHECK(old[row*columns*4+2]==1 && old[row*columns*4+6]>.05f);
+ CHECK(actual[row*columns*4+2]==1 && actual[row*columns*4+6]==0);++armedLeaks;
+ }
+ // Explicit physical-path control: row21's original clear pixel falls back20 units,
+ // but the displaced actual nearest is(1,0,-5), distance sqrt26, despite bad neighbours.
+ CHECK(std::abs(actual[21*columns*4+3]-std::sqrt(26.0f))<3e-5f);
+ CHECK(std::abs(actual[21*columns*4+3]-20.0f)>14.0f);
+ // All-valid RGB mixture retains hardware bilinear values. Differently deep neighbours
+ // do not turn transport into averaged depth: nearest red has depth2, not weighted3.9375.
+ CHECK(std::abs(actual[23*columns*4+4]-.5625f)<3e-6f);
+ CHECK(std::abs(actual[23*columns*4+5]-.25f)<3e-6f);
+ CHECK(std::abs(actual[23*columns*4+6]-.375f)<3e-6f);
+ CHECK(std::abs(actual[23*columns*4+3]-2.0f)<3e-5f);
+ CHECK(std::abs(actual[24*columns*4+4]-15.0f/29)<3e-6f);
+ CHECK(std::abs(actual[24*columns*4+5]-5.0f/29)<3e-6f);
+ CHECK(std::abs(actual[24*columns*4+6]-9.0f/29)<3e-6f);
+ CHECK(old[24*columns*4+5]-actual[24*columns*4+5]>.05f); // armed invalid-white mixture
+ CHECK(actual[25*columns*4+2]==0); // no substitute ray when nearest itself is invalid
+ CHECK(actual[26*columns*4+2]==1); // exactly1/4 surviving weight is sufficient
+ CHECK(actual[4*columns*4+2]==1); // zero-weight bad neighbour must not suppress an exact-centre sample
+ CHECK(actual[17*columns*4+2]==1 && actual[17*columns*4+6]>.2f); // valid .081-deep blue object stays visible
+ SDL_ReleaseGPUTexture(r.device,r.colour);r.colour=NULL;SDL_ReleaseGPUTexture(r.device,r.depth);r.depth=NULL;
+ SDL_ReleaseGPUTexture(r.device,r.white);r.white=NULL;
+ }
+ CHECK(renders==10 && checked==54 && armedLeaks==26 && missingColourChecks==108);
+ printf("sdl_gpu_frame_selfcheck: M4D production depth-aware colour filter: %u renders, %u cases at two sizes, %u armed nearest-only leaks, %u missing-colour checks; independent normalized colours, nearest transport, both surfaces/rays, clear depth, margins, viewport and fallback passed\n",renders,checked,armedLeaks,missingColourChecks);
+}
+#endif // __linux__
+
+// Verify production refraction helpers against independent ray/plane intersections.
+#if defined(__linux__)
+static void check_gpu_water_refraction_coordinates(SdlGpuFrame *frame)
+{
+ const unsigned rows=10,columns=3;
+ struct Resources {
+ SDL_GPUDevice *device;
+ SDL_GPUShader *vertex=NULL,*pixel=NULL;
+ SDL_GPUGraphicsPipeline *pipeline=NULL;
+ SDL_GPUTexture *target=NULL,*colour=NULL,*depth=NULL,*white=NULL;
+ SDL_GPUSampler *linear=NULL,*point=NULL;
+ ~Resources() {
+ if(pipeline) SDL_ReleaseGPUGraphicsPipeline(device,pipeline);
+ if(vertex) SDL_ReleaseGPUShader(device,vertex);
+ if(pixel) SDL_ReleaseGPUShader(device,pixel);
+ if(target) SDL_ReleaseGPUTexture(device,target);
+ if(colour) SDL_ReleaseGPUTexture(device,colour);
+ if(depth) SDL_ReleaseGPUTexture(device,depth);
+ if(white) SDL_ReleaseGPUTexture(device,white);
+ if(linear) SDL_ReleaseGPUSampler(device,linear);
+ if(point) SDL_ReleaseGPUSampler(device,point);
+ }
+ } r;
+ r.device=frame->Device();
+ PixelPipelineDescription pd={};std::string ps;
+ const char *oldDebug=getenv("ZH_WATER_DEBUG");const bool hadDebug=oldDebug!=NULL;
+ const std::string savedDebug=oldDebug?oldDebug:"";
+ // This isolated optical probe reserves b1 for its cases, with no hull packets.
+ const char *oldContact=getenv("ZH_WATER_HULL_CONTACT");const bool hadContact=oldContact!=NULL;
+ const std::string savedContact=oldContact?oldContact:"";
+ CHECK(setenv("ZH_WATER_HULL_CONTACT","0",1)==0);
+ CHECK(unsetenv("ZH_WATER_DEBUG")==0);
+ const bool generated=EngineShader_Pixel_Program(ENGINE_SHADER_WATER_TRAPEZOID,pd,ps,
+ COMBINER_SHADER_TARGET_SDL3_GPU);
+ if(hadDebug)CHECK(setenv("ZH_WATER_DEBUG",savedDebug.c_str(),1)==0);
+ else CHECK(unsetenv("ZH_WATER_DEBUG")==0);
+ if(hadContact)CHECK(setenv("ZH_WATER_HULL_CONTACT",savedContact.c_str(),1)==0);
+ else CHECK(unsetenv("ZH_WATER_HULL_CONTACT")==0);
+ CHECK(generated);if(!generated)return;
+ const std::string entry="float4 main(Input input)";
+ const size_t at=ps.find(entry);CHECK(at!=std::string::npos);if(at==std::string::npos)return;
+ ps.replace(at,entry.size(),"float4 unusedWaterMain(Input input)");
+ ps+="\n#define M4aCaseCount 10\n";
+ ps+=R"M4A(
+// Test-only wrapper appended to the exact generated production water pixel shader after
+// renaming its main to unusedWaterMain. This invokes the same helpers used by production main.
+// Set M4aCaseCount when constructing this shader; each case occupies four float4s.
+cbuffer M4aCases : register(b1, space3) { float4 M4aFixtures[M4aCaseCount * 4]; };
+
+// Deliberately retain the old equations as armed controls, not as expected results.
+float2 m4aOldOffset(float depth, float3 view, float3 normal)
+{
+ float3 incident = -view, underwater = refract(incident, normal, 0.75);
+ return clamp(depth * (underwater.xy/min(underwater.z,-0.1)
+ - incident.xy/min(incident.z,-0.1)), float2(-8,-8), float2(8,8))
+ * smoothstep(0.15,2.5,depth);
+}
+WaterRefractionSample m4aOldSample(float2 origin, float2 offset,
+ float3 world, float3 view, float3 originalBottom)
+{
+ WaterRefractionSample result;
+ float2 candidate = origin + offset;
+ float3 hit = bottomPosition(candidate,world,0);
+ float valid = step(hit.z,world.z-0.08) * step(0.0,dot(hit-world,-view));
+ result.pixel = lerp(origin,candidate,valid);
+ result.bottom = lerp(originalBottom,hit,valid);
+ result.accepted = valid;
+ result.colour = Texture5.SampleLevel(Sampler5,saturate(result.pixel*SceneParameters.yz),0).rgb;
+ return result;
+}
+float4 main(float4 position : SV_Position) : SV_Target0
+{
+ uint row = (uint)position.y, column = (uint)position.x;
+ float4 a = M4aFixtures[row*4], b = M4aFixtures[row*4+1];
+ float4 c = M4aFixtures[row*4+2], flags = M4aFixtures[row*4+3];
+ if (flags.x < 0.5) {
+ // Supplied constant ray, avoiding an accidental claim to fix production ortho cameras.
+ // b.xyz=view, b.w=original vertical depth, c.xyz=normal, c.w=analytic height delta.
+ float shift = WaterOpticalRayShift(c.w,b.z,1,7,b.w/b.z,100);
+ float opticalDepth = max(b.w+b.z*shift,0.0);
+ float2 offset = flags.y > 0.5 ? m4aOldOffset(opticalDepth,b.xyz,c.xyz)
+ : waterRefractionPixels(opticalDepth,b.xyz,c.xyz,float2(1,0),float2(0,1));
+ return float4(offset,shift,opticalDepth);
+ }
+ // Sampling cases use WorldFromClip below: the raster surface is z=0 and actual depth
+ // maps to negative world z. a.xy=original pixel, a.zw=prescribed fractional displacement.
+ float3 world = scenePosition(a.xy,0), view = float3(0,0,1);
+ float3 originalBottom = bottomPosition(a.xy,world,0);
+ WaterRefractionSample sampledScene;
+ if (flags.y > 0.5) sampledScene = m4aOldSample(a.xy,a.zw,world,view,originalBottom);
+ else sampledScene = waterRefractedScene(a.xy,a.zw,world,world,view,0,originalBottom);
+ if (column == 0) return float4(sampledScene.pixel,sampledScene.accepted,length(sampledScene.bottom-world));
+ if (column == 1) return float4(sampledScene.colour,1);
+ return float4(sampledScene.bottom,1);
+}
+
+)M4A";
+ const char *vs="float4 main(uint id:SV_VertexID):SV_Position { return float4(id==1?3.0:-1.0,id==2?3.0:-1.0,0,1); }";
+ std::string error;std::vector<unsigned char> spirv;
+ bool compiled=SDL3_Compile_HLSL_To_SPIRV(vs,true,spirv,error);CHECK(compiled);if(!compiled)return;
+ r.vertex=SDL3_Create_Shader(r.device,spirv,true,error);CHECK(r.vertex);if(!r.vertex)return;
+ compiled=SDL3_Compile_HLSL_To_SPIRV(ps,false,spirv,error);CHECK(compiled);
+ if(!compiled){printf("M4A production helper compile: %s\n",error.c_str());return;}
+ unsigned samplers=0,uniforms=0;SDL3_Shader_Slots(spirv,false,samplers,uniforms);
+ CHECK(samplers<=16 && uniforms==2);if(samplers>16 || uniforms!=2)return;
+ r.pixel=SDL3_Create_Shader(r.device,spirv,false,error);CHECK(r.pixel);if(!r.pixel)return;
+ SDL_GPUColorTargetDescription colourDescription={};colourDescription.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
+ SDL_GPUGraphicsPipelineCreateInfo pi={};pi.vertex_shader=r.vertex;pi.fragment_shader=r.pixel;
+ pi.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;pi.rasterizer_state.cull_mode=SDL_GPU_CULLMODE_NONE;
+ pi.target_info.color_target_descriptions=&colourDescription;pi.target_info.num_color_targets=1;
+ r.pipeline=SDL_CreateGPUGraphicsPipeline(r.device,&pi);CHECK(r.pipeline);if(!r.pipeline)return;
+ SDL_GPUTextureCreateInfo ti={};ti.type=SDL_GPU_TEXTURETYPE_2D;ti.format=colourDescription.format;
+ ti.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;ti.width=columns;ti.height=rows;ti.layer_count_or_depth=ti.num_levels=1;
+ r.target=SDL_CreateGPUTexture(r.device,&ti);CHECK(r.target);if(!r.target)return;
+ SDL_GPUSamplerCreateInfo si={};si.address_mode_u=si.address_mode_v=si.address_mode_w=SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
+ si.min_filter=si.mag_filter=SDL_GPU_FILTER_LINEAR;si.mipmap_mode=SDL_GPU_SAMPLERMIPMAPMODE_NEAREST;
+ r.linear=SDL_CreateGPUSampler(r.device,&si);si.min_filter=si.mag_filter=SDL_GPU_FILTER_NEAREST;
+ r.point=SDL_CreateGPUSampler(r.device,&si);CHECK(r.linear && r.point);if(!r.linear || !r.point)return;
+ const float templateCases[rows][16]={
+ {0,0,0,0, .6f,0,.8f,4, 0,0,1,0, 0,0,0,0},
+ {0,0,0,0, -.6f,0,.8f,4, 0,0,1,0, 0,0,0,0},
+ {0,0,0,0, 0,0,1,4, 0,0,1,0, 0,0,0,0},
+ {0,0,0,0, .6f,0,.8f,4, 0,0,1,.8f, 0,0,0,0},
+ {0,0,0,0, .6f,0,.8f,4, 0,0,1,-.8f, 0,0,0,0},
+ {0,0,0,0, 0,0,1,4, .6f,0,.8f,0, 0,0,0,0},
+ {0,0,0,0, .6f,0,.8f,.1f, 0,0,1,0, 0,0,0,0},
+ {0,0,0,0, .6f,0,.8f,100, 0,0,1,0, 0,0,0,0},
+ {7.5f,7.5f,.75f,.875f, 0,0,1,0, 0,0,1,0, 1,0,0,0},
+ {15.5f,7.5f,8,0, 0,0,1,0, 0,0,1,0, 1,0,0,0}
+ };
+ unsigned renders=0,armedSign=0,armedViewport=0;
+ CHECK(frame->Flush());
+ for(unsigned resize=0;resize<2;++resize) {
+ const unsigned width=24u<<resize,height=20u<<resize;
+ ti.format=colourDescription.format;ti.usage=SDL_GPU_TEXTUREUSAGE_SAMPLER;ti.width=width;ti.height=height;
+ r.colour=SDL_CreateGPUTexture(r.device,&ti);ti.format=SDL_GPU_TEXTUREFORMAT_R32_FLOAT;
+ r.depth=SDL_CreateGPUTexture(r.device,&ti);ti.format=colourDescription.format;ti.width=ti.height=1;
+ r.white=SDL_CreateGPUTexture(r.device,&ti);CHECK(r.colour && r.depth && r.white);
+ if(!r.colour || !r.depth || !r.white)return;
+ std::vector<float> pixels(width*height*4),depth(width*height,.5f);
+ for(unsigned y=0;y<height;++y)for(unsigned x=0;x<width;++x) {
+ const unsigned p=(y*width+x)*4;const bool outside=x<4 || x>15 || y<3 || y>12;
+ pixels[p]=outside?1.0f:float(x)/width;pixels[p+1]=outside?0.0f:float(y)/height;
+ pixels[p+2]=outside?1.0f:0.0f;pixels[p+3]=1;
+ }
+ const unsigned colourBytes=unsigned(pixels.size()*sizeof(float)),depthBytes=unsigned(depth.size()*sizeof(float));
+ SDL_GPUTransferBufferCreateInfo bi={};bi.usage=SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD;bi.size=colourBytes+depthBytes+16;
+ SDL_GPUTransferBuffer *transfer=SDL_CreateGPUTransferBuffer(r.device,&bi);CHECK(transfer);if(!transfer)return;
+ unsigned char *mapped=(unsigned char*)SDL_MapGPUTransferBuffer(r.device,transfer,false);CHECK(mapped);
+ if(!mapped){SDL_ReleaseGPUTransferBuffer(r.device,transfer);return;}
+ memcpy(mapped,pixels.data(),colourBytes);memcpy(mapped+colourBytes,depth.data(),depthBytes);
+ const float white[4]={1,1,1,1};memcpy(mapped+colourBytes+depthBytes,white,sizeof(white));
+ SDL_UnmapGPUTransferBuffer(r.device,transfer);
+ SDL_GPUCommandBuffer *upload=SDL_AcquireGPUCommandBuffer(r.device);CHECK(upload);
+ if(!upload){SDL_ReleaseGPUTransferBuffer(r.device,transfer);return;}
+ SDL_GPUCopyPass *copy=SDL_BeginGPUCopyPass(upload);CHECK(copy);
+ if(!copy){SDL_CancelGPUCommandBuffer(upload);SDL_ReleaseGPUTransferBuffer(r.device,transfer);return;}
+ SDL_GPUTexture *textures[3]={r.colour,r.depth,r.white};const unsigned offsets[3]={0,colourBytes,colourBytes+depthBytes};
+ for(unsigned i=0;i<3;++i) {
+ SDL_GPUTextureTransferInfo from={};from.transfer_buffer=transfer;from.offset=offsets[i];
+ from.pixels_per_row=i==2?1:width;from.rows_per_layer=i==2?1:height;
+ SDL_GPUTextureRegion to={};to.texture=textures[i];to.w=i==2?1:width;to.h=i==2?1:height;to.d=1;
+ SDL_UploadToGPUTexture(copy,&from,&to,false);
+ }
+ SDL_EndGPUCopyPass(copy);CHECK(SDL_SubmitGPUCommandBuffer(upload));SDL_ReleaseGPUTransferBuffer(r.device,transfer);
+ SdlWaterPixelConstants water={};water.WorldFromClip[0]=6;water.WorldFromClip[5]=5;
+ water.WorldFromClip[10]=-10;water.WorldFromClip[15]=1;
+ water.Viewport[0]=4.5f;water.Viewport[1]=3.5f;water.Viewport[2]=12;water.Viewport[3]=10;
+ water.SceneParameters[0]=water.SceneParameters[3]=1;
+ water.SceneParameters[1]=1.0f/width;water.SceneParameters[2]=1.0f/height;water.TerrainParameters[1]=1;
+ auto render=[&](bool old) {
+ float cases[rows][16];memcpy(cases,templateCases,sizeof(cases));
+ for(unsigned row=0;row<rows;++row)cases[row][13]=old?1.0f:0.0f;
+ SDL_GPUCommandBuffer *commands=SDL_AcquireGPUCommandBuffer(r.device);CHECK(commands);
+ if(!commands)return std::vector<float>();
+ SDL_GPUColorTargetInfo attachment={};attachment.texture=r.target;
+ attachment.load_op=SDL_GPU_LOADOP_CLEAR;attachment.store_op=SDL_GPU_STOREOP_STORE;
+ SDL_GPURenderPass *pass=SDL_BeginGPURenderPass(commands,&attachment,1,NULL);CHECK(pass);
+ if(!pass){SDL_CancelGPUCommandBuffer(commands);return std::vector<float>();}
+ SDL_BindGPUGraphicsPipeline(pass,r.pipeline);
+ SDL_GPUTextureSamplerBinding bindings[16]={};
+ for(unsigned i=0;i<samplers;++i){bindings[i].texture=i==5?r.colour:i==6?r.depth:r.white;bindings[i].sampler=i==6?r.point:r.linear;}
+ SDL_BindGPUFragmentSamplers(pass,0,bindings,samplers);
+ SDL_PushGPUFragmentUniformData(commands,0,&water,sizeof(water));
+ SDL_PushGPUFragmentUniformData(commands,1,cases,sizeof(cases));
+ SDL_DrawGPUPrimitives(pass,3,1,0,0);SDL_EndGPURenderPass(pass);CHECK(SDL_SubmitGPUCommandBuffer(commands));++renders;
+ return read_float_targets(frame,&r.target,1,columns,rows);
+ };
+ const auto actual=render(false),old=render(true);
+ CHECK(actual.size()==columns*rows*4 && old.size()==actual.size());
+ if(actual.size()!=columns*rows*4 || old.size()!=actual.size())return;
+ for(unsigned row=0;row<6;++row) {
+ const float *f=templateCases[row],*got=&actual[row*columns*4];
+ const double vx=f[4],vy=f[5],vz=f[6],D=f[7],nx=f[8],ny=f[9],nz=f[10];
+ const double shift=f[11]/vz,ox=vx*shift,oy=vy*shift,oz=vz*shift;
+ const double ix=-vx,iy=-vy,iz=-vz,dot=ix*nx+iy*ny+iz*nz;
+ const double eta=.75,k=eta*dot+std::sqrt(1-eta*eta*(1-dot*dot));
+ const double ux=eta*ix-k*nx,uy=eta*iy-k*ny,uz=eta*iz-k*nz;
+ // Independent ray/plane intersections, not the implementation's ratio subtraction.
+ const double straightT=(-D-oz)/iz,bentT=(-D-oz)/uz;
+ const double straightX=ox+ix*straightT,straightY=oy+iy*straightT;
+ const double bentX=ox+ux*bentT,bentY=oy+uy*bentT;
+ CHECK(std::abs(straightX+vx*D/vz)<2e-6 && std::abs(straightY+vy*D/vz)<2e-6);
+ CHECK(std::abs(got[0]-(bentX-straightX))<3e-5 && std::abs(got[1]-(bentY-straightY))<3e-5);
+ CHECK(std::abs(got[2]-shift)<3e-5 && std::abs(got[3]-(D+oz))<3e-5);
+ if(row==0 || row==3 || row==4){CHECK(std::abs(old[row*columns*4]-(bentX-straightX))>.1);++armedSign;}
+ }
+ CHECK(actual[6*columns*4]==0 && actual[6*columns*4+1]==0);
+ CHECK(std::abs(actual[7*columns*4]-8)<1e-6 && actual[7*columns*4+1]==0);
+ const float *fraction=&actual[8*columns*4],*fractionColour=fraction+4,*fractionBottom=fraction+8;
+ CHECK(std::abs(fraction[0]-8.25f)<1e-6 && std::abs(fraction[1]-8.375f)<1e-6 && fraction[2]==1);
+ CHECK(std::abs(fractionColour[0]-7.75f/width)<2e-6 && std::abs(fractionColour[1]-7.875f/height)<2e-6 && fractionColour[2]==0);
+ // Nearest point depth unprojects (8.5,8.5), whereas fractional colour stays bilinear.
+ CHECK(std::abs(fractionBottom[0]+2)<2e-6 && std::abs(fractionBottom[1])<2e-6 && std::abs(fractionBottom[2]+5)<2e-6);
+ CHECK(std::abs(fraction[3]-std::sqrt(27.0))<3e-5);
+ const float *edge=&actual[9*columns*4],*edgeColour=edge+4,*edgeBottom=edge+8;
+ CHECK(edge[0]==15.5f && edge[1]==7.5f && edge[2]==1);
+ CHECK(std::abs(edgeColour[0]-15.0f/width)<2e-6 && std::abs(edgeColour[1]-7.0f/height)<2e-6 && edgeColour[2]==0);
+ CHECK(std::abs(edgeBottom[0]-5)<2e-6 && std::abs(edgeBottom[1]-1)<2e-6 && std::abs(edgeBottom[2]+5)<2e-6);
+ CHECK(old[9*columns*4+4+2]>.99f);++armedViewport;
+ SDL_ReleaseGPUTexture(r.device,r.colour);r.colour=NULL;SDL_ReleaseGPUTexture(r.device,r.depth);r.depth=NULL;
+ SDL_ReleaseGPUTexture(r.device,r.white);r.white=NULL;
+ }
+ CHECK(armedSign==6 && armedViewport==2);
+ printf("sdl_gpu_frame_selfcheck: M4A production refraction helpers: %u renders; sign, zero, tilt, optical shift, clamp, fractional centres, subviewport and resize passed; %u sign/%u viewport old controls\n",renders,armedSign,armedViewport);
+}
+#endif // __linux__
+
+// Authored material invariants are checked on the GPU with the production helpers. This
+// deliberately avoids a second C++ implementation of their colour conversion or extinction.
+static void check_gpu_modern_water_material(SdlGpuFrame *frame)
+{
+ const unsigned rows=12,columns=3;
+ // display colour/brightness, tint/pollution/bubbles/reserved, path/depth/illumination/face.
+ const float fixtures[rows][12]={
+ {0,0,0,0, 0,0,0,0, 20,10,1,.6f},
+ {1,1,1,1, 1,0,0,0, 20,10,1,.6f},
+ {.5f,.5f,.5f,1, 1,0,0,0, 20,10,1,.6f},
+ {.7f,0,0,1, 1,0,0,0, 20,10,1,.6f},
+ {0,0,.7f,1, 1,0,0,0, 20,10,1,.6f},
+ {.7f,0,0,1, 1,.8f,1,0, 20,10,1,.6f},
+ {0,0,.7f,1, 1,.8f,1,0, 20,10,1,.6f},
+ {45/255.f,58/255.f,11/255.f,.67f, 1,.8f,0,0, 20,10,1,.6f},
+ {45/255.f,58/255.f,11/255.f,.67f, 1,0,1,0, 20,10,1,.6f},
+ {45/255.f,58/255.f,11/255.f,.67f, 1,.8f,1,0, 20,0,1,.6f},
+ {45/255.f,58/255.f,11/255.f,.67f, 1,.8f,1,0, 20,10,1,.6f},
+ {45/255.f,58/255.f,11/255.f,1, 1,.8f,1,0, 20,10,1,.6f}
+ };
+ struct Resources {
+ SDL_GPUDevice *device;SDL_GPUShader *vertex=NULL,*pixel=NULL;
+ SDL_GPUGraphicsPipeline *pipeline=NULL;SDL_GPUTexture *target=NULL;
+ ~Resources(){if(pipeline)SDL_ReleaseGPUGraphicsPipeline(device,pipeline);
+ if(vertex)SDL_ReleaseGPUShader(device,vertex);if(pixel)SDL_ReleaseGPUShader(device,pixel);
+ if(target)SDL_ReleaseGPUTexture(device,target);}
+ } r;r.device=frame->Device();
+ const char *vs="float4 main(uint id:SV_VertexID):SV_Position {return float4(id==1?3.0:-1.0,id==2?3.0:-1.0,0,1);}";
+ std::string ps="cbuffer Fixtures:register(b0,space3){float4 F[36];};\n";
+ ps+=ModernWaterMaterial::OpticalSource();
+ ps+=R"HLSL(
+float4 main(float4 position:SV_Position):SV_Target0 {
+ uint row=(uint)position.y,column=(uint)position.x;
+ float4 colour=F[row*3],params=F[row*3+1],context=F[row*3+2];
+ if(column==0)return float4(modernWaterMaterialSource(float3(.002,.035,.075),colour,params.x,context.z,context.w),1);
+ if(column==1)return float4(modernWaterMaterialTransmission(float3(.8,.8,.8),colour.rgb,params.y,context.x,.5),1);
+ return float4(modernWaterBubbleFilm(colour.rgb),modernWaterBubbleWeight(params.y,params.z,context.y));
+})HLSL";
+ std::string error;std::vector<unsigned char> spirv;
+ bool compiled=SDL3_Compile_HLSL_To_SPIRV(vs,true,spirv,error);CHECK(compiled);if(!compiled)return;
+ r.vertex=SDL3_Create_Shader(r.device,spirv,true,error);CHECK(r.vertex);if(!r.vertex)return;
+ compiled=SDL3_Compile_HLSL_To_SPIRV(ps,false,spirv,error);CHECK(compiled);
+ if(!compiled){printf("Modern water material compile: %s\n",error.c_str());return;}
+ r.pixel=SDL3_Create_Shader(r.device,spirv,false,error);CHECK(r.pixel);if(!r.pixel)return;
+ SDL_GPUColorTargetDescription cd={};cd.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
+ SDL_GPUGraphicsPipelineCreateInfo pi={};pi.vertex_shader=r.vertex;pi.fragment_shader=r.pixel;
+ pi.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;pi.rasterizer_state.cull_mode=SDL_GPU_CULLMODE_NONE;
+ pi.target_info.color_target_descriptions=&cd;pi.target_info.num_color_targets=1;
+ r.pipeline=SDL_CreateGPUGraphicsPipeline(r.device,&pi);CHECK(r.pipeline);if(!r.pipeline)return;
+ SDL_GPUTextureCreateInfo ti={};ti.type=SDL_GPU_TEXTURETYPE_2D;ti.format=cd.format;
+ ti.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;ti.width=columns;ti.height=rows;ti.layer_count_or_depth=ti.num_levels=1;
+ r.target=SDL_CreateGPUTexture(r.device,&ti);CHECK(r.target);if(!r.target)return;
+ CHECK(frame->Flush());
+ SDL_GPUCommandBuffer *commands=SDL_AcquireGPUCommandBuffer(r.device);CHECK(commands);if(!commands)return;
+ SDL_GPUColorTargetInfo attachment={};attachment.texture=r.target;attachment.load_op=SDL_GPU_LOADOP_CLEAR;attachment.store_op=SDL_GPU_STOREOP_STORE;
+ SDL_GPURenderPass *pass=SDL_BeginGPURenderPass(commands,&attachment,1,NULL);CHECK(pass);
+ if(!pass){SDL_CancelGPUCommandBuffer(commands);return;}
+ SDL_BindGPUGraphicsPipeline(pass,r.pipeline);SDL_PushGPUFragmentUniformData(commands,0,fixtures,sizeof(fixtures));
+ SDL_DrawGPUPrimitives(pass,3,1,0,0);SDL_EndGPURenderPass(pass);CHECK(SDL_SubmitGPUCommandBuffer(commands));
+ const auto actual=read_float_targets(frame,&r.target,1,columns,rows);
+ CHECK(actual.size()==rows*columns*4);if(actual.size()!=rows*columns*4)return;
+ auto value=[&](unsigned row,unsigned column,unsigned channel){return actual[(row*columns+column)*4+channel];};
+ for(float value:actual)CHECK(std::isfinite(value) && value>=0 && value<=1);
+ const float baseline[]={.002f,.035f,.075f};
+ for(unsigned c=0;c<3;++c) {
+ CHECK(value(0,0,c)==baseline[c] && value(1,0,c)==baseline[c]);
+ CHECK(std::abs(value(2,0,c)/baseline[c]-std::pow(.5f,2.2f))<.000001);
+ CHECK(value(0,1,c)==.8f && value(3,1,c)==.8f && value(4,1,c)==.8f);
+ CHECK(value(3,0,c)==value(5,0,c) && value(4,0,c)==value(6,0,c)); // tint independent of pollution
+ CHECK(value(5,1,c)<value(3,1,c) && value(6,1,c)<value(4,1,c));
+ CHECK(value(7,0,c)==value(8,0,c) && value(8,0,c)==value(10,0,c));
+ CHECK(std::abs(value(10,0,c)-.67f*value(11,0,c))<.000001);
+ }
+ CHECK(value(3,0,0)>0 && value(3,0,1)==0 && value(3,0,2)==0); // red does not inherit a blue cast
+ CHECK(value(4,0,2)>0 && value(4,0,0)==0 && value(4,0,1)==0);
+ CHECK(value(5,1,0)>value(5,1,1) && value(5,1,1)==value(5,1,2));
+ CHECK(value(6,1,2)>value(6,1,0) && value(6,1,0)==value(6,1,1));
+ CHECK(value(5,2,0)>value(5,2,1) && value(6,2,2)>value(6,2,1));
+ CHECK(value(7,2,3)==0 && value(8,2,3)==0 && value(9,2,3)==0 && value(10,2,3)==.8f);
+ printf("sdl_gpu_frame_selfcheck: Modern material: exact clean/white identity, gray attenuation, red/blue tint and absorption, independent pollution, brightness and bubble gates passed\n");
+}
+
+// Executes the exact shared functions called by generated production water; not a whole-frame
+// FFT toggle test. Fixed context/path/face inputs intentionally isolate material independence.
+static void check_gpu_water_material_transport(SdlGpuFrame *frame)
+{
+ const unsigned rows=15,columns=4;
+ struct Resources {
+ SDL_GPUDevice *device;SDL_GPUShader *vertex=NULL,*pixel=NULL;
+ SDL_GPUGraphicsPipeline *pipeline=NULL;SDL_GPUTexture *target=NULL;
+ ~Resources(){if(pipeline)SDL_ReleaseGPUGraphicsPipeline(device,pipeline);
+ if(vertex)SDL_ReleaseGPUShader(device,vertex);if(pixel)SDL_ReleaseGPUShader(device,pixel);
+ if(target)SDL_ReleaseGPUTexture(device,target);}
+ } r;r.device=frame->Device();
+ // a=(path,river,effective-offshore,face), b=(scene.rgb,daylight),
+ // c=(caustic,sceneAvailable,FFT weight,old control), d=(reference-depth,opacity,0,0).
+ const float base[rows][16]={
+ {0,0,1,0, .2f,.4f,.6f,1, 1,1,0,0, 3,.75f,0,0},
+ {0,0,1,0, .2f,.4f,.6f,1, 1,1,1,0, 3,.75f,0,0},
+ {0,0,1,1, .2f,.4f,.6f,1, 1,1,1,0, 3,.75f,0,0},
+ {100000,0,1,.3f, .2f,.4f,.6f,1, 1,1,0,0, 3,.75f,0,0},
+ {100000,0,1,.3f, .8f,.1f,.2f,1, 1,1,1,0, 3,.75f,0,0},
+ {4,0,.5f,.4f, .2f,.4f,.6f,.7f, 1,1,.5f,0, 3,.75f,0,0},
+ {4,1,0,.4f, .2f,.4f,.6f,.7f, 1,1,0,0, 3,.75f,0,0},
+ {4,0,0,.4f, .2f,.4f,.6f,.7f, 1,1,0,0, 3,.75f,0,0},
+ {2,0,1,0, .7f,.5f,.3f,1, 1.2f,1,1,0, 3,.75f,0,0},
+ {2,0,1,0, .1f,.2f,.1f,1, 1.2f,1,1,0, 3,.75f,0,0},
+ {2,0,1,1, .7f,.5f,.3f,1, 1.2f,1,1,0, 3,.75f,0,0},
+ {2,0,1,1, .1f,.2f,.1f,1, 1.2f,1,1,0, 3,.75f,0,0},
+ {2,0,1,.4f, .7f,.5f,.3f,.7f, 1.2f,0,1,0, 3,.75f,0,0},
+ {4,0,.6f,.4f, .2f,.4f,.6f,1, 1,1,0,0, 3,.75f,0,0},
+ {4,.4f,.6f,.4f, .2f,.4f,.6f,1, 1,1,1,0, 3,.75f,0,0}
+ };
+ const char *vs="float4 main(uint id:SV_VertexID):SV_Position {return float4(id==1?3.0:-1.0,id==2?3.0:-1.0,0,1);}";
+ std::string ps="cbuffer Fixtures:register(b0,space3){float4 F[60];};\n";
+ ps+=WaterOpticalModel::GetHlslSource();
+ ps+=R"HLSL(
+float4 main(float4 position:SV_Position):SV_Target0 {
+ uint row=(uint)position.y,column=(uint)position.x;
+ float4 a=F[row*4],b=F[row*4+1],c=F[row*4+2],d=F[row*4+3];
+ float3 T=WaterOpticalTransmission(a.x,a.y,a.z,d.x,d.y);
+ float3 S=WaterOpticalScatteringSource(a.y,a.z,b.w,a.w);
+ float3 body=WaterOpticalBody(b.xyz,T,S,c.x,c.y);
+ if(c.w>0.5) {
+ // Armed pre-fix colour/whole-body-lighting control, not the expected-value oracle.
+ float3 oldSource=lerp(float3(.002,.028,.041),float3(.0012,.015,.029),a.z)*(.08+.92*b.w);
+ oldSource=lerp(oldSource,float3(.002,.035,.075)*(.08+.92*b.w),c.z);
+ float face=lerp(1.0,.4+1.8*a.w,a.z);
+ S=oldSource*face;
+ body=lerp(oldSource,b.xyz*T*c.x+oldSource*(1-T),c.y)*face;
+ }
+ if(column==0)return float4(T,1);
+ if(column==1)return float4(S,1);
+ if(column==2)return float4(body,1);
+ return float4(WaterOpticalMaterialSource(a.y,a.z),1);
+})HLSL";
+ std::string error;std::vector<unsigned char> spirv;
+ bool compiled=SDL3_Compile_HLSL_To_SPIRV(vs,true,spirv,error);CHECK(compiled);if(!compiled)return;
+ r.vertex=SDL3_Create_Shader(r.device,spirv,true,error);CHECK(r.vertex);if(!r.vertex)return;
+ compiled=SDL3_Compile_HLSL_To_SPIRV(ps,false,spirv,error);CHECK(compiled);
+ if(!compiled){printf("M4B optical source compile: %s\n",error.c_str());return;}
+ r.pixel=SDL3_Create_Shader(r.device,spirv,false,error);CHECK(r.pixel);if(!r.pixel)return;
+ SDL_GPUColorTargetDescription cd={};cd.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
+ SDL_GPUGraphicsPipelineCreateInfo pi={};pi.vertex_shader=r.vertex;pi.fragment_shader=r.pixel;
+ pi.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;pi.rasterizer_state.cull_mode=SDL_GPU_CULLMODE_NONE;
+ pi.target_info.color_target_descriptions=&cd;pi.target_info.num_color_targets=1;
+ r.pipeline=SDL_CreateGPUGraphicsPipeline(r.device,&pi);CHECK(r.pipeline);if(!r.pipeline)return;
+ SDL_GPUTextureCreateInfo ti={};ti.type=SDL_GPU_TEXTURETYPE_2D;ti.format=cd.format;
+ ti.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;ti.width=columns;ti.height=rows;ti.layer_count_or_depth=ti.num_levels=1;
+ r.target=SDL_CreateGPUTexture(r.device,&ti);CHECK(r.target);if(!r.target)return;
+ CHECK(frame->Flush());
+ auto render=[&](bool old){
+ float fixtures[rows][16];memcpy(fixtures,base,sizeof(fixtures));
+ for(unsigned row=0;row<rows;++row)fixtures[row][11]=old?1.0f:0.0f;
+ SDL_GPUCommandBuffer *commands=SDL_AcquireGPUCommandBuffer(r.device);CHECK(commands);if(!commands)return std::vector<float>();
+ SDL_GPUColorTargetInfo attachment={};attachment.texture=r.target;attachment.load_op=SDL_GPU_LOADOP_CLEAR;attachment.store_op=SDL_GPU_STOREOP_STORE;
+ SDL_GPURenderPass *pass=SDL_BeginGPURenderPass(commands,&attachment,1,NULL);CHECK(pass);
+ if(!pass){SDL_CancelGPUCommandBuffer(commands);return std::vector<float>();}
+ SDL_BindGPUGraphicsPipeline(pass,r.pipeline);SDL_PushGPUFragmentUniformData(commands,0,fixtures,sizeof(fixtures));
+ SDL_DrawGPUPrimitives(pass,3,1,0,0);SDL_EndGPURenderPass(pass);CHECK(SDL_SubmitGPUCommandBuffer(commands));
+ return read_float_targets(frame,&r.target,1,columns,rows);
+ };
+ const auto actual=render(false),old=render(true);CHECK(actual.size()==rows*columns*4 && old.size()==actual.size());
+ if(actual.size()!=rows*columns*4 || old.size()!=actual.size())return;
+ auto value=[&](const std::vector<float>& data,unsigned row,unsigned column,unsigned channel){return data[(row*columns+column)*4+channel];};
+ float maximumError=0;
+ for(unsigned row=0;row<rows;++row){
+ using namespace WaterOpticalModel;const float *f=base[row];
+ const RGB T=Transmission(f[0],f[1],f[2],f[12],f[13]),S=ScatteringSource(f[1],f[2],f[7],f[3]);
+ const RGB scene={f[4],f[5],f[6]},B=Body(scene,T,S,f[8],f[9]),M=MaterialSource(f[1],f[2]);
+ const RGB expected[4]={T,S,B,M};
+ for(unsigned col=0;col<columns;++col)for(unsigned c=0;c<3;++c){
+ const float e=c==0?expected[col].r:c==1?expected[col].g:expected[col].b;
+ const float got=value(actual,row,col,c),difference=std::abs(got-e);
+ maximumError=std::max(maximumError,difference);CHECK(std::isfinite(got) && difference<2e-5f);
+ }
+ }
+ for(unsigned c=0;c<3;++c){
+ // Independent identities, not just CPU/HLSL agreement.
+ for(unsigned row=0;row<3;++row)CHECK(std::abs(value(actual,row,2,c)-base[row][4+c])<1e-6f);
+ CHECK(std::abs(value(actual,0,1,c)-value(actual,1,1,c))<1e-7f); // FFT metadata cannot retint fixed material
+ CHECK(std::abs(value(actual,3,2,c)-value(actual,3,1,c))<1e-7f);
+ CHECK(std::abs(value(actual,3,2,c)-value(actual,4,2,c))<1e-7f); // deep source independent of scene and FFT
+ CHECK(std::abs(value(actual,12,2,c)-value(actual,12,1,c))<1e-7f); // no-scene source fallback
+ const float contrast0=value(actual,8,2,c)-value(actual,9,2,c),contrast1=value(actual,10,2,c)-value(actual,11,2,c);
+ CHECK(std::abs(contrast0-contrast1)<2e-6f);
+ CHECK(std::abs(contrast0-(base[8][4+c]-base[9][4+c])*value(actual,8,0,c)*base[8][8])<2e-6f);
+ CHECK(std::abs(value(actual,13,3,c)-value(actual,14,3,c))<1e-7f); // no second river gate
+ }
+ CHECK(std::abs(value(old,0,2,0)-base[0][4])>.1f); // old whole-body factor violates zero-path identity
+ CHECK(std::abs(value(old,0,1,2)-value(old,1,1,2))>.01f); // old FFT colour selection is armed
+ const float oldContrast0=value(old,8,2,0)-value(old,9,2,0),oldContrast1=value(old,10,2,0)-value(old,11,2,0);
+ CHECK(std::abs(oldContrast0-oldContrast1)>.1f);
+ printf("sdl_gpu_frame_selfcheck: M4B shared material transport: %u fixtures, max CPU/GPU error %.8f; zero/deep/fallback/contrast/context/FFT-independence and old controls passed\n",rows,maximumError);
+}
+
+static std::vector<float> read_ocean(SdlGpuFrame *frame,unsigned mip=0)
+{
+ SDL_GPUTexture *textures[6];for(unsigned i=0;i<6;++i) textures[i]=frame->Ocean_Map(i);
+ return read_float_targets(frame,textures,6,WaterFftSpectrum::Resolution>>mip,WaterFftSpectrum::Resolution>>mip,mip);
+}
+
+using OceanMipReference=std::array<std::vector<double>,WaterFftSpectrum::Phases+1>;
+static OceanMipReference ocean_mip_reference(const std::vector<float> &base)
+{
+ // Independent direct box integrals of actual GPU base texels, not repeated averages of the
+ // runtime's previous mip. Every channel remains signed float, including all derivatives.
+ using namespace WaterFftSpectrum;OceanMipReference result;
+ for(unsigned level=0;level<=Phases;++level) {
+ const unsigned side=Resolution>>level,block=1u<<level;
+ result[level].resize(6*side*side*4);
+ for(unsigned map=0;map<6;++map) for(unsigned y=0;y<side;++y) for(unsigned x=0;x<side;++x) for(unsigned c=0;c<4;++c) {
+ double sum=0;
+ for(unsigned by=0;by<block;++by) for(unsigned bx=0;bx<block;++bx)
+ sum+=base[((map*Resolution+y*block+by)*Resolution+x*block+bx)*4+c];
+ result[level][((map*side+y)*side+x)*4+c]=sum/double(block*block);
+ }
+ }
+ return result;
+}
+static double ocean_mip_sample(const OceanMipReference &mips,unsigned map,unsigned channel,double u,double v,double lod)
+{
+ using namespace WaterFftSpectrum;lod=(std::max)(0.0,(std::min)(double(Phases),lod));
+ const unsigned low=unsigned(lod),high=(std::min)(Phases,low+1);const double blend=lod-low;
+ auto bilinear=[&](unsigned level) {
+ const int side=int(Resolution>>level);const double x=u*side-.5,y=v*side-.5;
+ const int ix=int(std::floor(x)),iy=int(std::floor(y));const double fx=x-ix,fy=y-iy;
+ auto at=[&](int px,int py) {px=(px%side+side)%side;py=(py%side+side)%side;
+ return mips[level][((map*side+unsigned(py))*side+unsigned(px))*4+channel];};
+ return (at(ix,iy)*(1-fx)+at(ix+1,iy)*fx)*(1-fy)+(at(ix,iy+1)*(1-fx)+at(ix+1,iy+1)*fx)*fy;
+ };
+ return bilinear(low)*(1-blend)+bilinear(high)*blend;
+}
+static std::array<std::vector<float>,WaterFftSpectrum::Phases+1> check_ocean_mip_contents(
+ SdlGpuFrame *frame,const OceanMipReference &expected,double &maximumError)
+{
+ std::array<std::vector<float>,WaterFftSpectrum::Phases+1> result;
+ for(unsigned level=0;level<result.size();++level) {
+ result[level]=read_ocean(frame,level);bool valid=result[level].size()==expected[level].size();
+ for(size_t i=0;i<result[level].size();++i) {
+ const double error=std::abs(double(result[level][i])-expected[level][i]);maximumError=(std::max)(maximumError,error);
+ valid &= std::isfinite(result[level][i]) && error<1e-6+std::abs(expected[level][i])*3e-6;
+ }
+ CHECK(valid);
+ }
+ return result;
+}
+static void check_ocean_fractional_mips(SdlGpuFrame *frame,const OceanMipReference &expected)
+{
+ const unsigned width=36,height=6;
+ std::string source;
+ for(unsigned i=0;i<6;++i) source+="Texture2D<float4> T"+std::to_string(i)+":register(t"+std::to_string(i)+",space2);SamplerState S"+std::to_string(i)+":register(s"+std::to_string(i)+",space2);\n";
+ source+="float4 main(float4 position:SV_Position):SV_Target0 { int2 pixel=int2(position.xy);float lod=pixel.x*0.25;float2 uv=float2((pixel.x%3)-1,pixel.y%3)*2.0;\n";
+ for(unsigned i=0;i<6;++i) source+="if(pixel.y=="+std::to_string(i)+") return T"+std::to_string(i)+".SampleLevel(S"+std::to_string(i)+",uv,lod);\n";
+ source+="return 0;}\n";
+ std::vector<unsigned char> spirv;std::string error;
+ CHECK(SDL3_Compile_HLSL_To_SPIRV(WaterFftSpectrum::VertexHlsl(),true,spirv,error));
+ SDL_GPUShader *vertex=SDL3_Create_Shader(frame->Device(),spirv,true,error);CHECK(vertex);
+ CHECK(SDL3_Compile_HLSL_To_SPIRV(source,false,spirv,error));
+ SDL_GPUShader *pixel=SDL3_Create_Shader(frame->Device(),spirv,false,error);CHECK(pixel);
+ SDL_GPUColorTargetDescription colour={};colour.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
+ SDL_GPUGraphicsPipelineCreateInfo info={};info.vertex_shader=vertex;info.fragment_shader=pixel;
+ info.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;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();
+ SDL_GPUGraphicsPipeline *pipeline=vertex&&pixel?SDL_CreateGPUGraphicsPipeline(frame->Device(),&info):NULL;CHECK(pipeline);
+ SDL_GPUTextureCreateInfo texture={};texture.type=SDL_GPU_TEXTURETYPE_2D;texture.format=colour.format;
+ texture.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET|SDL_GPU_TEXTUREUSAGE_SAMPLER;texture.width=width;texture.height=height;
+ texture.layer_count_or_depth=texture.num_levels=1;SDL_GPUTexture *target=SDL_CreateGPUTexture(frame->Device(),&texture);CHECK(target);
+ if(pipeline && target) {
+ frame->Set_Target({target,frame->Depth_For(width,height),width,height});SdlRecordedDraw draw={};draw.Pipeline=pipeline;draw.Count=3;
+ memset(frame->Stage(16,draw.VertexOffset),0,16);draw.SamplerCount=6;
+ for(unsigned i=0;i<6;++i) {draw.Textures[i]=frame->Ocean_Map(i);draw.Samplers[i]=frame->Ocean_Sampler();}
+ draw.Viewport[2]=draw.Scissor[2]=width;draw.Viewport[3]=draw.Scissor[3]=height;draw.Viewport[5]=1;frame->Record_Draw(draw);
+ const auto sampled=read_float_targets(frame,&target,1,width,height);double maximumError=0,armedNearest=0,armedBase=0;
+ for(unsigned y=0;y<height;++y) for(unsigned x=0;x<width;++x) for(unsigned c=0;c<4;++c) {
+ const double lod=x*.25,u=2*(int(x%3)-1),v=2*(y%3);
+ const double value=ocean_mip_sample(expected,y,c,u,v,lod),actual=sampled[(y*width+x)*4+c];
+ maximumError=(std::max)(maximumError,std::abs(actual-value));
+ CHECK(std::abs(actual-value)<1e-5);
+ armedNearest=(std::max)(armedNearest,std::abs(value-ocean_mip_sample(expected,y,c,u,v,std::floor(lod+.5))));
+ armedBase=(std::max)(armedBase,std::abs(value-ocean_mip_sample(expected,y,c,u,v,0)));
+ }
+ CHECK(armedNearest>1e-4 && armedBase>1e-3);
+ printf("sdl_gpu_frame_selfcheck: all6 FFT maps fractional/negative-wrapped mip sampling: max error %.9f, armed nearest %.6f and base-only %.6f\n",maximumError,armedNearest,armedBase);
+ }
+ CHECK(frame->Flush());frame->Set_Target(frame->Back_Buffer_Target());
+ if(target) SDL_ReleaseGPUTexture(frame->Device(),target);if(pipeline) SDL_ReleaseGPUGraphicsPipeline(frame->Device(),pipeline);
+ if(vertex) SDL_ReleaseGPUShader(frame->Device(),vertex);if(pixel) SDL_ReleaseGPUShader(frame->Device(),pixel);
+}
+
+static void check_gpu_water_vertex_uniform_order(SdlGpuFrame *frame)
+{
+ // Use the real recorded draw path, with the complete water block shared between VS b1 and
+ // PS b0. Reading its last hull and FFT tail catches a truncated copy that a count-only test
+ // misses. All draws remain queued while the source variables are changed again.
+ const unsigned width=4,rows=6;
+ const unsigned timeRegister=offsetof(SdlWaterPixelConstants,WaterParameters)/16;
+ const unsigned lastHullRegister=offsetof(SdlWaterPixelConstants,HullData)/16+79;
+ const unsigned fftRegister=offsetof(SdlWaterPixelConstants,FftParameters)/16;
+ const unsigned historyAreaRegister=offsetof(SdlWaterPixelConstants,FoamHistoryArea)/16;
+ const unsigned historyRegister=offsetof(SdlWaterPixelConstants,FoamHistoryParameters)/16;
+ const unsigned contactRegister=offsetof(SdlWaterPixelConstants,ContactHullData)/16;
+ const unsigned lastContactRegister=contactRegister+79;
+ const unsigned fillRegister=offsetof(SdlWaterPixelConstants,FoamFillLights)/16;
+ const unsigned coastalAreaRegister=offsetof(SdlWaterPixelConstants,CoastalArea)/16;
+ const unsigned coastalParamsRegister=offsetof(SdlWaterPixelConstants,CoastalParams)/16;
+ CHECK(contactRegister==100 && fillRegister==180 && coastalAreaRegister==184 && coastalParamsRegister==185
+ && sizeof(SdlWaterPixelConstants)==188*16);
+ std::string block="cbuffer WaterBlock : register(b1,space1) { float4 Water[";
+ block+=std::to_string(sizeof(SdlWaterPixelConstants)/16)+"]; };\n";
+ const std::string output="struct Output { float4 Position:SV_Position; [[vk::location(0)]] float4 Value:TEXCOORD0; };\n";
+ const std::string position="Output o;o.Position=float4(id==1?3.0:-1.0,id==2?3.0:-1.0,0,1);";
+ std::string waterVertex="cbuffer FixedBlock : register(b0,space1) { float4 Fixed; };\n"+block+output;
+ waterVertex+="Output main(uint id:SV_VertexID) {"+position+
+ "o.Value=float4(Fixed.x,Water["+std::to_string(timeRegister)+"].x,Water["+
+ std::to_string(lastHullRegister)+"].w,Water["+std::to_string(fftRegister)+"].y);"
+ "o.Value.x+=Water["+std::to_string(historyAreaRegister)+"].x;"
+ "o.Value.z+=Water["+std::to_string(historyRegister)+"].w;"
+ "o.Value.x+=Water["+std::to_string(contactRegister)+"].w;"
+ "o.Value.y+=Water["+std::to_string(lastContactRegister)+"].w;"
+ "o.Value.x+=Water["+std::to_string(fillRegister)+"].w+Water["+std::to_string(fillRegister+1)+"].x;"
+ "o.Value+=Water["+std::to_string(coastalAreaRegister)+"]+Water["+std::to_string(coastalParamsRegister)+"];return o;}\n";
+ std::string waterPixel="cbuffer WaterBlock : register(b0,space3) { float4 Water["+
+ std::to_string(sizeof(SdlWaterPixelConstants)/16)+"]; };\n";
+ waterPixel+="float4 main([[vk::location(0)]] float4 value:TEXCOORD0):SV_Target0 {\n"
+ "value.w+=abs(value.y-Water["+std::to_string(timeRegister)+"].x-Water["+
+ std::to_string(lastContactRegister)+"].w-Water["+std::to_string(coastalAreaRegister)+"].y-Water["+
+ std::to_string(coastalParamsRegister)+"].y)*100.0;"
+ "value.x-=Water["+std::to_string(historyAreaRegister)+"].x;"
+ "value.z+=Water["+std::to_string(historyAreaRegister)+"].w;"
+ "value.w+=Water["+std::to_string(historyRegister)+"].w;"
+ "value.z+=Water["+std::to_string(lastContactRegister)+"].z;"
+ "value.y+=Water["+std::to_string(fillRegister+3)+"].z;"
+ "value.z+=Water["+std::to_string(fillRegister+2)+"].z;"
+ "value+=2*Water["+std::to_string(coastalAreaRegister)+"]+3*Water["+std::to_string(coastalParamsRegister)+"];return value;}\n";
+ const std::string plainVertex="cbuffer FixedBlock : register(b0,space1) { float4 Fixed; };\n"+output+
+ "Output main(uint id:SV_VertexID) {"+position+"o.Value=float4(9,8,7,6)*Fixed.x;return o;}\n";
+ const char *plainPixel="float4 main([[vk::location(0)]] float4 value:TEXCOORD0):SV_Target0 {return value;}\n";
+ struct Resources {
+ SDL_GPUDevice *device;SDL_GPUShader *vs[2]={},*ps[2]={};SDL_GPUGraphicsPipeline *pipelines[2]={};SDL_GPUTexture *target=NULL;
+ ~Resources() {
+ if(target) SDL_ReleaseGPUTexture(device,target);
+ for(unsigned i=0;i<2;++i) {
+ if(pipelines[i]) SDL_ReleaseGPUGraphicsPipeline(device,pipelines[i]);
+ if(vs[i]) SDL_ReleaseGPUShader(device,vs[i]);if(ps[i]) SDL_ReleaseGPUShader(device,ps[i]);
+ }
+ }
+ } resources;
+ resources.device=frame->Device();
+ for(unsigned water=0;water<2;++water) {
+ std::vector<unsigned char> spirv;std::string error;
+ bool compiled=SDL3_Compile_HLSL_To_SPIRV(water?waterVertex:plainVertex,true,spirv,error);CHECK(compiled);
+ if(!compiled) {printf("water uniform VS: %s\n",error.c_str());return;}
+ unsigned samplers=0,buffers=0;SDL3_Shader_Slots(spirv,true,samplers,buffers);
+ CHECK(samplers==0 && buffers==(water?2u:1u));
+ resources.vs[water]=SDL3_Create_Shader(resources.device,spirv,true,error);CHECK(resources.vs[water]);
+ compiled=SDL3_Compile_HLSL_To_SPIRV(water?waterPixel:std::string(plainPixel),false,spirv,error);CHECK(compiled);
+ if(!compiled) {printf("water uniform PS: %s\n",error.c_str());return;}
+ resources.ps[water]=SDL3_Create_Shader(resources.device,spirv,false,error);CHECK(resources.ps[water]);
+ if(!resources.vs[water] || !resources.ps[water]) return;
+ SDL_GPUColorTargetDescription colour={};colour.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
+ SDL_GPUGraphicsPipelineCreateInfo info={};info.vertex_shader=resources.vs[water];info.fragment_shader=resources.ps[water];
+ info.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;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();
+ resources.pipelines[water]=SDL_CreateGPUGraphicsPipeline(resources.device,&info);CHECK(resources.pipelines[water]);
+ if(!resources.pipelines[water]) return;
+ }
+ SDL_GPUTextureCreateInfo texture={};texture.type=SDL_GPU_TEXTURETYPE_2D;texture.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
+ texture.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;texture.width=width;texture.height=rows;texture.layer_count_or_depth=texture.num_levels=1;
+ resources.target=SDL_CreateGPUTexture(resources.device,&texture);CHECK(resources.target);if(!resources.target) return;
+ CHECK(frame->Flush());frame->Set_Target({resources.target,frame->Depth_For(width,rows),width,rows});
+ const bool waterRows[rows]={true,false,true,true,false,true};
+ const unsigned state[rows]={0,0,1,0,0,1};
+ const float expectedWater[2][4]={{.25f,2.5f,79.25f,1.0f},{.75f,9.125f,-3.75f,0.0f}};
+ const float historyTail[2][3]={{-128,.25f,24.25f},{192,.125f,26.0f}};
+ const float contactTail[2][3]={{12,-175.25f,91.5f},{0,0,0}};
+ const float fillTail[2][4]={{1,2.25f,-.875f,5.125f},{0,0,0,0}};
+ // Every native tail component is read in both stages. State 1 is explicit invalid/zero,
+ // including after non-water; state 0 returns immediately after a rectangle clear.
+ const float coastalArea[2][4]={{-32,48,256,128},{0,0,0,0}};
+ const float coastalParams[2][4]={{1,7,24.25f,24.375f},{0,0,0,0}};
+ for(unsigned row=0;row<rows;++row) {
+ if(row==3) {
+ // Engine rectangle-clear pipelines target its native UNORM scene format.
+ frame->Set_Target(frame->Back_Buffer_Target());
+ frame->Clear_Rect(0,0,1,1,true,false,false,0xFF123456u,1,0);
+ frame->Set_Target({resources.target,frame->Depth_For(width,rows),width,rows});
+ }
+ SdlRecordedDraw draw={};draw.Pipeline=resources.pipelines[waterRows[row]?1:0];draw.Count=3;
+ memset(frame->Stage(16,draw.VertexOffset),0,16);
+ float fixed[4]={waterRows[row]?expectedWater[state[row]][0]:2.0f,0,0,0};
+ draw.VertexConstants=frame->Constants(0,fixed,sizeof(fixed));draw.VertexConstantsSize=sizeof(fixed);
+ if(waterRows[row]) {
+ SdlWaterPixelConstants water={};water.WaterParameters[0]=expectedWater[state[row]][1];
+ water.HullData[79][3]=expectedWater[state[row]][2];water.FftParameters[0]=1;water.FftParameters[1]=expectedWater[state[row]][3];
+ water.FoamHistoryArea[0]=historyTail[state[row]][0];water.FoamHistoryArea[3]=historyTail[state[row]][1];
+ water.FoamHistoryParameters[3]=historyTail[state[row]][2];
+ water.ContactHullData[0][3]=contactTail[state[row]][0];
+ water.ContactHullData[79][3]=contactTail[state[row]][1];
+ water.ContactHullData[79][2]=contactTail[state[row]][2];
+ water.FoamFillLights[0][3]=fillTail[state[row]][0];water.FoamFillLights[1][0]=fillTail[state[row]][1];
+ water.FoamFillLights[2][2]=fillTail[state[row]][2];water.FoamFillLights[3][2]=fillTail[state[row]][3];
+ memcpy(water.CoastalArea,coastalArea[state[row]],sizeof(water.CoastalArea));
+ memcpy(water.CoastalParams,coastalParams[state[row]],sizeof(water.CoastalParams));
+ draw.PixelConstants=frame->Constants(1,&water,sizeof(water));draw.PixelConstantsSize=sizeof(water);
+ draw.VertexWaterConstants=draw.PixelConstants;draw.VertexWaterConstantsSize=draw.PixelConstantsSize;
+ // Poison the source after recording: deferred execution must read its copied snapshot.
+ memset(&water,0xDA,sizeof(water));
+ } else CHECK(draw.VertexWaterConstantsSize==0 && draw.PixelConstantsSize==0);
+ draw.Viewport[1]=float(row);draw.Viewport[2]=width;draw.Viewport[3]=1;draw.Viewport[5]=1;
+ draw.Scissor[1]=row;draw.Scissor[2]=width;draw.Scissor[3]=1;frame->Record_Draw(draw);
+ }
+ const auto values=read_float_targets(frame,&resources.target,1,width,rows);
+ frame->Set_Target(frame->Back_Buffer_Target());
+ bool matched=values.size()==width*rows*4;
+ if(matched) for(unsigned row=0;row<rows;++row) for(unsigned x=0;x<width;++x) for(unsigned c=0;c<4;++c) {
+ float expected=waterRows[row]?expectedWater[state[row]][c]:float(9-c)*2.0f;
+ if(waterRows[row] && c>=2)expected+=historyTail[state[row]][2]+(c==2?historyTail[state[row]][1]:0);
+ if(waterRows[row] && c<3)expected+=contactTail[state[row]][c];
+ if(waterRows[row] && c<3)expected+=c==0?fillTail[state[row]][0]+fillTail[state[row]][1]:fillTail[state[row]][c==1?3:2];
+ if(waterRows[row])expected+=3*coastalArea[state[row]][c]+4*coastalParams[state[row]][c];
+ matched &= std::isfinite(values[(row*width+x)*4+c]) && std::abs(values[(row*width+x)*4+c]-expected)<0.00001f;
+ }
+ CHECK(matched);
+ printf("sdl_gpu_frame_selfcheck: GPU water VS slot1: %u queued draws, shared 188-float4 pixel snapshot, mean/FFT/history/contact/fill-light/coastal tails in both stages, explicit zero contact/light/coastal fallback, intervening non-water and rectangle clear checked\n",rows);
+}
+
+static void check_gpu_water_visual_uniform_order(SdlGpuFrame *frame)
+{
+ // Every packet register and component is rendered, including both sides of b1/b2/b3
+ // boundaries and hull eight's tail. Queued draws outlive poisoned stack sources.
+ using namespace WaterHullVisualLayout;
+ const unsigned width=PacketRegisters+MaxHulls,rows=8;
+ const char *output="struct Output { float4 Position:SV_Position; [[vk::location(0)]] float4 Value:TEXCOORD0; };\n";
+ const char *position="Output o;o.Position=float4(id==1?3.0:-1.0,id==2?3.0:-1.0,0,1);";
+ std::string vs=std::string(output)+WaterFftSampling::UniformSource("WaterVertex",1)+
+ "cbuffer FixedBlock:register(b0){float4 Fixed;};\n"+
+ "Output main(uint id:SV_VertexID){"+position+
+ "o.Value=float4(WaterParameters.x,ContactHullData[79].w,FoamFillLights[3].z,1)+Fixed+CoastalArea+CoastalParams;return o;}\n";
+ std::string ps=WaterFftSampling::UniformSource("WaterFragment",0,true)+R"HLSL(
+float4 main(float4 position:SV_Position,[[vk::location(0)]] float4 value:TEXCOORD0):SV_Target0 {
+ int x=(int)position.x;
+ value+=2*CoastalArea+3*CoastalParams;
+ if(x<704) {
+ float4 packet;
+ if(x<256) packet=VisualHullBlock0[x];
+ else if(x<512) packet=VisualHullBlock1[x-256];
+ else packet=VisualHullBlock2[x-512];
+ return packet+VisualHullMeta[x/88]+value;
+ }
+ return VisualHullMeta[x-704]+value;
+}
+)HLSL";
+ const std::string plainVS=std::string(output)+"Output main(uint id:SV_VertexID){"+position+
+ "o.Value=float4(9,8,7,6);return o;}\n";
+ const char *plainPS="float4 main([[vk::location(0)]] float4 value:TEXCOORD0):SV_Target0{return value;}\n";
+ // UniformSource emits engine register syntax; the production generator retargets it
+ // to SDL descriptor sets. Apply that same register placement before direct compilation.
+ const bool placed=sdl3target_detail::place_registers(vs,true) && sdl3target_detail::place_registers(ps,false);
+ CHECK(placed);if(!placed)return;
+ struct Resources {
+ SDL_GPUDevice *device;SDL_GPUShader *vs[2]={},*ps[2]={};SDL_GPUGraphicsPipeline *pipelines[2]={};SDL_GPUTexture *target=NULL;
+ ~Resources() {
+ if(target) SDL_ReleaseGPUTexture(device,target);
+ for(unsigned i=0;i<2;++i) {
+ if(pipelines[i]) SDL_ReleaseGPUGraphicsPipeline(device,pipelines[i]);
+ if(vs[i]) SDL_ReleaseGPUShader(device,vs[i]);if(ps[i]) SDL_ReleaseGPUShader(device,ps[i]);
+ }
+ }
+ } resources;
+ resources.device=frame->Device();
+ for(unsigned water=0;water<2;++water) {
+ std::vector<unsigned char> spirv;std::string error;
+ bool compiled=SDL3_Compile_HLSL_To_SPIRV(water?vs:plainVS,true,spirv,error);CHECK(compiled);
+ if(!compiled){printf("visual hull transport VS: %s\n",error.c_str());return;}
+ unsigned samplers=0,buffers=0;SDL3_Shader_Slots(spirv,true,samplers,buffers);
+ CHECK(samplers==0 && buffers==(water?2u:0u));
+ if(samplers!=0 || buffers!=(water?2u:0u))return;
+ resources.vs[water]=SDL3_Create_Shader(resources.device,spirv,true,error);CHECK(resources.vs[water]);
+ compiled=SDL3_Compile_HLSL_To_SPIRV(water?ps:std::string(plainPS),false,spirv,error);CHECK(compiled);
+ if(!compiled){printf("visual hull transport PS: %s\n",error.c_str());return;}
+ SDL3_Shader_Slots(spirv,false,samplers,buffers);CHECK(samplers==0 && buffers==(water?4u:0u));
+ if(samplers!=0 || buffers!=(water?4u:0u))return;
+ resources.ps[water]=SDL3_Create_Shader(resources.device,spirv,false,error);CHECK(resources.ps[water]);
+ if(!resources.vs[water] || !resources.ps[water]) return;
+ SDL_GPUColorTargetDescription colour={};colour.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
+ SDL_GPUGraphicsPipelineCreateInfo info={};info.vertex_shader=resources.vs[water];info.fragment_shader=resources.ps[water];
+ info.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;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();
+ resources.pipelines[water]=SDL_CreateGPUGraphicsPipeline(resources.device,&info);CHECK(resources.pipelines[water]);
+ if(!resources.pipelines[water]) return;
+ }
+ SDL_GPUTextureCreateInfo texture={};texture.type=SDL_GPU_TEXTURETYPE_2D;texture.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
+ texture.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;texture.width=width;texture.height=rows;texture.layer_count_or_depth=texture.num_levels=1;
+ resources.target=SDL_CreateGPUTexture(resources.device,&texture);CHECK(resources.target);if(!resources.target)return;
+ CHECK(frame->Flush());frame->Set_Target({resources.target,frame->Depth_For(width,rows),width,rows});
+ const bool waterRows[rows]={true,false,true,true,false,true,true,true};
+ const unsigned states[rows]={1,0,2,1,0,0,1,2};
+ for(unsigned row=0;row<rows;++row) {
+ if(row==3) {
+ frame->Set_Target(frame->Back_Buffer_Target());frame->Clear_Rect(0,0,1,1,true,false,false,0xFF123456u,1,0);
+ frame->Set_Target({resources.target,frame->Depth_For(width,rows),width,rows});
+ }
+ if(row==6) {
+ // A new batch and replacement scene target cannot reuse old constant-arena offsets.
+ CHECK(frame->Flush());CHECK(frame->Resize(WIDTH+3,HEIGHT+2));
+ frame->Set_Target({resources.target,frame->Depth_For(width,rows),width,rows});
+ }
+ SdlRecordedDraw draw={};draw.Pipeline=resources.pipelines[waterRows[row]?1:0];draw.Count=3;
+ memset(frame->Stage(16,draw.VertexOffset),0,16);
+ if(waterRows[row]) {
+ const unsigned state=states[row];SdlWaterVisualPixelConstants water={};float packet[PacketRegisters][4]={};
+ float fixed[4]={.0625f,.125f,.1875f,.25f};
+ draw.VertexConstants=frame->Constants(0,fixed,sizeof(fixed));draw.VertexConstantsSize=sizeof(fixed);
+ water.Water.WaterParameters[0]=state+.125f;water.Water.ContactHullData[79][3]=state*2+.25f;
+ water.Water.FoamFillLights[3][2]=state*3+.5f;
+ for(unsigned c=0;c<4;++c) {
+ water.Water.CoastalArea[c]=state?float(state*8+c)+.25f:0;
+ water.Water.CoastalParams[c]=state?float(state*4+c)+.125f:0;
+ }
+ for(unsigned h=0;h<MaxHulls;++h)for(unsigned c=0;c<4;++c)
+ water.VisualHullMeta[h][c]=state?float(state*100+h*4+c)+.5f:0;
+ for(unsigned r=0;r<PacketRegisters;++r)for(unsigned c=0;c<4;++c)
+ packet[r][c]=state?float(state*10000+r*4+c)+.25f:0;
+ draw.PixelConstants=frame->Constants(1,&water,sizeof(water));draw.PixelConstantsSize=sizeof(water);
+ draw.VertexWaterConstants=draw.PixelConstants;draw.VertexWaterConstantsSize=sizeof(SdlWaterPixelConstants);
+ for(unsigned b=0;b<BlockCount;++b) {
+ draw.PixelWaterConstantsSize[b]=BlockRegisters(b)*16;
+ draw.PixelWaterConstants[b]=frame->Constants(1,packet[BlockOffset(b)],draw.PixelWaterConstantsSize[b],b+1);
+ }
+ // Cache keys include the slot, so same-sized b1/b2 and later b0 cannot evict each other.
+ CHECK(frame->Constants(1,packet[0],Block0Registers*16,1)==draw.PixelWaterConstants[0]);
+ CHECK(frame->Constants(1,&water,sizeof(water))==draw.PixelConstants);
+ memset(&water,0xDA,sizeof(water));memset(packet,0xDB,sizeof(packet));
+ } else {
+ CHECK(draw.PixelConstantsSize==0 && draw.VertexWaterConstantsSize==0);
+ for(unsigned b=0;b<BlockCount;++b)CHECK(draw.PixelWaterConstantsSize[b]==0);
+ }
+ draw.Viewport[1]=float(row);draw.Viewport[2]=width;draw.Viewport[3]=1;draw.Viewport[5]=1;
+ draw.Scissor[1]=row;draw.Scissor[2]=width;draw.Scissor[3]=1;frame->Record_Draw(draw);
+ }
+ const auto values=read_float_targets(frame,&resources.target,1,width,rows);
+ frame->Set_Target(frame->Back_Buffer_Target());CHECK(frame->Resize(WIDTH,HEIGHT));
+ bool matched=values.size()==width*rows*4;unsigned armedLatest=0,armedBoundary=0;double maxError=0;
+ if(matched)for(unsigned row=0;row<rows;++row)for(unsigned x=0;x<width;++x)for(unsigned c=0;c<4;++c) {
+ const unsigned state=states[row],h=x<PacketRegisters?x/RegistersPerHull:x-PacketRegisters;
+ double expected=9-c;
+ if(waterRows[row]) {
+ const double prefix=c==0?state+.125:c==1?state*2+.25:c==2?state*3+.5:1;
+ expected=prefix+(c+1)*.0625+(state?state*100+h*4+c+.5:0);
+ if(state)expected+=3*(state*8+c+.25)+4*(state*4+c+.125);
+ if(x<PacketRegisters)expected+=state?state*10000+x*4+c+.25:0;
+ }
+ const double actual=values[(row*width+x)*4+c],error=std::abs(actual-expected);maxError=std::max(maxError,error);
+ matched&=std::isfinite(actual) && error<.0001;
+ if(waterRows[row] && state==1 && x<PacketRegisters)armedLatest+=std::abs(actual-(expected+10000))>100;
+ if(waterRows[row] && state && (x==256 || x==512))armedBoundary+=std::abs(actual-(expected-1024))>100;
+ }
+ CHECK(matched && armedLatest>0 && armedBoundary>0);
+ printf("sdl_gpu_frame_selfcheck: visual hull transport: all704 packet float4s +8 metadata, PS slots0..3, 188-register VS alias and 196-register PS common, both coastal float4s in both stages, queued A/B/zero, non-water, clear, new batch, resize; max error %.9g, armed %u/%u\n",maxError,armedLatest,armedBoundary);
+}
+
+static void check_gpu_water_visual_query(SdlGpuFrame *frame)
+{
+ // Closed-form geometry is the oracle, never WaterHullVisual::Query. Every
+ // hull uses all 96 index scalars, exercising 255/256,511/512 and703.w.
+ using namespace WaterHullVisualLayout;
+ const unsigned width=MaxHulls*3,rows=27;
+ const char *vs="float4 main(uint id:SV_VertexID):SV_Position{return float4(id==1?3.0:-1.0,id==2?3.0:-1.0,0,1);}";
+ std::string ps=WaterFftSampling::UniformSource("WaterQuery",0,true)+WaterHullVisual::Source()+R"HLSL(
+float4 main(float4 position:SV_Position):SV_Target0 {
+ int column=(int)position.x,hull=column/3;
+ float scale=1.0+0.25*hull;
+ float3 q=float3(float2(17*hull,-3*hull)+WaterParameters.xy*scale,WaterParameters.z);
+ int mode=(int)WaterParameters.w;
+ if(mode==19) hull=-1;
+ if(mode==20) hull=8;
+ WaterVisualResult r=WaterVisualQuery(hull,q);
+ if(column%3==0) return float4(r.distance,r.hasSegment,r.coplanar,r.segmentCount);
+ if(column%3==1) return float4(r.closest,r.positive);
+ return float4(r.negative,r.minY,r.maxY);
+}
+)HLSL";
+ const bool placed=sdl3target_detail::place_registers(ps,false);
+ CHECK(placed);if(!placed)return;
+ struct Resources {
+ SDL_GPUDevice *device;SDL_GPUShader *vs=nullptr,*ps=nullptr;SDL_GPUGraphicsPipeline *pipeline=nullptr;SDL_GPUTexture *target=nullptr;
+ ~Resources(){if(target)SDL_ReleaseGPUTexture(device,target);if(pipeline)SDL_ReleaseGPUGraphicsPipeline(device,pipeline);
+ if(vs)SDL_ReleaseGPUShader(device,vs);if(ps)SDL_ReleaseGPUShader(device,ps);}
+ } resources;
+ resources.device=frame->Device();
+ std::vector<unsigned char> spirv;std::string error;
+ bool compiled=SDL3_Compile_HLSL_To_SPIRV(vs,true,spirv,error);CHECK(compiled);
+ if(!compiled){printf("visual query VS: %s\n",error.c_str());return;}
+ resources.vs=SDL3_Create_Shader(resources.device,spirv,true,error);CHECK(resources.vs);
+ compiled=SDL3_Compile_HLSL_To_SPIRV(ps,false,spirv,error);CHECK(compiled);
+ if(!compiled){printf("visual query PS: %s\n",error.c_str());return;}
+ unsigned samplers=0,buffers=0;SDL3_Shader_Slots(spirv,false,samplers,buffers);CHECK(samplers==0&&buffers==4);
+ if(samplers!=0 || buffers!=4)return;
+ resources.ps=SDL3_Create_Shader(resources.device,spirv,false,error);CHECK(resources.ps);
+ if(!resources.vs||!resources.ps)return;
+ SDL_GPUColorTargetDescription colour={};colour.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
+ SDL_GPUGraphicsPipelineCreateInfo info={};info.vertex_shader=resources.vs;info.fragment_shader=resources.ps;
+ info.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;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();
+ resources.pipeline=SDL_CreateGPUGraphicsPipeline(resources.device,&info);CHECK(resources.pipeline);if(!resources.pipeline)return;
+ SDL_GPUTextureCreateInfo texture={};texture.type=SDL_GPU_TEXTURETYPE_2D;texture.format=colour.format;
+ texture.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;texture.width=width;texture.height=rows;texture.layer_count_or_depth=texture.num_levels=1;
+ resources.target=SDL_CreateGPUTexture(resources.device,&texture);CHECK(resources.target);if(!resources.target)return;
+ CHECK(frame->Flush());frame->Set_Target({resources.target,frame->Depth_For(width,rows),width,rows});
+ std::vector<float> expected(width*rows*4,0);
+ const float nan=std::numeric_limits<float>::quiet_NaN(),inf=std::numeric_limits<float>::infinity();
+ for(unsigned row=0;row<rows;++row) {
+ SdlWaterVisualPixelConstants water={};float packet[PacketRegisters][4]={};
+ float qx=2,qy=3,qz=0;
+ if(row==1){qx=qy=0;qz=-2;} // exact tangent vertex
+ if(row==2){qx=4;qy=2;qz=2;} // exact top edge
+ if(row==3)qz=3; // no triangle at this height
+ if(row==4){qx=2.5f;qy=2.25f;qz=.5f;} // raked triangle at intermediate height
+ if(row==5||row==6||row==26){qx=row==26?-5.75f:row==5?5.75f:6.75f;qy=.25f;qz=row==6?1:.5f;}
+ if(row==7){qx=qy=5;qz=0;} // coplanar plane must not emit its diagonal
+ if(row==17)qx=nan;
+ if(row==18)qz=inf;
+ water.Water.WaterParameters[0]=qx;water.Water.WaterParameters[1]=qy;
+ water.Water.WaterParameters[2]=qz;water.Water.WaterParameters[3]=float(row);
+ for(unsigned h=0;h<MaxHulls;++h) {
+ const float ox=float(h*17),oy=-float(h*3),s=1+h*.25f;
+ WaterHullVisual::Packet p={};p.metadata[0]=64;p.metadata[1]=96;p.metadata[2]=512;p.metadata[3]=1;
+ const float triangle[3][3]={{0,0,-2},{8,0,2},{0,4,2}};
+ for(unsigned v=0;v<3;++v){p.data[61+v][0]=ox+s*triangle[v][0];p.data[61+v][1]=oy+s*triangle[v][1];p.data[61+v][2]=triangle[v][2];}
+ for(unsigned t=0;t<96;++t)p.data[64+t/4][t%4]=float(61+64*62+4096*63);
+ if(row==5||row==6||row==26) {
+ // Closed raked box: at height z, L=4+2z and B=1+z/2.
+ const float v[8][3]={{-2,-.5f,-1},{2,-.5f,-1},{2,.5f,-1},{-2,.5f,-1},
+ {-6,-1.5f,1},{6,-1.5f,1},{6,1.5f,1},{-6,1.5f,1}};
+ const unsigned f[12][3]={{0,1,5},{0,5,4},{1,2,6},{1,6,5},{2,3,7},{2,7,6},{3,0,4},{3,4,7},
+ {0,2,1},{0,3,2},{4,5,6},{4,6,7}};
+ for(unsigned i=0;i<8;++i){p.data[i][0]=ox+s*v[i][0];p.data[i][1]=oy+s*v[i][1];p.data[i][2]=v[i][2];}
+ p.metadata[0]=8;
+ for(unsigned t=0;t<96;++t){const auto& indices=f[t%12];p.data[64+t/4][t%4]=float(indices[0]+64*indices[1]+4096*indices[2]);}
+ }
+ if(row==7) {
+ const float v[4][2]={{0,0},{10,0},{10,10},{0,10}};
+ for(unsigned i=0;i<4;++i){p.data[i][0]=ox+s*v[i][0];p.data[i][1]=oy+s*v[i][1];p.data[i][2]=0;}
+ p.metadata[0]=4;p.metadata[1]=2;p.data[64][0]=float(0+64*1+4096*2);p.data[64][1]=float(0+64*2+4096*3);
+ }
+ if(row==8) {WaterHullVisual::Builder degenerate(-2,2);CHECK(degenerate.AddTriangle({0,0,-1},{1,1,0},{2,2,1}));CHECK(degenerate.Finish(p));}
+ if(row==9){p=WaterHullVisual::Packet{};p.metadata[3]=1;}
+ if(row==10)p.metadata[3]=0;
+ if(row==11)p.metadata[1]=97;
+ if(row==12)p.metadata[0]=65;
+ if(row==13)p.data[64][0]=nan;
+ if(row==14)p.data[64][0]+=.5f;
+ if(row==15)p.metadata[0]=63; // index63 outside declared vertex count
+ if(row==16)p.data[61][0]=nan;
+ if(row==21)p.metadata[2]=-1;
+ if(row==22)p.metadata[0]=nan;
+ if(row==23)p.metadata[0]=0; // incomplete nonempty pair
+ if(row==24)p.data[64][0]=262144;
+ if(row==25)p.metadata[1]=1.5f;
+ memcpy(water.VisualHullMeta[h],p.metadata,sizeof(p.metadata));memcpy(packet[h*RegistersPerHull],p.data,sizeof(p.data));
+ float e[12]={1e6f,0,0,0,0,0,0,0,0,0,0,0};
+ if((row<=6&&row!=3)||row==26) {
+ e[1]=1;e[3]=row==5||row==6||row==26?64:96;
+ float ax=0,ay=0,px=0,py=0,nx=0,ny=0,minY=0,maxY=0;
+ if(row==0){e[0]=4*s/std::sqrt(5.0f);ax=1.2f;ay=1.4f;px=4;ny=2;maxY=2;}
+ if(row==1)e[0]=0;
+ if(row==2){e[0]=0;ax=4;ay=2;px=8;ny=4;maxY=4;}
+ if(row==4){e[0]=2*s/std::sqrt(5.0f);ax=2.1f;ay=1.45f;px=5;ny=2.5f;maxY=2.5f;}
+ if(row==5||row==6||row==26){const float L=row==6?6:5,B=row==6?1.5f:1.25f;e[0]=.75f*s;e[2]=row==6?1:0;ax=row==26?-L:L;ay=.25f;px=L;py=0;nx=-L;ny=0;minY=-B;maxY=B;}
+ e[4]=ox+s*ax;e[5]=oy+s*ay;e[6]=ox+s*px;e[7]=oy+s*py;
+ e[8]=ox+s*nx;e[9]=oy+s*ny;e[10]=oy+s*minY;e[11]=oy+s*maxY;
+ }
+ if(row==7)e[2]=1;
+ memcpy(&expected[(row*width+h*3)*4],e,sizeof(e));
+ }
+ SdlRecordedDraw draw={};draw.Pipeline=resources.pipeline;draw.Count=3;memset(frame->Stage(16,draw.VertexOffset),0,16);
+ draw.PixelConstants=frame->Constants(1,&water,sizeof(water));draw.PixelConstantsSize=sizeof(water);
+ for(unsigned b=0;b<BlockCount;++b){draw.PixelWaterConstantsSize[b]=BlockRegisters(b)*16;
+ draw.PixelWaterConstants[b]=frame->Constants(1,packet[BlockOffset(b)],draw.PixelWaterConstantsSize[b],b+1);}
+ draw.Viewport[1]=float(row);draw.Viewport[2]=width;draw.Viewport[3]=1;draw.Viewport[5]=1;
+ draw.Scissor[1]=row;draw.Scissor[2]=width;draw.Scissor[3]=1;frame->Record_Draw(draw);
+ memset(packet,0xDB,sizeof(packet));memset(&water,0xDA,sizeof(water));
+ }
+ const auto actual=read_float_targets(frame,&resources.target,1,width,rows);frame->Set_Target(frame->Back_Buffer_Target());
+ bool matched=actual.size()==expected.size();double maxError=0;unsigned checked=0,armed=0;
+ if(matched)for(unsigned i=0;i<actual.size();++i){const double difference=std::abs(double(actual[i])-expected[i]);maxError=std::max(maxError,difference);
+ if(!std::isfinite(actual[i])||difference>.0005){if(checked<8)printf("visual query mismatch row%u hull%u component%u: %.9g expected %.9g\n",i/(width*4),(i%(width*4))/12,i%12,actual[i],expected[i]);++checked;matched=false;}
+ if(i<width*4&&i%12==0)armed+=std::abs(actual[i])>.5;}
+ CHECK(matched&&armed==8);
+ printf("sdl_gpu_frame_selfcheck: exact visual query: 27 closed-form/guard cases x8 hulls x12 outputs; triangle/raked hull/actual-height/tangent/coplanar/empty/corrupt, all packet boundaries; max error %.9g, mismatches %u, armed %u\n",maxError,checked,armed);
+}
+
+#if defined(__linux__)
+static void check_gpu_water_visual_zero_effect_skip(SdlGpuFrame *frame)
+{
+ // Compare actual emitted effects against an explicit full-query control using the current
+ // contact response in the same fragment. Only the optimized body may skip a zero-effect query.
+ // The only test instrumentation is a counter immediately before each geometry query.
+ using namespace WaterHullVisualLayout;
+ const char *oldContact=getenv("ZH_WATER_HULL_CONTACT"),*oldDebug=getenv("ZH_WATER_DEBUG");
+ const bool hadContact=oldContact!=NULL,hadDebug=oldDebug!=NULL;
+ const std::string savedContact=oldContact?oldContact:"",savedDebug=oldDebug?oldDebug:"";
+ CHECK(unsetenv("ZH_WATER_HULL_CONTACT")==0); // Exercise the ordinary launch default.
+ CHECK(unsetenv("ZH_WATER_DEBUG")==0);
+ PixelPipelineDescription description={};std::string production;
+ const bool generated=EngineShader_Pixel_Program(ENGINE_SHADER_WATER_TRAPEZOID,description,production,COMBINER_SHADER_TARGET_SDL3_GPU);
+ if(hadContact)CHECK(setenv("ZH_WATER_HULL_CONTACT",savedContact.c_str(),1)==0);else CHECK(unsetenv("ZH_WATER_HULL_CONTACT")==0);
+ if(hadDebug)CHECK(setenv("ZH_WATER_DEBUG",savedDebug.c_str(),1)==0);else CHECK(unsetenv("ZH_WATER_DEBUG")==0);
+ CHECK(generated);if(!generated)return;
+ auto extract=[&](const char *signature) {
+ const size_t start=production.find(signature),opening=start==std::string::npos?start:production.find('{',start);
+ if(opening==std::string::npos)return std::string();
+ size_t at=opening+1;int depth=1;
+ for(;at<production.size()&&depth;++at){if(production[at]=='{')++depth;else if(production[at]=='}')--depth;}
+ return depth?std::string():production.substr(start,at-start);
+ };
+ std::string current=extract("float2 oceanMeshHullEffects("),contact=extract("float4 WaterContactRegister(");
+ const std::string sharedContact=extract("float3 oceanMeshContactFoam(");
+ CHECK(!sharedContact.empty());if(sharedContact.empty())return;
+ const size_t noiseBegin=production.find("float oceanHash("),noiseEnd=production.find("float3 oceanSky(");
+ CHECK(!current.empty()&&!contact.empty()&&noiseBegin!=std::string::npos&&noiseEnd!=std::string::npos&&noiseEnd>noiseBegin);
+ if(current.empty()||contact.empty()||noiseBegin==std::string::npos||noiseEnd==std::string::npos||noiseEnd<=noiseBegin)return;
+ // Pre-skip control with the current contact-response curve. The query ordering and
+ // accumulation remain the original implementation; both paths must agree per fragment.
+ std::string previous=R"BASELINE(
+float2 oceanMeshHullEffects(float3 world,float level,float time,float offshore,
+ float incomingHeight,float footprint,float waveImpact)
+{
+ float foam=0.0,turbulence=0.0;
+ if(offshore<=0.001 || abs(world.z-level)>fftVerticalBound) return float2(0,0);
+ for(int h=0;h<clamp((int)HullParameters.x,0,8);++h) {
+ float4 meta=VisualHullMeta[h];
+ if(meta.w<0.5 || meta.y<1.0) continue;
+ int index=h*10;
+ float4 position=WaterContactRegister(index),axis=WaterContactRegister(index+1);
+ if(position.w<3.0 || abs(level-position.z)>0.1) continue;
+ float2 delta=world.xy-position.xy;
+ if(dot(delta,delta)>(meta.z+12.0)*(meta.z+12.0)) continue;
+ float2 local=float2(dot(delta,axis.xy),dot(delta,float2(-axis.y,axis.x)));
+ WaterVisualResult contact=WaterVisualQuery(h,float3(local,world.z-level));
+ if(contact.hasSegment<0.5 || contact.distance>12.0) continue;
+ float4 motion=WaterContactRegister(index+2);
+ float speed=length(motion.xy),moving=smoothstep(0.3,18.0,speed);
+ float2 velocity=float2(dot(motion.xy,axis.xy),dot(motion.xy,float2(-axis.y,axis.x)));
+ float blend=smoothstep(-0.25,0.25,velocity.x/max(speed,0.001));
+ float2 bow=lerp(contact.negative,contact.positive,blend);
+ float width=max((contact.maxY-contact.minY)*0.5,1.0);
+ float aa=clamp(footprint*0.6,0.25,1.5);
+ float wash=oceanNoise(local*float2(0.065,0.32)+float2(-time*0.12,motion.z*9.0));
+ float flecks=oceanNoise(local*0.48+float2(time*0.08,-time*0.13));
+ float collision=waterHullContactResponse(incomingHeight,waveImpact);
+ float sideWidth=1.0+moving*min(2.0,sqrt(width)*0.35)+collision*1.3;
+ float rim=1.0-smoothstep(sideWidth,sideWidth+aa,contact.distance);
+ float streak=smoothstep(0.43,0.68,wash)*(0.2+0.8*smoothstep(0.25,0.65,flecks));
+ float sideFoam=max(rim*streak*moving*0.38,
+ waterHullContactCoverage(contact.distance,footprint,incomingHeight,waveImpact,width));
+ float outer=1.0-smoothstep(sideWidth,sideWidth+3.5,contact.distance);
+ float bowDistance=length((local-bow)/float2(max(width*0.8,3.0),max(width*0.9,3.0)));
+ float bowRegion=exp(-bowDistance*bowDistance*1.4);
+ float bowWidth=2.0+moving*min(7.0,3.0+sqrt(width)*0.55);
+ float bowFoam=(1.0-smoothstep(bowWidth,bowWidth+aa,contact.distance))*bowRegion
+ *moving*(0.45+0.55*smoothstep(0.25,0.7,flecks));
+ foam=max(foam,max(sideFoam,bowFoam*0.82));
+ turbulence=max(turbulence,outer*(collision*0.18+moving*0.25)+bowFoam*0.4);
+ }
+ return saturate(float2(foam,turbulence))*offshore;
+}
+)BASELINE";
+ auto instrument=[&](std::string text,const char *name) {
+ const std::string signature="oceanMeshHullEffects(",tail="float waveImpact)\n{",query="WaterVisualResult contact=WaterVisualQuery(";
+ const size_t entry=text.find(signature),parameters=text.find(tail),call=text.find(query);
+ CHECK(entry!=std::string::npos&&parameters!=std::string::npos&&call!=std::string::npos);
+ if(entry==std::string::npos||parameters==std::string::npos||call==std::string::npos)return std::string();
+ // Work backwards so the source offsets remain valid.
+ text.insert(call,"queryCalls++; ");
+ text.replace(parameters,tail.size(),"float waveImpact,out int queryCalls)\n{\n queryCalls=0;");
+ text.replace(entry,signature.size(),std::string(name)+"(");return text;
+ };
+ current=instrument(current,"CurrentMeshEffects");previous=instrument(previous,"PreviousMeshEffects");
+ if(current.empty()||previous.empty())return;
+ const unsigned samplesX=25,samplesY=7,width=samplesX*2;
+ const char *vs="float4 main(uint id:SV_VertexID):SV_Position{return float4(id==1?3.0:-1.0,id==2?3.0:-1.0,0,1);}";
+ std::string ps=WaterFftSampling::UniformSource("WaterEffects",0,true)+WaterFftSampling::CommonSource()+
+ production.substr(noiseBegin,noiseEnd-noiseBegin)+WaterHullContactFoam::Source()+
+ contact+WaterHullVisual::Source()+sharedContact+previous+current+R"HLSL(
+float4 main(float4 pixel:SV_Position):SV_Target0 {
+ int x=(int)pixel.x,y=(int)pixel.y;
+ float2 local=float2((x/2-12)*2,(y%7-3)*2);
+ float2 world=CameraPosition.xy+local.x*CameraPosition.zw+local.y*float2(-CameraPosition.w,CameraPosition.z);
+ float3 q=float3(world,WaterParameters.x+TerrainParameters.z);
+ int oldCalls=0,newCalls=0;
+ float2 oldValue=PreviousMeshEffects(q,WaterParameters.x,WaterParameters.y,WaterParameters.z,
+ TerrainParameters.x,WaterParameters.w,TerrainParameters.y,oldCalls);
+ float2 newValue=CurrentMeshEffects(q,WaterParameters.x,WaterParameters.y,WaterParameters.z,
+ TerrainParameters.x,WaterParameters.w,TerrainParameters.y,newCalls);
+ if(x%2==0)return float4(oldValue,newValue);
+ return float4(oldCalls,newCalls,0,1);
+}
+)HLSL";
+ const bool placed=sdl3target_detail::place_registers(ps,false);CHECK(placed);if(!placed)return;
+ struct Case {
+ float speed=0,impact=.6f,height=.75f,time=1.25f,offshore=1,footprint=.5f,z=0,axisX=1,axisY=0;
+ unsigned slot=0,mix=0,packet=0,oldCalls=1,newCalls=1;
+ bool expectZero=false,expectPositive=true;
+ };
+ std::vector<Case> cases;
+ auto add=[&](Case c){cases.push_back(c);return unsigned(cases.size()-1);};
+ Case c;
+ const unsigned stationaryImpact=add(c);
+ // Zero slope alone is not calm: a broad crest must survive. The moving-threshold
+ // controls below use height=0 too, isolating the unchanged propulsion predicate.
+ c.impact=0;const unsigned stationaryCrest=add(c);
+ c.height=0;c.newCalls=0;c.expectZero=true;c.expectPositive=false;add(c);
+ c.speed=.2999f;add(c);c.speed=.3f;add(c);
+ c.speed=std::nextafter(.3f,1.0f);c.newCalls=1;c.expectZero=false;c.expectPositive=true;add(c);
+ c.speed=.3001f;add(c);c.speed=2;add(c);c.speed=18;const unsigned movingNoImpact=add(c);
+ c.speed=-18;add(c);
+ // There is no old .04 slope cutoff in the incident-energy response. Keep those
+ // samples as armed controls, plus a small positive slope at mean water height.
+ c=Case{};c.height=0;c.impact=.0001f;add(c);
+ c.impact=.03999f;add(c);c.impact=.04f;add(c);
+ c.impact=std::nextafter(.04f,1.0f);add(c);c.impact=.0401f;add(c);c.impact=.2f;add(c);c.impact=.4f;add(c);
+ const float trough=-WaterHullContactFoam::HeightScale;
+ c=Case{};c.height=std::nextafter(trough,-std::numeric_limits<float>::infinity());
+ c.newCalls=0;c.expectZero=true;c.expectPositive=false;add(c);
+ c.height=trough;add(c);
+ c.height=std::nextafter(trough,0.0f);c.newCalls=1;c.expectZero=false;c.expectPositive=true;add(c);
+ c.height=-.8f;add(c);c.height=1.6f;add(c);
+ c=Case{};c.speed=18;c.impact=0;c.height=-2;add(c);
+ for(unsigned h=0;h<MaxHulls;++h){c=Case{};c.speed=18;c.slot=h;c.time+=h*.57f;add(c);}
+ c=Case{};c.impact=0;c.height=0;c.mix=1;c.oldCalls=2;c.newCalls=1;const unsigned inactiveFirst=add(c);
+ c.mix=2;const unsigned inactiveLast=add(c);c.mix=3;c.newCalls=2;add(c);
+ c=Case{};c.speed=18;c.axisX=.6f;c.axisY=.8f;c.footprint=4;add(c);
+ c=Case{};c.z=1;add(c);c.z=2;add(c);c.z=3;c.expectZero=true;c.expectPositive=false;add(c);
+ c=Case{};c.offshore=.001f;c.oldCalls=c.newCalls=0;c.expectZero=true;c.expectPositive=false;add(c);
+ c.offshore=0;add(c);c=Case{};c.offshore=.0011f;add(c);
+ c=Case{};c.z=WaterFftGeometry::MaxVerticalDisplacement+.25f;c.oldCalls=c.newCalls=0;c.expectZero=true;c.expectPositive=false;add(c);
+ for(unsigned mode=1;mode<=6;++mode){c=Case{};c.packet=mode;c.expectZero=true;c.expectPositive=false;
+ c.oldCalls=c.newCalls=mode==3?1:0;add(c);}
+ const unsigned rows=unsigned(cases.size())*samplesY;
+ struct Resources {
+ SDL_GPUDevice *device;SDL_GPUShader *vs=nullptr,*ps=nullptr;SDL_GPUGraphicsPipeline *pipeline=nullptr;SDL_GPUTexture *target=nullptr;
+ ~Resources(){if(target)SDL_ReleaseGPUTexture(device,target);if(pipeline)SDL_ReleaseGPUGraphicsPipeline(device,pipeline);
+ if(vs)SDL_ReleaseGPUShader(device,vs);if(ps)SDL_ReleaseGPUShader(device,ps);}
+ } resources;
+ resources.device=frame->Device();std::vector<unsigned char> spirv;std::string error;
+ bool compiled=SDL3_Compile_HLSL_To_SPIRV(vs,true,spirv,error);CHECK(compiled);if(!compiled)return;
+ unsigned samplers=0,buffers=0;SDL3_Shader_Slots(spirv,true,samplers,buffers);CHECK(samplers==0&&buffers==0);if(samplers||buffers)return;
+ resources.vs=SDL3_Create_Shader(resources.device,spirv,true,error);CHECK(resources.vs);if(!resources.vs)return;
+ compiled=SDL3_Compile_HLSL_To_SPIRV(ps,false,spirv,error);CHECK(compiled);
+ if(!compiled){printf("exact zero-effect PS: %s\n",error.c_str());return;}
+ SDL3_Shader_Slots(spirv,false,samplers,buffers);CHECK(samplers==0&&buffers==4);if(samplers||buffers!=4)return;
+ resources.ps=SDL3_Create_Shader(resources.device,spirv,false,error);CHECK(resources.ps);if(!resources.ps)return;
+ SDL_GPUColorTargetDescription colour={};colour.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
+ SDL_GPUGraphicsPipelineCreateInfo info={};info.vertex_shader=resources.vs;info.fragment_shader=resources.ps;
+ info.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;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();
+ resources.pipeline=SDL_CreateGPUGraphicsPipeline(resources.device,&info);CHECK(resources.pipeline);if(!resources.pipeline)return;
+ SDL_GPUTextureCreateInfo ti={};ti.type=SDL_GPU_TEXTURETYPE_2D;ti.format=colour.format;ti.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;
+ ti.width=width;ti.height=rows;ti.layer_count_or_depth=ti.num_levels=1;
+ resources.target=SDL_CreateGPUTexture(resources.device,&ti);CHECK(resources.target);if(!resources.target)return;
+ CHECK(frame->Flush());frame->Set_Target({resources.target,frame->Depth_For(width,rows),width,rows});
+ for(unsigned row=0;row<cases.size();++row) {
+ const Case &f=cases[row];SdlWaterVisualPixelConstants water={};float packet[PacketRegisters][4]={};
+ water.Water.WaterParameters[0]=7;water.Water.WaterParameters[1]=f.time;water.Water.WaterParameters[2]=f.offshore;water.Water.WaterParameters[3]=f.footprint;
+ water.Water.TerrainParameters[0]=f.height;water.Water.TerrainParameters[1]=f.impact;water.Water.TerrainParameters[2]=f.z;
+ water.Water.CameraPosition[0]=47;water.Water.CameraPosition[1]=-29;water.Water.CameraPosition[2]=f.axisX;water.Water.CameraPosition[3]=f.axisY;
+ water.Water.HullParameters[0]=f.mix?8:float(f.slot+1);
+ for(unsigned h=0;h<MaxHulls;++h) {
+ if(f.mix?(h!=0&&h!=7):(h!=f.slot))continue;
+ const float vertices[8][3]={{-20,-4,-2},{20,-4,-2},{20,4,-2},{-20,4,-2},
+ {-20,-4,2},{20,-4,2},{20,4,2},{-20,4,2}};
+ const unsigned faces[12][3]={{0,1,5},{0,5,4},{1,2,6},{1,6,5},{2,3,7},{2,7,6},{3,0,4},{3,4,7},
+ {0,2,1},{0,3,2},{4,5,6},{4,6,7}};
+ WaterHullVisual::Packet p={};p.metadata[0]=8;p.metadata[1]=96;p.metadata[2]=21;p.metadata[3]=1;
+ for(unsigned v=0;v<8;++v)for(unsigned d=0;d<3;++d)p.data[v][d]=vertices[v][d];
+ for(unsigned t=0;t<96;++t){const auto &v=faces[t%12];p.data[64+t/4][t%4]=float(v[0]+64*v[1]+4096*v[2]);}
+ float speed=f.speed;
+ if(f.mix==1)speed=h==7?18:0;
+ if(f.mix==2)speed=h==0?18:0;
+ if(f.mix==3)speed=h==0?2:18;
+ float *position=water.Water.ContactHullData[h*10],*axis=water.Water.ContactHullData[h*10+1],*motion=water.Water.ContactHullData[h*10+2];
+ position[0]=47;position[1]=-29;position[2]=7;position[3]=4;
+ axis[0]=f.axisX;axis[1]=f.axisY;motion[0]=speed*f.axisX;motion[1]=speed*f.axisY;motion[2]=.37f+h*.09f;
+ if(f.packet==1)p.metadata[3]=0;
+ if(f.packet==2){p.metadata[0]=p.metadata[1]=0;}
+ if(f.packet==3)p.data[64][0]=std::numeric_limits<float>::quiet_NaN();
+ if(f.packet==4)position[2]=8;
+ if(f.packet==5)position[3]=2; // fallback mean packet is also explicitly empty
+ if(f.packet==6)position[0]+=1000;
+ memcpy(water.VisualHullMeta[h],p.metadata,sizeof(p.metadata));memcpy(packet[h*RegistersPerHull],p.data,sizeof(p.data));
+ }
+ SdlRecordedDraw draw={};draw.Pipeline=resources.pipeline;draw.Count=3;memset(frame->Stage(16,draw.VertexOffset),0,16);
+ draw.PixelConstants=frame->Constants(1,&water,sizeof(water));draw.PixelConstantsSize=sizeof(water);
+ for(unsigned b=0;b<BlockCount;++b){draw.PixelWaterConstantsSize[b]=BlockRegisters(b)*16;
+ draw.PixelWaterConstants[b]=frame->Constants(1,packet[BlockOffset(b)],draw.PixelWaterConstantsSize[b],b+1);}
+ draw.Viewport[1]=float(row*samplesY);draw.Viewport[2]=width;draw.Viewport[3]=samplesY;draw.Viewport[5]=1;
+ draw.Scissor[1]=row*samplesY;draw.Scissor[2]=width;draw.Scissor[3]=samplesY;frame->Record_Draw(draw);
+ memset(packet,0xDB,sizeof(packet));memset(&water,0xDA,sizeof(water));
+ }
+ const auto actual=read_float_targets(frame,&resources.target,1,width,rows);frame->Set_Target(frame->Back_Buffer_Target());
+ bool matched=actual.size()==size_t(width)*rows*4;double maxError=0;unsigned skipped=0,active=0,mismatches=0;
+ std::vector<unsigned> positive(cases.size(),0);
+ if(matched)for(unsigned row=0;row<cases.size();++row)for(unsigned y=0;y<samplesY;++y)for(unsigned x=0;x<samplesX;++x) {
+ const Case &f=cases[row];const size_t offset=((row*samplesY+y)*width+x*2)*4;
+ for(unsigned channel=0;channel<2;++channel) {
+ const float before=actual[offset+channel],after=actual[offset+2+channel];const double difference=std::abs(double(before)-after);
+ maxError=std::max(maxError,difference);
+ if(!std::isfinite(before)||!std::isfinite(after)||before<0||before>1||after<0||after>1||difference>1e-6||(f.expectZero&&(before!=0||after!=0))) {
+ if(mismatches++<8)printf("zero-effect mismatch case%u xy%u/%u channel%u old %.9g new %.9g\n",row,x,y,channel,before,after);matched=false;
+ }
+ if(after>0)++positive[row];
+ }
+ const float oldCalls=actual[offset+4],newCalls=actual[offset+5];
+ if(oldCalls!=f.oldCalls||newCalls!=f.newCalls){if(mismatches++<8)printf("zero-effect query count case%u: %.0f/%.0f expected %u/%u\n",row,oldCalls,newCalls,f.oldCalls,f.newCalls);matched=false;}
+ if(f.newCalls<f.oldCalls)++skipped;else if(f.newCalls)++active;
+ }
+ if(matched)for(unsigned row=0;row<cases.size();++row)if(cases[row].expectPositive)CHECK(positive[row]>0);
+ CHECK(matched&&skipped>0&&active>0);
+ CHECK(positive[stationaryImpact]>0&&positive[stationaryCrest]>0&&positive[movingNoImpact]>0&&positive[inactiveFirst]>0&&positive[inactiveLast]>0);
+ printf("sdl_gpu_frame_selfcheck: exact zero-effect skip: %zu cases x%u samples, emitted/control same-fragment max %.9g, mismatches %u; query-skipped %u active %u; calm/trough and moving thresholds, all8 slots/96 triangles, stationary slope/zero-slope crest, moving/reverse, mixed accumulation, actual-height and guards checked\n",
+ cases.size(),samplesX*samplesY,maxError,mismatches,skipped,active);
+}
+#endif // __linux__
+
+// Append after read_float_targets; include Platform/WaterCoastalSurf.h once and call
+// check_gpu_coastal_surf_owner(frame) in the GPU selfcheck after core math fixtures.
+// Runtime owner performs no readbacks; every readback below is test-only.
+// Insert after read_float_targets; invoke after check_gpu_fft_ocean and the
+// independent WaterCoastalIncident fixture so FFT initial-owner assertions remain valid.
+static void check_gpu_coastal_surf_from_ocean(SdlGpuFrame *frame)
+{
+ using namespace WaterCoastalSurf;
+ const uint64_t revision=0xc0a571;
+ struct Cleanup {SdlGpuFrame *frame;~Cleanup(){CHECK(frame->Clear_Coastal_Surf());frame->Set_Target(frame->Back_Buffer_Target());}} cleanup{frame};
+ CHECK(frame->Clear_Coastal_Surf());
+ std::vector<Node> nodes(3);
+ for(unsigned i=0;i<3;++i) {
+ nodes[i].world[0]=-137.25f+83*i;nodes[i].world[1]=91.5f;nodes[i].world[2]=7+4*i;
+ nodes[i].context={4,32,1,0,1,float(i)*.5f,.4f,.5f,1,1};
+ }
+ const bool installed=frame->Install_Coastal_Surf(revision,nodes,8);CHECK(installed);if(!installed)return;
+ const SdlTarget input=frame->Coastal_Surf_Field_Target(revision);CHECK(input.Colour);if(!input.Colour)return;
+ const uint64_t fftBefore=frame->Ocean_Updates();
+ CHECK(frame->Prepare_Coastal_Surf_From_Ocean(revision,2.25)); // reset needs no field/FFT phase
+ SDL_GPUTexture *initialState=frame->Coastal_Surf_State(revision);CHECK(initialState);if(!initialState)return;
+ CHECK(frame->Ocean_Updates()==fftBefore && !frame->Coastal_Surf_Field_Due(revision,2.25));
+ const auto initial=read_float_targets(frame,&initialState,1,256,256);
+ CHECK(initial.size()==MaxNodes*4);if(initial.size()!=MaxNodes*4)return;
+ auto field=[&](){return read_float_targets(frame,&input.Colour,1,256,256);};
+ const auto untouched=field();
+ const uint64_t resetUpdates=frame->Coastal_Surf_Updates();
+ CHECK(frame->Prepare_Ocean(9.0f)); // deliberately wrong phase for next source tick
+ const uint64_t wrongFft=frame->Ocean_Updates();
+ CHECK(!frame->Prepare_Coastal_Surf_From_Ocean(revision,2.35));
+ CHECK(frame->Coastal_Surf_Updates()==resetUpdates && frame->Ocean_Updates()==wrongFft);
+ CHECK(frame->Coastal_Surf_State(revision)==initialState && frame->Coastal_Surf_Time(revision)==2.25);
+ CHECK(field()==untouched);
+ CHECK(read_float_targets(frame,&initialState,1,256,256)==initial);
+
+ // An armed queued stale field must be overwritten by the real producer before
+ // Advance samples it in the same command buffer; caller input upload comes first.
+ uint32_t offset=0;float *poison=reinterpret_cast<float *>(frame->Upload_Space(MaxNodes*4*sizeof(float),offset));
+ CHECK(poison);if(!poison)return;
+ for(unsigned i=0;i<MaxNodes;++i){poison[i*4]=63;poison[i*4+1]=poison[i*4+2]=0;poison[i*4+3]=1;}
+ frame->Queue_Texture_Upload(input.Colour,0,256,256,offset);
+ CHECK(frame->Prepare_Ocean(float(2.35)*WaterFftSampling::TimeScale));
+ const uint64_t correctFft=frame->Ocean_Updates();
+ CHECK(frame->Prepare_Coastal_Surf_From_Ocean(revision,2.35));
+ CHECK(frame->Ocean_Updates()==correctFft && frame->Coastal_Surf_Updates()==resetUpdates+1);
+ SDL_GPUTexture *warmState=frame->Coastal_Surf_State(revision);CHECK(warmState);if(!warmState)return;
+ const auto generated=field(),warm=read_float_targets(frame,&warmState,1,256,256);
+ CHECK(generated.size()==MaxNodes*4 && warm.size()==MaxNodes*4);
+ if(generated.size()!=MaxNodes*4 || warm.size()!=MaxNodes*4)return;
+ bool finite=true,nonzero=false,tail=true;
+ for(unsigned i=0;i<MaxNodes;++i)for(unsigned c=0;c<4;++c)finite &= std::isfinite(generated[i*4+c])&&std::isfinite(warm[i*4+c]);
+ for(unsigned i=0;i<nodes.size();++i) {
+ CHECK(generated[i*4]!=63 && warm[i*4+2]==generated[i*4]);
+ CHECK(warm[i*4]==0 && warm[i*4+1]==0 && warm[i*4+3]==0);
+ nonzero |= std::abs(generated[i*4])>.001f || std::abs(generated[i*4+1])>.001f;
+ }
+ for(unsigned i=unsigned(nodes.size());i<MaxNodes;++i) {
+ tail &= generated[i*4]==0 && generated[i*4+1]==0 && generated[i*4+2]==0 && generated[i*4+3]==1;
+ tail &= warm[i*4]==0 && warm[i*4+1]==0 && warm[i*4+2]==0 && warm[i*4+3]==-1;
+ }
+ CHECK(finite && nonzero && tail);
+ CHECK(!frame->Coastal_Surf_Field_Due(revision,2.35));
+ CHECK(frame->Prepare_Coastal_Surf_From_Ocean(revision,2.35));
+ CHECK(frame->Coastal_Surf_Updates()==resetUpdates+1 && frame->Ocean_Updates()==correctFft);
+ CHECK(frame->Coastal_Surf_State(revision)==warmState && field()==generated);
+ CHECK(read_float_targets(frame,&warmState,1,256,256)==warm);
+
+ // Failed due-time phase checks leave the clock uncommitted, so a corrected
+ // existing FFT can retry that exact tick without losing or duplicating it.
+ CHECK(!frame->Prepare_Coastal_Surf_From_Ocean(revision,2.45));
+ CHECK(frame->Coastal_Surf_Time(revision)==2.35 && frame->Coastal_Surf_Updates()==resetUpdates+1);
+ CHECK(field()==generated);
+ CHECK(frame->Prepare_Ocean(float(2.45)*WaterFftSampling::TimeScale));
+ const uint64_t nextFft=frame->Ocean_Updates();
+ CHECK(frame->Prepare_Coastal_Surf_From_Ocean(revision,2.45));
+ CHECK(frame->Ocean_Updates()==nextFft && frame->Coastal_Surf_Updates()==resetUpdates+2);
+ SDL_GPUTexture *advancedState=frame->Coastal_Surf_State(revision);CHECK(advancedState);if(!advancedState)return;
+ const auto advanced=read_float_targets(frame,&advancedState,1,256,256),changedField=field();
+ CHECK(changedField!=generated);
+ for(unsigned i=0;i<nodes.size();++i)CHECK(advanced[i*4+2]==changedField[i*4]);
+ CHECK(!frame->Prepare_Coastal_Surf_From_Ocean(revision+1,2.55));
+ CHECK(!frame->Prepare_Coastal_Surf_From_Ocean(revision,NAN));
+ CHECK(frame->Coastal_Surf_Time(revision)==2.45 && frame->Coastal_Surf_Updates()==resetUpdates+2);
+ CHECK(frame->Prepare_Coastal_Surf_From_Ocean(revision,2.25)); // rewind: clear, do not force FFT backwards
+ CHECK(frame->Ocean_Updates()==nextFft);
+ SDL_GPUTexture *rewound=frame->Coastal_Surf_State(revision);CHECK(rewound);
+ if(rewound)CHECK(read_float_targets(frame,&rewound,1,256,256)==initial);
+ printf("sdl_gpu_frame_selfcheck: coastal production wrapper: same-phase existing FFT required, wrong-phase retry atomic, queued stale input replaced, actual field consumed by history, all atlas channels/tail, pause/rewind and no extra FFT updates checked\n");
+}
+
+// Insert after read_float_targets and invoke after the coastal owner fixture.
+static void check_gpu_coastal_surf_view(SdlGpuFrame *frame)
+{
+ using namespace WaterCoastalSurf;
+ const uint64_t revision=0xc051e;
+ const unsigned oldWidth=frame->Width(),oldHeight=frame->Height();
+ struct Cleanup {SdlGpuFrame *f;unsigned w,h;~Cleanup(){CHECK(f->Clear_Coastal_Surf());CHECK(f->Resize(w,h));f->Set_Target(f->Back_Buffer_Target());}} cleanup{frame,oldWidth,oldHeight};
+ CHECK(frame->Clear_Coastal_Surf());
+ std::vector<Node> nodes(257);
+ for(unsigned i=0;i<nodes.size();++i){nodes[i].world[0]=float(i*8);nodes[i].world[2]=7;nodes[i].context={4,32,1,0,1,1,.4f,.5f,1,1};}
+ nodes[2].world[2]=11;
+ const bool installed=frame->Install_Coastal_Surf(revision,nodes,8);CHECK(installed);if(!installed)return;
+ WaterCoastalView::Mapping mapping={-16,24,48,32,3,2};
+ std::vector<Lookup> lookups(6);
+ lookups[1].node[0]=1;lookups[1].weight[0]=1;
+ lookups[2].node[0]=2;lookups[2].weight[0]=1;
+ lookups[3].node[0]=1;lookups[3].node[1]=2;lookups[3].node[2]=257;
+ lookups[3].weight[0]=.25f;lookups[3].weight[1]=.5f;lookups[3].weight[2]=.125f;
+ lookups[4].node[0]=257;lookups[4].weight[0]=.25f;
+ lookups[5].node[0]=lookups[5].node[1]=1;lookups[5].weight[0]=lookups[5].weight[1]=.25f;
+ const uint64_t sets=frame->Coastal_Surf_View_Sets(),updates=frame->Coastal_Surf_View_Updates();
+ CHECK(frame->Set_Coastal_Surf_View(revision,mapping,7,lookups));
+ CHECK(!frame->Prepare_Coastal_Surf_View(revision) && !frame->Coastal_Surf_View(revision,7)); // history not ready
+ const SdlTarget input=frame->Coastal_Surf_Field_Target(revision);
+ CHECK(frame->Prepare_Coastal_Surf(revision,0,input));
+ SDL_GPUTexture *state=frame->Coastal_Surf_State(revision);CHECK(state);if(!state)return;
+ // Seed exact finite moments through a test-only GPU upload. The composition
+ // oracle is closed form and deliberately uses densities above coverage's range.
+ uint32_t offset=0;float *seed=reinterpret_cast<float *>(frame->Upload_Space(MaxNodes*4*sizeof(float),offset));
+ CHECK(seed);if(!seed)return;memset(seed,0,MaxNodes*4*sizeof(float));
+ for(unsigned i=0;i<MaxNodes;++i)seed[i*4+3]=i<nodes.size()?0:-1;
+ seed[0]=2;seed[1]=10;seed[4]=6;seed[5]=6;seed[8]=5;seed[9]=20;seed[256*4]=8;seed[256*4+1]=24;
+ frame->Queue_Texture_Upload(state,0,256,256,offset);
+ CHECK(frame->Prepare_Coastal_Surf_View(revision));
+ SDL_GPUTexture *view=frame->Coastal_Surf_View(revision,7);CHECK(view);if(!view)return;
+ CHECK(frame->Coastal_Surf_View_Sampler(revision,7));
+ CHECK(!frame->Coastal_Surf_View(revision,11) && !frame->Coastal_Surf_View(revision+1,7));
+ CHECK(frame->Coastal_Surf_View_Time(revision,7)==0);
+ CHECK(frame->Coastal_Surf_View_Sets()==sets+1 && frame->Coastal_Surf_View_Updates()==updates+1);
+ const double expected[6][2]={{0,0},{2,10},{6,6},{4.5,8.5},{2,6},{1,5}};
+ auto verify=[&](const std::vector<float>&values,double elapsed){
+ CHECK(values.size()==24);if(values.size()!=24)return;
+ const double q=std::exp(-elapsed/Lifetime);
+ for(unsigned i=0;i<6;++i){
+ CHECK(std::abs(values[i*4]-expected[i][0]*q)<2e-5);
+ CHECK(std::abs(values[i*4+1]-(expected[i][1]+elapsed*expected[i][0])*q)<2e-5);
+ CHECK(values[i*4+2]==0 && values[i*4+3]==0);
+ }
+ };
+ const auto first=read_float_targets(frame,&view,1,3,2);CHECK(first.size()==24);if(first.size()!=24)return;verify(first,0);
+ CHECK(first[4]>1 && first[4*4]==2); // raw density, quarter weight remains quarter
+ CHECK(frame->Set_Coastal_Surf_View(revision,mapping,7,lookups));CHECK(frame->Prepare_Coastal_Surf_View(revision));
+ CHECK(frame->Coastal_Surf_View_Updates()==updates+1 && frame->Coastal_Surf_View_Sets()==sets+1);
+ CHECK(read_float_targets(frame,&view,1,3,2)==first);
+ auto invalid=lookups;invalid[1].node[0]=3; // valid atlas index, wrong exact level
+ CHECK(!frame->Set_Coastal_Surf_View(revision,mapping,7,invalid));
+ CHECK(!frame->Coastal_Surf_View(revision,7) && !frame->Coastal_Surf_View_Sampler(revision,7));
+ invalid=lookups;invalid[1].weight[0]=NAN;CHECK(!frame->Set_Coastal_Surf_View(revision,mapping,7,invalid));
+ invalid=lookups;invalid[1].node[1]=2;invalid[1].weight[1]=.25f;CHECK(!frame->Set_Coastal_Surf_View(revision,mapping,7,invalid));
+ invalid=lookups;invalid[1].node[0]=258;CHECK(!frame->Set_Coastal_Surf_View(revision,mapping,7,invalid));
+ auto badMapping=mapping;badMapping.widthPixels=513;CHECK(!frame->Set_Coastal_Surf_View(revision,badMapping,7,lookups));
+ CHECK(!frame->Set_Coastal_Surf_View(revision,mapping,7.1,lookups));
+ CHECK(!frame->Set_Coastal_Surf_View(revision+1,mapping,7,lookups));
+ CHECK(frame->Set_Coastal_Surf_View(revision,mapping,7,lookups));CHECK(frame->Prepare_Coastal_Surf_View(revision));
+ CHECK(frame->Coastal_Surf_View(revision,7)==view);
+ CHECK(frame->Prepare_Coastal_Surf(revision,.1,input)); // pure decay; initial incident field is still zero
+ CHECK(!frame->Coastal_Surf_View(revision,7)); // stale composed moments may not be exposed
+ const uint64_t beforeCompose=frame->Coastal_Surf_View_Updates();
+ CHECK(frame->Prepare_Coastal_Surf_View(revision));CHECK(frame->Coastal_Surf_View_Updates()==beforeCompose+1);
+ CHECK(frame->Coastal_Surf_View(revision,7)==view && frame->Coastal_Surf_View_Time(revision,7)==.1);
+ const auto decayed=read_float_targets(frame,&view,1,3,2);CHECK(decayed.size()==24);if(decayed.size()!=24)return;verify(decayed,.1);
+ CHECK(frame->Resize(oldWidth+7,oldHeight+5));
+ CHECK(frame->Coastal_Surf_View(revision,7)==view && frame->Coastal_Surf_State(revision));
+ CHECK(frame->Prepare_Coastal_Surf_View(revision) && frame->Coastal_Surf_View_Updates()==beforeCompose+1);
+ CHECK(read_float_targets(frame,&view,1,3,2)==decayed);
+ mapping.originX+=8;CHECK(frame->Set_Coastal_Surf_View(revision,mapping,7,lookups));
+ CHECK(!frame->Coastal_Surf_View(revision,7));CHECK(frame->Prepare_Coastal_Surf_View(revision));
+ CHECK(frame->Coastal_Surf_View(revision,7)==view);verify(read_float_targets(frame,&view,1,3,2),.1);
+
+ // A recorded ordinary draw must read the old composition before the same
+ // output texture is reused, and before a different-sized view releases it.
+ struct Reader {
+ SdlGpuFrame *f;SDL_GPUShader *vs=NULL,*ps=NULL;SDL_GPUGraphicsPipeline *pipeline=NULL;SDL_GPUTexture *target=NULL;
+ ~Reader(){CHECK(f->Flush());f->Set_Target(f->Back_Buffer_Target());if(target)SDL_ReleaseGPUTexture(f->Device(),target);
+ if(pipeline)SDL_ReleaseGPUGraphicsPipeline(f->Device(),pipeline);if(vs)SDL_ReleaseGPUShader(f->Device(),vs);if(ps)SDL_ReleaseGPUShader(f->Device(),ps);}
+ } reader{frame};
+ std::string error;std::vector<unsigned char> spirv;
+ bool ok=SDL3_Compile_HLSL_To_SPIRV(WaterFftSpectrum::VertexHlsl(),true,spirv,error);CHECK(ok);
+ if(ok)reader.vs=SDL3_Create_Shader(frame->Device(),spirv,true,error);
+ const char *ps="Texture2D<float4> View:register(t0,space2);float4 main(float4 p:SV_Position):SV_Target0{return View.Load(int3((int2)p.xy,0));}";
+ ok=SDL3_Compile_HLSL_To_SPIRV(ps,false,spirv,error);CHECK(ok);
+ if(ok){unsigned samplers=0,uniforms=0;SDL3_Shader_Slots(spirv,false,samplers,uniforms);CHECK(samplers==1&&uniforms==0);
+ if(samplers==1&&uniforms==0)reader.ps=SDL3_Create_Shader(frame->Device(),spirv,false,error);}
+ CHECK(reader.vs&&reader.ps);if(!reader.vs||!reader.ps)return;
+ SDL_GPUColorTargetDescription colour={};colour.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
+ SDL_GPUGraphicsPipelineCreateInfo pi={};pi.vertex_shader=reader.vs;pi.fragment_shader=reader.ps;pi.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;
+ pi.target_info.color_target_descriptions=&colour;pi.target_info.num_color_targets=1;pi.target_info.has_depth_stencil_target=true;
+ pi.target_info.depth_stencil_format=(SDL_GPUTextureFormat)frame->Depth_Format();reader.pipeline=SDL_CreateGPUGraphicsPipeline(frame->Device(),&pi);
+ SDL_GPUTextureCreateInfo ti={};ti.type=SDL_GPU_TEXTURETYPE_2D;ti.format=colour.format;ti.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;
+ ti.width=3;ti.height=2;ti.layer_count_or_depth=ti.num_levels=1;reader.target=SDL_CreateGPUTexture(frame->Device(),&ti);
+ CHECK(reader.pipeline&&reader.target);if(!reader.pipeline||!reader.target)return;
+ auto record=[&]()->bool{frame->Set_Target({reader.target,frame->Depth_For(3,2),3,2});SdlRecordedDraw draw={};
+ draw.Pipeline=reader.pipeline;draw.Count=3;draw.SamplerCount=1;
+ void *staged=frame->Stage(16,draw.VertexOffset);CHECK(staged);if(!staged)return false;memset(staged,0,16);
+ draw.Textures[0]=frame->Coastal_Surf_View(revision,7);draw.Samplers[0]=frame->Coastal_Surf_View_Sampler(revision,7);
+ CHECK(draw.Textures[0]&&draw.Samplers[0]);if(!draw.Textures[0]||!draw.Samplers[0])return false;
+ draw.Viewport[2]=3;draw.Viewport[3]=2;draw.Viewport[5]=1;draw.Scissor[2]=3;draw.Scissor[3]=2;frame->Record_Draw(draw);return true;};
+ if(!record())return;const uint64_t batch=frame->Batch();
+ auto changed=lookups;changed[1].weight[0]=.25f;changed[2].node[0]=1;
+ CHECK(frame->Set_Coastal_Surf_View(revision,mapping,7,changed));CHECK(frame->Prepare_Coastal_Surf_View(revision));
+ CHECK(frame->Batch()>batch && frame->Coastal_Surf_View(revision,7)==view);
+ CHECK(read_float_targets(frame,&reader.target,1,3,2)==decayed);
+ const auto changedValues=read_float_targets(frame,&view,1,3,2);CHECK(changedValues.size()==24);if(changedValues.size()!=24)return;
+ CHECK(std::abs(changedValues[4]-.25f*decayed[4])<1e-6 && changedValues[8]==decayed[4]);
+ if(!record())return;WaterCoastalView::Mapping narrow=mapping;narrow.widthPixels=4;narrow.heightPixels=1;
+ std::vector<Lookup> single(4);for(auto &l:single){l.node[0]=1;l.weight[0]=1;}
+ CHECK(frame->Set_Coastal_Surf_View(revision,narrow,7,single));CHECK(!frame->Coastal_Surf_View(revision,7));
+ CHECK(frame->Prepare_Coastal_Surf_View(revision));SDL_GPUTexture *newView=frame->Coastal_Surf_View(revision,7);
+ CHECK(newView&&newView!=view);if(!newView)return;
+ CHECK(read_float_targets(frame,&reader.target,1,3,2)==changedValues);
+ for(auto &l:single)l.node[0]=3;
+ CHECK(frame->Set_Coastal_Surf_View(revision,narrow,11,single));CHECK(frame->Prepare_Coastal_Surf_View(revision));
+ CHECK(!frame->Coastal_Surf_View(revision,7) && frame->Coastal_Surf_View(revision,11)==newView);
+ const auto level=read_float_targets(frame,&newView,1,4,1);CHECK(level.size()==16);if(level.size()!=16)return;const double q=std::exp(-.1/Lifetime);
+ for(unsigned i=0;i<4;++i){CHECK(std::abs(level[i*4]-5*q)<2e-5);CHECK(std::abs(level[i*4+1]-20.5*q)<2e-5);}
+ frame->Set_Target({newView,NULL,4,1});CHECK(frame->Clear_Coastal_Surf_View());
+ CHECK(!frame->Coastal_Surf_View(revision,11) && frame->Coastal_Surf_State(revision));
+ frame->Clear_Back_Buffer(true,false,false,0xFF102030,1,0);CHECK(frame->Flush()); // released current target invalidated
+ CHECK(frame->Set_Coastal_Surf_View(revision,mapping,7,lookups));CHECK(frame->Prepare_Coastal_Surf_View(revision));
+ CHECK(frame->Install_Coastal_Surf(revision+1,nodes,8));CHECK(!frame->Coastal_Surf_View(revision,7));
+ CHECK(!frame->Prepare_Coastal_Surf_View(revision+1));
+ printf("sdl_gpu_frame_selfcheck: coastal view: raw density/age, quarter/missing weights without renormalization, row-crossing IDs, exact levels, invalid input, cache/state refresh, resize/remap, queued reuse/release and independent history lifetime checked\n");
+}
+
+static void check_gpu_coastal_surf_owner(SdlGpuFrame *frame)
+{
+ using namespace WaterCoastalSurf;
+ const unsigned oldWidth=frame->Width(),oldHeight=frame->Height();
+ CHECK(frame->Clear_Coastal_Surf());
+ CHECK(!frame->Coastal_Surf_State(71) && !frame->Coastal_Surf_Field_Target(71).Colour);
+ CHECK(!frame->Coastal_Surf_Field_Due(71,0));
+ const SDL_GPUTextureUsageFlags usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET|SDL_GPU_TEXTUREUSAGE_SAMPLER;
+ if(!SDL_GPUTextureSupportsFormat(frame->Device(),SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT,
+ SDL_GPU_TEXTURETYPE_2D,usage)) {
+ std::vector<Node> probe(1);probe[0].context={1,8,1,0,1,1,0,0,1,1};
+ CHECK(!frame->Install_Coastal_Surf(71,probe,8));
+ CHECK(!frame->Coastal_Surf_State(71));
+ printf("sdl_gpu_frame_selfcheck: coastal owner RGBA32F unsupported: safe fallback checked\n");return;
+ }
+ // Only nodes 0 and 256 exchange. Their IDs cross an atlas row. Isolated node 1
+ // occupies the same XY as node 0 at a distinct exact level and must stay empty.
+ std::vector<Node> nodes(257);
+ for(unsigned i=0;i<nodes.size();++i) {
+ nodes[i].world[0]=float(100+i*8);nodes[i].world[1]=16;nodes[i].world[2]=7;
+ nodes[i].context={1,200,1,0,1,1,0,0,1,1}; // valid wet no-birth spread support
+ }
+ nodes[0].world[0]=nodes[0].world[1]=0;nodes[0].context.distance=8;
+ nodes[1].world[0]=nodes[1].world[1]=0;nodes[1].world[2]=11;
+ nodes[256].world[0]=8;nodes[256].world[1]=0;nodes[256].context.distance=8;
+ nodes[0].neighbour[1]=257;nodes[256].neighbour[0]=1;
+ CHECK(ValidGraph(nodes,8));
+ const uint64_t installs=frame->Coastal_Surf_Installs(),updates=frame->Coastal_Surf_Updates();
+ CHECK(frame->Install_Coastal_Surf(71,nodes,8));
+ SdlTarget input=frame->Coastal_Surf_Field_Target(71);
+ CHECK(input.Colour && !input.Depth && input.Width==256 && input.Height==256);
+ if(!input.Colour) return;
+ CHECK(frame->Coastal_Surf_Installs()==installs+1 && frame->Coastal_Surf_Nodes(71)==257);
+ CHECK(!frame->Coastal_Surf_State(71) && !frame->Coastal_Surf_State(72));
+ CHECK(frame->Coastal_Surf_Sampler(71) && !frame->Coastal_Surf_Sampler(72));
+ for(unsigned i=0;i<5;++i)CHECK(frame->Coastal_Surf_Domain(i,71));
+ CHECK(!frame->Coastal_Surf_Domain(5,71) && !frame->Coastal_Surf_Domain(0,72));
+ CHECK(!frame->Coastal_Surf_Field_Due(71,0));
+ CHECK(frame->Prepare_Coastal_Surf(71,0,input));
+ CHECK(frame->Coastal_Surf_Updates()==updates+1 && frame->Coastal_Surf_Time(71)==0);
+ auto state=[&]() {
+ SDL_GPUTexture *texture=frame->Coastal_Surf_State(71);CHECK(texture);
+ return texture?read_float_targets(frame,&texture,1,256,256)
+ :std::vector<float>(MaxNodes*4,std::numeric_limits<float>::quiet_NaN());
+ };
+ auto sentinel=[&](const std::vector<float>&v,unsigned start) {
+ bool ok=v.size()==MaxNodes*4;
+ if(ok)for(unsigned i=start;i<MaxNodes;++i) {
+ ok &= v[i*4]==0 && v[i*4+1]==0 && v[i*4+2]==0 && v[i*4+3]==-1;
+ }
+ CHECK(ok);
+ };
+ const auto reset=state();sentinel(reset,0);
+ auto field=[&](float height) {
+ uint32_t offset=0;float *p=reinterpret_cast<float *>(frame->Upload_Space(MaxNodes*4*sizeof(float),offset));
+ CHECK(p);if(!p)return;
+ for(unsigned i=0;i<MaxNodes;++i) {
+ p[i*4]=height;p[i*4+1]=i==256?-.4f:.4f;p[i*4+2]=0;p[i*4+3]=.5f;
+ }
+ frame->Queue_Texture_Upload(input.Colour,0,256,256,offset);
+ };
+ CHECK(frame->Coastal_Surf_Field_Due(71,.1));
+ field(.5f); // Deliberately no Flush: Prepare must submit this upload first.
+ CHECK(frame->Prepare_Coastal_Surf(71,.1,input));
+ const auto warm=state();sentinel(warm,257);
+ CHECK(warm[0]==0 && warm[2]==.5f && warm[3]==0);
+ CHECK(warm[256*4]==0 && warm[256*4+2]==.5f && warm[256*4+3]==0);
+ field(1.5f);CHECK(frame->Prepare_Coastal_Surf(71,.2,input));
+ const auto born=state();sentinel(born,257);
+ CHECK(born[3]>.99f*MaximumRate && born[256*4+3]==0);
+ // Independent Simpson integration of a linear 0 -> 1.2 source, with age
+ // measured from the source time. It does not call Integrate/Advance/Diffuse.
+ double mass=0,moment=0;const unsigned steps=1000;const double dt=.1;
+ for(unsigned i=0;i<=steps;++i) {
+ const double u=dt*i/steps,weight=i==0||i==steps?1:i%2?4:2;
+ const double value=MaximumRate*(u/dt)*std::exp(-(dt-u)/Lifetime);
+ mass+=weight*value;moment+=weight*value*(dt-u);
+ }
+ mass*=dt/(3*steps);moment*=dt/(3*steps);
+ const double alpha=Diffusivity*dt/64;
+ CHECK(std::abs(born[0]-mass*(1-alpha))<2e-6 && std::abs(born[1]-moment*(1-alpha))<2e-6);
+ CHECK(std::abs(born[256*4]-mass*alpha)<2e-6 && std::abs(born[256*4+1]-moment*alpha)<2e-6);
+ CHECK(born[4]==0 && born[5]==0); // exact-level isolation
+ CHECK(born[0]>.05f && born[256*4]>0.0001f); // armed, non-vacuous source and diffusion
+
+ const uint64_t pausedUpdates=frame->Coastal_Surf_Updates();
+ SDL_GPUTexture *paused=frame->Coastal_Surf_State(71);
+ CHECK(!frame->Coastal_Surf_Field_Due(71,.2));
+ CHECK(frame->Prepare_Coastal_Surf(71,.2,input));
+ CHECK(frame->Coastal_Surf_Updates()==pausedUpdates && frame->Coastal_Surf_State(71)==paused);
+ CHECK(state()==born);
+ CHECK(frame->Install_Coastal_Surf(71,nodes,8));
+ CHECK(frame->Coastal_Surf_Installs()==installs+1 && frame->Coastal_Surf_State(71)==paused);
+ auto badNodes=nodes;badNodes[0].context.depth=2;
+ CHECK(!frame->Install_Coastal_Surf(71,badNodes,8)); // same revision, changed payload
+ badNodes=nodes;badNodes[256].context.wet=0;
+ CHECK(!frame->Install_Coastal_Surf(72,badNodes,8)); // dry graph endpoint
+ badNodes=nodes;badNodes[0].neighbour[1]=MaxNodes+1;
+ CHECK(!frame->Install_Coastal_Surf(72,badNodes,8));
+ CHECK(!frame->Install_Coastal_Surf(0,nodes,8));
+ SdlTarget wrong=input;wrong.Width=255;CHECK(!frame->Prepare_Coastal_Surf(71,.3,wrong));
+ wrong=input;wrong.Depth=frame->Back_Buffer_Target().Depth;CHECK(!frame->Prepare_Coastal_Surf(71,.3,wrong));
+ wrong=input;wrong.Colour=frame->Coastal_Surf_State(71);CHECK(!frame->Prepare_Coastal_Surf(71,.3,wrong));
+ wrong=input;wrong.Colour=frame->Coastal_Surf_Domain(0,71);CHECK(!frame->Prepare_Coastal_Surf(71,.3,wrong));
+ CHECK(!frame->Prepare_Coastal_Surf(72,.3,input) && !frame->Prepare_Coastal_Surf(71,NAN,input));
+ CHECK(frame->Coastal_Surf_State(71)==paused && frame->Coastal_Surf_Updates()==pausedUpdates && state()==born);
+ CHECK(frame->Resize(oldWidth+5,oldHeight+3));
+ CHECK(frame->Coastal_Surf_Field_Target(71).Colour==input.Colour && frame->Coastal_Surf_State(71)==paused);
+ CHECK(state()==born && !frame->Coastal_Surf_Field_Due(71,.2));
+
+ // Queue an ordinary draw reading the old state, then advance far enough to
+ // recycle that exact physical state texture. The unsubmitted reader must
+ // retain the old values instead of observing the overwritten ping-pong slot.
+ struct Reader {
+ SDL_GPUDevice *device;SDL_GPUShader *vs=NULL,*ps=NULL;SDL_GPUGraphicsPipeline *pipeline=NULL;
+ SDL_GPUTexture *target=NULL;
+ ~Reader(){if(target)SDL_ReleaseGPUTexture(device,target);if(pipeline)SDL_ReleaseGPUGraphicsPipeline(device,pipeline);
+ if(vs)SDL_ReleaseGPUShader(device,vs);if(ps)SDL_ReleaseGPUShader(device,ps);}
+ } reader;reader.device=frame->Device();
+ std::vector<unsigned char> spirv;std::string error;
+ const char *vs="float4 main(uint id:SV_VertexID):SV_Position{return float4(id==1?3.0:-1.0,id==2?3.0:-1.0,0,1);}";
+ const char *ps="Texture2D<float4> State:register(t0,space2);float4 main(float4 p:SV_Position):SV_Target0{return State.Load(int3(0,(uint)p.x==0?0:1,0));}";
+ bool ok=SDL3_Compile_HLSL_To_SPIRV(vs,true,spirv,error);CHECK(ok);
+ if(ok)reader.vs=SDL3_Create_Shader(reader.device,spirv,true,error);
+ ok=SDL3_Compile_HLSL_To_SPIRV(ps,false,spirv,error);CHECK(ok);
+ if(ok) {
+ unsigned samplers=0,uniforms=0;SDL3_Shader_Slots(spirv,false,samplers,uniforms);
+ CHECK(samplers==1 && uniforms==0);
+ if(samplers==1 && uniforms==0)reader.ps=SDL3_Create_Shader(reader.device,spirv,false,error);
+ }
+ CHECK(reader.vs && reader.ps);
+ if(reader.vs && reader.ps) {
+ SDL_GPUColorTargetDescription colour={};colour.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
+ SDL_GPUGraphicsPipelineCreateInfo pi={};pi.vertex_shader=reader.vs;pi.fragment_shader=reader.ps;
+ pi.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;pi.target_info.color_target_descriptions=&colour;pi.target_info.num_color_targets=1;
+ pi.target_info.has_depth_stencil_target=true;pi.target_info.depth_stencil_format=(SDL_GPUTextureFormat)frame->Depth_Format();
+ reader.pipeline=SDL_CreateGPUGraphicsPipeline(reader.device,&pi);
+ SDL_GPUTextureCreateInfo ti={};ti.type=SDL_GPU_TEXTURETYPE_2D;ti.format=colour.format;ti.usage=usage;
+ ti.width=2;ti.height=1;ti.layer_count_or_depth=ti.num_levels=1;
+ reader.target=SDL_CreateGPUTexture(reader.device,&ti);CHECK(reader.pipeline && reader.target);
+ if(reader.pipeline && reader.target) {
+ frame->Set_Target({reader.target,frame->Depth_For(2,1),2,1});
+ SdlRecordedDraw draw={};draw.Pipeline=reader.pipeline;draw.Count=3;draw.SamplerCount=1;
+ memset(frame->Stage(16,draw.VertexOffset),0,16);draw.Textures[0]=paused;draw.Samplers[0]=frame->Coastal_Surf_Sampler(71);
+ draw.Viewport[2]=2;draw.Viewport[3]=1;draw.Viewport[5]=1;draw.Scissor[2]=2;draw.Scissor[3]=1;
+ frame->Record_Draw(draw);const uint64_t batch=frame->Batch();
+ field(2.5f);CHECK(frame->Prepare_Coastal_Surf(71,.3,input));CHECK(frame->Batch()>batch);
+ field(3.5f);CHECK(frame->Prepare_Coastal_Surf(71,.4,input));
+ const auto saved=read_float_targets(frame,&reader.target,1,2,1);
+ for(unsigned c=0;c<4;++c) {
+ CHECK(std::abs(saved[c]-born[c])<1e-6);
+ CHECK(std::abs(saved[4+c]-born[256*4+c])<1e-6);
+ }
+ const auto current=state();CHECK(current[0]>born[0]+.1f);
+ }
+ }
+ CHECK(frame->Flush());frame->Set_Target(frame->Back_Buffer_Target());
+ const auto beforeGap=state();const double beforeGapTime=frame->Coastal_Surf_Time(71);field(4.5f);
+ CHECK(frame->Coastal_Surf_Field_Due(71,1.4));CHECK(frame->Prepare_Coastal_Surf(71,1.4,input));
+ const auto gap=state();const double elapsed=1.4-beforeGapTime;
+ // Gap performs pure decay, no diffusion/birth, and commits the fresh height.
+ CHECK(elapsed>MaximumSourceInterval);
+ CHECK(std::abs(gap[0]-beforeGap[0]*std::exp(-elapsed/Lifetime))<2e-6);
+ CHECK(gap[2]==4.5f && gap[3]==0);
+ CHECK(frame->Prepare_Coastal_Surf(71,1.3,input));sentinel(state(),0); // rewind reset
+ CHECK(!frame->Coastal_Surf_Field_Due(71,1.3));
+ CHECK(frame->Install_Coastal_Surf(72,nodes,8));
+ CHECK(!frame->Coastal_Surf_State(71) && !frame->Coastal_Surf_State(72));
+ CHECK(!frame->Prepare_Coastal_Surf(72,0,input)); // stale pointer rejected
+ input=frame->Coastal_Surf_Field_Target(72);CHECK(input.Colour);
+ CHECK(frame->Prepare_Coastal_Surf(72,0,input) && frame->Coastal_Surf_State(72));
+ frame->Set_Target(input);CHECK(frame->Clear_Coastal_Surf());
+ CHECK(!frame->Coastal_Surf_State(72) && !frame->Coastal_Surf_Field_Target(72).Colour);
+ // Release invalidates an owned CurrentTarget. A subsequent ordinary clear is safe.
+ frame->Clear_Back_Buffer(true,false,false,0xFF102030,1,0);CHECK(frame->Flush());
+ CHECK(frame->Resize(oldWidth,oldHeight));frame->Set_Target(frame->Back_Buffer_Target());
+ printf("sdl_gpu_frame_selfcheck: coastal owner: source ordering, independent linear-source integral, reciprocal row-crossing diffusion, level isolation, inactive tail, pause, queued old reader, gap/rewind, immutable revision, input/alias guards, resize and clear checked\n");
+}
+
+static void check_gpu_foam_history_upload(SdlGpuFrame *frame)
+{
+ // Exercise the same versioned CPU texture mirror as the runtime atlas. Reading via slot14
+ // catches binding truncation; changing a used image before submitting catches upload hazards.
+ const unsigned width=8,tileHeight=4,rows=tileHeight*4;
+ const char *vs="float4 main(uint id:SV_VertexID):SV_Position {return float4(id==1?3.0:-1.0,id==2?3.0:-1.0,0,1);}";
+ std::string ps=WaterFftSampling::UniformSource("WaterBlock",0)+R"HLSL(
+Texture2D History:register(t14);SamplerState HistorySampler:register(s14);
+float4 main(float4 pixel:SV_Position):SV_Target0 {
+ float2 uv=float2(pixel.x/8.0,frac(pixel.y/4.0));
+ float2 world=FoamHistoryArea.xy+uv/FoamHistoryArea.zw;
+ return History.SampleLevel(HistorySampler,(world-FoamHistoryArea.xy)*FoamHistoryArea.zw,0);
+}
+)HLSL";
+ CHECK(SDL3_Shader_Retarget(ps,false));
+ struct Resources {
+ SDL_GPUDevice *device;SDL_GPUShader *vertex=NULL,*pixel=NULL;SDL_GPUGraphicsPipeline *pipeline=NULL;
+ SDL_GPUTexture *target=NULL;SDL_GPUSampler *sampler=NULL;PosixTexture9 *atlas=NULL;
+ ~Resources(){if(atlas)atlas->Release();if(target)SDL_ReleaseGPUTexture(device,target);
+ if(pipeline)SDL_ReleaseGPUGraphicsPipeline(device,pipeline);if(vertex)SDL_ReleaseGPUShader(device,vertex);
+ if(pixel)SDL_ReleaseGPUShader(device,pixel);if(sampler)SDL_ReleaseGPUSampler(device,sampler);}
+ } resources;
+ resources.device=frame->Device();std::string error;std::vector<unsigned char> spirv;
+ bool compiled=SDL3_Compile_HLSL_To_SPIRV(vs,true,spirv,error);CHECK(compiled);if(!compiled)return;
+ resources.vertex=SDL3_Create_Shader(resources.device,spirv,true,error);CHECK(resources.vertex);
+ compiled=SDL3_Compile_HLSL_To_SPIRV(ps,false,spirv,error);CHECK(compiled);
+ if(!compiled){printf("history upload PS: %s\n",error.c_str());return;}
+ unsigned samplers=0,uniforms=0;SDL3_Shader_Slots(spirv,false,samplers,uniforms);CHECK(samplers==15 && uniforms==1);
+ resources.pixel=SDL3_Create_Shader(resources.device,spirv,false,error);CHECK(resources.pixel);
+ SDL_GPUColorTargetDescription colour={};colour.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
+ SDL_GPUGraphicsPipelineCreateInfo pi={};pi.vertex_shader=resources.vertex;pi.fragment_shader=resources.pixel;
+ pi.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;pi.target_info.color_target_descriptions=&colour;pi.target_info.num_color_targets=1;
+ pi.target_info.has_depth_stencil_target=true;pi.target_info.depth_stencil_format=(SDL_GPUTextureFormat)frame->Depth_Format();
+ resources.pipeline=SDL_CreateGPUGraphicsPipeline(resources.device,&pi);CHECK(resources.pipeline);if(!resources.pipeline)return;
+ SDL_GPUTextureCreateInfo ti={};ti.type=SDL_GPU_TEXTURETYPE_2D;ti.format=colour.format;ti.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;
+ ti.width=width;ti.height=rows;ti.layer_count_or_depth=ti.num_levels=1;
+ resources.target=SDL_CreateGPUTexture(resources.device,&ti);CHECK(resources.target);if(!resources.target)return;
+ SDL_GPUSamplerCreateInfo si={};si.min_filter=si.mag_filter=SDL_GPU_FILTER_LINEAR;
+ si.address_mode_u=si.address_mode_v=si.address_mode_w=SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
+ resources.sampler=SDL_CreateGPUSampler(resources.device,&si);CHECK(resources.sampler);if(!resources.sampler)return;
+ resources.atlas=PosixTexture9::create(width,tileHeight,1,0,D3DFMT_A8R8G8B8,D3DPOOL_MANAGED);CHECK(resources.atlas);if(!resources.atlas)return;
+ auto packed=[](unsigned revision,unsigned x,unsigned y) {
+ return ((32+x*20+revision*40)<<16)|(((y+1)*16+revision*8)<<8)|(12+x*3+y*7+revision*5);
+ };
+ auto update=[&](unsigned revision) {
+ D3DLOCKED_RECT locked={};CHECK(resources.atlas->LockRect(0,&locked,NULL,0)==D3D_OK);
+ if(!locked.pBits)return;
+ for(unsigned y=0;y<tileHeight;++y)for(unsigned x=0;x<width;++x)
+ ((uint32_t *)((uint8_t *)locked.pBits+y*locked.Pitch))[x]=packed(revision,x,y);
+ CHECK(resources.atlas->UnlockRect(0)==D3D_OK);
+ };
+ CHECK(frame->Flush());const unsigned oldWidth=frame->Width(),oldHeight=frame->Height();
+ {
+ SdlResourceMirrors mirrors(frame);
+ auto record=[&](unsigned band) {
+ std::string refusal;SDL_GPUTexture *atlas=mirrors.Texture(resources.atlas,refusal);CHECK(atlas);if(!atlas)return;
+ SDL_GPUTexture *white=mirrors.White();CHECK(white);if(!white)return;
+ frame->Set_Target({resources.target,frame->Depth_For(width,rows),width,rows});
+ SdlRecordedDraw draw={};draw.Pipeline=resources.pipeline;draw.Count=3;draw.SamplerCount=15;
+ memset(frame->Stage(16,draw.VertexOffset),0,16);
+ for(unsigned i=0;i<15;++i){draw.Textures[i]=i==14?atlas:white;draw.Samplers[i]=resources.sampler;}
+ SdlWaterPixelConstants water={};water.FoamHistoryArea[0]=band==3?96:-32;water.FoamHistoryArea[1]=band==3?-128:48;
+ water.FoamHistoryArea[2]=1.0f/64;water.FoamHistoryArea[3]=1.0f/32;
+ water.FoamHistoryParameters[0]=1;water.FoamHistoryParameters[1]=7;water.FoamHistoryParameters[2]=8;water.FoamHistoryParameters[3]=float(band);
+ draw.PixelConstants=frame->Constants(1,&water,sizeof(water));draw.PixelConstantsSize=sizeof(water);
+ draw.Viewport[1]=float(band*tileHeight);draw.Viewport[2]=width;draw.Viewport[3]=tileHeight;draw.Viewport[5]=1;
+ draw.Scissor[1]=band*tileHeight;draw.Scissor[2]=width;draw.Scissor[3]=tileHeight;frame->Record_Draw(draw);
+ };
+ update(0);record(0);CHECK(mirrors.Textures_Uploaded()==1);
+ const uint64_t oldBatch=frame->Batch();update(1);record(1);
+ CHECK(frame->Batch()>oldBatch && mirrors.Stale_Flushes()==1 && mirrors.Textures_Uploaded()==2);
+ record(2);CHECK(mirrors.Textures_Uploaded()==2); // duplicate/reflection draw does not upload again
+ // Destroy the CPU owner while recorded draws still reference its GPU copy. The normal
+ // deferred-release path must retain that copy through submission and a frame resize.
+ resources.atlas->Release();resources.atlas=NULL;CHECK(mirrors.Live_Copies()==0);mirrors.Collect_Dead();
+ CHECK(frame->Resize(oldWidth+8,oldHeight+4));
+ resources.atlas=PosixTexture9::create(width,tileHeight,1,0,D3DFMT_A8R8G8B8,D3DPOOL_MANAGED);CHECK(resources.atlas);
+ if(!resources.atlas)return;
+ update(2);record(3);CHECK(mirrors.Textures_Uploaded()==3);
+ const auto values=read_float_targets(frame,&resources.target,1,width,rows);
+ CHECK(values.size()==width*rows*4);bool pixels=values.size()==width*rows*4;
+ if(pixels)for(unsigned band=0;band<4;++band)for(unsigned y=0;y<tileHeight;++y)for(unsigned x=0;x<width;++x) {
+ const uint32_t expected=packed(band==0?0:band==3?2:1,x,y);
+ for(unsigned c=0;c<4;++c) {
+ const unsigned shift=c<3?16-c*8:24;const float value=values[((band*tileHeight+y)*width+x)*4+c];
+ pixels &= std::isfinite(value) && std::abs(value-float((expected>>shift)&255)/255)<.00001f;
+ }
+ }
+ CHECK(pixels);resources.atlas->Release();resources.atlas=NULL;mirrors.Collect_Dead();CHECK(frame->Flush());
+ }
+ CHECK(frame->Resize(oldWidth,oldHeight));frame->Set_Target(frame->Back_Buffer_Target());
+ printf("sdl_gpu_frame_selfcheck: GPU foam history upload: slot14 channels, queued A/B snapshots, unchanged reuse, deferred release, resize and recreation checked\n");
+}
+
+static void check_gpu_foam_history_tiles(SdlGpuFrame *frame)
+{
+ // Actual slot14 UNORM mirror, production tile/shore helpers, and an independent
+ // single-tile reference. No material/noise helper is involved in this test.
+ struct Query {float uvLevelTime[4];};std::vector<Query> queries;
+ auto add=[&](float x,float y,float level=7,float time=10){queries.push_back({{x,y,level,time}});};
+ for(unsigned y=0;y<4;++y)for(unsigned x=0;x<8;++x)add((x+.5f)/8,(y+.5f)/4);
+ const float edges[]={0,1.f/4096,1.f/16,3.f/32,.5f,29.f/32,15.f/16,1-1.f/4096,1};
+ for(float x:edges){add(x,0);add(x,1);add(0,x);add(1,x);}
+ add(5.f/32,7.f/16);add(13.f/32,11.f/16);add(-1.f/32,.5f);add(33.f/32,.5f);
+ add(.5f,-1.f/32);add(.5f,33.f/32);add(.5f,.5f,8);add(.5f,.5f,7,12);
+ const unsigned count=unsigned(queries.size()),bands=9,rows=count*bands;
+ const char *vs="float4 main(uint id:SV_VertexID):SV_Position{return float4(id==1?3.0:-1.0,id==2?3.0:-1.0,0,1);}";
+ std::string ps=WaterFftSampling::UniformSource("WaterBlock",0)+
+ "Texture2D<float4> Legacy:register(t13);Texture2D<float4> Texture14:register(t14);SamplerState Sampler14:register(s14);\n"
+ "cbuffer TileQueries:register(b1){float4 Queries["+std::to_string(count)+"];};\n"+
+ WaterFoamShading::HistorySamplingSource()+WaterShoreFoam::HistorySource()+
+ "float4 main(float4 pixel:SV_Position):SV_Target0{float4 q=Queries[(uint)pixel.y%"+std::to_string(count)+"];\n"
+ "uint column=(uint)pixel.x;if(column==0)return waterFoamHistoryTile(q.xy,0u);\n"
+ "if(column==1)return Legacy.SampleLevel(Sampler14,q.xy,0);\n"
+ "if(column==2)return waterFoamHistoryTile(q.xy,1u);\n"
+ "float2 p=FoamHistoryArea.xy+q.xy/FoamHistoryArea.zw;return float4(waterShoreHistory(p,q.z,q.w),0,0,1);}\n";
+ const bool retarget=SDL3_Shader_Retarget(ps,false);CHECK(retarget);if(!retarget)return;
+ struct Resources {
+ SdlGpuFrame *f;unsigned oldWidth,oldHeight;SDL_GPUDevice *device;
+ SDL_GPUShader *vs=nullptr,*ps=nullptr;SDL_GPUGraphicsPipeline *pipeline=nullptr;
+ SDL_GPUTexture *target=nullptr;SDL_GPUSampler *sampler=nullptr;PosixTexture9 *atlas=nullptr,*legacy=nullptr;
+ ~Resources(){CHECK(f->Flush());f->Set_Target(f->Back_Buffer_Target());
+ if(atlas)atlas->Release();if(legacy)legacy->Release();if(target)SDL_ReleaseGPUTexture(device,target);
+ if(pipeline)SDL_ReleaseGPUGraphicsPipeline(device,pipeline);if(vs)SDL_ReleaseGPUShader(device,vs);
+ if(ps)SDL_ReleaseGPUShader(device,ps);if(sampler)SDL_ReleaseGPUSampler(device,sampler);
+ CHECK(f->Resize(oldWidth,oldHeight));f->Set_Target(f->Back_Buffer_Target());}
+ } r{frame,frame->Width(),frame->Height(),frame->Device()};
+ std::string error;std::vector<unsigned char> spirv;
+ bool ok=SDL3_Compile_HLSL_To_SPIRV(vs,true,spirv,error);CHECK(ok);if(!ok)return;
+ r.vs=SDL3_Create_Shader(r.device,spirv,true,error);CHECK(r.vs);if(!r.vs)return;
+ ok=SDL3_Compile_HLSL_To_SPIRV(ps,false,spirv,error);CHECK(ok);
+ if(!ok){printf("history tiles PS: %s\n",error.c_str());return;}
+ unsigned samplers=0,buffers=0;SDL3_Shader_Slots(spirv,false,samplers,buffers);
+ CHECK(samplers==15&&buffers==2);if(samplers!=15||buffers!=2)return;
+ r.ps=SDL3_Create_Shader(r.device,spirv,false,error);CHECK(r.ps);if(!r.ps)return;
+ SDL_GPUColorTargetDescription colour={};colour.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
+ SDL_GPUGraphicsPipelineCreateInfo pi={};pi.vertex_shader=r.vs;pi.fragment_shader=r.ps;
+ pi.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;pi.target_info.color_target_descriptions=&colour;
+ pi.target_info.num_color_targets=1;pi.target_info.has_depth_stencil_target=true;
+ pi.target_info.depth_stencil_format=(SDL_GPUTextureFormat)frame->Depth_Format();
+ r.pipeline=SDL_CreateGPUGraphicsPipeline(r.device,&pi);CHECK(r.pipeline);if(!r.pipeline)return;
+ SDL_GPUTextureCreateInfo ti={};ti.type=SDL_GPU_TEXTURETYPE_2D;ti.format=colour.format;
+ ti.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;ti.width=4;ti.height=rows;ti.layer_count_or_depth=ti.num_levels=1;
+ r.target=SDL_CreateGPUTexture(r.device,&ti);CHECK(r.target);if(!r.target)return;
+ SDL_GPUSamplerCreateInfo si={};si.min_filter=si.mag_filter=SDL_GPU_FILTER_LINEAR;
+ si.address_mode_u=si.address_mode_v=si.address_mode_w=SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
+ r.sampler=SDL_CreateGPUSampler(r.device,&si);CHECK(r.sampler);if(!r.sampler)return;
+ auto texel=[](unsigned revision,unsigned tile,unsigned x,unsigned y){
+ const unsigned red=tile?239-7*x-3*y-11*revision:17+11*x+7*y+23*revision;
+ const unsigned green=tile?211-9*x-5*y-13*revision:43+5*x+13*y+17*revision;
+ const unsigned blue=tile?13+19*x+11*y+5*revision:91+3*x+2*y+13*revision;
+ const unsigned alpha=tile?227-3*x-7*y-17*revision:32+7*x+9*y+19*revision;
+ return (alpha<<24)|(red<<16)|(green<<8)|blue;
+ };
+ unsigned width=8,height=4;
+ auto create=[&](){r.atlas=PosixTexture9::create(width,height*2,1,0,D3DFMT_A8R8G8B8,D3DPOOL_MANAGED);
+ r.legacy=PosixTexture9::create(width,height,1,0,D3DFMT_A8R8G8B8,D3DPOOL_MANAGED);
+ CHECK(r.atlas&&r.legacy);return r.atlas&&r.legacy;};
+ auto update=[&](unsigned revision){
+ PosixTexture9 *textures[]={r.legacy,r.atlas};
+ for(unsigned n=0;n<2;++n){D3DLOCKED_RECT lock={};const bool locked=textures[n]->LockRect(0,&lock,nullptr,0)==D3D_OK;
+ CHECK(locked&&lock.pBits&&lock.Pitch>=int(width*4));if(!locked||!lock.pBits)return false;
+ if(lock.Pitch<int(width*4)){textures[n]->UnlockRect(0);return false;}
+ for(unsigned y=0;y<height*(n+1);++y)for(unsigned x=0;x<width;++x)
+ reinterpret_cast<uint32_t *>(static_cast<uint8_t *>(lock.pBits)+y*lock.Pitch)[x]=texel(revision,y/height,x,y%height);
+ const bool unlocked=textures[n]->UnlockRect(0)==D3D_OK;CHECK(unlocked);if(!unlocked)return false;
+ }return true;
+ };
+ if(!create())return;CHECK(frame->Flush());
+ {
+ SdlResourceMirrors mirrors(frame);
+ auto record=[&](unsigned band,unsigned flags){
+ std::string refusal;SDL_GPUTexture *legacy=mirrors.Texture(r.legacy,refusal);
+ SDL_GPUTexture *atlas=(flags&4)?mirrors.Texture(r.atlas,refusal):legacy;
+ SDL_GPUTexture *white=mirrors.White();CHECK(legacy&&atlas&&white);if(!legacy||!atlas||!white)return false;
+ SDL_GPUTexture *depth=frame->Depth_For(4,rows);CHECK(depth);if(!depth)return false;
+ frame->Set_Target({r.target,depth,4,rows});SdlRecordedDraw draw={};draw.Pipeline=r.pipeline;draw.Count=3;draw.SamplerCount=15;
+ void *bytes=frame->Stage(16,draw.VertexOffset);CHECK(bytes);if(!bytes)return false;memset(bytes,0,16);
+ for(unsigned i=0;i<15;++i){draw.Textures[i]=i==14?atlas:i==13?legacy:white;draw.Samplers[i]=r.sampler;}
+ SdlWaterPixelConstants water={};water.FoamHistoryArea[2]=1.f/64;water.FoamHistoryArea[3]=1.f/32;
+ water.FoamHistoryParameters[0]=float(flags);water.FoamHistoryParameters[1]=7;
+ water.FoamHistoryParameters[2]=1;water.FoamHistoryParameters[3]=10;
+ draw.PixelConstants=frame->Constants(1,&water,sizeof(water));draw.PixelConstantsSize=sizeof(water);
+ draw.PixelWaterConstants[0]=frame->Constants(1,queries.data(),unsigned(queries.size()*sizeof(Query)),1);
+ draw.PixelWaterConstantsSize[0]=unsigned(queries.size()*sizeof(Query));
+ draw.Viewport[1]=float(band*count);draw.Viewport[2]=4;draw.Viewport[3]=float(count);draw.Viewport[5]=1;
+ draw.Scissor[1]=band*count;draw.Scissor[2]=4;draw.Scissor[3]=count;frame->Record_Draw(draw);return true;
+ };
+ if(!update(0)||!record(0,7))return;CHECK(mirrors.Textures_Uploaded()==2);
+ const uint64_t firstBatch=frame->Batch();if(!update(1)||!record(1,7))return;
+ CHECK(frame->Batch()>firstBatch&&mirrors.Stale_Flushes()==1&&mirrors.Textures_Uploaded()==4);
+ if(!record(2,7)||!record(3,5)||!record(4,6))return;CHECK(mirrors.Textures_Uploaded()==4);
+ // The queued B readers retain both old textures and their dimensions through
+ // destruction, backbuffer resize and a differently shaped recreated atlas.
+ r.atlas->Release();r.atlas=nullptr;r.legacy->Release();r.legacy=nullptr;
+ CHECK(mirrors.Live_Copies()==0);mirrors.Collect_Dead();CHECK(frame->Resize(r.oldWidth+5,r.oldHeight+3));
+ width=4;height=8;if(!create()||!update(2)||!record(5,7))return;
+ if(!record(6,3)||!record(7,1)||!record(8,2))return;CHECK(mirrors.Textures_Uploaded()==6);
+ const auto values=read_float_targets(frame,&r.target,1,4,rows);
+ CHECK(values.size()==size_t(rows)*4*4);if(values.size()!=size_t(rows)*4*4)return;
+ auto reference=[&](unsigned revision,unsigned tile,unsigned w,unsigned h,const Query&q,unsigned channel){
+ const double x=double(q.uvLevelTime[0])*w-.5,y=double(q.uvLevelTime[1])*h-.5;
+ const int ix=int(std::floor(x)),iy=int(std::floor(y));const double fx=x-ix,fy=y-iy;double value=0;
+ for(unsigned dy=0;dy<2;++dy)for(unsigned dx=0;dx<2;++dx){
+ const unsigned sx=unsigned((std::max)(0,(std::min)(int(w)-1,ix+int(dx))));
+ const unsigned sy=unsigned((std::max)(0,(std::min)(int(h)-1,iy+int(dy))));
+ const unsigned shift=channel<3?16-channel*8:24;
+ value+=double((texel(revision,tile,sx,sy)>>shift)&255)/255*(dx?fx:1-fx)*(dy?fy:1-fy);
+ }return value;
+ };
+ const unsigned flags[bands]={7,7,7,5,6,7,3,1,2};
+ // The unchanged UNORM legacy sampler also rounds filtered values; it is not a
+ // double-precision bilinear evaluator. Bound that independent scalar comparison
+ // by one16-bit normalized unit; packed-vs-legacy remains BIT-EXACT below.
+ const double scalarTolerance=1.0/65535.0+1e-7;
+ double maximum=0,topDifference=0,legacyMaximum=0,centreMaximum=0;
+ unsigned exactTop=0,checks=0,roundingExamples=0;
+ for(unsigned band=0;band<bands;++band)for(unsigned i=0;i<count;++i){
+ const unsigned rev=band==0?0:band<5?1:2,w=band<5?8:4,h=band<5?4:8;
+ const Query&q=queries[i];const size_t row=size_t(band*count+i)*16;
+ for(unsigned c=0;c<4;++c){
+ const double top=reference(rev,0,w,h,q,c),bottom=(flags[band]&4)?reference(rev,1,w,h,q,c):0;
+ for(unsigned column=0;column<3;++column){const double expected=column==2?bottom:top;
+ const double error=std::abs(values[row+column*4+c]-expected);maximum=(std::max)(maximum,error);
+ if(column==1) {
+ legacyMaximum=(std::max)(legacyMaximum,error);
+ const double tx=double(q.uvLevelTime[0])*w-.5,ty=double(q.uvLevelTime[1])*h-.5;
+ if(tx==std::floor(tx)&&ty==std::floor(ty))centreMaximum=(std::max)(centreMaximum,error);
+ if(error>.000002 && roundingExamples<4) {++roundingExamples;
+ printf("history legacy rounding: band%u uv(%.8g,%.8g) c%u expected %.10g actual %.10g error %.10g\n",
+ band,double(q.uvLevelTime[0]),double(q.uvLevelTime[1]),c,expected,double(values[row+column*4+c]),error);}
+ }
+ CHECK(std::isfinite(values[row+column*4+c])&&error<scalarTolerance);++checks;}
+ const double difference=std::abs(values[row+c]-values[row+4+c]);topDifference=(std::max)(topDifference,difference);
+ CHECK(values[row+c]==values[row+4+c]);exactTop+=values[row+c]==values[row+4+c];
+ }
+ double shore=0;const double u=q.uvLevelTime[0],v=q.uvLevelTime[1];
+ if((flags[band]&2)&&u>=0&&u<=1&&v>=0&&v<=1&&q.uvLevelTime[2]==7){
+ // Use the independently sampled legacy alpha for this composition oracle.
+ // Its scalar bilinear error is already checked above; a rounded UNORM
+ // input must not be mistaken for an error in the shore decay/guards.
+ const double coverage=values[row+7],elapsed=(std::max)(0.0,double(q.uvLevelTime[3])-10);
+ const double distance=(std::min)((std::min)(u,1-u)*64,(std::min)(v,1-v)*32);
+ const double t=(std::max)(0.0,(std::min)(1.0,distance/8));
+ shore=(1-std::pow((std::max)(1-coverage,1.0/65536),std::exp(-elapsed/5)))*t*t*(3-2*t);
+ }
+ CHECK(std::isfinite(values[row+12])&&std::abs(values[row+12]-shore)<.000002);
+ CHECK(values[row+13]==0&&values[row+14]==0&&values[row+15]==1);
+ }
+ CHECK(exactTop==bands*count*4&&maximum<scalarTolerance&&topDifference==0);
+ CHECK(centreMaximum<.0000001);
+ printf("sdl_gpu_frame_selfcheck: history legacy scalar rounding max %.10g, texel centres %.10g; tile-vs-legacy difference %.10g\n",legacyMaximum,centreMaximum,topDifference);
+ r.atlas->Release();r.atlas=nullptr;r.legacy->Release();r.legacy=nullptr;mirrors.Collect_Dead();CHECK(frame->Flush());
+ printf("sdl_gpu_frame_selfcheck: history tiles: %u scalar samples max %.9g, %u exact legacy/top components; bottom bytes, seam/edges/fractional/outside, shore flags1/2/3/5/6/7, queued A/B, reuse, deferred release, resize and shape recreation checked\n",checks,maximum,exactTop);
+ }
+}
+
+#if defined(__linux__)
+static void check_gpu_foam_history_sampling(SdlGpuFrame *frame)
+{
+ // Unequal density/age moments distinguish filtered weighted age from an incorrectly
+ // filtered unweighted age. All sampling, guards and breakup below are production HLSL.
+ const uint32_t texels[4]={0x00800080u,0x00FFFF00u,0,0x00402010u};
+ struct Query {float point[4];};std::vector<Query> queries;
+ auto add=[&](float x,float y,float level=7,float time=10){queries.push_back({{x,y,level,time}});return unsigned(queries.size()-1);};
+ const unsigned fresh=add(64,128),old=add(192,128),weighted=add(256,128),empty=add(320,128);
+ add(384,128);add(448,128);const unsigned outside=add(-1,128);add(513,128);add(64,-1);add(64,257);
+ const unsigned wrongLevel=add(64,128,8),border=add(0,128),repeat=add(64,128),aged=add(64,128,7,11.5f),expired=add(64,128,7,250);
+ const unsigned evolution=unsigned(queries.size());
+ for(unsigned i=0;i<16;++i){add(64,16+i*14);add(64,16+i*14,7,22);}
+ const unsigned rows=unsigned(queries.size());
+ PixelPipelineDescription pd={};std::string production;
+ CHECK(EngineShader_Pixel_Program(ENGINE_SHADER_WATER_TRAPEZOID,pd,production,COMBINER_SHADER_TARGET_SDL3_GPU));
+ const size_t noiseStart=production.find("float oceanHash("),noiseEnd=production.find("float3 oceanSky(");
+ CHECK(noiseStart!=std::string::npos && noiseEnd>noiseStart);if(noiseStart==std::string::npos || noiseEnd==std::string::npos || noiseEnd<=noiseStart)return;
+ const char *vs="float4 main(uint id:SV_VertexID):SV_Position{return float4(id==1?3.0:-1.0,id==2?3.0:-1.0,0,1);}";
+ std::string oldHistory=WaterFoamShading::Source();
+ const size_t oldStart=oldHistory.find("float3 waterFoamHistory(");CHECK(oldStart!=std::string::npos);if(oldStart==std::string::npos)return;
+ oldHistory.erase(0,oldStart);
+ const std::string replacement=" coverage=waterFoamHistoryRemnants(p,coverage,footprint,age*24.0,time);\n";
+ const size_t changed=oldHistory.find(replacement);CHECK(changed!=std::string::npos);if(changed==std::string::npos)return;
+ oldHistory.erase(changed,replacement.size());
+ oldHistory.replace(oldHistory.find("waterFoamHistory("),strlen("waterFoamHistory("),"frozenHistory(");
+ std::string ps=WaterFftSampling::UniformSource("WaterBlock",0)+
+ "Texture2D Texture14:register(t14);SamplerState Sampler14:register(s14);\n"+
+ "cbuffer QueryBlock:register(b1){float4 Queries["+std::to_string(rows)+"];};\n"+
+ production.substr(noiseStart,noiseEnd-noiseStart)+WaterFoamShading::HistorySamplingSource()+WaterFoamShading::Source()+oldHistory+
+ "float4 main(float4 pixel:SV_Position):SV_Target0{float4 q=Queries[(uint)pixel.y];return float4(waterFoamHistory(q.xy,q.z,q.w,0.5),frozenHistory(q.xy,q.z,q.w,0.5).x);}\n";
+ CHECK(SDL3_Shader_Retarget(ps,false));
+ struct Resources {
+ SDL_GPUDevice *device;SDL_GPUShader *vertex=NULL,*pixel=NULL;SDL_GPUGraphicsPipeline *pipeline=NULL;
+ SDL_GPUTexture *target=NULL;SDL_GPUSampler *sampler=NULL;PosixTexture9 *atlas=NULL;
+ ~Resources(){if(atlas)atlas->Release();if(target)SDL_ReleaseGPUTexture(device,target);
+ if(pipeline)SDL_ReleaseGPUGraphicsPipeline(device,pipeline);if(vertex)SDL_ReleaseGPUShader(device,vertex);
+ if(pixel)SDL_ReleaseGPUShader(device,pixel);if(sampler)SDL_ReleaseGPUSampler(device,sampler);}
+ } resources;
+ resources.device=frame->Device();std::string error;std::vector<unsigned char> spirv;
+ bool compiled=SDL3_Compile_HLSL_To_SPIRV(vs,true,spirv,error);CHECK(compiled);if(!compiled)return;
+ resources.vertex=SDL3_Create_Shader(resources.device,spirv,true,error);CHECK(resources.vertex);
+ compiled=SDL3_Compile_HLSL_To_SPIRV(ps,false,spirv,error);CHECK(compiled);
+ if(!compiled){printf("history sampling PS: %s\n",error.c_str());return;}
+ resources.pixel=SDL3_Create_Shader(resources.device,spirv,false,error);CHECK(resources.pixel);
+ SDL_GPUColorTargetDescription colour={};colour.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
+ SDL_GPUGraphicsPipelineCreateInfo pi={};pi.vertex_shader=resources.vertex;pi.fragment_shader=resources.pixel;
+ pi.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;pi.target_info.color_target_descriptions=&colour;pi.target_info.num_color_targets=1;
+ resources.pipeline=SDL_CreateGPUGraphicsPipeline(resources.device,&pi);CHECK(resources.pipeline);if(!resources.pipeline)return;
+ SDL_GPUTextureCreateInfo ti={};ti.type=SDL_GPU_TEXTURETYPE_2D;ti.format=colour.format;ti.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;
+ ti.width=1;ti.height=rows;ti.layer_count_or_depth=ti.num_levels=1;resources.target=SDL_CreateGPUTexture(resources.device,&ti);CHECK(resources.target);if(!resources.target)return;
+ SDL_GPUSamplerCreateInfo si={};si.min_filter=si.mag_filter=SDL_GPU_FILTER_LINEAR;
+ si.address_mode_u=si.address_mode_v=si.address_mode_w=SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
+ resources.sampler=SDL_CreateGPUSampler(resources.device,&si);CHECK(resources.sampler);if(!resources.sampler)return;
+ resources.atlas=PosixTexture9::create(4,1,1,0,D3DFMT_A8R8G8B8,D3DPOOL_MANAGED);CHECK(resources.atlas);if(!resources.atlas)return;
+ D3DLOCKED_RECT lock={};CHECK(resources.atlas->LockRect(0,&lock,NULL,0)==D3D_OK);if(!lock.pBits)return;
+ memcpy(lock.pBits,texels,sizeof(texels));CHECK(resources.atlas->UnlockRect(0)==D3D_OK);
+ CHECK(frame->Flush());SdlResourceMirrors mirrors(frame);std::string refusal;
+ SDL_GPUTexture *atlas=mirrors.Texture(resources.atlas,refusal),*white=mirrors.White();CHECK(atlas && white);if(!atlas || !white)return;
+ CHECK(frame->Flush());SdlWaterPixelConstants water={};water.FoamHistoryArea[2]=1.0f/512;water.FoamHistoryArea[3]=1.0f/256;
+ water.FoamHistoryParameters[0]=1;water.FoamHistoryParameters[1]=7;water.FoamHistoryParameters[2]=1;water.FoamHistoryParameters[3]=10;
+ auto render=[&](bool enabled) {
+ water.FoamHistoryParameters[0]=enabled?1:0;
+ SDL_GPUCommandBuffer *commands=SDL_AcquireGPUCommandBuffer(resources.device);CHECK(commands);
+ SDL_GPUColorTargetInfo attachment={};attachment.texture=resources.target;attachment.load_op=SDL_GPU_LOADOP_DONT_CARE;attachment.store_op=SDL_GPU_STOREOP_STORE;
+ SDL_GPURenderPass *pass=SDL_BeginGPURenderPass(commands,&attachment,1,NULL);CHECK(pass);SDL_BindGPUGraphicsPipeline(pass,resources.pipeline);
+ SDL_GPUTextureSamplerBinding bindings[15]={};for(unsigned i=0;i<15;++i){bindings[i].texture=i==14?atlas:white;bindings[i].sampler=resources.sampler;}
+ SDL_BindGPUFragmentSamplers(pass,0,bindings,15);SDL_PushGPUFragmentUniformData(commands,0,&water,sizeof(water));
+ SDL_PushGPUFragmentUniformData(commands,1,queries.data(),queries.size()*sizeof(Query));SDL_DrawGPUPrimitives(pass,3,1,0,0);
+ SDL_EndGPURenderPass(pass);CHECK(SDL_SubmitGPUCommandBuffer(commands));return read_float_targets(frame,&resources.target,1,1,rows);
+ };
+ const auto values=render(true),paused=render(true),disabled=render(false);CHECK(values==paused);
+ CHECK(values.size()==rows*4 && disabled.size()==rows*4);if(values.size()!=rows*4 || disabled.size()!=rows*4)return;
+ double ageError=0,churnError=0;
+ for(unsigned row=0;row<rows;++row) {
+ const Query &q=queries[row];const bool inside=q.point[0]>=0 && q.point[0]<=512 && q.point[1]>=0 && q.point[1]<=256 && q.point[2]==7;
+ double channels[3]={};const double coordinate=q.point[0]/512.0*4-.5;const int lower=int(std::floor(coordinate));const double fraction=coordinate-lower;
+ for(unsigned c=0;c<3;++c)for(unsigned tap=0;tap<2;++tap) {
+ const int index=(std::max)(0,(std::min)(3,lower+int(tap)));
+ channels[c]+=double((texels[index]>>(16-c*8))&255)/255*(tap?fraction:1-fraction);
+ }
+ const double elapsed=(std::max)(0.0,double(q.point[3])-10),expectedAge=inside && channels[0]>0?(std::min)(1.0,channels[1]/channels[0]+elapsed/24):0;
+ const double expectedChurn=inside?channels[2]*std::exp(-elapsed/1.5):0;
+ ageError=(std::max)(ageError,std::abs(values[row*4+1]-expectedAge));churnError=(std::max)(churnError,std::abs(values[row*4+2]-expectedChurn));
+ CHECK(std::abs(values[row*4+1]-expectedAge)<.00001 && std::abs(values[row*4+2]-expectedChurn)<.00001);
+ // Porous redistribution can exceed its mean at individual pixels; the unchanged
+ // envelope remains bounded by source coverage, and fresh history is exactly equal.
+ CHECK(values[row*4]>=0 && values[row*4]<=1);
+ CHECK(values[row*4+3]>=0 && values[row*4+3]<=channels[0]*std::exp(-elapsed/9)+.00001);
+ CHECK(values[row*4]<=std::sqrt(double(values[row*4+3]))+.000002);
+ if(expectedAge*24<=1.5)CHECK(values[row*4]==values[row*4+3]);
+ for(unsigned c=0;c<3;++c){CHECK(std::isfinite(values[row*4+c]));CHECK(disabled[row*4+c]==0);if(!inside)CHECK(values[row*4+c]==0);}
+ }
+ CHECK(values[fresh*4]>.18f && values[old*4+1]==1 && values[weighted*4+1]==1); // unweighted interpolation would report .5
+ CHECK(values[empty*4]==0 && values[empty*4+1]==0 && values[empty*4+2]==0);
+ CHECK(values[outside*4]==0 && values[wrongLevel*4]==0 && values[border*4]==0);
+ for(unsigned c=0;c<3;++c)CHECK(values[fresh*4+c]==values[repeat*4+c]);
+ CHECK(values[aged*4+1]>.06f && values[expired*4]<.0000000001f);
+ unsigned breakupChanged=0,remnants=0;
+ for(unsigned i=0;i<16;++i) {
+ const double freshCoverage=values[(evolution+i*2)*4],oldCoverage=values[(evolution+i*2+1)*4];
+ if(std::abs(oldCoverage/std::exp(-12.0/9)-freshCoverage)>.01)++breakupChanged;
+ if(oldCoverage<freshCoverage*.15)++remnants;
+ }
+ CHECK(breakupChanged>=4 && remnants>=3);
+ resources.atlas->Release();resources.atlas=NULL;mirrors.Collect_Dead();CHECK(frame->Flush());
+ printf("sdl_gpu_frame_selfcheck: GPU production foam history: %u samples, age %.8f/churn %.8f; density-weighted filtering, level/outside/border/disabled guards, exact pause and elapsed-time breakup (%u changed, %u fragmented) checked\n",rows,ageError,churnError,breakupChanged,remnants);
+}
+#endif // __linux__
+
+#if defined(__linux__)
+static void check_gpu_foam_microcoverage(SdlGpuFrame *frame)
+{
+ // Evaluate the real production helper over large, distinct world windows. The independent
+ // invariants distinguish conserved optical density from nonlinear average coverage,
+ // continuous time evolution from static masks, and the exact unchanged older material.
+ const unsigned width=256,height=256;
+ PixelPipelineDescription description={};std::string source;
+ CHECK(EngineShader_Pixel_Program(ENGINE_SHADER_WATER_TRAPEZOID,description,source,COMBINER_SHADER_TARGET_SDL3_GPU));
+ const size_t noiseStart=source.find("float oceanHash("),noiseEnd=source.find("float3 oceanSky(");
+ std::string helper=WaterFoamShading::Source();const size_t historyStart=helper.find("// Returns coverage");
+ CHECK(noiseStart!=std::string::npos && noiseEnd>noiseStart && historyStart!=std::string::npos);
+ if(noiseStart==std::string::npos || noiseEnd<=noiseStart || historyStart==std::string::npos)return;
+ helper.resize(historyStart); // exact emitted functions; the unused history resource is unnecessary here
+ const char *vs="float4 main(uint id:SV_VertexID):SV_Position{return float4(id==1?3.0:-1.0,id==2?3.0:-1.0,0,1);}";
+ std::string ps="cbuffer Samples : register(b0,space3) {float4 Query;float4 Basis;float4 Clock;};\n"+
+ source.substr(noiseStart,noiseEnd-noiseStart)+helper+
+ // Frozen M1i/M1j morphology, including the old fresh allocation and band filter. This
+ // supplies independent unchanged-old and armed smooth/large/hard-patch controls.
+ "float frozenBand(float2 q,float c,float fp,float size,float minimumWidth) {"
+ "c=saturate(c);if(c<=0 || c>=1)return c;float ratio=max(fp,0)/size;"
+ "float unresolved=smoothstep(.5,1.5,ratio);if(unresolved>=1)return c;"
+ "float rank=waterFoamNoiseRank(oceanNoise(q/size));float w=clamp(ratio*.5,minimumWidth,.5);"
+ "return lerp(waterFoamRankCoverage(rank,c,w),c,unresolved);}"
+ "float frozenFoam(float2 p,float c,float fp,float age,float coarseSize,float minimumWidth) {"
+ "c=saturate(c);if(c<=0 || c>=1)return c;float a=lerp(1,sqrt(c),smoothstep(2,8,max(age,0)));"
+ "float2 coarse=float2(dot(p,float2(.8,.6)),dot(p,float2(-.6,.8)))+float2(17.31,-8.67);"
+ "float2 fine=float2(dot(p,float2(.28,.96)),dot(p,float2(-.96,.28)))+float2(-31.7,23.2);"
+ "return frozenBand(coarse,a,fp,coarseSize,minimumWidth)*frozenBand(fine,c/max(a,.00001),fp,.35,.01);}"
+ "float sampleFoam(float2 p,float c,float fp,float age) {return waterFoamMicroCoverage(p,c,fp,age,Clock.x);}"
+ "float4 main(float4 pixel:SV_Position):SV_Target0 {"
+ // Mode 12 exercises the actual fresh-contact redistribution separately from
+ // history and downstream microcoverage. Query.w optionally supplies compact support.
+ "if(Query.z>11.5) {float2 q=(pixel.xy-.5)*2.0;"
+ "float2 p=Basis.xy+float2(q.x*Basis.z-q.y*Basis.w,q.x*Basis.w+q.y*Basis.z);"
+ "float c=Query.x;if(Query.w>.5 && (abs(q.x-256)>96 || abs(q.y-256)>96))c=0;"
+ "return float4(waterFoamContactPatches(p,c,Query.y,Clock.x),c,"
+ "waterFoamContactPatches(p,0,Query.y,Clock.x),waterFoamContactPatches(p,1,Query.y,Clock.x));}"
+ // Fixture-only controls: mode 9 supplies angle/half-length/confidence directly;
+ // mode 10 checks the decoder; mode 11 connects real decoded moments to fallback.
+ "if(Query.z>9.5 && Query.z<10.5) {float a=Query.x;"
+ "float2 axial=float2(cos(2*Clock.y),sin(2*Clock.y))*Query.y;"
+ "return waterFoamRecordedDirection(float4((1+axial)*(.5*a),a*Query.w/32,a));}"
+ "if(Query.z>8.5) {float2 q=(pixel.xy-.5)*2.0;"
+ "float2 p=Basis.xy+float2(q.x*Basis.z-q.y*Basis.w,q.x*Basis.w+q.y*Basis.z);"
+ "float iso=waterFoamHistoryRemnants(p,Query.x,Query.y,Query.w,Clock.x);"
+ "float4 d=float4(cos(Clock.y),sin(Clock.y),Clock.z,Clock.w);"
+ "if(Query.z>10.5) {float2 axial=float2(cos(2*Clock.y),sin(2*Clock.y))*Clock.w;"
+ "d=waterFoamRecordedDirection(float4((1+axial)*(.5*Query.x),Query.x*Clock.z/32,Query.x));"
+ "return float4(waterFoamHistoryStreaks(p,Query.x,Query.y,Query.w,Clock.x,d,iso),iso,d.z,d.w);}"
+ "float streak=waterFoamHistoryStreaks(p,Query.x,Query.y,Query.w,Clock.x,d,iso);"
+ "float reverse=waterFoamHistoryStreaks(p,Query.x,Query.y,Query.w,Clock.x,float4(-d.xy,d.zw),iso);"
+ "float control=iso;if(Query.x>0 && Query.x<1 && Query.w>1.5) {float area=sqrt(Query.x);"
+ "control=lerp(Query.x,waterFoamStreakTap(p,area,max(Query.y,0)*1.7,Query.w,Clock.x)"
+ "*(Query.x/area),smoothstep(1.5,6,Query.w));}return float4(streak,reverse,iso,control);}"
+ "if(Query.z>7.5) {float2 q=(pixel.xy-.5)*2.0;"
+ "float2 p=Basis.xy+float2(q.x*Basis.z-q.y*Basis.w,q.x*Basis.w+q.y*Basis.z);"
+ "float c=waterFoamHistoryRemnants(p,Query.x,Query.y,Query.w,Clock.x);"
+ "return float4(c,waterFoamMicroCoverage(p,c,Query.y,Query.w,Clock.x),"
+ "waterFoamMicroCoverage(p,Query.x,Query.y,Query.w,Clock.x),Query.x);}"
+ "if(Query.z>5.5) {float c=Query.z>6.5?Query.x:(pixel.y-.5)/255.0,r=pixel.x/256.0;"
+ "if(c<=0 || c>=1)return float4(c,c,c,c);float d=waterFoamOpticalDepth(c),m=lerp(.15,1.85,r);"
+ "return float4(d*m,waterFoamOpticalCoverage(d*m),waterFoamFreshMean(d),c);}"
+ "if(Query.z>0.5 && Query.z<1.5) {float c=(pixel.y-.5)/255.0,r= pixel.x/256.0;"
+ "return float4(waterFoamRankCoverage(r,c,Query.y),0,0,1);}"
+ "float2 q=(pixel.xy-.5)*2.0;"
+ "float2 p=Basis.xy+float2(q.x*Basis.z-q.y*Basis.w,q.x*Basis.w+q.y*Basis.z);"
+ "if(Query.z>4.5) return float4(sampleFoam(p,Query.x,Query.y,0),"
+ "frozenFoam(p,Query.x,Query.y,0,1,.08),"
+ "sampleFoam(p,Query.x,Query.y,Query.w),frozenFoam(p,Query.x,Query.y,Query.w,1,.08));"
+ "if(Query.z>3.5) return float4(sampleFoam(p,Query.x,Query.y,8),"
+ "frozenFoam(p,Query.x,Query.y,8,1,.01),"
+ "waterFoamCoverageBand(p,Query.x,Query.y,1,.08),frozenBand(p,Query.x,Query.y,1,.01));"
+ "if(Query.z>2.5) return float4(sampleFoam(p,Query.x,Query.y,8),"
+ "frozenFoam(p,Query.x,Query.y,8,2.8,.01),frozenFoam(p,Query.x,Query.y,0,1,.08),1);"
+ "if(Query.z>1.5) return float4(waterFoamMicroCoverage(p,Query.x,Query.y),"
+ "sampleFoam(p,Query.x,Query.y,2),"
+ "sampleFoam(p,Query.x,Query.y,Query.w),frozenFoam(p,Query.x,Query.y,Query.w,1,.08));"
+ "return float4(sampleFoam(p,Query.x,Query.y,Query.w),"
+ "sampleFoam(p,Query.x*.25,Query.y,Query.w),"
+ "sampleFoam(p,0,Query.y,Query.w),sampleFoam(p,1,Query.y,Query.w));}";
+ struct Resources {
+ SDL_GPUDevice *device;SDL_GPUShader *vs=NULL,*ps=NULL;SDL_GPUGraphicsPipeline *pipeline=NULL;SDL_GPUTexture *target=NULL;
+ ~Resources(){if(target)SDL_ReleaseGPUTexture(device,target);if(pipeline)SDL_ReleaseGPUGraphicsPipeline(device,pipeline);
+ if(vs)SDL_ReleaseGPUShader(device,vs);if(ps)SDL_ReleaseGPUShader(device,ps);}
+ } resources;resources.device=frame->Device();
+ std::vector<unsigned char> spirv;std::string error;
+ bool compiled=SDL3_Compile_HLSL_To_SPIRV(vs,true,spirv,error);CHECK(compiled);if(!compiled)return;
+ resources.vs=SDL3_Create_Shader(resources.device,spirv,true,error);CHECK(resources.vs);if(!resources.vs)return;
+ compiled=SDL3_Compile_HLSL_To_SPIRV(ps,false,spirv,error);CHECK(compiled);
+ if(!compiled){printf("foam microcoverage PS: %s\n",error.c_str());return;}
+ unsigned samplers=0,buffers=0;SDL3_Shader_Slots(spirv,false,samplers,buffers);CHECK(samplers==0 && buffers==1);
+ if(samplers!=0 || buffers!=1)return;
+ resources.ps=SDL3_Create_Shader(resources.device,spirv,false,error);CHECK(resources.ps);if(!resources.ps)return;
+ SDL_GPUColorTargetDescription colour={};colour.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
+ SDL_GPUGraphicsPipelineCreateInfo pi={};pi.vertex_shader=resources.vs;pi.fragment_shader=resources.ps;
+ pi.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;pi.target_info.color_target_descriptions=&colour;pi.target_info.num_color_targets=1;
+ resources.pipeline=SDL_CreateGPUGraphicsPipeline(resources.device,&pi);CHECK(resources.pipeline);if(!resources.pipeline)return;
+ SDL_GPUTextureCreateInfo ti={};ti.type=SDL_GPU_TEXTURETYPE_2D;ti.format=colour.format;ti.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;
+ ti.width=width;ti.height=height;ti.layer_count_or_depth=ti.num_levels=1;
+ resources.target=SDL_CreateGPUTexture(resources.device,&ti);CHECK(resources.target);if(!resources.target)return;
+ CHECK(frame->Flush());unsigned renders=0;
+ auto render=[&](float coverage,float footprint,float age=0,float x=0,float y=0,float angle=0,unsigned mode=0,float step=2,float time=0,float directionAngle=0,float halfLength=0,float confidence=0) {
+ const float constants[12]={coverage,footprint,float(mode),age,x,y,cosf(angle)*step*.5f,sinf(angle)*step*.5f,time,directionAngle,halfLength,confidence};
+ SDL_GPUCommandBuffer *commands=SDL_AcquireGPUCommandBuffer(resources.device);CHECK(commands);
+ SDL_GPUColorTargetInfo attachment={};attachment.texture=resources.target;attachment.load_op=SDL_GPU_LOADOP_DONT_CARE;attachment.store_op=SDL_GPU_STOREOP_STORE;
+ SDL_GPURenderPass *pass=SDL_BeginGPURenderPass(commands,&attachment,1,NULL);CHECK(pass);
+ SDL_BindGPUGraphicsPipeline(pass,resources.pipeline);SDL_PushGPUFragmentUniformData(commands,0,constants,sizeof(constants));
+ SDL_DrawGPUPrimitives(pass,3,1,0,0);SDL_EndGPURenderPass(pass);CHECK(SDL_SubmitGPUCommandBuffer(commands));++renders;
+ return read_float_targets(frame,&resources.target,1,width,height);
+ };
+ auto meanFresh=[](double coverage) {
+ if(coverage<=0 || coverage>=1)return coverage;
+ const double d=-std::log1p(-coverage);
+ return 1-std::exp(-.15*d)*(-std::expm1(-1.7*d))/(1.7*d);
+ };
+ auto expectedMean=[&](double coverage,double age) {
+ const double t=(std::max)(0.0,(std::min)(1.0,(age-2)/6));
+ const double aged=t*t*(3-2*t);
+ return meanFresh(coverage)*(1-aged)+coverage*aged;
+ };
+ double maximumMeanError=0;unsigned gradedFresh=0;std::vector<float> reference;
+ for(float age:{0.f,2.f,5.f,8.f,16.f})for(float footprint:{.04f,.4f,4.f})for(float coverage:{.02f,.2f,.5f,.8f}) {
+ const auto values=render(coverage,footprint,age);CHECK(values.size()==width*height*4);if(values.size()!=width*height*4)return;
+ double sum[2]={};bool bounded=true,nested=true,endpoints=true;
+ for(unsigned i=0;i<width*height;++i) {
+ for(unsigned c=0;c<2;++c){const float v=values[i*4+c];bounded &= std::isfinite(v) && v>=0 && v<=1;sum[c]+=v;}
+ nested &= values[i*4+1]<=values[i*4]+.000001f;
+ endpoints &= values[i*4+2]==0 && values[i*4+3]==1;
+ if(footprint==4.f)nested &= std::abs(values[i*4]-expectedMean(coverage,age))<.000002 && std::abs(values[i*4+1]-expectedMean(coverage*.25f,age))<.000002;
+ }
+ CHECK(bounded && nested && endpoints);
+ for(unsigned c=0;c<2;++c) {
+ const double mean=sum[c]/(width*height),expected=expectedMean(coverage*(c?.25:1),age);
+ maximumMeanError=(std::max)(maximumMeanError,std::abs(mean-expected));
+ if(std::abs(mean-expected)>=.003+expected*.025)
+ printf("foam mean: age %.3f footprint %.3f coverage %.4f measured %.7f expected %.7f\n",age,footprint,coverage,mean,expected);
+ CHECK(std::abs(mean-expected)<.003+expected*.025);
+ }
+ if(age==0 && coverage==.5f && footprint==.04f) {
+ reference=values;
+ for(unsigned i=0;i<width*height;++i)gradedFresh+=values[i*4]>.05f && values[i*4]<.95f;
+ }
+ }
+ CHECK(gradedFresh==width*height); // no nearly opaque/empty ranked islands at c=.5
+ CHECK(render(.5f,.04f)==reference); // world-fixed, stationary/paused evaluation is exact
+ CHECK(render(.5f,.04f,2)==reference); // fresh allocation stays stable before the age transition
+ const auto panned=render(.5f,.04f,0,2,0),rotated=render(.5f,.04f,8,2113,-192,1.13f);
+ bool fixedWorld=true;double rotatedMean=0;
+ for(unsigned y=0;y<height;++y)for(unsigned x=0;x<width;++x) {
+ rotatedMean+=rotated[(y*width+x)*4];
+ if(x+1<width)fixedWorld &= panned[(y*width+x)*4]==reference[(y*width+x+1)*4];
+ }
+ CHECK(fixedWorld && std::abs(rotatedMean/(width*height)-.5)<.025);
+ const auto aged=render(.5f,.04f,8),agedPaused=render(.5f,.04f,8),agedLater=render(.5f,.04f,16);
+ CHECK(aged==agedPaused && aged==agedLater);
+ const auto agedPan=render(.5f,.04f,8,2,0);
+ for(unsigned y=0;y<height;++y)for(unsigned x=0;x<width;++x) {
+ const size_t at=(y*width+x)*4;
+ if(x+1<width)CHECK(agedPan[at]==aged[at+4]);
+ }
+ for(float coverage:{.02f,.2f,.5f,.8f})for(float footprint:{.04f,.4f,1.5f})for(float age:{8.f,16.f}) {
+ const auto oldControl=render(coverage,footprint,age,0,0,0,2);bool exactAgeEndpoints=true;
+ float freshDifference=0,oldDifference=0;
+ for(unsigned i=0;i<width*height;++i) {
+ exactAgeEndpoints &= oldControl[i*4]==oldControl[i*4+1] && oldControl[i*4+2]==oldControl[i*4+3];
+ freshDifference=fmaxf(freshDifference,fabsf(oldControl[i*4]-oldControl[i*4+1]));
+ oldDifference=fmaxf(oldDifference,fabsf(oldControl[i*4+2]-oldControl[i*4+3]));
+ }
+ if(!exactAgeEndpoints)printf("foam endpoint: c %.9g footprint %.9g age %.9g fresh %.9g old %.9g\n",coverage,footprint,age,freshDifference,oldDifference);
+ CHECK(exactAgeEndpoints); // fresh overload agrees at time zero; old ages exactly retain frozen M1j
+ }
+ const auto close=render(.5f,.0401f),almostFar=render(.5f,1.499f,8),far=render(.5f,1.5f,8);
+ float nearChange=0,farChange=0;
+ for(unsigned i=0;i<width*height;++i) {
+ nearChange=fmaxf(nearChange,fabsf(close[i*4]-reference[i*4]));
+ farChange=fmaxf(farChange,fabsf(almostFar[i*4]-far[i*4]));
+ }
+ CHECK(nearChange<.002f && farChange<.000002f);
+ float maximumAgeChange=0,ageGateChange=0;
+ for(float age:{2.f,5.f,8.f}) {
+ const auto before=render(.5f,.04f,age-.001f),after=render(.5f,.04f,age+.001f);
+ for(unsigned i=0;i<width*height;++i) {
+ const float change=fabsf(before[i*4]-after[i*4]);maximumAgeChange=fmaxf(maximumAgeChange,change);
+ if(age!=5)ageGateChange=fmaxf(ageGateChange,change);
+ }
+ }
+ CHECK(maximumAgeChange<.01f && ageGateChange<.00001f);
+ for(float coverage:{.000001f,.99f,.999f,.9999f,std::nextafter(1.f,0.f)}) {
+ const auto values=render(coverage,0),filtered=render(coverage,4);bool endpointLimit=true;
+ const double d=-std::log1p(-double(coverage));
+ const double lower=-std::expm1(-.15*d),upper=-std::expm1(-1.85*d);
+ for(unsigned i=0;i<width*height;++i) {
+ endpointLimit &= values[i*4]>=lower-.000002 && values[i*4]<=upper+.000002;
+ endpointLimit &= std::abs(filtered[i*4]-meanFresh(coverage))<.000002;
+ }
+ CHECK(endpointLimit); // explicitly retain the nonlinear, slow high-density limit
+ }
+
+ // Frozen M1j fresh pores are unresolved here, but one-world-unit old remnants remain resolved. The
+ // frozen M1i field has identical coverage and a 2.8-world-unit coarse scale. A normalized
+ // variogram measures actual connected-patch size independently of brightness/mean: at a
+ // half-world separation the smaller new remnants must decorrelate faster than that control.
+ const auto shape=render(.5f,.55f,0,0,0,0,3,.0625f);
+ double shapeMean[3]={},shapeVariance[3]={},shapeDifference[2]={};unsigned oldHoles=0,oldBodies=0,shapePairs=0;
+ for(unsigned i=0;i<width*height;++i)for(unsigned channel=0;channel<3;++channel)shapeMean[channel]+=shape[i*4+channel]/double(width*height);
+ for(unsigned y=0;y<height;++y)for(unsigned x=0;x<width;++x) {
+ const size_t at=(y*width+x)*4;
+ for(unsigned channel=0;channel<3;++channel) {
+ const double centered=shape[at+channel]-shapeMean[channel];shapeVariance[channel]+=centered*centered/(width*height);
+ }
+ oldHoles+=shape[at]<.25f;oldBodies+=shape[at]>.65f;
+ if(x+8<width && y+8<height) {
+ for(unsigned channel=0;channel<2;++channel) {
+ const double dx=shape[at+8*4+channel]-shape[at+channel],dy=shape[at+8*width*4+channel]-shape[at+channel];
+ shapeDifference[channel]+=dx*dx+dy*dy;
+ }
+ ++shapePairs;
+ }
+ }
+ double shapeVariogram[2]={};for(unsigned c=0;c<2;++c)shapeVariogram[c]=shapeDifference[c]/(4*shapePairs*(std::max)(shapeVariance[c],1e-12));
+ CHECK(shapeVariance[2]<.000000001 && shapeVariance[0]>.01 && oldHoles>100 && oldBodies>100);
+ CHECK(shapeVariogram[0]>shapeVariogram[1]*2); // armed old large-patch control
+ // Compare the same world positions, scale, coverage and footprint against a hard-edged
+ // control. More transition pixels and less normalized edge energy prove softness without
+ // relying on mean opacity, a larger remnant size, or averaging over distant pixels. The
+ // full two-band composition is checked as well as the isolated old-remnant boundary.
+ const auto soft=render(.5f,.01f,0,0,0,0,4,.03125f);
+ double softMean[4]={},softVariance[4]={},softDifference[4]={};unsigned transition[4]={},softPairs=0;
+ for(unsigned i=0;i<width*height;++i)for(unsigned c=0;c<4;++c)softMean[c]+=soft[i*4+c]/double(width*height);
+ for(unsigned y=0;y<height;++y)for(unsigned x=0;x<width;++x) {
+ const size_t at=(y*width+x)*4;
+ for(unsigned c=0;c<4;++c) {
+ const double value=soft[at+c],centered=value-softMean[c];softVariance[c]+=centered*centered/(width*height);
+ transition[c]+=value>.05 && value<.95;
+ if(x+1<width && y+1<height) {
+ const double dx=soft[at+4+c]-value,dy=soft[at+width*4+c]-value;softDifference[c]+=dx*dx+dy*dy;
+ }
+ }
+ if(x+1<width && y+1<height)++softPairs;
+ }
+ double softEnergy[4]={};for(unsigned c=0;c<4;++c)softEnergy[c]=softDifference[c]/(4*softPairs*(std::max)(softVariance[c],1e-12));
+ CHECK(softVariance[0]>.05 && softVariance[2]>.05);
+ CHECK(transition[2]>transition[3]*4 && softEnergy[2]<softEnergy[3]*.6);
+ CHECK(transition[0]>transition[1] && softEnergy[0]<softEnergy[1]); // production call must select the softer coarse filter
+ // Independent uniform-rank quadrature proves density conservation and the different
+ // coverage mean, including the stable near-zero branch. This control is not calibrated
+ // against the actual procedural noise or the implementation's mean helper.
+ const auto quadrature=render(0,0,0,0,0,0,6);
+ double densityError=0,coverageQuadratureError=0,meanFormulaError=0;
+ for(unsigned y=1;y<height-1;++y) {
+ // The shader may lower division to multiplication by a float reciprocal. Near one,
+ // that input rounding is amplified by -log(1-c); use its explicit input channel,
+ // not the output density, for an independent double-precision reference.
+ const double c=quadrature[y*width*4+3],d=-std::log1p(-c);double densitySum=0,coverageSum=0;
+ CHECK(std::abs(c-double(y)/(height-1))<.00000012);
+ for(unsigned x=0;x<width;++x) {
+ const size_t at=(y*width+x)*4;const double multiplier=.15+1.7*(x+.5)/width;
+ densityError=(std::max)(densityError,std::abs(quadrature[at]-d*multiplier));
+ coverageQuadratureError=(std::max)(coverageQuadratureError,std::abs(quadrature[at+1]+std::expm1(-d*multiplier)));
+ meanFormulaError=(std::max)(meanFormulaError,std::abs(quadrature[at+2]-meanFresh(c)));
+ densitySum+=quadrature[at];coverageSum+=quadrature[at+1];
+ }
+ if(std::abs(densitySum/width-d)>=.000003)printf("foam density row: y %u c %.12g mean %.12g expected %.12g\n",y,c,densitySum/width,d);
+ CHECK(std::abs(densitySum/width-d)<.000003);
+ CHECK(std::abs(coverageSum/width-meanFresh(c))<.000005);
+ CHECK(coverageSum/width<c); // Jensen: averaging density first would fail this control
+ }
+ CHECK(densityError<.000006 && coverageQuadratureError<.000002 && meanFormulaError<.000002);
+ for(float coverage:{.00000001f,.000001f,.0001f,.001f,.00999f,.01001f,.04876f,.04878f}) {
+ const auto values=render(coverage,0,0,0,0,0,7);
+ const double d=-std::log1p(-double(coverage)),mean=meanFresh(coverage);
+ bool accurateSmallDensity=true;double relativeErrors[3]={};
+ for(unsigned x=0;x<width;++x) {
+ const double multiplier=.15+1.7*(x+.5)/width;
+ const double expected=-std::expm1(-d*multiplier);
+ accurateSmallDensity &= std::abs(values[x*4]-d*multiplier)<(std::max)(1e-11,d*multiplier*2e-5);
+ accurateSmallDensity &= std::abs(values[x*4+1]-expected)<(std::max)(1e-11,expected*2e-5);
+ accurateSmallDensity &= std::abs(values[x*4+2]-mean)<(std::max)(1e-11,mean*2e-5);
+ relativeErrors[0]=(std::max)(relativeErrors[0],std::abs(values[x*4]-d*multiplier)/(d*multiplier));
+ relativeErrors[1]=(std::max)(relativeErrors[1],std::abs(values[x*4+1]-expected)/expected);
+ relativeErrors[2]=(std::max)(relativeErrors[2],std::abs(values[x*4+2]-mean)/mean);
+ }
+ if(!accurateSmallDensity)printf("foam small density: c %.12g first %.12g/%.12g/%.12g relative %.9g/%.9g/%.9g\n",coverage,values[0],values[1],values[2],relativeErrors[0],relativeErrors[1],relativeErrors[2]);
+ CHECK(accurateSmallDensity); // zero/cancellation cannot pass on faint trail edges
+ }
+ // Continuous material interiors and time evolution are both required. Use a close,
+ // contiguous world window, then compare a tiny time step and a substantial elapsed time.
+ // Pause and camera translation reproduce exactly the same world samples at that time.
+ const auto freshShape=render(.8f,.4f,8,0,0,0,5,.0625f,3);
+ const auto freshSoon=render(.8f,.4f,8,0,0,0,5,.0625f,3.001f);
+ const auto freshLater=render(.8f,.4f,8,0,0,0,5,.0625f,4);
+ CHECK(freshShape==render(.8f,.4f,8,0,0,0,5,.0625f,3));
+ const auto freshPan=render(.8f,.4f,8,.0625f,0,0,5,.0625f,3);
+ double freshMean=0,temporalRms=0;float tinyTimeChange=0;unsigned gradedInterior=0;bool exactOldShape=true,freshWorld=true;
+ for(unsigned y=0;y<height;++y)for(unsigned x=0;x<width;++x) {
+ const size_t at=(y*width+x)*4;const double value=freshShape[at];freshMean+=value/(width*height);
+ gradedInterior+=value>.25 && value<.93;
+ tinyTimeChange=fmaxf(tinyTimeChange,fabsf(freshSoon[at]-value));
+ const double dt=freshLater[at]-value;temporalRms+=dt*dt/(width*height);
+ exactOldShape &= freshShape[at+2]==freshShape[at+3] && freshLater[at+2]==freshShape[at+2];
+ if(x+1<width)freshWorld &= freshPan[at]==freshShape[at+4];
+ }
+ temporalRms=std::sqrt(temporalRms);
+ CHECK(exactOldShape && freshWorld && gradedInterior>width*height/2);
+ CHECK(tinyTimeChange<.002 && temporalRms>.005 && temporalRms<.2);
+ const auto freshFar=render(.8f,4,0,0,0,0,0,.0625f,3);
+ const auto freshFarLater=render(.8f,4,0,0,0,0,0,.0625f,4);
+ CHECK(freshFar==freshFarLater); // filtered coverage mean, independent of unresolved phase
+ const auto filterBefore=render(.8f,6.f/1.7f-.001f),filterAfter=render(.8f,6.f/1.7f+.001f);
+ float freshFilterChange=0;
+ for(unsigned i=0;i<width*height;++i)freshFilterChange=fmaxf(freshFilterChange,fabsf(filterBefore[i*4]-filterAfter[i*4]));
+ CHECK(freshFilterChange<.000002);
+
+ // Independent quadrature over uniform ranks: each row must have its requested mean at all
+ // filter widths and be monotone, so a folded/periodic outlining interval fails this control.
+ double rankAreaError=0;
+ for(float filterWidth:{.02f,.1125f,.3f,.5f}) {
+ const auto values=render(0,filterWidth,0,0,0,0,1);bool monotone=true;
+ for(unsigned y=0;y<height;++y) {
+ double sum=0;for(unsigned x=0;x<width;++x) {
+ const float v=values[(y*width+x)*4];sum+=v;
+ if(x>0)monotone &= v<=values[(y*width+x-1)*4]+.000001f;
+ if(y==0 || y==height-1)monotone &= v==float(y/(height-1));
+ }
+ rankAreaError=(std::max)(rankAreaError,std::abs(sum/width-double(y)/(height-1)));
+ }
+ CHECK(monotone);
+ }
+ CHECK(rankAreaError<.0002);
+ // The history-only redistribution targets a local mean, not a pointwise opacity cap.
+ // The preceding uniform-rank quadrature is an independent area oracle for each band.
+ // Here the actual production noise and full microcoverage composition must be armed at
+ // RTS footprints, remain bounded, and converge to the previous material when unresolved.
+ double historyMeanError=0,historyFinalMeanError=0,historyVariance=0,historyTemporal=0;
+ unsigned historyHoles=0,historyBright=0;
+ for(float age:{1.f,6.f,12.f})for(float footprint:{1.f,3.f})for(float coverage:{.2f,.5f,.8f}) {
+ const auto values=render(coverage,footprint,age,0,0,0,8,2,3);
+ CHECK(values.size()==width*height*4);if(values.size()!=width*height*4)return;
+ double mean=0,composed=0;bool finite=true,fresh=true;
+ for(unsigned i=0;i<width*height;++i) {
+ const double v=values[i*4];mean+=v/(width*height);composed+=values[i*4+1]/double(width*height);
+ CHECK(v<=std::sqrt(double(coverage))+.000001);
+ for(unsigned c=0;c<4;++c)finite &= std::isfinite(values[i*4+c]) && values[i*4+c]>=0 && values[i*4+c]<=1;
+ if(age<=1.5f)fresh &= values[i*4]==coverage && values[i*4+1]==values[i*4+2];
+ if(age==12 && footprint==3 && coverage==.5f) {
+ historyVariance+=(v-.5)*(v-.5)/(width*height);
+ historyHoles+=v<.2;historyBright+=v>.6;
+ }
+ }
+ CHECK(finite && fresh);historyMeanError=(std::max)(historyMeanError,std::abs(mean-coverage));
+ // A spatial CDF is calibrated, not an exact per-window integral. This bound applies
+ // to the 512x512-world test window; it does not assert exact conservation in a trail.
+ CHECK(std::abs(mean-coverage)<.025);
+ if(age==12 && footprint==3) {
+ historyFinalMeanError=(std::max)(historyFinalMeanError,std::abs(composed-coverage));
+ CHECK(std::abs(composed-coverage)<.025);
+ }
+ }
+ CHECK(historyVariance>.012 && historyHoles>width*height/20 && historyBright>width*height/20);
+ const auto history=render(.5f,3,12,0,0,0,8,2,3),historyPause=render(.5f,3,12,0,0,0,8,2,3);
+ const auto historyPan=render(.5f,3,12,2,0,0,8,2,3),historyLater=render(.5f,3,12,0,0,0,8,2,5);
+ const auto historySoon=render(.5f,3,12,0,0,0,8,2,3.0001f);
+ const auto noHistory=render(0,3,12,0,0,0,8,2,3),fullHistory=render(1,3,12,0,0,0,8,2,3);
+ const auto historyFar=render(.5f,12,12,0,0,0,8,2,3),historyFarLater=render(.5f,12,12,0,0,0,8,2,5);
+ const auto historyAgeBefore=render(.5f,3,1.499f,0,0,0,8,2,3),historyAgeAfter=render(.5f,3,1.501f,0,0,0,8,2,3);
+ const auto historyFilterBefore=render(.5f,18.f/1.7f-.001f,12,0,0,0,8,2,3);
+ const auto historyFilterAfter=render(.5f,18.f/1.7f+.001f,12,0,0,0,8,2,3);
+ for(const auto *v:{&history,&historyPause,&historyPan,&historyLater,&historySoon,&noHistory,&fullHistory,&historyFar,&historyFarLater,&historyAgeBefore,&historyAgeAfter,&historyFilterBefore,&historyFilterAfter}) {
+ CHECK(v->size()==width*height*4);if(v->size()!=width*height*4)return;
+ }
+ CHECK(history==historyPause && historyFar==historyFarLater);
+ bool historyWorld=true,historyEndpoints=true;float historyStep=0,historyAgeStep=0,historyFilterStep=0;
+ for(unsigned y=0;y<height;++y)for(unsigned x=0;x<width;++x) {
+ const size_t i=(y*width+x)*4;
+ if(x+1<width)historyWorld &= historyPan[i]==history[i+4];
+ historyEndpoints &= noHistory[i]==0 && noHistory[i+1]==0 && fullHistory[i]==1 && fullHistory[i+1]==1;
+ historyEndpoints &= historyFar[i]==.5f && historyFar[i+1]==historyFar[i+2];
+ historyTemporal+=(historyLater[i]-history[i])*(historyLater[i]-history[i])/double(width*height);
+ historyStep=fmaxf(historyStep,fabsf(historySoon[i]-history[i]));
+ historyAgeStep=fmaxf(historyAgeStep,fabsf(historyAgeBefore[i]-historyAgeAfter[i]));
+ historyFilterStep=fmaxf(historyFilterStep,fabsf(historyFilterBefore[i]-historyFilterAfter[i]));
+ }
+ historyTemporal=std::sqrt(historyTemporal);
+ CHECK(historyWorld && historyEndpoints && historyStep<.002f && historyAgeStep<.00001f && historyFilterStep<.00001f);
+ CHECK(historyTemporal>.005 && historyTemporal<.4);
+ printf("sdl_gpu_frame_selfcheck: history remnant material mean error %.7f/final %.7f, RTS variance %.7f holes %u bright %u, temporal RMS %.7f, small-time/age/filter %.7f/%.7f/%.7f; exact fresh/empty/full/pause/world-pan/unresolved controls checked\n",historyMeanError,historyFinalMeanError,historyVariance,historyHoles,historyBright,historyTemporal,historyStep,historyAgeStep,historyFilterStep);
+
+ // Retained axial moments orient coverage convolution, not the procedural coordinates.
+ // Decoder cases use an independent double-precision axial tensor/confidence oracle;
+ // compare the tensor rather than its arbitrary eigenvector sign near the pi seam.
+ auto smoothUnit=[](double lo,double hi,double x) {
+ const double t=(std::max)(0.0,(std::min)(1.0,(x-lo)/(hi-lo)));return t*t*(3-2*t);
+ };
+ struct DirectionCase {float opacity,coherence,angle,initialWidth;};
+ const DirectionCase directionCases[]={
+ {0,1,0,6},{.00005f,1,0,6},{.01f,1,.7f,6},{.02f,1,.7f,6},
+ {.05f,1,.7f,6},{.08f,1,.7f,6},{.5f,0,.7f,6},{.5f,.19f,.7f,6},
+ {.5f,.4f,.7f,6},{.5f,.65f,.7f,6},{.5f,1,0,0},{.5f,1,0,3},
+ {.5f,1,1.5707963f,6},{.5f,1,-1.5707963f,12},
+ {.5f,1,.7f,24},{.5f,1,3.8415927f,32},{.05f,.4f,-.7f,9}};
+ double directionError=0;
+ for(const auto &q:directionCases) {
+ const auto values=render(q.opacity,q.coherence,q.initialWidth,0,0,0,10,2,3,q.angle);
+ CHECK(values.size()==width*height*4);if(values.size()!=width*height*4)return;
+ const double confidence=q.opacity<=.0001f?0:
+ smoothUnit(.20,.65,q.coherence)*smoothUnit(.02,.08,q.opacity);
+ const double expectedLength=(std::max)(3.0,(std::min)(12.0,double(q.initialWidth)));
+ bool constant=true;
+ for(unsigned i=0;i<width*height;++i)for(unsigned c=0;c<4;++c)
+ constant &= std::isfinite(values[i*4+c]) && values[i*4+c]==values[c];
+ CHECK(constant);
+ if(confidence==0) {
+ CHECK(values[0]==0 && values[1]==0 && values[2]==0 && values[3]==0);
+ } else {
+ const double x=values[0],y=values[1];
+ directionError=(std::max)(directionError,std::abs(x*x+y*y-1));
+ directionError=(std::max)(directionError,std::abs(x*x-y*y-std::cos(2*double(q.angle))));
+ directionError=(std::max)(directionError,std::abs(2*x*y-std::sin(2*double(q.angle))));
+ directionError=(std::max)(directionError,std::abs(values[2]-expectedLength));
+ directionError=(std::max)(directionError,std::abs(values[3]-confidence));
+ }
+ }
+ CHECK(directionError<.00002);
+ // Each positive normalized convolution preserves the band's expected coverage. These
+ // finite windows are statistical checks, not exact mass conservation for a real trail
+ // with spatially varying density, age or direction. Existing rank quadrature is the
+ // independent area oracle; the zero-offset fourth channel is an armed spatial control.
+ double streakMeanError=0,streakSignError=0;
+ for(float coverage:{.2f,.5f,.8f})for(float footprint:{1.f,3.f})for(float length:{3.f,12.f}) {
+ const auto values=render(coverage,footprint,12,0,0,0,9,2,3,.7f,length,1);
+ CHECK(values.size()==width*height*4);if(values.size()!=width*height*4)return;
+ double sums[4]={};bool bounded=true;
+ for(unsigned i=0;i<width*height;++i)for(unsigned c=0;c<4;++c) {
+ const double v=values[i*4+c];sums[c]+=v/(width*height);
+ bounded &= std::isfinite(v) && v>=0 && v<=std::sqrt(double(coverage))+.000001;
+ streakSignError=(std::max)(streakSignError,std::abs(double(values[i*4])-values[i*4+1]));
+ }
+ CHECK(bounded);
+ for(unsigned c=0;c<4;++c)streakMeanError=(std::max)(streakMeanError,std::abs(sums[c]-coverage));
+ }
+ CHECK(streakMeanError<.025 && streakSignError==0);
+ // Low opacity and incoherent crossing moments must exercise the actual decoder and
+ // return the unmodified isotropic material, not invent a direction from a near-zero axis.
+ for(float opacity:{.01f,.5f})for(float coherence:{0.f,.19f}) {
+ const auto values=render(opacity,3,12,0,0,0,11,2,3,.7f,12,coherence);
+ CHECK(values.size()==width*height*4);if(values.size()!=width*height*4)return;
+ bool exact=true;for(unsigned i=0;i<width*height;++i)
+ exact &= values[i*4]==values[i*4+1] && values[i*4+2]==0 && values[i*4+3]==0;
+ CHECK(exact);
+ }
+ const auto lowOpacity=render(.01f,3,12,0,0,0,11,2,3,.7f,12,1);
+ CHECK(lowOpacity.size()==width*height*4);if(lowOpacity.size()!=width*height*4)return;
+ for(unsigned i=0;i<width*height;++i)CHECK(lowOpacity[i*4]==lowOpacity[i*4+1] && lowOpacity[i*4+3]==0);
+ const auto activeDecoded=render(.5f,3,12,0,0,0,11,2,3,.7f,12,1);
+ const auto partlyDecoded=render(.5f,3,12,0,0,0,11,2,3,.7f,12,.4f);
+ const auto directAxis=render(.5f,3,12,0,0,0,9,2,3,.7f,12,1);
+ for(const auto *v:{&activeDecoded,&partlyDecoded,&directAxis}) {
+ CHECK(v->size()==width*height*4);if(v->size()!=width*height*4)return;
+ }
+ double decodedCompositionError=0;
+ const double partialConfidence=smoothUnit(.20,.65,double(.4f));
+ for(unsigned i=0;i<width*height;++i) {
+ const size_t at=i*4;const double expected=directAxis[at+2]+partialConfidence*(directAxis[at]-directAxis[at+2]);
+ decodedCompositionError=(std::max)(decodedCompositionError,std::abs(double(activeDecoded[at])-directAxis[at]));
+ decodedCompositionError=(std::max)(decodedCompositionError,std::abs(double(partlyDecoded[at])-expected));
+ CHECK(activeDecoded[at+2]==12 && activeDecoded[at+3]==1);
+ }
+ CHECK(decodedCompositionError<.0001); // only decoder/trig roundoff may separate the paths
+ // Correlation is measured at a four-world-unit separation with the sampling grid
+ // aligned to each chosen axis. Comparing against the SAME 4/8-world unconvolved field
+ // prevents the older isotropic helper's different 6/12 scales from faking this result.
+ double minimumCorrelationGain=1e30,minimumAlongAdvantage=1e30,minimumStreakVariance=1e30;
+ for(float angle:{0.f,.7f,1.5707963f}) {
+ const auto values=render(.5f,3,12,0,0,angle,9,2,3,angle,12,1);
+ CHECK(values.size()==width*height*4);if(values.size()!=width*height*4)return;
+ double means[2]={},variances[2]={},along[2]={},across[2]={};unsigned pairs=0;
+ for(unsigned i=0;i<width*height;++i)for(unsigned c=0;c<2;++c)means[c]+=values[i*4+c*3]/double(width*height);
+ for(unsigned y=0;y<height;++y)for(unsigned x=0;x<width;++x) {
+ const size_t at=(y*width+x)*4;
+ for(unsigned c=0;c<2;++c) {
+ const double v=values[at+c*3],centered=v-means[c];variances[c]+=centered*centered/(width*height);
+ if(x+2<width && y+2<height) {
+ const double dx=values[at+8+c*3]-v,dy=values[at+width*8+c*3]-v;
+ along[c]+=dx*dx;across[c]+=dy*dy;
+ }
+ }
+ if(x+2<width && y+2<height)++pairs;
+ }
+ CHECK(pairs>0 && variances[0]>.005 && variances[1]>.02 && along[0]>0 && along[1]>0 && across[1]>0);
+ const double gain=(across[0]/along[0])/(across[1]/along[1]);
+ const double advantage=(across[0]-along[0])/(2*pairs*variances[0]);
+ minimumCorrelationGain=(std::min)(minimumCorrelationGain,gain);
+ minimumAlongAdvantage=(std::min)(minimumAlongAdvantage,advantage);
+ minimumStreakVariance=(std::min)(minimumStreakVariance,variances[0]);
+ CHECK(gain>2 && advantage>.15); // scalar blur or the unconvolved control cannot pass
+ }
+ const auto streak=render(.5f,3,12,0,0,0,9,2,3,.7f,12,1);
+ const auto streakPause=render(.5f,3,12,0,0,0,9,2,3,.7f,12,1);
+ const auto streakPan=render(.5f,3,12,2,0,0,9,2,3,.7f,12,1);
+ const auto streakTurn=render(.5f,3,12,0,0,0,9,2,3,.7001f,12,1);
+ const auto streakCross=render(.5f,3,12,0,0,0,9,2,3,2.2707963f,12,1);
+ const auto streakFallback=render(.5f,3,12,0,0,0,9,2,3,.7f,12,0);
+ const auto streakHalf=render(.5f,3,12,0,0,0,9,2,3,.7f,12,.5f);
+ for(const auto *v:{&streak,&streakPause,&streakPan,&streakTurn,&streakCross,&streakFallback,&streakHalf}) {
+ CHECK(v->size()==width*height*4);if(v->size()!=width*height*4)return;
+ }
+ CHECK(streak==streakPause);
+ bool streakWorld=true,exactFallback=true;float smallTurn=0,confidenceError=0;double crossTurnRms=0;
+ for(unsigned y=0;y<height;++y)for(unsigned x=0;x<width;++x) {
+ const size_t at=(y*width+x)*4;
+ if(x+1<width)streakWorld &= streakPan[at]==streak[at+4];
+ exactFallback &= streakFallback[at]==streakFallback[at+2];
+ smallTurn=fmaxf(smallTurn,fabsf(streakTurn[at]-streak[at]));
+ confidenceError=fmaxf(confidenceError,fabsf(streakHalf[at]-(streak[at]+streak[at+2])*.5f));
+ const double d=streakCross[at]-streak[at];crossTurnRms+=d*d/(width*height);
+ }
+ crossTurnRms=std::sqrt(crossTurnRms);
+ CHECK(streakWorld && exactFallback && smallTurn<.002f && confidenceError<.000001f && crossTurnRms>.02);
+ // The early endpoints must call the actual production function and remain exact.
+ for(float coverage:{0.f,.2f,.5f,1.f})for(float age:{0.f,1.5f,12.f}) {
+ if(age>1.5f && coverage>0 && coverage<1)continue;
+ const auto values=render(coverage,3,age,0,0,0,9,2,3,.7f,12,1);
+ CHECK(values.size()==width*height*4);if(values.size()!=width*height*4)return;
+ bool exact=true;for(unsigned i=0;i<width*height;++i)for(unsigned c=0;c<4;++c)exact &= values[i*4+c]==coverage;
+ CHECK(exact);
+ }
+ const auto streakFar=render(.5f,12,12,0,0,0,9,2,3,.7f,12,1);
+ const auto streakFarMoved=render(.5f,12,12,137,-219,0,9,2,5,1.1f,3,1);
+ CHECK(streakFar.size()==width*height*4 && streakFarMoved.size()==width*height*4);
+ if(streakFar.size()!=width*height*4 || streakFarMoved.size()!=width*height*4)return;
+ CHECK(streakFar==streakFarMoved);
+ float unresolvedError=0;for(float v:streakFar)unresolvedError=fmaxf(unresolvedError,fabsf(v-.5f));
+ CHECK(unresolvedError<.000001f);
+ printf("sdl_gpu_frame_selfcheck: recorded streak material decoder %.8f/composition %.8f, mean %.7f, exact sign error %.8f; minimum axial correlation gain %.5f / along advantage %.5f / variance %.7f; small-angle %.7f, quarter-turn RMS %.7f, confidence %.8f, unresolved %.8f; exact low-coherence/fresh/pause/world-pan controls checked\n",directionError,decodedCompositionError,streakMeanError,streakSignError,minimumCorrelationGain,minimumAlongAdvantage,minimumStreakVariance,smallTurn,crossTurnRms,confidenceError,unresolvedError);
+
+ // Fresh contact: verify statistical redistribution, not a particular noise formula.
+ // The earlier uniform-rank quadrature independently checks the rank-area integral.
+ // These constant-source windows cannot establish conservation for a correlated,
+ // spatially varying native contact source, nor replace its visual acceptance.
+ const float contactWindows[][3]={{0,0,0},{2113,-192,1.13f},{-811,1201,.37f}};
+ double contactMeanError=0,contactMinimumVariance=1e30,contactMinimumScaleRatio=1e30;
+ unsigned contactMinimumGaps=width*height,contactMinimumClusters=width*height;
+ std::vector<float> contactReference;
+ for(float footprint:{1.f,3.f})for(float coverage:{.2f,.5f,.8f}) {
+ if(footprint==3 && coverage!=.5f)continue;
+ for(const auto &window:contactWindows) {
+ const auto values=render(coverage,footprint,0,window[0],window[1],window[2],12,2,3);
+ CHECK(values.size()==width*height*4);if(values.size()!=width*height*4)return;
+ const double ceiling=1;double sum=0;bool bounded=true,endpoints=true;
+ for(unsigned i=0;i<width*height;++i) {
+ const double v=values[i*4];sum+=v;
+ bounded &= std::isfinite(v) && v>=0 && v<=ceiling+.000001;
+ endpoints &= values[i*4+1]==coverage && values[i*4+2]==0 && values[i*4+3]==1;
+ }
+ CHECK(bounded && endpoints);
+ const double mean=sum/(width*height),error=std::abs(mean-coverage);
+ contactMeanError=(std::max)(contactMeanError,error);
+ if(error>=.025)printf("contact patch mean: c %.3f fp %.3f window %.1f %.1f angle %.3f measured %.7f\n",coverage,footprint,window[0],window[1],window[2],mean);
+ CHECK(error<.025);
+ if(footprint==1 && coverage==.5f) {
+ double variance=0,nearEnergy=0,farEnergy=0;unsigned gaps=0,clusters=0;
+ for(unsigned y=0;y<height;++y)for(unsigned x=0;x<width;++x) {
+ const size_t at=(y*width+x)*4;const double v=values[at],d=v-mean;
+ // A dilute film remains between clusters; test contrast around the
+ // supplied mean rather than requiring opaque/empty binary islands.
+ variance+=d*d/(width*height);gaps+=v<.30;clusters+=v>.65;
+ if(x+8<width) {const double near=values[at+4]-v,far=values[at+32]-v;
+ nearEnergy+=near*near;farEnergy+=far*far;}
+ }
+ CHECK(variance>.015 && gaps>width*height/100 && clusters>width*height/20);
+ CHECK(nearEnergy>0 && farEnergy>1.5*nearEnergy);
+ contactMinimumVariance=(std::min)(contactMinimumVariance,variance);
+ if(nearEnergy>0)contactMinimumScaleRatio=(std::min)(contactMinimumScaleRatio,farEnergy/nearEnergy);
+ contactMinimumGaps=(std::min)(contactMinimumGaps,gaps);
+ contactMinimumClusters=(std::min)(contactMinimumClusters,clusters);
+ if(window[0]==0 && window[1]==0)contactReference=values;
+ }
+ }
+ }
+ const auto contactFrozen=render(.5f,1,0,0,0,0,12,2,3);
+ const auto contactTinyTime=render(.5f,1,0,0,0,0,12,2,3.0001f);
+ const auto contactLater=render(.5f,1,0,0,0,0,12,2,4);
+ const auto contactPan=render(.5f,1,0,2,0,0,12,2,3);
+ const std::vector<float> *contactTimeSamples[]={&contactReference,&contactFrozen,&contactTinyTime,&contactLater,&contactPan};
+ for(const auto *v:contactTimeSamples) {
+ CHECK(v->size()==width*height*4);if(v->size()!=width*height*4)return;
+ }
+ CHECK(contactReference==contactFrozen);
+ float contactTinyChange=0;double contactTimeRms=0;bool contactWorldFixed=true;
+ for(unsigned y=0;y<height;++y)for(unsigned x=0;x<width;++x) {
+ const size_t at=(y*width+x)*4;
+ contactTinyChange=fmaxf(contactTinyChange,fabsf(contactTinyTime[at]-contactReference[at]));
+ const double d=contactLater[at]-contactReference[at];contactTimeRms+=d*d/(width*height);
+ if(x+1<width)contactWorldFixed &= contactPan[at]==contactReference[at+4];
+ }
+ contactTimeRms=std::sqrt(contactTimeRms);
+ CHECK(contactTinyChange<.002f && contactTimeRms>.005 && contactTimeRms<.35 && contactWorldFixed);
+ // An armed finite source region distinguishes redistribution from additive foam:
+ // thousands of samples outside the support must remain exactly zero at nonzero time.
+ const auto contactSupported=render(.5f,1,1,-73,119,.37f,12,2,4);
+ CHECK(contactSupported.size()==width*height*4);if(contactSupported.size()!=width*height*4)return;
+ unsigned contactOutside=0,contactInsideActive=0;bool contactSupportExact=true;
+ for(unsigned y=0;y<height;++y)for(unsigned x=0;x<width;++x) {
+ const size_t at=(y*width+x)*4;
+ const bool inside=std::abs(int(x)*2-256)<=96 && std::abs(int(y)*2-256)<=96;
+ const float c=inside?.5f:0.f,v=contactSupported[at];
+ contactSupportExact &= contactSupported[at+1]==c && contactSupported[at+2]==0 && contactSupported[at+3]==1;
+ contactSupportExact &= std::isfinite(v) && v>=0 && v<=1;
+ if(!inside){++contactOutside;contactSupportExact &= v==0;}
+ else contactInsideActive+=v>.1f;
+ }
+ CHECK(contactSupportExact && contactOutside>width*height/2 && contactInsideActive>100);
+ // Above the physical filter cutoff, phase/position must not leave shimmering patches.
+ // The independent target is the input mean; sqrt/divide/multiply may round by an ULP.
+ float contactFarError=0;std::vector<float> contactFarHalf;
+ for(float coverage:{.2f,.5f,.8f}) {
+ const auto values=render(coverage,12,0,0,0,0,12,2,3);
+ CHECK(values.size()==width*height*4);if(values.size()!=width*height*4)return;
+ bool uniform=true;for(unsigned i=0;i<width*height;++i) {
+ contactFarError=fmaxf(contactFarError,fabsf(values[i*4]-coverage));
+ uniform &= values[i*4]==values[0] && values[i*4+1]==coverage && values[i*4+2]==0 && values[i*4+3]==1;
+ }
+ CHECK(uniform);if(coverage==.5f)contactFarHalf=values;
+ }
+ const auto contactFarMoved=render(.5f,12,0,137,-219,.71f,12,2,19);
+ CHECK(contactFarMoved.size()==width*height*4);if(contactFarMoved.size()!=width*height*4)return;
+ CHECK(contactFarHalf==contactFarMoved && contactFarError<.000001f);
+ printf("sdl_gpu_frame_selfcheck: fresh contact patches: 21 added atlases, maximum mean error %.7f; bounded two-scale coverage, minimum variance %.7f / 16:2-world energy ratio %.5f, minimum gaps %u / clusters %u; 0.0001-second max %.7f / 1-second RMS %.7f; exact pause/world-pan/support (%u exterior samples), unresolved mean error %.8f\n",contactMeanError,contactMinimumVariance,contactMinimumScaleRatio,contactMinimumGaps,contactMinimumClusters,contactTinyChange,contactTimeRms,contactOutside,contactFarError);
+
+ printf("sdl_gpu_frame_selfcheck: GPU foam microcoverage: %u world atlases, maximum expected-coverage error %.7f; uniform-rank density/value/mean errors %.7f/%.7f/%.7f; graded fresh %u, close mean %.7f, time-step max %.7f and 1-second RMS %.7f; old/frozen patch variogram %.7f/%.7f; soft/hard edge energy %.7f/%.7f, band %.7f/%.7f; rank quadrature %.7f; exact pause/world pan/old ages, smooth age %.7f (gates %.9f), footprint %.7f/%.7f/%.7f checked\n",renders,maximumMeanError,densityError,coverageQuadratureError,meanFormulaError,gradedInterior,freshMean,tinyTimeChange,temporalRms,shapeVariogram[0],shapeVariogram[1],softEnergy[0],softEnergy[1],softEnergy[2],softEnergy[3],rankAreaError,maximumAgeChange,ageGateChange,nearChange,farChange,freshFilterChange);
+}
+#endif // __linux__
+
+#if defined(__linux__)
+static void check_gpu_foam_irradiance(SdlGpuFrame *frame)
+{
+ // These are authored legacy light colours, not pre-linearized radiance. Expected values
+ // are independently integrated in double precision below, including coloured and HDR sums.
+ struct Query {float normal[4],light[4],ambient[4],sun[4],fillDirection1[4],fillColour1[4],fillDirection2[4],fillColour2[4];};
+ const Query queries[]={
+ {{0,0,1,0},{0,0,1,0},{.21f,.34f,.56f,0},{0,0,0,0}},
+ {{1,0,0,0},{0,0,-1,1},{.21f,.34f,.56f,0},{0,0,0,0}},
+ {{0,0,-1,0},{.6f,0,.8f,.5f},{.21f,.34f,.56f,0},{0,0,0,0}},
+ {{0,0,1,0},{0,0,1,1},{0,0,0,0},{.25f,.5f,.75f,0}},
+ {{0,0,1,0},{0,0,1,0},{0,0,0,0},{.25f,.5f,.75f,0}},
+ {{0,0,-1,0},{0,0,1,1},{0,0,0,0},{.25f,.5f,.75f,0}},
+ {{1,0,0,0},{0,0,1,1},{0,0,0,0},{.25f,.5f,.75f,0}},
+ {{.6f,0,.8f,0},{0,0,1,1},{0,0,0,0},{.25f,.5f,.75f,0}},
+ {{.6f,0,.8f,0},{0,.6f,.8f,1},{.18f,.31f,.52f,0},{.67f,.23f,.11f,0}},
+ {{.6f,0,.8f,0},{0,.6f,.8f,.375f},{.18f,.31f,.52f,0},{.67f,.23f,.11f,0}},
+ {{0,0,1,0},{0,0,1,1},{.75f,.65f,.55f,0},{.85f,.95f,1.15f,0}},
+ {{0,0,1,0},{0,0,1,1},{-.1f,.1f,-.5f,0},{.3f,.2f,.1f,0}},
+ {{0,0,1,0},{0,0,1,1},{0,0,0,0},{0,0,0,0}},
+ {{.6f,0,.8f,0},{0,.6f,.8f,0},{.18f,.31f,.52f,0},{.67f,.23f,.11f,0}},
+ // Rotate both directions ninety degrees around Z: diffuse illumination is unchanged.
+ {{0,.6f,.8f,0},{-.6f,0,.8f,1},{.18f,.31f,.52f,0},{.67f,.23f,.11f,0}},
+ // Three coloured lights, then shadow only the main sun. The authored fill stays present.
+ {{0,0,1,0},{0,0,1,1},{.1f,.2f,.3f,0},{.4f,.2f,.1f,0},{.6f,0,.8f,0},{.2f,.4f,.6f,0},{0,.8f,.6f,0},{.3f,.2f,.1f,0}},
+ {{0,0,1,0},{0,0,1,0},{.1f,.2f,.3f,0},{.4f,.2f,.1f,0},{.6f,0,.8f,0},{.2f,.4f,.6f,0},{0,.8f,.6f,0},{.3f,.2f,.1f,0}},
+ {{1,0,0,0},{0,0,1,1},{.1f,.2f,.3f,0},{.4f,.2f,.1f,0},{.6f,0,.8f,0},{.2f,.4f,.6f,0},{0,.8f,.6f,0},{.3f,.2f,.1f,0}},
+ {{0,1,0,0},{0,0,1,1},{.1f,.2f,.3f,0},{.4f,.2f,.1f,0},{0,.6f,.8f,0},{.2f,.4f,.6f,0},{-.8f,0,.6f,0},{.3f,.2f,.1f,0}},
+ {{0,0,-1,0},{0,0,1,1},{.1f,.2f,.3f,0},{.4f,.2f,.1f,0},{.6f,0,.8f,0},{.2f,.4f,.6f,0},{0,.8f,.6f,0},{.3f,.2f,.1f,0}},
+ {{0,0,1,0},{0,0,1,0},{.1f,.2f,.3f,0},{.4f,.2f,.1f,0}},
+ // Tournament Island's actual morning map lights, with an armed one-sun-only control.
+ {{0,0,1,0},{.88978535f,-.04663176f,.45399061f,1},{.50196081f,.4f,.3019608f,0},{.38823530f,.27450982f,.08627451f,0},
+ {.38457698f,-.86377418f,.32556823f,0},{.23529412f,.19607843f,.19607843f,0},{.80184519f,.27609733f,.52991933f,0},{.23529412f,.19607843f,.19607843f,0}},
+ {{0,0,1,0},{.88978535f,-.04663176f,.45399061f,1},{.50196081f,.4f,.3019608f,0},{.38823530f,.27450982f,.08627451f,0}},
+ // USA02 has valid fill directions but zero diffuse colours: preserve its former result.
+ {{0,0,1,0},{.79692197f,-.53753084f,.27563736f,1},{.52156866f,.41568628f,.3019608f,0},{.90196079f,.70196080f,.56470591f,0},
+ {-.01745246f,0,.99984771f,0},{0,0,0,0},{-.01745246f,0,.99984771f,0},{0,0,0,0}},
+ };
+ const unsigned rows=sizeof(queries)/sizeof(queries[0]);
+ PixelPipelineDescription pd={};std::string production;
+ CHECK(EngineShader_Pixel_Program(ENGINE_SHADER_WATER_TRAPEZOID,pd,production,COMBINER_SHADER_TARGET_SDL3_GPU));
+ const size_t noiseStart=production.find("float oceanHash("),noiseEnd=production.find("float3 oceanSky(");
+ CHECK(noiseStart!=std::string::npos && noiseEnd>noiseStart);
+ if(noiseStart==std::string::npos || noiseEnd==std::string::npos || noiseEnd<=noiseStart)return;
+ const char *vs="float4 main(uint id:SV_VertexID):SV_Position{return float4(id==1?3.0:-1.0,id==2?3.0:-1.0,0,1);}";
+ std::string ps="Texture2D Texture14:register(t14);SamplerState Sampler14:register(s14);\n"
+ "struct Query{float4 normal;float4 light;float4 ambient;float4 sun;float4 fillDirection1;float4 fillColour1;float4 fillDirection2;float4 fillColour2;};\n"
+ "cbuffer QueryBlock:register(b0){Query Queries["+std::to_string(rows)+"];"
+ "float4 FoamHistoryArea;float4 FoamHistoryParameters;};\n"+
+ production.substr(noiseStart,noiseEnd-noiseStart)+WaterFoamShading::HistorySamplingSource()+WaterFoamShading::Source()+
+ "float4 main(float4 pixel:SV_Position):SV_Target0{Query q=Queries[(uint)pixel.y];"
+ "float3 value=waterFoamIrradiance(q.normal.xyz,q.light.xyz,q.ambient.xyz,q.sun.xyz,q.light.w,q.fillDirection1.xyz,q.fillColour1.xyz,q.fillDirection2.xyz,q.fillColour2.xyz);"
+ "float3 old=waterFoamIrradiance(q.normal.xyz,q.light.xyz,q.ambient.xyz,q.sun.xyz,q.light.w);float3 error=abs(value-old);"
+ "return float4(value,max(error.x,max(error.y,error.z)));}\n";
+ CHECK(SDL3_Shader_Retarget(ps,false));
+ struct Resources {
+ SDL_GPUDevice *device;SDL_GPUShader *vertex=NULL,*pixel=NULL;SDL_GPUGraphicsPipeline *pipeline=NULL;SDL_GPUTexture *target=NULL;
+ SDL_GPUSampler *sampler=NULL;
+ ~Resources(){if(target)SDL_ReleaseGPUTexture(device,target);if(pipeline)SDL_ReleaseGPUGraphicsPipeline(device,pipeline);
+ if(vertex)SDL_ReleaseGPUShader(device,vertex);if(pixel)SDL_ReleaseGPUShader(device,pixel);
+ if(sampler)SDL_ReleaseGPUSampler(device,sampler);}
+ } resources;
+ resources.device=frame->Device();std::string error;std::vector<unsigned char> spirv;
+ bool compiled=SDL3_Compile_HLSL_To_SPIRV(vs,true,spirv,error);CHECK(compiled);if(!compiled)return;
+ resources.vertex=SDL3_Create_Shader(resources.device,spirv,true,error);CHECK(resources.vertex);if(!resources.vertex)return;
+ compiled=SDL3_Compile_HLSL_To_SPIRV(ps,false,spirv,error);CHECK(compiled);
+ if(!compiled){printf("foam irradiance PS: %s\n",error.c_str());return;}
+ unsigned samplers=0,buffers=0;SDL3_Shader_Slots(spirv,false,samplers,buffers);CHECK(samplers==15 && buffers==1);
+ if(samplers!=15 || buffers!=1)return;
+ resources.pixel=SDL3_Create_Shader(resources.device,spirv,false,error);CHECK(resources.pixel);if(!resources.pixel)return;
+ SDL_GPUColorTargetDescription colour={};colour.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
+ SDL_GPUGraphicsPipelineCreateInfo pi={};pi.vertex_shader=resources.vertex;pi.fragment_shader=resources.pixel;
+ pi.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;pi.target_info.color_target_descriptions=&colour;pi.target_info.num_color_targets=1;
+ resources.pipeline=SDL_CreateGPUGraphicsPipeline(resources.device,&pi);CHECK(resources.pipeline);if(!resources.pipeline)return;
+ SDL_GPUTextureCreateInfo ti={};ti.type=SDL_GPU_TEXTURETYPE_2D;ti.format=colour.format;ti.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;
+ ti.width=1;ti.height=rows;ti.layer_count_or_depth=ti.num_levels=1;
+ resources.target=SDL_CreateGPUTexture(resources.device,&ti);CHECK(resources.target);if(!resources.target)return;
+ SDL_GPUSamplerCreateInfo si={};si.min_filter=si.mag_filter=SDL_GPU_FILTER_LINEAR;
+ si.address_mode_u=si.address_mode_v=si.address_mode_w=SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
+ resources.sampler=SDL_CreateGPUSampler(resources.device,&si);CHECK(resources.sampler);if(!resources.sampler)return;
+ CHECK(frame->Flush());SdlResourceMirrors mirrors(frame);SDL_GPUTexture *white=mirrors.White();CHECK(white);if(!white)return;
+ CHECK(frame->Flush());SDL_GPUCommandBuffer *commands=SDL_AcquireGPUCommandBuffer(resources.device);CHECK(commands);if(!commands)return;
+ SDL_GPUColorTargetInfo attachment={};attachment.texture=resources.target;attachment.load_op=SDL_GPU_LOADOP_DONT_CARE;attachment.store_op=SDL_GPU_STOREOP_STORE;
+ SDL_GPURenderPass *pass=SDL_BeginGPURenderPass(commands,&attachment,1,NULL);CHECK(pass);
+ if(!pass){SDL_CancelGPUCommandBuffer(commands);return;}
+ SDL_BindGPUGraphicsPipeline(pass,resources.pipeline);
+ // The unused history declarations deliberately remain available to the full production
+ // source. The compiler retains its Texture14 descriptor, so all reflected slots must be
+ // valid even for the irradiance entry. Its noise function is the real one, not a stub.
+ SDL_GPUTextureSamplerBinding bindings[15]={};
+ for(unsigned i=0;i<15;++i){bindings[i].texture=white;bindings[i].sampler=resources.sampler;}
+ SDL_BindGPUFragmentSamplers(pass,0,bindings,15);
+ std::vector<float> constants(rows*sizeof(Query)/sizeof(float)+8,0);
+ memcpy(constants.data(),queries,sizeof(queries));
+ SDL_PushGPUFragmentUniformData(commands,0,constants.data(),unsigned(constants.size()*sizeof(float)));
+ SDL_DrawGPUPrimitives(pass,3,1,0,0);SDL_EndGPURenderPass(pass);CHECK(SDL_SubmitGPUCommandBuffer(commands));
+ const auto values=read_float_targets(frame,&resources.target,1,1,rows);CHECK(values.size()==rows*4);if(values.size()!=rows*4)return;
+ double errorMax=0,wrongLinearOrder=0;
+ for(unsigned row=0;row<rows;++row) {
+ const Query &q=queries[row];double cosine=0,fillCosine1=0,fillCosine2=0;
+ for(unsigned c=0;c<3;++c){cosine+=double(q.normal[c])*q.light[c];
+ fillCosine1+=double(q.normal[c])*q.fillDirection1[c];fillCosine2+=double(q.normal[c])*q.fillDirection2[c];}
+ const double incoming=(std::max)(0.0,cosine)*q.light[3];
+ for(unsigned c=0;c<3;++c) {
+ const double expected=std::pow((std::max)(0.0,double(q.ambient[c])+q.sun[c]*incoming
+ +q.fillColour1[c]*(std::max)(0.0,fillCosine1)+q.fillColour2[c]*(std::max)(0.0,fillCosine2)),2.2);
+ const double actual=values[row*4+c];errorMax=(std::max)(errorMax,std::abs(actual-expected));
+ CHECK(std::isfinite(actual) && std::abs(actual-expected)<.00001);
+ if(row==8) {
+ // Armed control: decoding the two light terms separately is observably different.
+ const double wrong=std::pow(double(q.ambient[c]),2.2)+std::pow(double(q.sun[c]),2.2)*incoming;
+ wrongLinearOrder=(std::max)(wrongLinearOrder,std::abs(actual-wrong));
+ }
+ }
+ if(row<15 || row==20 || row==22 || row==23)CHECK(values[row*4+3]==0); // one-light/zero-fill results remain bit-exact
+ }
+ for(unsigned c=0;c<3;++c) {
+ CHECK(values[c]==values[4+c] && values[c]==values[8+c]); // ambient ignores normal, sun direction and shadow
+ CHECK(values[3*4+c]>0 && values[4*4+c]==0 && values[5*4+c]==0 && values[6*4+c]==0);
+ CHECK(values[7*4+c]>0 && values[7*4+c]<values[3*4+c]);
+ CHECK(values[9*4+c]<values[8*4+c] && values[13*4+c]<values[9*4+c]);
+ CHECK(values[10*4+c]>1.0f); // no global radiance saturation before surface composition
+ CHECK(values[12*4+c]==0);
+ CHECK(std::abs(values[14*4+c]-values[8*4+c])<.000001f);
+ }
+ CHECK(values[11*4]>0 && values[11*4+1]>0 && values[11*4+2]==0);
+ CHECK(wrongLinearOrder>.03);
+ for(unsigned c=0;c<3;++c) {
+ CHECK(values[15*4+c]>values[16*4+c] && values[16*4+c]>values[20*4+c]);
+ CHECK(values[17*4+c]==values[18*4+c] && values[19*4+c]==values[20*4+c]);
+ CHECK(values[21*4+c]>values[22*4+c]);
+ }
+ CHECK(values[21*4+3]>.3f && values[23*4+3]==0);
+ printf("sdl_gpu_frame_selfcheck: GPU production foam irradiance: %u coloured fixtures, independent error %.8f; zero/one/three lights, unshadowed authored fills, ambient invariance, rotated normals, Island missing-fill control %.8f, USA02 unchanged, HDR/no clamp and decode-after-light-sum control %.8f checked\n",rows,errorMax,values[21*4+3],wrongLinearOrder);
+}
+#endif // __linux__
+
+#if defined(__linux__)
+static void check_gpu_foam_environment(SdlGpuFrame *frame)
+{
+ using namespace WaterFoamEnvironment;
+ // The source below independently reproduces the selected oceanSky radiance, including its
+ // hash and directional cloud bank, with only the explicit solar halo omitted. It never
+ // calls the CPU sky generator or its emitted coefficients. GPU radiance is integrated
+ // with independent sphere and cosine-hemisphere measures on the CPU after test readback.
+ const char *reference=R"HLSL(
+float originalHash(float2 p) {
+ float3 q=frac(float3(p.x,p.y,p.x)*0.1031);q+=dot(q,q.yzx+33.33);return frac((q.x+q.y)*q.z);
+}
+float originalNoise(float2 p) {
+ float2 cell=floor(p),f=frac(p);f=f*f*(3.0-2.0*f);
+ return lerp(lerp(originalHash(cell),originalHash(cell+float2(1,0)),f.x),
+ lerp(originalHash(cell+float2(0,1)),originalHash(cell+float2(1,1)),f.x),f.y);
+}
+float3 originalSky(float3 ray) {
+ float horizon=pow(1.0-saturate(ray.z),4.0);
+ float2 plane=ray.xy/(0.45+abs(ray.z));
+ float cloud=originalNoise(plane*2.7+float2(7.8,2.3))*0.7+originalNoise(plane*6.1+float2(0.4,13.7))*0.3;
+ float bank=pow(saturate(dot(ray,normalize(float3(0,1,0.85)))),48.0);
+ cloud=smoothstep(0.46,0.73,cloud)*(0.04+1.5*bank);
+ float3 radiance=lerp(float3(0.016,0.055,0.110),float3(0.023,0.070,0.130),horizon)+cloud*float3(1.85,1.96,2.04);
+ return lerp(float3(0.001,0.005,0.010),radiance,smoothstep(-0.12,0.18,ray.z));
+}
+)HLSL";
+ struct Query {float normal[4],light[4],ambient[4],sun[4],fillDirection1[4],fillColour1[4],fillDirection2[4],fillColour2[4];};
+ std::vector<Query> queries;
+ std::vector<unsigned> canonical,rotationSource;
+ const double pi=3.14159265358979323846;
+ auto append=[&](Query q){q.fillDirection1[3]=1;queries.push_back(q);return unsigned(queries.size()-1);};
+ for(unsigned tilt:{0u,20u,45u,60u,85u,90u,120u,160u,180u}) for(unsigned azimuth=0;azimuth<360;azimuth+=60) {
+ if((tilt==0 || tilt==180) && azimuth)continue;
+ const double a=tilt*pi/180,b=azimuth*pi/180;
+ Query q={};q.normal[0]=float(std::sin(a)*std::cos(b));q.normal[1]=float(std::sin(a)*std::sin(b));q.normal[2]=float(std::cos(a));
+ q.normal[3]=1;q.light[0]=1;q.light[3]=1;q.sun[3]=1;canonical.push_back(append(q));
+ }
+ const unsigned canonicalCount=unsigned(canonical.size());
+ for(unsigned index:{0u,7u,14u,21u,28u,35u,43u})for(float angle:{.67f,2.13f}) {
+ Query q=queries[index];const float c=cosf(angle),s=sinf(angle),x=q.normal[0],y=q.normal[1];
+ q.normal[0]=c*x-s*y;q.normal[1]=s*x+c*y;q.light[0]=c;q.light[1]=s;append(q);rotationSource.push_back(index);
+ }
+ const unsigned lightingBegin=unsigned(queries.size());
+ for(float offshore:{0.f,.35f,1.f})for(float visibility:{0.f,.4f,1.f}) {
+ Query q={{.6f,0,.8f,offshore},{0,.6f,.8f,visibility},{.5019608f,.4f,.3019608f,0},
+ {.3882353f,.2745098f,.0862745f,.3882353f},{.384577f,-.863774f,.325568f,0},{.235294f,.196078f,.196078f,0},
+ {.801845f,.276097f,.529919f,0},{.235294f,.196078f,.196078f,0}};
+ append(q);
+ }
+ Query q=queries[lightingBegin];q.normal[3]=1;q.ambient[0]=q.ambient[1]=q.ambient[2]=0;
+ q.sun[0]=q.sun[1]=q.sun[2]=q.fillColour1[0]=q.fillColour1[1]=q.fillColour1[2]=q.fillColour2[0]=q.fillColour2[1]=q.fillColour2[2]=0;
+ q.sun[3]=0;const unsigned night=append(q);q.sun[3]=1;const unsigned day=append(q);q.sun[3]=5;const unsigned hdr=append(q);
+ q=queries[lightingBegin];q.normal[3]=0;q.sun[0]=2;q.sun[1]=3;q.sun[2]=4;q.light[3]=1;
+ const unsigned hdrAuthored=append(q);
+ q=queries[lightingBegin+6];const unsigned noVessel=append(q);queries[noVessel].fillDirection1[3]=0;
+ const unsigned count=unsigned(queries.size()),batchQueries=31;CHECK(count<128);
+ static_assert(sizeof(Query)==128,"Lighting query must follow eight HLSL float4 registers");
+ // SDL Vulkan exposes4096-byte UBO sections. The production water block is smaller,
+ // but this independent atlas has more queries and must upload bounded batches.
+ CHECK(16+batchQueries*sizeof(Query)<=4096);
+ PixelPipelineDescription description={};std::string production;
+ CHECK(EngineShader_Pixel_Program(ENGINE_SHADER_WATER_TRAPEZOID,description,production,COMBINER_SHADER_TARGET_SDL3_GPU));
+ const size_t callStart=production.find("float3 vesselIrradiance=waterFoamIrradiance("),callEnd=production.find("float3 vesselDiffuse=",callStart);
+ CHECK(callStart!=std::string::npos && callEnd>callStart);if(callStart==std::string::npos || callEnd<=callStart)return;
+ const std::string foam=WaterFoamShading::Source();const size_t end=foam.find("// Cubic bilinear value noise");
+ CHECK(end!=std::string::npos && foam.find("waterFoamReplaceAmbient")<end);if(end==std::string::npos)return;
+ std::string ps="struct Query{float4 normal;float4 light;float4 ambient;float4 sun;float4 fillDirection1;float4 fillColour1;float4 fillDirection2;float4 fillColour2;};\n"
+ "cbuffer QueriesBlock:register(b0){float4 Meta;Query Queries["+std::to_string(batchQueries)+"];};\n"+
+ reference+HlslSource()+foam.substr(0,end)+
+ "float3 productionIrradiance(Query q){float3 normal=q.normal.xyz,light=q.light.xyz;"
+ "float4 HullParameters=float4(0,q.ambient.xyz),SunColour=q.sun;float sunVisible=q.light.w;"
+ "float4 FoamFillLights[4]={float4(q.fillDirection1.xyz,1),q.fillColour1,q.fillDirection2,q.fillColour2};"
+ "float vesselFoam=q.fillDirection1.w,offshore=q.normal.w,daylight=q.sun.w;"+
+ production.substr(callStart,callEnd-callStart)+"return vesselIrradiance;}\n"+R"HLSL(
+struct Result{float4 radiance:SV_Target0;float4 ray:SV_Target1;};
+Result main(float4 pixel:SV_Position) {
+ Result result;
+ if(Meta.z<1.5) {
+ uint id=(uint)pixel.x+(uint)pixel.y*(uint)Meta.x;float u=(float(id)+0.5)/Meta.w;
+ float phase=float(id)*2.399963229728653;float3 ray;
+ if(Meta.z<0.5) {float z=1.0-2.0*u,r=sqrt(max(0.0,1.0-z*z));ray=float3(r*cos(phase),r*sin(phase),z);}
+ else {
+ float3 n=normalize(Queries[0].normal.xyz);
+ float3 tangent=normalize(cross(n,abs(n.z)<0.9?float3(0,0,1):float3(1,0,0))),bitangent=cross(n,tangent);
+ float radius=sqrt(u);ray=tangent*(radius*cos(phase))+bitangent*(radius*sin(phase))+n*sqrt(1.0-u);
+ }
+ result.radiance=float4(originalSky(ray),1);result.ray=float4(ray,1);return result;
+ }
+ Query q=Queries[min((uint)pixel.x,(uint)Meta.w-1)];
+ float3 sky=waterFoamSkyIrradiance(q.normal.xyz,q.light.xyz,q.sun.w);
+ float3 authored=waterFoamIrradiance(q.normal.xyz,q.light.xyz,q.ambient.xyz,q.sun.xyz,q.light.w,
+ q.fillDirection1.xyz,q.fillColour1.xyz,q.fillDirection2.xyz,q.fillColour2.xyz);
+ float3 replaced=waterFoamReplaceAmbient(authored,q.ambient.xyz,sky,q.normal.w);
+ result.radiance=float4(sky,all(replaced==authored)?1.0:0.0);
+ result.ray=float4(productionIrradiance(q),1);return result;
+}
+)HLSL";
+ CHECK(SDL3_Shader_Retarget(ps,false));
+ const char *vs="float4 main(uint id:SV_VertexID):SV_Position{return float4(id==1?3.0:-1.0,id==2?3.0:-1.0,0,1);}";
+ struct Resources {
+ SDL_GPUDevice *device;SDL_GPUShader *vs=NULL,*ps=NULL;SDL_GPUGraphicsPipeline *pipeline=NULL;SDL_GPUTexture *targets[2]={};
+ ~Resources(){for(auto *t:targets)if(t)SDL_ReleaseGPUTexture(device,t);if(pipeline)SDL_ReleaseGPUGraphicsPipeline(device,pipeline);
+ if(vs)SDL_ReleaseGPUShader(device,vs);if(ps)SDL_ReleaseGPUShader(device,ps);}
+ } resources;resources.device=frame->Device();std::string error;std::vector<unsigned char> spirv;
+ bool compiled=SDL3_Compile_HLSL_To_SPIRV(vs,true,spirv,error);CHECK(compiled);if(!compiled)return;
+ resources.vs=SDL3_Create_Shader(resources.device,spirv,true,error);CHECK(resources.vs);if(!resources.vs)return;
+ compiled=SDL3_Compile_HLSL_To_SPIRV(ps,false,spirv,error);CHECK(compiled);
+ if(!compiled){printf("foam environment PS: %s\n",error.c_str());return;}
+ unsigned samplers=0,buffers=0;SDL3_Shader_Slots(spirv,false,samplers,buffers);CHECK(samplers==0 && buffers==1);
+ if(samplers!=0 || buffers!=1)return;
+ resources.ps=SDL3_Create_Shader(resources.device,spirv,false,error);CHECK(resources.ps);if(!resources.ps)return;
+ SDL_GPUColorTargetDescription colour[2]={};colour[0].format=colour[1].format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
+ SDL_GPUGraphicsPipelineCreateInfo piInfo={};piInfo.vertex_shader=resources.vs;piInfo.fragment_shader=resources.ps;
+ piInfo.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;piInfo.target_info.color_target_descriptions=colour;piInfo.target_info.num_color_targets=2;
+ resources.pipeline=SDL_CreateGPUGraphicsPipeline(resources.device,&piInfo);CHECK(resources.pipeline);if(!resources.pipeline)return;
+ SDL_GPUTextureCreateInfo ti={};ti.type=SDL_GPU_TEXTURETYPE_2D;ti.format=colour[0].format;ti.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;
+ ti.width=ti.height=256;ti.layer_count_or_depth=ti.num_levels=1;
+ for(auto &target:resources.targets){target=SDL_CreateGPUTexture(resources.device,&ti);CHECK(target);if(!target)return;}
+ auto render=[&](unsigned width,unsigned height,float mode,unsigned query=0) {
+ const bool queryMode=mode>=1.5f;
+ const unsigned batches=queryMode?(count+batchQueries-1)/batchQueries:1;
+ std::vector<float> combined(queryMode?count*8:0);
+ for(unsigned batch=0;batch<batches;++batch) {
+ const unsigned first=queryMode?batch*batchQueries:query;
+ const unsigned localCount=queryMode?(std::min)(batchQueries,count-first):1;
+ const unsigned localWidth=queryMode?localCount:width,localHeight=queryMode?1:height;
+ std::vector<unsigned char> constants(16+batchQueries*sizeof(Query));
+ const float meta[4]={float(localWidth),float(localHeight),mode,float(queryMode?localCount:width*height)};
+ memcpy(constants.data(),meta,16);memcpy(constants.data()+16,queries.data()+first,localCount*sizeof(Query));
+ CHECK(frame->Flush());SDL_GPUCommandBuffer *commands=SDL_AcquireGPUCommandBuffer(resources.device);CHECK(commands);if(!commands)return std::vector<float>();
+ SDL_GPUColorTargetInfo targets[2]={};for(unsigned i=0;i<2;++i){targets[i].texture=resources.targets[i];targets[i].load_op=SDL_GPU_LOADOP_DONT_CARE;targets[i].store_op=SDL_GPU_STOREOP_STORE;}
+ SDL_GPURenderPass *pass=SDL_BeginGPURenderPass(commands,targets,2,NULL);CHECK(pass);if(!pass){SDL_CancelGPUCommandBuffer(commands);return std::vector<float>();}
+ SDL_BindGPUGraphicsPipeline(pass,resources.pipeline);SDL_GPUViewport viewport={0,0,float(localWidth),float(localHeight),0,1};SDL_SetGPUViewport(pass,&viewport);
+ SDL_PushGPUFragmentUniformData(commands,0,constants.data(),unsigned(constants.size()));SDL_DrawGPUPrimitives(pass,3,1,0,0);SDL_EndGPURenderPass(pass);
+ CHECK(SDL_SubmitGPUCommandBuffer(commands));const auto result=read_float_targets(frame,resources.targets,2,localWidth,localHeight);
+ if(!queryMode)return result;
+ CHECK(result.size()==localCount*8);if(result.size()!=localCount*8)return std::vector<float>();
+ for(unsigned target=0;target<2;++target)std::copy(result.begin()+target*localCount*4,result.begin()+(target+1)*localCount*4,
+ combined.begin()+target*count*4+first*4);
+ }
+ return combined;
+ };
+ const auto fine=render(256,256,0),coarse=render(128,128,0),values=render(count,1,2);
+ CHECK(fine.size()==65536*8 && coarse.size()==16384*8 && values.size()==count*8);
+ if(fine.size()!=65536*8 || coarse.size()!=16384*8 || values.size()!=count*8)return;
+ auto component=[](RGB rgb,unsigned c){return c==0?rgb.r:c==1?rgb.g:rgb.b;};
+ auto integrate=[&](const std::vector<float>&samples,const Query &query) {
+ const unsigned n=unsigned(samples.size()/8);RGB out={};double sum[3]={};
+ for(unsigned i=0;i<n;++i) {
+ const float *ray=&samples[n*4+i*4];const double cosine=(std::max)(0.0,double(query.normal[0])*ray[0]+double(query.normal[1])*ray[1]+double(query.normal[2])*ray[2]);
+ for(unsigned c=0;c<3;++c)sum[c]+=samples[i*4+c]*cosine;
+ }
+ out.r=sum[0]*4/n;out.g=sum[1]*4/n;out.b=sum[2]*4/n;return out;
+ };
+ double maxReferenceError=0,maxConvergence=0,maxCpuGpu=0,maxRotation=0,maxAmbient=0,maxCosineConvergence=0;
+ for(unsigned index=0;index<canonicalCount;++index) {
+ const RGB a=integrate(fine,queries[index]),b=integrate(coarse,queries[index]);
+ for(unsigned c=0;c<3;++c) {
+ const double v=values[index*4+c],expected=component(a,c),convergence=std::abs(expected-component(b,c));
+ maxReferenceError=(std::max)(maxReferenceError,std::abs(v-expected));maxConvergence=(std::max)(maxConvergence,convergence);
+ if(std::abs(v-expected)>=.006 || convergence>=.003)printf("sky integral: normal %u channel %u GPU %.8g reference %.8g coarse %.8g\n",index,c,v,expected,component(b,c));
+ CHECK(std::abs(v-expected)<.006 && convergence<.003);
+ }
+ }
+ for(unsigned index:{0u,13u,16u,25u,43u}) {
+ const auto cosine=render(256,128,1,index);CHECK(cosine.size()==32768*8);if(cosine.size()!=32768*8)return;
+ const RGB reference=integrate(fine,queries[index]);
+ for(unsigned c=0;c<3;++c) {
+ double sum=0;for(unsigned i=0;i<32768;++i)sum+=cosine[i*4+c];const double difference=std::abs(sum/32768-component(reference,c));
+ maxCosineConvergence=(std::max)(maxCosineConvergence,difference);CHECK(difference<.003);
+ }
+ }
+ for(unsigned row=0;row<count;++row) {
+ const Query &f=queries[row];const RGB cpu=Evaluate({f.normal[0],f.normal[1],f.normal[2]},{f.light[0],f.light[1],f.light[2]},f.sun[3]);
+ double sunDot=0,fill1=0,fill2=0;for(unsigned c=0;c<3;++c){sunDot+=double(f.normal[c])*f.light[c];fill1+=double(f.normal[c])*f.fillDirection1[c];fill2+=double(f.normal[c])*f.fillDirection2[c];}
+ for(unsigned c=0;c<3;++c) {
+ const double sky=values[row*4+c],value=values[count*4+row*4+c];
+ maxCpuGpu=(std::max)(maxCpuGpu,std::abs(sky-component(cpu,c)));
+ CHECK(std::isfinite(sky) && sky>=0 && std::abs(sky-component(cpu,c))<.00001);
+ const double authored=std::pow((std::max)(0.0,double(f.ambient[c])+f.sun[c]*(std::max)(0.0,sunDot)*f.light[3]+
+ f.fillColour1[c]*(std::max)(0.0,fill1)+f.fillColour2[c]*(std::max)(0.0,fill2)),2.2);
+ const double expected=authored+(sky-std::pow((std::max)(0.0,double(f.ambient[c])),2.2))*(f.fillDirection1[3]>0?f.normal[3]:0);
+ maxAmbient=(std::max)(maxAmbient,std::abs(value-expected));CHECK(std::isfinite(value) && value>=0 && std::abs(value-expected)<.00003);
+ if(f.normal[3]==0)CHECK(values[row*4+3]==1); // exact production early return, including HDR authored lighting
+ }
+ }
+ for(unsigned i=0;i<rotationSource.size();++i)for(unsigned c=0;c<3;++c) {
+ const double difference=std::abs(values[(canonicalCount+i)*4+c]-values[rotationSource[i]*4+c]);
+ maxRotation=(std::max)(maxRotation,difference);CHECK(difference<.00002);
+ }
+ for(unsigned c=0;c<3;++c) {
+ CHECK(std::abs(values[night*4+c]-.06*values[day*4+c])<.000002);
+ CHECK(values[hdr*4+c]==values[day*4+c]); // daylight is the existing bounded weather factor; HDR radiance is tested below
+ CHECK(values[count*4+hdrAuthored*4+c]>1); // HDR light energy remains unclamped
+ CHECK(values[count*4+noVessel*4+c]==values[count*4+lightingBegin*4+c]); // same authored lights, new material guard bypassed
+ CHECK(std::abs(values[count*4+noVessel*4+c]-values[count*4+(lightingBegin+6)*4+c])>.001); // armed ambient replacement control
+ for(unsigned shore=0;shore<3;++shore) {
+ const unsigned first=lightingBegin+shore*3,last=first+2;
+ const double a=values[count*4+first*4+c],b=values[count*4+last*4+c];
+ const double oldA=values[count*4+lightingBegin*4+c],oldB=values[count*4+(lightingBegin+2)*4+c];
+ CHECK(std::abs((b-a)-(oldB-oldA))<.000003); // shadow delta is preserved, never applied to ambient/fill sky
+ }
+ }
+ CHECK(&CachedTable()==&CachedTable());
+ const Table dark=Build([](Vector){return RGB{0,0,0};});
+ const Table unit=Build([](Vector){return RGB{1,1,1};});
+ const Table coloured=Build([](Vector){return RGB{2,4,8};});
+ double unitMaximum=0,unitMinimum=1;
+ for(const Query &f:queries) {
+ const Vector normal={f.normal[0],f.normal[1],f.normal[2]};const RGB d=Evaluate(dark,normal),u=Evaluate(unit,normal),h=Evaluate(coloured,normal);
+ CHECK(d.r==0 && d.g==0 && d.b==0);
+ unitMaximum=(std::max)(unitMaximum,u.r);unitMinimum=(std::min)(unitMinimum,u.r);
+ CHECK(u.r>=0 && u.r<=1.00001 && std::abs(u.r-u.g)<1e-12 && std::abs(u.r-u.b)<1e-12);
+ CHECK(h.r>=0 && h.r<=2.00002 && h.g<=4.00004 && h.b<=8.00008);
+ CHECK(std::abs(h.g-2*h.r)<1e-10 && std::abs(h.b-4*h.r)<1e-10); // no tint/clamp or per-channel gain
+ }
+ CHECK(std::abs(Evaluate(unit,{0,0,1}).r-1)<.00001 && std::abs(Evaluate(unit,{0,0,-1}).r-1)<.00001);
+ printf("sdl_gpu_frame_selfcheck: GPU foam sky: %u full-sphere/rotated/light queries; independent original-sky integral max %.7f, sphere/cosine convergence %.7f/%.7f, CPU/GPU %.7f, rigid rotation %.7f; ambient replacement %.7f, executed production callsite with exact zero-foam/offshore0/HDR and shadow increment, constant positive energy %.7f..%.7f checked\n",count,maxReferenceError,maxConvergence,maxCosineConvergence,maxCpuGpu,maxRotation,maxAmbient,unitMinimum,unitMaximum);
+}
+#endif // __linux__
+
+#if defined(__linux__)
+static void check_gpu_foam_material(SdlGpuFrame *frame)
+{
+ // Execute the actual material helpers and the emitted production integration block. A
+ // deliberately coloured mirror separates incident reflection, diffuse foam and transmitted
+ // clear water; double precision bilinear integration is independent of the shader filter.
+ struct Query {float uv[4],mapping[4],sky[4],diffuse[4],incident[4],clear[4],crest[4],material[4];};
+ const Query base={{8.5f/32,8.5f/32,0,0},{.1408f,.1408f,.55f,1},{.03f,.08f,.17f,0},
+ {.3f,.12f,.6f,0},{.02f,1.4f,.7f,0},{.07f,.5f,.21f,0},{.6f,.35f,.15f,0},{.025f,.6f,.5f,.5f}};
+ std::vector<Query> queries;
+ auto add=[&](Query q){queries.push_back(q);return unsigned(queries.size()-1);};
+ const unsigned constant=add(base);
+ Query q=base;q.uv[0]=20.5f/32;q.uv[1]=5.5f/32;const unsigned empty=add(q);
+ q=base;q.mapping[3]=0;const unsigned disabled=add(q);
+ q=base;q.mapping[3]=.5f;add(q);
+ q=base;q.uv[0]=-.5f;const unsigned outside=add(q);
+ q=base;q.uv[0]=0;add(q);
+ q=base;q.uv[0]=.5f/32;add(q); // partial border and coloured edge texels
+ q=base;q.uv[0]=1.5f;add(q);
+ q=base;q.mapping[1]*=.5f;add(q); // same footprint in both dimensions of a non-square reflection
+ q=base;q.uv[0]=23.25f/32;q.uv[1]=23.75f/32;const unsigned mixed=add(q);
+ q.uv[2]=.25f/32;q.uv[3]=-.5f/32;add(q); // distortion stays in the reflection's coordinate system
+ q=base;q.uv[0]=q.uv[1]=16.5f/32;const unsigned feature=add(q);
+ q.uv[0]-=1.0f/32;const unsigned featureLeft=add(q);
+ q.uv[0]+=2.0f/32;const unsigned featureRight=add(q);
+ q.uv[0]-=1.0f/32;q.uv[1]-=1.0f/32;const unsigned featureDown=add(q);
+ q.uv[1]+=2.0f/32;const unsigned featureUp=add(q);
+ q.uv[0]=18.5f/32;q.uv[1]=16.5f/32;const unsigned featureFar=add(q);
+ q=base;q.material[0]=0;const unsigned noFresnel=add(q);
+ q=base;q.material[1]=0;const unsigned tangent=add(q);
+ q=base;q.material[1]=-.2f;add(q);
+ q=base;q.material[0]=q.material[1]=1;const unsigned fullReflection=add(q);
+ q=base;for(unsigned c=0;c<3;++c)q.diffuse[c]=q.incident[c]=0;const unsigned dark=add(q);
+ q=base;for(unsigned c=0;c<3;++c){q.diffuse[c]=2.0f+c*1.7f;q.incident[c]=4.0f+c*2;}const unsigned hdr=add(q);
+ q=base;q.mapping[2]=1;q.mapping[0]=q.mapping[1]=.256f;add(q);
+ q=base;q.mapping[2]=0;add(q);
+ q=base;q.diffuse[0]=.3f;q.diffuse[1]=q.diffuse[2]=0;
+ q.incident[0]=q.incident[1]=0;q.incident[2]=.9f;
+ q.clear[0]=q.clear[2]=0;q.clear[1]=.5f;
+ q.material[0]=.2f;const float k=q.mapping[2]*q.mapping[2]*.5f;q.material[1]=k/(1+k);
+ q.material[2]=q.material[3]=1;const unsigned singleFresnel=add(q);
+ q.material[2]=q.material[3]=.4f;const unsigned partial=add(q);
+ q=base;q.material[2]=q.material[3]=0;const unsigned clear=add(q);
+ q.material[2]=.7f;const unsigned crestOnly=add(q);
+ q.incident[0]=7;q.incident[1]=11;q.incident[2]=19;q.mapping[3]=0;q.material[0]=1;
+ const unsigned changedUnusedMaterial=add(q);
+ const unsigned rows=unsigned(queries.size()),columns=5,side=32;
+ std::vector<uint32_t> texels(side*side,0);
+ for(unsigned y=0;y<side;++y)for(unsigned x=0;x<side;++x) {
+ if(x<2)texels[y*side+x]=0xFF20C060;
+ if(x>=4 && x<=11 && y>=4 && y<=11)texels[y*side+x]=0xFF4080C0;
+ if(x>=21 && x<=26 && y>=21 && y<=26)texels[y*side+x]=(x+y)%2?0xFFC02060:0xFF1090E0;
+ }
+ texels[16*side+16]=0xFFE06020;
+ PixelPipelineDescription pd={};std::string production;
+ CHECK(EngineShader_Pixel_Program(ENGINE_SHADER_WATER_TRAPEZOID,pd,production,COMBINER_SHADER_TARGET_SDL3_GPU));
+ const size_t lightingStart=production.find("float3 waterLinear("),lightingEnd=production.find("float terrainHeight("),
+ integrationStart=production.find("float3 vesselRadiance=vesselDiffuse;"),integrationEnd=production.find("float4 current;",integrationStart);
+ CHECK(lightingStart!=std::string::npos && lightingEnd>lightingStart && integrationStart!=std::string::npos && integrationEnd>integrationStart);
+ if(lightingStart==std::string::npos || lightingEnd<=lightingStart || integrationStart==std::string::npos || integrationEnd<=integrationStart)return;
+ std::string ps="Texture2D Texture1:register(t1);SamplerState Sampler1:register(s1);\n"
+ "struct Query{float4 uv;float4 mapping;float4 sky;float4 diffuse;float4 incident;float4 clear;float4 crest;float4 material;};\n"
+ "cbuffer QueriesBlock:register(b0){Query Queries["+std::to_string(rows)+"];};\n"+
+ production.substr(lightingStart,lightingEnd-lightingStart)+WaterFoamShading::MaterialSource()+
+ "float3 productionLayer(Query q){float3 vesselDiffuse=q.diffuse.rgb,surface=q.clear.rgb;"
+ "float vesselFoam=q.material.w,foam=q.material.z,environmentRoughness=q.mapping.z;"
+ "float3 sky=pow(q.sky.rgb,1.0/2.2),reflectedRay=float3(0,0,1),light=float3(0,0,1);"
+ "float offshore=0,daylight=1,baseLevel=0;float4 WaterParameters=float4(0,0,q.mapping.w,0);"
+ "float2 reflectionUV=q.uv.xy,distortion=q.uv.zw,reflectionScale=q.mapping.xy;"
+ "float environmentFresnel=q.material.x,oceanViewCosine=q.material.y,foamDiffuse=1;"
+ "float3 foamAlbedo=pow(q.crest.rgb,1.0/2.2),vesselIrradiance=float3(0,0,0);float shoreMaterialWeight=0;"+
+ production.substr(integrationStart,integrationEnd-integrationStart)+"return surface;}\n"
+ "float4 main(float4 pixel:SV_Position):SV_Target0{Query q=Queries[(uint)pixel.y];uint col=(uint)pixel.x;"
+ "if(col==0)return float4(waterFoamPlanarReflection(q.sky.rgb,q.uv.xy,q.uv.zw,q.mapping.xy,q.mapping.z,q.mapping.w),1);"
+ "float3 material=waterFoamRoughMaterial(q.diffuse.rgb,q.incident.rgb,q.material.x,q.material.y,q.mapping.z);"
+ "if(col==1)return float4(material,1);"
+ "if(col==2)return float4(waterFoamLayer(q.clear.rgb,q.crest.rgb,material,q.material.z,q.material.w),1);"
+ "if(col==3){float share=saturate(q.material.w/max(q.material.z,.0001));"
+ "float3 crest=waterLinear(pow(q.crest.rgb,1.0/2.2));"
+ "return float4(waterDisplay(lerp(q.clear.rgb,lerp(crest,q.diffuse.rgb,share),"
+ "saturate(max(q.material.z*.88,q.material.w)))),1);}"
+ "return float4(productionLayer(q),1);}";
+ CHECK(SDL3_Shader_Retarget(ps,false));
+ const char *vs="float4 main(uint id:SV_VertexID):SV_Position{return float4(id==1?3.0:-1.0,id==2?3.0:-1.0,0,1);}";
+ struct Resources {
+ SDL_GPUDevice *device;SDL_GPUShader *vs=NULL,*ps=NULL;SDL_GPUGraphicsPipeline *pipeline=NULL;
+ SDL_GPUTexture *target=NULL;SDL_GPUSampler *sampler=NULL;PosixTexture9 *mirror=NULL;
+ ~Resources(){if(mirror)mirror->Release();if(target)SDL_ReleaseGPUTexture(device,target);if(sampler)SDL_ReleaseGPUSampler(device,sampler);
+ if(pipeline)SDL_ReleaseGPUGraphicsPipeline(device,pipeline);if(vs)SDL_ReleaseGPUShader(device,vs);if(ps)SDL_ReleaseGPUShader(device,ps);}
+ } resources;resources.device=frame->Device();std::vector<unsigned char> spirv;std::string error;
+ bool compiled=SDL3_Compile_HLSL_To_SPIRV(vs,true,spirv,error);CHECK(compiled);if(!compiled)return;
+ resources.vs=SDL3_Create_Shader(resources.device,spirv,true,error);CHECK(resources.vs);if(!resources.vs)return;
+ compiled=SDL3_Compile_HLSL_To_SPIRV(ps,false,spirv,error);CHECK(compiled);
+ if(!compiled){printf("foam material PS: %s\n",error.c_str());return;}
+ unsigned samplers=0,buffers=0;SDL3_Shader_Slots(spirv,false,samplers,buffers);CHECK(samplers==2 && buffers==1);
+ if(samplers!=2 || buffers!=1)return;
+ resources.ps=SDL3_Create_Shader(resources.device,spirv,false,error);CHECK(resources.ps);if(!resources.ps)return;
+ SDL_GPUColorTargetDescription colour={};colour.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
+ SDL_GPUGraphicsPipelineCreateInfo pi={};pi.vertex_shader=resources.vs;pi.fragment_shader=resources.ps;
+ pi.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;pi.target_info.color_target_descriptions=&colour;pi.target_info.num_color_targets=1;
+ resources.pipeline=SDL_CreateGPUGraphicsPipeline(resources.device,&pi);CHECK(resources.pipeline);if(!resources.pipeline)return;
+ SDL_GPUTextureCreateInfo ti={};ti.type=SDL_GPU_TEXTURETYPE_2D;ti.format=colour.format;ti.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;
+ ti.width=columns;ti.height=rows;ti.layer_count_or_depth=ti.num_levels=1;
+ resources.target=SDL_CreateGPUTexture(resources.device,&ti);CHECK(resources.target);if(!resources.target)return;
+ SDL_GPUSamplerCreateInfo si={};si.min_filter=si.mag_filter=SDL_GPU_FILTER_LINEAR;
+ si.address_mode_u=si.address_mode_v=si.address_mode_w=SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
+ resources.sampler=SDL_CreateGPUSampler(resources.device,&si);CHECK(resources.sampler);if(!resources.sampler)return;
+ resources.mirror=PosixTexture9::create(side,side,2,0,D3DFMT_A8R8G8B8,D3DPOOL_MANAGED);CHECK(resources.mirror);if(!resources.mirror)return;
+ for(unsigned level=0;level<2;++level) {
+ D3DLOCKED_RECT lock={};CHECK(resources.mirror->LockRect(level,&lock,NULL,0)==D3D_OK);if(!lock.pBits)return;
+ for(unsigned y=0;y<(side>>level);++y)for(unsigned x=0;x<(side>>level);++x)
+ ((uint32_t *)((uint8_t *)lock.pBits+y*lock.Pitch))[x]=level?0xFFFF00FF:texels[y*side+x];
+ CHECK(resources.mirror->UnlockRect(level)==D3D_OK);
+ }
+ CHECK(frame->Flush());SdlResourceMirrors mirrors(frame);std::string refusal;
+ SDL_GPUTexture *mirror=mirrors.Texture(resources.mirror,refusal),*white=mirrors.White();CHECK(mirror && white);if(!mirror || !white)return;
+ CHECK(frame->Flush());SDL_GPUCommandBuffer *commands=SDL_AcquireGPUCommandBuffer(resources.device);CHECK(commands);if(!commands)return;
+ SDL_GPUColorTargetInfo attachment={};attachment.texture=resources.target;attachment.load_op=SDL_GPU_LOADOP_DONT_CARE;attachment.store_op=SDL_GPU_STOREOP_STORE;
+ SDL_GPURenderPass *pass=SDL_BeginGPURenderPass(commands,&attachment,1,NULL);CHECK(pass);
+ if(!pass){SDL_CancelGPUCommandBuffer(commands);return;}
+ SDL_BindGPUGraphicsPipeline(pass,resources.pipeline);SDL_GPUTextureSamplerBinding bindings[2]={{white,resources.sampler},{mirror,resources.sampler}};
+ SDL_BindGPUFragmentSamplers(pass,0,bindings,2);SDL_PushGPUFragmentUniformData(commands,0,queries.data(),unsigned(queries.size()*sizeof(Query)));
+ SDL_DrawGPUPrimitives(pass,3,1,0,0);SDL_EndGPURenderPass(pass);CHECK(SDL_SubmitGPUCommandBuffer(commands));
+ const auto values=read_float_targets(frame,&resources.target,1,columns,rows);CHECK(values.size()==rows*columns*4);if(values.size()!=rows*columns*4)return;
+ auto sat=[](double v){return (std::max)(0.0,(std::min)(1.0,v));};
+ auto sample=[&](double u,double v,unsigned channel) {
+ const double px=sat(u)*side-.5,py=sat(v)*side-.5;const int ix=int(std::floor(px)),iy=int(std::floor(py));
+ const double fx=px-ix,fy=py-iy;double value=0;
+ for(int dy=0;dy<2;++dy)for(int dx=0;dx<2;++dx) {
+ const unsigned x=unsigned((std::max)(0,(std::min)(int(side)-1,ix+dx))),y=unsigned((std::max)(0,(std::min)(int(side)-1,iy+dy)));
+ value+=double((texels[y*side+x]>>(16-channel*8))&255)/255*(dx?fx:1-fx)*(dy?fy:1-fy);
+ }
+ return value;
+ };
+ auto planar=[&](const Query &f,double roughness,double *out,double *wrongDecode) {
+ const double offset[5][2]={{0,0},{1,0},{-1,0},{0,1},{0,-1}},weight[5]={.4,.15,.15,.15,.15};
+ double averagedDisplay[3]={};bool allCovered=true;for(unsigned c=0;c<3;++c)out[c]=0;
+ for(unsigned tap=0;tap<5;++tap) {
+ const double u=f.uv[0]+f.uv[2]+offset[tap][0]*sat(roughness)*.008/(std::max)(double(f.mapping[0]),.001),
+ v=f.uv[1]+f.uv[3]+offset[tap][1]*sat(roughness)*.008/(std::max)(double(f.mapping[1]),.001);
+ double rgb[3]={sample(u,v,0),sample(u,v,1),sample(u,v,2)};
+ const double border=(std::min)((std::min)(u,1-u),(std::min)(v,1-v));
+ const double coverage=sat(f.mapping[3])*sat(border*30)*sat((std::max)(rgb[0],(std::max)(rgb[1],rgb[2]))*64);
+ allCovered &= coverage>.999999;
+ for(unsigned c=0;c<3;++c){out[c]+=weight[tap]*(f.sky[c]*(1-coverage)+std::pow(rgb[c],2.2)*coverage);averagedDisplay[c]+=weight[tap]*rgb[c];}
+ }
+ if(wrongDecode)for(unsigned c=0;c<3;++c)wrongDecode[c]=allCovered?std::pow(averagedDisplay[c],2.2):out[c];
+ };
+ auto reflectance=[&](const Query &f,double roughness){const double mu=sat(f.material[1]),r=sat(roughness),k=r*r*.5;
+ return sat(f.material[0])*mu/(std::max)(mu*(1-k)+k,.0001);};
+ auto at=[&](unsigned row,unsigned column,unsigned channel){return double(values[(row*columns+column)*4+channel]);};
+ double filterError=0,materialError=0,layerError=0,productionError=0,decodeControl=0;
+ for(unsigned row=0;row<rows;++row) {
+ const Query &f=queries[row];double reflected[3],wideReflected[3],wrongDecode[3];planar(f,f.mapping[2],reflected,wrongDecode);
+ const double wideRoughness=(std::max)(double(f.mapping[2]),.55);planar(f,wideRoughness,wideReflected,NULL);
+ const double factor=reflectance(f,f.mapping[2]),wideFactor=reflectance(f,wideRoughness),
+ share=sat(f.material[3]/(std::max)(double(f.material[2]),.0001)),coverage=sat((std::max)(f.material[2]*.88,double(f.material[3])));
+ for(unsigned c=0;c<3;++c) {
+ const double material=f.diffuse[c]*(1-factor)+f.incident[c]*factor;
+ const double layer=f.clear[c]*(1-coverage)+(f.crest[c]*(1-share)+material*share)*coverage;
+ const double integratedMaterial=f.material[3]>0?f.diffuse[c]*(1-wideFactor)+wideReflected[c]*wideFactor:f.diffuse[c];
+ const double integrated=f.clear[c]*(1-coverage)+(f.crest[c]*(1-share)+integratedMaterial*share)*coverage;
+ filterError=(std::max)(filterError,std::abs(at(row,0,c)-reflected[c]));
+ materialError=(std::max)(materialError,std::abs(at(row,1,c)-material));
+ layerError=(std::max)(layerError,std::abs(at(row,2,c)-layer));
+ productionError=(std::max)(productionError,std::abs(at(row,4,c)-std::pow(sat(integrated),1/2.2)));
+ CHECK(std::abs(at(row,0,c)-reflected[c])<.00002 && std::abs(at(row,1,c)-material)<.00001);
+ CHECK(std::abs(at(row,2,c)-layer)<.00001 && std::abs(at(row,4,c)-std::pow(sat(integrated),1/2.2))<.00002);
+ CHECK(at(row,1,c)>=(std::min)(double(f.diffuse[c]),double(f.incident[c]))-.00001
+ && at(row,1,c)<=(std::max)(double(f.diffuse[c]),double(f.incident[c]))+.00001);
+ for(unsigned col=0;col<columns;++col)CHECK(std::isfinite(at(row,col,c)) && at(row,col,c)>=0);
+ if(row==mixed)decodeControl=(std::max)(decodeControl,std::abs(at(row,0,c)-wrongDecode[c]));
+ if(f.material[3]==0)CHECK(at(row,4,c)==at(row,3,c)); // actual emitted engine block, not a fixture-only composition
+ }
+ }
+ for(unsigned c=0;c<3;++c) {
+ const double constantRadiance=std::pow(double((texels[8*side+8]>>(16-c*8))&255)/255,2.2);
+ CHECK(std::abs(at(constant,0,c)-constantRadiance)<.00001);
+ CHECK(std::abs(at(empty,0,c)-base.sky[c])<.000001 && std::abs(at(disabled,0,c)-base.sky[c])<.000001 && std::abs(at(outside,0,c)-base.sky[c])<.000001);
+ CHECK(at(noFresnel,1,c)==base.diffuse[c] && at(tangent,1,c)==base.diffuse[c]);
+ CHECK(std::abs(at(fullReflection,1,c)-base.incident[c])<.000001 && at(dark,1,c)==0 && at(hdr,1,c)>1);
+ CHECK(at(clear,4,c)==at(clear,3,c) && at(crestOnly,4,c)==at(changedUnusedMaterial,4,c));
+ }
+ const double sharpRed=std::pow(224.0/255,2.2);
+ CHECK(at(feature,0,0)<sharpRed-.1 && at(feature,0,0)>base.sky[0]+.1);
+ for(unsigned row:{featureLeft,featureRight,featureDown,featureUp})CHECK(at(row,0,0)>base.sky[0]+.05);
+ CHECK(std::abs(at(featureFar,0,0)-base.sky[0])<.000001 && decodeControl>.001);
+ CHECK(std::abs(at(singleFresnel,1,0)-.27)<.000001 && at(singleFresnel,1,1)==0 && std::abs(at(singleFresnel,1,2)-.09)<.000001);
+ CHECK(std::abs(at(singleFresnel,1,2)-.018)>.07); // armed double-Fresnel control
+ CHECK(std::abs(at(partial,2,0)-.108)<.000001 && std::abs(at(partial,2,1)-.3)<.000001 && std::abs(at(partial,2,2)-.036)<.000001);
+ resources.mirror->Release();resources.mirror=NULL;mirrors.Collect_Dead();CHECK(frame->Flush());
+ printf("sdl_gpu_frame_selfcheck: GPU rough foam material: %u fixtures, independent filter/material/layer/production errors %.8f/%.8f/%.8f/%.8f; mip-zero coloured planar filtering, isotropic broadening, sky/border/level guards, single-Fresnel/HDR/convex energy, exact clear/crest invariance and decode-before-filter control %.8f checked\n",rows,filterError,materialError,layerError,productionError,decodeControl);
+}
+#endif // __linux__
+
+#if defined(__linux__)
+static void check_gpu_coastal_material(SdlGpuFrame *frame)
+{
+ // Execute the actual emitted material block. Independent double-precision weights and
+ // authored-light arithmetic check the layer, including its display/visibility composition.
+ struct Query {float normal[4],light[4],ambient[4],sun[4],fillDirection1[4],fillColour1[4],
+ fillDirection2[4],fillColour2[4],clear[4],foam[4],material[4],sky[4],edge[4],fog[4];};
+ static_assert(sizeof(Query)==224,"Coastal queries follow fourteen HLSL float4 registers");
+ const Query base={{0,0,1,0},{0,.8910065f,.4539905f,1},{.5019608f,.4f,.3019608f,0},
+ {.3882353f,.2745098f,.0862745f,.3882353f},{.384577f,-.863774f,.325568f,0},{.235294f,.196078f,.196078f,0},
+ {.801845f,.276097f,.529919f,0},{.235294f,.196078f,.196078f,0},
+ {.12f,.10f,.06f,.65f},{.5f,0,0,0},{.025f,.8f,.35f,0},{.08f,.12f,.17f,0},
+ {.9f,.8f,.7f,.7f},{.11f,.15f,.19f,0}};
+ std::vector<Query> queries;
+ auto add=[&](Query q){queries.push_back(q);return unsigned(queries.size()-1);};
+ Query q=base;q.foam[0]=q.foam[1]=0;const unsigned clear=add(q);
+ q=base;q.foam[0]=q.foam[1]=.7f;const unsigned crest=add(q);
+ q=base;q.foam[0]=q.foam[1]=q.foam[2]=.6f;const unsigned vessel=add(q);
+ const unsigned partial=add(base);
+ q=base;q.foam[0]=1.0f/.88f;const unsigned full=add(q);
+ q=base;q.foam[0]=q.foam[1]=.8f;const unsigned hiddenCrest=add(q);
+ q=base;q.foam[0]=q.foam[1]=q.foam[2]=.8f;const unsigned hiddenVessel=add(q);
+ q=base;q.foam[0]=.9f;q.foam[1]=.4f;q.foam[2]=.3f;const unsigned mixed=add(q);
+ q=base;q.light[3]=0;const unsigned shadow=add(q);
+ q=base;for(unsigned c=0;c<3;++c)q.fillColour1[c]=q.fillColour2[c]=0;const unsigned noFill=add(q);
+ q=base;for(unsigned c=0;c<3;++c)q.ambient[c]=q.sun[c]=q.fillColour1[c]=q.fillColour2[c]=q.sky[c]=0;
+ const unsigned dark=add(q);
+ q=base;q.material[1]=0;const unsigned tangent=add(q);
+ q=base;q.edge[3]=0;const unsigned fogged=add(q);
+ q=base;for(unsigned c=0;c<3;++c)q.edge[c]=0;const unsigned shrouded=add(q);
+ q=base;q.clear[3]=0;const unsigned transparent=add(q);
+ q=base;for(unsigned c=0;c<3;++c){q.ambient[c]=1+c;q.sun[c]=4-c;}const unsigned hdr=add(q);
+ const unsigned rows=unsigned(queries.size()),columns=4;
+ CHECK(rows==16 && rows*sizeof(Query)<=4096);
+ PixelPipelineDescription pd={};std::string production;
+ CHECK(EngineShader_Pixel_Program(ENGINE_SHADER_WATER_TRAPEZOID,pd,production,COMBINER_SHADER_TARGET_SDL3_GPU));
+ const size_t lightStart=production.find("float3 waterLinear("),lightEnd=production.find("float terrainHeight("),
+ start=production.find("float3 vesselRadiance=vesselDiffuse;"),end=production.find("float4 current;",start);
+ CHECK(lightStart!=std::string::npos && lightEnd>lightStart && start!=std::string::npos && end>start);
+ if(lightStart==std::string::npos || lightEnd<=lightStart || start==std::string::npos || end<=start)return;
+ const std::string lighting=WaterFoamShading::Source();const size_t lightingEnd=lighting.find("// Cubic bilinear value noise");
+ CHECK(lightingEnd!=std::string::npos);if(lightingEnd==std::string::npos)return;
+ std::string ps="Texture2D Texture1:register(t1);SamplerState Sampler1:register(s1);\n"
+ "struct Query{float4 normal;float4 light;float4 ambient;float4 sun;float4 fillDirection1;float4 fillColour1;"
+ "float4 fillDirection2;float4 fillColour2;float4 clear;float4 foam;float4 material;float4 sky;float4 edge;float4 fog;};\n"
+ "cbuffer QueriesBlock:register(b0){Query Queries["+std::to_string(rows)+"];};\n"+
+ production.substr(lightStart,lightEnd-lightStart)+lighting.substr(0,lightingEnd)+WaterFoamShading::MaterialSource()+
+ "float3 productionCoast(Query q,bool applyCoast){float3 surface=q.clear.rgb,normal=q.normal.xyz,light=q.light.xyz;"
+ "float vesselFoam=q.foam.z,foam=q.foam.x,environmentRoughness=q.material.z,offshore=0,daylight=q.sun.w,baseLevel=0;"
+ "float shoreMaterialWeight=applyCoast?waterFoamCoastWeight(foam,q.foam.y,vesselFoam):0;"
+ "float3 foamAlbedo=float3(.67,.73,.71);float foamDiffuse=(.22+.78*saturate(dot(normal,light)))*(.12+.88*daylight);"
+ "float3 vesselIrradiance=waterFoamIrradiance(normal,light,q.ambient.rgb,q.sun.rgb,q.light.w,"
+ "q.fillDirection1.xyz,q.fillColour1.rgb,q.fillDirection2.xyz,q.fillColour2.rgb);"
+ "float3 vesselDiffuse=waterLinear(float3(.75,.80,.77))*vesselIrradiance;"
+ "float3 sky=pow(q.sky.rgb,1.0/2.2),reflectedRay=float3(0,0,1);float4 WaterParameters=float4(0,0,q.material.w,0);"
+ "float2 reflectionUV=float2(.5,.5),distortion=float2(0,0),reflectionScale=float2(1,1);"
+ "float environmentFresnel=q.material.x,oceanViewCosine=q.material.y;"+
+ production.substr(start,end-start)+"return surface;}\n"
+ "float4 main(float4 pixel:SV_Position):SV_Target0{Query q=Queries[(uint)pixel.y];uint col=(uint)pixel.x;"
+ "float3 result=productionCoast(q,true);if(col==0)return float4(result,1);"
+ "if(col==1)return float4(productionCoast(q,false),1);"
+ "if(col==2){float3 visible=lerp(q.fog.rgb,saturate(result)*q.edge.rgb,saturate(q.edge.w));"
+ "return float4(lerp(float3(.07,.11,.19),visible,q.clear.w),q.clear.w);}"
+ "float coverage=saturate(max(q.foam.x*.88,q.foam.z)),share=saturate(q.foam.z/max(q.foam.x,.0001));"
+ "return float4(waterFoamCoastWeight(q.foam.x,q.foam.y,q.foam.z),coverage,coverage*(1-share),1);}";
+ CHECK(SDL3_Shader_Retarget(ps,false));
+ const char *vs="float4 main(uint id:SV_VertexID):SV_Position{return float4(id==1?3.0:-1.0,id==2?3.0:-1.0,0,1);}";
+ struct Resources {
+ SDL_GPUDevice *device;SDL_GPUShader *vs=NULL,*ps=NULL;SDL_GPUGraphicsPipeline *pipeline=NULL;
+ SDL_GPUTexture *target=NULL;SDL_GPUSampler *sampler=NULL;
+ ~Resources(){if(target)SDL_ReleaseGPUTexture(device,target);if(sampler)SDL_ReleaseGPUSampler(device,sampler);
+ if(pipeline)SDL_ReleaseGPUGraphicsPipeline(device,pipeline);if(vs)SDL_ReleaseGPUShader(device,vs);if(ps)SDL_ReleaseGPUShader(device,ps);}
+ } r;r.device=frame->Device();std::vector<unsigned char> spirv;std::string error;
+ bool compiled=SDL3_Compile_HLSL_To_SPIRV(vs,true,spirv,error);CHECK(compiled);if(!compiled)return;
+ r.vs=SDL3_Create_Shader(r.device,spirv,true,error);CHECK(r.vs);if(!r.vs)return;
+ compiled=SDL3_Compile_HLSL_To_SPIRV(ps,false,spirv,error);CHECK(compiled);
+ if(!compiled){printf("coastal material PS: %s\n",error.c_str());return;}
+ unsigned samplers=0,buffers=0;SDL3_Shader_Slots(spirv,false,samplers,buffers);CHECK(samplers==2 && buffers==1);
+ if(samplers!=2 || buffers!=1)return;
+ r.ps=SDL3_Create_Shader(r.device,spirv,false,error);CHECK(r.ps);if(!r.ps)return;
+ SDL_GPUColorTargetDescription colour={};colour.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
+ SDL_GPUGraphicsPipelineCreateInfo pi={};pi.vertex_shader=r.vs;pi.fragment_shader=r.ps;
+ pi.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;pi.target_info.color_target_descriptions=&colour;pi.target_info.num_color_targets=1;
+ r.pipeline=SDL_CreateGPUGraphicsPipeline(r.device,&pi);CHECK(r.pipeline);if(!r.pipeline)return;
+ SDL_GPUTextureCreateInfo ti={};ti.type=SDL_GPU_TEXTURETYPE_2D;ti.format=colour.format;ti.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;
+ ti.width=columns;ti.height=rows;ti.layer_count_or_depth=ti.num_levels=1;
+ r.target=SDL_CreateGPUTexture(r.device,&ti);CHECK(r.target);if(!r.target)return;
+ SDL_GPUSamplerCreateInfo si={};si.min_filter=si.mag_filter=SDL_GPU_FILTER_LINEAR;
+ si.address_mode_u=si.address_mode_v=si.address_mode_w=SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
+ r.sampler=SDL_CreateGPUSampler(r.device,&si);CHECK(r.sampler);if(!r.sampler)return;
+ CHECK(frame->Flush());SdlResourceMirrors mirrors(frame);SDL_GPUTexture *white=mirrors.White();CHECK(white);if(!white)return;
+ CHECK(frame->Flush());SDL_GPUCommandBuffer *commands=SDL_AcquireGPUCommandBuffer(r.device);CHECK(commands);if(!commands)return;
+ SDL_GPUColorTargetInfo target={};target.texture=r.target;target.load_op=SDL_GPU_LOADOP_DONT_CARE;target.store_op=SDL_GPU_STOREOP_STORE;
+ SDL_GPURenderPass *pass=SDL_BeginGPURenderPass(commands,&target,1,NULL);CHECK(pass);
+ if(!pass){SDL_CancelGPUCommandBuffer(commands);return;}
+ SDL_BindGPUGraphicsPipeline(pass,r.pipeline);SDL_GPUTextureSamplerBinding bindings[2]={{white,r.sampler},{white,r.sampler}};
+ SDL_BindGPUFragmentSamplers(pass,0,bindings,2);SDL_PushGPUFragmentUniformData(commands,0,queries.data(),unsigned(queries.size()*sizeof(Query)));
+ SDL_DrawGPUPrimitives(pass,3,1,0,0);SDL_EndGPURenderPass(pass);CHECK(SDL_SubmitGPUCommandBuffer(commands));
+ const auto values=read_float_targets(frame,&r.target,1,columns,rows);CHECK(values.size()==rows*columns*4);if(values.size()!=rows*columns*4)return;
+ auto sat=[](double x){return (std::max)(0.0,(std::min)(1.0,x));};
+ auto at=[&](unsigned row,unsigned col,unsigned channel){return double(values[(row*columns+col)*4+channel]);};
+ auto dot=[](const float *a,const float *b){return double(a[0])*b[0]+double(a[1])*b[1]+double(a[2])*b[2];};
+ double maximumError=0,oldControl=0,wrongAlbedoControl=0;
+ for(unsigned row=0;row<rows;++row) {
+ const Query &f=queries[row];const double total=f.foam[0],other=f.foam[1],vesselCoverage=f.foam[2];
+ const double cover=sat((std::max)(total*.88,vesselCoverage));
+ const double vesselWeight=cover*sat(vesselCoverage/(std::max)(total,.0001)),genericWeight=cover-vesselWeight;
+ const double otherCover=sat((std::max)(other*.88,vesselCoverage));
+ const double otherGeneric=otherCover*(1-sat(vesselCoverage/(std::max)(other,.0001)));
+ const double coastWeight=(std::max)(0.0,genericWeight-otherGeneric);
+ CHECK(coastWeight>=0 && coastWeight<=genericWeight+1e-12);
+ CHECK(std::abs(at(row,3,0)-coastWeight)<.000001 && std::abs(at(row,3,1)-cover)<.000001 && std::abs(at(row,3,2)-genericWeight)<.000001);
+ const double roughness=(std::max)(double(f.material[2]),.55),mu=sat(f.material[1]),k=roughness*roughness*.5;
+ const double reflected=sat(f.material[0])*mu/(std::max)(mu*(1-k)+k,.0001);
+ const double genericLight=(.22+.78*sat(dot(f.normal,f.light)))*(.12+.88*f.sun[3]);
+ const double albedo[3]={.67,.73,.71},vesselAlbedo[3]={.75,.80,.77},destination[3]={.07,.11,.19};
+ for(unsigned c=0;c<3;++c) {
+ // Sum authored display-space illumination once, then decode. This does not
+ // call any production CPU shading helper and gives each material its own albedo.
+ const double authored=f.ambient[c]+f.sun[c]*(std::max)(dot(f.normal,f.light),0.0)*f.light[3]
+ +f.fillColour1[c]*(std::max)(dot(f.normal,f.fillDirection1),0.0)
+ +f.fillColour2[c]*(std::max)(dot(f.normal,f.fillDirection2),0.0);
+ const double irradiance=std::pow((std::max)(authored,0.0),2.2),generic=std::pow(albedo[c],2.2)*genericLight;
+ const double coast=std::pow(albedo[c],2.2)*irradiance*(1-reflected)+f.sky[c]*reflected;
+ const double vesselMaterial=std::pow(vesselAlbedo[c],2.2)*irradiance*(1-reflected)+f.sky[c]*reflected;
+ const double ordinary=f.clear[c]*(1-cover)+generic*genericWeight+vesselMaterial*vesselWeight;
+ const double linear=f.clear[c]*(1-cover)+generic*(genericWeight-coastWeight)+coast*coastWeight+vesselMaterial*vesselWeight;
+ const double display=std::pow(sat(linear),1/2.2),oldDisplay=std::pow(sat(ordinary),1/2.2);
+ const double visible=f.fog[c]*(1-sat(f.edge[3]))+display*f.edge[c]*sat(f.edge[3]);
+ const double final=destination[c]*(1-f.clear[3])+visible*f.clear[3];
+ maximumError=(std::max)(maximumError,std::abs(at(row,0,c)-display));
+ maximumError=(std::max)(maximumError,std::abs(at(row,1,c)-oldDisplay));
+ maximumError=(std::max)(maximumError,std::abs(at(row,2,c)-final));
+ CHECK(std::abs(at(row,0,c)-display)<.00002 && std::abs(at(row,1,c)-oldDisplay)<.00002 && std::abs(at(row,2,c)-final)<.00002);
+ for(unsigned col=0;col<columns;++col)CHECK(std::isfinite(at(row,col,c)) && at(row,col,c)>=0 && at(row,col,c)<=1.000001);
+ if(coastWeight==0)CHECK(at(row,0,c)==at(row,1,c));
+ if(row==partial){oldControl=(std::max)(oldControl,std::abs(display-oldDisplay));
+ const double wrong=linear+coastWeight*(vesselMaterial-coast);
+ wrongAlbedoControl=(std::max)(wrongAlbedoControl,std::abs(display-std::pow(sat(wrong),1/2.2)));}
+ }
+ CHECK(std::abs(at(row,2,3)-f.clear[3])<.000001);
+ }
+ for(unsigned row:{clear,crest,vessel,hiddenCrest,hiddenVessel})for(unsigned c=0;c<3;++c)CHECK(at(row,0,c)==at(row,1,c));
+ CHECK(at(full,3,0)>.999999 && at(mixed,3,0)>0 && at(partial,3,0)>0);
+ for(unsigned c=0;c<3;++c) {
+ CHECK(at(partial,0,c)>at(shadow,0,c) && at(partial,0,c)>at(noFill,0,c));
+ CHECK(at(dark,0,c)<at(partial,0,c) && at(hdr,0,c)>at(partial,0,c));
+ CHECK(at(transparent,2,c)==float(c==0?.07:(c==1?.11:.19)));
+ }
+ CHECK(oldControl>.02 && wrongAlbedoControl>.005);
+ CHECK(frame->Flush());
+ printf("sdl_gpu_frame_selfcheck: GPU coastal material: %u actual emitted-block fixtures; independent lighting/weight/display/fog/shroud/alpha error %.8f, armed old-material %.6f and vessel-albedo %.6f controls; exact zero/crest/vessel/max-hidden identity, full and mixed coverage, same albedo, shadow/fill/HDR, tangent %u, fog %u and shroud %u checked\n",
+ rows,maximumError,oldControl,wrongAlbedoControl,tangent,fogged,shrouded);
+}
+#endif // __linux__
+
+// Independent scalar pressure reference: intentionally does not call the production parameter
+// builder, constants, dual arithmetic, or derivative expressions. GPU slopes use differences
+// of this double-precision height, so a shared CPU/HLSL derivative mistake cannot self-confirm.
+static void vessel_test_pressure_parameters(double beam,double speed,double result[3])
+{
+ result[0]=result[1]=result[2]=0;
+ if(!std::isfinite(beam)||!std::isfinite(speed)||beam<0||speed<0)return;
+ const double u=(std::max)(0.0,(std::min)(speed,250.0)-.3);
+ result[0]=(std::max)(9.0,(std::min)(32.0,6+1.2*beam));
+ result[1]=(std::max)(4.0,(std::min)(60.0,1.5+.95*beam));
+ result[2]=(std::max)(3.0,(std::min)(8.0,1.8*std::sqrt(beam)))*u*u/(u*u+26*26);
+}
+static double vessel_test_pressure(double along,double across,double beam,double speed)
+{
+ double p[3];vessel_test_pressure_parameters(beam,speed,p);if(p[2]<=0)return 0;
+ const double q=across/p[1],s=along/p[0]+.6*(std::sqrt(1+q*q)-1);
+ return p[2]*std::exp(-s*s-q*q);
+}
+static double vessel_test_packet(const WaterHullModel::Hull &h,double x,double y,double level,double time,
+ double *sternOut=NULL,double *bowOut=NULL)
+{
+ if(sternOut)*sternOut=0;if(bowOut)*bowOut=0;
+ const double speed=std::hypot(h.data[2][0],h.data[2][1]);
+ if(h.data[0][3]<3||std::abs(level-h.data[0][2])>.1||speed<=double(.3f))return 0;
+ auto smooth=[](double a,double b,double v){const double t=(std::max)(0.0,(std::min)(1.0,(v-a)/(b-a)));return t*t*(3-2*t);};
+ auto gaussian=[](double v,double width){return std::exp(-v*v/(width*width));};
+ const double fx=h.data[2][0]/speed,fy=h.data[2][1]/speed,ax=h.data[1][0],ay=h.data[1][1],beam=h.data[1][3];
+ const double blend=smooth(-.25,.25,fx*ax+fy*ay);
+ const double sx=h.data[3][2]+(h.data[3][0]-h.data[3][2])*blend,sy=h.data[3][3]+(h.data[3][1]-h.data[3][3])*blend;
+ const double bx=h.data[3][0]+(h.data[3][2]-h.data[3][0])*blend,by=h.data[3][1]+(h.data[3][3]-h.data[3][1])*blend;
+ const double dx=x-h.data[0][0]-(ax*sx-ay*sy),dy=y-h.data[0][1]-(ay*sx+ax*sy);
+ const double along=-dx*fx-dy*fy,across=-dx*fy+dy*fx;
+ const double length=(std::max)(30.0,(std::min)(110.0,speed*3.2+beam*2));
+ const double width=(std::max)(beam*.35,1.0)+along*.353553,strip=(std::max)(2.5,(std::min)(7.0,beam*.18+2));
+ const double arms=gaussian(across-width,strip)*std::cos((across-width)*.40)+gaussian(across+width,strip)*std::cos((across+width)*.40);
+ const double churn=gaussian(across,(std::max)(beam*.55,2.0))*std::sin(along*.30-time*1.15+h.data[2][2]*6.2831853)*.24;
+ const double radial=std::hypot(x-h.data[0][0],y-h.data[0][1]);
+ const double support=1-smooth(h.data[2][3]+80,h.data[2][3]+110,radial);
+ const double stern=(arms*1.35+churn)*smooth(0,10,along)*(1-smooth(length*.5,length,along))*smooth(.3,14,speed)*support;
+ const double dbx=x-h.data[0][0]-(ax*bx-ay*by),dby=y-h.data[0][1]-(ay*bx+ax*by);
+ const double bow=vessel_test_pressure(dbx*fx+dby*fy,-dbx*fy+dby*fx,beam,speed)*support;
+ if(sternOut)*sternOut=stern;if(bowOut)*bowOut=bow;return stern+bow;
+}
+
+static void check_gpu_vessel_wave_model(SdlGpuFrame *frame)
+{
+ using WaterHullModel::Hull;
+ Hull hulls[8];
+ auto rectangle=[](Hull &h,float velocity) {
+ h.data[0][2]=7;h.data[0][3]=4;h.data[1][0]=1;h.data[1][2]=20;h.data[1][3]=6;
+ h.data[2][0]=velocity;h.data[2][2]=.23f;h.data[2][3]=sqrtf(436.0f);
+ h.data[3][0]=-20;h.data[3][2]=20;
+ const float points[8]={-20,-6,20,-6,20,6,-20,6};memcpy(h.data[4],points,sizeof(points));
+ };
+ rectangle(hulls[0],0);rectangle(hulls[1],12);rectangle(hulls[2],-12);rectangle(hulls[4],.3f);
+ hulls[3]=hulls[1];const float cosine=cosf(.63f),sine=sinf(.63f);
+ hulls[3].data[0][0]=137;hulls[3].data[0][1]=-83;hulls[3].data[1][0]=cosine;hulls[3].data[1][1]=sine;
+ hulls[3].data[2][0]=12*cosine;hulls[3].data[2][1]=12*sine;
+ hulls[5]=hulls[1];hulls[5].data[0][3]=2;hulls[7]=hulls[1];
+ rectangle(hulls[6],.00001f);hulls[6].data[2][1]=12;
+ struct Fixture { float point[4],other[4]; };
+ std::vector<Fixture> fixtures;
+ auto add=[&](float x,float y,unsigned h,float time=4,float level=7) {
+ Fixture f={{x,y,level,time},{float(h),0,0,0}};fixtures.push_back(f);return unsigned(fixtures.size()-1);
+ };
+ const unsigned edge=add(0,8,0),corner=add(23,10,0),inside=add(0,0,0),far=add(90,70,0);
+ const unsigned wrong=add(0,8,0,4,8),fade=add(0,34,0),leftCorner=add(19.999f,10,0),rightCorner=add(20.001f,10,0);
+ const unsigned wake=add(-40,9,1),bow=add(28,0,1),stationary=add(-40,9,0),reverse=add(40,-9,2);
+ const unsigned rotated=add(137-40*cosine-9*sine,-83-40*sine+9*cosine,3);
+ const unsigned slow=add(-40,9,4),bad=add(-40,9,5),last=add(-40,9,7);
+ const unsigned repeat=add(-40,9,1),churn=add(-40,0,1),later=add(-40,0,1,5),wakeEnd=add(-140,0,1),bowFar=add(100,0,1);
+ // Keep the broadside endpoint control inside the corner region: x==20 is
+ // an edge/corner derivative crease, so a central difference is not valid there.
+ const unsigned sideBow=add(0,8,6),sideSwitch=add(20.1f,8,6),sideStern=add(0,-20,6),sideWing=add(9,-20,6);
+ add(-24,-10,0);add(-15,-7,0);add(8,19,0);add(137+23*cosine-10*sine,-83+23*sine+10*cosine,3);
+ const double horizontalBound=8/std::sqrt(2.0);
+ const unsigned translatedPeak=add(float(20-.5*horizontalBound*std::tanh(4/horizontalBound)),
+ float(.5*horizontalBound*std::tanh(3/horizontalBound)),1);
+ const unsigned packetCount=unsigned(fixtures.size());
+ const float beams[4]={6,9,30,80},speeds[7]={0,5,14,25,40,60,250};
+ unsigned pressureRows[4][7];
+ for(unsigned b=0;b<4;++b)for(unsigned v=0;v<7;++v) {
+ double p[3];vessel_test_pressure_parameters(beams[b],speeds[v],p);
+ Fixture f={{float(p[0]*.45),float(p[1]*.65),0,0},{0,beams[b],speeds[v],1}};
+ pressureRows[b][v]=unsigned(fixtures.size());fixtures.push_back(f);
+ }
+ const float invalidInputs[][2]={{-1,40},{9,-1},{NAN,40},{9,INFINITY}};
+ for(const auto &invalid:invalidInputs) {
+ Fixture f={{2,3,0,0},{0,invalid[0],invalid[1],1}};fixtures.push_back(f);
+ }
+ const unsigned columns=24,count=unsigned(fixtures.size());
+ std::string ps="cbuffer FixturesBlock : register(b0,space3) { float4 HullData[80]; float4 Fixtures[";
+ ps+=std::to_string(count*2)+"]; };\nstatic const float4 HullParameters=float4(0,0,0,0);\n";
+ ps+=WaterFftSampling::CommonSource()+WaterVesselWaves::Source(false,false); // Independent Gaussian fallback oracle below.
+ ps+=R"HLSL(
+float3 incident(float2 p) {return float3(2.0*sin(.07*p.x+.025*p.y),1.5*cos(.035*p.x-.045*p.y),3.0*sin(.055*p.x-.08*p.y));}
+float3 incidentX(float2 p) {return float3(.14*cos(.07*p.x+.025*p.y),-.0525*sin(.035*p.x-.045*p.y),.165*cos(.055*p.x-.08*p.y));}
+float3 incidentY(float2 p) {return float3(.05*cos(.07*p.x+.025*p.y),.0675*sin(.035*p.x-.045*p.y),-.24*cos(.055*p.x-.08*p.y));}
+float4 main(float4 pixel:SV_Position):SV_Target0 {
+ uint row=(uint)pixel.y,col=(uint)pixel.x;float4 f=Fixtures[row*2];int h=(int)Fixtures[row*2+1].x;
+ float4 mode=Fixtures[row*2+1];
+ if(mode.w>0.5) {
+ float3 parameters=vesselBowPressure(mode.y,mode.z);
+ if(col==0) return float4(parameters,0);
+ float2 queryPoint=f.xy;
+ if(col>=2 && col<=5) queryPoint+=col==2?float2(.03125,0):col==3?float2(-.03125,0):col==4?float2(0,.03125):float2(0,-.03125);
+ if(col==6) queryPoint=0;
+ float halfCoordinate=sqrt(log(2.0));
+ if(col==7) queryPoint=float2(parameters.x*halfCoordinate,0);
+ if(col==8) queryPoint=float2(-.6*parameters.x*(sqrt(1.0+halfCoordinate*halfCoordinate)-1.0),parameters.y*halfCoordinate);
+ return float4(vesselBowPressureField(float3(queryPoint.x,1,0),float3(queryPoint.y,0,1),parameters),0);
+ }
+ if(col>=20) {
+ // All four asymptotic component-limit corners. This fails if the emitter
+ // accidentally uses radial8 as each component's bound instead of 8/sqrt(2).
+ float2 sign=float2((col&1)!=0?1.0:-1.0,(col&2)!=0?1.0:-1.0);
+ float2 shifted=fftHorizontalPosition(float2(0,0),float3(sign*1000.0,0),1.0);
+ return float4(shifted,length(shifted),0);
+ }
+ if(col>=10) {
+ float2 p=f.xy;
+ if(col>=11 && col<=14) p+=col==11?float2(.03125,0):col==12?float2(-.03125,0):col==13?float2(0,.03125):float2(0,-.03125);
+ float3 oldBow;
+ float3 oldGenerated=vesselGeneratedWave(p,f.z,f.w,h,oldBow);
+ float3 raw=incident(p),rawX=incidentX(p),rawY=incidentY(p);
+ float phase=.013*p.x-.017*p.y;
+ float3 scale=float3(.5+.1*sin(phase),.0013*cos(phase),-.0017*cos(phase));
+ if(col==15) {raw=0;rawX=0;rawY=0;scale=float3(.5,0,0);}
+ if(col==18) {raw=float3(4,-3,0);rawX=0;rawY=0;scale=float3(.5,0,0);}
+ FftHorizontalRegistration map=fftHorizontalRegistration(p,raw,rawX,rawY,scale);
+ float3 correction=vesselRegisteredBowDifference(map.position,map.derivativeX,map.derivativeY,f.z,h,oldBow);
+ float3 registered=oldGenerated+correction;
+ if(col==15) return float4(registered-oldGenerated,0);
+ if(col==16) return float4(map.position,scale.x,0);
+ if(col==17) {
+ float3 mapped=vesselGeneratedBow(map.position,f.z,h);
+ mapped.yz=float2(dot(mapped.yz,map.derivativeX),dot(mapped.yz,map.derivativeY));
+ return float4((registered-mapped)-(oldGenerated-oldBow),0);
+ }
+ if(col==19) return float4(oldGenerated,0);
+ return float4(registered,0);
+ }
+ float2 p=f.xy;
+ if(col>=6) p+=col==6?float2(.03125,0):col==7?float2(-.03125,0):col==8?float2(0,.03125):float2(0,-.03125);
+ VesselReflection v=vesselReflection(p,f.z,h);float3 d=incident(v.samplePosition);
+ float3 value=vesselReflectedValue(d,v),generated=vesselGeneratedWave(p,f.z,f.w,h);
+ if(col==0 || col>=6) return float4(value,generated.x);
+ if(col==1) return float4(vesselReflectedDerivative(d,incidentX(v.samplePosition),incidentY(v.samplePosition),float2(1,0),v),0);
+ if(col==2) return float4(vesselReflectedDerivative(d,incidentX(v.samplePosition),incidentY(v.samplePosition),float2(0,1),v),0);
+ if(col==3) return float4(v.samplePosition,v.weight,v.corner);
+ if(col==4) return float4(v.weightGradient,v.normal);
+ return float4(generated,0);
+}
+
+)HLSL";
+ const char *vs="float4 main(uint id:SV_VertexID):SV_Position {return float4(id==1?3.0:-1.0,id==2?3.0:-1.0,0,1);}";
+ std::vector<unsigned char> spirv;std::string error;
+ bool compiled=SDL3_Compile_HLSL_To_SPIRV(vs,true,spirv,error);CHECK(compiled);if(!compiled) return;
+ SDL_GPUShader *vertex=SDL3_Create_Shader(frame->Device(),spirv,true,error);CHECK(vertex);
+ compiled=SDL3_Compile_HLSL_To_SPIRV(ps,false,spirv,error);CHECK(compiled);
+ if(!compiled) {printf("vessel wave model: %s\n",error.c_str());if(vertex) SDL_ReleaseGPUShader(frame->Device(),vertex);return;}
+ SDL_GPUShader *pixel=SDL3_Create_Shader(frame->Device(),spirv,false,error);CHECK(pixel);
+ SDL_GPUColorTargetDescription colour={};colour.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
+ SDL_GPUGraphicsPipelineCreateInfo info={};info.vertex_shader=vertex;info.fragment_shader=pixel;
+ info.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;info.target_info.color_target_descriptions=&colour;info.target_info.num_color_targets=1;
+ SDL_GPUGraphicsPipeline *pipeline=vertex&&pixel?SDL_CreateGPUGraphicsPipeline(frame->Device(),&info):NULL;CHECK(pipeline);
+ SDL_GPUTextureCreateInfo texture={};texture.type=SDL_GPU_TEXTURETYPE_2D;texture.format=colour.format;
+ texture.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;texture.width=columns;texture.height=count;texture.layer_count_or_depth=texture.num_levels=1;
+ SDL_GPUTexture *target=SDL_CreateGPUTexture(frame->Device(),&texture);CHECK(target);
+ if(pipeline && target) {
+ std::vector<float> uniforms(80*4+count*8);memcpy(uniforms.data(),hulls,sizeof(hulls));
+ CHECK(uniforms.size()*sizeof(float)<=4096); // bundled Vulkan uniform section limit
+ memcpy(uniforms.data()+80*4,fixtures.data(),fixtures.size()*sizeof(Fixture));
+ auto render=[&]() {
+ CHECK(frame->Flush());SDL_GPUCommandBuffer *commands=SDL_AcquireGPUCommandBuffer(frame->Device());CHECK(commands);
+ SDL_GPUColorTargetInfo attachment={};attachment.texture=target;attachment.load_op=SDL_GPU_LOADOP_DONT_CARE;attachment.store_op=SDL_GPU_STOREOP_STORE;
+ SDL_GPURenderPass *pass=SDL_BeginGPURenderPass(commands,&attachment,1,NULL);CHECK(pass);
+ SDL_BindGPUGraphicsPipeline(pass,pipeline);SDL_PushGPUFragmentUniformData(commands,0,uniforms.data(),uniforms.size()*sizeof(float));
+ SDL_DrawGPUPrimitives(pass,3,1,0,0);SDL_EndGPURenderPass(pass);CHECK(SDL_SubmitGPUCommandBuffer(commands));
+ return read_float_targets(frame,&target,1,columns,count);
+ };
+ const auto values=render();
+ auto value=[&](unsigned row,unsigned col,unsigned component){return double(values[(row*columns+col)*4+component]);};
+ // Independent CPU geometry: clamp to a rectangle, then mirror about that closest point.
+ // This does not call the production closest-edge, mirror-Jacobian, or derivative helpers.
+ auto reflected=[&](unsigned row,double x,double y,double result[3]) {
+ const Fixture &f=fixtures[row];const Hull &h=hulls[unsigned(f.other[0])];
+ result[0]=result[1]=result[2]=0;
+ if(h.data[0][3]<3 || std::abs(f.point[2]-h.data[0][2])>.1) return;
+ const double ax=h.data[1][0],ay=h.data[1][1],dx=x-h.data[0][0],dy=y-h.data[0][1];
+ const double lx=dx*ax+dy*ay,ly=-dx*ay+dy*ax;
+ if(std::abs(lx)<=20 && std::abs(ly)<=6) return;
+ const double qx=(std::max)(-20.0,(std::min)(20.0,lx)),qy=(std::max)(-6.0,(std::min)(6.0,ly));
+ const double distance=std::hypot(lx-qx,ly-qy);if(distance>=28 || distance<.0001) return;
+ const double nx=(ax*(lx-qx)-ay*(ly-qy))/distance,ny=(ay*(lx-qx)+ax*(ly-qy))/distance;
+ const double mx=x-2*distance*nx,my=y-2*distance*ny,t=distance/28,fade=1-t*t*(3-2*t),weight=.68*fade*fade;
+ const double d[3]={2*std::sin(.07*mx+.025*my),1.5*std::cos(.035*mx-.045*my),3*std::sin(.055*mx-.08*my)};
+ const double normal=nx*d[0]+ny*d[1];result[0]=(d[0]-2*nx*normal)*weight;result[1]=(d[1]-2*ny*normal)*weight;result[2]=d[2]*weight;
+ };
+ double maxValue=0,maxDerivative=0,maxPacketDerivative=0,maxPacketValue=0,maxScalarPacketDerivative=0,maxSternError=0;
+ for(unsigned row=0;row<packetCount;++row) {
+ const double x=fixtures[row].point[0],y=fixtures[row].point[1];double expected[3];reflected(row,x,y,expected);
+ const auto &h=hulls[unsigned(fixtures[row].other[0])];double sternValue=0,bowValue=0;
+ const double packet=vessel_test_packet(h,x,y,fixtures[row].point[2],fixtures[row].point[3],&sternValue,&bowValue);
+ maxPacketValue=(std::max)(maxPacketValue,std::abs(value(row,5,0)-packet));CHECK(std::abs(value(row,5,0)-packet)<.00002);
+ const double sternError=std::abs((value(row,5,0)-bowValue)-sternValue);
+ maxSternError=(std::max)(maxSternError,sternError);CHECK(sternError<.00002);
+ for(unsigned c=0;c<3;++c) {maxValue=(std::max)(maxValue,std::abs(value(row,0,c)-expected[c]));CHECK(std::abs(value(row,0,c)-expected[c])<.00002);}
+ for(unsigned axis=0;axis<2;++axis) {
+ double plus[3],minus[3];const double step=.0001;
+ reflected(row,x+(axis==0?step:0),y+(axis==1?step:0),plus);
+ reflected(row,x-(axis==0?step:0),y-(axis==1?step:0),minus);
+ for(unsigned c=0;c<3;++c) {
+ const double difference=std::abs(value(row,1+axis,c)-(plus[c]-minus[c])/(2*step));
+ maxDerivative=(std::max)(maxDerivative,difference);CHECK(difference<.0002);
+ }
+ const double numeric=(value(row,6+axis*2,3)-value(row,7+axis*2,3))/.0625;
+ const double difference=std::abs(numeric-value(row,5,axis+1));
+ maxPacketDerivative=(std::max)(maxPacketDerivative,difference);CHECK(difference<.0003);
+ const double packetPlus=vessel_test_packet(h,x+(axis==0?.0001:0),y+(axis==1?.0001:0),fixtures[row].point[2],fixtures[row].point[3]);
+ const double packetMinus=vessel_test_packet(h,x-(axis==0?.0001:0),y-(axis==1?.0001:0),fixtures[row].point[2],fixtures[row].point[3]);
+ const double scalarError=std::abs(value(row,5,axis+1)-(packetPlus-packetMinus)/.0002);
+ maxScalarPacketDerivative=(std::max)(maxScalarPacketDerivative,scalarError);CHECK(scalarError<.00003);
+ }
+ for(unsigned col=0;col<columns;++col) for(unsigned c=0;c<4;++c) CHECK(std::isfinite(value(row,col,c)));
+ }
+ // The reference maps scalar query positions and separately evaluates the original
+ // stern and mapped bow. It never calls the production Jacobian or dual helpers.
+ auto registeredScalar=[&](unsigned row,double x,double y,bool constant=false) {
+ const Fixture &f=fixtures[row];const Hull &h=hulls[unsigned(f.other[0])];
+ double stern=0;vessel_test_packet(h,x,y,f.point[2],f.point[3],&stern);
+ const double scale=constant?.5:.5+.1*std::sin(.013*x-.017*y);
+ const double rawX=constant?4:2*std::sin(.07*x+.025*y),rawY=constant?-3:1.5*std::cos(.035*x-.045*y);
+ const double mappedX=x+scale*horizontalBound*std::tanh(rawX/horizontalBound);
+ const double mappedY=y+scale*horizontalBound*std::tanh(rawY/horizontalBound);
+ double bow=0;vessel_test_packet(h,mappedX,mappedY,f.point[2],f.point[3],NULL,&bow);
+ return stern+bow;
+ };
+ double registrationValueError=0,registrationDerivativeError=0,registrationDifferenceError=0,registrationOldControl=0;
+ for(unsigned row=0;row<packetCount;++row) {
+ const double x=fixtures[row].point[0],y=fixtures[row].point[1];
+ const double error=std::abs(value(row,10,0)-registeredScalar(row,x,y));
+ registrationValueError=(std::max)(registrationValueError,error);CHECK(error<.00003);
+ registrationOldControl=(std::max)(registrationOldControl,std::abs(value(row,10,0)-value(row,19,0)));
+ for(unsigned axis=0;axis<2;++axis) {
+ const double step=.0001;
+ const double plus=registeredScalar(row,x+(axis==0?step:0),y+(axis==1?step:0));
+ const double minus=registeredScalar(row,x-(axis==0?step:0),y-(axis==1?step:0));
+ const double error=std::abs(value(row,10,1+axis)-(plus-minus)/(2*step));
+ registrationDerivativeError=(std::max)(registrationDerivativeError,error);CHECK(error<.00005);
+ const double gpuDifference=(value(row,11+2*axis,0)-value(row,12+2*axis,0))/.0625;
+ const double gpuError=std::abs(value(row,10,1+axis)-gpuDifference);
+ registrationDifferenceError=(std::max)(registrationDifferenceError,gpuError);CHECK(gpuError<.0004);
+ }
+ for(unsigned c=0;c<3;++c) {CHECK(value(row,15,c)==0);CHECK(std::abs(value(row,17,c))<.000002);}
+ CHECK(std::abs(value(row,18,0)-registeredScalar(row,x,y,true))<.00003);
+ const double horizontal=std::hypot(value(row,16,0)-x,value(row,16,1)-y);
+ CHECK(horizontal<=8*value(row,16,2)+.00002);
+ for(unsigned col=20;col<24;++col) {
+ CHECK(std::abs(value(row,col,0)-((col&1)?1:-1)*horizontalBound)<.000002);
+ CHECK(std::abs(value(row,col,1)-((col&2)?1:-1)*horizontalBound)<.000002);
+ CHECK(value(row,col,2)<=8.000002 && value(row,col,2)>7.999998);
+ }
+ }
+ double peakParameters[3];vessel_test_pressure_parameters(6,12,peakParameters);
+ CHECK(std::abs(value(translatedPeak,18,0)-peakParameters[2])<.000003);
+ CHECK(registrationOldControl>.005);
+ printf("sdl_gpu_frame_selfcheck: registered bow %u scalar fixtures: value %.8g, derivative %.8g, GPU finite difference %.8g; old-coordinate control %.8g; translated world peak, exact zero-chop and stern preservation checked\n",
+ packetCount,registrationValueError,registrationDerivativeError,registrationDifferenceError,registrationOldControl);
+ double maxPressureParameter=0,maxPressureValue=0,maxPressureDerivative=0,maxPressureCpu=0,maxPressureDifference=0;
+ for(unsigned row=packetCount;row<count;++row) {
+ const Fixture &f=fixtures[row];double expected[3];vessel_test_pressure_parameters(f.other[1],f.other[2],expected);
+ const auto cpu=WaterVesselWaves::BowPressure(f.other[1],f.other[2]);const float cpuParameters[3]={cpu.along,cpu.across,cpu.amplitude};
+ for(unsigned c=0;c<3;++c) {
+ maxPressureParameter=(std::max)(maxPressureParameter,std::abs(value(row,0,c)-expected[c]));
+ CHECK(std::abs(value(row,0,c)-expected[c])<.00001 && std::abs(value(row,0,c)-cpuParameters[c])<.00001);
+ }
+ const double scalar=vessel_test_pressure(f.point[0],f.point[1],f.other[1],f.other[2]);
+ maxPressureValue=(std::max)(maxPressureValue,std::abs(value(row,1,0)-scalar));CHECK(std::abs(value(row,1,0)-scalar)<.00001);
+ const auto cpuValue=WaterVesselWaves::EvaluateBowPressure(cpu,f.point[0],f.point[1]);
+ const float cpuSample[3]={cpuValue.height,cpuValue.dAlong,cpuValue.dAcross};
+ for(unsigned c=0;c<3;++c) {
+ maxPressureCpu=(std::max)(maxPressureCpu,std::abs(value(row,1,c)-cpuSample[c]));CHECK(std::abs(value(row,1,c)-cpuSample[c])<.00002);
+ }
+ for(unsigned axis=0;axis<2;++axis) {
+ const double plus=vessel_test_pressure(f.point[0]+(axis==0?.0001:0),f.point[1]+(axis==1?.0001:0),f.other[1],f.other[2]);
+ const double minus=vessel_test_pressure(f.point[0]-(axis==0?.0001:0),f.point[1]-(axis==1?.0001:0),f.other[1],f.other[2]);
+ const double derivativeError=std::abs(value(row,1,axis+1)-(plus-minus)/.0002);
+ maxPressureDerivative=(std::max)(maxPressureDerivative,derivativeError);CHECK(derivativeError<.00002);
+ const double differenceError=std::abs(value(row,1,axis+1)-(value(row,2+axis*2,0)-value(row,3+axis*2,0))/.0625);
+ maxPressureDifference=(std::max)(maxPressureDifference,differenceError);CHECK(differenceError<.00003);
+ }
+ CHECK(std::abs(value(row,6,0)-expected[2])<.000003);
+ CHECK(std::abs(value(row,7,0)-expected[2]*.5)<.000003 && std::abs(value(row,8,0)-expected[2]*.5)<.000003);
+ for(unsigned col=0;col<columns;++col)for(unsigned c=0;c<4;++c)CHECK(std::isfinite(value(row,col,c)));
+ }
+ for(unsigned b=0;b<4;++b) {
+ CHECK(value(pressureRows[b][0],6,0)==0);
+ for(unsigned v=1;v<7;++v)CHECK(value(pressureRows[b][v],6,0)>value(pressureRows[b][v-1],6,0));
+ CHECK(value(pressureRows[b][4],6,0)>value(pressureRows[b][2],6,0)*3);
+ }
+ CHECK(value(pressureRows[3][4],0,1)>value(pressureRows[0][4],0,1)*8 && value(pressureRows[3][4],6,0)>value(pressureRows[0][4],6,0));
+ CHECK(std::abs(value(edge,3,0))<.00001 && std::abs(value(edge,3,1)-4)<.00001 && value(edge,3,3)==0);
+ CHECK(std::abs(value(corner,3,0)-17)<.00001 && std::abs(value(corner,3,1)-2)<.00001 && value(corner,3,3)==1);
+ for(unsigned row:{inside,far,wrong,fade}) CHECK(value(row,3,2)==0);
+ for(unsigned c=0;c<3;++c) CHECK(std::abs(value(leftCorner,0,c)-value(rightCorner,0,c))<.001);
+ CHECK(value(wake,5,0)>.05 && value(bow,5,0)>.5);
+ for(unsigned row:{stationary,slow,bad,wakeEnd,bowFar}) CHECK(std::abs(value(row,5,0))<.00001);
+ CHECK(std::abs(value(reverse,5,0)-value(wake,5,0))<.00002);
+ CHECK(std::abs(value(reverse,5,1)+value(wake,5,1))<.00002 && std::abs(value(reverse,5,2)+value(wake,5,2))<.00002);
+ CHECK(std::abs(value(rotated,5,0)-value(wake,5,0))<.00002);
+ CHECK(std::abs(value(rotated,5,1)-(value(wake,5,1)*cosine-value(wake,5,2)*sine))<.00002);
+ CHECK(std::abs(value(rotated,5,2)-(value(wake,5,1)*sine+value(wake,5,2)*cosine))<.00002);
+ for(unsigned c=0;c<3;++c) CHECK(value(repeat,5,c)==value(wake,5,c) && value(last,5,c)==value(wake,5,c));
+ // The divergent crests are steady in the boat frame. Animate the centre churn instead:
+ // at along=20/across=0 both spatial envelopes are one, so its expected temporal delta
+ // is independently just the scalar sinusoid times the measured-speed gate.
+ const double speedT=(12.0-.3)/(14.0-.3),speedGate=speedT*speedT*(3-2*speedT);
+ const double phase=6.0+double(hulls[1].data[2][2])*6.2831853;
+ const double expectedDelta=.24*speedGate*(std::sin(phase-5*1.15)-std::sin(phase-4*1.15));
+ CHECK(expectedDelta>.15 && std::abs((value(later,5,0)-value(churn,5,0))-expectedDelta)<.00002);
+ // The travel direction crosses sideways by only 0.00000167 radians. Heights and slopes
+ // must not jump from one end of a forty-unit hull to the other. Check active bow/churn and
+ // both old endpoint regions; the armed endpoint-forcing control proves this catches a snap.
+ hulls[6].data[2][0]=-.00001f;memcpy(uniforms.data()+6*40,&hulls[6],sizeof(Hull));
+ const auto oppositeSide=render();double maxSideChange=0;
+ CHECK(value(sideBow,5,0)>.5);
+ for(unsigned row:{sideBow,sideSwitch,sideStern,sideWing}) for(unsigned c=0;c<3;++c) {
+ const double change=std::abs(value(row,5,c)-oppositeSide[(row*columns+5)*4+c]);
+ maxSideChange=(std::max)(maxSideChange,change);CHECK(change<.0003);
+ }
+ hulls[6].data[2][0]=.00001f;hulls[6].data[3][0]=hulls[6].data[3][2]=20;
+ memcpy(uniforms.data()+6*40,&hulls[6],sizeof(Hull));const auto forcedRight=render();
+ const double forcedRightExpected=vessel_test_packet(hulls[6],fixtures[sideSwitch].point[0],fixtures[sideSwitch].point[1],7,4);
+ hulls[6].data[2][0]=-.00001f;hulls[6].data[3][0]=hulls[6].data[3][2]=-20;
+ memcpy(uniforms.data()+6*40,&hulls[6],sizeof(Hull));const auto forcedLeft=render();
+ const double forcedLeftExpected=vessel_test_packet(hulls[6],fixtures[sideSwitch].point[0],fixtures[sideSwitch].point[1],7,4);
+ const double forcedDelta=forcedRight[(sideSwitch*columns+5)*4]-forcedLeft[(sideSwitch*columns+5)*4];
+ CHECK(std::abs(forcedDelta)>.4 && std::abs(forcedDelta-(forcedRightExpected-forcedLeftExpected))<.00002);
+ // This armed old-model control catches accidental retention of the detached fixed8/1.9
+ // bump; it is separate from numerical error tolerances, which remain tight.
+ CHECK(std::abs(value(bow,5,0)-1.9*speedGate)>.5);
+ double maxScaledPacket=0;
+ for(float beam:beams) {
+ double previousHeight=0;
+ for(float speed:{14.0f,40.0f}) {
+ Hull large;rectangle(large,speed);large.data[1][2]=beam*3;large.data[1][3]=beam;
+ large.data[2][3]=std::hypot(beam*3,beam);large.data[3][0]=-beam*3;large.data[3][2]=beam*3;
+ const float points[8]={-beam*3,-beam,beam*3,-beam,beam*3,beam,-beam*3,beam};memcpy(large.data[4],points,sizeof(points));
+ memcpy(uniforms.data()+7*40,&large,sizeof(large));
+ Fixture sample=fixtures[last];sample.point[0]=beam*3+9;sample.point[1]=beam*.5f;
+ memcpy(uniforms.data()+80*4+last*8,&sample,sizeof(sample));const auto scaled=render();
+ const double observed=scaled[(last*columns+5)*4],expected=vessel_test_packet(large,sample.point[0],sample.point[1],7,4);
+ maxScaledPacket=(std::max)(maxScaledPacket,std::abs(observed-expected));CHECK(std::abs(observed-expected)<.00002);
+ for(unsigned axis=0;axis<2;++axis) {
+ const double plus=vessel_test_packet(large,sample.point[0]+(axis==0?.0001:0),sample.point[1]+(axis==1?.0001:0),7,4);
+ const double minus=vessel_test_packet(large,sample.point[0]-(axis==0?.0001:0),sample.point[1]-(axis==1?.0001:0),7,4);
+ CHECK(std::abs(scaled[(last*columns+5)*4+axis+1]-(plus-minus)/.0002)<.00003);
+ }
+ if(previousHeight>0)CHECK(observed>previousHeight*3);previousHeight=observed;
+ }
+ }
+ printf("sdl_gpu_frame_selfcheck: GPU bow pressure: %u beam/speed/invalid fixtures, independent parameters %.8f/value %.8f/gradient %.8f, CPU agreement %.8f, GPU height differences %.8f, full scaled packet %.8f; actual bow anchor, curved half-height widths, monotonic speed beyond14 and beam-dependent extent checked\n",count-packetCount,maxPressureParameter,maxPressureValue,maxPressureDerivative,maxPressureCpu,maxPressureDifference,maxScaledPacket);
+ printf("sdl_gpu_frame_selfcheck: GPU physical vessel waves: %u fixtures, independent reflection value %.8f/gradient %.8f, packet value %.8f/scalar gradient %.8f/GPU finite-difference %.8f, unchanged stern %.8f, sideways height/slope change %.8f; stationary/corners/reverse/rotation/level/speed/pause/support/final hull and armed endpoint snap checked\n",packetCount,maxValue,maxDerivative,maxPacketValue,maxScalarPacketDerivative,maxPacketDerivative,maxSternError,maxSideChange);
+ }
+ if(target) SDL_ReleaseGPUTexture(frame->Device(),target);if(pipeline) SDL_ReleaseGPUGraphicsPipeline(frame->Device(),pipeline);
+ if(vertex) SDL_ReleaseGPUShader(frame->Device(),vertex);if(pixel) SDL_ReleaseGPUShader(frame->Device(),pixel);
+}
+
+static void check_gpu_vessel_hull_damping(SdlGpuFrame *frame)
+{
+ // Independent rectangle distances and finite differences check the shared VS/PS helper.
+ // The reference never calls the production closest-edge or damping-gradient expressions.
+ SdlWaterPixelConstants water={};water.HullParameters[0]=8;
+ struct Rectangle {double x,y,angle,level;unsigned slot;};
+ const Rectangle rectangles[]={{0,0,0,7,0},{80,23,.63,7,4},{91,27,.63,7,5},{-70,-40,-.41,7,7}};
+ for(const auto &r:rectangles) {
+ WaterHullModel::Hull hull;hull.data[0][0]=float(r.x);hull.data[0][1]=float(r.y);hull.data[0][2]=float(r.level);hull.data[0][3]=4;
+ hull.data[1][0]=float(cos(r.angle));hull.data[1][1]=float(sin(r.angle));hull.data[1][2]=20;hull.data[1][3]=6;
+ const float outline[8]={-20,-6,20,-6,20,6,-20,6};memcpy(hull.data[4],outline,sizeof(outline));
+ memcpy(water.HullData+r.slot*10,&hull,sizeof(hull));
+ }
+ memcpy(water.HullData+10,water.HullData,sizeof(WaterHullModel::Hull));water.HullData[10][3]=2; // invalid contour
+ memcpy(water.HullData+20,water.HullData,sizeof(WaterHullModel::Hull));water.HullData[20][2]=11; // another level
+ struct Fixture {float point[4],freeDamping[4],offshore[4];};
+ std::vector<Fixture> fixtures;
+ auto add=[&](float x,float y,float level,float freeValue,float offshoreValue,float fx=0,float fy=0,float ox=0,float oy=0) {
+ Fixture f={{x,y,level,0},{freeValue,fx,fy,0},{offshoreValue,ox,oy,0}};fixtures.push_back(f);
+ };
+ for(float y:{0.0f,5.0f,6.0f,6.01f,8.0f,10.5f,14.99f,15.0f,15.01f,40.0f}) add(0,y,7,1,1);
+ for(float x:{19.99f,20.0f,20.01f,22.0f,25.0f}) add(x,8,7,1,1);
+ const double localPoints[][2]={{0,8},{23,10},{-23,-10}};
+ for(const auto &r:rectangles) for(const auto &p:localPoints)
+ add(float(r.x+cos(r.angle)*p[0]-sin(r.angle)*p[1]),float(r.y+sin(r.angle)*p[0]+cos(r.angle)*p[1]),7,1,1);
+ add(0,8,8,1,1);add(0,8,7,1,0);add(0,8,7,0,1);add(0,8,7,.9f,.6f,.003f,-.002f,.004f,.006f);
+ add(0,12,7,.1f,.6f,.003f,-.002f,.004f,.006f); // floor/terrain wins the minimum
+ add(0,8,7,WaterFftGeometry::SafeDamping(1,2.25f),1);
+ add(0,14,7,WaterFftGeometry::SafeDamping(1,2.25f),1);
+ add(23,10,7,.95f,.8f,-.004f,.001f,-.003f,.004f);
+ add(80,23,7,.7f,.4f,.003f,-.002f,.004f,.006f); // inside the rotated hull
+ const unsigned rows=unsigned(fixtures.size()),columns=3;
+ std::string common=WaterFftSampling::UniformSource("WaterBlock",0)+WaterVesselWaves::Source()+
+ "cbuffer FixtureBlock:register(b1) {float4 Point;float4 FreeDamping;float4 Offshore;};\n";
+ std::string vs=common+R"HLSL(
+struct Output {float4 Position:SV_Position;[[vk::location(0)]] float3 Value:TEXCOORD0;};
+Output main(uint id:SV_VertexID) {Output o;o.Position=float4(id==1?3.0:-1.0,id==2?3.0:-1.0,0,1);
+o.Value=vesselApplyHullDamping(Point.xy,Point.z,FreeDamping.xyz,Offshore.xyz);return o;}
+)HLSL";
+ std::string ps=common+R"HLSL(
+float4 main(float4 pixel:SV_Position,[[vk::location(0)]] float3 value:TEXCOORD0):SV_Target0 {
+uint col=(uint)pixel.x;
+if(col==0) return float4(vesselHullDamping(Point.xy,Point.z),1);
+if(col==1) return float4(vesselApplyHullDamping(Point.xy,Point.z,FreeDamping.xyz,Offshore.xyz),1);
+return float4(value,1);}
+)HLSL";
+ struct Resources {
+ SDL_GPUDevice *device;SDL_GPUTexture *target=NULL;SDL_GPUShader *vertex=NULL,*pixel=NULL;SDL_GPUGraphicsPipeline *pipeline=NULL;
+ ~Resources(){if(target)SDL_ReleaseGPUTexture(device,target);if(pipeline)SDL_ReleaseGPUGraphicsPipeline(device,pipeline);
+ if(vertex)SDL_ReleaseGPUShader(device,vertex);if(pixel)SDL_ReleaseGPUShader(device,pixel);}
+ } resources;
+ resources.device=frame->Device();std::vector<unsigned char> spirv;std::string error;
+ CHECK(SDL3_Shader_Retarget(vs,true));CHECK(SDL3_Shader_Retarget(ps,false));
+ bool compiled=SDL3_Compile_HLSL_To_SPIRV(vs,true,spirv,error);CHECK(compiled);
+ if(!compiled){printf("hull damping VS: %s\n",error.c_str());return;}
+ resources.vertex=SDL3_Create_Shader(resources.device,spirv,true,error);CHECK(resources.vertex);
+ compiled=SDL3_Compile_HLSL_To_SPIRV(ps,false,spirv,error);CHECK(compiled);
+ if(!compiled){printf("hull damping PS: %s\n",error.c_str());return;}
+ resources.pixel=SDL3_Create_Shader(resources.device,spirv,false,error);CHECK(resources.pixel);
+ SDL_GPUColorTargetDescription colour={};colour.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
+ SDL_GPUGraphicsPipelineCreateInfo pi={};pi.vertex_shader=resources.vertex;pi.fragment_shader=resources.pixel;
+ pi.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;pi.target_info.color_target_descriptions=&colour;pi.target_info.num_color_targets=1;
+ resources.pipeline=SDL_CreateGPUGraphicsPipeline(resources.device,&pi);CHECK(resources.pipeline);if(!resources.pipeline)return;
+ SDL_GPUTextureCreateInfo ti={};ti.type=SDL_GPU_TEXTURETYPE_2D;ti.format=colour.format;ti.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;
+ ti.width=columns;ti.height=rows;ti.layer_count_or_depth=ti.num_levels=1;
+ resources.target=SDL_CreateGPUTexture(resources.device,&ti);CHECK(resources.target);if(!resources.target)return;
+ CHECK(frame->Flush());SDL_GPUCommandBuffer *commands=SDL_AcquireGPUCommandBuffer(resources.device);CHECK(commands);
+ SDL_GPUColorTargetInfo target={};target.texture=resources.target;target.load_op=SDL_GPU_LOADOP_DONT_CARE;target.store_op=SDL_GPU_STOREOP_STORE;
+ SDL_GPURenderPass *pass=SDL_BeginGPURenderPass(commands,&target,1,NULL);CHECK(pass);SDL_BindGPUGraphicsPipeline(pass,resources.pipeline);
+ SDL_PushGPUVertexUniformData(commands,0,&water,sizeof(water));SDL_PushGPUFragmentUniformData(commands,0,&water,sizeof(water));
+ for(unsigned row=0;row<rows;++row) {
+ SDL_GPUViewport viewport={0,float(row),float(columns),1,0,1};SDL_SetGPUViewport(pass,&viewport);
+ SDL_PushGPUVertexUniformData(commands,1,&fixtures[row],sizeof(Fixture));SDL_PushGPUFragmentUniformData(commands,1,&fixtures[row],sizeof(Fixture));
+ SDL_DrawGPUPrimitives(pass,3,1,0,0);
+ }
+ SDL_EndGPURenderPass(pass);CHECK(SDL_SubmitGPUCommandBuffer(commands));
+ const auto values=read_float_targets(frame,&resources.target,1,columns,rows);CHECK(values.size()==rows*columns*4);if(values.size()!=rows*columns*4)return;
+ auto raw=[&](double x,double y,double level) {
+ double result=1;
+ for(const auto &r:rectangles) {
+ if(std::abs(level-r.level)>.1)continue;
+ const double ax=water.HullData[r.slot*10+1][0],ay=water.HullData[r.slot*10+1][1];
+ const double localX=(x-r.x)*ax+(y-r.y)*ay,localY=-(x-r.x)*ay+(y-r.y)*ax;
+ const double distance=std::hypot((std::max)(0.0,std::abs(localX)-20),(std::max)(0.0,std::abs(localY)-6));
+ const double t=(std::min)(1.0,distance/9);result=(std::min)(result,t*t*(3-2*t));
+ }
+ return result;
+ };
+ double maxValue=0,maxGradient=0,maxStage=0;unsigned hullWins=0,freeWins=0,gradientControls=0;
+ for(unsigned row=0;row<rows;++row) {
+ const Fixture &f=fixtures[row];const double x=f.point[0],y=f.point[1],level=f.point[2];
+ auto composed=[&](double px,double py) {
+ const double free=f.freeDamping[0]+f.freeDamping[1]*(px-x)+f.freeDamping[2]*(py-y);
+ const double offshore=f.offshore[0]+f.offshore[1]*(px-x)+f.offshore[2]*(py-y);
+ if(free<=0 || offshore<=0)return free;
+ return (std::min)(free,1+(raw(px,py,level)-1)*offshore);
+ };
+ for(unsigned col=0;col<2;++col) {
+ const double expected=col?composed(x,y):raw(x,y,level);
+ const double difference=std::abs(values[(row*columns+col)*4]-expected);
+ maxValue=(std::max)(maxValue,difference);CHECK(difference<.000004);
+ for(unsigned axis=0;axis<2;++axis) {
+ const double step=.0001,px=x+(axis==0?step:0),py=y+(axis==1?step:0),mx=x-(axis==0?step:0),my=y-(axis==1?step:0);
+ const double numeric=(col?composed(px,py)-composed(mx,my):raw(px,py,level)-raw(mx,my,level))/(2*step);
+ const double error=std::abs(values[(row*columns+col)*4+1+axis]-numeric);
+ maxGradient=(std::max)(maxGradient,error);CHECK(error<.00004);
+ }
+ }
+ for(unsigned c=0;c<3;++c) {
+ const double error=std::abs(values[(row*columns+1)*4+c]-values[(row*columns+2)*4+c]);maxStage=(std::max)(maxStage,error);CHECK(error<.000001);
+ }
+ CHECK(values[(row*columns+1)*4]>=0 && values[(row*columns+1)*4]<=f.freeDamping[0]+.000001f);
+ if(f.offshore[0]==0) for(unsigned c=0;c<3;++c) CHECK(values[(row*columns+1)*4+c]==f.freeDamping[c]);
+ if(composed(x,y)<f.freeDamping[0]-.01)++hullWins;else if(f.freeDamping[0]>0 && f.freeDamping[0]<1)++freeWins;
+ const double missingOffshoreX=values[row*columns*4+1]*f.offshore[0];
+ if(std::abs(values[(row*columns+1)*4+1]-missingOffshoreX)>.001)++gradientControls;
+ const double shallow=(std::min)(double(WaterFftGeometry::SafeDamping(1,2.25f)),composed(x,y));
+ CHECK(-WaterFftGeometry::MaxVerticalDisplacement*shallow>=-2.100001);
+ }
+ for(float value:values)CHECK(std::isfinite(value));CHECK(hullWins>8 && freeWins>=2 && gradientControls>=2);
+ printf("sdl_gpu_frame_selfcheck: GPU analytic hull damping: %u fixtures, independent value %.8f/gradient %.8f/VS-PS %.8f; rotated/corner/final hull, level, min winner, offshore product, zero/floor bounds checked\n",rows,maxValue,maxGradient,maxStage);
+}
+
+static void check_gpu_water_wave_cage(SdlGpuFrame *frame)
+{
+ // The real water vertex wrapper reads VS3; the fragment mapping reads PS2. A
+ // curved bilinear terrain field exercises changing cage axes/radii and the final
+ // floor correction. The oracle samples the uploaded field and finite-differences
+ // the complete ellipsoid map, independently of the generated shader derivatives.
+ const unsigned side=16,width=8,height=8,plane=side*side*4;
+ struct Resources {
+ SDL_GPUDevice *device;SDL_GPUShader *vs=NULL,*ps=NULL;SDL_GPUGraphicsPipeline *pipeline=NULL;
+ SDL_GPUTexture *terrain[3]={},*spectrum=NULL,*zero=NULL,*targets[4]={};SDL_GPUSampler *sampler=NULL;
+ ~Resources(){if(pipeline)SDL_ReleaseGPUGraphicsPipeline(device,pipeline);if(vs)SDL_ReleaseGPUShader(device,vs);
+ if(ps)SDL_ReleaseGPUShader(device,ps);for(auto *t:terrain)if(t)SDL_ReleaseGPUTexture(device,t);
+ for(auto *t:targets)if(t)SDL_ReleaseGPUTexture(device,t);if(spectrum)SDL_ReleaseGPUTexture(device,spectrum);
+ if(zero)SDL_ReleaseGPUTexture(device,zero);if(sampler)SDL_ReleaseGPUSampler(device,sampler);}
+ } r;r.device=frame->Device();
+ VertexPipelineDescription vd={};vd.FVF=FF_FVF_XYZ|FF_FVF_NORMAL|FF_FVF_DIFFUSE|FF_FVF_TEX2;vd.StageCount=4;
+ vd.Stages[0].TextureCoordinateIndex=0;vd.Stages[1].TextureCoordinateIndex=1;
+ std::string vs;CHECK(VertexShader_Generate(vd,VERTEX_SHADER_TARGET_D3D11,vs));CHECK(WaterFftSampling::WrapVertex(vs,false,false));
+ CHECK(SDL3_Shader_Retarget(vs,true));
+ const std::string entry="Output main(Input input)";const size_t at=vs.find(entry);CHECK(at!=std::string::npos);if(at==std::string::npos)return;
+ vs.replace(at,entry.size(),"Output cageWaterVertex(Input input)");
+ const std::string fixture=R"HLSL(
+cbuffer Fixture:register(b2) {float4 ProbePoint;float4 ProbeControl;float4 ProbeEta;};
+)HLSL";
+ vs+=fixture+R"HLSL(
+struct CageProbe {float4 Position:SV_Position;float4 Displacement:TEXCOORD0;};
+CageProbe main(uint id:SV_VertexID) {
+ Input input=(Input)0;input.Position=float3(ProbePoint.xy,ProbePoint.z+ProbePoint.w);
+ input.Normal=ProbeControl.xyz;input.TexCoord1=float2(0,ProbePoint.z);
+ // The actual SDL vertex entry converts its packed BGRA attribute to RGBA.
+ input.Diffuse=float4(0,0,ProbeControl.w,1);
+ Output actual=cageWaterVertex(input);CageProbe o;
+ o.Displacement=float4(actual.Position.xyz-float3(ProbePoint.xy,ProbePoint.z),1);
+ o.Position=float4(id==1?3.0:-1.0,id==2?3.0:-1.0,0,1);return o;
+}
+)HLSL";
+ // Retarget the newly added fixture block; the actual fixed input was already retargeted.
+ const size_t fixtureAt=vs.find("cbuffer Fixture:register(b2)");CHECK(fixtureAt!=std::string::npos);
+ if(fixtureAt==std::string::npos)return;vs.replace(fixtureAt,strlen("cbuffer Fixture:register(b2)"),"cbuffer Fixture:register(b2,space1)");
+ std::string pixelFixture=fixture;pixelFixture.replace(pixelFixture.find("register(b2)"),strlen("register(b2)"),"register(b1)");
+ std::string ps=WaterFftSampling::UniformSource("WaterBlock",0)+pixelFixture+R"HLSL(
+Texture2D Texture2:register(t2);SamplerState Sampler2:register(s2);
+)HLSL"+WaterFftSampling::CommonSource()+WaterWaveCageShader::Source(false)+R"HLSL(
+struct CageProbe {float4 Position:SV_Position;float4 Displacement:TEXCOORD0;};
+struct Result {float4 Vertex:SV_Target0;float4 Pixel:SV_Target1;float4 DX:SV_Target2;float4 DY:SV_Target3;};
+Result main(CageProbe input) {
+ float2 p=ProbePoint.xy+(input.Position.xy-float2(4.5,4.5))*.625;
+ float3 etaX=float3(.07,-.03,.05),etaY=float3(-.02,.04,-.06);
+ float3 eta=ProbeEta.xyz+etaX*(p.x-ProbePoint.x)+etaY*(p.y-ProbePoint.y);
+ WaveCage c=waveCage(p,ProbePoint.z);
+ float3 obstacle=ProbeControl.w>0.0?float3(ProbeControl.w+.0003*(p.x-ProbePoint.x)-.0002*(p.y-ProbePoint.y),.0003,-.0002):float3(0,0,0);
+ WaveCageSurface mapped=waveCageSurface(c,p,ProbePoint.z,eta,etaX,etaY,obstacle,ddx(p),ddy(p));
+ Result o;o.Vertex=input.Displacement;o.Pixel=float4(mapped.displacement,c.support);
+ o.DX=float4(mapped.derivativeX,waveCageMap(c,eta).z*obstacle.x);
+ o.DY=float4(mapped.derivativeY,waveCageHeight(p+mapped.displacement.xy)-ProbePoint.z+.035);return o;
+}
+)HLSL";
+ CHECK(SDL3_Shader_Retarget(ps,false));
+ std::string error;std::vector<unsigned char> spirv;
+ bool compiled=SDL3_Compile_HLSL_To_SPIRV(vs,true,spirv,error);CHECK(compiled);if(!compiled){printf("wave cage VS: %s\n",error.c_str());return;}
+ unsigned samplers=0,buffers=0;SDL3_Shader_Slots(spirv,true,samplers,buffers);CHECK(samplers==4&&buffers==3);
+ r.vs=SDL3_Create_Shader(r.device,spirv,true,error);CHECK(r.vs);
+ compiled=SDL3_Compile_HLSL_To_SPIRV(ps,false,spirv,error);CHECK(compiled);if(!compiled){printf("wave cage PS: %s\n",error.c_str());return;}
+ r.ps=SDL3_Create_Shader(r.device,spirv,false,error);CHECK(r.ps);if(!r.vs||!r.ps)return;
+ SDL_GPUColorTargetDescription colours[4]={};for(auto &c:colours)c.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
+ SDL_GPUGraphicsPipelineCreateInfo pi={};pi.vertex_shader=r.vs;pi.fragment_shader=r.ps;pi.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;
+ pi.target_info.color_target_descriptions=colours;pi.target_info.num_color_targets=4;r.pipeline=SDL_CreateGPUGraphicsPipeline(r.device,&pi);CHECK(r.pipeline);if(!r.pipeline)return;
+ SDL_GPUTextureCreateInfo ti={};ti.type=SDL_GPU_TEXTURETYPE_2D;ti.format=colours[0].format;ti.layer_count_or_depth=ti.num_levels=1;
+ ti.width=ti.height=side;ti.usage=SDL_GPU_TEXTUREUSAGE_SAMPLER;for(auto &t:r.terrain)t=SDL_CreateGPUTexture(r.device,&ti);
+ ti.width=ti.height=1;r.spectrum=SDL_CreateGPUTexture(r.device,&ti);r.zero=SDL_CreateGPUTexture(r.device,&ti);
+ ti.width=width;ti.height=height;ti.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;for(auto &t:r.targets)t=SDL_CreateGPUTexture(r.device,&ti);
+ SDL_GPUSamplerCreateInfo si={};si.min_filter=si.mag_filter=SDL_GPU_FILTER_LINEAR;
+ si.address_mode_u=si.address_mode_v=si.address_mode_w=SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;r.sampler=SDL_CreateGPUSampler(r.device,&si);
+ for(auto *t:r.terrain){CHECK(t);if(!t)return;}for(auto *t:r.targets){CHECK(t);if(!t)return;}
+ CHECK(r.spectrum&&r.zero&&r.sampler);if(!r.spectrum||!r.zero||!r.sampler)return;
+ std::vector<float> texels(3*plane+8,0);
+ for(unsigned a=0;a<3;++a)for(unsigned y=0;y<side;++y)for(unsigned x=0;x<side;++x){
+ const double px=x*10,py=y*10;float *t=&texels[a*plane+(y*side+x)*4];
+ t[0]=float((20+.03*px+.02*py+.0001*px*py)/100);t[1]=float(.6+.001*px-.0005*py);t[2]=float(.45+.0001*px);t[3]=a==0?1:a==1?0:.4f;
+ }
+ texels[3*plane]=.025f;texels[3*plane+1]=.12f;texels[3*plane+2]=-.04f;
+ SDL_GPUTransferBufferCreateInfo tb={};tb.usage=SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD;tb.size=texels.size()*sizeof(float);
+ SDL_GPUTransferBuffer *transfer=SDL_CreateGPUTransferBuffer(r.device,&tb);CHECK(transfer);if(!transfer)return;
+ void *data=SDL_MapGPUTransferBuffer(r.device,transfer,false);CHECK(data);if(!data){SDL_ReleaseGPUTransferBuffer(r.device,transfer);return;}
+ memcpy(data,texels.data(),tb.size);SDL_UnmapGPUTransferBuffer(r.device,transfer);CHECK(frame->Flush());
+ SDL_GPUCommandBuffer *upload=SDL_AcquireGPUCommandBuffer(r.device);CHECK(upload);if(!upload){SDL_ReleaseGPUTransferBuffer(r.device,transfer);return;}
+ SDL_GPUCopyPass *copy=SDL_BeginGPUCopyPass(upload);CHECK(copy);
+ for(unsigned i=0;i<5;++i){SDL_GPUTextureTransferInfo from={};from.transfer_buffer=transfer;from.offset=(i<3?i*plane:3*plane+(i-3)*4)*sizeof(float);from.pixels_per_row=from.rows_per_layer=i<3?side:1;
+ SDL_GPUTextureRegion to={};to.texture=i<3?r.terrain[i]:i==3?r.spectrum:r.zero;to.w=to.h=i<3?side:1;to.d=1;SDL_UploadToGPUTexture(copy,&from,&to,false);}
+ SDL_EndGPUCopyPass(copy);CHECK(SDL_SubmitGPUCommandBuffer(upload));SDL_ReleaseGPUTransferBuffer(r.device,transfer);
+ auto sample=[&](unsigned channel,double x,double y){
+ const double gx=(std::max)(0.0,(std::min)(double(side-1),x/10)),gy=(std::max)(0.0,(std::min)(double(side-1),y/10));
+ const unsigned ix=unsigned(gx),iy=unsigned(gy),jx=(std::min)(ix+1,side-1),jy=(std::min)(iy+1,side-1);
+ return (texels[(iy*side+ix)*4+channel]*(1-(gx-ix))+texels[(iy*side+jx)*4+channel]*(gx-ix))*(1-(gy-iy))+
+ (texels[(jy*side+ix)*4+channel]*(1-(gx-ix))+texels[(jy*side+jx)*4+channel]*(gx-ix))*(gy-iy);
+ };
+ using V=std::array<double,3>;
+ const double bound=WaterFftGeometry::MaxVerticalDisplacement,horizontal=WaterFftGeometry::MaxHorizontalDisplacement/std::sqrt(2.0);
+ const V incident={horizontal*std::tanh(-1.2*WaterFftSampling::WorldScale*texels[3*plane]/horizontal),
+ horizontal*std::tanh(-1.2*WaterFftSampling::WorldScale*texels[3*plane+2]/horizontal),bound*std::tanh(WaterFftSampling::WorldScale*texels[3*plane+1]/bound)};
+ SdlVertexConstants fixed={};SdlWaterPixelConstants water={};for(unsigned i=0;i<4;++i){fixed.WorldViewProjection[i*5]=fixed.WorldView[i*5]=fixed.NormalTransform[i*5]=1;for(unsigned j=0;j<MAXIMUM_VERTEX_STAGES;++j)fixed.TextureMatrix[j][i*5]=1;}
+ water.TerrainParameters[1]=side*10;water.TerrainParameters[2]=100;water.FftParameters[0]=1;
+ struct Fixture {float point[4],control[4],eta[4];};
+ // Only the final floor probe uses non-dyadic texture coordinates, because its
+ // XY includes the nonlinear displacement. Bound that filtered height separately
+ // using Vulkan's minimum four subtexel bits and the uploaded adjacent differences.
+ // Ellipsoid values, zero-obstacle guards, stage agreement and the projection law
+ // still use strict tolerances; this bound cannot hide an omitted floor correction.
+ double floorFilterBound=0;
+ for(unsigned y=0;y+1<side;++y)for(unsigned x=0;x+1<side;++x){const double h=texels[(y*side+x)*4];
+ floorFilterBound=(std::max)(floorFilterBound,100*(std::abs(texels[(y*side+x+1)*4]-h)+std::abs(texels[((y+1)*side+x)*4]-h))/16);}
+ floorFilterBound+=.00001;
+ double maxVertex=0,maxValue=0,maxDerivative=0,maxFloor=0,maxProjection=0,maxStage=0,armed=0;unsigned checks=0;
+ for(unsigned mode=0;mode<11;++mode){
+ Fixture f={{35,45,0,.4f},{1,.04f,0,.7f},{}};f.point[2]=float(sample(0,35,45)*100+(mode==2||mode==10?0:mode==0?2:12));
+ if(mode==1){f.control[0]=.45f;f.control[1]=.6f;f.control[2]=.65f;}if(mode>=9)f.control[3]=0;
+ for(unsigned c=0;c<3;++c)f.eta[c]=mode==3?0:float(incident[c]);
+ water.TerrainParameters[3]=mode==5?0:1;water.OpticalParameters[3]=mode==6?0:1;water.WaterParameters[1]=mode==7?1:0;
+ const unsigned field=mode==4?1:mode==8?2:0;const bool active=mode!=4&&mode!=5&&mode!=6&&mode!=7;
+ const double support=active?(mode==8?double(.4f):1):0;
+ auto mapped=[&](double x,double y,bool varying,bool project=true){
+ const double dx=x-f.point[0],dy=y-f.point[1];V eta={f.eta[0],f.eta[1],f.eta[2]};
+ if(varying){eta[0]+=.07*dx-.02*dy;eta[1]+=-.03*dx+.04*dy;eta[2]+=.05*dx-.06*dy;}
+ const double gx=5*(sample(0,x+10,y)-sample(0,x-10,y)),gy=5*(sample(0,x,y+10)-sample(0,x,y-10)),nl=std::sqrt(1+gx*gx+gy*gy);
+ const V n={-gx/nl,-gy/nl,1/nl};const double rt=active?sample(1,x,y)*bound:0,rn=active?(std::min)(sample(2,x,y)*bound,std::abs(f.point[2]-sample(0,x,y)*100)/nl):0;
+ const double length=std::sqrt(eta[0]*eta[0]+eta[1]*eta[1]+eta[2]*eta[2]),scale=length?std::tanh(length/bound)/length:1/bound;
+ const double along=(eta[0]*n[0]+eta[1]*n[1]+eta[2]*n[2])*scale,obstacle=f.control[3]>0?f.control[3]+(varying?.0003*dx-.0002*dy:0):0;
+ V out;for(unsigned c=0;c<3;++c)out[c]=(rt*(eta[c]*scale-along*n[c])+rn*along*n[c])*obstacle;
+ if(project&&active&&obstacle>0)out[2]=(std::min)(bound,(std::max)(out[2],sample(0,x+out[0],y+out[1])*100-f.point[2]+.035));return out;
+ };
+ V expected=mapped(f.point[0],f.point[1],false);for(unsigned c=0;c<3;++c){const double legacy=c==2?f.point[3]*(1-f.control[0])+f.eta[c]*f.control[1]*f.control[0]:f.eta[c]*f.control[0]*f.control[2]*f.control[1];
+ expected[c]=legacy*(1-support)+(c==2?f.point[3]*(1-f.control[0])+expected[c]*f.control[0]:expected[c]*f.control[0])*support;
+ if(mode==0)armed=(std::max)(armed,std::abs(expected[c]-legacy));}
+ SDL_GPUCommandBuffer *commands=SDL_AcquireGPUCommandBuffer(r.device);CHECK(commands);if(!commands)return;
+ SDL_GPUColorTargetInfo attachments[4]={};for(unsigned i=0;i<4;++i){attachments[i].texture=r.targets[i];attachments[i].load_op=SDL_GPU_LOADOP_CLEAR;attachments[i].store_op=SDL_GPU_STOREOP_STORE;}
+ SDL_GPURenderPass *pass=SDL_BeginGPURenderPass(commands,attachments,4,NULL);CHECK(pass);SDL_BindGPUGraphicsPipeline(pass,r.pipeline);
+ SDL_GPUTextureSamplerBinding vb[4]={{mode==3?r.zero:r.spectrum,r.sampler},{r.zero,r.sampler},{r.zero,r.sampler},{r.terrain[field],r.sampler}};
+ SDL_GPUTextureSamplerBinding pb[3]={{r.zero,r.sampler},{r.zero,r.sampler},{r.terrain[field],r.sampler}};
+ SDL_BindGPUVertexSamplers(pass,0,vb,4);SDL_BindGPUFragmentSamplers(pass,0,pb,3);
+ SDL_PushGPUVertexUniformData(commands,0,&fixed,sizeof(fixed));SDL_PushGPUVertexUniformData(commands,1,&water,sizeof(water));SDL_PushGPUVertexUniformData(commands,2,&f,sizeof(f));
+ SDL_PushGPUFragmentUniformData(commands,0,&water,sizeof(water));SDL_PushGPUFragmentUniformData(commands,1,&f,sizeof(f));
+ SDL_DrawGPUPrimitives(pass,3,1,0,0);SDL_EndGPURenderPass(pass);CHECK(SDL_SubmitGPUCommandBuffer(commands));
+ const auto values=read_float_targets(frame,r.targets,4,width,height);CHECK(values.size()==width*height*16);if(values.size()!=width*height*16)return;
+ auto value=[&](unsigned target,unsigned x,unsigned y,unsigned c){return double(values[((target*height+y)*width+x)*4+c]);};
+ double caseVertex=0,caseValue=0,caseDerivative=0;
+ for(unsigned y=0;y<height;++y)for(unsigned x=0;x<width;++x){const double px=f.point[0]+(x-4.0)*.625,py=f.point[1]+(y-4.0)*.625;const V pixel=mapped(px,py,true),unprojected=mapped(px,py,true,false);
+ for(unsigned c=0;c<3;++c){const double ve=std::abs(value(0,x,y,c)-expected[c]),pe=std::abs(value(1,x,y,c)-pixel[c]);
+ if(mode==2&&c==2)maxFloor=(std::max)(maxFloor,(std::max)(ve,pe));
+ else {caseVertex=(std::max)(caseVertex,ve);caseValue=(std::max)(caseValue,pe);}}
+ caseValue=(std::max)(caseValue,std::abs(value(2,x,y,3)-unprojected[2]));
+ if(mode==2)maxProjection=(std::max)(maxProjection,std::abs(value(1,x,y,2)-(std::min)(bound,(std::max)(value(2,x,y,3),value(3,x,y,3)))));
+ CHECK(std::abs(value(1,x,y,3)-support)<.00001);
+ // The exact waterline has an abs-depth cusp. Check its positions and floor
+ // clearance; differentiability is exercised on either smooth side instead.
+ if(active&&mode!=2)for(unsigned axis=0;axis<2;++axis){const double e=.001;const V a=mapped(px+(axis==0?e:0),py+(axis==1?e:0),true),b=mapped(px-(axis==0?e:0),py-(axis==1?e:0),true);
+ for(unsigned c=0;c<3;++c)caseDerivative=(std::max)(caseDerivative,std::abs(value(2+axis,x,y,c)-(a[c]-b[c])/(2*e)));++checks;}
+ }
+ if(f.control[0]==1)for(unsigned c=0;c<3;++c)maxStage=(std::max)(maxStage,std::abs(value(0,4,4,c)-value(1,4,4,c)*support-f.eta[c]*f.control[1]*(1-support)*(c==2?1:f.control[2])));
+ if(mode==2)CHECK(value(1,4,4,2)-value(2,4,4,3)>.02); // Armed: removing floor projection fails despite its sampling bound.
+ if(caseVertex>=.0001||caseValue>=.0001||caseDerivative>=.003)printf("wave cage case%u: vertex %.9f, value %.9f, derivative %.9f, center vertex/pixel z %.9f/%.9f, before-floor %.9f\n",mode,caseVertex,caseValue,caseDerivative,value(0,4,4,2),value(1,4,4,2),value(2,4,4,3));
+ maxVertex=(std::max)(maxVertex,caseVertex);maxValue=(std::max)(maxValue,caseValue);maxDerivative=(std::max)(maxDerivative,caseDerivative);
+ for(float v:values)CHECK(std::isfinite(v));
+ }
+ CHECK(maxVertex<.0001&&maxValue<.0001&&maxDerivative<.0002&&maxStage<.00001&&maxProjection<.00001&&maxFloor<floorFilterBound);CHECK(armed>.1&&checks>500);
+ printf("sdl_gpu_frame_selfcheck: GPU wave cages: VS3/PS2 real wrapper %.8f, independent map %.8f, full spatial derivative %.8f (%u checks), stage %.8f/projection %.8f/floor filter %.8f bound %.8f, armed legacy coast delta %.5f; waterline, zero, partial support, obstacle and four fallback guards checked\n",maxVertex,maxValue,maxDerivative,checks,maxStage,maxProjection,maxFloor,floorFilterBound,armed);
+}
+
+#if defined(__linux__)
+static void check_gpu_water_hull_normal(SdlGpuFrame *frame)
+{
+ // A constant spectral height has zero spectral slope. Its production normal is therefore
+ // independently the derivative of the analytic hull envelope. Changing a coarse quad's
+ // diagonal must not change that normal; the old interpolated-envelope control must change it.
+ const unsigned width=96,height=32;
+ struct Resources {
+ SDL_GPUDevice *device;SDL_GPUShader *vertex=NULL,*pixel=NULL;SDL_GPUGraphicsPipeline *pipeline=NULL;
+ SDL_GPUTexture *target=NULL,*white=NULL,*zero=NULL,*displacement=NULL;SDL_GPUSampler *sampler=NULL;
+ ~Resources(){if(pipeline)SDL_ReleaseGPUGraphicsPipeline(device,pipeline);if(vertex)SDL_ReleaseGPUShader(device,vertex);
+ if(pixel)SDL_ReleaseGPUShader(device,pixel);for(auto *t:{target,white,zero,displacement})if(t)SDL_ReleaseGPUTexture(device,t);
+ if(sampler)SDL_ReleaseGPUSampler(device,sampler);}
+ } resources;
+ resources.device=frame->Device();
+ const char *previous=getenv("ZH_WATER_DEBUG");const bool hadDebug=previous!=NULL;const std::string oldDebug=previous?previous:"";
+ CHECK(setenv("ZH_WATER_DEBUG","normal",1)==0);
+ PixelPipelineDescription pd={};std::string ps;const bool generated=EngineShader_Pixel_Program(ENGINE_SHADER_WATER_TRAPEZOID,pd,ps,COMBINER_SHADER_TARGET_SDL3_GPU);
+ if(hadDebug)CHECK(setenv("ZH_WATER_DEBUG",oldDebug.c_str(),1)==0);else CHECK(unsetenv("ZH_WATER_DEBUG")==0);
+ CHECK(generated);if(!generated)return;
+ VertexPipelineDescription vd={};vd.FVF=FF_FVF_XYZ|FF_FVF_NORMAL|FF_FVF_DIFFUSE|FF_FVF_TEX2;vd.StageCount=4;
+ vd.Stages[0].TextureCoordinateIndex=0;vd.Stages[1].TextureCoordinateIndex=1;
+ std::string vs;CHECK(VertexShader_Generate(vd,VERTEX_SHADER_TARGET_D3D11,vs));CHECK(WaterFftSampling::WrapVertex(vs));
+ CHECK(SDL3_Shader_Retarget(vs,true));
+ const std::string entry="Output main(Input input)";const size_t at=vs.find(entry);CHECK(at!=std::string::npos);if(at==std::string::npos)return;
+ vs.replace(at,entry.size(),"Output hullFixtureWaterVertex(Input input)");
+ vs+=R"HLSL(
+cbuffer Fixture:register(b2,space1) {float4 FixtureControls;};
+Output main(uint id:SV_VertexID) {
+ // Two diagonals through the same asymmetric quad. A corner and its nearby straight hull
+ // edge both cross the domain, so interpolating the old envelope is measurably non-planar.
+ uint c;
+ if(FixtureControls.x<0.5) c=id==0?0:id==1?1:id==2?2:id==3?0:id==4?2:3;
+ else c=id==0?0:id==1?1:id==2?3:id==3?1:id==4?2:3;
+ float2 p=float2(c==0||c==3?-24.0:28.0,c<2?4.0:17.0);
+ Input input=(Input)0;input.Position=float3(p,0.5);input.Diffuse=float4(0,0,0,1);
+ input.Normal=float3(FixtureControls.z,FixtureControls.w,1);
+ if(FixtureControls.y>0.5) {
+ input.Normal.y=min(input.Normal.y,vesselHullDamping(p,0.5).x);
+ input.Normal.z=0; // armed pre-fix path: transport the hull-combined vertex damping
+ }
+ input.TexCoord1=float2(0,0.5);
+ Output o=hullFixtureWaterVertex(input);
+ // Keep an exact parameter-space atlas after executing the production vertex wrapper.
+ // Its displacement was checked separately; its actual Specular/TC2 transport stays intact.
+ o.Position=float4((p.x-2.0)/26.0,(p.y-10.5)/6.5,0.5,1);
+ return o;
+}
+)HLSL";
+ std::string error;std::vector<unsigned char> spirv;
+ bool compiled=SDL3_Compile_HLSL_To_SPIRV(vs,true,spirv,error);CHECK(compiled);
+ if(!compiled){printf("hull normal VS: %s\n",error.c_str());return;}
+ resources.vertex=SDL3_Create_Shader(resources.device,spirv,true,error);CHECK(resources.vertex);
+ compiled=SDL3_Compile_HLSL_To_SPIRV(ps,false,spirv,error);CHECK(compiled);
+ if(!compiled){printf("hull normal PS: %s\n",error.c_str());return;}
+ unsigned samplers=0,uniforms=0;SDL3_Shader_Slots(spirv,false,samplers,uniforms);CHECK(samplers<=16 && uniforms==(WaterHullVisual::Enabled()?4u:1u));
+ resources.pixel=SDL3_Create_Shader(resources.device,spirv,false,error);CHECK(resources.pixel);
+ SDL_GPUColorTargetDescription colour={};colour.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
+ SDL_GPUGraphicsPipelineCreateInfo pi={};pi.vertex_shader=resources.vertex;pi.fragment_shader=resources.pixel;
+ pi.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;pi.target_info.color_target_descriptions=&colour;pi.target_info.num_color_targets=1;
+ resources.pipeline=SDL_CreateGPUGraphicsPipeline(resources.device,&pi);CHECK(resources.pipeline);if(!resources.pipeline)return;
+ SDL_GPUTextureCreateInfo ti={};ti.type=SDL_GPU_TEXTURETYPE_2D;ti.format=colour.format;ti.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;
+ ti.width=width;ti.height=height;ti.layer_count_or_depth=ti.num_levels=1;resources.target=SDL_CreateGPUTexture(resources.device,&ti);
+ ti.width=ti.height=1;ti.usage|=SDL_GPU_TEXTUREUSAGE_SAMPLER;
+ resources.white=SDL_CreateGPUTexture(resources.device,&ti);resources.zero=SDL_CreateGPUTexture(resources.device,&ti);resources.displacement=SDL_CreateGPUTexture(resources.device,&ti);
+ SDL_GPUSamplerCreateInfo si={};si.min_filter=si.mag_filter=SDL_GPU_FILTER_NEAREST;resources.sampler=SDL_CreateGPUSampler(resources.device,&si);
+ CHECK(resources.target && resources.white && resources.zero && resources.displacement && resources.sampler);
+ if(!resources.target || !resources.white || !resources.zero || !resources.displacement || !resources.sampler)return;
+ SdlVertexConstants vertex={};SdlWaterPixelConstants water={};
+ for(unsigned i=0;i<4;++i) {
+ vertex.WorldViewProjection[i*5]=vertex.WorldView[i*5]=vertex.NormalTransform[i*5]=1;water.WorldFromClip[i*5]=1;
+ for(unsigned stage=0;stage<MAXIMUM_VERTEX_STAGES;++stage)vertex.TextureMatrix[stage][i*5]=1;
+ }
+ water.WorldFromClip[0]=26;water.WorldFromClip[5]=6.5f;water.WorldFromClip[12]=2;water.WorldFromClip[13]=10.5f;
+ water.Viewport[2]=width;water.Viewport[3]=height;water.CameraPosition[2]=100;
+ water.SunDirection[2]=1;water.SunColour[0]=water.SunColour[1]=water.SunColour[2]=1;
+ water.TerrainParameters[1]=100;water.SceneParameters[1]=water.SceneParameters[2]=1;
+ water.OpticalParameters[0]=3;water.OpticalParameters[1]=water.OpticalParameters[2]=1;
+ water.FftParameters[0]=1;water.FftParameters[1]=0; // isolate clearance from optional reflected/generated waves
+ water.HullParameters[0]=1;water.HullData[0][2]=.5f;water.HullData[0][3]=4;
+ water.HullData[1][0]=1;water.HullData[1][2]=20;water.HullData[1][3]=6;
+ const float outline[8]={-20,-6,20,-6,20,6,-20,6};memcpy(water.HullData[4],outline,sizeof(outline));
+ CHECK(frame->Flush());unsigned renders=0;
+ auto render=[&](unsigned diagonal,bool coarse,float weight,float freeDamping) {
+ SDL_GPUCommandBuffer *commands=SDL_AcquireGPUCommandBuffer(resources.device);CHECK(commands);
+ SDL_GPUColorTargetInfo attachment={};attachment.load_op=SDL_GPU_LOADOP_CLEAR;attachment.store_op=SDL_GPU_STOREOP_STORE;
+ for(unsigned i=0;i<3;++i) {
+ attachment.texture=i==0?resources.white:i==1?resources.zero:resources.displacement;
+ attachment.clear_color={i==0?1.0f:0.0f,i==0?1.0f:i==2?.05f:0.0f,i==0?1.0f:0.0f,i==0?1.0f:0.0f};
+ SDL_GPURenderPass *pass=SDL_BeginGPURenderPass(commands,&attachment,1,NULL);CHECK(pass);SDL_EndGPURenderPass(pass);
+ }
+ attachment.texture=resources.target;attachment.clear_color={0,0,0,0};
+ SDL_GPURenderPass *pass=SDL_BeginGPURenderPass(commands,&attachment,1,NULL);CHECK(pass);SDL_BindGPUGraphicsPipeline(pass,resources.pipeline);
+ SDL_GPUTextureSamplerBinding bindings[16]={};for(unsigned i=0;i<samplers;++i) {
+ bindings[i].texture=i<8?resources.white:i==8?resources.displacement:resources.zero;bindings[i].sampler=resources.sampler;
+ }
+ SDL_BindGPUFragmentSamplers(pass,0,bindings,samplers);
+ SDL_GPUTextureSamplerBinding vertexBindings[4]={{resources.displacement,resources.sampler},{resources.zero,resources.sampler},{resources.zero,resources.sampler},{resources.zero,resources.sampler}};
+ SDL_BindGPUVertexSamplers(pass,0,vertexBindings,4); // TerrainParameters.w=0 preserves this hull-only fixture.
+ const float controls[4]={float(diagonal),coarse?1.0f:0.0f,weight,freeDamping};
+ SDL_PushGPUVertexUniformData(commands,0,&vertex,sizeof(vertex));SDL_PushGPUVertexUniformData(commands,1,&water,sizeof(water));
+ SDL_PushGPUVertexUniformData(commands,2,controls,sizeof(controls));push_empty_visual_water(commands,water);
+ SDL_DrawGPUPrimitives(pass,6,1,0,0);SDL_EndGPURenderPass(pass);CHECK(SDL_SubmitGPUCommandBuffer(commands));++renders;
+ return read_float_targets(frame,&resources.target,1,width,height);
+ };
+ const auto first=render(0,false,1,1),second=render(1,false,1,1);
+ const auto coarseFirst=render(0,true,1,1),coarseSecond=render(1,true,1,1);
+ const auto seam=render(0,false,0,1),floor=render(1,false,1,WaterFftGeometry::SafeDamping(1,2.25f));
+ CHECK(first.size()==width*height*4 && second.size()==first.size() && coarseFirst.size()==first.size() && coarseSecond.size()==first.size() && seam.size()==first.size() && floor.size()==first.size());
+ if(first.size()!=width*height*4 || second.size()!=first.size() || coarseFirst.size()!=first.size() || coarseSecond.size()!=first.size() || seam.size()!=first.size() || floor.size()!=first.size())return;
+ const double waveHeight=WaterFftGeometry::MaxVerticalDisplacement*std::tanh(1.0/WaterFftGeometry::MaxVerticalDisplacement);
+ double maximumError=0,maximumDiagonal=0,maximumControl=0,maximumSeam=0,maximumFloor=0;unsigned controls=0,active=0;
+ for(unsigned y=1;y<height-1;++y)for(unsigned x=1;x<width-1;++x) {
+ const double px=-24+52*(x+.5)/width,py=17-13*(y+.5)/height;
+ const double sx=px<-20?px+20:px>20?px-20:0,sy=py>6?py-6:py<-6?py+6:0,distance=std::hypot(sx,sy);
+ const double t=(std::min)(1.0,distance/9),damping=t*t*(3-2*t),slope=6*t*(1-t)/9;
+ const double gx=distance>0?slope*sx/distance:0,gy=distance>0?slope*sy/distance:0;
+ const double normalLength=std::sqrt(1+waveHeight*waveHeight*(gx*gx+gy*gy));
+ const double normal[3]={-waveHeight*gx/normalLength,-waveHeight*gy/normalLength,1/normalLength};
+ const bool floorWins=WaterFftGeometry::SafeDamping(1,2.25f)<=damping;
+ for(unsigned c=0;c<3;++c) {
+ const unsigned offset=(y*width+x)*4+c;
+ const double error=std::abs(first[offset]-(.5+.5*normal[c]));maximumError=(std::max)(maximumError,error);
+ maximumDiagonal=(std::max)(maximumDiagonal,double(std::abs(first[offset]-second[offset])));
+ const double control=std::abs(coarseFirst[offset]-coarseSecond[offset]);maximumControl=(std::max)(maximumControl,control);controls+=control>.005;
+ maximumSeam=(std::max)(maximumSeam,std::abs(seam[offset]-(c==2?1.0:.5)));
+ const double expected=floorWins?(c==2?1.0:.5):(.5+.5*normal[c]);maximumFloor=(std::max)(maximumFloor,std::abs(floor[offset]-expected));
+ }
+ active+=std::abs(normal[0])+std::abs(normal[1])>.08;
+ }
+ for(const auto *image:{&first,&second,&coarseFirst,&coarseSecond,&seam,&floor})for(float v:*image)CHECK(std::isfinite(v));
+ CHECK(maximumError<.0001 && maximumDiagonal<.0001 && maximumFloor<.0001 && maximumSeam<.0001);
+ CHECK(active>200 && maximumControl>.01 && controls>100);
+ printf("sdl_gpu_frame_selfcheck: GPU production hull normal: %u renders, independent normal %.8f/diagonal %.8f/floor %.8f/zero-weight %.8f; armed interpolated damping diagonal error %.8f (%u components), disabled vessel-wave gate checked\n",renders,maximumError,maximumDiagonal,maximumFloor,maximumSeam,maximumControl,controls);
+}
+#endif // __linux__
+
+#include "WaterBowShoulderTest.h"
+static void check_gpu_water_bow_shoulder(SdlGpuFrame *frame)
+{
+ namespace T=WaterBowShoulderTest;using WaterHullModel::Hull;
+ Hull hulls[8];hulls[0]=T::hull();hulls[1]=T::hull(-40);hulls[2]=T::hull(40,.63);
+ hulls[3]=T::hull();hulls[3].data[2][0]=0;hulls[3].data[2][1]=40;
+ hulls[4]=T::hull(.3);hulls[5]=T::hull();hulls[5].data[0][3]=0;
+ hulls[6]=T::hull();hulls[6].data[0][3]=13;hulls[7]=T::scaledHull(280,54);
+ struct Fixture {float x,y,level,h;};std::vector<Fixture> fixtures;
+ auto add=[&](unsigned h,float x,float y,float level=4) {
+ const auto &v=hulls[h];fixtures.push_back({v.data[0][0]+x*v.data[1][0]-y*v.data[1][1],
+ v.data[0][1]+x*v.data[1][1]+y*v.data[1][0],level,float(h)});
+ };
+ for(unsigned h=0;h<8;++h){add(h,42.025f,0);add(h,33,-7.5f);add(h,-42.025f,0);add(h,0,11.025f);}
+ add(0,42.025f,0,5);add(0,55,0);add(0,40,0);add(0,42.025f,0); // wrong level/compact/exact vertex/repeat
+ add(7,286,0);add(7,292,0);add(7,298,0);add(7,322,0); // carrier cap/wing/derivative/compact
+ const unsigned rows=unsigned(fixtures.size()),columns=12;
+ std::string common="cbuffer BowShoulderFixtures : register(b0) {float4 HullData[80];float4 Fixture["+std::to_string(rows)+"];};\nstatic const float4 HullParameters=float4(8,0,0,0);\n";
+ common+=WaterFftSampling::CommonSource()+WaterVesselWaves::Source(false,true);
+ common+=R"HLSL(
+float3 shoulderEval(uint row,uint col) {
+ float4 f=Fixture[row];int h=(int)f.w;float2 p=f.xy;
+ if(col>=6&&col<=9)p+=col==6?float2(.015625,0):col==7?float2(-.015625,0):col==8?float2(0,.015625):float2(0,-.015625);
+ float3 direct=vesselGeneratedBow(p,f.z,h),oldBow;
+ float3 old=vesselGeneratedWave(p,f.z,4.0,h,oldBow);
+ if(col==0)return direct;
+ if(col==4)return old;
+ float phase=.013*p.x-.017*p.y;
+ float3 raw=float3(2.0*sin(.07*p.x+.025*p.y),1.5*cos(.035*p.x-.045*p.y),0);
+ float3 rawX=float3(.14*cos(.07*p.x+.025*p.y),-.0525*sin(.035*p.x-.045*p.y),0);
+ float3 rawY=float3(.05*cos(.07*p.x+.025*p.y),.0675*sin(.035*p.x-.045*p.y),0);
+ float3 scale=float3(.5+.1*sin(phase),.0013*cos(phase),-.0017*cos(phase));
+ if(col==3){raw=0;rawX=0;rawY=0;}
+ FftHorizontalRegistration map=fftHorizontalRegistration(p,raw,rawX,rawY,scale);
+ float3 mapped=vesselGeneratedBow(map.position,f.z,h);
+ mapped.yz=float2(dot(mapped.yz,map.derivativeX),dot(mapped.yz,map.derivativeY));
+ float3 result=old+mapped-oldBow;
+ if(col==2)return (result-mapped)-(old-oldBow);
+ if(col==5)return result-mapped; // unchanged stern, including time/phase
+ if(col==10)return mapped;
+ return result;
+}
+)HLSL";
+ std::string vs=common+
+ "struct Output {float4 position:SV_Position;nointerpolation float3 value:TEXCOORD0;};\n"
+ "Output main(uint id:SV_VertexID){uint cell=id/6,row=cell/"+std::to_string(columns)+",col=cell%"+std::to_string(columns)+";"
+ "uint v=id%6;float2 corner=v==0?float2(0,0):v==1?float2(1,0):v==2?float2(0,1):v==3?float2(0,1):v==4?float2(1,0):float2(1,1);"
+ "Output o;o.position=float4((float2(col,row)+corner)/float2("+std::to_string(columns)+","+std::to_string(rows)+")*float2(2,-2)+float2(-1,1),0,1);o.value=shoulderEval(row,col);return o;}";
+ std::string ps=common+R"HLSL(
+float4 main(float4 p:SV_Position,nointerpolation float3 value:TEXCOORD0):SV_Target0 {
+ uint row=(uint)p.y,col=(uint)p.x;float3 result=shoulderEval(row,col);
+ return float4(col==11?abs(result-value):result,0);
+})HLSL";
+ const bool placed=sdl3target_detail::place_registers(vs,true)&&sdl3target_detail::place_registers(ps,false);CHECK(placed);if(!placed)return;
+ std::vector<unsigned char> spirv;std::string error;
+ bool compiled=SDL3_Compile_HLSL_To_SPIRV(vs,true,spirv,error);CHECK(compiled);if(!compiled){printf("shoulder VS: %s\n",error.c_str());return;}
+ SDL_GPUShader *vertex=SDL3_Create_Shader(frame->Device(),spirv,true,error);CHECK(vertex);if(!vertex)return;
+ compiled=SDL3_Compile_HLSL_To_SPIRV(ps,false,spirv,error);CHECK(compiled);
+ if(!compiled){printf("shoulder PS: %s\n",error.c_str());SDL_ReleaseGPUShader(frame->Device(),vertex);return;}
+ SDL_GPUShader *pixel=SDL3_Create_Shader(frame->Device(),spirv,false,error);CHECK(pixel);
+ SDL_GPUColorTargetDescription colour={};colour.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
+ SDL_GPUGraphicsPipelineCreateInfo info={};info.vertex_shader=vertex;info.fragment_shader=pixel;
+ info.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;info.target_info.color_target_descriptions=&colour;info.target_info.num_color_targets=1;
+ SDL_GPUGraphicsPipeline *pipeline=pixel?SDL_CreateGPUGraphicsPipeline(frame->Device(),&info):NULL;CHECK(pipeline);
+ SDL_GPUTextureCreateInfo ti={};ti.type=SDL_GPU_TEXTURETYPE_2D;ti.format=colour.format;ti.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;
+ ti.width=columns;ti.height=rows;ti.layer_count_or_depth=ti.num_levels=1;
+ SDL_GPUTexture *target=SDL_CreateGPUTexture(frame->Device(),&ti);CHECK(target);
+ if(pipeline&&target) {
+ std::vector<float> uniforms(80*4+rows*4);memcpy(uniforms.data(),hulls,sizeof(hulls));memcpy(uniforms.data()+80*4,fixtures.data(),fixtures.size()*sizeof(Fixture));
+ CHECK(uniforms.size()*sizeof(float)<=4096);CHECK(frame->Flush());
+ SDL_GPUCommandBuffer *commands=SDL_AcquireGPUCommandBuffer(frame->Device());CHECK(commands);
+ if(commands){SDL_GPUColorTargetInfo attachment={};attachment.texture=target;attachment.load_op=SDL_GPU_LOADOP_DONT_CARE;attachment.store_op=SDL_GPU_STOREOP_STORE;
+ SDL_GPURenderPass *pass=SDL_BeginGPURenderPass(commands,&attachment,1,NULL);CHECK(pass);
+ if(pass){SDL_BindGPUGraphicsPipeline(pass,pipeline);SDL_PushGPUVertexUniformData(commands,0,uniforms.data(),uniforms.size()*sizeof(float));SDL_PushGPUFragmentUniformData(commands,0,uniforms.data(),uniforms.size()*sizeof(float));
+ SDL_DrawGPUPrimitives(pass,rows*columns*6,1,0,0);SDL_EndGPURenderPass(pass);}
+ CHECK(SDL_SubmitGPUCommandBuffer(commands));
+ const auto pixels=read_float_targets(frame,&target,1,columns,rows);
+ auto at=[&](unsigned r,unsigned c,unsigned k){return double(pixels[(r*columns+c)*4+k]);};
+ double maxValue=0,maxDerivative=0,maxParity=0,maxStern=0;unsigned armed=0;
+ auto scalar=[&](unsigned row,double x,double y,bool mapped,bool stern) {
+ const auto &f=fixtures[row];const auto &h=hulls[unsigned(f.h)];
+ if(h.data[0][3]<3||std::abs(f.level-h.data[0][2])>.1)return 0.;
+ double wake=0;vessel_test_packet(h,x,y,f.level,4,&wake);
+ if(h.data[0][3]>12)return stern?wake:0.;
+ if(mapped){double phase=.013*x-.017*y,scale=.5+.1*std::sin(phase),bound=8/std::sqrt(2.);
+ double px=x+scale*bound*std::tanh(2*std::sin(.07*x+.025*y)/bound),py=y+scale*bound*std::tanh(1.5*std::cos(.035*x-.045*y)/bound);x=px;y=py;}
+ return T::oracle(h,x,y)+(stern?wake:0);
+ };
+ for(unsigned r=0;r<rows;++r){const auto &f=fixtures[r];const auto &h=hulls[unsigned(f.h)];
+ for(unsigned col=0;col<columns;++col)for(unsigned c=0;c<4;++c)CHECK(std::isfinite(at(r,col,c)));
+ for(unsigned col:{0u,1u,3u}) {
+ const double expected=scalar(r,f.x,f.y,col==1,col!=0),error=std::abs(at(r,col,0)-expected);maxValue=(std::max)(maxValue,error);CHECK(error<.00003);
+ // Exact vertex has a legitimate derivative crease, tested for finite value only.
+ if(r!=34)for(unsigned k=0;k<2;++k){const double e=.0001;double plus=scalar(r,f.x+(k==0?e:0),f.y+(k==1?e:0),col==1,col!=0),minus=scalar(r,f.x-(k==0?e:0),f.y-(k==1?e:0),col==1,col!=0);
+ const double diff=std::abs(at(r,col,k+1)-(plus-minus)/(2*e));maxDerivative=(std::max)(maxDerivative,diff);CHECK(diff<.00006);}
+ }
+ double stern=0;vessel_test_packet(h,f.x,f.y,f.level,4,&stern);
+ // Invalid-count row6 is explicitly unsupported for shoulder; legacy packet
+ // itself had no upper-count check, so exclude it from its unrelated oracle.
+ if(h.data[0][3]<=12){maxStern=(std::max)(maxStern,std::abs(at(r,5,0)-stern));CHECK(std::abs(at(r,5,0)-stern)<.00003);}
+ for(unsigned c=0;c<3;++c){CHECK(std::abs(at(r,2,c))<.000004);maxParity=(std::max)(maxParity,at(r,11,c));CHECK(at(r,11,c)<.000003);}
+ if(at(r,0,0)>.1)++armed;
+ }
+ CHECK(armed>=6);CHECK(at(0,0,0)>.1&&at(1,0,0)>.1&&at(2,0,0)==0);
+ for(unsigned r=16;r<28;++r)CHECK(at(r,0,0)==0);
+ CHECK(at(32,0,0)==0&&at(33,0,0)==0);
+ CHECK(at(36,0,0)>5 && at(37,0,0)>4 && at(38,0,0)>1 && at(39,0,0)==0);
+ const auto &wide=fixtures[37];
+ CHECK(at(37,0,0)-T::oracle(hulls[7],wide.x,wide.y,6)>3); // armed old-cap control
+ for(unsigned c=0;c<3;++c)CHECK(at(0,0,c)==at(35,0,c));
+ printf("sdl_gpu_frame_selfcheck: GPU contour shoulder %u rows: scalar %.8g, independent derivative %.8g, VS/PS %.8g, stern %.8g; rest/reverse/broadside/rotated/unsupported/compact/zerochop/pause checked\n",rows,maxValue,maxDerivative,maxParity,maxStern);
+ }
+ }
+ if(target)SDL_ReleaseGPUTexture(frame->Device(),target);if(pipeline)SDL_ReleaseGPUGraphicsPipeline(frame->Device(),pipeline);
+ if(pixel)SDL_ReleaseGPUShader(frame->Device(),pixel);SDL_ReleaseGPUShader(frame->Device(),vertex);
+}
+
+static void check_gpu_water_bow_refinement(SdlGpuFrame *frame)
+{
+ // Exercise the actual nonlinear water vertex wrapper over production subdivision output.
+ // The independent raster oracle uses uploaded texels, fresh world-space metadata and affine
+ // barycentrics. It does not copy the refinement constructor or the vertex shader source.
+ using namespace WaterBowRefinement;
+ const unsigned width=80,height=64,side=32,maxNodes=32,maxIndices=128;
+ struct Fixture {float vertex[maxNodes][3][4];uint32_t indices[maxIndices];};
+ static_assert(sizeof(Fixture)==2048,"SDL Vulkan uniform section bound");
+ struct Resources {
+ SDL_GPUDevice *device;SDL_GPUShader *vs=NULL,*ps=NULL;SDL_GPUGraphicsPipeline *pipeline=NULL;
+ SDL_GPUTexture *field=NULL,*zero=NULL,*targets[2]={};SDL_GPUSampler *sampler=NULL;
+ ~Resources(){if(pipeline)SDL_ReleaseGPUGraphicsPipeline(device,pipeline);if(vs)SDL_ReleaseGPUShader(device,vs);
+ if(ps)SDL_ReleaseGPUShader(device,ps);for(auto *t:{field,zero,targets[0],targets[1]})if(t)SDL_ReleaseGPUTexture(device,t);
+ if(sampler)SDL_ReleaseGPUSampler(device,sampler);}
+ } r;r.device=frame->Device();
+ VertexPipelineDescription vd={};vd.FVF=FF_FVF_XYZ|FF_FVF_NORMAL|FF_FVF_DIFFUSE|FF_FVF_TEX2;vd.StageCount=4;
+ vd.Stages[0].TextureCoordinateIndex=0;vd.Stages[1].TextureCoordinateIndex=1;
+ std::string vs;CHECK(VertexShader_Generate(vd,VERTEX_SHADER_TARGET_D3D11,vs));CHECK(WaterFftSampling::WrapVertex(vs));
+ // Retarget the actual Input entry before replacing it with the procedural fixture.
+ CHECK(SDL3_Shader_Retarget(vs,true));
+ const std::string entry="Output main(Input input)";const size_t at=vs.find(entry);CHECK(at!=std::string::npos);if(at==std::string::npos)return;
+ vs.replace(at,entry.size(),"Output refinementWaterVertex(Input input)");
+ vs+=R"HLSL(
+cbuffer Fixture : register(b2,space1) {float4 FixtureVertex[96];uint4 FixtureIndex[32];};
+struct ProbeOutput {float4 Position:SV_Position;float4 Parameter:TEXCOORD0;float4 Metadata:TEXCOORD1;};
+ProbeOutput main(uint id:SV_VertexID) {
+ uint v=FixtureIndex[id/4][id%4]*3;
+ Input input=(Input)0;input.Position=FixtureVertex[v].xyz;input.Normal=FixtureVertex[v+1].xyz;
+ input.TexCoord0=FixtureVertex[v+2].xy;input.TexCoord1=FixtureVertex[v+2].zw;input.Diffuse=float4(0,0,0,1);
+ Output displaced=refinementWaterVertex(input);ProbeOutput o;o.Position=displaced.Position;
+ o.Parameter=float4(displaced.TexCoord2,displaced.Specular.z,1);
+ o.Metadata=float4(displaced.Specular.x,displaced.Specular.y,displaced.Specular.w,0);return o;
+}
+)HLSL";
+ std::string ps=R"HLSL(
+struct ProbeOutput {float4 Position:SV_Position;float4 Parameter:TEXCOORD0;float4 Metadata:TEXCOORD1;};
+struct Result {float4 Parameter:SV_Target0;float4 Metadata:SV_Target1;};
+Result main(ProbeOutput input) {Result o;o.Parameter=input.Parameter;o.Metadata=float4(input.Metadata.xyz,input.Position.z);return o;}
+)HLSL";
+ CHECK(SDL3_Shader_Retarget(ps,false));
+ std::string error;std::vector<unsigned char> spirv;
+ bool compiled=SDL3_Compile_HLSL_To_SPIRV(vs,true,spirv,error);CHECK(compiled);if(!compiled){printf("bow refinement VS: %s\n",error.c_str());return;}
+ r.vs=SDL3_Create_Shader(r.device,spirv,true,error);CHECK(r.vs);
+ compiled=SDL3_Compile_HLSL_To_SPIRV(ps,false,spirv,error);CHECK(compiled);if(!compiled){printf("bow refinement PS: %s\n",error.c_str());return;}
+ r.ps=SDL3_Create_Shader(r.device,spirv,false,error);CHECK(r.ps);if(!r.vs||!r.ps)return;
+ SDL_GPUColorTargetDescription colours[2]={};for(auto &c:colours)c.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
+ SDL_GPUGraphicsPipelineCreateInfo pi={};pi.vertex_shader=r.vs;pi.fragment_shader=r.ps;pi.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;
+ pi.target_info.color_target_descriptions=colours;pi.target_info.num_color_targets=2;r.pipeline=SDL_CreateGPUGraphicsPipeline(r.device,&pi);CHECK(r.pipeline);if(!r.pipeline)return;
+ SDL_GPUTextureCreateInfo ti={};ti.type=SDL_GPU_TEXTURETYPE_2D;ti.format=colours[0].format;ti.layer_count_or_depth=ti.num_levels=1;
+ ti.width=ti.height=side;ti.usage=SDL_GPU_TEXTUREUSAGE_SAMPLER;r.field=SDL_CreateGPUTexture(r.device,&ti);r.zero=SDL_CreateGPUTexture(r.device,&ti);
+ ti.width=width;ti.height=height;ti.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;for(auto &t:r.targets)t=SDL_CreateGPUTexture(r.device,&ti);
+ SDL_GPUSamplerCreateInfo si={};si.min_filter=si.mag_filter=SDL_GPU_FILTER_LINEAR;si.address_mode_u=si.address_mode_v=si.address_mode_w=SDL_GPU_SAMPLERADDRESSMODE_REPEAT;
+ r.sampler=SDL_CreateGPUSampler(r.device,&si);CHECK(r.field&&r.zero&&r.targets[0]&&r.targets[1]&&r.sampler);if(!r.field||!r.zero||!r.targets[0]||!r.targets[1]||!r.sampler)return;
+ std::vector<float> texels(side*side*4*2,0);
+ for(unsigned y=0;y<side;++y)for(unsigned x=0;x<side;++x) {
+ const double u=2*WaterFftSpectrum::Pi*(x+.5)/side,v=2*WaterFftSpectrum::Pi*(y+.5)/side;
+ float *p=&texels[(y*side+x)*4];p[0]=float(.055*std::sin(u+.4)*std::cos(v));p[1]=float(.075*std::cos(2*u-.3)*std::cos(v+.5));p[2]=float(.04*std::cos(u)*std::sin(v-.2));
+ }
+ SDL_GPUTransferBufferCreateInfo tb={};tb.usage=SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD;tb.size=texels.size()*sizeof(float);
+ SDL_GPUTransferBuffer *transfer=SDL_CreateGPUTransferBuffer(r.device,&tb);CHECK(transfer);if(!transfer)return;
+ void *mapped=SDL_MapGPUTransferBuffer(r.device,transfer,false);CHECK(mapped);if(!mapped){SDL_ReleaseGPUTransferBuffer(r.device,transfer);return;}
+ memcpy(mapped,texels.data(),tb.size);SDL_UnmapGPUTransferBuffer(r.device,transfer);CHECK(frame->Flush());
+ SDL_GPUCommandBuffer *upload=SDL_AcquireGPUCommandBuffer(r.device);CHECK(upload);if(!upload){SDL_ReleaseGPUTransferBuffer(r.device,transfer);return;}
+ SDL_GPUCopyPass *copy=SDL_BeginGPUCopyPass(upload);CHECK(copy);
+ for(unsigned i=0;i<2;++i){SDL_GPUTextureTransferInfo from={};from.transfer_buffer=transfer;from.offset=i*side*side*4*sizeof(float);from.pixels_per_row=from.rows_per_layer=side;
+ SDL_GPUTextureRegion to={};to.texture=i?r.zero:r.field;to.w=to.h=side;to.d=1;SDL_UploadToGPUTexture(copy,&from,&to,false);}
+ SDL_EndGPUCopyPass(copy);CHECK(SDL_SubmitGPUCommandBuffer(upload));SDL_ReleaseGPUTransferBuffer(r.device,transfer);
+ SdlVertexConstants fixed={};SdlWaterPixelConstants water={};
+ for(unsigned i=0;i<4;++i){fixed.WorldView[i*5]=fixed.NormalTransform[i*5]=1;for(unsigned j=0;j<MAXIMUM_VERTEX_STAGES;++j)fixed.TextureMatrix[j][i*5]=1;}
+ fixed.WorldViewProjection[0]=fixed.WorldViewProjection[5]=1.0f/45;fixed.WorldViewProjection[9]=.018f;fixed.WorldViewProjection[10]=.02f;fixed.WorldViewProjection[14]=.5f;fixed.WorldViewProjection[15]=1;
+ water.FftParameters[0]=1;
+ WaterProjectedMesh::Projection projection={{1.0/45,0,0,0,1.0/45,0,0,0,1},{0},{0,0,1},.1,10,0};CHECK(projection.Prepare());
+ Topology base;
+ const double p[4][2]={{-28,-23},{27,-23},{27,25},{-28,25}};
+ const int logical[4][2]={{0,0},{4,0},{4,4},{0,4}};
+ for(unsigned i=0;i<4;++i){Node n;n.logical={logical[i][0],logical[i][1]};n.world={p[i][0],p[i][1]};CHECK(projection.Transform(n.world,n.screen));n.source=int(i);base.nodes.push_back(n);}
+ base.triangles={{0,1,2,1},{0,2,3,1}};
+ auto fresh=[](double x,double y,float out[3][4]) {
+ memset(out,0,12*sizeof(float));out[0][0]=float(x);out[0][1]=float(y);out[0][2]=.2f+float(.24*std::sin(x*.09)*std::cos(y*.07));
+ out[1][0]=float(.46+.15*std::cos(x*.055)*std::cos(y*.04));out[1][1]=float(.38+.00018*(x*x+y*y));out[1][2]=float(.6+.12*std::sin(x*.065-y*.035));
+ out[2][1]=float(y/150);out[2][2]=float(.4+.2*std::cos(x*.06+y*.04));out[2][3]=.2f;
+ };
+ struct V {double sx,sy,value[8];};
+ auto displaced=[&](const float input[3][4]) {
+ const double x=input[0][0],y=input[0][1],u=x/(13*WaterFftSampling::WorldScale)*side-.5,v=y/(13*WaterFftSampling::WorldScale)*side-.5;
+ const int ix=int(std::floor(u)),iy=int(std::floor(v));const double tx=u-ix,ty=v-iy;
+ double d[3]={};for(unsigned c=0;c<3;++c)for(int j=0;j<2;++j)for(int i=0;i<2;++i){int xx=(ix+i)%int(side),yy=(iy+j)%int(side);if(xx<0)xx+=side;if(yy<0)yy+=side;d[c]+=texels[(yy*side+xx)*4+c]*(i?tx:1-tx)*(j?ty:1-ty);}
+ const double horizontal=WaterFftGeometry::MaxHorizontalDisplacement/std::sqrt(2.0),vertical=WaterFftGeometry::MaxVerticalDisplacement;
+ const double dx=horizontal*std::tanh(-1.5*WaterFftSampling::WorldScale*d[0]/horizontal),dy=horizontal*std::tanh(-1.5*WaterFftSampling::WorldScale*d[2]/horizontal),dz=vertical*std::tanh(WaterFftSampling::WorldScale*d[1]/vertical);
+ const double weight=input[1][0],damping=input[1][1],old=input[0][2]-input[2][3];
+ const double chopWeight=weight*input[1][2];
+ const double wx=x+dx*chopWeight*damping,wy=y+dy*chopWeight*damping,wz=input[2][3]+old*(1-weight)+dz*damping*weight;
+ V out;out.sx=(wx*fixed.WorldViewProjection[0]+1)*width*.5;out.sy=(1-wy*fixed.WorldViewProjection[5]-wz*fixed.WorldViewProjection[9])*height*.5;
+ const double values[8]={x,y,old,1,weight,damping,input[1][2],wz*fixed.WorldViewProjection[10]+fixed.WorldViewProjection[14]};memcpy(out.value,values,sizeof(values));return out;
+ };
+ // Vulkan Core guarantees at least four subpixel/subtexel precision bits:
+ // https://docs.vulkan.org/refpages/latest/refpages/source/Required_Limits.html
+ // Use a whole least-significant bit, not an assumed device-specific nearest rounding.
+ // The bilinear error is bounded independently by the largest adjacent texel differences;
+ // tanh is 1-Lipschitz. These bounds apply only to coverage/XY, never to metadata or depth.
+ double filterError[3]={};
+ for(unsigned c=0;c<3;++c) {double du=0,dv=0;
+ for(unsigned y=0;y<side;++y)for(unsigned x=0;x<side;++x) {
+ const double value=texels[(y*side+x)*4+c];
+ du=(std::max)(du,std::abs(value-texels[(y*side+(x+1)%side)*4+c]));
+ dv=(std::max)(dv,std::abs(value-texels[(((y+1)%side)*side+x)*4+c]));
+ }
+ filterError[c]=(du+dv)/16;
+ }
+ const double coverageBoundX=1.0/16+filterError[0]*1.5*WaterFftSampling::WorldScale*width/90+.00001;
+ const double coverageBoundY=1.0/16+(filterError[2]*1.5/45+filterError[1]*.018)*WaterFftSampling::WorldScale*height/2+.00001;
+ unsigned renders=0,totalStable=0;double maxCoordinateError=0,maxMetadataError=0,maxDepthError=0,maxPixelErrorX=0,maxPixelErrorY=0,maxBound=0;std::vector<float> coarse,zero,nearZero,intermediate,full,stale,locked;
+ for(unsigned mode=0;mode<9;++mode) {
+ const double amount=mode==0||mode==1?0:mode==2?1e-6:mode==3?.25:mode==4||mode==6?.65:1;
+ Topology mesh;std::vector<std::pair<Logical,WaterProjectedMesh::Point>> finals;
+ auto weight=[&](unsigned level,Logical midpoint,WaterProjectedMesh::Point finalWorld){finals.push_back({midpoint,finalWorld});return amount;};
+ CHECK(Subdivide(base,projection,weight,mesh,mode==0?0:2,mode==7));CHECK(mesh.nodes.size()<=maxNodes&&mesh.triangles.size()*3<=maxIndices);if(mesh.nodes.size()>maxNodes||mesh.triangles.size()*3>maxIndices)return;
+ Fixture fixture={};std::vector<V> vertices;
+ for(size_t i=0;i<mesh.nodes.size();++i){const Node &n=mesh.nodes[i];fresh(n.world.x,n.world.y,fixture.vertex[i]);
+ if(mode==8)fixture.vertex[i][1][2]=0; // Connected R0 shore: FFT height stays active, horizontal chop is zero.
+ if(mode==6&&n.source<0){for(const auto &q:finals)if(q.first.x==n.logical.x&&q.first.y==n.logical.y){float bad[3][4];fresh(q.second.x,q.second.y,bad);memcpy(fixture.vertex[i][1],bad[1],4*sizeof(float));break;}}
+ if(n.parent>=0) {CHECK(size_t(n.parent)<i);if(mode!=6)CHECK(memcmp(fixture.vertex[i],fixture.vertex[n.parent],sizeof(fixture.vertex[i]))==0);}
+ vertices.push_back(displaced(fixture.vertex[i]));}
+ unsigned count=0;for(const Triangle &t:mesh.triangles){fixture.indices[count++]=t.a;fixture.indices[count++]=t.b;fixture.indices[count++]=t.c;}
+ SDL_GPUCommandBuffer *commands=SDL_AcquireGPUCommandBuffer(r.device);CHECK(commands);if(!commands)return;
+ SDL_GPUColorTargetInfo attachments[2]={};for(unsigned i=0;i<2;++i){attachments[i].texture=r.targets[i];attachments[i].load_op=SDL_GPU_LOADOP_CLEAR;attachments[i].store_op=SDL_GPU_STOREOP_STORE;}
+ SDL_GPURenderPass *pass=SDL_BeginGPURenderPass(commands,attachments,2,NULL);CHECK(pass);SDL_BindGPUGraphicsPipeline(pass,r.pipeline);
+ SDL_GPUTextureSamplerBinding bindings[4]={{r.zero,r.sampler},{r.zero,r.sampler},{r.field,r.sampler},{r.zero,r.sampler}};SDL_BindGPUVertexSamplers(pass,0,bindings,4);
+ SDL_PushGPUVertexUniformData(commands,0,&fixed,sizeof(fixed));SDL_PushGPUVertexUniformData(commands,1,&water,sizeof(water));SDL_PushGPUVertexUniformData(commands,2,&fixture,sizeof(fixture));
+ SDL_DrawGPUPrimitives(pass,count,1,0,0);SDL_EndGPURenderPass(pass);CHECK(SDL_SubmitGPUCommandBuffer(commands));++renders;
+ const auto values=read_float_targets(frame,r.targets,2,width,height);CHECK(values.size()==width*height*8);if(values.size()!=width*height*8)return;
+ for(float v:values)CHECK(std::isfinite(v));
+ unsigned stable=0,coverage=0;
+ for(unsigned py=0;py<height;++py)for(unsigned px=0;px<width;++px){const double x=px+.5,y=py+.5;bool found=false,edge=false;double expected[8]={},parameterExpected[8]={},surfaceX=0,surfaceY=0;
+ const unsigned offset=(py*width+px)*4;
+ for(const Triangle &t:mesh.triangles){const V &a=vertices[t.a],&b=vertices[t.b],&c=vertices[t.c];const double det=(b.sx-a.sx)*(c.sy-a.sy)-(b.sy-a.sy)*(c.sx-a.sx);if(std::abs(det)<1e-10)continue;
+ // Rasterizers quantize edge equations to subpixels. Exclude a fixed 0.15-pixel
+ // band on BOTH sides of every segment, rather than forgiving arbitrary mismatches.
+ const V *ends[3]={&a,&b,&c};for(unsigned e=0;e<3;++e){const V &lo=*ends[e],&hi=*ends[(e+1)%3];const double dx=hi.sx-lo.sx,dy=hi.sy-lo.sy,len2=dx*dx+dy*dy;
+ if(len2>1e-20){const double t=(std::max)(0.0,(std::min)(1.0,((x-lo.sx)*dx+(y-lo.sy)*dy)/len2));edge|=std::hypot(x-lo.sx-t*dx,y-lo.sy-t*dy)<.15;}}
+ const double wb=((x-a.sx)*(c.sy-a.sy)-(y-a.sy)*(c.sx-a.sx))/det,wc=((b.sx-a.sx)*(y-a.sy)-(b.sy-a.sy)*(x-a.sx))/det,wa=1-wb-wc;
+ if(wa>=-1e-5&&wb>=-1e-5&&wc>=-1e-5){const double distance=(std::min)(wa*std::abs(det)/std::hypot(b.sx-c.sx,b.sy-c.sy),(std::min)(wb*std::abs(det)/std::hypot(a.sx-c.sx,a.sy-c.sy),wc*std::abs(det)/std::hypot(a.sx-b.sx,a.sy-b.sy)));edge|=distance<.15;found=true;for(unsigned k=0;k<8;++k)expected[k]=a.value[k]*wa+b.value[k]*wb+c.value[k]*wc;
+ // At an observed interpolated parameter XY, metadata and depth have an
+ // independent exact affine answer. This removes subpixel raster rounding
+ // without copying the GPU's nonlinear displacement or its metadata values.
+ const double ax=a.value[0],ay=a.value[1],bx=b.value[0],by=b.value[1],cx=c.value[0],cy=c.value[1];
+ const double qx=values[offset],qy=values[offset+1],area=(bx-ax)*(cy-ay)-(by-ay)*(cx-ax);
+ CHECK(std::abs(area)>1e-12);if(std::abs(area)<=1e-12)continue;
+ const double qb=((qx-ax)*(cy-ay)-(qy-ay)*(cx-ax))/area,qc=((bx-ax)*(qy-ay)-(by-ay)*(qx-ax))/area,qa=1-qb-qc;
+ for(unsigned k=0;k<8;++k)parameterExpected[k]=a.value[k]*qa+b.value[k]*qb+c.value[k]*qc;
+ surfaceX=a.sx*qa+b.sx*qb+c.sx*qc;surfaceY=a.sy*qa+b.sy*qb+c.sy*qc;
+ }}
+ coverage+=values[offset+3]>.5f;if(edge)continue;++stable;
+ if(found) {
+ for(unsigned k=0;k<8;++k){const double actual=values[(k/4)*width*height*4+offset+k%4];
+ if(k<2)maxCoordinateError=(std::max)(maxCoordinateError,std::abs(actual-expected[k]));
+ else if(k<7)maxMetadataError=(std::max)(maxMetadataError,std::abs(actual-parameterExpected[k]));
+ else maxDepthError=(std::max)(maxDepthError,std::abs(actual-parameterExpected[k]));
+ }
+ maxPixelErrorX=(std::max)(maxPixelErrorX,std::abs(surfaceX-x));maxPixelErrorY=(std::max)(maxPixelErrorY,std::abs(surfaceY-y));
+ CHECK(std::abs(surfaceX-x)<=coverageBoundX&&std::abs(surfaceY-y)<=coverageBoundY);
+ } else CHECK(values[offset+3]==0);
+ }
+ CHECK(stable>width*height/2&&coverage>width*height/4);totalStable+=stable;
+ for(const V &v:vertices){maxBound=(std::max)(maxBound,std::abs((v.value[7]-.5)/.02-.2));CHECK(v.sx>=0&&v.sx<width&&v.sy>=0&&v.sy<height);}
+ if(mode==0)coarse=values;if(mode==1)zero=values;if(mode==2)nearZero=values;if(mode==4)intermediate=values;if(mode==5)full=values;if(mode==6)stale=values;if(mode==7)locked=values;
+ }
+ CHECK(maxMetadataError<.00003&&maxDepthError<.00003);CHECK(maxBound<=WaterFftGeometry::MaxVerticalDisplacement);
+ unsigned changed=0;double staleDifference=0,zeroError=0,nearError=0;
+ for(unsigned i=0;i<width*height;++i) {
+ // Full interior demand with locked boundary must cover exactly the original
+ // displaced outer quad, including sparse collapsed-parent closure.
+ CHECK(coarse[i*4+3]==zero[i*4+3]);CHECK(coarse[i*4+3]==locked[i*4+3]);
+ if(coarse[i*4+3]>0.5&&nearZero[i*4+3]>0.5)
+ for(unsigned c=0;c<8;++c){size_t at=(c/4)*width*height*4+i*4+c%4;nearError=(std::max)(nearError,double(std::abs(coarse[at]-nearZero[at])));}
+ }
+ for(size_t i=0;i<coarse.size();++i){changed+=std::abs(full[i]-coarse[i])>.01;zeroError=(std::max)(zeroError,double(std::abs(coarse[i]-zero[i])));staleDifference=(std::max)(staleDifference,double(std::abs(stale[i]-intermediate[i])));}
+ CHECK(changed>100);CHECK(staleDifference>.01);CHECK(zeroError<.00003&&nearError<.0003);
+ printf("sdl_gpu_frame_selfcheck: GPU production bow refinement: %u meshes/%u stable pixels, raster world-coordinate error %.8f; fresh metadata/depth errors %.8f/%.8f (bounds .00003/.00003), pixel XY errors %.8f/%.8f (independent bounds %.8f/%.8f), coarse collapse %.8f/near-limit %.8f, full-change %u, stale metadata control %.8f, exact locked-boundary coverage, bounded height %.5f\n",renders,totalStable,maxCoordinateError,maxMetadataError,maxDepthError,maxPixelErrorX,maxPixelErrorY,coverageBoundX,coverageBoundY,zeroError,nearError,changed,staleDifference,maxBound);
+}
+
+static void check_gpu_fft_vessel_composition(SdlGpuFrame *frame,bool bowLift=false,bool bowShoulder=false)
+{
+ // Known Fourier modes, independently packed into the six real field maps, make a numerical
+ // derivative meaningful: the random full-band spectrum is too close to texture Nyquist for a
+ // small finite difference of bilinear samples to approximate its stored spectral derivative.
+ const unsigned side=256,rows=10,columns=bowLift?51:40,plane=side*side*4;
+ const double amplitude[3]={.13,.17,.32},phase[3]={.31,-.42,.71},chop[3]={-1.2,-1.5,-1.5};
+ const int modes[3][2]={{1,1},{1,-1},{1,0}};
+ const float points[rows][4]={{0,8,7,0},{23,10,7,.5f},{-24,-10,7,1.5f},{12,18,7,3},{28,0,7,8},
+ {-40,9,7,16},{-60,-15,7,64},{80,65,7,128},{0,0,7,512},{8,-17,7,8192}};
+ std::vector<float> fields(6*plane);
+ for(unsigned c=0;c<3;++c) for(unsigned y=0;y<side;++y) for(unsigned x=0;x<side;++x) {
+ const double kx=2*WaterFftSpectrum::Pi*modes[c][0]/WaterFftSpectrum::Sizes[c];
+ const double ky=2*WaterFftSpectrum::Pi*modes[c][1]/WaterFftSpectrum::Sizes[c],k=std::hypot(kx,ky);
+ const double angle=2*WaterFftSpectrum::Pi*(modes[c][0]*(x+.5)+modes[c][1]*(y+.5))/side+phase[c];
+ const double a=amplitude[c]*std::sin(angle),b=amplitude[c]*std::cos(angle);
+ float *d=&fields[c*2*plane+(y*side+x)*4],*s=d+plane;
+ d[0]=float(a*kx/k);d[1]=float(b);d[2]=float(a*ky/k);d[3]=float(b*kx*ky/k);
+ s[0]=float(-a*kx);s[1]=float(-a*ky);s[2]=float(b*kx*kx/k);s[3]=float(b*ky*ky/k);
+ }
+ struct Resources {
+ SDL_GPUDevice *device;SDL_GPUTexture *maps[6]={},*targets[2]={};SDL_GPUSampler *sampler=NULL;
+ SDL_GPUShader *vs[2]={},*ps[2]={};SDL_GPUGraphicsPipeline *pipelines[2]={};unsigned vertexSamplers[2]={};
+ ~Resources() {
+ for(auto *p:maps) if(p) SDL_ReleaseGPUTexture(device,p);
+ for(auto *p:targets) if(p) SDL_ReleaseGPUTexture(device,p);
+ if(sampler) SDL_ReleaseGPUSampler(device,sampler);
+ for(unsigned i=0;i<2;++i) {if(pipelines[i]) SDL_ReleaseGPUGraphicsPipeline(device,pipelines[i]);
+ if(vs[i]) SDL_ReleaseGPUShader(device,vs[i]);if(ps[i]) SDL_ReleaseGPUShader(device,ps[i]);}
+ }
+ } resources;
+ resources.device=frame->Device();
+ SDL_GPUTextureCreateInfo texture={};texture.type=SDL_GPU_TEXTURETYPE_2D;texture.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
+ texture.usage=SDL_GPU_TEXTUREUSAGE_SAMPLER;texture.width=texture.height=side;texture.layer_count_or_depth=1;texture.num_levels=WaterFftSpectrum::Phases+1;
+ for(auto &map:resources.maps) {map=SDL_CreateGPUTexture(resources.device,&texture);CHECK(map);if(!map) return;}
+ texture.num_levels=1;texture.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;texture.width=columns;texture.height=rows;
+ for(auto &target:resources.targets) {target=SDL_CreateGPUTexture(resources.device,&texture);CHECK(target);if(!target) return;}
+ SDL_GPUSamplerCreateInfo sampler={};sampler.min_filter=sampler.mag_filter=SDL_GPU_FILTER_LINEAR;
+ sampler.address_mode_u=sampler.address_mode_v=sampler.address_mode_w=SDL_GPU_SAMPLERADDRESSMODE_REPEAT;
+ sampler.mipmap_mode=SDL_GPU_SAMPLERMIPMAPMODE_LINEAR;sampler.max_lod=WaterFftSpectrum::Phases;
+ resources.sampler=SDL_CreateGPUSampler(resources.device,&sampler);CHECK(resources.sampler);if(!resources.sampler) return;
+ OceanMipReference knownMips;
+ auto upload=[&]() {
+ knownMips=ocean_mip_reference(fields);
+ std::vector<float> packed;std::array<unsigned,WaterFftSpectrum::Phases+1> offsets={};
+ for(unsigned level=0;level<knownMips.size();++level) {
+ offsets[level]=unsigned(packed.size());
+ for(double value:knownMips[level])packed.push_back(float(value));
+ }
+ SDL_GPUTransferBufferCreateInfo ti={};ti.usage=SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD;ti.size=packed.size()*sizeof(float);
+ SDL_GPUTransferBuffer *transfer=SDL_CreateGPUTransferBuffer(resources.device,&ti);CHECK(transfer);if(!transfer) return false;
+ void *mapped=SDL_MapGPUTransferBuffer(resources.device,transfer,false);CHECK(mapped);
+ if(!mapped) {SDL_ReleaseGPUTransferBuffer(resources.device,transfer);return false;}
+ memcpy(mapped,packed.data(),ti.size);SDL_UnmapGPUTransferBuffer(resources.device,transfer);
+ SDL_GPUCommandBuffer *commands=SDL_AcquireGPUCommandBuffer(resources.device);CHECK(commands);
+ if(!commands) {SDL_ReleaseGPUTransferBuffer(resources.device,transfer);return false;}
+ SDL_GPUCopyPass *copy=SDL_BeginGPUCopyPass(commands);CHECK(copy);
+ for(unsigned level=0;level<knownMips.size();++level) for(unsigned i=0;i<6;++i) {
+ const unsigned size=side>>level;
+ SDL_GPUTextureTransferInfo source={};source.transfer_buffer=transfer;source.offset=(offsets[level]+i*size*size*4)*sizeof(float);source.pixels_per_row=source.rows_per_layer=size;
+ SDL_GPUTextureRegion dest={};dest.texture=resources.maps[i];dest.w=dest.h=size;dest.d=1;dest.mip_level=level;
+ SDL_UploadToGPUTexture(copy,&source,&dest,false);
+ }
+ SDL_EndGPUCopyPass(copy);const bool submitted=SDL_SubmitGPUCommandBuffer(commands);CHECK(submitted);
+ SDL_ReleaseGPUTransferBuffer(resources.device,transfer);return submitted;
+ };
+ CHECK(frame->Flush());if(!upload()) return;
+ const std::string basicVS="float4 main(uint id:SV_VertexID):SV_Position {return float4(id==1?3.0:-1.0,id==2?3.0:-1.0,0,1);}";
+ std::string sampleVS=WaterFftSampling::UniformSource("WaterBlock",0)+WaterFftSampling::VertexSource(bowLift,bowShoulder)+R"HLSL(
+cbuffer PointBlock:register(b1) {float4 PointData;};
+struct Output {float4 Position:SV_Position;[[vk::location(0)]] float4 Value:TEXCOORD0;[[vk::location(1)]] nointerpolation float4 Registered:TEXCOORD1;};
+Output main(uint id:SV_VertexID) {Output o;o.Position=float4(id==1?3.0:-1.0,id==2?3.0:-1.0,0,1);
+o.Value=float4(fftVertexDisplacement(PointData.xy,PointData.z),1);
+o.Registered=float4(fftVertexDisplacement(PointData.xy,PointData.z,.559713426),1);return o;}
+)HLSL";
+ std::string samplePS="float4 main(float4 pixel:SV_Position,[[vk::location(0)]] float4 value:TEXCOORD0,[[vk::location(1)]] nointerpolation float4 registered:TEXCOORD1):SV_Target0 {return pixel.x>=36.0?registered:value;}";
+ std::string surfacePS=WaterFftSampling::UniformSource("WaterBlock",0);
+ for(unsigned i=0;i<6;++i) surfacePS+="Texture2D Texture"+std::to_string(8+i)+":register(t"+std::to_string(i)+");SamplerState Sampler"+std::to_string(8+i)+":register(s"+std::to_string(i)+");\n";
+ surfacePS+="cbuffer PointBlock:register(b1) {float4 Points["+std::to_string(rows)+"];};\n";
+ surfacePS+=WaterFftSampling::PixelSource(bowLift,bowShoulder);
+ surfacePS+=R"HLSL(
+float4 main(float4 pixel:SV_Position):SV_Target0 {uint col=(uint)pixel.x;float4 p=Points[(uint)pixel.y];
+FftSurface s=fftSurface(p.xy,p.z);
+if(col>=36) {
+ FftSurface registered=fftSurface(p.xy,p.z,p.w,float3(.559713426,0,0));
+ if(col==36)return float4(registered.displacement,registered.vesselCrest);
+ if(col==37)return float4(registered.derivativeX,registered.generatedRaw);
+ if(col==38)return float4(registered.derivativeY,registered.generatedHeight);
+ FftSurface unfiltered=fftSurface(p.xy,p.z,0.0,float3(.559713426,0,0));
+ return float4(max(abs(registered.displacement-unfiltered.displacement),
+ max(abs(registered.derivativeX-unfiltered.derivativeX),abs(registered.derivativeY-unfiltered.derivativeY))),
+ abs(registered.generatedRaw-unfiltered.generatedRaw));
+}
+if(col==0) return float4(s.displacement,s.compression);
+if(col==1) return float4(s.derivativeX,s.vesselHeight);
+if(col==2) return float4(s.derivativeY,s.vesselCrest);
+if(col==3) return float4(normalize(cross(float3(1,0,0)+s.derivativeX,float3(0,1,0)+s.derivativeY)),s.incidentCompression);
+if(col==4) return float4(vesselGeneratedFoam(s.vesselCrest,1,saturate((4.0-0.15)/fftVerticalBound)),
+ vesselGeneratedFoam(s.vesselCrest,1,saturate((2.25-0.15)/fftVerticalBound)),
+ vesselGeneratedFoam(s.vesselCrest,0,1),vesselGeneratedFoam(s.vesselCrest,1,0));
+if(col==5) return float4(vesselGeneratedFoam(-1,1,1),vesselGeneratedFoam(2,1,2),
+ vesselGeneratedFoam(1,-2,1),vesselGeneratedFoam(1,2,1));
+float damping=saturate((4.0-0.15)/fftVerticalBound);
+float coverage=vesselGeneratedFoam(s.vesselCrest,1,damping);
+if(col==6) return float4(s.generatedRaw,s.generatedHeight,fftVerticalBound*tanh(s.generatedRaw/fftVerticalBound),s.vesselHeight);
+if(col==7) return float4(fftPressureDebug(s,1,damping,coverage),0);
+if(col==8) return float4(fftPressureRetentionDebug(s,1,damping,coverage),0);
+if(col==9) return float4(fftPressureDebug(s,0,damping,0),0);
+if(col==10) return float4(fftPressureDebug(s,1,0,0),0);
+if(col==11) {
+ FftSurface masked=s;uint maskCase=(uint)pixel.y%3;
+ masked.generatedRaw=maskCase==0?0.0:maskCase==1?-1.0:0.000001;
+ return float4(fftPressureRetentionDebug(masked,1,1,1),0);
+}
+float3 lod=fftShadingLod(p.w);
+if(col==19)return Texture8.SampleLevel(Sampler8,p.xy/(450.0*fftWorldScale),lod.x);
+if(col==20)return Texture9.SampleLevel(Sampler9,p.xy/(450.0*fftWorldScale),lod.x);
+if(col==21)return Texture10.SampleLevel(Sampler10,p.xy/(103.0*fftWorldScale),lod.y);
+if(col==22)return Texture11.SampleLevel(Sampler11,p.xy/(103.0*fftWorldScale),lod.y);
+if(col==23)return Texture12.SampleLevel(Sampler12,p.xy/(13.0*fftWorldScale),lod.z);
+if(col==24)return Texture13.SampleLevel(Sampler13,p.xy/(13.0*fftWorldScale),lod.z);
+if(col>=30) {
+ FftMapSamples all=fftMapSamples(p.xy,float3(0,0,0));
+ FftMapSamples low=all;low.c=0;low.cd=0;
+ FftMapSamples fine=(FftMapSamples)0;fine.c=all.c;fine.cd=all.cd;
+ FftSurface broadMedium=fftDecodeSamples(low),ripple=fftDecodeSamples(fine);
+ if(col==30)return float4(broadMedium.displacement,broadMedium.incidentCompression);
+ if(col==31)return float4(ripple.displacement,ripple.incidentCompression);
+ // Armed old behavior: the fine-only field has actual horizontal compression even
+ // though it must no longer add an ambient whitecap-breaking trigger.
+ float3 fineLimit=fftLimitDerivative(ripple.displacement);
+ float3 fineX=ripple.derivativeX*fineLimit,fineY=ripple.derivativeY*fineLimit;
+ if(col==32)return float4(broadMedium.derivativeX,(1+fineX.x)*(1+fineY.y)-fineX.y*fineY.x);
+ if(col==33)return float4(broadMedium.derivativeY,fftDecodeSamples(all).incidentCompression);
+ FftMapSamples broad=low; broad.b=0; broad.bd=0;
+ FftMapSamples medium=low; medium.a=0; medium.ad=0;
+ if(col==34)return float4(ripple.derivativeX,fftDecodeSamples(broad).incidentCompression);
+ return float4(ripple.derivativeY,fftDecodeSamples(medium).incidentCompression);
+}
+if(col>=25) {
+ float2 queryPosition=p.xy;
+ if(col==27 || col==28) {
+ // Actual mirrored positions whenever this hull contributes; otherwise several
+ // negative/positive world-period wraps exercise arbitrary signed coordinates.
+ queryPosition+=float2(-18000.25,4120.5);
+ if(FftParameters.y>0.5 && HullParameters.x>0.5) {
+ int hullIndex=(int)HullParameters.x-1;
+ VesselReflection reflected=vesselReflection(p.xy,p.z,hullIndex);
+ if(reflected.weight>0.0)queryPosition=reflected.samplePosition;
+ }
+ }
+ FftSurface pairedPhysical,pairedShading;
+ fftRawAndShadingSurface(queryPosition,lod,pairedPhysical,pairedShading);
+ // This route always fetches all six maps independently. It does not use the new
+ // paired helper or its per-cascade reuse decisions; the CPU oracle above separately
+ // validates the common channel decode and the existing physical model.
+ FftSurface independentPhysical=fftRawSurface(queryPosition,float3(0,0,0));
+ FftSurface independentShading=fftRawSurface(queryPosition,lod);
+ if(col==29)return float4(abs(pairedShading.displacement-independentPhysical.displacement),0);
+ FftSurface paired=pairedPhysical,independent=independentPhysical;
+ if(col==26 || col==28) {paired=pairedShading;independent=independentShading;}
+ return float4(max(abs(paired.displacement-independent.displacement),
+ max(abs(paired.derivativeX-independent.derivativeX),abs(paired.derivativeY-independent.derivativeY))),0);
+}
+FftSurface filtered=fftSurface(p.xy,p.z,p.w);
+if(col==12) return float4(filtered.shadingDisplacement,filtered.unresolvedSlopeVariance);
+if(col==13) return float4(filtered.shadingDerivativeX,filtered.vesselCrest);
+if(col==14) return float4(filtered.shadingDerivativeY,filtered.incidentCompression);
+if(col==15) return float4(normalize(cross(float3(1,0,0)+filtered.shadingDerivativeX,
+ float3(0,1,0)+filtered.shadingDerivativeY)),filtered.compression);
+if(col==16) return float4(lod,fftShadingVariance(lod));
+if(col==17) return float4(max(abs(filtered.displacement-s.displacement),
+ max(abs(filtered.derivativeX-s.derivativeX),abs(filtered.derivativeY-s.derivativeY))),
+ abs(filtered.compression-s.compression)+abs(filtered.incidentCompression-s.incidentCompression));
+return float4(abs(filtered.generatedRaw-s.generatedRaw),abs(filtered.generatedHeight-s.generatedHeight),
+ abs(filtered.vesselHeight-s.vesselHeight),abs(filtered.vesselCrest-s.vesselCrest));}
+)HLSL";
+ if(bowLift) {
+ const std::string oldStruct="nointerpolation float4 Registered:TEXCOORD1;";
+ sampleVS.replace(sampleVS.find(oldStruct),oldStruct.size(),oldStruct+"[[vk::location(2)]] nointerpolation float4 Lifted:TEXCOORD2;");
+ const std::string oldReturn="return o;}";
+ sampleVS.replace(sampleVS.find(oldReturn),oldReturn.size(),R"HLSL(
+float f=.559713426,d=f*saturate(abs(PointData.x)/28.0),w=.65+.002*PointData.y,bow;
+float3 v=fftVertexBowDisplacement(PointData.xy,PointData.z,w*d,bow);
+float added=fftBowLift(float3(bow,0,0),float3(f,0,0),float3(d,0,0)).x;
+o.Lifted=float4(v.xy*(w*d),(v.z*d+added)*w,fftBowLiftFoam(added,w));return o;}
+)HLSL");
+ const std::string oldArgument="nointerpolation float4 registered:TEXCOORD1)";
+ samplePS.replace(samplePS.find(oldArgument),oldArgument.size(),
+ "nointerpolation float4 registered:TEXCOORD1,[[vk::location(2)]] nointerpolation float4 lifted:TEXCOORD2)");
+ const std::string oldChoice="return pixel.x>=36.0?registered:value;";
+ samplePS.replace(samplePS.find(oldChoice),oldChoice.size(),"return pixel.x>=40.0?lifted:pixel.x>=36.0?registered:value;");
+ const std::string before="if(col>=36) {";
+ surfacePS.insert(surfacePS.find(before),R"HLSL(
+if(col>=40) {
+ float f=.559713426,d=f*saturate(abs(p.x)/28.0),w=.65+.002*p.y;
+ float3 df=float3(d,abs(p.x)>0.0 && abs(p.x)<28.0?f/28.0*sign(p.x):0.0,0);
+ float3 scale=float3(w*d,w*df.y,.002*d);
+ FftSurface q=fftSurface(p.xy,p.z,p.w,scale);
+ float3 added=fftBowLift(q.bow,float3(f,0,0),df);
+ float height=q.displacement.z*d+added.x;
+ float2 slope=float2(q.derivativeX.z,q.derivativeY.z)*d+q.displacement.z*df.yz+added.yz;
+ if(col==40)return float4(q.displacement.xy*(w*d),height*w,fftBowLiftFoam(added.x,w));
+ if(col==41)return float4(added,q.bow.x);
+ FftSurface zero=fftSurface(p.xy,p.z,0.0,scale);
+ if(col==42)return float4(q.bow,length(q.bow-zero.bow));
+ return float4(slope*w+height*float2(0,.002),height*w,f*w*fftVerticalBound);
+}
+)HLSL");
+ }
+
+ if(bowLift) {
+ surfacePS.insert(surfacePS.find("if(col>=40) {"),R"HLSL(
+if(col==49) return float4(s.contactIncident,0);
+if(col==50) {
+ FftMapSamples low=fftMapSamples(p.xy,float3(0,0,0));
+ FftMapSamples fine=(FftMapSamples)0;fine.c=low.c;fine.cd=low.cd;low.c=0;low.cd=0;
+ FftSurface incident=fftDecodeSamples(low),ripples=fftDecodeSamples(fine);
+ FftSurface filtered=fftSurface(p.xy,p.z,p.w);
+ return float4(max(abs(s.contactIncident-incident.contactIncident),abs(ripples.contactIncident)),
+ length(filtered.contactIncident-s.contactIncident));
+}
+)HLSL");
+ // Same-fragment bow attribution: actual physical raw composition is checked
+ // independently below. The synthetic column only isolates the display helper.
+ const std::string before="if(col>=40) {";
+ surfacePS.insert(surfacePS.find(before),R"HLSL(
+if(col>=45) {
+ float f=.559713426,d=f*saturate(abs(p.x)/28.0),w=.65+.002*p.y;
+ float3 df=float3(d,abs(p.x)>0.0 && abs(p.x)<28.0?f/28.0*sign(p.x):0.0,0);
+ float3 scale=float3(w*d,w*df.y,.002*d);
+ FftSurface q=fftSurface(p.xy,p.z,p.w,scale);
+ if(col==45)return float4(fftBowRetentionDebug(q,w,f,d),q.bowLimitedDelta);
+ if(col==46) {
+ FftSurface noBow=q;noBow.bow=0;noBow.bowLimitedDelta=0;
+ return float4(fftBowRetentionDebug(q,w,f,0).y,fftBowRetentionDebug(q,w,d,d).y,
+ fftBowRetentionDebug(q,0,f,d).y,fftBowRetentionDebug(noBow,w,f,d).y);
+ }
+ if(col==47) {
+ const float background[10]={-32,-10,-1,0,1,10,32,0,0,0};
+ const float bow[10]={64,8,.2,3,8,8,64,0,.000001,8};
+ uint row=(uint)pixel.y;float a=background[row],b=bow[row];
+ FftSurface synthetic=(FftSurface)0;synthetic.bow=float3(b,0,0);
+ synthetic.bowLimitedDelta=fftVerticalBound*(tanh((a+b)/fftVerticalBound)-tanh(a/fftVerticalBound));
+ return float4(fftBowRetentionDebug(synthetic,row==0?1.0:.7,1.0,row==0?1.0:.6),synthetic.bowLimitedDelta);
+ }
+ FftSurface zero=fftSurface(p.xy,p.z,0.0,scale);
+ return float4(abs(fftBowRetentionDebug(q,w,f,d)-fftBowRetentionDebug(zero,w,f,d)),
+ abs(q.bowLimitedDelta-zero.bowLimitedDelta));
+}
+)HLSL");
+ }
+
+ if(bowShoulder) {
+ CHECK(bowLift);
+ // Full emitted fftSurface integration. Remove only the incident/reflected field
+ // difference between physical and filtered maps; generated bow/stern corrections
+ // must be common to both. The scalar field itself has separate independent CPU
+ // and finite-difference oracles below. This catches a missing filtered correction
+ // even when vertex and physical pixel evaluations agree with one another.
+ const std::string before="if(col>=40) {";
+ surfacePS.insert(surfacePS.find(before),R"HLSL(
+if(col==44) {
+ float f=.559713426,d=f*saturate(abs(p.x)/28.0),w=.65+.002*p.y;
+ float3 df=float3(d,abs(p.x)>0.0 && abs(p.x)<28.0?f/28.0*sign(p.x):0.0,0);
+ float3 scale=float3(w*d,w*df.y,.002*d);
+ FftSurface q=fftSurface(p.xy,p.z,p.w,scale);
+ float3 lod=fftShadingLod(p.w);
+ FftSurface incident,filtered;
+ fftRawAndShadingSurface(p.xy,lod,incident,filtered);
+ float oldBowTotal=0;
+ if(FftParameters.y>0.5)for(int h=0;h<clamp((int)HullParameters.x,0,8);++h) {
+ VesselReflection r=vesselReflection(p.xy,p.z,h);
+ if(r.weight>0.0) {
+ FftSurface a,b;fftRawAndShadingSurface(r.samplePosition,lod,a,b);
+ incident.displacement+=vesselReflectedValue(a.displacement,r);
+ incident.derivativeX+=vesselReflectedDerivative(a.displacement,a.derivativeX,a.derivativeY,float2(1,0),r);
+ incident.derivativeY+=vesselReflectedDerivative(a.displacement,a.derivativeX,a.derivativeY,float2(0,1),r);
+ filtered.displacement+=vesselReflectedValue(b.displacement,r);
+ filtered.derivativeX+=vesselReflectedDerivative(b.displacement,b.derivativeX,b.derivativeY,float2(1,0),r);
+ filtered.derivativeY+=vesselReflectedDerivative(b.displacement,b.derivativeX,b.derivativeY,float2(0,1),r);
+ }
+ float3 oldBow;vesselGeneratedWave(p.xy,p.z,WaterParameters.x,h,oldBow);oldBowTotal+=oldBow.x;
+ }
+ float n=q.displacement.z/fftVerticalBound,physicalDerivative=1.0-n*n;
+ float raw=fftVerticalBound*.5*log((1.0+n)/(1.0-n));
+ float rawFiltered=raw+filtered.displacement.z-incident.displacement.z;
+ float expected=fftVerticalBound*tanh(rawFiltered/fftVerticalBound);
+ float derivative=1.0-(expected/fftVerticalBound)*(expected/fftVerticalBound);
+ float2 expectedSlope=(float2(q.derivativeX.z,q.derivativeY.z)/physicalDerivative+
+ float2(filtered.derivativeX.z-incident.derivativeX.z,filtered.derivativeY.z-incident.derivativeY.z))*derivative;
+ float missingCorrection=fftVerticalBound*tanh((rawFiltered-q.bow.x+oldBowTotal)/fftVerticalBound);
+ return float4(abs(q.shadingDisplacement.z-expected),
+ abs(float2(q.shadingDerivativeX.z,q.shadingDerivativeY.z)-expectedSlope),
+ any(lod>0.0)?abs(missingCorrection-expected):0.0);
+}
+)HLSL");
+ }
+ for(unsigned stage=0;stage<2;++stage) {
+ std::string vs=stage?sampleVS:basicVS,ps=stage?samplePS:surfacePS,error;std::vector<unsigned char> spirv;
+ CHECK(SDL3_Shader_Retarget(vs,true));CHECK(SDL3_Shader_Retarget(ps,false));
+ bool compiled=SDL3_Compile_HLSL_To_SPIRV(vs,true,spirv,error);CHECK(compiled);
+ if(!compiled) {printf("FFT vessel VS: %s\n",error.c_str());return;}
+ unsigned buffers=0;SDL3_Shader_Slots(spirv,true,resources.vertexSamplers[stage],buffers);
+ CHECK(stage?(resources.vertexSamplers[stage]>=3&&resources.vertexSamplers[stage]<=4):resources.vertexSamplers[stage]==0);
+ resources.vs[stage]=SDL3_Create_Shader(resources.device,spirv,true,error);CHECK(resources.vs[stage]);
+ compiled=SDL3_Compile_HLSL_To_SPIRV(ps,false,spirv,error);CHECK(compiled);
+ if(!compiled) {printf("FFT vessel PS: %s\n",error.c_str());return;}
+ resources.ps[stage]=SDL3_Create_Shader(resources.device,spirv,false,error);CHECK(resources.ps[stage]);
+ SDL_GPUColorTargetDescription colour={};colour.format=texture.format;
+ SDL_GPUGraphicsPipelineCreateInfo info={};info.vertex_shader=resources.vs[stage];info.fragment_shader=resources.ps[stage];
+ info.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;info.target_info.color_target_descriptions=&colour;info.target_info.num_color_targets=1;
+ resources.pipelines[stage]=SDL_CreateGPUGraphicsPipeline(resources.device,&info);CHECK(resources.pipelines[stage]);if(!resources.pipelines[stage]) return;
+ }
+ SdlWaterPixelConstants water={};water.FftParameters[0]=water.FftParameters[1]=1;water.WaterParameters[0]=4;
+ WaterHullModel::Hull hull;hull.data[0][2]=7;hull.data[0][3]=4;hull.data[1][0]=1;hull.data[1][2]=20;hull.data[1][3]=6;
+ hull.data[2][2]=.23f;hull.data[2][3]=sqrtf(436.0f);hull.data[3][0]=-20;hull.data[3][2]=20;
+ const float outline[8]={-20,-6,20,-6,20,6,-20,6};memcpy(hull.data[4],outline,sizeof(outline));
+ // Scalar reference only: normals come from independent double-precision finite differences,
+ // not from copying the production derivative/Jacobian expressions.
+ auto smooth=[](double a,double b,double x) {const double t=(std::max)(0.0,(std::min)(1.0,(x-a)/(b-a)));return t*t*(3-2*t);};
+ // Separate scalar contour oracle from WaterBowShoulderTest: no production query,
+ // gradient or registration helper. Keep the first two legacy invocations unchanged.
+ auto shoulderScalar=[&](double x,double y,double halfLength) {
+ WaterHullModel::Hull selected=hull;selected.data[0][2]=7;selected.data[0][3]=4;
+ selected.data[1][2]=float(halfLength);selected.data[2][3]=float(std::hypot(halfLength,6.0));
+ selected.data[3][0]=float(-halfLength);selected.data[3][2]=float(halfLength);
+ const float contour[8]={float(-halfLength),-6,float(halfLength),-6,float(halfLength),6,float(-halfLength),6};
+ memcpy(selected.data[4],contour,sizeof(contour));
+ return WaterBowShoulderTest::oracle(selected,x,y);
+ };
+ auto packet=[&](double x,double y,double halfLength) {
+ const double along=-x-halfLength,across=y,width=2.1+along*.353553,strip=3.08,length=50.4;
+ auto gaussian=[](double distance,double w) {return std::exp(-distance*distance/(w*w));};
+ const double arms=gaussian(across-width,strip)*std::cos((across-width)*.40)+gaussian(across+width,strip)*std::cos((across+width)*.40);
+ const double churn=gaussian(across,3.3)*std::sin(along*.30-4*1.15+.23*6.2831853)*.24;
+ const double trail=smooth(0,10,along)*(1-smooth(length*.5,length,along));
+ const double bow=bowShoulder?0.0:vessel_test_pressure(x-halfLength,y,6,12);
+ const double radius=std::sqrt(halfLength*halfLength+36);
+ return (trail*(arms*1.35+churn)*smooth(.3,14,12)+bow)*(1-smooth(radius+80,radius+110,std::hypot(x,y)))+
+ (bowShoulder?shoulderScalar(x,y,halfLength):0.0);
+ };
+ double maxValue=0,maxDerivative=0,maxNormal=0,maxVertex=0,maxIncident=0;
+ double registeredStageError=0,registeredChanged=0,registeredPhysicalError=0;
+ double liftStageError=0,liftHeightError=0,liftGradientError=0,liftBowError=0;
+ double bowRetentionError=0,bowLimitedError=0,bowFilterError=0,bowSyntheticError=0;
+ double contactIncidentError=0;
+ unsigned bowCrestControls=0,bowTroughControls=0,bowWithoutLiftControls=0,bowIsolatedControls=0,bowOverEnvelopeControls=0;
+ double shoulderFilteredError=0,shoulderMissingCorrection=0;unsigned shoulderFilteredControls=0;unsigned liftActive=0,liftZero=0,liftNonconstant=0;
+ unsigned registeredPhysicalDifferences=0;
+ unsigned changedStationary=0,changedMoving=0,changedGradient=0,changedCompression=0;
+ unsigned visibleShallowCrests=0;double maxGeneratedFoam=0;
+ double maxGeneratedRaw=0,maxGeneratedDelta=0,maxPressureDebug=0,maxRetentionDebug=0;
+ unsigned positiveIncidentCases=0,negativeIncidentCases=0,maskedDiagnostics=0;
+ std::vector<float> baseline,generatedBaseline,flatBaseline,contactBaseline;
+ double idealSamplerError=0;
+ double armedAnchorChange=0,maxShadingValue=0,maxShadingDerivative=0,maxShadingNormal=0,maxLod=0,maxVariance=0;
+ unsigned filteredChanged=0,preservedPacket=0,armedReuse=0;double pairedError=0;
+ unsigned armedFineBreaking=0,broadBreaking=0,mediumBreaking=0,physicalFineSamples=0;
+ double maxSelectedCompression=0,maxFineValue=0,maxFineDerivative=0;
+ const auto &varianceTable=WaterFftFiltering::SpectrumVariance();
+ for(unsigned scenario=0;scenario<18;++scenario) {
+ const bool enabled=scenario!=3,hasHull=scenario!=0,moving=scenario==2 || scenario==3 || scenario==5 || scenario>=6;
+ const bool applicable=hasHull && enabled && scenario!=4,flat=scenario>=6;
+ const bool contact=scenario==7 || scenario==8 || scenario==10 || scenario==11 || scenario==12;
+ const bool lastSlot=scenario==5 || scenario==11;
+ if(scenario==6) {std::fill(fields.begin(),fields.end(),0);if(!upload()) return;}
+ if(scenario>=16) {
+ std::fill(fields.begin(),fields.end(),0);
+ for(unsigned pixel=0;pixel<side*side;++pixel)fields[pixel*4+1]=scenario==16?.5f:-.5f;
+ if(!upload())return; // exactly +10/-10 world-unit incident height, zero derivatives
+ }
+ water.FftParameters[1]=enabled?1:0;water.HullParameters[0]=hasHull?(lastSlot?8:1):0;
+ water.SunColour[0]=water.SunColour[1]=water.SunColour[2]=scenario==8?1.0f:0.0f;
+ memset(water.HullData,0,sizeof(water.HullData));hull.data[2][0]=moving?12:0;hull.data[0][2]=scenario==4?8:7;
+ memset(water.ContactHullData,0,sizeof(water.ContactHullData));
+ const float meanLength=scenario==8 || scenario==9?11.0f:20.0f;
+ hull.data[1][2]=meanLength;hull.data[2][3]=sqrtf(meanLength*meanLength+36);
+ hull.data[3][0]=-meanLength;hull.data[3][2]=meanLength;
+ if(bowShoulder) {
+ const float contour[8]={-meanLength,-6,meanLength,-6,meanLength,6,-meanLength,6};
+ memcpy(hull.data[4],contour,sizeof(contour));
+ }
+ memcpy(water.HullData+(lastSlot?70:0),&hull,sizeof(hull));
+ if(contact || (scenario>=13 && scenario<=15)) {
+ WaterHullModel::Hull stable=hull;stable.data[1][2]=28;stable.data[2][3]=sqrtf(820.0f);
+ stable.data[3][0]=-28;stable.data[3][2]=28;
+ if(bowShoulder) {const float contour[8]={-28,-6,28,-6,28,6,-28,6};memcpy(stable.data[4],contour,sizeof(contour));}
+ stable.data[0][2]=scenario==10?8:7;stable.data[0][3]=scenario==13?2:scenario==14?13:scenario==15?0:4;
+ memcpy(water.ContactHullData+(lastSlot?70:0),&stable,sizeof(stable));
+ }
+ SDL_GPUCommandBuffer *commands=SDL_AcquireGPUCommandBuffer(resources.device);CHECK(commands);
+ for(unsigned stage=0;stage<2;++stage) {
+ SDL_GPUColorTargetInfo attachment={};attachment.texture=resources.targets[stage];attachment.load_op=SDL_GPU_LOADOP_DONT_CARE;attachment.store_op=SDL_GPU_STOREOP_STORE;
+ SDL_GPURenderPass *pass=SDL_BeginGPURenderPass(commands,&attachment,1,NULL);CHECK(pass);SDL_BindGPUGraphicsPipeline(pass,resources.pipelines[stage]);
+ SDL_GPUTextureSamplerBinding bindings[6]={};
+ for(unsigned i=0;i<(stage?3u:6u);++i) {bindings[i].texture=resources.maps[stage?i*2:i];bindings[i].sampler=resources.sampler;}
+ if(stage) {
+ // Some compilers retain the unused cage declaration in VertexSource.
+ // TerrainParameters.w is zero; nevertheless every reflected slot must bind.
+ bindings[3]={resources.maps[0],resources.sampler};
+ SDL_BindGPUVertexSamplers(pass,0,bindings,resources.vertexSamplers[stage]);SDL_PushGPUVertexUniformData(commands,0,&water,sizeof(water));
+ for(unsigned row=0;row<rows;++row) {
+ SDL_GPUViewport viewport={0,float(row),float(columns),1,0,1};SDL_SetGPUViewport(pass,&viewport);
+ SDL_PushGPUVertexUniformData(commands,1,points[row],sizeof(points[row]));SDL_DrawGPUPrimitives(pass,3,1,0,0);
+ }
+ } else {
+ SDL_BindGPUFragmentSamplers(pass,0,bindings,6);SDL_PushGPUFragmentUniformData(commands,0,&water,sizeof(water));
+ SDL_PushGPUFragmentUniformData(commands,1,points,sizeof(points));SDL_DrawGPUPrimitives(pass,3,1,0,0);
+ }
+ SDL_EndGPURenderPass(pass);
+ }
+ CHECK(SDL_SubmitGPUCommandBuffer(commands));const auto values=read_float_targets(frame,resources.targets,2,columns,rows);
+ auto gpu=[&](unsigned row,unsigned col,unsigned c){return double(values[(row*columns+col)*4+c]);};
+ auto raw=[&](double x,double y,double out[3],unsigned cascades=3) {
+ out[0]=out[1]=out[2]=0;if(scenario>=16) {out[2]=scenario==16?10:-10;return;}if(flat) return;
+ for(unsigned c=0;c<cascades;++c) {
+ const double length=std::hypot(modes[c][0],modes[c][1]);
+ const double a=2*WaterFftSpectrum::Pi*(modes[c][0]*x+modes[c][1]*y)/(WaterFftSpectrum::Sizes[c]*20)+phase[c];
+ out[0]+=20*chop[c]*amplitude[c]*modes[c][0]/length*std::sin(a);
+ out[1]+=20*chop[c]*amplitude[c]*modes[c][1]/length*std::sin(a);out[2]+=20*amplitude[c]*std::cos(a);
+ }
+ };
+ auto surface=[&](double x,double y,double out[3],bool includeGenerated=true,bool limited=true) {
+ raw(x,y,out);
+ if(applicable) {
+ const double qx=(std::max)(-20.0,(std::min)(20.0,x)),qy=(std::max)(-6.0,(std::min)(6.0,y));
+ const double distance=std::hypot(x-qx,y-qy);
+ if(distance>.0001 && distance<28) {
+ const double nx=(x-qx)/distance,ny=(y-qy)/distance,t=distance/28,fade=1-t*t*(3-2*t),weight=.68*fade*fade;
+ double d[3];raw(2*qx-x,2*qy-y,d);const double dot=d[0]*nx+d[1]*ny;
+ out[0]+=(d[0]-2*nx*dot)*weight;out[1]+=(d[1]-2*ny*dot)*weight;out[2]+=d[2]*weight;
+ }
+ if(includeGenerated && moving && scenario!=10) out[2]+=packet(x,y,contact?28.0:double(meanLength));
+ }
+ const double bounds[3]={8/std::sqrt(2.0),8/std::sqrt(2.0),WaterFftGeometry::MaxVerticalDisplacement};
+ if(limited)for(unsigned c=0;c<3;++c) out[c]=bounds[c]*std::tanh(out[c]/bounds[c]);
+ };
+ for(unsigned row=0;row<rows;++row) {
+ const double x=points[row][0],y=points[row][1];double expected[3],gradient[2][3];surface(x,y,expected);
+ if(bowLift) {
+ // Columns30/32/33 independently expose the already-verified broad/medium
+ // raw field. Contact uses its own vertical limiter before vessel additions.
+ const double v=WaterFftGeometry::MaxVerticalDisplacement;
+ const double t=std::tanh(gpu(row,30,2)/v),d=1-t*t;
+ CHECK(std::abs(gpu(row,49,0)-v*t)<.00002);
+ CHECK(std::abs(gpu(row,49,1)-gpu(row,32,2)*d)<.000002);
+ CHECK(std::abs(gpu(row,49,2)-gpu(row,33,2)*d)<.000002);
+ for(unsigned c=0;c<4;++c) {
+ contactIncidentError=(std::max)(contactIncidentError,gpu(row,50,c));
+ // Independent inlining of tanh can differ below a millionth of a
+ // world unit; this must not be mistaken for footprint/wake dependence.
+ CHECK(gpu(row,50,c)<.000002);
+ }
+ if(scenario>0 && !flat) for(unsigned c=0;c<3;++c)
+ CHECK(gpu(row,49,c)==baseline[(row*columns+49)*4+c]);
+ }
+ for(unsigned c=0;c<3;++c) {
+ const double vertex=values[rows*columns*4+(row*columns+36)*4+c];
+ const double error=std::abs(vertex-gpu(row,36,c));
+ registeredStageError=(std::max)(registeredStageError,error);CHECK(error<.00002);
+ registeredPhysicalError=(std::max)(registeredPhysicalError,double(gpu(row,39,c)));
+ registeredPhysicalDifferences+=gpu(row,39,c)!=0;
+ CHECK(std::abs(gpu(row,36,c))<=(c==2?WaterFftGeometry::MaxVerticalDisplacement:8/std::sqrt(2.0))+.000001);
+ if(flat)CHECK(gpu(row,36,c)==gpu(row,0,c)); // exact zero horizontal chop
+ }
+ CHECK(gpu(row,39,3)==0);
+ registeredChanged=(std::max)(registeredChanged,std::abs(gpu(row,36,2)-gpu(row,0,2)));
+ if(bowLift) {
+ const double free=.559713426,mean=free*(std::min)(1.0,std::abs(x)/28.0),weight=.65+.002*y;
+ const double bound=WaterFftGeometry::MaxVerticalDisplacement;
+ for(unsigned c=0;c<4;++c) {
+ const double vertex=values[rows*columns*4+(row*columns+40)*4+c];
+ const double error=std::abs(vertex-gpu(row,40,c));liftStageError=(std::max)(liftStageError,error);CHECK(error<.00003);
+ }
+ CHECK(std::abs(gpu(row,40,2))<=free*weight*bound+.000003);
+ CHECK(gpu(row,41,0)>=0 && gpu(row,40,3)>=0 && gpu(row,40,3)<=.65);
+ CHECK(gpu(row,42,3)<.000001); // filtered lighting cannot change the physical bow
+ const double lifted=(free-mean)*bound*std::tanh(gpu(row,41,3)/bound);
+ CHECK(std::abs(lifted-gpu(row,41,0))<.000003);
+ CHECK(std::abs(gpu(row,40,3)-.65*weight*(std::min)(1.0,lifted*.32))<.000003);
+ if(!applicable || !moving || scenario==10 || mean==free) {
+ CHECK(gpu(row,41,0)==0);CHECK(gpu(row,40,3)==0);++liftZero;
+ } else if(lifted>.001)++liftActive;
+ {
+ // Independent scalar composition from the known Fourier modes and the
+ // old independent reflection/stern oracle. Reconstruct the raw total
+ // from its exact double limiter, remove the old bow, and evaluate the
+ // bow at independently displaced XY using varying W and D. No GPU
+ // derivative, registration helper or production lift helper is reused.
+ auto bow=[&](double px,double py) {
+ if(!applicable || !moving || scenario==10)return 0.0;
+ const double length=contact?28.0:double(meanLength),radius=std::hypot(length,6.0);
+ return bowShoulder?shoulderScalar(px,py,length):vessel_test_pressure(px-length,py,6,12)*(1-smooth(radius+80,radius+110,std::hypot(px,py)));
+ };
+ auto composed=[&](double px,double py) {
+ double current[3];surface(px,py,current);
+ const double d=free*(std::min)(1.0,std::abs(px)/28.0),w=.65+.002*py;
+ const double mappedBow=bow(px+current[0]*w*d,py+current[1]*w*d);
+ const double rawTotal=bound*std::atanh(current[2]/bound);
+ const double registered=bound*std::tanh((rawTotal-bow(px,py)+mappedBow)/bound);
+ return w*(d*registered+(free-d)*bound*std::tanh(mappedBow/bound));
+ };
+ double independent[3];surface(x,y,independent);
+ const double expectedBow=bow(x+independent[0]*weight*mean,y+independent[1]*weight*mean);
+ const double expectedHeight=composed(x,y);
+ // Independently reconstruct RAW incident + reflection + stern + old
+ // bow from known modes, then replace only the bow at registered XY.
+ // Do not invert the limited GPU result or reuse its bow accumulator.
+ double rawTotal[3];surface(x,y,rawTotal,true,false);
+ const double background=rawTotal[2]-bow(x,y);
+ const double limitedDelta=bound*(std::tanh((background+expectedBow)/bound)-std::tanh(background/bound));
+ const double marginal=weight*(mean*limitedDelta+(free-mean)*bound*std::tanh(expectedBow/bound));
+ const double expectedRGB[3]={expectedBow/8,marginal/bound,weight*free};
+ const double tolerance=flat?.00003:.004; // existing independent known-map precision
+ bowLimitedError=(std::max)(bowLimitedError,std::abs(limitedDelta-gpu(row,45,3)));
+ CHECK(std::abs(limitedDelta-gpu(row,45,3))<tolerance);
+ for(unsigned c=0;c<3;++c) {
+ const double error=std::abs(expectedRGB[c]-gpu(row,45,c));
+ bowRetentionError=(std::max)(bowRetentionError,error);CHECK(error<tolerance);
+ }
+ CHECK(gpu(row,45,1)>=0 && gpu(row,45,1)<=weight*(free+mean)+.000003);
+ const double dZero=weight*free*std::tanh(expectedBow/bound);
+ const double freeEqualsD=weight*mean*limitedDelta/bound;
+ CHECK(std::abs(gpu(row,46,0)-dZero)<tolerance);
+ CHECK(std::abs(gpu(row,46,1)-freeEqualsD)<tolerance);
+ CHECK(gpu(row,46,2)==0 && gpu(row,46,3)==0);
+ for(unsigned c=0;c<4;++c) {
+ bowFilterError=(std::max)(bowFilterError,gpu(row,48,c));CHECK(gpu(row,48,c)<.000001);
+ }
+ if(expectedBow>.01) {
+ bowCrestControls+=scenario==16;bowTroughControls+=scenario==17;
+ bowWithoutLiftControls+=std::abs(marginal-weight*mean*limitedDelta)>.001;
+ bowIsolatedControls+=std::abs(marginal-weight*free*bound*std::tanh(expectedBow/bound))>.001;
+ }
+ const double a[10]={-32,-10,-1,0,1,10,32,0,0,0};
+ const double b[10]={64,8,.2,3,8,8,64,0,.000001,8};
+ const double sw=row==0?1.:.7,sd=row==0?1.:.6;
+ const double delta=bound*(std::tanh((a[row]+b[row])/bound)-std::tanh(a[row]/bound));
+ const double synthetic[4]={b[row]/8,sw*(sd*delta/bound+(1-sd)*std::tanh(b[row]/bound)),sw,delta};
+ for(unsigned c=0;c<4;++c) {
+ const double error=std::abs(synthetic[c]-gpu(row,47,c));
+ bowSyntheticError=(std::max)(bowSyntheticError,error);CHECK(error<.00001);
+ }
+ // The final total is bounded, but marginal trough-to-crest rise is
+ // not bounded by the blue envelope (nor by 1 before display clamp).
+ if(row==0) {CHECK(gpu(row,47,1)>1.9 && gpu(row,47,1)>gpu(row,47,2));++bowOverEnvelopeControls;}
+ liftBowError=(std::max)(liftBowError,std::abs(expectedBow-gpu(row,41,3)));
+ liftHeightError=(std::max)(liftHeightError,std::abs(expectedHeight-gpu(row,40,2)));
+ // Nonconstant ideal Fourier modes differ slightly from sampled
+ // bilinear textures; use the existing physical fixture's scale of
+ // tolerances there. Constant-map strict checks remain unchanged.
+ CHECK(std::abs(expectedBow-gpu(row,41,3))<(flat?.00001:.003));
+ CHECK(std::abs(expectedHeight-gpu(row,40,2))<(flat?.00003:.004));
+ if(std::abs(x)>0.001 && std::abs(std::abs(x)-28)>0.001)for(unsigned axis=0;axis<2;++axis) {
+ const double epsilon=.0001;
+ const double expected=(composed(x+(axis==0?epsilon:0),y+(axis==1?epsilon:0))-
+ composed(x-(axis==0?epsilon:0),y-(axis==1?epsilon:0)))/(2*epsilon);
+ const double error=std::abs(expected-gpu(row,43,axis));
+ liftGradientError=(std::max)(liftGradientError,error);CHECK(error<(flat?.0001:.004));
+ if(!flat && applicable && moving && expectedBow>.01)++liftNonconstant;
+ }
+ }
+ }
+ if(bowShoulder) {
+ for(unsigned c=0;c<3;++c) {
+ shoulderFilteredError=(std::max)(shoulderFilteredError,gpu(row,44,c));
+ CHECK(gpu(row,44,c)<.00003);
+ }
+ shoulderMissingCorrection=(std::max)(shoulderMissingCorrection,gpu(row,44,3));
+ shoulderFilteredControls+=gpu(row,44,3)>.01;
+ }
+ // Fine-only decode keeps its physical ripple but has exactly the identity
+ // breaking Jacobian. Adding fine waves, reflected fields or generated packets
+ // cannot change the selected broad/medium incident compression.
+ CHECK(gpu(row,31,3)==1);
+ CHECK(gpu(row,30,3)==gpu(row,33,3) && gpu(row,30,3)==gpu(row,3,3));
+ double selectedX[2],selectedY[2];
+ for(unsigned c=0;c<2;++c) {
+ const double q=std::tanh(gpu(row,30,c)/(8/std::sqrt(2.0))),limit=1-q*q;
+ selectedX[c]=gpu(row,32,c)*limit;selectedY[c]=gpu(row,33,c)*limit;
+ }
+ const double selectedCompression=(1+selectedX[0])*(1+selectedY[1])-selectedX[1]*selectedY[0];
+ maxSelectedCompression=(std::max)(maxSelectedCompression,std::abs(gpu(row,30,3)-selectedCompression));
+ CHECK(std::abs(gpu(row,30,3)-selectedCompression)<.000001);
+ if(scenario==0) {
+ armedFineBreaking+=std::abs(gpu(row,32,3)-1)>.001;
+ broadBreaking+=std::abs(gpu(row,34,3)-1)>.001;
+ mediumBreaking+=std::abs(gpu(row,35,3)-1)>.001;
+ physicalFineSamples+=std::abs(gpu(row,31,2))>.01 && std::abs(gpu(row,34,2))>.001;
+ const double k=2*WaterFftSpectrum::Pi/WaterFftSpectrum::Sizes[2];
+ const double theta=k*x/20+phase[2],a=amplitude[2]*std::sin(theta),b=amplitude[2]*std::cos(theta);
+ const double fine[3]={20*chop[2]*a,0,20*b},fineX[3]={chop[2]*b*k,0,-a*k};
+ for(unsigned c=0;c<3;++c) {
+ maxFineValue=(std::max)(maxFineValue,std::abs(gpu(row,31,c)-fine[c]));
+ maxFineDerivative=(std::max)(maxFineDerivative,std::abs(gpu(row,34,c)-fineX[c]));
+ CHECK(std::abs(gpu(row,31,c)-fine[c])<.004 && std::abs(gpu(row,34,c)-fineX[c])<.003);
+ CHECK(gpu(row,35,c)==0);
+ }
+ }
+ // The resource fixture separately checks ideal trilinear interpolation at exact
+ // filter coordinates. At these arbitrary world positions, read each signed map
+ // sample independently: hardware interpolation has finite fractional precision,
+ // and must not be mistaken for an error in the surface/Jacobian calculation.
+ // Existing independent finite-difference physical checks below remain unchanged.
+ double lod[3],expectedVariance=0,shading[3]={},shadingGradient[2][3]={};
+ for(unsigned cascade=0;cascade<3;++cascade) {
+ lod[cascade]=(std::max)(0.0,(std::min)(8.0,std::log2((std::max)(1.0,double(points[row][3])*256/(WaterFftSpectrum::Sizes[cascade]*20)))));
+ const unsigned low=(std::min)(7u,unsigned(lod[cascade]));const double fraction=lod[cascade]-low;
+ expectedVariance+=varianceTable[low][cascade]*(1-fraction)+varianceTable[low+1][cascade]*fraction;
+ maxLod=(std::max)(maxLod,std::abs(gpu(row,16,cascade)-lod[cascade]));CHECK(std::abs(gpu(row,16,cascade)-lod[cascade])<.000002);
+ double d[4],slope[4];
+ for(unsigned c=0;c<4;++c) {
+ const double u=x/(WaterFftSpectrum::Sizes[cascade]*20),v=y/(WaterFftSpectrum::Sizes[cascade]*20);
+ d[c]=gpu(row,19+cascade*2,c);slope[c]=gpu(row,20+cascade*2,c);
+ idealSamplerError=(std::max)(idealSamplerError,std::abs(d[c]-ocean_mip_sample(knownMips,cascade*2,c,u,v,lod[cascade])));
+ idealSamplerError=(std::max)(idealSamplerError,std::abs(slope[c]-ocean_mip_sample(knownMips,cascade*2+1,c,u,v,lod[cascade])));
+ }
+ shading[0]+=20*chop[cascade]*d[0];shading[1]+=20*chop[cascade]*d[2];shading[2]+=20*d[1];
+ shadingGradient[0][0]+=chop[cascade]*slope[2];shadingGradient[0][1]+=chop[cascade]*d[3];shadingGradient[0][2]+=slope[0];
+ shadingGradient[1][0]+=chop[cascade]*d[3];shadingGradient[1][1]+=chop[cascade]*slope[3];shadingGradient[1][2]+=slope[1];
+ }
+ maxVariance=(std::max)(maxVariance,std::abs(gpu(row,16,3)-expectedVariance));CHECK(std::abs(gpu(row,16,3)-expectedVariance)<.000002);
+ for(unsigned c=0;c<4;++c)CHECK(gpu(row,17,c)==0 && gpu(row,18,c)==0);
+ for(unsigned column=25;column<=28;++column) for(unsigned c=0;c<4;++c) {
+ pairedError=(std::max)(pairedError,std::abs(gpu(row,column,c)));CHECK(gpu(row,column,c)==0);
+ }
+ if(scenario==0) for(unsigned c=0;c<3;++c)armedReuse+=gpu(row,29,c)>.001;
+ CHECK(gpu(row,13,3)==gpu(row,2,3) && gpu(row,14,3)==gpu(row,3,3) && gpu(row,15,3)==gpu(row,0,3));
+ CHECK(gpu(row,12,3)>=0);
+ if(row<=1 || flat) {
+ for(unsigned c=0;c<3;++c) {
+ CHECK(gpu(row,12,c)==gpu(row,0,c));CHECK(gpu(row,13,c)==gpu(row,1,c));CHECK(gpu(row,14,c)==gpu(row,2,c));
+ CHECK(gpu(row,15,c)==gpu(row,3,c));
+ }
+ if(flat && std::abs(gpu(row,0,2))>.01 && row>1)++preservedPacket;
+ if(row<=1)CHECK(gpu(row,12,3)==0);
+ }
+ if(scenario==0) {
+ const double bound[3]={8/std::sqrt(2.0),8/std::sqrt(2.0),WaterFftGeometry::MaxVerticalDisplacement};
+ const double verticalLimit=1-std::pow(std::tanh(shading[2]/bound[2]),2);
+ for(unsigned c=0;c<3;++c) {
+ const double t=std::tanh(shading[c]/bound[c]);shading[c]=bound[c]*t;
+ maxShadingValue=(std::max)(maxShadingValue,std::abs(gpu(row,12,c)-shading[c]));CHECK(std::abs(gpu(row,12,c)-shading[c])<.00002);
+ for(unsigned axis=0;axis<2;++axis) {
+ shadingGradient[axis][c]*=1-t*t;
+ maxShadingDerivative=(std::max)(maxShadingDerivative,std::abs(gpu(row,13+axis,c)-shadingGradient[axis][c]));
+ CHECK(std::abs(gpu(row,13+axis,c)-shadingGradient[axis][c])<.000002);
+ }
+ filteredChanged+=std::abs(gpu(row,12,c)-gpu(row,0,c))>.001;
+ }
+ CHECK(std::abs(gpu(row,12,3)-expectedVariance*verticalLimit*verticalLimit)<.000002);
+ shadingGradient[0][0]+=1;shadingGradient[1][1]+=1;double normal[3];
+ for(unsigned c=0;c<3;++c)normal[c]=shadingGradient[0][(c+1)%3]*shadingGradient[1][(c+2)%3]-shadingGradient[0][(c+2)%3]*shadingGradient[1][(c+1)%3];
+ const double length=std::hypot(normal[0],std::hypot(normal[1],normal[2]));
+ for(unsigned c=0;c<3;++c) {maxShadingNormal=(std::max)(maxShadingNormal,std::abs(gpu(row,15,c)-normal[c]/length));CHECK(std::abs(gpu(row,15,c)-normal[c]/length)<.000002);}
+ }
+ const double generated=applicable && moving && scenario!=10?packet(x,y,contact?28.0:double(meanLength)):0;
+ const double expectedCrest=(std::min)(1.0,(std::max)(0.0,generated)*.32);
+ double without[3];surface(x,y,without,false);
+ const double generatedDelta=expected[2]-without[2],bound=WaterFftGeometry::MaxVerticalDisplacement;
+ const double isolated=bound*std::tanh(generated/bound),damping=WaterFftGeometry::SafeDamping(1,4);
+ const double coverage=expectedCrest*.65*smooth(.15,.65,damping);
+ const double rawError=std::abs(gpu(row,6,0)-generated),deltaError=std::abs(gpu(row,6,1)-generatedDelta);
+ maxGeneratedRaw=(std::max)(maxGeneratedRaw,rawError);maxGeneratedDelta=(std::max)(maxGeneratedDelta,deltaError);
+ CHECK(rawError<.00001 && deltaError<(flat?.00001:.0015));
+ CHECK(std::abs(gpu(row,6,2)-isolated)<.00001);
+ const double pressure[3]={(std::max)(0.0,generated)/8,(std::max)(0.0,generatedDelta)*damping/3.85,coverage};
+ const bool mask=generated>.0001;
+ const double retention[3]={mask?1-(std::max)(0.0,(std::min)(1.0,generatedDelta/(std::max)(isolated,.000001))):0,mask?damping:0,mask?coverage:0};
+ for(unsigned c=0;c<3;++c) {
+ const double pressureError=std::abs(gpu(row,7,c)-pressure[c]),retentionError=std::abs(gpu(row,8,c)-retention[c]);
+ maxPressureDebug=(std::max)(maxPressureDebug,pressureError);maxRetentionDebug=(std::max)(maxRetentionDebug,retentionError);
+ CHECK(pressureError<.0003 && retentionError<.003);
+ CHECK(gpu(row,11,c)==0);++maskedDiagnostics;
+ if(!mask)CHECK(gpu(row,8,c)==0);
+ }
+ for(unsigned col:{9u,10u}) {
+ CHECK(std::abs(gpu(row,col,0)-pressure[0])<.00001);
+ CHECK(gpu(row,col,1)==0 && gpu(row,col,2)==0);
+ }
+ if(scenario>=16 && generated>.01) {
+ CHECK(generatedDelta>0 && generatedDelta<isolated*.6 && gpu(row,8,0)>.4);
+ if(scenario==16)++positiveIncidentCases;else ++negativeIncidentCases;
+ }
+ CHECK(std::abs(gpu(row,2,3)-expectedCrest)<.00001);
+ for(unsigned c=0;c<2;++c) {
+ const double damping=WaterFftGeometry::SafeDamping(1,c?2.25f:4.0f);
+ const double expectedFoam=expectedCrest*.65*smooth(.15,.65,damping);
+ const double difference=std::abs(gpu(row,4,c)-expectedFoam);
+ maxGeneratedFoam=(std::max)(maxGeneratedFoam,difference);CHECK(difference<.00001);
+ if(expectedFoam>.005)++visibleShallowCrests;
+ }
+ CHECK(gpu(row,4,2)==0 && gpu(row,4,3)==0);
+ CHECK(gpu(row,5,0)==0 && std::abs(gpu(row,5,1)-.65)<.000001 && gpu(row,5,2)==0 && std::abs(gpu(row,5,3)-.65)<.000001);
+ double incidentGradient[2][2];
+ for(unsigned axis=0;axis<2;++axis) {
+ double plus[3],minus[3];const double step=.0001;
+ surface(x+(axis==0?step:0),y+(axis==1?step:0),plus);surface(x-(axis==0?step:0),y-(axis==1?step:0),minus);
+ for(unsigned c=0;c<3;++c) gradient[axis][c]=(plus[c]-minus[c])/(2*step);
+ // Only the intended ambient-breaking oracle changes: the independent
+ // physical height/normal reference above still uses all three cascades.
+ raw(x+(axis==0?step:0),y+(axis==1?step:0),plus,2);raw(x-(axis==0?step:0),y-(axis==1?step:0),minus,2);
+ const double bound=8/std::sqrt(2.0);
+ for(unsigned c=0;c<2;++c) incidentGradient[axis][c]=bound*(std::tanh(plus[c]/bound)-std::tanh(minus[c]/bound))/(2*step);
+ }
+ const double incident=(1+incidentGradient[0][0])*(1+incidentGradient[1][1])-incidentGradient[0][1]*incidentGradient[1][0];
+ maxIncident=(std::max)(maxIncident,std::abs(gpu(row,3,3)-incident));CHECK(std::abs(gpu(row,3,3)-incident)<.0003);
+ if(scenario>0 && !flat) CHECK(gpu(row,3,3)==baseline[(row*columns+3)*4+3]);
+ if(flat) CHECK(gpu(row,3,3)==1);
+ for(unsigned c=0;c<3;++c) {
+ maxValue=(std::max)(maxValue,std::abs(gpu(row,0,c)-expected[c]));CHECK(std::abs(gpu(row,0,c)-expected[c])<.004);
+ for(unsigned axis=0;axis<2;++axis) {
+ const double difference=std::abs(gpu(row,axis+1,c)-gradient[axis][c]);maxDerivative=(std::max)(maxDerivative,difference);CHECK(difference<.003);
+ }
+ const double vertex=values[rows*columns*4+row*columns*4+c],difference=std::abs(vertex-gpu(row,0,c));
+ maxVertex=(std::max)(maxVertex,difference);CHECK(difference<.00001);
+ }
+ gradient[0][0]+=1;gradient[1][1]+=1;double normal[3];
+ for(unsigned c=0;c<3;++c) normal[c]=gradient[0][(c+1)%3]*gradient[1][(c+2)%3]-gradient[0][(c+2)%3]*gradient[1][(c+1)%3];
+ const double norm=std::sqrt(normal[0]*normal[0]+normal[1]*normal[1]+normal[2]*normal[2]);
+ for(unsigned c=0;c<3;++c) {const double difference=std::abs(gpu(row,3,c)-normal[c]/norm);maxNormal=(std::max)(maxNormal,difference);CHECK(difference<.003);}
+ CHECK(std::hypot(gpu(row,0,0),gpu(row,0,1))<=8.00001 && std::abs(gpu(row,0,2))<=WaterFftGeometry::MaxVerticalDisplacement+.00001);
+ const float shallow=WaterFftGeometry::SafeDamping(1,2.25f);CHECK(gpu(row,0,2)*shallow>=-2.10-.00001);
+ if(scenario==1) {
+ changedStationary+=std::abs(gpu(row,0,2)-baseline[row*columns*4+2])>.001;
+ double difference=0;
+ for(unsigned col=1;col<=2;++col) for(unsigned c=0;c<3;++c)
+ difference=(std::max)(difference,std::abs(gpu(row,col,c)-baseline[(row*columns+col)*4+c]));
+ changedGradient+=difference>.001;
+ changedCompression+=std::abs(gpu(row,0,3)-gpu(row,3,3))>.001;
+ }
+ if(flat) changedMoving+=std::abs(gpu(row,0,2))>.01;
+ }
+ for(float v:values) CHECK(std::isfinite(v));
+ if(scenario==0) baseline=values;
+ if(scenario==2) generatedBaseline=values;
+ if(scenario==3 || scenario==4) {
+ double previousMaximum=0,newMaximum=0;unsigned mismatches=0;
+ for(size_t i=0;i<values.size();++i)if(values[i]!=baseline[i]) {
+ const double error=std::abs(double(values[i])-baseline[i]);
+ if(i/4%columns<36)previousMaximum=(std::max)(previousMaximum,error);else newMaximum=(std::max)(newMaximum,error);
+ ++mismatches;
+ }
+ printf("registered disabled scenario%u previous/new maxima %.9g / %.9g, mismatches%u\n",scenario,previousMaximum,newMaximum,mismatches);
+ // Retain the previous 36-column exact contract. Registered evaluations
+ // permit <1e-6 world units for differently optimized uniform branches;
+ // observed maxima were 4.77e-7, not a change to their physical model.
+ // The new shoulder shader's enabled/count-zero path and disabled/count-one
+ // path have identical scalar fields but differ by 2.39e-7 on this GPU.
+ // Preserve both old exact contracts and the wrong-level exact comparison;
+ // bound only this new inactive-path comparison at registered-map precision.
+ if(bowShoulder && scenario==3)CHECK(previousMaximum<.000001);
+ else CHECK(previousMaximum==0);
+ CHECK(newMaximum<.000001);
+ }
+ if(scenario==5) CHECK(values==generatedBaseline);
+ if(scenario==6)flatBaseline=values;
+ if(scenario==7)contactBaseline=values;
+ if(scenario==11 || scenario==12)CHECK(values==contactBaseline);
+ if(scenario==8) {
+ // Contact packet remains exact while the mean hull changes. Its incident
+ // reflection variance is allowed to follow that changed mean-hull bound.
+ for(size_t i=0;i<values.size();++i)if(!(i/4%columns==12 && i%4==3))CHECK(values[i]==contactBaseline[i]);
+ }
+ if(scenario==9)for(unsigned row=0;row<rows;++row)
+ armedAnchorChange=(std::max)(armedAnchorChange,std::abs(double(values[row*columns*4+2])-flatBaseline[row*columns*4+2]));
+ if(scenario>=13 && scenario<=15)CHECK(values==flatBaseline);
+ }
+ if(bowLift) printf("contact incident: broad/medium limiter and gradients; fine/reflection/generated/footprint isolation maximum %.9g\n",contactIncidentError);
+ if(bowShoulder) {
+ CHECK(shoulderFilteredControls>5 && shoulderMissingCorrection>.05);
+ printf("sdl_gpu_frame_selfcheck: full contour shoulder FFT integration: physical/filtered generated correction %.9g, armed omitted-filter correction %.9g (%u cases); actual VertexSource(true,true)/PixelSource(true,true), known Fourier modes, varying weight/damping, zero chop, fallback/contact/last-slot and independent scalar/derivative/foam checks retained\n",shoulderFilteredError,shoulderMissingCorrection,shoulderFilteredControls);
+ }
+ if(bowLift) {
+ CHECK(liftActive>5 && liftZero>20 && liftNonconstant>1);
+ CHECK(bowCrestControls>0 && bowTroughControls>0 && bowWithoutLiftControls>0 && bowIsolatedControls>0 && bowOverEnvelopeControls==18);
+ printf("sdl_gpu_frame_selfcheck: bow retention physical raw decomposition: RGB %.9g/limited marginal %.9g, helper %.9g, filtered identity %.9g; crest/trough %u/%u, omitted-lift %u, isolated-peak %u, G>envelope controls %u; zero bow/weight, F=D and D=0 checked\n",bowRetentionError,bowLimitedError,bowSyntheticError,bowFilterError,bowCrestControls,bowTroughControls,bowWithoutLiftControls,bowIsolatedControls,bowOverEnvelopeControls);
+ printf("sdl_gpu_frame_selfcheck: optional bow lift actual FFT VS/PS %.9g, independent bow %.9g/height %.9g/finite-difference derivative %.9g; active %u, exact zero %u and nonconstant derivative controls %u, floor bound, physical filtering and actual-height foam checked\n",liftStageError,liftBowError,liftHeightError,liftGradientError,liftActive,liftZero,liftNonconstant);
+ }
+ CHECK(registeredChanged>.001);
+ printf("sdl_gpu_frame_selfcheck: registered physical footprint comparison max %.9g across %u nonzero values\n",registeredPhysicalError,registeredPhysicalDifferences);
+ // Identical mip-zero inputs/geometry, with filtered and constant-zero-LOD calls
+ // optimized separately. Keep this far below the armed .001-unit displacement
+ // control; the observed maximum is 2.27e-7. Raw generated terms remain exact.
+ CHECK(registeredPhysicalError<.000001);
+ printf("sdl_gpu_frame_selfcheck: registered bow texture/stage parity %.8g, armed coordinate displacement %.8g; physical footprint agreement <1e-6, exact flat-chop identity and bounds checked\n",registeredStageError,registeredChanged);
+ CHECK(changedStationary>=3 && changedGradient>=3 && changedCompression>=2 && changedMoving>=2 && armedAnchorChange>.2);
+ CHECK(visibleShallowCrests>10);CHECK(filteredChanged>=5 && preservedPacket>=20);CHECK(armedReuse>=5);
+ CHECK(armedFineBreaking>=5 && broadBreaking>=5 && mediumBreaking>=5 && physicalFineSamples>=5);
+ printf("sdl_gpu_frame_selfcheck: FFT breaking scale: coarse/medium limiter error %.9f; fine-only compression exactly1 with %u physical ripple samples, %u armed old fine-breaking controls and %u/%u broad/medium responses; independent fine value %.9f/derivative %.9f, full physical/vessel/reflection checks retained\n",maxSelectedCompression,physicalFineSamples,armedFineBreaking,broadBreaking,mediumBreaking,maxFineValue,maxFineDerivative);
+ printf("sdl_gpu_frame_selfcheck: FFT paired sampling reuse: bit-exact displacement/derivatives at arbitrary, negative-wrapped and real mirrored queries with zero/mixed/all positive LOD; maxdifference %.9f, armed missing-filter controls %u\n",pairedError,armedReuse);
+ printf("sdl_gpu_frame_selfcheck: FFT footprint filtering: sampled-channel value %.9f/tangent %.9f/normal %.9f, LOD %.9f/variance %.9f; %u changed components, %u constant-field packet samples preserved, all physical/diagnostic outputs bit-exact across footprints0..8192; arbitrary-coordinate ideal sampler discrepancy %.9f reported separately\n",maxShadingValue,maxShadingDerivative,maxShadingNormal,maxLod,maxVariance,filteredChanged,preservedPacket,idealSamplerError);
+ CHECK(positiveIncidentCases>=3 && negativeIncidentCases>=3 && maskedDiagnostics==18*rows*3);
+ printf("sdl_gpu_frame_selfcheck: GPU pressure diagnostics: raw %.8f, generated-only limited delta %.8f, pressure RGB %.8f, retention RGB %.8f; independent with/without-generated composition, +10/-10 incident cases %u/%u, zero/negative/tiny-footprint masks %u and zero weight/damping checked\n",maxGeneratedRaw,maxGeneratedDelta,maxPressureDebug,maxRetentionDebug,positiveIncidentCases,negativeIncidentCases,maskedDiagnostics);
+ printf("sdl_gpu_frame_selfcheck: GPU generated vessel foam: independent packet-crest/coverage error %.8f, %u active depth4/2.25 samples; rest/disabled/zero weight/zero hull damping, bounded inputs, unchanged coverage under changed sunlight checked\n",maxGeneratedFoam,visibleShallowCrests);
+ printf("sdl_gpu_frame_selfcheck: GPU FFT-vessel composition: 18 known-mode/constant atlases, value %.8f/gradient %.8f/normal %.8f/VS-PS %.8f/incident compression %.8f; coarse+medium incident compression, stable contact packet despite changing mean slice, armed old-anchor height jump %.8f, independent curved-pressure/stern reference, contact level/pause/final-slot/count0/2/13 fallback, stationary reflection and bounds checked\n",maxValue,maxDerivative,maxNormal,maxVertex,maxIncident,armedAnchorChange);
+}
+
+// Direct O(N^2) Fourier sum at a few points: deliberately independent of GPU butterfly ordering,
+// bit reversal, .5-per-phase normalization and checkerboard postprocessing. Complex-pair packing
+// also verifies all four channels, not just a visually plausible height map.
+static void direct_ocean(const std::vector<float>& initial,unsigned cascade,double px,double py,double time,double out[8])
+{
+ using C=std::complex<double>;const unsigned n=WaterFftSpectrum::Resolution;
+ C sums[4]={},unpacked[8]={};const C imaginary(0,1);
+ for(unsigned y=0;y<n;++y) for(unsigned x=0;x<n;++x) {
+ const double kx=2*WaterFftSpectrum::Pi*(int(x)-int(n/2))/WaterFftSpectrum::Sizes[cascade];
+ const double ky=2*WaterFftSpectrum::Pi*(int(y)-int(n/2))/WaterFftSpectrum::Sizes[cascade],k=std::hypot(kx,ky);
+ if(k==0) continue;
+ const float *h=&initial[((cascade*n+y)*n+x)*4];
+ const C e=std::polar(1.0,std::sqrt(9.81*k)*time),height=C(h[0],h[1])*e+C(h[2],h[3])*std::conj(e);
+ const C dx=x?height*C(0,-kx/k):C(0),dz=y?height*C(0,-ky/k):C(0);
+ const C sx=x?height*C(0,kx):C(0),sz=y?height*C(0,ky):C(0);
+ const C dxx=x?height*(kx*kx/k):C(0),dzz=y?height*(ky*ky/k):C(0),dxz=x&&y?height*(kx*ky/k):C(0);
+ const C phase=std::polar(1.0,2*WaterFftSpectrum::Pi*((int(x)-int(n/2))*px+(int(y)-int(n/2))*py)/n);
+ sums[0]+=(dx+imaginary*height)*phase;sums[1]+=(dz+imaginary*dxz)*phase;
+ sums[2]+=(sx+imaginary*sz)*phase;sums[3]+=(dxx+imaginary*dzz)*phase;
+ const C physical[8]={dx,height,dz,dxz,sx,sz,dxx,dzz};
+ for(unsigned i=0;i<8;++i) unpacked[i]+=physical[i]*phase;
+ }
+ for(unsigned i=0;i<4;++i) {out[2*i]=sums[i].real();out[2*i+1]=sums[i].imag();}
+ // The packed DFT alone can agree with a broken implementation: an imaginary height component
+ // would silently appear in its neighbour's real channel. Independently invert all eight physical
+ // spectra and require a real result, before comparing that result against the packed transform.
+ for(unsigned i=0;i<8;++i) {
+ CHECK(std::abs(unpacked[i].imag())<0.00000001);
+ CHECK(std::abs(unpacked[i].real()-out[i])<0.00000001);
+ }
+}
+
+static void check_fft_spectral_reality(const std::vector<float>& initial)
+{
+ using namespace WaterFftSpectrum;using C=std::complex<double>;
+ auto height=[&](const std::vector<float>& data,unsigned cascade,unsigned x,unsigned y,double time) {
+ const double kx=2*Pi*(int(x)-int(Resolution/2))/Sizes[cascade],ky=2*Pi*(int(y)-int(Resolution/2))/Sizes[cascade];
+ const float *h=&data[((cascade*Resolution+y)*Resolution+x)*4];
+ const C e=std::polar(1.0,std::sqrt(9.81*std::hypot(kx,ky))*time);
+ return C(h[0],h[1])*e+C(h[2],h[3])*std::conj(e);
+ };
+ double maximum=0;bool nyquistZero=true;
+ for(unsigned cascade=0;cascade<3;++cascade) for(unsigned y=0;y<Resolution;++y) for(unsigned x=0;x<Resolution;++x) {
+ if(x==0 || y==0) for(unsigned c=0;c<4;++c) nyquistZero &= initial[((cascade*Resolution+y)*Resolution+x)*4+c]==0;
+ for(double time:{0.0,1.375,3.125}) {
+ const C a=height(initial,cascade,x,y,time),b=height(initial,cascade,(Resolution-x)%Resolution,(Resolution-y)%Resolution,time);
+ maximum=(std::max)(maximum,std::abs(a-std::conj(b)));
+ }
+ }
+ CHECK(nyquistZero && maximum<0.000000000001);
+ // An unpaired self-conjugate Nyquist coefficient is the precise old failure. This control must
+ // violate the reality assertion even though a packed CPU/GPU FFT comparison would still pass.
+ auto broken=initial;const unsigned at=(Resolution/2)*Resolution*4;
+ broken[at]=1;
+ const C bad=height(broken,0,0,Resolution/2,1.375);
+ CHECK(std::abs(bad-std::conj(bad))>0.01);
+}
+
+static void check_gpu_fft_ocean(SdlGpuFrame *frame)
+{
+ using namespace WaterFftSpectrum;
+ CHECK(frame->Ocean_Map(0)==NULL && frame->Ocean_Sampler()==NULL);
+ CHECK(!frame->Prepare_Ocean(NAN));
+ CHECK(frame->Prepare_Ocean(1.375f));if(!frame->Ocean_Map(0)) return;
+ CHECK(frame->Ocean_Map(6)==NULL && frame->Ocean_Sampler()!=NULL && frame->Ocean_Updates()==1);
+ std::vector<float> field=read_ocean(frame);const std::vector<float> initial=InitialSpectrum();
+ const auto mipReference=ocean_mip_reference(field);double mipError=0;
+ const auto mipField=check_ocean_mip_contents(frame,mipReference,mipError);
+ check_ocean_fractional_mips(frame,mipReference);
+ check_fft_spectral_reality(initial);
+ const unsigned plane=Resolution*Resolution*4;
+ auto value=[&](const std::vector<float>& data,unsigned cascade,unsigned channel,unsigned x,unsigned y) -> double {
+ return data[(cascade*2+channel/4)*plane+(y*Resolution+x)*4+channel%4];
+ };
+ bool finite=true,nonempty=true;double largest=0,means[24]={},energies[24]={};
+ for(unsigned m=0;m<6;++m) for(unsigned p=0;p<Resolution*Resolution;++p) for(unsigned c=0;c<4;++c) {
+ const double v=field[m*plane+p*4+c];finite &= std::isfinite(v);means[m*4+c]+=v;energies[m*4+c]+=v*v;
+ }
+ for(unsigned c=0;c<24;++c) {nonempty &= energies[c]>0.00001;CHECK(std::abs(means[c]/(Resolution*Resolution))<0.00001);}
+ CHECK(finite && nonempty);
+ const unsigned coordinates[][2]={{0,0},{17,53},{128,128},{255,7}};
+ for(unsigned cascade=0;cascade<3;++cascade) for(auto &point:coordinates) {
+ double expected[8];direct_ocean(initial,cascade,point[0],point[1],1.375,expected);
+ for(unsigned c=0;c<8;++c) {const double error=std::abs(value(field,cascade,c,point[0],point[1])-expected[c]);
+ largest=(std::max)(largest,error);CHECK(error<0.001+std::abs(expected[c])*0.0001);}
+ }
+ // Project several real GPU maps onto Fourier modes independently. A wrong UV orientation, sign,
+ // cascade size or derivative channel cannot satisfy dh/dx=i*kx*h and dh/dz=i*kz*h.
+ // Select nonzero modes inside the separated swell/wind/ripple bands (world
+ // wavelengths about 445, 94 and 23). Keep the nonzero-energy assertion below:
+ // a derivative check on a deliberately excluded mode would be vacuous.
+ const int modes[3][2]={{17,11},{19,11},{9,7}};
+ double derivativeError=0,finiteDifferenceError=0;
+ for(unsigned cascade=0;cascade<3;++cascade) {
+ using C=std::complex<double>;C coefficients[3]={};
+ const int mx=modes[cascade][0],my=modes[cascade][1];
+ std::vector<C> ex(Resolution),ey(Resolution);
+ for(unsigned i=0;i<Resolution;++i) {ex[i]=std::polar(1.0,-2*Pi*mx*i/Resolution);ey[i]=std::polar(1.0,-2*Pi*my*i/Resolution);}
+ for(unsigned y=0;y<Resolution;++y) for(unsigned x=0;x<Resolution;++x) {
+ const C phase=ex[x]*ey[y]/double(Resolution*Resolution);
+ coefficients[0]+=value(field,cascade,1,x,y)*phase;
+ coefficients[1]+=value(field,cascade,4,x,y)*phase;coefficients[2]+=value(field,cascade,5,x,y)*phase;
+ }
+ CHECK(std::abs(coefficients[0])>0.000001);
+ for(unsigned axis=0;axis<2;++axis) {
+ const double k=2*Pi*(axis?my:mx)/Sizes[cascade];
+ const double error=std::abs(coefficients[axis+1]-C(0,k)*coefficients[0]);
+ derivativeError=(std::max)(derivativeError,error);CHECK(error<0.00001);
+ if(cascade==2) {
+ const double step=Sizes[cascade]/Resolution,at=0.173;
+ auto height=[&](double p){return (coefficients[0]*std::polar(1.0,k*p)).real();};
+ const double numeric=(height(at-2*step)-8*height(at-step)+8*height(at+step)-height(at+2*step))/(12*step);
+ const double stored=(coefficients[axis+1]*std::polar(1.0,k*at)).real();
+ finiteDifferenceError=(std::max)(finiteDifferenceError,std::abs(numeric-stored));CHECK(std::abs(numeric-stored)<0.000001);
+ }
+ }
+ }
+ const uint64_t beforePause=frame->Ocean_Updates();CHECK(frame->Prepare_Ocean(1.375f));
+ CHECK(frame->Ocean_Updates()==beforePause && read_ocean(frame)==field);
+ for(unsigned level=1;level<=Phases;++level) CHECK(read_ocean(frame,level)==mipField[level]);
+ CHECK(!frame->Prepare_Ocean(INFINITY) && frame->Ocean_Updates()==beforePause);
+ SDL_GPUTexture *original=frame->Ocean_Map(0);
+ CHECK(frame->Resize(83,57));CHECK(frame->Prepare_Ocean(1.375f));
+ CHECK(frame->Ocean_Map(0)==original && frame->Ocean_Updates()==beforePause && read_ocean(frame)==field);
+ for(unsigned level=1;level<=Phases;++level) CHECK(read_ocean(frame,level)==mipField[level]);
+ CHECK(frame->Resize(WIDTH,HEIGHT));
+
+ // Exercise the actual recorded vertex-sampler path, including updates while an earlier field
+ // reader is still unsubmitted. Three vertex reads arrive as an unclamped float colour.
+ const char *vs=R"HLSL(
+Texture2D<float4> A:register(t0,space0);SamplerState SA:register(s0,space0);
+Texture2D<float4> B:register(t1,space0);SamplerState SB:register(s1,space0);
+Texture2D<float4> C:register(t2,space0);SamplerState SC:register(s2,space0);
+struct Output { float4 Position:SV_Position; [[vk::location(0)]] float4 Value:TEXCOORD0; };
+Output main(uint id:SV_VertexID) { Output output;output.Position=float4(id==1?3.0:-1.0,id==2?3.0:-1.0,0,1);
+float2 uv=float2(0,0);output.Value=float4(A.SampleLevel(SA,uv,2.375).y,B.SampleLevel(SB,uv,2.375).y,C.SampleLevel(SC,uv,2.375).y,1);return output; }
+)HLSL";
+ const char *ps="float4 main([[vk::location(0)]] float4 value:TEXCOORD0):SV_Target0 {return value;}";
+ std::vector<unsigned char> spirv;std::string error;
+ CHECK(SDL3_Compile_HLSL_To_SPIRV(vs,true,spirv,error));SDL_GPUShader *vertex=SDL3_Create_Shader(frame->Device(),spirv,true,error);CHECK(vertex);
+ CHECK(SDL3_Compile_HLSL_To_SPIRV(ps,false,spirv,error));SDL_GPUShader *pixel=SDL3_Create_Shader(frame->Device(),spirv,false,error);CHECK(pixel);
+ SDL_GPUColorTargetDescription colour={};colour.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
+ SDL_GPUGraphicsPipelineCreateInfo pipelineInfo={};pipelineInfo.vertex_shader=vertex;pipelineInfo.fragment_shader=pixel;
+ pipelineInfo.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;pipelineInfo.target_info.color_target_descriptions=&colour;pipelineInfo.target_info.num_color_targets=1;
+ pipelineInfo.target_info.has_depth_stencil_target=true;pipelineInfo.target_info.depth_stencil_format=(SDL_GPUTextureFormat)frame->Depth_Format();
+ SDL_GPUGraphicsPipeline *pipeline=SDL_CreateGPUGraphicsPipeline(frame->Device(),&pipelineInfo);CHECK(pipeline);
+ SDL_GPUTextureCreateInfo textureInfo={};textureInfo.type=SDL_GPU_TEXTURETYPE_2D;textureInfo.format=colour.format;
+ textureInfo.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET|SDL_GPU_TEXTUREUSAGE_SAMPLER;textureInfo.width=textureInfo.height=4;
+ textureInfo.layer_count_or_depth=textureInfo.num_levels=1;
+ SDL_GPUTexture *targets[2]={SDL_CreateGPUTexture(frame->Device(),&textureInfo),SDL_CreateGPUTexture(frame->Device(),&textureInfo)};
+ CHECK(targets[0] && targets[1]);
+ auto draw=[&](unsigned target) {
+ frame->Set_Target({targets[target],frame->Depth_For(4,4),4,4});SdlRecordedDraw record={};record.Pipeline=pipeline;record.Count=3;
+ memset(frame->Stage(16,record.VertexOffset),0,16);record.VertexSamplerCount=3;
+ for(unsigned i=0;i<3;++i) {record.VertexTextures[i]=frame->Ocean_Map(2*i);record.VertexSamplers[i]=frame->Ocean_Sampler();}
+ record.Viewport[2]=record.Viewport[3]=4;record.Viewport[5]=1;record.Scissor[2]=record.Scissor[3]=4;frame->Record_Draw(record);
+ };
+ if(pipeline && targets[0] && targets[1]) {
+ draw(0);CHECK(frame->Prepare_Ocean(3.125f));CHECK(frame->Ocean_Updates()==beforePause+1);draw(1);
+ const auto sampled=read_float_targets(frame,targets,2,4,4),advanced=read_ocean(frame);
+ const auto advancedReference=ocean_mip_reference(advanced);
+ const auto advancedMips=check_ocean_mip_contents(frame,advancedReference,mipError);
+ check_ocean_fractional_mips(frame,advancedReference);
+ double changedMipSample=0;
+ for(unsigned c=0;c<3;++c) {
+ const double oldSample=ocean_mip_sample(mipReference,c*2,1,0,0,2.375);
+ const double newSample=ocean_mip_sample(advancedReference,c*2,1,0,0,2.375);
+ CHECK(std::abs(sampled[c]-oldSample)<0.00001);
+ CHECK(std::abs(sampled[64+c]-newSample)<0.00001);
+ changedMipSample=(std::max)(changedMipSample,std::abs(newSample-oldSample));
+ double expected[8];direct_ocean(initial,c,17,53,3.125,expected);
+ for(unsigned component=0;component<8;++component) CHECK(std::abs(value(advanced,c,component,17,53)-expected[component])<0.001+std::abs(expected[component])*0.0001);
+ }
+ CHECK(advanced!=field);
+ CHECK(changedMipSample>0.0001 && advancedMips[2]!=mipField[2]);
+ }
+ CHECK(frame->Flush());frame->Set_Target(frame->Back_Buffer_Target());
+ for(auto *target:targets) if(target) SDL_ReleaseGPUTexture(frame->Device(),target);
+ if(pipeline) SDL_ReleaseGPUGraphicsPipeline(frame->Device(),pipeline);
+ if(vertex) SDL_ReleaseGPUShader(frame->Device(),vertex);if(pixel) SDL_ReleaseGPUShader(frame->Device(),pixel);
+ printf("sdl_gpu_frame_selfcheck: GPU FFT ocean: all24 finite channels, direct Fourier error %.8f, spectral derivative error %.9f, finite-difference mode error %.9f, independent all-mip box error %.9f; all9-mip pause/resize reuse and queued trilinear vertex-sampled field ordering checked\n",largest,derivativeError,finiteDifferenceError,mipError);
+}
+
// 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])
{
@@ -79,6 +6902,1254 @@ static unsigned int mismatches(const std::vector<uint8_t> &got, const uint16_t (
return bad;
}
+// Execute the actual generated integration, including UV0 residual and screen-to-world
+// derivatives. Field sampling is controlled here; native terrain/mesh sampling is separate.
+static void check_gpu_water_coastal_crest_injection(SdlGpuFrame *frame,const std::string &production)
+{
+ auto block=[&](const char *first,const char *last) {
+ const size_t a=production.find(first),b=a==std::string::npos?std::string::npos:production.find(last,a);
+ CHECK(a!=std::string::npos && b!=std::string::npos);
+ return a!=std::string::npos && b!=std::string::npos?production.substr(a,b-a):std::string();
+ };
+ const std::string composition=block(" float determinant = parameterDx.x", " WaveCage cage=waveCage(");
+ const std::string gradient=block("float2 fftParameterGradient(", "\n}")+"\n}\n";
+ const std::string metadata=block(" float meshCorrection=OpticalParameters.w", " float2 materialUV=");
+ const std::string offshoreSource=block(" float offshore = opticalContext.r", " // The mesh and this derivative");
+ CHECK(composition.find("slope+=coastalCorrection.yz;meshCorrection+=coastalCorrection.x;")!=std::string::npos);
+ if(composition.empty() || metadata.empty() || offshoreSource.empty() || gradient.size()<10)return;
+ const std::string shore=WaterShoreFoam::Source(),crest=WaterCoastalCrest::Source();
+ CHECK(production.find(shore)!=std::string::npos && production.find(crest)!=std::string::npos);
+ // Each scenario occupies four raster rows so every derivative quad stays in one case.
+ // The two eight-pixel output tiles have identical parameter fields and return height/
+ // slopes/residual and normal separately. All test fields vary in world, not screen, axes.
+ struct Query {float f[8][4];};
+ Query ordinary={{{1.7f,-2.3f,0,1},{20,.25f,.11f,.31f},{2,.75f,.65f,.9f},{1,1,0,0},
+ {.013f,-.008f,.03f,-.025f},{.003f,-.002f,.021f,.017f},{.04f,-.03f,.005f,-.002f},{.004f,.003f,-.001f,.002f}}};
+ auto broad=[](double x,double y,double time) {
+ double value=0;
+ for(unsigned i=0;i<WaterShoreFoam::ModeCount;++i) {
+ const auto &m=WaterShoreFoam::Modes[i];
+ const double phase=x*m.kx+y*m.ky-time*m.omega+m.phase;
+ value+=m.amplitude*(std::sin(phase)+.13*std::sin(2*phase));
+ }
+ return value;
+ };
+ float crestTime=-1,troughTime=-1;
+ for(unsigned i=0;i<600 && (crestTime<0 || troughTime<0);++i) {
+ const double value=broad(ordinary.f[0][0],ordinary.f[0][1],i/30.);
+ if(crestTime<0 && value>1)crestTime=float(i)/30;
+ if(troughTime<0 && value<-1)troughTime=float(i)/30;
+ }
+ CHECK(crestTime>=0 && troughTime>=0);if(crestTime<0 || troughTime<0)return;
+ ordinary.f[0][2]=crestTime;
+ std::vector<Query> queries(14,ordinary);
+ queries[1].f[1][3]=-.27f;queries[1].f[5][2]=-.019f;queries[1].f[5][3]=.029f; // signed collar residual
+ queries[2].f[2][0]=.45f; // varying depth inside the wet gate
+ queries[3].f[1][2]=.95f; // obstacle restoration gain closed
+ queries[4].f[2][1]=0;queries[4].f[6][2]=queries[4].f[6][3]=0;
+ queries[5].f[2][2]=0;queries[5].f[7][0]=queries[5].f[7][1]=0;
+ queries[6].f[3][3]=.2f; // nonzero offshore
+ queries[7].f[3][2]=1; // river
+ queries[8].f[3][0]=0; // missing optical context
+ queries[9].f[3][1]=0; // missing terrain texture
+ queries[10].f[0][2]=troughTime;
+ queries[11].f[2][0]=.1f;queries[11].f[6][0]=queries[11].f[6][1]=0;
+ queries[12].f[0][3]=0; // metadata gate off; crest still active
+ queries[13].f[1][3]=0;queries[13].f[5][2]=queries[13].f[5][3]=0;
+ const unsigned width=16,height=unsigned(queries.size())*4;
+ CHECK(queries.size()*sizeof(Query)<=4096);if(queries.size()*sizeof(Query)>4096)return;
+ std::string ps="struct Query{float4 f[8];};cbuffer CoastComposition:register(b0){Query Queries["+std::to_string(queries.size())+"];};\n"
+ "struct Input{float4 Diffuse;float2 TexCoord0;};\n"+shore+crest+gradient+R"COAST(
+float4 main(float4 pixel:SV_Position):SV_Target0 {
+ uint row=(uint)pixel.y/4;Query q=Queries[row];
+ float2 tile=float2((uint)pixel.x%8,(uint)pixel.y%4);
+ float2 offset=tile.x*float2(.35,.11)+tile.y*float2(-.09,.29);
+ float2 wavePosition=q.f[0].xy+offset;
+ float2 parameterDx=ddx(wavePosition),parameterDy=ddy(wavePosition);
+ float time=q.f[0].z;
+ float4 OpticalParameters=float4(0,0,q.f[3].x,q.f[0].w);
+ float4 TerrainParameters=float4(0,0,0,q.f[3].y);
+ float4 WaterParameters=float4(time,q.f[3].z,0,0);
+ float baseLevel=q.f[1].x+dot(q.f[4].xy,offset);
+ float attenuation=q.f[1].z+dot(q.f[5].xy,offset);
+ float surfaceTerrainHeight=baseLevel-(q.f[2].x+dot(q.f[6].xy,offset));
+ float4 opticalContext=float4(q.f[3].w,0,q.f[2].z+dot(q.f[7].xy,offset),q.f[2].y+dot(q.f[6].zw,offset));
+ Input input;input.Diffuse=float4(q.f[2].w+dot(q.f[7].zw,offset),0,0,1);
+ input.TexCoord0=float2(q.f[1].w+dot(q.f[5].zw,offset),0);
+ float3 wave=float3(q.f[1].y+dot(q.f[4].zw,offset),q.f[4].zw);
+ float3 legacyWave=wave,oceanWave=wave;
+)COAST"+metadata+offshoreSource+composition+R"COAST(
+ if(pixel.x<8)return float4(continuousHeight,slope,meshCorrection);
+ return float4(normal,1);
+}
+)COAST";
+ const bool placed=sdl3target_detail::place_registers(ps,false);CHECK(placed);if(!placed)return;
+ const char *vs="float4 main(uint id:SV_VertexID):SV_Position{return float4(id==1?3.0:-1.0,id==2?3.0:-1.0,0,1);}";
+ struct Resources {
+ SDL_GPUDevice*device;SDL_GPUShader*vs=nullptr,*ps=nullptr;SDL_GPUGraphicsPipeline*pipeline=nullptr;SDL_GPUTexture*target=nullptr;
+ ~Resources(){if(target)SDL_ReleaseGPUTexture(device,target);if(pipeline)SDL_ReleaseGPUGraphicsPipeline(device,pipeline);
+ if(vs)SDL_ReleaseGPUShader(device,vs);if(ps)SDL_ReleaseGPUShader(device,ps);}
+ }r;r.device=frame->Device();std::vector<unsigned char>spirv;std::string error;
+ bool ok=SDL3_Compile_HLSL_To_SPIRV(vs,true,spirv,error);CHECK(ok);if(!ok)return;
+ r.vs=SDL3_Create_Shader(r.device,spirv,true,error);CHECK(r.vs);if(!r.vs)return;
+ ok=SDL3_Compile_HLSL_To_SPIRV(ps,false,spirv,error);CHECK(ok);if(!ok){printf("coastal injection PS: %s\n",error.c_str());return;}
+ unsigned samplers=0,buffers=0;SDL3_Shader_Slots(spirv,false,samplers,buffers);CHECK(samplers==0&&buffers==1);if(samplers!=0||buffers!=1)return;
+ r.ps=SDL3_Create_Shader(r.device,spirv,false,error);CHECK(r.ps);if(!r.ps)return;
+ SDL_GPUColorTargetDescription colour={};colour.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
+ SDL_GPUGraphicsPipelineCreateInfo pi={};pi.vertex_shader=r.vs;pi.fragment_shader=r.ps;pi.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;
+ pi.target_info.color_target_descriptions=&colour;pi.target_info.num_color_targets=1;
+ r.pipeline=SDL_CreateGPUGraphicsPipeline(r.device,&pi);CHECK(r.pipeline);if(!r.pipeline)return;
+ SDL_GPUTextureCreateInfo ti={};ti.type=SDL_GPU_TEXTURETYPE_2D;ti.format=colour.format;ti.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;
+ ti.width=width;ti.height=height;ti.layer_count_or_depth=ti.num_levels=1;r.target=SDL_CreateGPUTexture(r.device,&ti);CHECK(r.target);if(!r.target)return;
+ CHECK(frame->Flush());
+ auto render=[&](){SDL_GPUCommandBuffer*cmd=SDL_AcquireGPUCommandBuffer(r.device);CHECK(cmd);if(!cmd)return std::vector<float>();
+ SDL_GPUColorTargetInfo target={};target.texture=r.target;target.load_op=SDL_GPU_LOADOP_DONT_CARE;target.store_op=SDL_GPU_STOREOP_STORE;
+ SDL_GPURenderPass*pass=SDL_BeginGPURenderPass(cmd,&target,1,nullptr);CHECK(pass);if(!pass){SDL_CancelGPUCommandBuffer(cmd);return std::vector<float>();}
+ SDL_BindGPUGraphicsPipeline(pass,r.pipeline);SDL_PushGPUFragmentUniformData(cmd,0,queries.data(),unsigned(queries.size()*sizeof(Query)));
+ SDL_DrawGPUPrimitives(pass,3,1,0,0);SDL_EndGPURenderPass(pass);CHECK(SDL_SubmitGPUCommandBuffer(cmd));return read_float_targets(frame,&r.target,1,width,height);};
+ const auto actual=render(),repeat=render();CHECK(actual==repeat&&actual.size()==width*height*4);if(actual.size()!=width*height*4)return;
+ auto scalar=[&](const Query&q,double ox,double oy,double &addition,double &residual) {
+ auto unit=[](double x){return (std::max)(0.,(std::min)(1.,x));};
+ auto smooth=[&](double a,double b,double x){const double t=unit((x-a)/(b-a));return t*t*(3-2*t);};
+ const double base=q.f[1][0]+q.f[4][0]*ox+q.f[4][1]*oy;
+ const double wave=q.f[1][1]+q.f[4][2]*ox+q.f[4][3]*oy;
+ const double damping=q.f[1][2]+q.f[5][0]*ox+q.f[5][1]*oy;
+ const double depth=q.f[2][0]+q.f[6][0]*ox+q.f[6][1]*oy;
+ const double support=q.f[2][1]+q.f[6][2]*ox+q.f[6][3]*oy;
+ const double exposure=q.f[2][2]+q.f[7][0]*ox+q.f[7][1]*oy;
+ const double obstacle=q.f[2][3]+q.f[7][2]*ox+q.f[7][3]*oy;
+ const double h=broad(q.f[0][0]+ox,q.f[0][1]+oy,q.f[0][2]);
+ residual=q.f[0][3]>.5?q.f[1][3]+q.f[5][2]*ox+q.f[5][3]*oy:0;
+ addition=0;
+ const double offshore=q.f[3][3]*q.f[3][0]*(1-q.f[3][2]);
+ if(q.f[3][0]>.5 && q.f[3][1]>.5 && q.f[3][2]<.5 && offshore==0 && support>0 && exposure>0 && h>0 && depth>double(WaterShoreFoam::MinDepth)) {
+ const double clearance=depth-double(WaterShoreFoam::MinDepth);
+ const double gain=(std::max)(0.,unit(obstacle)-double(.5f/255.f)-unit(damping));
+ addition=unit(support)*unit(exposure)*smooth(WaterShoreFoam::MinDepth,WaterShoreFoam::WetDepth,depth)*gain
+ *clearance*std::tanh(h/clearance)*smooth(0,WaterShoreFoam::CrestHeight,h);
+ }
+ return base+wave*damping+residual+addition;
+ };
+ double maximum=0,omittedHeight=0,duplicateHeight=0,omittedResidual=0;unsigned active=0,inactive=0;
+ for(unsigned c=0;c<queries.size();++c)for(unsigned y=0;y<4;++y)for(unsigned x=0;x<8;++x) {
+ const Query&q=queries[c];const double ox=x*.35-y*.09,oy=x*.11+y*.29;
+ double addition=0,residual=0;const double h=scalar(q,ox,oy,addition,residual);
+ auto heightAt=[&](double px,double py){double a=0,r=0;return scalar(q,px,py,a,r);};
+ const double gx=(heightAt(ox+1e-4,oy)-heightAt(ox-1e-4,oy))/.0002;
+ const double gy=(heightAt(ox,oy+1e-4)-heightAt(ox,oy-1e-4))/.0002;
+ const double inverse=1/std::sqrt(1+gx*gx+gy*gy);
+ const double expected[8]={h,gx,gy,residual+addition,-gx*inverse,-gy*inverse,inverse,1};
+ for(unsigned channel=0;channel<8;++channel) {
+ const unsigned index=((c*4+y)*width+x+(channel>=4?8:0))*4+channel%4;
+ const double error=std::abs(double(actual[index])-expected[channel]);maximum=(std::max)(maximum,error);
+ if(!(std::isfinite(actual[index])&&error<.0001))printf("coastal injection case%u xy%u,%u channel%u actual%.9g expected%.9g\n",c,x,y,channel,double(actual[index]),expected[channel]);
+ CHECK(std::isfinite(actual[index])&&error<.0001);
+ }
+ // Explicit controls: missing/doubled crest and losing the signed UV0 residual would
+ // all be detected at this threshold; they are not merely alternate algebraic labels.
+ omittedHeight=(std::max)(omittedHeight,std::abs(addition));duplicateHeight=(std::max)(duplicateHeight,std::abs(addition));
+ omittedResidual=(std::max)(omittedResidual,std::abs(residual));
+ if(addition>.01)++active;else if(addition==0)++inactive;
+ if(c==0) {
+ // Real generated-branch controls under identical fields: optical gate off
+ // removes exactly one crest; zero UV0 removes exactly one signed residual.
+ const unsigned index=(y*width+x)*4;
+ CHECK(std::abs(double(actual[index])-actual[((8*4+y)*width+x)*4]-addition)<.0001);
+ CHECK(std::abs(double(actual[index+3])-actual[((8*4+y)*width+x)*4+3]-addition)<.0001);
+ CHECK(std::abs(double(actual[index])-actual[((13*4+y)*width+x)*4]-residual)<.0001);
+ CHECK(std::abs(double(actual[index+3])-actual[((13*4+y)*width+x)*4+3]-residual)<.0001);
+ }
+ }
+ CHECK(active>64&&inactive>192);CHECK(omittedHeight>.1&&duplicateHeight>.1&&omittedResidual>.2);
+ printf("sdl_gpu_frame_selfcheck: actual coastal injection %zu cases, %u raster samples, scalar/FD-normal max %.9g; active%u inactive%u, omitted/doubled crest %.7g/%.7g, omitted UV0 %.7g, exact repeat\n",
+ queries.size(),unsigned(queries.size())*32,maximum,active,inactive,omittedHeight,duplicateHeight,omittedResidual);
+}
+
+
+#if defined(__linux__)
+static void check_gpu_water_coastal_crest(SdlGpuFrame *frame)
+{
+ struct Env {
+ bool present;std::string saved;
+ Env(){const char*p=getenv("ZH_WATER_COAST_CREST");present=p!=nullptr;saved=p?p:"";}
+ ~Env(){if(present)setenv("ZH_WATER_COAST_CREST",saved.c_str(),1);else unsetenv("ZH_WATER_COAST_CREST");}
+ }restore;
+ PixelPipelineDescription description={};std::string baseline,production,disabled;
+ CHECK(unsetenv("ZH_WATER_COAST_CREST")==0);
+ bool generated=EngineShader_Pixel_Program(ENGINE_SHADER_WATER_TRAPEZOID,description,baseline,COMBINER_SHADER_TARGET_SDL3_GPU);CHECK(generated);if(!generated)return;
+ CHECK(setenv("ZH_WATER_COAST_CREST","0",1)==0);
+ generated=EngineShader_Pixel_Program(ENGINE_SHADER_WATER_TRAPEZOID,description,disabled,COMBINER_SHADER_TARGET_SDL3_GPU);CHECK(generated&&disabled==baseline);if(!generated)return;
+ CHECK(setenv("ZH_WATER_COAST_CREST","1",1)==0);
+ generated=EngineShader_Pixel_Program(ENGINE_SHADER_WATER_TRAPEZOID,description,production,COMBINER_SHADER_TARGET_SDL3_GPU);CHECK(generated);if(!generated)return;
+ const std::string helper=WaterCoastalCrest::Source();const size_t at=production.find(helper);CHECK(at!=std::string::npos);if(at==std::string::npos)return;
+ const std::string marker=" // All screen derivatives are evaluated before the eligibility branch.";
+ const size_t begin=production.find(marker),end=production.find(" float3 normal = normalize(float3(-slope, 1.0));",begin);
+ CHECK(begin!=std::string::npos&&end!=std::string::npos);if(begin==std::string::npos||end==std::string::npos)return;
+ const std::string injection=production.substr(begin,end-begin);
+ CHECK(injection.find("slope+=coastalCorrection.yz;meshCorrection+=coastalCorrection.x;")!=std::string::npos);
+ CHECK(injection.find("offshore==0.0 && opticalContext.a>0.0 && opticalContext.b>0.0")!=std::string::npos);
+ CHECK(injection.find("WaterParameters.y<0.5")!=std::string::npos);
+ std::string stripped=production;stripped.erase(begin,end-begin);stripped.erase(at,helper.size());CHECK(stripped==baseline);
+ // Compile both actual production variants with opt-in, not merely the small helper fixture.
+ std::vector<unsigned char> fullSpirv;std::string fullError;
+ CHECK(SDL3_Compile_HLSL_To_SPIRV(production,false,fullSpirv,fullError));
+ std::string river;generated=EngineShader_Pixel_Program(ENGINE_SHADER_WATER_RIVER,description,river,COMBINER_SHADER_TARGET_SDL3_GPU);CHECK(generated);
+ if(generated)CHECK(SDL3_Compile_HLSL_To_SPIRV(river,false,fullSpirv,fullError));
+ struct Query {float f[6][4];};std::vector<Query> queries;
+ for(unsigned i=0;i<32;++i) {
+ Query q={{{.05f+.085f*i,.17f,-.23f,0},{.17f+.11f*i,.07f,-.04f,0},
+ {.13f+float(i%6)*.11f,.031f,-.023f,0},{.21f+float(i%5)*.13f,-.017f,.021f,0},
+ {.67f+float(i%4)*.07f,.011f,-.019f,0},{.03f+float(i%7)*.035f,.013f,.009f,0}}};queries.push_back(q);
+ }
+ Query q=queries[7];q.f[0][0]=-1;queries.push_back(q);q=queries[7];q.f[1][0]=0;queries.push_back(q);
+ q=queries[7];q.f[2][0]=0;queries.push_back(q);q=queries[7];q.f[3][0]=0;queries.push_back(q);
+ q=queries[7];q.f[4][0]=q.f[5][0];queries.push_back(q);q=queries[7];q.f[0][0]=std::numeric_limits<float>::quiet_NaN();queries.push_back(q);
+ const unsigned rows=unsigned(queries.size()),columns=2;CHECK(rows*sizeof(Query)<=4096);if(rows*sizeof(Query)>4096)return;
+ const char *vs="float4 main(uint id:SV_VertexID):SV_Position{return float4(id==1?3.0:-1.0,id==2?3.0:-1.0,0,1);}";
+ const std::string shore=WaterShoreFoam::Source();CHECK(production.find(shore)!=std::string::npos);
+ std::string ps="struct Query{float4 f[6];};cbuffer CoastQueries:register(b0){Query Queries["+std::to_string(rows)+"];};\n"+
+ shore+production.substr(at,helper.size())+R"COAST(
+float4 main(float4 pixel:SV_Position):SV_Target0 {
+ Query q=Queries[(uint)pixel.y];float3 d=waterCoastalCrest(q.f[0].xyz,q.f[1].xyz,q.f[2].xyz,q.f[3].xyz,q.f[4].xyz,q.f[5].xyz);
+ if(pixel.x<1)return float4(d,.2+d.x);
+ return float4(normalize(float3(-float2(.03,-.02)-d.yz,1)),1);
+}
+)COAST";
+ const bool placed=sdl3target_detail::place_registers(ps,false);CHECK(placed);if(!placed)return;
+ struct Resources {
+ SDL_GPUDevice*device;SDL_GPUShader*vs=nullptr,*ps=nullptr;SDL_GPUGraphicsPipeline*pipeline=nullptr;SDL_GPUTexture*target=nullptr;
+ ~Resources(){if(target)SDL_ReleaseGPUTexture(device,target);if(pipeline)SDL_ReleaseGPUGraphicsPipeline(device,pipeline);
+ if(vs)SDL_ReleaseGPUShader(device,vs);if(ps)SDL_ReleaseGPUShader(device,ps);}
+ }r;r.device=frame->Device();std::vector<unsigned char>spirv;std::string error;
+ bool ok=SDL3_Compile_HLSL_To_SPIRV(vs,true,spirv,error);CHECK(ok);if(!ok)return;
+ r.vs=SDL3_Create_Shader(r.device,spirv,true,error);CHECK(r.vs);if(!r.vs)return;
+ ok=SDL3_Compile_HLSL_To_SPIRV(ps,false,spirv,error);CHECK(ok);if(!ok){printf("coastal crest PS: %s\n",error.c_str());return;}
+ unsigned samplers=0,buffers=0;SDL3_Shader_Slots(spirv,false,samplers,buffers);CHECK(samplers==0&&buffers==1);if(samplers!=0||buffers!=1)return;
+ r.ps=SDL3_Create_Shader(r.device,spirv,false,error);CHECK(r.ps);if(!r.ps)return;
+ SDL_GPUColorTargetDescription colour={};colour.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
+ SDL_GPUGraphicsPipelineCreateInfo pi={};pi.vertex_shader=r.vs;pi.fragment_shader=r.ps;pi.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;
+ pi.target_info.color_target_descriptions=&colour;pi.target_info.num_color_targets=1;
+ r.pipeline=SDL_CreateGPUGraphicsPipeline(r.device,&pi);CHECK(r.pipeline);if(!r.pipeline)return;
+ SDL_GPUTextureCreateInfo ti={};ti.type=SDL_GPU_TEXTURETYPE_2D;ti.format=colour.format;ti.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;
+ ti.width=columns;ti.height=rows;ti.layer_count_or_depth=ti.num_levels=1;r.target=SDL_CreateGPUTexture(r.device,&ti);CHECK(r.target);if(!r.target)return;
+ CHECK(frame->Flush());
+ auto render=[&](){SDL_GPUCommandBuffer*cmd=SDL_AcquireGPUCommandBuffer(r.device);CHECK(cmd);if(!cmd)return std::vector<float>();
+ SDL_GPUColorTargetInfo target={};target.texture=r.target;target.load_op=SDL_GPU_LOADOP_DONT_CARE;target.store_op=SDL_GPU_STOREOP_STORE;
+ SDL_GPURenderPass*pass=SDL_BeginGPURenderPass(cmd,&target,1,nullptr);CHECK(pass);if(!pass){SDL_CancelGPUCommandBuffer(cmd);return std::vector<float>();}
+ SDL_BindGPUGraphicsPipeline(pass,r.pipeline);SDL_PushGPUFragmentUniformData(cmd,0,queries.data(),unsigned(rows*sizeof(Query)));
+ SDL_DrawGPUPrimitives(pass,3,1,0,0);SDL_EndGPURenderPass(pass);CHECK(SDL_SubmitGPUCommandBuffer(cmd));return read_float_targets(frame,&r.target,1,columns,rows);};
+ const auto actual=render(),paused=render();CHECK(actual==paused&&actual.size()==rows*columns*4);if(actual.size()!=rows*columns*4)return;
+ auto scalar=[](const double f[6]) {
+ auto unit=[](double x){return (std::max)(0.,(std::min)(1.,x));};
+ auto smooth=[&](double a,double b,double x){const double t=unit((x-a)/(b-a));return t*t*(3-2*t);};
+ for(unsigned i=0;i<6;++i)if(!std::isfinite(f[i]))return 0.;
+ if(f[0]<=0||f[1]<=double(WaterShoreFoam::MinDepth))return 0.;
+ const double c=f[1]-double(WaterShoreFoam::MinDepth);
+ const double gain=(std::max)(0.,unit(f[4])-double(.5f/255.f)-unit(f[5]));
+ return unit(f[2])*unit(f[3])*smooth(WaterShoreFoam::MinDepth,WaterShoreFoam::WetDepth,f[1])*gain*c*std::tanh(f[0]/c)*smooth(0,WaterShoreFoam::CrestHeight,f[0]);
+ };
+ double maximum=0;unsigned active=0;
+ for(unsigned row=0;row<rows;++row) {
+ double f[6];for(unsigned n=0;n<6;++n)f[n]=queries[row].f[n][0];
+ double d[3]={scalar(f),0,0};
+ for(unsigned axis=0;axis<2;++axis){double a[6],b[6];for(unsigned n=0;n<6;++n){a[n]=f[n]-1e-4*queries[row].f[n][axis+1];b[n]=f[n]+1e-4*queries[row].f[n][axis+1];}d[axis+1]=(scalar(b)-scalar(a))/.0002;}
+ // At closed guards the production field is identically zero, including endpoint derivatives.
+ if(row>=32)d[0]=d[1]=d[2]=0;
+ double nx=-.03-d[1],ny=.02-d[2],nz=1,norm=std::sqrt(nx*nx+ny*ny+1);nx/=norm;ny/=norm;nz/=norm;
+ const double expected[8]={d[0],d[1],d[2],.2+d[0],nx,ny,nz,1};
+ for(unsigned c=0;c<8;++c){const double error=std::abs(double(actual[row*8+c])-expected[c]);maximum=(std::max)(maximum,error);
+ if(!(std::isfinite(actual[row*8+c])&&error<.0001))printf("coastal crest row%u channel%u actual%.9g expected%.9g\n",row,c,double(actual[row*8+c]),expected[c]);
+ CHECK(std::isfinite(actual[row*8+c])&&error<.0001);}
+ active+=d[0]>.01;
+ }
+ CHECK(active>15);
+ printf("sdl_gpu_frame_selfcheck: coastal crest %u cases; actual production helper vs independent scalar/FD-normal max %.9g, exact pause, opt-out source identity\n",rows,maximum);
+ check_gpu_water_coastal_crest_injection(frame,production);
+}
+#endif // __linux__
+
+#if defined(__linux__)
+static void check_gpu_water_shore_front(SdlGpuFrame *frame)
+{
+ using namespace WaterShoreFoam;
+ struct Query {float position[4],normal[4],footprint[4],context[4],gates[4];};
+ std::vector<Query> queries;
+ const float widths[]={0,.0001f,.01f,.2f,1.f,3.f,6.283185307f,9.f};
+ for(unsigned i=0;i<32;++i)queries.push_back({{float((i*7)%13)-6,float((i*3)%11)-5,float(i)*.41f,float(i)*.23f-1},
+ {-1,0,widths[i%8],float(i%4)*.2f},{float(i%4)*.5f,0,0,float(i%3)*.75f},
+ {2,1,.1f,1},{1,1,1,.2f}});
+ Query q=queries[7];q.normal[0]=1;queries.push_back(q);
+ q=queries[7];q.gates[0]=0;queries.push_back(q);q=queries[7];q.gates[1]=0;queries.push_back(q);
+ q=queries[7];q.gates[2]=0;queries.push_back(q);q=queries[7];q.context[0]=.15f;queries.push_back(q);
+ q=queries[7];q.context[0]=20;queries.push_back(q);q=queries[7];q.normal[0]=q.normal[1]=0;queries.push_back(q);
+ const unsigned rows=unsigned(queries.size()),columns=3;CHECK(rows*sizeof(Query)<=4096);if(rows*sizeof(Query)>4096)return;
+ PixelPipelineDescription description={};std::string production;
+ const bool generated=EngineShader_Pixel_Program(ENGINE_SHADER_WATER_TRAPEZOID,description,production,COMBINER_SHADER_TARGET_SDL3_GPU);
+ CHECK(generated);if(!generated)return;
+ const std::string helper=Source();const size_t at=production.find(helper);CHECK(at!=std::string::npos);if(at==std::string::npos)return;
+ CHECK(production.find("terrainSlope,opticalContext.b,shoreSupport)*shoreFront.x;")!=std::string::npos);
+ CHECK(production.find("foam=waterShoreBlendFrontHistory(foam,shoreRate,shoreFront.y,shoreHistory,")!=std::string::npos);
+ const char *vs="float4 main(uint id:SV_VertexID):SV_Position{return float4(id==1?3.0:-1.0,id==2?3.0:-1.0,0,1);}";
+ std::string ps="struct Query{float4 position,normal,footprint,context,gates;};cbuffer FrontQueries:register(b0){Query Queries["+std::to_string(rows)+"];};\n"+
+ production.substr(at,helper.size())+R"FRONT(
+float4 main(float4 pixel:SV_Position):SV_Target0 {
+ Query q=Queries[(uint)pixel.y];float2 front;
+ float4 wave=waterShoreWaveFront(q.position.xy,q.position.z,q.normal.xy,q.footprint.xy,q.footprint.zw,front);
+ float rate=waterShoreRate(wave,q.context.x,q.context.y,q.normal.xy,q.context.z,q.context.w,q.gates.x)*front.x;
+ if(pixel.x<1)return float4(front,rate,waterShoreFrontFresh(rate,front.y));
+ if(pixel.x<2)return float4(waterShoreBlendFrontHistory(q.gates.w,rate,front.y,q.normal.w,q.gates.x,q.gates.y,q.gates.z),wave.xyz);
+ float s=sin(q.position.w),c=cos(q.position.w);
+ return float4(waterShoreFrontKernel(s,c),waterShoreFrontFiltered(s,c,q.normal.z),waterShoreFresh(rate),wave.w);
+}
+)FRONT";
+ const bool placed=sdl3target_detail::place_registers(ps,false);CHECK(placed);if(!placed)return;
+ struct Resources {
+ SDL_GPUDevice*device;SDL_GPUShader*vs=nullptr,*ps=nullptr;SDL_GPUGraphicsPipeline*pipeline=nullptr;SDL_GPUTexture*target=nullptr;
+ ~Resources(){if(target)SDL_ReleaseGPUTexture(device,target);if(pipeline)SDL_ReleaseGPUGraphicsPipeline(device,pipeline);
+ if(vs)SDL_ReleaseGPUShader(device,vs);if(ps)SDL_ReleaseGPUShader(device,ps);}
+ }r;r.device=frame->Device();std::vector<unsigned char>spirv;std::string error;
+ bool ok=SDL3_Compile_HLSL_To_SPIRV(vs,true,spirv,error);CHECK(ok);if(!ok)return;
+ r.vs=SDL3_Create_Shader(r.device,spirv,true,error);CHECK(r.vs);if(!r.vs)return;
+ ok=SDL3_Compile_HLSL_To_SPIRV(ps,false,spirv,error);CHECK(ok);if(!ok){printf("shore front PS: %s\n",error.c_str());return;}
+ unsigned samplers=0,buffers=0;SDL3_Shader_Slots(spirv,false,samplers,buffers);CHECK(samplers==0&&buffers==1);if(samplers!=0||buffers!=1)return;
+ r.ps=SDL3_Create_Shader(r.device,spirv,false,error);CHECK(r.ps);if(!r.ps)return;
+ SDL_GPUColorTargetDescription colour={};colour.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
+ SDL_GPUGraphicsPipelineCreateInfo pi={};pi.vertex_shader=r.vs;pi.fragment_shader=r.ps;pi.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;
+ pi.target_info.color_target_descriptions=&colour;pi.target_info.num_color_targets=1;
+ r.pipeline=SDL_CreateGPUGraphicsPipeline(r.device,&pi);CHECK(r.pipeline);if(!r.pipeline)return;
+ SDL_GPUTextureCreateInfo ti={};ti.type=SDL_GPU_TEXTURETYPE_2D;ti.format=colour.format;ti.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;
+ ti.width=columns;ti.height=rows;ti.layer_count_or_depth=ti.num_levels=1;r.target=SDL_CreateGPUTexture(r.device,&ti);CHECK(r.target);if(!r.target)return;
+ CHECK(frame->Flush());
+ auto render=[&](){SDL_GPUCommandBuffer*cmd=SDL_AcquireGPUCommandBuffer(r.device);CHECK(cmd);if(!cmd)return std::vector<float>();
+ SDL_GPUColorTargetInfo target={};target.texture=r.target;target.load_op=SDL_GPU_LOADOP_DONT_CARE;target.store_op=SDL_GPU_STOREOP_STORE;
+ SDL_GPURenderPass*pass=SDL_BeginGPURenderPass(cmd,&target,1,nullptr);CHECK(pass);if(!pass){SDL_CancelGPUCommandBuffer(cmd);return std::vector<float>();}
+ SDL_BindGPUGraphicsPipeline(pass,r.pipeline);SDL_PushGPUFragmentUniformData(cmd,0,queries.data(),unsigned(rows*sizeof(Query)));
+ SDL_DrawGPUPrimitives(pass,3,1,0,0);SDL_EndGPURenderPass(pass);CHECK(SDL_SubmitGPUCommandBuffer(cmd));return read_float_targets(frame,&r.target,1,columns,rows);};
+ const auto actual=render(),paused=render();CHECK(actual==paused&&actual.size()==rows*columns*4);if(actual.size()!=rows*columns*4)return;
+ // Independent double reference: locate the harmonic crest numerically and integrate
+ // pixel support by midpoint samples, not the shader's periodic antiderivative.
+ const double piD=std::acos(-1.0),tauD=2*piD;double lo=0,hi=piD*.5;
+ for(unsigned n=0;n<48;++n){double mid=(lo+hi)*.5;if(std::cos(mid)+.26*std::cos(2*mid)>0)lo=mid;else hi=mid;}
+ const double crest=(lo+hi)*.5,crestCos=std::cos(crest),durationPhase=piD-crest;
+ auto kernel=[&](double phase){phase-=tauD*std::floor(phase/tauD);if(phase<=crest||phase>=piD)return 0.0;
+ const double u=(crestCos-std::cos(phase))/(1+crestCos);return 4*u*(1-u);};
+ auto average=[&](double phase,double width){if(width==0)return kernel(phase);double sum=0;
+ for(unsigned i=0;i<8192;++i)sum+=kernel(phase+width*((i+.5)/8192-.5));return sum/8192;};
+ auto smooth=[](double a,double b,double x){double t=(std::max)(0.0,(std::min)(1.0,(x-a)/(b-a)));return t*t*(3-2*t);};
+ double maximum=0;unsigned active=0,changed=0,filtered=0;
+ for(unsigned row=0;row<rows;++row){const auto&p=queries[row];double wave[4]={},mask=0,residence=0,total=0;
+ const double nl=std::hypot(p.normal[0],p.normal[1]);
+ for(unsigned mode=0;mode<ModeCount;++mode){const auto&m=Modes[mode];const double phase=double(p.position[0])*m.kx+double(p.position[1])*m.ky-double(p.position[2])*m.omega+m.phase;
+ const double derivative=m.amplitude*(std::cos(phase)+.26*std::cos(2*phase));wave[0]+=m.amplitude*(std::sin(phase)+.13*std::sin(2*phase));
+ wave[1]+=derivative*m.kx;wave[2]+=derivative*m.ky;wave[3]-=derivative*m.omega;
+ const double weight=nl>1e-8?m.amplitude*m.amplitude*smooth(0,.25,-(m.kx*p.normal[0]+m.ky*p.normal[1])/std::hypot(m.kx,m.ky)/nl):0;
+ const double width=std::abs(m.kx*p.footprint[0]+m.ky*p.footprint[1])+std::abs(m.kx*p.footprint[2]+m.ky*p.footprint[3]);
+ const double pulse=weight*average(phase,width);mask+=pulse;residence+=pulse*durationPhase/m.omega;total+=weight;
+ }
+ if(mask>0)residence/=mask;if(total>0)mask/=total;
+ const double depth=p.context[0],shore=p.context[1],slope=p.context[2],exposure=p.context[3],support=p.gates[0],wl=std::hypot(wave[1],wave[2]);
+ double rate=0;
+ if(depth>double(.15f)&&support>0&&wave[0]>0&&nl>1e-8&&wl>1e-8&&std::abs(wave[3])>1e-8){
+ const double approach=smooth(0,.25,(wave[3]>0?1:-1)*(wave[1]*p.normal[0]+wave[2]*p.normal[1])/wl/nl);
+ const double a=smooth(0,9,depth),beach=smooth(.4,.85,2*wave[0]/(std::max)(depth+.5,1.0))*(1-a*a);
+ const double rock=1-smooth(0,6,(std::max)(0.0,shore));rate=1.2*support*smooth(.15,.8,depth)*approach*(.15+.85*exposure)
+ *(beach+(rock-beach)*smooth(.35,1,slope))*smooth(0,.5,wave[0])*mask;
+ }
+ const double fresh=-std::expm1(-rate*residence),old=-std::expm1(-rate*.35);
+ const double blend=p.gates[3]*(1-support*p.gates[2])+(std::max)(fresh,double(p.normal[3]))*p.gates[1]*p.gates[2];
+ const double expected[12]={mask,residence,rate,fresh,blend,wave[0],wave[1],wave[2],kernel(p.position[3]),average(p.position[3],p.normal[2]),old,wave[3]};
+ for(unsigned c=0;c<12;++c){const double error=std::abs(actual[row*12+c]-expected[c]);maximum=(std::max)(maximum,error);
+ if(!(std::isfinite(actual[row*12+c])&&error<.0015))printf("shore front mismatch row=%u channel=%u actual=%.9g expected=%.9g\n",row,c,double(actual[row*12+c]),expected[c]);
+ CHECK(std::isfinite(actual[row*12+c])&&error<.0015);}
+ active+=rate>.02;changed+=fresh>old+.05;filtered+=std::abs(expected[8]-expected[9])>.02;
+ }
+ CHECK(active>5&&changed>5&&filtered>5);
+ printf("sdl_gpu_frame_selfcheck: phase-locked shore front %u cases, independent integrated phase/rate/residence/blend max %.8g; %u active, %u old-cap controls, %u footprint controls, exact pause\n",rows,maximum,active,changed,filtered);
+}
+#endif // __linux__
+
+#if defined(__linux__)
+static void check_gpu_water_shore_source(SdlGpuFrame *frame)
+{
+ // Production source, independently checked against double scalar height and analytic
+ // source expectations. No texture/readback is added to the game path by this fixture.
+ using namespace WaterShoreFoam;
+ struct Query {float position[4],wave[4],context[4],shape[4];};std::vector<Query> queries;
+ for(unsigned i=0;i<16;++i)queries.push_back({{float(i*13)-64,float((i*7)%11)-5,float(i)*.43f,0},
+ {0,0,0,0},{2,1,1,0},{.1f,1,1,0}});
+ const Query incoming={{0,0,0,0},{2,.3f,0,1},{2,1,1,0},{.1f,1,1,1}};
+ queries.push_back(incoming);Query q=incoming;q.wave[3]=-1;queries.push_back(q);
+ q=incoming;q.wave[0]=-1;queries.push_back(q);q=incoming;q.wave[1]=0;queries.push_back(q);
+ q=incoming;q.context[0]=.15f;queries.push_back(q);q=incoming;q.context[0]=20;queries.push_back(q);
+ q=incoming;q.shape[1]=0;queries.push_back(q);q=incoming;q.shape[2]=0;queries.push_back(q);
+ q=incoming;q.shape[0]=1;q.context[1]=5;queries.push_back(q);q.context[1]=7;queries.push_back(q);
+ q=incoming;q.context[2]=-1;queries.push_back(q);q=incoming;q.context[2]=0;q.context[3]=1;queries.push_back(q);
+ q=incoming;q.shape[2]=.5f;queries.push_back(q);q=incoming;q.wave[3]=0;queries.push_back(q);
+ q=incoming;q.context[0]=NAN;queries.push_back(q);q=incoming;q.wave[0]=INFINITY;queries.push_back(q);
+ const unsigned rows=unsigned(queries.size()),columns=2;CHECK(sizeof(Query)*rows<=4096);
+ PixelPipelineDescription description={};std::string production;
+ CHECK(EngineShader_Pixel_Program(ENGINE_SHADER_WATER_TRAPEZOID,description,production,COMBINER_SHADER_TARGET_SDL3_GPU));
+ CHECK(production.find("foam=waterShoreBlendFrontHistory(")!=std::string::npos);
+ CHECK(production.find("opticalContext.r==0.0")!=std::string::npos);
+ const char *vs="float4 main(uint id:SV_VertexID):SV_Position{return float4(id==1?3.0:-1.0,id==2?3.0:-1.0,0,1);}";
+ const std::string ps="struct Query{float4 position,wave,context,shape;};cbuffer QueriesBlock:register(b0,space3){Query Queries["+std::to_string(rows)+"];};\n"+
+ Source()+"float4 main(float4 pixel:SV_Position):SV_Target0{Query q=Queries[(uint)pixel.y];"
+ "float4 w=waterShoreWave(q.position.xy,q.position.z);if(pixel.x<1)return w;"
+ "if(q.shape.w>.5)w=q.wave;float r=waterShoreRate(w,q.context.x,q.context.y,q.context.zw,q.shape.x,q.shape.y,q.shape.z);"
+ "return float4(r,waterShoreFresh(r),waterShoreBlend(.2,r,q.shape.z,1,1),waterShoreBlend(.2,r,0,1,0));}";
+ struct Resources {
+ SDL_GPUDevice *device;SDL_GPUShader *vs=nullptr,*ps=nullptr;SDL_GPUGraphicsPipeline *pipeline=nullptr;SDL_GPUTexture *target=nullptr;
+ ~Resources(){if(target)SDL_ReleaseGPUTexture(device,target);if(pipeline)SDL_ReleaseGPUGraphicsPipeline(device,pipeline);
+ if(vs)SDL_ReleaseGPUShader(device,vs);if(ps)SDL_ReleaseGPUShader(device,ps);}
+ } resources;resources.device=frame->Device();std::vector<unsigned char> spirv;std::string error;
+ bool ok=SDL3_Compile_HLSL_To_SPIRV(vs,true,spirv,error);CHECK(ok);if(!ok)return;
+ resources.vs=SDL3_Create_Shader(resources.device,spirv,true,error);CHECK(resources.vs);if(!resources.vs)return;
+ ok=SDL3_Compile_HLSL_To_SPIRV(ps,false,spirv,error);CHECK(ok);if(!ok){printf("shore source PS: %s\n",error.c_str());return;}
+ unsigned samplers=0,buffers=0;SDL3_Shader_Slots(spirv,false,samplers,buffers);CHECK(samplers==0 && buffers==1);
+ resources.ps=SDL3_Create_Shader(resources.device,spirv,false,error);CHECK(resources.ps);if(!resources.ps)return;
+ SDL_GPUColorTargetDescription colour={};colour.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
+ SDL_GPUGraphicsPipelineCreateInfo pi={};pi.vertex_shader=resources.vs;pi.fragment_shader=resources.ps;
+ pi.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;pi.target_info.color_target_descriptions=&colour;pi.target_info.num_color_targets=1;
+ resources.pipeline=SDL_CreateGPUGraphicsPipeline(resources.device,&pi);CHECK(resources.pipeline);if(!resources.pipeline)return;
+ SDL_GPUTextureCreateInfo ti={};ti.type=SDL_GPU_TEXTURETYPE_2D;ti.format=colour.format;ti.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;
+ ti.width=columns;ti.height=rows;ti.layer_count_or_depth=ti.num_levels=1;
+ resources.target=SDL_CreateGPUTexture(resources.device,&ti);CHECK(resources.target);if(!resources.target)return;CHECK(frame->Flush());
+ auto render=[&]() {
+ SDL_GPUCommandBuffer *commands=SDL_AcquireGPUCommandBuffer(resources.device);CHECK(commands);
+ SDL_GPUColorTargetInfo target={};target.texture=resources.target;target.load_op=SDL_GPU_LOADOP_DONT_CARE;target.store_op=SDL_GPU_STOREOP_STORE;
+ SDL_GPURenderPass *pass=SDL_BeginGPURenderPass(commands,&target,1,nullptr);CHECK(pass);
+ SDL_BindGPUGraphicsPipeline(pass,resources.pipeline);SDL_PushGPUFragmentUniformData(commands,0,queries.data(),unsigned(queries.size()*sizeof(Query)));
+ SDL_DrawGPUPrimitives(pass,3,1,0,0);SDL_EndGPURenderPass(pass);CHECK(SDL_SubmitGPUCommandBuffer(commands));
+ return read_float_targets(frame,&resources.target,1,columns,rows);
+ };
+ const auto values=render(),paused=render();CHECK(values==paused);CHECK(values.size()==rows*columns*4);if(values.size()!=rows*columns*4)return;
+ auto scalar=[](double x,double y,double t){double h=0;for(unsigned i=0;i<ModeCount;++i){const auto &m=Modes[i];const double p=x*m.kx+y*m.ky-t*m.omega+m.phase;h+=m.amplitude*(std::sin(p)+.13*std::sin(2*p));}return h;};
+ auto smooth=[](double a,double b,double x){double t=(std::max)(0.0,(std::min)(1.0,(x-a)/(b-a)));return t*t*(3-2*t);};
+ double maxWave=0,maxRate=0;unsigned active=0;
+ for(unsigned row=0;row<rows;++row) {
+ const Query &p=queries[row];const double x=p.position[0],y=p.position[1],t=p.position[2],eps=.0001;
+ double w[4]={scalar(x,y,t),(scalar(x+eps,y,t)-scalar(x-eps,y,t))/(2*eps),
+ (scalar(x,y+eps,t)-scalar(x,y-eps,t))/(2*eps),(scalar(x,y,t+eps)-scalar(x,y,t-eps))/(2*eps)};
+ for(unsigned c=0;c<4;++c){const double err=std::abs(values[(row*columns)*4+c]-w[c]);maxWave=(std::max)(maxWave,err);CHECK(err<.00008);}
+ if(p.shape[3]>.5f)for(unsigned c=0;c<4;++c)w[c]=p.wave[c];
+ const double depth=p.context[0],shore=p.context[1],nx=p.context[2],ny=p.context[3],slope=p.shape[0],exposure=p.shape[1],support=p.shape[2];
+ double expected=0;const double nl=std::hypot(nx,ny),wl=std::hypot(w[1],w[2]);
+ if(std::isfinite(depth)&&std::isfinite(w[0])&&depth>.15f&&support>0&&w[0]>0&&nl>1e-8&&wl>1e-8&&std::abs(w[3])>1e-8) {
+ const double incoming=smooth(0,.25,w[3]*(w[1]*nx+w[2]*ny)/nl/(std::max)(std::abs(w[3])*wl,1e-8));
+ const double a=smooth(0,9,depth),beach=smooth(.4,.85,2*w[0]/(std::max)(depth+.5,1.0))*(1-a*a);
+ const double rock=1-smooth(0,6,(std::max)(0.0,shore)),steep=smooth(.35,1,slope);
+ expected=1.2*support*smooth(.15,.8,depth)*incoming*(.15+.85*exposure)*(beach+(rock-beach)*steep)*smooth(0,.5,w[0]);
+ }
+ const double fresh=-std::expm1(-expected*.35),expectedValues[4]={expected,fresh,.2*(1-support)+fresh,.2};
+ for(unsigned c=0;c<4;++c){const float actual=values[(row*columns+1)*4+c];const double err=std::abs(actual-expectedValues[c]);maxRate=(std::max)(maxRate,err);CHECK(std::isfinite(actual)&&err<.00015);}
+ if(expected>.02)++active;
+ }
+ CHECK(active>=5);
+ CHECK(values[(16*columns+1)*4]>.5f && values[(17*columns+1)*4]==0 && values[(18*columns+1)*4]==0);
+ printf("sdl_gpu_frame_selfcheck: coastal source %u queries: wave/independent space-time %.8f, rate/blend %.8f; incoming/outgoing, trough, exposure, dry/deep, invalid, exact pause and fallback checked\n",rows,maxWave,maxRate);
+}
+#endif // __linux__
+
+
+static void check_gpu_authored_shore_overlay(SdlGpuFrame *frame)
+{
+ // Execute the production wrapper around the real two-stage fixed-function combiner.
+ // A separate unwrapped program is the exact fallback oracle for colour/shroud/fog/alpha.
+ CombinerDescription d={};d.StageCount=2;d.PixelPipeline.FogEnabled=true;
+ for(unsigned i=0;i<2;++i){auto &s=d.Stages[i];s.TextureBound=true;s.TextureCoordinateIndex=i;
+ s.ColourOperation=FF_TOP_MODULATE;s.ColourArgument1=FF_TA_TEXTURE;s.ColourArgument2=FF_TA_CURRENT;
+ s.AlphaOperation=i==0?FF_TOP_MODULATE:FF_TOP_SELECTARG2;s.AlphaArgument1=FF_TA_TEXTURE;s.AlphaArgument2=FF_TA_CURRENT;}
+ std::string ps[2];CHECK(CombinerShader_Generate(d,COMBINER_SHADER_TARGET_D3D11,ps[0]));ps[1]=ps[0];
+ CHECK(WaterShoreOverlay::WrapPixel(ps[1]));CHECK(SDL3_Shader_Retarget(ps[0],false));CHECK(SDL3_Shader_Retarget(ps[1],false));
+ const char *vs=R"OVERLAY(
+struct Output {
+ float4 Position:SV_Position;
+ [[vk::location(0)]] float4 Diffuse:COLOR0;
+ [[vk::location(1)]] float4 Specular:COLOR1;
+ [[vk::location(2)]] float2 TexCoord0:TEXCOORD0;
+ [[vk::location(3)]] float2 TexCoord1:TEXCOORD1;
+ [[vk::location(4)]] float2 TexCoord2:TEXCOORD2;
+ [[vk::location(5)]] float2 TexCoord3:TEXCOORD3;
+ [[vk::location(10)]] float Fog:FOG;
+};
+Output main(uint id:SV_VertexID) {
+ Output o;o.Position=float4(id==1?3:-1,id==2?3:-1,.5,1);
+ o.Diffuse=float4(.8,.6,.4,.75);o.Specular=0;
+ o.TexCoord0=o.TexCoord1=o.TexCoord2=o.TexCoord3=.5.xx;o.Fog=.4;return o;
+}
+)OVERLAY";
+ struct Resources {
+ SDL_GPUDevice *device;SDL_GPUShader *vs=nullptr,*ps[2]={};SDL_GPUGraphicsPipeline *pipelines[2]={};
+ SDL_GPUTexture *target=nullptr,*textures[7]={};SDL_GPUSampler *point=nullptr;
+ ~Resources(){for(auto *p:pipelines)if(p)SDL_ReleaseGPUGraphicsPipeline(device,p);
+ for(auto *p:ps)if(p)SDL_ReleaseGPUShader(device,p);if(vs)SDL_ReleaseGPUShader(device,vs);
+ for(auto *t:textures)if(t)SDL_ReleaseGPUTexture(device,t);if(target)SDL_ReleaseGPUTexture(device,target);
+ if(point)SDL_ReleaseGPUSampler(device,point);}
+ } r;r.device=frame->Device();std::vector<unsigned char> spirv;std::string error;bool ok;
+ ok=SDL3_Compile_HLSL_To_SPIRV(vs,true,spirv,error);CHECK(ok);if(!ok)return;
+ r.vs=SDL3_Create_Shader(r.device,spirv,true,error);CHECK(r.vs);if(!r.vs)return;
+ unsigned samplerCount[2]={};
+ for(unsigned i=0;i<2;++i){ok=SDL3_Compile_HLSL_To_SPIRV(ps[i],false,spirv,error);CHECK(ok);
+ if(!ok){printf("overlay PS: %s\n",error.c_str());return;}unsigned buffers=0;SDL3_Shader_Slots(spirv,false,samplerCount[i],buffers);
+ CHECK(buffers==1 && samplerCount[i]<=7);r.ps[i]=SDL3_Create_Shader(r.device,spirv,false,error);CHECK(r.ps[i]);if(!r.ps[i])return;}
+ SDL_GPUColorTargetDescription colour={};colour.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
+ SDL_GPUGraphicsPipelineCreateInfo pi={};pi.vertex_shader=r.vs;pi.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;
+ pi.target_info.color_target_descriptions=&colour;pi.target_info.num_color_targets=1;
+ for(unsigned i=0;i<2;++i){pi.fragment_shader=r.ps[i];r.pipelines[i]=SDL_CreateGPUGraphicsPipeline(r.device,&pi);CHECK(r.pipelines[i]);if(!r.pipelines[i])return;}
+ const unsigned W=8,H=4,S=8;SDL_GPUTextureCreateInfo ti={};ti.type=SDL_GPU_TEXTURETYPE_2D;ti.format=colour.format;
+ ti.width=W;ti.height=H;ti.layer_count_or_depth=ti.num_levels=1;ti.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;
+ r.target=SDL_CreateGPUTexture(r.device,&ti);CHECK(r.target);if(!r.target)return;
+ ti.height=S;ti.usage=SDL_GPU_TEXTUREUSAGE_SAMPLER;
+ for(auto &t:r.textures){t=SDL_CreateGPUTexture(r.device,&ti);CHECK(t);if(!t)return;}
+ SDL_GPUSamplerCreateInfo si={};si.min_filter=si.mag_filter=SDL_GPU_FILTER_NEAREST;si.mipmap_mode=SDL_GPU_SAMPLERMIPMAPMODE_NEAREST;
+ si.address_mode_u=si.address_mode_v=si.address_mode_w=SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
+ r.point=SDL_CreateGPUSampler(r.device,&si);CHECK(r.point);if(!r.point)return;
+ float data[7][S*S][4]={};for(unsigned y=0;y<S;++y)for(unsigned x=0;x<S;++x){
+ const unsigned k=y*S+x;float raw=.25f;if(x==3)raw=.75f;if(x==4)raw=1;if(x==5)raw=-.01f;
+ if(y==2 && x==4)raw=NAN;if(y==2 && x==5)raw=.999999f;
+ const float wave[4]={.7f,.8f,.9f,.6f},shroud[4]={.4f,.5f,.6f,1};
+ memcpy(data[0][k],wave,16);memcpy(data[1][k],shroud,16);
+ data[2][k][0]=4*raw+8; // real terrain at the sampled scene hit, both wet and dry
+ if(y==2 && x==2)data[2][k][0]-=2; // submerged/foreground object differs from terrain
+ // Broad authored surf traverses both the narrow breaking support and the
+ // analytic/FFT transition. Neither changes proven modern-patch ownership.
+ data[4][k][0]=float(x%3)*.5f;data[4][k][3]=float(y%3)*.5f;data[6][k][0]=raw;
+ }
+ CHECK(frame->Flush());SDL_GPUTransferBufferCreateInfo bi={};bi.usage=SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD;bi.size=sizeof(data);
+ SDL_GPUTransferBuffer *transfer=SDL_CreateGPUTransferBuffer(r.device,&bi);CHECK(transfer);if(!transfer)return;
+ void *mapped=SDL_MapGPUTransferBuffer(r.device,transfer,false);CHECK(mapped);if(!mapped){SDL_ReleaseGPUTransferBuffer(r.device,transfer);return;}
+ memcpy(mapped,data,sizeof(data));SDL_UnmapGPUTransferBuffer(r.device,transfer);
+ SDL_GPUCommandBuffer *upload=SDL_AcquireGPUCommandBuffer(r.device);CHECK(upload);if(!upload){SDL_ReleaseGPUTransferBuffer(r.device,transfer);return;}
+ SDL_GPUCopyPass *copy=SDL_BeginGPUCopyPass(upload);CHECK(copy);if(!copy){SDL_CancelGPUCommandBuffer(upload);SDL_ReleaseGPUTransferBuffer(r.device,transfer);return;}
+ for(unsigned i=0;i<7;++i){SDL_GPUTextureTransferInfo from={};from.transfer_buffer=transfer;from.offset=i*sizeof(data[0]);from.pixels_per_row=S;from.rows_per_layer=S;
+ SDL_GPUTextureRegion to={};to.texture=r.textures[i];to.w=to.h=S;to.d=1;SDL_UploadToGPUTexture(copy,&from,&to,false);}
+ SDL_EndGPUCopyPass(copy);CHECK(SDL_SubmitGPUCommandBuffer(upload));SDL_ReleaseGPUTransferBuffer(r.device,transfer);
+ SdlShorePixelConstants u={};u.Combiner.FogColour[0]=.1f;u.Combiner.FogColour[1]=.2f;u.Combiner.FogColour[2]=.3f;
+ u.WorldFromClip[0]=2;u.WorldFromClip[5]=-1;u.WorldFromClip[10]=4;u.WorldFromClip[12]=4.5f;u.WorldFromClip[13]=2.5f;u.WorldFromClip[14]=8;u.WorldFromClip[15]=1;
+ u.Viewport[0]=2.5f;u.Viewport[1]=1.5f;u.Viewport[2]=4;u.Viewport[3]=2;
+ u.Terrain[0]=-5;u.Terrain[1]=S;u.Terrain[2]=u.Terrain[3]=1;
+ u.Scene[1]=1.f/W;u.Scene[2]=1.f/S;u.Scene[3]=1;u.Surface[0]=10;u.Surface[1]=11.5f;u.Surface[2]=1;
+ auto render=[&](unsigned which){SDL_GPUCommandBuffer *cmd=SDL_AcquireGPUCommandBuffer(r.device);CHECK(cmd);if(!cmd)return std::vector<float>();
+ SDL_GPUColorTargetInfo out={};out.texture=r.target;out.load_op=SDL_GPU_LOADOP_DONT_CARE;out.store_op=SDL_GPU_STOREOP_STORE;
+ SDL_GPURenderPass *pass=SDL_BeginGPURenderPass(cmd,&out,1,nullptr);CHECK(pass);if(!pass){SDL_CancelGPUCommandBuffer(cmd);return std::vector<float>();}
+ SDL_BindGPUGraphicsPipeline(pass,r.pipelines[which]);SDL_GPUTextureSamplerBinding bindings[7];for(unsigned i=0;i<7;++i)bindings[i]={r.textures[i],r.point};
+ SDL_BindGPUFragmentSamplers(pass,0,bindings,samplerCount[which]);SDL_PushGPUFragmentUniformData(cmd,0,&u,which?sizeof(u):sizeof(u.Combiner));
+ SDL_DrawGPUPrimitives(pass,3,1,0,0);SDL_EndGPURenderPass(pass);CHECK(SDL_SubmitGPUCommandBuffer(cmd));return read_float_targets(frame,&r.target,1,W,H);};
+ const auto legacy=render(0);CHECK(legacy.size()==W*H*4);if(legacy.size()!=W*H*4)return;
+ unsigned wet=0,dry=0,preserved=0;double maximum=0;
+ for(unsigned mode=0;mode<4;++mode){u.Scene[3]=mode==1?0:1;u.Terrain[3]=mode==2?0:1;u.Surface[2]=mode==3?0:1;
+ const auto actual=render(1),paused=render(1);CHECK(actual==paused && actual.size()==legacy.size());if(actual.size()!=legacy.size())return;
+ for(unsigned y=0;y<H;++y)for(unsigned x=0;x<W;++x){const unsigned sx=std::max(2u,std::min(5u,x)),sy=std::max(1u,std::min(2u,y)),k=sy*S+sx,p=(y*W+x)*4;
+ // The depth resource and shader threshold are float32. Promote the actual
+ // float threshold too, so equality cannot accidentally become a real hit.
+ const double raw=data[6][k][0];const bool hit=std::isfinite(raw)&&raw>=0&&raw<double(.999999f);
+ const bool ground=std::isfinite(data[2][k][0])&&std::abs((4*raw+8)-data[2][k][0])<.5;
+ const bool removed=mode==0 && hit && ground;
+ for(unsigned c=0;c<4;++c){const double expected=c==3&&removed?0:legacy[p+c];const double err=std::abs(actual[p+c]-expected);maximum=std::max(maximum,err);
+ if(!(std::isfinite(actual[p+c])&&err<.000001))printf("shore-overlay mismatch mode=%u pixel=(%u,%u) channel=%u source=(%u,%u) raw=%.9g ground=%.9g expected=%.9g actual=%.9g\n",mode,x,y,c,sx,sy,raw,double(data[2][k][0]),expected,double(actual[p+c]));
+ CHECK(std::isfinite(actual[p+c])&&err<.000001);}
+ if(mode==0){if(removed){if(raw<.5)++wet;else ++dry;}else ++preserved;}
+ }
+ }
+ CHECK(wet>0 && dry>0 && preserved>0);
+ printf("sdl_gpu_frame_selfcheck: authored surf production wrapper: dry/wet replacement %u/%u, %u object/invalid fallbacks, max %.8f; original RGB/fog/shroud, unavailable resources and pause preserved\n",dry,wet,preserved,maximum);
+}
+
+#if defined(__linux__)
+static void check_gpu_water_shore_history(SdlGpuFrame *frame)
+{
+ // Real production alpha sampler and non-double-counting composition, with independently
+ // uploaded RGBA channels. RGB-only, wrong-level, window, time and replacement cases.
+ PixelPipelineDescription description={};std::string production;
+ CHECK(EngineShader_Pixel_Program(ENGINE_SHADER_WATER_TRAPEZOID,description,production,COMBINER_SHADER_TARGET_SDL3_GPU));
+ CHECK(production.find("foam=waterShoreBlendFrontHistory(")!=std::string::npos);
+ CHECK(production.find(WaterShoreFoam::HistorySource())!=std::string::npos);
+ const char *vs="float4 main(uint id:SV_VertexID):SV_Position{return float4(id==1?3.0:-1.0,id==2?3.0:-1.0,0,1);}";
+ const std::string ps=R"SHORE(
+cbuffer ShoreCase:register(b0,space3) {float4 FoamHistoryArea,FoamHistoryParameters,Query;};
+Texture2D<float4> Texture14:register(t0,space2);SamplerState Sampler14:register(s0,space2);
+)SHORE"+std::string(WaterFoamShading::HistorySamplingSource())+WaterShoreFoam::Source()+WaterShoreFoam::HistorySource()+R"SHORE(
+float4 main(float4 pixel:SV_Position):SV_Target0 {
+ float2 p=pixel.xy*8.0+Query.ww;
+ float retained=waterShoreHistory(p,Query.x,Query.y);
+ float mixed=waterShoreBlendHistory(.2,Query.z,retained,1,1,1);
+ float3 rgb=Texture14.SampleLevel(Sampler14,(p-FoamHistoryArea.xy)*FoamHistoryArea.zw,0).rgb;
+ return float4(retained,mixed,rgb.r,rgb.g+rgb.b);
+}
+)SHORE";
+ struct Resources {
+ SDL_GPUDevice *device;SDL_GPUShader *vs=nullptr,*ps=nullptr;SDL_GPUGraphicsPipeline *pipeline=nullptr;
+ SDL_GPUTexture *target=nullptr,*atlas=nullptr;SDL_GPUSampler *linear=nullptr;
+ ~Resources(){if(target)SDL_ReleaseGPUTexture(device,target);if(atlas)SDL_ReleaseGPUTexture(device,atlas);
+ if(linear)SDL_ReleaseGPUSampler(device,linear);if(pipeline)SDL_ReleaseGPUGraphicsPipeline(device,pipeline);
+ if(vs)SDL_ReleaseGPUShader(device,vs);if(ps)SDL_ReleaseGPUShader(device,ps);}
+ } resources;resources.device=frame->Device();std::string error;std::vector<unsigned char> spirv;
+ bool ok=SDL3_Compile_HLSL_To_SPIRV(vs,true,spirv,error);CHECK(ok);if(!ok)return;
+ resources.vs=SDL3_Create_Shader(resources.device,spirv,true,error);CHECK(resources.vs);if(!resources.vs)return;
+ ok=SDL3_Compile_HLSL_To_SPIRV(ps,false,spirv,error);CHECK(ok);if(!ok){printf("shore history PS: %s\n",error.c_str());return;}
+ unsigned samplers=0,buffers=0;SDL3_Shader_Slots(spirv,false,samplers,buffers);CHECK(samplers==1&&buffers==1);
+ resources.ps=SDL3_Create_Shader(resources.device,spirv,false,error);CHECK(resources.ps);if(!resources.ps)return;
+ SDL_GPUColorTargetDescription colour={};colour.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
+ SDL_GPUGraphicsPipelineCreateInfo pi={};pi.vertex_shader=resources.vs;pi.fragment_shader=resources.ps;
+ pi.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;pi.target_info.color_target_descriptions=&colour;pi.target_info.num_color_targets=1;
+ resources.pipeline=SDL_CreateGPUGraphicsPipeline(resources.device,&pi);CHECK(resources.pipeline);if(!resources.pipeline)return;
+ const unsigned side=8;SDL_GPUTextureCreateInfo ti={};ti.type=SDL_GPU_TEXTURETYPE_2D;ti.format=colour.format;
+ ti.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;ti.width=ti.height=side;ti.layer_count_or_depth=ti.num_levels=1;
+ resources.target=SDL_CreateGPUTexture(resources.device,&ti);CHECK(resources.target);if(!resources.target)return;
+ ti.usage=SDL_GPU_TEXTUREUSAGE_SAMPLER;resources.atlas=SDL_CreateGPUTexture(resources.device,&ti);CHECK(resources.atlas);if(!resources.atlas)return;
+ SDL_GPUSamplerCreateInfo si={};si.min_filter=si.mag_filter=SDL_GPU_FILTER_LINEAR;si.mipmap_mode=SDL_GPU_SAMPLERMIPMAPMODE_NEAREST;
+ si.address_mode_u=si.address_mode_v=si.address_mode_w=SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
+ resources.linear=SDL_CreateGPUSampler(resources.device,&si);CHECK(resources.linear);if(!resources.linear)return;
+ std::vector<float> pixels(side*side*4);
+ for(unsigned y=0;y<side;++y)for(unsigned x=0;x<side;++x) {
+ const size_t i=(y*side+x)*4;pixels[i]=.83f;pixels[i+1]=.17f;pixels[i+2]=.31f;
+ pixels[i+3]=.1f+.02f*x+.03f*y;
+ }
+ auto upload=[&]() {
+ SDL_GPUTransferBufferCreateInfo bi={};bi.usage=SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD;bi.size=unsigned(pixels.size()*sizeof(float));
+ SDL_GPUTransferBuffer *transfer=SDL_CreateGPUTransferBuffer(resources.device,&bi);CHECK(transfer);if(!transfer)return false;
+ void *mapped=SDL_MapGPUTransferBuffer(resources.device,transfer,false);CHECK(mapped);
+ if(!mapped){SDL_ReleaseGPUTransferBuffer(resources.device,transfer);return false;}
+ memcpy(mapped,pixels.data(),bi.size);SDL_UnmapGPUTransferBuffer(resources.device,transfer);
+ SDL_GPUCommandBuffer *commands=SDL_AcquireGPUCommandBuffer(resources.device);CHECK(commands);
+ if(!commands){SDL_ReleaseGPUTransferBuffer(resources.device,transfer);return false;}
+ SDL_GPUCopyPass *copy=SDL_BeginGPUCopyPass(commands);CHECK(copy);
+ if(!copy){SDL_CancelGPUCommandBuffer(commands);SDL_ReleaseGPUTransferBuffer(resources.device,transfer);return false;}
+ SDL_GPUTextureTransferInfo from={};from.transfer_buffer=transfer;from.pixels_per_row=from.rows_per_layer=side;
+ SDL_GPUTextureRegion to={};to.texture=resources.atlas;to.w=to.h=side;to.d=1;
+ SDL_UploadToGPUTexture(copy,&from,&to,true);SDL_EndGPUCopyPass(copy);
+ const bool result=SDL_SubmitGPUCommandBuffer(commands);CHECK(result);SDL_ReleaseGPUTransferBuffer(resources.device,transfer);return result;
+ };
+ CHECK(frame->Flush());if(!upload())return;
+ auto render=[&](float flags,float level,float time,float offset,float rate) {
+ const float uniforms[12]={0,0,1.0f/64,1.0f/64,flags,4,8,1,level,time,rate,offset};
+ SDL_GPUCommandBuffer *commands=SDL_AcquireGPUCommandBuffer(resources.device);CHECK(commands);if(!commands)return std::vector<float>{};
+ SDL_GPUColorTargetInfo target={};target.texture=resources.target;target.load_op=SDL_GPU_LOADOP_DONT_CARE;target.store_op=SDL_GPU_STOREOP_STORE;
+ SDL_GPURenderPass *pass=SDL_BeginGPURenderPass(commands,&target,1,nullptr);CHECK(pass);
+ if(!pass){SDL_CancelGPUCommandBuffer(commands);return std::vector<float>{};}
+ SDL_BindGPUGraphicsPipeline(pass,resources.pipeline);
+ const SDL_GPUTextureSamplerBinding binding={resources.atlas,resources.linear};SDL_BindGPUFragmentSamplers(pass,0,&binding,1);
+ SDL_PushGPUFragmentUniformData(commands,0,uniforms,sizeof(uniforms));SDL_DrawGPUPrimitives(pass,3,1,0,0);
+ SDL_EndGPURenderPass(pass);CHECK(SDL_SubmitGPUCommandBuffer(commands));
+ return read_float_targets(frame,&resources.target,1,side,side);
+ };
+ const float cases[][5]={{2,4,1,0,0},{1,4,1,0,0},{3,4,1,0,0},{2,9,1,0,0},
+ {2,4,1.1f,0,0},{2,4,1,2,0},{2,4,1,-80,0},{2,4,1,0,1.2f}};
+ std::vector<float> baseline;unsigned armed=0;
+ auto smooth=[](double x){x=(std::max)(0.0,(std::min)(1.0,x));return x*x*(3-2*x);};
+ for(unsigned run=0;run<sizeof(cases)/sizeof(cases[0]);++run) {
+ const auto&c=cases[run];const auto values=render(c[0],c[1],c[2],c[3],c[4]);
+ CHECK(values.size()==side*side*4);if(values.size()!=side*side*4)return;
+ if(run==0){baseline=values;CHECK(values==render(c[0],c[1],c[2],c[3],c[4]));}
+ for(unsigned y=0;y<side;++y)for(unsigned x=0;x<side;++x) {
+ const double px=(x+.5)*8+c[3],py=(y+.5)*8+c[3];
+ const double sx=(std::max)(0.0,(std::min)(7.0,px/8-.5)),sy=(std::max)(0.0,(std::min)(7.0,py/8-.5));
+ double expected=.1+.02*sx+.03*sy;
+ expected=1-std::pow(1-expected,std::exp(-(std::max)(0.0,double(c[2])-1)/5));
+ expected*=smooth((std::min)((std::min)(px,py),(std::min)(64-px,64-py))/24);
+ if(c[0]<1.5||std::abs(c[1]-4)>.1||px<0||py<0||px>64||py>64)expected=0;
+ const double fresh=1-std::exp(-double(c[4])*.35),mixed=(std::max)(fresh,expected);const size_t n=(y*side+x)*4;
+ CHECK(std::isfinite(values[n])&&std::abs(values[n]-expected)<.00003);
+ CHECK(std::abs(values[n+1]-mixed)<.00003);
+ CHECK(std::abs(values[n+2]-.83)<.00001&&std::abs(values[n+3]-.48)<.00001);
+ if(run==0&&x>=2&&x<=5&&y>=2&&y<=5){CHECK(std::abs(values[n]-.83)>.3);++armed;}
+ }
+ }
+ // Replace A in the same bound resource: the second submission must see the new alpha,
+ // while the earlier readback and all three vessel channels remain unchanged.
+ for(size_t i=3;i<pixels.size();i+=4)pixels[i]=0;
+ if(!upload())return;const auto cleared=render(2,4,1,0,0);CHECK(cleared.size()==baseline.size());
+ if(cleared.size()==baseline.size())for(size_t i=0;i<cleared.size();i+=4) {
+ CHECK(cleared[i]==0&&cleared[i+1]==0);CHECK(cleared[i+2]==baseline[i+2]&&cleared[i+3]==baseline[i+3]);
+ }
+ CHECK(armed==16);
+ printf("sdl_gpu_frame_selfcheck: coast alpha 8x8, 8 cases, linear sampling, age hold, pause, level/window flags, source trough, no double count, upload replacement and %u armed RGB-channel controls checked\n",armed);
+}
+#endif // __linux__
+
+#if defined(__linux__)
+static void check_gpu_water_shore_depth_gate(SdlGpuFrame *frame)
+{
+ // Execute the actual generated coastal branch with a point-sampled depth texture and
+ // its real raster coordinates. The independent oracle starts with uploaded depth bits,
+ // not bottomPosition(), which deliberately has a different terrain-fallback contract.
+ using namespace WaterShoreFoam;
+ PixelPipelineDescription description={};std::string production;
+ const char *old=getenv("ZH_WATER_SHORE_FOAM");const bool had=old!=nullptr;const std::string saved=old?old:"";
+ CHECK(setenv("ZH_WATER_SHORE_FOAM","1",1)==0);
+ const bool generated=EngineShader_Pixel_Program(ENGINE_SHADER_WATER_TRAPEZOID,description,production,COMBINER_SHADER_TARGET_SDL3_GPU);
+ if(had)CHECK(setenv("ZH_WATER_SHORE_FOAM",saved.c_str(),1)==0);else CHECK(unsetenv("ZH_WATER_SHORE_FOAM")==0);
+ CHECK(generated);if(!generated)return;
+ const size_t pixelAt=production.find("float2 waterScenePixel("),pixelEnd=production.find("// Depth is a point-sampled",pixelAt);
+ const size_t blockAt=production.find(" float shoreRate=0.0,shoreSupport=0.0;"),blockEnd=production.find(" // At a known hull",blockAt);
+ const size_t cageAt=production.find(" // Contact wash follows",blockAt),shoreAt=production.find(" if(shoreFoamEnabled &&",cageAt);
+ CHECK(pixelAt!=std::string::npos && pixelEnd!=std::string::npos && blockAt<cageAt && cageAt<shoreAt && shoreAt<blockEnd && blockEnd!=std::string::npos);
+ if(pixelAt==std::string::npos || pixelEnd==std::string::npos || !(blockAt<cageAt && cageAt<shoreAt && shoreAt<blockEnd) || blockEnd==std::string::npos)return;
+ // Keep the original source/history initialization and actual analytic depth-gated
+ // branch. Cage wash and optional GPU surf have their own resources and fixtures.
+ const std::string block=production.substr(blockAt,cageAt-blockAt)+production.substr(shoreAt,blockEnd-shoreAt);
+ CHECK(block.find("waterShoreSceneDepth(SceneParameters.w,shoreRawDepth)")!=std::string::npos);
+ CHECK(block.find("floor(input.Position.xy)+0.5")!=std::string::npos);
+ const std::string ps=R"SHORE(
+cbuffer ShoreCase:register(b0,space3) {
+ float4 Viewport,SceneParameters,WaterParameters,OpticalParameters,TerrainParameters;
+ float4 CaseParameters,CaseGradient,CaseContext;
+};
+Texture2D<float> Texture6:register(t0,space2);SamplerState Sampler6:register(s0,space2);
+struct Input {float4 Position;};
+static const bool shoreFoamEnabled=true;
+float terrainHeight(float2 p) {return 0.0;}
+float waterShoreHistory(float2 p,float level,float time) {return CaseGradient.z;}
+)SHORE"+Source()+production.substr(pixelAt,pixelEnd-pixelAt)+R"SHORE(
+float4 main(float4 pixel:SV_Position):SV_Target0 {
+ Input input;input.Position=pixel;
+ float foam=.2,baseLevel=2.0,surfaceTerrainHeight=0.0;
+ float2 terrainGradient=CaseGradient.xy,wavePosition=float2(0,0),parameterDx=0,parameterDy=0;
+ float4 opticalContext=CaseContext;
+ float time=CaseParameters.x,depth=CaseParameters.y,fftWeight=CaseParameters.w;
+ float3 shoreSceneBottom=float3(0,0,CaseParameters.z);
+)SHORE"+block+R"SHORE(
+ float2 sampled=waterScenePixel(floor(input.Position.xy)+.5);
+ return float4(shoreRate,shoreSupport,foam,sampled.x+8*sampled.y);
+}
+)SHORE";
+ const char *vs="float4 main(uint id:SV_VertexID):SV_Position{return float4(id==1?3.0:-1.0,id==2?3.0:-1.0,0,1);}";
+ struct Resources {
+ SDL_GPUDevice *device;SDL_GPUShader *vs=nullptr,*ps=nullptr;SDL_GPUGraphicsPipeline *pipeline=nullptr;
+ SDL_GPUTexture *target=nullptr,*depth=nullptr;SDL_GPUSampler *point=nullptr;
+ ~Resources(){if(target)SDL_ReleaseGPUTexture(device,target);if(depth)SDL_ReleaseGPUTexture(device,depth);
+ if(point)SDL_ReleaseGPUSampler(device,point);if(pipeline)SDL_ReleaseGPUGraphicsPipeline(device,pipeline);
+ if(vs)SDL_ReleaseGPUShader(device,vs);if(ps)SDL_ReleaseGPUShader(device,ps);}
+ } resources;resources.device=frame->Device();std::string error;std::vector<unsigned char> spirv;
+ bool ok=SDL3_Compile_HLSL_To_SPIRV(vs,true,spirv,error);CHECK(ok);if(!ok)return;
+ resources.vs=SDL3_Create_Shader(resources.device,spirv,true,error);CHECK(resources.vs);if(!resources.vs)return;
+ ok=SDL3_Compile_HLSL_To_SPIRV(ps,false,spirv,error);CHECK(ok);if(!ok){printf("shore depth PS: %s\n",error.c_str());return;}
+ unsigned samplers=0,buffers=0;SDL3_Shader_Slots(spirv,false,samplers,buffers);CHECK(samplers==1 && buffers==1);
+ resources.ps=SDL3_Create_Shader(resources.device,spirv,false,error);CHECK(resources.ps);if(!resources.ps)return;
+ SDL_GPUColorTargetDescription colour={};colour.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
+ SDL_GPUGraphicsPipelineCreateInfo pi={};pi.vertex_shader=resources.vs;pi.fragment_shader=resources.ps;
+ pi.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;pi.target_info.color_target_descriptions=&colour;pi.target_info.num_color_targets=1;
+ resources.pipeline=SDL_CreateGPUGraphicsPipeline(resources.device,&pi);CHECK(resources.pipeline);if(!resources.pipeline)return;
+ const unsigned width=8,height=4;SDL_GPUTextureCreateInfo ti={};ti.type=SDL_GPU_TEXTURETYPE_2D;ti.format=colour.format;
+ ti.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;ti.width=width;ti.height=height;ti.layer_count_or_depth=ti.num_levels=1;
+ resources.target=SDL_CreateGPUTexture(resources.device,&ti);CHECK(resources.target);if(!resources.target)return;
+ ti.format=SDL_GPU_TEXTUREFORMAT_R32_FLOAT;ti.usage=SDL_GPU_TEXTUREUSAGE_SAMPLER;
+ resources.depth=SDL_CreateGPUTexture(resources.device,&ti);CHECK(resources.depth);if(!resources.depth)return;
+ SDL_GPUSamplerCreateInfo si={};si.min_filter=si.mag_filter=SDL_GPU_FILTER_NEAREST;si.mipmap_mode=SDL_GPU_SAMPLERMIPMAPMODE_NEAREST;
+ si.address_mode_u=si.address_mode_v=si.address_mode_w=SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
+ resources.point=SDL_CreateGPUSampler(resources.device,&si);CHECK(resources.point);if(!resources.point)return;
+ float texels[width*height];std::fill(texels,texels+width*height,1.0f);
+ texels[1*width+2]=.4f;texels[1*width+3]=1;texels[1*width+4]=-.001f;texels[1*width+5]=std::nextafter(.999999f,0.0f);
+ texels[2*width+2]=0;texels[2*width+3]=.999999f;texels[2*width+4]=NAN;texels[2*width+5]=INFINITY;
+ CHECK(frame->Flush());SDL_GPUTransferBufferCreateInfo bi={};bi.usage=SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD;bi.size=sizeof(texels);
+ SDL_GPUTransferBuffer *transfer=SDL_CreateGPUTransferBuffer(resources.device,&bi);CHECK(transfer);if(!transfer)return;
+ void *mapped=SDL_MapGPUTransferBuffer(resources.device,transfer,false);CHECK(mapped);
+ if(!mapped){SDL_ReleaseGPUTransferBuffer(resources.device,transfer);return;}memcpy(mapped,texels,sizeof(texels));SDL_UnmapGPUTransferBuffer(resources.device,transfer);
+ SDL_GPUCommandBuffer *upload=SDL_AcquireGPUCommandBuffer(resources.device);CHECK(upload);
+ if(!upload){SDL_ReleaseGPUTransferBuffer(resources.device,transfer);return;}
+ SDL_GPUCopyPass *copy=SDL_BeginGPUCopyPass(upload);CHECK(copy);
+ if(!copy){SDL_CancelGPUCommandBuffer(upload);SDL_ReleaseGPUTransferBuffer(resources.device,transfer);return;}
+ SDL_GPUTextureTransferInfo from={};from.transfer_buffer=transfer;from.pixels_per_row=width;from.rows_per_layer=height;
+ SDL_GPUTextureRegion to={};to.texture=resources.depth;to.w=width;to.h=height;to.d=1;
+ SDL_UploadToGPUTexture(copy,&from,&to,false);SDL_EndGPUCopyPass(copy);CHECK(SDL_SubmitGPUCommandBuffer(upload));SDL_ReleaseGPUTransferBuffer(resources.device,transfer);
+ float activeTime=0,troughTime=0,best=0,gx=0,gy=0;bool foundTrough=false;
+ for(unsigned i=0;i<2048;++i) {
+ const float time=float(i)*.05f;const Wave w=Evaluate(0,0,time);const float length=std::hypot(w.dx,w.dy);
+ if(w.height<-.25f && !foundTrough){troughTime=time;foundTrough=true;}
+ if(length<=1e-6f || std::abs(w.dt)<=1e-6f)continue;
+ Context c;c.depth=2;c.shore=1;c.slope=.1f;c.exposure=c.support=1;
+ c.nx=(w.dt>0?1.f:-1.f)*w.dx/length;c.ny=(w.dt>0?1.f:-1.f)*w.dy/length;
+ const float rate=Rate(c,w)*EvaluateFront(0,0,time,c.nx,c.ny).mask;if(rate>best){best=rate;activeTime=time;gx=-.1f*c.nx;gy=-.1f*c.ny;}
+ }
+ CHECK(best>.1f && foundTrough);if(best<=.1f || !foundTrough)return;
+ struct Case {float available,time,wet=2,bottom=0,river=0,terrain=1,context=1,offshore=0,support=1,fft=0,history=0;};
+ std::vector<Case> cases;
+ for(float available:{0.f,.5f,std::nextafter(.5f,1.f),1.f,NAN,INFINITY}) {
+ cases.push_back({available,activeTime});cases.push_back({available,troughTime});
+ }
+ Case q={1,activeTime};q.wet=0;cases.push_back(q);q={1,activeTime};q.bottom=2;cases.push_back(q);
+ q={1,activeTime};q.river=1;cases.push_back(q);q={1,activeTime};q.terrain=0;cases.push_back(q);
+ q={1,activeTime};q.context=0;cases.push_back(q);q={1,activeTime};q.offshore=.01f;cases.push_back(q);
+ q={1,activeTime};q.support=0;cases.push_back(q);
+ q={1,activeTime};q.history=.8f;cases.push_back(q);q.fft=1;cases.push_back(q);
+ auto smooth=[](double a,double b,double x){const double t=std::max(0.0,std::min(1.0,(x-a)/(b-a)));return t*t*(3-2*t);};
+ unsigned accepted=0,invalidArmed=0,unavailableArmed=0,dry=0,object=0,spectralSuppressed=0,historyArmed=0;double maximumError=0;
+ for(const Case &c:cases) {
+ float uniforms[8][4]={{2.5f,1.5f,4,2},{0,1.f/width,1.f/height,c.available},{0,c.river,0,0},
+ {0,0,c.context,0},{0,0,0,c.terrain},{c.time,c.wet,c.bottom,c.fft},{gx,gy,c.history,0},{c.offshore,.01f,1,c.support}};
+ auto render=[&]() {
+ SDL_GPUCommandBuffer *commands=SDL_AcquireGPUCommandBuffer(resources.device);CHECK(commands);if(!commands)return std::vector<float>();
+ SDL_GPUColorTargetInfo target={};target.texture=resources.target;target.load_op=SDL_GPU_LOADOP_DONT_CARE;target.store_op=SDL_GPU_STOREOP_STORE;
+ SDL_GPURenderPass *pass=SDL_BeginGPURenderPass(commands,&target,1,nullptr);CHECK(pass);
+ if(!pass){SDL_CancelGPUCommandBuffer(commands);return std::vector<float>();}
+ SDL_BindGPUGraphicsPipeline(pass,resources.pipeline);SDL_GPUTextureSamplerBinding binding={resources.depth,resources.point};
+ SDL_BindGPUFragmentSamplers(pass,0,&binding,1);SDL_PushGPUFragmentUniformData(commands,0,uniforms,sizeof(uniforms));
+ SDL_DrawGPUPrimitives(pass,3,1,0,0);SDL_EndGPURenderPass(pass);CHECK(SDL_SubmitGPUCommandBuffer(commands));
+ return read_float_targets(frame,&resources.target,1,width,height);
+ };
+ const auto values=render(),paused=render();CHECK(values==paused && values.size()==width*height*4);
+ if(values.size()!=width*height*4)return;
+ Context context;context.depth=2;context.shore=1;context.nx=-gx;context.ny=-gy;
+ context.slope=std::hypot(gx,gy);context.exposure=1;context.support=c.support*(1-c.fft);
+ const Front front=EvaluateFront(0,0,c.time,context.nx,context.ny);
+ const float rate=Rate(context,Evaluate(0,0,c.time))*front.mask;
+ for(unsigned y=0;y<height;++y)for(unsigned x=0;x<width;++x) {
+ const unsigned sx=std::max(2u,std::min(5u,x)),sy=std::max(1u,std::min(2u,y));const float raw=texels[sy*width+sx];
+ const bool sourceContext=c.river<.5f && c.terrain>.5f && c.context>.5f && c.offshore==0 && c.support>0;
+ const bool real=std::isfinite(c.available)&&c.available>.5f&&std::isfinite(raw)&&raw>=0 && raw<.999999f;
+ const bool valid=sourceContext&&real;const double match=1-smooth(.5,1.5,std::abs(c.bottom));
+ const double fresh=-std::expm1(-double(rate)*front.residence),history=c.history*(1-c.fft);
+ const double foam=valid?.2f*(1-context.support*match)+std::max(fresh,history)*smooth(0,.8,c.wet)*match:.2f;
+ const double expected[4]={valid?rate:0,valid?context.support:0,foam,sx+.5+8*(sy+.5)};
+ for(unsigned channel=0;channel<4;++channel){const float actual=values[(y*width+x)*4+channel];const double error=std::abs(actual-expected[channel]);maximumError=std::max(maximumError,error);CHECK(std::isfinite(actual)&&error<.00015);}
+ if(valid){++accepted;if(c.wet==0){CHECK(values[(y*width+x)*4+2]==0);++dry;}if(c.bottom==2){CHECK(values[(y*width+x)*4+2]==.2f);++object;}}
+ if(valid&&c.fft==1){CHECK(values[(y*width+x)*4]==0&&values[(y*width+x)*4+1]==0&&values[(y*width+x)*4+2]==.2f);++spectralSuppressed;}
+ if(valid&&c.history>0&&c.fft==0){CHECK(values[(y*width+x)*4+2]>.7f);++historyArmed;}
+ if(!valid&&sourceContext) {
+ CHECK(values[(y*width+x)*4+2]==.2f);
+ // Armed old integration assumes fallback terrain is a hit; at a trough it
+ // erases the rim. Here the actual generated branch must retain it instead.
+ if(c.time==troughTime){if(c.available==1 && !real)++invalidArmed;if(c.available<=.5f)++unavailableArmed;}
+ }
+ }
+ }
+ CHECK(accepted>0 && invalidArmed>0 && unavailableArmed>0 && dry>0 && object>0 && spectralSuppressed>0 && historyArmed>0);
+ printf("sdl_gpu_frame_selfcheck: coastal original-depth raster %zu cases, generated branch max %.8f; real/clear/negative/nonfinite, unavailable, offset viewport, trough, dry/object, FFT suppression of analytic source/history and exact pause checked\n",cases.size(),maximumError);
+}
+#endif // __linux__
+
+// Core-only fixture: actual production FFT decode/limiter feeds the proposed source.
+// Native texture binding, graph transport and scene masks remain separate rollout gates.
+static void check_gpu_water_coastal_surf_core(SdlGpuFrame *frame)
+{
+ struct Query {float f[12][4];};
+ Query base={{{.015f,.065f,-.004f,.01f},{-.35f,.08f,.02f,.025f},
+ {.005f,.035f,.007f,.005f},{-.15f,.02f,.03f,.02f},
+ {10,20,30,40},{50,60,70,80},{2.4f,-.3f,.08f,1},
+ {4,64,-1,0},{1,.4f,.4f,.5f},{1,1,0,0},{.7f,1.3f,2,.4f},{.1f,1,.25f,0}}};
+ std::vector<Query> queries(20,base);
+ queries[1].f[8][1]=0;queries[2].f[8][1]=1;queries[2].f[10][2]=1.7f;
+ for(float &v:queries[3].f[4])v*=100000;for(float &v:queries[3].f[5])v*=100000;
+ queries[4].f[6][0]=-1;queries[4].f[0][1]=queries[4].f[2][1]=-.05f;
+ queries[5].f[7][2]=1;queries[6].f[10][2]=3;
+ queries[7].f[7][0]=.1f;queries[8].f[8][0]=0;queries[9].f[7][1]=128;
+ queries[10].f[7][0]=12;queries[11].f[9][0]=0;queries[12].f[9][1]=0;
+ queries[13].f[11][0]=0;queries[14].f[11][0]=1.3f;queries[15].f[10][3]=-1;
+ queries[16].f[1][0]=(std::numeric_limits<float>::max)();
+ queries[17].f[7][2]=(std::numeric_limits<float>::max)();queries[18].f[11][0]=1e-40f;
+ queries[19].f[6][1]=queries[19].f[6][2]=0;
+ queries[19].f[1][0]=queries[19].f[1][1]=queries[19].f[3][0]=queries[19].f[3][1]=0;
+ const std::string production=WaterFftSampling::PixelSource(false,false);
+ const size_t start=production.find("struct FftSurface {"),end=production.find("struct FftMapSamples");
+ const size_t decode=production.find("FftSurface fftDecodeSamples("),after=production.find("FftSurface fftRawSurface(");
+ CHECK(start!=std::string::npos&&end>start&&decode!=std::string::npos&&after>decode);
+ if(start==std::string::npos||end<=start||decode==std::string::npos||after<=decode)return;
+ std::string ps="struct Query{float4 f[12];};cbuffer Queries:register(b0,space3){Query Q[20];};\n"
+ +WaterFftSampling::CommonSource()+production.substr(start,end-start)
+ +"struct FftMapSamples {float4 a,ad,b,bd,c,cd;};\n"+production.substr(decode,after-decode)
+ +WaterCoastalSurf::IncidentSource()+WaterCoastalSurf::Source()+R"SURF(
+float4 main(float4 pixel:SV_Position):SV_Target0 {
+ Query q=Q[(uint)pixel.y];FftMapSamples samples;
+ samples.a=q.f[0];samples.ad=q.f[1];samples.b=q.f[2];samples.bd=q.f[3];samples.c=q.f[4];samples.cd=q.f[5];
+ float4 incident=waterSurfIncident(samples),field=waterSurfBlend(q.f[6],incident,q.f[8].y);
+ WaterSurfContext context;context.coast=q.f[7];context.surface=q.f[8];context.admission=q.f[9];
+ float4 updated=waterSurfAdvance(context,field,q.f[10],q.f[11].x,q.f[11].y>.5);
+ if(pixel.x<1)return incident;if(pixel.x<2)return field;
+ if(pixel.x<3)return float4(waterSurfRate(context,field,q.f[10],q.f[11].x),waterSurfDomain(context),waterSurfCoverage(updated,q.f[11].z),1);
+ if(pixel.x<4)return updated;
+ return waterSurfDiffuse(q.f[10],float4(0,0,0,0),float4(1,2,3,0),float4(4,8,0,0),float4(0,0,0,0),6,5,min(q.f[11].x,.25));
+})SURF";
+ const char *vs="float4 main(uint id:SV_VertexID):SV_Position{return float4(id==1?3.0:-1.0,id==2?3.0:-1.0,0,1);}";
+ struct Resources {
+ SDL_GPUDevice *device;SDL_GPUShader *vs=nullptr,*ps=nullptr;SDL_GPUGraphicsPipeline *pipeline=nullptr;SDL_GPUTexture *target=nullptr;
+ ~Resources(){if(target)SDL_ReleaseGPUTexture(device,target);if(pipeline)SDL_ReleaseGPUGraphicsPipeline(device,pipeline);
+ if(vs)SDL_ReleaseGPUShader(device,vs);if(ps)SDL_ReleaseGPUShader(device,ps);}
+ }r;r.device=frame->Device();std::vector<unsigned char>spirv;std::string error;
+ bool ok=SDL3_Compile_HLSL_To_SPIRV(vs,true,spirv,error);CHECK(ok);if(!ok)return;
+ r.vs=SDL3_Create_Shader(r.device,spirv,true,error);CHECK(r.vs);if(!r.vs)return;
+ ok=SDL3_Compile_HLSL_To_SPIRV(ps,false,spirv,error);CHECK(ok);if(!ok){printf("coastal surf core PS: %s\n",error.c_str());return;}
+ unsigned samplers=0,buffers=0;SDL3_Shader_Slots(spirv,false,samplers,buffers);CHECK(samplers==0&&buffers==1);
+ r.ps=SDL3_Create_Shader(r.device,spirv,false,error);CHECK(r.ps);if(!r.ps)return;
+ SDL_GPUColorTargetDescription colour={};colour.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
+ SDL_GPUGraphicsPipelineCreateInfo pi={};pi.vertex_shader=r.vs;pi.fragment_shader=r.ps;pi.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;
+ pi.target_info.color_target_descriptions=&colour;pi.target_info.num_color_targets=1;
+ r.pipeline=SDL_CreateGPUGraphicsPipeline(r.device,&pi);CHECK(r.pipeline);if(!r.pipeline)return;
+ const unsigned width=5,height=unsigned(queries.size());CHECK(sizeof(Query)*height<=4096);
+ SDL_GPUTextureCreateInfo ti={};ti.type=SDL_GPU_TEXTURETYPE_2D;ti.format=colour.format;ti.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;
+ ti.width=width;ti.height=height;ti.layer_count_or_depth=ti.num_levels=1;
+ r.target=SDL_CreateGPUTexture(r.device,&ti);CHECK(r.target);if(!r.target)return;CHECK(frame->Flush());
+ auto render=[&](){
+ SDL_GPUCommandBuffer *commands=SDL_AcquireGPUCommandBuffer(r.device);CHECK(commands);if(!commands)return std::vector<float>();
+ SDL_GPUColorTargetInfo target={};target.texture=r.target;target.load_op=SDL_GPU_LOADOP_DONT_CARE;target.store_op=SDL_GPU_STOREOP_STORE;
+ SDL_GPURenderPass *pass=SDL_BeginGPURenderPass(commands,&target,1,nullptr);CHECK(pass);if(!pass){SDL_CancelGPUCommandBuffer(commands);return std::vector<float>();}
+ SDL_BindGPUGraphicsPipeline(pass,r.pipeline);SDL_PushGPUFragmentUniformData(commands,0,queries.data(),unsigned(queries.size()*sizeof(Query)));
+ SDL_DrawGPUPrimitives(pass,3,1,0,0);SDL_EndGPURenderPass(pass);CHECK(SDL_SubmitGPUCommandBuffer(commands));
+ return read_float_targets(frame,&r.target,1,width,height);
+ };
+ const auto actual=render(),repeat=render();CHECK(actual==repeat&&actual.size()==width*height*4);if(actual.size()!=width*height*4)return;
+ auto clamp=[](double x,double a,double b){return (std::max)(a,(std::min)(b,x));};
+ auto smooth=[&](double a,double b,double x){const double t=clamp((x-a)/(b-a),0,1);return t*t*(3-2*t);};
+ const double vz=WaterFftGeometry::MaxVerticalDisplacement,xy=WaterFftGeometry::MaxHorizontalDisplacement/std::sqrt(2.0);
+ double maximum=0;unsigned active=0,suppressed=0;double armedFine=0;
+ for(unsigned row=0;row<height;++row){const Query&q=queries[row];
+ const double h=(double(q.f[0][1])+q.f[2][1])*20;
+ const double hx=double(q.f[1][0])+q.f[3][0],hy=double(q.f[1][1])+q.f[3][1];
+ const double d0=(-1.2*double(q.f[0][0])-1.5*double(q.f[2][0]))*20;
+ const double d1=(-1.2*double(q.f[0][2])-1.5*double(q.f[2][2]))*20;
+ const double lx=1-std::pow(std::tanh(d0/xy),2),ly=1-std::pow(std::tanh(d1/xy),2);
+ const double xx=(-1.2*double(q.f[1][2])-1.5*double(q.f[3][2]))*lx;
+ const double cross=-1.2*double(q.f[0][3])-1.5*double(q.f[2][3]);
+ const double yy=(-1.2*double(q.f[1][3])-1.5*double(q.f[3][3]))*ly;
+ const double incident[4]={vz*std::tanh(h/vz),hx*(1-std::pow(std::tanh(h/vz),2)),hy*(1-std::pow(std::tanh(h/vz),2)),(1+xx)*(1+yy)-cross*cross*lx*ly};
+ const double weight=q.f[8][1];double field[4];for(unsigned i=0;i<3;++i)field[i]=q.f[6][i]+(incident[i]-q.f[6][i])*weight;
+ field[3]=1+(incident[3]-1)*weight;
+ if(row==16){field[0]=field[1]=field[2]=0;field[3]=1;}
+ const double dt=q.f[11][0],depth=q.f[7][0],distance=q.f[7][1],n=std::hypot(q.f[7][2],q.f[7][3]),slope=std::hypot(field[1],field[2]);
+ const bool contextValid=std::abs(q.f[7][2])<=1024;
+ const bool fieldValid=std::abs(field[0])<=64&&std::abs(field[1])<=1024&&std::abs(field[2])<=1024&&std::abs(field[3])<=1048576;
+ const bool wet=contextValid&&q.f[9][0]>=.5&&q.f[9][1]>=.5&&q.f[8][0]>0&&depth>.15;
+ const double domain=wet&&distance>=0?smooth(.15,.8,depth)*(1-smooth(8,12,depth))*(1-smooth(96,128,distance))*q.f[8][0]:0;
+ const double ht=dt>0?(field[0]-q.f[10][2])/dt:0;double rate=0;
+ if(domain>0&&fieldValid&&q.f[10][3]>=0&&dt>1e-6&&dt<=.25&&field[0]>0&&ht>0&&n>1e-8&&slope>1e-8){
+ const double incoming=smooth(0,.25,(field[1]/slope)*(q.f[7][2]/n)+(field[2]/slope)*(q.f[7][3]/n));
+ const double breaking=(std::max)(smooth(.4,.85,2*field[0]/(std::max)(depth+.5,1.0)),smooth(.04,.30,1-field[3]));
+ const double damping=q.f[8][2]+(q.f[8][3]-q.f[8][2])*q.f[8][0];
+ rate=1.2*domain*incoming*breaking*(1-damping*damping)*smooth(0,.5,field[0])*smooth(0,.08,ht);
+ }
+ double next[4]={0,0,0,-1};
+ if(dt<=1e-6)for(unsigned i=0;i<4;++i)next[i]=q.f[10][i];
+ else if(wet&&fieldValid){const double decay=std::exp(-dt/5);next[0]=decay*q.f[10][0];next[1]=decay*(q.f[10][1]+dt*q.f[10][0]);next[2]=field[0];next[3]=dt<=.25?rate:0;
+ if(dt<=.25){ // independent numerical convolution, not production integral series
+ constexpr unsigned steps=2048;double density=0,age=0;
+ for(unsigned i=0;i<=steps;++i){const double a=dt*i/steps,r0=clamp(q.f[10][3],0,1.2),r=rate+(r0-rate)*a/dt;
+ const double mass=std::exp(-a/5)*r,w=(i==0||i==steps)?1:(i%2?4:2);density+=w*mass;age+=w*a*mass;}
+ next[0]+=density*dt/(3*steps);next[1]+=age*dt/(3*steps);
+ }}
+ double coverage=0;if(next[0]>0){const double age=next[1]/next[0];coverage=(1-std::exp(-next[0]))*(1-smooth(.4,3,age)*(1-q.f[11][2]))*(1-smooth(8,14,age));}
+ const double status[4]={rate,domain,coverage,1};
+ double diffusion[4]={q.f[10][0],q.f[10][1],q.f[10][2],q.f[10][3]};const double amount=2*(std::min)(dt,.25)/25;
+ diffusion[0]+=amount*(5-2*diffusion[0]);diffusion[1]+=amount*(10-2*diffusion[1]);
+ for(unsigned col=0;col<5;++col)for(unsigned c=0;c<4;++c){
+ if(row==16&&col<2)continue; // adversarial finite magnitude is a source-admission control
+ const double expected=col==0?incident[c]:col==1?field[c]:col==2?status[c]:col==3?next[c]:diffusion[c];
+ const double value=actual[(row*width+col)*4+c],error=std::abs(value-expected);maximum=(std::max)(maximum,error);
+ if(!(std::isfinite(value)&&error<.00003))printf("surf core row%u col%u ch%u got%.9g expected%.9g\n",row,col,c,value,expected);
+ CHECK(std::isfinite(value)&&error<.00003);
+ }
+ active+=rate>.1;suppressed+=rate==0;
+ if(row==0)armedFine=std::abs(vz*std::tanh((h+q.f[4][1]*20)/vz)-incident[0]);
+ }
+ CHECK(active>=3&&suppressed>=12&&armedFine>1);
+ for(unsigned i=0;i<width*4;++i)CHECK(actual[i]==actual[(3*width)*4+i]); // fine-scale trigger is exactly absent
+ printf("sdl_gpu_frame_selfcheck: coastal surf core %u cases actual FFT decode/shared limiter + independent blend/rate/convolution/age/diffusion max%.9g active%u suppressed%u fine-control%.6g repeat exact\n",height,maximum,active,suppressed,armedFine);
+}
+
+
+// Append after read_ocean and invoke AFTER check_gpu_fft_ocean, whose initial-state
+// assertions deliberately precede every other use of the real ocean owner.
+static void check_gpu_water_coastal_incident(SdlGpuFrame *frame)
+{
+ using namespace WaterCoastalSurf;
+ const uint64_t revision=0xc04157;
+ std::vector<Node> nodes;
+ const float positions[][2]={{0,0},{-137.25f,91.5f},{1938,736},{3050,-330}};
+ for(const auto &p:positions)for(unsigned support=0;support<2;++support)for(unsigned weight=0;weight<3;++weight){
+ Node node;node.world[0]=p[0];node.world[1]=p[1];node.world[2]=7+4*(support*3+weight);
+ node.context={4,64,-1,0,support==0?1.f:.4f,weight==0?0.f:weight==1?.4f:1.f,.4f,.5f,1,1};
+ nodes.push_back(node);
+ }
+ CHECK(ValidGraph(nodes,5));
+ struct Resources {
+ SdlGpuFrame *frame=nullptr;SDL_GPUShader *vertex=nullptr,*pixel=nullptr;SDL_GPUGraphicsPipeline *pipeline=nullptr;bool installed=false;
+ ~Resources(){if(installed)CHECK(frame->Clear_Coastal_Surf());
+ if(pipeline)SDL_ReleaseGPUGraphicsPipeline(frame->Device(),pipeline);
+ if(vertex)SDL_ReleaseGPUShader(frame->Device(),vertex);if(pixel)SDL_ReleaseGPUShader(frame->Device(),pixel);}
+ } resources;resources.frame=frame;
+ std::string source,error;std::vector<unsigned char>spirv;
+ const bool generated=WaterCoastalIncident::PixelSource(source);CHECK(generated);if(!generated)return;
+ bool ok=SDL3_Compile_HLSL_To_SPIRV(WaterCoastalIncident::VertexSource(),true,spirv,error);CHECK(ok);if(!ok)return;
+ resources.vertex=SDL3_Create_Shader(frame->Device(),spirv,true,error);CHECK(resources.vertex);if(!resources.vertex)return;
+ ok=SDL3_Compile_HLSL_To_SPIRV(source,false,spirv,error);CHECK(ok);
+ if(!ok){printf("coastal incident shader: %s\n",error.c_str());return;}
+ unsigned samplers=0,buffers=0;SDL3_Shader_Slots(spirv,false,samplers,buffers);
+ CHECK(samplers==WaterCoastalIncident::SamplerCount&&buffers==1);
+ resources.pixel=SDL3_Create_Shader(frame->Device(),spirv,false,error);CHECK(resources.pixel);if(!resources.pixel)return;
+ SDL_GPUColorTargetDescription colour={};colour.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
+ SDL_GPUGraphicsPipelineCreateInfo pipeline={};pipeline.vertex_shader=resources.vertex;pipeline.fragment_shader=resources.pixel;
+ pipeline.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;pipeline.target_info.color_target_descriptions=&colour;pipeline.target_info.num_color_targets=1;
+ resources.pipeline=SDL_CreateGPUGraphicsPipeline(frame->Device(),&pipeline);CHECK(resources.pipeline);if(!resources.pipeline)return;
+ resources.installed=frame->Install_Coastal_Surf(revision,nodes,5);CHECK(resources.installed);if(!resources.installed)return;
+ const SdlTarget target=frame->Coastal_Surf_Field_Target(revision);
+ CHECK(target.Colour&&target.Depth==nullptr&&target.Width==256&&target.Height==256);if(!target.Colour)return;
+ auto render=[&](float time,float count){
+ CHECK(frame->Flush());SDL_GPUCommandBuffer *commands=SDL_AcquireGPUCommandBuffer(frame->Device());CHECK(commands);
+ if(!commands)return std::vector<float>();
+ SDL_GPUColorTargetInfo attachment={};attachment.texture=target.Colour;attachment.load_op=SDL_GPU_LOADOP_DONT_CARE;attachment.store_op=SDL_GPU_STOREOP_STORE;
+ SDL_GPURenderPass *pass=SDL_BeginGPURenderPass(commands,&attachment,1,nullptr);CHECK(pass);
+ if(!pass){SDL_CancelGPUCommandBuffer(commands);return std::vector<float>();}
+ SDL_BindGPUGraphicsPipeline(pass,resources.pipeline);
+ SDL_GPUTextureSamplerBinding bindings[WaterCoastalIncident::SamplerCount]={};
+ for(unsigned i=0;i<4;++i){bindings[i].texture=frame->Coastal_Surf_Domain(i,revision);bindings[i].sampler=frame->Coastal_Surf_Sampler(revision);}
+ for(unsigned i=0;i<4;++i){bindings[4+i].texture=frame->Ocean_Map(i);bindings[4+i].sampler=frame->Ocean_Sampler();}
+ SDL_BindGPUFragmentSamplers(pass,0,bindings,WaterCoastalIncident::SamplerCount);
+ const WaterCoastalIncident::Parameters parameters{time,count,0,0};
+ SDL_PushGPUFragmentUniformData(commands,0,&parameters,sizeof(parameters));
+ SDL_DrawGPUPrimitives(pass,3,1,0,0);SDL_EndGPURenderPass(pass);CHECK(SDL_SubmitGPUCommandBuffer(commands));
+ return read_float_targets(frame,&target.Colour,1,256,256);
+ };
+ struct Mode{double x,y,a,w,p;};
+#define COASTAL_INCIDENT_MODE(kx,ky,a,w,p) {kx,ky,a,w,p},
+ const Mode legacyModes[]={WATER_SURFACE_MODES(COASTAL_INCIDENT_MODE)};
+ const Mode oceanModes[]={WATER_OCEAN_MODES(COASTAL_INCIDENT_MODE)};
+#undef COASTAL_INCIDENT_MODE
+ // Independent scalar equations using the source coefficient data. Derivatives
+ // come from double central differences, not either generated analytic derivative.
+ auto scalar=[&](double x,double y,double time,bool ocean){
+ double sum=0;
+ if(!ocean){for(unsigned i=0;i<3;++i){const Mode&m=legacyModes[i];const double phase=x*m.x+y*m.y-time*m.w+m.p;
+ sum+=m.a*(std::sin(phase)+.13*std::sin(2*phase));}return sum;}
+ const double s0=std::sin(x*.0241+y*.0157-time*.23+.4),s1=std::sin(x*-.0173+y*.0299-time*.19+2.1);
+ x+=5*s0;y+=4*s1;
+ for(const Mode&m:oceanModes)if(m.x*m.x+m.y*m.y<.18){const double phase=x*m.x+y*m.y-time*m.w+m.p;
+ sum+=m.a*(std::sin(phase)+.08*std::sin(2*phase));}
+ return sum*(.86+.14*s0*s1);
+ };
+ auto analytic=[&](double x,double y,double time,bool ocean){const double epsilon=.0001;
+ return std::array<double,4>{scalar(x,y,time,ocean),
+ (scalar(x+epsilon,y,time,ocean)-scalar(x-epsilon,y,time,ocean))/(2*epsilon),
+ (scalar(x,y+epsilon,time,ocean)-scalar(x,y-epsilon,time,ocean))/(2*epsilon),1};};
+ struct Texel {std::array<double,4> value{},error{};};
+ auto sample=[&](const std::vector<float>&maps,unsigned map,float worldX,float worldY){
+ const unsigned cascade=map/2;const float period=WaterFftSpectrum::Sizes[cascade]*WaterFftSampling::WorldScale;
+ // Float division matches the production UV arithmetic; interpolation itself
+ // is independent double bilinear of the REAL sampled mip-zero texels.
+ const float u=worldX/period,v=worldY/period;
+ const double x=double(u)*256-.5,y=double(v)*256-.5;const int ix=int(std::floor(x)),iy=int(std::floor(y));
+ const double fx=x-ix,fy=y-iy;Texel result;
+ auto at=[&](int px,int py,unsigned c){px=(px%256+256)%256;py=(py%256+256)%256;return double(maps[((map*256+py)*256+px)*4+c]);};
+ for(unsigned c=0;c<4;++c){const double a=at(ix,iy,c),b=at(ix+1,iy,c),d=at(ix,iy+1,c),e=at(ix+1,iy+1,c);
+ result.value[c]=(a+(b-a)*fx)*(1-fy)+(d+(e-d)*fx)*fy;
+ // A portable 8-bit subtexel precision bound, plus float UV rounding.
+ // Neighbouring cells are included if rounding crosses a bilinear edge.
+ double sx=0,sy=0,magnitude=0;
+ for(int yy=iy-1;yy<=iy+1;++yy)for(int xx=ix-1;xx<=ix+1;++xx){
+ sx=(std::max)(sx,std::abs(at(xx+1,yy,c)-at(xx,yy,c)));
+ sy=(std::max)(sy,std::abs(at(xx,yy+1,c)-at(xx,yy,c)));
+ magnitude=(std::max)(magnitude,std::abs(at(xx,yy,c)));}
+ const double ex=1./256+4*std::numeric_limits<float>::epsilon()*std::abs(u)*256;
+ const double ey=1./256+4*std::numeric_limits<float>::epsilon()*std::abs(v)*256;
+ result.error[c]=sx*ex+sy*ey+2e-7*(1+magnitude);
+ }return result;
+ };
+ auto spectral=[&](const std::vector<float>&maps,float x,float y,bool fine){
+ std::array<Texel,6> samples;for(unsigned i=0;i<(fine?6:4);++i)samples[i]=sample(maps,i,x,y);
+ double displacement[3]={},derivative[5]={},de[3]={},ge[5]={};
+ for(unsigned cascade=0;cascade<(fine?3:2);++cascade){const auto&a=samples[cascade*2],&b=samples[cascade*2+1];
+ const double chop=cascade?-1.5:-1.2,scale=WaterFftSampling::WorldScale;
+ displacement[0]+=chop*scale*a.value[0];displacement[1]+=chop*scale*a.value[2];displacement[2]+=scale*a.value[1];
+ de[0]+=std::abs(chop)*scale*a.error[0];de[1]+=std::abs(chop)*scale*a.error[2];de[2]+=scale*a.error[1];
+ derivative[0]+=b.value[0];derivative[1]+=b.value[1];derivative[2]+=chop*b.value[2];derivative[3]+=chop*b.value[3];derivative[4]+=chop*a.value[3];
+ ge[0]+=b.error[0];ge[1]+=b.error[1];ge[2]+=std::abs(chop)*b.error[2];ge[3]+=std::abs(chop)*b.error[3];ge[4]+=std::abs(chop)*a.error[3];
+ }
+ const double vertical=WaterFftGeometry::MaxVerticalDisplacement,horizontal=WaterFftGeometry::MaxHorizontalDisplacement/std::sqrt(2.0);
+ double limiter[3],le[3];for(unsigned i=0;i<3;++i){const double bound=i==2?vertical:horizontal;
+ limiter[i]=1-std::pow(std::tanh(displacement[i]/bound),2);le[i]=2*de[i]/bound;}
+ Texel result;result.value[0]=vertical*std::tanh(displacement[2]/vertical);
+ result.value[1]=derivative[0]*limiter[2];result.value[2]=derivative[1]*limiter[2];
+ const double a=1+derivative[2]*limiter[0],b=1+derivative[3]*limiter[1],cross=derivative[4];
+ result.value[3]=a*b-cross*cross*limiter[0]*limiter[1];
+ result.error[0]=de[2];result.error[1]=ge[0]+std::abs(derivative[0])*le[2];result.error[2]=ge[1]+std::abs(derivative[1])*le[2];
+ const double ae=ge[2]+std::abs(derivative[2])*le[0],be=ge[3]+std::abs(derivative[3])*le[1];
+ result.error[3]=std::abs(a)*be+std::abs(b)*ae+ae*be+2*std::abs(cross)*ge[4]+ge[4]*ge[4]+cross*cross*(le[0]+le[1]);
+ return result;
+ };
+ double maximum=0,maximumBound=0,wrongBlend=0,wrongTime=0,fineArmed=0,advanced=0,oldCoastPhase=0;
+ std::vector<float> first;
+ for(float time:{3.4375f,7.75f}){
+ CHECK(frame->Prepare_Ocean(time*WaterFftSampling::TimeScale));
+ const auto maps=read_ocean(frame),actual=render(time,float(nodes.size())),repeat=render(time,float(nodes.size()));
+ CHECK(actual.size()==256*256*4 && actual==repeat);if(actual.size()!=256*256*4)return;
+ for(unsigned n=0;n<nodes.size();++n){const Node&node=nodes[n];
+ const double r=node.context.offshore,w=node.context.exposure;
+ const auto river=analytic(node.world[0],node.world[1],time,false),ocean=analytic(node.world[0],node.world[1],time,true);
+ const auto wrongClock=analytic(node.world[0],node.world[1],time*WaterFftSampling::TimeScale,false);
+ const auto fft=spectral(maps,node.world[0],node.world[1],false),full=spectral(maps,node.world[0],node.world[1],true);
+ fineArmed=(std::max)(fineArmed,std::abs(fft.value[0]-full.value[0]));
+ for(unsigned c=0;c<4;++c){const double a=c==3?1:river[c]+(ocean[c]-river[c])*r;
+ const double expected=c==3?1+(fft.value[3]-1)*w*r:a+(fft.value[c]-a)*w;
+ // Analytic tolerance retains the existing float-phase model bound;
+ // spectral tolerance is derived from THIS point's real texel gradients.
+ const double bound=.0025*(1-w)+w*fft.error[c]+.00002;
+ const double error=std::abs(actual[n*4+c]-expected);maximum=(std::max)(maximum,error);maximumBound=(std::max)(maximumBound,bound);
+ CHECK(std::isfinite(actual[n*4+c])&&error<bound);
+ if(c<3&&w<1&&r>0)wrongBlend=(std::max)(wrongBlend,std::abs(expected-(river[c]+(fft.value[c]-river[c])*w)));
+ if(c<3&&w<1&&r==0)wrongTime=(std::max)(wrongTime,std::abs((river[c]-wrongClock[c])*(1-w)));
+ if(c<3&&w==1&&r==0)oldCoastPhase=(std::max)(oldCoastPhase,std::abs(expected-river[c]));
+ }
+ // Full connected-water support has exactly one wave phase at R0,
+ // transitional R and R1. Only horizontal compression retains the R fade.
+ if(n%6<3)for(unsigned c=0;c<3;++c)CHECK(std::abs(actual[n*4+c]-actual[(n-n%6)*4+c])<.000002f);
+ if(r==0)CHECK(actual[n*4+3]==1);
+ }
+ for(unsigned n=unsigned(nodes.size());n<256*256;++n){CHECK(actual[n*4]==0&&actual[n*4+1]==0&&actual[n*4+2]==0&&actual[n*4+3]==1);}
+ if(first.empty())first=actual;else for(unsigned n=0;n<nodes.size()*4;++n)advanced=(std::max)(advanced,std::abs(double(first[n])-actual[n]));
+ }
+ CHECK(wrongBlend>.05&&wrongTime>.05&&fineArmed>.001&&advanced>.05&&oldCoastPhase>.05);
+ const auto invalid=render(std::numeric_limits<float>::quiet_NaN(),float(nodes.size()));
+ const auto fractional=render(7.75f,float(nodes.size())+.5f);
+ CHECK(invalid.size()==256*256*4&&fractional==invalid);
+ for(unsigned n=0;n<invalid.size()/4;++n)CHECK(invalid[n*4]==0&&invalid[n*4+1]==0&&invalid[n*4+2]==0&&invalid[n*4+3]==1);
+ printf("sdl_gpu_frame_selfcheck: coastal incident real FFT atlas %zu nodes x2 phases, B1 and B.4 across R0/mixed/R1, max error %.8g bound %.8g; old coastal phase mismatch %.6g, analytic mix %.6g time-scale %.6g fine %.6g advance %.6g; repeat exact, padding/invalid clear\n",
+ nodes.size(),maximum,maximumBound,oldCoastPhase,wrongBlend,wrongTime,fineArmed,advanced);
+}
+
+// Run after the new presentation header/uniform transport is integrated. This fixture
+// extracts the ACTUAL generated injection, then supplies controlled scene provenance.
+// Existing scene-depth/refraction tests independently validate real reconstruction.
+#if defined(__linux__)
+static void check_gpu_water_coastal_presentation(SdlGpuFrame *frame)
+{
+ struct Query{float q[7][4];};
+ Query base={{{1,.1f,.0625f,1},{0,0,.4f,.4f},{.2f,1,1,1},{1,1,1,0},{0,0,0,1},{1,1,1,0},{2,1,0,0}}};
+ std::vector<Query>queries(30,base);
+ queries[1].q[1][2]=queries[1].q[1][3]=0;queries[2].q[1][2]=queries[2].q[1][3]=1;
+ queries[3].q[0][3]=0;queries[4].q[1][0]=.2f;queries[5].q[0][2]=-.1f;queries[6].q[1][1]=1;
+ queries[7].q[0][0]=0;queries[8].q[0][1]=20;queries[9].q[0][0]=std::numeric_limits<float>::quiet_NaN();
+ queries[10].q[2][1]=6;queries[11].q[6][1]=-1;queries[12].q[3][0]=-2;
+ queries[13].q[2][2]=5;queries[14].q[2][3]=5;queries[15].q[3][1]=0;queries[16].q[3][2]=0;
+ queries[17].q[1][2]=0;queries[18].q[3][3]=.5f;queries[19].q[4][0]=.1f;
+ queries[20].q[5][0]=0;queries[21].q[4][3]=0;queries[22].q[4][2]=1;
+ queries[23].q[2][0]=1;queries[24].q[2][0]=-1;queries[25].q[5][3]=2;
+ queries[26].q[0][1]=3;queries[27].q[0][2]=3;queries[28].q[6][0]=30;queries[29].q[1][3]=.42f;
+ const unsigned rows=unsigned(queries.size()),columns=2;CHECK(queries.size()*sizeof(Query)<=4096);
+ const char *oldOption=getenv("ZH_WATER_SURF_GPU"),*oldDebug=getenv("ZH_WATER_DEBUG");
+ const bool hadOption=oldOption!=nullptr,hadDebug=oldDebug!=nullptr;
+ const std::string savedOption=oldOption?oldOption:"",savedDebug=oldDebug?oldDebug:"";
+ CHECK(setenv("ZH_WATER_SURF_GPU","1",1)==0);CHECK(unsetenv("ZH_WATER_DEBUG")==0);
+ PixelPipelineDescription pd={};std::string production;
+ const bool generated=EngineShader_Pixel_Program(ENGINE_SHADER_WATER_TRAPEZOID,pd,production,COMBINER_SHADER_TARGET_SDL3_GPU);
+ if(hadOption)CHECK(setenv("ZH_WATER_SURF_GPU",savedOption.c_str(),1)==0);else CHECK(unsetenv("ZH_WATER_SURF_GPU")==0);
+ if(hadDebug)CHECK(setenv("ZH_WATER_DEBUG",savedDebug.c_str(),1)==0);else CHECK(unsetenv("ZH_WATER_DEBUG")==0);
+ CHECK(generated);if(!generated)return;
+ const size_t begin=production.find("float gpuCoastFoam="),end=production.find("if(shoreFoamEnabled",begin);
+ CHECK(begin!=std::string::npos&&end!=std::string::npos&&end>begin);if(begin==std::string::npos||end==std::string::npos||end<=begin)return;
+ std::string ps="struct Query{float4 q[7];};cbuffer Queries:register(b0,space3){Query Q[30];};\n";
+ for(unsigned i:{4u,6u,15u}){const std::string n=std::to_string(i);
+ ps+="Texture2D<float4> Texture"+n+":register(t"+n+",space2);SamplerState Sampler"+n+":register(s"+n+",space2);\n";}
+ ps+=R"HLSL(
+float oceanNoise(float2 p){return .5;}
+float2 waterScenePixel(float2 p){return p;}
+float3 scenePosition(float2 p,float raw){return float3(2,floor(p.y),Q[(uint)p.y].q[2].y);}
+float terrainHeight(float2 p){Query q=Q[(uint)p.y];return p.x<.5?q.q[2].z:p.x<1.5?q.q[2].w:q.q[3].x;}
+float3 vesselHullDamping(float2 p,float level){return float3(Q[(uint)p.y].q[3].z,0,0);}
+bool waterShoreSceneDepth(float available,float raw){return isfinite(available)&&available>.5&&isfinite(raw)&&raw>=0&&raw<.999999;}
+struct Input{float4 Position;float4 Diffuse;float2 TexCoord0;};
+)HLSL";
+ // Keep the actual rank/coverage/porosity helpers, excluding unrelated vessel
+ // history entry points that require a different atlas and uniform layout.
+ const std::string foamSource=WaterFoamShading::Source();
+ const size_t foamBegin=foamSource.find("float waterFoamNoiseRank("),foamEnd=foamSource.find("float waterFoamMicroCoverage(");
+ CHECK(foamBegin!=std::string::npos&&foamEnd!=std::string::npos&&foamEnd>foamBegin);
+ if(foamBegin==std::string::npos||foamEnd==std::string::npos||foamEnd<=foamBegin)return;
+ ps+=foamSource.substr(foamBegin,foamEnd-foamBegin);ps+=WaterCoastalPresentation::Source();
+ ps+=R"HLSL(
+float4 main(float4 pixel:SV_Position):SV_Target0 {
+ uint row=(uint)pixel.y;Query q=Q[row];Input input;
+ input.Position=float4(.5,row+.5,.5,1);input.Diffuse=float4(q.q[3].y,1,1,1);input.TexCoord0=float2(q.q[3].w,0);
+ float time=q.q[6].x,baseLevel=5,fftWeight=q.q[1].z,foamFootprint=.25;
+ float2 wavePosition=float2(1,row),correctionSlope=q.q[4].xy;
+ float3 world=float3(0,row,5),view=float3(0,0,q.q[6].y);
+ float surfaceTerrainHeight=q.q[2].z;
+ float4 WaterParameters=float4(time,q.q[4].z,0,0),OpticalParameters=float4(0,0,q.q[5].z,q.q[4].w);
+ float4 TerrainParameters=float4(-4.5,30,1,q.q[5].y),SceneParameters=float4(1,1,1.0/30,q.q[5].x);
+ float4 CoastalArea=float4(q.q[5].w,-.5,2,30);
+ float4 CoastalParams=float4(q.q[0].w,baseLevel+q.q[1].x,time-q.q[0].z,time+q.q[1].y);
+ // Deliberately wrong refracted/fallback values arm use of original depth instead.
+ float depth=100;float3 bottom=float3(0,0,-100),shoreSceneBottom=bottom;
+)HLSL";
+ ps+=production.substr(begin,end-begin);
+ ps+=R"HLSL(
+ if(pixel.x<1)return float4(gpuCoastRaw,gpuCoastGate,gpuCoastFoam,1);
+ float2 moments=waterCoastalAtTime(q.q[0].xy,q.q[0].z);
+ return float4(moments,waterCoastalModelGate(q.q[1].z,q.q[1].w,q.q[3].w,q.q[4].xy),
+ waterCoastalViewValid(CoastalArea,CoastalParams,wavePosition,baseLevel,time)?1:0);
+})HLSL";
+ struct Resources{SDL_GPUDevice*d=nullptr;SDL_GPUTexture*t[3]={},*target=nullptr;SDL_GPUSampler*point=nullptr;SDL_GPUShader*vs=nullptr,*ps=nullptr;SDL_GPUGraphicsPipeline*pipeline=nullptr;
+ ~Resources(){if(target)SDL_ReleaseGPUTexture(d,target);for(auto*p:t)if(p)SDL_ReleaseGPUTexture(d,p);if(point)SDL_ReleaseGPUSampler(d,point);
+ if(pipeline)SDL_ReleaseGPUGraphicsPipeline(d,pipeline);if(vs)SDL_ReleaseGPUShader(d,vs);if(ps)SDL_ReleaseGPUShader(d,ps);}}r;r.d=frame->Device();
+ std::vector<unsigned char>spirv;std::string error;bool ok=SDL3_Compile_HLSL_To_SPIRV(WaterFftSpectrum::VertexHlsl(),true,spirv,error);CHECK(ok);if(!ok)return;
+ r.vs=SDL3_Create_Shader(r.d,spirv,true,error);CHECK(r.vs);if(!r.vs)return;
+ ok=SDL3_Compile_HLSL_To_SPIRV(ps,false,spirv,error);CHECK(ok);if(!ok){printf("coastal presentation PS: %s\n",error.c_str());return;}
+ unsigned samplers=0,buffers=0;SDL3_Shader_Slots(spirv,false,samplers,buffers);CHECK(samplers==16&&buffers==1);if(samplers!=16||buffers!=1)return;
+ r.ps=SDL3_Create_Shader(r.d,spirv,false,error);CHECK(r.ps);if(!r.ps)return;
+ SDL_GPUSamplerCreateInfo si={};si.min_filter=si.mag_filter=SDL_GPU_FILTER_NEAREST;si.mipmap_mode=SDL_GPU_SAMPLERMIPMAPMODE_NEAREST;
+ si.address_mode_u=si.address_mode_v=si.address_mode_w=SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
+ r.point=SDL_CreateGPUSampler(r.d,&si);CHECK(r.point);if(!r.point)return;
+ SDL_GPUColorTargetDescription colour={};colour.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
+ SDL_GPUGraphicsPipelineCreateInfo pi={};pi.vertex_shader=r.vs;pi.fragment_shader=r.ps;pi.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;
+ pi.target_info.color_target_descriptions=&colour;pi.target_info.num_color_targets=1;r.pipeline=SDL_CreateGPUGraphicsPipeline(r.d,&pi);CHECK(r.pipeline);if(!r.pipeline)return;
+ SDL_GPUTextureCreateInfo ti={};ti.type=SDL_GPU_TEXTURETYPE_2D;ti.format=colour.format;ti.usage=SDL_GPU_TEXTUREUSAGE_SAMPLER;ti.width=1;ti.height=rows;ti.layer_count_or_depth=ti.num_levels=1;
+ for(auto &texture:r.t){texture=SDL_CreateGPUTexture(r.d,&ti);CHECK(texture);if(!texture)return;}
+ ti.width=columns;ti.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;r.target=SDL_CreateGPUTexture(r.d,&ti);CHECK(r.target);if(!r.target)return;
+ const unsigned bytes=rows*4*sizeof(float);std::vector<float> data(rows*4*3,0);
+ // Canonical phase support is B. Deliberately unrelated optical R arms the
+ // regression: reading R would reject otherwise matching coastal FFT support.
+ for(unsigned row=0;row<rows;++row){data[row*4]=.73f;data[row*4+2]=queries[row].q[1][3];data[rows*4+row*4]=queries[row].q[2][0];
+ data[rows*8+row*4]=queries[row].q[0][0];data[rows*8+row*4+1]=queries[row].q[0][1];}
+ SDL_GPUTransferBufferCreateInfo transferInfo={};transferInfo.usage=SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD;transferInfo.size=bytes*3;
+ SDL_GPUTransferBuffer *transfer=SDL_CreateGPUTransferBuffer(r.d,&transferInfo);CHECK(transfer);if(!transfer)return;
+ void*mapped=SDL_MapGPUTransferBuffer(r.d,transfer,false);CHECK(mapped);if(!mapped){SDL_ReleaseGPUTransferBuffer(r.d,transfer);return;}
+ memcpy(mapped,data.data(),bytes*3);SDL_UnmapGPUTransferBuffer(r.d,transfer);CHECK(frame->Flush());
+ SDL_GPUCommandBuffer *upload=SDL_AcquireGPUCommandBuffer(r.d);CHECK(upload);if(!upload){SDL_ReleaseGPUTransferBuffer(r.d,transfer);return;}
+ SDL_GPUCopyPass *copy=SDL_BeginGPUCopyPass(upload);CHECK(copy);if(!copy){SDL_CancelGPUCommandBuffer(upload);SDL_ReleaseGPUTransferBuffer(r.d,transfer);return;}
+ for(unsigned i=0;i<3;++i){SDL_GPUTextureTransferInfo source={};source.transfer_buffer=transfer;source.offset=i*bytes;source.pixels_per_row=1;source.rows_per_layer=rows;
+ SDL_GPUTextureRegion region={};region.texture=r.t[i];region.w=1;region.h=rows;region.d=1;SDL_UploadToGPUTexture(copy,&source,&region,false);}
+ SDL_EndGPUCopyPass(copy);CHECK(SDL_SubmitGPUCommandBuffer(upload));SDL_ReleaseGPUTransferBuffer(r.d,transfer);
+ auto render=[&](){SDL_GPUCommandBuffer *commands=SDL_AcquireGPUCommandBuffer(r.d);CHECK(commands);if(!commands)return std::vector<float>();
+ SDL_GPUColorTargetInfo target={};target.texture=r.target;target.load_op=SDL_GPU_LOADOP_DONT_CARE;target.store_op=SDL_GPU_STOREOP_STORE;
+ SDL_GPURenderPass *pass=SDL_BeginGPURenderPass(commands,&target,1,nullptr);CHECK(pass);if(!pass){SDL_CancelGPUCommandBuffer(commands);return std::vector<float>();}
+ SDL_BindGPUGraphicsPipeline(pass,r.pipeline);SDL_GPUTextureSamplerBinding bindings[16]={};for(auto &binding:bindings){binding.texture=r.t[0];binding.sampler=r.point;}
+ bindings[6].texture=r.t[1];bindings[15].texture=r.t[2];SDL_BindGPUFragmentSamplers(pass,0,bindings,16);
+ SDL_PushGPUFragmentUniformData(commands,0,queries.data(),unsigned(queries.size()*sizeof(Query)));SDL_DrawGPUPrimitives(pass,3,1,0,0);
+ SDL_EndGPURenderPass(pass);CHECK(SDL_SubmitGPUCommandBuffer(commands));return read_float_targets(frame,&r.target,1,columns,rows);};
+ const auto actual=render(),repeat=render();CHECK(actual==repeat&&actual.size()==rows*columns*4);if(actual.size()!=rows*columns*4)return;
+ auto clamp=[](double x,double lo,double hi){return (std::max)(lo,(std::min)(hi,x));};
+ auto smooth=[&](double a,double b,double x){const double t=clamp((x-a)/(b-a),0,1);return t*t*(3-2*t);};
+ auto band=[&](double coverage,double cell){const double ratio=.25/cell,unresolved=smooth(.5,1.5,ratio),width=clamp(ratio*.5,cell==1?.08:.01,.5);
+ double cutoff=coverage;if(coverage<width)cutoff=-width+std::sqrt(4*width*coverage);else if(coverage>1-width)cutoff=1+width-std::sqrt(4*width*(1-coverage));
+ const double resolved=clamp((cutoff-.5+width)/(2*width),0,1);return resolved*(1-unresolved)+coverage*unresolved;};
+ double maximum=0;unsigned admitted=0,rejected=0;
+ for(unsigned row=0;row<rows;++row){const auto&q=queries[row].q;double density=0,age=0;
+ if(std::isfinite(q[0][0])&&q[0][0]>0&&q[0][0]<=16&&q[0][1]>=0&&q[0][1]<=1024&&q[0][2]>=0&&q[0][2]<14){
+ age=q[0][1]/double(q[0][0])+q[0][2];if(age<14)density=q[0][0]*std::exp(-q[0][2]/5.0);else age=0;}
+ const double model=(1-smooth(.015,.06,std::abs(q[1][2]-q[1][3])))*(1-smooth(.02,.15,std::abs(q[3][3])))
+ *(1-smooth(.002,.02,std::hypot(q[4][0],q[4][1])));
+ const bool view=q[0][3]>=.5&&std::abs(q[1][0])<=.01&&std::abs(q[1][1])<=.0001&&q[0][2]+q[1][1]>=0
+ &&q[6][0]-q[0][2]>=0&&q[5][3]<=1&&q[5][3]+2>=1;
+ const bool enabled=q[4][2]<.5&&q[4][3]>.5&&q[5][0]>.5&&q[5][1]>.5&&q[5][2]>.5&&view;
+ double raw=0,gate=0;
+ if(enabled&&density>0){const double coverage=-std::expm1(-density),aged=smooth(.4,3,age),patch=std::sqrt(coverage);
+ const double porous=band(patch,1)*band(patch,.35);
+ raw=(coverage*(1-aged)+porous*aged)*(1-smooth(8,14,age));
+ if(model>0&&raw>0&&q[2][0]>=0&&q[2][0]<.999999&&q[2][1]<=4.92&&(q[2][1]-5)*q[6][1]<-.01
+ &&q[2][2]<(std::min)(4.92,4.85)&&q[2][3]<4.85){
+ gate=model*smooth(0,.8,5-q[2][1])*smooth(.15,.8,5-q[2][2])*(1-smooth(.5,1.5,std::abs(q[2][1]-q[3][0])))
+ *smooth(.001,.1,(std::min)(clamp(q[3][1],0,1),clamp(q[3][2],0,1)));}
+ }
+ const double expected[8]={raw,gate,raw*gate,1,density,age,model,view?1.:0.};
+ for(unsigned c=0;c<8;++c){const double error=std::abs(actual[row*8+c]-expected[c]);maximum=(std::max)(maximum,error);
+ if(!(std::isfinite(actual[row*8+c])&&error<.00003))printf("coast presentation row%u ch%u got%.9g expected%.9g\n",row,c,actual[row*8+c],expected[c]);
+ CHECK(std::isfinite(actual[row*8+c])&&error<.00003);}
+ admitted+=raw*gate>0;rejected+=raw*gate==0;
+ }
+ CHECK(admitted>=5&&rejected>=20);
+ for(unsigned c=0;c<4;++c)CHECK(actual[c]==actual[28*8+c]); // shifted absolute time, same age: no material oscillator
+ CHECK(actual[1*8+2]>0&&actual[2*8+2]>0); // R0 and R1 are both supported
+ CHECK(actual[23*8+2]==0&&actual[12*8+2]==0&&actual[16*8+2]==0); // false fallback, object, known hull armed
+ printf("sdl_gpu_frame_selfcheck: coastal presentation actual injection %u cases, independent moment/model/original-depth/wet/porosity oracle max%.9g admitted%u rejected%u repeat exact; absolute-time shift exact\n",rows,maximum,admitted,rejected);
+}
+#endif // __linux__
+
int main()
{
if (!SDL_Init(SDL_INIT_VIDEO)) {
@@ -93,6 +8164,69 @@ int main()
return 77;
}
printf("sdl_gpu_frame_selfcheck: %s\n", SDL_GetGPUDeviceDriver(frame->Device()));
+ check_gpu_fft_ocean(frame);
+ check_gpu_water_coastal_incident(frame);
+ check_gpu_coastal_surf_from_ocean(frame);
+ check_gpu_water_vertex_uniform_order(frame);
+ check_gpu_modern_water_material(frame);
+ check_gpu_water_visual_uniform_order(frame);
+ check_gpu_water_visual_query(frame);
+#if defined(__linux__)
+ check_gpu_water_visual_zero_effect_skip(frame);
+#endif
+ check_gpu_coastal_surf_owner(frame);
+ check_gpu_coastal_surf_view(frame);
+#if defined(__linux__)
+ check_gpu_water_coastal_presentation(frame);
+#endif
+ check_gpu_foam_history_upload(frame);
+ check_gpu_foam_history_tiles(frame);
+#if defined(__linux__)
+ check_gpu_foam_history_sampling(frame);
+ check_gpu_foam_microcoverage(frame);
+ check_gpu_foam_irradiance(frame);
+ check_gpu_foam_environment(frame);
+ check_gpu_water_shore_source(frame);
+#endif
+ check_gpu_water_coastal_surf_core(frame);
+#if defined(__linux__)
+ check_gpu_water_coastal_crest(frame);
+ check_gpu_water_shore_front(frame);
+ check_gpu_water_shore_depth_gate(frame);
+ check_gpu_water_shore_history(frame);
+#endif
+ check_gpu_authored_shore_overlay(frame);
+#if defined(__linux__)
+ check_gpu_foam_material(frame);
+ check_gpu_coastal_material(frame);
+#endif
+ check_gpu_vessel_wave_model(frame);
+ check_gpu_vessel_hull_damping(frame);
+ check_gpu_water_wave_cage(frame);
+#if defined(__linux__)
+ check_gpu_water_hull_normal(frame);
+#endif
+ check_gpu_water_bow_shoulder(frame);
+ check_gpu_water_bow_refinement(frame);
+ check_gpu_fft_vessel_composition(frame);
+ check_gpu_fft_vessel_composition(frame,true);
+ check_gpu_fft_vessel_composition(frame,true,true);
+ check_gpu_wave_model(frame);
+ check_gpu_ocean_wave_model(frame);
+#if defined(__linux__)
+ check_gpu_water_mesh_correction(frame);
+#endif
+ check_gpu_water_optical_model(frame);
+ check_gpu_water_optical_ray_shift(frame);
+#if defined(__linux__)
+ check_gpu_water_refraction_coordinates(frame);
+ check_gpu_water_refraction_footprint(frame);
+#endif
+ check_gpu_water_material_transport(frame);
+ check_gpu_water_hull_distance(frame);
+#if defined(__linux__)
+ check_gpu_water_hull_effects(frame);
+#endif
// 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);
@@ -110,6 +8244,7 @@ int main()
frame->Clear_Back_Buffer(false, true, true, 0xFFFFFFFFu, 0.5f, 7);
CHECK(frame->Read_Back(frame->Back_Buffer(), WIDTH, HEIGHT, pixels));
CHECK(pixels.size() >= 4 && pixels[0] == 0x10 && pixels[2] == 0x40);
+ check_scene_depth(frame);
// The gamma pass, into a target of the test's.
std::vector<uint8_t> picture(WIDTH * HEIGHT * 4);
@@ -120,11 +8255,28 @@ int main()
}
CHECK(frame->Upload_Back_Buffer(picture));
+ // Refraction gets a stable pre-water snapshot, including ordered pending clears/blits.
+ SDL_GPUTexture *background = frame->Water_Background(frame->Back_Buffer_Target());
+ CHECK(background != NULL && background != frame->Back_Buffer());
+ CHECK(frame->Read_Back(background, WIDTH, HEIGHT, pixels));
+ CHECK(pixels == picture);
+ std::vector<uint8_t> replacement(WIDTH * HEIGHT * 4, 0xFF);
+ CHECK(frame->Upload_Back_Buffer(replacement));
+ CHECK(frame->Water_Background(frame->Back_Buffer_Target()) == background);
+ CHECK(frame->Read_Back(background, WIDTH, HEIGHT, pixels));
+ CHECK(pixels == picture); // Later water draws must not refract previously drawn water.
+ frame->Clear_Back_Buffer(true, false, false, 0xFF123456u, 1.0f, 0);
+ CHECK(frame->Water_Background(frame->Back_Buffer_Target()) == background);
+ CHECK(frame->Read_Back(background, WIDTH, HEIGHT, pixels));
+ CHECK(pixels.size() == WIDTH * HEIGHT * 4 && pixels[0] == 0x56 && pixels[1] == 0x34
+ && pixels[2] == 0x12 && pixels[3] == 0xFF);
+ CHECK(frame->Upload_Back_Buffer(picture));
+
SDL_GPUTextureCreateInfo info;
SDL_zero(info);
info.type = SDL_GPU_TEXTURETYPE_2D;
info.format = (SDL_GPUTextureFormat)SdlGpuFrame::Target_Format();
- info.usage = SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;
+ info.usage = SDL_GPU_TEXTUREUSAGE_COLOR_TARGET | SDL_GPU_TEXTUREUSAGE_SAMPLER;
info.width = WIDTH;
info.height = HEIGHT;
info.layer_count_or_depth = 1;
@@ -155,6 +8307,50 @@ int main()
CHECK(frame->Read_Back(target, WIDTH, HEIGHT, pixels));
CHECK(pixels == picture);
+ // Present begins a new frame even when it did not clear the colour buffer.
+ CHECK(frame->Water_Background(frame->Back_Buffer_Target()) == background);
+ CHECK(frame->Read_Back(background, WIDTH, HEIGHT, pixels));
+ CHECK(pixels == picture);
+
+ // The game also draws water into an intermediate colour target, rather than the back buffer.
+ SdlTarget intermediate = { target, frame->Depth_For(WIDTH, HEIGHT), WIDTH, HEIGHT };
+ frame->Set_Target(intermediate);
+ frame->Clear_Back_Buffer(true, false, false, 0xFF102030u, 1.0f, 0);
+ CHECK(frame->Read_Back(frame->Water_Background(intermediate), WIDTH, HEIGHT, pixels));
+ CHECK(pixels.size() == WIDTH * HEIGHT * 4 && pixels[0] == 0x30 && pixels[1] == 0x20
+ && pixels[2] == 0x10);
+ frame->Clear_Back_Buffer(true, false, false, 0xFF445566u, 1.0f, 0);
+ CHECK(frame->Read_Back(frame->Water_Background(intermediate), WIDTH, HEIGHT, pixels));
+ CHECK(pixels.size() == WIDTH * HEIGHT * 4 && pixels[0] == 0x66 && pixels[1] == 0x55
+ && pixels[2] == 0x44);
+ frame->Set_Target(frame->Back_Buffer_Target());
+ CHECK(frame->Read_Back(frame->Water_Background(frame->Back_Buffer_Target()), WIDTH, HEIGHT, pixels));
+ CHECK(pixels == picture);
+
+ // A resize must replace the snapshot and match the new back-buffer dimensions.
+ const SdlTarget before_shore_resize=frame->Back_Buffer_Target();
+ uint64_t before_shore_serial=0,after_shore_serial=123;
+ frame->Ready_Water_Depth(before_shore_resize,before_shore_serial);
+ CHECK(frame->Resize(16, 8));
+ CHECK(frame->Ready_Water_Depth(before_shore_resize,after_shore_serial)==NULL && after_shore_serial==0);
+ after_shore_serial=123;
+ CHECK(frame->Ready_Water_Depth(frame->Back_Buffer_Target(),after_shore_serial)==NULL && after_shore_serial==0);
+ frame->Clear_Back_Buffer(true, true, true, 0xFFAABBCCu, 0.42f, 0);
+ CHECK(frame->Read_Back(frame->Water_Background(frame->Back_Buffer_Target()), 16, 8, pixels));
+ CHECK(pixels.size() == 16 * 8 * 4 && pixels[0] == 0xCC && pixels[1] == 0xBB
+ && pixels[2] == 0xAA && pixels[3] == 0xFF);
+ if (frame->Depth_Usage() & SDL_GPU_TEXTUREUSAGE_SAMPLER) {
+ CHECK(frame->Read_Back(frame->Water_Depth(frame->Back_Buffer_Target()), 16, 8, pixels));
+ CHECK(frame->Ready_Water_Depth(frame->Back_Buffer_Target(),after_shore_serial)!=NULL
+ && after_shore_serial!=0 && after_shore_serial!=before_shore_serial);
+ CHECK(pixels.size() == 16 * 8 * 4 && fabs(depth_at(pixels, 16, 15, 7) - 0.42f) < 0.00001f);
+ DepthObject resized_object(frame);
+ resized_object.Draw(frame->Back_Buffer_Target(), 0.21f);
+ CHECK(frame->Present(NULL));
+ CHECK(frame->Read_Back(frame->Water_Depth(frame->Back_Buffer_Target()), 16, 8, pixels));
+ CHECK(fabs(depth_at(pixels, 16, 8, 4) - 0.21f) < 0.00001f);
+ }
+
SDL_ReleaseGPUTexture(frame->Device(), target);
delete frame;
SDL_Quit();
@@ -164,6 +8360,6 @@ int main()
return 1;
}
printf("sdl_gpu_frame_selfcheck: clear, depth-only clear, gamma (control differs in %u of %u pixels) "
- "and the identity blit all hold\n", control, WIDTH * HEIGHT);
+ "scene colour/depth snapshots, submerged object depth, per-target refresh, resource lifetime, resize and identity blit all hold\n", control, WIDTH * HEIGHT);
return 0;
}
diff --git a/GeneralsMD/Code/Tests/test_sdl_program_cache.cpp b/GeneralsMD/Code/Tests/test_sdl_program_cache.cpp
index 6fa6a62af..ecbb32594 100644
--- a/GeneralsMD/Code/Tests/test_sdl_program_cache.cpp
+++ b/GeneralsMD/Code/Tests/test_sdl_program_cache.cpp
@@ -34,6 +34,8 @@
#include "SdlProgramCache.h"
#include "ffshader.h"
#include "ffvertex.h"
+#include "engineshader.h"
+#include "Platform/EngineShaderName.h"
#include <SDL3/SDL.h>
@@ -70,6 +72,43 @@ static void check_slot_lines()
CHECK(textures[6] == 4 && samplers[6] == 1 && textures[4] == 4 && samplers[4] == 0 && textures[5] == 5 && samplers[5] == 5);
}
+struct WaterShaderNameProbe : PosixDevice9 { using PosixDevice9::Engine_Name_Of; };
+
+static void check_live_water_style_programs(PosixDevice9 *device,SdlProgramCache &cache)
+{
+ const RenderUInt32 tokens[]={0xffff0101u,0x0000ffffu};
+ IDirect3DPixelShader9 *shader=NULL;
+ CHECK(device->CreatePixelShader(tokens,&shader)==D3D_OK);
+ if (!shader) return;
+ CHECK(device->SetPixelShader(shader)==D3D_OK);
+ PixelPipelineDescription pipeline={};
+ const char *names[]={"river water ps.1.1","classic river water ps.1.1",
+ "trapezoid water ps.1.1","classic trapezoid water ps.1.1"};
+ const SdlProgram *programs[4]={};
+ const unsigned built=cache.Programs_Built();
+ for (unsigned pass=0;pass<32;++pass) for (unsigned style=0;style<4;++style) {
+ PosixDevice_Name_Shader(shader,names[style]);
+ IDirect3DPixelShader9 *bound=NULL;
+ CHECK(device->GetPixelShader(&bound)==D3D_OK && bound==shader);
+ const auto engine=EngineShader_From_File(WaterShaderNameProbe::Engine_Name_Of(bound).c_str());
+ if (bound) bound->Release();
+ const SdlProgram &program=cache.Engine_Pixel_Program(engine,pipeline);
+ CHECK(program.Shader!=NULL);
+ if (!pass) programs[style]=&program;
+ CHECK(&program==programs[style]);
+#if defined(__linux__)
+ if (style&1) CHECK(program.SamplerSlots==6 && program.UniformBuffers==1);
+ else CHECK(program.SamplerSlots>6);
+#else
+ CHECK(program.SamplerSlots==6 && program.UniformBuffers==1);
+#endif
+ }
+ CHECK(cache.Programs_Built()==built+4);
+ CHECK(programs[0]->Shader!=programs[1]->Shader && programs[2]->Shader!=programs[3]->Shader);
+ device->SetPixelShader(NULL);shader->Release();
+ printf("sdl_program_cache_selfcheck: 128 water style changes on the same bound shader, four distinct cached GPU programs, no recompiles on return\n");
+}
+
int main()
{
check_slot_lines();
@@ -162,6 +201,8 @@ int main()
const SdlProgram &refused_again = cache.Pixel_Program(combiner);
CHECK(refused_again.Shader == NULL && cache.Programs_Refused() == refused_before + 1);
+ check_live_water_style_programs(device,cache);
+
printf("sdl_program_cache_selfcheck: %s, %u programs built in %.0f ms, %u refused\n",
SDL_GetGPUDeviceDriver(frame->Device()), cache.Programs_Built(), cache.Milliseconds_Compiling(),
cache.Programs_Refused());
diff --git a/GeneralsMD/Code/Tests/test_shader_sdl.cpp b/GeneralsMD/Code/Tests/test_shader_sdl.cpp
index 53f89e737..084ec1954 100644
--- a/GeneralsMD/Code/Tests/test_shader_sdl.cpp
+++ b/GeneralsMD/Code/Tests/test_shader_sdl.cpp
@@ -57,11 +57,25 @@
#include <string>
#include <vector>
+#include <complex>
#include <SDL3/SDL.h>
+#if defined(__linux__)
+#include <spirv_cross_c.h>
+#include "../GameEngineDevice/Source/PosixDevice/Render/SdlConstants.h"
+#endif
#include "sdl3shadercompile.h"
#include "shader_cases.h"
+#include "Platform/WaterBedMaterial.h"
+#include "Platform/WaterOpticalModel.h"
+#include "Platform/WaterHullModel.h"
+#include "Platform/WaterHullVisual.h"
+#include "Platform/WaterSurfaceModel.h"
+#include "Platform/WaterFftSampling.h"
+#include "Platform/WaterFoamEnvironment.h"
+#include "sdl3target.h"
+#include <limits>
namespace {
@@ -195,6 +209,454 @@ bool vertex_layout(const std::string & hlsl, std::vector<SDL_GPUVertexAttribute>
return !attributes.empty();
}
+TEST(runtime_bed_material_is_tileable_deterministic_and_has_distinct_relief)
+{
+ // Sample every texel: wrapping must be identical without a random generator shared with gameplay.
+ // Each channel must carry useful contrast; a flat texture or an accidental repeated channel fails.
+ double sum[4] = {}, squares[4] = {};
+ unsigned different = 0, raised = 0;
+ const int side = 256;
+ for (int y = 0; y < side; ++y) for (int x = 0; x < side; ++x) {
+ const uint32_t value = WaterBedMaterial::Texel(x,y,side);
+ CHECK_EQ(value, WaterBedMaterial::Texel(x+side,y-side,side));
+ const unsigned relief = value & 255, pebbles = (value>>8)&255, sand = (value>>16)&255;
+ different += pebbles != sand;
+ raised += relief > 100;
+ for (unsigned c = 0; c < 4; ++c) {
+ const double b = (value >> (c*8)) & 255;
+ sum[c] += b; squares[c] += b*b;
+ }
+ }
+ CHECK(different > unsigned(side*side/2));
+ CHECK(raised > unsigned(side*side/8) && raised < unsigned(side*side*3/4));
+ for (unsigned c = 0; c < 4; ++c) {
+ const double mean = sum[c]/(side*side);
+ CHECK(mean > 10.0 && mean < 240.0);
+ CHECK(squares[c]/(side*side)-mean*mean > 200.0);
+ }
+}
+
+TEST(classic_water_uses_the_original_program_and_separate_cache_identity)
+{
+ // D3D11 retains the original transcription. Classic on SDL must be exactly that
+ // program after binding retargeting, including fog/alpha-test variants.
+ for (unsigned river=0; river<2; ++river) for (unsigned state=0; state<4; ++state) {
+ const auto original=river?ENGINE_SHADER_WATER_RIVER:ENGINE_SHADER_WATER_TRAPEZOID;
+ const auto classic=river?ENGINE_SHADER_WATER_CLASSIC_RIVER:ENGINE_SHADER_WATER_CLASSIC_TRAPEZOID;
+ PixelPipelineDescription pipeline={};
+ pipeline.FogEnabled=(state&1)!=0;
+ pipeline.AlphaTestEnabled=(state&2)!=0;
+ pipeline.AlphaFunction=FF_CMP_GREATEREQUAL;
+ std::string expected,actual,modern;
+ CHECK(EngineShader_Pixel_Program(original,pipeline,expected,COMBINER_SHADER_TARGET_D3D11));
+ CHECK(SDL3_Shader_Retarget(expected,false));
+ CHECK(EngineShader_Pixel_Program(classic,pipeline,actual,COMBINER_SHADER_TARGET_SDL3_GPU));
+ CHECK(actual==expected);
+ CHECK(EngineShader_Pixel_Program(original,pipeline,modern,COMBINER_SHADER_TARGET_SDL3_GPU));
+#if defined(__linux__)
+ CHECK(actual!=modern);
+#else
+ CHECK(actual==modern);
+#endif
+ CHECK(std::string(EngineShader_Name(original))!=EngineShader_Name(classic));
+ CHECK(EngineShader_From_File(river?"classic river water ps.1.1":"classic trapezoid water ps.1.1")==classic);
+ std::vector<unsigned char> spirv;std::string log,msl;
+ const bool compiled=SDL3_Compile_HLSL_To_SPIRV(actual,false,spirv,log);
+ CHECK(compiled);
+ if (!compiled) { printf("Classic water: %s\n",log.c_str()); continue; }
+ unsigned samplers=0,buffers=0;SDL3_Shader_Slots(spirv,false,samplers,buffers);
+ // The original preamble also declares ShadowMap at t5, retaining six binding slots.
+ CHECK_EQ(samplers,6u);CHECK_EQ(buffers,1u);
+ CHECK(SDL3_Translate_SPIRV_To_MSL(spirv,false,msl,log));
+ const char *validator=getenv("ZH_SPIRV_VAL");
+ if(validator && *validator) CHECK(validate(validator,spirv,log));
+ }
+}
+
+#if defined(__linux__)
+// These programs are selected only by the Linux Modern water runtime.
+TEST(fft_water_vertex_and_pixel_compile_with_separate_texture_bindings)
+{
+ VertexPipelineDescription description=shader_cases_detail::plain_vertex();
+ description.FVF=0x252; // XYZ, normal, diffuse, two texture coordinate sets, the actual water mesh.
+ description.LightingEnabled=false;
+ description.StageCount=4;
+ for(unsigned i=0;i<4;++i) {
+ description.Stages[i].TextureCoordinateIndex=i<2?i:0;
+ description.Stages[i].TextureTransformFlags=FF_TTFF_DISABLE;
+ }
+ std::string vertex;
+ CHECK(VertexShader_Generate(description,VERTEX_SHADER_TARGET_D3D11,vertex));
+ // Hull constants must remain a water-only second slot. The ordinary fixed vertex program
+ // keeps its existing single block even when it has the same water-compatible FVF.
+ {
+ std::string fixed=vertex,log;std::vector<unsigned char> spirv;
+ CHECK(SDL3_Shader_Retarget(fixed,true));
+ const bool compiled=SDL3_Compile_HLSL_To_SPIRV(fixed,true,spirv,log);CHECK(compiled);
+ if(compiled) {
+ unsigned samplers=0,buffers=0;SDL3_Shader_Slots(spirv,true,samplers,buffers);
+ CHECK_EQ(samplers,0u);CHECK_EQ(buffers,1u);
+ }
+ }
+ CHECK(WaterFftSampling::WrapVertex(vertex));
+ CHECK(SDL3_Shader_Retarget(vertex,true));
+ const size_t swap=vertex.find("input.Diffuse = input.Diffuse.bgra");
+ CHECK(swap!=std::string::npos);
+ CHECK(vertex.find("input.Diffuse = input.Diffuse.bgra",swap+1)==std::string::npos);
+ PixelPipelineDescription pipeline={};
+ std::string pixel;
+ CHECK(EngineShader_Pixel_Program(ENGINE_SHADER_WATER_TRAPEZOID,pipeline,pixel,COMBINER_SHADER_TARGET_SDL3_GPU));
+ for(int stage=0;stage<2;++stage) {
+ const bool isVertex=stage==0;
+ std::vector<unsigned char> spirv;std::string log,msl,why;
+ const bool compiled=SDL3_Compile_HLSL_To_SPIRV(isVertex?vertex:pixel,isVertex,spirv,log);
+ if(!compiled) printf("FFT water stage%d: %s\n",stage,log.c_str());
+ CHECK(compiled);if(!compiled) continue;
+ unsigned samplers=0,buffers=0;
+ SDL3_Shader_Slots(spirv,isVertex,samplers,buffers);
+ const char *surfOption=getenv("ZH_WATER_SURF_GPU");
+ const bool surfEnabled=surfOption && strcmp(surfOption,"1")==0;
+ CHECK_EQ(samplers,isVertex?4u:(surfEnabled?16u:15u));CHECK_EQ(buffers,isVertex?2u:(WaterHullVisual::Enabled()?4u:1u));
+ const char *validator=getenv("ZH_SPIRV_VAL");
+ if(validator && *validator) CHECK(validate(validator,spirv,log));
+ CHECK(SDL3_Translate_SPIRV_To_MSL(spirv,isVertex,msl,log));
+ CHECK(slots_kept(msl,samplers,why));
+ }
+}
+
+namespace {
+
+// Restore launch-time shader options after testing each production variant.
+struct SavedShaderOption
+{
+ const char *name;
+ bool present;
+ std::string value;
+
+ explicit SavedShaderOption(const char *key) : name(key), present(getenv(key) != NULL),
+ value(present ? getenv(key) : "") {}
+
+ ~SavedShaderOption()
+ {
+ if (present) setenv(name, value.c_str(), 1);
+ else unsetenv(name);
+ }
+};
+
+struct WaterUniformMember
+{
+ const char *name;
+ size_t offset;
+ size_t size;
+};
+
+// The first three fields are flattened in HLSL, while C++ nests that common prefix.
+#define WATER_COMBINER_MEMBER(name) { #name, offsetof(SdlWaterPixelConstants, Combiner) \
+ + offsetof(SdlPixelConstants, name), sizeof(((SdlPixelConstants *)NULL)->name) }
+#define WATER_UNIFORM_MEMBER(name) { #name, offsetof(SdlWaterPixelConstants, name), \
+ sizeof(((SdlWaterPixelConstants *)NULL)->name) }
+const WaterUniformMember WaterUniformMembers[] = {
+ WATER_COMBINER_MEMBER(TextureFactor),
+ WATER_COMBINER_MEMBER(FogColour),
+ WATER_COMBINER_MEMBER(AlphaReference),
+ WATER_UNIFORM_MEMBER(WorldFromClip),
+ WATER_UNIFORM_MEMBER(CameraPosition),
+ WATER_UNIFORM_MEMBER(SunDirection),
+ WATER_UNIFORM_MEMBER(SunColour),
+ WATER_UNIFORM_MEMBER(Viewport),
+ WATER_UNIFORM_MEMBER(ReflectionArea),
+ WATER_UNIFORM_MEMBER(WaterParameters),
+ WATER_UNIFORM_MEMBER(TerrainParameters),
+ WATER_UNIFORM_MEMBER(SceneParameters),
+ WATER_UNIFORM_MEMBER(OpticalParameters),
+ WATER_UNIFORM_MEMBER(HullParameters),
+ WATER_UNIFORM_MEMBER(HullData),
+ WATER_UNIFORM_MEMBER(FftParameters),
+ WATER_UNIFORM_MEMBER(FoamHistoryArea),
+ WATER_UNIFORM_MEMBER(FoamHistoryParameters),
+ WATER_UNIFORM_MEMBER(ContactHullData),
+ WATER_UNIFORM_MEMBER(FoamFillLights),
+ WATER_UNIFORM_MEMBER(CoastalArea),
+ WATER_UNIFORM_MEMBER(CoastalParams),
+ WATER_UNIFORM_MEMBER(MaterialColor),
+ WATER_UNIFORM_MEMBER(MaterialParameters)
+};
+#undef WATER_COMBINER_MEMBER
+#undef WATER_UNIFORM_MEMBER
+
+void checkCompiledWaterUniformLayout(const std::string &source, bool vertex,
+ const char *blockName, bool visual)
+{
+ std::vector<unsigned char> spirv;
+ std::string log;
+ const bool compiled = SDL3_Compile_HLSL_To_SPIRV(source, vertex, spirv, log);
+ if (!compiled) printf("Water uniform reflection: %s\n", log.c_str());
+ CHECK(compiled);
+ if (!compiled) return;
+
+ struct ReflectionContext {
+ spvc_context context = NULL;
+ ~ReflectionContext() { if (context) spvc_context_destroy(context); }
+ } reflection;
+ const bool created = spvc_context_create(&reflection.context) == SPVC_SUCCESS;
+ CHECK(created);
+ if (!created) return;
+
+ // Copy into aligned words; the production compiler exposes its bytes as unsigned char.
+ CHECK(spirv.size() % sizeof(SpvId) == 0);
+ if (spirv.size() % sizeof(SpvId) != 0) return;
+ std::vector<SpvId> words(spirv.size() / sizeof(SpvId));
+ memcpy(words.data(), spirv.data(), spirv.size());
+ spvc_parsed_ir ir = NULL;
+ spvc_compiler compiler = NULL;
+ spvc_resources resources = NULL;
+ const spvc_reflected_resource *blocks = NULL;
+ size_t blockCount = 0;
+ const bool reflected =
+ spvc_context_parse_spirv(reflection.context, words.data(), words.size(), &ir) == SPVC_SUCCESS
+ && spvc_context_create_compiler(reflection.context, SPVC_BACKEND_NONE, ir,
+ SPVC_CAPTURE_MODE_TAKE_OWNERSHIP, &compiler) == SPVC_SUCCESS
+ && spvc_compiler_create_shader_resources(compiler, &resources) == SPVC_SUCCESS
+ && spvc_resources_get_resource_list_for_type(resources, SPVC_RESOURCE_TYPE_UNIFORM_BUFFER,
+ &blocks, &blockCount) == SPVC_SUCCESS;
+ CHECK(reflected);
+ if (!reflected) return;
+
+ const spvc_reflected_resource *block = NULL;
+ for (size_t i = 0; i < blockCount; ++i)
+ if (strcmp(blocks[i].name, blockName) == 0) block = &blocks[i];
+ CHECK(block != NULL);
+ if (!block) return;
+
+ const spvc_type type = spvc_compiler_get_type_handle(compiler, block->base_type_id);
+ size_t blockSize = 0;
+ CHECK(spvc_compiler_get_declared_struct_size(compiler, type, &blockSize) == SPVC_SUCCESS);
+ CHECK_EQ(blockSize, visual ? sizeof(SdlWaterVisualPixelConstants) : sizeof(SdlWaterPixelConstants));
+ const unsigned commonMembers = sizeof(WaterUniformMembers) / sizeof(WaterUniformMembers[0]);
+ const unsigned memberCount = spvc_type_get_num_member_types(type);
+ CHECK_EQ(memberCount, commonMembers + (visual ? 1u : 0u));
+ for (unsigned i = 0; i < memberCount; ++i) {
+ const WaterUniformMember metadata = { "VisualHullMeta",
+ offsetof(SdlWaterVisualPixelConstants, VisualHullMeta),
+ sizeof(((SdlWaterVisualPixelConstants *)NULL)->VisualHullMeta) };
+ if (i >= commonMembers && (!visual || i != commonMembers)) continue;
+ const WaterUniformMember &expected = i < commonMembers ? WaterUniformMembers[i] : metadata;
+ const char *name = spvc_compiler_get_member_name(compiler, block->base_type_id, i);
+ unsigned offset = 0;
+ size_t size = 0;
+ CHECK(strcmp(name, expected.name) == 0);
+ CHECK(spvc_compiler_type_struct_member_offset(compiler, type, i, &offset) == SPVC_SUCCESS);
+ CHECK(spvc_compiler_get_declared_struct_member_size(compiler, type, i, &size) == SPVC_SUCCESS);
+ CHECK_EQ(size_t(offset), expected.offset);
+ CHECK_EQ(size, expected.size);
+ }
+}
+
+} // namespace
+
+TEST(modern_water_compiled_uniform_layout_matches_every_cpu_upload_field)
+{
+ SavedShaderOption contact("ZH_WATER_HULL_CONTACT"), debug("ZH_WATER_DEBUG");
+ CHECK(unsetenv(debug.name) == 0);
+ for (unsigned visual = 0; visual < 2; ++visual) {
+ CHECK(setenv(contact.name, visual ? "mesh" : "0", 1) == 0);
+ for (const EngineShaderProgram program : {ENGINE_SHADER_WATER_TRAPEZOID, ENGINE_SHADER_WATER_RIVER}) {
+ PixelPipelineDescription pipeline = {};
+ std::string source;
+ const bool generated = EngineShader_Pixel_Program(program, pipeline, source,
+ COMBINER_SHADER_TARGET_SDL3_GPU);
+ CHECK(generated);
+ if (generated) checkCompiledWaterUniformLayout(source, false, "CombinerConstants", visual != 0);
+ }
+ }
+
+ VertexPipelineDescription description = shader_cases_detail::plain_vertex();
+ description.FVF = 0x252;
+ description.LightingEnabled = false;
+ description.StageCount = 4;
+ for (unsigned i = 0; i < 4; ++i) {
+ description.Stages[i].TextureCoordinateIndex = i < 2 ? i : 0;
+ description.Stages[i].TextureTransformFlags = FF_TTFF_DISABLE;
+ }
+ std::string vertex;
+ const bool generated = VertexShader_Generate(description, VERTEX_SHADER_TARGET_D3D11, vertex)
+ && WaterFftSampling::WrapVertex(vertex) && SDL3_Shader_Retarget(vertex, true);
+ CHECK(generated);
+ if (generated) checkCompiledWaterUniformLayout(vertex, true, "WaterVertexParameters", false);
+}
+
+#endif // __linux__
+
+TEST(fft_spectral_power_bands_partition_and_join_smoothly)
+{
+ using namespace WaterFftSpectrum;
+ // Requested world-space band boundaries. Assertions concern conservation and
+ // continuity, not copied ramp math.
+ const double joins[]={24.0,40.0,128.0,256.0,1024.0,1792.0};
+ for(unsigned i=1;i<=20000;++i) {
+ const double wavelength=2000.0*i/20000;
+ double sum=0;
+ for(unsigned c=0;c<Cascades;++c) {
+ const double power=BandPower(c,wavelength);
+ CHECK(std::isfinite(power) && power>=0 && power<=1);
+ sum+=power;
+ }
+ if(wavelength<=1024.0) CHECK_NEAR(sum,1,1e-12);
+ else CHECK(sum>=0 && sum<=1+1e-12);
+ if(wavelength>=1792.0) CHECK(sum==0);
+ }
+ for(double join:joins) for(unsigned c=0;c<Cascades;++c) {
+ const double step=1e-5,mid=BandPower(c,join);
+ const double left=BandPower(c,join-step),right=BandPower(c,join+step);
+ CHECK(std::abs(left-right)<1e-7);
+ // Each adjoining constant segment has derivative zero. Check both sides,
+ // so a merely continuous triangular fade cannot satisfy this contract.
+ CHECK(std::abs((mid-left)/step)<1e-5);
+ CHECK(std::abs((right-mid)/step)<1e-5);
+ }
+ // Direction of the crossfades and no gap or duplicate full-strength band.
+ for(unsigned i=0;i<100;++i) {
+ const double fine=24.0+16.0*i/100,medium=128.0+128.0*i/100,longer=1024.0+768.0*i/100;
+ CHECK(BandPower(2,fine+.16)<=BandPower(2,fine));
+ CHECK(BandPower(1,fine+.16)>=BandPower(1,fine));
+ CHECK(BandPower(0,medium+1.28)>=BandPower(0,medium));
+ CHECK(BandPower(1,medium+1.28)<=BandPower(1,medium));
+ CHECK(BandPower(0,longer+7.68)<=BandPower(0,longer));
+ }
+ CHECK(BandPower(0,180.0)>0 && BandPower(1,180.0)>0);
+ CHECK(BandPower(1,32.0)>0 && BandPower(2,32.0)>0);
+ CHECK(BandPower(0,32.0)==0 && BandPower(2,180.0)==0);
+}
+
+TEST(fft_generated_spectrum_has_normalized_separated_directional_energy)
+{
+ using namespace WaterFftSpectrum;
+ const std::vector<float> initial=InitialSpectrum(),again=InitialSpectrum();
+ CHECK(initial==again); // repeated generation must not consume gameplay RNG/state
+ const unsigned n=Resolution,texels=n*n;
+ CHECK_EQ(initial.size(),size_t(texels*Cascades*4));
+ if(initial.size()!=texels*Cascades*4) return;
+ double energy[Cascades]={},slope[Cascades]={},broad[Cascades]={};
+ double directionCos[Cascades]={},directionSin[Cascades]={};
+ bool finite=true,zeroSpecial=true,support=true,oneWay=true,paired=true;
+ unsigned active[Cascades]={};
+ const double axis=std::atan2(WindDirectionY,WindDirectionX);
+ for(unsigned c=0;c<Cascades;++c) for(unsigned y=0;y<n;++y) for(unsigned x=0;x<n;++x) {
+ const unsigned opposite=((n-y)%n)*n+(n-x)%n;
+ const float *h=&initial[(c*texels+y*n+x)*4],*other=&initial[(c*texels+opposite)*4];
+ double power=0;
+ for(unsigned j=0;j<4;++j) {finite=finite && std::isfinite(h[j]);power+=double(h[j])*h[j];}
+ if(x==0 || y==0 || (x==n/2 && y==n/2)) zeroSpecial=zeroSpecial && power==0;
+ const double forward=double(h[0])*h[0]+double(h[1])*h[1];
+ const double backward=double(h[2])*h[2]+double(h[3])*h[3];
+ oneWay=oneWay && (forward==0 || backward==0);
+ // h0(k) == conjugate(packed negative branch at -k), exactly after float stores.
+ paired=paired && h[0]==other[2] && h[1]==-other[3] && h[2]==other[0] && h[3]==-other[1];
+ const double kx=2*Pi*(int(x)-int(n/2))/Sizes[c],ky=2*Pi*(int(y)-int(n/2))/Sizes[c];
+ const double k2=kx*kx+ky*ky;
+ if(k2==0) continue;
+ const double wavelength=2*Pi*WorldScale/std::sqrt(k2);
+ // Independent generated-support checks: a broken generator cannot pass
+ // merely because it and the BandPower function agree on the same mistake.
+ const bool outside=(c==0 && (wavelength<=128.0 || wavelength>=1792.0)) ||
+ (c==1 && (wavelength<=24.0 || wavelength>=256.0)) || (c==2 && wavelength>=40.0);
+ if(outside) support=support && power==0;
+ if(power==0) continue;
+ ++active[c];energy[c]+=power;slope[c]+=power*k2;
+ if(wavelength>512) broad[c]+=power;
+ const double angle=std::atan2(ky,kx)-axis;
+ directionCos[c]+=power*std::cos(2*angle);directionSin[c]+=power*std::sin(2*angle);
+ }
+ CHECK(finite && zeroSpecial && support && oneWay && paired);
+ double totalSlope=0;
+ const auto &unresolved=WaterFftFiltering::SpectrumVariance();
+ for(unsigned c=0;c<Cascades;++c) {
+ CHECK(active[c]>100);
+ CHECK(std::abs(std::sqrt(energy[c])*WorldScale-HeightRms[c])<HeightRms[c]*2e-7);
+ // For angular power |cos(theta)|^p, the continuous axial second moment
+ // is p/(p+2). This independent integral tests actual generated direction,
+ // allowing finite seeded-grid variation without pinning exact coefficients.
+ const double expectedMoment=DirectionPowers[c]/(DirectionPowers[c]+2);
+ CHECK(std::abs(directionCos[c]/energy[c]-expectedMoment)<.08);
+ CHECK(std::abs(directionSin[c]/energy[c])<.08);
+ // Final mip averages the entire periodic field. With zero DC, all slope
+ // power is unresolved: a stale M2 spectrum table must not silently survive.
+ CHECK(std::abs(unresolved[Phases][c]-slope[c])<1e-10*(1+slope[c]));
+ totalSlope+=slope[c];
+ }
+ // Broad swell must actually exist, while medium/fine cannot counterfeit it.
+ CHECK(broad[0]/energy[0]>.25 && broad[0]/energy[0]<.55);
+ CHECK(broad[1]==0 && broad[2]==0);
+ CHECK(energy[0]>3*energy[1] && energy[1]>10*energy[2]);
+ // Guard against recovering old height by amplifying the high-frequency slope.
+ CHECK(std::sqrt(totalSlope)<.15 && std::sqrt(slope[2])<.10);
+ printf(" FFT bands: height RMS %.8g/%.8g/%.8g; slope RMS %.8g/%.8g/%.8g; long power >512 %.3f%%\n",
+ std::sqrt(energy[0])*WorldScale,std::sqrt(energy[1])*WorldScale,std::sqrt(energy[2])*WorldScale,
+ std::sqrt(slope[0]),std::sqrt(slope[1]),std::sqrt(slope[2]),100*broad[0]/energy[0]);
+}
+
+TEST(fft_generated_spectrum_preserves_real_field_and_energy_over_time)
+{
+ using namespace WaterFftSpectrum;using Complex=std::complex<double>;
+ const auto initial=InitialSpectrum();const unsigned n=Resolution,texels=n*n;
+ const double times[]={0.0,2.75,61.0};
+ for(unsigned c=0;c<Cascades;++c) for(double seconds:times) {
+ double packedEnergy=0,evolvedEnergy=0,maxConjugateError=0;
+ for(unsigned y=0;y<n;++y) for(unsigned x=0;x<n;++x) {
+ const float *h=&initial[(c*texels+y*n+x)*4];
+ const float *other=&initial[(c*texels+((n-y)%n)*n+(n-x)%n)*4];
+ const double kx=2*Pi*(int(x)-int(n/2))/Sizes[c],ky=2*Pi*(int(y)-int(n/2))/Sizes[c];
+ // Independently evolve the actual packed coefficients with the retained
+ // dispersion. Conjugate symmetry gives a real spatial inverse transform.
+ const Complex phase=std::polar(1.0,std::sqrt(9.81*std::hypot(kx,ky))*seconds);
+ const Complex forward(h[0],h[1]),backward(h[2],h[3]);
+ const Complex evolved=forward*phase+backward*std::conj(phase);
+ const Complex opposite=Complex(other[0],other[1])*phase+Complex(other[2],other[3])*std::conj(phase);
+ maxConjugateError=(std::max)(maxConjugateError,std::abs(evolved-std::conj(opposite)));
+ packedEnergy+=std::norm(forward)+std::norm(backward);evolvedEnergy+=std::norm(evolved);
+ }
+ CHECK(maxConjugateError<1e-12);
+ CHECK(std::abs(packedEnergy-evolvedEnergy)<1e-12*(1+packedEnergy));
+ CHECK(std::abs(std::sqrt(evolvedEnergy)*WorldScale-HeightRms[c])<HeightRms[c]*2e-7);
+ }
+}
+
+TEST(fft_filter_variance_matches_independent_discrete_box_averages)
+{
+ using namespace WaterFftSpectrum;
+ const int modes[][2]={{1,0},{3,2},{19,-11},{83,47}};
+ double largest=0;
+ for(unsigned cascade=0;cascade<Cascades;++cascade) for(const auto &mode:modes) {
+ std::vector<float> input(Resolution*Resolution*Cascades*4,0);
+ const unsigned x=mode[0]+Resolution/2,y=mode[1]+Resolution/2;
+ float *v=&input[((cascade*Resolution+y)*Resolution+x)*4];v[0]=.75f;v[1]=.25f;
+ const auto table=WaterFftFiltering::UnresolvedSlopeVariance(input);
+ // Explicitly average complex samples of one Fourier mode over the texel box.
+ // This oracle does not use the production sine-ratio transfer function.
+ const double kx=2*Pi*mode[0]/Sizes[cascade],ky=2*Pi*mode[1]/Sizes[cascade];
+ const double power=(.75*.75+.25*.25)*(kx*kx+ky*ky);
+ for(unsigned level=0;level<WaterFftFiltering::Levels;++level) {
+ const unsigned width=1u<<level;std::complex<double> ax=0,ay=0;
+ for(unsigned i=0;i<width;++i) {
+ ax+=std::polar(1.0,2*Pi*mode[0]*i/Resolution);
+ ay+=std::polar(1.0,2*Pi*mode[1]*i/Resolution);
+ }
+ const double retained=std::norm(ax/double(width))*std::norm(ay/double(width));
+ const double expected=power*(1-retained),error=std::abs(table[level][cascade]-expected);
+ largest=(std::max)(largest,error);CHECK(error<1e-10*(1+power));
+ for(unsigned c=0;c<Cascades;++c) if(c!=cascade) CHECK(table[level][c]==0);
+ }
+ }
+ const auto &table=WaterFftFiltering::SpectrumVariance();
+ CHECK(&table==&WaterFftFiltering::SpectrumVariance());
+ for(unsigned c=0;c<Cascades;++c) {
+ CHECK(table[0][c]==0 && table[8][c]>0);
+ for(unsigned l=1;l<WaterFftFiltering::Levels;++l)
+ CHECK(std::isfinite(table[l][c]) && table[l][c]>=table[l-1][c]-1e-12 && table[l][c]<=table[8][c]+1e-12);
+ }
+ printf(" FFT unresolved slope power: independent discrete box error %.9g; per-cascade zero-LOD and bounded mip hierarchy checked\n",largest);
+}
+
TEST(every_generated_program_reaches_sdl3_gpu)
{
const char * spirv_val = getenv("ZH_SPIRV_VAL");
@@ -392,3 +854,669 @@ TEST(every_vertex_program_links_with_every_pixel_program_it_can_meet)
SDL_Quit();
#endif
}
+
+namespace {
+float opticalChannel(const WaterOpticalModel::RGB &rgb,int channel)
+{
+ return channel==0?rgb.r:(channel==1?rgb.g:rgb.b);
+}
+float displayedBed(float bed,float scatter,float transmission)
+{
+ return std::pow(std::pow(bed,2.2f)*transmission+scatter*(1.0f-transmission),1.0f/2.2f);
+}
+float displayedBedContrast(float transmission,float scatter)
+{
+ return (displayedBed(0.65f,scatter,transmission)-displayedBed(0.25f,scatter,transmission))/0.4f;
+}
+}
+
+TEST(water_optics_shores_and_unclassified_pools_keep_existing_shallow_transmission)
+{
+ using namespace WaterOpticalModel;
+ for (float river:{0.0f,0.25f,0.5f,1.0f}) for (float distance:{0.0f,0.25f,2.0f,5.0f,10.0f,20.0f,80.0f}) {
+ const float materialPath=distance*(2.4f+(1.0f-2.4f)*river);
+ const RGB original={std::exp(-materialPath*0.065f),std::exp(-materialPath*0.026f),std::exp(-materialPath*0.019f)};
+ for (float opacity:{0.0f,0.5f,0.75f,1.0f}) for (float depth:{0.25f,2.7f,3.0f,10.0f}) {
+ const RGB shore=Transmission(distance,river,0.0f,depth,opacity);
+ CHECK(memcmp(&shore,&original,sizeof(RGB))==0);
+ const RGB unauthored=Transmission(distance,river,1.0f,depth,0.0f);
+ CHECK(memcmp(&unauthored,&original,sizeof(RGB))==0);
+ }
+ }
+ CHECK(std::abs(OffshoreExtinction(2.7f,0.75f)-(-std::log(0.25f)/2.7f))<0.000001f);
+ CHECK(std::abs(OffshoreExtinction(3.0f,1.0f)-(-std::log(0.01f)/3.0f))<0.000001f);
+ const RGB zero=Transmission(0,0,1,0,1);
+ CHECK(zero.r==1 && zero.g==1 && zero.b==1);
+ CHECK(std::abs(displayedBed(0.43f,0.028f,zero.g)-0.43f)<0.000001f);
+}
+
+TEST(water_optics_authored_extinction_uses_unscaled_physical_ray_length)
+{
+ using namespace WaterOpticalModel;
+ for (float distance:{0.25f,1.0f,3.2f,10.0f,40.0f}) for (float river:{0.0f,0.5f,1.0f}) {
+ const RGB base=Transmission(distance,river,0,2.7f,0.75f);
+ const RGB offshore=Transmission(distance,river,1,2.7f,0.75f);
+ const RGB halfway=Transmission(distance,river,0.5f,2.7f,0.75f);
+ const float authored=std::exp(-distance*OffshoreExtinction(2.7f,0.75f));
+ for (int channel=0;channel<3;++channel) {
+ const float a=opticalChannel(base,channel),b=opticalChannel(offshore,channel),m=opticalChannel(halfway,channel);
+ CHECK(std::abs(b-a*authored)<0.000001f);
+ CHECK(m>=b && m<=a);
+ CHECK(std::abs(m*m-a*b)<0.000001f); // Optical thickness interpolates, not display colour.
+ }
+ }
+}
+
+TEST(water_optics_transmission_is_finite_bounded_and_monotone)
+{
+ using namespace WaterOpticalModel;
+ const float infinity=std::numeric_limits<float>::infinity(),nan=std::numeric_limits<float>::quiet_NaN();
+ const float inputs[]={-infinity,nan,-3,0,0.1f,0.5f,1,3,100,infinity};
+ for (float distance:inputs) for (float river:inputs) for (float offshore:inputs)
+ for (float depth:inputs) for (float opacity:inputs) {
+ const RGB t=Transmission(distance,river,offshore,depth,opacity);
+ CHECK(std::isfinite(t.r) && std::isfinite(t.g) && std::isfinite(t.b));
+ CHECK(t.r>=0 && t.r<=1 && t.g>=0 && t.g<=1 && t.b>=0 && t.b<=1);
+ }
+ for (float river:{0.0f,1.0f}) for (float offshore:{0.0f,0.5f,1.0f}) {
+ RGB previous=Transmission(0,river,offshore,2.7f,0.75f);
+ for (int i=1;i<=1000;++i) {
+ const RGB current=Transmission(i*0.5f,river,offshore,2.7f,0.75f);
+ CHECK(current.r<=previous.r && current.g<=previous.g && current.b<=previous.b);
+ previous=current;
+ }
+ }
+}
+
+TEST(water_optics_deep_water_converges_without_a_180_unit_visibility_plateau)
+{
+ using namespace WaterOpticalModel;
+ for (float river:{0.0f,1.0f}) {
+ const RGB at180=Transmission(180,river,0,3,0),at360=Transmission(360,river,0,3,0),deep=Transmission(100000,river,0,3,0);
+ CHECK(at360.r<at180.r && at360.g<at180.g && at360.b<at180.b);
+ CHECK(deep.r<1e-30f && deep.g<1e-30f && deep.b<1e-30f);
+ CHECK(std::abs(displayedBed(0.65f,0.041f,deep.b)-std::pow(0.041f,1.0f/2.2f))<0.000001f);
+ }
+ for (float distance:{0.0f,1.0f,10.0f,100.0f}) {
+ const RGB t=Transmission(distance,0,1,3,1);
+ // A bed already equal to the scattering radiance must not brighten/darken with distance.
+ const float scatter=0.028f,displayScatter=std::pow(scatter,1.0f/2.2f);
+ CHECK(std::abs(displayedBed(displayScatter,scatter,t.g)-displayScatter)<0.000001f);
+ }
+}
+
+TEST(water_optics_authored_offshore_examples_hide_bed_in_display_space)
+{
+ using namespace WaterOpticalModel;
+ const float scatter[3]={0.002f,0.028f,0.041f};
+ // Optical interpretations of the maps' existing artistic settings: mission water at Z=7
+ // has a ~10-unit ray, opacity .75 at reference depth 2.7; shell water at Z=21 has ~2.25
+ // units of vertical depth and a ~3.2-unit ray, opacity 1 at reference depth 3.
+ const float scenarios[][3]={{10.0f,0.75f,2.7f},{3.2f,1.0f,3.0f}};
+ for (const auto &scenario:scenarios) {
+ const RGB shore=Transmission(scenario[0],0,0,scenario[2],scenario[1]);
+ const RGB offshore=Transmission(scenario[0],0,1,scenario[2],scenario[1]);
+ for (int channel=0;channel<3;++channel) {
+ CHECK(displayedBedContrast(opticalChannel(offshore,channel),scatter[channel])<0.05f);
+ CHECK(displayedBedContrast(opticalChannel(offshore,channel),scatter[channel])<
+ displayedBedContrast(opticalChannel(shore,channel),scatter[channel]));
+ }
+ }
+}
+
+TEST(water_optical_ray_correction_preserves_camera_rays_and_zero_offshore)
+{
+ using namespace WaterOpticalModel;
+ for (float vz:{.25f,.5f,.8f,1.0f}) for (float delta:{-3.0f,-.7f,0.0f,.4f,2.0f})
+ for (float offshore:{0.0f,.25f,.5f,1.0f}) {
+ const float vx=std::sqrt(1-vz*vz),shift=RayShift(delta,vz,offshore,7,100,100);
+ const float x=5+vx*shift,z=12+vz*shift;
+ // Independent intersection with a horizontal analytic surface: sufficient room to both
+ // the camera and the scene means the new point must land exactly at its blended height.
+ CHECK(std::abs(z-(12+delta*offshore))<0.000003f);
+ CHECK(std::abs((x-5)*vz-(z-12)*vx)<0.000003f); // parallel to the same camera ray
+ const float sceneX=5-vx*100,sceneZ=12-vz*100;
+ const float distance=std::sqrt((x-sceneX)*(x-sceneX)+(z-sceneZ)*(z-sceneZ));
+ CHECK(std::abs(distance-(100+shift))<0.00003f);
+ if (offshore==0) {
+ CHECK(shift==0 && x==5 && z==12);
+ const RGB before=Transmission(100,0,0,3,.75f),after=Transmission(100+shift,0,0,3,.75f);
+ CHECK(before.r==after.r && before.g==after.g && before.b==after.b);
+ }
+ }
+}
+
+TEST(water_optical_ray_correction_cannot_cross_scene_hits_or_the_camera)
+{
+ using namespace WaterOpticalModel;
+ for (float delta:{-1000000.0f,-100.0f,-1.0f,0.0f,1.0f,100.0f,1000000.0f})
+ for (float vz:{-.8f,0.0f,.001f,.05f,.2f,.8f,1.0f})
+ for (float offshore:{0.0f,.25f,.5f,1.0f})
+ for (float hit:{0.0f,.01f,.08f,.2f,2.0f,50.0f})
+ for (float camera:{0.0f,.04f,.08f,.3f,12.0f,100.0f}) {
+ const float shift=RayShift(delta,vz,offshore,7,hit,camera);
+ CHECK(std::isfinite(shift));
+ CHECK(std::abs(shift)<=70.00001f); // 2*7 height / .2 grazing denominator
+ CHECK(hit+shift>=std::min(hit,RaySurfaceMargin)-0.00001f);
+ CHECK(camera-shift>=std::min(camera,RaySurfaceMargin)-0.00001f);
+ if (vz<=0 || offshore==0) CHECK(shift==0);
+ }
+ const float nan=std::numeric_limits<float>::quiet_NaN(),inf=std::numeric_limits<float>::infinity();
+ for (float invalid:{nan,inf,-inf}) {
+ CHECK(RayShift(invalid,.8f,1,7,10,100)==0);
+ CHECK(RayShift(1,invalid,1,7,10,100)==0);
+ CHECK(std::isfinite(RayShift(-1,.8f,1,7,invalid,100)));
+ CHECK(std::isfinite(RayShift(1,.8f,1,7,10,invalid)));
+ CHECK(std::isfinite(RayShift(1,.8f,invalid,7,10,100)));
+ CHECK(std::isfinite(RayShift(1,.8f,1,invalid,10,100)));
+ }
+}
+
+TEST(water_optical_ray_correction_keeps_submerged_objects_clearer_than_the_bed)
+{
+ using namespace WaterOpticalModel;
+ // An object lies .25 along the rendered camera ray and the terrain lies 4 units away. The
+ // analytic trough would move the surface 2.5 units along that ray, behind the close object.
+ const float objectShift=RayShift(-2,.8f,1,7,.25f,100),bedShift=RayShift(-2,.8f,1,7,4,100);
+ const float objectGap=.25f+objectShift,bedGap=4+bedShift;
+ CHECK(std::abs(objectGap-.08f)<0.000001f && std::abs(bedGap-1.5f)<0.000001f);
+ const RGB object=Transmission(objectGap,0,1,3,.75f),bed=Transmission(bedGap,0,1,3,.75f);
+ CHECK(object.r>bed.r && object.g>bed.g && object.b>bed.b);
+ // Armed control reproduces the old bug: a length() taken after passing the hit becomes
+ // positive again and makes the near object *darker* than the farther bed.
+ const RGB crossed=Transmission(std::abs(.25f-2.5f),0,1,3,.75f);
+ CHECK(crossed.r<bed.r && crossed.g<bed.g && crossed.b<bed.b);
+ CHECK(RayShift(-2,.8f,1,7,.03f,100)==0); // preserve a hit closer than the safety margin
+ CHECK(std::abs(RayShift(2,.8f,1,7,10,.3f)-.22f)<0.000001f);
+}
+
+TEST(water_optics_shared_hlsl_compiles_and_translates_without_gpu_execution)
+{
+ std::string hlsl=WaterOpticalModel::GetHlslSource();
+ hlsl+="float4 main(float4 position : SV_Position) : SV_Target { float shift=WaterOpticalRayShift(position.x,.8,position.z,7,10,100); return float4(WaterOpticalTransmission(abs(position.x), position.y, position.z, 2.7, 0.75), shift); }\n";
+ std::vector<unsigned char> spirv;
+ std::string log,msl;
+ const bool compiled=SDL3_Compile_HLSL_To_SPIRV(hlsl,false,spirv,log);
+ if (!compiled) printf(" water optics HLSL compilation failed: %s\n",log.c_str());
+ CHECK(compiled);
+ if (!compiled) return;
+ const char *spirvVal=getenv("ZH_SPIRV_VAL");
+ if (spirvVal && *spirvVal) {
+ std::string output;
+ const bool valid=validate(spirvVal,spirv,output);
+ if (!valid) printf(" water optics SPIR-V validation failed: %s\n",output.c_str());
+ CHECK(valid);
+ }
+ const bool translated=SDL3_Translate_SPIRV_To_MSL(spirv,false,msl,log);
+ if (!translated) printf(" water optics MSL translation failed: %s\n",log.c_str());
+ CHECK(translated);
+}
+
+TEST(water_source_zero_path_keeps_transmitted_scene_independent_of_face_lighting)
+{
+ using namespace WaterOpticalModel;
+ const RGB scene={.17f,.38f,.61f};
+ unsigned oldControls=0;
+ for(float river:{0.0f,.25f,1.0f})for(float rawOcean:{0.0f,.5f,1.0f})
+ for(float daylight:{0.0f,.5f,1.0f})for(float face:{0.0f,.25f,1.0f})for(float caustic:{.82f,1.0f,1.55f}) {
+ const float offshore=rawOcean*(1-river);
+ const RGB source=ScatteringSource(river,offshore,daylight,face);
+ const RGB body=Body(scene,Transmission(0,river,offshore,3,.75f),source,caustic,1);
+ for(int c=0;c<3;++c)CHECK(std::abs(opticalChannel(body,c)-opticalChannel(scene,c)*caustic)<1e-6f);
+ // The pre-fix face multiplier also scales scene at T=1; an offshore face must expose it.
+ if(offshore==1 && face==0) {
+ const float oldRed=scene.r*caustic*.4f;
+ CHECK(std::abs(body.r-oldRed)>.05f);++oldControls;
+ }
+ }
+ CHECK(oldControls>0);
+}
+
+TEST(water_source_face_lighting_does_not_change_transmitted_object_contrast)
+{
+ using namespace WaterOpticalModel;
+ const RGB a={.72f,.51f,.29f},b={.12f,.08f,.04f};
+ for(float path:{.1f,1.0f,4.0f,12.0f})for(float offshore:{0.0f,.4f,1.0f})
+ for(float caustic:{.82f,1.0f,1.55f}) {
+ const RGB t=Transmission(path,0,offshore,3,.75f);
+ RGB contrasts[2];
+ for(int f=0;f<2;++f) {
+ const RGB source=ScatteringSource(0,offshore,1,float(f));
+ const RGB ba=Body(a,t,source,caustic,1),bb=Body(b,t,source,caustic,1);
+ contrasts[f]={ba.r-bb.r,ba.g-bb.g,ba.b-bb.b};
+ for(int c=0;c<3;++c) {
+ const float expected=(opticalChannel(a,c)-opticalChannel(b,c))*opticalChannel(t,c)*caustic;
+ CHECK(std::abs(opticalChannel(contrasts[f],c)-expected)<2e-6f);
+ }
+ }
+ CHECK(std::abs(contrasts[0].r-contrasts[1].r)<2e-6f);
+ CHECK(std::abs(contrasts[0].g-contrasts[1].g)<2e-6f);
+ CHECK(std::abs(contrasts[0].b-contrasts[1].b)<2e-6f);
+ }
+}
+
+TEST(water_source_deep_limit_fallback_and_radiance_equilibrium)
+{
+ using namespace WaterOpticalModel;
+ const RGB scene={.71f,.31f,.13f};
+ for(float river:{0.0f,1.0f})for(float ocean:{0.0f,.5f,1.0f})for(float face:{0.0f,.4f,1.0f}) {
+ const float offshore=ocean*(1-river);
+ const RGB source=ScatteringSource(river,offshore,.7f,face);
+ for(float path:{0.0f,.1f,3.0f,20.0f,100000.0f}) {
+ const RGB t=Transmission(path,river,offshore,3,.75f);
+ const RGB equilibrium=Body(source,t,source,1,1),fallback=Body(scene,t,source,1.5f,0);
+ for(int c=0;c<3;++c) {
+ CHECK(std::abs(opticalChannel(equilibrium,c)-opticalChannel(source,c))<1e-7f);
+ CHECK(std::abs(opticalChannel(fallback,c)-opticalChannel(source,c))<1e-7f);
+ }
+ if(path>1000) {
+ const RGB deep=Body(scene,t,source,1.5f,1);
+ for(int c=0;c<3;++c)CHECK(std::abs(opticalChannel(deep,c)-opticalChannel(source,c))<1e-7f);
+ }
+ }
+ }
+}
+
+TEST(water_source_context_is_continuous_and_does_not_gate_offshore_twice)
+{
+ using namespace WaterOpticalModel;
+ const RGB clear=MaterialSource(0,0),ocean=MaterialSource(0,1),river=MaterialSource(1,0);
+ // Migration checks pin existing art endpoints; they intentionally do not derive expected
+ // values from the new preset constants, which would allow an accidental retint to self-pass.
+ CHECK(std::abs(clear.r-.002f)<1e-8f && std::abs(clear.g-.028f)<1e-8f && std::abs(clear.b-.041f)<1e-8f);
+ CHECK(std::abs(ocean.r-.002f)<1e-8f && std::abs(ocean.g-.035f)<1e-8f && std::abs(ocean.b-.075f)<1e-8f);
+ CHECK(river.r==clear.r && river.g==clear.g && river.b==clear.b);
+ RGB previous=clear;
+ for(int i=1;i<=100;++i) {
+ const float offshore=i/100.0f;const RGB current=MaterialSource(0,offshore);
+ for(int c=0;c<3;++c) {
+ const float lo=opticalChannel(clear,c),hi=opticalChannel(ocean,c),value=opticalChannel(current,c);
+ CHECK(value>=std::min(lo,hi)-1e-8f && value<=std::max(lo,hi)+1e-8f);
+ CHECK(std::abs(value-opticalChannel(previous,c))<=std::abs(hi-lo)/100+1e-7f);
+ }
+ previous=current;
+ }
+ // Valid continuous context: river .4 + effective offshore .6 = 1. River currently shares
+ // the clear source, so changing the river share cannot shrink this already-gated ocean share.
+ const RGB partial=MaterialSource(.4f,.6f),ungated=MaterialSource(0,.6f);
+ CHECK(std::abs(partial.r-ungated.r)<1e-8f && std::abs(partial.g-ungated.g)<1e-8f && std::abs(partial.b-ungated.b)<1e-8f);
+ const RGB capped=MaterialSource(1,1);CHECK(capped.r==river.r && capped.g==river.g && capped.b==river.b);
+ // Shared source colour does not erase the existing river/standing-water transmission distinction.
+ const RGB riverT=Transmission(5,1,0,3,.75f),poolT=Transmission(5,0,0,3,.75f);
+ CHECK(riverT.r>poolT.r && riverT.g>poolT.g && riverT.b>poolT.b);
+}
+
+TEST(water_hull_slices_actual_triangles_at_water_not_the_deck_or_collision_box)
+{
+ using namespace WaterHullModel;
+ // An asymmetric, tapered hull widens from 10 below water to 30 at its elevated deck.
+ // At z=0 its waterline must be exactly half way: width20, not the deck/collision width30.
+ const Point outline[]={{-40,-10},{20,-10},{40,0},{20,10},{-40,10}};
+ std::vector<Point> intersections;
+ for(unsigned i=0;i<5;++i) {
+ const Point a=outline[i],b=outline[(i+1)%5];
+ const Point3 lowA={a.x,a.y,-5},lowB={b.x,b.y,-5};
+ const Point3 highA={a.x,a.y*3,5},highB={b.x,b.y*3,5};
+ CHECK(SliceTriangle(lowA,lowB,highB,intersections));
+ CHECK(SliceTriangle(lowA,highB,highA,intersections));
+ }
+ const Polygon hull=BuildPolygon(intersections);
+ // The slanted bow quad is not planar: its authored triangle diagonal intersects at
+ // (30,15), outside the straight line joining (40,0) and (20,20). Keep that real mesh kink.
+ CHECK(hull.count==6 && hull.error<0.0001f);
+ CHECK(std::abs(SignedDistance({30,15},hull))<0.0001f);
+ CHECK(std::abs(SignedDistance({0,20},hull))<0.0001f);
+ CHECK(std::abs(SignedDistance({0,25},hull)-5)<0.0001f);
+ CHECK(std::abs(SignedDistance({0,0},hull)+20)<0.0001f);
+ CHECK(SignedDistance({38,10},hull)>0); // pointed bow, not a rectangular collision box
+ CHECK(SignedDistance({-38,10},hull)<0); // broad stern retained
+ const Polygon wrongDeck=BuildPolygon({{-40,-30},{20,-30},{40,0},{20,30},{-40,30}});
+ CHECK(SignedDistance({0,25},wrongDeck)<0); // armed deck-footprint control
+ std::vector<Point> dry;
+ CHECK(SliceTriangle({0,0,1},{1,0,2},{0,1,3},dry));CHECK(dry.empty());
+ CHECK(SliceTriangle({0,0,0},{10,0,0},{0,10,0},dry));CHECK(BuildPolygon(dry).count==3);
+}
+
+TEST(water_hull_contours_have_bounded_cost_and_report_simplification_error)
+{
+ using namespace WaterHullModel;
+ std::vector<Point> ellipse;
+ for(unsigned i=0;i<256;++i) {
+ const float angle=float(i)*6.28318530718f/256;
+ ellipse.push_back({283.0f*std::cos(angle),36.0f*std::sin(angle)});
+ }
+ const Polygon reduced=BuildPolygon(ellipse);
+ CHECK(reduced.count==MaxVertices && reduced.error>0 && reduced.error<6);
+ float independentlyMeasured=0;
+ for(Point p:ellipse) independentlyMeasured=std::max(independentlyMeasured,SignedDistance(p,reduced));
+ CHECK(std::abs(independentlyMeasured-reduced.error)<0.0001f);
+ for(unsigned i=0;i<reduced.count;++i) {
+ const Point p=reduced.points[i];
+ CHECK(p.x*p.x/(283*283)+p.y*p.y/(36*36)<1.00001f);
+ }
+ CHECK(BuildPolygon({{0,0},{1,1},{2,2}}).count==0);
+ CHECK(BuildPolygon({{0,0},{0,0},{0,0}}).count==0);
+ ellipse.resize(MaxSlicePoints+1);CHECK(BuildPolygon(ellipse).count==0);
+ std::vector<Point> full(MaxSlicePoints);
+ CHECK(!SliceTriangle({0,0,-1},{1,0,1},{0,1,1},full));CHECK(full.size()==MaxSlicePoints);
+ std::vector<Point> invalid;
+ CHECK(!SliceTriangle({0,0,0},{1,std::numeric_limits<float>::quiet_NaN(),0},{0,1,0},invalid));
+}
+
+TEST(water_hull_packing_rotation_damping_and_distinct_water_levels)
+{
+ using namespace WaterHullModel;
+ Hull hull;
+ hull.data[0][0]=3028;hull.data[0][1]=588;hull.data[0][2]=7;hull.data[0][3]=4;
+ hull.data[1][0]=0;hull.data[1][1]=-1;hull.data[1][2]=100;hull.data[1][3]=20;
+ const Point p[]={{-100,-20},{100,-20},{100,20},{-100,20}};
+ for(unsigned i=0;i<4;++i) {hull.data[4+i/2][(i%2)*2]=p[i].x;hull.data[4+i/2][(i%2)*2+1]=p[i].y;}
+ CHECK(Damping(hull,3028,588,7)==0);
+ CHECK(Damping(hull,3028,588,9)==1); // another water plane cannot flatten this one
+ CHECK(Damping(hull,3052.5f,588,7)==0.5f);
+ CHECK(Damping(hull,3057,588,7)==1);
+ CHECK(Damping(hull,10000,10000,7)==1);
+ for(float blend:{0.0f,.25f,.5f,1.0f}) {
+ const float atten=1+(Damping(hull,3052.5f,588,7)-1)*blend;
+ CHECK(std::abs(atten-(1-.5f*blend))<0.000001f);
+ }
+ const Point bowWorld={3028,488};
+ const Point local=LocalPoint(hull,bowWorld.x,bowWorld.y);
+ CHECK(local.x==100 && local.y==0); // authored negative-X bow can become positive local bow
+ CHECK(sizeof(Hull)==RegistersPerHull*16);
+}
+
+TEST(water_hull_shared_distance_hlsl_compiles_and_translates)
+{
+ std::string hlsl="cbuffer Hulls : register(b0, space3) { float4 HullData[80]; };\n";
+ hlsl+=WaterHullModel::GetHlslSource();
+ hlsl+="float4 main(float4 position : SV_Position) : SV_Target { return WaterHullSignedDistance(position.xy,70,12); }\n";
+ std::vector<unsigned char> spirv;std::string log,msl;
+ const bool compiled=SDL3_Compile_HLSL_To_SPIRV(hlsl,false,spirv,log);
+ if(!compiled) printf(" hull HLSL compilation failed: %s\n",log.c_str());
+ CHECK(compiled);if(!compiled) return;
+ const bool translated=SDL3_Translate_SPIRV_To_MSL(spirv,false,msl,log);
+ if(!translated) printf(" hull HLSL MSL translation failed: %s\n",log.c_str());
+ CHECK(translated);
+}
+
+TEST(water_macro_swell_gradients_and_curvature_include_warp_and_packet_derivatives)
+{
+ using namespace WaterSurfaceModel;
+ unsigned gradientControls=0,curvatureControls=0;
+ for(float time:{0.0f,1.7f,12.0f,38.0f}) for(float x:{-80.0f,0.0f,17.0f}) for(float y:{-21.0f,0.0f,43.0f}) {
+ const OceanSurface s=EvaluateOceanSwell(x,y,time);
+ const float step=.125f;
+ const float xp=EvaluateOceanSwell(x+step,y,time).height,xm=EvaluateOceanSwell(x-step,y,time).height;
+ const float yp=EvaluateOceanSwell(x,y+step,time).height,ym=EvaluateOceanSwell(x,y-step,time).height;
+ CHECK(std::abs((xp-xm)/(2*step)-s.dx)<.0015f);
+ CHECK(std::abs((yp-ym)/(2*step)-s.dy)<.0015f);
+ CHECK(std::abs((xp+xm+yp+ym-4*s.height)/(step*step)-s.laplacian)<.0015f);
+ const float q0=x*.0241f+y*.0157f-time*.23f+.4f,q1=x*-.0173f+y*.0299f-time*.19f+2.1f;
+ const float s0=std::sin(q0),s1=std::sin(q1),px=x+5*s0,py=y+4*s1,envelope=.86f+.14f*s0*s1;
+ float wrongX=0,wrongY=0,wrongLaplacian=0,height=0;
+#define TEST_MACRO_SWELL(kx,ky,amplitude,omega,phase) if((kx)*(kx)+(ky)*(ky)<.18f) { \
+ const float p=px*(kx)+py*(ky)-time*(omega)+(phase),sn=std::sin(p),cs=std::cos(p); \
+ height+=(amplitude)*(sn+.16f*sn*cs); \
+ const float derivative=(amplitude)*(cs+.16f*(cs*cs-sn*sn)); \
+ wrongX+=derivative*(kx);wrongY+=derivative*(ky); \
+ wrongLaplacian+=(amplitude)*(-sn-.64f*sn*cs)*((kx)*(kx)+(ky)*(ky)); }
+ WATER_OCEAN_MODES(TEST_MACRO_SWELL)
+#undef TEST_MACRO_SWELL
+ CHECK(std::abs(height*envelope-s.height)<.000001f);
+ if(std::max(std::abs(wrongX*envelope-s.dx),std::abs(wrongY*envelope-s.dy))>.002f) ++gradientControls;
+ if(std::abs(wrongLaplacian*envelope-s.laplacian)>.002f) ++curvatureControls;
+ }
+ CHECK(gradientControls>=8 && curvatureControls>=8);
+}
+
+TEST(foam_environment_positive_quadrature_preserves_energy_without_renormalizing)
+{
+ using namespace WaterFoamEnvironment;
+ const Table white=Build([](Vector){return RGB{1,1,1};});
+ const Table dark=Build([](Vector){return RGB{0,0,0};});
+ // Independent analytic irradiance: for L(w)=1+.5*w.z, E/pi=1+n.z/3.
+ // A coloured HDR environment also proves neither radiance nor irradiance is saturated.
+ const Table gradient=Build([](Vector w){const double a=1+.5*w.z;return RGB{2*a,.75*a,3.5*a};});
+ double maximumLoss=0,maximumWhiteLoss=0;unsigned finiteBinLosses=0;
+ for(unsigned i=0;i<256;++i) {
+ const double z=1-2*(i+.5)/256,phase=i*2.399963229728653,r=std::sqrt(1-z*z);
+ const Vector n={r*std::cos(phase),r*std::sin(phase),z};
+ const RGB unit=Evaluate(white,n),black=Evaluate(dark,n),colour=Evaluate(gradient,n);
+ CHECK(unit.r>=0 && unit.g>=0 && unit.b>=0);
+ CHECK(unit.r<=1.00002 && unit.g<=1.00002 && unit.b<=1.00002);
+ CHECK(black.r==0 && black.g==0 && black.b==0);
+ const double exact=1+z/3,values[3]={colour.r/2,colour.g/.75,colour.b/3.5};
+ for(double value:values) {
+ CHECK(std::isfinite(value) && value>=0 && value<=exact+.00002);
+ const double loss=(exact-value)/exact;if(loss>maximumLoss)maximumLoss=loss;
+ }
+ if(1-unit.r>maximumWhiteLoss)maximumWhiteLoss=1-unit.r;
+ if(1-unit.r>.001)++finiteBinLosses;
+ }
+ // Retain the measured finite-bin loss. A renormalized approximation could pass
+ // positivity while incorrectly increasing the current bright cloud's incident energy.
+ CHECK(finiteBinLosses>64);
+ CHECK(maximumLoss<.10 && maximumWhiteLoss<.10);
+ const RGB up=Evaluate(white,{0,0,1}),down=Evaluate(white,{0,0,-1});
+ CHECK(std::abs(up.r-1)<1e-12 && std::abs(down.r-1)<1e-12);
+ printf(" foam environment constant/linear maximum finite-bin losses %.6g/%.6g\n",maximumWhiteLoss,maximumLoss);
+}
+
+TEST(foam_environment_canonical_rotation_daylight_and_generated_constants_are_stable)
+{
+ using namespace WaterFoamEnvironment;
+ CHECK(&CachedTable()==&CachedTable());
+ CHECK(&HlslSource()==&HlslSource());
+ CHECK(HlslSource().find("waterFoamSkyMoments[144]")!=std::string::npos);
+ CHECK(HlslSource().find("i<48")!=std::string::npos);
+ // Rotate sun azimuth and normal together. Adding the inverse of oceanSky's small
+ // sun-axis bias retains exactly the same canonical direction at every orientation.
+ const Vector canonical={.3,.4,std::sqrt(.75)};
+ const RGB expected=Evaluate(CachedTable(),canonical);
+ for(double angle:{0.0,.2,1.7,3.1,5.4})for(double day:{0.0,.4,1.0}) {
+ const double x=std::cos(angle),y=std::sin(angle),scale=.06+.94*day;
+ const Vector normal={canonical.x*x-canonical.y*y,canonical.x*y+canonical.y*x,canonical.z};
+ const RGB actual=Evaluate(normal,{x-.00001,y,.45},day);
+ CHECK(std::abs(actual.r-expected.r*scale)<1e-12);
+ CHECK(std::abs(actual.g-expected.g*scale)<1e-12);
+ CHECK(std::abs(actual.b-expected.b*scale)<1e-12);
+ }
+ // All normals, including overturned FFT tangents, receive nonnegative radiance.
+ for(unsigned i=0;i<128;++i) {
+ const double z=1-2*(i+.5)/128,phase=i*2.399963229728653,r=std::sqrt(1-z*z);
+ const RGB value=Evaluate(CachedTable(),{r*std::cos(phase),r*std::sin(phase),z});
+ CHECK(std::isfinite(value.r) && value.r>=0 && std::isfinite(value.g) && value.g>=0 && std::isfinite(value.b) && value.b>=0);
+ }
+}
+
+#include "Platform/WaterShoreOverlay.h"
+TEST(authored_surf_wrapper_compiles_with_original_fixed_function_fog_and_alpha)
+{
+ CombinerDescription d={};d.StageCount=2;d.PixelPipeline.FogEnabled=true;
+ d.PixelPipeline.AlphaTestEnabled=true;d.PixelPipeline.AlphaFunction=FF_CMP_GREATER;
+ for(unsigned i=0;i<2;++i) {
+ auto &s=d.Stages[i];s.TextureBound=true;s.TextureCoordinateIndex=i;
+ s.ColourOperation=FF_TOP_MODULATE;s.ColourArgument1=FF_TA_TEXTURE;s.ColourArgument2=FF_TA_CURRENT;
+ s.AlphaOperation=i==0?FF_TOP_MODULATE:FF_TOP_SELECTARG2;s.AlphaArgument1=FF_TA_TEXTURE;s.AlphaArgument2=FF_TA_CURRENT;
+ }
+ std::string source;CHECK(CombinerShader_Generate(d,COMBINER_SHADER_TARGET_D3D11,source));
+ const std::string original=source;CHECK(WaterShoreOverlay::WrapPixel(source));
+ CHECK(source.find("shoreOriginalPixel(input)")!=std::string::npos);
+ CHECK(source.find("result.a*=1-shoreReplacement")!=std::string::npos);
+ CHECK(SDL3_Shader_Retarget(source,false));
+ std::vector<unsigned char> spirv;std::string log,msl;
+ const bool compiled=SDL3_Compile_HLSL_To_SPIRV(source,false,spirv,log);
+ if(!compiled)printf(" authored surf wrapper: %s\n",log.c_str());CHECK(compiled);if(!compiled)return;
+ unsigned samplers=0,buffers=0;SDL3_Shader_Slots(spirv,false,samplers,buffers);
+ CHECK(samplers<=8 && buffers==1);
+ CHECK(SDL3_Translate_SPIRV_To_MSL(spirv,false,msl,log));
+ std::string bad="not a generated combiner";const std::string saved=bad;
+ CHECK(!WaterShoreOverlay::WrapPixel(bad));CHECK(bad==saved);
+}
+
+
+#if defined(__linux__)
+// Full Modern shader integration, including its optional production diagnostics.
+TEST(shore_source_terms_reports_actual_front_and_is_absent_from_normal_source)
+{
+ struct RestoreDebug {
+ bool had;std::string value;
+ RestoreDebug(){const char*p=getenv("ZH_WATER_DEBUG");had=p!=nullptr;value=p?p:"";}
+ ~RestoreDebug(){if(had)setenv("ZH_WATER_DEBUG",value.c_str(),1);else unsetenv("ZH_WATER_DEBUG");}
+ }restore;
+ for(auto program:{ENGINE_SHADER_WATER_TRAPEZOID,ENGINE_SHADER_WATER_RIVER}) {
+ PixelPipelineDescription description={};std::string normal,diagnostic;
+ CHECK(unsetenv("ZH_WATER_DEBUG")==0);
+ CHECK(EngineShader_Pixel_Program(program,description,normal,COMBINER_SHADER_TARGET_SDL3_GPU));
+ CHECK(setenv("ZH_WATER_DEBUG","shore-source-terms",1)==0);
+ CHECK(EngineShader_Pixel_Program(program,description,diagnostic,COMBINER_SHADER_TARGET_SDL3_GPU));
+ const std::string start="\n // Shore source attribution (M5i):";
+ const std::string finish=" // End shore source attribution. Only the opt-in diagnostic recomputes residence.\n";
+ const size_t begin=diagnostic.find(start),end=diagnostic.find(finish,begin);
+ CHECK(begin!=std::string::npos&&end!=std::string::npos);
+ if(begin==std::string::npos||end==std::string::npos)continue;
+ const std::string block=diagnostic.substr(begin,end+finish.size()-begin);
+ CHECK(block.find("waterShoreFrontFresh(shoreRate,sourceTermsFront.y)")!=std::string::npos);
+ CHECK(block.find("shoreSupport)*fixedShoreFront.x")!=std::string::npos);
+ CHECK(block.find("waterShoreFresh(")==std::string::npos); // no accidental old-cap normalization
+ CHECK(block.find("fixedShoreRate/ShoreMaximumRate,finalShoreCoverage,1.0)")!=std::string::npos);
+ std::string stripped=diagnostic;stripped.erase(begin,end+finish.size()-begin);
+ CHECK(stripped==normal);CHECK(normal.find("sourceTermsFront")==std::string::npos);
+ std::vector<unsigned char>spirv;std::string log;
+ const bool compiled=SDL3_Compile_HLSL_To_SPIRV(diagnostic,false,spirv,log);
+ if(!compiled)printf(" actual shore-source-terms program %d: %s\n",int(program),log.c_str());
+ CHECK(compiled);
+ }
+}
+
+TEST(coastal_surf_optional_texture_contract_compiles_with_exact_hull_contact)
+{
+ // Exercise both branches explicitly rather than relying on the test process's
+ // ambient environment. Keep the existing larger shader matrix unchanged.
+ struct SavedOption {
+ const char *key;bool had;std::string value;
+ explicit SavedOption(const char *k):key(k),had(getenv(k)!=nullptr),value(getenv(k)?getenv(k):""){}
+ ~SavedOption(){if(had)setenv(key,value.c_str(),1);else unsetenv(key);}
+ } surf("ZH_WATER_SURF_GPU"),contact("ZH_WATER_HULL_CONTACT"),lift("ZH_WATER_BOW_LIFT"),
+ shoulder("ZH_WATER_BOW_SHOULDER"),crest("ZH_WATER_COAST_CREST"),debug("ZH_WATER_DEBUG");
+ CHECK(unsetenv("ZH_WATER_DEBUG")==0);
+ CHECK(setenv("ZH_WATER_BOW_LIFT","floor",1)==0);
+ CHECK(setenv("ZH_WATER_BOW_SHOULDER","contour",1)==0);
+ CHECK(setenv("ZH_WATER_COAST_CREST","1",1)==0);
+ PixelPipelineDescription pipeline={};
+ for(unsigned hull=0;hull<2;++hull) {
+ CHECK(setenv("ZH_WATER_HULL_CONTACT",hull?"mesh":"0",1)==0);
+ std::string riverWithoutSurf,flatWithoutSurf;
+ for(unsigned enabled=0;enabled<2;++enabled) {
+ CHECK(setenv("ZH_WATER_SURF_GPU",enabled?"1":"0",1)==0);
+ for(unsigned river=0;river<2;++river) {
+ std::string pixel,log,msl,why;std::vector<unsigned char>spirv;
+ const bool generated=EngineShader_Pixel_Program(river?ENGINE_SHADER_WATER_RIVER:ENGINE_SHADER_WATER_TRAPEZOID,
+ pipeline,pixel,COMBINER_SHADER_TARGET_SDL3_GPU);
+ CHECK(generated);if(!generated)continue;
+ if(!enabled){if(river)riverWithoutSurf=pixel;else flatWithoutSurf=pixel;}
+ if(enabled&&river)CHECK(pixel==riverWithoutSurf); // river source exactly independent of surf switch
+ CHECK((pixel.find("float gpuCoastFoam=")!=std::string::npos)==bool(enabled&&!river));
+ const bool compiled=SDL3_Compile_HLSL_To_SPIRV(pixel,false,spirv,log);
+ if(!compiled)printf("coastal surf shader hull%u surf%u river%u: %s\n",hull,enabled,river,log.c_str());
+ CHECK(compiled);if(!compiled)continue;
+ unsigned samplers=0,buffers=0;SDL3_Shader_Slots(spirv,false,samplers,buffers);
+ CHECK_EQ(samplers,enabled&&!river?16u:15u);CHECK_EQ(buffers,hull?4u:1u);
+ const char *validator=getenv("ZH_SPIRV_VAL");
+ if(validator&&*validator)CHECK(validate(validator,spirv,log));
+ const bool translated=SDL3_Translate_SPIRV_To_MSL(spirv,false,msl,log);
+ CHECK(translated);if(translated)CHECK(slots_kept(msl,samplers,why));
+ }
+ }
+ // Only the exact token opts in; unset and misleading values retain the
+ // same generated flat program as the explicit off mode, not merely its slots.
+ for(const char *value:{static_cast<const char *>(nullptr),"true","01"}) {
+ if(value)CHECK(setenv("ZH_WATER_SURF_GPU",value,1)==0);else CHECK(unsetenv("ZH_WATER_SURF_GPU")==0);
+ std::string pixel;CHECK(EngineShader_Pixel_Program(ENGINE_SHADER_WATER_TRAPEZOID,pipeline,pixel,COMBINER_SHADER_TARGET_SDL3_GPU));
+ CHECK(pixel==flatWithoutSurf);
+ }
+ }
+}
+
+TEST(water_mesh_contact_diagnostics_compile_with_the_shared_contact_material)
+{
+ struct SavedOption {
+ const char *key;bool had;std::string value;
+ explicit SavedOption(const char *k):key(k),had(getenv(k)!=nullptr),value(getenv(k)?getenv(k):""){}
+ ~SavedOption(){if(had)setenv(key,value.c_str(),1);else unsetenv(key);}
+ } contact("ZH_WATER_HULL_CONTACT"),debug("ZH_WATER_DEBUG");
+ CHECK(unsetenv(contact.key)==0);
+ PixelPipelineDescription pipeline={};
+ for(const char *mode:{"contact-mesh-query","contact-mesh-sources"}) {
+ CHECK(setenv(debug.key,mode,1)==0);
+ std::string pixel,log,msl,why;std::vector<unsigned char> spirv;
+ CHECK(EngineShader_Pixel_Program(ENGINE_SHADER_WATER_TRAPEZOID,pipeline,pixel,COMBINER_SHADER_TARGET_SDL3_GPU));
+ const bool compiled=SDL3_Compile_HLSL_To_SPIRV(pixel,false,spirv,log);
+ if(!compiled)printf("mesh contact diagnostic %s: %s\n",mode,log.c_str());
+ CHECK(compiled);if(!compiled)continue;
+ unsigned samplers=0,buffers=0;SDL3_Shader_Slots(spirv,false,samplers,buffers);
+ CHECK_EQ(buffers,4u);
+ const char *validator=getenv("ZH_SPIRV_VAL");
+ if(validator && *validator)CHECK(validate(validator,spirv,log));
+ CHECK(SDL3_Translate_SPIRV_To_MSL(spirv,false,msl,log));
+ CHECK(slots_kept(msl,samplers,why));
+ }
+}
+
+TEST(water_plain_launch_matches_explicit_validated_settings)
+{
+ struct SavedOption {
+ const char *key;bool had;std::string value;
+ explicit SavedOption(const char *k):key(k),had(getenv(k)!=nullptr),value(getenv(k)?getenv(k):""){}
+ ~SavedOption(){if(had)setenv(key,value.c_str(),1);else unsetenv(key);}
+ } contact("ZH_WATER_HULL_CONTACT"),lift("ZH_WATER_BOW_LIFT"),
+ shoulder("ZH_WATER_BOW_SHOULDER"),debug("ZH_WATER_DEBUG");
+ const char *keys[]={contact.key,lift.key,shoulder.key};
+ const char *modes[]={"mesh","floor","contour"};
+ auto configure=[&](unsigned disabled,bool explicitModes) {
+ for(unsigned i=0;i<3;++i) {
+ if(disabled&(1u<<i))CHECK(setenv(keys[i],"0",1)==0);
+ else if(explicitModes)CHECK(setenv(keys[i],modes[i],1)==0);
+ else CHECK(unsetenv(keys[i])==0);
+ }
+ CHECK(WaterHullVisual::Enabled()==!(disabled&1u));
+ CHECK(WaterBowLift::Enabled()==!(disabled&2u));
+ CHECK(WaterBowShoulder::Enabled()==!(disabled&4u));
+ };
+ VertexPipelineDescription description=shader_cases_detail::plain_vertex();
+ description.FVF=0x252;description.LightingEnabled=false;description.StageCount=4;
+ for(unsigned i=0;i<4;++i) {
+ description.Stages[i].TextureCoordinateIndex=i<2?i:0;
+ description.Stages[i].TextureTransformFlags=FF_TTFF_DISABLE;
+ }
+ std::string fixedVertex;
+ CHECK(VertexShader_Generate(description,VERTEX_SHADER_TARGET_D3D11,fixedVertex));
+ PixelPipelineDescription pipeline={};
+ // Check each independent opt-out as well as the ordinary all-enabled launch.
+ // Complete generated programs must match, including diagnostics and resource layouts.
+ for(unsigned disabled=0;disabled<8;++disabled) {
+ configure(disabled,false);std::string defaultVertex=fixedVertex;
+ CHECK(WaterFftSampling::WrapVertex(defaultVertex));
+ configure(disabled,true);std::string explicitVertex=fixedVertex;
+ CHECK(WaterFftSampling::WrapVertex(explicitVertex));
+ CHECK(defaultVertex==explicitVertex);
+ for(const char *mode:{static_cast<const char *>(nullptr),"contact-mesh","bow-retention",
+ "contact-mesh-query","contact-mesh-sources"}) {
+ if(mode)CHECK(setenv(debug.key,mode,1)==0);else CHECK(unsetenv(debug.key)==0);
+ for(auto program:{ENGINE_SHADER_WATER_TRAPEZOID,ENGINE_SHADER_WATER_RIVER}) {
+ configure(disabled,false);std::string defaultPixel;
+ CHECK(EngineShader_Pixel_Program(program,pipeline,defaultPixel,COMBINER_SHADER_TARGET_SDL3_GPU));
+ configure(disabled,true);std::string explicitPixel;
+ CHECK(EngineShader_Pixel_Program(program,pipeline,explicitPixel,COMBINER_SHADER_TARGET_SDL3_GPU));
+ CHECK(defaultPixel==explicitPixel);
+ }
+ }
+ }
+ // Preserve the previous interpretation of explicit non-matching values.
+ for(const char *value:{"","0","off","true","invalid"}) {
+ for(const char *key:keys)CHECK(setenv(key,value,1)==0);
+ CHECK(!WaterHullVisual::Enabled());CHECK(!WaterBowLift::Enabled());CHECK(!WaterBowShoulder::Enabled());
+ }
+}
+#endif // __linux__
diff --git a/GeneralsMD/Code/Tests/test_water_grid.cpp b/GeneralsMD/Code/Tests/test_water_grid.cpp
index ec8df6019..fe10ceae2 100644
--- a/GeneralsMD/Code/Tests/test_water_grid.cpp
+++ b/GeneralsMD/Code/Tests/test_water_grid.cpp
@@ -51,9 +51,15 @@
#include "Common/GlobalData.h"
#include "Common/NameKeyGenerator.h"
#include "GameLogic/WaterGridMotion.h"
+#include "Platform/WaterFoamParticlePolicy.h"
+#include "Platform/WaterCoastalCrest.h"
+#include <limits>
#include <string>
#include <vector>
+#include <array>
+#include <map>
+#include <set>
#include "water_grid_scenario.h"
@@ -163,3 +169,5093 @@ TEST(water_grid_unstepped_is_not_the_golden)
const std::string line = water_grid::run( still, std::vector<int>( 1, 1 ), nextFirstFrame() );
CHECK( line != eaLoop );
}
+
+#include "Platform/WaterSurfaceModel.h"
+#include "Platform/WaterProjectedMesh.h"
+#include "Platform/WaterBowRefinement.h"
+#include "Platform/WaterFftGeometry.h"
+#include "Platform/WaterVesselMotion.h"
+#include "Platform/WaterFoamHistory.h"
+#include "Platform/WaterFoamWindow.h"
+#include "Platform/WaterHullContact.h"
+#include "Platform/WaterHullPoseCache.h"
+#include "Platform/WaterObstacleIndex.h"
+#include "Platform/WaterOpticalContext.h"
+#include <cmath>
+
+namespace {
+WaterOpticalContext::Polygon opticalRectangle(float x0,float y0,float x1,float y1,float level=4) {
+ return {{{x0,y0,level},{x1,y0,level},{x1,y1,level},{x0,y1,level}}};
+}
+}
+
+TEST(water_optical_context_keeps_enclosed_pools_clear_inside_an_ocean_polygon)
+{
+ using namespace WaterOpticalContext;
+ const int width=50,height=40,border=2;
+ std::vector<uint8_t> heights(width*height,20);
+ for (int y=0;y<height;++y) for (int x=0;x<18;++x) heights[y*width+x]=0;
+ for (int y=10;y<31;++y) for (int x=28;x<47;++x) heights[y*width+x]=0;
+ std::vector<Polygon> polygons={opticalRectangle(-100,-100,600,500)};
+ Field field;
+ CHECK(Build(heights.data(),width,height,border,10,1,4,polygons,field));
+ CHECK_EQ(field.ocean[20*width+4],255);
+ CHECK_EQ(field.ocean[20*width+37],0); // Broad, wet pool still disconnected from the coast.
+ CHECK_EQ(field.ocean[20*width+22],0);
+ CHECK_EQ(field.ocean[20*width+15],0); // Within 30 world units of shore.
+ CHECK(field.ocean[20*width+12]>0 && field.ocean[20*width+12]<255);
+ for (int x=1;x<18;++x) CHECK(field.ocean[20*width+x]<=field.ocean[20*width+x-1]);
+}
+
+TEST(water_optical_context_polygon_union_cannot_invent_a_water_connection)
+{
+ using namespace WaterOpticalContext;
+ const int side=60;
+ std::vector<uint8_t> heights(side*side,0);
+ Field field;
+ std::vector<Polygon> polygons={opticalRectangle(-100,-100,180,700),opticalRectangle(300,100,550,500)};
+ CHECK(Build(heights.data(),side,side,0,10,1,4,polygons,field));
+ CHECK_EQ(field.ocean[30*side+3],255);
+ CHECK_EQ(field.ocean[30*side+42],0); // Low terrain between polygons is not authored water.
+ CHECK_EQ(field.ocean[30*side+24],0);
+ polygons.push_back(opticalRectangle(100,100,400,500,9));
+ CHECK(Build(heights.data(),side,side,0,10,1,4,polygons,field));
+ CHECK_EQ(field.ocean[30*side+42],0); // A different level cannot supply the missing connection.
+ for (Point& p:polygons.back().points) p.z=4;
+ CHECK(Build(heights.data(),side,side,0,10,1,4,polygons,field));
+ CHECK_EQ(field.ocean[30*side+42],255); // Same-level overlapping polygons join correctly.
+}
+
+TEST(water_optical_context_uses_the_playable_boundary_and_has_no_texture_edge_shore)
+{
+ using namespace WaterOpticalContext;
+ const int side=40,border=5;
+ std::vector<uint8_t> heights(side*side,0);
+ Field field;
+ std::vector<Polygon> polygons={opticalRectangle(-100,-100,500,500)};
+ CHECK(Build(heights.data(),side,side,border,10,1,4,polygons,field));
+ CHECK_EQ(field.ocean[0],255);
+ CHECK_EQ(field.ocean[side*side-1],255);
+ polygons={opticalRectangle(-50,-50,340,340)}; // Exact native grid bounds, both orientations.
+ CHECK(Build(heights.data(),side,side,border,10,1,4,polygons,field));
+ for (uint8_t value:field.ocean) CHECK_EQ(value,255);
+ std::reverse(polygons[0].points.begin(),polygons[0].points.end());
+ CHECK(Build(heights.data(),side,side,border,10,1,4,polygons,field));
+ for (uint8_t value:field.ocean) CHECK_EQ(value,255);
+ // Restrict water to the padded border: that alone does not mark it as ocean.
+ polygons={opticalRectangle(-100,-100,-10,500)};
+ CHECK(Build(heights.data(),side,side,border,10,1,4,polygons,field));
+ for (uint8_t value:field.ocean) CHECK_EQ(value,0);
+}
+
+TEST(water_optical_context_concave_polygon_preserves_its_dry_notch)
+{
+ using namespace WaterOpticalContext;
+ const int side=60;
+ std::vector<uint8_t> heights(side*side,0);
+ std::vector<Polygon> polygons={{{{-10,-10,4},{600,-10,4},{600,600,4},{400,600,4},
+ {400,200,4},{200,200,4},{200,600,4},{-10,600,4}}}};
+ Field field;
+ CHECK(Build(heights.data(),side,side,0,10,1,4,polygons,field));
+ CHECK_EQ(field.ocean[40*side+30],0);
+ CHECK_EQ(field.ocean[10*side+30],255);
+ CHECK_EQ(field.ocean[40*side+5],255);
+ CHECK_EQ(field.ocean[40*side+55],255);
+}
+
+TEST(water_optical_context_refreshes_terrain_level_dimensions_and_polygon_geometry)
+{
+ using namespace WaterOpticalContext;
+ const int side=40;
+ std::vector<uint8_t> heights(side*side,20);
+ for (int y=10;y<31;++y) for (int x=10;x<31;++x) heights[y*side+x]=0;
+ std::vector<Polygon> polygons={opticalRectangle(-100,-100,500,500)};
+ Field field;
+ CHECK(Build(heights.data(),side,side,0,10,1,4,polygons,field));
+ CHECK_EQ(field.ocean[20*side+20],0);
+ for (int y=10;y<31;++y) for (int x=0;x<10;++x) heights[y*side+x]=0;
+ CHECK(Build(heights.data(),side,side,0,10,1,4,polygons,field));
+ CHECK_EQ(field.ocean[20*side+20],255);
+ CHECK(Build(heights.data(),side,side,0,10,1,8,polygons,field));
+ CHECK_EQ(field.ocean[20*side+20],0);
+ const std::vector<Polygon> before=polygons;
+ CHECK(SamePolygons(before,polygons));
+ polygons[0].points[0].z=8;
+ CHECK(!SamePolygons(before,polygons));
+ polygons=before; polygons[0].points[0].x+=1;
+ CHECK(!SamePolygons(before,polygons));
+ CHECK(Build(heights.data(),20,20,1,10,1,4,before,field));
+ CHECK_EQ(field.ocean.size(),400);
+ CHECK_EQ(field.shore.size(),400);
+}
+
+TEST(water_optical_context_bounds_and_shore_fade)
+{
+ using namespace WaterOpticalContext;
+ CHECK_EQ(Offshore(0),0);
+ CHECK_EQ(Offshore(30),0);
+ CHECK(std::abs(Offshore(65)-0.5f)<0.00001f);
+ CHECK_EQ(Offshore(100),1);
+ CHECK_EQ(Offshore(1000),1);
+ std::vector<uint8_t> heights(16,0);
+ std::vector<Polygon> polygons={opticalRectangle(-10,-10,100,100)};
+ Field field;
+ CHECK(Build(heights.data(),4,4,0,10,1,4,polygons,field));
+ CHECK(!Build(heights.data(),MaxDimension+1,2,0,10,1,4,polygons,field));
+ CHECK(field.ocean.empty() && field.shore.empty());
+ CHECK(!Build(heights.data(),2048,2048,0,10,1,4,polygons,field));
+ CHECK(!Build(heights.data(),4,4,2,10,1,4,polygons,field));
+ CHECK(!Build(heights.data(),4,4,0,0,1,4,polygons,field));
+ CHECK(!Build(NULL,4,4,0,10,1,4,polygons,field));
+}
+
+TEST(water_surface_analytic_normal_is_derivative_of_displaced_height)
+{
+ using namespace WaterSurfaceModel;
+ for (int t=0;t<4;++t) for (int i=0;i<20;++i) {
+ const float x=2.31f*i,y=-1.57f*i,time=0.73f*t,epsilon=0.002f;
+ const Sample sample=Evaluate(x,y,time);
+ const float dx=(Evaluate(x+epsilon,y,time).height-Evaluate(x-epsilon,y,time).height)/(2*epsilon);
+ const float dy=(Evaluate(x,y+epsilon,time).height-Evaluate(x,y-epsilon,time).height)/(2*epsilon);
+ CHECK(std::abs(sample.dx-dx)<0.003f);
+ CHECK(std::abs(sample.dy-dy)<0.003f);
+ CHECK(std::abs(sample.height)<MaxDisplacement);
+ }
+}
+
+TEST(water_surface_modes_evolve_and_all_freeze_controls_hold_time)
+{
+ using namespace WaterSurfaceModel;
+ // A single location can be at the same height at two different phases. Check the field's
+ // motion energy instead, so destructive interference at one point is not a false failure.
+ double heightChange=0, slopeChange=0;
+ for (int i=0;i<16;++i) {
+ const Sample a=Evaluate(12+i*3.7f,34-i*1.3f,0),b=Evaluate(12+i*3.7f,34-i*1.3f,1);
+ heightChange+=(a.height-b.height)*(a.height-b.height);
+ slopeChange+=(a.dx-b.dx)*(a.dx-b.dx)+(a.dy-b.dy)*(a.dy-b.dy);
+ }
+ CHECK(heightChange>0.1);
+ CHECK(slopeChange>0.1);
+ CHECK(AdvanceTime(2,0.1f,true,false,false)==2);
+ CHECK(AdvanceTime(2,0.1f,false,true,false)==2);
+ CHECK(AdvanceTime(2,0.1f,false,false,true)==2);
+ CHECK(AdvanceTime(2,30,false,false,false)==2.1f);
+ CHECK(AdvanceTime(2,-1,false,false,false)==2);
+ const float resumed=AdvanceTime(2,0.02f,false,false,false);
+ CHECK(resumed>2 && resumed<2.1f);
+ std::string shader;
+ AppendHLSL(shader);
+ CHECK(shader.find("float3 waterWave")!=std::string::npos);
+ CHECK(shader.find("value.yz")!=std::string::npos);
+}
+
+TEST(water_surface_shores_limit_render_displacement_without_changing_water_level)
+{
+ using namespace WaterSurfaceModel;
+ CHECK(ShoreDamping(-10)==0);
+ CHECK(ShoreDamping(0)==0);
+ CHECK(ShoreDamping(9)==1);
+ CHECK(ShoreDamping(100)==1);
+ for (int depth=0;depth<90;++depth) CHECK(ShoreDamping(depth*0.1f)<=ShoreDamping((depth+1)*0.1f));
+}
+
+TEST(water_surface_shared_edges_weld_in_reverse_and_move_continuously_with_camera)
+{
+ using namespace WaterSurfaceModel;
+ const Point a={-200,17,12},b={2100,533,12};
+ const Point cameras[]={{500,200,110},{-100,-300,100},{3500,700,1000}};
+ for (const Point &camera:cameras) for (int cells=1;cells<=MeshCells;cells*=2) for (int i=0;i<=cells;++i) {
+ const float t=float(i)/cells;
+ const Point forward=EdgePoint(a,b,t,camera),reverse=EdgePoint(b,a,1-t,camera);
+ CHECK(memcmp(&forward,&reverse,sizeof(Point))==0);
+ Point moved=camera;moved.x+=0.01f;
+ const Point next=EdgePoint(a,b,t,moved);
+ CHECK(std::abs(next.x-forward.x)<0.02f);
+ CHECK(std::abs(next.y-forward.y)<0.02f);
+ }
+}
+
+TEST(water_surface_mesh_stays_in_convex_patch_and_triangle_indices_are_bounded)
+{
+ using namespace WaterSurfaceModel;
+ const Point corners[4]={{0,0,12},{600,10,12},{520,300,12},{-100,270,12}};
+ const Point cameras[]={{0,0,1},{300,100,30},{-1000,200,100},{10000,-4000,1200}};
+ for (const Point &camera:cameras) {
+ std::vector<Point> mesh(MeshVertices);
+ for (int j=0;j<=MeshCells;++j) for (int i=0;i<=MeshCells;++i) {
+ const float u=float(i)/MeshCells,v=float(j)/MeshCells;
+ const Point edges[4]={EdgePoint(corners[0],corners[1],u,camera),EdgePoint(corners[1],corners[2],v,camera),
+ EdgePoint(corners[3],corners[2],u,camera),EdgePoint(corners[0],corners[3],v,camera)};
+ const Point p=PatchPoint(corners,edges,u,v);
+ mesh[j*(MeshCells+1)+i]=p;
+ CHECK(std::abs(p.z-12)<0.0001f);
+ for (int edge=0;edge<4;++edge) {
+ const Point &a=corners[edge],&b=corners[(edge+1)%4];
+ CHECK((b.x-a.x)*(p.y-a.y)-(b.y-a.y)*(p.x-a.x)>-0.05f);
+ }
+ }
+ for (int j=0;j<MeshCells;++j) for (int i=0;i<MeshCells;++i) {
+ const int a=j*(MeshCells+1)+i,b=a+1,c=a+MeshCells+1,d=c+1;
+ CHECK(a>=0 && b<MeshVertices && c<MeshVertices && d<MeshVertices);
+ const Point &p=mesh[a],&q=mesh[b],&r=mesh[d],&s=mesh[c];
+ CHECK((q.x-p.x)*(r.y-p.y)-(q.y-p.y)*(r.x-p.x)>0);
+ CHECK((r.x-p.x)*(s.y-p.y)-(r.y-p.y)*(s.x-p.x)>0);
+ }
+ }
+ for (int patches=1;patches<=2000;++patches) {
+ const int cells=CellsForPatches(patches);
+ CHECK(cells>=1 && cells<=MeshCells);
+ CHECK(patches*(cells+1)*(cells+1)<=VertexBudget);
+ int emitted=0;
+ for (int row=0;row<cells;row+=IndexBatchRows(cells)) {
+ const int rows=std::min(IndexBatchRows(cells),cells-row);
+ CHECK(rows*cells*6<=65535);
+ emitted+=rows*cells*6;
+ }
+ CHECK(emitted==cells*cells*6);
+ }
+}
+
+TEST(water_surface_cannot_be_replaced_by_uniform_texture_advection)
+{
+ using namespace WaterSurfaceModel;
+ // Fit the best possible single scrolling velocity to the temporal derivative. A static
+ // translated height map has zero residual; dispersive independently directed modes do not.
+ double xx=0,xy=0,yy=0,xt=0,yt=0;
+ struct Derivative { double x,y,t; } values[64];
+ for (int i=0;i<64;++i) {
+ const float x=float(i%8)*7.13f,y=float(i/8)*9.77f,t=1.37f,epsilon=0.002f;
+ const Sample sample=Evaluate(x,y,t);
+ Derivative &v=values[i];v.x=sample.dx;v.y=sample.dy;
+ v.t=(Evaluate(x,y,t+epsilon).height-Evaluate(x,y,t-epsilon).height)/(2*epsilon);
+ xx+=v.x*v.x;xy+=v.x*v.y;yy+=v.y*v.y;xt+=v.x*v.t;yt+=v.y*v.t;
+ }
+ const double determinant=xx*yy-xy*xy;
+ CHECK(determinant>0.001);
+ const double vx=(xt*yy-yt*xy)/determinant,vy=(yt*xx-xt*xy)/determinant;
+ double residual=0,energy=0;
+ for (const Derivative &v:values) { const double e=v.t-vx*v.x-vy*v.y;residual+=e*e;energy+=v.t*v.t; }
+ CHECK(residual/energy>0.2);
+}
+
+namespace {
+struct LODTestVertex {
+ WaterSurfaceModel::Point position;
+ float attenuation,base;
+};
+LODTestVertex testLODMorph(const LODTestVertex &fine,const LODTestVertex &a,const LODTestVertex &b,float amount)
+{
+ using namespace WaterSurfaceModel;
+ return {{MorphCoordinate(fine.position.x,a.position.x,b.position.x,amount),
+ MorphCoordinate(fine.position.y,a.position.y,b.position.y,amount),
+ MorphCoordinate(fine.position.z,a.position.z,b.position.z,amount)},
+ MorphCoordinate(fine.attenuation,a.attenuation,b.attenuation,amount),MorphCoordinate(fine.base,a.base,b.base,amount)};
+}
+std::vector<LODTestVertex> testLODGrid(int cells,float amount,bool ocean=false)
+{
+ using namespace WaterSurfaceModel;
+ const Point corners[4]={{0,0,12},{600,10,12},{520,300,12},{-100,270,12}},camera={180,75,200};
+ std::vector<LODTestVertex> grid((cells+1)*(cells+1));
+ for (int j=0;j<=cells;++j) for (int i=0;i<=cells;++i) {
+ const float u=float(i)/cells,v=float(j)/cells;
+ const Point edges[4]={EdgePoint(corners[0],corners[1],u,camera),EdgePoint(corners[1],corners[2],v,camera),
+ EdgePoint(corners[3],corners[2],u,camera),EdgePoint(corners[0],corners[3],v,camera)};
+ Point p=PatchPoint(corners,edges,u,v);
+ const Sample blend={ocean?0.5f+0.0005f*p.x:0.0f,ocean?0.0005f:0.0f,0};
+ const float attenuation=TerrainDamping(0.05f*(p.y+20),blend.height),base=p.z;
+ p.z+=attenuation*EvaluateBlended(p.x,p.y,1.73f,blend).height;
+ grid[j*(cells+1)+i]={p,attenuation,base};
+ }
+ if (amount>0) for (int j=0;j<=cells;++j) for (int i=0;i<=cells;++i) {
+ if (((i|j)&1)==0) continue;
+ const CoarsePair pair=CoarsePairForVertex(i,j,cells);
+ grid[j*(cells+1)+i]=testLODMorph(grid[j*(cells+1)+i],grid[pair.first],grid[pair.second],amount);
+ }
+ return grid;
+}
+LODTestVertex testLODSample(const std::vector<LODTestVertex> &grid,int cells,float u,float v)
+{
+ const int i=std::min(int(u*cells),cells-1),j=std::min(int(v*cells),cells-1),side=cells+1;
+ const float x=u*cells-i,y=v*cells-j;
+ const LODTestVertex &a=grid[j*side+i],&d=grid[(j+1)*side+i+1];
+ const LODTestVertex &other=y>x?grid[(j+1)*side+i]:grid[j*side+i+1];
+ const float wa=1-std::max(x,y),wd=std::min(x,y),wo=std::abs(x-y);
+ return {{a.position.x*wa+d.position.x*wd+other.position.x*wo,
+ a.position.y*wa+d.position.y*wd+other.position.y*wo,
+ a.position.z*wa+d.position.z*wd+other.position.z*wo},
+ a.attenuation*wa+d.attenuation*wd+other.attenuation*wo,a.base*wa+d.base*wd+other.base*wo};
+}
+void checkLODVertexNear(const LODTestVertex &a,const LODTestVertex &b,float epsilon)
+{
+ CHECK(std::abs(a.position.x-b.position.x)<epsilon);
+ CHECK(std::abs(a.position.y-b.position.y)<epsilon);
+ CHECK(std::abs(a.position.z-b.position.z)<epsilon);
+ CHECK(std::abs(a.attenuation-b.attenuation)<epsilon);
+ CHECK(std::abs(a.base-b.base)<epsilon);
+}
+}
+
+TEST(water_surface_lod_retains_freecam_detail_and_reduces_rts_cost_monotonically)
+{
+ using namespace WaterSurfaceModel;
+ CHECK(LODForCameraHeight(128,117).cells==128);
+ CHECK(LODForCameraHeight(128,120).morph==0);
+ CHECK(LODForCameraHeight(128,180).cells==64);
+ CHECK(LODForCameraHeight(128,270).cells==32);
+ CHECK(LODForCameraHeight(128,405).cells==16);
+ CHECK(LODForCameraHeight(128,607.5f).cells==8);
+ CHECK(LODForCameraHeight(128,310).cells==32);
+ CHECK(LODForCameraHeight(64,310).cells==16);
+ for (int base=1;base<=MeshCells;base*=2) {
+ int previous=base;
+ float previousDetail=0;
+ for (int height=-10;height<=3000;++height) {
+ const MeshLOD lod=LODForCameraHeight(base,float(height));
+ CHECK(lod.cells<=previous && lod.cells>=std::min(base,MinimumLODCells));
+ CHECK(lod.morph>=0 && lod.morph<=1);
+ const float detail=std::log2(float(base)/lod.cells)+lod.morph;
+ CHECK(detail+0.00001f>=previousDetail);
+ previous=lod.cells;previousDetail=detail;
+ }
+ }
+}
+
+TEST(water_surface_lod_coarse_pairs_stay_bounded_and_do_not_read_morphed_vertices)
+{
+ using namespace WaterSurfaceModel;
+ for (int cells=1;cells<=MeshCells;cells*=2) for (int j=0;j<=cells;++j) for (int i=0;i<=cells;++i) {
+ const CoarsePair pair=CoarsePairForVertex(i,j,cells);
+ CHECK(pair.first>=0 && pair.second<(cells+1)*(cells+1));
+ if (cells>1) {
+ CHECK(((pair.first%(cells+1))&1)==0 && ((pair.first/(cells+1))&1)==0);
+ CHECK(((pair.second%(cells+1))&1)==0 && ((pair.second/(cells+1))&1)==0);
+ }
+ }
+}
+
+TEST(water_surface_lod_completed_morph_equals_coarse_triangles_and_metadata)
+{
+ using namespace WaterSurfaceModel;
+ const std::vector<LODTestVertex> fine=testLODGrid(32,1.0f),coarse=testLODGrid(16,0.0f);
+ for (int j=0;j<32;++j) for (int i=0;i<32;++i) {
+ // Sample both triangle interiors, not only their shared vertices: this catches a wrong
+ // diagonal or an arbitrary nearest-vertex collapse that would still match even/even nodes.
+ for (int triangle=0;triangle<2;++triangle) {
+ const float u=(i+(triangle?0.23f:0.71f))/32.0f,v=(j+(triangle?0.73f:0.29f))/32.0f;
+ checkLODVertexNear(testLODSample(fine,32,u,v),testLODSample(coarse,16,u,v),0.0002f);
+ }
+ }
+ const std::vector<LODTestVertex> original=testLODGrid(32,0.0f);
+ for (float amount:{0.1f,0.35f,0.7f}) {
+ const std::vector<LODTestVertex> morphed=testLODGrid(32,amount);
+ for (size_t i=0;i<morphed.size();++i) {
+ CHECK(morphed[i].attenuation>=0 && morphed[i].attenuation<=1);
+ CHECK(std::abs(morphed[i].position.z-morphed[i].base)<=MaxDisplacement);
+ CHECK(morphed[i].position.x>=std::min(original[i].position.x,fine[i].position.x)-0.0001f);
+ CHECK(morphed[i].position.x<=std::max(original[i].position.x,fine[i].position.x)+0.0001f);
+ }
+ }
+}
+
+TEST(water_surface_lod_transition_is_continuous_in_both_camera_directions)
+{
+ using namespace WaterSurfaceModel;
+ for (float threshold:{180.0f,270.0f,405.0f,607.5f}) {
+ const MeshLOD below=LODForCameraHeight(128,threshold-0.001f),above=LODForCameraHeight(128,threshold+0.001f);
+ const std::vector<LODTestVertex> fine=testLODGrid(below.cells,below.morph),coarse=testLODGrid(above.cells,above.morph);
+ for (int j=0;j<12;++j) for (int i=0;i<12;++i) {
+ const float u=(i+0.17f)/12,v=(j+0.63f)/12;
+ checkLODVertexNear(testLODSample(fine,below.cells,u,v),testLODSample(coarse,above.cells,u,v),0.0003f);
+ }
+ }
+ CHECK(MorphColour(0x10203040,0xff00aa55,0x00ff55aa,0)==0x10203040);
+ CHECK(MorphColour(0x10203040,0xff00aa55,0x00ff55aa,1)==0x80808080);
+}
+
+TEST(water_surface_lod_shared_edges_remain_bit_identical_throughout_morph)
+{
+ using namespace WaterSurfaceModel;
+ const Point a={-200,17,12},b={2100,533,12},camera={500,200,110};
+ for (int cells=8;cells<=MeshCells;cells*=2) {
+ std::vector<LODTestVertex> forward(cells+1),reverse(cells+1);
+ for (int i=0;i<=cells;++i) {
+ Point p=EdgePoint(a,b,float(i)/cells,camera);
+ const float attenuation=ShoreDamping((p.y-30)*0.07f);
+ p.z+=Evaluate(p.x,p.y,1.73f).height*attenuation;
+ forward[i]={p,attenuation,12};
+ p=EdgePoint(b,a,float(i)/cells,camera);
+ const float reverseAttenuation=ShoreDamping((p.y-30)*0.07f);
+ p.z+=Evaluate(p.x,p.y,1.73f).height*reverseAttenuation;
+ reverse[i]={p,reverseAttenuation,12};
+ }
+ for (float amount:{0.0f,0.17f,0.5f,0.93f,1.0f}) for (int i=0;i<=cells;++i) {
+ const CoarsePair fp=CoarsePairForVertex(i,0,cells),rp=CoarsePairForVertex(cells-i,0,cells);
+ const LODTestVertex f=testLODMorph(forward[i],forward[fp.first],forward[fp.second],amount);
+ const LODTestVertex r=testLODMorph(reverse[cells-i],reverse[rp.first],reverse[rp.second],amount);
+ CHECK(memcmp(&f,&r,sizeof(f))==0);
+ }
+ }
+}
+
+
+namespace {
+struct IndexedTestObstacle {
+ WaterObstacleIndex::Influence influence;
+ float z,height,major,minor,cosine,sine;bool box,hasHull;
+};
+struct IndexedTestDamping { float surface,obstacle;size_t visited; };
+IndexedTestDamping indexedTestDamping(const std::vector<IndexedTestObstacle> &objects,
+ const WaterObstacleIndex::Grid *index,float x,float y,float z,float depth,float offshore)
+{
+ IndexedTestDamping result={WaterSurfaceModel::TerrainDamping(depth,offshore),1,0};
+ if (result.surface<=0) return result;
+ const WaterObstacleIndex::Range range=index && offshore>0?index->Query(x,y):WaterObstacleIndex::Range{};
+ const size_t count=range.indexed?range.count:objects.size();
+ for (size_t i=0;i<count;++i) {
+ const IndexedTestObstacle &o=objects[range.indexed?range.indices[i]:i];++result.visited;
+ if (z<o.z-12 || z>o.z+o.height+3) continue;
+ const float dx=x-o.influence.x,dy=y-o.influence.y;
+ if (offshore>0 && WaterSurfaceModel::BeyondObstacleFade(dx,dy,o.influence.radius)) continue;
+ float damping;
+ if (o.hasHull && offshore>0) {
+ const float legacy=offshore<1?WaterSurfaceModel::ShoreDamping(std::sqrt(dx*dx+dy*dy)-o.influence.radius):1;
+ damping=legacy+(1-legacy)*offshore;
+ } else if (o.box && offshore>0) {
+ damping=WaterSurfaceModel::BoxDamping(dx*o.cosine+dy*o.sine,-dx*o.sine+dy*o.cosine,o.major,o.minor);
+ if (offshore<1) { const float legacy=WaterSurfaceModel::ShoreDamping(std::sqrt(dx*dx+dy*dy)-o.influence.radius);damping=legacy+(damping-legacy)*offshore; }
+ } else damping=WaterSurfaceModel::ShoreDamping(std::sqrt(dx*dx+dy*dy)-o.influence.radius);
+ result.obstacle=(std::min)(result.obstacle,damping);result.surface=(std::min)(result.surface,damping);
+ if (result.surface<=0) return result;
+ }
+ return result;
+}
+}
+
+TEST(water_obstacle_bins_match_ordered_damping_and_metadata_with_fewer_candidates)
+{
+ using namespace WaterObstacleIndex;
+ std::vector<IndexedTestObstacle> obstacles;std::vector<Influence> influences;
+ uint32_t random=0x5317a291u;
+ auto unit=[&]() { random=random*1664525u+1013904223u;return float(random>>8)/16777216.0f; };
+ for (int i=0;i<839;++i) {
+ const float major=2+unit()*70,minor=2+unit()*30,angle=unit()*6.2831853f;
+ IndexedTestObstacle o={{unit()*4096-2048,unit()*4096-2048,std::sqrt(major*major+minor*minor)},unit()*30,5+unit()*40,
+ major,minor,std::cos(angle),std::sin(angle),i%3!=0,i%11==0};
+ obstacles.push_back(o);influences.push_back(o.influence);
+ }
+ Grid index;CHECK(index.Build(influences,{-2200,-2200,2200,2200}));
+ CHECK(index.CellCount()<=Grid::MaxCells && index.ReferenceCount()<=Grid::MaxReferences);
+ size_t indexedVisits=0,bruteVisits=0;
+ for (int i=0;i<4000;++i) {
+ const float x=unit()*4400-2200,y=unit()*4400-2200,z=unit()*50,depth=unit()*14;
+ const float offshore=i%5==0?0:(i%5==1?1:unit());
+ const auto a=indexedTestDamping(obstacles,nullptr,x,y,z,depth,offshore),b=indexedTestDamping(obstacles,&index,x,y,z,depth,offshore);
+ CHECK(a.surface==b.surface && a.obstacle==b.obstacle);
+ if (offshore==0) CHECK(a.visited==b.visited);
+ else { indexedVisits+=b.visited;bruteVisits+=a.visited; }
+ const Range range=index.Query(x,y);
+ for (size_t j=1;j<range.count;++j) CHECK(range.indices[j]>range.indices[j-1]);
+ }
+ CHECK(indexedVisits*20<bruteVisits); // Armed cost check: the implementation cannot return all839.
+ // Movement/removal invalidates membership on the next draw; no old candidate list survives.
+ for (int i=0;i<50;++i) { obstacles[i].influence.x+=317;obstacles[i].influence.y-=199; }
+ obstacles.erase(obstacles.begin()+50,obstacles.begin()+80);influences.clear();
+ for (const auto &o:obstacles) influences.push_back(o.influence);
+ CHECK(index.Build(influences,{-2200,-2200,2200,2200}));
+ for (int i=0;i<2000;++i) {
+ const float x=unit()*5000-2500,y=unit()*5000-2500,offshore=unit();
+ const auto a=indexedTestDamping(obstacles,nullptr,x,y,7,8,offshore),b=indexedTestDamping(obstacles,&index,x,y,7,8,offshore);
+ CHECK(a.surface==b.surface && a.obstacle==b.obstacle);
+ }
+ index.Clear();CHECK(!index.Query(0,0).indexed);
+}
+
+TEST(water_obstacle_bins_include_negative_boundaries_and_fail_to_complete_full_list)
+{
+ using namespace WaterObstacleIndex;
+ const std::vector<IndexedTestObstacle> obstacles={{{-64,-128,54},7,30,40,30,0.6f,0.8f,true,false},
+ {{0,0,54},7,30,40,30,1,0,true,true},{{64,128,54},7,30,40,30,1,0,false,false}};
+ std::vector<Influence> influences;for (const auto &o:obstacles) influences.push_back(o.influence);
+ Grid index;CHECK(index.Build(influences,{-256,-256,256,256}));
+ for (float x:{-128.0001f,-128.0f,-127.9999f,-64.0001f,-64.0f,-63.9999f,-0.0001f,0.0f,0.0001f,63.9999f,64.0f,64.0001f,127.9999f,128.0f,128.0001f})
+ for (float y:{-192.0f,-128.0f,-64.0f,0.0f,64.0f,128.0f,192.0f}) for (float offshore:{0.0f,0.001f,0.5f,0.999f,1.0f}) {
+ const auto a=indexedTestDamping(obstacles,nullptr,x,y,7,7,offshore),b=indexedTestDamping(obstacles,&index,x,y,7,7,offshore);
+ CHECK(a.surface==b.surface && a.obstacle==b.obstacle);
+ }
+ for (Bounds bounds: {Bounds{-1e30f,-1e30f,1e30f,1e30f},Bounds{0,0,100000,100000},Bounds{NAN,0,1,1}}) {
+ CHECK(!index.Build(influences,bounds));CHECK(!index.Query(0,0).indexed);
+ const auto a=indexedTestDamping(obstacles,nullptr,0,0,7,7,0.5f),b=indexedTestDamping(obstacles,&index,0,0,7,7,0.5f);
+ CHECK(a.surface==b.surface && a.obstacle==b.obstacle);
+ }
+ const std::vector<Influence> huge(20,Influence{0,0,100000});
+ CHECK(!index.Build(huge,{-4000,-4000,4000,4000}));CHECK(!index.Query(0,0).indexed);
+ CHECK(!index.Build({Influence{INFINITY,0,10}},{-128,-128,128,128}));
+ CHECK(index.Build({}, {-128,-128,128,128}));CHECK(index.Query(0,0).indexed && index.Query(0,0).count==0);
+ CHECK(!index.Query(INFINITY,0).indexed);
+}
+
+namespace {
+WaterProjectedMesh::Projection testWaterProjection()
+{
+ WaterProjectedMesh::Projection p={{0.01,0,0,0,0.01,0,0,0,1},{0},{0,0,1},0.1,10,0.12};
+ CHECK(p.Prepare());return p;
+}
+double projectedMeshArea(const WaterProjectedMesh::Mesh &mesh,const WaterProjectedMesh::Projection &projection)
+{
+ double area=0;
+ for (size_t i=0;i<mesh.indices.size();i+=3) {
+ WaterProjectedMesh::Point p[3];
+ for (int j=0;j<3;++j) { CHECK(mesh.indices[i+j]<mesh.vertices.size());CHECK(projection.Transform(mesh.vertices[mesh.indices[i+j]].world,p[j])); }
+ const double triangle=(p[1].x-p[0].x)*(p[2].y-p[0].y)-(p[1].y-p[0].y)*(p[2].x-p[0].x);
+ CHECK(triangle>0);area+=triangle*0.5;
+ }
+ return area;
+}
+}
+
+TEST(water_projected_lattice_covers_visible_plane_once_with_bounded_shared_vertices)
+{
+ using namespace WaterProjectedMesh;
+ const Point polygon[4]={{-500,-500},{500,-500},{500,500},{-500,500}};
+ const Projection projection=testWaterProjection();Mesh mesh;
+ CHECK(Build(polygon,projection,{160,90},mesh));
+ CHECK(mesh.vertices.size()<=VertexBound(160,90));
+ // Frustum-edge cells retain their centre fan so authored-edge knots can enter without a
+ // topology pop. Interior cells still have exactly two triangles; added work is perimeter-only.
+ const size_t perimeterCells=2u*160+2u*90-4;
+ CHECK(mesh.indices.size()>=160u*90*6 && mesh.indices.size()<=160u*90*6+perimeterCells*6);
+ CHECK(mesh.vertices.size()<=161u*91+perimeterCells);
+ CHECK(std::abs(projectedMeshArea(mesh,projection)-4*1.12*1.12)<1e-9);
+ CHECK(mesh.vertices.size()<mesh.indices.size()/4); // Adjacent cells actually share samples.
+ for (const Vertex &vertex:mesh.vertices) {
+ CHECK(std::isfinite(vertex.world.x) && std::isfinite(vertex.world.y));
+ CHECK(std::abs(vertex.world.x)<=112.000001 && std::abs(vertex.world.y)<=112.000001);
+ }
+}
+
+TEST(water_projected_integer_cache_preserves_exact_reference_vertices_and_indices)
+{
+ using namespace WaterProjectedMesh;
+ for (int fixture=0;fixture<8;++fixture) for (Resolution resolution:{Resolution{2,2},Resolution{31,17},Resolution{160,90}}) {
+ Point corners[4]={{-500,-500},{500,-500},{500,500},{-500,500}};
+ if (fixture%3==1) { corners[0]={-95,-170};corners[1]={81,-110};corners[2]={120,92};corners[3]={-64,170}; }
+ if (fixture%3==2) { corners[0]={-200,-200};corners[1]={0,-200};corners[2]={0,200};corners[3]={-200,200}; }
+ if (fixture&1) std::reverse(corners,corners+4);
+ Projection projection=testWaterProjection();
+ projection.matrix[2]=fixture*0.013;projection.matrix[5]=fixture*-0.009;
+ projection.matrix[6]=fixture*0.000021;projection.matrix[7]=fixture*0.00011;CHECK(projection.Prepare());
+ std::vector<BoundaryKnot> knots;
+ for (int edge=0;edge<4;++edge) {
+ Point a=corners[edge],b=corners[(edge+1)%4];
+ if (a.x>b.x || (a.x==b.x && a.y>b.y)) std::swap(a,b);
+ for (int i=0;i<=16;++i) { const double t=double(i)/16;knots.push_back({{a.x+(b.x-a.x)*t,a.y+(b.y-a.y)*t},edge,i,t}); }
+ }
+ Mesh reference,fast;
+ CHECK(Build(corners,projection,resolution,reference,60000,knots,false));
+ CHECK(Build(corners,projection,resolution,fast,60000,knots,true));
+ CHECK(reference.cells==fast.cells && reference.indices==fast.indices);
+ CHECK(reference.vertices.size()==fast.vertices.size());
+ CHECK(reference.transitions.size()==fast.transitions.size() && reference.collars.size()==fast.collars.size());
+ if (reference.vertices.size()!=fast.vertices.size()) continue;
+ std::unordered_map<WorldKey,float,WorldHash> cachedHeights;
+ for (size_t i=0;i<fast.vertices.size();++i) {
+ const Vertex &a=reference.vertices[i],&b=fast.vertices[i];
+ CHECK(std::memcmp(&a.world,&b.world,sizeof(a.world))==0);
+ CHECK(a.boundary==b.boundary && a.knot==b.knot && std::memcmp(&a.edgeParameter,&b.edgeParameter,sizeof(double))==0);
+ CHECK(a.transition==b.transition && a.collar==b.collar);
+ CHECK(a.lattice==b.lattice);
+ if (i%17==0) {
+ const float x=float(a.world.x),y=float(a.world.y);
+ const WorldKey key=SampleKey(x,y,7);
+ const float direct=WaterSurfaceModel::EvaluateOceanHeight(x,y,2.3f);
+ const auto old=cachedHeights.emplace(key,direct);
+ CHECK(direct==old.first->second); // Bypassing the single-patch value cache changes no wave sample.
+ }
+ }
+ }
+}
+
+TEST(water_projected_clipping_preserves_reversed_shared_authored_boundaries)
+{
+ using namespace WaterProjectedMesh;
+ const Point left[4]={{-200,-200},{0,-200},{0,200},{-200,200}};
+ const Point right[4]={{200,200},{0,200},{0,-200},{200,-200}};
+ Projection projection=testWaterProjection();projection.matrix[7]=0.001;CHECK(projection.Prepare());
+ Mesh a,b;CHECK(Build(left,projection,{40,24},a));CHECK(Build(right,projection,{40,24},b));
+ std::vector<double> ea,eb;
+ for (const Vertex &v:a.vertices) if (v.world.x==0 && v.boundary>=0) ea.push_back(v.world.y);
+ for (const Vertex &v:b.vertices) if (v.world.x==0 && v.boundary>=0) eb.push_back(v.world.y);
+ std::sort(ea.begin(),ea.end());ea.erase(std::unique(ea.begin(),ea.end()),ea.end());
+ std::sort(eb.begin(),eb.end());eb.erase(std::unique(eb.begin(),eb.end()),eb.end());
+ CHECK(ea.size()>20 && ea.size()==eb.size());
+ for (size_t i=0;i<ea.size() && i<eb.size();++i) CHECK(ea[i]==eb[i]);
+ CHECK(std::abs(projectedMeshArea(a,projection)+projectedMeshArea(b,projection)-4*1.12*1.12)<1e-9);
+}
+
+TEST(water_projected_plane_guard_preserves_authored_nonplanar_levels)
+{
+ const float level[4]={7,7,7,7},sloped[4]={7,7,7,7.001f},invalid[4]={INFINITY,INFINITY,INFINITY,INFINITY};
+ CHECK(WaterProjectedMesh::HasSingleLevel(level));
+ CHECK(!WaterProjectedMesh::HasSingleLevel(sloped));
+ CHECK(!WaterProjectedMesh::HasSingleLevel(invalid));
+}
+
+TEST(water_projected_near_horizon_is_finite_and_clips_real_authored_coverage)
+{
+ using namespace WaterProjectedMesh;
+ const Point polygon[4]={{-500,-500},{500,-500},{500,500},{-500,500}};
+ Projection projection=testWaterProjection();projection.matrix[7]=0.002;projection.depth={0,0.002,1};projection.nearDistance=0.2;CHECK(projection.Prepare());
+ Mesh mesh;CHECK(Build(polygon,projection,{48,32},mesh));CHECK(!mesh.indices.empty());
+ for (const Vertex &v:mesh.vertices) {
+ CHECK(std::isfinite(v.world.x) && std::isfinite(v.world.y));
+ CHECK(std::abs(v.world.x)<=500.000001 && std::abs(v.world.y)<=500.000001);
+ CHECK(Distance(projection.depth,v.world)>=0.2-1e-10);
+ }
+ CHECK(projectedMeshArea(mesh,projection)>0);
+ projection.matrix[3]=projection.matrix[4]=projection.matrix[5]=0;CHECK(!projection.Prepare());
+ CHECK(!Build(polygon,testWaterProjection(),{192,128},mesh,20)); // Explicit fallback; no partial mesh accepted.
+}
+
+TEST(water_projected_boundary_contains_each_retained_displaced_edge_bend)
+{
+ using namespace WaterProjectedMesh;
+ const Point polygon[4]={{-100,-100},{0,-100},{0,100},{-100,100}};
+ std::vector<BoundaryKnot> knots;
+ for (int i=0;i<=16;++i) knots.push_back({{0,-100+i*12.5},1,i,double(i)/16});
+ Mesh mesh;CHECK(Build(polygon,testWaterProjection(),{2,2},mesh,60000,knots));
+ CHECK(mesh.vertices.size()<=VertexBound(2,2,knots.size()));
+ auto knotHeight=[](int i) { return std::sin((-100+i*12.5)*0.12)+i*0.07; };
+ auto retainedHeight=[&](double y) {
+ const double u=(y+100)/12.5;const int i=(std::max)(0,(std::min)(15,int(u)));
+ return knotHeight(i)+(knotHeight(i+1)-knotHeight(i))*(u-i);
+ };
+ bool included[17]={};double covered=0,maxSkippedBend=0;
+ for (const Vertex &v:mesh.vertices) if (v.knot>=0) {
+ CHECK(v.knot<=16);included[v.knot]=true;
+ CHECK(v.world.y==knots[v.knot].world.y);
+ }
+ for (bool present:included) CHECK(present);
+ for (size_t t=0;t<mesh.indices.size();t+=3) for (int e=0;e<3;++e) {
+ const Vertex &a=mesh.vertices[mesh.indices[t+e]],&b=mesh.vertices[mesh.indices[t+(e+1)%3]];
+ if (a.world.x!=0 || b.world.x!=0 || a.world.y==b.world.y) continue;
+ const double lo=(std::min)(a.world.y,b.world.y),hi=(std::max)(a.world.y,b.world.y);
+ covered+=hi-lo;
+ for (const BoundaryKnot &k:knots) CHECK(!(k.world.y>lo+1e-10 && k.world.y<hi-1e-10));
+ const double midpoint=(lo+hi)*0.5;
+ CHECK(std::abs((retainedHeight(lo)+retainedHeight(hi))*0.5-retainedHeight(midpoint))<1e-12);
+ }
+ CHECK(std::abs(covered-200)<1e-10);
+ // Armed control: joining only the projected cell endpoints would visibly skip wave bends.
+ for (int i=1;i<8;++i) maxSkippedBend=(std::max)(maxSkippedBend,
+ std::abs(knotHeight(i)-(knotHeight(0)+(knotHeight(8)-knotHeight(0))*i/8)));
+ CHECK(maxSkippedBend>0.5);
+ const Point concave[4]={{-100,-100},{100,-100},{0,-50},{-100,100}};
+ CHECK(!Build(concave,testWaterProjection(),{2,2},mesh));
+}
+
+TEST(water_projected_sampling_moves_continuously_and_refreshes_for_resize)
+{
+ using namespace WaterProjectedMesh;
+ Projection a=testWaterProjection(),b=a;b.matrix[2]+=1e-7;CHECK(b.Prepare());
+ for (int y=-4;y<=4;++y) for (int x=-4;x<=4;++x) {
+ Point p,q;CHECK(a.Transform({x*0.2,y*0.2},p,true));CHECK(b.Transform({x*0.2,y*0.2},q,true));
+ CHECK(std::abs((q.x-p.x)+0.00001)<1e-10 && std::abs(q.y-p.y)<1e-10);
+ CHECK(std::abs(WaterSurfaceModel::EvaluateOceanHeight(float(p.x),float(p.y),1.7f)-
+ WaterSurfaceModel::EvaluateOceanHeight(float(q.x),float(q.y),1.7f))<0.0001f);
+ }
+ const size_t available=WaterSurfaceModel::VertexBudget-50u*65*65;
+ const Resolution carrier=ChooseResolution(1280,720,2,available,4*65),resize=ChooseResolution(960,540,2,available,4*65);
+ CHECK(carrier.columns==160 && carrier.rows==90);
+ CHECK(resize.columns<carrier.columns && resize.rows<carrier.rows);
+ for (int patches:{1,2,10,50}) {
+ const Resolution r=ChooseResolution(3840,2160,patches,WaterSurfaceModel::VertexBudget);
+ CHECK(size_t(patches)*VertexBound(r.columns,r.rows)<=WaterSurfaceModel::VertexBudget);
+ CHECK(VertexBound(r.columns,r.rows)<=60000);
+ }
+ for (int allPatches:{2,52,500,4000}) {
+ const int base=WaterSurfaceModel::CellsForPatches(allPatches),flat=(std::max)(1,allPatches/3);
+ const size_t legacy=size_t(base+1)*(base+1),retained=size_t(allPatches-flat)*legacy;
+ const size_t available=WaterSurfaceModel::VertexBudget-retained,share=available/flat;
+ const Resolution r=ChooseResolution(1280,720,flat,available,4*(base+1));
+ const size_t bound=VertexBound(r.columns,r.rows,4*(base+1));
+ // Projection can fail (budget, singular camera or concavity); its legacy grid remains
+ // inside the same share, so an arbitrary mix of accepted and fallback patches is bounded.
+ CHECK(legacy<=share);
+ CHECK(retained+size_t(flat)*(bound<=share?bound:legacy)<=WaterSurfaceModel::VertexBudget);
+ }
+}
+
+namespace {
+double projectedTestWave(WaterProjectedMesh::Point p) {
+ return 1.2*std::sin(p.x*0.037)+0.7*std::cos(p.y*0.049)+0.4*std::sin((p.x+p.y)*0.021);
+}
+double projectedTestEdge(const WaterProjectedMesh::Point corners[4],int edge,double parameter) {
+ using namespace WaterProjectedMesh;
+ Point a=corners[edge],b=corners[(edge+1)%4];
+ if (a.x>b.x || (a.x==b.x && a.y>b.y)) std::swap(a,b);
+ // The retained mesh is deliberately much coarser than the nonlinear analytic height.
+ const double u=parameter*2;const int index=(std::min)(1,int(u));const double t=u-index;
+ const Point lo={a.x+(b.x-a.x)*index/2,a.y+(b.y-a.y)*index/2};
+ const Point hi={a.x+(b.x-a.x)*(index+1)/2,a.y+(b.y-a.y)*(index+1)/2};
+ return projectedTestWave(lo)+(projectedTestWave(hi)-projectedTestWave(lo))*t;
+}
+double projectedTestCollar(const WaterProjectedMesh::Point corners[4],WaterProjectedMesh::Point p,const WaterProjectedMesh::BoundaryCollar &collar) {
+ const double analytic=projectedTestWave(p);double value=analytic;
+ for (int i=0;i<collar.count;++i) value+=collar.weight[i]*(projectedTestEdge(corners,collar.edge[i],collar.parameter[i])-analytic);
+ return value;
+}
+std::vector<double> projectedTestHeights(const WaterProjectedMesh::Mesh &mesh,const WaterProjectedMesh::Point corners[4]) {
+ using namespace WaterProjectedMesh;
+ std::vector<double> heights;
+ for (const Vertex &v:mesh.vertices) {
+ double height=v.boundary>=0?projectedTestEdge(corners,v.boundary,v.edgeParameter):
+ (v.collar>=0?projectedTestCollar(corners,v.world,mesh.collars[v.collar]):projectedTestWave(v.world));
+ if (v.transition>=0) {
+ const CentreTransition &transition=mesh.transitions[v.transition];double source[3],sum=0;
+ for (int i=0;i<3;++i) {
+ CHECK(transition.weight[i]>=-1e-10 && transition.weight[i]<=1+1e-10);sum+=transition.weight[i];
+ source[i]=projectedTestCollar(corners,transition.source[i],CollarAt(corners,transition.source[i]));
+ }
+ CHECK(std::abs(sum-1)<1e-10);height=InterpolateCentre(transition,height,source);
+ }
+ CHECK(std::abs(height)<=2.300001);heights.push_back(height);
+ }
+ return heights;
+}
+double projectedTestRenderedHeight(const WaterProjectedMesh::Mesh &mesh,const std::vector<double> &height,WaterProjectedMesh::Point p) {
+ using namespace WaterProjectedMesh;
+ for (size_t i=0;i<mesh.indices.size();i+=3) {
+ const unsigned ia=mesh.indices[i],ib=mesh.indices[i+1],ic=mesh.indices[i+2];
+ const Point a=mesh.vertices[ia].world,b=mesh.vertices[ib].world,c=mesh.vertices[ic].world;
+ const double determinant=(b.x-a.x)*(c.y-a.y)-(b.y-a.y)*(c.x-a.x);
+ if (std::abs(determinant)<1e-16) continue;
+ const double v=((p.x-a.x)*(c.y-a.y)-(p.y-a.y)*(c.x-a.x))/determinant;
+ const double w=((b.x-a.x)*(p.y-a.y)-(b.y-a.y)*(p.x-a.x))/determinant;
+ if (v>=-1e-10 && w>=-1e-10 && v+w<=1+1e-10) return height[ia]*(1-v-w)+height[ib]*v+height[ic]*w;
+ }
+ CHECK(false);return 0;
+}
+}
+
+TEST(water_projected_actual_triangles_stay_continuous_at_knot_and_full_cell_transitions)
+{
+ using namespace WaterProjectedMesh;
+ const Point polygon[4]={{-500,-500},{0,-500},{0,500},{-500,500}};
+ std::vector<BoundaryKnot> knots;
+ for (int edge=0;edge<4;++edge) {
+ Point a=polygon[edge],b=polygon[(edge+1)%4];
+ if (a.x>b.x || (a.x==b.x && a.y>b.y)) std::swap(a,b);
+ for (int i=0;i<=2;++i) knots.push_back({{a.x+(b.x-a.x)*i/2,a.y+(b.y-a.y)*i/2},edge,i,i/2.0});
+ }
+ for (int axis:{0,1}) {
+ Projection before=testWaterProjection(),after=before;
+ // Y motion moves the only visible retained knot across a lattice line; X motion
+ // changes a clipped cell into a full cell. Compare the actual nonlinear triangles.
+ before.matrix[axis*3+2]=-1e-7;after.matrix[axis*3+2]=1e-7;
+ CHECK(before.Prepare() && after.Prepare());Mesh a,b;
+ CHECK(Build(polygon,before,{2,2},a,60000,knots));CHECK(Build(polygon,after,{2,2},b,60000,knots));
+ const auto ah=projectedTestHeights(a,polygon),bh=projectedTestHeights(b,polygon);
+ for (double y:{-90.0,-50.0,-10.0,10.0,50.0,90.0}) for (double x:{-95.0,-65.0,-35.0,-5.0})
+ CHECK(std::abs(projectedTestRenderedHeight(a,ah,{x,y})-projectedTestRenderedHeight(b,bh,{x,y}))<0.00002);
+ CHECK(a.vertices.size()<=VertexBound(2,2,knots.size()) && b.vertices.size()<=VertexBound(2,2,knots.size()));
+ }
+ // Armed controls: both discarded centre height and the old boundary/interior handoff
+ // differ materially here. A test comparing only moving XY samples would miss these pops.
+ CHECK(std::abs(projectedTestWave({-56,-56})-(projectedTestWave({-112,-112})+projectedTestWave({0,0}))*0.5)>0.1);
+ CHECK(std::abs(projectedTestWave({0,50})-projectedTestEdge(polygon,1,0.55))>0.1);
+ for (double y:{-501.0,-499.0,0.0,499.0,501.0}) for (double x:{-12.00001,-12.0,-11.99999,-0.00001,0.00001}) {
+ const double a=projectedTestCollar(polygon,{x,y},CollarAt(polygon,{x,y}));
+ const double b=projectedTestCollar(polygon,{x+1e-7,y},CollarAt(polygon,{x+1e-7,y}));
+ CHECK(std::abs(a-b)<0.000001 && std::abs(a)<=2.300001);
+ }
+}
+
+TEST(water_projected_horizon_reference_rejects_nonconvex_weights_and_preserves_height_bounds)
+{
+ using namespace WaterProjectedMesh;
+ const Point polygon[4]={{-500,-0.9},{500,-0.9},{500,500},{-500,500}};
+ // The horizon lies inside one lattice row. More than75% of that row is visible, so it
+ // attempts the regular-cell transition, but its upper reference corners are behind the eye.
+ Projection projection={{1,0,0,0,1.018,0,0,1,1},{0},{0,1,1},0.1,600,0.12};
+ CHECK(projection.Prepare());Mesh mesh;CHECK(Build(polygon,projection,{16,90},mesh));
+ CHECK(projectedMeshArea(mesh,projection)>0);
+ const double bottom=1.12*(2.0*85/90-1),top=1.12*(2.0*86/90-1),visibleTop=1.018*500/501;
+ const double centre=(bottom+visibleTop)*0.5;
+ Point lo,hi,mid;CHECK(projection.Transform({0,bottom},lo,true));
+ CHECK(projection.Transform({0,top},hi,true));CHECK(projection.Transform({0,centre},mid,true));
+ CHECK((top-visibleTop)/(top-bottom)<0.25 && Distance(projection.depth,hi)<0);
+ const double opposite=(mid.y-lo.y)/(hi.y-lo.y);
+ CHECK(opposite<-0.08); // Armed control: the unguarded production formula is non-convex.
+ double unsafe[3]={1-opposite,0,opposite};CHECK(!NormalizeCentreWeights(unsafe));
+ CHECK((1-opposite)*2.3+opposite*-2.3>2.6); // It can exceed the2.3-unit source bound.
+ int guarded=0;
+ for (const Vertex &v:mesh.vertices) if (v.boundary<0 && std::abs(v.world.y-mid.y)<1e-7) {
+ ++guarded;CHECK(v.transition<0);
+ }
+ CHECK(guarded>0);
+ const auto heights=projectedTestHeights(mesh,polygon);
+ for (double height:heights) CHECK(std::isfinite(height) && std::abs(height)<=2.300001);
+ CHECK(mesh.vertices.size()<=VertexBound(16,90));
+ double roundoff[3]={-1e-12,0.4,0.600000000001};CHECK(NormalizeCentreWeights(roundoff));
+ CHECK(roundoff[0]==0 && std::abs(roundoff[0]+roundoff[1]+roundoff[2]-1)<1e-14);
+ double nonfinite[3]={0.5,0.5,NAN};CHECK(!NormalizeCentreWeights(nonfinite));
+}
+
+static WaterHullModel::Hull foamTestHull(float x,float y,float vx,float vy,float angle=0,float level=7)
+{
+ WaterHullModel::Hull h;
+ h.data[0][0]=x;h.data[0][1]=y;h.data[0][2]=level;h.data[0][3]=4;
+ h.data[1][0]=std::cos(angle);h.data[1][1]=std::sin(angle);h.data[1][2]=12;h.data[1][3]=4;
+ h.data[2][0]=vx;h.data[2][1]=vy;h.data[3][0]=-12;h.data[3][2]=12;
+ const float p[8]={-12,-4,12,-4,12,4,-12,4};
+ for(int i=0;i<8;++i) h.data[4+i/4][i%4]=p[i];return h;
+}
+
+TEST(water_hull_contact_clips_actual_mesh_and_excludes_unreachable_superstructure)
+{
+ using namespace WaterHullModel;
+ std::vector<Point> points;
+ // The greatest projected extent is strictly inside the slab. Endpoint-plane
+ // slices alone miss it; a collision rectangle would include unsupported corners.
+ CHECK(WaterHullContact::ProjectTriangle({7,0,1},{-2,-3,-1},{-2,3,4},3,points));
+ const Polygon polygon=BuildPolygon(points);CHECK(polygon.count>=3);
+ float maxX=-1e30f,minY=1e30f,maxY=-1e30f;
+ for(unsigned i=0;i<polygon.count;++i) {
+ maxX=(std::max)(maxX,polygon.points[i].x);minY=(std::min)(minY,polygon.points[i].y);maxY=(std::max)(maxY,polygon.points[i].y);
+ }
+ CHECK(maxX==7 && minY>-3 && maxY<3);
+ CHECK(SignedDistance({6,2},polygon)>0); // Armed against using the triangle AABB.
+ const auto before=points;
+ CHECK(WaterHullContact::ProjectTriangle({-100,-100,4},{100,-100,5},{0,100,8},3,points));
+ CHECK(WaterHullContact::ProjectTriangle({-100,-100,-8},{100,-100,-5},{0,100,-4},3,points));
+ CHECK(points.size()==before.size()); // Neither the deck above the slab nor a deep part leaks in.
+ CHECK(!WaterHullContact::ProjectTriangle({NAN,0,0},{1,0,0},{0,1,0},3,points));
+ CHECK(!WaterHullContact::ProjectTriangle({0,0,0},{1,0,0},{0,1,0},3.1f,points));
+ CHECK(points.size()==before.size());
+ std::vector<Point> budget(MaxSlicePoints-2);
+ CHECK(!WaterHullContact::ProjectTriangle({0,0,1},{1,0,1},{0,1,1},3,budget));
+ CHECK(budget.size()==MaxSlicePoints-2); // Failure cannot append a truncated contour.
+ std::vector<Point> boundary;
+ CHECK(WaterHullContact::ProjectTriangle({0,0,3},{1,0,3},{0,1,3},3,boundary));
+ CHECK(BuildPolygon(boundary).count==3);
+ CHECK(WaterHullContact::ReachableCrest(NAN)==0);
+ CHECK(WaterHullContact::ReachableCrest(4,NAN)==0);
+ CHECK(WaterHullContact::ReachableCrest(-1)==0 && WaterHullContact::ReachableCrest(4,0)==0);
+ CHECK(std::abs(WaterHullContact::ReachableCrest(.25f)-.10f)<1e-6f);
+ CHECK(WaterHullContact::ReachableCrest(4)==3 && WaterHullContact::ReachableCrest(100)==3);
+ CHECK(WaterHullContact::ReachableCrest(4,.1f)<=WaterFftGeometry::MaxVerticalDisplacement*.100001f);
+}
+
+TEST(water_hull_contact_current_slab_stabilizes_a_tilted_keel_without_changing_mean_slice)
+{
+ using namespace WaterHullModel;
+ const Point3 hull[8]={{-40,-.5f,-.25f},{40,-.5f,-.25f},{40,.5f,-.25f},{-40,.5f,-.25f},
+ {-44,-10,3},{44,-10,3},{44,10,3},{-44,10,3}};
+ const unsigned indices[12][3]={{0,2,1},{0,3,2},{4,5,6},{4,6,7},{0,1,5},{0,5,4},
+ {1,2,6},{1,6,5},{2,3,7},{2,7,6},{3,0,4},{3,4,7}};
+ for(float pitch:{-.05f,0.0f,.05f}) for(float roll:{-.05f,0.0f,.05f}) {
+ Point3 rotated[8];float lowX=1e30f,highX=-1e30f,lowY=1e30f,highY=-1e30f;
+ const float cy=std::cos(pitch),sy=std::sin(pitch),cp=std::cos(roll),sp=std::sin(roll);
+ for(unsigned i=0;i<8;++i) {
+ const Point3 p=hull[i];rotated[i]={cy*p.x+sy*sp*p.y+sy*cp*p.z,cp*p.y-sp*p.z,-sy*p.x+cy*sp*p.y+cy*cp*p.z};
+ lowX=(std::min)(lowX,rotated[i].x);highX=(std::max)(highX,rotated[i].x);
+ lowY=(std::min)(lowY,rotated[i].y);highY=(std::max)(highY,rotated[i].y);
+ }
+ std::vector<Point> mean,contact,reversed;
+ for(const auto &tri:indices) {
+ const Point3 a=rotated[tri[0]],b=rotated[tri[1]],c=rotated[tri[2]];
+ CHECK(SliceTriangle(a,b,c,mean));
+ CHECK(WaterHullContact::ProjectTriangle(a,b,c,3,contact));
+ CHECK(WaterHullContact::ProjectTriangle(c,b,a,3,reversed));
+ }
+ const Polygon exact=BuildPolygon(mean),envelope=BuildPolygon(contact),reverse=BuildPolygon(reversed);
+ CHECK(exact.count>=3 && envelope.count>=3 && envelope.count<=MaxVertices);
+ CHECK(reverse.count==envelope.count);
+ for(unsigned i=0;i<envelope.count;++i) {
+ const Point p=envelope.points[i];
+ CHECK(p.x>=lowX-.0001f && p.x<=highX+.0001f && p.y>=lowY-.0001f && p.y<=highY+.0001f);
+ CHECK(std::abs(p.x-reverse.points[i].x)<.0001f && std::abs(p.y-reverse.points[i].y)<.0001f);
+ }
+ for(unsigned i=0;i<exact.count;++i) CHECK(SignedDistance(exact.points[i],envelope)<=.0002f+envelope.error);
+ CHECK(SignedDistance({0,7},envelope)<0 && SignedDistance({0,-7},envelope)<0);
+ // Building a new current-transform envelope never mutates the original mean contour.
+ const Polygon meanAfter=BuildPolygon(mean);CHECK(meanAfter.count==exact.count);
+ for(unsigned i=0;i<exact.count;++i) CHECK(exact.points[i].x==meanAfter.points[i].x && exact.points[i].y==meanAfter.points[i].y);
+ if(pitch==0 && roll==0) CHECK(SignedDistance({0,7},exact)>4); // Meaningful tiny-keel control.
+ }
+}
+
+namespace {
+WaterHullPoseCache::Mesh waterTestHullPose(float angle=0,float draft=0)
+{
+ static int model,vertices,triangles;
+ WaterHullPoseCache::Mesh mesh;mesh.identity=&model;mesh.vertexArray=&vertices;mesh.triangleArray=&triangles;
+ mesh.vertexCount=8;mesh.triangleCount=12;mesh.crossesMean=true;
+ const float center[3]={0,-20,24.859f},extent[3]={285,50,25.141f};
+ mesh.supportRadius=WaterHullPoseCache::SupportRadius(center,extent);
+ mesh.transform[0][0]=mesh.transform[2][2]=std::cos(angle);
+ mesh.transform[0][2]=std::sin(angle);mesh.transform[2][0]=-std::sin(angle);
+ mesh.transform[1][1]=1;mesh.transform[2][3]=-draft;return mesh;
+}
+WaterHullModel::Point3 waterTestTransformPoint(const WaterHullPoseCache::Mesh &mesh,WaterHullModel::Point3 p)
+{
+ WaterHullModel::Point3 q;
+ q.x=mesh.transform[0][0]*p.x+mesh.transform[0][1]*p.y+mesh.transform[0][2]*p.z+mesh.transform[0][3];
+ q.y=mesh.transform[1][0]*p.x+mesh.transform[1][1]*p.y+mesh.transform[1][2]*p.z+mesh.transform[1][3];
+ q.z=mesh.transform[2][0]*p.x+mesh.transform[2][1]*p.y+mesh.transform[2][2]*p.z+mesh.transform[2][3];return q;
+}
+double waterTestSliceMinimumX(const WaterHullPoseCache::Mesh &mesh,bool contact)
+{
+ using namespace WaterHullModel;
+ const Point3 vertices[8]={{-285,-70,-.282f},{285,-70,-.282f},{285,30,-.282f},{-285,30,-.282f},
+ {-285,-70,50},{285,-70,50},{285,30,50},{-285,30,50}};
+ const unsigned triangles[12][3]={{0,2,1},{0,3,2},{4,5,6},{4,6,7},{0,1,5},{0,5,4},
+ {1,2,6},{1,6,5},{2,3,7},{2,7,6},{3,0,4},{3,4,7}};
+ std::vector<Point> points;
+ for(const auto &t:triangles) {
+ const Point3 a=waterTestTransformPoint(mesh,vertices[t[0]]),b=waterTestTransformPoint(mesh,vertices[t[1]]),
+ c=waterTestTransformPoint(mesh,vertices[t[2]]);
+ CHECK(contact?WaterHullContact::ProjectTriangle(a,b,c,3,points):SliceTriangle(a,b,c,points));
+ }
+ CHECK(points.size()>=3);double minimum=1e30;
+ for(Point p:points) minimum=(std::min)(minimum,double(p.x));return minimum;
+}
+}
+
+TEST(water_hull_pose_cache_refreshes_old_rotation_bucket_at_both_drafts)
+{
+ using namespace WaterHullPoseCache;
+ for(float draft:{0.0f,6.375f}) {
+ const float angle0=.0351f,angle1=.0449f;
+ const Mesh old=waterTestHullPose(angle0,draft),current=waterTestHullPose(angle1,draft);
+ // Armed reproduction of the old signature: these different rotations have identical
+ // hundredth-rounded coefficients, despite moving the long hull by several world units.
+ for(unsigned i=0;i<3;++i) for(unsigned j=0;j<4;++j)
+ CHECK(std::llround(old.transform[i][j]*100.0f)==std::llround(current.transform[i][j]*100.0f));
+ CHECK(VertexMovementBound(old,current)>2);
+ Cache cache;unsigned sliceCalls=0;double cachedMinimum[2]={};
+ auto updateSlice=[&](const Mesh &pose) {
+ const std::vector<Mesh> meshes{pose};
+ if(!cache.Reusable(meshes,3)) {
+ for(unsigned contact=0;contact<2;++contact) cachedMinimum[contact]=waterTestSliceMinimumX(pose,contact!=0);
+ ++sliceCalls;CHECK(cache.Store(meshes,3));
+ }
+ };
+ updateSlice(old);CHECK(sliceCalls==1);
+ const double savedMean=cachedMinimum[0],savedContact=cachedMinimum[1];
+ for(unsigned repeat=0;repeat<20;++repeat) updateSlice(old);
+ const Mesh noise=waterTestHullPose(angle0+.000001f,draft);
+ CHECK(VertexMovementBound(old,noise)<MaxVertexMovement);
+ // Actual-height triangle contact cannot reuse even this small rotation: near-tangent
+ // slice endpoints amplify it. The default mean-water cache keeps its old tolerance.
+ CHECK(cache.Reusable(std::vector<Mesh>{old},3,0));
+ CHECK(!cache.Reusable(std::vector<Mesh>{noise},3,0));
+ CHECK(!cache.Reusable(std::vector<Mesh>{old},3,-1));
+ CHECK(!cache.Reusable(std::vector<Mesh>{old},3,std::numeric_limits<double>::infinity()));
+ updateSlice(noise);
+ CHECK(sliceCalls==1 && cachedMinimum[0]==savedMean && cachedMinimum[1]==savedContact);
+ CHECK(std::abs(waterTestSliceMinimumX(noise,true)-savedContact)>.0001); // a genuinely stale-but-reusable slice
+ CHECK(!cache.Reusable(std::vector<Mesh>{current},3));
+ for(bool contact:{false,true}) {
+ const double h=draft+(contact?3:0),z=-.282;
+ // Independent analytic intersection of the tilted lower face with the upper slice
+ // plane. The chosen fixture intersects strictly inside its570-unit long side.
+ const double expected0=(z-std::cos(double(angle0))*h)/std::sin(double(angle0));
+ const double expected1=(z-std::cos(double(angle1))*h)/std::sin(double(angle1));
+ const double stale=waterTestSliceMinimumX(old,contact),exact=waterTestSliceMinimumX(current,contact);
+ CHECK(std::abs(stale-expected0)<.002 && std::abs(exact-expected1)<.002);
+ CHECK(std::abs(stale-exact)>1); // Both actual planes expose a stale contour.
+ }
+ updateSlice(current);CHECK(sliceCalls==2);
+ CHECK(cachedMinimum[0]==waterTestSliceMinimumX(current,false) && cachedMinimum[1]==waterTestSliceMinimumX(current,true));
+ updateSlice(current);CHECK(sliceCalls==2 && cache.Reusable(std::vector<Mesh>{current},3));
+ }
+}
+
+TEST(water_hull_pose_error_bounds_every_transformed_local_aabb_corner)
+{
+ using namespace WaterHullPoseCache;
+ // Nonzero local origin, negative coordinates, scale and shear catch an extent-only R
+ // or a rotation-angle shortcut. True movement is evaluated independently at all corners.
+ const float center[3]={1000,-700,250},extent[3]={285,50,25};
+ const double radius=SupportRadius(center,extent);
+ CHECK(radius>std::sqrt(285.0*285+50.0*50+25.0*25)*4);
+ for(unsigned fixture=0;fixture<96;++fixture) {
+ Mesh a=waterTestHullPose(),b=a;a.supportRadius=b.supportRadius=radius;
+ for(unsigned i=0;i<3;++i) for(unsigned j=0;j<4;++j)
+ b.transform[i][j]+=float(std::sin(fixture*.71+i*1.31+j*.47)*(j==3?.07:.004));
+ const double bound=VertexMovementBound(a,b);CHECK(std::isfinite(bound) && bound>=0);
+ for(unsigned corner=0;corner<8;++corner) {
+ double squared=0;
+ for(unsigned i=0;i<3;++i) {
+ double q0=a.transform[i][3],q1=b.transform[i][3];
+ for(unsigned j=0;j<3;++j) {
+ const double p=double(center[j])+((corner&(1u<<j))?extent[j]:-double(extent[j]));
+ q0+=double(a.transform[i][j])*p;q1+=double(b.transform[i][j])*p;
+ }
+ squared+=(q1-q0)*(q1-q0);
+ }
+ CHECK(std::sqrt(squared)<=bound+1e-10);
+ }
+ }
+ float badExtent[3]={1,-1,2};CHECK(!std::isfinite(SupportRadius(center,badExtent)));
+ badExtent[1]=NAN;CHECK(!std::isfinite(SupportRadius(center,badExtent)));
+}
+
+TEST(water_hull_pose_cache_accumulates_translation_and_rotation_against_sliced_pose)
+{
+ using namespace WaterHullPoseCache;
+ Mesh original=waterTestHullPose();std::vector<Mesh> current{original};Cache cache;
+ CHECK(!cache.Reusable(current,3));CHECK(cache.Store(current,3));
+ for(int repeat=0;repeat<100;++repeat) CHECK(cache.Reusable(current,3));
+ current[0].transform[0][3]=.0001f;current[0].transform[1][3]=-.0001f;
+ CHECK(cache.Reusable(current,3)); // cancellation noise still reuses the original slice
+ unsigned refreshes=0;Mesh previous=original;
+ for(unsigned frame=1;frame<=24;++frame) {
+ current[0]=original;current[0].transform[0][3]=frame*.002f;
+ CHECK(VertexMovementBound(previous,current[0])<MaxVertexMovement); // previous-frame-only control would miss drift
+ if(!cache.Reusable(current,3)) { ++refreshes;CHECK(cache.Store(current,3)); }
+ previous=current[0];
+ }
+ CHECK(refreshes>=4);
+ CHECK(cache.Store(std::vector<Mesh>{original},3));
+ for(unsigned step=1;step<=4;++step) {
+ current[0]=waterTestHullPose(step*.000001f);
+ CHECK(cache.Reusable(current,3));
+ }
+ current[0]=waterTestHullPose(.00003f);CHECK(!cache.Reusable(current,3));
+ // Store copied the original pose; editing the caller's vector never edits the snapshot.
+ cache.Clear();CHECK(cache.Size()==0 && !cache.Reusable(current,3));
+}
+
+TEST(water_hull_pose_cache_refreshes_geometry_membership_flags_and_crest)
+{
+ using namespace WaterHullPoseCache;
+ Mesh a=waterTestHullPose(),b=a;static int other;
+ std::vector<Mesh> original{a};Cache cache;CHECK(cache.Store(original,3));
+ auto rejects=[&](const Mesh &changed) { CHECK(!cache.Reusable(std::vector<Mesh>{changed},3)); };
+ b.identity=&other;rejects(b);b=a;b.vertexArray=&other;rejects(b);b=a;b.triangleArray=&other;rejects(b);
+ b=a;++b.vertexCount;rejects(b);b=a;++b.triangleCount;rejects(b);
+ b=a;b.crossesMean=false;rejects(b);b=a;b.supportRadius+=1;rejects(b);
+ CHECK(cache.Reusable(original,2.995));CHECK(!cache.Reusable(original,2.98));
+ b=a;b.transform[0][3]=.009f;
+ CHECK(cache.Reusable(std::vector<Mesh>{b},3));CHECK(!cache.Reusable(std::vector<Mesh>{b},2.998));
+ CHECK(!cache.Reusable(std::vector<Mesh>{},3));CHECK(!cache.Reusable(std::vector<Mesh>{a,a},3));
+ b=a;b.identity=&other;CHECK(cache.Store(std::vector<Mesh>{a,b},3));
+ CHECK(cache.Reusable(std::vector<Mesh>{a,b},3));CHECK(!cache.Reusable(std::vector<Mesh>{b,a},3));
+ // Invalid data cannot even reuse its own identical-looking cached state.
+ b=a;b.transform[2][1]=NAN;CHECK(!cache.Store(std::vector<Mesh>{b},3));CHECK(cache.Size()==0);
+ CHECK(!cache.Reusable(std::vector<Mesh>{b},3));CHECK(!cache.Store(original,NAN));
+ b=a;b.supportRadius=INFINITY;CHECK(!cache.Store(std::vector<Mesh>{b},3));
+ CHECK(cache.Store(std::vector<Mesh>(MaxMeshes,a),3));CHECK(cache.Size()==MaxMeshes);
+ CHECK(!cache.Reusable(std::vector<Mesh>(MaxMeshes+1,a),3));
+ CHECK(!cache.Store(std::vector<Mesh>(MaxMeshes+1,a),3));CHECK(cache.Size()==0);
+ CHECK(cache.Store(std::vector<Mesh>{},3));CHECK(cache.Reusable(std::vector<Mesh>{},3)); // stable empty slice
+}
+
+TEST(water_foam_line_integral_is_partition_invariant_and_has_no_endpoint_beads)
+{
+ using namespace WaterFoamHistory;
+ const double radius=3.75,speed=30,length=120;
+ for(double along:{-3.0,0.0,1.0,15.0,18.75,60.0,118.0,120.0,123.0})
+ for(double side:{0.0,1.5,3.74,3.75,4.0}) {
+ const auto whole=IntegrateKernel(along,side*side,length,radius);
+ double mass=0,moment=0;
+ for(unsigned section=0;section<16;++section) {
+ const double begin=section*7.5;
+ const auto part=IntegrateKernel(along-begin,side*side,7.5,radius);
+ mass+=part.mass/16;moment+=part.mass/16*(begin+part.mean*7.5)/length;
+ }
+ CHECK(std::abs(mass-whole.mass)<1e-13);
+ CHECK(std::abs(moment-whole.mass*whole.mean)<1e-13);
+ CHECK(whole.mass>=0 && whole.mass<=1 && whole.mean>=0 && whole.mean<=1);
+ // Independent scalar Simpson integration of the unclipped radial kernel. This
+ // detects a matching algebra mistake in the whole and partitioned analytic path.
+ const unsigned samples=8192;double reference=0;
+ for(unsigned i=0;i<=samples;++i) {
+ const double offset=length*i/samples-along;
+ const double value=(std::max)(0.0,1-(offset*offset+side*side)/(radius*radius));
+ reference+=value*value*(i==0||i==samples?1:i%2?4:2);
+ }
+ reference/=3*samples;
+ CHECK(std::abs(reference-whole.mass)<2e-8);
+ }
+ const double expected=(16.0/15)*radius/speed;
+ for(double position:{15.0,18.75,30.0,33.75,60.0,63.75,90.0,93.75}) {
+ double dose=0;
+ for(unsigned section=0;section<16;++section)
+ dose+=.25*IntegrateKernel(position-section*7.5,0,7.5,radius).mass;
+ CHECK(std::abs(dose-expected)<1e-13); // Joint and mid-section are equally dense.
+ }
+ // Armed old algorithm: a constant capsule plus each rounded cap doubles the
+ // density at a shared endpoint while a half-section has one contribution.
+ auto oldDose=[&](double position) {
+ double dose=0;
+ for(unsigned section=0;section<16;++section) {
+ const double begin=section*7.5,nearest=Clamp(position,begin,begin+7.5),distance=position-nearest;
+ const double kernel=(std::max)(0.0,1-distance*distance/(radius*radius));
+ dose+=.25*kernel*kernel;
+ }
+ return dose;
+ };
+ CHECK(oldDose(60)>1.9*oldDose(63.75));
+ const auto point=IntegrateKernel(0,0,0,radius);CHECK(point.mass==1 && point.mean==.5);
+ CHECK(IntegrateKernel(0,0,1,0).mass==0);
+ CHECK(IntegrateKernel(NAN,0,1,radius).mass==0);
+ CHECK(IntegrateKernel(0,-1,1,radius).mass==0);
+ const auto tiny=IntegrateKernel(5e-8,0,1e-7,radius);
+ CHECK(std::abs(tiny.mass-1)<1e-12 && std::abs(tiny.mean-.5)<1e-9);
+}
+
+TEST(water_foam_window_covers_rts_frustum_and_has_bounded_resize_fallback)
+{
+ using WaterFoamWindow::Point;using WaterFoamWindow::Choose;
+ const Point camera={125.3,-54.1,430};const double level=4,diagonal=std::sqrt(.5);
+ auto raysFor=[&](double aspect,Point rays[5]) {
+ rays[0]={0,diagonal,-diagonal};unsigned at=1;
+ for(double vertical:{-1.0,1.0}) for(double horizontal:{-1.0,1.0})
+ rays[at++]={horizontal*.45*aspect,diagonal*(1+vertical*.45),diagonal*(-1+vertical*.45)};
+ };
+ Point rays[5];raysFor(16.0/9,rays);const auto map=Choose(camera,rays,level);
+ // Freeze the pre-horizon-fix RTS mapping, including the non-power-of-two texel pitch.
+ CHECK(map.originX==-957 && map.originY==-38 && map.widthWorld==2112 && map.heightWorld==1216);
+ CHECK(map.widthPixels==512 && map.heightPixels==512);
+ CHECK(map.widthWorld>=256 && map.widthWorld<=4096 && map.heightWorld>=256 && map.heightWorld<=4096);
+ for(unsigned i=0;i<5;++i) {
+ const double time=(level-camera.z)/rays[i].z;
+ const double x=camera.x+rays[i].x*time,y=camera.y+rays[i].y*time;
+ CHECK(x-map.originX>=32 && map.originX+map.widthWorld-x>=32);
+ CHECK(y-map.originY>=32 && map.originY+map.heightWorld-y>=32);
+ }
+ const auto pan=Choose({camera.x+.000001,camera.y+.000001,camera.z},rays,level);
+ CHECK(pan.originX==map.originX && pan.originY==map.originY);
+ // An equal-aspect viewport resize preserves world mapping; a wider FOV expands it.
+ Point resized[5];raysFor(1920.0/1080,resized);const auto same=Choose(camera,resized,level);
+ CHECK(same.originX==map.originX && same.originY==map.originY && same.widthWorld==map.widthWorld);
+ raysFor(21.0/9,resized);const auto wide=Choose(camera,resized,level);
+ CHECK(wide.widthWorld>map.widthWorld && wide.heightWorld==map.heightWorld);
+ CHECK(wide.originX==-1260 && wide.originY==-38 && wide.widthWorld==2688 && wide.heightWorld==1216);
+ Point horizon[5]={{1,0,-1e-8},{1,-1,0},{1,1,0},{1,-1,-.1},{1,1,-.1}};
+ for(const auto fallback:{Choose(camera,horizon,level),Choose({0,0,-3},rays,level)}) {
+ CHECK(fallback.widthWorld==4096 && fallback.heightWorld==4096);
+ CHECK(std::isfinite(fallback.originX) && std::isfinite(fallback.originY));
+ CHECK(fallback.widthPixels==512 && fallback.heightPixels==512);
+ }
+}
+
+TEST(water_foam_horizon_window_preserves_near_water_across_yaw_pitch_and_resize)
+{
+ using WaterFoamWindow::Point;using WaterFoamWindow::Choose;
+ auto inside=[](const WaterFoamHistory::Mapping &map,Point p,double margin) {
+ return p.x-map.originX>=margin && map.originX+map.widthWorld-p.x>=margin &&
+ p.y-map.originY>=margin && map.originY+map.heightWorld-p.y>=margin;
+ };
+ // Armed regression: the former 4096-unit centre-ray focus placed this atlas at
+ // x=[2048,6144], excluding water that is plainly visible below a horizontal camera.
+ const Point horizontal[5]={{1,0,0},{1,-.5,-.5},{1,.5,-.5},{1,-.5,.5},{1,.5,.5}};
+ const auto concrete=Choose({0,0,30},horizontal,0);
+ CHECK(concrete.originX==-1024 && concrete.originY==-2048);
+ CHECK(inside(concrete,{0,0,0},128));
+ CHECK(inside(concrete,{60,-30,0},128) && inside(concrete,{60,30,0},128));
+ for(double yaw:{0.0,.37,1.5707963267948966,2.4,3.141592653589793,-2.1})
+ for(double pitch:{-.001,0.0,.1,.3,.6})
+ for(double aspect:{9.0/16,16.0/9,21.0/9,32.0/9}) {
+ const Point camera={-347.25,891.125,34};const double level=4;
+ const double cy=std::cos(yaw),sy=std::sin(yaw),cp=std::cos(pitch),sp=std::sin(pitch);
+ Point rays[5]={{cy*cp,sy*cp,sp}};unsigned at=1;
+ for(double vertical:{-1.0,1.0}) for(double horizontalSide:{-1.0,1.0})
+ rays[at++]={cy*cp-horizontalSide*.5*aspect*sy-vertical*.5*cy*sp,
+ sy*cp+horizontalSide*.5*aspect*cy-vertical*.5*sy*sp,sp+vertical*.5*cp};
+ const auto map=Choose(camera,rays,level);
+ CHECK(map.widthWorld==4096 && map.heightWorld==4096 && map.widthPixels==512 && map.heightPixels==512);
+ CHECK(inside(map,{camera.x,camera.y,level},128));
+ CHECK(std::fmod(map.originX,64)==0 && std::fmod(map.originY,64)==0);
+ unsigned nearHits=0;
+ for(unsigned i=1;i<5;++i) if(rays[i].z<0) {
+ const double time=(level-camera.z)/rays[i].z;
+ const Point hit={camera.x+rays[i].x*time,camera.y+rays[i].y*time,level};
+ // These lower-ray intersections all fit together with a substantial margin.
+ CHECK(std::hypot(hit.x-camera.x,hit.y-camera.y)<1024);
+ CHECK(inside(map,hit,128));++nearHits;
+ }
+ CHECK(nearHits==(pitch<.5?2u:0u));
+ }
+ // A very distant centre/upper hit must not displace finite nearby lower hits.
+ const Point far[5]={{1,0,-.000001},{1,-.4,-.2},{1,.4,-.2},{1,-.4,-.00001},{1,.4,-.00001}};
+ const auto prioritized=Choose({0,0,30},far,0);
+ CHECK(inside(prioritized,{150,-60,0},128) && inside(prioritized,{150,60,0},128));
+ CHECK(inside(prioritized,{0,0,0},128));
+ // Below-water and fully upward views remain finite and bounded without inventing
+ // negative-distance plane hits as part of the near-water footprint.
+ const auto below=Choose({0,0,-30},horizontal,0);
+ CHECK(inside(below,{60,-30,0},128) && inside(below,{60,30,0},128));
+ // A paused pan across two snap boundaries reconstructs exactly the same world trail
+ // in the overlap. This exercises real history rasterization with the chosen windows.
+ WaterFoamHistory::History history;
+ for(unsigned i=0;i<=4;++i) {
+ history.Advance(i*.25);history.Observe(1,foamTestHull(float(i)*7.5f,0,30,0),i*.25);
+ }
+ const auto first=Choose({0,0,37},horizontal,7),panned=Choose({128,0,37},horizontal,7);
+ CHECK(panned.originX-first.originX==128 && panned.originY==first.originY);
+ std::vector<std::uint32_t> a,b;CHECK(history.BuildAtlas(first,7,a) && history.BuildAtlas(panned,7,b));
+ bool identical=true;unsigned covered=0;
+ for(unsigned y=0;y<512;++y) for(unsigned x=16;x<512;++x) {
+ identical=identical && a[y*512+x]==b[y*512+x-16];covered+=a[y*512+x]!=0;
+ }
+ CHECK(identical && covered>0 && history.Time()==1.0);
+}
+
+TEST(water_foam_stern_spread_is_size_bounded_and_emission_remains_time_integrated)
+{
+ using namespace WaterFoamHistory;
+ Sample small,large,tiny,huge;
+ auto hull=foamTestHull(0,0,30,0);CHECK(MakeSample(hull,0,small));
+ hull.data[1][3]=74;CHECK(MakeSample(hull,0,large));
+ hull.data[1][3]=1;CHECK(MakeSample(hull,0,tiny));
+ hull.data[1][3]=4096;CHECK(MakeSample(hull,0,huge));
+ CHECK(std::abs(small.width[0]-2.8)<1e-12 && tiny.width[0]==2.5);
+ CHECK(large.width[0]>29 && large.width[0]<30 && huge.width[0]==30);
+ CHECK(small.width[0]/small.halfWidth>large.width[0]/large.halfWidth);
+ CHECK(small.width[1]==.65 && large.width[1]==3 && huge.width[1]==3);
+ CHECK(std::abs(small.rate[0]-2*(.8+.25*std::sqrt(30.0)))<1e-12);
+ CHECK(std::abs(small.rate[1]/small.rate[0]-.22)<1e-12);
+ // A short live section must accumulate by elapsed dose time. Repeating the same
+ // render cannot stamp another full-opacity blob, even with the stronger response.
+ const Mapping map={-12.5,-.5,1,1,1,1};History history;
+ history.Observe(1,foamTestHull(0,0,30,0),0);
+ std::vector<std::uint32_t> initial,first,duplicate,second;
+ CHECK(history.BuildAtlas(map,7,initial) && initial[0]==0);
+ history.Advance(.01);history.Observe(1,foamTestHull(.3f,0,30,0),.01);
+ CHECK(history.BuildAtlas(map,7,first));
+ for(unsigned pass=0;pass<20;++pass)
+ CHECK(!history.Observe(1,foamTestHull(.3f,0,30,0),.01));
+ CHECK(history.BuildAtlas(map,7,duplicate) && duplicate==first);
+ history.Advance(.02);history.Observe(1,foamTestHull(.6f,0,30,0),.02);
+ CHECK(history.BuildAtlas(map,7,second) && history.SegmentCount()==0);
+ const double coverage1=((first[0]>>16)&255)/255.0,coverage2=((second[0]>>16)&255)/255.0;
+ CHECK(coverage1>0 && coverage2<.2);
+ const double dose1=-std::log(1-coverage1),dose2=-std::log(1-coverage2);
+ CHECK(dose2>1.8*dose1 && dose2<2.2*dose1);
+}
+
+TEST(water_foam_history_fixed_time_sampling_is_frame_rate_invariant)
+{
+ using namespace WaterFoamHistory;
+ std::vector<Segment> reference;std::vector<std::uint32_t> referenceAtlas;
+ const Mapping mapping={-32,-32,192,64,192,64};
+ for(unsigned fps:{20u,30u,60u,120u}) {
+ History history;
+ for(unsigned frame=0;frame<=fps*4;++frame) {
+ const double time=double(frame)/fps;history.Advance(time);
+ history.Observe(1,foamTestHull(float(30*time),0,30,0),time);
+ }
+ CHECK(history.SegmentCount()==16 && history.TrackedCount()==1);
+ std::vector<std::uint32_t> atlas;CHECK(history.BuildAtlas(mapping,7,atlas));
+ if(reference.empty()) {reference=history.Segments();referenceAtlas=atlas;}
+ for(size_t i=0;i<reference.size();++i) {
+ const auto &a=reference[i],&b=history.Segments()[i];
+ CHECK(a.begin.time==b.begin.time && a.end.time==b.end.time);
+ for(int lane=0;lane<3;++lane) {
+ CHECK(Distance(a.begin.lanes[lane],b.begin.lanes[lane])<0.00001);
+ CHECK(Distance(a.end.lanes[lane],b.end.lanes[lane])<0.00001);
+ }
+ }
+ unsigned total=0;
+ for(size_t i=0;i<atlas.size();++i) for(unsigned shift:{0u,8u,16u}) {
+ CHECK(std::abs(int((atlas[i]>>shift)&255)-int((referenceAtlas[i]>>shift)&255))<=1);
+ if(shift==16) total+=(atlas[i]>>shift)&255;
+ }
+ CHECK(total>10000); // Armed against an empty atlas satisfying timing invariance.
+ for(int pass=0;pass<100;++pass) {
+ CHECK(!history.Advance(4));CHECK(!history.Observe(1,foamTestHull(120,0,30,0),4));
+ }
+ std::vector<std::uint32_t> paused;CHECK(history.BuildAtlas(mapping,7,paused));CHECK(atlas==paused);
+ }
+}
+
+TEST(water_foam_history_turns_preserve_old_world_paths_and_stops_leave_fading_remnants)
+{
+ using namespace WaterFoamHistory;
+ History history;
+ for(unsigned frame=0;frame<=120;++frame) {
+ const double t=frame/30.0,angle=t*0.4;
+ history.Advance(t);history.Observe(1,foamTestHull(float(70*std::sin(angle)),float(70*(1-std::cos(angle))),
+ float(28*std::cos(angle)),float(28*std::sin(angle)),float(angle)),t);
+ }
+ CHECK(history.SegmentCount()==16);
+ const Segment first=history.Segments().front();const Segment last=history.Segments().back();
+ CHECK(Distance(first.begin.lanes[0],{-12,0})<1e-7);
+ CHECK(last.end.lanes[0].y>55); // The history follows the curve, not one current-heading ray.
+ const auto stopped=foamTestHull(float(70*std::sin(1.6)),float(70*(1-std::cos(1.6))),30,0,1.6f);
+ for(unsigned frame=121;frame<=150;++frame) {const double t=frame/30.0;history.Advance(t);history.Observe(1,stopped,t);}
+ const size_t stoppedCount=history.SegmentCount();CHECK(stoppedCount>=16 && stoppedCount<=17);
+ CHECK(Distance(history.Segments().front().begin.lanes[0],first.begin.lanes[0])==0);
+ const Mapping mapping={-64,-64,192,192,192,192};std::vector<std::uint32_t> fresh,old;
+ CHECK(history.BuildAtlas(mapping,7,fresh));
+ for(unsigned frame=151;frame<=300;++frame) {const double t=frame/30.0;history.Advance(t);history.Observe(1,stopped,t);}
+ CHECK(history.SegmentCount()==stoppedCount);CHECK(history.BuildAtlas(mapping,7,old));
+ unsigned freshDensity=0,oldDensity=0,freshChurn=0,oldChurn=0;
+ for(size_t i=0;i<fresh.size();++i) {freshDensity+=(fresh[i]>>16)&255;oldDensity+=(old[i]>>16)&255;
+ freshChurn+=fresh[i]&255;oldChurn+=old[i]&255;}
+ CHECK(oldDensity>0 && oldDensity<freshDensity && oldChurn<freshChurn);
+ history.Advance(30);CHECK(history.SegmentCount()==0);CHECK(history.BuildAtlas(mapping,7,old));
+ for(auto pixel:old) CHECK(pixel==0);
+}
+
+TEST(water_foam_history_held_logic_transforms_do_not_reduce_emission_at_high_render_fps)
+{
+ using namespace WaterFoamHistory;
+ const Mapping map={-32,-32,256,64,256,64};
+ std::vector<std::uint32_t> reference;unsigned referenceDensity=0;
+ for(unsigned fps:{30u,60u,120u}) {
+ History history;
+ for(unsigned frame=0;frame<=fps*6;++frame) {
+ const double time=double(frame)/fps;
+ const unsigned logicFrame=(frame*30)/fps;
+ history.Advance(time);history.Observe(1,foamTestHull(float(logicFrame),0,30,0),time);
+ }
+ CHECK(history.SegmentCount()==24);
+ std::vector<std::uint32_t> atlas;CHECK(history.BuildAtlas(map,7,atlas));unsigned density=0;
+ for(auto pixel:atlas) density+=(pixel>>16)&255;
+ if(reference.empty()) {reference=atlas;referenceDensity=density;}
+ // Different first render phases locate a fixed-time sample at most half a logic
+ // step apart. Integrated density stays close, and the trail remains in the same cells.
+ CHECK(density>0 && std::abs(double(density)-referenceDensity)<referenceDensity*0.04);
+ for(size_t i=0;i<atlas.size();++i)
+ CHECK(std::abs(int((atlas[i]>>16)&255)-int((reference[i]>>16)&255))<=12);
+ const size_t moving=history.SegmentCount();
+ for(unsigned frame=fps*6+1;frame<=fps*8;++frame) {
+ const double time=double(frame)/fps;history.Advance(time);
+ history.Observe(1,foamTestHull(180,0,30,0),time); // Deliberately stale filtered speed.
+ }
+ CHECK(history.SegmentCount()==moving);
+ }
+ History neverMoved;
+ for(unsigned frame=0;frame<=120;++frame) {
+ const double time=frame/30.0;neverMoved.Advance(time);
+ neverMoved.Observe(1,foamTestHull(0,0,30,0),time);
+ }
+ CHECK(neverMoved.SegmentCount()==0); // A new stationary object with stale speed cannot emit.
+}
+
+TEST(water_foam_history_live_tail_closes_fast_stern_gaps_without_duplicate_sections)
+{
+ using namespace WaterFoamHistory;
+ const Mapping map={-32,-16,160,32,320,64};std::vector<std::uint32_t> reference;
+ for(unsigned fps:{30u,60u,120u}) {
+ History history;
+ for(unsigned frame=0;double(frame)/fps<0.37;++frame) {
+ const double time=double(frame)/fps;history.Advance(time);
+ history.Observe(1,foamTestHull(float(time*250),0,250,0),time);
+ }
+ history.Advance(.37);history.Observe(1,foamTestHull(92.5f,0,250,0),.37);
+ CHECK(history.SegmentCount()==1); // The live .25→.37 tail remains uncommitted.
+ std::vector<std::uint32_t> atlas;CHECK(history.BuildAtlas(map,7,atlas));
+ const unsigned sternX=unsigned((80.5-map.originX)/map.widthWorld*map.widthPixels);
+ CHECK(((atlas[32*320+sternX]>>16)&255)>3); // Armed: committed-only history ends30 units earlier.
+ if(reference.empty()) reference=atlas;
+ for(size_t i=0;i<atlas.size();++i) for(unsigned shift:{0u,8u,16u})
+ CHECK(std::abs(int((atlas[i]>>shift)&255)-int((reference[i]>>shift)&255))<=1);
+ CHECK(!history.Advance(.37));CHECK(!history.Observe(1,foamTestHull(92.5f,0,250,0),.37));
+ std::vector<std::uint32_t> paused;CHECK(history.BuildAtlas(map,7,paused));CHECK(atlas==paused);
+ // Stopping preserves the dose's true end time. Committing that already-visible partial
+ // at the next fixed boundary cannot increase coverage or duplicate its contribution.
+ history.Advance(.39);history.Observe(1,foamTestHull(92.5f,0,250,0),.39);
+ history.Advance(.5);std::vector<std::uint32_t> before,after;
+ CHECK(history.BuildAtlas(map,7,before));history.Observe(1,foamTestHull(92.5f,0,250,0),.5);
+ CHECK(history.BuildAtlas(map,7,after));CHECK(before==after && history.SegmentCount()==2);
+ CHECK(history.Segments().back().end.time==.37);
+ for(int step=3;step<=8;++step) {const double time=step*.25;history.Advance(time);
+ history.Observe(1,foamTestHull(92.5f,0,250,0),time);}
+ CHECK(history.SegmentCount()==2 && history.Segments().back().end.time==.37);
+ }
+ for(double time:{.01,.06,.12,.24,.25,.26}) {
+ History history;history.Observe(1,foamTestHull(0,0,250,0),0);
+ CHECK(!history.HasFoam());
+ history.Advance(time);history.Observe(1,foamTestHull(float(time*250),0,250,0),time);
+ CHECK(history.HasFoam());
+ std::vector<std::uint32_t> atlas;CHECK(history.BuildAtlas(map,7,atlas));
+ const unsigned x=unsigned((time*250-12-map.originX)/map.widthWorld*map.widthPixels);
+ CHECK(((atlas[32*320+x]>>16)&255)>1);
+ }
+}
+
+TEST(water_foam_history_true_motion_ignores_contact_center_bobbing_after_stop)
+{
+ using namespace WaterFoamHistory;
+ History steady,tilting;const Mapping map={-32,-16,128,32,256,64};
+ for(double time:{0.0,.1,.2,.3,.37}) {
+ const Point origin={time*30,0};const auto hull=foamTestHull(float(origin.x),0,30,0);
+ steady.Advance(time);tilting.Advance(time);
+ steady.Observe(1,hull,time,true,false,&origin);tilting.Observe(1,hull,time,true,false,&origin);
+ }
+ CHECK(steady.SegmentCount()==1 && tilting.SegmentCount()==1);
+ const Point stoppedOrigin={11.1,0};
+ for(unsigned step=4;step<=30;++step) {
+ const double time=step*.1;const float offset=float(std::sin(time*13)*2);
+ steady.Advance(time);tilting.Advance(time);
+ steady.Observe(1,foamTestHull(11.1f,0,30,0),time,true,false,&stoppedOrigin);
+ // The actual contour and its lanes continue moving as the hull tilts, while
+ // the velocity filter deliberately retains its previous30-unit/s speed.
+ tilting.Observe(1,foamTestHull(11.1f+offset,offset*.4f,30,0),time,true,false,&stoppedOrigin);
+ std::vector<std::uint32_t> a,b;CHECK(steady.BuildAtlas(map,7,a) && tilting.BuildAtlas(map,7,b));
+ CHECK(a==b && steady.SegmentCount()==tilting.SegmentCount());
+ }
+ CHECK(tilting.SegmentCount()==2 && tilting.Segments().back().end.time==.37);
+ // Without the independent motion coordinate, this residual-speed contour motion
+ // is incorrectly classified as translation and emits new stationary foam.
+ History oldBehavior;
+ for(unsigned step=0;step<=10;++step) {
+ const double time=step*.1;oldBehavior.Advance(time);
+ oldBehavior.Observe(1,foamTestHull(float(std::sin(time*13)*2),0,30,0),time);
+ }
+ CHECK(oldBehavior.SegmentCount()>0);
+ const Point invalid={NAN,0};tilting.Advance(3.1);
+ CHECK(!tilting.Observe(1,foamTestHull(11.1f,0,30,0),3.1,true,false,&invalid));
+ CHECK(tilting.TrackedCount()==0 && tilting.SegmentCount()==2);
+}
+
+TEST(water_foam_history_removal_and_reentry_keep_the_existing_partial_tail)
+{
+ using namespace WaterFoamHistory;
+ History history;const Mapping map={-32,-16,128,32,128,32};
+ history.Observe(1,foamTestHull(0,0,100,0),0);
+ history.Advance(.12);history.Observe(1,foamTestHull(12,0,100,0),.12);
+ std::vector<std::uint32_t> before,after;CHECK(history.BuildAtlas(map,7,before));
+ CHECK(history.SegmentCount()==0);
+ history.Observe(1,foamTestHull(12,0,100,0),.12,false);
+ CHECK(history.BuildAtlas(map,7,after));CHECK(before==after);
+ CHECK(history.SegmentCount()==1 && history.TrackedCount()==0);
+ history.Advance(.2);CHECK(!history.Observe(1,foamTestHull(10000,0,100,0),.2));
+ CHECK(history.SegmentCount()==1); // A new anchor cannot connect the retained trail to a teleport.
+ history.Advance(25);CHECK(history.SegmentCount()==0);
+ CHECK(!history.Observe(1,foamTestHull(10001,0,100,0),25));CHECK(history.SegmentCount()==0);
+}
+
+TEST(water_foam_history_breaks_spawns_teleports_hidden_gaps_levels_and_reverse_jumps)
+{
+ using namespace WaterFoamHistory;
+ History history;CHECK(!history.Observe(7,foamTestHull(0,0,30,0),0));
+ for(int i=1;i<=4;++i) {history.Advance(i*.25);history.Observe(7,foamTestHull(i*7.5f,0,30,0),i*.25);}
+ CHECK(history.SegmentCount()==4);const size_t before=history.SegmentCount();
+ history.Advance(1.1); // Omitted observation breaks a connection even if the gap is short.
+ history.Advance(1.25);CHECK(!history.Observe(7,foamTestHull(37.5f,0,30,0),1.25));
+ history.Advance(1.5);CHECK(!history.Observe(7,foamTestHull(10000,0,30,0),1.5));
+ history.Advance(1.75);CHECK(!history.Observe(7,foamTestHull(10001,0,30,0),1.75,true,true));
+ history.Advance(2);CHECK(!history.Observe(7,foamTestHull(10002,0,30,0,0,9),2));
+ history.Advance(2.25);CHECK(!history.Observe(7,foamTestHull(10003,0,30,0,0,9),2.25,false));
+ history.Advance(2.5);CHECK(!history.Observe(7,foamTestHull(10004,0,30,0,0,9),2.5));
+ CHECK(history.SegmentCount()==before);
+ // A reversal moves the chosen stern to the other end of this hull. Do not paint the
+ // interpolation across its deck as a long wake, even when the hull center barely moved.
+ history.Advance(2.75);CHECK(!history.Observe(7,foamTestHull(10003,0,-30,0,0,9),2.75));
+ CHECK(history.SegmentCount()==before);
+ history.Advance(4);CHECK(!history.Observe(7,foamTestHull(10000,0,-30,0,0,9),4));
+ history.Advance(0.5);CHECK(history.SegmentCount()==0 && history.TrackedCount()==0);
+ CHECK(!history.Observe(7,foamTestHull(12,0,30,0),0.5));
+ History fast;fast.Observe(1,foamTestHull(0,0,250,0),0);
+ fast.Advance(.25);CHECK(fast.Observe(1,foamTestHull(400,0,250,0),.25)); // Accelerated native simulation is allowed.
+}
+
+TEST(water_foam_atlas_world_mapping_levels_and_inputs_are_bounded)
+{
+ using namespace WaterFoamHistory;
+ History history;
+ for(int i=0;i<=8;++i) {history.Advance(i*.25);history.Observe(1,foamTestHull(i*4.0f,0,16,0),i*.25);}
+ const Mapping wide={-64,-64,128,128,128,128},crop={-32,-32,64,64,64,64};
+ std::vector<std::uint32_t> a,b;CHECK(history.BuildAtlas(wide,7,a));CHECK(history.BuildAtlas(crop,7,b));
+ for(unsigned y=0;y<64;++y) for(unsigned x=0;x<64;++x) {
+ CHECK(b[y*64+x]==a[(y+32)*128+x+32]);
+ const unsigned pixel=b[y*64+x],r=(pixel>>16)&255,g=(pixel>>8)&255,churn=pixel&255;
+ CHECK((pixel>>24)==0 && g<=r && churn<=r);
+ }
+ CHECK(history.BuildAtlas(wide,8,b));for(auto pixel:b) CHECK(pixel==0);
+ CHECK(history.BuildAtlas({10000,10000,128,128,128,128},7,b));for(auto pixel:b) CHECK(pixel==0);
+ CHECK(!history.BuildAtlas({0,0,1,1,513,512},7,b) && b.empty());
+ CHECK(!history.BuildAtlas({0,0,0,1,1,1},7,b) && b.empty());
+ CHECK(!history.BuildAtlas({NAN,0,1,1,1,1},7,b) && b.empty());
+ auto bad=foamTestHull(0,0,0,0);bad.data[2][0]=NAN;
+ history.Advance(2.25);CHECK(!history.Observe(1,bad,2.25));CHECK(history.TrackedCount()==0);
+ history.Advance(NAN);CHECK(history.SegmentCount()==0 && history.TrackedCount()==0);
+ History stationary;
+ for(int i=0;i<=120;++i) {stationary.Advance(i*.25);stationary.Observe(1,foamTestHull(0,0,0,0),i*.25);}
+ CHECK(stationary.SegmentCount()==0);
+}
+
+TEST(water_foam_history_capacity_is_bounded_under_many_vessels)
+{
+ using namespace WaterFoamHistory;
+ History history;
+ for(unsigned id=0;id<MaxEmitters+10;++id) history.Observe(id,foamTestHull(0,float(id*20),30,0),0);
+ CHECK(history.TrackedCount()==MaxEmitters);
+ history.Clear();
+ for(unsigned frame=0;frame<=96;++frame) {
+ const double time=frame*.25;history.Advance(time);
+ for(unsigned id=0;id<16;++id) history.Observe(id,foamTestHull(float(time*30),float(id*20),30,0),time);
+ CHECK(history.SegmentCount()<=MaxSegments && history.TrackedCount()<=MaxEmitters);
+ }
+ CHECK(history.SegmentCount()==MaxSegments);
+ for(const Segment &s:history.Segments()) CHECK(s.end.time>=history.Time()-Lifetime && s.begin.time<s.end.time);
+}
+
+// Recorded wake orientation is an axial moment, not current vessel heading or
+// wave travel direction. Quantization tolerances below follow the ARGB8 packing.
+struct FoamDirectionDecoded {
+ unsigned alpha=0;
+ double x=0,y=0,width=0;
+};
+static FoamDirectionDecoded foamDecodeDirection(std::uint32_t p)
+{
+ FoamDirectionDecoded d;d.alpha=p>>24;
+ if(d.alpha) {d.x=(2.0*((p>>16)&255)-d.alpha)/d.alpha;
+ d.y=(2.0*((p>>8)&255)-d.alpha)/d.alpha;
+ d.width=32.0*(p&255)/d.alpha;}
+ return d;
+}
+static bool foamDirectionAtlas(const WaterFoamHistory::History &history,
+ const WaterFoamHistory::Mapping &mapping,float level,
+ std::vector<std::uint32_t> &base,std::vector<std::uint32_t> &direction)
+{
+ std::vector<std::uint32_t> legacy;
+ const bool oldOk=history.BuildAtlas(mapping,level,legacy);
+ const bool newOk=history.BuildAtlas(mapping,level,base,&direction);
+ CHECK(oldOk==newOk && legacy==base); // The extra output cannot alter even one first-tile byte.
+ CHECK(direction.size()==base.size());
+ if(!newOk || direction.size()!=base.size()) return false;
+ for(size_t i=0;i<base.size();++i) {
+ const unsigned opacity=(base[i]>>16)&255,a=direction[i]>>24;
+ CHECK(a==opacity && (base[i]>>24)==0);
+ CHECK(((direction[i]>>16)&255)<=a && ((direction[i]>>8)&255)<=a && (direction[i]&255)<=a);
+ if(!a) CHECK(direction[i]==0);
+ }
+ return true;
+}
+
+// Independent direct quadrature of the deposited radial quartic. It does not call
+// IntegrateKernel, use its antiderivative/mean, or reproduce its float accumulator.
+// The radius-at-nearest-point and endpoint amplitude interpolation are deliberately
+// the established history model, rather than an assertion of exact fluid physics.
+struct FoamDirectionOracle {double density=0,x=0,y=0,width=0;};
+static FoamDirectionOracle foamDirectionOracle(const WaterFoamHistory::History &history,
+ WaterFoamHistory::Point p,unsigned steps=1024)
+{
+ using namespace WaterFoamHistory;
+ FoamDirectionOracle out;
+ auto clip=[](double x,double a,double b){return (std::max)(a,(std::min)(b,x));};
+ for(const Segment &s:history.Segments()) for(unsigned lane=0;lane<3;++lane) {
+ const double dx=s.end.lanes[lane].x-s.begin.lanes[lane].x;
+ const double dy=s.end.lanes[lane].y-s.begin.lanes[lane].y;
+ const double lengthSquared=dx*dx+dy*dy;
+ const double nearest=lengthSquared>1e-20?clip(((p.x-s.begin.lanes[lane].x)*dx+
+ (p.y-s.begin.lanes[lane].y)*dy)/lengthSquared,0,1):.5;
+ double amplitude[2],radius[2];
+ for(unsigned end=0;end<2;++end) {
+ const Sample &sample=end?s.end:s.begin;
+ const double age=clip(history.Time()-sample.time,0,24),w=sample.width[lane];
+ const double aged=w+((lane==0?.28:.10)+std::sqrt(w)*(lane==0?.12:.06))*age;
+ const double u=clip((age-20)/4,0,1),fade=1-u*u*(3-2*u);
+ radius[end]=2.5*aged;
+ amplitude[end]=sample.rate[lane]*std::exp(-age/(lane==0?7:3.5))*fade*w*w/(aged*aged);
+ }
+ const double r=radius[0]+(radius[1]-radius[0])*nearest;
+ double density=0,width=0;
+ for(unsigned k=0;k<steps;++k) {
+ const double t=(k+.5)/steps;
+ const double x=p.x-s.begin.lanes[lane].x-t*dx,y=p.y-s.begin.lanes[lane].y-t*dy;
+ const double radial=(std::max)(0.0,1-(x*x+y*y)/(r*r));
+ const double dose=(s.end.time-s.begin.time)*radial*radial/steps;
+ const double a=amplitude[0]*(1-t),b=amplitude[1]*t;
+ density+=dose*(a+b);
+ width+=dose*(a*s.begin.width[lane]+b*s.end.width[lane]);
+ }
+ out.density+=density;out.width+=width;
+ if(lengthSquared>1e-12) {out.x+=density*(dx*dx-dy*dy)/lengthSquared;
+ out.y+=density*2*dx*dy/lengthSquared;}
+ }
+ if(out.density>0) {out.x/=out.density;out.y/=out.density;out.width/=out.density;}
+ return out;
+}
+static void foamCheckDirectionOracle(std::uint32_t pixel,const FoamDirectionOracle &expected)
+{
+ const FoamDirectionDecoded d=foamDecodeDirection(pixel);
+ CHECK(d.alpha>10 && expected.density>0);
+ if(!d.alpha || expected.density<=0) return;
+ CHECK_NEAR(double(d.alpha),255*(1-std::exp(-expected.density)),.501);
+ // R and A round independently: |decoded moment error| <= (1+.5*(1+|q|))/A.
+ CHECK_NEAR(d.x,expected.x,2.0/d.alpha+2e-5);
+ CHECK_NEAR(d.y,expected.y,2.0/d.alpha+2e-5);
+ CHECK_NEAR(d.width,expected.width,16*(1+expected.width/32)/d.alpha+2e-5);
+}
+
+TEST(water_foam_direction_uses_recorded_translation_and_is_axial_under_reversal)
+{
+ using namespace WaterFoamHistory;
+ const Mapping map={-96,-96,192,192,96,96};
+ struct Case {float vx,vy,heading;double x,y;};
+ const Case cases[]={{30,0,0,1,0},{-30,0,0,1,0},{0,30,0,-1,0},
+ {0,-30,0,-1,0},{24,24,0,0,1},{-24,-24,0,0,1},{24,-24,0,0,-1}};
+ for(const Case &c:cases) {
+ History history;
+ for(unsigned i=0;i<=8;++i) {const double t=i*.25;history.Advance(t);
+ history.Observe(1,foamTestHull(float(c.vx*t),float(c.vy*t),c.vx,c.vy,c.heading),t);}
+ CHECK(history.SegmentCount()==8);
+ std::vector<std::uint32_t> base,direction;CHECK(foamDirectionAtlas(history,map,7,base,direction));
+ unsigned active=0;
+ for(auto p:direction) {const auto d=foamDecodeDirection(p);if(d.alpha<20)continue;++active;
+ CHECK_NEAR(d.x,c.x,2.0/d.alpha+1e-6);CHECK_NEAR(d.y,c.y,2.0/d.alpha+1e-6);
+ CHECK(d.width>=.65-32.0/d.alpha && d.width<=2.8+32.0/d.alpha);}
+ CHECK(active>20);
+ // All hulls face +X, so diagonal/broadside cases arm a current-heading substitution.
+ if(c.vy!=0) CHECK(std::abs(c.x-1)+std::abs(c.y)>.9);
+ }
+}
+
+TEST(water_foam_direction_crossings_cancel_or_retain_density_weighted_confidence)
+{
+ using namespace WaterFoamHistory;
+ const Mapping sample={-.5,-.5,1,1,1,1};
+ for(unsigned horizontal:{1u,3u}) {
+ History history;
+ for(unsigned step=0;step<=4;++step) {const double t=step*.25;history.Advance(t);
+ for(unsigned id=0;id<horizontal;++id)
+ history.Observe(id,foamTestHull(float(30*t-3),0,30,0),t);
+ auto vertical=foamTestHull(0,float(30*t-3),0,30);
+ vertical.data[1][0]=0;vertical.data[1][1]=1;
+ history.Observe(10,vertical,t);
+ }
+ CHECK(history.SegmentCount()==4*(horizontal+1));
+ std::vector<std::uint32_t> base,direction;CHECK(foamDirectionAtlas(history,sample,7,base,direction));
+ if(direction.empty())continue;const auto d=foamDecodeDirection(direction[0]);CHECK(d.alpha>100);
+ if(!d.alpha)continue;
+ const double expected=(double(horizontal)-1)/(horizontal+1);
+ CHECK_NEAR(d.x,expected,2.0/d.alpha+1e-6);CHECK_NEAR(d.y,0,2.0/d.alpha+1e-6);
+ if(horizontal==1) CHECK(std::hypot(d.x,d.y)<.03); // Isotropic fallback, not an arbitrary diagonal.
+ else CHECK(std::hypot(d.x,d.y)>.45 && std::hypot(d.x,d.y)<.55);
+ foamCheckDirectionOracle(direction[0],foamDirectionOracle(history,{0,0}));
+ }
+}
+
+TEST(water_foam_direction_curves_and_changing_width_match_independent_deposition)
+{
+ using namespace WaterFoamHistory;
+ History history;
+ for(unsigned i=0;i<=16;++i) {
+ const double t=i*.25,a=t*.4;const float width=float(4+2*t);
+ auto hull=foamTestHull(float(70*std::sin(a)),float(70*(1-std::cos(a))),
+ float(28*std::cos(a)),float(28*std::sin(a)),float(a));
+ hull.data[1][3]=width;
+ for(unsigned j=1;j<8;j+=2) hull.data[4+j/4][j%4]*=width/4;
+ history.Advance(t);history.Observe(1,hull,t);
+ }
+ CHECK(history.SegmentCount()==16);if(history.SegmentCount()!=16)return;
+ unsigned headingControl=0,oldWidthControl=0;
+ for(unsigned index:{1u,5u,10u,14u}) for(unsigned lane:{0u,1u}) {
+ const Segment &s=history.Segments()[index];
+ const Point p={(s.begin.lanes[lane].x+s.end.lanes[lane].x)*.5,
+ (s.begin.lanes[lane].y+s.end.lanes[lane].y)*.5};
+ const Mapping map={p.x-.5,p.y-.5,1,1,1,1};
+ std::vector<std::uint32_t> base,direction;CHECK(foamDirectionAtlas(history,map,7,base,direction));
+ if(direction.empty())continue;
+ const auto expected=foamDirectionOracle(history,p,2048);
+ foamCheckDirectionOracle(direction[0],expected);
+ // Coarser independent quadrature convergence makes the .501-byte coverage
+ // oracle margin meaningful, rather than hiding arbitrary numerical error.
+ const auto coarse=foamDirectionOracle(history,p,1024);
+ CHECK_NEAR(coarse.density,expected.density,1e-7);
+ CHECK_NEAR(coarse.x,expected.x,1e-7);CHECK_NEAR(coarse.y,expected.y,1e-7);
+ CHECK_NEAR(coarse.width,expected.width,1e-7);
+ if(std::hypot(expected.x-std::cos(3.2),expected.y-std::sin(3.2))>.5)++headingControl;
+ if(std::abs(expected.width-history.Segments().back().end.width[lane])>.4)++oldWidthControl;
+ }
+ CHECK(headingControl>=2 && oldWidthControl>=2);
+ History turned=history;
+ const auto last=history.Segments().back().end;
+ for(unsigned i=17;i<=20;++i) {const double t=i*.25;history.Advance(t);turned.Advance(t);
+ history.Observe(1,foamTestHull(float(last.center.x),float(last.center.y),30,0,1.6f),t);
+ turned.Observe(1,foamTestHull(float(last.center.x),float(last.center.y),30,0,2.2f),t);}
+ std::vector<std::uint32_t> a,b,da,db;
+ const Mapping map={-32,-32,160,160,80,80};
+ CHECK(foamDirectionAtlas(history,map,7,a,da) && foamDirectionAtlas(turned,map,7,b,db));
+ CHECK(a==b && da==db); // Rotating the stopped hull cannot rotate its retained path.
+}
+
+TEST(water_foam_direction_zero_length_lane_has_no_invented_axis)
+{
+ using namespace WaterFoamHistory;
+ History history;const auto hull=foamTestHull(0,0,30,0);
+ const Point p0={0,0},p1={1,0};
+ history.Observe(1,hull,0,true,false,&p0);history.Advance(.25);
+ history.Observe(1,hull,.25,true,false,&p1);
+ CHECK(history.SegmentCount()==1);
+ // Deliberate synthetic pose: motion origin advances while every contour lane
+ // stays fixed. Radial dose remains possible, but there is no recorded tangent.
+ std::vector<std::uint32_t> base,direction;
+ CHECK(foamDirectionAtlas(history,{-12.5,-.5,1,1,1,1},7,base,direction));
+ if(direction.empty())return;const auto d=foamDecodeDirection(direction[0]);CHECK(d.alpha>20);
+ if(d.alpha) {CHECK_NEAR(d.x,0,2.0/d.alpha);CHECK_NEAR(d.y,0,2.0/d.alpha);}
+ foamCheckDirectionOracle(direction[0],foamDirectionOracle(history,{-12,0}));
+}
+
+TEST(water_foam_direction_time_sampling_live_tail_pause_and_commit_are_stable)
+{
+ using namespace WaterFoamHistory;
+ const Mapping map={-32,-16,160,32,160,32};std::vector<std::uint32_t> reference;
+ for(unsigned fps:{20u,30u,60u,120u}) {
+ History history;
+ for(unsigned frame=0;double(frame)/fps<.37;++frame) {const double t=double(frame)/fps;
+ history.Advance(t);history.Observe(1,foamTestHull(float(250*t),0,250,0),t);}
+ history.Advance(.37);history.Observe(1,foamTestHull(92.5f,0,250,0),.37);
+ CHECK(history.SegmentCount()==1);
+ std::vector<std::uint32_t> base,direction;
+ CHECK(foamDirectionAtlas(history,map,7,base,direction));
+ if(direction.size()!=160u*32u)return;
+ CHECK((direction[16*160+112]>>24)>3); // Live stern lies near x80.5, beyond committed section.
+ if(reference.empty())reference=direction;
+ for(size_t i=0;i<direction.size();++i)for(unsigned shift:{0u,8u,16u,24u})
+ CHECK(std::abs(int((direction[i]>>shift)&255)-int((reference[i]>>shift)&255))<=1);
+ CHECK(!history.Advance(.37));CHECK(!history.Observe(1,foamTestHull(92.5f,0,250,0),.37));
+ std::vector<std::uint32_t> b,d;CHECK(foamDirectionAtlas(history,map,7,b,d));CHECK(base==b && direction==d);
+ history.Advance(.39);history.Observe(1,foamTestHull(92.5f,0,250,0),.39);
+ history.Advance(.5);CHECK(foamDirectionAtlas(history,map,7,base,direction));
+ history.Observe(1,foamTestHull(92.5f,0,250,0),.5);
+ CHECK(foamDirectionAtlas(history,map,7,b,d));CHECK(base==b && direction==d);
+ CHECK(history.SegmentCount()==2 && history.Segments().back().end.time==.37);
+ }
+}
+
+TEST(water_foam_direction_pan_empty_level_invalid_and_aging_are_bounded)
+{
+ using namespace WaterFoamHistory;
+ History history;
+ for(unsigned i=0;i<=8;++i) {history.Advance(i*.25);history.Observe(1,foamTestHull(i*4.f,0,16,0),i*.25);}
+ std::vector<std::uint32_t> a,b,da,db;
+ CHECK(foamDirectionAtlas(history,{-64,-64,128,128,128,128},7,a,da));
+ CHECK(foamDirectionAtlas(history,{-32,-32,64,64,64,64},7,b,db));
+ if(a.size()!=128u*128u || da.size()!=a.size() || b.size()!=64u*64u || db.size()!=b.size())return;
+ for(unsigned y=0;y<64;++y)for(unsigned x=0;x<64;++x) {
+ CHECK(b[y*64+x]==a[(y+32)*128+x+32]);CHECK(db[y*64+x]==da[(y+32)*128+x+32]);}
+ const Mapping map={-32,-16,128,32,64,16};
+ CHECK(foamDirectionAtlas(history,map,8,b,db));for(auto p:db)CHECK(p==0);
+ CHECK(foamDirectionAtlas(history,{10000,10000,128,32,64,16},7,b,db));for(auto p:db)CHECK(p==0);
+ for(const Mapping invalid:std::initializer_list<Mapping>{{0,0,1,1,513,1},{0,0,0,1,1,1},
+ {NAN,0,1,1,1,1},{0,0,1,1,0,1},{0,0,1,1,1,513}}) {
+ b.assign(1,0xffffffffu);db=b;CHECK(!history.BuildAtlas(invalid,7,b,&db));CHECK(b.empty()&&db.empty());}
+ b.assign(1,0xffffffffu);db=b;CHECK(!history.BuildAtlas(map,NAN,b,&db));CHECK(b.empty()&&db.empty());
+ history.Advance(12);CHECK(foamDirectionAtlas(history,map,7,b,db));unsigned active=0;
+ for(auto p:db) {const auto d=foamDecodeDirection(p);if(d.alpha<10)continue;++active;
+ CHECK_NEAR(d.x,1,2.0/d.alpha);CHECK_NEAR(d.y,0,2.0/d.alpha);}
+ CHECK(active>0); // Aging spreads/decays the deposit without changing its recorded axis.
+ history.Advance(30);CHECK(foamDirectionAtlas(history,map,7,b,db));for(auto p:db)CHECK(p==0);
+ history.Advance(0);CHECK(history.SegmentCount()==0 && history.TrackedCount()==0);
+ CHECK(foamDirectionAtlas(history,{0,0,512,512,512,512},7,b,db));
+ CHECK(db.size()==512u*512u);for(auto p:db)CHECK(p==0);
+}
+
+TEST(water_foam_direction_emitter_eviction_preserves_tail_and_segment_budget)
+{
+ using namespace WaterFoamHistory;
+ History history;history.Observe(1,foamTestHull(0,0,100,0),0);
+ history.Advance(.12);history.Observe(1,foamTestHull(12,0,100,0),.12);
+ const Mapping map={-24,-12,64,24,64,24};std::vector<std::uint32_t> a,b,da,db;
+ CHECK(foamDirectionAtlas(history,map,7,a,da));CHECK(history.SegmentCount()==0);
+ for(unsigned id=2;id<MaxEmitters+2;++id)history.Observe(id,foamTestHull(10000,float(id*20),30,0),.12);
+ CHECK(history.TrackedCount()==MaxEmitters && history.SegmentCount()==1);
+ CHECK(foamDirectionAtlas(history,map,7,b,db));CHECK(a==b && da==db);
+ history.Clear();
+ for(unsigned frame=0;frame<=96;++frame) {const double t=frame*.25;history.Advance(t);
+ for(unsigned id=0;id<16;++id)history.Observe(id,foamTestHull(float(t*30),float(id*20),30,0),t);}
+ CHECK(history.SegmentCount()==MaxSegments);
+ CHECK(foamDirectionAtlas(history,{620,-4,80,8,16,4},7,b,db));unsigned active=0;
+ for(auto p:db) {const auto d=foamDecodeDirection(p);if(d.alpha<10)continue;++active;
+ CHECK_NEAR(d.x,1,2.0/d.alpha);CHECK_NEAR(d.y,0,2.0/d.alpha);}
+ CHECK(active>0);
+}
+
+TEST(water_vessel_motion_tracks_scripted_transforms_and_braking)
+{
+ using namespace WaterVesselMotion;
+ State state;
+ CHECK(Update(state,{0,0},7,100,false,{},30).x==0);
+ // A scripted vessel can have zero physics velocity while its displayed hull moves.
+ // Braking must likewise follow that transform instead of forcing its wake speed to zero.
+ for (unsigned step=1;step<=60;++step) {
+ const Point velocity=Update(state,{float(step),-0.5f*step},7,100+step,false,{},30);
+ const float response=1-std::exp(-float(step)/30/SmoothingSeconds);
+ CHECK(std::abs(velocity.x-30*response)<0.00002f);
+ CHECK(std::abs(velocity.y+15*response)<0.00002f);
+ }
+ CHECK(state.velocity.x>29.99f); // Armed against retaining the zero physics-only velocity.
+ const Point moving=state.velocity;
+ for (unsigned step=1;step<=30;++step) {
+ const Point velocity=Update(state,{60,-30},7,160+step,false,{100,100},30);
+ const float decay=std::exp(-float(step)/30/SmoothingSeconds);
+ CHECK(std::abs(velocity.x-moving.x*decay)<0.00002f);
+ CHECK(std::abs(velocity.y-moving.y*decay)<0.00002f);
+ }
+ CHECK(std::abs(state.velocity.x)<0.04f); // Stale nonzero physics cannot sustain a stopped wake.
+}
+
+TEST(water_vessel_motion_is_stable_during_pause_and_repeated_render_frames)
+{
+ using namespace WaterVesselMotion;
+ State state;
+ Update(state,{0,0},7,100,false,{30,-15},30);
+ const Point original=state.velocity;
+ for (int draw=0;draw<100;++draw) {
+ const Point sameFrame=Update(state,{0.99f,-0.45f},7,100,false,{0,0},30);
+ CHECK(sameFrame.x==original.x && sameFrame.y==original.y);
+ CHECK(state.frame==100 && state.position.x==0 && state.position.y==0);
+ const Point frozen=Update(state,{9,9},7,101,true,{0,0},30);
+ CHECK(frozen.x==original.x && frozen.y==original.y);
+ CHECK(state.frame==100 && state.position.x==0 && state.position.y==0);
+ }
+ const Point resumed=Update(state,{1,-0.5f},7,101,false,{},30);
+ CHECK(std::abs(resumed.x-30)<0.00001f && std::abs(resumed.y+15)<0.00001f);
+ // Equal elapsed simulation time gives the same filtered velocity when render visibility
+ // samples every frame, every other frame, or every third frame; extra render calls do not age it.
+ Point results[3];
+ for (unsigned cadence=1;cadence<=3;++cadence) {
+ State sampled;Update(sampled,{0,0},7,0,false,{},30);
+ for (unsigned frame=cadence;frame<=60;frame+=cadence) {
+ results[cadence-1]=Update(sampled,{float(frame),float(frame)*0.5f},7,frame,false,{},30);
+ Update(sampled,{float(frame)+0.4f,float(frame)*0.5f+0.2f},7,frame,false,{},30);
+ }
+ }
+ for (const Point velocity:results) {
+ CHECK(std::abs(velocity.x-results[0].x)<0.00002f);
+ CHECK(std::abs(velocity.y-results[0].y)<0.00002f);
+ }
+}
+
+TEST(water_vessel_motion_preserves_seconds_when_logic_rate_changes)
+{
+ using namespace WaterVesselMotion;
+ for (unsigned fps : {30u,unsigned(LOGICFRAMES_PER_SECOND),120u}) {
+ State state;
+ Update(state,{0,0},7,0,false,{},float(fps));
+ for (unsigned frame=1;frame<=fps*2;++frame) {
+ const float time=float(frame)/fps;
+ const Point velocity=Update(state,{60*time,-30*time},7,frame,false,{},float(fps));
+ const float response=1-std::exp(-time/SmoothingSeconds);
+ CHECK_NEAR(velocity.x,60*response,.0001f);
+ CHECK_NEAR(velocity.y,-30*response,.0001f);
+ }
+ const Point moving=state.velocity;
+ for (unsigned frame=1;frame<=fps;++frame) {
+ const Point velocity=Update(state,{120,-60},7,fps*2+frame,false,{},float(fps));
+ const float decay=std::exp(-float(frame)/fps/SmoothingSeconds);
+ CHECK_NEAR(velocity.x,moving.x*decay,.0001f);
+ CHECK_NEAR(velocity.y,moving.y*decay,.0001f);
+ }
+ }
+}
+
+TEST(water_vessel_motion_rejects_teleports_stale_history_and_object_replacement)
+{
+ using namespace WaterVesselMotion;
+ auto moving=[]() { State state;Update(state,{0,0},7,100,false,{30,10},30);return state; };
+ State state=moving();
+ Point result=Update(state,{33,0},7,101,false,{90,0},30);
+ CHECK(result.x==0 && result.y==0 && state.position.x==33 && state.frame==101);
+ result=Update(state,{34,0},7,102,false,{},30);
+ CHECK(result.x>0 && result.x<30); // A teleport anchors, then genuine movement can resume.
+ state=moving();result=Update(state,{16,0},7,116,false,{90,0},30);
+ CHECK(result.x==90 && result.y==0); // Camera reentry reseeds from current physics, never old displacement.
+ state=moving();result=Update(state,{16,0},7,116,false,{NAN,0},30);
+ CHECK(result.x==0 && result.y==0); // Missing/invalid physics cannot resurrect stale motion.
+ state=moving();result=Update(state,{16,0},7,116,false,{300,400},30);
+ CHECK(result.x==150 && result.y==200); // The reentry seed obeys the same vector speed bound.
+ state=moving();result=Update(state,{1000,0},7,116,false,{90,0},30);
+ CHECK(result.x==0 && result.y==0); // A teleport still resets, even after a visibility gap.
+ state=moving();result=Update(state,{15,0},7,115,false,{},30);
+ CHECK(result.x>0); // The inclusive half-second limit still observes real motion.
+ state=moving();result=Update(state,{1,0},8,101,false,{90,0},30);
+ CHECK(result.x==0 && result.y==0 && state.level==8);
+ state=moving();result=Update(state,{1,0},7,99,false,{90,0},30);
+ CHECK(result.x==0 && result.y==0 && state.frame==99);
+ state=moving();state=State();result=Update(state,{1000,2000},7,101,false,{},30);
+ CHECK(result.x==0 && result.y==0); // Model/ID cache replacement cannot inherit old velocity.
+}
+
+TEST(water_vessel_motion_uses_the_actual_first_render_phase)
+{
+ using namespace WaterVesselMotion;
+ const float phases[]={0.125f,0.875f,0.25f,0.75f,0.5f};
+ State sampled,integerTime;
+ float largestControlError=0;
+ for (unsigned frame=100;frame<160;++frame) {
+ const float phase=phases[(frame-100)%5];
+ // A constant 30,-15 unit/s ship, rendered at a different interpolation phase on
+ // each tick. Binary phases keep this independent reference free of roundoff noise.
+ const float sampleTime=float(frame-1)+phase;
+ const Point position={sampleTime,-sampleTime*0.5f};
+ const Point velocity=Update(sampled,position,7,frame,false,{30,-15},30,phase);
+ CHECK(std::abs(velocity.x-30)<0.00001f && std::abs(velocity.y+15)<0.00001f);
+ CHECK(sampled.phase==phase && sampled.frame==frame);
+ const Point control=Update(integerTime,position,7,frame,false,{30,-15},30);
+ largestControlError=(std::max)(largestControlError,std::abs(control.x-30));
+ // Additional draws and frozen passes do not replace this tick's sampled phase.
+ const Point repeated=Update(sampled,{sampleTime+0.1f,0},7,frame,false,{},30,0.99f);
+ const Point frozen=Update(sampled,{1000,1000},7,frame+1,true,{},30,0.75f);
+ CHECK(repeated.x==velocity.x && frozen.x==velocity.x);
+ CHECK(sampled.phase==phase && sampled.position.x==position.x && sampled.frame==frame);
+ }
+ CHECK(largestControlError>4.0f); // Armed control: integer-only timing invents acceleration.
+ // Models snapped to their current tick are sampled at phase1, even when the global
+ // renderer alpha differs. Switching between a snapped and blended model stays correct.
+ State transitions;
+ Update(transitions,{99.25f,0},7,100,false,{30,0},30,0.25f);
+ Point velocity=Update(transitions,{101,0},7,101,false,{},30,1);
+ CHECK(velocity.x==30 && transitions.phase==1);
+ velocity=Update(transitions,{101.5f,0},7,102,false,{},30,0.5f);
+ CHECK(velocity.x==30 && transitions.phase==0.5f);
+}
+
+TEST(water_vessel_motion_handles_zero_elapsed_phase_and_invalid_phase)
+{
+ using namespace WaterVesselMotion;
+ State state;
+ Update(state,{5,3},7,100,false,{30,-15},30,1);
+ Point velocity=Update(state,{5,3},7,101,false,{},30,0);
+ CHECK(velocity.x==30 && velocity.y==-15 && state.frame==101 && state.phase==0);
+ velocity=Update(state,{6.5f,2.25f},7,102,false,{},30,0.5f);
+ CHECK(velocity.x==30 && velocity.y==-15);
+ Update(state,{8,1.5f},7,103,false,{},30,1);
+ velocity=Update(state,{40,10},7,104,false,{100,100},30,0);
+ CHECK(velocity.x==0 && velocity.y==0); // Changed transform at identical time cannot be divided by zero.
+ for (float invalid:{float(NAN),float(INFINITY),float(-INFINITY)}) {
+ State bad;velocity=Update(bad,{0,0},7,0,false,{10,10},30,invalid);
+ CHECK(velocity.x==0 && velocity.y==0 && !bad.initialized);
+ }
+ State clamped;
+ Update(clamped,{0,0},7,0,false,{},30,-0.01f);CHECK(clamped.phase==0);
+ Update(clamped,{2,0},7,1,false,{},30,1.01f);CHECK(clamped.phase==1);
+ // The history threshold uses real displayed sample time too, not an integer tick count.
+ State recent;Update(recent,{0,0},7,100,false,{30,0},30,0.875f);
+ velocity=Update(recent,{14.25f,0},7,115,false,{90,0},30,0.125f);
+ CHECK(velocity.x==30);
+ State stale;Update(stale,{0,0},7,100,false,{30,0},30,0.125f);
+ velocity=Update(stale,{15.75f,0},7,115,false,{90,0},30,0.875f);
+ CHECK(velocity.x==90);
+}
+
+TEST(water_vessel_motion_is_finite_vector_bounded_and_rotation_equivariant)
+{
+ using namespace WaterVesselMotion;
+ State state;
+ Point velocity=Update(state,{0,0},7,0,false,{300,400},30);
+ CHECK(std::abs(velocity.x-150)<0.00001f && std::abs(velocity.y-200)<0.00001f);
+ for (unsigned frame=1;frame<=60;++frame) {
+ velocity=Update(state,{10.0f*frame,10.0f*frame},7,frame,false,{},30);
+ CHECK(std::isfinite(velocity.x) && std::isfinite(velocity.y));
+ CHECK(double(velocity.x)*velocity.x+double(velocity.y)*velocity.y<=double(MaxSpeed)*MaxSpeed+0.01);
+ }
+ for (float invalid:{float(NAN),float(INFINITY),float(-INFINITY)}) {
+ State bad;velocity=Update(bad,{0,0},7,0,false,{invalid,1},30);
+ CHECK(velocity.x==0 && velocity.y==0);
+ velocity=Update(state,{invalid,0},7,61,false,{},30);
+ CHECK(velocity.x==0 && velocity.y==0 && !state.initialized);
+ velocity=Update(state,{0,0},invalid,61,false,{},30);
+ CHECK(velocity.x==0 && velocity.y==0 && !state.initialized);
+ velocity=Update(state,{0,0},7,61,false,{},invalid);
+ CHECK(velocity.x==0 && velocity.y==0 && !state.initialized);
+ }
+ State straight,rotated;
+ Update(straight,{0,0},7,0,false,{},30);Update(rotated,{100,-200},7,0,false,{},30);
+ for (unsigned frame=1;frame<=60;++frame) {
+ const Point p={float(frame),0.125f*float(frame*frame)};
+ const Point a=Update(straight,p,7,frame,false,{},30);
+ const Point b=Update(rotated,{100-p.y,-200+p.x},7,frame,false,{},30);
+ CHECK(std::abs(a.x-b.y)<0.00002f && std::abs(a.y+b.x)<0.00002f);
+ }
+}
+
+TEST(water_fft_metadata_preserves_shared_edges_and_floor_and_hull_bounds)
+{
+ using namespace WaterProjectedMesh;
+ using namespace WaterFftGeometry;
+ const Point left[4]={{-500,-500},{0,-500},{0,500},{-500,500}};
+ const Point right[4]={{0,500},{0,-500},{500,-500},{500,500}};
+ const Projection projection=testWaterProjection();SeamFade a,b;
+ CHECK(a.Prepare(left,projection,{16,16}) && b.Prepare(right,projection,{16,16}));
+ for (int i=-100;i<=100;++i) {
+ CHECK(a.Weight({0,double(i)},1)==0 && b.Weight({0,double(i)},1)==0);
+ CHECK(a.Weight({-75,double(i)},0)==0);
+ }
+ CHECK(a.Weight({-75,0},1)==1);
+ CHECK(a.Weight({-75,0},0.37f)==0.37f);
+ CHECK(InnerWorldCollar>MaxHorizontalDisplacement);
+ for (int i=0;i<500;++i) {
+ const double distance=i*0.1;
+ CHECK(MaxHorizontalDisplacement*a.Weight({-distance,0},1)<=distance+1e-6);
+ }
+ for (float depth:{-4.0f,0.0f,0.1f,0.15f,0.16f,2.25f,7.0f,30.0f})
+ for (float damping:{-1.0f,0.0f,0.17f,0.5f,1.0f,2.0f}) {
+ const float safe=SafeDamping(damping,depth);
+ CHECK(std::isfinite(safe) && safe>=0 && safe<=1);
+ CHECK(safe*MaxVerticalDisplacement<=(std::max)(0.0f,depth-FloorClearance)+1e-6f);
+ if (damping<=0 || depth<=FloorClearance) CHECK(safe==0);
+ }
+ CHECK(SafeDamping(NAN,3)==0 && SafeDamping(1,NAN)==0);
+ // The existing nine-unit hull fade also bounds lateral travel: an eight-unit maximum
+ // offset cannot carry a sample across the waterline it was attenuated against.
+ for (int i=0;i<=900;++i) {
+ const float distance=i*0.01f;
+ CHECK(MaxHorizontalDisplacement*WaterSurfaceModel::ShoreDamping(distance)<=distance+1e-6f);
+ }
+}
+
+TEST(water_fft_connected_coasts_keep_phase_support_without_changing_optical_classification)
+{
+ using namespace WaterOpticalContext;
+ const int width=50,height=40,border=2;
+ std::vector<uint8_t> heights(width*height,20);
+ for (int y=0;y<height;++y) for (int x=0;x<18;++x) heights[y*width+x]=0;
+ for (int y=10;y<31;++y) for (int x=28;x<47;++x) heights[y*width+x]=0;
+ Field field;
+ CHECK(Build(heights.data(),width,height,border,10,1,4,{opticalRectangle(-100,-100,600,500)},field));
+ const WaterProjectedMesh::Point polygon[4]={{-100,-100},{600,-100},{600,500},{-100,500}};
+ WaterFftGeometry::SeamFade seam;
+ CHECK(seam.Prepare(polygon,testWaterProjection(),{160,90}));
+ auto sample=[&](const std::vector<uint8_t> &channel,int x,int y) {
+ return WaterSurfaceModel::SampleOffshore(channel.data(),width,height,float(x),float(y),10).height;
+ };
+ // Actual topology metadata distinguishes a nearshore zero-R ocean texel from
+ // a zero-R enclosed pool. Colour/extinction R remains unchanged in both cases.
+ CHECK(sample(field.ocean,15,20)==0 && sample(field.exposure,15,20)==1);
+ CHECK(sample(field.ocean,37,20)==0 && sample(field.exposure,37,20)==0);
+ CHECK(sample(field.ocean,4,20)==1 && sample(field.exposure,4,20)==1);
+ const WaterProjectedMesh::Point coast={130,180},pool={350,180},open={20,180};
+ CHECK(seam.Weight(coast,sample(field.exposure,15,20))==1);
+ CHECK(seam.Weight(open,sample(field.exposure,4,20))==1);
+ CHECK(seam.Weight(pool,sample(field.exposure,37,20))==0);
+ CHECK(seam.Weight(coast,sample(field.ocean,15,20))==0); // Armed pre-fix phase switch.
+ // Connection cannot bypass the authored-boundary collar or invalid metadata.
+ CHECK(seam.Weight({-100,180},sample(field.exposure,4,20))==0);
+ CHECK(seam.Weight(coast,WaterSurfaceModel::SampleOffshore(nullptr,width,height,15,20,10).height)==0);
+ std::fill(heights.begin(),heights.end(),0);
+ CHECK(Build(heights.data(),width,height,border,10,1,4,{opticalRectangle(100,100,300,300)},field));
+ for (uint8_t exposure:field.exposure) CHECK(exposure==0);
+ CHECK(seam.Weight(coast,sample(field.exposure,15,20))==0);
+}
+
+TEST(water_fft_hull_free_metadata_preserves_original_vertices_and_clearance)
+{
+ using namespace WaterFftGeometry;
+ // Moving only the hull minimum to the two GPU stages must preserve the original
+ // vertex displacement, including the authored shallow sea's stricter floor envelope.
+ for (float depth:{-2.0f,0.15f,0.3f,2.25f,7.0f,30.0f})
+ for (float offshore:{0.0f,0.125f,0.5f,0.875f,1.0f})
+ for (float obstacle:{0.0f,0.1f,0.37f,0.8f,1.0f})
+ for (int step=-10;step<=120;++step) {
+ const float distance=step*0.1f;
+ const float hull=1.0f+(WaterSurfaceModel::ShoreDamping(distance)-1.0f)*offshore;
+ const float freeDamping=(std::min)(WaterSurfaceModel::TerrainDamping(depth,offshore),obstacle);
+ const float original=SafeDamping((std::min)(freeDamping,hull),depth);
+ const float separated=(std::min)(SafeDamping(freeDamping,depth),hull);
+ CHECK(original==separated && separated>=0 && separated<=1);
+ CHECK(separated*MaxVerticalDisplacement<=(std::max)(0.0f,depth-FloorClearance)+1e-6f);
+ if (offshore==1 && distance>=0)
+ CHECK(MaxHorizontalDisplacement*separated<=distance+1e-6f);
+ if (offshore==0 || distance>=9)
+ CHECK(separated==SafeDamping(freeDamping,depth));
+ }
+ // An overlapping second hull remains an ordered minimum, without dividing out a
+ // zero hull factor or losing a lower floor/non-vessel obstacle constraint.
+ for (int step=0;step<=90;++step) {
+ const float a=WaterSurfaceModel::ShoreDamping(step*0.1f);
+ const float b=WaterSurfaceModel::ShoreDamping((90-step)*0.1f);
+ const float original=SafeDamping((std::min)(0.8f,(std::min)(a,b)),2.25f);
+ const float separated=(std::min)(SafeDamping(0.8f,2.25f),(std::min)(a,b));
+ CHECK(original==separated);
+ }
+}
+
+TEST(water_fft_seam_fade_is_continuous_under_camera_motion_resize_and_horizon_crossing)
+{
+ using namespace WaterProjectedMesh;
+ using namespace WaterFftGeometry;
+ const Point polygon[4]={{-500,-500},{0,-500},{0,500},{-500,500}};
+ for (Resolution resolution:{Resolution{16,16},Resolution{160,90},Resolution{192,128}}) {
+ Projection p=testWaterProjection(),q=p;q.matrix[2]+=1e-7;CHECK(q.Prepare());SeamFade a,b;
+ CHECK(a.Prepare(polygon,p,resolution) && b.Prepare(polygon,q,resolution));
+ for (int i=0;i<=1000;++i) {
+ const Point point={-i*0.1,1.3};const float w=a.Weight(point,0.8f);
+ CHECK(w>=0 && w<=0.8f && std::isfinite(w));
+ CHECK(std::abs(w-b.Weight(point,0.8f))<1e-6f);
+ CHECK(std::abs(w-a.Weight({point.x-1e-7,point.y},0.8f))<1e-6f);
+ if (i>0) CHECK(w+1e-7f>=a.Weight({point.x+0.1,point.y},0.8f));
+ }
+ }
+ // An authored endpoint is exactly on the projective horizon. Moving it from one side
+ // to the other must not turn the entire interior field off for a single camera frame.
+ const Point horizonPolygon[4]={{-500,-1},{500,-1},{500,500},{-500,500}};
+ float previous=-1;
+ for (double shift:{-1e-9,0.0,1e-9}) {
+ Projection p={{0.01,0,0,0,1.018,0,0,1,1+shift},{0},{0,1,1+shift},0.1,600,0.12};
+ CHECK(p.Prepare());SeamFade fade;CHECK(fade.Prepare(horizonPolygon,p,{160,90}));
+ const float weight=fade.Weight({0,15},1);CHECK(std::isfinite(weight) && weight>0);
+ if (previous>=0) CHECK(std::abs(weight-previous)<1e-6f);previous=weight;
+ }
+}
+
+TEST(water_fft_actual_boundary_triangles_keep_the_analytic_transition_continuous)
+{
+ using namespace WaterProjectedMesh;
+ using namespace WaterFftGeometry;
+ const Point polygon[4]={{-500,-500},{0,-500},{0,500},{-500,500}};
+ std::vector<BoundaryKnot> knots;
+ for (int edge=0;edge<4;++edge) {
+ Point a=polygon[edge],b=polygon[(edge+1)%4];if (a.x>b.x || (a.x==b.x && a.y>b.y)) std::swap(a,b);
+ for (int i=0;i<=2;++i) knots.push_back({{a.x+(b.x-a.x)*i/2,a.y+(b.y-a.y)*i/2},edge,i,i/2.0});
+ }
+ for (int axis:{0,1}) {
+ Projection p=testWaterProjection(),q=p;p.matrix[axis*3+2]=-1e-7;q.matrix[axis*3+2]=1e-7;
+ CHECK(p.Prepare() && q.Prepare());Mesh a,b;
+ CHECK(Build(polygon,p,{16,16},a,60000,knots) && Build(polygon,q,{16,16},b,60000,knots));
+ SeamFade fa,fb;CHECK(fa.Prepare(polygon,p,{16,16}) && fb.Prepare(polygon,q,{16,16}));
+ int guardedTotal=0;
+ auto displaced=[&](const Mesh &mesh,const SeamFade &fade) {
+ auto height=projectedTestHeights(mesh,polygon);int active=0;
+ for (size_t i=0;i<mesh.vertices.size();++i) {
+ const Vertex &v=mesh.vertices[i];const float weight=fade.Weight(v.world,1);
+ if (v.boundary>=0) CHECK(weight==0);
+ if (v.transition>=0 && v.world.x>-20 && std::abs(v.world.y)<90) {
+ ++guardedTotal;CHECK(weight==0);
+ for (Point source:mesh.transitions[v.transition].source) CHECK(fade.Weight(source,1)==0);
+ }
+ const double fft=1.4*std::cos(v.world.x*0.18)+0.6*std::sin(v.world.y*0.11);
+ if (weight>0) { ++active; height[i]+=(fft-height[i])*weight; }
+ CHECK(std::abs(height[i])<=2.300001);
+ }
+ CHECK(active>0);return height;
+ };
+ const auto ah=displaced(a,fa),bh=displaced(b,fb);
+ CHECK(guardedTotal>0);
+ for (double y:{-80.0,-35.0,-5.0,5.0,35.0,80.0}) for (double x:{-95.0,-75.0,-35.0,-5.0})
+ CHECK(std::abs(projectedTestRenderedHeight(a,ah,{x,y})-projectedTestRenderedHeight(b,bh,{x,y}))<0.00003);
+ }
+}
+
+TEST(water_ocean_height_and_slopes_include_warp_and_packet_derivatives)
+{
+ using namespace WaterSurfaceModel;
+ for (float time:{0.0f,1.73f,31.0f,139.7f}) for (int i=0;i<180;++i) {
+ const float x=-190.0f+i*3.713f,y=81.0f-i*2.419f,epsilon=0.015625f;
+ const Sample wave=EvaluateOcean(x,y,time);
+ const float dx=(EvaluateOcean(x+epsilon,y,time).height-EvaluateOcean(x-epsilon,y,time).height)/(2*epsilon);
+ const float dy=(EvaluateOcean(x,y+epsilon,time).height-EvaluateOcean(x,y-epsilon,time).height)/(2*epsilon);
+ CHECK(std::abs(wave.dx-dx)<0.002f);
+ CHECK(std::abs(wave.dy-dy)<0.002f);
+ CHECK(std::isfinite(wave.height) && std::abs(wave.height)<=OceanMaxDisplacement);
+ }
+ CHECK(MaxDisplacement>=LegacyMaxDisplacement && MaxDisplacement>=OceanMaxDisplacement);
+ std::string shader;AppendHLSL(shader);
+ CHECK(shader.find("float3 waterOceanWave")!=std::string::npos);
+ CHECK(shader.find("envelopeSlope")!=std::string::npos);
+}
+
+TEST(water_ocean_zero_classification_preserves_existing_waves_and_damping_exactly)
+{
+ using namespace WaterSurfaceModel;
+ for (int i=0;i<100;++i) {
+ const float x=i*19.3f-180,y=i*-7.13f,time=i*0.371f;
+ const Sample original=Evaluate(x,y,time),unchanged=EvaluateBlended(x,y,time,{0,0,0});
+ CHECK(memcmp(&original,&unchanged,sizeof(Sample))==0);
+ const Sample ocean=EvaluateOcean(x,y,time),full=EvaluateBlended(x,y,time,{1,0,0});
+ CHECK(memcmp(&ocean,&full,sizeof(Sample))==0);
+ const float depth=i*0.137f-1;
+ CHECK(TerrainDamping(depth,0)==ShoreDamping(depth));
+ }
+ const std::uint8_t pool[9]={0,0,0,0,0,0,0,0,0};
+ const Sample enclosed=SampleOffshore(pool,3,3,0.3f,1.2f,10);
+ CHECK(enclosed.height==0 && enclosed.dx==0 && enclosed.dy==0);
+}
+
+TEST(water_ocean_cpu_field_sampling_matches_bilinear_texel_centres_and_padding)
+{
+ using namespace WaterSurfaceModel;
+ const std::uint8_t field[9]={0,64,255,16,96,223,48,128,191};
+ for (int y=0;y<3;++y) for (int x=0;x<3;++x)
+ CHECK(SampleOffshore(field,3,3,float(x),float(y),10).height==field[y*3+x]/255.0f);
+ for (int iy=0;iy<2;++iy) for (int ix=0;ix<2;++ix) for (float fy:{0.17f,0.63f}) for (float fx:{0.23f,0.71f}) {
+ const float gx=ix+fx,gy=iy+fy,epsilon=0.001f;
+ const Sample sample=SampleOffshore(field,3,3,gx,gy,10);
+ const float independent=(field[iy*3+ix]*(1-fx)*(1-fy)+field[iy*3+ix+1]*fx*(1-fy)
+ +field[(iy+1)*3+ix]*(1-fx)*fy+field[(iy+1)*3+ix+1]*fx*fy)/255.0f;
+ CHECK(std::abs(sample.height-independent)<0.000001f);
+ CHECK(std::abs(sample.dx-(SampleOffshore(field,3,3,gx+epsilon,gy,10).height-
+ SampleOffshore(field,3,3,gx-epsilon,gy,10).height)/(20*epsilon))<0.00001f);
+ CHECK(std::abs(sample.dy-(SampleOffshore(field,3,3,gx,gy+epsilon,10).height-
+ SampleOffshore(field,3,3,gx,gy-epsilon,10).height)/(20*epsilon))<0.00001f);
+ }
+ const Sample left=SampleOffshore(field,3,3,-100,1.5f,10),right=SampleOffshore(field,3,3,100,1.5f,10);
+ CHECK(left.dx==0 && right.dx==0);
+ CHECK(left.height==SampleOffshore(field,3,3,0,1.5f,10).height);
+ CHECK(right.height==SampleOffshore(field,3,3,2,1.5f,10).height);
+ CHECK(SampleOffshore(NULL,3,3,1,1,10).height==0);
+}
+
+TEST(water_ocean_transition_normals_include_spatial_blend_and_attenuation)
+{
+ using namespace WaterSurfaceModel;
+ auto blend=[](float x,float y) { return Sample{0.45f+x*0.001f+y*0.0005f,0.001f,0.0005f}; };
+ auto damping=[&](float x,float y) { return TerrainDamping(6.0f+x*0.01f-y*0.005f,blend(x,y).height); };
+ auto height=[&](float x,float y) { return EvaluateBlended(x,y,3.17f,blend(x,y)).height*damping(x,y); };
+ for (int i=0;i<80;++i) {
+ const float x=-130+i*3.1f,y=53-i*1.7f,epsilon=0.015625f;
+ const Sample wave=EvaluateBlended(x,y,3.17f,blend(x,y));
+ const float dx=wave.dx*damping(x,y)+wave.height*(damping(x+epsilon,y)-damping(x-epsilon,y))/(2*epsilon);
+ const float dy=wave.dy*damping(x,y)+wave.height*(damping(x,y+epsilon)-damping(x,y-epsilon))/(2*epsilon);
+ CHECK(std::abs(dx-(height(x+epsilon,y)-height(x-epsilon,y))/(2*epsilon))<0.003f);
+ CHECK(std::abs(dy-(height(x,y+epsilon)-height(x,y-epsilon))/(2*epsilon))<0.003f);
+ }
+}
+
+TEST(water_ocean_displacement_stays_above_authored_floor_and_uses_ship_footprint)
+{
+ using namespace WaterSurfaceModel;
+ for (int d=0;d<=2000;++d) for (int o=0;o<=20;++o) {
+ const float depth=d*0.01f,offshore=o/20.0f,attenuation=TerrainDamping(depth,offshore);
+ const float bound=LegacyMaxDisplacement+(OceanMaxDisplacement-LegacyMaxDisplacement)*offshore;
+ CHECK(attenuation>=0 && attenuation<=1);
+ CHECK(attenuation*bound<=depth+0.00001f);
+ if (o==20 && depth>=0.15f) CHECK(attenuation*bound<=depth-0.15f+0.00001f);
+ }
+ CHECK(TerrainDamping(2.25f,1)>TerrainDamping(2.25f,0));
+ CHECK(TerrainDamping(OceanMaxDisplacement+0.2f,1)==1);
+ CHECK(BoxDamping(0,0,112,74)==0);
+ CHECK(BoxDamping(112,74,112,74)==0);
+ CHECK(BoxDamping(0,84,112,74)==1); // carrier side: legacy radius134 still flattened here
+ CHECK(ShoreDamping(84-134.24f)==0);
+ CHECK(BoxDamping(122,0,112,74)==1);
+ for (int i=0;i<90;++i) CHECK(BoxDamping(112+i*0.1f,0,112,74)<=BoxDamping(112+(i+1)*0.1f,0,112,74));
+}
+
+TEST(water_ocean_obstacle_metadata_preserves_opacity_and_lod_profile)
+{
+ using namespace WaterSurfaceModel;
+ const std::uint32_t colour=0x9e357abdu;
+ for (int i=0;i<=1000;++i) {
+ const float obstacle=i/1000.0f;
+ const std::uint32_t encoded=EncodeObstacleAttenuation(colour,obstacle);
+ CHECK((encoded&0xff00ffffu)==(colour&0xff00ffffu));
+ CHECK(std::abs(float((encoded>>16)&255)/255.0f-obstacle)<=0.5f/255.0f+0.000001f);
+ const std::uint32_t a=EncodeObstacleAttenuation(colour,0.13f),b=EncodeObstacleAttenuation(colour,0.89f);
+ for (float morph:{0.0f,0.25f,0.75f,1.0f}) {
+ const std::uint32_t mixed=MorphColour(encoded,a,b,morph);
+ CHECK((mixed&0xff00ffffu)==(colour&0xff00ffffu));
+ CHECK(std::abs(float((mixed>>16)&255)/255.0f-MorphCoordinate(obstacle,0.13f,0.89f,morph))<=1.0f/255.0f+0.000001f);
+ }
+ }
+ CHECK(((EncodeObstacleAttenuation(colour,-1)>>16)&255)==0);
+ CHECK(((EncodeObstacleAttenuation(colour,2)>>16)&255)==255);
+}
+
+TEST(water_ocean_lod_preserves_budget_and_morphs_continuously_with_shared_topology)
+{
+ using namespace WaterSurfaceModel;
+ for (int height=0;height<2000;++height) {
+ const MeshLOD old=LODForCameraHeight(128,float(height)),river=LODForView(128,float(height),0);
+ CHECK(old.cells==river.cells && old.morph==river.morph);
+ const MeshLOD ocean=LODForView(128,float(height),3000);
+ CHECK(ocean.cells>=river.cells && ocean.cells<=128 && ocean.morph>=0 && ocean.morph<=1);
+ }
+ for (int patches:{1,3,20,33,80,200}) {
+ const int base=CellsForPatches(patches);
+ for (float height:{117.0f,310.0f,480.0f,900.0f}) {
+ const MeshLOD ocean=LODForView(base,height,3000);
+ CHECK(patches*(ocean.cells+1)*(ocean.cells+1)<=VertexBudget);
+ }
+ }
+ for (float threshold:{720.0f,1080.0f,1620.0f,2430.0f}) {
+ const MeshLOD below=LODForView(128,threshold-0.001f,3000),above=LODForView(128,threshold+0.001f,3000);
+ const auto fine=testLODGrid(below.cells,below.morph,true),coarse=testLODGrid(above.cells,above.morph,true);
+ for (int j=0;j<12;++j) for (int i=0;i<12;++i) {
+ const float u=(i+0.17f)/12,v=(j+0.63f)/12;
+ checkLODVertexNear(testLODSample(fine,below.cells,u,v),testLODSample(coarse,above.cells,u,v),0.0003f);
+ }
+ }
+}
+
+TEST(water_ocean_blended_displaced_shared_edges_are_exact_through_all_morphs)
+{
+ using namespace WaterSurfaceModel;
+ std::vector<std::uint8_t> field(256*96);
+ for (int y=0;y<96;++y) for (int x=0;x<256;++x) field[y*256+x]=std::uint8_t(x);
+ const Point a={-200,17,12},b={2100,533,12},camera={500,200,110};
+ auto vertex=[&](Point p) {
+ const Sample offshore=SampleOffshore(field.data(),256,96,p.x/10,p.y/10,10);
+ const float attenuation=TerrainDamping((p.y-30)*0.07f,offshore.height);
+ p.z+=EvaluateBlended(p.x,p.y,1.73f,offshore).height*attenuation;
+ return LODTestVertex{p,attenuation,12};
+ };
+ for (int cells=8;cells<=MeshCells;cells*=2) {
+ std::vector<LODTestVertex> forward(cells+1),reverse(cells+1);
+ for (int i=0;i<=cells;++i) {
+ forward[i]=vertex(EdgePoint(a,b,float(i)/cells,camera));
+ reverse[i]=vertex(EdgePoint(b,a,float(i)/cells,camera));
+ }
+ for (float amount:{0.0f,0.17f,0.5f,0.93f,1.0f}) for (int i=0;i<=cells;++i) {
+ const CoarsePair fp=CoarsePairForVertex(i,0,cells),rp=CoarsePairForVertex(cells-i,0,cells);
+ const LODTestVertex f=testLODMorph(forward[i],forward[fp.first],forward[fp.second],amount);
+ const LODTestVertex r=testLODMorph(reverse[cells-i],reverse[rp.first],reverse[rp.second],amount);
+ CHECK(memcmp(&f,&r,sizeof(f))==0);
+ }
+ }
+}
+
+TEST(water_ocean_height_only_evaluation_is_bit_identical_to_the_full_model)
+{
+ using namespace WaterSurfaceModel;
+ for (float time:{0.0f,3.17f,97.5f,1220.3f}) for (int i=0;i<1200;++i) {
+ const float x=-4395.0f+i*7.731f,y=3526.0f-i*5.377f;
+ CHECK(EvaluateOceanHeight(x,y,time)==EvaluateOcean(x,y,time).height);
+ for (const Sample offshore: {Sample{0,0,0},Sample{0.25f,0.01f,-0.005f},Sample{1,0,0},Sample{1,0.001f,0}})
+ CHECK(EvaluateBlendedHeight(x,y,time,offshore)==EvaluateBlended(x,y,time,offshore).height);
+ }
+}
+
+TEST(water_ocean_obstacle_broadphase_only_rejects_fully_unattenuated_samples)
+{
+ using namespace WaterSurfaceModel;
+ for (float major:{3.0f,50.0f,112.0f}) for (float minor:{2.0f,30.0f,74.0f}) {
+ const float radius=std::sqrt(major*major+minor*minor);
+ CHECK(!BeyondObstacleFade(0,0,radius));
+ CHECK(!BeyondObstacleFade(radius+8.9f,0,radius));
+ CHECK(BeyondObstacleFade(radius+20,0,radius));
+ for (int i=0;i<100;++i) for (float margin:{8.0f,9.0f,9.999f,10.001f,50.0f}) {
+ const float angle=i*0.37f,orientation=i*0.83f;
+ const float dx=std::cos(angle)*(radius+margin),dy=std::sin(angle)*(radius+margin);
+ if (!BeyondObstacleFade(dx,dy,radius)) continue;
+ CHECK(ShoreDamping(std::sqrt(dx*dx+dy*dy)-radius)==1);
+ CHECK(BoxDamping(dx*std::cos(orientation)+dy*std::sin(orientation),
+ -dx*std::sin(orientation)+dy*std::cos(orientation),major,minor)==1);
+ }
+ }
+}
+
+TEST(water_ocean_analytic_laplacian_matches_independent_height_curvature)
+{
+ using namespace WaterSurfaceModel;
+ for (float time:{0.0f,3.17f,19.7f}) for (int i=0;i<120;++i) {
+ const float x=-61.0f+i*1.073f,y=43.0f-i*0.917f,epsilon=0.125f;
+ const OceanSurface surface=EvaluateOceanSurface(x,y,time);
+ const Sample wave=EvaluateOcean(x,y,time);
+ CHECK(surface.height==wave.height && surface.dx==wave.dx && surface.dy==wave.dy);
+ auto central=[&](float step) {
+ return (EvaluateOcean(x+step,y,time).height+EvaluateOcean(x-step,y,time).height
+ +EvaluateOcean(x,y+step,time).height+EvaluateOcean(x,y-step,time).height
+ -4*surface.height)/(step*step);
+ };
+ // Richardson extrapolation removes the O(h^2) truncation of the shortest ripple modes,
+ // without reducing h until float subtraction loses the small curvature signal.
+ const float numerical=(4*central(epsilon)-central(2*epsilon))/3;
+ CHECK(std::isfinite(surface.laplacian));
+ CHECK(std::abs(surface.laplacian-numerical)<0.0025f);
+ auto gradientDifference=[&](float step) {
+ return (EvaluateOcean(x+step,y,time).dx-EvaluateOcean(x-step,y,time).dx
+ +EvaluateOcean(x,y+step,time).dy-EvaluateOcean(x,y-step,time).dy)/(2*step);
+ };
+ // The gradient stencil also needs its h^2 term removed: at h=.125 the fastest ripples
+ // biased three fixtures by .008–.009 although the analytic/double-height error was <2e-5.
+ const float derivative=(4*gradientDifference(epsilon*0.5f)-gradientDifference(epsilon))/3;
+ CHECK(std::abs(surface.laplacian-derivative)<0.0005f);
+ }
+ std::string hlsl=OceanShaderSource();
+ CHECK(hlsl.find("float4 waterOceanSurface")!=std::string::npos);
+ CHECK(hlsl.find("return waterOceanSurface(pxy,seconds).xyz")!=std::string::npos);
+}
+
+TEST(water_legacy_foam_replacement_is_exact_attached_current_hull_and_main_pass_only)
+{
+ using namespace WaterFoamParticlePolicy;
+ const char *names[]={"AmphibWave","AmphibWaveRest"};
+ const char *textures[]={"EXWave01.tga","EXShockWav.tga"};
+ for(unsigned pair=0;pair<2;++pair) {
+ // Full truth table prevents a missing readiness, owner, particle-type or mirror gate
+ // from removing the fallback or changing an unrelated particle draw path.
+ for(unsigned flags=0;flags<16;++flags)
+ CHECK(Replace(names[pair],textures[pair],(flags&1)!=0,(flags&2)!=0,
+ (flags&4)!=0,(flags&8)!=0)==(flags==7));
+ CHECK(KnownSurfaceFoam(names[pair],textures[pair]));
+ CHECK(!Replace(names[pair],pair==0?"EXShockWav.tga":"EXWave01.tga",true,true,true,false));
+ for(const char *texture:{static_cast<const char*>(nullptr),"","EXWater01.tga","Smoke.tga",
+ "Other/EXShockWav.tga","EXShockWav.tga.extra"})
+ CHECK(!Replace(names[pair],texture,true,true,true,false));
+ }
+ CHECK(Replace("amphibwave","exwave01.TGA",true,true,true,false));
+ CHECK(Replace("AMPHIBWAVEREST","exshockwav.tga",true,true,true,false));
+ CHECK(!Replace("aircarrierwaterripples","exshockwav.TGA",true,true,true,false));
+ CHECK(!Replace("BATTLESHIPWATERRIPPLES","EXSHOCKWAV.TGA",true,true,true,false));
+ for(const char *name:{"", "Amphib", "AmphibWaveRestExtra", "AmphibWaveSpray", "WaveSpray01",
+ "RocketBuggyDust", "MuzzleFlash", "Explosion", "ToxinField", "AirCarrierWaterRipplesExtra",
+ "BattleShipWaterRipple", "AirCarrierBowWake", "AirCarrierSideWake", "AirCarrierPropWake",
+ "AirCarrierWaterWake", "AirCarrierWaterWakePort", "CustomWake"}) {
+ CHECK(!Replace(name,"EXWave01.tga",true,true,true,false));
+ CHECK(!Replace(name,"EXShockWav.tga",true,true,true,false));
+ }
+ CHECK(!Replace(nullptr,"EXWave01.tga",true,true,true,false));
+ CHECK(!Replace("AmphibWave",nullptr,true,true,true,false));
+ CHECK(!Replace("AmphibWave","EXWave01.tga.extra",true,true,true,false));
+ CHECK(!Replace("AmphibWave","Other/EXWave01.tga",true,true,true,false));
+}
+
+TEST(water_authored_splash_rings_survive_every_pass_admission)
+{
+ using namespace WaterFoamParticlePolicy;
+ for(const char *name:{"AirCarrierWaterRipples","BattleShipWaterRipples"}) {
+ // Authored splash rings remain visible with modern hull foam, in the main and mirror passes.
+ CHECK(!KnownSurfaceFoam(name,"EXShockWav.tga"));
+ for(unsigned flags=0;flags<8;++flags) {
+ const bool ground=(flags&1)!=0,owner=(flags&2)!=0,admitted=(flags&4)!=0;
+ CHECK(!Replace(name,"EXShockWav.tga",ground,owner,admitted,false));
+ CHECK(!ExcludeSelfReflection(name,"EXShockWav.tga",ground,owner,admitted));
+ }
+ }
+}
+
+TEST(water_surface_foam_does_not_reflect_itself_into_same_modern_plane)
+{
+ using namespace WaterFoamParticlePolicy;
+ for(const auto pair:{std::make_pair("AmphibWave","EXWave01.tga"),std::make_pair("AmphibWaveRest","EXShockWav.tga")}) {
+ for(unsigned flags=0;flags<8;++flags)
+ CHECK(ExcludeSelfReflection(pair.first,pair.second,(flags&1)!=0,(flags&2)!=0,(flags&4)!=0)==(flags==7));
+ // Mirror exclusion is independent of successful main-view foam replacement.
+ CHECK(!Replace(pair.first,pair.second,true,true,false,false));
+ CHECK(ExcludeSelfReflection(pair.first,pair.second,true,true,true));
+ CHECK(!ExcludeSelfReflection(pair.first,"Smoke.tga",true,true,true));
+ }
+ for(const char *name:{"AmphibWaveSpray","MuzzleFlash","Explosion","Smoke","CustomWake",
+ "AirCarrierWaterRipplesExtra","BattleShipWaterRipple","AirCarrierBowWake","AirCarrierSideWake",
+ "AirCarrierPropWake","AirCarrierWaterWake","AirCarrierWaterWakePort"}) {
+ CHECK(!ExcludeSelfReflection(name,"EXWave01.tga",true,true,true));
+ CHECK(!ExcludeSelfReflection(name,"EXShockWav.tga",true,true,true));
+ }
+ for(const char *name:{"AirCarrierWaterRipples","BattleShipWaterRipples"})
+ for(const char *texture:{static_cast<const char*>(nullptr),"","EXWave01.tga","EXWater01.tga",
+ "Other/EXShockWav.tga","EXShockWav.tga.extra"})
+ CHECK(!ExcludeSelfReflection(name,texture,true,true,true));
+ CHECK(!ExcludeSelfReflection(nullptr,"EXWave01.tga",true,true,true));
+ CHECK(!ExcludeSelfReflection("AmphibWave",nullptr,true,true,true));
+ CHECK(SameMirrorSurface(true,true,4.0f,4.0f));
+ CHECK(SameMirrorSurface(true,true,4.04f,4.0f));
+ CHECK(!SameMirrorSurface(true,true,4.2f,4.0f));
+ CHECK(!SameMirrorSurface(true,true,-4.0f,4.0f));
+ CHECK(!SameMirrorSurface(false,true,4.0f,4.0f)); // main, legacy or released target
+ CHECK(!SameMirrorSurface(true,false,4.0f,4.0f)); // removed, hidden, dry or missing owner
+ CHECK(!SameMirrorSurface(true,true,std::numeric_limits<float>::quiet_NaN(),4.0f));
+ CHECK(!SameMirrorSurface(true,true,4.0f,std::numeric_limits<float>::infinity()));
+}
+
+namespace {
+// Independent parameter-domain oracle: it knows triangles and scanlines, not the
+// subdivision stencil, admission policy or edge-morph implementation under test.
+using BowTestPoint=WaterProjectedMesh::Point;
+using BowTestTriangle=std::array<BowTestPoint,3>;
+using BowTestInterval=std::pair<double,double>;
+double bowTestArea(const BowTestTriangle &p)
+{
+ return .5*((p[1].x-p[0].x)*(p[2].y-p[0].y)-(p[1].y-p[0].y)*(p[2].x-p[0].x));
+}
+bool bowTestCoincident(const BowTestTriangle &p)
+{
+ for(unsigned i=0;i<3;++i) if(p[i].x==p[(i+1)%3].x && p[i].y==p[(i+1)%3].y) return true;
+ return false;
+}
+std::vector<BowTestTriangle> bowTestTriangles(const WaterProjectedMesh::Mesh &mesh,
+ const WaterProjectedMesh::Projection &projection)
+{
+ std::vector<BowTestTriangle> result;
+ CHECK(mesh.indices.size()%3==0);
+ for(size_t i=0;i+2<mesh.indices.size();i+=3) {
+ BowTestTriangle triangle;
+ bool valid=true;
+ for(unsigned j=0;j<3;++j) {
+ const size_t index=mesh.indices[i+j];CHECK(index<mesh.vertices.size());
+ if(index>=mesh.vertices.size()) { valid=false;continue; }
+ const bool finite=projection.Transform(mesh.vertices[index].world,triangle[j]);
+ CHECK(finite);valid=valid&&finite;
+ }
+ if(valid) result.push_back(triangle);
+ }
+ return result;
+}
+std::vector<BowTestInterval> bowTestIntervals(const std::vector<BowTestTriangle> &triangles,double y)
+{
+ std::vector<BowTestInterval> result;
+ for(const auto &triangle:triangles) {
+ if(std::abs(bowTestArea(triangle))<1e-15) continue;
+ double crossing[3];unsigned count=0;
+ for(unsigned edge=0;edge<3;++edge) {
+ const auto a=triangle[edge],b=triangle[(edge+1)%3];
+ // Half-open edges count a vertex only once. Horizontal edges do not cross.
+ if((a.y<=y && y<b.y)||(b.y<=y && y<a.y))
+ crossing[count++]=a.x+(b.x-a.x)*(y-a.y)/(b.y-a.y);
+ }
+ if(count==2) {
+ const double a=(std::min)(crossing[0],crossing[1]),b=(std::max)(crossing[0],crossing[1]);
+ if(b-a>1e-13) result.emplace_back(a,b);
+ }
+ }
+ std::sort(result.begin(),result.end());return result;
+}
+struct BowTestCoverage {
+ double minimumArea=1e30,areaError=0,gap=0,overlap=0,edgeError=0;
+ bool finite=true;
+ bool Good() const { return finite && minimumArea>=-1e-12 && areaError<1e-9 && gap<1e-9 && overlap<1e-9 && edgeError<1e-9; }
+};
+BowTestCoverage bowTestCoverage(const std::vector<BowTestTriangle> &actual,
+ const std::vector<BowTestTriangle> &reference)
+{
+ BowTestCoverage audit;double area=0,expected=0,y0=1e30,y1=-1e30;
+ for(const auto &triangle:reference) {
+ expected+=bowTestArea(triangle);
+ for(auto p:triangle) { y0=(std::min)(y0,p.y);y1=(std::max)(y1,p.y); }
+ }
+ for(const auto &triangle:actual) {
+ const double a=bowTestArea(triangle);audit.finite=audit.finite&&std::isfinite(a);
+ audit.minimumArea=(std::min)(audit.minimumArea,a);area+=a;
+ }
+ audit.areaError=std::abs(area-expected);
+ // Off-lattice rows independently test the complete interval union. Total area
+ // alone would miss equal-sized holes and overlaps elsewhere in the same patch.
+ for(double fraction:{.00773,.03191,.07973,.13731,.21379,.31917,.41371,.51793,.61379,.71931,.81317,.91379,.97311,.99731}) {
+ const double y=y0+(y1-y0)*fraction;
+ const auto wanted=bowTestIntervals(reference,y),got=bowTestIntervals(actual,y);
+ if(wanted.empty()) { if(!got.empty()) audit.edgeError=1e30;continue; }
+ if(got.empty()) { audit.edgeError=1e30;continue; }
+ const double left=wanted.front().first,right=wanted.back().second;
+ audit.edgeError=(std::max)(audit.edgeError,std::abs(got.front().first-left));
+ double end=left;
+ for(auto interval:got) {
+ audit.gap=(std::max)(audit.gap,interval.first-end);
+ audit.overlap=(std::max)(audit.overlap,end-interval.first);
+ end=interval.second;
+ }
+ audit.edgeError=(std::max)(audit.edgeError,std::abs(end-right));
+ }
+ return audit;
+}
+bool bowTestSameVertex(const WaterProjectedMesh::Vertex &a,const WaterProjectedMesh::Vertex &b)
+{
+ return a.world.x==b.world.x && a.world.y==b.world.y && a.boundary==b.boundary &&
+ a.edgeParameter==b.edgeParameter && a.knot==b.knot && a.transition==b.transition && a.collar==b.collar && a.lattice==b.lattice;
+}
+// The full sample deliberately contains nonlinear position, height, floor damping
+// and UV-like metadata. Exact collapsed equality must survive more than XY alone.
+std::array<double,8> bowTestSample(BowTestPoint p)
+{
+ return {{p.x+.013*std::sin(1.73*p.y),p.y+.007*std::cos(2.1*p.x),
+ std::sin(1.4*p.x)+.41*std::cos(2.6*p.y),
+ .5+.3*std::sin(p.x*.7)*std::cos(p.y*.4),p.x/1.5,p.y/1.5,0,7}};
+}
+using BowTestSurface=std::vector<std::array<std::array<double,8>,3>>;
+BowTestSurface bowTestSurface(const std::vector<BowTestTriangle> &triangles)
+{
+ BowTestSurface surface;
+ for(const auto &triangle:triangles) {
+ // Three collinear parameter samples can form a real triangle after the
+ // nonlinear vertex shader; only identical complete samples may be removed.
+ if(bowTestCoincident(triangle)) continue;
+ std::array<std::array<double,8>,3> samples={{bowTestSample(triangle[0]),bowTestSample(triangle[1]),bowTestSample(triangle[2])}};
+ std::sort(samples.begin(),samples.end());surface.push_back(samples);
+ }
+ std::sort(surface.begin(),surface.end());return surface;
+}
+uint32_t bowTestRandom(uint32_t &state) { state=state*1664525u+1013904223u;return state; }
+}
+
+namespace {
+WaterProjectedMesh::Projection bowTestProjection()
+{
+ WaterProjectedMesh::Projection p={{1,0,0,0,1,0,0,0,1},{0},{0,0,1},.1,100,0};
+ CHECK(p.Prepare());return p;
+}
+WaterBowRefinement::Topology bowTestGrid(unsigned columns=1,unsigned rows=1)
+{
+ using namespace WaterBowRefinement;Topology mesh;
+ for(unsigned y=0;y<=rows;++y) for(unsigned x=0;x<=columns;++x) {
+ Node node;node.logical={int(x*4),int(y*4)};node.screen={double(x*4),double(y*4)};
+ node.world=node.screen;node.source=int(mesh.nodes.size());mesh.nodes.push_back(node);
+ }
+ for(unsigned y=0;y<rows;++y) for(unsigned x=0;x<columns;++x) {
+ const unsigned a=y*(columns+1)+x,b=a+1,c=b+columns+1,d=a+columns+1;
+ Triangle first;first.a=a;first.b=b;first.c=c;mesh.triangles.push_back(first);
+ Triangle second;second.a=a;second.b=c;second.c=d;mesh.triangles.push_back(second);
+ }
+ return mesh;
+}
+std::vector<BowTestTriangle> bowTestTopologyTriangles(const WaterBowRefinement::Topology &mesh,bool reverse=false)
+{
+ std::vector<BowTestTriangle> triangles;
+ for(const auto &t:mesh.triangles) {
+ CHECK(t.a<mesh.nodes.size() && t.b<mesh.nodes.size() && t.c<mesh.nodes.size());
+ if(t.a>=mesh.nodes.size() || t.b>=mesh.nodes.size() || t.c>=mesh.nodes.size()) continue;
+ BowTestTriangle tri={{mesh.nodes[t.a].screen,mesh.nodes[t.b].screen,mesh.nodes[t.c].screen}};
+ if(reverse) std::swap(tri[1],tri[2]);triangles.push_back(tri);
+ }
+ return triangles;
+}
+void bowTestAliases(const WaterBowRefinement::Topology &mesh)
+{
+ for(size_t i=0;i<mesh.nodes.size();++i) {
+ const auto &node=mesh.nodes[i];
+ CHECK(std::isfinite(node.world.x) && std::isfinite(node.world.y));
+ if(node.parent<0) continue;
+ CHECK(size_t(node.parent)<i);
+ if(size_t(node.parent)>=i) continue;
+ const auto &parent=mesh.nodes[size_t(node.parent)];
+ CHECK(node.world.x==parent.world.x && node.world.y==parent.world.y);
+ CHECK(node.screen.x==parent.screen.x && node.screen.y==parent.screen.y);
+ // This models the production complete-sample alias, including a nonlinear
+ // floor envelope and UVs. A final-logical-location sample would fail here.
+ CHECK(bowTestSample(node.world)==bowTestSample(parent.world));
+ }
+}
+bool bowTestSameTopology(const WaterBowRefinement::Topology &a,const WaterBowRefinement::Topology &b)
+{
+ if(a.nodes.size()!=b.nodes.size() || a.triangles.size()!=b.triangles.size()) return false;
+ for(size_t i=0;i<a.nodes.size();++i) {
+ const auto &x=a.nodes[i],&y=b.nodes[i];
+ if(x.logical.x!=y.logical.x || x.logical.y!=y.logical.y || x.screen.x!=y.screen.x || x.screen.y!=y.screen.y ||
+ x.world.x!=y.world.x || x.world.y!=y.world.y || x.source!=y.source || x.parent!=y.parent) return false;
+ }
+ for(size_t i=0;i<a.triangles.size();++i) {
+ const auto &x=a.triangles[i],&y=b.triangles[i];
+ if(x.a!=y.a || x.b!=y.b || x.c!=y.c || x.gate!=y.gate) return false;
+ }
+ return true;
+}
+void bowTestNoInteriorCracks(const std::vector<BowTestTriangle> &triangles,double extent)
+{
+ using Edge=std::array<double,4>;
+ std::map<Edge,std::pair<unsigned,int>> incidence;
+ for(const auto &triangle:triangles) {
+ if(bowTestCoincident(triangle)) continue;
+ for(unsigned i=0;i<3;++i) {
+ auto a=triangle[i],b=triangle[(i+1)%3];
+ if(a.x==b.x && a.y==b.y) continue;
+ int sign=1;if(a.x>b.x || (a.x==b.x && a.y>b.y)) { std::swap(a,b);sign=-1; }
+ auto &entry=incidence[{{a.x,a.y,b.x,b.y}}];++entry.first;entry.second+=sign;
+ }
+ }
+ for(const auto &edge:incidence) {
+ const auto &p=edge.first;
+ const bool boundary=(p[0]==0 && p[2]==0)||(p[1]==0 && p[3]==0)||
+ (p[0]==extent && p[2]==extent)||(p[1]==extent && p[3]==extent);
+ // A folded-down interior pair can temporarily lie on the geometric outer
+ // edge. Its opposing incidences still cancel; only single edges are borders.
+ CHECK(edge.second.first==2 || (boundary && edge.second.first==1));
+ if(edge.second.first==2) CHECK(edge.second.second==0);
+ }
+}
+}
+
+TEST(water_bow_refinement_independent_edge_morphs_preserve_union_and_winding)
+{
+ using namespace WaterBowRefinement;const auto base=bowTestGrid();const auto projection=bowTestProjection();
+ const auto reference=bowTestTopologyTriangles(base);uint32_t random=736117335u;
+ for(unsigned fixture=0;fixture<128;++fixture) {
+ std::map<std::array<int,3>,double> amounts;
+ auto weight=[&](unsigned level,Logical at,BowTestPoint) {
+ const std::array<int,3> key={{int(level),at.x,at.y}};
+ const auto found=amounts.find(key);if(found!=amounts.end()) return found->second;
+ const double t=fixture==0?0:fixture==1?1:fixture<32?double(bowTestRandom(random)&1u):double(bowTestRandom(random))/4294967295.0;
+ amounts.emplace(key,t);return t;
+ };
+ Topology fine;CHECK(Subdivide(base,projection,weight,fine,2,false));
+ const auto triangles=bowTestTopologyTriangles(fine);
+ CHECK(bowTestCoverage(triangles,reference).Good());bowTestAliases(fine);bowTestNoInteriorCracks(triangles,4);
+ // Opposite triangle winding changes no logical edge or physical sample.
+ Topology reversed=base,other;for(auto &t:reversed.triangles) std::swap(t.b,t.c);
+ std::reverse(reversed.triangles.begin(),reversed.triangles.end());
+ CHECK(Subdivide(reversed,projection,weight,other,2,false));
+ CHECK(bowTestCoverage(bowTestTopologyTriangles(other,true),reference).Good());
+ std::map<std::pair<int,int>,std::array<double,4>> locations;
+ for(const auto &n:fine.nodes) locations[{n.logical.x,n.logical.y}]={{n.screen.x,n.screen.y,n.world.x,n.world.y}};
+ for(const auto &n:other.nodes) {
+ const auto found=locations.find({n.logical.x,n.logical.y});CHECK(found!=locations.end());
+ if(found!=locations.end()) CHECK((found->second==std::array<double,4>{{n.screen.x,n.screen.y,n.world.x,n.world.y}}));
+ }
+ if(fixture==0) CHECK(bowTestSurface(triangles)==bowTestSurface(reference));
+ }
+}
+
+TEST(water_bow_refinement_zero_child_level_exactly_preserves_current_parent_surface)
+{
+ using namespace WaterBowRefinement;const auto base=bowTestGrid();const auto projection=bowTestProjection();
+ for(unsigned fixture=0;fixture<48;++fixture) {
+ auto weight=[fixture](unsigned level,Logical at,BowTestPoint) {
+ if(level==2) return 0.0;
+ uint32_t random=fixture*173u+unsigned(at.x)*119u+unsigned(at.y)*431u+17u;
+ return double(bowTestRandom(random))/4294967295.0;
+ };
+ Topology first,second;CHECK(Subdivide(base,projection,weight,first,1,false));
+ CHECK(Subdivide(base,projection,weight,second,2,false));
+ CHECK(bowTestSurface(bowTestTopologyTriangles(first))==bowTestSurface(bowTestTopologyTriangles(second)));
+ bowTestAliases(second);
+ }
+}
+
+TEST(water_bow_refinement_perspective_inverse_uses_actual_morphed_coordinates)
+{
+ using namespace WaterBowRefinement;auto base=bowTestGrid();auto projection=bowTestProjection();
+ projection.matrix[0]=.017;projection.matrix[4]=.023;projection.matrix[2]=-.31;
+ projection.matrix[5]=.17;projection.matrix[6]=.0011;projection.matrix[7]=-.0008;
+ CHECK(projection.Prepare());
+ for(auto &node:base.nodes) CHECK(projection.Transform(node.screen,node.world,true));
+ const auto reference=bowTestTopologyTriangles(base);
+ for(unsigned fixture=0;fixture<32;++fixture) {
+ auto weight=[fixture](unsigned level,Logical p,BowTestPoint) {
+ return fixture==0?0.0:(.05+.9*double((p.x*11+p.y*7+int(level)*23+int(fixture)*17)%89)/88);
+ };
+ Topology fine;CHECK(Subdivide(base,projection,weight,fine,2,false));
+ CHECK(bowTestCoverage(bowTestTopologyTriangles(fine),reference).Good());bowTestAliases(fine);
+ for(const auto &node:fine.nodes) {
+ BowTestPoint expected;CHECK(projection.Transform(node.screen,expected,true));
+ CHECK_NEAR(node.world.x,expected.x,1e-10);CHECK_NEAR(node.world.y,expected.y,1e-10);
+ if(fixture==0 && node.source<0) CHECK(node.parent>=0);
+ }
+ }
+}
+
+TEST(water_bow_refinement_sparse_zero_one_two_neighborhoods_have_no_t_junctions)
+{
+ using namespace WaterBowRefinement;const auto base=bowTestGrid(3,3);const auto projection=bowTestProjection();
+ const auto reference=bowTestTopologyTriangles(base);
+ for(unsigned fixture=0;fixture<48;++fixture) {
+ auto weight=[fixture](unsigned level,Logical at,BowTestPoint) {
+ const unsigned region=(unsigned(at.x/4)+2u*unsigned(at.y/4)+fixture)%3u;
+ if(region<level) return 0.0;
+ return fixture<3?1.0:.13+.83*double((at.x*17+at.y*29+int(fixture)*13)%97)/96;
+ };
+ Topology fine;CHECK(Subdivide(base,projection,weight,fine,2,true));
+ const auto triangles=bowTestTopologyTriangles(fine);
+ CHECK(bowTestCoverage(triangles,reference).Good());bowTestNoInteriorCracks(triangles,12);bowTestAliases(fine);
+ for(const auto &node:fine.nodes) {
+ CHECK(node.screen.x>=0 && node.screen.x<=12 && node.screen.y>=0 && node.screen.y<=12);
+ if(node.source<0 && node.parent<0)
+ CHECK(node.screen.x>0 && node.screen.x<12 && node.screen.y>0 && node.screen.y<12);
+ }
+ }
+}
+
+TEST(water_bow_refinement_coverage_oracle_rejects_fold_and_equal_area_hole_overlap)
+{
+ const auto reference=bowTestTopologyTriangles(bowTestGrid());CHECK(bowTestCoverage(reference,reference).Good());
+ auto folded=reference;std::swap(folded[0][1],folded[0][2]);CHECK(!bowTestCoverage(folded,reference).Good());
+ // Duplicate one half and omit the other: unchanged total area, yet half the
+ // square is uncovered and the other half overlaps. This arms the union oracle.
+ std::vector<BowTestTriangle> equalArea={reference[0],reference[0]};
+ const auto audit=bowTestCoverage(equalArea,reference);
+ CHECK(audit.areaError==0);CHECK(audit.gap>0 || audit.overlap>0 || audit.edgeError>0);CHECK(!audit.Good());
+}
+
+TEST(water_bow_refinement_collapsed_parent_edge_cannot_create_a_new_boundary_sample)
+{
+ using namespace WaterBowRefinement;const auto base=bowTestGrid();const auto projection=bowTestProjection();
+ auto full=[](unsigned,Logical,BowTestPoint) { return 1.0; };
+ Topology first,fine;CHECK(Subdivide(base,projection,full,first,1,true));CHECK(Subdivide(base,projection,full,fine,2,true));
+ auto find=[](const Topology &mesh,int x,int y)->int {
+ for(size_t i=0;i<mesh.nodes.size();++i) if(mesh.nodes[i].logical.x==x && mesh.nodes[i].logical.y==y) return int(i);
+ return -1;
+ };
+ const int lo=find(first,2,0),hi=find(first,4,2),child=find(fine,3,1);
+ CHECK(lo>=0 && hi>=0 && child>=0);if(lo<0 || hi<0 || child<0) return;
+ const auto a=first.nodes[size_t(lo)].screen,b=first.nodes[size_t(hi)].screen;
+ CHECK(a.x==0 && a.y==0 && b.x==4 && b.y==0);
+ // Armed old max-parent-edge gate: the diagonal split amount 1 admits this
+ // logical interior child although its parents lie on the locked outer edge.
+ const Point oldMaxTarget={(a.x+b.x)*.5,(a.y+b.y)*.5};CHECK(oldMaxTarget.x==2 && oldMaxTarget.y==0);
+ CHECK(std::abs(bowTestSample(oldMaxTarget)[2]-.5*(bowTestSample(a)[2]+bowTestSample(b)[2]))>.1);
+ auto boundarySamples=[](const Topology &mesh) {
+ unsigned count=0;for(const auto &n:mesh.nodes)
+ if(n.source<0 && n.parent<0 && (n.screen.x==0 || n.screen.x==4 || n.screen.y==0 || n.screen.y==4)) ++count;
+ return count;
+ };
+ CHECK(boundarySamples(fine)==0);CHECK(fine.nodes[size_t(child)].parent>=0);
+ auto oldMaxControl=fine;oldMaxControl.nodes[size_t(child)].parent=-1;
+ oldMaxControl.nodes[size_t(child)].screen=oldMaxTarget;oldMaxControl.nodes[size_t(child)].world=oldMaxTarget;
+ CHECK(boundarySamples(oldMaxControl)==1);
+}
+
+TEST(water_bow_refinement_invalid_input_is_atomic_and_zero_levels_are_exact)
+{
+ using namespace WaterBowRefinement;const auto base=bowTestGrid();const auto projection=bowTestProjection();
+ const auto sentinel=bowTestGrid(2,2);Topology result=sentinel;
+ auto half=[](unsigned,Logical,BowTestPoint) { return .5; };
+ CHECK(Subdivide(base,projection,half,result,0,false));CHECK(bowTestSameTopology(result,base));
+ result=sentinel;CHECK(!Subdivide(base,projection,half,result,3,false));CHECK(bowTestSameTopology(result,sentinel));
+ for(double value:{-.001,1.001,double(NAN),double(INFINITY)}) {
+ result=sentinel;
+ auto invalid=[value](unsigned,Logical,BowTestPoint) { return value; };
+ CHECK(!Subdivide(base,projection,invalid,result,2,false));CHECK(bowTestSameTopology(result,sentinel));
+ }
+ auto broken=base;broken.triangles[0].a=unsigned(base.nodes.size()+10);result=sentinel;
+ CHECK(!Subdivide(broken,projection,half,result,2,false));CHECK(bowTestSameTopology(result,sentinel));
+ auto invalidProjection=projection;invalidProjection.inverse[0]=NAN;result=sentinel;
+ CHECK(!Subdivide(base,invalidProjection,half,result,2,false));CHECK(bowTestSameTopology(result,sentinel));
+}
+
+namespace {
+// Independent scalar oracle: no shared production coefficients, gradient helper or
+// projection expression. Numeric derivatives below must agree with the emitted model.
+std::array<double,3> pressureTestParameters(double beam,double speed)
+{
+ const double u=(std::max)(0.0,(std::min)(speed,250.0)-.3);
+ return {{(std::max)(9.0,(std::min)(32.0,6+1.2*beam)),
+ (std::max)(4.0,(std::min)(60.0,1.5+.95*beam)),
+ (std::max)(3.0,(std::min)(8.0,1.8*std::sqrt(beam)))*u*u/(u*u+26*26)}};
+}
+double pressureTestScalar(const std::array<double,3> &p,double along,double across)
+{
+ const double q=across/p[1],s=along/p[0]+.6*(std::sqrt(1+q*q)-1);
+ return p[2]*std::exp(-s*s-q*q);
+}
+}
+
+TEST(water_bow_pressure_size_speed_and_half_height_are_independently_measured)
+{
+ using namespace WaterVesselWaves;
+ for(float beam:{0.0f,.1f,2.5f,6.0f,8.37f,22.0f,54.0f,100.0f}) {
+ double previous=-1;
+ for(float speed:{0.0f,.3f,.3001f,1.0f,5.0f,14.0f,26.3f,40.0f,70.0f,250.0f,500.0f}) {
+ const auto expected=pressureTestParameters(beam,speed);const auto p=BowPressure(beam,speed);
+ CHECK_NEAR(p.along,expected[0],.00001);CHECK_NEAR(p.across,expected[1],.00001);CHECK_NEAR(p.amplitude,expected[2],.000003);
+ CHECK(p.along>=9 && p.along<=32 && p.across>=4 && p.across<=60 && p.amplitude>=0 && p.amplitude<=8);
+ CHECK(p.amplitude>=previous);previous=p.amplitude;
+ const auto peak=EvaluateBowPressure(p,0,0);CHECK_NEAR(peak.height,expected[2],.000003);
+ CHECK(peak.dAlong==0 && peak.dAcross==0);
+ if(speed<=.3f) CHECK(peak.height==0);
+ if(speed<1) continue;
+ // Solve for the actual half-height point by scalar bisection. A stale
+ // 8-unit width or sqrt(2) Gaussian convention cannot satisfy this.
+ double lo=0,hi=2*expected[0];
+ for(unsigned iteration=0;iteration<48;++iteration) {
+ const double x=(lo+hi)*.5;if(pressureTestScalar(expected,x,0)>expected[2]*.5)lo=x;else hi=x;
+ }
+ CHECK_NEAR(EvaluateBowPressure(p,float((lo+hi)*.5),0).height,expected[2]*.5,.000003);
+ lo=0;hi=2*expected[1];
+ for(unsigned iteration=0;iteration<48;++iteration) {
+ const double y=(lo+hi)*.5,u=-.6*expected[0]*(std::sqrt(1+y*y/(expected[1]*expected[1]))-1);
+ if(pressureTestScalar(expected,u,y)>expected[2]*.5)lo=y;else hi=y;
+ }
+ const double y=(lo+hi)*.5,u=-.6*expected[0]*(std::sqrt(1+y*y/(expected[1]*expected[1]))-1);
+ CHECK(u<0);CHECK_NEAR(EvaluateBowPressure(p,float(u),float(y)).height,expected[2]*.5,.000003);
+ }
+ CHECK(BowPressure(beam,70).amplitude>BowPressure(beam,14).amplitude*3);
+ CHECK(BowPressure(beam,500).amplitude==BowPressure(beam,250).amplitude);
+ }
+ const auto small=BowPressure(8.37f,70),large=BowPressure(54,70);
+ CHECK(large.along>small.along && large.across>small.across && large.amplitude>small.amplitude);
+ // Armed old model: it saturates at speed14 and peaks eight units beyond
+ // the contact bow. Neither behavior is allowed to pass as pressure response.
+ CHECK(std::abs(1.9*std::exp(-1.0)-small.amplitude)>2);
+ CHECK(std::abs(BowPressure(8.37f,14).amplitude-BowPressure(8.37f,70).amplitude)>2);
+}
+
+TEST(water_bow_pressure_independent_derivatives_curvature_and_bounds)
+{
+ using namespace WaterVesselWaves;
+ for(float beam:{.1f,6.0f,8.37f,22.0f,54.0f,100.0f}) for(float speed:{.31f,5.0f,14.0f,40.0f,70.0f,250.0f}) {
+ const auto expected=pressureTestParameters(beam,speed);const auto p=BowPressure(beam,speed);
+ for(double a:{-4.0,-1.7,-.7071067811865475,0.0,.31,.7071067811865475,1.7,4.0})
+ for(double b:{-3.0,-1.3,-.5,0.0,.5,1.3,3.0}) {
+ const float x=float(a*expected[0]),y=float(b*expected[1]);const auto value=EvaluateBowPressure(p,x,y);
+ constexpr double step=.0005;
+ const double dx=(pressureTestScalar(expected,x+step,y)-pressureTestScalar(expected,x-step,y))/(2*step);
+ const double dy=(pressureTestScalar(expected,x,y+step)-pressureTestScalar(expected,x,y-step))/(2*step);
+ CHECK_NEAR(value.height,pressureTestScalar(expected,x,y),.000005);
+ CHECK_NEAR(value.dAlong,dx,.00002);CHECK_NEAR(value.dAcross,dy,.00002);
+ CHECK(value.height>=0 && value.height<=p.amplitude+.000001);
+ // Supremum of |2q exp(-q²)| is sqrt(2/e). The curved
+ // shoulder adds at most .6 times that across-slope envelope.
+ CHECK(std::abs(value.dAlong)<=std::sqrt(2/std::exp(1.0))*expected[2]/expected[0]+.000001);
+ CHECK(std::abs(value.dAcross)<=1.6*std::sqrt(2/std::exp(1.0))*expected[2]/expected[1]+.000001);
+ const auto mirror=EvaluateBowPressure(p,x,-y);
+ CHECK(value.height==mirror.height && value.dAlong==mirror.dAlong && value.dAcross==-mirror.dAcross);
+ }
+ // Rest is approached quadratically, with a zero slope at the threshold.
+ const auto a=BowPressure(beam,.301f),b=BowPressure(beam,.302f);
+ CHECK(a.amplitude<.000001 && b.amplitude>3.9f*a.amplitude && b.amplitude<4.1f*a.amplitude);
+ }
+}
+
+TEST(water_bow_refinement_uses_all_contact_packets_and_velocity_selected_bow)
+{
+ // Explicitly exercise the legacy Gaussian fallback; contour mode has separate tests.
+ using namespace WaterBowRefinement;
+ for(unsigned id=1;id<=WaterHullModel::MaxHulls;++id) for(double direction:{0.0,1.3,3.141592653589793,4.7}) {
+ const float modelAngle=float(id*.31),speed=float(5+id*3);
+ const float vx=speed*float(std::cos(direction)),vy=speed*float(std::sin(direction));
+ auto mean=foamTestHull(float(id*37),float(-int(id)*11),vx,vy,modelAngle,7),contact=mean;
+ // Unequal and off-axis endpoints prevent collision-bound or symmetric-hull
+ // approximations from passing as the shader's actual contact packet.
+ contact.data[3][0]=-17;contact.data[3][1]=-2;contact.data[3][2]=23;contact.data[3][3]=3;
+ contact.data[1][3]=float(id+2);
+ Bow bow;CHECK(MakeBow(id,mean,contact,7,bow,false));
+ const double length=std::hypot(double(vx),double(vy)),fx=vx/length,fy=vy/length;
+ const double ax=contact.data[1][0],ay=contact.data[1][1];
+ double blend=(fx*ax+fy*ay+.25)/.5;blend=(std::max)(0.0,(std::min)(1.0,blend));blend=blend*blend*(3-2*blend);
+ const double localX=-17+(23+17)*blend,localY=-2+(3+2)*blend;
+ const double x=contact.data[0][0]+ax*localX-ay*localY;
+ const double y=contact.data[0][1]+ay*localX+ax*localY;
+ CHECK(bow.id==id && bow.level==7);CHECK_NEAR(bow.origin.x,x,2e-5);CHECK_NEAR(bow.origin.y,y,2e-5);
+ CHECK_NEAR(bow.centre.x,x+9*fx,2e-5);CHECK_NEAR(bow.centre.y,y+9*fy,2e-5);
+ CHECK_NEAR(bow.forward.x,fx,1e-6);CHECK_NEAR(bow.forward.y,fy,1e-6);
+ const auto pressure=pressureTestParameters(contact.data[1][3],length);
+ CHECK_NEAR(bow.sigmaAlong,pressure[0],.00001);CHECK_NEAR(bow.sigmaAcross,pressure[1],.00001);
+ CHECK_NEAR(bow.amplitude,pressure[2],.000003);
+ double moving=(length-.3)/(14-.3);moving=(std::max)(0.0,(std::min)(1.0,moving));moving=moving*moving*(3-2*moving);
+ CHECK_NEAR(bow.moving,moving,1e-6);
+ CHECK(bow.hullCentre.x==contact.data[0][0] && bow.hullCentre.y==contact.data[0][1]);
+ contact.data[0][3]=0;Bow fallback;CHECK(MakeBow(id,mean,contact,7,fallback,false));
+ const double baseLocal=-12+24*blend;
+ CHECK_NEAR(fallback.centre.x,mean.data[0][0]+ax*baseLocal+9*fx,2e-5);
+ CHECK_NEAR(fallback.centre.y,mean.data[0][1]+ay*baseLocal+9*fy,2e-5);
+ }
+}
+
+TEST(water_bow_registration_refinement_encloses_bounded_horizontal_inverse_image)
+{
+ // Explicitly exercise the legacy Gaussian fallback; contour mode has separate tests.
+ using namespace WaterBowRefinement;
+ // CommonSource emits MaxHorizontalDisplacement/sqrt(2) per component; test
+ // its full axis-aligned square, including diagonal corners, at rotated hulls.
+ const double componentRadius=WaterFftGeometry::MaxHorizontalDisplacement/std::sqrt(2.0);
+ for(float beam:{.1f,6.0f,9.0f,30.0f,80.0f})for(unsigned orientation=0;orientation<8;++orientation) {
+ const double angle=orientation*6.283185307179586/8;
+ auto hull=foamTestHull(0,0,float(40*std::cos(angle)),float(40*std::sin(angle)),float(angle));hull.data[1][3]=beam;
+ Bow bow;CHECK(MakeBow(1,hull,hull,7,bow,false));
+ Prepared prepared;prepared.bow=bow;prepared.cell={20,20};prepared.desiredDepth=2;prepared.heightGate=1;
+ const Logical at={80,80};
+ for(int x=-6;x<=6;++x)for(int y=-6;y<=6;++y)
+ for(double shiftX:{-1.0,-.5,0.0,.5,1.0})for(double shiftY:{-1.0,-.5,0.0,.5,1.0}) {
+ const double localX=x*bow.sigmaAlong*.6,localY=y*bow.sigmaAcross*.6;
+ const Point parameter={bow.origin.x+localX*bow.forward.x-localY*bow.forward.y,
+ bow.origin.y+localX*bow.forward.y+localY*bow.forward.x};
+ const Point mapped={parameter.x+componentRadius*shiftX,parameter.y+componentRadius*shiftY};
+ const double dx=mapped.x-bow.origin.x,dy=mapped.y-bow.origin.y;
+ const double q=(-dx*bow.forward.y+dy*bow.forward.x)/bow.sigmaAcross;
+ const double u=(dx*bow.forward.x+dy*bow.forward.y)/bow.sigmaAlong+.6*(std::sqrt(1+q*q)-1);
+ const double expected=(1-Smooth(1.5,3,std::hypot(u,q)))*
+ (1-Smooth(bow.reach-30,bow.reach,std::hypot(mapped.x-bow.hullCentre.x,mapped.y-bow.hullCentre.y)));
+ CHECK(Demand(prepared,1,at,parameter)+1e-12>=expected);
+ CHECK(Demand(prepared,2,at,parameter)+1e-12>=expected);
+ // World expansion must never defeat the hard cell/region cost limits.
+ CHECK(Demand(prepared,1,{97,80},parameter)==0);
+ }
+ }
+ CHECK(MaxRegions==3 && RegionVertices==2730 && RegionTriangles==5460);
+ CHECK(MaxAddedVertices==8190 && MaxAddedTriangles==16380);
+}
+
+TEST(water_bow_refinement_stationary_wrong_level_and_nonfinite_packets_are_rejected)
+{
+ using namespace WaterBowRefinement;Bow bow;auto hull=foamTestHull(0,0,30,0);
+ CHECK(MakeBow(1,hull,hull,7,bow));CHECK(!MakeBow(1,hull,hull,7.11,bow));
+ CHECK(!MakeBow(1,hull,hull,NAN,bow));
+ for(float speed:{0.0f,.01f,.29f,.3f}) {
+ const auto stopped=foamTestHull(0,0,speed,0);CHECK(!MakeBow(1,stopped,stopped,7,bow));
+ }
+ const auto slow=foamTestHull(0,0,.31f,0);CHECK(MakeBow(1,slow,slow,7,bow));CHECK(bow.moving>0 && bow.moving<.00001);
+ for(unsigned field:{0u,1u,2u,3u}) {
+ auto invalid=hull;invalid.data[field][0]=NAN;CHECK(!MakeBow(1,invalid,invalid,7,bow));
+ }
+ // Match the shader selector: an invalid contact count falls back to the
+ // intact mean packet, including a malformed contact's unrelated coordinates.
+ Bow valid;CHECK(MakeBow(1,hull,hull,7,valid));
+ for(float count:{0.0f,2.0f,13.0f,float(NAN)}) {
+ auto invalidContact=hull;invalidContact.data[0][3]=count;invalidContact.data[0][0]=NAN;
+ CHECK(MakeBow(1,hull,invalidContact,7,bow));
+ CHECK(bow.origin.x==valid.origin.x && bow.origin.y==valid.origin.y && bow.amplitude==valid.amplitude);
+ }
+ hull.data[0][3]=0;CHECK(!MakeBow(1,hull,hull,7,bow));
+}
+
+TEST(water_bow_refinement_projected_width_matches_independent_ellipse_sampling)
+{
+ // Explicitly exercise the legacy Gaussian fallback; contour mode has separate tests.
+ using namespace WaterBowRefinement;
+ for(unsigned fixture=0;fixture<24;++fixture) {
+ const double angle=fixture*.319;
+ const auto hull=foamTestHull(float(fixture*3),float(-int(fixture)*2),float(30*std::cos(angle)),float(30*std::sin(angle)),float(angle));
+ Bow bow;CHECK(MakeBow(fixture+1,hull,hull,7,bow,false));View view;
+ view.projection=bowTestProjection();view.projection.matrix[0]=.004;view.projection.matrix[1]=fixture*.00003;
+ view.projection.matrix[3]=-.001;view.projection.matrix[4]=.007;
+ view.projection.matrix[6]=fixture*.00001;view.projection.matrix[7]=-.00012;
+ view.projection.margin=.12;CHECK(view.projection.Prepare());view.resolution={100,80};view.width=1280;view.height=720;
+ view.verticalClip[0]=.0001;view.verticalClip[1]=.0005;view.verticalClip[2]=.00001;
+ Prepared prepared;CHECK(PrepareBow(bow,view,prepared,.75));
+ // Search the projected unit covariance ellipse directly with central
+ // differences, independent of the production Jacobian/eigenvalue formula.
+ double minor=1e30;constexpr double epsilon=.002;
+ for(unsigned i=0;i<2048;++i) {
+ const double phase=i*6.283185307179586/2048;
+ const double dx=bow.sigmaAlong*bow.forward.x*std::cos(phase)-bow.sigmaAcross*bow.forward.y*std::sin(phase);
+ const double dy=bow.sigmaAlong*bow.forward.y*std::cos(phase)+bow.sigmaAcross*bow.forward.x*std::sin(phase);
+ BowTestPoint lo,hi;
+ CHECK(view.projection.Transform({bow.centre.x-epsilon*dx,bow.centre.y-epsilon*dy},lo));
+ CHECK(view.projection.Transform({bow.centre.x+epsilon*dx,bow.centre.y+epsilon*dy},hi));
+ minor=(std::min)(minor,std::hypot((hi.x-lo.x)*view.width/(4*epsilon),(hi.y-lo.y)*view.height/(4*epsilon)));
+ }
+ const double step=(std::max)(1.12*view.width/100,1.12*view.height/80);
+ // Independently find the half-height radius of the actual exp(-q*q)
+ // packet. Treating its width as a standard deviation adds a wrong sqrt(2).
+ double halfLo=0,halfHi=2;
+ for(unsigned i=0;i<48;++i) { const double q=(halfLo+halfHi)*.5;if(std::exp(-q*q)>.5) halfLo=q;else halfHi=q; }
+ const double expected=(std::max)(0.0,(std::min)(2.0,std::log2(3*step/((halfLo+halfHi)*minor))));
+ CHECK_NEAR(prepared.desiredDepth,expected,.0001);
+ CHECK(prepared.heightGate>=0 && prepared.heightGate<=1);
+ const auto *m=view.projection.matrix;
+ const double clipX=m[0]*bow.centre.x+m[1]*bow.centre.y+m[2];
+ const double clipY=m[3]*bow.centre.x+m[4]*bow.centre.y+m[5];
+ const double clipW=m[6]*bow.centre.x+m[7]*bow.centre.y+m[8];
+ auto raised=[&](double z) {
+ return BowTestPoint{(clipX+z*view.verticalClip[0])/(clipW+z*view.verticalClip[2]),
+ (clipY+z*view.verticalClip[1])/(clipW+z*view.verticalClip[2])};
+ };
+ const auto lower=raised(-epsilon),upper=raised(epsilon);
+ const double verticalPixels=std::hypot((upper.x-lower.x)*view.width/(4*epsilon),(upper.y-lower.y)*view.height/(4*epsilon));
+ const auto pressure=pressureTestParameters(hull.data[1][3],30);
+ const double pressureHeight=pressureTestScalar(pressure,9,0);
+ const double bound=WaterFftGeometry::MaxVerticalDisplacement;
+ double height=(verticalPixels*bound*std::tanh(pressureHeight/bound)*.75-.25)/.75;
+ height=(std::max)(0.0,(std::min)(1.0,height));height=height*height*(3-2*height);
+ CHECK_NEAR(prepared.heightGate,height,.000001);
+ BowTestPoint anchorScreen;CHECK(view.projection.Transform(bow.origin,anchorScreen));
+ CHECK_NEAR(prepared.cell.x,(anchorScreen.x/1.12+1)*50,1e-10);
+ CHECK_NEAR(prepared.cell.y,(anchorScreen.y/1.12+1)*40,1e-10);
+ Prepared hidden;CHECK(PrepareBow(bow,view,hidden,0));CHECK(hidden.heightGate==0);
+ const Logical at={int(std::round(prepared.cell.x*4)),int(std::round(prepared.cell.y*4))};
+ for(unsigned level:{1u,2u}) CHECK(Demand(hidden,level,at,bow.centre)==0);
+ }
+}
+
+TEST(water_bow_refinement_demand_is_bounded_local_continuous_and_pause_repeatable)
+{
+ // Explicitly exercise the legacy Gaussian fallback; contour mode has separate tests.
+ using namespace WaterBowRefinement;Bow bow;const auto hull=foamTestHull(0,0,30,0);
+ CHECK(MakeBow(1,hull,hull,7,bow,false));Prepared p;p.bow=bow;p.cell={20,20};p.heightGate=1;
+ const double radius=WaterFftGeometry::MaxHorizontalDisplacement;
+ const double allowance=radius*std::sqrt(1/(bow.sigmaAlong*bow.sigmaAlong)+
+ (1+.6*.6)/(bow.sigmaAcross*bow.sigmaAcross));
+ const Logical at={80,80};double previous[2]={0,0};
+ for(unsigned i=0;i<=400;++i) {
+ p.desiredDepth=double(i)/200;
+ const double a=Demand(p,1,at,bow.centre),b=Demand(p,2,at,bow.centre);
+ CHECK(a>=0 && a<=1 && b>=0 && b<=a);CHECK(a>=previous[0] && b>=previous[1]);
+ CHECK(a-previous[0]<.008 && b-previous[1]<.008);previous[0]=a;previous[1]=b;
+ CHECK(a==Demand(p,1,at,bow.centre) && b==Demand(p,2,at,bow.centre));
+ }
+ CHECK(previous[0]==1 && previous[1]==1);
+ for(unsigned level:{1u,2u}) {
+ CHECK(Demand(p,level,at,bow.centre,0)==0);
+ CHECK_NEAR(Demand(p,level,at,bow.centre,.37),.37,1e-12);
+ CHECK(Demand(p,level,{at.x+17,at.y},bow.centre)==0);
+ CHECK(Demand(p,level,at,{bow.origin.x+(3+allowance)*bow.sigmaAlong+.001,bow.origin.y})==0);
+ CHECK(Demand(p,level,at,{bow.origin.x,bow.origin.y+(3+allowance)*bow.sigmaAcross+.001})==0);
+ CHECK(Demand(p,level,at,{NAN,0})==0);
+ }
+ CHECK(Demand(p,0,at,bow.centre)==0 && Demand(p,3,at,bow.centre)==0);
+ const double across=1.4*bow.sigmaAcross;
+ const double along=-.6*bow.sigmaAlong*(std::sqrt(1+1.4*1.4)-1);
+ const BowTestPoint shoulder={bow.origin.x+along,bow.origin.y+across};
+ CHECK_NEAR(Demand(p,1,at,shoulder),1,1e-12);
+ const BowTestPoint outside={bow.origin.x+(3.1+allowance)*bow.sigmaAlong,bow.origin.y};
+ CHECK(Demand(p,1,at,outside)==0);
+ // The original radial culling contract also limits the wider pressure wing.
+ CHECK(Demand(p,1,at,{bow.hullCentre.x+bow.reach+radius,bow.hullCentre.y})==0);
+}
+
+namespace {
+WaterBowRefinement::View bowTestView()
+{
+ WaterBowRefinement::View view;view.projection=testWaterProjection();view.projection.matrix[0]=.005;
+ view.projection.matrix[4]=.005;CHECK(view.projection.Prepare());view.resolution={40,40};view.width=1280;view.height=720;
+ view.verticalClip[1]=.01;return view;
+}
+WaterBowRefinement::Active bowTestActive(const WaterBowRefinement::View &view,double x,double y,unsigned id=1)
+{
+ using namespace WaterBowRefinement;const auto hull=foamTestHull(float(x-20),float(y),30,0);
+ // These legacy topology fixtures place the Gaussian centre at endpoint + 9.
+ Active active;Bow bow;CHECK(MakeBow(id,hull,hull,7,bow,false));CHECK(PrepareBow(bow,view,active.prepared));
+ active.amount=1;return active;
+}
+bool bowTestSameMesh(const WaterProjectedMesh::Mesh &a,const WaterProjectedMesh::Mesh &b)
+{
+ if(a.indices!=b.indices || a.cells!=b.cells || a.vertices.size()!=b.vertices.size() ||
+ a.collars.size()!=b.collars.size() || a.transitions.size()!=b.transitions.size()) return false;
+ for(size_t i=0;i<a.vertices.size();++i) if(!bowTestSameVertex(a.vertices[i],b.vertices[i])) return false;
+ // These arrays are not touched or reconstructed by optional refinement. Byte
+ // comparison against the saved copy also catches accidental metadata writes.
+ for(size_t i=0;i<a.transitions.size();++i)
+ if(std::memcmp(&a.transitions[i],&b.transitions[i],sizeof(a.transitions[i]))) return false;
+ for(size_t i=0;i<a.collars.size();++i)
+ if(std::memcmp(&a.collars[i],&b.collars[i],sizeof(a.collars[i]))) return false;
+ return true;
+}
+const WaterBowRefinement::Admissions::Slot *bowTestSlot(const WaterBowRefinement::Admissions &admissions,unsigned id)
+{
+ for(const auto &slot:admissions.Slots()) if(slot.occupied && slot.bow.id==id) return &slot;
+ return nullptr;
+}
+}
+
+TEST(water_bow_refinement_projected_build_keeps_protected_metadata_and_boundary_triangles)
+{
+ using namespace WaterProjectedMesh;using namespace WaterBowRefinement;
+ const Point corners[4]={{-190,-180},{195,-165},{185,190},{-180,180}};const auto view=bowTestView();
+ std::vector<BoundaryKnot> knots;
+ for(unsigned edge=0;edge<4;++edge) {
+ Point a=corners[edge],b=corners[(edge+1)%4];if(a.x>b.x || (a.x==b.x && a.y>b.y)) std::swap(a,b);
+ for(unsigned i=0;i<=17;++i) { const double t=double(i)/17;knots.push_back({{a.x+(b.x-a.x)*t,a.y+(b.y-a.y)*t},int(edge),int(i),t}); }
+ }
+ Mesh base;CHECK(Build(corners,view.projection,view.resolution,base,60000,knots));
+ CHECK(!base.collars.empty() && !base.transitions.empty());
+ const auto reference=bowTestTriangles(base,view.projection);
+ for(Point centre:{Point{0,0},Point{-157,0},Point{-143,0},Point{145,0}}) {
+ const auto active=bowTestActive(view,centre.x,centre.y);Mesh fine=base;Stats stats;
+ CHECK(Refine(fine,view,corners,{active},60000,stats));
+ CHECK(fine.vertices.size()>=base.vertices.size());CHECK(stats.addedVertices<=RegionVertices && stats.addedTriangles<=RegionTriangles);
+ CHECK(fine.vertices.size()<65535);CHECK(bowTestCoverage(bowTestTriangles(fine,view.projection),reference).Good());
+ for(size_t i=0;i<base.vertices.size();++i) CHECK(bowTestSameVertex(base.vertices[i],fine.vertices[i]));
+ CHECK(base.collars.size()==fine.collars.size() && base.transitions.size()==fine.transitions.size());
+ std::set<std::array<uint16_t,3>> triangles;
+ for(size_t i=0;i<fine.indices.size();i+=3) triangles.insert({{fine.indices[i],fine.indices[i+1],fine.indices[i+2]}});
+ unsigned protectedCount=0;
+ for(size_t i=0;i<base.indices.size();i+=3) {
+ bool protectedTriangle=false;
+ for(unsigned j=0;j<3;++j) {
+ const auto &v=base.vertices[base.indices[i+j]];
+ protectedTriangle|=v.boundary>=0 || v.collar>=0 || v.transition>=0 || v.knot>=0 || v.lattice<0;
+ }
+ if(protectedTriangle) { ++protectedCount;CHECK(triangles.count({{base.indices[i],base.indices[i+1],base.indices[i+2]}})==1); }
+ }
+ CHECK(protectedCount>0);
+ if(centre.x==0) CHECK(stats.addedVertices>0 && stats.addedTriangles>0);
+ for(size_t i=base.vertices.size();i<fine.vertices.size();++i) {
+ const auto &v=fine.vertices[i];CHECK(v.boundary<0 && v.collar<0 && v.transition<0 && v.knot<0 && v.lattice<0);
+ const auto collar=CollarAt(corners,v.world);CHECK(collar.count==0);
+ }
+ }
+}
+
+TEST(water_bow_refinement_denied_budget_and_zero_demand_preserve_exact_base_mesh)
+{
+ using namespace WaterProjectedMesh;using namespace WaterBowRefinement;
+ const Point corners[4]={{-300,-300},{300,-300},{300,300},{-300,300}};const auto view=bowTestView();
+ Mesh base;CHECK(Build(corners,view.projection,view.resolution,base));const auto active=bowTestActive(view,0,0);
+ for(size_t budget:{base.vertices.size(),base.vertices.size()+1}) {
+ Mesh denied=base;Stats stats;CHECK(!Refine(denied,view,corners,{active},budget,stats));
+ CHECK(stats.rejected && bowTestSameMesh(denied,base));
+ }
+ for(unsigned exhausted=0;exhausted<2;++exhausted) {
+ Mesh denied=base;Stats stats;
+ CHECK(!Refine(denied,view,corners,{active},60000,stats,exhausted?MaxAddedVertices:0,exhausted?0:MaxAddedTriangles));
+ CHECK(stats.rejected && bowTestSameMesh(denied,base));
+ }
+ for(unsigned field=0;field<5;++field) {
+ auto invalid=active;
+ if(field==0) invalid.amount=NAN;if(field==1) invalid.amount=1.1;
+ if(field==2) invalid.prepared.desiredDepth=NAN;if(field==3) invalid.prepared.heightGate=-.1;
+ if(field==4) invalid.prepared.heightGate=INFINITY;
+ Mesh denied=base;Stats stats;CHECK(!Refine(denied,view,corners,{invalid},60000,stats));
+ CHECK(stats.rejected && bowTestSameMesh(denied,base));
+ }
+ {
+ Mesh invalid=base;invalid.indices[0]=uint16_t(base.vertices.size()+1);const auto saved=invalid;Stats stats;
+ CHECK(!Refine(invalid,view,corners,{active},60000,stats));CHECK(stats.rejected && bowTestSameMesh(invalid,saved));
+ }
+ for(unsigned reason=0;reason<4;++reason) {
+ auto noDemand=active;
+ if(reason==0) noDemand.amount=0;if(reason==1) noDemand.prepared.heightGate=0;
+ if(reason==2) noDemand.prepared.desiredDepth=0;
+ if(reason==3) noDemand.prepared.cell={-1000,-1000};
+ Mesh same=base;Stats stats;CHECK(Refine(same,view,corners,{noDemand},60000,stats));
+ CHECK(!stats.rejected && stats.addedVertices==0 && bowTestSameMesh(same,base));
+ }
+ Mesh denied=base;Stats stats;
+ CHECK(!Refine(denied,view,corners,std::vector<Active>(MaxRegions+1,active),60000,stats));
+ CHECK(stats.rejected && bowTestSameMesh(denied,base));
+ std::vector<Active> admitted;
+ for(unsigned id=1;id<=MaxRegions;++id) admitted.push_back(bowTestActive(view,double(int(id)-2)*75,0,id));
+ Mesh bounded=base;CHECK(Refine(bounded,view,corners,admitted,60000,stats));
+ CHECK(stats.addedVertices>0 && stats.addedVertices<=MaxAddedVertices && stats.addedTriangles<=MaxAddedTriangles);
+ CHECK(bounded.vertices.size()==base.vertices.size()+stats.addedVertices && bounded.vertices.size()<65535);
+ CHECK(bowTestCoverage(bowTestTriangles(bounded,view.projection),bowTestTriangles(base,view.projection)).Good());
+}
+
+TEST(water_bow_refinement_admission_reserves_capacity_and_retires_without_replacement_pop)
+{
+ using namespace WaterBowRefinement;
+ const Point corners[4]={{-300,-300},{300,-300},{300,300},{-300,300}};const auto key=MakePatchKey(corners,7);
+ const size_t patchBaseBudget=2048;CHECK(patchBaseBudget<Admissions::WorstBaseVertices());
+ std::array<Bow,WaterHullModel::MaxHulls> bows;
+ for(unsigned i=0;i<bows.size();++i) { const auto hull=foamTestHull(float(i*5),0,30,0);CHECK(MakeBow(i+1,hull,hull,7,bows[i])); }
+ Admissions state;state.Begin(0);
+ for(unsigned i=0;i<bows.size();++i) CHECK(state.Request(key,bows[i],patchBaseBudget)==(i<MaxRegions));
+ state.End();CHECK(bowTestSlot(state,1) && bowTestSlot(state,2) && bowTestSlot(state,3));
+ CHECK(bowTestSlot(state,1)->amount==0 && bowTestSlot(state,2)->amount==0 && bowTestSlot(state,3)->amount==0);
+ double previous=0,time=0;
+ for(unsigned frame=1;frame<=16;++frame) {
+ time=frame*.025;state.Begin(time);
+ // Demand order and small viewport changes cannot replace retained slots.
+ for(unsigned i=MaxRegions;i<bows.size();++i) CHECK(!state.Request(key,bows[i],patchBaseBudget));
+ CHECK(state.Request(key,bows[2],patchBaseBudget));CHECK(state.Request(key,bows[1],patchBaseBudget));
+ CHECK(state.Request(key,bows[0],patchBaseBudget));
+ const double firstRequest=bowTestSlot(state,1)->amount;CHECK(state.Request(key,bows[0],patchBaseBudget));
+ CHECK(bowTestSlot(state,1)->amount==firstRequest);state.End();
+ const double amount=bowTestSlot(state,1)->amount;CHECK(amount>=previous && amount-previous<=.100000000001);previous=amount;
+ }
+ CHECK(previous==1);
+ for(unsigned repeat=0;repeat<8;++repeat) {
+ state.Begin(time);for(unsigned i=0;i<MaxRegions;++i) CHECK(state.Request(key,bows[i],patchBaseBudget));state.End();
+ CHECK(bowTestSlot(state,1)->amount==1 && bowTestSlot(state,2)->amount==1);
+ }
+ previous=1;
+ for(unsigned frame=1;frame<=12 && bowTestSlot(state,1);++frame) {
+ time+=.025;state.Begin(time);CHECK(state.Request(key,bows[1],patchBaseBudget));CHECK(state.Request(key,bows[2],patchBaseBudget));
+ CHECK(!state.Request(key,bows[3],patchBaseBudget));state.End();
+ const auto *retiring=bowTestSlot(state,1);
+ const double amount=retiring?retiring->amount:0;CHECK(amount<=previous && previous-amount<=.100000000001);previous=amount;
+ }
+ CHECK(!bowTestSlot(state,1));
+ // The next request after the outgoing reserve retires starts exactly collapsed.
+ time+=.025;state.Begin(time);CHECK(state.Request(key,bows[1],patchBaseBudget));CHECK(state.Request(key,bows[2],patchBaseBudget));
+ CHECK(state.Request(key,bows[3],patchBaseBudget));state.End();
+ CHECK(bowTestSlot(state,4) && bowTestSlot(state,4)->amount==0);CHECK(bowTestSlot(state,2)->amount==1);
+ CHECK(!(key==MakePatchKey(corners,8)));
+ state.Clear();for(const auto &slot:state.Slots()) CHECK(!slot.occupied);
+}
+
+TEST(water_bow_refinement_teleport_clock_reset_and_all_eight_hulls_stay_bounded)
+{
+ using namespace WaterBowRefinement;
+ const Point corners[4]={{-300,-300},{300,-300},{300,300},{-300,300}};const auto key=MakePatchKey(corners,7);
+ Admissions state;std::array<Bow,WaterHullModel::MaxHulls> bows;
+ for(unsigned i=0;i<bows.size();++i) { const auto hull=foamTestHull(float(i*5),0,30,0);CHECK(MakeBow(i+1,hull,hull,7,bows[i])); }
+ state.Begin(10);for(unsigned i=0;i<bows.size();++i) CHECK(state.Request(key,bows[i],60000)==(i<MaxRegions));state.End();
+ state.Begin(10.25);for(unsigned i=0;i<MaxRegions;++i) CHECK(state.Request(key,bows[i],60000));state.End();
+ for(const auto &slot:state.Slots()) CHECK(slot.occupied && slot.amount==1);
+ const auto oldCentre=bows[0].centre;bows[0].centre.x+=1000;
+ state.Begin(10.275);CHECK(!state.Request(key,bows[0],60000));
+ for(unsigned i=1;i<MaxRegions;++i) CHECK(state.Request(key,bows[i],60000));state.End();
+ const auto *old=bowTestSlot(state,1);CHECK(old && old->bow.centre.x==oldCentre.x && old->amount>0 && old->amount<1);
+ state.Begin(1);for(const auto &slot:state.Slots()) CHECK(!slot.occupied); // new level/water clock
+ CHECK(state.Request(key,bows[0],60000));state.End();CHECK(bowTestSlot(state,1)->amount==0);
+ state.Begin(NAN);for(const auto &slot:state.Slots()) CHECK(!slot.occupied);
+}
+
+TEST(water_bow_refinement_adjacent_reversed_authored_edges_remain_exact)
+{
+ using namespace WaterProjectedMesh;using namespace WaterBowRefinement;const auto view=bowTestView();
+ const Point left[4]={{-180,-180},{0,-180},{0,180},{-180,180}};
+ const Point right[4]={{180,180},{0,180},{0,-180},{180,-180}};
+ Mesh a,b;CHECK(Build(left,view.projection,view.resolution,a));CHECK(Build(right,view.projection,view.resolution,b));
+ const Mesh originalA=a,originalB=b;Stats stats;
+ CHECK(Refine(a,view,left,{bowTestActive(view,-90,0)},60000,stats));
+ CHECK(Refine(b,view,right,{bowTestActive(view,90,0,2)},60000,stats));
+ auto boundary=[](const Mesh &mesh) {
+ std::vector<double> values;
+ for(const auto &vertex:mesh.vertices) if(vertex.world.x==0 && vertex.boundary>=0) values.push_back(vertex.world.y);
+ std::sort(values.begin(),values.end());return values;
+ };
+ CHECK(boundary(a)==boundary(originalA) && boundary(b)==boundary(originalB));CHECK(boundary(a)==boundary(b));
+ CHECK(bowTestCoverage(bowTestTriangles(a,view.projection),bowTestTriangles(originalA,view.projection)).Good());
+ CHECK(bowTestCoverage(bowTestTriangles(b,view.projection),bowTestTriangles(originalB,view.projection)).Good());
+}
+
+namespace {
+double bowTestInterpolatedSurface(const WaterProjectedMesh::Mesh &mesh,BowTestPoint q)
+{
+ for(size_t i=0;i<mesh.indices.size();i+=3) {
+ const auto a=mesh.vertices[mesh.indices[i]].world,b=mesh.vertices[mesh.indices[i+1]].world,c=mesh.vertices[mesh.indices[i+2]].world;
+ const double den=(b.y-c.y)*(a.x-c.x)+(c.x-b.x)*(a.y-c.y);
+ if(std::abs(den)<1e-12) continue;
+ const double u=((b.y-c.y)*(q.x-c.x)+(c.x-b.x)*(q.y-c.y))/den;
+ const double v=((c.y-a.y)*(q.x-c.x)+(a.x-c.x)*(q.y-c.y))/den,w=1-u-v;
+ if(u>=-1e-10 && v>=-1e-10 && w>=-1e-10)
+ return u*bowTestSample(a)[2]+v*bowTestSample(b)[2]+w*bowTestSample(c)[2];
+ }
+ CHECK(false);return NAN;
+}
+}
+
+TEST(water_bow_refinement_window_crossings_are_continuous_and_resize_rebuilds_cleanly)
+{
+ using namespace WaterProjectedMesh;using namespace WaterBowRefinement;
+ const Point corners[4]={{-300,-300},{300,-300},{300,300},{-300,300}};const auto view=bowTestView();
+ Mesh base;CHECK(Build(corners,view.projection,view.resolution,base));
+ for(double column:{19.0,20.0,21.0}) {
+ Mesh side[2];
+ for(unsigned sign=0;sign<2;++sign) {
+ const double cell=column+(sign?1:-1)*.000001;
+ const double screen=1.12*(cell*2/view.resolution.columns-1);BowTestPoint world;
+ CHECK(view.projection.Transform({screen,0},world,true));
+ // Preserve this tiny double displacement: native Hull packets are floats,
+ // so use a prepared descriptor to test the window threshold itself.
+ auto active=bowTestActive(view,0,0);active.prepared.cell.x=cell;active.prepared.bow.centre=world;
+ side[sign]=base;Stats stats;CHECK(Refine(side[sign],view,corners,{active},60000,stats));
+ CHECK(stats.addedVertices>0 && !stats.rejected);
+ }
+ for(unsigned y=0;y<7;++y) for(unsigned x=0;x<7;++x) {
+ const Point q={-29.731+x*9.37,-28.913+y*9.13};
+ const double a=bowTestInterpolatedSurface(side[0],q),b=bowTestInterpolatedSurface(side[1],q);
+ CHECK(std::abs(a-b)<.001);
+ }
+ }
+ for(Resolution resolution:{Resolution{40,40},Resolution{64,48},Resolution{40,40}}) {
+ auto resized=view;resized.resolution=resolution;resized.width=resolution.columns*24;resized.height=resolution.rows*16;
+ Mesh rebuilt;CHECK(Build(corners,resized.projection,resolution,rebuilt));const auto original=rebuilt;
+ Stats stats;CHECK(Refine(rebuilt,resized,corners,{bowTestActive(resized,0,0)},60000,stats));
+ CHECK(stats.addedVertices<=RegionVertices && stats.addedTriangles<=RegionTriangles);
+ CHECK(bowTestCoverage(bowTestTriangles(rebuilt,resized.projection),bowTestTriangles(original,resized.projection)).Good());
+ Mesh repeat=original;Stats repeated;
+ CHECK(Refine(repeat,resized,corners,{bowTestActive(resized,0,0)},60000,repeated));CHECK(bowTestSameMesh(rebuilt,repeat));
+ }
+}
+
+TEST(water_bow_refinement_small_patch_budget_uses_separate_reserve_without_reducing_base)
+{
+ using namespace WaterProjectedMesh;using namespace WaterBowRefinement;
+ const Point corners[4]={{-300,-300},{300,-300},{300,300},{-300,300}};auto view=bowTestView();
+ const size_t patchBaseBudget=1600;view.resolution=ChooseResolution(1280,720,80,262144);
+ CHECK(VertexBound(view.resolution.columns,view.resolution.rows)<=262144u/80u);
+ Mesh base;CHECK(Build(corners,view.projection,view.resolution,base,patchBaseBudget));
+ Admissions state;state.Begin(0);const auto active=bowTestActive(view,0,0);
+ CHECK(state.Request(MakePatchKey(corners,7),active.prepared.bow,patchBaseBudget));state.End();
+ Mesh fine=base;Stats stats;CHECK(Refine(fine,view,corners,{active},patchBaseBudget+RegionVertices,stats));
+ CHECK(stats.addedVertices>0 && stats.addedVertices<=RegionVertices);
+ CHECK(fine.cells==base.cells && fine.vertices.size()==base.vertices.size()+stats.addedVertices);
+ for(size_t i=0;i<base.vertices.size();++i) CHECK(bowTestSameVertex(base.vertices[i],fine.vertices[i]));
+ CHECK(bowTestCoverage(bowTestTriangles(fine,view.projection),bowTestTriangles(base,view.projection)).Good());
+ CHECK(MaxAddedVertices==8190 && MaxAddedTriangles==16380);
+ // Even an oversized caller budget cannot wrap the 16-bit draw indices.
+ Mesh nearLimit=base;nearLimit.vertices.resize(65534,base.vertices[0]);const auto saved=nearLimit;
+ CHECK(!Refine(nearLimit,view,corners,{active},100000,stats));CHECK(stats.rejected && bowTestSameMesh(nearLimit,saved));
+ Topology sentinel=bowTestGrid(),output=sentinel;const auto many=bowTestGrid(26,26);
+ auto full=[](unsigned,Logical,BowTestPoint) { return 1.0; };
+ CHECK(!Subdivide(many,bowTestProjection(),full,output,2,false));CHECK(bowTestSameTopology(output,sentinel));
+}
+
+TEST(water_bow_refinement_invalid_view_does_not_create_demand)
+{
+ using namespace WaterBowRefinement;const auto good=bowTestView();const auto active=bowTestActive(good,0,0);
+ for(unsigned field=0;field<7;++field) {
+ auto view=good;auto bow=active.prepared.bow;Prepared result;result.desiredDepth=.713;
+ if(field==0) view.width=NAN;if(field==1) view.height=INFINITY;
+ if(field==2) bow.centre.x=NAN;if(field==3) bow.forward.y=INFINITY;
+ if(field==4) bow.sigmaAcross=NAN;if(field==5) bow.moving=NAN;
+ const double amplitude=field==6?double(NAN):1;
+ CHECK(!PrepareBow(bow,view,result,amplitude));CHECK(result.desiredDepth==.713);
+ }
+}
+
+TEST(water_bow_refinement_coincident_patch_owners_share_the_global_cap)
+{
+ using namespace WaterBowRefinement;const Point corners[4]={{-300,-300},{300,-300},{300,300},{-300,300}};
+ Bow bow;const auto hull=foamTestHull(0,0,30,0);CHECK(MakeBow(1,hull,hull,7,bow));
+ Admissions state;state.Begin(0);
+ CHECK(!state.Request(MakePatchKey(corners,7),bow,0));CHECK(!state.Request(MakePatchKey(corners,7),bow,65536));
+ for(unsigned owner=1;owner<=8;++owner) {
+ const auto key=MakePatchKey(corners,7,uintptr_t(owner),0);
+ CHECK(state.Request(key,bow,1024)==(owner<=MaxRegions));
+ CHECK(!(key==MakePatchKey(corners,7,uintptr_t(owner),1)));
+ CHECK(!(key==MakePatchKey(corners,7,uintptr_t(owner+1),0)));
+ }
+ state.End();unsigned occupied=0;for(const auto &slot:state.Slots()) occupied+=slot.occupied?1u:0u;
+ CHECK(occupied==MaxRegions && occupied*RegionVertices<=MaxAddedVertices && occupied*RegionTriangles<=MaxAddedTriangles);
+}
+
+TEST(water_bow_refinement_unrelated_visible_patches_cannot_spend_bow_admission)
+{
+ using namespace WaterProjectedMesh;using namespace WaterBowRefinement;
+ auto view=bowTestView();view.resolution={80,80};const auto actual=bowTestActive(view,0,0);
+ const Point unrelated[3][4]={
+ {{-220,-60},{-110,-60},{-110,60},{-220,60}},
+ {{110,-60},{220,-60},{220,60},{110,60}},
+ {{-60,110},{60,110},{60,220},{-60,220}}};
+ const Point ownCentre[3]={{-165,0},{165,0},{0,165}};
+ Admissions admissions;admissions.Begin(0);
+ for(unsigned i=0;i<3;++i) {
+ Mesh mesh;CHECK(Build(unrelated[i],view.projection,view.resolution,mesh));const auto saved=mesh;
+ CHECK(!mesh.indices.empty());CHECK(!HasRefinableDemand(mesh,view,unrelated[i],actual.prepared));
+ if(HasRefinableDemand(mesh,view,unrelated[i],actual.prepared))
+ admissions.Request(MakePatchKey(unrelated[i],7,uintptr_t(i+1)),actual.prepared.bow,60000);
+ CHECK(bowTestSameMesh(mesh,saved));
+ // Prove each negative is spatial, not an empty, invisible or universally
+ // protected fixture: a bow at that polygon's own centre really adds detail.
+ const auto local=bowTestActive(view,ownCentre[i].x,ownCentre[i].y,i+2);
+ CHECK(HasRefinableDemand(mesh,view,unrelated[i],local.prepared));
+ Stats stats;CHECK(Refine(mesh,view,unrelated[i],{local},60000,stats));CHECK(stats.addedVertices>0);
+ }
+ for(const auto &slot:admissions.Slots()) CHECK(!slot.occupied);
+ const Point boatPatch[4]={{-100,-100},{100,-100},{100,100},{-100,100}};
+ Mesh mesh;CHECK(Build(boatPatch,view.projection,view.resolution,mesh));const auto saved=mesh;
+ CHECK(HasRefinableDemand(mesh,view,boatPatch,actual.prepared));CHECK(bowTestSameMesh(mesh,saved));
+ CHECK(admissions.Request(MakePatchKey(boatPatch,7,4),actual.prepared.bow,60000));admissions.End();
+ unsigned occupied=0;for(const auto &slot:admissions.Slots()) occupied+=slot.occupied?1u:0u;
+ CHECK(occupied==1 && bowTestSlot(admissions,actual.prepared.bow.id));
+}
+
+TEST(water_bow_refinement_protected_only_or_nonfresh_geometry_cannot_admit)
+{
+ using namespace WaterProjectedMesh;using namespace WaterBowRefinement;
+ auto view=bowTestView();view.resolution={80,80};
+ const Point corners[4]={{-100,-100},{100,-100},{100,100},{-100,100}};
+ Mesh mesh;CHECK(Build(corners,view.projection,view.resolution,mesh));const auto saved=mesh;
+ const auto actual=bowTestActive(view,0,0),collarOnly=bowTestActive(view,-110,0);
+ // The bow's 32-world-unit support enters this polygon by only 22 units,
+ // entirely inside the independently specified 24-unit protected world band.
+ CHECK(collarOnly.prepared.bow.centre.x+32>corners[0].x);
+ CHECK(collarOnly.prepared.bow.centre.x+32-corners[0].x<24);
+ CHECK(!HasRefinableDemand(mesh,view,corners,collarOnly.prepared));CHECK(bowTestSameMesh(mesh,saved));
+ CHECK(HasRefinableDemand(mesh,view,corners,actual.prepared));
+ for(auto &vertex:mesh.vertices) vertex.lattice=-1;const auto nonfresh=mesh;
+ CHECK(!HasRefinableDemand(mesh,view,corners,actual.prepared));CHECK(bowTestSameMesh(mesh,nonfresh));
+ const Point small[4]={{-20,-20},{20,-20},{20,20},{-20,20}};
+ Mesh protectedMesh;CHECK(Build(small,view.projection,view.resolution,protectedMesh));CHECK(!protectedMesh.indices.empty());
+ CHECK(!HasRefinableDemand(protectedMesh,view,small,actual.prepared));
+}
+
+#include "Platform/WaterShoreFoam.h"
+#include <limits>
+
+namespace {
+double shoreScalar(double x,double y,double time) {
+ double h=0;
+ for(unsigned i=0;i<WaterShoreFoam::ModeCount;++i) {
+ const auto &m=WaterShoreFoam::Modes[i];
+ const double phase=x*m.kx+y*m.ky-time*m.omega+m.phase;
+ h+=m.amplitude*(std::sin(phase)+.13*std::sin(2*phase));
+ }
+ return h;
+}
+}
+TEST(water_shore_wave_matches_shared_visible_modes_and_independent_space_time_derivatives)
+{
+ using namespace WaterShoreFoam;
+ unsigned omittedTimeControls=0,harmonicControls=0;
+ for(float x:{-128.f,-9.f,0.f,37.f,1000.f})for(float y:{-31.f,0.f,53.f})for(float t:{0.f,.125f,7.f,120.f}) {
+ const Wave w=Evaluate(x,y,t);const double eps=.001;
+ const double dx=(shoreScalar(x+eps,y,t)-shoreScalar(x-eps,y,t))/(2*eps);
+ const double dy=(shoreScalar(x,y+eps,t)-shoreScalar(x,y-eps,t))/(2*eps);
+ const double dt=(shoreScalar(x,y,t+eps)-shoreScalar(x,y,t-eps))/(2*eps);
+ CHECK(std::abs(w.height-shoreScalar(x,y,t))<.00008);
+ CHECK(std::abs(w.dx-dx)<.00003 && std::abs(w.dy-dy)<.00003 && std::abs(w.dt-dt)<.0001);
+ if(std::abs(dt)>.1)++omittedTimeControls;
+ double noHarmonic=0;for(unsigned i=0;i<ModeCount;++i) {
+ const auto &m=Modes[i];noHarmonic-=m.amplitude*m.omega*std::cos(double(x)*m.kx+double(y)*m.ky-double(t)*m.omega+m.phase);
+ }
+ if(std::abs(noHarmonic-dt)>.03)++harmonicControls;
+ const Wave repeated=Evaluate(x,y,t);CHECK(w.height==repeated.height && w.dx==repeated.dx && w.dy==repeated.dy && w.dt==repeated.dt);
+ }
+ CHECK(omittedTimeControls>20 && harmonicControls>20);
+ for(float invalid:{std::numeric_limits<float>::infinity(),std::numeric_limits<float>::quiet_NaN()}) {
+ const Wave w=Evaluate(invalid,0,0);CHECK(w.height==0 && w.dx==0 && w.dy==0 && w.dt==0);
+ }
+}
+TEST(water_shore_source_has_no_permanent_floor_and_respects_direction_depth_exposure_and_material)
+{
+ using namespace WaterShoreFoam;
+ Context c;c.depth=2;c.shore=1;c.nx=1;c.slope=.1f;c.exposure=1;c.support=1;
+ Wave incoming;incoming.height=2;incoming.dx=.3f;incoming.dt=1;
+ const float exposed=Rate(c,incoming);CHECK(exposed>.5f && exposed<=MaximumRate);
+ Wave trough=incoming;trough.height=-1;CHECK(Rate(c,trough)==0);
+ Wave flat=incoming;flat.dx=0;CHECK(Rate(c,flat)==0);
+ Wave outgoing=incoming;outgoing.dt=-1;CHECK(Rate(c,outgoing)==0);
+ Context dry=c;dry.depth=.15f;CHECK(Rate(dry,incoming)==0);
+ Context unsupported=c;unsupported.support=0;CHECK(Rate(unsupported,incoming)==0);
+ Context sheltered=c;sheltered.exposure=0;CHECK(std::abs(Rate(sheltered,incoming)-exposed*ShelteredScale)<.000001f);
+ Context deep=c;deep.depth=20;CHECK(Rate(deep,incoming)==0);
+ Context rock=c;rock.slope=1;rock.shore=5;const float rockRate=Rate(rock,incoming);
+ rock.shore=7;CHECK(Rate(rock,incoming)==0 && rockRate>0 && rockRate<exposed);
+ CHECK(Blend(.2f,0,1,1,1)==0); // valid coast trough removes the old permanent contact floor
+ CHECK(Blend(.2f,exposed,0,1,0)==.2f); // object hit or missing coast keeps the original rim
+ CHECK(Blend(.2f,exposed,1,0,1)==0); // scene-depth dry fragment cannot receive fresh source
+ CHECK(Blend(.2f,exposed,0,1,0)==Blend(.2f,0,0,1,0));
+ float previous=0;
+ for(unsigned i=0;i<=1000;++i) {
+ Wave w=incoming;w.height=-.5f+3*float(i)/1000;
+ const float value=Rate(c,w);CHECK(std::isfinite(value) && value>=0 && value<=MaximumRate);
+ CHECK(std::abs(value-previous)<.03f);previous=value;
+ }
+ // The three physical modes predominantly travel +X. This exposed coast faces -X;
+ // the opposite-facing beach should not be used to demand sustained incoming surf.
+ c.nx=-1;
+ unsigned active=0,inactive=0;
+ for(unsigned i=0;i<600;++i) {const float value=Rate(c,Evaluate(0,0,float(i)/30));if(value>.02f)++active;else++inactive;}
+ CHECK(active>20 && inactive>100); // the static coastline must actually form and recede
+ c.depth=std::numeric_limits<float>::quiet_NaN();CHECK(Rate(c,incoming)==0);
+ CHECK(Fresh(std::numeric_limits<float>::infinity())==0);
+}
+namespace {
+double shoreFrontIndependentKernel(double q) {
+ const double pi=std::acos(-1.0),tau=2*pi;
+ q-=tau*std::floor(q/tau);
+ // Find the real harmonic crest from h'(q), independently of stored constants.
+ static const double alpha=[](){double lo=0,hi=std::acos(-1.0)*.5;
+ for(unsigned n=0;n<48;++n){const double mid=(lo+hi)*.5;if(std::cos(mid)+.26*std::cos(2*mid)>0)lo=mid;else hi=mid;}
+ return (lo+hi)*.5;}();
+ if(q<=alpha||q>=pi)return 0;
+ const double u=(std::cos(alpha)-std::cos(q))/(1+std::cos(alpha));return 4*u*(1-u);
+}
+double shoreFrontIndependentAverage(double q,double width) {
+ if(width==0)return shoreFrontIndependentKernel(q);
+ // Composite midpoint integration, deliberately not the production antiderivative.
+ const unsigned count=8192;double sum=0;
+ for(unsigned i=0;i<count;++i)sum+=shoreFrontIndependentKernel(q+width*((i+.5)/count-.5));
+ return sum/count;
+}
+}
+TEST(water_shore_front_phases_belong_to_displaced_nearshore_geometry)
+{
+ using namespace WaterShoreFoam;
+ const WaterProjectedMesh::Point corners[4]={{-500,-500},{500,-500},{500,500},{-500,500}};
+ WaterFftGeometry::SeamFade seam;CHECK(seam.Prepare(corners,testWaterProjection(),{16,16}));
+ for(float x:{-125.f,0.f,193.f})for(float y:{-40.f,31.f})for(float t:{0.f,.125f,17.f}) {
+ const auto actual=WaterSurfaceModel::EvaluateBlended(x,y,t,{0,0,0});
+ const auto nearshore=WaterSurfaceModel::Evaluate(x,y,t);const auto broad=Evaluate(x,y,t);
+ CHECK(actual.height==nearshore.height&&actual.dx==nearshore.dx&&actual.dy==nearshore.dy);
+ CHECK(WaterSurfaceModel::EvaluateBlendedHeight(x,y,t,{0,0,0})==nearshore.height);
+ CHECK(seam.Weight({x,y},0)==0); // GPU wrapper retains CPU height at zero FFT weight
+ double omitted=0;
+ for(unsigned i=ModeCount;i<sizeof(Modes)/sizeof(Modes[0]);++i) {
+ const auto&m=Modes[i];const double q=double(x)*m.kx+double(y)*m.ky-double(t)*m.omega+m.phase;
+ omitted+=m.amplitude*(std::sin(q)+.13*std::sin(2*q));
+ }
+ for(float depth:{.8f,2.f,9.f}) {
+ const double damping=WaterSurfaceModel::ShoreDamping(depth);
+ CHECK(std::abs((broad.height+omitted)*damping-double(actual.height)*damping)<.00008);
+ }
+ }
+ CHECK(std::abs(.52*FrontCrestCosine*FrontCrestCosine+FrontCrestCosine-.26)<1e-7);
+ CHECK(std::abs(FrontCrestPhase+FrontPhaseWidth-std::acos(-1.0))<2e-7);
+}
+TEST(water_shore_front_leading_face_propagates_and_preserves_eligibility)
+{
+ using namespace WaterShoreFoam;const double tau=2*std::acos(-1.0);
+ unsigned moving=0,active=0,inactive=0,hiddenBefore=0;double maximumKernelError=0,maximumShiftError=0;
+ for(unsigned i=0;i<ModeCount;++i) {
+ // Invert phase in double precision. hypot(float,float) rounds before assignment
+ // to double and would move the independent reference off its intended phase.
+ const auto&m=Modes[i];const double k=std::hypot(double(m.kx),double(m.ky));
+ CHECK(FrontPhaseWidth/k>5 && FrontPhaseWidth/m.omega>1.1);
+ for(unsigned step=0;step<256;++step) {
+ const double q=(step+.25)*tau/256;
+ const float value=FrontKernel(float(std::sin(q)),float(std::cos(q)));
+ CHECK(std::isfinite(value)&&value>=0&&value<=1);
+ const double kernelError=std::abs(value-shoreFrontIndependentKernel(q));
+ maximumKernelError=(std::max)(maximumKernelError,kernelError);
+ CHECK(kernelError<5e-7); // bounded float polynomial rounding; double oracle stays independent
+ if(value>0)CHECK(std::sin(q)+.13*std::sin(2*q)>0 && std::cos(q)+.26*std::cos(2*q)<0);
+ // Follow one actual phase for dt=.1: its world-space displacement is k*omega*dt/|k|^2.
+ const double x=(q-m.phase)*m.kx/(k*k),y=(q-m.phase)*m.ky/(k*k),dt=.1;
+ const double shifted=(x+m.kx*m.omega*dt/(k*k))*m.kx+(y+m.ky*m.omega*dt/(k*k))*m.ky-dt*m.omega+m.phase;
+ const double shiftedError=std::abs(value-shoreFrontIndependentKernel(shifted));
+ maximumShiftError=(std::max)(maximumShiftError,shiftedError);CHECK(shiftedError<4e-7);
+ if(std::abs(value-shoreFrontIndependentKernel(q-m.omega*dt))>.03)++moving;
+ }
+ }
+ Context c;c.depth=2;c.shore=1;c.nx=-1;c.ny=0;c.slope=.1;c.exposure=c.support=1;
+ for(unsigned step=0;step<600;++step) {
+ const float t=step/30.f;const auto wave=Evaluate(0,0,t);const Front front=EvaluateFront(0,0,t,c.nx,c.ny);
+ const float previous=Rate(c,wave),rate=previous*front.mask;
+ const Front pause=EvaluateFront(0,0,t,c.nx,c.ny);CHECK(front.mask==pause.mask&&front.residence==pause.residence);
+ CHECK(front.mask>=0&&front.mask<=1&&front.residence>=0&&front.residence<=FrontMaximumResidence+.000001f);
+ CHECK(rate>=0&&rate<=previous&&rate<=MaximumRate);
+ if(wave.height<=0)CHECK(rate==0);
+ CHECK(EvaluateFront(0,0,t,1,0).mask==0); // every broad mode travels away from this reversed coast
+ const float fresh=FrontFresh(rate,front.residence);
+ if(rate>.02)++active;else ++inactive;
+ if(fresh>Fresh(MaximumRate)+.02f)++hiddenBefore;
+ CHECK(BlendFrontHistory(.2f,rate,front.residence,.5f,1,0,1)==0);
+ CHECK(BlendFrontHistory(.2f,rate,front.residence,.5f,1,1,0)==.2f);
+ CHECK(BlendFrontHistory(.2f,rate,front.residence,fresh,1,1,1)==fresh); // no duplicated front/history
+ for(float depth:{0.f,.15f,20.f}){Context d=c;d.depth=depth;CHECK(Rate(d,wave)*front.mask==0);}
+ Context unsupported=c;unsupported.support=0;CHECK(Rate(unsupported,wave)*front.mask==0);
+ }
+ CHECK(moving>50&&active>20&&inactive>100&&hiddenBefore>5);
+ CHECK(EvaluateFront(NAN,0,0,-1,0).mask==0&&EvaluateFront(0,0,0,NAN,0).mask==0);
+ CHECK(FrontFiltered(0,1,NAN)==0&&FrontFresh(INFINITY,1)==0&&FrontFresh(1,NAN)==0);
+ std::printf("shore front float kernel/independent phase-shift maxima %.9g / %.9g\n",maximumKernelError,maximumShiftError);
+}
+TEST(water_shore_front_pixel_integral_and_existing_lattice_do_not_lose_arriving_bands)
+{
+ using namespace WaterShoreFoam;const double pi=std::acos(-1.0),tau=2*pi;
+ double maximum=0;unsigned partial=0;
+ for(double q:{-.1,0.0,.5,1.336653506,1.8,2.00009,2.6,pi,4.3,6.2})for(float width:{.000015f,.0001f,.001f,.01f,.2f,1.f,3.f,6.283185307f,9.f,20.f}) {
+ const double expected=shoreFrontIndependentAverage(q,width);
+ const float actual=FrontFiltered(float(std::sin(q)),float(std::cos(q)),width);
+ maximum=(std::max)(maximum,std::abs(actual-expected));CHECK(std::isfinite(actual)&&actual>=0&&actual<=1);
+ CHECK(std::abs(actual-expected)<.0015);
+ if(shoreFrontIndependentKernel(q)==0&&expected>.01)++partial;
+ }
+ for(unsigned i=0;i<128;++i) {
+ const double q=tau*i/128;
+ CHECK(std::abs(FrontFiltered(float(std::sin(q)),float(std::cos(q)),float(tau))-FrontArea/FrontTau)<.000002);
+ }
+ // Sweep every mode through the real 5-world-unit lattice, its unchanged 2x2
+ // quadrature, and .1-second deposition ticks with independent spatial/time offsets.
+ // A full face cannot be missed, and phase-integrated mass remains bounded.
+ double maxSpatial=0,maxTemporal=0;
+ for(unsigned i=0;i<ModeCount;++i) {
+ const auto&m=Modes[i];const double k=std::hypot(m.kx,m.ky),wavelength=tau/k,period=tau/m.omega;
+ for(unsigned offset=0;offset<24;++offset) {
+ const double phase=tau*offset/24;double spatial=0,temporal=0;unsigned hits=0;
+ for(double u=-wavelength;u<wavelength;u+=5) {
+ double sample=0;
+ for(double ox:{-1.25,1.25})for(double oy:{-1.25,1.25}) {
+ const double q=k*(u+2.5)+phase+m.kx*ox+m.ky*oy;
+ sample+=.25*shoreFrontIndependentKernel(q);
+ }
+ // Exactly two periods with fractional terminal cells integrated separately
+ // below; the lattice coverage check itself needs no normalization trick.
+ hits+=sample>.01;
+ }
+ CHECK(hits>0);
+ // Keep the actual lattice/tick spacing, and independently integrate its
+ // finite window including fractional periods rather than aligning endpoints.
+ const unsigned cells=unsigned(std::ceil(4*wavelength/5));const double length=cells*5.0;
+ for(unsigned n=0;n<cells;++n)for(double ox:{-1.25,1.25})for(double oy:{-1.25,1.25})
+ spatial+=1.25*shoreFrontIndependentKernel(k*((n+.5)*5)+phase+m.kx*ox+m.ky*oy);
+ double referenceSpatial=0;
+ for(double ox:{-1.25,1.25})for(double oy:{-1.25,1.25})
+ referenceSpatial+=.25*length*shoreFrontIndependentAverage(k*length*.5+phase+m.kx*ox+m.ky*oy,k*length);
+ const unsigned ticks=unsigned(std::ceil(period/.1));const double duration=ticks*.1;
+ for(unsigned n=0;n<ticks;++n)temporal+=.1*shoreFrontIndependentKernel(phase-(n+.5)*.1*m.omega);
+ const double referenceTemporal=duration*shoreFrontIndependentAverage(phase-duration*.5*m.omega,duration*m.omega);
+ maxSpatial=(std::max)(maxSpatial,std::abs(spatial-referenceSpatial)/referenceSpatial);
+ maxTemporal=(std::max)(maxTemporal,std::abs(temporal-referenceTemporal)/referenceTemporal);
+ }
+ }
+ CHECK(partial>5&&maxSpatial<.12&&maxTemporal<.007);
+ std::printf("shore leading-front independent footprint max %.8g; lattice phase integral %.6g, time crossing %.6g\n",maximum,maxSpatial,maxTemporal);
+}
+
+TEST(water_shore_optical_metadata_preserves_rg_and_cannot_create_polygon_or_deep_ocean_coasts)
+{
+ using namespace WaterOpticalContext;
+ const int side=48;std::vector<uint8_t> heights(side*side,0);
+ for(int y=0;y<side;++y)for(int x=0;x<16;++x)heights[y*side+x]=20;
+ const std::vector<Polygon> polygons={opticalRectangle(-10,-10,600,600)};Field field;
+ CHECK(Build(heights.data(),side,side,0,10,1,4,polygons,field));
+ CHECK(field.exposure.size()==heights.size() && field.coast.size()==heights.size());
+ for(int y=0;y<side;++y)for(int x=0;x<side;++x) {
+ const size_t n=y*side+x;const float distance=x<16?0:(std::min)(100.f,float(x-15)*10);
+ const uint8_t expectedR=x<16?0:uint8_t(Offshore(distance)*255+.5f),expectedG=uint8_t(distance/100*255+.5f);
+ CHECK(field.ocean[n]==expectedR && field.shore[n]==expectedG);
+ CHECK((Texel(field,n)&0x00ffff00u)==((uint32_t(expectedR)<<16)|(uint32_t(expectedG)<<8)));
+ CHECK(field.exposure[n]==(x<15?0:255));
+ if(x<15 || distance>=20)CHECK(field.coast[n]==0);
+ if(field.coast[n])for(int yy=(std::max)(0,y-1);yy<=(std::min)(side-1,y+1);++yy)
+ for(int xx=(std::max)(0,x-1);xx<=(std::min)(side-1,x+1);++xx)CHECK(field.ocean[yy*side+xx]==0);
+ }
+ CHECK(field.coast[24*side+15]==255 && field.coast[24*side+16]==255);
+ // The real waterline lies inside the dry-to-wet interpolation interval. Validity must
+ // remain one there even when the old wet-only mask would be only .02 or .2.
+ for(float f:{.02f,.1f,.2f,.5f,.9f}) {
+ const float validity=(field.coast[24*side+15]*(1-f)+field.coast[24*side+16]*f)/255;
+ CHECK(std::abs(validity-1)<.000001f);
+ CHECK(std::abs(WaterShoreFoam::Blend(.2f,0,validity,1,1))<.000001f);
+ CHECK(WaterShoreFoam::Blend(.2f,0,f,1,1)>.019f); // armed wet-only permanent-border control
+ CHECK(WaterShoreFoam::Blend(.2f,0,validity,0,1)==0); // no dry coverage
+ CHECK(WaterShoreFoam::Blend(.2f,0,validity,1,0)==.2f); // object contact stays intact
+ }
+ // An authored polygon edge over uniformly submerged terrain is not a shoreline source.
+ std::fill(heights.begin(),heights.end(),0);
+ CHECK(Build(heights.data(),side,side,0,10,1,4,{opticalRectangle(100,100,300,300)},field));
+ for(auto a:field.coast)CHECK(a==0);
+ for(auto r:field.ocean)CHECK(r==0);
+ // A shallow but entirely open sea (including carrier/menu floors) has no synthetic border.
+ CHECK(Build(heights.data(),side,side,0,10,1,4,polygons,field));
+ for(size_t n=0;n<heights.size();++n)CHECK(field.ocean[n]==255 && field.exposure[n]==255 && field.coast[n]==0);
+ CHECK(!Build(nullptr,side,side,0,10,1,4,polygons,field));
+ CHECK(field.ocean.empty() && field.shore.empty() && field.exposure.empty() && field.coast.empty());
+}
+TEST(water_shore_replacement_requires_real_original_scene_depth_even_in_troughs)
+{
+ using namespace WaterShoreFoam;
+ const float nan=std::numeric_limits<float>::quiet_NaN(),inf=std::numeric_limits<float>::infinity();
+ const float beforeClear=std::nextafter(.999999f,0.0f),afterAvailable=std::nextafter(.5f,1.0f);
+ unsigned unavailableFallbackControls=0,invalidFallbackControls=0,realTroughs=0;
+ for(float available:{0.f,.5f,afterAvailable,1.f,nan,inf,-inf})
+ for(float raw:{-inf,-.001f,0.f,.2f,beforeClear,.999999f,1.f,1.1f,inf,nan}) {
+ // Independent literal acceptance table: a terrain fallback is never a real hit.
+ const bool expected=std::isfinite(available)&&available>.5f&&std::isfinite(raw)
+ &&raw>=0.f&&raw<.999999f;
+ const bool actual=SceneDepthEligible(available,raw);CHECK(actual==expected);
+ const float legacy=.2f,zeroRateReplacement=actual?Blend(legacy,0,1,1,1):legacy;
+ const float activeReplacement=actual?Blend(legacy,MaximumRate,1,1,1):legacy;
+ if(expected) {
+ CHECK(zeroRateReplacement==0 && activeReplacement>0 && activeReplacement<1);++realTroughs;
+ } else {
+ CHECK(zeroRateReplacement==legacy && activeReplacement==legacy);
+ // Armed previous gate: a fallback bottom at terrain height would match it
+ // exactly and incorrectly replace the legacy rim, even with zero source.
+ CHECK(Blend(legacy,0,1,1,1)==0);
+ if(!(std::isfinite(available)&&available>.5f))++unavailableFallbackControls;
+ else ++invalidFallbackControls;
+ }
+ }
+ CHECK(realTroughs==6 && unavailableFallbackControls==50 && invalidFallbackControls==14);
+}
+
+// ARTIFACT: append to test_water_grid.cpp only after authorized implementation.
+#include "Platform/WaterShoreHistory.h"
+#include <limits>
+
+namespace {
+using ShoreState=WaterShoreHistory::State;
+struct ShoreTestSource {
+ double rate=1,stop=1e30;unsigned calls=0;bool varying=false;
+ void operator()(double time,const WaterShoreHistory::Cell*cells,size_t count,double*out) {
+ ++calls;
+ for(size_t i=0;i<count;++i)out[i]=time>=stop?0:rate*(varying?(1+.3*std::sin(time*1.7+cells[i].x*.2+cells[i].y*.4)):1);
+ }
+};
+std::vector<WaterShoreHistory::Cell> shoreTestCells() {
+ std::vector<WaterShoreHistory::Cell> cells;
+ for(int y=-2;y<=2;++y)for(int x=-2;x<=2;++x)cells.push_back({x,y,4,uint32_t(cells.size())});
+ return cells;
+}
+bool shoreStatesEqual(const std::vector<ShoreState>&a,const std::vector<ShoreState>&b) {
+ if(a.size()!=b.size())return false;
+ for(size_t i=0;i<a.size();++i)if(a[i].density!=b[i].density||a[i].ageMoment!=b[i].ageMoment)return false;
+ return true;
+}
+std::vector<ShoreState> shoreRun(unsigned fps,bool previews) {
+ WaterShoreHistory::History history;const auto cells=shoreTestCells();
+ CHECK(history.Install({},cells,1,0)==WaterShoreHistory::BuildResult::Ready);
+ ShoreTestSource source;source.varying=true;source.stop=2.35;
+ for(unsigned frame=1;frame<=fps*8;++frame) {
+ CHECK(history.Advance(double(frame)/fps,source)!=WaterShoreHistory::AdvanceResult::Invalid);
+ if(previews)history.Preview(source);
+ }
+ return history.Preview(source);
+}
+}
+TEST(water_shore_history_exact_density_age_step_matches_independent_integral_and_partition)
+{
+ using namespace WaterShoreHistory;
+ for(double elapsed:{1e-9,1e-5,.005,.049,.1,1.3,17.0})for(double rate:{0.0,.2,1.2,16.0}) {
+ const State initial={.7,2.1};const Decay d=Decay::Make(elapsed,5);const State value=d.Apply(initial,rate);
+ // Independent composite midpoint integral over deposition ages, accumulated in long double.
+ const unsigned count=16384;long double density=0,age=0;
+ for(unsigned i=0;i<count;++i) {
+ const long double a=(i+.5L)*elapsed/count,weight=std::exp(-a/5.0L)*elapsed/count;
+ density+=rate*weight;age+=rate*a*weight;
+ }
+ const long double q=std::exp(-static_cast<long double>(elapsed)/5);
+ density+=q*initial.density;age+=q*(initial.ageMoment+elapsed*initial.density);
+ CHECK(std::abs(value.density-double(density))<2e-7);
+ CHECK(std::abs(value.ageMoment-double(age))<3e-6);
+ const State split=Decay::Make(elapsed*.63,5).Apply(Decay::Make(elapsed*.37,5).Apply(initial,rate),rate);
+ CHECK(std::abs(value.density-split.density)<1e-12 && std::abs(value.ageMoment-split.ageMoment)<1e-11);
+ CHECK(value.density>=0 && value.ageMoment>=0);
+ }
+ const State equilibrium=Decay::Make(1e300,5).Apply({1,1},1.2);
+ CHECK(equilibrium.density==6 && equilibrium.ageMoment==30);
+}
+TEST(water_shore_history_topology_is_deterministic_globally_bounded_and_level_isolated)
+{
+ using namespace WaterShoreHistory;
+ auto cells=shoreTestCells();cells.push_back({0,0,9,99});Topology a,b;
+ CHECK(a.Build({},cells)==BuildResult::Ready);std::reverse(cells.begin(),cells.end());CHECK(b.Build({},cells)==BuildResult::Ready);
+ CHECK(a.SameGeometry(b) && a.Edges().size()==b.Edges().size());
+ for(size_t i=0;i<a.Cells().size();++i)CHECK(a.Cells()[i].sourceIndex==b.Cells()[i].sourceIndex);
+ for(size_t i=0;i<a.Edges().size();++i) {
+ CHECK(a.Edges()[i].a==b.Edges()[i].a && a.Edges()[i].b==b.Edges()[i].b);
+ CHECK(a.Cells()[a.Edges()[i].a].level==a.Cells()[a.Edges()[i].b].level);
+ }
+ CHECK(a.Find(-1,-2,4)>=0 && a.Find(-1,-2,9)<0 && a.Find(0,0,9)>=0);
+ auto duplicate=cells;duplicate.push_back(cells.front());CHECK(a.Build({},duplicate)==BuildResult::Invalid);CHECK(a.SameGeometry(b));
+ std::vector<Cell> capacity;for(size_t i=0;i<MaxCells;++i)capacity.push_back({int32_t(i),0,4,uint32_t(i)});
+ Topology full;CHECK(full.Build({},capacity)==BuildResult::Ready);CHECK(full.Cells().size()==MaxCells && full.Edges().size()==MaxCells-1);
+ capacity.push_back({int32_t(MaxCells),0,4,0});CHECK(full.Build({},capacity)==BuildResult::TooManyCells);CHECK(full.Cells().size()==MaxCells);
+ std::vector<Cell> levels;for(unsigned i=0;i<=MaxLevels;++i)levels.push_back({0,0,double(i),i});
+ CHECK(a.Build({},levels)==BuildResult::TooManyLevels);CHECK(a.SameGeometry(b));
+ Grid invalid;invalid.spacing=NAN;CHECK(a.Build(invalid,cells)==BuildResult::Invalid);CHECK(a.SameGeometry(b));
+}
+TEST(water_shore_history_diffusion_preserves_mass_age_and_does_not_cross_dry_or_level_boundaries)
+{
+ using namespace WaterShoreHistory;
+ // Two cells each side of an absent dry x=0 column, plus a separate higher water level.
+ Topology topology;CHECK(topology.Build({},{{-2,0,4,0},{-1,0,4,1},{1,0,4,2},{2,0,4,3},{-1,0,9,4}})==BuildResult::Ready);
+ std::vector<State> state(topology.Cells().size()),decayed,result;std::vector<double> rates(state.size(),0);
+ const int seed=topology.Find(-1,0,4);state[size_t(seed)]={1,3};Parameters parameters;
+ for(unsigned step=0;step<30;++step) {
+ double beforeDensity=0,beforeAge=0;for(auto s:state){beforeDensity+=s.density;beforeAge+=s.ageMoment;}
+ CHECK(Step(topology,parameters,state,rates,Tick,decayed,result));
+ double afterDensity=0,afterAge=0;for(auto s:result){CHECK(s.density>=0 && s.ageMoment>=0);afterDensity+=s.density;afterAge+=s.ageMoment;}
+ const double q=std::exp(-Tick/parameters.lifetime);
+ CHECK(std::abs(afterDensity-beforeDensity*q)<1e-13);
+ CHECK(std::abs(afterAge-(beforeAge+Tick*beforeDensity)*q)<1e-13);
+ for(size_t i=0;i<state.size();++i)if(topology.Cells()[i].x>0||topology.Cells()[i].level!=4)
+ CHECK(result[i].density==0 && result[i].ageMoment==0);
+ state.swap(result);
+ }
+ const double nu=parameters.diffusivity*Tick/25;
+ const double expectedNeighbour=.5*(1-std::pow(1-2*nu,30))*std::exp(-30*Tick/parameters.lifetime);
+ CHECK(std::abs(state[size_t(topology.Find(-2,0,4))].density-expectedNeighbour)<1e-13 && expectedNeighbour>.05);
+ CHECK(std::abs(state[size_t(seed)].ageMoment/state[size_t(seed)].density-6)<1e-12);
+ auto before=state;rates[0]=NAN;rates[1]=-1;rates[2]=1000;
+ CHECK(Step(topology,parameters,state,rates,Tick,decayed,result));
+ CHECK(result[2].density<=parameters.maximumRate*Tick && std::isfinite(result[0].density));
+ const auto unchanged=result;CHECK(!Step(topology,parameters,state,rates,Tick*2,decayed,result));CHECK(shoreStatesEqual(result,unchanged));
+}
+TEST(water_shore_history_render_schedule_and_partial_preview_do_not_change_deposition)
+{
+ using namespace WaterShoreHistory;
+ const auto baseline=shoreRun(30,false);
+ CHECK(shoreStatesEqual(baseline,shoreRun(30,true)));
+ CHECK(shoreStatesEqual(baseline,shoreRun(60,true)));
+ CHECK(shoreStatesEqual(baseline,shoreRun(120,true)));
+ History history,direct;const auto cells=shoreTestCells();ShoreTestSource source,other;source.varying=other.varying=true;
+ CHECK(history.Install({},cells,1,0)==BuildResult::Ready && direct.Install({},cells,1,0)==BuildResult::Ready);
+ for(double t:{.01,.037,.08,.099999999}) {
+ history.Advance(t,source);const auto committed=history.Committed();const auto a=history.Preview(source);const unsigned calls=source.calls;
+ CHECK(shoreStatesEqual(a,history.Preview(source)) && source.calls==calls);
+ CHECK(shoreStatesEqual(committed,history.Committed()));
+ }
+ direct.Advance(.099999999,other);CHECK(shoreStatesEqual(history.Preview(source),direct.Preview(other)));
+ const auto justBefore=history.Preview(source);history.Advance(.1,source);const auto atBoundary=history.Preview(source);
+ for(size_t i=0;i<justBefore.size();++i) {
+ CHECK(std::abs(justBefore[i].density-atBoundary[i].density)<2e-8);
+ CHECK(std::abs(justBefore[i].ageMoment-atBoundary[i].ageMoment)<2e-8);
+ }
+ const unsigned frozenCalls=source.calls;CHECK(history.Advance(.1,source)==AdvanceResult::Unchanged);
+ CHECK(shoreStatesEqual(atBoundary,history.Preview(source)) && frozenCalls==source.calls);
+}
+TEST(water_shore_history_resource_refresh_reset_stale_gap_and_time_rewind_have_explicit_lifetime)
+{
+ using namespace WaterShoreHistory;
+ History history;auto cells=shoreTestCells();ShoreTestSource source;CHECK(history.Install({},cells,7,0)==BuildResult::Ready);
+ for(unsigned i=1;i<=7;++i)history.Advance(i*.1,source);
+ history.Advance(.75,source);const auto visible=history.Preview(source);
+ std::reverse(cells.begin(),cells.end());CHECK(history.Install({},cells,7,.75)==BuildResult::Ready);
+ CHECK(shoreStatesEqual(visible,history.Preview(source))); // device refresh/reordered source metadata
+ CHECK(history.Advance(3.25,source)==AdvanceResult::GapDecayed);const auto stale=history.Preview(source);
+ const Decay onlyDecay=Decay::Make(2.5,5);
+ for(size_t i=0;i<stale.size();++i) {
+ const State expected=onlyDecay.Apply(visible[i],0);
+ CHECK(stale[i].density==expected.density && stale[i].ageMoment==expected.ageMoment);
+ }
+ CHECK(history.Advance(0,source)==AdvanceResult::Rewound);
+ for(auto s:history.Preview(source))CHECK(s.density==0 && s.ageMoment==0);
+ history.Advance(.2,source);CHECK(history.Preview(source)[0].density>0);
+ CHECK(history.Install({},cells,8,.2)==BuildResult::Ready && !history.ValidFor(7) && history.ValidFor(8));
+ for(auto s:history.Preview(source))CHECK(s.density==0 && s.ageMoment==0);
+ auto excessive=cells;excessive.resize(MaxCells+1);CHECK(history.Install({},excessive,9,.2)==BuildResult::TooManyCells);
+ CHECK(!history.ValidFor(9)); // failed new-map construction cannot expose the old map's alpha
+}
+TEST(water_shore_history_atlas_sampling_preserves_rgb_world_anchor_and_density_weighted_age)
+{
+ using namespace WaterShoreHistory;
+ Topology topology;CHECK(topology.Build({},{{-1,0,4,0},{0,0,4,1}})==BuildResult::Ready);
+ const std::vector<State> states={{1,1},{3,30}};
+ const State mixed=Sample(topology,states,-2.5,0,4);
+ CHECK(mixed.density==2 && mixed.ageMoment==15.5 && mixed.ageMoment/mixed.density==7.75);
+ CHECK(std::abs(mixed.ageMoment/mixed.density-(1.0+10.0)/2)>2); // armed unweighted-age control
+ CHECK(Sample(topology,states,-2.5,0,9).density==0 && Sample(topology,states,-100,0,4).density==0);
+ auto material=[](const State&s,double,double,double){return -std::expm1(-s.density);};
+ Mapping map;map.originX=-5.5;map.originY=-.5;map.widthWorld=6;map.heightWorld=1;map.widthPixels=6;map.heightPixels=1;
+ std::vector<uint32_t> pixels(6);for(unsigned i=0;i<6;++i)pixels[i]=0xfa000000u|(i*0x234567u&0x00ffffffu);
+ const auto original=pixels;CHECK(RasterizeAlpha(topology,states,map,4,1,material,pixels));
+ for(unsigned i=0;i<6;++i)CHECK((pixels[i]&0x00ffffffu)==(original[i]&0x00ffffffu));
+ auto repeat=pixels;CHECK(RasterizeAlpha(topology,states,map,4,1,material,repeat));CHECK(repeat==pixels);
+ Mapping panned=map;panned.originX-=1;panned.widthWorld=7;panned.widthPixels=7;std::vector<uint32_t> shifted(7,0);
+ CHECK(RasterizeAlpha(topology,states,panned,4,1,material,shifted));
+ for(unsigned i=0;i<6;++i)CHECK((pixels[i]>>24)==(shifted[i+1]>>24));
+ CHECK(RasterizeAlpha(topology,states,map,9,1,material,repeat));
+ for(unsigned i=0;i<6;++i)CHECK(repeat[i]==(original[i]&0x00ffffffu));
+ CHECK(WithAlpha(0x12abcdefu,NAN)==0x00abcdefu && WithAlpha(0x12abcdefu,2)==0xffabcdefu);
+}
+
+#include "Platform/WaterShoreSource.h"
+namespace {
+struct ShoreFixtureDomain {
+ int width=33,height=25;std::vector<uint8_t> heights;
+ std::vector<WaterOpticalContext::Polygon> polygons;
+ WaterOpticalContext::Field field;
+ ShoreFixtureDomain() {
+ heights.resize(size_t(width)*height);
+ for(int y=0;y<height;++y)for(int x=0;x<width;++x)heights[size_t(y)*width+x]=uint8_t(x>=24?20:(std::max)(0,x-14));
+ WaterOpticalContext::Polygon polygon;polygon.points={{0,0,10},{320,0,10},{320,240,10},{0,240,10}};polygons.push_back(polygon);
+ CHECK(WaterOpticalContext::Build(heights.data(),width,height,0,10,1,10,polygons,field));
+ }
+};
+}
+TEST(water_shore_integrated_domain_uses_wet_geometry_level_and_polygon_segments) {
+ using namespace WaterShoreHistory;using namespace WaterShoreSource;
+ ShoreFixtureDomain input;Batch source;
+ CHECK(source.Build(input.heights.data(),input.width,input.height,0,10,1,input.polygons,{{10,&input.field}})==BuildResult::Ready);
+ CHECK(!source.Cells().empty()&&source.Cells().size()<MaxCells&&source.Grid().spacing==5);
+ Topology graph;CHECK(graph.Build(source.Grid(),source.Cells())==BuildResult::Ready);
+ for(const auto&c:graph.Cells()) {
+ const double x=source.Grid().originX+c.x*5,y=source.Grid().originY+c.y*5;
+ CHECK(Height(input.heights.data(),input.width,input.height,x/10,y/10,1)<10);
+ CHECK(Covered(Intervals(input.polygons,10,y,true),x,x));
+ }
+ // Both endpoints are wet, but a subcell gap between authored polygons must have no edge.
+ std::vector<WaterOpticalContext::Polygon> gap(2);
+ gap[0].points={{0,0,10},{2,0,10},{2,10,10},{0,10,10}};
+ gap[1].points={{3,0,10},{10,0,10},{10,10,10},{3,10,10}};
+ const auto spans=Intervals(gap,10,5,true);
+ CHECK(Covered(spans,0,0)&&Covered(spans,5,5)&&!Covered(spans,0,5));
+ Topology guarded;CHECK(guarded.Build({},{{0,0,10,0,2},{1,0,10,1,3}})==BuildResult::Ready);
+ CHECK(guarded.Edges().empty()); // armed old endpoint-only topology would create one edge
+ Topology connected;CHECK(connected.Build({},{{0,0,10,0},{1,0,10,1}})==BuildResult::Ready);
+ CHECK(connected.Edges().size()==1&&!guarded.SameGeometry(connected));
+ gap[1].points[0].x=2;gap[1].points[3].x=2;
+ CHECK(Covered(Intervals(gap,10,5,true),0,5)); // touching union is continuous
+ const auto old=source.Cells();auto invalid=input.polygons;invalid[0].points[0].x=NAN;
+ CHECK(source.Build(input.heights.data(),input.width,input.height,0,10,1,invalid,{{10,&input.field}})==BuildResult::Invalid);
+ CHECK(source.Cells().size()==old.size()); // atomic failed rebuild
+}
+TEST(water_shore_cached_source_matches_direct_world_wave_and_gradient) {
+ using namespace WaterShoreHistory;using namespace WaterShoreSource;
+ ShoreFixtureDomain input;Batch source;
+ CHECK(source.Build(input.heights.data(),input.width,input.height,0,10,1,input.polygons,{{10,&input.field}})==BuildResult::Ready);
+ std::vector<double> rates(source.Cells().size());double maximum=0;unsigned active=0;
+ for(double time:{0.0,.05,.4,1.7,6.3,17.0}) {
+ source(time,source.Cells().data(),source.Cells().size(),rates.data());
+ for(size_t i=0;i<rates.size();++i) {
+ const auto&cell=source.Cells()[i];const auto&context=source.Contexts()[cell.sourceIndex].coast;
+ const float x=float(source.Grid().originX+cell.x*5),y=float(source.Grid().originY+cell.y*5);
+ double expected=0;
+ for(unsigned q=0;q<4;++q) {
+ const auto&coast=source.Contexts()[cell.sourceIndex].quadrature[q].coast;
+ const float qx=x+(q%2?1.25f:-1.25f),qy=y+(q/2?1.25f:-1.25f);
+ expected+=.25*WaterShoreFoam::Rate(coast,WaterShoreFoam::Evaluate(qx,qy,float(time)))
+ *WaterShoreFoam::EvaluateFront(qx,qy,float(time),coast.nx,coast.ny).mask;
+ }
+ maximum=(std::max)(maximum,std::abs(rates[i]-expected));
+ CHECK(std::isfinite(rates[i])&&rates[i]>=0&&rates[i]<=WaterShoreFoam::MaximumRate);
+ CHECK(std::abs(rates[i]-expected)<.00015);
+ active+=rates[i]>.05;
+ const double gx=(Height(input.heights.data(),input.width,input.height,(x+5)/10,y/10,1)
+ -Height(input.heights.data(),input.width,input.height,(x-5)/10,y/10,1))/10;
+ CHECK(std::abs(context.nx+gx)<1e-7);
+ }
+ }
+ CHECK(active>10);std::printf("shore cached source max direct-rate error %.9g (%u active samples)\n",maximum,active);
+}
+TEST(water_shore_clock_bounds_and_age_material_are_explicit) {
+ using namespace WaterShoreHistory;
+ History history;ShoreTestSource source;
+ CHECK(history.Install({},{{0,0,4,0}},1,1e28)==BuildResult::Invalid);
+ CHECK(history.Install({},{{0,0,4,0}},1,0)==BuildResult::Ready);
+ CHECK(history.Advance(1e28,source)==AdvanceResult::Invalid);
+ CHECK(history.Time()==0);CHECK(history.Advance(.1,source)==AdvanceResult::Advanced);
+ CHECK(WaterShoreSource::Coverage({1,15},1,1,0)==0);
+ double youngest=WaterShoreSource::Coverage({1,0},13,7,0),oldest=WaterShoreSource::Coverage({1,6},13,7,0);
+ CHECK(youngest>0&&oldest>=0&&oldest<=youngest);
+ unsigned fragmented=0;for(int y=0;y<8;++y)for(int x=0;x<8;++x) {
+ const double fresh=WaterShoreSource::Coverage({1,0},x*3,y*3,0),old=WaterShoreSource::Coverage({1,6},x*3,y*3,0);
+ CHECK(old>=0&&old<=fresh);fragmented+=old<fresh*.8;
+ }
+ CHECK(fragmented>10);
+ CHECK(WaterShoreSource::Coverage({1,6},13,7,100)==oldest); // material follows world+age, not frame time
+ CHECK(WaterShoreFoam::BlendHistory(.2f,0,.5f,1,1,1)==.5f); // remnant survives source trough
+ CHECK(WaterShoreFoam::BlendHistory(.2f,0,.5f,1,0,1)==0); // actual dry fragment
+ CHECK(WaterShoreFoam::BlendHistory(.2f,0,.5f,1,1,0)==.2f); // object retains contact fallback
+ const float fresh=WaterShoreFoam::Fresh(1.2f);
+ CHECK(WaterShoreFoam::BlendHistory(.2f,1.2f,fresh,1,1,1)==fresh); // no fresh/history double-count
+}
+TEST(water_shore_cached_source_large_world_phase_bound) {
+ using namespace WaterShoreSource;using namespace WaterShoreHistory;
+ ShoreFixtureDomain input;input.width=1025;input.heights.resize(size_t(input.width)*input.height);
+ for(int y=0;y<input.height;++y)for(int x=0;x<input.width;++x)
+ input.heights[size_t(y)*input.width+x]=uint8_t(x>=1010?20:(std::max)(0,x-1000));
+ input.polygons[0].points[1].x=input.polygons[0].points[2].x=10240;
+ CHECK(WaterOpticalContext::Build(input.heights.data(),input.width,input.height,0,10,1,10,input.polygons,input.field));
+ Batch source;CHECK(source.Build(input.heights.data(),input.width,input.height,0,10,1,input.polygons,{{10,&input.field}})==BuildResult::Ready);
+ std::vector<double> rates(source.Cells().size());double maximum=0;unsigned active=0;
+ for(double time:{0.0,.05,7.75,60.0,600.0,3600.0}) {
+ source(time,source.Cells().data(),source.Cells().size(),rates.data());
+ for(size_t i=0;i<rates.size();++i) {
+ const auto&cell=source.Cells()[i];
+ const float x=float(source.Grid().originX+cell.x*5),y=float(source.Grid().originY+cell.y*5);
+ double expected=0;
+ for(unsigned q=0;q<4;++q) {
+ const auto&coast=source.Contexts()[cell.sourceIndex].quadrature[q].coast;
+ const float qx=x+(q%2?1.25f:-1.25f),qy=y+(q/2?1.25f:-1.25f);
+ expected+=.25*WaterShoreFoam::Rate(coast,WaterShoreFoam::Evaluate(qx,qy,float(time)))
+ *WaterShoreFoam::EvaluateFront(qx,qy,float(time),coast.nx,coast.ny).mask;
+ }
+ maximum=(std::max)(maximum,std::abs(rates[i]-expected));active+=expected>.05;
+ CHECK(std::abs(rates[i]-expected)<.003); // float phase re-association at 10,000 world units / one hour
+ }
+ }
+ CHECK(active>0&&maximum>1e-5);std::printf("shore cached source 10,000-unit / one-hour maximum rate error %.9g\n",maximum);
+}
+
+TEST(water_shore_source_spatial_resolution_sensitivity) {
+ using namespace WaterShoreSource;ShoreFixtureDomain input;
+ auto integral=[&](double step) {
+ double sum=0;
+ for(unsigned frame=0;frame<40;++frame) {
+ const float time=float((frame+.5)*.2);
+ for(double y=0;y<240;y+=step)for(double x=180;x<240;x+=step) {
+ const float terrain=Height(input.heights.data(),input.width,input.height,x/10,y/10,1);
+ if(terrain>=10)continue;
+ const int ix=int(x/10),iy=int(y/10);const float fx=float(x/10-ix),fy=float(y/10-iy);
+ WaterShoreFoam::Context c;c.depth=10-terrain;
+ c.nx=-(Height(input.heights.data(),input.width,input.height,(x+5)/10,y/10,1)
+ -Height(input.heights.data(),input.width,input.height,(x-5)/10,y/10,1))*.1f;
+ c.ny=-(Height(input.heights.data(),input.width,input.height,x/10,(y+5)/10,1)
+ -Height(input.heights.data(),input.width,input.height,x/10,(y-5)/10,1))*.1f;
+ c.slope=std::hypot(c.nx,c.ny);c.support=FieldSample(input.field.coast,input.width,ix,iy,fx,fy);
+ c.exposure=FieldSample(input.field.exposure,input.width,ix,iy,fx,fy);
+ c.shore=(std::min)(FieldSample(input.field.shore,input.width,ix,iy,fx,fy)*100,c.depth/(std::max)(c.slope,.01f));
+ sum+=WaterShoreFoam::Rate(c,WaterShoreFoam::Evaluate(float(x),float(y),time))
+ *WaterShoreFoam::EvaluateFront(float(x),float(y),time,c.nx,c.ny).mask*step*step*.2;
+ }
+ }
+ return sum;
+ };
+ const double fine=integral(1.25),point5=integral(5),coarse=integral(10);
+ Batch source;CHECK(source.Build(input.heights.data(),input.width,input.height,0,10,1,input.polygons,{{10,&input.field}})==WaterShoreHistory::BuildResult::Ready);
+ std::vector<double> rates(source.Cells().size());double proposed=0;
+ for(unsigned frame=0;frame<40;++frame) {
+ source((frame+.5)*.2,source.Cells().data(),source.Cells().size(),rates.data());
+ for(double rate:rates)proposed+=rate*25*.2;
+ }
+ const double proposedError=std::abs(proposed-fine)/fine,pointError=std::abs(point5-fine)/fine,coarseError=std::abs(coarse-fine)/fine;
+ CHECK(fine>0&&std::isfinite(proposedError)&&std::isfinite(coarseError));
+ // The phase-locked mirrored fixture measured 12.77%/34.10%/80.89% errors.
+ // Keep the actual quadrature budget and require both absolute and relative alias
+ // discrimination; an old >100% error requirement is not a correctness property.
+ CHECK(proposedError<.15 && pointError>.3 && coarseError>.5 && coarseError>4*proposedError);
+ std::printf("shore source spatial integral 1.25=%.8g, quadrature5=%.8g (error %.5f), point5 error %.5f, point10 error %.5f\n",fine,proposed,proposedError,pointError,coarseError);
+}
+
+#include "Platform/WaterShoreSource.h"
+namespace {
+using ShorePolygon=WaterOpticalContext::Polygon;
+ShorePolygon shoreRect(float left,float bottom,float right,float top,float level=10) {
+ ShorePolygon p;p.points={{left,bottom,level},{right,bottom,level},{right,top,level},{left,top,level}};return p;
+}
+std::vector<WaterShoreHistory::Cell> shoreFourCorners(double level=10) {
+ return {{0,0,level,0},{1,0,level,1},{0,1,level,2},{1,1,level,3}};
+}
+bool shoreIndependentContains(const ShorePolygon&p,double x,double y) {
+ bool inside=false;
+ for(size_t i=0,j=p.points.size()-1;i<p.points.size();j=i++) {
+ const auto&a=p.points[j];const auto&b=p.points[i];
+ const double dx=b.x-a.x,dy=b.y-a.y,px=x-a.x,py=y-a.y;
+ if(std::abs(dx*py-dy*px)<1e-10&&px*dx+py*dy>=-1e-10&&px*dx+py*dy<=dx*dx+dy*dy+1e-10)return true;
+ if((a.y>y)!=(b.y>y))inside=inside^(x<a.x+(y-a.y)*dx/dy);
+ }
+ return inside;
+}
+}
+TEST(water_shore_atlas_gap_support_does_not_renormalize_or_guess_nearest_membership) {
+ using namespace WaterShoreHistory;
+ const auto cells=shoreFourCorners();Topology graph;CHECK(graph.Build({},cells)==BuildResult::Ready);
+ WaterShoreSupport::Domain support;auto flat=[](double,double){return 0.0f;};
+ CHECK(support.Build({},cells,3,3,{shoreRect(0,0,2,5),shoreRect(3,0,5,5)},flat));
+ const std::vector<State> left={{1,2},{0,0},{1,2},{0,0}};
+ CHECK(std::abs(Sample(graph,left,4,2.5,10).density-.2)<1e-14); // armed old interpolation
+ CHECK(Sample(graph,left,4,2.5,10,support).density==0);
+ CHECK(Sample(graph,left,2.5,2.5,10,support).density==0);
+ const State own=Sample(graph,left,1,2.5,10,support);
+ CHECK(std::abs(own.density-.8)<1e-14&&std::abs(own.ageMoment-1.6)<1e-14); // no 0.8 -> 1 normalization
+ const std::vector<State> right={{0,0},{1,3},{0,0},{1,3}};
+ CHECK(Sample(graph,right,1,2.5,10,support).density==0);
+ // The target polygon need not contain a history node. Nearest-node labeling would
+ // attribute this isolated tiny pool to the emitting polygon on its left.
+ std::vector<Cell> sparse={{0,0,10,0},{0,1,10,1}};Topology sparseGraph;
+ CHECK(sparseGraph.Build({},sparse)==BuildResult::Ready);
+ CHECK(support.Build({},sparse,3,3,{shoreRect(0,0,1,5),shoreRect(2,2,3,3)},flat));
+ std::vector<State> sparseStates={{1,2},{1,2}};
+ CHECK(Sample(sparseGraph,sparseStates,2.5,2.5,10).density==.5);
+ CHECK(Sample(sparseGraph,sparseStates,2.5,2.5,10,support).density==0);
+ CHECK(std::abs(Sample(sparseGraph,sparseStates,.5,2.5,10,support).density-.9)<1e-14);
+}
+TEST(water_shore_atlas_touching_and_overlapping_unions_keep_original_weights) {
+ using namespace WaterShoreHistory;
+ const auto cells=shoreFourCorners();Topology graph;CHECK(graph.Build({},cells)==BuildResult::Ready);
+ WaterShoreSupport::Domain support;auto flat=[](double,double){return 0.0f;};
+ const std::vector<State> states={{1,2},{2,6},{3,12},{4,20}};
+ for(const auto&polygons:std::vector<std::vector<ShorePolygon>>{
+ {shoreRect(-5,-5,10,10)},
+ {shoreRect(0,0,2,5),shoreRect(2,0,5,5)},
+ {shoreRect(0,0,3,5),shoreRect(2,0,5,5)}}) {
+ CHECK(support.Build({},cells,3,3,polygons,flat));
+ for(int iy=0;iy<=20;++iy)for(int ix=0;ix<=20;++ix) {
+ const double x=ix*.249,y=iy*.249;
+ const State expected=Sample(graph,states,x,y,10),actual=Sample(graph,states,x,y,10,support);
+ CHECK(std::abs(expected.density-actual.density)<1e-12&&std::abs(expected.ageMoment-actual.ageMoment)<1e-12);
+ }
+ }
+ CHECK(support.Build({},cells,3,3,{shoreRect(-100,-100,100,100)},flat));
+ CHECK(support.VertexCount()==0); // interior certificate has no per-pixel polygon traversal
+}
+TEST(water_shore_atlas_concave_support_matches_independent_segment_membership) {
+ using namespace WaterShoreHistory;
+ const auto cells=shoreFourCorners();WaterShoreSupport::Domain support;auto flat=[](double,double){return 0.0f;};
+ ShorePolygon u;u.points={{0,0,10},{5,0,10},{5,5,10},{4,5,10},{4,1,10},{1,1,10},{1,5,10},{0,5,10}};
+ CHECK(support.Build({},cells,3,3,{u},flat));
+ unsigned blocked=0,allowed=0;
+ for(unsigned iy=0;iy<29;++iy)for(unsigned ix=0;ix<29;++ix) {
+ const double fx=.013+ix*.034,fy=.017+iy*.034;const auto stencil=support.At(0,0,10,fx,fy);
+ for(unsigned corner=0;corner<4;++corner) {
+ const double ax=(corner&1)*5,ay=(corner>>1)*5;bool expected=true;
+ for(unsigned step=0;step<=256&&expected;++step) {
+ const double t=double(step)/256;
+ expected=shoreIndependentContains(u,ax+(fx*5-ax)*t,ay+(fy*5-ay)*t);
+ }
+ const bool actual=stencil.Allows(corner&1,corner>>1);
+ CHECK(expected==actual);blocked+=!actual;allowed+=actual;
+ }
+ }
+ CHECK(blocked>1000&&allowed>100);
+}
+TEST(water_shore_atlas_terrain_saddle_blocks_cross_ridge_without_losing_local_foam) {
+ using namespace WaterShoreHistory;
+ const std::vector<Cell> cells={{0,0,1,0},{1,1,1,1}};Topology graph;CHECK(graph.Build({},cells)==BuildResult::Ready);
+ WaterShoreSupport::Domain support;
+ // Coordinates received by the height callback are in terrain cells; the support
+ // square is half a terrain cell. Its heights are exactly {0,4,4,0}.
+ auto saddle=[](double x,double y){x*=2;y*=2;return float(4*(x+y-2*x*y));};
+ CHECK(support.Build({},cells,3,3,{shoreRect(0,0,5,5,1)},saddle));
+ const std::vector<State> left={{1,2},{0,0}},right={{0,0},{1,3}};
+ CHECK(Sample(graph,left,4.5,4.5,1).density>.0099);
+ CHECK(Sample(graph,left,4.5,4.5,1,support).density==0);
+ CHECK(std::abs(Sample(graph,right,4.5,4.5,1,support).density-.81)<1e-12);
+ CHECK(Sample(graph,left,2.5,2.5,1,support).density==0); // dry target
+}
+TEST(water_shore_supported_raster_preserves_rgb_and_produces_no_gap_alpha) {
+ using namespace WaterShoreHistory;
+ const auto cells=shoreFourCorners();Topology graph;CHECK(graph.Build({},cells)==BuildResult::Ready);
+ WaterShoreSupport::Domain support;auto flat=[](double,double){return 0.0f;};
+ CHECK(support.Build({},cells,3,3,{shoreRect(0,0,2,5),shoreRect(3,0,5,5)},flat));
+ const std::vector<State> states={{1,2},{0,0},{1,2},{0,0}};
+ auto material=[](const State&s,double,double,double){return -std::expm1(-s.density);};
+ Mapping map={0,0,5,5,20,20};std::vector<uint32_t> pixels(400,0xfaabcdefu),legacy=pixels;
+ CHECK(RasterizeAlpha(graph,states,map,10,1,material,pixels,support));
+ CHECK(RasterizeAlpha(graph,states,map,10,1,material,legacy));
+ unsigned changed=0,retained=0;
+ for(unsigned y=0;y<20;++y)for(unsigned x=0;x<20;++x) {
+ const unsigned i=y*20+x;const double worldX=(x+.5)*.25;
+ CHECK((pixels[i]&0xffffffu)==0xabcdefu);
+ if(worldX>2){CHECK((pixels[i]>>24)==0);changed+=(legacy[i]>>24)>0;}
+ else {CHECK(pixels[i]==legacy[i]);retained+=(pixels[i]>>24)>0;}
+ }
+ CHECK(changed>100&&retained>100);
+ auto repeat=pixels;CHECK(RasterizeAlpha(graph,states,map,10,1,material,repeat,support));CHECK(repeat==pixels);
+}
+TEST(water_shore_support_complexity_failure_is_atomic_and_bounded) {
+ using namespace WaterShoreHistory;
+ const auto cells=shoreFourCorners();WaterShoreSupport::Domain support;auto flat=[](double,double){return 0.0f;};
+ CHECK(support.Build({},cells,3,3,{shoreRect(-1,-1,6,6)},flat));
+ const size_t before=support.TileCount();
+ // A high-vertex closed polygon wholly within the square needs more local
+ // boundary data than the declared cap. Reject the candidate; never truncate it.
+ ShorePolygon circle;for(unsigned i=0;i<256;++i) {
+ const double theta=i*6.283185307179586/256;
+ circle.points.push_back({float(2.5+2*std::cos(theta)),float(2.5+2*std::sin(theta)),10});
+ }
+ CHECK(!support.Build({},cells,3,3,{circle},flat));
+ CHECK(support.TileCount()==before&&support.At(0,0,10,.3,.7).Allows(0,0));
+ CHECK(support.Work()<=WaterShoreSupport::MaxWork&&support.VertexCount()<=WaterShoreSupport::MaxVertices);
+}
+
+#include <random>
+#include <set>
+#include <tuple>
+#include <cstdio>
+namespace ShoreSparseRasterAudit {
+using namespace WaterShoreHistory;
+static unsigned cases=0;static uint64_t pixels=0;
+// Frozen pre-optimization raster loop: independent full-image traversal and original
+// Sample hash lookups. Production sparse tiles are never inspected by this oracle.
+template<class Coverage,class Support> bool Reference(const Topology&t,const std::vector<State>&s,const Mapping&m,double l,double time,Coverage&c,std::vector<uint32_t>&p,const Support&support){
+ if(!std::isfinite(m.originX)||!std::isfinite(m.originY)||!std::isfinite(m.widthWorld)||!std::isfinite(m.heightWorld)||m.widthWorld<=0||m.heightWorld<=0
+ ||!std::isfinite(m.originX+m.widthWorld)||!std::isfinite(m.originY+m.heightWorld)||!m.widthPixels||!m.heightPixels||m.widthPixels>512||m.heightPixels>512
+ ||!std::isfinite(l)||!std::isfinite(time)||s.size()!=t.Cells().size()||p.size()!=size_t(m.widthPixels)*m.heightPixels)return false;
+ for(unsigned y=0;y<m.heightPixels;++y)for(unsigned x=0;x<m.widthPixels;++x){double wx=m.originX+(double(x)+.5)*m.widthWorld/m.widthPixels,wy=m.originY+(double(y)+.5)*m.heightWorld/m.heightPixels;
+ State state=Sample(t,s,wx,wy,l,support);double v=state.density>0?c(state,wx,wy,time):0;size_t n=size_t(y)*m.widthPixels+x;p[n]=WithAlpha(p[n],v);}
+ return true;
+}
+struct Coverage {unsigned calls=0;double operator()(const State&s,double x,double y,double time){++calls;
+ if(!std::isfinite(s.density)||!std::isfinite(s.ageMoment))return 0;
+ return -std::expm1(-s.density)*(.55+.45*std::sin(x*.31+y*.27+time+s.ageMoment/(s.density+.0001)));}};
+template<class Support> void Compare(const Topology&t,const std::vector<State>&s,const Mapping&m,double l,const Support&support,double time=1.375){
+ std::vector<uint32_t> seed(size_t(m.widthPixels)*m.heightPixels);for(size_t i=0;i<seed.size();++i)seed[i]=0xaa000000u|((uint32_t(i)*2654435761u)&0xffffffu);
+ auto a=seed,b=seed;Coverage ca,cb;bool ra=Reference(t,s,m,l,time,ca,a,support),rb=RasterizeAlpha(t,s,m,l,time,cb,b,support);
+ CHECK(ra==rb);CHECK(ca.calls==cb.calls);if(a!=b){size_t at=0;while(at<a.size()&&a[at]==b[at])++at;
+ std::fprintf(stderr,"RGBA mismatch case %u at %zu expected %08x actual %08x mapping %.17g %.17g %.17g %.17g %u %u level %.17g\n",cases,at,a[at],b[at],m.originX,m.originY,m.widthWorld,m.heightWorld,m.widthPixels,m.heightPixels,l);CHECK(a==b);}
+ for(size_t i=0;i<seed.size();++i)CHECK((b[i]&0xffffffu)==(seed[i]&0xffffffu));++cases;pixels+=seed.size();
+}
+static void Layout(const Topology&t){const auto&tiles=t.RasterTiles();CHECK(tiles.size()<=4*t.Cells().size());
+ for(size_t i=0;i<tiles.size();++i){if(i)CHECK(RasterLess(tiles[i-1],tiles[i]));for(int dy=0;dy<2;++dy)for(int dx=0;dx<2;++dx)
+ CHECK(tiles[i].nodes[dy*2+dx]==t.Find(tiles[i].x+dx,tiles[i].y+dy,tiles[i].level));}}
+static void General(){std::mt19937 rng(0x5afe51);for(unsigned run=0;run<180;++run){std::set<std::tuple<double,int,int>> keys;std::vector<Cell> cells;
+ for(unsigned i=0;i<320;++i){int x=int(rng()%31)-15,y=int(rng()%31)-15;double level=int(rng()%3)*7-7;if(keys.insert({level,y,x}).second)cells.push_back({x,y,level,0,uint8_t(rng()%4)});}
+ Grid grid{double(int(rng()%13)-6)/3,double(int(rng()%11)-5)/7,1+double(rng()%10)};Topology t;CHECK(t.Build(grid,cells)==BuildResult::Ready);Layout(t);
+ std::vector<State>s(t.Cells().size());for(auto&v:s){v.density=rng()%4?0:double(rng()%500)/100;v.ageMoment=v.density*double(rng()%200)/10;}
+ for(unsigned k=0;k<4;++k){Mapping m{double(int(rng()%251)-125)/3,double(int(rng()%251)-125)/7,.01+double(rng()%401)/3,.02+double(rng()%401)/4,unsigned(1+rng()%65),unsigned(1+rng()%65)};
+ Compare(t,s,m,double(int(rng()%4)*7-7),UnrestrictedSupport{});}
+ // Exact grid boundaries, repeated texels in the same cell, integer/negative origins.
+ Compare(t,s,{grid.originX-grid.spacing*2.5,grid.originY-grid.spacing*2.5,grid.spacing*20,grid.spacing*20,20,20},0,UnrestrictedSupport{});
+ }
+ for(int edge:{(std::numeric_limits<int32_t>::min)(),(std::numeric_limits<int32_t>::max)()-1}){
+ std::vector<Cell>cells{{edge,edge,7,0,3},{edge+1,edge,7,0,3},{edge,edge+1,7,0,3},{edge+1,edge+1,7,0,3}};Topology t;CHECK(t.Build({},cells)==BuildResult::Ready);Layout(t);std::vector<State>s(4,{1,.5});
+ Compare(t,s,{double(edge)*5-10,double(edge)*5-10,30,30,31,29},7,UnrestrictedSupport{});}
+ Topology t;CHECK(t.Build({1e16,1e16,5},{{0,0,7,0,3},{1,0,7,0,3},{0,1,7,0,3},{1,1,7,0,3}})==BuildResult::Ready);std::vector<State>s(4,{1,.5});
+ Compare(t,s,{1e16,1e16,1,1,64,64},7,UnrestrictedSupport{});Compare(t,s,{-1e308,-1e308,1e308,1e308,64,64},7,UnrestrictedSupport{});
+ for(auto&v:s)v={0,NAN};Compare(t,s,{1e16,1e16,1,1,16,16},7,UnrestrictedSupport{});
+ s[0]={1,2};s[1]={NAN,0};s[2]={-1,0};s[3]={INFINITY,1};Compare(t,s,{1e16,1e16,10,10,16,16},7,UnrestrictedSupport{});
+ Compare(t,s,{0,0,0,5,2,2},7,UnrestrictedSupport{});Compare(t,s,{1e308,0,1e308,5,2,2},7,UnrestrictedSupport{});
+ Compare(t,s,{0,0,10,10,4,4},NAN,UnrestrictedSupport{});Compare(t,s,{0,0,10,10,4,4},7,UnrestrictedSupport{},NAN);
+ Topology empty;CHECK(empty.Build({}, {})==BuildResult::Ready);Compare(empty,{}, {-5,-5,100,100,512,512},7,UnrestrictedSupport{});
+}
+static void Gaps(){Grid g{-25,-35,5};std::vector<WaterOpticalContext::Polygon> polygons;
+ // Fractional 0.4-unit dry polygon gap within a single5-unit history tile, plus a
+ // concave boundary and a second level. Support is the real production segment test.
+ polygons.push_back({{{-25,-35,7},{1.1f,-35,7},{1.1f,80,7},{-25,80,7}}});
+ polygons.push_back({{{1.5f,-35,7},{100,-35,7},{100,80,7},{1.5f,80,7},{1.5f,35,7},{20,35,7},{20,25,7},{1.5f,25,7}}});
+ auto high=polygons[0];for(auto&p:high.points)p.z=14;polygons.push_back(high);
+ auto terrain=[](double x,double y){return 2+5*std::sin(x*.8)*std::sin(y*.9);};
+ std::vector<Cell>cells;for(double l:{7.,14.})for(int y=0;y<24;++y)for(int x=0;x<24;++x)if(terrain(x*.5,y*.5)<l)cells.push_back({x,y,l,0,3});
+ Topology t;CHECK(t.Build(g,cells)==BuildResult::Ready);WaterShoreSupport::Domain support;CHECK(support.Build(g,cells,32,32,polygons,terrain));
+ std::vector<State>s(t.Cells().size());for(size_t i=0;i<s.size();++i)s[i]={i%5?double(i%17)/13:0,double(i%7)/9};
+ for(double level:{7.,14.,3.})for(double phase:{0.,.01,.25,.5,.999999999}){Compare(t,s,{-26+phase,-36+phase,130,130,257,191},level,support);
+ Compare(t,s,{-1+phase,-1-phase,5,5,37,41},level,support);}Layout(t);
+}
+static void Bounds(){
+ std::vector<Cell> cells;cells.reserve(MaxCells);for(unsigned i=0;i<MaxCells;++i)cells.push_back({int(i*3),0,7,0,3});
+ Topology t;CHECK(t.Build({},cells)==BuildResult::Ready);CHECK(t.RasterTiles().size()==4*MaxCells);Layout(t);
+ std::vector<State>s(cells.size(),{.5,.75});Compare(t,s,{-10,-10,1000,20,512,17},7,UnrestrictedSupport{});
+ const size_t retained=t.RasterTiles().size();cells.push_back({-1,0,7,0,3});CHECK(t.Build({},cells)==BuildResult::TooManyCells);CHECK(t.RasterTiles().size()==retained);
+ std::printf("BOUNDS nodes=%zu tiles=%zu tile_bytes=%zu maximum_reserved_bytes=%zu\n",t.Cells().size(),t.RasterTiles().size(),sizeof(RasterTile),4*MaxCells*sizeof(RasterTile));
+ for(double direction:{-INFINITY,INFINITY})for(double boundary:{-5.,0.,5.}){
+ double at=std::nextafter(boundary,direction);Compare(t,s,{at-.5,-.5,1,1,1,1},7,UnrestrictedSupport{});}
+}
+}
+
+TEST(water_shore_sparse_raster_matches_full_scan_reference_across_mappings_and_invalid_states)
+{ ShoreSparseRasterAudit::General(); }
+TEST(water_shore_sparse_raster_preserves_exact_gap_saddle_and_concave_support)
+{ ShoreSparseRasterAudit::Gaps(); }
+TEST(water_shore_sparse_raster_bounds_cache_and_owns_every_pixel_once)
+{ ShoreSparseRasterAudit::Bounds(); }
+
+// Pure scalar oracle exercises the same bounded positive contribution emitted to both
+// stages. The independent central difference includes gradients of F, D and bow pressure.
+#include "Platform/WaterBowLift.h"
+TEST(water_bow_lift_bounds_zero_and_product_derivative)
+{
+ using namespace WaterBowLift;const double V=WaterFftGeometry::MaxVerticalDisplacement;
+ unsigned restored=0;
+ for(double free:{0.,.05,.31,.559713426,1.})for(double ratio:{0.,.2,.8,1.})
+ for(double incident:{-100.,-10.,-1.,0.,1.,10.,100.})for(double bow:{0.,.000001,.2,3.,8.,64.}) {
+ const double damping=free*ratio,old=damping*V*std::tanh((incident+bow)/V);
+ const Field added=Additional({bow,.31,-.22},{free,.003,.002},{damping,-.002,.001});
+ const double total=old+added.value;
+ CHECK(std::isfinite(total) && std::abs(total)<=free*V+1e-12 && total>=old);
+ if(bow==0 || free==damping)CHECK(added.value==0 && added.dx==0 && added.dy==0);
+ else {
+ ++restored;
+ const double epsilon=1e-5;
+ auto independent=[&](double x,double y) {
+ return (free+.003*x+.002*y-damping+.002*x-.001*y)*V*
+ std::tanh((bow+.31*x-.22*y)/V);
+ };
+ // Stay within the branch's positive B domain; separate exact boundary
+ // cases above test zero emission without finite-differencing a clamp kink.
+ if(bow>.00001) {
+ CHECK(std::abs(added.dx-(independent(epsilon,0)-independent(-epsilon,0))/(2*epsilon))<1e-8);
+ CHECK(std::abs(added.dy-(independent(0,epsilon)-independent(0,-epsilon))/(2*epsilon))<1e-8);
+ }
+ CHECK(Foam(added.value,0)==0 && Foam(0,1)==0);
+ CHECK(Foam(added.value,1)>=0 && Foam(added.value,1)<=.65);
+ }
+ }
+ CHECK(restored>100);
+}
+
+// Scalar contract for the diagnostic's counterfactual. Removing only bow keeps
+// incident/reflected/stern height and phase; compare complete final heights directly.
+TEST(water_bow_retention_same_phase_marginal_is_not_an_isolated_peak)
+{
+ const double v=WaterFftGeometry::MaxVerticalDisplacement;
+ auto limit=[&](double z){return v*std::tanh(z/v);};
+ unsigned positive=0,isolatedWrong=0,overEnvelope=0;
+ for(double a:{-32.,-10.,-1.,0.,1.,10.,32.})for(double b:{0.,.000001,.2,3.,8.,64.})
+ for(double f:{0.,.559713426,1.})for(double ratio:{0.,.5,1.})for(double w:{0.,.4,1.}) {
+ const double d=f*ratio,oldAnalytic=-2.3;
+ const auto lift=WaterBowLift::Additional({b,0,0},{f,0,0},{d,0,0});
+ const double finalWith=(1-w)*oldAnalytic+w*(d*limit(a+b)+lift.value);
+ const double finalWithout=(1-w)*oldAnalytic+w*d*limit(a);
+ const double expected=w*(d*(limit(a+b)-limit(a))+(f-d)*limit(b));
+ CHECK_NEAR(finalWith-finalWithout,expected,1e-12);
+ CHECK(expected>=-1e-12 && expected<=w*(f+d)*v+1e-12);
+ if(b==0 || w==0 || f==0)CHECK(expected==0);
+ if(d==0)CHECK_NEAR(expected,w*f*limit(b),1e-12);
+ if(d==f)CHECK(lift.value==0);
+ positive+=expected>.01;isolatedWrong+=std::abs(expected-w*f*limit(b))>.01;
+ overEnvelope+=expected>w*f*v+.01;
+ }
+ CHECK(positive>100 && isolatedWrong>100 && overEnvelope>0);
+ const double b=8;
+ CHECK(limit(-10+b)-limit(-10)>limit(10+b)-limit(10));
+ CHECK(limit(-32+64)-limit(-32)>1.9*v);
+}
+
+namespace SternAnchorNative {
+// Original native campaign carrier trace, object1735. These unmodified contact polygons
+// expose the tilted-transom extremal-corner switch, especially frames4336/4337.
+struct Pose { unsigned frame;float origin[2],axis[2];double sectionY;WaterHullModel::Point vertices[12]; };
+static const Pose Poses[]={
+ {4220, {2959.32f,1120.78f}, {-0.99979f,-0.0204964f}, -1.0578909956073836, {{-284.549f,-0.231101f},{-267.471f,-7.19379f},{-7.28663f,-76.2132f},{199.121f,-70.1169f},{270.821f,-65.6736f},{272.496f,-50.5279f},{273.377f,23.8783f},{270.693f,24.3134f},{45.5953f,32.0521f},{-115.97f,25.2146f},{-267.925f,6.48248f},{-275.605f,3.95113f}}},
+ {4250, {2999.31f,1121.6f}, {-0.99979f,-0.0204936f}, -0.32441283366568285, {{-226.052f,-16.2233f},{-6.73874f,-76.747f},{160.862f,-73.3101f},{259.01f,-67.9497f},{261.689f,-67.4745f},{265.114f,-44.1614f},{266.778f,20.4989f},{266.337f,24.7154f},{263.832f,25.0799f},{46.1111f,32.0093f},{-114.734f,24.4844f},{-195.63f,14.8339f}}},
+ {4280, {3039.3f,1122.42f}, {-0.99979f,-0.0204889f}, -0.10351113058784023, {{-213.799f,12.7919f},{-196.922f,-22.2646f},{-7.64609f,-74.9638f},{183.475f,-70.5559f},{263.074f,-65.9937f},{265.728f,-65.7127f},{267.34f,-42.9061f},{265.513f,21.6078f},{264.768f,26.2135f},{262.238f,26.7739f},{46.5009f,33.2244f},{-115.12f,25.0265f}}},
+ {4310, {3079.29f,1123.24f}, {-0.99979f,-0.0204799f}, -1.0705070375351973, {{-284.638f,-0.0455329f},{-268.456f,-6.92232f},{-8.20531f,-74.473f},{224.652f,-67.5397f},{274.875f,-64.5264f},{275.34f,-54.0291f},{271.542f,24.9342f},{268.829f,25.5826f},{46.028f,33.2945f},{-116.389f,26.0933f},{-267.6f,6.71308f},{-275.661f,4.113f}}},
+ {4336, {3113.95f,1123.96f}, {-0.999791f,-0.020461f}, -0.4750876418450609, {{-271.514f,-0.275939f},{-247.809f,-8.57374f},{-42.514f,-66.4348f},{-7.76008f,-75.8955f},{256.202f,-65.8565f},{278.09f,-64.5216f},{281.147f,-64.1222f},{281.706f,22.5218f},{279.095f,22.9693f},{45.0761f,31.9652f},{-117.476f,26.114f},{-248.194f,7.7703f}}},
+ {4337, {3115.28f,1123.98f}, {-0.999791f,-0.0204598f}, -0.4560529930414532, {{-270.872f,-0.310776f},{-247.179f,-8.64923f},{-43.0014f,-66.3589f},{-7.7475f,-75.9495f},{257.873f,-65.7452f},{281.417f,-64.0851f},{281.679f,-43.3014f},{281.696f,22.5213f},{279.549f,22.8832f},{45.0306f,31.9014f},{-117.493f,26.0859f},{-247.663f,7.77216f}}},
+ {4340, {3119.28f,1124.06f}, {-0.999791f,-0.0204556f}, -0.3622370990942123, {{-268.474f,-0.423517f},{-244.801f,-8.91572f},{-45.2046f,-65.9759f},{-7.67355f,-76.1656f},{261.119f,-65.5286f},{278.867f,-64.4342f},{281.712f,-64.0363f},{281.663f,22.5193f},{44.9356f,31.7687f},{-75.0565f,27.7287f},{-117.611f,26.0414f},{-245.581f,7.80207f}}},
+ {4369, {3156.56f,1124.83f}, {-0.999791f,-0.020452f}, -0.5364621224824262, {{-252.058f,-1.0349f},{-250.711f,-2.70629f},{-239.325f,-10.5158f},{-54.7156f,-64.3754f},{-7.48132f,-77.0003f},{250.628f,-64.9803f},{165.937f,26.2414f},{44.4449f,31.2162f},{-72.8416f,27.6113f},{-118.362f,25.9218f},{-210.78f,21.1847f},{-239.904f,8.07114f}}},
+ {4370, {3157.54f,1124.85f}, {-0.99979f,-0.0204889f}, -0.5084142236865787, {{-252.188f,-1.01236f},{-250.953f,-2.54707f},{-239.406f,-10.4677f},{-54.4356f,-64.4199f},{-7.48825f,-76.9737f},{252.311f,-64.9286f},{168.415f,26.1623f},{44.4587f,31.2324f},{-72.8634f,27.6204f},{-118.345f,25.9305f},{-210.885f,20.9874f},{-239.972f,8.07099f}}},
+};
+static WaterHullModel::Hull Pack(const Pose &p) {
+ WaterHullModel::Hull h;
+ float minX=1e30f,maxX=-1e30f,minY=1e30f,maxY=-1e30f;
+ for(const auto &v:p.vertices){minX=(std::min)(minX,v.x);maxX=(std::max)(maxX,v.x);minY=(std::min)(minY,v.y);maxY=(std::max)(maxY,v.y);}
+ const float cx=(minX+maxX)*.5f,cy=(minY+maxY)*.5f;
+ h.data[0][0]=p.origin[0]+p.axis[0]*cx-p.axis[1]*cy;h.data[0][1]=p.origin[1]+p.axis[1]*cx+p.axis[0]*cy;
+ h.data[0][2]=7;h.data[0][3]=12;h.data[1][0]=p.axis[0];h.data[1][1]=p.axis[1];
+ h.data[1][2]=(maxX-minX)*.5f;h.data[1][3]=(maxY-minY)*.5f;h.data[2][0]=40;h.data[2][1]=.82f;
+ h.data[3][0]=-h.data[1][2];h.data[3][2]=h.data[1][2];unsigned left=0,right=0;
+ for(unsigned i=0;i<12;++i){const float x=p.vertices[i].x-cx,y=p.vertices[i].y-cy;
+ h.data[4+i/2][(i%2)*2]=x;h.data[4+i/2][(i%2)*2+1]=y;
+ if(x<-h.data[1][2]+.5f){h.data[3][1]+=y;++left;}if(x>h.data[1][2]-.5f){h.data[3][3]+=y;++right;}}
+ if(left)h.data[3][1]/=left;if(right)h.data[3][3]/=right;return h;
+}
+static WaterFoamHistory::Point OldAnchor(const WaterHullModel::Hull &h) {
+ const double norm=std::hypot(double(h.data[1][0]),double(h.data[1][1]));
+ const double ax=h.data[1][0]/norm,ay=h.data[1][1]/norm;
+ const double speed=std::hypot(double(h.data[2][0]),double(h.data[2][1]));
+ const double f=WaterFoamHistory::Smooth(-.25,.25,(h.data[2][0]*ax+h.data[2][1]*ay)/(std::max)(speed,.001));
+ const double x=h.data[3][2]+(h.data[3][0]-h.data[3][2])*f,y=h.data[3][3]+(h.data[3][1]-h.data[3][3])*f;
+ return {h.data[0][0]+ax*x-ay*y,h.data[0][1]+ay*x+ax*y};
+}
+}
+TEST(water_foam_stern_anchor_native_carrier_extrema_do_not_jump_across_transom)
+{
+ using namespace WaterFoamHistory;
+ double oldLow=1e30,oldHigh=-1e30,newLow=1e30,newHigh=-1e30;
+ Point oldBefore={},oldAfter={},newBefore={},newAfter={};
+ for(const auto &pose:SternAnchorNative::Poses) {
+ auto hull=SternAnchorNative::Pack(pose);Sample sample;CHECK(MakeSample(hull,0,sample));
+ const double axisLength=std::hypot(double(hull.data[1][0]),double(hull.data[1][1]));
+ const Point axis={hull.data[1][0]/axisLength,hull.data[1][1]/axisLength};
+ const Point relative={sample.lanes[0].x-sample.center.x,sample.lanes[0].y-sample.center.y};
+ const double cross=-relative.x*axis.y+relative.y*axis.x;
+ CHECK_NEAR(cross,pose.sectionY,.00004); // Independent raw-contour double intersection oracle.
+ const Point old=SternAnchorNative::OldAnchor(hull);
+ oldLow=(std::min)(oldLow,old.y);oldHigh=(std::max)(oldHigh,old.y);
+ newLow=(std::min)(newLow,sample.lanes[0].y);newHigh=(std::max)(newHigh,sample.lanes[0].y);
+ if(pose.frame==4336){oldBefore=old;newBefore=sample.lanes[0];}
+ if(pose.frame==4337){oldAfter=old;newAfter=sample.lanes[0];}
+ CHECK_NEAR(sample.width[0],Clamp(sample.halfWidth*.30+std::sqrt(sample.halfWidth)*.8,2.5,30),1e-12);
+ const double speed=std::hypot(double(hull.data[2][0]),double(hull.data[2][1]));
+ const double response=2*Smooth(.3,12,speed)*(.8+.25*std::sqrt((std::min)(speed,250.)));
+ CHECK_NEAR(sample.rate[0],response*(std::min)(1.0,6.0/sample.width[0]),1e-12);
+ CHECK_NEAR(sample.rate[1],response*.22,1e-12);CHECK(sample.rate[2]==sample.rate[1]);
+ // Longitudinal aft selection is unchanged, including reverse and the existing
+ // smooth broadside transition. The correction concerns only transverse placement.
+ for(double direction:{-1.0,0.0,1.0}) {
+ auto test=hull;test.data[2][0]=float(direction*40*axis.x-40*(1-std::abs(direction))*axis.y);
+ test.data[2][1]=float(direction*40*axis.y+40*(1-std::abs(direction))*axis.x);
+ Sample selected;CHECK(MakeSample(test,0,selected));
+ const Point r={selected.lanes[0].x-selected.center.x,selected.lanes[0].y-selected.center.y};
+ const double forward=Smooth(-.25,.25,(test.data[2][0]*axis.x+test.data[2][1]*axis.y)/std::hypot(double(test.data[2][0]),double(test.data[2][1])));
+ const double expectedX=test.data[3][2]+(test.data[3][0]-test.data[3][2])*forward;
+ CHECK_NEAR(r.x*axis.x+r.y*axis.y,expectedX,.000001);
+ CHECK_NEAR(-r.x*axis.y+r.y*axis.x,pose.sectionY,.00004);
+ CHECK(Distance(selected.lanes[1],sample.lanes[1])<1e-10 && Distance(selected.lanes[2],sample.lanes[2])<1e-10);
+ }
+ }
+ CHECK(oldHigh-oldLow>90 && newHigh-newLow<6); // Armed original endpoint-placement regression.
+ CHECK(Distance(oldBefore,oldAfter)>50 && Distance(newBefore,newAfter)<2);
+ std::printf("stern anchor native9poses lateral span %.7g->%.7g; jump4336/4337 %.7g->%.7g\n",
+ oldHigh-oldLow,newHigh-newLow,Distance(oldBefore,oldAfter),Distance(newBefore,newAfter));
+}
+
+static WaterHullModel::Hull asymmetricSternHull(float x,float y,float vx,float vy,float angle=0)
+{
+ auto h=foamTestHull(x,y,vx,vy,angle);h.data[1][3]=7;h.data[3][1]=-3;h.data[3][3]=2;
+ const float vertices[8]={-12,-7,12,-3,12,7,-12,1};
+ for(unsigned i=0;i<8;++i)h.data[4+i/4][i%4]=vertices[i];return h;
+}
+TEST(water_foam_stern_anchor_turn_stop_pause_and_reverse_keep_history_contract)
+{
+ using namespace WaterFoamHistory;
+ // The asymmetric transom corners have different averages at each end. Their
+ // central cross-section is analytically [-5,4], hence the retained path is y=-.5.
+ for(float angle:{0.f,.7f,1.6f})for(float direction:{-1.f,1.f}) {
+ const double c=std::cos(angle),s=std::sin(angle);
+ auto h=asymmetricSternHull(17,-23,float(direction*30*c),float(direction*30*s),angle);Sample sample;
+ CHECK(MakeSample(h,0,sample));
+ const double norm=std::hypot(double(h.data[1][0]),double(h.data[1][1]));
+ const Point axis={h.data[1][0]/norm,h.data[1][1]/norm};
+ CHECK_NEAR(sample.lanes[0].x,17-direction*12*axis.x+.5*axis.y,1e-10);
+ CHECK_NEAR(sample.lanes[0].y,-23-direction*12*axis.y-.5*axis.x,1e-10);
+ }
+ History history;
+ for(unsigned frame=0;frame<=120;++frame) {
+ const double t=frame/30.,angle=t*.4;history.Advance(t);
+ history.Observe(1,asymmetricSternHull(float(70*std::sin(angle)),float(70*(1-std::cos(angle))),
+ float(28*std::cos(angle)),float(28*std::sin(angle)),float(angle)),t);
+ }
+ CHECK(history.SegmentCount()==16);const Segment first=history.Segments().front();
+ CHECK(Distance(first.begin.lanes[0],{-12,-.5})<1e-10);
+ CHECK(history.Segments().back().end.lanes[0].y>55);
+ const auto stopped=asymmetricSternHull(float(70*std::sin(1.6)),float(70*(1-std::cos(1.6))),30,0,1.6f);
+ const Point stoppedOrigin={stopped.data[0][0],stopped.data[0][1]};
+ for(unsigned frame=121;frame<=150;++frame) {
+ const double t=frame/30.;auto bob=stopped;bob.data[3][1]+=float(std::sin(t*13)*5);bob.data[3][3]-=float(std::cos(t*11)*5);
+ history.Advance(t);history.Observe(1,bob,t,true,false,&stoppedOrigin);
+ }
+ const size_t count=history.SegmentCount();CHECK(count>=16&&count<=17);
+ const Mapping mapping={-64,-64,192,192,192,192};std::vector<std::uint32_t> fresh,paused,old;
+ CHECK(history.BuildAtlas(mapping,7,fresh));
+ for(unsigned i=0;i<20;++i){CHECK(!history.Advance(5));CHECK(!history.Observe(1,stopped,5,true,false,&stoppedOrigin));}
+ CHECK(history.BuildAtlas(mapping,7,paused)&&paused==fresh);
+ for(unsigned frame=151;frame<=300;++frame){const double t=frame/30.;history.Advance(t);history.Observe(1,stopped,t,true,false,&stoppedOrigin);}
+ CHECK(history.SegmentCount()==count && Distance(history.Segments().front().begin.lanes[0],first.begin.lanes[0])==0);
+ CHECK(history.BuildAtlas(mapping,7,old));unsigned freshSum=0,oldSum=0;
+ for(size_t i=0;i<fresh.size();++i){freshSum+=(fresh[i]>>16)&255;oldSum+=(old[i]>>16)&255;}
+ CHECK(oldSum>0&&oldSum<freshSum);
+ history.Advance(30);CHECK(history.SegmentCount()==0);
+}
+
+static WaterHullModel::Hull foamSizedHull(float x,float y,float vx,float vy,float beam)
+{
+ auto h=foamTestHull(x,y,vx,vy);const float length=(std::min)(beam*3,4096.f);
+ h.data[1][2]=length;h.data[1][3]=beam;h.data[3][0]=-length;h.data[3][2]=length;
+ const float p[8]={-length,-beam,length,-beam,length,beam,-length,beam};
+ for(unsigned i=0;i<8;++i)h.data[4+i/4][i%4]=p[i];return h;
+}
+TEST(water_foam_stern_dose_preserves_small_boats_and_unmodified_side_sources)
+{
+ using namespace WaterFoamHistory;
+ // Native PT half-widths 8.34..10.69 imply initial widths 4.812..5.823. The
+ // six-world reference preserves that measured range, including both endpoints.
+ for(float beam:{1.f,4.f,8.34f,9.33f,10.69f,11.f,11.2f,54.1f,74.f,4096.f})
+ for(float speed:{0.f,.3f,1.f,6.f,12.f,40.f,250.f,500.f})for(float sign:{-1.f,1.f}) {
+ Sample s;CHECK(MakeSample(foamSizedHull(0,0,sign*speed,0,beam),0,s));
+ const double response=2*Smooth(.3,12,double(speed))*(.8+.25*std::sqrt((std::min)(double(speed),250.)));
+ const double frozenWidth=Clamp(double(beam)*.30+std::sqrt(double(beam))*.8,2.5,30);
+ CHECK(s.width[0]==frozenWidth);
+ CHECK(s.width[1]==Clamp(double(beam)*.055,.65,3) && s.width[2]==s.width[1]);
+ CHECK(s.rate[1]==response*.22 && s.rate[2]==s.rate[1]);
+ if(frozenWidth<=6) CHECK(s.rate[0]==response); // Exact legacy arithmetic, no approximate tolerance.
+ else CHECK_NEAR(s.rate[0]*frozenWidth,response*6,1e-12);
+ CHECK(s.rate[0]>=response*.2-1e-14 && s.rate[0]<=response);
+ }
+}
+TEST(water_foam_stern_integrated_dose_scales_with_transom_span_not_disk_area)
+{
+ using namespace WaterFoamHistory;
+ const double pi=3.14159265358979323846;
+ for(float beam:{4.f,10.69f,20.f,54.1f,74.f,4096.f})for(float speed:{6.f,12.f,40.f}) {
+ Sample s;CHECK(MakeSample(foamSizedHull(0,0,speed,0,beam),0,s));
+ const double w=s.width[0],r=2.5*w,response=2*Smooth(.3,12,double(speed))*(.8+.25*std::sqrt(double(speed)));
+ // Closed-form radial quartic area is pi*R^2/3. Integrate the actual kernel
+ // numerically in polar coordinates, independently of that antiderivative.
+ const unsigned radialSteps=1024;double area=0;
+ for(unsigned i=0;i<radialSteps;++i) {
+ const double rho=r*(i+.5)/radialSteps;
+ area+=IntegrateKernel(rho,0,0,r).mass*2*pi*rho*r/radialSteps;
+ }
+ const double integrated=s.rate[0]*area;
+ const double expected=response*(25*pi/12)*w*(std::min)(w,6.0);
+ CHECK(std::abs(integrated-expected)<expected*6e-7);
+ // A point crossed by a steady path sees 16R/(15*speed) seconds of weighted
+ // residence. Both whole-path and partitioned actual kernels must agree;
+ // the previous rate grows centre dose with width and is an armed control.
+ const double path=4*r,duration=path/speed,position=path*.5;
+ const double expectedPeak=response*(8.0/3)*(std::min)(w,6.0)/speed;
+ for(unsigned sections:{1u,8u,64u}) {
+ double dose=0;
+ for(unsigned i=0;i<sections;++i)
+ dose+=s.rate[0]*duration/sections*IntegrateKernel(position-path*i/sections,0,path/sections,r).mass;
+ CHECK_NEAR(dose,expectedPeak,2e-13);
+ }
+ if(beam>50) {
+ const double oldPeak=response*(16.0/15)*r/speed;
+ CHECK(oldPeak>3*expectedPeak);
+ CHECK(response*area>3*integrated);
+ }
+ }
+}
+TEST(water_foam_large_stern_normalization_preserves_fixed_time_pause_stop_and_age)
+{
+ using namespace WaterFoamHistory;
+ const Mapping map={-240,-100,480,200,256,128};std::vector<std::uint32_t> reference;
+ for(unsigned fps:{30u,120u}) {
+ History history;
+ for(unsigned frame=0;frame<=fps*4;++frame) {
+ const double t=double(frame)/fps;history.Advance(t);
+ history.Observe(1,foamSizedHull(float(40*t),0,40,0,54.1f),t);
+ }
+ CHECK(history.SegmentCount()==16);const auto first=history.Segments().front();
+ std::vector<std::uint32_t> moving,paused,aged;CHECK(history.BuildAtlas(map,7,moving));
+ if(reference.empty())reference=moving;
+ unsigned sum=0,peak=0;
+ for(size_t i=0;i<moving.size();++i)for(unsigned shift:{0u,8u,16u}) {
+ CHECK(std::abs(int((moving[i]>>shift)&255)-int((reference[i]>>shift)&255))<=1);
+ if(shift==16){sum+=(moving[i]>>16)&255;peak=(std::max)(peak,(moving[i]>>16)&255u);}
+ }
+ CHECK(sum>10000 && peak>100 && peak<250); // Nonempty, visibly bounded density, no UNORM saturation.
+ const auto stopped=foamSizedHull(160,0,40,0,54.1f); // Deliberately stale speed after position stops.
+ for(unsigned pass=0;pass<20;++pass){CHECK(!history.Advance(4));CHECK(!history.Observe(1,stopped,4));}
+ CHECK(history.BuildAtlas(map,7,paused)&&paused==moving);
+ for(unsigned frame=fps*4+1;frame<=fps*8;++frame) {
+ const double t=double(frame)/fps;history.Advance(t);history.Observe(1,stopped,t);
+ }
+ CHECK(history.SegmentCount()==16 && Distance(history.Segments().front().begin.lanes[0],first.begin.lanes[0])==0);
+ CHECK(history.BuildAtlas(map,7,aged));unsigned oldSum=0;for(auto px:aged)oldSum+=(px>>16)&255;
+ CHECK(oldSum>0 && oldSum<sum);
+ history.Advance(30);CHECK(history.SegmentCount()==0);CHECK(history.BuildAtlas(map,7,aged));
+ for(auto px:aged)CHECK(px==0);
+ }
+}
+
+#include "WaterBowShoulderTest.h"
+
+TEST(water_default_bow_refinement_matches_explicit_contour)
+{
+ struct RestoreOption {
+ bool had;std::string value;
+ RestoreOption():had(getenv("ZH_WATER_BOW_SHOULDER")!=nullptr),
+ value(getenv("ZH_WATER_BOW_SHOULDER")?getenv("ZH_WATER_BOW_SHOULDER"):""){}
+ ~RestoreOption(){if(had)setenv("ZH_WATER_BOW_SHOULDER",value.c_str(),1);else unsetenv("ZH_WATER_BOW_SHOULDER");}
+ } restore;
+ CHECK(unsetenv("ZH_WATER_BOW_SHOULDER")==0);
+ using namespace WaterBowRefinement;
+ for(unsigned i=0;i<3;++i) {
+ const auto hull=WaterBowShoulderTest::CapturedHull(i);
+ Bow ordinary,explicitContour;
+ CHECK(MakeBow(i+1,hull,hull,4,ordinary));
+ CHECK(MakeBow(i+1,hull,hull,4,explicitContour,true));
+ CHECK(ordinary.shoulder && explicitContour.shoulder);
+ CHECK(ordinary.origin.x==explicitContour.origin.x && ordinary.origin.y==explicitContour.origin.y);
+ CHECK(ordinary.centre.x==explicitContour.centre.x && ordinary.centre.y==explicitContour.centre.y);
+ Prepared a,b;const auto view=bowTestView();
+ CHECK(PrepareBow(ordinary,view,a));CHECK(PrepareBow(explicitContour,view,b));
+ CHECK(a.desiredDepth==b.desiredDepth && a.heightGate==b.heightGate);
+ const Logical at={int(std::round(a.cell.x*4)),int(std::round(a.cell.y*4))};
+ for(int x=-60;x<=60;x+=5)for(int y=-20;y<=20;y+=5)for(unsigned level:{1u,2u}) {
+ const Point world={ordinary.centre.x+x,ordinary.centre.y+y};
+ CHECK(Demand(a,level,at,world)==Demand(b,level,at,world));
+ }
+ }
+}
+#include "WaterHullContactFoamTest.h"
+TEST(water_bow_shoulder_contour_gradient_motion_bounds_and_inverse_refinement)
+{
+ namespace S=WaterBowShoulder;namespace T=WaterBowShoulderTest;
+ unsigned tested=0;double maximum=0;
+ for(double speed:{1.,15.,40.,-40.})for(double angle:{0.,.4,1.3}) {
+ auto h=T::hull(speed,angle);auto c=T::contour(h);
+ for(int x=-64;x<64;x+=3)for(int y=-23;y<24;y+=3) {
+ S::Point local={x+.317,y+.213},p=S::ToWorld(c,local);const auto f=S::Evaluate(c,p);
+ CHECK_NEAR(f.value,T::oracle(h,p.x,p.y),.000002);CHECK(f.value>=0&&f.value<=c.amplitude+.000001);
+ const double step=.0001;
+ CHECK_NEAR(f.dx,(T::oracle(h,p.x+step,p.y)-T::oracle(h,p.x-step,p.y))/(2*step),.00002);
+ CHECK_NEAR(f.dy,(T::oracle(h,p.x,p.y+step)-T::oracle(h,p.x,p.y-step))/(2*step),.00002);
+ const auto q=S::QueryLocal(c,local);
+ for(unsigned k=0;k<8;++k) {
+ const double a=k*.7853981633974483;const S::Point parameter={p.x+8*std::cos(a),p.y+8*std::sin(a)};
+ const auto lower=S::InverseProfileLowerBounds(c,parameter,8);
+ CHECK(lower.x<=std::abs((q.distance-.5*c.width)/c.width)+.000002);
+ CHECK(lower.y<=q.retreat/c.length+.000002);
+ }
+ maximum=(std::max)(maximum,f.value);++tested;
+ }
+ }
+ CHECK(tested>8000&&maximum>3);
+ auto h=T::hull();auto c=T::contour(h);const auto centre=S::ToWorld(c,{40+.5*c.width,0});
+ CHECK_NEAR(S::Evaluate(c,centre).value,c.amplitude,.000001);
+ CHECK(S::Evaluate(c,S::ToWorld(c,{-42,0})).value==0);
+ CHECK(S::Evaluate(c,S::ToWorld(c,{40+3.5*c.width,0})).value==0);
+ WaterBowRefinement::Bow bow;CHECK(WaterBowRefinement::MakeBow(1,h,h,4,bow,true));
+ CHECK(bow.shoulder&&bow.sigmaAlong==c.width&&bow.sigmaAcross==c.width);
+ CHECK(WaterBowRefinement::MaxAddedVertices==8190&&WaterBowRefinement::MaxAddedTriangles==16380);
+ auto a=S::Evaluate(c,centre),b=S::Evaluate(c,centre);CHECK(a.value==b.value&&a.dx==b.dx&&a.dy==b.dy);
+ h.data[2][0]=0;S::Contour stopped;CHECK(!S::Prepare(h,4,16,4,stopped));
+ for(float invalid:{0.f,2.f,3.5f,13.f}){h=T::hull();h.data[0][3]=invalid;CHECK(!S::Prepare(h,4,16,4,stopped));}
+ h=T::hull();h.data[4][0]=NAN;CHECK(!S::Prepare(h,4,16,4,stopped));
+}
+
+TEST(water_bow_shoulder_actual_native_contours_and_detail_anchor_stability)
+{
+ namespace S=WaterBowShoulder;namespace T=WaterBowShoulderTest;
+ for(unsigned pose=0;pose<3;++pose) {
+ const auto h=T::CapturedHull(pose);const auto c=T::contour(h);
+ for(double x:{20.31,30.27,38.17,43.13,46.21})for(double y:{-11.13,-7.21,-2.17,1.31,6.19,10.23}) {
+ const auto p=S::ToWorld(c,{x,y});const auto f=S::Evaluate(c,p);const double e=.0001;
+ CHECK_NEAR(f.value,T::oracle(h,p.x,p.y),.000003);
+ CHECK_NEAR(f.dx,(T::oracle(h,p.x+e,p.y)-T::oracle(h,p.x-e,p.y))/(2*e),.00003);
+ CHECK_NEAR(f.dy,(T::oracle(h,p.x,p.y+e)-T::oracle(h,p.x,p.y-e))/(2*e),.00003);
+ }
+ }
+ auto h=T::hull(-40);h.data[2][1]=-.0004f;const auto a=T::contour(h);
+ h.data[2][1]=.0004f;const auto b=T::contour(h);
+ CHECK(std::hypot(a.supportCentre.x-b.supportCentre.x,a.supportCentre.y-b.supportCentre.y)<.002);
+ // The physical support value and field do not jump when an extremal edge tie changes.
+ const auto p=S::ToWorld(a,{-42,2});CHECK_NEAR(S::Evaluate(a,p).value,S::Evaluate(b,p).value,.0001);
+}
+
+namespace CoastalCrestAudit {
+double Scalar(const double f[6]) {
+ auto unit=[](double x){return (std::max)(0.,(std::min)(1.,x));};
+ auto smooth=[&](double a,double b,double x){const double t=unit((x-a)/(b-a));return t*t*(3-2*t);};
+ for(unsigned i=0;i<6;++i)if(!std::isfinite(f[i]))return 0;
+ const double h=f[0],d=f[1],s=unit(f[2]),e=unit(f[3]);
+ const double obstacle=(std::max)(0.,unit(f[4])-double(.5f/255.f));
+ const double gain=(std::max)(0.,obstacle-unit(f[5]));
+ if(h<=0||d<=double(WaterShoreFoam::MinDepth))return 0;
+ const double c=d-double(WaterShoreFoam::MinDepth);
+ return s*e*smooth(WaterShoreFoam::MinDepth,WaterShoreFoam::WetDepth,d)*gain
+ *c*std::tanh(h/c)*smooth(0,WaterShoreFoam::CrestHeight,h);
+}
+}
+TEST(water_coastal_crest_shared_height_derivative_and_zero_controls)
+{
+ using namespace WaterCoastalCrest;double maximum=0;unsigned armed=0;
+ for(unsigned i=0;i<96;++i) {
+ Field fields[6]={{.05f+.029f*i,.17f,-.23f},{.17f+.037f*i,.07f,-.04f},
+ {.13f+float(i%6)*.11f,.031f,-.023f},{.21f+float(i%5)*.13f,-.017f,.021f},
+ {.67f+float(i%4)*.07f,.011f,-.019f},{.03f+float(i%7)*.035f,.013f,.009f}};
+ const Field a=Correction(fields[0],fields[1],fields[2],fields[3],fields[4],fields[5]);
+ double v[6];for(unsigned n=0;n<6;++n)v[n]=fields[n].height;
+ CHECK_NEAR(a.height,CoastalCrestAudit::Scalar(v),.000003);
+ for(unsigned axis=0;axis<2;++axis) {
+ double lo[6],hi[6];for(unsigned n=0;n<6;++n){const double gradient=axis?fields[n].dy:fields[n].dx;lo[n]=v[n]-1e-4*gradient;hi[n]=v[n]+1e-4*gradient;}
+ const double derivative=(CoastalCrestAudit::Scalar(hi)-CoastalCrestAudit::Scalar(lo))/.0002;
+ const double error=std::abs(double(axis?a.dy:a.dx)-derivative);maximum=(std::max)(maximum,error);CHECK(error<.00008);
+ }
+ armed+=a.height>.01f;
+ }
+ CHECK(armed>30);
+ CHECK(Eligible(false,true,0));CHECK(!Eligible(true,true,0));CHECK(!Eligible(false,false,0));CHECK(!Eligible(false,true,.000001f));
+ CHECK(Height(-1,2,1,1,1,.1f)==0);CHECK(Height(1,0,1,1,1,.1f)==0);
+ CHECK(Height(1,2,0,1,1,.1f)==0);CHECK(Height(1,2,1,0,1,.1f)==0);CHECK(Height(1,2,1,1,.1f,.1f)==0);
+ CHECK(Height(std::numeric_limits<float>::quiet_NaN(),2,1,1,1,.1f)==0);
+ std::printf("coastal crest independent scalar/complete product derivative96cases max %.9g\n",maximum);
+}
+TEST(water_coastal_crest_cannot_lower_mesh_or_exceed_existing_legacy_envelope)
+{
+ using namespace WaterCoastalCrest;unsigned nonzero=0;float largest=0;
+ for(unsigned i=0;i<20000;++i) {
+ const float x=float((i*73)%1000)-500,y=float((i*47)%800)-400,time=float(i%601)/30;
+ const auto wave=WaterSurfaceModel::Evaluate(x,y,time);const float broad=WaterShoreFoam::Evaluate(x,y,time).height;
+ const float depth=float(i%201)*.06f,obstacle=float((i*17)%256)/255.f;
+ const float damping=(std::min)(WaterSurfaceModel::ShoreDamping(depth),obstacle);
+ const float add=Height(broad,depth,float((i*13)%31)/30,float((i*29)%11)/10,EncodeObstacle(obstacle),damping);
+ const float old=wave.height*damping,next=old+add;
+ CHECK(std::isfinite(add)&&add>=0);CHECK(next>=old);
+ CHECK(add<=(std::max)(0.f,obstacle-damping)*(std::max)(0.f,broad)+.000002f);
+ CHECK(std::abs(next)<=WaterSurfaceModel::LegacyMaxDisplacement+.00001f);
+ CHECK(next>=-depth-.00001f); // Original conservative vertex floor still holds.
+ largest=(std::max)(largest,add);nonzero+=add>.01f;
+ }
+ CHECK(nonzero>1000&&largest>.3f);
+ // Actual existing convex morph/collar algebra: added vertices cannot lower interpolated
+ // triangles, shared edge morphs or centre transitions. No topology/XY changes are proposed.
+ const double old[3]={-1.1,.8,-.4},added[3]={.7,.02,1.3};
+ for(unsigned i=0;i<=20;++i)for(unsigned j=0;j<=20-i;++j) {
+ WaterProjectedMesh::CentreTransition t={};t.weight[0]=i/20.;t.weight[1]=j/20.;t.weight[2]=1-t.weight[0]-t.weight[1];t.analytic=.35;
+ const double next[3]={old[0]+added[0],old[1]+added[1],old[2]+added[2]};
+ CHECK(WaterProjectedMesh::InterpolateCentre(t,.9,next)>=WaterProjectedMesh::InterpolateCentre(t,-.2,old));
+ for(unsigned k=0;k<=10;++k)CHECK(WaterSurfaceModel::MorphCoordinate(float(old[0]+added[0]),float(next[1]),float(next[2]),k/10.f)
+ >=WaterSurfaceModel::MorphCoordinate(float(old[0]),float(old[1]),float(old[2]),k/10.f));
+ }
+ std::printf("coastal crest20000 bound/floor cases; active%u max added %.7g within original bound %.7g\n",nonzero,largest,WaterSurfaceModel::LegacyMaxDisplacement);
+}
+TEST(water_coastal_crest_uses_existing_phase_freezes_and_reports_positive_mean)
+{
+ using namespace WaterCoastalCrest;double sum=0;unsigned zero=0,active=0;float peak=0;
+ for(unsigned i=0;i<1920;++i) {
+ const float t=i/30.f;const float h=WaterShoreFoam::Evaluate(1150,352,t).height;
+ const float add=Height(h,2,1,1,EncodeObstacle(1),WaterSurfaceModel::ShoreDamping(2));
+ CHECK(add==Height(WaterShoreFoam::Evaluate(1150,352,WaterSurfaceModel::AdvanceTime(t,.1f,true,false,false)).height,
+ 2,1,1,EncodeObstacle(1),WaterSurfaceModel::ShoreDamping(2)));
+ sum+=add;peak=(std::max)(peak,add);zero+=add==0;active+=add>.1f;
+ }
+ CHECK(zero>400&&active>200);CHECK(sum/1920>.02&&sum/1920<1.0);CHECK(peak>0.5f);
+ std::printf("coastal crest64s phase sweep: nonzero DC %.7g world, peak %.7g, zero frames%u/1920; NOT a zero-mean fluid solver\n",sum/1920,peak,zero);
+}
+
+TEST(water_bow_shoulder_large_hull_scale_cap_support_and_small_boat_identity)
+{
+ namespace S=WaterBowShoulder;namespace T=WaterBowShoulderTest;
+ // The native carrier half-beam is about54; the PT remains below the old cap.
+ // Assert the intended dimensions independently so a stale6-world cap fails.
+ for(double beam:{9.,16.,27.,54.,120.})for(double speed:{1.,25.,40.,-40.}) {
+ const auto h=T::scaledHull(280,beam,speed);const auto c=T::contour(h);
+ CHECK_NEAR(c.width,(std::max)(3.,(std::min)(12.,beam*double(.45f))),.000001);
+ CHECK(c.length<=32 && c.width<=12 && c.reach==h.data[2][3]+110);
+ const double sign=speed>0?1:-1;
+ const auto crest=S::ToWorld(c,{sign*(280+.5*c.width),0});
+ CHECK_NEAR(S::Evaluate(c,crest).value,c.amplitude,.000001);
+ CHECK_NEAR(c.amplitude,WaterVesselWaves::BowPressure(float(beam),float(std::abs(speed))).amplitude,.000001);
+ CHECK(S::Evaluate(c,S::ToWorld(c,{sign*(280+3.5*c.width),0})).value==0);
+ // Entire compact support lies within hull radius+42, inside the inherited
+ // radius+80 start of attenuation and+110 finite collection support.
+ CHECK(3.5*c.width+WaterFftGeometry::MaxHorizontalDisplacement<=50);
+ for(double distance:{.31,3.17,6.23,12.37,20.41,34.29,42.13}) {
+ const auto p=S::ToWorld(c,{sign*(280+distance),.271});const auto f=S::Evaluate(c,p);
+ CHECK_NEAR(f.value,T::oracle(h,p.x,p.y),.000003);
+ const double e=.0001;
+ CHECK_NEAR(f.dx,(T::oracle(h,p.x+e,p.y)-T::oracle(h,p.x-e,p.y))/(2*e),.00003);
+ CHECK_NEAR(f.dy,(T::oracle(h,p.x,p.y+e)-T::oracle(h,p.x,p.y-e))/(2*e),.00003);
+ CHECK(f.value>=0 && f.value<=c.amplitude+.000001);
+ const auto q=S::QueryLocal(c,S::ToLocal(c,p));
+ for(unsigned k=0;k<16;++k) {
+ const double a=k*.39269908169872415;
+ const auto lower=S::InverseProfileLowerBounds(c,{p.x+8*std::cos(a),p.y+8*std::sin(a)},8);
+ CHECK(lower.x<=std::abs((q.distance-.5*c.width)/c.width)+.000002);
+ CHECK(lower.y<=q.retreat/c.length+.000002);
+ }
+ }
+ }
+ const auto large=T::scaledHull(280,54);const auto c=T::contour(large);
+ const auto outside=S::ToWorld(c,{292,0});
+ CHECK(S::Evaluate(c,outside).value-T::oracle(large,outside.x,outside.y,6)>3);
+ WaterBowRefinement::Bow bow;CHECK(WaterBowRefinement::MakeBow(7,large,large,4,bow,true));
+ CHECK(bow.sigmaAlong==12 && bow.sigmaAcross==12 && bow.contour.length==32);
+ CHECK(WaterBowRefinement::MaxRegions==3 && WaterBowRefinement::WindowRadius==6);
+ CHECK(WaterBowRefinement::MaxAddedVertices==8190 && WaterBowRefinement::MaxAddedTriangles==16380);
+ // Small captured PT bodies, including reverse/rotation in the prior test, must
+ // retain the exact old6-cap scalar. No tolerance can hide a changed footprint.
+ for(unsigned pose=0;pose<3;++pose) {
+ const auto h=T::CapturedHull(pose);const auto small=T::contour(h);CHECK(small.width<6);
+ for(double x:{-45.31,20.31,38.17,43.13,46.21})for(double y:{-11.13,-2.17,6.19,10.23}) {
+ const auto p=S::ToWorld(small,{x,y});
+ CHECK(T::oracle(h,p.x,p.y)==T::oracle(h,p.x,p.y,6));
+ }
+ }
+}
+
+
+#include "Platform/WaterCoastalSurf.h"
+
+namespace CoastalSurfTest {
+using namespace WaterCoastalSurf;
+inline Context Coast(){return {4,64,-1,0,1,.4f,.4f,.5f,1,1};}
+inline Field Travelling(double x,double time){const double k=6.283185307179586/64,q=k*x-time;
+ return {float(2*std::sin(q)),float(2*k*std::cos(q)),0,float(1-.20*std::sin(q))};}
+inline double Simp(double duration,double lifetime,double rate0,double rate1,unsigned power){
+ constexpr unsigned n=10000;double sum=0;
+ for(unsigned i=0;i<=n;++i){const double age=duration*i/n;
+ const double value=std::pow(age,int(power))*std::exp(-age/lifetime)*(rate1+(rate0-rate1)*age/duration);
+ sum+=(i==0||i==n?1:i%2?4:2)*value;}
+ return sum*duration/(3*n);
+}
+inline State Schedule(const std::vector<double>&steps,double end){
+ Clock clock;State state;double time=0;auto p=clock.Inspect(7,0);CHECK(clock.Commit(7,p));
+ state.height=Travelling(5,0).height;state.rate=0;
+ for(unsigned i=0;time<end;++i){time=(std::min)(end,time+steps[i%steps.size()]);p=clock.Inspect(7,time);
+ if(p.action==Action::Sample||p.action==Action::GapDecay)
+ state=Advance(Coast(),Travelling(5,time),state,p.elapsed,p.action==Action::Sample);
+ CHECK(clock.Commit(7,p));}
+ return state;
+}
+}
+
+TEST(water_coastal_surf_front_propagates_from_actual_phase_and_leaves_remnants)
+{
+ using namespace CoastalSurfTest;
+ auto peak=[](double time){float maximum=0;double result=0;
+ for(unsigned i=0;i<=256;++i){double x=-32+i*.25;Field f=Travelling(x,time);State old;
+ old.height=Travelling(x,time-.1).height;old.rate=0;
+ const float rate=Rate(Coast(),f,old,.1);if(rate>maximum){maximum=rate;result=x;}}
+ CHECK(maximum>.25f);return result;};
+ const double a=peak(0),b=peak(.5);
+ CHECK(std::abs((b-a)-32/6.283185307179586)<.5); // independently known phase speed, +X
+ auto c=Coast();c.outwardX=1;State old;old.height=Travelling(20,-.1).height;old.rate=0;
+ CHECK(Rate(c,Travelling(20,0),old,.1)==0); // opposite coast sees an outgoing front
+ State state;state.height=Travelling(0,0).height;state.rate=0;
+ float maximum=0;
+ for(unsigned i=1;i<=48;++i){state=Advance(Coast(),Travelling(0,i*.1),state,.1);maximum=(std::max)(maximum,state.rate);}
+ CHECK(maximum>.25f && state.density>.15f);
+ const State fresh=state;CHECK(Coverage(fresh,.25f)>0);
+ for(unsigned i=0;i<30;++i)state=Advance(Coast(),Travelling(0,4.8+(i+1)*.1),state,.1,false);
+ CHECK(state.density>0 && state.density<fresh.density);
+ CHECK(state.ageMoment/state.density>fresh.ageMoment/fresh.density+2.9f);
+ CHECK(Coverage(state,.25f)<Coverage(state,1)); // age produces porosity, not only fading
+ for(unsigned i=0;i<150;++i)state=Advance(Coast(),Travelling(0,8+i*.1),state,.1,false);
+ CHECK(Coverage(state,.25f)==0);
+}
+
+TEST(water_coastal_surf_linear_rate_integration_has_independent_density_and_age_oracles)
+{
+ using namespace CoastalSurfTest;
+ for(double dt:{.0001,.025,.1,.25})for(float first:{0.f,.4f,1.2f})for(float last:{0.f,.7f,1.2f}){
+ State old{.7f,1.3f,1,first};State result=Integrate(old,2,last,dt,true);
+ const double q=std::exp(-dt/5);
+ const double density=q*.7+Simp(dt,5,first,last,0);
+ const double age=q*(1.3+dt*.7)+Simp(dt,5,first,last,1);
+ CHECK(std::abs(result.density-density)<.000001);
+ CHECK(std::abs(result.ageMoment-age)<.000001);
+ CHECK(result.height==2 && result.rate==last);
+ }
+ State old{.5f,.8f,1,.9f};const State paused=Integrate(old,12,1.2,0,true);
+ CHECK(paused.density==old.density && paused.ageMoment==old.ageMoment && paused.height==old.height && paused.rate==old.rate);
+ const State gap=Integrate(old,2,1.2,4,false);
+ CHECK(std::abs(gap.density-.5*std::exp(-.8))<.000001 && gap.rate==0);
+ CHECK(std::abs(gap.ageMoment-(.8+2)*std::exp(-.8))<.000001);
+ CHECK(Integrate(old,2,1.2,100000,false).density==0);
+}
+
+TEST(water_coastal_surf_schedule_error_is_bounded_and_not_render_count_driven)
+{
+ using namespace CoastalSurfTest;
+ const State at30=Schedule({1./30},30),at120=Schedule({1./120},30);
+ const State jitter=Schedule({.012,.047,.021,.035},30);
+ CHECK(at30.density>.03f && at30.ageMoment>.03f);
+ CHECK(std::abs(at30.density-at120.density)<.0005f);
+ CHECK(std::abs(at30.ageMoment-at120.ageMoment)<.002f);
+ // The source uses real current FFT samples, not extra transforms at every ideal tick.
+ // Jitter may therefore change sample phase; this is an explicit error bound, not identity.
+ CHECK(std::abs(at30.density-jitter.density)<.05f*(std::max)(at30.density,.1f));
+ CHECK(std::abs(at30.ageMoment-jitter.ageMoment)<.06f*(std::max)(at30.ageMoment,.1f));
+ Clock clock;auto p=clock.Inspect(11,2);CHECK(p.action==Action::Reset && clock.Commit(11,p));
+ p=clock.Inspect(11,2);CHECK(p.action==Action::None && clock.Commit(11,p));
+ p=clock.Inspect(11,2.05);CHECK(p.action==Action::None && clock.Commit(11,p));
+ p=clock.Inspect(11,2.1);CHECK(p.action==Action::Sample && clock.Commit(11,p));
+ const double sampled=clock.SampledTime();CHECK(clock.Inspect(11,2.1).action==Action::None);
+ CHECK(clock.SampledTime()==sampled); // inspecting an unsubmitted GPU plan cannot advance state
+ p=clock.Inspect(11,5);CHECK(p.action==Action::GapDecay && clock.Commit(11,p));
+ CHECK(clock.Inspect(11,4.9).action==Action::Reset); // rollback clears source derivative history
+ CHECK(clock.Inspect(12,5).action==Action::Reset); // map/terrain/polygon revision, even same dimensions
+ CHECK(clock.Inspect(0,5).action==Action::Invalid);
+ CHECK(clock.Inspect(11,std::numeric_limits<double>::infinity()).action==Action::Invalid);
+ p=clock.Inspect(11,5.1);p.elapsed=.01;CHECK(!clock.Commit(11,p));
+}
+
+TEST(water_coastal_surf_distinct_domain_keeps_broad_wet_support_and_excludes_dry_pools)
+{
+ using namespace CoastalSurfTest;
+ Context c=Coast();Field f{2,-.25f,0,.7f};State old{.7f,.1f,1.9f,0};
+ CHECK(c.distance>20 && c.offshore>0 && Domain(c)>0 && Rate(c,f,old,.1)>.1f);
+ Context q=c;q.wet=0;CHECK(Advance(q,f,old,.1).density==0);
+ q=c;q.depth=.15f;CHECK(Rate(q,f,old,.1)==0 && Advance(q,f,old,.1).density==0);
+ q=c;q.exposure=0;CHECK(Advance(q,f,old,.1).density==0);
+ q=c;q.admitted=0;CHECK(Advance(q,f,old,.1).density==0);
+ q=c;q.distance=128;CHECK(Rate(q,f,old,.1)==0);
+ // Wet spread margin can retain old foam after leaving source support; it cannot emit.
+ const State margin=Advance(q,f,old,.1);CHECK(margin.density>0 && margin.density<old.density);
+ q=c;q.depth=12;CHECK(Rate(q,f,old,.1)==0);
+ q=c;q.depth=std::numeric_limits<float>::quiet_NaN();CHECK(Rate(q,f,old,.1)==0);
+ Field still=f;old.height=f.height;CHECK(Rate(c,still,old,.1)==0);
+ Field falling=f;falling.height=old.height-.1f;CHECK(Rate(c,falling,old,.1)==0);
+ Field trough=f;trough.height=-1;CHECK(Rate(c,trough,old,.1)==0);
+ q=c;q.analyticDamping=q.spectralDamping=1;old.height=1.9f;CHECK(Rate(q,f,old,.1)==0);
+ q=c;q.offshore=0;
+ Context offshore=q;offshore.offshore=1;
+ CHECK(Rate(q,f,old,.1)==Rate(offshore,f,old,.1)); // Optical R cannot select the phase field's damping.
+ q.analyticDamping=0;q.spectralDamping=1;
+ CHECK(Rate(q,f,old,.1)==0); // B1/R0 uses the same spectral damping as open water.
+ Field analytic{1,.3f,-.2f,1},spectral{3,-.2f,.1f,.6f};
+ Field mixed=Blend(analytic,spectral,.25f);CHECK(mixed.height==1.5f);
+ CHECK(std::abs(mixed.dx-.175f)<.000001f && std::abs(mixed.compression-.9f)<.000001f);
+}
+
+TEST(water_coastal_surf_wet_graph_diffusion_and_lookup_do_not_cross_levels_or_renormalize_gaps)
+{
+ using namespace CoastalSurfTest;
+ std::vector<Node> nodes(3);for(auto &n:nodes)n.context=Coast();
+ nodes[0].world[2]=nodes[1].world[2]=7;nodes[1].world[0]=5;
+ nodes[2].world[2]=11;nodes[0].neighbour[1]=2;nodes[1].neighbour[0]=1;
+ CHECK(ValidGraph(nodes,5));nodes[1].neighbour[1]=3;CHECK(!ValidGraph(nodes,5));nodes[1].neighbour[1]=0;
+ nodes[1].world[2]=11;CHECK(!ValidGraph(nodes,5));nodes[1].world[2]=7;
+ nodes[1].context.wet=0;CHECK(!ValidGraph(nodes,5));nodes[1].context=Coast();
+ nodes[1].context.admitted=0;CHECK(!ValidGraph(nodes,5));nodes[1].context=Coast();
+ nodes[1].context.exposure=0;CHECK(!ValidGraph(nodes,5));nodes[1].context=Coast();
+ nodes[1].context.depth=.15f;CHECK(!ValidGraph(nodes,5));nodes[1].context=Coast();
+ nodes[1].context.distance=144;nodes[1].context.depth=14;
+ CHECK(Domain(nodes[1].context)==0 && ValidGraph(nodes,5)); // valid wet spreading margin
+ State a{1,2,1,0},b{0,0,2,0};std::array<State,4> na{},nb{};na[1]=b;nb[0]=a;
+ const State da=Diffuse(a,na,2,5,.1),db=Diffuse(b,nb,1,5,.1);
+ CHECK(da.density<1 && db.density>0 && std::abs(da.density+db.density-1)<.000001);
+ CHECK(std::abs(da.ageMoment+db.ageMoment-2)<.000001 && da.height==a.height && db.height==b.height);
+ Lookup lookup{{1,2,0,0},{.25f,.25f,0,0}};CHECK(ValidLookup(lookup,3));
+ CHECK(lookup.weight[0]+lookup.weight[1]==.5f); // missing dry half remains missing
+ lookup.weight[2]=.1f;CHECK(!ValidLookup(lookup,3));lookup.weight[2]=0;
+ lookup.node[0]=4;CHECK(!ValidLookup(lookup,3));
+ CHECK(!ValidGraph(std::vector<Node>(MaxNodes+1),5));
+}
+
+TEST(water_coastal_surf_rejects_overflow_inputs_and_preserves_tiny_step_finiteness)
+{
+ using namespace CoastalSurfTest;
+ State old{.7f,.1f,1.9f,0};Field f{2,-.25f,0,.7f};Context c=Coast();
+ c.outwardX=std::numeric_limits<float>::max();CHECK(Rate(c,f,old,.1)==0);
+ c=Coast();f.dx=std::numeric_limits<float>::max();CHECK(Rate(c,f,old,.1)==0);
+ f={2,-.25f,0,.7f};c.spectralDamping=std::numeric_limits<float>::max();CHECK(Rate(c,f,old,.1)==0);
+ for(double dt:{1e-40,1e-30,1e-12,1e-8}){
+ const State state=Integrate(old,2,.8f,dt,true);CHECK(Finite(state));
+ CHECK(std::abs(state.density-old.density)<.000001 && std::abs(state.ageMoment-old.ageMoment)<.000001);
+ }
+ std::vector<Node> duplicate(2);for(auto &n:duplicate){n.context=Coast();n.world[2]=7;}
+ CHECK(!ValidGraph(duplicate,5));
+ Lookup lookup;CHECK(!ValidLookup(lookup,MaxNodes+1));
+ // R varies between constant endpoints: its static transition is not wave steepness.
+ const Field a{1,0,0,1},b{2,0,0,1};const Field mixed=Blend(a,b,.5f);
+ c=Coast();old.height=1.4f;CHECK(mixed.dx==0 && mixed.dy==0 && Rate(c,mixed,old,.1)==0);
+}
+
+#include "WaterWaveCageTest.h"
+TEST(water_wave_cage_phase_terrain_bounds_classification_and_constrained_smoothing)
+{
+ WaterWaveCageTest::Check();
+}
+
+#include "WaterTerrainCullingTest.h"
+TEST(water_terrain_culling_preserves_wet_interiors_displacement_and_mesh_metadata)
+{
+ WaterTerrainCullingTest::Check();
+}
+
+#include "WaterCoastalDomainTest.h"
+TEST(water_coastal_domain_connected_wet_geometry_limits_and_atomic_refresh)
+{
+ WaterCoastalDomainTest::Check();
+}
+
+#include "WaterCoastalViewTest.h"
+TEST(water_coastal_view_centres_support_levels_limits_and_atomic_refresh)
+{
+ WaterCoastalViewTest::Check();
+}
+
+#include "Platform/WaterCoastalPresentation.h"
+
+TEST(water_coastal_presentation_advances_age_and_density_without_new_births)
+{
+ using namespace WaterCoastalPresentation;
+ const Moments same=AtTime(2,3,0),later=AtTime(2,3,2.5f);
+ CHECK(same.density==2&&same.age==1.5f);
+ CHECK(std::abs(later.density-2*std::exp(-.5))<.000001&&later.age==4);
+ const Moments split=AtTime(later.density,later.density*later.age,1.5f),one=AtTime(2,3,4);
+ CHECK(std::abs(split.density-one.density)<.000001&&std::abs(split.age-one.age)<.000001);
+ CHECK(AtTime(0,0,0).density==0&&AtTime(2,3,-1).density==0);
+ CHECK(AtTime(2,3,14).density==0&&AtTime(1,14,0).density==0);
+ CHECK(AtTime(std::numeric_limits<float>::quiet_NaN(),0,0).density==0);
+ CHECK(AtTime(1,std::numeric_limits<float>::infinity(),0).density==0);
+}
+
+TEST(water_coastal_presentation_accepts_r0_but_rejects_unsupported_geometry)
+{
+ using namespace WaterCoastalPresentation;
+ CHECK(ModelGate(0,0,0,0,0)==1&&ModelGate(1,1,0,0,0)==1);
+ CHECK(ModelGate(.4f,.4f,0,0,0)==1);
+ CHECK(ModelGate(0,.4f,0,0,0)==0); // camera/authored-edge FFT fade
+ CHECK(ModelGate(.4f,.4f,.5f,0,0)==0); // boundary/centre height correction
+ CHECK(ModelGate(.4f,.4f,0,.1f,0)==0); // zero height with a nonzero correction slope
+ CHECK(ModelGate(.4f,.42f,0,0,0)>0&&ModelGate(.4f,.42f,0,0,0)<1);
+ CHECK(ModelGate(std::numeric_limits<float>::quiet_NaN(),0,0,0,0)==0);
+}
+
+#include "WaterCoastalFootprintTest.h"
+TEST(water_coastal_view_full_filter_footprint_blocks_subtexel_gaps)
+{
+ WaterCoastalFootprintTest::Check();
+}
+
+#include "WaterCoastalCapacityTest.h"
+TEST(water_coastal_domain_stride_two_capacity_preserves_fine_connectivity_and_terrain)
+{
+ WaterCoastalCapacityTest::Check();
+}
+
+#if defined(__linux__)
+#include "W3DDevice/GameClient/W3DWater.h"
+#include "GameClient/Water.h"
+#include "../GameEngineDevice/Source/PosixDevice/Render/PosixDevice9.h"
+#include "../Libraries/Source/WWVegas/WW3D2/engineshader.h"
+
+namespace {
+struct WaterShaderNameProbe : PosixDevice9 { using PosixDevice9::Engine_Name_Of; };
+class LiveWaterStyleProbe : public WaterRenderObjClass
+{
+public:
+ void prepareShaders(IDirect3DDevice9 *device) {
+ const RenderUInt32 tokens[]={0xffff0101u,0x0000ffffu};
+ CHECK(device->CreatePixelShader(tokens,&m_riverWaterPixelShader)==D3D_OK);
+ CHECK(device->CreatePixelShader(tokens,&m_trapezoidWaterPixelShader)==D3D_OK);
+ registerWaterStyleShaders();
+ m_modernWaveTime=37.5f;
+ m_level=7;m_drawnMotionEnabled=TRUE;
+ }
+ void seedPresentation() {
+ m_modernHulls.resize(1);m_modernContactHulls.resize(1);m_modernVisualHulls.resize(1);
+ m_modernHullObjectIDs.push_back(42);m_modernFoamDrawObjectIDs.push_back(42);
+ m_modernFoamDrawFrame=123;m_modernShoreReady=m_modernCoastalReady=m_modernCoastalViewReady=TRUE;
+ m_modernCoastalRevision=42;m_modernProfile.frames=17;m_reflectionReused=FALSE;
+ }
+ void checkChanged(bool modern) {
+ CHECK_EQ(bool(m_useModernWater),modern);
+ CHECK(m_modernHulls.empty() && m_modernContactHulls.empty() && m_modernVisualHulls.empty());
+ CHECK(m_modernHullObjectIDs.empty() && m_modernFoamDrawObjectIDs.empty());
+ CHECK(!m_modernShoreReady && !m_modernCoastalReady && !m_modernCoastalViewReady);
+ CHECK(m_modernCoastalRevision==0 && m_modernProfile.frames==0);
+ CHECK(m_reflectionReused); // force the new clear colour even with a stationary camera
+ CHECK_EQ(m_modernWaveTime,37.5f);CHECK_EQ(m_level,7);CHECK(m_drawnMotionEnabled);
+ const auto river=EngineShader_From_File(WaterShaderNameProbe::Engine_Name_Of(m_riverWaterPixelShader).c_str());
+ const auto flat=EngineShader_From_File(WaterShaderNameProbe::Engine_Name_Of(m_trapezoidWaterPixelShader).c_str());
+ CHECK(river==(modern?ENGINE_SHADER_WATER_RIVER:ENGINE_SHADER_WATER_CLASSIC_RIVER));
+ CHECK(flat==(modern?ENGINE_SHADER_WATER_TRAPEZOID:ENGINE_SHADER_WATER_CLASSIC_TRAPEZOID));
+ }
+ void checkUnchanged() {
+ CHECK(!m_modernHulls.empty() && !m_modernFoamDrawObjectIDs.empty());
+ CHECK(m_modernShoreReady && m_modernCoastalRevision==42 && m_modernProfile.frames==17);
+ CHECK(!m_reflectionReused); // no per-frame history reset or forced mirror refresh
+ }
+};
+}
+
+TEST(water_style_changes_at_render_boundary_without_advancing_paused_time_or_reloading_the_map)
+{
+ GlobalData *saved=TheWritableGlobalData;
+ GlobalData *scratch=NEW GlobalData;TheWritableGlobalData=scratch;
+ WaterTransparencySetting *savedTransparency=(WaterTransparencySetting*)TheWaterTransparency.getNonOverloadedPointer();
+ TheWaterTransparency=newInstance(WaterTransparencySetting);
+ IDirect3D9 *d3d=Direct3DCreate9(D3D_SDK_VERSION);
+ D3DPRESENT_PARAMETERS parameters={};parameters.BackBufferWidth=16;parameters.BackBufferHeight=16;
+ parameters.BackBufferFormat=D3DFMT_X8R8G8B8;parameters.Windowed=TRUE;
+ IDirect3DDevice9 *device=NULL;
+ CHECK(d3d && d3d->CreateDevice(0,D3DDEVTYPE_HAL,NULL,0,&parameters,&device)==D3D_OK);
+ if (device) {
+ {
+ LiveWaterStyleProbe water;water.prepareShaders(device);
+ for (unsigned i=0;i<32;++i) {
+ const bool modern=(i&1)!=0;
+ water.seedPresentation();scratch->m_waterStyle=modern?1:0;
+ // No camera/map/device rendering: this is the real pre-mirror boundary,
+ // which must apply an accepted option even while simulation time is paused.
+ water.updateRenderTargetTextures(NULL);water.checkChanged(modern);
+ water.seedPresentation();water.updateRenderTargetTextures(NULL);water.checkUnchanged();
+ }
+ }
+ device->Release();
+ } else {
+ ((WaterTransparencySetting*)TheWaterTransparency.getNonOverloadedPointer())->deleteInstance();
+ TheWaterTransparency=NULL;
+ }
+ if (d3d) d3d->Release();
+ TheWaterTransparency=savedTransparency;
+ delete scratch;TheWritableGlobalData=saved;
+}
+#endif
diff --git a/GeneralsMD/Code/Tests/test_water_preview_preset.cpp b/GeneralsMD/Code/Tests/test_water_preview_preset.cpp
new file mode 100644
index 000000000..824275ae0
--- /dev/null
+++ b/GeneralsMD/Code/Tests/test_water_preview_preset.cpp
@@ -0,0 +1,52 @@
+#include "test_harness.h"
+#include "WaterPreviewPreset.h"
+
+#include <filesystem>
+#include <fstream>
+#include <sstream>
+#include <cstdlib>
+
+TEST(water_preview_presets_reject_partial_and_trailing_edits_atomically)
+{
+ const char *invalid[] = {
+ "WATER_PREVIEW_COLOR_V1 0.2 0.3 0.4 0.67",
+ "WATER_PREVIEW_COLOR_V1 0.2 0.3 0.4 0.67 0.8 extra",
+ "WATER_PREVIEW_COLOR_V1 0.2 0.3 0.4 0.67 0.8\n0.9",
+ "WATER_PREVIEW_COLOR_V2 0.2 0.3 0.4 0.67 0.8",
+ "WATER_PREVIEW_COLOR_V1 0.2 0.3 0.4 0.01 0.8",
+ "WATER_PREVIEW_COLOR_V1 0.2 0.3 0.4 0.67 nan",
+ };
+ for (const char *text : invalid) {
+ WaterPreviewColor::Values values;
+ values.red = 0.75f;
+ std::istringstream input(text);
+ CHECK(!WaterPreviewColor::readPreset(input, values));
+ CHECK_EQ(values.red, 0.75f);
+ CHECK_EQ(values.strength, 0.f);
+ }
+ WaterPreviewColor::Values values;
+ std::istringstream input("WATER_PREVIEW_COLOR_V1\n0.2 0.3 0.4 0.67 0.8\n \t");
+ CHECK(WaterPreviewColor::readPreset(input, values));
+ CHECK_NEAR(values.red, 0.2f, 0.000001f);
+ CHECK_NEAR(values.brightness, 0.67f, 0.000001f);
+ CHECK_NEAR(values.strength, 0.8f, 0.000001f);
+}
+
+TEST(water_preview_default_export_preserves_loaded_rules_and_aliases)
+{
+ namespace fs = std::filesystem;
+ char pattern[] = "water-preview-preset-XXXXXX";
+ const char *directory = mkdtemp(pattern);
+ CHECK(directory != nullptr);
+ if (!directory) return;
+ const fs::path root(directory);
+ const fs::path input = root / "water-preview-rule.ini";
+ std::ofstream(input) << "; authored rules\n";
+ const fs::path alias = root / "alias.ini";
+ fs::create_hard_link(input, alias);
+ CHECK(WaterPreviewColor::defaultExportOverwritesInput(input, input));
+ CHECK(WaterPreviewColor::defaultExportOverwritesInput(input, alias));
+ CHECK(!WaterPreviewColor::defaultExportOverwritesInput(input, root / "export.ini"));
+ CHECK(!WaterPreviewColor::defaultExportOverwritesInput({}, input));
+ fs::remove_all(root);
+}
diff --git a/GeneralsMD/Code/Tests/test_water_tracks.cpp b/GeneralsMD/Code/Tests/test_water_tracks.cpp
index 0f1804515..2eb400dad 100644
--- a/GeneralsMD/Code/Tests/test_water_tracks.cpp
+++ b/GeneralsMD/Code/Tests/test_water_tracks.cpp
@@ -61,3 +61,62 @@ TEST(wak_track_count_never_passes_what_the_file_holds)
CHECK_EQ(wakTrackCount(0, 1), 0);
CHECK_EQ(wakTrackCount(-1, 1), 0);
}
+
+#include "Platform/WaterShoreOverlay.h"
+#include <limits>
+
+TEST(shore_overlay_accepts_whole_same_level_convex_coverage_both_windings)
+{
+ using namespace WaterShoreOverlay;
+ Quad patch={{0,0,100,0,100,100,0,100},7},track={{10,20,60,20,60,70,10,70},7};
+ CHECK(Contains(patch,track));
+ for(unsigned i=0;i<4;++i) {std::swap(patch.xy[0],patch.xy[4]);std::swap(patch.xy[1],patch.xy[5]);CHECK(Contains(patch,track));}
+ Quad crossing=track;crossing.xy[0]=-1;CHECK(!Contains(patch,crossing));
+ Quad other=track;other.level=7.1f;CHECK(!Contains(patch,other));
+ other=track;other.xy[0]=std::numeric_limits<float>::quiet_NaN();CHECK(!Contains(patch,other));
+ other=track;other.xy[4]=other.xy[2];other.xy[5]=other.xy[3];CHECK(!Contains(patch,other));
+ Quad concave={{0,0,100,0,25,25,0,100},7};CHECK(!Contains(concave,track));
+ // Real fallback: a surf quad crossing two adjacent supported patches cannot be
+ // incorrectly admitted by either patch independently.
+ Quad right={{100,0,200,0,200,100,100,100},7};track={{90,20,110,20,110,70,90,70},7};
+ CHECK(!Contains(patch,track)&&!Contains(right,track));
+}
+
+TEST(shore_overlay_requires_same_live_capture_view_target_and_size)
+{
+ using namespace WaterShoreOverlay;
+ View a;a.colour=1;a.depth=2;a.capture=3;a.width=1280;a.height=720;
+ a.viewport[2]=1280;a.viewport[3]=720;
+ for(unsigned i=0;i<4;++i)a.worldFromClip[i*5]=1;
+ CHECK(SameView(a,a));
+ View b=a;b.capture=4;CHECK(!SameView(a,b)); // same textures recaptured after clear/frame
+ b=a;b.capture=0;CHECK(!SameView(a,b));
+ b=a;b.colour=3;CHECK(!SameView(a,b)); // intermediate colour target
+ b=a;b.depth=3;CHECK(!SameView(a,b));
+ b=a;b.width=1920;CHECK(!SameView(a,b));
+ b=a;b.viewport[0]=.5f;CHECK(!SameView(a,b));
+ b=a;b.worldFromClip[12]=1;CHECK(!SameView(a,b)); // changed camera
+ b=a;b.worldFromClip[0]=std::numeric_limits<float>::quiet_NaN();CHECK(!SameView(b,b));
+}
+
+TEST(shore_overlay_removes_valid_dry_strand_but_not_missing_depth_or_objects)
+{
+ using WaterShoreOverlay::Replacement;
+ CHECK(Replacement(1,.25f,0,1,0)==1); // wet terrain
+ CHECK(Replacement(1,.75f,0,1,0)==1); // dry terrain: no wetness test on removal
+ CHECK(Replacement(1,0,0,1,0)==1); // a real near-plane hit is valid
+ CHECK(Replacement(1,.75f,0,.25f,0)==1);
+ CHECK(Replacement(1,.75f,0,1,1)==.5f);
+ CHECK(Replacement(1,.75f,0,1,2)==0); // object well above terrain
+ CHECK(Replacement(0,.25f,0,1,0)==0);
+ CHECK(Replacement(.5f,.25f,0,1,0)==0);
+ for(float depth:{-1.f,.999999f,1.f,std::numeric_limits<float>::quiet_NaN(),std::numeric_limits<float>::infinity()})
+ CHECK(Replacement(1,depth,0,1,0)==0);
+ // Replacement ownership comes from the accepted modern patch, independently
+ // of narrow fresh-source support or analytic/FFT wave weighting.
+ for(float offshore:{0.f,.0001f,.5f,1.f})for(float support:{0.f,.25f,1.f})
+ CHECK(Replacement(1,.25f,offshore,support,0)==1);
+ CHECK(Replacement(1,.25f,NAN,1,0)==0);
+ CHECK(Replacement(1,.25f,0,NAN,0)==0);
+ // This decision has no wave-rate input: a supported trough must not keep an old permanent rim.
+}
diff --git a/GeneralsMD/Code/Tools/WaterPreviewColorPanel.h b/GeneralsMD/Code/Tools/WaterPreviewColorPanel.h
new file mode 100644
index 000000000..193f3e934
--- /dev/null
+++ b/GeneralsMD/Code/Tools/WaterPreviewColorPanel.h
@@ -0,0 +1,269 @@
+// Small, dependency-free color editor for the standalone water preview.
+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.
+#pragma once
+
+#include "PosixDevice9.h"
+#include "WaterPreviewPreset.h"
+#include <SDL3/SDL.h>
+#include <algorithm>
+#include <array>
+#include <cmath>
+#include <cstdint>
+#include <cstdio>
+#include <string>
+#include <vector>
+
+namespace WaterPreviewColor {
+
+class Panel {
+public:
+ Values values;
+ Values defaults;
+ bool visible = true;
+ bool saveRequested = false;
+ std::string status = "DRAG SLIDERS TO CHANGE WATER";
+
+ bool handle(const SDL_Event &event)
+ {
+ if (event.type == SDL_EVENT_KEY_DOWN && event.key.key == SDLK_H) {
+ if (!event.key.repeat) {
+ visible = !visible;
+ activeSlider = -1;
+ }
+ return true;
+ }
+ if (event.type == SDL_EVENT_WINDOW_FOCUS_LOST) activeSlider = -1;
+ if (!visible) return false;
+ if (event.type == SDL_EVENT_MOUSE_MOTION) {
+ mouseX = event.motion.x / scale;
+ mouseY = event.motion.y / scale;
+ if (activeSlider >= 0) {
+ updateSlider(activeSlider, mouseX);
+ return true;
+ }
+ return inside(mouseX, mouseY);
+ }
+ if (event.type == SDL_EVENT_MOUSE_BUTTON_DOWN || event.type == SDL_EVENT_MOUSE_BUTTON_UP) {
+ mouseX = event.button.x / scale;
+ mouseY = event.button.y / scale;
+ if (event.type == SDL_EVENT_MOUSE_BUTTON_UP) {
+ const bool consumed = activeSlider >= 0 || inside(mouseX, mouseY);
+ if (event.button.button == SDL_BUTTON_LEFT) activeSlider = -1;
+ return consumed;
+ }
+ if (!inside(mouseX, mouseY)) return false;
+ if (event.button.button == SDL_BUTTON_LEFT) {
+ for (int row = 0; row < 5; ++row) {
+ if (mouseY >= trackY(row) - 12 && mouseY <= trackY(row) + 12 &&
+ mouseX >= Left + 12 && mouseX <= Left + Width - 12) {
+ activeSlider = row;
+ updateSlider(row, mouseX);
+ return true;
+ }
+ }
+ if (hit(mouseX, mouseY, Left + 16, Top + 351, 122, 34)) {
+ values = defaults;
+ status = "UNSAVED CHANGES";
+ } else if (hit(mouseX, mouseY, Left + 150, Top + 351, 122, 34)) {
+ saveRequested = true;
+ status = "SAVING COLOR...";
+ }
+ }
+ return true;
+ }
+ if (event.type == SDL_EVENT_MOUSE_WHEEL) {
+ mouseX = event.wheel.mouse_x / scale;
+ mouseY = event.wheel.mouse_y / scale;
+ return inside(mouseX, mouseY);
+ }
+ return false;
+ }
+
+ void draw(PosixDevice9 *device, unsigned width, unsigned height)
+ {
+ if (!visible || !device || !width || !height) return;
+ scale = std::min(1.f, std::min(float(width) / (Width + 32), float(height) / (Height + 32)));
+ vertices.clear();
+ vertices.reserve(16000);
+
+ rect(Left + 4, Top + 5, Width, Height, 0x60000000);
+ rect(Left, Top, Width, Height, 0xf51a2027);
+ rect(Left, Top, Width, 3, 0xff93bd75);
+ rect(Left, Top + Height - 1, Width, 1, 0xff3a4650);
+ text(Left + 16, Top + 16, "WATER PREVIEW", 2.f, 0xffeaf0e6);
+ text(Left + 16, Top + 39, "LIVE COLOR MODIFIER", 1.5f, 0xff9caeb9);
+
+ const unsigned r = byte(values.red), g = byte(values.green), b = byte(values.blue);
+ const uint32_t tint = 0xff000000u | (r << 16) | (g << 8) | b;
+ rect(Left + 16, Top + 59, 256, 36, 0xff66736b);
+ rect(Left + 17, Top + 60, 254, 34, tint);
+ const uint32_t swatchText = .2126f * r + .7152f * g + .0722f * b > 145 ? 0xff101710 : 0xfff8fff4;
+ text(Left + 26, Top + 72, "TINT", 1.5f, swatchText);
+ char hex[12];
+ std::snprintf(hex, sizeof(hex), "#%02X%02X%02X", r, g, b);
+ text(Left + 178, Top + 70, hex, 2.f, swatchText);
+
+ const char *labels[] = {"RED", "GREEN", "BLUE", "BRIGHTNESS", "POLLUTION"};
+ const uint32_t accents[] = {0xffe58484, 0xff91c788, 0xff83acdc, 0xffd0c78f, 0xffa2bf7c};
+ for (int row = 0; row < 5; ++row) {
+ const float labelY = Top + 111 + 45 * row;
+ const float value = component(row);
+ const float low = row == 3 ? .1f : 0.f;
+ const float fraction = clamp((value - low) / (1.f - low));
+ const float knobX = Left + 21 + fraction * 246;
+ char amount[16];
+ std::snprintf(amount, sizeof(amount), "%3d%%", int(std::lround(value * 100.f)));
+ text(Left + 16, labelY, labels[row], 1.5f, 0xffd8e1e5);
+ text(Left + 224, labelY, amount, 1.5f, accents[row]);
+ rect(Left + 21, trackY(row) - 3, 246, 6, 0xff3c4650);
+ rect(Left + 21, trackY(row) - 3, fraction * 246, 6, accents[row]);
+ if (activeSlider == row) rect(knobX - 7, trackY(row) - 10, 14, 20, 0x508cdcab);
+ rect(knobX - 4, trackY(row) - 8, 8, 16, 0xffedf3eb);
+ rect(knobX - 2, trackY(row) - 5, 4, 10, accents[row]);
+ }
+
+ button(Left + 16, Top + 351, "RESET COLOR", false);
+ button(Left + 150, Top + 351, "SAVE COLOR", true);
+ text(Left + 16, Top + 397, status.substr(0, 28).c_str(), 1.5f, 0xffa9b9a2);
+ text(Left + 16, Top + 420, "H PANEL L LOAD E EXPORT INI", 1.f, 0xff879ba8);
+
+ device->SetPixelShader(nullptr);
+ device->SetVertexShader(nullptr);
+ device->SetRenderState(D3DRS_LIGHTING, 0);
+ device->SetRenderState(D3DRS_FOGENABLE, 0);
+ device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
+ device->SetRenderState(D3DRS_ZENABLE, D3DZB_FALSE);
+ device->SetRenderState(D3DRS_ZWRITEENABLE, 0);
+ device->SetRenderState(D3DRS_ALPHATESTENABLE, 0);
+ device->SetRenderState(D3DRS_ALPHABLENDENABLE, 1);
+ device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
+ device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
+ device->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
+ device->SetRenderState(D3DRS_SCISSORTESTENABLE, 0);
+ device->SetRenderState(D3DRS_COLORWRITEENABLE, 15);
+ device->SetTexture(0, nullptr);
+ device->SetTexture(1, nullptr);
+ device->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
+ device->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_DIFFUSE);
+ device->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
+ device->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_DIFFUSE);
+ device->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE);
+ device->SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
+ device->SetFVF(D3DFVF_XYZRHW | D3DFVF_DIFFUSE);
+ device->DrawPrimitiveUP(D3DPT_TRIANGLELIST, static_cast<unsigned>(vertices.size() / 3), vertices.data(), sizeof(Vertex));
+ }
+
+private:
+ struct Vertex { float x, y, z, rhw; uint32_t color; };
+ static constexpr float Left = 16, Top = 16, Width = 288, Height = 442;
+ float scale = 1.f, mouseX = -1.f, mouseY = -1.f;
+ int activeSlider = -1;
+ std::vector<Vertex> vertices;
+
+ static float clamp(float value) { return std::max(0.f, std::min(1.f, value)); }
+ static unsigned byte(float value) { return static_cast<unsigned>(std::lround(clamp(value) * 255.f)); }
+ static float trackY(int row) { return Top + 134 + 45 * row; }
+ static bool hit(float x, float y, float left, float top, float w, float h)
+ { return x >= left && x < left + w && y >= top && y < top + h; }
+ static bool inside(float x, float y) { return hit(x, y, Left, Top, Width, Height); }
+ float &component(int row)
+ {
+ switch (row) {
+ case 0: return values.red;
+ case 1: return values.green;
+ case 2: return values.blue;
+ case 3: return values.brightness;
+ default: return values.strength;
+ }
+ }
+ void updateSlider(int row, float x)
+ {
+ const float fraction = clamp((x - Left - 21) / 246.f);
+ const float low = row == 3 ? .1f : 0.f;
+ const float next = low + fraction * (1.f - low);
+ if (component(row) != next) {
+ component(row) = next;
+ status = "UNSAVED CHANGES";
+ }
+ }
+ void rect(float x, float y, float w, float h, uint32_t color)
+ {
+ if (w <= 0 || h <= 0) return;
+ const Vertex a = {x * scale, y * scale, 0.f, 1.f, color};
+ const Vertex b = {(x + w) * scale, y * scale, 0.f, 1.f, color};
+ const Vertex c = {(x + w) * scale, (y + h) * scale, 0.f, 1.f, color};
+ const Vertex d = {x * scale, (y + h) * scale, 0.f, 1.f, color};
+ vertices.insert(vertices.end(), {a, b, c, a, c, d});
+ }
+ void button(float x, float y, const char *label, bool primary)
+ {
+ const bool hover = hit(mouseX, mouseY, x, y, 122, 34);
+ rect(x, y, 122, 34, primary ? 0xff95ba79 : 0xff56636d);
+ rect(x + 1, y + 1, 120, 32, primary ? (hover ? 0xff466043 : 0xff354b34) : (hover ? 0xff3e4a55 : 0xff2d3741));
+ const float offset = primary ? 16.f : 11.5f;
+ text(x + offset, y + 12, label, 1.5f, 0xffe4eedf);
+ }
+
+ // Each byte is one five-pixel row of a compact, original bitmap alphabet.
+ static std::array<uint8_t, 7> glyph(char c)
+ {
+ if (c >= 'a' && c <= 'z') c -= 'a' - 'A';
+ switch (c) {
+ case 'A': return {{14,17,17,31,17,17,17}};
+ case 'B': return {{30,17,17,30,17,17,30}};
+ case 'C': return {{14,17,16,16,16,17,14}};
+ case 'D': return {{30,17,17,17,17,17,30}};
+ case 'E': return {{31,16,16,30,16,16,31}};
+ case 'F': return {{31,16,16,30,16,16,16}};
+ case 'G': return {{14,17,16,23,17,17,15}};
+ case 'H': return {{17,17,17,31,17,17,17}};
+ case 'I': return {{14,4,4,4,4,4,14}};
+ case 'J': return {{7,2,2,2,18,18,12}};
+ case 'K': return {{17,18,20,24,20,18,17}};
+ case 'L': return {{16,16,16,16,16,16,31}};
+ case 'M': return {{17,27,21,21,17,17,17}};
+ case 'N': return {{17,25,25,21,19,19,17}};
+ case 'O': return {{14,17,17,17,17,17,14}};
+ case 'P': return {{30,17,17,30,16,16,16}};
+ case 'Q': return {{14,17,17,17,21,18,13}};
+ case 'R': return {{30,17,17,30,20,18,17}};
+ case 'S': return {{15,16,16,14,1,1,30}};
+ case 'T': return {{31,4,4,4,4,4,4}};
+ case 'U': return {{17,17,17,17,17,17,14}};
+ case 'V': return {{17,17,17,17,17,10,4}};
+ case 'W': return {{17,17,17,21,21,21,10}};
+ case 'X': return {{17,17,10,4,10,17,17}};
+ case 'Y': return {{17,17,10,4,4,4,4}};
+ case 'Z': return {{31,1,2,4,8,16,31}};
+ case '0': return {{14,17,19,21,25,17,14}};
+ case '1': return {{4,12,4,4,4,4,14}};
+ case '2': return {{14,17,1,2,4,8,31}};
+ case '3': return {{30,1,1,14,1,1,30}};
+ case '4': return {{2,6,10,18,31,2,2}};
+ case '5': return {{31,16,16,30,1,1,30}};
+ case '6': return {{14,16,16,30,17,17,14}};
+ case '7': return {{31,1,2,4,8,8,8}};
+ case '8': return {{14,17,17,14,17,17,14}};
+ case '9': return {{14,17,17,15,1,1,14}};
+ case '#': return {{10,10,31,10,31,10,10}};
+ case '%': return {{25,25,2,4,8,19,19}};
+ case '/': return {{1,1,2,4,8,16,16}};
+ case '-': return {{0,0,0,31,0,0,0}};
+ case '.': return {{0,0,0,0,0,6,6}};
+ case ':': return {{0,6,6,0,6,6,0}};
+ default: return {{0,0,0,0,0,0,0}};
+ }
+ }
+ void text(float x, float y, const char *label, float size, uint32_t color)
+ {
+ for (; *label; ++label, x += 6 * size) {
+ const auto rows = glyph(*label);
+ for (unsigned row = 0; row < rows.size(); ++row)
+ for (unsigned column = 0; column < 5; ++column)
+ if (rows[row] & (1u << (4 - column)))
+ rect(x + column * size, y + row * size, size, size, color);
+ }
+ }
+};
+
+} // namespace WaterPreviewColor
diff --git a/GeneralsMD/Code/Tools/WaterPreviewPreset.h b/GeneralsMD/Code/Tools/WaterPreviewPreset.h
new file mode 100644
index 000000000..6d4eeb1f4
--- /dev/null
+++ b/GeneralsMD/Code/Tools/WaterPreviewPreset.h
@@ -0,0 +1,62 @@
+// Persistence shared by the water editor and its CPU regression checks.
+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.
+#pragma once
+
+#include <cmath>
+#include <filesystem>
+#include <istream>
+#include <initializer_list>
+#include <locale>
+#include <string>
+
+namespace WaterPreviewColor {
+
+// Display RGB; the production water shader converts it to linear color.
+struct Values {
+ float red = 1.f;
+ float green = 1.f;
+ float blue = 1.f;
+ float brightness = 1.f;
+ float strength = 0.f;
+};
+
+inline bool valid(const Values &values)
+{
+ for (float channel : {values.red, values.green, values.blue, values.strength}) {
+ if (!std::isfinite(channel) || channel < 0.f || channel > 1.f)
+ return false;
+ }
+ return std::isfinite(values.brightness)
+ && values.brightness >= 0.1f && values.brightness <= 1.f;
+}
+
+// Commit only a complete preset. Trailing fields are editing errors, just as
+// malformed INI rules are, and must leave the currently displayed values intact.
+inline bool readPreset(std::istream &input, Values &values)
+{
+ input.imbue(std::locale::classic());
+ std::string version;
+ Values parsed;
+ if (!(input >> version >> parsed.red >> parsed.green >> parsed.blue
+ >> parsed.brightness >> parsed.strength)
+ || version != "WATER_PREVIEW_COLOR_V1" || !valid(parsed))
+ return false;
+ input >> std::ws;
+ if (!input.eof() || input.bad())
+ return false;
+ values = parsed;
+ return true;
+}
+
+// Default export names must not silently replace the loaded rule file. Resolve
+// symlinks and hard links too; an explicit export destination remains permitted.
+inline bool defaultExportOverwritesInput(const std::filesystem::path &input,
+ const std::filesystem::path &output)
+{
+ if (input.empty())
+ return false;
+ std::error_code error;
+ return std::filesystem::equivalent(input, output, error) && !error;
+}
+
+} // namespace WaterPreviewColor
diff --git a/GeneralsMD/Code/Tools/optionsmenu_layout.py b/GeneralsMD/Code/Tools/optionsmenu_layout.py
index ccb4a55da..ea504cdb3 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, "LabelWaterStyle", "GUI:WaterStyle"),
+ (COMBO, "ComboBoxWaterStyle", 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("LabelWaterStyle", "ComboBoxWaterStyle")])]),
("PageEffects", [
("GUI:OptionsGroupShadows",
diff --git a/GeneralsMD/Code/Tools/water_preview.cpp b/GeneralsMD/Code/Tools/water_preview.cpp
new file mode 100644
index 000000000..314c1547b
--- /dev/null
+++ b/GeneralsMD/Code/Tools/water_preview.cpp
@@ -0,0 +1,670 @@
+// Standalone water-material editor using the production SDL device, FFT, shader and INI rules.
+#include "PosixDevice9.h"
+#include "SdlGpuFrame.h"
+#include "Platform/EngineShaderName.h"
+#include "Platform/ModernWaterConfig.h"
+#include "Platform/ModernWaterMaterial.h"
+
+#include <SDL3/SDL.h>
+#include <algorithm>
+#include <cmath>
+#include <cstdint>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <fstream>
+#include <sstream>
+#include <filesystem>
+#include <stdexcept>
+#include <string>
+#include <vector>
+#include "WaterPreviewColorPanel.h"
+
+namespace {
+constexpr float Pi = 3.14159265358979323846f;
+constexpr float WaterLevel = 40.0f;
+constexpr unsigned Grid = 220;
+constexpr float Extent = 1100.0f;
+constexpr RenderUInt32 WaterFVF = D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_DIFFUSE | D3DFVF_TEX4;
+
+struct Options {
+ unsigned width = 1280, height = 800, frames = 0;
+ float time = 18.0f, strength = 0.80f, brightness = 0.67f;
+ float mapDepth = 2.0f, mapOpacity = 0.8f;
+ int mode = 2;
+ bool offscreen = false, bubbles = true;
+ bool controls = true, strengthSet = false, brightnessSet = false, bubblesSet = false;
+ bool loadPreset = false;
+ std::string screenshot, colour, config, exportConfig;
+ std::string mapColour = "324B32", mapTexture = "TSWater03.tga";
+};
+
+void help()
+{
+ std::puts(
+ "Water Preview - standalone production-water material editor\n"
+ "Usage: water_preview [--offscreen] [--frames N] [--screenshot FILE.png]\n"
+ " [--mode clean|material|split] [--no-bubbles] [--strength 0..1]\n"
+ " [--color RRGGBB] [--brightness 0.1..1] [--hide-controls]\n"
+ " [--config FILE.ini] [--map-color RRGGBB] [--map-texture NAME]\n"
+ " [--map-depth N] [--map-opacity 0..1] [--export-config FILE.ini]\n"
+ " [--load-preset] [--width N] [--height N] [--time SECONDS]\n"
+ "\n1 clean baseline | 2 resolved material | 3 split (baseline left / material right)\n"
+ "B bubbles | Space pause | drag / arrows orbit | wheel / +/- zoom\n"
+ "[ / ] pollution | R reset camera | S save PNG | E export rule | Escape close\n"
+ "H color panel: RGB, brightness, pollution; Save color stores an editor preset.\n"
+ "L loads saved editor colors; --load-preset restores them at startup.\n"
+ "Ordinary starts resolve the INI rules.\n"
+ "E writes --export-config or water-preview-rule.ini in the working directory.\n"
+ "The texture name is a matching input; authored texture pixels are not loaded.\n"
+ "\nNo game data is required. No game/save files are changed.\n"
+ "--offscreen defaults to one frame; captures use deterministic 1/60 s steps.");
+}
+
+std::string hexColour(const char *text)
+{
+ const std::string value=text;
+ if (value.size()!=6 || value.find_first_not_of("0123456789abcdefABCDEF")!=std::string::npos)
+ throw std::runtime_error("color must be six hexadecimal digits RRGGBB");
+ return value;
+}
+
+ModernWaterConfig::Color mapColour(const std::string &value)
+{
+ const unsigned rgb=unsigned(std::strtoul(value.c_str(),nullptr,16));
+ return {int((rgb>>16)&255),int((rgb>>8)&255),int(rgb&255)};
+}
+
+unsigned integer(const char *text, unsigned low, unsigned high)
+{
+ char *end = nullptr;
+ const unsigned long n = std::strtoul(text, &end, 10);
+ if (!*text || *end || n < low || n > high)
+ throw std::runtime_error(std::string("invalid integer: ") + text);
+ return static_cast<unsigned>(n);
+}
+
+float number(const char *text, float low, float high)
+{
+ char *end = nullptr;
+ const float n = std::strtof(text, &end);
+ if (!*text || *end || !std::isfinite(n) || n < low || n > high)
+ throw std::runtime_error(std::string("invalid number: ") + text);
+ return n;
+}
+
+Options parse(int argc, char **argv)
+{
+ Options o;
+ for (int i = 1; i < argc; ++i) {
+ const std::string arg = argv[i];
+ const auto value = [&]() {
+ if (i + 1 == argc) throw std::runtime_error("missing value after " + arg);
+ return argv[++i];
+ };
+ if (arg == "--offscreen") o.offscreen = true;
+ else if (arg == "--no-bubbles") { o.bubbles = false; o.bubblesSet = true; }
+ else if (arg == "--width") o.width = integer(value(), 320, 4096);
+ else if (arg == "--height") o.height = integer(value(), 240, 4096);
+ else if (arg == "--frames") o.frames = integer(value(), 1, 1000000);
+ else if (arg == "--time") o.time = number(value(), 0, 1000000);
+ else if (arg == "--strength") { o.strength = number(value(), 0, 1); o.strengthSet = true; }
+ else if (arg == "--brightness") { o.brightness = number(value(), 0.1f, 1); o.brightnessSet = true; }
+ else if (arg == "--hide-controls") o.controls = false;
+ else if (arg == "--load-preset") o.loadPreset = true;
+ else if (arg == "--color") o.colour = hexColour(value());
+ else if (arg == "--map-color") o.mapColour = hexColour(value());
+ else if (arg == "--map-texture") {
+ o.mapTexture=value();
+ if (o.mapTexture.empty() || o.mapTexture.find_first_not_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-.\\/")!=std::string::npos)
+ throw std::runtime_error("map texture must be a filename without spaces or INI delimiters");
+ }
+ else if (arg == "--map-depth") o.mapDepth = number(value(), 0.001f, 1000000);
+ else if (arg == "--map-opacity") o.mapOpacity = number(value(), 0, 1);
+ else if (arg == "--config") o.config = value();
+ else if (arg == "--export-config") o.exportConfig = value();
+ else if (arg == "--screenshot") o.screenshot = value();
+ else if (arg == "--mode") {
+ const std::string mode = value();
+ if (mode == "clean") o.mode = 1;
+ else if (mode == "polluted" || mode == "material") o.mode = 2;
+ else if (mode == "split") o.mode = 3;
+ else throw std::runtime_error("mode must be clean, material (or polluted), or split");
+ } else throw std::runtime_error("unknown argument: " + arg);
+ }
+ if (o.offscreen && !o.frames) o.frames = 1;
+ return o;
+}
+
+struct Vec3 { float x, y, z; };
+Vec3 subtract(Vec3 a, Vec3 b) { return {a.x-b.x,a.y-b.y,a.z-b.z}; }
+Vec3 cross(Vec3 a, Vec3 b) { return {a.y*b.z-a.z*b.y,a.z*b.x-a.x*b.z,a.x*b.y-a.y*b.x}; }
+float dot(Vec3 a, Vec3 b) { return a.x*b.x+a.y*b.y+a.z*b.z; }
+Vec3 normalized(Vec3 v) { const float s = 1.0f / std::sqrt(dot(v,v)); return {v.x*s,v.y*s,v.z*s}; }
+
+D3DMATRIX identity()
+{
+ D3DMATRIX m = {};
+ m._11 = m._22 = m._33 = m._44 = 1;
+ return m;
+}
+
+// Row-vector, right-handed view and zero-to-one depth, as the game's D3D9 device expects.
+D3DMATRIX viewMatrix(Vec3 eye, Vec3 target)
+{
+ const Vec3 z = normalized(subtract(eye,target));
+ const Vec3 x = normalized(cross({0,0,1},z));
+ const Vec3 y = cross(z,x);
+ D3DMATRIX m = identity();
+ m._11=x.x; m._12=y.x; m._13=z.x;
+ m._21=x.y; m._22=y.y; m._23=z.y;
+ m._31=x.z; m._32=y.z; m._33=z.z;
+ m._41=-dot(x,eye); m._42=-dot(y,eye); m._43=-dot(z,eye);
+ return m;
+}
+
+D3DMATRIX projection(float aspect)
+{
+ const float near = 2.0f, far = 6000.0f, scale = 1.0f / std::tan(48.0f*Pi/360.0f);
+ D3DMATRIX m = {};
+ m._11=scale/aspect; m._22=scale; m._33=far/(near-far);
+ m._34=-1; m._43=near*far/(near-far);
+ return m;
+}
+
+void require(RenderResult result, const char *operation)
+{
+ if (result != D3D_OK) throw std::runtime_error(std::string(operation) + " failed (" + std::to_string(result) + ")");
+}
+
+struct WaterVertex { float x,y,z,nx,ny,nz; uint32_t colour; float uv[8]; };
+struct BedVertex { float x,y,z; uint32_t colour; float u,v; };
+
+class Preview {
+public:
+ explicit Preview(Options options) : options(options), time(options.time) {}
+ ~Preview()
+ {
+ if (vertices) vertices->Release();
+ if (indices) indices->Release();
+ if (shader) shader->Release();
+ for (auto *texture : textures) texture->Release();
+ if (device) device->Release();
+ if (adapter) adapter->Release();
+ if (window) SDL_DestroyWindow(window);
+ SDL_Quit();
+ }
+
+ int run()
+ {
+ initialize();
+ updateTitle();
+ std::puts("Controls: drag color sliders; H panel; L load saved colors; 1 clean baseline, 2 material, 3 split; B bubbles; Space pause; drag/arrows orbit; wheel/+/- zoom; S PNG; E export rule; Esc close.");
+ uint64_t previous = SDL_GetTicksNS();
+ unsigned frame = 0;
+ bool done = false;
+ while (!done) {
+ SDL_Event event;
+ while (SDL_PollEvent(&event)) handle(event, done);
+ if (done) break;
+ const uint64_t now = SDL_GetTicksNS();
+ const float elapsed = options.frames ? 1.0f/60.0f : std::min(float(now-previous)*1.0e-9f,0.05f);
+ previous = now;
+ if (frame && !paused) time += elapsed;
+ keyboard(elapsed);
+ draw();
+ const bool last = options.frames && frame+1 >= options.frames;
+ if (capture || (last && !options.screenshot.empty())) {
+ save(options.screenshot.empty() ? "water-preview.png" : options.screenshot);
+ capture = false;
+ }
+ require(device->Present(nullptr,nullptr,nullptr,nullptr),"present");
+ ++frame;
+ if (last) done = true;
+ }
+ if (frame) std::printf("Rendered %u frames; %u recorded draws; %llu production FFT updates; no refused draws.\n",
+ frame,device->Draws_Recorded(),static_cast<unsigned long long>(device->Get_Gpu()->Ocean_Updates()));
+ return 0;
+ }
+
+private:
+ Options options;
+ SDL_Window *window = nullptr;
+ IDirect3D9 *adapter = nullptr;
+ PosixDevice9 *device = nullptr;
+ IDirect3DPixelShader9 *shader = nullptr;
+ IDirect3DVertexBuffer9 *vertices = nullptr;
+ IDirect3DIndexBuffer9 *indices = nullptr;
+ std::vector<IDirect3DTexture9 *> textures;
+ IDirect3DTexture9 *bed = nullptr, *height = nullptr, *optical = nullptr, *material = nullptr;
+ float time, yaw = 0.10f, pitch = 0.82f, distance = 370.0f;
+ bool paused = false, dragging = false, capture = false;
+ WaterPreviewColor::Panel colourPanel;
+ std::string colourSettingsPath;
+ ModernWaterConfig::Material resolvedMaterial;
+ std::string loadedConfigPath;
+
+ void loadMaterial()
+ {
+ auto rules=ModernWaterConfig::Defaults();
+ std::string path=options.config;
+ if (path.empty()) {
+ const char *base=SDL_GetBasePath();
+ if (base) {
+ for (const char *suffix : {"overlay/Data/INI/ModernWater.ini","Data/INI/ModernWater.ini"}) {
+ const std::string candidate=std::string(base)+suffix;
+ if (std::filesystem::exists(candidate)) { path=candidate; break; }
+ }
+ }
+ }
+ if (!path.empty()) {
+ std::ifstream input(path,std::ios::binary);
+ if (input) {
+ const std::string text((std::istreambuf_iterator<char>(input)),std::istreambuf_iterator<char>());
+ std::string error;
+ if (!ModernWaterConfig::Parse(text,rules,error))
+ throw std::runtime_error("invalid ModernWater INI "+path+": "+error);
+ loadedConfigPath = path;
+ std::printf("Modern water configuration: %s\n",path.c_str());
+ } else if (std::filesystem::exists(path)) {
+ throw std::runtime_error("cannot read ModernWater INI: "+path);
+ } else std::printf("Modern water configuration absent (%s); using built-in defaults.\n",path.c_str());
+ } else std::puts("Modern water configuration absent; using built-in defaults.");
+ resolvedMaterial=ModernWaterConfig::Resolve(rules,mapColour(options.mapColour),options.mapTexture);
+ auto &v=colourPanel.values;
+ v.red=resolvedMaterial.color.r/255.f;
+ v.green=resolvedMaterial.color.g/255.f;
+ v.blue=resolvedMaterial.color.b/255.f;
+ v.brightness=resolvedMaterial.brightness;
+ v.strength=resolvedMaterial.pollution;
+ colourPanel.defaults=v;
+ if (!options.bubblesSet) options.bubbles=resolvedMaterial.bubbles;
+ colourPanel.status=resolvedMaterial.ruleName.empty()?"MAP COLOR - NO RULE MATCH":"INI MATERIAL LOADED";
+ std::printf("Map input: #%s, %s; material: %s; tint #%02X%02X%02X, brightness %.2f, pollution %.2f, bubbles %s.\n",
+ options.mapColour.c_str(),options.mapTexture.c_str(),
+ resolvedMaterial.ruleName.empty()?"map color fallback":resolvedMaterial.ruleName.c_str(),
+ resolvedMaterial.color.r,resolvedMaterial.color.g,resolvedMaterial.color.b,
+ v.brightness,v.strength,options.bubbles?"yes":"no");
+ }
+
+ void loadColour()
+ {
+ char *folder=SDL_GetPrefPath("CnCGeneralsZH-Reforged","WaterPreview");
+ if (folder) { colourSettingsPath=std::string(folder)+"colors.ini"; SDL_free(folder); }
+ // The INI is authoritative unless loading a local editor preset is requested explicitly.
+ if (options.loadPreset && !loadSavedColour())
+ throw std::runtime_error("no valid saved preview preset at "+colourSettingsPath);
+ auto &v=colourPanel.values;
+ if (options.strengthSet) v.strength=options.strength;
+ if (options.brightnessSet) v.brightness=options.brightness;
+ if (!options.colour.empty()) {
+ const unsigned rgb=unsigned(std::strtoul(options.colour.c_str(),nullptr,16));
+ v.red=float((rgb>>16)&255)/255; v.green=float((rgb>>8)&255)/255; v.blue=float(rgb&255)/255;
+ }
+ if (options.strengthSet || options.brightnessSet || !options.colour.empty())
+ colourPanel.status="UNSAVED CHANGES";
+ colourPanel.visible=options.controls;
+ }
+
+ bool loadSavedColour()
+ {
+ if (colourSettingsPath.empty()) { colourPanel.status="LOAD UNAVAILABLE"; return false; }
+ std::ifstream input(colourSettingsPath);
+ if (!input) { colourPanel.status="NO SAVED COLOR FOUND"; return false; }
+ WaterPreviewColor::Values saved;
+ if (!WaterPreviewColor::readPreset(input, saved)) {
+ colourPanel.status="SAVED COLOR INVALID";
+ return false;
+ }
+ colourPanel.values=saved;
+ colourPanel.status="SAVED COLOR LOADED";
+ std::printf("Loaded preview color: %s\n",colourSettingsPath.c_str());
+ return true;
+ }
+
+ void saveColour()
+ {
+ colourPanel.saveRequested=false;
+ if (colourSettingsPath.empty()) { colourPanel.status="SAVE UNAVAILABLE"; return; }
+ const auto &v=colourPanel.values;
+ const std::string temporary=colourSettingsPath+".tmp";
+ std::ofstream output(temporary,std::ios::trunc);
+ output.imbue(std::locale::classic());
+ output.precision(9);
+ output<<"WATER_PREVIEW_COLOR_V1\n"<<v.red<<' '<<v.green<<' '<<v.blue<<' '
+ <<v.brightness<<' '<<v.strength<<'\n';
+ output.close();
+ if (!output || std::rename(temporary.c_str(),colourSettingsPath.c_str())!=0) {
+ std::remove(temporary.c_str());
+ colourPanel.status="SAVE FAILED";
+ return;
+ }
+ colourPanel.status="COLOR SAVED";
+ std::printf("Saved preview color: %s\n",colourSettingsPath.c_str());
+ }
+
+ void exportRule()
+ {
+ const std::string path=options.exportConfig.empty()?"water-preview-rule.ini":options.exportConfig;
+ if (options.exportConfig.empty()
+ && WaterPreviewColor::defaultExportOverwritesInput(loadedConfigPath, path))
+ throw std::runtime_error("default export would overwrite the loaded configuration; "
+ "choose --export-config explicitly");
+ const std::string temporary=path+".tmp";
+ const auto input=mapColour(options.mapColour);
+ const auto &v=colourPanel.values;
+ const auto channel=[](float value) { return int(std::lround(std::clamp(value,0.f,1.f)*255)); };
+ std::ostringstream contents;
+ contents.imbue(std::locale::classic());
+ contents.precision(9);
+ contents<<"; Exported by Water Preview. Add entries to either matching list as needed.\n"
+ <<"ModernWaterRule PreviewMaterial\n"
+ <<" MatchColors\n Color = R:"<<input.r<<" G:"<<input.g<<" B:"<<input.b<<"\n End\n"
+ <<" MatchTextures\n Texture = "<<options.mapTexture<<"\n End\n"
+ <<" ReplacementColor = R:"<<channel(v.red)<<" G:"<<channel(v.green)<<" B:"<<channel(v.blue)<<"\n"
+ <<" Brightness = "<<v.brightness<<"\n Pollution = "<<v.strength
+ <<"\n Bubbles = "<<(options.bubbles?"Yes":"No")<<"\nEnd\n";
+ ModernWaterConfig::Rules parsed;
+ std::string error;
+ if (!ModernWaterConfig::Parse(contents.str(),parsed,error))
+ throw std::runtime_error("cannot export material rule: "+error);
+ std::ofstream output(temporary,std::ios::binary|std::ios::trunc);
+ output<<contents.str();
+ output.close();
+ if (!output || std::rename(temporary.c_str(),path.c_str())!=0) {
+ std::remove(temporary.c_str());
+ throw std::runtime_error("cannot write material rule: "+path);
+ }
+ colourPanel.status="INI RULE EXPORTED";
+ std::printf("Exported ModernWater rule: %s\n",path.c_str());
+ }
+
+ IDirect3DTexture9 *texture(unsigned side, const std::vector<uint32_t> &pixels)
+ {
+ IDirect3DTexture9 *result = nullptr;
+ require(device->CreateTexture(side,side,1,0,D3DFMT_A8R8G8B8,D3DPOOL_MANAGED,&result,nullptr),"create texture");
+ textures.push_back(result);
+ D3DLOCKED_RECT locked = {};
+ require(result->LockRect(0,&locked,nullptr,0),"lock texture");
+ for (unsigned y=0; y<side; ++y)
+ std::memcpy(static_cast<uint8_t *>(locked.pBits)+y*locked.Pitch,pixels.data()+y*side,side*4);
+ require(result->UnlockRect(0),"unlock texture");
+ return result;
+ }
+
+ void initialize()
+ {
+ if (!SDL_Init(SDL_INIT_VIDEO)) throw std::runtime_error(std::string("SDL video: ")+SDL_GetError());
+ loadMaterial();
+ loadColour();
+ if (!options.exportConfig.empty()) exportRule();
+ // The preview requires the game's native FFT path even if a user's game launch disables it.
+ SDL_setenv_unsafe("ZH_WATER_FFT","1",1);
+ SDL_unsetenv_unsafe("ZH_WATER_DEBUG");
+ if (!options.offscreen) {
+ window = SDL_CreateWindow("Water Preview",options.width,options.height,0);
+ if (!window) throw std::runtime_error(std::string("create window: ")+SDL_GetError());
+ } else SDL_SetHint("ZH_OFFSCREEN_FRAMES","1");
+ adapter = Direct3DCreate9(D3D_SDK_VERSION);
+ if (!adapter) throw std::runtime_error("create D3D9-shaped SDL adapter");
+ D3DPRESENT_PARAMETERS parameters = {};
+ parameters.BackBufferWidth=options.width; parameters.BackBufferHeight=options.height;
+ parameters.BackBufferFormat=D3DFMT_X8R8G8B8;
+ parameters.hDeviceWindow=reinterpret_cast<RenderWindow>(window);
+ parameters.Windowed=1; parameters.EnableAutoDepthStencil=1; parameters.AutoDepthStencilFormat=D3DFMT_D24S8;
+ IDirect3DDevice9 *created = nullptr;
+ require(adapter->CreateDevice(0,D3DDEVTYPE_HAL,parameters.hDeviceWindow,0,&parameters,&created),"create GPU device");
+ device = static_cast<PosixDevice9 *>(created);
+ if (!device->Get_Gpu()) throw std::runtime_error("no SDL GPU frame available");
+ std::printf("Renderer: %s; %ux%u; standalone production-water preview\n",SDL_GetGPUDeviceDriver(device->Get_Gpu()->Device()),options.width,options.height);
+ const RenderUInt32 tokens[] = {0xffff0101u,0x0000ffffu};
+ require(device->CreatePixelShader(tokens,&shader),"create water shader");
+ PosixDevice_Name_Shader(shader,"trapezoid water ps.1.1");
+ createMesh();
+ createTextures();
+ device->SetRenderState(D3DRS_LIGHTING,0);
+ device->SetRenderState(D3DRS_CULLMODE,D3DCULL_NONE);
+ device->SetRenderState(D3DRS_FOGENABLE,0);
+ device->SetRenderState(D3DRS_ALPHATESTENABLE,0);
+ device->SetRenderState(D3DRS_ZENABLE,D3DZB_TRUE);
+ device->SetRenderState(D3DRS_ZFUNC,D3DCMP_LESSEQUAL);
+ device->SetVertexShader(nullptr);
+ for (unsigned stage=0; stage<8; ++stage) {
+ device->SetSamplerState(stage,D3DSAMP_MINFILTER,D3DTEXF_LINEAR);
+ device->SetSamplerState(stage,D3DSAMP_MAGFILTER,D3DTEXF_LINEAR);
+ device->SetSamplerState(stage,D3DSAMP_MIPFILTER,D3DTEXF_NONE);
+ device->SetTextureStageState(stage,D3DTSS_TEXCOORDINDEX,stage);
+ device->SetTextureStageState(stage,D3DTSS_TEXTURETRANSFORMFLAGS,D3DTTFF_DISABLE);
+ }
+ }
+
+ void createMesh()
+ {
+ std::vector<WaterVertex> data;
+ data.reserve((Grid+1)*(Grid+1));
+ for (unsigned y=0; y<=Grid; ++y) for (unsigned x=0; x<=Grid; ++x) {
+ const float px=(float(x)/Grid*2-1)*Extent, py=(float(y)/Grid*2-1)*Extent;
+ // Exact production FFT metadata: weight, free damping, offshore exposure;
+ // UV0 geometric correction, UV1 attenuation and original water elevation.
+ data.push_back({px,py,WaterLevel,1.0f,0.72f,0.26f,0xffffffffu,{0,0,0.72f,WaterLevel,0,0,0,0}});
+ }
+ std::vector<uint16_t> faces;
+ faces.reserve(Grid*Grid*6);
+ for (unsigned y=0; y<Grid; ++y) for (unsigned x=0; x<Grid; ++x) {
+ const uint16_t a=uint16_t(y*(Grid+1)+x), b=uint16_t(a+1), c=uint16_t(a+Grid+1), d=uint16_t(c+1);
+ faces.insert(faces.end(),{a,b,c,b,d,c});
+ }
+ require(device->CreateVertexBuffer(unsigned(data.size()*sizeof(WaterVertex)),D3DUSAGE_WRITEONLY,WaterFVF,D3DPOOL_MANAGED,&vertices,nullptr),"create water vertices");
+ void *memory = nullptr;
+ require(vertices->Lock(0,0,&memory,0),"lock water vertices");
+ std::memcpy(memory,data.data(),data.size()*sizeof(WaterVertex));
+ require(vertices->Unlock(),"unlock water vertices");
+ require(device->CreateIndexBuffer(unsigned(faces.size()*sizeof(uint16_t)),D3DUSAGE_WRITEONLY,D3DFMT_INDEX16,D3DPOOL_MANAGED,&indices,nullptr),"create water indices");
+ require(indices->Lock(0,0,&memory,0),"lock water indices");
+ std::memcpy(memory,faces.data(),faces.size()*sizeof(uint16_t));
+ require(indices->Unlock(),"unlock water indices");
+ }
+
+ void createTextures()
+ {
+ std::vector<uint32_t> colour(256*256), detail(256*256);
+ for (unsigned y=0; y<256; ++y) for (unsigned x=0; x<256; ++x) {
+ uint32_t hash=(x*1973u+y*9277u+89173u); hash=(hash^(hash>>13))*1274126177u;
+ const float grain=float(hash&255)/255.0f;
+ const float variation=std::sin(float(x)*0.068f+std::sin(float(y)*0.037f)*2)*0.04f;
+ const auto channel=[](float c) { return uint32_t(std::clamp(c,0.0f,1.0f)*255.0f); };
+ colour[y*256+x]=0xff000000u|(channel(.39f+grain*.11f+variation)<<16)
+ |(channel(.36f+grain*.09f+variation)<<8)|channel(.27f+grain*.07f+variation);
+ detail[y*256+x]=0xff000000u|(channel(.49f+grain*.12f)<<16)|(channel(.40f+grain*.10f)<<8)|channel(.45f+grain*.10f);
+ }
+ bed=texture(256,colour);
+ material=texture(256,detail);
+ height=texture(1,{0x00000000u}); // zero-height bed, alpha zero disables wave cages
+ optical=texture(1,{0xff430000u}); // enclosed-water exposure: 0.263, no coastline
+ }
+
+ void camera()
+ {
+ pitch=std::clamp(pitch,0.48f,1.38f); distance=std::clamp(distance,180.0f,1050.0f);
+ const Vec3 offset={std::sin(yaw)*std::cos(pitch),-std::cos(yaw)*std::cos(pitch),std::sin(pitch)};
+ const Vec3 right=normalized(cross({0,0,1},offset)),up=cross(offset,right);
+ const float tangent=std::tan(48.0f*Pi/360.0f),aspect=float(options.width)/options.height;
+ float farthest=0;
+ for (int x : {-1,1}) for (int y : {-1,1}) {
+ const Vec3 ray={-offset.x+tangent*(up.x*y+right.x*x*aspect),
+ -offset.y+tangent*(up.y*y+right.y*x*aspect),-offset.z+tangent*(up.z*y+right.z*x*aspect)};
+ const float travel=-offset.z/ray.z;
+ farthest=std::max(farthest,std::max(std::abs(offset.x+ray.x*travel),std::abs(offset.y+ray.y*travel)));
+ }
+ // Keep the finite patch outside every camera ray, including wide windows and
+ // low viewpoints. A margin covers the actual wave displacement near the boundary.
+ distance=std::min(distance,Extent*.90f/std::max(farthest,.01f));
+ const Vec3 eye={offset.x*distance,offset.y*distance,WaterLevel+offset.z*distance};
+ const D3DMATRIX world=identity(),view=viewMatrix(eye,{0,0,WaterLevel}),project=projection(float(options.width)/options.height);
+ device->SetTransform(D3DTS_WORLD,&world);
+ device->SetTransform(D3DTS_VIEW,&view);
+ device->SetTransform(D3DTS_PROJECTION,&project);
+ }
+
+ void draw()
+ {
+ camera();
+ require(device->Clear(0,nullptr,D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER,0xff1b2830u,1,0),"clear frame");
+ require(device->BeginScene(),"begin scene");
+ device->SetPixelShader(nullptr);
+ device->SetRenderState(D3DRS_ZENABLE,D3DZB_TRUE);
+ device->SetRenderState(D3DRS_ZWRITEENABLE,1);
+ device->SetRenderState(D3DRS_ALPHABLENDENABLE,0);
+ device->SetRenderState(D3DRS_TEXTUREFACTOR,0xffffffffu);
+ for (unsigned stage=0; stage<16; ++stage) device->SetTexture(stage,nullptr);
+ device->SetTexture(0,bed);
+ device->SetTextureStageState(0,D3DTSS_COLOROP,D3DTOP_MODULATE);
+ device->SetTextureStageState(0,D3DTSS_COLORARG1,D3DTA_TEXTURE);
+ device->SetTextureStageState(0,D3DTSS_COLORARG2,D3DTA_DIFFUSE);
+ device->SetTextureStageState(0,D3DTSS_ALPHAOP,D3DTOP_SELECTARG1);
+ device->SetTextureStageState(0,D3DTSS_ALPHAARG1,D3DTA_TEXTURE);
+ device->SetTextureStageState(1,D3DTSS_COLOROP,D3DTOP_DISABLE);
+ device->SetFVF(D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1);
+ const float edge=1800,uv=edge/80;
+ const BedVertex floor[]={{-edge,-edge,0,0xffffffffu,-uv,-uv},{edge,-edge,0,0xffffffffu,uv,-uv},{-edge,edge,0,0xffffffffu,-uv,uv},
+ {edge,-edge,0,0xffffffffu,uv,-uv},{edge,edge,0,0xffffffffu,uv,uv},{-edge,edge,0,0xffffffffu,-uv,uv}};
+ require(device->DrawPrimitiveUP(D3DPT_TRIANGLELIST,2,floor,sizeof(BedVertex)),"draw submerged bed");
+
+ device->SetTexture(0,nullptr);
+ device->SetTexture(2,height);
+ device->SetTexture(4,optical);
+ device->SetTexture(7,material);
+ device->SetPixelShader(shader);
+ const float constants[7][4]={{time,0,0,WaterLevel},{-Extent,-Extent,Extent,Extent},
+ {-.30f,-.45f,.84f,0},{.88f,.81f,.66f,1},{Extent,Extent*2,100,1},
+ {options.mapDepth,options.mapOpacity,1,1},{0,.26f,.28f,.30f}};
+ device->SetPixelShaderConstantF(1,&constants[0][0],7);
+ const float fill[4][4]={{0,0,0,1},{0,0,0,0},{0,0,0,0},{0,0,0,0}};
+ device->SetPixelShaderConstantF(90,&fill[0][0],4);
+ device->SetRenderState(D3DRS_TEXTUREFACTOR,0xffffffffu);
+ device->SetRenderState(D3DRS_ZWRITEENABLE,0);
+ device->SetRenderState(D3DRS_ALPHABLENDENABLE,1);
+ device->SetRenderState(D3DRS_SRCBLEND,D3DBLEND_SRCALPHA);
+ device->SetRenderState(D3DRS_DESTBLEND,D3DBLEND_INVSRCALPHA);
+ device->SetFVF(WaterFVF);
+ device->SetStreamSource(0,vertices,0,sizeof(WaterVertex));
+ device->SetIndices(indices);
+ if (options.mode==3) {
+ // Crop the same projection into two viewports. The device's viewport scissor
+ // supplies the comparison boundary; production shading needs no split hook.
+ drawWater(false,0,options.width/2);
+ drawWater(true,options.width/2,options.width-options.width/2);
+ const D3DVIEWPORT9 viewport={0,0,options.width,options.height,0,1};
+ require(device->SetViewport(&viewport),"restore viewport");
+ const D3DMATRIX project=projection(float(options.width)/options.height);
+ require(device->SetTransform(D3DTS_PROJECTION,&project),"restore projection");
+ } else drawWater(options.mode!=1,0,options.width);
+ colourPanel.draw(device,options.width,options.height);
+ require(device->EndScene(),"end scene");
+ if (!device->Draw_Refusals().empty()) {
+ std::string why="GPU refused a draw:";
+ for (const auto &entry:device->Draw_Refusals()) why+=" "+entry.first+";";
+ throw std::runtime_error(why);
+ }
+ if (!device->Get_Gpu()->Ocean_Updates()) throw std::runtime_error("production FFT did not initialize");
+ }
+
+ void drawWater(bool enabled,unsigned left,unsigned width)
+ {
+ const D3DVIEWPORT9 viewport={left,0,width,options.height,0,1};
+ require(device->SetViewport(&viewport),"set water viewport");
+ D3DMATRIX project=projection(float(options.width)/options.height);
+ project._11*=float(options.width)/width;
+ const float offset=(float(options.width)-2.f*left-width)/width;
+ project._31+=offset*project._34;
+ require(device->SetTransform(D3DTS_PROJECTION,&project),"set water projection");
+ const auto &v=colourPanel.values;
+ const float colour[4]={v.red,v.green,v.blue,v.brightness};
+ // Editing a neutral fallback creates an explicit tint without changing pollution.
+ const float tint=resolvedMaterial.tintAmount>0 || v.red<1 || v.green<1 || v.blue<1 || v.brightness<1 ? 1.f : 0.f;
+ const float parameters[4]={enabled?tint:0.f,enabled?v.strength:0.f,enabled&&options.bubbles?1.f:0.f,0.f};
+ require(device->SetPixelShaderConstantF(ModernWaterMaterial::RegisterColor,colour,1),"set water material color");
+ require(device->SetPixelShaderConstantF(ModernWaterMaterial::RegisterParameters,parameters,1),"set water material parameters");
+ require(device->DrawIndexedPrimitive(D3DPT_TRIANGLELIST,0,0,(Grid+1)*(Grid+1),0,Grid*Grid*2),"draw modern water");
+ }
+
+ void save(const std::string &path)
+ {
+ std::vector<uint8_t> pixels;
+ if (!device->Get_Gpu()->Read_Back(device->Get_Gpu()->Back_Buffer(),options.width,options.height,pixels))
+ throw std::runtime_error("read screenshot from GPU");
+ SDL_Surface *surface=SDL_CreateSurfaceFrom(options.width,options.height,SDL_PIXELFORMAT_BGRA32,pixels.data(),options.width*4);
+ if (!surface) throw std::runtime_error(std::string("create screenshot surface: ")+SDL_GetError());
+ const bool bmp=path.size()>=4 && path.substr(path.size()-4)==".bmp";
+ const bool saved=bmp?SDL_SaveBMP(surface,path.c_str()):SDL_SavePNG(surface,path.c_str());
+ SDL_DestroySurface(surface);
+ if (!saved) throw std::runtime_error(std::string("save screenshot: ")+SDL_GetError());
+ std::printf("Screenshot: %s\n",path.c_str());
+ }
+
+ void updateTitle()
+ {
+ if (!window) return;
+ char title[320];
+ const char *mode=options.mode==1?"Clean baseline":options.mode==2?"Resolved material":"Baseline LEFT | Material RIGHT";
+ std::snprintf(title,sizeof(title),"Water Preview: %s | brightness %.0f%% | pollution %.0f%% | bubbles %s | H panel, E export%s",
+ mode,colourPanel.values.brightness*100,colourPanel.values.strength*100,options.bubbles?"ON":"OFF",paused?" | PAUSED":"");
+ SDL_SetWindowTitle(window,title);
+ }
+
+ void handle(const SDL_Event &event, bool &done)
+ {
+ if (event.type==SDL_EVENT_WINDOW_FOCUS_LOST) dragging=false;
+ if (colourPanel.handle(event)) {
+ dragging=false;
+ if (colourPanel.saveRequested) saveColour();
+ updateTitle();
+ return;
+ }
+ if (event.type==SDL_EVENT_QUIT) done=true;
+ else if (event.type==SDL_EVENT_MOUSE_BUTTON_DOWN && event.button.button==SDL_BUTTON_LEFT) dragging=true;
+ else if (event.type==SDL_EVENT_MOUSE_BUTTON_UP && event.button.button==SDL_BUTTON_LEFT) dragging=false;
+ else if (event.type==SDL_EVENT_MOUSE_MOTION && dragging) {yaw-=event.motion.xrel*.005f;pitch+=event.motion.yrel*.004f;}
+ else if (event.type==SDL_EVENT_MOUSE_WHEEL) distance*=std::exp(-event.wheel.y*.09f);
+ else if (event.type==SDL_EVENT_KEY_DOWN && !event.key.repeat) {
+ switch (event.key.key) {
+ case SDLK_ESCAPE: done=true; break;
+ case SDLK_1: options.mode=1; break;
+ case SDLK_2: options.mode=2; break;
+ case SDLK_3: options.mode=3; break;
+ case SDLK_B: options.bubbles=!options.bubbles; colourPanel.status="UNSAVED CHANGES"; break;
+ case SDLK_SPACE: paused=!paused; break;
+ case SDLK_R: yaw=.10f;pitch=.82f;distance=370; break;
+ case SDLK_S: capture=true; break;
+ case SDLK_L: colourPanel.visible=true; loadSavedColour(); break;
+ case SDLK_E:
+ try { exportRule(); }
+ catch (const std::exception &error) { colourPanel.status="EXPORT FAILED"; std::fprintf(stderr,"%s\n",error.what()); }
+ break;
+ case SDLK_LEFTBRACKET: colourPanel.values.strength=std::max(0.0f,colourPanel.values.strength-.05f); colourPanel.status="UNSAVED CHANGES"; break;
+ case SDLK_RIGHTBRACKET: colourPanel.values.strength=std::min(1.0f,colourPanel.values.strength+.05f); colourPanel.status="UNSAVED CHANGES"; break;
+ default: break;
+ }
+ updateTitle();
+ }
+ }
+
+ void keyboard(float dt)
+ {
+ const bool *keys=SDL_GetKeyboardState(nullptr);
+ if (keys[SDL_SCANCODE_LEFT]) yaw-=dt*.65f;
+ if (keys[SDL_SCANCODE_RIGHT]) yaw+=dt*.65f;
+ if (keys[SDL_SCANCODE_UP]) pitch+=dt*.5f;
+ if (keys[SDL_SCANCODE_DOWN]) pitch-=dt*.5f;
+ if (keys[SDL_SCANCODE_EQUALS] || keys[SDL_SCANCODE_KP_PLUS]) distance*=std::exp(-dt*.7f);
+ if (keys[SDL_SCANCODE_MINUS] || keys[SDL_SCANCODE_KP_MINUS]) distance*=std::exp(dt*.7f);
+ }
+};
+} // namespace
+
+int main(int argc, char **argv)
+{
+ for (int i=1;i<argc;++i) if (std::strcmp(argv[i],"--help")==0 || std::strcmp(argv[i],"-h")==0) {help();return 0;}
+ try { Preview preview(parse(argc,argv)); return preview.run(); }
+ catch (const std::exception &error) { std::fprintf(stderr,"water_preview: %s\n",error.what()); return 1; }
+}
diff --git a/docs/linux.md b/docs/linux.md
new file mode 100644
index 000000000..fecf0eda2
--- /dev/null
+++ b/docs/linux.md
@@ -0,0 +1,13 @@
+
+
+## Modern water contribution
+
+On Linux, Water style selects Modern or Classic live. Modern is the default.
+Windows keeps its original water shader identities; macOS uses the legacy SDL
+water programs and hides the Linux selector. Material rules are loaded from
+`Data/INI/ModernWater.ini` through the game filesystem. Source edits are staged
+into the build overlay; invalid or missing game rules use built-in defaults.
+
+Build the standalone editor explicitly: `cmake --build build-linux --target water_preview`.
+See [water-preview.md](water-preview.md) for controls, matching, explicit exports
+and the distinction between game fallback and preview parse failures.
diff --git a/docs/porting/windows-impact.md b/docs/porting/windows-impact.md
index 41d429e33..1e0a8220b 100644
--- a/docs/porting/windows-impact.md
+++ b/docs/porting/windows-impact.md
@@ -443,3 +443,13 @@ 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 Modern water proposal (2026-10-18)
+
+New water surfaces, material loading and native particle replacements are admitted
+only on Linux. Shared water declarations, portable sampling helpers and inert
+option metadata still compile elsewhere. Windows retains its original shader
+names and shader programs; macOS binds the legacy SDL programs. The Linux style
+widget is hidden on both platforms. Windows/macOS builds and runtime checks remain
+open; Linux compilation and GPU tests do not establish their runtime compatibility.
diff --git a/docs/water-preview.md b/docs/water-preview.md
new file mode 100644
index 000000000..2d93ec092
--- /dev/null
+++ b/docs/water-preview.md
@@ -0,0 +1,149 @@
+# Water Preview
+
+`water_preview` is the dedicated native editor for Modern water materials. It shares the
+production SDL renderer, GPU FFT, Modern water shader and `ModernWater.ini` parser with
+the game. It requires no game assets, save or running match. The synthetic flat submerged
+bed and fixed lighting make comparisons repeatable; this is not a campaign-map viewer.
+
+## Configuration and matching
+
+On an ordinary launch the tool looks beside its executable for
+`overlay/Data/INI/ModernWater.ini`, then `Data/INI/ModernWater.ini`. If neither exists it
+uses the same built-in rule as the game. `--config FILE.ini` selects another file;
+a missing file uses built-in defaults and reports that choice. Invalid configuration
+produces a diagnostic and stops the preview so a bad edit cannot be mistaken for a
+successful comparison. An empty file intentionally disables all replacement rules.
+
+The initial map inputs are color **#324B32** (RGB 50,75,50), texture name `TSWater03.tga`,
+water depth **2.0**, and minimum opacity **0.8**. These are the common authored water
+settings in `GC_ChemGeneral` and `MD_USA05`. The texture name is used for rule matching;
+the tool does not load the authored texture's pixels. The default matched material uses
+**#2D3A0B** (RGB 45,58,11), **67% brightness**, **80% pollution**, and bubbles.
+
+```ini
+ModernWaterRule PollutedWater
+ MatchColors
+ Color = R:50 G:75 B:50
+ End
+ MatchTextures
+ Texture = TSWater03.tga
+ End
+ ReplacementColor = R:45 G:58 B:11
+ Brightness = 0.67
+ Pollution = 0.80
+ Bubbles = Yes
+End
+```
+
+Each list accepts additional entries. A rule matches any listed color **and** any listed
+texture; the first enabled matching rule wins. Colors match exact RGB bytes. Texture
+matching ignores case and directory prefixes. An unmatched color is used by Modern
+water without pollution; white preserves its normal blue appearance. Pollution does not
+control tint strength. The Modern material's bubbles are procedural surface shading
+with popping rings, not a volumetric gas simulation.
+
+## Game integration
+
+The global source file is `GeneralsMD/Code/Data/INI/ModernWater.ini`. A normal native
+build stages it as `<build>/overlay/Data/INI/ModernWater.ini` (in this checkout,
+`build-linux/overlay/Data/INI/ModernWater.ini`). The game reads `Data/INI/ModernWater.ini`
+through its existing filesystem/overlay lookup at startup. There is no in-game settings
+control for these rules.
+
+Matching uses the effective map `StandingWaterColor` and `StandingWaterTexture` after
+the existing map overrides have loaded, including save restoration. It does not inspect
+map names, save names or the chosen general. The material is resolved again when those
+effective values change. Classic water retains its authored parameters; Modern rules
+replace only the material color and effects, retaining the map's depth and opacity.
+
+If the game cannot read the INI or an edit is invalid, it logs a diagnostic and keeps the
+complete built-in default rule set. Parsing is transactional: a valid first rule followed
+by an invalid rule cannot install a partial configuration. A valid empty/comment-only
+file disables all replacement rules. The preview instead stops on an invalid file so
+editing mistakes are visible. Neither the game nor the preview automatically regenerates
+a missing INI or rewrites its loaded configuration; preview export writes only its
+selected output.
+
+Keep durable project changes in the source INI. Building `water_preview`, building the
+`zh_overlay` target, or running a normal full build copies it into the runtime overlay.
+Restaging recreates that overlay, so direct edits to the staged copy are replaced. Restart
+the game or preview after editing the configuration; neither watches the file for changes.
+
+## Build and run
+
+With an existing configured native build and dependencies:
+
+```sh
+cmake --build build-linux --target water_preview -j 4
+./build-linux/water_preview
+./build-linux/water_preview --help
+```
+
+The preview does not edit the game configuration or maps automatically.
+
+## Interactive editor
+
+- **1:** clean Modern baseline; **2:** resolved/editable material; **3:** split comparison,
+ baseline on the left. Split mode uses two cropped views of the same scene and shader.
+- **H:** show or hide the RGB, brightness and pollution panel.
+- **L:** load the saved editor colors. This opens the panel and reports success,
+ a missing preset, or an invalid preset without closing the viewer.
+- **B:** toggle bubbles; the title reports their state. **[ / ]:** adjust pollution.
+- **Space:** pause animation. Drag outside the panel or use arrows to orbit. Wheel or
+ **+ / -** zooms. **R** resets the camera.
+- **S:** save `water-preview.png` in the working directory, or the `--screenshot` path.
+- **E:** export the current material as `water-preview-rule.ini` in the working
+ directory, or the `--export-config` path. Export replaces that destination with a
+ single rule matching the selected map color and texture; it does not merge a rule set.
+- **Escape:** close the viewer.
+
+**Reset color** restores the material resolved at startup. **Save color** stores the five
+panel values in SDL's per-user `CnCGeneralsZH-Reforged/WaterPreview/colors.ini` preference
+file. Press **L** to restore those colors in the current session, or use **`--load-preset`**
+to restore them at startup. Ordinary starts always resolve the INI, and old Dr Thrax
+preview preferences cannot override it silently.
+The bubble toggle is a material option exported to INI, not part of the five-value editor
+preset. Unsaved slider changes affect only the current session.
+
+## Repeatable comparisons and export
+
+```sh
+./build-linux/water_preview --offscreen --time 12 --mode split \
+ --screenshot /tmp/water-split.png
+
+./build-linux/water_preview --map-color C03020 --map-texture OtherWater.tga \
+ --offscreen --screenshot /tmp/water-red-map.png
+
+./build-linux/water_preview --color 2D3A0B --brightness 0.67 --strength 0.8 \
+ --export-config /tmp/proposed-modern-water.ini
+```
+
+`--export-config` writes the startup material immediately and makes **E** update that
+same file after edits. The exported rule is parsed by the shared parser before writing.
+Explicit `--color`, `--brightness` and `--strength` override the resolved material and any
+explicitly loaded editor preset. `--no-bubbles` overrides the rule's bubble switch.
+`--map-color` and `--map-texture` change matching inputs; `--map-depth` and `--map-opacity`
+change the independent authored depth/opacity parameters. `--strength 0` removes
+pollution while retaining the selected color; **1** or `--mode clean` shows the untouched
+Modern baseline. `--hide-controls` excludes the editor panel from captures.
+
+Offscreen mode defaults to one frame. `--frames 180` runs three seconds with deterministic
+1/60-second steps. `--time` sets the initial wave time; `--width` and `--height` set output
+size. Startup never loads a saved preset without `--load-preset`, including offscreen
+captures; **L** loads it explicitly during an interactive session.
+
+## Implementation
+
+The tool compiles `Tools/water_preview.cpp` and `Tools/WaterPreviewColorPanel.h` and links
+the ordinary production shader library. Material inputs use the dedicated constants in
+`Platform/ModernWaterMaterial.h`; light colors, texture factors and vertex metadata retain
+their production meanings. Material matching and constants are shared with the game renderer. The preview is
+built explicitly and does not add an editor dependency to the game executable.
+
+## Validation
+
+The source includes material parsing, map-override/cache, preset persistence, GPU
+water/FFT and compiled uniform-layout checks. Run the Release CTest suite in the
+configured build, and build `water_preview` explicitly. Runtime checks should use
+isolated preferences and copied saves, compare both water styles, and retain
+actual source/executable hashes alongside captures and timing samples.