Repath around blocking units or structures.

This commit is contained in:
Bob
2009-10-28 17:59:09 +13:00
parent 58f9347cb7
commit 222b72a679
4 changed files with 245 additions and 181 deletions

View File

@@ -8,7 +8,7 @@ using IrrKlang;
using IjwFramework.Collections; using IjwFramework.Collections;
using System; using System;
using IjwFramework.Types; using IjwFramework.Types;
using OpenRa.Game.Traits; using OpenRa.Game.Traits;
using OpenRa.Game.GameRules; using OpenRa.Game.GameRules;
namespace OpenRa.Game namespace OpenRa.Game
@@ -22,7 +22,7 @@ namespace OpenRa.Game
static TreeCache treeCache; static TreeCache treeCache;
public static TerrainRenderer terrain; public static TerrainRenderer terrain;
public static Viewport viewport; public static Viewport viewport;
public static PathFinder pathFinder; public static PathFinder PathFinder;
public static Network network; public static Network network;
public static WorldRenderer worldRenderer; public static WorldRenderer worldRenderer;
public static Controller controller; public static Controller controller;
@@ -32,50 +32,50 @@ namespace OpenRa.Game
public static Dictionary<int, Player> players = new Dictionary<int, Player>(); public static Dictionary<int, Player> players = new Dictionary<int, Player>();
public static Player LocalPlayer { get { return players[localPlayerIndex]; } } public static Player LocalPlayer { get { return players[localPlayerIndex]; } }
public static BuildingInfluenceMap BuildingInfluence; public static BuildingInfluenceMap BuildingInfluence;
public static UnitInfluenceMap UnitInfluence; public static UnitInfluenceMap UnitInfluence;
static ISoundEngine soundEngine; static ISoundEngine soundEngine;
public static void Initialize(string mapName, Renderer renderer, int2 clientSize, int localPlayer) public static void Initialize(string mapName, Renderer renderer, int2 clientSize, int localPlayer)
{ {
Rules.LoadRules(mapName); Rules.LoadRules(mapName);
for (int i = 0; i < 8; i++) for (int i = 0; i < 8; i++)
players.Add(i, new Player(i, string.Format("Multi{0}", i), Race.Soviet)); players.Add(i, new Player(i, string.Format("Multi{0}", i), Race.Soviet));
localPlayerIndex = localPlayer; localPlayerIndex = localPlayer;
var mapFile = new IniFile(FileSystem.Open(mapName)); var mapFile = new IniFile(FileSystem.Open(mapName));
map = new Map(mapFile); map = new Map(mapFile);
FileSystem.Mount(new Package(map.Theater + ".mix")); FileSystem.Mount(new Package(map.Theater + ".mix"));
viewport = new Viewport(clientSize, map.Size, renderer); viewport = new Viewport(clientSize, map.Size, renderer);
terrain = new TerrainRenderer(renderer, map, viewport); terrain = new TerrainRenderer(renderer, map, viewport);
world = new World(); world = new World();
treeCache = new TreeCache(map); treeCache = new TreeCache(map);
foreach (TreeReference treeReference in map.Trees) foreach (TreeReference treeReference in map.Trees)
world.Add(new Actor(treeReference, treeCache, map.Offset)); world.Add(new Actor(treeReference, treeCache, map.Offset));
BuildingInfluence = new BuildingInfluenceMap(8); BuildingInfluence = new BuildingInfluenceMap(8);
UnitInfluence = new UnitInfluenceMap(); UnitInfluence = new UnitInfluenceMap();
LoadMapBuildings(mapFile); LoadMapBuildings(mapFile);
LoadMapUnits(mapFile); LoadMapUnits(mapFile);
pathFinder = new PathFinder(map, terrain.tileSet); PathFinder = new PathFinder(map, terrain.tileSet);
network = new Network(); network = new Network();
controller = new Controller(); controller = new Controller();
worldRenderer = new WorldRenderer(renderer); worldRenderer = new WorldRenderer(renderer);
soundEngine = new ISoundEngine(); soundEngine = new ISoundEngine();
sounds = new Cache<string, ISoundSource>(LoadSound); sounds = new Cache<string, ISoundSource>(LoadSound);
PlaySound("intro.aud", false); PlaySound("intro.aud", false);
} }
static void LoadMapBuildings( IniFile mapfile ) static void LoadMapBuildings( IniFile mapfile )
@@ -125,7 +125,7 @@ namespace OpenRa.Game
public static void Tick() public static void Tick()
{ {
var stuffFromOtherPlayers = network.Tick(); // todo: actually use the orders! var stuffFromOtherPlayers = network.Tick(); // todo: actually use the orders!
world.Update(); world.Update();
UnitInfluence.Tick(); UnitInfluence.Tick();
viewport.DrawRegions(); viewport.DrawRegions();
@@ -133,7 +133,7 @@ namespace OpenRa.Game
public static bool IsCellBuildable(int2 a, UnitMovementType umt) public static bool IsCellBuildable(int2 a, UnitMovementType umt)
{ {
if (BuildingInfluence.GetBuildingAt(a) != null) return false; if (BuildingInfluence.GetBuildingAt(a) != null) return false;
if (UnitInfluence.GetUnitAt(a) != null) return false; if (UnitInfluence.GetUnitAt(a) != null) return false;
a += map.Offset; a += map.Offset;
@@ -158,19 +158,19 @@ namespace OpenRa.Game
{ {
return FindUnits(a - new float2(r, r), a + new float2(r, r)) return FindUnits(a - new float2(r, r), a + new float2(r, r))
.Where(x => (x.CenterLocation - a).LengthSquared < r * r); .Where(x => (x.CenterLocation - a).LengthSquared < r * r);
} }
public static IEnumerable<int2> FindTilesInCircle(int2 a, int r) public static IEnumerable<int2> FindTilesInCircle(int2 a, int r)
{ {
var min = a - new int2(r, r); var min = a - new int2(r, r);
var max = a + new int2(r, r); var max = a + new int2(r, r);
for (var j = min.Y; j <= max.Y; j++) for (var j = min.Y; j <= max.Y; j++)
for (var i = min.X; i <= max.X; i++) for (var i = min.X; i <= max.X; i++)
if (r * r >= (new int2(i, j) - a).LengthSquared) if (r * r >= (new int2(i, j) - a).LengthSquared)
yield return new int2(i, j); yield return new int2(i, j);
} }
public static IEnumerable<Actor> SelectUnitsInBox(float2 a, float2 b) public static IEnumerable<Actor> SelectUnitsInBox(float2 a, float2 b)
{ {
return FindUnits(a, b).Where(x => x.Owner == LocalPlayer && x.traits.Contains<Traits.Mobile>()); return FindUnits(a, b).Where(x => x.Owner == LocalPlayer && x.traits.Contains<Traits.Mobile>());
@@ -197,52 +197,52 @@ namespace OpenRa.Game
public static readonly Pair<VoicePool, VoicePool> SovietVoices = public static readonly Pair<VoicePool, VoicePool> SovietVoices =
Pair.New( Pair.New(
new VoicePool("ackno", "affirm1", "noprob", "overout", "ritaway", "roger", "ugotit"), new VoicePool("ackno", "affirm1", "noprob", "overout", "ritaway", "roger", "ugotit"),
new VoicePool("await1", "ready", "report1", "yessir1")); new VoicePool("await1", "ready", "report1", "yessir1"));
static int2? FindAdjacentTile(Actor a, UnitMovementType umt) static int2? FindAdjacentTile(Actor a, UnitMovementType umt)
{ {
var tiles = Footprint.Tiles(a); var tiles = Footprint.Tiles(a);
var min = tiles.Aggregate(int2.Min) - new int2(1, 1); var min = tiles.Aggregate(int2.Min) - new int2(1, 1);
var max = tiles.Aggregate(int2.Max) + new int2(1, 1); var max = tiles.Aggregate(int2.Max) + new int2(1, 1);
for (var j = min.Y; j <= max.Y; j++) for (var j = min.Y; j <= max.Y; j++)
for (var i = min.X; i <= max.X; i++) for (var i = min.X; i <= max.X; i++)
if (IsCellBuildable(new int2(i, j), umt)) if (IsCellBuildable(new int2(i, j), umt))
return new int2(i, j); return new int2(i, j);
return null; return null;
} }
public static void BuildUnit(Player player, string name) public static void BuildUnit(Player player, string name)
{ {
var producerTypes = Rules.UnitInfo[name].BuiltAt; var producerTypes = Rules.UnitInfo[name].BuiltAt;
var producer = world.Actors var producer = world.Actors
.FirstOrDefault(a => a.unitInfo != null .FirstOrDefault(a => a.unitInfo != null
&& producerTypes.Contains(a.unitInfo.Name) && a.Owner == player); && producerTypes.Contains(a.unitInfo.Name) && a.Owner == player);
if (producer == null) if (producer == null)
throw new InvalidOperationException("BuildUnit without suitable production structure!"); throw new InvalidOperationException("BuildUnit without suitable production structure!");
Actor unit; Actor unit;
if (producerTypes.Contains("spen") || producerTypes.Contains("syrd")) if (producerTypes.Contains("spen") || producerTypes.Contains("syrd"))
{ {
var space = FindAdjacentTile(producer, Rules.UnitInfo[name].WaterBound ? var space = FindAdjacentTile(producer, Rules.UnitInfo[name].WaterBound ?
UnitMovementType.Float : UnitMovementType.Wheel ); /* hackety hack */ UnitMovementType.Float : UnitMovementType.Wheel ); /* hackety hack */
if (space == null) if (space == null)
throw new NotImplementedException("Nowhere to place this unit."); throw new NotImplementedException("Nowhere to place this unit.");
unit = new Actor(name, space.Value, player); unit = new Actor(name, space.Value, player);
var mobile = unit.traits.Get<Mobile>(); var mobile = unit.traits.Get<Mobile>();
mobile.facing = SharedRandom.Next(256); mobile.facing = SharedRandom.Next(256);
} }
else else
{ {
unit = new Actor(name, (1 / 24f * producer.CenterLocation).ToInt2(), player); unit = new Actor(name, (1 / 24f * producer.CenterLocation).ToInt2(), player);
var mobile = unit.traits.Get<Mobile>(); var mobile = unit.traits.Get<Mobile>();
mobile.facing = 128; mobile.facing = 128;
mobile.QueueActivity(new Mobile.MoveTo(unit.Location + new int2(0, 3))); mobile.QueueActivity(new Mobile.MoveTo(unit.Location + new int2(0, 3)));
} }
world.AddFrameEndTask(_ => world.Add(unit)); world.AddFrameEndTask(_ => world.Add(unit));

View File

@@ -42,6 +42,32 @@ namespace OpenRa.Game
return path; return path;
} }
public List<int2> FindPathToPath( int2 from, List<int2> path, UnitMovementType umt )
{
var offset = map.Offset;
var cellInfo = InitCellInfo();
var queue = new PriorityQueue<PathDistance>();
var estimator = DefaultEstimator( from );
var cost = 0.0;
var prev = path[ 0 ] + offset;
for( int i = 0 ; i < path.Count ; i++ )
{
var sl = path[ i ] + offset;
if( Game.BuildingInfluence.GetBuildingAt( path[ i ] ) == null & Game.UnitInfluence.GetUnitAt( path[ i ] ) == null )
{
queue.Add( new PathDistance( estimator( sl - offset ), sl ) );
cellInfo[ sl.X, sl.Y ] = new CellInfo( cost, prev, false );
}
var d = sl - prev;
cost += ( ( d.X * d.Y != 0 ) ? 1.414213563 : 1.0 ) * passableCost[ (int)umt ][ sl.X, sl.Y ];
prev = sl;
}
var ret = FindPath( cellInfo, queue, estimator, umt, true );
ret.Reverse();
return ret;
}
List<int2> FindUnitPath( int2 unitLocation, Func<int2,double> estimator, UnitMovementType umt ) List<int2> FindUnitPath( int2 unitLocation, Func<int2,double> estimator, UnitMovementType umt )
{ {
var startLocation = unitLocation + map.Offset; var startLocation = unitLocation + map.Offset;
@@ -50,13 +76,8 @@ namespace OpenRa.Game
List<int2> FindUnitPath(IEnumerable<int2> startLocations, Func<int2, double> estimator, UnitMovementType umt) List<int2> FindUnitPath(IEnumerable<int2> startLocations, Func<int2, double> estimator, UnitMovementType umt)
{ {
var cellInfo = new CellInfo[128, 128];
var offset = map.Offset; var offset = map.Offset;
var cellInfo = InitCellInfo();
for (int x = 0; x < 128; x++)
for (int y = 0; y < 128; y++)
cellInfo[x, y] = new CellInfo(double.PositiveInfinity, new int2(x, y), false);
var queue = new PriorityQueue<PathDistance>(); var queue = new PriorityQueue<PathDistance>();
foreach (var sl in startLocations) foreach (var sl in startLocations)
@@ -65,6 +86,13 @@ namespace OpenRa.Game
cellInfo[sl.X, sl.Y].MinCost = 0; cellInfo[sl.X, sl.Y].MinCost = 0;
} }
return FindPath( cellInfo, queue, estimator, umt, false );
}
List<int2> FindPath( CellInfo[ , ] cellInfo, PriorityQueue<PathDistance> queue, Func<int2, double> estimator, UnitMovementType umt, bool checkForBlock )
{
var offset = map.Offset;
while( !queue.Empty ) while( !queue.Empty )
{ {
PathDistance p = queue.Pop(); PathDistance p = queue.Pop();
@@ -84,6 +112,8 @@ namespace OpenRa.Game
continue; continue;
if (Game.BuildingInfluence.GetBuildingAt(newHere - offset) != null) if (Game.BuildingInfluence.GetBuildingAt(newHere - offset) != null)
continue; continue;
if( checkForBlock && Game.UnitInfluence.GetUnitAt( newHere - offset ) != null )
continue;
double cellCost = ( ( d.X * d.Y != 0 ) ? 1.414213563 : 1.0 ) * passableCost[(int)umt][ newHere.X, newHere.Y ]; double cellCost = ( ( d.X * d.Y != 0 ) ? 1.414213563 : 1.0 ) * passableCost[(int)umt][ newHere.X, newHere.Y ];
double newCost = cellInfo[ here.X, here.Y ].MinCost + cellCost; double newCost = cellInfo[ here.X, here.Y ].MinCost + cellCost;
@@ -102,6 +132,15 @@ namespace OpenRa.Game
return new List<int2>(); return new List<int2>();
} }
static CellInfo[ , ] InitCellInfo()
{
var cellInfo = new CellInfo[ 128, 128 ];
for( int x = 0 ; x < 128 ; x++ )
for( int y = 0 ; y < 128 ; y++ )
cellInfo[ x, y ] = new CellInfo( double.PositiveInfinity, new int2( x, y ), false );
return cellInfo;
}
List<int2> MakePath( CellInfo[ , ] cellInfo, int2 destination, int2 offset ) List<int2> MakePath( CellInfo[ , ] cellInfo, int2 destination, int2 offset )
{ {
List<int2> ret = new List<int2>(); List<int2> ret = new List<int2>();

View File

@@ -49,9 +49,9 @@ namespace OpenRa.Game.Traits
public Order Order(Actor self, int2 xy, bool lmb, Actor underCursor) public Order Order(Actor self, int2 xy, bool lmb, Actor underCursor)
{ {
if( lmb ) return null; if( lmb ) return null;
if( underCursor != null ) if( underCursor != null )
return null; return null;
if (xy != toCell) if (xy != toCell)
@@ -121,31 +121,32 @@ namespace OpenRa.Game.Traits
public CurrentActivity NextActivity { get; set; } public CurrentActivity NextActivity { get; set; }
int2? destination; int2? destination;
public List<int2> path; public List<int2> path;
Func<Actor, Mobile, List<int2>> getPath; Func<Actor, Mobile, List<int2>> getPath;
MovePart move; MovePart move;
public MoveTo( int2 destination ) public MoveTo( int2 destination )
{ {
this.getPath = (self, mobile) => Game.pathFinder.FindUnitPath( this.getPath = (self, mobile) => Game.PathFinder.FindUnitPath(
self.Location, destination, self.Location, destination,
mobile.GetMovementType()); mobile.GetMovementType());
this.destination = destination; this.destination = destination;
} }
public MoveTo(Actor target, int range) public MoveTo(Actor target, int range)
{ {
this.getPath = (self, mobile) => Game.pathFinder.FindUnitPathToRange( this.getPath = (self, mobile) => Game.PathFinder.FindUnitPathToRange(
self.Location, target.Location, self.Location, target.Location,
mobile.GetMovementType(), range); mobile.GetMovementType(), range);
this.destination = null; this.destination = null;
} }
static bool CanEnterCell(int2 c, Actor self) static bool CanEnterCell(int2 c, Actor self)
{ {
var u = Game.UnitInfluence.GetUnitAt(c); var u = Game.UnitInfluence.GetUnitAt(c);
return u == null || u == self; var b = Game.BuildingInfluence.GetBuildingAt(c);
return (u == null || u == self) && b == null;
} }
public void Tick( Actor self, Mobile mobile ) public void Tick( Actor self, Mobile mobile )
@@ -154,46 +155,67 @@ namespace OpenRa.Game.Traits
{ {
move.TickMove( self, mobile, this ); move.TickMove( self, mobile, this );
return; return;
} }
if( destination == self.Location ) if( destination == self.Location )
{ {
mobile.currentActivity = NextActivity; mobile.currentActivity = NextActivity;
return; return;
} }
if (path == null) path = getPath(self, mobile).TakeWhile(a => a != self.Location).ToList();
if (path.Count == 0)
{
destination = mobile.toCell;
return;
}
destination = path[0];
if (path == null) path = getPath(self, mobile).TakeWhile(a => a != self.Location).ToList(); var nextCell = PopPath( self, mobile );
if( nextCell == null )
if (path.Count == 0) return;
int2 dir = nextCell.Value - mobile.fromCell;
var firstFacing = Util.GetFacing( dir, mobile.facing );
if( firstFacing != mobile.facing )
{ {
destination = mobile.toCell; mobile.currentActivity = new Turn( firstFacing ) { NextActivity = this };
return; path.Add( nextCell.Value );
} }
else else
destination = path[0]; {
mobile.toCell = nextCell.Value;
var nextCell = path[ path.Count - 1 ]; move = new MoveFirstHalf(
int2 dir = nextCell - mobile.fromCell; CenterOfCell( mobile.fromCell ),
var firstFacing = Util.GetFacing( dir, mobile.facing ); BetweenCells( mobile.fromCell, mobile.toCell ),
if( firstFacing != mobile.facing ) mobile.facing,
mobile.currentActivity = new Turn( firstFacing ) { NextActivity = this }; mobile.facing,
else 0 );
{
if (!CanEnterCell(nextCell, self)) return; /* todo: repath, sometimes */ Game.UnitInfluence.Update( mobile );
mobile.toCell = nextCell;
path.RemoveAt( path.Count - 1 );
move = new MoveFirstHalf(
CenterOfCell( mobile.fromCell ),
BetweenCells( mobile.fromCell, mobile.toCell ),
mobile.facing,
mobile.facing,
0 );
Game.UnitInfluence.Update(mobile);
} }
mobile.currentActivity.Tick( self, mobile ); mobile.currentActivity.Tick( self, mobile );
}
int2? PopPath( Actor self, Mobile mobile )
{
if( path.Count == 0 ) return null;
var nextCell = path[ path.Count - 1 ];
if( !CanEnterCell( nextCell, self ) )
{
Game.UnitInfluence.Remove( mobile );
path = Game.PathFinder.FindPathToPath( self.Location, path, mobile.GetMovementType() )
.TakeWhile( a => a != self.Location )
.ToList();
Game.UnitInfluence.Add( mobile );
if( path.Count == 0 )
return null;
nextCell = path[ path.Count - 1 ];
}
path.RemoveAt( path.Count - 1 );
return nextCell;
} }
static float2 CenterOfCell( int2 loc ) static float2 CenterOfCell( int2 loc )
@@ -260,28 +282,25 @@ namespace OpenRa.Game.Traits
} }
protected override MovePart OnComplete( Actor self, Mobile mobile, MoveTo parent ) protected override MovePart OnComplete( Actor self, Mobile mobile, MoveTo parent )
{ {
if( parent.path.Count > 0 ) var nextCell = parent.PopPath( self, mobile );
{ if( nextCell != null )
var nextCell = parent.path[ parent.path.Count - 1 ]; {
if( ( nextCell - mobile.toCell ) != ( mobile.toCell - mobile.fromCell ) ) if( ( nextCell - mobile.toCell ) != ( mobile.toCell - mobile.fromCell ) )
{ {
if( CanEnterCell( nextCell, self ) ) var ret = new MoveFirstHalf(
{ BetweenCells( mobile.fromCell, mobile.toCell ),
parent.path.RemoveAt( parent.path.Count - 1 ); BetweenCells( mobile.toCell, nextCell.Value ),
mobile.facing,
var ret = new MoveFirstHalf( Util.GetNearestFacing( mobile.facing, Util.GetFacing( nextCell.Value - mobile.toCell, mobile.facing ) ),
BetweenCells( mobile.fromCell, mobile.toCell ), moveFraction - moveFractionTotal );
BetweenCells( mobile.toCell, nextCell ), mobile.fromCell = mobile.toCell;
mobile.facing, mobile.toCell = nextCell.Value;
Util.GetNearestFacing( mobile.facing, Util.GetFacing( nextCell - mobile.toCell, mobile.facing ) ), Game.UnitInfluence.Update( mobile );
moveFraction - moveFractionTotal ); return ret;
mobile.fromCell = mobile.toCell; }
mobile.toCell = nextCell; else
Game.UnitInfluence.Update( mobile ); parent.path.Add( nextCell.Value );
return ret;
}
}
} }
var ret2 = new MoveSecondHalf( var ret2 = new MoveSecondHalf(
BetweenCells( mobile.fromCell, mobile.toCell ), BetweenCells( mobile.fromCell, mobile.toCell ),
@@ -314,13 +333,13 @@ namespace OpenRa.Game.Traits
path.Clear(); path.Clear();
NextActivity = null; NextActivity = null;
} }
} }
public IEnumerable<int2> GetCurrentPath() public IEnumerable<int2> GetCurrentPath()
{ {
var move = currentActivity as MoveTo; var move = currentActivity as MoveTo;
if (move == null || move.path == null) return new int2[] { }; if (move == null || move.path == null) return new int2[] { };
return Enumerable.Reverse(move.path); return Enumerable.Reverse(move.path);
} }
} }
} }

View File

@@ -25,7 +25,13 @@ namespace OpenRa.Game
Update(u); Update(u);
} }
public Actor GetUnitAt(int2 a) { return influence[a.X, a.Y]; } public Actor GetUnitAt( int2 a )
{
var actor = influence[ a.X, a.Y ];
if( actor != null && !actor.traits.Get<Mobile>().OccupiedCells().Contains( a ) )
throw new InvalidOperationException( "UIM: Unit is not in influenced square" );
return actor;
}
public void Add(Mobile a) public void Add(Mobile a)
{ {