using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
///
/// The script-provided combat hook (Shared/RynthAiCombatApi.cs): who holds it, for which kinds,
/// until when, and one request slot per kind. Static, like the interface table that serves it,
/// so it survives a re-Init of the plugin instance; everything runs on the plugin pump thread.
///
/// RynthAi asks (CombatManager.AttackWithMagic for an attack, BuffManager.CheckVitals for a heal)
/// with : the first call opens a request and says Wait; later calls say Wait
/// until the answer is in (Decided), the answer is a decline (Native), or the deadline passes
/// (Native). The hook is active only while its lease is live, so a script plugin that stops
/// renewing (unloaded, crashed, stopped) leaves RynthAi native within one lease.
///
internal static class CombatHook
{
/// What a consumer does this tick.
internal enum Outcome { Native, Wait, Decided }
/// One kind's request slot.
internal sealed class Slot
{
public readonly uint Kind;
public Slot(uint kind) => Kind = kind;
public bool Open;
public CombatRequestV1 Request;
public bool Decided;
public uint DecidedSpell, DecidedTarget, DecidedFlags;
// The last decision consumed (handed back in the next request).
public uint LastSeq, LastSpell, LastTarget;
public long LastAtMs;
// Counters for /ra combat and the tests.
public int Opened, Casts, Declines, Timeouts, Rejects;
public long LastTimeoutLogMs = long.MinValue;
public long LastRejectLogMs = long.MinValue;
public void Reset()
{
Open = false; Decided = false; Request = default;
DecidedSpell = DecidedTarget = DecidedFlags = 0;
LastSeq = LastSpell = LastTarget = 0; LastAtMs = 0;
Opened = Casts = Declines = Timeouts = Rejects = 0;
LastTimeoutLogMs = LastRejectLogMs = long.MinValue;
}
}
/// Milliseconds clock (Environment.TickCount64; the host tests replace it).
internal static Func Clock = static () => Environment.TickCount64;
internal static long Now => Clock();
/// A timeout is logged at most this often per kind.
internal const long TimeoutLogIntervalMs = 60_000;
private const long RejectLogIntervalMs = 5_000;
/// A request this long past its deadline when RynthAi next asks is dropped and asked again.
internal const long StaleGraceMs = 1_000;
public static string Owner { get; private set; } = "";
public static uint Kinds { get; private set; }
public static long LeaseUntilMs { get; private set; }
public static uint AttackTimeoutMs { get; private set; } = RynthAiCombat.DefaultAttackTimeoutMs;
public static uint HealTimeoutMs { get; private set; } = RynthAiCombat.DefaultHealTimeoutMs;
public static readonly Slot Attack = new(RynthAiCombat.KindAttack);
public static readonly Slot Heal = new(RynthAiCombat.KindHeal);
private static uint _seq;
/// Forget everything (plugin shutdown, host tests).
public static void Reset()
{
Owner = "";
Kinds = 0;
LeaseUntilMs = 0;
AttackTimeoutMs = RynthAiCombat.DefaultAttackTimeoutMs;
HealTimeoutMs = RynthAiCombat.DefaultHealTimeoutMs;
Attack.Reset();
Heal.Reset();
_seq = 0;
}
public static Slot? SlotFor(uint kind) => kind == RynthAiCombat.KindAttack ? Attack : kind == RynthAiCombat.KindHeal ? Heal : null;
/// True while is held and the lease is live.
public static bool IsActive(uint kind) => (Kinds & kind) != 0 && Now < LeaseUntilMs;
private static bool LeaseLive => Kinds != 0 && Now < LeaseUntilMs;
/// Takes or renews the hook. Returns the kinds granted (0 = another owner's lease is live).
public static uint Claim(uint kinds, uint leaseMs, uint attackTimeoutMs, uint healTimeoutMs, string owner)
{
owner = (owner ?? "").Trim();
if (owner.Length > RynthAiCombat.MaxOwnerLength) owner = owner.Substring(0, RynthAiCombat.MaxOwnerLength);
kinds &= RynthAiCombat.KindsAll;
long now = Now;
bool live = LeaseLive;
if (live && !string.Equals(Owner, owner, StringComparison.Ordinal)) return 0;
// Kinds this owner no longer claims: their open requests are dropped (native that tick).
uint dropped = live ? Kinds & ~kinds : RynthAiCombat.KindsAll;
if ((dropped & RynthAiCombat.KindAttack) != 0) Cancel(Attack);
if ((dropped & RynthAiCombat.KindHeal) != 0) Cancel(Heal);
if (kinds == 0)
{
Owner = "";
Kinds = 0;
LeaseUntilMs = 0;
return 0;
}
Owner = owner;
Kinds = kinds;
LeaseUntilMs = now + RynthAiCombat.ClampLease(leaseMs);
AttackTimeoutMs = RynthAiCombat.ClampTimeout(attackTimeoutMs, RynthAiCombat.DefaultAttackTimeoutMs);
HealTimeoutMs = RynthAiCombat.ClampTimeout(healTimeoutMs, RynthAiCombat.DefaultHealTimeoutMs);
return kinds;
}
/// Drops now; their open requests are cancelled.
public static void Release(uint kinds)
{
kinds &= RynthAiCombat.KindsAll;
if ((kinds & RynthAiCombat.KindAttack) != 0) Cancel(Attack);
if ((kinds & RynthAiCombat.KindHeal) != 0) Cancel(Heal);
Kinds &= ~kinds;
if (Kinds == 0) { Owner = ""; LeaseUntilMs = 0; }
}
/// 1 when a request of is open and unanswered (copied to ).
public static bool Poll(uint kind, out CombatRequestV1 request)
{
request = default;
Slot? s = SlotFor(kind);
if (s == null || !IsActive(kind) || !s.Open || s.Decided || Now > s.Request.DeadlineMs) return false;
request = s.Request;
request.LastSeq = s.LastSeq;
request.LastSpell = s.LastSpell;
request.LastTarget = s.LastTarget;
request.LastAtMs = s.LastAtMs;
return true;
}
/// The answer to request . False = stale.
public static bool Decide(uint seq, uint kind, uint spellId, uint targetId, uint flags)
{
Slot? s = SlotFor(kind);
if (s == null || !IsActive(kind) || !s.Open || s.Decided || s.Request.Seq != seq || Now > s.Request.DeadlineMs) return false;
s.Decided = true;
s.DecidedSpell = spellId;
s.DecidedTarget = targetId;
s.DecidedFlags = flags;
return true;
}
private static void Cancel(Slot s)
{
s.Open = false;
s.Decided = false;
}
///
/// One consumer step for . is what the request
/// is about (the attack target; for a heal the fight target, informational, 0 when none): an open request about another target is dropped
/// and a fresh one opened. fills a new request's context (RynthAi's
/// view of the fight); Seq, Kind, TargetId and the times are set here.
///
public static Outcome Step(Slot slot, uint forTarget, Func build, Action? log,
out uint spellId, out uint targetId, out uint flags)
{
spellId = targetId = flags = 0;
if (!IsActive(slot.Kind))
{
Cancel(slot);
return Outcome.Native;
}
long now = Now;
if (slot.Open && slot.Request.TargetId != forTarget) Cancel(slot); // the target moved on: ask afresh
// RynthAi stopped asking for a while (its gates held the cast, or health came back over the
// line): an answer, or a missing one, from back then is stale. Ask afresh, no timeout counted.
if (slot.Open && now > slot.Request.DeadlineMs + StaleGraceMs) Cancel(slot);
if (!slot.Open)
{
CombatRequestV1 r = build();
r.StructSize = (uint)Unsafe.SizeOf();
if (++_seq == 0) _seq = 1;
r.Seq = _seq;
r.Kind = slot.Kind;
r.TargetId = forTarget;
r.IssuedAtMs = now;
r.DeadlineMs = now + (slot.Kind == RynthAiCombat.KindAttack ? AttackTimeoutMs : HealTimeoutMs);
slot.Request = r;
slot.Open = true;
slot.Decided = false;
slot.Opened++;
return Outcome.Wait;
}
if (slot.Decided)
{
if (slot.DecidedSpell == 0)
{
Consume(slot, 0, 0);
slot.Declines++;
return Outcome.Native;
}
spellId = slot.DecidedSpell;
targetId = slot.DecidedTarget;
flags = slot.DecidedFlags;
return Outcome.Decided; // the consumer validates, then Cast or Reject
}
if (now > slot.Request.DeadlineMs)
{
Cancel(slot);
slot.Timeouts++;
if (slot.LastTimeoutLogMs == long.MinValue || now - slot.LastTimeoutLogMs >= TimeoutLogIntervalMs)
{
slot.LastTimeoutLogMs = now;
log?.Invoke($"[CombatHook] {RynthAiCombat.KindNames(slot.Kind)} request {slot.Request.Seq} unanswered after " +
$"{slot.Request.DeadlineMs - slot.Request.IssuedAtMs} ms ('{Owner}'): RynthAi chose instead " +
$"({slot.Timeouts} timeout(s) so far; logged at most once a minute)");
}
return Outcome.Native;
}
return Outcome.Wait;
}
/// The decided spell went out (or was waited on): the request is done.
public static void Cast(Slot slot, uint spellId, uint targetId)
{
Consume(slot, spellId, targetId);
if (spellId != 0) slot.Casts++; // 0: handled without a cast (a wand swap step in flight)
}
/// The decided spell failed RynthAi's checks: the request is done, RynthAi chooses.
public static void Reject(Slot slot, string why, Action? log)
{
uint seq = slot.Request.Seq, spell = slot.DecidedSpell, target = slot.DecidedTarget;
Consume(slot, 0, 0);
slot.Rejects++;
long now = Now;
if (slot.LastRejectLogMs == long.MinValue || now - slot.LastRejectLogMs >= RejectLogIntervalMs)
{
slot.LastRejectLogMs = now;
log?.Invoke($"[CombatHook] {RynthAiCombat.KindNames(slot.Kind)} request {seq}: spell {spell} at 0x{target:X8} rejected ({why}); RynthAi chose instead");
}
}
private static void Consume(Slot slot, uint spellId, uint targetId)
{
slot.LastSeq = slot.Request.Seq;
slot.LastSpell = spellId;
slot.LastTarget = targetId;
slot.LastAtMs = Now;
slot.Open = false;
slot.Decided = false;
}
/// One line for /ra combat.
public static string Describe()
{
long now = Now;
bool live = LeaseLive;
string head = live
? $"hook: '{Owner}' holds {RynthAiCombat.KindNames(Kinds)} (lease {Math.Max(0, LeaseUntilMs - now) / 1000.0:0.0}s)"
: "hook: none (RynthAi chooses every spell)";
static string S(Slot s) => $"{s.Opened} asked, {s.Casts} cast, {s.Declines} declined, {s.Timeouts} timed out, {s.Rejects} rejected" +
(s.Open ? $", request {s.Request.Seq} open" : "");
return $"{head} attack: {S(Attack)} heal: {S(Heal)}";
}
}
///
/// RynthAi's side of the "RynthAi.Combat" interface: the table RynthPluginQueryInterface hands
/// out, and the functions behind it (pump thread, current plugin instance).
///
internal static unsafe class CombatHookInterface
{
private static RynthAiCombatApiV1* _table;
public static IntPtr Query(string iface, uint version)
{
if (iface != RynthAiCombatApiV1.InterfaceName || version == 0 || version > RynthAiCombatApiV1.InterfaceVersion) return IntPtr.Zero;
if (_table == null)
{
var t = (RynthAiCombatApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthAiCombatApiV1));
t->Version = RynthAiCombatApiV1.InterfaceVersion;
t->StructSize = (uint)sizeof(RynthAiCombatApiV1);
t->Claim = &Claim;
t->Release = &Release;
t->Poll = &Poll;
t->Decide = &Decide;
t->GetScanned = &GetScanned;
_table = t;
}
return (IntPtr)_table;
}
/// Frees the table and drops the hook (plugin shutdown). Callers resolve it every tick.
public static void Shutdown()
{
var t = _table;
_table = null;
if (t != null) NativeMemory.Free(t);
CombatHook.Reset();
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int Claim(uint kinds, uint leaseMs, uint attackTimeoutMs, uint healTimeoutMs, byte* owner)
{
try
{
string name = owner == null ? "" : Marshal.PtrToStringUTF8((IntPtr)owner) ?? "";
return (int)CombatHook.Claim(kinds, leaseMs, attackTimeoutMs, healTimeoutMs, name);
}
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static void Release(uint kinds)
{
try { CombatHook.Release(kinds); } catch { }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int Poll(uint kind, CombatRequestV1* req)
{
try
{
if (req == null || !CombatHook.Poll(kind, out CombatRequestV1 r)) return 0;
uint room = req->StructSize;
uint size = (uint)sizeof(CombatRequestV1);
if (room == 0 || room > size) room = size; // an older caller passes less; never write past it
r.StructSize = room;
Buffer.MemoryCopy(&r, req, room, room);
return 1;
}
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int Decide(uint seq, uint kind, uint spellId, uint targetId, uint flags)
{
try { return CombatHook.Decide(seq, kind, spellId, targetId, flags) ? 1 : 0; }
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetScanned(uint* ids, float* distances, int capacity)
{
try { return PluginExports.Runtime.Plugin?.CombatHookScanned(ids, distances, capacity) ?? 0; }
catch { return 0; }
}
}
public sealed partial class RynthAiPlugin
{
/// RynthAi.Combat GetScanned: the combat scan list, nearest first as scanned.
internal unsafe int CombatHookScanned(uint* ids, float* distances, int capacity)
{
var list = _combatManager?.ScannedTargets;
if (list == null) return 0;
int n = list.Count;
if (ids != null)
for (int i = 0; i < n && i < capacity; i++)
{
ids[i] = unchecked((uint)list[i].Id);
if (distances != null) distances[i] = (float)list[i].Distance;
}
return n;
}
}