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(gameengine): run the tick beside the render at -logicthread 1
Olcay Seyganb159eb227ca6
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/GameEngine.h b/GeneralsMD/Code/GameEngine/Include/Common/GameEngine.hindex 54b31f113..41529ed31 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/GameEngine.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/GameEngine.h@@ -158,8 +158,25 @@ public:virtual Bool isActive(void) {return m_isActive;} ///< returns whether app has OS focus.virtual void setIsActive(Bool isActive) { m_isActive = isActive; };+ /** LOGIC-THREAD.md phase 3, step 3b. Called by GameClient::update in front of the draw at+ * -logicthread 1 and 2: in a single-player game it runs this pass's message stream and asks the+ * pacer here, and answers whether this pass's first tick is due and may run beside the render. */+ Bool planOverlappedTick( void );++ /** What the pacer decided for one pass, see planLogicPass. */+ struct LogicPassPlan+ {+ Bool fastMode;+ Bool mayRun;+ Bool due;+ Bool mayCatchUp;+ Bool networkPaced;+ };+protected:+ void planLogicPass( LogicPassPlan &plan ); ///< the pacer: whether logic frames are due this pass, asked once a pass+virtual FileSystem *createFileSystem( void ); ///< Factory for FileSystem classesvirtual LocalFileSystem *createLocalFileSystem( void ) = 0; ///< Factory for LocalFileSystem classesvirtual ArchiveFileSystem *createArchiveFileSystem( void ) = 0; ///< Factory for ArchiveFileSystem classesdiff --git a/GeneralsMD/Code/GameEngine/Include/Common/LogicThread.h b/GeneralsMD/Code/GameEngine/Include/Common/LogicThread.hindex 8026dd5d8..fe4360e93 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/LogicThread.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/LogicThread.h@@ -110,6 +110,8 @@ namespace LogicThreadWINDOW_TERRAIN, ///< TerrainLogic's heights and waterWINDOW_PLAYER, ///< PlayerList::getNthPlayerWINDOW_RADAR_OBJECT, ///< RadarObject::friend_getObject, the radar's list of Objects+ WINDOW_DRAWABLE_FIELD, ///< a drawable's model condition or status bits, which the tick sets beside the render (step 3b); the look is LookForDraw's+ WINDOW_PLAYER_STATE, ///< a player's energy, radar, rank or defeat, which the tick changes (step 3b)WINDOW_COUNT};@@ -129,18 +131,35 @@ namespace LogicThreadnoteWindow( read );}- /** The window's span on the main thread, closed when it goes out of scope (a continue included). */+ /** The window's span on the main thread, closed when it goes out of scope (a continue included).+ * Step 3b: at 1 and 2, a window opened with mayOverlap on a pass prepareOverlap found a tick due+ * for hands that tick to the logic thread before it marks itself open, and close waits for it. */class OverlapWindow{public:OverlapWindow( void ) : m_open( FALSE ) {}~OverlapWindow( void ) { close(); }- void open( void );+ void open( Bool mayOverlap );void close( void );private:Bool m_open;};+ /** LOGIC-THREAD.md phase 3, step 3b, the overlap. GameClient::update calls this in front of the+ * draw: at 1 and 2 it asks GameEngine::planOverlappedTick, which runs the message stream and the+ * pacer there in a single-player match, whether the pass's first tick is due. */+ void prepareOverlap( void );++ /** W3DDisplay::draw, after the render's own restore (smooth motion): the tick that ran beside the+ * render is flushed here, as runTick flushes one, and an exception it threw is thrown again. */+ void flushOverlap( void );++ /** GameEngine::update: TRUE once if this pass's first tick ran beside the render. */+ Bool takeOverlappedTick( void );++ /** The last overlapped tick's own length on the logic thread, and how long the main thread waited for it. */+ void takeOverlapTimes( Real &tickMS, Real &waitMS );+/** Read -logicthread and start the thread if it asks for one. Called once, from GameEngine::init. */void init( void );diff --git a/GeneralsMD/Code/GameEngine/Include/Common/Player.h b/GeneralsMD/Code/GameEngine/Include/Common/Player.hindex 9889a183e..b10d52fd6 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/Player.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/Player.h@@ -55,6 +55,7 @@#include "Common/GameType.h"#include "Common/Handicap.h"#include "Common/KindOf.h"+#include "Common/LogicThread.h"#include "Common/MissionStats.h"#include "Common/Money.h"#include "Common/Science.h"@@ -401,8 +402,8 @@ public:UnsignedInt getSupplyBoxValue();///< Many things can affect the alue of a crate, but at heart it is a GlobalData ratio.- inline Energy *getEnergy() { return &m_energy; }- inline const Energy *getEnergy() const { return &m_energy; }+ inline Energy *getEnergy() { LOGIC_WINDOW_READ( WINDOW_PLAYER_STATE ); return &m_energy; }+ inline const Energy *getEnergy() const { LOGIC_WINDOW_READ( WINDOW_PLAYER_STATE ); return &m_energy; }// adds a power bonus to this player because of energy upgrade at his power plantsinline void addPowerBonus(Object *obj) { m_energy.addPowerBonus(obj); }@@ -883,6 +884,7 @@ public:/// divide by that difference.Int getRankProgressPercent() const{+ LOGIC_WINDOW_READ( WINDOW_PLAYER_STATE );const Int span = m_levelUp - m_levelDown;if( span <= 0 )return 100;diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/Drawable.h b/GeneralsMD/Code/GameEngine/Include/GameClient/Drawable.hindex 398bfbff0..8b04ff90b 100644--- a/GeneralsMD/Code/GameEngine/Include/GameClient/Drawable.h+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/Drawable.h@@ -374,7 +374,7 @@ public:void setTintStatus( TintStatus statusBits ) { BitSet( m_tintStatus, statusBits ); };void clearTintStatus( TintStatus statusBits ) { BitClear( m_tintStatus, statusBits ); };- Bool testTintStatus( TintStatus statusBits ) const { return BitTest( m_tintStatus, statusBits ); };+ Bool testTintStatus( TintStatus statusBits ) const { return BitTest( LogicThread::isInsideWindow() ? m_lookForDraw.tintStatus : m_tintStatus, statusBits ); };TintEnvelope *getColorTintEnvelope( void ) { return m_colorTintEnvelope; }void setColorTintEnvelope( TintEnvelope &source ) { if (m_colorTintEnvelope) *m_colorTintEnvelope = source; }@@ -395,7 +395,7 @@ public:// note that this is not necessarily the 'get' reflection of setDrawableHidden, since drawables// can spontaneously hide via stealth. (srj)//- inline Bool isDrawableEffectivelyHidden() const { return m_hidden || m_hiddenByStealth; }+ inline Bool isDrawableEffectivelyHidden() const { if( LogicThread::isInsideWindow() ) return m_lookForDraw.hidden; return m_hidden || m_hiddenByStealth; }void setSelectable( Bool selectable ); ///< Changes the drawables selectabilityBool isSelectable( void ) const;@@ -403,15 +403,17 @@ public:void setStealthLook(StealthLookType look);- StealthLookType getStealthLook() const { return m_stealthLook; }- StealthLookType getStealthDrawnLook() const { return m_stealthDrawnLook; }- Real getStealthFade() const { return m_stealthFade; }+ StealthLookType getStealthLook() const { return LogicThread::isInsideWindow() ? m_lookForDraw.stealthLook : m_stealthLook; }+ StealthLookType getStealthDrawnLook() const { return LogicThread::isInsideWindow() ? m_lookForDraw.stealthDrawnLook : m_stealthDrawnLook; }+ Real getStealthFade() const { return LogicThread::isInsideWindow() ? m_lookForDraw.stealthFade : m_stealthFade; }// 1 is own paint with no bend, the stealth floor (about a half) is glass. Cloak-in fade 0// is solid. The mix goes to that floor so the first frames still have travel while the// pulse has not left 1.0; once faded, the 2003 breath owns it. Decloak: fade 1 is the// pulse, fade 0 is solid. The shader keeps coverage: this is the mix, not alpha.Real getStealthSolid() const{+ if( LogicThread::isInsideWindow() )+ return m_lookForDraw.stealthSolid;const Real breath = getEffectiveOpacity();const Real fade = getStealthFade();if( getStealthLook() == STEALTHLOOK_NONE )@@ -472,7 +474,7 @@ public://---------------------------------------------------------------------------void setDrawableStatus( DrawableStatus bit ) { BitSet( m_status, bit ); }void clearDrawableStatus( DrawableStatus bit ) { BitClear( m_status, bit ); }- inline Bool testDrawableStatus( DrawableStatus bit ) const { return (m_status & bit) != 0; }+ inline Bool testDrawableStatus( DrawableStatus bit ) const { LOGIC_WINDOW_READ( WINDOW_DRAWABLE_FIELD ); return (m_status & bit) != 0; }void setShroudClearFrame( UnsignedInt frame ) { m_shroudClearFrame = frame; }UnsignedInt getShroudClearFrame( void ) { return m_shroudClearFrame; }@@ -510,12 +512,37 @@ public:void allocateShadows(void); ///< create shadow resources if not already present. Used by Options screen.void setFullyObscuredByShroud(Bool fullyObscured);- inline Bool getFullyObscuredByShroud(void) {return m_drawableFullyObscuredByShroud;}+ inline Bool getFullyObscuredByShroud(void) { return LogicThread::isInsideWindow() ? m_lookForDraw.fullyObscured : m_drawableFullyObscuredByShroud; }// Put on ice until later... M Lorenzen// inline UnsignedByte getFullyObscuredByShroudWithCheatSpy(void) {return (UnsignedByte)m_drawableFullyObscuredByShroud | 128;}//8 looks like a zero in most fonts- Bool getDrawsInMirror() const { return BitTest(m_status, DRAWABLE_STATUS_DRAWS_IN_MIRROR) || isKindOf(KINDOF_CAN_CAST_REFLECTIONS); }+ Bool getDrawsInMirror() const { if( LogicThread::isInsideWindow() ) return m_lookForDraw.drawsInMirror; return BitTest(m_status, DRAWABLE_STATUS_DRAWS_IN_MIRROR) || isKindOf(KINDOF_CAN_CAST_REFLECTIONS); }++ /** LOGIC-THREAD.md phase 3, step 3b. How the drawable looks, as the render reads it: hidden, stealth,+ * opacity, tint, the mirror and dynamic light flags. The tick writes these fields beside the render+ * (a unit stealthing, a container hiding its passengers, a flash on a hit) and Drawable::draw eases+ * the fades at the sync point, so takeLookForDraw copies them there, after the views' update and+ * before the overlap window, and every getter above answers the copy from inside the window. */+ struct LookForDraw+ {+ Bool hidden;+ Bool fullyObscured;+ Bool drawsInMirror;+ Bool receivesDynamicLights;+ Bool hasTintColor;+ Bool hasSelectionColor;+ StealthLookType stealthLook;+ StealthLookType stealthDrawnLook;+ Real stealthFade;+ Real stealthSolid;+ Real secondMaterialPassOpacity;+ Real effectiveOpacity;+ UnsignedInt tintStatus;+ Vector3 tintColor;+ Vector3 selectionColor;+ };+ void takeLookForDraw( void );void colorFlash( const RGBColor *color, UnsignedInt decayFrames = DEF_DECAY_FRAMES, UnsignedInt attackFrames = 0, UnsignedInt sustainAtPeak = FALSE ); ///< flash a drawable in the color specified for a short timevoid colorTint( const RGBColor *color ); ///< tint this drawable the color specified@@ -554,7 +581,7 @@ public:void removeFromList(Drawable **pListHead);void setID( DrawableID id ); ///< set this drawable's unique ID- inline const ModelConditionFlags& getModelConditionFlags( void ) const { return m_conditionState; }+ inline const ModelConditionFlags& getModelConditionFlags( void ) const { LOGIC_WINDOW_READ( WINDOW_DRAWABLE_FIELD ); return m_conditionState; }//// NOTE: avoid repeated calls to the set and clear for the condition state as they@@ -670,7 +697,7 @@ public:void setEffectiveOpacity( Real pulseFactor, Real explicitOpacity = -1.0f );// this is for the add'l pass fx which operates completely independently of the stealth opacity effects. Draw() does the fading every frame.- inline Real getSecondMaterialPassOpacity() const { return m_secondMaterialPassOpacity; } ///< get alpha/opacity value used to render add'l rendering pass.+ inline Real getSecondMaterialPassOpacity() const { return LogicThread::isInsideWindow() ? m_lookForDraw.secondMaterialPassOpacity : m_secondMaterialPassOpacity; } ///< get alpha/opacity value used to render add'l rendering pass.void setSecondMaterialPassOpacity( Real op ) { m_secondMaterialPassOpacity = op; }; ///< set alpha/opacity value used to render add'l rendering pass.// both of these assume that you are starting at one extreme 100% or 0% opacity and are trying to go to the other!! -- amit@@ -701,7 +728,7 @@ public:Bool hasIconInfo() const { return m_iconInfo != NULL; }- Bool getReceivesDynamicLights( void ) { return m_receivesDynamicLights; };+ Bool getReceivesDynamicLights( void ) { return LogicThread::isInsideWindow() ? m_lookForDraw.receivesDynamicLights : m_receivesDynamicLights; };void setReceivesDynamicLights( Bool set ) { m_receivesDynamicLights = set; };//---------------------------------------------------------------------------------@@ -828,6 +855,7 @@ private:ObjectShroudStatus m_shroudForDraw; ///< see setShroudForDrawBool m_objectDeadForDraw; ///< see setShroudForDrawObjectForDraw m_objectForDraw; ///< see setObjectForDraw+ LookForDraw m_lookForDraw; ///< see takeLookForDrawDrawableLocoInfo* m_locoInfo; // lazily allocateddiff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/GameClient.h b/GeneralsMD/Code/GameEngine/Include/GameClient/GameClient.hindex bf2a03392..8fe3cd721 100644--- a/GeneralsMD/Code/GameEngine/Include/GameClient/GameClient.h+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/GameClient.h@@ -157,7 +157,11 @@ public:virtual void selectDrawablesInGroup( Int group ); ///< select all drawables belong to the specifies groupvirtual void assignSelectedDrawablesToGroup( Int group ); ///< assign all selected drawables to the specified group//---------------------------------------------------------------------------------------- virtual UnsignedInt getFrame( void ) { return m_frame; } ///< Returns the current simulation frame number+ virtual UnsignedInt getFrame( void ) { return LogicThread::isInsideWindow() ? m_frameForDraw : m_frame; } ///< Returns the current simulation frame number+ /** LOGIC-THREAD.md phase 3, step 3b: the frame the render draws. A tick handed over beside the render+ * moves m_frame to its own frame first (LogicThread::runTick), and the window's clocks (tree sway,+ * move hints, string caches) read the frame they read when the tick ran after the draw. */+ void takeFrameForDraw( void ) { m_frameForDraw = m_frame; }//---------------------------------------------------------------------------virtual void setTeamColor( Int red, Int green, Int blue ) = 0; ///< @todo superhack for demo, remove!!!@@ -185,6 +189,7 @@ protected:// @todo Should there be a separate GameClient frame counter?UnsignedInt m_frame; ///< Simulation frame number from server+ UnsignedInt m_frameForDraw = 0; ///< see takeFrameForDrawDrawable *m_drawableList; ///< All of the drawables in the world// DrawablePtrHash m_drawableHash; ///< Used for DrawableID lookupsdiff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleSys.h b/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleSys.hindex f14c20256..bb0a75a56 100644--- a/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleSys.h+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleSys.h@@ -857,6 +857,7 @@ protected:DrawableID m_attachedToDrawableID; ///< if non-zero, system is parented to this DrawableObjectID m_attachedToObjectID; ///< if non-zero, system is parented to this Object+ DrawableID m_attachedObjectDrawableForDraw; ///< that Object's drawable at the last update, for getStealthFade inside the overlap windowMatrix3D m_localTransform; ///< local orientation & position of systemMatrix3D m_transform; ///< composite transform of parent Drawable and localdiff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.hindex 157b511de..b158af141 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.h@@ -165,7 +165,7 @@ public:UnsignedInt getFrame( void ); ///< Returns the current simulation frame number/** LOGIC-THREAD.md phase 3: the frame as the render's sync point found it, which getFrame answers the* main thread with inside the overlap window, where the tick may be advancing m_frame beside it. */- void takeFrameForDraw( void ) { m_frameForDraw = m_frame; }+ void takeFrameForDraw( void ) { m_frameForDraw = m_frame; m_pausedForDraw = m_gamePaused; }UnsignedInt getFrameForClient( void ) const { return m_frameForClient; } ///< the frame the last tick ran, for the client's clock (LogicThread::runTick)UnsignedInt getCRC( Int mode = CRC_CACHED, AsciiString deepCRCFileName = AsciiString::TheEmptyString ); ///< Returns the CRC@@ -367,6 +367,7 @@ private:UnsignedInt m_frame; ///< Simulation frame numberUnsignedInt m_frameForClient; ///< m_frame at the top of the last update that got past the intro movieUnsignedInt m_frameForDraw = 0; ///< see takeFrameForDraw+ Bool m_pausedForDraw = FALSE; ///< m_gamePaused, taken with m_frameForDraw for the same reason// CRC cache system -----------------------------------------------------------------------------UnsignedInt m_CRC; ///< Cache of previous CRC valuediff --git a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cppindex a13da3ac0..1c1f23fdf 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp@@ -2786,6 +2786,131 @@ static void updateHeadlessRun( void )TheGameEngine->setQuitting( TRUE );}+/* The pacer's debt, and the pass's plan when planOverlappedTick asked for it in front of the draw. */+static Real s_logicAccumMs = 0.0f;+static Bool s_passPlanned = FALSE;+static GameEngine::LogicPassPlan s_passPlan;+static UnsignedInt s_frameBeforeOverlap = 0;++void GameEngine::planLogicPass( LogicPassPlan &plan )+{+ // Fast-forward modes run a logic frame on every call; otherwise logic ticks at+ // m_maxFPS Hz of wall clock, however fast the client/renderer above is running.+#if defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE)+ Bool fastMode = TheGlobalData->m_TiVOFastMode;+#else+ Bool fastMode = TheGlobalData->m_TiVOFastMode && TheGameLogic->isInReplayGame();+#endif+ fastMode = fastMode || TheTacticalView->getTimeMultiplier() > 1 || TheScriptEngine->isTimeFast();++ /* -headless has no picture to pace the tick against and nobody watching it go by, so it runs+ a logic frame every pass and the match plays out as fast as the machine manages. Same+ branch as fast-forward, different reason: this one is not a cheat, it is the whole point+ of an unattended run. */+ fastMode = fastMode || TheGlobalData->m_headless;++ /* -jumpToFrame n: undrawn and as fast as the machine goes up to frame n, then paced. EA's loop+ ran a tick a pass anyway; paced on the wall clock, jumping to minute 24 took 24 minutes. */+ fastMode = fastMode || TheGlobalData->m_noDraw > TheGameLogic->getFrame();++ /* -turbo: the same for a run that draws, unless a network owns the clock. A -wav recording does+ not: its mix moves with the logic frames, not the wall clock (updateSoundCapture). The five seconds before a -screenshot run at the real rate. Taken straight out of+ fast-forward, a shot differed from its own repeat on 5.6% of the pixels; settled first, on+ 0.01%, where two paced runs differ on 0.1%. */+ const Int TURBO_SETTLE_FRAMES = 5 * LOGICFRAMES_PER_SECOND;+ const Int turboFrame = (Int)TheGameLogic->getFrame();+ const Bool turboSettling = TheGlobalData->m_screenShotFrame > 0+ && turboFrame + TURBO_SETTLE_FRAMES >= TheGlobalData->m_screenShotFrame+ && turboFrame <= TheGlobalData->m_screenShotFrame;+ fastMode = fastMode || ( TheGlobalData->m_turbo && !turboSettling && TheNetwork == NULL );++ /* -video: one logic frame a pass across the range being recorded, so the draw in front of each+ logic frame is the one picture of it. Paced by the wall clock, a pass that fell behind would+ run two logic frames back to back and the video would jump over one. */+ const Int videoLogicFrame = (Int)TheGameLogic->getFrame();+ fastMode = fastMode || ( TheGlobalData->m_videoEndFrame > 0 && TheGameLogic->isInGame()+ && !TheGameLogic->isInShellGame()+ && videoLogicFrame + 1 >= TheGlobalData->m_videoStartFrame+ && videoLogicFrame <= TheGlobalData->m_videoEndFrame );++ static UnsignedInt prevLogicTime = Clock_Milliseconds();+ UnsignedInt now = Clock_Milliseconds();+ Real elapsedMs = (Real)(now - prevLogicTime);+ prevLogicTime = now;++ const Bool logicMayRun =+ ((TheNetwork == NULL && !TheGameLogic->isGamePaused()) || (TheNetwork && TheNetwork->isFrameDataReady()));++ Bool logicFrameDue;+ Bool mayCatchUp = FALSE;+ const Bool networkPaced = TheNetwork != NULL && TheNetwork->isPacingLogicFrames();+ if (networkPaced)+ {+ // A network game already has a clock: Network::timeForNewFrame() paces the tick against+ // the negotiated frame rate and only then publishes the frame's commands. Gating a+ // second time here against m_maxFPS beats two independent clocks against each other -+ // a frame needs both to say yes, so the effective rate settles *below* either one and+ // drifts, which is a systematic multiplayer-only slowdown. Let the network own it and+ // keep the accumulator clean for when the game drops back to single player.+ //+ // It owns the debt as well. Each logic frame this machine manages a second is what it+ // reports to the room, and the room runs at the slowest report, so a pass that ran one+ // logic frame per picture made a slow graphics card everybody's frame rate: 60ms of+ // drawing on one of two machines held both at 15 logic frames a second. This one runs+ // ahead in this machine's own simulation by as many frames as the network has ready+ // and due, and headless is here too, since the network paces it all the same.+ s_logicAccumMs = 0.0f;+ logicFrameDue = TRUE;+ mayCatchUp = TRUE;+ }+ else if (fastMode)+ {+ s_logicAccumMs = 0.0f;+ // -recordfps: a recorded frame is drawn as many times as it has pictures, the logic waiting+ // for the last of them. A paused game draws its last picture again+ if (logicMayRun)+ s_videoPicture = (s_videoPicture + 1) % GameEngine_videoPictures();+ logicFrameDue = s_videoPicture == 0;+ }+ else+ {+ logicFrameDue = GameEngine_isLogicFrameDue(s_logicAccumMs, elapsedMs, m_maxFPS);+ // Fast mode means exactly one logic frame per call, by its own definition.+ mayCatchUp = (m_maxFPS > 0);+ }++ if (!logicMayRun)+ {+ // A paused game, or one waiting on the network, is not falling behind - it is stopped.+ // Drop the debt so resuming does not open with a catch-up burst.+ s_logicAccumMs = 0.0f;+ }++ plan.fastMode = fastMode;+ plan.mayRun = logicMayRun;+ plan.due = logicFrameDue;+ plan.mayCatchUp = mayCatchUp;+ plan.networkPaced = networkPaced;+}++/* LOGIC-THREAD.md phase 3, step 3b. The pass that overlaps: the client update up to the draw, then+ here the message stream and the pacer, which a pass that does not overlap runs after the client+ update; then the draw's sync point, and the tick goes to the logic thread as the overlap window+ opens (LogicThread::OverlapWindow). A network game keeps its own order, the network's update+ between the message stream and the tick, and stays serialised until phase 5. */+Bool GameEngine::planOverlappedTick( void )+{+ if (TheNetwork != NULL || !TheGameLogic->isInGame() || TheGameLogic->isInShellGame()+ || TheGameLogic->isLoadingMap())+ return FALSE;++ TheMessageStream->propagateMessages();+ planLogicPass( s_passPlan );+ s_passPlanned = TRUE;+ s_frameBeforeOverlap = TheGameLogic->getFrame();+ return s_passPlan.mayRun && s_passPlan.due;+}+void GameEngine::update( void ){USE_PERF_TIMER(GameEngine_update)@@ -2848,7 +2973,9 @@ void GameEngine::update( void )? (Int)( now % ( TheGlobalData->m_drawDelayJitterMS + 1 ) ) : 0;sleepMilliseconds( TheGlobalData->m_drawDelayMS + jitter );}- TheMessageStream->propagateMessages();+ // planOverlappedTick ran it in front of the draw on a pass that may overlap+ if (!s_passPlanned)+ TheMessageStream->propagateMessages();if (TheNetwork != NULL){@@ -2869,99 +2996,21 @@ void GameEngine::update( void )#endif- // Fast-forward modes run a logic frame on every call; otherwise logic ticks at- // m_maxFPS Hz of wall clock, however fast the client/renderer above is running.-#if defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE)- Bool fastMode = TheGlobalData->m_TiVOFastMode;-#else- Bool fastMode = TheGlobalData->m_TiVOFastMode && TheGameLogic->isInReplayGame();-#endif- fastMode = fastMode || TheTacticalView->getTimeMultiplier() > 1 || TheScriptEngine->isTimeFast();-- /* -headless has no picture to pace the tick against and nobody watching it go by, so it runs- a logic frame every pass and the match plays out as fast as the machine manages. Same- branch as fast-forward, different reason: this one is not a cheat, it is the whole point- of an unattended run. */- fastMode = fastMode || TheGlobalData->m_headless;-- /* -jumpToFrame n: undrawn and as fast as the machine goes up to frame n, then paced. EA's loop- ran a tick a pass anyway; paced on the wall clock, jumping to minute 24 took 24 minutes. */- fastMode = fastMode || TheGlobalData->m_noDraw > TheGameLogic->getFrame();-- /* -turbo: the same for a run that draws, unless a network owns the clock. A -wav recording does- not: its mix moves with the logic frames, not the wall clock (updateSoundCapture). The five seconds before a -screenshot run at the real rate. Taken straight out of- fast-forward, a shot differed from its own repeat on 5.6% of the pixels; settled first, on- 0.01%, where two paced runs differ on 0.1%. */- const Int TURBO_SETTLE_FRAMES = 5 * LOGICFRAMES_PER_SECOND;- const Int turboFrame = (Int)TheGameLogic->getFrame();- const Bool turboSettling = TheGlobalData->m_screenShotFrame > 0- && turboFrame + TURBO_SETTLE_FRAMES >= TheGlobalData->m_screenShotFrame- && turboFrame <= TheGlobalData->m_screenShotFrame;- fastMode = fastMode || ( TheGlobalData->m_turbo && !turboSettling && TheNetwork == NULL );-- /* -video: one logic frame a pass across the range being recorded, so the draw in front of each- logic frame is the one picture of it. Paced by the wall clock, a pass that fell behind would- run two logic frames back to back and the video would jump over one. */- const Int videoLogicFrame = (Int)TheGameLogic->getFrame();- fastMode = fastMode || ( TheGlobalData->m_videoEndFrame > 0 && TheGameLogic->isInGame()- && !TheGameLogic->isInShellGame()- && videoLogicFrame + 1 >= TheGlobalData->m_videoStartFrame- && videoLogicFrame <= TheGlobalData->m_videoEndFrame );-- static UnsignedInt prevLogicTime = Clock_Milliseconds();- static Real logicAccumMs = 0.0f;- UnsignedInt now = Clock_Milliseconds();- Real elapsedMs = (Real)(now - prevLogicTime);- prevLogicTime = now;-- const Bool logicMayRun =- ((TheNetwork == NULL && !TheGameLogic->isGamePaused()) || (TheNetwork && TheNetwork->isFrameDataReady()));-- Bool logicFrameDue;- Bool mayCatchUp = FALSE;- const Bool networkPaced = TheNetwork != NULL && TheNetwork->isPacingLogicFrames();- if (networkPaced)- {- // A network game already has a clock: Network::timeForNewFrame() paces the tick against- // the negotiated frame rate and only then publishes the frame's commands. Gating a- // second time here against m_maxFPS beats two independent clocks against each other -- // a frame needs both to say yes, so the effective rate settles *below* either one and- // drifts, which is a systematic multiplayer-only slowdown. Let the network own it and- // keep the accumulator clean for when the game drops back to single player.- //- // It owns the debt as well. Each logic frame this machine manages a second is what it- // reports to the room, and the room runs at the slowest report, so a pass that ran one- // logic frame per picture made a slow graphics card everybody's frame rate: 60ms of- // drawing on one of two machines held both at 15 logic frames a second. This one runs- // ahead in this machine's own simulation by as many frames as the network has ready- // and due, and headless is here too, since the network paces it all the same.- logicAccumMs = 0.0f;- logicFrameDue = TRUE;- mayCatchUp = TRUE;- }- else if (fastMode)- {- logicAccumMs = 0.0f;- // -recordfps: a recorded frame is drawn as many times as it has pictures, the logic waiting- // for the last of them. A paused game draws its last picture again- if (logicMayRun)- s_videoPicture = (s_videoPicture + 1) % GameEngine_videoPictures();- logicFrameDue = s_videoPicture == 0;- }+ // the pacer, asked once a pass: here, or in front of the draw by planOverlappedTick+ LogicPassPlan plan;+ if (s_passPlanned)+ plan = s_passPlan;else- {- logicFrameDue = GameEngine_isLogicFrameDue(logicAccumMs, elapsedMs, m_maxFPS);- // Fast mode means exactly one logic frame per call, by its own definition.- mayCatchUp = (m_maxFPS > 0);- }-- if (!logicMayRun)- {- // A paused game, or one waiting on the network, is not falling behind - it is stopped.- // Drop the debt so resuming does not open with a catch-up burst.- logicAccumMs = 0.0f;- }- else if (logicFrameDue)+ planLogicPass( plan );+ s_passPlanned = FALSE;+ const Bool fastMode = plan.fastMode;+ const Bool networkPaced = plan.networkPaced;+ const Bool mayCatchUp = plan.mayCatchUp;+ // LOGIC-THREAD.md phase 3, step 3b: this pass's first tick ran beside the render and was flushed+ // at the end of the draw+ const Bool overlapped = LogicThread::takeOverlappedTick();++ if (plan.mayRun && plan.due){#ifdef DEBUG_LOGGINGtLogicStart = Clock_Ticks();@@ -2979,11 +3028,13 @@ void GameEngine::update( void )plus the render is a dropped frame nobody files a bug about. */Int64 tCatchupStart, tCatchupNow;tCatchupStart = Clock_Ticks();- const UnsignedInt frameBeforeTicks = TheGameLogic->getFrame();+ const UnsignedInt frameBeforeTicks = overlapped ? s_frameBeforeOverlap : TheGameLogic->getFrame();for( ;; ){- // TheGameLogic->UPDATE(), on the logic thread at -logicthread 1- LogicThread::runTick();+ // TheGameLogic->UPDATE(), on the logic thread at -logicthread 1; the first of an overlapped+ // pass has run already, beside the render+ if (logicTicksThisPass > 0 || !overlapped)+ LogicThread::runTick();++logicTicksThisPass;// -maxframes' frame ends the burst, its CRC logged as it finishes (noteFrameLimit)@@ -3022,7 +3073,7 @@ void GameEngine::update( void )break;}// Asked last, because it is the one with a side effect: it spends the debt it reports.- else if (!GameEngine_isLogicFrameDue(logicAccumMs, 0.0f, m_maxFPS))+ else if (!GameEngine_isLogicFrameDue(s_logicAccumMs, 0.0f, m_maxFPS))break;}GameEngine_noteLogicTickDone( networkPaced ? TheGlobalData->m_framesPerSecondLimit : m_maxFPS, fastMode );@@ -3035,8 +3086,13 @@ void GameEngine::update( void )logicMS = engineElapsedMS( tLogicStart, tLogicEnd );logicTicks = logicTicksThisPass;// One pass can pay off several ticks of debt; charge the histogram per tick, or a- // catch-up burst reads as one enormous logic frame that never actually happened.- GameEngine_noteLogicTime( logicMS / (Real)logicTicksThisPass, TheGameLogic->getFrame() );+ // catch-up burst reads as one enormous logic frame that never actually happened. The tick+ // beside the render is charged at its own length, the pass at the wait for it.+ Real overlapTickMS = 0.0f, overlapWaitMS = 0.0f;+ if (overlapped)+ LogicThread::takeOverlapTimes( overlapTickMS, overlapWaitMS );+ GameEngine_noteLogicTime( ( logicMS + overlapTickMS ) / (Real)logicTicksThisPass, TheGameLogic->getFrame() );+ logicMS += overlapWaitMS;#endif}diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cppindex 548c2f061..1eaa13f56 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp@@ -3884,6 +3884,7 @@ void Player::enableRadar()//-------------------------------------------------------------------------------------------------Bool Player::hasRadar() const{+ LOGIC_WINDOW_READ( WINDOW_PLAYER_STATE );if( m_radarDisabled && (m_disableProofRadarCount == 0) )return FALSE;// Nope, no matter how many you have, if I say no, you don't have it@@ -4650,6 +4651,7 @@ Bool Player::isPlayerDead(void) const// ------------------------------------------------------------------------------------------------Bool Player::isPlayerActive(void) const{+ LOGIC_WINDOW_READ( WINDOW_PLAYER_STATE );return !m_observer && !m_isPlayerDead;}diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/LogicThread.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/LogicThread.cppindex 1f450bd38..523ab1f42 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/System/LogicThread.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/LogicThread.cpp@@ -27,6 +27,7 @@#include "Common/CriticalSection.h"#include "Common/EarlyCommandLine.h"#include "Common/GameAudio.h"+#include "Common/GameEngine.h"#include "Common/MessageStream.h"#include "GameClient/ControlBar.h"#include "GameClient/Drawable.h"@@ -92,9 +93,25 @@ namespaceconst char *const WINDOW_NAMES[ LogicThread::WINDOW_COUNT ] ={"drawableobject", "findobject", "objectlist", "logicframe", "thing", "shroud", "partition",- "terrain", "player", "radarobject"+ "terrain", "player", "radarobject", "drawablefield", "playerstate"};+ // step 3b, main thread only: the pass's first tick due and allowed beside the render (prepareOverlap),+ // handed over (the window open), waited for (the window closed), flushed, and the times of the last one+ Bool s_overlapWanted = FALSE;+ Bool s_overlapRunning = FALSE;+ Bool s_overlapDone = FALSE;+ Bool s_overlapTaken = FALSE;+ std::exception_ptr s_overlapError;+ LogicClock::time_point s_overlapStart;+ Real s_overlapTickMS = 0.0f;+ Real s_overlapWaitMS = 0.0f;+ Int s_overlappedTicks = 0;+ Real s_overlapWaitTotalMS = 0.0f;+ // the wait in tenths of a millisecond up to 50, the last bucket everything past it+ const Int WAIT_BUCKETS = 501;+ Int s_waitHistogram[ WAIT_BUCKETS ] = { 0 };+// -logicthread 2: 1 with a jitter on both sides of the handoff, so the races step 3 must not have// meet more orders. A generator per thread and of its own: nothing here may touch a game stream.Int s_mode = 0;@@ -269,8 +286,63 @@ void LogicThread::noteWindow( WindowRead read )}//--------------------------------------------------------------------------------------------------void LogicThread::OverlapWindow::open( void )+/* Step 3b: the pass's first tick to the logic thread, at the sync point's end. Everything the render+ reads of logic was taken before this (takeReadsForRender), and the client block the tick reads is+ taken here, as runTick takes it. */+static void startOverlap( void ){+ if( tickNeedsMainThread() )+ return;+ captureClientBlock();+ TheGameClient->setFrame( TheGameLogic->getFrame() );+ jitter();+ s_overlapStart = LogicClock::now();+ {+ std::lock_guard<std::mutex> lock( s_lock );+ s_tickPending = TRUE;+ }+ s_wakeCv.notify_one();+ s_overlapRunning = TRUE;+}++//-------------------------------------------------------------------------------------------------+static void waitOverlap( void )+{+ const LogicClock::time_point t0 = LogicClock::now();+ std::exception_ptr error;+ Real tickMS;+ {+ std::unique_lock<std::mutex> lock( s_lock );+ s_doneCv.wait( lock, []{ return s_tickDone; } );+ s_tickDone = FALSE;+ error = s_error;+ s_error = NULL;+ tickMS = s_tickMS;+ }+ const LogicClock::time_point t1 = LogicClock::now();+ jitter();+ // as runTick: the main thread's FPU as an inline tick leaves it+ setFPMode();++ s_overlapRunning = FALSE;+ s_overlapDone = TRUE;+ s_overlapError = error;+ s_overlapTickMS = tickMS;+ s_overlapWaitMS = elapsedMS( t0, t1 );+ ++s_overlappedTicks;+ s_overlapWaitTotalMS += s_overlapWaitMS;+ Int bucket = (Int)( s_overlapWaitMS * 10.0f );+ if( bucket >= WAIT_BUCKETS )+ bucket = WAIT_BUCKETS - 1;+ ++s_waitHistogram[ bucket ];+}++//-------------------------------------------------------------------------------------------------+void LogicThread::OverlapWindow::open( Bool mayOverlap )+{+ if( mayOverlap && s_overlapWanted )+ startOverlap();+ s_overlapWanted = FALSE;m_open = TRUE;++s_windows;g_windowOpen.store( 1, std::memory_order_relaxed );@@ -283,6 +355,48 @@ void LogicThread::OverlapWindow::close( void )return;m_open = FALSE;g_windowOpen.store( 0, std::memory_order_relaxed );+ if( s_overlapRunning )+ waitOverlap();+}++//-------------------------------------------------------------------------------------------------+void LogicThread::prepareOverlap( void )+{+ s_overlapWanted = s_enabled && TheGameEngine->planOverlappedTick();+}++//-------------------------------------------------------------------------------------------------+void LogicThread::flushOverlap( void )+{+ if( !s_overlapDone )+ return;+ s_overlapDone = FALSE;+ s_overlapTaken = TRUE;+ if( s_overlapError )+ {+ std::exception_ptr error = s_overlapError;+ s_overlapError = NULL;+ std::rethrow_exception( error );+ }+ flushAfterTick();+}++//-------------------------------------------------------------------------------------------------+Bool LogicThread::takeOverlappedTick( void )+{+ // a draw that left before its flush (none does today) still has the tick flushed before the engine goes on+ flushOverlap();+ const Bool taken = s_overlapTaken;+ s_overlapTaken = FALSE;+ s_overlapWanted = FALSE;+ return taken;+}++//-------------------------------------------------------------------------------------------------+void LogicThread::takeOverlapTimes( Real &tickMS, Real &waitMS )+{+ tickMS = s_overlapTickMS;+ waitMS = s_overlapWaitMS;}//-------------------------------------------------------------------------------------------------@@ -496,6 +610,22 @@ void LogicThread::report( void )s_threadedTicks ? s_handoffTotalMS / s_threadedTicks : 0.0f,handoffPercentileMicros( 0.5f ) / 1000.0f, handoffPercentileMicros( 0.99f ) / 1000.0f, s_handoffMaxMS ));+ // step 3b: the ticks that ran beside the render, and how long the render's end waited for them+ {+ Int waitP50 = 0, waitP99 = 0, seen = 0;+ for( Int i = 0; i < WAIT_BUCKETS; ++i )+ {+ if( seen <= s_overlappedTicks / 2 && seen + s_waitHistogram[ i ] > s_overlappedTicks / 2 )+ waitP50 = i;+ if( seen <= (Int)( s_overlappedTicks * 0.99f ) && seen + s_waitHistogram[ i ] > (Int)( s_overlappedTicks * 0.99f ) )+ waitP99 = i;+ seen += s_waitHistogram[ i ];+ }+ DEBUG_LOG(( "HEADLESS LOGICTHREAD OVERLAP: %d ticks beside the render | wait %.2f/%.1f/%.1f ms mean/p50/p99\n",+ s_overlappedTicks, s_overlappedTicks ? s_overlapWaitTotalMS / s_overlappedTicks : 0.0f,+ waitP50 / 10.0f, waitP99 / 10.0f ));+ }+char line[ 1024 ];Int used = 0;for( Int i = 0; i < CENSUS_COUNT; ++i )diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cppindex f22f6d1b2..bb8e0741f 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp@@ -537,9 +537,39 @@ Bool Drawable_disabledShowsBlueHealthBar( DisabledMaskType disabledFlags )//-------------------------------------------------------------------------------------------------Real Drawable::getEffectiveOpacity() const{+ if( LogicThread::isInsideWindow() )+ return m_lookForDraw.effectiveOpacity;return Drawable_effectiveOpacity( m_explicitOpacity, m_effectiveStealthOpacity, m_objectForDraw.awaitingBuilder );}+//-------------------------------------------------------------------------------------------------+/** LOGIC-THREAD.md phase 3, step 3b: see LookForDraw. Outside the window, so every getter reads the+ * drawable's own fields. */+//-------------------------------------------------------------------------------------------------+void Drawable::takeLookForDraw( void )+{+ LookForDraw &look = m_lookForDraw;+ look.hidden = isDrawableEffectivelyHidden();+ look.fullyObscured = m_drawableFullyObscuredByShroud;+ look.drawsInMirror = getDrawsInMirror();+ look.receivesDynamicLights = m_receivesDynamicLights;+ look.stealthLook = m_stealthLook;+ look.stealthDrawnLook = m_stealthDrawnLook;+ look.stealthFade = m_stealthFade;+ look.stealthSolid = getStealthSolid();+ look.secondMaterialPassOpacity = m_secondMaterialPassOpacity;+ look.effectiveOpacity = getEffectiveOpacity();+ look.tintStatus = m_tintStatus;+ const Vector3 *tint = getTintColor();+ look.hasTintColor = tint != NULL;+ if( tint )+ look.tintColor = *tint;+ const Vector3 *selection = getSelectionColor();+ look.hasSelectionColor = selection != NULL;+ if( selection )+ look.selectionColor = *selection;+}+//-------------------------------------------------------------------------------------------------/** Drawables are lightweight, graphical entities which live on the GameClient,* and are usually bound to GameLogic objects. In other words, they are the@@ -622,6 +652,21 @@ Drawable::Drawable( const ThingTemplate *thingTemplate, DrawableStatus statusBitm_objectForDraw.safeOcclusionFrame = 0;m_objectForDraw.layer = LAYER_GROUND;m_objectForDraw.layerHeight = 0.0f;+ m_lookForDraw.hidden = FALSE;+ m_lookForDraw.fullyObscured = FALSE;+ m_lookForDraw.drawsInMirror = FALSE;+ m_lookForDraw.receivesDynamicLights = TRUE;+ m_lookForDraw.hasTintColor = FALSE;+ m_lookForDraw.hasSelectionColor = FALSE;+ m_lookForDraw.stealthLook = STEALTHLOOK_NONE;+ m_lookForDraw.stealthDrawnLook = STEALTHLOOK_NONE;+ m_lookForDraw.stealthFade = 0.0f;+ m_lookForDraw.stealthSolid = 1.0f;+ m_lookForDraw.secondMaterialPassOpacity = 0.0f;+ m_lookForDraw.effectiveOpacity = 1.0f;+ m_lookForDraw.tintStatus = 0;+ m_lookForDraw.tintColor.Set( 0.0f, 0.0f, 0.0f );+ m_lookForDraw.selectionColor.Set( 0.0f, 0.0f, 0.0f );for (i = 0; i < NUM_DRAWABLE_MODULE_TYPES; ++i)m_modules[i] = NULL;@@ -1323,6 +1368,8 @@ void Drawable::onUnselected()//-------------------------------------------------------------------------------------------------const Vector3 * Drawable::getTintColor( void ) const{+ if( LogicThread::isInsideWindow() )+ return m_lookForDraw.hasTintColor ? &m_lookForDraw.tintColor : NULL;if ( m_colorTintEnvelope ){if (m_colorTintEnvelope->isEffective())@@ -1339,6 +1386,8 @@ const Vector3 * Drawable::getTintColor( void ) const//-------------------------------------------------------------------------------------------------const Vector3 * Drawable::getSelectionColor( void ) const{+ if( LogicThread::isInsideWindow() )+ return m_lookForDraw.hasSelectionColor ? &m_lookForDraw.selectionColor : NULL;if (m_selectionFlashEnvelope){if (m_selectionFlashEnvelope->isEffective())@@ -5149,6 +5198,10 @@ DrawModule** Drawable::getDrawModules(){DrawModule** dm = (DrawModule**)getModuleList(MODULETYPE_DRAW);#ifdef DIRTY_CONDITION_FLAGS+ // LOGIC-THREAD.md phase 3, step 3b: inside the overlap window the tick may be setting this drawable's+ // conditions; W3DDisplay's takeReadsForRender flushed the client's at the sync point+ if (LogicThread::isInsideWindow())+ return dm;if (m_isModelDirty){if (TheGameLogic->isInGameLogicUpdate())@@ -5165,6 +5218,8 @@ DrawModule const** Drawable::getDrawModules() const{DrawModule const** dm = (DrawModule const**)getModuleList(MODULETYPE_DRAW);#ifdef DIRTY_CONDITION_FLAGS+ if (LogicThread::isInsideWindow())+ return dm;if (m_isModelDirty){if (TheGameLogic->isInGameLogicUpdate())@@ -6961,6 +7016,9 @@ void Drawable::loadPostProcess( void )#ifdef DIRTY_CONDITION_FLAGS/*static*/ void Drawable::friend_lockDirtyStuffForIteration(){+ // the walk ran at the sync point, and the tick reads s_modelLockCount beside the render+ if (LogicThread::isInsideWindow())+ return;if (s_modelLockCount == 0){if (TheGameClient) // WB has no GameClient!@@ -6981,6 +7039,8 @@ void Drawable::loadPostProcess( void )#ifdef DIRTY_CONDITION_FLAGS/*static*/ void Drawable::friend_unlockDirtyStuffForIteration(){+ if (LogicThread::isInsideWindow())+ return;if (s_modelLockCount > 0)--s_modelLockCount;}diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GameClient.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GameClient.cppindex b968ab4b1..165575036 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GameClient.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GameClient.cpp@@ -982,6 +982,9 @@ void GameClient::update( void )Int64 drawStart, drawEnd;drawStart = Clock_Ticks();#endif+ // LOGIC-THREAD.md phase 3, step 3b: at 1 and 2 the message stream and the pacer run here, so a+ // due tick can go to the logic thread when the draw's sync point is done+ LogicThread::prepareOverlap();/* -directorrecord's panes: every pane past the first is drawn first, for the recording onlyand never presented, then the frame everybody sees. W3D's clock stands still for everydraw after the first on one client frame, so nothing animates twice. */diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cppindex 37db3bd02..dcc6277a8 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp@@ -1422,6 +1422,7 @@ ParticleSystem::ParticleSystem( const ParticleSystemTemplate *sysTemplate,m_attachedToDrawableID = INVALID_DRAWABLE_ID;m_attachedToObjectID = INVALID_ID;+ m_attachedObjectDrawableForDraw = INVALID_DRAWABLE_ID;m_isLocalIdentity = true;m_localTransform.Make_Identity();@@ -2350,6 +2351,7 @@ Bool ParticleSystem::updateEmission( Int localPlayerIndex, Bool *keepSystem )isShrouded = (objectAttachedTo->getShroudedStatus(localPlayerIndex) >= OBJECTSHROUD_FOGGED);const Drawable * draw = objectAttachedTo->getDrawable();+ m_attachedObjectDrawableForDraw = draw ? draw->getID() : INVALID_DRAWABLE_ID;if ( draw )parentXfrm = draw->getTransformMatrix();else@@ -2762,6 +2764,8 @@ Real ParticleSystem::getStealthFade( void ) constconst Drawable *draw = NULL;if (sys->m_attachedToDrawableID != INVALID_DRAWABLE_ID)draw = TheGameClient->findDrawableByID( sys->m_attachedToDrawableID );+ else if (LogicThread::isInsideWindow())+ draw = TheGameClient->findDrawableByID( sys->m_attachedObjectDrawableForDraw );else if (sys->m_attachedToObjectID != INVALID_ID){// gone since the last particle update, which then destroys the systemdiff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cppindex 4fed8ef6d..a501bf9f5 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp@@ -5455,7 +5455,7 @@ void GameLogic::sendObjectDestroyed( Object *obj )// ------------------------------------------------------------------------------------------------Bool GameLogic::isGamePaused( void ){- return m_gamePaused;+ return LogicThread::isInsideWindow() ? m_pausedForDraw : m_gamePaused;}// ------------------------------------------------------------------------------------------------diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/BaseHeightMap.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/BaseHeightMap.hindex 276f60706..4db44c956 100644--- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/BaseHeightMap.h+++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/BaseHeightMap.h@@ -42,6 +42,7 @@#include "Lib/BaseType.h"#include "GameLogic/TerrainHeightSampling.h"#include "Common/GameType.h"+#include "Common/LogicThread.h"#include "WorldHeightMap.h"// The lights one terrain relight takes in, the rest dropped. Only the vertex path reads it: the@@ -62,13 +63,15 @@ class W3DPropBuffer;class W3DTreeDrawModuleData;class GeometryInfo;-/** LOGIC-THREAD.md phase 3: the drawn map's heights as the last sync point left them. The map the- * terrain draws is logic's own, and a structure flattening its footprint lowers it inside the tick;- * this copy takes a cell only when terrainHeightChanged tells the terrain, after the tick. */-class DrawHeightMapData : public WorldHeightMapData+/** LOGIC-THREAD.md phase 3, step 3b: logic's own copy of the map's heights. A structure flattening its+ * footprint lowers cells inside the tick (W3DTerrainVisual::setRawMapHeight), and the render reads the+ * map beside the tick everywhere it builds, lights and shadows the ground. So the tick writes this+ * copy and every height logic asks for comes from it, and the map the terrain draws takes the cell+ * after the tick, with terrainHeightChanged. */+class LogicHeightMapData : public WorldHeightMapData{public:- ~DrawHeightMapData( void ) { m_data = NULL; } // m_heights owns them, not the base+ ~LogicHeightMapData( void ) { m_data = NULL; } // m_heights owns them, not the basevoid copyFrom( WorldHeightMapData *map ){m_width = map->getXExtent();@@ -78,7 +81,6 @@ public:m_heights.assign( map->getDataPtr(), map->getDataPtr() + m_dataSize );m_data = m_heights.empty() ? NULL : &m_heights[ 0 ];}- void copyCell( WorldHeightMapData *map, Int x, Int y ) { m_heights[ x + y * m_width ] = map->getDataPtr()[ x + y * m_width ]; }private:std::vector< UnsignedByte > m_heights;};@@ -243,8 +245,10 @@ public:void setShoreLineDetail(void); ///<update shoreline tiles in case the feature was toggled by user.Bool getMaximumVisibleBox(const FrustumClass &frustum, AABoxClass *box, Bool ignoreMaxHeight); ///<3d extent of visible terrain.Real getHeightMapHeight(Real x, Real y, Coord3D* normal) const; ///<return height and normal at given point- Real getDrawHeight(Real x, Real y) const; ///< getHeightMapHeight from the sync point's copy, for the render beside a tick- void heightsLoaded(void) { m_drawHeights.copyFrom(m_map); staticLightingChanged(); } ///< a save wrote every height at once+ Real getDrawHeight(Real x, Real y) const; ///< getHeightMapHeight from the drawn map, for the render beside a tick+ void heightsLoaded(void) { s_logicHeights.copyFrom(m_map); staticLightingChanged(); } ///< a save wrote every height at once+ UnsignedByte getLogicRawHeight(Int x, Int y) { return s_logicHeights.getHeight(x, y); } ///< a cell of logic's heights (LogicHeightMapData)+ void setLogicRawHeight(Int x, Int y, UnsignedByte height) { s_logicHeights.setRawHeight(x, y, height); } ///< the drawn map takes it with terrainHeightChangedBool isCliffCell(Real x, Real y); ///<return height and normal at given pointReal getMinHeight(void) const {return m_minHeight;} ///<return minimum height of entire terrainReal getMaxHeight(void) const {return m_maxHeight;} ///<return maximum height of entire terrain@@ -313,7 +317,20 @@ protected:void drawScorches(void); ///< Draws the scorch mark polygons in m_vertexScorch.#endifWorldHeightMap *m_map;- mutable DrawHeightMapData m_drawHeights; ///< getDrawHeight's, see DrawHeightMapData+ /** Every height logic asks for, see LogicHeightMapData. One for the map, not one a render object: the+ * terrain LOD swaps TheTerrainRenderObject between this and the flat one, a choice each machine+ * makes for itself, and logic has to read the same heights through either. */+ static LogicHeightMapData s_logicHeights;+ /** The heights a query reads: logic's copy, or the drawn map for a render inside the overlap window+ * (the tree shadows, the decals), where the tick may be writing the copy. */+ WorldHeightMapData *logicHeightsOrNull( void ) const+ {+ if( m_map == NULL )+ return NULL;+ if( LogicThread::isInsideWindow() )+ return m_map;+ return &s_logicHeights;+ }Bool m_useDepthFade; ///<fade terrain lighting under waterBool m_updating;Vector3 m_depthFade; ///<depth based fall off values for r,g,bdiff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DView.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DView.hindex 726c41b54..ffa01d69a 100644--- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DView.h+++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DView.h@@ -359,6 +359,7 @@ private:AsciiString m_cameraSlaveObjectBoneName;Display::DrawCalls m_postDraw; ///< recordPostDraw's calls, replayed by draw+ Drawable *m_cameraLockDrawForDraw = NULL; ///< the camera lock's drawable, looked up by recordPostDraw for a filtered draw}; // end class W3DView// EXTERNALS //////////////////////////////////////////////////////////////////////////////////////diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/Common/System/W3DRadar.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/Common/System/W3DRadar.cppindex aa27bea61..c2f77ccd0 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/Common/System/W3DRadar.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/Common/System/W3DRadar.cpp@@ -1379,12 +1379,8 @@ void W3DRadar::setShroudLevel(Int shroudX, Int shroudY, CellShroudStatus setting//-------------------------------------------------------------------------------------------------void W3DRadar::draw( Int pixelX, Int pixelY, Int width, Int height ){-- // if the local player does not have a radar then we can't draw anything- Player *player = ThePlayerList->getLocalPlayer();- if( !player->hasRadar() && !TheRadar->isRadarForced() )- return;-+ // W3DLeftHUDDraw, the one caller, asked whether the local player has a radar, from the sync point's+ // copy inside the overlap window//// given a upper left corner at pixelX|Y and a width and height to draw into, figure out// where we should start and end the image so that the final drawn image has thediff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/BaseHeightMap.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/BaseHeightMap.cppindex 7697fcfcf..b414dd3df 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/BaseHeightMap.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/BaseHeightMap.cpp@@ -119,6 +119,8 @@ extern HeightMapRenderObjClass *TheHeightMap;static ShaderClass detailOpaqueShader(SC_DETAIL_BLEND);+LogicHeightMapData BaseHeightMapRenderObjClass::s_logicHeights;+//-----------------------------------------------------------------------------// Global Functions & Data//-----------------------------------------------------------------------------@@ -931,25 +933,26 @@ Real BaseHeightMapRenderObjClass::getHeightMapHeight(Real x, Real y, Coord3D* no// M Lorenzen- // by doing it this way the compiler won't call getLogicHeightMap twice...- WorldHeightMap *logicHeightMap = TheTerrainVisual?TheTerrainVisual->getLogicHeightMap():m_map;- return TerrainHeightSampling::getHeightMapHeight(m_map, logicHeightMap, x, y, normal);+ // LOGIC-THREAD.md phase 3, step 3b: logic's heights are their own copy now (LogicHeightMapData), the+ // same bytes as the visual's logical map whenever no tick is running+ WorldHeightMapData *logicHeights = logicHeightsOrNull();+ return TerrainHeightSampling::getHeightMapHeight(logicHeights, logicHeights, x, y, normal);}//=============================================================================-/** getHeightMapHeight for the render: the same sampling over the heights the last sync point left- (DrawHeightMapData), which a tick running beside the render does not write. */+/** getHeightMapHeight for the render: the same sampling over the drawn map, which the tick does not+ write (LogicHeightMapData). *///=============================================================================Real BaseHeightMapRenderObjClass::getDrawHeight(Real x, Real y) const{- return TerrainHeightSampling::getHeightMapHeight(&m_drawHeights, &m_drawHeights, x, y, NULL);+ return TerrainHeightSampling::getHeightMapHeight(m_map, m_map, x, y, NULL);}//=============================================================================Bool BaseHeightMapRenderObjClass::isClearLineOfSight(const Coord3D& pos, const Coord3D& posOther) const{- WorldHeightMap *logicHeightMap = TheTerrainVisual?TheTerrainVisual->getLogicHeightMap():m_map;- return TerrainHeightSampling::isClearLineOfSight(m_map, logicHeightMap, getMaxHeight(), pos, posOther);+ WorldHeightMapData *logicHeights = logicHeightsOrNull();+ return TerrainHeightSampling::isClearLineOfSight(logicHeights, logicHeights, getMaxHeight(), pos, posOther);}//=============================================================================@@ -959,8 +962,8 @@ Bool BaseHeightMapRenderObjClass::isClearLineOfSight(const Coord3D& pos, const C//=============================================================================Real BaseHeightMapRenderObjClass::getMaxCellHeight(Real x, Real y) const{- WorldHeightMap *logicHeightMap = TheTerrainVisual?TheTerrainVisual->getLogicHeightMap():m_map;- return TerrainHeightSampling::getMaxCellHeight(m_map, logicHeightMap, x, y);+ WorldHeightMapData *logicHeights = logicHeightsOrNull();+ return TerrainHeightSampling::getMaxCellHeight(logicHeights, logicHeights, x, y);}//=============================================================================@@ -1498,8 +1501,10 @@ Int BaseHeightMapRenderObjClass::initHeightData(Int x, Int y, WorldHeightMap *pM{REF_PTR_SET(m_map, pMap); //update our heightmap pointer in case it changed since last call.- if (pMap)- m_drawHeights.copyFrom(pMap);+ // a device reset re-inits the same map from inside the overlap window, beside a tick that may be+ // flattening cells the drawn map takes only after it+ if (pMap && !LogicThread::isInsideWindow())+ s_logicHeights.copyFrom(pMap);m_staticDiffuseStale = true;m_terrainContentVersion++;@@ -2277,7 +2282,6 @@ void BaseHeightMapRenderObjClass::terrainHeightChanged( Int x, Int y )rebuilding only the cell that moved leaves a seam of stale shading around it. */const Int PAD = 2;m_terrainContentVersion++;- m_drawHeights.copyCell(m_map, x, y);if (!m_hasDirtyRegion){m_dirtyRegion.lo.x = x - PAD;diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/GUICallbacks/W3DControlBar.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/GUICallbacks/W3DControlBar.cppindex 5b52a4a43..b7eb0a6e9 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/GUICallbacks/W3DControlBar.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/GUICallbacks/W3DControlBar.cpp@@ -41,12 +41,75 @@#include "GameClient/Image.h"#include "GameClient/MapUtil.h"#include "GameLogic/GameLogic.h"+#include "Common/LogicThread.h"#ifdef _INTERNAL// for occasional debugging...//#pragma optimize("", off)//#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes")#endif+//-------------------------------------------------------------------------------------------------+/** LOGIC-THREAD.md phase 3, step 3b. The window repaint inside the overlap window asks the players+ * what to paint: the radar, the power bar, the general's rank bar, whether the player is still in.+ * The tick changes all of it beside the render, so the sync point takes it here and the painters+ * read this from inside the window. */+//-------------------------------------------------------------------------------------------------+namespace+{+ struct HudReads+ {+ Bool hasRadar; ///< the local player's+ Bool active; ///< the local player's+ Int rankProgress; ///< the local player's+ Int production; ///< the power shown: the observed player's, or the local one's+ Int consumption;+ };+ HudReads s_hudReads;++ Player *powerPlayer( void )+ {+ if( TheControlBar->isObserverControlBarOn() )+ return TheControlBar->getObserverLookAtPlayer();+ return ThePlayerList->getLocalPlayer();+ }+}++void W3DControlBar_takeReadsForRender( void )+{+ // no tick runs beside a render outside a match, and before the first one there is no local player+ if( !TheGameLogic->isInGame() )+ return;+ Player *local = ThePlayerList->getLocalPlayer();+ s_hudReads.hasRadar = local->hasRadar();+ s_hudReads.active = local->isPlayerActive();+ s_hudReads.rankProgress = local->getRankProgressPercent();+ const Player *shown = powerPlayer();+ s_hudReads.production = shown ? shown->getEnergy()->getProduction() : 0;+ s_hudReads.consumption = shown ? shown->getEnergy()->getConsumption() : 0;+}++static Bool hasRadarForDraw( const Player *player )+{+ return LogicThread::isInsideWindow() ? s_hudReads.hasRadar : player->hasRadar();+}++static Bool isActiveForDraw( const Player *player )+{+ return LogicThread::isInsideWindow() ? s_hudReads.active : player->isPlayerActive();+}++static void readPowerForDraw( const Player *player, Int &production, Int &consumption )+{+ if( LogicThread::isInsideWindow() )+ {+ production = s_hudReads.production;+ consumption = s_hudReads.consumption;+ return;+ }+ production = player->getEnergy()->getProduction();+ consumption = player->getEnergy()->getConsumption();+}+//-------------------------------------------------------------------------------------------------void W3DCameoMovieDraw( GameWindow *window, WinInstanceData *instData ){@@ -79,7 +142,7 @@ void W3DLeftHUDDraw( GameWindow *window, WinInstanceData *instData )TheDisplay->drawVideoBuffer( video, pos.x, pos.y, pos.x + size.x, pos.y + size.y );}- else if( TheRadar->isRadarForced() || ( TheRadar->isRadarHidden() == false && player->hasRadar() ) )+ else if( TheRadar->isRadarForced() || ( TheRadar->isRadarHidden() == false && hasRadarForDraw( player ) ) ){ICoord2D pos, size;//W3DGameWinDefaultDraw( window, instData );@@ -144,12 +207,8 @@ void W3DPowerDraw( GameWindow *window, WinInstanceData *instData )if(!player || !TheGlobalData)return;- Energy *energy = player->getEnergy();- if( energy == NULL )- return;-- Int consumption = energy->getConsumption();- Int production = energy->getProduction();+ Int consumption, production;+ readPowerForDraw( player, production, consumption );ICoord2D pos, size;window->winGetScreenPosition( &pos.x, &pos.y );@@ -158,7 +217,7 @@ void W3DPowerDraw( GameWindow *window, WinInstanceData *instData )static Real pixelsPerInterval = size.x / TheGlobalData->m_powerBarIntervals;Int delta = TheGlobalData->m_powerBarYellowRange;- if((consumption > energy->getProduction() - delta) && (consumption <= energy->getProduction()))+ if((consumption > production - delta) && (consumption <= production)){// 6 and 1 is Green, 6 and 2 is yellow, 6 and 6 is yellow//endBar = endBarYellow;@@ -311,12 +370,8 @@ void W3DPowerDrawA( GameWindow *window, WinInstanceData *instData )if(!player || !TheGlobalData)return;- Energy *energy = player->getEnergy();- if( energy == NULL )- return;-- Int consumption = energy->getConsumption();- Int production = energy->getProduction();+ Int consumption, production;+ readPowerForDraw( player, production, consumption );ICoord2D pos, size;window->winGetScreenPosition( &pos.x, &pos.y );@@ -325,7 +380,7 @@ void W3DPowerDrawA( GameWindow *window, WinInstanceData *instData )static Real pixelsPerInterval = size.x / TheGlobalData->m_powerBarIntervals;Int delta = TheGlobalData->m_powerBarYellowRange;- if((consumption > energy->getProduction() - delta) && (consumption <= energy->getProduction()))+ if((consumption > production - delta) && (consumption <= production)){// 6 and 1 is Green, 6 and 2 is yellow, 6 and 6 is yellowendBar = endBarYellow;@@ -494,12 +549,12 @@ void W3DCommandBarGridDraw( GameWindow *window, WinInstanceData *instData )void W3DCommandBarGenExpDraw( GameWindow *window, WinInstanceData *instData ){Player *player = ThePlayerList->getLocalPlayer();- if(!player->isPlayerActive())+ if(!isActiveForDraw( player ))return;static const Image *endBar = TheMappedImageCollection->findImageByName("GenExpBarTop1");static const Image *beginBar = TheMappedImageCollection->findImageByName("GenExpBarBottom1");static const Image *centerBar = TheMappedImageCollection->findImageByName("GenExpBar1");- const Int progress = player->getRankProgressPercent();+ const Int progress = LogicThread::isInsideWindow() ? s_hudReads.rankProgress : player->getRankProgressPercent();if(progress <= 0)return;@@ -611,7 +666,7 @@ void W3DCommandBarGenExpDraw( GameWindow *window, WinInstanceData *instData )void W3DCommandBarTopDraw( GameWindow *window, WinInstanceData *instData ){GameWindow *win = TheWindowManager->winGetWindowFromId(NULL, TheNameKeyGenerator->nameToKey("ControlBar.wnd:ButtonGeneral"));- if(!win || win->winIsHidden() || !ThePlayerList->getLocalPlayer()->isPlayerActive())+ if(!win || win->winIsHidden() || !isActiveForDraw( ThePlayerList->getLocalPlayer() ))return;// TheControlBar->drawTransitionHandler();diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cppindex bc05c550a..bd8e68819 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp@@ -88,6 +88,7 @@ static void drawFramerateBar(void);#include "GameClient/Line2D.h"#include "GameClient/Mouse.h"#include "GameClient/ObserverCamera.h"+#include "GameClient/CinemaDirector.h"#include "GameClient/GlobalLanguage.h"#include "GameClient/Water.h"@@ -2308,10 +2309,23 @@ static Bool rendersThisPass( void )stealth fades and fields, the toppling trees, and the strings the last pass's overlays freed, nowthat nothing recorded draws them. The scene's own reads of an object were taken byGameClient::update's drawable walk (Drawable::getObjectForDraw) and the radar's blips by its update. */+extern void W3DControlBar_takeReadsForRender( void );+static void takeReadsForRender( Bool renders ){TheDisplay->freeDeferred();TheGameLogic->takeFrameForDraw();+ // step 3b: what the tick handed over at the window's opening writes beside the render, the client's+ // clock, each drawable's look (after the views' update eased its fades) and the players the control+ // bar's painters ask+ TheGameClient->takeFrameForDraw();+ for( Drawable *draw = TheGameClient->firstDrawable(); draw; draw = draw->getNextDrawable() )+ {+ // flushes the conditions the client set; inside the window the scene's dirty walk is a no-op+ draw->getDrawModules();+ draw->takeLookForDraw();+ }+ W3DControlBar_takeReadsForRender();if( !renders || TheGlobalData->m_breakTheMovie || TheGlobalData->m_disableRender )return;for( View *view = TheDisplay->getFirstView(); view; view = TheDisplay->getNextView( view ) )@@ -2604,9 +2618,24 @@ AGAIN:#ifdef DEBUG_LOGGINGtOverlapStart = Clock_Ticks();#endif- // a draw from inside a tick (the load screen the map start paints) is the tick's own+ // a draw from inside a tick (the load screen the map start paints) is the tick's own. The+ // tick runs beside a render that reads logic only through the sync point's copies, which+ // rules out the scripted camera's loop of renders, the debug overlays and displays that walk+ // the objects live, -cinema's own interface, smooth motion's restore and the load screen.if( !TheGameLogic->isInGameLogicUpdate() )- overlapWindow.open();+ {+ Bool mayOverlap = !loopForCameraMovement && rendersThisPass() && !TheSmoothMotionActive+ && m_debugDisplayCallback == NULL && !TheGlobalData->m_loadScreenRender+ && !TheGlobalData->m_showLanes && !CinemaDirector_hidesHud()+ && TheObserverCamera.getDrawnPaneCount() <= 1;+#if defined(_DEBUG) || defined(_INTERNAL)+ mayOverlap = mayOverlap && !TheGlobalData->m_debugAI && !TheGlobalData->m_debugCamera+ && !TheGlobalData->m_showAudioLocations;+#else+ mayOverlap = mayOverlap && !TheGlobalData->m_debugAI;+#endif+ overlapWindow.open( mayOverlap );+ }// R1: after the particles read the logic bones (Lorenzen's note above), before anything renders.smoothMotionApply();@@ -2868,6 +2897,10 @@ AGAIN:// R1: the logic transforms back on every model, before picking (the message stream) and the logic.smoothMotionRestore();+ // LOGIC-THREAD.md phase 3, step 3b: the tick that ran beside the render hands the client its work here,+ // after the restore, so the transforms it gives the models are the ones they keep+ LogicThread::flushOverlap();+#ifdef EXTENDED_STATSif (DX8Wrapper::stats.m_disableOverhead) {goto AGAIN;diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainVisual.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainVisual.cppindex 0f0ed167a..7b3c5c446 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainVisual.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainVisual.cpp@@ -816,11 +816,13 @@ void W3DTerrainVisual::setRawMapHeight(const ICoord2D *gridPos, Int height)Int x = gridPos->x+m_logicHeightMap->getBorderSizeInline();Int y = gridPos->y+m_logicHeightMap->getBorderSizeInline();//if (m_logicHeightMap->getHeight(x,y) != height) //ML changed to prevent scissoring with roads- if (m_logicHeightMap->getHeight(x,y) > height)+ if (m_terrainRenderObject->getLogicRawHeight(x,y) > height){- // logic's own height, read back by getGroundHeight, so now; the drawn terrain after the tick- m_logicHeightMap->setRawHeight(x, y, height);+ // logic's own height, read back by getGroundHeight, so now; the drawn map after the tick, which+ // the render reads beside it (LOGIC-THREAD.md phase 3, LogicHeightMapData)+ m_terrainRenderObject->setLogicRawHeight(x, y, height);LogicThread::callAfterTick( [this, x, y, height]() {+ m_logicHeightMap->setRawHeight(x, y, height);/* This used to be staticLightingChanged(), which rebuilds and re-lights every drawnvertex on the map - 61 ms, measured, a visible stutter - because one cell moved. EAhad noticed: "OOH! this could benefit from the new Seismic update code". It gets a@@ -848,7 +850,7 @@ Int W3DTerrainVisual::getRawMapHeight(const ICoord2D *gridPos)Int x = gridPos->x+m_logicHeightMap->getBorderSizeInline();Int y = gridPos->y+m_logicHeightMap->getBorderSizeInline();//if (m_logicHeightMap->getHeight(x,y) != height) //ML changed to prevent scissoring with roads- return m_logicHeightMap->getHeight(x,y) ;+ return m_terrainRenderObject->getLogicRawHeight(x,y) ;}return 0;diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cppindex da4f079de..43d94ac76 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp@@ -2331,6 +2331,10 @@ static Real viewElapsedMS( const Int64 &from, const Int64 &to )//-------------------------------------------------------------------------------------------------void W3DView::recordPostDraw( void ){+ // a view filter draws the camera's locked object on its own, over the filtered scene (draw)+ const Object *cameraLockObj = getCameraLock() != INVALID_ID ? TheGameLogic->findObjectByID( getCameraLock() ) : NULL;+ m_cameraLockDrawForDraw = cameraLockObj ? cameraLockObj->getDrawable() : NULL;+Region3D axisAlignedRegion;getAxisAlignedViewRegion(axisAlignedRegion);@@ -2349,6 +2353,20 @@ void W3DView::recordPostDraw( void )#endif}+/* LOGIC-THREAD.md phase 3, step 3b: the locked drawable is left out of a filtered scene and drawn alone+ over it by hiding its render objects. It used to go through Drawable::setDrawableHidden, which writes+ a field the tick writes beside the render and deselected the unit for the frame; shown again, the+ render objects take the drawable's own look. */+static void hideLockedDrawable( Drawable *draw, Bool hide )+{+ for( DrawModule **dm = draw->getDrawModulesNonDirty(); *dm; ++dm )+ {+ ObjectDrawInterface *di = (*dm)->getObjectDrawInterface();+ if( di )+ di->setHidden( hide );+ }+}+void W3DView::draw( void ){USE_PERF_TIMER(W3DView_drawView)@@ -2363,15 +2381,8 @@ void W3DView::draw( void ){// Most likely will redirect rendering to a texture.preRenderResult=W3DShaderManager::filterPreRender(m_viewFilter, skipRender, customScenePassMode);- if (!skipRender && getCameraLock())- {- Object* cameraLockObj = TheGameLogic->findObjectByID(getCameraLock());- if (cameraLockObj)- {- Drawable *drawable = cameraLockObj->getDrawable();- drawable->setDrawableHidden(true);- }- }+ if (!skipRender && m_cameraLockDrawForDraw)+ hideLockedDrawable( m_cameraLockDrawForDraw, TRUE );}if (!skipRender)@@ -2412,13 +2423,11 @@ void W3DView::draw( void )(Int)m_viewFilter, (Int)m_viewFilterMode));}}- if (!skipRender && getCameraLock())+ if (!skipRender && m_cameraLockDrawForDraw){- Object* cameraLockObj = TheGameLogic->findObjectByID(getCameraLock());- if (cameraLockObj){- Drawable *drawable = cameraLockObj->getDrawable();- drawable->setDrawableHidden(false);+ Drawable *drawable = m_cameraLockDrawForDraw;+ hideLockedDrawable( drawable, drawable->isDrawableEffectivelyHidden() );RenderInfoClass rinfo(*m_3DCamera);// Apply the camera and viewport (including depth range)m_3DCamera->Apply();