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): drive routes as a measured band behind -crowd

Olcay Seygand7172649cd22
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 11a91f059..81a172c10 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -478,6 +478,24 @@ found and fixed — EA's own, not port damage.**
- A group sent across the map plans its corridor from the member already closest to where you
clicked, not from the one nearest the middle of the group. Planning from the middle made everyone
ahead of it drive backwards to join, straight across the rest of the group.
+- A route is now a width, not a line. Every unit used to steer at the exact middle of the ground it
+ had been given, which is why twenty tanks sent across an empty field arrived in single file: they
+ were all aiming at the same metre of it. Each unit now holds its own position across whatever
+ width the ground allows beside it, measured where it is standing rather than fixed when the order
+ was given, so an open field is crossed as a wide front and a bridge squeezes the same units back
+ into a line without anybody deciding to queue. The width closes back onto the middle over the last
+ few squares, so everyone still parks where you sent them.
+- The position a unit takes across that width is the one it already had. A group you dragged a box
+ round is spread out before it starts moving, and whoever was on the left of it stays on the left
+ the whole way there. The spread is proportional, so a selection two hundred feet across arrives as
+ a front rather than as two files pressed against the edges, and nothing is replaced by a formation
+ nobody asked for. The unit keeps that line until it arrives; there is no slow drift back to the
+ middle, which was the first version of this and was exactly what pulled a group back into single
+ file a few seconds after it set off.
+- A tank stuck behind a slower one now pulls out and goes past, if there is room beside the route to
+ do it in. It holds the new line for a second and a half so it does not weave, and gives up a
+ little speed while it crosses over. Nothing here costs a new route: the road is the same, only the
+ part of it the tank drives on changes.
- Measured over twenty seven-minute four-way battles on the same twenty maps: time spent standing
behind another unit fell 31%. Over six 4v4 battles, where every unit is on one of two fronts, it
fell 38%, units left properly stuck fell by half, and the worst single frame of a match went from
@@ -582,7 +600,28 @@ found and fixed — EA's own, not port damage.**
- Every knob in it is one switch away from off, and the switch is in the same executable, because a
batch of matches only argues something if both halves of it were built by the same compiler on the
same afternoon.
-- Group movement was also asked one more question and answered no. The idea was to stop treating the route as a line and treat it as a band: every unit holds a sideways position inside it and drifts away from whichever side ahead is busiest, so a queue drains outwards where there is room and files up where there is not. It was built in the movement sandbox and measured against the columns the game ships, 96 layouts counted one at a time, at four different drift speeds. It is worse at every speed, and steadily worse the harder it pushes. The columns stay.
+- Group movement was also asked one more question and answered no, then asked it again with one piece changed and answered yes. The idea was to stop treating the route as a line and treat it as a band. The first version had every unit drift away from whichever side ahead was busiest; that was built in the movement sandbox, measured against the columns the game ships over 96 layouts one at a time at four drift speeds, and it was worse at every speed and steadily worse the harder it pushed. What was missing was a reason to move sideways at all beyond a crowd reading. The version that shipped keeps the band and throws the drift away: a unit changes its line only when something slower is actually in front of it.
+- The first attempt at the band did nothing at all, and looked like it worked. Each unit was to take its line from its own sideways distance to its own route, which is zero for every unit that ever existed: a unit's route starts under its own tracks. So every one of them came out on the centre line, the band was measured correctly and nobody was ever put anywhere in it, and the only thing left moving units sideways was the overtaking rule. It only showed up on screen, twenty-five tanks still collapsing into one column with all the machinery switched on. The line now comes from the group that gave the order, which is the only thing that knows the group has a shape, and it is handed down as a fraction of the group's own width rather than in feet, so a wide selection maps onto a narrow road instead of everybody piling up against the two edges.
+- Paired with that, the drift back to the middle came out. It moved every unit 0.8% of the way to the same line every frame, which over four seconds is the whole spread, and it was fighting the thing it shipped alongside. Arrival is already handled by the band closing over the last few squares.
+- The charge for driving through a queue was then doubled, to the weight the sandbox this was designed in opens at, and the game got worse at exactly the thing the charge is for: twelve four-way battles, time spent standing behind another unit up 64%, five of twelve maps worse and none better, one of them from 770 unit-frames to 2,968. Search got cheaper doing it - a tenth fewer squares looked at, a sixth less time - which is the tell: the routes are being decided sooner and further away from the queue, so a unit commits to a detour before it knows whether the queue was worth avoiding. The two weights are not the same quantity either, and calling them both four is a coincidence of naming - the sandbox's traffic value grows without limit and fades, the game's is capped. It is one number to put back. Measured again after the band was widened and re-anchored, it is still the wrong number, and now for a reason worth writing down: on the twelve-match average it looks 20% better, and seed by seed it wins one map and loses four. The average is one map - a single battle that went from 4,389 unit-frames of standing still down to 1,563 - carrying eleven others in the other direction, and on one of those the units that jammed against each other and both stopped went from 7 to 129.
+- The band is not free of doubt, and the self-play harness is close to blind to it. Twelve four-way battles with it on and off: time spent standing behind another unit identical to three figures, the worst single frame of a match 69ms down to 28ms, and units left properly stuck 0.8 a match up to 2.9. That last column is the one the earlier overtaking attempt was thrown out over. A computer opponent moves five units at a time and never drags a box round twenty-five tanks, so the case the band is for is the case the harness does not play - the same reason the first group-movement attempt could not be measured. Both the band and the passing are one switch away from off, and twelve matches is not a result.
+- With the band finally visible, it turned out to be three tanks wide. Measured over a four-player match it came out 77 feet across, and a tank is 24 of those, so a selection of twenty-five had nowhere to go and squeezed back into a column the moment they touched. The ground is now measured twice as far to each side, and the line each unit is given is a distance rather than a share of the group: members are sorted across the direction they are travelling and spaced by the width of the largest body among them, with the count of lanes capped at what the widest band can hold and everybody else queueing behind in order. A tight blob and a wide box now leave in the same shape, and a doorway still puts them back in single file because the offsets scale with the room actually found.
+- Widening it exposed a second mistake, worth 10% of the time units spend standing still: the middle of the band was the middle of the free ground rather than the route itself. On a road with a cliff one side and a field the other, a unit that had never been given a line at all slid up to seventy-five feet off its own route. The two halves of the band are now measured separately and meet on the route. Twelve four-way battles: time spent blocked down 34%, from 770 unit-frames a match to 464.
+- Watching the wide band in game found three more things wrong with it, and fixing them took time spent standing still down another 30%, from 464 unit-frames a match to 324, with units left properly stuck against each other down from 11.7 a match to 2.7. A tank reaching a corner used to stop there and rotate on the spot: its line was being measured sideways to the direction it came in on, while the point it was steering at had already moved past the turn onto the next stretch, so on a sharp bend the game was aiming it at somewhere behind itself. The line is now measured against whichever stretch the steering point is actually on, and any offset that lands behind the unit is thrown away rather than driven at. A group ordered onto one spot used to arrive spread across it instead of gathering on it, because the band only finished closing at the goal itself - it now shuts thirty feet short of it, and starts closing fifty feet earlier to have room to do it in.
+- The third one is why a jam stayed a jam. A unit only tried to go round something in front of it if that thing was slower than it, and it asked the question by comparing engines rather than speedometers - so a column of identical tanks nose to tail, every one of them crawling and every one of them reporting full speed, never passed anybody at all. It is the actual speed now, which is the one case the passing rule was written for and the one case it refused to fire in.
+- Closing the band through corners was tried at the same time and thrown out: scaling the offset by how sharp the bend is sounds right, and it more than tripled the time units spend blocked, 32 unit-frames per 1000 to 102 over twelve battles. A route bends constantly, and a band that shuts at every bend is single file for most of its length.
+- A group you send somewhere now travels as a crowd rather than a queue, behind its own switch. Each unit holds a measured line across the road instead of the middle of it, moves over for a bigger unit coming up behind, pulls round something slower in front when there is room beside it, spreads out at the back of a jam and closes up again when it clears, and slows down only for traffic it is actually catching. It applies to orders given to more than one unit, because a single vehicle repositioning inside a firefight has nobody to share a road with, and the rules cost it real time when it was included: with every unit in the game steering this way the time spent standing behind another unit came out at 108 unit-frames per 1000 rather than 29.
+- Two things the crowd did that no measurement could see, both of them tanks rotating on the spot instead of driving. Moving over for someone names a line a full body away, and taking it in one frame swings the point the unit is aiming at some twenty-five feet sideways two squares in front of its tracks, which is not a turn a tank can make: it stops, rotates, and by the time it is facing the new line the unit it was moving over for has gone past. A unit now slides into its new line at a quarter of the speed it is driving, which is about twenty degrees of steering. The second was the aiming point landing behind the unit - shoved out of a queue, or carried past its own lookahead through a bend - and the tank turning round and driving at it, which is the rocking back and forth. The point is now walked forward along the route until it is genuinely in front. The self-play harness reports both of these as no change at all, to three figures across sixteen battles, which is what a fix to something only the camera can see looks like.
+- Two more places where the crowd was told the right thing one frame at a time and shook itself apart doing it. Keeping out of a neighbour's way is measured every frame against whatever is nearest, and whatever is nearest changes the moment two units cross, so the push each unit felt jumped from one side to the other between frames and the tank sat there twitching. The push is now averaged over about a quarter of a second, which is longer than the swap and shorter than anything a player can see. The other is the steering itself: a tank was being handed a new heading every frame with no memory of the last one, so a hundred small corrections became a wobble down the length of a column. It now turns towards the point it wants at a fixed rate rather than snapping to it, a quarter of the difference per frame while it is cruising and two thirds when something is actually in its way, because a unit dodging a collision cannot afford a smooth turn. Under two degrees off it holds the wheel still instead of chasing the last of the error, which is the difference between a tank standing still and a tank trembling.
+- The one tank in thirty that stops for good now gets itself out. A unit that has asked to move and covered no ground for two seconds is not in traffic, it is wedged: between two allies it never quite touches, in the corner of a cliff, behind the one vehicle in the column that is never going to move again. Nothing counted it as blocked, because there was no collision to count, so nothing came to its rescue and it sat there for the rest of the battle. It now measures its own progress against the speed it asked for, and the answer has two rungs. A third of a second of getting nowhere and it stops being polite: no giving way, no moving over, no braking, no spreading out, all of which were costing it the speed it needs to push through. Two seconds and it backs out, to the side and behind, and tries the road again from there. Failing that it turns round. If it is walled in on all four sides it keeps trying and asks again a second later.
+- Moving over for someone and joining a road are the same manoeuvre from two sides, and the crowd now does both. A unit coming in at an angle used to be invisible until it was in front of you, at which point everybody braked; the units already on the road now see it crossing their line up to a second and a half ahead and shift a lane over instead, which is what turns a queue into a zipper. The test is a real closest approach rather than a cone, and the courtesy is only extended to traffic that would have made you brake anyway - anything looser and a column spends the whole march shuffling sideways for vehicles driving vaguely alongside it.
+- Three ways of building that were measured and thrown away, one of them expensive. Slowing down by how far away the traffic in front is, rather than by whether it is being caught, costs 3518 unit-frames of standing still a battle against 1236. Slowing down behind a unit that is not moving at all costs 16593, and it is the worst kind of bug: braking short of a parked ally means the collision never happens, so nothing counts the unit as blocked and none of the machinery that would have sent it round fires. It dies politely, three feet behind a tank that is never going to move. And standing the rules down for short trips, on the theory that a four-square shuffle inside a fight is not a march, is three times worse than leaving them on: short trips are exactly where units are packed tightest.
+- Light vehicles could not hold a straight line: the head of a scout shook the whole way down a road an Overlord drove dead straight. The point a unit steers at sat two cells and a body ahead, taken from whichever sample of the route it happened to be beside, and both halves of that were wrong for a fast chassis. Samples are a cell apart, so the point jumped ten feet forward each time the unit crossed one and the heading jumped with it; it is taken between samples now, off the unit's own unrounded distance along the route, and slides forward a foot at a time. The other half is that thirty feet of warning is forty frames of road for an Overlord and ten for a scout, so the light stuff was steering at something under its nose where a foot of error is a full lock. Moving the point further out for fast units cured the shake and cost four times the units left stuck - a point fifty feet up the road is measured against the ground fifty feet up the road, and nobody asks about the narrow bit in between - so the chassis difference is dealt with in the wheel instead. The rate a unit turns towards its heading is now cut by how much of that thirty feet it eats in half a second: unchanged for anything heavy, about halved for a scout. It is a lag rather than a different place to drive at, which is the part the other version got wrong.
+- Vehicles walked off the side of bridges and queued up beside the entrance to them instead of driving on. A unit driving in a crowd holds a line a set distance off the middle of the road, and the road's width is measured by asking the ground either side whether a tank fits on it. On a bridge that question was being asked of the riverbank underneath. So the road read as sixty feet wide over a deck barely wide enough for two tanks, and a line held a body width off centre walked a column into the water - and on the approach, the same line put the leading tank against the abutment rather than the entrance, with everybody behind it stopped on the bank. The width is now measured on the deck the route actually runs over, and both the bridge and forty feet of road each side of it have no width at all: every unit drives the middle of the road across a bridge, which is what the crossing is for.
+- Infantry can walk through infantry again. Two soldiers crossing have never blocked each other in this game - only two going the same way do - and the crowd rules had quietly taken that back: a squad crossing another squad read as a wall, and every man in it braked, gave way and shuffled sideways for a crowd he was supposed to walk straight into. The crowd now uses the game's own rule for that, so a column following a column is still traffic and two squads crossing pass through one another.
+- None of the crowd was being measured, and the numbers written here for it were another rule's. A unit steers as part of a crowd only if it was handed a line across the road, a line is handed out only by the order a player gives to a selection, and a computer opponent never gives that order: it moves its teams one vehicle at a time. So every self-play batch run to argue about the crowd was driving the two rules that live in the collision code and none of the steering. The harness now has a switch that hands every army on the map one group order every twenty seconds, to alternating corners. The match it produces is nonsense and its result says nothing, but it multiplies the time units spend standing still by fourteen, from around 300 unit-frames a match to 4,200, which is the proof it is finally creating the traffic the crowd was written for.
+- With the traffic there, the crowd steering does not pay for itself. Thirty-nine battles paired map by map: time spent standing behind another unit 4,444 unit-frames a match with the rules off against 4,787 with them on, 7.7% worse, eleven maps better and twenty worse. The middle map moved by 19 unit-frames either way, so that average is four bad maps carrying thirty-five that barely noticed. What it does fix is the thing it was asked to fix. Units left properly stuck fell from 3.0 a match to 1.4, and the maps that moved are the pathological ones: 62 units wedged for good down to none, 35 down to none, 7 down to none. It creates new ones elsewhere, one map going from 5 to 34. The switch stays off, and what needs explaining now is the four maps, not the average.
+- Since the first attempt at the band failed silently and passed every test it had, the band can now be drawn. A switch puts each moving unit's route on the ground in blue, the line it holds as a yellow mark sideways from the unit, and the offset that survived as a green mark from the route out to where the unit is actually aiming. The three failures that look identical from the camera - a line never given out, a line given out and dropped on the way, a line applied but too small to see - are three different pictures under it, and the same run writes them to the log as well.
---
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h
index dff8e383f..c1a6504aa 100644
--- a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h
+++ b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h
@@ -379,6 +379,10 @@ public:
Real m_slowFrameMS; ///< -slowframe <ms>: a logic frame over this long logs its own breakdown (default 20)
Int m_aiSliceFrames; ///< -aislice <n>: a unit's AI decides once every n logic frames, staggered by id (1 = every frame, the default)
Bool m_noFlowPath; ///< -noflowpath: price terrain only, the way retail does - no clearance, traffic or crossing cost
+ Bool m_noLanePath; ///< -nolanes: follow the centre of the route, the way retail does - no band, no lane, no passing
+ Bool m_showLanes; ///< -showlanes: draw every moving unit's route, the lane it was handed and the offset it kept
+ Bool m_crowdModel; ///< -crowd: the sandbox crowd model - corridor, absolute lanes, right of way, give way, fan out
+ Int m_groupDrill; ///< -groupdrill <n>: every n frames, order each player's army corner to corner as one group (0 = off)
AsciiString m_netGameHosts; ///< -netgame <ip>[,<ip>...]: the slot list of a LAN game started from the command line (empty = off)
Int m_netGameLocalSlot; ///< -netslot <n>: which of those addresses this copy of the game is
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h
index ae8f59435..6dca01a82 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h
@@ -222,6 +222,27 @@ public:
/// Given a location, return nearest location on path, and along-path dist to end as function result
void peekCachedPointOnPath( Coord3D& pos ) const {pos = m_cpopOut.posOnPath;}
+ /** How far along the route was still left, last time anybody asked. Priority in the crowd model
+ is decided on this, and recomputing it for every neighbour of every unit would be the same
+ walk over the same node list a hundred times a frame. Only meaningful once
+ hasCachedPointOnPath() is true. */
+ Real peekCachedDistToGoal( void ) const { return m_cpopOut.distAlongPath; }
+
+ /** True once computePointOnPath has run at least once on this path, which is the only state in
+ which the cached point above means anything. Read by the -showlanes overlay. */
+ Bool hasCachedPointOnPath( void ) const { return m_cpopValid; }
+
+ /** Throw away the cached steering point. computePointOnPath reuses its answer for up to
+ MAX_CPOP frames while the unit barely moves, which is right for a unit following the same
+ line and wrong the frame it decides to take a different one. */
+ void invalidateCachedPointOnPath( void ) { m_cpopValid = false; }
+
+ /** The point on the optimized route closest to `pos`, and the unit direction of the segment it
+ sits on. This is the geometry the lane code works in and nothing else: it does no steering,
+ no passability check and no caching, so it is safe to call from outside a locomotor pass.
+ False if the path is empty or has a single node, in which case there is no direction. */
+ Bool closestPointAndDir( const Coord3D& pos, Coord3D *ptOut, Coord2D *dirOut ) const;
+
/// Given a flight path, compute the distance to goal (0 if we are past it) & return the goal pos.
Real computeFlightDistToGoal( const Coord3D *pos, Coord3D& goalPos );
@@ -685,7 +706,7 @@ enum
PF_TRAFFIC_DECAY_DEN = 64,
PF_TRAFFIC_DECAY_FRAMES = 3,
PF_TRAFFIC_FULL = 192, ///< traffic at or above this is as expensive as it gets
- PF_TRAFFIC_NUM = 2, ///< peak traffic penalty is NUM/DEN of a step
+ PF_TRAFFIC_NUM = 4, ///< peak traffic penalty is NUM/DEN of a step - the sandbox's traffic weight
PF_TRAFFIC_DEN = 1,
PF_TRAFFIC_CELLS = 4096, ///< live traffic cells tracked; past this, deposits are dropped
@@ -704,7 +725,28 @@ enum
charge is invisible to the estimate, so leaving the estimate alone leaves the search with
no reason to walk towards the goal rather than round it. */
PF_HEURISTIC_FLOW_NUM = 9,
- PF_HEURISTIC_FLOW_DEN = 4
+ PF_HEURISTIC_FLOW_DEN = 4,
+
+ /* Lanes. The three maps above decide where a route goes; these decide where across it a unit
+ drives. PROBE is how far sideways the ground is measured before the band is called wide
+ enough, in cells; TAPER is how close to the goal the band closes back onto the centre so
+ every unit can still reach the cell reserved for it; HOLD is how long a lane taken to get
+ round somebody is kept before the unit drifts back toward the middle.
+
+ PROBE was 8 and that was too small to see: measured over a four-player match the band came
+ out 77 world units wide, and a tank is 24 of those, so the whole band was three tanks and a
+ selection of twenty-five had nowhere to go. 16 cells is 160 a side before the body's own
+ radius comes off it, which is about ten tanks abreast where the ground allows it and exactly
+ what it was before where it does not. TAPER moved with it: the band now opens wider, so it
+ needs longer to close again before the goal. */
+ PF_LANE_PROBE_CELLS = 16,
+ PF_LANE_TAPER_CELLS = 12,
+ /* The band is shut, not merely narrowing, over the last few cells. A taper that only reaches
+ zero at the goal itself leaves a unit seventy feet off its own route still twenty feet off
+ it when it arrives, and a group ordered onto one point spreads out instead of gathering on
+ it - which is what the ramp looked like in game. */
+ PF_LANE_CLOSE_CELLS = 3,
+ PF_LANE_HOLD_FRAMES = 45 ///< a second and a half at 30 logic frames
};
/** How much extra a step into a cell with this clearance costs a body needing `needClearance`.
@@ -717,6 +759,41 @@ extern Int Pathfinder_trafficCost( Int baseCost, Int traffic );
/// How much extra a step into a cell somebody else wants at the same moment costs.
extern Int Pathfinder_crossingCost( Int baseCost, Int claimHalves );
+/** Where across a band a body sitting `lateral` world units left of the centre line rides.
+ 0 is hard against the right edge, 1 hard against the left, 0.5 the centre; clamped just
+ inside both edges so a lane is never the wall itself. Half-widths of zero give 0.5. */
+extern Real Pathfinder_laneFraction( Real lateral, Real leftExtent, Real rightExtent );
+
+/// The sideways offset, in world units left of the centre line, that lane fraction `u` means.
+extern Real Pathfinder_laneOffset( Real u, Real leftExtent, Real rightExtent );
+/** Where across the band a group member riding `lateral` world units left of its route's centre
+ line belongs, against the widest band the probe can ever find rather than against the width
+ this particular piece of ground turns out to have.
+
+ Measuring it against the group's own width was the previous answer and it was wrong twice
+ over: a tightly packed selection has almost no width, so every member came out near the
+ centre, and a wide one has more width than any road, so every member came out against an
+ edge. Neither has anything to do with how much room a tank needs. Against a fixed
+ reference the offset means feet, the caller can space members a body apart, and a narrow
+ road still squeezes them - laneOffset scales the fraction by the room actually found, so
+ half the band is half the offset. */
+extern Real Pathfinder_groupLane( Real lateral );
+
+/// The widest half-band the probe can report, which is what Pathfinder_groupLane measures against.
+extern Real Pathfinder_laneReference( void );
+
+/** How much of a lane is left this many world units short of the end of the route: all of it
+ beyond PF_LANE_TAPER_CELLS, none of it inside PF_LANE_CLOSE_CELLS, straight line between. */
+extern Real Pathfinder_laneTaper( Real remaining );
+
+/* There is no lane-bend factor here on purpose. Pinching the band shut through a turn - scaling
+ the offset by the cosine between the two headings - sounds right and measures terrible: twelve
+ four-player matches went from 32 blocked unit-frames per 1000 to 102, because a route bends
+ constantly and closing the band at every bend puts the whole group back into single file for
+ the length of each one. The corner problem is that the offset was being measured against the
+ wrong heading, and computePointOnPath fixes that by taking the heading at the steering point
+ and refusing a lane point that lands behind the unit. */
+
/// The A* estimate's scale factor over plain octile distance, set per search by beginFlowSearch.
extern Int thePathHeuristicNum;
extern Int thePathHeuristicDen;
@@ -908,6 +985,14 @@ public:
Bool validMovementPosition( Bool isCrusher, PathfindLayerEnum layer, const LocomotorSet& locomotorSet, const Coord3D *pos ); ///< Return true if given position is a valid movement location
Bool validMovementTerrain( PathfindLayerEnum layer, const Locomotor* locomotor, const Coord3D *pos ); ///< Return true if given position is a valid movement location
+ /** How far sideways, in world units, a body could slide from `from` along `dir` before the
+ ground stops taking it. Half-cell steps out to PF_LANE_PROBE_CELLS, then the body's own
+ radius taken off the answer so a wide tank is not offered the last passable cell as a lane.
+ This is the width of the band the route runs down, measured where the unit is now rather
+ than stored with the path: the terrain under a route changes while units are on it. */
+ Real laneExtent( const Object *obj, const LocomotorSet& locomotorSet, PathfindLayerEnum layer,
+ const Coord3D *from, const Coord2D *dir );
+
Locomotor* chooseBestLocomotorForPosition(PathfindLayerEnum layer, LocomotorSet* locomotorSet, const Coord3D* pos );
Bool isViewBlockedByObstacle(const Object* obj, const Object* objOther); ///< Return true if the straight line between the given points contains any obstacle, and thus blocks vision
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/CrowdModel.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/CrowdModel.h
new file mode 100644
index 000000000..b6d941ff1
--- /dev/null
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/CrowdModel.h
@@ -0,0 +1,172 @@
+/*
+** Command & Conquer Generals Zero Hour(tm)
+** Copyright 2025 Electronic Arts Inc.
+**
+** This program is free software: you can redistribute it and/or modify
+** it under the terms of the GNU General Public License as published by
+** the Free Software Foundation, either version 3 of the License, or
+** (at your option) any later version.
+**
+** This program is distributed in the hope that it will be useful,
+** but WITHOUT ANY WARRANTY; without even the implied warranty of
+** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+** GNU General Public License for more details.
+**
+** You should have received a copy of the GNU General Public License
+** along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+// FILE: CrowdModel.h //////////////////////////////////////////////////////////////////////////
+// The route as a band of measured width, and the rules a unit uses to decide where across it to
+// drive. Everything here is behind -crowd; without it none of it is built or consulted.
+//
+// The band is the part retail has no equivalent of. A route is a line, every unit handed one
+// steers at the same metre of it, and a group of twenty crossing open ground therefore drives in
+// single file for no reason anybody chose. A corridor measures how much ground there actually is
+// either side of that line, sample by sample, and then a lane is a distance across it - not a
+// share of it. The distinction is not cosmetic: a fraction of the width pulls units into every
+// wide bay the route passes and swings them backwards round the outside of corners, which is what
+// the first version of this did.
+//
+// Author: fork, 2026
+///////////////////////////////////////////////////////////////////////////////////////////////
+
+#pragma once
+
+#ifndef _CROWD_MODEL_H_
+#define _CROWD_MODEL_H_
+
+#include "Lib/BaseType.h"
+#include "Common/GameType.h"
+#include "GameLogic/LocomotorSet.h"
+
+#include <vector>
+
+class Object;
+class Path;
+
+enum
+{
+ /* How far sideways the corridor looks for ground, in cells. The sandbox uses ten and so does
+ this; a wider probe is not a wider road, it just costs more and finds the far side of open
+ country, which no lane is ever going to use. */
+ CROWD_PROBE_CELLS = 10,
+
+ /// samples are one cell apart until the route is longer than this, then they stretch
+ CROWD_MAX_SAMPLES = 160,
+
+ /// a lane taken to get round somebody is held this long, so it cannot flap side to side
+ CROWD_HOLD_FRAMES = 45,
+
+ /// how many samples either side of a bridge lose their band as well, so the approach funnels in
+ CROWD_BRIDGE_SEAL = 4,
+
+ /// how far ahead of itself a unit steers, in cells, before its own body length is added
+ CROWD_LOOKAHEAD_CELLS = 2
+};
+
+/**
+ * A route, sampled, with the width of the drivable ground either side of every sample.
+ *
+ * Built once when a unit is handed a path and thrown away with it. The probing is the expensive
+ * part (twenty cell tests a sample) which is why it is not done per frame, and why the sample
+ * count is capped rather than the step being fixed.
+ */
+class CrowdCorridor
+{
+public:
+ struct Sample
+ {
+ Coord3D pos; ///< the point on the route itself
+ Coord2D tan; ///< unit direction of travel here
+ Real left; ///< drivable ground to the left, past this body's own radius
+ Real right; ///< and to the right
+ Real along; ///< distance from the start of the route
+ PathfindLayerEnum layer; ///< which deck this sample is on: anything above ground is a bridge or a wall
+ };
+
+ CrowdCorridor( void );
+
+ /** Measure the route. Returns false if the path is too short to have a direction, in which
+ case the corridor stays empty and the caller drives the centre line the way retail does. */
+ Bool build( const Object *obj, const LocomotorSet& locomotorSet, Path *path );
+
+ Bool isEmpty( void ) const { return m_samples.size() < 2; }
+ Int count( void ) const { return (Int)m_samples.size(); }
+ const Sample& at( Int i ) const { return m_samples[ i ]; }
+ Real length( void ) const { return m_samples.empty() ? 0.0f : m_samples.back().along; }
+
+ /** Index of the sample nearest to pos. `hint` is where the caller was last frame; the search
+ starts there and only falls back to the whole route if that window misses. */
+ Int nearest( const Coord3D& pos, Int hint ) const;
+
+ /// how hard the route turns at this sample, as the cross product of two tangents four apart
+ Real curvature( Int i ) const;
+
+ /// the world point `lat` to the left of sample i (negative is right)
+ void point( Int i, Real lat, Coord3D *out ) const;
+
+ /// `lat`, cut down to what the ground at sample i actually allows
+ Real clampLat( Int i, Real lat ) const;
+
+ /// where across the band `pos` sits, measured against sample i
+ Real latOf( Int i, const Coord3D& pos ) const;
+
+ /** How far along the route `pos` is, measured against sample i. The sample's own `along` is
+ quantised to the sample step; this is not, which is what lets a steering point advance a
+ foot at a time instead of a cell at a time. */
+ Real alongOf( Int i, const Coord3D& pos ) const;
+
+ /// the world point `lat` to the left of the route at distance `along`, interpolated between samples
+ void pointAt( Real along, Real lat, Coord3D *out ) const;
+
+ /// `lat`, cut down to what the ground allows at distance `along`
+ Real clampLatAt( Real along, Real lat ) const;
+
+ /** Build from a plain polyline, with the same width everywhere: for tests, which have no Object,
+ no pathfinder and no ground to probe. `layers`, when given, is one entry per point. */
+ void buildForTest( const Coord3D *pts, Int count, Real halfWidth, const PathfindLayerEnum *layers = NULL );
+
+ /// close the band on every bridge deck and on the ground either side of one
+ void sealBridges( void );
+
+private:
+ /// the sample at or before `along`, with the fraction of the way to the next one
+ Int bracket( Real along, Real *frac ) const;
+
+ std::vector<Sample> m_samples;
+};
+
+/** Right of way by body size. A bigger unit has less room to be squeezed and less patience in a
+ bottleneck, so the small one moves. The margin stops two nearly-equal bodies from each
+ deciding the other outranks them. */
+// (the second parameter is not called `small`: rpcndr.h, which comes in with windows.h, defines
+// that name as `char`)
+extern Bool Crowd_outranks( const Object *big, const Object *little );
+
+/** Distance between two bodies, discs, never negative-infinite: touching is zero and overlapping
+ is negative by however much they overlap. */
+extern Real Crowd_gap( const Object *a, const Object *b );
+
+/** How far along its own route a unit still has to go, which is what priority is decided on.
+ Falls back to straight-line distance to the goal when there is no path. */
+extern Real Crowd_remaining( const Object *obj );
+
+/** The speed to hold behind a unit that is going the same way, or `speed` unchanged when there is
+ nothing to hold back for.
+
+ Closing speed and the time it leaves, never the raw gap. Braking by distance slows a whole
+ column that was not catching anybody up, and braking behind a unit that is not moving at all
+ is worse than either: the collision never happens, so the blocked-frame count never rises and
+ none of the engine's own stuck machinery ever fires. Measured over eight seeds, distance
+ braking cost 3518 blocked unit-frames a match and braking behind parked allies 16593, against
+ 1236 for this. */
+extern Real Crowd_brakeSpeed( Real speed, Real blockerSpeed, Real gap, Int frames );
+
+/** The inside of a bend counts as being further ahead than it is.
+ A unit on the inside of a turn has the least room and is the easiest to squeeze, so it is
+ let out of the corner first and the outside units, which have room to keep rolling, flow
+ round it. Zero on a straight. */
+extern Real Crowd_bendBonus( const CrowdCorridor *corr, Int sample, Real lat );
+
+#endif // _CROWD_MODEL_H_
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h
index 5403115f4..516f03892 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h
@@ -40,6 +40,7 @@
class AIGroup;
class AIStateMachine;
class AttackPriorityInfo;
+class CrowdCorridor;
class DamageInfo;
class DozerAIInterface;
class Object;
@@ -478,6 +479,35 @@ public:
Bool isQuickPathAvailable( const Coord3D *destination ) const; ///< does a path (using quick pathfind) exist between us and the destination
Int getNumFramesBlocked(void) const {return m_blockedFrames;}
Bool isBlockedAndStuck(void) const {return m_isBlockedAndStuck;}
+
+ /* Lanes. The route says where to go; the lane fraction says where across its width this unit
+ rides while it goes there - 0 hard right, 1 hard left, 0.5 the centre line, which is where
+ retail always drove. It is seeded from where the unit actually was when the route was
+ built, so a spread-out group starts spread out, and it is the only per-unit state the band
+ needs: the width itself is measured off the map where the unit is, never stored. */
+ Bool hasLaneFraction(void) const {return m_laneFractionValid;}
+ Real getLaneFraction(void) const {return m_laneFraction;}
+
+ /** Told by the group that issued the order where this member sat across the group, as a
+ fraction of the group's own width. It has to come from outside: every member is handed
+ its own route starting under its own tracks, so measured against that route each of them
+ is dead centre and none of them has any reason to prefer a side. The offset from the
+ group's centre is the only shape there is, and it is the shape the player drew a box
+ round. Held until the path actually arrives, which can be several frames later. */
+ void setPendingLane( Real u ) { m_pendingLane = u; m_hasPendingLane = TRUE; }
+
+ /** The crowd model's version of the same thing, and the reason it is a second field rather than
+ a rescaling of the one above: this one is a distance in world units, positive to the left of
+ the route, and it means the same thing wherever the unit is standing. A fraction of the
+ local width does not - it drags a unit into every wide bay its route happens to pass and
+ swings it round the outside of corners. Only read under -crowd. */
+ void setPendingCrowdLat( Real lat ) { m_pendingCrowdLat = lat; m_hasPendingCrowdLat = TRUE; }
+ Real getCrowdLat( void ) const { return m_crowdLat; }
+ const CrowdCorridor *getCrowdCorridor( void ) const { return m_corridor; }
+ /** Which sample of its own band the unit was beside last frame. Priority between two units is
+ decided from both of their bends, and a unit that worked one of them out for itself and the
+ other one by guesswork would rank the pair differently from how they rank themselves. */
+ Int getCrowdSample( void ) const { return m_crowdSample; }
Bool canComputeQuickPath(void); ///< Returns true if we can quickly comput a path. Usually missiles & the like that just move straight to the destination.
Bool computeQuickPath(const Coord3D *destination); ///< Computes a quick path to the destination.
@@ -689,6 +719,28 @@ private:
// it does no sanity checking; it just jams it in.
Bool chooseLocomotorSetExplicit(LocomotorSetType wst);
+ /// Pick this unit's lane off its own sideways distance from the route it was just handed.
+ void seedLaneFraction( void );
+
+ /** Slide across the band to get past somebody who is not moving out of the way.
+ Called from the collision path, which already has the blocker in hand: no query is made
+ here on purpose, because the order a query returns objects in is part of the logic CRC
+ and a movement rule that depends on it desyncs every replay and every network game. */
+ void tryLaneChangeAround( Object *other );
+
+ /** The crowd model, one frame, one unit: measure the band if it has not been measured, look at
+ the neighbours once, and come back with where to steer and how fast. Everything the sandbox
+ does per frame - separation, right of way, priority, passing, fanning out, easing through a
+ bend - happens in here and expresses itself as those two numbers, because that is the whole
+ interface the locomotor gives us. */
+ void crowdSteer( Coord3D& goalPos, Real& speed );
+
+ /// throw the measured band away; the next frame that needs one measures the new route
+ void crowdReleaseCorridor( void );
+
+ /// TRUE when `other` gets the line and we are the one who has to do something about it
+ Bool crowdOutranksMe( Object *other ) const;
+
private:
UnsignedInt m_priorWaypointID; ///< ID of the path we follwed to before the most recent one
UnsignedInt m_currentWaypointID; ///< ID of the most recent one...
@@ -731,6 +783,31 @@ private:
ICoord2D m_pathfindCurCell; ///< Cell we are currently occupying.
Int m_blockedFrames; ///< Number of frames we've been blocked.
Real m_curMaxBlockedSpeed; ///< Max speed we can have and not run into blocking things.
+ Real m_laneFraction; ///< Where across the route's width we ride: 0 right edge, 1 left edge.
+ Bool m_laneFractionValid; ///< False until the fraction has been seeded off the current path.
+ UnsignedInt m_laneHoldFrame; ///< A lane taken to get round somebody is kept until this frame.
+ Real m_pendingLane; ///< Lane the ordering group picked for us, waiting for the path to arrive.
+ Bool m_hasPendingLane; ///< False when nobody handed us one and we have to measure our own.
+ CrowdCorridor* m_corridor; ///< -crowd: the current route with the width of the ground beside it. Owned; dies with the path.
+ Real m_crowdLat; ///< -crowd: how far left of the route we ride, in world units.
+ Real m_pendingCrowdLat; ///< -crowd: the same, as the ordering group wanted it, waiting for the path.
+ Bool m_hasPendingCrowdLat; ///< -crowd: FALSE for a unit ordered on its own, which rides where it already is.
+ Bool m_crowdLatValid; ///< -crowd: FALSE until the lane has been taken up against the current route.
+ UnsignedInt m_crowdHoldFrame; ///< -crowd: a lane taken to pass somebody is kept until this frame.
+ Int m_crowdSample; ///< -crowd: which sample of the band we were beside last frame (search hint; -1 = no band).
+ Int m_crowdQueued; ///< -crowd: consecutive frames spent braking or stuck behind somebody.
+ Int m_crowdSide; ///< -crowd: which side we prefer to pass on, +1 left, -1 right.
+ /* The rest of the crowd state is transient and deliberately not saved, for the same reason the
+ band itself is not: a filter, a stuck count and a half-finished backing-out manoeuvre are all
+ rebuilt within a second of the load, and a saved one restarts a jam that is over. */
+ Real m_crowdSepSmooth; ///< -crowd: low-passed sideways push from the neighbours.
+ Real m_crowdAim; ///< -crowd: low-passed direction the steering point is taken in, radians.
+ Bool m_crowdAimValid; ///< -crowd: FALSE until the filter has something to start from.
+ Int m_crowdStuck; ///< -crowd: consecutive frames spent wanting to move and not moving.
+ Coord3D m_crowdLastPos; ///< -crowd: where we were last frame, which is how the above is counted.
+ Coord3D m_crowdEscape; ///< -crowd: the free ground a wedged unit is backing out to.
+ UnsignedInt m_crowdEscapeUntil; ///< -crowd: frame that manoeuvre gives up (0 = not backing out).
+ UnsignedInt m_crowdEscapeCool; ///< -crowd: no second one before this frame.
Real m_bumpSpeedLimit; ///< Max speed after bumping a unit.
UnsignedInt m_ignoreCollisionsUntil; ///< Timer to cheat if we get stuck.
/**
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp
index 1c4bd8825..6f865b418 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp
@@ -1398,6 +1398,78 @@ Int parseNoFlowPath(char *args[], int num)
return 1;
}
+/* -nolanes puts every unit back on the centre line of its route.
+
+ The flow model decides where a route goes; lanes decide where across it a unit drives, which
+ is a separate question and needs its own baseline. With this on, computePointOnPath steers at
+ the centre the way retail always did, nothing measures the width of the ground beside the
+ route, and a unit stuck behind a slower one waits instead of sliding past. Same reasoning as
+ -noflowpath: one binary, run twice. */
+Int parseNoLanePath(char *args[], int num)
+{
+ if (TheWritableGlobalData)
+ TheWritableGlobalData->m_noLanePath = TRUE;
+ return 1;
+}
+
+/* -showlanes draws the band model on top of the world.
+
+ A movement change that measures well in a batch and cannot be seen in a game is a change nobody
+ has any reason to believe, and two different failures - a lane that was never handed out, and a
+ lane that was handed out and then refused - look exactly alike from the camera. So the overlay
+ draws both halves separately: what the ordering group asked for, and what the unit ended up
+ steering at. Release, because the machine that has the complaint is the one running Release. */
+Int parseShowLanes(char *args[], int num)
+{
+ if (TheWritableGlobalData)
+ TheWritableGlobalData->m_showLanes = TRUE;
+ return 1;
+}
+
+/* -crowd turns on the crowd model, in one switch, so that it can be argued with.
+
+ It is not one rule but a stack of them - the corridor with its measured width, the lane handed
+ out as a distance rather than a share, right of way by body size, giving way to something bigger
+ closing on you, passing a unit that is actually slower rather than one whose engine is, fanning
+ out only while held up, and easing off through a bend. Every one of those changes what a group
+ looks like crossing a map, and shipping them one at a time means eight batches and eight
+ opinions about which of them did the damage. So they land together behind one flag, off by
+ default: the same exe run twice is the before and the after, and the argument is about the whole
+ model rather than about any single constant inside it. */
+Int parseCrowdModel(char *args[], int num)
+{
+ if (TheWritableGlobalData)
+ TheWritableGlobalData->m_crowdModel = TRUE;
+ return 1;
+}
+
+/* -groupdrill <n> gives every player's army a group order every n frames.
+
+ A skirmish AI moves its teams one unit at a time, so a self-play batch contains no group orders
+ at all and measures nothing the crowd model does. This puts them in: the same call a right-click
+ makes, over the whole army, corner to corner. The match becomes meaningless - the win rate under
+ this switch says nothing about anything - and the blocked unit-frames become the first honest
+ measurement of group movement this fork has. 600 frames, twenty seconds, is long enough for an
+ army to cross a generated map. */
+Int parseGroupDrill(char *args[], int num)
+{
+ if (TheWritableGlobalData)
+ {
+ Int frames = 600;
+ Int eaten = 1;
+ if (num > 1 && args[1] && args[1][0] != '-')
+ {
+ frames = atoi(args[1]);
+ eaten = 2;
+ }
+ if (frames < LOGICFRAMES_PER_SECOND)
+ frames = LOGICFRAMES_PER_SECOND; // an order a frame is not a drill, it is a stutter
+ TheWritableGlobalData->m_groupDrill = frames;
+ return eaten;
+ }
+ return 1;
+}
+
/* -teams <n> splits an -autoskirmish lobby into n allied teams instead of a free-for-all.
Free-for-all and 4v4 are not the same load and not the same game. Eight players each fighting
@@ -1687,6 +1759,10 @@ static CommandLineParam params[] =
{ "-teams", parseTeams },
{ "-aislice", parseAISlice },
{ "-noflowpath", parseNoFlowPath },
+ { "-nolanes", parseNoLanePath },
+ { "-showlanes", parseShowLanes },
+ { "-crowd", parseCrowdModel },
+ { "-groupdrill", parseGroupDrill },
{ "-replay", parseReplay },
{ "-netgame", parseNetGame },
{ "-netslot", parseNetSlot },
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp
index d7d8ef57b..bd1e0a3a9 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp
@@ -684,6 +684,10 @@ GlobalData::GlobalData()
m_slowFrameMS = 20.0f; // a frame worth a line in the log; -slowframe lowers it for a hunt
m_aiSliceFrames = 1; // every unit thinks every frame, which is what the game has always done
m_noFlowPath = FALSE; // the flow model is on; -noflowpath is the retail baseline to measure against
+ m_noLanePath = FALSE; // lanes are on; -nolanes is the retail baseline to measure against
+ m_showLanes = FALSE; // the lane overlay is a diagnostic, off unless -showlanes asks for it
+ m_crowdModel = FALSE; // the crowd model is the change under test; without -crowd this is the old build
+ m_groupDrill = 0; // no group orders are faked; -groupdrill is a measuring tool and ruins the match it runs in
m_netGameHosts.clear(); // no network game from the command line
m_netGameLocalSlot = 0;
m_horizontalScrollSpeedFactor = 1.0;
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp
index 26e92e42b..f6d4f0848 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp
@@ -31,6 +31,7 @@
#include "Common/ActionManager.h"
#include "Common/BuildAssistant.h"
#include "Common/CRCDebug.h"
+#include "Common/GlobalData.h"
#include "Common/Player.h"
#include "Common/SpecialPower.h"
#include "Common/ThingTemplate.h"
@@ -1567,6 +1568,85 @@ void clampWaypointPosition( Coord3D &position, Int margin )
}
+/** One member of a group being handed a lane, and where it stands across the direction the group is
+ about to travel in. Only groupMoveToPosition builds these, and only for as long as it takes to
+ sort them. */
+struct LaneSeed
+{
+ Object* obj;
+ Real lat;
+};
+
+/** Sort members left to right across the group. Object id breaks a tie, so two units standing on
+ exactly the same line still get the same two lanes on every machine in a network game - the
+ positions are identical everywhere but the order they arrive in is not. */
+static Bool laneSeedIsLeftOf( const LaneSeed& a, const LaneSeed& b )
+{
+ if (a.lat != b.lat)
+ return a.lat < b.lat;
+ return a.obj->getID() < b.obj->getID();
+}
+
+/** Hand every member of a group the distance it should sit off the centre of the road, for the
+ crowd model only.
+
+ The same arithmetic groupMoveToPosition does inline, extracted because the computer's armies
+ never go through that function: an AI team moves with groupTightenToPosition
+ (AIPlayer.cpp:3505), which handed nobody a lane, and a unit with no lane is a unit crowdSteer
+ returns out of on its first line. So every steering rule under -crowd was reachable by the
+ player and by nothing else, and the self-play harness was measuring the flag's other half - the
+ collision rules in AIUpdate::blockedBy - while reporting on the crowd model. */
+static void crowdSeedLanes( std::list<Object *>& members, const Coord3D& center, const Coord3D *pos )
+{
+ Coord2D dir;
+ dir.x = pos->x - center.x;
+ dir.y = pos->y - center.y;
+ if (dir.length() <= 1.0f)
+ return; // a group already standing on its destination has no direction to spread across
+ dir.normalize();
+
+ std::vector<LaneSeed> across;
+ Real spacing = 0.0f;
+ for (std::list<Object *>::iterator it = members.begin(); it != members.end(); ++it)
+ {
+ Object *o = *it;
+ if (o->getAIUpdateInterface() == NULL || o->isKindOf( KINDOF_IMMOBILE ))
+ continue;
+
+ LaneSeed seed;
+ seed.obj = o;
+ seed.lat = (o->getPosition()->x - center.x) * -dir.y
+ + (o->getPosition()->y - center.y) * dir.x;
+ across.push_back( seed );
+
+ const Real body = 2.0f * o->getGeometryInfo().getBoundingCircleRadius();
+ if (body > spacing)
+ spacing = body;
+ }
+
+ spacing *= 1.15f;
+
+ const Int count = (Int)across.size();
+ if (count < 2 || spacing < 0.001f)
+ return;
+
+ std::sort( across.begin(), across.end(), laneSeedIsLeftOf );
+
+ Int lanes = (Int)(2.0f * Pathfinder_laneReference() / spacing);
+ if (lanes < 1) lanes = 1;
+ if (lanes > count) lanes = count;
+
+ for (Int i = 0; i < count; i++)
+ {
+ const Int lane = (i * lanes) / count;
+ const Real offset = ((Real)lane - (Real)(lanes - 1) * 0.5f) * spacing;
+ across[i].obj->getAIUpdateInterface()->setPendingCrowdLat( offset );
+ }
+
+ if (TheGlobalData->m_showLanes)
+ DEBUG_LOG(("SHOWLANES crowdSeedLanes: members=%d lanes=%d spacing=%.1f\n", count, lanes, spacing));
+}
+
/**
* Move to given position(s)
*/
@@ -1745,6 +1825,102 @@ void AIGroup::groupMoveToPosition( const Coord3D *p_posIn, Bool addWaypoint, Com
Coord3D goalPos = *pos;
iter->sort(ITER_SORTED_NEAR_TO_FAR);
+
+ /* Where each member rides across its route. Every unit is handed its own route starting under
+ its own tracks, so measured against that route each of them is dead centre and none of them
+ has any reason to prefer a side - which is how a selection ends up in single file. The order
+ the members sit in across the group is the only shape there is at this point, and it is the
+ shape the player just drew a box round.
+
+ The lane is a distance, not a share of the group. The first version divided each member's
+ offset by the group's own half width, and a selection standing in a tight blob has almost no
+ half width, so twenty-five tanks were spread across thirty feet - less than two of them. Now
+ members are sorted across the direction of travel and spaced by the size of the largest body
+ in the group, which is the only spacing that means anything to a tank.
+
+ The band cannot hold an arbitrary number of them, so the count of lanes is capped at what the
+ widest possible band fits and the rest of the group queues behind: members are cut into that
+ many blocks in order, so whoever was on the left is still on the left and the ones sharing a
+ lane simply follow each other. A narrow road squeezes all of it - laneOffset scales by the
+ room actually measured, so half a band is half the offset, and a doorway is single file
+ again without anybody deciding to queue. */
+ Coord2D groupDir;
+ groupDir.x = pos->x - center.x;
+ groupDir.y = pos->y - center.y;
+ const Coord3D groupCenter = center;
+ Bool spreadLanes = !TheGlobalData->m_noLanePath && groupDir.length() > 1.0f;
+ if (spreadLanes)
+ {
+ groupDir.normalize();
+
+ std::vector<LaneSeed> across;
+ Real spacing = 0.0f;
+ for (Object *o = iter->first(); o; o = iter->next())
+ {
+ if (o->getAIUpdateInterface() == NULL)
+ continue;
+
+ LaneSeed seed;
+ seed.obj = o;
+ seed.lat = (o->getPosition()->x - groupCenter.x) * -groupDir.y
+ + (o->getPosition()->y - groupCenter.y) * groupDir.x;
+ across.push_back( seed );
+
+ Real body = 2.0f * o->getGeometryInfo().getBoundingCircleRadius();
+ if (body > spacing)
+ spacing = body;
+ }
+
+ // a little air between bodies, or the lanes are exactly touching and the collision push
+ // undoes the spread the frame it is applied
+ spacing *= 1.15f;
+
+ Int count = across.size();
+ if (count > 1 && spacing > 0.001f)
+ {
+ std::sort( across.begin(), across.end(), laneSeedIsLeftOf );
+
+ Int lanes = (Int)(2.0f * Pathfinder_laneReference() / spacing);
+ if (lanes < 1) lanes = 1;
+ if (lanes > count) lanes = count;
+
+ for (Int i = 0; i < count; i++)
+ {
+ // blocks, not round-robin: whoever was left of somebody stays left of them, and a
+ // group with more members than lanes puts the extra ones behind rather than beside
+ Int lane = (i * lanes) / count;
+ Real offset = ((Real)lane - (Real)(lanes - 1) * 0.5f) * spacing;
+ Real u = Pathfinder_groupLane( offset );
+ across[i].obj->getAIUpdateInterface()->setPendingLane( u );
+
+ /* -crowd takes the offset as it stands. The old model had to turn it into a share of
+ a width guessed here and re-measured somewhere else, and the two never agreed: the
+ conversion is where the spacing this loop just worked out was thrown away. */
+ if (TheGlobalData->m_crowdModel)
+ across[i].obj->getAIUpdateInterface()->setPendingCrowdLat( offset );
+
+ if (TheGlobalData->m_showLanes)
+ {
+ DEBUG_LOG(("SHOWLANES unit %d lat=%.1f lane %d/%d offset=%.1f u=%.2f\n",
+ across[i].obj->getID(), across[i].lat, lane, lanes, offset, u));
+ }
+ }
+ }
+ else
+ {
+ spreadLanes = FALSE;
+ }
+
+ /* The overlay draws what happened on the ground; this says whether this function is where it
+ happened at all. A player order that never reaches here hands nobody a lane, and from the
+ camera that looks exactly like an order that reached here and was refused. */
+ if (TheGlobalData->m_showLanes)
+ {
+ DEBUG_LOG(("SHOWLANES groupMoveToPosition: spread=%d members=%d spacing=%.1f\n",
+ spreadLanes ? 1 : 0, count, spacing));
+ }
+ }
+
// Works better if you let the near units get the first paths... jba.
// Move the ones nearest the goal first. Reduces collision problems later.
Object *theUnit;
@@ -1753,6 +1929,7 @@ void AIGroup::groupMoveToPosition( const Coord3D *p_posIn, Bool addWaypoint, Com
{
theUnit->setFormationID(NO_FORMATION_ID);
AIUpdateInterface *ai = theUnit->getAIUpdateInterface();
+
if (firstUnit) {
if (isFormation) {
Coord2D v;
@@ -1937,6 +2114,17 @@ void AIGroup::groupTightenToPosition( const Coord3D *pos, Bool addWaypoint, Comm
// outsideOfBounds = FALSE;
//}
}
+ /* The computer's armies come through here rather than groupMoveToPosition, so this is where they
+ are handed their lanes. Under -crowd only: without the flag a tighten is retail's, and the
+ lane is read by nothing. */
+ if (TheGlobalData->m_crowdModel && !addWaypoint)
+ {
+ Coord2D tMin, tMax;
+ Coord3D tCenter;
+ getMinMaxAndCenter( &tMin, &tMax, &tCenter );
+ crowdSeedLanes( m_memberList, tCenter, pos );
+ }
+
// Tighten.
MemoryPoolObjectHolder iterHolder;
SimpleObjectIterator *iter = newInstance(SimpleObjectIterator);
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp
index ba8ef5ea4..6235f6951 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp
@@ -924,6 +924,52 @@ static Coord3D steerCheckTarget( const Coord3D& from, const Coord3D& to )
return clamped;
}
+Bool Path::closestPointAndDir( const Coord3D& pos, Coord3D *ptOut, Coord2D *dirOut ) const
+{
+ if (m_path == NULL) return false;
+
+ Real closeDistSqr = 99999999.9f;
+ Bool found = false;
+
+ const PathNode *prevNode = m_path;
+ Coord2D segmentDirNorm;
+ Real segmentLength;
+ for ( const PathNode *node = prevNode->getNextOptimized(&segmentDirNorm, &segmentLength);
+ node != NULL;
+ node = node->getNextOptimized(&segmentDirNorm, &segmentLength) )
+ {
+ const Coord3D *prevNodePos = prevNode->getPosition();
+
+ Coord2D toPos;
+ toPos.x = pos.x - prevNodePos->x;
+ toPos.y = pos.y - prevNodePos->y;
+
+ Real along = segmentDirNorm.x * toPos.x + segmentDirNorm.y * toPos.y;
+ if (along < 0.0f) along = 0.0f;
+ if (along > segmentLength) along = segmentLength;
+
+ Coord3D pointOnPath;
+ pointOnPath.x = prevNodePos->x + along * segmentDirNorm.x;
+ pointOnPath.y = prevNodePos->y + along * segmentDirNorm.y;
+ pointOnPath.z = prevNodePos->z;
+
+ Real dx = pos.x - pointOnPath.x;
+ Real dy = pos.y - pointOnPath.y;
+ Real distSqr = dx*dx + dy*dy;
+ if (distSqr < closeDistSqr)
+ {
+ closeDistSqr = distSqr;
+ *ptOut = pointOnPath;
+ *dirOut = segmentDirNorm;
+ found = true;
+ }
+
+ prevNode = node;
+ }
+
+ return found;
+}
+
void Path::computePointOnPath(
const Object* obj,
const LocomotorSet& locomotorSet,
@@ -1187,6 +1233,103 @@ void Path::computePointOnPath(
}
}
+ /* The route is a band, not a line.
+ Everything above picked a point on the centre line, which is why twenty tanks handed twenty
+ routes down the same open ground drive nose to tail: they are all steering at the same
+ metre of it. This slides the steering point sideways to the unit's own lane across
+ whatever width the ground allows where it is standing, so a wide field is used as a wide
+ field and a doorway squeezes the same units back into a line without anybody deciding to
+ queue. Two things it must not break: the unit still has to reach the cell reserved for it
+ at the end, so the band closes onto the centre over the last few cells, and it still has
+ to be able to drive at whatever it is aimed at, so a lane point with something in the way
+ is dropped and the centre kept. */
+ if (!TheGlobalData->m_noLanePath && closeNode != NULL && closeNode->getNextOptimized() != NULL)
+ {
+ const AIUpdateInterface *ai = obj ? obj->getAIUpdateInterface() : NULL;
+ if (ai && ai->hasLaneFraction())
+ {
+ const PathNode *nextNode = closeNode->getNextOptimized();
+ const Coord3D *segA = closeNode->getPosition();
+ const Coord3D *segB = nextNode->getPosition();
+ Coord2D dirIn;
+ dirIn.x = segB->x - segA->x;
+ dirIn.y = segB->y - segA->y;
+ Real segLen = dirIn.length();
+ if (segLen > 0.001f)
+ {
+ dirIn.x /= segLen;
+ dirIn.y /= segLen;
+
+ /* Which way the route is heading where the steering point actually is, which is not
+ always the segment the unit is standing beside: everything above will happily hand
+ back the corner node itself, or the middle of the segment after it. Measuring the
+ lane sideways to the old heading then puts the point beside the corner instead of
+ past it - on a sharp turn, behind the unit - and that is the tank that stops at the
+ bend and turns on the spot. */
+ Coord2D dirOut = dirIn;
+ const PathNode *afterNext = nextNode->getNextOptimized();
+ if (afterNext)
+ {
+ Coord2D d;
+ d.x = afterNext->getPosition()->x - segB->x;
+ d.y = afterNext->getPosition()->y - segB->y;
+ if (d.length() > 0.001f)
+ {
+ d.normalize();
+ dirOut = d;
+ }
+ }
+
+ Real atPoint = (out.posOnPath.x - segA->x) * dirIn.x + (out.posOnPath.y - segA->y) * dirIn.y;
+ Coord2D dir = (atPoint >= segLen - 0.1f) ? dirOut : dirIn;
+
+ Coord2D left, right;
+ left.x = -dir.y; left.y = dir.x;
+ right.x = dir.y; right.y = -dir.x;
+
+ Pathfinder *pf = TheAI->pathfinder();
+ Real leftRoom = pf->laneExtent( obj, locomotorSet, out.layer, &out.posOnPath, &left );
+ Real rightRoom = pf->laneExtent( obj, locomotorSet, out.layer, &out.posOnPath, &right );
+ Real lateral = Pathfinder_laneOffset( ai->getLaneFraction(), leftRoom, rightRoom );
+
+ // and it is shut some way before the goal, not at it
+ Real remaining = totalPathLength - lengthAlongPathToPos;
+ lateral *= Pathfinder_laneTaper( remaining );
+
+ Bool applied = FALSE;
+ if (fabs(lateral) > 0.5f)
+ {
+ Coord3D lanePos = out.posOnPath;
+ lanePos.x += left.x * lateral;
+ lanePos.y += left.y * lateral;
+
+ /* Never hand back a point on the other side of the unit from the one the route
+ asked for. Sliding sideways can cross the unit's own position, and a unit told
+ to drive at something behind it turns round to face it instead of driving on. */
+ Real ahead = (out.posOnPath.x - pos.x) * (lanePos.x - pos.x)
+ + (out.posOnPath.y - pos.y) * (lanePos.y - pos.y);
+
+ if (ahead > 0.0f && pf->isLinePassable( obj, locomotorSet.getValidSurfaces(), out.layer, pos,
+ steerCheckTarget( pos, lanePos ), false, true ))
+ {
+ out.posOnPath = lanePos;
+ applied = TRUE;
+ }
+ }
+
+ /* The last place a lane can die: the band measured as one cell wide, the taper closed
+ it, or the line to the lane point is not drivable. Logged once a second per unit -
+ every frame is a megabyte a minute and says nothing more. */
+ if (TheGlobalData->m_showLanes && (TheGameLogic->getFrame() % 30) == 0)
+ {
+ DEBUG_LOG(("SHOWLANES cpop: unit %d lane=%.2f room=%.0f/%.0f left=%.0f lateral=%.1f applied=%d\n",
+ obj->getID(), ai->getLaneFraction(), leftRoom, rightRoom, remaining, lateral,
+ applied ? 1 : 0));
+ }
+ }
+ }
+ }
+
TheAI->pathfinder()->setDebugPathPosition( &out.posOnPath );
out.distAlongPath = totalPathLength - lengthAlongPathToPos;
@@ -4296,6 +4439,85 @@ Int Pathfinder_crossingCost( Int baseCost, Int claimHalves )
return (baseCost * PF_CROSSING_NUM * units) / PF_CROSSING_DEN;
}
+/* Lanes across the band. Both of these are the whole of the lane arithmetic and neither of them
+ touches the map, so the tests can check the edges - a band with no width, a body already outside
+ it, a lane hard against a wall - without standing a Pathfinder up. */
+
+/// The 5% at either end is kept clear: a lane exactly on the edge is a lane in the terrain.
+static const Real LANE_MIN = 0.05f;
+static const Real LANE_MAX = 0.95f;
+
+/* Half is the route's centre line, not the middle of whatever room was found.
+
+ Stretching one straight line from the left wall to the right wall makes half of a lopsided band
+ mean "the middle of the free ground", which walks a unit with no opinion sideways every time the
+ terrain is uneven on one side. With the probe reaching sixteen cells that is up to seventy-five
+ feet off its own route for a unit that was never given a lane at all, and it cost 10% more time
+ spent blocked over twelve matches - measured, and the reason the two sides are now scaled
+ separately. Each half of the band is its own scale and they meet at the centre. */
+Real Pathfinder_laneFraction( Real lateral, Real leftExtent, Real rightExtent )
+{
+ Real u = 0.5f;
+ if (lateral > 0.0f && leftExtent > 0.001f)
+ u = 0.5f + 0.5f * (lateral / leftExtent);
+ else if (lateral < 0.0f && rightExtent > 0.001f)
+ u = 0.5f + 0.5f * (lateral / rightExtent);
+
+ if (u < LANE_MIN) u = LANE_MIN;
+ if (u > LANE_MAX) u = LANE_MAX;
+ return u;
+}
+
+Real Pathfinder_laneOffset( Real u, Real leftExtent, Real rightExtent )
+{
+ return (u >= 0.5f) ? (u - 0.5f) * 2.0f * leftExtent
+ : (u - 0.5f) * 2.0f * rightExtent;
+}
+
+/**
+ * The widest half-band laneExtent can ever report: it probes PF_LANE_PROBE_CELLS cells sideways and
+ * stops there whatever the ground does. A lane handed down from outside is measured against this,
+ * so it can be stated in feet without knowing which piece of road the unit will be standing on.
+ */
+Real Pathfinder_laneReference( void )
+{
+ return PATHFIND_CELL_SIZE_F * (Real)PF_LANE_PROBE_CELLS;
+}
+
+/**
+ * Where a member of a group sits across the band, given how far left of the centre line it wants to
+ * ride in world units.
+ *
+ * The previous version divided by the group's own width, which made the answer say nothing about
+ * distance: twenty-five tanks parked in a tight blob have a half width of thirty feet, so the whole
+ * selection mapped into thirty feet of band and every one of them was on top of every other. A
+ * fixed reference means the caller can space members by their own size and have it survive.
+ */
+Real Pathfinder_groupLane( Real lateral )
+{
+ Real u = 0.5f + 0.5f * (lateral / Pathfinder_laneReference());
+ if (u < LANE_MIN) u = LANE_MIN;
+ if (u > LANE_MAX) u = LANE_MAX;
+ return u;
+}
+
+/**
+ * How much of the lane survives this far from the end of the route.
+ *
+ * The band has to be shut before the goal rather than at it. A ramp reaching zero exactly at the
+ * end leaves a unit riding seventy feet out still twenty feet out when it stops, so a group sent
+ * to one point arrives as a line across it instead of a huddle on it.
+ */
+Real Pathfinder_laneTaper( Real remaining )
+{
+ const Real taper = PATHFIND_CELL_SIZE_F * (Real)PF_LANE_TAPER_CELLS;
+ const Real close = PATHFIND_CELL_SIZE_F * (Real)PF_LANE_CLOSE_CELLS;
+
+ if (remaining <= close) return 0.0f;
+ if (remaining >= taper) return 1.0f;
+ return (remaining - close) / (taper - close);
+}
+
/// Is this cell one no ground unit can stand in? Rubble counts as ground: crushers drive over it.
static Bool clearanceBlocks( const PathfindCell *cell )
{
@@ -4692,6 +4914,37 @@ void Pathfinder::beginFlowSearch( const Object *obj )
thePathHeuristicDen = m_flowCosts ? PF_HEURISTIC_FLOW_DEN : 2;
}
+/* How wide the ground is beside a point, on one side. Half-cell steps, stopping at the first
+ position the body could not stand in. Deliberately not the clearance map: that is a chamfer
+ distance to the nearest obstacle in any direction, so a route running along a wall reads as
+ narrow even when the whole field is open on the other side, and it is exactly that asymmetry
+ the band has to see. Sixteen cell lookups, on a path recompute rather than every frame. */
+Real Pathfinder::laneExtent( const Object *obj, const LocomotorSet& locomotorSet, PathfindLayerEnum layer,
+ const Coord3D *from, const Coord2D *dir )
+{
+ const Bool isCrusher = obj ? obj->getCrusherLevel() > 0 : false;
+ const Real step = PATHFIND_CELL_SIZE_F * 0.5f;
+ const Real maxDist = PATHFIND_CELL_SIZE_F * (Real)PF_LANE_PROBE_CELLS;
+
+ Real room = 0.0f;
+ for (Real s = step; s <= maxDist; s += step)
+ {
+ Coord3D probe;
+ probe.x = from->x + dir->x * s;
+ probe.y = from->y + dir->y * s;
+ probe.z = from->z;
+ if (!validMovementPosition(isCrusher, layer, locomotorSet, &probe))
+ break;
+ room = s;
+ }
+
+ // the body has to fit in whatever room was found, so it only owns the part past its own radius
+ if (obj)
+ room -= obj->getGeometryInfo().getBoundingCircleRadius();
+
+ return room > 0.0f ? room : 0.0f;
+}
+
void Pathfinder::resetProfile( void )
{
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/CrowdModel.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/CrowdModel.cpp
new file mode 100644
index 000000000..c0458c2f7
--- /dev/null
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/CrowdModel.cpp
@@ -0,0 +1,495 @@
+/*
+** Command & Conquer Generals Zero Hour(tm)
+** Copyright 2025 Electronic Arts Inc.
+**
+** This program is free software: you can redistribute it and/or modify
+** it under the terms of the GNU General Public License as published by
+** the Free Software Foundation, either version 3 of the License, or
+** (at your option) any later version.
+**
+** This program is distributed in the hope that it will be useful,
+** but WITHOUT ANY WARRANTY; without even the implied warranty of
+** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+** GNU General Public License for more details.
+**
+** You should have received a copy of the GNU General Public License
+** along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+// FILE: CrowdModel.cpp ////////////////////////////////////////////////////////////////////////
+// The measured band, and the small pieces of arithmetic the steering rules are built out of.
+///////////////////////////////////////////////////////////////////////////////////////////////
+
+#include "PreRTS.h"
+
+#include "Common/GlobalData.h"
+#include "GameLogic/AI.h"
+#include "GameLogic/AIPathfind.h"
+#include "GameLogic/CrowdModel.h"
+#include "GameLogic/Module/AIUpdate.h"
+#include "GameLogic/Object.h"
+
+//-------------------------------------------------------------------------------------------------
+CrowdCorridor::CrowdCorridor( void )
+{
+}
+
+//-------------------------------------------------------------------------------------------------
+/** How much drivable ground there is one way from a point, stopping at the first place the body
+ would not fit. Half-cell steps, so a doorway one cell wide is not reported as two.
+
+ Deliberately not the clearance map: that is a distance to the nearest obstacle in any
+ direction, so a route hugging a wall reads as narrow even when the whole field is open on the
+ other side - and that asymmetry is the only thing the band is for. */
+//-------------------------------------------------------------------------------------------------
+static Real crowdExtent( const Object *obj, const LocomotorSet& locomotorSet, PathfindLayerEnum layer,
+ const Coord3D *from, const Coord2D *dir )
+{
+ const Bool isCrusher = obj ? obj->getCrusherLevel() > 0 : false;
+ const Real step = PATHFIND_CELL_SIZE_F * 0.5f;
+ const Real maxDist = PATHFIND_CELL_SIZE_F * (Real)CROWD_PROBE_CELLS;
+
+ Real room = 0.0f;
+ for (Real s = step; s <= maxDist; s += step)
+ {
+ Coord3D probe;
+ probe.x = from->x + dir->x * s;
+ probe.y = from->y + dir->y * s;
+ probe.z = from->z;
+ if (!TheAI->pathfinder()->validMovementPosition( isCrusher, layer, locomotorSet, &probe ))
+ break;
+ room = s;
+ }
+
+ // the body has to fit in whatever was found, so the lane only owns the part past its own radius
+ if (obj)
+ room -= obj->getGeometryInfo().getBoundingCircleRadius();
+
+ return room > 0.0f ? room : 0.0f;
+}
+
+//-------------------------------------------------------------------------------------------------
+Bool CrowdCorridor::build( const Object *obj, const LocomotorSet& locomotorSet, Path *path )
+{
+ m_samples.clear();
+
+ if (path == NULL)
+ return FALSE;
+
+ const PathNode *node = path->getFirstNode();
+ if (node == NULL || node->getNextOptimized() == NULL)
+ return FALSE;
+
+ // length first, so the step can be chosen to fit the sample budget
+ Real total = 0.0f;
+ for (const PathNode *n = node; n && n->getNextOptimized(); n = n->getNextOptimized())
+ {
+ Real segLen = 0.0f;
+ n->getNextOptimized( NULL, &segLen );
+ total += segLen;
+ }
+ if (total < PATHFIND_CELL_SIZE_F)
+ return FALSE;
+
+ Real step = PATHFIND_CELL_SIZE_F;
+ if (total / step > (Real)(CROWD_MAX_SAMPLES - 1))
+ step = total / (Real)(CROWD_MAX_SAMPLES - 1);
+
+ Real walked = 0.0f; // distance already covered by emitted samples
+ Real base = 0.0f; // distance to the start of the segment being walked
+ for (const PathNode *n = node; n && n->getNextOptimized(); n = n->getNextOptimized())
+ {
+ Coord2D dir;
+ Real segLen = 0.0f;
+ const PathNode *next = n->getNextOptimized( &dir, &segLen );
+ if (segLen < 0.001f)
+ continue;
+
+ const Coord3D *a = n->getPosition();
+ const Coord3D *b = next->getPosition();
+
+ /* The layer this piece of route is on, not the one the unit is standing on. A route over a
+ bridge changes deck halfway along, and probing a bridge sample against the ground layer asks
+ how much room there is on the riverbank underneath - which is where a lane measured that way
+ sends the unit. That is the walking off the side of a bridge. */
+ const PathfindLayerEnum layer = n->getLayer();
+
+ while (walked <= base + segLen && (Int)m_samples.size() < CROWD_MAX_SAMPLES)
+ {
+ const Real t = walked - base;
+
+ Sample s;
+ s.pos.x = a->x + dir.x * t;
+ s.pos.y = a->y + dir.y * t;
+ s.pos.z = a->z + (b->z - a->z) * (t / segLen);
+ s.tan = dir;
+ s.along = walked;
+ s.layer = layer;
+
+ Coord2D left, right;
+ left.x = -dir.y; left.y = dir.x;
+ right.x = dir.y; right.y = -dir.x;
+ s.left = crowdExtent( obj, locomotorSet, layer, &s.pos, &left );
+ s.right = crowdExtent( obj, locomotorSet, layer, &s.pos, &right );
+
+ m_samples.push_back( s );
+ walked += step;
+ }
+
+ base += segLen;
+ }
+
+ if (m_samples.size() < 2)
+ {
+ m_samples.clear();
+ return FALSE;
+ }
+
+ /* Smooth the two width curves. A single sample that happened to land beside a rock reports a
+ metre of road in the middle of a field, and a lane clamped to that one sample jerks sideways
+ and back again over two frames. Two [1 2 1] passes, which is what the sandbox settled on. */
+ const Int n = (Int)m_samples.size();
+ std::vector<Real> tmpL( n ), tmpR( n );
+ for (Int pass = 0; pass < 2; pass++)
+ {
+ for (Int i = 0; i < n; i++)
+ {
+ const Int p = (i > 0) ? i - 1 : 0;
+ const Int q = (i < n - 1) ? i + 1 : n - 1;
+ tmpL[ i ] = (m_samples[ p ].left + 2.0f * m_samples[ i ].left + m_samples[ q ].left) * 0.25f;
+ tmpR[ i ] = (m_samples[ p ].right + 2.0f * m_samples[ i ].right + m_samples[ q ].right) * 0.25f;
+ }
+ for (Int i = 0; i < n; i++)
+ {
+ m_samples[ i ].left = tmpL[ i ];
+ m_samples[ i ].right = tmpR[ i ];
+ }
+ }
+
+ sealBridges();
+
+ return TRUE;
+}
+
+//-------------------------------------------------------------------------------------------------
+/** A bridge has no band, and neither does the ground each side of one.
+
+ Probing the right deck already reports a bridge as narrow, but narrow is not the same as
+ single file: half a lane of drift is enough to put a tank over the railing, and the roadway is
+ a different width from the pathfind cells that carry it. The approach matters as much as the
+ deck. A unit holding a lane a body width off centre while it rolls up to a bridge arrives
+ beside the entrance rather than at it, stops against the abutment, and every unit behind it
+ queues on the bank - which is the not getting onto the bridge at all. So the band closes
+ CROWD_BRIDGE_SEAL samples before the deck starts and opens the same distance after it ends,
+ and inside that stretch every unit drives the centre line exactly the way retail does. */
+//-------------------------------------------------------------------------------------------------
+void CrowdCorridor::sealBridges( void )
+{
+ const Int n = (Int)m_samples.size();
+
+ for (Int i = 0; i < n; i++)
+ {
+ if (m_samples[ i ].layer <= LAYER_GROUND)
+ continue;
+
+ Int lo = i - CROWD_BRIDGE_SEAL;
+ Int hi = i + CROWD_BRIDGE_SEAL;
+ if (lo < 0) lo = 0;
+ if (hi > n - 1) hi = n - 1;
+ for (Int j = lo; j <= hi; j++)
+ {
+ m_samples[ j ].left = 0.0f;
+ m_samples[ j ].right = 0.0f;
+ }
+ }
+
+}
+
+//-------------------------------------------------------------------------------------------------
+Int CrowdCorridor::nearest( const Coord3D& pos, Int hint ) const
+{
+ const Int n = (Int)m_samples.size();
+ if (n == 0)
+ return 0;
+
+ Int lo = hint - 4;
+ Int hi = hint + 12;
+ if (lo < 0) lo = 0;
+ if (hi > n - 1) hi = n - 1;
+
+ Int best = lo;
+ Real bestSqr = 1e30f;
+ for (Int i = lo; i <= hi; i++)
+ {
+ const Real dx = pos.x - m_samples[ i ].pos.x;
+ const Real dy = pos.y - m_samples[ i ].pos.y;
+ const Real d = dx * dx + dy * dy;
+ if (d < bestSqr) { bestSqr = d; best = i; }
+ }
+
+ /* The window is right while the unit is following the route and wrong the moment it is not -
+ shoved off it, retreating, or handed a new one - so a miss falls back to the whole route
+ rather than steering at a sample fifty cells behind. */
+ const Real close = PATHFIND_CELL_SIZE_F * 6.0f;
+ if (bestSqr > close * close && (lo > 0 || hi < n - 1))
+ {
+ for (Int i = 0; i < n; i++)
+ {
+ const Real dx = pos.x - m_samples[ i ].pos.x;
+ const Real dy = pos.y - m_samples[ i ].pos.y;
+ const Real d = dx * dx + dy * dy;
+ if (d < bestSqr) { bestSqr = d; best = i; }
+ }
+ }
+
+ return best;
+}
+
+//-------------------------------------------------------------------------------------------------
+Real CrowdCorridor::curvature( Int i ) const
+{
+ const Int n = (Int)m_samples.size();
+ if (n < 2)
+ return 0.0f;
+ if (i < 0) i = 0;
+ if (i > n - 1) i = n - 1;
+ Int j = i + 4;
+ if (j > n - 1) j = n - 1;
+ return m_samples[ i ].tan.x * m_samples[ j ].tan.y - m_samples[ i ].tan.y * m_samples[ j ].tan.x;
+}
+
+//-------------------------------------------------------------------------------------------------
+void CrowdCorridor::point( Int i, Real lat, Coord3D *out ) const
+{
+ const Sample& s = m_samples[ i ];
+ out->x = s.pos.x - s.tan.y * lat;
+ out->y = s.pos.y + s.tan.x * lat;
+ out->z = s.pos.z;
+}
+
+//-------------------------------------------------------------------------------------------------
+Real CrowdCorridor::clampLat( Int i, Real lat ) const
+{
+ const Sample& s = m_samples[ i ];
+ if (lat > s.left) lat = s.left;
+ if (lat < -s.right) lat = -s.right;
+ return lat;
+}
+
+//-------------------------------------------------------------------------------------------------
+Real CrowdCorridor::latOf( Int i, const Coord3D& pos ) const
+{
+ const Sample& s = m_samples[ i ];
+ return (pos.x - s.pos.x) * -s.tan.y + (pos.y - s.pos.y) * s.tan.x;
+}
+
+//-------------------------------------------------------------------------------------------------
+Real CrowdCorridor::alongOf( Int i, const Coord3D& pos ) const
+{
+ const Sample& s = m_samples[ i ];
+ Real a = s.along + (pos.x - s.pos.x) * s.tan.x + (pos.y - s.pos.y) * s.tan.y;
+ if (a < 0.0f)
+ a = 0.0f;
+ const Real len = length();
+ if (a > len)
+ a = len;
+ return a;
+}
+
+//-------------------------------------------------------------------------------------------------
+Int CrowdCorridor::bracket( Real along, Real *frac ) const
+{
+ const Int n = (Int)m_samples.size();
+ *frac = 0.0f;
+ if (n < 2)
+ return 0;
+
+ Int lo = 0;
+ Int hi = n - 1;
+ while (lo + 1 < hi)
+ {
+ const Int mid = (lo + hi) / 2;
+ if (m_samples[ mid ].along <= along)
+ lo = mid;
+ else
+ hi = mid;
+ }
+
+ const Real span = m_samples[ lo + 1 ].along - m_samples[ lo ].along;
+ Real f = (span > 0.001f) ? (along - m_samples[ lo ].along) / span : 0.0f;
+ if (f < 0.0f) f = 0.0f;
+ if (f > 1.0f) f = 1.0f;
+ *frac = f;
+ return lo;
+}
+
+//-------------------------------------------------------------------------------------------------
+/** The same point `point` returns, but at a distance rather than at a sample.
+
+ Samples are a cell apart, so a steering point taken from one jumps ten feet forward every time
+ the unit crosses a sample boundary, and the direction handed to the locomotor steps with it. A
+ heavy tank's steering absorbs that; a light one turns it into a wobble down the whole march. */
+//-------------------------------------------------------------------------------------------------
+void CrowdCorridor::pointAt( Real along, Real lat, Coord3D *out ) const
+{
+ Real f = 0.0f;
+ const Int i = bracket( along, &f );
+ const Int j = (i + 1 < (Int)m_samples.size()) ? i + 1 : i;
+ const Sample& a = m_samples[ i ];
+ const Sample& b = m_samples[ j ];
+
+ Real tx = a.tan.x + (b.tan.x - a.tan.x) * f;
+ Real ty = a.tan.y + (b.tan.y - a.tan.y) * f;
+ const Real tl = (Real)sqrt( tx * tx + ty * ty );
+ if (tl > 0.001f)
+ {
+ tx /= tl;
+ ty /= tl;
+ }
+ else
+ {
+ // two samples pointing exactly opposite each other: keep the one we are leaving
+ tx = a.tan.x;
+ ty = a.tan.y;
+ }
+
+ out->x = a.pos.x + (b.pos.x - a.pos.x) * f - ty * lat;
+ out->y = a.pos.y + (b.pos.y - a.pos.y) * f + tx * lat;
+ out->z = a.pos.z + (b.pos.z - a.pos.z) * f;
+}
+
+//-------------------------------------------------------------------------------------------------
+Real CrowdCorridor::clampLatAt( Real along, Real lat ) const
+{
+ Real f = 0.0f;
+ const Int i = bracket( along, &f );
+ const Int j = (i + 1 < (Int)m_samples.size()) ? i + 1 : i;
+
+ const Real left = m_samples[ i ].left + (m_samples[ j ].left - m_samples[ i ].left ) * f;
+ const Real right = m_samples[ i ].right + (m_samples[ j ].right - m_samples[ i ].right) * f;
+
+ if (lat > left) lat = left;
+ if (lat < -right) lat = -right;
+ return lat;
+}
+
+//-------------------------------------------------------------------------------------------------
+void CrowdCorridor::buildForTest( const Coord3D *pts, Int count, Real halfWidth, const PathfindLayerEnum *layers )
+{
+ m_samples.clear();
+ if (pts == NULL || count < 2)
+ return;
+
+ Real along = 0.0f;
+ for (Int k = 0; k < count; k++)
+ {
+ const Int ahead = (k + 1 < count) ? k + 1 : k;
+ const Int behind = (k + 1 < count) ? k : k - 1;
+
+ Real dx = pts[ ahead ].x - pts[ behind ].x;
+ Real dy = pts[ ahead ].y - pts[ behind ].y;
+ const Real d = (Real)sqrt( dx * dx + dy * dy );
+ if (d > 0.001f)
+ {
+ dx /= d;
+ dy /= d;
+ }
+
+ if (k > 0)
+ {
+ const Real sx = pts[ k ].x - pts[ k - 1 ].x;
+ const Real sy = pts[ k ].y - pts[ k - 1 ].y;
+ along += (Real)sqrt( sx * sx + sy * sy );
+ }
+
+ Sample s;
+ s.pos = pts[ k ];
+ s.tan.x = dx;
+ s.tan.y = dy;
+ s.left = halfWidth;
+ s.right = halfWidth;
+ s.along = along;
+ s.layer = layers ? layers[ k ] : LAYER_GROUND;
+ m_samples.push_back( s );
+ }
+}
+
+//-------------------------------------------------------------------------------------------------
+Bool Crowd_outranks( const Object *big, const Object *little )
+{
+ if (big == NULL || little == NULL)
+ return FALSE;
+ const Real rb = big->getGeometryInfo().getBoundingCircleRadius();
+ const Real rs = little->getGeometryInfo().getBoundingCircleRadius();
+ return rb > rs + 2.0f;
+}
+
+//-------------------------------------------------------------------------------------------------
+Real Crowd_gap( const Object *a, const Object *b )
+{
+ const Coord3D *pa = a->getPosition();
+ const Coord3D *pb = b->getPosition();
+ const Real dx = pb->x - pa->x;
+ const Real dy = pb->y - pa->y;
+ const Real d = (Real)sqrt( dx * dx + dy * dy );
+ return d - a->getGeometryInfo().getBoundingCircleRadius()
+ - b->getGeometryInfo().getBoundingCircleRadius();
+}
+
+//-------------------------------------------------------------------------------------------------
+Real Crowd_remaining( const Object *obj )
+{
+ const AIUpdateInterface *ai = obj ? obj->getAIUpdateInterface() : NULL;
+ if (ai == NULL)
+ return 0.0f;
+
+ /* Along the route, not across the map. Two units the same distance from the goal are not the
+ same distance from it when one of them has a hill in the way, and priority handed to the one
+ with the longer drive is priority handed to the wrong unit. */
+ const Path *path = ai->getPath();
+ if (path != NULL && path->hasCachedPointOnPath())
+ return path->peekCachedDistToGoal();
+
+ const Coord3D *goal = ai->getGoalPosition();
+ if (goal == NULL)
+ return 0.0f;
+ const Coord3D *pos = obj->getPosition();
+ const Real dx = goal->x - pos->x;
+ const Real dy = goal->y - pos->y;
+ return (Real)sqrt( dx * dx + dy * dy );
+}
+
+//-------------------------------------------------------------------------------------------------
+Real Crowd_brakeSpeed( Real speed, Real blockerSpeed, Real gap, Int frames )
+{
+ if (frames <= 0)
+ return speed;
+
+ /* His speed, plus enough to close the gap over `frames` frames rather than this one. The two
+ cases that need no brake fall out of the same line and are not worth testing for: a blocker
+ going as fast as us or faster puts `want` above `speed`, and so does a gap wider than the
+ closing speed can cross in the window. */
+ Real want = blockerSpeed + gap / (Real)frames;
+ if (want < 0.0f) want = 0.0f;
+ return (want < speed) ? want : speed;
+}
+
+//-------------------------------------------------------------------------------------------------
+Real Crowd_bendBonus( const CrowdCorridor *corr, Int sample, Real lat )
+{
+ if (corr == NULL || corr->isEmpty())
+ return 0.0f;
+
+ const Real curv = corr->curvature( sample );
+ if (fabs( curv ) < 0.08f)
+ return 0.0f;
+
+ // positive curvature is a left turn, and a unit on the left of a left turn is on the inside
+ const Real inside = (curv > 0.0f) ? lat : -lat;
+ if (inside <= 0.0f)
+ return 0.0f;
+
+ Real strength = fabs( curv ) * 2.0f;
+ if (strength > 1.0f) strength = 1.0f;
+ return inside * strength;
+}
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp
index 203450185..5e6ecf620 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp
@@ -47,6 +47,7 @@
#include "Common/UnitTimings.h"
#include "Common/Xfer.h"
#include "Common/XferCRC.h"
+#include "Lib/Trig.h"
#include "GameClient/ControlBar.h"
#include "GameClient/Drawable.h"
@@ -54,6 +55,7 @@
#include "GameLogic/AI.h"
#include "GameLogic/AIPathfind.h"
+#include "GameLogic/CrowdModel.h"
#include "GameLogic/Locomotor.h"
#include "GameLogic/Module/AIUpdate.h"
#include "GameLogic/Module/BodyModule.h"
@@ -302,6 +304,28 @@ AIUpdateInterface::AIUpdateInterface( Thing *thing, const ModuleData* moduleData
m_pathfindCurCell.x = m_pathfindCurCell.y = -1;
m_blockedFrames = 0;
m_curMaxBlockedSpeed = 0;
+ m_laneFraction = 0.5f;
+ m_laneFractionValid = FALSE;
+ m_laneHoldFrame = 0;
+ m_pendingLane = 0.5f;
+ m_hasPendingLane = FALSE;
+ m_corridor = NULL;
+ m_crowdLat = 0.0f;
+ m_pendingCrowdLat = 0.0f;
+ m_hasPendingCrowdLat = FALSE;
+ m_crowdLatValid = FALSE;
+ m_crowdHoldFrame = 0;
+ m_crowdSample = 0;
+ m_crowdQueued = 0;
+ m_crowdSide = 1;
+ m_crowdSepSmooth = 0.0f;
+ m_crowdAim = 0.0f;
+ m_crowdAimValid = FALSE;
+ m_crowdStuck = 0;
+ m_crowdLastPos.zero();
+ m_crowdEscape.zero();
+ m_crowdEscapeUntil = 0;
+ m_crowdEscapeCool = 0;
m_bumpSpeedLimit = FAST_AS_POSSIBLE;
m_ignoreCollisionsUntil = 0;
m_queueForPathFrame = 0;
@@ -1517,7 +1541,29 @@ Bool AIUpdateInterface::needToRotate(void)
//-------------------------------------------------------------------------------------------------
-/* Returns TRUE if the physics collide should apply the force. Normally not.
+// -crowd: the constants the steering stack is made of, all in world units (a pathfind cell is 10).
+//-------------------------------------------------------------------------------------------------
+static const Real CROWD_AIR = 4.0f; ///< air a body wants round it, on top of both radii
+static const Real CROWD_SEP_STEP = 1.5f; ///< most one frame of separation may move a lane
+static const Real CROWD_PASS_CLEAR = 6.0f; ///< room a passing lane leaves beside the blocker
+static const Real CROWD_TAPER_DIST = PATHFIND_CELL_SIZE_F * 8.0f; ///< the band closes over the last of the route
+static const Int CROWD_BRAKE_FRAMES = 8; ///< frames of closing time a brake is allowed to read
+static const Int CROWD_FAN_FRAMES = 30; ///< held up this long before spreading out
+static const Real CROWD_FAN_RATE = 0.8f; ///< and then sideways at this much a frame
+static const Real CROWD_SEP_FILTER = 0.13f; ///< how much of a frame's sideways push is believed (~4/sec)
+static const Real CROWD_AIM_CRUISE = 0.23f; ///< how fast the aim follows the route while driving (~7/sec)
+static const Real CROWD_AIM_URGENT = 0.67f; ///< and while manoeuvring (~20/sec), where lag is worse than twitch
+static const Real CROWD_AIM_DEAD = 0.035f; ///< two degrees: hold the wheel still rather than chase the noise
+static const Int CROWD_STUCK_PRESS = 10; ///< a third of a second of getting nowhere: stop being polite
+static const Int CROWD_STUCK_GIVEUP = 60; ///< two seconds of it: back out of wherever this is
+static const Int CROWD_ESCAPE_FRAMES = 66; ///< and spend this long doing it before giving the route another go
+static const Int CROWD_ESCAPE_COOL = 90; ///< no second attempt before this, or a wedged pair rock forever
+static const Int CROWD_MERGE_FRAMES = 45; ///< a second and a half: how far ahead a merge is worth noticing
+static const Real CROWD_LOOK_FRAMES = 16.0f; ///< half a second: the travel the aim filter is damped against
+static const Real CROWD_AIM_SLOWEST = 0.08f; ///< however fast the chassis, the aim still follows this much of the error
+
+//-------------------------------------------------------------------------------------------------
+/* Returns TRUE if the physics collide should apply the force. Normally not.
Also determines whether objects are blocked, and if so, if they are stuck. jba.*/
Bool AIUpdateInterface::processCollision(PhysicsBehavior *physics, Object *other)
{
@@ -1560,11 +1606,17 @@ Bool AIUpdateInterface::processCollision(PhysicsBehavior *physics, Object *other
}
Real maxSpeed = calculateMaxBlockedSpeed(other);
- if (maxSpeed < m_curMaxBlockedSpeed)
+ if (maxSpeed < m_curMaxBlockedSpeed)
{
m_curMaxBlockedSpeed = maxSpeed;
}
+ // before settling in behind him, see whether the route is wide enough to go round.
+ // under -crowd the same decision is made every frame in crowdSteer, off the band and the
+ // whole neighbourhood rather than off this one collision, so the old rule stands down
+ if (!TheGlobalData->m_crowdModel)
+ tryLaneChangeAround(other);
+
if (!aiOther->isMovingAwayFrom(getObject())) {
if (other->isKindOf(KINDOF_INFANTRY) && !getObject()->isKindOf(KINDOF_INFANTRY))
@@ -1604,6 +1656,25 @@ Bool AIUpdateInterface::processCollision(PhysicsBehavior *physics, Object *other
// (asking the idle allied blocker to step aside was tried here and reverted:
// at a group's destination every arriving unit shoved the parked ones, which
// shoved others - the group milled about and repathed without end)
+ //
+ /* -crowd asks again, under the three conditions that revert was missing. We have
+ to have been held up for a while, so an arrival that clears on its own is left
+ alone; we have to still have somewhere to be, which is what stops the whole thing
+ at a destination where nobody does; and the parked unit has to be the smaller of
+ the two, so a mob of infantry cannot pass a tank around by taking turns to shove
+ it. */
+ if (TheGlobalData->m_crowdModel
+ && m_crowdQueued > CROWD_FAN_FRAMES * 2
+ && Crowd_remaining(getObject()) > PATHFIND_CELL_SIZE_F * 3.0f
+ && !crowdOutranksMe(other)
+ && !aiOther->isMovingAwayFrom(getObject())
+ && !aiOther->isBusy()
+ && !other->testStatus(OBJECT_STATUS_IS_USING_ABILITY))
+ {
+ aiOther->aiMoveAwayFromUnit(getObject(), CMD_FROM_AI);
+ m_crowdQueued = 0; // he has been asked; give him time to answer
+ return FALSE;
+ }
// Intense logging jba
// DEBUG_LOG(("Blocked&Stuck !otherMoving\n"));
m_isBlockedAndStuck = TRUE;
@@ -1615,8 +1686,13 @@ Bool AIUpdateInterface::processCollision(PhysicsBehavior *physics, Object *other
{
if (!aiOther->needToRotate())
{
- // Deadlocked.
- if (!hasHigherPathPriority(aiOther))
+ // Deadlocked. -crowd settles it by size and by who is nearer the end of his
+ // route, which is the same order the steering used all the way here; retail
+ // settles it by who is carrying the more urgent kind of order
+ const Bool yield = TheGlobalData->m_crowdModel
+ ? crowdOutranksMe(other)
+ : !hasHigherPathPriority(aiOther);
+ if (yield)
{
// get out of his way.
aiMoveAwayFromUnit(aiOther->getObject(), CMD_FROM_AI);
@@ -2135,9 +2211,782 @@ void AIUpdateInterface::destroyPath( void )
m_waitingForPath = FALSE; // we no longer need it.
//CRCDEBUG_LOG(("AIUpdateInterface::destroyPath() - m_isAttackPath = FALSE for object %d\n", getObject()->getID()));
m_isAttackPath = FALSE;
+ // the lane belongs to the route, not to the unit: a new route gets a new one, seeded off
+ // wherever the unit is standing when it is handed
+ m_laneFractionValid = FALSE;
+ crowdReleaseCorridor();
setLocomotorGoalNone();
}
+//-------------------------------------------------------------------------------------------------
+/** The band was measured against one route and means nothing against another, so it dies with the
+ path. m_crowdSample going back to 0 also clears the "this route has no band" latch, which is
+ what stops a unit on a two-cell path from re-probing every frame for the rest of its life. */
+//-------------------------------------------------------------------------------------------------
+void AIUpdateInterface::crowdReleaseCorridor( void )
+{
+ if (m_corridor)
+ {
+ delete m_corridor;
+ m_corridor = NULL;
+ }
+ m_crowdLatValid = FALSE;
+ m_crowdSample = 0;
+ m_crowdQueued = 0;
+ m_crowdHoldFrame = 0;
+ m_crowdSepSmooth = 0.0f;
+ m_crowdAimValid = FALSE;
+ m_crowdStuck = 0;
+ /* The backing-out manoeuvre survives the route. Being wedged is the one thing a new route does
+ not cure - the new one starts in the same hole - and a unit that repaths every second while
+ stuck would throw away the only rule that gets it out, once a second, forever. */
+}
+
+//-------------------------------------------------------------------------------------------------
+/**
+ * Pick where across the route's width this unit rides.
+ *
+ * The lane has to be handed down by whoever issued the order, and the first version of this
+ * measured it here instead, which was worth nothing: a unit's route starts under its own tracks,
+ * so its sideways distance from that route is zero and every member of a group came out at 0.5.
+ * A group therefore has to say, at order time, where each member sat across the group - see
+ * AIGroup::groupMoveToPosition. A unit ordered on its own has no group to sit across and rides
+ * the centre, which is what retail does anyway.
+ */
+//-------------------------------------------------------------------------------------------------
+void AIUpdateInterface::seedLaneFraction( void )
+{
+ Bool hadPending = m_hasPendingLane;
+
+ m_laneFraction = m_hasPendingLane ? m_pendingLane : 0.5f;
+ m_laneFractionValid = TRUE;
+ m_laneHoldFrame = 0;
+ m_hasPendingLane = FALSE;
+
+ if (TheGlobalData->m_noLanePath)
+ m_laneFraction = 0.5f;
+
+ // the other end of the SHOWLANES trail: a lane handed out at order time is worth nothing if the
+ // path arrives after something else has already seeded this unit at the centre.
+ if (TheGlobalData->m_showLanes)
+ {
+ DEBUG_LOG(("SHOWLANES seed: unit %d pending=%d lane=%.2f\n", getObject()->getID(),
+ hadPending ? 1 : 0, m_laneFraction));
+ }
+}
+
+//-------------------------------------------------------------------------------------------------
+/**
+ * Take a different lane to get past a unit that is in the way and not going anywhere.
+ *
+ * The alternative retail offers is to wait, count blocked frames, and eventually spend a search on
+ * a route that starts from the middle of the queue - which is how a column of tanks turns into a
+ * column of stopped tanks. Sliding across the band costs no search at all: the route is unchanged,
+ * only the point on it the unit steers at moves. The lane is held for a while so it does not flap
+ * between the two sides of a blocker who is himself drifting, and it is paid for in a little speed.
+ */
+//-------------------------------------------------------------------------------------------------
+void AIUpdateInterface::tryLaneChangeAround( Object *other )
+{
+ if (TheGlobalData->m_noLanePath)
+ return;
+ if (!m_laneFractionValid || getPath() == NULL)
+ return;
+ if (TheGameLogic->getFrame() < m_laneHoldFrame)
+ return;
+ if (m_curLocomotor == NULL)
+ return;
+
+ // only worth going round somebody slower than us; anybody keeping up will clear on his own
+ Real mySpeed = m_curLocomotor->getMaxSpeedForCondition(getObject()->getBodyModule()->getDamageState());
+ if (mySpeed < 0.05f)
+ return;
+ /* How fast the blocker is actually going, not how fast his engine could. Comparing top speeds
+ means a column of identical tanks never passes anything: every one of them reports full
+ speed while crawling nose to tail behind the same jam, so the one mechanism that could
+ break the queue up refused to fire in exactly the case it was written for. */
+ AIUpdateInterface *aiOther = other->getAI();
+ Real hisSpeed = 0.0f;
+ if (aiOther != NULL && aiOther->isMoving() && other->getPhysics() != NULL)
+ hisSpeed = other->getPhysics()->getVelocityMagnitude();
+ if (hisSpeed > mySpeed * 0.8f)
+ return;
+
+ Coord3D onPath;
+ Coord2D dir;
+ if (!getPath()->closestPointAndDir(*getObject()->getPosition(), &onPath, &dir))
+ return;
+
+ Coord2D left, right;
+ left.x = -dir.y; left.y = dir.x;
+ right.x = dir.y; right.y = -dir.x;
+
+ Pathfinder *pf = TheAI->pathfinder();
+ PathfindLayerEnum layer = getObject()->getLayer();
+ Real leftRoom = pf->laneExtent(getObject(), m_locomotorSet, layer, &onPath, &left);
+ Real rightRoom = pf->laneExtent(getObject(), m_locomotorSet, layer, &onPath, &right);
+ Real width = leftRoom + rightRoom;
+ if (width < 1.0f)
+ return; // a doorway has no room to pass in, and pretending otherwise just wedges both units
+
+ // where the blocker sits across the same band, and how far past him we have to be to clear
+ Real hisLateral = (other->getPosition()->x - onPath.x) * left.x
+ + (other->getPosition()->y - onPath.y) * left.y;
+ Real hisFraction = Pathfinder_laneFraction(hisLateral, leftRoom, rightRoom);
+ Real gap = (getObject()->getGeometryInfo().getBoundingCircleRadius()
+ + other->getGeometryInfo().getBoundingCircleRadius()) / width;
+
+ // prefer the side we are already on, and take the other one if that side has no room
+ Real want = (m_laneFraction >= hisFraction) ? (hisFraction + gap) : (hisFraction - gap);
+ if (want > 0.95f || want < 0.05f)
+ want = (m_laneFraction >= hisFraction) ? (hisFraction - gap) : (hisFraction + gap);
+ if (want > 0.95f || want < 0.05f)
+ return;
+ if (fabs(want - m_laneFraction) < 0.02f)
+ return;
+
+ m_laneFraction = want;
+ m_laneHoldFrame = TheGameLogic->getFrame() + PF_LANE_HOLD_FRAMES;
+ getPath()->invalidateCachedPointOnPath(); // or we steer at the old lane for another twenty frames
+
+ // a unit crabbing sideways is not driving forwards at full speed
+ Real cap = mySpeed * 0.85f;
+ if (cap < m_curMaxBlockedSpeed)
+ m_curMaxBlockedSpeed = cap;
+}
+
+//-------------------------------------------------------------------------------------------------
+/**
+ * Right of way between two units, decided the same way by both of them.
+ *
+ * Size first, because a bigger body has less room to be squeezed and shoving it is what wedges a
+ * doorway. Then how much route is left, so the unit nearly there is let out rather than made to
+ * wait behind one that has half a map to cross. The inside of a bend counts as being further along
+ * than it is: it is the position with no room, and letting it out first is what lets the rest flow
+ * round the corner instead of all four of them arriving at the apex together. Id last, which
+ * decides nothing on the ground but guarantees the two answers are opposites.
+ */
+//-------------------------------------------------------------------------------------------------
+Bool AIUpdateInterface::crowdOutranksMe( Object *other ) const
+{
+ const Object *self = getObject();
+ if (other == NULL)
+ return FALSE;
+
+ if (Crowd_outranks( other, self ))
+ return TRUE;
+ if (Crowd_outranks( self, other ))
+ return FALSE;
+
+ Real mine = Crowd_remaining( self ) - Crowd_bendBonus( m_corridor, m_crowdSample, m_crowdLat );
+ Real his = Crowd_remaining( other );
+ const AIUpdateInterface *ai = other->getAIUpdateInterface();
+ if (ai != NULL)
+ his -= Crowd_bendBonus( ai->getCrowdCorridor(), ai->getCrowdSample(), ai->getCrowdLat() );
+
+ if (fabs( mine - his ) > 1.0f)
+ return his < mine;
+
+ return other->getID() < self->getID();
+}
+
+//-------------------------------------------------------------------------------------------------
+/**
+ * Where across the route to drive this frame, and how fast.
+ *
+ * This is the whole -crowd model, and it is one function on purpose: every rule in it reads the
+ * same neighbour scan and writes the same two numbers, and the only two numbers the engine's
+ * steering will accept are the point to aim at and the speed to aim at it with. Retail has one
+ * reactive rule (a collision, once it has already happened, caps the speed) and consequently a
+ * group of twenty crosses a map in single file and stops dead in a doorway.
+ *
+ * Order matters and is the sandbox's: give way to something bigger coming up behind, then deal with
+ * whatever is directly ahead - pass it if there is room, brake if there is not - then spread out,
+ * but only while actually held up, then push apart from whoever is too close. Separation last
+ * because it is the smallest correction and has to win the tie; fanning out before it, because a
+ * unit that has been stopped for a second wants a different lane and not a nudge.
+ */
+//-------------------------------------------------------------------------------------------------
+/** Somewhere a wedged unit can back out to, or FALSE if it is walled in on every side.
+ Sideways first and backwards second: the ground ahead is what it is already failing to drive
+ through, and a unit that has been stationary for two seconds is in a hole its own route made. */
+//-------------------------------------------------------------------------------------------------
+static Bool crowdFindEscape( Object *self, const LocomotorSet& locoSet, const Coord2D& tan,
+ Int firstSide, Coord3D *out )
+{
+ const Coord3D *pos = self->getPosition();
+ const Real myR = self->getGeometryInfo().getBoundingCircleRadius();
+ const Real across = myR * 2.0f + PATHFIND_CELL_SIZE_F;
+ const Real behind = myR + PATHFIND_CELL_SIZE_F * 0.5f;
+ const Bool crusher = self->getCrusherLevel() > 0;
+ const PathfindLayerEnum layer = self->getLayer();
+
+ const Real sx = -tan.y, sy = tan.x; // left of the route
+ for (Int t = 0; t < 4; t++)
+ {
+ // out and back to the roomier side, out and back the other way, straight out, straight back
+ const Real side = (t == 1) ? -(Real)firstSide : (Real)firstSide;
+ const Real lat = (t < 3) ? across : 0.0f;
+ const Real back = (t < 2) ? behind : ((t == 2) ? 0.0f : across);
+
+ Coord3D p;
+ p.x = pos->x + sx * lat * side - tan.x * back;
+ p.y = pos->y + sy * lat * side - tan.y * back;
+ p.z = TheTerrainLogic->getGroundHeight( p.x, p.y );
+ if (TheAI->pathfinder()->validMovementPosition( crusher, layer, locoSet, &p ))
+ {
+ *out = p;
+ return TRUE;
+ }
+ }
+ return FALSE;
+}
+
+//-------------------------------------------------------------------------------------------------
+void AIUpdateInterface::crowdSteer( Coord3D& goalPos, Real& speed )
+{
+ Object *self = getObject();
+ Path *path = getPath();
+ if (path == NULL || m_curLocomotor == NULL)
+ return;
+
+ /* Only units that were sent somewhere as a group. A group order hands every member a lane
+ before the paths exist, and that hand-out is the flag: no lane handed down, no band, and the
+ unit drives retail's centre line. A unit crossing a map on its own has nobody to share the
+ road with, and the rules below then cost it real time - they are written to resolve traffic,
+ and a single vehicle repositioning inside a firefight is not traffic. */
+ if (!m_hasPendingCrowdLat && !m_crowdLatValid)
+ return;
+
+ /* The band is measured once per route. m_crowdSample = -1 is the latch for a route too short
+ to have one, without which a unit driving the last two cells of its path re-probes two
+ hundred cells every frame for the rest of its life. */
+ if (m_corridor == NULL)
+ {
+ if (m_crowdSample < 0)
+ return;
+ CrowdCorridor *corr = new CrowdCorridor;
+ if (!corr->build( self, m_locomotorSet, path ))
+ {
+ delete corr;
+ m_crowdSample = -1;
+ return;
+ }
+ m_corridor = corr;
+ m_crowdSample = 0;
+ // the lane is not cleared here: destroyPath already did that for a new route, and a save
+ // reloaded mid-drive has to come back in the lane it was saved in rather than at the centre
+ }
+
+ const Coord3D *myPos = self->getPosition();
+ const Int i = m_corridor->nearest( *myPos, m_crowdSample );
+ m_crowdSample = i;
+
+ const CrowdCorridor::Sample& here = m_corridor->at( i );
+ const Real myR = self->getGeometryInfo().getBoundingCircleRadius();
+
+ /* The last cell of the route is arrival, and arrival is not a formation problem. Only the last
+ cell: standing the rules down over the last four instead - on the theory that a short hop
+ inside a firefight is not a march - measures three times worse (298 blocked unit-frames per
+ 1000 against 108). Short hops are exactly where units are packed tightest. */
+ if (m_corridor->length() - here.along < PATHFIND_CELL_SIZE_F)
+ return;
+
+ if (!m_crowdLatValid)
+ {
+ /* A unit ordered on its own rides wherever it is already standing, which for a route that
+ starts under its own tracks is the centre line - retail's answer, and the right one. A
+ unit ordered as part of a group was told where to sit before the path existed. */
+ m_crowdLat = m_hasPendingCrowdLat ? m_pendingCrowdLat : m_corridor->latOf( i, *myPos );
+ m_hasPendingCrowdLat = FALSE;
+ m_crowdLatValid = TRUE;
+ m_crowdSide = (here.left >= here.right) ? 1 : -1;
+ }
+
+ const UnsignedInt now = TheGameLogic->getFrame();
+
+ /* ---- how long this unit has been asking to move and not moving ----
+ Not the same question as m_blockedFrames, which is about collisions: a unit facing the wrong
+ way, one whose speed cap has been talked down to nothing by the rules below, and one wedged
+ between two allies it never quite touches are all standing still without a collision to show
+ for it. This counts the ground covered against the speed asked for, which catches all three
+ and is the number the whole ladder below is hung off. */
+ const Real dxMoved = myPos->x - m_crowdLastPos.x;
+ const Real dyMoved = myPos->y - m_crowdLastPos.y;
+ const Real moved = (Real)sqrt( dxMoved * dxMoved + dyMoved * dyMoved );
+ if (speed > 0.01f && moved < speed * 0.2f)
+ ++m_crowdStuck;
+ else
+ m_crowdStuck = 0;
+ m_crowdLastPos = *myPos;
+
+ /* ---- and what to do about it ----
+ Two rungs. The first stands the courtesies down: a unit that is getting nowhere has already
+ given way, braked and queued for a third of a second, and every one of those rules is now
+ costing it the speed it needs to push through. The second backs it out. Two seconds of
+ nothing is not traffic, it is a wedge - between two allies, in the corner of a cliff, against
+ the one tank in the column that is never going to move - and no amount of steering along a
+ route that leads through the wedge gets out of it. Retail's answer is to keep driving into
+ whatever it is until the pathfinder notices; that works when there is a collision to count,
+ and this is the case where there is not. */
+ const Bool pressing = m_crowdStuck > CROWD_STUCK_PRESS;
+
+ if (m_crowdEscapeUntil > 0)
+ {
+ const Real edx = m_crowdEscape.x - myPos->x;
+ const Real edy = m_crowdEscape.y - myPos->y;
+ const Bool arrived = (Real)sqrt( edx * edx + edy * edy ) < myR + 2.0f;
+ if (arrived || now >= m_crowdEscapeUntil)
+ {
+ m_crowdEscapeUntil = 0;
+ m_crowdEscapeCool = now + CROWD_ESCAPE_COOL;
+ m_crowdStuck = 0;
+ }
+ else
+ {
+ // nothing else applies: the route is what it is wedged against
+ goalPos = m_crowdEscape;
+ goalPos.z = TheTerrainLogic->getGroundHeight( goalPos.x, goalPos.y );
+ m_crowdQueued = 0;
+ m_crowdAimValid = FALSE; // the aim filter is for following a route, not for getting out of a hole
+ if (TheGlobalData->m_showLanes && (now % LOGICFRAMES_PER_SECOND) == 0)
+ DEBUG_LOG(("SHOWLANES crowd: unit %d escape to %.0f,%.0f\n", self->getID(), goalPos.x, goalPos.y));
+ return;
+ }
+ }
+ else if (m_crowdStuck > CROWD_STUCK_GIVEUP && now >= m_crowdEscapeCool)
+ {
+ const Int firstSide = (here.left >= here.right) ? 1 : -1;
+ if (crowdFindEscape( self, m_locomotorSet, here.tan, firstSide, &m_crowdEscape ))
+ {
+ m_crowdEscapeUntil = now + CROWD_ESCAPE_FRAMES;
+ m_crowdStuck = 0;
+ return;
+ }
+ // walled in on all four sides: keep trying the route, and ask again in a second
+ m_crowdStuck = CROWD_STUCK_GIVEUP - LOGICFRAMES_PER_SECOND;
+ }
+
+ //--- one scan, every rule reads it -------------------------------------------------------------
+ const Real scanRange = PATHFIND_CELL_SIZE_F * 4.0f + myR;
+ const Real lookAhead = PATHFIND_CELL_SIZE_F * (Real)CROWD_LOOKAHEAD_CELLS + myR;
+
+ PartitionFilterRelationship fRel( self, PartitionFilterRelationship::ALLOW_ALLIES );
+ PartitionFilterAlive fAlive;
+ PartitionFilterSameMapStatus fMap( self );
+ PartitionFilter *filters[] = { &fRel, &fAlive, &fMap, NULL };
+ SimpleObjectIterator *iter = ThePartitionManager->iterateObjectsInRange( self, scanRange, FROM_CENTER_2D, filters );
+ MemoryPoolObjectHolder hold( iter );
+
+ Real sep = 0.0f; // how far sideways the crowd is pushing us
+ Object *blocker = NULL; // nearest thing directly in the way
+ Real blockerFwd = 0.0f;
+ Real blockerGap = 0.0f;
+ Real blockerSpeed = 0.0f;
+ Bool blockerMoving = FALSE;
+ Bool giveWay = FALSE;
+ Real giveWayLat = 0.0f;
+ Int rank = 0; // how many held-up neighbours are ahead of us in the queue
+ Bool touching = FALSE; // somebody's body is inside ours right now
+ Object *joiner = NULL; // somebody coming in from the side who will cross our line
+ Real joinerSide = 0.0f;
+ Real joinerR = 0.0f;
+ Real joinerWhen = 1.0e9f;
+
+ PhysicsBehavior *myPhys = self->getPhysics();
+ Coord3D myVel;
+ myVel.zero();
+ if (myPhys != NULL)
+ myVel = *myPhys->getVelocity();
+
+ for (Object *o = iter->first(); o; o = iter->next())
+ {
+ if (o == self)
+ continue;
+ AIUpdateInterface *ai = o->getAI();
+ if (ai == NULL || !ai->isDoingGroundMovement())
+ continue;
+
+ /* Infantry walks through infantry, and the band is not allowed to take that back. Retail's
+ own rule is in blockedBy: two foot soldiers block each other only while they are going the
+ same way, and two squads crossing pass straight through one another. Left in the scan
+ below, a crossing squad reads as a wall of blockers - every man of it brakes, gives way and
+ shuffles sideways for a crowd he is supposed to walk into. Same dot product as blockedBy's
+ so the two agree; a column following a column is still traffic and still gets the rules. */
+ if (self->isKindOf( KINDOF_INFANTRY ) && o->isKindOf( KINDOF_INFANTRY ))
+ {
+ const Coord3D *myDir = self->getUnitDirectionVector2D();
+ const Coord3D *hisDir = o->getUnitDirectionVector2D();
+ if (myDir->x * hisDir->x + myDir->y * hisDir->y <= 0.25f)
+ continue;
+ }
+
+ const Coord3D *hp = o->getPosition();
+ const Real dx = hp->x - myPos->x;
+ const Real dy = hp->y - myPos->y;
+ const Real fwd = dx * here.tan.x + dy * here.tan.y; // along our route
+ const Real side = -dx * here.tan.y + dy * here.tan.x; // across it, left positive
+ const Real hisR = o->getGeometryInfo().getBoundingCircleRadius();
+ const Real gap = (Real)sqrt( dx * dx + dy * dy ) - myR - hisR;
+ const Real comfort = myR + hisR + CROWD_AIR;
+
+ PhysicsBehavior *hisPhys = o->getPhysics();
+ const Bool hisMoving = ai->isMoving() && hisPhys != NULL && hisPhys->getVelocityMagnitude() > 0.05f;
+
+ if (gap < 0.0f)
+ touching = TRUE;
+
+ /* Somebody joining our road from the side, which is the case braking handles worst: he is not
+ in front of us yet, so nothing slows down, and by the time he is, both of us are in the same
+ square. Moving over for him costs nothing and turns a queue into a zipper.
+
+ The test is a real closest approach on the two current courses, not a cone. Anything looser
+ and a column shuffles sideways for every unit driving vaguely alongside it, which costs more
+ speed than the braking it replaces. */
+ if (hisMoving && fabs( side ) > (myR + hisR) * 0.5f && hisPhys != NULL)
+ {
+ const Coord3D *hv = hisPhys->getVelocity();
+ const Real hs = (Real)sqrt( hv->x * hv->x + hv->y * hv->y );
+ if (hs > 0.01f)
+ {
+ const Real align = (hv->x * here.tan.x + hv->y * here.tan.y) / hs;
+ // a merge comes in at an angle: parallel traffic is the stream itself, head-on is not a merge
+ if (align > 0.35f && align < 0.8f)
+ {
+ const Real rvx = hv->x - myVel.x;
+ const Real rvy = hv->y - myVel.y;
+ const Real rvv = rvx * rvx + rvy * rvy;
+ if (rvv > 1.0e-6f)
+ {
+ const Real when = -(dx * rvx + dy * rvy) / rvv; // frames to closest approach
+ if (when >= 0.0f && when < (Real)CROWD_MERGE_FRAMES && when < joinerWhen)
+ {
+ const Real mx = dx + rvx * when;
+ const Real my = dy + rvy * when;
+ if ((Real)sqrt( mx * mx + my * my ) < myR + hisR + 0.8f && crowdOutranksMe( o ))
+ {
+ joiner = o;
+ joinerSide = side;
+ joinerR = hisR;
+ joinerWhen = when;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // abreast and too close: push apart
+ if (gap < comfort && fabs( fwd ) < myR + hisR)
+ {
+ Real dir;
+ if (fabs( side ) > 0.01f)
+ dir = (side > 0.0f) ? -1.0f : 1.0f;
+ else
+ dir = (o->getID() < self->getID()) ? -1.0f : 1.0f; // exactly abreast; somebody has to pick
+ sep += dir * (comfort - gap);
+ }
+
+ /* Something bigger coming up behind in our lane. It cannot go round us in the room it has
+ and it will not stop, so the courtesy is ours to extend, and extending it costs us a lane
+ rather than a stop. */
+ if (!giveWay && hisMoving && fwd < 0.0f && Crowd_outranks( o, self )
+ && fabs( side ) < myR + hisR + CROWD_AIR)
+ {
+ const Real away = myR + hisR + CROWD_AIR;
+ Real dir;
+ if (fabs( side ) > 0.01f)
+ dir = (side > 0.0f) ? -1.0f : 1.0f;
+ else
+ dir = (Real)m_crowdSide;
+ /* Clear of *his* line, not of wherever we happen to be. Stepping aside from our own
+ current lane looks the same for one frame and is not the same thing at all: the lane it
+ produces is the input to the next frame's step, so a unit given way to for a second walks
+ itself out to the edge of the band a body width at a time. */
+ giveWayLat = m_corridor->latOf( i, *hp ) + dir * away;
+ giveWay = TRUE;
+ }
+
+ // directly ahead, near enough to matter
+ if (fwd > 0.0f && fwd < lookAhead + hisR && fabs( side ) < myR + hisR + 1.0f)
+ {
+ if (blocker == NULL || fwd < blockerFwd)
+ {
+ blocker = o;
+ blockerFwd = fwd;
+ blockerGap = gap;
+ blockerSpeed = 0.0f;
+ blockerMoving = hisMoving;
+ if (hisPhys != NULL)
+ {
+ const Coord3D *v = hisPhys->getVelocity();
+ blockerSpeed = v->x * here.tan.x + v->y * here.tan.y; // his speed our way, not his speed
+ if (blockerSpeed < 0.0f)
+ blockerSpeed = 0.0f;
+ }
+ }
+ }
+
+ // our place in the queue, which is how far out we fan when it stops moving
+ if (gap < comfort * 2.0f && crowdOutranksMe( o ))
+ ++rank;
+ }
+
+ //--- the rules, in order -----------------------------------------------------------------------
+ Real lat = m_crowdLat;
+ Real cap = speed;
+ Bool queued = FALSE;
+ Bool merged = FALSE;
+
+ if (giveWay && !pressing)
+ {
+ lat = giveWayLat;
+ m_crowdHoldFrame = now + CROWD_HOLD_FRAMES;
+ }
+
+ /* Make room for the joiner rather than braking for him, and only for one we would have had to
+ brake for anyway - crowdOutranksMe already asked that question. A unit that is itself getting
+ nowhere extends no courtesies: it has none to spare. */
+ if (joiner != NULL && !pressing)
+ {
+ const Real shift = myR + joinerR + 0.5f;
+ const Real want = lat - ((joinerSide > 0.0f) ? shift : -shift);
+ if (fabs( m_corridor->clampLat( i, want ) - want ) < 0.5f)
+ {
+ lat = want;
+ m_crowdHoldFrame = now + CROWD_HOLD_FRAMES;
+ merged = TRUE;
+ }
+ }
+
+ if (blocker != NULL && !pressing)
+ {
+ if (!crowdOutranksMe( blocker ))
+ {
+ // we have right of way; he is the one who has to move, and we only avoid rear-ending him
+ if (blockerMoving && blockerGap < myR && blockerSpeed < cap)
+ cap = blockerSpeed;
+ }
+ else
+ {
+ const Real hisR = blocker->getGeometryInfo().getBoundingCircleRadius();
+ const Real hisLat = m_corridor->latOf( i, *blocker->getPosition() );
+ const Real shift = myR + hisR + CROWD_PASS_CLEAR;
+
+ /* Pass on the outside of a bend. The inside is where the road runs out, and a unit that
+ dives up the inside of a turn to get past somebody arrives at the apex with a wall on
+ one side and the unit it just passed on the other. */
+ const Real curv = m_corridor->curvature( i );
+ Int first = (fabs( curv ) > 0.08f) ? ((curv > 0.0f) ? -1 : 1) : m_crowdSide;
+
+ Bool took = FALSE;
+ if (now >= m_crowdHoldFrame)
+ {
+ for (Int t = 0; t < 2 && !took; t++)
+ {
+ const Real want = hisLat + (Real)((t == 0) ? first : -first) * shift;
+ if (fabs( m_corridor->clampLat( i, want ) - want ) < 0.5f)
+ {
+ lat = want;
+ m_crowdSide = (want >= hisLat) ? 1 : -1;
+ m_crowdHoldFrame = now + CROWD_HOLD_FRAMES;
+ took = TRUE;
+ }
+ }
+ }
+
+ if (!took)
+ {
+ queued = TRUE;
+
+ /* Brake behind a unit that is going somewhere, and never behind one that is not.
+ A parked ally on the route is not traffic, it is an obstacle, and the engine already
+ knows what to do about obstacles: drive into it, count the blocked frames, repath.
+ Braking short of it instead means the collision never happens, m_blockedFrames never
+ rises, and every piece of retail's stuck machinery sits idle while the column dies
+ politely a metre behind a tank that is never going to move. That one line was worth
+ 16593 blocked unit-frames against a baseline of 507. */
+ /* And then only when we are actually going to hit him. Braking by distance slows the
+ whole march: a unit ten units behind traffic moving at its own speed is not catching
+ anybody up, and pricing that gap costs 60% of the column's speed for nothing. Closing
+ speed and the time it leaves is the only thing worth reading. */
+ if (blockerMoving)
+ {
+ const Real want = Crowd_brakeSpeed( speed, blockerSpeed, blockerGap, CROWD_BRAKE_FRAMES );
+ if (want < cap)
+ cap = want;
+ }
+ }
+ }
+ }
+
+ if (queued)
+ ++m_crowdQueued;
+ else if (m_crowdQueued > 0)
+ --m_crowdQueued;
+
+ /* Fanning out is only worth anything while stopped. Doing it all the time is a formation, and
+ a formation held across a map is what drives a group into every obstacle sideways-on; the
+ sandbox spreads out at the back of a jam and closes up again the moment it clears. */
+ if (m_crowdQueued > CROWD_FAN_FRAMES && !pressing)
+ {
+ /* Two bodies off the line is a wide road. Multiplying by the whole queue rank is how the
+ eighth unit in a jam ends up eighty units into the scenery, still politely queueing. */
+ Int step = rank + 1;
+ if (step > 2) step = 2;
+ const Real target = (Real)m_crowdSide * (2.0f * myR + CROWD_PASS_CLEAR) * (Real)step;
+ if (target > lat + 0.1f)
+ lat += CROWD_FAN_RATE;
+ else if (target < lat - 0.1f)
+ lat -= CROWD_FAN_RATE;
+ }
+
+ /* Separation goes into the lane and stays there. Steering with it frame by frame and leaving
+ the lane where it was reads better on paper - a shove is not a decision - and measures worse:
+ 3312 blocked unit-frames against 1236 over the same eight seeds. A shove that is forgotten
+ has to be paid again every frame, and two units abreast in a narrow band spend the whole
+ drive rediscovering each other. */
+ /* Through a filter on the way in, though. The raw push is the sum over whoever happens to be
+ inside the comfort radius this frame, and that set changes every frame: one neighbour drifting
+ in and out of range flips the push by a body width and back again, and the lane - and with it
+ the point the unit is aiming at - shimmers. */
+ m_crowdSepSmooth += (sep - m_crowdSepSmooth) * CROWD_SEP_FILTER;
+ sep = m_crowdSepSmooth;
+ if (sep > CROWD_SEP_STEP) sep = CROWD_SEP_STEP;
+ if (sep < -CROWD_SEP_STEP) sep = -CROWD_SEP_STEP;
+ lat += sep;
+
+ /* Everything above chose a lane; this is the only place the unit is allowed to move into one,
+ and never faster than it drives. Giving way and passing both name a lane a full body width
+ away, and taking it in one frame swings the aim point twenty-odd feet sideways two cells in
+ front of the tracks - which is a turn no tank can make, so the unit stops and rotates on the
+ spot, and by the time it is facing the new lane the rule that asked for it has moved on. The
+ spinning and the rocking back and forth are both this. A quarter of forward speed sideways
+ is about twenty degrees of steering, which a tank takes without stopping. */
+ const Real laneRate = (speed * 0.25f > 0.4f) ? speed * 0.25f : 0.4f;
+ Real move = m_corridor->clampLat( i, lat ) - m_crowdLat;
+ if (move > laneRate) move = laneRate;
+ if (move < -laneRate) move = -laneRate;
+ m_crowdLat = m_corridor->clampLat( i, m_crowdLat + move );
+
+ // ease off through a bend, or the outside of the group is asked for a speed it cannot turn at
+ const Real bend = (Real)fabs( m_corridor->curvature( i ) );
+ if (bend > 0.15f)
+ {
+ Real f = 1.0f - bend * 0.5f;
+ if (f < 0.55f) f = 0.55f;
+ cap *= f;
+ }
+
+ //--- and finally, the two numbers the locomotor takes ------------------------------------------
+ /* How far ahead to steer. The distance is the old one, two cells and a body; what changed is
+ where it is measured from. Taking the point at a sample index quantises it: the aim jumped a
+ whole cell forward every time the unit crossed a sample boundary, and on anything but a
+ straight the direction handed to the locomotor stepped with it. It runs off the unit's own
+ unquantised distance along the route now, and the point is taken between samples, so it slides.
+
+ Making the distance itself a travel time was tried and reverted. It cures the same wobble and
+ costs four times the stuck units: on forty maps, 4667 blocked unit-frames a match and 1.4 stuck
+ became 5159 and 5.4, and clamping the horizon where the route bends recovered none of it (29 of
+ 39 seeds came back bit-identical). A point fifty feet up the road is measured against ground
+ fifty feet up the road, and the narrow bit in between is not consulted by anybody. The chassis
+ difference is dealt with in the aim filter below instead, where being wrong only costs lag. */
+ const Real myAlong = m_corridor->alongOf( i, *myPos );
+ const Real routeLen = m_corridor->length();
+
+ Real wantAlong = myAlong + lookAhead;
+ if (wantAlong > routeLen) wantAlong = routeLen;
+
+ /* The point has to be in front of the unit, and being in front along the route is not the same
+ thing. A unit shoved sideways out of a queue, or one carried past its own lookahead through a
+ corner, gets handed a point behind its own tracks, and the locomotor turns round and drives at
+ it: that is the rocking back and forth, and at a corner, where the route is already round the
+ bend, it is the rotating on the spot. Walk forward until the point is ahead. */
+ for (;;)
+ {
+ Real outLat = m_crowdLat;
+ const Real leftToRun = routeLen - wantAlong;
+ if (leftToRun < CROWD_TAPER_DIST)
+ outLat *= leftToRun / CROWD_TAPER_DIST; // the band closes on the destination, so the group arrives together
+
+ m_corridor->pointAt( wantAlong, m_corridor->clampLatAt( wantAlong, outLat ), &goalPos );
+
+ const Real ahead = (goalPos.x - myPos->x) * here.tan.x + (goalPos.y - myPos->y) * here.tan.y;
+ if (ahead >= myR || wantAlong >= routeLen)
+ break;
+
+ wantAlong += PATHFIND_CELL_SIZE_F;
+ if (wantAlong > routeLen) wantAlong = routeLen;
+ }
+
+ /* ---- and the aim goes through a filter of its own ----
+ Every rule above moves the point a little, the sample the point is taken from hops forward a
+ cell at a time, and the band's own width wobbles: the direction handed to the locomotor is
+ never still, and a locomotor steered at a direction that is never still is a metronome. So
+ the direction is low-passed and small errors are ignored outright.
+
+ Only while cruising. In a jam, behind somebody, giving way, moving over, or when the route
+ genuinely turns hard, the filter opens right up - lag costs more than twitch the moment the
+ unit is actually manoeuvring, and a smoothed answer to "there is a tank in front of you" is
+ the wrong kind of calm. */
+ const Real aimDx = goalPos.x - myPos->x;
+ const Real aimDy = goalPos.y - myPos->y;
+ const Real aimDist = (Real)sqrt( aimDx * aimDx + aimDy * aimDy );
+ if (aimDist > 0.01f)
+ {
+ const Real wantAim = ATan2( aimDy, aimDx ); // the table, not the runtime: this decides a position
+ if (!m_crowdAimValid)
+ {
+ m_crowdAim = wantAim;
+ m_crowdAimValid = TRUE;
+ }
+
+ const Real err = normalizeAngle( wantAim - m_crowdAim );
+ const Bool urgent = pressing || touching || queued || giveWay || merged
+ || (blocker != NULL && blockerGap < myR)
+ || fabs( err ) > 1.0f;
+
+ /* One gain is the wrong gain for two chassis. The steering point sits a fixed distance in
+ front - two cells and a body, about thirty feet - which a heavy tank at 25 covers in forty
+ frames and a scout at 90 in ten. Pure pursuit goes unstable when the unit eats its own
+ lookahead faster than the wheel settles: the light thing overshoots, the error changes sign,
+ it oversteers back, and that is the head shaking players see on fast vehicles and never on
+ heavy ones. So the cruising gain is damped by how much of the aim distance the chassis
+ covers in half a second. It is a lag, not a different point to drive at: nothing aims
+ anywhere it was not already aiming, which is what the horizon experiment got wrong. */
+ Real gain = urgent ? CROWD_AIM_URGENT : CROWD_AIM_CRUISE;
+ if (!urgent)
+ {
+ const Real travel = speed * CROWD_LOOK_FRAMES;
+ if (travel > aimDist)
+ {
+ gain *= aimDist / travel;
+ if (gain < CROWD_AIM_SLOWEST) gain = CROWD_AIM_SLOWEST;
+ }
+ }
+ m_crowdAim = normalizeAngle( m_crowdAim + err * gain );
+
+ if (!urgent && fabs( normalizeAngle( m_crowdAim - self->getOrientation() ) ) < CROWD_AIM_DEAD)
+ m_crowdAim = self->getOrientation(); // two degrees is not worth a steering input
+
+ goalPos.x = myPos->x + Cos( m_crowdAim ) * aimDist;
+ goalPos.y = myPos->y + Sin( m_crowdAim ) * aimDist;
+ }
+
+ goalPos.z = TheTerrainLogic->getGroundHeight( goalPos.x, goalPos.y );
+
+ if (cap < speed)
+ speed = cap;
+
+ if (TheGlobalData->m_showLanes && (now % LOGICFRAMES_PER_SECOND) == 0)
+ {
+ const char *mode = pressing ? "press" : (giveWay ? "yield" : (merged ? "merge"
+ : (queued ? "brake" : (blocker != NULL ? "pass" : "free"))));
+ DEBUG_LOG(("SHOWLANES crowd: unit %d %s sample %d lat %.1f band %.1f/%.1f queued %d stuck %d rank %d speed %.2f\n",
+ self->getID(), mode, i, m_crowdLat, here.left, here.right, m_crowdQueued, m_crowdStuck, rank, speed));
+ }
+}
+
//-------------------------------------------------------------------------------------------------
/**
* This is used by the internal move to state to indicate that a move started.
@@ -2276,6 +3125,18 @@ UpdateSleepTime AIUpdateInterface::doLocomotor( void )
TheAI->pathfinder()->claimPathTiming(getObject(), getPath());
}
+ /* The lane across the route is taken the first frame the unit drives on a new route, not when
+ the route is built: a path can be handed over several frames ahead of the move actually
+ starting, and the group that ordered it may still be handing out lanes.
+
+ There is no drift back to the middle. The first version had one, on the theory that a lane
+ should be a response to traffic and not a permanent kink, and it was the whole reason a
+ group kept collapsing back into single file - it pulled every unit at 0.008 a frame towards
+ the same line. The taper over the last PF_LANE_TAPER_CELLS closes the band on arrival,
+ which is the only place the spread actually has to go away. */
+ if (!m_laneFractionValid && getPath() != NULL)
+ seedLaneFraction();
+
const Bool traceWasBlocked = m_isBlocked; // -tracemove: the flag is cleared on the next line
m_isBlocked = FALSE;
@@ -2372,7 +3233,14 @@ UpdateSleepTime AIUpdateInterface::doLocomotor( void )
}
}
- m_curLocomotor->locoUpdate_moveTowardsPosition(getObject(), goalPos,
+ /* -crowd hangs here, on the two numbers about to be handed to the locomotor. The
+ point on the route has already been worked out; the crowd model moves it sideways
+ across the width of the road and takes speed off for whatever is in the way.
+ Ground movement only - an aircraft has no road and no traffic. */
+ if (TheGlobalData->m_crowdModel && isDoingGroundMovement())
+ crowdSteer(goalPos, speed);
+
+ m_curLocomotor->locoUpdate_moveTowardsPosition(getObject(), goalPos,
onPathDistToGoal+getPathExtraDistance(), speed, &blocked);
m_doFinalPosition = FALSE;
@@ -5253,7 +6121,7 @@ void AIUpdateInterface::crc( Xfer *x )
void AIUpdateInterface::xfer( Xfer *xfer )
{
// version
- const XferVersion currentVersion = 6;
+ const XferVersion currentVersion = 9;
XferVersion version = currentVersion;
xfer->xferVersion( &version, currentVersion );
@@ -5484,6 +6352,38 @@ void AIUpdateInterface::xfer( Xfer *xfer )
xfer->xferBool(&m_hasExitProductionRallyPoint);
}
+ if (version >= 7)
+ {
+ // the lane across the route. An older save has none, and the ctor's 0.5 / not-valid means
+ // every loaded unit re-seeds itself the first frame it drives, which is the right answer.
+ xfer->xferReal(&m_laneFraction);
+ xfer->xferBool(&m_laneFractionValid);
+ xfer->xferUnsignedInt(&m_laneHoldFrame);
+ }
+
+ if (version >= 8)
+ {
+ // a lane handed down by the ordering group and not yet taken up. Only a save made in the
+ // few frames between the order and the path arriving carries one.
+ xfer->xferReal(&m_pendingLane);
+ xfer->xferBool(&m_hasPendingLane);
+ }
+
+ if (version >= 9)
+ {
+ /* -crowd's lane, which is a distance and not a share, plus how long the unit has been held
+ up - a save made in the middle of a jam that came back with everybody patient again would
+ restart the jam from the beginning. The band itself is not saved: it is derived from the
+ route and is rebuilt the first frame after the load. */
+ xfer->xferReal(&m_crowdLat);
+ xfer->xferBool(&m_crowdLatValid);
+ xfer->xferReal(&m_pendingCrowdLat);
+ xfer->xferBool(&m_hasPendingCrowdLat);
+ xfer->xferUnsignedInt(&m_crowdHoldFrame);
+ xfer->xferInt(&m_crowdQueued);
+ xfer->xferInt(&m_crowdSide);
+ }
+
} // end xfer
diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cpp
index d15f6cdac..e7682e58c 100644
--- a/GeneralsMD/Code/Tests/test_gameengine.cpp
+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp
@@ -86,6 +86,7 @@
#include "GameLogic/IncomingDamage.h"
#include "GameLogic/AIPlayer.h"
#include "GameLogic/AIPathfind.h"
+#include "GameLogic/CrowdModel.h"
#include "GameLogic/ScriptEngine.h"
#include "GameLogic/Scripts.h"
#include "GameLogic/SidesList.h"
@@ -8468,6 +8469,320 @@ TEST(the_whole_flow_charge_for_one_step_is_bounded)
const Int worst = Pathfinder_wallHugCost( base, 0, 5 ) +
Pathfinder_trafficCost( base, PF_TRAFFIC_MAX ) +
Pathfinder_crossingCost( base, 0xFFFF );
- CHECK( worst <= 6 * base );
+ CHECK( worst <= 8 * base ); // 7.6 of a step: 1.6 wall-hug, 4 traffic, 2 crossing
CHECK( worst >= 3 * base ); // and it is not so small that none of it does anything
}
+
+/* Lanes. The route is a band and each unit rides somewhere across it; these two functions are the
+ whole of that arithmetic, and every degenerate case below is one the map really produces - a
+ doorway with no width at all, a unit that has already been shoved outside its own band, a body
+ wider than the room measured for it. */
+
+TEST(half_is_the_route_itself_however_lopsided_the_room_beside_it_is)
+{
+ /* The two sides of the band are scaled separately and meet at the centre line. The first
+ version ran one scale from wall to wall, so half of a lopsided band was the middle of the
+ free ground and a unit holding no particular lane slid sideways whenever the terrain was
+ uneven - a mistake that grew with the probe and was worth 10% of the time spent blocked. */
+ CHECK_NEAR( Pathfinder_laneFraction( 0.0f, 20.0f, 20.0f ), 0.5f, 0.0001f );
+ CHECK_NEAR( Pathfinder_laneOffset( 0.5f, 20.0f, 20.0f ), 0.0f, 0.0001f );
+ CHECK_NEAR( Pathfinder_laneOffset( 0.5f, 30.0f, 10.0f ), 0.0f, 0.0001f );
+ // five feet left of the route, in a band with thirty feet of room on that side
+ CHECK_NEAR( Pathfinder_laneFraction( 5.0f, 30.0f, 10.0f ), 0.5833f, 0.0001f );
+ // the same five feet on the narrow side is a much bigger share of it
+ CHECK_NEAR( Pathfinder_laneFraction( -5.0f, 30.0f, 10.0f ), 0.25f, 0.0001f );
+}
+
+TEST(a_lane_is_never_the_wall_itself)
+{
+ // a unit standing well outside its own band still gets a lane inside it
+ CHECK_NEAR( Pathfinder_laneFraction( 500.0f, 20.0f, 20.0f ), 0.95f, 0.0001f );
+ CHECK_NEAR( Pathfinder_laneFraction( -500.0f, 20.0f, 20.0f ), 0.05f, 0.0001f );
+ // and the offset that lane means keeps it off both edges
+ CHECK( Pathfinder_laneOffset( 0.95f, 20.0f, 20.0f ) < 20.0f );
+ CHECK( Pathfinder_laneOffset( 0.05f, 20.0f, 20.0f ) > -20.0f );
+}
+
+TEST(a_band_with_no_width_puts_everybody_on_the_centre_line)
+{
+ // a doorway, or a body as wide as the room beside it: laneExtent returns zero on both sides
+ CHECK_NEAR( Pathfinder_laneFraction( 0.0f, 0.0f, 0.0f ), 0.5f, 0.0001f );
+ CHECK_NEAR( Pathfinder_laneFraction( 40.0f, 0.0f, 0.0f ), 0.5f, 0.0001f );
+ CHECK_NEAR( Pathfinder_laneOffset( 0.5f, 0.0f, 0.0f ), 0.0f, 0.0001f );
+ CHECK_NEAR( Pathfinder_laneOffset( 0.95f, 0.0f, 0.0f ), 0.0f, 0.0001f );
+}
+
+TEST(a_lane_fraction_and_its_offset_are_the_same_measurement_backwards)
+{
+ // what seedLaneFraction reads off the map, computePointOnPath has to be able to steer back to.
+ // Only over the interior: the outer 5% at each edge is clamped away on purpose and does not
+ // survive the round trip, which is the point of clamping it.
+ const Real left = 25.0f, right = 15.0f;
+ for (Real lateral = -13.0f; lateral <= 22.0f; lateral += 1.0f)
+ {
+ Real u = Pathfinder_laneFraction( lateral, left, right );
+ CHECK_NEAR( Pathfinder_laneOffset( u, left, right ), lateral, 0.0001f );
+ }
+}
+
+TEST(only_the_side_with_room_on_it_widens_the_band)
+{
+ // a route running along a wall: no room right, plenty left. The lane has to end up left of
+ // centre, which is the asymmetry the clearance map cannot see and the reason it is not used here.
+ CHECK( Pathfinder_laneOffset( 0.9f, 40.0f, 0.0f ) > 0.0f );
+ CHECK_NEAR( Pathfinder_laneOffset( 0.0f, 40.0f, 0.0f ), 0.0f, 0.0001f ); // hard right is the wall, which is the centre line
+ // twenty feet into forty feet of room is halfway across that side of the band
+ CHECK_NEAR( Pathfinder_laneFraction( 20.0f, 40.0f, 0.0f ), 0.75f, 0.0001f );
+ // and a body pushed onto the wall side of a route with no room there stays on the route
+ CHECK_NEAR( Pathfinder_laneOffset( Pathfinder_laneFraction( -20.0f, 40.0f, 0.0f ), 40.0f, 0.0f ),
+ 0.0f, 0.0001f );
+}
+
+TEST(a_lane_handed_to_a_group_member_is_a_distance_not_a_share_of_the_group)
+{
+ // A group's lanes are spaced by the size of its bodies, so what gets handed down has to mean
+ // feet. The reference is the widest band the probe can find, and the same offset therefore
+ // means the same distance whether it came from a tight blob or a wide box.
+ const Real ref = Pathfinder_laneReference();
+ CHECK( ref > 100.0f ); // 16 cells of 10; a tank is about 24 wide, so this is several of them
+
+ CHECK_NEAR( Pathfinder_groupLane( 0.0f ), 0.5f, 0.0001f );
+ CHECK_NEAR( Pathfinder_groupLane( ref * 0.5f ), 0.75f, 0.0001f );
+ CHECK_NEAR( Pathfinder_groupLane( ref * -0.5f ), 0.25f, 0.0001f );
+
+ // the edges are the clamp, not the wall itself
+ CHECK( Pathfinder_groupLane( ref * 4.0f ) < 1.0f );
+ CHECK( Pathfinder_groupLane( ref * -4.0f ) > 0.0f );
+
+ // order is preserved: whoever was left of somebody stays left of them
+ CHECK( Pathfinder_groupLane( -30.0f ) < Pathfinder_groupLane( 10.0f ) );
+
+ /* Two tanks a body apart have to come out at least a body apart on a full-width band, or the
+ spacing the group did the arithmetic for is thrown away here. Taken back out through
+ laneOffset at the widest band the probe reports, which is what the group measured against. */
+ Real uLeft = Pathfinder_groupLane( 14.0f );
+ Real uRight = Pathfinder_groupLane( -14.0f );
+ Real apart = Pathfinder_laneOffset( uLeft, ref, ref ) - Pathfinder_laneOffset( uRight, ref, ref );
+ CHECK_NEAR( apart, 28.0f, 0.01f );
+
+ // and a narrow road squeezes all of it rather than dropping anybody: quarter band, quarter gap
+ Real narrow = Pathfinder_laneOffset( uLeft, ref * 0.25f, ref * 0.25f )
+ - Pathfinder_laneOffset( uRight, ref * 0.25f, ref * 0.25f );
+ CHECK_NEAR( narrow, 7.0f, 0.01f );
+}
+
+TEST(the_band_is_shut_before_the_goal_not_at_it)
+{
+ const Real cell = PATHFIND_CELL_SIZE_F;
+ const Real taper = cell * (Real)PF_LANE_TAPER_CELLS;
+ const Real close = cell * (Real)PF_LANE_CLOSE_CELLS;
+ CHECK( close < taper );
+
+ // out on the route, nothing is given up
+ CHECK_NEAR( Pathfinder_laneTaper( taper * 4.0f ), 1.0f, 0.0001f );
+ CHECK_NEAR( Pathfinder_laneTaper( taper ), 1.0f, 0.0001f );
+
+ /* The whole point of the close distance: at the goal, and for the last few cells before it,
+ the lane is gone completely. A ramp that only reached zero at the goal left a unit riding
+ the edge of a wide band still yards off its own route when it stopped, and a group ordered
+ onto one point arrived spread across it. */
+ CHECK_NEAR( Pathfinder_laneTaper( close ), 0.0f, 0.0001f );
+ CHECK_NEAR( Pathfinder_laneTaper( 0.0f ), 0.0f, 0.0001f );
+ CHECK_NEAR( Pathfinder_laneTaper( -5.0f ), 0.0f, 0.0001f );
+
+ // straight line between the two, and never a step backwards
+ CHECK_NEAR( Pathfinder_laneTaper( (taper + close) * 0.5f ), 0.5f, 0.0001f );
+ Real last = 0.0f;
+ for (Real r = 0.0f; r < taper * 1.5f; r += 2.0f)
+ {
+ Real f = Pathfinder_laneTaper( r );
+ CHECK( f >= last - 0.0001f );
+ CHECK( f >= 0.0f && f <= 1.0f );
+ last = f;
+ }
+}
+
+TEST(the_taper_is_long_enough_for_the_band_it_has_to_close)
+{
+ /* A unit riding the edge of the widest band the probe can find has to be able to get back to
+ the centre line before the lane is switched off, or it arrives beside its own goal. The
+ taper is that distance, so it has to be at least as long as the offset it is undoing -
+ anything shorter is a unit told to move sideways faster than it drives forwards. */
+ const Real taper = PATHFIND_CELL_SIZE_F * (Real)PF_LANE_TAPER_CELLS;
+ CHECK( taper >= Pathfinder_laneReference() * 0.5f );
+}
+
+TEST(crowd_corridor_measures_distance_along_the_route_not_samples)
+{
+ /* The sample's own `along` is quantised to the sample step, so a steering point taken from it
+ hops a whole cell forward every time the unit crosses a boundary. alongOf is the unquantised
+ answer: it has to grow smoothly as the unit advances, and it has to ignore sideways offset. */
+ Coord3D pts[ 5 ];
+ for (Int k = 0; k < 5; k++)
+ {
+ pts[ k ].x = (Real)k * 10.0f;
+ pts[ k ].y = 0.0f;
+ pts[ k ].z = 0.0f;
+ }
+
+ CrowdCorridor corr;
+ corr.buildForTest( pts, 5, 20.0f );
+ CHECK_EQ( corr.count(), 5 );
+ CHECK_NEAR( corr.length(), 40.0f, 0.001f );
+
+ Coord3D p;
+ p.y = 0.0f;
+ p.z = 0.0f;
+
+ Real last = -1.0f;
+ for (Real x = 0.0f; x <= 40.0f; x += 1.0f)
+ {
+ p.x = x;
+ const Real a = corr.alongOf( corr.nearest( p, 0 ), p );
+ CHECK_NEAR( a, x, 0.001f );
+ CHECK( a > last ); // no plateau, which is what a sample-quantised answer would give
+ last = a;
+ }
+
+ // standing off the line does not move a unit forwards or backwards along it
+ p.x = 15.0f;
+ p.y = 12.0f;
+ CHECK_NEAR( corr.alongOf( corr.nearest( p, 0 ), p ), 15.0f, 0.001f );
+}
+
+TEST(crowd_corridor_steering_point_slides_instead_of_hopping)
+{
+ /* The wobble on light chassis was this: point() lands on a sample, so the aim point jumped ten
+ feet at a time and on a bend the direction handed to the locomotor stepped with it. pointAt
+ has to be continuous - consecutive queries a foot apart give answers a foot apart - and it has
+ to agree with point() exactly where a sample sits. */
+ Coord3D pts[ 6 ];
+ pts[ 0 ].x = 0.0f; pts[ 0 ].y = 0.0f;
+ pts[ 1 ].x = 10.0f; pts[ 1 ].y = 0.0f;
+ pts[ 2 ].x = 20.0f; pts[ 2 ].y = 0.0f;
+ pts[ 3 ].x = 28.0f; pts[ 3 ].y = 6.0f;
+ pts[ 4 ].x = 34.0f; pts[ 4 ].y = 14.0f;
+ pts[ 5 ].x = 36.0f; pts[ 5 ].y = 24.0f;
+ for (Int k = 0; k < 6; k++)
+ pts[ k ].z = 0.0f;
+
+ CrowdCorridor corr;
+ corr.buildForTest( pts, 6, 15.0f );
+
+ // on a sample, the two agree
+ for (Int k = 0; k < corr.count(); k++)
+ {
+ Coord3D a, b;
+ corr.point( k, 4.0f, &a );
+ corr.pointAt( corr.at( k ).along, 4.0f, &b );
+ CHECK_NEAR( a.x, b.x, 0.001f );
+ CHECK_NEAR( a.y, b.y, 0.001f );
+ }
+
+ // and between them it slides: a tenth of a foot of route never moves the point a foot
+ Coord3D prev;
+ corr.pointAt( 0.0f, 4.0f, &prev );
+ for (Real s = 0.1f; s <= corr.length(); s += 0.1f)
+ {
+ Coord3D now;
+ corr.pointAt( s, 4.0f, &now );
+ const Real dx = now.x - prev.x;
+ const Real dy = now.y - prev.y;
+ CHECK( dx * dx + dy * dy < 1.0f );
+ prev = now;
+ }
+
+ // the width follows too, and a lane wider than the band is still cut to the band
+ CHECK_NEAR( corr.clampLatAt( 12.5f, 4.0f ), 4.0f, 0.001f );
+ CHECK_NEAR( corr.clampLatAt( 12.5f, 90.0f ), 15.0f, 0.001f );
+ CHECK_NEAR( corr.clampLatAt( 12.5f, -90.0f ), -15.0f, 0.001f );
+
+ // off the ends is clamped, not indexed out of the vector
+ Coord3D ends;
+ corr.pointAt( -50.0f, 0.0f, &ends );
+ CHECK_NEAR( ends.x, pts[ 0 ].x, 0.001f );
+ corr.pointAt( corr.length() + 50.0f, 0.0f, &ends );
+ CHECK_NEAR( ends.x, pts[ 5 ].x, 0.001f );
+}
+
+TEST(crowd_corridor_has_no_band_on_a_bridge_or_at_its_approaches)
+{
+ /* A bridge deck is not road with room either side of it, and the ground beside a bridge is a
+ riverbank. A lane held across either one drives the unit off the side, and a lane held on the
+ approach arrives beside the abutment instead of at the entrance - which is a unit that never
+ gets onto the bridge and a queue behind it that never gets anywhere. The band closes over the
+ deck and for four samples each side of it. */
+ Coord3D pts[ 20 ];
+ PathfindLayerEnum layers[ 20 ];
+ for (Int k = 0; k < 20; k++)
+ {
+ pts[ k ].x = (Real)k * 10.0f;
+ pts[ k ].y = 0.0f;
+ pts[ k ].z = 0.0f;
+ layers[ k ] = LAYER_GROUND;
+ }
+ layers[ 10 ] = (PathfindLayerEnum)2; // the deck: three samples of it, out over the water
+ layers[ 11 ] = (PathfindLayerEnum)2;
+ layers[ 12 ] = (PathfindLayerEnum)2;
+
+ CrowdCorridor corr;
+ corr.buildForTest( pts, 20, 15.0f, layers );
+ CHECK_EQ( corr.count(), 20 );
+
+ // open road, far from the bridge either side: the band is what it was built with
+ CHECK_NEAR( corr.at( 0 ).left, 15.0f, 0.001f );
+ CHECK_NEAR( corr.at( 5 ).right, 15.0f, 0.001f );
+ CHECK_NEAR( corr.at( 19 ).left, 15.0f, 0.001f );
+
+ corr.sealBridges();
+
+ // the deck itself, and the four samples each side of it
+ for (Int k = 6; k <= 16; k++)
+ {
+ CHECK_NEAR( corr.at( k ).left, 0.0f, 0.001f );
+ CHECK_NEAR( corr.at( k ).right, 0.0f, 0.001f );
+ CHECK_NEAR( corr.clampLat( k, 12.0f ), 0.0f, 0.001f );
+ CHECK_NEAR( corr.clampLatAt( corr.at( k ).along, -12.0f ), 0.0f, 0.001f );
+ }
+
+ // and the road on either side of that stretch keeps its band
+ CHECK_NEAR( corr.at( 5 ).left, 15.0f, 0.001f );
+ CHECK_NEAR( corr.at( 17 ).right, 15.0f, 0.001f );
+ CHECK_NEAR( corr.clampLat( 5, 12.0f ), 12.0f, 0.001f );
+
+ // a route with no bridge on it is untouched
+ CrowdCorridor plain;
+ plain.buildForTest( pts, 20, 15.0f );
+ plain.sealBridges();
+ for (Int k = 0; k < plain.count(); k++)
+ CHECK_NEAR( plain.at( k ).left, 15.0f, 0.001f );
+}
+
+TEST(crowd_brake_only_reads_closing_time)
+{
+ const Int frames = 8;
+ const Real full = 2.0f;
+
+ // nobody in front of us is gaining on us: no brake at any gap
+ CHECK_NEAR( Crowd_brakeSpeed( full, full, 1.0f, frames ), full, 0.0001f );
+ CHECK_NEAR( Crowd_brakeSpeed( full, full + 1.0f, 0.0f, frames ), full, 0.0001f );
+
+ // closing, but the gap is more than eight frames of closing: still no brake. This is the
+ // distance-braking bug the measurement caught - a unit ten units back was being slowed to a
+ // third of its speed for traffic it was never going to reach
+ CHECK_NEAR( Crowd_brakeSpeed( full, 1.0f, 20.0f, frames ), full, 0.0001f );
+
+ // inside that, the answer closes the gap over the eight frames rather than this one
+ CHECK_NEAR( Crowd_brakeSpeed( full, 1.0f, 4.0f, frames ), 1.5f, 0.0001f );
+
+ // touching a stopped unit is a stop, and nothing ever comes back negative
+ CHECK_NEAR( Crowd_brakeSpeed( full, 0.0f, 0.0f, frames ), 0.0f, 0.0001f );
+ CHECK_NEAR( Crowd_brakeSpeed( full, 0.0f, -3.0f, frames ), 0.0f, 0.0001f );
+
+ // and the cap is never a speed-up
+ for (Real g = -2.0f; g < 30.0f; g += 0.5f)
+ CHECK( Crowd_brakeSpeed( full, 0.5f, g, frames ) <= full + 0.0001f );
+
+ // a zero window is the rule switched off, not a division by zero
+ CHECK_NEAR( Crowd_brakeSpeed( full, 0.0f, 0.0f, 0 ), full, 0.0001f );
+}