Skip to content

Commit

Permalink
Add helper methods to locate actors that can be reached via a path.
Browse files Browse the repository at this point in the history
Previously, the ClosestTo and PositionClosestTo existed to perform a simple distance based check to choose the closest location from a choice of locations to a single other location. For some functions this is sufficient, but for many functions we want to then move between the locations. If the location selected is in fact unreachable (e.g. on another island) then we would not want to consider it.

We now introduce ClosestToIgnoringPath for checks where we don't care about a path existing, e.g. weapons hitting nearby targets. When we do care about paths, we introduce ClosestToWithPathFrom and ClosestToWithPathTo which will check that a path exists. The PathFrom check will make sure one of the actors from the list can make it to the single target location. The PathTo check will make sure the single actor can make it to one of the target locations. This difference allows us to specify which actor will be doing the moving. This is important as a path might exists for one actor, but not another. Consider two islands with a hovercraft on one and a tank on the other. The hovercraft can path to the tank, but the tank cannot path to the hovercraft.

We also introduce WithPathFrom and WithPathTo. These will perform filtering by checking for valid paths, but won't select the closest location.

By employing the new methods that filter for paths, we fix various behaviour that would cause actors to get confused. Imagine an islands map, by checking for paths we ensure logic will locate reachable locations on the island, rather than considering a location on a nearby island that is physically closer but unreachable. This fixes AI squad automation, and other automated behaviours such as rearming.
  • Loading branch information
RoosterDragon committed Jul 15, 2023
1 parent 659ec5e commit 23a0e5b
Show file tree
Hide file tree
Showing 27 changed files with 368 additions and 322 deletions.
5 changes: 5 additions & 0 deletions OpenRA.Game/Exts.cs
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,11 @@ public static int MultiplyBySqrtTwo(short number)
return number * 46341 / 32768;
}

public static int MultiplyBySqrtTwoOverTwo(int number)
{
return (int)(number * 23170L / 32768L);
}

public static int IntegerDivisionRoundingAwayFromZero(int dividend, int divisor)
{
var quotient = Math.DivRem(dividend, divisor, out var remainder);
Expand Down
24 changes: 18 additions & 6 deletions OpenRA.Game/WorldUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,19 +19,31 @@ namespace OpenRA
{
public static class WorldUtils
{
public static Actor ClosestTo(this IEnumerable<Actor> actors, Actor a)
/// <summary>
/// From the given <paramref name="actors"/>, select the one nearest the given <paramref name="actor"/> by
/// comparing their <see cref="Actor.CenterPosition"/>. No check is done to see if a path exists.
/// </summary>
public static Actor ClosestToIgnoringPath(this IEnumerable<Actor> actors, Actor actor)
{
return actors.ClosestTo(a.CenterPosition);
return actors.ClosestToIgnoringPath(actor.CenterPosition);
}

public static Actor ClosestTo(this IEnumerable<Actor> actors, WPos pos)
/// <summary>
/// From the given <paramref name="actors"/>, select the one nearest the given <paramref name="position"/> by
/// comparing the <see cref="Actor.CenterPosition"/>. No check is done to see if a path exists.
/// </summary>
public static Actor ClosestToIgnoringPath(this IEnumerable<Actor> actors, WPos position)
{
return actors.MinByOrDefault(a => (a.CenterPosition - pos).LengthSquared);
return actors.MinByOrDefault(a => (a.CenterPosition - position).LengthSquared);
}

public static WPos PositionClosestTo(this IEnumerable<WPos> positions, WPos pos)
/// <summary>
/// From the given <paramref name="positions"/>, select the one nearest the given <paramref name="position"/>.
/// No check is done to see if a path exists, as an actor is required for that.
/// </summary>
public static WPos ClosestToIgnoringPath(this IEnumerable<WPos> positions, WPos position)
{
return positions.MinByOrDefault(p => (p - pos).LengthSquared);
return positions.MinByOrDefault(p => (p - position).LengthSquared);
}

public static IEnumerable<Actor> FindActorsInCircle(this World world, WPos origin, WDist r)
Expand Down
2 changes: 1 addition & 1 deletion OpenRA.Mods.Cnc/Projectiles/TeslaZap.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ public void Tick(World world)

// Zap tracks target
if (info.TrackTarget && args.GuidedTarget.IsValidFor(args.SourceActor))
target = args.Weapon.TargetActorCenter ? args.GuidedTarget.CenterPosition : args.GuidedTarget.Positions.PositionClosestTo(args.Source);
target = args.Weapon.TargetActorCenter ? args.GuidedTarget.CenterPosition : args.GuidedTarget.Positions.ClosestToIgnoringPath(args.Source);

if (damageDuration-- > 0)
args.Weapon.Impact(Target.FromPos(target), new WarheadArgs(args));
Expand Down
2 changes: 1 addition & 1 deletion OpenRA.Mods.Common/Activities/Air/ReturnToBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public static Actor ChooseResupplier(Actor self, bool unreservedOnly)
&& a.Owner == self.Owner
&& rearmInfo.RearmActors.Contains(a.Info.Name)
&& (!unreservedOnly || Reservable.IsAvailableFor(a, self)))
.ClosestTo(self);
.ClosestToWithPathFrom(self);
}

bool ShouldLandAtBuilding(Actor self, Actor dest)
Expand Down
2 changes: 1 addition & 1 deletion OpenRA.Mods.Common/Activities/Enter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ public override bool Tick(Actor self)
case EnterState.Entering:
{
// Check that we reached the requested position
var targetPos = target.Positions.PositionClosestTo(self.CenterPosition);
var targetPos = target.Positions.ClosestToWithPathFrom(self);
if (!IsCanceling && self.CenterPosition == targetPos && target.Type == TargetType.Actor)
OnEnterComplete(self, target.Actor);

Expand Down
2 changes: 1 addition & 1 deletion OpenRA.Mods.Common/Activities/Hunt.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public override bool Tick(Actor self)
if (IsCanceling)
return true;

var target = targets.ClosestTo(self);
var target = targets.ClosestToWithPathFrom(self);
if (target == null)
return false;

Expand Down
7 changes: 5 additions & 2 deletions OpenRA.Mods.Common/Activities/LayMines.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,11 @@ public override bool Tick(Actor self)
if (rearmableInfo != null && ammoPools.Any(p => p.Info.Name == minelayer.Info.AmmoPoolName && !p.HasAmmo))
{
// Rearm (and possibly repair) at rearm building, then back out here to refill the minefield some more
rearmTarget = self.World.Actors.Where(a => self.Owner.RelationshipWith(a.Owner) == PlayerRelationship.Ally && rearmableInfo.RearmActors.Contains(a.Info.Name))
.ClosestTo(self);
rearmTarget = self.World.Actors
.Where(a =>
self.Owner.RelationshipWith(a.Owner) == PlayerRelationship.Ally
&& rearmableInfo.RearmActors.Contains(a.Info.Name))
.ClosestToWithPathFrom(self);

if (rearmTarget == null)
return true;
Expand Down
15 changes: 9 additions & 6 deletions OpenRA.Mods.Common/Activities/Move/LocalMoveIntoTarget.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public class LocalMoveIntoTarget : Activity
readonly Target target;
readonly Color? targetLineColor;
readonly WDist targetMovementThreshold;
WPos targetStartPos;
WPos? targetStartPos;

public LocalMoveIntoTarget(Actor self, in Target target, WDist targetMovementThreshold, Color? targetLineColor = null)
{
Expand All @@ -35,7 +35,7 @@ public LocalMoveIntoTarget(Actor self, in Target target, WDist targetMovementThr

protected override void OnFirstRun(Actor self)
{
targetStartPos = target.Positions.PositionClosestTo(self.CenterPosition);
targetStartPos = target.Positions.ClosestToWithPathFrom(self);
}

public override bool Tick(Actor self)
Expand All @@ -47,14 +47,17 @@ public override bool Tick(Actor self)
return false;

var currentPos = self.CenterPosition;
var targetPos = target.Positions.PositionClosestTo(currentPos);
var targetPos = target.Positions.ClosestToWithPathFrom(self);

if (targetStartPos == null || targetPos == null)
return true;

// Give up if the target has moved too far
if (targetMovementThreshold > WDist.Zero && (targetPos - targetStartPos).LengthSquared > targetMovementThreshold.LengthSquared)
if (targetMovementThreshold > WDist.Zero && (targetPos.Value - targetStartPos.Value).LengthSquared > targetMovementThreshold.LengthSquared)
return true;

// Turn if required
var delta = targetPos - currentPos;
var delta = targetPos.Value - currentPos;
var facing = delta.HorizontalLengthSquared != 0 ? delta.Yaw : mobile.Facing;
if (facing != mobile.Facing)
{
Expand All @@ -66,7 +69,7 @@ public override bool Tick(Actor self)
var speed = mobile.MovementSpeedForCell(self.Location);
if (delta.LengthSquared <= speed * speed)
{
mobile.SetCenterPosition(self, targetPos);
mobile.SetCenterPosition(self, targetPos.Value);
return true;
}

Expand Down
2 changes: 1 addition & 1 deletion OpenRA.Mods.Common/Projectiles/AreaBeam.cs
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ void TrackTarget()

if (args.GuidedTarget.IsValidFor(args.SourceActor))
{
var guidedTargetPos = args.Weapon.TargetActorCenter ? args.GuidedTarget.CenterPosition : args.GuidedTarget.Positions.PositionClosestTo(args.Source);
var guidedTargetPos = args.Weapon.TargetActorCenter ? args.GuidedTarget.CenterPosition : args.GuidedTarget.Positions.ClosestToIgnoringPath(args.Source);
var targetDistance = new WDist((guidedTargetPos - args.Source).Length);

// Only continue tracking target if it's within weapon range +
Expand Down
2 changes: 1 addition & 1 deletion OpenRA.Mods.Common/Projectiles/LaserZap.cs
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ public void Tick(World world)

// Beam tracks target
if (info.TrackTarget && args.GuidedTarget.IsValidFor(args.SourceActor))
target = args.Weapon.TargetActorCenter ? args.GuidedTarget.CenterPosition : args.GuidedTarget.Positions.PositionClosestTo(source);
target = args.Weapon.TargetActorCenter ? args.GuidedTarget.CenterPosition : args.GuidedTarget.Positions.ClosestToIgnoringPath(source);

// Check for blocking actors
if (info.Blockable && BlocksProjectiles.AnyBlockingActorsBetween(world, args.SourceActor.Owner, source, target, info.Width, out var blockedPos))
Expand Down
2 changes: 1 addition & 1 deletion OpenRA.Mods.Common/Projectiles/Missile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -849,7 +849,7 @@ public void Tick(World world)
// Check if target position should be updated (actor visible & locked on)
var newTarPos = targetPosition;
if (args.GuidedTarget.IsValidFor(args.SourceActor) && lockOn)
newTarPos = (args.Weapon.TargetActorCenter ? args.GuidedTarget.CenterPosition : args.GuidedTarget.Positions.PositionClosestTo(args.Source))
newTarPos = (args.Weapon.TargetActorCenter ? args.GuidedTarget.CenterPosition : args.GuidedTarget.Positions.ClosestToIgnoringPath(args.Source))
+ new WVec(WDist.Zero, WDist.Zero, info.AirburstAltitude);

// Compute target's predicted velocity vector (assuming uniform circular motion)
Expand Down
2 changes: 1 addition & 1 deletion OpenRA.Mods.Common/Traits/Armament.cs
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,7 @@ protected virtual void FireBarrel(Actor self, IFacing facing, in Target target,
WAngle MuzzleFacing() => MuzzleOrientation(self, barrel).Yaw;
var muzzleOrientation = WRot.FromYaw(MuzzleFacing());

var passiveTarget = Weapon.TargetActorCenter ? target.CenterPosition : target.Positions.PositionClosestTo(MuzzlePosition());
var passiveTarget = Weapon.TargetActorCenter ? target.CenterPosition : target.Positions.ClosestToIgnoringPath(MuzzlePosition());
var initialOffset = Weapon.FirstBurstTargetOffset;
if (initialOffset != WVec.Zero)
{
Expand Down
2 changes: 1 addition & 1 deletion OpenRA.Mods.Common/Traits/Attack/AttackBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ public bool HasAnyValidWeapons(in Target t, bool checkForCenterTargetingWeapons

public virtual WPos GetTargetPosition(WPos pos, in Target target)
{
return HasAnyValidWeapons(target, true) ? target.CenterPosition : target.Positions.PositionClosestTo(pos);
return HasAnyValidWeapons(target, true) ? target.CenterPosition : target.Positions.ClosestToIgnoringPath(pos);
}

public WDist GetMinimumRange()
Expand Down
2 changes: 1 addition & 1 deletion OpenRA.Mods.Common/Traits/AutoCarryall.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ static bool IsBestAutoCarryallForCargo(Actor self, Actor candidateCargo)
var carriers = self.World.ActorsHavingTrait<AutoCarryall>(c => !c.busy)
.Where(a => a.Owner == self.Owner && a.IsInWorld);

return carriers.ClosestTo(candidateCargo) == self;
return carriers.ClosestToWithPathTo(candidateCargo) == self;
}

void FindCarryableForTransport(Actor self)
Expand Down
2 changes: 1 addition & 1 deletion OpenRA.Mods.Common/Traits/AutoCrusher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ void INotifyIdle.TickIdle(Actor self)
self.Location != a.Location && a.IsAtGroundLevel() &&
Info.TargetRelationships.HasRelationship(self.Owner.RelationshipWith(a.Owner)) &&
a.TraitsImplementing<ICrushable>().Any(c => c.CrushableBy(a, self, Info.CrushClasses)))
.ClosestTo(self); // TODO: Make it use shortest pathfinding distance instead
.ClosestToWithPathFrom(self); // TODO: Make it use shortest pathfinding distance instead

if (crushableActor == null)
return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -468,8 +468,9 @@ ActorInfo ChooseBuildingToBuild(ProductionQueue queue)
case BuildingType.Defense:

// Build near the closest enemy structure
var closestEnemy = world.ActorsHavingTrait<Building>().Where(a => !a.Disposed && player.RelationshipWith(a.Owner) == PlayerRelationship.Enemy)
.ClosestTo(world.Map.CenterOfCell(baseBuilder.DefenseCenter));
var closestEnemy = world.ActorsHavingTrait<Building>()
.Where(a => !a.Disposed && player.RelationshipWith(a.Owner) == PlayerRelationship.Enemy)
.ClosestToIgnoringPath(world.Map.CenterOfCell(baseBuilder.DefenseCenter));

var targetCell = closestEnemy != null ? closestEnemy.Location : baseCenter;

Expand Down
18 changes: 1 addition & 17 deletions OpenRA.Mods.Common/Traits/BotModules/CaptureManagerBotModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ public class CaptureManagerBotModule : ConditionalTrait<CaptureManagerBotModuleI
{
readonly World world;
readonly Player player;
readonly Func<Actor, bool> isEnemyUnit;
readonly Predicate<Actor> unitCannotBeOrderedOrIsIdle;
readonly int maximumCaptureTargetOptions;
int minCaptureDelayTicks;
Expand All @@ -64,11 +63,6 @@ public CaptureManagerBotModule(Actor self, CaptureManagerBotModuleInfo info)
if (world.Type == WorldType.Editor)
return;

isEnemyUnit = unit =>
player.RelationshipWith(unit.Owner) == PlayerRelationship.Enemy
&& !unit.Info.HasTraitInfo<HuskInfo>()
&& unit.Info.HasTraitInfo<ITargetableInfo>();

unitCannotBeOrderedOrIsIdle = a => a.Owner != player || a.IsDead || !a.IsInWorld || a.IsIdle;

maximumCaptureTargetOptions = Math.Max(1, Info.MaximumCaptureTargetOptions);
Expand All @@ -89,16 +83,6 @@ void IBotTick.BotTick(IBot bot)
}
}

internal Actor FindClosestEnemy(WPos pos)
{
return world.Actors.Where(isEnemyUnit).ClosestTo(pos);
}

internal Actor FindClosestEnemy(WPos pos, WDist radius)
{
return world.FindActorsInCircle(pos, radius).Where(isEnemyUnit).ClosestTo(pos);
}

IEnumerable<Actor> GetVisibleActorsBelongingToPlayer(Player owner)
{
foreach (var actor in GetActorsThatCanBeOrderedByPlayer(owner))
Expand Down Expand Up @@ -159,7 +143,7 @@ void QueueCaptureOrders(IBot bot)

foreach (var capturer in capturers)
{
var targetActor = capturableTargetOptions.MinByOrDefault(target => (target.CenterPosition - capturer.Actor.CenterPosition).LengthSquared);
var targetActor = capturableTargetOptions.ClosestToWithPathFrom(capturer.Actor);
if (targetActor == null)
continue;

Expand Down

0 comments on commit 23a0e5b

Please sign in to comment.