Skip to content

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

feat(gameengine): observer strips, defence reach shading, jet falls

Olcay Seygan6f92ca56b012
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2146fea32..82d14f4eb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -65,6 +65,8 @@ found and fixed — EA's own, not port damage.**
- Hard picks its road into your base. Of the three approaches it takes the one with the fewest guns it has seen along it, and keeps to the one its plan named until it has scouted something. Aiming at your money instead was tried first and walked it straight past your army.
- Hard sends its attack groups out together. A group too small to be a wave on its own waits on the near side of its base until about seven tanks' worth has gathered, or a minute and a half has passed, and then everything waiting leaves on one road at the pace of its slowest unit. A lone artillery piece or a single bomb truck used to drive across the map by itself, and nearly a third of Hard's units died with barely anyone of their own nearby.
- It puts more harvesters on a supply centre with more piles around it, instead of the same three numbers everywhere.
+- It keeps its lights on, and keeps them out of reach. Its plan carries a fixed number of power plants and nothing ever adds one, so a raid that took two of them left the base underpowered - radar dark, base defences off, superweapon clock stopped - until a rebuild timer came round and put the new plant back on the spot the raid already knew the way to. It now buys a plant when the margin gets thin rather than when the meter reads zero, and puts it on the far side of the base from whoever it is fighting.
+- Spare cash also buys a gun on the side the trouble comes from. Production and income go up around the middle of the base, the power goes behind it, and base defences go out in front, so money that keeps arriving thickens the base in the order a base wants to be thick in. Front means towards the nearest enemy, which is not the same as the one it has decided to attack - that one can be across the map, and a wall built facing it has its back to the neighbour. One gun every minute and a half at most, and it stops at ten of them; a base made of bunkers is a base with no army.
## The computer picks its fights
- Which enemy it goes after was the nearest one and nothing else, plus a rule with its sign the wrong way round: an opponent who had lost his units or his production had his distance treated as half the map, so the computer ignored the one it was about to beat. That is what dragged matches out.
@@ -141,6 +143,7 @@ found and fixed — EA's own, not port damage.**
- G is guard, armed the same way and aimed with the same left button. A left click posts the selection on that spot: they hold it, shoot what walks into range and do not chase it off the post you put them on. The cursor turns into the targeting cross while G is armed, so you can see the key is down before you click, and a right click puts it down again. Drag the left button with G armed (the right one draws nothing while G is down) and they post along the line you draw, one unit per station, which is how a hill or a bridge approach gets covered in one gesture instead of a click per tank. Guard has its own colour, blue, on the line while you draw it and on the thread and marker afterwards, so a group told to hold ground reads apart from one told to walk there. Hold position, which posts every unit on the spot it is already standing on, has moved to H.
- With A armed, hold the left button and drag a circle instead: everything hostile you can see inside it becomes a target list, nearest first, and the selection works down that list on its own. When the current target dies the next order goes out the same frame, so a strike group clears a circle without you clicking once per tank. It moves on from a target the group has stopped working on, too, rather than only from a dead one: something none of them can reach or hurt used to sit at the head of the list and hold every other target behind it for the rest of the match. That list is the same queue a shift-clicked attack builds, so you can see it: every target still owed has its own thread and marker, in the order they will be taken, instead of one line to whatever is being shot at this second. Hold shift while you draw the circle and its targets go on the end of what the group is already working through; draw it without shift and the circle replaces the lot. The ground inside the circle is washed the same red while you drag it, painted on the map rather than over it, so it runs up the hills inside the circle and your own tanks stand on top of it. Any order you give by hand ends the list. Losing a unit does not: the list belongs to the group that was told and carries on with whoever is left, which is worth saying because for a while it did not, and one tank dying threw away every target still owed. A target with enough of your fire already in the air to kill it counts as done, so the rest of the group takes the next thing on the list rather than emptying itself into something that is dead and has not fallen over yet. Aircraft are what this is for: a flight fires from range and the missiles are seconds behind, and four planes used to spend all four loads on the first tank in the circle. Running out of ammo does not cost you the list either. A flight that empties its racks flies home, lands, rearms and comes back to the target it left, and the queue waits for it instead of counting the trip as the group giving up: a circle drawn for four planes used to be empty by the time they were back in the air, one entry lost every two seconds they were away. The threads stay on the ground for the whole trip, too. A plane flying home has no target and no order to read, so the list it was still holding used to vanish off the map the moment it turned for base and reappear only when it was shooting again, which looks exactly like the list being thrown away. What the circle picks up is what you can shoot: a shell or a missile crossing it is on the enemy's side like everything else and used to go on the list as a target, costing the group a two second stall on something that was about to stop existing. A target that has driven into the shroud since you picked it keeps its place in the list but stops drawing its thread, so the line cannot be used to trace it through the fog. An attack-move queued behind other orders keeps the force fire it was given rather than losing it when the attack key drops.
- Shift queues an attack now, not only a move. A or F held down while you shift-click adds a force-attack or an attack-move to the line of orders a group is already holding, and it fires the moment the order in front of it is finished - a target dead, or nobody left chasing an attack-move point. The coloured thread that shows a queued order covers it too, so a queue of "go here, then attack that, then attack-move over there" reads as one continuous line in three colours. The game's own white waypoint markings, which used to draw over the same ground the moment shift went down, are gone - they only ever duplicated what the coloured thread already showed, and doing both left a queued attack sitting under two different pictures of itself.
+- What the circle picks up is what you can see, and a stealthed unit is not that. Shroud was the only test, so a hidden tank parked in ground you had already cleared went on the list like anything else: drag a circle over open country and the group opened fire on air, one order per hidden unit, which is a stealth detector drawn with the mouse. An undetected unit is not in the circle.
- Ctrl+D takes every unit of the kinds you have selected that is on the screen, and pressed twice inside half a second takes them across the whole map. One tank selected and two keystrokes is your whole armour, wherever it is standing. It was on Shift+Ctrl+E, which is three fingers for something you do in every fight, and it only ever reached across the map when the screen had nothing left to give - so the wide selection happened to you instead of being asked for.
## Aircraft, guards, and orders that used to be ignored
@@ -153,6 +156,8 @@ found and fixed — EA's own, not port damage.**
- A guarding unit no longer fights itself between returning to post and shooting back.
- Engineers can clear mines and booby traps they cannot see.
- A helicopter no longer boards a transport from the air.
+- A jet shot down in the air flies on before it falls. Its wings stopped working on the frame it was hit, so it dropped almost vertically and hit the ground under the spot it was killed at, which is the one thing a plane doing three hundred knots cannot do. It keeps its lift now and gives it up over the next second or so, carrying forward and nosing over as it goes.
+- And the bombers come down at all. A B-52, a Spectre gunship, a cargo plane and an A-10 all left the falling speed out of their data, and nought means the lift exactly cancels gravity: shot down, they flew on at cruising height, burning, and blew up in the air still level. Every one of them now falls at half gravity or better, and the fireball waits for the ground instead of going off on a timer somewhere over the map. Measured on the way in: a B-52 falls for 2.8 seconds and lands, where it used to detonate at a hundred feet.
## The same game on both screens, and after loading
@@ -308,6 +313,8 @@ found and fixed — EA's own, not port damage.**
## One crate, one collector
+- Salvage gets collected. A wreck leaves money and a free upgrade lying on the ground, and the game asked you to spot it in the middle of the fight that made it, work out which of your units was allowed to take it, and drive that one over it by hand. Nobody does that, so most salvage on most maps timed out where it fell. Whoever is standing nearest with nothing to do goes and gets it now: a unit that can still be upgraded off it goes first, however far back it is standing, and failing that the nearest idle unit takes the cash. Only idle units, so nothing is ever pulled out of a fight or off an order, and dozers and harvesters are left to the job they are already earning at.
+- And anybody can take the money. A salvage crate could only be picked up by a unit that salvages, so one dropped among troops who could not use it was money that belonged to nobody. The parts still only go to a salvager - the weapon, the armour, the promotion - but the cash goes to whoever drives over it.
- A crate pays once per frame, not once per soldier who touched it.
- A thrown vehicle's crash damage hits the pile once, not once per unit.
- A dying unit is no longer promoted by its last kill.
@@ -384,6 +391,14 @@ found and fixed — EA's own, not port damage.**
- Watching, the bars over the buildings are everyone's too - what each factory is turning out, and how long the superweapons have left. An observer used to see none of it.
- Watching, you see the fog the player you are watching sees. The game only ever remembered one player's fog, so switching seats handed you the first player's idea of the map.
- An ally, and anyone watching, now sees a stealthed unit's muzzle flash, its promotion and the cash it earns - if they can see the unit at all. Those three asked 'is it mine' instead of 'can I see it', so allies and observers got nothing.
+- Watching, the match opens on the middle of the map. An observer has no start position, so the game looked for the camera waypoint of "player zero", did not find it, and fell back to the corner of the map: every match watched from the stands began pointed at empty ground in the south west.
+- Watching, you can click a stealth building. The rule that stops you selecting an enemy you cannot see never asked who was asking, so an observer, and a player already knocked out, could see a stealthed structure on the map and not pick it up to read it. A spectator commands nothing and sees everything already, so there is nothing there to give away.
+- Watching, the promotions every general has bought are on screen the whole match: a strip of them in the bottom right corner, standing on the command bar the way the production rows do on the left, one row per player in his own colour. There was nowhere else to find this out - the promotion screen filled itself in with the watcher's own player, who has no general and no command sets at all, so a spectator got a blank screen.
+- Watching, clicking one player's unit is clicking his name in the player list, and clicking empty ground puts the whole match back. The command bar brings up his readouts and his money and wears his side's metal; the production rows on the left close down to his, and get longer since he has the strip to himself; the promotions on the right are his alone. The tilde key, or the general's stars on the right of the bar, then opens his promotion screen, on his side's artwork, with his skill points and his rank - greyed out, because they are not yours to spend. With nothing selected the key does nothing and the stars are dark; there is no one general to show.
+- A general who has taken Artillery Barrage to level 3 shows one Artillery Barrage on the promotions strip, not three copies of the same picture in a row.
+- The strips close up again: across a row the trays slide an eighth of a tray under each other, so a row reads as one run of metal. The cameos never overlap each other, because every tray goes down before any picture does.
+- Watching, the strips can be switched off. A small "Strips" drop-down in the top left corner opens into three boxes - the production queue, the generals' promotions and the superweapon timers - and each box switches its strip the moment it is clicked and is remembered for the next match you watch. The message list moves down to start under it. Playing, there is no drop-down and every strip is up, whatever you chose in the stands.
+- A minimised command bar stays minimised. Changing seats, or clicking another player's unit while watching, put the whole bar back up over the battlefield you had just cleared. A new match still opens with the bar up.
## Placing buildings
@@ -396,6 +411,8 @@ found and fixed — EA's own, not port damage.**
- A building you point at blocked ground slides to the nearest spot it fits, and lands there.
- The pointer keeps its build cursor while you place, even passing over your own buildings.
- GLA defences get a range ring while you site them.
+- The ground a defence on your cursor can shoot into is painted red. It used to be the thin white guard circle, which read as the edge of a building's footprint more than as a field of fire; now it is the red area the artillery powers aim with, glowing at the edge of the defence's reach, so a Patriot battery's 450 is a red disc you can lay over the approach you are covering.
+- Inside that red area, the ground the defence cannot see is shaded. A Patriot battery, a Gattling Cannon or a Fire Base does not shoot through a building - the game refuses the shot when a solid structure stands between the gun and its target - so from where your cursor is, each building in range throws a shadow that starts at its near wall and runs out to the edge of the reach, a wedge that swings as you move the defence round the corner of your War Factory. Hills count as well. The game will not pick a target when the ground rises between the top of the gun and the top of a tank, so the far side of a ridge goes dark too, and a valley beyond it lights up again where the gun can see down into it. The shade lies on the ground as one piece and follows its slopes. A Stinger Site or a bunker gets no shade, because a building in the way does not stop them.
- Two buildings can no longer be put down on the same spot online. A build order travels to the other players before anything appears on the ground, and every click made while it was in flight was answered by a map that still showed the square as empty - so a shift-held row on a bad connection came out as buildings standing inside each other. The ghost now knows about the orders you have already spent, and turns red over them or slides to the square beside; and the order itself is checked again where it lands, on every machine, after the first building is standing. A second one aimed at the same ground is refused there and costs you nothing.
- The right button drops the building on your cursor whether the click travelled or not. Sending a dozer off somewhere in the middle of a shift-held row moved it and left the ghost riding the cursor, because the cancel only counted a press that had not moved a pixel and a hand on the way to a destination always moves a few.
- A click clears a half-typed building shortcut.
@@ -412,7 +429,7 @@ found and fixed — EA's own, not port damage.**
- A worker fetching or handing over a box shows a bar while it works.
- That bar is now the work itself. A worker used to reset it to empty at the very moment it finished and then walk away, so every trip looked like it left mid-handover; and after taking its last box it stood at the pile for one more full loading cycle, taking nothing. It leaves the instant the load is done - which is a little more money per trip, on every worker you own.
- A worker loads in one go instead of a box at a time. It used to take one, wait a loading cycle, take the next, wait again, and the bar over its head restarted for each of them; now the whole load changes hands once and the wait is that load's worth of time - four boxes cost what four boxes always cost, in one stretch rather than four. Money in the bank is unchanged, which is the point: three headless matches on the same seeds came back within a few percent of what they earned before.
-- Supply points refill themselves, slowly, and faster the more of a base has grown around them. A warehouse used to be a fixed lump of money that ran out and left the map with nothing to fight over: whoever mined out the middle first had the game, and the second half of every match was played on income neither side could earn any more. A box comes back every forty seconds standing on its own, every twenty with one supply centre built near it, every thirteen with two - up to what the point started with, never past it. Both sides expanding onto the same patch make it richer and then have to decide which of them keeps it.
+- Supply points refill themselves, slowly, and faster the more of a base has grown around them. A warehouse used to be a fixed lump of money that ran out and left the map with nothing to fight over: whoever mined out the middle first had the game, and the second half of every match was played on income neither side could earn any more. Six hundred dollars comes back every forty seconds standing on its own, every twenty with one supply centre built near it, every thirteen with two - up to what the point started with, never past it. A single box was too little to be worth the trip: a hundred dollars every forty seconds is less than the harvester earns going to fetch it, so a mined-out point stayed mined out as far as anybody playing was concerned. Both sides expanding onto the same patch make it richer and then have to decide which of them keeps it.
- Workers stop hesitating on their way in and out. A dock has a queue outside it and a worker treated its place in that queue as a destination: it drove to the spot, stopped dead, waited a frame, drove to the door, stopped again, and only then went in - twice a load, and nearly every load with nothing else queued. With the dock empty it drives straight in. The first version of that also skipped the walk to a supply pile or a GLA stash, which have no door of their own, so a worker a long way off played its loading animation where it stood and was paid anyway. In a four-player test match 72 loads were picked up or dropped off away from the dock, one of them 613 feet from it; now there are none.
- Hackers show how far off the next payout is. So do the black market and the oil derricks.
- A hacker working from inside an Internet Center shows what it earns. The green figure floats over the building on every payout, the way it does over one sitting in the field. It never appeared, because the game asked the hacker whether it could be seen and a garrisoned unit is not drawn at all - which is the one place a hacker is meant to work.
@@ -434,6 +451,7 @@ found and fixed — EA's own, not port damage.**
- A building's bar sits above its roof rather than inside its art.
- A unit that is inside a transport and also disabled wears the blue bar. Being carried and being knocked out were asked as one question, so the two together answered no: a squad EMP'd inside a bunker, or hacked while riding a Battle Bus, looked perfectly healthy from outside.
- The progress bar stacked over the health bar is white, wherever it turns up - a factory turning out a tank, a silo charging, a supply drop counting down to its payout. It was yellow, which is a colour the game already spends on your own units and on damage, and a strip of it sitting directly above a coloured health bar read as part of the same bar.
+- A building being captured wears a capture clock under its health bar, filling in the colour of whoever is taking it. The building flashes while a rifleman works on it, which says somebody is at the door and nothing about whether that is nearly over: the choice between driving across to shoot him and carrying on with your fight was made blind. The bar runs from the moment he reaches the door to the moment the building changes hands, and Black Lotus hacking one gets the same bar.
- Every garrisonable building shows how full it is, whoever holds it.
- A vehicle's load stays private.
- What you have selected wears a white frame just outside its bar, so a selection is still readable in a crowd where every unit carries a bar - and the bar itself keeps its owner colour all the way round.
@@ -505,6 +523,12 @@ found and fixed — EA's own, not port damage.**
- The mouse wheel no longer cancels a camera move already in progress.
## Peace time, if the host wants it
+## The buildings nobody repairs, repair themselves
+
+- Civilian buildings and tech buildings patch their own walls. Nobody else was ever going to: a neutral building is on no player's build list, a captured one is not on its captor's either, and no dozer in the game will touch either of them. So the first squad to be burned out of a hospital left it a wreck for the rest of the match, and an oil derrick that changed hands four times spent the game at a tenth of its health.
+- Two seconds without taking a hit and the building starts mending, three percent of its full health a second, until it is whole or somebody shoots it again. It makes no difference whether it is standing empty, holding somebody's riflemen or flying somebody's flag.
+- Your own buildings are not in this. A command center is a faction structure with a dozer of its own, and it repairs the way it always did.
+
- A new lobby setting next to starting cash: three, five, ten or fifteen minutes of truce at the head of the match, or none, which is how the game has always played. LAN and online carry it, only the host can change it, and everyone in the room sees the choice before the game starts.
- While it runs, nobody can attack anybody. Not a rush, not a scout taking a pot shot on the way past, not a shell fired at empty ground in the hope the splash counts.
@@ -693,6 +717,7 @@ found and fixed — EA's own, not port damage.**
- `UseShadowVolumesForSkins = No` puts the old flat blobs back.
- Scuds, rockets and falling bombs cast a shadow running along the ground.
- A big smoke cloud darkens the ground under it and fades as it does.
+- An aircraft's shadow lands where the sun puts it, not underneath the aircraft. Every plane and helicopter in the game's own data asks for a sun "no lower than 89 degrees", so each one cast its shadow straight down and towed it along directly below itself at any height, while the tank beside it was lit by the map's real sun and threw its shadow off to the side. Aircraft now take the same sun as everything else: a helicopter's shadow slides out from under it as it climbs, and a plane's runs ahead of or behind it depending on the hour the map is set at. On a map lit by a very low sun the shadow is held to what a 30 degree sun would cast, so it does not stretch across half the screen. The flat blob shadows under missiles and bombs follow the same ray.
- The soft blob shadow for trees and scenery had never been drawn at all.
- Every one of the 128 tree types casts now, plus the bushes and palms.
- A tree's shadow is the tree. Trunk, crown, and the gaps between the leaves, lying along the
diff --git a/GeneralsMD/Code/Data/Patch.str b/GeneralsMD/Code/Data/Patch.str
index 33394cb6b..15768e366 100644
--- a/GeneralsMD/Code/Data/Patch.str
+++ b/GeneralsMD/Code/Data/Patch.str
@@ -1004,3 +1004,20 @@ END
GUI:CantBuildTooManyDerrickDefenses
"You already have two defenses round these oil derricks."
END
+
+// the drop-down in the top left corner of a match that switches the strips on and off
+GUI:HudToggles
+"Strips"
+END
+
+GUI:HudProductionStrip
+"Production queue"
+END
+
+GUI:HudSkillStrip
+"Generals' promotions"
+END
+
+GUI:HudSuperweaponStrip
+"Superweapon timers"
+END
diff --git a/GeneralsMD/Code/Data/Turkish/Generals.str b/GeneralsMD/Code/Data/Turkish/Generals.str
index f57dc4528..2b67b6d2d 100644
--- a/GeneralsMD/Code/Data/Turkish/Generals.str
+++ b/GeneralsMD/Code/Data/Turkish/Generals.str
@@ -15536,3 +15536,19 @@ END
TOOLTIP:WeaponStats
"Hasar %d Menzil %d"
END
+
+GUI:HudToggles
+"Şeritler"
+END
+
+GUI:HudProductionStrip
+"Üretim sırası"
+END
+
+GUI:HudSkillStrip
+"General yetenekleri"
+END
+
+GUI:HudSuperweaponStrip
+"Süper silah sayaçları"
+END
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h
index 6e067b49a..5a81e55b1 100644
--- a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h
+++ b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h
@@ -400,6 +400,9 @@ public:
Bool m_showPlacementRangeRing; ///< while placing a structure, ring its weapon range
Bool m_workersReturnToSupply; ///< a worker that finishes a build job goes back to the dock it left
Bool m_detailedBuildTooltips; ///< put build time, weapon range and damage in the build tooltip
+ Bool m_showProductionStrip; ///< the production queue rows above the command bar, bottom left
+ Bool m_showSkillStrip; ///< watching, every general's bought promotions, bottom right
+ Bool m_showSuperweaponStrip; ///< the superweapon countdown cameos, top right
Bool m_archiveReplays; ///< keep a timestamped copy of every replay, instead of only the last one
Int m_bloomIntensity; ///< bloom strength in percent, 0 = off
Int m_bloomThreshold; ///< brightness in percent below which nothing blooms
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/Science.h b/GeneralsMD/Code/GameEngine/Include/Common/Science.h
index 445995a5f..70db4fd8d 100644
--- a/GeneralsMD/Code/GameEngine/Include/Common/Science.h
+++ b/GeneralsMD/Code/GameEngine/Include/Common/Science.h
@@ -106,6 +106,9 @@ public:
Int getSciencePurchaseCost(ScienceType science) const;
+ /// does st name prereq among its own prerequisites (one level, not the whole chain)
+ Bool isDirectPrereq(ScienceType prereq, ScienceType st) const;
+
ScienceType getScienceFromInternalName(const AsciiString& name) const;
AsciiString getInternalNameForScience(ScienceType science) const;
diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/ControlBar.h b/GeneralsMD/Code/GameEngine/Include/GameClient/ControlBar.h
index cb5962d87..73b31760f 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameClient/ControlBar.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/ControlBar.h
@@ -788,6 +788,19 @@ public:
/// find existing command set
const CommandSet *findCommandSet( const AsciiString& name );
+ /// whose promotion screen and skills are shown: your own while playing, the selected or
+ /// observed player's while watching
+ Player *getWatchedPlayer( void );
+
+ /// watching, the player whose thing is selected; NULL for nothing selected, which is the
+ /// whole-match view
+ Player *getSelectedPlayer( void );
+
+ /// watching, follow the selection: the player's readouts, his money and his side's metal
+ void updateWatchedPlayer( void );
+ void showObserverPlayerInfo( void ); ///< his readouts up, the player list down
+ void showObserverPlayerList( void ); ///< and back again
+
void showPurchaseScience( void );
void hidePurchaseScience( void );
void togglePurchaseScience( void );
@@ -838,6 +851,7 @@ public:
// Functions for repositioning/resizing the control bar
void switchControlBarStage( ControlBarStages stage );
+ void restoreStageAfterScheme( void ); ///< a new scheme keeps a minimised bar minimised
void toggleControlBarStage( void );
const Image *getStarImage( void );
@@ -1267,6 +1281,8 @@ protected:
Bool m_isObserverCommandBar; ///< If this is true, the command bar behaves greatly differnt
Player *m_observerLookAtPlayer; ///< The current player we're looking at, Null if we're not looking at anyone.
+ AsciiString m_watchedSide; ///< the side the bar is wearing while watching, so a selection change only lays it out again when it really changes side
+ Player *m_watchedSelection; ///< the player the selection last named while watching, NULL for nobody
WindowLayout *m_buildToolTipLayout; ///< The window that will slide on/display tooltips
Bool m_showBuildToolTipLayout; ///< every frame we test to see if we aregoing to continue showing this or not.
diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/Drawable.h b/GeneralsMD/Code/GameEngine/Include/GameClient/Drawable.h
index 6ffd68bf9..fa718eafd 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameClient/Drawable.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/Drawable.h
@@ -781,6 +781,7 @@ private:
void drawEmoticon( const IRegion2D* healthBarRegion );
void drawHealthBar( const IRegion2D* healthBarRegion ); ///< draw heath bar
+ void drawCaptureProgress( void ); ///< the clock under the health bar of the building this one is taking
void drawHealing( const IRegion2D* healthBarRegion ); ///< draw icons
void drawEnthusiastic( const IRegion2D* healthBarRegin ); ///< draw icons
#ifdef ALLOW_DEMORALIZE
diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/InGameUI.h b/GeneralsMD/Code/GameEngine/Include/GameClient/InGameUI.h
index 8e208ee99..a67b06a6c 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameClient/InGameUI.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/InGameUI.h
@@ -777,6 +777,11 @@ public: // ********************************************************************
enum { SUPERWEAPON_STRIP_COLS = 6 }; ///< cameos in one row, the soonest at the right hand end
enum { SUPERWEAPON_STRIP_ROWS = 3 }; ///< rows of them, and the rest become a "+N"
enum { SUPERWEAPON_STRIP_MAX = SUPERWEAPON_STRIP_COLS * SUPERWEAPON_STRIP_ROWS };
+
+ enum { SKILL_STRIP_COLS = 6 }; ///< bought promotions in one row, under the countdowns
+ enum { SKILL_STRIP_ROWS = 8 }; ///< a row per player watching the whole match, or one
+ /// player's promotions wrapped over as many as they need
+ enum { SKILL_STRIP_MAX = SKILL_STRIP_COLS * SKILL_STRIP_ROWS };
struct SuperweaponIconSlot
{
const Image * image; ///< the cameo the command bar wears for this power
@@ -1157,9 +1162,24 @@ protected:
void drawStripQuantity( Int which, Int x, Int y, Int w, Int quantity ); ///< the "xN" in a cameo's top right corner
void addSuperweaponIcon( const Image *image, Int seconds, Int percent, Bool ready, Color color );
void drawSuperweaponStrip( void ); ///< those icons, top right, soonest at the right hand end
+ void drawSkillStrip( void ); ///< the watched player's bought promotions, under those
+
+ //
+ // The drop-down in the top left corner that switches the strips on and off. Row 0 is its header,
+ // the rest are one check box each.
+ //
+ enum { HUD_TOGGLE_ROWS = 4 };
+ void drawHudToggles( void );
+ Bool handleHudTogglesClick( const ICoord2D *mouse, Bool act ); ///< TRUE when the click landed on it
+ Bool m_hudTogglesOpen;
+ Int m_hudToggleRowsShown; ///< rows drawn this frame, header included
+ Int m_hudTogglesBottom; ///< its bottom edge, so the message list starts under it
+ IRegion2D m_hudToggleRects[ HUD_TOGGLE_ROWS ];
+ DisplayString * m_hudToggleStrings[ HUD_TOGGLE_ROWS ];
Bool m_placementRangeRingUp; ///< we put a radius cursor up for a pending structure, so we owe a clear
Real m_placementRingRadius; ///< the radius that ring was built at, so it is not rebuilt every frame
+ void drawPlacementBlindSpots( void ); ///< shade the ground behind buildings a placed defence cannot shoot past
DisplayString * m_hudDisplayString; ///< the ShowHudOverlay line (fps / clock)
DisplayString * m_peaceTimeDisplayString; ///< the peace time clock at the top of the screen
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h
index afdf05b1f..1ea6946db 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h
@@ -311,6 +311,13 @@ protected:
* expansion when every one of a kind is busy, another income building when production keeps up,
* and money units (China's hackers) from any factory standing idle. */
virtual void doEconomy(void);
+
+ /** Buy a power plant before the margin runs out rather than after, and put it on the far side of
+ * the base from whoever this player is fighting. */
+ virtual void doPower(void);
+
+ Bool enemyDirection(Coord3D *dir); ///< unit vector from this base towards the nearest enemy's best known address
+
void buyMoneyUnit(void);
Bool placeNear(const ThingTemplate *tmpl, const Coord3D *center, Real innerRadius); ///< a legal, safe spot on a ring round center, queued for a dozer
Real knownFirepowerAlongPath(Waypoint *way); ///< what this AI has seen that can shoot, along an approach
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/JetSlowDeathBehavior.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/JetSlowDeathBehavior.h
index be354f8cd..547191f1d 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/JetSlowDeathBehavior.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/JetSlowDeathBehavior.h
@@ -99,6 +99,7 @@ protected:
UnsignedInt m_timerDeathFrame; ///< fame we died on
UnsignedInt m_timerOnGroundFrame; ///< frame we landed on the ground on
+ UnsignedInt m_fallDeadlineFrame; ///< how long the fall may hold the explosion back for
Real m_rollRate; ///< our roll rate
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/SlowDeathBehavior.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/SlowDeathBehavior.h
index d39fd21fc..fa83c4617 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/SlowDeathBehavior.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/SlowDeathBehavior.h
@@ -161,6 +161,10 @@ protected:
inline Bool isSlowDeathActivated() const { return (m_flags & (1<<SLOW_DEATH_ACTIVATED)) != 0; }
inline UnsignedInt getDestructionFrame() const { return m_destructionFrame; }
+ /** Move the moment of destruction, for a subclass whose death ends somewhere rather than at a
+ * time - an aircraft's ends at the ground. */
+ inline void setDestructionFrame(UnsignedInt frame) { m_destructionFrame = frame; }
+
private:
enum
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/SpecialAbilityUpdate.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/SpecialAbilityUpdate.h
index ea8c6690d..6a542a05e 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/SpecialAbilityUpdate.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/SpecialAbilityUpdate.h
@@ -213,6 +213,7 @@ public:
virtual Bool doesSpecialPowerHaveOverridableDestination() const { return false; } //Does it have it, even if it's not active?
virtual void setSpecialPowerOverridableDestination( const Coord3D *loc ) {}
virtual Bool isPowerCurrentlyInUse( const CommandButton *command = NULL ) const;
+ virtual Bool getCaptureProgress( ObjectID *targetID, Real *progress ) const;
// virtual Bool isBusy() const { return m_isBusy; }
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/SpecialPowerUpdateModule.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/SpecialPowerUpdateModule.h
index f129933cd..4bfff1325 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/SpecialPowerUpdateModule.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/SpecialPowerUpdateModule.h
@@ -51,6 +51,11 @@ public:
virtual Bool doesSpecialPowerHaveOverridableDestination() const = 0; //Does it have it, even if it's not active?
virtual void setSpecialPowerOverridableDestination( const Coord3D *loc ) = 0;
virtual Bool isPowerCurrentlyInUse( const CommandButton *command = NULL ) const = 0;
+
+ /** While this module is in the middle of taking a building: which building, and how far through
+ * it is, nought to one. Asked by the client so the building can wear a clock. Not pure, because
+ * taking a building is one ability out of dozens and the rest have no answer to give. */
+ virtual Bool getCaptureProgress( ObjectID *targetID, Real *progress ) const { return FALSE; }
};
//-------------------------------------------------------------------------------------------------
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Object.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Object.h
index 7de6cb1c9..93582533e 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Object.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Object.h
@@ -360,6 +360,7 @@ public:
SpecialPowerModuleInterface* findAnyShortcutSpecialPowerModuleInterface() const;
SpecialAbilityUpdate* findSpecialAbilityUpdate( SpecialPowerType type ) const;
SpecialPowerCompletionDie* findSpecialPowerCompletionDie() const;
+ Bool getCaptureProgress( ObjectID *targetID, Real *progress ) const; ///< the building this one is taking, and how far through it is
SpecialPowerUpdateInterface* findSpecialPowerWithOverridableDestinationActive( SpecialPowerType type = SPECIAL_INVALID ) const;
SpecialPowerUpdateInterface* findSpecialPowerWithOverridableDestination( SpecialPowerType type = SPECIAL_INVALID ) const;
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp
index 4b564bacd..89b58343c 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp
@@ -1123,6 +1123,9 @@ GlobalData::GlobalData()
m_showPlacementRangeRing = TRUE;
m_workersReturnToSupply = TRUE;
m_detailedBuildTooltips = TRUE;
+ m_showProductionStrip = TRUE;
+ m_showSkillStrip = TRUE;
+ m_showSuperweaponStrip = TRUE;
m_archiveReplays = TRUE;
// Bloom is the one that does NOT default on: it changes how the game looks rather than what it
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/OptionsCatalog.cpp b/GeneralsMD/Code/GameEngine/Source/Common/OptionsCatalog.cpp
index 9ce3f5267..b9f384e59 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/OptionsCatalog.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/OptionsCatalog.cpp
@@ -78,6 +78,9 @@ OPTION_BOOL_ACCESSORS( m_shadowsForProps )
OPTION_BOOL_ACCESSORS( m_shadowsForParticles )
OPTION_BOOL_ACCESSORS( m_particleGroundBounce )
+OPTION_BOOL_ACCESSORS( m_showProductionStrip )
+OPTION_BOOL_ACCESSORS( m_showSkillStrip )
+OPTION_BOOL_ACCESSORS( m_showSuperweaponStrip )
//-----------------------------------------------------------------------------
static const unsigned TheMsaaSamples[ OPTION_MSAA_LEVEL_COUNT ] = { 0, 2, 4, 8, 16 };
@@ -375,6 +378,21 @@ const Int TheOptionCatalogCount = (sizeof( TheOptionCatalog ) / sizeof( TheOptio
//-----------------------------------------------------------------------------
const OptionDef *findOptionDef( const char *iniKey )
{
+ // The strips over the battlefield while watching a match. They have no control in the options
+ // menu: a spectator switches them from the drop-down in the top left corner, which writes them
+ // back itself. Playing, every strip is drawn whatever these say.
+ { "ShowProductionStrip", NULL, "GUI:HudProductionStrip",
+ OPTION_BOOL, APPLY_LIVE, 0, 1,
+ get_m_showProductionStrip, set_m_showProductionStrip },
+
+ { "ShowSkillStrip", NULL, "GUI:HudSkillStrip",
+ OPTION_BOOL, APPLY_LIVE, 0, 1,
+ get_m_showSkillStrip, set_m_showSkillStrip },
+
+ { "ShowSuperweaponStrip", NULL, "GUI:HudSuperweaponStrip",
+ OPTION_BOOL, APPLY_LIVE, 0, 1,
+ get_m_showSuperweaponStrip, set_m_showSuperweaponStrip },
+
for( Int i = 0; i < TheOptionCatalogCount; ++i )
if( stricmp( TheOptionCatalog[ i ].iniKey, iniKey ) == 0 )
return &TheOptionCatalog[ i ];
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Science.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Science.cpp
index 084275c9c..cb9eb08bf 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Science.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Science.cpp
@@ -33,6 +33,8 @@
#include "Common/Player.h"
#include "Common/Science.h"
+#include <algorithm>
+
ScienceStore* TheScienceStore = NULL;
#ifdef _INTERNAL
@@ -247,6 +249,17 @@ Int ScienceStore::getSciencePurchaseCost(ScienceType st) const
}
}
+//-----------------------------------------------------------------------------
+/** Does st ask for prereq directly - the way Artillery Barrage 2 asks for Artillery Barrage 1? */
+Bool ScienceStore::isDirectPrereq(ScienceType prereq, ScienceType st) const
+{
+ const ScienceInfo* si = findScienceInfo(st);
+ if (si == NULL)
+ return false;
+
+ return std::find(si->m_prereqSciences.begin(), si->m_prereqSciences.end(), prereq) != si->m_prereqSciences.end();
+}
+
//-----------------------------------------------------------------------------
Bool ScienceStore::isScienceGrantable(ScienceType st) const
{
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp
index a382eb555..685950256 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp
@@ -2978,6 +2978,7 @@ void Drawable::drawIconUI( void )
return;
drawHealing( healthBarRegion );//call so dead things can kill their healing icons
drawBombed( healthBarRegion );
+ drawCaptureProgress();
//Disabled for multiplay!
@@ -4118,6 +4119,60 @@ void Drawable::drawVeterancy( const IRegion2D *healthBarRegion )
} // end drawVeterancy
+// ------------------------------------------------------------------------------------------------
+/** The capture clock, drawn under the health bar of the building being taken.
+ *
+ * A capture is a man standing at a door for several seconds and a building that flashes while it
+ * happens. The flash says somebody is taking it; it does not say whether that is nearly over or
+ * barely started, so the choice between driving over to shoot him and carrying on with the fight
+ * was made blind. The bar says how long is left.
+ *
+ * Drawn by the man rather than by the building, because he is the one who knows: a building being
+ * captured is told nothing about it until it changes hands. So this runs in the captor's icon
+ * pass and puts its rectangle under the target's health bar, in the capturing player's colour -
+ * whose capture it is, is the other half of the question.
+ */
+// ------------------------------------------------------------------------------------------------
+void Drawable::drawCaptureProgress( void )
+{
+ const Object *obj = getObject();
+ if( obj == NULL || !obj->isKindOf( KINDOF_INFANTRY ) )
+ return;
+
+ ObjectID targetID = INVALID_ID;
+ Real progress = 0.0f;
+ if( !obj->getCaptureProgress( &targetID, &progress ) )
+ return;
+
+ const Object *target = TheGameLogic->findObjectByID( targetID );
+ const Drawable *targetDraw = target ? target->getDrawable() : NULL;
+ if( targetDraw == NULL )
+ return;
+
+ IRegion2D healthBarRegion;
+ if( !computeHealthRegion( targetDraw, healthBarRegion ) )
+ return;
+
+ const Real barWidth = healthBarRegion.hi.x - healthBarRegion.lo.x;
+ const Real barHeight = max( 3, healthBarRegion.hi.y - healthBarRegion.lo.y );
+ const Real barTop = healthBarRegion.hi.y + 2; // clear of the health bar, and of its outline
+
+ Color fillColor = GameMakeColor( 255, 255, 255, 255 );
+ const Player *owner = obj->getControllingPlayer();
+ if( owner != NULL && owner->getPlayerColor() != 0 )
+ {
+ UnsignedByte r, g, b, a;
+ GameGetColorComponents( clientPlayerColor( owner ), &r, &g, &b, &a );
+ fillColor = GameMakeColor( r, g, b, 255 );
+ }
+
+ TheDisplay->drawOpenRect( healthBarRegion.lo.x, barTop, barWidth, barHeight,
+ 1.0f, GameDarkenColor( fillColor, 60 ) );
+ TheDisplay->drawFillRect( healthBarRegion.lo.x + 1, barTop + 1,
+ (barWidth - 2) * progress, barHeight - 2, fillColor );
+
+} // end drawCaptureProgress
+
// ------------------------------------------------------------------------------------------------
/** Draw health bar information for drawable */
// ------------------------------------------------------------------------------------------------
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp
index b17fa2fea..d8aa94a23 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp
@@ -374,6 +374,100 @@ void ControlBar::markUIDirty( void )
}
+//-------------------------------------------------------------------------------------------------
+/** Whose promotion screen is being shown. Playing, it is your own and nothing else.
+ *
+ * Watching - an observer, or a player knocked out who stayed to watch - the screen used to be
+ * populated with the watcher's own player, who owns no command sets at all, so the whole screen
+ * came up blank. It follows the field instead: whatever is selected names its owner, and with
+ * nothing selected it is the player the observer list is pointed at, or the first side still in
+ * the match. */
+//-------------------------------------------------------------------------------------------------
+/** The player a watcher has picked out by clicking one of his things, NULL when nothing is
+ * selected or the selection belongs to nobody who is still playing. It is what narrows the
+ * whole screen to one player: the production rows on the left, the skills on the right, the
+ * side the bar wears and whose promotion screen the key opens. */
+Player *ControlBar::getSelectedPlayer( void )
+{
+ if( ThePlayerList->getLocalPlayer()->isPlayerActive() )
+ return NULL;
+
+ const DrawableList *selection = TheInGameUI->getAllSelectedDrawables();
+ if( selection == NULL || selection->empty() )
+ return NULL;
+
+ Object *selected = selection->front()->getObject();
+ Player *owner = selected ? selected->getControllingPlayer() : NULL;
+ if( owner == NULL || !owner->isPlayableSide() || !owner->isPlayerActive() )
+ return NULL;
+
+ return owner;
+}
+
+//-------------------------------------------------------------------------------------------------
+/** Watching, the selection drives the whole bar: clicking a unit is clicking its owner in the
+ * player list. His readouts come up, the money plate becomes his, and the bar wears his side's
+ * metal - and clicking empty ground puts the list and the watcher's own plain bar back.
+ *
+ * Before this, picking up somebody's tank told you nothing about him: the bar stayed on whatever
+ * side had last been chosen off the list, and the money plate with it. */
+//-------------------------------------------------------------------------------------------------
+void ControlBar::updateWatchedPlayer( void )
+{
+ Player *selected = getSelectedPlayer();
+ if( selected == m_watchedSelection )
+ return;
+
+ m_watchedSelection = selected;
+ setObserverLookAtPlayer( selected );
+
+ if( selected )
+ showObserverPlayerInfo();
+ else
+ showObserverPlayerList();
+
+ const PlayerTemplate *wear = selected ? selected->getPlayerTemplate()
+ : ThePlayerList->getLocalPlayer()->getPlayerTemplate();
+ if( m_controlBarSchemeManager && wear && wear->getSide().compare( m_watchedSide ) != 0 )
+ {
+ // a scheme lays the whole bar out again, so it is set when the side really changes and not
+ // on every click
+ m_watchedSide = wear->getSide();
+ m_controlBarSchemeManager->setControlBarSchemeByPlayerTemplate( wear );
+ restoreStageAfterScheme();
+ }
+
+ // the general's stars open the promotion screen of the player who is selected, and there is
+ // nobody's to open with nothing selected
+ static NameKeyType buttonGeneralID = NAMEKEY( "ControlBar.wnd:ButtonGeneral" );
+ GameWindow *buttonGeneral = TheWindowManager->winGetWindowFromId( NULL, buttonGeneralID );
+ if( buttonGeneral )
+ buttonGeneral->winEnable( selected != NULL );
+}
+
+Player *ControlBar::getWatchedPlayer( void )
+{
+ Player *local = ThePlayerList->getLocalPlayer();
+ if( local->isPlayerActive() )
+ return local;
+
+ Player *selected = getSelectedPlayer();
+ if( selected )
+ return selected;
+
+ if( m_observerLookAtPlayer )
+ return m_observerLookAtPlayer;
+
+ for( Int i = 0; i < ThePlayerList->getPlayerCount(); i++ )
+ {
+ Player *candidate = ThePlayerList->getNthPlayer( i );
+ if( candidate != local && candidate->isPlayerActive() && candidate->isPlayableSide() )
+ return candidate;
+ }
+
+ return local;
+}
+
void ControlBar::populatePurchaseScience( Player* player )
{
// TheInGameUI->deselectAllDrawables();
@@ -590,6 +684,19 @@ void ControlBar::populatePurchaseScience( Player* player )
} // end for
+ //
+ // Somebody else's screen is a read-out, not a shop: a watcher sees what that general has bought
+ // and what is still open to him, and cannot press any of it.
+ //
+ if( player != ThePlayerList->getLocalPlayer() )
+ {
+ for( i = 0; i < MAX_PURCHASE_SCIENCE_RANK_1; i++ )
+ m_sciencePurchaseWindowsRank1[ i ]->winEnable( FALSE );
+ for( i = 0; i < MAX_PURCHASE_SCIENCE_RANK_3; i++ )
+ m_sciencePurchaseWindowsRank3[ i ]->winEnable( FALSE );
+ for( i = 0; i < MAX_PURCHASE_SCIENCE_RANK_8; i++ )
+ m_sciencePurchaseWindowsRank8[ i ]->winEnable( FALSE );
+ }
GameWindow *win = NULL;
UnicodeString tempUS;
@@ -670,7 +777,7 @@ void ControlBar::populatePurchaseScience( Player* player )
void ControlBar::updateContextPurchaseScience( void )
{
GameWindow *win =NULL;
- Player *player = ThePlayerList->getLocalPlayer();
+ Player *player = getWatchedPlayer();
// hash the name once, not on every render frame this panel is open
static const NameKeyType key_progressBarExperience = TheNameKeyGenerator->nameToKey( "GeneralsExpPoints.wnd:ProgressBarExperience" );
win = TheWindowManager->winGetWindowFromId( m_contextParent[ CP_PURCHASE_SCIENCE ], key_progressBarExperience );
@@ -1084,6 +1191,9 @@ ControlBar::ControlBar( void )
m_controlBarSchemeManager = NULL;
m_isObserverCommandBar = FALSE;
m_observerLookAtPlayer = NULL;
+ m_watchedSide.clear();
+ m_watchedSelection = NULL;
+ m_currentControlBarStage = CONTROL_BAR_STAGE_DEFAULT;
m_buildToolTipLayout = NULL;
m_showBuildToolTipLayout = FALSE;
@@ -2726,6 +2836,9 @@ void ControlBar::reset( void )
m_isObserverCommandBar = FALSE; // reset us to use a normal command bar
m_observerLookAtPlayer = NULL;
+ m_watchedSide.clear();
+ m_watchedSelection = NULL;
+ m_currentControlBarStage = CONTROL_BAR_STAGE_DEFAULT; // a minimised bar is this match's, not the next one's
// the next match has its own sides, and a mod switch reloads the artwork these point at
m_borrowedTrayCount = 0;
@@ -2933,6 +3046,9 @@ void ControlBar::update( void )
// if we're an observer, don't do the complete update
if( m_isObserverCommandBar)
{
+ // clicking a unit is clicking its owner in the player list: his readouts, his money, his side
+ updateWatchedPlayer();
+
// twice a second is plenty for the observer readouts, and only on a real logic tick -
// a bare "frame % n == 0" fires on every render frame that lands inside that one tick
if( logicTick && (logicNow % (LOGICFRAMES_PER_SECOND/2)) == 0 )
@@ -3276,10 +3392,10 @@ void ControlBar::evaluateContextUI( void )
// information to the player
//
m_UIDirty = FALSE;
-
+
// if our purchase science window is up, we will want to update it by repopulating it.
if( isPurchaseScienceVisible() )
- populatePurchaseScience( ThePlayerList->getLocalPlayer() );
+ populatePurchaseScience( getWatchedPlayer() );
// erase any current state of the GUI by switching out to the empty context
switchToContext( CB_CONTEXT_NONE, NULL );
@@ -5062,7 +5178,19 @@ void ControlBar::setControlBarSchemeByPlayer(Player *p)
buttonGeneral->winEnable(TRUE);
}
}
- switchControlBarStage(CONTROL_BAR_STAGE_DEFAULT);
+ restoreStageAfterScheme();
+}
+
+//-------------------------------------------------------------------------------------------------
+/** A scheme change lays the bar out again at full size. A bar the player minimised stays that way:
+ * switching seats, or clicking another player's unit while watching, used to throw the whole bar
+ * back up over the battlefield the player had just cleared it off. A new match starts at full
+ * size because reset() puts the stage back first. */
+//-------------------------------------------------------------------------------------------------
+void ControlBar::restoreStageAfterScheme( void )
+{
+ switchControlBarStage( m_currentControlBarStage == CONTROL_BAR_STAGE_LOW ? CONTROL_BAR_STAGE_LOW
+ : CONTROL_BAR_STAGE_DEFAULT );
}
void ControlBar::setControlBarSchemeByPlayerTemplate( const PlayerTemplate *pt)
@@ -5107,7 +5235,7 @@ void ControlBar::setControlBarSchemeByPlayerTemplate( const PlayerTemplate *pt)
buttonGeneral->winEnable(TRUE);
}
}
- switchControlBarStage(CONTROL_BAR_STAGE_DEFAULT);
+ restoreStageAfterScheme();
hidePurchaseScience();
}
@@ -5217,7 +5345,19 @@ void ControlBar::showPurchaseScience( void )
if(TheScriptEngine->isGameEnding())
return;
- populatePurchaseScience(ThePlayerList->getLocalPlayer());
+
+ //
+ // Watching, the screen is one player's in particular and the selection is what names him. With
+ // nothing selected there is nobody to open it on, so the key does nothing rather than putting up
+ // a general the watcher did not ask for. The painting behind it is his side's, which is the
+ // same scheme the bar is already wearing by then - evaluateContextUI put it on when he was
+ // selected.
+ //
+ Player *watched = getWatchedPlayer();
+ if( watched != ThePlayerList->getLocalPlayer() && getSelectedPlayer() == NULL )
+ return;
+
+ populatePurchaseScience(watched);
m_genStarFlash = FALSE;
if( m_purchaseScienceOpen )
return;
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarObserver.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarObserver.cpp
index 12bb49255..5e1730450 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarObserver.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarObserver.cpp
@@ -299,6 +299,33 @@ void ControlBar::populateObserverList( void )
}
}
+//-------------------------------------------------------------------------------------------------
+/** Put up the readouts of the player the bar is looking at, and take the list down - what pressing
+ * his button in the list does, reached from the selection as well. */
+//-------------------------------------------------------------------------------------------------
+void ControlBar::showObserverPlayerInfo( void )
+{
+ if( ObserverPlayerInfoWindow == NULL || ObserverPlayerListWindow == NULL )
+ return;
+
+ ObserverPlayerInfoWindow->winHide( FALSE );
+ ObserverPlayerListWindow->winHide( TRUE );
+ populateObserverInfoWindow();
+}
+
+//-------------------------------------------------------------------------------------------------
+/** ... and back to the list of everybody, which is what the cancel button does. */
+//-------------------------------------------------------------------------------------------------
+void ControlBar::showObserverPlayerList( void )
+{
+ if( ObserverPlayerInfoWindow == NULL || ObserverPlayerListWindow == NULL )
+ return;
+
+ ObserverPlayerInfoWindow->winHide( TRUE );
+ ObserverPlayerListWindow->winHide( FALSE );
+ populateObserverList();
+}
+
void ControlBar::populateObserverInfoWindow ( void )
{
if(ObserverPlayerInfoWindow->winIsHidden())
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp
index 520904119..a895edd1c 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp
@@ -39,6 +39,8 @@
#include "Common/MessageStream.h"
#include "Common/PerfTimer.h"
#include "Common/Player.h"
+#include "Common/PlayerTemplate.h"
+#include "Common/Science.h"
#include "Common/Upgrade.h"
#include "Common/PlayerList.h"
#include "Common/Radar.h"
@@ -56,6 +58,7 @@
#include "GameClient/Diplomacy.h"
#include "GameClient/Eva.h"
#include "GameClient/GameText.h"
+#include "Common/UserPreferences.h"
#include "GameClient/GameWindowManager.h"
#include "GameClient/Drawable.h"
#include "GameClient/GadgetPushButton.h"
@@ -82,6 +85,7 @@
#include "GameNetwork/NetworkInterface.h"
+#include "GameLogic/AI.h"
#include "GameLogic/AIGuard.h"
#include "GameLogic/AIPathfind.h"
#include "GameLogic/AIStateMachine.h"
@@ -138,9 +142,16 @@ enum
PRODUCTION_STRIP_LEFT = 8, ///< inset from the left edge of the screen
PRODUCTION_STRIP_LIFT = 24, ///< clearance above the control bar
PRODUCTION_STRIP_MORE = 18, ///< width kept for the "+N" that closes an overflowing row
- PRODUCTION_STRIP_SECS = 7 ///< point size of the countdown written inside a cameo
+ PRODUCTION_STRIP_SECS = 7, ///< point size of the countdown written inside a cameo
+
+ STRIP_TRAY_OVERLAP_PARTS = 8, ///< a strip's trays close up by one part in this many of a tray
+
+ BLIND_SPOT_RAYS = 180 ///< rays round a placed defence looking for the buildings it cannot shoot past
};
+static const Real BLIND_SPOT_TARGET_HEIGHT = 10.0f; ///< top of a tank, the height a defence has to see over a hill
+static const Real LOS_TERRAIN_SLOP = 0.5f; ///< the terrain line-of-sight test's own fudge
+
//-------------------------------------------------------------------------------------------------
/** Every number above is an 800x600 one, the resolution the command bar right below the strip was
* drawn at, so every one of them goes through here to become pixels.
@@ -1162,6 +1173,11 @@ InGameUI::InGameUI()
m_productionStripTraySource = NULL;
for( Int stripString = 0; stripString < STRIP_OVERFLOW_STRINGS; stripString++ )
m_productionStripOverflow[ stripString ] = NULL;
+ m_hudTogglesOpen = FALSE;
+ m_hudToggleRowsShown = 0;
+ m_hudTogglesBottom = 0;
+ for( Int toggleRow = 0; toggleRow < HUD_TOGGLE_ROWS; toggleRow++ )
+ m_hudToggleStrings[ toggleRow ] = NULL;
for( Int stripSeconds = 0; stripSeconds < STRIP_SECONDS_STRINGS; stripSeconds++ )
m_stripSecondsString[ stripSeconds ] = NULL;
for( Int stripQuantity = 0; stripQuantity < STRIP_QUANTITY_STRINGS; stripQuantity++ )
@@ -1384,7 +1400,11 @@ void InGameUI::init( void )
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
-/** Ring a radius we already know, rather than one derived from a selected object. */
+/** Paint a radius we already know, rather than one derived from a selected object.
+ *
+ * It is the red attack area the artillery powers aim with, not the white guard ring: what a
+ * defence on the cursor covers is ground it will shoot into, and a filled red disc says that where
+ * a thin white circle read as a building footprint. */
//-------------------------------------------------------------------------------------------------
void InGameUI::setRadiusCursorForRadius(Real radius)
{
@@ -1396,13 +1416,13 @@ void InGameUI::setRadiusCursorForRadius(Real radius)
// re-create only when the size actually changed, otherwise the decal restarts every frame.
// (this used to hang off a function-level static, which outlived the decal it described.)
- if (m_curRcType == RADIUSCURSOR_GUARD_AREA && !m_curRadiusCursor.isEmpty() && m_placementRingRadius == radius)
+ if (m_curRcType == RADIUSCURSOR_ATTACK_DAMAGE_AREA && !m_curRadiusCursor.isEmpty() && m_placementRingRadius == radius)
return;
m_curRadiusCursor.clear();
Coord3D pos = { 0, 0, 0 }; // handleRadiusCursor() puts it under the cursor
- m_radiusCursors[RADIUSCURSOR_GUARD_AREA].createRadiusDecal(pos, radius, ThePlayerList->getLocalPlayer(), m_curRadiusCursor);
- m_curRcType = RADIUSCURSOR_GUARD_AREA;
+ m_radiusCursors[RADIUSCURSOR_ATTACK_DAMAGE_AREA].createRadiusDecal(pos, radius, ThePlayerList->getLocalPlayer(), m_curRadiusCursor);
+ m_curRcType = RADIUSCURSOR_ATTACK_DAMAGE_AREA;
m_placementRingRadius = radius;
handleRadiusCursor();
@@ -1684,6 +1704,354 @@ static Real templatePlacementRange( const ThingTemplate *tmpl )
return range;
}
+//-------------------------------------------------------------------------------------------------
+// The top left drop-down. Row 0 is its header; each row after it is one strip, its words, the
+// GlobalData switch it flips and the Options.ini key that switch is saved under.
+//-------------------------------------------------------------------------------------------------
+static const char *const TheHudToggleLabels[] =
+{
+ "GUI:HudToggles", "GUI:HudProductionStrip", "GUI:HudSkillStrip", "GUI:HudSuperweaponStrip"
+};
+static Bool GlobalData::* const TheHudToggleFlags[] =
+{
+ NULL, &GlobalData::m_showProductionStrip, &GlobalData::m_showSkillStrip, &GlobalData::m_showSuperweaponStrip
+};
+static const char *const TheHudToggleKeys[] =
+{
+ NULL, "ShowProductionStrip", "ShowSkillStrip", "ShowSuperweaponStrip"
+};
+
+enum
+{
+ HUD_TOGGLES_INSET = 6, ///< from the top and left edges of the screen, 800x600
+ HUD_TOGGLES_WIDTH = 150, ///< the whole drop-down's width, 800x600
+ HUD_TOGGLES_PAD = 3 ///< round the words and the boxes inside a row, 800x600
+};
+
+//-------------------------------------------------------------------------------------------------
+/** Is the local player watching rather than playing - an observer, or knocked out and stayed? */
+//-------------------------------------------------------------------------------------------------
+static Bool localPlayerWatching( void )
+{
+ const Player *local = ThePlayerList ? ThePlayerList->getLocalPlayer() : NULL;
+ return local != NULL && !local->isPlayerActive();
+}
+
+//-------------------------------------------------------------------------------------------------
+/** Is this strip switched off from the drop-down? Only a watcher has the drop-down, so a player
+ * always has his strips, whatever he last chose while watching somebody else's match. */
+//-------------------------------------------------------------------------------------------------
+static Bool stripSwitchedOff( Bool GlobalData::* flag )
+{
+ return localPlayerWatching() && !( TheGlobalData->*flag );
+}
+
+//-------------------------------------------------------------------------------------------------
+/** The strips over the battlefield, switched on and off from a drop-down in the top left corner.
+ *
+ * Watching a match three of them fight over the same picture - the production rows, the
+ * promotions, the superweapon countdowns - and which of them a spectator wants depends on what he
+ * is watching for. Closed it is one line with a plus in it. Each box flips its strip the moment
+ * it is clicked and saves the choice with the rest of the options. Only while watching: playing,
+ * the top left corner belongs to the messages. */
+//-------------------------------------------------------------------------------------------------
+void InGameUI::drawHudToggles( void )
+{
+ m_hudToggleRowsShown = 0;
+ m_hudTogglesBottom = 0;
+
+ if( TheGameLogic == NULL || !TheGameLogic->isInGame() || TheGameLogic->isInShellGame() )
+ return;
+ if( !localPlayerWatching() )
+ return;
+
+ const Int rows = m_hudTogglesOpen ? HUD_TOGGLE_ROWS : 1;
+ for( Int row = 0; row < rows; row++ )
+ {
+ if( m_hudToggleStrings[ row ] )
+ continue;
+
+ m_hudToggleStrings[ row ] = TheDisplayStringManager->newDisplayString();
+ m_hudToggleStrings[ row ]->setFont( TheFontLibrary->getFont( m_superweaponNormalFont,
+ TheGlobalLanguageData->adjustFontSize( HUD_OVERLAY_POINT_SIZE ), TRUE ) );
+ m_hudToggleStrings[ row ]->setText( TheGameText->fetch( TheHudToggleLabels[ row ] ) );
+ }
+
+ Int textW = 0, textH = 0;
+ m_hudToggleStrings[ 0 ]->getSize( &textW, &textH );
+
+ const Int pad = stripPixels( HUD_TOGGLES_PAD );
+ const Int left = stripPixels( HUD_TOGGLES_INSET );
+ const Int top = stripPixels( HUD_TOGGLES_INSET );
+ const Int width = stripPixels( HUD_TOGGLES_WIDTH );
+ const Int rowH = textH + 2 * pad;
+ const Int box = textH;
+ const Color plate = GameMakeColor( 0, 0, 0, 150 );
+ const Color edge = GameMakeColor( 200, 200, 200, 255 );
+ const Color on = GameMakeColor( 90, 200, 90, 255 );
+ const Color words = GameMakeColor( 235, 235, 235, 255 );
+ const Color shade = GameMakeColor( 0, 0, 0, 255 );
+
+ TheDisplay->beginBatch2D();
+
+ for( Int row = 0; row < rows; row++ )
+ {
+ const Int y = top + row * rowH;
+ IRegion2D *rect = &m_hudToggleRects[ row ];
+ rect->lo.x = left;
+ rect->lo.y = y;
+ rect->hi.x = left + width;
+ rect->hi.y = y + rowH;
+
+ TheDisplay->drawFillRect( left, y, width, rowH, plate );
+
+ const Int boxX = left + pad;
+ const Int boxY = y + pad;
+ TheDisplay->drawOpenRect( boxX, boxY, box, box, 1.0f, edge );
+
+ if( row == 0 )
+ {
+ // a minus to close it, a plus to open it
+ const Int middleY = boxY + box / 2;
+ const Int middleX = boxX + box / 2;
+ TheDisplay->drawLine( boxX + pad, middleY, boxX + box - pad, middleY, 2.0f, edge );
+ if( !m_hudTogglesOpen )
+ TheDisplay->drawLine( middleX, boxY + pad, middleX, boxY + box - pad, 2.0f, edge );
+ }
+ else if( TheGlobalData->*TheHudToggleFlags[ row ] )
+ {
+ TheDisplay->drawFillRect( boxX + pad, boxY + pad, box - 2 * pad, box - 2 * pad, on );
+ }
+
+ m_hudToggleStrings[ row ]->draw( boxX + box + 2 * pad, y + pad, words, shade );
+ }
+
+ TheDisplay->endBatch2D();
+
+ m_hudToggleRowsShown = rows;
+ m_hudTogglesBottom = top + rows * rowH;
+}
+
+//-------------------------------------------------------------------------------------------------
+/** A click on the drop-down is the drop-down's, whatever button it was, so it never becomes a move
+ * order into the ground under it. Only a plain left click does anything. */
+//-------------------------------------------------------------------------------------------------
+Bool InGameUI::handleHudTogglesClick( const ICoord2D *mouse, Bool act )
+{
+ for( Int row = 0; row < m_hudToggleRowsShown; row++ )
+ {
+ const IRegion2D &rect = m_hudToggleRects[ row ];
+ if( mouse->x < rect.lo.x || mouse->x >= rect.hi.x || mouse->y < rect.lo.y || mouse->y >= rect.hi.y )
+ continue;
+
+ if( !act )
+ return TRUE;
+
+ if( row == 0 )
+ {
+ m_hudTogglesOpen = !m_hudTogglesOpen;
+ return TRUE;
+ }
+
+ const Bool now = !( TheGlobalData->*TheHudToggleFlags[ row ] );
+ TheWritableGlobalData->*TheHudToggleFlags[ row ] = now;
+
+ OptionPreferences pref;
+ pref[ AsciiString( TheHudToggleKeys[ row ] ) ] = AsciiString( now ? "yes" : "no" );
+ pref.write();
+ return TRUE;
+ }
+
+ return FALSE;
+}
+
+//-------------------------------------------------------------------------------------------------
+/** Add the pixel rows a convex four-cornered shape covers to a per-row list of spans, one span a
+ * row, as x = start and y = end. Rows are sampled through their middle and both edges are rounded
+ * the same way, so two shapes sharing an edge meet on the same pixel. */
+//-------------------------------------------------------------------------------------------------
+static void addQuadSpans( const ICoord2D *corners[ 4 ], std::vector< std::vector< ICoord2D > > &rows )
+{
+ Int top = corners[ 0 ]->y;
+ Int bottom = corners[ 0 ]->y;
+ for( Int c = 1; c < 4; c++ )
+ {
+ top = min( top, corners[ c ]->y );
+ bottom = max( bottom, corners[ c ]->y );
+ }
+ top = max( top, 0 );
+ bottom = min( bottom, (Int)rows.size() );
+
+ for( Int y = top; y < bottom; y++ )
+ {
+ const Real rowY = y + 0.5f;
+ Real left = FLT_MAX;
+ Real right = -FLT_MAX;
+
+ for( Int c = 0; c < 4; c++ )
+ {
+ const ICoord2D &from = *corners[ c ];
+ const ICoord2D &to = *corners[ ( c + 1 ) % 4 ];
+ if( ( rowY < from.y ) == ( rowY < to.y ) )
+ continue; // this edge does not cross the row
+
+ const Real x = from.x + ( to.x - from.x ) * ( rowY - from.y ) / (Real)( to.y - from.y );
+ left = min( left, x );
+ right = max( right, x );
+ }
+
+ ICoord2D span;
+ span.x = REAL_TO_INT_FLOOR( left + 0.5f );
+ span.y = REAL_TO_INT_FLOOR( right + 0.5f );
+ rows[ y ].push_back( span );
+ }
+}
+
+static Bool spanStartsFirst( const ICoord2D &a, const ICoord2D &b )
+{
+ return a.x < b.x;
+}
+
+//-------------------------------------------------------------------------------------------------
+/** The ground a defence on the cursor could not shoot into, darkened inside its red range area.
+ *
+ * A defence that needs a line of sight - a Patriot battery, a Gattling Cannon, a Fire Base - does
+ * not fire through a building, and cannot pick a target a hill hides from it. Both rules are the
+ * game's own. Target picking asks the terrain for a clear line from the top of the defence to the
+ * target, and the pathfinder refuses a shot when a solid structure's cells lie between them; a
+ * structure the art says can be seen through does not count.
+ *
+ * The range area is cut into a polar grid, a sector per ray and a ring per half pathfind cell, and
+ * each cell of it is looked at from the defence. Along one sector the walk keeps the steepest
+ * terrain seen so far, which is the horizon: a target whose top sits under that slope is behind a
+ * hill. Everything from the first building cell outwards is behind that building, the building's
+ * own ground included. The blocked cells are projected corner by corner onto the terrain and
+ * filled as one shape, row by row, so the shade follows the ground and has no seams in it.
+ *
+ * A Stinger Site, a bunker and anything else that does not need the line of sight gets no shading,
+ * because none of that ground is out of its reach. */
+//-------------------------------------------------------------------------------------------------
+void InGameUI::drawPlacementBlindSpots( void )
+{
+ if( m_pendingPlaceType == NULL || !m_placementRangeRingUp )
+ return;
+ if( !TheAI->getAiData()->m_attackUsesLineOfSight || !m_pendingPlaceType->isKindOf( KINDOF_ATTACK_NEEDS_LINE_OF_SIGHT ) )
+ return;
+
+ const Coord3D center = *m_placeIcon[ 0 ]->getPosition();
+ const Real range = m_placementRingRadius;
+ const Real ringWidth = PATHFIND_CELL_SIZE_F * 0.5f; // two looks a cell, so a corner is not stepped over
+ const Int rings = (Int)ceil( range / ringWidth );
+ const Real eyeZ = TheTerrainLogic->getGroundHeight( center.x, center.y )
+ + m_pendingPlaceType->getTemplateGeometryInfo().getMaxHeightAbovePosition();
+
+ std::vector< Bool > blocked( BLIND_SPOT_RAYS * rings, FALSE );
+ Bool anyBlocked = FALSE;
+ for( Int ray = 0; ray < BLIND_SPOT_RAYS; ray++ )
+ {
+ const Real angle = 2.0f * PI * ( ray + 0.5f ) / BLIND_SPOT_RAYS;
+ const Real dx = Cos( angle );
+ const Real dy = Sin( angle );
+
+ Real horizonSlope = -FLT_MAX;
+ Bool behindBuilding = FALSE;
+ for( Int ring = 0; ring < rings; ring++ )
+ {
+ const Real along = min( ( ring + 0.5f ) * ringWidth, range );
+ Coord3D look = { center.x + dx * along, center.y + dy * along, center.z };
+ const Real groundZ = TheTerrainLogic->getGroundHeight( look.x, look.y );
+
+ const PathfindCell *cell = TheAI->pathfinder()->getCell( LAYER_GROUND, &look );
+ if( cell && cell->getType() == PathfindCell::CELL_OBSTACLE && !cell->isObstacleTransparent() )
+ behindBuilding = TRUE;
+
+ const Real targetSlope = ( groundZ + BLIND_SPOT_TARGET_HEIGHT - eyeZ ) / along;
+ const Bool behindHill = targetSlope < horizonSlope;
+ horizonSlope = max( horizonSlope, ( groundZ - LOS_TERRAIN_SLOP - eyeZ ) / along );
+
+ if( behindBuilding || behindHill )
+ {
+ blocked[ ray * rings + ring ] = TRUE;
+ anyBlocked = TRUE;
+ }
+ }
+ }
+
+ if( !anyBlocked )
+ return;
+
+ // corner ( ray, ring ) sits on the ray's leading edge at the ring's inner radius
+ const Int cornerRings = rings + 1;
+ std::vector< ICoord2D > corners( BLIND_SPOT_RAYS * cornerRings );
+ std::vector< Bool > onScreen( BLIND_SPOT_RAYS * cornerRings );
+ for( Int ray = 0; ray < BLIND_SPOT_RAYS; ray++ )
+ {
+ const Real angle = 2.0f * PI * ray / BLIND_SPOT_RAYS;
+ for( Int ring = 0; ring < cornerRings; ring++ )
+ {
+ const Real along = min( ring * ringWidth, range );
+ Coord3D ground;
+ ground.x = center.x + Cos( angle ) * along;
+ ground.y = center.y + Sin( angle ) * along;
+ ground.z = TheTerrainLogic->getGroundHeight( ground.x, ground.y );
+ const Int index = ray * cornerRings + ring;
+ onScreen[ index ] = TheTacticalView->worldToScreenTriReturn( &ground, &corners[ index ] ) != View::WTS_INVALID;
+ }
+ }
+
+ const Int screenW = (Int)TheDisplay->getWidth();
+ std::vector< std::vector< ICoord2D > > rows( TheDisplay->getHeight() );
+ for( Int ray = 0; ray < BLIND_SPOT_RAYS; ray++ )
+ {
+ const Int next = ( ray + 1 ) % BLIND_SPOT_RAYS;
+ for( Int ring = 0; ring < rings; ring++ )
+ {
+ if( !blocked[ ray * rings + ring ] )
+ continue;
+
+ const Int quad[ 4 ] = { ray * cornerRings + ring, next * cornerRings + ring,
+ next * cornerRings + ring + 1, ray * cornerRings + ring + 1 };
+ if( !onScreen[ quad[ 0 ] ] || !onScreen[ quad[ 1 ] ] || !onScreen[ quad[ 2 ] ] || !onScreen[ quad[ 3 ] ] )
+ continue;
+
+ const ICoord2D *quadCorners[ 4 ] = { &corners[ quad[ 0 ] ], &corners[ quad[ 1 ] ], &corners[ quad[ 2 ] ], &corners[ quad[ 3 ] ] };
+ addQuadSpans( quadCorners, rows );
+ }
+ }
+
+ const Color shade = GameMakeColor( 0, 0, 0, 120 );
+
+ TheDisplay->beginBatch2D();
+
+ for( Int y = 0; y < (Int)rows.size(); y++ )
+ {
+ std::vector< ICoord2D > &spans = rows[ y ];
+ if( spans.empty() )
+ continue;
+
+ std::sort( spans.begin(), spans.end(), spanStartsFirst );
+ ICoord2D run = spans[ 0 ];
+ for( size_t s = 1; s <= spans.size(); s++ )
+ {
+ // a pixel's gap between two neighbours is rounding, not open ground
+ if( s < spans.size() && spans[ s ].x <= run.y + 1 )
+ {
+ run.y = max( run.y, spans[ s ].y );
+ continue;
+ }
+
+ const Int x0 = max( run.x, 0 );
+ const Int x1 = min( run.y, screenW );
+ if( x1 > x0 )
+ TheDisplay->drawFillRect( x0, y, x1 - x0, 1, shade );
+ if( s < spans.size() )
+ run = spans[ s ];
+ }
+ }
+
+ TheDisplay->endBatch2D();
+}
+
void InGameUI::handleBuildPlacements( void )
{
@@ -3456,6 +3824,15 @@ Bool InGameUI::issueAttackCircle( void )
if( isHiddenByShroud( obj ) )
continue;
+ //
+ // Shroud is only half of invisible. A stealthed tank sitting in ground the player has
+ // cleared passes the test above, so a circle swept over open country used to pick out every
+ // hidden unit in it and open fire: a detector nobody built, and a way to read the map for
+ // stealth by dragging a circle over it. Undetected means not in the circle.
+ //
+ if( obj->testStatus( OBJECT_STATUS_STEALTHED ) && !obj->testStatus( OBJECT_STATUS_DETECTED ) )
+ continue;
+
//
// Not everything hostile standing in the circle is something to shoot at. A shell or a
// missile in flight is an object on the enemy's team like any other, and the range query hands
@@ -5480,6 +5857,9 @@ void InGameUI::postDraw( void )
{
// drawHudOverlay is NOT called here - it goes on top of everything, see W3DInGameUI::draw
drawProductionStrip();
+ drawSkillStrip(); // the same shelf, the other end of it
+ drawPlacementBlindSpots();
+ drawHudToggles();
// render our display strings for the messages if on
@@ -5491,6 +5871,9 @@ void InGameUI::postDraw( void )
x = m_messagePosition.x;
y = m_messagePosition.y;
+ // the messages start under the strip drop-down rather than being written across it
+ if( m_hudTogglesBottom + stripPixels( HUD_TOGGLES_INSET ) > y )
+ y = m_hudTogglesBottom + stripPixels( HUD_TOGGLES_INSET );
for( i = MAX_UI_MESSAGES - 1; i >= 0; i-- )
{
@@ -7672,17 +8055,26 @@ const Image *InGameUI::productionStripTray( void )
//-------------------------------------------------------------------------------------------------
void InGameUI::stripTrayMetrics( ICoord2D *tray, ICoord2D *cameo, ICoord2D *hole, Int *step )
{
- if( TheControlBar
- && TheControlBar->getSpecialPowerTrayLayout( tray, cameo, hole, step ) )
- return;
+ if( !TheControlBar || !TheControlBar->getSpecialPowerTrayLayout( tray, cameo, hole, step ) )
+ {
+ tray->x = stripPixels( PRODUCTION_STRIP_TRAY_W );
+ tray->y = stripPixels( PRODUCTION_STRIP_TRAY_H );
+ cameo->x = stripPixels( PRODUCTION_STRIP_QUEUE_W );
+ cameo->y = stripPixels( PRODUCTION_STRIP_QUEUE_H );
+ hole->x = stripPixels( PRODUCTION_STRIP_TRAY_X );
+ hole->y = stripPixels( PRODUCTION_STRIP_TRAY_Y );
+ }
- tray->x = stripPixels( PRODUCTION_STRIP_TRAY_W );
- tray->y = stripPixels( PRODUCTION_STRIP_TRAY_H );
- cameo->x = stripPixels( PRODUCTION_STRIP_QUEUE_W );
- cameo->y = stripPixels( PRODUCTION_STRIP_QUEUE_H );
- hole->x = stripPixels( PRODUCTION_STRIP_TRAY_X );
- hole->y = stripPixels( PRODUCTION_STRIP_TRAY_Y );
- *step = tray->x;
+ //
+ // Across a row the trays close up an eighth of a tray under each other, so a row reads as one
+ // run of metal rather than a line of separate boxes. The command bar's own power slots stopped
+ // doing that because they are windows and the neighbour's rail was drawn over each cameo's edge;
+ // every strip here lays all its trays down before any cameo, so the rails overlap each other and
+ // never a picture. The step never closes past a cameo's own width, so no two pictures touch.
+ //
+ const Int overlapped = tray->x - tray->x / STRIP_TRAY_OVERLAP_PARTS;
+ const Int narrowest = cameo->x + stripPixels( PRODUCTION_STRIP_GAP );
+ *step = overlapped > narrowest ? overlapped : narrowest;
}
//-------------------------------------------------------------------------------------------------
@@ -7810,7 +8202,7 @@ void InGameUI::addSuperweaponIcon( const Image *image, Int seconds, Int percent,
//-------------------------------------------------------------------------------------------------
void InGameUI::drawSuperweaponStrip( void )
{
- if( m_superweaponIconCount < 1 )
+ if( m_superweaponIconCount < 1 || stripSwitchedOff( &GlobalData::m_showSuperweaponStrip ) )
return;
if( TheGameLogic == NULL || !TheGameLogic->isInGame() || TheGameLogic->isInShellGame() )
@@ -7998,6 +8390,216 @@ void InGameUI::drawSuperweaponStrip( void )
TheDisplay->endBatch2D();
}
+//-------------------------------------------------------------------------------------------------
+/** One bought promotion, and the cameo the promotion screen buys it from. */
+struct BoughtSkill
+{
+ ScienceType science;
+ const Image *cameo;
+};
+
+/** Every science in one of a general's three promotion command sets that the player has actually
+ * bought. Appends to skills and hands back the new count, so the three sets fill one list in rank
+ * order. */
+//-------------------------------------------------------------------------------------------------
+static Int gatherSkillCameos( const Player *player, const AsciiString &setName,
+ BoughtSkill *skills, Int count, Int max )
+{
+ const CommandSet *set = TheControlBar->findCommandSet( setName );
+ if( set == NULL )
+ return count;
+
+ for( Int i = 0; i < MAX_COMMANDS_PER_SET && count < max; i++ )
+ {
+ const CommandButton *button = set->getCommandButton( i );
+ if( button == NULL || button->getScienceVec().empty() || button->getButtonImage() == NULL )
+ continue;
+
+ const ScienceType science = button->getScienceVec()[ 0 ];
+ if( !player->hasScience( science ) || player->isScienceHidden( science ) )
+ continue;
+
+ skills[ count ].science = science;
+ skills[ count ].cameo = button->getButtonImage();
+ count++;
+ }
+
+ return count;
+}
+
+//-------------------------------------------------------------------------------------------------
+/** Everything one player has bought out of his three promotion sets, in rank order, as cameos
+ * appended to icons. Hands back the new count.
+ *
+ * A level that a later level of the same power has replaced is left out: Artillery Barrage 3 is
+ * one cameo, not three of the same picture in a row. "Replaced" is the science's own
+ * prerequisite list, so the second level asking for the first is what hides the first. */
+//-------------------------------------------------------------------------------------------------
+static Int gatherPlayerSkills( const Player *player, const Image **icons, Int count, Int max )
+{
+ const PlayerTemplate *playerTemplate = player->getPlayerTemplate();
+ if( playerTemplate == NULL )
+ return count;
+
+ enum { MOST_SKILLS = 3 * MAX_COMMANDS_PER_SET };
+ BoughtSkill skills[ MOST_SKILLS ];
+ Int bought = gatherSkillCameos( player, playerTemplate->getPurchaseScienceCommandSetRank1(),
+ skills, 0, MOST_SKILLS );
+ bought = gatherSkillCameos( player, playerTemplate->getPurchaseScienceCommandSetRank3(),
+ skills, bought, MOST_SKILLS );
+ bought = gatherSkillCameos( player, playerTemplate->getPurchaseScienceCommandSetRank8(),
+ skills, bought, MOST_SKILLS );
+
+ for( Int i = 0; i < bought && count < max; i++ )
+ {
+ Bool replaced = FALSE;
+ for( Int later = 0; later < bought && !replaced; later++ )
+ replaced = TheScienceStore->isDirectPrereq( skills[ i ].science, skills[ later ].science );
+
+ if( !replaced )
+ icons[ count++ ] = skills[ i ].cameo;
+ }
+
+ return count;
+}
+
+//-------------------------------------------------------------------------------------------------
+/** The skill strip: what the generals have spent their promotions on, down the right hand edge
+ * under the superweapon countdowns.
+ *
+ * Watching a match, those choices decide half of what is about to happen on the field, and the
+ * only place they were written down was a screen you had to open - which came up blank anyway,
+ * because it was filled in with the watcher's own empty template. The strip reads the way the
+ * production rows on the other side of the screen do: with nothing selected it is every player
+ * at once, one row each in his own colour, and a selected unit narrows the whole screen to his
+ * owner - his row, and as many rows as his promotions need. Playing, it is not drawn at all:
+ * your own promotions are one key away and you bought them yourself. */
+//-------------------------------------------------------------------------------------------------
+void InGameUI::drawSkillStrip( void )
+{
+ if( stripSwitchedOff( &GlobalData::m_showSkillStrip ) )
+ return;
+ if( TheGameLogic == NULL || !TheGameLogic->isInGame() || TheGameLogic->isInShellGame() )
+ return;
+
+ Player *local = ThePlayerList->getLocalPlayer();
+ if( local == NULL || local->isPlayerActive() || TheControlBar == NULL )
+ return;
+
+ const Image *icons[ SKILL_STRIP_MAX ];
+ Color rowColor[ SKILL_STRIP_ROWS ];
+ Int rowCount[ SKILL_STRIP_ROWS ];
+ Int rows = 0;
+
+ Player *selected = TheControlBar->getSelectedPlayer();
+ if( selected )
+ {
+ const Int count = gatherPlayerSkills( selected, icons, 0, SKILL_STRIP_MAX );
+ const Color color = clientPlayerColor( selected );
+
+ while( rows * SKILL_STRIP_COLS < count && rows < SKILL_STRIP_ROWS )
+ {
+ const Int left = count - rows * SKILL_STRIP_COLS;
+ rowCount[ rows ] = left > SKILL_STRIP_COLS ? SKILL_STRIP_COLS : left;
+ rowColor[ rows ] = color;
+ rows++;
+ }
+ }
+ else
+ {
+ for( Int i = 0; i < ThePlayerList->getPlayerCount() && rows < SKILL_STRIP_ROWS; i++ )
+ {
+ Player *player = ThePlayerList->getNthPlayer( i );
+ if( player == local || !player->isPlayerActive() || !player->isPlayableSide() )
+ continue;
+
+ // a row is one player's, so his own run stops at the end of it rather than running on
+ const Int start = rows * SKILL_STRIP_COLS;
+ const Int count = gatherPlayerSkills( player, icons, start, start + SKILL_STRIP_COLS );
+ if( count == start )
+ continue; // nothing bought yet: no row rather than an empty one
+
+ rowCount[ rows ] = count - start;
+ rowColor[ rows ] = clientPlayerColor( player );
+ rows++;
+ }
+ }
+
+ if( rows < 1 )
+ return;
+
+ ICoord2D traySize, cameoSize, trayHole;
+ Int trayStep = 0;
+ stripTrayMetrics( &traySize, &cameoSize, &trayHole, &trayStep );
+
+ const Int trayW = traySize.x;
+ const Int trayH = traySize.y;
+ const Int cameoW = cameoSize.x;
+ const Int cameoH = cameoSize.y;
+ const Image *tray = TheControlBar->getSpecialPowerTrayImage();
+
+ //
+ // Bottom right, standing on the control bar and growing upward - the production rows' own
+ // corner, on the other side of the screen. It was up under the superweapon countdowns to begin
+ // with, which is where the eye is not: watching a match you read the bottom of the screen, and
+ // the two strips now sit at either end of the same shelf.
+ //
+ Int barTop = TheDisplay->getHeight();
+ static NameKeyType controlBarKey = TheNameKeyGenerator->nameToKey( "ControlBar.wnd:ControlBarParent" );
+ GameWindow *bar = TheWindowManager->winGetWindowFromId( NULL, controlBarKey );
+ if( bar && !bar->winIsHidden() )
+ {
+ ICoord2D barPos;
+ bar->winGetScreenPosition( &barPos.x, &barPos.y );
+ barTop = barPos.y;
+ }
+
+ const Int lowerY = barTop - ( trayH - trayHole.y ) - stripPixels( PRODUCTION_STRIP_LIFT );
+ const Int right = TheDisplay->getWidth();
+
+ // drawn as a batch, for the reason drawProductionStrip() gives - see Display::beginBatch2D
+ TheDisplay->beginBatch2D();
+
+ for( Int row = 0; row < rows; row++ )
+ {
+ const Int first = row * SKILL_STRIP_COLS;
+ const Int inRow = rowCount[ row ];
+
+ UnsignedByte red, green, blue, alpha;
+ GameGetColorComponents( rowColor[ row ], &red, &green, &blue, &alpha );
+
+ // the first row is the one on the bar, and the rest are piled over it
+ const Int y = lowerY - row * trayH;
+ const Int trayY = y - trayHole.y;
+ if( trayY < 0 )
+ break;
+
+ for( Int back = inRow - 1; back >= 0; back-- )
+ {
+ const Int backX = right - trayW - back * trayStep;
+ if( tray )
+ TheDisplay->drawImage( tray, backX, trayY, backX + trayW, trayY + trayH );
+ else
+ TheDisplay->drawFillRect( backX, trayY, trayW, trayH, GameMakeColor( 0, 0, 0, 130 ) );
+ }
+
+ for( Int cameoSlot = 0; cameoSlot < inRow; cameoSlot++ )
+ {
+ const Int x = right - trayW + trayHole.x - cameoSlot * trayStep;
+ TheDisplay->drawImage( icons[ first + cameoSlot ], x, y, x + cameoW, y + cameoH );
+ }
+
+ // whose skills these are, in his own colour, the same border the superweapon cameos wear
+ for( Int borderSlot = 0; borderSlot < inRow; borderSlot++ )
+ {
+ const Int x = right - trayW + trayHole.x - borderSlot * trayStep;
+ TheDisplay->drawOpenRect( x, y, cameoW, cameoH, 2.0f, GameMakeColor( red, green, blue, 255 ) );
+ }
+ }
+
+ TheDisplay->endBatch2D();
+}
+
//-------------------------------------------------------------------------------------------------
/** Lay out and draw one run of cells, its left edge at left and the first cameo's top edge at
* bottomY.
@@ -8349,6 +8951,9 @@ void InGameUI::drawProductionStrip( void )
m_productionStripRowColor[ row ] = 0;
}
+ // switched off from the drop-down: nothing drawn, and with the counts at nought nothing to click
+ if( stripSwitchedOff( &GlobalData::m_showProductionStrip ) )
+ return;
if( TheGameLogic == NULL || !TheGameLogic->isInGame() || TheGameLogic->isInShellGame() )
return;
@@ -8366,19 +8971,29 @@ void InGameUI::drawProductionStrip( void )
m_productionStripWatching = !player->isPlayerActive();
if( m_productionStripWatching )
{
+ //
+ // Selecting somebody's unit narrows the whole screen to him - his rows here, his skills on
+ // the right, his side on the bar - and clicking empty ground puts the whole match back.
+ //
+ Player *only = TheControlBar ? TheControlBar->getSelectedPlayer() : NULL;
+
Int row = 0;
for( Int i = 0; i < ThePlayerList->getPlayerCount() && row < PRODUCTION_STRIP_ROWS; i++ )
{
Player *p = ThePlayerList->getNthPlayer( i );
if( p == NULL || p == player || !p->isPlayerActive() || !p->isPlayableSide() )
continue;
+ if( only && p != only )
+ continue;
ProductionStripGather watch;
watch.slot = m_productionStrip[ row ];
watch.count = &m_productionStripCount[ row ];
watch.total = &m_productionStripTotal[ row ];
- // eight rows are on screen at once here, so each one is the few soonest and a "+N"
- watch.max = PRODUCTION_STRIP_WATCH_MAX;
+ // eight rows are on screen at once here, so each one is the few soonest and a "+N" -
+ // unless one player has the screen to himself, and then his row is as long as the
+ // playing strip's own column
+ watch.max = only ? PRODUCTION_STRIP_ROW_MAX : PRODUCTION_STRIP_WATCH_MAX;
watch.skip = INVALID_ID; // nothing is selected in somebody else's base
p->iterateObjects( gatherStripEverything, &watch );
@@ -8521,6 +9136,10 @@ Bool InGameUI::handleProductionStripClick( const ICoord2D *mouse, Bool cancel )
if( mouse == NULL )
return FALSE;
+ // the strip drop-down lies over the world the same way the strip does, so its clicks come here too
+ if( handleHudTogglesClick( mouse, !cancel ) )
+ return TRUE;
+
for( Int row = 0; row < PRODUCTION_STRIP_ROWS; row++ )
{
for( Int i = 0; i < m_productionStripCount[ row ]; i++ )
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/SelectionInfo.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/SelectionInfo.cpp
index f69ce1382..e5c516cb2 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/SelectionInfo.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/SelectionInfo.cpp
@@ -387,7 +387,12 @@ Bool addDrawableToList( Drawable *draw, void *userData )
{
const Player *player = ThePlayerList->getLocalPlayer();
Relationship rel = player->getRelationship( obj->getTeam() );
- if( rel == NEUTRAL || rel == ENEMIES )
+ /* ...but a spectator is not somebody who could exploit knowing. An observer, and a player
+ who has already lost, commands nothing, sees the whole map anyway, and is watching the
+ match precisely to look at what the players are doing - a stealth building that cannot be
+ clicked is a hole in the broadcast. Same test the control bar uses to switch to its
+ observer scheme. */
+ if( ( rel == NEUTRAL || rel == ENEMIES ) && player->isPlayerActive() )
{
if( obj->getShroudedStatus( player->getPlayerIndex() ) >= OBJECTSHROUD_FOGGED )
{
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
index 43a25740b..48ffb5c05 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
@@ -3979,9 +3979,9 @@ void AIPlayer::doUpgradesAndSkills( void )
Pathfinder already break theirs down: per job, plus whichever single player cost the most.
Reset once per logic frame by AI::update. */
enum { AIP_BASE, AIP_READY, AIP_QUEUED, AIP_TEAM, AIP_UPGRADE,
- AIP_BRIDGE, AIP_SCOUT, AIP_RETREAT, AIP_EXPAND, AIP_CAPTURE, AIP_ECONOMY, AIP_WAVE, AIP_PHASE_COUNT };
+ AIP_BRIDGE, AIP_SCOUT, AIP_RETREAT, AIP_EXPAND, AIP_CAPTURE, AIP_ECONOMY, AIP_POWER, AIP_WAVE, AIP_PHASE_COUNT };
static const char *theAIPhaseName[ AIP_PHASE_COUNT ] =
- { "base", "ready", "queued", "team", "upg", "bridge", "scout", "retreat", "expand", "capture", "economy", "wave" };
+ { "base", "ready", "queued", "team", "upg", "bridge", "scout", "retreat", "expand", "capture", "economy", "power", "wave" };
static Real theAIPhaseMS[ AIP_PHASE_COUNT ];
static Real theAIWorstPlayerMS = 0.0f;
static Int theAIWorstPlayer = -1;
@@ -4055,6 +4055,7 @@ void AIPlayer::update( void )
AI_PHASE( AIP_EXPAND, doExpansion() ); // Go and take the money that is lying around.
AI_PHASE( AIP_CAPTURE, doCapture() ); // ... and the money that is standing around.
AI_PHASE( AIP_ECONOMY, doEconomy() ); // ... and the money sitting in the bank.
+ AI_PHASE( AIP_POWER, doPower() ); // Keep the lights on, and out of reach.
AI_PHASE( AIP_WAVE, doWaves() ); // Send the parked attack teams out together.
#ifdef DEBUG_LOGGING
@@ -4286,6 +4287,23 @@ void AIPlayer::doExpansion( void )
* is nothing to save and every machine lands on the same frame. */
static const Int ECONOMY_CHECK_RATE = 10 * LOGICFRAMES_PER_SECOND;
+/** How often the power is looked at, and the margin that counts as thin. Five seconds because a
+ * plant takes about that long to matter and an outage costs the whole base; the reserve is about
+ * what one more building will draw, so the plant is ordered before the building that needs it. */
+static const Int POWER_CHECK_RATE = 5 * LOGICFRAMES_PER_SECOND;
+static const Int POWER_RESERVE = 5;
+
+/** How far behind the base a new power plant goes, in base radii, measured away from the enemy. */
+static const Real POWER_SETBACK = 0.75f;
+
+/** And how far in front of it a bought base defense goes, on the same line the other way. */
+static const Real DEFENSE_STANDOFF = 1.0f;
+
+/** What rations those: one purchase every ninth economy pass, which is a minute and a half, and a
+ * ceiling on the guns standing at once counting the ones the build list put there. */
+static const Int DEFENSE_BUY_PASSES = 9;
+static const Int MAX_BASE_DEFENSES = 10;
+
/** Tries on each ring when looking for somewhere to put a purchase down. Every try is a legality
* check that costs about a millisecond, so this bounds the spike rather than the search. */
static const Int PLACEMENT_ANGLES = 12;
@@ -4371,6 +4389,136 @@ static Bool priorityBuildPending( Player *player, const ThingTemplate *tmpl )
return FALSE;
}
+/** A plant of this player's is already going up. One halfway built is the answer to the outage
+ * arriving, and queueing a second one is a war factory this player will not be able to buy. */
+static void findPowerUnderConstruction( Object *obj, void *userData )
+{
+ Bool *building = (Bool *)userData;
+ if( obj->isKindOf( KINDOF_FS_POWER ) && !obj->isKindOf( KINDOF_CASH_GENERATOR )
+ && obj->testStatus( OBJECT_STATUS_UNDER_CONSTRUCTION ) )
+ *building = TRUE;
+}
+
+/** Base defenses this player already owns, going up or standing. */
+static void countBaseDefenses( Object *obj, void *userData )
+{
+ Int *count = (Int *)userData;
+ if( obj->isKindOf( KINDOF_FS_BASE_DEFENSE ) && !obj->isEffectivelyDead() )
+ ++(*count);
+}
+
+//----------------------------------------------------------------------------------------------------------
+/** Which way the trouble comes from, as a unit vector out of this base: towards the nearest enemy,
+ * at the best address this player has for him.
+ *
+ * The nearest one, not the one it has decided to attack - those are different questions. An
+ * attack target is picked on what it is worth and can be on the far side of the map, and a wall
+ * built facing that has its back to the neighbour who is actually next door.
+ *
+ * enemyStartGuess is what answers "where is he": a base it has scouted, or the start position it
+ * has not yet been able to rule out. Reading the enemy's object list directly would put a
+ * defence line exactly where the enemy is standing without anybody having gone to look, which is
+ * the map-reading this AI had taken out of it everywhere else. */
+//----------------------------------------------------------------------------------------------------------
+Bool AIPlayer::enemyDirection( Coord3D *dir )
+{
+ Coord3D target;
+ Bool found = FALSE;
+ Real bestDistanceSqr = 0.0f;
+
+ for( Int i = 0; i < ThePlayerList->getPlayerCount(); ++i )
+ {
+ Player *them = ThePlayerList->getNthPlayer( i );
+ if( them == m_player || m_player->getRelationship( them->getDefaultTeam() ) != ENEMIES )
+ continue;
+ if( !them->hasAnyObjects() )
+ continue;
+
+ Coord3D theirs;
+ if( !enemyStartGuess( i, &theirs ) )
+ continue;
+
+ const Real distanceSqr = sqr( theirs.x - m_baseCenter.x ) + sqr( theirs.y - m_baseCenter.y );
+ if( !found || distanceSqr < bestDistanceSqr )
+ {
+ target = theirs;
+ bestDistanceSqr = distanceSqr;
+ found = TRUE;
+ }
+ }
+
+ if( !found )
+ {
+ // nobody left to face, so face the middle, which is the way every skirmish start faces
+ Region3D bounds;
+ TheTerrainLogic->getMaximumPathfindExtent( &bounds );
+ target.x = bounds.lo.x + bounds.width() * 0.5f;
+ target.y = bounds.lo.y + bounds.height() * 0.5f;
+ target.z = 0;
+ }
+
+ dir->x = target.x - m_baseCenter.x;
+ dir->y = target.y - m_baseCenter.y;
+ dir->z = 0;
+ if( dir->length() < 1.0f )
+ return FALSE;
+
+ dir->normalize();
+ return TRUE;
+}
+
+//----------------------------------------------------------------------------------------------------------
+/** Keeping the lights on, which the plan does not. The build list carries a fixed number of power
+ * plants and the scripts never add one, so a base that loses two of them to a raid sits
+ * underpowered - radar dark, base defenses offline, the superweapon's clock stopped - until the
+ * rebuild timer comes round, and then the rebuild goes back to the exact spot the raid already
+ * knows the way to. A plant is the cheapest building on the list and the one thing every other
+ * building depends on, so it is worth buying one before the meter reads zero.
+ *
+ * Two decisions here. Build when the margin is thin rather than when the power is already out,
+ * because a plant takes time to go up and the base is disabled for all of it. And put it behind
+ * the base, on the far side from whoever this player is fighting, so the raid that comes for it
+ * has to cross the whole base first - which is the half of the answer the rebuild timer can
+ * never give. */
+//----------------------------------------------------------------------------------------------------------
+void AIPlayer::doPower( void )
+{
+ const Int phase = computeUpdatePhase( m_player->getPlayerIndex(), POWER_CHECK_RATE );
+ if( (TheGameLogic->getFrame() + phase) % POWER_CHECK_RATE != 0 )
+ return;
+
+ if( !m_player->getCanBuildBase() || !m_baseCenterSet )
+ return;
+
+ const Energy *energy = m_player->getEnergy();
+ if( energy->getProduction() >= energy->getConsumption() + POWER_RESERVE )
+ return;
+
+ Bool building = FALSE;
+ m_player->iterateObjects( findPowerUnderConstruction, &building );
+ if( building )
+ return;
+
+ Object *dozer = NULL;
+ m_player->iterateObjects( findAnyDozer, &dozer );
+ if( dozer == NULL )
+ return;
+
+ const ThingTemplate *tmpl = buildableOfKind( dozer, GUI_COMMAND_DOZER_CONSTRUCT, KINDOF_FS_POWER );
+ if( tmpl == NULL || tmpl->isKindOf( KINDOF_CASH_GENERATOR ) || priorityBuildPending( m_player, tmpl ) )
+ return;
+
+ Coord3D spot = m_baseCenter;
+ Coord3D dir;
+ if( enemyDirection( &dir ) )
+ {
+ spot.x -= dir.x * m_baseRadius * POWER_SETBACK;
+ spot.y -= dir.y * m_baseRadius * POWER_SETBACK;
+ }
+
+ placeNear( tmpl, &spot, 0.0f );
+}
+
//----------------------------------------------------------------------------------------------------------
/** A bank of a hundred thousand is an army and an economy that were never bought. The skirmish build
* list is a fixed plan - two war factories and a barracks - and the scripts never add to it, so
@@ -4438,6 +4586,37 @@ void AIPlayer::doEconomy( void )
if( tmpl && !priorityBuildPending( m_player, tmpl ) && placeNear( tmpl, &m_baseCenter, m_baseRadius ) )
return;
}
+
+ /* And a gun on the side the trouble comes from. Production and income go round the base center,
+ the power goes behind it, and this goes out in front, so money that keeps arriving thickens
+ the base in the order a base wants to be thick in: the defenses first, everything else
+ standing behind them.
+
+ Rationed twice over, because the first version of this was not rationed at all: a rich AI
+ bought one every ten seconds for the rest of the match and ended up living in a wall of
+ bunkers. One every few minutes, and never past the point where another gun is worth less
+ than the tank it could have been. */
+ if( (TheGameLogic->getFrame() / ECONOMY_CHECK_RATE) % DEFENSE_BUY_PASSES != 0 )
+ return;
+
+ Int defenses = 0;
+ m_player->iterateObjects( countBaseDefenses, &defenses );
+ if( defenses >= MAX_BASE_DEFENSES )
+ return;
+
+ const ThingTemplate *defense = buildableOfKind( dozer, GUI_COMMAND_DOZER_CONSTRUCT, KINDOF_FS_BASE_DEFENSE );
+ if( defense && !priorityBuildPending( m_player, defense ) )
+ {
+ Coord3D spot = m_baseCenter;
+ Coord3D dir;
+ if( enemyDirection( &dir ) )
+ {
+ spot.x += dir.x * m_baseRadius * DEFENSE_STANDOFF;
+ spot.y += dir.y * m_baseRadius * DEFENSE_STANDOFF;
+ }
+ if( placeNear( defense, &spot, 0.0f ) )
+ return;
+ }
}
//----------------------------------------------------------------------------------------------------------
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/JetSlowDeathBehavior.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/JetSlowDeathBehavior.cpp
index 02cbd9ce5..54e2dc400 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/JetSlowDeathBehavior.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/JetSlowDeathBehavior.cpp
@@ -38,6 +38,7 @@
#include "GameLogic/GameLogic.h"
#include "GameLogic/Locomotor.h"
#include "GameLogic/Module/AIUpdate.h"
+#include "GameLogic/Module/BodyModule.h"
#include "GameLogic/Module/JetSlowDeathBehavior.h"
#include "GameLogic/Module/PhysicsUpdate.h"
#include "GameLogic/Object.h"
@@ -136,6 +137,7 @@ JetSlowDeathBehavior::JetSlowDeathBehavior( Thing *thing, const ModuleData *modu
m_timerDeathFrame = 0;
m_timerOnGroundFrame = 0;
+ m_fallDeadlineFrame = 0;
m_rollRate = 0.0f;
} // end JetSlowDeathBehavior
@@ -195,6 +197,10 @@ void JetSlowDeathBehavior::beginSlowDeath( const DamageInfo *damageInfo )
// record the frame we died on
m_timerDeathFrame = TheGameLogic->getFrame();
+ // ... and the latest the fall is allowed to hold the fireball back to
+ const UnsignedInt MAX_FALL_SECONDS = 15;
+ m_fallDeadlineFrame = m_timerDeathFrame + MAX_FALL_SECONDS * LOGICFRAMES_PER_SECOND;
+
// do some effects
FXList::doFXObj( modData->m_fxInitialDeath, us );
ObjectCreationList::create( modData->m_oclInitialDeath, us, NULL );
@@ -212,9 +218,13 @@ void JetSlowDeathBehavior::beginSlowDeath( const DamageInfo *damageInfo )
// initialize our roll rate to that defined as the initial value in the module data
m_rollRate = modData->m_rollRate;
- // set the locomotor so that the plane starts falling
+ /* A wing does not stop working the moment the engine behind it stops. The lift used to drop
+ straight to the module's FallHowFast on the frame of the kill, so a plane doing two hundred
+ knots fell out of the sky on the spot and hit the ground almost under where it was shot,
+ which is the one thing a plane cannot do. It keeps its lift here and gives it up over the
+ next couple of seconds in update(), so it carries on forward first and noses over after. */
Locomotor *locomotor = us->getAIUpdateInterface()->getCurLocomotor();
- locomotor->setMaxLift( -TheGlobalData->m_gravity * (1.0f - modData->m_fallHowFast) );
+ locomotor->setMaxLift( -TheGlobalData->m_gravity );
// do not allow the jet to turn anymore
locomotor->setMaxTurnRate( 0.0f );
@@ -250,7 +260,36 @@ UpdateSleepTime JetSlowDeathBehavior::update( void )
// do effects for death while in the air
if( m_timerOnGroundFrame == 0 )
{
-
+ /* Bleed the lift away towards what the module data asked for. A tenth of the gap a frame
+ puts the plane at the falling speed the data names about two seconds after it is hit,
+ having flown a plane's length or three further forward on the way.
+
+ With a floor under it, because FallHowFast defaults to nought and the delivery aircraft -
+ the B-52, the Spectre gunship, the cargo plane, the A-10 - never set it. Nought means the
+ lift exactly cancels gravity, so those four did not fall at all: they flew on at cruising
+ height, burning, until the destruction timer went off and blew them up in mid-air. Half
+ of gravity is a plane coming down, which is the only thing a dead plane does. */
+ AIUpdateInterface *ai = us->getAIUpdateInterface();
+ Locomotor *locomotor = ai ? ai->getCurLocomotor() : NULL;
+ if( locomotor )
+ {
+ const Real LIFT_BLEED_PER_FRAME = 0.1f;
+ const Real MIN_FALL_FRACTION = 0.5f;
+ const Real fallFraction = max( MIN_FALL_FRACTION, modData->m_fallHowFast );
+ const Real fallingLift = -TheGlobalData->m_gravity * (1.0f - fallFraction);
+ const Real currentLift = locomotor->getMaxLift( us->getBodyModule()->getDamageState() );
+ locomotor->setMaxLift( currentLift + (fallingLift - currentLift) * LIFT_BLEED_PER_FRAME );
+ }
+
+ /* And the explosion waits for the ground. The base class destroys the object on a timer
+ whatever is happening to it, which for a plane still in the air is the mid-air blast again
+ by another route; the fireball belongs where the airframe lands. Held off only up to the
+ deadline set when it died, so one that never arrives - shot down over the edge of the
+ world, or held up by something driving its locomotor - still goes away. */
+ const UnsignedInt now = TheGameLogic->getFrame();
+ if( now < m_fallDeadlineFrame && now + 1 >= getDestructionFrame() )
+ setDestructionFrame( now + 2 );
+
PathfindLayerEnum layer = TheTerrainLogic->getLayerForDestination(us->getPosition());
us->setLayer(layer);
Real height;
@@ -357,13 +396,14 @@ void JetSlowDeathBehavior::crc( Xfer *xfer )
// ------------------------------------------------------------------------------------------------
/** Xfer method
* Version Info:
- * 1: Initial version */
+ * 1: Initial version
+ * 2: the deadline the fall may hold the explosion back to */
// ------------------------------------------------------------------------------------------------
void JetSlowDeathBehavior::xfer( Xfer *xfer )
{
// version
- XferVersion currentVersion = 1;
+ XferVersion currentVersion = 2;
XferVersion version = currentVersion;
xfer->xferVersion( &version, currentVersion );
@@ -379,6 +419,11 @@ void JetSlowDeathBehavior::xfer( Xfer *xfer )
// roll rate
xfer->xferReal( &m_rollRate );
+ // how long the fall may hold the explosion back for; a version 1 save has no such deadline, so
+ // a plane loaded in mid-fall blows up on the timer it was saved with
+ if( version >= 2 )
+ xfer->xferUnsignedInt( &m_fallDeadlineFrame );
+
} // end xfer
// ------------------------------------------------------------------------------------------------
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/SalvageCrateCollide.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/SalvageCrateCollide.cpp
index 23e3458dc..c21dfcb59 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/SalvageCrateCollide.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/SalvageCrateCollide.cpp
@@ -64,17 +64,21 @@ Bool SalvageCrateCollide::isValidToExecute( const Object *other ) const
if( ! CrateCollide::isValidToExecute( other ) )
return FALSE;
- // Only salvage units can pick up a Salvage crate
- if( ! other->getTemplate()->isKindOf( KINDOF_SALVAGER ) )
- return FALSE;
-
+ /* Salvagers are what a salvage crate is for, and they are the only ones who get anything out of
+ it but money. Anybody else may still pick it up, because the alternative is what the game did
+ before: a crate nobody in range could take sat in the middle of a battlefield until it timed
+ out, and the money in it belonged to nobody. A tank driving over one now at least gets paid
+ for the wreck. */
return TRUE;
}
//-------------------------------------------------------------------------------------------------
Bool SalvageCrateCollide::executeCrateBehavior( Object *other )
{
- if( eligibleForArmorSet(other) )// No percent chance on this one, if you can get it, you get it.
+ // what a salvager takes off a wreck; everybody else takes the cash and leaves the parts
+ const Bool salvager = other->isKindOf( KINDOF_SALVAGER );
+
+ if( salvager && eligibleForArmorSet(other) )// No percent chance on this one, if you can get it, you get it.
{
doArmorSet(other);
@@ -83,7 +87,7 @@ Bool SalvageCrateCollide::executeCrateBehavior( Object *other )
soundToPlay.setObjectID( other->getID() );
TheAudio->addAudioEvent( &soundToPlay );
}
- else if( eligibleForWeaponSet( other ) && testWeaponChance() )
+ else if( salvager && eligibleForWeaponSet( other ) && testWeaponChance() )
{
doWeaponSet( other );
@@ -99,7 +103,7 @@ Bool SalvageCrateCollide::executeCrateBehavior( Object *other )
//soundToPlay.setObjectID( other->getID() );
//TheAudio->addAudioEvent( &soundToPlay );
}
- else if( eligibleForLevel( other ) && testLevelChance() )
+ else if( salvager && eligibleForLevel( other ) && testLevelChance() )
{
doLevelGain( other );
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp
index dc910cc29..dc8691b5e 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp
@@ -6251,6 +6251,24 @@ ProjectileUpdateInterface* Object::getProjectileUpdateInterface() const
// ------------------------------------------------------------------------------------------------
// Simply find the special power module that is currently allowing plotting of positions to target.
+// ------------------------------------------------------------------------------------------------
+// ------------------------------------------------------------------------------------------------
+// The building this object is in the middle of taking, and how far through it is. Asked of the
+// capturing unit because that is where the clock lives: a building being captured is told nothing
+// about it until it changes hands.
+// ------------------------------------------------------------------------------------------------
+Bool Object::getCaptureProgress( ObjectID *targetID, Real *progress ) const
+{
+ for( BehaviorModule** u = m_behaviors; *u; ++u )
+ {
+ SpecialPowerUpdateInterface *spInterface = (*u)->getSpecialPowerUpdateInterface();
+ if( spInterface && spInterface->getCaptureProgress( targetID, progress ) )
+ return TRUE;
+ }
+
+ return FALSE;
+}
+
// ------------------------------------------------------------------------------------------------
SpecialPowerUpdateInterface* Object::findSpecialPowerWithOverridableDestinationActive( SpecialPowerType type ) const
{
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/DockUpdate/SupplyWarehouseDockUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/DockUpdate/SupplyWarehouseDockUpdate.cpp
index 637573de9..4015f0d51 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/DockUpdate/SupplyWarehouseDockUpdate.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/DockUpdate/SupplyWarehouseDockUpdate.cpp
@@ -179,7 +179,19 @@ UpdateSleepTime SupplyWarehouseDockUpdate::update()
if( now < m_nextRegenFrame )
return ret;
- ++m_boxesStored;
+ /* One box at a time was money nobody noticed: a hundred dollars every forty seconds is less
+ than a harvester earns on the trip it takes to go and collect it, so a mined-out point stayed
+ mined out as far as anybody playing was concerned. A refill is worth six hundred now, which
+ is a trip worth making and a reason to keep somebody standing on the ground. */
+ const Int REGEN_CASH = 600;
+ const Int boxValue = TheGlobalData->m_baseValuePerSupplyBox;
+ Int boxes = ( boxValue > 0 ) ? ( REGEN_CASH / boxValue ) : 1;
+ if( boxes < 1 )
+ boxes = 1;
+ if( m_boxesStored + boxes > ceiling )
+ boxes = ceiling - m_boxesStored;
+
+ m_boxesStored += boxes;
m_nextRegenFrame = 0; // re-measured against the new count next time round
Drawable *draw = getObject()->getDrawable();
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/SpecialAbilityUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/SpecialAbilityUpdate.cpp
index 8cc2e928a..bdfb94893 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/SpecialAbilityUpdate.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/SpecialAbilityUpdate.cpp
@@ -597,10 +597,36 @@ Bool SpecialAbilityUpdate::isPowerCurrentlyInUse( const CommandButton *command )
return true;
}
}
-
+
return false;
}
+//-------------------------------------------------------------------------------------------------
+/** How far through taking a building this unit is, for the bar the building wears while it happens.
+ *
+ * m_prepFrames is the whole of the answer: it is set to the preparation length when the man
+ * reaches the door and counts down from there, and it is zero while he is still walking over and
+ * again once the building has changed hands. Two abilities take a building - a rifleman walking
+ * in and Black Lotus hacking one - and every other ability this module drives says nothing. */
+//-------------------------------------------------------------------------------------------------
+Bool SpecialAbilityUpdate::getCaptureProgress( ObjectID *targetID, Real *progress ) const
+{
+ if( !m_active || m_prepFrames == 0 || m_targetID == INVALID_ID )
+ return FALSE;
+
+ const SpecialPowerType type = getSpecialPowerType();
+ if( type != SPECIAL_INFANTRY_CAPTURE_BUILDING && type != SPECIAL_BLACKLOTUS_CAPTURE_BUILDING )
+ return FALSE;
+
+ const UnsignedInt total = getSpecialAbilityUpdateModuleData()->m_preparationFrames;
+ if( total == 0 || m_prepFrames > total )
+ return FALSE;
+
+ *targetID = m_targetID;
+ *progress = 1.0f - (Real)m_prepFrames / (Real)total;
+ return TRUE;
+}
+
//-------------------------------------------------------------------------------------------------
void SpecialAbilityUpdate::onExit( Bool cleanup )
{
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp
index 848fb21ac..2ef18fc67 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp
@@ -2126,12 +2126,19 @@ void GameLogic::startNewGame( Bool loadingSaveGame )
// Note - We construct the multiplayer start spot name manually here, so change this if you
// change TheKey_Player_1_Start etc. mdc
AsciiString startingCamName = TheNameKeyGenerator->keyToName(TheKey_InitialCameraPosition);
+ Bool watchingFromNowhere = FALSE;
if (game)
{
GameSlot *slot = game->getSlot(localSlot);
DEBUG_ASSERTCRASH(slot, ("Starting a LAN game without ourselves!"));
-
- if (slot->isHuman())
+
+ //
+ // An observer has no start position, so this built the name "Player_0_Start", found no such
+ // waypoint, and fell through to the corner of the map below - which is where every match
+ // watched from the stands used to open, looking at nothing.
+ //
+ watchingFromNowhere = slot->getPlayerTemplate() == PLAYERTEMPLATE_OBSERVER;
+ if (slot->isHuman() && !watchingFromNowhere)
{
Int startPos = slot->getStartPos();
startingCamName.format("Player_%d_Start", startPos+1); // start pos waypoints are 1-based
@@ -2142,7 +2149,7 @@ void GameLogic::startNewGame( Bool loadingSaveGame )
// update the loadscreen
updateLoadProgress(LOAD_PROGRESS_POST_STARTING_CAMERA);
- Waypoint *way = findNamedWaypoint(startingCamName);
+ Waypoint *way = watchingFromNowhere ? NULL : findNamedWaypoint(startingCamName);
if (way)
{
Coord3D pos = *way->getLocation();
@@ -2150,14 +2157,19 @@ void GameLogic::startNewGame( Bool loadingSaveGame )
}
else
{
- // Just look somewhere. lookAt does some terrain specific setup, so it is good
- // to call it. jba
+ //
+ // Nowhere of our own to look: watching rather than playing, or a map with no camera
+ // waypoint on it. The middle of the map is the one answer that is right for both of those,
+ // where the corner the game used to pick was right for neither.
+ //
+ Region3D extent;
+ TheTerrainLogic->getExtent( &extent );
Coord3D pos;
- pos.x = 50;
- pos.y = 50;
+ pos.x = extent.lo.x + extent.width() * 0.5f;
+ pos.y = extent.lo.y + extent.height() * 0.5f;
pos.z = 0;
TheTacticalView->lookAt( &pos );
- DEBUG_LOG(("Failed to find initial camera position waypoint %s\n", startingCamName.str()));
+ DEBUG_ASSERTLOG(watchingFromNowhere, ("Failed to find initial camera position waypoint %s\n", startingCamName.str()));
}
// Set up the camera height based on the map height & globalData.
@@ -4032,6 +4044,134 @@ static void peaceTimeTick( void )
}
}
+/* A civilian building is nobody's property and everybody's cover. Infantry take one, get burned
+ out of it, and the next squad inherits a wreck: no dozer will ever touch it, because a neutral
+ building is on no player's build list and a captured one is not on its captor's either. The
+ same goes for the tech buildings a match is fought over - an oil derrick changes hands four
+ times and spends the rest of the game at a tenth of its health.
+
+ So they mend themselves. Two seconds without a hit and the walls go back up, a fixed fraction
+ of full health a second, whether the building is standing empty, holding somebody's riflemen or
+ flying somebody's flag.
+
+ Once a second, off the same object walk peace time uses. Tech buildings and garrisonable
+ structures are the test; KINDOF_CAPTURABLE is not, because it sits on every faction structure
+ as well - Black Lotus takes those - and would hand every command center on the map a free
+ repair crew. */
+static void neutralBuildingRepairTick( void )
+{
+ const UnsignedInt now = TheGameLogic->getFrame();
+ if( now % LOGICFRAMES_PER_SECOND != 0 )
+ return;
+
+ const UnsignedInt quietFrames = 2 * LOGICFRAMES_PER_SECOND;
+ const Real repairFractionPerSecond = 0.03f;
+
+ for( Object *obj = TheGameLogic->getFirstObject(); obj != NULL; obj = obj->getNextObject() )
+ {
+ if( !obj->isKindOf( KINDOF_STRUCTURE ) || obj->isEffectivelyDead() )
+ continue;
+ if( obj->testStatus( OBJECT_STATUS_UNDER_CONSTRUCTION ) )
+ continue;
+
+ ContainModuleInterface *contain = obj->getContain();
+ const Bool mendsItself = obj->isKindOf( KINDOF_TECH_BUILDING )
+ || obj->isKindOf( KINDOF_TECH_BASE_DEFENSE )
+ || ( contain != NULL && contain->isGarrisonable() );
+ if( !mendsItself )
+ continue;
+
+ BodyModuleInterface *body = obj->getBodyModule();
+ if( body->getHealth() >= body->getMaxHealth() )
+ continue;
+ if( body->getLastDamageTimestamp() + quietFrames > now )
+ continue;
+
+ obj->attemptHealing( body->getMaxHealth() * repairFractionPerSecond, obj );
+ }
+}
+
+/** A unit that can still take something off a wreck besides the money in it. */
+static Bool wantsSalvageUpgrade( const Object *obj )
+{
+ if( obj->isKindOf( KINDOF_WEAPON_SALVAGER ) && !obj->testWeaponSetFlag( WEAPONSET_CRATEUPGRADE_TWO ) )
+ return TRUE;
+ if( obj->isKindOf( KINDOF_ARMOR_SALVAGER ) && !obj->testArmorSetFlag( ARMORSET_CRATE_UPGRADE_TWO ) )
+ return TRUE;
+
+ return FALSE;
+}
+
+/* Somebody goes and gets the salvage. A crate dropped by a wreck is money and a free upgrade lying
+ on the ground, and the game asked you to notice it, work out which of your units was allowed to
+ take it, and drive that one over it by hand, in the middle of the fight that made it. Nobody
+ does that, so most salvage on most maps timed out where it fell.
+
+ Whoever is standing nearest and has nothing else to do goes and takes it, once a second. A unit
+ that can still be upgraded off it wins over one that cannot, however far back it is standing,
+ because the upgrade is worth more than the walk; failing that the nearest idle unit takes the
+ cash. Only idle units, so this never pulls a unit out of a fight or off an order, and the trip
+ itself makes the unit busy, which is what stops it being ordered again on the next pass.
+
+ A dozer and a harvester are left alone: both have a job of their own that earns more than the
+ crate does. An aircraft is left alone too, because a crate cannot be claimed from the air. */
+static void salvageCrateTick( void )
+{
+ const UnsignedInt now = TheGameLogic->getFrame();
+ if( now % LOGICFRAMES_PER_SECOND != 0 )
+ return;
+
+ const Real SALVAGE_CALL_RADIUS = 250.0f;
+
+ for( Object *crate = TheGameLogic->getFirstObject(); crate != NULL; crate = crate->getNextObject() )
+ {
+ if( !crate->isSalvageCrate() || crate->isDestroyed() )
+ continue;
+
+ PartitionFilterAlive alive;
+ PartitionFilterSameMapStatus sameMap( crate );
+ PartitionFilter *filters[] = { &alive, &sameMap, NULL };
+
+ SimpleObjectIterator *iter = ThePartitionManager->iterateObjectsInRange( crate, SALVAGE_CALL_RADIUS,
+ FROM_CENTER_2D, filters, ITER_SORTED_NEAR_TO_FAR );
+ MemoryPoolObjectHolder hold( iter );
+
+ Object *collector = NULL;
+ Bool collectorUpgrades = FALSE;
+ for( Object *them = iter->first(); them != NULL; them = iter->next() )
+ {
+ if( them->isKindOf( KINDOF_STRUCTURE ) || them->isKindOf( KINDOF_AIRCRAFT ) )
+ continue;
+ if( them->isKindOf( KINDOF_DOZER ) || them->isKindOf( KINDOF_HARVESTER ) )
+ continue;
+ if( them->isContained() || them->isEffectivelyDead() || them->isNeutralControlled() )
+ continue;
+
+ AIUpdateInterface *ai = them->getAI();
+ if( ai == NULL || !ai->isIdle() )
+ continue;
+
+ const Player *owner = them->getControllingPlayer();
+ if( owner == NULL || crate->getShroudedStatus( owner->getPlayerIndex() ) >= OBJECTSHROUD_FOGGED )
+ continue;
+
+ const Bool upgrades = wantsSalvageUpgrade( them );
+ if( collector == NULL || ( upgrades && !collectorUpgrades ) )
+ {
+ collector = them;
+ collectorUpgrades = upgrades;
+ }
+
+ // the iterator runs near to far, so the first one that can be upgraded is the best answer
+ if( collectorUpgrades )
+ break;
+ }
+
+ if( collector )
+ collector->getAI()->aiMoveToPosition( crate->getPosition(), CMD_FROM_AI );
+ }
+}
+
void GameLogic::update( void )
{
USE_PERF_TIMER(GameLogic_update)
@@ -4108,6 +4248,12 @@ void GameLogic::update( void )
// the lobby's peace time, if the host set one
peaceTimeTick();
+ // and the buildings nobody repairs
+ neutralBuildingRepairTick();
+
+ // ... and the salvage nobody collects
+ salvageCrateTick();
+
/* The scripted measurement harness. Keyed to the logic frame rather than to the render pass, so the same
scenario file plays out on the same frames however fast the machine draws - which is the whole
point of measuring two builds against it. */
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DProjectedShadow.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DProjectedShadow.cpp
index 9da5c34b2..1d0675c5e 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DProjectedShadow.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DProjectedShadow.cpp
@@ -924,7 +924,33 @@ void W3DProjectedShadowManager::queueDecal(W3DProjectedShadow *shadow)
//Find size of heightmap sub-rectangle affected by shadow
//If user supplied size values, ignore bounding box
- objPos.Z=0.0f; //we don't care about object height since shadows project top-down
+ /* An aircraft's shadow belongs where the sun puts it, not underneath the aircraft. A decal is
+ laid flat on the terrain and this used to throw the object's height away, so a Raptor at a
+ hundred feet towed its shadow along directly below itself - the one place the sun cannot
+ put it outside of noon on the equator, and the thing that makes a plane read as a sticker
+ on the map rather than as something flying over it.
+
+ So the decal slides down the ray to the sun by as much as the object's height asks for.
+ Anything standing on the ground is unmoved, because its height is nought; a helicopter
+ drifts its shadow out to the side, and a plane's shadow runs along well ahead of or behind
+ it depending on the hour the map is set at.
+
+ Not for something on a bridge: that decal is already drawn at the bridge's own height, and
+ sliding it sideways would drop the shadow in the river. */
+ if (layerHeight == 0.0f && TheW3DShadowManager != NULL && TheTerrainLogic != NULL)
+ {
+ const Real heightAboveGround = objPos.Z - TheTerrainLogic->getGroundHeight(objPos.X, objPos.Y);
+ const Vector3 &toSun = TheW3DShadowManager->getLightPosWorld(0);
+ const Real MIN_SUN_HEIGHT = 0.01f; // a sun on the horizon casts a shadow of infinite length
+ if (heightAboveGround > 0.0f && toSun.Z > MIN_SUN_HEIGHT)
+ {
+ const Real alongRay = heightAboveGround / toSun.Z;
+ objPos.X -= toSun.X * alongRay;
+ objPos.Y -= toSun.Y * alongRay;
+ }
+ }
+
+ objPos.Z=0.0f; //the decal itself is flat on the terrain
uVector=objXform.Get_X_Vector();
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cpp
index 918c2da8e..6d0cd8180 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cpp
@@ -2029,6 +2029,16 @@ void W3DVolumetricShadow::Update()
if (fabs(pos.Z - groundHeight) >= AIRBORNE_UNIT_GROUND_DELTA)
{
Real extent = MAX_SHADOW_LENGTH_EXTRA_AIRBORNE_SCALE_FACTOR * m_robjExtent;
+
+ //a shadow cast by the real sun lands off to one side of the aircraft, as far out as its
+ //height asks for, so an aircraft just off screen can still have its shadow on it
+ const Vector3 &lightPos = TheW3DShadowManager->getLightPosWorld(0);
+ const Real lightXY = sqrt(lightPos.X*lightPos.X + lightPos.Y*lightPos.Y);
+ Real lightZ = lightPos.Z;
+ if (lightXY * m_shadowLengthScale > lightZ)
+ lightZ = lightXY * m_shadowLengthScale;
+ if (lightZ > 0.0f)
+ extent += fabs(pos.Z - groundHeight) * lightXY / lightZ;
if (WWMath::Fabs(pos.X - bcX) > (beX + extent) ||
WWMath::Fabs(pos.Y - bcY) > (beY + extent) ||
WWMath::Fabs(pos.Z - bcZ) > (beZ + extent))
@@ -4207,10 +4217,26 @@ W3DVolumetricShadow* W3DVolumetricShadowManager::addShadow(RenderObjClass *robj,
robj->Get_Obj_Space_Bounding_Sphere(sphere);
shadow->setRenderObjExtent(sphere.Radius*MAX_SHADOW_LENGTH_SCALE_FACTOR);
+ /* Every aircraft EA shipped asks for ShadowSizeX = 89, a sun no lower than 89 degrees, so every
+ plane and helicopter cast its shadow straight down and towed it along underneath itself at any
+ height - while the tank beside it was lit by the map's real sun and threw its shadow off to the
+ side. An aircraft takes the same sun as everything else now, so its shadow lands where the
+ sun puts it and slides out from under it as it climbs. The floor only lifts a sun lower than
+ AIRCRAFT_MIN_SUN_ELEVATION, so a dusk map does not throw a Comanche's shadow across half the
+ screen. */
+ const Real AIRCRAFT_MIN_SUN_ELEVATION = 30.0f;
+ Drawable *owner = draw;
+ if (owner == NULL && robj->Get_User_Data())
+ owner = ((DrawableInfo *)robj->Get_User_Data())->m_drawable;
+
+ Real sunElevation = shadowInfo->m_sizeX;
+ if (owner && owner->isKindOf(KINDOF_AIRCRAFT) && sunElevation > AIRCRAFT_MIN_SUN_ELEVATION)
+ sunElevation = AIRCRAFT_MIN_SUN_ELEVATION;
+
Real sunElevationAngleTan = 0;
- if (shadowInfo->m_sizeX)
+ if (sunElevation)
{ //need to adjust sun elevation for this model in order to limit shadow length
- sunElevationAngleTan=tan(shadowInfo->m_sizeX/180.0f*PI);
+ sunElevationAngleTan=tan(sunElevation/180.0f*PI);
}
shadow->setShadowLengthScale(sunElevationAngleTan);