ModernUO/Projects/UOContent/Items/Skill Items/Magical/Potions/Conflagration Potions/BaseConflagrationPotion.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

326 lines
9.5 KiB
C#

using System;
using System.Collections.Generic;
using Server.Spells;
using Server.Targeting;
namespace Server.Items
{
public abstract class BaseConflagrationPotion : BasePotion
{
private static readonly Dictionary<Mobile, TimerExecutionToken> m_Delay = new();
private readonly List<Mobile> m_Users = new();
public BaseConflagrationPotion(PotionEffect effect) : base(0xF06, effect) => Hue = 0x489;
public BaseConflagrationPotion(Serial serial) : base(serial)
{
}
public abstract int MinDamage { get; }
public abstract int MaxDamage { get; }
public override bool RequireFreeHand => false;
public override void Drink(Mobile from)
{
if (Core.AOS && (from.Paralyzed || from.Frozen || from.Spell?.IsCasting == true))
{
from.SendLocalizedMessage(1062725); // You can not use that potion while paralyzed.
return;
}
var delay = GetDelay(from);
if (delay > 0)
{
from.SendLocalizedMessage(
1072529,
$"{delay}\t{(delay > 1 ? "seconds." : "second.")}"
); // You cannot use that for another ~1_NUM~ ~2_TIMEUNITS~
return;
}
if (from.Target is ThrowTarget targ && targ.Potion == this)
{
return;
}
from.RevealingAction();
if (!m_Users.Contains(from))
{
m_Users.Add(from);
}
from.Target = new ThrowTarget(this);
}
public override void Serialize(IGenericWriter writer)
{
base.Serialize(writer);
writer.Write(0); // version
}
public override void Deserialize(IGenericReader reader)
{
base.Deserialize(reader);
var version = reader.ReadInt();
}
public virtual void Explode(Mobile from, Point3D loc, Map map)
{
if (Deleted || map == null)
{
return;
}
Consume();
// Check if any other players are using this potion
for (var i = 0; i < m_Users.Count; i++)
{
if (m_Users[i].Target is ThrowTarget targ && targ.Potion == this)
{
Target.Cancel(from);
}
}
// Effects
Effects.PlaySound(loc, map, 0x20C);
for (var i = -2; i <= 2; i++)
{
for (var j = -2; j <= 2; j++)
{
var p = new Point3D(loc.X + i, loc.Y + j, loc.Z);
if (map.CanFit(p, 12, true, false) && from.InLOS(p))
{
new InternalItem(from, p, map, MinDamage, MaxDamage);
}
}
}
}
public static void AddDelay(Mobile m)
{
m_Delay.TryGetValue(m, out var timer);
timer.Cancel();
Timer.StartTimer(TimeSpan.FromSeconds(30), () => EndDelay(m), out timer);
m_Delay[m] = timer;
}
public static int GetDelay(Mobile m)
{
if (m_Delay.TryGetValue(m, out var timer) && timer.Next > Core.Now)
{
return (int)(timer.Next - Core.Now).TotalSeconds;
}
return 0;
}
public static void EndDelay(Mobile m)
{
if (m_Delay.Remove(m, out var timer))
{
timer.Cancel();
}
}
private class ThrowTarget : Target
{
public ThrowTarget(BaseConflagrationPotion potion) : base(12, true, TargetFlags.None) => Potion = potion;
public BaseConflagrationPotion Potion { get; }
protected override void OnTarget(Mobile from, object targeted)
{
if (Potion.Deleted || Potion.Map == Map.Internal)
{
return;
}
if (targeted is not IPoint3D p || from.Map == null)
{
return;
}
// Add delay
AddDelay(from);
SpellHelper.GetSurfaceTop(ref p);
var loc = new Point3D(p);
var map = from.Map;
from.RevealingAction();
IEntity to;
if (p is Mobile mobile)
{
to = mobile;
}
else
{
to = new Entity(Serial.Zero, loc, map);
}
Effects.SendMovingEffect(from, to, 0xF0D, 7, 0, false, false, Potion.Hue);
Timer.StartTimer(TimeSpan.FromSeconds(1.5), () => Potion.Explode(from, loc, map));
}
}
public class InternalItem : Item
{
private DateTime m_End;
private int m_MaxDamage;
private int m_MinDamage;
private Timer m_Timer;
public InternalItem(Mobile from, Point3D loc, Map map, int min, int max) : base(0x398C)
{
Movable = false;
Light = LightType.Circle300;
MoveToWorld(loc, map);
From = from;
m_End = Core.Now + TimeSpan.FromSeconds(10);
SetDamage(min, max);
m_Timer = new InternalTimer(this, m_End);
m_Timer.Start();
}
public InternalItem(Serial serial) : base(serial)
{
}
public Mobile From { get; private set; }
public override bool BlocksFit => true;
public override void OnAfterDelete()
{
base.OnAfterDelete();
m_Timer?.Stop();
}
public int GetDamage() => Utility.RandomMinMax(m_MinDamage, m_MaxDamage);
private void SetDamage(int min, int max)
{
/* new way to apply alchemy bonus according to Stratics' calculator.
this gives a mean to values 25, 50, 75 and 100. Stratics' calculator is outdated.
Those goals will give 2 to alchemy bonus. It's not really OSI-like but it's an approximation. */
m_MinDamage = min;
m_MaxDamage = max;
if (From == null)
{
return;
}
var alchemySkill = From.Skills.Alchemy.Fixed;
var alchemyBonus = alchemySkill / 125 + alchemySkill / 250;
m_MinDamage = Scale(From, m_MinDamage + alchemyBonus);
m_MaxDamage = Scale(From, m_MaxDamage + alchemyBonus);
}
public override void Serialize(IGenericWriter writer)
{
base.Serialize(writer);
writer.Write(0); // version
writer.Write(From);
writer.Write(m_End);
writer.Write(m_MinDamage);
writer.Write(m_MaxDamage);
}
public override void Deserialize(IGenericReader reader)
{
base.Deserialize(reader);
var version = reader.ReadInt();
From = reader.ReadEntity<Mobile>();
m_End = reader.ReadDateTime();
m_MinDamage = reader.ReadInt();
m_MaxDamage = reader.ReadInt();
m_Timer = new InternalTimer(this, m_End);
m_Timer.Start();
}
public override bool OnMoveOver(Mobile m)
{
if (Visible && From != null && (!Core.AOS || m != From) && SpellHelper.ValidIndirectTarget(From, m) &&
From.CanBeHarmful(m, false))
{
From.DoHarmful(m);
AOS.Damage(m, From, GetDamage(), 0, 100, 0, 0, 0);
m.PlaySound(0x208);
}
return true;
}
private class InternalTimer : Timer
{
private readonly DateTime m_End;
private readonly InternalItem m_Item;
public InternalTimer(InternalItem item, DateTime end) : base(TimeSpan.Zero, TimeSpan.FromSeconds(1.0))
{
m_Item = item;
m_End = end;
}
protected override void OnTick()
{
if (m_Item.Deleted)
{
return;
}
if (Core.Now > m_End)
{
m_Item.Delete();
Stop();
return;
}
var from = m_Item.From;
if (m_Item.Map == null || from == null)
{
return;
}
foreach (var m in m_Item.GetMobilesInRange(0))
{
if (m.Z + 16 > m_Item.Z && m_Item.Z + 12 > m.Z && (!Core.AOS || m != from) &&
SpellHelper.ValidIndirectTarget(from, m) && from.CanBeHarmful(m, false))
{
from.DoHarmful(m);
AOS.Damage(m, from, m_Item.GetDamage(), 0, 100, 0, 0, 0);
m.PlaySound(0x208);
}
}
}
}
}
}
}