Zero Hour rebuilt from EA's source: x64, Direct3D 11, VS2022/CMake, ~60 original bugs fixed, an AI that builds a base. Bring your own game.
C++ cmakecnccommand-and-conquercppdirectx11game-enginegame-preservationgeneralsrtssage-enginex64zero-hour
feat(gameengine): port the last two upstream batches, closing FINDINGS 6
Olcay Seygan6dad58f765ec
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 564292e58..1e9c2fca7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -117,6 +117,123 @@ W vehicles, E aircraft — but Q was grabbing every armed thing you own, tanks athere was no way to pull just the foot soldiers out of a mixed army. Press it twice for the wholemap. Ctrl+A is still everything at once.+## Aircraft, guards, and orders that used to be ignored++- **A pair of jets on a two-runway airfield could stop taking off.** Each one waited for the other+ to finish taxiing, and neither ever decided that the wait was over: whoever taxied next restarted+ the countdown, so two Raptors sat on a working airfield doing nothing while the battle went on+ without them. They now wait for exactly one aircraft, once, and go.+- **Losing the airfield used to leave its aircraft in limbo.** With the runway gone the game told+ the plane it had permission to use it, so it went on flying a landing pattern for a building that+ was rubble, and one destroyed mid-rearm left the aircraft parked on nothing. They now do what they+ should when their base dies.+- **Repaired aircraft come back to you.** A Comanche or a Chinook that finished patching itself up+ used to lift off and hover over the pad. If the airfield has a rally point, it flies there.+ Infantry walking out of a captured building follow the building's rally point too, instead of+ standing in the doorway.+- **A Chinook told to fly somewhere and unload no longer empties itself in a single frame.** Eight+ passengers used to appear on top of each other. They get out one at a time now, unless you+ actually ordered an evacuation.+- **A guarding unit under fire stopped fighting itself.** Guard mode had a unit break off its move+ to shoot back, then break off shooting to resume the move, over and over, so it did neither well.+ The order to return to its post and the order to defend itself no longer fight.+- **Clearing mines works on mines you cannot see.** Mines and booby traps are invisible by nature,+ and the game refuses to let a unit walk up to something invisible. So an engineer ordered to clear+ a minefield simply stood still. Ordering a disarm now overrides that rule — and only that.+- **A helicopter no longer boards a transport from the air.** The check for "am I close enough to+ get in" only asked whether the transport was off the ground, not whether the two were anywhere+ near each other.++## The same game on both screens, and the same game after loading++- **A unit with nowhere to stand no longer appears somewhere else entirely.** When the game spawns+ something — a crew bailing out, a garrison emptying, anything placed *near* a spot rather than on+ it — and every nearby space is taken, it used to drop the new unit at a leftover position from+ whatever ran before it: a random point on the map, or off it. It now appears where it was asked+ for, crowded or not.+- **Loading a save remembers what your guards were guarding.** The guard order was written to the+ file one slot too far and overwrote the position it was guarding, so units restored from a save+ could come back watching the wrong place.+- **Two machines playing the same match drift apart less.** Defeating a player, playing a second+ map without restarting, and the fingerprint the game uses to notice that two players have stopped+ agreeing — all three had bugs that made one side quietly diverge from the other, and the+ fingerprint itself was checking the same number 128 times instead of the wall it was supposed to+ be checking. Fixed. This is groundwork: network play is still not something this build claims.++## Sharper textures, for free++Zero Hour shipped downscaled copies of a lot of the base game's textures, and because of the order+the game loads its archives in, those small copies were the ones you saw — the full-size originals+were sitting right there in the base game's files, unused. Where both exist, the bigger one wins now.+On a standard install that is 481 textures, each of them four times the resolution you were getting:+buildings, walls, vehicles.++## Every replay, not just the last one++The game overwrites the same replay file after every match, so the only way to keep a game was to go+and rename the file before starting the next one. Turn on replay archiving and each game is also+saved under its own date-and-time name, in its own folder, automatically.++## Placing a building, then changing your mind++Right-clicking to cancel a building you were about to place used to also deselect the builder, so+putting down something else meant finding and clicking the dozer again. The cancel now cancels the+placement and nothing else.++## Bonuses that come and go when they should++A squad of infantry standing over its own dead used to keep the horde bonus the dead were paying+for. Nationalism and fanaticism were worse: once a unit had been in a horde with those upgrades+bought, it kept the damage bonus for the rest of its life, alone in a corner of the map, and+fanaticism refused to work at all unless nationalism had been bought first. All three bonuses now+come and go with the horde. (If you make maps or mods and want the old rule, a horde module can ask+for it by name — nothing that ships with the game changes.)++The strategy center had the same disease from the other end. Running two battle plans told each of+your units it was under the newest one only, undoing a plan scrambled the center's own record of+what it had handed out, and capturing an enemy strategy center gave you nothing while its old owner+kept the bonus. Plans now move with the building.++## One crate, one collector++Walk a five-man squad over a salvage crate and you used to get paid five times, because the crate is+only cleared away at the end of the frame and everybody who touched it in that frame counted. Same+frame, same crate, one payout now.++A vehicle thrown onto a crowd had the mirror-image bug: the crash damage was an area weapon, fired+once for every unit in the pile, so a group of five each took five hits. It hits what it lands on,+once.++A unit already on its way down could still be promoted by its last kill — new upgrades, new weapon+bonuses, the promotion sound and the flash, on a corpse. And getting healed used to count as taking+damage, which meant a stealth unit was dragged into view by its own medic.++## Circles are round, and a tunnel is one tunnel++Range checks against a circular area were really checks against the square around it, so the corners+counted as inside. The bigger the radius, the more territory a unit was "in range" of without being+anywhere near it. Now measured properly.++Infantry hiding in a tunnel network healed once per tunnel per frame: five tunnels, five times the+healing rate the data asks for. The network heals at its own rate now, however many entrances it+has.++## The power bar tells the truth++A knocked-out power plant is supposed to count for nothing until it comes back. The original game+kept two separate sets of books on that, and they disagreed with each other in four different ways.++- **An EMP on a plant you had already upgraded took the upgrade off your grid twice** — once when+ the plant went down, again when the plant was sold, captured or lost its upgrade while still+ down. The bar showed a blackout your base was not actually in, and everything on it shut off.+- **An EMP on a half-built plant moved power that did not exist yet.** A building site has never+ produced anything; disabling and re-enabling one used to add and subtract its full output anyway.+- **Loading a saved game brought disabled plants back as working ones**, so the power you loaded+ into was not the power you saved.+- **A Control Rods upgrade that finished while the plant was down was credited immediately and then+ credited again when the plant came back up** — free power, permanently, for anyone whose plant got+ hit at the right moment.+## Your whole base, on one stripThe original showed you one factory at a time and made you click through the rest.diff --git a/GeneralsMD/Code/GameEngine/Include/Common/ArchiveFileSystem.h b/GeneralsMD/Code/GameEngine/Include/Common/ArchiveFileSystem.hindex 5d36cdfeb..703bac48a 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/ArchiveFileSystem.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/ArchiveFileSystem.h@@ -176,6 +176,7 @@ class ArchiveFileSystem : public SubsystemInterfaceprotected:virtual void loadIntoDirectoryTree(const ArchiveFile *archiveFile, const AsciiString& archiveFilename, Bool overwrite = FALSE ); ///< load the archive file's header information and apply it to the global archive directory tree.+ void prioritizeLargerFiles(const AsciiString& directory, const char *inferiorArchive, const char *superiorArchive); ///< where two archives claim the same file in this directory, keep the bigger copy.ArchiveFileMap m_archiveFileMap;ArchivedDirectoryInfo m_rootDirectory;diff --git a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.hindex 937b1b0c9..7e4033003 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h@@ -340,6 +340,7 @@ public:Bool m_showPlacementRangeRing; ///< while placing a structure, ring its weapon rangeBool m_workersReturnToSupply; ///< a worker that finishes a build job goes back to the dock it leftBool m_detailedBuildTooltips; ///< put build time, weapon range and damage in the build tooltip+ Bool m_archiveReplays; ///< keep a timestamped copy of every replay, instead of only the last oneInt m_bloomIntensity; ///< bloom strength in percent, 0 = offInt m_bloomThreshold; ///< brightness in percent below which nothing bloomsBool m_buildMapCache;diff --git a/GeneralsMD/Code/GameEngine/Include/Common/Player.h b/GeneralsMD/Code/GameEngine/Include/Common/Player.hindex 188614372..bdf4a53f4 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/Player.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/Player.h@@ -309,8 +309,8 @@ public:/// return t iff the player has all sciences that are prereqs for knowing the given scienceBool hasPrereqsForScience(ScienceType t) const;- Bool hasUpgradeComplete( const UpgradeTemplate *upgradeTemplate ); ///< does player have totally done and produced upgrade- Bool hasUpgradeComplete( UpgradeMaskType testMask ); ///< does player have totally done and produced upgrade+ Bool hasUpgradeComplete( const UpgradeTemplate *upgradeTemplate ) const; ///< does player have totally done and produced upgrade+ Bool hasUpgradeComplete( UpgradeMaskType testMask ) const; ///< does player have totally done and produced upgradeUpgradeMaskType getCompletedUpgradeMask() const { return m_upgradesCompleted; } ///< get list of upgrades that are completedBool hasUpgradeInProduction( const UpgradeTemplate *upgradeTemplate ); ///< does player have this upgrade in progress right nowUpgrade *addUpgrade( const UpgradeTemplate *upgradeTemplate,@@ -365,7 +365,7 @@ public://it's possible for multiple strategy centers to have the same plan, so we need//to keep track of that like radar. Keep in mind multiple strategy centers with//same plan do not stack, but different strategy centers with different plans do.- void changeBattlePlan( BattlePlanStatus plan, Int delta, BattlePlanBonuses *bonus );+ void changeBattlePlan( BattlePlanStatus plan, Int delta, const BattlePlanBonuses *bonus );Int getNumBattlePlansActive() const { return m_bombardBattlePlans + m_holdTheLineBattlePlans + m_searchAndDestroyBattlePlans; }Int getBattlePlansActiveSpecific( BattlePlanStatus plan ) const;void applyBattlePlanBonusesForObject( Object *obj ) const; //New object or converted object gaining our current battle plan bonuses.diff --git a/GeneralsMD/Code/GameEngine/Include/Common/Recorder.h b/GeneralsMD/Code/GameEngine/Include/Common/Recorder.hindex b232b1aab..e3c7cdee6 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/Recorder.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/Recorder.h@@ -109,6 +109,7 @@ public:void initControls(); ///< Show or Hide the Replay controlsAsciiString getReplayDir(); ///< Returns the directory that holds the replay files.+ static AsciiString getReplayArchiveDir(); ///< Returns the directory that holds the archived replay files.AsciiString getReplayExtention(); ///< Returns the file extention for replay files.AsciiString getLastReplayFileName(); ///< Returns the filename used for the default replay.@@ -126,6 +127,7 @@ public:protected:void startRecording(GameDifficulty diff, Int originalGameMode, Int rankPoints, Int maxFPS); ///< Start recording to m_file.void writeToFile(GameMessage *msg); ///< Write this GameMessage to m_file.+ void archiveReplay(const AsciiString& fileName); ///< Copy the given replay to the archive directory under a timestamped name.void logGameStart(AsciiString options);void logGameEnd( void );diff --git a/GeneralsMD/Code/GameEngine/Include/Common/SparseMatchFinder.h b/GeneralsMD/Code/GameEngine/Include/Common/SparseMatchFinder.hindex 0af234aee..fd68b2a28 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/SparseMatchFinder.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/SparseMatchFinder.h@@ -188,6 +188,23 @@ private://-------------------------------------------------------------------------------------------------public:+ //-------------------------------------------------------------------------------------------------+ /**+ m_bestMatches holds pointers *into the vector that was handed to findBestInfo*, so a copy of+ this finder would point at the original owner's vector - which is exactly what happened to a+ ThingTemplate override: the copy answered with weapon and armor sets belonging to another+ template, and freeing the original left the copy pointing at dead memory. The map is only a+ cache, so a copy simply starts empty and refills itself.+ */+ SparseMatchFinder() { }+ SparseMatchFinder(const SparseMatchFinder& other) { }+ SparseMatchFinder& operator=(const SparseMatchFinder& other)+ {+ if (this != &other)+ m_bestMatches.clear();+ return *this;+ }+//-------------------------------------------------------------------------------------------------void clear(){diff --git a/GeneralsMD/Code/GameEngine/Include/Common/TunnelTracker.h b/GeneralsMD/Code/GameEngine/Include/Common/TunnelTracker.hindex f16b790e5..a9728a6dd 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/TunnelTracker.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/TunnelTracker.h@@ -62,7 +62,7 @@ public:static void destroyObject( Object *obj, void *userData ); ///< Callback for Iterate Contained systemstatic void healObject( Object *obj, void *frames ); ///< Callback for Iterate Contained system- void healObjects(Real frames); ///< heal all objects within the tunnel+ void healObjects(); ///< heal all objects within the tunnel network, once per frameUnsignedInt friend_getTunnelCount() const {return m_tunnelCount;}///< TunnelContains are allowed to ask if they are the last one ahead of deletion time@@ -78,7 +78,9 @@ protected:virtual void loadPostProcess( void );private:-++ Real getFramesForFullHeal() const; ///< the fastest tunnel in the network sets the pace+std::list< ObjectID > m_tunnelIDs; ///< I have to try to keep track of these because Caves need to iterate on them.ContainedItemsList m_containList; ///< the contained object pointers liststd::list< ObjectID > m_xferContainList;///< for loading of m_containList during post processingdiff --git a/GeneralsMD/Code/GameEngine/Include/Common/UserPreferences.h b/GeneralsMD/Code/GameEngine/Include/Common/UserPreferences.hindex f7fdff7bc..01f4b6ea1 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/UserPreferences.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/UserPreferences.h@@ -119,6 +119,7 @@ public:Bool getShowPlacementRangeRing(void);Bool getWorkersReturnToSupply(void);Bool getDetailedBuildTooltips(void);+ Bool getArchiveReplays(void);Int getBloomIntensity(void);Int getBloomThreshold(void);Int getTextureReduction(void);diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.hindex 703a30031..5403115f4 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h@@ -60,6 +60,7 @@ class AssaultTransportAIInterface;class JetAIUpdate;enum AIStateType;+enum HordeActionType;enum ObjectID;@@ -564,7 +565,11 @@ public:void setAttitude( AttitudeType tude ); ///< set the behavior modifier for this agent// Common AI "status" effects -------------------------------------------------------------------- void evaluateMoraleBonus( void );+ Bool hasNationalism() const;+ Bool hasFanaticism() const;+ void evaluateMoraleBonus( Bool inHorde, Bool allowNationalism, HordeActionType type );+ void evaluateNationalismBonusClassic( Bool inHorde, Bool allowNationalism );+ void evaluateNationalismBonus( Bool inHorde, Bool allowNationalism );#ifdef ALLOW_DEMORALIZE// demoralization ... what a nifty word to write.diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/BattlePlanUpdate.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/BattlePlanUpdate.hindex 4eb28dbcf..46b978402 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/BattlePlanUpdate.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/BattlePlanUpdate.h@@ -152,6 +152,7 @@ public:virtual void onObjectCreated();virtual void onDelete();+ virtual void onCapture( Player *oldOwner, Player *newOwner );virtual UpdateSleepTime update();virtual CommandOption getCommandOption() const;diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/BehaviorModule.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/BehaviorModule.hindex e16a021bc..926544ad5 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/BehaviorModule.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/BehaviorModule.h@@ -213,6 +213,11 @@ enum RunwayReservationTypeRESERVATION_LANDING,};+enum+{+ InvalidRunway = -1,+};+//-------------------------------------------------------------------------------------------------class ParkingPlaceBehaviorInterface{@@ -241,6 +246,7 @@ public:virtual Bool reserveRunway(ObjectID id, Bool forLanding) = 0;virtual void calcPPInfo( ObjectID id, PPInfo *info ) = 0;virtual void releaseRunway(ObjectID id) = 0;+ virtual Int getRunwayIndex(ObjectID id) = 0;virtual Int getRunwayCount() const = 0;virtual ObjectID getRunwayReservation( Int r, RunwayReservationType type = RESERVATION_TAKEOFF ) = 0;virtual void transferRunwayReservationToNextInLineForTakeoff(ObjectID id) = 0;diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/FlightDeckBehavior.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/FlightDeckBehavior.hindex 5386d0363..2eda5339b 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/FlightDeckBehavior.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/FlightDeckBehavior.h@@ -139,6 +139,7 @@ public:virtual Bool reserveRunway(ObjectID id, Bool forLanding);virtual void releaseRunway(ObjectID id);virtual void calcPPInfo( ObjectID id, PPInfo *info );+ virtual Int getRunwayIndex(ObjectID id);virtual Int getRunwayCount() const { return m_runways.size(); }virtual ObjectID getRunwayReservation( Int r, RunwayReservationType type );virtual void transferRunwayReservationToNextInLineForTakeoff(ObjectID id);diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/HordeUpdate.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/HordeUpdate.hindex 7562269c2..d33b8f793 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/HordeUpdate.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/HordeUpdate.h@@ -44,17 +44,24 @@ class UpgradeTemplate;//-------------------------------------------------------------------------------------------------//-------------------------------------------------------------------------------------------------+// the horde action picks which of the two bonus rules a horde module follows. every horde module+// the game ships names HORDE explicitly, so the default only affects new content.enum HordeActionType{- HORDEACTION_HORDE = 0,+ HORDEACTION_HORDE = 0, ///< classic: nationalism and fanaticism are never taken away again once granted+ HORDEACTION_HORDE_FIXED, ///< horde, nationalism and fanaticism all follow the horde status- HORDEACTION_COUNT+ HORDEACTION_COUNT,++ HORDEACTION_DEFAULT = HORDEACTION_HORDE_FIXED};#ifdef DEFINE_HORDEACTION_NAMESstatic const char *TheHordeActionTypeNames[] ={"HORDE",+ "HORDE_FIXED",+NULL};#endif@@ -89,6 +96,7 @@ public:virtual Bool hasFlag() const = 0;virtual Bool isTrueHordeMember() const = 0;virtual Bool isAllowedNationalism() const = 0;+ virtual HordeActionType getHordeActionType() const = 0;};@@ -110,6 +118,7 @@ public:virtual Bool isTrueHordeMember() const { return m_trueHordeMember && m_inHorde; }virtual Bool isAllowedNationalism() const;virtual Bool hasFlag() const { return m_hasFlag; }+ virtual HordeActionType getHordeActionType() const { return getHordeUpdateModuleData()->m_action; }virtual UpdateSleepTime update(); ///< update this object's AIprotected:diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/ParkingPlaceBehavior.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/ParkingPlaceBehavior.hindex 8def59d5e..48db84096 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/ParkingPlaceBehavior.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/ParkingPlaceBehavior.h@@ -142,6 +142,7 @@ public:virtual Bool reserveRunway(ObjectID id, Bool forLanding);virtual void releaseRunway(ObjectID id);virtual void calcPPInfo( ObjectID id, PPInfo *info );+ virtual Int getRunwayIndex(ObjectID id);virtual Int getRunwayCount() const { return m_runways.size(); }virtual ObjectID getRunwayReservation( Int r, RunwayReservationType type );virtual void transferRunwayReservationToNextInLineForTakeoff(ObjectID id);diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/TunnelContain.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/TunnelContain.hindex 81753edcf..0d97896b5 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/TunnelContain.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/TunnelContain.h@@ -95,6 +95,7 @@ public:virtual Bool isBustable() const { return TRUE; } ///< can this container get busted by a bunkerbustervirtual Bool isHealContain() const { return false; } ///< true when container only contains units while healing (not a transport!)virtual Bool isTunnelContain() const { return TRUE; }+ Real getFullTimeForHeal() const { return getTunnelContainModuleData()->m_framesForFullHeal; } ///< frames until a contained object is fully healedvirtual Bool isImmuneToClearBuildingAttacks() const { return true; }virtual Bool isSpecialOverlordStyleContainer() const {return FALSE;}diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/PartitionManager.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/PartitionManager.hindex d571e3846..f865d4d54 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/PartitionManager.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/PartitionManager.h@@ -462,6 +462,12 @@ private:fill in the pixels covered by the given circular shape with the givencenter and radius. Note that this is used for both spheres and cylinders.*/+ /**+ The same fill, asking whether the circle actually reaches each cell rather than drawing a+ midpoint-circle outline and filling between its spans.+ */+ void doCircleFillPrecise(Real centerX, Real centerY, Real radius);+void doCircleFill(Real centerX,Real centerY,diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GameLOD.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GameLOD.cppindex dd739156f..4c4130e43 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/GameLOD.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/GameLOD.cpp@@ -375,6 +375,7 @@ void GameLODManager::init(void)TheWritableGlobalData->m_showPlacementRangeRing = optionPref.getShowPlacementRangeRing();TheWritableGlobalData->m_workersReturnToSupply = optionPref.getWorkersReturnToSupply();TheWritableGlobalData->m_detailedBuildTooltips = optionPref.getDetailedBuildTooltips();+ TheWritableGlobalData->m_archiveReplays = optionPref.getArchiveReplays();// Bloom is a look, not a detail level - it is honored at every preset, like the zoom ceiling.TheWritableGlobalData->m_bloomIntensity = optionPref.getBloomIntensity();diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cppindex 045fc32ef..82d0f7c91 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp@@ -196,6 +196,7 @@ GlobalData* GlobalData::m_theOriginal = NULL;{ "ShowPlacementRangeRing", INI::parseBool, NULL, offsetof( GlobalData, m_showPlacementRangeRing ) },{ "WorkersReturnToSupply", INI::parseBool, NULL, offsetof( GlobalData, m_workersReturnToSupply ) },{ "DetailedBuildTooltips", INI::parseBool, NULL, offsetof( GlobalData, m_detailedBuildTooltips ) },+ { "ArchiveReplays", INI::parseBool, NULL, offsetof( GlobalData, m_archiveReplays ) },{ "Bloom", INI::parseInt, NULL, offsetof( GlobalData, m_bloomIntensity ) },{ "BloomThreshold", INI::parseInt, NULL, offsetof( GlobalData, m_bloomThreshold ) },{ "MinCameraHeight", INI::parseReal, NULL, offsetof( GlobalData, m_minCameraHeight ) },@@ -1023,6 +1024,7 @@ GlobalData::GlobalData()m_showPlacementRangeRing = TRUE;m_workersReturnToSupply = TRUE;m_detailedBuildTooltips = TRUE;+ m_archiveReplays = FALSE;// Bloom is the one that does NOT default on: it changes how the game looks rather than what it// can do, and the artwork was painted in 2003 for a screen with no glow at all. "Bloom = 60"diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cppindex cf75bd433..54df2e99c 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp@@ -733,6 +733,10 @@ void Player::update()onPowerBrownOutChange( !m_energy.hasSufficientPower() );}+ // heal what is inside the tunnel network, once for the whole network+ if( m_tunnelSystem )+ m_tunnelSystem->healObjects();+//Update the academy stats (this only checks applicable things that require a polling method)getAcademyStats()->update();@@ -2084,7 +2088,12 @@ void Player::killPlayer(void)}if (isLocalPlayer() && !TheGameLogic->isInShellGame()){- becomingLocalPlayer(TRUE); // recalc disguises, etc+ // becomingLocalPlayer(TRUE) used to run here to "recalc disguises, etc". It calls+ // recalcApparentControllingPlayer on every object with a contain, which resets the team of+ // an empty one - and a container remembers the team its owner had *before* anyone got in,+ // which is not updated when the player dies and the units change hands. So this reset the+ // team to neutral, and only on the client whose player it was. The disguise recalculation+ // it was there for does not work anyway. Restore it once containers track their team.if (TheControlBar ){if (isPlayerActive())@@ -3006,7 +3015,7 @@ Upgrade *Player::findUpgrade( const UpgradeTemplate *upgradeTemplate )//=================================================================================================/** Does the player have this completed upgrade *///=================================================================================================-Bool Player::hasUpgradeComplete( const UpgradeTemplate *upgradeTemplate )+Bool Player::hasUpgradeComplete( const UpgradeTemplate *upgradeTemplate ) const{UpgradeMaskType testMask = upgradeTemplate->getUpgradeMask();return hasUpgradeComplete( testMask );@@ -3017,7 +3026,7 @@ Bool Player::hasUpgradeComplete( const UpgradeTemplate *upgradeTemplate )Does the player have this completed upgrade. This form is exposed so Objects can do quick lookups.*///=================================================================================================-Bool Player::hasUpgradeComplete( UpgradeMaskType testMask )+Bool Player::hasUpgradeComplete( UpgradeMaskType testMask ) const{return m_upgradesCompleted.testForAll( testMask );}@@ -3423,8 +3432,7 @@ Bool Player::doesObjectQualifyForBattlePlan( Object *obj ) const}//--------------------------------------------------------------------------------------------------// note, bonus is an in-out parm.-void Player::changeBattlePlan( BattlePlanStatus plan, Int delta, BattlePlanBonuses *bonus )+void Player::changeBattlePlan( BattlePlanStatus plan, Int delta, const BattlePlanBonuses *bonus ){DUMPBATTLEPLANBONUSES(bonus, this, NULL);Bool addBonus = false;@@ -3477,23 +3485,29 @@ void Player::changeBattlePlan( BattlePlanStatus plan, Int delta, BattlePlanBonus}else if( removeBonus ){- //First, inverse the bonuses- bonus->m_armorScalar = 1.0f / __max( bonus->m_armorScalar, 0.01f );- bonus->m_sightRangeScalar = 1.0f / __max( bonus->m_sightRangeScalar, 0.01f );- if( bonus->m_bombardment > 0 )+ // inverse the bonuses in a copy: this used to invert the caller's own data in place, which is+ // the strategy center's m_bonuses, so the module's record of what it granted was destroyed by+ // the act of taking it away.+ BattlePlanBonuses *invertedBonus = newInstance(BattlePlanBonuses);+ *invertedBonus = *bonus;++ invertedBonus->m_armorScalar = 1.0f / __max( bonus->m_armorScalar, 0.01f );+ invertedBonus->m_sightRangeScalar = 1.0f / __max( bonus->m_sightRangeScalar, 0.01f );+ if( invertedBonus->m_bombardment > 0 ){- bonus->m_bombardment = -1;+ invertedBonus->m_bombardment = -1;}- if( bonus->m_holdTheLine > 0 )+ if( invertedBonus->m_holdTheLine > 0 ){- bonus->m_holdTheLine = -1;+ invertedBonus->m_holdTheLine = -1;}- if( bonus->m_searchAndDestroy > 0 )+ if( invertedBonus->m_searchAndDestroy > 0 ){- bonus->m_searchAndDestroy = -1;+ invertedBonus->m_searchAndDestroy = -1;}- applyBattlePlanBonusesForPlayerObjects( bonus );+ applyBattlePlanBonusesForPlayerObjects( invertedBonus );+ invertedBonus->deleteInstance();}}@@ -3655,7 +3669,18 @@ void Player::applyBattlePlanBonusesForPlayerObjects( const BattlePlanBonuses *bo}DUMPBATTLEPLANBONUSES(m_battlePlanBonuses, this, NULL);- iterateObjects( localApplyBattlePlanBonusesToObject, (void*)bonus );++ // hand every object the whole set the player holds, not just the plan that changed: the counts+ // and the kindof filters live in m_battlePlanBonuses, and passing only the newest one told a+ // unit it was under that plan alone. The scalars still come from the change itself, because+ // they are applied multiplicatively, once per change.+ BattlePlanBonuses *newBonus = newInstance(BattlePlanBonuses);+ *newBonus = *m_battlePlanBonuses;+ newBonus->m_armorScalar = bonus->m_armorScalar;+ newBonus->m_sightRangeScalar = bonus->m_sightRangeScalar;++ iterateObjects( localApplyBattlePlanBonusesToObject, newBonus );+ newBonus->deleteInstance();}diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/TunnelTracker.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/TunnelTracker.cppindex 05b392be2..d8477f5b7 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/TunnelTracker.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/TunnelTracker.cpp@@ -252,10 +252,45 @@ void TunnelTracker::destroyObject( Object *obj, void * )}// ------------------------------------------------------------------------- // heal all the objects within the tunnel system using the iterateContained function-void TunnelTracker::healObjects(Real frames)+ // heal all the objects within the tunnel system using the iterateContained function.+ // this used to be driven by every TunnelContain's own update, so a network of five tunnels+ // healed everyone inside it five times a frame - the more tunnels you owned, the faster your+ // units healed. The player drives it now, once.+void TunnelTracker::healObjects(){- iterateContained(healObject, &frames, FALSE);+ if( m_containListSize == 0 )+ return;++ Real framesForFullHeal = getFramesForFullHeal();+ if( framesForFullHeal <= 0.0f )+ return;++ iterateContained(healObject, &framesForFullHeal, FALSE);+}++// ------------------------------------------------------------------------+ // the shortest full-heal time of the tunnels still standing+Real TunnelTracker::getFramesForFullHeal() const+{+ Real minFrames = 0.0f;++ for( std::list<ObjectID>::const_iterator it = m_tunnelIDs.begin(); it != m_tunnelIDs.end(); ++it )+ {+ const Object *tunnelObj = TheGameLogic->findObjectByID( *it );+ if( tunnelObj == NULL )+ continue;++ const ContainModuleInterface *contain = tunnelObj->getContain();+ DEBUG_ASSERTCRASH( contain != NULL, ("a tunnel with no contain module") );+ if( !contain->isTunnelContain() )+ continue;++ const Real frames = ((const TunnelContain *)contain)->getFullTimeForHeal();+ if( minFrames == 0.0f || frames < minFrames )+ minFrames = frames;+ }++ return minFrames;}// ------------------------------------------------------------------------diff --git a/GeneralsMD/Code/GameEngine/Source/Common/Recorder.cpp b/GeneralsMD/Code/GameEngine/Source/Common/Recorder.cppindex c387f9e91..17147d394 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/Recorder.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/Recorder.cpp@@ -714,10 +714,38 @@ void RecorderClass::stopRecording() {if (m_file != NULL) {fclose(m_file);m_file = NULL;++ if (TheGlobalData->m_archiveReplays)+ archiveReplay(m_fileName);}m_fileName.clear();}+/**+ * Copy the replay that was just written to the archive directory, under a timestamped name.+ * Every game overwrites the same LastReplay file, so without this only the most recent one+ * survives unless the player renames it by hand before starting the next match.+ */+void RecorderClass::archiveReplay(const AsciiString& fileName)+{+ SYSTEMTIME st;+ GetLocalTime(&st);++ AsciiString sourcePath = getReplayDir();+ sourcePath.concat(fileName);++ AsciiString destPath = getReplayArchiveDir();+ TheFileSystem->createDirectory(destPath);++ AsciiString stamp;+ stamp.format("%04d%02d%02d_%02d%02d%02d", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);+ destPath.concat(stamp);+ destPath.concat(getReplayExtention());++ if (!CopyFile(sourcePath.str(), destPath.str(), FALSE))+ DEBUG_LOG(("RecorderClass::archiveReplay - failed to copy %s to %s\n", sourcePath.str(), destPath.str()));+}+/*** Write this game message to the record file. This also writes the game message's execution frame.*/@@ -1495,6 +1523,16 @@ AsciiString RecorderClass::getReplayDir()return tmp;}+/**+ * returns the directory that holds the archived replay files.+ */+AsciiString RecorderClass::getReplayArchiveDir()+{+ AsciiString tmp = TheGlobalData->getPath_UserData();+ tmp.concat("ArchivedReplays\\");+ return tmp;+}+/*** returns the file extention for the replay files.*/diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/ArchiveFileSystem.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/ArchiveFileSystem.cppindex 70c34153a..d74c274ad 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/System/ArchiveFileSystem.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/ArchiveFileSystem.cpp@@ -264,6 +264,71 @@ Bool ArchiveFileSystem::getFileInfo(const AsciiString& filename, FileInfo *fileI}}+// Where two archives hold the same file, loadIntoDirectoryTree keeps whichever was loaded first.+// That is the right rule for content, but Zero Hour ships downscaled copies of a number of the base+// game's textures in TexturesZH.big, and those win over the full-size originals in the base game's+// Textures.big purely because of load order. For the named pair of archives, and only inside the+// named directory, keep whichever copy is actually the larger file.+void ArchiveFileSystem::prioritizeLargerFiles(const AsciiString& directory, const char *inferiorArchive, const char *superiorArchive)+{+ // walk down to the directory+ AsciiString path = directory;+ path.toLower();+ AsciiString token;++ ArchivedDirectoryInfo *dirInfo = &m_rootDirectory;+ while (path.nextToken(&token, "\\/"))+ {+ ArchivedDirectoryInfoMap::iterator dirIt = dirInfo->m_directories.find(token);+ if (dirIt == dirInfo->m_directories.end())+ return;++ dirInfo = &dirIt->second;+ }++ // find the archive that holds the bigger copies+ ArchiveFile *superior = NULL;+ AsciiString superiorName;+ for (ArchiveFileMap::iterator archiveIt = m_archiveFileMap.begin(); archiveIt != m_archiveFileMap.end(); ++archiveIt)+ {+ if (archiveIt->first.endsWithNoCase(superiorArchive))+ {+ superior = archiveIt->second;+ superiorName = archiveIt->first;+ break;+ }+ }++ if (superior == NULL)+ return;++ for (ArchivedFileLocationMap::iterator fileIt = dirInfo->m_files.begin(); fileIt != dirInfo->m_files.end(); ++fileIt)+ {+ if (!fileIt->second.endsWithNoCase(inferiorArchive))+ continue;++ ArchiveFileMap::iterator inferiorIt = m_archiveFileMap.find(fileIt->second);+ if (inferiorIt == m_archiveFileMap.end())+ continue;++ AsciiString filePath = directory;+ filePath.concat(fileIt->first);++ FileInfo inferiorInfo, superiorInfo;+ if (!inferiorIt->second->getFileInfo(filePath, &inferiorInfo))+ continue;+ if (!superior->getFileInfo(filePath, &superiorInfo))+ continue;++ if (superiorInfo.sizeLow > inferiorInfo.sizeLow)+ {+ DEBUG_LOG(("ArchiveFileSystem::prioritizeLargerFiles - %s (%d bytes) from %s wins over the %d byte copy in %s\n",+ filePath.str(), superiorInfo.sizeLow, superiorName.str(), inferiorInfo.sizeLow, fileIt->second.str()));+ fileIt->second = superiorName;+ }+ }+}+AsciiString ArchiveFileSystem::getArchiveFilenameForFile(const AsciiString& filename) const{AsciiString path;diff --git a/GeneralsMD/Code/GameEngine/Source/Common/Thing/ThingFactory.cpp b/GeneralsMD/Code/GameEngine/Source/Common/Thing/ThingFactory.cppindex b36648a76..b3a6ea957 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/Thing/ThingFactory.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/Thing/ThingFactory.cpp@@ -241,6 +241,13 @@ void ThingFactory::reset( void )t = nextT;}++ // The ids handed out above are what a network game and a save file identify templates by, so+ // they must depend only on the data loaded, not on how many matches this process has played.+ // m_nextTemplateID kept counting up across resets; it now goes back to just past the templates+ // that survived.+ DEBUG_ASSERTCRASH( m_firstTemplate != NULL, ("no templates left after deleting overrides") );+ m_nextTemplateID = (UnsignedShort)(m_firstTemplate->getTemplateID() + 1);} // end reset//-------------------------------------------------------------------------------------------------diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cppindex 9b10e14a6..46338b156 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp@@ -836,6 +836,15 @@ Bool OptionPreferences::getDetailedBuildTooltips(void)return stricmp(it->second.str(), "yes") == 0;}+Bool OptionPreferences::getArchiveReplays(void)+{+ OptionPreferences::const_iterator it = find("ArchiveReplays");+ if (it == end())+ return TheGlobalData->m_archiveReplays;++ return stricmp(it->second.str(), "yes") == 0;+}+Int OptionPreferences::getBloomIntensity(void){// Not written by the options menu - a power-user Options.ini key. Percent, 0 = off, which isdiff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/SelectionXlat.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/SelectionXlat.cppindex 15b92162f..0c1f08c0e 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/SelectionXlat.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/SelectionXlat.cpp@@ -1012,14 +1012,19 @@ GameMessageDisposition SelectionTranslator::translateGameMessage(const GameMessadisp = DESTROY_MESSAGE;TheInGameUI->setScrolling( FALSE );}- else+ else if( TheInGameUI->getPendingPlaceSourceObjectID() != INVALID_ID )+ {+ //Cancel the building placement, and keep the builder selected: you almost always+ //want to place something else with it, and reselecting it costs a click.+ TheInGameUI->placeBuildAvailable( NULL, NULL );++ disp = DESTROY_MESSAGE;+ TheInGameUI->setScrolling( FALSE );+ }+ else if( !TheGlobalData->m_useAlternateMouse ){//No GUI command mode, so deselect everyone if we're in regular mouse mode.- //In alternate mouse mode, right click still cancels building placement.- if (! TheGlobalData->m_useAlternateMouse || TheInGameUI->getPendingPlaceSourceObjectID() != INVALID_ID)- {- deselectAll();- }+ deselectAll();}}diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGuard.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGuard.cppindex d4f791a30..a2b1fb8c2 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGuard.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGuard.cpp@@ -184,8 +184,11 @@ AIGuardMachine::AIGuardMachine( Object *owner ) ://Kris: Except that guard return is more like an attack move, and will acquire targets while moving there.//This breaks deployAI units because they have to completely unpack before realizing that there is a target in range.//So I'm making AI_GUARD_INNER the first state.- defineState( AI_GUARD_INNER, newInstance(AIGuardInnerState)( this ), AI_GUARD_OUTER, AI_GUARD_OUTER, attackAggressors );- defineState( AI_GUARD_RETURN, newInstance(AIGuardReturnState)( this ), AI_GUARD_IDLE, AI_GUARD_INNER, attackAggressors );+ // No attackAggressors condition on these two: while the unit is moving (inner sweep, or the+ // walk back to its post) that condition fought the movement itself, so a guarding unit under+ // fire stuttered between driving and shooting instead of doing either.+ defineState( AI_GUARD_INNER, newInstance(AIGuardInnerState)( this ), AI_GUARD_OUTER, AI_GUARD_OUTER );+ defineState( AI_GUARD_RETURN, newInstance(AIGuardReturnState)( this ), AI_GUARD_IDLE, AI_GUARD_INNER );defineState( AI_GUARD_IDLE, newInstance(AIGuardIdleState)( this ), AI_GUARD_INNER, AI_GUARD_RETURN, attackAggressors );defineState( AI_GUARD_OUTER, newInstance(AIGuardOuterState)( this ), AI_GUARD_GET_CRATE, AI_GUARD_GET_CRATE );defineState( AI_GUARD_GET_CRATE, newInstance(AIGuardPickUpCrateState)( this ), AI_GUARD_RETURN, AI_GUARD_RETURN );diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGuardRetaliate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGuardRetaliate.cppindex 50e86eb64..8e4c21b18 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGuardRetaliate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGuardRetaliate.cpp@@ -189,7 +189,8 @@ AIGuardRetaliateMachine::AIGuardRetaliateMachine( Object *owner ) :// srj sez: I made "return" the start state, so that if ordered to guard a position// that isn't the unit's current position, it moves to that position first.defineState( AI_GUARD_RETALIATE_ATTACK_AGGRESSOR, newInstance(AIGuardRetaliateAttackAggressorState)( this ), AI_GUARD_RETALIATE_RETURN, AI_GUARD_RETALIATE_RETURN );- defineState( AI_GUARD_RETALIATE_RETURN, newInstance(AIGuardRetaliateReturnState)( this ), AI_GUARD_RETALIATE_IDLE, AI_GUARD_RETALIATE_INNER, attackAggressors );+ // see AIGuardMachine: the attackAggressors condition fought the return move itself.+ defineState( AI_GUARD_RETALIATE_RETURN, newInstance(AIGuardRetaliateReturnState)( this ), AI_GUARD_RETALIATE_IDLE, AI_GUARD_RETALIATE_INNER );defineState( AI_GUARD_RETALIATE_IDLE, newInstance(AIGuardRetaliateIdleState)( this ), AI_GUARD_RETALIATE_INNER, EXIT_MACHINE_WITH_SUCCESS, attackAggressors );defineState( AI_GUARD_RETALIATE_INNER, newInstance(AIGuardRetaliateInnerState)( this ), AI_GUARD_RETALIATE_OUTER, AI_GUARD_RETALIATE_OUTER );defineState( AI_GUARD_RETALIATE_OUTER, newInstance(AIGuardRetaliateOuterState)( this ), AI_GUARD_RETALIATE_GET_CRATE, AI_GUARD_RETALIATE_GET_CRATE );diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cppindex 5e4e3c970..65fe95b5e 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp@@ -11310,10 +11310,10 @@ void Pathfinder::crc( Xfer *xfer )xfer->xferInt(&m_numWallPieces);CRCDEBUG_LOG(("m_numWallPieces: %8.8X\n", ((XferCRC *)xfer)->getCRC()));- for (Int i=0; i<MAX_WALL_PIECES; ++i)- {- xfer->xferObjectID(&m_wallPieces[MAX_WALL_PIECES]);- }+ // this used to loop MAX_WALL_PIECES times over &m_wallPieces[MAX_WALL_PIECES], which is one past+ // the end of the array and lands on m_numWallPieces - so the crc covered that member 128 times+ // and the wall pieces not at all.+ xfer->xferUser(m_wallPieces, sizeof(m_wallPieces));CRCDEBUG_LOG(("m_wallPieces: %8.8X\n", ((XferCRC *)xfer)->getCRC()));xfer->xferReal(&m_wallHeight);diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cppindex 9f5568cec..5cd5282de 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp@@ -2691,7 +2691,14 @@ StateReturnType AIAttackApproachTargetState::updateInternal()}if( victim->testStatus( OBJECT_STATUS_STEALTHED ) && !victim->testStatus( OBJECT_STATUS_DETECTED ) && !victim->testStatus( OBJECT_STATUS_DISGUISED ) ){- return STATE_FAILURE; // If obj is stealthed, can no longer approach.+ // If obj is stealthed, can no longer approach - except to disarm it. Mines and traps+ // are stealthed by nature, so refusing the approach here left a unit ordered to clear+ // one standing still.+ const Bool isTargetingMine = weapon && weapon->getDamageType() == DAMAGE_DISARM &&+ (victim->isKindOf(KINDOF_MINE) || victim->isKindOf(KINDOF_BOOBY_TRAP) || victim->isKindOf(KINDOF_DEMOTRAP));++ if (!isTargetingMine)+ return STATE_FAILURE;}ai->setCurrentVictim(victim);// Attacking an object.@@ -6655,6 +6662,17 @@ void AIEnterState::onExit( StateExitType status )}}+//----------------------------------------------------------------------------------------------------------+/** Do the two objects' vertical extents touch at all? */+static Bool hasVerticalOverlap( const Object* a, const Object* b )+{+ const Real aLower = a->getPosition()->z;+ const Real aUpper = aLower + a->getGeometryInfo().getMaxHeightAbovePosition();+ const Real bLower = b->getPosition()->z;+ const Real bUpper = bLower + b->getGeometryInfo().getMaxHeightAbovePosition();+ return aUpper >= bLower && aLower <= bUpper;+}+//----------------------------------------------------------------------------------------------------------StateReturnType AIEnterState::update(){@@ -6717,8 +6735,10 @@ StateReturnType AIEnterState::update()StateReturnType code = AIInternalMoveToState::update();- // if it's airborne, wait for it to land- if (code == STATE_SUCCESS && goal->isAboveTerrain() && !obj->isAboveTerrain())+ // if it's airborne, wait for it to land. Comparing the two vertical extents (rather than+ // asking only whether the goal is off the ground and we are not) also stops a levitating or+ // airborne rider from stepping into a transport it is nowhere near touching.+ if (code == STATE_SUCCESS && !hasVerticalOverlap(goal, obj)){code = STATE_CONTINUE;}diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/FlightDeckBehavior.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/FlightDeckBehavior.cppindex 3e4fb6e30..3636130ab 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/FlightDeckBehavior.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/FlightDeckBehavior.cpp@@ -602,6 +602,21 @@ void FlightDeckBehavior::releaseSpace(ObjectID id)}+//-------------------------------------------------------------------------------------------------+Int FlightDeckBehavior::getRunwayIndex(ObjectID id)+{+ purgeDead();++ for (std::vector<FlightDeckInfo>::iterator it = m_spaces.begin(); it != m_spaces.end(); ++it)+ {+ if (it->m_objectInSpace == id)+ {+ return it->m_runway;+ }+ }+ return InvalidRunway;+}+//-------------------------------------------------------------------------------------------------ObjectID FlightDeckBehavior::getRunwayReservation( Int runway, RunwayReservationType type ){diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/ParkingPlaceBehavior.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/ParkingPlaceBehavior.cppindex 4228b823c..c24c6e3cc 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/ParkingPlaceBehavior.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/ParkingPlaceBehavior.cpp@@ -448,6 +448,21 @@ void ParkingPlaceBehavior::releaseSpace(ObjectID id)}+//-------------------------------------------------------------------------------------------------+Int ParkingPlaceBehavior::getRunwayIndex(ObjectID id)+{+ purgeDead();++ for (std::vector<ParkingPlaceInfo>::iterator it = m_spaces.begin(); it != m_spaces.end(); ++it)+ {+ if (it->m_objectInSpace == id)+ {+ return it->m_runway;+ }+ }+ return InvalidRunway;+}+//-------------------------------------------------------------------------------------------------ObjectID ParkingPlaceBehavior::getRunwayReservation( Int runway, RunwayReservationType type ){diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/CrateCollide.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/CrateCollide.cppindex 3985be20c..c6f0de4a6 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/CrateCollide.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/CrateCollide.cpp@@ -176,6 +176,11 @@ Bool CrateCollide::isValidToExecute( const Object *other ) constif( getObject()->isAboveTerrain() && !validBuildingAttempt )return FALSE;+ // every unit that touches the crate in the same frame used to collect it: the crate is marked+ // destroyed by the first one, but destruction does not happen until the end of the frame.+ if( getObject()->isDestroyed() )+ return FALSE;+if( md->m_isForbidOwnerPlayer && (getObject()->getControllingPlayer() == other->getControllingPlayer()) )return FALSE; // Design has decreed this to not be picked up by the dead guy's team.diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cppindex 5f66c70aa..91a933f00 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cpp@@ -1041,8 +1041,8 @@ void OpenContain::exitObjectViaDoor( Object *exitObj, ExitDoorType exitDoor )std::vector<Coord3D> exitPath;exitPath.push_back(endPosition);exitPath.push_back(endPosition); // Do it twice, in case units stack up due to brief flying. jba.- if (m_rallyPointExists) {- exitPath.push_back(m_rallyPoint);+ if (const Coord3D *rallyPoint = getRallyPoint()) {+ exitPath.push_back(*rallyPoint);}if( ai )@@ -1555,6 +1555,12 @@ const Coord3D *OpenContain::getRallyPoint( void ) constif (m_rallyPointExists)return &m_rallyPoint;+ // A container that was never given a rally point of its own follows the building's, so the+ // flag the player planted on the barracks also applies to whatever walks out of its hold.+ ExitInterface *primaryExit = getObject()->getObjectExitInterface();+ if (primaryExit && primaryExit != static_cast<const ExitInterface *>(this))+ return primaryExit->getRallyPoint();+return NULL;}diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/TunnelContain.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/TunnelContain.cppindex 62d70d1ea..8064f4b8d 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/TunnelContain.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/TunnelContain.cpp@@ -504,10 +504,10 @@ void TunnelContain::onCapture( Player *oldOwner, Player *newOwner )// ------------------------------------------------------------------------------------------------UpdateSleepTime TunnelContain::update( void ){- // extending functionality to heal the units within the tunnel system+ // the healing of the units within the tunnel system is driven by the player, once a frame for+ // the whole network - see TunnelTracker::healObjects.OpenContain::update();- const TunnelContainModuleData *modData = getTunnelContainModuleData();-+Object *obj = getObject();Player *controllingPlayer = NULL;if (obj)@@ -517,10 +517,6 @@ UpdateSleepTime TunnelContain::update( void )if (controllingPlayer){TunnelTracker *tunnelSystem = controllingPlayer->getTunnelSystem();- if (tunnelSystem)- {- tunnelSystem->healObjects(modData->m_framesForFullHeal);- }// check for attacked.BodyModuleInterface *body = obj->getBodyModule();diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cppindex 4c1fccfac..2dadb8256 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp@@ -3137,6 +3137,11 @@ Bool Object::hasAnySpecialPower() const//-------------------------------------------------------------------------------------------------void Object::onVeterancyLevelChanged( VeterancyLevel oldLevel, VeterancyLevel newLevel, Bool provideFeedback ){+ // a kill scored by a unit that is already dying used to promote the corpse: upgrades, weapon+ // bonuses, the level-up animation and the sound.+ if( isEffectivelyDead() )+ return;+updateUpgradeModules();const UpgradeTemplate* up = TheUpgradeCenter->findVeterancyUpgrade(newLevel);diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/ObjectCreationList.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/ObjectCreationList.cppindex 2a7e52af8..acd5eb70b 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/ObjectCreationList.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/ObjectCreationList.cpp@@ -1396,7 +1396,9 @@ protected:// longer be necessary and can be taken out -- amitif (m_spreadFormation){- Coord3D resultPos;+ // findPositionAround leaves the result alone when it fails, and this used to be an+ // uninitialised stack Coord3D: the debris then appeared at whatever was on the stack.+ Coord3D resultPos = *pos;FindPositionOptions fpOptions;fpOptions.minRadius = GameLogicRandomValueReal(m_minDistanceAFormation, m_minDistanceBFormation);fpOptions.maxRadius = m_maxDistanceFormation;diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cppindex c2337b92a..7f5725b05 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp@@ -1873,6 +1873,46 @@ void PartitionData::doCircleFill(}}+// -----------------------------------------------------------------------------+// The scanline circle above is a midpoint-circle outline with its spans filled in, in whole cells:+// it claims cells the object does not reach and misses cells it does, most visibly for radii of+// about 20 to 40 (one to two cells). This one keeps a cell if the circle overlaps the cell's+// square at all.+void PartitionData::doCircleFillPrecise(Real centerX, Real centerY, Real radius)+{+ DEBUG_ASSERTCRASH(m_coiInUseCount == 0, ("expected no coi in use here"));++ Int minCellX, minCellY, maxCellX, maxCellY;+ ThePartitionManager->worldToCell(centerX - radius, centerY - radius, &minCellX, &minCellY);+ ThePartitionManager->worldToCell(centerX + radius, centerY + radius, &maxCellX, &maxCellY);++ const Real halfCell = ThePartitionManager->getCellSize() * 0.5f;++ for (Int x = minCellX; x <= maxCellX; ++x)+ {+ for (Int y = minCellY; y <= maxCellY; ++y)+ {+ PartitionCell *cell = ThePartitionManager->getCellAt(x, y);+ if (cell == NULL)+ continue;++ Real cellCenterX, cellCenterY;+ ThePartitionManager->getCellCenterPos(x, y, cellCenterX, cellCenterY);++ // distance from the circle's center to the closest point of the cell's square+ Real dx = (Real)fabs(centerX - cellCenterX) - halfCell;+ Real dy = (Real)fabs(centerY - cellCenterY) - halfCell;+ if (dx < 0.0f)+ dx = 0.0f;+ if (dy < 0.0f)+ dy = 0.0f;++ if (sqr(dx) + sqr(dy) < sqr(radius))+ addSubPixToCoverage(cell);+ }+ }+}+// -----------------------------------------------------------------------------void PartitionData::doSmallFill(Real centerX,@@ -2070,7 +2110,7 @@ void PartitionData::updateCellsTouched()case GEOMETRY_SPHERE:case GEOMETRY_CYLINDER:{- doCircleFill(pos.x, pos.y, majorRadius);+ doCircleFillPrecise(pos.x, pos.y, majorRadius);break;}diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cppindex ff76e6d4b..7988e3218 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp@@ -4737,122 +4737,137 @@ setTmpValue(now);// ------------------------------------------------------------------------------------------------// -------------------------------------------------------------------------------------------------void AIUpdateInterface::evaluateMoraleBonus( void )+Bool AIUpdateInterface::hasNationalism() const{- Object *us = getObject();-#ifdef ALLOW_DEMORALIZE- Bool demoralized = isDemoralized();-#endif- Bool horde = FALSE;- Bool nationalism = FALSE;- Bool fanaticism = FALSE;-- // do we have nationalism- ///@todo Find a better way to represent nationalism without hardcoding here (CBD)- static const UpgradeTemplate *nationalismTemplate = TheUpgradeCenter->findUpgrade( "Upgrade_Nationalism" );- DEBUG_ASSERTCRASH( nationalismTemplate != NULL, ("AIUpdateInterface::evaluateMoraleBonus - Nationalism upgrade not found\n") );- Player *player = us->getControllingPlayer();- if( player && player->hasUpgradeComplete( nationalismTemplate ) )- nationalism = TRUE;-- // do we have fanaticism- ///@todo Find a better way to represent fanaticism without hardcoding here (MAL)- static const UpgradeTemplate *fanaticismTemplate = TheUpgradeCenter->findUpgrade( "Upgrade_Fanaticism" );- DEBUG_ASSERTCRASH( fanaticismTemplate != NULL, ("AIUpdateInterface::evaluateMoraleBonus - Fanaticism upgrade not found\n") );- if( player && player->hasUpgradeComplete( fanaticismTemplate ) )- fanaticism = TRUE;-- // are we in a horde- HordeUpdateInterface *hui;- for( BehaviorModule** u = us->getBehaviorModules(); *u; ++u )- {-- hui = (*u)->getHordeUpdateInterface();- if( hui && hui->isInHorde() )- {- horde = TRUE;-- if( !hui->isAllowedNationalism() )- {- // Sorry CBD and MAL, but the cancer has spread to the lymph nodes. After Alpha, just pump full of painkillers.- nationalism = FALSE;- fanaticism = FALSE;- }- }+ const Player *player = getObject()->getControllingPlayer();+ if( player )+ {+ ///@todo Find a better way to represent nationalism without hardcoding here (CBD)+ static const UpgradeTemplate *nationalismTemplate = TheUpgradeCenter->findUpgrade( "Upgrade_Nationalism" );+ DEBUG_ASSERTCRASH( nationalismTemplate != NULL, ("AIUpdateInterface::hasNationalism - Nationalism upgrade not found\n") );+ if( nationalismTemplate )+ return player->hasUpgradeComplete( nationalismTemplate );+ }+ return FALSE;+}- } // end for+// ------------------------------------------------------------------------------------------------+// ------------------------------------------------------------------------------------------------+Bool AIUpdateInterface::hasFanaticism() const+{+ const Player *player = getObject()->getControllingPlayer();+ if( player )+ {+ ///@todo Find a better way to represent fanaticism without hardcoding here (MAL)+ static const UpgradeTemplate *fanaticismTemplate = TheUpgradeCenter->findUpgrade( "Upgrade_Fanaticism" );+ DEBUG_ASSERTCRASH( fanaticismTemplate != NULL, ("AIUpdateInterface::hasFanaticism - Fanaticism upgrade not found\n") );+ if( fanaticismTemplate )+ return player->hasUpgradeComplete( fanaticismTemplate );+ }+ return FALSE;+}+// ------------------------------------------------------------------------------------------------+// the horde module that owns the bonus tells us what it sees, instead of us walking every behavior+// module of the object to work it out again.+// ------------------------------------------------------------------------------------------------+void AIUpdateInterface::evaluateMoraleBonus( Bool inHorde, Bool allowNationalism, HordeActionType type )+{#ifdef ALLOW_DEMORALIZE- // if we are are not demoralized we can have horde and nationalism effects- if( demoralized == FALSE )-#endif+ if( isDemoralized() ){+ Object *us = getObject();-#ifdef ALLOW_DEMORALIZE- // demoralized- us->clearWeaponBonusCondition( WEAPONBONUSCONDITION_DEMORALIZED );-#endif-- //Lorenzen temporarily disabled, since it fights with the horde buff- //Drawable *draw = us->getDrawable();- //if ( draw && !us->isKindOf( KINDOF_PORTABLE_STRUCTURE ) )- // draw->setTerrainDecal(TERRAIN_DECAL_NONE);+ us->setWeaponBonusCondition( WEAPONBONUSCONDITION_DEMORALIZED );- // horde- if( horde )- {- us->setWeaponBonusCondition( WEAPONBONUSCONDITION_HORDE );+ // a demoralized unit gets none of the three bonuses+ us->clearWeaponBonusCondition( WEAPONBONUSCONDITION_HORDE );+ us->clearWeaponBonusCondition( WEAPONBONUSCONDITION_NATIONALISM );+ us->clearWeaponBonusCondition( WEAPONBONUSCONDITION_FANATICISM );- } // end if- else- us->clearWeaponBonusCondition( WEAPONBONUSCONDITION_HORDE );+ Drawable *draw = us->getDrawable();+ if( draw && !us->isKindOf( KINDOF_PORTABLE_STRUCTURE ) )+ draw->setTerrainDecal( TERRAIN_DECAL_DEMORALIZED );- // nationalism- if( nationalism )- {- us->setWeaponBonusCondition( WEAPONBONUSCONDITION_NATIONALISM );- // fanaticism- if ( fanaticism )- us->setWeaponBonusCondition( WEAPONBONUSCONDITION_FANATICISM );// FOR THE NEW GC INFANTRY GENERAL- else- us->clearWeaponBonusCondition( WEAPONBONUSCONDITION_FANATICISM );- }- else- us->clearWeaponBonusCondition( WEAPONBONUSCONDITION_NATIONALISM );+ return;+ }+ getObject()->clearWeaponBonusCondition( WEAPONBONUSCONDITION_DEMORALIZED );+#endif+ //Lorenzen temporarily disabled, since it fights with the horde buff+ //Drawable *draw = getObject()->getDrawable();+ //if ( draw && !getObject()->isKindOf( KINDOF_PORTABLE_STRUCTURE ) )+ // draw->setTerrainDecal(TERRAIN_DECAL_NONE);- } // end if-#ifdef ALLOW_DEMORALIZE- else+ switch( type ){+ case HORDEACTION_HORDE:+ evaluateNationalismBonusClassic( inHorde, allowNationalism );+ break;- // demoralized- us->setWeaponBonusCondition( WEAPONBONUSCONDITION_DEMORALIZED );+ case HORDEACTION_HORDE_FIXED:+ evaluateNationalismBonus( inHorde, allowNationalism );+ break;+ }+}- // we cannot have horde bonus condition+// ------------------------------------------------------------------------------------------------+// the classic rule: nationalism and fanaticism are granted while the upgrades are owned and are+// never taken away again, even when the horde breaks up.+// ------------------------------------------------------------------------------------------------+void AIUpdateInterface::evaluateNationalismBonusClassic( Bool inHorde, Bool allowNationalism )+{+ Object *us = getObject();++ if( inHorde )+ us->setWeaponBonusCondition( WEAPONBONUSCONDITION_HORDE );+ elseus->clearWeaponBonusCondition( WEAPONBONUSCONDITION_HORDE );- Drawable *draw = us->getDrawable();- if( draw && !us->isKindOf( KINDOF_PORTABLE_STRUCTURE ) )- {- draw->setTerrainDecal(TERRAIN_DECAL_DEMORALIZED);- }-- // we cannot have nationalism bonus condition++ if( allowNationalism && hasNationalism() )+ {+ us->setWeaponBonusCondition( WEAPONBONUSCONDITION_NATIONALISM );++ // FOR THE NEW GC INFANTRY GENERAL+ if( hasFanaticism() )+ us->setWeaponBonusCondition( WEAPONBONUSCONDITION_FANATICISM );+ else+ us->clearWeaponBonusCondition( WEAPONBONUSCONDITION_FANATICISM );+ }+ elseus->clearWeaponBonusCondition( WEAPONBONUSCONDITION_NATIONALISM );- us->clearWeaponBonusCondition( WEAPONBONUSCONDITION_FANATICISM );+}- } // end else-#endif+// ------------------------------------------------------------------------------------------------+// the fixed rule: all three bonuses follow the horde status, and fanaticism no longer needs+// nationalism to be owned as well.+// ------------------------------------------------------------------------------------------------+void AIUpdateInterface::evaluateNationalismBonus( Bool inHorde, Bool allowNationalism )+{+ Object *us = getObject();-/*- UnicodeString msg;- msg.format( L"'%S' Horde=%d,Nationalism=%d,Demoralized=%d",- us->getTemplate()->getName().str(), horde, nationalism, demoralized );- TheInGameUI->message( msg );-*/+ if( inHorde )+ {+ us->setWeaponBonusCondition( WEAPONBONUSCONDITION_HORDE );++ if( allowNationalism && hasNationalism() )+ us->setWeaponBonusCondition( WEAPONBONUSCONDITION_NATIONALISM );+ else+ us->clearWeaponBonusCondition( WEAPONBONUSCONDITION_NATIONALISM );-} // end evaluateMoraleBonus+ if( allowNationalism && hasFanaticism() )+ us->setWeaponBonusCondition( WEAPONBONUSCONDITION_FANATICISM );+ else+ us->clearWeaponBonusCondition( WEAPONBONUSCONDITION_FANATICISM );+ }+ else+ {+ us->clearWeaponBonusCondition( WEAPONBONUSCONDITION_HORDE );+ us->clearWeaponBonusCondition( WEAPONBONUSCONDITION_NATIONALISM );+ us->clearWeaponBonusCondition( WEAPONBONUSCONDITION_FANATICISM );+ }+}#ifdef ALLOW_DEMORALIZE// ------------------------------------------------------------------------------------------------@@ -4870,7 +4885,13 @@ void AIUpdateInterface::setDemoralized( UnsignedInt durationInFrames ){// evaluate demoralization, nationalism, and horde effect as they are all intertwined- evaluateMoraleBonus();+ Object *us = getObject();+ for( BehaviorModule** u = us->getBehaviorModules(); *u; ++u )+ {+ HordeUpdateInterface *hui = (*u)->getHordeUpdateInterface();+ if( hui )+ evaluateMoraleBonus( hui->isInHorde(), hui->isAllowedNationalism(), hui->getHordeActionType() );+ }} // end if@@ -5077,12 +5098,14 @@ void AIUpdateInterface::crc( Xfer *x )// ------------------------------------------------------------------------------------------------/** Xfer method* Version Info:- * 1: Initial version */+ * 1: Initial version+ * 5: the production rally point and its flag+ * 6: the out-of-bounds xfer of m_guardTargetType is fixed */// ------------------------------------------------------------------------------------------------void AIUpdateInterface::xfer( Xfer *xfer ){// version- const XferVersion currentVersion = 5;+ const XferVersion currentVersion = 6;XferVersion version = currentVersion;xfer->xferVersion( &version, currentVersion );@@ -5099,8 +5122,20 @@ void AIUpdateInterface::xfer( Xfer *xfer )xfer->xferObjectID(&m_currentVictimID);xfer->xferReal(&m_desiredSpeed);xfer->xferUser(&m_lastCommandSource, sizeof(m_lastCommandSource));- xfer->xferUser(&m_guardTargetType[0], sizeof(m_guardTargetType));- xfer->xferUser(&m_guardTargetType[1], sizeof(m_guardTargetType));+ if (version < 6)+ {+ // the original wrote m_guardTargetType[0] and [1], then [1] and [2] - and [2] is one past the+ // end of a two-element array, landing on m_locationToGuard. Read an old save exactly the way+ // it was written, so it still loads.+ xfer->xferUser(&m_guardTargetType[0], sizeof(m_guardTargetType));+ xfer->xferUser(&m_guardTargetType[1], sizeof(m_guardTargetType[1]));+ xfer->xferUser(&m_locationToGuard, sizeof(m_guardTargetType[1]));+ }+ else+ {+ xfer->xferUser(m_guardTargetType, sizeof(m_guardTargetType));+ }+xfer->xferCoord3D(&m_locationToGuard);xfer->xferObjectID(&m_objectToGuard);diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/ChinookAIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/ChinookAIUpdate.cppindex fdcd48ee7..23e0bb804 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/ChinookAIUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/ChinookAIUpdate.cpp@@ -1073,6 +1073,19 @@ UpdateSleepTime ChinookAIUpdate::update()// we're completely healed, so take off againpp->setHealee(getObject(), false);setMyState(TAKING_OFF, NULL, NULL, CMD_FROM_AI);++ // and then go where the airfield's rally point says, instead of hovering over the pad+ Object *airfield = TheGameLogic->findObjectByID( m_airfieldForHealing );+ if (airfield)+ {+ ExitInterface *exitInterface = airfield->getObjectExitInterface();+ if (exitInterface)+ {+ const Coord3D *rallyPoint = exitInterface->getRallyPoint();+ if (rallyPoint)+ aiMoveToPosition( rallyPoint, CMD_FROM_AI );+ }+ }}else{@@ -1289,6 +1302,13 @@ void ChinookAIUpdate::aiDoCommand(const AICommandParms* parms){const Real THRESH = 3.0f;const Real THRESH_SQR = THRESH*THRESH;++ // the evac state below unloads the whole hold in one frame. Only take it when the+ // container has somebody queued to get in or out; otherwise let the standard move+ // command through, which unloads one passenger at a time.+ const ContainModuleInterface* contain = getObject()->getContain();+ const Bool allowExit = contain && contain->hasObjectsWantingToEnterOrExit();+if (calcDistSqr(*getObject()->getPosition(), parms->m_pos) > THRESH_SQR &&m_flightStatus == CHINOOK_LANDED){@@ -1299,7 +1319,7 @@ void ChinookAIUpdate::aiDoCommand(const AICommandParms* parms)setMyState(TAKING_OFF, NULL, NULL, CMD_FROM_AI);passItThru = false;}- else+ else if (allowExit){// do this INSTEAD of the standard stuffsetMyState(diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/JetAIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/JetAIUpdate.cppindex 50b64ce4d..d0789d1a1 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/JetAIUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/JetAIUpdate.cpp@@ -241,8 +241,10 @@ public:ParkingPlaceBehaviorInterface* pp = getPP(jet->getProducerID());if (pp == NULL){- // no producer? just skip this step.- return STATE_SUCCESS;+ // No airfield left to wait for. Succeeding here says "the runway is yours", and the+ // aircraft then flies the rest of a landing that has nowhere to land, so fail instead+ // and let the machine take the dead-airfield route.+ return STATE_FAILURE;}// gotta reserve a space in order to reserve a runway@@ -511,10 +513,9 @@ public:jetAI->chooseLocomotorSet(LOCOMOTORSET_TAXIING);DEBUG_ASSERTCRASH(jetAI->getCurLocomotor(), ("no loco"));- Object* airfield;- ParkingPlaceBehaviorInterface* pp = getPP(jet->getProducerID(), &airfield);+ ParkingPlaceBehaviorInterface* pp = getPP(jet->getProducerID());if (pp == NULL)- return STATE_SUCCESS; // no airfield? just skip this step.+ return STATE_FAILURE; // no airfield left to taxi onParkingPlaceBehaviorInterface::PPInfo ppinfo;if (!pp->reserveSpace(jet->getID(), jetAI->friend_getParkingOffset(), &ppinfo))@@ -753,7 +754,7 @@ public:ParkingPlaceBehaviorInterface* pp = getPP(jet->getProducerID());if (pp == NULL)- return STATE_SUCCESS; // no airfield? just skip this step+ return STATE_FAILURE; // no airfield left to take off from or land onParkingPlaceBehaviorInterface::PPInfo ppinfo;if (!pp->reserveSpace(jet->getID(), jetAI->friend_getParkingOffset(), &ppinfo))@@ -1001,10 +1002,9 @@ public:loco->setUltraAccurate(true);jetAI->ignoreObstacleID(jet->getProducerID());- Object* airfield;- ParkingPlaceBehaviorInterface* pp = getPP(jet->getProducerID(), &airfield);+ ParkingPlaceBehaviorInterface* pp = getPP(jet->getProducerID());if (pp == NULL)- return STATE_SUCCESS; // no airfield? just skip this step+ return STATE_FAILURE; // no helipad left to take off from or land onCoord3D landingApproach;if (jet->isKindOf(KINDOF_PRODUCED_AT_HELIPAD))@@ -1252,15 +1252,23 @@ protected:virtual void xfer( Xfer *xfer ){// version- XferVersion currentVersion = 1;+ XferVersion currentVersion = 2;XferVersion version = currentVersion;xfer->xferVersion( &version, currentVersion );// set on create. xfer->xferBool(&m_landing);- xfer->xferUnsignedInt(&m_when);+ xfer->xferUnsignedInt(&m_whenTakeoff);xfer->xferUnsignedInt(&m_whenTransfer);- xfer->xferBool(&m_afterburners);- xfer->xferBool(&m_resetTimer);++ if (version <= 1)+ {+ // the pre-rewrite state kept two flags here; read past them and throw them away.+ Bool afterburners = false;+ Bool resetTimer = false;+ xfer->xferBool(&afterburners);+ xfer->xferBool(&resetTimer);+ }+xfer->xferObjectID(&m_waitedForTaxiID);}virtual void loadPostProcess()@@ -1269,50 +1277,53 @@ protected:}private:- UnsignedInt m_when;+ UnsignedInt m_whenTakeoff;UnsignedInt m_whenTransfer;ObjectID m_waitedForTaxiID;- Bool m_resetTimer;- Bool m_afterburners;- Bool findWaiter()+ /**+ The jet on the *other* runway that we have to let go first, or NULL if nobody is in our way.+ The runway index is what makes this correct: our own runway's reservation is us, and a jet+ still taxiing on it is the one behind us, which must wait for us, not the other way round.+ (Written for two runways. More than two would want another look.)+ */+ Object* findJetToWaitFor() const{- Object* jet = getMachineOwner();- ParkingPlaceBehaviorInterface* pp = getPP(getMachineOwner()->getProducerID());+ const Object* thisJet = getMachineOwner();+ ParkingPlaceBehaviorInterface* pp = getPP(thisJet->getProducerID());if (pp){- Int count = pp->getRunwayCount();- for (Int i = 0; i < count; ++i)+ const Int thisJetRunway = pp->getRunwayIndex(thisJet->getID());+ const Int runwayCount = pp->getRunwayCount();++ for (Int runway = 0; runway < runwayCount; ++runway){- Object* otherJet = TheGameLogic->findObjectByID( pp->getRunwayReservation( i, RESERVATION_TAKEOFF ) );- if (otherJet == NULL || otherJet == jet)+ if (runway == thisJetRunway)+ continue;++ Object* otherJet = TheGameLogic->findObjectByID( pp->getRunwayReservation( runway, RESERVATION_TAKEOFF ) );+ if (otherJet == NULL)continue;AIUpdateInterface* ai = otherJet->getAIUpdateInterface();if (ai == NULL)continue;- if (ai->getCurrentStateID() == TAXI_TO_TAKEOFF)- {- if (m_waitedForTaxiID == INVALID_ID)- {- m_waitedForTaxiID = otherJet->getID();- }- return true;- }+ if (ai->getCurrentStateID() != TAXI_TO_TAKEOFF)+ continue;++ return otherJet;}}- return false;+ return NULL;}public:JetPauseBeforeTakeoffState( StateMachine *machine ) :AIFaceState(machine, false),- m_when(0),+ m_whenTakeoff(0),m_whenTransfer(0),- m_waitedForTaxiID(INVALID_ID),- m_resetTimer(false),- m_afterburners(false)+ m_waitedForTaxiID(INVALID_ID){// nothing}@@ -1327,11 +1338,9 @@ public:jetAI->friend_setTakeoffInProgress(true);jetAI->friend_setLandingInProgress(false);- m_when = 0;+ m_whenTakeoff = 0;m_whenTransfer = 0;m_waitedForTaxiID = INVALID_ID;- m_resetTimer = false;- m_afterburners = false;ParkingPlaceBehaviorInterface* pp = getPP(jet->getProducerID());if (pp == NULL)@@ -1355,45 +1364,59 @@ public:// always call this.StateReturnType superStatus = AIFaceState::update();-- if (findWaiter())- return STATE_CONTINUE;- UnsignedInt now = TheGameLogic->getFrame();- if (!m_resetTimer)+ Object* otherJet = findJetToWaitFor();+ if (otherJet != NULL){- // we had to wait, but now everyone else is ready, so restart our countdown.- m_when = now + jetAI->friend_getTakeoffPause();+ if (m_waitedForTaxiID == INVALID_ID)+ {+ // remember who we are waiting for, so a jet that starts taxiing after we picked+ // ours cannot make us wait a second time (that was the endless-wait bug).+ m_waitedForTaxiID = otherJet->getID();+ }++ if (m_waitedForTaxiID == otherJet->getID())+ return STATE_CONTINUE;+ }++ const UnsignedInt now = TheGameLogic->getFrame();++ if (m_whenTakeoff == 0)+ {+ // whoever we were waiting for is out of the way: set the countdown, once.if (m_waitedForTaxiID == INVALID_ID){m_waitedForTaxiID = jet->getID(); // just so we don't pick up anyone else- m_whenTransfer = now + 1;+ m_whenTransfer = now + 1;}else{m_whenTransfer = now + 2; // 2 seems odd, but is correct}- m_resetTimer = true;- }- if (!m_afterburners)- {+ // take off soon, but never before the runway has been handed on.+ m_whenTakeoff = now + jetAI->friend_getTakeoffPause();+ if (m_whenTakeoff < m_whenTransfer)+ m_whenTakeoff = m_whenTransfer;+jetAI->friend_enableAfterburners(true);- m_afterburners = true;}-- DEBUG_ASSERTCRASH(m_when != 0, ("hmm"));- DEBUG_ASSERTCRASH(m_whenTransfer != 0, ("hmm"));-- // once we start the final wait, release the runways for guys behind us, so they can start taxiing- ParkingPlaceBehaviorInterface* pp = getPP(jet->getProducerID());- if (pp && now >= m_whenTransfer)+ else{- pp->transferRunwayReservationToNextInLineForTakeoff(jet->getID());- }+ // once we start the final wait, release the runways for guys behind us, so they can start taxiing+ if (now >= m_whenTransfer)+ {+ ParkingPlaceBehaviorInterface* pp = getPP(jet->getProducerID());+ if (pp)+ {+ pp->transferRunwayReservationToNextInLineForTakeoff(jet->getID());+ }+ m_whenTransfer = ~0u; // hand it on once, not every frame afterwards+ }- if (now >= m_when)- return superStatus;+ if (now >= m_whenTakeoff)+ return superStatus;+ }return STATE_CONTINUE;}@@ -1485,6 +1508,12 @@ public:virtual StateReturnType update(){Object* jet = getMachineOwner();++ // the pad can be destroyed while the aircraft is sitting on it, rearming+ ParkingPlaceBehaviorInterface* pp = getPP(jet->getProducerID());+ if (pp == NULL)+ return STATE_FAILURE;+UnsignedInt now = TheGameLogic->getFrame();Bool allDone = true;for (Int i = 0; i < WEAPONSLOT_COUNT; ++i)@@ -1633,8 +1662,8 @@ HeliAIStateMachine::HeliAIStateMachine(Object *owner, AsciiString name) : AIStatdefineState( TAKING_OFF, newInstance(HeliTakeoffOrLandingState)( this, false ), AI_IDLE, AI_IDLE );defineState( LANDING_AWAIT_CLEARANCE, newInstance(SuccessState)( this ), ORIENT_FOR_PARKING_PLACE, AI_IDLE );defineState( ORIENT_FOR_PARKING_PLACE, newInstance(JetOrHeliParkOrientState)( this ), LANDING, AI_IDLE );- defineState( LANDING, newInstance(HeliTakeoffOrLandingState)( this, true ), RELOAD_AMMO, AI_IDLE );- defineState( RELOAD_AMMO, newInstance(JetOrHeliReloadAmmoState)( this ), AI_IDLE, AI_IDLE );+ defineState( LANDING, newInstance(HeliTakeoffOrLandingState)( this, true ), RELOAD_AMMO, TAKING_OFF );+ defineState( RELOAD_AMMO, newInstance(JetOrHeliReloadAmmoState)( this ), AI_IDLE, TAKING_OFF );defineState( RETURN_TO_DEAD_AIRFIELD, newInstance(JetOrHeliReturningToDeadAirfieldState)( this ), CIRCLING_DEAD_AIRFIELD, RETURN_TO_DEAD_AIRFIELD );defineState( CIRCLING_DEAD_AIRFIELD, newInstance(JetOrHeliCirclingDeadAirfieldState)( this ), AI_IDLE, AI_IDLE );defineState( TAXI_FROM_HANGAR, newInstance(JetOrHeliTaxiState)( this, FROM_HANGAR ), AI_IDLE, AI_IDLE );@@ -1873,6 +1902,19 @@ UpdateSleepTime JetAIUpdate::update()getStateMachine()->clear();setLastCommandSource( CMD_FROM_AI );getStateMachine()->setState( TAKING_OFF_AWAIT_CLEARANCE );++ // and then go where the helipad's rally point says+ Object *airfield = TheGameLogic->findObjectByID( jet->getProducerID() );+ if (airfield)+ {+ ExitInterface *exitInterface = airfield->getObjectExitInterface();+ if (exitInterface)+ {+ const Coord3D *rallyPoint = exitInterface->getRallyPoint();+ if (rallyPoint)+ aiMoveToPosition( rallyPoint, CMD_FROM_AI );+ }+ }}else{diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/BattlePlanUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/BattlePlanUpdate.cppindex dc8a80a7a..0c43a4c49 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/BattlePlanUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/BattlePlanUpdate.cpp@@ -214,6 +214,21 @@ void BattlePlanUpdate::onDelete()}+//-------------------------------------------------------------------------------------------------+// A captured strategy center used to leave its plan running for the player that lost it, and give+// the new owner nothing.+//-------------------------------------------------------------------------------------------------+void BattlePlanUpdate::onCapture( Player *oldOwner, Player *newOwner )+{+ if( m_planAffectingArmy == PLANSTATUS_NONE )+ return;++ if( oldOwner )+ oldOwner->changeBattlePlan( m_planAffectingArmy, -1, m_bonuses );+ if( newOwner )+ newOwner->changeBattlePlan( m_planAffectingArmy, 1, m_bonuses );+}+//-------------------------------------------------------------------------------------------------// Validate that we have the necessary data from the ini file.//-------------------------------------------------------------------------------------------------diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/HordeUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/HordeUpdate.cppindex bdcb9e9e2..223873234 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/HordeUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/HordeUpdate.cpp@@ -85,6 +85,10 @@ public:virtual Bool allow(Object *objOther){+ // a corpse still sitting in the partition is not a hordesman.+ if (objOther->isEffectivelyDead())+ return false;+// must be exact same type as us (well, maybe)if (m_data->m_exactMatch && m_obj->getTemplate() != objOther->getTemplate())return false;@@ -126,7 +130,7 @@ HordeUpdateModuleData::HordeUpdateModuleData() :m_alliesOnly(true),m_exactMatch(false),m_allowedNationalism(TRUE),- m_action(HORDEACTION_HORDE)+ m_action(HORDEACTION_DEFAULT){}@@ -195,36 +199,21 @@ Bool HordeUpdate::isAllowedNationalism() const// ------------------------------------------------------------------------------------------------void HordeUpdate::joinOrLeaveHorde(SimpleObjectIterator *iter, Bool join){- Bool prevInHorde = m_inHorde;-- m_inHorde = join;----- const HordeUpdateModuleData* d = getHordeUpdateModuleData();- switch (d->m_action)+ // give/remove bonus effects+ if( m_inHorde != join ){- case HORDEACTION_HORDE:- {-- // give/remove bonus effects- if( prevInHorde != m_inHorde )- {- AIUpdateInterface *ai = getObject()->getAIUpdateInterface();+ m_inHorde = join;- if( ai )- ai->evaluateMoraleBonus();- else- DEBUG_CRASH(( "HordeUpdate::joinOrLeaveHorde - We (%s) must have an AI to benefit from horde\n",- getObject()->getTemplate()->getName().str() ));- } // end if-- }- break;+ AIUpdateInterface *ai = getObject()->getAIUpdateInterface();+ if( ai )+ {+ const HordeUpdateModuleData* md = getHordeUpdateModuleData();+ ai->evaluateMoraleBonus( m_inHorde, md->m_allowedNationalism, md->m_action );+ }+ else+ DEBUG_CRASH(( "HordeUpdate::joinOrLeaveHorde - We (%s) must have an AI to benefit from horde\n",+ getObject()->getTemplate()->getName().str() ));}--}//-------------------------------------------------------------------------------------------------@@ -313,7 +302,7 @@ UpdateSleepTime HordeUpdate::update( void )AIUpdateInterface *ai = getObject()->getAIUpdateInterface();if( ai )- ai->evaluateMoraleBonus();+ ai->evaluateMoraleBonus( m_inHorde, md->m_allowedNationalism, md->m_action );}diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/PhysicsUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/PhysicsUpdate.cppindex 43f3db636..e58ec41bd 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/PhysicsUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/PhysicsUpdate.cpp@@ -32,6 +32,7 @@#define NO_DEBUG_CRC#include "Common/PerfTimer.h"+#include "Common/Player.h"#include "Common/ThingTemplate.h"#include "Common/Xfer.h"#include "GameLogic/GameLogic.h"@@ -45,6 +46,7 @@#include "GameLogic/TerrainLogic.h"#include "GameLogic/Weapon.h"#include "GameLogic/LogicRandomValue.h"+#include "GameClient/FXList.h"#include "GameClient/Statistics.h" // MuLaw/NormalizeToRange, for the bounce sound volumeconst Real DEFAULT_MASS = 1.0f;@@ -1391,7 +1393,25 @@ void PhysicsBehavior::onCollide( Object *other, const Coord3D *loc, const Coord3// fall into a nonbuilding -- whatever. if we're a vehicle, quietly do a little damage.if (obj->isKindOf(KINDOF_VEHICLE)){- TheWeaponStore->createAndFireTempWeapon(getPhysicsBehaviorModuleData()->m_vehicleCrashesIntoNonBuildingWeaponTemplate, obj, obj->getPosition());+ // this used to fire a temp weapon at the crash site, which hits everything in the+ // weapon's radius - and the collision is re-evaluated for every object in the pile,+ // so a vehicle landing among five units damaged all five, five times over. Damage+ // the thing actually collided with, once.+ const WeaponTemplate *weaponTemplate = getPhysicsBehaviorModuleData()->m_vehicleCrashesIntoNonBuildingWeaponTemplate;+ if (weaponTemplate)+ {+ WeaponBonus nullBonus;++ DamageInfo damageInfo;+ damageInfo.in.m_damageType = weaponTemplate->getDamageType();+ damageInfo.in.m_deathType = weaponTemplate->getDeathType();+ damageInfo.in.m_sourceID = obj->getID();+ damageInfo.in.m_sourcePlayerMask = obj->getControllingPlayer() ? obj->getControllingPlayer()->getPlayerMask() : 0;+ damageInfo.in.m_amount = weaponTemplate->getPrimaryDamage(nullBonus);++ other->attemptDamage(&damageInfo);+ FXList::doFXObj(weaponTemplate->getFireFX(obj->getVeterancyLevel()), obj);+ }}}}diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/StealthUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/StealthUpdate.cppindex cb67ffdb1..5ac3af4dc 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/StealthUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/StealthUpdate.cpp@@ -325,8 +325,8 @@ Bool StealthUpdate::allowedToStealth( Object *stealthOwner ) constif( flags & STEALTH_NOT_WHILE_TAKING_DAMAGE && self->getBodyModule()->getLastDamageTimestamp() >= now - 1 ){- //Only if it's not healing damage.- if( self->getBodyModule()->getLastDamageInfo()->in.m_damageType != DAMAGE_HEALING )+ // the healing test that used to sit here is gone: a heal no longer stamps the damage+ // timestamp at all, so getting patched up does not keep a unit visible.{//Can't stealth if we just took damage in the last frame or two.if( self->getBodyModule()->getLastDamageTimestamp() != 0xffffffff )diff --git a/GeneralsMD/Code/GameEngineDevice/Source/Win32Device/Common/Win32BIGFileSystem.cpp b/GeneralsMD/Code/GameEngineDevice/Source/Win32Device/Common/Win32BIGFileSystem.cppindex da2eed559..8181f8d80 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/Win32Device/Common/Win32BIGFileSystem.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/Win32Device/Common/Win32BIGFileSystem.cpp@@ -89,6 +89,10 @@ void Win32BIGFileSystem::init() {// Loaded second on purpose: loadIntoDirectoryTree does not overwrite, so the// Zero Hour bigs already in the tree win over the base game's copies.loadBigFilesFromDirectory(installPath, "*.big");++ // ... except where that costs resolution: a number of the base game's textures were shipped+ // downscaled in TexturesZH.big, and load order alone made those the ones the game uses.+ prioritizeLargerFiles(TGA_DIR_PATH, "TexturesZH.big", "Textures.big");}void Win32BIGFileSystem::reset() {