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,155 @@
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using RynthCore.Plugin.Shared;
namespace RynthLua.CompatTests;
/// <summary>
/// A fake "RynthAi.Combat" table (Shared/RynthAiCombatApi.cs) for the compat tests: the same
/// lease, owner, poll and decide rules as RynthAi's CombatHook, served by FakeHost's
/// GetPluginInterface while <see cref="Enabled"/> is set. The test script drives it through
/// the harness (open a request, read the decisions, the claim and release counts).
/// </summary>
internal static unsafe class FakeCombat
{
public sealed record Decision(uint Seq, uint Kind, uint Spell, uint Target, uint Flags, bool Taken);
/// <summary>Served by GetPluginInterface (off: RynthAi without the hook, an older build).</summary>
public static bool Enabled;
public static string Owner = "";
public static uint Kinds;
public static long LeaseUntil;
public static int Claims, Refusals, Releases;
public static uint ReleasedKinds; // every kind a Release named, or'ed
public static readonly List<Decision> Decisions = new();
public static readonly List<(uint Id, float Distance)> Scanned = new();
private sealed class Req { public CombatRequestV1 R; public bool Open, Decided; }
private static readonly Dictionary<uint, Req> Slots = new();
private static uint _seq;
private static RynthAiCombatApiV1* _table;
private static long Now => Environment.TickCount64;
public static void Reset()
{
Enabled = false;
Owner = "";
Kinds = 0;
LeaseUntil = 0;
Claims = Refusals = Releases = 0;
ReleasedKinds = 0;
Decisions.Clear();
Scanned.Clear();
Slots.Clear();
}
/// <summary>RynthAi reloaded: its seq restarts and nothing is claimed or open (the table stays served).</summary>
public static void Reload()
{
_seq = 0;
Slots.Clear();
Owner = "";
Kinds = 0;
LeaseUntil = 0;
}
public static IntPtr Table()
{
if (!Enabled) 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>Opens a request of <paramref name="kind"/> (RynthAi reaching a cast choice). Returns its seq.</summary>
public static uint Open(uint kind, uint targetId, long timeoutMs = 2000)
{
uint seq = ++_seq;
var r = new CombatRequestV1
{
StructSize = (uint)sizeof(CombatRequestV1), Seq = seq, Kind = kind, TargetId = targetId,
TargetHealth = kind == RynthAiCombat.KindAttack ? 0.5f : -1f, HealthPct = 80, StaminaPct = 70, ManaPct = 60,
HealLine = kind == RynthAiCombat.KindHeal ? 60 : 0, InCombat = 1, CombatMode = 8,
IssuedAtMs = Now, DeadlineMs = Now + timeoutMs,
};
if (Slots.TryGetValue(kind, out var old) && old.Decided)
{
r.LastSeq = old.R.Seq;
Decision? d = Decisions.FindLast(x => x.Seq == old.R.Seq && x.Taken);
r.LastSpell = d?.Spell ?? 0;
r.LastTarget = d?.Target ?? 0;
r.LastAtMs = Now;
}
Slots[kind] = new Req { R = r, Open = true };
return seq;
}
private static bool Active(uint kind) => (Kinds & kind) != 0 && Now < LeaseUntil;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int Claim(uint kinds, uint leaseMs, uint attackTimeoutMs, uint healTimeoutMs, byte* owner)
{
string name = owner == null ? "" : Marshal.PtrToStringUTF8((IntPtr)owner) ?? "";
kinds &= RynthAiCombat.KindsAll;
if (Kinds != 0 && Now < LeaseUntil && Owner != name) { Refusals++; return 0; }
Claims++;
Owner = kinds == 0 ? "" : name;
Kinds = kinds;
LeaseUntil = kinds == 0 ? 0 : Now + RynthAiCombat.ClampLease(leaseMs);
return (int)kinds;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static void Release(uint kinds)
{
Releases++;
ReleasedKinds |= kinds;
Kinds &= ~kinds;
if (Kinds == 0) { Owner = ""; LeaseUntil = 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int Poll(uint kind, CombatRequestV1* req)
{
if (req == null || !Active(kind) || !Slots.TryGetValue(kind, out var s) || !s.Open || s.Decided || Now > s.R.DeadlineMs) return 0;
uint room = req->StructSize == 0 || req->StructSize > (uint)sizeof(CombatRequestV1) ? (uint)sizeof(CombatRequestV1) : req->StructSize;
CombatRequestV1 r = s.R;
r.StructSize = room;
Buffer.MemoryCopy(&r, req, room, room);
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int Decide(uint seq, uint kind, uint spellId, uint targetId, uint flags)
{
bool taken = Active(kind) && Slots.TryGetValue(kind, out var s) && s.Open && !s.Decided && s.R.Seq == seq && Now <= s.R.DeadlineMs;
if (taken) Slots[kind].Decided = true;
Decisions.Add(new Decision(seq, kind, spellId, targetId, flags, taken));
return taken ? 1 : 0;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetScanned(uint* ids, float* distances, int capacity)
{
if (ids != null)
for (int i = 0; i < Scanned.Count && i < capacity; i++)
{
ids[i] = Scanned[i].Id;
if (distances != null) distances[i] = Scanned[i].Distance;
}
return Scanned.Count;
}
}

View file

@ -137,7 +137,12 @@ internal static unsafe class FakeHost
private static IntPtr GetAccountName() => Ansi("testaccount");
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static IntPtr GetPluginInterface(IntPtr plugin, IntPtr iface, uint version) => IntPtr.Zero;
private static IntPtr GetPluginInterface(IntPtr plugin, IntPtr iface, uint version)
{
// RynthAi's combat hook when a test turned it on (FakeCombat); nothing else is served.
string p = Marshal.PtrToStringAnsi(plugin) ?? string.Empty, i = Marshal.PtrToStringAnsi(iface) ?? string.Empty;
return p == "RynthAi" && i == RynthCore.Plugin.Shared.RynthAiCombatApiV1.InterfaceName && version == 1 ? FakeCombat.Table() : IntPtr.Zero;
}
// ── Objects ─────────────────────────────────────────────────────────────

View file

@ -22,11 +22,20 @@ internal static class Harness
private static FakeWorld W => FakeWorld.W;
/// <summary>Plugins\RynthCore.Plugin.RynthLua\Examples\<paramref name="file"/>, found from this source file's folder.</summary>
private static string ExamplePath(string file, [System.Runtime.CompilerServices.CallerFilePath] string source = "")
{
string tools = System.IO.Path.GetDirectoryName(System.IO.Path.GetDirectoryName(source) ?? string.Empty) ?? string.Empty;
string root = System.IO.Path.GetDirectoryName(tools) ?? string.Empty;
return System.IO.Path.Combine(root, "Plugins", "RynthCore.Plugin.RynthLua", "Examples", System.IO.Path.GetFileName(file));
}
public static void Reset()
{
Checks = 0;
Failures.Clear();
Done = false;
FakeCombat.Reset();
}
public static void Register(Script s, string scriptName)
@ -216,6 +225,53 @@ internal static class Harness
foreach (uint id in W.SalvageItems) t.Append(DynValue.NewNumber(id));
return DynValue.NewTable(t);
});
// RynthAi's combat hook (FakeCombat): turn the table on/off, open a request as RynthAi
// would, and read back what RynthLua claimed, decided and released.
Fn("combatTable", a => { FakeCombat.Enabled = a.Count > 0 && a[0].CastToBool(); return DynValue.Nil; });
Fn("combatOpen", a => DynValue.NewNumber(FakeCombat.Open((uint)Num(a, 0, 1), Id(a, 1), (long)Num(a, 2, 2000))));
Fn("combatScanned", a =>
{
FakeCombat.Scanned.Clear();
if (a.Count > 0 && a[0].Type == DataType.Table)
foreach (DynValue row in a[0].Table.Values)
FakeCombat.Scanned.Add(((uint)row.Table.Get(1).Number, (float)row.Table.Get(2).Number));
return DynValue.Nil;
});
Fn("combatDecisions", a =>
{
var t = new Table(s);
foreach (var d in FakeCombat.Decisions)
{
var row = new Table(s);
row["seq"] = (double)d.Seq; row["kind"] = (double)d.Kind; row["spell"] = (double)d.Spell;
row["target"] = (double)d.Target; row["flags"] = (double)d.Flags; row["taken"] = d.Taken;
t.Append(DynValue.NewTable(row));
}
return DynValue.NewTable(t);
});
Fn("combatState", a =>
{
var t = new Table(s);
t["owner"] = FakeCombat.Owner; t["kinds"] = (double)FakeCombat.Kinds;
t["claims"] = (double)FakeCombat.Claims; t["refusals"] = (double)FakeCombat.Refusals;
t["releases"] = (double)FakeCombat.Releases; t["releasedKinds"] = (double)FakeCombat.ReleasedKinds;
return DynValue.NewTable(t);
});
// A second script in the same plugin (another script competing for a handler).
Fn("runScript", a => { Plugin!.RunCode(Str(a, 0), Str(a, 1)); return DynValue.Nil; });
Fn("stopScript", a => DynValue.NewBoolean(Plugin!.StopScript(Str(a, 0))));
Fn("scriptLoaded", a => DynValue.NewBoolean(Plugin!.ScriptIsLoaded(Str(a, 0))));
Fn("scriptConsole", a => DynValue.NewString(Plugin!.ScriptConsoleText(Str(a, 0))));
Fn("combatReload", a => { FakeCombat.Reload(); return DynValue.Nil; });
// The text of a script in the plugin's Examples folder (so a test can run it).
Fn("exampleCode", a => DynValue.NewString(System.IO.File.ReadAllText(ExamplePath(Str(a, 0)))));
Fn("scriptHooks", a =>
{
var (keepAlive, onStop) = Plugin!.ScriptHookCounts(Str(a, 0));
var t = new Table(s);
t["keepAlive"] = (double)keepAlive; t["onStop"] = (double)onStop;
return DynValue.NewTable(t);
});
s.Globals["harness"] = DynValue.NewTable(h);
}
}

View file

@ -28,6 +28,7 @@
<ItemGroup>
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthLua\**\*.cs" Exclude="..\..\Plugins\RynthCore.Plugin.RynthLua\obj\**;..\..\Plugins\RynthCore.Plugin.RynthLua\bin\**" Link="Plugin\%(RecursiveDir)%(Filename)%(Extension)" />
<Compile Include="..\..\Plugins\Shared\RynthAiScriptApi.cs" Link="Plugin\Shared\RynthAiScriptApi.cs" />
<Compile Include="..\..\Plugins\Shared\RynthAiCombatApi.cs" Link="Plugin\Shared\RynthAiCombatApi.cs" />
<Compile Include="..\..\Plugins\Shared\UseAudit.cs" Link="Plugin\Shared\UseAudit.cs" />
<Compile Include="..\..\..\RynthCore\src\RynthCore.PluginSdk\*.cs" Link="Sdk\%(Filename)%(Extension)" />
<!-- The SDK takes CurrentApiVersion from the engine's constant since plugin manifests (API v79). -->

View file

@ -0,0 +1,279 @@
-- RynthAi's combat hook from a script (rynth.ai SetAttackHandler / SetHealHandler, RynthLua's
-- CombatHookPump against a fake "RynthAi.Combat" table): the handler's answer reaches Decide, a
-- yielding handler still answers, an error declines, three in a row unregister, one script per
-- kind, a stopped script releases its kinds, and no table means a refusal with the reason.
local ai = require("rynth.ai")
local ATTACK, HEAL = 1, 2
local function decisions() return harness.combatDecisions() end
local function waitDecisions(n)
return waitfor(function() return #decisions() >= n end, 3000)
end
-- No table: RynthAi without the hook (or not loaded).
harness.combatTable(false)
local ok, why = ai.SetAttackHandler(function() return 1 end)
eq(ok, false, "no combat table: refused")
eq(why, "RynthAi has no combat hook", "and says why")
eq(ai.CombatHook.Supported, false, "CombatHook.Supported is false")
eq(ai.CombatHook.AttackOwner, nil, "no owner")
harness.combatTable(true)
sleep(10) -- RynthLua looks the table up again on its next tick
eq(ai.CombatHook.Supported, true, "table on: supported")
-- 1. A decision is posted, with the request's context.
local seen
ok = ai.SetAttackHandler(function(ctx)
seen = ctx
return 1234, ctx.monsters[2].id
end)
eq(ok, true, "attack handler registered")
eq(ai.CombatHook.AttackOwner, "combathook", "the owner is this script")
check(waitfor(function() return harness.combatState().kinds == ATTACK end, 2000), "the pump claims the attack kind")
eq(harness.combatState().owner, "RynthLua/combathook", "claimed under RynthLua/<script>")
eq(ai.CombatHook.Claimed, true, "Claimed")
harness.combatScanned({ { 0x80000101, 3.5 }, { 0x80000102, 7.25 } })
local seq1 = harness.combatOpen(ATTACK, 0x80000101)
check(waitDecisions(1), "the handler answered")
local d = decisions()[1]
eq(d.seq, seq1, "decided for the open seq")
eq(d.kind, ATTACK, "attack kind")
eq(d.spell, 1234, "the handler's spell")
eq(d.target, 0x80000102, "the handler's target")
eq(d.flags, 0, "no flags")
eq(d.taken, true, "taken by RynthAi")
eq(seen.seq, seq1, "ctx.seq")
eq(seen.kind, "attack", "ctx.kind")
eq(seen.targetId, 0x80000101, "ctx.targetId")
eq(seen.targetHealth, 0.5, "ctx.targetHealth")
eq(seen.healthPct, 80, "ctx.healthPct")
eq(seen.inCombat, true, "ctx.inCombat")
eq(seen.combatMode, 8, "ctx.combatMode")
check(seen.deadline > seen.issuedAt, "ctx.deadline after ctx.issuedAt")
check(seen.deadline > clock(), "ctx.deadline is on clock()'s scale and still ahead")
eq(#seen.monsters, 2, "ctx.monsters")
eq(seen.monsters[1].distance, 3.5, "ctx.monsters[1].distance")
eq(seen.last.seq, 0, "no last decision yet")
-- The next request carries the last decision.
local seq2 = harness.combatOpen(ATTACK, 0x80000101)
check(waitDecisions(2), "second request answered")
eq(seen.last.seq, seq1, "ctx.last.seq")
eq(seen.last.spell, 1234, "ctx.last.spell")
eq(seen.last.target, 0x80000102, "ctx.last.target")
-- 2. A yielding handler (the same script registering again replaces its handler), area flag.
ok = ai.SetAttackHandler(function(ctx)
sleep(60)
return 55, nil, "area"
end)
eq(ok, true, "the same script replaces its handler")
local seq3 = harness.combatOpen(ATTACK, 0x80000101)
check(waitDecisions(3), "the yielding handler still answers")
d = decisions()[3]
eq(d.seq, seq3, "for its seq")
eq(d.spell, 55, "its spell")
eq(d.target, 0, "nil target = the request's target")
eq(d.flags, 1, "\"area\" sets the AREA flag")
eq(d.taken, true, "taken")
-- 3. nil declines.
ai.SetAttackHandler(function(ctx) return nil end)
harness.combatOpen(ATTACK, 0x80000101)
check(waitDecisions(4), "a nil answer is still an answer")
eq(decisions()[4].spell, 0, "nil = decline (spell 0)")
-- 4. An error declines at once; three in a row unregister.
ai.SetAttackHandler(function(ctx) error("boom (expected)") end)
for i = 1, 3 do
harness.combatOpen(ATTACK, 0x80000101)
check(waitDecisions(4 + i), "error " .. i .. ": declined at once")
eq(decisions()[4 + i].spell, 0, "error " .. i .. ": spell 0")
eq(decisions()[4 + i].taken, true, "error " .. i .. ": taken (no wait for the deadline)")
end
eq(ai.CombatHook.AttackOwner, nil, "three errors: the handler is removed")
check(waitfor(function() return harness.combatState().kinds == 0 end, 2000), "and the kind released in RynthAi")
local unregistered = false
for _, line in ipairs(harness.chatLog()) do
if line:find("failed 3 times in a row", 1, true) then unregistered = true end
end
check(unregistered, "a chat warning says so")
check(harness.scriptConsole("combathook"):find("combat attack handler:", 1, true) ~= nil, "each error is in the console")
-- A bad answer counts as an error too (and declines).
ai.SetAttackHandler(function(ctx) return "fireball" end)
harness.combatOpen(ATTACK, 0x80000101)
check(waitDecisions(8), "a bad answer declines")
eq(decisions()[8].spell, 0, "spell 0")
check(harness.scriptConsole("combathook"):find("expected a spell id", 1, true) ~= nil, "and says what was wrong")
ai.ClearCombatHandlers()
eq(ai.CombatHook.AttackOwner, nil, "ClearCombatHandlers drops it")
-- 5. One script per kind; a stopped script releases its kinds.
ok = ai.SetHealHandler(function(ctx) return 2001, 0 end)
eq(ok, true, "heal handler registered")
harness.runScript("rival", [[
local ai = require("rynth.ai")
local ok, why = ai.SetHealHandler(function(ctx) return 9 end)
eq(ok, false, "rival: the heal kind is taken")
eq(why, "the heal handler is already set by combathook", "rival: and by whom")
ok = ai.SetAttackHandler(function(ctx) return 777 end)
eq(ok, true, "rival: the attack kind is free")
rivalReady = true
]])
check(waitfor(function() return ai.CombatHook.AttackOwner == "rival" end, 2000), "the rival holds attack")
eq(ai.CombatHook.HealOwner, "combathook", "this script still holds heal")
check(waitfor(function() return harness.combatState().kinds == ATTACK + HEAL end, 2000), "both kinds claimed")
eq(harness.combatState().owner, "RynthLua/combathook+rival", "under both scripts' names")
check(harness.scriptLoaded("rival"), "the rival's main chunk ended but its handler keeps it running")
local healSeq = harness.combatOpen(HEAL, 0)
check(waitDecisions(9), "heal answered")
eq(decisions()[9].seq, healSeq, "heal seq")
eq(decisions()[9].kind, HEAL, "heal kind")
eq(decisions()[9].spell, 2001, "heal spell")
local releasesBefore = harness.combatState().releases
check(harness.stopScript("rival"), "stop the rival")
check(not harness.scriptLoaded("rival"), "stopped")
check(harness.combatState().releases > releasesBefore, "stopping it released in RynthAi")
check(harness.combatState().releasedKinds % 2 == 1, "the attack kind among the released")
eq(ai.CombatHook.AttackOwner, nil, "attack is free again")
eq(ai.CombatHook.HealOwner, "combathook", "heal untouched")
check(waitfor(function() return harness.combatState().kinds == HEAL end, 2000), "only heal claimed now")
-- SetHealHandler(nil) clears this script's heal handler.
ai.SetHealHandler(nil)
eq(ai.CombatHook.HealOwner, nil, "nil clears it")
check(waitfor(function() return harness.combatState().kinds == 0 end, 2000), "nothing claimed")
-- 6. Flags: "nojudge", a table of flags, true = area; an unknown flag is an error.
local function answerWith(fn)
ai.SetAttackHandler(fn)
local n = #decisions()
harness.combatOpen(ATTACK, 0x80000101)
check(waitDecisions(n + 1), "answered")
return decisions()[n + 1]
end
eq(answerWith(function() return 55, nil, "nojudge" end).flags, 2, "\"nojudge\" sets the NOJUDGE flag")
eq(answerWith(function() return 55, nil, { area = true, nojudge = true } end).flags, 3, "a table sets both")
eq(answerWith(function() return 55, nil, { nojudge = true, area = false } end).flags, 2, "a false field is no flag")
eq(answerWith(function() return 55, nil, true end).flags, 1, "true is still \"area\"")
d = answerWith(function() return 55, nil, "aera" end)
eq(d.spell, 0, "an unknown flag declines")
check(harness.scriptConsole("combathook"):find('expected "area", "nojudge"', 1, true) ~= nil, "and says what it expected")
ai.ClearCombatHandlers()
-- 7. Set/clear cycles register the script's KeepAlive / OnStop hooks once, not once per cycle.
ai.SetAttackHandler(function() return nil end)
local hooks = harness.scriptHooks("combathook")
check(hooks.keepAlive >= 1 and hooks.onStop >= 1, "the hooks are registered")
for i = 1, 3 do
ai.ClearCombatHandlers()
ai.SetAttackHandler(function() return nil end)
ai.SetHealHandler(function() return nil end)
end
local after = harness.scriptHooks("combathook")
eq(after.keepAlive, hooks.keepAlive, "no KeepAlive hook added by the cycles")
eq(after.onStop, hooks.onStop, "no OnStop hook added by the cycles")
ai.ClearCombatHandlers()
check(waitfor(function() return harness.combatState().kinds == 0 end, 2000), "nothing claimed")
-- 8. A handler that never returns is aborted after the deadline plus the stall budget and counts
-- as an error; three in a row remove it and release the kind.
ai.SetAttackHandler(function(ctx) while true do sleep(50) end end)
check(waitfor(function() return harness.combatState().kinds == ATTACK end, 2000), "the stalling handler's kind is claimed")
for i = 1, 3 do
local n = #decisions()
local t0 = clock()
harness.combatOpen(ATTACK, 0x80000101, 100)
check(waitDecisions(n + 1), "stall " .. i .. ": the stuck handler is aborted and declines")
eq(decisions()[n + 1].spell, 0, "stall " .. i .. ": spell 0")
check(clock() - t0 >= 1000, "stall " .. i .. ": only after the deadline plus the stall budget")
end
eq(ai.CombatHook.AttackOwner, nil, "three stalls: the handler is removed")
check(waitfor(function() return harness.combatState().kinds == 0 end, 2000), "and the kind released in RynthAi")
local stalledLine = false
for _, line in ipairs(harness.chatLog()) do
if line:find("did not answer within the deadline 3 times in a row", 1, true) then stalledLine = true end
end
check(stalledLine, "a chat line says the handler did not answer within the deadline")
check(harness.scriptConsole("combathook"):find("the handler did not answer within the deadline", 1, true) ~= nil, "each stall is in the console")
-- 9. RynthAi reloads (its seq restarts): a new request whose seq repeats the last one started is
-- still answered.
ai.SetAttackHandler(function(ctx) return 4242 end)
harness.combatReload()
local before = #decisions()
eq(harness.combatOpen(ATTACK, 0x80000101), 1, "after a reload the first request is seq 1")
check(waitDecisions(before + 1), "answered")
harness.combatReload() -- again: the next request is seq 1 too, the same seq as the last one started
before = #decisions()
eq(harness.combatOpen(ATTACK, 0x80000101), 1, "seq 1 again")
check(waitDecisions(before + 1), "the repeated seq is still answered (it is a new request)")
eq(decisions()[before + 1].spell, 4242, "with the handler's spell")
eq(decisions()[before + 1].taken, true, "taken")
ai.ClearCombatHandlers()
-- 10. Replacing a handler while it is still answering: the new one answers the open request.
local slowStarted = false
ai.SetAttackHandler(function(ctx) slowStarted = true; sleep(400); return 11 end)
check(waitfor(function() return harness.combatState().kinds == ATTACK end, 2000), "claimed")
before = #decisions()
harness.combatOpen(ATTACK, 0x80000101)
check(waitfor(function() return slowStarted end, 2000), "the slow handler is running")
ai.SetAttackHandler(function(ctx) return 77 end)
check(waitDecisions(before + 1), "the replacement answers the open request")
eq(decisions()[before + 1].spell, 77, "the new handler's answer")
eq(decisions()[before + 1].taken, true, "taken")
sleep(500)
eq(#decisions(), before + 1, "the replaced handler's answer never arrives")
ai.ClearCombatHandlers()
check(waitfor(function() return harness.combatState().kinds == 0 end, 2000), "nothing claimed")
-- 11. Examples\combat-handler.lua, with its spell ids and lines set.
local example = harness.exampleCode("combat-handler.lua")
local code = example
local n1, n2, n3, n4
code, n1 = code:gsub("local FINISHER_SPELL = 0", "local FINISHER_SPELL = 3001", 1)
code, n2 = code:gsub("local FINISH_BELOW = 0%.30", "local FINISH_BELOW = 0.60", 1)
code, n3 = code:gsub("local HEAL_SPELL = 0", "local HEAL_SPELL = 3002", 1)
code, n4 = code:gsub("local HEAL_BELOW = 50", "local HEAL_BELOW = 90", 1)
eq(n1 + n2 + n3 + n4, 4, "example: its four settings found")
harness.runScript("combat-handler", code)
check(waitfor(function() return ai.CombatHook.AttackOwner == "combat-handler" and ai.CombatHook.HealOwner == "combat-handler" end, 2000),
"example: holds attack and heal")
check(harness.scriptConsole("combat-handler"):find("combat handlers on", 1, true) ~= nil, "example: says it is on")
before = #decisions()
harness.combatOpen(ATTACK, 0x80000101) -- target health 0.5, under its 0.60
check(waitDecisions(before + 1), "example: attack answered")
eq(decisions()[before + 1].spell, 3001, "example: its finisher under the line")
eq(decisions()[before + 1].target, 0, "example: at RynthAi's target")
harness.combatOpen(HEAL, 0) -- health 80%, under its 90
check(waitDecisions(before + 2), "example: heal answered")
eq(decisions()[before + 2].spell, 3002, "example: its heal under the line")
eq(decisions()[before + 2].target, 0, "example: on yourself")
harness.chatInput("/combathook")
check(waitfor(function() return ai.CombatHook.AttackOwner == nil and harness.combatState().kinds == 0 end, 2000), "example: /combathook turns it off")
harness.chatInput("/combathook")
check(waitfor(function() return ai.CombatHook.AttackOwner == "combat-handler" end, 2000), "example: and on again")
check(harness.stopScript("combat-handler"), "example: stopped")
eq(ai.CombatHook.AttackOwner, nil, "example: stopping releases attack")
eq(ai.CombatHook.HealOwner, nil, "example: and heal")
-- As shipped (ids 0) it declines; a kind held by another script is refused with the reason.
ai.SetAttackHandler(function() return nil end)
harness.runScript("combat-handler", example)
check(waitfor(function() return ai.CombatHook.HealOwner == "combat-handler" end, 2000), "shipped example: holds heal")
check(harness.scriptConsole("combat-handler"):find("attack handler refused: the attack handler is already set by combathook", 1, true) ~= nil,
"shipped example: prints why attack was refused")
before = #decisions()
harness.combatOpen(HEAL, 0)
check(waitDecisions(before + 1), "shipped example: heal answered")
eq(decisions()[before + 1].spell, 0, "shipped example: no heal id set, so it declines")
harness.stopScript("combat-handler")
ai.ClearCombatHandlers()
done()