Zero Hour rebuilt from EA's source: x64, Direct3D 11, VS2022/CMake, ~60 original bugs fixed, an AI that builds a base. Bring your own game.
C++ cmakecnccommand-and-conquercppdirectx11game-enginegame-preservationgeneralsrtssage-enginex64zero-hour
feat(gameclient): rework the command bar, build grid and placement
Olcay Seygand374bb6b0a39
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/INI.h b/GeneralsMD/Code/GameEngine/Include/Common/INI.hindex 1eef9ee1d..074c0d4cc 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/INI.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/INI.h@@ -228,7 +228,6 @@ public:static void parseSpecialPowerDefinition( INI *ini );static void parseInGameUIDefinition( INI *ini );static void parseControlBarSchemeDefinition( INI *ini );- static void parseControlBarResizerDefinition( INI *ini );static void parseShellMenuSchemeDefinition( INI *ini );static void parseCampaignDefinition( INI *ini );static void parseAudioSettingsDefinition( INI *ini );diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/ControlBar.h b/GeneralsMD/Code/GameEngine/Include/GameClient/ControlBar.hindex 3811fd362..bf8ccc94c 100644--- a/GeneralsMD/Code/GameEngine/Include/GameClient/ControlBar.h+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/ControlBar.h@@ -57,7 +57,6 @@ class PlayerTemplate;class AudioEventRTS;class ControlBarSchemeManager;class UpgradeTemplate;-class ControlBarResizer;class GameWindowTransitionsHandler;class DisplayString;@@ -722,6 +721,13 @@ public:Bool handleChordKey( Int mappableKey );Bool isChordArmed( void ) const { return m_chordGroup >= 0; }+ /** forget a half-typed chord. An armed chord swallows the next A S D F - attack move, stop -+ and turns it into a structure to place, so anything that says the player has moved on+ (a click, a new selection, a key that is not part of the chord, or simply time passing)+ must drop it. */+ void dropChord( void );+ enum { CHORD_TIMEOUT_FRAMES = 60 }; ///< two seconds at 30Hz, then the chord expires+/// is the drawable the currently selected drawable for the context sensitive UI?Bool isDrivingContextUI( Drawable *draw ) const { return draw == m_currentSelectedDrawable; }@@ -782,7 +788,6 @@ public:void populateObserverList( void );Bool isObserverControlBarOn( void ) { return m_isObserverCommandBar;}-// ControlBarResizer *getControlBarResizer( void ) {return m_controlBarResizer;}// Functions for repositioning/resizing the control barvoid switchControlBarStage( ControlBarStages stage );@@ -996,6 +1001,7 @@ protected:Int m_buildPage; ///< BUILD_PAGE_ROOT, or the page being shownObjectID m_buildPageObjectID; ///< builder the page belongs to; a new one starts at the menuInt m_chordGroup; ///< -1, or the structure group (0 = Q, 1 = W) armed by the first chord key+ UnsignedInt m_chordFrame; ///< client frame the chord was armed on, for CHORD_TIMEOUT_FRAMESDrawableID m_standInBuilderID; ///< with nothing selected, the builder whose command bar is shown (INVALID_DRAWABLE_ID otherwise)Drawable *findStandInBuilder( Bool freeOnly ); ///< the local player's free builder (or, unless freeOnly, any builder) to stand in for an empty selection@@ -1120,7 +1126,6 @@ private:UnsignedInt m_lastFrameMarkedDirty;UnsignedInt m_consecutiveDirtyFrames;#endif-// ControlBarResizer *m_controlBarResizer;};diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/ControlBarResizer.h b/GeneralsMD/Code/GameEngine/Include/GameClient/ControlBarResizer.hdeleted file mode 100644index a20f5a6d1..000000000--- a/GeneralsMD/Code/GameEngine/Include/GameClient/ControlBarResizer.h+++ /dev/null@@ -1,107 +0,0 @@-/*-** Command & Conquer Generals Zero Hour(tm)-** Copyright 2025 Electronic Arts Inc.-**-** This program is free software: you can redistribute it and/or modify-** it under the terms of the GNU General Public License as published by-** the Free Software Foundation, either version 3 of the License, or-** (at your option) any later version.-**-** This program is distributed in the hope that it will be useful,-** but WITHOUT ANY WARRANTY; without even the implied warranty of-** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-** GNU General Public License for more details.-**-** You should have received a copy of the GNU General Public License-** along with this program. If not, see <http://www.gnu.org/licenses/>.-*/--////////////////////////////////////////////////////////////////////////////////-// //-// (c) 2001-2003 Electronic Arts Inc. //-// //-////////////////////////////////////////////////////////////////////////////////--// FILE: ControlBarResizer.h /////////////////////////////////////////////////-//------------------------------------------------------------------------------//-// Electronic Arts Pacific.-//-// Confidential Information-// Copyright (C) 2002 - All Rights Reserved-//-//------------------------------------------------------------------------------//-// created: Sep 2002-//-// Filename: ControlBarResizer.h-//-// author: Chris Huybregts-//-// purpose:-//-//------------------------------------------------------------------------------///////////////////////////////////////////////////////////////////////////////--#pragma once--#ifndef __CONTROL_BAR_RESIZER_H_-#define __CONTROL_BAR_RESIZER_H_--//------------------------------------------------------------------------------// SYSTEM INCLUDES ////////////////////////////////////////////////////////////-//-------------------------------------------------------------------------------//------------------------------------------------------------------------------// USER INCLUDES //////////////////////////////////////////////////////////////-//-------------------------------------------------------------------------------//------------------------------------------------------------------------------// FORWARD REFERENCES /////////////////////////////////////////////////////////-//-------------------------------------------------------------------------------//------------------------------------------------------------------------------// TYPE DEFINES ///////////////////////////////////////////////////////////////-//------------------------------------------------------------------------------class ResizerWindow-{-public:-ResizerWindow( void );- AsciiString m_name;- ICoord2D m_defaultSize;- ICoord2D m_defaultPos;- ICoord2D m_altSize;- ICoord2D m_altPos;-};--class ControlBarResizer-{-public:- ControlBarResizer( void );- ~ControlBarResizer( void );-- void init( void );-- // parse Functions for the INI file- const FieldParse *getFieldParse() const { return m_controlBarResizerParseTable; } ///< returns the parsing fields- static const FieldParse m_controlBarResizerParseTable[]; ///< the parse table-- ResizerWindow *findResizerWindow( AsciiString name ); ///< attempt to find the control bar scheme by it's name- ResizerWindow *newResizerWindow( AsciiString name ); ///< create a new control bar scheme and return it.-- void sizeWindowsDefault( void );- void sizeWindowsAlt( void );-- typedef std::list< ResizerWindow *> ResizerWindowList;- ResizerWindowList m_resizerWindowsList;--};-//------------------------------------------------------------------------------// INLINING ///////////////////////////////////////////////////////////////////-//-------------------------------------------------------------------------------//------------------------------------------------------------------------------// EXTERNALS //////////////////////////////////////////////////////////////////-//-------------------------------------------------------------------------------#endif // __CONTROL_BAR_RESIZER_H_diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/GadgetPushButton.h b/GeneralsMD/Code/GameEngine/Include/GameClient/GadgetPushButton.hindex e30e3f70b..13670b9e0 100644--- a/GeneralsMD/Code/GameEngine/Include/GameClient/GadgetPushButton.h+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/GadgetPushButton.h@@ -78,6 +78,7 @@ void GadgetButtonEnableCheckLike( GameWindow *g, Bool makeCheckLike, Bool initiavoid GadgetButtonSetText( GameWindow *g, UnicodeString text );void GadgetButtonDrawClock( GameWindow *g, Int percent, Color color ); //Darkens the progress+void GadgetButtonClearClock( GameWindow *g ); //Takes the clock back off, see GadgetButtonDrawClockvoid GadgetButtonDrawInverseClock( GameWindow *g, Int percent, Color color ); //Darkens the remaining portion.void GadgetButtonDrawOverlayImage( GameWindow *g, const Image *image );void GadgetButtonSetBorder( GameWindow *g, Color color, Bool drawBorder = TRUE );diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/InGameUI.h b/GeneralsMD/Code/GameEngine/Include/GameClient/InGameUI.hindex f98fc81af..c6e8be62f 100644--- a/GeneralsMD/Code/GameEngine/Include/GameClient/InGameUI.h+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/InGameUI.h@@ -758,7 +758,12 @@ protected:void drawFloatingText( void ); ///< Draw all our floating textvoid clearFloatingText( void ); ///< clear the floating text list- virtual void drawBuildGrid( void ) { } ///< the pathfinder's build grid under a pending structure+public:+ /** The pathfinder's build grid under a pending structure. Public and called from the terrain+ * renderer rather than from preDraw: it is geometry lying on the ground, and it has to go down+ * with the terrain so that everything drawn after the terrain covers it. */+ virtual void drawBuildGrid( void ) { }+protected:void clearWorldAnimations( void ); ///< delete all world animationsvoid updateAndDrawWorldAnimations( void ); ///< update and draw visible world animations@@ -834,6 +839,12 @@ protected:UnsignedInt m_hudLastSampleFrame; ///< client frame the fps sample was last refreshed onUnsignedInt m_hudLastSampleMs; ///< wall clock of that sampleReal m_hudFps; ///< smoothed render rate+ // A script time freeze stops the logic clock, and the military subtitle's counters are+ // logic frames, so they have to be stepped by hand while it lasts. These two turn the+ // wall clock into that step without drift: every update works out how many 30Hz frames+ // have passed since the freeze began and applies only the ones not applied yet.+ UnsignedInt m_subtitleFreezeStartMs; ///< wall clock the current freeze started on, 0 = not frozen+ UnsignedInt m_subtitleFreezeSteps; ///< frames already handed to the subtitle during it// Income is sampled from the player's cumulative earnings every INCOME_SAMPLE_SECONDS and// averaged over the whole ring, so a lumpy supply run reads as a rate instead of a spike.enum { INCOME_SAMPLES = 16, INCOME_SAMPLE_SECONDS = 2 }; ///< 16 buckets of 2s = a 30s window@@ -945,6 +956,10 @@ protected:Bool m_attackMoveToMode; ///< are we in attack move mode?Bool m_preferSelection; ///< the shift key has been depressed.+ // wall clock of the previous update(), so a held camera key can be stepped by elapsed+ // time instead of by render frames. 0 = no previous update yet.+ UnsignedInt m_cameraKeyLastMs;+Bool m_cameraRotatingLeft;Bool m_cameraRotatingRight;Bool m_cameraZoomingIn;diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/View.h b/GeneralsMD/Code/GameEngine/Include/GameClient/View.hindex cf80ffa81..2aeed5171 100644--- a/GeneralsMD/Code/GameEngine/Include/GameClient/View.h+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/View.h@@ -182,8 +182,8 @@ public:virtual void setZoom(Real z) { }virtual Real getHeightAboveGround() { return m_heightAboveGround; }virtual void setHeightAboveGround(Real z) { m_heightAboveGround = z; }- virtual void zoomIn( void ); ///< Zoom in, closer to the ground, limit to min- virtual void zoomOut( void ); ///< Zoom out, farther away from the ground, limit to max+ virtual void zoomIn( Real steps = 1.0f ); ///< Zoom in, closer to the ground, limit to min+ virtual void zoomOut( Real steps = 1.0f ); ///< Zoom out, farther away from the ground, limit to maxvirtual void setZoomToDefault( void ) { } ///< Set zoom to default valuevirtual void setZoomToMax( void ) { } ///< Set zoom as far out as the player may zoom by handvirtual Real getMaxZoom( void ) { return m_maxZoom; } ///< return max zoom valuediff --git a/GeneralsMD/Code/GameEngine/Source/Common/INI/INI.cpp b/GeneralsMD/Code/GameEngine/Source/Common/INI/INI.cppindex bfcba1609..ca50b0d59 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/INI/INI.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/INI/INI.cpp@@ -96,7 +96,6 @@ static const BlockParse theTypeTable[] ={ "CommandMap", INI::parseMetaMapDefinition },{ "CommandSet", INI::parseCommandSetDefinition },{ "ControlBarScheme", INI::parseControlBarSchemeDefinition },- { "ControlBarResizer", INI::parseControlBarResizerDefinition },{ "CrateData", INI::parseCrateTemplateDefinition },{ "Credits", INI::parseCredits},{ "WindowTransition", INI::parseWindowTransitions},diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cppindex 2e01d7622..37a102266 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp@@ -81,7 +81,6 @@ static Bool builderIsFree( AIUpdateInterface *ai, DozerAIInterface *dozer ); //#include "GameClient/GadgetTextEntry.h"#include "GameClient/InGameUI.h"#include "GameClient/WindowVideoManager.h"-#include "GameClient/ControlBarResizer.h"#include "GameClient/GadgetListBox.h"#include "GameClient/HotKey.h"#include "GameClient/Keyboard.h"@@ -174,13 +173,15 @@ void ControlBar::pressCommandButton( Int index )if( index == CHORD_SLOT_Q || index == CHORD_SLOT_W ){m_chordGroup = ( index == CHORD_SLOT_Q ) ? 0 : 1;+ m_chordFrame = TheGameClient ? TheGameClient->getFrame() : 0;+ markUIDirty(); // the group that is armed greys the other one outreturn;}}else{Int group = m_chordGroup;- m_chordGroup = -1;+ dropChord();if( index >= CHORD_GROUP_SIZE )return; // the second key must be one of the first group's cells (Q W E R A S D F)index += group * CHORD_GROUP_SIZE;@@ -235,12 +236,31 @@ Bool ControlBar::handleChordKey( Int mappableKey )}}- // any other key is not ours; a grid key of another cell drops the chord in- // pressCommandButton, a context change drops it in switchToContext+ //+ // Any other key means the player is done with the chord, so drop it and let the key through.+ // It used to be left armed: nothing in the game cleared it except another grid key or a+ // context change, so a Q pressed and thought better of stayed armed for the rest of the+ // game and the next A or S - attack move, stop - silently became "place this structure",+ // which took the selection away and looked like the click had been eaten.+ //+ dropChord();return FALSE;} // end handleChordKey+//-------------------------------------------------------------------------------------------------+/** Forget a half-typed structure chord. */+//-------------------------------------------------------------------------------------------------+void ControlBar::dropChord( void )+{+ if( m_chordGroup < 0 )+ return;++ m_chordGroup = -1;+ markUIDirty(); // the greyed-out half of the structures comes back++} // end dropChord+//-------------------------------------------------------------------------------------------------/** Build the menu and back buttons a paged builder shows. They carry no thing template and notext label of their own - the page they open is told by the cameo of its first structure, and@@ -1039,7 +1059,6 @@ ControlBar::ControlBar( void )m_genStarOn = NULL;m_UIDirty = FALSE;//-// m_controlBarResizer = NULL;m_buildUpClockColor = GameMakeColor(0,0,0,100);m_commandBarBorderColor = GameMakeColor(0,0,0,100);for( i = 0; i < NUM_CONTEXT_PARENTS; i++ )@@ -1079,6 +1098,7 @@ ControlBar::ControlBar( void )m_buildPageButton[ i ] = NULL;m_buildPageBackButton = NULL;m_chordGroup = -1;+ m_chordFrame = 0;m_standInBuilderID = INVALID_DRAWABLE_ID;for( i = 0; i < MAX_MULTI_SELECT_GROUPS; i++ ){@@ -1159,9 +1179,6 @@ ControlBar::~ControlBar( void )delete m_controlBarSchemeManager;m_controlBarSchemeManager = NULL;-// if(m_controlBarResizer)-// delete m_controlBarResizer;-// m_controlBarResizer = NULL;// destroy all the command set definitionsCommandSet *set;while( m_commandSets )@@ -1451,9 +1468,6 @@ void ControlBar::init( void )m_rankHeroicIcon = TheMappedImageCollection ? TheMappedImageCollection->findImageByName( "SSChevron3L" ) : NULL;-// if(!m_controlBarResizer)-// m_controlBarResizer = NEW ControlBarResizer;-// m_controlBarResizer->init();@@ -1563,8 +1577,37 @@ void ControlBar::reset( void )//-------------------------------------------------------------------------------------------------void ControlBar::update( void ){- getStarImage();- updateRadarAttackGlow();+ //+ // This is driven by the client, once per RENDER frame, but nearly everything it recomputes -+ // button availability, build clocks, special power readiness, the general's star flash - is+ // keyed to the LOGIC frame and cannot change twice inside one tick. With the renderer+ // uncapped that was several whole passes per tick for nothing, and updateRadarAttackGlow()+ // was actively wrong: it burns one frame off its own countdown per call, so the "under+ // attack" radar glow blinked (fps/30)x too fast and went dark early. Latch that work to the+ // logic frame. The scheme/video/animation managers and the window runUpdate()s below really+ // are per-render and stay outside the latch, and so does anything the UI marks dirty, which+ // must still answer a selection change on the frame it happens. See FINDINGS.md 7.4.+ //+ static UnsignedInt s_lastUpdateFrame = 0xffffffff;+ const UnsignedInt logicNow = TheGameLogic->getFrame();+ const Bool logicTick = (logicNow != s_lastUpdateFrame);+ s_lastUpdateFrame = logicNow;++ if( logicTick )+ {+ getStarImage();+ updateRadarAttackGlow();+ }++ //+ // a chord the player armed and then walked away from expires on its own, so it cannot be+ // waiting to eat a keystroke a minute later+ //+ if( m_chordGroup >= 0 && TheGameClient &&+ TheGameClient->getFrame() - m_chordFrame > CHORD_TIMEOUT_FRAMES )+ {+ dropChord();+ }if(m_controlBarSchemeManager)m_controlBarSchemeManager->update();@@ -1611,18 +1654,16 @@ void ControlBar::update( void )hideBuildTooltipLayout();}*/- updateSpecialPowerShortcut();+ // walks every shortcut button and asks the player for its most ready special power object+ if( logicTick )+ updateSpecialPowerShortcut();// if we're an observer, don't do the complete updateif( m_isObserverCommandBar){- // same per-render-frame retrigger as the flash above: once per logic frame is enough- static UnsignedInt s_lastObserverFrame = 0xffffffff;- const UnsignedInt observerNow = TheGameLogic->getFrame();- if( (observerNow % (LOGICFRAMES_PER_SECOND/2)) == 0 && observerNow != s_lastObserverFrame )- {- s_lastObserverFrame = observerNow;+ // twice a second is plenty for the observer readouts, and only on a real logic tick -+ // a bare "frame % n == 0" fires on every render frame that lands inside that one tick+ if( logicTick && (logicNow % (LOGICFRAMES_PER_SECOND/2)) == 0 )populateObserverInfoWindow();- }Drawable *drawToEvaluateFor = NULL;Bool multiSelect = FALSE;@@ -1646,16 +1687,7 @@ void ControlBar::update( void )}- //- // ControlBar::update runs once per RENDER frame, so a bare "getFrame() % 10 == 0" fires on- // every render frame that lands inside that one logic frame - the flash count then burned- // down several times per tick and the button stopped flashing early. Latch it to the frame.- //- static UnsignedInt s_lastFlashFrame = 0xffffffff;- const UnsignedInt flashNow = TheGameClient->getFrame();- const Bool flashTick = (flashNow % 10 == 0) && (flashNow != s_lastFlashFrame);- if( flashTick )- s_lastFlashFrame = flashNow;+ const Bool flashTick = logicTick && (logicNow % 10 == 0);// check flashingif( m_flash )@@ -1730,6 +1762,7 @@ void ControlBar::update( void )// first, if the UI is dirty repopulate the UI with what the user should see for all the// selected drawables//+ const Bool wasUIDirty = m_UIDirty;if( m_UIDirty ){evaluateContextUI();@@ -1738,6 +1771,12 @@ void ControlBar::update( void )repopulateBuildTooltipLayout();}+ // nothing below here can change without either a logic tick or a rebuilt UI, and the rest+ // of it is the expensive half: a full object count for the beacon cap and then a pass over+ // every command button in the current context+ if( !logicTick && !wasUIDirty )+ return;+// enable/disable the beacon button depending on if the max has been reachedif (ThePlayerList && ThePlayerList->getLocalPlayer() && ThePlayerList->getLocalPlayer()->getPlayerTemplate()){@@ -2384,6 +2423,7 @@ Bool ControlBar::cancelQueuedUpgrade( const UpgradeTemplate *upgrade )if( upgrade == NULL )return FALSE;+ Bool cancelled = FALSE;const DrawableList *selected = TheInGameUI->getAllSelectedDrawables();for( DrawableListCIt it = selected->begin(); it != selected->end(); ++it ){@@ -2399,10 +2439,12 @@ Bool ControlBar::cancelQueuedUpgrade( const UpgradeTemplate *upgrade )GameMessage *msg = TheMessageStream->appendMessage( GameMessage::MSG_CANCEL_UPGRADE );msg->appendIntegerArgument( upgrade->getUpgradeNameKey() );msg->appendObjectIDArgument( candidate->getID() );- return TRUE;+ cancelled = TRUE;+ // an object upgrade is bought per building and one click buys it for the whole selection,+ // so one click takes it back off the whole selection too - keep going}- return FALSE;+ return cancelled;} // end cancelQueuedUpgrade@@ -2590,7 +2632,7 @@ void ControlBar::switchToContext( ControlBarContext context, Drawable *draw )m_currentSelectedDrawable = draw;// a half-typed structure chord does not survive a context change- m_chordGroup = -1;+ dropChord();if (IsInGameChatActive() == FALSE && TheGameLogic && !TheGameLogic->isInShellGame()) {TheWindowManager->winSetFocus( NULL );@@ -3562,11 +3604,6 @@ void ControlBar::switchControlBarStage( ControlBarStages stage )}void ControlBar::setDefaultControlBarConfig( void ){-// if(m_currentControlBarStage == CONTROL_BAR_STAGE_SQUISHED)-// {-// m_controlBarResizer->sizeWindowsDefault();-// m_controlBarSchemeManager->setControlBarSchemeByPlayerTemplate(ThePlayerList->getLocalPlayer()->getPlayerTemplate(), FALSE);-// }m_currentControlBarStage = CONTROL_BAR_STAGE_DEFAULT;TheTacticalView->setHeight((Int)(TheDisplay->getHeight() * 0.80f));m_contextParent[ CP_MASTER ]->winSetPosition(m_defaultControlBarPosition.x, m_defaultControlBarPosition.y);@@ -3583,7 +3620,6 @@ void ControlBar::setSquishedControlBarConfig( void )m_currentControlBarStage = CONTROL_BAR_STAGE_SQUISHED;m_contextParent[ CP_MASTER ]->winSetPosition(m_defaultControlBarPosition.x, m_defaultControlBarPosition.y);-// m_controlBarResizer->sizeWindowsAlt();repopulateBuildTooltipLayout();TheTacticalView->setHeight((Int)(TheDisplay->getHeight()));m_controlBarSchemeManager->setControlBarSchemeByPlayerTemplate(ThePlayerList->getLocalPlayer()->getPlayerTemplate(), TRUE);@@ -3591,11 +3627,6 @@ void ControlBar::setSquishedControlBarConfig( void )void ControlBar::setLowControlBarConfig( void ){-// if(m_currentControlBarStage == CONTROL_BAR_STAGE_SQUISHED)-// {-// m_controlBarResizer->sizeWindowsDefault();-// m_controlBarSchemeManager->setControlBarSchemeByPlayerTemplate(ThePlayerList->getLocalPlayer()->getPlayerTemplate(), FALSE);-// }m_currentControlBarStage = CONTROL_BAR_STAGE_LOW;ICoord2D pos;@@ -4136,6 +4167,8 @@ void ControlBar::updateSpecialPowerShortcut( void )if( command == NULL )continue;+ // the clock is no longer eaten by the draw, so take last pass's off first+ GadgetButtonClearClock( win );win->winClearStatus( WIN_STATUS_NOT_READY );win->winClearStatus( WIN_STATUS_ALWAYS_COLOR );diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommand.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommand.cppindex 82982009b..794fc2ac1 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommand.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommand.cpp@@ -71,6 +71,45 @@static GameWindow *commandWindows[ MAX_COMMANDS_PER_SET ];Bool commandWindowsInitialized = FALSE;static Color BuildClockColor = GameMakeColor(0,0,0,120); ///< translucent black radial fill drawn over the cameo as production progresses++//-------------------------------------------------------------------------------------------------+/** 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+ * one that has progress to show), and NULL when it is merely waiting its turn. */+//-------------------------------------------------------------------------------------------------+static Bool findUpgradeInSelection( const UpgradeTemplate *upgrade, const ProductionEntry **head )+{+ if( head )+ *head = NULL;++ if( upgrade == NULL || TheInGameUI == NULL || ThePlayerList == NULL )+ return FALSE;++ Bool found = FALSE;+ const DrawableList *selected = TheInGameUI->getAllSelectedDrawables();+ for( DrawableListCIt it = selected->begin(); it != selected->end(); ++it )+ {+ Object *obj = (*it)->getObject();+ if( obj == NULL || obj->getControllingPlayer() != ThePlayerList->getLocalPlayer() )+ continue;++ ProductionUpdateInterface *pu = obj->getProductionUpdateInterface();+ if( pu == NULL || pu->isUpgradeInQueue( upgrade ) == FALSE )+ continue;++ found = TRUE;++ const ProductionEntry *first = pu->firstProduction();+ if( head && first && first->getProductionType() == PRODUCTION_UPGRADE &&+ first->getProductionUpgrade() == upgrade )+ {+ *head = first;+ break; // this one is actually working on it, no better answer to be had+ }+ }++ return found;+}// STATIC DATA STORAGE ////////////////////////////////////////////////////////////////////////////ControlBar::ContainEntry ControlBar::m_containData[ MAX_COMMANDS_PER_SET ];@@ -698,6 +737,12 @@ void ControlBar::updateContextCommand( void )if( command == NULL )continue;+ //+ // the clock survives until it is taken off, so every pass starts with a clean button and+ // whatever is still running below puts its own clock back on+ //+ GadgetButtonClearClock( win );+//// a unit build button wears its own queue: a radial fill over the cameo while its unit// is the one being built, and a corner badge with how many of it are queued@@ -732,19 +777,23 @@ void ControlBar::updateContextCommand( void )}//- // an upgrade button wears the same radial fill while its upgrade is the one the building is- // researching. An upgrade is never queued twice, so there is no count badge to go with it.- // The button is disabled for the duration - getCommandAvailability refuses an upgrade that- // is already in production - and the clock draws over the disabled state too.+ // 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+ // to go with it. The producer is looked for across the whole selection, not just on the+ // representative: with four barracks selected the one actually paying for the upgrade is+ // rarely the one the bar is drawn from, and the button showed no progress at all.//- if( ( command->getCommandType() == GUI_COMMAND_PLAYER_UPGRADE ||- command->getCommandType() == GUI_COMMAND_OBJECT_UPGRADE ) &&- pu && m_currContext != CB_CONTEXT_MULTI_SELECT )+ Bool upgradeQueuedHere = FALSE;+ if( command->getCommandType() == GUI_COMMAND_PLAYER_UPGRADE ||+ command->getCommandType() == GUI_COMMAND_OBJECT_UPGRADE ){- const ProductionEntry *first = pu->firstProduction();- if( first && first->getProductionType() == PRODUCTION_UPGRADE &&- first->getProductionUpgrade() == command->getUpgradeTemplate() )- GadgetButtonDrawClock( win, first->getPercentComplete(), BuildClockColor );+ const ProductionEntry *entry = NULL;+ if( findUpgradeInSelection( command->getUpgradeTemplate(), &entry ) )+ {+ upgradeQueuedHere = TRUE;+ if( entry )+ GadgetButtonDrawClock( win, entry->getPercentComplete(), BuildClockColor );+ }}// a structure outside the armed chord group greys out until the chord resolves@@ -797,6 +846,19 @@ void ControlBar::updateContextCommand( void )break;}+ //+ // The button an upgrade is cancelled from is the button that upgrade is bought from, and a+ // disabled window never sees a mouse message at all (GameWindow::winPointInChild skips it),+ // so the one thing you could not right-click was the upgrade you wanted to take back.+ // Leave it enabled and merely colourless while it is being researched; a left click on it+ // costs nothing, ProductionUpdate::queueUpgrade refuses to queue the same upgrade twice.+ //+ if( upgradeQueuedHere && availability != COMMAND_HIDDEN )+ {+ win->winEnable( TRUE );+ win->winSetStatus( WIN_STATUS_ALWAYS_COLOR );+ }+// while a chord is armed, the structures of its group that can be built right now wear// a green border - those are what the next key picks; otherwise the command's own borderif( command->getCommandType() == GUI_COMMAND_DOZER_CONSTRUCT )diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommandProcessing.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommandProcessing.cppindex 75e4f13be..042202e8a 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommandProcessing.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommandProcessing.cpp@@ -649,6 +649,55 @@ CBCommandStatus ControlBar::processCommandUI( GameWindow *control,}}+ //+ // An object upgrade is bought per building, so with several selected the click is+ // spread over all of them that still want it and that the player can pay for, in+ // selection order. It used to go to one object only - and to the same one every+ // time, since the bar cannot see the queue the previous click just filled until the+ // next logic frame - so a click on four selected barracks upgraded one of them and+ // the other three clicks were silently thrown away by the duplicate guard in+ // ProductionUpdate::queueUpgrade.+ //+ if( m_currContext == CB_CONTEXT_MULTI_SELECT )+ {+ Player *player = ThePlayerList->getLocalPlayer();+ Int purse = player->getMoney()->countMoney();+ Int cost = upgradeT->calcCostToBuild( player );+ Int sent = 0;++ const DrawableList *selected = TheInGameUI->getAllSelectedDrawables();+ for( DrawableListCIt it = selected->begin(); it != selected->end(); ++it )+ {+ Object *target = (*it)->getObject();+ if( target == NULL || target->getControllingPlayer() != player )+ continue;++ ProductionUpdateInterface *tpu = target->getProductionUpdateInterface();+ if( tpu == NULL || tpu->canQueueUpgrade( upgradeT ) != CANMAKE_OK )+ continue;++ if( target->hasUpgrade( upgradeT ) == TRUE ||+ target->affectedByUpgrade( upgradeT ) == FALSE ||+ tpu->isUpgradeInQueue( upgradeT ) == TRUE ||+ target->canProduceUpgrade( upgradeT ) == FALSE )+ continue;++ // the logic charges each one as it queues it, so stop at what is in the bank+ if( cost > 0 && purse < cost )+ break;+ purse -= cost;++ GameMessage *msg = TheMessageStream->appendMessage( GameMessage::MSG_QUEUE_UPGRADE );+ msg->appendObjectIDArgument( target->getID() );+ msg->appendIntegerArgument( upgradeT->getUpgradeNameKey() );+ sent++;+ }++ if( sent > 0 )+ break;+ // nobody in the selection could take it; fall through to the single-object path+ }+ObjectID objID = INVALID_ID;if (obj)objID = obj->getID();diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarPrintPositions.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarPrintPositions.cppdeleted file mode 100644index 7cf44e1ff..000000000--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarPrintPositions.cpp+++ /dev/null@@ -1,105 +0,0 @@-/*-** Command & Conquer Generals Zero Hour(tm)-** Copyright 2025 Electronic Arts Inc.-**-** This program is free software: you can redistribute it and/or modify-** it under the terms of the GNU General Public License as published by-** the Free Software Foundation, either version 3 of the License, or-** (at your option) any later version.-**-** This program is distributed in the hope that it will be useful,-** but WITHOUT ANY WARRANTY; without even the implied warranty of-** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-** GNU General Public License for more details.-**-** You should have received a copy of the GNU General Public License-** along with this program. If not, see <http://www.gnu.org/licenses/>.-*/--////////////////////////////////////////////////////////////////////////////////-// //-// (c) 2001-2003 Electronic Arts Inc. //-// //-////////////////////////////////////////////////////////////////////////////////--// FILE: ControlBarPrintPositions.cpp /////////////////////////////////////////////////-//------------------------------------------------------------------------------//-// Electronic Arts Pacific.-//-// Confidential Information-// Copyright (C) 2002 - All Rights Reserved-//-//------------------------------------------------------------------------------//-// created: Sep 2002-//-// Filename: ControlBarPrintPositions.cpp-//-// author: Chris Huybregts-//-// purpose: Convience function for degayifying the whole squished control bar-// process-//-//------------------------------------------------------------------------------///////////////////////////////////////////////////////////////////////////////--//------------------------------------------------------------------------------// SYSTEM INCLUDES ////////////////////////////////////////////////////////////-//------------------------------------------------------------------------------#include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine-#include <stdio.h>-//------------------------------------------------------------------------------// USER INCLUDES //////////////////////////////////////////////////////////////-//------------------------------------------------------------------------------#include "GameClient/GameWindowManager.h"-#include "GameClient/WindowLayout.h"-//------------------------------------------------------------------------------// DEFINES ////////////////////////////////////////////////////////////////////-//-------------------------------------------------------------------------------//------------------------------------------------------------------------------// PUBLIC FUNCTIONS ///////////////////////////////////////////////////////////-//------------------------------------------------------------------------------void PrintInfoRecursive( GameWindow *win, FILE *fp)-{- if(!win)- return;- ICoord2D pos, size;- win->winGetSize(&size.x, &size.y);- win->winGetPosition(&pos.x, &pos.y);- fprintf(fp, "ControlBarResizer %s\n",win->winGetInstanceData()->m_decoratedNameString.str());- fprintf(fp, " AltPosition = X:%d Y:%d\n",pos.x, pos.y);- fprintf(fp, " AltSize = X:%d Y:%d\n",size.x, size.y);- fprintf(fp, "END\n\n");-- PrintInfoRecursive(win->winGetChild(),fp);- PrintInfoRecursive(win->winGetNext(),fp);--}--void PrintOffsetsFromControlBarParent( void )-{- GameWindow *controlBarParent = TheWindowManager->winGetWindowFromId( NULL, TheNameKeyGenerator->nameToKey( "ControlBar.wnd:ControlBarParent" ));- if(!controlBarParent)- return;-- WindowLayout *layout = TheWindowManager->winCreateLayout("controlBarHidden.wnd");- if(!layout)- return;- FILE *fp = fopen("ControlBarEasier.txt", "w");- if(!fp)- return;-- PrintInfoRecursive(layout->getFirstWindow(), fp);-- fclose(fp);- layout->destroyWindows();- layout->deleteInstance();-}---//------------------------------------------------------------------------------// PRIVATE FUNCTIONS //////////////////////////////////////////////////////////-//------------------------------------------------------------------------------diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarResizer.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarResizer.cppdeleted file mode 100644index 31a721ada..000000000--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarResizer.cpp+++ /dev/null@@ -1,245 +0,0 @@-/*-** Command & Conquer Generals Zero Hour(tm)-** Copyright 2025 Electronic Arts Inc.-**-** This program is free software: you can redistribute it and/or modify-** it under the terms of the GNU General Public License as published by-** the Free Software Foundation, either version 3 of the License, or-** (at your option) any later version.-**-** This program is distributed in the hope that it will be useful,-** but WITHOUT ANY WARRANTY; without even the implied warranty of-** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-** GNU General Public License for more details.-**-** You should have received a copy of the GNU General Public License-** along with this program. If not, see <http://www.gnu.org/licenses/>.-*/--////////////////////////////////////////////////////////////////////////////////-// //-// (c) 2001-2003 Electronic Arts Inc. //-// //-////////////////////////////////////////////////////////////////////////////////--// FILE: ControlBarResizer.cpp /////////////////////////////////////////////////-//------------------------------------------------------------------------------//-// Electronic Arts Pacific.-//-// Confidential Information-// Copyright (C) 2002 - All Rights Reserved-//-//------------------------------------------------------------------------------//-// created: Sep 2002-//-// Filename: ControlBarResizer.cpp-//-// author: Chris Huybregts-//-// purpose: We want a "squished" control bar, this is the methods that will do it-//-//------------------------------------------------------------------------------///////////////////////////////////////////////////////////////////////////////--//------------------------------------------------------------------------------// SYSTEM INCLUDES ////////////////////////////////////////////////////////////-//------------------------------------------------------------------------------#include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine-//------------------------------------------------------------------------------// USER INCLUDES //////////////////////////////////////////////////////////////-//------------------------------------------------------------------------------#include "GameClient/ControlBar.h"-#include "GameClient/ControlBarResizer.h"-#include "GameClient/GameWindow.h"-#include "GameClient/GameWindowManager.h"-#include "GameClient/Display.h"-//------------------------------------------------------------------------------// DEFINES ////////////////////////////////////////////////////////////////////-//-------------------------------------------------------------------------------const FieldParse ControlBarResizer::m_controlBarResizerParseTable[] =-{- { "AltPosition", INI::parseICoord2D, NULL, offsetof( ResizerWindow, m_altPos ) },- { "AltSize", INI::parseICoord2D, NULL, offsetof( ResizerWindow, m_altSize ) },- { NULL, NULL, NULL, 0 } // keep this last--};-//------------------------------------------------------------------------------// PUBLIC FUNCTIONS ///////////////////////////////////////////////////////////-//-------------------------------------------------------------------------------ResizerWindow::ResizerWindow(void)-{- m_defaultPos.x = m_defaultPos.y = 0;- m_defaultSize.x = m_defaultSize.y = 0;- m_altSize.x = m_altSize.y = 0;- m_altPos.x = m_altPos.y = 0;-}--ControlBarResizer::ControlBarResizer( void )-{--}-ControlBarResizer::~ControlBarResizer( void )-{- ResizerWindowList::iterator it = m_resizerWindowsList.begin();- while (it != m_resizerWindowsList.end())- {- ResizerWindow *rWin = *it;- if( !rWin )- {- it = m_resizerWindowsList.erase(it);- continue;- }- delete rWin;- it = m_resizerWindowsList.erase(it);- }- m_resizerWindowsList.clear();-}--void ControlBarResizer::init( void )-{- INI ini;- // Read from INI all the ControlBarSchemes- ini.load( AsciiString( "Data\\INI\\ControlBarResizer.ini" ), INI_LOAD_OVERWRITE, NULL );--}---ResizerWindow *ControlBarResizer::findResizerWindow( AsciiString name )-{- ResizerWindowList::iterator it = m_resizerWindowsList.begin();-- while (it != m_resizerWindowsList.end())- {- ResizerWindow *rWin = *it;- if( !rWin )- {- DEBUG_ASSERTCRASH(FALSE,("There's no resizerWindow in ControlBarResizer::findResizerWindow"));- it++;- continue;- }- // find the scheme that best matches our resolution- if(rWin->m_name.compare(name) == 0)- {- return rWin;- }- it ++;- }- return NULL;-}--ResizerWindow *ControlBarResizer::newResizerWindow( AsciiString name )-{- ResizerWindow *newRwin = NEW ResizerWindow;- if(!newRwin)- return NULL;-- newRwin->m_name = name;- GameWindow *win = NULL;- win = TheWindowManager->winGetWindowFromId(NULL, TheNameKeyGenerator->nameToKey(name));- if( !win )- {- DEBUG_ASSERTCRASH(win,("ControlBarResizer::newResizerWindow could not find window %s Are you sure that window is loaded yet?", name.str()) );- delete newRwin;- return NULL;- }- win->winGetPosition(&newRwin->m_defaultPos.x,&newRwin->m_defaultPos.y);- win->winGetSize(&newRwin->m_defaultSize.x,&newRwin->m_defaultSize.y);- m_resizerWindowsList.push_back(newRwin);- return newRwin;-}-void ControlBarResizer::sizeWindowsDefault( void )-{- ResizerWindowList::iterator it = m_resizerWindowsList.begin();- GameWindow *win = NULL;- while (it != m_resizerWindowsList.end())- {- ResizerWindow *rWin = *it;- if( !rWin )- {- DEBUG_ASSERTCRASH(FALSE,("There's no resizerWindow in ControlBarResizer::sizeWindowsDefault"));- it++;- continue;- }- win = TheWindowManager->winGetWindowFromId(NULL, TheNameKeyGenerator->nameToKey(rWin->m_name));- if(!win)- {- it++;- continue;- }- win->winSetPosition(rWin->m_defaultPos.x, rWin->m_defaultPos.y);- win->winSetSize(rWin->m_defaultSize.x, rWin->m_defaultSize.y);- DEBUG_LOG(("sizeWindowsDefault:%s pos X:%d pos Y: %d size X:%d sizeY: %d",rWin->m_name.str(),rWin->m_defaultPos.x, rWin->m_defaultPos.y,rWin->m_defaultSize.x, rWin->m_defaultSize.y ));- it ++;- }-}-void ControlBarResizer::sizeWindowsAlt( void )-{- ResizerWindowList::iterator it = m_resizerWindowsList.begin();- GameWindow *win = NULL;- Real x = (Real)TheDisplay->getWidth() / 800;- Real y = (Real)TheDisplay->getHeight() / 600;- while (it != m_resizerWindowsList.end())- {- ResizerWindow *rWin = *it;- if( !rWin )- {- DEBUG_ASSERTCRASH(FALSE,("There's no resizerWindow in ControlBarResizer::sizeWindowsDefault"));- it++;- continue;- }- win = TheWindowManager->winGetWindowFromId(NULL, TheNameKeyGenerator->nameToKey(rWin->m_name));- if(!win)- {- it++;- continue;- }-- win->winSetPosition(rWin->m_altPos.x * x, rWin->m_altPos.y * y);- if(rWin->m_altSize.x >0 || rWin->m_altSize.y > 0)- win->winSetSize(rWin->m_altSize.x *x, rWin->m_altSize.y *y);- DEBUG_LOG(("sizeWindowsAlt:%s pos X:%d pos Y: %d size X:%d sizeY: %d",rWin->m_name.str(), rWin->m_altPos.x*x, rWin->m_altPos.y*y,rWin->m_altSize.x*x, rWin->m_altSize.y *y));- it ++;- }-}---void INI::parseControlBarResizerDefinition( INI* ini )-{-// AsciiString name;-// ResizerWindow *rWin = NULL;-//-// // read the name-// const char* c = ini->getNextToken();-// name.set( c );-//-//// ControlBarResizer *resizer = TheControlBar->getControlBarResizer();-// if( !resizer )-// {-// //We don't need it if we're in the builder... which doesn't have this.-// return;-// }-// rWin = resizer->findResizerWindow( name );-// if( rWin == NULL )-// {-//-// // image not found, create a new one-// rWin = resizer->newResizerWindow(name);-// DEBUG_ASSERTCRASH( rWin, ("parseControlBarResizerDefinition: unable to allocate ResizerWindow for '%s'\n",-// name.str()) );-//-// } // end if-//-// // parse the ini definition-// ini->initFromINI( rWin, resizer->getFieldParse());-//-} // end parseMappedImage---//------------------------------------------------------------------------------// PRIVATE FUNCTIONS //////////////////////////////////////////////////////////-//------------------------------------------------------------------------------diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MainMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MainMenu.cppindex 4193a3e6b..41ca16bb2 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MainMenu.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MainMenu.cpp@@ -1044,7 +1044,6 @@ WindowMsgHandledType MainMenuInput( GameWindow *window, UnsignedInt msg,return MSG_IGNORED;} // end MainMenuInput-void PrintOffsetsFromControlBarParent( void );//-------------------------------------------------------------------------------------------------/** Main menu window system callback *///-------------------------------------------------------------------------------------------------diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetPushButton.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetPushButton.cppindex 94af9723d..52e2793c5 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetPushButton.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetPushButton.cpp@@ -277,10 +277,20 @@ WindowMsgHandledType GadgetPushButtonInput( GameWindow *window,} // end ifelse{-- // just select as normal++ //+ // Right clicks fire on the way down, like check-like buttons do. Waiting for the+ // up click meant the message only went out if WIN_STATE_SELECTED survived until+ // then, and it often did not: there is no grab window for right clicks, so a+ // hair of mouse movement off the button raised GWM_MOUSE_LEAVING, which clears+ // the bit, and the click was silently eaten. That is why cancelling a queued+ // unit or upgrade took several tries.+ //BitSet( instData->m_state, WIN_STATE_SELECTED );+ TheWindowManager->winSendSystemMsg( instData->getOwner(), GBM_SELECTED_RIGHT,+ (WindowMsgData)window, mData1 );+} // end else}@@ -300,26 +310,12 @@ WindowMsgHandledType GadgetPushButtonInput( GameWindow *window,{//- // note check like selected messages aren't sent here ... they are sent- // on the down press+ // The message already went out on the down press, for check-like and plain buttons+ // alike. All that is left here is to drop the selected look. The up click is still+ // consumed either way - it belongs to the button we pressed on, and letting it+ // bubble would hand a stray right click to whatever is underneath.//- if( BitTest( instData->getState(), WIN_STATE_SELECTED ) &&- BitTest( window->winGetStatus(), WIN_STATUS_CHECK_LIKE ) == FALSE )- {-- TheWindowManager->winSendSystemMsg( instData->getOwner(), GBM_SELECTED_RIGHT,- (WindowMsgData)window, mData1 );-- BitClear( instData->m_state, WIN_STATE_SELECTED );-- }- else- {-- // this up click was not meant for this button- return MSG_IGNORED;-- }+ BitClear( instData->m_state, WIN_STATE_SELECTED );}else@@ -648,7 +644,13 @@ void GadgetButtonSetBorder( GameWindow *g, Color color, Bool drawBorder = TRUE )}// GadgetButtonDrawClock ======================================================-/** Set to draw a rectClock on the button */+/** Set to draw a rectClock on the button.+ *+ * The flag stays set until somebody clears it - the draw used to eat it, one clock per+ * frame drawn. That only worked while the frame rate matched the rate the flag was put+ * back at, and it does not: the command bar re-arms the clock on a logic tick (30Hz) while+ * the renderer runs free, so every frame in between drew a cameo with no radial fill on it+ * and the production progress flickered. *///=============================================================================void GadgetButtonDrawClock( GameWindow *g, Int percent, Color color ){@@ -689,6 +691,24 @@ void GadgetButtonDrawInverseClock( GameWindow *g, Int percent, Color color )}+// GadgetButtonClearClock =====================================================+/** Take the clock back off the button. Whoever draws a clock owns clearing it - see+ * GadgetButtonDrawClock for why the draw no longer does. */+//=============================================================================+void GadgetButtonClearClock( GameWindow *g )+{++ if( g == NULL )+ return;++ PushButtonData *pData = (PushButtonData *)g->winGetUserData();+ if( !pData )+ return;++ pData->drawClock = NO_CLOCK;++}+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.cppindex 539ee40d6..c8f3b7963 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp@@ -89,6 +89,7 @@#include "GameLogic/Module/StealthUpdate.h"#include "GameLogic/Module/SupplyWarehouseDockUpdate.h"#include "GameLogic/Module/MobMemberSlavedUpdate.h"//ML+#include "GameLogic/Module/SpawnBehavior.h"#include "Common/UnitTimings.h" //Contains the DO_UNIT_TIMINGS define jba.@@ -1050,6 +1051,9 @@ InGameUI::InGameUI()m_lastIncomeDisplayed = -1;m_hudLastSampleFrame = 0;m_hudLastSampleMs = 0;+ m_cameraKeyLastMs = 0;+ m_subtitleFreezeStartMs = 0;+ m_subtitleFreezeSteps = 0;m_hudFps = 0.0f;for( Int incomeBucket = 0; incomeBucket < INCOME_SAMPLES; incomeBucket++ )m_incomeSamples[ incomeBucket ] = 0;@@ -1491,6 +1495,70 @@ void InGameUI::evaluateSoloNexus( Drawable *newlyAddedDrawable )}+//-------------------------------------------------------------------------------------------------+/** The longest weapon range anything in this template's weapon sets can reach. Every set is+ * walked, not just the one an empty condition mask happens to select: a defence whose gun lives+ * in a conditional set (an upgrade, a garrisoned variant) would otherwise report no range. */+//-------------------------------------------------------------------------------------------------+static Real templateWeaponRange( const ThingTemplate *tmpl )+{+ if( tmpl == NULL )+ return 0.0f;++ Real range = 0.0f;+ const WeaponTemplateSetVector& sets = tmpl->getWeaponTemplateSets();+ for( WeaponTemplateSetVector::const_iterator si = sets.begin(); si != sets.end(); ++si )+ {+ for( Int ws = PRIMARY_WEAPON; ws < WEAPONSLOT_COUNT; ++ws )+ {+ const WeaponTemplate *wt = si->getNth( (WeaponSlotType)ws );+ if( wt && wt->getUnmodifiedAttackRange() > range )+ range = wt->getUnmodifiedAttackRange();+ }+ }++ return range;+}++//-------------------------------------------------------------------------------------------------+/** The radius to ring while this structure is being placed.+ *+ * Its own weapons first - and if it has none, the weapons of whatever it puts on the ground.+ * Half the GLA's defences carry no gun at all: a stinger site is an empty shell with a+ * SpawnBehavior that keeps three stinger soldiers alive next to it, and the soldiers own the+ * missiles. Judged by its own template the site is unarmed, so no ring was ever drawn for the+ * one faction whose defences most need siting. */+//-------------------------------------------------------------------------------------------------+static Real templatePlacementRange( const ThingTemplate *tmpl )+{+ Real range = templateWeaponRange( tmpl );+ if( range > 0.0f || tmpl == NULL || TheThingFactory == NULL )+ return range;++ const ModuleInfo& modules = tmpl->getBehaviorModuleInfo();+ for( Int i = 0; i < modules.getCount(); i++ )+ {+ if( modules.getNthName( i ) != "SpawnBehavior" )+ continue;++ const SpawnBehaviorModuleData *data =+ (const SpawnBehaviorModuleData *)modules.getNthData( i );+ if( data == NULL )+ continue;++ for( size_t s = 0; s < data->m_spawnTemplateNameData.size(); ++s )+ {+ const ThingTemplate *spawn =+ TheThingFactory->findTemplate( data->m_spawnTemplateNameData[ s ] );+ Real spawnRange = templateWeaponRange( spawn );+ if( spawnRange > range )+ range = spawnRange;+ }+ }++ return range;+}+void InGameUI::handleBuildPlacements( void ){@@ -1512,22 +1580,7 @@ void InGameUI::handleBuildPlacements( void )//if( TheGlobalData->m_showPlacementRangeRing ){- //- // Walk every weapon set the template has, not just the one an empty condition mask- // happens to select: a defence whose gun lives in a conditional set (an upgrade, a- // garrisoned variant) would otherwise report no range at all and draw no ring.- //- Real placeRange = 0.0f;- const WeaponTemplateSetVector& sets = m_pendingPlaceType->getWeaponTemplateSets();- for( WeaponTemplateSetVector::const_iterator si = sets.begin(); si != sets.end(); ++si )- {- for( Int ws = PRIMARY_WEAPON; ws < WEAPONSLOT_COUNT; ++ws )- {- const WeaponTemplate *wt = si->getNth( (WeaponSlotType)ws );- if( wt && wt->getUnmodifiedAttackRange() > placeRange )- placeRange = wt->getUnmodifiedAttackRange();- }- }+ Real placeRange = templatePlacementRange( m_pendingPlaceType );setRadiusCursorForRadius( placeRange );m_placementRangeRingUp = ( placeRange > 0.0f );}@@ -1715,8 +1768,8 @@ void InGameUI::preDraw( void )// handle radius-cursors, if anyhandleRadiusCursor();- // show the build grid under a structure waiting to be placed- drawBuildGrid();+ // the build grid under a structure waiting to be placed is not drawn here: it is terrain+ // geometry now, and HeightMapRenderObjClass::Render puts it down with the ground itself// draw the floating text first;drawFloatingText();@@ -1816,15 +1869,31 @@ void InGameUI::update( void )// if the timeis frozen by a script, then we still want the text to displayif(TheScriptEngine->isTimeFrozenScript()){- // NOTE: these are LOGIC-frame counters decremented to fake time passing while the- // logic clock is frozen, but InGameUI::update runs once per RENDER frame - so with- // rendering uncapped they run down (fps/30)x too fast and cutscene subtitles expire- // early. Not gated on the logic frame here because the logic frame is exactly what is- // NOT advancing during a script freeze; the fix needs a wall-clock 30Hz source and an- // in-game cutscene to verify. See FINDINGS.md 7.2.- m_militarySubtitle->lifetime--;- m_militarySubtitle->blockBeginFrame--;- m_militarySubtitle->incrementOnFrame--;+ //+ // These are LOGIC-frame counters walked down by hand to fake time passing while the+ // logic clock is frozen. They cannot be gated on the logic frame - that is exactly+ // what is not advancing - and one step per call was one step per RENDER frame, so+ // with the renderer uncapped a cutscene's subtitles ran down (fps/30) times too fast.+ // The wall clock supplies the missing 30Hz: count the frames the freeze has lasted+ // so far and apply only the ones not applied yet, so nothing drifts however long it+ // runs. See FINDINGS.md 7.2.+ //+ const UnsignedInt nowMs = timeGetTime();+ if( m_subtitleFreezeStartMs == 0 )+ {+ m_subtitleFreezeStartMs = nowMs;+ m_subtitleFreezeSteps = 0;+ }+ const UnsignedInt elapsedFrames = (nowMs - m_subtitleFreezeStartMs) * LOGICFRAMES_PER_SECOND / 1000;+ const UnsignedInt steps = elapsedFrames - m_subtitleFreezeSteps;+ m_subtitleFreezeSteps = elapsedFrames;+ m_militarySubtitle->lifetime -= min( steps, m_militarySubtitle->lifetime );+ m_militarySubtitle->blockBeginFrame -= min( steps, m_militarySubtitle->blockBeginFrame );+ m_militarySubtitle->incrementOnFrame -= min( steps, m_militarySubtitle->incrementOnFrame );+ }+ else+ {+ m_subtitleFreezeStartMs = 0;}// if it's time to remove the subtitle, Then remove itif((Int)m_militarySubtitle->lifetime < (Int)currLogicFrame)@@ -1995,26 +2064,42 @@ void InGameUI::update( void )layout->runUpdate();}- //Handle keyboard camera rotations+ //+ // Handle keyboard camera rotations. These used to apply one whole step per call and this+ // update runs once per RENDER frame, so with the renderer uncapped the camera swung as fast+ // as the machine happened to draw - the same key held for the same time went a different+ // distance on every PC, and on a fast one a tap threw the view right past what you wanted.+ // The step sizes are written for the 30Hz logic rate, so scale them by how many of those+ // frames the wall clock says went by. Capped at four, so coming back from a hitch or an+ // alt-tab does not fling the camera across the map on the first frame. See FINDINGS.md 7.4.+ //+ const UnsignedInt cameraNowMs = timeGetTime();+ Real cameraSteps = 1.0f;+ if( m_cameraKeyLastMs != 0 )+ cameraSteps = (Real)(cameraNowMs - m_cameraKeyLastMs) * (LOGICFRAMES_PER_SECOND / 1000.0f);+ m_cameraKeyLastMs = cameraNowMs;+ if( cameraSteps > 4.0f )+ cameraSteps = 4.0f;+if( m_cameraRotatingLeft && !m_cameraRotatingRight ){//Keyboard rotate left- TheTacticalView->setAngle( TheTacticalView->getAngle() - TheGlobalData->m_keyboardCameraRotateSpeed );+ TheTacticalView->setAngle( TheTacticalView->getAngle() - TheGlobalData->m_keyboardCameraRotateSpeed * cameraSteps );}if( m_cameraRotatingRight && !m_cameraRotatingLeft ){//Keyboard rotate right- TheTacticalView->setAngle( TheTacticalView->getAngle() + TheGlobalData->m_keyboardCameraRotateSpeed );+ TheTacticalView->setAngle( TheTacticalView->getAngle() + TheGlobalData->m_keyboardCameraRotateSpeed * cameraSteps );}if( m_cameraZoomingIn && !m_cameraZoomingOut ){//Keyboard zoom in- TheTacticalView->zoomIn();+ TheTacticalView->zoomIn( cameraSteps );}if( m_cameraZoomingOut && !m_cameraZoomingIn ){//Keyboard zoom out- TheTacticalView->zoomOut();+ TheTacticalView->zoomOut( cameraSteps );}@@ -5576,7 +5661,7 @@ enumPRODUCTION_STRIP_CAMEO = 32, ///< cameo edge in pixelsPRODUCTION_STRIP_GAP = 3, ///< space between cameos, and between the two rowsPRODUCTION_STRIP_LEFT = 8, ///< inset from the left edge of the screen- PRODUCTION_STRIP_LIFT = 6, ///< clearance above the control bar+ PRODUCTION_STRIP_LIFT = 24, ///< clearance above the control barPRODUCTION_STRIP_MORE = 34 ///< width kept for the "+N" that closes an overflowing row};diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/MetaEvent.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/MetaEvent.cppindex 929251bad..ee6c02b5b 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/MetaEvent.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/MetaEvent.cpp@@ -455,6 +455,17 @@ GameMessageDisposition MetaEventTranslator::translateGameMessage(const GameMessaGameMessageDisposition disp = KEEP_MESSAGE;GameMessage::Type t = msg->getType();+ //+ // a click is the player saying what they want with the mouse, so whatever half-typed+ // structure chord is still armed from the keyboard is stale - drop it before it can eat+ // the next A or S and turn it into a building to place+ //+ if( ( t == GameMessage::MSG_RAW_MOUSE_LEFT_BUTTON_DOWN ||+ t == GameMessage::MSG_RAW_MOUSE_RIGHT_BUTTON_DOWN ) && TheControlBar )+ {+ TheControlBar->dropChord();+ }+if (t == GameMessage::MSG_RAW_KEY_DOWN || t == GameMessage::MSG_RAW_KEY_UP){MappableKeyType key = (MappableKeyType)msg->getArgument(0)->integer;diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/PlaceEventTranslator.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/PlaceEventTranslator.cppindex 9e6b04401..5975f21b1 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/PlaceEventTranslator.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/PlaceEventTranslator.cpp@@ -268,29 +268,42 @@ GameMessageDisposition PlaceEventTranslator::translateGameMessage(const GameMessCanMakeType cmt = TheBuildAssistant->canMakeUnit( builderObj, build );if( cmt != CANMAKE_OK ){+ //+ // Whatever the reason, the click was spent on the attempt: unhook the anchor and+ // eat the message. It used to just break out - the placement stayed anchored to+ // the spot that had been clicked, so the ghost sat there stuck to the map with no+ // way to place or aim it, and the click itself fell through to the world and+ // became a move order on whatever was selected. Running out of money halfway+ // through a shift-held row of structures hit this every time.+ //if (cmt == CANMAKE_NO_MONEY){TheEva->setShouldPlay(EVA_InsufficientFunds);TheInGameUI->message( "GUI:NotEnoughMoneyToBuild" );- break;}else if (cmt == CANMAKE_QUEUE_FULL){TheInGameUI->message( "GUI:ProductionQueueFull" );- break;}else if (cmt == CANMAKE_PARKING_PLACES_FULL){TheInGameUI->message( "GUI:ParkingPlacesFull" );- break;}else if( cmt == CANMAKE_MAXED_OUT_FOR_PLAYER ){TheInGameUI->message( "GUI:UnitMaxedOut" );- break;}- // get out of pending placement mode, this will also clear the arrow anchor status- TheInGameUI->placeBuildAvailable( NULL, NULL );+ else+ {+ // nothing to say about it, so drop out of placement mode altogether+ TheInGameUI->placeBuildAvailable( NULL, NULL );+ }++ // the ghost keeps following the cursor for the cases that may pass (the money+ // comes in, the queue drains), it just is not nailed to the map any more+ TheInGameUI->setPlacementStart( NULL );+ disp = DESTROY_MESSAGE;+ m_frameOfUpButton = TheGameLogic->getFrame();break;}diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/View.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/View.cppindex c41f10802..a991400a6 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/View.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/View.cpp@@ -125,14 +125,17 @@ View *View::prependViewToList( View *list )return this;}-void View::zoomIn( void )+// One "step" is what a single mouse wheel notch does, and what one 30Hz frame of a held+// zoom key does; a caller driving this from a render frame passes the fraction of a logic+// frame that has actually gone by, so the zoom rate stops depending on the frame rate.+void View::zoomIn( Real steps ){- setHeightAboveGround(getHeightAboveGround() - 10.0f);+ setHeightAboveGround(getHeightAboveGround() - 10.0f * steps);}-void View::zoomOut( void )+void View::zoomOut( Real steps ){- setHeightAboveGround(getHeightAboveGround() + 10.0f);+ setHeightAboveGround(getHeightAboveGround() + 10.0f * steps);}/**diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DInGameUI.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DInGameUI.hindex cf44dcb9c..a2d3a7801 100644--- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DInGameUI.h+++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DInGameUI.h@@ -85,12 +85,6 @@ protected:RenderObjClass *m_buildingPlacementAnchor;RenderObjClass *m_buildingPlacementArrow;- /** The build grid is a few thousand short lines, and TheDisplay->drawLine is a Reset() and a- * Render() each - one draw call per segment (EA's own @todo on it). One renderer of our own,- * filled in a single pass and drawn once, is what lets the patch be wide enough to lay a base- * out on. */- Render2DClass *m_buildGridRender;-}; // end class W3DInGameUI#endif // end __W3DINGAMEUI_H_diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/GUICallbacks/W3DMainMenu.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/GUICallbacks/W3DMainMenu.cppindex 30464c897..b763458b9 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/GUICallbacks/W3DMainMenu.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/GUICallbacks/W3DMainMenu.cpp@@ -761,8 +761,7 @@ void W3DMainMenuButtonDropShadowDraw( GameWindow *window,{TheDisplay->drawRemainingRectClock( start.x, start.y, size.x, size.y, pData->percentClock,pData->colorClock );}- pData->drawClock = NO_CLOCK;- window->winSetUserData(pData);+ // the clock is not consumed by drawing it - see GadgetButtonDrawClock}if( pData->drawBorder && pData->colorBorder != GAME_COLOR_UNDEFINED )diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DPushButton.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DPushButton.cppindex f2f3b1039..2f23d3836 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DPushButton.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DPushButton.cpp@@ -315,8 +315,7 @@ void W3DGadgetPushButtonDraw( GameWindow *window, WinInstanceData *instData ){TheDisplay->drawRemainingRectClock( origin.x, origin.y, size.x, size.y, pData->percentClock,pData->colorClock );}- pData->drawClock = NO_CLOCK;- window->winSetUserData(pData);+ // the clock is not consumed by drawing it - see GadgetButtonDrawClock}if( pData->drawBorder && pData->colorBorder != GAME_COLOR_UNDEFINED )@@ -487,8 +486,7 @@ void W3DGadgetPushButtonImageDrawOne( GameWindow *window,{TheDisplay->drawRemainingRectClock( start.x, start.y, size.x, size.y, pData->percentClock,pData->colorClock );}- pData->drawClock = NO_CLOCK;- window->winSetUserData(pData);+ // the clock is not consumed by drawing it - see GadgetButtonDrawClock}if( pData->drawBorder && pData->colorBorder != GAME_COLOR_UNDEFINED )@@ -749,8 +747,7 @@ void W3DGadgetPushButtonImageDrawThree(GameWindow *window, WinInstanceData *inst{TheDisplay->drawRemainingRectClock( start.x, start.y, size.x, size.y, pData->percentClock,pData->colorClock );}- pData->drawClock = NO_CLOCK;- window->winSetUserData(pData);+ // the clock is not consumed by drawing it - see GadgetButtonDrawClock}if( pData->drawBorder && pData->colorBorder != GAME_COLOR_UNDEFINED )diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HeightMap.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HeightMap.cppindex 7c9a0ea93..fd52ee707 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HeightMap.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HeightMap.cpp@@ -65,6 +65,7 @@#include "Common/GlobalData.h"#include "Common/PerfTimer.h"+#include "GameClient/InGameUI.h"#include "GameClient/TerrainVisual.h"#include "GameClient/View.h"#include "GameClient/Water.h"@@ -2185,6 +2186,12 @@ void HeightMapRenderObjClass::Render(RenderInfoClass & rinfo)m_bibBuffer->renderBibs();+ // the build grid goes down with the ground it describes: drawn here it is depth tested against+ // the terrain and covered by everything drawn after it, so it reads as paint on the map rather+ // than as a wireframe floating over the scene+ if( TheInGameUI )+ TheInGameUI->drawBuildGrid();+// We do some custom blending, so tell the shader class to reset everything.DX8Wrapper::Set_Texture(0,NULL);DX8Wrapper::Set_Texture(1,NULL);diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DInGameUI.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DInGameUI.cppindex f5d7ed16d..f982e5d13 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DInGameUI.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DInGameUI.cpp@@ -51,6 +51,11 @@#include "W3DDevice/Common/W3DConvert.h"#include "WW3D2/WW3D.h"#include "WW3D2/HAnim.h"+#include "WW3D2/DX8Wrapper.h"+#include "WW3D2/dx8vertexbuffer.h"+#include "WW3D2/dx8indexbuffer.h"+#include "WW3D2/vertmaterial.h"+#include "WW3D2/shader.h"#include "Common/UnitTimings.h" //Contains the DO_UNIT_TIMINGS define jba.@@ -284,7 +289,6 @@ W3DInGameUI::W3DInGameUI()m_buildingPlacementAnchor = NULL;m_buildingPlacementArrow = NULL;- m_buildGridRender = NULL;} // end W3DInGameUI@@ -306,13 +310,6 @@ W3DInGameUI::~W3DInGameUI()REF_PTR_RELEASE( m_buildingPlacementAnchor );REF_PTR_RELEASE( m_buildingPlacementArrow );- if( m_buildGridRender )- {- m_buildGridRender->Reset();- delete m_buildGridRender;- m_buildGridRender = NULL;- }-} // end ~W3DInGameUI// loadText ===================================================================@@ -454,6 +451,115 @@ void W3DInGameUI::draw( void )} // end draw+//-------------------------------------------------------------------------------------------------+// The build grid's own render state. Alpha blended, untextured, depth tested but never depth+// written, and PASS_ALWAYS: the grid is a sheet lying exactly on the terrain, so anything that+// compared depth against the terrain would z-fight with it. Drawing it in the terrain pass and+// never writing depth means everything drawn after the terrain - buildings, units, trees, the+// placement ghost itself - covers it, which is what makes it read as paint on the ground.+// This is the bibs' shader with texturing off (see W3DBibBuffer).+#define SC_BUILD_GRID ( SHADE_CNST(ShaderClass::PASS_ALWAYS, ShaderClass::DEPTH_WRITE_DISABLE, ShaderClass::COLOR_WRITE_ENABLE, ShaderClass::SRCBLEND_SRC_ALPHA, \+ ShaderClass::DSTBLEND_ONE_MINUS_SRC_ALPHA, ShaderClass::FOG_DISABLE, ShaderClass::GRADIENT_MODULATE, ShaderClass::SECONDARY_GRADIENT_DISABLE, ShaderClass::TEXTURING_DISABLE, \+ ShaderClass::ALPHATEST_DISABLE, ShaderClass::CULL_MODE_DISABLE, \+ ShaderClass::DETAILCOLOR_DISABLE, ShaderClass::DETAILALPHA_DISABLE) )++/** rgb plus an alpha given as a float 0..255, clamped - the grid's colours are all one colour at+ * a per-vertex strength. */+static UnsignedInt gridColor( UnsignedInt rgb, Real alpha )+{+ Int a = REAL_TO_INT( alpha );+ if( a < 0 )+ a = 0;+ else if( a > 255 )+ a = 255;+ return rgb | ((UnsignedInt)a << 24);+}++/** Batches the grid's quads through the dynamic vertex buffer. The patch is ~1700 line quads plus+ * a fill for each blocked cell, which is more than one dynamic lock wants to hold, so it flushes+ * in fixed chunks - the draw state is set once by the caller and holds across the flushes. */+class BuildGridQuads+{+public:+ BuildGridQuads( void ) : m_quads( 0 ) { }++ void add( const Vector3 &p0, const Vector3 &p1, const Vector3 &p2, const Vector3 &p3,+ UnsignedInt c0, UnsignedInt c1, UnsignedInt c2, UnsignedInt c3 )+ {+ if( m_quads >= MAX_QUADS )+ flush();++ Vert *v = &m_verts[ m_quads * 4 ];+ v[ 0 ].pos = p0; v[ 0 ].diffuse = c0;+ v[ 1 ].pos = p1; v[ 1 ].diffuse = c1;+ v[ 2 ].pos = p2; v[ 2 ].diffuse = c2;+ v[ 3 ].pos = p3; v[ 3 ].diffuse = c3;+ ++m_quads;+ }++ void flush( void );++private:+ enum { MAX_QUADS = 512 };+ struct Vert+ {+ Vector3 pos;+ UnsignedInt diffuse;+ };+ Vert m_verts[ MAX_QUADS * 4 ];+ Int m_quads;+};++void BuildGridQuads::flush( void )+{+ if( m_quads == 0 )+ return;++ const Int quads = m_quads;+ m_quads = 0; // whatever happens below, this batch is spent++ DynamicVBAccessClass vbAccess( BUFFER_TYPE_DYNAMIC_DX8, DX8_FVF_XYZNDUV2, quads * 4 );+ DynamicIBAccessClass ibAccess( BUFFER_TYPE_DYNAMIC_DX8, quads * 6 );+ {+ DynamicVBAccessClass::WriteLockClass vbLock( &vbAccess );+ DynamicIBAccessClass::WriteLockClass ibLock( &ibAccess );+ VertexFormatXYZNDUV2 *vb = vbLock.Get_Formatted_Vertex_Array();+ UnsignedShort *ib = ibLock.Get_Index_Array();+ if( vb == NULL || ib == NULL )+ return;++ for( Int q = 0; q < quads; ++q )+ {+ for( Int i = 0; i < 4; ++i, ++vb )+ {+ const Vert &src = m_verts[ q * 4 + i ];+ vb->x = src.pos.X;+ vb->y = src.pos.Y;+ vb->z = src.pos.Z;+ vb->nx = 0.0f;+ vb->ny = 0.0f;+ vb->nz = 1.0f;+ vb->diffuse = src.diffuse;+ vb->u1 = 0.0f;+ vb->v1 = 0.0f;+ vb->u2 = 0.0f;+ vb->v2 = 0.0f;+ }++ *ib++ = (UnsignedShort)(q * 4);+ *ib++ = (UnsignedShort)(q * 4 + 1);+ *ib++ = (UnsignedShort)(q * 4 + 2);+ *ib++ = (UnsignedShort)(q * 4);+ *ib++ = (UnsignedShort)(q * 4 + 2);+ *ib++ = (UnsignedShort)(q * 4 + 3);+ }+ }++ DX8Wrapper::Set_Index_Buffer( ibAccess, 0 );+ DX8Wrapper::Set_Vertex_Buffer( vbAccess );+ DX8Wrapper::Draw_Triangles( 0, quads * 2, 0, quads * 4 );+}+//-------------------------------------------------------------------------------------------------/** Draw the pathfinder's own cell grid under the structure sitting on the cursor, and cross out* the cells it cannot go on. GridBuildPlacement snaps a footprint's edges to these very lines@@ -464,6 +570,11 @@ void W3DInGameUI::draw( void )* and the ones being aimed at are the ones worth seeing - so the lines also fade out towards the* edge of the patch instead of ending on a hard square.*+ * It is drawn as quads lying on the terrain, from inside the terrain pass+ * (HeightMapRenderObjClass::Render calls it right after the bibs), not as a screen space+ * overlay: painted on the ground it is read at a glance, and everything drawn after the terrain+ * covers it, so a building never has grid lines crawling over its roof.+ ** "Cannot build" here is the pathfinder cell's own type: water, a cliff, rubble, an existing* structure, plain impassable. It deliberately does not run the full isLocationLegalToBuild for* every cell - that is a per-structure query (build radius, shroud, supply proximity) and a@@ -477,7 +588,7 @@ void W3DInGameUI::drawBuildGrid( void )return;if( m_placeIcon == NULL || m_placeIcon[ 0 ] == NULL )return;- if( TheTacticalView == NULL || TheDisplay == NULL || TheTerrainLogic == NULL || TheAI == NULL )+ if( TheTerrainLogic == NULL || TheAI == NULL )return;Pathfinder *pathfinder = TheAI->pathfinder();@@ -492,68 +603,92 @@ void W3DInGameUI::drawBuildGrid( void )enum { GRID_RADIUS = 14 };enum { GRID_CELLS = GRID_RADIUS * 2 + 1, GRID_POINTS = GRID_CELLS + 1 };+ // half the width of a painted line, in world units - a cell is PLACEMENT_CELL (10) across+ const Real LINE_HALF_WIDTH = 0.45f;+ // the ground is sampled at the line, so a line running across a slope would sink into the hill+ // on one side; lifting the whole sheet a hair keeps it out of the dirt without floating+ const Real GRID_LIFT = 0.35f;+// the pathfinder's own cell indexing, so the lines drawn are the lines it reasons aboutconst Int cellX = REAL_TO_INT_FLOOR( (center->x + 0.5f) / PATHFIND_CELL_SIZE_F ) - GRID_RADIUS;const Int cellY = REAL_TO_INT_FLOOR( (center->y + 0.5f) / PATHFIND_CELL_SIZE_F ) - GRID_RADIUS;- // project every corner of the patch once, rather than four times per cell- ICoord2D screen[ GRID_POINTS ][ GRID_POINTS ];- Bool onScreen[ GRID_POINTS ][ GRID_POINTS ];+ // sample the terrain once per grid corner, rather than once per quad corner+ Real gx[ GRID_POINTS ], gy[ GRID_POINTS ];+ Real gz[ GRID_POINTS ][ GRID_POINTS ];+ Real fade[ GRID_POINTS ][ GRID_POINTS ];Int ix, iy;++ for( ix = 0; ix < GRID_POINTS; ++ix )+ {+ gx[ ix ] = placementGridLine( cellX + ix );+ gy[ ix ] = placementGridLine( cellY + ix );+ }++ // the patch fades out to nothing at its edge, measured from the cursor's own cell, so it ends+ // on a soft edge instead of a hard square+ const Real mid = (Real)GRID_RADIUS + 0.5f;for( iy = 0; iy < GRID_POINTS; ++iy ){for( ix = 0; ix < GRID_POINTS; ++ix ){- Coord3D world;- world.x = placementGridLine( cellX + ix );- world.y = placementGridLine( cellY + iy );- world.z = TheTerrainLogic->getGroundHeight( world.x, world.y );- onScreen[ iy ][ ix ] = TheTacticalView->worldToScreen( &world, &screen[ iy ][ ix ] );+ gz[ iy ][ ix ] = TheTerrainLogic->getGroundHeight( gx[ ix ], gy[ iy ] ) + GRID_LIFT;++ const Real dx = (Real)fabs( ix - mid );+ const Real dy = (Real)fabs( iy - mid );+ const Real d = ( dx > dy ) ? dx : dy;+ const Real f = 1.0f - d / mid;+ fade[ iy ][ ix ] = ( f > 0.0f ) ? f : 0.0f;}}- if( m_buildGridRender == NULL )- m_buildGridRender = NEW Render2DClass;- if( m_buildGridRender == NULL )- return;-- m_buildGridRender->Reset();- m_buildGridRender->Enable_Texturing( FALSE );- m_buildGridRender->Set_Coordinate_Range( RectClass( 0, 0, (Real)TheDisplay->getWidth(),- (Real)TheDisplay->getHeight() ) );-- // the lines fade to nothing at the edge of the patch, measured from the cursor's own cell- const Real fadeFrom = (Real)GRID_RADIUS;-- // the grid itself+ // the state the quads are drawn with: prelit (the colour is all in the vertices), untextured,+ // alpha blended, depth tested but never depth written, and PASS_ALWAYS so a sheet lying on the+ // terrain cannot z-fight with the terrain triangles underneath it. This is the bibs' own+ // shader, and the bibs are the proof it reads as paint rather than as decal geometry.+ static ShaderClass gridShader( SC_BUILD_GRID );+ VertexMaterialClass *material = VertexMaterialClass::Get_Preset( VertexMaterialClass::PRELIT_DIFFUSE );+ DX8Wrapper::Set_Material( material );+ REF_PTR_RELEASE( material );+ DX8Wrapper::Set_Texture( 0, NULL );+ DX8Wrapper::Set_Shader( gridShader );+ DX8Wrapper::Apply_Render_State_Changes();++ static BuildGridQuads quads; // 32k of vertices; static so it is not a stack frame++ // the lines themselves, one quad per cell edge so they follow the ground over every bump+ const Real LINE_ALPHA = 0x58;for( iy = 0; iy < GRID_POINTS; ++iy ){for( ix = 0; ix < GRID_POINTS; ++ix ){- // distance in cells from the middle, on the axis the segment runs along- const Real dx = (Real)fabs( ix - GRID_RADIUS - 0.5f );- const Real dy = (Real)fabs( iy - GRID_RADIUS - 0.5f );-- const Real d = ( dx > dy ) ? dx : dy;- const Int alpha = REAL_TO_INT( 0x50 * ( 1.0f - d / fadeFrom ) );- if( alpha <= 0 )- continue;-- const UnsignedInt color = (alpha << 24) | 0x00FFFFFF;-- if( ix + 1 < GRID_POINTS && onScreen[ iy ][ ix ] && onScreen[ iy ][ ix + 1 ] )- m_buildGridRender->Add_Line( Vector2( (Real)screen[ iy ][ ix ].x, (Real)screen[ iy ][ ix ].y ),- Vector2( (Real)screen[ iy ][ ix + 1 ].x, (Real)screen[ iy ][ ix + 1 ].y ),- 1.0f, color );+ if( ix + 1 < GRID_POINTS && ( fade[ iy ][ ix ] > 0.0f || fade[ iy ][ ix + 1 ] > 0.0f ) )+ {+ const UnsignedInt c0 = gridColor( 0x00FFFFFF, LINE_ALPHA * fade[ iy ][ ix ] );+ const UnsignedInt c1 = gridColor( 0x00FFFFFF, LINE_ALPHA * fade[ iy ][ ix + 1 ] );+ quads.add( Vector3( gx[ ix ], gy[ iy ] - LINE_HALF_WIDTH, gz[ iy ][ ix ] ),+ Vector3( gx[ ix + 1 ], gy[ iy ] - LINE_HALF_WIDTH, gz[ iy ][ ix + 1 ] ),+ Vector3( gx[ ix + 1 ], gy[ iy ] + LINE_HALF_WIDTH, gz[ iy ][ ix + 1 ] ),+ Vector3( gx[ ix ], gy[ iy ] + LINE_HALF_WIDTH, gz[ iy ][ ix ] ),+ c0, c1, c1, c0 );+ }- if( iy + 1 < GRID_POINTS && onScreen[ iy ][ ix ] && onScreen[ iy + 1 ][ ix ] )- m_buildGridRender->Add_Line( Vector2( (Real)screen[ iy ][ ix ].x, (Real)screen[ iy ][ ix ].y ),- Vector2( (Real)screen[ iy + 1 ][ ix ].x, (Real)screen[ iy + 1 ][ ix ].y ),- 1.0f, color );+ if( iy + 1 < GRID_POINTS && ( fade[ iy ][ ix ] > 0.0f || fade[ iy + 1 ][ ix ] > 0.0f ) )+ {+ const UnsignedInt c0 = gridColor( 0x00FFFFFF, LINE_ALPHA * fade[ iy ][ ix ] );+ const UnsignedInt c1 = gridColor( 0x00FFFFFF, LINE_ALPHA * fade[ iy + 1 ][ ix ] );+ quads.add( Vector3( gx[ ix ] - LINE_HALF_WIDTH, gy[ iy ], gz[ iy ][ ix ] ),+ Vector3( gx[ ix ] + LINE_HALF_WIDTH, gy[ iy ], gz[ iy ][ ix ] ),+ Vector3( gx[ ix ] + LINE_HALF_WIDTH, gy[ iy + 1 ], gz[ iy + 1 ][ ix ] ),+ Vector3( gx[ ix ] - LINE_HALF_WIDTH, gy[ iy + 1 ], gz[ iy + 1 ][ ix ] ),+ c0, c0, c1, c1 );+ }}}- // and an X through every cell a structure cannot stand on+ // and a red wash over every cell a structure cannot stand on. Filling the cell reads at a+ // glance where an X drawn in thin lines did not.+ const Real BLOCKED_ALPHA = 0x44;for( iy = 0; iy < GRID_CELLS; ++iy ){for( ix = 0; ix < GRID_CELLS; ++ix )@@ -562,20 +697,21 @@ void W3DInGameUI::drawBuildGrid( void )if( cell == NULL || cell->getType() == PathfindCell::CELL_CLEAR )continue;- if( !onScreen[ iy ][ ix ] || !onScreen[ iy + 1 ][ ix + 1 ] ||- !onScreen[ iy ][ ix + 1 ] || !onScreen[ iy + 1 ][ ix ] )+ if( fade[ iy ][ ix ] <= 0.0f && fade[ iy + 1 ][ ix + 1 ] <= 0.0f )continue;- m_buildGridRender->Add_Line( Vector2( (Real)screen[ iy ][ ix ].x, (Real)screen[ iy ][ ix ].y ),- Vector2( (Real)screen[ iy + 1 ][ ix + 1 ].x, (Real)screen[ iy + 1 ][ ix + 1 ].y ),- 1.0f, 0xAAFF3030 );- m_buildGridRender->Add_Line( Vector2( (Real)screen[ iy ][ ix + 1 ].x, (Real)screen[ iy ][ ix + 1 ].y ),- Vector2( (Real)screen[ iy + 1 ][ ix ].x, (Real)screen[ iy + 1 ][ ix ].y ),- 1.0f, 0xAAFF3030 );+ quads.add( Vector3( gx[ ix ], gy[ iy ], gz[ iy ][ ix ] ),+ Vector3( gx[ ix + 1 ], gy[ iy ], gz[ iy ][ ix + 1 ] ),+ Vector3( gx[ ix + 1 ], gy[ iy + 1 ], gz[ iy + 1 ][ ix + 1 ] ),+ Vector3( gx[ ix ], gy[ iy + 1 ], gz[ iy + 1 ][ ix ] ),+ gridColor( 0x00FF3030, BLOCKED_ALPHA * fade[ iy ][ ix ] ),+ gridColor( 0x00FF3030, BLOCKED_ALPHA * fade[ iy ][ ix + 1 ] ),+ gridColor( 0x00FF3030, BLOCKED_ALPHA * fade[ iy + 1 ][ ix + 1 ] ),+ gridColor( 0x00FF3030, BLOCKED_ALPHA * fade[ iy + 1 ][ ix ] ) );}}- m_buildGridRender->Render();+ quads.flush();} // end drawBuildGrid