RynthAi.Combat v1: let a RynthLua script choose RynthAi's attack and heal spells

Adds a polling hand-off ("RynthAi.Combat" v1 interface table) so a script can
pick the spell RynthAi casts for an attack or an HP heal, while RynthAi keeps
scanning, targeting, the arbiter, nav/loot gating, thresholds, buffs, stance and
wand. Decline, invalid answers, timeouts and lease lapse all fall back to
native selection in the same tick; the emergency heal path is untouched; the
hook is inert when no script registers. RynthAi's mana reserve holds a script's
attack spell as it holds its own (the answer is kept, nothing native is cast
instead, and the script is asked again after the deadline plus 1 s); a spell
costing more than max mana is rejected so RynthAi chooses its own. Lua API:
ai.SetAttackHandler, ai.SetHealHandler, ai.ClearCombatHandlers, ai.CombatHook.
Includes host and compat tests and Examples/combat-handler.lua. No
RynthCore/SDK changes.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Daniel Wallace 2026-10-10 10:26:25 -07:00
commit 10e2c2eb0a
30 changed files with 3620 additions and 27 deletions

View file

@ -0,0 +1,104 @@
using System;
using RynthCore.PluginSdk;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
// The heal seam of the script-provided combat hook (RynthAi.Combat, CombatHookInterface.cs):
// CheckVitals asks the script for the heal spell (and its target: the player, or a monster for a
// drain) before kits. The cast itself goes through CastVital, the same steps as Heal Self.
public partial class BuffManager
{
/// <summary>
/// True when the hook handled this vitals check: waiting for the answer, or the answer was
/// cast (or its wand swap is in flight). False = the native order (kit, Heal Self, potion).
/// </summary>
private bool TryScriptHeal(int healLine, bool inCombat)
{
// AC just said "You're too busy!": the same pacing as a Heal Self (AttemptVitalCast).
if (DateTime.Now < _busyBackoffUntil && (DateTime.Now - _lastCastAttempt).TotalMilliseconds < BusyHealRetryMs)
{
_vitalWhy = $"AC too busy, waiting {(_busyBackoffUntil - DateTime.Now).TotalMilliseconds:0} ms";
_healWaitKind = "too-busy backoff";
return true;
}
var slot = CombatHook.Heal;
// The request names RynthAi's current fight target (informational: the monster with live
// health data, e.g. for a drain); a fight target change re-asks. The answer's target 0
// still means the player.
var cm = _combatManager;
uint fight = cm == null ? 0u : unchecked((uint)cm.activeTargetId);
var outcome = CombatHook.Step(slot, fight, () => BuildHealRequest(healLine, inCombat), s => _host.Log(s),
out uint spell, out uint target, out _);
switch (outcome)
{
case CombatHook.Outcome.Native:
return false;
case CombatHook.Outcome.Wait:
_vitalWhy = $"waiting for '{CombatHook.Owner}' to choose the heal";
_healWaitKind = "script choosing the heal";
return true;
}
uint player = (uint)_host.GetPlayerId();
if (target == 0) target = player;
string? why = ScriptHealProblem(spell, target, player);
if (why != null)
{
CombatHook.Reject(slot, why, s => _host.Log(s));
return false;
}
string name = SpellTableStub.GetById((int)spell)?.Name ?? $"spell {spell}";
bool handled = CastVital((int)spell, target, LabelHealing, name + " (script)", out bool sent);
if (!handled)
{
CombatHook.Reject(slot, _vitalWhy.Length > 0 ? _vitalWhy : "it couldn't be cast", s => _host.Log(s));
return false;
}
// A script-chosen heal takes no early nudge (HeldNudgeUrgent): its result can come later
// than RynthAi's own heals' (Vitality Siphon: 2.42-2.75 s after the incantation, 2026-10-10
// log), or never (a resisted or dead target), and an early nudge steps the character.
if (sent && _cast.Current is { } sentCast && sentCast.SpellId == (int)spell) sentCast.Script = true;
// Handled: cast, or a swap step to Magic mode is in flight (the next check asks again).
CombatHook.Cast(slot, sent ? spell : 0, sent ? target : 0);
if (sent) _host.Log($"[RynthAi] Vitals: script heal id={spell} '{name}' at 0x{target:X8} (owner '{CombatHook.Owner}').");
return true;
}
/// <summary>Why the script's heal can't be cast, or null when it can.</summary>
private string? ScriptHealProblem(uint spell, uint target, uint player)
{
if (!_spellManager.IsKnownSpellId((int)spell)) return $"spell {spell} isn't known";
// The refusal memory RynthAi's own heal honours (AttemptVitalCast): a level the server
// said there are no components for.
if (LevelLacksComponents((int)spell)) return $"spell {spell} has no components (refused by the server; RynthAi uses a lower level)";
if (target == player) return null;
var cm = _combatManager;
bool listed = cm != null && unchecked((uint)cm.activeTargetId) == target;
if (!listed && cm != null)
foreach (var t in cm.ScannedTargets)
if (unchecked((uint)t.Id) == target) { listed = true; break; }
if (!listed) return "the target is not the player, the fight target or a scanned monster";
if (_host.HasObjectIsAttackable && !_host.ObjectIsAttackable(target)) return "the target is not attackable";
return null;
}
private CombatRequestV1 BuildHealRequest(int healLine, bool inCombat)
{
bool known = _vitals.MaxHealth > 0;
var cm = _combatManager;
float fightHealth = cm?.FightTargetHealthRatio ?? -1f;
return new CombatRequestV1
{
TargetHealth = fightHealth,
HealthPct = known ? _vitals.HealthPct : -1,
StaminaPct = _vitals.MaxStamina > 0 ? _vitals.StaminaPct : -1,
ManaPct = _vitals.MaxMana > 0 ? _vitals.ManaPct : -1,
HealLine = healLine,
InCombat = inCombat ? 1 : 0,
CombatMode = CurrentCombatMode,
};
}
}

View file

@ -6,7 +6,7 @@ using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
public class BuffManager : IDisposable
public partial class BuffManager : IDisposable
{
private readonly RynthCoreHost _host;
private readonly LegacyUiSettings _settings;
@ -453,6 +453,19 @@ public class BuffManager : IDisposable
/// mana is under the spell's own cost (it would be refused), or under the refill line while
/// vitals can refill it (Stamina to Mana goes first).
/// </summary>
/// <summary>
/// For CombatManager's script hook, before <see cref="OffensiveCastHold"/>: false when
/// <paramref name="spellId"/> costs more than the character's max mana, so the cost hold would
/// never lift. Same cost source and the same guards as OffensiveCastHold (no hold, no veto:
/// macro off, or max mana unknown); an unknown cost (0) is affordable.
/// </summary>
internal bool CanEverAfford(int spellId)
{
if (!_settings.IsMacroRunning || _vitals.MaxMana == 0) return true;
int cost = SpellManaCost(spellId);
return cost <= 0 || cost <= _vitals.MaxMana;
}
internal string? OffensiveCastHold(int spellId)
{
if (!_settings.IsMacroRunning || _vitals.MaxMana == 0) return null;
@ -1681,6 +1694,15 @@ public class BuffManager : IDisposable
// works: no spell, Life Magic untrained, or out of components).
if (curHealthPct < hpThreshold)
{
// A script holding the heal kind (RynthAi.Combat) is asked first, before kits: a class
// that heals by draining monsters must not have a kit pre-empt it. The emergency step
// above stays native (the safety floor). Waiting for the answer counts as handled; a
// decline, a bad answer or no answer in time falls through to kit, Heal Self, potion.
if (CombatHook.IsActive(RynthAiCombat.KindHeal) && TryScriptHeal(hpThreshold, inCombat))
{
_isHealingSelf = true;
return true;
}
_vitalWhy = "";
bool healed = AttemptHealthKitUse();
string kitWhy = _vitalWhy;
@ -1929,6 +1951,20 @@ public class BuffManager : IDisposable
spellId = payable;
}
}
return CastVital(spellId, (uint)_host.GetPlayerId(), VitalLabel(baseName), baseName, out _);
}
/// <summary>
/// The cast step of a vital spell, shared by AttemptVitalCast (self vitals) and the script
/// hook's heal (a drain at a monster id goes through the same steps): the family park, the
/// wand swap / Magic stance, the pending-vital bookkeeping (confirmed by chat; released with
/// no strike when the line is late) and the heal latency. Returns "handled" as
/// AttemptVitalCast does (true also while a swap step is in flight); <paramref name="sent"/>
/// says whether the cast actually went out.
/// </summary>
private bool CastVital(int spellId, uint targetId, string label, string what, out bool sent)
{
sent = false;
// Parked after a hard server refusal (see OnChatWindowText) — the same
// per-family cooldown the buff selectors honour.
int family = SpellTableStub.GetById(spellId)?.Family ?? 0;
@ -1938,7 +1974,7 @@ public class BuffManager : IDisposable
return VitalNo($"parked for {(coolUntil - DateTime.Now).TotalSeconds:0} s more after a refusal or no-show");
if (CurrentCombatMode != CombatMode.Magic && DateTime.Now < _vitalSwapBlockedUntil)
return VitalNo("wand swap blocked, retrying shortly");
bool urgentHeal = baseName is "Heal Self" or "Stamina to Health Self" && HealIsUrgent(_vitals.HealthPct, _vitals.StaminaPct);
bool urgentHeal = label == LabelHealing && HealIsUrgent(_vitals.HealthPct, _vitals.StaminaPct);
if (!EnsureMagicMode(urgentHeal: urgentHeal))
{
if (!_magicModeBlocked) { _healWaitKind = "wand swap / Magic stance"; return true; } // a swap step is in flight: yield the tick
@ -1952,21 +1988,22 @@ public class BuffManager : IDisposable
// strike. Mirror the buff path: not handled, so the potion gets its turn.
_pendingSpellId = spellId;
_pendingVitalSpellId = spellId; // instant: confirmed by chat, never by the registry
_pendingVitalLabel = VitalLabel(baseName);
bool castOk = _host.CastSpellFor((uint)_host.GetPlayerId(), spellId, "Buff",
SpellTableStub.GetById(spellId)?.Name ?? baseName);
_pendingVitalLabel = label;
bool castOk = _host.CastSpellFor(targetId, spellId, "Buff",
SpellTableStub.GetById(spellId)?.Name ?? what);
_lastCastAttempt = DateTime.Now;
if (!castOk)
{
_pendingSpellId = 0;
return VitalNo($"the client refused the cast (spell {spellId})");
}
sent = true;
NoteCastIssued(spellId);
if (_pendingVitalLabel == LabelMana) _manaStarvedLogged = false; // the next starved spell logs again
if (_pendingVitalLabel == LabelHealing)
{
_healSpellIds.Add(spellId);
_healLatency.HealSent(Now, baseName);
_healLatency.HealSent(Now, what);
}
return true;
}
@ -3733,15 +3770,47 @@ public class BuffManager : IDisposable
return;
}
// A script heal (a transfer such as Vitality Siphon) cast at a monster that resists it:
// "Doorheld Surveyor resists your spell" is its only result, no "due to casting" line
// follows. Closed here as CombatManager reads the same line for its own casts.
if (lower.Contains("resists your spell"))
{
var c = _cast.Open is { Done: false } o ? o
: _cast.Current is { Done: false, Refused: false } cur ? cur : null;
if (c != null && c.Script)
{
_cast.Result(null, "resisted");
_host.Log($"[BuffChat] script heal '{c.Name}' resisted; pending={_pendingSpellId} cleared.");
_pendingSpellId = 0;
_onCastResolved?.Invoke("resisted");
return;
}
}
// "You cast Incantation of Flame Bane on Gelidite Robe, refreshing ..."
// "You cast Strength Self VIII"
// The leading 'Y' is stripped by AC's chat-glyph layer before our handler
// sees it — text actually arrives as "ou cast …". IndexOf works for both.
// A transfer to the caster names the spell after "due to casting " instead.
const string DueToCasting = "due to casting ";
int castIdx = lower.IndexOf("ou cast ", StringComparison.Ordinal);
int skip = 8; // "ou cast "
bool viaDueToCasting = false;
if (castIdx < 0)
{
// A transfer to the caster names the spell after "due to casting": "You gain 51 points
// of health due to casting Vitality Siphon on Doorheld Surveyor" (a heal the script
// hook casts at a monster). Unread, the heal stayed "held" and its early nudge (autorun
// on/off) went out mid-cast: the character stepped forward (2026-10-10 log, 13 of 14
// nudges).
castIdx = lower.IndexOf(DueToCasting, StringComparison.Ordinal);
skip = DueToCasting.Length;
viaDueToCasting = castIdx >= 0;
}
if (castIdx < 0) return;
// Extract spell name: everything after "ou cast " up to " on " or ","
string afterCast = text.Substring(castIdx + 8); // skip "ou cast "
// Extract spell name: everything after "ou cast " (or "due to casting ") up to " on " or ","
string afterCast = text.Substring(castIdx + skip);
int onIdx = afterCast.IndexOf(" on ", StringComparison.OrdinalIgnoreCase);
int commaIdx = afterCast.IndexOf(',');
int endIdx = afterCast.Length;
@ -3753,6 +3822,18 @@ public class BuffManager : IDisposable
// line, "You cast Revitalize Self V and restore 70 points...", has no " on " or comma).
var tracked = _cast.Result(afterCast, "result");
// A "due to casting" line that matches no open cast is only a result when it names the
// pending spell (its cast closed first, on a UseDone). Otherwise it is not ours to read:
// one transfer can print several lines (Crimson Harvest, 2026-10-10), and RynthAi's own
// drain attacks (CombatManager, never tracked here) print one each. Read as results they
// recorded a timer, ended a too-busy backoff and resolved a cast that was still running.
if (viaDueToCasting && tracked == null)
{
string? pendingName = _pendingSpellId != 0 ? SpellTableStub.GetById(_pendingSpellId)?.Name : null;
if (pendingName == null || !string.Equals(spellName, pendingName, StringComparison.OrdinalIgnoreCase))
return;
}
// Try to find the spell by name first (authoritative — this is what was actually cast)
int spellId = SpellDatabase.GetIdByName(spellName);
SpellInfo? spellInfo = spellId > 0 ? SpellTableStub.GetById(spellId) : null;
@ -3803,7 +3884,7 @@ public class BuffManager : IDisposable
var ps = SpellTableStub.GetById(_pendingSpellId);
if (ps != null) _forceRebuffCastFamilies.Add(ps.Family);
}
_host.Log($"[BuffChat] CLEARED pending={_pendingSpellId} via ou-cast match name='{spellName}' resolvedId={spellId}");
_host.Log($"[BuffChat] CLEARED pending={_pendingSpellId} via {(viaDueToCasting ? "due-to-casting" : "ou-cast")} match name='{spellName}' resolvedId={spellId}");
}
_pendingSpellId = 0;
_onCastResolved?.Invoke($"cast '{spellName}'");
@ -3897,11 +3978,12 @@ public class BuffManager : IDisposable
SendCastNudge(urgent: true);
}
/// <summary>The held cast is a heal, or health is under a heal line: nudge it early.</summary>
/// <summary>The held cast is a heal, or health is under a heal line: nudge it early. Never a
/// cast the script hook chose (CastTracker.Cast.Script): those wait HeldAfterIncantMs.</summary>
private bool HeldNudgeUrgent()
{
var held = _cast.Held;
if (held == null) return false;
if (held == null || held.Script) return false;
return IsHealCast(held.SpellId)
|| (_vitals.MaxHealth > 0 && HealthUnderAnyLine(_vitals.HealthPct, _vitals.StaminaPct));
}

View file

@ -38,6 +38,9 @@ internal sealed class CastTracker
public bool Done; // its result line, or UseDone(0) after its incantation
public bool Nudged; // the one movement nudge for this held cast has gone out
public bool StuckLogged;
// The script combat hook chose this cast (a heal): no early nudge, HeldAfterIncantMs only.
// A Vitality Siphon's result can come 2.75 s after its incantation (2026-10-10 log).
public bool Script;
public bool HasIncantation => IncantAt != DateTime.MinValue;
}

View file

@ -0,0 +1,285 @@
using System;
using RynthCore.PluginSdk;
using RynthCore.Plugin.RynthAi.Combat;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
// The attack seam of the script-provided combat hook (RynthAi.Combat, CombatHookInterface.cs):
// with a script holding the attack kind, AttackWithMagic asks it for the spell after its debuffs
// and before its own shape choice. RynthAi keeps everything around the cast: the scan, the
// target lock, the stance, the cadence and busy gates, and the cast bookkeeping. The script only
// names the spell (and optionally another scanned monster, or the player).
public partial class CombatManager
{
// True on a tick where AttackWithMagic sent nothing because it is waiting on the script's
// answer: Think then ends the tick without stamping lastAttackCmd (like the wall hold).
private bool _scriptHeld;
/// <summary>The player's vitals, for the hook's request (set by the plugin; null in tests that don't need it).</summary>
internal PlayerVitalsCache? Vitals { get; set; }
/// <summary>The fight target's last known health ratio (0-1), or -1 when unknown or no target.</summary>
internal float FightTargetHealthRatio => activeTargetId == 0 ? -1f : _worldFilter.GetHealthRatio(activeTargetId);
/// <summary>Host tests: true after a tick that held for the script's answer.</summary>
internal bool ScriptHeld => _scriptHeld;
/// <summary>
/// True when the hook handled this attack cycle: held for the answer, or cast the script's
/// spell. False = RynthAi chooses as usual (no hook, a decline, a rejected answer, a timeout).
/// </summary>
private bool TryScriptAttack(WorldObject target, string element)
{
if (!CombatHook.IsActive(RynthAiCombat.KindAttack)) return false; // no hook: no per-tick lambdas
var slot = CombatHook.Attack;
uint forTarget = unchecked((uint)activeTargetId);
var outcome = CombatHook.Step(slot, forTarget, () => BuildAttackRequest(target), s => _host.Log(s),
out uint spell, out uint castTarget, out uint flags);
switch (outcome)
{
case CombatHook.Outcome.Native:
return false;
case CombatHook.Outcome.Wait:
_scriptHeld = true;
LastCombatSkipReason = "script-wait"; // D4 record-only
return true;
}
if (castTarget == 0) castTarget = forTarget;
string? why = ScriptAttackProblem(spell, castTarget);
if (why != null)
{
CombatHook.Reject(slot, why, s => _host.Log(s));
return false;
}
// A spell that costs more than max mana can never be paid, so the mana hold below would
// never lift: rejected, and RynthAi chooses its own spell this same tick.
bool affordable = true;
try { affordable = ManaCanEverAfford?.Invoke((int)spell) ?? true; } catch { affordable = true; }
if (!affordable)
{
CombatHook.Reject(slot, "costs more than max mana", s => _host.Log(s));
return false;
}
// RynthAi's mana reserve holds the script's spell as it holds its own (ManaHoldsCast: mana
// under the spell's cost, or under the reserve kept for Stamina to Mana): nothing is sent,
// Think ends the tick on _manaCastHeld, and the answer is kept for the next tick. It is not
// a rejection, so RynthAi does not cast a spell of its own choosing instead. Once the
// request is past its deadline + StaleGraceMs, Step drops the answer and asks again.
if (ManaHoldsCast((int)spell)) return true;
if (!IssueScriptCast((int)spell, castTarget, flags, element))
{
CombatHook.Reject(slot, "the client refused the cast", s => _host.Log(s));
return false;
}
CombatHook.Cast(slot, spell, castTarget);
return true;
}
/// <summary>Why the script's answer can't be cast, or null when it can.</summary>
private string? ScriptAttackProblem(uint spell, uint castTarget)
{
if (_spellManager == null || !_spellManager.IsKnownSpellId((int)spell)) return $"spell {spell} isn't known";
// A script spell the server refused outright (no components): parked like a vital level.
if (_scriptParkedUntil.TryGetValue((int)spell, out DateTime parked) && DateTime.Now < parked)
return $"spell {spell} was refused by the server, parked for {(parked - DateTime.Now).TotalSeconds:0} s more";
uint player = _playerId != 0 ? _playerId : _host.GetPlayerId();
if (castTarget == player) return null;
bool listed = castTarget == unchecked((uint)activeTargetId);
for (int i = 0; !listed && i < _scannedTargets.Count; i++)
if (unchecked((uint)_scannedTargets[i].Id) == castTarget) listed = true;
if (!listed) return "the target is not the fight target, a scanned monster or the player";
// The same veto as RynthAi's own casts: never offensive magic at something AC says isn't attackable.
if (_host.HasObjectIsAttackable && !_host.ObjectIsAttackable(castTarget)) return "the target is not attackable";
return null;
}
private CombatRequestV1 BuildAttackRequest(WorldObject target)
{
var v = Vitals;
bool vitalsKnown = v != null && v.MaxHealth > 0;
return new CombatRequestV1
{
TargetHealth = _worldFilter.GetHealthRatio(activeTargetId),
HealthPct = vitalsKnown ? v!.HealthPct : -1,
StaminaPct = vitalsKnown && v!.MaxStamina > 0 ? v.StaminaPct : -1,
ManaPct = vitalsKnown && v!.MaxMana > 0 ? v.ManaPct : -1,
HealLine = 0,
InCombat = 1,
CombatMode = CurrentCombatMode,
};
}
/// <summary>
/// Sends the script's spell with RynthAi's own cast bookkeeping: the cadence guard
/// (MarkCombatCastIssued), the attack interval and the area flag. The pending-offensive
/// judgement (blacklist on no damage) is armed only for a single-target cast at the fight
/// target without NOJUDGE. A damaging cast at the fight target (not NOJUDGE) is tagged for
/// the Damage tab like RynthAi's own: wielded wand, element and level from the spell, the
/// fight's cast count and the last-fight snapshot; a single-target one also runs the
/// kill-shot prediction (EvaluateKillShot), as RynthAi's own cast does.
/// </summary>
private bool IssueScriptCast(int spellId, uint castTarget, uint flags, string fallbackElement)
{
bool area = (flags & RynthAiCombat.FlagArea) != 0;
bool noJudge = (flags & RynthAiCombat.FlagNoJudge) != 0;
string name = SpellTableStub.GetById(spellId)?.Name ?? $"spell {spellId}";
bool ok;
try { ok = _host.CastSpellFor(castTarget, spellId, "Combat", name + " (script)"); }
catch { ok = false; }
if (!ok) return false;
MarkCombatCastIssued();
StartCastChatTrace(spellId, unchecked((int)castTarget)); // the server's answers, logged as for RynthAi's own casts
SessionAttackCasts++;
CastsSinceLastKill++;
_lastSpellCast = DateTime.Now;
_scriptCastSpellId = spellId;
_scriptCastAt = DateTime.Now;
_scriptCastSent = ActionPacer.CastsSent; // includes this cast: any later send changes it
bool atFight = castTarget == unchecked((uint)activeTargetId);
bool judged = atFight && !area && !noJudge;
_lastCastWasRing = !judged; // anything else gets no per-target judgement
_wallFaceAt = DateTime.MinValue;
if (judged)
{
// What the NO DAMAGE report names as the last cast (ReportNoDamageCasts).
_lastOffensiveCastLine = $"script id={spellId} '{name}' target=0x{castTarget:X8}";
_pendingOffensiveSpellId = spellId;
_pendingOffensiveCastAt = DateTime.Now;
_pendingOffensiveTargetId = activeTargetId;
}
// As the native block: a throw here must not fail the cast that already went out (the
// slot would stay Decided and the same answer be cast again).
// A single-target damaging cast at the fight target also takes part in RynthAi's kill-shot
// swap (Think arms it, the deferred swap moves on while the projectile flies), with the
// weapon, element and tier just tagged. Area, nojudge and off-target casts never do.
_predictKillSwap = false;
if (atFight && !noJudge)
{
try
{
TagScriptCast(spellId, area, fallbackElement);
if (!area) EvaluateKillShot(_lastCastWeaponId, _lastCastElement, _lastCastTier, isRing: false);
}
catch { }
}
LastCombatSkipReason = "script-cast"; // D4 record-only
string tags = (area ? " (area)" : "") + (noJudge ? " (nojudge)" : "");
_host.Log($"[CombatCast] script id={spellId} '{name}' at 0x{castTarget:X8}{tags} " +
$"fight=0x{activeTargetId:X8} owner='{CombatHook.Owner}'");
return true;
}
/// <summary>
/// The damage attribution RynthAi's own cast does (AttackWithMagic), for a script's cast at
/// the fight target: the weapon, element and tier the pushed damage is filed under, the
/// Damage tab's latest tier, the casts-to-kill count and the last-fight snapshot.
/// </summary>
private void TagScriptCast(int spellId, bool area, string fallbackElement)
{
int castWand = InHandWeaponId();
if (castWand == 0 || !IsWandObject(_worldFilter[castWand] ?? new WorldObject(0, ""))) castWand = FindWandInItems();
_lastCastWeaponId = unchecked((uint)castWand);
// No element in the spell (a Life drain, say) on a caster with no War or Void: the plan's
// element (a weapon-weakness pick like "Slash") would be wrong, so it is filed under
// "Physical", the key RynthAi's own damage path already uses for vital drains.
_lastCastElement = ScriptSpellElement(spellId) ?? (AttackMagicTrained ? fallbackElement : "Physical");
int castLevel = SpellTableStub.GetById(spellId)?.Level ?? 0;
if (castLevel <= 0 && SpellDatabase.TryGetCategoryAndPower(spellId, out _, out int castPower))
castLevel = SpellDatabase.LevelFromPower(castPower);
if (castLevel <= 0)
castLevel = Math.Max(_spellManager?.GetHighestSpellTier(AcSkillType.WarMagic) ?? 0,
_spellManager?.GetHighestSpellTier(AcSkillType.VoidMagic) ?? 0);
_lastCastTier = area ? -castLevel : castLevel; // area casts filed with the rings (negative)
if (_fightTargetWcid != 0) _damageStore?.NoteCast(_fightTargetWcid, _lastCastTier, _fightTargetName);
_fightCastCount++;
if (_fightTargetWcid != 0)
{
_lastFightWcid = _fightTargetWcid;
_lastFightName = _worldFilter[activeTargetId]?.Name ?? _fightTargetName;
_lastFightWeaponId = _lastCastWeaponId;
_lastFightElement = _lastCastElement;
_lastFightTier = _lastCastTier;
_lastFightCount = _fightCastCount;
StampRecentFight();
}
}
/// <summary>
/// The element of a war/void attack spell, from RynthAi's own shape tables (base name, tier-7
/// lore names, ring lore names, wall categories), else from its name's words; null when
/// none of those says.
/// </summary>
internal static string? ScriptSpellElement(int spellId)
{
string? name = SpellTableStub.GetById(spellId)?.Name;
if (string.IsNullOrEmpty(name)) return null;
string n = name.Trim();
if (n.StartsWith("Incantation of ", StringComparison.OrdinalIgnoreCase)) n = n.Substring(15).Trim();
int sp = n.LastIndexOf(' ');
if (sp > 0 && IsRoman(n.Substring(sp + 1))) n = n.Substring(0, sp);
// Blade and Slash share their spells: answer Slash (the Damage tab's element name).
foreach (var kv in SpellShapes)
if (!kv.Key.Equals("Blade", StringComparison.OrdinalIgnoreCase)
&& Array.Exists(kv.Value, b => b.Equals(n, StringComparison.OrdinalIgnoreCase)))
return kv.Key;
foreach (var table in new[] { WarTier7Lore, RingLoreNames })
foreach (var kv in table)
if (!kv.Key.Equals("Blade", StringComparison.OrdinalIgnoreCase)
&& Array.Exists(kv.Value, b => b.Equals(name.Trim(), StringComparison.OrdinalIgnoreCase)))
return kv.Key;
if (SpellDatabase.TryGetCategoryAndPower(spellId, out int category, out _))
foreach (var kv in WallCategories)
if (kv.Value == category && !kv.Key.Equals("Blade", StringComparison.OrdinalIgnoreCase)) return kv.Key;
string byWords = PetChoice.ElementFromName(name);
return byWords.Length > 0 ? byWords : null;
static bool IsRoman(string s)
{
if (s.Length == 0) return false;
foreach (char c in s) if (c != 'I' && c != 'V' && c != 'X') return false;
return true;
}
}
// -- Refusal memory for script casts --
// The script's last cast, while it is still the last cast this plugin sent (ActionPacer counts
// every send: combat, buffs and heals, nav, commands, meta): a hard refusal arriving soon after
// it is the script spell's, and parks that spell. Forgotten once any other cast goes out, the
// spell's own success line arrives, or the window passes.
private int _scriptCastSpellId;
private DateTime _scriptCastAt = DateTime.MinValue;
private long _scriptCastSent;
private readonly System.Collections.Generic.Dictionary<int, DateTime> _scriptParkedUntil = new();
/// <summary>How long a script spell the server refused outright is rejected (as BuffManager parks a vital level).</summary>
internal const double ScriptParkSec = 600.0;
/// <summary>A refusal later than this after the script's cast is not attributed to it.</summary>
internal const double ScriptRefusalWindowMs = 2_000.0;
/// <summary>Host tests: true while <paramref name="spellId"/> is parked after a refusal.</summary>
internal bool ScriptSpellParked(int spellId) => _scriptParkedUntil.TryGetValue(spellId, out DateTime u) && DateTime.Now < u;
/// <summary>A chat line: park the script's last spell on a hard refusal (missing components, unknown spell).</summary>
private void NoteScriptCastRefusal(string text)
{
if (_scriptCastSpellId == 0) return;
if (ActionPacer.CastsSent != _scriptCastSent
|| (DateTime.Now - _scriptCastAt).TotalMilliseconds > ScriptRefusalWindowMs) { _scriptCastSpellId = 0; return; }
string lo = text.ToLowerInvariant();
string? own = SpellTableStub.GetById(_scriptCastSpellId)?.Name;
if (own != null && lo.Contains("ou cast " + own.ToLowerInvariant())) { _scriptCastSpellId = 0; return; } // it landed
if (!(lo.Contains("missing some required") || lo.Contains("you do not have the")
|| lo.Contains("have all the components for this spell"))) return;
int spell = _scriptCastSpellId;
_scriptCastSpellId = 0;
_scriptParkedUntil[spell] = DateTime.Now.AddSeconds(ScriptParkSec);
_host.Log($"[CombatCast] script spell id={spell} '{SpellTableStub.GetById(spell)?.Name}' refused: '{text.Trim()}'. " +
$"Rejected for {ScriptParkSec / 60:0} min (RynthAi chooses instead while the script asks for it).");
}
}

View file

@ -296,6 +296,11 @@ public partial class CombatManager : IDisposable
/// Stamina to Mana), or null to cast. Null hook = never hold (2026-10-11).
/// </summary>
public Func<int, string?>? ManaReserveHold { get; set; }
/// <summary>
/// BuffManager.CanEverAfford, for the script hook: false when a spell costs more than max mana,
/// so ManaReserveHold would hold it forever. Null hook = always affordable.
/// </summary>
public Func<int, bool>? ManaCanEverAfford { get; set; }
private bool _manaCastHeld; // AttackWithMagic held its cast for mana this tick
private bool _manaHoldLogged;
@ -787,6 +792,9 @@ public partial class CombatManager : IDisposable
PickedWeaponWieldLoc = weaponWieldLoc,
HasWieldedAmmoFlag = hasAmmo,
LastCombatSkipReason = LastCombatSkipReason,
ScriptHookOwner = CombatHook.IsActive(RynthAiCombat.KindsAll) ? CombatHook.Owner : "",
ScriptHookKinds = CombatHook.IsActive(RynthAiCombat.KindsAll) ? CombatHook.Kinds : 0,
ScriptHook = CombatHook.Describe(),
};
}
@ -817,6 +825,11 @@ public partial class CombatManager : IDisposable
public int PickedWeaponWieldLoc;
public bool HasWieldedAmmoFlag;
public string LastCombatSkipReason;
/// <summary>The script holding the combat hook (RynthAi.Combat), "" when none; and its kinds (RynthAiCombat.Kind* bits).</summary>
public string ScriptHookOwner;
public uint ScriptHookKinds;
/// <summary>The hook's one-line summary (owner, lease, per-kind counters).</summary>
public string ScriptHook;
}
/// <summary>
@ -1530,6 +1543,9 @@ public partial class CombatManager : IDisposable
// BuffManager's categorisation so a war spell the char can't actually
// cast gets marked unresolvable and FindBestOffensiveSpellId drops to
// an alternative, instead of silently re-firing the dead spell forever.
// A script's cast (RynthAi.Combat) is remembered on its own: it may not have armed the
// pending judgement (an area, nojudge or off-target cast) yet must not be re-cast forever.
NoteScriptCastRefusal(text);
if (_pendingOffensiveSpellId != 0)
{
string lo = text.ToLowerInvariant();
@ -3141,6 +3157,15 @@ public partial class CombatManager : IDisposable
return true;
}
// Waiting on a script's choice of spell (RynthAi.Combat): nothing was sent. The same
// as the wall hold: the attack interval doesn't start, the target and scan stay as they
// are, and the next tick asks again (bounded by the request's deadline).
if (_scriptHeld)
{
_tickWait = CombatLatencyTracker.Wait.Other;
return true;
}
// Don't restore the physical weapon on top of a cast just issued this tick
// (AttackWithMagic → MarkCombatCastIssued): the UseObject + re-equip below would
// truncate the in-flight gesture and strand Player.IsBusy. Defer one windup
@ -4039,11 +4064,32 @@ public partial class CombatManager : IDisposable
/// <summary>The Items list's usable weapons, in list order, with their kind, element, rending and whether each is in hand.</summary>
internal List<WeaponCandidate> ListedCandidates()
{
var list = ListedCandidates(admitCasters: false, out List<int>? leftOut);
// A script choosing the attack spells (RynthAi.Combat) can attack with a caster whatever
// War/Void training says, but only when the list has no melee/missile weapon to use:
// a fighter's listed buff wand must not pull it out of melee.
if (list.Count == 0 && leftOut != null && ScriptPicksAttack)
return ListedCandidates(admitCasters: true, out _);
if (list.Count == 0 && leftOut != null)
foreach (int id in leftOut)
if (_wandRejectedNoted.Add(id))
_host.Log($"[EquipDiag] caster 0x{(uint)id:X8} '{_worldFilter[id]?.Name}' is not a combat weapon: {CanMagicDiag()}");
return list;
}
/// <param name="admitCasters">Take listed casters even with War and Void untrained.</param>
/// <param name="leftOut">The casters skipped for that (null when none).</param>
private List<WeaponCandidate> ListedCandidates(bool admitCasters, out List<int>? leftOut)
{
leftOut = null;
int inHand = InHandWeaponId();
var list = new List<WeaponCandidate>();
foreach (var r in _settings.ItemRules)
{
if (r.Id == 0 || !IsUsableCombatWeapon(r.Id)) continue;
if (r.Id == 0) continue;
var cand = _worldFilter[r.Id];
if (cand == null) continue;
if (!admitCasters && !IsUsableCombatWeapon(r.Id)) { (leftOut ??= new List<int>()).Add(r.Id); continue; }
if (list.Any(c => c.Id == r.Id)) continue;
var wo = _worldFilter[r.Id];
if (wo == null) continue;
@ -4290,7 +4336,7 @@ public partial class CombatManager : IDisposable
if ((DateTime.Now - _lastEquipDiagAt).TotalSeconds > 5)
{
_lastEquipDiagAt = DateTime.Now;
_host.Log($"[EquipDiag] no weapon found (source=none, desired='{desired}', ItemRules={_settings.ItemRules.Count}, MonsterRule='{rule?.Name ?? "null"}') — proceeding unarmed");
_host.Log($"[EquipDiag] no weapon found (source=none, desired='{desired}', ItemRules={_settings.ItemRules.Count}, MonsterRule='{rule?.Name ?? "null"}', {CanMagicDiag()}) - proceeding unarmed");
}
return EnsureUnarmedStance();
}
@ -5299,6 +5345,7 @@ public partial class CombatManager : IDisposable
{
_wallFaceHeld = false;
_manaCastHeld = false;
_scriptHeld = false;
if (_spellManager == null || target == null) return;
// Hard safety veto: never cast offensive magic at something AC's combat
@ -5399,6 +5446,11 @@ public partial class CombatManager : IDisposable
}
}
// A script chooses this cast (RynthAi.Combat, CombatManager.ScriptHook.cs): ask it, wait for
// its answer (held, not an attack yet), cast what it chose; a decline, a bad answer or no
// answer in time falls through to RynthAi's own choice below, this same tick.
if (TryScriptAttack(target, element)) return;
if (rule != null && PickBaseShape(rule) < 0)
{
_host.Log($"[CombatCast] rule '{rule.Name}' has no attack shapes enabled (UseArc/Ring/Streak/Bolt/Blast/Wall all false) — no offensive cast");
@ -5596,13 +5648,32 @@ public partial class CombatManager : IDisposable
private static bool IsWandObject(WorldObject wo) => WeaponList.IsWand(wo);
/// <summary>War or Void Magic trained — the character can attack with a caster.
/// Skills not read yet count as trained, like the other skill gates here.</summary>
private bool CanAttackWithMagic =>
/// <summary>War or Void Magic trained. Skills not read yet count as trained, like the
/// other skill gates here.</summary>
private bool AttackMagicTrained =>
_charSkills == null
|| _charSkills[AcSkillType.WarMagic].Training >= 2
|| _charSkills[AcSkillType.VoidMagic].Training >= 2;
/// <summary>A script holds the attack kind (RynthAi.Combat): it picks the attack spell, from
/// any school, so a caster is the combat weapon whatever War/Void training says.</summary>
private static bool ScriptPicksAttack => CombatHook.IsActive(RynthAiCombat.KindAttack);
/// <summary>The character can attack with a caster: War or Void Magic trained, or a script
/// choosing the attack spells (a Life-only caster whose script drains, for one). Gates the
/// wand fallback when no weapon was chosen; the Items list itself admits a caster under the
/// hook only when it has no melee/missile weapon (ListedCandidates).</summary>
private bool CanAttackWithMagic => AttackMagicTrained || ScriptPicksAttack;
/// <summary>For the [EquipDiag] lines: canMagic and whether the script hook made it true.</summary>
private string CanMagicDiag()
{
bool trained = AttackMagicTrained, hook = ScriptPicksAttack;
return $"canMagic={trained || hook}" + (hook && !trained ? " (script attack hook)" : "");
}
private readonly HashSet<int> _wandRejectedNoted = new();
/// <summary>A weapon combat may fight with: anything the character has (in the world
/// cache) but a caster when the character has no attack magic. Debuff casting picks its
/// wand separately. An id missing from the cache is not a candidate: a weapon that was
@ -5613,7 +5684,7 @@ public partial class CombatManager : IDisposable
{
var wo = _worldFilter[id];
if (wo == null) return false;
return CanAttackWithMagic || !IsWandObject(wo);
return AttackMagicTrained || !IsWandObject(wo);
}
private static List<string> BuildDebuffList(MonsterRule rule, string element)

View file

@ -0,0 +1,379 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// 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 <see cref="Step"/>: 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.
/// </summary>
internal static class CombatHook
{
/// <summary>What a consumer does this tick.</summary>
internal enum Outcome { Native, Wait, Decided }
/// <summary>One kind's request slot.</summary>
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;
}
}
/// <summary>Milliseconds clock (Environment.TickCount64; the host tests replace it).</summary>
internal static Func<long> Clock = static () => Environment.TickCount64;
internal static long Now => Clock();
/// <summary>A timeout is logged at most this often per kind.</summary>
internal const long TimeoutLogIntervalMs = 60_000;
private const long RejectLogIntervalMs = 5_000;
/// <summary>A request this long past its deadline when RynthAi next asks is dropped and asked again.</summary>
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;
/// <summary>Forget everything (plugin shutdown, host tests).</summary>
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;
/// <summary>True while <paramref name="kind"/> is held and the lease is live.</summary>
public static bool IsActive(uint kind) => (Kinds & kind) != 0 && Now < LeaseUntilMs;
private static bool LeaseLive => Kinds != 0 && Now < LeaseUntilMs;
/// <summary>Takes or renews the hook. Returns the kinds granted (0 = another owner's lease is live).</summary>
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;
}
/// <summary>Drops <paramref name="kinds"/> now; their open requests are cancelled.</summary>
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; }
}
/// <summary>1 when a request of <paramref name="kind"/> is open and unanswered (copied to <paramref name="request"/>).</summary>
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;
}
/// <summary>The answer to request <paramref name="seq"/>. False = stale.</summary>
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;
}
/// <summary>
/// One consumer step for <paramref name="slot"/>. <paramref name="forTarget"/> 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. <paramref name="build"/> fills a new request's context (RynthAi's
/// view of the fight); Seq, Kind, TargetId and the times are set here.
/// </summary>
public static Outcome Step(Slot slot, uint forTarget, Func<CombatRequestV1> build, Action<string>? 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<CombatRequestV1>();
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;
}
/// <summary>The decided spell went out (or was waited on): the request is done.</summary>
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)
}
/// <summary>The decided spell failed RynthAi's checks: the request is done, RynthAi chooses.</summary>
public static void Reject(Slot slot, string why, Action<string>? 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;
}
/// <summary>One line for /ra combat.</summary>
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)}";
}
}
/// <summary>
/// RynthAi's side of the "RynthAi.Combat" interface: the table RynthPluginQueryInterface hands
/// out, and the functions behind it (pump thread, current plugin instance).
/// </summary>
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;
}
/// <summary>Frees the table and drops the hook (plugin shutdown). Callers resolve it every tick.</summary>
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
{
/// <summary>RynthAi.Combat GetScanned: the combat scan list, nearest first as scanned.</summary>
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;
}
}

View file

@ -15,7 +15,8 @@ public static unsafe class PluginExports
// Typed interfaces for other plugins (host GetPluginInterface, API v68): "RynthAi.Script" v1
// for RynthLua, "RynthAi.Status" v1 for RynthNet (the bot state it shares with the other clients),
// "RynthAi.Activity" v1 for RynthSort (what the bot is doing, so pack moves stay out of its way).
// "RynthAi.Activity" v1 for RynthSort (what the bot is doing, so pack moves stay out of its way),
// "RynthAi.Combat" v1 for RynthLua (a script choosing attack and heal spells, Shared/RynthAiCombatApi.cs).
// Fixed signature: void* (const char* iface, uint version).
[UnmanagedCallersOnly(EntryPoint = "RynthPluginQueryInterface", CallConvs = new[] { typeof(CallConvCdecl) })]
private static IntPtr QueryInterface(IntPtr ifaceAnsi, uint version)
@ -25,7 +26,8 @@ public static unsafe class PluginExports
string iface = ifaceAnsi == IntPtr.Zero ? "" : Marshal.PtrToStringAnsi(ifaceAnsi) ?? "";
IntPtr table = ScriptInterface.Query(iface, version);
if (table == IntPtr.Zero) table = StatusInterface.Query(iface, version);
return table != IntPtr.Zero ? table : ActivityInterface.Query(iface, version);
if (table == IntPtr.Zero) table = ActivityInterface.Query(iface, version);
return table != IntPtr.Zero ? table : CombatHookInterface.Query(iface, version);
}
catch
{
@ -42,6 +44,7 @@ public static unsafe class PluginExports
Runtime.Shutdown();
StatusInterface.Release();
ActivityInterface.Release();
CombatHookInterface.Shutdown(); // the hook goes native at once (RynthLua re-claims after a reload)
// The loot editor's state can be a few hundred KB (LootSnobV4): don't leave it behind on a reload.
foreach (IntPtr p in new[] { Interlocked.Exchange(ref _lootStatePtr, IntPtr.Zero),
Interlocked.Exchange(ref _lootRulePtr, IntPtr.Zero), Interlocked.Exchange(ref _lootVocabPtr, IntPtr.Zero) })

View file

@ -1905,6 +1905,7 @@ public sealed partial class RynthAiPlugin
ChatLine($"[RynthAi] scanned={s.ScannedCount} closest=0x{(uint)s.ClosestScannedId:X8} '{s.ClosestScannedName}' @ {s.ClosestScannedDist:F1}yd");
ChatLine($"[RynthAi] weapon=0x{(uint)s.PickedWeaponId:X8} '{s.PickedWeaponName}' ({s.PickedWeaponWhy}) wieldLoc={s.PickedWeaponWieldLoc} ammoWielded={s.HasWieldedAmmoFlag}");
ChatLine($"[RynthAi] busy={s.BusyCount} sinceAtk={sinceAttackS:F1}s sinceStance={sinceStanceS:F1}s sinceEquip={sinceEquipS:F1}s sinceLost={sinceLostS:F1}s");
ChatLine($"[RynthAi] script {s.ScriptHook}");
// Dump every cache-known object that's wielded — using Host.TryGetObjectWielderInfo
// as the authoritative check, not the cached WieldedLocation/Wielder fields

View file

@ -635,8 +635,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_combatManager = new CombatManager(Host, _dashboard.Settings, _objectCache!, _spellManager);
_combatManager.SetWeaponSwapGate(_weaponSwapGate);
_combatManager.Vitals = _vitals; // the script hook's request carries the player's vitals
_combatManager.HoldIdlePeace = LootHoldsIdlePeace;
_combatManager.ManaReserveHold = spellId => _buffManager?.OffensiveCastHold(spellId); // the mana reserve
_combatManager.ManaCanEverAfford = spellId => _buffManager?.CanEverAfford(spellId) ?? true; // script hook: never-payable spells
_combatManager.SetStaleBusyCallback(OnCombatBusyStale);
_buffManager?.SetStaleBusyCallback(OnCombatBusyStale); // a heal ahead of a leftover busy count
if (_buffManager != null)

View file

@ -35,6 +35,8 @@
<Compile Include="..\Shared\RynthAiStatusApi.cs" Link="Shared\RynthAiStatusApi.cs" />
<!-- RynthSort reads what the bot is doing through RynthAi.Activity (read only). -->
<Compile Include="..\Shared\RynthAiActivityApi.cs" Link="Shared\RynthAiActivityApi.cs" />
<!-- RynthLua's scripts choose attack and heal spells through RynthAi.Combat. -->
<Compile Include="..\Shared\RynthAiCombatApi.cs" Link="Shared\RynthAiCombatApi.cs" />
<!-- RynthNav's navmesh path queries (stuck-recovery detours outdoors). -->
<Compile Include="..\Shared\RynthNavPathApi.cs" Link="Shared\RynthNavPathApi.cs" />
<!-- Reading our hits out of the combat log (victim + amount); RynthTracker reads the same lines. -->