* Maintains lists of claims, and only restricts reservations for friendly units. * Removes OnNotifyResourceClaimLost; it's not clear whether that is still useful, and it prevents future necessary cleanups. * Moves other code without changing behaviour. This fixed stale claims from dead units and enemy claims from preventing otherwise valid harvest activities.
74 lines
2.2 KiB
C#
74 lines
2.2 KiB
C#
#region Copyright & License Information
|
|
/*
|
|
* Copyright 2007-2017 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, either version 3 of
|
|
* the License, or (at your option) any later version. For more
|
|
* information, see COPYING.
|
|
*/
|
|
#endregion
|
|
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using OpenRA.Graphics;
|
|
using OpenRA.Traits;
|
|
|
|
namespace OpenRA.Mods.Common.Traits
|
|
{
|
|
[Desc("Allows harvesters to coordinate their operations. Attach this to the world actor.")]
|
|
public sealed class ResourceClaimLayerInfo : TraitInfo<ResourceClaimLayer> { }
|
|
|
|
public sealed class ResourceClaimLayer
|
|
{
|
|
readonly Dictionary<CPos, List<Actor>> claimByCell = new Dictionary<CPos, List<Actor>>(32);
|
|
readonly Dictionary<Actor, CPos> claimByActor = new Dictionary<Actor, CPos>(32);
|
|
|
|
/// <summary>
|
|
/// Attempt to reserve the resource in a cell for the given actor.
|
|
/// </summary>
|
|
public bool TryClaimCell(Actor claimer, CPos cell)
|
|
{
|
|
var claimers = claimByCell.GetOrAdd(cell);
|
|
|
|
// Clean up any stale claims
|
|
claimers.RemoveAll(a => a.IsDead);
|
|
|
|
// Prevent harvesters from the player or their allies fighting over the same cell
|
|
if (claimers.Any(c => c != claimer && claimer.Owner.IsAlliedWith(c.Owner)))
|
|
return false;
|
|
|
|
// Remove the actor's last claim, if it has one
|
|
CPos lastClaim;
|
|
if (claimByActor.TryGetValue(claimer, out lastClaim))
|
|
claimByCell.GetOrAdd(lastClaim).Remove(claimer);
|
|
|
|
claimers.Add(claimer);
|
|
claimByActor[claimer] = cell;
|
|
return true;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Returns false if the cell is already reserved by an allied actor.
|
|
/// </summary>
|
|
public bool CanClaimCell(Actor claimer, CPos cell)
|
|
{
|
|
return !claimByCell.GetOrAdd(cell)
|
|
.Any(c => c != claimer && !c.IsDead && claimer.Owner.IsAlliedWith(c.Owner));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Release the last resource claim made by this actor.
|
|
/// </summary>
|
|
/// <param name="claimer"></param>
|
|
public void RemoveClaim(Actor claimer)
|
|
{
|
|
CPos lastClaim;
|
|
if (claimByActor.TryGetValue(claimer, out lastClaim))
|
|
claimByCell.GetOrAdd(lastClaim).Remove(claimer);
|
|
|
|
claimByActor.Remove(claimer);
|
|
}
|
|
}
|
|
}
|