Moves Attack, Armament, Move, Air traits and activities as well as anything required by them to Mods.Common.

Extracts Exit from Production into its own trait.
This commit is contained in:
reaperrr
2015-01-01 18:08:08 +01:00
parent 158517c09f
commit 654f56c5d5
113 changed files with 255 additions and 244 deletions

View File

@@ -0,0 +1,65 @@
#region Copyright & License Information
/*
* Copyright 2007-2014 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using System.Linq;
using OpenRA.Activities;
using OpenRA.GameRules;
using OpenRA.Mods.Common.Traits;
using OpenRA.Traits;
namespace OpenRA.Mods.Common.Activities
{
public class FallToEarth : Activity
{
int acceleration = 0;
int spin = 0;
FallsToEarthInfo info;
public FallToEarth(Actor self, FallsToEarthInfo info)
{
this.info = info;
if (info.Spins)
acceleration = self.World.SharedRandom.Next(2) * 2 - 1;
}
public override Activity Tick(Actor self)
{
var aircraft = self.Trait<Aircraft>();
if (self.CenterPosition.Z <= 0)
{
if (info.Explosion != null)
{
var weapon = self.World.Map.Rules.Weapons[info.Explosion.ToLowerInvariant()];
// Use .FromPos since this actor is killed. Cannot use Target.FromActor
weapon.Impact(Target.FromPos(self.CenterPosition), self, Enumerable.Empty<int>());
}
self.Destroy();
return null;
}
if (info.Spins)
{
spin += acceleration;
aircraft.Facing = (aircraft.Facing + spin) % 256;
}
var move = info.Moves ? aircraft.FlyStep(aircraft.Facing) : WVec.Zero;
move -= new WVec(WRange.Zero, WRange.Zero, info.Velocity);
aircraft.SetPosition(self, aircraft.CenterPosition + move);
return this;
}
// Cannot be cancelled
public override void Cancel(Actor self) { }
}
}

View File

@@ -0,0 +1,87 @@
#region Copyright & License Information
/*
* Copyright 2007-2014 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using System.Collections.Generic;
using OpenRA.Activities;
using OpenRA.Mods.Common.Traits;
using OpenRA.Traits;
namespace OpenRA.Mods.Common.Activities
{
public class Fly : Activity
{
readonly Plane plane;
readonly Target target;
readonly WRange maxRange;
readonly WRange minRange;
public Fly(Actor self, Target t)
{
plane = self.Trait<Plane>();
target = t;
}
public Fly(Actor self, Target t, WRange minRange, WRange maxRange)
: this(self, t)
{
this.maxRange = maxRange;
this.minRange = minRange;
}
public static void FlyToward(Actor self, Plane plane, int desiredFacing, WRange desiredAltitude)
{
var move = plane.FlyStep(plane.Facing);
var altitude = plane.CenterPosition.Z;
plane.Facing = Util.TickFacing(plane.Facing, desiredFacing, plane.ROT);
if (altitude != desiredAltitude.Range)
{
var delta = move.HorizontalLength * plane.Info.MaximumPitch.Tan() / 1024;
var dz = (desiredAltitude.Range - altitude).Clamp(-delta, delta);
move += new WVec(0, 0, dz);
}
plane.SetPosition(self, plane.CenterPosition + move);
}
public override Activity Tick(Actor self)
{
if (IsCanceled || !target.IsValidFor(self))
return NextActivity;
// Inside the target annulus, so we're done
var insideMaxRange = maxRange.Range > 0 && target.IsInRange(plane.CenterPosition, maxRange);
var insideMinRange = minRange.Range > 0 && target.IsInRange(plane.CenterPosition, minRange);
if (insideMaxRange && !insideMinRange)
return NextActivity;
// Close enough (ported from old code which checked length against sqrt(50) px)
var d = target.CenterPosition - self.CenterPosition;
if (d.HorizontalLengthSquared < 91022)
return NextActivity;
var desiredFacing = Util.GetFacing(d, plane.Facing);
// Don't turn until we've reached the cruise altitude
if (plane.CenterPosition.Z < plane.Info.CruiseAltitude.Range)
desiredFacing = plane.Facing;
FlyToward(self, plane, desiredFacing, plane.Info.CruiseAltitude);
return this;
}
public override IEnumerable<Target> GetTargets(Actor self)
{
yield return target;
}
}
}

View File

@@ -0,0 +1,64 @@
#region Copyright & License Information
/*
* Copyright 2007-2014 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using System.Linq;
using OpenRA.Activities;
using OpenRA.Mods.Common.Traits;
using OpenRA.Traits;
namespace OpenRA.Mods.Common.Activities
{
public class FlyAttack : Activity
{
readonly Target target;
Activity inner;
int ticksUntilTurn = 50;
public FlyAttack(Target target) { this.target = target; }
public override Activity Tick(Actor self)
{
if (!target.IsValidFor(self))
return NextActivity;
var limitedAmmo = self.TraitOrDefault<LimitedAmmo>();
if (limitedAmmo != null && !limitedAmmo.HasAmmo())
return NextActivity;
var attack = self.TraitOrDefault<AttackPlane>();
if (attack != null)
attack.DoAttack(self, target);
if (inner == null)
{
if (IsCanceled)
return NextActivity;
if (target.IsInRange(self.CenterPosition, attack.Armaments.Select(a => a.Weapon.MinRange).Min()))
inner = Util.SequenceActivities(new FlyTimed(ticksUntilTurn), new Fly(self, target), new FlyTimed(ticksUntilTurn));
else
inner = Util.SequenceActivities(new Fly(self, target), new FlyTimed(ticksUntilTurn));
}
inner = Util.RunActivity(self, inner);
return this;
}
public override void Cancel(Actor self)
{
if (!IsCanceled && inner != null)
inner.Cancel(self);
// NextActivity must always be set to null:
base.Cancel(self);
}
}
}

View File

@@ -0,0 +1,33 @@
#region Copyright & License Information
/*
* Copyright 2007-2014 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using OpenRA.Activities;
using OpenRA.Mods.Common.Traits;
using OpenRA.Traits;
namespace OpenRA.Mods.Common.Activities
{
public class FlyCircle : Activity
{
public override Activity Tick(Actor self)
{
if (IsCanceled)
return NextActivity;
var plane = self.Trait<Plane>();
// We can't possibly turn this fast
var desiredFacing = plane.Facing + 64;
Fly.FlyToward(self, plane, desiredFacing, plane.Info.CruiseAltitude);
return this;
}
}
}

View File

@@ -0,0 +1,46 @@
#region Copyright & License Information
/*
* Copyright 2007-2014 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using OpenRA.Activities;
using OpenRA.Mods.Common.Traits;
using OpenRA.Traits;
namespace OpenRA.Mods.Common.Activities
{
public class FlyFollow : Activity
{
Target target;
Plane plane;
WRange minRange;
WRange maxRange;
public FlyFollow(Actor self, Target target, WRange minRange, WRange maxRange)
{
this.target = target;
plane = self.Trait<Plane>();
this.minRange = minRange;
this.maxRange = maxRange;
}
public override Activity Tick(Actor self)
{
if (IsCanceled || !target.IsValidFor(self))
return NextActivity;
if (target.IsInRange(self.CenterPosition, maxRange) && !target.IsInRange(self.CenterPosition, minRange))
{
Fly.FlyToward(self, plane, plane.Facing, plane.Info.CruiseAltitude);
return this;
}
return Util.SequenceActivities(new Fly(self, target, minRange, maxRange), this);
}
}
}

View File

@@ -0,0 +1,52 @@
#region Copyright & License Information
/*
* Copyright 2007-2014 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using OpenRA.Activities;
using OpenRA.Mods.Common.Traits;
using OpenRA.Traits;
namespace OpenRA.Mods.Common.Activities
{
public class FlyTimed : Activity
{
int remainingTicks;
public FlyTimed(int ticks) { remainingTicks = ticks; }
public override Activity Tick(Actor self)
{
if (IsCanceled || remainingTicks-- == 0)
return NextActivity;
var plane = self.Trait<Plane>();
Fly.FlyToward(self, plane, plane.Facing, plane.Info.CruiseAltitude);
return this;
}
}
public class FlyOffMap : Activity
{
public override Activity Tick(Actor self)
{
if (IsCanceled || !self.World.Map.Contains(self.Location))
return NextActivity;
var plane = self.Trait<Plane>();
Fly.FlyToward(self, plane, plane.Facing, plane.Info.CruiseAltitude);
return this;
}
public override void Cancel(Actor self)
{
base.Cancel(self);
}
}
}

View File

@@ -0,0 +1,52 @@
#region Copyright & License Information
/*
* Copyright 2007-2014 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using OpenRA.Activities;
using OpenRA.Mods.Common.Traits;
using OpenRA.Traits;
namespace OpenRA.Mods.Common.Activities
{
public class HeliAttack : Activity
{
Target target;
public HeliAttack(Target target) { this.target = target; }
public override Activity Tick(Actor self)
{
if (IsCanceled || !target.IsValidFor(self))
return NextActivity;
var limitedAmmo = self.TraitOrDefault<LimitedAmmo>();
var reloads = self.TraitOrDefault<Reloads>();
if (limitedAmmo != null && !limitedAmmo.HasAmmo() && reloads == null)
return Util.SequenceActivities(new HeliReturn(), NextActivity);
var helicopter = self.Trait<Helicopter>();
var attack = self.Trait<AttackHeli>();
var dist = target.CenterPosition - self.CenterPosition;
// Can rotate facing while ascending
var desiredFacing = Util.GetFacing(dist, helicopter.Facing);
helicopter.Facing = Util.TickFacing(helicopter.Facing, desiredFacing, helicopter.ROT);
if (HeliFly.AdjustAltitude(self, helicopter, helicopter.Info.CruiseAltitude))
return this;
// Fly towards the target
if (!target.IsInRange(self.CenterPosition, attack.GetMaximumRange()))
helicopter.SetPosition(self, helicopter.CenterPosition + helicopter.FlyStep(desiredFacing));
attack.DoAttack(self, target);
return this;
}
}
}

View File

@@ -0,0 +1,95 @@
#region Copyright & License Information
/*
* Copyright 2007-2014 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using System.Collections.Generic;
using OpenRA.Activities;
using OpenRA.Mods.Common.Traits;
using OpenRA.Traits;
namespace OpenRA.Mods.Common.Activities
{
public class HeliFly : Activity
{
readonly Helicopter helicopter;
readonly Target target;
readonly WRange maxRange;
readonly WRange minRange;
public HeliFly(Actor self, Target t)
{
helicopter = self.Trait<Helicopter>();
target = t;
}
public HeliFly(Actor self, Target t, WRange minRange, WRange maxRange)
: this(self, t)
{
this.maxRange = maxRange;
this.minRange = minRange;
}
public static bool AdjustAltitude(Actor self, Helicopter helicopter, WRange targetAltitude)
{
var altitude = helicopter.CenterPosition.Z;
if (altitude == targetAltitude.Range)
return false;
var delta = helicopter.Info.AltitudeVelocity.Range;
var dz = (targetAltitude.Range - altitude).Clamp(-delta, delta);
helicopter.SetPosition(self, helicopter.CenterPosition + new WVec(0, 0, dz));
return true;
}
public override Activity Tick(Actor self)
{
if (IsCanceled || !target.IsValidFor(self))
return NextActivity;
if (AdjustAltitude(self, helicopter, helicopter.Info.CruiseAltitude))
return this;
var pos = target.CenterPosition;
// Rotate towards the target
var dist = pos - self.CenterPosition;
var desiredFacing = Util.GetFacing(dist, helicopter.Facing);
helicopter.Facing = Util.TickFacing(helicopter.Facing, desiredFacing, helicopter.ROT);
var move = helicopter.FlyStep(desiredFacing);
// Inside the minimum range, so reverse
if (minRange.Range > 0 && target.IsInRange(helicopter.CenterPosition, minRange))
{
helicopter.SetPosition(self, helicopter.CenterPosition - move);
return this;
}
// Inside the maximum range, so we're done
if (maxRange.Range > 0 && target.IsInRange(helicopter.CenterPosition, maxRange))
return NextActivity;
// The next move would overshoot, so just set the final position
if (dist.HorizontalLengthSquared < move.HorizontalLengthSquared)
{
helicopter.SetPosition(self, pos + new WVec(0, 0, helicopter.Info.CruiseAltitude.Range - pos.Z));
return NextActivity;
}
helicopter.SetPosition(self, helicopter.CenterPosition + move);
return this;
}
public override IEnumerable<Target> GetTargets(Actor self)
{
yield return target;
}
}
}

View File

@@ -0,0 +1,45 @@
#region Copyright & License Information
/*
* Copyright 2007-2014 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using System;
using System.Collections.Generic;
using OpenRA.Activities;
using OpenRA.Mods.Common.Traits;
using OpenRA.Traits;
namespace OpenRA.Mods.Common.Activities
{
public class HeliFlyCircle : Activity
{
readonly Helicopter helicopter;
public HeliFlyCircle(Actor self)
{
helicopter = self.Trait<Helicopter>();
}
public override Activity Tick(Actor self)
{
if (IsCanceled)
return NextActivity;
if (HeliFly.AdjustAltitude(self, helicopter, helicopter.Info.CruiseAltitude))
return this;
var move = helicopter.FlyStep(helicopter.Facing);
helicopter.SetPosition(self, helicopter.CenterPosition + move);
var desiredFacing = helicopter.Facing + 64;
helicopter.Facing = Util.TickFacing(helicopter.Facing, desiredFacing, helicopter.ROT / 3);
return this;
}
}
}

View File

@@ -0,0 +1,41 @@
#region Copyright & License Information
/*
* Copyright 2007-2014 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using OpenRA.Activities;
using OpenRA.Mods.Common.Traits;
namespace OpenRA.Mods.Common.Activities
{
public class HeliLand : Activity
{
bool requireSpace;
public HeliLand(bool requireSpace)
{
this.requireSpace = requireSpace;
}
public override Activity Tick(Actor self)
{
if (IsCanceled)
return NextActivity;
var helicopter = self.Trait<Helicopter>();
if (requireSpace && !helicopter.CanLand(self.Location))
return this;
if (HeliFly.AdjustAltitude(self, helicopter, helicopter.Info.LandAltitude))
return this;
return NextActivity;
}
}
}

View File

@@ -0,0 +1,68 @@
#region Copyright & License Information
/*
* Copyright 2007-2014 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using System.Linq;
using OpenRA.Activities;
using OpenRA.Mods.Common.Traits;
using OpenRA.Traits;
namespace OpenRA.Mods.Common.Activities
{
public class HeliReturn : Activity
{
static Actor ChooseHelipad(Actor self)
{
var rearmBuildings = self.Info.Traits.Get<HelicopterInfo>().RearmBuildings;
return self.World.Actors.Where(a => a.Owner == self.Owner).FirstOrDefault(
a => rearmBuildings.Contains(a.Info.Name) && !Reservable.IsReserved(a));
}
public override Activity Tick(Actor self)
{
if (IsCanceled)
return NextActivity;
var dest = ChooseHelipad(self);
var initialFacing = self.Info.Traits.Get<AircraftInfo>().InitialFacing;
if (dest == null)
{
var rearmBuildings = self.Info.Traits.Get<HelicopterInfo>().RearmBuildings;
var nearestHpad = self.World.ActorsWithTrait<Reservable>()
.Where(a => a.Actor.Owner == self.Owner && rearmBuildings.Contains(a.Actor.Info.Name))
.Select(a => a.Actor)
.ClosestTo(self);
if (nearestHpad == null)
return Util.SequenceActivities(new Turn(self, initialFacing), new HeliLand(true), NextActivity);
else
return Util.SequenceActivities(new HeliFly(self, Target.FromActor(nearestHpad)));
}
var res = dest.TraitOrDefault<Reservable>();
var heli = self.Trait<Helicopter>();
if (res != null)
{
heli.UnReserve();
heli.Reservation = res.Reserve(dest, self, heli);
}
var exit = dest.Info.Traits.WithInterface<ExitInfo>().FirstOrDefault();
var offset = (exit != null) ? exit.SpawnOffset : WVec.Zero;
return Util.SequenceActivities(
new HeliFly(self, Target.FromPos(dest.CenterPosition + offset)),
new Turn(self, initialFacing),
new HeliLand(false),
new ResupplyAircraft());
}
}
}

View File

@@ -0,0 +1,48 @@
#region Copyright & License Information
/*
* Copyright 2007-2014 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using OpenRA.Activities;
using OpenRA.Mods.Common.Traits;
using OpenRA.Traits;
namespace OpenRA.Mods.Common.Activities
{
public class Land : Activity
{
Target target;
public Land(Target t) { target = t; }
public override Activity Tick(Actor self)
{
if (!target.IsValidFor(self))
Cancel(self);
if (IsCanceled)
return NextActivity;
var plane = self.Trait<Plane>();
var d = target.CenterPosition - self.CenterPosition;
// The next move would overshoot, so just set the final position
var move = plane.FlyStep(plane.Facing);
if (d.HorizontalLengthSquared < move.HorizontalLengthSquared)
{
plane.SetPosition(self, target.CenterPosition);
return NextActivity;
}
var desiredFacing = Util.GetFacing(d, plane.Facing);
Fly.FlyToward(self, plane, desiredFacing, WRange.Zero);
return this;
}
}
}

View File

@@ -0,0 +1,35 @@
#region Copyright & License Information
/*
* Copyright 2007-2014 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using OpenRA.Activities;
using OpenRA.Mods.Common.Traits;
using OpenRA.Primitives;
using OpenRA.Traits;
namespace OpenRA.Mods.Common.Activities
{
public class ResupplyAircraft : Activity
{
public override Activity Tick(Actor self)
{
var aircraft = self.Trait<Aircraft>();
var host = aircraft.GetActorBelow();
if (host == null)
return NextActivity;
return Util.SequenceActivities(
aircraft.GetResupplyActivities(host).Append(NextActivity).ToArray());
}
}
}

View File

@@ -0,0 +1,127 @@
#region Copyright & License Information
/*
* Copyright 2007-2014 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using System;
using System.Linq;
using OpenRA.Activities;
using OpenRA.Mods.Common.Traits;
using OpenRA.Traits;
namespace OpenRA.Mods.Common.Activities
{
public class ReturnToBase : Activity
{
bool isCalculated;
Actor dest;
WPos w1, w2, w3;
public static Actor ChooseAirfield(Actor self, bool unreservedOnly)
{
var rearmBuildings = self.Info.Traits.Get<PlaneInfo>().RearmBuildings;
return self.World.ActorsWithTrait<Reservable>()
.Where(a => a.Actor.Owner == self.Owner)
.Where(a => rearmBuildings.Contains(a.Actor.Info.Name)
&& (!unreservedOnly || !Reservable.IsReserved(a.Actor)))
.Select(a => a.Actor)
.ClosestTo(self);
}
void Calculate(Actor self)
{
if (dest == null || Reservable.IsReserved(dest))
dest = ChooseAirfield(self, true);
if (dest == null)
return;
var plane = self.Trait<Plane>();
var planeInfo = self.Info.Traits.Get<PlaneInfo>();
var res = dest.TraitOrDefault<Reservable>();
if (res != null)
{
plane.UnReserve();
plane.Reservation = res.Reserve(dest, self, plane);
}
var landPos = dest.CenterPosition;
var altitude = planeInfo.CruiseAltitude.Range;
// Distance required for descent.
var landDistance = altitude * 1024 / plane.Info.MaximumPitch.Tan();
// Land towards the east
var approachStart = landPos + new WVec(-landDistance, 0, altitude);
// Add 10% to the turning radius to ensure we have enough room
var speed = plane.MovementSpeed * 32 / 35;
var turnRadius = (int)(141 * speed / planeInfo.ROT / (float)Math.PI);
// Find the center of the turning circles for clockwise and counterclockwise turns
var angle = WAngle.FromFacing(plane.Facing);
var fwd = -new WVec(angle.Sin(), angle.Cos(), 0);
// Work out whether we should turn clockwise or counter-clockwise for approach
var side = new WVec(-fwd.Y, fwd.X, fwd.Z);
var approachDelta = self.CenterPosition - approachStart;
var sideTowardBase = new[] { side, -side }
.MinBy(a => WVec.Dot(a, approachDelta));
// Calculate the tangent line that joins the turning circles at the current and approach positions
var cp = self.CenterPosition + turnRadius * sideTowardBase / 1024;
var posCenter = new WPos(cp.X, cp.Y, altitude);
var approachCenter = approachStart + new WVec(0, turnRadius * Math.Sign(self.CenterPosition.Y - approachStart.Y), 0);
var tangentDirection = approachCenter - posCenter;
var tangentOffset = new WVec(-tangentDirection.Y, tangentDirection.X, 0) * turnRadius / tangentDirection.Length;
// TODO: correctly handle CCW <-> CW turns
if (tangentOffset.X > 0)
tangentOffset = -tangentOffset;
w1 = posCenter + tangentOffset;
w2 = approachCenter + tangentOffset;
w3 = approachStart;
plane.RTBPathHash = w1 + (WVec)w2 + (WVec)w3;
isCalculated = true;
}
public ReturnToBase(Actor self, Actor dest)
{
this.dest = dest;
}
public override Activity Tick(Actor self)
{
if (IsCanceled || self.IsDead)
return NextActivity;
if (!isCalculated)
Calculate(self);
if (dest == null)
{
var nearestAfld = ChooseAirfield(self, false);
self.CancelActivity();
if (nearestAfld != null)
return Util.SequenceActivities(new Fly(self, Target.FromActor(nearestAfld)), new FlyCircle());
else
return new FlyCircle();
}
return Util.SequenceActivities(
new Fly(self, Target.FromPos(w1)),
new Fly(self, Target.FromPos(w2)),
new Fly(self, Target.FromPos(w3)),
new Land(Target.FromActor(dest)),
NextActivity);
}
}
}

View File

@@ -0,0 +1,42 @@
#region Copyright & License Information
/*
* Copyright 2007-2014 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using OpenRA.Activities;
using OpenRA.Mods.Common.Traits;
using OpenRA.Traits;
namespace OpenRA.Mods.Common.Activities
{
public class TakeOff : Activity
{
public override Activity Tick(Actor self)
{
var aircraft = self.Trait<Aircraft>();
self.CancelActivity();
var reservation = aircraft.Reservation;
if (reservation != null)
{
reservation.Dispose();
reservation = null;
}
var host = aircraft.GetActorBelow();
var hasHost = host != null;
var rp = hasHost ? host.TraitOrDefault<RallyPoint>() : null;
var destination = rp != null ? rp.Location :
(hasHost ? self.World.Map.CellContaining(host.CenterPosition) : self.Location);
return new AttackMoveActivity(self, self.Trait<IMove>().MoveTo(destination, 1));
}
}
}

View File

@@ -0,0 +1,80 @@
#region Copyright & License Information
/*
* Copyright 2007-2014 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using OpenRA.Activities;
using OpenRA.Mods.Common.Traits;
using OpenRA.Traits;
namespace OpenRA.Mods.Common.Activities
{
/* non-turreted attack */
public class Attack : Activity
{
protected readonly Target Target;
readonly AttackBase attack;
readonly IMove move;
readonly IFacing facing;
readonly WRange minRange;
readonly WRange maxRange;
readonly IPositionable positionable;
public Attack(Actor self, Target target, WRange minRange, WRange maxRange, bool allowMovement)
{
Target = target;
this.minRange = minRange;
this.maxRange = maxRange;
attack = self.Trait<AttackBase>();
facing = self.Trait<IFacing>();
positionable = self.Trait<IPositionable>();
move = allowMovement ? self.TraitOrDefault<IMove>() : null;
}
public override Activity Tick(Actor self)
{
var ret = InnerTick(self, attack);
attack.IsAttacking = ret == this;
return ret;
}
protected virtual Activity InnerTick(Actor self, AttackBase attack)
{
if (IsCanceled)
return NextActivity;
var type = Target.Type;
if (!Target.IsValidFor(self) || type == TargetType.FrozenActor)
return NextActivity;
if (attack.Info.AttackRequiresEnteringCell && !positionable.CanEnterCell(Target.Actor.Location, null, false))
return NextActivity;
// Drop the target if it moves under the shroud / fog.
// HACK: This would otherwise break targeting frozen actors
// The problem is that Shroud.IsTargetable returns false (as it should) for
// frozen actors, but we do want to explicitly target the underlying actor here.
if (type == TargetType.Actor && !Target.Actor.HasTrait<FrozenUnderFog>() && !self.Owner.Shroud.IsTargetable(Target.Actor))
return NextActivity;
// Try to move within range
if (move != null && (!Target.IsInRange(self.CenterPosition, maxRange) || Target.IsInRange(self.CenterPosition, minRange)))
return Util.SequenceActivities(move.MoveWithinRange(Target, minRange, maxRange), this);
var desiredFacing = Util.GetFacing(Target.CenterPosition - self.CenterPosition, 0);
if (facing.Facing != desiredFacing)
return Util.SequenceActivities(new Turn(self, desiredFacing), this);
attack.DoAttack(self, Target);
return this;
}
}
}

View File

@@ -0,0 +1,71 @@
#region Copyright & License Information
/*
* Copyright 2007-2014 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using System;
using OpenRA.Mods.Common.Traits;
using OpenRA.Traits;
namespace OpenRA.Mods.Common.Activities
{
class EnterTransport : Enter
{
readonly Actor transport;
readonly Passenger passenger;
readonly int maxTries;
Cargo cargo;
public EnterTransport(Actor self, Actor transport, int maxTries = 0, bool targetCenter = false)
: base(self, transport, maxTries, targetCenter)
{
this.transport = transport;
this.maxTries = maxTries;
cargo = transport.Trait<Cargo>();
passenger = self.Trait<Passenger>();
}
protected override void Unreserve(Actor self, bool abort) { passenger.Unreserve(self); }
protected override bool CanReserve(Actor self) { return cargo.Unloading || cargo.CanLoad(transport, self); }
protected override ReserveStatus Reserve(Actor self)
{
var status = base.Reserve(self);
if (status != ReserveStatus.Ready)
return status;
if (passenger.Reserve(self, cargo))
return ReserveStatus.Ready;
return ReserveStatus.Pending;
}
protected override void OnInside(Actor self)
{
self.World.AddFrameEndTask(w =>
{
if (self.IsDead || transport.IsDead || !cargo.CanLoad(transport, self))
return;
cargo.Load(transport, self);
w.Remove(self);
});
Done(self);
}
protected override bool TryGetAlternateTarget(Actor self, int tries, ref Target target)
{
if (tries > maxTries)
return false;
var type = target.Actor.Info.Name;
return TryGetAlternateTargetInCircle(
self, passenger.Info.AlternateTransportScanRange,
t => cargo = t.Actor.Trait<Cargo>(), // update cargo
a => { var c = a.TraitOrDefault<Cargo>(); return c != null && (c.Unloading || c.CanLoad(a, self)); },
new Func<Actor, bool>[] { a => a.Info.Name == type }); // Prefer transports of the same type
}
}
}

View File

@@ -0,0 +1,33 @@
#region Copyright & License Information
/*
* Copyright 2007-2014 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using OpenRA.Activities;
using OpenRA.Mods.Common.Traits;
using OpenRA.Traits;
namespace OpenRA.Mods.Common.Activities
{
public class Heal : Attack
{
public Heal(Actor self, Target target, WRange minRange, WRange maxRange, bool allowMovement)
: base(self, target, minRange, maxRange, allowMovement) { }
protected override Activity InnerTick(Actor self, AttackBase attack)
{
if (!Target.IsValidFor(self) || !self.Owner.IsAlliedWith(Target.Actor.Owner))
return NextActivity;
if (Target.Type == TargetType.Actor && Target.Actor.GetDamageState() == DamageState.Undamaged)
return NextActivity;
return base.InnerTick(self, attack);
}
}
}

View File

@@ -0,0 +1,64 @@
#region Copyright & License Information
/*
* Copyright 2007-2014 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using System.Collections.Generic;
using OpenRA.Activities;
using OpenRA.Mods.Common.Traits;
using OpenRA.Traits;
namespace OpenRA.Mods.Common.Activities
{
public class AttackMoveActivity : Activity
{
const int ScanInterval = 7;
Activity inner;
int scanTicks;
AutoTarget autoTarget;
public AttackMoveActivity(Actor self, Activity inner)
{
this.inner = inner;
autoTarget = self.TraitOrDefault<AutoTarget>();
}
public override Activity Tick(Actor self)
{
if (autoTarget != null && --scanTicks <= 0)
{
autoTarget.ScanAndAttack(self);
scanTicks = ScanInterval;
}
if (inner == null)
return NextActivity;
inner = Util.RunActivity(self, inner);
return this;
}
public override void Cancel(Actor self)
{
if (inner != null)
inner.Cancel(self);
base.Cancel(self);
}
public override IEnumerable<Target> GetTargets(Actor self)
{
if (inner != null)
return inner.GetTargets(self);
return Target.None;
}
}
}

View File

@@ -0,0 +1,50 @@
#region Copyright & License Information
/*
* Copyright 2007-2014 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using OpenRA.Activities;
using OpenRA.Traits;
namespace OpenRA.Mods.Common.Activities
{
public class Follow : Activity
{
readonly Target target;
readonly WRange minRange;
readonly WRange maxRange;
readonly IMove move;
public Follow(Actor self, Target target, WRange minRange, WRange maxRange)
{
this.target = target;
this.minRange = minRange;
this.maxRange = maxRange;
move = self.Trait<IMove>();
}
public override Activity Tick(Actor self)
{
if (IsCanceled || !target.IsValidFor(self))
return NextActivity;
var cachedPosition = target.CenterPosition;
var path = move.MoveWithinRange(target, minRange, maxRange);
// We are already in range, so wait until the target moves before doing anything
if (target.IsInRange(self.CenterPosition, maxRange) && !target.IsInRange(self.CenterPosition, minRange))
{
var wait = new WaitFor(() => !target.IsValidFor(self) || target.CenterPosition != cachedPosition);
return Util.SequenceActivities(wait, path, this);
}
return Util.SequenceActivities(path, this);
}
}
}

View File

@@ -0,0 +1,451 @@
#region Copyright & License Information
/*
* Copyright 2007-2014 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using OpenRA.Activities;
using OpenRA.Mods.Common.Traits;
using OpenRA.Primitives;
using OpenRA.Traits;
namespace OpenRA.Mods.Common.Activities
{
public class Move : Activity
{
static readonly List<CPos> NoPath = new List<CPos>();
readonly Mobile mobile;
readonly IEnumerable<IDisableMove> moveDisablers;
readonly WRange nearEnough;
readonly Func<List<CPos>> getPath;
readonly Actor ignoredActor;
List<CPos> path;
CPos? destination;
// For dealing with blockers
bool hasWaited;
bool hasNotifiedBlocker;
int waitTicksRemaining;
// Scriptable move order
// Ignores lane bias and nearby units
public Move(Actor self, CPos destination)
{
mobile = self.Trait<Mobile>();
moveDisablers = self.TraitsImplementing<IDisableMove>();
getPath = () =>
self.World.WorldActor.Trait<PathFinder>().FindPath(
PathSearch.FromPoint(self.World, mobile.Info, self, mobile.toCell, destination, false)
.WithoutLaneBias());
this.destination = destination;
this.nearEnough = WRange.Zero;
}
// HACK: for legacy code
public Move(Actor self, CPos destination, int nearEnough)
: this(self, destination, WRange.FromCells(nearEnough)) { }
public Move(Actor self, CPos destination, WRange nearEnough)
{
mobile = self.Trait<Mobile>();
moveDisablers = self.TraitsImplementing<IDisableMove>();
getPath = () => self.World.WorldActor.Trait<PathFinder>()
.FindUnitPath(mobile.toCell, destination, self);
this.destination = destination;
this.nearEnough = nearEnough;
}
public Move(Actor self, CPos destination, SubCell subCell, WRange nearEnough)
{
mobile = self.Trait<Mobile>();
moveDisablers = self.TraitsImplementing<IDisableMove>();
getPath = () => self.World.WorldActor.Trait<PathFinder>()
.FindUnitPathToRange(mobile.fromCell, subCell, self.World.Map.CenterOfSubCell(destination, subCell), nearEnough, self);
this.destination = destination;
this.nearEnough = nearEnough;
}
public Move(Actor self, CPos destination, Actor ignoredActor)
{
mobile = self.Trait<Mobile>();
moveDisablers = self.TraitsImplementing<IDisableMove>();
getPath = () =>
self.World.WorldActor.Trait<PathFinder>().FindPath(
PathSearch.FromPoint(self.World, mobile.Info, self, mobile.toCell, destination, false)
.WithIgnoredActor(ignoredActor));
this.destination = destination;
this.nearEnough = WRange.Zero;
this.ignoredActor = ignoredActor;
}
public Move(Actor self, Target target, WRange range)
{
mobile = self.Trait<Mobile>();
moveDisablers = self.TraitsImplementing<IDisableMove>();
getPath = () =>
{
if (!target.IsValidFor(self))
return NoPath;
return self.World.WorldActor.Trait<PathFinder>().FindUnitPathToRange(
mobile.toCell, mobile.toSubCell, target.CenterPosition, range, self);
};
destination = null;
nearEnough = range;
}
public Move(Actor self, Func<List<CPos>> getPath)
{
mobile = self.Trait<Mobile>();
moveDisablers = self.TraitsImplementing<IDisableMove>();
this.getPath = getPath;
destination = null;
nearEnough = WRange.Zero;
}
static int HashList<T>(List<T> xs)
{
var hash = 0;
var n = 0;
foreach (var x in xs)
hash += n++ * x.GetHashCode();
return hash;
}
List<CPos> EvalPath(Actor self, Mobile mobile)
{
var path = getPath().TakeWhile(a => a != mobile.toCell).ToList();
mobile.PathHash = HashList(path);
return path;
}
public override Activity Tick(Actor self)
{
if (moveDisablers.Any(d => d.MoveDisabled(self)))
return this;
if (destination == mobile.toCell)
return NextActivity;
if (path == null)
{
if (mobile.ticksBeforePathing > 0)
{
--mobile.ticksBeforePathing;
return this;
}
path = EvalPath(self, mobile);
SanityCheckPath(mobile);
}
if (path.Count == 0)
{
destination = mobile.toCell;
return this;
}
destination = path[0];
var nextCell = PopPath(self, mobile);
if (nextCell == null)
return this;
var firstFacing = self.World.Map.FacingBetween(mobile.fromCell, nextCell.Value.First, mobile.Facing);
if (firstFacing != mobile.Facing)
{
path.Add(nextCell.Value.First);
return Util.SequenceActivities(new Turn(self, firstFacing), this);
}
else
{
mobile.SetLocation(mobile.fromCell, mobile.fromSubCell, nextCell.Value.First, nextCell.Value.Second);
var move = new MoveFirstHalf(
this,
self.World.Map.CenterOfSubCell(mobile.fromCell, mobile.fromSubCell),
Util.BetweenCells(self.World, mobile.fromCell, mobile.toCell) + (self.World.Map.OffsetOfSubCell(mobile.fromSubCell) + self.World.Map.OffsetOfSubCell(mobile.toSubCell)) / 2,
mobile.Facing,
mobile.Facing,
0);
return move;
}
}
[Conditional("SANITY_CHECKS")]
void SanityCheckPath(Mobile mobile)
{
if (path.Count == 0)
return;
var d = path[path.Count - 1] - mobile.toCell;
if (d.LengthSquared > 2)
throw new InvalidOperationException("(Move) Sanity check failed");
}
static void NotifyBlocker(Actor self, CPos nextCell)
{
foreach (var blocker in self.World.ActorMap.GetUnitsAt(nextCell))
{
// Notify the blocker that he's blocking our move:
foreach (var moveBlocked in blocker.TraitsImplementing<INotifyBlockingMove>())
moveBlocked.OnNotifyBlockingMove(blocker, self);
}
}
Pair<CPos, SubCell>? PopPath(Actor self, Mobile mobile)
{
if (path.Count == 0)
return null;
var nextCell = path[path.Count - 1];
// Next cell in the move is blocked by another actor
if (!mobile.CanEnterCell(nextCell, ignoredActor, true))
{
// Are we close enough?
var cellRange = nearEnough.Range / 1024;
if ((mobile.toCell - destination.Value).LengthSquared <= cellRange * cellRange)
{
path.Clear();
return null;
}
// See if they will move
if (!hasNotifiedBlocker)
{
NotifyBlocker(self, nextCell);
hasNotifiedBlocker = true;
}
// Wait a bit to see if they leave
if (!hasWaited)
{
var info = self.Info.Traits.Get<MobileInfo>();
waitTicksRemaining = info.WaitAverage + self.World.SharedRandom.Next(-info.WaitSpread, info.WaitSpread);
hasWaited = true;
}
if (--waitTicksRemaining >= 0)
return null;
if (mobile.ticksBeforePathing > 0)
{
--mobile.ticksBeforePathing;
return null;
}
// Calculate a new path
mobile.RemoveInfluence();
var newPath = EvalPath(self, mobile);
mobile.AddInfluence();
if (newPath.Count != 0)
path = newPath;
return null;
}
hasNotifiedBlocker = false;
hasWaited = false;
path.RemoveAt(path.Count - 1);
var subCell = mobile.GetAvailableSubCell(nextCell, SubCell.Any, ignoredActor);
return Pair.New(nextCell, subCell);
}
public override void Cancel(Actor self)
{
path = NoPath;
base.Cancel(self);
}
public override IEnumerable<Target> GetTargets(Actor self)
{
if (path != null)
return Enumerable.Reverse(path).Select(c => Target.FromCell(self.World, c));
if (destination != null)
return new Target[] { Target.FromCell(self.World, destination.Value) };
return Target.None;
}
abstract class MovePart : Activity
{
protected readonly Move move;
protected readonly WPos from, to;
protected readonly int fromFacing, toFacing;
protected readonly int moveFractionTotal;
protected int moveFraction;
public MovePart(Move move, WPos from, WPos to, int fromFacing, int toFacing, int startingFraction)
{
this.move = move;
this.from = from;
this.to = to;
this.fromFacing = fromFacing;
this.toFacing = toFacing;
this.moveFraction = startingFraction;
this.moveFractionTotal = (to - from).Length;
}
public override void Cancel(Actor self)
{
move.Cancel(self);
base.Cancel(self);
}
public override void Queue(Activity activity)
{
move.Queue(activity);
}
public override Activity Tick(Actor self)
{
var mobile = self.Trait<Mobile>();
var ret = InnerTick(self, move.mobile);
mobile.IsMoving = ret is MovePart;
if (moveFraction > moveFractionTotal)
moveFraction = moveFractionTotal;
UpdateCenterLocation(self, mobile);
return ret;
}
Activity InnerTick(Actor self, Mobile mobile)
{
moveFraction += mobile.MovementSpeedForCell(self, mobile.toCell);
if (moveFraction <= moveFractionTotal)
return this;
var next = OnComplete(self, mobile, move);
if (next != null)
return next;
return move;
}
void UpdateCenterLocation(Actor self, Mobile mobile)
{
// avoid division through zero
if (moveFractionTotal != 0)
mobile.SetVisualPosition(self, WPos.Lerp(from, to, moveFraction, moveFractionTotal));
else
mobile.SetVisualPosition(self, to);
if (moveFraction >= moveFractionTotal)
mobile.Facing = toFacing & 0xFF;
else
mobile.Facing = int2.Lerp(fromFacing, toFacing, moveFraction, moveFractionTotal) & 0xFF;
}
protected abstract MovePart OnComplete(Actor self, Mobile mobile, Move parent);
public override IEnumerable<Target> GetTargets(Actor self)
{
return move.GetTargets(self);
}
}
class MoveFirstHalf : MovePart
{
public MoveFirstHalf(Move move, WPos from, WPos to, int fromFacing, int toFacing, int startingFraction)
: base(move, from, to, fromFacing, toFacing, startingFraction) { }
static bool IsTurn(Mobile mobile, CPos nextCell)
{
return nextCell - mobile.toCell !=
mobile.toCell - mobile.fromCell;
}
protected override MovePart OnComplete(Actor self, Mobile mobile, Move parent)
{
var fromSubcellOffset = self.World.Map.OffsetOfSubCell(mobile.fromSubCell);
var toSubcellOffset = self.World.Map.OffsetOfSubCell(mobile.toSubCell);
var nextCell = parent.PopPath(self, mobile);
if (nextCell != null)
{
if (IsTurn(mobile, nextCell.Value.First))
{
var nextSubcellOffset = self.World.Map.OffsetOfSubCell(nextCell.Value.Second);
var ret = new MoveFirstHalf(
move,
Util.BetweenCells(self.World, mobile.fromCell, mobile.toCell) + (fromSubcellOffset + toSubcellOffset) / 2,
Util.BetweenCells(self.World, mobile.toCell, nextCell.Value.First) + (toSubcellOffset + nextSubcellOffset) / 2,
mobile.Facing,
Util.GetNearestFacing(mobile.Facing, self.World.Map.FacingBetween(mobile.toCell, nextCell.Value.First, mobile.Facing)),
moveFraction - moveFractionTotal);
mobile.FinishedMoving(self);
mobile.SetLocation(mobile.toCell, mobile.toSubCell, nextCell.Value.First, nextCell.Value.Second);
return ret;
}
parent.path.Add(nextCell.Value.First);
}
var ret2 = new MoveSecondHalf(
move,
Util.BetweenCells(self.World, mobile.fromCell, mobile.toCell) + (fromSubcellOffset + toSubcellOffset) / 2,
self.World.Map.CenterOfCell(mobile.toCell) + toSubcellOffset,
mobile.Facing,
mobile.Facing,
moveFraction - moveFractionTotal);
mobile.EnteringCell(self);
mobile.SetLocation(mobile.toCell, mobile.toSubCell, mobile.toCell, mobile.toSubCell);
return ret2;
}
}
class MoveSecondHalf : MovePart
{
public MoveSecondHalf(Move move, WPos from, WPos to, int fromFacing, int toFacing, int startingFraction)
: base(move, from, to, fromFacing, toFacing, startingFraction) { }
protected override MovePart OnComplete(Actor self, Mobile mobile, Move parent)
{
mobile.SetPosition(self, mobile.toCell);
return null;
}
}
}
public static class ActorExtensionsForMove
{
public static bool IsMoving(this Actor self)
{
var a = self.GetCurrentActivity();
if (a == null)
return false;
// HACK: Dirty, but it suffices until we do something better:
if (a.GetType() == typeof(Move)) return true;
if (a.GetType() == typeof(MoveAdjacentTo)) return true;
if (a.GetType() == typeof(AttackMoveActivity)) return true;
// Not a move:
return false;
}
}
}

View File

@@ -0,0 +1,144 @@
#region Copyright & License Information
/*
* Copyright 2007-2014 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using OpenRA.Activities;
using OpenRA.Mods.Common.Traits;
using OpenRA.Traits;
namespace OpenRA.Mods.Common.Activities
{
public class MoveAdjacentTo : Activity
{
static readonly List<CPos> NoPath = new List<CPos>();
readonly Mobile mobile;
readonly PathFinder pathFinder;
readonly DomainIndex domainIndex;
readonly uint movementClass;
protected Target target { get; private set; }
protected CPos targetPosition;
Activity inner;
bool repath;
public MoveAdjacentTo(Actor self, Target target)
{
this.target = target;
mobile = self.Trait<Mobile>();
pathFinder = self.World.WorldActor.Trait<PathFinder>();
domainIndex = self.World.WorldActor.Trait<DomainIndex>();
movementClass = (uint)mobile.Info.GetMovementClass(self.World.TileSet);
if (target.IsValidFor(self))
targetPosition = self.World.Map.CellContaining(target.CenterPosition);
repath = true;
}
protected virtual bool ShouldStop(Actor self, CPos oldTargetPosition)
{
return false;
}
protected virtual bool ShouldRepath(Actor self, CPos oldTargetPosition)
{
return targetPosition != oldTargetPosition;
}
protected virtual IEnumerable<CPos> CandidateMovementCells(Actor self)
{
return Util.AdjacentCells(self.World, target);
}
public override Activity Tick(Actor self)
{
var targetIsValid = target.IsValidFor(self);
// Inner move order has completed.
if (inner == null)
{
// We are done here if the order was cancelled for any
// reason except the target moving.
if (IsCanceled || !repath || !targetIsValid)
return NextActivity;
// Target has moved, and MoveAdjacentTo is still valid.
inner = mobile.MoveTo(() => CalculatePathToTarget(self));
repath = false;
}
if (targetIsValid)
{
// Check if the target has moved
var oldTargetPosition = targetPosition;
targetPosition = self.World.Map.CellContaining(target.CenterPosition);
var shouldStop = ShouldStop(self, oldTargetPosition);
if (shouldStop || (!repath && ShouldRepath(self, oldTargetPosition)))
{
// Finish moving into the next cell and then repath.
if (inner != null)
inner.Cancel(self);
repath = !shouldStop;
}
}
else
{
// Target became invalid. Move to its last known position.
target = Target.FromCell(self.World, targetPosition);
}
// Ticks the inner move activity to actually move the actor.
inner = Util.RunActivity(self, inner);
return this;
}
List<CPos> CalculatePathToTarget(Actor self)
{
var targetCells = CandidateMovementCells(self);
var searchCells = new List<CPos>();
var loc = self.Location;
foreach (var cell in targetCells)
if (domainIndex.IsPassable(loc, cell, movementClass) && mobile.CanEnterCell(cell))
searchCells.Add(cell);
if (!searchCells.Any())
return NoPath;
var fromSrc = PathSearch.FromPoints(self.World, mobile.Info, self, searchCells, loc, true);
var fromDest = PathSearch.FromPoint(self.World, mobile.Info, self, loc, targetPosition, true).Reverse();
return pathFinder.FindBidiPath(fromSrc, fromDest);
}
public override IEnumerable<Target> GetTargets(Actor self)
{
if (inner != null)
return inner.GetTargets(self);
return Target.None;
}
public override void Cancel(Actor self)
{
if (inner != null)
inner.Cancel(self);
base.Cancel(self);
}
}
}

View File

@@ -0,0 +1,62 @@
#region Copyright & License Information
/*
* Copyright 2007-2014 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using System.Collections.Generic;
using System.Linq;
using OpenRA.Activities;
using OpenRA.Mods.Common.Traits;
using OpenRA.Traits;
namespace OpenRA.Mods.Common.Activities
{
public class MoveWithinRange : MoveAdjacentTo
{
readonly WRange maxRange;
readonly WRange minRange;
public MoveWithinRange(Actor self, Target target, WRange minRange, WRange maxRange)
: base(self, target)
{
this.minRange = minRange;
this.maxRange = maxRange;
}
protected override bool ShouldStop(Actor self, CPos oldTargetPosition)
{
// We are now in range. Don't move any further!
// HACK: This works around the pathfinder not returning the shortest path
var cp = self.CenterPosition;
return target.IsInRange(cp, maxRange) && !target.IsInRange(cp, minRange);
}
protected override bool ShouldRepath(Actor self, CPos oldTargetPosition)
{
var cp = self.CenterPosition;
return targetPosition != oldTargetPosition && (!target.IsInRange(cp, maxRange) || target.IsInRange(cp, minRange));
}
protected override IEnumerable<CPos> CandidateMovementCells(Actor self)
{
var map = self.World.Map;
var maxCells = (maxRange.Range + 1023) / 1024;
var minCells = minRange.Range / 1024;
var outerSq = maxRange.Range * maxRange.Range;
var innerSq = minRange.Range * minRange.Range;
var center = target.CenterPosition;
return map.FindTilesInAnnulus(targetPosition, minCells + 1, maxCells).Where(c =>
{
var dxSq = (map.CenterOfCell(c) - center).HorizontalLengthSquared;
return dxSq >= innerSq && dxSq <= outerSq;
});
}
}
}

View File

@@ -0,0 +1,60 @@
#region Copyright & License Information
/*
* Copyright 2007-2014 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using System.Linq;
using OpenRA.Activities;
using OpenRA.Mods.Common.Traits;
using OpenRA.Traits;
namespace OpenRA.Mods.Common.Activities
{
public class Rearm : Activity
{
readonly LimitedAmmo limitedAmmo;
int ticksPerPip = 25 * 2;
int remainingTicks = 25 * 2;
string sound = null;
public Rearm(Actor self, string sound = null)
{
limitedAmmo = self.TraitOrDefault<LimitedAmmo>();
if (limitedAmmo != null)
ticksPerPip = limitedAmmo.ReloadTimePerAmmo();
remainingTicks = ticksPerPip;
this.sound = sound;
}
public override Activity Tick(Actor self)
{
if (IsCanceled || limitedAmmo == null)
return NextActivity;
if (--remainingTicks == 0)
{
var hostBuilding = self.World.ActorMap.GetUnitsAt(self.Location)
.FirstOrDefault(a => a.HasTrait<RenderBuilding>());
if (hostBuilding == null || !hostBuilding.IsInWorld)
return NextActivity;
if (!limitedAmmo.GiveAmmo())
return NextActivity;
hostBuilding.Trait<RenderBuilding>().PlayCustomAnim(hostBuilding, "active");
if (sound != null)
Sound.Play(sound, self.CenterPosition);
remainingTicks = limitedAmmo.ReloadTimePerAmmo();
}
return this;
}
}
}

View File

@@ -0,0 +1,63 @@
#region Copyright & License Information
/*
* Copyright 2007-2014 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using System;
using OpenRA.Activities;
using OpenRA.Mods.Common.Traits;
using OpenRA.Traits;
namespace OpenRA.Mods.Common.Activities
{
public class Repair : Activity
{
int remainingTicks;
Actor host;
Health health;
public Repair(Actor host) { this.host = host; }
public override Activity Tick(Actor self)
{
if (IsCanceled) return NextActivity;
if (host == null || !host.IsInWorld) return NextActivity;
health = self.TraitOrDefault<Health>();
if (health == null) return NextActivity;
if (health.DamageState == DamageState.Undamaged)
return NextActivity;
if (remainingTicks == 0)
{
var repairsUnits = host.Info.Traits.Get<RepairsUnitsInfo>();
var unitCost = self.Info.Traits.Get<ValuedInfo>().Cost;
var hpToRepair = repairsUnits.HpPerStep;
var cost = Math.Max(1, (hpToRepair * unitCost * repairsUnits.ValuePercentage) / (health.MaxHP * 100));
if (!self.Owner.PlayerActor.Trait<PlayerResources>().TakeCash(cost))
{
remainingTicks = 1;
return this;
}
self.InflictDamage(self, -hpToRepair, null);
foreach (var depot in host.TraitsImplementing<INotifyRepair>())
depot.Repairing(self, host);
remainingTicks = repairsUnits.Interval;
}
else
--remainingTicks;
return this;
}
}
}

View File

@@ -0,0 +1,103 @@
#region Copyright & License Information
/*
* Copyright 2007-2014 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using OpenRA.Activities;
using OpenRA.Mods.Common.Traits;
using OpenRA.Primitives;
using OpenRA.Traits;
namespace OpenRA.Mods.Common.Activities
{
public class UnloadCargo : Activity
{
readonly Actor self;
readonly Cargo cargo;
readonly Cloak cloak;
readonly bool unloadAll;
public UnloadCargo(Actor self, bool unloadAll)
{
this.self = self;
cargo = self.Trait<Cargo>();
cloak = self.TraitOrDefault<Cloak>();
this.unloadAll = unloadAll;
}
public Pair<CPos, SubCell>? ChooseExitSubCell(Actor passenger)
{
var pos = passenger.Trait<IPositionable>();
return cargo.CurrentAdjacentCells
.Shuffle(self.World.SharedRandom)
.Select(c => Pair.New(c, pos.GetAvailableSubCell(c)))
.Cast<Pair<CPos, SubCell>?>()
.FirstOrDefault(s => s.Value.Second != SubCell.Invalid);
}
IEnumerable<CPos> BlockedExitCells(Actor passenger)
{
var pos = passenger.Trait<IPositionable>();
// Find the cells that are blocked by transient actors
return cargo.CurrentAdjacentCells
.Where(c => pos.CanEnterCell(c, null, true) != pos.CanEnterCell(c, null, false));
}
public override Activity Tick(Actor self)
{
cargo.Unloading = false;
if (IsCanceled || cargo.IsEmpty(self))
return NextActivity;
if (cloak != null && cloak.Info.UncloakOnUnload)
cloak.Uncloak();
var actor = cargo.Peek(self);
var spawn = self.CenterPosition;
var exitSubCell = ChooseExitSubCell(actor);
if (exitSubCell == null)
{
foreach (var blocker in BlockedExitCells(actor).SelectMany(p => self.World.ActorMap.GetUnitsAt(p)))
{
foreach (var nbm in blocker.TraitsImplementing<INotifyBlockingMove>())
nbm.OnNotifyBlockingMove(blocker, self);
}
return Util.SequenceActivities(new Wait(10), this);
}
cargo.Unload(self);
self.World.AddFrameEndTask(w =>
{
if (actor.Destroyed)
return;
var move = actor.Trait<IMove>();
var pos = actor.Trait<IPositionable>();
actor.CancelActivity();
pos.SetVisualPosition(actor, spawn);
actor.QueueActivity(move.MoveIntoWorld(actor, exitSubCell.Value.First, exitSubCell.Value.Second));
actor.SetTargetLine(Target.FromCell(w, exitSubCell.Value.First, exitSubCell.Value.Second), Color.Green, false);
w.Add(actor);
});
if (!unloadAll || cargo.IsEmpty(self))
return NextActivity;
cargo.Unloading = true;
return this;
}
}
}