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): move a group down one corridor and price crossings

Olcay Seygan472bb5db7408
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h
index ab1021706..f528a4596 100644
--- a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h
+++ b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h
@@ -97,6 +97,8 @@ public:
Bool m_useDrawModuleLOD;
Bool m_useHeatEffects;
Bool m_useFpsLimit;
+ Bool m_useGroupPaths; ///< false = -nogrouppath: every unit solves its own path, no shared corridor
+ Bool m_useCrossingCost; ///< false = -nocrosstime: the reservation map is not kept and paths ignore when other units will be where
Bool m_dumpAssetUsage;
Int m_framesPerSecondLimit;
Int m_chipSetType; ///<See W3DShaderManager::ChipsetType for options
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h
index d74719d8e..ba7a24694 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h
@@ -1230,6 +1230,7 @@ private:
UnsignedInt m_id; ///< the unique ID of this group
Path *m_groundPath; ///< Group ground path.
+ Int m_groundPathDiameter; ///< width in cells the group corridor was actually found at.
mutable VecObjectID m_lastRequestedIDList; ///< this is used so we can return by reference, saving a copy
};
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h
index f32d84573..b5eb9e338 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h
@@ -31,6 +31,8 @@
#ifndef _PATHFIND_H_
#define _PATHFIND_H_
+#include <vector>
+
#include "Common/GameType.h"
#include "Common/GameMemory.h"
#include "Common/Snapshot.h"
@@ -40,6 +42,7 @@
class Bridge;
class Object;
+class Path;
class Weapon;
class PathfindZoneManager;
@@ -195,6 +198,40 @@ struct ClosestPointOnPathInfo
PathfindLayerEnum layer;
};
+//----------------------------------------------------------------------------------------------------------
+
+/**
+ * One live path's claim on one pathfind cell: the logic frame its owner expects to be standing
+ * there, and which way it is going when it arrives.
+ *
+ * The congestion map (Pathfinder::m_pathUsage) has no clock in it, so a cell somebody will drive
+ * over in ten seconds costs exactly as much as one they are sitting in now. That is the right
+ * answer for "is this ground spoken for" and the wrong one for "will we be on it at the same
+ * moment" - which is the whole difference between a shared road, where units queue nose to tail
+ * and everyone gets through, and a crossing, where two columns arrive from different directions
+ * and stop each other dead.
+ *
+ * The heading is why a reservation stores more than a time. Units following each other down one
+ * road are in the same cells at nearly the same moments and must not be charged for it; the
+ * expensive case is two of them wanting a cell at the same moment while going different ways.
+ */
+struct PathReservation
+{
+ const Path* m_owner; ///< the path that claimed this cell (identity only)
+ ICoord2D m_cell;
+ UnsignedInt m_frame; ///< logic frame the owner expects to reach m_cell
+ Real m_headingX; ///< normalized direction of travel on arrival
+ Real m_headingY;
+ Int m_nextInBucket; ///< next reservation in this hash bucket, -1 = end of chain
+};
+
+/// The crossing penalty, split out of examineNeighboringCells so the cap is testable.
+extern Int Pathfinder_crossingPenalty( Int conflicts );
+
+/// Do these two claims on one cell clash - same moment, and not going the same way?
+extern Bool Pathfinder_reservationsClash( UnsignedInt frameA, Real headingAX, Real headingAY,
+ UnsignedInt frameB, Real headingBX, Real headingBY );
+
/**
* This class encapsulates a "path" returned by the Pathfinder.
*/
@@ -286,6 +323,13 @@ protected:
UnsignedShort m_totalCost, m_costSoFar; ///< cost estimates for A* search
+ /* Distance travelled to reach this cell, in the same units as m_costSoFar but with none of the
+ penalties in it. The penalties are money, not ground: a detour taken to dodge someone must
+ not also make the search believe it arrives eight cells later than it does, and the crossing
+ cost below turns this number into an arrival frame. 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 only
ICoord2D m_pos;
@@ -394,9 +438,11 @@ 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;}
+ inline void setTravelSoFar(UnsignedInt travel) { if( m_info ) m_info->m_travelSoFar = travel;}
void setParentCell(PathfindCell* parent);
void clearParentCell(void);
@@ -773,11 +819,18 @@ public:
/// Congestion map: how many live unit paths run through each cell. A* charges extra per path, so
/// units ordered along the same route spread into parallel lanes instead of stacking on one line.
- void registerPathUsage( const Path *path );
+ void registerPathUsage( const Path *path, const Object *obj );
void unregisterPathUsage( const Path *path );
void releasePathUsageBefore( const Path *path, const PathNode *node ); ///< unit has passed everything before node
void adjustPathUsage( const PathNode *from, const PathNode *to, Int delta ); ///< [from, to) raw nodes, +1/-1
+ /// Reservation map: *when* each live path expects to be in each cell, and going which way. A*
+ /// charges extra where somebody else wants the same cell at the same moment on a different
+ /// heading, which is a crossing; two units queued along one road never pay it.
+ void reservePathTiming( const Path *path, const Object *obj ); ///< stamp arrival frames for the whole path
+ void releaseReservations( const Path *path, const PathNode *from, const PathNode *to ); ///< [from, to) raw nodes
+ Int countCrossingReservations( Int x, Int y, UnsignedInt frame, Real headingX, Real headingY ) const;
+
void setIgnoreObstacleID( ObjectID objID ); ///< if non-zero, the pathfinder will ignore the given obstacle
void setIgnoreUnderConstruction( Bool ignore ); ///< if true, half-built structures are not obstacles to this search
Bool builderMayCross( const PathfindCell *cell ) const; ///< is this obstacle cell a structure the builder now searching may walk over?
@@ -947,6 +1000,20 @@ private:
PathfindCell **m_map; ///< Pathfinding map indexes - contains matrix indexing into the map.
UnsignedByte *m_pathUsage; ///< Congestion map, (hi.x+1)*(hi.y+1), indexed [x*(hi.y+1)+y]
Int getPathUsage( Int x, Int y ) const;
+
+ //
+ // Reservation map. A dense per-cell array would be a second whole-map allocation to hold a few
+ // thousand live claims, so the claims live in a pool and are found through a fixed hash of the
+ // cell coordinate. The A* only ever probes it for a cell the congestion map already says a live
+ // path runs through - the two maps stamp exactly the same cells - so the hash is walked on the
+ // handful of cells where a crossing is even possible and nowhere else.
+ //
+ enum {PATH_RESERVATION_BUCKETS = 2048}; ///< power of two: the hash is masked, not divided
+ std::vector<PathReservation> m_reservations; ///< pool; a free entry is linked into m_firstFreeReservation
+ Int m_firstFreeReservation; ///< head of the free list, -1 = grow the pool
+ Int m_reservationBuckets[PATH_RESERVATION_BUCKETS]; ///< cell hash -> first reservation, -1 = empty
+ static Int reservationBucketOf( Int x, Int y );
+ void resetReservations( void ); ///< drop every claim: the map underneath them is gone
IRegion2D m_extent; ///< Grid extent limits
IRegion2D m_logicalExtent; ///< Logical grid extent limits
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp
index 8e0f0c580..34895302d 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp
@@ -77,6 +77,7 @@ AIGroup::AIGroup( void )
{
// DEBUG_LOG(("***AIGROUP %x is being constructed.\n", this));
m_groundPath = NULL;
+ m_groundPathDiameter = 0;
m_speed = 0.0f;
m_matchSpeeds = TRUE;
m_dirty = false;
@@ -520,6 +521,11 @@ void AIGroup::computeIndividualDestination( Coord3D *dest, const Coord3D *groupD
static const Int PATH_DIAMETER_IN_CELLS = 6;
+/* A player's selection keeps its shape - a shared wide corridor split into columns for a move, the
+ centroid offsets for an attack move - up to this many members. Past it the shape is what breaks:
+ two hundred units strung out along an arc, three hundred with no workable goal cell at all. */
+static const Int MAX_MEMBERS_FOR_GROUP_LANES = 40;
+
//-------------------------------------------------------------------------------------------------
// Internal function for moving a group of infantry as a column.
//
@@ -601,6 +607,7 @@ Bool AIGroup::friend_computeGroundPath( const Coord3D *pos, CommandSourceType cm
distSqr = dx*dx+dy*dy;
}
if (distSqr < sqr(TheAI->getAiData()->m_minDistanceForGroup)) {
+ DEBUG_LOG(("GROUPPATH probe: too close, distSqr %f min %f\n", distSqr, sqr(TheAI->getAiData()->m_minDistanceForGroup)));
return false;
}
if (distSqr>sqr(TheAI->getAiData()->m_distanceRequiresGroup)) {
@@ -635,10 +642,28 @@ Bool AIGroup::friend_computeGroundPath( const Coord3D *pos, CommandSourceType cm
}
if (isPassable) closeEnough = true;
}
- if (!closeEnough) return false;
-
- m_groundPath = TheAI->pathfinder()->findGroundPath(&center, pos, PATH_DIAMETER_IN_CELLS, false);
- return m_groundPath!=NULL;
+ if (!closeEnough) {
+ DEBUG_LOG(("GROUPPATH probe: not closeEnough, infantry %d vehicles %d\n", numInfantry, numVehicles));
+ return false;
+ }
+
+ // A corridor six cells wide does not exist on every route - a bridge, a ramp or a gap between
+ // two cliffs is narrower than sixty world units, and findGroundPath then returns NULL. Retail
+ // gave up there and let every member solve its own path to the same point, which is exactly the
+ // single file this is trying to avoid: the group is at its most cramped precisely where it most
+ // needs to be told who drives where. So ask for a narrower corridor before giving up, and
+ // remember the width that answered - the columns below are spaced against it, not against six.
+ const Int groupPathDiameters[3] = { PATH_DIAMETER_IN_CELLS, 4, 3 };
+ for (Int w = 0; w < 3; ++w) {
+ m_groundPathDiameter = groupPathDiameters[w];
+ m_groundPath = TheAI->pathfinder()->findGroundPath(&center, pos, m_groundPathDiameter, false);
+ DEBUG_LOG(("GROUPPATH probe: findGroundPath diameter %d -> %s\n", m_groundPathDiameter, m_groundPath?"path":"NULL"));
+ if (m_groundPath) {
+ return true;
+ }
+ }
+ m_groundPathDiameter = 0;
+ return false;
}
@@ -1141,6 +1166,51 @@ void AIGroup::friend_moveFormationToPos( const Coord3D *pos, CommandSourceType c
}
}
+/**
+ * Is there room for this unit, centred on spot, across its own width along normal?
+ * The corridor is wide enough for the group, but a lane offset is a blind sideways step off the
+ * path the pathfinder actually checked, and a tank is wider than the cell that step lands in.
+ */
+static Bool laneSpotIsClear( Object *unit, const Coord3D *spot, const Coord2D *normal, Real halfWidth )
+{
+ AIUpdateInterface *ai = unit->getAIUpdateInterface();
+ if (ai == NULL) return false;
+ Pathfinder *pathfinder = TheAI->pathfinder();
+ const Bool isCrusher = unit->getCrusherLevel() > 0;
+ const PathfindLayerEnum layer = unit->getLayer();
+ if (!pathfinder->validMovementPosition( isCrusher, layer, ai->getLocomotorSet(), spot )) {
+ return false;
+ }
+ Coord3D edge = *spot;
+ edge.x += halfWidth * normal->x;
+ edge.y += halfWidth * normal->y;
+ if (!pathfinder->validMovementPosition( isCrusher, layer, ai->getLocomotorSet(), &edge )) {
+ return false;
+ }
+ edge = *spot;
+ edge.x -= halfWidth * normal->x;
+ edge.y -= halfWidth * normal->y;
+ return pathfinder->validMovementPosition( isCrusher, layer, ai->getLocomotorSet(), &edge );
+}
+
+/**
+ * Perpendicular distance of pt from the segment from a to b, in 2d.
+ */
+static Real distanceFromSegment( const Coord3D *a, const Coord3D *b, const Coord3D *pt )
+{
+ Real dx = b->x - a->x;
+ Real dy = b->y - a->y;
+ Real lenSqr = dx*dx + dy*dy;
+ if (lenSqr < 1.0f) {
+ dx = pt->x - a->x;
+ dy = pt->y - a->y;
+ return sqrtf(dx*dx + dy*dy);
+ }
+ Real cross = (pt->x - a->x)*dy - (pt->y - a->y)*dx;
+ if (cross < 0) cross = -cross;
+ return cross / sqrtf(lenSqr);
+}
+
//-------------------------------------------------------------------------------------------------
// Internal function for moving a group of vehicles as a column.
//
@@ -1191,11 +1261,12 @@ Bool AIGroup::friend_moveVehicleToPos( const Coord3D *pos, CommandSourceType cmd
endNode = NULL;
}
if (startNode==NULL || endNode==NULL) {
+ DEBUG_LOG(("VEHCOLUMN probe: corridor too short to take a heading from\n"));
m_groundPath->deleteInstance();
m_groundPath = NULL;
return false;
}
-
+
Coord2D startVector;
startVector.x = startNode->getPosition()->x - startPoint.x;
startVector.y = startNode->getPosition()->y - startPoint.y;
@@ -1217,6 +1288,7 @@ Bool AIGroup::friend_moveVehicleToPos( const Coord3D *pos, CommandSourceType cmd
endVectorNormal.normalize();
Int unitsToPath = 0;
+ Real maxUnitRadius = 0.0f;
Bool useEndVector = false;
// Move.
MemoryPoolObjectHolder iterHolder;
@@ -1256,6 +1328,9 @@ Bool AIGroup::friend_moveVehicleToPos( const Coord3D *pos, CommandSourceType cmd
// Sort by the dot product of normal.
iter->insert((*i), dx*startVectorNormal.x+dy*startVectorNormal.y);
unitsToPath++;
+ if ((*i)->getGeometryInfo().getBoundingCircleRadius() > maxUnitRadius) {
+ maxUnitRadius = (*i)->getGeometryInfo().getBoundingCircleRadius();
+ }
// If units are closer to the end vector than the start vector, use the end vector.
Real distToEndSqr;
@@ -1272,8 +1347,10 @@ Bool AIGroup::friend_moveVehicleToPos( const Coord3D *pos, CommandSourceType cmd
}
if (unitsToPath<TheAI->getAiData()->m_minVehiclesForGroup) {
+ DEBUG_LOG(("VEHCOLUMN probe: only %d vehicles, need %d\n", unitsToPath, TheAI->getAiData()->m_minVehiclesForGroup));
return false;
}
+ DEBUG_LOG(("VEHCOLUMN probe: laying %d vehicles into columns\n", unitsToPath));
Object *theUnit;
if (useEndVector) {
@@ -1404,13 +1481,16 @@ Bool AIGroup::friend_moveVehicleToPos( const Coord3D *pos, CommandSourceType cmd
curIndex = 0;
Int columnFactor[5] = {0,0,0,0,0};
+ // A lane is only a lane if the widest thing in the group fits in it with room to steer. Two
+ // cells was a guess, and it is narrower than a tank; this is measured off the units that were
+ // actually ordered, so a group of tanks spreads wider than a group of humvees.
+ const Real laneSpacing = 2.0f*maxUnitRadius + 0.5f*PATHFIND_CELL_SIZE_F;
PathfindLayerEnum layer = TheTerrainLogic->getLayerForDestination(pos);
for (theUnit = iter2->first(); theUnit; theUnit = iter2->next())
{
AIUpdateInterface *ai = theUnit->getAIUpdateInterface();
Int tmp = ai->getTmpValue();
Int threeColumnDelta = tmp>>16;
- Int columnDelta = (Short)(tmp & 0xFFFF);
Int factor = columnFactor[threeColumnDelta+2];
columnFactor[threeColumnDelta+2] = factor+1;
@@ -1418,6 +1498,21 @@ Bool AIGroup::friend_moveVehicleToPos( const Coord3D *pos, CommandSourceType cmd
PathNode *node = startNode;
PathNode *previousNode = m_groundPath->getFirstNode();
Coord3D prevPos = *theUnit->getPosition();
+ // Every waypoint kept is a turn taken: the unit stops steering for the horizon and steers for
+ // the next point instead. The corridor hands out one point per path node, and most of them sit
+ // on or near the straight line through their neighbours - a wobble the driver pays for and
+ // nobody asked for. This is the raycast simplification every modern pathfinder ends with: a
+ // point is dropped when the straight line past it is one this unit can actually drive
+ // (isLinePassable, which is the raycast) and it does not pull the route more than a lane
+ // width off the corridor the pathfinder cleared. A cheap distance test comes first so the
+ // common case - a point that barely bends anything - never pays for a line check.
+ const Real straightenTolerance = 0.5f*PATHFIND_CELL_SIZE_F;
+ const Int maxStraightenRun = 16;
+ const LocomotorSurfaceTypeMask surfaces = ai->getLocomotorSet().getValidSurfaces();
+ const PathfindLayerEnum unitLayer = theUnit->getLayer();
+ Coord3D pendingPos;
+ Bool havePending = false;
+ Int straightenRun = 0;
while (node) {
Coord3D dest = *node->getPosition();
PathNode *tmpNode;
@@ -1440,16 +1535,34 @@ Bool AIGroup::friend_moveVehicleToPos( const Coord3D *pos, CommandSourceType cmd
cornerVector.x = nextNode->getPosition()->x - previousNode->getPosition()->x;
cornerVector.y = nextNode->getPosition()->y - previousNode->getPosition()->y;
- Real offset = PATHFIND_CELL_SIZE_F*1.5f;
- dest.x += offset * columnDelta * cornerVectorNormal.x;
- dest.y += offset * columnDelta * cornerVectorNormal.y;
- if (factor&1) {
- dest.x += 0.5f*PATHFIND_CELL_SIZE_F * cornerVectorNormal.x;
- dest.y += 0.5f*PATHFIND_CELL_SIZE_F * cornerVectorNormal.y;
- } else {
- dest.x -= 0.5f*PATHFIND_CELL_SIZE_F * cornerVectorNormal.x;
- dest.y -= 0.5f*PATHFIND_CELL_SIZE_F * cornerVectorNormal.y;
+ // Retail drove the corridor in two lanes a cell and a half either side of its centre and
+ // nudged alternate units half a cell sideways on top of that, which is narrower than the
+ // units themselves: side by side they overlapped, so a group crossing open ground spent
+ // the trip shoving. Lanes are a whole unit apart plus a little air instead (laneSpacing),
+ // so a lane is somewhere a tank actually fits, and there is no half-cell nudge - two
+ // units sharing a lane drive one line, in file, which is what a lane is for.
+ Real lateral = laneSpacing * threeColumnDelta;
+
+ // The lane is a sideways step off the line the pathfinder checked, so it can land in a
+ // cliff or a building even though the corridor as a whole was passable - and a tank
+ // wedged against terrain is worse than a tank in a queue. Give the step back rather than
+ // take it blindly: full width, then half, then none, which is the corridor centre the
+ // path already proved. Trying half before giving up matters at the pinch points, where
+ // there is room for a nudge but not for a whole lane.
+ const Real halfWidth = theUnit->getGeometryInfo().getBoundingCircleRadius();
+ Coord3D laneDest = dest;
+ for (Int shrink = 0; shrink < 3; ++shrink) {
+ Real tryLateral = lateral;
+ if (shrink == 1) tryLateral = lateral * 0.5f;
+ if (shrink == 2) tryLateral = 0.0f;
+ laneDest = dest;
+ laneDest.x += tryLateral * cornerVectorNormal.x;
+ laneDest.y += tryLateral * cornerVectorNormal.y;
+ if (tryLateral == 0.0f || laneSpotIsClear( theUnit, &laneDest, &cornerVectorNormal, halfWidth )) {
+ break;
+ }
}
+ dest = laneDest;
Coord2D curVector;
curVector.x = dest.x-prevPos.x;
@@ -1457,8 +1570,24 @@ Bool AIGroup::friend_moveVehicleToPos( const Coord3D *pos, CommandSourceType cmd
clampToMap(&dest, controllingPlayerType);
// Make sure that this dest is going in the same direction as the vector.
if (cornerVector.x*curVector.x + cornerVector.y*curVector.y > 0) {
- path.push_back( dest );
- prevPos = dest;
+ if (!havePending) {
+ pendingPos = dest;
+ havePending = true;
+ straightenRun = 0;
+ } else if (straightenRun < maxStraightenRun &&
+ (distanceFromSegment( &prevPos, &dest, &pendingPos ) < straightenTolerance ||
+ (distanceFromSegment( &prevPos, &dest, &pendingPos ) < laneSpacing &&
+ TheAI->pathfinder()->isLinePassable( theUnit, surfaces, unitLayer,
+ prevPos, dest, false, true )))) {
+ // prevPos -> dest is drivable without the point in between; drop it and hold the turn.
+ pendingPos = dest;
+ straightenRun++;
+ } else {
+ path.push_back( pendingPos );
+ prevPos = pendingPos;
+ pendingPos = dest;
+ straightenRun = 0;
+ }
}
node=node->getNextOptimized();
@@ -1471,6 +1600,10 @@ Bool AIGroup::friend_moveVehicleToPos( const Coord3D *pos, CommandSourceType cmd
}
}
}
+ if (havePending) {
+ // the last corridor point is never dropped - it is what aims the unit at the goal.
+ path.push_back( pendingPos );
+ }
Coord3D dest = *pos;
if (threeColumnDelta<-3) threeColumnDelta=-3;
@@ -1479,11 +1612,16 @@ Bool AIGroup::friend_moveVehicleToPos( const Coord3D *pos, CommandSourceType cmd
if (unitsToPath<5) {
offset = PATHFIND_CELL_SIZE_F*1.5f;
}
+ // Same rule as the lanes: a cell and a half is less than a tank, so four tanks arriving on
+ // that spacing arrive on top of each other and finish the trip pushing.
+ if (offset < laneSpacing) {
+ offset = laneSpacing;
+ }
dest.x += offset * threeColumnDelta * endVectorNormal.x;
dest.y += offset * threeColumnDelta * endVectorNormal.y;
if (factor&1) {
- dest.x += PATHFIND_CELL_SIZE_F * endVectorNormal.x;
- dest.y += PATHFIND_CELL_SIZE_F * endVectorNormal.y;
+ dest.x += 0.5f*laneSpacing * endVectorNormal.x;
+ dest.y += 0.5f*laneSpacing * endVectorNormal.y;
}
#if 0
LocomotorPriority movePriority = LOCO_MOVES_MIDDLE;
@@ -1592,13 +1730,25 @@ void AIGroup::groupMoveToPosition( const Coord3D *p_posIn, Bool addWaypoint, Com
// holding a shape. Explicit formations - the ones the player asked for by name - still keep
// theirs, and the AI still moves its teams the old way.
//
- const Bool gatherOnPoint = ( cmdSource == CMD_FROM_PLAYER && !isFormation );
+ // That was too wide a net. Only a selection far larger than anyone drags a box around fails to
+ // fit its shape, and paying for it at every size cost the one thing the group path is for: a
+ // dozen tanks sent across a map all solve the same A* and drive down the single cheapest line
+ // nose to tail, because the congestion cost can only push a lane a cell or two aside. Below the
+ // cap they get the retail answer instead - one corridor wide enough for the group
+ // (PATH_DIAMETER_IN_CELLS), split into columns, so the group crosses a gap abreast and some of
+ // it takes the wider way round.
+ //
+ const Bool gatherOnPoint = ( cmdSource == CMD_FROM_PLAYER && !isFormation &&
+ m_memberListSize > MAX_MEMBERS_FOR_GROUP_LANES );
if (!addWaypoint && !isFormation && !gatherOnPoint) {
friend_computeGroundPath(pos, cmdSource);
didInfantry = friend_moveInfantryToPos(pos, cmdSource);
didVehicles = friend_moveVehicleToPos(pos, cmdSource);
}
+ DEBUG_LOG(("GROUPMOVE probe: members %d src %d gatherOnPoint %d formation %d waypoint %d corridor %d infantry %d vehicles %d\n",
+ m_memberListSize, (Int)cmdSource, gatherOnPoint?1:0, isFormation?1:0, addWaypoint?1:0,
+ m_groundPath!=NULL?1:0, didInfantry?1:0, didVehicles?1:0));
if (m_dirty)
recompute();
@@ -2369,10 +2519,11 @@ void AIGroup::groupAttackMoveToPosition( const Coord3D *pos, Int maxShotsToFire,
// As with a plain move (see groupMoveToPosition): a player's attack move sends everyone to
// the point and lets each unit take the nearest free cell to it, rather than holding the
// selection's shape on the way in - which a large group could only do by spreading along
- // an arc.
+ // an arc. And, as there, only a selection past the cap actually has that problem: under it
+ // the shape is what keeps the group off one another's path on the way in.
//
Coord3D dest;
- if (cmdSource == CMD_FROM_PLAYER)
+ if (cmdSource == CMD_FROM_PLAYER && m_memberListSize > MAX_MEMBERS_FOR_GROUP_LANES)
dest = goalPos;
else
computeIndividualDestination( &dest, &goalPos, theUnit, &center, FALSE );
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp
index 0662c9869..2ccbc2049 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp
@@ -1259,8 +1259,9 @@ PathfindCellInfo *PathfindCellInfo::getACellInfo(PathfindCell *cell,const ICoord
info->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;
@@ -1340,6 +1341,7 @@ Bool PathfindCell::startPathfind( PathfindCell *goalCell )
m_info->m_pathParent = NULL;
m_info->m_costSoFar = 0; // start node, no cost to get here
m_info->m_totalCost = 0;
+ m_info->m_travelSoFar = 0; // ... and no ground covered yet, which is when the search starts
if (goalCell) {
m_info->m_totalCost = costToGoal( goalCell );
}
@@ -1971,15 +1973,70 @@ const Int COST_DIAGONAL = 14;
const Int PATH_CONGESTION_COST = 5;
const Int PATH_CONGESTION_RANGE = 30; ///< cells from the start within which other paths cost anything
const Int PATH_CONGESTION_MAX_PATHS = 4; ///< the penalty stops growing past this many paths in a footprint
+
/* Split out of examineNeighboringCells so the cap is testable: the cap is the only thing keeping
this cost from flooding the search, since the heuristic cannot see it. */
-Int Pathfinder_congestionPenalty( Int usage )
+Int Pathfinder_congestionPenalty( Int usage, Int costPerPath )
{
if (usage <= 0)
return 0;
if (usage > PATH_CONGESTION_MAX_PATHS)
usage = PATH_CONGESTION_MAX_PATHS;
- return usage * PATH_CONGESTION_COST;
+ return usage * costPerPath;
+}
+
+/* The congestion cost above has no clock in it, and that is the one thing it cannot be taught: a
+ cell is either spoken for or it is not, so a road two columns share ten seconds apart is priced
+ exactly like the intersection they both want at once. Pricing it harder does not separate them,
+ it just makes every road expensive.
+
+ The reservation map adds the clock - each live path stamps the frame it expects to reach each of
+ its cells, and this cost is paid only where somebody else wants that cell inside a window of the
+ same moment *and* is going a different way. Nose to tail down one road is a queue and a queue is
+ what a road is for; two columns meeting at right angles is the case worth buying out.
+
+ Swept in Tools/PathLab (the same grid, costs and cap in Python) with --scenario cross, two groups
+ of eight sent to each other's corner across eight open layouts:
+ crossing cost blocked unit-frames frames to arrive real crossings search cost
+ 0 984 545 12 --
+ 60 741 531 11 +1%
+ 120 and 240 route identically to 60 - it saturates - and below 60 the effect fades out. On
+ the choke and twogaps layouts it is neutral, which is the point of the two gates below.
+
+ Two gates, each of which was measured before it was kept:
+
+ - Only traffic that is not going your way (PATH_CROSSING_SAME_WAY, headings within about 53
+ degrees). Charging everyone who shares a cell at the same moment charges a queue: the first
+ version of this priced hundreds of following-traffic pairs per run instead of the ten to
+ seventeen real crossings.
+ - Only where there is room to dodge, which here is the cell not being pinched. Pricing a
+ two-cell doorway does not spread anyone out - there is nowhere to spread to - it just sends
+ them to the next doorway to queue at that one instead.
+
+ The cap is here for the same reason the congestion cap is: the A* heuristic cannot see this cost,
+ so an uncapped one widens the search until it floods the cell pool and comes back with no path. */
+const Int PATH_CROSSING_COST = 60; ///< per clashing claim - six cells of detour, and it saturates there
+const Int PATH_CROSSING_WINDOW = 12; ///< frames either side of an arrival that still count as the same moment
+const Int PATH_CROSSING_MAX = 3; ///< the penalty stops growing past this many clashes in a cell
+const Real PATH_CROSSING_SAME_WAY = 0.6f; ///< headings this aligned are a queue, not a crossing
+
+Int Pathfinder_crossingPenalty( Int conflicts )
+{
+ if (conflicts <= 0)
+ return 0;
+ if (conflicts > PATH_CROSSING_MAX)
+ conflicts = PATH_CROSSING_MAX;
+ return conflicts * PATH_CROSSING_COST;
+}
+
+Bool Pathfinder_reservationsClash( UnsignedInt frameA, Real headingAX, Real headingAY,
+ UnsignedInt frameB, Real headingBX, Real headingBY )
+{
+ // UnsignedInt frames: subtract the smaller one, never negate.
+ UnsignedInt apart = (frameA > frameB) ? (frameA - frameB) : (frameB - frameA);
+ if (apart >= (UnsignedInt)PATH_CROSSING_WINDOW)
+ return false;
+ return headingAX*headingBX + headingAY*headingBY <= PATH_CROSSING_SAME_WAY;
}
const Real COST_TO_DISTANCE_FACTOR = 1.0f/10.0f;
@@ -4295,6 +4352,7 @@ void Pathfinder::reset( void )
delete [] m_pathUsage;
m_pathUsage = NULL;
}
+ resetReservations();
Int i;
for (i=0; i<=LAYER_LAST; i++) {
@@ -5699,17 +5757,19 @@ void Pathfinder::adjustPathUsage( const PathNode *from, const PathNode *to, Int
}
}
-void Pathfinder::registerPathUsage( const Path *path )
+void Pathfinder::registerPathUsage( const Path *path, const Object *obj )
{
if (!path || path->isUsageRegistered() || !m_pathUsage || !path->getFirstNode()) return;
adjustPathUsage(path->getFirstNode(), NULL, +1);
path->setUsageHead(path->getFirstNode());
+ reservePathTiming(path, obj);
}
void Pathfinder::unregisterPathUsage( const Path *path )
{
if (!path || !path->isUsageRegistered()) return;
adjustPathUsage(path->getUsageHead(), NULL, -1);
+ releaseReservations(path, path->getUsageHead(), NULL);
path->setUsageHead(NULL);
}
@@ -5721,9 +5781,152 @@ void Pathfinder::releasePathUsageBefore( const Path *path, const PathNode *node
while (n && n != node) n = n->getNext();
if (!n) return;
adjustPathUsage(path->getUsageHead(), node, -1);
+ releaseReservations(path, path->getUsageHead(), node);
path->setUsageHead(node);
}
+//-------------------------------------------------------------------------------------------------
+// Reservation map. Same cells as the congestion map, one entry each, plus the frame and heading.
+Int Pathfinder::reservationBucketOf( Int x, Int y )
+{
+ // two odd multipliers and a xor: cheap, and it scatters the neighbouring cells a search walks.
+ UnsignedInt hash = ((UnsignedInt)x * 73856093u) ^ ((UnsignedInt)y * 19349663u);
+ return (Int)(hash & (UnsignedInt)(PATH_RESERVATION_BUCKETS-1));
+}
+
+void Pathfinder::resetReservations( void )
+{
+ m_reservations.clear();
+ m_firstFreeReservation = -1;
+ for (Int i = 0; i < PATH_RESERVATION_BUCKETS; i++)
+ m_reservationBuckets[i] = -1;
+}
+
+/**
+ * Stamp an arrival frame and a heading onto every raw node of a freshly built path.
+ *
+ * The times come off the raw node list rather than the optimized one the unit actually drives:
+ * the two agree to within the corners the optimizer cuts, and the raw list is what the congestion
+ * map already stamps, so a claim and a usage count are put down and taken up together for the
+ * whole life of the path.
+ */
+void Pathfinder::reservePathTiming( const Path *path, const Object *obj )
+{
+ if (!obj || !obj->getAIUpdateInterface()) return;
+
+ const Locomotor *loco = obj->getAIUpdateInterface()->getCurLocomotor();
+ if (!loco) return;
+ Real speed = loco->getMaxSpeedForCondition(obj->getBodyModule()->getDamageState());
+ if (speed < 0.01f) return; // a unit that cannot move is never anywhere at a particular moment
+
+ UnsignedInt now = TheGameLogic->getFrame();
+ Real distance = 0.0f;
+ // the heading a cell is claimed on is the one the unit leaves it on, so the first node has a real
+ // direction (a unit sitting on a crossing is crossing it) and only the last node inherits.
+ Real headingX = 0.0f;
+ Real headingY = 0.0f;
+ for (const PathNode *node = path->getFirstNode(); node; node = node->getNext()) {
+ Real segment = 0.0f;
+ if (node->getNext()) {
+ Real dx = node->getNext()->getPosition()->x - node->getPosition()->x;
+ Real dy = node->getNext()->getPosition()->y - node->getPosition()->y;
+ segment = (Real)sqrt(dx*dx + dy*dy);
+ if (segment > 0.0f) {
+ headingX = dx/segment;
+ headingY = dy/segment;
+ }
+ }
+
+ ICoord2D cell;
+ if (!worldToCell(node->getPosition(), &cell)) { // worldToCell returns true when off map
+ /* One claim per path per cell, because that is what releaseReservations takes back. A
+ path that doubles back over a cell it already claimed would otherwise leave the second
+ claim behind for good, and a claim nobody can release makes that cell expensive to
+ everybody forever. */
+ Bool alreadyClaimed = false;
+ for (Int walk = m_reservationBuckets[reservationBucketOf(cell.x, cell.y)]; walk >= 0;
+ walk = m_reservations[walk].m_nextInBucket) {
+ if (m_reservations[walk].m_owner == path &&
+ m_reservations[walk].m_cell.x == cell.x && m_reservations[walk].m_cell.y == cell.y) {
+ alreadyClaimed = true;
+ break;
+ }
+ }
+ if (alreadyClaimed) {
+ distance += segment;
+ continue;
+ }
+
+ Int index = m_firstFreeReservation;
+ if (index >= 0) {
+ m_firstFreeReservation = m_reservations[index].m_nextInBucket;
+ } else {
+ index = (Int)m_reservations.size();
+ m_reservations.push_back(PathReservation());
+ }
+ PathReservation &reservation = m_reservations[index];
+ reservation.m_owner = path;
+ reservation.m_cell = cell;
+ reservation.m_frame = now + (UnsignedInt)(distance/speed);
+ reservation.m_headingX = headingX;
+ reservation.m_headingY = headingY;
+
+ Int bucket = reservationBucketOf(cell.x, cell.y);
+ reservation.m_nextInBucket = m_reservationBuckets[bucket];
+ m_reservationBuckets[bucket] = index;
+ }
+ distance += segment;
+ }
+}
+
+/**
+ * Drop this path's claims on the raw nodes [from, to) - the range adjustPathUsage just uncounted.
+ */
+void Pathfinder::releaseReservations( const Path *path, const PathNode *from, const PathNode *to )
+{
+ if (m_reservations.empty()) return;
+ for (const PathNode *node = from; node && node != to; node = node->getNext()) {
+ ICoord2D cell;
+ if (worldToCell(node->getPosition(), &cell)) continue; // off map, so nothing was claimed
+ Int bucket = reservationBucketOf(cell.x, cell.y);
+ Int prev = -1;
+ for (Int index = m_reservationBuckets[bucket]; index >= 0; ) {
+ PathReservation &reservation = m_reservations[index];
+ Int next = reservation.m_nextInBucket;
+ if (reservation.m_owner == path && reservation.m_cell.x == cell.x && reservation.m_cell.y == cell.y) {
+ if (prev < 0)
+ m_reservationBuckets[bucket] = next;
+ else
+ m_reservations[prev].m_nextInBucket = next;
+ reservation.m_owner = NULL;
+ reservation.m_nextInBucket = m_firstFreeReservation;
+ m_firstFreeReservation = index;
+ break; // one claim per path per cell
+ }
+ prev = index;
+ index = next;
+ }
+ }
+}
+
+/**
+ * How many other paths want this cell at about this frame, coming from a different direction.
+ */
+Int Pathfinder::countCrossingReservations( Int x, Int y, UnsignedInt frame, Real headingX, Real headingY ) const
+{
+ Int conflicts = 0;
+ for (Int index = m_reservationBuckets[reservationBucketOf(x, y)]; index >= 0;
+ index = m_reservations[index].m_nextInBucket) {
+ const PathReservation &reservation = m_reservations[index];
+ if (reservation.m_cell.x != x || reservation.m_cell.y != y)
+ continue; // another cell that hashed here
+ if (Pathfinder_reservationsClash(frame, headingX, headingY,
+ reservation.m_frame, reservation.m_headingX, reservation.m_headingY))
+ conflicts++;
+ }
+ return conflicts;
+}
+
/**
* Returns coordinates of goal.
*
@@ -6688,11 +6891,18 @@ Int Pathfinder::examineNeighboringCells(PathfindCell *parentCell, PathfindCell *
{
pfBump( PF_EXPAND );
Bool canPathThroughUnits = false;
+ // world units per frame, for turning a distance travelled into the frame we get there.
+ // Zero switches the crossing cost off for this search: without a speed there is no clock.
+ Real crossingSpeed = 0.0f;
if (obj && obj->getAIUpdateInterface()) {
canPathThroughUnits = obj->getAIUpdateInterface()->canPathThroughUnits();
// Our own current path must not repel us while we repath (the caller only destroys it
// once the new one is built). O(1) after the first neighbour expansion of a search.
unregisterPathUsage(obj->getAIUpdateInterface()->getPath());
+ // getCurLocomotor, not getCurLocomotorSpeed: the latter DEBUG_LOGs when there is none.
+ const Locomotor *loco = obj->getAIUpdateInterface()->getCurLocomotor();
+ if (loco)
+ crossingSpeed = loco->getMaxSpeedForCondition(obj->getBodyModule()->getDamageState());
}
Bool isCrusher = obj ? obj->getCrusherLevel() > 0 : false;
/* The straight-line-to-goal probe below walks every cell between this cell and the goal and
@@ -6863,8 +7073,9 @@ Int Pathfinder::examineNeighboringCells(PathfindCell *parentCell, PathfindCell *
if (!newCell->hasInfo()) {
if (!newCell->allocateInfo(newCellCoord)) {
// Out of cells for pathing...
+ DEBUG_LOG(("CONGEST probe: out of pathfind cells after %d cells\n", cellCount));
return cellCount;
- }
+ }
cellCount++;
}
@@ -6874,16 +7085,37 @@ Int Pathfinder::examineNeighboringCells(PathfindCell *parentCell, PathfindCell *
}
if (m_pathUsage && dx < PATH_CONGESTION_RANGE && dy < PATH_CONGESTION_RANGE) {
// Other units' live paths through our footprint: pay per path so we pick a parallel
- // lane. Only near the start (where lanes form) and capped: the heuristic does not
- // know about this cost, so an uncapped penalty along a long path inflates the
- // search toward a full flood - nine tanks sent across the map used to exhaust the
- // cell pool (no path) and hitch the frame.
+ // lane. Capped, because the heuristic does not know about this cost and an uncapped
+ // penalty inflates the search toward a full flood - nine tanks sent across the map
+ // used to exhaust the cell pool (no path) and hitch the frame. The group corridor
+ // already holds the group apart, so this cost only has to break the tie where lanes
+ // form: it stops thirty cells out, where the map has not started pinching yet.
Int usage = 0;
Int above = radius + (centerInCell ? 1 : 0);
for (Int ux = newCellCoord.x-radius; ux < newCellCoord.x+above; ux++)
for (Int uy = newCellCoord.y-radius; uy < newCellCoord.y+above; uy++)
usage += getPathUsage(ux, uy);
- newCostSoFar += Pathfinder_congestionPenalty( usage );
+ newCostSoFar += Pathfinder_congestionPenalty( usage, PATH_CONGESTION_COST );
+ }
+ //
+ // The same ground, with the clock on. m_pathUsage is the gate: the two maps stamp exactly
+ // the same cells, so a cell no live path runs through cannot hold a reservation and the
+ // hash is never touched for it - the probe below runs on the handful of cells where a
+ // crossing is even possible. Pinched cells are skipped because there is nowhere to dodge
+ // to in a doorway: charging one there does not spread anyone out, it sends them to the
+ // next doorway to queue at that one instead.
+ //
+ UnsignedInt newTravelSoFar = parentCell->getTravelSoFar() +
+ ((delta[i].x == 0 || delta[i].y == 0) ? COST_ORTHOGONAL : COST_DIAGONAL);
+ if (crossingSpeed > 0.01f && !newCell->getPinched() && getPathUsage(newCellCoord.x, newCellCoord.y) > 0) {
+ // travel is in cost units and a cell of cost is a cell of ground, so distance is
+ // newTravelSoFar cells worth of PATHFIND_CELL_SIZE / COST_ORTHOGONAL.
+ Real distance = newTravelSoFar * (PATHFIND_CELL_SIZE_F / (Real)COST_ORTHOGONAL);
+ UnsignedInt arrival = TheGameLogic->getFrame() + (UnsignedInt)(distance/crossingSpeed);
+ Real length = (delta[i].x == 0 || delta[i].y == 0) ? 1.0f : 1.414214f;
+ Int conflicts = countCrossingReservations( newCellCoord.x, newCellCoord.y, arrival,
+ delta[i].x/length, delta[i].y/length );
+ newCostSoFar += Pathfinder_crossingPenalty( conflicts );
}
if (newCell->getType() == PathfindCell::CELL_CLIFF && !newCell->getPinched() ) {
Coord3D fromPos;
@@ -6965,6 +7197,7 @@ Int Pathfinder::examineNeighboringCells(PathfindCell *parentCell, PathfindCell *
}
}
newCell->setCostSoFar(newCostSoFar);
+ newCell->setTravelSoFar(newTravelSoFar); // ground covered, with none of the penalties in it
// keep track of path we're building - point back to cell we moved here from
newCell->setParentCell(parentCell) ;
if (m_isTunneling) {
@@ -9794,7 +10027,7 @@ Path *Pathfinder::buildActualPath( const Object *obj, LocomotorSurfaceTypeMask a
// cleanup the path by checking line of sight
path->optimize(obj, acceptableSurfaces, blocked);
- registerPathUsage(path);
+ registerPathUsage(path, obj);
#if defined _DEBUG || defined _INTERNAL
if (TheGlobalData->m_debugAI==AI_DEBUG_PATHS)
@@ -11334,7 +11567,7 @@ Path *Pathfinder::patchPath( const Object *obj, const LocomotorSet& locomotorSet
// cleanup the path by checking line of sight
path->optimize(obj, locomotorSet.getValidSurfaces(), blocked);
- registerPathUsage(path);
+ registerPathUsage(path, obj);
cleanOpenAndClosedLists();
parentCell->releaseInfo();
candidateGoal->releaseInfo();
diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cpp
index 0f4ec98da..77a56659f 100644
--- a/GeneralsMD/Code/Tests/test_gameengine.cpp
+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp
@@ -51,6 +51,8 @@
#include "GameNetwork/CrcAgreement.h"
#include "GameLogic/GameLogic.h"
#include "Common/EarlyCommandLine.h"
+#include "Common/CommandLine.h"
+#include "Common/GlobalData.h"
#include "GameNetwork/NetworkUtil.h"
#include "Common/Recorder.h"
#include "Common/RadarShroudCache.h"
@@ -6230,31 +6232,84 @@ TEST(headless_run_ends_on_a_decision_or_on_the_frame_limit)
CHECK_STR( GameEngine_headlessRunResult( 3000, 2000, 3000 ), "decided" );
}
-extern Int Pathfinder_congestionPenalty( Int usage );
+extern Int Pathfinder_congestionPenalty( Int usage, Int costPerPath );
TEST(congestion_cost_is_charged_per_path_and_capped)
{
/* Another unit's live path through a cell we would step on costs us, so two units heading the
same way take parallel lanes instead of one queue. Empty ground stays free - a map with no
traffic on it has to path exactly as it always did. */
- CHECK_EQ( 0, Pathfinder_congestionPenalty( 0 ) );
- CHECK_EQ( 0, Pathfinder_congestionPenalty( -1 ) ); // usage is summed over a footprint that can leave the map
+ CHECK_EQ( 0, Pathfinder_congestionPenalty( 0, 5 ) );
+ CHECK_EQ( 0, Pathfinder_congestionPenalty( -1, 5 ) ); // usage is summed over a footprint that can leave the map
// one path through the footprint costs one unit of the cost, two cost two
- CHECK_EQ( 5, Pathfinder_congestionPenalty( 1 ) );
- CHECK_EQ( 10, Pathfinder_congestionPenalty( 2 ) );
+ CHECK_EQ( 5, Pathfinder_congestionPenalty( 1, 5 ) );
+ CHECK_EQ( 10, Pathfinder_congestionPenalty( 2, 5 ) );
/* and the cap is the point: the heuristic does not know about this cost, so an uncapped
penalty on a crowded cell inflates the search until it floods and the cell pool runs dry.
Four paths and forty pay the same as four. */
- CHECK_EQ( 20, Pathfinder_congestionPenalty( 4 ) );
- CHECK_EQ( 20, Pathfinder_congestionPenalty( 5 ) );
- CHECK_EQ( 20, Pathfinder_congestionPenalty( 255 ) ); // m_pathUsage is a byte: this is its ceiling
+ CHECK_EQ( 20, Pathfinder_congestionPenalty( 4, 5 ) );
+ CHECK_EQ( 20, Pathfinder_congestionPenalty( 5, 5 ) );
+ CHECK_EQ( 20, Pathfinder_congestionPenalty( 255, 5 ) ); // m_pathUsage is a byte: this is its ceiling
/* The whole penalty has to stay small against the step costs it is added to (10 orthogonal,
14 diagonal): a crowded cell may look worse than an empty one, never worse than a detour
around the map. */
- CHECK( Pathfinder_congestionPenalty( 255 ) <= 2*10 );
+ CHECK( Pathfinder_congestionPenalty( 255, 5 ) <= 2*10 );
+
+ /* The cost per path is a parameter because the cap has to move with it: whatever it is set to,
+ the ceiling stays four of them, which is the bound on how far a unit will go around. */
+ CHECK_EQ( 20, Pathfinder_congestionPenalty( 1, 20 ) );
+ CHECK_EQ( 80, Pathfinder_congestionPenalty( 4, 20 ) );
+ CHECK_EQ( 80, Pathfinder_congestionPenalty( 255, 20 ) );
+ CHECK( Pathfinder_congestionPenalty( 255, 20 ) <= 8*10 );
+}
+
+extern Int Pathfinder_crossingPenalty( Int conflicts );
+
+TEST(crossing_cost_is_charged_per_conflict_and_capped)
+{
+ /* The congestion map says somebody's path runs through this cell; the reservation map says
+ *when* they will be in it. A cell two units want at the same moment, going different ways,
+ is a crossing, and it costs - a cell two units want minutes apart costs nothing. */
+ CHECK_EQ( 0, Pathfinder_crossingPenalty( 0 ) );
+ CHECK_EQ( 0, Pathfinder_crossingPenalty( -1 ) );
+
+ // 60 per crossing: six orthogonal steps, i.e. worth going around a short way and no further
+ CHECK_EQ( 60, Pathfinder_crossingPenalty( 1 ) );
+ CHECK_EQ( 120, Pathfinder_crossingPenalty( 2 ) );
+
+ /* Capped at three for the same reason the congestion cost is capped: the heuristic cannot see
+ this cost, so an uncapped one on a busy junction floods the search. A junction thirty units
+ want at once is a junction, not a reason to walk around the map. */
+ CHECK_EQ( 180, Pathfinder_crossingPenalty( 3 ) );
+ CHECK_EQ( 180, Pathfinder_crossingPenalty( 4 ) );
+ CHECK_EQ( 180, Pathfinder_crossingPenalty( 1000 ) );
+}
+
+extern Bool Pathfinder_reservationsClash( UnsignedInt frameA, Real headingAX, Real headingAY,
+ UnsignedInt frameB, Real headingBX, Real headingBY );
+
+TEST(two_claims_on_a_cell_clash_only_at_the_same_moment_and_across_each_other)
+{
+ // head-on, same frame: the crossing this whole cost exists for
+ CHECK( Pathfinder_reservationsClash( 100, 1.0f, 0.0f, 100, -1.0f, 0.0f ) );
+ // at right angles, eleven frames apart - still inside the twelve-frame window
+ CHECK( Pathfinder_reservationsClash( 100, 1.0f, 0.0f, 111, 0.0f, 1.0f ) );
+
+ /* The window is how long a tank owns a ten-unit cell. Twelve frames apart is not the same
+ moment, in either order - and the frames are unsigned, so the older-first case must not
+ subtract its way into a huge positive number. */
+ CHECK( !Pathfinder_reservationsClash( 100, 1.0f, 0.0f, 112, 0.0f, 1.0f ) );
+ CHECK( !Pathfinder_reservationsClash( 112, 0.0f, 1.0f, 100, 1.0f, 0.0f ) );
+ CHECK( !Pathfinder_reservationsClash( 0, 1.0f, 0.0f, 5000, -1.0f, 0.0f ) );
+
+ /* Traffic going your way is a queue, not a crossing. Charging it prices hundreds of following
+ pairs per order and buys nothing: the unit behind you is where you are about to not be. */
+ CHECK( !Pathfinder_reservationsClash( 100, 1.0f, 0.0f, 100, 1.0f, 0.0f ) );
+ CHECK( !Pathfinder_reservationsClash( 100, 1.0f, 0.0f, 100, 0.707107f, 0.707107f ) ); // 45 deg
+ CHECK( Pathfinder_reservationsClash( 100, 1.0f, 0.0f, 100, 0.0f, 1.0f ) ); // 90 deg
}
TEST(a_replay_game_is_never_itself_recorded)
@@ -7563,3 +7618,41 @@ TEST(a_door_stays_open_while_another_unit_is_still_coming)
CHECK( !Production_shouldCloseDoorNow( 31, 30, true, false ) );
CHECK( !Production_shouldCloseDoorNow( 31, 30, true, true ) );
}
+
+TEST(borderless_asks_for_a_windowed_device_the_size_of_the_desktop)
+{
+ /* -borderless is borderless fullscreen. Half of it is the window itself, which WinMain creates
+ before the engine exists and which nothing here can reach; the other half is the back buffer,
+ and that half is this table's. Getting it wrong is not cosmetic: a back buffer that does not
+ match the window is presented as a stretched blit, and the cursor stops landing where it is
+ drawn. */
+ GlobalData *saved = TheWritableGlobalData;
+ GlobalData *scratch = NEW GlobalData;
+ TheWritableGlobalData = scratch;
+
+ scratch->m_windowed = FALSE;
+ scratch->m_xResolution = 640;
+ scratch->m_yResolution = 480;
+ scratch->m_edgeScrollInWindowedMode = FALSE;
+
+ char *argv[] = { "generals.exe", "-borderless" };
+ parseCommandLine( 2, argv );
+
+ CHECK( scratch->m_windowed );
+ CHECK_EQ( scratch->m_xResolution, GetSystemMetrics( SM_CXSCREEN ) );
+ CHECK_EQ( scratch->m_yResolution, GetSystemMetrics( SM_CYSCREEN ) );
+
+ /* and edge scrolling comes back on: retail refuses it in a window because the cursor can
+ legitimately sit on the border, and a window covering the display has no such border. */
+ CHECK( scratch->m_edgeScrollInWindowedMode );
+
+ /* -xres/-yres after it still win - that is how a smaller back buffer in a borderless window is
+ asked for, and it is the same rule -headless follows. */
+ char *argv2[] = { "generals.exe", "-borderless", "-xres", "1280", "-yres", "720" };
+ parseCommandLine( 6, argv2 );
+ CHECK_EQ( scratch->m_xResolution, 1280 );
+ CHECK_EQ( scratch->m_yResolution, 720 );
+
+ TheWritableGlobalData = saved;
+ delete scratch;
+}
diff --git a/Tools/PathLab/pathlab.py b/Tools/PathLab/pathlab.py
new file mode 100644
index 000000000..efeec6ebe
--- /dev/null
+++ b/Tools/PathLab/pathlab.py
@@ -0,0 +1,1461 @@
+"""
+PathLab - a sandbox for the group-movement work in GameEngine/Source/GameLogic/AI.
+
+The engine's pathfinder is a 10-unit grid, 8-way A*, cost 10 orthogonal / 14 diagonal, with a
+congestion map of other units' remaining paths. Group orders either take one shared corridor split
+into lanes (AIGroup::friend_computeGroundPath + friend_moveVehicleToPos) or fall back to one A* per
+unit. All of that is reproduced here at the same numbers, so a change can be looked at - with the
+line-of-sight rays every check actually makes drawn on screen - before it is written in C++.
+
+The congestion map has no clock in it, so it cannot tell a shared road from a crossing. On top of
+it there is a reservation map - *when* each unit expects to be in each cell - and a second cost paid
+only when two units want the same cell at the same moment. That is the expensive case: a road two
+columns use one after the other is fine, a junction they reach together is not.
+
+ python pathlab.py # corridor mode, the engine's default
+ python pathlab.py --mode single # -nogrouppath: one path per unit, congestion the whole way
+ python pathlab.py --map open # no chokepoint, to see lanes on open ground
+ python pathlab.py --headless 6 --scenario cross --map open --units 16 --sweep 20/4/0,20/4/60
+
+Two units are only counted as crossing when they want a cell at the same moment *and* are not
+going the same way - traffic following the same road is a queue, and a queue is what a road is
+for. Nor is it charged in a cell with no room to dodge: pricing a two-cell doorway does not
+spread anyone out, it sends them to queue at the next doorway instead.
+
+Controls
+ left click order the selection to a point
+ right drag select units (right click empty ground selects all)
+ 1 / 2 corridor mode / individual mode
+ c congestion cost on/off
+ t crossing cost on/off (the time dimension)
+ r draw the line-of-sight rays planning used
+ p draw the congestion map
+ space pause
+ n new map, same mode
+ tab re-issue the last order (replan with what is on the map now)
+ esc quit
+
+Red squares are cells two units still plan to be in within PATH_CROSSING_WINDOW frames of each
+other - the clashes the crossing cost is there to buy out.
+"""
+
+import argparse
+import heapq
+import itertools
+import math
+import random
+import sys
+from collections import Counter
+from collections.abc import Iterable, Sequence
+from contextlib import contextmanager
+from dataclasses import dataclass, field
+from enum import IntEnum
+from typing import NamedTuple
+import pygame
+
+Cell = tuple[int, int]
+Point = tuple[float, float]
+Heading = tuple[float, float]
+Ray = tuple[float, float, float, float, bool]
+Colour = tuple[int, int, int]
+Rect = tuple[float, float, float, float]
+
+# Engine constants: keep these equal to the C++ or the sandbox is measuring something else.
+CELL: float = 10.0 # PATHFIND_CELL_SIZE_F
+COST_ORTHOGONAL: int = 10
+COST_DIAGONAL: int = 14
+
+# AIPathfind.cpp charges 5 per path with a group corridor and 20 without one; the sandbox has no
+# corridor congestion at all, so 20 is the value it runs at. --cost overrides, --sweep compares.
+PATH_CONGESTION_COST: int = 20
+PATH_CONGESTION_RANGE_NO_GROUP: int = 10000
+PATH_CONGESTION_MAX_PATHS: int = 4 # cap, so a mob cannot make a cell infinitely expensive
+GROUP_PATH_DIAMETERS: tuple[int, ...] = (6, 4, 3) # what friend_computeGroundPath tries in order
+STRAIGHTEN_MAX_RUN: int = 16 # raycast simplify: points dropped in a row
+MAP_KINDS: tuple[str, ...] = ("choke", "open", "twogaps")
+MODES: tuple[str, ...] = ("corridor", "single")
+SCENARIOS: tuple[str, ...] = ("column", "cross")
+UNIT_RADIUS: float = 11.0 # a Crusader's bounding circle, near enough
+UNIT_SPEED: float = 2.4 # world units per logic frame
+
+# The congestion map above has no clock in it: a cell another unit will drive over in ten seconds
+# costs the same as one it is sitting in now. The reservation map does have a clock - it stores
+# *when* each unit expects to be in a cell, and charges only for an overlap in time. That is what
+# makes a crossing expensive without making a shared road expensive.
+PATH_CROSSING_COST: int = 60 # per conflicting reservation - six cells of detour
+PATH_CROSSING_WINDOW: int = 12 # frames either side of an arrival that still clash
+PATH_CROSSING_MAX: int = 3 # cap, same reason the congestion cost has one
+SAME_WAY: float = 0.6 # headings this aligned are a queue, not a crossing
+
+# Two points closer than this are the same point: a zero-length segment has no direction to take.
+EPSILON: float = 1e-3
+# Larger than any route this grid can produce, so it reads as "not reached yet" in the A* tables.
+UNREACHABLE_COST: int = 1 << 30
+DEFAULT_CELL_BUDGET: int = 60000 # the engine's "out of pathfind cells" ceiling
+SEED_RANGE: int = 1 << 30
+
+# Terrain
+MAP_WIDTH_CELLS: int = 96
+MAP_HEIGHT_CELLS: int = 72
+ROCK_RADIUS_CELLS: int = 2 # rocks are five cells across
+OPEN_MAP_ROCKS: int = 18
+OPEN_MAP_MARGIN: int = 8
+CHOKE_MAP_ROCKS: int = 10
+CHOKE_MAP_MARGIN: int = 6
+CHOKE_GAP_CELLS: int = 4 # narrower than three lanes of tanks
+SCATTER_KEEP_CLEAR_CELLS: int = 6 # a rock this near the wall column would seal its gap
+NARROW_GAP_HALF_CELLS: int = 2
+WIDE_GAP_ROWS: tuple[int, int] = (6, 13)
+RAYCAST_STEP: float = CELL * 0.5 # isLinePassable samples twice per cell
+ROOM_CLEARANCE: int = 1 # a clear ring one cell deep is "somewhere to dodge to"
+
+# Units and collision
+COLLISION_SLACK: float = 0.95 # units may touch this close before they count as one
+GOAL_SPACING_SLACK: float = 0.95
+GOAL_SEARCH_RINGS: int = 24
+YIELD_REACH: float = 1.3 # radii within which a parked unit is in the way
+FINAL_ARRIVE_RADII: float = 0.9 # the last waypoint is reached this loosely ...
+WAYPOINT_ARRIVE_RADII: float = 0.25 # ... and the ones on the way, this tightly
+PROGRESS_EPSILON_SPEEDS: float = 0.25 # closing by less than this is inching, not progress
+REPATH_AFTER_STUCK_FRAMES: int = 60
+PARK_RADII: float = 3.0 # jammed this near the goal counts as arrived ...
+PARK_RADII_AFTER_RETRIES: float = 6.0 # ... and the tolerance grows the longer it fails
+PARK_RETRY_LIMIT: int = 3
+# (turn in radians, fraction of full speed) tried in order: straight, crawl, then wider swerves
+SWERVE_ATTEMPTS: tuple[tuple[float, float], ...] = (
+ (0.0, 1.0), (0.0, 0.4), (0.6, 0.8), (-0.6, 0.8), (1.2, 0.6), (-1.2, 0.6))
+
+# Ordering
+LANES_MAX: int = 3
+LANES_MIN: int = 2
+LANES_MIN_UNITS: int = 5 # below this, three lanes are wider than the group
+LANE_GAP: float = 0.5 * CELL # slack between neighbouring lanes
+LANE_SHRINKS: tuple[float, ...] = (1.0, 0.5, 0.0) # full offset, half, then the corridor line
+INDIVIDUAL_OFFSET_RADII: float = 6.0 # computeIndividualDestination's cap on the spread
+SPAWN_ROW_WIDTH: int = 5
+SPAWN_STRIDE_CELLS: int = 3
+SPAWN_CELL: Cell = (6, 12) # the column scenario's single block
+CROSS_SPAWN_TOP: Cell = (6, 10) # the cross scenario's high block ...
+CROSS_SPAWN_BOTTOM_INSET: int = 16 # ... and the low one, this far up from the bottom
+GOAL_INSET_X: int = 8 # goals sit this far in from the right edge ...
+GOAL_INSET_Y: int = 12 # ... and this far from the top or bottom
+
+# Measurement and window
+MEASURE_MAX_FRAMES: int = 4000
+RENDER_FPS: int = 60
+HUD_HEIGHT: int = 96
+HUD_TOP_PAD: int = 4
+HUD_TEXT_X: int = 8
+HUD_LINE_HEIGHT: int = 18
+HUD_FONT_SIZE: int = 14
+HUD_NOTES_SHOWN: int = 2
+WAYPOINT_DOT: int = 2
+BLOCKED_RING_WIDTH: int = 1
+CROSSING_OUTLINE_WIDTH: int = 1
+TERRAIN_OVERDRAW: int = 1 # one pixel, so neighbouring wall cells do not seam
+MOUSE_LEFT: int = 1
+MOUSE_RIGHT: int = 3
+
+
+def frames_for_cost(cost: float) -> float:
+ """A* cost back to logic frames: 10 of cost is one cell, one cell is CELL/UNIT_SPEED frames."""
+ return (cost / float(COST_ORTHOGONAL)) * (CELL / UNIT_SPEED)
+
+
+def cell_of(x: float, y: float) -> Cell:
+ return int(x // CELL), int(y // CELL)
+
+
+def world_of(cx: int, cy: int) -> Point:
+ return (cx + 0.5) * CELL, (cy + 0.5) * CELL
+
+
+class Grid:
+ def __init__(self, width: int, height: int) -> None:
+ self.width = width
+ self.height = height
+ self.blocked = bytearray(width * height)
+ self._room: bytearray | None = None
+
+ def in_bounds(self, cx: int, cy: int) -> bool:
+ return 0 <= cx < self.width and 0 <= cy < self.height
+
+ def block(self, cx: int, cy: int) -> None:
+ self.blocked[cy * self.width + cx] = 1
+ self._room = None
+
+ def open_span(self, cx: int, first_row: int, last_row: int) -> None:
+ """Cut a two-cell-wide gap through a wall at column cx, rows first_row..last_row."""
+ for y in range(first_row, last_row + 1):
+ self.blocked[y * self.width + cx] = 0
+ self.blocked[y * self.width + cx + 1] = 0
+ self._room = None
+
+ def has_room(self, cx: int, cy: int) -> bool:
+ """True when the whole ring around this cell is clear - somewhere to dodge to. In a
+ two-cell doorway there is nowhere to go, so charging a crossing there does not spread
+ anyone out, it just sends them to the next doorway to queue at that one instead."""
+ if not self.in_bounds(cx, cy):
+ return False
+ if self._room is None:
+ self._room = bytearray(
+ 1 if self.clear_for(x, y, ROOM_CLEARANCE) else 0
+ for y in range(self.height) for x in range(self.width))
+ return bool(self._room[cy * self.width + cx])
+
+ def passable(self, cx: int, cy: int) -> bool:
+ return self.in_bounds(cx, cy) and not self.blocked[cy * self.width + cx]
+
+ def passable_world(self, x: float, y: float) -> bool:
+ return self.passable(*cell_of(x, y))
+
+ def clear_for(self, cx: int, cy: int, clearance: int) -> bool:
+ """Every cell within `clearance` of this one is passable - the engine's path diameter."""
+ return all(self.passable(x, y)
+ for x in range(cx - clearance, cx + clearance + 1)
+ for y in range(cy - clearance, cy + clearance + 1))
+
+ def line_passable(self, ax: float, ay: float, bx: float, by: float, *,
+ radius: float = 0.0) -> bool:
+ """Pathfinder::isLinePassable - walk the line, every cell on it has to be drivable."""
+ dx, dy = bx - ax, by - ay
+ distance = math.hypot(dx, dy)
+ if distance < EPSILON:
+ return self.passable_world(ax, ay)
+ steps = int(distance / RAYCAST_STEP) + 1
+ nx, ny = -dy / distance, dx / distance
+ for step in range(steps + 1):
+ fraction = step / steps
+ x, y = ax + dx * fraction, ay + dy * fraction
+ if not self.passable_world(x, y):
+ return False
+ if radius > 0.0 and not (self.passable_world(x + nx * radius, y + ny * radius)
+ and self.passable_world(x - nx * radius, y - ny * radius)):
+ return False
+ return True
+
+
+def scatter_blocks(grid: Grid, rng: random.Random, count: int, margin: int,
+ keep_clear_of: int | None = None) -> None:
+ """`count` five-by-five rocks at random, never within `margin` of the edge and never straddling
+ the column a map wants left open."""
+ for _ in range(count):
+ cx = rng.randrange(margin, grid.width - margin)
+ cy = rng.randrange(margin, grid.height - margin)
+ if keep_clear_of is not None and abs(cx - keep_clear_of) < SCATTER_KEEP_CLEAR_CELLS:
+ continue
+ for x in range(cx - ROCK_RADIUS_CELLS, cx + ROCK_RADIUS_CELLS + 1):
+ for y in range(cy - ROCK_RADIUS_CELLS, cy + ROCK_RADIUS_CELLS + 1):
+ grid.block(x, y)
+
+
+def make_map(kind: str, width: int = MAP_WIDTH_CELLS, height: int = MAP_HEIGHT_CELLS,
+ seed: int | None = None) -> Grid:
+ rng = random.Random(seed)
+ grid = Grid(width, height)
+ for x in range(width):
+ grid.block(x, 0)
+ grid.block(x, height - 1)
+ for y in range(height):
+ grid.block(0, y)
+ grid.block(width - 1, y)
+ if kind == "open":
+ scatter_blocks(grid, rng, OPEN_MAP_ROCKS, OPEN_MAP_MARGIN)
+ return grid
+ if kind == "choke":
+ # one wall across the middle with a gap the group cannot cross abreast
+ wall = width // 2
+ gap_y = height // 2
+ for y in range(1, height - 1):
+ if abs(y - gap_y) * 2 > CHOKE_GAP_CELLS:
+ grid.block(wall, y)
+ grid.block(wall + 1, y)
+ scatter_blocks(grid, rng, CHOKE_MAP_ROCKS, CHOKE_MAP_MARGIN, keep_clear_of=wall)
+ return grid
+ if kind == "twogaps":
+ # the case the whole exercise is about: a cheap narrow way and a wider way round
+ wall = width // 2
+ for y in range(1, height - 1):
+ grid.block(wall, y)
+ grid.block(wall + 1, y)
+ grid.open_span(wall, height // 2 - NARROW_GAP_HALF_CELLS,
+ height // 2 + NARROW_GAP_HALF_CELLS)
+ grid.open_span(wall, *WIDE_GAP_ROWS)
+ return grid
+ raise ValueError(f"unknown map kind {kind!r}, expected one of {', '.join(MAP_KINDS)}")
+
+
+class UsageMap:
+ """Cells covered by units' *remaining* paths. A unit releases what it has driven past.
+ Pathfinder::registerPathUsage / releasePathUsageBefore."""
+
+ def __init__(self) -> None:
+ self.count: dict[Cell, int] = {}
+ self.owner: dict[int, list[Cell]] = {}
+
+ def register(self, owner: int, cells: Sequence[Cell]) -> None:
+ self.unregister(owner)
+ self.owner[owner] = list(cells)
+ for cell in cells:
+ self.count[cell] = self.count.get(cell, 0) + 1
+
+ def _drop_cells(self, cells: Iterable[Cell]) -> None:
+ """Every cell here was counted by register, so the count is there to be decremented."""
+ for cell in cells:
+ remaining = self.count[cell] - 1
+ if remaining <= 0:
+ del self.count[cell]
+ else:
+ self.count[cell] = remaining
+
+ def unregister(self, owner: int) -> None:
+ self._drop_cells(self.owner.get(owner, ()))
+ # the key stays, empty: a unit whose repath failed still gets released as it drives on
+ self.owner[owner] = []
+
+ def release_before(self, owner: int, index: int) -> None:
+ cells = self.owner[owner]
+ self._drop_cells(cells[:index])
+ self.owner[owner] = cells[index:]
+
+ def count_paths_on(self, cell: Cell, exclude_owner: int | None = None) -> int:
+ paths = self.count.get(cell, 0)
+ if paths and exclude_owner is not None and cell in self.owner.get(exclude_owner, ()):
+ paths -= 1
+ return paths
+
+
+def price_congestion(paths: int) -> int:
+ """One orthogonal step costs 10, so a cost of 5 buys at most half a cell of detour per cell -
+ which is why the default barely bends a path. This is the knob to turn."""
+ if paths <= 0:
+ return 0
+ return min(paths, PATH_CONGESTION_MAX_PATHS) * PATH_CONGESTION_COST
+
+
+def count_path_overlap(units: Sequence["Unit"]) -> int:
+ """Cells claimed by more than one unit at plan time - 'ayni yerde ayni anda', counted."""
+ claims = Counter(cell for unit in units for cell in unit.cells)
+ return sum(claimants - 1 for claimants in claims.values() if claimants > 1)
+
+
+class Reservation(NamedTuple):
+ """One unit's claim on one cell: when it expects to be there, and which way it is going."""
+ arrival: float
+ owner: int
+ hx: float
+ hy: float
+
+
+class ReservationTrack(NamedTuple):
+ """The cells one drive line passes through, in order, with an arrival and a heading each."""
+ cells: list[Cell]
+ times: list[float]
+ headings: list[Heading]
+
+
+class ReservationMap:
+ """When each unit expects to be where, and going which way.
+
+ The congestion map answers 'is this ground spoken for'; this one answers 'will we be on it
+ at the same moment'. Two units driving the same road nose to tail never clash here, because
+ their arrival times at each cell are far apart - which is right, that road is fine. Two
+ units whose routes cross do clash, in exactly the one or two cells where they cross, and
+ that is where the cost has to land.
+
+ The heading is why it stores more than a time. Units nose to tail on the same road at the
+ same moment are a queue, and a queue is what a road is for; the expensive case is two of
+ them arriving from different directions. Only the second is charged for."""
+
+ def __init__(self) -> None:
+ self.at: dict[Cell, list[Reservation]] = {}
+ self.owner: dict[int, list[tuple[Cell, Reservation]]] = {}
+
+ def reserve(self, owner: int, cells: Sequence[Cell], times: Sequence[float],
+ headings: Sequence[Heading]) -> None:
+ self.release(owner)
+ entries = [(cell, Reservation(arrival, owner, hx, hy))
+ for cell, arrival, (hx, hy) in zip(cells, times, headings)]
+ self.owner[owner] = entries
+ for cell, reservation in entries:
+ self.at.setdefault(cell, []).append(reservation)
+
+ def _drop(self, cell: Cell, reservation: Reservation) -> None:
+ """`reserve` put this entry in this cell's slot and nothing else removes it, so both are
+ there to be found - a miss is a book-keeping bug, not a case to absorb."""
+ slot = self.at[cell]
+ slot.remove(reservation)
+ if not slot:
+ del self.at[cell]
+
+ def release(self, owner: int) -> None:
+ for cell, reservation in self.owner.get(owner, ()):
+ self._drop(cell, reservation)
+ # the key stays, empty: a unit whose repath failed still gets released as it drives on
+ self.owner[owner] = []
+
+ def release_before(self, owner: int, now: float) -> None:
+ """Drop what is already in the past - a unit cannot collide with where it has been."""
+ keep: list[tuple[Cell, Reservation]] = []
+ for cell, reservation in self.owner[owner]:
+ if reservation.arrival >= now:
+ keep.append((cell, reservation))
+ else:
+ self._drop(cell, reservation)
+ self.owner[owner] = keep
+
+ def count_conflicts(self, cell: Cell, when: float, exclude_owner: int | None = None,
+ heading: Heading | None = None) -> int:
+ conflicts = 0
+ for other in self.at.get(cell, ()):
+ if other.owner == exclude_owner:
+ continue
+ if abs(other.arrival - when) >= PATH_CROSSING_WINDOW:
+ continue
+ if heading is not None and heading[0] * other.hx + heading[1] * other.hy > SAME_WAY:
+ continue # following, not crossing - that is just a queue
+ conflicts += 1
+ return conflicts
+
+
+def price_crossing(conflicts: int) -> int:
+ if conflicts <= 0:
+ return 0
+ return min(conflicts, PATH_CROSSING_MAX) * PATH_CROSSING_COST
+
+
+def find_crossing_cells(reservations: ReservationMap) -> dict[Cell, int]:
+ """cell -> how many pairs of units still plan to be in it inside the clash window. Drawn on
+ screen and counted in the headless table; both want the same answer."""
+ crossings: dict[Cell, int] = {}
+ for cell, slot in reservations.at.items():
+ # same way at the same time is a queue, not a clash
+ pairs = sum(1 for first, second in itertools.combinations(slot, 2)
+ if abs(first.arrival - second.arrival) < PATH_CROSSING_WINDOW
+ and first.hx * second.hx + first.hy * second.hy <= SAME_WAY)
+ if pairs:
+ crossings[cell] = pairs
+ return crossings
+
+
+def count_planned_crossings(reservations: ReservationMap) -> int:
+ return sum(find_crossing_cells(reservations).values())
+
+
+@dataclass
+class PathPricing:
+ """What a search pays for beyond distance. A default-constructed one prices nothing, which is
+ the plain shortest path - so a search that is not meant to pay passes no pricing at all
+ rather than five separate arguments saying so."""
+ # an empty usage map, not None: `congestion_range` is the switch, and a range of 0 never reads it
+ usage: UsageMap = field(default_factory=UsageMap)
+ congestion_range: int = 0
+ owner: int | None = None
+ reservations: ReservationMap | None = None
+ start_frame: float = 0.0
+
+
+NO_PRICING = PathPricing()
+
+
+@dataclass
+class TrafficModel:
+ """The two shared maps a group order plans against, and which of their costs it is charged.
+
+ The switches live next to the maps because they are always chosen together - turning one
+ cost off is the A/B this sandbox exists to run, and carrying them as two loose booleans put
+ a bare `True, False` at every call site instead."""
+ usage: UsageMap
+ reservations: ReservationMap
+ is_congestion_charged: bool = True
+ is_crossing_charged: bool = True
+
+ @property
+ def congestion_range(self) -> int:
+ return PATH_CONGESTION_RANGE_NO_GROUP if self.is_congestion_charged else 0
+
+ @property
+ def priced_reservations(self) -> ReservationMap | None:
+ return self.reservations if self.is_crossing_charged else None
+
+ def release(self, owner: int) -> None:
+ """Take one unit's old plan off both maps, so its own claims cannot price its next one."""
+ self.usage.unregister(owner)
+ self.reservations.release(owner)
+
+ def pricing_for(self, owner: int, now: float) -> PathPricing:
+ """What one unit's own search pays: everyone else's ground, and everyone else's moment."""
+ return PathPricing(usage=self.usage, congestion_range=self.congestion_range, owner=owner,
+ reservations=self.priced_reservations, start_frame=now)
+
+ def corridor_pricing(self, now: float) -> PathPricing:
+ """The group corridor is one search for the whole group, so it pays no congestion - its own
+ units are the congestion. It still dodges other groups' moments."""
+ return PathPricing(reservations=self.priced_reservations, start_frame=now)
+
+
+# Pathfinder::findPath, near enough for the question being asked.
+NEIGHBOURS: tuple[tuple[int, int, int], ...] = (
+ (1, 0, COST_ORTHOGONAL), (-1, 0, COST_ORTHOGONAL),
+ (0, 1, COST_ORTHOGONAL), (0, -1, COST_ORTHOGONAL),
+ (1, 1, COST_DIAGONAL), (1, -1, COST_DIAGONAL),
+ (-1, 1, COST_DIAGONAL), (-1, -1, COST_DIAGONAL))
+
+# a step's length in cells, keyed by its cost, to turn (dx, dy) into a unit heading
+STEP_LEN: dict[int, float] = {COST_ORTHOGONAL: 1.0, COST_DIAGONAL: math.sqrt(2.0)}
+
+
+def heuristic(start: Cell, goal: Cell) -> int:
+ dx, dy = abs(start[0] - goal[0]), abs(start[1] - goal[1])
+ shorter, longer = (dx, dy) if dx < dy else (dy, dx)
+ return COST_DIAGONAL * shorter + COST_ORTHOGONAL * (longer - shorter)
+
+
+def astar(grid: Grid, start: Cell, goal: Cell, *, clearance: int = 0,
+ pricing: PathPricing = NO_PRICING,
+ cell_budget: int = DEFAULT_CELL_BUDGET) -> tuple[list[Cell], int]:
+ """Returns (cells, expansions). cells is [] when there is no path, or the budget ran out -
+ which is the engine's 'out of pathfind cells', the failure congestion cost can cause.
+
+ `travelled` is the cost without any penalty in it - the penalties are money, not distance,
+ and a detour taken to dodge someone must not also make us think we arrive later than we
+ do."""
+ if not grid.passable(*goal) or not grid.passable(*start):
+ return [], 0
+ open_heap: list[tuple[int, int, int, Cell]] = [(heuristic(start, goal), 0, 0, start)]
+ came_from: dict[Cell, Cell | None] = {start: None}
+ best_cost: dict[Cell, int] = {start: 0}
+ expansions = 0
+ while open_heap:
+ _, cost, travelled, current = heapq.heappop(open_heap)
+ if cost > best_cost.get(current, UNREACHABLE_COST):
+ continue
+ if current == goal:
+ path: list[Cell] = []
+ step: Cell | None = current
+ while step is not None:
+ path.append(step)
+ step = came_from[step]
+ path.reverse()
+ return path, expansions
+ expansions += 1
+ if expansions > cell_budget:
+ return [], expansions
+ for dx, dy, step_cost in NEIGHBOURS:
+ neighbour = (current[0] + dx, current[1] + dy)
+ if clearance:
+ if not grid.clear_for(neighbour[0], neighbour[1], clearance):
+ continue
+ elif not grid.passable(*neighbour):
+ continue
+ new_cost = cost + step_cost
+ new_travel = travelled + step_cost
+ if pricing.congestion_range:
+ if (abs(neighbour[0] - start[0]) < pricing.congestion_range
+ and abs(neighbour[1] - start[1]) < pricing.congestion_range):
+ new_cost += price_congestion(
+ pricing.usage.count_paths_on(neighbour, pricing.owner))
+ if pricing.reservations is not None and grid.has_room(*neighbour):
+ when = pricing.start_frame + frames_for_cost(new_travel)
+ heading = (dx / STEP_LEN[step_cost], dy / STEP_LEN[step_cost])
+ new_cost += price_crossing(pricing.reservations.count_conflicts(
+ neighbour, when, pricing.owner, heading))
+ if new_cost < best_cost.get(neighbour, UNREACHABLE_COST):
+ best_cost[neighbour] = new_cost
+ came_from[neighbour] = current
+ heapq.heappush(open_heap,
+ (new_cost + heuristic(neighbour, goal), new_cost, new_travel,
+ neighbour))
+ return [], expansions
+
+
+def track_reservations(start: Point, points: Sequence[Point],
+ start_frame: float = 0.0) -> ReservationTrack:
+ """The cells a unit driving these waypoints passes through, the frame it reaches each, and the
+ direction it is going when it does.
+
+ It walks the actual drive line rather than the A* cell list: after straightening, the
+ waypoints are far apart and the cells between them are exactly the ground nobody would
+ otherwise know is claimed. Corridor lanes have no cell list at all."""
+ cells: list[Cell] = []
+ times: list[float] = []
+ headings: list[Heading] = []
+ arrival = start_frame
+ px, py = start
+ last: Cell | None = None
+ for qx, qy in points:
+ length = math.hypot(qx - px, qy - py)
+ heading = ((qx - px) / length, (qy - py) / length) if length > EPSILON else (0.0, 0.0)
+ steps = max(1, int(length / RAYCAST_STEP))
+ for step in range(1, steps + 1):
+ fraction = step / float(steps)
+ cell = cell_of(px + (qx - px) * fraction, py + (qy - py) * fraction)
+ if cell != last:
+ cells.append(cell)
+ times.append(arrival + length * fraction / UNIT_SPEED)
+ headings.append(heading)
+ last = cell
+ arrival += length / UNIT_SPEED
+ px, py = qx, qy
+ return ReservationTrack(cells, times, headings)
+
+
+@dataclass
+class Unit:
+ # the id comes from whoever spawned the group: the usage and reservation maps are keyed by it,
+ # so two groups spawned separately must not both start counting from zero
+ x: float
+ y: float
+ id: int
+ radius: float = UNIT_RADIUS
+ path: list[Point] = field(default_factory=list) # world-space waypoints
+ index: int = 0
+ is_selected: bool = False
+ blocked_frames: int = 0 # had to slow, swerve or stop for another unit
+ stuck_run: int = 0 # consecutive frames going nowhere -> repath
+ last_dist: float | None = None # distance to the current waypoint, to notice inching
+ repaths: int = 0
+ goal: Point | None = None # where this unit was actually sent, after the spread
+ rays: list[Ray] = field(default_factory=list) # what planning actually checked
+ cells: list[Cell] = field(default_factory=list) # cells its path claims, for congestion
+
+ @property
+ def pos(self) -> Point:
+ return self.x, self.y
+
+ @property
+ def has_arrived(self) -> bool:
+ return self.index >= len(self.path)
+
+
+def is_occupied(units: Sequence[Unit], mover: Unit, nx: float, ny: float, *,
+ slack: float = COLLISION_SLACK) -> bool:
+ """Two units cannot share a spot. PhysicsUpdate's collision, minus the mass."""
+ return any(other is not mover
+ and math.hypot(other.x - nx, other.y - ny) < (mover.radius + other.radius) * slack
+ for other in units)
+
+
+def resolve_overlaps(units: Sequence[Unit], grid: Grid) -> None:
+ """The engine shoves overlapping units apart rather than stopping them dead; without this the
+ sandbox deadlocks at every chokepoint and measures the sandbox, not the pathing."""
+ for index, first in enumerate(units):
+ for second in units[index + 1:]:
+ dx, dy = second.x - first.x, second.y - first.y
+ distance = math.hypot(dx, dy)
+ overlap = (first.radius + second.radius) - distance
+ if overlap <= 0.0:
+ continue
+ if distance < EPSILON:
+ dx, dy, distance = 1.0, 0.0, 1.0
+ push = overlap * 0.5
+ ux, uy = dx / distance * push, dy / distance * push
+ if grid.passable_world(first.x - ux, first.y - uy):
+ first.x -= ux
+ first.y -= uy
+ if grid.passable_world(second.x + ux, second.y + uy):
+ second.x += ux
+ second.y += uy
+
+
+def yield_for(units: Sequence[Unit], grid: Grid, mover: Unit, hx: float, hy: float) -> None:
+ """A unit that has arrived is parked, not welded down: when someone still driving cannot get
+ past it, it steps aside. The engine does this too, and without it a tank that has finished
+ its order can wedge one that has not for the rest of the run."""
+ for other in units:
+ if other is mover or not other.has_arrived:
+ continue
+ ox, oy = other.x - mover.x, other.y - mover.y
+ if math.hypot(ox, oy) > (mover.radius + other.radius) * YIELD_REACH:
+ continue
+ if ox * hx + oy * hy <= 0: # behind us, not in the way
+ continue
+ for sx, sy in ((-hy, hx), (hy, -hx), (hx, hy)):
+ nx, ny = other.x + sx * UNIT_SPEED, other.y + sy * UNIT_SPEED
+ if grid.passable_world(nx, ny) and not is_occupied(units, other, nx, ny):
+ other.x, other.y = nx, ny
+ return
+
+
+def step_units(units: Sequence[Unit], grid: Grid, *, traffic: TrafficModel, now: float) -> None:
+ for unit in units:
+ if unit.has_arrived:
+ continue
+ tx, ty = unit.path[unit.index]
+ dx, dy = tx - unit.x, ty - unit.y
+ distance = math.hypot(dx, dy)
+ is_final = unit.index == len(unit.path) - 1
+ # a unit shoved sideways every frame still "moves", and counting only frames where it did
+ # not move at all misses it entirely - it inches around the goal for the rest of the run
+ is_closing = (unit.last_dist is None
+ or distance < unit.last_dist - UNIT_SPEED * PROGRESS_EPSILON_SPEEDS)
+ unit.last_dist = distance
+ arrive_radii = FINAL_ARRIVE_RADII if is_final else WAYPOINT_ARRIVE_RADII
+ if distance < UNIT_SPEED + unit.radius * arrive_radii:
+ unit.index += 1
+ unit.last_dist = None
+ # everything behind us stops costing other units anything
+ if unit.cells:
+ done = min(len(unit.cells) - 1,
+ int(unit.index * len(unit.cells) / len(unit.path)))
+ traffic.usage.release_before(unit.id, done)
+ traffic.reservations.release_before(unit.id, now)
+ continue
+ # slow down behind whoever is in front, and only sidestep if that is not enough
+ has_moved = False
+ for angle, speed in SWERVE_ATTEMPTS:
+ cos_angle, sin_angle = math.cos(angle), math.sin(angle)
+ rx, ry = dx * cos_angle - dy * sin_angle, dx * sin_angle + dy * cos_angle
+ turned_length = math.hypot(rx, ry)
+ nx = unit.x + rx / turned_length * UNIT_SPEED * speed
+ ny = unit.y + ry / turned_length * UNIT_SPEED * speed
+ if grid.passable_world(nx, ny) and not is_occupied(units, unit, nx, ny):
+ unit.x, unit.y = nx, ny
+ has_moved = True
+ unit.stuck_run = 0 if is_closing else unit.stuck_run + 1
+ if angle or speed < 1.0:
+ unit.blocked_frames += 1
+ break
+ if not has_moved:
+ unit.blocked_frames += 1
+ unit.stuck_run += 1
+ yield_for(units, grid, unit, dx / distance, dy / distance)
+ resolve_overlaps(units, grid)
+
+
+def apply_path(unit: Unit, points: list[Point], cells: list[Cell], traffic: TrafficModel,
+ now: float) -> None:
+ """Give a unit a freshly planned path and tell both shared maps about it. Every planner ends
+ this way, and they must end it the same way or a unit drives ground it never claimed."""
+ unit.path = points
+ unit.index = 0
+ unit.cells = cells
+ traffic.usage.register(unit.id, cells)
+ traffic.reservations.reserve(unit.id, *track_reservations(unit.pos, points, now))
+
+
+def repath_stuck(grid: Grid, units: Sequence[Unit], *, traffic: TrafficModel, now: float) -> None:
+ """AIInternalMoveToState gives up and asks the pathfinder again when a unit stops making
+ progress. Without it one wedged tank owns the whole measurement."""
+ for unit in units:
+ if unit.has_arrived or unit.stuck_run < REPATH_AFTER_STUCK_FRAMES or unit.goal is None:
+ continue
+ traffic.release(unit.id)
+ # jammed in the destination cluster: the engine parks rather than shuffling for ever, and
+ # the tolerance grows the longer it fails. Without this one such unit is the whole run.
+ park_radii = PARK_RADII if unit.repaths < PARK_RETRY_LIMIT else PARK_RADII_AFTER_RETRIES
+ if math.hypot(unit.x - unit.goal[0], unit.y - unit.goal[1]) < park_radii * unit.radius:
+ unit.index = len(unit.path)
+ unit.stuck_run = 0
+ continue
+ cells, _ = astar(grid, cell_of(unit.x, unit.y), cell_of(*unit.goal),
+ pricing=traffic.pricing_for(unit.id, now))
+ unit.stuck_run = 0
+ unit.repaths += 1
+ if not cells:
+ continue
+ points = [world_of(*cell) for cell in cells[1:]] or [unit.goal]
+ points[-1] = unit.goal
+ points, unit.rays = simplify_raycast(grid, unit.pos, points, radius=unit.radius,
+ lane_spacing=2.0 * unit.radius)
+ apply_path(unit, points, cells, traffic, now)
+
+
+def compute_centroid(units: Sequence[Unit]) -> Point:
+ return (sum(unit.x for unit in units) / len(units),
+ sum(unit.y for unit in units) / len(units))
+
+
+def reserve_goal(grid: Grid, taken: set[Point], gx: float, gy: float, *, radius: float) -> Point:
+ """Pathfinder::adjustDestination - spiral out from the clicked point to a goal spot no one else
+ has claimed. Reserving a *cell* is not enough: a cell is 10 units and a tank is 22 across,
+ so neighbouring cells still overlap and the group shoves itself for ever on arrival."""
+ start = cell_of(gx, gy)
+ spacing = 2.0 * radius * GOAL_SPACING_SLACK
+ for ring in range(GOAL_SEARCH_RINGS):
+ for cx in range(start[0] - ring, start[0] + ring + 1):
+ for cy in range(start[1] - ring, start[1] + ring + 1):
+ if ring and abs(cx - start[0]) != ring and abs(cy - start[1]) != ring:
+ continue
+ if not grid.passable(cx, cy):
+ continue
+ wx, wy = world_of(cx, cy)
+ if any(math.hypot(wx - tx, wy - ty) < spacing for tx, ty in taken):
+ continue
+ if not grid.line_passable(wx, wy, wx, wy, radius=radius):
+ continue
+ taken.add((wx, wy))
+ return wx, wy
+ return gx, gy
+
+
+def simplify_raycast(grid: Grid, start: Point, points: list[Point], *, radius: float,
+ lane_spacing: float) -> tuple[list[Point], list[Ray]]:
+ """AIGroup's straightening: drop a point when the line past it is one this unit can drive.
+
+ Returns (points, rays). Every check made is recorded as a ray, which is the whole reason
+ this file exists - handed back rather than appended to the unit, so a caller that wants the
+ straightened line without redrawing the screen can have it."""
+ if len(points) < 2:
+ return points, []
+ simplified: list[Point] = []
+ rays: list[Ray] = []
+ anchor = start
+ pending = points[0]
+ run = 0
+ for point in points[1:]:
+ deviation = point_line_distance(anchor, point, pending)
+ can_drop = False
+ if deviation < lane_spacing and run < STRAIGHTEN_MAX_RUN:
+ # even a deviation under half a cell is worth the ray: the unit is 22 wide, so a
+ # shortcut that looks straight can still put its flank through a rock.
+ is_clear = grid.line_passable(anchor[0], anchor[1], point[0], point[1], radius=radius)
+ rays.append((anchor[0], anchor[1], point[0], point[1], is_clear))
+ can_drop = is_clear
+ if can_drop and run < STRAIGHTEN_MAX_RUN:
+ pending = point
+ run += 1
+ else:
+ simplified.append(pending)
+ anchor = pending
+ pending = point
+ run = 0
+ simplified.append(pending)
+ return simplified, rays
+
+
+def point_line_distance(start: Point, end: Point, point: Point) -> float:
+ dx, dy = end[0] - start[0], end[1] - start[1]
+ if dx * dx + dy * dy < 1.0:
+ return math.hypot(point[0] - start[0], point[1] - start[1])
+ cross = (point[0] - start[0]) * dy - (point[1] - start[1]) * dx
+ return abs(cross) / math.hypot(dx, dy)
+
+
+@dataclass
+class OrderStats:
+ """What one order reports about itself. Both the window and the headless runner start here, so
+ a column added for one of them shows up in the other."""
+ expansions: int = 0
+ searches: int = 0
+ avg_waypoints: float = 0.0
+ corridor: list[Point] = field(default_factory=list)
+ diameter: int = 0
+ crossings: int = 0
+ notes: list[str] = field(default_factory=list)
+
+
+def summarise_order(stats: OrderStats, units: Sequence[Unit], traffic: TrafficModel) -> None:
+ """Both planners finish the same way, and a column counted for one has to be counted for the
+ other or the two halves of the comparison are not measuring the same thing."""
+ stats.avg_waypoints = sum(len(unit.path) for unit in units) / len(units)
+ stats.crossings = count_planned_crossings(traffic.reservations)
+
+
+def order_corridor(grid: Grid, units: Sequence[Unit], goal: Point, *, traffic: TrafficModel,
+ stats: OrderStats, now: float) -> None:
+ """AIGroup::friend_computeGroundPath + friend_moveVehicleToPos."""
+ cx, cy = compute_centroid(units)
+ start_cell = cell_of(cx, cy)
+ goal_cell = cell_of(*goal)
+ # this group is about to be re-planned, so its own old reservations must not price the corridor
+ for unit in units:
+ traffic.reservations.release(unit.id)
+ corridor: list[Cell] = []
+ diameter = 0
+ for candidate in GROUP_PATH_DIAMETERS:
+ corridor, expansions = astar(grid, start_cell, goal_cell, clearance=candidate // 2,
+ pricing=traffic.corridor_pricing(now))
+ stats.expansions += expansions
+ stats.searches += 1
+ if corridor:
+ diameter = candidate
+ break
+ if not corridor:
+ stats.notes.append("no corridor at any width - falling back to individual paths")
+ order_individual(grid, units, goal, traffic=traffic, stats=stats, now=now)
+ return
+ stats.corridor = [world_of(*cell) for cell in corridor]
+ stats.diameter = diameter
+ if start_cell == goal_cell:
+ # ordered onto the group's own centre: there is no corridor to lay lanes along
+ stats.notes.append("goal is the group's own cell - nothing to move to")
+ return
+ # heading of the corridor, and the normal the lanes are laid out along
+ sx, sy = world_of(*corridor[0])
+ ex, ey = world_of(*corridor[-1])
+ hx, hy = ex - sx, ey - sy
+ hlen = math.hypot(hx, hy)
+ hx, hy = hx / hlen, hy / hlen
+ nx, ny = -hy, hx
+ lane_spacing = 2.0 * max(unit.radius for unit in units) + LANE_GAP
+ ordered = sorted(units, key=lambda unit: (unit.x - cx) * nx + (unit.y - cy) * ny)
+ lanes = LANES_MAX if len(ordered) >= LANES_MIN_UNITS else LANES_MIN
+ per_lane = (len(ordered) + lanes - 1) // lanes
+ corridor_world = [world_of(*cell) for cell in corridor]
+ taken: set[Point] = set()
+ for index, unit in enumerate(ordered):
+ lane_index = min(lanes - 1, index // per_lane)
+ delta = lane_index - (lanes - 1) / 2.0
+ if lanes == LANES_MIN:
+ delta *= 2.0 # -1, +1 rather than -0.5, +0.5
+ unit.rays = []
+ points: list[Point] = []
+ for wx, wy in corridor_world[1:]:
+ lateral = lane_spacing * delta
+ placed = (wx, wy)
+ for shrink in LANE_SHRINKS:
+ px, py = wx + lateral * shrink * nx, wy + lateral * shrink * ny
+ if shrink == 0.0:
+ placed = (px, py)
+ break
+ is_clear = (grid.passable_world(px, py)
+ and grid.passable_world(px + nx * unit.radius, py + ny * unit.radius)
+ and grid.passable_world(px - nx * unit.radius, py - ny * unit.radius))
+ unit.rays.append((px + nx * unit.radius, py + ny * unit.radius,
+ px - nx * unit.radius, py - ny * unit.radius, is_clear))
+ if is_clear:
+ placed = (px, py)
+ break
+ points.append(placed)
+ gx, gy = reserve_goal(grid, taken, goal[0] + lane_spacing * delta * nx,
+ goal[1] + lane_spacing * delta * ny, radius=unit.radius)
+ points.append((gx, gy))
+ unit.goal = (gx, gy)
+ # lanes are parallel, so they clash with each other almost nowhere - which is the
+ # corridor's whole point, and worth being able to see next to individual mode
+ points, straighten_rays = simplify_raycast(grid, unit.pos, points, radius=unit.radius,
+ lane_spacing=lane_spacing)
+ unit.rays.extend(straighten_rays)
+ apply_path(unit, points, [cell_of(*point) for point in points], traffic, now)
+ summarise_order(stats, units, traffic)
+
+
+def order_individual(grid: Grid, units: Sequence[Unit], goal: Point, *, traffic: TrafficModel,
+ stats: OrderStats, now: float) -> None:
+ """-nogrouppath: one A* per unit, and the congestion cost is what holds them apart.
+
+ With the crossing cost on, the search pays twice: the congestion cost for ground someone
+ else's remaining path covers, and the crossing cost for ground someone else will be standing
+ on at the same moment. The first spreads the column out, the second is what makes it go
+ round a junction instead of through it - and, unlike the first, it charges nothing for
+ following the same road a few seconds behind."""
+ taken: set[Point] = set()
+ cx, cy = compute_centroid(units)
+ # nearest the goal first, so the ones in front claim their line first
+ ordered = sorted(units, key=lambda unit: math.hypot(unit.x - goal[0], unit.y - goal[1]))
+ for unit in ordered:
+ unit.rays = []
+ # computeIndividualDestination: keep the offset from the group centre, capped
+ ox, oy = unit.x - cx, unit.y - cy
+ offset_length = math.hypot(ox, oy)
+ cap = INDIVIDUAL_OFFSET_RADII * unit.radius
+ if offset_length > cap:
+ ox, oy = ox / offset_length * cap, oy / offset_length * cap
+ gx, gy = reserve_goal(grid, taken, goal[0] + ox, goal[1] + oy, radius=unit.radius)
+ unit.goal = (gx, gy)
+ traffic.release(unit.id)
+ cells, expansions = astar(grid, cell_of(unit.x, unit.y), cell_of(gx, gy),
+ pricing=traffic.pricing_for(unit.id, now))
+ stats.expansions += expansions
+ stats.searches += 1
+ if not cells:
+ stats.notes.append(f"unit {unit.id}: no path (search budget)")
+ unit.path = []
+ unit.cells = []
+ continue
+ points = [world_of(*cell) for cell in cells[1:]]
+ points[-1] = (gx, gy)
+ points, unit.rays = simplify_raycast(grid, unit.pos, points, radius=unit.radius,
+ lane_spacing=2.0 * unit.radius)
+ # reserve the straightened line, not the A* cells: the shortcut is where it drives
+ apply_path(unit, points, cells, traffic, now)
+ summarise_order(stats, units, traffic)
+
+
+def spawn_block(grid: Grid, count: int, cx: int, cy: int, first_id: int = 0) -> list[Unit]:
+ """`first_id` keeps a second block's ids clear of the first: both blocks share one usage map and
+ one reservation map, and those are keyed by id."""
+ units: list[Unit] = []
+ row = cy
+ while len(units) < count:
+ for column in range(min(count - len(units), SPAWN_ROW_WIDTH)):
+ cell_x = cx + column * SPAWN_STRIDE_CELLS
+ if grid.passable(cell_x, row):
+ units.append(Unit(*world_of(cell_x, row), id=first_id + len(units)))
+ row += SPAWN_STRIDE_CELLS
+ return units
+
+
+def build_scenario(grid: Grid, unit_count: int,
+ scenario: str) -> tuple[list[Unit], list[tuple[list[Unit], Point]]]:
+ """(units, [(group, goal), ...]) - what gets ordered where.
+
+ `column` is one group crossing the map, which is what the congestion cost was tuned on.
+ `cross` is two groups going to each other's corner: their routes have to meet in the middle,
+ and that is the case the time dimension exists for. A cost that only looks good on `column`
+ has not been tested."""
+ far_x = grid.width - GOAL_INSET_X
+ if scenario == "cross":
+ top = spawn_block(grid, unit_count // 2, *CROSS_SPAWN_TOP)
+ bottom = spawn_block(grid, unit_count - len(top), CROSS_SPAWN_TOP[0],
+ grid.height - CROSS_SPAWN_BOTTOM_INSET, first_id=len(top))
+ return top + bottom, [(top, world_of(far_x, grid.height - GOAL_INSET_Y)),
+ (bottom, world_of(far_x, GOAL_INSET_Y))]
+ units = spawn_block(grid, unit_count, *SPAWN_CELL)
+ return units, [(units, world_of(far_x, grid.height - GOAL_INSET_Y))]
+
+
+@dataclass
+class Measurement:
+ """One row of the headless table: what every seed of one setting added up to, then averaged."""
+ waypoints: float = 0.0
+ length: float = 0.0
+ frames: float = 0.0
+ blocked: float = 0.0
+ overlap: float = 0.0
+ crossings: float = 0.0
+ stuck: int = 0
+ expansions: float = 0.0
+ repaths: float = 0.0
+
+ def average_over(self, seeds: int, unit_count: int) -> None:
+ """`stuck` is a count of units and stays whole; everything else is per seed, and the path
+ length is per unit on top of that."""
+ divisor = float(seeds)
+ self.waypoints /= divisor
+ self.length /= divisor * unit_count
+ self.frames /= divisor
+ self.blocked /= divisor
+ self.overlap /= divisor
+ self.crossings /= divisor
+ self.expansions /= divisor
+ self.repaths /= divisor
+
+
+def measure(map_kind: str, unit_count: int, seeds: int, mode: str, *,
+ is_congestion_charged: bool, is_crossing_charged: bool,
+ scenario: str) -> Measurement:
+ """The scenario's orders, played out, averaged over `seeds` maps."""
+ total = Measurement()
+ for seed in range(seeds):
+ grid = make_map(map_kind, seed=seed)
+ traffic = TrafficModel(UsageMap(), ReservationMap(),
+ is_congestion_charged=is_congestion_charged,
+ is_crossing_charged=is_crossing_charged)
+ units, orders = build_scenario(grid, unit_count, scenario)
+ stats = OrderStats()
+ planner = order_corridor if mode == "corridor" else order_individual
+ for group, goal in orders:
+ planner(grid, group, goal, traffic=traffic, stats=stats, now=0.0)
+ total.overlap += count_path_overlap(units)
+ total.crossings += count_planned_crossings(traffic.reservations)
+ for unit in units:
+ previous = unit.pos
+ for point in unit.path:
+ total.length += math.hypot(point[0] - previous[0], point[1] - previous[1])
+ previous = point
+ frames = 0
+ while frames < MEASURE_MAX_FRAMES and any(
+ not unit.has_arrived and unit.path for unit in units):
+ step_units(units, grid, traffic=traffic, now=float(frames))
+ repath_stuck(grid, units, traffic=traffic, now=float(frames))
+ frames += 1
+ total.waypoints += stats.avg_waypoints
+ total.frames += frames
+ total.blocked += sum(unit.blocked_frames for unit in units)
+ total.stuck += sum(1 for unit in units if not unit.has_arrived)
+ total.expansions += stats.expansions
+ total.repaths += sum(unit.repaths for unit in units)
+ total.average_over(seeds, unit_count)
+ return total
+
+
+def print_table_head() -> None:
+ print(f"{'mode':<9} {'cost/cap/x':<11} {'waypts':>8} {'length':>8} {'frames':>8} "
+ f"{'blocked':>9} {'overlap':>8} {'cross':>6} {'stuck':>7} {'cells':>8}")
+
+
+def print_row(mode: str, label: str, result: Measurement) -> None:
+ print(f"{mode:<9} {label:<11} {result.waypoints:>8.1f} {result.length:>8.0f} "
+ f"{result.frames:>8.0f} {result.blocked:>9.0f} {result.overlap:>8.0f} "
+ f"{result.crossings:>6.0f} {result.stuck:>7d} {result.expansions:>8.0f}")
+
+
+@contextmanager
+def tuning(*, congestion_cost: int, congestion_cap: int, crossing_cost: int,
+ crossing_window: int):
+ """The penalty constants are read deep inside the search, so a sweep row sets them for the
+ duration of its own measurement and hands them back - a row that raised the cost must not
+ leave it raised for the next one."""
+ global PATH_CONGESTION_COST, PATH_CONGESTION_MAX_PATHS, PATH_CROSSING_COST, PATH_CROSSING_WINDOW
+ before = (PATH_CONGESTION_COST, PATH_CONGESTION_MAX_PATHS, PATH_CROSSING_COST,
+ PATH_CROSSING_WINDOW)
+ PATH_CONGESTION_COST, PATH_CONGESTION_MAX_PATHS = congestion_cost, congestion_cap
+ PATH_CROSSING_COST, PATH_CROSSING_WINDOW = crossing_cost, crossing_window
+ try:
+ yield
+ finally:
+ (PATH_CONGESTION_COST, PATH_CONGESTION_MAX_PATHS, PATH_CROSSING_COST,
+ PATH_CROSSING_WINDOW) = before
+
+
+class SweepPoint(NamedTuple):
+ """One row of --sweep. A crossing cost of 0 is the time dimension off."""
+ cost: int
+ cap: int
+ crossing: int
+
+
+def parse_sweep(text: str) -> list[SweepPoint]:
+ """cost[/cap[/crossing]] - a crossing cost of 0 (the default) is the time dimension off."""
+ points: list[SweepPoint] = []
+ for spec in text.split(","):
+ parts = spec.split("/")
+ cap = int(parts[1]) if len(parts) > 1 and parts[1] else PATH_CONGESTION_MAX_PATHS
+ crossing = int(parts[2]) if len(parts) > 2 and parts[2] else 0
+ points.append(SweepPoint(int(parts[0]), cap, crossing))
+ return points
+
+
+def run_headless(args: argparse.Namespace, sweep: Sequence[SweepPoint]) -> None:
+ """No window: play the same order under each setting and print the numbers to compare.
+ This is ai-batch.ps1 for the sandbox - a claim about a change is argued with this.
+
+ `overlap` counts cells two plans share at all, `cross` only the ones they share at the same
+ moment. A change that trades the first for the second is doing what it was asked to."""
+ print(f"map {args.map} scenario {args.scenario} units {args.units} "
+ f"seeds {args.headless} window {args.window} frames")
+ print_table_head()
+ for mode in MODES:
+ with tuning(congestion_cost=args.cost, congestion_cap=args.cap, crossing_cost=args.cross,
+ crossing_window=args.window):
+ print_row(mode, "off",
+ measure(args.map, args.units, args.headless, mode,
+ is_congestion_charged=False, is_crossing_charged=False,
+ scenario=args.scenario))
+ for point in sweep:
+ with tuning(congestion_cost=point.cost, congestion_cap=point.cap,
+ crossing_cost=point.crossing or args.cross, crossing_window=args.window):
+ print_row(mode, f"{point.cost}/{point.cap}/{point.crossing}",
+ measure(args.map, args.units, args.headless, mode,
+ is_congestion_charged=True,
+ is_crossing_charged=point.crossing > 0,
+ scenario=args.scenario))
+
+
+class Simulation:
+ """The map, the units on it and the two shared traffic maps - everything a headless run needs.
+ Held apart from the window so ordering and stepping are the same code in both."""
+
+ def __init__(self, map_kind: str, seed: int, unit_count: int, mode: str) -> None:
+ self.map_kind = map_kind
+ self.unit_count = unit_count
+ self.mode = mode
+ self.frames = 0
+ self.last_goal: Point | None = None
+ self.stats = OrderStats()
+ self.seed = seed
+ self.grid = make_map(map_kind, seed=seed)
+ self.traffic = TrafficModel(UsageMap(), ReservationMap())
+ self.units = self._spawn()
+
+ def _spawn(self) -> list[Unit]:
+ units = spawn_block(self.grid, self.unit_count, *SPAWN_CELL)
+ for unit in units:
+ unit.is_selected = True
+ return units
+
+ def regenerate(self, seed: int) -> None:
+ """A new map under the same settings. The traffic maps go with the old map: they are keyed
+ by cell, and every cell they name has just moved."""
+ self.seed = seed
+ self.grid = make_map(self.map_kind, seed=seed)
+ self.traffic = TrafficModel(UsageMap(), ReservationMap())
+ self.units = self._spawn()
+
+ @property
+ def selected_units(self) -> list[Unit]:
+ selected = [unit for unit in self.units if unit.is_selected]
+ return selected or self.units
+
+ def order(self, goal: Point) -> None:
+ self.last_goal = goal
+ self.stats = OrderStats()
+ selected = self.selected_units
+ for unit in selected:
+ unit.blocked_frames = 0
+ planner = order_corridor if self.mode == "corridor" else order_individual
+ planner(self.grid, selected, goal, traffic=self.traffic, stats=self.stats,
+ now=float(self.frames))
+ print(f"[order] mode={self.mode} units={len(selected)} searches={self.stats.searches} "
+ f"expansions={self.stats.expansions} "
+ f"avg waypoints={self.stats.avg_waypoints:.1f} "
+ f"crossings={self.stats.crossings} {' '.join(self.stats.notes)}")
+
+ def step(self) -> None:
+ now = float(self.frames)
+ step_units(self.units, self.grid, traffic=self.traffic, now=now)
+ repath_stuck(self.grid, self.units, traffic=self.traffic, now=now)
+ self.frames += 1
+
+
+BG: Colour = (24, 26, 30)
+WALL: Colour = (58, 62, 70)
+UNIT_COL: Colour = (120, 190, 255)
+UNIT_SEL: Colour = (255, 214, 110)
+PATH_COL: Colour = (90, 220, 160)
+CORRIDOR_COL: Colour = (70, 90, 140)
+RAY_OK: Colour = (60, 200, 120)
+RAY_BAD: Colour = (220, 90, 90)
+HEAT: Colour = (200, 120, 60)
+HEAT_FLOOR: Colour = (50, 28, 24) # an unused cell is still darker than the walls
+HEAT_GAIN: tuple[float, float, float] = (0.8, 0.7, 0.5) # warm, so a busy cell reads as orange
+HUD_TEXT: Colour = (200, 205, 215)
+
+
+class RayDetail(IntEnum):
+ """Whose line-of-sight checks the window draws."""
+ OFF = 0
+ SELECTED = 1
+ ALL = 2
+
+
+class Renderer:
+ """The window. It reads a Simulation and owns nothing the simulation needs back."""
+
+ def __init__(self, grid: Grid, scale: float) -> None:
+ pygame.init()
+ self.scale = scale
+ self.screen = pygame.display.set_mode(
+ (int(grid.width * CELL * scale), int(grid.height * CELL * scale) + HUD_HEIGHT))
+ pygame.display.set_caption("PathLab")
+ self.font = pygame.font.SysFont("consolas", HUD_FONT_SIZE)
+ self.ray_detail = RayDetail.SELECTED
+ self.show_heat = False
+
+ def close(self) -> None:
+ pygame.quit()
+
+ def to_screen(self, x: float, y: float) -> tuple[int, int]:
+ return int(x * self.scale), int(y * self.scale)
+
+ def _cell_rect(self, cx: int, cy: int, pad: int = 0) -> Rect:
+ size = CELL * self.scale
+ return cx * size, cy * size, size + pad, size + pad
+
+ def draw(self, sim: Simulation) -> None:
+ self.screen.fill(BG)
+ self._draw_terrain(sim.grid)
+ if self.show_heat:
+ self._draw_heat(sim)
+ self._draw_crossings(sim)
+ self._draw_corridor(sim.stats)
+ if self.ray_detail is not RayDetail.OFF:
+ self._draw_rays(sim.units)
+ self._draw_paths(sim.units)
+ self._draw_units(sim.units)
+ self._draw_hud(sim)
+ pygame.display.flip()
+
+ def _draw_terrain(self, grid: Grid) -> None:
+ for cy in range(grid.height):
+ for cx in range(grid.width):
+ if not grid.passable(cx, cy):
+ pygame.draw.rect(self.screen, WALL,
+ self._cell_rect(cx, cy, pad=TERRAIN_OVERDRAW))
+
+ def _draw_heat(self, sim: Simulation) -> None:
+ for (cx, cy), paths in sim.traffic.usage.count.items():
+ if not sim.grid.in_bounds(cx, cy):
+ continue
+ level = min(paths, PATH_CONGESTION_MAX_PATHS) / PATH_CONGESTION_MAX_PATHS
+ colour = (int(HEAT_FLOOR[0] + HEAT[0] * level * HEAT_GAIN[0]),
+ int(HEAT_FLOOR[1] + HEAT[1] * level * HEAT_GAIN[1]),
+ int(HEAT_FLOOR[2] + HEAT[2] * level * HEAT_GAIN[2]))
+ pygame.draw.rect(self.screen, colour, self._cell_rect(cx, cy))
+
+ def _draw_crossings(self, sim: Simulation) -> None:
+ # where two units still plan to be at the same moment - what the crossing cost buys out
+ for cx, cy in find_crossing_cells(sim.traffic.reservations):
+ if sim.grid.in_bounds(cx, cy):
+ pygame.draw.rect(self.screen, RAY_BAD, self._cell_rect(cx, cy),
+ CROSSING_OUTLINE_WIDTH)
+
+ def _draw_corridor(self, stats: OrderStats) -> None:
+ points = [self.to_screen(x, y) for x, y in stats.corridor]
+ if len(points) > 1:
+ pygame.draw.lines(self.screen, CORRIDOR_COL, False, points,
+ max(1, int(stats.diameter * CELL * self.scale / 2)))
+
+ def _draw_rays(self, units: Sequence[Unit]) -> None:
+ # failures last, so the one check that rejected a lane is not buried under the rest
+ for want_clear in (True, False):
+ for unit in units:
+ if self.ray_detail is RayDetail.SELECTED and not unit.is_selected:
+ continue
+ for ax, ay, bx, by, is_clear in unit.rays:
+ if is_clear != want_clear:
+ continue
+ pygame.draw.line(self.screen, RAY_OK if is_clear else RAY_BAD,
+ self.to_screen(ax, ay), self.to_screen(bx, by), 1)
+
+ def _draw_paths(self, units: Sequence[Unit]) -> None:
+ for unit in units:
+ if not unit.path or unit.has_arrived:
+ continue
+ remaining = unit.path[unit.index:]
+ points = [self.to_screen(unit.x, unit.y)]
+ points.extend(self.to_screen(x, y) for x, y in remaining)
+ if len(points) > 1:
+ pygame.draw.lines(self.screen, PATH_COL, False, points, 1)
+ for x, y in remaining:
+ pygame.draw.circle(self.screen, PATH_COL, self.to_screen(x, y), WAYPOINT_DOT)
+
+ def _draw_units(self, units: Sequence[Unit]) -> None:
+ for unit in units:
+ colour = UNIT_SEL if unit.is_selected else UNIT_COL
+ centre = self.to_screen(unit.x, unit.y)
+ pygame.draw.circle(self.screen, colour, centre, int(unit.radius * self.scale))
+ if unit.blocked_frames:
+ pygame.draw.circle(self.screen, RAY_BAD, centre, int(unit.radius * self.scale),
+ BLOCKED_RING_WIDTH)
+
+ def _draw_hud(self, sim: Simulation) -> None:
+ top = int(sim.grid.height * CELL * self.scale) + HUD_TOP_PAD
+ blocked = sum(unit.blocked_frames for unit in sim.units)
+ moving = sum(1 for unit in sim.units if not unit.has_arrived)
+ congestion = str(PATH_CONGESTION_COST) if sim.traffic.is_congestion_charged else "off"
+ crossing = str(PATH_CROSSING_COST) if sim.traffic.is_crossing_charged else "off"
+ heat = "on" if self.show_heat else "off"
+ lines = [
+ f"mode {sim.mode:<9} congestion {congestion:<3} crossing {crossing:<3} "
+ f"rays {self.ray_detail.name.lower():<8} heat {heat:<3} "
+ f"[1][2] [c][t][r][p] [n]map [tab]replan",
+ f"corridor width {sim.stats.diameter} cells searches {sim.stats.searches} "
+ f"cell expansions {sim.stats.expansions} "
+ f"avg waypoints/unit {sim.stats.avg_waypoints:.1f}",
+ f"units {len(sim.units)} still moving {moving} blocked unit-frames {blocked} "
+ f"repaths {sum(unit.repaths for unit in sim.units)} "
+ f"crossings {count_planned_crossings(sim.traffic.reservations)} now {sim.frames} "
+ f"{'; '.join(sim.stats.notes[:HUD_NOTES_SHOWN])}",
+ ]
+ for line_index, text in enumerate(lines):
+ self.screen.blit(self.font.render(text, True, HUD_TEXT),
+ (HUD_TEXT_X, top + line_index * HUD_LINE_HEIGHT))
+
+
+class Lab:
+ """Keys and mouse in, one simulation step and one drawn frame out."""
+
+ def __init__(self, args: argparse.Namespace) -> None:
+ self.sim = Simulation(map_kind=args.map, seed=args.seed, unit_count=args.units,
+ mode=args.mode)
+ self.view = Renderer(self.sim.grid, args.scale)
+ self.is_paused = False
+ self.drag_start: Point | None = None
+
+ def __enter__(self) -> "Lab":
+ return self
+
+ def __exit__(self, exc_type: object, exc: object, traceback: object) -> None:
+ self.view.close()
+
+ def run(self) -> None:
+ clock = pygame.time.Clock()
+ while True:
+ for event in pygame.event.get():
+ if event.type == pygame.QUIT:
+ return
+ if event.type == pygame.KEYDOWN:
+ if event.key == pygame.K_ESCAPE:
+ return
+ self._on_key(event.key)
+ if event.type == pygame.MOUSEBUTTONDOWN:
+ self._on_press(event)
+ if (event.type == pygame.MOUSEBUTTONUP and event.button == MOUSE_RIGHT
+ and self.drag_start):
+ self._on_drag_end(self.drag_start, event)
+ if not self.is_paused:
+ self.sim.step()
+ self.view.draw(self.sim)
+ clock.tick(RENDER_FPS)
+
+ def _on_key(self, key: int) -> None:
+ if key == pygame.K_1:
+ self.sim.mode = "corridor"
+ elif key == pygame.K_2:
+ self.sim.mode = "single"
+ elif key == pygame.K_c:
+ self.sim.traffic.is_congestion_charged = not self.sim.traffic.is_congestion_charged
+ elif key == pygame.K_t:
+ self.sim.traffic.is_crossing_charged = not self.sim.traffic.is_crossing_charged
+ elif key == pygame.K_r:
+ self.view.ray_detail = RayDetail((self.view.ray_detail + 1) % len(RayDetail))
+ elif key == pygame.K_p:
+ self.view.show_heat = not self.view.show_heat
+ elif key == pygame.K_SPACE:
+ self.is_paused = not self.is_paused
+ elif key == pygame.K_n:
+ self.sim.regenerate(random.randrange(SEED_RANGE))
+ elif key == pygame.K_TAB and self.sim.last_goal:
+ self.sim.order(self.sim.last_goal)
+
+ def _world_pos(self, screen_pos: tuple[int, int]) -> Point:
+ return screen_pos[0] / self.view.scale, screen_pos[1] / self.view.scale
+
+ def _on_press(self, event: pygame.event.Event) -> None:
+ wx, wy = self._world_pos(event.pos)
+ if event.button == MOUSE_LEFT and wy < self.sim.grid.height * CELL:
+ self.sim.order((wx, wy))
+ if event.button == MOUSE_RIGHT:
+ self.drag_start = (wx, wy)
+
+ def _on_drag_end(self, drag_start: Point, event: pygame.event.Event) -> None:
+ x0, y0 = drag_start
+ x1, y1 = self._world_pos(event.pos)
+ left, right = min(x0, x1), max(x0, x1)
+ top, bottom = min(y0, y1), max(y0, y1)
+ # a right click rather than a drag: that selects everything, not nothing
+ is_box = (right - left) > CELL and (bottom - top) > CELL
+ for unit in self.sim.units:
+ unit.is_selected = (left <= unit.x <= right and top <= unit.y <= bottom
+ if is_box else True)
+ self.drag_start = None
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__,
+ formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("--mode", choices=MODES, default="corridor")
+ parser.add_argument("--map", choices=MAP_KINDS, default="choke")
+ parser.add_argument("--units", type=int, default=8)
+ parser.add_argument("--scenario", choices=SCENARIOS, default="column",
+ help="headless only: one group crossing the map, or two crossing each other")
+ parser.add_argument("--scale", type=float, default=1.0)
+ parser.add_argument("--seed", type=int, default=7)
+ parser.add_argument("--headless", type=int, metavar="SEEDS",
+ help="no window: run SEEDS orders per mode and print the comparison")
+ parser.add_argument("--cost", type=int, default=PATH_CONGESTION_COST,
+ help="cost per path already claiming a cell (engine default 5, step is 10)")
+ parser.add_argument("--cap", type=int, default=PATH_CONGESTION_MAX_PATHS,
+ help="how many paths on one cell still add cost (engine default 4)")
+ parser.add_argument("--cross", type=int, default=PATH_CROSSING_COST,
+ help="cost per unit that will be in a cell at the same moment we are")
+ parser.add_argument("--window", type=int, default=PATH_CROSSING_WINDOW,
+ help="frames either side of an arrival that still count as the same moment")
+ parser.add_argument("--sweep", default="5/4/0,20/4/0,20/4/60,20/4/120",
+ help="headless only: cost/cap/crossing triples to compare (crossing 0 = off)")
+ args = parser.parse_args()
+ sweep = parse_sweep(args.sweep)
+ if args.headless:
+ run_headless(args, sweep)
+ return
+ with tuning(congestion_cost=args.cost, congestion_cap=args.cap, crossing_cost=args.cross,
+ crossing_window=args.window), Lab(args) as lab:
+ lab.run()
+
+
+if __name__ == "__main__":
+ main()
+ sys.exit(0)
diff --git a/Tools/PathLab/test_pathlab.py b/Tools/PathLab/test_pathlab.py
new file mode 100644
index 000000000..e7819563f
--- /dev/null
+++ b/Tools/PathLab/test_pathlab.py
@@ -0,0 +1,298 @@
+"""Checks for pathlab.py - stdlib unittest, no window, no pygame display.
+
+ python -m unittest test_pathlab -v (from Tools/PathLab)
+
+The point of these is the parts a screenshot cannot argue with: the A* costs, the two penalty
+functions and their caps, and the book-keeping in the usage and reservation maps - which is where a
+mistake is silent, because a mis-released cell only shows up as a number in a table being slightly
+wrong."""
+
+import math
+import unittest
+
+import pathlab
+from pathlab import (CELL, COST_DIAGONAL, COST_ORTHOGONAL, PATH_CONGESTION_COST,
+ PATH_CONGESTION_MAX_PATHS, PATH_CROSSING_COST, PATH_CROSSING_MAX,
+ Grid, OrderStats, ReservationMap, TrafficModel, UsageMap,
+ astar, build_scenario, cell_of, compute_centroid, count_planned_crossings,
+ find_crossing_cells, make_map, order_corridor, order_individual, parse_sweep,
+ price_congestion, price_crossing, simplify_raycast, spawn_block,
+ track_reservations, tuning, world_of)
+
+
+def open_grid(size: int = 21) -> Grid:
+ """No border wall: the tests that want one build it themselves."""
+ return Grid(size, size)
+
+
+def corridor_grid(size: int = 21) -> Grid:
+ """A wall down the middle with a single-cell gap - too narrow for a clearance of 1."""
+ grid = open_grid(size)
+ for y in range(size):
+ if y != size // 2:
+ grid.block(size // 2, y)
+ return grid
+
+
+class GeometryTests(unittest.TestCase):
+ def test_world_of_is_the_centre_of_the_cell_it_names(self):
+ self.assertEqual(cell_of(*world_of(4, 7)), (4, 7))
+ self.assertEqual(world_of(0, 0), (CELL / 2, CELL / 2))
+
+ def test_line_passable_sees_a_wall_the_endpoints_miss(self):
+ grid = corridor_grid()
+ left, right = world_of(2, 2), world_of(18, 2)
+ self.assertFalse(grid.line_passable(*left, *right))
+ through_gap = world_of(18, 10)
+ self.assertTrue(grid.line_passable(*world_of(2, 10), *through_gap))
+
+ def test_has_room_is_false_in_a_doorway(self):
+ grid = corridor_grid()
+ self.assertFalse(grid.has_room(10, 10)) # the gap itself
+ self.assertTrue(grid.has_room(3, 3)) # open ground
+
+ def test_make_map_names_the_kinds_it_knows(self):
+ with self.assertRaises(ValueError) as raised:
+ make_map("cliff")
+ self.assertIn("cliff", str(raised.exception))
+ self.assertIn("twogaps", str(raised.exception))
+
+
+class AStarTests(unittest.TestCase):
+ def test_straight_line_costs_one_orthogonal_step_per_cell(self):
+ cells, expansions = astar(open_grid(), (2, 2), (2, 8))
+ self.assertEqual(cells[0], (2, 2))
+ self.assertEqual(cells[-1], (2, 8))
+ self.assertEqual(len(cells), 7)
+ self.assertGreater(expansions, 0)
+
+ def test_diagonal_is_cheaper_than_going_round_the_corner(self):
+ self.assertLess(COST_DIAGONAL, 2 * COST_ORTHOGONAL)
+ cells, _ = astar(open_grid(), (2, 2), (6, 6))
+ self.assertEqual(len(cells), 5) # four diagonal steps
+
+ def test_no_path_through_a_blocked_goal(self):
+ grid = open_grid()
+ grid.block(5, 5)
+ self.assertEqual(astar(grid, (2, 2), (5, 5))[0], [])
+
+ def test_clearance_rejects_a_gap_a_wide_group_cannot_use(self):
+ grid = corridor_grid()
+ self.assertTrue(astar(grid, (2, 10), (18, 10))[0])
+ self.assertEqual(astar(grid, (2, 10), (18, 10), clearance=1)[0], [])
+
+ def test_budget_exhaustion_returns_no_path_rather_than_running_for_ever(self):
+ cells, expansions = astar(open_grid(41), (2, 2), (38, 38), cell_budget=5)
+ self.assertEqual(cells, [])
+ self.assertLessEqual(expansions, 6)
+
+
+class PricingTests(unittest.TestCase):
+ def test_congestion_is_linear_then_capped(self):
+ self.assertEqual(price_congestion(0), 0)
+ self.assertEqual(price_congestion(2), 2 * PATH_CONGESTION_COST)
+ self.assertEqual(price_congestion(PATH_CONGESTION_MAX_PATHS + 5),
+ PATH_CONGESTION_MAX_PATHS * PATH_CONGESTION_COST)
+
+ def test_crossing_is_linear_then_capped(self):
+ self.assertEqual(price_crossing(0), 0)
+ self.assertEqual(price_crossing(1), PATH_CROSSING_COST)
+ self.assertEqual(price_crossing(PATH_CROSSING_MAX + 5),
+ PATH_CROSSING_MAX * PATH_CROSSING_COST)
+
+ def test_a_priced_route_goes_round_a_claimed_gap(self):
+ """Four diagonal steps instead of four orthogonal ones cost 16; crossing the claimed cell
+ costs 20. So the detour has to win, and it is the cost that made it, not the map."""
+ grid = open_grid()
+ claimed = [(10, 9), (10, 10), (10, 11)]
+ usage = UsageMap()
+ usage.register(0, claimed)
+ pricing = pathlab.PathPricing(usage=usage, congestion_range=1000, owner=1)
+ plain, _ = astar(grid, (2, 10), (18, 10))
+ priced, _ = astar(grid, (2, 10), (18, 10), pricing=pricing)
+ self.assertIn((10, 10), plain)
+ self.assertFalse(set(priced) & set(claimed))
+
+ def test_tuning_hands_the_constants_back(self):
+ before = (pathlab.PATH_CONGESTION_COST, pathlab.PATH_CONGESTION_MAX_PATHS,
+ pathlab.PATH_CROSSING_COST, pathlab.PATH_CROSSING_WINDOW)
+ with tuning(congestion_cost=99, congestion_cap=9, crossing_cost=98, crossing_window=97):
+ self.assertEqual(pathlab.PATH_CONGESTION_COST, 99)
+ self.assertEqual(pathlab.PATH_CROSSING_WINDOW, 97)
+ self.assertEqual((pathlab.PATH_CONGESTION_COST, pathlab.PATH_CONGESTION_MAX_PATHS,
+ pathlab.PATH_CROSSING_COST, pathlab.PATH_CROSSING_WINDOW), before)
+
+
+class UsageMapTests(unittest.TestCase):
+ def test_registering_twice_does_not_double_count(self):
+ usage = UsageMap()
+ usage.register(0, [(1, 1), (2, 2)])
+ usage.register(0, [(1, 1), (3, 3)])
+ self.assertEqual(usage.count, {(1, 1): 1, (3, 3): 1})
+
+ def test_full_release_leaves_nothing_behind(self):
+ usage = UsageMap()
+ usage.register(0, [(1, 1), (2, 2)])
+ usage.register(1, [(1, 1)])
+ usage.unregister(0)
+ usage.unregister(1)
+ self.assertEqual(usage.count, {})
+
+ def test_release_before_drops_only_what_is_driven_past(self):
+ usage = UsageMap()
+ usage.register(0, [(1, 1), (2, 2), (3, 3)])
+ usage.release_before(0, 2)
+ self.assertEqual(usage.count, {(3, 3): 1})
+ self.assertEqual(usage.owner[0], [(3, 3)])
+
+ def test_a_unit_is_not_charged_for_its_own_path(self):
+ usage = UsageMap()
+ usage.register(0, [(4, 4)])
+ usage.register(1, [(4, 4)])
+ self.assertEqual(usage.count_paths_on((4, 4)), 2)
+ self.assertEqual(usage.count_paths_on((4, 4), exclude_owner=0), 1)
+
+
+class ReservationMapTests(unittest.TestCase):
+ def reserve(self, reservations, owner, arrival, heading):
+ reservations.reserve(owner, [(5, 5)], [arrival], [heading])
+
+ def test_following_traffic_is_not_a_crossing(self):
+ reservations = ReservationMap()
+ self.reserve(reservations, 0, 100.0, (1.0, 0.0))
+ self.assertEqual(reservations.count_conflicts((5, 5), 101.0, 1, (1.0, 0.0)), 0)
+
+ def test_opposing_traffic_at_the_same_moment_is(self):
+ reservations = ReservationMap()
+ self.reserve(reservations, 0, 100.0, (1.0, 0.0))
+ self.assertEqual(reservations.count_conflicts((5, 5), 101.0, 1, (0.0, 1.0)), 1)
+
+ def test_the_same_cell_much_later_is_not(self):
+ reservations = ReservationMap()
+ self.reserve(reservations, 0, 100.0, (1.0, 0.0))
+ far = 100.0 + pathlab.PATH_CROSSING_WINDOW + 1
+ self.assertEqual(reservations.count_conflicts((5, 5), far, 1, (0.0, 1.0)), 0)
+
+ def test_release_before_keeps_the_future_and_drops_the_past(self):
+ reservations = ReservationMap()
+ reservations.reserve(0, [(1, 1), (2, 2)], [10.0, 30.0], [(1.0, 0.0), (1.0, 0.0)])
+ reservations.release_before(0, 20.0)
+ self.assertEqual(list(reservations.at), [(2, 2)])
+ self.assertEqual(len(reservations.owner[0]), 1)
+
+ def test_full_release_leaves_nothing_behind(self):
+ reservations = ReservationMap()
+ reservations.reserve(0, [(1, 1)], [10.0], [(1.0, 0.0)])
+ reservations.reserve(1, [(1, 1)], [11.0], [(0.0, 1.0)])
+ reservations.release(0)
+ reservations.release(1)
+ self.assertEqual(reservations.at, {})
+
+ def test_crossing_cells_counts_an_opposed_pair_once(self):
+ reservations = ReservationMap()
+ self.reserve(reservations, 0, 100.0, (1.0, 0.0))
+ self.reserve(reservations, 1, 101.0, (0.0, 1.0))
+ self.assertEqual(find_crossing_cells(reservations), {(5, 5): 1})
+ self.assertEqual(count_planned_crossings(reservations), 1)
+
+ def test_a_queue_produces_no_crossing_cells(self):
+ reservations = ReservationMap()
+ self.reserve(reservations, 0, 100.0, (1.0, 0.0))
+ self.reserve(reservations, 1, 101.0, (1.0, 0.0))
+ self.assertEqual(find_crossing_cells(reservations), {})
+
+
+class TrackTests(unittest.TestCase):
+ def test_arrival_times_only_ever_grow(self):
+ track = track_reservations((5.0, 5.0), [(5.0, 205.0)], start_frame=7.0)
+ self.assertTrue(all(later >= earlier
+ for earlier, later in zip(track.times, track.times[1:])))
+ self.assertGreaterEqual(track.times[0], 7.0)
+
+ def test_headings_are_unit_length_and_point_along_the_leg(self):
+ track = track_reservations((5.0, 5.0), [(205.0, 5.0)])
+ for hx, hy in track.headings:
+ self.assertAlmostEqual(math.hypot(hx, hy), 1.0, places=6)
+ self.assertAlmostEqual(hx, 1.0, places=6)
+
+ def test_every_cell_on_the_drive_line_is_claimed_once(self):
+ track = track_reservations((5.0, 5.0), [(95.0, 5.0)])
+ self.assertEqual(track.cells, [(cx, 0) for cx in range(1, 10)])
+ self.assertEqual(len(track.times), len(track.cells))
+ self.assertEqual(len(track.headings), len(track.cells))
+
+
+class StraighteningTests(unittest.TestCase):
+ def test_collinear_waypoints_on_open_ground_collapse(self):
+ grid = open_grid()
+ points = [world_of(cx, 2) for cx in range(3, 12)]
+ simplified, rays = simplify_raycast(grid, world_of(2, 2), points, radius=11.0,
+ lane_spacing=22.0)
+ self.assertLess(len(simplified), len(points))
+ self.assertEqual(simplified[-1], points[-1])
+ self.assertTrue(rays)
+
+ def test_a_wall_stops_the_shortcut(self):
+ grid = corridor_grid()
+ points = [world_of(cx, 2) for cx in range(3, 20)]
+ simplified, rays = simplify_raycast(grid, world_of(2, 2), points, radius=11.0,
+ lane_spacing=22.0)
+ self.assertTrue(any(not is_clear for *_, is_clear in rays))
+ self.assertEqual(simplified[-1], points[-1])
+
+
+class OrderTests(unittest.TestCase):
+ def plan(self, planner, map_kind="open", unit_count=6):
+ grid = make_map(map_kind, seed=3)
+ traffic = TrafficModel(UsageMap(), ReservationMap())
+ units, orders = build_scenario(grid, unit_count, "column")
+ stats = OrderStats()
+ for group, goal in orders:
+ planner(grid, group, goal, traffic=traffic, stats=stats, now=0.0)
+ return grid, units, traffic, stats
+
+ def test_the_corridor_gives_every_unit_its_own_goal(self):
+ _, units, _, stats = self.plan(order_corridor)
+ self.assertTrue(all(unit.path and unit.goal for unit in units))
+ self.assertIn(stats.diameter, pathlab.GROUP_PATH_DIAMETERS)
+ self.assertEqual(len({unit.goal for unit in units}), len(units))
+
+ def test_individual_paths_claim_ground_in_both_shared_maps(self):
+ _, units, traffic, _ = self.plan(order_individual)
+ self.assertTrue(all(unit.cells for unit in units))
+ self.assertTrue(traffic.usage.count)
+ self.assertTrue(traffic.reservations.at)
+ for unit in units:
+ self.assertEqual(traffic.usage.owner[unit.id], unit.cells)
+
+ def test_the_corridor_is_searched_once_for_the_whole_group(self):
+ _, _, _, corridor_stats = self.plan(order_corridor)
+ _, units, _, single_stats = self.plan(order_individual)
+ self.assertEqual(single_stats.searches, len(units))
+ self.assertLess(corridor_stats.searches, single_stats.searches)
+
+ def test_a_group_ordered_onto_itself_says_so_instead_of_moving(self):
+ grid = make_map("open", seed=3)
+ traffic = TrafficModel(UsageMap(), ReservationMap())
+ units = spawn_block(grid, 4, *pathlab.SPAWN_CELL)
+ stats = OrderStats()
+ order_corridor(grid, units, compute_centroid(units), traffic=traffic, stats=stats, now=0.0)
+ self.assertTrue(stats.notes)
+ self.assertFalse(any(unit.path for unit in units))
+
+
+class SweepTests(unittest.TestCase):
+ def test_cap_and_crossing_default_when_left_out(self):
+ self.assertEqual(parse_sweep("5"),
+ [(5, PATH_CONGESTION_MAX_PATHS, 0)])
+
+ def test_a_full_triple_is_read_in_order(self):
+ self.assertEqual(parse_sweep("20/4/60,40/2/0"), [(20, 4, 60), (40, 2, 0)])
+
+ def test_a_sweep_point_is_addressed_by_name(self):
+ point = parse_sweep("20/4/60")[0]
+ self.assertEqual((point.cost, point.cap, point.crossing), (20, 4, 60))
+
+
+if __name__ == "__main__":
+ unittest.main()