Skip to content

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

perf(gameclient): batch the 2D draws and time the frame in parts

Olcay Seygan698436442f46
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/Debug.h b/GeneralsMD/Code/GameEngine/Include/Common/Debug.h
index b33806d10..708817af5 100644
--- a/GeneralsMD/Code/GameEngine/Include/Common/Debug.h
+++ b/GeneralsMD/Code/GameEngine/Include/Common/Debug.h
@@ -120,9 +120,17 @@ class AsciiString;
DEBUG_FLAG_LOG_TO_FILE = 0x01,
DEBUG_FLAG_LOG_TO_CONSOLE = 0x02,
DEBUG_FLAG_PREPEND_TIME = 0x04,
-#ifdef _INTERNAL
+#if defined(_INTERNAL) || defined(RELEASE_DEBUG_LOGGING)
+ //
// by default, _INTERNAL builds log to file, but not to console, in the interest
// of speed. want console output? just change this line:
+ //
+ // A release build that logs is here for the same reason and pays the same price twice over:
+ // the console side is OutputDebugString, which takes a system-wide lock and crosses into the
+ // kernel on every line, whether or not anything is listening. A frame that logs a few
+ // hundred lines - one per object, which the battle plan code does - then spends more time in
+ // that call than in the work the frame was for. The file is what anybody reads afterwards.
+ //
DEBUG_FLAGS_DEFAULT = (DEBUG_FLAG_LOG_TO_FILE)
#else
DEBUG_FLAGS_DEFAULT = (DEBUG_FLAG_LOG_TO_FILE | DEBUG_FLAG_LOG_TO_CONSOLE)
@@ -159,6 +167,19 @@ class AsciiString;
#endif
+//
+// A line written once per object, or once per drawable per frame, is a development trace: useful
+// with a debugger attached, and in a release build nothing but cost - every line is a flush to
+// disk, and a frame that writes a few hundred of them is a frame the player feels. DEBUG_LOG_DEV
+// says "this one is a trace": it stays in a debug or internal build and disappears from the release
+// build that logs. Anything a player's log has to be able to answer stays on plain DEBUG_LOG.
+//
+#if defined(DEBUG_LOGGING) && (defined(_DEBUG) || defined(_INTERNAL))
+ #define DEBUG_LOG_DEV(m) do { { DebugLog m ; } } while (0)
+#else
+ #define DEBUG_LOG_DEV(m) ((void)0)
+#endif
+
#ifdef DEBUG_CRASHING
DEBUG_EXTERN_C void DebugCrash(const char *format, ...);
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/GameEngine.h b/GeneralsMD/Code/GameEngine/Include/Common/GameEngine.h
index 68a29ebba..27f85eaf1 100644
--- a/GeneralsMD/Code/GameEngine/Include/Common/GameEngine.h
+++ b/GeneralsMD/Code/GameEngine/Include/Common/GameEngine.h
@@ -36,12 +36,20 @@
#define DEFAULT_MAX_FPS 45
-/** How many logic frames of wall-clock debt the pacer will carry and pay back. A render pass
- slower than one logic frame owes the simulation more than one tick; without a catch-up the
- game speed just becomes the render speed. The cap is the anti-spiral: when the logic frame
- itself is what overran, the debt past this many frames is dropped and the match runs slow.
- See GameEngine_isLogicFrameDue in GameEngine.cpp. */
-#define LOGIC_CATCHUP_MAX_FRAMES 3
+/** How much wall-clock debt the pacer will carry and pay back. A render pass slower than one
+ logic frame owes the simulation more than one tick; without a catch-up the game speed just
+ becomes the render speed. The cap is the anti-spiral: when the logic frame itself is what
+ overran, the debt past this much is dropped and the match runs slow.
+
+ It is a duration, not a frame count, because the frame count that duration buys depends on the
+ game speed. Three frames - the number this used to be - is a tenth of a second at the retail
+ 30fps and half that at 60, so picking a faster game speed made the pacer give up on a slow
+ render twice as early: at 60fps a match visibly ran in slow motion the moment the frame rate
+ dropped under 20. See GameEngine_isLogicFrameDue in GameEngine.cpp. */
+#define LOGIC_CATCHUP_MAX_MS 100.0f
+
+/** The above in logic frames, at a given game speed: 3 at the retail 30fps, 6 at 60. */
+Int GameEngine_logicCatchupMaxFrames( Int logicFps );
// forward declarations
class AudioManager;
diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/Display.h b/GeneralsMD/Code/GameEngine/Include/GameClient/Display.h
index 6ebcb0cb6..1f337079b 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameClient/Display.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/Display.h
@@ -148,9 +148,24 @@ public:
Int endX, Int endY, Color color = 0xFFFFFFFF, DrawImageMode mode=DRAW_IMAGE_ALPHA) = 0;
/// draw a video buffer fit within the screen coordinates
- virtual void drawVideoBuffer( VideoBuffer *buffer, Int startX, Int startY,
+ virtual void drawVideoBuffer( VideoBuffer *buffer, Int startX, Int startY,
Int endX, Int endY ) = 0;
+ /** Every 2D call above is its own draw call at the device: it sets the renderer up, hands it one
+ * quad and draws it. For a handful of pieces that is nothing; for a strip of cameos with a
+ * tray, a scrim and a border each it is hundreds of draw calls a frame, which the driver
+ * charges for one at a time. Between beginBatch2D() and endBatch2D() a run of calls that
+ * wants the same state - the same image, or none - is gathered and drawn once. The order
+ * everything is drawn in is untouched: a call that needs different state draws what is waiting
+ * first. Displays that do not batch simply draw as they always did. */
+ virtual void beginBatch2D( void ) { }
+ virtual void endBatch2D( void ) { }
+
+ /** Draw whatever a batch is holding, now. Anything that puts pixels on the screen without going
+ * through the calls above - text, which draws through its own renderer - has to call this
+ * first, or the batch it did not join lands on top of it when it is finally drawn. */
+ virtual void flushBatch2D( void ) { }
+
/// FullScreen video playback
virtual void playLogoMovie( AsciiString movieName, Int minMovieLength, Int minCopyrightLength );
virtual void playMovie( AsciiString movieName );
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp
index e383c59b8..48f8b65bb 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp
@@ -997,12 +997,20 @@ DECLARE_PERF_TIMER(GameEngine_update)
*
* Free function (not a member, not static) so test_gameengine can link straight to it.
*/
+Int GameEngine_logicCatchupMaxFrames( Int logicFps )
+{
+ if (logicFps <= 0)
+ return 1;
+ const Int frames = (Int)(logicFps * LOGIC_CATCHUP_MAX_MS / 1000.0f + 0.5f);
+ return frames < 1 ? 1 : frames;
+}
+
Bool GameEngine_isLogicFrameDue( Real& accumMs, Real elapsedMs, Int logicFps )
{
if (logicFps <= 0)
return TRUE;
const Real msPerLogicFrame = 1000.0f / logicFps;
- const Real maxAccumMs = msPerLogicFrame * LOGIC_CATCHUP_MAX_FRAMES;
+ const Real maxAccumMs = msPerLogicFrame * GameEngine_logicCatchupMaxFrames(logicFps);
if (elapsedMs > maxAccumMs)
elapsedMs = maxAccumMs;
accumMs += elapsedMs;
@@ -1027,6 +1035,14 @@ Bool GameEngine_isLogicFrameDue( Real& accumMs, Real elapsedMs, Int logicFps )
// half of the loop. So time both halves of every pass and, once a second, say what the rate was and
// where the time went - but only when the rate actually dropped, so a smooth match logs nothing.
//
+extern Real TheClientDrawMS; ///< GameClient.cpp: how long the last TheDisplay->DRAW() took
+extern Real TheSceneDrawMS; ///< ...of which the 3D world
+extern Real TheUIDrawMS; ///< ...and the interface over it
+extern Real TheUIPostDrawMS; ///< ...of which the overlays and the HUD strips
+extern Real TheWindowRepaintMS; ///< ...and the window system's repaint
+extern Real TheStripGatherMS; ///< ...of the overlays, the production strip's sweep
+extern Real TheStripDrawMS; ///< ...and the production strip's own drawing
+
static Real engineElapsedMS( const Int64 &from, const Int64 &to )
{
Int64 freq;
@@ -1159,22 +1175,33 @@ void GameEngine::update( void )
static Real fpsLogicTotal = 0.0f, fpsLogicMax = 0.0f;
static Int fpsLogicTicks = 0, fpsCatchupPasses = 0;
static DWORD fpsWindowStart = timeGetTime();
- Int64 tClientStart, tClientEnd, tLogicStart, tLogicEnd;
- Real clientMS = 0.0f, logicMS = 0.0f;
+ static Real fpsRadarTotal = 0.0f, fpsAudioTotal = 0.0f, fpsDrawTotal = 0.0f, fpsDrawMax = 0.0f;
+ static Real fpsSceneTotal = 0.0f, fpsUITotal = 0.0f, fpsPostTotal = 0.0f, fpsWinTotal = 0.0f;
+ static Real fpsStripGatherTotal = 0.0f, fpsStripDrawTotal = 0.0f;
+ Int64 tClientStart, tClientEnd, tLogicStart, tLogicEnd, tRadarEnd, tAudioEnd;
+ Real clientMS = 0.0f, logicMS = 0.0f, radarMS = 0.0f, audioMS = 0.0f;
Int logicTicks = 0;
+ TheClientDrawMS = TheSceneDrawMS = TheUIDrawMS = TheUIPostDrawMS = TheWindowRepaintMS = 0.0f;
+ TheStripGatherMS = TheStripDrawMS = 0.0f;
QueryPerformanceCounter( (LARGE_INTEGER *)&tClientStart );
#endif
{
-
+
// VERIFY CRC needs to be in this code block. Please to not pull TheGameLogic->update() inside this block.
VERIFY_CRC
TheRadar->UPDATE();
+#ifdef DEBUG_LOGGING
+ QueryPerformanceCounter( (LARGE_INTEGER *)&tRadarEnd );
+#endif
/// @todo Move audio init, update, etc, into GameClient update
-
+
TheAudio->UPDATE();
+#ifdef DEBUG_LOGGING
+ QueryPerformanceCounter( (LARGE_INTEGER *)&tAudioEnd );
+#endif
TheGameClient->UPDATE();
TheMessageStream->propagateMessages();
@@ -1182,12 +1209,14 @@ void GameEngine::update( void )
{
TheNetwork->UPDATE();
}
-
+
TheCDManager->UPDATE();
}
#ifdef DEBUG_LOGGING
QueryPerformanceCounter( (LARGE_INTEGER *)&tClientEnd );
clientMS = engineElapsedMS( tClientStart, tClientEnd );
+ radarMS = engineElapsedMS( tClientStart, tRadarEnd );
+ audioMS = engineElapsedMS( tRadarEnd, tAudioEnd );
#endif
@@ -1258,12 +1287,13 @@ void GameEngine::update( void )
// count and the pacer's own accumulator cap stop at LOGIC_CATCHUP_MAX_FRAMES, so a logic
// frame that is itself over budget cannot pull the loop into a spiral.
Int logicTicksThisPass = 0;
+ const Int maxTicksThisPass = GameEngine_logicCatchupMaxFrames(m_maxFPS);
do
{
TheGameLogic->UPDATE();
++logicTicksThisPass;
}
- while (mayCatchUp && logicTicksThisPass < LOGIC_CATCHUP_MAX_FRAMES &&
+ while (mayCatchUp && logicTicksThisPass < maxTicksThisPass &&
GameEngine_isLogicFrameDue(logicAccumMs, 0.0f, m_maxFPS));
#ifdef DEBUG_LOGGING
QueryPerformanceCounter( (LARGE_INTEGER *)&tLogicEnd );
@@ -1277,6 +1307,16 @@ void GameEngine::update( void )
#ifdef DEBUG_LOGGING
fpsFrames++;
fpsClientTotal += clientMS;
+ fpsRadarTotal += radarMS;
+ fpsAudioTotal += audioMS;
+ fpsDrawTotal += TheClientDrawMS;
+ fpsSceneTotal += TheSceneDrawMS;
+ fpsUITotal += TheUIDrawMS;
+ fpsPostTotal += TheUIPostDrawMS;
+ fpsWinTotal += TheWindowRepaintMS;
+ fpsStripGatherTotal += TheStripGatherMS;
+ fpsStripDrawTotal += TheStripDrawMS;
+ if( TheClientDrawMS > fpsDrawMax ) fpsDrawMax = TheClientDrawMS;
fpsLogicTotal += logicMS;
fpsLogicTicks += logicTicks;
if( logicTicks > 1 ) fpsCatchupPasses++;
@@ -1293,17 +1333,28 @@ void GameEngine::update( void )
// 'hz' is the rate the simulation actually achieved and 'catchup' how many render
// frames were dropped to hold it there; hz short of m_maxFPS with catchup passes
// present is the logic side being genuinely over budget, not the pacer.
- DEBUG_LOG(("FPS %.0f over %dms (%d frames, %d hz, %d catchup, logic frame %d) | client avg %.1f max %.1f | logic avg %.1f max %.1f | unaccounted %.1fms\n",
+ DEBUG_LOG(("FPS %.0f over %dms (%d frames, %d hz, %d catchup, logic frame %d) | client avg %.1f max %.1f (render avg %.1f max %.1f [scene %.1f, ui %.1f (post %.1f [strip gather %.1f, draw %.1f], win %.1f), present %.1f], radar %.1f, audio %.1f, rest %.1f) | logic avg %.1f max %.1f | unaccounted %.1fms\n",
fps, (Int)windowMS, fpsFrames,
(Int)((Real)fpsLogicTicks * 1000.0f / (Real)windowMS + 0.5f), fpsCatchupPasses,
TheGameLogic->getFrame(),
fpsClientTotal / fpsFrames, fpsClientMax,
+ fpsDrawTotal / fpsFrames, fpsDrawMax,
+ fpsSceneTotal / fpsFrames, fpsUITotal / fpsFrames,
+ fpsPostTotal / fpsFrames,
+ fpsStripGatherTotal / fpsFrames, fpsStripDrawTotal / fpsFrames,
+ fpsWinTotal / fpsFrames,
+ ( fpsDrawTotal - fpsSceneTotal - fpsUITotal ) / fpsFrames,
+ fpsRadarTotal / fpsFrames, fpsAudioTotal / fpsFrames,
+ ( fpsClientTotal - fpsDrawTotal - fpsRadarTotal - fpsAudioTotal ) / fpsFrames,
fpsLogicTotal / fpsFrames, fpsLogicMax,
(Real)windowMS - fpsClientTotal - fpsLogicTotal));
}
fpsFrames = 0;
fpsLogicTicks = fpsCatchupPasses = 0;
fpsClientTotal = fpsLogicTotal = 0.0f;
+ fpsRadarTotal = fpsAudioTotal = fpsDrawTotal = fpsDrawMax = 0.0f;
+ fpsSceneTotal = fpsUITotal = fpsPostTotal = fpsWinTotal = 0.0f;
+ fpsStripGatherTotal = fpsStripDrawTotal = 0.0f;
fpsClientMax = fpsLogicMax = 0.0f;
fpsWindowStart = nowMS;
}
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp
index c1238d825..edd05882d 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp
@@ -191,7 +191,7 @@ void dumpBattlePlanBonuses(const BattlePlanBonuses *b, AsciiString name, const P
kindofMaskAsAsciiString(b->m_invalidKindOf).str()));
if (!doDebugLog)
return;
- DEBUG_LOG(("dumpBattlePlanBonuses() %s:%d %s\n Player %d(%ls) object %d(%s) armor:%g/%8.8X bombardment:%d, holdTheLine:%d, searchAndDestroy:%d sight:%g/%8.8X, valid:%s invalid:%s\n",
+ DEBUG_LOG_DEV(("dumpBattlePlanBonuses() %s:%d %s\n Player %d(%ls) object %d(%s) armor:%g/%8.8X bombardment:%d, holdTheLine:%d, searchAndDestroy:%d sight:%g/%8.8X, valid:%s invalid:%s\n",
fname.str(), line, name.str(),
(p)?p->getPlayerIndex():-1, (p)?((Player *)p)->getPlayerDisplayName().str():L"<No Name>", (o)?o->getID():-1, (o)?o->getTemplate()->getName().str():"<No Name>",
b->m_armorScalar, AS_INT(b->m_armorScalar),
@@ -3602,7 +3602,7 @@ static void localApplyBattlePlanBonusesToObject( Object *obj, void *userData )
Object *objectToValidate = obj;
Object *objectToModify = obj;
- DEBUG_LOG(("localApplyBattlePlanBonusesToObject() - looking at object %d (%s)\n",
+ DEBUG_LOG_DEV(("localApplyBattlePlanBonusesToObject() - looking at object %d (%s)\n",
(objectToValidate)?objectToValidate->getID():INVALID_ID,
(objectToValidate)?objectToValidate->getTemplate()->getName().str():"<No Object>"));
@@ -3612,20 +3612,20 @@ static void localApplyBattlePlanBonusesToObject( Object *obj, void *userData )
if( isProjectile )
{
objectToValidate = TheGameLogic->findObjectByID( obj->getProducerID() );
- DEBUG_LOG(("Object is a projectile - looking at object %d (%s) instead\n",
+ DEBUG_LOG_DEV(("Object is a projectile - looking at object %d (%s) instead\n",
(objectToValidate)?objectToValidate->getID():INVALID_ID,
(objectToValidate)?objectToValidate->getTemplate()->getName().str():"<No Object>"));
}
if( objectToValidate && objectToValidate->isAnyKindOf( bonus->m_validKindOf ) )
{
- DEBUG_LOG(("Is valid kindof\n"));
+ DEBUG_LOG_DEV(("Is valid kindof\n"));
if( !objectToValidate->isAnyKindOf( bonus->m_invalidKindOf ) )
{
- DEBUG_LOG(("Is not invalid kindof\n"));
+ DEBUG_LOG_DEV(("Is not invalid kindof\n"));
//Quite the trek eh? Now we can apply the bonuses!
if( !isProjectile )
{
- DEBUG_LOG(("Is not projectile. Armor scalar is %g\n", bonus->m_armorScalar));
+ DEBUG_LOG_DEV(("Is not projectile. Armor scalar is %g\n", bonus->m_armorScalar));
//Really important to not apply certain bonuses like health augmentation to projectiles!
if( bonus->m_armorScalar != 1.0f )
{
@@ -3635,7 +3635,7 @@ static void localApplyBattlePlanBonusesToObject( Object *obj, void *userData )
bonus->m_armorScalar, AS_INT(bonus->m_armorScalar), objectToModify->getID(),
objectToModify->getTemplate()->getDisplayName().str(),
objectToModify->getControllingPlayer()->getPlayerIndex()));
- DEBUG_LOG(("After apply, armor scalar is %g\n", body->getDamageScalar()));
+ DEBUG_LOG_DEV(("After apply, armor scalar is %g\n", body->getDamageScalar()));
}
if( bonus->m_sightRangeScalar != 1.0f )
{
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GameClient.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GameClient.cpp
index d334ea28c..9c3ca43f6 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GameClient.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GameClient.cpp
@@ -94,6 +94,32 @@
/// The GameClient singleton instance
GameClient *TheGameClient = NULL;
+#ifdef DEBUG_LOGGING
+//
+// How long the last TheDisplay->DRAW() took. The engine's frame rate watchdog reports the client
+// half of the loop as one number, and that number is two very different things added together: the
+// renderer, and everything the client does around it (the window system, the drawables, the UI).
+// Splitting the render out is what says which of the two a slow frame is.
+//
+Real TheClientDrawMS = 0.0f;
+//
+// And the same question one level down, because the renderer's own time is three very different
+// things: the 3D scene, the interface drawn over it, and the window system underneath that.
+// W3DDisplay and W3DInGameUI fill these in; the watchdog prints them.
+//
+Real TheSceneDrawMS = 0.0f; ///< W3DDisplay::drawViews() - the world
+Real TheUIDrawMS = 0.0f; ///< TheInGameUI->DRAW() - everything over the world
+Real TheUIPostDrawMS = 0.0f; ///< InGameUI::postDraw() - the strips and the world overlays
+Real TheWindowRepaintMS = 0.0f; ///< TheWindowManager->winRepaint() - the control bar and dialogs
+//
+// postDraw is mostly the production strip, and the strip is two halves that fail for different
+// reasons: the sweep that reads every player's queues, and the 2D draw that puts the rows on the
+// screen. A sweep that costs is a data problem; a draw that costs is a batching problem.
+//
+Real TheStripGatherMS = 0.0f; ///< InGameUI::drawProductionStrip() - reading the queues
+Real TheStripDrawMS = 0.0f; ///< InGameUI::drawProductionStrip() - drawing the rows
+#endif
+
//-------------------------------------------------------------------------------------------------
/** Fog and shroud hide a drawable from the local player, with one exception: a structure the player
* has just planned. It clears no shroud of its own, so a base planned out into fog would otherwise
@@ -793,15 +819,28 @@ void GameClient::update( void )
{
USE_PERF_TIMER(GameClient_draw)
-
+
// redraw all views, update the GUI
//if(TheGameLogic->getFrame() >= 2)
-
+
/* -headless never draws. The device and every drawable stay alive - this skips the frame,
not the client - which is what makes an unattended run fast: rendering is the larger half
of the loop's wall clock in a normal match. */
if (!TheGlobalData->m_headless)
+ {
+#ifdef DEBUG_LOGGING
+ Int64 drawStart, drawEnd;
+ QueryPerformanceCounter( (LARGE_INTEGER *)&drawStart );
+#endif
TheDisplay->DRAW();
+#ifdef DEBUG_LOGGING
+ QueryPerformanceCounter( (LARGE_INTEGER *)&drawEnd );
+ Int64 freq;
+ QueryPerformanceFrequency( (LARGE_INTEGER *)&freq );
+ if( freq > 0 )
+ TheClientDrawMS = (Real)((double)(drawEnd - drawStart) * 1000.0 / (double)freq);
+#endif
+ }
}
{
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGuard.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGuard.cpp
index a2b1fb8c2..d3937eda0 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGuard.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGuard.cpp
@@ -394,7 +394,7 @@ StateReturnType AIGuardInnerState::onEnter( void )
Object* nemesis = TheGameLogic->findObjectByID(getGuardMachine()->getNemesisID()) ;
if (nemesis == NULL)
{
- DEBUG_LOG(("Unexpected NULL nemesis in AIGuardInnerState.\n"));
+ DEBUG_LOG_DEV(("Unexpected NULL nemesis in AIGuardInnerState.\n"));
return STATE_SUCCESS;
}
m_enterState = newInstance(AIEnterState)(getMachine());
@@ -414,7 +414,7 @@ StateReturnType AIGuardInnerState::onEnter( void )
Object* nemesis = TheGameLogic->findObjectByID(getGuardMachine()->getNemesisID()) ;
if (nemesis == NULL)
{
- DEBUG_LOG(("Unexpected NULL nemesis in AIGuardInnerState.\n"));
+ DEBUG_LOG_DEV(("Unexpected NULL nemesis in AIGuardInnerState.\n"));
return STATE_SUCCESS;
}
m_exitConditions.m_center = pos;
@@ -527,7 +527,7 @@ StateReturnType AIGuardOuterState::onEnter( void )
Object* nemesis = TheGameLogic->findObjectByID(getGuardMachine()->getNemesisID()) ;
if (nemesis == NULL)
{
- DEBUG_LOG(("Unexpected NULL nemesis in AIGuardInnerState.\n"));
+ DEBUG_LOG_DEV(("Unexpected NULL nemesis in AIGuardInnerState.\n"));
return STATE_SUCCESS;
}
Object *obj = getMachineOwner();
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp
index 4b6428d30..2a5c790e2 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp
@@ -3747,31 +3747,86 @@ static NameKeyType theWorstModuleKey = NAMEKEY_INVALID;
static const ThingTemplate *theWorstModuleThing = NULL;
static Int theModuleUpdateCount = 0;
+//
+// The worst single module names a hitch, not a cost: a frame where two thousand modules each take
+// a little is exactly as slow and has no worst. So the sweep is also totalled by kind of module,
+// which is what says whether the frame went on AI, on weapons, or on something nobody suspects.
+// A linear scan over the kinds seen so far - there are a few dozen, not thousands - is cheaper
+// than a map and does not allocate inside the frame.
+//
+enum { MODULE_PROFILE_MAX = 96 };
+static NameKeyType theModuleKindKey[ MODULE_PROFILE_MAX ];
+static Int64 theModuleKindTicks[ MODULE_PROFILE_MAX ];
+static Int theModuleKindCount[ MODULE_PROFILE_MAX ];
+static Int theModuleKindsUsed = 0;
+
static void resetModuleProfile( void )
{
theWorstModuleTicks = 0;
theWorstModuleKey = NAMEKEY_INVALID;
theWorstModuleThing = NULL;
theModuleUpdateCount = 0;
+ theModuleKindsUsed = 0;
+}
+
+static void addModuleProfile( NameKeyType key, Int64 ticks )
+{
+ for( Int at = 0; at < theModuleKindsUsed; at++ )
+ {
+ if( theModuleKindKey[ at ] == key )
+ {
+ theModuleKindTicks[ at ] += ticks;
+ theModuleKindCount[ at ]++;
+ return;
+ }
+ }
+
+ if( theModuleKindsUsed >= MODULE_PROFILE_MAX )
+ return; // more kinds than the table holds: the top three are in it already
+
+ theModuleKindKey[ theModuleKindsUsed ] = key;
+ theModuleKindTicks[ theModuleKindsUsed ] = ticks;
+ theModuleKindCount[ theModuleKindsUsed ] = 1;
+ theModuleKindsUsed++;
}
static const char *getModuleProfileReport( void )
{
- static char report[ 256 ];
+ static char report[ 512 ];
+ Int64 freq = 0;
+ QueryPerformanceFrequency( (LARGE_INTEGER *)&freq );
+
if( theWorstModuleKey == NAMEKEY_INVALID )
{
sprintf( report, "%d updates", theModuleUpdateCount );
+ return report;
}
- else
+
+ const Real worstMS = freq ? (Real)( (double)theWorstModuleTicks * 1000.0 / (double)freq ) : 0.0f;
+ Int used = sprintf( report, "%d updates, worst %s on %s %.1fms", theModuleUpdateCount,
+ TheNameKeyGenerator->keyToName( theWorstModuleKey ).str(),
+ theWorstModuleThing ? theWorstModuleThing->getName().str() : "<none>",
+ worstMS );
+
+ // and the three kinds of module the sweep spent the most time in, whatever the worst one was
+ for( Int rank = 0; rank < 3; rank++ )
{
- Int64 freq = 0;
- QueryPerformanceFrequency( (LARGE_INTEGER *)&freq );
- const Real worstMS = freq ? (Real)( (double)theWorstModuleTicks * 1000.0 / (double)freq ) : 0.0f;
- sprintf( report, "%d updates, worst %s on %s %.1fms", theModuleUpdateCount,
- TheNameKeyGenerator->keyToName( theWorstModuleKey ).str(),
- theWorstModuleThing ? theWorstModuleThing->getName().str() : "<none>",
- worstMS );
+ Int best = -1;
+ for( Int at = 0; at < theModuleKindsUsed; at++ )
+ if( theModuleKindTicks[ at ] >= 0 && ( best < 0 || theModuleKindTicks[ at ] > theModuleKindTicks[ best ] ) )
+ best = at;
+
+ if( best < 0 )
+ break;
+
+ const Real ms = freq ? (Real)( (double)theModuleKindTicks[ best ] * 1000.0 / (double)freq ) : 0.0f;
+ used += sprintf( report + used, " | %s %dx/%.1f",
+ TheNameKeyGenerator->keyToName( theModuleKindKey[ best ] ).str(),
+ theModuleKindCount[ best ], ms );
+
+ theModuleKindTicks[ best ] = -1; // taken; the next pass finds the next one down
}
+
return report;
}
#endif
@@ -3988,6 +4043,7 @@ void GameLogic::update( void )
QueryPerformanceCounter( (LARGE_INTEGER *)&profModuleEnd );
theModuleUpdateCount++;
const Int64 profModuleTicks = profModuleEnd - profModuleStart;
+ addModuleProfile( profModuleKey, profModuleTicks );
if( profModuleTicks > theWorstModuleTicks )
{
theWorstModuleTicks = profModuleTicks;
diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DDisplay.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DDisplay.h
index a0df6bc1c..e8667fb01 100644
--- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DDisplay.h
+++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DDisplay.h
@@ -116,9 +116,14 @@ public:
Int endX, Int endY, Color color = 0xFFFFFFFF, DrawImageMode mode=DRAW_IMAGE_ALPHA);
/// draw a video buffer fit within the screen coordinates
- virtual void drawVideoBuffer( VideoBuffer *buffer, Int startX, Int startY,
+ virtual void drawVideoBuffer( VideoBuffer *buffer, Int startX, Int startY,
Int endX, Int endY );
+ /// gather the 2D calls made until endBatch2D() into as few draw calls as their state allows
+ virtual void beginBatch2D( void );
+ virtual void endBatch2D( void );
+ virtual void flushBatch2D( void );
+
virtual VideoBuffer* createVideoBuffer( void ) ; ///< Create a video buffer that can be used for this display
virtual void takeScreenShot(void); //save screenshot to file
@@ -164,6 +169,22 @@ protected:
Byte m_initialized; ///< TRUE when system is initialized
LightClass *m_myLight[LightEnvironmentClass::MAX_LIGHTS]; ///< light hack for now
Render2DClass *m_2DRender; ///< interface for common 2D functions
+
+ //
+ // The 2D batch (see beginBatch2D). m_2DRender is the one renderer every 2D call goes through,
+ // so a batch is nothing more than not drawing it until something needs it drawn: the state the
+ // waiting geometry was set up for is kept here and the next call either matches it and adds to
+ // it, or draws it first.
+ //
+ Bool m_batch2D; ///< between beginBatch2D() and endBatch2D()
+ Bool m_batch2DOpen; ///< m_2DRender holds geometry nobody has drawn yet
+ Bool m_batch2DKeepOpen; ///< that geometry's state is one another call can share
+ const Image *m_batch2DImage; ///< the image it is drawn with, NULL for the untextured calls
+
+ Bool setup2D( const Image *image, Bool batchable ); ///< set the renderer up, unless what is waiting can take this call
+ void finish2D( void ); ///< draw what was added, unless a batch may still add to it
+ void flush2D( void ); ///< draw whatever is waiting, now
+
IRegion2D m_clipRegion; ///< the clipping region for images
Bool m_isClippedEnabled; ///<used by 2D drawing operations to define clip re
Real m_averageFPS; ///<average fps over the last 30 frames.
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DDependencyModelDraw.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DDependencyModelDraw.cpp
index 1b9f4fe94..7c5245df5 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DDependencyModelDraw.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DDependencyModelDraw.cpp
@@ -150,7 +150,7 @@ void W3DDependencyModelDraw::adjustTransformMtx(Matrix3D& mtx) const
else
{
mtx = *theirDrawable->getTransformMatrix();//TransformMatrix();
- DEBUG_LOG(("m_attachToDrawableBoneInContainer %s not found\n",getW3DDependencyModelDrawModuleData()->m_attachToDrawableBoneInContainer.str()));
+ DEBUG_LOG_DEV(("m_attachToDrawableBoneInContainer %s not found\n",getW3DDependencyModelDrawModuleData()->m_attachToDrawableBoneInContainer.str()));
}
}
}
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp
index a0915a2b3..ceba17894 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp
@@ -407,6 +407,10 @@ W3DDisplay::W3DDisplay()
for (i=0; i<LightEnvironmentClass::MAX_LIGHTS; i++)
m_myLight[i] = NULL;
m_2DRender = NULL;
+ m_batch2D = FALSE;
+ m_batch2DOpen = FALSE;
+ m_batch2DKeepOpen = FALSE;
+ m_batch2DImage = NULL;
m_isClippedEnabled = FALSE;
m_clipRegion.lo.x = 0;
m_clipRegion.lo.y = 0;
@@ -1685,6 +1689,25 @@ Int W3DDisplay::getLastFrameDrawCalls()
static Bool s_screenShotPending = FALSE; // F12 pressed: save the frame at the end of the next draw()
static void saveScreenShot(void);
+#ifdef DEBUG_LOGGING
+//
+// The frame rate watchdog in GameEngine.cpp reports the renderer as one number. These split it:
+// the world, and the interface drawn on top of it. A slow frame is one or the other and they have
+// nothing to do with each other.
+//
+extern Real TheSceneDrawMS;
+extern Real TheUIDrawMS;
+
+static Real w3dElapsedMS( const Int64 &from, const Int64 &to )
+{
+ Int64 freq;
+ QueryPerformanceFrequency( (LARGE_INTEGER *)&freq );
+ if( freq < 1 )
+ return 0.0f;
+ return (Real)((double)(to - from) * 1000.0 / (double)freq);
+}
+#endif
+
void W3DDisplay::draw( void )
{
//USE_PERF_TIMER(W3DDisplay_draw)
@@ -1953,10 +1976,22 @@ AGAIN:
Debug_Statistics::Record_DX8_Polys_And_Vertices(numRenderTargetPolygons,numRenderTargetVertices,ShaderClass::_PresetOpaqueShader);
// draw all views of the world
+#ifdef DEBUG_LOGGING
+ Int64 tSceneStart, tSceneEnd, tUIEnd;
+ QueryPerformanceCounter( (LARGE_INTEGER *)&tSceneStart );
+#endif
drawViews();
+#ifdef DEBUG_LOGGING
+ QueryPerformanceCounter( (LARGE_INTEGER *)&tSceneEnd );
+#endif
// draw the user interface
TheInGameUI->DRAW();
+#ifdef DEBUG_LOGGING
+ QueryPerformanceCounter( (LARGE_INTEGER *)&tUIEnd );
+ TheSceneDrawMS = w3dElapsedMS( tSceneStart, tSceneEnd );
+ TheUIDrawMS = w3dElapsedMS( tSceneEnd, tUIEnd );
+#endif
// end of video example code
@@ -2249,21 +2284,101 @@ void W3DDisplay::setTimeOfDay( TimeOfDay tod )
}
}
+// W3DDisplay::setup2D ========================================================
+/** Get the 2D renderer ready for the geometry a drawing call is about to add. Returns TRUE when
+ * the renderer was emptied for it and the caller has to set its state up - the texture it wants,
+ * or none - and FALSE when a batch is already open in exactly that state and the call may simply
+ * add to it. Whatever was waiting in a state this call cannot share is drawn first, so nothing
+ * ever changes the order things appear in. */
+//=============================================================================
+Bool W3DDisplay::setup2D( const Image *image, Bool batchable )
+{
+
+ if( m_batch2D && batchable && m_batch2DOpen && m_batch2DKeepOpen && m_batch2DImage == image )
+ return FALSE; // what is waiting was set up for exactly this: add to it
+
+ flush2D();
+
+ m_batch2DImage = image;
+ m_batch2DKeepOpen = batchable;
+ m_batch2DOpen = TRUE;
+ m_2DRender->Reset();
+ return TRUE;
+
+} // end setup2D
+
+// W3DDisplay::finish2D =======================================================
+/** The geometry is in. Outside a batch - and for the calls whose renderer state nobody else can
+ * share - that means draw it now, which is what every one of these calls always did. */
+//=============================================================================
+void W3DDisplay::finish2D( void )
+{
+
+ if( m_batch2D == FALSE || m_batch2DKeepOpen == FALSE )
+ flush2D();
+
+} // end finish2D
+
+// W3DDisplay::flush2D ========================================================
+/** Draw whatever is waiting in the 2D renderer. */
+//=============================================================================
+void W3DDisplay::flush2D( void )
+{
+
+ if( m_batch2DOpen )
+ {
+ m_2DRender->Render();
+ m_batch2DOpen = FALSE;
+ m_batch2DKeepOpen = FALSE;
+ m_batch2DImage = NULL;
+ }
+
+} // end flush2D
+
+// W3DDisplay::beginBatch2D ===================================================
+//=============================================================================
+void W3DDisplay::beginBatch2D( void )
+{
+
+ flush2D();
+ m_batch2D = TRUE;
+
+} // end beginBatch2D
+
+// W3DDisplay::endBatch2D =====================================================
+//=============================================================================
+void W3DDisplay::endBatch2D( void )
+{
+
+ flush2D();
+ m_batch2D = FALSE;
+
+} // end endBatch2D
+
+// W3DDisplay::flushBatch2D ===================================================
+/** draw what the batch is holding, for a caller that is about to draw around it */
+//=============================================================================
+void W3DDisplay::flushBatch2D( void )
+{
+
+ flush2D();
+
+} // end flushBatch2D
+
// W3DDisplay::drawLine =======================================================
/** draw a line on the display in pixel coordinates with the specified color */
//=============================================================================
-void W3DDisplay::drawLine( Int startX, Int startY,
- Int endX, Int endY,
+void W3DDisplay::drawLine( Int startX, Int startY,
+ Int endX, Int endY,
Real lineWidth,
UnsignedInt lineColor )
{
-
- /// @todo we need to consider the efficiency of the 2D renderer
- m_2DRender->Reset();
- m_2DRender->Enable_Texturing( FALSE );
- m_2DRender->Add_Line( Vector2( startX, startY ), Vector2( endX, endY ),
+
+ if( setup2D( NULL, TRUE ) )
+ m_2DRender->Enable_Texturing( FALSE );
+ m_2DRender->Add_Line( Vector2( startX, startY ), Vector2( endX, endY ),
lineWidth, lineColor );
- m_2DRender->Render();
+ finish2D();
} // end drawLine
@@ -2276,12 +2391,11 @@ void W3DDisplay::drawLine( Int startX, Int startY,
UnsignedInt lineColor1,UnsignedInt lineColor2 )
{
- /// @todo we need to consider the efficiency of the 2D renderer
- m_2DRender->Reset();
- m_2DRender->Enable_Texturing( FALSE );
- m_2DRender->Add_Line( Vector2( startX, startY ), Vector2( endX, endY ),
+ if( setup2D( NULL, TRUE ) )
+ m_2DRender->Enable_Texturing( FALSE );
+ m_2DRender->Add_Line( Vector2( startX, startY ), Vector2( endX, endY ),
lineWidth, lineColor1, lineColor2 );
- m_2DRender->Render();
+ finish2D();
} // end drawLine
@@ -2324,16 +2438,14 @@ void W3DDisplay::drawOpenRect( Int startX, Int startY, Int width, Int height,
}
else
{
- /// @todo we need to consider the efficiency of the 2D renderer
- m_2DRender->Reset();
- m_2DRender->Enable_Texturing( FALSE );
-
- m_2DRender->Add_Outline( RectClass( startX, startY,
- startX + width, startY + height ),
+ if( setup2D( NULL, TRUE ) )
+ m_2DRender->Enable_Texturing( FALSE );
+
+ m_2DRender->Add_Outline( RectClass( startX, startY,
+ startX + width, startY + height ),
lineWidth, lineColor );
- // render it now!
- m_2DRender->Render();
+ finish2D();
}
} // end drawOpenRect
@@ -2344,15 +2456,13 @@ void W3DDisplay::drawFillRect( Int startX, Int startY, Int width, Int height,
UnsignedInt color )
{
- /// @todo we need to consider the efficiency of the 2D renderer
- m_2DRender->Reset();
- m_2DRender->Enable_Texturing( FALSE );
- m_2DRender->Add_Rect( RectClass( startX, startY,
- startX + width, startY + height ),
+ if( setup2D( NULL, TRUE ) )
+ m_2DRender->Enable_Texturing( FALSE );
+ m_2DRender->Add_Rect( RectClass( startX, startY,
+ startX + width, startY + height ),
0, 0, color );
- // render it now!
- m_2DRender->Render();
+ finish2D();
} // end drawFillRect
@@ -2362,8 +2472,8 @@ void W3DDisplay::drawRectClock(Int startX, Int startY, Int width, Int height, In
if(percent < 1 || percent > 100)
return;
- m_2DRender->Reset();
- m_2DRender->Enable_Texturing( FALSE );
+ if( setup2D( NULL, TRUE ) )
+ m_2DRender->Enable_Texturing( FALSE );
// The rectanges are numberd as follows
//(x,y) |---------|
@@ -2508,8 +2618,7 @@ void W3DDisplay::drawRectClock(Int startX, Int startY, Int width, Int height, In
}
}
- // render it now!
- m_2DRender->Render();
+ finish2D();
}
@@ -2526,8 +2635,8 @@ void W3DDisplay::drawRemainingRectClock(Int startX, Int startY, Int width, Int h
if( percent < 0 || percent > 99 )
return;
- m_2DRender->Reset();
- m_2DRender->Enable_Texturing( FALSE );
+ if( setup2D( NULL, TRUE ) )
+ m_2DRender->Enable_Texturing( FALSE );
// The rectanges are numbered as follows
//(x,y) |---------|
@@ -2682,13 +2791,12 @@ void W3DDisplay::drawRemainingRectClock(Int startX, Int startY, Int width, Int h
//Draw the last part of the 2nd half of rectangle #4
Real percentDraw = (Real)( percent - 88 ) / 12;
- m_2DRender->Add_Tri( Vector2( midX, midY ), Vector2( midX, startY ), Vector2( startX + halfWidth * percentDraw, startY ),
+ m_2DRender->Add_Tri( Vector2( midX, midY ), Vector2( midX, startY ), Vector2( startX + halfWidth * percentDraw, startY ),
Vector2( 0, 0 ), Vector2( 0, 0 ), Vector2( 0, 0 ), color );
}
}
- // render it now!
- m_2DRender->Render();
+ finish2D();
}
@@ -2712,36 +2820,42 @@ void W3DDisplay::drawImage( const Image *image, Int startX, Int startY,
const Region2D *uv = image->getUV();
- m_2DRender->Reset();
- m_2DRender->Enable_Texturing( TRUE );
-
Bool doAlphaReset=FALSE;
- ///@todo: Why are we alpha blending all images? Reduces our fillrate. -MW
- switch (mode)
+ //
+ // only the plain alpha mode - what nearly every image is drawn in - can share a batch: the
+ // others leave the renderer in a state of their own and have to put it back afterwards.
+ //
+ if( setup2D( image, mode == DRAW_IMAGE_ALPHA ) )
{
- case DRAW_IMAGE_ALPHA: //nothing to do since alpha is the default state
- break;
- case DRAW_IMAGE_GRAYSCALE:
- m_2DRender->Enable_Grayscale(true);
- break;
- case DRAW_IMAGE_ADDITIVE:
- m_2DRender->Enable_Additive(true);
- doAlphaReset = TRUE;
- break;
- case DRAW_IMAGE_SOLID:
- m_2DRender->Enable_Additive(false);
- m_2DRender->Enable_Alpha(false);
- doAlphaReset = TRUE;
- default:
- break;
- }
+ m_2DRender->Enable_Texturing( TRUE );
- // if we have raw texture data we will use it, otherwise we are referencing filenames
- if( BitTest( image->getStatus(), IMAGE_STATUS_RAW_TEXTURE ) )
- m_2DRender->Set_Texture( (TextureClass *)(image->getRawTextureData()) );
- else
- m_2DRender->Set_Texture( image->getFilename().str() );
+ ///@todo: Why are we alpha blending all images? Reduces our fillrate. -MW
+ switch (mode)
+ {
+ case DRAW_IMAGE_ALPHA: //nothing to do since alpha is the default state
+ break;
+ case DRAW_IMAGE_GRAYSCALE:
+ m_2DRender->Enable_Grayscale(true);
+ break;
+ case DRAW_IMAGE_ADDITIVE:
+ m_2DRender->Enable_Additive(true);
+ doAlphaReset = TRUE;
+ break;
+ case DRAW_IMAGE_SOLID:
+ m_2DRender->Enable_Additive(false);
+ m_2DRender->Enable_Alpha(false);
+ doAlphaReset = TRUE;
+ default:
+ break;
+ }
+
+ // if we have raw texture data we will use it, otherwise we are referencing filenames
+ if( BitTest( image->getStatus(), IMAGE_STATUS_RAW_TEXTURE ) )
+ m_2DRender->Set_Texture( (TextureClass *)(image->getRawTextureData()) );
+ else
+ m_2DRender->Set_Texture( image->getFilename().str() );
+ }
RectClass screen_rect(startX,startY,endX,endY);
RectClass uv_rect(uv->lo.x,uv->lo.y,uv->hi.x,uv->hi.y);
@@ -2856,12 +2970,15 @@ void W3DDisplay::drawImage( const Image *image, Int startX, Int startY,
} // end else
- m_2DRender->Render();
+ finish2D();
//reset to default states for next time this method is called.
- m_2DRender->Enable_Grayscale(false); //never leave it in this mode
- if (doAlphaReset)
- m_2DRender->Enable_Alpha(true);
+ if( mode != DRAW_IMAGE_ALPHA )
+ {
+ m_2DRender->Enable_Grayscale(false); //never leave it in this mode
+ if (doAlphaReset)
+ m_2DRender->Enable_Alpha(true);
+ }
} // end drawImage
@@ -2926,12 +3043,12 @@ void W3DDisplay::drawVideoBuffer( VideoBuffer *buffer, Int startX, Int startY, I
{
W3DVideoBuffer *vbuffer = (W3DVideoBuffer*) buffer;
- m_2DRender->Reset();
+ setup2D( NULL, FALSE );
m_2DRender->Enable_Texturing( TRUE );
m_2DRender->Set_Texture( vbuffer->texture() );
m_2DRender->Add_Quad( RectClass( startX, startY, endX, endY ),
vbuffer->Rect( 0, 0, 1, 1) );
- m_2DRender->Render();
+ finish2D();
}
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplayString.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplayString.cpp
index 29913c1b3..cff51c361 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplayString.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplayString.cpp
@@ -50,6 +50,7 @@
// USER INCLUDES //////////////////////////////////////////////////////////////
#include "GameClient/GameClient.h"
+#include "GameClient/Display.h"
#include "W3DDevice/GameClient/W3DDisplayString.h"
#include "GameClient/HotKey.h"
#include "GameClient/GameFont.h"
@@ -166,9 +167,18 @@ void W3DDisplayString::draw( Int x, Int y, Color color, Color dropColor, Int xDr
Bool needNewPolys = FALSE;
// sanity
- if( getTextLength() == 0 )
+ if( getTextLength() == 0 )
return; // nothing to draw
-
+
+ //
+ // Text draws through its own renderer, so it goes to the device the moment it is asked for -
+ // while the display may still be holding 2D geometry that was handed over before it. That
+ // geometry would then be drawn afterwards, on top of the text. Let it out first.
+ //
+ if( TheDisplay )
+ TheDisplay->flushBatch2D();
+
+
// if our font or text has changed we need to build a new sentence
if( m_fontChanged || m_textChanged )
{
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DInGameUI.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DInGameUI.cpp
index defd0dff7..548d9c389 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DInGameUI.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DInGameUI.cpp
@@ -441,10 +441,35 @@ void W3DInGameUI::draw( void )
if (!g_UT_startTiming)
#endif
+#ifdef DEBUG_LOGGING
+ //
+ // The interface's own half of a frame, split again: the overlays and strips this class draws
+ // over the world, and the window system's repaint of the control bar and every dialog.
+ //
+ extern Real TheUIPostDrawMS;
+ extern Real TheWindowRepaintMS;
+ Int64 tPostStart, tPostEnd, tWinEnd, freq;
+ QueryPerformanceCounter( (LARGE_INTEGER *)&tPostStart );
+#endif
+
postDraw();
+#ifdef DEBUG_LOGGING
+ QueryPerformanceCounter( (LARGE_INTEGER *)&tPostEnd );
+#endif
+
TheWindowManager->winRepaint();
+#ifdef DEBUG_LOGGING
+ QueryPerformanceCounter( (LARGE_INTEGER *)&tWinEnd );
+ QueryPerformanceFrequency( (LARGE_INTEGER *)&freq );
+ if( freq > 0 )
+ {
+ TheUIPostDrawMS = (Real)((double)(tPostEnd - tPostStart) * 1000.0 / (double)freq);
+ TheWindowRepaintMS = (Real)((double)(tWinEnd - tPostEnd) * 1000.0 / (double)freq);
+ }
+#endif
+
//
// The clock/rate plate goes on last, after every window has painted. In postDraw with the rest
// of the world overlays it was drawn before the window manager, so anything the manager put on
diff --git a/ai-batch.ps1 b/ai-batch.ps1
index a22896e21..8906db044 100644
--- a/ai-batch.ps1
+++ b/ai-batch.ps1
@@ -35,6 +35,9 @@ param(
[string] $Tag = "ai",
# map sizes to spread the batch over, in playable cells a side
[int[]] $MapCells = @(96, 128, 160),
+ # first seed of the batch. A change tuned against seeds 0..23 has to be confirmed on seeds it
+ # was not tuned on, or the number is a fit to twenty-four maps rather than a result
+ [int] $SeedStart = 0,
# where the game is; the default is this repo's own Run directory
[string] $RunDir = "$PSScriptRoot\GeneralsMD\Run",
# which executable in that directory to play. Two builds can sit side by side under different
@@ -60,8 +63,9 @@ $rows = @()
for ($i = 0; $i -lt $Runs; $i++) {
+ $seed = $SeedStart + $i
$cells = $MapCells[$i % $MapCells.Count]
- $prefix = "{0}_{1:d3}" -f $Tag, $i
+ $prefix = "{0}_{1:d3}" -f $Tag, $seed
$log = Join-Path $RunDir "$($prefix)DebugLogFile.txt"
# a stale log from an earlier batch would read as this run's result if the process died early
@@ -73,10 +77,10 @@ for ($i = 0; $i -lt $Runs; $i++) {
# running" and bails at once, so a batch cannot be measured while a copy of the game is open
$args = @(
"-headless", "-quickstart", "-noshellmap", "-observer", "-multiInstance",
- "-randommap", $i, $Players, $cells,
+ "-randommap", $seed, $Players, $cells,
"-autoskirmish", $Players,
"-aidiff", $Difficulty,
- "-seed", $i,
+ "-seed", $seed,
"-maxframes", $MaxFrames,
"-logPrefix", $prefix
)
@@ -84,20 +88,20 @@ for ($i = 0; $i -lt $Runs; $i++) {
if ($Difficulty2) { $args += "-aidiff2"; $args += $Difficulty2 }
if ($ExtraArgs.Count) { $args += $ExtraArgs }
- Write-Host ("[{0,3}/{1}] seed {2} cells {3} ... " -f ($i + 1), $Runs, $i, $cells) -NoNewline
+ Write-Host ("[{0,3}/{1}] seed {2} cells {3} ... " -f ($i + 1), $Runs, $seed, $cells) -NoNewline
$sw = [Diagnostics.Stopwatch]::StartNew()
$proc = Start-Process -FilePath $exe -ArgumentList $args -WorkingDirectory $RunDir -PassThru
if (-not $proc.WaitForExit($TimeoutMinutes * 60 * 1000)) {
$proc.Kill()
Write-Host "KILLED (wedged past $TimeoutMinutes min)"
- $rows += [pscustomobject]@{ Seed = $i; Cells = $cells; Why = "wedged"; Frames = 0; Wall = $sw.Elapsed.TotalSeconds; Slots = @{}; Pf = $null }
+ $rows += [pscustomobject]@{ Seed = $seed; Cells = $cells; Why = "wedged"; Frames = 0; Wall = $sw.Elapsed.TotalSeconds; Slots = @{}; Pf = $null }
continue
}
$sw.Stop()
if (-not (Test-Path $log)) {
Write-Host "NO LOG (exit $($proc.ExitCode))"
- $rows += [pscustomobject]@{ Seed = $i; Cells = $cells; Why = "no log"; Frames = 0; Wall = $sw.Elapsed.TotalSeconds; Slots = @{}; Pf = $null }
+ $rows += [pscustomobject]@{ Seed = $seed; Cells = $cells; Why = "no log"; Frames = 0; Wall = $sw.Elapsed.TotalSeconds; Slots = @{}; Pf = $null }
continue
}
@@ -146,7 +150,7 @@ for ($i = 0; $i -lt $Runs; $i++) {
$winnerText = if ($null -ne $winner) { "player $winner" } else { "no winner" }
Write-Host ("{0}, {1}, frame {2}, {3:n0}s" -f $why, $winnerText, $frames, $sw.Elapsed.TotalSeconds)
- $rows += [pscustomobject]@{ Seed = $i; Cells = $cells; Why = $why; Frames = $frames; Wall = $sw.Elapsed.TotalSeconds; Slots = $slots; Pf = $pf }
+ $rows += [pscustomobject]@{ Seed = $seed; Cells = $cells; Why = $why; Frames = $frames; Wall = $sw.Elapsed.TotalSeconds; Slots = $slots; Pf = $pf }
}
# ---------------------------------------------------------------------------------------------