Snapshot for release 2026.10.13.1 (internal d2b5fb3)

This commit is contained in:
Tom Bohar 2026-10-13 14:25:49 -04:00
commit 319740ff5d
291 changed files with 58505 additions and 2107 deletions

View file

@ -0,0 +1,393 @@
using System;
using System.Collections.Generic;
using System.Linq;
using MoonSharp.Interpreter;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthLua;
/// <summary>
/// RynthLua's side of RynthAi's combat hook ("RynthAi.Combat", Shared/RynthAiCombatApi.cs):
/// scripts register an attack and/or heal handler (rynth.ai SetAttackHandler / SetHealHandler),
/// and every tick, before the scripts run, this pump renews RynthAi's lease for the kinds that
/// have a handler, polls each kind, and starts the handler as a script thread for a new request.
/// When the thread ends its answer goes back with Decide. The handler never runs inside RynthAi:
/// it is an ordinary script thread (it may yield; auto-yield keeps a runaway one from freezing the
/// client), and RynthAi casts what it answers. RynthAi waits up to the request's deadline, then
/// chooses for itself.
///
/// One script per kind (the first to register owns it; the same script registering again
/// replaces its handler). A handler error declines that request; three in a row unregister the
/// handler. A stopped script releases its kinds; an unloaded or stalled RynthLua stops renewing
/// and RynthAi goes native when the lease lapses.
/// </summary>
public sealed partial class RynthLuaPlugin
{
/// <summary>Consecutive handler errors that unregister a handler.</summary>
internal const int CombatHandlerMaxErrors = 3;
/// <summary>
/// How long past its request's deadline a handler thread may run before it is aborted and
/// counted as an error (a handler that never returns would otherwise hold its kind forever).
/// </summary>
internal const long CombatHandlerStallMs = 1_000;
private const string CombatStallError = "the handler did not answer within the deadline";
private const string CombatLateError = "the handler answered after the deadline (RynthAi had already chosen)";
private sealed class CombatHandler
{
public required ScriptContext Ctx;
public required uint Kind;
public DynValue Fn = DynValue.Nil;
public int Errors;
public bool InFlight;
public object? Thread; // the in-flight handler thread (LuaScriptHost.Abort)
public uint InFlightSeq;
public long StartedDeadlineMs; // the in-flight request's deadline (RynthAi's clock)
// The last request started, by seq AND issue time: RynthAi's seq restarts when it reloads.
public uint LastStartedSeq;
public long LastStartedIssuedAtMs;
}
/// <summary>The pump's clock; must match RynthAi's (CombatHook.Clock, Environment.TickCount64).</summary>
internal static Func<long> CombatClock = () => Environment.TickCount64;
private readonly Dictionary<uint, CombatHandler> _combatHandlers = new();
// Scripts whose KeepAlive / OnStop hooks are registered: once per run (ScriptContext.Clear
// drops both lists when the script stops, and the OnStop hook takes the script out of here).
private readonly HashSet<ScriptContext> _combatHooked = new();
private uint _combatClaimedKinds;
private string _combatClaimOwner = string.Empty;
private bool _combatRefusedLogged;
internal static string CombatKindName(uint kind) => kind == RynthAiCombat.KindAttack ? "attack" : "heal";
/// <summary>The script holding <paramref name="kind"/>, or null.</summary>
internal string? CombatOwner(uint kind) => _combatHandlers.TryGetValue(kind, out var h) ? h.Ctx.Name : null;
/// <summary>True when RynthAi granted the kinds last claimed (this tick's claim).</summary>
internal bool CombatClaimed => _combatClaimedKinds != 0;
/// <summary>
/// Sets (fn a function) or clears (fn nil) <paramref name="ctx"/>'s handler for <paramref name="kind"/>.
/// Returns null on success, or why it was refused.
/// </summary>
internal string? SetCombatHandler(ScriptContext ctx, uint kind, DynValue fn)
{
if (fn.IsNil())
{
if (_combatHandlers.TryGetValue(kind, out var mine) && mine.Ctx == ctx) DropCombatHandler(kind, release: true);
return null;
}
if (fn.Type != DataType.Function) return "the handler must be a function (or nil to clear it)";
if (!_ai.CombatAvailable) return "RynthAi has no combat hook";
if (_combatHandlers.TryGetValue(kind, out var held) && held.Ctx != ctx)
return $"the {CombatKindName(kind)} handler is already set by {held.Ctx.Name}";
// The replaced handler's request: already answered, skip it; still running (aborted here,
// its answer no longer counts), start the new handler on it.
bool restart = held != null && held.InFlight;
_combatHandlers[kind] = new CombatHandler
{
Ctx = ctx, Kind = kind, Fn = fn,
LastStartedSeq = restart ? 0 : held?.LastStartedSeq ?? 0,
LastStartedIssuedAtMs = restart ? 0 : held?.LastStartedIssuedAtMs ?? 0,
};
if (restart) held!.Ctx.Host.Abort(held.Thread);
if (_combatHooked.Add(ctx))
{
// A script with only handlers stays running; stopping it releases what it holds.
ctx.KeepAlive.Add(() => _combatHandlers.Values.Count(h => h.Ctx == ctx));
ctx.OnStop.Add(() =>
{
ClearCombatHandlers(ctx);
_combatHooked.Remove(ctx);
});
}
return null;
}
/// <summary>Drops every handler <paramref name="ctx"/> holds and releases those kinds in RynthAi.</summary>
internal void ClearCombatHandlers(ScriptContext ctx)
{
foreach (uint kind in _combatHandlers.Where(kv => kv.Value.Ctx == ctx).Select(kv => kv.Key).ToArray())
DropCombatHandler(kind, release: true);
}
/// <summary>Test harness only: how many KeepAlive / OnStop hooks a script has registered.</summary>
internal (int KeepAlive, int OnStop) ScriptHookCounts(string name)
=> _scripts.TryGetValue(name, out var ctx) ? (ctx.KeepAlive.Count, ctx.OnStop.Count) : (0, 0);
private void DropCombatHandler(uint kind, bool release)
{
if (_combatHandlers.TryGetValue(kind, out var h) && h.InFlight) h.Ctx.Host.Abort(h.Thread);
_combatHandlers.Remove(kind);
if (release)
{
try { _ai.CombatRelease(kind); } catch { }
_combatClaimedKinds &= ~kind;
}
}
/// <summary>Releases every kind (plugin shutdown); RynthAi goes native at once.</summary>
private void ReleaseCombatHook()
{
_combatHandlers.Clear();
_combatHooked.Clear();
if (_combatClaimedKinds != 0)
{
try { _ai.CombatRelease(RynthAiCombat.KindsAll); } catch { }
_combatClaimedKinds = 0;
}
}
/// <summary>One pump pass (OnTick, before the scripts run).</summary>
private void PumpCombatHook()
{
if (_combatHandlers.Count == 0) return; // nothing registered: no per-tick work or allocation
// A handler whose script is gone (stopped without its stop handlers, or never ran).
foreach (var kv in _combatHandlers.Where(kv => !kv.Value.Ctx.Host.Loaded).ToArray())
DropCombatHandler(kv.Key, release: true);
if (_combatHandlers.Count == 0) return;
if (!_ai.CombatAvailable) { _combatClaimedKinds = 0; return; } // RynthAi not loaded (yet): nothing to renew
// A handler past its request's deadline plus the stall budget never answered (a loop that
// sleeps forever, an await that never finishes): abort it so the kind isn't held forever.
long now = CombatClock();
foreach (CombatHandler h in _combatHandlers.Values.ToArray())
if (h.InFlight && now > h.StartedDeadlineMs + CombatHandlerStallMs)
{
h.Ctx.Host.Abort(h.Thread);
OnCombatHandlerDone(h, h.InFlightSeq, null, CombatStallError);
}
if (_combatHandlers.Count == 0) return;
uint kinds = 0;
foreach (uint k in _combatHandlers.Keys) kinds |= k;
string owner = CombatOwnerName();
if (owner != _combatClaimOwner && _combatClaimedKinds != 0)
_ai.CombatRelease(RynthAiCombat.KindsAll); // same plugin, new name: RynthAi refuses a rename while the lease is live
_combatClaimOwner = owner;
uint before = _combatClaimedKinds;
_combatClaimedKinds = _ai.CombatClaim(kinds, RynthAiCombat.DefaultLeaseMs, 0, 0, owner);
// A kind granted again after a gap (a lapse, a refusal, RynthAi reloaded): its seq may have
// restarted, so the last started seq no longer identifies a request already handled.
foreach (CombatHandler h in _combatHandlers.Values)
if ((before & h.Kind) == 0 && (_combatClaimedKinds & h.Kind) != 0)
h.LastStartedSeq = 0;
if (_combatClaimedKinds == 0)
{
if (!_combatRefusedLogged)
{
_combatRefusedLogged = true;
Log($"[RynthLua] combat hook: RynthAi refused the claim for {RynthAiCombat.KindNames(kinds)} (another owner holds it); retrying every tick.");
}
return;
}
_combatRefusedLogged = false;
foreach (CombatHandler h in _combatHandlers.Values.ToArray())
{
if ((_combatClaimedKinds & h.Kind) == 0 || h.InFlight) continue;
if (!_ai.CombatPoll(h.Kind, out CombatRequestV1 req)) continue;
if (req.Seq == h.LastStartedSeq && req.IssuedAtMs == h.LastStartedIssuedAtMs) continue;
Script? s = h.Ctx.Host.Lua;
if (s == null) continue;
DynValue ctxTable;
try { ctxTable = BuildCombatContext(s, req); }
catch (Exception ex) { h.Ctx.Host.Print($"error: combat {CombatKindName(h.Kind)} context: {ex.Message}"); continue; }
uint seq = req.Seq;
CombatHandler started = h;
h.LastStartedSeq = seq;
h.LastStartedIssuedAtMs = req.IssuedAtMs;
h.Thread = h.Ctx.Host.Start(h.Fn, new[] { ctxTable }, (result, error) => OnCombatHandlerDone(started, seq, result, error));
h.InFlight = h.Thread != null;
h.InFlightSeq = seq;
h.StartedDeadlineMs = req.DeadlineMs;
}
}
private string CombatOwnerName()
{
var names = _combatHandlers.Values.Select(h => h.Ctx.Name).Distinct(StringComparer.OrdinalIgnoreCase).OrderBy(n => n, StringComparer.OrdinalIgnoreCase);
string owner = "RynthLua/" + string.Join("+", names);
return owner.Length > RynthAiCombat.MaxOwnerLength ? owner.Substring(0, RynthAiCombat.MaxOwnerLength) : owner;
}
/// <summary>The handler's thread ended: decide with its answer, or decline on an error.</summary>
private void OnCombatHandlerDone(CombatHandler h, uint seq, DynValue? result, string? error)
{
h.InFlight = false;
h.Thread = null;
// A Lua error the script host has already printed ("error: ..."): not printed twice.
bool printed = error != null && error != CombatStallError;
// An answer after the deadline: RynthAi has already chosen for itself, so the answer is
// wasted. It counts as a stall, the same as no answer within the stall budget.
if (error == null && CombatClock() > h.StartedDeadlineMs)
error = CombatLateError;
string? bad = null;
if (error == null && TryReadCombatAnswer(result, out uint spell, out uint target, out uint flags, out bad))
{
h.Errors = 0;
_ai.CombatDecide(seq, h.Kind, spell, target, flags); // stale (0) when RynthAi moved on: harmless
return;
}
error ??= bad;
// An error (raised, or an answer that isn't spellId, targetId [, "area"]): decline at once
// rather than make RynthAi wait out the deadline.
_ai.CombatDecide(seq, h.Kind, 0, 0, 0);
bool current = _combatHandlers.TryGetValue(h.Kind, out var now) && ReferenceEquals(now, h);
if (!current) return; // replaced or removed meanwhile: its errors don't count
string kindName = CombatKindName(h.Kind);
h.Errors++;
h.Ctx.Host.Print(printed
? $"combat {kindName} handler failed (declined; {h.Errors}/{CombatHandlerMaxErrors} in a row)"
: $"combat {kindName} handler: {error} (declined; {h.Errors}/{CombatHandlerMaxErrors} in a row)");
if (h.Errors >= CombatHandlerMaxErrors)
{
DropCombatHandler(h.Kind, release: true);
string what = error == CombatStallError || error == CombatLateError ? "did not answer within the deadline" : "failed";
string msg = $"{h.Ctx.Name}: the {kindName} handler {what} {CombatHandlerMaxErrors} times in a row and was removed; RynthAi chooses the {kindName} spells again.";
h.Ctx.Host.Print(msg);
ChatLine(msg);
Log("[RynthLua] combat hook: " + msg);
}
}
/// <summary>
/// Reads a handler's return: nil / false / nothing = decline; otherwise spellId (a number),
/// targetId (a number or an object; nil = the request's target) and optional flags: "area"
/// (or true), "nojudge", or a table { area = true, nojudge = true }.
/// </summary>
internal static bool TryReadCombatAnswer(DynValue? result, out uint spell, out uint target, out uint flags, out string? error)
{
spell = target = flags = 0;
error = null;
DynValue[] values = result == null ? Array.Empty<DynValue>()
: result.Type == DataType.Tuple ? result.Tuple ?? Array.Empty<DynValue>()
: new[] { result };
DynValue first = values.Length > 0 ? values[0] : DynValue.Nil;
if (first.IsNil() || first.Type == DataType.Void || (first.Type == DataType.Boolean && !first.Boolean)) return true; // decline
if (first.Type != DataType.Number || first.Number < 0 || first.Number > uint.MaxValue || first.Number != Math.Floor(first.Number))
{
error = $"returned {first.Type.ToString().ToLowerInvariant()} '{first.ToPrintString()}', expected a spell id (or nil to decline)";
return false;
}
spell = (uint)first.Number;
DynValue second = values.Length > 1 ? values[1] : DynValue.Nil;
if (!second.IsNil() && second.Type != DataType.Void)
{
target = LuaArgs.Id(second);
if (target == 0 && !(second.Type == DataType.Number && second.Number == 0))
{
error = $"returned target '{second.ToPrintString()}', expected an object id or object (or nil for the request's target)";
return false;
}
}
DynValue third = values.Length > 2 ? values[2] : DynValue.Nil;
switch (third.Type)
{
case DataType.Nil:
case DataType.Void:
break;
case DataType.Boolean: // true = "area" (the v1 form); false = no flags
if (third.Boolean) flags |= RynthAiCombat.FlagArea;
break;
case DataType.String:
if (!TryCombatFlag(third.String, out uint f))
{
error = $"returned flag '{third.String}', expected \"area\", \"nojudge\" or a table {{ area = true, nojudge = true }}";
return false;
}
flags |= f;
break;
case DataType.Table:
foreach (TablePair p in third.Table.Pairs)
{
if (p.Key.Type != DataType.String || !TryCombatFlag(p.Key.String, out uint tf))
{
error = $"returned flag '{p.Key.ToPrintString()}', expected the keys area and nojudge";
return false;
}
if (p.Value.CastToBool()) flags |= tf;
}
break;
default:
error = $"returned {third.Type.ToString().ToLowerInvariant()} flags, expected \"area\", \"nojudge\" or a table {{ area = true, nojudge = true }}";
return false;
}
return true;
}
private static bool TryCombatFlag(string name, out uint flag)
{
flag = name.Trim().ToLowerInvariant() switch
{
"area" => RynthAiCombat.FlagArea,
"nojudge" => RynthAiCombat.FlagNoJudge,
_ => 0u,
};
return flag != 0;
}
/// <summary>The ctx table a handler gets.</summary>
private DynValue BuildCombatContext(Script s, in CombatRequestV1 r)
{
var t = new Table(s);
t["seq"] = (double)r.Seq;
t["kind"] = CombatKindName(r.Kind);
t["targetId"] = (double)r.TargetId;
t["targetHealth"] = (double)r.TargetHealth;
t["healthPct"] = (double)r.HealthPct;
t["staminaPct"] = (double)r.StaminaPct;
t["manaPct"] = (double)r.ManaPct;
t["healLine"] = (double)r.HealLine;
t["inCombat"] = r.InCombat != 0;
t["combatMode"] = (double)r.CombatMode;
t["issuedAt"] = (double)r.IssuedAtMs;
t["deadline"] = (double)r.DeadlineMs;
var monsters = new Table(s);
foreach (var (id, distance) in _ai.CombatScanned())
{
var m = new Table(s);
m["id"] = (double)id;
m["distance"] = Math.Round(distance, 2);
monsters.Append(DynValue.NewTable(m));
}
t["monsters"] = monsters;
// ctx.last: the most recent RESOLVED cast, its err final (nil only when no answer could be
// read); ctx.pending: the cast still in flight, or nil. From a RynthAi that writes the
// appended fields; an older one: ctx.last is its last decision, no err, no pending.
var last = new Table(s);
uint newEnd = (uint)System.Runtime.InteropServices.Marshal.OffsetOf<CombatRequestV1>(nameof(CombatRequestV1.PendingAtMs)) + sizeof(long);
if (r.StructSize >= newEnd)
{
last["seq"] = (double)r.ResolvedSeq;
last["spell"] = (double)r.ResolvedSpell;
last["target"] = (double)r.ResolvedTarget;
last["at"] = (double)r.ResolvedAtMs;
if (r.ResolvedSpell != 0 && r.ResolvedErr >= 0) last["err"] = (double)r.ResolvedErr;
if (r.PendingSpell != 0)
{
var pending = new Table(s);
pending["seq"] = (double)r.PendingSeq;
pending["spell"] = (double)r.PendingSpell;
pending["target"] = (double)r.PendingTarget;
pending["at"] = (double)r.PendingAtMs;
t["pending"] = pending;
}
}
else
{
last["seq"] = (double)r.LastSeq;
last["spell"] = (double)r.LastSpell;
last["target"] = (double)r.LastTarget;
last["at"] = (double)r.LastAtMs;
}
t["last"] = last;
return DynValue.NewTable(t);
}
}

View file

@ -13,6 +13,7 @@ Scripts that listen for events keep running until you stop them (`/lua stop <nam
- `hunt-settings.lua`: a settings form saved with `storage` (checkbox, slider, 0-based combo, text box) and a button that sets your combat mode; `/hunt` shows or hides it.
- `salvage-list.lua`: a list with buttons: your salvage, gathered in a spawned loop, a filter box, a scrolling region with `PushID` rows, and Use / Give buttons (Give waits for its result in a thread of its own). The buttons really act.
- `item-icons.lua`: an item list with icons: your pack items drawn with their AC icons (`views.Huds.GetObjectIconTexture`, `ImGui.ImageButton`, `ImGui.Image`), an `InputInt` for how many rows and a `DragFloat` for the icon size. Nothing acts on the game. Needs an engine from 2026-09-30 or later.
- `combat-handler.lua`: RynthAi's combat hook (`rynth.ai` SetAttackHandler / SetHealHandler): an attack handler that casts a set spell while the target's health is under a line and otherwise lets RynthAi choose, a heal handler that heals you under a health line, the refusal reasons printed, and `/combathook` to turn them on and off. Set its spell ids first; it needs RynthAi running.
The window examples need RynthCore API v71 with ImGui on; see "Script windows" in the reference.

View file

@ -0,0 +1,56 @@
-- combat-handler.lua: choose RynthAi's attack and heal spells from a script (the combat hook).
--
-- RynthAi still picks the target, the stance and the pacing. When it is about to cast it asks
-- the handler, waits until ctx.deadline at most, and casts the answer. A handler returns
-- spellId [, targetId [, flags]] targetId nil = ctx.targetId (attack) / yourself (heal)
-- nil let RynthAi choose this time
-- flags: "area" (a ring/wall cast) or "nojudge" (not meant to damage; no miss counting).
-- /combathook turns the handlers on and off. Set the spell ids below to spells you know.
local ai = require("rynth.ai")
local FINISHER_SPELL = 0 -- attack spell id, cast while the target is under FINISH_BELOW
local FINISH_BELOW = 0.30 -- the target's health ratio, 0..1
local HEAL_SPELL = 0 -- heal spell id, cast on yourself under HEAL_BELOW
local HEAL_BELOW = 50 -- your health percent
local function onAttack(ctx)
-- ctx.targetHealth is -1 while RynthAi has no health for the target.
if FINISHER_SPELL ~= 0 and ctx.targetHealth >= 0 and ctx.targetHealth < FINISH_BELOW then
return FINISHER_SPELL
end
return nil -- RynthAi casts its own choice
end
local function onHeal(ctx)
if HEAL_SPELL ~= 0 and ctx.healthPct >= 0 and ctx.healthPct < HEAL_BELOW then
return HEAL_SPELL, 0 -- target 0 = yourself
end
return nil -- kits, Heal Self and potions as usual
end
local enabled = false
local function enable()
local okAttack, whyAttack = ai.SetAttackHandler(onAttack)
if not okAttack then print("attack handler refused: " .. tostring(whyAttack)) end
local okHeal, whyHeal = ai.SetHealHandler(onHeal)
if not okHeal then print("heal handler refused: " .. tostring(whyHeal)) end
enabled = okAttack or okHeal
print("combat handlers " .. (enabled and "on" or "off"))
end
local function disable()
ai.ClearCombatHandlers()
enabled = false
print("combat handlers off: RynthAi chooses every spell")
end
game.RegisterCommand("/combathook", function()
if enabled then disable() else enable() end
end)
-- Stopping the script releases the handlers anyway; clearing them here says so explicitly.
game.OnScriptEnd.Add(function() ai.ClearCombatHandlers() end)
enable()

View file

@ -19,6 +19,11 @@ namespace RynthCore.Plugin.RynthLua;
/// ai.DistanceTo(objectOrId) metres, -1 when unknown
/// ai.IsPathClear(objectOrIdOrName) line of sight
/// ai.Command(text) (SubmitCommand) a chat line as if typed (/ra, /vt, ...; AC's parser without RynthAi)
/// ai.SetAttackHandler(fn) this script chooses RynthAi's attack spells (CombatHookPump.cs);
/// ai.SetHealHandler(fn) ... and its heal spells, asked before kits. true, or false and why.
/// fn(ctx) returns spellId, targetId [, "area"], or nil to let RynthAi choose
/// ai.ClearCombatHandlers() drops this script's handlers (stopping the script does too)
/// ai.CombatHook { Supported, AttackOwner, HealOwner, Claimed }
///
/// Everything except Available and Command raises "RynthAi isn't loaded ..." when RynthAi
/// isn't there, so a script can check <c>ai.Available</c> first or pcall.
@ -144,6 +149,23 @@ public sealed partial class RynthLuaPlugin
m.Set("Command", command);
m.Set("SubmitCommand", command);
// The combat hook (RynthAi.Combat): handlers run as script threads started by the pump.
DynValue SetHandler(CallbackArguments a, uint kind, string what)
{
DynValue fn = LuaArgs.At(LuaArgs.Of(a, m), 0);
if (!fn.IsNil() && fn.Type != DataType.Function)
throw new ScriptRuntimeException($"rynth.ai.{what}(fn) needs a function (or nil to clear it)");
string? refused = SetCombatHandler(ctx, kind, fn);
return refused == null ? DynValue.True : DynValue.NewTuple(DynValue.False, DynValue.NewString(refused));
}
m.Set("SetAttackHandler", DynValue.NewCallback((c, a) => SetHandler(a, RynthCore.Plugin.Shared.RynthAiCombat.KindAttack, "SetAttackHandler")));
m.Set("SetHealHandler", DynValue.NewCallback((c, a) => SetHandler(a, RynthCore.Plugin.Shared.RynthAiCombat.KindHeal, "SetHealHandler")));
m.Set("ClearCombatHandlers", DynValue.NewCallback((c, a) =>
{
ClearCombatHandlers(ctx);
return DynValue.Nil;
}));
// Live fields: Available / IsLoaded, MacroRunning (read and write).
var mt = new Table(s);
mt.Set("__index", DynValue.NewCallback((c, a) =>
@ -156,6 +178,15 @@ public sealed partial class RynthLuaPlugin
return DynValue.NewBoolean(_ai.Available);
case "MacroRunning":
return DynValue.NewBoolean(_ai.MacroRunning);
case "CombatHook":
{
var h = new Table(s);
h["Supported"] = _ai.CombatAvailable;
h["AttackOwner"] = CombatOwner(RynthCore.Plugin.Shared.RynthAiCombat.KindAttack) is string ao ? DynValue.NewString(ao) : DynValue.Nil;
h["HealOwner"] = CombatOwner(RynthCore.Plugin.Shared.RynthAiCombat.KindHeal) is string ho ? DynValue.NewString(ho) : DynValue.Nil;
h["Claimed"] = CombatClaimed;
return DynValue.NewTable(h);
}
default:
return DynValue.Nil;
}
@ -172,6 +203,7 @@ public sealed partial class RynthLuaPlugin
return DynValue.Nil;
case "Available":
case "IsLoaded":
case "CombatHook":
throw new ScriptRuntimeException($"rynth.ai.{key} is read-only");
default:
// Script's own fields on the module are fine.

View file

@ -34,6 +34,8 @@ internal sealed class LuaScriptHost
public Func<bool>? WaitFor; // await: resume only once this is true
public DynValue[] Args = Array.Empty<DynValue>();
public bool Started;
/// <summary>Called once when the thread ends: its return values, or the error message.</summary>
public Action<DynValue?, string?>? OnDone;
}
private readonly Action<string> _log;
@ -206,12 +208,42 @@ internal sealed class LuaScriptHost
}
/// <summary>Starts <paramref name="fn"/> as a new script thread.</summary>
public void Start(DynValue fn, DynValue[] args)
public void Start(DynValue fn, DynValue[] args) => Start(fn, args, onDone: null);
/// <summary>
/// Starts <paramref name="fn"/> as a new script thread and calls <paramref name="onDone"/> once
/// it ends: with its return values (a tuple for several, Nil for none) and a null error, or with
/// a null result and the error message when it raised one. Not called when the script stops
/// first (its stop handlers clean up), nor after <see cref="Abort"/>. Returns the thread's
/// handle (for Abort), or null when nothing was started.
/// </summary>
public object? Start(DynValue fn, DynValue[] args, Action<DynValue?, string?>? onDone)
{
if (_script == null || fn.Type != DataType.Function) return;
if (_script == null || fn.Type != DataType.Function) return null;
DynValue co = _script.CreateCoroutine(fn);
co.Coroutine.AutoYieldCounter = AutoYieldCounter;
_threads.Add(new LuaThread { Co = co, Args = args });
var t = new LuaThread { Co = co, Args = args, OnDone = onDone };
_threads.Add(t);
return t;
}
/// <summary>
/// Ends the thread <paramref name="handle"/> (from <see cref="Start(DynValue, DynValue[], Action{DynValue?, string?}?)"/>)
/// without resuming it again; its onDone is not called. Returns false when it had already ended.
/// </summary>
public bool Abort(object? handle)
{
if (handle is not LuaThread t) return false;
t.OnDone = null;
if (ReferenceEquals(_botTickThread, t)) _botTickThread = null;
return _threads.Remove(t);
}
private static void Done(LuaThread t, DynValue? result, string? error)
{
Action<DynValue?, string?>? cb = t.OnDone;
t.OnDone = null;
try { cb?.Invoke(result, error); } catch { }
}
/// <summary>Calls every v1 handler registered for <paramref name="evt"/>, each on its own thread.</summary>
@ -276,11 +308,12 @@ internal sealed class LuaScriptHost
}
_current = t;
DynValue r = DynValue.Nil;
try
{
while (_script != null)
{
DynValue r = t.Started ? t.Co.Coroutine.Resume() : t.Co.Coroutine.Resume(t.Args);
r = t.Started ? t.Co.Coroutine.Resume() : t.Co.Coroutine.Resume(t.Args);
t.Started = true;
if (t.Co.Coroutine.State == CoroutineState.Dead) break;
// Forced (auto) yield: keep going while this tick has budget.
@ -292,18 +325,24 @@ internal sealed class LuaScriptHost
{
Print("error: " + (ex.DecoratedMessage ?? ex.Message));
_threads.Remove(t);
Done(t, null, ex.DecoratedMessage ?? ex.Message);
continue;
}
catch (Exception ex)
{
Print("error: " + ex.Message);
_threads.Remove(t);
Done(t, null, ex.Message);
continue;
}
finally { _current = null; }
if (_script == null) return;
if (t.Co.Coroutine.State == CoroutineState.Dead) _threads.Remove(t);
if (t.Co.Coroutine.State == CoroutineState.Dead)
{
_threads.Remove(t);
Done(t, r, null);
}
if (OverBudget()) break;
}
}

View file

@ -16,13 +16,25 @@ public static unsafe class PluginExports
private static int Init(RynthCoreApiNative* api) => Runtime.Init(api);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Shutdown() => Runtime.Shutdown();
public static void Shutdown()
{
try { Runtime.Shutdown(); } // an exception out of a native export fail-fasts the client
catch { }
}
[UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetName() => RynthLuaPlugin.NamePointer;
public static IntPtr GetName()
{
try { return RynthLuaPlugin.NamePointer; } // a static initializer that throws surfaces here (TypeInitializationException)
catch { return IntPtr.Zero; }
}
[UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetVersion() => RynthLuaPlugin.VersionPointer;
public static IntPtr GetVersion()
{
try { return RynthLuaPlugin.VersionPointer; }
catch { return IntPtr.Zero; }
}
[UnmanagedCallersOnly(EntryPoint = "RynthPluginTick", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Tick() => Runtime.OnTick();

View file

@ -42,11 +42,88 @@ internal sealed unsafe class RynthAiBridge
}
}
/// <summary>Forget the table (logout, RynthAi reload); the next call looks it up again.</summary>
/// <summary>Forget the tables (logout, RynthAi reload); the next call looks them up again.</summary>
public void Reset()
{
_t = null;
_checked = false;
_c = null;
_cChecked = false;
}
// -- RynthAi.Combat (Shared/RynthAiCombatApi.cs): the script-provided combat hook --
private RynthAiCombatApiV1* _c;
private bool _cChecked;
private long _cCheckedAt;
private RynthAiCombatApiV1* Combat
{
get
{
long now = Environment.TickCount64;
if (_cChecked && now - _cCheckedAt < RecheckMs) return _c;
_cChecked = true;
_cCheckedAt = now;
IntPtr p = _host.GetPluginInterface("RynthAi", RynthAiCombatApiV1.InterfaceName, RynthAiCombatApiV1.InterfaceVersion);
var t = (RynthAiCombatApiV1*)p;
_c = t != null && t->Version >= 1 && t->StructSize >= (uint)sizeof(RynthAiCombatApiV1) ? t : null;
return _c;
}
}
/// <summary>True when RynthAi serves the combat hook right now.</summary>
public bool CombatAvailable => Combat != null;
/// <summary>Takes or renews the hook; the kinds granted (0 = refused or no RynthAi).</summary>
public uint CombatClaim(uint kinds, uint leaseMs, uint attackTimeoutMs, uint healTimeoutMs, string owner)
{
var t = Combat;
if (t == null) return 0;
using var o = new Utf8(owner);
return unchecked((uint)t->Claim(kinds, leaseMs, attackTimeoutMs, healTimeoutMs, o.P));
}
public void CombatRelease(uint kinds)
{
var t = Combat;
if (t != null) t->Release(kinds);
}
/// <summary>True when a request of <paramref name="kind"/> is open and unanswered.</summary>
public bool CombatPoll(uint kind, out CombatRequestV1 request)
{
request = default;
var t = Combat;
if (t == null) return false;
CombatRequestV1 r = default;
r.StructSize = (uint)sizeof(CombatRequestV1);
if (t->Poll(kind, &r) == 0) return false;
request = r;
return true;
}
/// <summary>The answer to request <paramref name="seq"/>; false = stale (or no RynthAi).</summary>
public bool CombatDecide(uint seq, uint kind, uint spellId, uint targetId, uint flags)
{
var t = Combat;
return t != null && t->Decide(seq, kind, spellId, targetId, flags) != 0;
}
/// <summary>RynthAi's scanned targets (id, metres), nearest first.</summary>
public (uint Id, float Distance)[] CombatScanned()
{
var t = Combat;
if (t == null) return Array.Empty<(uint, float)>();
const int Cap = 64;
uint* ids = stackalloc uint[Cap];
float* dist = stackalloc float[Cap];
int n = t->GetScanned(ids, dist, Cap);
if (n <= 0) return Array.Empty<(uint, float)>();
n = Math.Min(n, Cap);
var list = new (uint, float)[n];
for (int i = 0; i < n; i++) list[i] = (ids[i], dist[i]);
return list;
}
private static string Copy(byte* s) => s == null ? string.Empty : Marshal.PtrToStringUTF8((IntPtr)s) ?? string.Empty;

View file

@ -40,6 +40,8 @@
<ItemGroup>
<!-- RynthAi's script interface (RynthAi.Script v1), shared source with RynthAi. -->
<Compile Include="..\Shared\RynthAiScriptApi.cs" Link="Shared\RynthAiScriptApi.cs" />
<!-- RynthAi's combat hook (RynthAi.Combat v1): scripts choose attack and heal spells. -->
<Compile Include="..\Shared\RynthAiCombatApi.cs" Link="Shared\RynthAiCombatApi.cs" />
<!-- One logged, guarded way to use an object (who used what, and why). -->
<Compile Include="..\Shared\UseAudit.cs" Link="Shared\UseAudit.cs" />
</ItemGroup>

View file

@ -101,10 +101,16 @@ public sealed partial class RynthLuaPlugin : RynthPluginBase
public override void Shutdown()
{
// Forget RynthAi's cached tables first: stopping the scripts releases their combat
// handlers (ClearCombatHandlers -> CombatRelease), and RynthAi may have been unloaded or
// reloaded since the last tick looked them up, so a cached pointer could be stale.
// (Null when Initialize never ran: nothing is cached and nothing must throw here.)
try { _ai?.Reset(); } catch { }
// The resume list is taken while the scripts still run; the file is written last.
List<string> resume = new();
try { resume = CaptureResume(); } catch { }
try { StopAll("stopped: RynthLua unloaded"); } catch (Exception ex) { Log("[RynthLua] shutdown: " + ex.Message); }
try { ReleaseCombatHook(); } catch { } // RynthAi goes native now, not when the lease lapses
try { ShutdownHuds(); } catch { }
FlushHudMemory();
SaveEditor();
@ -134,6 +140,10 @@ public sealed partial class RynthLuaPlugin : RynthPluginBase
try { PollHudEvents(); } // script windows: input first, so this tick's passes see it
catch (Exception ex) { LogHudFault("events", ex); }
TickApi();
// RynthAi's combat hook: renew the lease, start handlers for new requests (they run in
// TickScripts just below, so a handler that doesn't yield answers in this same tick).
try { PumpCombatHook(); }
catch (Exception ex) { Log("[RynthLua] combat hook: " + ex.Message); }
TickScripts();
try { TickHuds(); } // render passes that are due, then submit what changed
catch (Exception ex) { LogHudFault("passes", ex); }

View file

@ -255,11 +255,30 @@ public sealed partial class RynthLuaPlugin
// ── /lua commands ───────────────────────────────────────────────────────
/// <summary>
/// Every built-in /lua verb. The one list behind both the dispatch gate in HandleLuaChatCommand
/// (a verb never falls back to a script command) and the usage summary (a script command with
/// one of these names is unreachable through /lua). A new verb goes in the switch AND here.
/// </summary>
private static readonly HashSet<string> BuiltInLuaVerbs = new(StringComparer.OrdinalIgnoreCase)
{
"run", "start", "restart", "stop", "exec", "execin", "autostart", "list", "hud",
};
private void HandleLuaChatCommand(string line)
{
string[] parts = line.Split(' ', 3, StringSplitOptions.RemoveEmptyEntries);
string sub = parts.Length > 1 ? parts[1].ToLowerInvariant() : "";
if (sub.StartsWith('/')) sub = sub[1..]; // "/lua /demo": the usage lists names with a slash, one is accepted
string rest = parts.Length > 2 ? parts[2].Trim() : "";
// Not a built-in verb (those always win): in a Decal (bridge-mode) client the engine only
// forwards /lua, so "/lua demo status" (or "/lua /demo status", as the usage text lists them) is
// the way to reach a script's game.RegisterCommand("/demo"). Same queue as a typed "/demo status":
// the handler runs once on the tick thread with args "status".
if (!BuiltInLuaVerbs.Contains(sub))
{
if (sub.Length > 0 && TryQueueScriptCommand("/" + sub + (rest.Length > 0 ? " " + rest : ""))) return;
}
switch (sub)
{
case "run":
@ -322,7 +341,21 @@ public sealed partial class RynthLuaPlugin
break;
default:
ChatLine("/lua list | start <script> | stop <script>|all | restart <script> | exec <code> | execin <script> <code> | autostart <script> none|global|character | hud list|show|hide|toggle <script>/<hud>|bench <n>|bench off");
ChatLine("/lua <command> [args] runs a script command (game.RegisterCommand) - " + ScriptCommandsSummary());
break;
}
}
/// <summary>The registered script commands for the /lua usage text.</summary>
private string ScriptCommandsSummary()
{
// Names as /lua takes them (no slash); a name equal to a built-in verb can't be reached here.
var names = _commandOwners.Keys
.Select(k => k.TrimStart('/'))
.Where(n => n.Length > 0 && !BuiltInLuaVerbs.Contains(n))
.Distinct(StringComparer.OrdinalIgnoreCase)
.OrderBy(n => n, StringComparer.OrdinalIgnoreCase)
.ToList();
return names.Count == 0 ? "none registered now." : "registered: " + string.Join(", ", names) + ".";
}
}

View file

@ -442,6 +442,10 @@ function Capabilities.Get() end
---A chat command owned by this script. A typed line starting with it is eaten and
---`fn(args)` runs on the next tick with the rest of the line.
---In a Decal (bridge-mode) client the engine only passes a few commands to plugins
---(/rc /ra /rv /rn /rnav /lua), so a bare "/name" never reaches this script there:
---players type `/lua name ...` instead (same handler, same args). Built-in /lua verbs
---(list, start, stop, ...) win over a script command of the same name.
---@param command string "/name" (the slash is added when missing)
---@param fn fun(args: string)
function Game.RegisterCommand(command, fn) end
@ -1410,6 +1414,7 @@ function FileSystemModule.GetCustom() end
---@field Available boolean RynthAi is loaded.
---@field IsLoaded boolean Same as Available.
---@field MacroRunning boolean Read, or assign true/false to start/stop the macro.
---@field CombatHook RynthLua.CombatHookInfo The combat hook's state (read-only; a fresh table each read).
local RynthAiModule = {}
---A meta expression; numbers come back as numbers.
---@param expression string
@ -1453,6 +1458,102 @@ function RynthAiModule.Command(text) end
---Same as Command.
---@param text string
function RynthAiModule.SubmitCommand(text) end
---This script chooses RynthAi's attack spells. RynthAi still picks the target, keeps the stance,
---the pacing and its debuffs, and casts what the handler answers. The handler runs as a script
---thread when RynthAi is about to cast (after its debuffs) and may yield, but RynthAi waits only
---until `ctx.deadline` (1 s by default) and then casts its own choice. It must not cast itself.
---Return `spellId, targetId [, flags]`, or nil to let RynthAi choose this time. targetId nil =
---ctx.targetId; it may also be another of `ctx.monsters` or the player. flags is "area" (or true),
---"nojudge", or a table `{ area = true, nojudge = true }`; anything else is an error. "area" marks
---a ring/wall/chain cast: no miss counting on the fight target, filed with the rings. "nojudge"
---marks a cast not meant to damage (a debuff, a drain): no miss counting (so no blacklist) and
---nothing on the Damage tab (no tier, element or fight cast count), but it still counts in the
---session attack-cast and casts-per-kill counters like any cast. A damaging cast at the fight
---target is tagged like RynthAi's own (wielded wand, element and level from the spell), and a
---single-target one takes part in RynthAi's kill-shot swap: a predicted kill moves RynthAi to
---another target while the projectile flies, and the next request names the new target. An
---unknown spell, a target that isn't the fight target, a scanned monster or the player, or a spell
---the server refused outright right after the script cast it (no components) is rejected and
---RynthAi casts its own; a rejected request is not a cast and appears in neither ctx.last nor ctx.pending. A refused spell stays parked
---for 600 s (as RynthAi parks a vital level); restocking components does not unpark it sooner.
---One script per kind: the first to register owns it; the same script registering again replaces
---its handler; nil clears it. An error declines that request; a handler still running 1 s past
---ctx.deadline is stopped and counts as an error; 3 errors in a row remove the handler.
---Stopping the script releases it. Keeps the script running while set. The deadlines (1 s attack,
---750 ms heal) and the lease are fixed: the RynthAi.Combat Claim's timeout parameters are reserved.
---While a script holds the attack kind, RynthAi treats the character as able to attack with magic
---even with War and Void untrained: a listed caster counts as the combat weapon when no usable
---listed melee/missile weapon exists.
---@param handler fun(ctx: RynthLua.CombatContext): (integer?, (integer|RynthLua.ObjectRef)?, ("area"|"nojudge"|boolean|{area: boolean?, nojudge: boolean?})?)|nil
---@return boolean ok
---@return string? why "RynthAi has no combat hook", or "the attack handler is already set by <script>".
function RynthAiModule.SetAttackHandler(handler) end
---This script chooses the vitals heal: asked when health is under Heal At (in combat) or Top Off HP
---(idle), before kits, Heal Self and potions (the emergency kit / Stamina to Health step stays
---RynthAi's). Same contract as SetAttackHandler; ctx.healLine is the line, and ctx.targetId /
---ctx.targetHealth are informational: RynthAi's current fight target (0 when none) and its health.
---Return a heal and target 0/nil for YOURSELF (never the fight target), or e.g. a drain spell and
---a monster from `ctx.monsters` or ctx.targetId. A level the server had no components for is
---rejected for 600 s (RynthAi's own heal skips it as long; restocking does not unpark it sooner).
---The deadline is 750 ms; nil or no
---answer = kit, Heal Self, potion.
---@param handler fun(ctx: RynthLua.CombatContext): (integer?, (integer|RynthLua.ObjectRef)?, ("area"|"nojudge"|boolean|{area: boolean?, nojudge: boolean?})?)|nil
---@return boolean ok
---@return string? why
function RynthAiModule.SetHealHandler(handler) end
---Drops this script's attack and heal handlers (RynthAi chooses again at once).
function RynthAiModule.ClearCombatHandlers() end
---What a combat handler gets (one table per request).
---@class RynthLua.CombatContext
---@field seq integer The request's id.
---@field kind "attack"|"heal"
---@field targetId integer Attack: RynthAi's locked target. Heal: RynthAi's current fight target (informational; 0 when none).
---@field targetHealth number That target's health 0..1; -1 unknown or no target.
---@field healthPct integer Your health %, -1 unknown.
---@field staminaPct integer Your stamina %, -1 unknown.
---@field manaPct integer Your mana %, -1 unknown.
---@field healLine integer Heal: the health line you are under (Heal At / Top Off HP). Attack: 0.
---@field inCombat boolean A monster is engaged or within Monster Range.
---@field combatMode integer 1 NonCombat, 2 Melee, 4 Missile, 8 Magic.
---@field issuedAt number clock() when RynthAi asked.
---@field deadline number clock() after which RynthAi casts its own choice.
---@field monsters RynthLua.CombatMonster[] RynthAi's targets in range (attackable, in sight), nearest first.
---@field last RynthLua.CombatLast The most recent RESOLVED cast of this kind (its answer is in).
---@field pending RynthLua.CombatPending? The cast of this kind still in flight (sent, no answer yet); nil = none.
---@class RynthLua.CombatMonster
---@field id integer
---@field distance number Metres.
---A cast of this kind is in flight from its send until its answer: the UseDones answer the casts in flight of both kinds in send order (an attack sent first takes the first one, a heal sent after it the next),
---then resolved. ctx.last never changes after the fact: a cast moves from ctx.pending to ctx.last once,
---with its final err. Declines and rejects are not casts and appear in neither.
---With an older RynthAi (one that does not write these fields): ctx.last is the last decision RynthAi used (spell 0 =
---declined or rejected), with no err, and ctx.pending is always nil.
---@class RynthLua.CombatLast
---@field seq integer The request seq of that cast; 0 before the first resolved cast.
---@field spell integer The spell cast; 0 before the first resolved cast.
---@field target integer
---@field at number clock() when it was sent.
---@field err integer? Its answer, final: the UseDone error. 0 = done (it went off), 29 (0x1D) =
--- refused 'too busy' (it never went off: not a miss), 1025 (0x401) = not enough
--- mana, 1026 (0x402) = fizzled. nil only when no answer could be read: no UseDone
--- within 7 s of the send, or another answer came first; also nil before the
--- first resolved cast.
---@class RynthLua.CombatPending
---@field seq integer The request seq of the cast in flight.
---@field spell integer
---@field target integer
---@field at number clock() when it was sent.
---ai.CombatHook
---@class RynthLua.CombatHookInfo
---@field Supported boolean RynthAi serves the combat hook now.
---@field AttackOwner string? The script holding the attack kind.
---@field HealOwner string? The script holding the heal kind.
---@field Claimed boolean RynthAi granted RynthLua's last claim (false while another owner holds it).
---require("rynthlua")
---@class RynthLua.InfoModule