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
fix(gameengine): port upstream september fixes and 45 open bug issues
Olcay Seygan264e2180c7b1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9d3192df5..8de49b47f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -770,6 +770,29 @@ A third pass went through the generals' powers, promotions and unit abilities.- Switching between fullscreen and windowed on Direct3D 9 no longer crashes. The graphics card can refuse a buffer for a moment while the screen changes, and the game wrote into the one it never got. It writes somewhere harmless now and asks again the next time it draws.- Closing the window while the game is still loading closes the game. The close was turned into a message stamped with your player, and no player exists that early.- Steam checking or repairing the game files no longer leaves you with a game that crashes the moment it starts. Steam puts its own original exe back and leaves this build's key bindings file in place, and the original read that file, found commands it had never heard of and gave up. The file has a name only this build looks for now, so the original starts as plain Zero Hour.+- A Propaganda Center's speech, a veterancy promotion or Jarmen Kell picking up scrap no longer throws away a reload in progress. A change to how fast a weapon fires restarted the wait from zero, so a Snipe that was nearly ready went back to the start; the reload now carries over at the new rate.+- Units in a plain Chinook stop firing. Rocket soldiers riding in a Humvee that drove into a Chinook kept shelling the ground from the helicopter's hold.+- A Laser Patriot no longer shoots at units outside its range.+- An empty Emperor or Battle Bus is taken by the first soldier who climbs in, not only when a second one follows.+- Hackers in an Internet Center keep hacking when you press Stop on a group that includes the building.+- A force-attack order on one of your own stealthed units, or an ally's, walks the attacker over to it. It used to stand where it was, because the target counted as unseen.+- Cancelling a unit in a production queue refunds what you paid for it, not whatever it costs by then.+- A stealthed vehicle whose driver was sniped stops being invisible. The empty hull used to stay stealthed, and no detector could reveal a hull that belongs to nobody.+- Killing a unit from stealth no longer tells your enemy about it with floating bounty money over the wreck. You still get the money.+- Search and Destroy widens every building's sight by the same share. It used to hand a building the sight radius of whichever unit set the number, not a larger version of its own.+- Rising water on a scripted map drowns what is under it, not the helicopters flying over it.+- A group sent along waypoints with Alt keeps its formation, and a mixed group no longer counts as one formation when its members were in different ones.+- A missile that reached its target on the same frame its fuel ran out explodes once, not twice.+- Burning trees, a crashing helicopter, a nuclear silo's open doors and a Hacker or Black Lotus at work make their sound again after you load a save.+- Loading a save keeps a Search and Destroy sight bonus, a pending order's origin, a script's next check and a dock's approach path, all of which came back wrong. Older saves still load.+- A garrison entered while the map's playable edge was still closed can no longer be cleared by any blast that lands on the building.+- Burning infantry run in every direction, not always north-east.+- A player name long enough to fill the LAN game room no longer hangs the lobby, changing settings there no longer crashes it, and the list of LAN games keeps its place instead of jumping back to the top every time it refreshes.+- Holding Ctrl while the beacon text box was open no longer leaves force-attack armed after you let go.+- The camera stops following a unit the moment it goes stealthed or into the fog, instead of showing you where it went.+- A broken map.ini, a damaged map cache in your user folder or a map name with forward slashes no longer crash the game or lose the map from the list; the cache is rebuilt.+- A replay no longer crashes when it has no player from this machine, and a skirmish restarted from the menu records its replay with the slots you set up.+- Replays recorded before this version that have burning infantry, missiles, captured vehicles or cancelled production in them play back differently.## The buildings nobody repairs, repair themselvesdiff --git a/GeneralsMD/Code/GameEngine/Include/Common/GameAudio.h b/GeneralsMD/Code/GameEngine/Include/Common/GameAudio.hindex b9e8e152a..c15e288ef 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/GameAudio.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/GameAudio.h@@ -238,8 +238,6 @@ class AudioManager : public SubsystemInterface// on zoom.virtual void set3DVolumeAdjustment( Real volumeAdjustment );- virtual Bool has3DSensitiveStreamsPlaying( void ) const = 0;-virtual void *getHandleForBink( void ) = 0;virtual void releaseHandleForBink( void ) = 0;diff --git a/GeneralsMD/Code/GameEngine/Include/Common/Player.h b/GeneralsMD/Code/GameEngine/Include/Common/Player.hindex d5f00f26e..fd0df3f06 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/Player.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/Player.h@@ -536,7 +536,7 @@ public:/**the given object has just become (or just ceased to be) a member of one of our teams (or subteams)*/- void becomingTeamMember(Object *obj, Bool yes);+ void becomingTeamMember(Object *obj, Bool yes, Bool objectXferLoad = false);/**this is called when the player becomes the local player (yes==true)diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/ControlBarScheme.h b/GeneralsMD/Code/GameEngine/Include/GameClient/ControlBarScheme.hindex 6a5d57554..5ef9da937 100644--- a/GeneralsMD/Code/GameEngine/Include/GameClient/ControlBarScheme.h+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/ControlBarScheme.h@@ -128,7 +128,8 @@ class ControlBarSchemepublic:ControlBarScheme( void );~ControlBarScheme( void );-++ void validate( void ) const;void init( void );void update( void );void drawForeground( Coord2D multi, ICoord2D offset ); ///< draw function to be called within a w3d draw procedure for the foregrounddiff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.hindex 8a18a6fe0..90e301b36 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h@@ -729,6 +729,7 @@ public:void store(const AICommandParms& parms);void reconstitute(AICommandParms& parms) const;void doXfer(Xfer *xfer);+ void setCommandSource(CommandSourceType cmdSource) { m_cmdSource = cmdSource; }AICommandType getCommandType() const { return m_cmd; }ObjectID getTargetObjectID() const { return m_obj; }const Coord3D& getTargetPosition() const { return m_pos; }diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/ProductionUpdate.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/ProductionUpdate.hindex e71e46ac8..00563fee6 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/ProductionUpdate.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/ProductionUpdate.h@@ -108,6 +108,7 @@ protected:Int m_productionQuantityTotal; ///< it is now possible to construct multiple units simultaneously.Int m_productionQuantityProduced; ///< And we need to allow pausing within an entry, so we keep track of number of sub-successesExitDoorType m_exitDoor;+ UnsignedInt m_costPaid; ///< what was withdrawn when this was queued, and what a cancel refundsProductionEntry *m_next; ///< next in listProductionEntry *m_prev; ///< prev in listdiff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/SupplyTruckAIUpdate.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/SupplyTruckAIUpdate.hindex c2ec4892a..8ef869fe3 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/SupplyTruckAIUpdate.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/SupplyTruckAIUpdate.h@@ -272,8 +272,9 @@ public:virtual void noteDockActionWindow( UnsignedInt frames );virtual Real getDockActionProgress() const;-+virtual UpdateSleepTime update();+ virtual void aiDoCommand(const AICommandParms* parms);protected:diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Object.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Object.hindex 2e6f75d53..f0ffbc4c2 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Object.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Object.h@@ -478,6 +478,7 @@ public:Real getShroudRange() const; ///< How far can you shroud? Even more dynamic since it'll start at zero for everyone.void setShroudRange( Real newShroudRange ); ///< Access to setting someone's shrouding distanceReal getShroudClearingRange() const; ///< How far do you clear shroud?+ Real getOwnShroudClearingRange() const { return m_shroudClearingRange; } ///< the range set on us, before a scaffold's zero; what a scalar multipliesvoid setShroudClearingRange( Real newShroudClearingRange ); ///< Access to setting someone's clear shroud distancevoid setVisionSpied(Bool setting, Int byWhom);///< Change who is looking through our eyes@@ -664,6 +665,7 @@ public:void setHealthBoxOffset( const Coord3D& offset ) { m_healthBoxOffset = offset; } ///< for special amorphous like angry mobvoid defect( Team *newTeam, UnsignedInt detectionTime );+ void takeOverUnmanned( Object *pilot ); ///< an unmanned vehicle gets this infantryman as its driver; he is used upvoid goInvulnerable( UnsignedInt time );// This is public, since there is no Thing level master setting of Turret stuff. It is all done in a sleepy hamletdiff --git a/GeneralsMD/Code/GameEngine/Include/GameNetwork/GameInfo.h b/GeneralsMD/Code/GameEngine/Include/GameNetwork/GameInfo.hindex 5a87a17e1..2e5d0febc 100644--- a/GeneralsMD/Code/GameEngine/Include/GameNetwork/GameInfo.h+++ b/GeneralsMD/Code/GameEngine/Include/GameNetwork/GameInfo.h@@ -196,6 +196,7 @@ public:void setSlot( Int slotNum, GameSlot slotInfo ); ///< Set the slot state (human, open, AI, etc)GameSlot* getSlot( Int slotNum ); ///< Get the slotconst GameSlot* getConstSlot( Int slotNum ) const; ///< Get the slot+ void handleOriginalSetups( void ); ///< a restart puts back the pre-random slot setup, a first start saves itvirtual Bool amIHost( void ) const; ///< Convenience function - is the local player the game host?virtual Int getLocalSlotNum( void ) const; ///< Get the local slot number, or -1 if we're not presentInt getSlotNum( AsciiString userName ) const; ///< Get the slot number corresponding to a specific user, or -1 if he's not presentdiff --git a/GeneralsMD/Code/GameEngine/Include/GameNetwork/LANGameInfo.h b/GeneralsMD/Code/GameEngine/Include/GameNetwork/LANGameInfo.hindex 9c8b88996..b5ed11233 100644--- a/GeneralsMD/Code/GameEngine/Include/GameNetwork/LANGameInfo.h+++ b/GeneralsMD/Code/GameEngine/Include/GameNetwork/LANGameInfo.h@@ -174,6 +174,7 @@ private:void LANDisplayGameList( GameWindow *gameListbox, LANGameInfo *gameList ); ///< Displays the list of games in a listbox, preserving selectionsvoid LANEnableStartButton(Bool enabled);+void LANDisableButtons();void LANDisplaySlotList( void ); ///< Displays the slot list according to TheLANGameInfovoid LANDisplayGameOptions( void ); ///< Displays the game options according to TheLANGameInfodiff --git a/GeneralsMD/Code/GameEngine/Source/Common/Audio/GameAudio.cpp b/GeneralsMD/Code/GameEngine/Source/Common/Audio/GameAudio.cppindex bb9739763..25008a8d4 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/Audio/GameAudio.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/Audio/GameAudio.cpp@@ -770,11 +770,14 @@ void AudioManager::set3DVolumeAdjustment( Real volumeAdjustment )if (m_sound3DVolume < 0.0f)m_sound3DVolume = 0.0f;- if (m_sound3DVolume > 1.0f)+ if (m_sound3DVolume > 1.0f)m_sound3DVolume = 1.0f;- if ( ! has3DSensitiveStreamsPlaying() )- m_volumeHasChanged = TRUE;+ // Flagged every frame, changed or not: MilesAudioManager::getEffectiveVolume folds the listener's+ // distance into a 3D sound's volume, so a playing sound needs it recomputed as the camera moves.+ // EA skipped this while any speech stream played, against a hang inside the Miles DLL that the+ // XAudio2 implementation does not have, and 3D volumes froze for as long as an EVA line lasted.+ m_volumeHasChanged = TRUE;}//-------------------------------------------------------------------------------------------------diff --git a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cppindex f45ba93f7..505b9bb1d 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp@@ -1299,8 +1299,9 @@ Int parseStats(char *args[], int num){if (TheWritableGlobalData && num > 1){- TheWritableGlobalData->m_dumpStatsAtInterval = TRUE;TheWritableGlobalData->m_statsInterval = atoi(args[1]);+ // W3DDisplay takes the frame modulo this; -stats 0 or a word divided by zero+ TheWritableGlobalData->m_dumpStatsAtInterval = TheWritableGlobalData->m_statsInterval > 0;}return 2;}diff --git a/GeneralsMD/Code/GameEngine/Source/Common/DamageFX.cpp b/GeneralsMD/Code/GameEngine/Source/Common/DamageFX.cppindex ec1bddb63..9d6950ed0 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/DamageFX.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/DamageFX.cpp@@ -164,7 +164,7 @@ static void parseCommonStuff(}else{- damageFirst = (DamageType)DamageTypeFlags::getSingleBitFromName(damageName);+ damageFirst = (DamageType)INI::scanIndexList(damageName, DamageTypeFlags::getBitNames());damageLast = damageFirst;}}diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GameLOD.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GameLOD.cppindex 3a398a211..3e878100d 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/GameLOD.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/GameLOD.cpp@@ -75,6 +75,7 @@ static const FieldParse TheStaticGameLODFieldParseTable[] ={ "UseEmissiveNightMaterials", INI::parseBool, NULL, offsetof( StaticGameLODInfo, m_useEmissiveNightMaterials ) },{ "UseHeatEffects", INI::parseBool, NULL, offsetof( StaticGameLODInfo, m_useHeatEffects ) },{ "TextureReductionFactor", INI::parseInt, NULL, offsetof( StaticGameLODInfo, m_textureReduction ) },+ { NULL, NULL, NULL, 0 }};static const char *StaticGameLODNames[]=@@ -121,6 +122,7 @@ static const FieldParse TheDynamicGameLODFieldParseTable[] ={ "SlowDeathScale", INI::parseReal, NULL, offsetof( DynamicGameLODInfo, m_slowDeathScale)},{ "MinParticlePriority", INI::parseIndexList, ParticlePriorityNames, offsetof( DynamicGameLODInfo, m_minDynamicParticlePriority)},{ "MinParticleSkipPriority", INI::parseIndexList, ParticlePriorityNames, offsetof( DynamicGameLODInfo, m_minDynamicParticleSkipPriority)},+ { NULL, NULL, NULL, 0 }};static const char *DynamicGameLODNames[]=diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cppindex f97985472..845557c61 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp@@ -1400,6 +1400,24 @@ void GlobalData::parseGameDataDefinition( INI* ini )TheWritableGlobalData->m_windowMode = TheWritableGlobalData->m_windowed? WINDOW_MODE_WINDOWED : WINDOW_MODE_FULLSCREEN;+ // These are loop bounds into fixed arrays, allocation sizes and divisors, and a mod's GameData+ // can hold anything. The road buffers index with 16 bits and allocate four past the maximum.+ const Int maxRoadBufferSize = 65535 - 4;+ GlobalData *data = TheWritableGlobalData;+ data->m_numGlobalLights = clamp( 0, data->m_numGlobalLights, MAX_GLOBAL_LIGHTS );+ data->m_maxVisibleTranslucentObjects = max( data->m_maxVisibleTranslucentObjects, 0 );+ data->m_maxVisibleOccluderObjects = max( data->m_maxVisibleOccluderObjects, 0 );+ data->m_maxVisibleOccludeeObjects = max( data->m_maxVisibleOccludeeObjects, 0 );+ data->m_maxVisibleNonOccluderOrOccludeeObjects = max( data->m_maxVisibleNonOccluderOrOccludeeObjects, 0 );+ data->m_maxLineBuildObjects = max( data->m_maxLineBuildObjects, 0 );+ data->m_maxRoadSegments = max( data->m_maxRoadSegments, 0 );+ data->m_maxRoadVertex = clamp( 0, data->m_maxRoadVertex, maxRoadBufferSize );+ data->m_maxRoadIndex = clamp( 0, data->m_maxRoadIndex, maxRoadBufferSize );+ data->m_maxRoadTypes = max( data->m_maxRoadTypes, 0 );+ data->m_networkFPSHistoryLength = max( data->m_networkFPSHistoryLength, 1u );+ data->m_networkLatencyHistoryLength = max( data->m_networkLatencyHistoryLength, 1u );+ data->m_networkCushionHistoryLength = max( data->m_networkCushionHistoryLength, 1u );+// override INI values with user preferencesOptionPreferences optionPref;diff --git a/GeneralsMD/Code/GameEngine/Source/Common/INI/INI.cpp b/GeneralsMD/Code/GameEngine/Source/Common/INI/INI.cppindex 747ee7f33..b9a5811ed 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/INI/INI.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/INI/INI.cpp@@ -902,7 +902,7 @@ void INI::parsePercentToReal( INI* ini, void * /*instance*/, void *store, const//-------------------------------------------------------------------------------------------------void INI::parseBitString8( INI* ini, void * /*instance*/, void *store, const void* userData ){- UnsignedInt tmp;+ UnsignedInt tmp = *(Byte*)store;INI::parseBitString32(ini, NULL, &tmp, userData);if (tmp & 0xffffff00){@@ -1845,13 +1845,13 @@ void INI::parseDamageTypeFlags(INI* ini, void* /*instance*/, void* store, const}if (token[0] == '+'){- DamageType dt = (DamageType)DamageTypeFlags::getSingleBitFromName(token+1);+ DamageType dt = (DamageType)scanIndexList(token+1, DamageTypeFlags::getBitNames());flags = setDamageTypeFlag(flags, dt);continue;}if (token[0] == '-'){- DamageType dt = (DamageType)DamageTypeFlags::getSingleBitFromName(token+1);+ DamageType dt = (DamageType)scanIndexList(token+1, DamageTypeFlags::getBitNames());flags = clearDamageTypeFlag(flags, dt);continue;}diff --git a/GeneralsMD/Code/GameEngine/Source/Common/INI/INIAudioEventInfo.cpp b/GeneralsMD/Code/GameEngine/Source/Common/INI/INIAudioEventInfo.cppindex eb3e8355b..ce9c07ddd 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/INI/INIAudioEventInfo.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/INI/INIAudioEventInfo.cpp@@ -149,6 +149,7 @@ const FieldParse AudioEventInfo::m_audioEventInfo[] ={ "MinRange", INI::parseReal, NULL, offsetof( AudioEventInfo, m_minDistance) },{ "MaxRange", INI::parseReal, NULL, offsetof( AudioEventInfo, m_maxDistance) },{ "LowPassCutoff", INI::parsePercentToReal, NULL, offsetof( AudioEventInfo, m_lowPassFreq) },+ { NULL, NULL, NULL, 0 }};//-------------------------------------------------------------------------------------------------diff --git a/GeneralsMD/Code/GameEngine/Source/Common/INI/INIControlBarScheme.cpp b/GeneralsMD/Code/GameEngine/Source/Common/INI/INIControlBarScheme.cppindex c215e0f2d..7aeeccc7b 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/INI/INIControlBarScheme.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/INI/INIControlBarScheme.cpp@@ -95,6 +95,7 @@ void INI::parseControlBarSchemeDefinition( INI *ini )// parse the ini definitionini->initFromINI( CBScheme, CBSchemeManager->getFieldParse() );+ CBScheme->validate();} // end parseCommandButtonDefinitiondiff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cppindex 700c5e6bc..cbaabe889 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp@@ -1125,17 +1125,33 @@ void Player::initFromDict(const Dict* d)}//=============================================================================-void Player::becomingTeamMember(Object *obj, Bool yes)-{+void Player::becomingTeamMember(Object *obj, Bool yes, Bool objectXferLoad)+{if (!obj)- return;+ return;// energy production/consumption hooks, note we ignore things that are UNDER_CONSTRUCTIONif( !obj->getStatusBits().test( OBJECT_STATUS_UNDER_CONSTRUCTION ) ){obj->friend_adjustPowerForPlayer(yes);} // end if-++ if (obj->isKindOf(KINDOF_DOZER)+ && obj->getAIUpdateInterface()+ && obj->getAIUpdateInterface()->isIdle())+ {+ // Need to remove it from the pick a peasant button+ if (yes)+ TheInGameUI->addIdleWorker(obj);+ else+ TheInGameUI->removeIdleWorker(obj, getPlayerIndex());+ }++ // An object being loaded already carries its saved vision range and bonuses; a battle plan+ // applied again here would stack a Search and Destroy bonus on top and break the shroud.+ if (objectXferLoad)+ return;+// when we capture a building, we need to see if there's an AutoDepositUpdate hooked to it,// if so, award the cash bonusif(this != ThePlayerList->getNeutralPlayer() && yes)@@ -1164,18 +1180,6 @@ void Player::becomingTeamMember(Object *obj, Bool yes)// A new object is not ready here yet; Object::initObject marks it. One being destroyed is gone.if( obj->areModulesReady() && !obj->isDestroyed() )applyVisionSpies( obj, yes );--- if (obj->isKindOf(KINDOF_DOZER)- && obj->getAIUpdateInterface()- && obj->getAIUpdateInterface()->isIdle())- {- // Need to remove it from the pick a peasant button- if (yes)- TheInGameUI->addIdleWorker(obj);- else- TheInGameUI->removeIdleWorker(obj, getPlayerIndex());- }}//=============================================================================@@ -2579,14 +2583,21 @@ void Player::doBountyForKill(const Object* killer, const Object* victim)getMoney()->deposit( bounty );m_scoreKeeper.addMoneyEarned( bounty );- //Display cash income floating over the recipient.- UnicodeString moneyString;- moneyString.format( TheGameText->fetch( "GUI:AddCash" ), bounty );- Coord3D pos;- pos.zero();- pos.add( killer->getPosition() );- pos.z += 10.0f; //add a little z to make it show up above the unit.- TheInGameUI->addFloatingText( moneyString, &pos, GameMakeColor( 255, 255, 0, 255 ) );+ // Display cash income floating over the recipient - but not to an enemy of a killer it cannot see,+ // or the number gives the stealthed unit away. Client display only, the deposit above is logic.+ const Object *seenKiller = killer->getContainedBy() ? killer->getContainedBy() : killer;+ const Bool hiddenKiller = seenKiller->testStatus( OBJECT_STATUS_STEALTHED ) && !seenKiller->testStatus( OBJECT_STATUS_DETECTED );+ const Player *localPlayer = ThePlayerList->getLocalPlayer();+ if( !hiddenKiller || localPlayer->getRelationship( killer->getTeam() ) != ENEMIES )+ {+ UnicodeString moneyString;+ moneyString.format( TheGameText->fetch( "GUI:AddCash" ), bounty );+ Coord3D pos;+ pos.zero();+ pos.add( killer->getPosition() );+ pos.z += 10.0f; //add a little z to make it show up above the unit.+ TheInGameUI->addFloatingText( moneyString, &pos, GameMakeColor( 255, 255, 0, 255 ) );+ }}}@@ -4031,7 +4042,8 @@ static void localApplyBattlePlanBonusesToObject( Object *obj, void *userData )if( bonus->m_sightRangeScalar != 1.0f ){objectToModify->setVisionRange( obj->getVisionRange() * bonus->m_sightRangeScalar );- objectToModify->setShroudClearingRange( obj->getShroudClearingRange() * bonus->m_sightRangeScalar );+ // the own range: a scaffold reports zero, and scaling that left the finished building blind+ objectToModify->setShroudClearingRange( obj->getOwnShroudClearingRange() * bonus->m_sightRangeScalar );}}diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Team.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Team.cppindex 0327f8de6..d56efe412 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Team.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Team.cpp@@ -1870,7 +1870,15 @@ void Team::updateState(void)PartitionFilterAlive filterAlive;PartitionFilterSameMapStatus filterMapStatus(iter.cur());- PartitionFilter *filters[] = { &filterTeam, &filterAlive, &filterMapStatus, NULL };+ // A shell in flight, an undetected stealth unit or the system object a power drops is not an+ // enemy the team can see; the unit's own Enemy Sighted condition leaves them out the same way.+ KindOfMaskType notSeen = MAKE_KINDOF_MASK(KINDOF_PROJECTILE);+ notSeen.set(KINDOF_INERT);+ PartitionFilterAcceptByKindOf filterSeenKind(KINDOFMASK_NONE, notSeen);+ PartitionFilterRejectByObjectStatus filterStealth( MAKE_OBJECT_STATUS_MASK( OBJECT_STATUS_STEALTHED ),+ MAKE_OBJECT_STATUS_MASK2( OBJECT_STATUS_DETECTED, OBJECT_STATUS_DISGUISED ) );++ PartitionFilter *filters[] = { &filterTeam, &filterAlive, &filterMapStatus, &filterSeenKind, &filterStealth, NULL };Real visionRange = iter.cur()->getVisionRange();anyAliveInTeam = true;Object *pObj = ThePartitionManager->getClosestObject( iter.cur(), visionRange,diff --git a/GeneralsMD/Code/GameEngine/Source/Common/Recorder.cpp b/GeneralsMD/Code/GameEngine/Source/Common/Recorder.cppindex 13220e7d2..dcbdce42d 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/Recorder.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/Recorder.cpp@@ -647,6 +647,9 @@ void RecorderClass::startRecording(GameDifficulty diff, Int originalGameMode, In{if(TheSkirmishGameInfo){+ // This runs before GameLogic::tryStartNewGame, so a restarted skirmish has to get its+ // pre-random slot setup back here too, or the replay records the first game's draws.+ TheSkirmishGameInfo->handleOriginalSetups();TheSkirmishGameInfo->setCRCInterval(REPLAY_CRC_INTERVAL);theSlotList = GameInfoToAsciiString(TheSkirmishGameInfo);DEBUG_LOG(("GameInfo String: %s\n",theSlotList.str()));diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/MemoryInit.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/MemoryInit.cppindex 8f786a3c9..e5b59fe49 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/System/MemoryInit.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/MemoryInit.cpp@@ -784,7 +784,7 @@ void userMemoryManagerInitPools(){if (buf[0] == ';')continue;- if (sscanf(buf, "%s %d %d", poolName, &initial, &overflow ) == 3)+ if (sscanf(buf, "%255s %d %d", poolName, &initial, &overflow ) == 3){for (PoolSizeRec* p = sizes; p->name != NULL; ++p){diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameState.cppindex 48b0272b2..9a6b5755e 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp@@ -1666,19 +1666,17 @@ void GameState::xfer( Xfer *xfer )// if no label was found, we'll use the map name (just filename, no directory info)if( exists == FALSE || saveGameInfo->mapLabel == AsciiString::TheEmptyString ){- char string[ _MAX_PATH ];-- strcpy( string, TheGlobalData->m_mapName.str() );- char *p = strrchr( string, '\\' );+ // either separator can end the directory part: a map named on the command line may use '/'+ const char *mapName = TheGlobalData->m_mapName.str();+ const char *back = strrchr( mapName, '\\' );+ const char *forward = strrchr( mapName, '/' );+ const char *p = back;+ if( forward != NULL && (p == NULL || forward > p) )+ p = forward;if( p == NULL )saveGameInfo->mapLabel = TheGlobalData->m_mapName;else- {-- p++; // skip the '\' we're on- saveGameInfo->mapLabel.set( p );-- } // end else+ saveGameInfo->mapLabel.set( p + 1 ); // skip the separator we're on} // end ifdiff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameStateMap.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameStateMap.cppindex e5ca1b0b8..edddeb6ae 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameStateMap.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameStateMap.cpp@@ -314,7 +314,7 @@ void GameStateMap::xfer( Xfer *xfer )xfer->xferAsciiString( &tmp );}- if (currentVersion >= 2)+ if (version >= 2){// save the game mode.Int gameMode = TheGameLogic->getGameMode();@@ -345,7 +345,7 @@ void GameStateMap::xfer( Xfer *xfer )xfer->xferAsciiString( &saveGameInfo->pristineMapName );saveGameInfo->pristineMapName = TheGameState->portableMapPathToRealMapPath(saveGameInfo->pristineMapName);- if (currentVersion >= 2)+ if (version >= 2){// get the game mode.Int gameMode;@@ -431,8 +431,10 @@ void GameStateMap::xfer( Xfer *xfer )}else{- if( TheSkirmishGameInfo )+ if( TheSkirmishGameInfo ){+ if( TheGameInfo == TheSkirmishGameInfo )+ TheGameInfo = NULL; // or it is left pointing at freed memorydelete TheSkirmishGameInfo;TheSkirmishGameInfo = NULL;}diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cppindex b76a01db4..928418b64 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp@@ -5224,6 +5224,8 @@ void ControlBar::showRallyPoint( const Coord3D *loc ){const ThingTemplate* ttn = TheThingFactory->findTemplate("RallyPointMarker");+ if (!ttn)+ return;marker = TheThingFactory->newDrawable( ttn );DEBUG_ASSERTCRASH( marker, ("showRallyPoint: Unable to create rally point drawable\n") );if (marker)@@ -6550,7 +6552,8 @@ void ControlBar::updateSpecialPowerShortcut( void )animateSpecialPowerShortcut(TRUE);}else if( !hasValidShortcutButton- && !m_specialPowerShortcutParent->winIsHidden()+ && !m_specialPowerShortcutParent->winIsHidden()+ && m_animateWindowManagerForGenShortcuts&& m_animateWindowManagerForGenShortcuts->isFinished() ){animateSpecialPowerShortcut(FALSE);diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarScheme.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarScheme.cppindex 02f2850e7..fbaddf211 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarScheme.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarScheme.cpp@@ -426,6 +426,17 @@ ControlBarScheme::ControlBarScheme(void)}+// The scheme's layout is scaled by the display over this resolution, so a zero here divides by zero.+void ControlBarScheme::validate(void) const+{+ if (m_ScreenCreationRes.x <= 0 || m_ScreenCreationRes.y <= 0)+ {+ DEBUG_CRASH(("ControlBarScheme '%s' has an invalid screen creation resolution (%d, %d)",+ m_name.str(), m_ScreenCreationRes.x, m_ScreenCreationRes.y));+ throw INI_INVALID_DATA;+ }+}+void ControlBarScheme::init(void){if(TheControlBar)diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanGameOptionsMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanGameOptionsMenu.cppindex 7ff06e84a..b036156c0 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanGameOptionsMenu.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanGameOptionsMenu.cpp@@ -416,6 +416,34 @@ void LANEnableStartButton(Bool enabled)buttonSelectMap->winEnable(enabled);}+// The countdown's last second: shutting the menu down clears every gadget pointer below, and a+// click that lands after that dereferences one of them.+void LANDisableButtons()+{+ buttonStart->winEnable(false);+ buttonBack->winEnable(false);+ buttonSelectMap->winEnable(false);+ comboBoxStartingCash->winEnable(false);++ GameWindow *optionalGadgets[] = { comboBoxSuperweapons, comboBoxPeaceTime, checkBoxUnitLimit,+ checkBoxProRules, comboBoxIncomeSharing, comboBoxTechRespawn };+ for (Int i = 0; i < (Int)ARRAY_SIZE(optionalGadgets); ++i)+ {+ if (optionalGadgets[i])+ optionalGadgets[i]->winEnable(false);+ }++ for (Int i = 0; i < MAX_SLOTS; ++i)+ {+ comboBoxPlayer[i]->winEnable(false);+ comboBoxColor[i]->winEnable(false);+ comboBoxPlayerTemplate[i]->winEnable(false);+ comboBoxTeam[i]->winEnable(false);+ buttonAccept[i]->winEnable(false);+ buttonMapStartPosition[i]->winEnable(false);+ }+}+static void handleColorSelection(int index){GameWindow *combo = comboBoxColor[index];diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishGameOptionsMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishGameOptionsMenu.cppindex 132ac04d1..aa9890241 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishGameOptionsMenu.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishGameOptionsMenu.cpp@@ -1699,6 +1699,8 @@ WindowMsgHandledType SkirmishGameOptionsMenuSystem( GameWindow *window, UnsignedskirmishMapSelectLayout = NULL;}TheShell->pop();+ if (TheGameInfo == TheSkirmishGameInfo)+ TheGameInfo = NULL; // or it is left pointing at freed memorydelete TheSkirmishGameInfo;TheSkirmishGameInfo = NULL;diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetTextEntry.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetTextEntry.cppindex 0baf1739f..472aa058b 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetTextEntry.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetTextEntry.cpp@@ -197,6 +197,18 @@ WindowMsgHandledType GadgetTextEntryInput( GameWindow *window, UnsignedInt msg,case KEY_DEL:return MSG_IGNORED;+ // the modifiers go on to the meta translator, both ways. A Ctrl press passed through+ // (the check above) but its release was swallowed here, so force-attack stayed armed+ // after typing into the beacon or chat box and a click on a building fired at it+ // instead of selecting it.+ case KEY_LCTRL:+ case KEY_RCTRL:+ case KEY_LALT:+ case KEY_RALT:+ case KEY_LSHIFT:+ case KEY_RSHIFT:+ return MSG_IGNORED;+// --------------------------------------------------------------------case KEY_DOWN:case KEY_RIGHT:diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowTransitions.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowTransitions.cppindex b707a714f..7c9a3ef4b 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowTransitions.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowTransitions.cpp@@ -516,6 +516,8 @@ void GameWindowTransitionsHandler::reverse( AsciiString groupName )void GameWindowTransitionsHandler::remove( AsciiString groupName, Bool skipPending ){TransitionGroup *g = findGroup(groupName);+ if(!g)+ return;if(m_pendingGroup == g){if(skipPending)diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GameClient.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GameClient.cppindex cd6fd1a0d..e14dcad5f 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GameClient.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GameClient.cpp@@ -683,8 +683,18 @@ void GameClient::update( void )if (TheInGameUI->isCameraTrackingDrawable()){+ // Stop following a unit the moment it can no longer be seen - stealthed, or gone into fog or+ // shroud for the player whose fog is drawn - or the camera shows where it went.Drawable *draw = TheInGameUI->getFirstSelectedDrawable();- if ( draw )+ const Object *object = draw ? draw->getObject() : NULL;+ Bool isVisible = object != NULL && !draw->isDrawableEffectivelyHidden();+ if ( isVisible )+ {+ const ObjectShroudStatus shroudStatus = object->getShroudedStatus( TheObserverCamera.getShroudPlayerIndex() );+ isVisible = shroudStatus == OBJECTSHROUD_CLEAR || shroudStatus == OBJECTSHROUD_PARTIAL_CLEAR;+ }++ if ( isVisible ){const Coord3D *pos = draw->getPosition();TheTacticalView->lookAt( pos );diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cppindex be72717f8..b95fddc0f 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp@@ -612,7 +612,7 @@ void InGameUI::xfer( Xfer *xfer )xfer->xferBool(&swInfo->m_hiddenByScript);xfer->xferBool(&swInfo->m_hiddenByScience);xfer->xferBool(&swInfo->m_ready);- if ( currentVersion >= 3 )+ if ( version >= 3 ){xfer->xferBool( &swInfo->m_evaReadyPlayed );}@@ -659,7 +659,7 @@ void InGameUI::xfer( Xfer *xfer )xfer->xferBool(&hiddenByScript);xfer->xferBool(&hiddenByScience);xfer->xferBool(&ready);- if ( currentVersion >= 3 )+ if ( version >= 3 ){xfer->xferBool( &evaReadyPlayed );}diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Mouse.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Mouse.cppindex 729b4cc33..299dd721d 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Mouse.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Mouse.cpp@@ -83,6 +83,7 @@ static const FieldParse TheMouseCursorFieldParseTable[] ={ "Frames", INI::parseInt, NULL, offsetof( CursorInfo, numFrames ) },{ "FPS", INI::parseReal, NULL, offsetof( CursorInfo, fps)},{ "Directions", INI::parseInt, NULL, offsetof( CursorInfo, numDirections ) },+ { NULL, NULL, NULL, 0 }};static const FieldParse TheMouseFieldParseTable[] =@@ -108,7 +109,7 @@ static const FieldParse TheMouseFieldParseTable[] ={ "DragTolerance", INI::parseUnsignedInt, NULL, offsetof( Mouse, m_dragTolerance) },{ "DragTolerance3D", INI::parseUnsignedInt, NULL, offsetof( Mouse, m_dragTolerance3D) },{ "DragToleranceMS", INI::parseUnsignedInt, NULL, offsetof( Mouse, m_dragToleranceMS) },-+ { NULL, NULL, NULL, 0 }};///////////////////////////////////////////////////////////////////////////////////////////////////diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/MapUtil.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/MapUtil.cppindex 7d313608d..3744b9b88 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/MapUtil.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/MapUtil.cpp@@ -568,6 +568,7 @@ Bool MapCache::loadUserMaps(){// Read in map list from diskAsciiString mapDir;+ Bool userCacheBroken = FALSE;if (TheGlobalData->m_buildMapCache){mapDir = getMapDir();@@ -589,7 +590,19 @@ Bool MapCache::loadUserMaps()if (fp){fp->close();- ini.load( fname, INI_LOAD_OVERWRITE, NULL );+ // the user folder's cache is ours to rebuild, and a hand edit or a torn write used to+ // stop the game at startup. Forget what it held; every map below parses fresh, and+ // returning TRUE has updateCache write a clean file over the broken one.+ try+ {+ ini.load( fname, INI_LOAD_OVERWRITE, NULL );+ }+ catch (...)+ {+ DEBUG_LOG(("MapCache: %s does not parse, rebuilding it\n", fname.str()));+ clear();+ userCacheBroken = TRUE;+ }}}@@ -706,7 +719,19 @@ Bool MapCache::loadUserMaps()if (clearUnseenMaps(mapDir))return TRUE;- return parsedAMap;+ return parsedAMap || userCacheBroken;+}++// The file name after the last separator of either kind, or the whole name when there is none.+// reverseFind('\\') + 1 was a pointer one past NULL for a name without a backslash.+static const char *mapFileNamePart( const AsciiString& fname )+{+ const char *back = fname.reverseFind('\\');+ const char *forward = fname.reverseFind('/');+ const char *sep = back;+ if (forward != NULL && (sep == NULL || forward > sep))+ sep = forward;+ return sep ? sep + 1 : fname.str();}//Bool MapCache::addMap( AsciiString dirName, AsciiString fname, WinTimeStamp timestamp, UnsignedInt filesize, Bool isOfficial )@@ -741,7 +766,7 @@ Bool MapCache::addMap( AsciiString dirName, AsciiString fname, FileInfo *fileInf{// unofficial maps or maps without namesAsciiString tempdisplayname;- tempdisplayname = fname.reverseFind('\\') + 1;+ tempdisplayname = mapFileNamePart(fname);(*this)[lowerFname].m_displayName.translate(tempdisplayname);if (md.m_numPlayers >= 2){@@ -797,7 +822,7 @@ Bool MapCache::addMap( AsciiString dirName, AsciiString fname, FileInfo *fileInf{DEBUG_LOG(("Missing TheKey_mapName!\n"));AsciiString tempdisplayname;- tempdisplayname = fname.reverseFind('\\') + 1;+ tempdisplayname = mapFileNamePart(fname);md.m_displayName.translate(tempdisplayname);if (md.m_numPlayers >= 2){diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/CommandXlat.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/CommandXlat.cppindex 163366580..4cd395ddf 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/CommandXlat.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/CommandXlat.cpp@@ -357,25 +357,32 @@ static CanAttackResult canObjectForceAttack( Object *obj, const Object *victim,//-------------------------------------------------------------------------------------------------static CanAttackResult canAnyForceAttack(const DrawableList *allSelected, const Object *victim, const Coord3D *pos ){- // check to make sure that allSelected can attack obj.- for (DrawableListCIt cit = allSelected->begin(); cit != allSelected->end(); ++cit)+ // "any" means any: this answered for the first object in the selection only, so a Sentry Drone+ // built before the Humvee beside it stopped the pair force firing at all.+ CanAttackResult best = ATTACKRESULT_NOT_POSSIBLE;+ for (DrawableListCIt cit = allSelected->begin(); cit != allSelected->end(); ++cit){Drawable *draw = *cit;- if (!draw)+ if (!draw){continue;}-+Object *obj = draw->getObject();- if (!obj)+ if (!obj){continue;}- return canObjectForceAttack( obj, victim, pos );+ CanAttackResult result = canObjectForceAttack( obj, victim, pos );+ if( result == ATTACKRESULT_POSSIBLE )+ return result;+ if( result == ATTACKRESULT_POSSIBLE_AFTER_MOVING+ || ( result == ATTACKRESULT_INVALID_SHOT && best == ATTACKRESULT_NOT_POSSIBLE ) )+ best = result;}- return ATTACKRESULT_NOT_POSSIBLE;+ return best;}//-------------------------------------------------------------------------------------------------@@ -3811,6 +3818,7 @@ GameMessageDisposition CommandTranslator::translateGameMessage(const GameMessageTheWritableGlobalData->m_showObjectHealth = 1 - TheGlobalData->m_showObjectHealth;TheInGameUI->message( UnicodeString( L"Object Health %s" ),TheGlobalData->m_showObjectHealth ? L"ON" : L"OFF" );+ disp = DESTROY_MESSAGE;}break;@@ -4977,6 +4985,7 @@ GameMessageDisposition CommandTranslator::translateGameMessage(const GameMessagecase GameMessage::MSG_META_DEMO_TOGGLE_RENDER:{TheWritableGlobalData->m_disableRender = !TheGlobalData->m_disableRender;+ disp = DESTROY_MESSAGE;break;}@@ -5029,6 +5038,7 @@ GameMessageDisposition CommandTranslator::translateGameMessage(const GameMessageobj->kill();}}+ disp = DESTROY_MESSAGE;}break;@@ -5123,6 +5133,7 @@ GameMessageDisposition CommandTranslator::translateGameMessage(const GameMessage} else {TheDisplay->setDebugDisplayCallback(NULL);}+ disp = DESTROY_MESSAGE;break;}#endif // #ifdef PERF_TIMERS@@ -5646,6 +5657,7 @@ GameMessageDisposition CommandTranslator::translateGameMessage(const GameMessage//Dump performance statistics for this frame.TheWritableGlobalData->m_dumpPerformanceStatistics = TRUE;TheInGameUI->message( UnicodeString( L"Statistics dump made on frame: %d" ), TheGameLogic->getFrame() );+ disp = DESTROY_MESSAGE;break;#endif // DUMP_PERF_STATSdiff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cppindex 0aa9e35f2..2607c620d 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp@@ -660,7 +660,7 @@ Bool Particle::update( const ParticleUpdateContext &context )else if (m_color.red > 1.0f)m_color.red = 1.0f;- if (m_color.red < 0.0f)+ if (m_color.green < 0.0f)m_color.green = 0.0f;else if (m_color.green > 1.0f)m_color.green = 1.0f;@@ -786,8 +786,9 @@ Bool Particle::isInvisible( const ParticleUpdateContext &context )case ParticleSystemInfo::ADDITIVE:// if color is black, this particle is invisible- // check that we're not in the process of going to another color- if (m_colorKey[ m_colorTargetKey ].frame == 0)+ // check that we're not in the process of going to another color; past the last key+ // frame the index is one beyond the array+ if (m_colorTargetKey >= MAX_KEYFRAMES || m_colorKey[ m_colorTargetKey ].frame == 0){if ((m_color.red + m_color.green + m_color.blue) <= 0.06f)return true;@@ -795,9 +796,13 @@ Bool Particle::isInvisible( const ParticleUpdateContext &context )return false;case ParticleSystemInfo::ALPHA:- // if alpha is zero, this particle is invisible- if (m_alpha < 0.02f)- return true;+ // if alpha is zero, this particle is invisible - but not while it is on its way to another+ // key, or a particle that fades in from zero slower than 0.02 a frame dies on its first update+ if (m_alphaTargetKey >= MAX_KEYFRAMES || m_alphaKey[ m_alphaTargetKey ].frame == 0)+ {+ if (m_alpha < 0.02f)+ return true;+ }return false;case ParticleSystemInfo::ALPHA_TEST:@@ -808,7 +813,7 @@ Bool Particle::isInvisible( const ParticleUpdateContext &context )// if color is white, this particle is invisible// check that we're not in the process of going to another color- if (m_colorKey[ m_colorTargetKey ].frame == 0)+ if (m_colorTargetKey >= MAX_KEYFRAMES || m_colorKey[ m_colorTargetKey ].frame == 0){if ((m_color.red * m_color.green * m_color.blue) > 0.95f)return true;diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cppindex ec607d218..4a8e46fbc 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp@@ -382,11 +382,11 @@ Bool AIGroup::getMinMaxAndCenter( Coord2D *min, Coord2D *max, Coord3D *center )max->y = max->y < objPos->y ? objPos->y : max->y;FormationID curID = (*i)->getFormationID() ;if (count==0) {- id = curID;- } else {- if (id == NO_FORMATION_ID) {- id = NO_FORMATION_ID;- }+ id = curID;+ } else if (curID != id) {+ // a formation only if every member is in the same one; this compared id with itself,+ // so the first member alone decided it+ id = NO_FORMATION_ID;}count++;@@ -1995,7 +1995,10 @@ void AIGroup::groupMoveToPosition( const Coord3D *p_posIn, Bool addWaypoint, ComBool tightenGroup = FALSE;Bool isFormation = getMinMaxAndCenter( &min, &max, ¢er );- if (addWaypoint)+ // a queued waypoint moves the members by their own offsets, which holds the shape anyway, so the+ // formation the player made survives it instead of being dropped by the first alt-click+ const Bool keepFormation = addWaypoint && isFormation;+ if (addWaypoint){isFormation = false;}@@ -2380,7 +2383,8 @@ void AIGroup::groupMoveToPosition( const Coord3D *p_posIn, Bool addWaypoint, ComBool firstUnit = true;for (theUnit = iter->first(); theUnit; theUnit = iter->next()){- theUnit->setFormationID(NO_FORMATION_ID);+ if (!keepFormation)+ theUnit->setFormationID(NO_FORMATION_ID);AIUpdateInterface *ai = theUnit->getAIUpdateInterface();if (firstUnit) {@@ -2838,9 +2842,11 @@ void AIGroup::groupIdle(CommandSourceType cmdSource)}else{- //Handle garrisoned buildings.+ //Handle garrisoned buildings. Stop is for the ones shooting out of them: passengers who+ //may not fire are there for the building's own job, and stopping them ended the hacking in+ //an Internet Center until every hacker was taken out and put back.ContainModuleInterface *contain = obj->getContain();- if( contain )+ if( contain && contain->isPassengerAllowedToFire() ){contain->iterateContained( makeMemberStop, &cmdSource, false );}diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cppindex 6fa82f71c..5f494b78a 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp@@ -544,9 +544,14 @@ void Path::appendNode( const Coord3D *pos, PathfindLayerEnum layer )node->setPosition( pos );node->setLayer(layer);- m_path = node->appendToList( m_path );+ // m_pathTail is always the last node of a non-empty m_path, so append there rather than+ // walking the whole list to find the end (appendToList) for every node added.+ if (m_path == NULL)+ m_path = node;+ else+ m_pathTail->append( node );- if (m_isOptimized && m_pathTail)+ if (m_isOptimized && m_pathTail){m_pathTail->setNextOptimized(node);}diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cppindex dbde5853b..d1ba6bc9a 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp@@ -693,7 +693,9 @@ void AIPlayer::queueSupplyTruck( void ){// This thinks he is a gatherer, but doesn't have a preferred dock id.Object *center = TheGameLogic->findObjectByID(info->getObjectID());- if (center) {+ // a GLA building that died leaves a rebuild hole in its build list slot, and a+ // hole is no dock: the gatherer drove to it and stood there+ if (center && !center->isKindOf(KINDOF_REBUILD_HOLE)) {info->setCurrentGatherers(info->getCurrentGatherers()+1);// Note - although this is the ai, we are sending in CMD_FROM_PLAYER.// This causes the dock object to stick in the docking interface.diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cppindex 8f7eec66d..056642234 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp@@ -151,10 +151,17 @@ void AISkirmishPlayer::processBaseBuilding( void )if (priorID == spawnerID) {DEBUG_LOG(("AI Found hole to rebuild %s\n", curPlan->getName().str()));info->setObjectID(obj->getID());+ break;}}}AIPlayer::profileBaseSubEnd( AIPlayer::BASE_SUB_HOLE );+ // The hole rebuilds it by itself. The bldg this pass tests further down is the outer+ // one, still the null lookup of the dead building, so the entry went on to be picked+ // for a dozer as well and a second copy went up beside the hole.+ if (info->getObjectID() != INVALID_ID) {+ continue;+ }} else {if (bldg->getControllingPlayer() == m_player) {// Check for built or dozer missing.@@ -1317,13 +1324,24 @@ void AISkirmishPlayer::xfer( Xfer *xfer ){// version- XferVersion currentVersion = 1;+ // 2: the current enemy and the frame to look for one again. Without them a loaded game picked+ // its enemy afresh on the first frame and played on differently from the one that was saved.+ XferVersion currentVersion = 2;XferVersion version = currentVersion;xfer->xferVersion( &version, currentVersion );// xfer base class infoAIPlayer::xfer( xfer );+ if( version >= 2 )+ {+ xfer->xferUnsignedInt( &m_frameToCheckEnemy );+ Int enemyIndex = m_currentEnemy ? m_currentEnemy->getPlayerIndex() : -1;+ xfer->xferInt( &enemyIndex );+ if( xfer->getXferMode() == XFER_LOAD )+ m_currentEnemy = enemyIndex >= 0 ? ThePlayerList->getNthPlayer( enemyIndex ) : NULL;+ }+// front base defensexfer->xferInt( &m_curFrontBaseDefense );diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cppindex 58167f612..e11d7c4f1 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp@@ -136,7 +136,10 @@ void AICommandParmsStorage::reconstitute(AICommandParms& parms) constvoid AICommandParmsStorage::doXfer(Xfer *xfer){xfer->xferUser(&m_cmd, sizeof(m_cmd));- xfer->xferUser(&m_cmd, sizeof(m_cmdSource));+ // EA wrote m_cmd a second time here, so a loaded command lost its source.+ // A save from before the fix holds a copy of m_cmd in this slot; the owners' xfer versions tell+ // them apart and reset the source with setCommandSource.+ xfer->xferUser(&m_cmdSource, sizeof(m_cmdSource));xfer->xferCoord3D(&m_pos);xfer->xferObjectID(&m_obj);xfer->xferObjectID(&m_otherObj);@@ -264,6 +267,19 @@ void AttackStateMachine::loadPostProcess( void )//----------------------------------------------------------------------------------------------------------static Bool inWeaponRangeObject(State *thisState, void* userData);+//----------------------------------------------------------------------------------------------------------+/**+ * A ground attack has no victim for cannotPossiblyAttackObject to look at, so nothing ended it when its+ * shooter's container stopped letting him fire: rocket soldiers in a Humvee kept shelling the ground from+ * inside the Chinook the Humvee drove into.+ */+static Bool passengerMayNotFire( State *thisState, void* userData )+{+ const Object *obj = thisState->getMachineOwner();+ const Object *containedBy = obj->getContainedBy();+ return containedBy && !containedBy->getContain()->isPassengerAllowedToFire( obj->getID() );+}+//----------------------------------------------------------------------------------------------------------/*** Create an AI state machine. Define all of the states the machine@@ -292,8 +308,9 @@ AttackStateMachine::AttackStateMachine( Object *obj, AIAttackState* att, AsciiStconst StateConditionInfo* objectConditions = forceAttacking ? objectConditionsForced : objectConditionsNormal;- static const StateConditionInfo positionConditions[] =+ static const StateConditionInfo positionConditions[] ={+ StateConditionInfo(passengerMayNotFire, EXIT_MACHINE_WITH_FAILURE, NULL),StateConditionInfo(outOfWeaponRangePosition, AttackStateMachine::CHASE_TARGET, NULL),StateConditionInfo(NULL, NULL, NULL) // keep last};@@ -2744,8 +2761,11 @@ StateReturnType AIAttackApproachTargetState::updateInternal()// one standing still.const Bool isTargetingMine = weapon && weapon->getDamageType() == DAMAGE_DISARM &&(victim->isKindOf(KINDOF_MINE) || victim->isKindOf(KINDOF_BOOBY_TRAP) || victim->isKindOf(KINDOF_DEMOTRAP));+ // our own and our allies' stealthed units are visible to us, so a force attack on one approaches+ const Bool isVisibleToUs = source->getControllingPlayer() == victim->getControllingPlayer() ||+ source->getRelationship(victim) == ALLIES;- if (!isTargetingMine)+ if (!isTargetingMine && !isVisibleToUs)return STATE_FAILURE;}ai->setCurrentVictim(victim);@@ -7069,7 +7089,11 @@ StateReturnType AIEnterState::update()// The partition manager doesn't generate collisions in the border area, so we have to// add ourselves. jba.ContainModuleInterface* contain = goal->getContain();- if (contain)+ if (obj->isKindOf(KINDOF_INFANTRY) && goal->isDisabledByType(DISABLED_UNMANNED))+ {+ goal->takeOverUnmanned(obj); // a driver, not a passenger - see OpenContain::onCollide+ }+ else if (contain){contain->addToContain(obj);}diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/TerrainLogic.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/TerrainLogic.cppindex 997ba1596..bc6546ae5 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/TerrainLogic.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/TerrainLogic.cpp@@ -2446,8 +2446,9 @@ void TerrainLogic::setWaterHeight( const WaterHandle *water, Real height, Real d// get other object positionobjPos = obj->getPosition();- // if this object is underwater, do some damage- if( isUnderwater( objPos->x, objPos->y ) )+ // if this object is underwater, do some damage; an aircraft or a bridge above the water is not+ Real waterZ;+ if( isUnderwater( objPos->x, objPos->y, &waterZ ) && objPos->z < waterZ ){// do a lot of water damagediff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Armor.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Armor.cppindex f422d5e3b..a89c391e7 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Armor.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Armor.cpp@@ -96,7 +96,7 @@ Real ArmorTemplate::adjustDamage(DamageType t, Real damage) constreturn;}- DamageType dt = (DamageType)DamageTypeFlags::getSingleBitFromName(damageName);+ DamageType dt = (DamageType)INI::scanIndexList(damageName, DamageTypeFlags::getBitNames());self->m_damageCoefficient[dt] = pct;}@@ -148,7 +148,8 @@ void ArmorStore::reset(){static const FieldParse myFieldParse[] ={- { "Armor", ArmorTemplate::parseArmorCoefficients, NULL, 0 }+ { "Armor", ArmorTemplate::parseArmorCoefficients, NULL, 0 },+ { NULL, NULL, NULL, 0 }};const char *c = ini->getNextToken();diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/HelixContain.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/HelixContain.cppindex ebbfafa0b..e15359841 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/HelixContain.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/HelixContain.cpp@@ -39,6 +39,7 @@#include "Common/ThingFactory.h"#include "GameClient/ControlBar.h"#include "GameClient/Drawable.h"+#include "GameLogic/ExperienceTracker.h"#include "GameLogic/Module/BodyModule.h"#include "GameLogic/Module/HelixContain.h"#include "GameLogic/Object.h"@@ -267,7 +268,7 @@ void HelixContain::addToContainList( Object *obj )//-------------------------------------------------------------------------------------------------void HelixContain::addToContain( Object *obj ){- if ( obj->isKindOf( KINDOF_PORTABLE_STRUCTURE ) && m_portableStructureID == INVALID_ID)+ if ( obj->isKindOf( KINDOF_PORTABLE_STRUCTURE ) && m_portableStructureID == INVALID_ID){Object *portable = getPortableStructure();if ( portable )@@ -276,6 +277,10 @@ void HelixContain::addToContain( Object *obj )m_portableStructureID = obj->getID();obj->friend_setContainedBy( getObject() );//fool portable into thinking my object is his container+ // The portable never goes through onContaining(), so the kills of the gattling or speaker on top+ // earned the Helix nothing; send them to the Helix the way OverlordContain does for its rider.+ if ( obj->getExperienceTracker() )+ obj->getExperienceTracker()->setExperienceSink( getObject()->getID() );}elsediff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cppindex 348b2c750..b7027fa81 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cpp@@ -463,6 +463,10 @@ void OpenContain::killAllContained( void )list.swap( m_containList );m_containListSize = 0;+ // the riders die in here; onRemoving played the door and the "getting out" voice for each of them+ const Bool soundsWereEnabled = m_loadSoundsEnabled;+ m_loadSoundsEnabled = FALSE;+ContainedItemsList::iterator it = list.begin();while ( it != list.end() )@@ -490,6 +494,7 @@ void OpenContain::killAllContained( void )} // end while+ m_loadSoundsEnabled = soundsWereEnabled;DEBUG_ASSERTCRASH( m_containListSize == 0, ("killallcontain just made a booboo, list size != zero.") );@@ -620,7 +625,7 @@ void OpenContain::iterateContained( ContainIterateFunc func, void *userData, BooObject* OpenContain::getClosestRider( const Coord3D *pos ){Object *closest = NULL;- Real closestDistance;+ Real closestDistance = 0.0f;for(ContainedItemsList::const_iterator it = m_containList.begin(); it != m_containList.end(); ++it){@@ -793,8 +798,11 @@ void OpenContain::onContaining( Object *rider, Bool wasSelected )}//--------------------------------------------------------------------------------------------------void OpenContain::onRemoving( Object *rider)+void OpenContain::onRemoving( Object *rider){+ if( !m_loadSoundsEnabled )+ return; // killAllContained: nobody is getting out+// Play audioAudioEventRTS exitSound = *getObject()->getTemplate()->getSoundExit();exitSound.setObjectID(getObject()->getID());@@ -843,6 +851,15 @@ void OpenContain::onCollide( Object *other, const Coord3D *loc, const Coord3D *nif (ai->getEnterTarget() != getObject())return;+ // An infantryman walking into an unmanned vehicle drives it away; he does not ride in it. When this+ // side of the collision came first he was taken in as a passenger instead, and a sniped Battle Bus+ // or Emperor stayed neutral with somebody shooting out of it.+ if( other->isKindOf( KINDOF_INFANTRY ) && getObject()->isDisabledByType( DISABLED_UNMANNED ) )+ {+ getObject()->takeOverUnmanned( other );+ return;+ }+// last-minute change: don't allow units from multiple (different) players to occupy the same// unit. so eject everyone else if they aren't controlled by the same player. (srj)for( ContainedItemsList::iterator it = m_containList.begin(); it != m_containList.end(); )diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cppindex d52424f36..59707b1e2 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp@@ -931,7 +931,7 @@ void Object::setOrRestoreTeam( Team* team, Bool restoring ){m_team->removeFrom_TeamMemberList(this);if (m_team->getControllingPlayer())- m_team->getControllingPlayer()->becomingTeamMember(this, false);+ m_team->getControllingPlayer()->becomingTeamMember(this, false, restoring);}}@@ -945,7 +945,7 @@ void Object::setOrRestoreTeam( Team* team, Bool restoring ){m_team->prependTo_TeamMemberList(this);if (m_team->getControllingPlayer())- m_team->getControllingPlayer()->becomingTeamMember(this, true);+ m_team->getControllingPlayer()->becomingTeamMember(this, true, restoring);}// now, adjust the attitude of the unit to its new team.@@ -2999,9 +2999,14 @@ void Object::friend_prepareForMapBoundaryAdjust(void)//-------------------------------------------------------------------------------------------------void Object::friend_notifyOfNewMapBoundary(void){- ThePartitionManager->registerObject(this);+ // A rider of an enclosing container stays out of the world the way OpenContain took it out:+ // registering it put a garrison's occupants back in reach of every splash weapon.+ const Bool enclosed = m_containedBy && m_containedBy->getContain()->isEnclosingContainerFor( this );+ if( !enclosed )+ ThePartitionManager->registerObject(this);TheRadar->addObject(this);- TheAI->pathfinder()->addObjectToPathfindMap( this );+ if( !enclosed )+ TheAI->pathfinder()->addObjectToPathfindMap( this );// Now that the PartitionManager has finished its reset, we need to relookhandlePartitionCellMaintenance();@@ -6590,6 +6595,28 @@ Bool Object::canProduceUpgrade( const UpgradeTemplate *upgrade )return FALSE;// Cheatin' punk.}+//-------------------------------------------------------------------------------------------------+/** An infantryman reaching an unmanned vehicle becomes its driver: the vehicle is his side's and+ * he is gone. The collision that brings him to it can arrive on either object first, so both+ * PhysicsUpdate (his) and OpenContain (the vehicle's) come here. */+//-------------------------------------------------------------------------------------------------+void Object::takeOverUnmanned( Object *pilot )+{+ clearDisabled( DISABLED_UNMANNED );++ //We need to be able to test whether an object on a team has been captured, so set here that this object+ //was captured.+ setCaptured(true);++ defect( pilot->getTeam(), 0 );++ //In order to make things easier for the designers, we are going to transfer the name+ //of the infantry to the vehicle... so the designer can control the vehicle with their scripts.+ TheScriptEngine->transferObjectName( pilot->getName(), this );++ TheGameLogic->destroyObject( pilot );+}+//=============================================================================// Object::defect, and related methods =//=============================================================================diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cppindex de3881730..a44a8564b 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp@@ -968,6 +968,14 @@ Bool AIUpdateInterface::chooseLocomotorSetExplicit(LocomotorSetType wst)const LocomotorTemplateVector* set = getAIUpdateModuleData()->findLocomotorTemplateVector(wst);if (set){+ // A dying aircraft keeps the locomotor it has. JetSlowDeathBehavior grounds a wreck by taking the+ // lift and the turn rate off the current Locomotor instance, and a rebuild from the templates+ // (the jet's attack or return set timing out, say) hands the wreck full lift back and it flies+ // on. LOCOMOTORSET_INVALID is a set not built yet, which loadPostProcess still has to build.+ const Object* obj = getObject();+ if (m_curLocomotorSet != LOCOMOTORSET_INVALID && obj->isEffectivelyDead() && obj->isKindOf(KINDOF_AIRCRAFT))+ return FALSE;+m_locomotorSet.clear();m_curLocomotor = NULL;for (Int i = 0; i < set->size(); ++i)diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/ChinookAIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/ChinookAIUpdate.cppindex 5bcafe033..7952545cd 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/ChinookAIUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/ChinookAIUpdate.cpp@@ -238,6 +238,7 @@ public:{// A chinook given transport duty loses his supplies.while( ai->loseOneBox() );+ ai->setForceWantingState(FALSE);}// kill any drift...@@ -1394,13 +1395,15 @@ void ChinookAIUpdate::crc( Xfer *xfer )// ------------------------------------------------------------------------------------------------/** Xfer method* Version Info:- * 1: Initial version */+ * 1: Initial version+ * 2: m_originalPos+ * 3: the pending command keeps its source */// ------------------------------------------------------------------------------------------------void ChinookAIUpdate::xfer( Xfer *xfer ){// version- XferVersion currentVersion = 2;+ XferVersion currentVersion = 3;XferVersion version = currentVersion;xfer->xferVersion( &version, currentVersion );// extend base class@@ -1409,6 +1412,8 @@ void ChinookAIUpdate::xfer( Xfer *xfer )xfer->xferBool(&m_hasPendingCommand);if (m_hasPendingCommand) {m_pendingCommand.doXfer(xfer);+ if (version < 3)+ m_pendingCommand.setCommandSource(CMD_FROM_AI);}xfer->xferUser(&m_flightStatus, sizeof(m_flightStatus));xfer->xferObjectID(&m_airfieldForHealing);diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/HackInternetAIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/HackInternetAIUpdate.cppindex 274b5c6c0..5c64972b8 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/HackInternetAIUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/HackInternetAIUpdate.cpp@@ -215,20 +215,23 @@ void HackInternetAIUpdate::crc( Xfer *xfer )// ------------------------------------------------------------------------------------------------/** Xfer method* Version Info:- * 1: Initial version */+ * 1: Initial version+ * 2: the pending command keeps its source */// ------------------------------------------------------------------------------------------------void HackInternetAIUpdate::xfer( Xfer *xfer ){// version- XferVersion currentVersion = 1;+ XferVersion currentVersion = 2;XferVersion version = currentVersion;xfer->xferVersion( &version, currentVersion );-+// extend base classAIUpdateInterface::xfer(xfer);xfer->xferBool(&m_hasPendingCommand);if (m_hasPendingCommand) {m_pendingCommand.doXfer(xfer);+ if (version < 2)+ m_pendingCommand.setCommandSource(CMD_FROM_AI);}} // end xferdiff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/JetAIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/JetAIUpdate.cppindex e07a3f0a7..bb434b113 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/JetAIUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/JetAIUpdate.cpp@@ -2671,13 +2671,14 @@ void JetAIUpdate::crc( Xfer *xfer )* Version Info:* 1: Initial version* 2: Save engine on/off state.- * 3: TheSuperHackers @bugfix Save the helipad landing position. */+ * 3: TheSuperHackers @bugfix Save the helipad landing position.+ * 4: the most recent command keeps its source */// ------------------------------------------------------------------------------------------------void JetAIUpdate::xfer( Xfer *xfer ){// version- XferVersion currentVersion = 3;+ XferVersion currentVersion = 4;XferVersion version = currentVersion;xfer->xferVersion( &version, currentVersion );@@ -2687,6 +2688,8 @@ void JetAIUpdate::xfer( Xfer *xfer )xfer->xferCoord3D(&m_producerLocation);m_mostRecentCommand.doXfer(xfer);+ if (version < 4)+ m_mostRecentCommand.setCommandSource(CMD_FROM_AI);xfer->xferUnsignedInt(&m_attackLocoExpireFrame);xfer->xferUnsignedInt(&m_attackersMissExpireFrame);xfer->xferUnsignedInt(&m_returnToBaseFrame);diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/MissileAIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/MissileAIUpdate.cppindex 36c1f6754..3898d9378 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/MissileAIUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/MissileAIUpdate.cpp@@ -389,6 +389,11 @@ void MissileAIUpdate::detonate(){Object* obj = getObject();+ // Once only. The kill state can detonate on arrival and a collision with the target land in the+ // same frame, before the missile is gone, and the warhead's damage was dealt twice.+ if( obj->testStatus( OBJECT_STATUS_MISSILE_KILLING_SELF ) )+ return;+if (m_detonationWeaponTmpl){diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/RailroadGuideAIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/RailroadGuideAIUpdate.cppindex 4a06bb3bb..c7fdc7103 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/RailroadGuideAIUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/RailroadGuideAIUpdate.cpp@@ -265,7 +265,8 @@ void RailroadBehavior::onCollide( Object *other, const Coord3D *loc, const Coordother->isKindOf( KINDOF_FS_FACTORY ) ||other->isKindOf( KINDOF_FS_BASE_DEFENSE ) ||other->isKindOf( KINDOF_FS_TECHNOLOGY ) ||- other->isKindOf( KINDOF_REBUILD_HOLE ) )+ other->isKindOf( KINDOF_REBUILD_HOLE ) ||+ other->isFactionStructure() ) // supply centers, fakes and internet centers carry none of the four above{playImpactSound(other, other->getPosition());other->kill();@@ -283,6 +284,7 @@ void RailroadBehavior::onCollide( Object *other, const Coord3D *loc, const Coordother->kill();return;}+ return; // any other structure is left standing}diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/SupplyTruckAIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/SupplyTruckAIUpdate.cppindex 958a53a41..40bb4aa28 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/SupplyTruckAIUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/SupplyTruckAIUpdate.cpp@@ -269,6 +269,20 @@ Real SupplyTruckAIUpdate::getWarehouseScanDistance() constreturn 2 * getSupplyTruckAIUpdateModuleData()->m_warehouseScanDistance;}+//-------------------------------------------------------------------------------------------------+/** A player's order ends the forced trip back to supply duty that a supply center gives a fresh+ * truck. */+//-------------------------------------------------------------------------------------------------+void SupplyTruckAIUpdate::aiDoCommand(const AICommandParms* parms)+{+ if (parms->m_cmdSource == CMD_FROM_PLAYER)+ {+ setForceWantingState(FALSE);+ }++ AIUpdateInterface::aiDoCommand(parms);+}+// ------------------------------------------------------------------------------------------------/** CRC */// ------------------------------------------------------------------------------------------------diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/WanderAIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/WanderAIUpdate.cppindex 9eebd53fd..eb0611bec 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/WanderAIUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/WanderAIUpdate.cpp@@ -55,9 +55,12 @@ UpdateSleepTime WanderAIUpdate::update( void )// If I'm standing still, move somewhereif (isIdle()){+ // 5 to 50 either way on each axis; the retail 5..50 only ever walked north eastCoord3D dest = *(getObject()->getPosition());- dest.x += GameLogicRandomValue( 5, 50 );- dest.y += GameLogicRandomValue( 5, 50 );+ const Int stepX = GameLogicRandomValue( -45, 45 );+ const Int stepY = GameLogicRandomValue( -45, 45 );+ dest.x += stepX < 0 ? stepX - 5 : stepX + 5;+ dest.y += stepY < 0 ? stepY - 5 : stepY + 5;aiMoveToPosition( &dest, CMD_FROM_AI );}diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/WorkerAIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/WorkerAIUpdate.cppindex 0e2393c3a..9b0308e7b 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/WorkerAIUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/WorkerAIUpdate.cpp@@ -427,7 +427,8 @@ Object *WorkerAIUpdate::construct( const ThingTemplate *what,// leave the supply truck state and now behave like a dozer.exitingSupplyTruckState();-+ setForceWantingState(FALSE);+// take the required money away from the playerif( isRebuild == FALSE ){@@ -721,6 +722,7 @@ void WorkerAIUpdate::newTask( DozerTask task, Object* target )getObject()->getAIUpdateInterface()->aiIdle(CMD_FROM_AI);}m_workerMachine->setState( AS_DOZER );+ setForceWantingState(FALSE);// To clarify, I leave supply truck mode when I notice I am doing something not supply// truck related. When given a construct command, I wait to do anything until I notice// I'm not busy. Both states are being polite, so I must force the switch.@@ -1074,7 +1076,10 @@ void WorkerAIUpdate::aiDoCommand(const AICommandParms* parms)// when a player issues commands, this will cause the dozer to re-evaluate what it's doingif( parms->m_cmdSource == CMD_FROM_PLAYER )+ {m_dozerMachine->resetToDefaultState();+ setForceWantingState(FALSE);+ }break;} // end defaultdiff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/DockUpdate/DockUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/DockUpdate/DockUpdate.cppindex 1a7b59b78..c28377a59 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/DockUpdate/DockUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/DockUpdate/DockUpdate.cpp@@ -585,13 +585,17 @@ void DockUpdate::crc( Xfer *xfer )} // end crc// -------------------------------------------------------------------------------------------------/** Xfer Method */+/** Xfer Method+ * Version Info:+ * 1: Initial version+ * 2: Save the approach position bone count. A load left it at -1 beside a TRUE m_positionsLoaded,+ * so a boneless dock stopped biasing the approach toward the arriving worker and gathering slowed. */// ------------------------------------------------------------------------------------------------void DockUpdate::xfer( Xfer *xfer ){// version- XferVersion currentVersion = 1;+ XferVersion currentVersion = 2;XferVersion version = currentVersion;xfer->xferVersion( &version, currentVersion );@@ -610,6 +614,10 @@ void DockUpdate::xfer( Xfer *xfer )// # approach positionsxfer->xferInt( &m_numberApproachPositions );+ // # approach position bones+ if( version >= 2 )+ xfer->xferInt( &m_numberApproachPositionBones );+// positions loadedxfer->xferBool( &m_positionsLoaded );diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/EMPUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/EMPUpdate.cppindex 0b11906e0..9c7e5790b 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/EMPUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/EMPUpdate.cpp@@ -238,9 +238,11 @@ void EMPUpdate::doDisableAttack( void )-////////////// // must match our kindof flags (if any)-////////////// if (data && !curVictim->isKindOfMulti(data->m_victimKindOf, data->m_victimKindOfNot))-////////////// continue;+ // must match our kindof flags (if any). VictimRequiredKindOf and VictimForbiddenKindOf were+ // parsed and then ignored with this commented out; no shipped EMP sets either, so both masks+ // are empty and this passes everything for them.+ if (!curVictim->isKindOfMulti(data->m_victimKindOf, data->m_victimKindOfNot))+ continue;diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/FlammableUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/FlammableUpdate.cppindex 8de2c056e..196b88a96 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/FlammableUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/FlammableUpdate.cpp@@ -323,4 +323,8 @@ void FlammableUpdate::loadPostProcess( void )// extend base classUpdateModule::loadPostProcess();+ // a save carries the burning state but not the playing handle, so the fire went silent on load+ if( m_status == FS_AFLAME )+ startBurningSound();+} // end loadPostProcessdiff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/HelicopterSlowDeathUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/HelicopterSlowDeathUpdate.cppindex fb0c9777a..b3c6d041a 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/HelicopterSlowDeathUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/HelicopterSlowDeathUpdate.cpp@@ -563,4 +563,16 @@ void HelicopterSlowDeathBehavior::loadPostProcess( void )// extend base classSlowDeathBehavior::loadPostProcess();+ // the death loop plays from the start of the spiral until the ground; a save carries neither the+ // event nor its handle, so a copter loaded mid-spiral fell in silence+ if( isSlowDeathActivated() && m_hitGroundFrame == 0 )+ {+ m_deathSound = getHelicopterSlowDeathBehaviorModuleData()->m_deathSound;+ if( m_deathSound.getEventName().isEmpty() == false )+ {+ m_deathSound.setObjectID( getObject()->getID() );+ m_deathSound.setPlayingHandle( TheAudio->addAudioEvent( &m_deathSound ) );+ }+ }+} // end loadPostProcessdiff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/MissileLauncherBuildingUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/MissileLauncherBuildingUpdate.cppindex b4b9841df..3cfcc583c 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/MissileLauncherBuildingUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/MissileLauncherBuildingUpdate.cpp@@ -329,4 +329,8 @@ void MissileLauncherBuildingUpdate::loadPostProcess( void )// extend base classUpdateModule::loadPostProcess();+ // the open-door loop starts on the switch to DOOR_OPEN, which a load does not repeat+ if( m_doorState == DOOR_OPEN )+ m_openIdleAudio.setPlayingHandle( TheAudio->addAudioEvent( &m_openIdleAudio ) );+} // end loadPostProcessdiff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ParticleUplinkCannonUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ParticleUplinkCannonUpdate.cppindex 241c74da0..f78b8caba 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ParticleUplinkCannonUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ParticleUplinkCannonUpdate.cpp@@ -297,6 +297,7 @@ Bool ParticleUplinkCannonUpdate::initiateIntentToDoSpecialPower(const SpecialPowm_startAttackFrame = TheGameLogic->getFrame();m_laserStatus = LASERSTATUS_NONE;m_manualTargetMode = TRUE;+ m_scriptedWaypointMode = FALSE; // a previous scripted run must not steer this one along its pathm_initialTargetPosition.set( targetPos );m_overrideTargetDestination.set( targetPos );m_currentTargetPosition.set( targetPos );@@ -316,6 +317,7 @@ Bool ParticleUplinkCannonUpdate::initiateIntentToDoSpecialPower(const SpecialPowpos.set( targetObj->getPosition() );}m_startAttackFrame = max( now, (UnsignedInt)1 );+ m_manualTargetMode = FALSE;m_scriptedWaypointMode = TRUE;m_laserStatus = LASERSTATUS_NONE;setLogicalStatus( STATUS_READY_TO_FIRE );@@ -348,6 +350,14 @@ Bool ParticleUplinkCannonUpdate::initiateIntentToDoSpecialPower(const SpecialPow{pos.set( targetObj->getPosition() );}+ else+ {+ // nothing to aim at; pos would be uninitialised+ return FALSE;+ }+ // the flags a previous manual or scripted-waypoint run left set would take this one over+ m_manualTargetMode = FALSE;+ m_scriptedWaypointMode = FALSE;m_initialTargetPosition.set( &pos );m_startAttackFrame = max( now, (UnsignedInt)1 );m_laserStatus = LASERSTATUS_NONE;diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/PhysicsUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/PhysicsUpdate.cppindex 6530da10b..2cb73c2fb 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/PhysicsUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/PhysicsUpdate.cpp@@ -1232,20 +1232,7 @@ void PhysicsBehavior::onCollide( Object *other, const Coord3D *loc, const Coord3{//This is in fact the case, and we are doing it here because it applies to all infantry in any unmanned vehicle.//This could be done via a special/new module, but doing it here doesn't require a new module update to every infantry.- other->clearDisabled( DISABLED_UNMANNED );-- //We need to be able to test whether an object on a team has been captured, so set here that this object- //was captured.- other->setCaptured(true);-- other->defect( obj->getTeam(), 0 );- //other->setTeam( obj->getTeam() );-- //In order to make things easier for the designers, we are going to transfer the name- //of the infantry to the vehicle... so the designer can control the vehicle with their scripts.- TheScriptEngine->transferObjectName( obj->getName(), other );-- TheGameLogic->destroyObject( obj );+ other->takeOverUnmanned( obj );}return;}diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ProductionUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ProductionUpdate.cppindex 18b065fa5..4045f09f4 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ProductionUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ProductionUpdate.cpp@@ -169,6 +169,7 @@ ProductionEntry::ProductionEntry( void )m_productionQuantityProduced = 0;m_productionQuantityTotal = 0;//+ m_costPaid = 0;} // end ProductionEntry//-------------------------------------------------------------------------------------------------@@ -305,12 +306,13 @@ Bool ProductionUpdate::queueUpgrade( const UpgradeTemplate *upgrade )// take the cost for the build away from the playerMoney *money = player->getMoney();- money->withdraw( upgrade->calcCostToBuild( player ) );+ const UnsignedInt costPaid = money->withdraw( upgrade->calcCostToBuild( player ) );// allocate a new production entryProductionEntry *production = newInstance(ProductionEntry);// assing production entry data+ production->m_costPaid = costPaid;production->m_type = PRODUCTION_UPGRADE;production->m_upgradeToResearch = upgrade;production->m_productionID = PRODUCTIONID_INVALID; // not needed for upgrades, you can only have one of@@ -373,7 +375,7 @@ void ProductionUpdate::cancelUpgrade( const UpgradeTemplate *upgrade )if( refundIt ){Money *money = player->getMoney();- money->deposit( production->m_upgradeToResearch->calcCostToBuild( player ) );+ money->deposit( production->m_costPaid );}// remove this production from the queue@@ -456,11 +458,12 @@ Bool ProductionUpdate::queueCreateUnit( const ThingTemplate *unitType, Productio// take the cost for the build away from the playerPlayer *player = getObject()->getControllingPlayer();Money *money = player->getMoney();- money->withdraw( unitType->calcCostToBuild( player ) );+ const UnsignedInt costPaid = money->withdraw( unitType->calcCostToBuild( player ) );// allocate a new production entryProductionEntry *production = newInstance(ProductionEntry);+ production->m_costPaid = costPaid;production->m_productionQuantityTotal = getQuantityPerOrder( unitType );production->m_productionQuantityProduced = 0;@@ -504,7 +507,7 @@ Bool ProductionUpdate::cancelUnitCreate( ProductionID productionID )// give the player the cost of the object backPlayer *player = getObject()->getControllingPlayer();Money *money = player->getMoney();- money->deposit( production->m_objectToProduce->calcCostToBuild( player ) );+ money->deposit( production->m_costPaid );// remove from queue listremoveFromProductionQueue( production );@@ -1346,7 +1349,8 @@ void ProductionUpdate::xfer( Xfer *xfer ){// version- XferVersion currentVersion = 1;+ // 2: each entry carries what was paid for it+ XferVersion currentVersion = 2;XferVersion version = currentVersion;xfer->xferVersion( &version, currentVersion );@@ -1397,6 +1401,9 @@ void ProductionUpdate::xfer( Xfer *xfer )// exit doorxfer->xferInt( (Int*)&production->m_exitDoor );+ // cost paid+ xfer->xferUnsignedInt( &production->m_costPaid );+} // end for} // end if, save@@ -1486,6 +1493,14 @@ void ProductionUpdate::xfer( Xfer *xfer )// exit doorxfer->xferInt( (Int*)&production->m_exitDoor );+ // cost paid; an older save refunds at today's price, as it always did+ if( version >= 2 )+ xfer->xferUnsignedInt( &production->m_costPaid );+ else if( production->m_type == PRODUCTION_UNIT )+ production->m_costPaid = production->m_objectToProduce->calcCostToBuild( getObject()->getControllingPlayer() );+ else+ production->m_costPaid = production->m_upgradeToResearch->calcCostToBuild( getObject()->getControllingPlayer() );+} // end for, i} // end else, loaddiff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/SpecialAbilityUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/SpecialAbilityUpdate.cppindex cded6c301..6b2011d65 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/SpecialAbilityUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/SpecialAbilityUpdate.cpp@@ -2113,4 +2113,13 @@ void SpecialAbilityUpdate::loadPostProcess( void )// extend base classUpdateModule::loadPostProcess();+ // the prep loop plays from startPreparation to endPreparation, the span the using-ability status+ // marks; a save keeps the status but not the playing handle+ if( m_active && getObject()->testStatus( OBJECT_STATUS_IS_USING_ABILITY ) )+ {+ m_prepSoundLoop = getSpecialAbilityUpdateModuleData()->m_prepSoundLoop;+ m_prepSoundLoop.setObjectID( getObject()->getID() );+ m_prepSoundLoop.setPlayingHandle( TheAudio->addAudioEvent( &m_prepSoundLoop ) );+ }+} // end loadPostProcessdiff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/StealthUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/StealthUpdate.cppindex 106b4c9f0..34613880f 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/StealthUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/StealthUpdate.cpp@@ -324,6 +324,13 @@ Bool StealthUpdate::allowedToStealth( Object *stealthOwner ) const{return FALSE;}++ // A vehicle whose crew was killed belongs to nobody, and no detector reveals a stealthed object it+ // is not an enemy of, so it stayed invisible to everyone for good. It stealths again once manned.+ if( self->isDisabledByType( DISABLED_UNMANNED ) )+ {+ return FALSE;+ }if( flags & STEALTH_NOT_WHILE_TAKING_DAMAGE && self->getBodyModule()->getLastDamageTimestamp() >= now - 1 ){diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cppindex 1885a7b26..bfed8cdea 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp@@ -2084,8 +2084,17 @@ void Weapon::onWeaponBonusChange(const Object *source)if( needUpdate ){- m_whenLastReloadStarted = TheGameLogic->getFrame();- m_whenWeCanFireAgain = m_whenLastReloadStarted + newDelay;+ // Carry the progress over rather than starting the wait again: a propaganda tower's rate of fire+ // bonus coming or going used to restart the whole reload, so a Nuke Cannon walking in and out of+ // range of one never got to fire. Half way through the old wait is half way through the new one.+ const UnsignedInt now = TheGameLogic->getFrame();+ const UnsignedInt oldDelay = m_whenWeCanFireAgain > m_whenLastReloadStarted ? m_whenWeCanFireAgain - m_whenLastReloadStarted : 0;+ const UnsignedInt elapsed = now > m_whenLastReloadStarted ? now - m_whenLastReloadStarted : 0;+ UnsignedInt newElapsed = 0;+ if( oldDelay > 0 && newDelay > 0 )+ newElapsed = (UnsignedInt)( (Real)min( elapsed, oldDelay ) / (Real)oldDelay * (Real)newDelay );+ m_whenLastReloadStarted = now - min( newElapsed, now );+ m_whenWeCanFireAgain = m_whenLastReloadStarted + newDelay;if (source->isReloadTimeShared()){@@ -3024,6 +3033,11 @@ static void makeAssistanceRequest( Object *requestOf, void *userData )if( requestOf == requestData->m_requestingObject )return;+ // Nor the battery being shot at: it took the lock onto its long-range assist weapon, could not+ // fire at itself, and went hunting with that range instead.+ if( requestOf == requestData->m_victimObject )+ return;+// Only request of our kind of peopleif( !requestOf->getTemplate()->isEquivalentTo( requestData->m_requestingObject->getTemplate() ) )return;diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/WeaponSet.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/WeaponSet.cppindex afe7e0efd..2a6df01a1 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/WeaponSet.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/WeaponSet.cpp@@ -209,12 +209,13 @@ void WeaponSet::crc( Xfer *xfer )// ------------------------------------------------------------------------------------------------/** Xfer method* Version Info:- * 1: Initial version */+ * 1: Initial version+ * 2: m_hasPitchLimit is written where m_hasDamageWeapon used to be written twice */// ------------------------------------------------------------------------------------------------void WeaponSet::xfer( Xfer *xfer ){// version- const XferVersion currentVersion = 1;+ const XferVersion currentVersion = 2;XferVersion version = currentVersion;xfer->xferVersion( &version, currentVersion );@@ -285,8 +286,16 @@ void WeaponSet::xfer( Xfer *xfer )xfer->xferUser(&m_curWeaponLockedStatus, sizeof(m_curWeaponLockedStatus));xfer->xferUnsignedInt(&m_filledWeaponSlotMask);xfer->xferInt(&m_totalAntiMask);+ xfer->xferBool(version >= 2 ? &m_hasPitchLimit : &m_hasDamageWeapon);xfer->xferBool(&m_hasDamageWeapon);- xfer->xferBool(&m_hasDamageWeapon);+ if (version < 2)+ {+ // a version 1 save never held the flag, so rebuild it from the loaded weapons+ m_hasPitchLimit = false;+ for (Int i = 0; i < WEAPONSLOT_COUNT; ++i)+ if (m_weapons[i] != NULL && m_weapons[i]->isPitchLimited())+ m_hasPitchLimit = true;+ }m_totalDamageTypeMask.xfer(xfer);// BitSet has built in xferdiff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptActions.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptActions.cppindex eb2195a15..b3075e7ac 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptActions.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptActions.cpp@@ -5591,6 +5591,8 @@ void ScriptActions::doTeamUseCommandButtonOnNearestGarrisonedBuilding( const Asc}PartitionFilterPlayerAffiliation f1(team->getControllingPlayer(), ALLOW_ENEMIES, true);+ // the affiliation filter lets the player's own objects through whatever it is asked for+ PartitionFilterPlayer notOwn(team->getControllingPlayer(), false);PartitionFilterAcceptByKindOf f2(MAKE_KINDOF_MASK(KINDOF_STRUCTURE), KINDOFMASK_NONE);PartitionFilterGarrisonable f3(true);PartitionFilterValidCommandButtonTarget f4(srcObj, commandButton, true, CMD_FROM_SCRIPT);@@ -5599,7 +5601,7 @@ void ScriptActions::doTeamUseCommandButtonOnNearestGarrisonedBuilding( const AscCoord3D pos;theGroup->getCenter(&pos);- PartitionFilter *filters[] = { &f1, &f2, &f3, &f4, &filterMapStatus, 0 };+ PartitionFilter *filters[] = { &f1, ¬Own, &f2, &f3, &f4, &filterMapStatus, 0 };Object *obj = ThePartitionManager->getClosestObject(&pos, REALLY_FAR, FROM_CENTER_2D, filters);if (!obj) {return;diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/Scripts.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/Scripts.cppindex d1f61a70f..b4a9f911c 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/Scripts.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/Scripts.cpp@@ -970,13 +970,15 @@ void Script::crc( Xfer *xfer )// ------------------------------------------------------------------------------------------------/** Xfer method* Version Info:- * 1: Initial version */+ * 1: Initial version+ * 2: The next evaluation frame of a delayed script. Without it every delayed script ran its+ * conditions on the first frame after a load instead of waiting out its delay. */// ------------------------------------------------------------------------------------------------void Script::xfer( Xfer *xfer ){// version- XferVersion currentVersion = 1;+ XferVersion currentVersion = 2;XferVersion version = currentVersion;xfer->xferVersion( &version, currentVersion );@@ -985,6 +987,9 @@ void Script::xfer( Xfer *xfer )xfer->xferBool( &active );setActive( active );+ if( version >= 2 )+ xfer->xferUnsignedInt( &m_frameToEvaluateAt );+} // end xfer// ------------------------------------------------------------------------------------------------diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/VictoryConditions.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/VictoryConditions.cppindex 2fce3dad5..c8f8b0dba 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/VictoryConditions.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/VictoryConditions.cpp@@ -180,6 +180,8 @@ void VictoryConditions::update( void ){m_singleAllianceRemaining = true; // don't check againm_endFrame = TheGameLogic->getFrame();+ // the score screen shows the match as it was decided, not what the winner did during the victory window+ TheGameLogic->enableScoring(FALSE);}}diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/Damage.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/Damage.cppindex 6012a3361..70f16f64b 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/Damage.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/Damage.cpp@@ -147,7 +147,7 @@ void DamageInfoInput::xfer( Xfer *xfer )xfer->xferReal( &m_amount );// kill no matter what (old versions default to FALSE).- if( currentVersion >= 2 )+ if( version >= 2 ){xfer->xferBool( &m_kill );}diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cppindex 0b3f4076f..af6c403dd 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp@@ -1289,25 +1289,14 @@ void GameLogic::startNewGame( Bool loadingSaveGame )Bool isSkirmishOrSkirmishReplay = FALSE;if (game){+ // Random color, position and faction are drawn off the logical seed. A restarted game puts+ // the pre-draw values back so the same draws happen again (see GameInfo::handleOriginalSetups).+ if (!loadingSaveGame)+ game->handleOriginalSetups();+for (Int i=0; i<MAX_SLOTS; ++i){GameSlot *slot = game->getSlot(i);- if (!loadingSaveGame) {- if (slot->hasSavedOriginalSetup())- {- DEBUG_ASSERTCRASH(m_gameMode == GAME_SKIRMISH, ("Expected GAME_SKIRMISH but got %d", m_gameMode));-- // Random color, position and faction are drawn off the logical seed. A restarted- // game puts the pre-draw values back so the same draws happen again.- slot->setColor(slot->getOriginalColor());- slot->setStartPos(slot->getOriginalStartPos());- slot->setPlayerTemplate(slot->getOriginalPlayerTemplate());- }- else- {- slot->saveOriginalSetup();- }- }if (slot->isAI()){isSkirmishOrSkirmishReplay = TRUE;@@ -1317,6 +1306,8 @@ void GameLogic::startNewGame( Bool loadingSaveGame )} else {if (m_gameMode == GAME_SINGLE_PLAYER) {if (TheSkirmishGameInfo) {+ if (TheGameInfo == TheSkirmishGameInfo)+ TheGameInfo = NULL; // or it is left pointing at freed memorydelete TheSkirmishGameInfo;TheSkirmishGameInfo = NULL;}@@ -1530,9 +1521,9 @@ void GameLogic::startNewGame( Bool loadingSaveGame )}}- AsciiString slotNameAscii;- slotNameAscii.translate(slot->getName());- if (slot->isHuman() && game->getSlotNum(slotNameAscii) == game->getLocalSlotNum()) {+ // by index: the name went through an ASCII translate and back, which no name with a+ // letter outside Latin-1 survives, so such a player started with the host's camera+ if (slot->isHuman() && i == game->getLocalSlotNum()) {localSlot = i;}TheSidesList->addSide(&d);@@ -2551,12 +2542,22 @@ void GameLogic::loadMapINI( AsciiString mapName )*extension = 0;+ //+ // A map's rules file comes with the map, and a mod map with a block this game does not know+ // (a DeleteKey, say) threw out of here and took the whole game down at the loading screen.+ // Keep what parsed up to the bad line and play on: every machine in a match has the same file,+ // the map CRC sees to that, so each stops at the same line and the rules still agree.+ //_snprintf(fullFledgeFilename, _MAX_PATH, "%s\\map.ini", filename); fullFledgeFilename[_MAX_PATH-1] = 0;if (TheFileSystem->doesFileExist(fullFledgeFilename)) {DEBUG_LOG(("Loading map.ini\n"));INI ini;ini.setSkipUnknownFields( TRUE );- ini.load( AsciiString(fullFledgeFilename), INI_LOAD_CREATE_OVERRIDES, NULL );+ try {+ ini.load( AsciiString(fullFledgeFilename), INI_LOAD_CREATE_OVERRIDES, NULL );+ } catch (...) {+ DEBUG_LOG(("%s does not parse, the rest of it is ignored\n", fullFledgeFilename));+ }}_snprintf(fullFledgeFilename, _MAX_PATH, "%s\\solo.ini", filename); fullFledgeFilename[_MAX_PATH-1] = 0;@@ -2564,7 +2565,11 @@ void GameLogic::loadMapINI( AsciiString mapName )DEBUG_LOG(("Loading solo.ini\n"));INI ini;ini.setSkipUnknownFields( TRUE );- ini.load( AsciiString(fullFledgeFilename), INI_LOAD_CREATE_OVERRIDES, NULL );+ try {+ ini.load( AsciiString(fullFledgeFilename), INI_LOAD_CREATE_OVERRIDES, NULL );+ } catch (...) {+ DEBUG_LOG(("%s does not parse, the rest of it is ignored\n", fullFledgeFilename));+ }}// No error here. There could've just *not* been a map.ini file.diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameInfo.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameInfo.cppindex 2a92ac01a..1721132a9 100644--- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameInfo.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameInfo.cpp@@ -73,6 +73,7 @@ void GameSlot::reset()m_NATBehavior = FirewallHelperClass::FIREWALL_TYPE_SIMPLE;m_lastFrameInGame = 0;m_disconnected = FALSE;+ m_IP = 0;m_port = 0;m_isMuted = FALSE;m_hasSavedOriginalSetup = FALSE;@@ -1025,11 +1026,131 @@ Bool GameInfo::isSandbox(void)static const char slotListID = 'S';+// The longest prefix of a UTF-8 name, at most maxBytes long, that does not cut a character in half:+// a continuation byte (10xxxxxx) at the cut belongs to the character before it.+static Int utf8PrefixLength( const AsciiString& name, Int maxBytes )+{+ const Int len = name.getLength();+ if (len <= maxBytes)+ return len;++ Int cut = maxBytes;+ while (cut > 0 && (((unsigned char)name.str()[cut]) & 0xC0) == 0x80)+ --cut;+ return cut;+}++static void truncatePlayerName( AsciiString& name, Int maxBytes )+{+ const Int cut = utf8PrefixLength(name, maxBytes);+ while (name.getLength() > cut)+ name.removeLastChar();+}++// Bytes of the first whole character of the name, 0 when there is none.+static Int getMinPlayerNameLength( const AsciiString& name )+{+ for (Int maxBytes = 1; maxBytes <= name.getLength(); ++maxBytes)+ {+ const Int cut = utf8PrefixLength(name, maxBytes);+ if (cut > 0)+ return cut;+ }+ return 0;+}++// Share maxPlayerNamesLength bytes between the human players' names, every one keeping at least its+// first character, and a name shorter than its share handing what it does not use to the ones after.+static Bool truncatePlayerNames( const GameInfo *game, AsciiString playerNames[MAX_SLOTS], Int maxPlayerNamesLength )+{+ Int minLengths[MAX_SLOTS] = { 0 };+ Int minTotalLength = 0;+ Int playerCount = 0;+ Int i;++ for (i = 0; i < MAX_SLOTS; ++i)+ {+ const GameSlot *slot = game->getConstSlot(i);+ if (slot && slot->isHuman())+ {+ minLengths[i] = getMinPlayerNameLength(playerNames[i]);+ if (minLengths[i] == 0)+ return FALSE;+ minTotalLength += minLengths[i];+ ++playerCount;+ }+ }++ if (playerCount == 0 || maxPlayerNamesLength < minTotalLength)+ return FALSE;++ Int remainingLength = maxPlayerNamesLength;+ for (i = 0; i < MAX_SLOTS; ++i)+ {+ const GameSlot *slot = game->getConstSlot(i);+ if (slot && slot->isHuman())+ {+ const Int extraLength = (remainingLength - minTotalLength) / playerCount;+ truncatePlayerName(playerNames[i], minLengths[i] + extraLength);+ remainingLength -= playerNames[i].getLength();+ minTotalLength -= minLengths[i];+ --playerCount;+ }+ }++ return TRUE;+}++static AsciiString buildGameInfoAsciiString( const GameInfo *game, const AsciiString playerNames[MAX_SLOTS] );++//+// The LAN packet has room for m_lanMaxOptionsLength bytes of this. EA shortened each name while it+// appended the slots, sharing what was left between the slots still to come; once the fixed fields+// had used it all the share went negative, the name emptied, and removeLastChar on an empty string+// looped forever - the host of a room with long names hung. The string is built with whole names+// first and only rebuilt with shortened ones when it does not fit.+//AsciiString GameInfoToAsciiString( const GameInfo *game ){if (!game)return AsciiString::TheEmptyString;+ AsciiString playerNames[MAX_SLOTS];+ Int playerNamesLength = 0;+ for (Int i = 0; i < MAX_SLOTS; ++i)+ {+ const GameSlot *slot = game->getConstSlot(i);+ if (slot && slot->isHuman())+ {+ playerNames[i] = WideCharStringToMultiByte(slot->getName().str()).c_str();+ playerNamesLength += playerNames[i].getLength();+ }+ }++ AsciiString optionsString = buildGameInfoAsciiString(game, playerNames);+ Bool optionsFit = TheLAN == NULL || optionsString.getLength() <= m_lanMaxOptionsLength;+ if (!optionsFit)+ {+ const Int fixedLength = optionsString.getLength() - playerNamesLength;+ if (truncatePlayerNames(game, playerNames, m_lanMaxOptionsLength - fixedLength))+ {+ optionsString = buildGameInfoAsciiString(game, playerNames);+ optionsFit = optionsString.getLength() <= m_lanMaxOptionsLength;+ }+ }++ if (!optionsFit)+ {+ DEBUG_CRASH(("WARNING: options string cannot fit within the expected length! Length is %d, but max is %d!\n",+ optionsString.getLength(), m_lanMaxOptionsLength));+ return AsciiString::TheEmptyString;+ }++ return optionsString;+}++static AsciiString buildGameInfoAsciiString( const GameInfo *game, const AsciiString playerNames[MAX_SLOTS] )+{AsciiString mapName = game->getMap();mapName = TheGameState->realMapPathToPortableMapPath(mapName);AsciiString newMapName;@@ -1078,15 +1199,8 @@ AsciiString GameInfoToAsciiString( const GameInfo *game )slot->getColor(), slot->getPlayerTemplate(),slot->getStartPos(), slot->getTeamNumber(),slot->getNATBehavior() );- //make sure name doesn't cause overflow of m_lanMaxOptionsLength- int lenCur = tmp.getLength() + optionsString.getLength() + 2; //+2 for H and trailing ;- int lenRem = m_lanMaxOptionsLength - lenCur; //length remaining before overflowing- int lenMax = lenRem / (MAX_SLOTS-i); //share lenRem with all remaining slots- AsciiString name = WideCharStringToMultiByte(slot->getName().str()).c_str();- while( name.getLength() > lenMax )- name.removeLastChar(); //what a horrible way to truncate. I hate AsciiString.-- str.format( "H%s%s", name.str(), tmp.str() );++ str.format( "H%s%s", playerNames[i].str(), tmp.str() );}else if (slot && slot->isAI()){@@ -1111,10 +1225,6 @@ AsciiString GameInfoToAsciiString( const GameInfo *game )}optionsString.concat(';');- DEBUG_ASSERTCRASH(!TheLAN || (optionsString.getLength() < m_lanMaxOptionsLength),- ("WARNING: options string is longer than expected! Length is %d, but max is %d!\n",- optionsString.getLength(), m_lanMaxOptionsLength));-return optionsString;}@@ -1799,4 +1909,28 @@ void SkirmishGameInfo::loadPostProcess( void ){} // end loadPostProcess+//+// Random color, position and faction are drawn off the logical seed. A restarted game puts the+// pre-draw values back so the same draws happen again. The recorder writes the slot list before+// GameLogic::tryStartNewGame runs, so both call this: done only in tryStartNewGame, the replay of a+// restarted skirmish recorded the first game's drawn values and every playback of it mismatched.+//+void GameInfo::handleOriginalSetups( void )+{+ for (Int i = 0; i < MAX_SLOTS; ++i)+ {+ GameSlot *slot = getSlot(i);+ if (slot->hasSavedOriginalSetup())+ {+ slot->setColor(slot->getOriginalColor());+ slot->setStartPos(slot->getOriginalStartPos());+ slot->setPlayerTemplate(slot->getOriginalPlayerTemplate());+ }+ else+ {+ slot->saveOriginalSetup();+ }+ }+}+diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/MainMenuUtils.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/MainMenuUtils.cppindex 6745de8f6..262664fff 100644--- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/MainMenuUtils.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/MainMenuUtils.cpp@@ -44,6 +44,8 @@#include "GameClient/ShellHooks.h"#include "GameSpy/ghttp/ghttp.h"+// Must follow ghttp.h: gsavailable.h uses gsi_char without including gsplatform.h.+#include "GameSpy/gsavailable.h"#include "GameNetwork/DownloadManager.h"#include "GameNetwork/GameSpy/BuddyThread.h"@@ -64,6 +66,14 @@static Bool checkingForPatchBeforeGameSpy = FALSE;static Int checksLeftBeforeOnline = 0;++// The GameSpy SDK checks this before every backend call: peerInitialize() returns NULL until it is+// GSIACAvailable, and nothing here ever ran the check, so going online faulted on that NULL peer.+static GSIACResult availableCheckResult = GSIACWaiting;+// Kept apart from the result so a cancelled check cannot decrement checksLeftBeforeOnline after+// CancelPatchCheckCallback() has reset it.+static Bool availableCheckInProgress = FALSE;+static Int timeThroughOnline = 0; // used to avoid having old callbacks cause problemsstatic Bool mustDownloadPatch = FALSE;static Bool cantConnectBeforeOnline = FALSE;@@ -145,6 +155,12 @@ static void noPatchBeforeOnlineCallback( void )}}+// the backend is unavailable: back to the menu+static void backendUnavailableCallback( void )+{+ HandleCanceledDownload();+}+///////////////////////////////////////////////////////////////////////////////////////static Bool hasWriteAccess()@@ -221,6 +237,16 @@ static void startOnline( void )TheScriptEngine->signalUIInteract(TheShellHookNames[SHELL_SCRIPT_HOOK_MAIN_MENU_ONLINE_SELECTED]);+ if (availableCheckResult != GSIACAvailable)+ {+ // The backend reported the title disabled; every GameSpy thread would fail to start.+ // noPatchBeforeOnlineCallback() would call startOnline() again and reopen this box.+ MessageBoxOk(TheGameText->fetch("GUI:GSErrorTitle"),+ TheGameText->fetch("GUI:GSDisconReason4"),+ backendUnavailableCallback);+ return;+ }+DEBUG_ASSERTCRASH( !TheGameSpyBuddyMessageQueue, ("TheGameSpyBuddyMessageQueue exists!") );DEBUG_ASSERTCRASH( !TheGameSpyPeerMessageQueue, ("TheGameSpyPeerMessageQueue exists!") );DEBUG_ASSERTCRASH( !TheGameSpyInfo, ("TheGameSpyInfo exists!") );@@ -587,6 +613,11 @@ void CancelPatchCheckCallbackAndReopenDropdown( void )void CancelPatchCheckCallback( void ){s_asyncDNSLookupInProgress = FALSE;+ if (availableCheckInProgress)+ {+ GSICancelAvailableCheck();+ availableCheckInProgress = FALSE;+ }HandleCanceledDownload(FALSE); // don't dropdowncheckingForPatchBeforeGameSpy = FALSE;checksLeftBeforeOnline = 0;@@ -748,6 +779,30 @@ void HTTPThinkWrapper( void )}}+ // GSIAvailableCheckThink() is what advances the check; it has to be called until it stops+ // returning GSIACWaiting. It counts as one of checksLeftBeforeOnline, so startOnline() waits+ // for it the same way it waits for the HTTP fetches.+ if (availableCheckInProgress)+ {+ availableCheckResult = GSIAvailableCheckThink();+ if (availableCheckResult != GSIACWaiting)+ {+ availableCheckInProgress = FALSE;+ --checksLeftBeforeOnline;+ DEBUG_ASSERTCRASH(checksLeftBeforeOnline>=0, ("Too many callbacks"));+ if (onlineCancelWindow && checksLeftBeforeOnline == 0)+ {+ TheWindowManager->winDestroy(onlineCancelWindow);+ onlineCancelWindow = NULL;+ }++ DEBUG_LOG(("Availability check returned %d\n", availableCheckResult));++ if (checksLeftBeforeOnline == 0)+ startOnline();+ }+ }+if (isHttpOk){try@@ -809,7 +864,12 @@ void StartPatchCheck( void )static void reallyStartPatchCheck( void ){- checksLeftBeforeOnline = 4;+ checksLeftBeforeOnline = 5; // the four ghttp calls below, plus the availability check++ GSICancelAvailableCheck(); // going online can be retried; do not leak the last attempt's socket+ availableCheckResult = GSIACWaiting;+ availableCheckInProgress = TRUE;+ GSIStartAvailableCheck("ccgenzh");std::string gameURL, mapURL;std::string configURL, motdURL;diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/PeerDefs.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/PeerDefs.cppindex c4a94f92f..51dc86cbf 100644--- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/PeerDefs.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/PeerDefs.cpp@@ -70,6 +70,8 @@ GameSpyInfo::GameSpyInfo()GameSpyInfo::~GameSpyInfo(){+ if (TheGameInfo == TheGameSpyGame)+ TheGameInfo = NULL; // the staging room is ours and goes with usTheGameSpyGame = NULL;reset();}diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/StagingRoomGameInfo.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/StagingRoomGameInfo.cppindex 01d63a2f8..118bb10f3 100644--- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/StagingRoomGameInfo.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/StagingRoomGameInfo.cpp@@ -271,7 +271,9 @@ Bool GetLocalChatConnectionAddress(AsciiString serverName, UnsignedShort serverP** Set up the bind list.*/bind_ptr->name.idLength = ARRAY_SIZE(mib_ii_name);- bind_ptr->name.ids = mib_ii_name;+ // the heap copy, not the stack array: every GETNEXT frees the name it was handed and puts the+ // next one in its place, and freeing mib_ii_name corrupted the heap on the way into the lobby+ bind_ptr->name.ids = mib_ii_name_ptr;bind_list_ptr->list = bind_ptr;bind_list_ptr->len = 1;@@ -393,9 +395,10 @@ Bool GetLocalChatConnectionAddress(AsciiString serverName, UnsignedShort serverP}}+ // the name is the last one the query allocated; mib_ii_name_ptr went with the first GETNEXT+ SnmpUtilMemFreePtr(bind_ptr->name.ids);SnmpUtilMemFreePtr(bind_list_ptr);SnmpUtilMemFreePtr(bind_ptr);- SnmpUtilMemFreePtr(mib_ii_name_ptr);DEBUG_LOG(("Got %d connections in list, parsing...\n", connectionVector.size()));diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/Thread/PeerThread.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/Thread/PeerThread.cppindex 9fb8244ec..117088023 100644--- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/Thread/PeerThread.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/Thread/PeerThread.cpp@@ -1211,6 +1211,17 @@ void PeerThreadClass::Thread_Function()peer = peerInitialize( &callbacks );DEBUG_ASSERTCRASH( peer != NULL, ("NULL peer!") );+ if (peer == NULL)+ {+ // The assert is gone in Release, where the NULL went on to fault in peerSetRoomWatchKeys().+ // startThread() reuses this object, so clear the flags for the next attempt.+ markAsDisconnected();+ PeerResponse resp;+ resp.peerResponseType = PeerResponse::PEERRESPONSE_DISCONNECT;+ resp.discon.reason = DISCONNECT_COULDNOTCONNECT;+ TheGameSpyPeerMessageQueue->addResponse(resp);+ return;+ }m_isConnected = m_isConnecting = false;qr2_register_key(EXECRC_KEY, EXECRC_STR);diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/LANAPI.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/LANAPI.cppindex 3e53b2420..4f38ec64d 100644--- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/LANAPI.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/LANAPI.cpp@@ -594,6 +594,9 @@ void LANAPI::update( void )// m_gameStartTime is when the next message goes out// m_gameStartSeconds is how many seconds remain in the message+ if (m_gameStartSeconds == 1)+ LANDisableButtons();+RequestGameStartTimer( m_gameStartSeconds );}else if (m_gameStartTime && m_gameStartTime <= now)@@ -724,6 +727,8 @@ void LANAPI::RequestGameAnnounce( void )reply.LANMessageType = LANMessage::MSG_GAME_ANNOUNCE;AsciiString gameOpts = GameInfoToAsciiString(m_currentGame);+ if (gameOpts.isEmpty())+ return;strlcpy(reply.GameInfo.options,gameOpts.str(),ARRAY_SIZE(reply.GameInfo.options));wcsncpy(reply.GameInfo.gameName, m_currentGame->getName().str(), g_lanGameNameLength);reply.GameInfo.gameName[g_lanGameNameLength] = 0;@@ -848,9 +853,9 @@ void LANAPI::RequestGameStartTimer( Int seconds )void LANAPI::RequestGameOptions( AsciiString gameOptions, Bool isPublic, UnsignedInt ip /* = 0 */ ){- DEBUG_ASSERTCRASH(gameOptions.getLength() < m_lanMaxOptionsLength, ("Game options string is too long!"));+ DEBUG_ASSERTCRASH(gameOptions.getLength() <= m_lanMaxOptionsLength, ("Game options string is too long!"));- if (!m_currentGame)+ if (!m_currentGame || gameOptions.isEmpty())return;LANMessage msg;diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/LANAPIhandlers.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/LANAPIhandlers.cppindex 3dd74d600..73f704ac2 100644--- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/LANAPIhandlers.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/LANAPIhandlers.cpp@@ -69,7 +69,9 @@ void LANAPI::handleRequestLocations( LANMessage *msg, UnsignedInt senderIP )reply.GameInfo.gameName[g_lanGameNameLength] = 0;reply.GameInfo.inProgress = m_currentGame->isGameInProgress();- sendMessage(&reply);+ // Empty when the room's options cannot fit the packet at all; announce nothing then.+ if (!gameOpts.isEmpty())+ sendMessage(&reply);}else{@@ -194,8 +196,10 @@ void LANAPI::handleRequestGameInfo( LANMessage *msg, UnsignedInt senderIP )LANMessage reply;fillInLANMessage( &reply );reply.LANMessageType = LANMessage::MSG_GAME_ANNOUNCE;-+AsciiString gameOpts = GameInfoToAsciiString(m_currentGame);+ if (gameOpts.isEmpty())+ return;strlcpy(reply.GameInfo.options,gameOpts.str(),ARRAY_SIZE(reply.GameInfo.options));wcsncpy(reply.GameInfo.gameName, m_currentGame->getName().str(), g_lanGameNameLength);reply.GameInfo.gameName[g_lanGameNameLength] = 0;diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/LANGameInfo.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/LANGameInfo.cppindex 0a4dfe6fd..781a1d1e7 100644--- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/LANGameInfo.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/LANGameInfo.cpp@@ -215,6 +215,10 @@ void LANDisplayGameList( GameWindow *gameListbox, LANGameInfo *gameList )selectedPtr = (LANGameInfo *)GadgetListBoxGetItemData(gameListbox, selectedIndex, 0);}+ // every game announced or closed rebuilds the list, and the reset threw the player's+ // scroll back to the top while he was reading down it+ const Int topVisible = GadgetListBoxGetTopVisibleEntry(gameListbox);+GadgetListBoxReset(gameListbox);while (gameList)@@ -243,6 +247,8 @@ void LANDisplayGameList( GameWindow *gameListbox, LANGameInfo *gameList )GadgetListBoxSetSelected(gameListbox, indexToSelect);elseHideGameInfoWindow(TRUE);++ GadgetListBoxSetTopVisibleEntry(gameListbox, topVisible);}}diff --git a/GeneralsMD/Code/GameEngineDevice/Include/MilesAudioDevice/MilesAudioManager.h b/GeneralsMD/Code/GameEngineDevice/Include/MilesAudioDevice/MilesAudioManager.hindex 1d0cf7513..7776f8f4e 100644--- a/GeneralsMD/Code/GameEngineDevice/Include/MilesAudioDevice/MilesAudioManager.h+++ b/GeneralsMD/Code/GameEngineDevice/Include/MilesAudioDevice/MilesAudioManager.h@@ -244,11 +244,8 @@ class MilesAudioManager : public AudioManagervirtual void closeAnySamplesUsingFile( const void *fileToClose );-- virtual Bool has3DSensitiveStreamsPlaying( void ) const;-- protected:+ protected:// 3-D functionsvirtual void setDeviceListenerPosition( void );const Coord3D *getCurrentPositionFromEvent( AudioEventRTS *event );diff --git a/GeneralsMD/Code/GameEngineDevice/Source/MilesAudioDevice/MilesAudioManager.cpp b/GeneralsMD/Code/GameEngineDevice/Source/MilesAudioDevice/MilesAudioManager.cppindex a6a89a289..459238c4c 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/MilesAudioDevice/MilesAudioManager.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/MilesAudioDevice/MilesAudioManager.cpp@@ -1971,7 +1971,7 @@ void MilesAudioManager::selectProvider( UnsignedInt providerNdx ){providerNdx = getProviderIndex( "Miles Fast 2D Positional Audio" );}- success = AIL_open_3D_provider( m_provider3D[providerNdx].id ) == 0;+ success = providerNdx < m_providerCount && AIL_open_3D_provider( m_provider3D[providerNdx].id ) == 0;//if (providerNdx < m_providerCount)//{@@ -1985,8 +1985,8 @@ void MilesAudioManager::selectProvider( UnsignedInt providerNdx )m_selectedProvider = PROVIDER_ERROR;// try to select a failsafeproviderNdx = getProviderIndex( "Miles Fast 2D Positional Audio" );- success = AIL_open_3D_provider( m_provider3D[providerNdx].id ) == 0;- }+ success = providerNdx < m_providerCount && AIL_open_3D_provider( m_provider3D[providerNdx].id ) == 0;+ }if ( success ){@@ -2629,44 +2629,6 @@ void MilesAudioManager::processPlayingList( void )}}-//Patch for a rare bug (only on about 5% of in-studio machines suffer, and not all the time) .-//The actual mechanics of this problem are still elusive as of the date of this comment. 8/21/03-//but the cause is clear. Some cinematics do a radical change in the microphone position, which-//calls for a radical 3DSoundVolume adjustment. If this happens while a stereo stream is *ENDING*,-//low-level code gets caught in a tight loop. (Hangs) on some machines.-//To prevent this condition, we just suppress the updating of 3DSoundVolume while one of these-//is on the list. Since the music tracks play continuously, they never *END* during these cinematics.-//so we filter them out as, *NOT SENSITIVE*... we do want to update 3DSoundVolume during music,-//which is almost all of the time.--Bool MilesAudioManager::has3DSensitiveStreamsPlaying( void ) const-{- if ( m_playingStreams.empty() )- return FALSE;-- for ( std::list< PlayingAudio* >::const_iterator it = m_playingStreams.begin(); it != m_playingStreams.end(); ++it )- {- const PlayingAudio *playing = (*it);-- if ( ! playing )- continue;-- if ( !audioIsType(playing->m_audioEventRTS, AT_Music) )- {- return TRUE;- }-- if ( playing->m_audioEventRTS->getEventName().startsWith("Game_") == FALSE )- {- return TRUE;- }- }-- return FALSE;--}--//-------------------------------------------------------------------------------------------------void MilesAudioManager::processFadingList( void ){diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DLaserDraw.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DLaserDraw.cppindex eae9b249e..1d6744276 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DLaserDraw.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DLaserDraw.cpp@@ -275,7 +275,12 @@ void W3DLaserDraw::doDrawModule(const Matrix3D* transformMtx)for( int segment = 0; segment < data->m_segments; segment++ ){- if( data->m_arcHeight > 0.0f && data->m_segments > 1 )+ // a laser drawn before LaserUpdate has placed it has both ends at the origin, and the arc+ // below divides by half its length: NaN points into the segmented line+ const Coord3D *start = update->getStartPos();+ const Coord3D *end = update->getEndPos();+ const Bool hasLength = start->x != end->x || start->y != end->y || start->z != end->z;+ if( data->m_arcHeight > 0.0f && data->m_segments > 1 && hasLength ){//CALCULATE A CURVED LINE BASED ON TOTAL LENGTH AND DESIRED HEIGHT INCREASE//To do this we will use a portion of the cos wave ranging between -0.25PIdiff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DModelDraw.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DModelDraw.cppindex 4138e24e4..229614e12 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DModelDraw.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DModelDraw.cpp@@ -2767,12 +2767,13 @@ void W3DModelDraw::handleClientTurretPositioning()*/void W3DModelDraw::handleClientRecoil(){- const W3DModelDrawModuleData* d = getW3DModelDrawModuleData();- if (!(m_curState->m_validStuff & ModelConditionInfo::BARRELS_VALID))+ if (!m_curState || !(m_curState->m_validStuff & ModelConditionInfo::BARRELS_VALID)){return;}+ const W3DModelDrawModuleData* d = getW3DModelDrawModuleData();+// do recoil, if anyfor (int wslot = 0; wslot < WEAPONSLOT_COUNT; ++wslot){diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DHorizontalSlider.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DHorizontalSlider.cppindex ad2eecffe..dd942d9cd 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DHorizontalSlider.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DHorizontalSlider.cpp@@ -356,8 +356,10 @@ void W3DGadgetHorizontalSliderImageDrawA( GameWindow *window,leftImageRight = leftImageLeft = GadgetSliderGetDisabledImageLeft( window );rightImageRight = rightImageLeft = GadgetSliderGetDisabledImageRight( window );-// centerImageRight = centerImageLeft = GadgetSliderGetDisabledImageCenter( window );-// smallCenterImageRight = smallCenterImageLeft = GadgetSliderGetDisabledImageSmallCenter( window );+ // these two were commented out, which left the centre images as whatever was on the stack for+ // every disabled slider: the sanity check below read them and the draw went through them+ centerImageRight = centerImageLeft = GadgetSliderGetDisabledImageCenter( window );+ smallCenterImageRight = smallCenterImageLeft = GadgetSliderGetDisabledImageSmallCenter( window );} // end if, disabledelse //if( BitTest( instData->getState(), WIN_STATE_HILITED ) )diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cppindex 31220353d..96afb17e4 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp@@ -2056,6 +2056,12 @@ void W3DDisplay::draw( void )extern HWND ApplicationHWnd;if (ApplicationHWnd && ::IsIconic(ApplicationHWnd)) {+ // A network game keeps its logic running while minimized (Win32GameEngine::update), and+ // the particle update below is the only thing that retires a particle system, so skipping+ // it with the draw stacked up every system the match made in the meantime, all of them to+ // start emitting at once on return (TheSuperHackers #2709 reproduce it with Propaganda+ // Towers). Same bookkeeping as the lost-device branch below.+ TheParticleSystemManager->update();return;}diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainVisual.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainVisual.cppindex f8d59de96..6388d90fd 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainVisual.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainVisual.cpp@@ -681,8 +681,8 @@ Bool W3DTerrainVisual::load( AsciiString filename )#ifdef DO_UNIT_TIMINGS#pragma MESSAGE("********************* WARNING- Doing UNIT TIMINGS. ")-#else- if (m_waterRenderObject)+#else+ if (m_waterRenderObject && W3DDisplay::m_3DScene){W3DDisplay::m_3DScene->Add_Render_Object( m_waterRenderObject);m_waterRenderObject->enableWaterGrid(false);diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/agg_def.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/agg_def.hindex cc03dac80..cb90113b8 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/agg_def.h+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/agg_def.h@@ -110,7 +110,7 @@ class AggregateDefClassvirtual WW3DErrorType Load_W3D (ChunkLoadClass &chunk_load);virtual WW3DErrorType Save_W3D (ChunkSaveClass &chunk_save);const char * Get_Name (void) const { return m_pName; }- void Set_Name (const char *pname) { SAFE_FREE (m_pName); m_pName = ::_strdup (pname); }+ void Set_Name (const char *pname) { char *name = ::_strdup (pname); SAFE_FREE (m_pName); m_pName = name; }RenderObjClass * Create (void);AggregateDefClass * Clone (void) const { return W3DNEW AggregateDefClass (*this); }diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8rendererdebugger.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8rendererdebugger.cppindex 5cb7d0e27..ec3bc52ed 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8rendererdebugger.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8rendererdebugger.cpp@@ -27,7 +27,7 @@ bool DX8RendererDebugger::Enabled;void DX8RendererDebugger::Enable(bool enable){- Enabled=true;+ Enabled=enable;}void DX8RendererDebugger::Get_String(StringClass& s)diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cppindex 0f2d4f334..aeed616da 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp@@ -3538,8 +3538,10 @@ IDirect3DSurface9 * DX8Wrapper::_Create_DX8_Surface(const char *filename_)// else create a surface with missing texture in itchar compressed_name[200];strncpy(compressed_name,filename_, 200);- char *ext = strstr(compressed_name, ".");- if ( (strlen(ext)==4) &&+ compressed_name[199] = 0;+ // the last dot: the first one turned "a.b.tga" into nothing, and a name without one was a strlen of NULL+ char *ext = strrchr(compressed_name, '.');+ if ( ext && (strlen(ext)==4) &&( (ext[1] == 't') || (ext[1] == 'T') ) &&( (ext[2] == 'g') || (ext[2] == 'G') ) &&( (ext[3] == 'a') || (ext[3] == 'A') ) ) {diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/meshmatdesc.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/meshmatdesc.cppindex efb0551d6..f708ef4fd 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/meshmatdesc.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/meshmatdesc.cpp@@ -682,66 +682,37 @@ void MeshMatDescClass::Post_Load_Process(bool lighting_enabled,MeshModelClass *if (!ColorArray[0] && !ColorArray[1]) continue; // If no color arrays, we don't have a problem- Vector3 single_diffuse(0.0f,0.0f,0.0f);- Vector3 single_ambient(0.0f,0.0f,0.0f);- Vector3 single_emissive(0.0f,0.0f,0.0f);- float single_opacity=1.0f;- bool single_diffuse_used=true;- bool single_ambient_used=true;- bool single_emissive_used=true;- bool single_opacity_used=true;bool diffuse_used=false;bool ambient_used=false;bool emissive_used=false;- bool opacity_used=false;-- Vector3 mtl_diffuse;- Vector3 mtl_ambient;- Vector3 mtl_emissive;- float mtl_opacity = 1.0f;+ // Which channels any material of this pass uses. The single_* bookkeeping that was here was+ // never read; what it left behind was mtl_ambient and mtl_emissive holding the LAST material's+ // colours, which the colouring loop below then applied to every vertex. A vertex with no+ // material is skipped rather than dereferenced.VertexMaterialClass * prev_mtl = NULL;- VertexMaterialClass * mtl = Peek_Material(0, pass);- if (mtl) {- mtl->Get_Diffuse(&single_diffuse);- single_opacity = mtl->Get_Opacity();- mtl->Get_Ambient(&single_ambient);- mtl->Get_Emissive(&single_emissive);-- if (single_diffuse.X || single_diffuse.Y || single_diffuse.Z) diffuse_used=true;- if (single_ambient.X || single_ambient.Y || single_ambient.Z) ambient_used=true;- if (single_emissive.X || single_emissive.Y || single_emissive.Z) emissive_used=true;- if (single_opacity!=1.0f) opacity_used=true;- }-for (int vidx=0; vidx<VertexCount; vidx++) {- mtl = Peek_Material(vidx,pass);+ VertexMaterialClass * mtl = Peek_Material(vidx,pass);+ if (mtl == NULL) {+ continue;+ }if (mtl != prev_mtl) {prev_mtl = mtl;+ Vector3 mtl_diffuse;+ Vector3 mtl_ambient;+ Vector3 mtl_emissive;mtl->Get_Diffuse(&mtl_diffuse);- mtl_opacity = mtl->Get_Opacity();mtl->Get_Ambient(&mtl_ambient);mtl->Get_Emissive(&mtl_emissive);- }-- if (mtl_diffuse.X!=single_diffuse.X || mtl_diffuse.Y!=single_diffuse.Y || mtl_diffuse.Z!=single_diffuse.Z) {- single_diffuse_used=false;- }- if (mtl_ambient.X!=single_ambient.X || mtl_ambient.Y!=single_ambient.Y || mtl_ambient.Z!=single_ambient.Z) {- single_ambient_used=false;- }- if (mtl_emissive.X!=single_emissive.X || mtl_emissive.Y!=single_emissive.Y || mtl_emissive.Z!=single_emissive.Z) {- single_emissive_used=false;- }- if (mtl_opacity!=single_opacity) {- single_opacity_used=false;- }- if (mtl_diffuse.X || mtl_diffuse.Y || mtl_diffuse.Z) diffuse_used=true;- if (mtl_ambient.X || mtl_ambient.Y || mtl_ambient.Z) ambient_used=true;- if (mtl_emissive.X || mtl_emissive.Y || mtl_emissive.Z) emissive_used=true;- if (mtl_opacity!=1.0f) opacity_used=true;+ diffuse_used = diffuse_used || mtl_diffuse.X || mtl_diffuse.Y || mtl_diffuse.Z;+ ambient_used = ambient_used || mtl_ambient.X || mtl_ambient.Y || mtl_ambient.Z;+ emissive_used = emissive_used || mtl_emissive.X || mtl_emissive.Y || mtl_emissive.Z;+ if (diffuse_used && ambient_used && emissive_used) {+ break;+ }+ }}// If both DCG and DIG arrays are submitted, multiply them together to DCG channel@@ -764,6 +735,8 @@ void MeshMatDescClass::Post_Load_Process(bool lighting_enabled,MeshModelClass *if ((DCGSource[pass] != VertexMaterialClass::MATERIAL) && (ColorArray[0] != NULL)) {unsigned * diffuse_array = ColorArray[0]->Get_Array();Vector3 mtl_diffuse;+ Vector3 mtl_ambient;+ Vector3 mtl_emissive;float mtl_opacity = 1.0f;VertexMaterialClass * prev_mtl = NULL;@@ -772,9 +745,14 @@ void MeshMatDescClass::Post_Load_Process(bool lighting_enabled,MeshModelClass *for (int vidx=0; vidx<VertexCount; vidx++) {mtl = Peek_Material(vidx,pass);+ if (mtl == NULL) {+ continue;+ }if (mtl != prev_mtl) {prev_mtl = mtl;mtl->Get_Diffuse(&mtl_diffuse);+ mtl->Get_Ambient(&mtl_ambient);+ mtl->Get_Emissive(&mtl_emissive);mtl_opacity = mtl->Get_Opacity();}@@ -884,54 +862,47 @@ void MeshMatDescClass::Post_Load_Process(bool lighting_enabled,MeshModelClass *}// Set lighting to false if requested in all passes...else if (set_lighting_to_false) {- Vector3 single_diffuse(0.0f,0.0f,0.0f);- Vector3 single_ambient(0.0f,0.0f,0.0f);- Vector3 single_emissive(0.0f,0.0f,0.0f);bool diffuse_used=false;bool ambient_used=false;bool emissive_used=false;- Vector3 mtl_diffuse;- Vector3 mtl_ambient;- Vector3 mtl_emissive;-VertexMaterialClass * prev_mtl = NULL;- VertexMaterialClass * mtl = Peek_Material(0, pass);- if (mtl) {- mtl->Get_Diffuse(&single_diffuse);- mtl->Get_Ambient(&single_ambient);- mtl->Get_Emissive(&single_emissive);-- if (single_diffuse.X || single_diffuse.Y || single_diffuse.Z) diffuse_used=true;- if (single_ambient.X || single_ambient.Y || single_ambient.Z) ambient_used=true;- if (single_emissive.X || single_emissive.Y || single_emissive.Z) emissive_used=true;- }-for (int vidx=0; vidx<VertexCount; vidx++) {- mtl = Peek_Material(vidx,pass);+ VertexMaterialClass * mtl = Peek_Material(vidx,pass);+ if (mtl == NULL) {+ continue;+ }if (mtl != prev_mtl) {prev_mtl = mtl;+ Vector3 mtl_diffuse;+ Vector3 mtl_ambient;+ Vector3 mtl_emissive;mtl->Get_Diffuse(&mtl_diffuse);mtl->Get_Ambient(&mtl_ambient);mtl->Get_Emissive(&mtl_emissive);- }- if (mtl_diffuse.X || mtl_diffuse.Y || mtl_diffuse.Z) diffuse_used=true;- if (mtl_ambient.X || mtl_ambient.Y || mtl_ambient.Z) ambient_used=true;- if (mtl_emissive.X || mtl_emissive.Y || mtl_emissive.Z) emissive_used=true;+ diffuse_used = diffuse_used || mtl_diffuse.X || mtl_diffuse.Y || mtl_diffuse.Z;+ ambient_used = ambient_used || mtl_ambient.X || mtl_ambient.Y || mtl_ambient.Z;+ emissive_used = emissive_used || mtl_emissive.X || mtl_emissive.Y || mtl_emissive.Z;++ if (diffuse_used && ambient_used && emissive_used) {+ break;+ }+ }}- if ((DCGSource[pass] != VertexMaterialClass::MATERIAL) && (ColorArray[0] != NULL)) {+ // Turn off lighting only for emissive-only materials using vertex colors.+ if (!diffuse_used && !ambient_used && emissive_used &&+ (DCGSource[pass] != VertexMaterialClass::MATERIAL) && (ColorArray[0] != NULL)) {VertexMaterialClass * prev_mtl = NULL;- VertexMaterialClass * mtl = Peek_Material(0,pass);for (int vidx=0; vidx<VertexCount; vidx++) {- mtl = Peek_Material(vidx,pass);+ VertexMaterialClass * mtl = Peek_Material(vidx,pass);+ if (mtl == NULL) {+ continue;+ }if (mtl != prev_mtl) {prev_mtl = mtl;- // If only emissive is used apply emissive to color channel, set diffuse source to color 1, and turn off lighting- if (!diffuse_used && !ambient_used && emissive_used) {- mtl->Set_Lighting(false);- }+ mtl->Set_Lighting(false);}}}diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/part_emt.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/part_emt.cppindex a6e119327..421ade5a1 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/part_emt.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/part_emt.cpp@@ -849,14 +849,10 @@ ParticleEmitterClass::Save (ChunkSaveClass &chunk_save) constvoidParticleEmitterClass::Set_Name (const char *pname){- // Free the old name if necessary- if (NameString != NULL) {- ::free (NameString);- NameString = NULL;- }-- // Copy the provided name- NameString = ::_strdup (pname);+ // Copy before freeing the old name: pname may point into it.+ char *name = ::_strdup (pname);+ ::free (NameString);+ NameString = name;return ;}diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/part_ldr.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/part_ldr.cppindex c58b2e5ae..e727fcdb0 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/part_ldr.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/part_ldr.cpp@@ -287,8 +287,10 @@ ParticleEmitterDefClass::Set_Creation_Volume (Vector3Randomizer *randomizer)voidParticleEmitterDefClass::Set_User_String (const char *pstring){- SAFE_FREE (m_pUserString);- m_pUserString = ::_strdup (pstring);+ // Copy first: pstring may be our own string (self-assignment).+ char *copy = ::_strdup (pstring);+ SAFE_FREE (m_pUserString);+ m_pUserString = copy;return ;}@@ -300,8 +302,9 @@ ParticleEmitterDefClass::Set_User_String (const char *pstring)voidParticleEmitterDefClass::Set_Name (const char *pname){- SAFE_FREE (m_pName);- m_pName = ::_strdup (pname);+ char *copy = ::_strdup (pname);+ SAFE_FREE (m_pName);+ m_pName = copy;return ;}diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/pointgr.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/pointgr.cppindex ce3b5c054..ff8760196 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/pointgr.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/pointgr.cpp@@ -1873,7 +1873,9 @@ void PointGroupClass::RenderVolumeParticle(RenderInfoClass &rinfo, unsigned int// 3 times per particle when we can do it oncefloat recipDepth = 0.1f / (float)depth;- float shiftInc = ( t * *current_size * recipDepth );+ // No size array means every point is DefaultPointSize, as Update_Arrays assumes.+ const float pointSize = current_size ? *current_size : DefaultPointSize;+ float shiftInc = ( t * pointSize * recipDepth );Vector3 volumeLayerShift;Vector3 cameraPosition = rinfo.Camera.Get_Position();diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/hash.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/hash.cppindex 0a6379f01..ea15be966 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/hash.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/hash.cpp@@ -138,7 +138,7 @@ int HashTableClass::Hash( const char * key )void HashTableIteratorClass::First(void){Index = 0;- NextEntry = Table.HashTable[ Index ];+ NextEntry = NULL;Advance_Next();Next(); // Accept the next we found, and go to the next next}@@ -155,11 +155,11 @@ void HashTableIteratorClass::Next(void)void HashTableIteratorClass::Advance_Next(void){while ( NextEntry == NULL ) {- Index++;if ( Index >= Table.HashTableSize ) {return; // Done!}NextEntry = Table.HashTable[ Index ];+ ++Index;}}diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/hash.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/hash.hindex 54b67af64..b27c3fca7 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/hash.h+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/hash.h@@ -99,7 +99,7 @@ private:class HashTableIteratorClass{public:- HashTableIteratorClass( HashTableClass & table ) : Table( table ) {}+ HashTableIteratorClass( HashTableClass & table ) : Table( table ) { First(); }virtual ~HashTableIteratorClass( void ) {}void First( void );diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/parameter.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/parameter.hindex d45ca3256..691787373 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/parameter.h+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/parameter.h@@ -220,14 +220,10 @@ ParameterClass::Get_Name (void) constinline voidParameterClass::Set_Name (const char *new_name){- if (m_Name != NULL) {- ::free ((void *)m_Name);- m_Name = NULL;- }-- if (new_name != NULL) {- m_Name = ::strdup (new_name);- }+ // Copy before freeing the old name: new_name may point into it.+ char *name = (new_name != NULL) ? ::strdup (new_name) : NULL;+ ::free ((void *)m_Name);+ m_Name = name;return ;}diff --git a/GeneralsMD/Code/Stubs/NullAudioManager.h b/GeneralsMD/Code/Stubs/NullAudioManager.hindex 942343cd6..3c78290f9 100644--- a/GeneralsMD/Code/Stubs/NullAudioManager.h+++ b/GeneralsMD/Code/Stubs/NullAudioManager.h@@ -83,8 +83,6 @@ public:virtual void removePlayingAudio( AsciiString ) {}virtual void removeAllDisabledAudio() {}- virtual Bool has3DSensitiveStreamsPlaying( void ) const { return FALSE; }-/* Bink is stubbed out too, so nobody asks for this handle. */virtual void *getHandleForBink( void ) { return NULL; }virtual void releaseHandleForBink( void ) {}