ModernUO/Projects/UOContent/Engines/ML Quests/Objectives/EscortObjective.cs
Kamron Batman 9b554f69b0
feat(timers): Adds timer pooling, fixes timer related bugs, and changes timer api (#667)
### Changes/Fixes:
* Adds timer pooling.
* Allows pool to be configurable in ModernUO.json
* Pool replenishes itself asynchronously if depleted.
* Fixes an issue with barkeeps and town criers
* Fixes an issue with incognito buff icons not being removed
* Fixes an issue with polymorph name mod not being removed
* Fixes several places where timers go on forever even after an object is deleted, keeping a reference (memory leak)
* Eliminates the timer for MiningCart altogether.
* Deletes `AcidSlime` since it is a duplicate of `PoolOfAcid`
* Fixes HonorableExecution and standardizes the code for other Bushido moves.

## Changes to the Timer API:
```cs
public class Timer
{
  // Creates a timer that will be returned to the pool once execution stops.
  public static void StartTimer(Action callback);
  public static void StartTimer(TimeSpan delay, Action callback);
  public static void StartTimer(TimeSpan delay, TimeSpan interval, Action callback);
  public static void StartTimer(TimeSpan interval, int count, Action callback);
  public static void StartTimer(TimeSpan delay, TimeSpan interval, int count, Action callback);

  // Creates a timer and returns a token for more control. Requires manual cancellation in order for the timer to be returned to the pool.
  // If the token is dereferenced, the timer will be dereferenced too. While not returning a timer to the pool is not considered hazardous, it does defeat the purpose of pooled timers.
  public static void StartTimer(Action callback, out TimerExecutionToken token);
  public static void StartTimer(TimeSpan delay, Action callback, out TimerExecutionToken token);
  public static void StartTimer(TimeSpan delay, TimeSpan interval, Action callback, out TimerExecutionToken token);
  public static void StartTimer(TimeSpan interval, int count, Action callback, out TimerExecutionToken token);
  public static void StartTimer(TimeSpan delay, TimeSpan interval, int count, Action callback, out TimerExecutionToken token);

  // If you aren't sure how to use the API above, or you don't care about performance, then you can use the old RunUO Timer.DelayCall
  public static DelayCallTimer DelayCall(Action callback);
  public static DelayCallTimer DelayCall(TimeSpan delay, Action callback);
  public static DelayCallTimer DelayCall(TimeSpan delay, TimeSpan interval, Action callback);
  public static DelayCallTimer DelayCall(TimeSpan interval, int count, Action callback);
  public static DelayCallTimer DelayCall(TimeSpan delay, TimeSpan interval, int count, Action callback);
}

public struct TimerExecutionToken
{
  public bool Running { get; }
  public int Index { get; }
  public int RemainingCount { get; }
  public DateTime Next { get; }
}
```

## When to use `TimerExecutionToken`?
Use tokens when you want to gain the performance benefit of using a pooled timer, but you need one of the following:
* Access to the next time the timer will tick:`token.Next`
* Access to which interval, how many intervals there are, or how many are remaining: `token.Index`, `token.Count`, and `token.RemainingCount`
* Stop a timer manually.
* Determine if the timer is running: `timer.Running`
* See notes below about requirements for using tokens!

## Notes about using the TimerExecutionToken:
When you opt-in to receive a token, you must call `Cancel()` to return the timer. This can be done inside of the callback, or outside of the callback at any time.
If this is not called and your timer is an infinite interval, then you will create a potential memory leak, or null pointer exception in your callback.
If the timer ends and is stopped, but cancel is not called, then the timer will never return to the pool and stay referenced until the token is deleted or cancel is called. (Memory leak)

## Is this thread safe?
No. The ModernUO timer system is not thread safe at all. If you require a thread safe timer system, contact me and I'll help adapt this system. Keep in mind that there is a massive performance hit to make this thread safe when there are literally no use cases for it.

If you need to synchronize execution, meaning you want to execute code from another thread on the core thread. Let's say you have a discord bot that is pushing commands to the game server. Then use `EventLoopContext.Post(SendOrPostCallback callback, object state);`.
2021-08-07 14:33:35 -07:00

305 lines
8.7 KiB
C#

using System;
using Server.Gumps;
using Server.Misc;
using Server.Mobiles;
namespace Server.Engines.MLQuests.Objectives
{
public class EscortObjective : BaseObjective
{
public EscortObjective(QuestArea destination = null) => Destination = destination;
public QuestArea Destination { get; set; }
public override bool CanOffer(IQuestGiver quester, PlayerMobile pm, bool message)
{
if (quester is BaseCreature creature && creature.Controlled ||
quester is BaseEscortable escortable && escortable.IsBeingDeleted)
{
return false;
}
var context = MLQuestSystem.GetContext(pm);
if (context != null)
{
foreach (var instance in context.QuestInstances)
{
if (instance.Quest.IsEscort)
{
if (message)
{
MLQuestSystem.Tell(quester, pm, 500896); // I see you already have an escort.
}
return false;
}
}
}
var nextEscort = pm.LastEscortTime + BaseEscortable.EscortDelay;
if (nextEscort > Core.Now)
{
if (message)
{
var minutes = (int)Math.Ceiling((nextEscort - Core.Now).TotalMinutes);
if (minutes == 1)
{
MLQuestSystem.Tell(quester, pm, "You must rest 1 minute before we set out on this journey.");
}
else
{
MLQuestSystem.Tell(
quester,
pm,
1071195,
minutes.ToString()
); // You must rest ~1_minsleft~ minutes before we set out on this journey.
}
}
return false;
}
return true;
}
public override void WriteToGump(Gump g, ref int y)
{
g.AddHtmlLocalized(98, y, 312, 16, 1072206, 0x15F90); // Escort to
if (Destination.Name.Number > 0)
{
g.AddHtmlLocalized(173, y, 312, 20, Destination.Name.Number, 0xFFFFFF);
}
else if (Destination.Name.String != null)
{
g.AddLabel(173, y, 0x481, Destination.Name.String);
}
y += 16;
}
public override BaseObjectiveInstance CreateInstance(MLQuestInstance instance)
{
if (instance == null || Destination == null)
{
return null;
}
return new EscortObjectiveInstance(this, instance);
}
}
public class EscortObjectiveInstance : BaseObjectiveInstance
{
private readonly BaseCreature m_Escort;
private readonly EscortObjective m_Objective;
private DateTime m_LastSeenEscorter;
private TimerExecutionToken _timerToken;
public EscortObjectiveInstance(EscortObjective objective, MLQuestInstance instance)
: base(instance, objective)
{
m_Objective = objective;
HasCompleted = false;
Timer.StartTimer(TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(5), CheckDestination, out _timerToken);
m_LastSeenEscorter = Core.Now;
m_Escort = instance.Quester as BaseCreature;
if (MLQuestSystem.Debug && m_Escort == null && instance.Quester != null)
{
Console.WriteLine(
"Warning: EscortObjective is not supported for type '{0}'",
instance.Quester.GetType().Name
);
}
}
public bool HasCompleted { get; set; }
public override DataType ExtraDataType => DataType.EscortObjective;
public override bool IsCompleted() => HasCompleted;
private void CheckDestination()
{
if (m_Escort == null || HasCompleted) // Completed by deserialization
{
StopTimer();
return;
}
var instance = Instance;
var pm = instance.Player;
if (instance.Removed)
{
Abandon();
}
else if (m_Objective.Destination.Contains(m_Escort))
{
m_Escort.Say(
1042809,
pm.Name
); // We have arrived! I thank thee, ~1_PLAYER_NAME~! I have no further need of thy services. Here is thy pay.
if (pm.Young || m_Escort.Region.IsPartOf("Haven Island"))
{
Titles.AwardFame(pm, 10, true);
}
else
{
VirtueHelper.AwardVirtue(
pm,
VirtueName.Compassion,
m_Escort is BaseEscortable escortable && escortable.IsPrisoner ? 400 : 200
);
}
EndFollow(m_Escort);
StopTimer();
HasCompleted = true;
CheckComplete();
// Auto claim reward
MLQuestSystem.OnDoubleClick(m_Escort, pm);
}
else if (pm.Map != m_Escort.Map || !pm.InRange(m_Escort, 30)) // TODO: verify range
{
if (m_LastSeenEscorter + BaseEscortable.AbandonDelay <= Core.Now)
{
Abandon();
}
}
else
{
m_LastSeenEscorter = Core.Now;
}
}
private void StopTimer()
{
_timerToken.Cancel();
}
public static void BeginFollow(BaseCreature quester, PlayerMobile pm)
{
quester.ControlSlots = 0;
quester.SetControlMaster(pm);
quester.ActiveSpeed = 0.1;
quester.PassiveSpeed = 0.2;
quester.ControlOrder = OrderType.Follow;
quester.ControlTarget = pm;
quester.CantWalk = false;
quester.CurrentSpeed = 0.1;
}
public static void EndFollow(BaseCreature quester)
{
quester.ActiveSpeed = 0.2;
quester.PassiveSpeed = 1.0;
quester.ControlOrder = OrderType.None;
quester.ControlTarget = null;
quester.CurrentSpeed = 1.0;
quester.SetControlMaster(null);
(quester as BaseEscortable)?.BeginDelete();
}
public override void OnQuestAccepted()
{
var instance = Instance;
var pm = instance.Player;
pm.LastEscortTime = Core.Now;
if (m_Escort != null)
{
BeginFollow(m_Escort, pm);
}
}
public void Abandon()
{
StopTimer();
var instance = Instance;
var pm = instance.Player;
if (m_Escort?.Deleted == false)
{
if (!pm.Alive)
{
m_Escort.Say(500901); // Ack! My escort has come to haunt me!
}
else
{
m_Escort.Say(500902); // My escort seems to have abandoned me!
}
EndFollow(m_Escort);
}
// Note: this sound is sent twice on OSI (once here and once in Cancel())
// m_Player.SendSound( 0x5B3 ); // private sound
pm.SendLocalizedMessage(1071194); // You have failed your escort quest...
if (!instance.Removed)
{
instance.Cancel();
}
}
public override void OnQuesterDeleted()
{
if (IsCompleted() || Instance.Removed)
{
return;
}
Abandon();
}
public override void OnPlayerDeath()
{
// Note: OSI also cancels it when the quest is already complete
if ( /*IsCompleted() ||*/ Instance.Removed)
{
return;
}
Instance.Cancel();
}
public override void OnExpire()
{
Abandon();
}
public override void WriteToGump(Gump g, ref int y)
{
m_Objective.WriteToGump(g, ref y);
base.WriteToGump(g, ref y);
// No extra instance stuff printed for this objective
}
public override void Serialize(IGenericWriter writer)
{
base.Serialize(writer);
writer.Write(HasCompleted);
}
}
}