Skip to content

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

feat(gameclient): time, experience and garrison room on the HUD

Olcay Seyganf0f214e59fba
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 45ca33cb5..c66610771 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -78,7 +78,11 @@ being punished for doing exactly what aircraft do.
What you get now:
-- **Groups arrive as a group**, at the pace of the slowest unit, instead of trickling in one by one.
+- **Groups arrive as a group when you ask them to.** Hold Ctrl on the attack-move click and every
+ ground unit in the selection goes at the pace of the slowest one, so they hit the line together.
+ Click it plainly and each unit runs at its own speed — which is what you want when the group is a
+ scout screen, or when one damaged truck would otherwise walk your tanks in at a crawl. It used to
+ be one shared pace, always, with no way to say otherwise.
- **Artillery, rocket infantry and Scud launchers find targets again.** They used to search only as
far as they could see, which is far shorter than they can shoot.
- **Attack-moving through a base shoots the base.** Buildings were being filtered out entirely.
@@ -293,6 +297,19 @@ Around it, the whole production loop got tightened:
interrupting a busy one when every worker you own is busy. Same for the build list you get with
nothing selected — it stays usable when the whole crew is out working.
- **Workers go back to collecting supplies** after they finish, instead of standing there.
+- **`S` stops your units again.** The key was simply not bound: the stop button on the command bar
+ worked, so nobody noticed that the key every RTS player reaches for did nothing at all.
+- **Every button says how long it takes.** Each picture in the command bar carries its time in the
+ corner: six seconds for a worker, twenty for a barracks, a hundred and twenty for a Scud storm.
+ It is the price in seconds, and it stays put while the thing is being built — what one costs is
+ still the question you are asking when one is already on the way, and the progress is on the
+ cameo anyway. Upgrades carry their research time the same way. A general's power or special
+ ability carries its cooldown, and that one does count down: how long until you can fire it, and
+ once it is ready, how long the next one will make you wait.
+- **A single selected unit shows its experience.** The portrait wears a gold bar filling toward the
+ next rank. The chevron on the cameo already said which rank a unit holds and nothing about how
+ close the next one is, which is the half of it you actually decide with — one more kill, or half
+ a career away.
- **Timings everywhere**: seconds left on a building going up, the current unit and the whole queue
behind it, a charge bar on superweapons, a progress clock on upgrades being researched. A bar only
appears while something is really happening: your command centre used to wear a yellow bar from
@@ -344,6 +361,24 @@ was — which is what the length of the bar was already telling you — and told
it was. In the middle of a fight that is the question you actually have. They now match the colour
the minimap and the selection rings use, so you can read a brawl without clicking anything.
+**Health bars sit above the roof, not on it.** A building's hit box is its walls, so the bar was
+placed at the top of the *walls* - which on a steep civilian roof is halfway up the picture, and from
+the side is inside the building in front. Buildings now carry their bar clear of their own art, and
+the garrison squares ride with it.
+
+**A building you can garrison shows how full it is.** The little squares over a building — one per
+room, filled for each soldier inside — used to appear only on buildings you already held, which is
+exactly when you least need them. Every garrisonable building shows them now, whoever is in it: how
+many rooms are left is the question you ask before sending a squad, and how many are occupied is the
+question you ask before shooting at it. A vehicle's load stays private — what is inside an enemy
+transport is real intelligence; what is inside a building is what you can see out of its windows.
+
+**And the scenery does not wear one.** Street lamps, phone boxes, barrels, planters, fire hydrants,
+rocks and bushes all have hit points in this engine, so with health bars always on, a town map came
+up with hundreds of little lines over things nobody fights. Buildings keep theirs — a civilian
+building is cover to garrison, a tech building is worth capturing, and both are worth shooting — and
+so does anything that can move.
+
## Twenty-two-year-old bugs, found by testing
Nothing here was guessed at. Every fix in this section came out of a test written against the
@@ -365,7 +400,10 @@ original code, and each one was proved by putting the bug back and watching the
in that code reads *"Empirically, in release the code can loop forever. So we limit to 100
passes."* — they knew something was wrong there and capped the symptom.
- **On-screen messages disappeared the instant they appeared.** The designed reading time never
- worked, in the retail game either.
+ worked, in the retail game either. Fixed — and then shortened: the corner used to hold each line
+ for five seconds and take another three to fade it, so what you did eight seconds ago was still
+ sitting there under everything you had done since. It reads for two and a half seconds and fades
+ in about one.
- **The mouse wheel cancelled whatever camera move was in progress** — zoom while panning, the most
common camera gesture there is, fought you every time.
diff --git a/GeneralsMD/Code/Data/INI/CommandMap.ini b/GeneralsMD/Code/Data/INI/CommandMap.ini
index 85ccfce47..8c498a32a 100644
--- a/GeneralsMD/Code/Data/INI/CommandMap.ini
+++ b/GeneralsMD/Code/Data/INI/CommandMap.ini
@@ -314,6 +314,20 @@ CommandMap TOGGLE_ATTACKMOVE
DisplayName = GUI:ToggleAttackMove
End
+; stop what you are doing. This file replaces the shipped command map rather than
+; merging with it, so a retail key that is not written out here is simply not bound -
+; which is what had happened to stop: the grid gives the command bar's stop button a
+; cell letter, but the key every RTS player reaches for was dead.
+CommandMap STOP
+ Key = KEY_S
+ Transition = DOWN
+ Modifiers = NONE
+ UseableIn = GAME
+ Category = CONTROL
+ Description = GUI:StopDescription
+ DisplayName = GUI:Stop
+End
+
; guard the spot you are standing on, without chasing anything
CommandMap HOLD_POSITION
Key = KEY_G
diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/Gadget.h b/GeneralsMD/Code/GameEngine/Include/GameClient/Gadget.h
index 9ed931730..538391ed3 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameClient/Gadget.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/Gadget.h
@@ -432,6 +432,9 @@ typedef struct _PushButtonData
Bool drawBorder; ///< We only want to draw the border if we want to
Color colorBorder; ///< The color for the border around the button
Int drawCount; ///< when > 0, a small number badge drawn in the bottom right corner
+ Int drawSeconds; ///< when > 0, a seconds label drawn in the bottom left corner
+ Int barPercent; ///< when >= 0, a thin bar drawn along the bottom edge (experience)
+ Color barColor; ///< colour of that bar
void *userData; ///< random additional data we can set
const Image *overlayImage; ///< An overlay image (like a veterancy symbol)
AsciiString altSound; ///< use an alternitive sound if one is set
diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/GadgetPushButton.h b/GeneralsMD/Code/GameEngine/Include/GameClient/GadgetPushButton.h
index 13670b9e0..fa121deaf 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameClient/GadgetPushButton.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/GadgetPushButton.h
@@ -83,6 +83,8 @@ void GadgetButtonDrawInverseClock( GameWindow *g, Int percent, Color color ); //
void GadgetButtonDrawOverlayImage( GameWindow *g, const Image *image );
void GadgetButtonSetBorder( GameWindow *g, Color color, Bool drawBorder = TRUE );
void GadgetButtonSetCount( GameWindow *g, Int count );
+void GadgetButtonSetSeconds( GameWindow *g, Int seconds );
+void GadgetButtonSetBar( GameWindow *g, Int percent, Color color );
void GadgetButtonSetData(GameWindow *g, void *data);
void *GadgetButtonGetData(GameWindow *g);
void GadgetButtonSetAltSound( GameWindow *g, AsciiString altSound );
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h
index 596024607..ce02906b7 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h
@@ -920,7 +920,8 @@ public:
}
void groupAttackTeam( const Team *team, Int maxShotsToFire, CommandSourceType cmdSource ); ///< attack the given team
void groupAttackPosition( const Coord3D *pos, Int maxShotsToFire, CommandSourceType cmdSource ); ///< attack given spot
- void groupAttackMoveToPosition( const Coord3D *pos, Int maxShotsToFire, CommandSourceType cmdSource ); ///< Attack move to the location
+ void groupAttackMoveToPosition( const Coord3D *pos, Int maxShotsToFire, CommandSourceType cmdSource, Bool matchSpeeds = TRUE ); ///< Attack move to the location
+ Bool getMatchSpeeds( void ) const { return m_matchSpeeds; } ///< does the last attack move hold everyone to the slowest member?
void groupHunt( CommandSourceType cmdSource ); ///< begin "seek and destroy"
void groupRepair( Object *obj, CommandSourceType cmdSource ); ///< repair the given object
void groupResumeConstruction( Object *obj, CommandSourceType cmdSource ); ///< resume construction on the object
@@ -1028,6 +1029,7 @@ private:
UnsignedInt m_memberListSize; ///< the size of the list of member Objects
Real m_speed; ///< maximum speed of group (slowest member)
+ Bool m_matchSpeeds; ///< last attack move asked for one shared speed (see groupAttackMoveToPosition)
Bool m_dirty; ///< "dirty bit" - if true then group speed, leader, needs recompute
UnsignedInt m_id; ///< the unique ID of this group
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp
index 60e5ffcfd..dbcb1cb5a 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp
@@ -2714,6 +2714,25 @@ void Drawable::draw( View *view )
/** Compute the health bar region based on the health of the object and the
* zoom level of the camera */
// ------------------------------------------------------------------------------------------------
+//-------------------------------------------------------------------------------------------------
+/** How far above `getHealthBoxPosition` a bar has to sit to clear the object's own art.
+ *
+ * A building's geometry box is its walls: the pitched roof of a civilian house, the mast on a
+ * radar dome and the tower on a barracks are not in the logical height at all, so the bar landed
+ * on the roof of its own building - and, side on, inside the one in front of it. Lift a structure
+ * by a share of its own height rather than by a fixed amount, so it scales from a low bunker to a
+ * four storey apartment block and a flat faction building barely moves. Everything that can move
+ * keeps its bar where it was: a unit's geometry is its model. */
+//-------------------------------------------------------------------------------------------------
+static Real healthBarArtLift( const Object *obj )
+{
+ if( obj == NULL || !obj->isKindOf( KINDOF_STRUCTURE ) )
+ return 0.0f;
+
+ return obj->getGeometryInfo().getMaxHeightAbovePosition() * 0.35f;
+}
+
+//-------------------------------------------------------------------------------------------------
static Bool computeHealthRegion( const Drawable *draw, IRegion2D& region )
{
@@ -2727,6 +2746,7 @@ static Bool computeHealthRegion( const Drawable *draw, IRegion2D& region )
Coord3D p;
obj->getHealthBoxPosition(p);
+ p.z += healthBarArtLift( obj );
ICoord2D screenCenter;
if( !TheTacticalView->worldToScreen( &p, &screenCenter ) )
return FALSE;
@@ -2975,6 +2995,11 @@ void Drawable::drawAmmo( const IRegion2D *healthBarRegion )
// ------------------------------------------------------------------------------------------------
void Drawable::drawContained( const IRegion2D *healthBarRegion )
{
+ // the pips are left-justified on the health bar, and this is the only thing that reads it -
+ // an object with no health region (off screen, or ignored in the GUI) would deref a NULL below
+ if (!healthBarRegion)
+ return;
+
const Object *obj = getObject();
ContainModuleInterface* container = obj->getContain();
@@ -2986,10 +3011,18 @@ void Drawable::drawContained( const IRegion2D *healthBarRegion )
return;
// container pips are always on for own objects (was: only when selected or moused over)
- if (!(
- TheGlobalData->m_showObjectHealth &&
- obj->getControllingPlayer() == ThePlayerList->getLocalPlayer()
- ))
+ if (!TheGlobalData->m_showObjectHealth)
+ return;
+
+ //
+ // ...and a building you can garrison shows them whoever holds it. How many rooms are left in
+ // that civilian block is the question you ask before sending a squad at it, and how many are
+ // occupied is the question you ask before shooting at it - both were answerable only by
+ // garrisoning it yourself. A vehicle's load stays private: an enemy transport's contents are
+ // real intelligence, a building's occupancy is what you can already see out of its windows.
+ //
+ if (obj->getControllingPlayer() != ThePlayerList->getLocalPlayer() &&
+ !(obj->isKindOf( KINDOF_STRUCTURE ) && container->isGarrisonable()))
return;
Int numTotal;
@@ -3025,6 +3058,7 @@ void Drawable::drawContained( const IRegion2D *healthBarRegion )
pos.x += TheGlobalData->m_containerPipWorldOffset.x;
pos.y += TheGlobalData->m_containerPipWorldOffset.y;
pos.z += TheGlobalData->m_containerPipWorldOffset.z + obj->getGeometryInfo().getMaxHeightAbovePosition();
+ pos.z += healthBarArtLift( obj ); // the pips ride at the bar's height, see computeHealthRegion
if( !TheTacticalView->worldToScreen( &pos, &screenCenter ) )
return;
@@ -3905,13 +3939,27 @@ void Drawable::drawHealthBar(const IRegion2D* healthBarRegion)
// wrecked hulks, subobject turrets) are not things the player commands or targets, so
// their bars are pure clutter.
//
+ // So is the scenery: street lamps, phone boxes, barrels, planters, fire hydrants, rocks,
+ // bushes and the odd tree all carry a BodyModule and so all drew a bar, and a built-up map
+ // came up wearing hundreds of them over things nobody fights.
+ //
+ // The rule is fixed-in-place-and-not-a-building, not a list of scenery kinds: the shipped
+ // data does not tag that furniture as PROP or SHRUBBERY at all (`KindOf = IMMOBILE
+ // CLEARED_BY_BUILD` is the whole of a street lamp, and `IMMOBILE` the whole of a rock), so
+ // a kind list catches almost none of it, while every real target is either mobile or a
+ // STRUCTURE. Buildings keep their bars - a civilian building is cover to garrison, a tech
+ // building is worth capturing, bridges are STRUCTURE too - and so does anything that can
+ // move.
+ //
if( obj->isKindOf( KINDOF_PROJECTILE ) ||
obj->isKindOf( KINDOF_INERT ) ||
obj->isKindOf( KINDOF_CLEANUP_HAZARD ) ||
obj->isKindOf( KINDOF_UNATTACKABLE ) ||
obj->isKindOf( KINDOF_PARACHUTE ) ||
obj->isKindOf( KINDOF_HULK ) ||
- obj->isKindOf( KINDOF_CLICK_THROUGH ) )
+ obj->isKindOf( KINDOF_CLICK_THROUGH ) ||
+ obj->isKindOf( KINDOF_CRATE ) ||
+ ( obj->isKindOf( KINDOF_IMMOBILE ) && !obj->isKindOf( KINDOF_STRUCTURE ) ) )
return;
if( obj->isKindOf( KINDOF_FORCEATTACKABLE ) )
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp
index 413311da7..6c97c4e72 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp
@@ -52,6 +52,7 @@
#include "Common/Recorder.h"
#include "GameLogic/GameLogic.h"
+#include "GameLogic/ExperienceTracker.h"
#include "GameLogic/Object.h"
#include "GameLogic/Module/AIUpdate.h"
#include "GameLogic/Module/DozerAIUpdate.h"
@@ -1582,6 +1583,19 @@ void ControlBar::reset( void )
m_genStarFlash = TRUE;
} // end reset
+//-------------------------------------------------------------------------------------------------
+/** How far a unit is into its current veterancy rank, 0..100, or -1 when there is no next rank to
+ * fill towards (top rank, or a template with no thresholds - both mean "draw no bar"). */
+//-------------------------------------------------------------------------------------------------
+Int ControlBar_experiencePercent( Int currentExp, Int levelExp, Int nextLevelExp )
+{
+ if( nextLevelExp <= levelExp )
+ return -1;
+
+ Int percent = ( currentExp - levelExp ) * 100 / ( nextLevelExp - levelExp );
+ return min( 100, max( 0, percent ) );
+}
+
//-------------------------------------------------------------------------------------------------
/** Update phase, we can track if our selected object is destroyed, update button
* percentages, status, enabled status etc */
@@ -1804,6 +1818,32 @@ void ControlBar::update( void )
}
}
+ //
+ // the experience bar under the portrait. The rank chevron on the cameo says which rank a
+ // unit holds and nothing about how close the next one is, and that is the half of it you
+ // decide with - whether this tank is one kill off veteran or has just got there. Only for a
+ // single selection: with a group selected the portrait is one member standing in for all of
+ // them, and its experience would be read as the group's.
+ //
+ if( m_rightHUDCameoWindow )
+ {
+ Int xpPercent = -1;
+ Object *portraitObj = ( TheInGameUI && TheInGameUI->getSelectCount() == 1 &&
+ m_currentSelectedDrawable ) ? m_currentSelectedDrawable->getObject()
+ : NULL;
+ const ExperienceTracker *xp = portraitObj ? portraitObj->getExperienceTracker() : NULL;
+ if( xp && portraitObj->isLocallyControlled() && xp->isTrainable() &&
+ xp->getVeterancyLevel() < LEVEL_LAST )
+ {
+ const ThingTemplate *tmpl = portraitObj->getTemplate();
+ xpPercent = ControlBar_experiencePercent( xp->getCurrentExperience(),
+ tmpl->getExperienceRequired( xp->getVeterancyLevel() ),
+ tmpl->getExperienceRequired( xp->getVeterancyLevel() + 1 ) );
+ }
+
+ GadgetButtonSetBar( m_rightHUDCameoWindow, xpPercent, GameMakeColor( 255, 200, 40, 255 ) );
+ }
+
//
// most control bar contexts have one selected thing that we switch on and update
// based on if that thing changed in some way ... the exception is when multi selected
@@ -3036,8 +3076,12 @@ void ControlBar::setControlCommand( GameWindow *button, const CommandButton *com
GadgetButtonSetData(button, (void*)commandButton);
//button->winSetUserData( commandButton );
- // a recycled button must not keep the previous occupant's count badge
+ // a recycled button must not keep the previous occupant's count badge, nor its seconds label:
+ // only the command context re-stamps those every frame, so a button that ends up in any other
+ // context (a garrisoned building's exit cameos, a beacon, an OCL timer) would wear the build
+ // time of whatever used to live in that window.
GadgetButtonSetCount( button, 0 );
+ GadgetButtonSetSeconds( button, 0 );
setCommandBarBorder(button, commandButton->getCommandButtonMappedBorderType());
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommand.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommand.cpp
index 40801ca15..466cb1aab 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommand.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommand.cpp
@@ -80,6 +80,19 @@ Bool commandWindowsInitialized = FALSE;
* lands, and the cameo reads as "uncovering" rather than "filling up with black". */
static Color BuildClockColor = GameMakeColor(0,0,0,120);
+//-------------------------------------------------------------------------------------------------
+/** Logic frames to whole seconds, rounded up and never down to zero: a button that still has work
+ * left on it must not read "0s". */
+//-------------------------------------------------------------------------------------------------
+Int ControlBar_secondsFromFrames( Real frames )
+{
+ if( frames <= 0.0f )
+ return 0;
+
+ Int seconds = (Int)( frames / LOGICFRAMES_PER_SECOND + 0.999f );
+ return seconds < 1 ? 1 : seconds;
+}
+
//-------------------------------------------------------------------------------------------------
/** Is any selected building of the local player's researching or holding 'upgrade' in its queue?
* Hands back the queue entry when the upgrade is the one being worked on right now (that is the
@@ -784,6 +797,26 @@ void ControlBar::updateContextCommand( void )
}
}
+ //
+ // what this button costs in seconds. The radial fill says "some of the way there" and
+ // nothing about how long that is, which is the one number a build decision needs.
+ //
+ // It stays the build time while the thing is being built rather than counting down to it:
+ // the number on the button answers "what does one of these cost me", and that question does
+ // not stop being asked because one is already on the way - a counting number turns the one
+ // stable figure on the bar into something you cannot read off at a glance, and the queue's
+ // own progress is already on the cameo (the radial fill and the count badge) and over the
+ // producer itself.
+ //
+ if( command->getCommandType() == GUI_COMMAND_UNIT_BUILD ||
+ command->getCommandType() == GUI_COMMAND_DOZER_CONSTRUCT )
+ {
+ const ThingTemplate *tmpl = command->getThingTemplate();
+ Player *localPlayer = ThePlayerList ? ThePlayerList->getLocalPlayer() : NULL;
+ if( tmpl && localPlayer )
+ GadgetButtonSetSeconds( win, ControlBar_secondsFromFrames( (Real)tmpl->calcTimeToBuild( localPlayer ) ) );
+ }
+
//
// an upgrade button wears the same radial fill while its upgrade is the one being
// researched. An upgrade is never queued twice on one building, so there is no count badge
@@ -796,7 +829,14 @@ void ControlBar::updateContextCommand( void )
command->getCommandType() == GUI_COMMAND_OBJECT_UPGRADE )
{
const ProductionEntry *entry = NULL;
- if( findUpgradeInSelection( command->getUpgradeTemplate(), &entry ) )
+ Bool queuedHere = findUpgradeInSelection( command->getUpgradeTemplate(), &entry );
+
+ const UpgradeTemplate *ut = command->getUpgradeTemplate();
+ Player *localPlayer = ThePlayerList ? ThePlayerList->getLocalPlayer() : NULL;
+ if( ut && localPlayer )
+ GadgetButtonSetSeconds( win, ControlBar_secondsFromFrames( (Real)ut->calcTimeToBuild( localPlayer ) ) );
+
+ if( queuedHere )
{
upgradeQueuedHere = TRUE;
if( entry )
@@ -1509,7 +1549,24 @@ CommandAvailability ControlBar::getCommandAvailability( const CommandButton *com
// perform was drawn ready to fire. There is nothing behind it, so hide it.
return COMMAND_HIDDEN;
}
- else if( mod->isReady() == FALSE )
+ //
+ // the cooldown in seconds: what is left of it while the power charges, and the whole
+ // of it while the power is ready, so you can see what firing it will cost you
+ //
+ {
+ const SpecialPowerTemplate *spTemplate = command->getSpecialPowerTemplate();
+ UnsignedInt now = TheGameLogic->getFrame();
+ UnsignedInt readyFrame = mod->getReadyFrame();
+
+ // frame numbers are unsigned - a ready frame already behind us wraps if subtracted
+ Real frames = ( readyFrame > now ) ? (Real)( readyFrame - now ) : 0.0f;
+ if( frames <= 0.0f && spTemplate )
+ frames = (Real)spTemplate->getReloadTime();
+
+ GadgetButtonSetSeconds( applyToWin, ControlBar_secondsFromFrames( frames ) );
+ }
+
+ if( mod->isReady() == FALSE )
{
Int percent = mod->getPercentReady() * 100;
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ControlBarCallback.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ControlBarCallback.cpp
index 75bbe2401..3108492fe 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ControlBarCallback.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ControlBarCallback.cpp
@@ -290,6 +290,7 @@ WindowMsgHandledType LeftHUDInput( GameWindow *window, UnsignedInt msg,
GameMessage *msg = TheMessageStream->appendMessage( GameMessage::MSG_DO_ATTACKMOVETO );
msg->appendLocationArgument( world );
+ msg->appendBooleanArgument( TheInGameUI->isInForceAttackMode() ); // ctrl: arrive together
// Play the unit voice response
pickAndPlayUnitVoiceResponse(TheInGameUI->getAllSelectedDrawables(), GameMessage::MSG_DO_ATTACKMOVETO);
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetPushButton.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetPushButton.cpp
index 52e2793c5..551068612 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetPushButton.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetPushButton.cpp
@@ -604,6 +604,9 @@ PushButtonData * getNewPushButtonData( void )
p->drawBorder = FALSE;
p->drawClock = NO_CLOCK;
p->drawCount = 0;
+ p->drawSeconds = 0;
+ p->barPercent = -1;
+ p->barColor = GAME_COLOR_UNDEFINED;
p->overlayImage = NULL;
return p;
}
@@ -706,9 +709,52 @@ void GadgetButtonClearClock( GameWindow *g )
return;
pData->drawClock = NO_CLOCK;
+ // the seconds label is the same per-frame overlay as the clock, and everyone who puts one on
+ // puts a clock on with it, so it comes off here too
+ pData->drawSeconds = 0;
}
+// GadgetButtonSetSeconds =====================================================
+/** Set the seconds label drawn in the button's bottom left corner, 0 for none.
+ * Cleared by GadgetButtonClearClock, so it must be re-set every frame. */
+//=============================================================================
+void GadgetButtonSetSeconds( GameWindow *g, Int seconds )
+{
+ if( g == NULL )
+ return;
+
+ PushButtonData *pData = (PushButtonData *)g->winGetUserData();
+ if(!pData)
+ {
+ pData = getNewPushButtonData();
+ if(!pData)
+ return;
+ }
+ pData->drawSeconds = seconds;
+ g->winSetUserData(pData);
+}
+
+// GadgetButtonSetBar =========================================================
+/** Set a thin progress bar along the button's bottom edge, percent < 0 for none */
+//=============================================================================
+void GadgetButtonSetBar( GameWindow *g, Int percent, Color color )
+{
+ if( g == NULL )
+ return;
+
+ PushButtonData *pData = (PushButtonData *)g->winGetUserData();
+ if(!pData)
+ {
+ pData = getNewPushButtonData();
+ if(!pData)
+ return;
+ }
+ pData->barPercent = percent;
+ pData->barColor = color;
+ g->winSetUserData(pData);
+}
+
void GadgetButtonDrawOverlayImage( GameWindow *g, const Image *image )
{
if( g == NULL )
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp
index 0fcd0d73e..4ee51587d 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp
@@ -1831,7 +1831,25 @@ void InGameUI::update( void )
// ms -> logic frames. This used to divide by LOGICFRAMES_PER_SECOND instead of multiplying and
// then divide by 1000 again, so with the shipped MessageDelayMS (~5000) it was 5000/30 = 166,
// 166/1000 = 0 - every UI message started fading on the frame it was posted.
- const int messageTimeout = m_messageDelayMS * LOGICFRAMES_PER_SECOND / 1000;
+ //
+ // ...and the shipped value holds a message for five whole seconds before the fade even
+ // starts, on top of a fade that took three more: the corner was still showing what you did
+ // eight seconds ago, stacked under what you have done since. Cap the hold at MESSAGE_HOLD_MS
+ // and take the fade down at a fixed rate, which is about a second.
+ //
+ // That rate is per LOGIC frame, not per call: this runs once per render frame, so a fixed
+ // step per call would empty the alpha (fps/30) times too fast - the same trap the military
+ // subtitle countdown below fell into.
+ //
+ const int MESSAGE_HOLD_MS = 2500;
+ const int MESSAGE_FADE_PER_FRAME = 8;
+ static UnsignedInt s_lastMessageFadeFrame = 0xffffffff;
+ const Bool fadeThisPass = ( currLogicFrame != s_lastMessageFadeFrame );
+ s_lastMessageFadeFrame = currLogicFrame;
+ int messageDelayMS = m_messageDelayMS;
+ if( messageDelayMS > MESSAGE_HOLD_MS )
+ messageDelayMS = MESSAGE_HOLD_MS;
+ const int messageTimeout = messageDelayMS * LOGICFRAMES_PER_SECOND / 1000;
UnsignedByte r, g, b, a;
Int amount;
for( i = MAX_UI_MESSAGES - 1; i >= 0; i-- )
@@ -1841,14 +1859,14 @@ void InGameUI::update( void )
if( m_uiMessages[ i ].displayString == NULL )
continue;
- if( currLogicFrame - m_uiMessages[ i ].timestamp > messageTimeout )
+ if( fadeThisPass && currLogicFrame - m_uiMessages[ i ].timestamp > messageTimeout )
{
// get the current color of this text
GameGetColorComponents( m_uiMessages[ i ].color, &r, &g, &b, &a );
// start fading the alpha on this color down
- amount = REAL_TO_INT( ((currLogicFrame - m_uiMessages[ i ].timestamp) * 0.01f) );
+ amount = MESSAGE_FADE_PER_FRAME;
if( a - amount < 0 )
a = 0;
else
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/CommandXlat.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/CommandXlat.cpp
index f07a31e17..21d95023e 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/CommandXlat.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/CommandXlat.cpp
@@ -903,6 +903,11 @@ GameMessage::Type CommandTranslator::issueMoveToLocationCommand( const Coord3D *
else
movemsg->appendLocationArgument( *pos );
+ // ctrl on an attack move click asks for one shared pace - the force attack modifier is
+ // the ctrl key, and it means nothing else while the attack move cursor is up
+ if (msgType == GameMessage::MSG_DO_ATTACKMOVETO)
+ movemsg->appendBooleanArgument( TheInGameUI->isInForceAttackMode() );
+
} // end if
}
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/GUICommandTranslator.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/GUICommandTranslator.cpp
index bdf1859f7..4d4529631 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/GUICommandTranslator.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/GUICommandTranslator.cpp
@@ -287,6 +287,7 @@ static CommandStatus doAttackMoveCommand( const CommandButton *command, const IC
// send the message to set the rally point
GameMessage *msg = TheMessageStream->appendMessage( GameMessage::MSG_DO_ATTACKMOVETO );
msg->appendLocationArgument( world );
+ msg->appendBooleanArgument( TheInGameUI->isInForceAttackMode() ); // ctrl: arrive together
// Play the unit voice response
pickAndPlayUnitVoiceResponse(TheInGameUI->getAllSelectedDrawables(), GameMessage::MSG_DO_ATTACKMOVETO);
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp
index b8c86d7e2..679e4b479 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp
@@ -78,6 +78,7 @@ AIGroup::AIGroup( void )
// DEBUG_LOG(("***AIGROUP %x is being constructed.\n", this));
m_groundPath = NULL;
m_speed = 0.0f;
+ m_matchSpeeds = TRUE;
m_dirty = false;
m_id = TheAI->getNextGroupID();
m_memberListSize = 0;
@@ -2287,15 +2288,22 @@ void AIGroup::groupAttackPosition( const Coord3D *pos, Int maxShotsToFire, Comma
/**
* Attack move to a location
*/
-void AIGroup::groupAttackMoveToPosition( const Coord3D *pos, Int maxShotsToFire, CommandSourceType cmdSource )
+void AIGroup::groupAttackMoveToPosition( const Coord3D *pos, Int maxShotsToFire, CommandSourceType cmdSource, Bool matchSpeeds )
{
//
// This used to hand every member the same single coordinate, so a group attack move arrived as
// a queue rather than a group: everyone pathed to one point, at their own top speed. Spread the
// destination the way groupMoveToPosition does (each member keeps its offset from the group
- // centroid) and hold the ground units to the speed of the slowest one so the group stays
- // together on the way in - the whole point of an attack move is arriving able to fight.
+ // centroid).
//
+ // Holding the ground units to the speed of the slowest one keeps the group together on the way
+ // in, but it also means one damaged truck walks the tanks in at its own pace, and that is not
+ // always what you asked for. So it is the player's call, taken from the ctrl key on the click:
+ // ctrl-click an attack move and they arrive together, click it plainly and they each go at
+ // their own speed. AIAttackMoveToState::onEnter reads it back off the group.
+ //
+ m_matchSpeeds = matchSpeeds;
+
if (m_dirty)
recompute();
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp
index 5cd5282de..17333110c 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp
@@ -3619,12 +3619,13 @@ StateReturnType AIAttackMoveToState::onEnter()
// spread the scans of a group that was all ordered on the same frame over the scan interval.
m_frameToScanOn = TheGameLogic->getFrame() + ((UnsignedInt)owner->getID() % ATTACK_MOVE_SCAN_RATE);
- // An attack move arrives as a group or it arrives as a queue of single units, so the ground
- // units go at the pace of the slowest one. The order is still running inside the AIGroup that
- // issued it, so the group is still reachable here; it is gone by the next update.
+ // An attack move can arrive as a group or as a queue of single units, and which one you want
+ // is the player's call: ctrl on the click asks for one shared pace, the slowest member's. The
+ // order is still running inside the AIGroup that issued it, so the group - and the flag it
+ // carries - is still reachable here; it is gone by the next update.
m_groupSpeed = FAST_AS_POSSIBLE;
AIGroup *group = ai->getGroup();
- if (group != NULL && ai->isDoingGroundMovement())
+ if (group != NULL && group->getMatchSpeeds() && ai->isDoingGroundMovement())
{
Real speed = group->getSpeed();
if (speed > 0.0f && speed < FAST_AS_POSSIBLE)
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp
index 459cded98..bec3e4202 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp
@@ -828,10 +828,13 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData )
{
Coord3D dest = msg->getArgument( 0 )->location;
+ // ctrl held on the click means "arrive together" - see AIGroup::groupAttackMoveToPosition
+ Bool matchSpeeds = ( msg->getArgumentCount() > 1 ) ? msg->getArgument( 1 )->boolean : FALSE;
+
if (currentlySelectedGroup)
{
currentlySelectedGroup->releaseWeaponLockForGroup(LOCKED_TEMPORARILY); // release any temporary locks.
- currentlySelectedGroup->groupAttackMoveToPosition( &dest, NO_MAX_SHOTS_LIMIT, CMD_FROM_PLAYER );
+ currentlySelectedGroup->groupAttackMoveToPosition( &dest, NO_MAX_SHOTS_LIMIT, CMD_FROM_PLAYER, matchSpeeds );
}
break;
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DPushButton.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DPushButton.cpp
index 2f23d3836..4a2a3ef67 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DPushButton.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DPushButton.cpp
@@ -16,6 +16,7 @@
** along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
+
////////////////////////////////////////////////////////////////////////////////
// //
// (c) 2001-2003 Electronic Arts Inc. //
@@ -191,6 +192,71 @@ static void drawCountBadge( GameWindow *window, Int count )
} // end drawCountBadge
+// drawSecondsBadge ===========================================================
+/** Draw a small "12s" label in the button's bottom left corner - how long the
+ * thing on this button takes to build, or how long is left on it. */
+//=============================================================================
+static void drawSecondsBadge( GameWindow *window, Int seconds )
+{
+ static DisplayString *label = NULL;
+ ICoord2D origin, size, textPos;
+ Int width, height;
+
+ if( label == NULL )
+ {
+ label = TheDisplayStringManager->newDisplayString();
+ if( label == NULL )
+ return;
+ }
+
+ UnicodeString text;
+ text.format( L"%ds", seconds );
+ label->setText( text );
+
+ if( label->getFont() != window->winGetFont() )
+ label->setFont( window->winGetFont() );
+
+ window->winGetScreenPosition( &origin.x, &origin.y );
+ window->winGetSize( &size.x, &size.y );
+ label->getSize( &width, &height );
+
+ textPos.x = origin.x + 3;
+ textPos.y = origin.y + size.y - height - 1;
+
+ // same translucent plate the count badge wears - button art can be any colour
+ TheDisplay->drawFillRect( textPos.x - 2, textPos.y, width + 4, height,
+ GameMakeColor( 0, 0, 0, 160 ) );
+ label->draw( textPos.x, textPos.y, GameMakeColor( 255, 255, 255, 255 ),
+ GameMakeColor( 0, 0, 0, 255 ) );
+
+} // end drawSecondsBadge
+
+// drawButtonBar ==============================================================
+/** Draw a thin progress bar along the button's bottom edge (experience) */
+//=============================================================================
+static void drawButtonBar( GameWindow *window, Int percent, Color color )
+{
+ ICoord2D origin, size;
+
+ window->winGetScreenPosition( &origin.x, &origin.y );
+ window->winGetSize( &size.x, &size.y );
+
+ if( percent > 100 )
+ percent = 100;
+
+ const Int barHeight = 4;
+ Int x = origin.x + 2;
+ Int y = origin.y + size.y - barHeight - 2;
+ Int w = size.x - 4;
+ if( w <= 0 )
+ return;
+
+ TheDisplay->drawFillRect( x, y, w, barHeight, GameMakeColor( 0, 0, 0, 180 ) );
+ TheDisplay->drawFillRect( x, y, w * percent / 100, barHeight, color );
+ TheDisplay->drawOpenRect( x, y, w, barHeight, 1.0f, GameMakeColor( 0, 0, 0, 255 ) );
+
+} // end drawButtonBar
+
///////////////////////////////////////////////////////////////////////////////
// PUBLIC FUNCTIONS ///////////////////////////////////////////////////////////
@@ -325,6 +391,12 @@ void W3DGadgetPushButtonDraw( GameWindow *window, WinInstanceData *instData )
if( pData->drawCount > 0 )
drawCountBadge( window, pData->drawCount );
+
+ if( pData->drawSeconds > 0 )
+ drawSecondsBadge( window, pData->drawSeconds );
+
+ if( pData->barPercent >= 0 )
+ drawButtonBar( window, pData->barPercent, pData->barColor );
}
} // end W3DGadgetPushButtonDraw
@@ -498,6 +570,12 @@ void W3DGadgetPushButtonImageDrawOne( GameWindow *window,
if( pData->drawCount > 0 )
drawCountBadge( window, pData->drawCount );
+
+ if( pData->drawSeconds > 0 )
+ drawSecondsBadge( window, pData->drawSeconds );
+
+ if( pData->barPercent >= 0 )
+ drawButtonBar( window, pData->barPercent, pData->barColor );
}
//Now render overlays that pertain to the correct state.
@@ -757,5 +835,11 @@ void W3DGadgetPushButtonImageDrawThree(GameWindow *window, WinInstanceData *inst
if( pData->drawCount > 0 )
drawCountBadge( window, pData->drawCount );
+
+ if( pData->drawSeconds > 0 )
+ drawSecondsBadge( window, pData->drawSeconds );
+
+ if( pData->barPercent >= 0 )
+ drawButtonBar( window, pData->barPercent, pData->barColor );
}
}
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DShaderManager.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DShaderManager.cpp
index 83c81f5e4..59f548f06 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DShaderManager.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DShaderManager.cpp
@@ -2985,6 +2985,22 @@ Bool W3DShaderManager::filterSetup(FilterTypes filter, enum FilterModes mode)
return FALSE;
}
+//=============================================================================
+/** Render-to-texture is how the smudge (heat haze) and bloom passes get the scene, and every way
+ * it can go wrong ends the same way on screen: a black world under a perfectly good UI, because
+ * the scene went into a texture that never got blitted back. None of these paths said anything,
+ * so the only evidence was the player's eyes. Rate limited - a broken frame usually repeats. */
+//=============================================================================
+static void rttComplain( const char *why )
+{
+ static UnsignedInt lastComplaintMs = 0;
+ const UnsignedInt now = timeGetTime();
+ if( lastComplaintMs != 0 && now - lastComplaintMs < 1000 )
+ return;
+ lastComplaintMs = now;
+ DEBUG_LOG(( "RenderToTexture: %s\n", why ));
+}
+
/*Draws 2 triangles covering the viewport given the current render states*/
void W3DShaderManager::drawViewport(Int color)
{
@@ -3035,7 +3051,15 @@ void W3DShaderManager::startRenderToTexture(void)
{
DEBUG_ASSERTCRASH(!m_renderingToTexture, ("Already rendering to texture - cannot nest calls."));
- if (m_renderingToTexture || m_newRenderSurface==NULL || m_oldDepthSurface==NULL) return;
+ if (m_renderingToTexture || m_newRenderSurface==NULL || m_oldDepthSurface==NULL)
+ {
+ // One of these leaves the scene going somewhere other than where the blit below expects
+ // it, which is what a black world with a live UI looks like. Say which, at most once a
+ // second, so a report of "the screen went black" has something behind it.
+ rttComplain( m_renderingToTexture ? "already rendering to texture"
+ : (m_newRenderSurface==NULL ? "no render target texture" : "no depth surface") );
+ return;
+ }
//m_oldDepthSurface is the back buffer's depth surface, which is multisampled when the back
//buffer is; D3D wants the depth buffer to match the render target, and ours is a plain
//texture. Ask the wrapper for a matching one (NULL = not multisampling, nothing to do).
@@ -3044,7 +3068,10 @@ void W3DShaderManager::startRenderToTexture(void)
HRESULT hr = DX8Wrapper::_Get_D3D_Device8()->SetRenderTarget(m_newRenderSurface,depthSurface);
DEBUG_ASSERTCRASH(hr==S_OK, ("Set target failed unexpectedly."));
if (hr != S_OK)
+ {
+ rttComplain( "SetRenderTarget(texture) failed" );
return;
+ }
m_renderingToTexture = true;
if (TheGlobalData->m_showSoftWaterEdge)
{ //Soft water edges use frame buffer destination alpha so we must clear it to a known value.
@@ -3076,9 +3103,15 @@ void W3DShaderManager::startRenderToTexture(void)
IDirect3DTexture8 *W3DShaderManager::endRenderToTexture(void)
{
DEBUG_ASSERTCRASH(m_renderingToTexture, ("Not rendering to texture."));
- if (!m_renderingToTexture) return NULL;
+ if (!m_renderingToTexture)
+ {
+ rttComplain( "end without a start" );
+ return NULL;
+ }
HRESULT hr = DX8Wrapper::_Get_D3D_Device8()->SetRenderTarget(m_oldRenderSurface,m_oldDepthSurface); //restore original render target
DEBUG_ASSERTCRASH(hr==S_OK, ("Set target failed unexpectedly."));
+ if (hr != S_OK)
+ rttComplain( "SetRenderTarget(back buffer) failed - the frame is stuck in the texture" );
if (hr == S_OK)
{
//assume render target texure will be in stage 0. Most hardware has "conditional" support for
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp
index 1b9612564..3901abdb6 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp
@@ -1656,6 +1656,24 @@ void W3DView::draw( void )
Bool continueTheEffect = false;
if (preRenderResult) //if prerender passed, do the post render.
continueTheEffect = W3DShaderManager::filterPostRender(m_viewFilter, m_viewFilterMode, deltaScroll,doExtraRender);
+
+ //
+ // A filter that took the scene into a texture and then failed to put it back leaves the
+ // world black under a live UI - the smudge/bloom filter runs on any frame with heat haze
+ // in it, so this is a frame the player sees, not a corner case. Name the filter, rate
+ // limited, so the log says what the eyes only saw.
+ //
+ if (preRenderResult && !continueTheEffect && !skipRender)
+ {
+ static UnsignedInt lastFilterComplaintMs = 0;
+ const UnsignedInt nowMs = timeGetTime();
+ if (lastFilterComplaintMs == 0 || nowMs - lastFilterComplaintMs >= 1000)
+ {
+ lastFilterComplaintMs = nowMs;
+ DEBUG_LOG(("ViewFilter %d mode %d: postRender failed, the scene may not have reached the screen\n",
+ (Int)m_viewFilter, (Int)m_viewFilterMode));
+ }
+ }
if (!skipRender && getCameraLock())
{
Object* cameraLockObj = TheGameLogic->findObjectByID(getCameraLock());
diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cpp
index 0d3f913fa..a41c27c89 100644
--- a/GeneralsMD/Code/Tests/test_gameengine.cpp
+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp
@@ -1741,3 +1741,50 @@ TEST(pathfind_zone_flatten_collapses_a_deep_chain_in_one_pass)
CHECK_EQ( notOne, 0 );
CHECK_EQ( (Int)zones[ 0 ], 0 );
}
+
+/* The two bits of arithmetic behind the command bar's new numbers. Declared here rather than by
+ including ControlBar.h for them: they are free functions in the ControlBar sources, and the
+ header carries the class, not these. */
+extern Int ControlBar_secondsFromFrames( Real frames );
+extern Int ControlBar_experiencePercent( Int currentExp, Int levelExp, Int nextLevelExp );
+
+TEST(controlbar_seconds_round_up_and_never_reach_zero_early)
+{
+ /* nothing left is the only thing that reads as no number at all */
+ CHECK_EQ( ControlBar_secondsFromFrames( 0.0f ), 0 );
+ CHECK_EQ( ControlBar_secondsFromFrames( -5.0f ), 0 );
+
+ /* a whole second is a whole second, at LOGICFRAMES_PER_SECOND to the second */
+ CHECK_EQ( ControlBar_secondsFromFrames( (Real)LOGICFRAMES_PER_SECOND ), 1 );
+ CHECK_EQ( ControlBar_secondsFromFrames( (Real)LOGICFRAMES_PER_SECOND * 6.0f ), 6 );
+ CHECK_EQ( ControlBar_secondsFromFrames( (Real)LOGICFRAMES_PER_SECOND * 120.0f ), 120 );
+
+ /* and anything in between rounds up: 1.1s must not print as 1s and then sit there */
+ CHECK_EQ( ControlBar_secondsFromFrames( (Real)LOGICFRAMES_PER_SECOND + 1.0f ), 2 );
+
+ /* the one that matters - a single frame of work left still says 1s, because a button with
+ work left on it reading 0s looks finished when it is not */
+ CHECK_EQ( ControlBar_secondsFromFrames( 1.0f ), 1 );
+}
+
+TEST(controlbar_experience_percent_fills_the_rank_and_clamps)
+{
+ /* a fresh unit at the bottom of its rank */
+ CHECK_EQ( ControlBar_experiencePercent( 0, 0, 100 ), 0 );
+ CHECK_EQ( ControlBar_experiencePercent( 50, 0, 100 ), 50 );
+ CHECK_EQ( ControlBar_experiencePercent( 99, 0, 100 ), 99 );
+
+ /* the window is between two thresholds, not from zero: half way from 100 to 300 is 50% */
+ CHECK_EQ( ControlBar_experiencePercent( 200, 100, 300 ), 50 );
+
+ /* experience past the next threshold (the level has not been applied yet) pins the bar full
+ rather than overflowing it, and a sink that took points away pins it empty */
+ CHECK_EQ( ControlBar_experiencePercent( 400, 100, 300 ), 100 );
+ CHECK_EQ( ControlBar_experiencePercent( 50, 100, 300 ), 0 );
+
+ /* no next rank to fill towards - top rank, or a template with no thresholds at all - is the
+ "draw no bar" answer, and must not be a division by zero */
+ CHECK_EQ( ControlBar_experiencePercent( 500, 300, 300 ), -1 );
+ CHECK_EQ( ControlBar_experiencePercent( 0, 0, 0 ), -1 );
+ CHECK_EQ( ControlBar_experiencePercent( 10, 300, 100 ), -1 );
+}