Zero Hour rebuilt from EA's source: x64, Direct3D 11, VS2022/CMake, ~60 original bugs fixed, an AI that builds a base. Bring your own game.
C++ cmakecnccommand-and-conquercppdirectx11game-enginegame-preservationgeneralsrtssage-enginex64zero-hour
feat(shadows): add sun and smoke shadow rendering on linux
Richard Louie Orilla204fb9b672f2
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 39304666c..de4d6b3c9 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,15 @@ found and fixed — EA's own, not port damage.**---+## Sun and smoke shadow parity on Linux++- Linux draws mapped sun and smoke shadows across terrain, buildings, units,+ trees and bridges. Sorted cloaked casters retain their partial coverage.+- Existing shadow options remain authoritative. Unavailable resources retain+ legacy shadows; legacy water and reflections keep their existing paths.+- Windows and macOS keep their existing renderer behavior. See+ [the Linux shadow guide](docs/sdl-sun-shadows.md) for diagnostics and limits.+## 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.manifestindex 48589592b..f57e8d1af 100644--- a/GeneralsMD/Code/BuildFingerprint.manifest+++ b/GeneralsMD/Code/BuildFingerprint.manifest@@ -379,6 +379,8 @@ Data/Scenarios/standinfake.txtData/Scenarios/stashbeside.txtData/Scenarios/statues.txtData/Scenarios/stealthintruder.txt+Data/Scenarios/sun_cloak.txt+Data/Scenarios/sun_trees.txtData/Scenarios/swhole.txtData/Scenarios/swpair.txtData/Scenarios/techrespawn.txt@@ -1719,6 +1721,7 @@ GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DTankTruckDraw.hGameEngineDevice/Include/W3DDevice/GameClient/Module/W3DTracerDraw.hGameEngineDevice/Include/W3DDevice/GameClient/Module/W3DTreeDraw.hGameEngineDevice/Include/W3DDevice/GameClient/Module/W3DTruckDraw.h+GameEngineDevice/Include/W3DDevice/GameClient/SunShadowCasterCull.hGameEngineDevice/Include/W3DDevice/GameClient/TerrainTex.hGameEngineDevice/Include/W3DDevice/GameClient/TileData.hGameEngineDevice/Include/W3DDevice/GameClient/W3DAssetManager.h@@ -1801,6 +1804,7 @@ GameEngineDevice/Source/PosixDevice/Render/PosixDevice9.hGameEngineDevice/Source/PosixDevice/Render/PosixDevice9Capture.cppGameEngineDevice/Source/PosixDevice/Render/PosixDevice9Draw.cppGameEngineDevice/Source/PosixDevice/Render/PosixDevice9Resources.cpp+GameEngineDevice/Source/PosixDevice/Render/PosixDevice9SunShadow.cppGameEngineDevice/Source/PosixDevice/Render/PosixDevice9Timing.cppGameEngineDevice/Source/PosixDevice/Render/PosixDirect3D9.cppGameEngineDevice/Source/PosixDevice/Render/PosixImage.cpp@@ -1816,12 +1820,16 @@ GameEngineDevice/Source/PosixDevice/Render/SdlCreationLog.hGameEngineDevice/Source/PosixDevice/Render/SdlGpuFrame.cppGameEngineDevice/Source/PosixDevice/Render/SdlGpuFrame.hGameEngineDevice/Source/PosixDevice/Render/SdlGpuFrameBatch.cpp+GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrameSmoke.cpp+GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrameSunShadow.cppGameEngineDevice/Source/PosixDevice/Render/SdlPipelineCache.cppGameEngineDevice/Source/PosixDevice/Render/SdlPipelineCache.hGameEngineDevice/Source/PosixDevice/Render/SdlProgramCache.cppGameEngineDevice/Source/PosixDevice/Render/SdlProgramCache.h+GameEngineDevice/Source/PosixDevice/Render/SdlRenderMatrix.hGameEngineDevice/Source/PosixDevice/Render/SdlResourceMirror.cppGameEngineDevice/Source/PosixDevice/Render/SdlResourceMirror.h+GameEngineDevice/Source/PosixDevice/Render/SdlSunShadowDebug.hGameEngineDevice/Source/SdlDevice/Common/SdlDisplays.cppGameEngineDevice/Source/SdlDevice/Common/SdlGameEngine.cppGameEngineDevice/Source/SdlDevice/Common/SdlMessageBox.cpp@@ -1974,6 +1982,9 @@ Libraries/Include/Platform/RenderTypes.hLibraries/Include/Platform/RendererName.hLibraries/Include/Platform/SleepMilliseconds.hLibraries/Include/Platform/StrdupAsWindows.h+Libraries/Include/Platform/SunShadow.h+Libraries/Include/Platform/SunShadowMode.h+Libraries/Include/Platform/SunSmoke.hLibraries/Include/rts/debug.hLibraries/Include/rts/profile.hLibraries/Lib/.gitignore@@ -3102,6 +3113,7 @@ Tests/test_sdl_program_cache.cppTests/test_selection_priority.incTests/test_shader_sdl.cppTests/test_smooth_motion.cpp+Tests/test_sun_shadow_sorting.cppTests/test_supply_center_save.incTests/test_support.cppTests/test_terrain_golden.cpp@@ -4093,6 +4105,7 @@ Tools/replay-check.shTools/root-readonly-check.shTools/signal_marks.pyTools/stage-overlay.sh+Tools/sun-shadow-check.pyTools/syntax_sweep.pyTools/terrain_oracle_extract.pyTools/textureCompress/resource.hdiff --git a/GeneralsMD/Code/CMakeLists.txt b/GeneralsMD/Code/CMakeLists.txtindex 30f6c550c..7abfc1f04 100644--- a/GeneralsMD/Code/CMakeLists.txt+++ b/GeneralsMD/Code/CMakeLists.txt@@ -1610,6 +1610,17 @@ if(ZH_PLATFORM_POSIX)if(ZH_GAME_DATA)set_tests_properties(test_render_hooks PROPERTIES ENVIRONMENT "ZH_DATA_DIR=${ZH_GAME_DATA}")endif()++ if(ZH_PLATFORM_LINUX)+ add_executable(test_sun_shadow_sorting ${CMAKE_CURRENT_SOURCE_DIR}/Tests/test_sun_shadow_sorting.cpp)+ set_target_properties(test_sun_shadow_sorting PROPERTIES CXX_STANDARD 17)+ target_include_directories(test_sun_shadow_sorting PRIVATE+ ${WW}/WWLib ${WW}/WWMath ${WW}/WWDebug ${WW}/WW3D2+ ${CMAKE_CURRENT_SOURCE_DIR}/GameEngineDevice/Source/PosixDevice/Render)+ target_link_libraries(test_sun_shadow_sorting PRIVATE w3ddevice ww3d2 posixdevice gameengine SDL3::SDL3-static)+ add_test(NAME test_sun_shadow_sorting COMMAND test_sun_shadow_sorting)+ set_tests_properties(test_sun_shadow_sorting PROPERTIES SKIP_RETURN_CODE 77 RUN_SERIAL TRUE)+ endif()endif()# ===========================================================================@@ -2850,7 +2861,7 @@ if(ZH_PLATFORM_POSIX)endforeach()elseif(ZH_PLATFORM_LINUX)foreach(_zh_test sdl_gpu_frame_selfcheck sdl_program_cache_selfcheck sdl_pipeline_state_selfcheck- posix_gpu_draw_selfcheck ffref_gpu_selfcheck ffref_capture_selfcheck)+ posix_gpu_draw_selfcheck ffref_gpu_selfcheck ffref_capture_selfcheck test_sun_shadow_sorting)if(TEST ${_zh_test})set_property(TEST ${_zh_test} APPEND PROPERTY ENVIRONMENT "SDL_VIDEO_DRIVER=offscreen")endif()diff --git a/GeneralsMD/Code/Data/Scenarios/sun_cloak.txt b/GeneralsMD/Code/Data/Scenarios/sun_cloak.txtnew file mode 100644index 000000000..0076a1700--- /dev/null+++ b/GeneralsMD/Code/Data/Scenarios/sun_cloak.txt@@ -0,0 +1,4 @@+# Friendly cloak shadow coverage, Flash Effect, local America (no observer).+# Wait for Burton's ordinary stealth update; a ranger provides an opaque reference.+30 spawn 0 AmericaInfantryColonelBurton 2 1640 1560 80+30 spawn 0 AmericaInfantryRanger 1 1780 1640diff --git a/GeneralsMD/Code/Data/Scenarios/sun_trees.txt b/GeneralsMD/Code/Data/Scenarios/sun_trees.txtnew file mode 100644index 000000000..ee8d88b7a--- /dev/null+++ b/GeneralsMD/Code/Data/Scenarios/sun_trees.txt@@ -0,0 +1,6 @@+# Both object-model palms and batched foliage, on flat ground in Flash Effect.+# The same actual leaves must cast in the map and remain coloured in the scene.+30 spawn 0 TreePalm1 1 1600 1520+30 spawn 0 TreePalm2short 1 1780 1520+30 spawn 0 TreeDogwood1 1 1600 1680+30 spawn 0 TreeFir01B 1 1780 1680diff --git a/GeneralsMD/Code/GameEngine/Include/Common/GameEngine.h b/GeneralsMD/Code/GameEngine/Include/Common/GameEngine.hindex 08c13cea0..8e7925610 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/GameEngine.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/GameEngine.h@@ -86,6 +86,8 @@ Int GameEngine_videoFramesPerSecond( void );Int GameEngine_videoPicture( void );Real GameEngine_pictureFrame( void );UnsignedInt GameEngine_pictureMilliseconds( void );+// Opt-in screenshot validation: one rendered picture per logic frame, fixed scenery time.+Bool GameEngine_isShadowCaptureClock( void );/** How long the catch-up loop may keep starting new logic ticks before it gives up for this pass.diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cppindex b20581e92..1a2e9e71c 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp@@ -1728,8 +1728,24 @@ UnsignedInt GameEngine_pictureMilliseconds( void )return shown <= 0 ? 0 : (UnsignedInt)(shown * 1000 / (LOGICFRAMES_PER_SECOND * pictures));}+Bool GameEngine_isShadowCaptureClock( void )+{+#if defined(__linux__)+ // Cache the request before the screenshot clears its pending frame. Never admit a replay+ // or network session, and never enable this clock through ordinary graphics settings.+ static const bool asked = TheGlobalData && TheGlobalData->m_screenShotFrame > 0+ && getenv("ZH_SUN_SHADOW_CAPTURE_CLOCK")+ && strcmp(getenv("ZH_SUN_SHADOW_CAPTURE_CLOCK"), "logic") == 0;+ return asked && TheGlobalData->m_turbo && TheNetwork == NULL && TheGameLogic+ && !TheGameLogic->isInMultiplayerGame() && !TheGameLogic->isInReplayGame();+#else+ return FALSE;+#endif+}+Real GameEngine_logicTickFraction( void ){+ if (GameEngine_isShadowCaptureClock()) return 1.0f;const Int pictures = GameEngine_videoPictures();if (pictures > 1)return (Real)(GameEngine_videoPicture() + 1) / (Real)pictures;@@ -2910,6 +2926,9 @@ void GameEngine::planLogicPass( LogicPassPlan &plan )&& turboFrame + TURBO_SETTLE_FRAMES >= TheGlobalData->m_screenShotFrame&& turboFrame <= TheGlobalData->m_screenShotFrame;fastMode = fastMode || ( TheGlobalData->m_turbo && !turboSettling && TheNetwork == NULL );+ // A fixed scenery clock also needs one client update per logic frame. Wall-clock+ // catch-up during screenshot settling otherwise skips tree/particle updates on a slower pass.+ fastMode = fastMode || GameEngine_isShadowCaptureClock();/* -video: one logic frame a pass across the range being recorded, so the draw in front of eachlogic frame is the one picture of it. Paced by the wall clock, a pass that fell behind would@@ -2989,7 +3008,7 @@ void GameEngine::planLogicPass( LogicPassPlan &plan )Bool GameEngine::planOverlappedTick( void ){if (TheNetwork != NULL || !TheGameLogic->isInGame() || TheGameLogic->isInShellGame()- || TheGameLogic->isLoadingMap() || isVideoPass())+ || TheGameLogic->isLoadingMap() || isVideoPass() || GameEngine_isShadowCaptureClock())return FALSE;TheMessageStream->propagateMessages();diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/BaseHeightMap.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/BaseHeightMap.hindex c352724e1..29ee22693 100644--- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/BaseHeightMap.h+++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/BaseHeightMap.h@@ -84,6 +84,7 @@ public:private:std::vector< UnsignedByte > m_heights;};+struct SunShadowCasterCull;#define no_TIMING_TESTS 1@@ -201,6 +202,7 @@ public:void stepTrees(void); ///< W3DTreeBuffer::stepTrees, at the render's sync pointvoid takeWaypointsForRender(void); ///< W3DWaypointBuffer::takeReadsForRender, at the render's sync pointvoid renderTrees(CameraClass * camera); ///< renders the tree buffer.+ void renderTreeShadowCasters(RenderInfoClass &sunInfo, CameraClass *sceneCamera, const SunShadowCasterCull &cull);void addProp(Int id, Coord3D location, Real angle, Real scale, const AsciiString &modelName);void removeProp(Int id);diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/SunShadowCasterCull.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/SunShadowCasterCull.hnew file mode 100644index 000000000..23aeb23f7--- /dev/null+++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/SunShadowCasterCull.h@@ -0,0 +1,52 @@+// Conservative receiver visibility shared by model and object-tree shadow casters.+#pragma once+#include "frustum.h"+#include "sphere.h"++/** Whether anything a pixel of this frame samples can be shadowed by a caster. The caster is its+ bounding sphere, and what it can darken lies downwind of it: the sphere swept away from the sun+ from its own sun side down to the lowest ground on the map, widened by how far the receiving+ filter reaches across the map. That capsule runs from upwind to downwind with this radius.+ Only the four sides of the view are tested: a draw with a depth-biased projection reads the+ map through near and far planes that are not the camera's, and the sides are the same for+ every one of them. The overlay's quads sit at z = 0 whatever the ground does, so for them the+ capsule runs on to overlayDownwind, swept down to z = 0 when the lowest ground is above it. */+inline bool SunShadowReachesTheFrame( const FrustumClass &view, const Vector3 &upwind,+ const Vector3 &downwind, const Vector3 &overlayDownwind, float radius, float overlayReach )+{+ bool inView = true;+ for (int side = 1; side <= 4 && inView; ++side)+ {+ const PlaneClass &plane = view.Planes[ side ];+ inView = Vector3::Dot_Product( plane.N, upwind ) - plane.D <= radius+ || Vector3::Dot_Product( plane.N, downwind ) - plane.D <= radius;+ }+ if (inView)+ return true;++ // the 2D scene's and the interface's quads, at the world's origin+ const Vector3 along = overlayDownwind - upwind;+ const float lengthSqr = along.Length2();+ float t = (lengthSqr > 0.0f) ? -Vector3::Dot_Product( upwind, along ) / lengthSqr : 0.0f;+ t = WWMath::Clamp( t, 0.0f, 1.0f );+ const Vector3 nearest = upwind + along * t;+ const float reach = radius + overlayReach;+ return nearest.Length2() <= reach * reach;+}++struct SunShadowCasterCull {+ const FrustumClass &View;+ Vector3 ToSun;+ float LowestReceiver, CasterPad, FilterReach, OverlayReach;+ bool Enabled;++ bool Visible(const SphereClass &bound) const {+ if (!Enabled) return true;+ const float casterRadius=bound.Radius+CasterPad;+ const float radius=casterRadius+FilterReach;+ const float sweep=WWMath::Max((bound.Center.Z-LowestReceiver+radius)/ToSun.Z,0.0f);+ const float overlaySweep=WWMath::Max((bound.Center.Z-WWMath::Min(LowestReceiver,0.0f)+radius)/ToSun.Z,0.0f);+ return SunShadowReachesTheFrame(View,bound.Center+ToSun*casterRadius,+ bound.Center-ToSun*sweep,bound.Center-ToSun*overlaySweep,radius,OverlayReach);+ }+};diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DTreeBuffer.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DTreeBuffer.hindex ecc5d2797..fa23ff1ec 100644--- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DTreeBuffer.h+++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DTreeBuffer.h@@ -64,6 +64,7 @@#include "Common/GameType.h"#include "Common/AsciiString.h"#include "Common/GlobalData.h"+#include <vector>//-----------------------------------------------------------------------------// Forward References@@ -75,6 +76,7 @@ class W3DTreeDrawModuleData;struct BreezeInfo;class GeometryInfo;class W3DProjectedShadow;+struct SunShadowCasterCull;//-----------------------------------------------------------------------------// Type Defines@@ -222,8 +224,10 @@ public:/// Empties the tree buffer.void setBounds(const Region2D &bounds) {m_bounds = bounds;}/// Draws the trees. Uses camera for culling.- void drawTrees(CameraClass * camera, RefRenderObjListIterator *pDynamicLightsIterator);+ void drawTrees(CameraClass * camera, RefRenderObjListIterator *pDynamicLightsIterator,+ const CameraClass *sunCamera = NULL);void stepTrees(void); ///< the toppling and pushed trees, once a logic frame, at the render's sync point+ void drawModelShadowCasters(RenderInfoClass &sunInfo, const SunShadowCasterCull &cull);/// Called when the view changes, and sort key needs to be recalculated./// Normally sortKey gets calculated when a tree becomes visible.void doFullUpdate(void) {m_updateAllKeys = true;};@@ -259,6 +263,9 @@ private:MAX_SHADOW_BATCH_VERTEX = 8000}; ///< per texture, per frameDX8VertexBufferClass *m_vertexTree[MAX_BUFFERS]; ///<Tree vertex buffer.DX8IndexBufferClass *m_indexTree[MAX_BUFFERS]; ///<indices defining a triangles for the tree drawing.+ struct ShadowRange { Int first, count; };+ std::vector<ShadowRange> m_shadowRanges[MAX_BUFFERS];+ Bool m_lastShadowsForProps = FALSE;IDirect3DPixelShader9 * m_dwTreePixelShader; ///<D3D pixel shaderIDirect3DVertexShader9 * m_dwTreeVertexShader; ///<D3D vertex shaderIDirect3DVertexDeclaration9 * m_treeVertexDeclaration; ///<what D3D8 carried beside the shader@@ -312,10 +319,10 @@ protected:void updateSway(const BreezeInfo& info);void loadTreesInVertexAndIndexBuffers(RefRenderObjListIterator *pDynamicLightsIterator); ///< Fills the index and vertex buffers for drawing.void updateVertexBuffer(void); ///< Fills the index and vertex buffers for drawing.- void drawTreeBuffers(Bool shadowPass); ///< Draws every filled buffer, as trees or as their shadows.+ void drawTreeBuffers(Bool shadowPass, Bool sunPass = FALSE); ///< Draws every filled buffer, as trees or as their shadows.void drawModelShadows(CameraClass *camera, Real stretchX, Real stretchY); ///< the object trees' shadowsInt addShadowTexture(TextureClass *tex); ///< index of this texture in the shadow list, adding it if new- void cull(const CameraClass * camera); ///< Culls the trees.+ void cull(const CameraClass * camera, const CameraClass *sunCamera = NULL); ///< Culls the trees.UnsignedInt doLighting(const Vector3 *normal,const GlobalData::TerrainLighting *objectLighting,const Vector3 *emissive, UnsignedInt vertexDiffuse, Real scale) const;diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/PosixDevice9.cpp b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/PosixDevice9.cppindex 8ce8811c1..db3c64223 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/PosixDevice9.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/PosixDevice9.cpp@@ -167,6 +167,8 @@ PosixDevice9::PosixDevice9(PosixDirect3D9 *adapter, RenderWindow window, const DPosixDevice9::~PosixDevice9(){+ Clear_Sun_Shadow();+ Sun.reset();Release_Surfaces();for (int index = 0; index < SAMPLER_COUNT; ++index) {Posix_Bind(Textures[index], (IDirect3DBaseTexture9 *)NULL);@@ -507,6 +509,8 @@ RenderResult PosixDevice9::Reset(D3DPRESENT_PARAMETERS *parameters)if (parameters == NULL || parameters->BackBufferWidth == 0 || parameters->BackBufferHeight == 0) {return D3DERR_INVALIDCALL;}+ Clear_Sun_Shadow();+ Sun.reset();Release_Surfaces();Parameters = *parameters;if (Parameters.hDeviceWindow != NULL) {@@ -791,6 +795,7 @@ RenderResult PosixDevice9::SetSoftwareVertexProcessing(int)RenderResult PosixDevice9::Draw_Unavailable(const char *what){+ if (SunActive) SunFailed = true;// -headless: Windows draws into a hidden window nobody sees, so succeeding and drawing nothing is// the same effect (decision 8's refinement, 2026-09-26).if (Window == NULL) {diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/PosixDevice9.h b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/PosixDevice9.hindex fc94a89a0..146856a0e 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/PosixDevice9.h+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/PosixDevice9.h@@ -48,6 +48,7 @@#include "Platform/D3D9Posix.h"#include <atomic>+#include <memory>#include <map>#include <string>#include <vector>@@ -164,6 +165,25 @@ public:PosixDevice9(PosixDirect3D9 *adapter, RenderWindow window, const D3DPRESENT_PARAMETERS ¶meters);+ bool Fill_Sun_Smoke(const float *casters, unsigned count, float strength);+ void Set_Sun_Caster_Effect(unsigned effect, const float parameters[4]);+ void Get_Sun_Caster_Effect(unsigned &effect, float parameters[4]) const;+ void Set_Smoke_Glow(bool glow) { SmokeGlow = glow; }+ bool Begin_Sun_Shadow(unsigned size);+ bool End_Sun_Shadow();+ bool Set_Sun_Shadow_Parameters(float bias, float strength, float widest, float narrowest,+ float texelsPerGap, float unitsPerDepth, float skyFill);+ bool Sun_Receives_View();+ bool Sun_Owns_Scene_Shadows();+ bool Enter_Sun_Scene(bool eligible);+ void Leave_Sun_Scene(bool eligible);+ void Exclude_Sun_Receivers(bool exclude);+ bool Sun_Receivers_Excluded() const { return SunExclusions != 0 || SunSceneExclusions != 0; }+ bool Sun_Scene_Excluded() const { return SunSceneExclusions != 0; }+ void Clear_Sun_Shadow();+ std::string Sun_Shadow_Report();+ bool Read_Sun_Shadow(std::vector<float> &depth);+// What the resource code (PosixDevice9Resources.cpp) reads.const D3DPRESENT_PARAMETERS & Get_Present_Parameters() const { return Parameters; }RenderWindow Get_Window() const { return Window; }@@ -326,6 +346,27 @@ public:RenderResult SetPixelShaderConstantF(unsigned int start, const float *data, unsigned int count) override;protected:+ struct SunCapture;+ std::shared_ptr<SunCapture> Sun;+ bool SunActive = false, SunFailed = false, SunReady = false;+ bool SmokeGlow = false;+ unsigned SunCasterEffect = 0;+ float SunCasterOpacity = 1;+ bool Sun_Camera_Space() const;+ bool Sun_Target(struct SdlTarget &target) const;+ unsigned SunExclusions = 0;+ unsigned SunSceneDepth = 0, SunSceneExclusions = 0;+ uint64_t SunSceneGeneration = 0;+ uint64_t SunSolidReceivers = 0, SunGroundReceivers = 0;+ uint64_t SunCameraReceivers = 0, SunAlphaReceivers = 0, SunCloakCasters = 0;+ uint64_t SunReceiversAtSceneStart = 0;+ std::string SunReceiverFailure, SunCaptureFailure;+ void Fail_Sun_Receiver(const char *reason);+ bool Sun_Receives_Target(const struct SdlTarget &target) const;+ bool Sun_Receiving(int vertexProgram, int pixelProgram, const struct SdlTarget &target) const;+ void Build_Sun_Constants(struct SdlEnginePixelConstants &constants) const;+ struct SDL_GPUTexture *Sun_Texture() const;+ struct SDL_GPUSampler *Sun_Sampler() const;~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.cppindex 05412095d..a8e831900 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/PosixDevice9Draw.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/PosixDevice9Draw.cpp@@ -179,6 +179,11 @@ void PosixDevice9::Build_Combiner_Description(CombinerDescription &description)// The alpha test and the fog are pipeline state under D3D9 and instructions in the program here.description.PixelPipeline.AlphaTestEnabled = RenderStates[D3DRS_ALPHATESTENABLE] != 0;description.PixelPipeline.AlphaFunction = RenderStates[D3DRS_ALPHAFUNC];+ if (SunActive && RenderStates[D3DRS_ALPHABLENDENABLE]) {+ description.PixelPipeline.AlphaTestEnabled = true;+ const bool addsLight = RenderStates[D3DRS_DESTBLEND] == D3DBLEND_ONE || RenderStates[D3DRS_SRCBLEND] == D3DBLEND_ONE;+ description.PixelPipeline.AlphaFunction = addsLight ? D3DCMP_NEVER : D3DCMP_GREATEREQUAL;+ }description.PixelPipeline.FogEnabled = RenderStates[D3DRS_FOGENABLE] != 0;description.SpecularAdd = RenderStates[D3DRS_SPECULARENABLE] != 0;@@ -438,7 +443,7 @@ void PosixDevice9::Build_Constants(SdlVertexConstants &vertex, SdlPixelConstantscolour_of(RenderStates[D3DRS_TEXTUREFACTOR], pixel.TextureFactor);colour_of(RenderStates[D3DRS_FOGCOLOR], pixel.FogColour);// A whole level, as D3D9 compares it: the program rounds the pixel's alpha to a level first.- pixel.AlphaReference[0] = (float)(RenderStates[D3DRS_ALPHAREF] & 0xFF);+ pixel.AlphaReference[0] = SunActive && RenderStates[D3DRS_ALPHABLENDENABLE] ? 8.0f : (float)(RenderStates[D3DRS_ALPHAREF] & 0xFF);}//-------------------------------------------------------------------------------------------------@@ -484,6 +489,7 @@ static bool is_dynamic(IDirect3DIndexBuffer9 *buffer)void PosixDevice9::Refuse_Draw(const std::string &reason){+ if (SunActive) SunFailed = true;unsigned int &count = DrawRefusals[reason];if (count++ == 0) {fprintf(stderr, "PosixDevice9: a draw refused: %s\n", reason.c_str());@@ -608,6 +614,7 @@ SDL_GPUTexture *PosixDevice9::Gpu_Texture_Of(IDirect3DSurface9 *surface, std::stbool PosixDevice9::Resolve_Target(SdlTarget &target, std::string &refusal){+ if (Sun_Target(target)) return true;if (RenderTargets[1] != NULL || RenderTargets[2] != NULL || RenderTargets[3] != NULL) {refusal = "more than one render target";return false;@@ -691,6 +698,7 @@ RenderResult PosixDevice9::DrawPrimitiveUP(D3DPRIMITIVETYPE type, unsigned int punsigned int stride){if (vertices == NULL) {+ if (SunActive) SunFailed = true;return D3DERR_INVALIDCALL;}DrawCall call;@@ -757,6 +765,7 @@ RenderResult PosixDevice9::Gpu_Draw(const DrawCall &call)const unsigned int reads = vertices_of(call.Type, call.PrimitiveCount);if (reads == 0 && call.PrimitiveCount != 0) {+ if (SunActive) SunFailed = true;return D3DERR_INVALIDCALL;}if (Gpu == NULL || call.PrimitiveCount == 0) {@@ -792,7 +801,7 @@ RenderResult PosixDevice9::Gpu_Draw(const DrawCall &call)Mirrors->Collect_Dead();if (Gpu->Batch_Is_Full()) {- Gpu->Flush();+ if (!Gpu->Flush()) { Refuse_Draw("batch submission failed"); return D3D_OK; }}phases.Mark("dead+full");@@ -814,43 +823,83 @@ RenderResult PosixDevice9::Gpu_Draw(const DrawCall &call)CombinerDescription combiner;VertexPipelineDescription vertex;Build_Combiner_Description(combiner);+ combiner.ShadowReceiving = Sun_Receiving(vertex_engine, pixel_engine, target);+ combiner.DrawEffect = SunActive ? SunCasterEffect : DRAW_EFFECT_NONE;+ combiner.SmokeGlow = SmokeGlow && vertex_engine == ENGINE_SHADER_NONE && pixel_engine == ENGINE_SHADER_NONE+ && !RenderStates[D3DRS_LIGHTING] && (FVF & D3DFVF_NORMAL) && !(FVF & D3DFVF_XYZRHW);if (vertex_engine == ENGINE_SHADER_NONE && !Build_Vertex_Description(vertex, &refusal)) {Refuse_Draw(refusal);return D3D_OK;}+ if (vertex_engine == ENGINE_SHADER_NONE) vertex.SmokeGlow = combiner.SmokeGlow;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) {+ const SdlProgram *pixel_program = SunActive+ ? &Programs->Sun_Pixel_Program(combiner, pixel_engine)+ : pixel_engine != ENGINE_SHADER_NONE+ ? &Programs->Engine_Pixel_Program(pixel_engine, combiner.PixelPipeline)+ : &Programs->Pixel_Program(combiner);+ const auto retry_without_sun = [&](const char *reason) {+ // Generated receivers add an optional program variant. Ground programs share the+ // established engine path; their existing source keeps its own failure handling.+ if (!combiner.ShadowReceiving || pixel_engine != ENGINE_SHADER_NONE || !vertex_program.Shader)+ return false;+ Fail_Sun_Receiver(reason);+ combiner.ShadowReceiving = false;+ pixel_program = &Programs->Pixel_Program(combiner);+ return pixel_program->Shader != NULL;+ };+ if (!pixel_program->Shader) retry_without_sun("pixel program refused");+ 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)+ retry_without_sun("receiver sampler count");+ if (pixel_program->SamplerSlots > SdlRecordedDraw::MAXIMUM_SAMPLERS || vertex_program.SamplerSlots != 0) {Refuse_Draw("more sampler slots than a draw binds");return D3D_OK;}+ if (vertex_program.UniformBuffers > 1 || pixel_program->UniformBuffers > 1)+ retry_without_sun("receiver uniform layout");+ if (!pixel_program->Shader || vertex_program.UniformBuffers > 1 || pixel_program->UniformBuffers > 1) {+ 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;RenderUInt32 without_depth[RENDER_STATE_COUNT];- if (DepthStencil == NULL) {+ if (DepthStencil == NULL && !SunActive) {memcpy(without_depth, RenderStates, sizeof(without_depth));without_depth[D3DRS_ZENABLE] = D3DZB_FALSE;without_depth[D3DRS_ZWRITEENABLE] = 0;without_depth[D3DRS_STENCILENABLE] = 0;states = without_depth;}+ RenderUInt32 caster_states[RENDER_STATE_COUNT];+ if (SunActive) {+ memcpy(caster_states, states, sizeof(caster_states));+ caster_states[D3DRS_ZENABLE] = D3DZB_TRUE;+ caster_states[D3DRS_ZWRITEENABLE] = 1;+ caster_states[D3DRS_STENCILENABLE] = 0;+ states = caster_states;+ }SdlPipelineKey key;- if (!Sdl_Pipeline_Key(states, call.Type, vertex_program.Shader, pixel_program.Shader, FVF,- SdlGpuFrame::Target_Format(), Gpu->Depth_Format(), key, refusal)) {+ if (!Sdl_Pipeline_Key(states, call.Type, vertex_program.Shader, pixel_program->Shader, FVF,+ target.Colour ? SdlGpuFrame::Target_Format() : 0, Gpu->Target_Depth_Format(target), key, refusal)) {Refuse_Draw("the pipeline: " + refusal);return D3D_OK;}phases.Mark("target+programs");SdlRecordedDraw draw;memset(&draw, 0, sizeof(draw));- draw.Pipeline = Pipelines->Pipeline(key);+ draw.Pipeline = Pipelines->Pipeline(key, combiner.ShadowReceiving && pixel_engine == ENGINE_SHADER_NONE);+ if (!draw.Pipeline && retry_without_sun("pipeline refused")) {+ if (Sdl_Pipeline_Key(states, call.Type, vertex_program.Shader, pixel_program->Shader, FVF,+ target.Colour ? SdlGpuFrame::Target_Format() : 0, Gpu->Target_Depth_Format(target), key, refusal))+ draw.Pipeline = Pipelines->Pipeline(key);+ }phases.Mark("pipeline");if (draw.Pipeline == NULL) {Refuse_Draw("the GPU refused a pipeline");@@ -863,6 +912,7 @@ RenderResult PosixDevice9::Gpu_Draw(const DrawCall &call)PosixVertexBuffer9 *vertex_buffer = user ? NULL : static_cast<PosixVertexBuffer9 *>(Streams[0]);PosixIndexBuffer9 *index_buffer = call.Indexed ? static_cast<PosixIndexBuffer9 *>(Indices) : NULL;if ((!user && vertex_buffer == NULL) || (call.Indexed && index_buffer == NULL)) {+ if (SunActive) SunFailed = true;return D3DERR_INVALIDCALL;}if (stride != layout.Stride) {@@ -879,10 +929,36 @@ RenderResult PosixDevice9::Gpu_Draw(const DrawCall &call)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];+ // Ground programs declare these slots even when their receiving strength is zero.+ // Bind neutral textures then, never material textures or the active attachment.+ const bool ground = EngineShader_Paints_Ground(static_cast<EngineShaderProgram>(pixel_engine));+ if (texture_stage == 5 && (combiner.ShadowReceiving || ground)) {+ draw.Textures[slot] = combiner.ShadowReceiving ? Sun_Texture() : Mirrors->White();+ draw.Samplers[slot] = combiner.ShadowReceiving ? Sun_Sampler() : Samplers->Sampler(SamplerStates[0]);+ if (!draw.Textures[slot] || !draw.Samplers[slot]) {+ if (combiner.ShadowReceiving) {+ Fail_Sun_Receiver("depth texture or sampler unavailable");+ return Gpu_Draw(call); // the failure latch bounds this retry+ }+ Refuse_Draw("sun receiver binding");+ return D3D_OK;+ }+ continue;+ }+ if (texture_stage == 6 && (combiner.ShadowReceiving || ground)) {+ const bool smoke = combiner.ShadowReceiving && Gpu->Sun_Smoke_Texture();+ draw.Textures[slot] = smoke ? Gpu->Sun_Smoke_Texture() : Mirrors->White();+ draw.Samplers[slot] = smoke ? Gpu->Sun_Smoke_Sampler() : Samplers->Sampler(SamplerStates[0]);+ if (!draw.Textures[slot] || !draw.Samplers[slot]) {+ Refuse_Draw("smoke receiver binding");+ 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;@@ -960,7 +1036,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();}}@@ -970,6 +1046,7 @@ RenderResult PosixDevice9::Gpu_Draw(const DrawCall &call)const size_t start = user ? 0 : (size_t)StreamOffsets[0] + (size_t)first * stride;const size_t size = (size_t)count * stride;if (!user && start + size > vertex_buffer->storage().length()) {+ if (SunActive) SunFailed = true;return D3DERR_INVALIDCALL;}const uint8_t *source = user ? (const uint8_t *)call.UserVertices : vertex_buffer->storage().bytes() + start;@@ -996,6 +1073,7 @@ RenderResult PosixDevice9::Gpu_Draw(const DrawCall &call)if (call.Indexed) {const size_t start = (size_t)call.StartIndex * index_size;if (start + (size_t)reads * index_size > index_buffer->storage().length()) {+ if (SunActive) SunFailed = true;return D3DERR_INVALIDCALL;}const uint8_t *source = index_buffer->storage().bytes() + start;@@ -1040,7 +1118,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 +1135,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 +1157,16 @@ 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_NONE || combiner.ShadowReceiving || combiner.DrawEffect)) {SdlEnginePixelConstants engine_constants;memset(&engine_constants, 0, sizeof(engine_constants));engine_constants.Combiner = pixel_constants;+ if (combiner.ShadowReceiving) Build_Sun_Constants(engine_constants);+ if (combiner.DrawEffect) engine_constants.DrawEffectParameters[3] = SunCasterOpacity;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 +1198,13 @@ RenderResult PosixDevice9::Gpu_Draw(const DrawCall &call)draw.StencilReference = RenderStates[D3DRS_STENCILREF] & 0xFF;draw.BlendFactor = RenderStates[D3DRS_BLENDFACTOR];Gpu->Record_Draw(draw);+ if (combiner.ShadowReceiving) {+ if (pixel_engine == ENGINE_SHADER_NONE) ++SunSolidReceivers;+ else ++SunGroundReceivers;+ if (Sun_Camera_Space()) ++SunCameraReceivers;+ if (RenderStates[D3DRS_ALPHABLENDENABLE]) ++SunAlphaReceivers;+ }+ if (SunActive && combiner.DrawEffect == DRAW_EFFECT_CLOAK_SHADOW) ++SunCloakCasters;++DrawsRecorded;if (vertex_engine != ENGINE_SHADER_NONE || pixel_engine != ENGINE_SHADER_NONE) {++EngineProgramDraws[EngineShader_Name((EngineShaderProgram)(vertex_engine != ENGINE_SHADER_NONEdiff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/PosixDevice9SunShadow.cpp b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/PosixDevice9SunShadow.cppnew file mode 100644index 000000000..572241828--- /dev/null+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/PosixDevice9SunShadow.cpp@@ -0,0 +1,411 @@+// Render-only sun capture. The snapshot owns COM references across caster queue flushes.+#include "PosixDevice9.h"+#include "SdlGpuFrame.h"+#include "SdlConstants.h"+#include "SdlPipelineCache.h"+#include "SdlRenderMatrix.h"+#include "engineshader.h"+#include "Platform/SunShadowMode.h"+#include "Platform/SunShadow.h"+#include "Platform/SunSmoke.h"+#include "ffshader.h"+#include <algorithm>+#include <cmath>+#include <cstring>+#include <cstdio>+#include <cstdlib>++// One list for declaration, capture and restoration, including shader register banks.+#define SUN_VALUES(X) \+ X(RenderStates) X(TextureStageStates) X(SamplerStates) X(Transforms) X(Viewport) \+ X(Material) X(Lights) X(LightsEnabled) X(ClipPlanes) X(StreamOffsets) X(StreamStrides) \+ X(DeclarationIsCurrent) X(FVF) X(VertexShaderConstants) X(PixelShaderConstants) X(SmokeGlow)+#define SUN_REFS(X) X(DepthStencil) X(Indices) X(Declaration) X(VertexShader) X(PixelShader)+#define SUN_REF_ARRAYS(X) X(RenderTargets) X(Textures) X(Streams)++struct PosixDevice9::SunCapture {+#define FIELD(name) decltype(PosixDevice9::name) name = {};+ SUN_VALUES(FIELD) SUN_REFS(FIELD) SUN_REF_ARRAYS(FIELD)+#undef FIELD+ SdlTarget Target = {};+ float ViewProjection[16] = {};+ unsigned FirstDraw = 0, Draws = 0;+ bool Receiving = false;+ bool SmokeFilled = false;+ float SmokeStrength = 0;+ uint64_t SceneGeneration = 0;+ SdlTarget Scene = {};+ D3DMATRIX SceneView = {}, SceneProjection = {};+ D3DVIEWPORT9 SceneViewport = {};+ float FromClip[16] = {}, WorldFromClip[16] = {}, Parameters[4] = {}, Softness[4] = {};+ SDL_GPUSampler *Sampler = nullptr; // owned by the device's sampler cache+ explicit SunCapture(PosixDevice9 &device) {+#define COPY(name) std::memcpy(&name, &device.name, sizeof(name));+ SUN_VALUES(COPY)+#undef COPY+#define HOLD(name) Posix_Bind(name, device.name);+#define HOLDS(name) for (unsigned i = 0; i < sizeof(name)/sizeof(name[0]); ++i) Posix_Bind(name[i], device.name[i]);+ SUN_REFS(HOLD) SUN_REF_ARRAYS(HOLDS)+#undef HOLD+#undef HOLDS+ }+ void Restore(PosixDevice9 &device) {+#define COPY(name) std::memcpy(&device.name, &name, sizeof(name));+ SUN_VALUES(COPY)+#undef COPY+#define BIND(name) Posix_Bind(device.name, name);+#define BINDS(name) for (unsigned i = 0; i < sizeof(name)/sizeof(name[0]); ++i) Posix_Bind(device.name[i], name[i]);+ SUN_REFS(BIND) SUN_REF_ARRAYS(BINDS)+#undef BIND+#undef BINDS+ Release();+ }+ void Release() {+#define DROP(name) if (name) { name->Release(); name = nullptr; }+#define DROPS(name) for (auto &object : name) if (object) { object->Release(); object = nullptr; }+ SUN_REFS(DROP) SUN_REF_ARRAYS(DROPS)+#undef DROP+#undef DROPS+ }+ ~SunCapture() { Release(); }+};+#undef SUN_VALUES+#undef SUN_REFS+#undef SUN_REF_ARRAYS++bool PosixDevice9::Begin_Sun_Shadow(unsigned size)+{+ // Refusing re-entry must leave the outer capture intact.+ if (SunActive || SunSceneExclusions) return false;+ SunReady = false;+ if (!Gpu || (!SunReceiverFailure.empty() && SunShadow::RequestedMode() == SunShadow::Mode::Mapped)) return false;+ SdlTarget target;+ std::string error;+ if (!Gpu->Sun_Shadow_Target(size, target, error)) {+ if (SunCaptureFailure != error)+ fprintf(stderr,"SunShadow: capture unavailable (%s); legacy shadows\n",error.c_str());+ SunCaptureFailure = error;+ return false;+ }+ SunCaptureFailure.clear();+ if (!SunSceneDepth) SunReceiversAtSceneStart = SunSolidReceivers + SunGroundReceivers;+ Sun = std::make_shared<SunCapture>(*this);+ Sun->Target = target;+ Sun->FirstDraw = DrawsRecorded;+ SunActive = true;+ SunCasterEffect = DRAW_EFFECT_NONE;+ SunFailed = false;+ Viewport = {0, 0, size, size, 0.0f, 1.0f};+ Gpu->Set_Target(target);+ Gpu->Clear_Back_Buffer(false, true, false, 0, 1.0f, 0);+ return true;+}++bool PosixDevice9::Sun_Target(SdlTarget &target) const+{+ if (!SunActive || !Sun) return false;+ target = Sun->Target;+ return true;+}++bool PosixDevice9::End_Sun_Shadow()+{+ if (!SunActive || !Sun) return false;+ const float *view = &Transforms[D3DTS_VIEW]._11;+ const float *projection = &Transforms[D3DTS_PROJECTION]._11;+ multiply(view, projection, Sun->ViewProjection);+ // Capture uses the D3D9 viewport displaced by +0.5 pixels. Convert nominal sun+ // clip coordinates to the texel centers actually written by that viewport.+ for (unsigned row=0; row<4; ++row) {+ Sun->ViewProjection[row*4] += Sun->ViewProjection[row*4+3] / Sun->Target.Width;+ Sun->ViewProjection[row*4+1] -= Sun->ViewProjection[row*4+3] / Sun->Target.Height;+ }+ Sun->Draws = DrawsRecorded - Sun->FirstDraw;+ // Submission failure must reach the stencil fallback before the engine decides who owns shadows.+ const bool submitted = Gpu->Flush();+ SunActive = false;+ SunCasterEffect = DRAW_EFFECT_NONE;+ Sun->Restore(*this);+ SdlTarget scene;+ std::string error;+ const bool restored = Resolve_Target(scene, error);+ if (restored) Gpu->Set_Target(scene);+ SunReady = submitted && restored && !SunFailed;+ return SunReady;+}++void PosixDevice9::Clear_Sun_Shadow()+{+ if (SunActive) End_Sun_Shadow();+ SunReady = false;+}++bool PosixDevice9::Fill_Sun_Smoke(const float *casters, unsigned count, float strength)+{+ if (!Gpu || SunActive || SunSceneExclusions) return false;+ if (Sun) Sun->SmokeFilled = false;+ if (!casters || !count) return Gpu->Fill_Sun_Smoke(nullptr,nullptr,0);+ if (!Sun || !SunReady || SunShadow::RequestedMode()!=SunShadow::Mode::Mapped+ || !std::isfinite(strength) || strength<0 || strength>1) return false;+ if (!Gpu->Fill_Sun_Smoke(Sun->ViewProjection,casters,count)) return false;+ Sun->SmokeFilled = Gpu->Sun_Smoke_Texture()!=nullptr;+ Sun->SmokeStrength = strength;+ return true;+}++void PosixDevice9::Set_Sun_Caster_Effect(unsigned effect, const float parameters[4])+{+ // Cosmetic scene effects need their own capture path. This pass implements only the+ // Windows cloak's shadow coverage, independently of Direct3D11_Draw_Effects().+ SunCasterEffect = SunActive && effect==DRAW_EFFECT_CLOAK_SHADOW ? effect : DRAW_EFFECT_NONE;+ SunCasterOpacity = parameters && std::isfinite(parameters[3]) ? std::max(0.0f,std::min(1.0f,parameters[3])) : 1.0f;+}++void PosixDevice9::Get_Sun_Caster_Effect(unsigned &effect, float parameters[4]) const+{+ effect = SunActive ? SunCasterEffect : DRAW_EFFECT_NONE;+ std::fill(parameters, parameters + 4, 0.0f);+ if (effect != DRAW_EFFECT_NONE) parameters[3] = SunCasterOpacity;+}++bool PosixDevice9::Read_Sun_Shadow(std::vector<float> &depth)+{+ depth.clear();+ return SunReady && Sun && Gpu->Read_Depth(Sun->Target.Depth, Sun->Target.Width, Sun->Target.Height, depth);+}++std::string PosixDevice9::Sun_Shadow_Report()+{+ std::vector<float> depth;+ if (!Read_Sun_Shadow(depth)) return "SDL sun capture unavailable" ++ (SunReceiverFailure.empty() ? std::string() : "; legacy fallback: " + SunReceiverFailure);+ unsigned covered=0;+ float nearest=1.0f, farthest=0.0f;+ for (float d : depth) if (d < 1.0f) {+ ++covered; nearest=std::min(nearest,d); farthest=std::max(farthest,d);+ }+ // Optional inspection of the latest report's map. Never read back or write files+ // in ordinary rendering; this path is reached only by the explicit report.+ if (const char *path = std::getenv("ZH_SUN_SHADOW_DEPTH_DUMP")) {+ if (FILE *file = std::fopen(path,"wb")) {+ std::fprintf(file,"P5\n# Row-vector world-to-shadow-clip matrix:");+ for (float value : Sun->ViewProjection) std::fprintf(file," %.9g",value);+ std::fprintf(file,"\n%u %u\n65535\n",Sun->Target.Width,Sun->Target.Height);+ std::vector<unsigned char> pixels(depth.size()*2);+ for (size_t i=0; i<depth.size(); ++i) {+ const float d = std::isfinite(depth[i]) ? std::max(0.0f,std::min(1.0f,depth[i])) : 1.0f;+ const unsigned value = unsigned(d*65535.0f+0.5f);+ pixels[2*i] = static_cast<unsigned char>(value>>8);+ pixels[2*i+1] = static_cast<unsigned char>(value&255);+ }+ const bool written = std::fwrite(pixels.data(),1,pixels.size(),file) == pixels.size();+ const int closed = std::fclose(file);+ if (!written || closed) std::fprintf(stderr,"SunShadow: depth dump write failed\n");+ } else std::fprintf(stderr,"SunShadow: depth dump open failed\n");+ }+ char line[360];+ std::snprintf(line,sizeof(line),"SDL sun %ux%u, %u draws, %u/%zu texels occupied, depth %.6f..%.6f, receiving=%u, cumulative receivers solid=%llu ground=%llu",+ Sun->Target.Width,Sun->Target.Height,Sun->Draws,covered,depth.size(),nearest,farthest,+ unsigned(Sun->Receiving && SunReceiverFailure.empty()),(unsigned long long)SunSolidReceivers,(unsigned long long)SunGroundReceivers);+ return std::string(line)+", smoke casters="+std::to_string(Sun->SmokeFilled ? Gpu->Sun_Smoke_Count() : 0)+ +", cumulative camera-space="+std::to_string(SunCameraReceivers)+ +" alpha="+std::to_string(SunAlphaReceivers)+" cloak casters="+std::to_string(SunCloakCasters);+}++bool PosixDevice9::Set_Sun_Shadow_Parameters(float bias, float strength, float widest, float narrowest,+ float texelsPerGap, float unitsPerDepth, float skyFill)+{+ if (!Sun || SunSceneExclusions || !SunReceiverFailure.empty()) return false;+ Sun->Receiving = false;+ if (!SunReady || SunActive || SunShadow::RequestedMode() != SunShadow::Mode::Mapped) return false;+ const float numbers[] = {bias,strength,widest,narrowest,texelsPerGap,unitsPerDepth,skyFill};+ for (float value : numbers) if (!std::isfinite(value)) return false;+ if (bias<0 || strength<0 || strength>1 || narrowest<0 || widest<narrowest || texelsPerGap<0+ || unitsPerDepth<=0 || skyFill<0 || skyFill>1 || !Viewport.Width || !Viewport.Height) return false;+ std::string error;+ if (!Resolve_Target(Sun->Scene,error) || !Sun->Scene.Colour || !Sun->Scene.Depth) return false;+ float sceneClip[16], inverse[16];+ multiply(&Transforms[D3DTS_VIEW]._11,&Transforms[D3DTS_PROJECTION]._11,sceneClip);+ if (!render_inverse(sceneClip,inverse)) return false;+ std::memcpy(Sun->WorldFromClip,inverse,sizeof(inverse));+ multiply(inverse,Sun->ViewProjection,Sun->FromClip);+ const float depthRange = Viewport.MaxZ - Viewport.MinZ;+ if (depthRange <= 1e-8f) return false;+ for (unsigned col=0; col<4; ++col) {+ const float z = Sun->FromClip[8+col] / depthRange;+ Sun->FromClip[12+col] -= Viewport.MinZ*z;+ Sun->FromClip[8+col] = z;+ }+ RenderUInt32 sampler[SAMPLER_STATE_COUNT] = {};+ sampler[D3DSAMP_ADDRESSU] = sampler[D3DSAMP_ADDRESSV] = sampler[D3DSAMP_ADDRESSW] = D3DTADDRESS_CLAMP;+ sampler[D3DSAMP_MINFILTER] = sampler[D3DSAMP_MAGFILTER] = D3DTEXF_POINT;+ sampler[D3DSAMP_MIPFILTER] = D3DTEXF_NONE;+ sampler[D3DSAMP_MAXANISOTROPY] = 1;+ Sun->Sampler = Samplers->Sampler(sampler);+ if (!Sun->Sampler) return false;+ Sun->SceneGeneration = SunSceneGeneration;+ Sun->SceneView = Transforms[D3DTS_VIEW];+ Sun->SceneProjection = Transforms[D3DTS_PROJECTION];+ Sun->SceneViewport = Viewport;+ const float parameters[] = {1.0f/Sun->Target.Width,bias,strength,widest};+ const float softness[] = {narrowest,texelsPerGap,unitsPerDepth,skyFill};+ std::memcpy(Sun->Parameters,parameters,sizeof(parameters));+ std::memcpy(Sun->Softness,softness,sizeof(softness));+ Sun->Receiving = true;+ return true;+}++void PosixDevice9::Fail_Sun_Receiver(const char *reason)+{+ if (!SunReceiverFailure.empty()) return;+ SunReceiverFailure = reason;+ const bool drawn = SunSolidReceivers + SunGroundReceivers != SunReceiversAtSceneStart;+ // Already-submitted mapped draws cannot be undone here. Do not add stencil+ // darkening over them; retain this scene's ownership and use legacy next scene.+ if (Sun && !drawn) Sun->Receiving = false;+ fprintf(stderr,"SunShadow: receiver failure (%s); ordinary draw retry, legacy shadows %s\n",+ reason,drawn ? "from next scene" : "in this scene");+ // Failed program/pipeline keys remain cached, so the latch lasts for the device.+}++bool PosixDevice9::Sun_Camera_Space() const+{+ static const float identity[16]={1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1};+ return Transforms[D3DTS_PROJECTION]._34!=0+ && std::memcmp(&Transforms[D3DTS_VIEW],identity,sizeof(identity))==0;+}++bool PosixDevice9::Sun_Receives_Target(const SdlTarget &target) const+{+ return Sun && SunReady && Sun->Receiving && !SunActive && !SunSceneExclusions+ && SunShadow::RequestedMode() == SunShadow::Mode::Mapped+ && target.Colour == Sun->Scene.Colour && target.Depth == Sun->Scene.Depth+ && target.Width == Sun->Scene.Width && target.Height == Sun->Scene.Height+ && std::memcmp(&Viewport,&Sun->SceneViewport,sizeof(Viewport)) == 0+ && (Sun_Camera_Space() || std::memcmp(&Transforms[D3DTS_VIEW],&Sun->SceneView,sizeof(D3DMATRIX)) == 0)+ && std::memcmp(&Transforms[D3DTS_PROJECTION],&Sun->SceneProjection,sizeof(D3DMATRIX)) == 0;+}++bool PosixDevice9::Sun_Receives_View()+{+ if (!Gpu || !Sun || !SunReady || !SunReceiverFailure.empty()) return false;+ SdlTarget target;+ std::string error;+ return Resolve_Target(target,error) && Sun_Receives_Target(target);+}++bool PosixDevice9::Enter_Sun_Scene(bool eligible)+{+ const bool owns = eligible && SunSceneDepth == 0;+ ++SunSceneDepth;+ if (owns) {+ Clear_Sun_Shadow();+ SunReceiversAtSceneStart = SunSolidReceivers + SunGroundReceivers;+ ++SunSceneGeneration;+ } else ++SunSceneExclusions;+ return owns;+}++void PosixDevice9::Leave_Sun_Scene(bool eligible)+{+ if (!SunSceneDepth) return;+ if (!eligible && SunSceneExclusions) --SunSceneExclusions;+ --SunSceneDepth;+ if (eligible) Clear_Sun_Shadow(); // recorded draws already own their constants/bindings+}++bool PosixDevice9::Sun_Owns_Scene_Shadows()+{+ SdlTarget target;+ std::string error;+ if (!SunSceneDepth) // direct-device callers retain the same late-failure rule+ return Gpu && Sun && SunReady && Resolve_Target(target,error) && Sun_Receives_Target(target);+ return Sun && SunReady && Sun->Receiving && !SunActive && !SunSceneExclusions+ && Sun->SceneGeneration == SunSceneGeneration+ && SunShadow::RequestedMode() == SunShadow::Mode::Mapped+ && Resolve_Target(target,error)+ && target.Colour == Sun->Scene.Colour && target.Depth == Sun->Scene.Depth+ && target.Width == Sun->Scene.Width && target.Height == Sun->Scene.Height+ && std::memcmp(&Viewport,&Sun->SceneViewport,sizeof(Viewport)) == 0;+}++void PosixDevice9::Exclude_Sun_Receivers(bool exclude)+{+ if (exclude) ++SunExclusions;+ else if (SunExclusions) --SunExclusions;+}++bool PosixDevice9::Sun_Receiving(int vertexProgram, int pixelProgram, const SdlTarget &target) const+{+ if (SunExclusions || !SunReceiverFailure.empty() || !Sun_Receives_Target(target) || (FVF & D3DFVF_XYZRHW)+ || !RenderStates[D3DRS_ZENABLE] || RenderStates[D3DRS_FILLMODE] != D3DFILL_SOLID+ || (RenderStates[D3DRS_COLORWRITEENABLE] & 7u) != 7u) return false;+ const bool ground = EngineShader_Paints_Ground(static_cast<EngineShaderProgram>(pixelProgram));+ if (pixelProgram != ENGINE_SHADER_NONE && !ground) return false;+ if (vertexProgram != ENGINE_SHADER_NONE && vertexProgram != ENGINE_SHADER_TREES) return false;+ // Match Windows: ordinary alpha surfaces/particles receive even without depth writes.+ // Additive light and multiplicative overlays retain their authored contribution.+ if (RenderStates[D3DRS_ALPHABLENDENABLE]) {+ const unsigned source=RenderStates[D3DRS_SRCBLEND], destination=RenderStates[D3DRS_DESTBLEND];+ if (source==D3DBLEND_ONE || destination==D3DBLEND_ONE || source==D3DBLEND_DESTCOLOR+ || destination==D3DBLEND_DESTCOLOR || destination==D3DBLEND_SRCCOLOR+ || destination==D3DBLEND_INVSRCCOLOR) return false;+ }+ return true;+}++void PosixDevice9::Build_Sun_Constants(SdlEnginePixelConstants &constants) const+{+ std::memcpy(constants.ShadowFromClip,Sun->FromClip,sizeof(Sun->FromClip));+ std::memcpy(constants.ShadowParameters,Sun->Parameters,sizeof(Sun->Parameters));+ std::memcpy(constants.ShadowSoftness,Sun->Softness,sizeof(Sun->Softness));+ constants.ShadowViewport[0] = 1.0f/Viewport.Width;+ constants.ShadowViewport[1] = 1.0f/Viewport.Height;+ constants.ShadowViewport[2] = Viewport.X+0.5f;+ constants.ShadowViewport[3] = Viewport.Y+0.5f;+ constants.VolumeParameters[0] = Sun->SmokeFilled ? Sun->SmokeStrength : 0;+ constants.VolumeParameters[1] = Sun->SmokeFilled ? SunSmoke::SelfGain : 0;+ constants.VolumeParameters[2] = Sun_Camera_Space() ? 1 : 0;+ constants.VolumeParameters[3] = SunSmoke::SelfCurve;+ std::memcpy(constants.WorldFromClip,Sun->WorldFromClip,sizeof(Sun->WorldFromClip));+ // Headlight/Blast counts stay zero. Linux still supplies its existing vertex lights.+}+SDL_GPUTexture *PosixDevice9::Sun_Texture() const { return Sun ? Sun->Target.Depth : nullptr; }+SDL_GPUSampler *PosixDevice9::Sun_Sampler() const { return Sun ? Sun->Sampler : nullptr; }++namespace SunShadow {+bool FillSmoke(IDirect3DDevice9 *d,const float *c,unsigned n,float s) { return d && static_cast<PosixDevice9*>(d)->Fill_Sun_Smoke(c,n,s); }+bool CasterEffects(IDirect3DDevice9 *d) { return d && static_cast<PosixDevice9*>(d)->Get_Gpu(); }+void SetCasterEffect(IDirect3DDevice9 *d,unsigned e,const float p[4]) { if(d) static_cast<PosixDevice9*>(d)->Set_Sun_Caster_Effect(e,p); }+CasterEffect GetCasterEffect(IDirect3DDevice9 *d) {+ CasterEffect effect;+ if (d) static_cast<PosixDevice9*>(d)->Get_Sun_Caster_Effect(effect.Effect, effect.Parameters);+ return effect;+}+void SetSmokeGlow(IDirect3DDevice9 *d,bool g) { if(d) static_cast<PosixDevice9*>(d)->Set_Smoke_Glow(g); }+bool Begin(IDirect3DDevice9 *device, unsigned size)+{+#if defined(__linux__)+ return device && static_cast<PosixDevice9 *>(device)->Begin_Sun_Shadow(size);+#else+ return false; // Preserve the existing macOS scene shadows.+#endif+}+bool End(IDirect3DDevice9 *d) { return d && static_cast<PosixDevice9*>(d)->End_Sun_Shadow(); }+void Clear(IDirect3DDevice9 *d) {+ // A nested view's renderShadowMap starts with Clear, even when Begin will be+ // refused. Leave the owning scene's map intact; reset/destruction clear directly.+ if (d && !static_cast<PosixDevice9*>(d)->Sun_Scene_Excluded())+ static_cast<PosixDevice9*>(d)->Clear_Sun_Shadow();+}+bool Parameters(IDirect3DDevice9 *d,float b,float s,float w,float n,float t,float u,float f) {+ return d && static_cast<PosixDevice9*>(d)->Set_Sun_Shadow_Parameters(b,s,w,n,t,u,f);+}+bool ReceivesView(IDirect3DDevice9 *d) { return d && static_cast<PosixDevice9*>(d)->Sun_Receives_View(); }+bool OwnsSceneShadows(IDirect3DDevice9 *d) { return d && static_cast<PosixDevice9*>(d)->Sun_Owns_Scene_Shadows(); }+bool EnterScene(IDirect3DDevice9 *d,bool eligible) { return d && static_cast<PosixDevice9*>(d)->Enter_Sun_Scene(eligible); }+void LeaveScene(IDirect3DDevice9 *d,bool eligible) { if (d) static_cast<PosixDevice9*>(d)->Leave_Sun_Scene(eligible); }+void ExcludeReceivers(IDirect3DDevice9 *d,bool exclude) { if (d) static_cast<PosixDevice9*>(d)->Exclude_Sun_Receivers(exclude); }+bool ReceiversExcluded(IDirect3DDevice9 *d) { return d && static_cast<PosixDevice9*>(d)->Sun_Receivers_Excluded(); }+std::string Report(IDirect3DDevice9 *d) { return d ? static_cast<PosixDevice9*>(d)->Sun_Shadow_Report() : "no device"; }+}diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlConstants.h b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlConstants.hindex f96fe2483..b2908eb8e 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlConstants.h+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlConstants.h@@ -25,9 +25,8 @@** declares a prefix of its block, and a longer push is legal. Every field is a float4 or a row-major** float4x4, so HLSL's packing and std140, which SDL3 asks for, agree.**-** The pixel block stops after the alpha reference: the fields after it serve the Direct3D 11 backend's-** own additions (normal maps, the shadow map, the sky), which A3 does not draw - A3 draws the Direct 3D 9-** picture.+** Ordinary combiners upload the small prefix. Sun/smoke receivers and cloak casters upload+** the shared extended engine block without changing the emulated register banks.*/#pragma once@@ -35,6 +34,7 @@#ifndef SDLCONSTANTS_H#define SDLCONSTANTS_H+#include <cstddef>#include "ffvertex.h" // MAXIMUM_VERTEX_STAGES, MAXIMUM_VERTEX_LIGHTSstruct SdlVertexConstants@@ -61,12 +61,8 @@ struct SdlPixelConstantsfloat AlphaReference[4]; ///< .x is D3DRS_ALPHAREF as a whole level, 0 to 255};-/// 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-/// normal maps taken out on 2026-10-06 and the fork's Direct3D 11 additions, which A3e does not-/// draw, and stay zero: zero shadow parameters-/// read as a pixel the sun reaches.+/// Shared engine/generated receiver b0 layout. Normal-map and sky fields remain zero;+/// eligible receivers fill sun/smoke fields; Windows per-pixel light counts remain zero.struct SdlEnginePixelConstants{SdlPixelConstants Combiner;@@ -80,8 +76,18 @@ struct SdlEnginePixelConstantsfloat ShadowSoftness[4];float Sky[4];float SkyUp[4];+ float VolumeParameters[4];+ float WorldFromClip[16];+ float HeadlightParameters[4];+ float HeadlightPosition[16][4], HeadlightDirection[16][4];+ float BlastLightParameters[4];+ float BlastLightPosition[32][4], BlastLightDiffuse[32][4], BlastLightAmbient[32][4];+ float SoftParticleDepth[4];+ float DrawEffectParameters[4];};-static_assert(sizeof(SdlEnginePixelConstants) == 22 * 16, "PixelConstantBlock's 22 float4s");+static_assert(sizeof(SdlEnginePixelConstants) == 159 * 16, "shared PixelConstantBlock packing");+static_assert(offsetof(SdlEnginePixelConstants, VolumeParameters) == 22 * 16, "smoke follows SkyUp");+static_assert(offsetof(SdlEnginePixelConstants, DrawEffectParameters) == 158 * 16, "caster opacity follows soft depth");static_assert(sizeof(SdlVertexConstants) % 16 == 0 && sizeof(SdlPixelConstants) % 16 == 0,"whole float4s, as std140 lays them out");diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrame.cpp b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrame.cppindex b78d2328e..c5fd5e84d 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrame.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrame.cpp@@ -196,6 +196,8 @@ SdlGpuFrame::~SdlGpuFrame()Release_Targets();Commands.clear();End_Batch();+ Release_Sun_Smoke();+ Release_Sun_Shadow();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]);diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrame.h b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrame.hindex 6bca8483d..7c9378189 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrame.h+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrame.h@@ -57,6 +57,8 @@ struct SdlTargetSDL_GPUTexture * Depth;uint32_t Width;uint32_t Height;+ // Zero retains the scene format; independent depth-only targets name their format.+ uint32_t DepthFormat = 0;};/// One draw as the flush replays it, everything by value. The device's resolve fills it.@@ -110,6 +112,16 @@ public:/// Where the clears and draws recorded from now on go (A3d); the back buffer until told otherwise.void Set_Target(const SdlTarget & target);SdlTarget Back_Buffer_Target() const;+ unsigned int Target_Depth_Format(const SdlTarget &target) const;+ /// Sampleable sun depth, retired only after previously recorded readers are submitted.+ bool Sun_Shadow_Target(unsigned int size, SdlTarget &target, std::string &error);+ bool Fill_Sun_Smoke(const float *sun, const float *casters, unsigned count);+ SDL_GPUTexture *Sun_Smoke_Texture() const;+ SDL_GPUSampler *Sun_Smoke_Sampler() const;+ bool Read_Sun_Smoke(std::vector<float> &moments);+ unsigned Sun_Smoke_Count() const { return SmokeCount; }+ /// Diagnostic scalar readback; no scene-depth snapshot or attachment mutation.+ bool Read_Depth(SDL_GPUTexture *texture, unsigned width, unsigned height, std::vector<float> &depth);/// A depth-stencil of this size for a render target the back buffer's does not fit, made once and/// kept. D3D9 lets a smaller target borrow the bigger depth surface; SDL3 GPU wants one size per pass.SDL_GPUTexture * Depth_For(unsigned int width, unsigned int height);@@ -269,6 +281,23 @@ private:SDL_GPUTexture * BackBuffer;SDL_GPUTexture * DepthStencil;SDL_GPUTexture * FrontCopy; ///< the last presented picture+ SDL_GPUTexture *SunShadowTexture = NULL;+ unsigned SunShadowSize = 0;+ struct SmokeResources;+ SmokeResources *Smoke = NULL;+ bool SmokeFailed = false;+ unsigned SmokeCount = 0;+ bool Create_Sun_Smoke();+ void Release_Sun_Smoke();+ bool Fail_Sun_Smoke(const char *reason);+ // The depth reader is diagnostic-only and samples the independent sun target.+ SDL_GPUShader *SunDepthVertex = NULL, *SunDepthPixel = NULL;+ SDL_GPUGraphicsPipeline *SunDepthPipeline = NULL;+ SDL_GPUSampler *SunDepthSampler = NULL;+ bool Create_Sun_Depth_Reader();+ bool Resolve_Sun_Depth(struct SDL_GPUCommandBuffer *commands, SDL_GPUTexture *source,+ SDL_GPUTexture *destination, unsigned width, unsigned height);+ void Release_Sun_Shadow();bool Copy_To_Front(struct SDL_GPUCommandBuffer * commands);unsigned int DepthFormat; ///< an SDL_GPUTextureFormat: D24S8 where there is one, else D32S8unsigned int BackWidth;diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrameBatch.cpp b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrameBatch.cppindex fb824ca26..a1ea8a27b 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrameBatch.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrameBatch.cpp@@ -210,7 +210,7 @@ void SdlGpuFrame::Release_After_Batch(SDL_GPUTexture * texture, SDL_GPUBuffer *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) {@@ -341,18 +341,28 @@ bool SdlGpuFrame::Begin_Pass(SDL_GPUCommandBuffer * commands, const SdlTarget &depth.clear_stencil = (Uint8)stencil_value;depth.load_op = clear_depth ? SDL_GPU_LOADOP_CLEAR : SDL_GPU_LOADOP_LOAD;depth.store_op = SDL_GPU_STOREOP_STORE;- depth.stencil_load_op = clear_stencil ? SDL_GPU_LOADOP_CLEAR : SDL_GPU_LOADOP_LOAD;- depth.stencil_store_op = SDL_GPU_STOREOP_STORE;- *pass = SDL_BeginGPURenderPass(commands, &colour, 1, &depth);+ const unsigned format = Target_Depth_Format(target);+ const bool has_stencil = format == SDL_GPU_TEXTUREFORMAT_D24_UNORM_S8_UINT+ || format == SDL_GPU_TEXTUREFORMAT_D32_FLOAT_S8_UINT;+ depth.stencil_load_op = !has_stencil ? SDL_GPU_LOADOP_DONT_CARE+ : clear_stencil ? SDL_GPU_LOADOP_CLEAR : SDL_GPU_LOADOP_LOAD;+ depth.stencil_store_op = has_stencil ? SDL_GPU_STOREOP_STORE : SDL_GPU_STOREOP_DONT_CARE;+ *pass = SDL_BeginGPURenderPass(commands, target.Colour ? &colour : NULL, target.Colour ? 1 : 0,+ target.Depth ? &depth : NULL);return *pass != NULL;}SdlTarget SdlGpuFrame::Back_Buffer_Target() const{- SdlTarget target = { BackBuffer, DepthStencil, BackWidth, BackHeight };+ SdlTarget target = { BackBuffer, DepthStencil, BackWidth, BackHeight, DepthFormat };return target;}+unsigned int SdlGpuFrame::Target_Depth_Format(const SdlTarget &target) const+{+ return target.Depth ? (target.DepthFormat ? target.DepthFormat : DepthFormat) : 0;+}+void SdlGpuFrame::Set_Target(const SdlTarget & target){CurrentTarget = target;@@ -363,7 +373,8 @@ uint32_t SdlGpuFrame::Target_Index(){const SdlTarget target = TargetSet ? CurrentTarget : Back_Buffer_Target();for (size_t i = Targets.size(); i-- > 0; ) {- if (Targets[i].Colour == target.Colour && Targets[i].Depth == target.Depth) {+ if (Targets[i].Colour == target.Colour && Targets[i].Depth == target.Depth+ && Targets[i].DepthFormat == target.DepthFormat && Targets[i].Width == target.Width && Targets[i].Height == target.Height) {return (uint32_t)i;}}diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrameSmoke.cpp b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrameSmoke.cppnew file mode 100644index 000000000..a6e2adeab--- /dev/null+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrameSmoke.cpp@@ -0,0 +1,184 @@+// Native smoke moments. The scene's colour/depth attachments and CPU state are untouched.+#include "SdlGpuFrame.h"+#include "SdlSunShadowDebug.h"+#include "Platform/SunSmoke.h"+#include "sdl3shadercompile.h"+#include <SDL3/SDL.h>+#include <cstring>+#include <cstdio>++struct SdlGpuFrame::SmokeResources {+ SDL_GPUTexture *Texture = nullptr;+ SDL_GPUSampler *Sampler = nullptr;+ SDL_GPUShader *Vertex = nullptr, *Pixel = nullptr;+ SDL_GPUGraphicsPipeline *Pipeline = nullptr;+ SDL_GPUBuffer *Instances = nullptr;+ SDL_GPUTransferBuffer *Upload = nullptr;+ std::vector<float> Splats;+};++void SdlGpuFrame::Release_Sun_Smoke()+{+ if (!Smoke) return;+ if (Smoke->Texture) SDL_ReleaseGPUTexture(GpuDevice, Smoke->Texture);+ if (Smoke->Sampler) SDL_ReleaseGPUSampler(GpuDevice, Smoke->Sampler);+ if (Smoke->Vertex) SDL_ReleaseGPUShader(GpuDevice, Smoke->Vertex);+ if (Smoke->Pixel) SDL_ReleaseGPUShader(GpuDevice, Smoke->Pixel);+ if (Smoke->Pipeline) SDL_ReleaseGPUGraphicsPipeline(GpuDevice, Smoke->Pipeline);+ if (Smoke->Instances) SDL_ReleaseGPUBuffer(GpuDevice, Smoke->Instances);+ if (Smoke->Upload) SDL_ReleaseGPUTransferBuffer(GpuDevice, Smoke->Upload);+ delete Smoke; Smoke = nullptr; SmokeCount = 0;+}++bool SdlGpuFrame::Fail_Sun_Smoke(const char *reason)+{+ if (!SmokeFailed) std::fprintf(stderr,"SunShadow: smoke map unavailable (%s); legacy particle shadows\n",reason);+ // Keep resources until destruction: a previously recorded receiver may still reference them.+ SmokeFailed = true; SmokeCount = 0;+ return false;+}++bool SdlGpuFrame::Create_Sun_Smoke()+{+ if (SmokeFailed) return false;+ if (Smoke) return true;+ if (Sdl_Sun_Shadow_Fault("smoke-target")) return Fail_Sun_Smoke("injected smoke target failure");+ const auto format = SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;+ const auto usage = SDL_GPU_TEXTUREUSAGE_COLOR_TARGET | SDL_GPU_TEXTUREUSAGE_SAMPLER;+ if (!SDL_GPUTextureSupportsFormat(GpuDevice,format,SDL_GPU_TEXTURETYPE_2D,usage))+ return Fail_Sun_Smoke("RGBA32F colour target/sampler unsupported");+ Smoke = new SmokeResources;+ SDL_GPUTextureCreateInfo texture = {};+ texture.type = SDL_GPU_TEXTURETYPE_2D; texture.format = format; texture.usage = usage;+ texture.width = texture.height = SunSmoke::Texels;+ texture.layer_count_or_depth = texture.num_levels = 1;+ Smoke->Texture = SDL_CreateGPUTexture(GpuDevice,&texture);+ SDL_GPUSamplerCreateInfo sampler = {};+ sampler.min_filter = sampler.mag_filter = SDL_GPU_FILTER_LINEAR;+ 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;+ Smoke->Sampler = SDL_CreateGPUSampler(GpuDevice,&sampler);+ SDL_GPUBufferCreateInfo buffer = {};+ buffer.usage = SDL_GPU_BUFFERUSAGE_VERTEX;+ buffer.size = SunSmoke::MaxCasters * SunSmoke::SplatFloats * sizeof(float);+ Smoke->Instances = SDL_CreateGPUBuffer(GpuDevice,&buffer);+ SDL_GPUTransferBufferCreateInfo transfer = {};+ transfer.usage = SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD; transfer.size = buffer.size;+ Smoke->Upload = SDL_CreateGPUTransferBuffer(GpuDevice,&transfer);+ if (!Smoke->Texture || !Smoke->Sampler || !Smoke->Instances || !Smoke->Upload)+ return Fail_Sun_Smoke(SDL_GetError());+ // These two stages have matching declaration-order varyings and no resources/uniforms.+ // Explicit instance locations avoid depending on the compiler's semantic assignment.+ std::string vertex = SunSmoke::SMOKE_SPLAT_VERTEX_PROGRAM;+ vertex.insert(vertex.find("float4 Centre"),"[[vk::location(0)]] ");+ vertex.insert(vertex.find("float2 Shape"),"[[vk::location(1)]] ");+ std::vector<unsigned char> spirv; std::string error;+ if (!SDL3_Compile_HLSL_To_SPIRV(vertex,true,spirv,error)+ || !(Smoke->Vertex = SDL3_Create_Shader(GpuDevice,spirv,true,error))+ || !SDL3_Compile_HLSL_To_SPIRV(SunSmoke::SMOKE_SPLAT_PIXEL_PROGRAM,false,spirv,error)+ || !(Smoke->Pixel = SDL3_Create_Shader(GpuDevice,spirv,false,error)))+ return Fail_Sun_Smoke(error.c_str());+ if (Sdl_Sun_Shadow_Fault("smoke-pipeline")) return Fail_Sun_Smoke("injected smoke pipeline failure");+ SDL_GPUVertexBufferDescription input = {};+ input.pitch = SunSmoke::SplatFloats * sizeof(float);+ input.input_rate = SDL_GPU_VERTEXINPUTRATE_INSTANCE;+ SDL_GPUVertexAttribute attributes[2] = {};+ attributes[0].format = SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4;+ attributes[1].location = 1; attributes[1].offset = 4*sizeof(float);+ attributes[1].format = SDL_GPU_VERTEXELEMENTFORMAT_FLOAT2;+ SDL_GPUColorTargetDescription target = {}; target.format = format;+ auto &blend = target.blend_state;+ blend.enable_blend = true;+ blend.src_color_blendfactor = blend.dst_color_blendfactor = SDL_GPU_BLENDFACTOR_ONE;+ blend.color_blend_op = SDL_GPU_BLENDOP_ADD;+ blend.src_alpha_blendfactor = blend.dst_alpha_blendfactor = SDL_GPU_BLENDFACTOR_ONE;+ blend.alpha_blend_op = SDL_GPU_BLENDOP_MIN;+ SDL_GPUGraphicsPipelineCreateInfo pipeline = {};+ pipeline.vertex_shader = Smoke->Vertex; pipeline.fragment_shader = Smoke->Pixel;+ pipeline.vertex_input_state.vertex_buffer_descriptions = &input;+ pipeline.vertex_input_state.num_vertex_buffers = 1;+ pipeline.vertex_input_state.vertex_attributes = attributes;+ pipeline.vertex_input_state.num_vertex_attributes = 2;+ pipeline.primitive_type = SDL_GPU_PRIMITIVETYPE_TRIANGLESTRIP;+ pipeline.rasterizer_state.cull_mode = SDL_GPU_CULLMODE_NONE;+ pipeline.rasterizer_state.fill_mode = SDL_GPU_FILLMODE_FILL;+ pipeline.target_info.color_target_descriptions = ⌖+ pipeline.target_info.num_color_targets = 1;+ Smoke->Pipeline = SDL_CreateGPUGraphicsPipeline(GpuDevice,&pipeline);+ return Smoke->Pipeline || Fail_Sun_Smoke(SDL_GetError());+}++bool SdlGpuFrame::Fill_Sun_Smoke(const float *sun, const float *casters, unsigned count)+{+ SmokeCount = 0;+ if (!casters || !count) return !SmokeFailed;+ if (!Create_Sun_Smoke()) return false;+ const unsigned splats = SunSmoke::Project(sun,casters,count,Smoke->Splats);+ if (!splats) return true;+ // All previously queued readers must be submitted before this overwrite. GPU submissions+ // run in order; cycling the upload and vertex buffer protects their in-flight versions.+ if (!Flush()) return Fail_Sun_Smoke("queued reader submission failed");+ void *mapped = SDL_MapGPUTransferBuffer(GpuDevice,Smoke->Upload,true);+ if (!mapped) return Fail_Sun_Smoke(SDL_GetError());+ const Uint32 bytes = splats * SunSmoke::SplatFloats * sizeof(float);+ std::memcpy(mapped,Smoke->Splats.data(),bytes);+ SDL_UnmapGPUTransferBuffer(GpuDevice,Smoke->Upload);+ SDL_GPUCommandBuffer *commands = SDL_AcquireGPUCommandBuffer(GpuDevice);+ if (!commands) return Fail_Sun_Smoke(SDL_GetError());+ SDL_GPUCopyPass *copy = SDL_BeginGPUCopyPass(commands);+ if (!copy) { SDL_CancelGPUCommandBuffer(commands); return Fail_Sun_Smoke(SDL_GetError()); }+ SDL_GPUTransferBufferLocation source = {}; source.transfer_buffer = Smoke->Upload;+ SDL_GPUBufferRegion destination = {}; destination.buffer = Smoke->Instances; destination.size = bytes;+ SDL_UploadToGPUBuffer(copy,&source,&destination,true);+ SDL_EndGPUCopyPass(copy);+ SDL_GPUColorTargetInfo colour = {}; colour.texture = Smoke->Texture;+ colour.clear_color.a = 1; colour.load_op = SDL_GPU_LOADOP_CLEAR; colour.store_op = SDL_GPU_STOREOP_STORE;+ // Do not cycle the map: already submitted readers use this version, and the ordered write+ // must be the one subsequently queued receivers sample.+ SDL_GPURenderPass *pass = SDL_BeginGPURenderPass(commands,&colour,1,nullptr);+ if (!pass) { SDL_CancelGPUCommandBuffer(commands); return Fail_Sun_Smoke(SDL_GetError()); }+ SDL_BindGPUGraphicsPipeline(pass,Smoke->Pipeline);+ SDL_GPUBufferBinding binding = {}; binding.buffer = Smoke->Instances;+ SDL_BindGPUVertexBuffers(pass,0,&binding,1);+ SDL_DrawGPUPrimitives(pass,4,splats,0,0);+ SDL_EndGPURenderPass(pass);+ if (!(SerializeSubmits ? Submit(commands) : Submit_Flush(commands)))+ return Fail_Sun_Smoke("smoke submission failed");+ SmokeCount = splats;+ return true;+}++SDL_GPUTexture *SdlGpuFrame::Sun_Smoke_Texture() const { return SmokeCount && Smoke ? Smoke->Texture : nullptr; }+SDL_GPUSampler *SdlGpuFrame::Sun_Smoke_Sampler() const { return Smoke ? Smoke->Sampler : nullptr; }++// Explicit tests/reports only. Four float channels cannot use the BGRA8 scene download.+bool SdlGpuFrame::Read_Sun_Smoke(std::vector<float> &moments)+{+ moments.clear();+ if (!Sun_Smoke_Texture() || !Flush()) return false;+ SDL_GPUTransferBufferCreateInfo info = {};+ info.usage = SDL_GPU_TRANSFERBUFFERUSAGE_DOWNLOAD;+ info.size = SunSmoke::Texels * SunSmoke::Texels * 4 * sizeof(float);+ SDL_GPUTransferBuffer *transfer = SDL_CreateGPUTransferBuffer(GpuDevice,&info);+ if (!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; }+ SDL_GPUTextureRegion region = {}; region.texture = Smoke->Texture;+ region.w = region.h = SunSmoke::Texels; region.d = 1;+ SDL_GPUTextureTransferInfo target = {}; target.transfer_buffer = transfer;+ target.pixels_per_row = target.rows_per_layer = SunSmoke::Texels;+ SDL_DownloadFromGPUTexture(copy,®ion,&target);+ SDL_EndGPUCopyPass(copy);+ SDL_GPUFence *fence = SDL_SubmitGPUCommandBufferAndAcquireFence(commands);+ bool ok = fence && SDL_WaitForGPUFences(GpuDevice,true,&fence,1);+ if (fence) SDL_ReleaseGPUFence(GpuDevice,fence);+ if (ok) {+ const float *mapped = static_cast<const float*>(SDL_MapGPUTransferBuffer(GpuDevice,transfer,false));+ ok = mapped != nullptr;+ if (ok) { moments.assign(mapped,mapped+info.size/sizeof(float)); SDL_UnmapGPUTransferBuffer(GpuDevice,transfer); }+ }+ SDL_ReleaseGPUTransferBuffer(GpuDevice,transfer);+ return ok;+}diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrameSunShadow.cpp b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrameSunShadow.cppnew file mode 100644index 000000000..d8d72c091--- /dev/null+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrameSunShadow.cpp@@ -0,0 +1,174 @@+// Independent sun-depth allocation and diagnostic readback. No scene attachments are sampled.+#include "SdlGpuFrame.h"+#include "SdlSunShadowDebug.h"+#include "sdl3shadercompile.h"+#include <SDL3/SDL.h>+#include <cstdio>+#include <cstring>++// A depth-to-R32 pass avoids backend-specific raw depth download restrictions.+static const char SUN_DEPTH_VERTEX_HLSL[] =+ "struct Output\n"+ "{\n"+ " float4 Position : SV_Position;\n"+ " [[vk::location(0)]] float2 Uv : TEXCOORD0;\n"+ "};\n"+ "Output main(uint id : SV_VertexID)\n"+ "{\n"+ " Output output;\n"+ " float2 corner = float2(id == 1 ? 3.0 : -1.0, id == 2 ? 3.0 : -1.0);\n"+ " output.Position = float4(corner, 0.0, 1.0);\n"+ " output.Uv = float2(corner.x * 0.5 + 0.5, 0.5 - corner.y * 0.5);\n"+ " return output;\n"+ "}\n";++static const char SUN_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 SdlGpuFrame::Sun_Shadow_Target(unsigned int size, SdlTarget &target, std::string &error)+{+ target = {};+ const SDL_GPUTextureFormat format = SDL_GPU_TEXTUREFORMAT_D32_FLOAT;+ const SDL_GPUTextureUsageFlags usage = SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET | SDL_GPU_TEXTUREUSAGE_SAMPLER;+ if (size == 0 || size > 8192 || !SDL_GPUTextureSupportsFormat(GpuDevice, format, SDL_GPU_TEXTURETYPE_2D, usage)) {+ error = "unsupported sampleable sun depth target or size";+ return false;+ }+ if (!SunShadowTexture || SunShadowSize != size) {+ SDL_GPUTextureCreateInfo info = {};+ info.type = SDL_GPU_TEXTURETYPE_2D;+ info.format = format;+ info.usage = usage;+ info.width = info.height = size;+ info.layer_count_or_depth = info.num_levels = 1;+ info.sample_count = SDL_GPU_SAMPLECOUNT_1;+ SDL_GPUTexture *replacement = nullptr;+ if (Sdl_Sun_Shadow_Fault("target")) SDL_SetError("injected sun depth allocation failure");+ else replacement = SDL_CreateGPUTexture(GpuDevice, &info);+ if (!replacement) { error = SDL_GetError(); return false; }+ if (SunShadowTexture) Release_After_Batch(SunShadowTexture, NULL);+ SunShadowTexture = replacement;+ SunShadowSize = size;+ }+ target = { NULL, SunShadowTexture, size, size, (uint32_t)format };+ error.clear();+ return true;+}++bool SdlGpuFrame::Create_Sun_Depth_Reader()+{+ if (SunDepthPipeline && SunDepthSampler) return true;+ std::string log;+ if (!SunDepthVertex) {+ std::vector<unsigned char> spirv;+ if (!SDL3_Compile_HLSL_To_SPIRV(SUN_DEPTH_VERTEX_HLSL, true, spirv, log)+ || !(SunDepthVertex = SDL3_Create_Shader(GpuDevice, spirv, true, log))) {+ fprintf(stderr, "SdlGpuFrame: sun depth reader vertex: %s\n", log.c_str());+ return false;+ }+ }+ if (!SunDepthPixel) {+ std::vector<unsigned char> spirv;+ if (!SDL3_Compile_HLSL_To_SPIRV(SUN_DEPTH_PIXEL_HLSL, false, spirv, log)+ || !(SunDepthPixel = SDL3_Create_Shader(GpuDevice, spirv, false, log))) {+ fprintf(stderr, "SdlGpuFrame: sun depth reader pixel: %s\n", log.c_str());+ return false;+ }+ }+ if (!SunDepthPipeline) {+ SDL_GPUColorTargetDescription target = {};+ target.format = SDL_GPU_TEXTUREFORMAT_R32_FLOAT;+ SDL_GPUGraphicsPipelineCreateInfo info = {};+ info.vertex_shader = SunDepthVertex;+ info.fragment_shader = SunDepthPixel;+ info.primitive_type = SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;+ info.rasterizer_state.fill_mode = SDL_GPU_FILLMODE_FILL;+ info.rasterizer_state.cull_mode = SDL_GPU_CULLMODE_NONE;+ info.target_info.color_target_descriptions = ⌖+ info.target_info.num_color_targets = 1;+ SunDepthPipeline = SDL_CreateGPUGraphicsPipeline(GpuDevice, &info);+ }+ if (!SunDepthSampler) {+ 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;+ SunDepthSampler = SDL_CreateGPUSampler(GpuDevice, &sampler);+ }+ if (!SunDepthPipeline || !SunDepthSampler)+ fprintf(stderr, "SdlGpuFrame: sun depth reader resolve: %s\n", SDL_GetError());+ return SunDepthPipeline && SunDepthSampler;+}++bool SdlGpuFrame::Resolve_Sun_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, SunDepthPipeline);+ const SDL_GPUTextureSamplerBinding binding = { source, SunDepthSampler };+ 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;+}+++void SdlGpuFrame::Release_Sun_Shadow()+{+ if (SunShadowTexture) SDL_ReleaseGPUTexture(GpuDevice, SunShadowTexture);+ if (SunDepthPipeline) SDL_ReleaseGPUGraphicsPipeline(GpuDevice, SunDepthPipeline);+ if (SunDepthVertex) SDL_ReleaseGPUShader(GpuDevice, SunDepthVertex);+ if (SunDepthPixel) SDL_ReleaseGPUShader(GpuDevice, SunDepthPixel);+ if (SunDepthSampler) SDL_ReleaseGPUSampler(GpuDevice, SunDepthSampler);+ SunShadowTexture = NULL;+ SunDepthPipeline = NULL;+ SunDepthVertex = SunDepthPixel = NULL;+ SunDepthSampler = NULL;+ SunShadowSize = 0;+}++bool SdlGpuFrame::Read_Depth(SDL_GPUTexture *texture, unsigned width, unsigned height,+ std::vector<float> &depth)+{+ depth.clear();+ if (!texture || !width || !height || !Flush() || !Create_Sun_Depth_Reader()) return false;+ SDL_GPUTextureCreateInfo info = {};+ info.type = SDL_GPU_TEXTURETYPE_2D;+ info.format = SDL_GPU_TEXTUREFORMAT_R32_FLOAT;+ info.usage = SDL_GPU_TEXTUREUSAGE_COLOR_TARGET | SDL_GPU_TEXTUREUSAGE_SAMPLER;+ info.width = width;+ info.height = height;+ info.layer_count_or_depth = info.num_levels = 1;+ SDL_GPUTexture *resolved = SDL_CreateGPUTexture(GpuDevice, &info);+ if (!resolved) return false;++ SDL_GPUCommandBuffer *commands = SDL_AcquireGPUCommandBuffer(GpuDevice);+ bool submitted = false;+ if (commands) {+ if (Resolve_Sun_Depth(commands, texture, resolved, width, height)) {+ // Previously queued readers were flushed above; this ordered submission owns+ // the resolve, and the existing download waits for it before mapping bytes.+ submitted = SerializeSubmits ? Submit(commands) : Submit_Flush(commands);+ } else SDL_CancelGPUCommandBuffer(commands);+ }+ std::vector<uint8_t> bytes;+ const bool read = submitted && Read_Back(resolved, width, height, bytes);+ const size_t expected = size_t(width) * height * sizeof(float);+ const bool ok = read && bytes.size() == expected;+ if (ok) {+ depth.resize(size_t(width) * height);+ std::memcpy(depth.data(), bytes.data(), expected);+ }+ Release_After_Batch(resolved, NULL);+ return ok;+}diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlPipelineCache.cpp b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlPipelineCache.cppindex 4bf41899c..35f28a4a9 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlPipelineCache.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlPipelineCache.cpp@@ -19,6 +19,7 @@// Pipelines and samplers on SDL3 GPU (decision 7, phase A3c). See SdlPipelineCache.h.#include "SdlPipelineCache.h"+#include "SdlSunShadowDebug.h"#include "SdlCreationLog.h"#include <SDL3/SDL.h>@@ -312,7 +313,7 @@ SdlPipelineCache::~SdlPipelineCache()}}-SDL_GPUGraphicsPipeline *SdlPipelineCache::Pipeline(const SdlPipelineKey &key)+SDL_GPUGraphicsPipeline *SdlPipelineCache::Pipeline(const SdlPipelineKey &key, bool sunReceiver){if (LastPipeline != NULL && memcmp(&key, &LastKey, sizeof(key)) == 0) {return LastPipeline;@@ -388,12 +389,14 @@ SDL_GPUGraphicsPipeline *SdlPipelineCache::Pipeline(const SdlPipelineKey &key)info.depth_stencil_state.compare_mask = key.StencilRead;info.depth_stencil_state.write_mask = key.StencilWrite;}- info.target_info.color_target_descriptions = ⌖- info.target_info.num_color_targets = 1;+ info.target_info.color_target_descriptions = key.ColourFormat ? &target : NULL;+ info.target_info.num_color_targets = key.ColourFormat ? 1 : 0;info.target_info.has_depth_stencil_target = key.DepthFormat != 0;info.target_info.depth_stencil_format = (SDL_GPUTextureFormat)key.DepthFormat;const double started = Sdl_Creation_Log_Asked() ? Sdl_Now_Ms() : 0.0;- pipeline = SDL_CreateGPUGraphicsPipeline(Device, &info);+ if (sunReceiver && Sdl_Sun_Shadow_Fault("receiver-pipeline"))+ SDL_SetError("injected sun receiver pipeline failure");+ else pipeline = SDL_CreateGPUGraphicsPipeline(Device, &info);if (Sdl_Creation_Log_Asked()) {char detail[96];snprintf(detail, sizeof(detail), "#%u, %u attributes, blend %u, depth %u/%u", Built + 1, layout.AttributeCount,diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlPipelineCache.h b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlPipelineCache.hindex b970bc553..752190757 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlPipelineCache.h+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlPipelineCache.h@@ -107,7 +107,7 @@ public:explicit SdlPipelineCache(SDL_GPUDevice *device);~SdlPipelineCache();/// Null when the device refuses it; logged once per key.- SDL_GPUGraphicsPipeline *Pipeline(const SdlPipelineKey &key);+ SDL_GPUGraphicsPipeline *Pipeline(const SdlPipelineKey &key, bool sunReceiver = false);unsigned int Pipelines_Built() const { return Built; }/// Names a program for a refusal's log line (the device points it at SdlProgramCache::Key_Of).std::function<std::string(const SDL_GPUShader *)> Describe_Shader;diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlProgramCache.cpp b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlProgramCache.cppindex 1a08bd6e6..dfaad051c 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlProgramCache.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlProgramCache.cpp@@ -28,6 +28,7 @@#include <SDL3/SDL.h>#include <stdio.h>+#include "SdlSunShadowDebug.h"#include <stdlib.h>#include <string.h>@@ -279,7 +280,43 @@ const SdlProgram &SdlProgramCache::Pixel_Program(const CombinerDescription &desc}std::string hlsl;const bool generated = CombinerShader_Generate(description, COMBINER_SHADER_TARGET_SDL3_GPU, hlsl);+ if (description.ShadowReceiving && Sdl_Sun_Shadow_Fault("receiver-program"))+ hlsl += "\n#error injected sun receiver compilation failure\n";const SdlProgram &made = Make(PixelPrograms, key, generated, hlsl, false);PixelByBytes.Add(&description, sizeof(description), &PixelPrograms[key]);return made;}++// Preserve the shared alpha/discard logic but expose no fragment color output on a depth-only pass.+const SdlProgram &SdlProgramCache::Sun_Pixel_Program(const CombinerDescription &description, int engine)+{+ struct { CombinerDescription Description; int Engine; } lookup = {};+ memcpy(&lookup.Description, &description, sizeof(description));+ lookup.Engine = engine;+ if (SdlProgram *found = SunPixelByBytes.Find(&lookup, sizeof(lookup))) {+ ++found->Uses;+ return *found;+ }+ const bool fixed = engine == ENGINE_SHADER_NONE;+ const std::string key = "sun-caster:" + (fixed ? CombinerShader_Key(description)+ : std::string(EngineShader_Name((EngineShaderProgram)engine)) + CombinerShader_Pipeline_Key(description.PixelPipeline));+ auto existing = PixelPrograms.find(key);+ if (existing != PixelPrograms.end()) {+ ++existing->second.Uses;+ SunPixelByBytes.Add(&lookup, sizeof(lookup), &existing->second);+ return existing->second;+ }+ std::string hlsl;+ bool generated = fixed ? CombinerShader_Generate(description, COMBINER_SHADER_TARGET_SDL3_GPU, hlsl)+ : EngineShader_Pixel_Program((EngineShaderProgram)engine, description.PixelPipeline, hlsl, COMBINER_SHADER_TARGET_SDL3_GPU);+ const std::string entry = "float4 main(Input input) : SV_Target";+ const size_t at = hlsl.find(entry);+ generated = generated && at != std::string::npos;+ if (generated) {+ hlsl.replace(at, entry.size(), "float4 sunCasterPixel(Input input)");+ hlsl += "\nvoid main(Input input) { sunCasterPixel(input); }\n";+ }+ const SdlProgram &made = Make(PixelPrograms, key, generated, hlsl, false);+ SunPixelByBytes.Add(&lookup, sizeof(lookup), &PixelPrograms[key]);+ return made;+}diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlProgramCache.h b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlProgramCache.hindex f4524a4d6..51d65bd7c 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlProgramCache.h+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlProgramCache.h@@ -71,6 +71,7 @@ public:/// comes back with a null Shader and its Refusal.const SdlProgram &Vertex_Program(const VertexPipelineDescription &description);const SdlProgram &Pixel_Program(const CombinerDescription &description);+ const SdlProgram &Sun_Pixel_Program(const CombinerDescription &description, int engine);/// 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 +106,7 @@ private:SdlProgram *Last = NULL;size_t Entries = 0;};- ByBytes VertexByBytes, PixelByBytes, EngineVertexByBytes, EnginePixelByBytes;+ ByBytes VertexByBytes, PixelByBytes, EngineVertexByBytes, EnginePixelByBytes, SunPixelByBytes;SDL_GPUDevice *Device;std::map<std::string, SdlProgram> VertexPrograms;diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlRenderMatrix.h b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlRenderMatrix.hnew file mode 100644index 000000000..68c1a91a2--- /dev/null+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlRenderMatrix.h@@ -0,0 +1,45 @@+// Render-only row-major matrix operations. No simulation arithmetic uses this header.+#pragma once+#include <math.h>++static void multiply(const float left[16], const float right[16], float result[16])+{+ for (unsigned row = 0; row < 4; ++row) {+ for (unsigned column = 0; column < 4; ++column) {+ float sum = 0.0f;+ for (unsigned index = 0; index < 4; ++index) {+ sum += left[row * 4 + index] * right[index * 4 + column];+ }+ result[row * 4 + column] = sum;+ }+ }+}++// Visual-only inverse for reconstructing render positions from depth. Double intermediates keep+// distant camera translations stable; this does not reach simulation or replay arithmetic.+static bool render_inverse(const float source[16], float result[16])+{+ double rows[4][8];+ for (unsigned r = 0; r < 4; ++r)+ for (unsigned c = 0; c < 8; ++c)+ rows[r][c] = c < 4 ? source[r * 4 + c] : (c - 4 == r ? 1.0 : 0.0);+ for (unsigned c = 0; c < 4; ++c) {+ unsigned pivot = c;+ for (unsigned r = c + 1; r < 4; ++r)+ if (fabs(rows[r][c]) > fabs(rows[pivot][c])) pivot = r;+ if (!isfinite(rows[pivot][c]) || fabs(rows[pivot][c]) < 1e-15) return false;+ for (unsigned k = 0; k < 8; ++k) {+ const double saved = rows[c][k]; rows[c][k] = rows[pivot][k]; rows[pivot][k] = saved;+ }+ const double scale = rows[c][c];+ for (unsigned k = 0; k < 8; ++k) rows[c][k] /= scale;+ for (unsigned r = 0; r < 4; ++r) {+ if (r == c) continue;+ const double factor = rows[r][c];+ for (unsigned k = 0; k < 8; ++k) rows[r][k] -= factor * rows[c][k];+ }+ }+ for (unsigned r = 0; r < 4; ++r)+ for (unsigned c = 0; c < 4; ++c) result[r * 4 + c] = (float)rows[r][c + 4];+ return true;+}diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlSunShadowDebug.h b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlSunShadowDebug.hnew file mode 100644index 000000000..228ddf713--- /dev/null+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlSunShadowDebug.h@@ -0,0 +1,11 @@+#pragma once+#include <cstdlib>+#include <cstring>++// Fault validation only, at resource/program/pipeline creation, never the cached+// draw path. The harness clears inherited requests unless --fault is explicit.+inline bool Sdl_Sun_Shadow_Fault(const char *point)+{+ const char *requested = std::getenv("ZH_TEST_SUN_SHADOW_FAILURE");+ return requested && std::strcmp(requested, point) == 0;+}diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/BaseHeightMap.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/BaseHeightMap.cppindex 5df826c1d..53d863899 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/BaseHeightMap.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/BaseHeightMap.cpp@@ -2951,6 +2951,17 @@ flushVertexBuffer1:/** Renders (draws) the trees. Since the trees are transparent, this has to becalled after flush. *///=============================================================================+void BaseHeightMapRenderObjClass::renderTreeShadowCasters(RenderInfoClass &sunInfo, CameraClass *sceneCamera, const SunShadowCasterCull &cull)+{+ if (!m_map || !Scene || !m_treeBuffer) return;+ DX8Wrapper::Set_Transform(D3DTS_WORLD, Transform);+ DX8Wrapper::Set_Material(m_vertexMaterialClass);+ RTS3DScene *scene = (RTS3DScene *)Scene;+ RefRenderObjListIterator lights(scene->getDynamicLights());+ m_treeBuffer->drawTrees(sceneCamera, &lights, &sunInfo.Camera);+ m_treeBuffer->drawModelShadowCasters(sunInfo,cull);+}+void BaseHeightMapRenderObjClass::renderTrees(CameraClass * camera){#ifdef EXTENDED_STATSdiff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DShadow.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DShadow.cppindex bdd8297f3..f34bc3bfa 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DShadow.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DShadow.cpp@@ -34,6 +34,7 @@//// USER INCLUDES //////////////////////////////////////////////////////////////+#include "Platform/SunShadow.h"#include "always.h"#include "GameClient/View.h"#include "WW3D2/camera.h"@@ -102,6 +103,7 @@ Bool volumeShadowCanReachView( const FrustumClass &view, const SphereClass &bodyDECLARE_PERF_TIMER(shadowsRender)void DoShadows(RenderInfoClass & rinfo, Bool stencilPass){+ SunShadow::ReceiverExclusion sunReceivers(DX8Wrapper::_Get_D3D_Device());USE_PERF_TIMER(shadowsRender)shadowCameraFrustum=&rinfo.Camera.Get_Frustum();Int projectionCount=0;diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cppindex cec6a70ee..60df29ea4 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cpp@@ -59,6 +59,7 @@#include "Common/DrawModule.h"#include "W3DDevice/GameClient/W3DVolumetricShadow.h"#include "W3DDevice/GameClient/W3DShadow.h"+#include "W3DDevice/GameClient/SunShadowCasterCull.h"#include "WW3D2/statistics.h"#include "Common/PerfTimer.h"#include "GameLogic/TerrainLogic.h"@@ -74,6 +75,8 @@#include "WW3D2/sortingrenderer.h"#include "GameClient/View.h"#include "Platform/RenderTypes.h"+#include "Platform/SunShadowMode.h"+#include "Platform/SunShadow.h"#include "Lib/Clock.h" // Clock_Ticks: QueryPerformanceCounter on Windows, a monotonic clock elsewhere#include "GameClient/ParticleSys.h"#include "W3DDevice/GameClient/W3DParticleSys.h"@@ -179,7 +182,7 @@ const Real cosAngleToCare = cos ((0.2 * PI) / 180.0); //1.5 degree difference// Whether the sun's map took this frame. The volumes read it to know whether to stand down, and it// is false on a machine with no Direct3D 11 device, which is what keeps that machine's shadows.-static Bool theShadowMapHoldsTheFrame = FALSE;+//#define SV_DEBUG//#define SV_DEBUG_BOUNDS@@ -3985,7 +3988,7 @@ static void fillSmokeMap( const Matrix3D &sunTransform, const Vector3 &focus, Repacked.push_back( found[ i ].opticalDepth );}- const Bool held = Direct3D11_Fill_Smoke_Map( packed.empty() ? NULL : &packed[ 0 ],+ const Bool held = SunShadow::FillSmoke(DX8Wrapper::_Get_D3D_Device(), packed.empty() ? NULL : &packed[ 0 ],(unsigned)found.size(), SMOKE_SHADOW_STRENGTH );if (!held)return;@@ -4039,6 +4042,11 @@ static void fillSmokeMap( const Matrix3D &sunTransform, const Vector3 &focus, Rewater areas; the grid mesh never does. */static Bool waterMirrorReadsTheMap(){+#if defined(__linux__)+ // SDL gives reflections a separate, excluded scene scope and never samples this+ // capture through their camera. Keep culling against the actual receiving view.+ return FALSE;+#elseif (TheWaterRenderObj == NULL)return FALSE;if (TheGlobalData->m_waterType == WaterRenderObjClass::WATER_TYPE_3_GRIDMESH)@@ -4051,37 +4059,7 @@ static Bool waterMirrorReadsTheMap()return TRUE;}return FALSE;-}--/** Whether anything a pixel of this frame samples can be shadowed by a caster. The caster is its- bounding sphere, and what it can darken lies downwind of it: the sphere swept away from the sun- from its own sun side down to the lowest ground on the map, widened by how far the receiving- filter reaches across the map. That capsule runs from upwind to downwind with this radius.- Only the four sides of the view are tested: a draw with a depth-biased projection reads the- map through near and far planes that are not the camera's, and the sides are the same for- every one of them. The overlay's quads sit at z = 0 whatever the ground does, so for them the- capsule runs on to overlayDownwind, swept down to z = 0 when the lowest ground is above it. */-static Bool shadowReachesTheFrame( const FrustumClass &view, const Vector3 &upwind,- const Vector3 &downwind, const Vector3 &overlayDownwind, Real radius )-{- Bool inView = TRUE;- for (Int side = 1; side <= 4 && inView; ++side)- {- const PlaneClass &plane = view.Planes[ side ];- inView = Vector3::Dot_Product( plane.N, upwind ) - plane.D <= radius- || Vector3::Dot_Product( plane.N, downwind ) - plane.D <= radius;- }- if (inView)- return TRUE;-- // the 2D scene's and the interface's quads, at the world's origin- const Vector3 along = overlayDownwind - upwind;- const Real lengthSqr = along.Length2();- Real t = (lengthSqr > 0.0f) ? -Vector3::Dot_Product( upwind, along ) / lengthSqr : 0.0f;- t = WWMath::Clamp( t, 0.0f, 1.0f );- const Vector3 nearest = upwind + along * t;- const Real reach = radius + SHADOW_MAP_OVERLAY_REACH;- return nearest.Length2() <= reach * reach;+#endif}/** Render() is not only a draw. Animatable3DObjClass::Render moves a playing animation on to the@@ -4199,7 +4177,26 @@ static void wholeMapSunBox( const Vector3 &toSun, Vector3 *focus, Real *halfWidtmore than one view. SHADOW-MAP-PLAN.md phase 1. */void W3DVolumetricShadowManager::renderShadowMap( CameraClass &sceneCamera ){- theShadowMapHoldsTheFrame = FALSE;+ // A failed, disabled or empty pass must not expose the previous view's shadow.+ SunShadow::Clear(DX8Wrapper::_Get_D3D_Device());+ DX8Wrapper::Flush_Deferred_D3D9_State();+ const SunShadow::Mode mode = SunShadow::RequestedMode();+ // Trees historically cast under either shadow option. Smoke has its own option;+ // it may keep an otherwise empty depth capture alive without enabling geometry.+#if defined(__linux__)+ const Bool geometryShadows = TheGlobalData->m_useShadowVolumes || TheGlobalData->m_useShadowDecals;+ const Bool captureShadows = geometryShadows || TheGlobalData->m_volumetricSmokeShadows;+#else+ const Bool geometryShadows = TRUE;+ const Bool captureShadows = m_shadowList != NULL;+#endif+ static bool modeReported = false;+ static SunShadow::Mode lastMode = SunShadow::Mode::Legacy;+ if (!modeReported || lastMode != mode) {+ fprintf(stderr, "SunShadow: requested %s\n", SunShadow::ModeName(mode));+ modeReported = true;+ lastMode = mode;+ }/* The freecam asks for a map four times as wide and makes do with the usual one if refused. Arefusal is remembered until the freecam lands: asking again every frame released the usual@@ -4214,9 +4211,10 @@ void W3DVolumetricShadowManager::renderShadowMap( CameraClass &sceneCamera )const UnsignedInt chosenTexels = (SHADOW_MAP_TEXELS / 2) << TheGlobalData->m_shadowQuality;UnsignedInt texels = chosenTexels;Bool begun = FALSE;- if (TheGlobalData->m_shadowMap && m_shadowList != NULL && TheTacticalView != NULL)+ if (mode != SunShadow::Mode::Legacy && TheGlobalData->m_shadowMap && captureShadows && TheTacticalView != NULL+ && TheTerrainRenderObject != NULL && TheTerrainLogic != NULL && TheW3DShadowManager != NULL){- if (wholeMap && !wholeMapRefused && Direct3D11_Begin_Shadow_Map( SHADOW_MAP_WHOLE_MAP_TEXELS ))+ if (wholeMap && !wholeMapRefused && SunShadow::Begin( DX8Wrapper::_Get_D3D_Device(), SHADOW_MAP_WHOLE_MAP_TEXELS )){texels = SHADOW_MAP_WHOLE_MAP_TEXELS;begun = TRUE;@@ -4225,14 +4223,14 @@ void W3DVolumetricShadowManager::renderShadowMap( CameraClass &sceneCamera ){if (wholeMap)wholeMapRefused = TRUE;- begun = Direct3D11_Begin_Shadow_Map( chosenTexels );+ begun = SunShadow::Begin( DX8Wrapper::_Get_D3D_Device(), chosenTexels );}}if (!begun){//no Direct3D 11 device, or it refused the surface: the volumes keep the frame, no smoke is//read out of a map the last frame filled, and every cloud keeps its blob- Direct3D11_Fill_Smoke_Map( NULL, 0, 0.0f );+ SunShadow::FillSmoke(DX8Wrapper::_Get_D3D_Device(), NULL, 0, 0.0f );forgetSmokeInSunMap();return;}@@ -4360,8 +4358,14 @@ void W3DVolumetricShadowManager::renderShadowMap( CameraClass &sceneCamera )const FrustumClass &seen = sceneCamera.Get_Frustum();const Real filterReach = (widest * 1.5f + 2.0f) * texelWidth;const Bool cullToFrame = toSun.Z > 0.01f && !waterMirrorReadsTheMap();+ const SunShadowCasterCull casterCull={seen,toSun,lowestReceiver,SHADOW_MAP_CASTER_PAD,filterReach,SHADOW_MAP_OVERLAY_REACH,cullToFrame};- for (W3DVolumetricShadow *shadow = m_shadowList; shadow; shadow = shadow->m_next)+#if defined(__linux__)+ W3DVolumetricShadow *firstCaster = TheGlobalData->m_useShadowVolumes ? m_shadowList : NULL;+#else+ W3DVolumetricShadow *firstCaster = m_shadowList;+#endif+ for (W3DVolumetricShadow *shadow = firstCaster; shadow; shadow = shadow->m_next){RenderObjClass *robj = shadow->getRenderObject();if (robj == NULL || !shadow->isRenderEnabled() || shadow->isInvisibleEnabled())@@ -4383,20 +4387,11 @@ void W3DVolumetricShadowManager::renderShadowMap( CameraClass &sceneCamera )out is a caster whose shadow, followed downwind to the lowest ground and widened by thefilter, never meets the frame: no pixel drawn this frame reads a texel it is nearest thesun in, so the map reads the same everywhere it is read. */- if (cullToFrame)+ if (!casterCull.Visible(bound)){- const Real casterRadius = bound.Radius + SHADOW_MAP_CASTER_PAD;- const Real radius = casterRadius + filterReach;- const Real sweep = WWMath::Max( (bound.Center.Z - lowestReceiver + radius) / toSun.Z, 0.0f );- const Real overlaySweep = WWMath::Max(- (bound.Center.Z - WWMath::Min( lowestReceiver, 0.0f ) + radius) / toSun.Z, 0.0f );- if (!shadowReachesTheFrame( seen, bound.Center + toSun * casterRadius,- bound.Center - toSun * sweep, bound.Center - toSun * overlaySweep, radius ))- {- CasterAnimationClock::advance( robj );- ++castersOutOfView;- continue;- }+ CasterAnimationClock::advance(robj);+ ++castersOutOfView;+ continue;}/* An own stealthed unit casts only a share of its shadow, breathing with its fade, the way@@ -4405,7 +4400,7 @@ void W3DVolumetricShadowManager::renderShadowMap( CameraClass &sceneCamera )sunInfo.drawEffect = DRAW_EFFECT_NONE;const DrawableInfo *casterInfo = (const DrawableInfo *)robj->Get_User_Data();const Drawable *caster = casterInfo ? casterInfo->m_drawable : NULL;- if (caster && Direct3D11_Draw_Effects()+ if (caster && SunShadow::CasterEffects(DX8Wrapper::_Get_D3D_Device())&& (caster->getStealthDrawnLook() == STEALTHLOOK_VISIBLE_FRIENDLY|| caster->getStealthDrawnLook() == STEALTHLOOK_VISIBLE_FRIENDLY_DETECTED)&& !caster->isKindOf( KINDOF_MINE )@@ -4418,6 +4413,15 @@ void W3DVolumetricShadowManager::renderShadowMap( CameraClass &sceneCamera )robj->Render( sunInfo );++castersCounted;}+ // Trees have no volume-shadow entry: batched foliage and object palms used+ // separate flattened silhouettes. Capture their actual geometry in the sun map.+ sunInfo.drawEffect = DRAW_EFFECT_NONE;+ // Use the trees actually present. The loader can override ShowTrees for multiplayer,+ // and changing that preference does not remove trees from an already loaded map.+#if defined(__linux__)+ if (geometryShadows)+ TheTerrainRenderObject->renderTreeShadowCasters(sunInfo, &sceneCamera, casterCull);+#endifTheDX8MeshRenderer.Flush();/* A mesh the material system calls translucent goes to the sort lists rather than to the meshrenderer, and a helicopter's rotor disc is one of them: without this the map holds the@@ -4442,19 +4446,30 @@ void W3DVolumetricShadowManager::renderShadowMap( CameraClass &sceneCamera )wrapper's cached value, which an invalidate leaves as a sentinel. */const float bridgeSlopeBias = SHADOW_MAP_BRIDGE_SLOPE_BIAS;DX8Wrapper::Set_DX8_Render_State( D3DRS_SLOPESCALEDEPTHBIAS, *(const uint32 *)&bridgeSlopeBias );- TheTerrainRenderObject->getBridgeBuffer()->drawBridgeShadowCasters();+ if (geometryShadows)+ TheTerrainRenderObject->getBridgeBuffer()->drawBridgeShadowCasters();DX8Wrapper::Set_DX8_Render_State( D3DRS_SLOPESCALEDEPTHBIAS, 0 );DX8Wrapper::Set_DX8_Render_State( D3DRS_COLORWRITEENABLE,D3DCOLORWRITEENABLE_RED | D3DCOLORWRITEENABLE_GREEN | D3DCOLORWRITEENABLE_BLUE| D3DCOLORWRITEENABLE_ALPHA );- Direct3D11_End_Shadow_Map();+ // Invalidate the engine caches before restoring the device snapshot: invalidation itself+ // unbinds textures and flushes deferred states. The restored scene must be the last writer.+#if defined(__linux__)+ DX8Wrapper::Invalidate_Cached_Render_States();+#endif+ const bool captured = SunShadow::End(DX8Wrapper::_Get_D3D_Device());// The smoke goes into a map of its own through the sun the casters were just drawn with.// past the map's limit the smoke nearest the camera wins: the freecam's box is centred on the// map's middle, which is not where it is looking from- fillSmokeMap( transform, wholeMap ? sceneCamera.Get_Position() : focus, halfWidth, farClip );+ if (mode == SunShadow::Mode::Mapped && captured)+ fillSmokeMap( transform, wholeMap ? sceneCamera.Get_Position() : focus, halfWidth, farClip );+ else {+ SunShadow::FillSmoke(DX8Wrapper::_Get_D3D_Device(), NULL, 0, 0.0f );+ forgetSmokeInSunMap();+ }// The frame's own camera, put back: the view, the projection and the viewport all went with the// sun. Without this everything drawn after the pass is drawn from the sun's seat, which is the@@ -4469,6 +4484,11 @@ void W3DVolumetricShadowManager::renderShadowMap( CameraClass &sceneCamera )Matrix4x4 view;DX8Wrapper::Get_Transform( D3DTS_VIEW, view );const Matrix4x4 deviceView = view.Transpose();+#if defined(__linux__)+ // Camera::Apply defers the view in render_state, outside the D3D9 state+ // queue. Publish this one transform before snapshotting receiver coordinates.+ DX8Wrapper::_Set_DX8_Transform(D3DTS_VIEW, deviceView);+#endifDirect3D11_Set_Scene_View( (const float *)&deviceView );}@@ -4497,15 +4517,17 @@ void W3DVolumetricShadowManager::renderShadowMap( CameraClass &sceneCamera )if (TheGlobalData->m_lightingStyle == LIGHTING_STYLE_REFORGED && TheGlobalData->m_shadowMapStrength <= 0.0f)strength = SHADOW_MAP_REFORGED_STRENGTH;- Direct3D11_Set_Shadow_Parameters( depthBias, strength, widest,- narrowest, penumbra / worldPerTexel, unitsPerUnitOfDepth, skyFill );+ DX8Wrapper::Flush_Deferred_D3D9_State();+ const bool receiving = captured && mode == SunShadow::Mode::Mapped+ && SunShadow::Parameters(DX8Wrapper::_Get_D3D_Device(), depthBias, strength, widest,+ narrowest, penumbra / worldPerTexel, unitsPerUnitOfDepth, skyFill);/* Said last, and only on the way out: everything above can bail, and the volumes have to knowwhether this frame's shadows are in the map or still theirs to draw. The count of casters isnot part of that answer. It was, and a frame that happened to hold none - a camera over openground - handed the frame back to the volumes for that one frame, so the whole scene'sshadows changed style and back again as the camera moved. */- theShadowMapHoldsTheFrame = TRUE;+ (void)receiving; // backend scene ownership is installed only after successful parameters#ifdef DEBUG_LOGGING{@@ -4522,7 +4544,14 @@ void W3DVolumetricShadowManager::renderShadowMap( CameraClass &sceneCamera )// The report costs a full stall of the pipeline, so it is one line a second rather than one a// frame: what it answers is whether the pass draws the world at all, and that does not change// thirty times a second.- if (TheGlobalData->m_shadowMapReport && castersCounted > 0)+#if defined(__linux__)+ // Foliage, bridges and smoke do not increment the volume-caster count.+ // Report any completed capture so those settings remain diagnosable.+ const bool hasReportableCapture = captured;+#else+ const bool hasReportableCapture = castersCounted > 0;+#endif+ if (TheGlobalData->m_shadowMapReport && hasReportableCapture){static UnsignedInt nextReportFrame = 0;const UnsignedInt frame = TheGameLogic ? TheGameLogic->getFrame() : 0;@@ -4531,7 +4560,7 @@ void W3DVolumetricShadowManager::renderShadowMap( CameraClass &sceneCamera )nextReportFrame = frame + LOGICFRAMES_PER_SECOND;DEBUG_LOG(("SHADOWMAP: %d casters, %d left out as reaching nothing in view, %d light meshes left out, %s\n",castersCounted, castersOutOfView, MeshClass::Shadow_Pass_Light_Meshes,- Direct3D11_Shadow_Map_Report().c_str()));+ SunShadow::Report(DX8Wrapper::_Get_D3D_Device()).c_str()));}}}@@ -4546,7 +4575,7 @@ void W3DVolumetricShadowManager::renderShadows( Bool forceStencilFill )stay registered either way, which is what keeps them in the map; what stops is the volumes'own darkening pass. A machine with no Direct3D 11 device fills no map and keeps the volumes,so nobody ends up with no shadows at all. */- if (TheGlobalData->m_shadowMapOnly && theShadowMapHoldsTheFrame)+ if (TheGlobalData->m_shadowMapOnly && SunShadow::OwnsSceneShadows(DX8Wrapper::_Get_D3D_Device()))return;AABoxClass bbox;diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cppindex 441284435..608f14650 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp@@ -2502,7 +2502,15 @@ AGAIN:}}- if (!freezeTime)+ // Diagnostic pictures need the same animation/cloud phase even when one renderer does+ // more work. Establish zero during loading so texture mappers inherit the same origin.+ // This is opt-in for screenshot runs; ordinary play, multiplayer and replay keep their clock.+ const bool shadowCaptureClock = GameEngine_isShadowCaptureClock();+ if (shadowCaptureClock) {+ if (!TheGameLogic->isInGame() || TheGameLogic->isInShellGame()) syncTime = 0;+ else if (!freezeTime) syncTime = GameEngine_pictureMilliseconds();+ }+ if (!freezeTime && !shadowCaptureClock){//// This is W3D's clock: every skeletal animation, texture flipbook and W3D-driven effectdiff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cppindex d9d5b4dce..47d3dd739 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp@@ -43,6 +43,7 @@#include "W3DDevice/GameClient/W3DSmoothMotion.h"#include "WW3D2/dx8wrapper.h"#include "WW3D2/dx11runtime.h"+#include "Platform/SunShadow.h"#include "Common/JobSystem.h"#include "GameLogic/GameLogic.h"#include "GameLogic/Object.h"@@ -1560,6 +1561,10 @@ void W3DParticleSystemManager::doParticles(RenderInfoClass &rinfo)fillJob.lightCount = gatherSmokeLights( fillJob.lights, bbox );}fillJob.glowAfterShade = Direct3D11_Present_Is_Enabled();+#if defined(__linux__)+ fillJob.glowAfterShade = fillJob.glowAfterShade+ || SunShadow::OwnsSceneShadows(DX8Wrapper::_Get_D3D_Device());+#endifJobSystem::parallel_for( (Int)m_billboardFills.size(), BILLBOARD_FILLS_PER_CLAIM, fillBillboards, &fillJob );s_fieldPos.clear();diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DScene.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DScene.cppindex 94b7cb054..655d44818 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DScene.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DScene.cpp@@ -34,6 +34,7 @@///////////////////////////////////////////////////////////////////////////////// SYSTEM INCLUDES ////////////////////////////////////////////////////////////+#include "Platform/SunShadow.h"#include <stdlib.h>#include "Lib/Clock.h"@@ -1158,6 +1159,11 @@ void RTS3DScene::updatePlayerColorPasses(void)DECLARE_PERF_TIMER(NonTerrainRender)void RTS3DScene::Render(RenderInfoClass & rinfo){+ // Covers both submission and Flush, including sorted draws. Nested reflections and+ // custom passes cannot borrow the main view's map or its stencil ownership.+ SunShadow::SceneScope sunScene(DX8Wrapper::_Get_D3D_Device(),+ m_customPassMode == SCENE_PASS_DEFAULT && !ShaderClass::Is_Backface_Culling_Inverted()+ && Get_Extra_Pass_Polygon_Mode() == EXTRA_PASS_DISABLE);USE_PERF_TIMER(NonTerrainRender)DX8Wrapper::Set_Fog(FogEnabled, FogColor, FogStart, FogEnd);diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTreeBuffer.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTreeBuffer.cppindex 08d739223..cb7927f33 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTreeBuffer.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTreeBuffer.cpp@@ -56,6 +56,8 @@ enum//-----------------------------------------------------------------------------// Includes//-----------------------------------------------------------------------------+#include "Platform/SunShadow.h"+#include "W3DDevice/GameClient/SunShadowCasterCull.h"#include "W3DDevice/GameClient/W3DTreeBuffer.h"#include <stdio.h>@@ -378,7 +380,7 @@ ShaderClass ShaderClass::_PresetAlpha2DShader(SC_ALPHA_2D);/** Culls the trees, marking the visible flag. If a tree becomes visible, it setsit's sortKey *///=============================================================================-void W3DTreeBuffer::cull(const CameraClass * camera)+void W3DTreeBuffer::cull(const CameraClass * camera, const CameraClass *sunCamera){Int curTree;@@ -399,6 +401,10 @@ void W3DTreeBuffer::cull(const CameraClass * camera)for (curTree=0; curTree<m_numTrees; curTree++) {Bool doKey = false; // We calculate the key when a tree becomes visible.Bool visible = !camera->Cull_Sphere(m_trees[curTree].bounds);+ // Keep one shared buffer for both views. A tree outside the screen can still+ // cast onto it; reculling to just the screen would also rebuild it twice a frame.+ if (!visible && sunCamera)+ visible = !sunCamera->Cull_Sphere(m_trees[curTree].bounds);if (!visible && castsSilhouette)visible = shadowCanReachView(camera->Get_Frustum(), m_trees[curTree].bounds, m_trees[curTree].location.Z,stretchX, stretchY);@@ -811,6 +817,7 @@ void W3DTreeBuffer::loadTreesInVertexAndIndexBuffers(RefRenderObjListIterator *pm_anythingChanged = false;Int curTree=0;Int bNdx;+ for (bNdx=0; bNdx<MAX_BUFFERS; ++bNdx) m_shadowRanges[bNdx].clear();const GlobalData::TerrainLighting *objectLighting = TheGlobalData->m_terrainObjectsLighting[TheGlobalData->m_timeOfDay];for (bNdx=0; bNdx<MAX_BUFFERS; bNdx++) {m_curNumTreeVertices[bNdx] = 0;@@ -1069,6 +1076,7 @@ void W3DTreeBuffer::loadTreesInVertexAndIndexBuffers(RefRenderObjListIterator *pm_curNumTreeVertices[bNdx]++;}+ const Int firstShadowIndex = m_curNumTreeIndices[bNdx];try {for (i=0; i<numIndex; i++) {if (m_curNumTreeIndices[bNdx]+4 > MAX_TREE_INDEX)@@ -1082,6 +1090,13 @@ void W3DTreeBuffer::loadTreesInVertexAndIndexBuffers(RefRenderObjListIterator *p} catch(...) {IndexBufferExceptionFunc();}+ const Int shadowCount = m_curNumTreeIndices[bNdx] - firstShadowIndex;+ if (shadowCount && (m_treeTypes[type].m_doShadow || TheGlobalData->m_shadowsForProps)) {+ std::vector<ShadowRange> &ranges = m_shadowRanges[bNdx];+ if (!ranges.empty() && ranges.back().first + ranges.back().count == firstShadowIndex)+ ranges.back().count += shadowCount;+ else ranges.push_back({firstShadowIndex, shadowCount});+ }}}@@ -1843,6 +1858,19 @@ them on screen at once - a palm is forty vertices.Colour comes from the vertex, not the texture, so the ground gets shade and not a picture of apalm; alpha comes from the texture, so the gaps between the fronds are gaps in the shadow. *///=============================================================================+void W3DTreeBuffer::drawModelShadowCasters(RenderInfoClass &sunInfo, const SunShadowCasterCull &cull)+{+ for (Int i=0; i<m_numModelShadows; ++i) {+ TModelShadow &model = m_modelShadows[i];+ for (Int k=0; k<model.numMesh; ++k) {+ MeshClass *mesh = model.mesh[k];+ if (mesh->Is_Not_Hidden_At_All() && !sunInfo.Camera.Cull_Sphere(mesh->Get_Bounding_Sphere())+ && cull.Visible(mesh->Get_Bounding_Sphere()))+ mesh->Render(sunInfo);+ }+ }+}+void W3DTreeBuffer::drawModelShadows(CameraClass *camera, Real stretchX, Real stretchY){if (m_numModelShadows == 0 || m_numShadowTextures == 0) {@@ -2026,7 +2054,7 @@ void W3DTreeBuffer::drawModelShadows(CameraClass *camera, Real stretchX, Real stshader's constants set to flatten them, as their shadows. The vertex and index buffers are thesame ones both times - a tree's shadow is that tree's triangles. *///=============================================================================-void W3DTreeBuffer::drawTreeBuffers(Bool shadowPass)+void W3DTreeBuffer::drawTreeBuffers(Bool shadowPass, Bool sunPass){LPDIRECT3DDEVICE9 dev = DX8Wrapper::_Get_D3D_Device();if (!dev) {@@ -2080,7 +2108,12 @@ void W3DTreeBuffer::drawTreeBuffers(Bool shadowPass)DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DTSS_COLOROP, D3DTOP_DISABLE);DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DTSS_ALPHAOP, D3DTOP_DISABLE);}- DX8Wrapper::Draw_Triangles( 0, m_curNumTreeIndices[bNdx]/3, 0, m_curNumTreeVertices[bNdx]);+ if (sunPass) {+ for (const ShadowRange &range : m_shadowRanges[bNdx])+ DX8Wrapper::Draw_Triangles(range.first, range.count/3, 0, m_curNumTreeVertices[bNdx]);+ } else {+ DX8Wrapper::Draw_Triangles(0, m_curNumTreeIndices[bNdx]/3, 0, m_curNumTreeVertices[bNdx]);+ }}if (shadowPass) {DX8Wrapper::Invalidate_Cached_Render_States();@@ -2143,10 +2176,17 @@ void W3DTreeBuffer::stepTrees( void )}}-void W3DTreeBuffer::drawTrees(CameraClass * camera, RefRenderObjListIterator *pDynamicLightsIterator)+void W3DTreeBuffer::drawTrees(CameraClass * camera, RefRenderObjListIterator *pDynamicLightsIterator,+ const CameraClass *sunCamera){+#if defined(__linux__)+ const Bool mapped = SunShadow::OwnsSceneShadows(DX8Wrapper::_Get_D3D_Device());+#else+ const Bool mapped = FALSE;+#endif+ SunShadow::ReceiverExclusion sunReceivers(DX8Wrapper::_Get_D3D_Device(), !mapped);USE_PERF_TIMER(Tree_Render)- if (!m_isTerrainPass) {+ if (!m_isTerrainPass && !sunCamera) {return;}@@ -2193,7 +2233,7 @@ void W3DTreeBuffer::drawTrees(CameraClass * camera, RefRenderObjListIterator *pD}}- m_isTerrainPass = false;+ if (!sunCamera) m_isTerrainPass = false;if (m_needToUpdateTexture) {m_needToUpdateTexture = false;@@ -2206,16 +2246,16 @@ void W3DTreeBuffer::drawTrees(CameraClass * camera, RefRenderObjListIterator *pD// culling them against its own frustum left the screen drawing the mirror's trees until the// next cull, and with the mirror skipping frames the trees flickered between the two sets. The// mirror draws what the screen culled, which is what stands near the water it lands on.- if (m_updateAllKeys && !ShaderClass::Is_Backface_Culling_Inverted()) {- cull(camera);+ if (sunCamera || (m_updateAllKeys && !ShaderClass::Is_Backface_Culling_Inverted())) {+ cull(camera, sunCamera);}Int curTree;// Shadows are wanted under either option: the loop used to be gated on m_useShadowDecals alone,// so with volume shadows picked trees were the one thing in the scene standing on nothing.- Bool drawShadows = TheGlobalData->m_useShadowDecals || TheGlobalData->m_useShadowVolumes;- Bool silhouetteShadows = treeSilhouetteShadows(m_dwTreeVertexShader);+ Bool drawShadows = !sunCamera && !mapped && (TheGlobalData->m_useShadowDecals || TheGlobalData->m_useShadowVolumes);+ Bool silhouetteShadows = drawShadows && treeSilhouetteShadows(m_dwTreeVertexShader);// Draw tree shadows.// Trees are batched vertices with no render object of their own, so the one shared blob decal@@ -2247,6 +2287,12 @@ void W3DTreeBuffer::drawTrees(CameraClass * camera, RefRenderObjListIterator *pD// the pushed aside and toppling trees moved in stepTrees, at the sync point+#if defined(__linux__)+ if (m_lastShadowsForProps != TheGlobalData->m_shadowsForProps) {+ m_lastShadowsForProps = TheGlobalData->m_shadowsForProps;+ m_anythingChanged = true;+ }+#endifif (m_anythingChanged) {loadTreesInVertexAndIndexBuffers(pDynamicLightsIterator);m_anythingChanged = false;@@ -2411,7 +2457,7 @@ void W3DTreeBuffer::drawTrees(CameraClass * camera, RefRenderObjListIterator *pDDX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DTSS_TEXCOORDINDEX, 1);// Draw all the trees.DX8Wrapper::Apply_Render_State_Changes();- W3DShaderManager::setShroudTex(1);+ if (!sunCamera) W3DShaderManager::setShroudTex(1);DX8Wrapper::Apply_Render_State_Changes();if (m_dwTreeVertexShader) {@@ -2496,7 +2542,13 @@ void W3DTreeBuffer::drawTrees(CameraClass * camera, RefRenderObjListIterator *pD}- drawTreeBuffers(false);+ if (sunCamera) {+ // Leaves are thin cards. Capture both faces with the same alpha cutoff as+ // the visible tree, and never stamp the shroud into their shadow shape.+ DX8Wrapper::Set_DX8_Render_State(D3DRS_ALPHABLENDENABLE, FALSE);+ DX8Wrapper::Set_DX8_Render_State(D3DRS_CULLMODE, D3DCULL_NONE);+ }+ drawTreeBuffers(false, sunCamera != NULL);DX8Wrapper::Set_Vertex_Format(DX8_FVF_XYZNDUV1);DX8Wrapper::Set_Pixel_Shader(NULL);diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cppindex 388c64937..328535726 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp@@ -147,7 +147,8 @@ Bool W3DView::drawsDrawables( void )logic, and W3DDisplay::draw loops until the pan is done. */static Bool onPictureClock( View *view ){- return GameEngine_isVideoFrame() && !( view->isTimeFrozen() && !view->isCameraMovementFinished() );+ return (GameEngine_isVideoFrame() || GameEngine_isShadowCaptureClock())+ && !( view->isTimeFrozen() && !view->isCameraMovementFinished() );}static UnsignedInt cameraClockMilliseconds( View *view )diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWaterTracks.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWaterTracks.cppindex 5079216aa..98cf4bb54 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWaterTracks.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWaterTracks.cpp@@ -54,6 +54,7 @@#include "GameClient/Water.h"#include "GameLogic/TerrainLogic.h"#include "Common/GlobalData.h"+#include "Common/GameEngine.h"#include "Common/UnicodeString.h"#include "Common/file.h"#include "Common/FileSystem.h"@@ -910,6 +911,15 @@ void WaterTracksRenderSystem::update()carryMs += elapsedMs;Int timeDiff = (Int)carryMs;carryMs -= (Real)timeDiff;+ if (GameEngine_isShadowCaptureClock()) {+ // Screenshot comparisons must hold authored shoreline waves at the same+ // phase too. Repeated renders of the same logic frame advance nothing.+ static UnsignedInt lastPictureMs = 0;+ const UnsignedInt pictureMs = GameEngine_pictureMilliseconds();+ timeDiff = pictureMs >= lastPictureMs ? (Int)(pictureMs-lastPictureMs) : 0;+ lastPictureMs = pictureMs;+ carryMs = 0;+ }//first update all the trackswhile( mod )diff --git a/GeneralsMD/Code/Libraries/Include/Platform/SunShadow.h b/GeneralsMD/Code/Libraries/Include/Platform/SunShadow.hnew file mode 100644index 000000000..1860fc2c2--- /dev/null+++ b/GeneralsMD/Code/Libraries/Include/Platform/SunShadow.h@@ -0,0 +1,71 @@+#pragma once+// Sun capture is independent of per-pixel lighting and of the renderer's API identity.+#include <string>+struct IDirect3DDevice9;+namespace SunShadow {+bool Begin(IDirect3DDevice9 *device, unsigned size);+// End restores the scene and reports whether this capture can be used.+bool End(IDirect3DDevice9 *device);+void Clear(IDirect3DDevice9 *device);+// Five floats per caster: world xyz, radius and optical depth. False retains particle blob shadows.+bool FillSmoke(IDirect3DDevice9 *device, const float *casters, unsigned count, float strength);+bool CasterEffects(IDirect3DDevice9 *device);+void SetCasterEffect(IDirect3DDevice9 *device, unsigned effect, const float parameters[4]);+// Coverage belongs to the queued draw, not to the caller's temporary device state.+// Only shadow-pass effects are captured; cosmetic scene effects keep their own path.+struct CasterEffect {+ unsigned Effect = 0;+ float Parameters[4] = {};+ bool operator==(const CasterEffect &other) const {+ if (Effect != other.Effect) return false;+ if (Effect) for (unsigned i = 0; i < 4; ++i)+ if (Parameters[i] != other.Parameters[i]) return false;+ return true;+ }+};+CasterEffect GetCasterEffect(IDirect3DDevice9 *device);+class CasterEffectScope {+ IDirect3DDevice9 *Device;+ CasterEffect Saved;+ bool Active;+public:+ CasterEffectScope(IDirect3DDevice9 *device, const CasterEffect &effect)+ : Device(device), Saved(GetCasterEffect(device)), Active(Saved.Effect || effect.Effect) {+ if (Active) SetCasterEffect(Device, effect.Effect, effect.Parameters);+ }+ ~CasterEffectScope() { if (Active) SetCasterEffect(Device, Saved.Effect, Saved.Parameters); }+ CasterEffectScope(const CasterEffectScope &) = delete;+ CasterEffectScope &operator=(const CasterEffectScope &) = delete;+};+void SetSmokeGlow(IDirect3DDevice9 *device, bool glow);+// True only when the backend can receive this completed capture.+bool Parameters(IDirect3DDevice9 *device, float bias, float strength, float widest,+ float narrowest, float texelsPerGap, float unitsPerDepth, float skyFill);+// Whether the current draw's coordinates match the captured scene.+bool ReceivesView(IDirect3DDevice9 *device);+// Scene ownership survives temporary camera-space draw state, but never another view.+bool OwnsSceneShadows(IDirect3DDevice9 *device);+bool EnterScene(IDirect3DDevice9 *device, bool eligible);+void LeaveScene(IDirect3DDevice9 *device, bool eligible);+class SceneScope {+ IDirect3DDevice9 *Device;+ bool Eligible;+public:+ SceneScope(IDirect3DDevice9 *device, bool eligible) : Device(device), Eligible(EnterScene(device, eligible)) {}+ ~SceneScope() { LeaveScene(Device, Eligible); }+ SceneScope(const SceneScope &) = delete;+ SceneScope &operator=(const SceneScope &) = delete;+};+void ExcludeReceivers(IDirect3DDevice9 *device, bool exclude);+// Retain exclusion metadata when a render queue outlives its caller's scope.+bool ReceiversExcluded(IDirect3DDevice9 *device);+class ReceiverExclusion {+ IDirect3DDevice9 *Device;+public:+ explicit ReceiverExclusion(IDirect3DDevice9 *device, bool exclude = true) : Device(exclude ? device : nullptr) { ExcludeReceivers(Device, true); }+ ~ReceiverExclusion() { ExcludeReceivers(Device, false); }+ ReceiverExclusion(const ReceiverExclusion &) = delete;+ ReceiverExclusion &operator=(const ReceiverExclusion &) = delete;+};+std::string Report(IDirect3DDevice9 *device);+}diff --git a/GeneralsMD/Code/Libraries/Include/Platform/SunShadowMode.h b/GeneralsMD/Code/Libraries/Include/Platform/SunShadowMode.hnew file mode 100644index 000000000..818fa7ffa--- /dev/null+++ b/GeneralsMD/Code/Libraries/Include/Platform/SunShadowMode.h@@ -0,0 +1,38 @@+// Sun-depth selection. Normal launches use maps; diagnostic overrides retain legacy/capture modes.+// This never selects dynamic lighting.+#pragma once++#include <cstdlib>+#include <cstring>++namespace SunShadow {+enum class Mode { Legacy, CaptureOnly, Mapped };++inline Mode ParseMode(const char *text, Mode defaultMode)+{+ if (!text || !*text) return defaultMode;+ if (std::strcmp(text, "capture-only") == 0) return Mode::CaptureOnly;+ if (std::strcmp(text, "mapped") == 0) return Mode::Mapped;+ // Unknown values retain the conservative legacy fallback.+ return Mode::Legacy;+}++inline Mode RequestedMode()+{+ const Mode defaultMode = Mode::Mapped;+#if defined(__linux__)+ return ParseMode(std::getenv("ZH_SUN_SHADOW_MODE"), defaultMode);+#else+ return defaultMode;+#endif+}++inline const char *ModeName(Mode mode)+{+ switch (mode) {+ case Mode::CaptureOnly: return "capture-only";+ case Mode::Mapped: return "mapped";+ default: return "legacy";+ }+}+}diff --git a/GeneralsMD/Code/Libraries/Include/Platform/SunSmoke.h b/GeneralsMD/Code/Libraries/Include/Platform/SunSmoke.hnew file mode 100644index 000000000..9b8403299--- /dev/null+++ b/GeneralsMD/Code/Libraries/Include/Platform/SunSmoke.h@@ -0,0 +1,83 @@+#pragma once+// Extracted from WW3D2/dx11backend.cpp (upstream CnCGeneralsZH-Reforged, GPL-3.0-or-later).+// Shared with the Windows smoke map: additive optical-depth moments and nearest front.+#include <cmath>+#include <vector>+namespace SunSmoke {+static const unsigned Texels = 512, MaxCasters = 16384, SplatFloats = 6;+static const float SelfGain = 0.8f, SelfCurve = 16.0f;+// Each caster is a disc facing the sun, drawn as a four corner strip whose corners come from the+// vertex number, so the only buffer is the one holding the casters.+static const char SMOKE_SPLAT_VERTEX_PROGRAM[] =+ "struct Caster\n"+ "{\n"+ " float4 Centre : CENTRE;\n" // the sun's clip x, y and depth, and the radius in clip units+ " float2 Shape : SHAPE;\n" // optical depth through the middle, and the spread in depth+ "};\n"+ "struct Splat\n"+ "{\n"+ " float4 Position : SV_Position;\n"+ " float2 Corner : TEXCOORD0;\n"+ " float3 Moment : TEXCOORD1;\n"+ "};\n"+ "Splat main(Caster caster, uint corner : SV_VertexID)\n"+ "{\n"+ " Splat splat;\n"+ " splat.Corner = float2((corner & 1u) ? 1.0 : -1.0, (corner & 2u) ? 1.0 : -1.0);\n"+ " splat.Position = float4(caster.Centre.xy + splat.Corner * caster.Centre.w, 0.5, 1.0);\n"+ " splat.Moment = float3(caster.Shape.x, caster.Centre.z, caster.Shape.y);\n"+ " return splat;\n"+ "}\n";++// The three sums VOLUMETRIC_SAMPLING reads back, added up by the blend, and in alpha the depth of+// the particle nearest the sun, kept by a minimum blend: the plume's own front, which a particle+// with nothing ahead of it is measured from. The disc is thickest in its middle and thins to+// nothing at its rim, which is the shape every smoke sprite in the game has; outside it the quad's+// corners leave the front alone.+static const char SMOKE_SPLAT_PIXEL_PROGRAM[] =+ "struct Splat\n"+ "{\n"+ " float4 Position : SV_Position;\n"+ " float2 Corner : TEXCOORD0;\n"+ " float3 Moment : TEXCOORD1;\n"+ "};\n"+ "float4 main(Splat splat) : SV_Target\n"+ "{\n"+ " float rim = saturate(1.0 - dot(splat.Corner, splat.Corner));\n"+ " float thickness = splat.Moment.x * rim * rim;\n"+ " float depth = splat.Moment.y;\n"+ " float spread = splat.Moment.z;\n"+ " return float4(thickness, thickness * depth, thickness * (depth * depth + spread * spread),\n"+ " rim > 0.0 ? depth : 1.0);\n"+ "}\n";+++// Input: world xyz, radius, optical depth. Output: clip xyz/radius, optical depth, spread.+inline unsigned Project(const float *sun, const float *casters, unsigned count, std::vector<float> &out)+{+ out.clear();+ if (!casters || !sun) return 0;+ if (count > MaxCasters) count = MaxCasters;+ const float across = std::sqrt(sun[0] * sun[0] + sun[4] * sun[4] + sun[8] * sun[8]);+ const float deep = std::sqrt(sun[2] * sun[2] + sun[6] * sun[6] + sun[10] * sun[10]);+ out.reserve(count * SplatFloats);+ for (unsigned i = 0; i < count; ++i) {+ const float *caster = casters + i * 5;+ bool finite = true;+ for (unsigned k = 0; k < 5; ++k)+ finite = finite && std::isfinite(caster[k]);+ const float w = caster[0] * sun[3] + caster[1] * sun[7] + caster[2] * sun[11] + sun[15];+ if (!finite || !std::isfinite(w) || w <= 0 || caster[3] <= 0 || caster[4] <= 0) continue;+ const float x = (caster[0] * sun[0] + caster[1] * sun[4] + caster[2] * sun[8] + sun[12]) / w;+ const float y = (caster[0] * sun[1] + caster[1] * sun[5] + caster[2] * sun[9] + sun[13]) / w;+ const float z = (caster[0] * sun[2] + caster[1] * sun[6] + caster[2] * sun[10] + sun[14]) / w;+ const float radius = caster[3] * across;+ const float spread = 0.5f * caster[3] * deep;+ if (!std::isfinite(x + y + z + radius + spread) || x < -1 - radius || x > 1 + radius+ || y < -1 - radius || y > 1 + radius || z < -spread || z > 1 + spread) continue;+ const float splat[] = {x, y, z, radius, caster[4], spread};+ out.insert(out.end(), splat, splat + SplatFloats);+ }+ return unsigned(out.size() / SplatFloats);+}+}diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cppindex 73fb2de91..f88b3aa43 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp@@ -18,6 +18,7 @@// Modified 2026 by İlyas Akın for the macOS/Linux port; see NOTICE.md and the git history.#include "dx11runtime.h"+#include "Platform/SunShadow.h"#include <map>#include <stdio.h>@@ -1235,3 +1236,38 @@ void Direct3D11_Take_Frame_Cost(double & pipeline_milliseconds, unsigned & pipel}DX11Texture_Take_Frame_Cost(texture_milliseconds, textures);}++// Shadow-only dispatch; does not change per-pixel lighting capability.+namespace SunShadow {+bool FillSmoke(IDirect3DDevice9 *,const float *c,unsigned n,float s) { return Direct3D11_Fill_Smoke_Map(c,n,s); }+bool CasterEffects(IDirect3DDevice9 *) { return Direct3D11_Draw_Effects(); }+void SetCasterEffect(IDirect3DDevice9 *,unsigned e,const float p[4]) { Direct3D11_Set_Draw_Effect(e,p); }+CasterEffect GetCasterEffect(IDirect3DDevice9 *) {+ CasterEffect effect;+ // Queued caster coverage is Linux-only; preserve Windows sorting behavior.+ return effect;+}+void SetSmokeGlow(IDirect3DDevice9 *,bool g) { Direct3D11_Set_Smoke_Glow(g); }+static bool receiving = false;+bool Begin(IDirect3DDevice9 *, unsigned size) { return Direct3D11_Begin_Shadow_Map(size); }+bool End(IDirect3DDevice9 *) {+ const bool bound = Direct3D11_Shadow_Map_Bound();+ Direct3D11_End_Shadow_Map();+ return bound;+}+void Clear(IDirect3DDevice9 *) { receiving = false; Direct3D11_Clear_Shadow_Parameters(); }+bool Parameters(IDirect3DDevice9 *, float bias, float strength, float widest, float narrowest,+ float texelsPerGap, float unitsPerDepth, float skyFill) {+ if (!Direct3D11_Is_Active()) return false;+ Direct3D11_Set_Shadow_Parameters(bias,strength,widest,narrowest,texelsPerGap,unitsPerDepth,skyFill);+ receiving = true;+ return true;+}+bool ReceivesView(IDirect3DDevice9 *) { return receiving && Direct3D11_Is_Active(); }+bool OwnsSceneShadows(IDirect3DDevice9 *d) { return ReceivesView(d); }+bool EnterScene(IDirect3DDevice9 *,bool eligible) { return eligible; }+void LeaveScene(IDirect3DDevice9 *,bool) {}+void ExcludeReceivers(IDirect3DDevice9 *, bool) {} // SDL phase-one exclusions; existing D3D11 behavior unchanged.+bool ReceiversExcluded(IDirect3DDevice9 *) { return false; }+std::string Report(IDirect3DDevice9 *) { return Direct3D11_Shadow_Map_Report(); }+}diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8renderer.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8renderer.cppindex 52411b50f..872d89403 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8renderer.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8renderer.cpp@@ -42,6 +42,7 @@//#define ENABLE_CATEGORY_LOG//#define ENABLE_STRIPING+#include "Platform/SunShadow.h"#include "dx8renderer.h"#include "dx8wrapper.h"#include "dx8polygonrenderer.h"@@ -1918,10 +1919,11 @@ void DX8TextureCategoryClass::Render(void)// The object's look on the Direct3D 11 frame (RTS3DScene::renderOneObject picks it), for this// mesh's draws only. A sorted mesh draws later, from the sorting pool, which keeps the look- // with its triangles (SortingRendererClass::Insert_Triangles).+ // with its triangles (SortingRendererClass::Insert_Triangles), and on Linux its sun shadow+ // coverage too.const unsigned draw_effect = mesh->Get_Draw_Effect();if (draw_effect != 0) {- Direct3D11_Set_Draw_Effect(draw_effect, mesh->Get_Draw_Effect_Parameters());+ SunShadow::SetCasterEffect(DX8Wrapper::_Get_D3D_Device(),draw_effect, mesh->Get_Draw_Effect_Parameters());}if ((!!mesh->Peek_Model()->Get_Flag(MeshGeometryClass::SORT)) && WW3D::Is_Sorting_Enabled()) {@@ -1980,7 +1982,7 @@ void DX8TextureCategoryClass::Render(void)}if (draw_effect != 0) {static const float no_effect[4] = { 0.0f, 0.0f, 0.0f, 0.0f };- Direct3D11_Set_Draw_Effect(0, no_effect);+ SunShadow::SetCasterEffect(DX8Wrapper::_Get_D3D_Device(),0, no_effect);}//--------------------------------------------------------------------if (mesh->Get_ObjectScale() != 1.0f)diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cppindex 9c001632c..f19415f74 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp@@ -155,6 +155,8 @@ IDirect3DPixelShader9 * DX8Wrapper::Pixel_Shader = NULL;Vector4 DX8Wrapper::Vertex_Shader_Constants[MAX_VERTEX_SHADER_CONSTANTS];Vector4 DX8Wrapper::Pixel_Shader_Constants[MAX_PIXEL_SHADER_CONSTANTS];+bool DX8Wrapper::Vertex_Shader_Constants_Valid[MAX_VERTEX_SHADER_CONSTANTS] = {};+bool DX8Wrapper::Pixel_Shader_Constants_Valid[MAX_PIXEL_SHADER_CONSTANTS] = {};LightEnvironmentClass* DX8Wrapper::Light_Environment = NULL;RenderInfoClass* DX8Wrapper::Render_Info = NULL;@@ -723,6 +725,10 @@ void DX8Wrapper::Invalidate_Cached_Render_States(void)render_state_changed=0;CurrentDX8MaterialValid=false;CurrentDX8LightsValid=0;+ // A native pass restores device constants behind the wrapper's cache. The+ // next setter must resend even an unchanged value (tree shroud UVs included).+ memset(Vertex_Shader_Constants_Valid, 0, sizeof(Vertex_Shader_Constants_Valid));+ memset(Pixel_Shader_Constants_Valid, 0, sizeof(Pixel_Shader_Constants_Valid));int a;for (a=0;a<sizeof(RenderStates)/sizeof(unsigned);++a) {diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.hindex 6bd0a3eae..e53beb1e8 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.h+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.h@@ -981,6 +981,8 @@ protected:static Vector4 Vertex_Shader_Constants[MAX_VERTEX_SHADER_CONSTANTS];static Vector4 Pixel_Shader_Constants[MAX_PIXEL_SHADER_CONSTANTS];+ static bool Vertex_Shader_Constants_Valid[MAX_VERTEX_SHADER_CONSTANTS];+ static bool Pixel_Shader_Constants_Valid[MAX_PIXEL_SHADER_CONSTANTS];static LightEnvironmentClass* Light_Environment;static RenderInfoClass* Render_Info;@@ -1110,28 +1112,45 @@ WWINLINE void DX8Wrapper::Set_Vertex_Shader_Constant(int reg, const void* data,{int memsize=sizeof(Vector4)*count;- // Ahead of the comparison below, not behind it. Invalidate_Cached_Render_States zeroes this- // cache without zeroing the device, so a set that writes zeros after one of those is skipped- // here while the device really does hold zeros - and the backend, which is not reset by that- // call, would keep whatever it was last told.+ // The mirrored backend owns its own cache and must see every requested update.Direct3D11_Mirror_Vertex_Shader_Constant((unsigned)reg, (const float*)data, (unsigned)count);- // may be incorrect if shaders are created and destroyed dynamically+#if defined(__linux__)+ bool valid = true;+ for (int i = reg; i < reg + count; ++i)+ valid = valid && Vertex_Shader_Constants_Valid[i];+ if (valid && memcmp(data, &Vertex_Shader_Constants[reg],memsize)==0) return;+#elseif (memcmp(data, &Vertex_Shader_Constants[reg],memsize)==0) return;+#endifmemcpy(&Vertex_Shader_Constants[reg],data,memsize);DX8CALL(SetVertexShaderConstantF(reg,(const float*)data,count));+#if defined(__linux__)+ for (int i = reg; i < reg + count; ++i)+ Vertex_Shader_Constants_Valid[i] = true;+#endif}WWINLINE void DX8Wrapper::Set_Pixel_Shader_Constant(int reg, const void* data, int count){int memsize=sizeof(Vector4)*count;- // may be incorrect if shaders are created and destroyed dynamically+#if defined(__linux__)+ bool valid = true;+ for (int i = reg; i < reg + count; ++i)+ valid = valid && Pixel_Shader_Constants_Valid[i];+ if (valid && memcmp(data, &Pixel_Shader_Constants[reg],memsize)==0) return;+#elseif (memcmp(data, &Pixel_Shader_Constants[reg],memsize)==0) return;+#endifmemcpy(&Pixel_Shader_Constants[reg],data,memsize);DX8CALL(SetPixelShaderConstantF(reg,(const float*)data,count));+#if defined(__linux__)+ for (int i = reg; i < reg + count; ++i)+ Pixel_Shader_Constants_Valid[i] = true;+#endif}// shader system updates KJM ^diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.cppindex 9de0478f1..4a0c19f69 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.cpp@@ -488,7 +488,7 @@ bool EngineShader_Pixel_Program(EngineShaderProgram program,return false;}if (target == COMBINER_SHADER_TARGET_SDL3_GPU) {- return write_engine_pixel_program(program, pipeline, hlsl, false)+ return write_engine_pixel_program(program, pipeline, hlsl, EngineShader_Paints_Ground(program))&& SDL3_Shader_Retarget(hlsl, false);}return write_engine_pixel_program(program, pipeline, hlsl, true);diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.cppindex de79ad6f7..868d6a403 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.cpp@@ -239,11 +239,14 @@ static bool generate_combiners(const CombinerDescription & description,bool CombinerShader_Generate(const CombinerDescription & description, CombinerShaderTarget target,std::string & hlsl){- // The SDL3 GPU program is the D3D11 one with its bindings rewritten, so everything below only- // ever sees the two profiles it was written for. It goes without the smoke: its backend binds- // nothing at t6 and uploads no field past SkyUp (SdlEnginePixelConstants).+ // SDL shares D3D11 arithmetic and constant layouts, then rewrites resource bindings.+ // Its cloak caster needs only ordered coverage, without cosmetic scene resources.if (target == COMBINER_SHADER_TARGET_SDL3_GPU) {- return generate_combiners(description, COMBINER_SHADER_TARGET_D3D11, hlsl, false)+ CombinerDescription supported = description;+ // Scene-depth fading and cosmetic refraction still have separate SDL integration work.+ supported.SoftParticle = SOFT_PARTICLE_NONE;+ if (supported.DrawEffect != DRAW_EFFECT_CLOAK_SHADOW) supported.DrawEffect = DRAW_EFFECT_NONE;+ return generate_combiners(supported, target, hlsl, true)&& SDL3_Shader_Retarget(hlsl, false);}return generate_combiners(description, target, hlsl, target == COMBINER_SHADER_TARGET_D3D11);@@ -252,10 +255,11 @@ bool CombinerShader_Generate(const CombinerDescription & description, CombinerShstatic bool generate_combiners(const CombinerDescription & description,CombinerShaderTarget target, std::string & hlsl, bool volumetric){- // The soft particles ride on the Direct3D 11 text for the smoke's reason: the SDL3 backend binds- // nothing at t7 and uploads nothing past SkyUp.+ const bool sdl = target == COMBINER_SHADER_TARGET_SDL3_GPU;+ if (sdl) target = COMBINER_SHADER_TARGET_D3D11;+ // Depth-faded particles remain Windows-only until SDL supplies the scene depth at t7.const bool soft = volumetric && description.SoftParticle != SOFT_PARTICLE_NONE;- // The per-object looks likewise: nothing past SoftParticleDepth reaches the SDL3 programs.+ // SDL accepts only the cloak caster variant; Windows also supplies the cosmetic scene effects.const unsigned effect = (volumetric && description.DrawEffect < DRAW_EFFECT_COUNT)? description.DrawEffect : DRAW_EFFECT_NONE;// The fire look reads no constant, but the vertex half that feeds it is the D3D11 one's.@@ -403,7 +407,9 @@ static bool generate_combiners(const CombinerDescription & description,hlsl += SOFT_PARTICLE_SAMPLING;}if (effect != DRAW_EFFECT_NONE) {- hlsl += DRAW_EFFECT_SAMPLING;+ // SDL admits only the cloak caster. The complete cosmetic helper declares+ // SceneColour at t8 even when unused, exceeding its eight-slot draw layout.+ hlsl += sdl ? CLOAK_SHADOW_SAMPLING : DRAW_EFFECT_SAMPLING;}if (fire != FIRE_LOOK_NONE) {hlsl += FIRE_LOOK_SAMPLING;diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.hindex 27f1e4dd0..abcb88a51 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.h+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.h@@ -168,8 +168,8 @@ const unsigned NORMAL_MAPPED_LIGHTS = 4;"float sun_reaching(float4 position)\n" \"{\n" \" if (ShadowParameters.z <= 0.0) return 1.0;\n" \- " float2 ndc = float2(position.x * ShadowViewport.x * 2.0 - 1.0,\n" \- " 1.0 - position.y * ShadowViewport.y * 2.0);\n" \+ " float2 ndc = float2((position.x - ShadowViewport.z) * ShadowViewport.x * 2.0 - 1.0,\n" \+ " 1.0 - (position.y - ShadowViewport.w) * ShadowViewport.y * 2.0);\n" \" float4 sun = mul(float4(ndc, position.z, 1.0), ShadowFromClip);\n" \" if (sun.w <= 0.0) return 1.0;\n" \" sun /= sun.w;\n" \@@ -254,9 +254,7 @@ const unsigned NORMAL_MAPPED_LIGHTS = 4;#define SHADOW_APPLY SHADOW_LIT \" current.rgb *= lerp(1.0, sun_reaching(input.Position), shadow_lit);\n"-// The smoke in the sun's light, for the Direct3D 11 programs only: written after SHADOW_SAMPLING,-// whose map and matrix it reads, and kept out of the SDL3 GPU text, which declares neither the-// field it adds to the constant block nor a texture at t6.+// Shared Windows and SDL smoke sampling, following SHADOW_SAMPLING.//// The smoke has a map of its own over the same sun (DX11BackendClass::Fill_Smoke_Map). Each texel// holds three sums over the particles the sun sees through it: their optical depth, that times@@ -274,14 +272,14 @@ const unsigned NORMAL_MAPPED_LIGHTS = 4;// plume's sun side lit. .z is one for a draw whose vertices are in camera space already, which is the// particles: they take the sun's map through four wide taps, because a smoke sprite drawn twenty// deep would otherwise pay the fifty taps the ground pays, twenty times over.-#define VOLUMETRIC_SAMPLING \+#define SUN_SMOKE_SAMPLING \"Texture2D SmokeMap : register(t6);\n" \"SamplerState SmokeSampler : register(s6);\n" \"\n" \"bool sun_point(float4 position, out float3 sun)\n" \"{\n" \- " float2 ndc = float2(position.x * ShadowViewport.x * 2.0 - 1.0,\n" \- " 1.0 - position.y * ShadowViewport.y * 2.0);\n" \+ " float2 ndc = float2((position.x - ShadowViewport.z) * ShadowViewport.x * 2.0 - 1.0,\n" \+ " 1.0 - (position.y - ShadowViewport.w) * ShadowViewport.y * 2.0);\n" \" float4 at = mul(float4(ndc, position.z, 1.0), ShadowFromClip);\n" \" sun = float3(0.0, 0.0, 0.0);\n" \" if (at.w <= 0.0) return false;\n" \@@ -343,9 +341,9 @@ const unsigned NORMAL_MAPPED_LIGHTS = 4;" else sun = sun_reaching(position);\n" \" return sun * smoke_reaching(position);\n" \"}\n" \- "\n" \- HEADLIGHT_SAMPLING \- BLAST_LIGHT_SAMPLING+ "\n"++#define VOLUMETRIC_SAMPLING SUN_SMOKE_SAMPLING HEADLIGHT_SAMPLING BLAST_LIGHT_SAMPLING// Vehicle headlights on a night map, Direct3D 11 only and riding on the smoke's text for that// reason: one spot light per lit vehicle, the nearest HEADLIGHT_SLOTS to the camera@@ -554,6 +552,22 @@ const unsigned NORMAL_MAPPED_LIGHTS = 4;#define DRAW_EFFECT_CONSTANTS \" float4 DrawEffectParameters;\n"+// Ordered cloak coverage reads only the caster opacity; it needs no scene texture.+#define CLOAK_SHADOW_SAMPLING \+ "/* Own stealthed unit drawn into the sun's map. A depth map holds a caster or not, so the\n" \+ " cloaked one keeps a share of its texels, an ordered four by four pattern, and the receiving\n" \+ " filter, which averages a square of taps over several texels, turns that share into a shadow\n" \+ " that strength. Half the stealth opacity: a quarter to a half, breathing with the body. */\n" \+ "float4 effect_cloak_shadow(float4 current, float4 position)\n" \+ "{\n" \+ " uint2 cell = uint2(position.xy) & 3u;\n" \+ " uint bayer = ((cell.x ^ cell.y) & 1u) * 8u + (cell.y & 1u) * 4u\n" \+ " + (((cell.x ^ cell.y) >> 1) & 1u) * 2u + ((cell.y >> 1) & 1u);\n" \+ " clip(DrawEffectParameters.w * 0.5 - ((float)bayer + 0.5) / 16.0);\n" \+ " return current;\n" \+ "}\n" \+ "\n"+#define DRAW_EFFECT_SAMPLING \"Texture2D SceneColour : register(t8);\n" \"\n" \@@ -723,19 +737,7 @@ const unsigned NORMAL_MAPPED_LIGHTS = 4;" return current;\n" \"}\n" \"\n" \- "/* Own stealthed unit drawn into the sun's map. A depth map holds a caster or not, so the\n" \- " cloaked one keeps a share of its texels, an ordered four by four pattern, and the receiving\n" \- " filter, which averages a square of taps over several texels, turns that share into a shadow\n" \- " that strength. Half the stealth opacity: a quarter to a half, breathing with the body. */\n" \- "float4 effect_cloak_shadow(float4 current, float4 position)\n" \- "{\n" \- " uint2 cell = uint2(position.xy) & 3u;\n" \- " uint bayer = ((cell.x ^ cell.y) & 1u) * 8u + (cell.y & 1u) * 4u\n" \- " + (((cell.x ^ cell.y) >> 1) & 1u) * 2u + ((cell.y >> 1) & 1u);\n" \- " clip(DrawEffectParameters.w * 0.5 - ((float)bayer + 0.5) / 16.0);\n" \- " return current;\n" \- "}\n" \- "\n"+ CLOAK_SHADOW_SAMPLING// SHADOW_APPLY with the smoke in it. A particle takes the shade whatever its own brightness: the// threshold is there for ground under the shroud, and on smoke it tied the shade to the colour, sodiff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/sortingrenderer.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/sortingrenderer.cppindex 143d78c75..0d6792ace 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/sortingrenderer.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/sortingrenderer.cpp@@ -40,6 +40,7 @@* Functions: ** - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */+#include "Platform/SunShadow.h"#include "sortingrenderer.h"#include "dx8vertexbuffer.h"#include "dx8indexbuffer.h"@@ -139,6 +140,8 @@ class SortingNodeStruct : public DLNodeClass<SortingNodeStruct>public:RenderStateStruct sorting_state;+ bool excludeSunReceivers;+ SunShadow::CasterEffect casterEffect;SphereClass bounding_sphere;@@ -241,6 +244,8 @@ void SortingRendererClass::Insert_Triangles(SortingNodeStruct* state=Get_Sorting_Struct();DX8Wrapper::Get_Render_State(state->sorting_state);+ state->excludeSunReceivers = SunShadow::ReceiversExcluded(DX8Wrapper::_Get_D3D_Device());+ state->casterEffect = SunShadow::GetCasterEffect(DX8Wrapper::_Get_D3D_Device());WWASSERT(((state->sorting_state.index_buffer_type==BUFFER_TYPE_SORTING || state->sorting_state.index_buffer_type==BUFFER_TYPE_DYNAMIC_SORTING) &&@@ -357,6 +362,8 @@ void SortingRendererClass::Insert_Quads(SortingNodeStruct* state=Get_Sorting_Struct();DX8Wrapper::Get_Render_State(state->sorting_state);+ state->excludeSunReceivers = SunShadow::ReceiversExcluded(DX8Wrapper::_Get_D3D_Device());+ state->casterEffect = SunShadow::GetCasterEffect(DX8Wrapper::_Get_D3D_Device());WWASSERT(((state->sorting_state.index_buffer_type==BUFFER_TYPE_SORTING || state->sorting_state.index_buffer_type==BUFFER_TYPE_DYNAMIC_SORTING) &&@@ -746,13 +753,17 @@ static void Flush_Sorting_Batch(const TempIndexStruct* entries,unsigned entry_co// two never share a draw even in one state.if (state->glow!=next->glow || state->fire!=next->fire || state->emissive!=next->emissive ||state->quads!=next->quads || !Same_Draw_Effect(state,next) ||+ state->excludeSunReceivers!=next->excludeSunReceivers ||+ !(state->casterEffect==next->casterEffect) ||!Same_Draw_State(state->sorting_state,next->sorting_state)) {Apply_Render_State(state->sorting_state);- Direct3D11_Set_Smoke_Glow(state->glow);+ SunShadow::SetSmokeGlow(DX8Wrapper::_Get_D3D_Device(),state->glow);Direct3D11_Set_Fire_Look(state->fire);Direct3D11_Set_Emissive(state->emissive);Direct3D11_Set_Soft_Particles(state->quads);Direct3D11_Set_Draw_Effect(state->draw_effect,state->draw_effect_parameters);+ SunShadow::ReceiverExclusion sunReceivers(DX8Wrapper::_Get_D3D_Device(), state->excludeSunReceivers);+ SunShadow::CasterEffectScope casterEffect(DX8Wrapper::_Get_D3D_Device(), state->casterEffect);DX8Wrapper::Draw_Triangles(run_first_index,run_triangles,run_first_vertex,vertex_cursor-run_first_vertex);run_first_index=index_cursor;run_first_vertex=vertex_cursor;@@ -766,13 +777,17 @@ static void Flush_Sorting_Batch(const TempIndexStruct* entries,unsigned entry_co}Apply_Render_State(overlapping_nodes[node_id]->sorting_state);- Direct3D11_Set_Smoke_Glow(overlapping_nodes[node_id]->glow);+ SunShadow::SetSmokeGlow(DX8Wrapper::_Get_D3D_Device(),overlapping_nodes[node_id]->glow);Direct3D11_Set_Fire_Look(overlapping_nodes[node_id]->fire);Direct3D11_Set_Emissive(overlapping_nodes[node_id]->emissive);Direct3D11_Set_Soft_Particles(overlapping_nodes[node_id]->quads);Direct3D11_Set_Draw_Effect(overlapping_nodes[node_id]->draw_effect,overlapping_nodes[node_id]->draw_effect_parameters);- DX8Wrapper::Draw_Triangles(run_first_index,run_triangles,run_first_vertex,vertex_cursor-run_first_vertex);- Direct3D11_Set_Smoke_Glow(false);+ {+ SunShadow::ReceiverExclusion sunReceivers(DX8Wrapper::_Get_D3D_Device(), overlapping_nodes[node_id]->excludeSunReceivers);+ SunShadow::CasterEffectScope casterEffect(DX8Wrapper::_Get_D3D_Device(), overlapping_nodes[node_id]->casterEffect);+ DX8Wrapper::Draw_Triangles(run_first_index,run_triangles,run_first_vertex,vertex_cursor-run_first_vertex);+ }+ SunShadow::SetSmokeGlow(DX8Wrapper::_Get_D3D_Device(),false);Direct3D11_Set_Fire_Look(false);Direct3D11_Set_Emissive(false);Direct3D11_Set_Soft_Particles(false);@@ -994,6 +1009,8 @@ void SortingRendererClass::Flush()}else {DX8Wrapper::Set_Render_State(state->sorting_state);+ SunShadow::ReceiverExclusion sunReceivers(DX8Wrapper::_Get_D3D_Device(), state->excludeSunReceivers);+ SunShadow::CasterEffectScope casterEffect(DX8Wrapper::_Get_D3D_Device(), state->casterEffect);DX8Wrapper::Draw_Triangles(state->start_index,state->polygon_count,state->min_vertex_index,state->vertex_count);DX8Wrapper::Release_Render_State();Release_Refs(state);@@ -1085,6 +1102,8 @@ void SortingRendererClass::Insert_VolumeParticle(SortingNodeStruct* state=Get_Sorting_Struct();DX8Wrapper::Get_Render_State(state->sorting_state);+ state->excludeSunReceivers = SunShadow::ReceiversExcluded(DX8Wrapper::_Get_D3D_Device());+ state->casterEffect = SunShadow::GetCasterEffect(DX8Wrapper::_Get_D3D_Device());WWASSERT(((state->sorting_state.index_buffer_type==BUFFER_TYPE_SORTING || state->sorting_state.index_buffer_type==BUFFER_TYPE_DYNAMIC_SORTING) &&diff --git a/GeneralsMD/Code/Tests/test_ffshadercompile.cpp b/GeneralsMD/Code/Tests/test_ffshadercompile.cppindex e1d1864e6..ba0ced2dc 100644--- a/GeneralsMD/Code/Tests/test_ffshadercompile.cpp+++ b/GeneralsMD/Code/Tests/test_ffshadercompile.cpp@@ -206,10 +206,8 @@ TEST(ffshadercompile_the_tree_shadow_program_compiles)CHECK(compiles(compile, eleven, D3D11_PROFILE));}-// A program that takes the sun's shadow takes the smoke's with it on Direct3D 11: the smoke's map at-// t6 and the field after SkyUp. The SDL3 GPU text is made from the same generator and must stay-// without both, because that backend binds no map there and uploads no such field.-TEST(ffshadercompile_a_shadow_receiving_program_reads_the_smoke_on_d3d11_only)+// Windows and SDL receivers share the smoke map at t6 and its constants after SkyUp.+TEST(ffshadercompile_shadow_receivers_share_the_smoke_filter){CombinerDescription description;memset(&description, 0, sizeof(description));@@ -227,8 +225,9 @@ TEST(ffshadercompile_a_shadow_receiving_program_reads_the_smoke_on_d3d11_only)std::string sdl;CHECK(CombinerShader_Generate(description, COMBINER_SHADER_TARGET_SDL3_GPU, sdl));- CHECK(sdl.find("SmokeMap") == std::string::npos);- CHECK(sdl.find("VolumeParameters") == std::string::npos);+ CHECK(sdl.find("register(t6, space2)") != std::string::npos);+ CHECK(sdl.find("VolumeParameters") > sdl.find("SkyUp"));+ CHECK(sdl.find("light_reaching(input.Position)") != std::string::npos);D3DCompileFunction compile = load_compiler();if (compile == NULL) {@@ -368,7 +367,8 @@ TEST(ffshadercompile_each_draw_effect_compiles_on_d3d11_only)std::string nine;CHECK(CombinerShader_Generate(description, COMBINER_SHADER_TARGET_SDL3_GPU, sdl));CHECK(CombinerShader_Generate(description, COMBINER_SHADER_TARGET_D3D9, nine));- CHECK(sdl.find("effect_") == std::string::npos);+ CHECK((sdl.find("current = effect_cloak_shadow(") != std::string::npos) == (effect == DRAW_EFFECT_CLOAK_SHADOW));+ if (effect != DRAW_EFFECT_CLOAK_SHADOW) CHECK(sdl.find("effect_") == std::string::npos);CHECK(nine.find("effect_") == std::string::npos);if (compile != NULL) {diff --git a/GeneralsMD/Code/Tests/test_posix_draw_resolve.cpp b/GeneralsMD/Code/Tests/test_posix_draw_resolve.cppindex 5eba9eb6c..a9ef03b27 100644--- a/GeneralsMD/Code/Tests/test_posix_draw_resolve.cpp+++ b/GeneralsMD/Code/Tests/test_posix_draw_resolve.cpp@@ -39,6 +39,7 @@#include "SdlConstants.h"#include "ffshader.h"#include "ffvertex.h"+#include "Platform/SunShadowMode.h"#include <math.h>#include <stdio.h>@@ -290,6 +291,34 @@ static void check_constants(PosixDevice9 *device)int main(){+ using SunShadow::Mode;+ CHECK(SunShadow::ParseMode(NULL, Mode::Legacy) == Mode::Legacy);+ CHECK(SunShadow::ParseMode("", Mode::Mapped) == Mode::Mapped);+ CHECK(SunShadow::ParseMode("legacy", Mode::Mapped) == Mode::Legacy);+ CHECK(SunShadow::ParseMode("capture-only", Mode::Legacy) == Mode::CaptureOnly);+ CHECK(SunShadow::ParseMode("mapped", Mode::Legacy) == Mode::Mapped);+ CHECK(SunShadow::ParseMode("mappde", Mode::Mapped) == Mode::Legacy);+ const char *savedMode = getenv("ZH_SUN_SHADOW_MODE");+ const bool hadMode = savedMode != NULL;+ const std::string savedModeText = savedMode ? savedMode : "";+ unsetenv("ZH_SUN_SHADOW_MODE");+ CHECK(SunShadow::RequestedMode() == Mode::Mapped);+ setenv("ZH_SUN_SHADOW_MODE", "mapped", 1);+ CHECK(SunShadow::RequestedMode() == Mode::Mapped);+ setenv("ZH_SUN_SHADOW_MODE", "capture-only", 1);+#if defined(__linux__)+ CHECK(SunShadow::RequestedMode() == Mode::CaptureOnly);+#else+ CHECK(SunShadow::RequestedMode() == Mode::Mapped);+#endif+ setenv("ZH_SUN_SHADOW_MODE", "legacy", 1);+#if defined(__linux__)+ CHECK(SunShadow::RequestedMode() == Mode::Legacy);+#else+ CHECK(SunShadow::RequestedMode() == Mode::Mapped);+#endif+ if (hadMode) setenv("ZH_SUN_SHADOW_MODE", savedModeText.c_str(), 1);+ else unsetenv("ZH_SUN_SHADOW_MODE");IDirect3D9 *d3d = NULL;PosixDevice9 *device = make_device(d3d);CHECK(device != NULL);diff --git a/GeneralsMD/Code/Tests/test_posix_gpu_draw.cpp b/GeneralsMD/Code/Tests/test_posix_gpu_draw.cppindex 1967f149b..3e9ac3b0f 100644--- a/GeneralsMD/Code/Tests/test_posix_gpu_draw.cpp+++ b/GeneralsMD/Code/Tests/test_posix_gpu_draw.cpp@@ -39,6 +39,10 @@#include "PosixDevice9.h"#include "SdlGpuFrame.h"#include "SdlResourceMirror.h"+#include "Platform/SunShadow.h"+#include "Platform/SunSmoke.h"+#include "../Libraries/Source/WWVegas/WW3D2/ffshader.h"+#include "Platform/EngineShaderName.h"#include <SDL3/SDL.h>@@ -529,6 +533,681 @@ static void check_render_targets(PosixDevice9 *device)target_texture->Release();}+#if defined(__linux__)+// Runtime sun capture and diagnostic mode overrides are enabled only on Linux.+static void check_sun_capture(PosixDevice9 *device)+{+ begin(device, BLUE);+ device->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE);+ device->SetRenderState(D3DRS_ZWRITEENABLE, 1);+ device->SetRenderState(D3DRS_ZFUNC, D3DCMP_LESSEQUAL);+ device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);+ device->SetRenderState(D3DRS_ALPHABLENDENABLE, 0);+ device->SetRenderState(D3DRS_ALPHATESTENABLE, 0);+ D3DVIEWPORT9 sceneView = {3, 5, 24, 20, 0, 1};+ device->SetViewport(&sceneView);+ ScreenVertex v[6];+ quad(v, 0, 0, 32, 32, .4f, RED);+ CHECK(device->DrawPrimitiveUP(D3DPT_TRIANGLELIST, 2, v, sizeof(v[0])) == D3D_OK);+ read_back(device);+ const std::vector<uint8_t> scene = pixels;++ IDirect3DTexture9 *savedTexture = NULL;+ CHECK(device->CreateTexture(1,1,1,0,D3DFMT_A8R8G8B8,D3DPOOL_MANAGED,&savedTexture,NULL)==D3D_OK);+ device->SetTexture(7,savedTexture); // unused by this program, owned across the pass+ D3DMATRIX sceneWorld;+ device->GetTransform(D3DTS_WORLD,&sceneWorld);+ CHECK(!device->Begin_Sun_Shadow(0));+ CHECK(device->Begin_Sun_Shadow(32));+ CHECK(!device->Begin_Sun_Shadow(64)); // re-entry leaves the first capture intact+ device->SetTexture(7,NULL);+ savedTexture->Release(); // the capture now holds the only reference+ D3DMATRIX casterWorld=sceneWorld; casterWorld._41=13.0f;+ device->SetTransform(D3DTS_WORLD,&casterWorld);+ device->SetRenderState(D3DRS_ZWRITEENABLE, 0); // a sorted rotor still writes sun depth+ device->SetRenderState(D3DRS_ALPHABLENDENABLE, 1);+ device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);+ device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);+ quad(v, 0, 0, 16, 32, .3f, 0x0700FF00); // below the existing 8/255 caster threshold+ device->DrawPrimitiveUP(D3DPT_TRIANGLELIST, 2, v, sizeof(v[0]));+ quad(v, 16, 0, 32, 32, .3f, 0x8000FF00);+ device->DrawPrimitiveUP(D3DPT_TRIANGLELIST, 2, v, sizeof(v[0]));+ device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE); // additive light must not occlude+ quad(v, 0, 0, 32, 32, .1f, WHITE);+ device->DrawPrimitiveUP(D3DPT_TRIANGLELIST, 2, v, sizeof(v[0]));+ CHECK(device->End_Sun_Shadow());+ D3DVIEWPORT9 restored;+ device->GetViewport(&restored);+ CHECK(memcmp(&restored, &sceneView, sizeof(restored)) == 0);+ RenderUInt32 blend=1,write=0;+ device->GetRenderState(D3DRS_ALPHABLENDENABLE,&blend);+ device->GetRenderState(D3DRS_ZWRITEENABLE,&write);+ CHECK(blend==0 && write==1);+ D3DMATRIX restoredWorld;device->GetTransform(D3DTS_WORLD,&restoredWorld);+ CHECK(memcmp(&sceneWorld,&restoredWorld,sizeof(sceneWorld))==0);+ IDirect3DBaseTexture9 *restoredTexture=NULL;+ device->GetTexture(7,&restoredTexture);+ CHECK(restoredTexture==savedTexture && restoredTexture->GetLevelCount()==1);+ if(restoredTexture) restoredTexture->Release();+ device->SetTexture(7,NULL);+ read_back(device);+ CHECK(pixels == scene);+ std::vector<float> depth;+ CHECK(device->Read_Sun_Shadow(depth));+ if (depth.size()==32*32) {+ CHECK(depth[16*32+8]==1.0f);+ CHECK(depth[16*32+24]>.299f && depth[16*32+24]<.301f);+ } else CHECK(false);+ // Scene depth and the restored state must survive too, not just its color.+ quad(v, 0, 0, 32, 32, .6f, GREEN);+ device->DrawPrimitiveUP(D3DPT_TRIANGLELIST, 2, v, sizeof(v[0]));+ read_back(device);+ CHECK(pixels == scene);++ CHECK(device->Begin_Sun_Shadow(64));+ CHECK(device->End_Sun_Shadow()); // no casters must erase stale depth+ CHECK(device->Read_Sun_Shadow(depth));+ for(float d:depth) CHECK(d==1.0f);+ CHECK(device->Begin_Sun_Shadow(32));+ CHECK(device->DrawPrimitiveUP(D3DPT_TRIANGLELIST,1,NULL,sizeof(v[0]))==D3DERR_INVALIDCALL);+ CHECK(!device->End_Sun_Shadow());+ CHECK(device->Begin_Sun_Shadow(32));+ CHECK(device->DrawPrimitiveUP((D3DPRIMITIVETYPE)999,1,v,sizeof(v[0]))==D3DERR_INVALIDCALL);+ CHECK(!device->End_Sun_Shadow()); // rejected capture must not authorize stencil suppression+ CHECK(!device->Read_Sun_Shadow(depth));+ device->Clear_Sun_Shadow();+ sceneView={0,0,SIZE,SIZE,0,1};device->SetViewport(&sceneView);+ device->SetRenderState(D3DRS_CULLMODE,D3DCULL_CCW);+ printf("sun capture: alpha/rotor and additive rules, scene color/depth/state, empty/resize/refusal checked\n");+}++// An independent world-space fixture: a left-half blocker at z=.25, white ground+// at z=.75, and a translated/scaled scene camera with a nonzero viewport origin.+static void check_sun_receivers(PosixDevice9 *device)+{+ const char *oldMode = getenv("ZH_SUN_SHADOW_MODE");+ const std::string savedMode = oldMode ? oldMode : "";+ const bool hadMode = oldMode != NULL;+ setenv("ZH_SUN_SHADOW_MODE","mapped",1);+ {+ SunShadow::SceneScope mainScene(device,true);+ D3DMATRIX identity = {}; identity._11=identity._22=identity._33=identity._44=1;+ device->SetTransform(D3DTS_WORLD,&identity);+ device->SetTransform(D3DTS_VIEW,&identity);+ device->SetTransform(D3DTS_PROJECTION,&identity);+ begin(device,BLUE);+ device->SetRenderState(D3DRS_ZENABLE,1);+ device->SetRenderState(D3DRS_ZWRITEENABLE,1);+ device->SetRenderState(D3DRS_ZFUNC,D3DCMP_LESSEQUAL);+ device->SetRenderState(D3DRS_CULLMODE,D3DCULL_NONE);+ device->SetRenderState(D3DRS_ALPHABLENDENABLE,0);+ device->SetRenderState(D3DRS_ALPHATESTENABLE,0);+ device->SetFVF(D3DFVF_XYZ|D3DFVF_DIFFUSE);+ struct V { float x,y,z; uint32_t color; };+ const V caster[] = {{-1,1,.25f,WHITE},{0,1,.25f,WHITE},{-1,-1,.25f,WHITE},+ {0,1,.25f,WHITE},{0,-1,.25f,WHITE},{-1,-1,.25f,WHITE}};+ const V receiver[] = {{-1,1,.75f,WHITE},{1,1,.75f,WHITE},{-1,-1,.75f,WHITE},+ {1,1,.75f,WHITE},{1,-1,.75f,WHITE},{-1,-1,.75f,WHITE}};+ CHECK(device->Begin_Sun_Shadow(32));+ CHECK(device->DrawPrimitiveUP(D3DPT_TRIANGLELIST,2,caster,sizeof(V))==D3D_OK);+ CHECK(device->End_Sun_Shadow());+ D3DMATRIX view=identity,projection=identity;+ view._41=.25f; projection._11=.8f; projection._22=.8f;+ device->SetTransform(D3DTS_VIEW,&view);+ device->SetTransform(D3DTS_PROJECTION,&projection);+ D3DVIEWPORT9 viewport={3,5,24,20,.2f,.8f}; device->SetViewport(&viewport);+ const auto parameters = [&] { return SunShadow::Parameters(device,0,.5f,0,0,0,1,0); };+ CHECK(parameters()); CHECK(SunShadow::ReceivesView(device));+ CHECK(SunShadow::OwnsSceneShadows(device));+ const auto draw = [&] {+ D3DVIEWPORT9 current; device->GetViewport(¤t);+ D3DVIEWPORT9 whole={0,0,SIZE,SIZE,0,1}; device->SetViewport(&whole);+ device->Clear(0,NULL,D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER,BLUE,1,0);+ device->SetViewport(¤t);+ CHECK(device->DrawPrimitiveUP(D3DPT_TRIANGLELIST,2,receiver,sizeof(V))==D3D_OK);+ read_back(device);+ };+ draw();+ CHECK_PIXEL(10,15,0xFF808080); CHECK_PIXEL(17,15,0xFF808080);+ CHECK_PIXEL(18,15,WHITE); CHECK_PIXEL(24,15,WHITE);+ CHECK_PIXEL(1,15,BLUE); CHECK_PIXEL(15,3,BLUE);+ const auto shadowed = pixels;+ CHECK(SunShadow::Parameters(device,0,0,0,0,0,1,0)); draw(); CHECK_PIXEL(10,15,WHITE);+ CHECK(SunShadow::Parameters(device,2,.5f,0,0,0,1,0)); draw(); CHECK_PIXEL(10,15,WHITE);+ CHECK(SunShadow::Parameters(device,0,.5f,4,0,0,1,0)); draw(); CHECK_PIXEL(17,15,0xFF808080);+ CHECK(SunShadow::Parameters(device,0,.5f,4,0,8,1,0)); draw();+ // A .5 depth gap opens the existing radius to four texels: the hard edge now+ // contains both lit and blocked taps. Full sky fill raises the interior to white.+ CHECK((at(17,15)&255)>128 && (at(17,15)&255)<255);+ CHECK(SunShadow::Parameters(device,0,.5f,4,0,8,1,1)); draw(); CHECK_PIXEL(10,15,WHITE);+ CHECK(!SunShadow::Parameters(device,0,.5f,1,2,0,1,0));+ CHECK(!SunShadow::ReceivesView(device));+ CHECK(parameters()); draw(); CHECK(pixels==shadowed);+ // Exercise every transcribed ground pixel program, including the road's blended+ // no-depth-write layer. All-white inputs yield the same analytic .5/1 sunlight.+ IDirect3DTexture9 *white=make_texture(device,1,1,D3DFMT_A8R8G8B8,&WHITE,sizeof(WHITE));+ for(unsigned i=0;i<5;++i) device->SetTexture(i,white);+ const RenderUInt32 tokens[]={0xffff0101u,0x0000ffffu};+ IDirect3DPixelShader9 *ground=NULL; CHECK(device->CreatePixelShader(tokens,&ground)==D3D_OK);+ const char *names[]={"terrain.pso","terrainnoise.pso","terrainnoise2.pso","fterrain.pso",+ "fterrain0.pso","fterrainnoise.pso","fterrainnoise2.pso","roadnoise2.pso"};+ device->SetPixelShader(ground);+ for(const char *name:names) {+ PosixDevice_Name_Shader(ground,name);+ draw(); CHECK_PIXEL(10,15,0xFF808080); CHECK_PIXEL(24,15,WHITE);+ }+ device->SetRenderState(D3DRS_ZWRITEENABLE,0);+ device->SetRenderState(D3DRS_ALPHABLENDENABLE,1);+ device->SetRenderState(D3DRS_SRCBLEND,D3DBLEND_SRCALPHA);+ device->SetRenderState(D3DRS_DESTBLEND,D3DBLEND_INVSRCALPHA);+ draw(); CHECK_PIXEL(10,15,0xFF808080); CHECK_PIXEL(24,15,WHITE);+ device->SetRenderState(D3DRS_ZWRITEENABLE,1);device->SetRenderState(D3DRS_ALPHABLENDENABLE,0);+ device->SetPixelShader(NULL);ground->Release();+ for(unsigned i=0;i<5;++i) device->SetTexture(i,NULL);+ white->Release();+ // Scoped exclusions include nesting. Deferred draws keep their own constant bytes.+ {+ SunShadow::ReceiverExclusion exclusion(device);+ { SunShadow::ReceiverExclusion nested(device); draw(); CHECK_PIXEL(10,15,WHITE); }+ draw(); CHECK_PIXEL(10,15,WHITE);+ }+ draw(); CHECK(pixels==shadowed);+ // A nested scene is independent even if its matrices and viewport match. Its+ // attempted clear/capture must not destroy the outer scene's completed map.+ for (bool eligible : {false,true}) {+ {+ SunShadow::SceneScope nestedScene(device,eligible);+ CHECK(SunShadow::ReceiversExcluded(device));+ CHECK(!SunShadow::ReceivesView(device));+ CHECK(!SunShadow::OwnsSceneShadows(device));+ SunShadow::Clear(device);+ CHECK(!SunShadow::Begin(device,64));+ CHECK(!parameters());+ draw(); CHECK_PIXEL(10,15,WHITE);+ }+ CHECK(!SunShadow::ReceiversExcluded(device));+ CHECK(SunShadow::OwnsSceneShadows(device));+ draw(); CHECK(pixels==shadowed);+ }+ // An independent target cannot borrow shadow ownership even with the exact+ // same camera, depth attachment and viewport. Read both targets independently.+ IDirect3DTexture9 *otherTexture=NULL;+ IDirect3DSurface9 *otherTarget=NULL,*back=NULL,*copy=NULL;+ CHECK(device->CreateTexture(SIZE,SIZE,1,D3DUSAGE_RENDERTARGET,D3DFMT_A8R8G8B8,+ D3DPOOL_DEFAULT,&otherTexture,NULL)==D3D_OK);+ CHECK(otherTexture->GetSurfaceLevel(0,&otherTarget)==D3D_OK);+ CHECK(device->GetRenderTarget(0,&back)==D3D_OK);+ CHECK(device->SetRenderTarget(0,otherTarget)==D3D_OK);+ device->SetViewport(&viewport);+ CHECK(!SunShadow::ReceivesView(device)); CHECK(!SunShadow::OwnsSceneShadows(device));+ draw(); CHECK(pixels==shadowed); // draw() reads the original back buffer+ CHECK(device->CreateOffscreenPlainSurface(SIZE,SIZE,D3DFMT_A8R8G8B8,D3DPOOL_SYSTEMMEM,©,NULL)==D3D_OK);+ CHECK(device->GetRenderTargetData(otherTarget,copy)==D3D_OK);+ D3DLOCKED_RECT locked;+ CHECK(copy->LockRect(&locked,NULL,D3DLOCK_READONLY)==D3D_OK);+ CHECK(((const uint32_t*)((const uint8_t*)locked.pBits+15*locked.Pitch))[10]==WHITE);+ copy->UnlockRect(); copy->Release();+ CHECK(device->SetRenderTarget(0,back)==D3D_OK); device->SetViewport(&viewport);+ otherTarget->Release(); otherTexture->Release(); back->Release();+ CHECK(SunShadow::OwnsSceneShadows(device)); draw(); CHECK(pixels==shadowed);+ // A secondary camera/viewport must keep legacy coverage and receive no stale map.+ D3DVIEWPORT9 other=viewport; other.X=4; device->SetViewport(&other);+ CHECK(!SunShadow::ReceivesView(device)); CHECK(!SunShadow::OwnsSceneShadows(device));+ draw(); CHECK_PIXEL(10,15,WHITE);+ device->SetViewport(&viewport);+ D3DMATRIX otherView=view; otherView._41+=.1f; device->SetTransform(D3DTS_VIEW,&otherView);+ CHECK(!SunShadow::ReceivesView(device));+ // Temporary camera-space drawing within the owning scene must not bring+ // stencil volumes back after other geometry already received mapped shadows.+ CHECK(SunShadow::OwnsSceneShadows(device)); draw(); CHECK_PIXEL(10,15,WHITE);+ device->SetTransform(D3DTS_VIEW,&view);+ draw(); CHECK(pixels==shadowed);+ // Ordinary solid geometry can mark stencil for the later occlusion pass.+ device->SetRenderState(D3DRS_STENCILENABLE,1);+ device->SetRenderState(D3DRS_STENCILFUNC,D3DCMP_ALWAYS);+ device->SetRenderState(D3DRS_STENCILPASS,D3DSTENCILOP_REPLACE);+ device->SetRenderState(D3DRS_STENCILREF,7);+ draw(); CHECK(pixels==shadowed);+ device->SetRenderState(D3DRS_STENCILENABLE,0);+ // The bridge's depth-writing alpha-tested material also uses ordinary alpha+ // blending. Ordinary transparent materials receive too, even without depth writes.+ // Tree exclusion still takes precedence.+ device->SetRenderState(D3DRS_ALPHABLENDENABLE,1);+ device->SetRenderState(D3DRS_SRCBLEND,D3DBLEND_SRCALPHA);+ device->SetRenderState(D3DRS_DESTBLEND,D3DBLEND_INVSRCALPHA);+ device->SetRenderState(D3DRS_ALPHATESTENABLE,1);+ device->SetRenderState(D3DRS_ALPHAFUNC,D3DCMP_GREATER);+ device->SetRenderState(D3DRS_ALPHAREF,8);+ draw(); CHECK(pixels==shadowed);+ { SunShadow::ReceiverExclusion tree(device); draw(); CHECK_PIXEL(10,15,WHITE); }+ device->SetRenderState(D3DRS_ZWRITEENABLE,0); draw(); CHECK(pixels==shadowed);+ device->SetRenderState(D3DRS_ZWRITEENABLE,1);+ device->SetRenderState(D3DRS_ALPHATESTENABLE,0); draw(); CHECK(pixels==shadowed);+ device->SetRenderState(D3DRS_ALPHABLENDENABLE,0);+ // Additive light must stay unshadowed; lack of depth writes alone is not an exclusion.+ device->SetRenderState(D3DRS_ZWRITEENABLE,0); draw(); CHECK(pixels==shadowed);+ device->SetRenderState(D3DRS_ZWRITEENABLE,1);+ device->SetRenderState(D3DRS_ALPHABLENDENABLE,1);+ device->SetRenderState(D3DRS_SRCBLEND,D3DBLEND_ONE);+ device->SetRenderState(D3DRS_DESTBLEND,D3DBLEND_ONE);+ draw(); CHECK_PIXEL(10,15,WHITE);+ device->SetRenderState(D3DRS_ALPHABLENDENABLE,0);+ // Live selection cannot keep receiving an earlier map after switching modes.+ setenv("ZH_SUN_SHADOW_MODE","capture-only",1);+ CHECK(!SunShadow::ReceivesView(device)); CHECK(!parameters()); draw(); CHECK_PIXEL(10,15,WHITE);+ setenv("ZH_SUN_SHADOW_MODE","mapped",1); CHECK(parameters()); draw(); CHECK(pixels==shadowed);+ // Leave a receiver queued against the old allocation, then replace it. End+ // submits both in order; the queued draw must still sample the old blocker.+ device->Clear(0,NULL,D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER,BLUE,1,0);+ device->DrawPrimitiveUP(D3DPT_TRIANGLELIST,2,receiver,sizeof(V));+ CHECK(device->Begin_Sun_Shadow(64)); CHECK(device->End_Sun_Shadow());+ read_back(device); CHECK_PIXEL(10,15,0xFF808080);+ // An empty replacement clears the previous blocker; parameters must be renewed.+ CHECK(!SunShadow::ReceivesView(device)); CHECK(parameters()); draw(); CHECK_PIXEL(10,15,WHITE);+ // Invalid allocation requests fall back immediately; the last map cannot+ // silently remain the current frame's shadow source.+ CHECK(!SunShadow::Begin(device,0)); CHECK(!SunShadow::OwnsSceneShadows(device));+ CHECK(!parameters());+ CHECK(SunShadow::Begin(device,32)); CHECK(SunShadow::End(device)); CHECK(parameters());+ device->SetTransform(D3DTS_VIEW,&identity); device->SetTransform(D3DTS_PROJECTION,&identity);+ viewport={0,0,SIZE,SIZE,0,1};device->SetViewport(&viewport);+ device->SetRenderState(D3DRS_CULLMODE,D3DCULL_CCW);+ } // no capture or stencil ownership may escape its scene+ CHECK(!SunShadow::ReceivesView(device)); CHECK(!SunShadow::OwnsSceneShadows(device));+ std::vector<float> expiredDepth; CHECK(!device->Read_Sun_Shadow(expiredDepth));+ {+ SunShadow::SceneScope nextScene(device,true);+ CHECK(!SunShadow::OwnsSceneShadows(device));+ }+ if(hadMode) setenv("ZH_SUN_SHADOW_MODE",savedMode.c_str(),1); else unsetenv("ZH_SUN_SHADOW_MODE");+ printf("sun receivers: shared filter, offset/depth-range matrix, exclusions, nested scenes, targets, modes and empty replacement checked\n");+}+++// Analytic two-sphere moments, then the production sampler/constant/camera paths.+static void check_sun_smoke(PosixDevice9 *device)+{+ const char *mode=getenv("ZH_SUN_SHADOW_MODE"); const std::string saved=mode?mode:""; const bool had=mode;+ setenv("ZH_SUN_SHADOW_MODE","mapped",1);+ D3DMATRIX identity={}; identity._11=identity._22=identity._33=identity._44=1;+ const float casters[]={0,0,.25f,.5f,1, 0,0,.75f,.5f,2};+ auto *gpu=device->Get_Gpu();+ CHECK(gpu->Fill_Sun_Smoke(&identity._11,casters,2));+ CHECK(gpu->Sun_Smoke_Count()==2);+ std::vector<float> moments;+ CHECK(gpu->Read_Sun_Smoke(moments));+ if(moments.size()==512*512*4) {+ const unsigned middle=(256*512+256)*4;+ const float rim=1-2*(1.0f/256)*(1.0f/256), shape=rim*rim;+ CHECK(std::fabs(moments[middle]-3*shape)<1e-5f);+ CHECK(std::fabs(moments[middle+1]-1.75f*shape)<1e-5f);+ CHECK(std::fabs(moments[middle+2]-1.375f*shape)<1e-5f);+ CHECK(moments[middle+3]==.25f);+ CHECK(moments[0]==0 && moments[1]==0 && moments[2]==0 && moments[3]==1);+ }+ std::vector<float> projected;+ // A quadrant away from the origin catches an inverted Y axis or swapped instance fields.+ const float offcentre[]={.5f,.5f,.3f,.2f,2};+ CHECK(gpu->Fill_Sun_Smoke(&identity._11,offcentre,1));+ CHECK(gpu->Read_Sun_Smoke(moments));+ if(moments.size()==512*512*4) {+ CHECK(moments[(128*512+384)*4]>1.99f);+ CHECK(moments[(128*512+384)*4+3]==.3f);+ CHECK(moments[(384*512+384)*4]==0 && moments[(128*512+128)*4]==0);+ }+ const float invalid[]={4,0,.5f,.1f,1, 0,0,.5f,0,1, 0,0,.5f,.1f,-1,+ 0,0,.5f,.1f,NAN};+ CHECK(SunSmoke::Project(&identity._11,invalid,4,projected)==0);+ std::vector<float> many;+ for(unsigned i=0;i<SunSmoke::MaxCasters+1;++i) many.insert(many.end(),casters,casters+5);+ CHECK(SunSmoke::Project(&identity._11,many.data(),SunSmoke::MaxCasters+1,projected)==SunSmoke::MaxCasters);+ {+ SunShadow::SceneScope scene(device,true);+ device->SetTransform(D3DTS_WORLD,&identity); device->SetTransform(D3DTS_VIEW,&identity);+ device->SetTransform(D3DTS_PROJECTION,&identity);+ D3DVIEWPORT9 viewport={0,0,SIZE,SIZE,0,1};device->SetViewport(&viewport);+ begin(device,0);+ device->SetRenderState(D3DRS_ZENABLE,1);device->SetRenderState(D3DRS_ZWRITEENABLE,1);+ device->SetRenderState(D3DRS_ZFUNC,D3DCMP_LESSEQUAL);device->SetRenderState(D3DRS_CULLMODE,D3DCULL_NONE);+ device->SetRenderState(D3DRS_ALPHABLENDENABLE,0);device->SetRenderState(D3DRS_ALPHATESTENABLE,0);+ CHECK(SunShadow::Begin(device,32)); CHECK(SunShadow::End(device));+ const float cloud[]={0,0,.5f,.5f,2};+ CHECK(SunShadow::FillSmoke(device,cloud,1,.6f));+ viewport={3,5,24,20,.2f,.8f};device->SetViewport(&viewport);+ CHECK(SunShadow::Parameters(device,0,0,0,0,0,1,0));+ struct V {float x,y,z;uint32_t color;};+ const auto draw=[&](float z,uint32_t colour=WHITE,float offset=0,bool read=true,uint32_t background=0) {+ const V v[]={{-2+offset,2,z,colour},{2+offset,2,z,colour},{-2+offset,-2,z,colour},+ {2+offset,2,z,colour},{2+offset,-2,z,colour},{-2+offset,-2,z,colour}};+ device->Clear(0,nullptr,D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER,background,1,0);+ device->SetFVF(D3DFVF_XYZ|D3DFVF_DIFFUSE);+ CHECK(device->DrawPrimitiveUP(D3DPT_TRIANGLELIST,2,v,sizeof(V))==D3D_OK);+ if(read) read_back(device);+ };+ draw(.9f); const int behind=at(15,15)&255;+ CHECK(behind>=123 && behind<=128); // logistic integral, gain .6, optical depth 2+ CHECK_PIXEL(4,6,WHITE); // outside the projected disc, even with viewport/depth offsets+ draw(.1f); CHECK((at(15,15)&255)>=235 && (at(15,15)&255)<=240);+ // Refill must submit the queued old-map reader before overwriting its texture.+ draw(.9f,WHITE,0,false);+ const float moved[]={.8f,.8f,.5f,.1f,2};+ CHECK(SunShadow::FillSmoke(device,moved,1,.6f)); read_back(device);+ CHECK(int(at(15,15)&255)==behind);+ const V farther[]={{-2,2,.95f,GREEN},{2,2,.95f,GREEN},{-2,-2,.95f,GREEN},+ {2,2,.95f,GREEN},{2,-2,.95f,GREEN},{-2,-2,.95f,GREEN}};+ device->DrawPrimitiveUP(D3DPT_TRIANGLELIST,2,farther,sizeof(V));read_back(device);+ CHECK(int(at(15,15)&255)==behind); // refill preserves scene depth as well as colour+ draw(.9f); CHECK_PIXEL(15,15,WHITE);+ CHECK(SunShadow::FillSmoke(device,offcentre,1,.6f));+ draw(.9f); CHECK((at(21,10)&255)>120 && (at(21,10)&255)<140);+ CHECK_PIXEL(9,10,WHITE);CHECK_PIXEL(21,20,WHITE);+ CHECK(SunShadow::FillSmoke(device,cloud,1,.6f));+ device->SetRenderState(D3DRS_ZWRITEENABLE,0);+ device->SetRenderState(D3DRS_ALPHABLENDENABLE,1);+ device->SetRenderState(D3DRS_SRCBLEND,D3DBLEND_SRCALPHA);+ device->SetRenderState(D3DRS_DESTBLEND,D3DBLEND_INVSRCALPHA);+ draw(.9f,0x80ffffff); CHECK(std::abs(int(at(15,15)&255)-behind/2)<=2);+ device->SetRenderState(D3DRS_SRCBLEND,D3DBLEND_ONE);device->SetRenderState(D3DRS_DESTBLEND,D3DBLEND_ONE);+ draw(.9f);CHECK_PIXEL(15,15,WHITE);+ device->SetRenderState(D3DRS_SRCBLEND,D3DBLEND_ZERO);device->SetRenderState(D3DRS_DESTBLEND,D3DBLEND_SRCCOLOR);+ draw(.9f,0xff808080,0,true,WHITE);CHECK_PIXEL(15,15,0xff808080); // multiplier remains unshaded+ device->SetRenderState(D3DRS_ALPHABLENDENABLE,0);+ // Perspective main view, followed by the sorting renderer's camera-space vertices.+ D3DMATRIX view=identity,projection=identity; view._41=.25f;projection._34=.5f;+ device->SetTransform(D3DTS_VIEW,&view);device->SetTransform(D3DTS_PROJECTION,&projection);+ CHECK(SunShadow::Parameters(device,0,0,0,0,0,1,0));+ device->SetTransform(D3DTS_VIEW,&identity);CHECK(SunShadow::ReceivesView(device));+ draw(.25f,WHITE,.25f);CHECK_PIXEL(17,15,WHITE); // sunward face has no smoke ahead+ draw(.9f,WHITE,.25f);CHECK((at(17,15)&255)>70 && (at(17,15)&255)<95);+ const auto particle=pixels;+ // Firelight in normals reaches the pixel after shadowing, exactly once.+ struct G {float x,y,z,nx,ny,nz;uint32_t colour;};+ const G glow[]={{-1.75f,2,.9f,.2f,0,0,0xff808080},{2.25f,2,.9f,.2f,0,0,0xff808080},+ {-1.75f,-2,.9f,.2f,0,0,0xff808080},{2.25f,2,.9f,.2f,0,0,0xff808080},+ {2.25f,-2,.9f,.2f,0,0,0xff808080},{-1.75f,-2,.9f,.2f,0,0,0xff808080}};+ device->Clear(0,nullptr,D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER,0,1,0);+ device->SetFVF(D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_DIFFUSE);+ device->SetRenderState(D3DRS_SPECULARENABLE,1);+ SunShadow::SetSmokeGlow(device,true);+ device->DrawPrimitiveUP(D3DPT_TRIANGLELIST,2,glow,sizeof(G)); read_back(device);+ const uint32_t lit=at(17,15);+ CHECK(std::abs(int((lit>>16)&255)-int((lit>>8)&255)-51)<=2);+ SunShadow::SetSmokeGlow(device,false);device->SetRenderState(D3DRS_SPECULARENABLE,0);+ { SunShadow::ReceiverExclusion excluded(device);draw(.9f,WHITE,.25f);CHECK_PIXEL(17,15,WHITE); }+ { SunShadow::SceneScope nested(device,true);+ CHECK(!SunShadow::FillSmoke(device,nullptr,0,0));draw(.9f,WHITE,.25f);CHECK_PIXEL(17,15,WHITE); }+ draw(.9f,WHITE,.25f);CHECK(pixels==particle);+ CHECK(SunShadow::FillSmoke(device,nullptr,0,0));draw(.9f,WHITE,.25f);CHECK_PIXEL(17,15,WHITE);+ CHECK(!gpu->Sun_Smoke_Texture());+ device->SetTransform(D3DTS_VIEW,&identity);device->SetTransform(D3DTS_PROJECTION,&identity);+ viewport={0,0,SIZE,SIZE,0,1};device->SetViewport(&viewport);+ device->SetRenderState(D3DRS_ZWRITEENABLE,1);+ // Cloaked casters use Windows' Bayer coverage; resetting the effect restores full coverage.+ for(float opacity : {0.0f,.5f,1.0f,2.0f}) {+ CHECK(SunShadow::Begin(device,32));+ const float parameters[]={0,0,0,opacity};+ SunShadow::SetCasterEffect(device,DRAW_EFFECT_CLOAK_SHADOW,parameters);+ ScreenVertex v[6];quad(v,0,0,32,32,.3f,WHITE);device->SetFVF(SCREEN_FVF);+ device->DrawPrimitiveUP(D3DPT_TRIANGLELIST,2,v,sizeof(ScreenVertex));+ CHECK(SunShadow::End(device));std::vector<float> depth;CHECK(device->Read_Sun_Shadow(depth));+ unsigned occupied=0;for(float z:depth) occupied+=z<1;+ CHECK(occupied==unsigned(std::min(opacity,1.0f)*.5f*1024));+ }+ CHECK(SunShadow::Begin(device,32));+ ScreenVertex v[6];quad(v,0,0,32,32,.3f,WHITE);device->SetFVF(SCREEN_FVF);+ device->DrawPrimitiveUP(D3DPT_TRIANGLELIST,2,v,sizeof(ScreenVertex));CHECK(SunShadow::End(device));+ std::vector<float> depth;CHECK(device->Read_Sun_Shadow(depth));for(float z:depth) CHECK(z<1);+ }+ if(had)setenv("ZH_SUN_SHADOW_MODE",saved.c_str(),1);else unsetenv("ZH_SUN_SHADOW_MODE");+ printf("smoke: moments/front, offset/depth-range reconstruction, queued refill, alpha particles, fire glow, exclusions, empty map and cloak coverage checked\n");+}++// The tree vertex program stores sway metadata in the normal slot. Verify its+// actual displaced alpha silhouette, then receive sunlight through that same program.+static void check_sun_trees(PosixDevice9 *device)+{+ const char *mode=getenv("ZH_SUN_SHADOW_MODE");+ const bool hadMode=mode!=nullptr;const std::string savedMode=mode?mode:"";+ setenv("ZH_SUN_SHADOW_MODE","mapped",1);+ {+ SunShadow::SceneScope scene(device,true);+ D3DMATRIX identity={};identity._11=identity._22=identity._33=identity._44=1;+ for(auto transform:{D3DTS_WORLD,D3DTS_VIEW,D3DTS_PROJECTION}) device->SetTransform(transform,&identity);+ begin(device,BLUE);+ device->SetRenderState(D3DRS_ZENABLE,1);device->SetRenderState(D3DRS_ZWRITEENABLE,1);+ device->SetRenderState(D3DRS_CULLMODE,D3DCULL_NONE);+ device->SetRenderState(D3DRS_ALPHABLENDENABLE,0);+ device->SetRenderState(D3DRS_ALPHATESTENABLE,1);+ device->SetRenderState(D3DRS_ALPHAFUNC,D3DCMP_GREATEREQUAL);+ device->SetRenderState(D3DRS_ALPHAREF,96);+ const uint32_t leaf[]={WHITE,0x00ffffff};+ IDirect3DTexture9 *texture=make_texture(device,2,1,D3DFMT_A8R8G8B8,leaf,sizeof(leaf));+ device->SetTexture(0,texture);+ device->SetSamplerState(0,D3DSAMP_MINFILTER,D3DTEXF_POINT);+ device->SetSamplerState(0,D3DSAMP_MAGFILTER,D3DTEXF_POINT);+ 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_MODULATE);+ device->SetTextureStageState(0,D3DTSS_ALPHAARG1,D3DTA_TEXTURE);+ device->SetTextureStageState(0,D3DTSS_ALPHAARG2,D3DTA_DIFFUSE);+ device->SetTextureStageState(1,D3DTSS_COLOROP,D3DTOP_DISABLE);+ const RenderUInt32 tokens[]={0xfffe0101u,0x0000ffffu};+ IDirect3DVertexShader9 *shader=nullptr;+ CHECK(device->CreateVertexShader(tokens,&shader)==D3D_OK);+ PosixDevice_Name_Shader(shader,"trees.vso");device->SetVertexShader(shader);+ device->SetFVF(D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_DIFFUSE|D3DFVF_TEX1);+ device->SetVertexShaderConstantF(4,&identity._11,4);+ const float sway[]={1,0,0,0};device->SetVertexShaderConstantF(9,sway,1);+ const float noSway[]={0,0,0,0};device->SetVertexShaderConstantF(8,noSway,1);+ struct TreeVertex {float x,y,z,type,shade,base;uint32_t color;float u,v;};+ TreeVertex leafQuad[]={+ {-.75f,.5f,.25f,1,1,0,WHITE,0,0},{.25f,.5f,.25f,1,1,0,WHITE,1,0},+ {-.75f,-.5f,.25f,1,1,0,WHITE,0,1},{.25f,.5f,.25f,1,1,0,WHITE,1,0},+ {.25f,-.5f,.25f,1,1,0,WHITE,1,1},{-.75f,-.5f,.25f,1,1,0,WHITE,0,1}};+ CHECK(SunShadow::Begin(device,32));+ device->DrawPrimitiveUP(D3DPT_TRIANGLELIST,2,leafQuad,sizeof(TreeVertex));+ CHECK(SunShadow::End(device));+ std::vector<float> depth;CHECK(device->Read_Sun_Shadow(depth));+ if(depth.size()==32*32) {+ CHECK(depth[16*32+6]==1); // unswayed location is now clear+ CHECK(depth[16*32+12]>.249f && depth[16*32+12]<.251f);+ CHECK(depth[16*32+20]==1); // transparent half of the displaced leaf+ }+ CHECK(SunShadow::Parameters(device,0,.5f,0,0,0,1,0));+ device->SetTexture(0,nullptr);+ device->SetTextureStageState(0,D3DTSS_COLOROP,D3DTOP_SELECTARG2);+ device->SetTextureStageState(0,D3DTSS_ALPHAOP,D3DTOP_SELECTARG2);+ for(auto &v:leafQuad) {v.x=(v.x+.75f)*2-1;v.y*=2;v.z=.75f;v.type=0;}+ device->Clear(0,nullptr,D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER,BLUE,1,0);+ device->DrawPrimitiveUP(D3DPT_TRIANGLELIST,2,leafQuad,sizeof(TreeVertex));read_back(device);+ CHECK_PIXEL(12,16,0xff808080);CHECK_PIXEL(20,16,WHITE);+ device->SetVertexShader(nullptr);shader->Release();texture->Release();+ device->SetRenderState(D3DRS_ALPHATESTENABLE,0);+ device->SetRenderState(D3DRS_CULLMODE,D3DCULL_CCW);+ }+ if(hadMode) setenv("ZH_SUN_SHADOW_MODE",savedMode.c_str(),1);else unsetenv("ZH_SUN_SHADOW_MODE");+ printf("sun trees: displaced alpha silhouette, transparent gaps and receiving checked\n");+}++static void check_sun_reset(PosixDevice9 *device)+{+ const char *oldMode=getenv("ZH_SUN_SHADOW_MODE");+ const std::string savedMode=oldMode ? oldMode : "";+ const bool hadMode=oldMode!=NULL;+ setenv("ZH_SUN_SHADOW_MODE","mapped",1);+ begin(device,BLUE);+ CHECK(SunShadow::Begin(device,32)); CHECK(SunShadow::End(device));+ CHECK(SunShadow::Parameters(device,0,.5f,0,0,0,1,0));+ CHECK(SunShadow::OwnsSceneShadows(device));+ // Keep work queued against the old scene allocation while Reset drains it.+ ScreenVertex vertices[6]; quad(vertices,0,0,32,32,.5f,RED);+ CHECK(device->DrawPrimitiveUP(D3DPT_TRIANGLELIST,2,vertices,sizeof(vertices[0]))==D3D_OK);+ D3DPRESENT_PARAMETERS original=device->Get_Present_Parameters(), resized=original;+ resized.BackBufferWidth=48; resized.BackBufferHeight=40;+ CHECK(device->Reset(&resized)==D3D_OK);+ std::vector<float> depth;+ CHECK(!device->Read_Sun_Shadow(depth)); CHECK(!SunShadow::OwnsSceneShadows(device));+ CHECK(!SunShadow::Parameters(device,0,.5f,0,0,0,1,0));+ D3DVIEWPORT9 viewport; device->GetViewport(&viewport);+ CHECK(viewport.Width==48 && viewport.Height==40);+ begin(device,GREEN);+ CHECK(SunShadow::Begin(device,64)); CHECK(SunShadow::End(device));+ CHECK(SunShadow::Parameters(device,0,.5f,0,0,0,1,0));+ CHECK(SunShadow::OwnsSceneShadows(device));+ CHECK(device->Read_Sun_Shadow(depth)); CHECK(depth.size()==64*64);+ for(float value:depth) CHECK(value==1.0f);+ std::vector<uint8_t> resizedPixels;+ CHECK(device->Get_Gpu()->Read_Back(device->Get_Gpu()->Back_Buffer(),48,40,resizedPixels));+ for(size_t i=0;i<resizedPixels.size();i+=4)+ CHECK(resizedPixels[i]==0 && resizedPixels[i+1]==255 && resizedPixels[i+2]==0 && resizedPixels[i+3]==255);+ CHECK(device->Reset(&original)==D3D_OK);+ CHECK(!SunShadow::OwnsSceneShadows(device));+ if(hadMode) setenv("ZH_SUN_SHADOW_MODE",savedMode.c_str(),1); else unsetenv("ZH_SUN_SHADOW_MODE");+ printf("sun reset: pending work drained, stale capture invalidated, resized capture and scene verified\n");+}++static PosixDevice9 *sun_fault_device(IDirect3D9 *adapter)+{+ D3DPRESENT_PARAMETERS parameters={};+ parameters.BackBufferWidth=parameters.BackBufferHeight=SIZE;+ parameters.BackBufferFormat=D3DFMT_X8R8G8B8;+ parameters.Windowed=parameters.EnableAutoDepthStencil=1;+ parameters.AutoDepthStencilFormat=D3DFMT_D24S8;+ IDirect3DDevice9 *created=NULL;+ CHECK(adapter->CreateDevice(0,D3DDEVTYPE_HAL,NULL,0,¶meters,&created)==D3D_OK);+ if(!created) return NULL;+ PosixDevice9 *device=static_cast<PosixDevice9*>(created);+ if(device->Create_Gpu_Frame(true)!=D3D_OK) { CHECK(false);device->Release();return NULL; }+ begin(device,BLUE);+ D3DMATRIX identity={};identity._11=identity._22=identity._33=identity._44=1;+ device->SetTransform(D3DTS_WORLD,&identity);device->SetTransform(D3DTS_VIEW,&identity);+ device->SetTransform(D3DTS_PROJECTION,&identity);+ device->SetFVF(D3DFVF_XYZ|D3DFVF_DIFFUSE);+ device->SetRenderState(D3DRS_ZENABLE,1);device->SetRenderState(D3DRS_ZWRITEENABLE,1);+ device->SetRenderState(D3DRS_ZFUNC,D3DCMP_LESSEQUAL);+ device->SetRenderState(D3DRS_CULLMODE,D3DCULL_NONE);+ device->SetRenderState(D3DRS_ALPHATESTENABLE,0);device->SetRenderState(D3DRS_ALPHABLENDENABLE,0);+ return device;+}++static void check_sun_failures(IDirect3D9 *adapter)+{+ const char *oldMode=getenv("ZH_SUN_SHADOW_MODE"),*oldFault=getenv("ZH_TEST_SUN_SHADOW_FAILURE");+ const std::string savedMode=oldMode ? oldMode : "",savedFault=oldFault ? oldFault : "";+ const bool hadMode=oldMode!=NULL,hadFault=oldFault!=NULL;+ setenv("ZH_SUN_SHADOW_MODE","mapped",1);unsetenv("ZH_TEST_SUN_SHADOW_FAILURE");+ struct V {float x,y,z;uint32_t color;};+ const V caster[]={{-1,1,.25f,WHITE},{1,1,.25f,WHITE},{-1,-1,.25f,WHITE},+ {1,1,.25f,WHITE},{1,-1,.25f,WHITE},{-1,-1,.25f,WHITE}};+ const V left[]={{-1,1,.75f,WHITE},{0,1,.75f,WHITE},{-1,-1,.75f,WHITE},+ {0,1,.75f,WHITE},{0,-1,.75f,WHITE},{-1,-1,.75f,WHITE}};+ const V right[]={{0,1,.75f,WHITE},{1,1,.75f,WHITE},{0,-1,.75f,WHITE},+ {1,1,.75f,WHITE},{1,-1,.75f,WHITE},{0,-1,.75f,WHITE}};+ const auto parameters=[](PosixDevice9 *device){return SunShadow::Parameters(device,0,.5f,0,0,0,1,0);};+ for(const char *fault : {"smoke-target","smoke-pipeline"}) {+ PosixDevice9 *smokeDevice=sun_fault_device(adapter);if(!smokeDevice) continue;+ { SunShadow::SceneScope scene(smokeDevice,true);+ CHECK(SunShadow::Begin(smokeDevice,32));+ CHECK(smokeDevice->DrawPrimitiveUP(D3DPT_TRIANGLELIST,2,caster,sizeof(V))==D3D_OK);+ CHECK(SunShadow::End(smokeDevice));+ const float cloud[]={0,0,.5f,.5f,2};+ setenv("ZH_TEST_SUN_SHADOW_FAILURE",fault,1);+ CHECK(!SunShadow::FillSmoke(smokeDevice,cloud,1,.6f));+ CHECK(!smokeDevice->Get_Gpu()->Sun_Smoke_Texture());+ CHECK(parameters(smokeDevice));CHECK(SunShadow::OwnsSceneShadows(smokeDevice));+ smokeDevice->DrawPrimitiveUP(D3DPT_TRIANGLELIST,2,left,sizeof(V));+ read_back(smokeDevice);CHECK_PIXEL(8,16,0xFF808080); // core depth map still works+ unsetenv("ZH_TEST_SUN_SHADOW_FAILURE");+ CHECK(!SunShadow::FillSmoke(smokeDevice,cloud,1,.6f)); // bounded refusal, no per-frame retry spam+ CHECK(!SunShadow::FillSmoke(smokeDevice,nullptr,0,0));+ }+ smokeDevice->Release();+ printf("smoke fault %s: particle fallback signalled, core shadows retained, refusal latched\n",fault);+ }+ for(const char *fault: {"receiver-program","receiver-pipeline"}) for(bool late: {false,true}) {+ PosixDevice9 *device=sun_fault_device(adapter);if(!device) continue;+ {+ SunShadow::SceneScope scene(device,true);+ CHECK(SunShadow::Begin(device,32));+ CHECK(device->DrawPrimitiveUP(D3DPT_TRIANGLELIST,2,caster,sizeof(V))==D3D_OK);+ CHECK(SunShadow::End(device));CHECK(parameters(device));+ if(late) {+ CHECK(device->DrawPrimitiveUP(D3DPT_TRIANGLELIST,2,left,sizeof(V))==D3D_OK);+ read_back(device);CHECK_PIXEL(8,16,0xFF808080);CHECK_PIXEL(24,16,BLUE);+ // A new shader/pipeline key after an actual submission, so the fault+ // cannot be repaired just by discarding the current CPU draw batch.+ device->SetRenderState(D3DRS_ALPHATESTENABLE,1);+ device->SetRenderState(D3DRS_ALPHAFUNC,D3DCMP_GREATER);+ device->SetRenderState(D3DRS_ALPHAREF,8);+ CHECK(parameters(device)); // changing parameters cannot forget earlier draws+ }+ setenv("ZH_TEST_SUN_SHADOW_FAILURE",fault,1);+ const unsigned recorded=device->Draws_Recorded();+ CHECK(device->DrawPrimitiveUP(D3DPT_TRIANGLELIST,2,right,sizeof(V))==D3D_OK);+ CHECK(device->Draws_Recorded()==recorded+1);CHECK(device->Draw_Refusals().empty());+ read_back(device);CHECK_PIXEL(24,16,WHITE);+ CHECK_PIXEL(8,16,late ? 0xFF808080 : BLUE);+ CHECK(!SunShadow::ReceivesView(device));CHECK(SunShadow::OwnsSceneShadows(device)==late);+ CHECK(!parameters(device));CHECK(SunShadow::OwnsSceneShadows(device)==late);+ unsetenv("ZH_TEST_SUN_SHADOW_FAILURE");+ // The failure latch, not the injection environment, now selects ordinary draws.+ CHECK(device->DrawPrimitiveUP(D3DPT_TRIANGLELIST,2,left,sizeof(V))==D3D_OK);+ read_back(device);CHECK_PIXEL(8,16,WHITE);CHECK_PIXEL(24,16,WHITE);+ }+ CHECK(!SunShadow::OwnsSceneShadows(device));+ {+ SunShadow::SceneScope next(device,true);+ CHECK(!SunShadow::Begin(device,32));CHECK(!parameters(device));+ CHECK(!SunShadow::OwnsSceneShadows(device));+ device->Clear(0,NULL,D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER,BLUE,1,0);+ CHECK(device->DrawPrimitiveUP(D3DPT_TRIANGLELIST,2,right,sizeof(V))==D3D_OK);+ read_back(device);CHECK_PIXEL(24,16,WHITE);+ }+ D3DPRESENT_PARAMETERS reset=device->Get_Present_Parameters();CHECK(device->Reset(&reset)==D3D_OK);+ CHECK(!SunShadow::Begin(device,32)); // Reset retains the refused program/pipeline cache+ setenv("ZH_SUN_SHADOW_MODE","capture-only",1);+ CHECK(SunShadow::Begin(device,32));CHECK(SunShadow::End(device));CHECK(!parameters(device));+ setenv("ZH_SUN_SHADOW_MODE","mapped",1);+ CHECK(!SunShadow::Begin(device,32));+ device->Release(); // the next case recreates the device and can receive again+ printf("sun fault %s %s: geometry retained, submitted pixels preserved, ownership and next-scene latch checked\n",+ fault,late ? "after submission" : "before receivers");+ }+ PosixDevice9 *device=sun_fault_device(adapter);+ if(device) {+ {+ SunShadow::SceneScope scene(device,true);+ setenv("ZH_TEST_SUN_SHADOW_FAILURE","target",1);+ CHECK(!SunShadow::Begin(device,32));CHECK(!parameters(device));+ CHECK(!SunShadow::OwnsSceneShadows(device));+ CHECK(device->DrawPrimitiveUP(D3DPT_TRIANGLELIST,2,right,sizeof(V))==D3D_OK);+ read_back(device);CHECK_PIXEL(24,16,WHITE);+ unsetenv("ZH_TEST_SUN_SHADOW_FAILURE");+ CHECK(SunShadow::Begin(device,32));+ CHECK(device->DrawPrimitiveUP(D3DPT_TRIANGLELIST,2,caster,sizeof(V))==D3D_OK);+ CHECK(SunShadow::End(device));CHECK(parameters(device));+ CHECK(device->DrawPrimitiveUP(D3DPT_TRIANGLELIST,2,left,sizeof(V))==D3D_OK);+ setenv("ZH_TEST_SUN_SHADOW_FAILURE","target",1);+ CHECK(!SunShadow::Begin(device,64));CHECK(!parameters(device));+ CHECK(!SunShadow::OwnsSceneShadows(device));+ read_back(device);CHECK_PIXEL(8,16,0xFF808080);CHECK_PIXEL(24,16,WHITE);+ unsetenv("ZH_TEST_SUN_SHADOW_FAILURE");+ CHECK(SunShadow::Begin(device,64));CHECK(SunShadow::End(device));CHECK(parameters(device));+ std::vector<float> depth;CHECK(device->Read_Sun_Shadow(depth));CHECK(depth.size()==64*64);+ for(float value:depth) CHECK(value==1.0f);+ CHECK(device->DrawPrimitiveUP(D3DPT_TRIANGLELIST,2,left,sizeof(V))==D3D_OK);+ read_back(device);CHECK_PIXEL(8,16,WHITE);CHECK_PIXEL(24,16,WHITE);+ }+ device->Release();+ printf("sun allocation fault: first allocation and replacement refused, queued old reader retained, recovery and empty clear checked\n");+ }+ if(hadMode) setenv("ZH_SUN_SHADOW_MODE",savedMode.c_str(),1);else unsetenv("ZH_SUN_SHADOW_MODE");+ if(hadFault) setenv("ZH_TEST_SUN_SHADOW_FAILURE",savedFault.c_str(),1);else unsetenv("ZH_TEST_SUN_SHADOW_FAILURE");+}++#endif+static void check_refusal(PosixDevice9 *device){IDirect3DCubeTexture9 *cube = NULL;@@ -740,6 +1419,9 @@ int main()device->SetFVF(SCREEN_FVF);CHECK(device->DrawPrimitiveUP(D3DPT_TRIANGLELIST, 2, v, sizeof(ScreenVertex)) == D3D_OK);CHECK(device->Draws_Recorded() == 0);+ CHECK(!SunShadow::Begin(device,32));+ CHECK(!SunShadow::Parameters(device,0,.5f,0,0,0,1,0));+ CHECK(!SunShadow::OwnsSceneShadows(device));if (!SDL_Init(SDL_INIT_VIDEO) || device->Create_Gpu_Frame(true) != D3D_OK) {printf("posix_gpu_draw_selfcheck: SKIP - no GPU device here: %s\n", SDL_GetError());@@ -754,8 +1436,18 @@ int main()check_min_vertex(device);check_clears_and_depth(device);check_render_targets(device);+#if defined(__linux__)+ check_sun_capture(device);+ check_sun_receivers(device);+ check_sun_smoke(device);+ check_sun_trees(device);+ check_sun_reset(device);+#endifcheck_refusal(device);check_quad_derivatives(device);+#if defined(__linux__)+ check_sun_failures(d3d);+#endifprintf("posix_gpu_draw_selfcheck: %s: %u draws recorded, %u textures and %u buffers uploaded, %u stale flushes\n",SDL_GetGPUDeviceDriver(device->Get_Gpu()->Device()), device->Draws_Recorded(),diff --git a/GeneralsMD/Code/Tests/test_sdl_gpu_frame.cpp b/GeneralsMD/Code/Tests/test_sdl_gpu_frame.cppindex a0c05ccbc..be2dd98a9 100644--- a/GeneralsMD/Code/Tests/test_sdl_gpu_frame.cpp+++ b/GeneralsMD/Code/Tests/test_sdl_gpu_frame.cpp@@ -30,11 +30,14 @@// - Any GPU but this one. Exits 77, and ctest reports it skipped, where SDL has no GPU device.#include "SdlGpuFrame.h"+#include "SdlPipelineCache.h"+#include "../Libraries/Source/WWVegas/WW3D2/sdl3shadercompile.h"#include <SDL3/SDL.h>#include <stdio.h>#include <stdlib.h>+#include <cstring>static int failures = 0;@@ -79,6 +82,187 @@ static unsigned int mismatches(const std::vector<uint8_t> &got, const uint16_t (return bad;}+#if defined(__linux__)+class DepthObject+{+public:+ SDL_GPUShader *Vertex = NULL, *Pixel = NULL;+ SDL_GPUGraphicsPipeline *Pipeline = NULL;+ SdlPipelineCache *Cache = NULL;+ SdlGpuFrame *Frame;+ explicit DepthObject(SdlGpuFrame *frame, bool sun = false) : Frame(frame)+ {+ const char *vertex =+ "cbuffer Object : register(b0, space1) { float4 Depth; };\n"+ "float4 main(uint id : SV_VertexID) : SV_Position {\n"+ "float2 p = id == 0 ? float2(-0.75,-0.75) : (id == 1 ? float2(0.75,-0.75) : float2(0,0.75));\n"+ "return float4(p,Depth.x,1); }\n";+ const char *pixel = sun ? "void main() {}\n" : "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();+ if (sun) {+ // Exercise the production cache with no colour attachment and a distinct+ // depth format, not just a hand-built SDL pipeline.+ RenderUInt32 states[256] = {};+ states[D3DRS_FILLMODE] = D3DFILL_SOLID;+ states[D3DRS_CULLMODE] = D3DCULL_NONE;+ states[D3DRS_ZENABLE] = states[D3DRS_ZWRITEENABLE] = 1;+ states[D3DRS_ZFUNC] = D3DCMP_LESS;+ SdlPipelineKey key;+ CHECK(Sdl_Pipeline_Key(states, D3DPT_TRIANGLELIST, Vertex, Pixel, D3DFVF_XYZ,+ 0, SDL_GPU_TEXTUREFORMAT_D32_FLOAT, key, error));+ Cache = new SdlPipelineCache(frame->Device());+ Pipeline = Cache->Pipeline(key);+ } else Pipeline = SDL_CreateGPUGraphicsPipeline(frame->Device(), &info);+ CHECK(Pipeline != NULL);+ }+ ~DepthObject()+ {+ Frame->Flush();+ if (Cache) delete Cache;+ else 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(36, draw.VertexOffset), 0, 36);+ 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 void check_sun_depth_target(SdlGpuFrame *frame)+{+ SdlTarget sun;+ std::string error;+ CHECK(frame->Sun_Shadow_Target(32, sun, error));+ CHECK(sun.Colour == NULL && sun.Depth != NULL && sun.Width == 32 && sun.Height == 32);+ CHECK(frame->Target_Depth_Format(sun) == SDL_GPU_TEXTUREFORMAT_D32_FLOAT);+ if (!sun.Depth) return;+ DepthObject caster(frame, true);+ frame->Set_Target(frame->Back_Buffer_Target());+ frame->Clear_Back_Buffer(true, true, true, 0xff123456, 0.8f, 0);+ frame->Set_Target(sun);+ frame->Clear_Back_Buffer(false, true, false, 0, 1.0f, 0);+ caster.Draw(sun, 0.25f);+ frame->Set_Target(frame->Back_Buffer_Target());+ std::vector<uint8_t> pixels;+ CHECK(frame->Read_Back(frame->Back_Buffer_Target().Colour, WIDTH, HEIGHT, pixels));+ CHECK(pixels.size() == WIDTH * HEIGHT * 4);+ for (size_t i = 0; i + 3 < pixels.size(); i += 4)+ CHECK(pixels[i] == 0x56 && pixels[i+1] == 0x34 && pixels[i+2] == 0x12 && pixels[i+3] == 255);++ const char *vs = "float4 main(uint id:SV_VertexID):SV_Position { return float4(id==1?3:-1,id==2?3:-1,0,1); }";+ const char *ps =+ "Texture2D<float> depthMap:register(t0,space2); SamplerState pointSampler:register(s0,space2);"+ "cbuffer Size:register(b0,space3) { float4 size; };"+ "float4 main(float4 p:SV_Position):SV_Target0 { float d=depthMap.SampleLevel(pointSampler,p.xy/size.xy,0); return float4(d,d,d,1); }";+ std::vector<unsigned char> spirv;+ CHECK(SDL3_Compile_HLSL_To_SPIRV(vs, true, spirv, error));+ SDL_GPUShader *vertex = SDL3_Create_Shader(frame->Device(), spirv, true, error);+ CHECK(SDL3_Compile_HLSL_To_SPIRV(ps, false, spirv, error));+ SDL_GPUShader *pixel = SDL3_Create_Shader(frame->Device(), spirv, false, error);+ 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.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 = SDL_CreateGPUGraphicsPipeline(frame->Device(), &info);+ SDL_GPUSamplerCreateInfo samplerInfo = {};+ samplerInfo.address_mode_u = samplerInfo.address_mode_v = samplerInfo.address_mode_w = SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;+ SDL_GPUSampler *sampler = SDL_CreateGPUSampler(frame->Device(), &samplerInfo);+ CHECK(vertex && pixel && pipeline && sampler);+ if (pipeline && sampler) {+ auto sample = [&](SDL_GPUTexture *texture) {+ const SdlTarget scene = frame->Back_Buffer_Target();+ frame->Set_Target(scene);+ SdlRecordedDraw draw = {};+ draw.Pipeline = pipeline; draw.Count = 3;+ memset(frame->Stage(16, draw.VertexOffset), 0, 16);+ const float size[4] = { (float)scene.Width, (float)scene.Height, 0, 0 };+ draw.PixelConstants = frame->Constants(1, size, sizeof(size)); draw.PixelConstantsSize = sizeof(size);+ draw.SamplerCount = 1; draw.Textures[0] = texture; draw.Samplers[0] = sampler;+ draw.Viewport[2] = draw.Scissor[2] = scene.Width;+ draw.Viewport[3] = draw.Scissor[3] = scene.Height; draw.Viewport[5] = 1;+ frame->Record_Draw(draw);+ };+ auto verify = [&](float expected) {+ const SdlTarget scene = frame->Back_Buffer_Target();+ CHECK(frame->Read_Back(scene.Colour, scene.Width, scene.Height, pixels));+ if (pixels.size() != scene.Width * scene.Height * 4) { CHECK(false); return; }+ CHECK(abs((int)pixels[((scene.Height/2)*scene.Width+scene.Width/2)*4] - (int)(expected*255+0.5f)) <= 1);+ CHECK(pixels[0] == 255); // clear depth outside the triangle+ };+ sample(sun.Depth);+ SdlTarget replacement;+ CHECK(frame->Sun_Shadow_Target(64, replacement, error));+ CHECK(replacement.Depth != sun.Depth);+ verify(0.25f); // queued sampling still owns the retired 32x32 resource+ frame->Set_Target(replacement);+ frame->Clear_Back_Buffer(false, true, false, 0, 1, 0);+ caster.Draw(replacement, 0.6f);+ sample(replacement.Depth);+ SdlTarget refused;+ CHECK(!frame->Sun_Shadow_Target(0, refused, error) && refused.Depth == NULL);+ CHECK(!frame->Sun_Shadow_Target(8193, refused, error) && refused.Depth == NULL);+ verify(0.6f);+ CHECK(frame->Resize(WIDTH+16, HEIGHT+8));+ SdlTarget kept;+ CHECK(frame->Sun_Shadow_Target(64, kept, error) && kept.Depth == replacement.Depth);+ sample(kept.Depth); verify(0.6f); // window resizing does not invalidate the sun allocation+ frame->Set_Target(kept);+ frame->Clear_Back_Buffer(false, true, false, 0, 1, 0);+ sample(kept.Depth); verify(1.0f); // empty capture clears stale caster depth+ CHECK(frame->Resize(WIDTH, HEIGHT));+ }+ frame->Set_Target(frame->Back_Buffer_Target());+ CHECK(frame->Flush());+ if (pipeline) SDL_ReleaseGPUGraphicsPipeline(frame->Device(), pipeline);+ if (sampler) SDL_ReleaseGPUSampler(frame->Device(), sampler);+ if (vertex) SDL_ReleaseGPUShader(frame->Device(), vertex);+ if (pixel) SDL_ReleaseGPUShader(frame->Device(), pixel);+ printf("sun depth target: depth-only draw/sample, scene preservation, empty clear, retirement and resize checked\n");+}++#endif // __linux__+int main(){if (!SDL_Init(SDL_INIT_VIDEO)) {@@ -93,6 +277,9 @@ int main()return 77;}printf("sdl_gpu_frame_selfcheck: %s\n", SDL_GetGPUDeviceDriver(frame->Device()));+#if defined(__linux__)+ check_sun_depth_target(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);diff --git a/GeneralsMD/Code/Tests/test_shader_sdl.cpp b/GeneralsMD/Code/Tests/test_shader_sdl.cppindex 53f89e737..3ce715b43 100644--- a/GeneralsMD/Code/Tests/test_shader_sdl.cpp+++ b/GeneralsMD/Code/Tests/test_shader_sdl.cpp@@ -195,6 +195,50 @@ bool vertex_layout(const std::string & hlsl, std::vector<SDL_GPUVertexAttribute>return !attributes.empty();}+TEST(sdl_cloak_caster_fits_the_eight_slot_draw_contract)+{+ for (unsigned textured = 0; textured < 2; ++textured) {+ CombinerDescription description = {};+ description.StageCount = 1;+ description.Stages[0].ColourOperation = FF_TOP_SELECTARG1;+ description.Stages[0].AlphaOperation = FF_TOP_SELECTARG1;+ description.Stages[0].ColourArgument1 = textured ? FF_TA_TEXTURE : FF_TA_DIFFUSE;+ description.Stages[0].AlphaArgument1 = description.Stages[0].ColourArgument1;+ description.Stages[0].TextureBound = textured != 0;+ description.DrawEffect = DRAW_EFFECT_CLOAK_SHADOW;+ std::string generated;+ CHECK(CombinerShader_Generate(description, COMBINER_SHADER_TARGET_SDL3_GPU, generated));+ // The cosmetic cloak's scene texture is outside SDL's eight-slot layout.+ // Ordered caster coverage must not inherit that unused declaration.+ CHECK(generated.find("SceneColour") == std::string::npos);+ CHECK(generated.find("effect_cloak_shadow") != std::string::npos);+ for (unsigned depth_only = 0; depth_only < 2; ++depth_only) {+ std::string hlsl = generated;+ if (depth_only) {+ // Compile the same depth-only entry point used by Sun_Pixel_Program.+ const std::string entry = "float4 main(Input input) : SV_Target";+ const size_t at = hlsl.find(entry);+ CHECK(at != std::string::npos);+ if (at == std::string::npos) continue;+ hlsl.replace(at, entry.size(), "float4 sunCasterPixel(Input input)");+ hlsl += "\nvoid main(Input input) { sunCasterPixel(input); }\n";+ }+ std::vector<unsigned char> spirv;+ std::string log;+ const bool compiled = SDL3_Compile_HLSL_To_SPIRV(hlsl, false, spirv, log);+ CHECK(compiled);+ if (!compiled) {+ printf(" cloak caster: %s\n", log.c_str());+ continue;+ }+ unsigned samplers = 0, uniforms = 0;+ SDL3_Shader_Slots(spirv, false, samplers, uniforms);+ CHECK(samplers <= 8);+ CHECK_EQ(uniforms, 1u);+ }+ }+}+TEST(every_generated_program_reaches_sdl3_gpu){const char * spirv_val = getenv("ZH_SPIRV_VAL");diff --git a/GeneralsMD/Code/Tests/test_sun_shadow_sorting.cpp b/GeneralsMD/Code/Tests/test_sun_shadow_sorting.cppnew file mode 100644index 000000000..22b431933--- /dev/null+++ b/GeneralsMD/Code/Tests/test_sun_shadow_sorting.cpp@@ -0,0 +1,142 @@+// Exercise WW3D's real sorting pool, including merging adjacent nodes with equal+// material state. Direct device draws cannot catch coverage lost while queued.+#include "PreRTS.h"+#include "Common/GameMemory.h"+#include "Platform/SunShadow.h"+#include "PosixDevice9.h"+#include "dx8wrapper.h"+#include "dx8vertexbuffer.h"+#include "dx8indexbuffer.h"+#include "dx8fvf.h"+#include "sortingrenderer.h"+#include "shader.h"+#include "vertmaterial.h"+#include "ffshader.h"+#include "ww3d.h"+#include "wwmath.h"+#include <SDL3/SDL.h>+#include <cstdio>+#include <cstdlib>+#include <vector>++const Char *g_strFile = "data\\Generals.str";+const Char *g_csfFile = "data\\%s\\Generals.csf";+static char appPrefix[] = "";+char *gAppPrefix = appPrefix;+RenderWindow ApplicationHWnd = NULL;+Bool ApplicationIsBorderless = FALSE;++static int failures = 0;+#define CHECK(condition) do { if (!(condition)) { ++failures; \+ std::printf("FAIL line %d: %s\n", __LINE__, #condition); } } while (0)++static void check_sorted_coverage(PosixDevice9 *device, bool reverse)+{+ CHECK(SunShadow::Begin(device, 64));+ DX8Wrapper::Set_Transform(D3DTS_WORLD, Matrix3D(1));+ DX8Wrapper::Set_Transform(D3DTS_VIEW, Matrix3D(1));+ DX8Wrapper::Set_Projection_Transform_With_Z_Bias(Matrix4x4(true), 0, 1);+ ShaderClass shader;+ shader.Set_Texturing(ShaderClass::TEXTURING_DISABLE);+ shader.Set_Cull_Mode(ShaderClass::CULL_MODE_DISABLE);+ shader.Set_Src_Blend_Func(ShaderClass::SRCBLEND_SRC_ALPHA);+ shader.Set_Dst_Blend_Func(ShaderClass::DSTBLEND_ONE_MINUS_SRC_ALPHA);+ DX8Wrapper::Set_Shader(shader);+ VertexMaterialClass *material = VertexMaterialClass::Get_Preset(VertexMaterialClass::PRELIT_DIFFUSE);+ DX8Wrapper::Set_Material(material);+ material->Release_Ref();+ DX8Wrapper::Set_DX8_Render_State(D3DRS_LIGHTING, FALSE);+ DX8Wrapper::Set_DX8_Render_State(D3DRS_ZENABLE, TRUE);+ DX8Wrapper::Set_DX8_Render_State(D3DRS_FILLMODE, D3DFILL_SOLID);+ DX8Wrapper::Set_DX8_Render_State(D3DRS_STENCILENABLE, FALSE);++ SortingVertexBufferClass *vb = new SortingVertexBufferClass(24);+ SortingIndexBufferClass *ib = new SortingIndexBufferClass(24);+ {+ VertexBufferClass::WriteLockClass lock(vb);+ auto *vertices = static_cast<VertexFormatXYZNDUV2 *>(lock.Get_Vertex_Array());+ const unsigned corners[] = {0, 1, 2, 2, 1, 3};+ for (unsigned strip = 0; strip < 4; ++strip) {+ const float left = -1.0f + strip * .5f, right = left + .5f;+ const float x[] = {left, right, left, right};+ const float y[] = {-1, -1, 1, 1};+ for (unsigned v = 0; v < 6; ++v) {+ vertices[strip * 6 + v] = {};+ auto &vertex = vertices[strip * 6 + v];+ vertex.x = x[corners[v]]; vertex.y = y[corners[v]];+ vertex.z = .5f; vertex.nz = 1; vertex.diffuse = 0xffffffff;+ }+ }+ }+ {+ IndexBufferClass::WriteLockClass lock(ib);+ for (unsigned i = 0; i < 24; ++i) lock.Get_Index_Array()[i] = i;+ }+ DX8Wrapper::Set_Vertex_Buffer(vb);+ DX8Wrapper::Set_Index_Buffer(ib, 0);+ // Equal spheres force the same sorting pool; all other draw state is identical.+ // These nodes must not merge across different cloak opacities or into opaque.+ const float opacity[] = {0, .5f, 1, 1};+ const float cleared[4] = {};+ for (unsigned entry = 0; entry < 4; ++entry) {+ const unsigned strip = reverse ? 3 - entry : entry;+ const float parameters[] = {0, 0, 0, opacity[strip]};+ SunShadow::SetCasterEffect(device, strip == 3 ? DRAW_EFFECT_NONE : DRAW_EFFECT_CLOAK_SHADOW, parameters);+ SortingRendererClass::Insert_Triangles(SphereClass(Vector3(0, 0, .5f), 10), strip * 6, 2, strip * 6, 6);+ SunShadow::SetCasterEffect(device, DRAW_EFFECT_NONE, cleared);+ }+ SortingRendererClass::Flush();+ CHECK(SunShadow::GetCasterEffect(device).Effect == DRAW_EFFECT_NONE);+ vb->Release_Ref(); ib->Release_Ref();+ DX8Wrapper::Flush_Deferred_D3D9_State();+ CHECK(SunShadow::End(device));+ std::vector<float> depth;+ CHECK(device->Read_Sun_Shadow(depth));+ if (depth.size() == 64 * 64) {+ // Interior 8x32 rectangles contain complete Bayer tiles, away from edges.+ // Cloak contributes half the opacity: 0%, 25%, 50%; ordinary mesh is 100%.+ const unsigned expected[] = {0, 64, 128, 256};+ for (unsigned strip = 0; strip < 4; ++strip) {+ unsigned occupied = 0;+ for (unsigned y = 16; y < 48; ++y)+ for (unsigned x = strip * 16 + 4; x < strip * 16 + 12; ++x)+ occupied += depth[y * 64 + x] < 1;+ std::printf("sorted coverage%s, strip %u: %u / 256\n", reverse ? " reversed" : "", strip, occupied);+ CHECK(occupied == expected[strip]);+ }+ } else CHECK(false);+ DX8Wrapper::Invalidate_Cached_Render_States();+}++int main()+{+ setenv("ZH_SUN_SHADOW_MODE", "mapped", 1);+ if (!SDL_Init(SDL_INIT_VIDEO)) return 77;+ SDL_SetHint("ZH_OFFSCREEN_FRAMES", "1");+ SDL_SetHint("ZH_OFFSCREEN_HZ", "0");+ initMemoryManager();+ WWMath::Init();+ const bool initialized = DX8Wrapper::Init(NULL);+ if (!initialized || WW3D::Set_Render_Device(0, 64, 64, 32, 1, false, false, false) != WW3D_ERROR_OK) {+ std::printf("SKIP: could not create offscreen renderer: %s\n", SDL_GetError());+ if (initialized) DX8Wrapper::Shutdown();+ WWMath::Shutdown();+ SDL_Quit();+ return 77;+ }+ auto *device = static_cast<PosixDevice9 *>(DX8Wrapper::_Get_D3D_Device());+ if (!device || !device->Get_Gpu()) {+ DX8Wrapper::Shutdown();+ WWMath::Shutdown();+ SDL_Quit();+ return 77;+ }+ WW3D::Enable_Sorting(true);+ check_sorted_coverage(device, false);+ check_sorted_coverage(device, true); // Reuses recycled nodes and reverses the final effect.+ SortingRendererClass::Deinit();+ DX8Wrapper::Shutdown();+ WWMath::Shutdown();+ SDL_Quit();+ return failures ? 1 : 0;+}diff --git a/GeneralsMD/Code/Tools/sun-shadow-check.py b/GeneralsMD/Code/Tools/sun-shadow-check.pynew file mode 100644index 000000000..6f52eedda--- /dev/null+++ b/GeneralsMD/Code/Tools/sun-shadow-check.py@@ -0,0 +1,236 @@+#!/usr/bin/env python3+"""Repeat a sun-shadow scene with isolated settings and an inspectable manifest.++Uses an existing executable, overlay and prepared file-link root. Installs nothing.+Never run concurrent GPU workloads when comparing the recorded timings. The original+timing probe includes loading; its aggregate is diagnostic, not steady-state FPS.+"""+import argparse+import hashlib+import json+import os+from pathlib import Path+import shutil+import subprocess+import time++CASES = {+ "solid": ("Flash Effect", 1200, 945, 800, None),+ "smoke": ("Flash Effect", 1700, 1580, 600, "rf_smoke"),+ "cloak": ("Flash Effect", 1700, 1580, 300, "sun_cloak"),+ "trees": ("Flash Effect", 1700, 1580, 300, "sun_trees"),+ "forest": ("ForgottenForestZH", 1620, 1470, 1200, None),+ "bridge": ("Golden Oasis", 1750, 1500, 600, "bridgecross"),+ "helicopter": ("Fortress Avalanche", 1000, 2100, 300, "s240_heli"),+ "water": ("Tournament Island", 400, 1000, 240, None),+ "river": ("Winding River", 1300, 1700, 240, None),+}++OPTIONS = """Resolution = 1280 720+StaticGameLOD = Custom+IdealStaticGameLOD = High+DynamicLOD = no+TextureReduction = 0+TextureFilter = 2+Anisotropy = 8+ShadowQuality = 1+UseShadowVolumes = yes+UseShadowVolumesForSkins = yes+UseShadowDecals = yes+ShadowsForProps = yes+ShadowsForProjectiles = yes+ShadowsForParticles = yes+ShowTrees = yes+TreeSway = yes+ShowSoftWaterEdge = yes+UseCloudMap = yes+UseLightMap = yes+MaxParticleCount = 3000+ExtraAnimations = yes+SmoothMotion = no+ShowNetBox = no+VSync = no+MSAA = 0+"""+++def digest(path):+ return hashlib.sha256(path.read_bytes()).hexdigest()+++def main():+ p = argparse.ArgumentParser(description=__doc__)+ for name in ("generals", "root", "overlay", "out"):+ p.add_argument("--" + name, type=Path, required=True)+ p.add_argument("--case", choices=CASES, default="solid")+ p.add_argument("--mode", choices=("default", "legacy", "capture-only", "mapped"), default="default")+ p.add_argument("--quality", type=int, choices=(0, 1, 2), default=1, help="existing shadow quality: 1024/2048/4096")+ p.add_argument("--trees", choices=("yes", "no"), default="yes", help="ShowTrees preference; multiplayer can still load trees")+ p.add_argument("--geometry-shadows", choices=("yes", "no"), default="yes", help="set both ordinary shadow options")+ p.add_argument("--smoke-shadows", choices=("yes", "no"), help="override the separate volumetric smoke shadow option")+ p.add_argument("--gpu-debug", action="store_true", help="enable GPU validation (not a performance run)")+ p.add_argument("--icd", type=Path)+ p.add_argument("--timeout", type=int, default=240)+ p.add_argument("--frame", type=int, help="override the case's screenshot frame (also the measurement length minus 60)")+ p.add_argument("--replay", type=Path, help="play an existing recording in isolated user data instead of starting a match")+ p.add_argument("--measure", action="store_true", help="omit the screenshot and its settling/pacing window")+ p.add_argument("--logic-clock", action="store_true", help="use a fixed W3D animation/cloud clock for screenshot comparisons")+ p.add_argument("--report", action="store_true", help="read back sun depth occupancy (excluded from performance runs)")+ p.add_argument("--depth-dump", action="store_true", help="save the latest reported map as a 16-bit PGM; requires --report")+ p.add_argument("--fault", choices=("target", "receiver-program", "receiver-pipeline", "smoke-target", "smoke-pipeline"), help="inject a sun-specific creation failure")+ args = p.parse_args()+ if args.depth_dump and not args.report:+ p.error("--depth-dump requires --report")+ if (args.report or args.logic_clock or args.gpu_debug or args.fault) and args.measure:+ p.error("diagnostic readback/clocks/validation cannot be used with --measure")+ replay = args.replay.resolve() if args.replay else None+ if replay and (not replay.is_file() or args.logic_clock or CASES[args.case][4]):+ p.error("--replay requires an existing file, an ordinary clock and a case without scenario actions")+ exe, root, overlay, out = (getattr(args, n).resolve() for n in ("generals", "root", "overlay", "out"))+ if not exe.is_file() or not root.is_dir() or not overlay.is_dir():+ p.error("executable, prepared root and overlay must already exist")+ # No mixing fresh pictures with stale results, and no player settings or saves.+ out.mkdir(parents=True, exist_ok=False)+ user = out / "user"+ user.mkdir()+ options = OPTIONS.replace("ShadowQuality = 1", "ShadowQuality = " + str(args.quality))+ options = options.replace("ShowTrees = yes", "ShowTrees = " + args.trees)+ for option in ("UseShadowVolumes", "UseShadowDecals"):+ options = options.replace(option + " = yes", option + " = " + args.geometry_shadows)+ if args.smoke_shadows:+ options += "VolumetricSmokeShadows = " + args.smoke_shadows + "\n"+ (user / "Options.ini").write_text(options)+ name, x, y, shot, scenario = CASES[args.case]+ if replay:+ (user / "Replays").mkdir()+ shutil.copyfile(replay, user / "Replays" / "sun-check.rep")+ if args.frame is not None:+ if args.frame < 1:+ p.error("--frame must be positive")+ shot = args.frame+ scenario_source = None+ if scenario:+ # Development scenarios are deliberately absent from the packaged overlay.+ # Add just the chosen fixture to a private overlay, leaving the build untouched.+ fixture_overlay = out / "overlay"+ fixture_overlay.mkdir()+ for entry in overlay.iterdir():+ if entry.name != "Scenarios":+ (fixture_overlay / entry.name).symlink_to(entry, target_is_directory=entry.is_dir())+ (fixture_overlay / "Scenarios").mkdir()+ scenario_source = Path(__file__).resolve().parent.parent / "Data" / "Scenarios" / (scenario + ".txt")+ shutil.copyfile(scenario_source, fixture_overlay / "Scenarios" / scenario_source.name)+ overlay = fixture_overlay+ command = [str(exe), "-root", str(root), "-overlay", str(overlay),+ "-offscreen", "-multiInstance", "-noaudio",+ "-win", "-xres", "1280", "-yres", "720", "-msaa", "0",+ "-quickstart", "-noshellmap", "-nologo", "-novideo", "-noFPSLimit",+ "-camera", str(x), str(y),+ "-turbo", "-screenshot", str(shot), "-maxframes", str(shot + 60),+ "-logPrefix", "shadow_"]+ if replay:+ command += ["-replay", "sun-check"]+ else:+ command += ["-map", f"Maps/{name}/{name}.map", "-autoskirmish", "2",+ "-seed", "1", "-side", "0", "FactionAmerica",+ "-side", "1", "FactionChina"]+ # Cloak coverage requires the owner's view; observers do not draw the friendly cloak.+ if args.case != "cloak":+ command.append("-observer")+ if args.report:+ command.append("-shadowmapreport")+ # Replay playback ignores scheduled screenshots. Its gate is the rendered run's+ # limit-frame CRC, with the input recording retained by hash in the manifest.+ if args.measure or replay:+ at = command.index("-screenshot")+ del command[at:at + 2]+ if scenario:+ command += ["-takeover", "-scenario", scenario]+ overrides = {"ZH_USER_DATA_DIR": str(user), "ZH_UNATTENDED": "1",+ "ZH_AUDIO_BACKEND": "null", "SDL_GPU_DRIVER": "vulkan",+ "ZH_OFFSCREEN_HZ": "0",+ "ZH_SUN_SHADOW_MODE": args.mode, "ZH_GPU_TIMING": "0,1000000"}+ if args.mode == "default":+ overrides.pop("ZH_SUN_SHADOW_MODE")+ if args.gpu_debug:+ overrides["ZH_GPU_DEBUG"] = "1"+ if args.logic_clock:+ overrides["ZH_SUN_SHADOW_CAPTURE_CLOCK"] = "logic"+ if args.fault:+ overrides["ZH_TEST_SUN_SHADOW_FAILURE"] = args.fault+ if args.depth_dump:+ overrides["ZH_SUN_SHADOW_DEPTH_DUMP"] = str(out / "sun-depth.pgm")+ if args.icd:+ overrides["VK_DRIVER_FILES"] = str(args.icd.resolve())+ repository = Path(__file__).resolve().parents[3]+ manifest = {"command": command, "environment": overrides, "case": args.case,+ "mode": args.mode, "quality": args.quality, "exe_sha256": digest(exe),+ "trees": args.trees, "geometry_shadows": args.geometry_shadows, "smoke_shadows": args.smoke_shadows,+ "options_sha256": digest(user / "Options.ini"),+ "git_head": subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=repository, text=True).strip(),+ "git_diff_sha256": hashlib.sha256(subprocess.check_output(["git", "diff", "HEAD"], cwd=repository)).hexdigest(),+ "timing_scope": "device probe includes loading; HEADLESS FRAMETIME starts after logic frame 60",+ "measurement": args.measure}+ if scenario_source:+ manifest["scenario_sha256"] = digest(scenario_source)+ if replay:+ manifest["replay"] = {"source": str(replay), "sha256": digest(replay)}+ # New backend files can be untracked while an increment is under review.+ untracked = subprocess.check_output(["git", "ls-files", "--others", "--exclude-standard", "-z"], cwd=repository, text=True).split("\0")+ manifest["untracked_files_sha256"] = {name: digest(repository / name) for name in untracked+ if name and (repository / name).is_file()}+ manifest_path = out / "manifest.json"+ manifest_path.write_text(json.dumps(manifest, indent=2) + "\n")+ environment = dict(os.environ)+ # This switch is presence-based in the backend: "0" would still enable it.+ environment.pop("ZH_SUN_SHADOW_MODE", None)+ environment.pop("ZH_GPU_DEBUG", None)+ environment.pop("ZH_TEST_SUN_SHADOW_FAILURE", None)+ environment.pop("ZH_SUN_SHADOW_DEPTH_DUMP", None)+ environment.pop("ZH_SUN_SHADOW_CAPTURE_CLOCK", None)+ environment.update(overrides)+ start = time.monotonic()+ with (out / "run.log").open("w") as log:+ process = subprocess.Popen(command, cwd=out, env=environment,+ stdout=log, stderr=subprocess.STDOUT)+ try:+ try:+ manifest["returncode"] = process.wait(timeout=args.timeout)+ except subprocess.TimeoutExpired:+ manifest["timeout"] = True+ finally:+ if process.poll() is None:+ process.kill()+ process.wait()+ manifest["returncode"] = process.returncode+ manifest["elapsed_seconds"] = time.monotonic() - start+ engine_log = exe.parent / "shadow_DebugLogFile.txt"+ if engine_log.is_file():+ shutil.copyfile(engine_log, out / "engine.log")+ manifest["match_summary"] = [line for line in engine_log.read_text(errors="replace").splitlines()+ if line.startswith(("HEADLESS CRC", "HEADLESS FRAMETIME", "HEADLESS LOGICTIME", "HEADLESS SCENARIO"))]+ manifest["scenario_loaded"] = not scenario or ("SCENARIO: cannot open" not in engine_log.read_text(errors="replace")+ and any(line.startswith("HEADLESS SCENARIO:") and "0 actions," not in line+ for line in manifest["match_summary"]))+ manifest["reached_limit"] = any(line.startswith("HEADLESS CRC AT LIMIT:") and line.endswith(f" at frame {shot + 60}")+ for line in manifest.get("match_summary", []))+ shots = sorted(user.rglob("sshot*.bmp"))+ manifest["screenshots"] = [{"path": str(s), "sha256": digest(s)} for s in shots]+ manifest["timings"] = [line for line in (out / "run.log").read_text(errors="replace").splitlines()+ if "PosixDevice9 timing:" in line and "LONG FRAME" not in line]+ manifest["shadow_diagnostics"] = [line for line in (out / "run.log").read_text(errors="replace").splitlines()+ if line.startswith("SunShadow:")]+ depth_dump = out / "sun-depth.pgm"+ if depth_dump.is_file():+ manifest["depth_dump"] = {"path": str(depth_dump), "sha256": digest(depth_dump),+ "time": "latest report, not necessarily the screenshot frame"}+ manifest_path.write_text(json.dumps(manifest, indent=2) + "\n")+ print(json.dumps({"manifest": str(manifest_path), "returncode": process.returncode,+ "screenshots": len(shots), "elapsed_seconds": manifest["elapsed_seconds"]}))+ return int(process.returncode != 0 or (not args.measure and not replay and len(shots) != 1)+ or manifest.get("timeout", False) or not manifest.get("scenario_loaded", not scenario)+ or not manifest["reached_limit"])+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/docs/porting/windows-impact.md b/docs/porting/windows-impact.mdindex 41d429e33..d00913b71 100644--- a/docs/porting/windows-impact.md+++ b/docs/porting/windows-impact.md@@ -443,3 +443,20 @@ 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. |+++## Independent Linux shadow parity contribution++This feature starts directly from reference/3.1.0. Sun capture, tree capture,+shadow-option admission and queued cloak coverage are enabled on Linux. The+Windows Direct3D 11 backend sources remain unchanged; the shared adapter forwards+existing calls and returns empty queued coverage. Windows retains its original+water programs, tree silhouettes, caster selection and constant-cache comparisons.+macOS refuses the new scene capture and retains its existing shadows. Shared API,+shader and queue metadata still compile on these platforms; native builds and+runtime validation remain required. Linux tests do not establish that evidence.++The generic SDL additions are depth-only targets, target-specific depth formats,+smoke moments and diagnostic depth readback. The original emulated pixel register+count, sampler limit, single-uniform bindings and legacy water source stay intact.+No Modern water, cloud-volume feature, preview or workflow change is included.diff --git a/docs/sdl-sun-shadows.md b/docs/sdl-sun-shadows.mdnew file mode 100644index 000000000..3a9349696--- /dev/null+++ b/docs/sdl-sun-shadows.md@@ -0,0 +1,128 @@+# Linux sun and smoke shadows++This feature starts directly from `reference/3.1.0` and has no dependency on the+Modern water or volumetric hazard-cloud features. Linux uses mapped sun shadows+by default through SDL GPU. Windows retains its existing Direct3D 11 shadows;+macOS retains its existing scene shadows. Shadow capability is independent of+per-pixel lighting.++## Behavior and controls++The renderer reuses the existing sun camera, caster selection and filtering.+Registered units and buildings, bridges, batched foliage, object palms and+sorted translucent meshes such as rotor discs can cast. Friendly cloak casters+retain their per-draw partial coverage through sorting. Eligible solid,+terrain, road, bridge, tree and particle draws receive sun and smoke shadows.+Legacy water and reflections keep the existing 3.1.0 paths.++Existing shadow preferences remain authoritative. `ShadowQuality = 0`, `1` or+`2` chooses a 1024, 2048 or 4096 square sun map, with a consistent world-space+filter width. Unit casters honor `UseShadowVolumes`; tree and bridge capture+honors the ordinary volume/decal options. Trees already loaded by multiplayer+can cast when the `ShowTrees` preference is off. `VolumetricSmokeShadows`+independently controls smoke projection, including an otherwise empty capture+when ordinary geometry shadows are disabled.++`ZH_SUN_SHADOW_MODE` is a Linux diagnostic override:++| Value | Result |+| --- | --- |+| unset or `mapped` | Capture and receive supported mapped shadows. |+| `capture-only` | Capture depth while retaining legacy scene shadows. |+| `legacy` or an unknown value | Skip capture and retain legacy shadows. |++A request does not prove capture succeeded. `-shadowmapreport`, or the harness's+`--report`, reads back depth occupancy and reports accepted receiver counts.+Diagnostic readback affects timing.++## State and fallback++Scene generation, target, viewport and camera determine ownership. Nested+scenes and reflections cannot borrow another view's map or suppress its legacy+shadows. Queued draws keep immutable constants, receiver exclusions and cloak+coverage. Capture restores device state; replaced sun textures survive until+queued readers have been submitted.++Unsupported depth targets, invalid sizes and failed captures retain legacy+shadows. Smoke allocation or pipeline failure retains particle blobs while+solid mapped shadows can continue. Optional receiver-program or pipeline+failure retries ordinary geometry and latches legacy for later scenes until+device recreation. When mapped pixels were already submitted, that scene+retains its ownership to avoid double darkening. Fallback does not atomically+replay a partially submitted frame.++The native engine receiver block extends from 22 to 159 float4s and keeps its+existing prefix. Both reconstruction matrices use explicit `row_major` HLSL+matching CPU memory. Unused Windows lighting fields stay zero. The emulated+pixel register bank remains 32 entries, the draw keeps 8 sampler slots and each+stage binds one native uniform block. Sun depth and smoke use fragment slots 5+and 6. These native blocks do not require water FFT textures or water uniforms.+Sun-depth reports use a small independent depth-to-R32 diagnostic pass without+sampling the scene's depth attachment.++## Reproduce a scene++Use an existing Release executable, its overlay and a prepared file-link root+containing your own game data. No dependencies are installed by the harness.+Each output directory must be new. Run GPU workloads serially.++```sh+python3 GeneralsMD/Code/Tools/sun-shadow-check.py \+ --generals "$PWD/build-linux/generals" \+ --root /absolute/path/to/prepared-game-root \+ --overlay "$PWD/build-linux/overlay" \+ --out "$PWD/build-linux/shadow-solid-mapped" \+ --case solid --mode mapped --logic-clock --gpu-debug --report+```++For a matched legacy image, retain the executable, case and settings, select+`--mode legacy` and choose a new output directory. `--logic-clock` fixes+animation and authored shoreline phases for single-player screenshots. It does+not admit multiplayer or replay sessions and leaves ordinary launches unchanged.++Available cases are `solid`, `smoke`, `cloak`, `trees`, `forest`, `bridge`,+`helicopter`, `water` and `river`. Water cases inspect unchanged legacy water and+reflection behavior. The harness also accepts `--quality 0|1|2`, `--trees yes|no`,+`--geometry-shadows yes|no` and `--smoke-shadows yes|no`. Scenario fixtures are+copied into a private overlay only for cases that need them.++`--fault target|receiver-program|receiver-pipeline|smoke-target|smoke-pipeline`+requests a specific creation failure. `--depth-dump --report` saves the latest+reported depth map, which need not be the screenshot frame. `--replay` accepts an+existing recording for a case without scenario actions or a fixed capture clock.++`manifest.json` records the command, explicit environment, executable hash,+source SHA/diff, settings and scenario/replay hashes, exit status, limit-frame+CRC, screenshot hashes and available timing/receiving diagnostics. Git+provenance is bound to the harness's source checkout. Inspect images and logs+and compare CRCs; process exit alone does not establish correct visuals.++Use `--measure` for matched timing runs, with the same scene, settings,+executable and driver. This excludes screenshots, reports, fixed clocks, fault+injection and GPU validation. The device probe includes loading;+`HEADLESS FRAMETIME` starts after logic frame 60. These diagnostics are not a+universal steady-state FPS result.++## Validation and limits++After configuring a Release build with the repository's existing dependencies:++```sh+cmake --build build-linux --target posix_draw_resolve_selfcheck \+ posix_gpu_draw_selfcheck sdl_gpu_frame_selfcheck test_sun_shadow_sorting+ctest --test-dir build-linux --output-on-failure \+ -R '^(posix_draw_resolve_selfcheck|posix_gpu_draw_selfcheck|sdl_gpu_frame_selfcheck|test_sun_shadow_sorting|test_ffshadercompile)$'+```++Focused fixtures cover mode parsing, analytic translated-camera receivers,+smoke moments, tree silhouettes, sorted cloak coverage, state restoration,+queued resource replacement, empty clears, reset and injected creation failures.+The sun-target frame test retains the baseline gamma and clear checks. Runtime+sun fixtures are Linux-only; portable parser expectations remain checked on+other platforms. GPU tests skip when no usable device is available.++Real-game scenes and replay comparisons complement these fixtures. No old+stacked-branch result establishes this independent branch's validation. Record+its exact tested SHA, hardware, commands, failures and skips with the PR.+Linux evidence does not establish native Windows/macOS compatibility or visual+parity on every Linux GPU and driver.