Zero Hour rebuilt from EA's source: x64, Direct3D 11, VS2022/CMake, ~60 original bugs fixed, an AI that builds a base. Bring your own game.
C++ cmakecnccommand-and-conquercppdirectx11game-enginegame-preservationgeneralsrtssage-enginex64zero-hour
feat(gameengine): price routes by clearance, traffic and crossing time
Olcay Seygane4ccbad1fedf
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d04a49495..11a91f059 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -459,6 +459,30 @@ found and fixed — EA's own, not port damage.**- A sound finishing does not take the game with it. Every sound carries a description of itself, and that description can be gone by the time the sound ends - it is dropped when the sound is renamed, cleared by hand when what it points at is about to be deleted, and absent on a sound that was queued to repeat after a delay. The 2003 code checked for that in two places and then read straight through it in fifteen others, one of which is where every finished sound goes. It crashed mid-match with a stack that is all audio and names nothing that caused it. A sound with no description is now simply not music and not speech, which is what all fifteen questions were asking; the channel it was using is still handed back, because losing one leaks a voice for the rest of the match and enough of them go quiet.- Something going wrong now writes a readable crash report.+## Units take corners wide, and drive round a jam instead of into it++- A route used to be priced by the ground under it and nothing else, so a tank was handed the+ shortest line whether or not it could drive it. The shortest line scrapes every corner, and a+ tank that clips a corner stops, reverses and tries again while everything behind it waits. Routes+ are now charged for how close they run to terrain, and the charge climbs sharply in the last+ couple of squares, so a wide body swings out where there is room and only squeezes where there is+ no alternative.+- Squares where units are actually standing still are expensive for about a second afterwards. A+ unit that asks for a new route while stuck in a line is no longer handed the same line back: the+ queue in front of it costs something now, and a way round it that is not much longer wins.+- Routes also carry a clock. Each unit on the move says where it expects to be and roughly when,+ half a second at a time, and a route is charged where it wants a square somebody else wants at the+ same moment. Two columns following the same road are in the same squares at different moments and+ pay nothing for it; two columns crossing pay, and one of them goes round. That distinction is the+ whole point - the same map without a clock in it makes a shared road look as bad as a crossing.+- 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.+- 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+ 30.6 milliseconds to 9.9.+## Long orders stopped hitching- The coarse pathfinder pass never worked, so every long move searched the whole map.@@ -538,7 +562,27 @@ found and fixed — EA's own, not port damage.**- Then the question changed from "how fast" to "how steady", and the stopwatch had to change with it: an average is exactly the number that hides a stutter. The game now keeps the shape of every frame it draws and reports the worst ones, with the name of what took the time. The building-foundation freeze above was found that way, in one run, having been in the game since 2003.- The self-play harness can set up teams now, which it never could: every computer opponent used to fight every other one. Eight players in a free-for-all spread the fighting over the whole map, and that is not the load anybody complains about - 4v4 puts every unit on one of two fronts, which is where they bunch up. That is now one switch, and it is how the numbers above were checked at the heavy end.- A second pass with the same tool named two more, and the log did the work each time rather than anyone guessing: the computer player's search for somewhere to build, and the angry mob's health count. A third is named and not fixed - a computer team sent across the map on its approach path spends 40 milliseconds finding the wide corridor for it, once or twice a match, and that is one search rather than a mistake repeated. It is the next one.-- Group movement was 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 asked a third time and this time answered yes, from a different direction. The+ version that was thrown out priced squares by how many other units planned to drive over them, and+ the harness could not see it work because a computer opponent never forms the queue a person makes+ by dragging a box round fifteen tanks - thirty-three of forty-eight maps came out bit-identical.+ What went back in is priced by terrain instead, which is on every map on every frame whether or+ not anyone is queuing, and the traffic and crossing costs ride on top of that rather than carrying+ the whole change on their own. Every route in every match changes, so there is something to+ measure: twenty four-player matches, same twenty maps, time spent standing behind another unit+ 31% lower; six 4v4 matches, 38% lower with half the properly-stuck frames.+- It cost search time and that had to be paid for. Adding a charge the distance estimate cannot see+ is the same mistake the pathfinder was rescued from two years ago: the search stops walking toward+ the goal and fans out instead. First measurement, twenty matches, 225,419 squares looked at per+ match against 57,596 before - four times the work. Raising the estimate to match what the charge+ adds brought it back to 90,058, and with it the units left properly stuck, from 43 a match to 8.+ What remains is 56% more searching for 31% less waiting, and on the heavy 4v4 load the worst frame+ of a match got better rather than worse, because the search work spreads over frames and a traffic+ jam does not.+- 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.---diff --git a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.hindex 6c999f454..dff8e383f 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h@@ -378,6 +378,7 @@ public:Int m_traceMoveID; ///< -tracemove [id]: log one movement line a frame for this object (0 = off, -1 = the first unit that gets blocked)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 costAsciiString 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 isdiff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.hindex 04971e3bf..ae8f59435 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h@@ -280,6 +280,14 @@ protected:UnsignedShort m_totalCost, m_costSoFar; ///< cost estimates for A* search+ /* Ground covered to reach this cell, in the same units as m_costSoFar but with none of the+ penalties in it. A penalty is money, not distance: a detour taken to dodge somebody must+ not also convince the search it arrives eight cells later than it really does. The flow+ model turns this number into an arrival frame, which is what the space-time claims below+ are looked up by. Only the main ground search maintains it; every other search leaves it+ at zero and charges no crossing cost. */+ UnsignedShort m_travelSoFar;+/// have to include cell's coordinates, since cells are often accessed via pointer onlyICoord2D m_pos;@@ -388,9 +396,14 @@ public:inline Bool getClosed(void) const {return m_info->m_closed;}inline UnsignedInt getCostSoFar(void) const {return m_info->m_costSoFar;}inline UnsignedInt getTotalCost(void) const {return m_info->m_totalCost;}+ inline UnsignedInt getTravelSoFar(void) const {return m_info->m_travelSoFar;}inline void setCostSoFar(UnsignedInt cost) { if( m_info ) m_info->m_costSoFar = cost;}inline void setTotalCost(UnsignedInt cost) { if( m_info ) m_info->m_totalCost = cost;}+ /* Saturates rather than wrapping. Sixteen bits is 6553 cells of route, which no map here can+ hold, but a search that wanders can still get there - and a wrapped distance turns into an+ arrival time in the wrong half-minute, which prices a crossing that is not there. */+ inline void setTravelSoFar(UnsignedInt travel) { if( m_info ) m_info->m_travelSoFar = (UnsignedShort)(travel > 0xFFFF ? 0xFFFF : travel);}void setParentCell(PathfindCell* parent);void clearParentCell(void);@@ -625,7 +638,103 @@ private:zoneStorageType *m_hierarchicalZones;};-/**+//----------------------------------------------------------------------------------------------------------+// The flow model.+//+// Retail's A* prices terrain and nothing else, so every unit ordered across the same ground is+// handed the same line: they stack on it, the ones behind stop, and the search that eventually+// runs for a stuck unit hands it the line it is stuck on. Three maps are laid over the terrain+// cost to fix that, ported from the browser sandbox (astar-units.html) that they were tuned in:+//+// Clearance - chamfer distance from each cell to the nearest cell the unit could not stand in.+// A route is charged for hugging terrain, quadratically, over a band about two and a half+// cells wide. That is what makes a tank take a corner wide instead of scraping it, and it+// is the one map that costs nothing to keep: the terrain it measures only changes when a+// building goes up.+//+// Traffic - where units are actually stopped, decayed over about a second. A queue therefore+// looks expensive to the next search, and a unit repathing out of one is given a way round+// it rather than back into it.+//+// Claims - where each live path expects its owner to be, and *when*, in half-second buckets.+// Two units following one road are in the same cells at different moments and pay nothing;+// two columns crossing want the same cell at the same moment and are charged for it. Time+// is the whole point: without it a shared road and a crossing look identical, which is what+// the fork's earlier congestion map got wrong.+//+// Every one of them is integer arithmetic over deterministic inputs, so two machines expand the+// same cells in the same order. All three are off under -noflowpath.+//----------------------------------------------------------------------------------------------------------++enum+{+ // clearance is a chamfer distance: 5 per orthogonal step, 7 per diagonal, so one cell is 5.+ PF_CLEARANCE_ORTHO = 5,+ PF_CLEARANCE_DIAG = 7,+ /* Twelve cells of open ground. Nothing above that is ever read: the widest body the game+ has needs about three cells and the band charged for is two and a half more, so a higher+ ceiling would only cost the rebuild time to compute. */+ PF_CLEARANCE_MAX = 60,+ PF_CLEARANCE_SOFT = 13, ///< the band charged for, ~2.5 cells+ PF_WALLHUG_NUM = 8, ///< peak wall-hug penalty is NUM/DEN of a step+ PF_WALLHUG_DEN = 5,++ PF_TRAFFIC_MAX = 255,+ PF_TRAFFIC_DEPOSIT = 24, ///< one blocked unit-frame, at the centre cell+ PF_TRAFFIC_DECAY_NUM = 54, ///< x54/64 every decay tick ~ the sandbox's x0.85 per 0.1s+ 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_DEN = 1,+ PF_TRAFFIC_CELLS = 4096, ///< live traffic cells tracked; past this, deposits are dropped++ PF_CLAIM_BUCKET_FRAMES = 15, ///< half a second+ PF_CLAIM_BUCKETS = 24, ///< twelve seconds of horizon+ PF_CLAIM_REFRESH_FRAMES = 30, ///< a unit re-stamps its plan once a second+ PF_CLAIM_TABLE_SIZE = 32768, ///< power of two: the hash is masked, not divided+ PF_CLAIM_PROBES = 8, ///< linear probe depth; past it a claim is simply dropped+ PF_CLAIM_UNITS_MAX = 4, ///< claims beyond this on one cell-moment cost nothing more+ PF_CLAIM_SAMPLES_MAX = 64, ///< cells of its own plan one unit may stamp per refresh+ PF_CLEARANCE_REBUILD_FRAMES = 30, ///< how often a dirty clearance field is actually rebuilt+ PF_CROSSING_NUM = 1, ///< peak crossing penalty is NUM/DEN of a step+ PF_CROSSING_DEN = 2,++ /* What the A* estimate is scaled by while the flow charge is on, against retail's 3/2. The+ 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+};++/** How much extra a step into a cell with this clearance costs a body needing `needClearance`.+ Zero out in the open, rising quadratically as the body's own margin is eaten into. */+extern Int Pathfinder_wallHugCost( Int baseCost, Int clearance, Int needClearance );++/// How much extra a step into a cell holding this much live traffic costs.+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 );++/// The A* estimate's scale factor over plain octile distance, set per search by beginFlowSearch.+extern Int thePathHeuristicNum;+extern Int thePathHeuristicDen;++/**+ * One claim on one cell at one moment: which cell, which absolute half-second bucket, and how+ * much of a unit is expected to be there. Weight is in halves, because a claim spills into the+ * buckets either side of the one it lands in at half strength - a unit's arrival time is an+ * estimate, and an estimate that is only ever right to the bucket prices nothing.+ */+struct PathClaim+{+ Int m_cell; ///< cell index, -1 when the slot has never been used+ UnsignedInt m_bucket; ///< absolute bucket (logic frame / PF_CLAIM_BUCKET_FRAMES)+ UnsignedShort m_weight; ///< in halves+};++/*** The pathfinding services interface provides access to the 3 expensive path find calls:* findPath, findClosestPath, and findAttackPath.* It is only available to units when their ai interface doPathfind method is called.@@ -764,8 +873,32 @@ public:Bool worldToCell( const Coord3D *pos, ICoord2D *cell ); ///< Given a world position, return grid cell coordinateconst ICoord2D *getExtent(void) const {return &m_extent.hi;}-- void setIgnoreObstacleID( ObjectID objID ); ///< if non-zero, the pathfinder will ignore the given obstacle++ // ---- the flow model; see the block comment above PathfindServicesInterface ----++ /// Chamfer distance from this cell to the nearest cell nothing can stand in. 5 units per cell.+ Int getClearance( Int x, Int y ) const;+ /// Rebuild the whole clearance field. Two linear scans over the map, no queue.+ void buildClearance( void );+ /* A structure went up or came down, so the field is stale. It is not rebuilt on the spot:+ during base building that would be several rebuilds a second for a field nothing reads+ until the next search, so the flag is collected and cashed in once, from the pathfind+ queue, at most every PF_CLEARANCE_REBUILD_FRAMES. */+ void markClearanceDirty( void ) { m_clearanceDirty = true; }+ void updateClearanceIfDirty( void );++ /// One blocked unit-frame, stamped where it happened and spread over the body's footprint.+ void noteTraffic( const Coord3D *pos, Int radiusInCells );+ void decayTraffic( void ); ///< age the whole live set; call once per logic frame+ Int getTraffic( Int x, Int y ) const;++ /// Stamp where this unit expects to be over the next few seconds, from where it actually is.+ void claimPathTiming( const Object *obj, class Path *path );+ /// Weight (in halves) claimed on this cell for the bucket holding `frame`.+ Int getClaims( Int x, Int y, UnsignedInt frame ) const;+ void resetClaims( void ); ///< the ground under every claim is gone++ void setIgnoreObstacleID( ObjectID objID ); ///< if non-zero, the pathfinder will ignore the given obstaclevoid setIgnoreUnderConstruction( Bool ignore ); ///< if true, half-built structures are not obstacles to this searchBool builderMayCross( const PathfindCell *cell ) const; ///< is this obstacle cell a structure the builder now searching may walk over?Bool builderMayCrossPinch( Int cellX, Int cellY, PathfindLayerEnum layer ); ///< is this cell pinched only by a site that builder may walk over?@@ -932,6 +1065,59 @@ private:/// This uses WAY too much memory. Should at least be array of pointers to cells w/ many fewer cellsPathfindCell *m_blockOfMapCells; ///< Pathfinding map - contains iconic representation of the mapPathfindCell **m_map; ///< Pathfinding map indexes - contains matrix indexing into the map.++ //+ // The three flow maps. All of them are (hi.x+1)*(hi.y+1) and indexed [x*(hi.y+1)+y], the same+ // shape as m_map, so a cell index is a cell index everywhere below.+ //+ UnsignedByte *m_clearance; ///< chamfer distance to the nearest impassable cell+ Bool m_clearanceDirty; ///< a structure changed; rebuild when the throttle allows+ UnsignedInt m_clearanceFrame; ///< logic frame the last rebuild ran on+ UnsignedByte *m_traffic; ///< where units are stopped, decayed++ /* The traffic map is nearly all zeroes nearly all of the time, and decaying it by walking the+ whole map every third frame costs more than the map buys. Only the cells that actually+ hold something are visited, so an unjammed match pays nothing at all. */+ Int *m_trafficCells; ///< PF_TRAFFIC_CELLS cell indices, the non-zero set+ Int m_numTrafficCells;+ UnsignedInt m_trafficDecayFrame; ///< logic frame the last decay ran on++ /* A dense cell-by-bucket array would be twenty-four whole-map allocations to hold a few+ thousand live claims, so they live in one open-addressed table hashed on (cell, bucket).+ An entry whose bucket is already in the past is dead and its slot is reused; nothing ever+ has to be released, which is what lets a unit simply re-stamp its plan once a second from+ where it really is instead of maintaining a claim list per path. */+ PathClaim *m_claims;++ /* The last bucket any claim was written for, per cell. Without it every neighbour of every+ expansion pays an eight-slot hash probe to be told the cell is empty, which it nearly+ always is; with it that is one array read and a compare, and the hash is only walked on+ ground somebody has actually spoken for. */+ UnsignedShort *m_claimTouch;++ void addClaim( Int cell, UnsignedInt bucket, Int weight );+ void stampClaimAt( const Coord3D *pos, UnsignedInt frame, Int dilation );+ void allocateFlowMaps( void );+ void freeFlowMaps( void );+ Int flowSpeedOf( const Object *obj );++public:+ /* Arm (or disarm) the flow charge for the search about to run. Every top-level search calls+ it: the two that units actually move on pass their object, the hierarchical, attack, safe+ and group-corridor searches pass NULL, because those answer "can this be reached at all"+ and pricing traffic into that answer only makes them fail. */+ void beginFlowSearch( const Object *obj );+ /// The whole flow charge for one step into (cellX, cellY), given the ground covered to get there.+ Int flowStepCost( Int baseCost, Int cellX, Int cellY, Int radius, UnsignedInt travelSoFar );+ Bool flowCostsOn( void ) const { return m_flowCosts; }++private:++ Bool m_flowCosts; ///< is the search now running allowed to price the flow maps?+ Int m_flowSpeed; ///< cost units of travel the searching unit covers per logic frame, x256+ UnsignedInt m_flowNow; ///< logic frame the search started on, so an ETA is absolute+ UnsignedInt m_flowNowBucket; ///< and the claim bucket it falls in, so the screen costs no division+IRegion2D m_extent; ///< Grid extent limitsIRegion2D m_logicalExtent; ///< Logical grid extent limits@@ -1077,6 +1263,23 @@ inline Bool Pathfinder::worldToCell( const Coord3D *pos, ICoord2D *cell )return overflow;}+/* Both of these are read once per neighbour per expansion - a few million times in a busy frame -+ so they are a bounds check and an array index and nothing else. Off the map reads as "no room+ at all" for clearance and "empty" for traffic, which is what the search wants at the edge. */+inline Int Pathfinder::getClearance( Int x, Int y ) const+{+ if (m_clearance == NULL) return PF_CLEARANCE_MAX;+ if (x < m_extent.lo.x || y < m_extent.lo.y || x > m_extent.hi.x || y > m_extent.hi.y) return 0;+ return m_clearance[x*(m_extent.hi.y+1) + y];+}++inline Int Pathfinder::getTraffic( Int x, Int y ) const+{+ if (m_traffic == NULL) return 0;+ if (x < m_extent.lo.x || y < m_extent.lo.y || x > m_extent.hi.x || y > m_extent.hi.y) return 0;+ return m_traffic[x*(m_extent.hi.y+1) + y];+}+/*** Return true if the given object ID is registered as an obstacle in this cell*/diff --git a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cppindex d7371a2df..1c4bd8825 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp@@ -1383,6 +1383,21 @@ Int parseAISlice(char *args[], int num)return 1;}+/* -noflowpath takes the flow model back out and prices terrain only, the way retail does.++ It exists to be measured against. A change to how a route is costed is argued with a batch of+ matches, and a batch is only an argument if both halves of it are the same binary: two builds+ differ in the compiler's mood as well as in the change. So the clearance charge, the traffic+ charge and the crossing charge all hang off this one switch, and ai-batch.ps1 runs the same+ exe twice. The maps are still built and still maintained under it - they cost almost nothing+ to keep and turning them off as well would measure two changes at once. */+Int parseNoFlowPath(char *args[], int num)+{+ if (TheWritableGlobalData)+ TheWritableGlobalData->m_noFlowPath = TRUE;+ 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@@ -1671,6 +1686,7 @@ static CommandLineParam params[] ={ "-slowframe", parseSlowFrame },{ "-teams", parseTeams },{ "-aislice", parseAISlice },+ { "-noflowpath", parseNoFlowPath },{ "-replay", parseReplay },{ "-netgame", parseNetGame },{ "-netslot", parseNetSlot },diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cppindex a972d2884..d7d8ef57b 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp@@ -683,6 +683,7 @@ GlobalData::GlobalData()m_traceMoveID = 0; // no movement tracem_slowFrameMS = 20.0f; // a frame worth a line in the log; -slowframe lowers it for a huntm_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 againstm_netGameHosts.clear(); // no network game from the command linem_netGameLocalSlot = 0;m_horizontalScrollSpeedFactor = 1.0;diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cppindex 2e6bbfe97..32246f0d0 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp@@ -376,6 +376,11 @@ void AI::update( void )Int64 start, afterPathfind, end;QueryPerformanceCounter( (LARGE_INTEGER *)&start );+ // Age the flow maps before anything reads them: the traffic left by last frame's jams decays,+ // and a clearance field made stale by a building going up is rebuilt at most once a second.+ m_pathfinder->decayTraffic();+ m_pathfinder->updateClearanceIfDirty();+// Do pathfinding.m_pathfinder->processPathfindQueue();diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cppindex e51f00b4c..26e92e42b 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp@@ -551,6 +551,12 @@ Bool AIGroup::friend_computeGroundPath( const Coord3D *pos, CommandSourceType cmInt numVehicles = 0;Object *centerVehicle = NULL;Real distSqrCenterVeh = distSqr*10;+ /* The trunk is planned from the member that is ALREADY closest to the destination, not from+ the one nearest the middle of the group. Starting it in the middle makes every unit that+ is ahead of the middle drive backwards to join the route, straight across the main body,+ and jam the very column it is trying to join. */+ Object *leadVehicle = NULL;+ Real distSqrLeadVeh = 0.0f;for( i = m_memberList.begin(); i != m_memberList.end(); ++i ){Object *obj = (*i);@@ -583,6 +589,12 @@ Bool AIGroup::friend_computeGroundPath( const Coord3D *pos, CommandSourceType cmdistSqr = dx*dx+dy*dy;}+ // find the object closest to where the group has been told to go.+ if (leadVehicle==NULL || dx*dx+dy*dy<distSqrLeadVeh) {+ leadVehicle = (*i);+ distSqrLeadVeh = dx*dx+dy*dy;+ }+// find object closest to the center.dx = unitPos.x-center.x;dy = unitPos.y-center.y;@@ -637,7 +649,8 @@ Bool AIGroup::friend_computeGroundPath( const Coord3D *pos, CommandSourceType cm}if (!closeEnough) return false;- m_groundPath = TheAI->pathfinder()->findGroundPath(¢er, pos, PATH_DIAMETER_IN_CELLS, false);+ Coord3D trunkStart = (leadVehicle != NULL) ? *leadVehicle->getPosition() : center;+ m_groundPath = TheAI->pathfinder()->findGroundPath(&trunkStart, pos, PATH_DIAMETER_IN_CELLS, false);return m_groundPath!=NULL;}diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cppindex 9e8612dba..ba8ef5ea4 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp@@ -1344,8 +1344,9 @@ PathfindCellInfo *PathfindCellInfo::getACellInfo(PathfindCell *cell,const ICoordinfo->m_nextOpen = NULL;info->m_prevOpen = NULL;info->m_pathParent = NULL;- info->m_costSoFar = 0;+ info->m_costSoFar = 0;info->m_totalCost = 0;+ info->m_travelSoFar = 0;info->m_open = 0;info->m_closed = 0;info->m_openBucket = 0;@@ -1425,6 +1426,7 @@ Bool PathfindCell::startPathfind( PathfindCell *goalCell )m_info->m_pathParent = NULL;m_info->m_costSoFar = 0; // start node, no cost to get herem_info->m_totalCost = 0;+ m_info->m_travelSoFar = 0; // and no ground covered, which is a different numberif (goalCell) {m_info->m_totalCost = costToGoal( goalCell );}@@ -2031,6 +2033,12 @@ PathfindCell *PathfindCell::removeFromClosedList( PathfindCell *list )const Int COST_ORTHOGONAL = 10;const Int COST_DIAGONAL = 14;++/* How far the A* estimate is scaled up over plain octile distance. See costToGoal below for why+ it is scaled at all and Pathfinder::beginFlowSearch for who sets it. Retail's own searches run+ at 3/2; it is only raised while the flow charge is on. */+Int thePathHeuristicNum = 3;+Int thePathHeuristicDen = 2;const Real COST_TO_DISTANCE_FACTOR = 1.0f/10.0f;const Real COST_TO_DISTANCE_FACTOR_SQR = COST_TO_DISTANCE_FACTOR*COST_TO_DISTANCE_FACTOR;@@ -2068,8 +2076,15 @@ UnsignedInt PathfindCell::costToGoal( PathfindCell *goal )route is a few cells longer, the search is several times cheaper, and the frame does notstall. It stays integer arithmetic and a fixed ratio, so every machine and every replayexpands the same cells in the same order. */- enum { HEURISTIC_WEIGHT_NUM = 3, HEURISTIC_WEIGHT_DEN = 2 };- cost = (cost * HEURISTIC_WEIGHT_NUM) / HEURISTIC_WEIGHT_DEN;+ /* The weight is not a constant any more, because the gap it is closing is not. With the flow+ model on, a step also pays for hugging terrain, for standing traffic and for wanting a cell+ somebody else wants at the same moment, and the estimate can see none of the three - so the+ same estimate that steers a retail search stops steering a flow one. Measured, on twenty+ four-player matches: cell expansions 57,596 a match at 3/2 against 225,419 with the flow+ charge on and the weight left alone, which is the search giving up on the goal and walking+ the corridor. Pathfinder::beginFlowSearch sets the pair, and it is the same pair on every+ machine for the whole of one search. */+ cost = (cost * thePathHeuristicNum) / thePathHeuristicDen;return cost;}@@ -4221,7 +4236,11 @@ void PathfindLayer::classifyWallMapCell( Int i, Int j , PathfindCell *cell, Obje//----------------------- Pathfinder ----------------------------------------Pathfinder::Pathfinder( void ) :m_map(NULL)+Pathfinder::Pathfinder( void ) :m_map(NULL),+ m_clearance(NULL), m_clearanceDirty(true), m_clearanceFrame(0),+ m_traffic(NULL), m_trafficCells(NULL), m_numTrafficCells(0), m_trafficDecayFrame(0),+ m_claims(NULL), m_claimTouch(NULL),+ m_flowCosts(false), m_flowSpeed(0), m_flowNow(0), m_flowNowBucket(0){debugPath = NULL;PathfindCellInfo::allocateCellInfos();@@ -4231,6 +4250,446 @@ Pathfinder::Pathfinder( void ) :m_map(NULL)Pathfinder::~Pathfinder( void ){PathfindCellInfo::releaseCellInfos();+ freeFlowMaps();+}++//----------------------------------------------------------------------------------------------------------+// The flow model+//+// See the block comment in AIPathfind.h for what the three maps are and why. Everything below is+// integer arithmetic over inputs both machines in a network game already agree on - the classified+// map, which unit was blocked on which frame, and the paths the pathfinder itself handed out - so+// it costs the same cells in the same order everywhere.+//----------------------------------------------------------------------------------------------------------++/* The wall-hug charge. `slack` is how much room the body has past what it needs; at zero the cell+ is exactly as tight as the body and the step costs PF_WALLHUG_NUM/DEN extra, and the charge+ falls away as the square of the remaining band so open ground is free and merely-narrow ground+ is nearly free. A linear falloff was the first version and it taxed half the map. */+Int Pathfinder_wallHugCost( Int baseCost, Int clearance, Int needClearance )+{+ Int slack = clearance - needClearance;+ if (slack >= PF_CLEARANCE_SOFT) return 0;+ if (slack < 0) slack = 0;+ Int nearness = ((PF_CLEARANCE_SOFT - slack) * 256) / PF_CLEARANCE_SOFT; // 256 at the wall+ Int squared = (nearness * nearness) >> 8; // still in 256ths+ return (baseCost * PF_WALLHUG_NUM * squared) / (PF_WALLHUG_DEN * 256);+}++/* The traffic charge, capped. An uncapped one is what makes a search balloon: the heuristic knows+ nothing about it, so every cost it cannot see costs cells expanded, and a queue that prices at+ ten times a step sends the search round the whole map looking for the road that is not there. */+Int Pathfinder_trafficCost( Int baseCost, Int traffic )+{+ if (traffic <= 0) return 0;+ if (traffic > PF_TRAFFIC_FULL) traffic = PF_TRAFFIC_FULL;+ return (baseCost * PF_TRAFFIC_NUM * traffic) / (PF_TRAFFIC_DEN * PF_TRAFFIC_FULL);+}++/* The crossing charge. Weight arrives in halves because a claim spills either side of its own+ bucket at half strength; four whole units wanting one cell at one moment is as bad as it gets. */+Int Pathfinder_crossingCost( Int baseCost, Int claimHalves )+{+ Int units = claimHalves / 2;+ if (units <= 0) return 0;+ if (units > PF_CLAIM_UNITS_MAX) units = PF_CLAIM_UNITS_MAX;+ return (baseCost * PF_CROSSING_NUM * units) / PF_CROSSING_DEN;+}++/// Is this cell one no ground unit can stand in? Rubble counts as ground: crushers drive over it.+static Bool clearanceBlocks( const PathfindCell *cell )+{+ if (cell == NULL) return true;+ PathfindCell::CellType t = cell->getType();+ return (t != PathfindCell::CELL_CLEAR && t != PathfindCell::CELL_RUBBLE);+}++void Pathfinder::allocateFlowMaps( void )+{+ freeFlowMaps();+ Int cells = (m_extent.hi.x+1) * (m_extent.hi.y+1);+ if (cells <= 0) return;+ m_clearance = MSGNEW("PathfindFlowMaps") UnsignedByte[cells];+ m_traffic = MSGNEW("PathfindFlowMaps") UnsignedByte[cells];+ m_claimTouch = MSGNEW("PathfindFlowMaps") UnsignedShort[cells];+ m_trafficCells = MSGNEW("PathfindFlowMaps") Int[PF_TRAFFIC_CELLS];+ m_claims = MSGNEW("PathfindFlowMaps") PathClaim[PF_CLAIM_TABLE_SIZE];+ memset(m_clearance, 0, cells*sizeof(UnsignedByte));+ memset(m_traffic, 0, cells*sizeof(UnsignedByte));+ memset(m_claimTouch, 0, cells*sizeof(UnsignedShort));+ m_numTrafficCells = 0;+ m_trafficDecayFrame = 0;+ m_clearanceFrame = 0;+ m_clearanceDirty = true;+ resetClaims();+}++void Pathfinder::freeFlowMaps( void )+{+ if (m_clearance) { delete [] m_clearance; m_clearance = NULL; }+ if (m_traffic) { delete [] m_traffic; m_traffic = NULL; }+ if (m_claimTouch) { delete [] m_claimTouch; m_claimTouch = NULL; }+ if (m_trafficCells) { delete [] m_trafficCells; m_trafficCells = NULL; }+ if (m_claims) { delete [] m_claims; m_claims = NULL; }+ m_numTrafficCells = 0;+}++/**+ * Rebuild the clearance field.+ *+ * A chamfer distance transform, which is two linear passes over the map and no queue at all: the+ * forward pass carries the distance down and right, the backward pass carries it up and left, and+ * 5/7 is the integer stand-in for 1 and sqrt(2) that keeps the whole thing in bytes. A breadth+ * first search would give the same answer for several times the work.+ */+void Pathfinder::buildClearance( void )+{+ if (m_clearance == NULL || m_map == NULL) return;+ const Int h = m_extent.hi.y + 1;+ const Int w = m_extent.hi.x + 1;+ Int x, y;++ // seed: an impassable cell has no room at all, everything else starts at the ceiling+ for (x = 0; x < w; x++) {+ UnsignedByte *col = &m_clearance[x*h];+ for (y = 0; y < h; y++) {+ col[y] = clearanceBlocks(&m_map[x][y]) ? 0 : (UnsignedByte)PF_CLEARANCE_MAX;+ }+ }++ // the map edge is a wall as far as a body is concerned+ for (x = 0; x < w; x++) { m_clearance[x*h] = 0; m_clearance[x*h + h-1] = 0; }+ for (y = 0; y < h; y++) { m_clearance[y] = 0; m_clearance[(w-1)*h + y] = 0; }++ #define CLEAR_RELAX(dst, src, add) \+ do { Int cand = (Int)(src) + (add); if (cand < (Int)(dst)) (dst) = (UnsignedByte)cand; } while(0)++ for (x = 1; x < w-1; x++) {+ UnsignedByte *col = &m_clearance[x*h];+ const UnsignedByte *west = &m_clearance[(x-1)*h];+ for (y = 1; y < h-1; y++) {+ if (col[y] == 0) continue;+ CLEAR_RELAX(col[y], col[y-1], PF_CLEARANCE_ORTHO);+ CLEAR_RELAX(col[y], west[y], PF_CLEARANCE_ORTHO);+ CLEAR_RELAX(col[y], west[y-1], PF_CLEARANCE_DIAG);+ CLEAR_RELAX(col[y], west[y+1], PF_CLEARANCE_DIAG);+ }+ }+ for (x = w-2; x >= 1; x--) {+ UnsignedByte *col = &m_clearance[x*h];+ const UnsignedByte *east = &m_clearance[(x+1)*h];+ for (y = h-2; y >= 1; y--) {+ if (col[y] == 0) continue;+ CLEAR_RELAX(col[y], col[y+1], PF_CLEARANCE_ORTHO);+ CLEAR_RELAX(col[y], east[y], PF_CLEARANCE_ORTHO);+ CLEAR_RELAX(col[y], east[y+1], PF_CLEARANCE_DIAG);+ CLEAR_RELAX(col[y], east[y-1], PF_CLEARANCE_DIAG);+ }+ }+ #undef CLEAR_RELAX++ m_clearanceDirty = false;+ m_clearanceFrame = TheGameLogic ? TheGameLogic->getFrame() : 0;+}++void Pathfinder::updateClearanceIfDirty( void )+{+ if (!m_clearanceDirty || m_clearance == NULL) return;+ UnsignedInt now = TheGameLogic->getFrame();+ if (now - m_clearanceFrame < PF_CLEARANCE_REBUILD_FRAMES) return;+ buildClearance();+}++//----------------------------------------------------------------------------------------------------------++void Pathfinder::noteTraffic( const Coord3D *pos, Int radiusInCells )+{+ if (m_traffic == NULL || pos == NULL) return;+ ICoord2D c;+ worldToCell(pos, &c); // clamps to the map+ Int r = radiusInCells;+ if (r < 0) r = 0;+ if (r > 2) r = 2;+ const Int h = m_extent.hi.y + 1;+ for (Int dx = -r; dx <= r; dx++) {+ Int x = c.x + dx;+ if (x < m_extent.lo.x || x > m_extent.hi.x) continue;+ for (Int dy = -r; dy <= r; dy++) {+ Int y = c.y + dy;+ if (y < m_extent.lo.y || y > m_extent.hi.y) continue;+ Int i = x*h + y;+ if (m_traffic[i] == 0) {+ // full: the map already knows about four thousand jammed cells, one more says nothing+ if (m_numTrafficCells >= PF_TRAFFIC_CELLS) continue;+ m_trafficCells[m_numTrafficCells++] = i;+ }+ Int v = (Int)m_traffic[i] + PF_TRAFFIC_DEPOSIT;+ m_traffic[i] = (UnsignedByte)(v > PF_TRAFFIC_MAX ? PF_TRAFFIC_MAX : v);+ }+ }+}++void Pathfinder::decayTraffic( void )+{+ if (m_traffic == NULL || m_numTrafficCells == 0) return;+ UnsignedInt now = TheGameLogic->getFrame();+ if (now - m_trafficDecayFrame < PF_TRAFFIC_DECAY_FRAMES) return;+ m_trafficDecayFrame = now;+ Int keep = 0;+ for (Int k = 0; k < m_numTrafficCells; k++) {+ Int i = m_trafficCells[k];+ Int v = ((Int)m_traffic[i] * PF_TRAFFIC_DECAY_NUM) / PF_TRAFFIC_DECAY_DEN;+ m_traffic[i] = (UnsignedByte)v;+ if (v > 0) m_trafficCells[keep++] = i; // order preserved: the list stays deterministic+ }+ m_numTrafficCells = keep;+}++//----------------------------------------------------------------------------------------------------------++/// Knuth multiplicative on the cell, mixed with the bucket, masked to the table.+static inline Int claimSlotOf( Int cell, UnsignedInt bucket )+{+ UnsignedInt hash = (UnsignedInt)cell * 2654435761u + bucket * 40503u;+ return (Int)((hash >> 11) & (PF_CLAIM_TABLE_SIZE - 1));+}++void Pathfinder::resetClaims( void )+{+ if (m_claims == NULL) return;+ for (Int i = 0; i < PF_CLAIM_TABLE_SIZE; i++) {+ m_claims[i].m_cell = -1;+ m_claims[i].m_bucket = 0;+ m_claims[i].m_weight = 0;+ }+ if (m_claimTouch) {+ memset(m_claimTouch, 0, (m_extent.hi.x+1)*(m_extent.hi.y+1)*sizeof(UnsignedShort));+ }+}++/* Two passes over the probe window on purpose. Reusing the first dead slot as soon as one turns+ up would let the same (cell, bucket) exist twice - the live copy further along the window would+ never be found again - and the weight the search reads would then depend on which of the two+ the probe happened to reach first. */+void Pathfinder::addClaim( Int cell, UnsignedInt bucket, Int weight )+{+ if (m_claims == NULL || weight <= 0) return;+ const Int base = claimSlotOf(cell, bucket);+ const UnsignedInt nowBucket = TheGameLogic->getFrame() / PF_CLAIM_BUCKET_FRAMES;+ Int p;+ for (p = 0; p < PF_CLAIM_PROBES; p++) {+ PathClaim& e = m_claims[(base + p) & (PF_CLAIM_TABLE_SIZE - 1)];+ if (e.m_cell == cell && e.m_bucket == bucket && e.m_weight > 0) {+ Int w = (Int)e.m_weight + weight;+ e.m_weight = (UnsignedShort)(w > 0xFFFF ? 0xFFFF : w);+ return;+ }+ }+ for (p = 0; p < PF_CLAIM_PROBES; p++) {+ PathClaim& e = m_claims[(base + p) & (PF_CLAIM_TABLE_SIZE - 1)];+ if (e.m_cell >= 0 && e.m_weight > 0 && e.m_bucket >= nowBucket) continue; // still live+ e.m_cell = cell;+ e.m_bucket = bucket;+ e.m_weight = (UnsignedShort)weight;+ return;+ }+ // the window is full of live claims: this one is simply not recorded. Dropping it costs the+ // search a penalty it will not see, which is the harmless direction to fail in.+}++Int Pathfinder::getClaims( Int x, Int y, UnsignedInt frame ) const+{+ if (m_claims == NULL || m_claimTouch == NULL) return 0;+ if (x < m_extent.lo.x || y < m_extent.lo.y || x > m_extent.hi.x || y > m_extent.hi.y) return 0;+ const Int cell = x*(m_extent.hi.y+1) + y;+ const UnsignedInt bucket = frame / PF_CLAIM_BUCKET_FRAMES;+ // the cheap screen: nobody has ever claimed this cell for a moment this late+ if ((UnsignedInt)m_claimTouch[cell] < bucket) return 0;+ const Int base = claimSlotOf(cell, bucket);+ for (Int p = 0; p < PF_CLAIM_PROBES; p++) {+ const PathClaim& e = m_claims[(base + p) & (PF_CLAIM_TABLE_SIZE - 1)];+ if (e.m_cell == cell && e.m_bucket == bucket) return e.m_weight;+ }+ return 0;+}++/* One sample of a plan: the cell the unit expects to be in, dilated over the body's own footprint,+ in the bucket it expects to be there and at half strength in the two either side. The spill is+ not decoration - an arrival time estimated from a straight-line speed is only ever right to+ about a bucket, and a claim with no spill prices nothing at all half the time. */+void Pathfinder::stampClaimAt( const Coord3D *pos, UnsignedInt frame, Int dilation )+{+ if (m_claims == NULL || m_claimTouch == NULL) return;+ ICoord2D c;+ worldToCell(pos, &c);+ const UnsignedInt bucket = frame / PF_CLAIM_BUCKET_FRAMES;+ const Int h = m_extent.hi.y + 1;+ for (Int dx = -dilation; dx <= dilation; dx++) {+ Int x = c.x + dx;+ if (x < m_extent.lo.x || x > m_extent.hi.x) continue;+ for (Int dy = -dilation; dy <= dilation; dy++) {+ Int y = c.y + dy;+ if (y < m_extent.lo.y || y > m_extent.hi.y) continue;+ Int cell = x*h + y;+ addClaim(cell, bucket, 2);+ if (bucket > 0) addClaim(cell, bucket-1, 1);+ addClaim(cell, bucket+1, 1);+ UnsignedShort touch = (UnsignedShort)(bucket + 1);+ if (m_claimTouch[cell] < touch) m_claimTouch[cell] = touch;+ }+ }+}++/**+ * Stamp where this unit expects to be over the next few seconds.+ *+ * Called from the unit itself, about once a second, and it always starts from where the unit+ * actually is rather than from where the path says it should be by now. That is the whole reason+ * nothing has to be released: a claim carries the absolute bucket it was made for, so it expires+ * by being in the past, and a unit that got held up simply re-stamps later times next second.+ */+void Pathfinder::claimPathTiming( const Object *obj, Path *path )+{+ if (m_claims == NULL || obj == NULL || path == NULL) return;+ if (TheGlobalData->m_noFlowPath) return;++ const AIUpdateInterface *ai = obj->getAIUpdateInterface();+ if (ai == NULL) return;+ const Locomotor *loco = ai->getCurLocomotor();+ if (loco == NULL) return;+ Real speed = loco->getMaxSpeedForCondition(obj->getBodyModule()->getDamageState());+ if (speed < 0.01f) return; // world units per logic frame++ Int radius = 0;+ Bool center = true;+ getRadiusAndCenter(obj, radius, center);+ Int dilation = radius;+ if (dilation > 2) dilation = 2;+ if (dilation < 0) dilation = 0;+ // one sample per body width: a tank stamping every cell would claim the same ground five times+ const Int stride = dilation > 0 ? dilation : 1;++ const Coord3D *myPos = obj->getPosition();+ // where on the path we actually are. The path is a line-of-sight skeleton after optimize(),+ // so this is a handful of nodes, not a cell walk.+ PathNode *from = path->getFirstNode();+ PathNode *node;+ Real bestSqr = FLT_MAX;+ for (node = path->getFirstNode(); node; node = node->getNext()) {+ const Coord3D *p = node->getPosition();+ Real dx = p->x - myPos->x, dy = p->y - myPos->y;+ Real d = dx*dx + dy*dy;+ if (d < bestSqr) { bestSqr = d; from = node; }+ }+ if (from == NULL) return;++ const UnsignedInt now = TheGameLogic->getFrame();+ const Real horizon = speed * (Real)(PF_CLAIM_BUCKETS * PF_CLAIM_BUCKET_FRAMES);+ Coord3D cur = *myPos;+ Real travelled = 0.0f;+ Int sample = 0, stamped = 0;++ for (node = from; node; node = node->getNext()) {+ const Coord3D *to = node->getPosition();+ Real dx = to->x - cur.x, dy = to->y - cur.y;+ Real segLen = (Real)sqrt(dx*dx + dy*dy);+ if (segLen < 0.01f) { cur = *to; continue; }+ Int steps = (Int)(segLen / PATHFIND_CELL_SIZE_F) + 1;+ for (Int s = 1; s <= steps; s++) {+ Real t = (Real)s / (Real)steps;+ travelled += segLen / (Real)steps;+ if (travelled > horizon) return;+ if ((sample++ % stride) != 0) continue;+ if (++stamped > PF_CLAIM_SAMPLES_MAX) return;+ Coord3D p;+ p.x = cur.x + dx*t;+ p.y = cur.y + dy*t;+ p.z = cur.z;+ stampClaimAt(&p, now + (UnsignedInt)(travelled / speed), dilation);+ }+ cur = *to;+ }+}++/**+ * The travel speed the search now running should convert distance into time with, x256 so the+ * division in the inner loop stays integer. Cost units per logic frame: a step of one cell is+ * COST_ORTHOGONAL, and a cell is PATHFIND_CELL_SIZE_F wide.+ */+Int Pathfinder::flowSpeedOf( const Object *obj )+{+ if (obj == NULL) return 0;+ const AIUpdateInterface *ai = obj->getAIUpdateInterface();+ if (ai == NULL) return 0;+ const Locomotor *loco = ai->getCurLocomotor();+ if (loco == NULL) return 0;+ Real speed = loco->getMaxSpeedForCondition(obj->getBodyModule()->getDamageState());+ if (speed < 0.01f) return 0;+ // the sandbox plans at four fifths of top speed, because nothing ever holds top speed+ Real costPerFrame = speed * 0.8f * (Real)COST_ORTHOGONAL / PATHFIND_CELL_SIZE_F;+ Int scaled = (Int)(costPerFrame * 256.0f);+ return scaled > 0 ? scaled : 0;+}++/**+ * The whole of the flow charge for one step, so both places that expand a cell price it the same+ * way and a test can hold the three parts against each other.+ *+ * This runs once per neighbour per expansion - low millions of times in a busy frame - so the+ * common case has to be cheap. It is: one bounds check for all three maps, then a screen in+ * front of each of them that the overwhelming majority of cells fail. Open ground reads one byte+ * and returns. In particular the crossing charge's division is behind the claim screen, not in+ * front of it, because nearly every cell on the map has never been claimed by anybody.+ */+Int Pathfinder::flowStepCost( Int baseCost, Int cellX, Int cellY, Int radius, UnsignedInt travelSoFar )+{+ if (cellX < m_extent.lo.x || cellY < m_extent.lo.y || cellX > m_extent.hi.x || cellY > m_extent.hi.y)+ return 0;+ const Int cell = cellX*(m_extent.hi.y+1) + cellY;+ Int extra = 0;++ /* Exempting infantry from this charge was tried and is not in: over twenty four-player matches+ it changed not one cell of one route, so it is a branch that buys nothing. Every class+ pays, which is also what the sandbox does. */+ // a body of radius r needs r+0.5 cells of room; clearance counts five to the cell+ const Int need = PF_CLEARANCE_ORTHO*radius + PF_CLEARANCE_ORTHO/2;+ const Int clearance = m_clearance[cell];+ if (clearance - need < PF_CLEARANCE_SOFT)+ extra += Pathfinder_wallHugCost(baseCost, clearance, need);++ if (m_numTrafficCells > 0) {+ const Int jam = m_traffic[cell];+ if (jam > 0)+ extra += Pathfinder_trafficCost(baseCost, jam);+ }++ if (m_flowSpeed > 0 && (UnsignedInt)m_claimTouch[cell] >= m_flowNowBucket) {+ const UnsignedInt eta = m_flowNow + ((UnsignedInt)travelSoFar * 256) / (UnsignedInt)m_flowSpeed;+ const UnsignedInt bucket = eta / PF_CLAIM_BUCKET_FRAMES;+ if ((UnsignedInt)m_claimTouch[cell] >= bucket) {+ const Int base = claimSlotOf(cell, bucket);+ for (Int p = 0; p < PF_CLAIM_PROBES; p++) {+ const PathClaim& e = m_claims[(base + p) & (PF_CLAIM_TABLE_SIZE - 1)];+ if (e.m_cell == cell && e.m_bucket == bucket) {+ extra += Pathfinder_crossingCost(baseCost, e.m_weight);+ break;+ }+ }+ }+ }+ return extra;+}++void Pathfinder::beginFlowSearch( const Object *obj )+{+ m_flowNow = TheGameLogic ? TheGameLogic->getFrame() : 0;+ m_flowNowBucket = m_flowNow / PF_CLAIM_BUCKET_FRAMES;+ m_flowCosts = !TheGlobalData->m_noFlowPath && obj != NULL &&+ m_clearance != NULL && m_traffic != NULL && m_claims != NULL && m_claimTouch != NULL;+ m_flowSpeed = m_flowCosts ? flowSpeedOf(obj) : 0;+ // and the estimate is raised to match what the charge adds, or the search stops steering+ thePathHeuristicNum = m_flowCosts ? PF_HEURISTIC_FLOW_NUM : 3;+ thePathHeuristicDen = m_flowCosts ? PF_HEURISTIC_FLOW_DEN : 2;}@@ -4336,10 +4795,13 @@ void Pathfinder::reset( void )delete []m_blockOfMapCells;m_blockOfMapCells = NULL;}- if (m_map) {+ if (m_map) {delete [] m_map;m_map = NULL;}+ freeFlowMaps();+ m_flowCosts = false;+ m_flowSpeed = 0;Int i;for (i=0; i<=LAYER_LAST; i++) {@@ -4564,6 +5026,7 @@ void Pathfinder::classifyFence( Object *obj, Bool insert )if (didAnything) {m_zoneManager.markZonesDirty( insert );m_zoneManager.updateZonesForModify(m_map, m_layers, cellBounds, m_extent);+ markClearanceDirty();}#if 0// Perhaps it would make more sense to use the iteratecellsalongpath() provided in this class,@@ -4820,7 +5283,8 @@ void Pathfinder::internal_classifyObjectFootprint( Object *obj, Bool insert )break;} // switchm_zoneManager.updateZonesForModify(m_map, m_layers, cellBounds, m_extent);-+ markClearanceDirty();+Int i, j;cellBounds.lo.x -= 2;cellBounds.lo.y -= 2;@@ -5079,6 +5543,7 @@ void Pathfinder::newMap( void )m_layers[LAYER_WALL].allocateCellsForWallLayer(&m_extent, m_wallPieces, m_numWallPieces);}}+ allocateFlowMaps();classifyMap();// Add existing objects.Object *obj;@@ -5087,6 +5552,9 @@ void Pathfinder::newMap( void )classifyObjectFootprint(obj, true);}+ // only now does the map hold the buildings, and clearance is a measure of the buildings+ buildClearance();+m_isMapReady = true;}@@ -5177,6 +5645,7 @@ void Pathfinder::classifyMap(void)void Pathfinder::forceMapRecalculation( void ){classifyMap( );+ buildClearance( );}/**@@ -6667,6 +7136,16 @@ struct ExamineCellsStructreturn 1;}to->setBlockedByAlly(false);+ /* The shortcut probe has to be priced the same way the ordinary expansion is, or it+ undercuts it: a straight run at the goal that pays nothing for traffic would beat+ every route the flow model just spent its cost steering units onto. */+ {+ const UnsignedInt travel = from->getTravelSoFar() + COST_ORTHOGONAL;+ to->setTravelSoFar(travel);+ if (d->thePathfinder->flowCostsOn() && to->getLayer()==LAYER_GROUND) {+ newCostSoFar += d->thePathfinder->flowStepCost(COST_ORTHOGONAL, to_x, to_y, d->radius, travel);+ }+ }Int costRemaining = 0;costRemaining = to->costToGoal( d->goalCell );// check if this neighbor cell is already on the open (waiting to be tried)@@ -6889,6 +7368,20 @@ Int Pathfinder::examineNeighboringCells(PathfindCell *parentCell, PathfindCell *}newCostSoFar = newCell->costSoFar( parentCell );++ /* The flow charge. Ground covered is tracked separately from cost paid, because the+ crossing charge asks "when will we be standing here" and a detour taken to dodge+ somebody does not slow the unit down - charging the penalties into the clock as well+ would have the search believe it arrives whole seconds later than it does. */+ {+ const Int stepBase = (i>=firstDiagonal) ? COST_DIAGONAL : COST_ORTHOGONAL;+ const UnsignedInt travel = parentCell->getTravelSoFar() + stepBase;+ newCell->setTravelSoFar(travel);+ if (m_flowCosts && newCell->getLayer()==LAYER_GROUND) {+ newCostSoFar += flowStepCost(stepBase, newCellCoord.x, newCellCoord.y, radius, travel);+ }+ }+if (info.allyMoving && dx<10 && dy<10) {newCostSoFar += 3*COST_DIAGONAL;}@@ -7105,7 +7598,8 @@ Path *Pathfinder::internalFindPath( Object *obj, const LocomotorSet& locomotorSeif (obj) {getRadiusAndCenter(obj, radius, centerInCell);}-+ beginFlowSearch(obj);+Bool isHuman = true;if (obj && obj->getControllingPlayer() && (obj->getControllingPlayer()->getPlayerType()==PLAYER_COMPUTER)) {isHuman = false; // computer gets to cheat.@@ -7751,7 +8245,8 @@ Path *Pathfinder::findGroundPath( const Coord3D *from,DEBUG_LOG(("Find ground path..."));#endifBool centerInCell = false;-+ beginFlowSearch(NULL); // the group corridor is terrain, and every member rides it+m_zoneManager.clearPassableFlags();Bool isHuman = true;@@ -8244,7 +8739,8 @@ Path *Pathfinder::internal_findHierarchicalPath( Bool isHuman, const LocomotorSu#if defined _DEBUG || defined _INTERNALInt startTimeMS = ::GetTickCount();#endif-+ beginFlowSearch(NULL); // "is there a way at all" must not be talked out of it by traffic+if (rawTo->x == 0.0f && rawTo->y == 0.0f) {DEBUG_LOG(("Attempting pathfind to 0,0, generally a bug.\n"));return NULL;@@ -8997,7 +9493,8 @@ Bool Pathfinder::pathDestination( Object *obj, const LocomotorSet& locomotorSet{//CRCDEBUG_LOG(("Pathfinder::pathDestination()\n"));if (m_isMapReady == false) return NULL;-+ beginFlowSearch(NULL);+if (!obj) return false;Int cellCount = 0;@@ -9283,7 +9780,8 @@ Int Pathfinder::checkPathCost(Object *obj, const LocomotorSet& locomotorSet, con{//CRCDEBUG_LOG(("Pathfinder::checkPathCost()\n"));if (m_isMapReady == false) return NULL;- enum {MAX_COST = 0x7fff0000};+ beginFlowSearch(NULL); // this is a yardstick between two points, not a route anybody drives+ enum {MAX_COST = 0x7fff0000};if (!obj) return MAX_COST;Int cellCount = 0;@@ -9491,6 +9989,7 @@ Path *Pathfinder::findClosestPath( Object *obj, const LocomotorSet& locomotorSetCoord3D *rawTo, Bool blocked, Real pathCostMultiplier, Bool moveAllies){PathProfile pfProfile( PF_CLOSEST );+ beginFlowSearch(obj);//CRCDEBUG_LOG(("Pathfinder::findClosestPath()\n"));#if defined _DEBUG || defined _INTERNALInt startTimeMS = ::GetTickCount();@@ -11042,6 +11541,7 @@ Path *Pathfinder::getMoveAwayFromPath(Object* obj, Object *otherObj,Path *pathToAvoid, Object *otherObj2, Path *pathToAvoid2){PathProfile pfProfile( PF_MOVEAWAY );+ beginFlowSearch(NULL);if (m_isMapReady == false) return false; // Should always be ok.#if defined _DEBUG || defined _INTERNALInt startTimeMS = ::GetTickCount();@@ -11218,6 +11718,7 @@ Path *Pathfinder::patchPath( const Object *obj, const LocomotorSet& locomotorSetPath *originalPath, Bool blocked ){PathProfile pfProfile( PF_PATCH );+ beginFlowSearch(obj);//CRCDEBUG_LOG(("Pathfinder::patchPath()\n"));#if defined _DEBUG || defined _INTERNALInt startTimeMS = ::GetTickCount();@@ -11404,6 +11905,7 @@ Path *Pathfinder::findAttackPath( const Object *obj, const LocomotorSet& locomotconst Object *victim, const Coord3D* victimPos, const Weapon *weapon ){PathProfile pfProfile( PF_ATTACK );+ beginFlowSearch(NULL); // "where can I shoot from" is not a movement route/*CRCDEBUG_LOG(("Pathfinder::findAttackPath() for object %d (%s)\n", obj->getID(), obj->getTemplate()->getName().str()));XferCRC xferCRC;@@ -11762,6 +12264,7 @@ Path *Pathfinder::findSafePath( const Object *obj, const LocomotorSet& locomotorconst Coord3D *from, const Coord3D* repulsorPos1, const Coord3D* repulsorPos2, Real repulsorRadius){PathProfile pfProfile( PF_SAFE );+ beginFlowSearch(NULL); // running away prices danger, not traffic//CRCDEBUG_LOG(("Pathfinder::findSafePath()\n"));if (m_isMapReady == false) return false; // Should always be ok.#if defined _DEBUG || defined _INTERNAL@@ -11974,5 +12477,18 @@ void Pathfinder::xfer( Xfer *xfer )//-----------------------------------------------------------------------------void Pathfinder::loadPostProcess( void ){+ /* None of the three flow maps is saved, and only one of them needs to be. Clearance is a+ measure of the map, so it is simply recomputed from the map that has just been loaded and+ comes out identical to the one the save was taken from. Traffic and claims are a few+ seconds of history that the game rebuilds by playing: a loaded game starts with nobody+ jammed and nobody's plan on the map, and is back to the same state within a second or two.+ The cost of that is a unit or two picking a marginally different route just after a load,+ which is a single-player concern - Generals has no mid-game save in a network match, so+ there is no second machine to disagree with. */+ buildClearance();+ resetClaims();+ m_numTrafficCells = 0;+ if (m_traffic)+ memset(m_traffic, 0, (m_extent.hi.x+1)*(m_extent.hi.y+1)*sizeof(UnsignedByte));} // end loadPostProcessdiff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cppindex a2880b109..203450185 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp@@ -2246,12 +2246,36 @@ UpdateSleepTime AIUpdateInterface::doLocomotor( void )// this is the only place a blocked unit is counted once per frame rather than once per// collision pair, so it is where the traffic-jam number for the headless run comes fromPathfinder::bumpBlockedFrame( m_isBlockedAndStuck );++ /* And it is where the traffic map is written. A unit that is stopped is the definition of+ traffic; a unit that is merely slow is not, and neither is a unit parked because it has+ arrived. The cell it is standing in gets more expensive for about a second, which is+ long enough for whoever repaths next to be handed a way round the line instead of a+ place in it. */+ if (!TheGlobalData->m_noFlowPath)+ {+ Int trafficRadius = 0;+ Bool trafficCenter = true;+ TheAI->pathfinder()->getRadiusAndCenter(getObject(), trafficRadius, trafficCenter);+ TheAI->pathfinder()->noteTraffic(getObject()->getPosition(), trafficRadius);+ }}else{m_blockedFrames = 0;}+ /* Re-stamp where this unit expects to be over the next few seconds, once a second, offset by+ its own id so the whole army does not do it on one frame. Always from where the unit+ actually is - a claim made a second ago against a plan that has since been held up is+ exactly the claim that would send somebody else round a crossing that is no longer there. */+ if (!TheGlobalData->m_noFlowPath && getPath() != NULL)+ {+ UnsignedInt stagger = TheGameLogic->getFrame() + (UnsignedInt)getObject()->getID();+ if ((stagger % PF_CLAIM_REFRESH_FRAMES) == 0)+ TheAI->pathfinder()->claimPathTiming(getObject(), getPath());+ }+const Bool traceWasBlocked = m_isBlocked; // -tracemove: the flag is cleared on the next linem_isBlocked = FALSE;diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cppindex b7234ae5c..d15f6cdac 100644--- a/GeneralsMD/Code/Tests/test_gameengine.cpp+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp@@ -8375,3 +8375,99 @@ TEST(a_tab_control_with_no_size_or_too_many_tabs_answers_nothing)CHECK_EQ( GadgetTabControl_tabAtOffset( 100 * (NUM_TAB_PANES - 1), 100, 20 ), NUM_TAB_PANES - 1 );CHECK_EQ( GadgetTabControl_tabAtOffset( 100 * NUM_TAB_PANES, 100, 20 ), -1 );}++//----------------------------------------------------------------------------------------------------------+// The flow model's three charges.+//+// Each of them is a small piece of integer arithmetic that runs a few million times a frame and+// that nothing else in the game can be used to check. What matters about all three is the same+// thing: open ground is free, the charge is bounded, and the bound is a stated multiple of a step.+// A version that gets the bound wrong does not look wrong - it looks like the pathfinder got slow.+//----------------------------------------------------------------------------------------------------------++/** Twelve cells from anything, a body pays nothing for the ground it is on. This is the case that+ covers most of most maps, and a charge here would be a tax on every route in the game. */+TEST(open_ground_costs_a_route_nothing)+{+ const Int need = PF_CLEARANCE_ORTHO*1 + PF_CLEARANCE_ORTHO/2; // a one-cell body+ CHECK_EQ( Pathfinder_wallHugCost( 10, PF_CLEARANCE_MAX, need ), 0 );+ CHECK_EQ( Pathfinder_wallHugCost( 14, PF_CLEARANCE_MAX, need ), 0 );++ // and nothing is charged at or past the edge of the band. Just inside it the charge is real+ // but rounds away against a ten-unit step, which is the intent: the band tapers to nothing+ // rather than stepping off a cliff, so a route is not pulled about by its outer edge.+ CHECK_EQ( Pathfinder_wallHugCost( 10, need + PF_CLEARANCE_SOFT, need ), 0 );+ CHECK_EQ( Pathfinder_wallHugCost( 10, need + PF_CLEARANCE_SOFT - 1, need ), 0 );+ CHECK( Pathfinder_wallHugCost( 10, need + PF_CLEARANCE_SOFT/2, need ) > 0 );+}++/** A cell exactly as tight as the body costs PF_WALLHUG_NUM/DEN of a step and never more, however+ far into the terrain the cell is. Unbounded is what sends the search round the whole map. */+TEST(wall_hugging_is_capped_at_its_stated_multiple)+{+ const Int need = PF_CLEARANCE_ORTHO*2 + PF_CLEARANCE_ORTHO/2; // a two-cell body+ const Int peak = (10 * PF_WALLHUG_NUM) / PF_WALLHUG_DEN;+ CHECK_EQ( Pathfinder_wallHugCost( 10, need, need ), peak );+ CHECK_EQ( Pathfinder_wallHugCost( 10, 0, need ), peak ); // inside a wall: no worse+ CHECK_EQ( Pathfinder_wallHugCost( 10, need - 99, need ), peak ); // and negative slack does not wrap++ // a diagonal step is charged in proportion to itself+ CHECK_EQ( Pathfinder_wallHugCost( 14, need, need ), (14 * PF_WALLHUG_NUM) / PF_WALLHUG_DEN );+}++/** Quadratic, not linear: half way into the band costs about a quarter of the peak. A linear+ falloff was the first version of this and it taxed half the map at a third of a step. */+TEST(wall_hugging_falls_off_as_the_square_of_the_room_left)+{+ const Int need = 5;+ const Int peak = Pathfinder_wallHugCost( 100, need, need );+ const Int half = Pathfinder_wallHugCost( 100, need + PF_CLEARANCE_SOFT/2, need );+ CHECK( half * 3 < peak ); // a quarter-ish, comfortably under a third+ CHECK( half > 0 );+}++/** Traffic prices a queue, and it is capped for the same reason wall-hugging is: the heuristic+ cannot see any of it, so every cost it cannot see is paid in cells expanded. */+TEST(traffic_is_free_when_empty_and_capped_when_full)+{+ CHECK_EQ( Pathfinder_trafficCost( 10, 0 ), 0 );+ CHECK_EQ( Pathfinder_trafficCost( 10, -1 ), 0 );+ const Int peak = (10 * PF_TRAFFIC_NUM) / PF_TRAFFIC_DEN;+ CHECK_EQ( Pathfinder_trafficCost( 10, PF_TRAFFIC_FULL ), peak );+ CHECK_EQ( Pathfinder_trafficCost( 10, PF_TRAFFIC_MAX ), peak ); // saturated, not overflowing+ CHECK( Pathfinder_trafficCost( 10, PF_TRAFFIC_FULL/2 ) < peak );+ CHECK( Pathfinder_trafficCost( 10, PF_TRAFFIC_FULL/2 ) > 0 );+}++/** A claim spills into the buckets either side of its own at half strength, so weights arrive in+ halves. One half of one unit is not a crossing and must cost nothing at all - otherwise every+ cell within a bucket of anybody's plan is charged, which is most of a battlefield. */+TEST(half_a_unit_wanting_a_cell_is_not_a_crossing)+{+ CHECK_EQ( Pathfinder_crossingCost( 10, 0 ), 0 );+ CHECK_EQ( Pathfinder_crossingCost( 10, 1 ), 0 ); // the spill from a neighbouring bucket alone+ CHECK( Pathfinder_crossingCost( 10, 2 ) > 0 ); // one whole unit, at the moment we get there+}++/** And the crossing charge saturates: four units wanting one cell at one moment is as bad as a+ crossing gets, and a fifth must not make the route look impossible. */+TEST(a_crossing_charge_saturates_rather_than_growing)+{+ const Int peak = (10 * PF_CROSSING_NUM * PF_CLAIM_UNITS_MAX) / PF_CROSSING_DEN;+ CHECK_EQ( Pathfinder_crossingCost( 10, 2*PF_CLAIM_UNITS_MAX ), peak );+ CHECK_EQ( Pathfinder_crossingCost( 10, 2*PF_CLAIM_UNITS_MAX + 40 ), peak );+ CHECK_EQ( Pathfinder_crossingCost( 10, 0xFFFF ), peak );+}++/** The three charges together bound what the flow model can add to one step. This is the number+ that decides whether the search still steers or fans out, so it is pinned here rather than left+ to be rediscovered from a slow frame. */+TEST(the_whole_flow_charge_for_one_step_is_bounded)+{+ const Int base = 10;+ const Int worst = Pathfinder_wallHugCost( base, 0, 5 ) ++ Pathfinder_trafficCost( base, PF_TRAFFIC_MAX ) ++ Pathfinder_crossingCost( base, 0xFFFF );+ CHECK( worst <= 6 * base );+ CHECK( worst >= 3 * base ); // and it is not so small that none of it does anything+}