ModernUO/Projects/UOContent/Items/Skill Items/Ninjitsu/NinjaWeapons.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

373 lines
11 KiB
C#

using System;
using Server.ContextMenus;
using Server.Mobiles;
using Server.SkillHandlers;
using Server.Spells.Chivalry;
using Server.Spells.Necromancy;
using Server.Spells.Ninjitsu;
using Server.Targeting;
using Server.Utilities;
/*
* There really was no prettier way to do this, other than the one
* suggestion to make a rigged baseninjaweapon class that bypasses its
* own serialization, due to the way these weapons were originaly coded.
*/
namespace Server.Items
{
public interface INinjaAmmo : IUsesRemaining
{
int PoisonCharges { get; set; }
Poison Poison { get; set; }
}
public interface INinjaWeapon : IUsesRemaining
{
int NoFreeHandMessage { get; }
int EmptyWeaponMessage { get; }
int RecentlyUsedMessage { get; }
int FullWeaponMessage { get; }
int WrongAmmoMessage { get; }
Type AmmoType { get; }
int PoisonCharges { get; set; }
Poison Poison { get; set; }
int WeaponDamage { get; }
int WeaponMinRange { get; }
int WeaponMaxRange { get; }
void AttackAnimation(Mobile from, Mobile to);
}
public static class NinjaWeapon
{
private const int MaxUses = 10;
public static void AttemptShoot(PlayerMobile from, INinjaWeapon weapon)
{
if (CanUseWeapon(from, weapon))
{
from.BeginTarget(weapon.WeaponMaxRange, false, TargetFlags.Harmful, OnTarget, weapon);
}
}
private static void Shoot(PlayerMobile from, Mobile target, INinjaWeapon weapon)
{
if (from != target && CanUseWeapon(from, weapon) && from.CanBeHarmful(target))
{
if (weapon.WeaponMinRange == 0 || !from.InRange(target, weapon.WeaponMinRange))
{
from.NinjaWepCooldown = true;
from.Direction = from.GetDirectionTo(target);
from.RevealingAction();
weapon.AttackAnimation(from, target);
ConsumeUse(weapon);
if (CombatCheck(from, target))
{
Timer.StartTimer(TimeSpan.FromSeconds(1.0), () => OnHit(from, target, weapon));
}
Timer.StartTimer(TimeSpan.FromSeconds(2.5), () => from.NinjaWepCooldown = false);
}
else
{
from.SendLocalizedMessage(1063303); // Your target is too close!
}
}
}
private static void Unload(Mobile from, INinjaWeapon weapon)
{
if (weapon.UsesRemaining > 0)
{
var ammo = weapon.AmmoType.CreateInstance<Item>(weapon.UsesRemaining);
if (ammo is INinjaAmmo ninaAmmo)
{
ninaAmmo.Poison = weapon.Poison;
ninaAmmo.PoisonCharges = weapon.PoisonCharges;
}
from.AddToBackpack(ammo);
weapon.UsesRemaining = 0;
weapon.PoisonCharges = 0;
weapon.Poison = null;
}
}
private static void Reload(PlayerMobile from, INinjaWeapon weapon, INinjaAmmo ammo)
{
if (weapon.UsesRemaining < MaxUses)
{
var need = Math.Min(MaxUses - weapon.UsesRemaining, ammo.UsesRemaining);
if (need > 0)
{
if (weapon.Poison != null && (ammo.Poison == null || weapon.Poison.Level > ammo.Poison.Level))
{
from.SendLocalizedMessage(1070767); // Loaded projectile is stronger, unload it first
}
else
{
if (weapon.UsesRemaining > 0)
{
if (weapon.Poison == null && ammo.Poison != null
|| weapon.Poison != null && ammo.Poison != null && weapon.Poison.Level != ammo.Poison.Level)
{
Unload(from, weapon);
need = Math.Min(MaxUses, ammo.UsesRemaining);
}
}
var poisonneeded = Math.Min(MaxUses - weapon.PoisonCharges, ammo.PoisonCharges);
weapon.UsesRemaining += need;
weapon.PoisonCharges += poisonneeded;
if (weapon.PoisonCharges > 0)
{
weapon.Poison = ammo.Poison;
}
ammo.PoisonCharges -= poisonneeded;
ammo.UsesRemaining -= need;
if (ammo.UsesRemaining < 1)
{
((Item)ammo).Delete();
}
else if (ammo.PoisonCharges < 1)
{
ammo.Poison = null;
}
}
} // "else" here would mean they targeted "ammo" with 0 uses. undefined behavior.
}
else
{
from.SendLocalizedMessage(weapon.FullWeaponMessage);
}
}
private static void ConsumeUse(INinjaWeapon weapon)
{
if (weapon.UsesRemaining > 0)
{
weapon.UsesRemaining--;
if (weapon.UsesRemaining < 1)
{
weapon.PoisonCharges = 0;
weapon.Poison = null;
}
}
}
private static bool CanUseWeapon(PlayerMobile from, INinjaWeapon weapon)
{
if (WeaponIsValid(weapon, from))
{
if (weapon.UsesRemaining > 0)
{
if (!from.NinjaWepCooldown)
{
if (BasePotion.HasFreeHand(from))
{
return true;
}
from.SendLocalizedMessage(weapon.NoFreeHandMessage);
}
else
{
from.SendLocalizedMessage(weapon.RecentlyUsedMessage);
}
}
else
{
from.SendLocalizedMessage(weapon.EmptyWeaponMessage);
}
}
return false;
}
private static bool CombatCheck(Mobile attacker, Mobile defender) /* mod'd from baseweapon */
{
var defWeapon = defender.Weapon as BaseWeapon;
var atkSkill = defender.Skills.Ninjitsu;
// Skill defSkill = defender.Skills[defWeapon.Skill];
var atSkillValue = attacker.Skills.Ninjitsu.Value;
var defSkillValue = defWeapon?.GetDefendSkillValue(attacker, defender) ?? 0.0;
if (defSkillValue <= -20.0)
{
defSkillValue = -19.9;
}
double attackValue = AosAttributes.GetValue(attacker, AosAttribute.AttackChance);
if (DivineFurySpell.UnderEffect(attacker))
{
attackValue += 10;
}
if (AnimalForm.UnderTransformation(attacker, typeof(GreyWolf)) ||
AnimalForm.UnderTransformation(attacker, typeof(BakeKitsune)))
{
attackValue += 20;
}
if (HitLower.IsUnderAttackEffect(attacker))
{
attackValue -= 25;
}
if (attackValue > 45)
{
attackValue = 45;
}
attackValue = (atSkillValue + 20.0) * (100 + attackValue);
double defenseValue = AosAttributes.GetValue(defender, AosAttribute.DefendChance);
if (DivineFurySpell.UnderEffect(defender))
{
defenseValue -= 20;
}
if (HitLower.IsUnderDefenseEffect(defender))
{
defenseValue -= 25;
}
var refBonus = 0;
if (Block.GetBonus(defender, ref refBonus))
{
defenseValue += refBonus;
}
if (Discordance.GetEffect(attacker, ref refBonus))
{
defenseValue -= refBonus;
}
if (defenseValue > 45)
{
defenseValue = 45;
}
defenseValue = (defSkillValue + 20.0) * (100 + defenseValue);
var chance = attackValue / (defenseValue * 2.0);
if (chance < 0.02)
{
chance = 0.02;
}
return attacker.CheckSkill(atkSkill.SkillName, chance);
}
private static void OnHit(Mobile from, Mobile target, INinjaWeapon weapon)
{
if (!from.CanBeHarmful(target))
{
return;
}
from.DoHarmful(target);
AOS.Damage(target, from, weapon.WeaponDamage, 100, 0, 0, 0, 0);
if (weapon.Poison != null && weapon.PoisonCharges > 0)
{
if (EvilOmenSpell.TryEndEffect(target))
{
target.ApplyPoison(from, Poison.GetPoison(weapon.Poison.Level + 1));
}
else
{
target.ApplyPoison(from, weapon.Poison);
}
weapon.PoisonCharges--;
if (weapon.PoisonCharges < 1)
{
weapon.Poison = null;
}
}
}
private static void OnTarget(Mobile from, object targeted, INinjaWeapon weapon)
{
if (from is PlayerMobile player && WeaponIsValid(weapon, from))
{
if (targeted is Mobile mobile)
{
Shoot(player, mobile, weapon);
}
else if (targeted.GetType() == weapon.AmmoType)
{
Reload(player, weapon, (INinjaAmmo)targeted);
}
else
{
player.SendLocalizedMessage(weapon.WrongAmmoMessage);
}
}
}
private static bool WeaponIsValid(INinjaWeapon weapon, Mobile from) =>
weapon is Item item && !item.Deleted && item.RootParent == from;
public class LoadEntry : ContextMenuEntry
{
private readonly INinjaWeapon weapon;
public LoadEntry(INinjaWeapon wep, int entry)
: base(entry, 0) =>
weapon = wep;
public override void OnClick()
{
if (WeaponIsValid(weapon, Owner.From))
{
Owner.From.BeginTarget(10, false, TargetFlags.Harmful, OnTarget, weapon);
}
}
}
public class UnloadEntry : ContextMenuEntry
{
private readonly INinjaWeapon weapon;
public UnloadEntry(INinjaWeapon wep, int entry)
: base(entry, 0)
{
weapon = wep;
Enabled = weapon.UsesRemaining > 0;
}
public override void OnClick()
{
if (WeaponIsValid(weapon, Owner.From))
{
Unload(Owner.From, weapon);
}
}
}
}
}