RynthSuite as of 2026-10-05 evening (internal a078b8e): release 2026.10.5.20 - healing delay fixes, stuck-cast safeguards, buffs over items, slayers recognised and chosen first, recover my corpse, /ub give and /mt give, Mana Tap skips wands, dungeon floor-plan bake, heal latency log
This commit is contained in:
parent
53438c65c1
commit
6847868401
60 changed files with 6361 additions and 769 deletions
|
|
@ -11,4 +11,14 @@
|
|||
<ItemGroup>
|
||||
<IlcArg Include="--runtimeopt:GCSegmentSize=800000" />
|
||||
</ItemGroup>
|
||||
|
||||
<!--
|
||||
Plugin manifest fields shared by every RynthSuite plugin (Directory.Build.targets embeds the
|
||||
manifest; each csproj sets its own RynthPluginMinEngineApi and description).
|
||||
-->
|
||||
<PropertyGroup>
|
||||
<RynthPluginAuthor>RynthSuite</RynthPluginAuthor>
|
||||
<RynthPluginHomepage>https://aelrynth.com/rynth.html</RynthPluginHomepage>
|
||||
<RynthPluginLicense>MIT</RynthPluginLicense>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
|
|
|
|||
12
Plugins/Directory.Build.targets
Normal file
12
Plugins/Directory.Build.targets
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
<Project>
|
||||
<!--
|
||||
Plugin manifests (RynthCore SDK): each plugin's csproj sets RynthPluginMinEngineApi (and any
|
||||
RynthPluginDependency items); the SDK's targets write the manifest JSON from the csproj, compile
|
||||
in RynthPluginInfo, and embed the JSON in the DLL. The plugins reference the SDK by
|
||||
ProjectReference, so its build\ targets are imported here rather than by NuGet.
|
||||
-->
|
||||
<PropertyGroup>
|
||||
<_RynthCoreSdkTargets>$(MSBuildThisFileDirectory)..\..\RynthCore\src\RynthCore.PluginSdk\build\RynthCore.PluginSdk.targets</_RynthCoreSdkTargets>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(_RynthCoreSdkTargets)" Condition="Exists('$(_RynthCoreSdkTargets)')" />
|
||||
</Project>
|
||||
|
|
@ -149,6 +149,22 @@ internal sealed class ActivityArbiter
|
|||
_ => "Default",
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// What a display shows for the bot's activity (the RynthAi dashboard and the phone, through
|
||||
/// the snapshot's "botAction"; RynthNet's status "action"). The same as the BotAction control
|
||||
/// string except for "Buffing", which is one slot for every vitals and buff job: there it is
|
||||
/// <paramref name="buffingLabel"/> (Healing, Restoring mana, Restoring stamina or Buffing).
|
||||
/// Healing showed as "Buffing" on both (2026-10-05). The control string itself never changes:
|
||||
/// CombatManager's canRun and CorpseOpenController compare against "Buffing".
|
||||
/// </summary>
|
||||
public static string DisplayLabel(string? botAction, string? buffingLabel)
|
||||
{
|
||||
string action = string.IsNullOrEmpty(botAction) ? "Default" : botAction;
|
||||
if (string.Equals(action, "Buffing", OIC) && !string.IsNullOrEmpty(buffingLabel))
|
||||
return buffingLabel;
|
||||
return action;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// STEP 1 shadow mode. Compute the would-be decision and log it whenever
|
||||
/// it (or the legacy BotAction it's being compared against) changes.
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
255
Plugins/RynthCore.Plugin.RynthAi/Combat/CastTracker.cs
Normal file
255
Plugins/RynthCore.Plugin.RynthAi/Combat/CastTracker.cs
Normal file
|
|
@ -0,0 +1,255 @@
|
|||
using System;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
/// <summary>
|
||||
/// Bookkeeping for the casts BuffManager sends (buffs and vitals): when each one went out,
|
||||
/// when its incantation ("You say, ...") arrived, and whether the server has finished it.
|
||||
///
|
||||
/// Why (Drakkon on DreamWeave, 2026-10-05, ops\overnight\2026-10-05-stuck-cast.md):
|
||||
/// * The give-up timers ran from the SEND. A healthy DreamWeave vital takes 2.2-2.5 s from
|
||||
/// its incantation to its result, and the incantation lags the send by up to 1.2 s, so a
|
||||
/// cast the server was still finishing was given up at 2.5 s and the next one drew
|
||||
/// "You're too busy!". Now the give-up runs from the incantation when one arrives
|
||||
/// (<see cref="GiveUpAt"/>), capped, and from the send when none does.
|
||||
/// * "Has the server finished?" cleared on ANY UseDone, including the 0x1D refusal of the
|
||||
/// next cast. Now only a completion that belongs to the outstanding cast counts: its own
|
||||
/// result line, or a UseDone with no error after its incantation (<see cref="AwaitingServer"/>).
|
||||
/// A refusal is a refusal, not "done".
|
||||
/// * A cast the server held open (incantation, no result) was only released when someone
|
||||
/// moved the character. <see cref="Refusal"/> says when to send one movement nudge.
|
||||
/// * Each cast's time from incantation to result is logged ([CastTime]), so a slow or held
|
||||
/// cast shows in the log.
|
||||
///
|
||||
/// Pure bookkeeping: it never calls the game. The clock is injectable for the tests.
|
||||
/// </summary>
|
||||
internal sealed class CastTracker
|
||||
{
|
||||
internal sealed class Cast
|
||||
{
|
||||
public int SpellId;
|
||||
public string Name = "";
|
||||
public DateTime SentAt;
|
||||
public DateTime IncantAt = DateTime.MinValue;
|
||||
public int SeqAtSend;
|
||||
public int SeqAtIncant;
|
||||
public int SeqAtRefusal;
|
||||
public bool Refused; // AC answered this cast with "You're too busy!"
|
||||
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;
|
||||
public bool HasIncantation => IncantAt != DateTime.MinValue;
|
||||
}
|
||||
|
||||
/// <summary>Incantation to result, at most. Healthy DreamWeave vitals: 2.21-2.52 s.</summary>
|
||||
public const double IncantToResultMs = 3000;
|
||||
/// <summary>Never wait longer than this after the send, whatever the incantation said.</summary>
|
||||
public const double GiveUpCapMs = 6000;
|
||||
/// <summary>An incantation with no result for this long is a held cast.</summary>
|
||||
public const double HeldAfterIncantMs = 6000;
|
||||
/// <summary>
|
||||
/// The same, when the held cast is a heal or health is under a heal line (2026-10-05: Drakkon
|
||||
/// died 4 s after a Heal Self the server held open). Past the healthy 2.2-2.5 s from
|
||||
/// incantation to result, so a cast still finishing normally is not nudged.
|
||||
/// </summary>
|
||||
public const double UrgentHeldAfterIncantMs = 2800;
|
||||
/// <summary>An incantation this long after the send isn't credited to it.</summary>
|
||||
private const double IncantWindowMs = 15000;
|
||||
|
||||
private readonly Action<string> _log;
|
||||
|
||||
public CastTracker(Action<string> log) => _log = log;
|
||||
|
||||
public Func<DateTime> Clock = () => DateTime.Now;
|
||||
public DateTime Now => Clock();
|
||||
|
||||
/// <summary>The last cast sent.</summary>
|
||||
public Cast? Current { get; private set; }
|
||||
|
||||
/// <summary>The cast whose incantation arrived and whose result hasn't (may be older than Current).</summary>
|
||||
public Cast? Open { get; private set; }
|
||||
|
||||
/// <summary>When to stop waiting for <paramref name="c"/>: <paramref name="fallbackMs"/> after
|
||||
/// the send, or later when its incantation came late (incantation + IncantToResultMs), but
|
||||
/// never past max(fallbackMs, GiveUpCapMs) after the send.</summary>
|
||||
public static DateTime GiveUpAt(Cast c, double fallbackMs)
|
||||
{
|
||||
DateTime basis = c.SentAt.AddMilliseconds(fallbackMs);
|
||||
if (!c.HasIncantation) return basis;
|
||||
DateTime byIncant = c.IncantAt.AddMilliseconds(IncantToResultMs);
|
||||
DateTime cap = c.SentAt.AddMilliseconds(Math.Max(fallbackMs, GiveUpCapMs));
|
||||
DateTime d = byIncant > basis ? byIncant : basis;
|
||||
return d < cap ? d : cap;
|
||||
}
|
||||
|
||||
/// <summary>True when the pending cast <paramref name="spellId"/> is past its give-up time.
|
||||
/// Null when the tracker doesn't hold that cast (the caller uses its old timer).</summary>
|
||||
public bool? GiveUpReached(int spellId, double fallbackMs)
|
||||
{
|
||||
Cast? c = Current;
|
||||
if (c == null || c.SpellId != spellId) return null;
|
||||
return Now >= GiveUpAt(c, fallbackMs);
|
||||
}
|
||||
|
||||
public void Sent(int spellId, string name, int useDoneSeq)
|
||||
{
|
||||
DateTime now = Now;
|
||||
// An earlier cast that is still held open stays Open; one with no incantation is simply replaced.
|
||||
Current = new Cast { SpellId = spellId, Name = name, SentAt = now, SeqAtSend = useDoneSeq };
|
||||
}
|
||||
|
||||
/// <summary>"You say, ..." arrived. Credited to the last cast sent when it has none yet.
|
||||
/// A new incantation also means the server let go of any older open cast.</summary>
|
||||
public Cast? Incantation(int useDoneSeq)
|
||||
{
|
||||
DateTime now = Now;
|
||||
Cast? c = Current;
|
||||
if (c == null || c.HasIncantation || c.Refused || c.Done || (now - c.SentAt).TotalMilliseconds > IncantWindowMs)
|
||||
return null;
|
||||
|
||||
if (Open != null && Open != c && !Open.Done)
|
||||
{
|
||||
_log($"[CastTime] '{Open.Name}': no result {Secs(now - Open.IncantAt)} after its incantation; the server started the next cast ('{c.Name}'), so it is over.");
|
||||
Open.Done = true;
|
||||
}
|
||||
c.IncantAt = now;
|
||||
c.SeqAtIncant = useDoneSeq;
|
||||
Open = c;
|
||||
_log($"[CastTime] '{c.Name}': incantation {Ms(now - c.SentAt)} after the send.");
|
||||
return c;
|
||||
}
|
||||
|
||||
/// <summary>A result line ("You cast X ...", a fizzle, a hard refusal). <paramref name="castText"/>
|
||||
/// is what followed "You cast " (null for lines that don't name the spell). <paramref name="atStart"/>:
|
||||
/// an unnamed refusal the server gives before the cast starts (no components, not enough mana),
|
||||
/// which belongs to the last cast sent. Returns the cast it belongs to, or null.</summary>
|
||||
public Cast? Result(string? castText, string kind, bool atStart = false)
|
||||
{
|
||||
Cast? c = null;
|
||||
bool currentLive = Current != null && !Current.Done && !Current.Refused;
|
||||
bool openLive = Open != null && !Open.Done;
|
||||
if (!string.IsNullOrEmpty(castText))
|
||||
{
|
||||
if (Current != null && !Current.Done && Matches(castText, Current.Name)) c = Current;
|
||||
else if (openLive && Matches(castText, Open!.Name)) c = Open;
|
||||
}
|
||||
else if (atStart)
|
||||
c = currentLive && !Current!.HasIncantation ? Current : (openLive ? Open : null);
|
||||
else
|
||||
// Unnamed, after the windup (a fizzle): the cast the server is running, else the last one sent.
|
||||
c = openLive ? Open : (currentLive ? Current : null);
|
||||
if (c == null) return null;
|
||||
Close(c, kind);
|
||||
return c;
|
||||
}
|
||||
|
||||
private static bool Matches(string castText, string name) =>
|
||||
name.Length > 0 && castText.StartsWith(name, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>The cast's own enchantment landed (self-buff confirmed by event or registry).</summary>
|
||||
public void Confirmed(int spellId, string kind)
|
||||
{
|
||||
if (Current != null && !Current.Done && Current.SpellId == spellId) Close(Current, kind);
|
||||
else if (Open != null && !Open.Done && Open.SpellId == spellId) Close(Open, kind);
|
||||
}
|
||||
|
||||
private void Close(Cast c, string kind)
|
||||
{
|
||||
c.Done = true;
|
||||
DateTime now = Now;
|
||||
string nudged = c.Nudged ? " (after the movement nudge)" : "";
|
||||
if (c.HasIncantation)
|
||||
_log($"[CastTime] '{c.Name}': {kind} {Secs(now - c.IncantAt)} after its incantation (send to incantation {Ms(c.IncantAt - c.SentAt)}){nudged}.");
|
||||
else
|
||||
_log($"[CastTime] '{c.Name}': {kind} {Secs(now - c.SentAt)} after the send (no incantation seen){nudged}.");
|
||||
if (Open == c) Open = null;
|
||||
}
|
||||
|
||||
/// <summary>The last UseDone the engine saw. A UseDone with no error after a cast's incantation
|
||||
/// is that cast finishing; anything else (0x1D too busy, a UseDone before the incantation) is not.</summary>
|
||||
public void ObserveUseDone(int lastSeq, uint lastError)
|
||||
{
|
||||
if (lastError != 0) return;
|
||||
foreach (Cast? c in new[] { Open, Current })
|
||||
{
|
||||
if (c == null || c.Done || !c.HasIncantation || lastSeq <= c.SeqAtIncant) continue;
|
||||
Close(c, $"UseDone #{lastSeq} (no error)");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True while the server hasn't finished the last cast sent. Clears on that cast's result
|
||||
/// line, on a UseDone(0) after its incantation, after a refusal once a UseDone(0) shows the
|
||||
/// server free again, or at its give-up time (<paramref name="fallbackMs"/> from the send,
|
||||
/// later with a late incantation). <paramref name="hasLast"/> false (an engine before v70)
|
||||
/// keeps the old rule: any new UseDone clears it.
|
||||
/// </summary>
|
||||
public bool AwaitingServer(double fallbackMs, int useDoneSeq, bool hasLast, int lastSeq, uint lastError)
|
||||
{
|
||||
Cast? c = Current;
|
||||
if (c == null || c.Done) return false;
|
||||
if (Now >= GiveUpAt(c, fallbackMs)) return false;
|
||||
if (!hasLast) return useDoneSeq == c.SeqAtSend;
|
||||
ObserveUseDone(lastSeq, lastError);
|
||||
if (c.Done) return false;
|
||||
if (c.Refused && lastError == 0 && lastSeq > c.SeqAtRefusal) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// "You're too busy!" arrived. The last cast sent, if it had no incantation yet, was refused.
|
||||
/// Returns true exactly once per held cast: an incantation more than HeldAfterIncantMs ago,
|
||||
/// no result, and AC still refusing casts. The caller sends one movement nudge.
|
||||
/// </summary>
|
||||
public bool Refusal(int useDoneSeq, double heldAfterMs = HeldAfterIncantMs)
|
||||
{
|
||||
Cast? c = Current;
|
||||
if (c != null && !c.HasIncantation && !c.Done && !c.Refused)
|
||||
{
|
||||
c.Refused = true;
|
||||
c.SeqAtRefusal = useDoneSeq;
|
||||
}
|
||||
return TakeNudge(heldAfterMs);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True exactly once per held cast: open (incantation, no result) for more than
|
||||
/// <paramref name="heldAfterMs"/> and not nudged yet. Marks it nudged. The refusal path uses
|
||||
/// it with HeldAfterIncantMs; a heal (or health under a heal line) polls it each tick with
|
||||
/// UrgentHeldAfterIncantMs, without waiting for a refusal.
|
||||
/// </summary>
|
||||
public bool TakeNudge(double heldAfterMs)
|
||||
{
|
||||
Cast? held = Open;
|
||||
if (held == null || held.Done || held.Nudged || !held.HasIncantation) return false;
|
||||
if ((Now - held.IncantAt).TotalMilliseconds <= heldAfterMs) return false;
|
||||
held.Nudged = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The cast the server holds open (incantation, no result), or null.</summary>
|
||||
public Cast? Held => Open is { Done: false } o && o.HasIncantation ? o : null;
|
||||
|
||||
/// <summary>One log line the first time a cast has been open past HeldAfterIncantMs (polled each tick).</summary>
|
||||
public void Poll()
|
||||
{
|
||||
Cast? held = Open;
|
||||
if (held == null || held.Done || held.StuckLogged) return;
|
||||
if ((Now - held.IncantAt).TotalMilliseconds <= HeldAfterIncantMs) return;
|
||||
held.StuckLogged = true;
|
||||
_log($"[CastTime] '{held.Name}': HELD - incantation {Secs(Now - held.IncantAt)} ago and no result yet (the server is holding the cast open).");
|
||||
}
|
||||
|
||||
/// <summary>Seconds a cast has been held open (incantation, no result), or 0.</summary>
|
||||
public double HeldSeconds
|
||||
{
|
||||
get
|
||||
{
|
||||
Cast? held = Open;
|
||||
return held == null || held.Done ? 0 : (Now - held.IncantAt).TotalSeconds;
|
||||
}
|
||||
}
|
||||
|
||||
private static string Secs(TimeSpan t) => $"{t.TotalSeconds:0.00} s";
|
||||
private static string Ms(TimeSpan t) => $"{t.TotalMilliseconds:0} ms";
|
||||
}
|
||||
|
|
@ -3348,8 +3348,9 @@ public partial class CombatManager : IDisposable
|
|||
|
||||
/// <summary>
|
||||
/// The weapon to fight <paramref name="target"/> with (0 = none), and the element in
|
||||
/// <paramref name="desired"/>. See WeaponPlanner for the order: the Damage tab's weapon
|
||||
/// (listed only), the Monsters rule's damage type, the weakness (weakest element a listed
|
||||
/// <paramref name="desired"/>. See WeaponPlanner for the order: this monster's Damage tab
|
||||
/// weapon (listed only), a slayer of the monster, the Damage tab DEFAULT row's weapon, the
|
||||
/// Monsters rule's damage type, the weakness (weakest element a listed
|
||||
/// weapon of the main kind has), else the weapon in hand, the learned best, the first.
|
||||
/// Casters are skipped when the character has no War/Void Magic (IsUsableCombatWeapon).
|
||||
/// </summary>
|
||||
|
|
@ -3414,7 +3415,13 @@ public partial class CombatManager : IDisposable
|
|||
var weak = WeaknessFor(target);
|
||||
listed = ApplyAmmo(listed, ruleElement, weak);
|
||||
// Slayers (PropertyInt 166 = the monster's PropertyInt 2) only when a listed weapon has one.
|
||||
int ctype = listed.Any(c => c.SlayerType > 0) ? CreatureTypeOf(wcid, target.Name, target.Id) : 0;
|
||||
int ctype = 0;
|
||||
if (listed.Any(c => c.SlayerType > 0))
|
||||
{
|
||||
ctype = CreatureTypeOf(wcid, target.Name, target.Id);
|
||||
if (ctype == 0 && _slayerTypeUnknownNoted.TryAdd(wcid != 0 ? wcid.ToString() : target.Name ?? "", 0))
|
||||
_host.Log($"[EquipDiag] '{target.Name}' (wcid {wcid}): creature type not known yet (not appraised, not in the creature data) - no slayer check until it is");
|
||||
}
|
||||
return WeaponPlanner.Choose(listed, ruleElement, weak, e => CanCastElement(e, rule),
|
||||
fixedId, fixedSource, learnedId, ctype, fixedIsDefault);
|
||||
}
|
||||
|
|
@ -3424,18 +3431,26 @@ public partial class CombatManager : IDisposable
|
|||
|
||||
/// <summary>
|
||||
/// A weapon's slayer (creature type, damage multiplier); (0, 0) when it has none or isn't
|
||||
/// identified yet (the weapon tracker identifies listed weapons). ACE needs both properties.
|
||||
/// identified yet (the weapon tracker identifies listed weapons). The multiplier is 0 when
|
||||
/// not known: ACE sends SlayerCreatureType (int 166, an assessment property) on appraisal
|
||||
/// but never SlayerDamageBonus (float 138), so requiring both (as before 2026-10-05) meant no
|
||||
/// slayer was ever seen on an ACE server. A server that does send float 138 gets it used.
|
||||
/// </summary>
|
||||
internal (int Type, double Bonus) SlayerOf(int weaponId)
|
||||
{
|
||||
uint uid = unchecked((uint)weaponId);
|
||||
if (!_host.HasGetObjectIntProperty || !_host.TryGetObjectIntProperty(uid, PropSlayerCreatureType, out int t) || t <= 0)
|
||||
return (0, 0);
|
||||
if (!_host.HasGetObjectDoubleProperty || !_host.TryGetObjectDoubleProperty(uid, PropSlayerDamageBonus, out double b) || b <= 0)
|
||||
return (0, 0);
|
||||
return (t, b);
|
||||
double bonus = _host.HasGetObjectDoubleProperty && _host.TryGetObjectDoubleProperty(uid, PropSlayerDamageBonus, out double b) && b > 0 ? b : 0;
|
||||
if (_slayerNoted.TryAdd((weaponId, t), 0))
|
||||
_host.Log($"[EquipDiag] weapon 0x{uid:X8} '{WeaponName(weaponId)}' slays {CreatureTypeNames.Name(t)} ({(bonus > 0 ? "x" + bonus.ToString("0.##", System.Globalization.CultureInfo.InvariantCulture) : "bonus not sent")})");
|
||||
return (t, bonus);
|
||||
}
|
||||
|
||||
// Logged once each: a listed weapon's slayer; a monster whose type isn't known while a slayer is listed.
|
||||
private readonly System.Collections.Concurrent.ConcurrentDictionary<(int, int), byte> _slayerNoted = new();
|
||||
private readonly System.Collections.Concurrent.ConcurrentDictionary<string, byte> _slayerTypeUnknownNoted = new();
|
||||
|
||||
// Creature type by wcid, once seen: a wcid's type never changes, so the next spawn is instant.
|
||||
// Concurrent: the Damage tab's JSON export asks for weaknesses off the combat tick.
|
||||
private readonly System.Collections.Concurrent.ConcurrentDictionary<uint, int> _creatureTypeByWcid = new();
|
||||
|
|
@ -3443,7 +3458,8 @@ public partial class CombatManager : IDisposable
|
|||
/// <summary>
|
||||
/// The monster's CreatureType (PropertyInt 2; 0 = unknown): this session's per-wcid cache,
|
||||
/// else the creature store (appraisals saved by name and wcid), else the live appraisal
|
||||
/// (the engine identifies every new object). Never guessed from the name.
|
||||
/// (the engine identifies every new object), else the shipped world-database table
|
||||
/// (CreatureWeakness: wcid and exact name). Never guessed from name keywords.
|
||||
/// </summary>
|
||||
internal int CreatureTypeOf(uint wcid, string? name, int objectId = 0)
|
||||
{
|
||||
|
|
@ -3464,6 +3480,11 @@ public partial class CombatManager : IDisposable
|
|||
if (_creatureTypeByWcid.Count > 4096) _creatureTypeByWcid.Clear();
|
||||
_creatureTypeByWcid[wcid] = ctype;
|
||||
}
|
||||
// Not seen yet on this server: the shipped world-database table (wcid and name must both
|
||||
// match, as for its resists). Not cached, so this monster's own appraisal still wins once
|
||||
// it lands. 4,506 of the ~4,900 creature profiles are seeded without a type (2026-10-05),
|
||||
// so before this the first fight with a monster had no slayer step.
|
||||
if (ctype <= 0) ctype = CreatureWeakness.TableCreatureType(wcid, name);
|
||||
return ctype > 0 ? ctype : 0;
|
||||
}
|
||||
|
||||
|
|
@ -3996,7 +4017,7 @@ public partial class CombatManager : IDisposable
|
|||
&& (CurrentCombatMode == CombatMode.Melee || CurrentCombatMode == CombatMode.Missile))
|
||||
{
|
||||
if (_host.HasCancelAttack) _host.CancelAttack();
|
||||
if (_host.HasStopCompletely) _host.StopCompletely();
|
||||
if (_host.HasStopCompletely) _host.StopCompletelyBy("Combat");
|
||||
_combatSwapTeardownDone = true;
|
||||
_host.Log($"[EquipDiag] CancelAttack+StopCompletely before wand equip (mode was {CurrentCombatMode})");
|
||||
}
|
||||
|
|
@ -4244,7 +4265,7 @@ public partial class CombatManager : IDisposable
|
|||
&& (CurrentCombatMode == CombatMode.Melee || CurrentCombatMode == CombatMode.Missile))
|
||||
{
|
||||
if (_host.HasCancelAttack) _host.CancelAttack();
|
||||
if (_host.HasStopCompletely) _host.StopCompletely();
|
||||
if (_host.HasStopCompletely) _host.StopCompletelyBy("Combat");
|
||||
_combatSwapTeardownDone = true;
|
||||
}
|
||||
if (!EnsureHandClearForWand(wandId, diagNow: true))
|
||||
|
|
@ -4393,13 +4414,13 @@ public partial class CombatManager : IDisposable
|
|||
}
|
||||
else if (error > 0)
|
||||
{
|
||||
_host.SetMotion(MotionTurnRight, true);
|
||||
_host.SetMotion(MotionTurnLeft, false);
|
||||
_host.SetMotionBy("Combat", MotionTurnRight, true);
|
||||
_host.SetMotionBy("Combat", MotionTurnLeft, false);
|
||||
}
|
||||
else
|
||||
{
|
||||
_host.SetMotion(MotionTurnLeft, true);
|
||||
_host.SetMotion(MotionTurnRight, false);
|
||||
_host.SetMotionBy("Combat", MotionTurnLeft, true);
|
||||
_host.SetMotionBy("Combat", MotionTurnRight, false);
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
|
|
@ -4407,8 +4428,8 @@ public partial class CombatManager : IDisposable
|
|||
|
||||
private void ClearCombatTurnMotions()
|
||||
{
|
||||
_host.SetMotion(MotionTurnRight, false);
|
||||
_host.SetMotion(MotionTurnLeft, false);
|
||||
_host.SetMotionBy("Combat", MotionTurnRight, false);
|
||||
_host.SetMotionBy("Combat", MotionTurnLeft, false);
|
||||
}
|
||||
|
||||
/// <summary>Let go of a turn the facing servo is holding. Called when combat stops
|
||||
|
|
|
|||
205
Plugins/RynthCore.Plugin.RynthAi/Combat/HealLatencyTracker.cs
Normal file
205
Plugins/RynthCore.Plugin.RynthAi/Combat/HealLatencyTracker.cs
Normal file
|
|
@ -0,0 +1,205 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
/// <summary>
|
||||
/// [HealLatency]: how long health sat under a heal line before the first heal went out, and what
|
||||
/// held it meanwhile. One line per episode, and a summary every <see cref="SummaryEvery"/> episodes.
|
||||
///
|
||||
/// Why (2026-10-05): a tester playing a mage reported heals that are "sometimes fine, sometimes
|
||||
/// several seconds late", and nothing in the log said when health crossed a line or what the bot
|
||||
/// was waiting on. With this a tester's log answers it:
|
||||
///
|
||||
/// [HealLatency] 3120 ms: health 41% under Heal At 60% (in combat) -> Heal Self; held by: busy count 2980 ms (leftover), cast gate 140 ms; arbiter Combat 120 ms
|
||||
///
|
||||
/// An episode opens on the first tick health is under the active line (Emergency Heal At, Stamina
|
||||
/// To Health At, Heal At in combat, Top Off HP idle) and ends at the first heal sent for it (kit,
|
||||
/// Heal Self, Stamina to Health or a health potion). While health stays under a line, the next
|
||||
/// episode opens once that heal has resolved (no kit or vital cast left in flight), so a slow
|
||||
/// second heal is measured from when it became possible, not from the first one. An episode that
|
||||
/// ends with no heal (health rose, or the fight ended and the idle line is lower) is logged only
|
||||
/// when it lasted <see cref="NoHealLogMs"/> or more.
|
||||
///
|
||||
/// Pure bookkeeping: BuffManager feeds it once per heartbeat and when a heal goes out; it never
|
||||
/// calls the game. The clock comes from the caller (tests move it by hand).
|
||||
/// </summary>
|
||||
internal sealed class HealLatencyTracker
|
||||
{
|
||||
/// <summary>A summary line after this many healed episodes.</summary>
|
||||
public const int SummaryEvery = 10;
|
||||
/// <summary>An episode that ends without a heal is logged only from this long.</summary>
|
||||
public const double NoHealLogMs = 1000;
|
||||
|
||||
private readonly Action<string> _log;
|
||||
public HealLatencyTracker(Action<string> log) => _log = log;
|
||||
|
||||
// ── The open episode ────────────────────────────────────────────────────
|
||||
private bool _open;
|
||||
private bool _healed; // a heal went out for the open episode; waiting for it to resolve
|
||||
private bool _followUp; // opened while health stayed under the line after a heal
|
||||
private DateTime _start;
|
||||
private int _startHp;
|
||||
private string _line = "";
|
||||
private int _lineValue;
|
||||
private bool _inCombat;
|
||||
private DateTime _lastTickAt = DateTime.MinValue;
|
||||
// Time held per reason, and time the arbiter gave the tick to something other than Buffing.
|
||||
private readonly Dictionary<string, double> _held = new(StringComparer.Ordinal);
|
||||
private readonly Dictionary<string, double> _arbiter = new(StringComparer.Ordinal);
|
||||
private string _lastDetail = "";
|
||||
|
||||
// ── Summary since the last summary line ─────────────────────────────────
|
||||
private int _n;
|
||||
private double _sumMs, _maxMs;
|
||||
private string _maxWhat = "";
|
||||
private int _over1s, _over3s, _noHeal;
|
||||
|
||||
/// <summary>Totals for the tests and /ra status.</summary>
|
||||
public int Episodes { get; private set; }
|
||||
public double LastDelayMs { get; private set; } = -1;
|
||||
public string LastLine { get; private set; } = "";
|
||||
public bool IsOpen => _open && !_healed;
|
||||
|
||||
/// <summary>
|
||||
/// Once per heartbeat, before the tick's work: health and the line it is under (line "" = none).
|
||||
/// <paramref name="healInFlight"/>: a kit or a heal cast from the last episode hasn't resolved yet.
|
||||
/// </summary>
|
||||
public void Observe(DateTime now, int hp, string line, int lineValue, bool inCombat, bool healInFlight)
|
||||
{
|
||||
bool under = line.Length > 0;
|
||||
if (!under)
|
||||
{
|
||||
if (_open && !_healed)
|
||||
{
|
||||
double ms = (now - _start).TotalMilliseconds;
|
||||
if (ms >= NoHealLogMs)
|
||||
{
|
||||
_noHeal++;
|
||||
_log($"[HealLatency] no heal in {ms:0} ms: health {_startHp}% under {_line} {_lineValue}%{Where(_inCombat)}{(_followUp ? " (follow-up)" : "")}, " +
|
||||
$"then {hp}% (over the line now); held by: {Held()}{Arb()}");
|
||||
}
|
||||
}
|
||||
_open = false;
|
||||
_healed = false;
|
||||
_followUp = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if (_open && _healed)
|
||||
{
|
||||
// Still under a line after a heal: the next one is measured from when it became possible.
|
||||
if (healInFlight) { _lastTickAt = now; return; }
|
||||
Begin(now, hp, line, lineValue, inCombat, followUp: true);
|
||||
return;
|
||||
}
|
||||
if (!_open)
|
||||
{
|
||||
Begin(now, hp, line, lineValue, inCombat, followUp: false);
|
||||
return;
|
||||
}
|
||||
// Open and waiting: a lower line (Heal At -> Emergency) is worth saying in the line.
|
||||
if (line != _line && (line.StartsWith("Emergency", StringComparison.Ordinal) || line.StartsWith("Stamina", StringComparison.Ordinal)))
|
||||
{
|
||||
_line = line;
|
||||
_lineValue = lineValue;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Once per heartbeat, after the tick's work: why no heal went out this tick.</summary>
|
||||
public void EndTick(DateTime now, string heldBy, string detail, string arbiterActivity)
|
||||
{
|
||||
if (!_open || _healed) { _lastTickAt = now; return; }
|
||||
double dt = _lastTickAt == DateTime.MinValue ? 0 : (now - _lastTickAt).TotalMilliseconds;
|
||||
if (dt < 0 || dt > 2000) dt = 0; // a hitch or a paused clock is not "held"
|
||||
_lastTickAt = now;
|
||||
if (dt <= 0) return;
|
||||
string key = heldBy.Length > 0 ? heldBy : "nothing reported";
|
||||
_held[key] = (_held.TryGetValue(key, out double h) ? h : 0) + dt;
|
||||
if (detail.Length > 0) _lastDetail = detail;
|
||||
if (arbiterActivity.Length > 0 && arbiterActivity != "Buffing")
|
||||
_arbiter[arbiterActivity] = (_arbiter.TryGetValue(arbiterActivity, out double a) ? a : 0) + dt;
|
||||
}
|
||||
|
||||
/// <summary>A heal went out (kit, Heal Self, Stamina to Health, health potion).</summary>
|
||||
public void HealSent(DateTime now, string action)
|
||||
{
|
||||
if (!_open || _healed) return;
|
||||
_healed = true;
|
||||
double ms = Math.Max(0, (now - _start).TotalMilliseconds);
|
||||
Episodes++;
|
||||
LastDelayMs = ms;
|
||||
string line = $"[HealLatency] {ms:0} ms: health {_startHp}% under {_line} {_lineValue}%{Where(_inCombat)}{(_followUp ? " (follow-up)" : "")} -> {action}; held by: {Held()}{Arb()}";
|
||||
LastLine = line;
|
||||
_log(line);
|
||||
|
||||
_n++;
|
||||
_sumMs += ms;
|
||||
if (ms >= 1000) _over1s++;
|
||||
if (ms >= 3000) _over3s++;
|
||||
if (ms > _maxMs) { _maxMs = ms; _maxWhat = $"{action}, {TopHeld()}"; }
|
||||
if (_n >= SummaryEvery)
|
||||
{
|
||||
_log($"[HealLatency] summary of {_n} heals: avg {_sumMs / _n:0} ms, max {_maxMs:0} ms ({_maxWhat}); " +
|
||||
$"{_over1s} over 1 s, {_over3s} over 3 s; {_noHeal} episode(s) with no heal");
|
||||
_n = 0; _sumMs = 0; _maxMs = 0; _maxWhat = ""; _over1s = 0; _over3s = 0; _noHeal = 0;
|
||||
}
|
||||
}
|
||||
|
||||
private void Begin(DateTime now, int hp, string line, int lineValue, bool inCombat, bool followUp)
|
||||
{
|
||||
_open = true;
|
||||
_healed = false;
|
||||
_followUp = followUp;
|
||||
_start = now;
|
||||
_startHp = hp;
|
||||
_line = line;
|
||||
_lineValue = lineValue;
|
||||
_inCombat = inCombat;
|
||||
_lastTickAt = now;
|
||||
_held.Clear();
|
||||
_arbiter.Clear();
|
||||
_lastDetail = "";
|
||||
}
|
||||
|
||||
private static string Where(bool inCombat) => inCombat ? " (in combat)" : " (idle)";
|
||||
|
||||
private string Held()
|
||||
{
|
||||
if (_held.Count == 0) return "nothing (healed on the first tick)";
|
||||
var parts = new List<KeyValuePair<string, double>>(_held);
|
||||
parts.Sort((a, b) => b.Value.CompareTo(a.Value));
|
||||
var sb = new StringBuilder();
|
||||
for (int i = 0; i < parts.Count && i < 4; i++)
|
||||
{
|
||||
if (i > 0) sb.Append(", ");
|
||||
sb.Append(parts[i].Key).Append(' ').Append(parts[i].Value.ToString("0")).Append(" ms");
|
||||
}
|
||||
if (_lastDetail.Length > 0) sb.Append(" [last: ").Append(_lastDetail).Append(']');
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
private string TopHeld()
|
||||
{
|
||||
string top = "nothing";
|
||||
double best = -1;
|
||||
foreach (var kv in _held)
|
||||
if (kv.Value > best) { best = kv.Value; top = kv.Key; }
|
||||
return top;
|
||||
}
|
||||
|
||||
private string Arb()
|
||||
{
|
||||
if (_arbiter.Count == 0) return "";
|
||||
var sb = new StringBuilder("; arbiter gave the tick to ");
|
||||
bool first = true;
|
||||
foreach (var kv in _arbiter)
|
||||
{
|
||||
if (!first) sb.Append(", ");
|
||||
first = false;
|
||||
sb.Append(kv.Key).Append(' ').Append(kv.Value.ToString("0")).Append(" ms");
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
32
Plugins/RynthCore.Plugin.RynthAi/Combat/ReloadSafety.cs
Normal file
32
Plugins/RynthCore.Plugin.RynthAi/Combat/ReloadSafety.cs
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
using System.Collections.Generic;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
/// <summary>
|
||||
/// What RynthAi tells the engine before a hot reload (the RynthPluginReloadBlocker export).
|
||||
///
|
||||
/// Drakkon died on 2026-10-05 13:43:20 after an engine hot reload at 13:42:55 took every plugin
|
||||
/// down for about 8 s in the middle of a fight. The engine now asks each plugin before it reloads
|
||||
/// and waits (up to 2 minutes) while one says a reload would hurt. RynthAi says so while the macro
|
||||
/// runs and a monster is engaged, health is under a heal line, or a cast is awaiting its result.
|
||||
///
|
||||
/// Pure: the plugin computes the text on its own thread each tick; the export only hands the last
|
||||
/// text to the engine.
|
||||
/// </summary>
|
||||
internal static class ReloadSafety
|
||||
{
|
||||
/// <summary>Why a reload now would hurt, or "" when it is safe. The engine logs
|
||||
/// "engine reload waiting: RynthAi " followed by this text.</summary>
|
||||
public static string Reason(bool macroRunning, bool monsterEngaged, string healLine, int healthPct,
|
||||
int lineValue, string castInFlight)
|
||||
{
|
||||
if (!macroRunning) return "";
|
||||
var parts = new List<string>(3);
|
||||
if (monsterEngaged) parts.Add("a monster engaged");
|
||||
if (healLine.Length > 0) parts.Add($"health {healthPct}% under {healLine} {lineValue}%");
|
||||
if (castInFlight.Length > 0) parts.Add($"'{castInFlight}' awaiting its result");
|
||||
if (parts.Count == 0) return "";
|
||||
bool fight = monsterEngaged || healLine.Length > 0;
|
||||
return (fight ? "in combat" : "casting") + " (" + string.Join(", ", parts) + ")";
|
||||
}
|
||||
}
|
||||
|
|
@ -9,7 +9,9 @@ namespace RynthCore.Plugin.RynthAi;
|
|||
/// <param name="Element">Normalized element ("" = unknown).</param>
|
||||
/// <param name="Rending">Element of a rending imbue ("" = none).</param>
|
||||
/// <param name="SlayerType">The creature type it slays (PropertyInt 166 SlayerCreatureType, 0 = none).</param>
|
||||
/// <param name="SlayerBonus">Its damage multiplier against that type (PropertyFloat 138 SlayerDamageBonus, 0 = none).</param>
|
||||
/// <param name="SlayerBonus">Its damage multiplier against that type (PropertyFloat 138 SlayerDamageBonus); 0 = not
|
||||
/// known. ACE never sends float 138 on appraisal (it isn't an assessment property), so with a SlayerType it is
|
||||
/// usually 0, and the weapon still slays (every slayer in the ACE world database has a bonus of 1.15 or more).</param>
|
||||
internal sealed record WeaponCandidate(int Id, string Name, int Kind, string Element, string Rending, bool InHand,
|
||||
int SlayerType = 0, double SlayerBonus = 0);
|
||||
|
||||
|
|
@ -19,17 +21,22 @@ internal readonly record struct WeaponPlan(int WeaponId, string Element, string
|
|||
|
||||
/// <summary>
|
||||
/// The element-and-weapon rule, pure (no host). The weakness decides the weapon, never the
|
||||
/// other way round, except for a slayer:
|
||||
/// 1. A Damage tab weapon (this monster's, else the DEFAULT row's) is used as set; it must be in the Items list.
|
||||
/// Its element is the rule's, else its own, else the weakest the character can cast.
|
||||
/// other way round, except for a slayer (owner's rule, 2026-10-05: a monster is always
|
||||
/// attacked with a slayer of it before an element choice, even when another weapon's element
|
||||
/// meets a lower resistance; only a weapon the player set for that monster trumps it):
|
||||
/// 1. The weapon set on THIS monster's own Damage tab row is used as set, slayer or not; it
|
||||
/// must be in the Items list. Its element is the rule's, else its own, else the weakest
|
||||
/// the character can cast.
|
||||
/// 2. A slayer: a listed weapon of the character's main kind whose SlayerCreatureType is
|
||||
/// the monster's CreatureType and whose SlayerDamageBonus is above 1 (ACE multiplies the
|
||||
/// whole hit by it, so it beats any element choice). Several: the biggest bonus, then
|
||||
/// the element order (the rule's element, else the weakest group), then a matching
|
||||
/// rending, then the one in hand, then list order. Its element is the wand's own, else a
|
||||
/// melee/missile weapon's own, else the rule's, else the weakest the character can cast.
|
||||
/// Creature type unknown (not appraised yet): no slayer step.
|
||||
/// 3. (The Damage tab DEFAULT row's weapon is a player pick too: it is step 1.)
|
||||
/// the monster's CreatureType and whose SlayerDamageBonus is above 1 or not known (ACE
|
||||
/// multiplies the whole hit by it, so it beats any element choice, and never sends the
|
||||
/// bonus on appraisal). Several: the biggest bonus (an unknown one counts as
|
||||
/// UnknownSlayerBonus), then the element order (the rule's element, else the weakest
|
||||
/// group), then a matching rending, then the one in hand, then list order. Its element
|
||||
/// is the wand's own, else a melee/missile weapon's own, else the rule's, else the
|
||||
/// weakest the character can cast. Creature type unknown: no slayer step.
|
||||
/// A slayer of another kind (a melee slayer for a mage) is not a candidate.
|
||||
/// 3. The Damage tab DEFAULT row's weapon (listed only): above the element steps, below a slayer.
|
||||
/// 4. A Monsters rule damage type (not Auto) is the element; wield the listed weapon of that
|
||||
/// element (a matching rending first, then the one in hand, then list order).
|
||||
/// Whatever is chosen, a wand casts its own element when it has one (owner's rule,
|
||||
|
|
@ -51,6 +58,12 @@ internal static class WeaponPlanner
|
|||
/// <summary>Two multipliers this close are a tie.</summary>
|
||||
public const double TieEpsilon = 0.005;
|
||||
|
||||
/// <summary>
|
||||
/// The bonus a slayer whose SlayerDamageBonus isn't known is ranked at: the smallest in the
|
||||
/// ACE world database (1.15), so a slayer with a known bigger bonus wins over it.
|
||||
/// </summary>
|
||||
public const double UnknownSlayerBonus = 1.15;
|
||||
|
||||
/// <summary>Fallback element order when nothing is known ("Slash" first).</summary>
|
||||
public static readonly string[] FallbackOrder = { "Slash", "Fire", "Cold", "Lightning", "Acid", "Pierce", "Bludgeon", "Nether" };
|
||||
|
||||
|
|
@ -69,12 +82,13 @@ internal static class WeaponPlanner
|
|||
bool ruleSet = rule.Length > 0;
|
||||
WeaponCandidate? fixedPick = fixedWeaponId != 0 ? Find(listed, fixedWeaponId) : null;
|
||||
|
||||
// 1. A weapon the player picked on the Damage tab: for this monster, or the DEFAULT row's
|
||||
// (listed only). A player's pick is honoured, slayer or not (owner, 2026-10-04: "if
|
||||
// it's set to auto slayer wins, if the player picks a weapon we honour that").
|
||||
// fixedIsDefault only changes the source label.
|
||||
if (fixedPick != null)
|
||||
return FixedPlan(fixedPick, fixedSource, rule, weak, canCast);
|
||||
// 1. The weapon the player set on this monster's own Damage tab row (listed only): honoured,
|
||||
// slayer or not (owner, 2026-10-05: "the only time a slayer property gets trumped is if
|
||||
// the player manually inputs a weapon without it"). The DEFAULT row's weapon is not a
|
||||
// pick for this monster: a slayer of it beats that one (step 3).
|
||||
if (fixedPick != null && !fixedIsDefault)
|
||||
return FixedPlan(fixedPick, Slays(fixedPick, creatureType)
|
||||
? fixedSource + ", " + SlayerSource(creatureType, fixedPick.SlayerBonus) : fixedSource, rule, weak, canCast);
|
||||
|
||||
if (listed.Count == 0)
|
||||
{
|
||||
|
|
@ -101,7 +115,7 @@ internal static class WeaponPlanner
|
|||
}
|
||||
}
|
||||
|
||||
// 3. The Damage tab default weapon (listed only).
|
||||
// 3. The Damage tab DEFAULT row's weapon (listed only): no slayer of this monster is listed.
|
||||
if (fixedPick != null)
|
||||
return FixedPlan(fixedPick, fixedSource, rule, weak, canCast);
|
||||
|
||||
|
|
@ -200,16 +214,24 @@ internal static class WeaponPlanner
|
|||
return null;
|
||||
}
|
||||
|
||||
/// <summary>True when <paramref name="c"/> slays <paramref name="creatureType"/> (ACE: SlayerCreatureType == CreatureType, with a bonus).</summary>
|
||||
/// <summary>
|
||||
/// True when <paramref name="c"/> slays <paramref name="creatureType"/> (ACE: SlayerCreatureType ==
|
||||
/// CreatureType). A bonus that is known must be above 1; an unknown one (0: ACE doesn't send
|
||||
/// float 138 on appraisal) counts.
|
||||
/// </summary>
|
||||
public static bool Slays(WeaponCandidate c, int creatureType) =>
|
||||
creatureType > 0 && c.SlayerType == creatureType && c.SlayerBonus > 1.0 + TieEpsilon;
|
||||
creatureType > 0 && c.SlayerType == creatureType && (c.SlayerBonus <= 0 || c.SlayerBonus > 1.0 + TieEpsilon);
|
||||
|
||||
/// <summary>The plan's source for a slayer: "slayer (Olthoi x2)".</summary>
|
||||
public static string SlayerSource(int creatureType, double bonus) =>
|
||||
$"slayer ({CreatureTypeNames.Name(creatureType)} x{bonus.ToString("0.##", System.Globalization.CultureInfo.InvariantCulture)})";
|
||||
/// <summary>The bonus a slayer is ranked at: its own when known, else <see cref="UnknownSlayerBonus"/>.</summary>
|
||||
public static double RankBonus(WeaponCandidate c) => c.SlayerBonus > 0 ? c.SlayerBonus : UnknownSlayerBonus;
|
||||
|
||||
/// <summary>The plan's source for a slayer: "slayer (Olthoi x2)", or "slayer (Olthoi)" when the bonus isn't known.</summary>
|
||||
public static string SlayerSource(int creatureType, double bonus) => bonus > 0
|
||||
? $"slayer ({CreatureTypeNames.Name(creatureType)} x{bonus.ToString("0.##", System.Globalization.CultureInfo.InvariantCulture)})"
|
||||
: $"slayer ({CreatureTypeNames.Name(creatureType)})";
|
||||
|
||||
/// <summary>
|
||||
/// The matching slayer to wield: the biggest bonus (ties within <see cref="TieEpsilon"/>),
|
||||
/// The matching slayer to wield: the biggest bonus (<see cref="RankBonus"/>; ties within <see cref="TieEpsilon"/>),
|
||||
/// then the element order (the rule's element, else the weakest group), then a matching
|
||||
/// rending, then the one in hand, then list order. Null when none matches.
|
||||
/// </summary>
|
||||
|
|
@ -217,7 +239,7 @@ internal static class WeaponPlanner
|
|||
CreatureWeakness.Ranking? weak, Func<string, bool> canCast)
|
||||
{
|
||||
double top = 0;
|
||||
foreach (var c in pool) if (Slays(c, creatureType) && c.SlayerBonus > top) top = c.SlayerBonus;
|
||||
foreach (var c in pool) if (Slays(c, creatureType) && RankBonus(c) > top) top = RankBonus(c);
|
||||
if (top <= 0) return null;
|
||||
|
||||
List<List<string>>? groups = rule.Length == 0 && weak != null && weak.Order.Count > 0 ? TieGroups(weak) : null;
|
||||
|
|
@ -226,7 +248,7 @@ internal static class WeaponPlanner
|
|||
for (int i = 0; i < pool.Count; i++)
|
||||
{
|
||||
var c = pool[i];
|
||||
if (!Slays(c, creatureType) || c.SlayerBonus < top - TieEpsilon) continue;
|
||||
if (!Slays(c, creatureType) || RankBonus(c) < top - TieEpsilon) continue;
|
||||
int elemRank = 0;
|
||||
if (rule.Length > 0) elemRank = c.Element == rule ? 0 : 1;
|
||||
else if (groups != null)
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
|
|
@ -21,6 +22,8 @@ public sealed partial class RynthAiPlugin
|
|||
public string LongDesc { get; init; }
|
||||
public bool InFellowship { get; init; }
|
||||
public bool KillerIsFellow { get; init; }
|
||||
/// <summary>Your own death corpse, to be recovered whole (LootOwnCorpse; see MatchOwnDeathCorpse).</summary>
|
||||
public bool IsOwnDeathCorpse { get; init; }
|
||||
}
|
||||
|
||||
// id → completed-at ms. Authoritative "looted, do not reopen" set. Aged out
|
||||
|
|
@ -238,7 +241,7 @@ public sealed partial class RynthAiPlugin
|
|||
{
|
||||
string count = _lastCombatBusyStaleLogAt == 0 ? "first"
|
||||
: $"{_combatBusyStaleSinceLog} in the last {(now - _lastCombatBusyStaleLogAt) / 1000.0:0}s";
|
||||
Log($"[RynthAi] shadow busy-reset by combat (was {was}, {reason}; {count}) — real field left to the engine reconciler");
|
||||
Log($"[RynthAi] shadow busy-reset for a leftover count (was {was}, {reason}; {count}) — real field left to the engine reconciler");
|
||||
_lastCombatBusyStaleLogAt = now;
|
||||
_combatBusyStaleSinceLog = 0;
|
||||
}
|
||||
|
|
@ -522,8 +525,9 @@ public sealed partial class RynthAiPlugin
|
|||
if (_targetCorpseId == 0)
|
||||
{
|
||||
// Same gate as HasLootWork: this claim runs every tick whatever the arbiter
|
||||
// decided, so without it a full pack still claimed the next corpse.
|
||||
if (IsLootingBlockedByPack(settings))
|
||||
// decided, so without it a full pack still claimed the next corpse. Your own
|
||||
// corpse is let through unless no pack has a slot at all.
|
||||
if (IsLootingBlockedByPack(settings) && !OwnCorpseBypassesPackGate(settings, maxMeters))
|
||||
return;
|
||||
|
||||
if (!TryFindNearestCorpse(maxMeters, out WorldObject? corpse, out _))
|
||||
|
|
@ -546,6 +550,22 @@ public sealed partial class RynthAiPlugin
|
|||
LootDiag($"[RynthAi] Corpse loot: claimed corpse target 0x{(uint)corpse.Id:X8}.");
|
||||
PauseNavigationForCorpse();
|
||||
}
|
||||
else if (_openedContainerId == 0 && settings.LootOwnCorpse)
|
||||
{
|
||||
// Your own corpse came into range while another (unopened) corpse was claimed:
|
||||
// it beats normal looting, so switch to it.
|
||||
WorldObject? claimed = _objectCache[_targetCorpseId];
|
||||
if ((claimed == null || !EvaluateCorpseLootDecision(claimed).IsOwnDeathCorpse)
|
||||
&& TryFindOwnCorpseInRange(maxMeters, out WorldObject? ownNow) && ownNow != null && ownNow.Id != _targetCorpseId)
|
||||
{
|
||||
LootDiag($"[RynthAi] Own corpse: 0x{(uint)ownNow.Id:X8} is in range; switching to it from 0x{(uint)_targetCorpseId:X8}.");
|
||||
ResetCorpseTarget();
|
||||
_targetCorpseId = ownNow.Id;
|
||||
_corpseTargetSince = now;
|
||||
_lastCorpseOpenAttemptAt = 0;
|
||||
_lastOpenAttemptCorpseId = 0;
|
||||
}
|
||||
}
|
||||
|
||||
// A claim can be tentative: the killer is unknown until the corpse's ID lands.
|
||||
// Once it says the corpse isn't ours to loot, drop the claim instead of walking
|
||||
|
|
@ -685,6 +705,8 @@ public sealed partial class RynthAiPlugin
|
|||
|
||||
long now = CorpseNowMs;
|
||||
int playerId = unchecked((int)_playerId);
|
||||
WorldObject? ownCorpse = null;
|
||||
double ownDistance = double.MaxValue;
|
||||
foreach (WorldObject candidate in _objectCache.GetLandscapeObjects())
|
||||
{
|
||||
if (candidate.ObjectClass != AcObjectClass.Corpse)
|
||||
|
|
@ -712,13 +734,28 @@ public sealed partial class RynthAiPlugin
|
|||
}
|
||||
|
||||
double dist = _objectCache.Distance(playerId, candidate.Id);
|
||||
if (dist > maxMeters || dist >= distanceMeters)
|
||||
if (dist > maxMeters)
|
||||
continue;
|
||||
|
||||
// Your own corpse beats any other corpse in range, whatever the distances.
|
||||
if (decision.IsOwnDeathCorpse)
|
||||
{
|
||||
if (ownCorpse == null || dist < ownDistance) { ownCorpse = candidate; ownDistance = dist; }
|
||||
continue;
|
||||
}
|
||||
|
||||
if (dist >= distanceMeters)
|
||||
continue;
|
||||
|
||||
corpse = candidate;
|
||||
distanceMeters = dist;
|
||||
}
|
||||
|
||||
if (ownCorpse != null)
|
||||
{
|
||||
corpse = ownCorpse;
|
||||
distanceMeters = ownDistance;
|
||||
}
|
||||
return corpse != null;
|
||||
}
|
||||
|
||||
|
|
@ -769,6 +806,44 @@ public sealed partial class RynthAiPlugin
|
|||
};
|
||||
}
|
||||
|
||||
// Your own death corpse (LootOwnCorpse): recovered whole, whatever Loot From says. A
|
||||
// corpse with your name whose ID hasn't landed yet waits for it (no profile looting of
|
||||
// it meanwhile); anything else falls through to the ownership rules below unchanged.
|
||||
if (settings.LootOwnCorpse)
|
||||
{
|
||||
OwnCorpseMatch own = MatchOwnDeathCorpse(corpse.Name, myName, longDesc);
|
||||
if (own == OwnCorpseMatch.Yes)
|
||||
{
|
||||
return new CorpseLootDecision
|
||||
{
|
||||
ShouldLoot = true,
|
||||
ModeName = "Own corpse",
|
||||
Reason = "Your own corpse: every item on it is recovered (Recover My Corpse).",
|
||||
KillerName = killerName,
|
||||
PlayerName = myName,
|
||||
LongDesc = longDesc,
|
||||
InFellowship = inFellowship,
|
||||
KillerIsFellow = killerIsFellow,
|
||||
IsOwnDeathCorpse = true
|
||||
};
|
||||
}
|
||||
if (own == OwnCorpseMatch.Pending)
|
||||
{
|
||||
RequestOwnCorpseId(corpse.Id);
|
||||
return new CorpseLootDecision
|
||||
{
|
||||
ShouldLoot = false,
|
||||
ModeName = "Own corpse",
|
||||
Reason = "Named like your corpse; waiting for its ID (the 'Killed by' line) before recovering it.",
|
||||
KillerName = killerName,
|
||||
PlayerName = myName,
|
||||
LongDesc = longDesc,
|
||||
InFellowship = inFellowship,
|
||||
KillerIsFellow = killerIsFellow
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (lootOwnership >= 2)
|
||||
{
|
||||
return new CorpseLootDecision
|
||||
|
|
@ -1017,6 +1092,15 @@ public sealed partial class RynthAiPlugin
|
|||
TickPendingCorpsePickup(settings);
|
||||
if (_currentLootItemMovePending)
|
||||
return; // Still waiting for this pickup to clear
|
||||
if (_openedContainerId != corpseId)
|
||||
return; // the retry finished or paused the corpse (no pack had room)
|
||||
}
|
||||
|
||||
// Your own corpse: every item, no profile (RynthAiPlugin.OwnCorpse.cs).
|
||||
if (IsOwnDeathCorpseId(settings, corpseId))
|
||||
{
|
||||
TickOwnCorpseRecovery(settings, corpseId, containedItems, openAge, now);
|
||||
return;
|
||||
}
|
||||
|
||||
// Pre-classify items and batch-request IDs only for items that need them.
|
||||
|
|
@ -1384,7 +1468,16 @@ public sealed partial class RynthAiPlugin
|
|||
/// </summary>
|
||||
private LootPickupResult SendLootPickup(int itemId, string itemName, int corpseId)
|
||||
{
|
||||
LootPickupResult r = LootPickup.Send(Host, _objectCache, unchecked((uint)itemId), _playerId, out uint dest);
|
||||
bool ownCorpse = corpseId != 0 && corpseId == _ownRecoveryCorpseId;
|
||||
uint dest;
|
||||
LootPickupResult r = ownCorpse
|
||||
? SendOwnCorpsePickup(itemId, out dest)
|
||||
: LootPickup.Send(Host, _objectCache, unchecked((uint)itemId), _playerId, out dest);
|
||||
if (ownCorpse && r == LootPickupResult.NoRoom)
|
||||
{
|
||||
PauseOwnCorpseNoRoom(corpseId, itemName);
|
||||
return r;
|
||||
}
|
||||
switch (r)
|
||||
{
|
||||
case LootPickupResult.Moved:
|
||||
|
|
@ -1412,6 +1505,8 @@ public sealed partial class RynthAiPlugin
|
|||
|
||||
_processedCorpseItems.Add(_currentLootItemId);
|
||||
LootDiag($"[RynthAi] Corpse loot: pickup confirmed for 0x{(uint)_currentLootItemId:X8}; {reason}.");
|
||||
if (_openedContainerId != 0 && _openedContainerId == _ownRecoveryCorpseId)
|
||||
NoteOwnCorpseItemRecovered(now);
|
||||
if (!string.IsNullOrWhiteSpace(_currentLootItemName))
|
||||
ChatLine($"[RynthAi] Looted [{_currentLootItemActionLabel}] {_currentLootItemName}");
|
||||
|
||||
|
|
@ -1462,7 +1557,8 @@ public sealed partial class RynthAiPlugin
|
|||
}
|
||||
|
||||
// No room anywhere: don't start on another corpse (IsPackFull says so once in chat).
|
||||
if (IsLootingBlockedByPack(settings))
|
||||
// Your own corpse is let through unless no pack has a slot at all.
|
||||
if (IsLootingBlockedByPack(settings) && !OwnCorpseBypassesPackGate(settings, GetCorpseApproachRangeMaxMeters(settings)))
|
||||
return false;
|
||||
|
||||
// Loot grace: combat just ended and the corpse CreateObject has not
|
||||
|
|
@ -1542,6 +1638,10 @@ public sealed partial class RynthAiPlugin
|
|||
if (now - _corpseWaitingSince[candidate.Id] >= LootStarveMs)
|
||||
_lootStarved = true;
|
||||
}
|
||||
else if (dist != double.MaxValue && decision.IsOwnDeathCorpse && _corpseSkipLogged.Add(candidate.Id))
|
||||
{
|
||||
LootDiag($"[RynthAi] Own corpse: 0x{(uint)candidate.Id:X8} '{candidate.Name}' is out of loot range (d={dist:0.0}m > {maxMeters:0.0}m); it is recovered once it is within range.");
|
||||
}
|
||||
else if (dist != double.MaxValue && IsOwnKill(decision) && _corpseSkipLogged.Add(candidate.Id))
|
||||
{
|
||||
LootDiag($"[RynthAi] Corpse loot: own corpse 0x{(uint)candidate.Id:X8} '{candidate.Name}' is out of loot range (d={dist:0.0}m > {maxMeters:0.0}m); not walking back for it.");
|
||||
|
|
@ -1603,22 +1703,37 @@ public sealed partial class RynthAiPlugin
|
|||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pure classification — evaluates an item against the active loot profile
|
||||
/// without performing any pickup or side effects. Returns true if the item
|
||||
/// matched a loot/salvage rule.
|
||||
/// Classification: evaluates an item against the active loot profile and RynthAi's
|
||||
/// built-in keeps without performing any pickup. Returns true if the item is to be
|
||||
/// taken; actionLabel/ruleLabel are what [LootEval] logs. The looter's calls record
|
||||
/// what they approve (pending sets, counters, chat); ClassifyLootItem has the preview.
|
||||
/// </summary>
|
||||
private bool ClassifyItemAgainstProfile(WorldObject item, LegacyUiSettings settings, out string actionLabel, out bool isSalvage, out string ruleLabel)
|
||||
private bool ClassifyItemAgainstProfile(WorldObject item, LegacyUiSettings settings, out string actionLabel, out bool isSalvage, out string ruleLabel) =>
|
||||
ClassifyLootItem(item, settings, preview: false, out actionLabel, out isSalvage, out ruleLabel, out _);
|
||||
|
||||
/// <summary>
|
||||
/// The one place the looter decides, with <paramref name="preview"/>: the same verdict
|
||||
/// with nothing recorded, counted, logged or said in chat (the "Add to loot profile"
|
||||
/// popup asking why an item is taken). <paramref name="builtIn"/> is set when one of
|
||||
/// RynthAi's built-in keeps took the item rather than a loot profile rule: Learn unknown
|
||||
/// spells and mana stones (checked before the profile), Mana Tap (when no rule matches).
|
||||
/// It says what and where to change it, in plain ASCII (the popup's font).
|
||||
/// </summary>
|
||||
private bool ClassifyLootItem(WorldObject item, LegacyUiSettings settings, bool preview,
|
||||
out string actionLabel, out bool isSalvage, out string ruleLabel, out string builtIn)
|
||||
{
|
||||
actionLabel = string.Empty;
|
||||
isSalvage = false;
|
||||
ruleLabel = string.Empty;
|
||||
builtIn = string.Empty;
|
||||
|
||||
// Learn unknown spells (VTank ReadUnknownScrolls): a built-in rule ahead of the loot
|
||||
// profile, as in VTank. A scroll of a spell we don't know and can learn is looted to read.
|
||||
if (_scrollLearner != null && _scrollLearner.ShouldLootFromCorpse(item, out string learnRule))
|
||||
if (_scrollLearner != null && _scrollLearner.ShouldLootFromCorpse(item, out string learnRule, out string learnWhy, preview))
|
||||
{
|
||||
actionLabel = ScrollLearner.ReadAction;
|
||||
ruleLabel = learnRule;
|
||||
builtIn = $"Learn unknown spells ({learnWhy}) - change in Settings > Looting, Learn Unknown Spells";
|
||||
return true;
|
||||
}
|
||||
|
||||
|
|
@ -1663,15 +1778,17 @@ public sealed partial class RynthAiPlugin
|
|||
int haveCount = liveCount + pendingNotYetCounted;
|
||||
|
||||
// One-time-per-corpse log so we can see what the count was based on.
|
||||
if (_pendingManaStoneIds.Count == 0)
|
||||
if (!preview && _pendingManaStoneIds.Count == 0)
|
||||
Host.Log($"[RynthAi] ManaStone count for cap check: live={liveCount} pending={pendingNotYetCounted} cap={settings.ManaStoneKeepCount} (cache_known={_objectCache?.AllKnownObjects().Count() ?? 0})");
|
||||
|
||||
// If this specific stone is already approved, return the same answer
|
||||
// we returned last time (no further log spam, no count change).
|
||||
string stoneWhy = $"a mana stone, {haveCount} of {settings.ManaStoneKeepCount} kept - change in the Items panel, Mana Stone Tapping (Keep count)";
|
||||
if (_pendingManaStoneIds.Contains(item.Id))
|
||||
{
|
||||
actionLabel = "Keep";
|
||||
ruleLabel = $"ManaStone (Consumable, {haveCount + 1}/{settings.ManaStoneKeepCount})";
|
||||
builtIn = stoneWhy;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
|
@ -1679,39 +1796,42 @@ public sealed partial class RynthAiPlugin
|
|||
{
|
||||
actionLabel = "Keep";
|
||||
ruleLabel = $"ManaStone (Consumable, {haveCount + 1}/{settings.ManaStoneKeepCount})";
|
||||
builtIn = stoneWhy;
|
||||
if (preview) return true;
|
||||
ChatLine($"[RynthAi] Mana stone match: '{item.Name}' (have {haveCount}/{settings.ManaStoneKeepCount}, +1) — looting.");
|
||||
_pendingManaStoneIds.Add(item.Id);
|
||||
return true;
|
||||
}
|
||||
|
||||
ChatLine($"[RynthAi] Mana stone match: '{item.Name}' (have {haveCount}/{settings.ManaStoneKeepCount}) — at cap, leaving.");
|
||||
if (!preview)
|
||||
ChatLine($"[RynthAi] Mana stone match: '{item.Name}' (have {haveCount}/{settings.ManaStoneKeepCount}) — at cap, leaving.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (TryLoadNativeLootProfile(out LootProfile nativeProfile, out _))
|
||||
{
|
||||
_corpseItemsEvaluated++;
|
||||
if (!preview) _corpseItemsEvaluated++;
|
||||
var (nativeAction, nativeRule) = LootEvaluator.Classify(nativeProfile, item, _charSkills);
|
||||
if (nativeRule == null)
|
||||
{
|
||||
if (TryClassifyAsManaTap(item, settings, out actionLabel, out ruleLabel))
|
||||
if (TryClassifyAsManaTap(item, settings, preview, out actionLabel, out ruleLabel, out builtIn))
|
||||
{
|
||||
_corpseItemsMatched++;
|
||||
if (!preview) _corpseItemsMatched++;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
ruleLabel = string.IsNullOrWhiteSpace(nativeRule.Name) ? "rule" : nativeRule.Name.Trim();
|
||||
if (nativeAction == LootAction.Read && IsReadOfNonScroll(item, ruleLabel))
|
||||
if (nativeAction == LootAction.Read && IsReadOfNonScroll(item, ruleLabel, preview))
|
||||
return false;
|
||||
if (nativeAction == LootAction.KeepUpTo)
|
||||
{
|
||||
var rule = nativeRule;
|
||||
if (!UnderKeepCap("n:" + ruleLabel, ruleLabel, item, rule.KeepCount,
|
||||
inv => LootEvaluator.Matches(rule, inv, _charSkills)))
|
||||
inv => LootEvaluator.Matches(rule, inv, _charSkills), preview))
|
||||
return false;
|
||||
}
|
||||
_corpseItemsMatched++;
|
||||
if (!preview) _corpseItemsMatched++;
|
||||
actionLabel = nativeAction.ToString();
|
||||
isSalvage = nativeAction == LootAction.Salvage;
|
||||
return true;
|
||||
|
|
@ -1721,15 +1841,15 @@ public sealed partial class RynthAiPlugin
|
|||
if (!TryLoadLootProfile(string.Empty, out VTankLootProfile vtankProfile, out _))
|
||||
return false;
|
||||
|
||||
_corpseItemsEvaluated++;
|
||||
if (!preview) _corpseItemsEvaluated++;
|
||||
VTankLootContext lootCtx = new(Host, _playerId) { Cache = _objectCache };
|
||||
VTankLootRule? matchedRule = VTankLootEvaluator.FirstMatch(vtankProfile, item, lootCtx, out int matchedRuleIndex);
|
||||
|
||||
if (matchedRule == null)
|
||||
{
|
||||
if (TryClassifyAsManaTap(item, settings, out actionLabel, out ruleLabel))
|
||||
if (TryClassifyAsManaTap(item, settings, preview, out actionLabel, out ruleLabel, out builtIn))
|
||||
{
|
||||
_corpseItemsMatched++;
|
||||
if (!preview) _corpseItemsMatched++;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
|
|
@ -1738,16 +1858,16 @@ public sealed partial class RynthAiPlugin
|
|||
ruleLabel = string.IsNullOrWhiteSpace(matchedRule.Name)
|
||||
? $"#{matchedRuleIndex}"
|
||||
: matchedRule.Name.Trim();
|
||||
if (matchedRule.Action == VTankLootAction.Read && IsReadOfNonScroll(item, ruleLabel))
|
||||
if (matchedRule.Action == VTankLootAction.Read && IsReadOfNonScroll(item, ruleLabel, preview))
|
||||
return false;
|
||||
if (matchedRule.Action == VTankLootAction.KeepUpTo)
|
||||
{
|
||||
var rule = matchedRule;
|
||||
if (!UnderKeepCap("v:" + matchedRuleIndex + ":" + ruleLabel, ruleLabel, item, rule.KeepCount ?? 0,
|
||||
inv => VTankLootEvaluator.Match(rule, inv, lootCtx)))
|
||||
inv => VTankLootEvaluator.Match(rule, inv, lootCtx), preview))
|
||||
return false;
|
||||
}
|
||||
_corpseItemsMatched++;
|
||||
if (!preview) _corpseItemsMatched++;
|
||||
actionLabel = matchedRule.Action.ToString();
|
||||
isSalvage = matchedRule.Action == VTankLootAction.Salvage;
|
||||
return true;
|
||||
|
|
@ -1760,9 +1880,10 @@ public sealed partial class RynthAiPlugin
|
|||
/// attempted to classify item ... for reading, but that item does not appear to be a
|
||||
/// scroll. Ignoring it." The item is left, with one log line.
|
||||
/// </summary>
|
||||
private bool IsReadOfNonScroll(WorldObject item, string ruleLabel)
|
||||
private bool IsReadOfNonScroll(WorldObject item, string ruleLabel, bool preview = false)
|
||||
{
|
||||
if (ScrollLearner.LooksLikeScroll(item)) return false;
|
||||
if (preview) return true;
|
||||
if (_readNonScrollLogged.Count > 1000) _readNonScrollLogged.Clear();
|
||||
if (_readNonScrollLogged.Add(item.Id))
|
||||
Host.Log($"[Learn] loot rule '{ruleLabel}' says Read, but '{item.Name}' isn't a scroll - leaving it");
|
||||
|
|
@ -1775,10 +1896,13 @@ public sealed partial class RynthAiPlugin
|
|||
/// items already approved on this corpse that haven't reached the pack yet.
|
||||
/// A matching Keep # rule used to loot everything, like a plain Keep.
|
||||
/// </summary>
|
||||
private bool UnderKeepCap(string key, string ruleLabel, WorldObject item, int cap, Func<WorldObject, bool> matches)
|
||||
private bool UnderKeepCap(string key, string ruleLabel, WorldObject item, int cap, Func<WorldObject, bool> matches, bool preview = false)
|
||||
{
|
||||
if (!_pendingKeepUpTo.TryGetValue(key, out var pending))
|
||||
_pendingKeepUpTo[key] = pending = new Dictionary<int, int>();
|
||||
{
|
||||
pending = new Dictionary<int, int>();
|
||||
if (!preview) _pendingKeepUpTo[key] = pending;
|
||||
}
|
||||
if (pending.ContainsKey(item.Id)) return true; // approved on an earlier pass
|
||||
|
||||
// Whole stacks in the pack that the rule matches, plus approved-but-not-in-the-pack-yet
|
||||
|
|
@ -1791,6 +1915,7 @@ public sealed partial class RynthAiPlugin
|
|||
id => _objectCache?[id] != null);
|
||||
|
||||
int stack = LootKeepCap.StackOf(item);
|
||||
if (preview) return LootKeepCap.UnderCap(have, cap);
|
||||
if (!LootKeepCap.UnderCap(have, cap))
|
||||
{
|
||||
ChatLine($"[RynthAi] Keep # '{ruleLabel}': have {have}/{cap} — leaving {item.Name}.");
|
||||
|
|
@ -1859,14 +1984,19 @@ public sealed partial class RynthAiPlugin
|
|||
/// only way an item becomes a tap target: the pickup (label ManaTap) is
|
||||
/// recorded via ManaStoneManager.MarkLootedForTap.
|
||||
/// </summary>
|
||||
private bool TryClassifyAsManaTap(WorldObject item, LegacyUiSettings settings,
|
||||
out string actionLabel, out string ruleLabel)
|
||||
private bool TryClassifyAsManaTap(WorldObject item, LegacyUiSettings settings, bool preview,
|
||||
out string actionLabel, out string ruleLabel, out string builtIn)
|
||||
{
|
||||
actionLabel = string.Empty;
|
||||
ruleLabel = string.Empty;
|
||||
builtIn = string.Empty;
|
||||
|
||||
if (_manaStoneManager == null) return false;
|
||||
if (!Host.HasGetObjectIntProperty) return false;
|
||||
// ACE won't drain a wand, staff or orb into a stone, so ManaStoneManager never taps
|
||||
// one (and its pending-drain count skips them, so the quota never filled): every
|
||||
// high-mana wand was looted and kept for good. Drakkon's "Piercing Sceptre", 2026-10-05.
|
||||
if (ManaStoneManager.IsWandLike(item)) return false;
|
||||
|
||||
int threshold = settings.ManaTapMinMana;
|
||||
if (threshold <= 0) return false;
|
||||
|
|
@ -1876,12 +2006,17 @@ public sealed partial class RynthAiPlugin
|
|||
return false;
|
||||
if (curMana < threshold) return false;
|
||||
|
||||
string tapWhy = "Mana Tap (" + curMana.ToString("N0", CultureInfo.InvariantCulture) + " mana >= "
|
||||
+ threshold.ToString("N0", CultureInfo.InvariantCulture)
|
||||
+ "), looted to drain into an empty mana stone - change in the Items panel, Mana Stone Tapping";
|
||||
|
||||
// Already approved this session — return same answer without re-logging
|
||||
// or re-counting against the quota.
|
||||
if (_pendingManaTapIds.Contains(item.Id))
|
||||
{
|
||||
actionLabel = ManaTapActionLabel;
|
||||
ruleLabel = $"ManaTap (mana={curMana} ≥ {threshold})";
|
||||
builtIn = tapWhy;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
|
@ -1893,6 +2028,8 @@ public sealed partial class RynthAiPlugin
|
|||
|
||||
actionLabel = ManaTapActionLabel;
|
||||
ruleLabel = $"ManaTap (mana={curMana} ≥ {threshold})";
|
||||
builtIn = tapWhy;
|
||||
if (preview) return true;
|
||||
ChatLine($"[RynthAi] Mana tap candidate: '{item.Name}' (mana {curMana}, slot {_pendingManaTapIds.Count + 1}) — looting to drain.");
|
||||
_pendingManaTapIds.Add(item.Id);
|
||||
return true;
|
||||
|
|
@ -2090,13 +2227,13 @@ public sealed partial class RynthAiPlugin
|
|||
ClearCorpseTurnMotions();
|
||||
if (!_navigationEngine.ServoToward(desiredDeg))
|
||||
{
|
||||
if (_corpseAutorunActive) { Host.SetAutoRun(false); _corpseAutorunActive = false; }
|
||||
if (_corpseAutorunActive) { Host.SetAutoRunBy("Loot", false); _corpseAutorunActive = false; }
|
||||
return;
|
||||
}
|
||||
long nowMs = CorpseNowMs;
|
||||
if (!_corpseAutorunActive || nowMs - _lastCorpseApproachHeartbeatAt >= 500)
|
||||
{
|
||||
Host.SetAutoRun(true);
|
||||
Host.SetAutoRunBy("Loot", true);
|
||||
_corpseAutorunActive = true;
|
||||
_lastCorpseApproachHeartbeatAt = nowMs;
|
||||
}
|
||||
|
|
@ -2110,13 +2247,13 @@ public sealed partial class RynthAiPlugin
|
|||
// Use smooth motion turns, same as NavigationEngine/CombatManager
|
||||
if (signedError > 0)
|
||||
{
|
||||
Host.SetMotion(MotionTurnRight, true);
|
||||
Host.SetMotion(MotionTurnLeft, false);
|
||||
Host.SetMotionBy("Loot", MotionTurnRight, true);
|
||||
Host.SetMotionBy("Loot", MotionTurnLeft, false);
|
||||
}
|
||||
else
|
||||
{
|
||||
Host.SetMotion(MotionTurnLeft, true);
|
||||
Host.SetMotion(MotionTurnRight, false);
|
||||
Host.SetMotionBy("Loot", MotionTurnLeft, true);
|
||||
Host.SetMotionBy("Loot", MotionTurnRight, false);
|
||||
}
|
||||
_corpseApproachTurnsActive = true;
|
||||
return;
|
||||
|
|
@ -2127,7 +2264,7 @@ public sealed partial class RynthAiPlugin
|
|||
long now = CorpseNowMs;
|
||||
if (!_corpseAutorunActive || now - _lastCorpseApproachHeartbeatAt >= 500)
|
||||
{
|
||||
Host.SetAutoRun(true);
|
||||
Host.SetAutoRunBy("Loot", true);
|
||||
_corpseAutorunActive = true;
|
||||
_lastCorpseApproachHeartbeatAt = now;
|
||||
}
|
||||
|
|
@ -2138,8 +2275,8 @@ public sealed partial class RynthAiPlugin
|
|||
if (!_corpseApproachTurnsActive)
|
||||
return;
|
||||
_corpseApproachTurnsActive = false;
|
||||
Host.SetMotion(MotionTurnRight, false);
|
||||
Host.SetMotion(MotionTurnLeft, false);
|
||||
Host.SetMotionBy("Loot", MotionTurnRight, false);
|
||||
Host.SetMotionBy("Loot", MotionTurnLeft, false);
|
||||
}
|
||||
|
||||
private void StopCorpseMovement()
|
||||
|
|
@ -2149,9 +2286,9 @@ public sealed partial class RynthAiPlugin
|
|||
if (!_corpseAutorunActive)
|
||||
return;
|
||||
|
||||
Host.SetAutoRun(false);
|
||||
Host.SetAutoRunBy("Loot", false);
|
||||
if (Host.HasStopCompletely)
|
||||
Host.StopCompletely();
|
||||
Host.StopCompletelyBy("Loot");
|
||||
|
||||
_corpseAutorunActive = false;
|
||||
}
|
||||
|
|
@ -2457,7 +2594,21 @@ public sealed partial class RynthAiPlugin
|
|||
bool openWasSent = wasOpened || _lastOpenAttemptCorpseId == corpseId;
|
||||
int abandons =_corpseAbandonCounts.TryGetValue(corpseId, out int n) ? n + 1 : 1;
|
||||
_corpseAbandonCounts[corpseId] = abandons;
|
||||
if (wasOpened || abandons >= 3)
|
||||
// Your own corpse is never written off after one timeout: it gets OwnCorpseMaxAbandons tries.
|
||||
bool ownCorpse = IsOwnDeathCorpseId(_dashboard?.Settings, corpseId);
|
||||
if (ownCorpse && abandons < OwnCorpseMaxAbandons)
|
||||
{
|
||||
_corpseCooldownUntil[corpseId] = now + NeverOpenedAbandonRetryMs;
|
||||
LootDiag($"[RynthAi] Own corpse: 0x{(uint)corpseId:X8} timed out (try {abandons} of {OwnCorpseMaxAbandons}); trying again in {NeverOpenedAbandonRetryMs / 1000}s.");
|
||||
}
|
||||
else if (ownCorpse)
|
||||
{
|
||||
_completedCorpses[corpseId] = now;
|
||||
_corpseCooldownUntil.Remove(corpseId);
|
||||
_corpseAbandonCounts.Remove(corpseId);
|
||||
ChatLine($"[RynthAi] Own corpse: giving up after {abandons} tries; recover what is left on it by hand.");
|
||||
}
|
||||
else if (wasOpened || abandons >= 3)
|
||||
{
|
||||
_completedCorpses[corpseId] = now;
|
||||
_corpseCooldownUntil.Remove(corpseId);
|
||||
|
|
@ -2509,7 +2660,7 @@ public sealed partial class RynthAiPlugin
|
|||
|
||||
if (Host.HasCancelAttack) Host.CancelAttack();
|
||||
if (Host.HasChangeCombatMode) Host.ChangeCombatMode(CombatMode.NonCombat);
|
||||
if (Host.HasStopCompletely) Host.StopCompletely();
|
||||
if (Host.HasStopCompletely) Host.StopCompletelyBy("Loot/Wedge");
|
||||
if (Host.HasForceResetBusyCount) Host.ForceResetBusyCount();
|
||||
// The lock is client-side: AC's pending-item-request slot or attacking
|
||||
// flag (see the engine's ClientActionGates). Open both now.
|
||||
|
|
|
|||
|
|
@ -91,6 +91,22 @@ internal static class CreatureWeakness
|
|||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The creature type the world-database table gives this monster (0 = not in it). Same match
|
||||
/// as <see cref="Rank"/>: the wcid's row when its name agrees (or no name is given); no wcid,
|
||||
/// the first row of that name. Never guessed from name keywords.
|
||||
/// </summary>
|
||||
public static int TableCreatureType(uint wcid, string? name)
|
||||
{
|
||||
EnsureLoaded();
|
||||
name ??= "";
|
||||
if (wcid == 0 && name.Length > 0 && ByName.TryGetValue(name, out uint byName)) wcid = byName;
|
||||
if (wcid != 0 && ByWcid.TryGetValue(wcid, out var row)
|
||||
&& (name.Length == 0 || row.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
|
||||
return row.Type > 0 ? row.Type : 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// <summary>Damage multiplier for one element from the server table or the type average; false when unknown.</summary>
|
||||
public static bool TryGetMultiplier(uint wcid, string? name, int creatureType, string element, out double mult)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -104,7 +104,7 @@ public sealed partial class RynthAiPlugin
|
|||
_doorActionAt = now;
|
||||
|
||||
_navigationEngine?.Stop();
|
||||
if (Host.HasStopCompletely) Host.StopCompletely();
|
||||
if (Host.HasStopCompletely) Host.StopCompletelyBy("Door");
|
||||
_doorPausedNav = true;
|
||||
|
||||
Host.UseFor(unchecked((uint)doorId), "Door",
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
using System;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.Plugin.Shared;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
|
|
@ -87,7 +88,7 @@ internal sealed class Jumper
|
|||
{
|
||||
_turningStartedAt = DateTime.UtcNow;
|
||||
if (_host.HasTurnToHeading)
|
||||
_host.TurnToHeading(_targetHeading);
|
||||
_host.TurnToHeadingBy("Jump", _targetHeading);
|
||||
_host.Log($"[Jumper] Start turn->{_targetHeading:F0} letters='{directionLetters}' hold={_msToHoldDown}ms");
|
||||
}
|
||||
else
|
||||
|
|
|
|||
|
|
@ -17,6 +17,7 @@ namespace RynthCore.Plugin.RynthAi.LegacyUi;
|
|||
/// CellType: Flat, SlopeUp (avg vertex Z above the layer), SlopeDown (below).
|
||||
/// This was also RynthAi's plugin-drawn Dungeon Map window (with baked D3D9 floor
|
||||
/// textures); that window is the engine's DungeonMapFace now, so nothing here draws.
|
||||
/// The floor grids are also baked to disk (Maps/DungeonMapBake) for DrakRemote's /map.
|
||||
/// </summary>
|
||||
internal sealed class DungeonMapUi
|
||||
{
|
||||
|
|
@ -45,6 +46,31 @@ internal sealed class DungeonMapUi
|
|||
|
||||
internal int BestLayerIdxFor(float playerZ) => BestLayerIdx(playerZ);
|
||||
|
||||
// Last indoor landblock TickBake handed to the bake (0 = none yet).
|
||||
private uint _bakeCheckLandblock;
|
||||
|
||||
/// <summary>
|
||||
/// Game-thread tick (throttled by the caller): when the player is indoors in a landblock not
|
||||
/// seen yet, bake its floor plans to disk for the StatusAgent's /map, whether or not a Radar
|
||||
/// or Dungeon Map panel is open (only those build this cache). One pose read here; the dat
|
||||
/// read, rasterise and disk work run on a pool thread, once per landblock per session.
|
||||
/// Also logs what the background bakes reported.
|
||||
/// </summary>
|
||||
internal void TickBake(RynthCoreHost host)
|
||||
{
|
||||
Maps.DungeonMapBake.DrainLog(host.Log);
|
||||
if (!host.HasGetPlayerPose
|
||||
|| !host.TryGetPlayerPose(out uint cellId, out _, out _, out _, out _, out _, out _, out _))
|
||||
return;
|
||||
uint landblock = cellId >> 16;
|
||||
bool isIndoor = (cellId & 0xFFFF) >= 0x100 && landblock != 0;
|
||||
if (!isIndoor || landblock == _bakeCheckLandblock) return;
|
||||
var los = _raycast?.GeometryLoader?.DungeonLOS;
|
||||
if (los is null) return; // dats still loading; try again next tick
|
||||
_bakeCheckLandblock = landblock;
|
||||
Maps.DungeonMapBake.RequestFromDat(los, landblock);
|
||||
}
|
||||
|
||||
private const float GridCell = 0.5f;
|
||||
private const float FloorNormalThreshold = 0.4f; // |Nz|/|N| — must exceed to be floor-like
|
||||
private const float FlatNormalThreshold = 0.95f; // |Nz|/|N| — must exceed to be flat (not a ramp)
|
||||
|
|
@ -77,115 +103,14 @@ internal sealed class DungeonMapUi
|
|||
var portalPolys = los.GetDungeonMapPolygons(landblock);
|
||||
if (floorPolys.Count == 0 && portalPolys.Count == 0) return;
|
||||
|
||||
var zSet = new SortedSet<float>();
|
||||
foreach (var p in floorPolys) zSet.Add((float)Math.Round(p.CellZ, 1));
|
||||
foreach (var p in portalPolys) zSet.Add((float)Math.Round(p.CellZ, 1));
|
||||
_zLayers = new List<float>(zSet);
|
||||
_zLayers = LayerZs(floorPolys, portalPolys);
|
||||
|
||||
_outerEdges = new Dictionary<float, List<(float, float, float, float, CellType)>>(_zLayers.Count);
|
||||
_fillStrips = new Dictionary<float, List<(float, float, float, float, CellType)>>(_zLayers.Count);
|
||||
|
||||
const float LayerTol = 1.0f;
|
||||
|
||||
foreach (float layerZ in _zLayers)
|
||||
{
|
||||
var filled = new Dictionary<(int, int), CellType>();
|
||||
|
||||
foreach (var poly in floorPolys)
|
||||
{
|
||||
if (MathF.Abs(poly.CellZ - layerZ) > LayerTol) continue;
|
||||
var verts = poly.Vertices;
|
||||
if (verts == null || verts.Length < 3) continue;
|
||||
|
||||
CellType type = ClassifyPoly(verts, layerZ);
|
||||
if ((byte)type == NotFloor) continue; // physics floor polys are upward-facing; skip any edge cases
|
||||
|
||||
RasterizeXY(verts, filled, type);
|
||||
}
|
||||
|
||||
// ── Portal gap-closing (width-matched bridges) ───────────────
|
||||
// For each pair of portals within 5 units, fill a rectangle
|
||||
// bridge between them. Width = actual doorway opening derived
|
||||
// from the portal polygon's larger XY bounding-box dimension.
|
||||
{
|
||||
var portals = new List<(float cx, float cy, float halfW)>();
|
||||
var pDedup = new HashSet<(int, int)>();
|
||||
foreach (var poly in portalPolys)
|
||||
{
|
||||
if (!poly.IsPortal) continue;
|
||||
if (MathF.Abs(poly.CellZ - layerZ) > LayerTol) continue;
|
||||
var verts = poly.Vertices;
|
||||
if (verts == null || verts.Length < 3) continue;
|
||||
float cx = 0, cy = 0;
|
||||
float xMin = verts[0].X, xMax = verts[0].X;
|
||||
float yMin = verts[0].Y, yMax = verts[0].Y;
|
||||
for (int k = 0; k < verts.Length; k++)
|
||||
{
|
||||
cx += verts[k].X; cy += verts[k].Y;
|
||||
if (verts[k].X < xMin) xMin = verts[k].X;
|
||||
if (verts[k].X > xMax) xMax = verts[k].X;
|
||||
if (verts[k].Y < yMin) yMin = verts[k].Y;
|
||||
if (verts[k].Y > yMax) yMax = verts[k].Y;
|
||||
}
|
||||
cx /= verts.Length; cy /= verts.Length;
|
||||
float halfW = MathF.Max(xMax - xMin, yMax - yMin) * 0.5f;
|
||||
halfW = MathF.Max(halfW, 1.0f); // minimum 1 unit wide
|
||||
if (pDedup.Add(((int)MathF.Round(cx), (int)MathF.Round(cy))))
|
||||
portals.Add((cx, cy, halfW));
|
||||
}
|
||||
|
||||
const float ConnectDist = 5f;
|
||||
|
||||
for (int a = 0; a < portals.Count; a++)
|
||||
for (int b = a + 1; b < portals.Count; b++)
|
||||
{
|
||||
float ddx = portals[b].cx - portals[a].cx;
|
||||
float ddy = portals[b].cy - portals[a].cy;
|
||||
float distSq = ddx * ddx + ddy * ddy;
|
||||
if (distSq > ConnectDist * ConnectDist) continue;
|
||||
|
||||
float dist = MathF.Sqrt(distSq);
|
||||
float hw = MathF.Max(portals[a].halfW, portals[b].halfW);
|
||||
|
||||
// Normalised A→B direction, then perpendicular scaled by half-width
|
||||
float normDx = dist > 0.001f ? ddx / dist : 1f;
|
||||
float normDy = dist > 0.001f ? ddy / dist : 0f;
|
||||
float perpX = -normDy * hw;
|
||||
float perpY = normDx * hw;
|
||||
|
||||
float pax = portals[a].cx, pay = portals[a].cy;
|
||||
float pbx = portals[b].cx, pby = portals[b].cy;
|
||||
|
||||
// 4 corners of the bridge quad
|
||||
float c0x = pax - perpX, c0y = pay - perpY;
|
||||
float c1x = pax + perpX, c1y = pay + perpY;
|
||||
float c2x = pbx + perpX, c2y = pby + perpY;
|
||||
float c3x = pbx - perpX, c3y = pby - perpY;
|
||||
|
||||
float bbMinX = MathF.Min(MathF.Min(c0x, c1x), MathF.Min(c2x, c3x));
|
||||
float bbMaxX = MathF.Max(MathF.Max(c0x, c1x), MathF.Max(c2x, c3x));
|
||||
float bbMinY = MathF.Min(MathF.Min(c0y, c1y), MathF.Min(c2y, c3y));
|
||||
float bbMaxY = MathF.Max(MathF.Max(c0y, c1y), MathF.Max(c2y, c3y));
|
||||
|
||||
int gcxMin2 = (int)MathF.Floor(bbMinX / GridCell);
|
||||
int gcxMax2 = (int)MathF.Ceiling(bbMaxX / GridCell);
|
||||
int gcyMin2 = (int)MathF.Floor(bbMinY / GridCell);
|
||||
int gcyMax2 = (int)MathF.Ceiling(bbMaxY / GridCell);
|
||||
|
||||
for (int gcy2 = gcyMin2; gcy2 <= gcyMax2; gcy2++)
|
||||
for (int gcx2 = gcxMin2; gcx2 <= gcxMax2; gcx2++)
|
||||
{
|
||||
float testX = (gcx2 + 0.5f) * GridCell;
|
||||
float testY = (gcy2 + 0.5f) * GridCell;
|
||||
if (PointInConvexQuad(testX, testY,
|
||||
c0x, c0y, c1x, c1y, c2x, c2y, c3x, c3y))
|
||||
{
|
||||
var key = (gcx2, gcy2);
|
||||
if (!filled.ContainsKey(key)) filled[key] = CellType.Flat;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
var filled = RasterizeLayer(floorPolys, portalPolys, layerZ);
|
||||
|
||||
if (filled.Count == 0) continue;
|
||||
|
||||
|
|
@ -266,6 +191,149 @@ internal sealed class DungeonMapUi
|
|||
if (strips.Count > 0) _fillStrips[layerZ] = strips;
|
||||
}
|
||||
|
||||
// Disk floor plans for DrakRemote (StatusAgent /map). Once per landblock, off this
|
||||
// thread; a plan that is already on disk with the same bytes is left alone.
|
||||
Maps.DungeonMapBake.Request(landblock, _zLayers, _floorCells);
|
||||
}
|
||||
|
||||
/// <summary>The floor heights (cell Z rounded to 0.1) of a landblock's polygons, ascending.
|
||||
/// A layer's index in this list is the layer number in the baked map file names.</summary>
|
||||
internal static List<float> LayerZs(List<DungeonLOS.MapPolygon> floorPolys, List<DungeonLOS.MapPolygon> portalPolys)
|
||||
{
|
||||
var zSet = new SortedSet<float>();
|
||||
foreach (var p in floorPolys) zSet.Add((float)Math.Round(p.CellZ, 1));
|
||||
foreach (var p in portalPolys) zSet.Add((float)Math.Round(p.CellZ, 1));
|
||||
return new List<float>(zSet);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The typed floor-cell grid of one layer (GridCell squares): physics floor polygons
|
||||
/// rasterised, plus width-matched bridges between nearby portals. Pure; no state.
|
||||
/// </summary>
|
||||
internal static Dictionary<(int, int), CellType> RasterizeLayer(
|
||||
List<DungeonLOS.MapPolygon> floorPolys, List<DungeonLOS.MapPolygon> portalPolys, float layerZ)
|
||||
{
|
||||
const float LayerTol = 1.0f;
|
||||
var filled = new Dictionary<(int, int), CellType>();
|
||||
|
||||
foreach (var poly in floorPolys)
|
||||
{
|
||||
if (MathF.Abs(poly.CellZ - layerZ) > LayerTol) continue;
|
||||
var verts = poly.Vertices;
|
||||
if (verts == null || verts.Length < 3) continue;
|
||||
|
||||
CellType type = ClassifyPoly(verts, layerZ);
|
||||
if ((byte)type == NotFloor) continue; // physics floor polys are upward-facing; skip any edge cases
|
||||
|
||||
RasterizeXY(verts, filled, type);
|
||||
}
|
||||
|
||||
// ── Portal gap-closing (width-matched bridges) ───────────────
|
||||
// For each pair of portals within 5 units, fill a rectangle
|
||||
// bridge between them. Width = actual doorway opening derived
|
||||
// from the portal polygon's larger XY bounding-box dimension.
|
||||
{
|
||||
var portals = new List<(float cx, float cy, float halfW)>();
|
||||
var pDedup = new HashSet<(int, int)>();
|
||||
foreach (var poly in portalPolys)
|
||||
{
|
||||
if (!poly.IsPortal) continue;
|
||||
if (MathF.Abs(poly.CellZ - layerZ) > LayerTol) continue;
|
||||
var verts = poly.Vertices;
|
||||
if (verts == null || verts.Length < 3) continue;
|
||||
float cx = 0, cy = 0;
|
||||
float xMin = verts[0].X, xMax = verts[0].X;
|
||||
float yMin = verts[0].Y, yMax = verts[0].Y;
|
||||
for (int k = 0; k < verts.Length; k++)
|
||||
{
|
||||
cx += verts[k].X; cy += verts[k].Y;
|
||||
if (verts[k].X < xMin) xMin = verts[k].X;
|
||||
if (verts[k].X > xMax) xMax = verts[k].X;
|
||||
if (verts[k].Y < yMin) yMin = verts[k].Y;
|
||||
if (verts[k].Y > yMax) yMax = verts[k].Y;
|
||||
}
|
||||
cx /= verts.Length; cy /= verts.Length;
|
||||
float halfW = MathF.Max(xMax - xMin, yMax - yMin) * 0.5f;
|
||||
halfW = MathF.Max(halfW, 1.0f); // minimum 1 unit wide
|
||||
if (pDedup.Add(((int)MathF.Round(cx), (int)MathF.Round(cy))))
|
||||
portals.Add((cx, cy, halfW));
|
||||
}
|
||||
|
||||
const float ConnectDist = 5f;
|
||||
|
||||
for (int a = 0; a < portals.Count; a++)
|
||||
for (int b = a + 1; b < portals.Count; b++)
|
||||
{
|
||||
float ddx = portals[b].cx - portals[a].cx;
|
||||
float ddy = portals[b].cy - portals[a].cy;
|
||||
float distSq = ddx * ddx + ddy * ddy;
|
||||
if (distSq > ConnectDist * ConnectDist) continue;
|
||||
|
||||
float dist = MathF.Sqrt(distSq);
|
||||
float hw = MathF.Max(portals[a].halfW, portals[b].halfW);
|
||||
|
||||
// Normalised A→B direction, then perpendicular scaled by half-width
|
||||
float normDx = dist > 0.001f ? ddx / dist : 1f;
|
||||
float normDy = dist > 0.001f ? ddy / dist : 0f;
|
||||
float perpX = -normDy * hw;
|
||||
float perpY = normDx * hw;
|
||||
|
||||
float pax = portals[a].cx, pay = portals[a].cy;
|
||||
float pbx = portals[b].cx, pby = portals[b].cy;
|
||||
|
||||
// 4 corners of the bridge quad
|
||||
float c0x = pax - perpX, c0y = pay - perpY;
|
||||
float c1x = pax + perpX, c1y = pay + perpY;
|
||||
float c2x = pbx + perpX, c2y = pby + perpY;
|
||||
float c3x = pbx - perpX, c3y = pby - perpY;
|
||||
|
||||
float bbMinX = MathF.Min(MathF.Min(c0x, c1x), MathF.Min(c2x, c3x));
|
||||
float bbMaxX = MathF.Max(MathF.Max(c0x, c1x), MathF.Max(c2x, c3x));
|
||||
float bbMinY = MathF.Min(MathF.Min(c0y, c1y), MathF.Min(c2y, c3y));
|
||||
float bbMaxY = MathF.Max(MathF.Max(c0y, c1y), MathF.Max(c2y, c3y));
|
||||
|
||||
int gcxMin2 = (int)MathF.Floor(bbMinX / GridCell);
|
||||
int gcxMax2 = (int)MathF.Ceiling(bbMaxX / GridCell);
|
||||
int gcyMin2 = (int)MathF.Floor(bbMinY / GridCell);
|
||||
int gcyMax2 = (int)MathF.Ceiling(bbMaxY / GridCell);
|
||||
|
||||
for (int gcy2 = gcyMin2; gcy2 <= gcyMax2; gcy2++)
|
||||
for (int gcx2 = gcxMin2; gcx2 <= gcxMax2; gcx2++)
|
||||
{
|
||||
float testX = (gcx2 + 0.5f) * GridCell;
|
||||
float testY = (gcy2 + 0.5f) * GridCell;
|
||||
if (PointInConvexQuad(testX, testY,
|
||||
c0x, c0y, c1x, c1y, c2x, c2y, c3x, c3y))
|
||||
{
|
||||
var key = (gcx2, gcy2);
|
||||
if (!filled.ContainsKey(key)) filled[key] = CellType.Flat;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return filled;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The layer heights and per-layer floor grids of a landblock, the same ones RefreshMap
|
||||
/// builds, without touching this instance's cache. Used by the background map bake. Layers
|
||||
/// with no cells are left out of the dictionary (but keep their index in the list).
|
||||
/// </summary>
|
||||
internal static (List<float> ZLayers, Dictionary<float, Dictionary<(int, int), CellType>> Cells) BuildFloorCells(
|
||||
DungeonLOS los, uint landblock)
|
||||
{
|
||||
var floorPolys = los.GetDungeonMapFloorPolygons(landblock);
|
||||
var portalPolys = los.GetDungeonMapPolygons(landblock);
|
||||
var cells = new Dictionary<float, Dictionary<(int, int), CellType>>();
|
||||
if (floorPolys.Count == 0 && portalPolys.Count == 0) return (new List<float>(), cells);
|
||||
var zLayers = LayerZs(floorPolys, portalPolys);
|
||||
foreach (float layerZ in zLayers)
|
||||
{
|
||||
var filled = RasterizeLayer(floorPolys, portalPolys, layerZ);
|
||||
if (filled.Count > 0) cells[layerZ] = filled;
|
||||
}
|
||||
return (zLayers, cells);
|
||||
}
|
||||
|
||||
// Merge collinear/adjacent axis-aligned edge segments into the fewest possible lines.
|
||||
|
|
|
|||
|
|
@ -711,6 +711,13 @@ internal sealed class LegacyAdvancedSettingsUi
|
|||
"alone. Default 1200 (20 minutes). At or below 'Rebuff With', only the\n" +
|
||||
"expiring buff is recast.");
|
||||
|
||||
ImGui.Checkbox("Cast buffs even when an item gives them", ref _settings.CastBuffsOverItemBuffs);
|
||||
if (ImGui.IsItemHovered())
|
||||
ImGui.SetTooltip(
|
||||
"Cast your own buff even when worn gear already gives that buff.\n" +
|
||||
"For servers with buff augments, where your own cast is stronger or\n" +
|
||||
"lasts longer. On by default: on retail it costs a few extra casts.");
|
||||
|
||||
ImGui.Spacing();
|
||||
ImGui.Separator();
|
||||
ImGui.Text("Buff Difficulty (Min Buffed Skill)");
|
||||
|
|
@ -757,6 +764,12 @@ internal sealed class LegacyAdvancedSettingsUi
|
|||
ImGui.Text("Corpse Ownership");
|
||||
ImGui.SetNextItemWidth(180);
|
||||
ImGui.Combo("Loot From", ref _settings.LootOwnership, LootOwnershipModes, LootOwnershipModes.Length);
|
||||
ImGui.Checkbox("Recover My Corpse", ref _settings.LootOwnCorpse);
|
||||
if (ImGui.IsItemHovered())
|
||||
ImGui.SetTooltip("When your own corpse (\"Corpse of <you>\") is within loot range, open it and take\nevery item on it, whatever the loot profile and Loot From say.");
|
||||
ImGui.Checkbox("Travel Back To My Corpse", ref _settings.TravelToOwnCorpse);
|
||||
if (ImGui.IsItemHovered())
|
||||
ImGui.SetTooltip("After a death, travel back to where you died with RynthNav (outdoors only),\nfighting on the way, recover the corpse, then carry on. Needs the macro running.");
|
||||
|
||||
ImGui.Spacing();
|
||||
ImGui.Text("Inventory Management");
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ using System.Text.Json;
|
|||
using RynthCore.PluginSdk;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.Meta;
|
||||
using RynthCore.Plugin.Shared;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
|
||||
|
|
@ -294,6 +295,10 @@ internal sealed class LegacyDashboardRenderer
|
|||
_dungeonMapUi.SetRaycast(raycast);
|
||||
}
|
||||
|
||||
/// <summary>Bake the floor plans of a dungeon just entered, with no map panel open
|
||||
/// (DrakRemote's /map). Cheap: one pose read; the work runs on a pool thread.</summary>
|
||||
public void TickDungeonMapBake() => _dungeonMapUi?.TickBake(_host); // null in tests' bare dashboards
|
||||
|
||||
public void PushChatLine(string? text, int chatType) => _rynthChatUi.Push(text, chatType);
|
||||
|
||||
/// <summary>Set the handler invoked when the user submits a line from the
|
||||
|
|
@ -1028,6 +1033,7 @@ internal sealed class LegacyDashboardRenderer
|
|||
RebuffWhenIdle = s.RebuffWhenIdle,
|
||||
RebuffSecondsRemaining = s.RebuffSecondsRemaining,
|
||||
RebuffTopOffSecondsRemaining = s.RebuffTopOffSecondsRemaining,
|
||||
CastBuffsOverItemBuffs = s.CastBuffsOverItemBuffs,
|
||||
BuffMinSkillLevelTier1 = s.BuffMinSkillLevelTier1,
|
||||
BuffMinSkillLevelTier2 = s.BuffMinSkillLevelTier2,
|
||||
BuffMinSkillLevelTier3 = s.BuffMinSkillLevelTier3,
|
||||
|
|
@ -1048,6 +1054,8 @@ internal sealed class LegacyDashboardRenderer
|
|||
LootJumpEnabled = s.LootJumpEnabled,
|
||||
LootJumpHeight = s.LootJumpHeight,
|
||||
LootOwnership = s.LootOwnership,
|
||||
LootOwnCorpse = s.LootOwnCorpse,
|
||||
TravelToOwnCorpse = s.TravelToOwnCorpse,
|
||||
EnableAutostack = s.EnableAutostack,
|
||||
ReadUnknownScrolls = s.ReadUnknownScrolls,
|
||||
EnableCombineSalvage = s.EnableCombineSalvage,
|
||||
|
|
@ -1228,6 +1236,7 @@ internal sealed class LegacyDashboardRenderer
|
|||
s.RebuffWhenIdle = p.RebuffWhenIdle;
|
||||
s.RebuffSecondsRemaining = p.RebuffSecondsRemaining;
|
||||
if (p.RebuffTopOffSecondsRemaining > 0) s.RebuffTopOffSecondsRemaining = p.RebuffTopOffSecondsRemaining;
|
||||
if (p.CastBuffsOverItemBuffs is bool castOverItems) s.CastBuffsOverItemBuffs = castOverItems; // absent = unchanged
|
||||
s.BuffMinSkillLevelTier1 = p.BuffMinSkillLevelTier1;
|
||||
s.BuffMinSkillLevelTier2 = p.BuffMinSkillLevelTier2;
|
||||
s.BuffMinSkillLevelTier3 = p.BuffMinSkillLevelTier3;
|
||||
|
|
@ -1245,6 +1254,8 @@ internal sealed class LegacyDashboardRenderer
|
|||
s.LootJumpEnabled = p.LootJumpEnabled;
|
||||
s.LootJumpHeight = p.LootJumpHeight;
|
||||
s.LootOwnership = p.LootOwnership;
|
||||
if (p.LootOwnCorpse is bool lootOwn) s.LootOwnCorpse = lootOwn; // absent = unchanged
|
||||
if (p.TravelToOwnCorpse is bool travelOwn) s.TravelToOwnCorpse = travelOwn; // absent = unchanged
|
||||
s.EnableAutostack = p.EnableAutostack;
|
||||
s.ReadUnknownScrolls = p.ReadUnknownScrolls;
|
||||
s.EnableCombineSalvage = p.EnableCombineSalvage;
|
||||
|
|
@ -1644,11 +1655,14 @@ internal sealed class LegacyDashboardRenderer
|
|||
dst.OpenDoorRange = tmp.OpenDoorRange;
|
||||
dst.AutoUnlockDoors = tmp.AutoUnlockDoors;
|
||||
dst.LootOwnership = tmp.LootOwnership;
|
||||
dst.LootOwnCorpse = tmp.LootOwnCorpse;
|
||||
dst.TravelToOwnCorpse = tmp.TravelToOwnCorpse;
|
||||
dst.LootOnlyRareCorpses = tmp.LootOnlyRareCorpses;
|
||||
dst.PeaceModeWhenIdle = tmp.PeaceModeWhenIdle;
|
||||
dst.RebuffWhenIdle = tmp.RebuffWhenIdle;
|
||||
dst.RebuffSecondsRemaining = tmp.RebuffSecondsRemaining;
|
||||
dst.RebuffTopOffSecondsRemaining = tmp.RebuffTopOffSecondsRemaining;
|
||||
dst.CastBuffsOverItemBuffs = tmp.CastBuffsOverItemBuffs;
|
||||
dst.BlacklistAttempts = tmp.BlacklistAttempts;
|
||||
dst.BlacklistTimeoutSec = tmp.BlacklistTimeoutSec;
|
||||
// 0 is never meant (every UI floors it at 250+) and is what the Settings-panel bug
|
||||
|
|
@ -2316,8 +2330,8 @@ internal sealed class LegacyDashboardRenderer
|
|||
break;
|
||||
|
||||
case "addWaypoint":
|
||||
_host.SetMotion(0x6500000D, false); // stop TurnRight
|
||||
_host.SetMotion(0x6500000E, false); // stop TurnLeft
|
||||
_host.SetMotionBy("UI", 0x6500000D, false); // stop TurnRight
|
||||
_host.SetMotionBy("UI", 0x6500000E, false); // stop TurnLeft
|
||||
if (_host.HasGetPlayerPose &&
|
||||
_host.TryGetPlayerPose(out _, out float wx, out float wy, out float wz, out _, out _, out _, out _) &&
|
||||
NavCoordinateHelper.TryGetNavCoords(_host, out double wNS, out double wEW))
|
||||
|
|
@ -2441,7 +2455,11 @@ internal sealed class LegacyDashboardRenderer
|
|||
sb.Append('{');
|
||||
AppendBool(sb, "macroRunning", _settings.IsMacroRunning); sb.Append(',');
|
||||
AppendString(sb, "currentState", _settings.CurrentState ?? string.Empty); sb.Append(',');
|
||||
AppendString(sb, "botAction", _settings.BotAction ?? "Default"); sb.Append(',');
|
||||
// "botAction" is what the displays show (the dashboard's activity line, and the phone through
|
||||
// RynthRemote's status file): the control string, except that the Buffing slot says what it
|
||||
// is doing (Healing, Restoring mana, ...). The control string itself is "botActionControl".
|
||||
AppendString(sb, "botAction", ActivityArbiter.DisplayLabel(_settings.BotAction, _settings.BuffingLabel)); sb.Append(',');
|
||||
AppendString(sb, "botActionControl", _settings.BotAction ?? "Default"); sb.Append(',');
|
||||
AppendString(sb, "selectedProfile", _settings.SelectedProfile ?? "Default"); sb.Append(',');
|
||||
// Copy the four profile lists under the lock so we never enumerate one
|
||||
// while a Refresh*Files mutator Clear()s it on the pump thread — that
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ using System.IO;
|
|||
using System.Numerics;
|
||||
using ImGuiNET;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.Plugin.Shared;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
|
||||
|
|
@ -97,8 +98,8 @@ internal sealed class LegacyNavigationUi
|
|||
if (ImGui.Button("Add Waypoint", new Vector2(100, 25)))
|
||||
{
|
||||
// Stop any active turn motion so the character doesn't keep spinning
|
||||
_host.SetMotion(0x6500000D, false); // TurnRight
|
||||
_host.SetMotion(0x6500000E, false); // TurnLeft
|
||||
_host.SetMotionBy("UI", 0x6500000D, false); // TurnRight
|
||||
_host.SetMotionBy("UI", 0x6500000E, false); // TurnLeft
|
||||
|
||||
if (_host.HasGetPlayerPose && _host.TryGetPlayerPose(out _, out float x, out float y, out float z, out _, out _, out _, out _))
|
||||
{
|
||||
|
|
|
|||
|
|
@ -24,6 +24,10 @@ public sealed class LegacyUiSettings
|
|||
/// <summary>Bot action state — what the bot is doing right now (Default, Combat, Looting, Navigating, Buffing).
|
||||
/// Separate from meta state so operational cycling doesn't corrupt meta rule matching.</summary>
|
||||
[JsonIgnore] public string BotAction = "Default";
|
||||
/// <summary>Display only: what the "Buffing" slot is doing (Healing, Restoring mana, Restoring
|
||||
/// stamina, Buffing). Written by RynthAiPlugin every tick; never read by control flow.
|
||||
/// Displays use ActivityArbiter.DisplayLabel, never this field alone.</summary>
|
||||
[JsonIgnore] public string BuffingLabel = "Buffing";
|
||||
[JsonIgnore] public bool IsRecordingNav;
|
||||
|
||||
public bool EnableBuffing = true;
|
||||
|
|
@ -180,6 +184,18 @@ public sealed class LegacyUiSettings
|
|||
public float OpenDoorRange = 5.0f;
|
||||
public bool AutoUnlockDoors;
|
||||
public int LootOwnership;
|
||||
/// <summary>
|
||||
/// Recover your own death corpse ("Corpse of <you>", identified by its "Killed by" line):
|
||||
/// when it is within loot range the bot opens it and takes every item on it, whatever the
|
||||
/// loot profile, Loot From, value or salvage rules say. On by default (owner, 2026-10-05);
|
||||
/// a profile saved before this setting loads it as on.
|
||||
/// </summary>
|
||||
public bool LootOwnCorpse = true;
|
||||
/// <summary>
|
||||
/// After a death and respawn, travel back to where you died (RynthNav, outdoors only), fight
|
||||
/// on the way as usual, recover the corpse, then carry on. Off by default.
|
||||
/// </summary>
|
||||
public bool TravelToOwnCorpse;
|
||||
public bool LootOnlyRareCorpses;
|
||||
public bool PeaceModeWhenIdle = true;
|
||||
public bool RebuffWhenIdle;
|
||||
|
|
@ -197,6 +213,15 @@ public sealed class LegacyUiSettings
|
|||
/// below RebuffSecondsRemaining only the expiring buff is recast.
|
||||
/// </summary>
|
||||
public int RebuffTopOffSecondsRemaining = 1200;
|
||||
/// <summary>
|
||||
/// Cast our own buff even when an item already gives that buff (a permanent, item-granted
|
||||
/// enchantment at the same tier or higher). For servers with buff augments, where a player's
|
||||
/// own cast is stronger or lasts longer than the item's. On by default: on retail the cost
|
||||
/// is a few extra casts, while missing the buff is worse. A profile saved before this
|
||||
/// setting existed loads it as on. Off = an item-granted buff at the tier we'd cast counts
|
||||
/// as on for good (the behaviour before 2026-10-05).
|
||||
/// </summary>
|
||||
public bool CastBuffsOverItemBuffs = true;
|
||||
public bool StartMacroOnLogin;
|
||||
public bool PatrolOnLogin;
|
||||
/// <summary>
|
||||
|
|
@ -828,6 +853,9 @@ public sealed class SettingsBridgePayload
|
|||
public bool RebuffWhenIdle { get; set; }
|
||||
public int RebuffSecondsRemaining { get; set; }
|
||||
public int RebuffTopOffSecondsRemaining { get; set; } = 1200; // absent in older files
|
||||
// Nullable: an engine that predates the setting doesn't send it, and a save from its
|
||||
// Settings face must leave the setting alone rather than force it either way.
|
||||
public bool? CastBuffsOverItemBuffs { get; set; }
|
||||
public int BuffMinSkillLevelTier1 { get; set; }
|
||||
public int BuffMinSkillLevelTier2 { get; set; }
|
||||
public int BuffMinSkillLevelTier3 { get; set; }
|
||||
|
|
@ -850,6 +878,10 @@ public sealed class SettingsBridgePayload
|
|||
public bool LootJumpEnabled { get; set; }
|
||||
public int LootJumpHeight { get; set; }
|
||||
public int LootOwnership { get; set; }
|
||||
// Nullable, as CastBuffsOverItemBuffs: an engine that predates them doesn't send them,
|
||||
// and its save must leave them alone.
|
||||
public bool? LootOwnCorpse { get; set; }
|
||||
public bool? TravelToOwnCorpse { get; set; }
|
||||
public bool EnableAutostack { get; set; }
|
||||
public bool ReadUnknownScrolls { get; set; } = true; // absent from an older engine: keep the default
|
||||
public bool EnableCombineSalvage { get; set; }
|
||||
|
|
|
|||
|
|
@ -187,6 +187,7 @@ internal sealed class LootEditorBridge
|
|||
d.ItemName = facts.Name;
|
||||
d.ClassName = LootItemRules.ClassName(facts.ObjectClass);
|
||||
d.Stackable = facts.Stackable;
|
||||
d.BuiltInReason = BuiltInSentence(Items.BuiltInKeep(id));
|
||||
|
||||
string inUse = InUse;
|
||||
string target = req.ToOpenProfile && _session.IsOpen ? _session.Path : inUse;
|
||||
|
|
@ -246,6 +247,7 @@ internal sealed class LootEditorBridge
|
|||
}
|
||||
else
|
||||
d.OrderNote = $"Goes in at the end ({at + 1} of {count + 1}): no rule takes this item now, so at the end it only gets items no other rule wants.";
|
||||
AppendBuiltIn(d);
|
||||
|
||||
if (s.IsDirty) return Refuse(d, $"The Loot Editor has unsaved changes in {d.TargetFile}. Save or discard them first.");
|
||||
d.Ok = true;
|
||||
|
|
@ -261,9 +263,30 @@ internal sealed class LootEditorBridge
|
|||
{
|
||||
d.Ok = false;
|
||||
d.Error = error;
|
||||
AppendBuiltIn(d);
|
||||
return d;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The popup's sentence for one of RynthAi's built-in keeps. "No rule matches" alone
|
||||
/// misled: a wand Mana Tap had looted read as looted for no reason (2026-10-05).
|
||||
/// </summary>
|
||||
internal static string BuiltInSentence(LootBuiltInKeep? keep)
|
||||
{
|
||||
if (keep == null || keep.Reason.Length == 0) return string.Empty;
|
||||
return keep.BeforeProfile
|
||||
? $"RynthAi takes it before any loot profile rule: {keep.Reason}."
|
||||
: $"No rule in the loot profile in use takes it, but RynthAi keeps it anyway: {keep.Reason}.";
|
||||
}
|
||||
|
||||
// OrderNote is what every engine's popup (and /ra loot add) shows, so the reason rides on it;
|
||||
// BuiltInReason carries it on its own for a face that wants it separately.
|
||||
private static void AppendBuiltIn(LootEditItemDraft d)
|
||||
{
|
||||
if (d.BuiltInReason.Length == 0 || d.OrderNote.EndsWith(d.BuiltInReason, StringComparison.Ordinal)) return;
|
||||
d.OrderNote = d.OrderNote.Length == 0 ? d.BuiltInReason : d.OrderNote + " " + d.BuiltInReason;
|
||||
}
|
||||
|
||||
/// <summary>The editor's session when it has <paramref name="target"/> open, else a second one (fresh from disk).</summary>
|
||||
private LootEditSession SessionFor(string target)
|
||||
{
|
||||
|
|
@ -321,4 +344,16 @@ internal sealed class LootItemHooks
|
|||
public Func<uint, LootProfile, int> FirstMatchNative { get; set; } = (_, _) => -1;
|
||||
/// <summary>A rule was added and saved: say so and reload the profile. Outside the bridge's lock.</summary>
|
||||
public Action<LootEditItemDraft> Added { get; set; } = _ => { };
|
||||
/// <summary>
|
||||
/// One of RynthAi's built-in keeps that takes the item now with the loot profile in use
|
||||
/// (the looter's own classification, run as a preview), or null.
|
||||
/// </summary>
|
||||
public Func<uint, LootBuiltInKeep?> BuiltInKeep { get; set; } = _ => null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A built-in keep: <see cref="Reason"/> says what and where to change it (ASCII);
|
||||
/// <see cref="BeforeProfile"/> when it is checked ahead of the loot profile's rules
|
||||
/// (Learn unknown spells, mana stones) rather than only when no rule matches (Mana Tap).
|
||||
/// </summary>
|
||||
internal sealed record LootBuiltInKeep(string Reason, bool BeforeProfile);
|
||||
|
|
|
|||
|
|
@ -279,28 +279,38 @@ internal sealed class ScrollLearner
|
|||
/// setting on, a scroll on a corpse whose spell the character doesn't know and can learn.
|
||||
/// One copy per spell.
|
||||
/// </summary>
|
||||
public bool ShouldLootFromCorpse(WorldObject item, out string ruleLabel)
|
||||
public bool ShouldLootFromCorpse(WorldObject item, out string ruleLabel) =>
|
||||
ShouldLootFromCorpse(item, out ruleLabel, out _, preview: false);
|
||||
|
||||
// preview: the same answer with nothing recorded or logged (the loot popup asking why).
|
||||
// why: the spell and why it is taken, in a few words.
|
||||
public bool ShouldLootFromCorpse(WorldObject item, out string ruleLabel, out string why, bool preview)
|
||||
{
|
||||
ruleLabel = string.Empty;
|
||||
why = string.Empty;
|
||||
if (!_settings.ReadUnknownScrolls || !LooksLikeScroll(item)) return false;
|
||||
|
||||
ScrollJudgement j = Judge(item);
|
||||
if (j.Verdict == ScrollVerdict.NoSpell) return false; // a book, a note: not ours to judge
|
||||
if (!j.Learnable)
|
||||
{
|
||||
LogItem(item.Id, $"[Learn] leaving '{item.Name}' ({j.SpellName}: {j.Why})");
|
||||
if (!preview) LogItem(item.Id, $"[Learn] leaving '{item.Name}' ({j.SpellName}: {j.Why})");
|
||||
return false;
|
||||
}
|
||||
|
||||
long now = NowMs();
|
||||
if (OtherCopyTaken(j.SpellId, item.Id, now))
|
||||
{
|
||||
LogItem(item.Id, $"[Learn] leaving '{item.Name}' ({j.SpellName}: another copy is already on its way)");
|
||||
if (!preview) LogItem(item.Id, $"[Learn] leaving '{item.Name}' ({j.SpellName}: another copy is already on its way)");
|
||||
return false;
|
||||
}
|
||||
_approved[j.SpellId] = (item.Id, now);
|
||||
LogItem(item.Id, $"[Learn] looting '{item.Name}' ({j.SpellName}: {j.Why})");
|
||||
if (!preview)
|
||||
{
|
||||
_approved[j.SpellId] = (item.Id, now);
|
||||
LogItem(item.Id, $"[Learn] looting '{item.Name}' ({j.SpellName}: {j.Why})");
|
||||
}
|
||||
ruleLabel = RuleLabel;
|
||||
why = $"{j.SpellName}: {j.Why}";
|
||||
return true;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -303,7 +303,7 @@ public sealed partial class RynthAiPlugin
|
|||
if (parts.Length < 3 || !float.TryParse(parts[2], out float degrees)) return false;
|
||||
if (!Host.HasTurnToHeading) { ChatLine("[RynthAi] TurnToHeading not available."); return true; }
|
||||
|
||||
Host.TurnToHeading(degrees);
|
||||
Host.TurnToHeadingBy("Command", degrees);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
|
@ -470,7 +470,12 @@ public sealed partial class RynthAiPlugin
|
|||
string itemName = argStr[..toIdx].Trim();
|
||||
string targetName = argStr[(toIdx + 4)..].Trim();
|
||||
|
||||
var item = FindObject(itemName, inv: true, land: false, partial: partial);
|
||||
// /mt give hands over the FIRST carried match (/ub give hands over all of them).
|
||||
// Never worn or wielded gear: FindObject's inventory walk includes it.
|
||||
var candidates = GiveCandidates(n => partial
|
||||
? n.IndexOf(itemName, StringComparison.OrdinalIgnoreCase) >= 0
|
||||
: string.Equals(n, itemName, StringComparison.OrdinalIgnoreCase));
|
||||
var item = candidates.Count > 0 ? candidates[0] : null;
|
||||
if (item == null) { ChatLine($"[RynthAi] Item not found: '{itemName}'"); return true; }
|
||||
|
||||
var target = FindObject(targetName, inv: false, land: true, partial: true);
|
||||
|
|
|
|||
|
|
@ -249,6 +249,9 @@ internal sealed class ManaStoneManager
|
|||
if (itemId != 0) _lootedForTap[itemId] = NowMs;
|
||||
}
|
||||
|
||||
/// <summary>The looter picked this item up as "ManaTap" this session (it is waiting to be drained).</summary>
|
||||
public bool WasLootedForTap(int itemId) => _lootedForTap.ContainsKey(itemId);
|
||||
|
||||
/// <summary>
|
||||
/// Drops entries whose item has left the pack: drained (destroyed), sold, given
|
||||
/// away, salvaged, dropped, or never arrived. Also drops items the player has
|
||||
|
|
@ -685,7 +688,7 @@ internal sealed class ManaStoneManager
|
|||
/// is unreliable for unappraised items, so we fall back to the name, matching
|
||||
/// CombatManager/BuffManager.IsWandObject.
|
||||
/// </summary>
|
||||
private static bool IsWandLike(WorldObject item)
|
||||
internal static bool IsWandLike(WorldObject item)
|
||||
=> item.ObjectClass == AcObjectClass.WandStaffOrb || IsWandName(item.Name);
|
||||
|
||||
private static bool IsWandName(string name)
|
||||
|
|
|
|||
279
Plugins/RynthCore.Plugin.RynthAi/Maps/DungeonMapBake.cs
Normal file
279
Plugins/RynthCore.Plugin.RynthAi/Maps/DungeonMapBake.cs
Normal file
|
|
@ -0,0 +1,279 @@
|
|||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.RynthAi.Raycasting;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.Maps;
|
||||
|
||||
/// <summary>
|
||||
/// Writes each dungeon floor as a finished top-down raster to
|
||||
/// C:\Games\RynthSuite\RynthAi\Maps\{landblock:X8}_{layer}.bin, which the RynthCore StatusAgent
|
||||
/// serves at /map (re-encoded to PNG) for DrakRemote's dungeon map.
|
||||
///
|
||||
/// File format (must match the StatusAgent's MapService and the 81 plans baked before
|
||||
/// 2026-09-28 by the old DungeonMapTexture): 20-byte header [uint32 Magic "XTMR" 0x524D5458,
|
||||
/// int32 xMin, int32 yMin, int32 w, int32 h], then w*h little-endian ARGB uint32 pixels
|
||||
/// (A<<24|R<<16|G<<8|B), 0.5 world units a pixel, row 0 = northernmost, 0 = empty.
|
||||
/// xMin/yMin are grid-cell coordinates (world units * 2). The landblock in the file name is the
|
||||
/// short form (cellId >> 16, e.g. 00006346_1.bin) and the layer is the index into the
|
||||
/// landblock's ascending floor heights (DungeonMapUi.LayerZs), empty layers included.
|
||||
///
|
||||
/// This is the disk half of the old DungeonMapTexture only: no D3D9 textures. Each landblock
|
||||
/// is baked at most once per session, on a pool thread, and a file that already holds the
|
||||
/// same bytes is left alone (no mtime churn on the plans already there). Writes go to a temp
|
||||
/// file that is then renamed over the target, so the agent never reads a half-written plan.
|
||||
/// </summary>
|
||||
internal static class DungeonMapBake
|
||||
{
|
||||
internal const uint Magic = 0x524D5458u; // "XTMR" - same constant as the StatusAgent's MapService
|
||||
private const int MaxDim = 8192; // the agent refuses bigger rasters
|
||||
|
||||
/// <summary>Where plans go. A test points this at its own folder.</summary>
|
||||
internal static string CacheDir { get; set; } = @"C:\Games\RynthSuite\RynthAi\Maps";
|
||||
|
||||
// Pixel colours, as the old DungeonMapTexture (and DungeonMapUi's former ImGui colours).
|
||||
private static uint Argb(float r, float g, float b, float a) =>
|
||||
((uint)(a * 255f) << 24) | ((uint)(r * 255f) << 16) | ((uint)(g * 255f) << 8) | (uint)(b * 255f);
|
||||
|
||||
private static readonly uint FillFlat = Argb(0.18f, 0.55f, 0.22f, 0.40f);
|
||||
private static readonly uint FillSlopeUp = Argb(0.55f, 0.12f, 0.08f, 0.40f);
|
||||
private static readonly uint FillSlopeDown = Argb(0.10f, 0.50f, 0.15f, 0.40f);
|
||||
private static readonly uint EdgeFlat = Argb(0.55f, 0.80f, 1.00f, 1.00f);
|
||||
private static readonly uint EdgeSlopeUp = Argb(1.00f, 0.35f, 0.25f, 1.00f);
|
||||
private static readonly uint EdgeSlopeDown = Argb(0.25f, 1.00f, 0.35f, 1.00f);
|
||||
|
||||
internal enum SaveResult { Written, Unchanged, Failed }
|
||||
|
||||
// Landblocks already baked (or being baked) this session.
|
||||
private static readonly ConcurrentDictionary<uint, byte> _requested = new();
|
||||
// Messages from the pool thread, logged by the game-thread tick (DrainLog).
|
||||
private static readonly ConcurrentQueue<string> _log = new();
|
||||
|
||||
/// <summary>Normalise to the short landblock id the file names use (0x63460000 -> 0x6346).</summary>
|
||||
internal static uint ShortLandblock(uint landblock) =>
|
||||
landblock > 0xFFFFu ? landblock >> 16 : landblock;
|
||||
|
||||
internal static bool WasRequested(uint landblock) => _requested.ContainsKey(ShortLandblock(landblock));
|
||||
|
||||
/// <summary>Messages queued by background bakes since the last call (game thread logs them).</summary>
|
||||
internal static void DrainLog(Action<string> log)
|
||||
{
|
||||
while (_log.TryDequeue(out string? m)) log(m);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Bake already-built floor grids (DungeonMapUi.RefreshMap) once per landblock. Returns at
|
||||
/// once; the rasterise and disk work run on a pool thread. The dictionaries must not be
|
||||
/// changed afterwards (RefreshMap builds new ones each time).
|
||||
/// </summary>
|
||||
internal static void Request(uint landblock, List<float>? zLayers,
|
||||
Dictionary<float, Dictionary<(int, int), DungeonMapUi.CellType>>? floorCells)
|
||||
{
|
||||
if (zLayers is null || floorCells is null || floorCells.Count == 0) return;
|
||||
uint lb = ShortLandblock(landblock);
|
||||
if (lb == 0 || !_requested.TryAdd(lb, 0)) return;
|
||||
Task.Run(() => BakeLogged(lb, zLayers, floorCells));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Build the floor grids from the dat and bake them, once per landblock, on a pool thread.
|
||||
/// For a landblock change indoors with no Radar or Dungeon Map panel open.
|
||||
/// </summary>
|
||||
internal static void RequestFromDat(DungeonLOS los, uint landblock)
|
||||
{
|
||||
uint lb = ShortLandblock(landblock);
|
||||
if (lb == 0 || !_requested.TryAdd(lb, 0)) return;
|
||||
Task.Run(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
var (zLayers, cells) = DungeonMapUi.BuildFloorCells(los, lb);
|
||||
if (cells.Count == 0) return; // no floor geometry (not a dungeon, or no dat data)
|
||||
BakeLogged(lb, zLayers, cells);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_requested.TryRemove(lb, out _);
|
||||
_log.Enqueue($"[RynthAi] map bake 0x{lb:X4}: {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static void BakeLogged(uint lb, List<float> zLayers,
|
||||
Dictionary<float, Dictionary<(int, int), DungeonMapUi.CellType>> floorCells)
|
||||
{
|
||||
try
|
||||
{
|
||||
var (written, unchanged, failed) = BakeLayers(CacheDir, lb, zLayers, floorCells);
|
||||
// A layer that could not be written (file held open, disk full): let the next
|
||||
// RefreshMap or re-entry try again instead of skipping it for the session.
|
||||
if (failed > 0) _requested.TryRemove(lb, out _);
|
||||
if (written > 0 || failed > 0)
|
||||
_log.Enqueue($"[RynthAi] map bake 0x{lb:X4}: {written} written, {unchanged} unchanged, {failed} failed ({CacheDir})");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_requested.TryRemove(lb, out _);
|
||||
_log.Enqueue($"[RynthAi] map bake 0x{lb:X4}: {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Bake every non-empty layer of a landblock into <paramref name="dir"/>. Synchronous.</summary>
|
||||
internal static (int Written, int Unchanged, int Failed) BakeLayers(string dir, uint landblock, List<float> zLayers,
|
||||
Dictionary<float, Dictionary<(int, int), DungeonMapUi.CellType>> floorCells)
|
||||
{
|
||||
uint lb = ShortLandblock(landblock);
|
||||
int written = 0, unchanged = 0, failed = 0;
|
||||
foreach (var (layerZ, cells) in floorCells)
|
||||
{
|
||||
int idx = zLayers.IndexOf(layerZ);
|
||||
if (idx < 0) continue;
|
||||
byte[]? bytes = BuildFile(cells);
|
||||
if (bytes is null) continue;
|
||||
switch (SaveToDisk(dir, lb, idx, bytes))
|
||||
{
|
||||
case SaveResult.Written: written++; break;
|
||||
case SaveResult.Unchanged: unchanged++; break;
|
||||
default: failed++; break;
|
||||
}
|
||||
}
|
||||
return (written, unchanged, failed);
|
||||
}
|
||||
|
||||
internal static string FileName(uint landblock, int layerIdx) => $"{ShortLandblock(landblock):X8}_{layerIdx}.bin";
|
||||
|
||||
/// <summary>The whole .bin (header + pixels) for one layer's cells, or null if empty / too big.</summary>
|
||||
internal static byte[]? BuildFile(Dictionary<(int gx, int gy), DungeonMapUi.CellType> cells)
|
||||
{
|
||||
if (cells.Count == 0) return null;
|
||||
int xMin = int.MaxValue, xMax = int.MinValue;
|
||||
int yMin = int.MaxValue, yMax = int.MinValue;
|
||||
foreach (var (gx, gy) in cells.Keys)
|
||||
{
|
||||
if (gx < xMin) xMin = gx; if (gx > xMax) xMax = gx;
|
||||
if (gy < yMin) yMin = gy; if (gy > yMax) yMax = gy;
|
||||
}
|
||||
int w = xMax - xMin + 1, h = yMax - yMin + 1;
|
||||
if (w <= 0 || h <= 0 || w > MaxDim || h > MaxDim) return null;
|
||||
|
||||
uint[] pixels = Rasterise(cells, xMin, yMax, w, h);
|
||||
var bytes = new byte[20 + pixels.Length * 4];
|
||||
var span = bytes.AsSpan();
|
||||
System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(span, Magic);
|
||||
System.Buffers.Binary.BinaryPrimitives.WriteInt32LittleEndian(span.Slice(4), xMin);
|
||||
System.Buffers.Binary.BinaryPrimitives.WriteInt32LittleEndian(span.Slice(8), yMin);
|
||||
System.Buffers.Binary.BinaryPrimitives.WriteInt32LittleEndian(span.Slice(12), w);
|
||||
System.Buffers.Binary.BinaryPrimitives.WriteInt32LittleEndian(span.Slice(16), h);
|
||||
for (int i = 0; i < pixels.Length; i++)
|
||||
System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(span.Slice(20 + i * 4), pixels[i]);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One layer's cells as ARGB pixels: cells bordering empty space get the bright edge colour,
|
||||
/// the rest the translucent fill, by cell type; empty = 0. Row 0 = northernmost (highest gy).
|
||||
/// Unchanged from the old DungeonMapTexture.Rasterise.
|
||||
/// </summary>
|
||||
internal static uint[] Rasterise(Dictionary<(int gx, int gy), DungeonMapUi.CellType> cells,
|
||||
int xMin, int yMax, int w, int h)
|
||||
{
|
||||
var pixels = new uint[w * h];
|
||||
foreach (var ((gx, gy), ctype) in cells)
|
||||
{
|
||||
bool isEdge = !cells.ContainsKey((gx + 1, gy))
|
||||
|| !cells.ContainsKey((gx - 1, gy))
|
||||
|| !cells.ContainsKey((gx, gy + 1))
|
||||
|| !cells.ContainsKey((gx, gy - 1));
|
||||
uint col = isEdge
|
||||
? ctype switch
|
||||
{
|
||||
DungeonMapUi.CellType.SlopeUp => EdgeSlopeUp,
|
||||
DungeonMapUi.CellType.SlopeDown => EdgeSlopeDown,
|
||||
_ => EdgeFlat,
|
||||
}
|
||||
: ctype switch
|
||||
{
|
||||
DungeonMapUi.CellType.SlopeUp => FillSlopeUp,
|
||||
DungeonMapUi.CellType.SlopeDown => FillSlopeDown,
|
||||
_ => FillFlat,
|
||||
};
|
||||
pixels[(yMax - gy) * w + (gx - xMin)] = col;
|
||||
}
|
||||
return pixels;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Write one plan unless the file already holds exactly these bytes. Temp file + rename, so a
|
||||
/// reader sees the old plan or the new one, never a partial one. Never throws.
|
||||
/// </summary>
|
||||
internal static SaveResult SaveToDisk(string dir, uint landblock, int layerIdx, byte[] bytes)
|
||||
{
|
||||
string path = Path.Combine(dir, FileName(landblock, layerIdx));
|
||||
string? tmp = null;
|
||||
try
|
||||
{
|
||||
if (SameContent(path, bytes)) return SaveResult.Unchanged;
|
||||
|
||||
Directory.CreateDirectory(dir);
|
||||
// Unique per process and call: two clients in the same dungeon can bake at once.
|
||||
string tmpPath = path + "." + Environment.ProcessId.ToString("X") + "." + Guid.NewGuid().ToString("N").Substring(0, 8) + ".tmp";
|
||||
tmp = tmpPath;
|
||||
using (var fs = new FileStream(tmpPath, FileMode.CreateNew, FileAccess.Write, FileShare.None))
|
||||
fs.Write(bytes, 0, bytes.Length);
|
||||
|
||||
// The agent may hold the target open for a moment (FileShare.ReadWrite, not Delete),
|
||||
// which makes the replace fail; try a few times.
|
||||
for (int attempt = 0; ; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Move(tmpPath, path, overwrite: true);
|
||||
tmp = null;
|
||||
return SaveResult.Written;
|
||||
}
|
||||
catch (IOException) when (attempt < 4)
|
||||
{
|
||||
if (SameContent(path, bytes)) return SaveResult.Unchanged; // another client won
|
||||
Thread.Sleep(100);
|
||||
}
|
||||
catch (UnauthorizedAccessException) when (attempt < 4)
|
||||
{
|
||||
Thread.Sleep(100);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
return SaveResult.Failed;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (tmp != null) { try { File.Delete(tmp); } catch { } }
|
||||
}
|
||||
}
|
||||
|
||||
private static bool SameContent(string path, byte[] bytes)
|
||||
{
|
||||
try
|
||||
{
|
||||
var fi = new FileInfo(path);
|
||||
if (!fi.Exists || fi.Length != bytes.Length) return false;
|
||||
using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
|
||||
var buf = new byte[64 * 1024];
|
||||
int off = 0;
|
||||
while (off < bytes.Length)
|
||||
{
|
||||
int got = fs.Read(buf, 0, Math.Min(buf.Length, bytes.Length - off));
|
||||
if (got <= 0) return false;
|
||||
if (!buf.AsSpan(0, got).SequenceEqual(bytes.AsSpan(off, got))) return false;
|
||||
off += got;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
catch { return false; }
|
||||
}
|
||||
}
|
||||
|
|
@ -2543,7 +2543,7 @@ internal sealed class ExpressionEngine
|
|||
if (!_castCombatTornDown && (mode == CombatMode.Melee || mode == CombatMode.Missile))
|
||||
{
|
||||
if (_host.HasCancelAttack) _host.CancelAttack();
|
||||
if (_host.HasStopCompletely) _host.StopCompletely();
|
||||
if (_host.HasStopCompletely) _host.StopCompletelyBy("Meta");
|
||||
_castCombatTornDown = true;
|
||||
_host.Log($"[MetaCast] CancelAttack+StopCompletely before wand equip (mode was {mode})");
|
||||
}
|
||||
|
|
@ -2882,7 +2882,7 @@ internal sealed class ExpressionEngine
|
|||
if (!MotionValues.TryGetValue(motionArg, out uint motionVal)) return "0";
|
||||
bool on = ToDouble(stateArg) != 0;
|
||||
_wantedMotion[motionArg] = on;
|
||||
return _host.SetMotion(motionVal, on) ? "1" : "0";
|
||||
return _host.SetMotionBy("Meta", motionVal, on) ? "1" : "0";
|
||||
}
|
||||
|
||||
private string EvalGetMotion(string motionArg)
|
||||
|
|
@ -2899,7 +2899,7 @@ internal sealed class ExpressionEngine
|
|||
if (_host.HasSetMotion)
|
||||
{
|
||||
foreach (var kvp in MotionValues)
|
||||
_host.SetMotion(kvp.Value, false);
|
||||
_host.SetMotionBy("Meta", kvp.Value, false);
|
||||
}
|
||||
_wantedMotion.Clear();
|
||||
return "1";
|
||||
|
|
@ -3305,6 +3305,8 @@ internal sealed class ExpressionEngine
|
|||
["StopMacroOnDeath"] = (() => B(s.StopMacroOnDeath), v => s.StopMacroOnDeath = ToDouble(v) != 0),
|
||||
["StopMacroOnNoComponents"] = (() => B(s.StopMacroOnNoComponents), v => s.StopMacroOnNoComponents = ToDouble(v) != 0),
|
||||
["StopLootingWhenPackFull"] = (() => B(s.StopLootingWhenPackFull), v => s.StopLootingWhenPackFull = ToDouble(v) != 0),
|
||||
["LootOwnCorpse"] = (() => B(s.LootOwnCorpse), v => s.LootOwnCorpse = ToDouble(v) != 0),
|
||||
["TravelToOwnCorpse"] = (() => B(s.TravelToOwnCorpse), v => s.TravelToOwnCorpse = ToDouble(v) != 0),
|
||||
["StopMacroWhenPackFull"] = (() => B(s.StopMacroWhenPackFull), v => s.StopMacroWhenPackFull = ToDouble(v) != 0),
|
||||
["SummonPets"] = (() => B(s.SummonPets), v => s.SummonPets = ToDouble(v) != 0),
|
||||
["MineOnly"] = (() => B(s.MineOnly), v => s.MineOnly = ToDouble(v) != 0),
|
||||
|
|
@ -3340,6 +3342,7 @@ internal sealed class ExpressionEngine
|
|||
["ManaStoneKeepCount"] = (() => I(s.ManaStoneKeepCount), v => { if (int.TryParse(v, out int i)) s.ManaStoneKeepCount = i; }),
|
||||
["RebuffSecondsRemaining"] = (() => I(s.RebuffSecondsRemaining), v => { if (int.TryParse(v, out int i)) s.RebuffSecondsRemaining = i; }),
|
||||
["RebuffTopOffSecondsRemaining"] = (() => I(s.RebuffTopOffSecondsRemaining), v => { if (int.TryParse(v, out int i)) s.RebuffTopOffSecondsRemaining = i; }),
|
||||
["CastBuffsOverItemBuffs"] = (() => B(s.CastBuffsOverItemBuffs), v => s.CastBuffsOverItemBuffs = ToDouble(v) != 0),
|
||||
// AutoVendor (UB names map here through /ub opt: AutoVendor.Enabled -> AutoVendorEnabled, ...)
|
||||
["AutoVendorEnabled"] = (() => B(s.AutoVendorEnabled), v => s.AutoVendorEnabled = ToDouble(v) != 0),
|
||||
["AutoVendorEnableBuying"] = (() => B(s.AutoVendorEnableBuying), v => s.AutoVendorEnableBuying = ToDouble(v) != 0),
|
||||
|
|
|
|||
|
|
@ -367,7 +367,7 @@ internal sealed class NavigationEngine
|
|||
|
||||
if (Now - _stopRequestedAt >= (long)StopDebounceMs)
|
||||
{
|
||||
_host.SetAutoRun(false);
|
||||
_host.SetAutoRunBy("Nav", false);
|
||||
_isMovingForward = false;
|
||||
_isTurning = false;
|
||||
_hasStopped = true;
|
||||
|
|
@ -444,16 +444,16 @@ internal sealed class NavigationEngine
|
|||
// Handle active settle period
|
||||
if (_globalSettling)
|
||||
{
|
||||
_host.SetAutoRun(false);
|
||||
_host.SetAutoRunBy("Nav", false);
|
||||
ClearTurnMotions();
|
||||
if (_host.HasStopCompletely) _host.StopCompletely();
|
||||
if (_host.HasStopCompletely) _host.StopCompletelyBy("Nav");
|
||||
_isMovingForward = false;
|
||||
_isTurning = false;
|
||||
|
||||
if (Now - _globalSettleStart > (long)PostTeleportMs)
|
||||
{
|
||||
_host.Log($"Nav: global post-teleport settle done ({PostTeleportMs:F0}ms)");
|
||||
if (_host.HasStopCompletely) _host.StopCompletely();
|
||||
if (_host.HasStopCompletely) _host.StopCompletelyBy("Nav");
|
||||
if (_host.HasForceResetBusyCount) _host.ForceResetBusyCount();
|
||||
if (_combatManager != null) _combatManager.BusyCount = 0;
|
||||
_hasGoodHeading = false;
|
||||
|
|
@ -632,7 +632,7 @@ internal sealed class NavigationEngine
|
|||
_offTrackSince = 0;
|
||||
RememberFiredPortalAction();
|
||||
ResetPortalState();
|
||||
_host.SetAutoRun(false);
|
||||
_host.SetAutoRunBy("Nav", false);
|
||||
ClearTurnMotions();
|
||||
_isMovingForward = false;
|
||||
_isTurning = false;
|
||||
|
|
@ -999,11 +999,11 @@ internal sealed class NavigationEngine
|
|||
int want = absError <= DeadZone ? 0 : (error > 0 ? 1 : -1);
|
||||
if (want != _tier1TurnDir)
|
||||
{
|
||||
if (_tier1TurnDir > 0) _host.StopMovement(MotionTurnRight, 0);
|
||||
else if (_tier1TurnDir < 0) _host.StopMovement(MotionTurnLeft, 0);
|
||||
if (_tier1TurnDir > 0) _host.StopMovementBy("Nav", MotionTurnRight, 0);
|
||||
else if (_tier1TurnDir < 0) _host.StopMovementBy("Nav", MotionTurnLeft, 0);
|
||||
|
||||
if (want > 0) _host.DoMovement(MotionTurnRight, (float)Tier1TurnSpeed, 0);
|
||||
else if (want < 0) _host.DoMovement(MotionTurnLeft, (float)Tier1TurnSpeed, 0);
|
||||
if (want > 0) _host.DoMovementBy("Nav", MotionTurnRight, (float)Tier1TurnSpeed, 0);
|
||||
else if (want < 0) _host.DoMovementBy("Nav", MotionTurnLeft, (float)Tier1TurnSpeed, 0);
|
||||
|
||||
_tier1TurnDir = want;
|
||||
}
|
||||
|
|
@ -1019,14 +1019,14 @@ internal sealed class NavigationEngine
|
|||
double newHeading = currentDeg + step;
|
||||
if (newHeading >= 360.0) newHeading -= 360.0;
|
||||
else if (newHeading < 0.0) newHeading += 360.0;
|
||||
_host.TurnToHeading((float)newHeading);
|
||||
_host.TurnToHeadingBy("Nav", (float)newHeading);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Heartbeat: periodically re-assert autorun ───────────────────────
|
||||
if (_isMovingForward && Now - _lastHeartbeat > (long)HeartbeatMs)
|
||||
{
|
||||
_host.SetAutoRun(true);
|
||||
_host.SetAutoRunBy("Nav", true);
|
||||
_lastHeartbeat = Now;
|
||||
}
|
||||
}
|
||||
|
|
@ -1050,13 +1050,13 @@ internal sealed class NavigationEngine
|
|||
|
||||
if (error > 0)
|
||||
{
|
||||
_host.SetMotion(MotionTurnRight, true);
|
||||
_host.SetMotion(MotionTurnLeft, false);
|
||||
_host.SetMotionBy("Nav", MotionTurnRight, true);
|
||||
_host.SetMotionBy("Nav", MotionTurnLeft, false);
|
||||
}
|
||||
else
|
||||
{
|
||||
_host.SetMotion(MotionTurnLeft, true);
|
||||
_host.SetMotion(MotionTurnRight, false);
|
||||
_host.SetMotionBy("Nav", MotionTurnLeft, true);
|
||||
_host.SetMotionBy("Nav", MotionTurnRight, false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
|
@ -1067,13 +1067,13 @@ internal sealed class NavigationEngine
|
|||
StopForward();
|
||||
if (error > 0)
|
||||
{
|
||||
_host.SetMotion(MotionTurnRight, true);
|
||||
_host.SetMotion(MotionTurnLeft, false);
|
||||
_host.SetMotionBy("Nav", MotionTurnRight, true);
|
||||
_host.SetMotionBy("Nav", MotionTurnLeft, false);
|
||||
}
|
||||
else
|
||||
{
|
||||
_host.SetMotion(MotionTurnLeft, true);
|
||||
_host.SetMotion(MotionTurnRight, false);
|
||||
_host.SetMotionBy("Nav", MotionTurnLeft, true);
|
||||
_host.SetMotionBy("Nav", MotionTurnRight, false);
|
||||
}
|
||||
_isTurning = true;
|
||||
return;
|
||||
|
|
@ -1098,13 +1098,13 @@ internal sealed class NavigationEngine
|
|||
|
||||
if (_lastTurnDir > 0)
|
||||
{
|
||||
_host.SetMotion(MotionTurnRight, true);
|
||||
_host.SetMotion(MotionTurnLeft, false);
|
||||
_host.SetMotionBy("Nav", MotionTurnRight, true);
|
||||
_host.SetMotionBy("Nav", MotionTurnLeft, false);
|
||||
}
|
||||
else
|
||||
{
|
||||
_host.SetMotion(MotionTurnLeft, true);
|
||||
_host.SetMotion(MotionTurnRight, false);
|
||||
_host.SetMotionBy("Nav", MotionTurnLeft, true);
|
||||
_host.SetMotionBy("Nav", MotionTurnRight, false);
|
||||
}
|
||||
}
|
||||
else
|
||||
|
|
@ -1115,7 +1115,7 @@ internal sealed class NavigationEngine
|
|||
|
||||
if (_isMovingForward && Now - _lastHeartbeat > (long)HeartbeatMs)
|
||||
{
|
||||
_host.SetAutoRun(true);
|
||||
_host.SetAutoRunBy("Nav", true);
|
||||
_lastHeartbeat = Now;
|
||||
}
|
||||
}
|
||||
|
|
@ -1742,7 +1742,7 @@ internal sealed class NavigationEngine
|
|||
case PortalState.Settling:
|
||||
// Keep clearing motions until settled
|
||||
ClearTurnMotions();
|
||||
_host.SetAutoRun(false);
|
||||
_host.SetAutoRunBy("Nav", false);
|
||||
_isMovingForward = false;
|
||||
|
||||
if (Now - _portalStateStart > (long)SettleDelayMs)
|
||||
|
|
@ -1861,9 +1861,9 @@ internal sealed class NavigationEngine
|
|||
// Hammer-stop to cancel any lingering UseItem walk and clear
|
||||
// the client's internal action queue (prevents stuck hourglass
|
||||
// cursor when UseObject is interrupted by portal teleport).
|
||||
_host.SetAutoRun(false);
|
||||
_host.SetAutoRunBy("Nav", false);
|
||||
ClearTurnMotions();
|
||||
if (_host.HasStopCompletely) _host.StopCompletely();
|
||||
if (_host.HasStopCompletely) _host.StopCompletelyBy("Nav");
|
||||
_isMovingForward = false;
|
||||
_isTurning = false;
|
||||
|
||||
|
|
@ -1874,7 +1874,7 @@ internal sealed class NavigationEngine
|
|||
// Force-clear the client's internal busy count (hourglass cursor)
|
||||
// and our tracked busy count. Portal teleport interrupts actions
|
||||
// without firing the matching DecrementBusyCount callback.
|
||||
if (_host.HasStopCompletely) _host.StopCompletely();
|
||||
if (_host.HasStopCompletely) _host.StopCompletelyBy("Nav");
|
||||
if (_host.HasForceResetBusyCount) _host.ForceResetBusyCount();
|
||||
if (_combatManager != null) _combatManager.BusyCount = 0;
|
||||
|
||||
|
|
@ -2096,13 +2096,13 @@ internal sealed class NavigationEngine
|
|||
double step = Math.Clamp(err, -MaxStepDeg, MaxStepDeg);
|
||||
double newHeading = curDeg + step;
|
||||
if (newHeading >= 360.0) newHeading -= 360.0; else if (newHeading < 0.0) newHeading += 360.0;
|
||||
_host.TurnToHeading((float)newHeading);
|
||||
_host.TurnToHeadingBy("Nav", (float)newHeading);
|
||||
// Run only once roughly aligned, so we don't arc wide on a big turn.
|
||||
if (Math.Abs(err) <= BigTurnEnter) StartForward(); else StopForward();
|
||||
}
|
||||
else
|
||||
{
|
||||
_host.TurnToHeading((float)desiredDeg);
|
||||
_host.TurnToHeadingBy("Nav", (float)desiredDeg);
|
||||
StartForward();
|
||||
}
|
||||
}
|
||||
|
|
@ -2220,7 +2220,7 @@ internal sealed class NavigationEngine
|
|||
if (escapeHeading >= 360.0) escapeHeading -= 360.0; else if (escapeHeading < 0.0) escapeHeading += 360.0;
|
||||
|
||||
_host.Log($"Nav: stuck x{_stuckCount} — escape burst {offset:+0;-0}° for {RecoveryBurstMs:F0}ms.");
|
||||
_host.TurnToHeading((float)escapeHeading);
|
||||
_host.TurnToHeadingBy("Nav", (float)escapeHeading);
|
||||
StartForward();
|
||||
_recoveryKind = RecoveryKind.Escape;
|
||||
_recoveryUntil = Now + (long)RecoveryBurstMs;
|
||||
|
|
@ -2767,7 +2767,7 @@ internal sealed class NavigationEngine
|
|||
long now = Environment.TickCount64;
|
||||
if (!_isMovingForward || now - _lastForwardAssertMs >= ForwardReassertMs)
|
||||
{
|
||||
_host.SetAutoRun(true);
|
||||
_host.SetAutoRunBy("Nav", true);
|
||||
_isMovingForward = true;
|
||||
_lastForwardAssertMs = now;
|
||||
}
|
||||
|
|
@ -2775,15 +2775,15 @@ internal sealed class NavigationEngine
|
|||
|
||||
private void StopForward()
|
||||
{
|
||||
_host.SetAutoRun(false);
|
||||
_host.SetAutoRunBy("Nav", false);
|
||||
_isMovingForward = false;
|
||||
}
|
||||
|
||||
private void ClearTurnMotions()
|
||||
{
|
||||
// Mode-0/legacy motion keys are local cmdinterp toggles — cheap, always clear.
|
||||
_host.SetMotion(MotionTurnRight, false);
|
||||
_host.SetMotion(MotionTurnLeft, false);
|
||||
_host.SetMotionBy("Nav", MotionTurnRight, false);
|
||||
_host.SetMotionBy("Nav", MotionTurnLeft, false);
|
||||
|
||||
// Tier 1 turns are CM_Movement *server events* (0xF661). Only send a
|
||||
// StopMovement when a turn is actually in flight — this method is called
|
||||
|
|
@ -2791,7 +2791,7 @@ internal sealed class NavigationEngine
|
|||
// send floods the server. _tier1TurnDir tracks the one active direction.
|
||||
if (_tier1TurnDir != 0 && _host.HasStopMovement)
|
||||
{
|
||||
_host.StopMovement(_tier1TurnDir > 0 ? MotionTurnRight : MotionTurnLeft, 0);
|
||||
_host.StopMovementBy("Nav", _tier1TurnDir > 0 ? MotionTurnRight : MotionTurnLeft, 0);
|
||||
_tier1TurnDir = 0;
|
||||
}
|
||||
}
|
||||
|
|
@ -2850,7 +2850,7 @@ internal sealed class NavigationEngine
|
|||
if (!_host.HasTurnToHeading) return true;
|
||||
if (!TryGetQuaternionHeading(out float curDeg))
|
||||
{
|
||||
_host.TurnToHeading((float)desiredDeg);
|
||||
_host.TurnToHeadingBy("Nav", (float)desiredDeg);
|
||||
return true;
|
||||
}
|
||||
long nowTicks = System.Diagnostics.Stopwatch.GetTimestamp();
|
||||
|
|
@ -2862,7 +2862,7 @@ internal sealed class NavigationEngine
|
|||
double maxStep = Math.Max(10.0, _settings.NavTurnRateDegPerSec) * Math.Max(dt, 0.01);
|
||||
double newHeading = curDeg + Math.Clamp(err, -maxStep, maxStep);
|
||||
if (newHeading >= 360.0) newHeading -= 360.0; else if (newHeading < 0.0) newHeading += 360.0;
|
||||
_host.TurnToHeading((float)newHeading);
|
||||
_host.TurnToHeadingBy("Nav", (float)newHeading);
|
||||
|
||||
double abs = Math.Abs(err);
|
||||
if (_servoTurning) { if (abs <= BigTurnExit) _servoTurning = false; }
|
||||
|
|
|
|||
|
|
@ -159,6 +159,34 @@ public static unsafe class PluginExports
|
|||
}
|
||||
}
|
||||
|
||||
// ── Hot-reload deferral (2026-10-05) ─────────────────────────────────────────
|
||||
// The engine calls this on its reload thread before it tears itself down for a hot reload:
|
||||
// a non-empty text ("in combat (a monster engaged, ...)") makes it wait and ask again, up to
|
||||
// its cap. Fixed signature, const char* (void); null or "" = safe. Optional: an engine that
|
||||
// doesn't know it simply reloads, and a plugin without it never holds a reload. Per-thread
|
||||
// buffer (same reasoning as _snapshotPtr).
|
||||
[ThreadStatic] private static IntPtr _reloadBlockerPtr;
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginReloadBlocker", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static IntPtr ReloadBlocker()
|
||||
{
|
||||
try
|
||||
{
|
||||
string reason = Runtime.Plugin?.ReloadBlocker ?? "";
|
||||
if (reason.Length == 0) return IntPtr.Zero;
|
||||
IntPtr newPtr = Marshal.StringToHGlobalAnsi(reason);
|
||||
IntPtr oldPtr = _reloadBlockerPtr;
|
||||
_reloadBlockerPtr = newPtr;
|
||||
if (oldPtr != IntPtr.Zero)
|
||||
Marshal.FreeHGlobal(oldPtr);
|
||||
return newPtr;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Full-inventory bridge (read-only remote inventory viewer, P1) ───────────
|
||||
// Dedicated export (NOT folded into the 150ms status snapshot) so 100s of items never ride the
|
||||
// hot path. The RynthRemote plugin polls this on its own slower cadence (P2). Per-thread buffer
|
||||
|
|
|
|||
|
|
@ -68,6 +68,7 @@ public sealed partial class RynthAiPlugin
|
|||
ChatLine("[RynthAi] /ra hazard add|del|list|near — mark current cell as lava/acid so patrol avoids it");
|
||||
ChatLine("[RynthAi] /ra jump[swzxc] [heading] [holdtime] — jump with optional face/direction (s=run w=fwd x=back z=strafeL c=strafeR)");
|
||||
ChatLine("[RynthAi] /ra corpseinfo — show corpse range/open diagnostics");
|
||||
ChatLine("[RynthAi] /ra owncorpse [go|stop] — where your corpse is; travel back to it, or stop");
|
||||
ChatLine("[RynthAi] /ra corpsecheck — explain whether a corpse would be looted");
|
||||
ChatLine("[RynthAi] /ra corpseopen — force the nearest corpse open flow");
|
||||
ChatLine("[RynthAi] /ra fellowinfo — show fellowship tracker state");
|
||||
|
|
@ -1209,8 +1210,8 @@ public sealed partial class RynthAiPlugin
|
|||
}
|
||||
|
||||
// Stop any active turn motion so the character doesn't keep spinning
|
||||
Host.SetMotion(0x6500000D, false); // TurnRight
|
||||
Host.SetMotion(0x6500000E, false); // TurnLeft
|
||||
Host.SetMotionBy("Command", 0x6500000D, false); // TurnRight
|
||||
Host.SetMotionBy("Command", 0x6500000E, false); // TurnLeft
|
||||
|
||||
if (!Host.HasGetPlayerPose || !Host.TryGetPlayerPose(out _, out _, out _, out float z, out _, out _, out _, out _))
|
||||
{
|
||||
|
|
@ -1517,9 +1518,38 @@ public sealed partial class RynthAiPlugin
|
|||
FirstMatchUtl = FirstLootRuleFor,
|
||||
FirstMatchNative = FirstLootRuleFor,
|
||||
Added = OnLootRuleAdded,
|
||||
BuiltInKeep = LootBuiltInKeepFor,
|
||||
},
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Why RynthAi's looting takes the item without a loot profile rule, for the "Add to
|
||||
/// loot profile" popup: the looter's own ClassifyItemAgainstProfile as a preview (nothing
|
||||
/// recorded), so the answer is exactly what [LootEval] would tag. An item already in the
|
||||
/// pack that Mana Tap looted earlier says so even when the tap quota is full now.
|
||||
/// </summary>
|
||||
private Loot.LootBuiltInKeep? LootBuiltInKeepFor(uint itemId)
|
||||
{
|
||||
WorldObject? wo = _objectCache?[unchecked((int)itemId)];
|
||||
LegacyUiSettings? settings = _dashboard?.Settings;
|
||||
if (wo == null || settings == null) return null;
|
||||
try
|
||||
{
|
||||
if (ClassifyLootItem(wo, settings, preview: true, out string action, out _, out _, out string builtIn)
|
||||
&& builtIn.Length > 0)
|
||||
return new Loot.LootBuiltInKeep(builtIn, BeforeProfile: action != ManaTapActionLabel);
|
||||
if (_manaStoneManager?.WasLootedForTap(wo.Id) == true)
|
||||
return new Loot.LootBuiltInKeep(
|
||||
"it was looted for Mana Tap, to drain into an empty mana stone - change in the Items panel, Mana Stone Tapping",
|
||||
BeforeProfile: false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Host.Log($"[LootAdd] built-in keep check failed for 0x{itemId:X8}: {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The Loot Editor saved <paramref name="path"/>: drop the cached copies and,
|
||||
/// when it is the loot profile in use, load it again now (its chat line says so).
|
||||
|
|
@ -2121,7 +2151,7 @@ public sealed partial class RynthAiPlugin
|
|||
if (Host.HasForceResetBusyCount)
|
||||
Host.ForceResetBusyCount();
|
||||
if (Host.HasStopCompletely)
|
||||
Host.StopCompletely();
|
||||
Host.StopCompletelyBy("Command");
|
||||
// Reset all tracked counts — engine, plugin, combat, buff
|
||||
_busyCount = 0;
|
||||
_busyCountLastIncrementAt = 0;
|
||||
|
|
@ -2144,7 +2174,7 @@ public sealed partial class RynthAiPlugin
|
|||
|
||||
if (Host.HasCancelAttack) Host.CancelAttack();
|
||||
if (Host.HasChangeCombatMode) Host.ChangeCombatMode(CombatMode.NonCombat);
|
||||
if (Host.HasStopCompletely) Host.StopCompletely();
|
||||
if (Host.HasStopCompletely) Host.StopCompletelyBy("Command");
|
||||
if (Host.HasForceResetBusyCount) Host.ForceResetBusyCount();
|
||||
// The item-action lock itself is not the busy count: AC refuses every use,
|
||||
// equip and move while its pending-item-request slot or attacking flag is
|
||||
|
|
@ -2409,6 +2439,38 @@ public sealed partial class RynthAiPlugin
|
|||
|
||||
private enum GiveItemMatch { Exact, Partial, Regex }
|
||||
|
||||
/// <summary>
|
||||
/// Hands <paramref name="amount"/> of an item to a player or NPC with AC's give action
|
||||
/// (Event_GiveObjectRequest) when the engine has it; MoveItemExternal is move-to-container
|
||||
/// and silently does nothing for an NPC. amount 0 or the whole stack = the whole object.
|
||||
/// </summary>
|
||||
internal bool GiveItem(uint itemId, uint targetId, int amount, int stackSize)
|
||||
{
|
||||
if (Host.HasGiveObjectTo)
|
||||
return Host.GiveObjectTo(itemId, targetId, amount <= 0 || amount >= stackSize ? 0 : amount);
|
||||
return Host.MoveItemExternal(itemId, targetId, Math.Max(1, amount));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Carried items a give may hand over, in pack order: never worn or wielded gear. Walks the
|
||||
/// live inventory, then every known object the client says the player carries (the live walk
|
||||
/// can miss items off AC's main thread, as FindObject notes).
|
||||
/// </summary>
|
||||
private List<WorldObject> GiveCandidates(Func<string, bool> nameMatches)
|
||||
{
|
||||
var found = new List<WorldObject>();
|
||||
var seen = new HashSet<int>();
|
||||
if (_objectCache == null) return found;
|
||||
foreach (var wo in _objectCache.GetDirectInventory(forceRefresh: true))
|
||||
if (nameMatches(wo.Name) && !WorldObjectCache.IsWieldedByPlayer(Host, wo) && seen.Add(wo.Id))
|
||||
found.Add(wo);
|
||||
foreach (var wo in _objectCache.AllKnownObjects())
|
||||
if (!seen.Contains(wo.Id) && nameMatches(wo.Name) && IsCarriedByPlayer(wo.Id)
|
||||
&& !WorldObjectCache.IsWieldedByPlayer(Host, wo) && seen.Add(wo.Id))
|
||||
found.Add(wo);
|
||||
return found;
|
||||
}
|
||||
|
||||
private void HandleGiveCommand(string[] parts, GiveItemMatch itemMatch, bool partialPlayer, bool allItems = false)
|
||||
{
|
||||
if (_objectCache == null) { ChatLine("[RynthAi] Object cache not ready."); return; }
|
||||
|
|
@ -2463,22 +2525,15 @@ public sealed partial class RynthAiPlugin
|
|||
catch { ChatLine($"[RynthAi] Invalid regex: {itemPart}"); return; }
|
||||
}
|
||||
|
||||
// Collect matching inventory stacks
|
||||
var matches = new List<WorldObject>();
|
||||
foreach (var wo in _objectCache.GetDirectInventory(forceRefresh: true))
|
||||
// Collect matching carried stacks (never worn or wielded gear)
|
||||
var matches = GiveCandidates(name => itemMatch switch
|
||||
{
|
||||
// GetDirectInventory includes worn and wielded gear; never give that away.
|
||||
if (WorldObjectCache.IsWieldedByPlayer(Host, wo)) continue;
|
||||
bool hit = itemMatch switch
|
||||
{
|
||||
GiveItemMatch.Exact => string.Equals(wo.Name, itemPart, StringComparison.OrdinalIgnoreCase),
|
||||
GiveItemMatch.Partial => wo.Name.IndexOf(itemPart, StringComparison.OrdinalIgnoreCase) >= 0,
|
||||
GiveItemMatch.Regex => rx!.IsMatch(wo.Name),
|
||||
_ => false,
|
||||
};
|
||||
if (hit) matches.Add(wo);
|
||||
if (matches.Count >= maxCount) break;
|
||||
}
|
||||
GiveItemMatch.Exact => string.Equals(name, itemPart, StringComparison.OrdinalIgnoreCase),
|
||||
GiveItemMatch.Partial => name.IndexOf(itemPart, StringComparison.OrdinalIgnoreCase) >= 0,
|
||||
GiveItemMatch.Regex => rx!.IsMatch(name),
|
||||
_ => false,
|
||||
});
|
||||
if (!allItems && matches.Count > maxCount) matches.RemoveRange(maxCount, matches.Count - maxCount);
|
||||
|
||||
if (matches.Count == 0) { ChatLine($"[RynthAi] No items found matching '{itemPart}'"); return; }
|
||||
|
||||
|
|
@ -2509,7 +2564,8 @@ public sealed partial class RynthAiPlugin
|
|||
}
|
||||
if (gives.Count == 1)
|
||||
{
|
||||
Host.MoveItemExternal((uint)gives[0].Item.Id, (uint)target.Id, gives[0].Amount);
|
||||
GiveItem((uint)gives[0].Item.Id, (uint)target.Id, gives[0].Amount,
|
||||
Math.Max(1, gives[0].Item.Values(LongValueKey.StackCount, 1)));
|
||||
ChatLine($"[RynthAi] Giving {gives[0].Amount} x '{gives[0].Item.Name}' to {target.Name}");
|
||||
}
|
||||
else
|
||||
|
|
@ -2523,7 +2579,7 @@ public sealed partial class RynthAiPlugin
|
|||
{
|
||||
var item = matches[0];
|
||||
int stackSize = Math.Max(1, item.Values(LongValueKey.StackCount, 1));
|
||||
Host.MoveItemExternal((uint)item.Id, (uint)target.Id, stackSize);
|
||||
GiveItem((uint)item.Id, (uint)target.Id, stackSize, stackSize);
|
||||
ChatLine($"[RynthAi] Giving '{item.Name}' to {target.Name}");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
687
Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.OwnCorpse.cs
Normal file
687
Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.OwnCorpse.cs
Normal file
|
|
@ -0,0 +1,687 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.RynthAi.Loot;
|
||||
using RynthCore.Plugin.Shared;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
/// <summary>What <see cref="RynthAiPlugin.MatchOwnDeathCorpse"/> made of a corpse.</summary>
|
||||
internal enum OwnCorpseMatch
|
||||
{
|
||||
/// <summary>Not your death corpse.</summary>
|
||||
No,
|
||||
/// <summary>Named "Corpse of <you>", but its ID (the "Killed by" line) hasn't landed yet.</summary>
|
||||
Pending,
|
||||
/// <summary>Your death corpse.</summary>
|
||||
Yes,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Own-corpse recovery (owner, 2026-10-05: "It needs to loot your corpse and every item on it.
|
||||
/// If it's a setting default to true please").
|
||||
///
|
||||
/// Recover My Corpse (LootOwnCorpse, default on): when your own death corpse is within loot range
|
||||
/// the looter opens it and takes every item on it, one at a time with the normal looter's
|
||||
/// pick-up confirmation, ignoring the loot profile, Loot From, value and salvage rules and the
|
||||
/// weapon-swap free-slot reserve (only "no pack has a slot at all" stops it). It beats any other
|
||||
/// corpse in range but not combat (the arbiter's Looting slot, loot starvation as usual).
|
||||
///
|
||||
/// It is identified as: name exactly "Corpse of <your name>" (ACE names a player's corpse
|
||||
/// "Corpse of " + the player's full name, GM sigil included; character names are unique per
|
||||
/// server, so no other player's corpse can carry it and a pet's corpse carries the pet's name),
|
||||
/// AND an identified LongDesc that is the server's "Killed by X." line with X not you (a death
|
||||
/// corpse is never killed by its own victim, so a namesake monster you killed is not it). The
|
||||
/// corpse's owner (the Victim instance id) is not sent to clients by ACE, so it can't be checked.
|
||||
/// Until the ID lands a corpse with your name is held, never looted by the profile meanwhile.
|
||||
///
|
||||
/// The death spot (position at the death) is remembered and logged, and with Travel Back To My
|
||||
/// Corpse (TravelToOwnCorpse, default off) the bot walks back there with RynthNav after the
|
||||
/// respawn: /rnav go <coords> through the engine's plugin-command broker, the way RynthRemote's
|
||||
/// Travel tab does. RynthNav routes on the map only, so this works for outdoor deaths only.
|
||||
/// RynthNav walks on its own and does not fight, so whenever RynthAi wants the tick (combat,
|
||||
/// buffing, looting, salvage) the walk is stopped and RynthAi does that; it resumes once RynthAi
|
||||
/// is idle again. Gives up on no progress or a timeout, and says why.
|
||||
/// </summary>
|
||||
public sealed partial class RynthAiPlugin
|
||||
{
|
||||
internal const string OwnCorpsePrefix = "Corpse of ";
|
||||
|
||||
// ── Identifying it ───────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Is this your death corpse? Pure (tests call it directly). <paramref name="myName"/> is the
|
||||
/// player object's name as the client has it (with a GM sigil if any, as the corpse name has).
|
||||
/// </summary>
|
||||
internal static OwnCorpseMatch MatchOwnDeathCorpse(string? corpseName, string? myName, string? longDesc)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(myName) || string.IsNullOrEmpty(corpseName))
|
||||
return OwnCorpseMatch.No;
|
||||
if (!string.Equals(corpseName, OwnCorpsePrefix + myName, StringComparison.Ordinal))
|
||||
return OwnCorpseMatch.No;
|
||||
if (string.IsNullOrWhiteSpace(longDesc))
|
||||
return OwnCorpseMatch.Pending;
|
||||
// The server writes exactly "Killed by X." on every corpse it makes for a death.
|
||||
if (!longDesc.TrimStart().StartsWith("Killed by ", StringComparison.OrdinalIgnoreCase))
|
||||
return OwnCorpseMatch.No;
|
||||
string? killer = ExtractCorpseKillerName(longDesc);
|
||||
if (string.IsNullOrWhiteSpace(killer))
|
||||
return OwnCorpseMatch.No;
|
||||
if (NormalizeCharName(killer).Equals(NormalizeCharName(myName), StringComparison.OrdinalIgnoreCase))
|
||||
return OwnCorpseMatch.No; // your own kill of a namesake, not your death corpse
|
||||
return OwnCorpseMatch.Yes;
|
||||
}
|
||||
|
||||
/// <summary>Recover My Corpse is on and this corpse id is your identified death corpse.</summary>
|
||||
private bool IsOwnDeathCorpseId(LegacyUiSettings? settings, int corpseId)
|
||||
{
|
||||
if (settings == null || !settings.LootOwnCorpse || corpseId == 0 || _objectCache == null)
|
||||
return false;
|
||||
WorldObject? corpse = _objectCache[corpseId];
|
||||
if (corpse == null)
|
||||
return false;
|
||||
return MatchOwnDeathCorpse(corpse.Name, GetPlayerNameForLootOwnership(),
|
||||
corpse.Values(StringValueKey.LongDesc, string.Empty)) == OwnCorpseMatch.Yes;
|
||||
}
|
||||
|
||||
// A corpse with your name waiting for its ID: asked again every OwnCorpseIdRetryMs (the
|
||||
// general corpse ID request goes out once per corpse; a lost answer must not strand it).
|
||||
private readonly Dictionary<int, long> _ownCorpseIdRequestedAt = new();
|
||||
private const long OwnCorpseIdRetryMs = 5_000;
|
||||
|
||||
private void RequestOwnCorpseId(int corpseId)
|
||||
{
|
||||
long now = CorpseNowMs;
|
||||
if (!_ownCorpseIdRequestedAt.TryGetValue(corpseId, out long last))
|
||||
{
|
||||
_ownCorpseIdRequestedAt[corpseId] = now; // the general request just went out
|
||||
LootDiag($"[RynthAi] Own corpse: 0x{(uint)corpseId:X8} is named like yours; waiting for its ID to confirm it.");
|
||||
return;
|
||||
}
|
||||
if (now - last < OwnCorpseIdRetryMs || !Host.HasRequestId)
|
||||
return;
|
||||
_ownCorpseIdRequestedAt[corpseId] = now;
|
||||
Host.RequestId(unchecked((uint)corpseId));
|
||||
}
|
||||
|
||||
/// <summary>Your identified death corpse within <paramref name="maxMeters"/> (not completed, not cooling down).</summary>
|
||||
private bool TryFindOwnCorpseInRange(double maxMeters, out WorldObject? corpse)
|
||||
{
|
||||
corpse = null;
|
||||
var settings = _dashboard?.Settings;
|
||||
if (settings == null || !settings.LootOwnCorpse || _objectCache == null || _playerId == 0)
|
||||
return false;
|
||||
string myName = GetPlayerNameForLootOwnership();
|
||||
if (myName.Length == 0)
|
||||
return false;
|
||||
string wanted = OwnCorpsePrefix + myName;
|
||||
long now = CorpseNowMs;
|
||||
int playerId = unchecked((int)_playerId);
|
||||
double best = double.MaxValue;
|
||||
foreach (WorldObject candidate in _objectCache.GetLandscapeObjects())
|
||||
{
|
||||
if (candidate.ObjectClass != AcObjectClass.Corpse || !string.Equals(candidate.Name, wanted, StringComparison.Ordinal))
|
||||
continue;
|
||||
if (_completedCorpses.ContainsKey(candidate.Id))
|
||||
continue;
|
||||
if (_corpseCooldownUntil.TryGetValue(candidate.Id, out long until) && until > now)
|
||||
continue;
|
||||
if (!EvaluateCorpseLootDecision(candidate).IsOwnDeathCorpse)
|
||||
continue;
|
||||
double d = _objectCache.Distance(playerId, candidate.Id);
|
||||
if (d > maxMeters || d >= best)
|
||||
continue;
|
||||
best = d;
|
||||
corpse = candidate;
|
||||
}
|
||||
return corpse != null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The pack gates (Stop Looting When Pack Full, the weapon-swap reserve) don't hold your own
|
||||
/// corpse back: only "no pack has a free slot at all" does, since then nothing can move.
|
||||
/// </summary>
|
||||
private bool OwnCorpseBypassesPackGate(LegacyUiSettings settings, double maxMeters)
|
||||
=> settings.LootOwnCorpse && !IsPackFull() && TryFindOwnCorpseInRange(maxMeters, out _);
|
||||
|
||||
// ── Recovering it ────────────────────────────────────────────────────────
|
||||
|
||||
private int _ownRecoveryCorpseId; // the own corpse this recovery is about (kept across pauses)
|
||||
private int _ownRecoveryTotal; // items on it when first opened
|
||||
private int _ownRecoveryTaken; // confirmed moved into a pack
|
||||
private int _ownRecoveryRounds; // opens that ended with items that would not move
|
||||
private readonly HashSet<int> _ownCorpseNoRoomSaid = new();
|
||||
|
||||
internal const int OwnCorpseMaxAbandons = 5; // timeouts before it is written off
|
||||
private const int OwnCorpseMaxRounds = 3; // reopen rounds for items that would not move
|
||||
private const long OwnCorpseNoRoomPauseMs = 60_000; // no pack has a slot: look again after this
|
||||
private const long OwnCorpseRetryPauseMs = 30_000; // items would not move: reopen after this
|
||||
private const long OwnCorpseBusyWaitMs = 1_000; // hold a pickup this long behind a busy count
|
||||
private const long OwnCorpseSettleMs = 1_000; // after the last pickup, before judging what is left
|
||||
|
||||
/// <summary>
|
||||
/// One tick of recovering your own corpse (it is open and its contents are listed): the next
|
||||
/// item still on it is moved into a pack; the normal pick-up confirmation in
|
||||
/// TickPendingCorpsePickup confirms it. Then the corpse is closed and completed.
|
||||
/// </summary>
|
||||
private void TickOwnCorpseRecovery(LegacyUiSettings settings, int corpseId, List<WorldObject> items, long openAge, long now)
|
||||
{
|
||||
if (items.Count == 0)
|
||||
{
|
||||
if (openAge < Math.Max(200, settings.LootEmptyCorpseMs))
|
||||
return;
|
||||
if (_ownRecoveryCorpseId != corpseId)
|
||||
BeginOwnCorpseRecovery(corpseId, 0);
|
||||
FinishOwnCorpseRecovery(corpseId, items);
|
||||
return;
|
||||
}
|
||||
|
||||
if (_ownRecoveryCorpseId != corpseId)
|
||||
BeginOwnCorpseRecovery(corpseId, items.Count);
|
||||
|
||||
WorldObject? next = null;
|
||||
int remaining = 0;
|
||||
foreach (WorldObject item in items)
|
||||
{
|
||||
if (item.Id == 0 || _processedCorpseItems.Contains(item.Id))
|
||||
continue;
|
||||
remaining++;
|
||||
next ??= item;
|
||||
}
|
||||
|
||||
if (next == null)
|
||||
{
|
||||
// Every item was tried. Let the last confirmed move leave the corpse's list first.
|
||||
if (_lastLootActionAt != 0 && now - _lastLootActionAt < OwnCorpseSettleMs)
|
||||
return;
|
||||
FinishOwnCorpseRecovery(corpseId, items);
|
||||
return;
|
||||
}
|
||||
|
||||
// One item at a time, as the looter does: wait out a busy count from our last action,
|
||||
// but only briefly (CheckBusyTimeout clears a leaked one).
|
||||
if (_busyCount > 0 && _lastLootActionAt != 0 && now - _lastLootActionAt < OwnCorpseBusyWaitMs)
|
||||
return;
|
||||
|
||||
string name = string.IsNullOrWhiteSpace(next.Name) ? $"0x{(uint)next.Id:X8}" : next.Name;
|
||||
_currentLootItemId = next.Id;
|
||||
Host.SelectItem(unchecked((uint)next.Id));
|
||||
LootDiag($"[RynthAi] Own corpse: taking 0x{(uint)next.Id:X8} '{name}' ({remaining} left on 0x{(uint)corpseId:X8}).");
|
||||
|
||||
LootPickupResult pickup = SendLootPickup(next.Id, name, corpseId);
|
||||
if (pickup == LootPickupResult.NoRoom || pickup == LootPickupResult.Refused)
|
||||
return; // SendLootPickup paused the corpse / left the item
|
||||
if (pickup != LootPickupResult.Moved && pickup != LootPickupResult.Used)
|
||||
{
|
||||
if (_busyCount > 0)
|
||||
return;
|
||||
LootDiag($"[RynthAi] Own corpse: the move of 0x{(uint)next.Id:X8} was not sent.");
|
||||
if (IncrementCorpseItemAttempt(next.Id) >= 3)
|
||||
_processedCorpseItems.Add(next.Id);
|
||||
ResetCurrentLootItem();
|
||||
_lastLootActionAt = now;
|
||||
return;
|
||||
}
|
||||
|
||||
_currentLootItemMovePending = true;
|
||||
_currentLootItemMoveRequestedAt = now;
|
||||
_currentLootItemMoveAttempts = 1;
|
||||
_currentLootItemActionLabel = "Recover";
|
||||
_currentLootItemName = name;
|
||||
_currentLootItemIsSalvage = false; // never salvage your own things
|
||||
_lastLootActionAt = now;
|
||||
_corpseTargetSince = now; // progress: a long recovery must not hit the corpse timeout
|
||||
}
|
||||
|
||||
private void BeginOwnCorpseRecovery(int corpseId, int itemCount)
|
||||
{
|
||||
_ownRecoveryCorpseId = corpseId;
|
||||
_ownRecoveryTotal = itemCount;
|
||||
_ownRecoveryTaken = 0;
|
||||
_ownRecoveryRounds = 0;
|
||||
_ownCorpseNoRoomSaid.Remove(corpseId);
|
||||
// Anything the profile looter passed over before the corpse was known to be yours
|
||||
// (opened by hand before its ID landed) is taken now; items already moved have left it.
|
||||
_processedCorpseItems.Clear();
|
||||
_corpseItemAttempts.Clear();
|
||||
if (itemCount > 0)
|
||||
OwnCorpseSay($"[RynthAi] Own corpse: recovering {itemCount} item{(itemCount == 1 ? "" : "s")}.");
|
||||
}
|
||||
|
||||
/// <summary>A pick-up from your corpse was confirmed (ConfirmCurrentLootItemMoved).</summary>
|
||||
private void NoteOwnCorpseItemRecovered(long now)
|
||||
{
|
||||
_ownRecoveryTaken++;
|
||||
_corpseTargetSince = now;
|
||||
}
|
||||
|
||||
private void FinishOwnCorpseRecovery(int corpseId, List<WorldObject> items)
|
||||
{
|
||||
var left = items.Where(i => i.Id != 0).ToList();
|
||||
if (left.Count == 0)
|
||||
{
|
||||
OwnCorpseSay(_ownRecoveryTaken > 0
|
||||
? $"[RynthAi] Own corpse: recovered everything ({_ownRecoveryTaken} item{(_ownRecoveryTaken == 1 ? "" : "s")})."
|
||||
: "[RynthAi] Own corpse: there was nothing on it to recover.");
|
||||
MarkDeathSpotRecovered();
|
||||
_ownRecoveryCorpseId = 0;
|
||||
MarkCorpseCompleted(corpseId);
|
||||
return;
|
||||
}
|
||||
|
||||
_ownRecoveryRounds++;
|
||||
string names = string.Join(", ", left.Take(5).Select(i => string.IsNullOrWhiteSpace(i.Name) ? $"0x{(uint)i.Id:X8}" : i.Name))
|
||||
+ (left.Count > 5 ? ", ..." : "");
|
||||
if (_ownRecoveryRounds >= OwnCorpseMaxRounds)
|
||||
{
|
||||
OwnCorpseSay($"[RynthAi] Own corpse: recovered {_ownRecoveryTaken}; {left.Count} item(s) would not move after {_ownRecoveryRounds} tries ({names}). Take them by hand.");
|
||||
_ownRecoveryCorpseId = 0;
|
||||
MarkCorpseCompleted(corpseId);
|
||||
return;
|
||||
}
|
||||
OwnCorpseSay($"[RynthAi] Own corpse: {left.Count} item(s) would not move ({names}); trying again in {OwnCorpseRetryPauseMs / 1000}s.");
|
||||
PauseOwnCorpse(corpseId, OwnCorpseRetryPauseMs, "own corpse: retry later");
|
||||
}
|
||||
|
||||
/// <summary>No pack has a slot for the next item: close the corpse and look again later (never write it off).</summary>
|
||||
private void PauseOwnCorpseNoRoom(int corpseId, string itemName)
|
||||
{
|
||||
LootDiag($"[RynthAi] Own corpse: no pack has room for '{itemName}'; pausing {OwnCorpseNoRoomPauseMs / 1000}s.");
|
||||
if (_ownCorpseNoRoomSaid.Add(corpseId))
|
||||
{
|
||||
ChatLine("[RynthAi] Own corpse: your packs are full. Make room and it carries on (it looks again every minute).");
|
||||
WorldObjectCache.WarnPackFull(Host, "own corpse recovery paused, no pack has a free slot");
|
||||
}
|
||||
PauseOwnCorpse(corpseId, OwnCorpseNoRoomPauseMs, "own corpse: no room");
|
||||
}
|
||||
|
||||
/// <summary>Closes the corpse and holds it for <paramref name="ms"/>, without the completed mark.</summary>
|
||||
private void PauseOwnCorpse(int corpseId, long ms, string why)
|
||||
{
|
||||
ResetCurrentLootItem();
|
||||
CloseCorpseContainer(corpseId, why);
|
||||
if (_openedContainerId == corpseId)
|
||||
{
|
||||
_openedContainerId = 0;
|
||||
_openedContainerAt = 0;
|
||||
_openedContainerInventoryObservedAt = 0;
|
||||
}
|
||||
MarkCorpseCooldown(corpseId, (int)ms);
|
||||
ResetCorpseTarget();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The move for an item on your corpse. A pack (or a foci) only fits the main pack, and its
|
||||
/// contents come with it (ACE never drops packs on death, but a slippery one can); everything
|
||||
/// else goes where the looter puts things (LootPickup).
|
||||
/// </summary>
|
||||
private LootPickupResult SendOwnCorpsePickup(int itemId, out uint destination)
|
||||
{
|
||||
destination = 0;
|
||||
WorldObject? item = _objectCache?[itemId];
|
||||
if (item != null && item.ObjectClass is AcObjectClass.Container or AcObjectClass.Foci
|
||||
&& Host.HasMoveItemExternal && _playerId != 0)
|
||||
{
|
||||
destination = _playerId;
|
||||
return Host.MoveItemExternal(unchecked((uint)itemId), _playerId, 0) ? LootPickupResult.Moved : LootPickupResult.Failed;
|
||||
}
|
||||
return LootPickup.Send(Host, _objectCache, unchecked((uint)itemId), _playerId, out destination);
|
||||
}
|
||||
|
||||
private void OwnCorpseSay(string text)
|
||||
{
|
||||
Log(text);
|
||||
ChatLine(text);
|
||||
}
|
||||
|
||||
// ── Where you died ───────────────────────────────────────────────────────
|
||||
|
||||
internal sealed class OwnDeathSpot
|
||||
{
|
||||
public uint Cell; // 0 when only the server's chat line gave the place
|
||||
public float X, Y, Z;
|
||||
public double Ns, Ew;
|
||||
public bool HasCoords;
|
||||
public bool Outdoors; // outdoor landblock cell: map coordinates mean something
|
||||
public DateTime AtUtc;
|
||||
public bool NothingDropped; // "You have retained all your items..."
|
||||
public bool Recovered;
|
||||
public string Where
|
||||
{
|
||||
get
|
||||
{
|
||||
if (Cell == 0)
|
||||
return FormatMapCoords(Ns, Ew);
|
||||
string cell = $"landblock 0x{Cell >> 16:X4}, cell 0x{Cell & 0xFFFF:X4}";
|
||||
return HasCoords && Outdoors
|
||||
? $"{FormatMapCoords(Ns, Ew)} ({cell})"
|
||||
: $"{cell} at ({X:0.0}, {Y:0.0}, {Z:0.0}), indoors";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private OwnDeathSpot? _deathSpot;
|
||||
internal OwnDeathSpot? DeathSpot => _deathSpot;
|
||||
|
||||
/// <summary>The death edge (CheckPlayerDeath): where the player stands is where the corpse will be.</summary>
|
||||
private void RecordDeathSpot()
|
||||
{
|
||||
if (_ownCorpseTravel != OwnCorpseTravelState.None)
|
||||
EndOwnCorpseTravel("you died again", sayInChat: false);
|
||||
|
||||
if (!Host.TryGetPlayerPose(out uint cell, out float x, out float y, out float z, out _, out _, out _, out _) || cell == 0)
|
||||
{
|
||||
_deathSpot = null;
|
||||
Log("[RynthAi] Death spot: no player position to remember.");
|
||||
return;
|
||||
}
|
||||
bool outdoors = (cell & 0xFFFF) < 0x100;
|
||||
bool hasCoords = NavCoordinateHelper.TryConvertPoseToCoords(cell, x, y, out double ns, out double ew);
|
||||
_deathSpot = new OwnDeathSpot
|
||||
{
|
||||
Cell = cell, X = x, Y = y, Z = z, Ns = ns, Ew = ew,
|
||||
HasCoords = hasCoords, Outdoors = outdoors, AtUtc = DateTime.UtcNow,
|
||||
};
|
||||
OwnCorpseSay($"[RynthAi] Your corpse is at {_deathSpot.Where}.");
|
||||
}
|
||||
|
||||
private static readonly Regex CorpseLocatedRx = new(
|
||||
@"Your corpse is located at \(\s*(\d+(?:\.\d+)?)\s*([NS])\s*,\s*(\d+(?:\.\d+)?)\s*([EW])\s*\)",
|
||||
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
|
||||
|
||||
/// <summary>The server's death lines: where the corpse is (outdoor deaths), or that nothing dropped.</summary>
|
||||
private void OnOwnCorpseChat(string text)
|
||||
{
|
||||
if (text.IndexOf("You do not need to recover your corpse", StringComparison.OrdinalIgnoreCase) >= 0)
|
||||
{
|
||||
if (_deathSpot != null && (DateTime.UtcNow - _deathSpot.AtUtc).TotalMinutes < 2)
|
||||
{
|
||||
_deathSpot.NothingDropped = true;
|
||||
Log("[RynthAi] Own corpse: the server says nothing dropped; no need to go back for it.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
Match m = CorpseLocatedRx.Match(text);
|
||||
if (!m.Success)
|
||||
return;
|
||||
double ns = double.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture) * (m.Groups[2].Value.Equals("S", StringComparison.OrdinalIgnoreCase) ? -1 : 1);
|
||||
double ew = double.Parse(m.Groups[3].Value, CultureInfo.InvariantCulture) * (m.Groups[4].Value.Equals("W", StringComparison.OrdinalIgnoreCase) ? -1 : 1);
|
||||
if (_deathSpot != null && (DateTime.UtcNow - _deathSpot.AtUtc).TotalMinutes < 2)
|
||||
{
|
||||
Log($"[RynthAi] Own corpse: the server confirms {FormatMapCoords(ns, ew)} (remembered {_deathSpot.Where}).");
|
||||
return;
|
||||
}
|
||||
// No position at the death edge (or it was missed): the server's line is the death spot.
|
||||
_deathSpot = new OwnDeathSpot { Ns = ns, Ew = ew, HasCoords = true, Outdoors = true, AtUtc = DateTime.UtcNow };
|
||||
OwnCorpseSay($"[RynthAi] Your corpse is at {FormatMapCoords(ns, ew)} (from the server).");
|
||||
}
|
||||
|
||||
private void MarkDeathSpotRecovered()
|
||||
{
|
||||
if (_deathSpot != null)
|
||||
_deathSpot.Recovered = true;
|
||||
}
|
||||
|
||||
internal static string FormatMapCoords(double ns, double ew)
|
||||
=> Math.Abs(ns).ToString("0.00", CultureInfo.InvariantCulture) + (ns >= 0 ? "N" : "S") + ", "
|
||||
+ Math.Abs(ew).ToString("0.00", CultureInfo.InvariantCulture) + (ew >= 0 ? "E" : "W");
|
||||
|
||||
/// <summary>/ra owncorpse [go|stop]: where your corpse is, the two settings, the travel state.</summary>
|
||||
private void HandleOwnCorpseCommand(string[] parts)
|
||||
{
|
||||
var s = _dashboard?.Settings;
|
||||
string sub = parts.Length >= 3 ? parts[2].Trim().ToLowerInvariant() : string.Empty;
|
||||
if (sub == "stop")
|
||||
{
|
||||
if (_ownCorpseTravel == OwnCorpseTravelState.None) ChatLine("[RynthAi] Own corpse: not travelling.");
|
||||
else EndOwnCorpseTravel("stopped by /ra owncorpse stop");
|
||||
return;
|
||||
}
|
||||
if (sub == "go")
|
||||
{
|
||||
StartOwnCorpseTravel(manual: true);
|
||||
return;
|
||||
}
|
||||
|
||||
var spot = _deathSpot;
|
||||
if (spot == null)
|
||||
ChatLine("[RynthAi] Own corpse: no death remembered this session.");
|
||||
else
|
||||
{
|
||||
int mins = (int)(DateTime.UtcNow - spot.AtUtc).TotalMinutes;
|
||||
string state = spot.Recovered ? ", recovered" : spot.NothingDropped ? ", nothing dropped" : string.Empty;
|
||||
ChatLine($"[RynthAi] Your corpse is at {spot.Where}, died {mins} min ago{state}.");
|
||||
}
|
||||
if (s != null)
|
||||
ChatLine($"[RynthAi] Recover My Corpse: {(s.LootOwnCorpse ? "on" : "off")}, Travel Back To My Corpse: {(s.TravelToOwnCorpse ? "on" : "off")}; travel: {OwnCorpseTravelText()}. /ra owncorpse go|stop");
|
||||
}
|
||||
|
||||
// ── Travelling back (TravelToOwnCorpse) ─────────────────────────────────
|
||||
|
||||
internal enum OwnCorpseTravelState { None, Waiting, Travelling, Paused, Arrived }
|
||||
|
||||
private OwnCorpseTravelState _ownCorpseTravel;
|
||||
private long _travelStartedAt;
|
||||
private long _travelIdleSince;
|
||||
private long _travelBestAt;
|
||||
private long _travelArrivedAt;
|
||||
private double _travelBestDistance;
|
||||
private bool _ownCorpseTravelManual;
|
||||
|
||||
internal const long OwnCorpseTravelTimeoutMs = 15 * 60_000; // whole trip, fights included
|
||||
internal const long OwnCorpseTravelNoProgressMs = 120_000; // walking without getting 10 m closer
|
||||
internal const double OwnCorpseTravelProgressMeters = 10.0;
|
||||
internal const double OwnCorpseArriveMeters = 6.0; // at the spot: stop walking, look for it
|
||||
internal const long OwnCorpseArriveSearchMs = 20_000; // at the spot with no corpse in range
|
||||
internal const long OwnCorpseTravelResumeMs = 1_500; // idle this long before walking (again)
|
||||
internal const string RynthNavPlugin = "RynthNav";
|
||||
|
||||
/// <summary>While travelling back, RynthAi's own nav route stays parked (the arbiter's wantNav).</summary>
|
||||
private bool OwnCorpseTravelHoldsNav => _ownCorpseTravel != OwnCorpseTravelState.None;
|
||||
|
||||
private string OwnCorpseTravelText() => _ownCorpseTravel switch
|
||||
{
|
||||
OwnCorpseTravelState.None => "off",
|
||||
OwnCorpseTravelState.Waiting => "waiting for a quiet moment",
|
||||
OwnCorpseTravelState.Travelling => "walking (RynthNav)",
|
||||
OwnCorpseTravelState.Paused => "paused while RynthAi works",
|
||||
OwnCorpseTravelState.Arrived => "at the spot, looking for the corpse",
|
||||
_ => _ownCorpseTravel.ToString(),
|
||||
};
|
||||
|
||||
/// <summary>The respawn edge (HoldForDeath): start the trip back when Travel Back To My Corpse is on.</summary>
|
||||
private void OnRespawnedForOwnCorpse()
|
||||
{
|
||||
var s = _dashboard?.Settings;
|
||||
if (s == null || !s.TravelToOwnCorpse)
|
||||
return;
|
||||
StartOwnCorpseTravel(manual: false);
|
||||
}
|
||||
|
||||
private void StartOwnCorpseTravel(bool manual)
|
||||
{
|
||||
var s = _dashboard?.Settings;
|
||||
var spot = _deathSpot;
|
||||
if (s == null)
|
||||
return;
|
||||
if (spot == null)
|
||||
{
|
||||
if (manual) ChatLine("[RynthAi] Own corpse: no death remembered this session, so nowhere to go.");
|
||||
return;
|
||||
}
|
||||
if (spot.Recovered)
|
||||
{
|
||||
if (manual) ChatLine("[RynthAi] Own corpse: already recovered.");
|
||||
return;
|
||||
}
|
||||
if (spot.NothingDropped && !manual)
|
||||
{
|
||||
Log("[RynthAi] Own corpse: nothing dropped on it; not travelling back.");
|
||||
return;
|
||||
}
|
||||
if (!s.IsMacroRunning)
|
||||
{
|
||||
OwnCorpseSay("[RynthAi] Own corpse: the macro is off; not travelling back (start it and use /ra owncorpse go).");
|
||||
return;
|
||||
}
|
||||
if (!spot.Outdoors || !spot.HasCoords)
|
||||
{
|
||||
OwnCorpseSay($"[RynthAi] Own corpse: you died indoors ({spot.Where}); travelling back only works outdoors, where RynthNav can route on the map.");
|
||||
return;
|
||||
}
|
||||
if (!Host.HasSendPluginCommand)
|
||||
{
|
||||
OwnCorpseSay("[RynthAi] Own corpse: this engine can't send RynthNav commands; not travelling back.");
|
||||
return;
|
||||
}
|
||||
|
||||
long now = Environment.TickCount64;
|
||||
_ownCorpseTravel = OwnCorpseTravelState.Waiting;
|
||||
_ownCorpseTravelManual = manual;
|
||||
_travelStartedAt = now;
|
||||
_travelIdleSince = 0;
|
||||
_travelArrivedAt = 0;
|
||||
_travelBestAt = now;
|
||||
_travelBestDistance = double.MaxValue;
|
||||
OwnCorpseSay($"[RynthAi] Own corpse: travelling back to {FormatMapCoords(spot.Ns, spot.Ew)} with RynthNav once nothing else needs doing.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Every tick after the arbiter's decision. Walks (RynthNav) only while RynthAi is idle; stops
|
||||
/// the walk the moment RynthAi wants the tick (combat, buffing, looting, salvage, a vendor or
|
||||
/// trade session, crafting) and resumes after. Ends when your corpse is in loot range.
|
||||
/// </summary>
|
||||
private void TickOwnCorpseTravel(LegacyUiSettings s)
|
||||
{
|
||||
if (_ownCorpseTravel == OwnCorpseTravelState.None)
|
||||
return;
|
||||
|
||||
long now = Environment.TickCount64;
|
||||
var spot = _deathSpot;
|
||||
if (spot == null) { EndOwnCorpseTravel("no death spot"); return; }
|
||||
if (!s.TravelToOwnCorpse && !_ownCorpseTravelManual) { EndOwnCorpseTravel("Travel Back To My Corpse was turned off"); return; }
|
||||
if (!s.IsMacroRunning) { EndOwnCorpseTravel("the macro stopped"); return; }
|
||||
if (spot.Recovered) { EndOwnCorpseTravel("your corpse is recovered", sayInChat: false); return; }
|
||||
|
||||
double lootRange = GetCorpseApproachRangeMaxMeters(s);
|
||||
if (s.EnableLooting && TryFindOwnCorpseInRange(lootRange, out WorldObject? corpse) && corpse != null)
|
||||
{
|
||||
EndOwnCorpseTravel($"your corpse (0x{(uint)corpse.Id:X8}) is in loot range; recovering it");
|
||||
return;
|
||||
}
|
||||
if (now - _travelStartedAt > OwnCorpseTravelTimeoutMs)
|
||||
{
|
||||
EndOwnCorpseTravel($"gave up: not there after {OwnCorpseTravelTimeoutMs / 60_000} min");
|
||||
return;
|
||||
}
|
||||
|
||||
double d = DistanceToDeathSpotMeters(spot);
|
||||
if (!double.IsNaN(d) && d <= OwnCorpseArriveMeters)
|
||||
{
|
||||
if (_ownCorpseTravel != OwnCorpseTravelState.Arrived)
|
||||
{
|
||||
if (_ownCorpseTravel == OwnCorpseTravelState.Travelling) SendRynthNav("stop");
|
||||
_ownCorpseTravel = OwnCorpseTravelState.Arrived;
|
||||
_travelArrivedAt = now;
|
||||
Log($"[RynthAi] Own corpse: at the death spot ({d:0.0} m); looking for the corpse.");
|
||||
}
|
||||
if (now - _travelArrivedAt > OwnCorpseArriveSearchMs)
|
||||
EndOwnCorpseTravel(s.EnableLooting
|
||||
? "gave up: at the spot, but no corpse of yours in loot range (it may have decayed, or lie further than loot range)"
|
||||
: "at the spot; Enable Looting is off, so it is not recovered");
|
||||
return;
|
||||
}
|
||||
|
||||
if (OwnCorpseTravelBlockedBy(out string by))
|
||||
{
|
||||
if (_ownCorpseTravel == OwnCorpseTravelState.Travelling)
|
||||
{
|
||||
SendRynthNav("stop");
|
||||
Log($"[RynthAi] Own corpse: travel paused for {by}.");
|
||||
}
|
||||
if (_ownCorpseTravel != OwnCorpseTravelState.Waiting)
|
||||
_ownCorpseTravel = OwnCorpseTravelState.Paused;
|
||||
_travelIdleSince = 0;
|
||||
_travelBestAt = now; // a fight is not "no progress"
|
||||
return;
|
||||
}
|
||||
|
||||
if (_ownCorpseTravel != OwnCorpseTravelState.Travelling)
|
||||
{
|
||||
if (_travelIdleSince == 0) _travelIdleSince = now;
|
||||
if (now - _travelIdleSince < OwnCorpseTravelResumeMs)
|
||||
return;
|
||||
bool resume = _ownCorpseTravel == OwnCorpseTravelState.Paused || _ownCorpseTravel == OwnCorpseTravelState.Arrived;
|
||||
if (!SendRynthNav("go " + FormatMapCoords(spot.Ns, spot.Ew)))
|
||||
{
|
||||
EndOwnCorpseTravel("gave up: RynthNav isn't loaded in this client", sendStop: false);
|
||||
return;
|
||||
}
|
||||
Log($"[RynthAi] Own corpse: {(resume ? "resuming the walk" : "walking")} to {FormatMapCoords(spot.Ns, spot.Ew)}{(double.IsNaN(d) ? "" : $" ({d:0} m away)")}.");
|
||||
_ownCorpseTravel = OwnCorpseTravelState.Travelling;
|
||||
_travelArrivedAt = 0;
|
||||
_travelBestAt = now;
|
||||
_travelBestDistance = double.IsNaN(d) ? double.MaxValue : d;
|
||||
return;
|
||||
}
|
||||
|
||||
if (!double.IsNaN(d) && (_travelBestDistance == double.MaxValue || d < _travelBestDistance - OwnCorpseTravelProgressMeters))
|
||||
{
|
||||
_travelBestDistance = d;
|
||||
_travelBestAt = now;
|
||||
}
|
||||
else if (now - _travelBestAt > OwnCorpseTravelNoProgressMs)
|
||||
{
|
||||
EndOwnCorpseTravel($"gave up: no closer in {OwnCorpseTravelNoProgressMs / 1000}s (RynthNav may have no route or navmesh here; /rnav here says)");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>RynthAi wants the tick for something, so RynthNav must not be walking.</summary>
|
||||
private bool OwnCorpseTravelBlockedBy(out string by)
|
||||
{
|
||||
by = string.Empty;
|
||||
if (_activity != BotActivity.Idle) by = ActivityArbiter.ToBotAction(_activity);
|
||||
else if (_autoVendor?.HoldsBot == true) by = "AutoVendor";
|
||||
else if (_autoTrade?.HoldsBot == true) by = "AutoTrade";
|
||||
else if (_missileCraftingManager?.IsCrafting == true) by = "ammo crafting";
|
||||
else if (Host.HasIsPortaling && Host.IsPortaling()) by = "portal space";
|
||||
return by.Length > 0;
|
||||
}
|
||||
|
||||
private void EndOwnCorpseTravel(string why, bool sayInChat = true, bool sendStop = true)
|
||||
{
|
||||
if (sendStop && _ownCorpseTravel == OwnCorpseTravelState.Travelling)
|
||||
SendRynthNav("stop");
|
||||
_ownCorpseTravel = OwnCorpseTravelState.None;
|
||||
_ownCorpseTravelManual = false;
|
||||
_travelIdleSince = 0;
|
||||
_travelArrivedAt = 0;
|
||||
string line = $"[RynthAi] Own corpse: travel back ended: {why}.";
|
||||
if (sayInChat) OwnCorpseSay(line); else Log(line);
|
||||
// RynthAi's own nav carries on from the nearest waypoint, not one from before the death.
|
||||
_navigationEngine?.ResumeFromNearestWaypoint();
|
||||
}
|
||||
|
||||
private bool SendRynthNav(string command)
|
||||
{
|
||||
bool sent = Host.HasSendPluginCommand && Host.SendPluginCommand(RynthNavPlugin, "rnav", command);
|
||||
Log($"[RynthAi] Own corpse: /rnav {command} -> RynthNav {(sent ? "ok" : "NOT delivered")}.");
|
||||
return sent;
|
||||
}
|
||||
|
||||
/// <summary>Metres from the player to the death spot by map coordinates (NaN without a position).</summary>
|
||||
private double DistanceToDeathSpotMeters(OwnDeathSpot spot)
|
||||
{
|
||||
if (!spot.HasCoords)
|
||||
return double.NaN;
|
||||
if (!Host.TryGetPlayerPose(out uint cell, out float x, out float y, out _, out _, out _, out _, out _) || cell == 0)
|
||||
return double.NaN;
|
||||
if (!NavCoordinateHelper.TryConvertPoseToCoords(cell, x, y, out double ns, out double ew))
|
||||
return double.NaN;
|
||||
// 0.1 of a map coordinate is 24 m.
|
||||
return Math.Sqrt(Math.Pow(ns - spot.Ns, 2) + Math.Pow(ew - spot.Ew, 2)) * 240.0;
|
||||
}
|
||||
}
|
||||
|
|
@ -29,6 +29,8 @@ public sealed partial class RynthAiPlugin
|
|||
{
|
||||
_deathSeen = true;
|
||||
Log("[RynthAi] Death detected (health 0).");
|
||||
try { RecordDeathSpot(); } // where the corpse will be (RynthAiPlugin.OwnCorpse.cs)
|
||||
catch (Exception ex) { Log($"[RynthAi] Death spot not recorded: {ex.Message}"); }
|
||||
if (s.StopMacroOnDeath && s.IsMacroRunning)
|
||||
{
|
||||
HandleMacroRunCommand("stop", Array.Empty<string>());
|
||||
|
|
@ -82,7 +84,11 @@ public sealed partial class RynthAiPlugin
|
|||
_navigationEngine?.Stop();
|
||||
}
|
||||
else
|
||||
{
|
||||
Log("[RynthAi] Respawned — resuming.");
|
||||
try { OnRespawnedForOwnCorpse(); } // Travel Back To My Corpse
|
||||
catch (Exception ex) { Log($"[RynthAi] Own corpse travel not started: {ex.Message}"); }
|
||||
}
|
||||
}
|
||||
return hold;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ using RynthCore.Plugin.RynthAi.Vendor;
|
|||
using RynthCore.PluginCore;
|
||||
using RynthCore.Loot;
|
||||
using RynthCore.Loot.VTank;
|
||||
using RynthCore.Plugin.Shared;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
|
|
@ -64,14 +65,12 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("RynthAi");
|
||||
internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi(PluginModule.HandWrittenVersion);
|
||||
|
||||
/// <summary>
|
||||
/// Oldest engine RynthAi runs on. Players get plugin updates automatically but engine
|
||||
/// updates only when they click, so this stays at 66 while newer calls are feature-
|
||||
/// detected (Host.HasVendorTrade for API v67 vendor trading: AutoVendor reports "needs a
|
||||
/// RynthCore update" without it). The SDK default is CurrentApiVersion, which would make
|
||||
/// every SDK bump refuse older engines. Raise it only for a call RynthAi can't run without.
|
||||
/// </summary>
|
||||
public override uint MinimumApiVersion => 66;
|
||||
// Oldest engine RynthAi runs on: RynthPluginMinEngineApi in the csproj (66), which is both its
|
||||
// manifest's minEngineApi and, through RynthPluginBase.MinimumApiVersion's default, its own
|
||||
// runtime check. Players get plugin updates automatically but engine updates only when they
|
||||
// click, so it stays at 66 while newer calls are feature-detected (Host.HasVendorTrade for API
|
||||
// v67 vendor trading: AutoVendor reports "needs a RynthCore update" without it). Raise it only
|
||||
// for a call RynthAi can't run without.
|
||||
|
||||
private LegacyDashboardRenderer? _dashboard;
|
||||
|
||||
|
|
@ -105,7 +104,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
private ActivityArbiter? _arbiter; // STEP 1: shadow-mode only (ACTIVITY_ARBITER_PLAN.md)
|
||||
private PlayerVitalsCache _vitals = new();
|
||||
private uint _playerId;
|
||||
private int _vitalsTickCounter;
|
||||
private long _lastVitalsPollAt;
|
||||
private const long VitalsPollMs = 100; // see the poll in OnTick
|
||||
private bool _initialized;
|
||||
private bool _loginComplete;
|
||||
private bool _patrolOnLoginPending;
|
||||
|
|
@ -153,6 +153,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
private readonly HashSet<uint> _seenMonstersThisSession = new();
|
||||
private int _creatureSaveTickCounter;
|
||||
private int _settingsSaveTickCounter;
|
||||
private int _mapBakeTickCounter;
|
||||
private int _settingsLoadRetryCounter;
|
||||
|
||||
public override int Initialize()
|
||||
|
|
@ -167,6 +168,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
// Every use goes through Host.UseFor (Plugins/Shared/UseAudit.cs): one log line
|
||||
// each, and no automatic door/corpse use while the macro is off.
|
||||
RynthCore.Plugin.Shared.UseAudit.Reset("RynthAi", () => _dashboard?.Settings.IsMacroRunning == true);
|
||||
// Every movement call is logged with its subsystem (Plugins/Shared/MoveAudit.cs).
|
||||
RynthCore.Plugin.Shared.MoveAudit.Reset();
|
||||
_objectCache = new WorldObjectCache(Host); // must exist before CreateObject events fire during login
|
||||
// Items we use (or use something on) get re-identified before a meta reads them.
|
||||
// ObjectUsed is a static event and Shutdown never unsubscribes: when the engine
|
||||
|
|
@ -242,9 +245,82 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
{
|
||||
Log("RynthAi: logout — tearing down session.");
|
||||
try { _dashboard?.SaveSettings(); } catch { }
|
||||
// A real logout: the next OnLoginComplete is a fresh login, not a hot reload.
|
||||
ClearInGameMarker();
|
||||
TeardownSession();
|
||||
}
|
||||
|
||||
// ── Hot reload vs real login (2026-10-05) ──────────────────────────────────────────────
|
||||
// The engine calls OnLoginComplete on a real login AND on a freshly (re)loaded plugin while
|
||||
// the character is already in game. After the engine reload at 13:42:55 RynthAi treated it as
|
||||
// a login: the buff refresh waited 5.8 s for two equal reads of an enchantment registry that
|
||||
// was already complete. A process-wide environment variable (it outlives the plugin's load
|
||||
// context and a NativeAOT plugin's runtime alike, and dies with the client) names the player
|
||||
// whose live buffs were read in this client; a real logout clears it.
|
||||
private const string InGameMarkerVar = "RYNTHAI_INGAME_PLAYER";
|
||||
private bool _inGameMarkerSet;
|
||||
|
||||
private static string InGameMarkerValue(uint playerId) => $"{Environment.ProcessId}:{playerId:X8}";
|
||||
|
||||
/// <summary>At login: true when this player's live buffs were already read in this client
|
||||
/// and no logout came since (an engine or plugin hot reload).</summary>
|
||||
private static bool IsCarriedOverSession(uint playerId)
|
||||
{
|
||||
if (playerId == 0) return false;
|
||||
try { return Environment.GetEnvironmentVariable(InGameMarkerVar) == InGameMarkerValue(playerId); }
|
||||
catch { return false; }
|
||||
}
|
||||
|
||||
/// <summary>Each tick until done: once the login refresh has a trusted snapshot, mark this
|
||||
/// player as in game for a later hot reload.</summary>
|
||||
private void NoteCarriedOverSessionReady()
|
||||
{
|
||||
if (_inGameMarkerSet || _buffManager == null || !_buffManager.LiveBuffsReady || _playerId == 0) return;
|
||||
_inGameMarkerSet = true;
|
||||
try { Environment.SetEnvironmentVariable(InGameMarkerVar, InGameMarkerValue(_playerId)); } catch { }
|
||||
}
|
||||
|
||||
private void ClearInGameMarker()
|
||||
{
|
||||
_inGameMarkerSet = false;
|
||||
try { Environment.SetEnvironmentVariable(InGameMarkerVar, null); } catch { }
|
||||
}
|
||||
|
||||
// ── Reload deferral (2026-10-05) ───────────────────────────────────────────────────────
|
||||
// The engine asks every plugin before a hot reload (RynthPluginReloadBlocker) and waits while
|
||||
// one answers with a reason. Computed here on the pump thread each tick; the export reads the
|
||||
// last text from the engine's reload thread. A text older than ReloadBlockerStaleMs (the tick
|
||||
// stopped, a logout) counts as safe, so a stalled plugin can't hold a reload.
|
||||
private volatile string _reloadBlocker = "";
|
||||
private long _reloadBlockerAt;
|
||||
private const long ReloadBlockerStaleMs = 5000;
|
||||
|
||||
private void UpdateReloadBlocker()
|
||||
{
|
||||
var s = _dashboard?.Settings;
|
||||
string reason = "";
|
||||
if (s != null && _buffManager != null)
|
||||
{
|
||||
string line = _buffManager.HealLineNow(out int hp, out int lineValue);
|
||||
reason = ReloadSafety.Reason(s.IsMacroRunning, _combatManager?.HasEngageableTarget == true,
|
||||
line, hp, lineValue, _buffManager.CastInFlightName);
|
||||
}
|
||||
_reloadBlocker = reason;
|
||||
Interlocked.Exchange(ref _reloadBlockerAt, Environment.TickCount64);
|
||||
}
|
||||
|
||||
/// <summary>For the RynthPluginReloadBlocker export (any thread): why a hot reload now would
|
||||
/// hurt, or "" when it is safe.</summary>
|
||||
internal string ReloadBlocker
|
||||
{
|
||||
get
|
||||
{
|
||||
if (!_loginComplete) return "";
|
||||
if (Environment.TickCount64 - Interlocked.Read(ref _reloadBlockerAt) > ReloadBlockerStaleMs) return "";
|
||||
return _reloadBlocker;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases every component that depends on being in-world. Idempotent.
|
||||
/// Used by both Shutdown (full plugin unload) and OnLogout (session-only).
|
||||
|
|
@ -493,6 +569,13 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
_weaponSwapGate ??= new WeaponSwapGate();
|
||||
|
||||
_buffManager = new BuffManager(Host, _dashboard.Settings, _spellManager, _vitals);
|
||||
_inGameMarkerSet = false;
|
||||
if (IsCarriedOverSession(_playerId))
|
||||
{
|
||||
// A hot reload: the registry is complete, and heals must not wait on a login refresh.
|
||||
_buffManager.CarriedOverSession = true;
|
||||
Log("RynthAi: hot reload - this character was already in game in this client; the buff refresh trusts its first read.");
|
||||
}
|
||||
_buffManager.SetWeaponSwapGate(_weaponSwapGate);
|
||||
_buffManager.SetCastResolvedCallback(OnBuffCastResolved);
|
||||
_buffManager.SetCharacterSkills(_charSkills);
|
||||
|
|
@ -525,6 +608,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
_combatManager = new CombatManager(Host, _dashboard.Settings, _objectCache!, _spellManager);
|
||||
_combatManager.SetWeaponSwapGate(_weaponSwapGate);
|
||||
_combatManager.SetStaleBusyCallback(OnCombatBusyStale);
|
||||
_buffManager?.SetStaleBusyCallback(OnCombatBusyStale); // a heal ahead of a leftover busy count
|
||||
if (_buffManager != null)
|
||||
_buffManager.OffhandStowed = id => _combatManager?.NoteOffhandStowed(id);
|
||||
_combatManager.SetCharacterSkills(_charSkills);
|
||||
|
|
@ -651,7 +735,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
|
||||
_navigationEngine?.Stop();
|
||||
if (Host.HasStopCompletely)
|
||||
Host.StopCompletely();
|
||||
Host.StopCompletelyBy("Arbiter");
|
||||
|
||||
// Combat taking the tick invalidates any in-progress door interaction.
|
||||
// The legacy cascade did this on the combat edge only; keep it there.
|
||||
|
|
@ -1262,6 +1346,14 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
_settingsSaveTickCounter = 0;
|
||||
_dashboard?.TickAutoSave();
|
||||
}
|
||||
// Dungeon floor plans on disk for DrakRemote (StatusAgent /map), whether or not a
|
||||
// map panel is open: one pose read about twice a second; the bake itself runs once
|
||||
// per landblock on a pool thread.
|
||||
if (_loginComplete && ++_mapBakeTickCounter >= 30)
|
||||
{
|
||||
_mapBakeTickCounter = 0;
|
||||
_dashboard?.TickDungeonMapBake();
|
||||
}
|
||||
// Pick up an external Monster Editor save (monsters.json watcher). This used
|
||||
// to run only inside the legacy dashboard's Render(), which the engine no
|
||||
// longer calls, so edits waited for the next login. A flag check when idle.
|
||||
|
|
@ -1317,9 +1409,16 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
// One bot per client (Decal bridge): VTank's macro started -> ours stops, before
|
||||
// anything below can move, attack, cast or buff this tick.
|
||||
if (_dashboard?.Settings is { } yieldSettings) TickVTankYield(yieldSettings);
|
||||
if (++_vitalsTickCounter >= 30)
|
||||
// Player vitals: AC sends none of its own health through OnUpdateHealth (that is the
|
||||
// 0x01C0 health-of-a-target message), so this read is how the bot learns health
|
||||
// dropped. It ran every 30th tick: ~1 s at a background client's 30 fps, 1.5-3 s on a
|
||||
// slower or busier PC, added to every heal at random (2026-10-05, "heals sometimes
|
||||
// late"). The engine's snapshot is a locked struct copy kept current by its vitals
|
||||
// hook, so read it every VitalsPollMs instead.
|
||||
long vitalsNow = Environment.TickCount64;
|
||||
if (vitalsNow - _lastVitalsPollAt >= VitalsPollMs)
|
||||
{
|
||||
_vitalsTickCounter = 0;
|
||||
_lastVitalsPollAt = vitalsNow;
|
||||
if (Host.HasGetPlayerVitals &&
|
||||
Host.TryGetPlayerVitals(out uint hp, out uint maxHp, out uint st, out uint maxSt, out uint mp, out uint maxMp))
|
||||
{
|
||||
|
|
@ -1342,6 +1441,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
if (diag) Host.Log("[RynthAi] OnTick: before buffManager");
|
||||
_buffManager?.OnHeartbeat();
|
||||
if (diag) Host.Log("[RynthAi] OnTick: after buffManager");
|
||||
NoteCarriedOverSessionReady();
|
||||
UpdateReloadBlocker();
|
||||
|
||||
var settings = _dashboard?.Settings;
|
||||
if (settings == null)
|
||||
|
|
@ -1370,7 +1471,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
{
|
||||
int busyBefore = Host.HasGetBusyState ? Host.GetBusyState() : -1;
|
||||
if (Host.HasCancelAttack) Host.CancelAttack();
|
||||
if (Host.HasStopCompletely) Host.StopCompletely();
|
||||
if (Host.HasStopCompletely) Host.StopCompletelyBy("MacroStop");
|
||||
if (busyBefore > 0 && Host.HasForceResetBusyCount) Host.ForceResetBusyCount();
|
||||
_busyCount = 0;
|
||||
_busyCountLastIncrementAt = 0;
|
||||
|
|
@ -1499,8 +1600,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
bool followActive = (settings.FollowMode && settings.FollowTargetId != 0)
|
||||
|| (settings.CurrentRoute != null && settings.CurrentRoute.RouteType == NavRouteType.Follow
|
||||
&& settings.CurrentRoute.FollowTargetName.Length > 0);
|
||||
// Travelling back to your corpse (RynthNav walks): RynthAi's own route waits.
|
||||
bool wantNav = settings.IsMacroRunning && settings.EnableNavigation
|
||||
&& (routeLoaded || followActive);
|
||||
&& (routeLoaded || followActive)
|
||||
&& !OwnCorpseTravelHoldsNav;
|
||||
// Loot starvation: a lootable corpse in range has waited LootStarveMs behind
|
||||
// combat and no monster is within LootStarveCloseYards. A busy spawn always
|
||||
// has a monster inside MonsterRange, so without this corpses waited until
|
||||
|
|
@ -1515,6 +1618,13 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
lootStarved: lootStarved);
|
||||
_activity = _arbiter.Apply(in inputs, settings);
|
||||
_lootStarveTurn = lootStarved && _activity == BotActivity.Looting;
|
||||
// Display only: what the Buffing slot is doing (ActivityArbiter.DisplayLabel),
|
||||
// and the decision for [HealLatency]'s "arbiter gave the tick to" part.
|
||||
if (_buffManager != null)
|
||||
{
|
||||
settings.BuffingLabel = _activity == BotActivity.Buffing ? _buffManager.BuffingLabel : BuffManager.LabelBuffing;
|
||||
_buffManager.ArbiterActivity = ActivityArbiter.ToBotAction(_activity);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
|
@ -1531,6 +1641,19 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
}
|
||||
}
|
||||
|
||||
// ── Travel back to your corpse (TravelToOwnCorpse) ─────────────────
|
||||
// After the decision, ahead of every early return below: RynthNav walks only
|
||||
// while the arbiter says Idle, and is stopped the moment RynthAi wants the tick.
|
||||
try { TickOwnCorpseTravel(settings); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (Environment.TickCount64 - _lastOwnCorpseTravelErrorLogAt > 10_000)
|
||||
{
|
||||
_lastOwnCorpseTravelErrorLogAt = Environment.TickCount64;
|
||||
Host.Log($"[RynthAi] Own corpse travel tick threw: {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
// ── Meta Manager ─────────────────────────────────────────────────
|
||||
// Here, ahead of every early return below (buffing, vendor, crafting),
|
||||
// so its timers and polls keep running; it reads _activity to wait for
|
||||
|
|
@ -1819,6 +1942,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
}
|
||||
private long _lastArbiterErrorLogAt = -100_000;
|
||||
private long _lastMetaScheduleErrorLogAt = -100_000;
|
||||
private long _lastOwnCorpseTravelErrorLogAt = -100_000;
|
||||
private long _lastTickErrorLogAt = -100_000;
|
||||
|
||||
private bool _lootInspectMode = true; // always on; /ra lootcheck off to disable
|
||||
|
|
@ -1877,6 +2001,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
_metaManager?.HandleChat(text, chatType);
|
||||
_questTracker?.OnChatLine(text);
|
||||
CheckChatForSafetyStops(text);
|
||||
try { OnOwnCorpseChat(text); } catch { }
|
||||
}
|
||||
|
||||
// ACE sends GameEventKillerNotification (0x01AD) to the killer at the
|
||||
|
|
@ -2845,7 +2970,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
if ((DateTime.UtcNow - _lastGiveAt).TotalMilliseconds < intervalMs) return;
|
||||
|
||||
var (itemId, targetId, stackSize) = _pendingGives.Dequeue();
|
||||
Host.MoveItemExternal(itemId, targetId, stackSize);
|
||||
// The queued amount is what to hand over; GiveItem gives the whole object when it is
|
||||
// the whole stack (amount 0) and uses AC's real give action, which an NPC accepts.
|
||||
int whole = _objectCache?[unchecked((int)itemId)] is WorldObject wo ? Math.Max(1, wo.Values(LongValueKey.StackCount, 1)) : stackSize;
|
||||
GiveItem(itemId, targetId, stackSize, whole);
|
||||
_lastGiveAt = DateTime.UtcNow;
|
||||
|
||||
if (_pendingGives.Count == 0)
|
||||
|
|
@ -2926,6 +3054,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
case "corpseinfo": HandleCorpseInfoCommand(); break;
|
||||
case "corpsecheck": HandleCorpseCheckCommand(parts); break;
|
||||
case "corpseopen": HandleCorpseOpenCommand(); break;
|
||||
case "owncorpse":
|
||||
case "mycorpse": HandleOwnCorpseCommand(parts); break;
|
||||
case "fellow":
|
||||
case "fellowship": HandleFellowshipCommand(parts); break;
|
||||
case "fellowinfo": HandleFellowshipInfoCommand(); break;
|
||||
|
|
|
|||
|
|
@ -15,8 +15,19 @@
|
|||
<RootNamespace>RynthCore.Plugin.RynthAi</RootNamespace>
|
||||
<AssemblyName>RynthCore.Plugin.RynthAi</AssemblyName>
|
||||
<Platforms>x86</Platforms>
|
||||
<!-- Plugin manifest (embedded in the DLL; Plugins\Directory.Build.targets). minEngineApi is the
|
||||
highest API use NOT behind a Has*/version check. Every call above v66 (vendor v67, plugin interfaces v68, use/weenie results and wield v70, trade v72, instance ids v73, VTank state v74, CloseContainer v76) is behind a Has*/version check with a fallback. -->
|
||||
<RynthPluginMinEngineApi>66</RynthPluginMinEngineApi>
|
||||
<RynthPluginDescription>The bot: combat, buffs, looting, navigation routes and metas.</RynthPluginDescription>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- Plugins it can use when they are loaded (looked up at run time; optional, so they never block or reorder it). -->
|
||||
<RynthPluginDependency Include="RynthNav" Optional="true" />
|
||||
<RynthPluginDependency Include="RynthLua" Optional="true" />
|
||||
<RynthPluginDependency Include="RynthNet" Optional="true" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- Interfaces shared with other RynthSuite plugins (RynthLua uses RynthAi.Script, RynthNet RynthAi.Status). -->
|
||||
<Compile Include="..\Shared\RynthAiScriptApi.cs" Link="Shared\RynthAiScriptApi.cs" />
|
||||
|
|
@ -26,6 +37,8 @@
|
|||
<Compile Include="..\Shared\RynthNavPathApi.cs" Link="Shared\RynthNavPathApi.cs" />
|
||||
<!-- One logged, guarded way to use an object (who used what, and why). -->
|
||||
<Compile Include="..\Shared\UseAudit.cs" Link="Shared\UseAudit.cs" />
|
||||
<!-- Movement calls logged with the subsystem that sent them (stuck-cast diagnosis, 2026-10-05). -->
|
||||
<Compile Include="..\Shared\MoveAudit.cs" Link="Shared\MoveAudit.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
|
|
|||
|
|
@ -76,7 +76,7 @@ public sealed partial class RynthAiPlugin
|
|||
{
|
||||
w.WriteStartObject();
|
||||
w.WriteBoolean("macro", st.IsMacroRunning);
|
||||
w.WriteString("action", st.BotAction ?? "");
|
||||
w.WriteString("action", ActivityArbiter.DisplayLabel(st.BotAction, st.BuffingLabel)); // display (RynthNet)
|
||||
w.WriteString("state", st.CurrentState ?? "");
|
||||
w.WriteBoolean("combat", st.EnableCombat);
|
||||
w.WriteBoolean("buff", st.EnableBuffing);
|
||||
|
|
|
|||
|
|
@ -117,6 +117,22 @@ public sealed partial class RynthAiPlugin
|
|||
// through to HandleMtCommand returning false → "Unrecognized /ub".
|
||||
int sp = fullCommand.IndexOf(' ');
|
||||
|
||||
// /ub give[p] [count] <item> to <target>: UtilityBelt gives EVERY matching carried item
|
||||
// (Tom, 2026-10-05: "/ub give ... should give every item that matches the name"), unless
|
||||
// a count is given. It used to fall through to /mt give, which hands over only the first.
|
||||
// Targets match partially, as /mt give always did. give = exact item, givep = partial item.
|
||||
if (sp > 0 && cmd is "give" or "givep")
|
||||
{
|
||||
string rest = fullCommand.Substring(sp + cmd.Length + 1).TrimStart();
|
||||
string first = rest.Split(' ', 2)[0];
|
||||
bool counted = int.TryParse(first, out int n) && n > 0;
|
||||
string verb = cmd == "givep"
|
||||
? (counted ? "givepp" : "giveapp")
|
||||
: (counted ? "givexp" : "giveaxp");
|
||||
HandleRaCommand("/ra " + verb + " " + rest);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Verbs /mt doesn't implement but /ra does — route to the /ra dispatcher
|
||||
// (VTank-meta migration). "/ub follow X" → "/ra follow X"; myquests → /ra
|
||||
// quest-flag refresh.
|
||||
|
|
|
|||
|
|
@ -337,7 +337,7 @@ internal sealed class AutoVendorManager
|
|||
_openAttempts = 1;
|
||||
_openNextAt = Now() + 250; // UB fudges the first attempt to ~250 ms after the command
|
||||
_opening = true;
|
||||
if (_host.HasSetAutoRun) _host.SetAutoRun(false);
|
||||
if (_host.HasSetAutoRun) _host.SetAutoRunBy("Vendor", false);
|
||||
_host.Log($"[RynthAi] AutoVendor: attempting to open vendor {vendor.Name}");
|
||||
}
|
||||
|
||||
|
|
@ -959,9 +959,9 @@ internal sealed class AutoVendorManager
|
|||
private void CancelUse()
|
||||
{
|
||||
if (_host.HasTurnToHeading && _host.TryGetPlayerHeading(out float h))
|
||||
_host.TurnToHeading((h + 359f) % 360f);
|
||||
_host.TurnToHeadingBy("Vendor", (h + 359f) % 360f);
|
||||
else if (_host.HasStopCompletely)
|
||||
_host.StopCompletely();
|
||||
_host.StopCompletelyBy("Vendor");
|
||||
}
|
||||
|
||||
private WorldObject? FindVendor(string target, bool partial)
|
||||
|
|
|
|||
|
|
@ -15,6 +15,9 @@
|
|||
<RootNamespace>RynthCore.Plugin.RynthChat</RootNamespace>
|
||||
<AssemblyName>RynthCore.Plugin.RynthChat</AssemblyName>
|
||||
<Platforms>x86</Platforms>
|
||||
<!-- Plugin manifest (embedded; see Plugins\Directory.Build.targets). Nothing above the SDK baseline. -->
|
||||
<RynthPluginMinEngineApi>66</RynthPluginMinEngineApi>
|
||||
<RynthPluginDescription>A chat window that sorts messages into tabs.</RynthPluginDescription>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
|
|
|||
|
|
@ -22,6 +22,10 @@
|
|||
<RootNamespace>RynthCore.Plugin.RynthInventory</RootNamespace>
|
||||
<AssemblyName>RynthCore.Plugin.RynthInventory</AssemblyName>
|
||||
<Platforms>x86</Platforms>
|
||||
<!-- Plugin manifest (embedded in the DLL; Plugins\Directory.Build.targets). minEngineApi is the
|
||||
highest API use NOT behind a Has*/version check. Script windows (v71, HasUi) draw the search window and instance ids (v73) fall back to ownership info; below v71 it still scans and saves (/ginv status), as with ImGui off. -->
|
||||
<RynthPluginMinEngineApi>66</RynthPluginMinEngineApi>
|
||||
<RynthPluginDescription>Search every character's items.</RynthPluginDescription>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
|
|
|||
|
|
@ -15,8 +15,17 @@
|
|||
<RootNamespace>RynthCore.Plugin.RynthLua</RootNamespace>
|
||||
<AssemblyName>RynthCore.Plugin.RynthLua</AssemblyName>
|
||||
<Platforms>x86</Platforms>
|
||||
<!-- Plugin manifest (embedded in the DLL; Plugins\Directory.Build.targets). minEngineApi is the
|
||||
highest API use NOT behind a Has*/version check. Vendor v67, the RynthAi bridge v68, live ids v69, action results v70, script windows v71, trade v72 and instance ids v73 are all guarded; scripts run without them (views.Available is false below v71). -->
|
||||
<RynthPluginMinEngineApi>66</RynthPluginMinEngineApi>
|
||||
<RynthPluginDescription>Lua scripting for metas and your own scripts.</RynthPluginDescription>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- Plugins it can use when they are loaded (looked up at run time; optional, so they never block or reorder it). -->
|
||||
<RynthPluginDependency Include="RynthAi" Optional="true" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginCore\RynthCore.PluginCore.csproj" />
|
||||
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" />
|
||||
|
|
|
|||
|
|
@ -15,6 +15,10 @@
|
|||
<RootNamespace>RynthCore.Plugin.RynthNav</RootNamespace>
|
||||
<AssemblyName>RynthCore.Plugin.RynthNav</AssemblyName>
|
||||
<Platforms>x86</Platforms>
|
||||
<!-- Plugin manifest (embedded in the DLL; Plugins\Directory.Build.targets). minEngineApi is the
|
||||
highest API use NOT behind a Has*/version check. Live object ids (v69) and WieldItem (v70) are behind Has* checks; without them portal avoidance/aiming and wand wielding fall back. -->
|
||||
<RynthPluginMinEngineApi>66</RynthPluginMinEngineApi>
|
||||
<RynthPluginDescription>Walks you to coordinates and towns, with route planning and the Atlas. Downloads its map (about 540 MB).</RynthPluginDescription>
|
||||
<!-- Publish straight to the launcher-registered home (mirrors RynthVision). -->
|
||||
<PublishDir>C:\Games\RynthSuite\RynthNav\</PublishDir>
|
||||
</PropertyGroup>
|
||||
|
|
|
|||
|
|
@ -15,8 +15,17 @@
|
|||
<RootNamespace>RynthCore.Plugin.RynthNet</RootNamespace>
|
||||
<AssemblyName>RynthCore.Plugin.RynthNet</AssemblyName>
|
||||
<Platforms>x86</Platforms>
|
||||
<!-- Plugin manifest (embedded in the DLL; Plugins\Directory.Build.targets). minEngineApi is the
|
||||
highest API use NOT behind a Has*/version check. The RynthAi status lookup (GetPluginInterface, v68) is guarded; networking needs nothing above v66. -->
|
||||
<RynthPluginMinEngineApi>66</RynthPluginMinEngineApi>
|
||||
<RynthPluginDescription>Lets the RynthCore clients on this PC talk to each other: shared commands, vitals, positions and bot state.</RynthPluginDescription>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- Plugins it can use when they are loaded (looked up at run time; optional, so they never block or reorder it). -->
|
||||
<RynthPluginDependency Include="RynthAi" Optional="true" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginCore\RynthCore.PluginCore.csproj" />
|
||||
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" />
|
||||
|
|
|
|||
|
|
@ -20,6 +20,10 @@
|
|||
<RootNamespace>RynthCore.Plugin.RynthOracle</RootNamespace>
|
||||
<AssemblyName>RynthCore.Plugin.RynthOracle</AssemblyName>
|
||||
<Platforms>x86</Platforms>
|
||||
<!-- Plugin manifest (embedded in the DLL; Plugins\Directory.Build.targets). minEngineApi is the
|
||||
highest API use NOT behind a Has*/version check. Script windows (v71, HasUi) draw its window and titles/server info (v75) are guarded with fallbacks; below v71 it runs without a window (/ro status), as on an engine with ImGui off. -->
|
||||
<RynthPluginMinEngineApi>66</RynthPluginMinEngineApi>
|
||||
<RynthPluginDescription>Quests, character, titles and leaderboards.</RynthPluginDescription>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
|
|
|||
|
|
@ -15,6 +15,10 @@
|
|||
<RootNamespace>RynthCore.Plugin.RynthTracker</RootNamespace>
|
||||
<AssemblyName>RynthCore.Plugin.RynthTracker</AssemblyName>
|
||||
<Platforms>x86</Platforms>
|
||||
<!-- Plugin manifest (embedded in the DLL; Plugins\Directory.Build.targets). minEngineApi is the
|
||||
highest API use NOT behind a Has*/version check. Nothing above the v66 baseline. -->
|
||||
<RynthPluginMinEngineApi>66</RynthPluginMinEngineApi>
|
||||
<RynthPluginDescription>Kills, experience and luminance per hour for each session.</RynthPluginDescription>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
|
|
|||
|
|
@ -15,6 +15,10 @@
|
|||
<RootNamespace>RynthCore.Plugin.RynthVision</RootNamespace>
|
||||
<AssemblyName>RynthCore.Plugin.RynthVision</AssemblyName>
|
||||
<Platforms>x86</Platforms>
|
||||
<!-- Plugin manifest (embedded in the DLL; Plugins\Directory.Build.targets). minEngineApi is the
|
||||
highest API use NOT behind a Has*/version check. Only the v60/v61 Nav3D calls, behind HasNav3DTriangle. -->
|
||||
<RynthPluginMinEngineApi>66</RynthPluginMinEngineApi>
|
||||
<RynthPluginDescription>Shows unclimbable slopes, impassable water and your radar range in the world.</RynthPluginDescription>
|
||||
<!-- Publish straight to the plugin's launcher-registered home so a bare
|
||||
`dotnet publish` lands where the engine hot-reloads it. Build still
|
||||
uses bin\; only publish is redirected. Deploy-RynthCore.ps1 points its
|
||||
|
|
|
|||
136
Plugins/Shared/MoveAudit.cs
Normal file
136
Plugins/Shared/MoveAudit.cs
Normal file
|
|
@ -0,0 +1,136 @@
|
|||
// ============================================================================
|
||||
// RynthSuite - Plugins/Shared/MoveAudit.cs
|
||||
// Movement calls with a caller tag: host.SetAutoRunBy("Nav", true) and friends.
|
||||
// Linked into the plugins that move the character, like UseAudit.cs.
|
||||
//
|
||||
// Why (2026-10-05, Drakkon's stuck casts on DreamWeave): a movement packet sent
|
||||
// while a cast winds up can cancel the cast, or leave the server holding it open.
|
||||
// The engine logged only one movement call in eight and never said who sent it,
|
||||
// so "which subsystem sent SetAutoRun during Buffing" could not be answered.
|
||||
// Every call is now one log line:
|
||||
//
|
||||
// [Move] RynthAi/Nav SetAutoRun(False)
|
||||
//
|
||||
// Identical calls from the same subsystem in a row (the nav servo turns every
|
||||
// tick; any angle counts as identical for turns) are counted instead of written
|
||||
// one by one, and the count goes out with the next line that is written (the
|
||||
// next different call, or the next repeat after RepeatWindowMs):
|
||||
//
|
||||
// [Move] RynthAi/Arbiter StopCompletely() (+14 more TurnToHeading, last 230.5 before this, over 480 ms)
|
||||
//
|
||||
// The engine logs the same calls (with the plugin's name) behind its own move
|
||||
// trace switch; this line adds the subsystem, which only the plugin knows.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace RynthCore.Plugin.Shared;
|
||||
|
||||
internal static class MoveAudit
|
||||
{
|
||||
/// <summary>Off = the calls go through without a line. On by default.</summary>
|
||||
public static volatile bool Enabled = true;
|
||||
|
||||
/// <summary>The plugin's name in every line (UseAudit.PluginName is set at Init too).</summary>
|
||||
public static string PluginName => UseAudit.PluginName;
|
||||
|
||||
/// <summary>Clock (ms); tests replace it.</summary>
|
||||
public static Func<long> NowMs = () => Environment.TickCount64;
|
||||
|
||||
// Identical calls closer than this to the last WRITTEN line are only counted.
|
||||
private const long RepeatWindowMs = 1000;
|
||||
|
||||
private static readonly object Gate = new();
|
||||
private static string _lastKey = "";
|
||||
private static long _lastWrittenMs = long.MinValue;
|
||||
private static int _repeats;
|
||||
private static string _repeatLastArg = "";
|
||||
private static long _repeatFirstMs;
|
||||
|
||||
public static bool SetAutoRunBy(this RynthCoreHost host, string who, bool on)
|
||||
{
|
||||
Note(host, who, "SetAutoRun", on ? "True" : "False", collapseByKindOnly: false);
|
||||
return host.SetAutoRun(on);
|
||||
}
|
||||
|
||||
public static bool StopCompletelyBy(this RynthCoreHost host, string who)
|
||||
{
|
||||
Note(host, who, "StopCompletely", "", collapseByKindOnly: false);
|
||||
return host.StopCompletely();
|
||||
}
|
||||
|
||||
public static bool SetMotionBy(this RynthCoreHost host, string who, uint motion, bool on)
|
||||
{
|
||||
Note(host, who, "SetMotion", $"0x{motion:X8}, {(on ? "True" : "False")}", collapseByKindOnly: false);
|
||||
return host.SetMotion(motion, on);
|
||||
}
|
||||
|
||||
public static bool DoMovementBy(this RynthCoreHost host, string who, uint motion, float speed, int holdKey)
|
||||
{
|
||||
Note(host, who, "DoMovement", $"0x{motion:X8}, {speed:0.##}, {holdKey}", collapseByKindOnly: false);
|
||||
return host.DoMovement(motion, speed, holdKey);
|
||||
}
|
||||
|
||||
public static bool StopMovementBy(this RynthCoreHost host, string who, uint motion, int holdKey)
|
||||
{
|
||||
Note(host, who, "StopMovement", $"0x{motion:X8}, {holdKey}", collapseByKindOnly: false);
|
||||
return host.StopMovement(motion, holdKey);
|
||||
}
|
||||
|
||||
/// <summary>A heading snap. Successive turns from one subsystem collapse whatever the angle.</summary>
|
||||
public static bool TurnToHeadingBy(this RynthCoreHost host, string who, float headingDegrees)
|
||||
{
|
||||
Note(host, who, "TurnToHeading", headingDegrees.ToString("0.0", System.Globalization.CultureInfo.InvariantCulture), collapseByKindOnly: true);
|
||||
return host.TurnToHeading(headingDegrees);
|
||||
}
|
||||
|
||||
/// <summary>Writes (or counts) one call. Internal for the tests.</summary>
|
||||
internal static string? Note(RynthCoreHost host, string who, string call, string arg, bool collapseByKindOnly)
|
||||
{
|
||||
if (!Enabled) return null;
|
||||
string? line = null;
|
||||
lock (Gate)
|
||||
{
|
||||
long now = NowMs();
|
||||
string key = collapseByKindOnly ? $"{who}|{call}" : $"{who}|{call}({arg})";
|
||||
if (key == _lastKey && now - _lastWrittenMs < RepeatWindowMs)
|
||||
{
|
||||
if (_repeats == 0) _repeatFirstMs = now;
|
||||
_repeats++;
|
||||
_repeatLastArg = arg;
|
||||
return null;
|
||||
}
|
||||
|
||||
string more = _repeats > 0
|
||||
? $" (+{_repeats} more {RepeatName()} before this, over {now - _repeatFirstMs} ms)"
|
||||
: "";
|
||||
line = $"[Move] {PluginName}/{who} {call}({arg}){more}";
|
||||
_lastKey = key;
|
||||
_lastWrittenMs = now;
|
||||
_repeats = 0;
|
||||
_repeatLastArg = "";
|
||||
}
|
||||
try { host.Log(line); } catch { }
|
||||
return line;
|
||||
}
|
||||
|
||||
private static string RepeatName()
|
||||
{
|
||||
int bar = _lastKey.IndexOf('|');
|
||||
string last = bar >= 0 ? _lastKey.Substring(bar + 1) : _lastKey;
|
||||
return _lastKey.EndsWith(")", StringComparison.Ordinal) ? last : $"{last}, last {_repeatLastArg}";
|
||||
}
|
||||
|
||||
/// <summary>Back to a fresh load (Init, tests).</summary>
|
||||
public static void Reset()
|
||||
{
|
||||
lock (Gate)
|
||||
{
|
||||
_lastKey = "";
|
||||
_lastWrittenMs = long.MinValue;
|
||||
_repeats = 0;
|
||||
_repeatLastArg = "";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -166,6 +166,12 @@ public sealed class LootEditItemDraft
|
|||
public int InsertAt { get; set; } = -1;
|
||||
public int RuleCount { get; set; }
|
||||
public string OrderNote { get; set; } = string.Empty;
|
||||
/// <summary>
|
||||
/// Why RynthAi's own looting takes the item whatever the profile says, or empty: one of
|
||||
/// its built-in keeps (Learn unknown spells, mana stones, Mana Tap), with where to change
|
||||
/// it (2026-10-05). Also appended to OrderNote, which every engine's popup shows.
|
||||
/// </summary>
|
||||
public string BuiltInReason { get; set; } = string.Empty;
|
||||
public List<string> Notes { get; set; } = new();
|
||||
/// <summary>item_add went through; Message says what was added where.</summary>
|
||||
public bool Added { get; set; }
|
||||
|
|
|
|||
|
|
@ -1,8 +1,59 @@
|
|||
// Ported ACE code with a null-returning public API that RynthAi, RynthJuice and
|
||||
// RynthVision already depend on; annotating it would add warnings in every caller.
|
||||
// ============================================================================
|
||||
// RynthCore.TerrainData - DatDatabase.cs
|
||||
// Read-only access to Asheron's Call .dat archives (client_portal.dat,
|
||||
// client_cell_1.dat, ...). Written for RynthCore (MIT) on 2026-10-05.
|
||||
//
|
||||
// Written from the dat container format as it is publicly documented, with
|
||||
// Chorizite's DatReaderWriter (MIT, notice below) used as the format reference:
|
||||
// - file header at byte 0x140: magic, block size, file size, data set,
|
||||
// subset, free head / tail / count, then the byte offset of the root
|
||||
// B-tree node (all little-endian uint32);
|
||||
// - storage is fixed-size blocks; a block's first uint32 is the byte offset
|
||||
// of the next block of the same chain (0 ends the chain), the remaining
|
||||
// BlockSize - 4 bytes are payload;
|
||||
// - the directory is a B-tree whose nodes are stored as block chains: 62
|
||||
// uint32 child offsets, a uint32 entry count (at most 61), then the
|
||||
// entries, 24 bytes each: flags/version, id, byte offset of the file's
|
||||
// first block, size, timestamp, iteration. Entries are sorted by id,
|
||||
// child i holds the ids between entry i-1 and entry i, and a node whose
|
||||
// first child offset is 0 is a leaf.
|
||||
//
|
||||
// Nothing is indexed up front: lookups descend the tree from the root. Every
|
||||
// interior node is kept once read (about 1 node in 62, a few hundred KB for
|
||||
// client_cell_1.dat) and leaves go through a small LRU, so a lookup usually
|
||||
// costs one leaf read and neighbouring ids (adjacent landblocks) none. The
|
||||
// public API (null when a file or the database is missing) is the one
|
||||
// RynthAi, RynthVision, RynthJuice and the RynthNav tools already use.
|
||||
//
|
||||
// Thread-safety: every stream read and cache access holds one lock, so one
|
||||
// database can be shared between threads. NativeAOT/trimming safe (no
|
||||
// reflection).
|
||||
//
|
||||
// Chorizite DatReaderWriter notice (format reference):
|
||||
// Copyright 2024 ACClientLib
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a
|
||||
// copy of this software and associated documentation files (the
|
||||
// "Software"), to deal in the Software without restriction, including
|
||||
// without limitation the rights to use, copy, modify, merge, publish,
|
||||
// distribute, sublicense, and/or sell copies of the Software, and to permit
|
||||
// persons to whom the Software is furnished to do so, subject to the
|
||||
// following conditions: The above copyright notice and this permission
|
||||
// notice shall be included in all copies or substantial portions of the
|
||||
// Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
|
||||
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
|
||||
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
|
||||
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
|
||||
// USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
// ============================================================================
|
||||
|
||||
// The API returns null for "not there" without annotations; its callers
|
||||
// (RynthAi, RynthJuice, RynthVision) are written against that.
|
||||
#nullable disable
|
||||
|
||||
using System;
|
||||
using System.Buffers.Binary;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using RynthCore.TerrainData;
|
||||
|
|
@ -10,497 +61,299 @@ using RynthCore.TerrainData;
|
|||
namespace RynthCore.Plugin.RynthAi.Raycasting
|
||||
{
|
||||
/// <summary>
|
||||
/// AC .dat file reader — ported from ACEmulator's DatLoader.
|
||||
///
|
||||
/// Key format details (from ACE source):
|
||||
/// - Header at file offset 0x140
|
||||
/// - Block chain: FIRST 4 bytes of each block = next block address (byte offset)
|
||||
/// Remaining (BlockSize - 4) bytes = data
|
||||
/// - B-tree node (DatDirectoryHeader): 62 branches, entry count, 61 entries × 24 bytes = 1716 total
|
||||
/// - All pointers (BTree root, chain pointers, file offsets) are byte offsets
|
||||
///
|
||||
/// Lookups walk the on-disk B-tree by key (root → child whose key range holds
|
||||
/// the id), the way ACE's DatDirectory search does, instead of indexing every
|
||||
/// entry up front: opening client_cell_1.dat used to read all ~805k entries
|
||||
/// (1.6-1.9 s and ~55 MB in a 32-bit process). Interior nodes are kept once
|
||||
/// read and leaves go through a small LRU, so a cold lookup reads one leaf
|
||||
/// and neighbouring ids (adjacent landblocks) touch the disk once. Full
|
||||
/// enumeration is still available on demand (<see cref="EnumerateEntries"/>,
|
||||
/// used by <see cref="GetSampleIds"/>; <see cref="RecordCount"/> walks only
|
||||
/// the node headers); neither keeps anything.
|
||||
///
|
||||
/// Thread-safety: every stream read and cache access holds one lock, so a
|
||||
/// database can be shared between threads.
|
||||
/// A read-only .dat archive. <see cref="Open"/> reads the header and checks
|
||||
/// the root directory node; files are then found by id
|
||||
/// (<see cref="FindFile"/>, <see cref="GetFileData"/>) by searching the
|
||||
/// on-disk B-tree. Methods return null / empty when the database isn't open
|
||||
/// or the file isn't there; nothing throws for a missing or damaged file.
|
||||
/// </summary>
|
||||
public class DatDatabase : IDisposable
|
||||
{
|
||||
private FileStream _stream;
|
||||
private readonly object _lock = new object();
|
||||
// ---- container layout ----
|
||||
private const long HeaderOffset = 0x140;
|
||||
private const int HeaderBytes = 9 * 4; // magic .. root offset
|
||||
private const int ChildSlots = 62;
|
||||
private const int MaxEntriesPerNode = 61;
|
||||
private const int EntryBytes = 24;
|
||||
private const int CountOffset = ChildSlots * 4; // 248
|
||||
private const int EntriesOffset = CountOffset + 4; // 252
|
||||
private const int NodeBytes = EntriesOffset + MaxEntriesPerNode * EntryBytes; // 1716
|
||||
|
||||
private const uint DAT_HEADER_OFFSET = 0x140;
|
||||
// A real tree is 4 levels deep at most; this only stops a damaged child
|
||||
// pointer from sending a search round in circles.
|
||||
private const int DepthLimit = 16;
|
||||
|
||||
// B-tree geometry (from ACE DatDirectoryHeader.cs):
|
||||
// 0x3E (62) branches, 0x3D (61) max entries, each entry = 6 × uint32 = 24 bytes
|
||||
// ObjectSize = (4 * 62) + 4 + (24 * 61) = 248 + 4 + 1464 = 1716
|
||||
private const int BTREE_BRANCH_COUNT = 0x3E; // 62
|
||||
private const int BTREE_MAX_ENTRIES = 0x3D; // 61
|
||||
private const int BTREE_ENTRY_SIZE = 24; // 6 × uint32
|
||||
private const int BTREE_NODE_SIZE = (4 * BTREE_BRANCH_COUNT) + 4 + (BTREE_ENTRY_SIZE * BTREE_MAX_ENTRIES); // 1716
|
||||
// Cache budget: all interior nodes (capped), a 128-leaf LRU.
|
||||
private const int LeafLruSize = 128;
|
||||
private const int InteriorCap = 4096;
|
||||
|
||||
// Deeper than any real dat (805k entries at fan-out 62 is 4 levels);
|
||||
// stops a corrupt branch pointer from looping forever.
|
||||
private const int MaxTreeDepth = 16;
|
||||
private readonly object _gate = new object();
|
||||
private FileStream _file;
|
||||
private long _length;
|
||||
private byte[] _nodeBuf; // one node's bytes, reused (under _gate)
|
||||
private readonly Dictionary<uint, Node> _interior = new Dictionary<uint, Node>();
|
||||
private readonly LruCache<uint, Node> _leaves = new LruCache<uint, Node>(LeafLruSize);
|
||||
private int _count = -1;
|
||||
|
||||
// Parsed nodes kept for repeat lookups (~2.5 KB each). Interior nodes
|
||||
// are few (about 1 in 62: ~220 for client_cell_1.dat) and on every
|
||||
// search path, so they are all kept once read, which makes a cold
|
||||
// lookup cost one leaf read. Leaves go through a small LRU; 128 holds
|
||||
// a 7×7-landblock window many times over.
|
||||
private const int LeafCacheCapacity = 128;
|
||||
private const int MaxInteriorNodes = 4096; // safety cap; real dats stay far below
|
||||
|
||||
// Header fields
|
||||
/// <summary>Header word at 0x140 (the dat magic).</summary>
|
||||
public uint FileType { get; private set; }
|
||||
/// <summary>Block size in bytes (1024 in the retail dats).</summary>
|
||||
public uint BlockSize { get; private set; }
|
||||
/// <summary>File size recorded in the header.</summary>
|
||||
public uint FileSize { get; private set; }
|
||||
/// <summary>The header's data set (database type) word.</summary>
|
||||
public uint DataSet { get; private set; }
|
||||
public uint BTreeRoot { get; private set; } // Byte offset
|
||||
/// <summary>Byte offset of the root directory node.</summary>
|
||||
public uint BTreeRoot { get; private set; }
|
||||
|
||||
/// <summary>True between a successful <see cref="Open"/> and <see cref="Close"/>.</summary>
|
||||
public bool IsLoaded { get; private set; }
|
||||
/// <summary>The path last passed to <see cref="Open"/>.</summary>
|
||||
public string FilePath { get; private set; }
|
||||
|
||||
private int _recordCount = -1;
|
||||
/// <summary>Diagnostics from Open and failed reads (first 100 lines).</summary>
|
||||
public List<string> DiagLog { get; } = new List<string>();
|
||||
|
||||
/// <summary>
|
||||
/// Number of files in the dat. Counted on first use by walking the
|
||||
/// B-tree node headers (branch table + entry count, the first block of
|
||||
/// each node; the entries themselves aren't read), then cached until
|
||||
/// Close. The old eager index paid a full read of every node at Open.
|
||||
/// Number of files in the dat. Counted on first use from the directory
|
||||
/// nodes' entry counts (only the first bytes of each node are read) and
|
||||
/// remembered until <see cref="Close"/>; 0 when not open.
|
||||
/// </summary>
|
||||
public int RecordCount
|
||||
{
|
||||
get
|
||||
{
|
||||
if (!IsLoaded) return 0;
|
||||
if (_recordCount < 0)
|
||||
_recordCount = CountEntries(BTreeRoot, 0);
|
||||
return _recordCount;
|
||||
lock (_gate)
|
||||
{
|
||||
if (!IsLoaded) return 0;
|
||||
if (_count < 0) _count = CountUnder(BTreeRoot, 0);
|
||||
return _count;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private int CountEntries(uint offset, int depth)
|
||||
private sealed class Node
|
||||
{
|
||||
if (offset == 0 || depth >= MaxTreeDepth) return 0;
|
||||
byte[] head;
|
||||
lock (_lock) head = ReadDatData(offset, NodeHeaderSize);
|
||||
if (head == null || head.Length < NodeHeaderSize) return 0;
|
||||
uint entryCount = BitConverter.ToUInt32(head, BTREE_BRANCH_COUNT * 4);
|
||||
if (entryCount > BTREE_MAX_ENTRIES) return 0;
|
||||
int total = (int)entryCount;
|
||||
if (BitConverter.ToUInt32(head, 0) != 0) // interior node
|
||||
for (int i = 0; i <= entryCount; i++)
|
||||
total += CountEntries(BitConverter.ToUInt32(head, i * 4), depth + 1);
|
||||
return total;
|
||||
public uint[] Children; // entry count + 1 offsets; null for a leaf
|
||||
public DatBTreeEntry[] Entries; // ascending ObjectId
|
||||
}
|
||||
|
||||
// Branch table + entry count: the part of a node CountEntries needs.
|
||||
private const int NodeHeaderSize = (4 * BTREE_BRANCH_COUNT) + 4; // 252
|
||||
|
||||
private sealed class BTreeNode
|
||||
{
|
||||
public uint[] Branches;
|
||||
public DatBTreeEntry[] Entries; // sorted by ObjectId
|
||||
public bool IsLeaf => Branches[0] == 0;
|
||||
}
|
||||
|
||||
private readonly LruCache<uint, BTreeNode> _leafCache = new LruCache<uint, BTreeNode>(LeafCacheCapacity);
|
||||
private readonly Dictionary<uint, BTreeNode> _interiorNodes = new Dictionary<uint, BTreeNode>();
|
||||
|
||||
public List<string> DiagLog { get; } = new List<string>();
|
||||
// ------------------------------------------------------------------ open / close
|
||||
|
||||
/// <summary>Opens <paramref name="path"/> read-only. False (and a DiagLog line) on any failure.</summary>
|
||||
public bool Open(string path)
|
||||
{
|
||||
// Re-opening must not leak the previous handle.
|
||||
Close();
|
||||
try
|
||||
lock (_gate)
|
||||
{
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
Log($"File not found: {path}");
|
||||
return false;
|
||||
}
|
||||
|
||||
CloseLocked();
|
||||
FilePath = path;
|
||||
// AC keeps its own handles on these files, and whichever of us
|
||||
// opens second must be compatible with the other: RynthAi opens
|
||||
// at plugin init (before acclient.exe opens its dats), RynthVision
|
||||
// and RynthJuice later. We only read, and we allow others to
|
||||
// read, write and delete-mark the file (FileShare.Delete matters
|
||||
// when we open first: AC's own open needs delete-rename semantics
|
||||
// for the patcher, and without it AC fails with "cannot access
|
||||
// the data files"). RandomAccess hint + 4 KB buffer suit the
|
||||
// scattered B-tree and block-chain reads.
|
||||
_stream = new FileStream(
|
||||
path,
|
||||
FileMode.Open,
|
||||
FileAccess.Read,
|
||||
FileShare.ReadWrite | FileShare.Delete,
|
||||
bufferSize: 4096,
|
||||
options: FileOptions.RandomAccess);
|
||||
|
||||
Log($"File: {Path.GetFileName(path)}, Size: {_stream.Length:N0} bytes");
|
||||
|
||||
if (!ReadHeader())
|
||||
try
|
||||
{
|
||||
Close();
|
||||
return false;
|
||||
}
|
||||
if (!File.Exists(path)) { Log($"Not found: {path}"); return false; }
|
||||
|
||||
// Validate the root node now so a bad file fails here, not on
|
||||
// the first lookup.
|
||||
BTreeNode root;
|
||||
lock (_lock) root = GetNodeLocked(BTreeRoot);
|
||||
if (root == null)
|
||||
{
|
||||
Log($"Unreadable B-tree root at 0x{BTreeRoot:X8}");
|
||||
Close();
|
||||
return false;
|
||||
}
|
||||
// acclient.exe keeps its own handles on the dats and may open
|
||||
// them after us (RynthAi opens at plugin init), so share
|
||||
// everything, including delete: the client's open asks for
|
||||
// delete-rename access and fails ("cannot access the data
|
||||
// files") if an earlier handle refuses it.
|
||||
_file = new FileStream(path, FileMode.Open, FileAccess.Read,
|
||||
FileShare.ReadWrite | FileShare.Delete, 4096, FileOptions.RandomAccess);
|
||||
_length = _file.Length;
|
||||
|
||||
IsLoaded = true;
|
||||
Log($"SUCCESS: opened (B-tree searched on demand), BlockSize={BlockSize}, Root=0x{BTreeRoot:X8}");
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log($"Error: {ex.Message}");
|
||||
Close();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
Span<byte> h = stackalloc byte[HeaderBytes];
|
||||
if (!ReadAt(HeaderOffset, h)) { Log("Header is short"); CloseLocked(); return false; }
|
||||
FileType = BinaryPrimitives.ReadUInt32LittleEndian(h);
|
||||
BlockSize = BinaryPrimitives.ReadUInt32LittleEndian(h.Slice(4));
|
||||
FileSize = BinaryPrimitives.ReadUInt32LittleEndian(h.Slice(8));
|
||||
DataSet = BinaryPrimitives.ReadUInt32LittleEndian(h.Slice(12));
|
||||
BTreeRoot = BinaryPrimitives.ReadUInt32LittleEndian(h.Slice(32));
|
||||
Log($"Header: type=0x{FileType:X8} blockSize={BlockSize} fileSize={FileSize} dataSet=0x{DataSet:X8} root=0x{BTreeRoot:X8} (file {_length} bytes)");
|
||||
|
||||
/// <summary>
|
||||
/// Reads the dat header from offset 0x140.
|
||||
/// Format matches ACE's DatDatabaseHeader.Unpack().
|
||||
/// </summary>
|
||||
private bool ReadHeader()
|
||||
{
|
||||
if (_stream.Length < DAT_HEADER_OFFSET + 64)
|
||||
{
|
||||
Log("File too small");
|
||||
return false;
|
||||
}
|
||||
if (BlockSize <= 4 || BlockSize > 0x10000) { Log($"Bad block size {BlockSize}"); CloseLocked(); return false; }
|
||||
if (BTreeRoot == 0 || BTreeRoot >= _length) { Log($"Bad root offset 0x{BTreeRoot:X8}"); CloseLocked(); return false; }
|
||||
|
||||
_stream.Seek(DAT_HEADER_OFFSET, SeekOrigin.Begin);
|
||||
using (var reader = new BinaryReader(_stream, System.Text.Encoding.Default, true))
|
||||
{
|
||||
FileType = reader.ReadUInt32();
|
||||
BlockSize = reader.ReadUInt32();
|
||||
FileSize = reader.ReadUInt32();
|
||||
DataSet = reader.ReadUInt32();
|
||||
reader.ReadUInt32(); // dataSubset
|
||||
reader.ReadUInt32(); // freeHead
|
||||
reader.ReadUInt32(); // freeTail
|
||||
reader.ReadUInt32(); // freeCount
|
||||
BTreeRoot = reader.ReadUInt32();
|
||||
}
|
||||
|
||||
Log($"FileType=0x{FileType:X8}, BlockSize={BlockSize}, DataSet={DataSet}, BTree=0x{BTreeRoot:X8}");
|
||||
|
||||
if (BlockSize <= 4 || BTreeRoot == 0 || BTreeRoot >= (uint)_stream.Length)
|
||||
{
|
||||
Log("Invalid header values");
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads data from the dat file following the block chain.
|
||||
/// Matches ACE's DatReader.ReadDat().
|
||||
///
|
||||
/// Block format:
|
||||
/// [4 bytes: next block address] [BlockSize - 4 bytes: data]
|
||||
///
|
||||
/// The FIRST 4 bytes of each block are the chain pointer (next block address).
|
||||
/// If 0, this is the last block. Caller holds _lock.
|
||||
/// </summary>
|
||||
private byte[] ReadDatData(uint offset, int size)
|
||||
{
|
||||
if (_stream == null || (long)offset + BlockSize > _stream.Length || size <= 0)
|
||||
return null;
|
||||
|
||||
byte[] buffer = new byte[size];
|
||||
Span<byte> addrBuf = stackalloc byte[4];
|
||||
|
||||
_stream.Seek(offset, SeekOrigin.Begin);
|
||||
if (!ReadFully(addrBuf)) return null;
|
||||
uint nextAddress = BitConverter.ToUInt32(addrBuf);
|
||||
|
||||
int bufferOffset = 0;
|
||||
int remaining = size;
|
||||
|
||||
while (remaining > 0)
|
||||
{
|
||||
if (nextAddress == 0)
|
||||
{
|
||||
// Last block — read remaining data directly
|
||||
int toRead = (int)Math.Min(remaining, _stream.Length - _stream.Position);
|
||||
if (toRead <= 0) break;
|
||||
ReadFully(buffer.AsSpan(bufferOffset, toRead));
|
||||
remaining = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Read data portion of this block (BlockSize - 4 bytes)
|
||||
int dataInBlock = (int)BlockSize - 4;
|
||||
int toRead = Math.Min(dataInBlock, remaining);
|
||||
if (!ReadFully(buffer.AsSpan(bufferOffset, toRead))) break;
|
||||
bufferOffset += toRead;
|
||||
remaining -= toRead;
|
||||
|
||||
if (remaining > 0)
|
||||
_nodeBuf = new byte[NodeBytes];
|
||||
IsLoaded = true;
|
||||
if (GetNode(BTreeRoot) == null)
|
||||
{
|
||||
// Follow chain to next block
|
||||
if (nextAddress >= (uint)_stream.Length) break;
|
||||
_stream.Seek(nextAddress, SeekOrigin.Begin);
|
||||
|
||||
// Read next block's chain pointer
|
||||
if (!ReadFully(addrBuf)) break;
|
||||
nextAddress = BitConverter.ToUInt32(addrBuf);
|
||||
Log($"Root node at 0x{BTreeRoot:X8} doesn't parse");
|
||||
CloseLocked();
|
||||
return false;
|
||||
}
|
||||
Log($"Opened {Path.GetFileName(path)}");
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log($"Open failed: {ex.Message}");
|
||||
CloseLocked();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return buffer;
|
||||
}
|
||||
|
||||
private bool ReadFully(Span<byte> dest)
|
||||
/// <summary>Closes the file and drops the cached directory nodes.</summary>
|
||||
public void Close()
|
||||
{
|
||||
while (dest.Length > 0)
|
||||
{
|
||||
int n = _stream.Read(dest);
|
||||
if (n <= 0) return false;
|
||||
dest = dest.Slice(n);
|
||||
}
|
||||
return true;
|
||||
lock (_gate) CloseLocked();
|
||||
}
|
||||
|
||||
/// <summary>Parses the B-tree node at <paramref name="offset"/>. Caller holds _lock.</summary>
|
||||
private BTreeNode ReadNodeLocked(uint offset)
|
||||
public void Dispose() { Close(); }
|
||||
|
||||
private void CloseLocked()
|
||||
{
|
||||
if (_stream == null || offset == 0 || offset >= (uint)_stream.Length)
|
||||
return null;
|
||||
|
||||
byte[] nodeData = ReadDatData(offset, BTREE_NODE_SIZE);
|
||||
if (nodeData == null || nodeData.Length < BTREE_NODE_SIZE)
|
||||
return null;
|
||||
|
||||
int countOffset = BTREE_BRANCH_COUNT * 4; // 248
|
||||
uint entryCount = BitConverter.ToUInt32(nodeData, countOffset);
|
||||
if (entryCount > BTREE_MAX_ENTRIES)
|
||||
return null; // Invalid node
|
||||
|
||||
var branches = new uint[BTREE_BRANCH_COUNT];
|
||||
for (int i = 0; i < BTREE_BRANCH_COUNT; i++)
|
||||
branches[i] = BitConverter.ToUInt32(nodeData, i * 4);
|
||||
|
||||
int entriesOffset = countOffset + 4; // 252
|
||||
var entries = new DatBTreeEntry[entryCount];
|
||||
for (int i = 0; i < entryCount; i++)
|
||||
{
|
||||
int eOff = entriesOffset + i * BTREE_ENTRY_SIZE;
|
||||
entries[i] = new DatBTreeEntry
|
||||
{
|
||||
BitFlags = BitConverter.ToUInt32(nodeData, eOff),
|
||||
ObjectId = BitConverter.ToUInt32(nodeData, eOff + 4),
|
||||
FileOffset = BitConverter.ToUInt32(nodeData, eOff + 8),
|
||||
FileSize = BitConverter.ToUInt32(nodeData, eOff + 12)
|
||||
};
|
||||
}
|
||||
|
||||
return new BTreeNode { Branches = branches, Entries = entries };
|
||||
IsLoaded = false;
|
||||
_file?.Dispose();
|
||||
_file = null;
|
||||
_length = 0;
|
||||
_nodeBuf = null;
|
||||
_interior.Clear();
|
||||
_leaves.Clear();
|
||||
_count = -1;
|
||||
}
|
||||
|
||||
/// <summary>Cached node read. Caller holds _lock.</summary>
|
||||
private BTreeNode GetNodeLocked(uint offset)
|
||||
{
|
||||
if (_interiorNodes.TryGetValue(offset, out var node)) return node;
|
||||
if (_leafCache.TryGet(offset, out node)) return node;
|
||||
node = ReadNodeLocked(offset);
|
||||
if (node == null) return null;
|
||||
if (!node.IsLeaf && _interiorNodes.Count < MaxInteriorNodes)
|
||||
_interiorNodes[offset] = node;
|
||||
else
|
||||
_leafCache.Set(offset, node);
|
||||
return node;
|
||||
}
|
||||
// ------------------------------------------------------------------ lookups
|
||||
|
||||
// Index of the first entry whose ObjectId is >= id (entries.Length if none).
|
||||
private static int LowerBound(DatBTreeEntry[] entries, uint id)
|
||||
{
|
||||
int lo = 0, hi = entries.Length;
|
||||
while (lo < hi)
|
||||
{
|
||||
int mid = (lo + hi) >> 1;
|
||||
if (entries[mid].ObjectId < id) lo = mid + 1;
|
||||
else hi = mid;
|
||||
}
|
||||
return lo;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds a file by ID: descends the B-tree from the root, picking at each
|
||||
/// node the branch between the two keys that bracket the id.
|
||||
/// </summary>
|
||||
/// <summary>The directory entry for <paramref name="fileId"/>, or null.</summary>
|
||||
public DatBTreeEntry FindFile(uint fileId)
|
||||
{
|
||||
if (!IsLoaded || fileId == 0) return null;
|
||||
|
||||
lock (_lock)
|
||||
lock (_gate)
|
||||
{
|
||||
uint offset = BTreeRoot;
|
||||
for (int depth = 0; depth < MaxTreeDepth && offset != 0; depth++)
|
||||
if (!IsLoaded) return null;
|
||||
uint at = BTreeRoot;
|
||||
for (int depth = 0; depth < DepthLimit && at != 0; depth++)
|
||||
{
|
||||
BTreeNode node = GetNodeLocked(offset);
|
||||
if (node == null) return null;
|
||||
|
||||
DatBTreeEntry[] entries = node.Entries;
|
||||
int i = LowerBound(entries, fileId);
|
||||
if (i < entries.Length && entries[i].ObjectId == fileId)
|
||||
return entries[i];
|
||||
if (node.IsLeaf || i >= BTREE_BRANCH_COUNT)
|
||||
return null;
|
||||
offset = node.Branches[i];
|
||||
Node n = GetNode(at);
|
||||
if (n == null) return null;
|
||||
int i = LowerBound(n.Entries, fileId);
|
||||
if (i < n.Entries.Length && n.Entries[i].ObjectId == fileId) return n.Entries[i];
|
||||
if (n.Children == null) return null;
|
||||
at = n.Children[i];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads file data for a given entry.
|
||||
/// </summary>
|
||||
/// <summary>The bytes of the file <paramref name="entry"/> describes, or null.</summary>
|
||||
public byte[] ReadFileData(DatBTreeEntry entry)
|
||||
{
|
||||
if (!IsLoaded || entry == null || entry.FileSize == 0)
|
||||
return null;
|
||||
|
||||
lock (_lock)
|
||||
if (entry == null) return null;
|
||||
lock (_gate)
|
||||
{
|
||||
return ReadDatData(entry.FileOffset, (int)entry.FileSize);
|
||||
if (!IsLoaded) return null;
|
||||
if (entry.FileSize > _length) { Log($"0x{entry.ObjectId:X8}: size {entry.FileSize} exceeds the file"); return null; }
|
||||
var data = new byte[entry.FileSize];
|
||||
if (ReadChain(entry.FileOffset, data) != data.Length)
|
||||
{
|
||||
Log($"0x{entry.ObjectId:X8}: block chain at 0x{entry.FileOffset:X8} is broken");
|
||||
return null;
|
||||
}
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
||||
public byte[] GetFileData(uint fileId)
|
||||
{
|
||||
var entry = FindFile(fileId);
|
||||
return entry != null ? ReadFileData(entry) : null;
|
||||
}
|
||||
/// <summary><see cref="FindFile"/> then <see cref="ReadFileData"/>.</summary>
|
||||
public byte[] GetFileData(uint fileId) => ReadFileData(FindFile(fileId));
|
||||
|
||||
/// <summary>
|
||||
/// Returns all interior cell IDs (0x0100–0xFFFD) for a given landblock,
|
||||
/// ascending. A B-tree range search: only the nodes whose key range
|
||||
/// overlaps the landblock's are read.
|
||||
/// The interior (EnvCell) ids 0xXXYY0100-0xXXYYFFFD of landblock
|
||||
/// <paramref name="landblockKey"/> (0xXXYY), ascending. Only the nodes
|
||||
/// whose id range overlaps the landblock are read.
|
||||
/// </summary>
|
||||
public List<uint> GetLandblockCellIds(uint landblockKey)
|
||||
{
|
||||
var cellIds = new List<uint>();
|
||||
if (!IsLoaded) return cellIds;
|
||||
|
||||
uint prefix = landblockKey << 16;
|
||||
uint lo = prefix | 0x0100;
|
||||
uint hi = prefix | 0xFFFD;
|
||||
lock (_lock)
|
||||
var found = new List<uint>();
|
||||
lock (_gate)
|
||||
{
|
||||
CollectRangeLocked(BTreeRoot, lo, hi, cellIds, 0);
|
||||
if (!IsLoaded) return found;
|
||||
uint lo = (landblockKey << 16) | 0x0100;
|
||||
uint hi = (landblockKey << 16) | 0xFFFD;
|
||||
CollectRange(BTreeRoot, lo, hi, found, 0);
|
||||
}
|
||||
return cellIds;
|
||||
return found;
|
||||
}
|
||||
|
||||
private void CollectRangeLocked(uint offset, uint lo, uint hi, List<uint> output, int depth)
|
||||
// In-order walk of the part of the subtree at `at` holding ids in [lo, hi].
|
||||
private void CollectRange(uint at, uint lo, uint hi, List<uint> into, int depth)
|
||||
{
|
||||
if (offset == 0 || depth >= MaxTreeDepth) return;
|
||||
BTreeNode node = GetNodeLocked(offset);
|
||||
if (node == null) return;
|
||||
|
||||
DatBTreeEntry[] entries = node.Entries;
|
||||
int count = entries.Length;
|
||||
// Branch i holds the ids between entries[i-1] and entries[i].
|
||||
int start = LowerBound(entries, lo);
|
||||
for (int i = start; i <= count; i++)
|
||||
if (at == 0 || depth >= DepthLimit) return;
|
||||
Node n = GetNode(at);
|
||||
if (n == null) return;
|
||||
var e = n.Entries;
|
||||
for (int i = 0; i <= e.Length; i++)
|
||||
{
|
||||
if (!node.IsLeaf && i < BTREE_BRANCH_COUNT)
|
||||
CollectRangeLocked(node.Branches[i], lo, hi, output, depth + 1);
|
||||
if (i == count) break;
|
||||
uint id = entries[i].ObjectId;
|
||||
// Child i spans (e[i-1], e[i]); visit it if that overlaps [lo, hi].
|
||||
if (n.Children != null)
|
||||
{
|
||||
bool aboveLo = i == e.Length || e[i].ObjectId > lo;
|
||||
bool belowHi = i == 0 || e[i - 1].ObjectId < hi;
|
||||
if (aboveLo && belowHi) CollectRange(n.Children[i], lo, hi, into, depth + 1);
|
||||
}
|
||||
if (i == e.Length) break;
|
||||
uint id = e[i].ObjectId;
|
||||
if (id > hi) break;
|
||||
output.Add(id);
|
||||
if (id >= lo) into.Add(id);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Every entry in the dat, in ascending id order, read from the B-tree
|
||||
/// on demand (nothing is kept afterwards). Walking client_cell_1.dat
|
||||
/// reads every node, so use it for diagnostics and counts, not lookups.
|
||||
/// Every entry, ascending by id, read from the tree as it goes (nothing
|
||||
/// is kept afterwards). Reads every node of the dat: for diagnostics and
|
||||
/// offline tools, not for lookups.
|
||||
/// </summary>
|
||||
public IEnumerable<DatBTreeEntry> EnumerateEntries()
|
||||
{
|
||||
if (!IsLoaded) yield break;
|
||||
|
||||
// Explicit stack instead of recursion so the lock is only held per
|
||||
// node read, never across a yield. A frame is "visit branch I, then
|
||||
// entry I, then move on to I+1".
|
||||
BTreeNode root = ReadNodeForWalk(BTreeRoot);
|
||||
Node root;
|
||||
lock (_gate)
|
||||
{
|
||||
if (!IsLoaded) yield break;
|
||||
root = GetNodeUncached(BTreeRoot);
|
||||
}
|
||||
if (root == null) yield break;
|
||||
var stack = new Stack<WalkFrame>();
|
||||
stack.Push(new WalkFrame(root, 0, false));
|
||||
|
||||
// Explicit stack (no recursion through iterators); the lock is taken
|
||||
// per node read, never held across a yield.
|
||||
var stack = new Stack<(Node node, int next)>();
|
||||
stack.Push((root, 0));
|
||||
DescendLeft(stack);
|
||||
while (stack.Count > 0)
|
||||
{
|
||||
WalkFrame f = stack.Pop();
|
||||
if (!f.BranchDone)
|
||||
var (node, next) = stack.Pop();
|
||||
if (next >= node.Entries.Length) continue;
|
||||
yield return node.Entries[next];
|
||||
stack.Push((node, next + 1));
|
||||
if (node.Children != null)
|
||||
{
|
||||
stack.Push(new WalkFrame(f.Node, f.Index, true));
|
||||
if (!f.Node.IsLeaf && f.Index < BTREE_BRANCH_COUNT && stack.Count <= MaxTreeDepth)
|
||||
{
|
||||
BTreeNode child = ReadNodeForWalk(f.Node.Branches[f.Index]);
|
||||
if (child != null) stack.Push(new WalkFrame(child, 0, false));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (f.Index < f.Node.Entries.Length)
|
||||
{
|
||||
yield return f.Node.Entries[f.Index];
|
||||
stack.Push(new WalkFrame(f.Node, f.Index + 1, false));
|
||||
Node child = ReadForWalk(node.Children[next + 1], stack.Count);
|
||||
if (child != null) { stack.Push((child, 0)); DescendLeft(stack); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private readonly struct WalkFrame
|
||||
// Pushes the leftmost path below the node on top of the stack.
|
||||
private void DescendLeft(Stack<(Node node, int next)> stack)
|
||||
{
|
||||
public readonly BTreeNode Node;
|
||||
public readonly int Index;
|
||||
public readonly bool BranchDone;
|
||||
public WalkFrame(BTreeNode node, int index, bool branchDone) { Node = node; Index = index; BranchDone = branchDone; }
|
||||
}
|
||||
|
||||
private BTreeNode ReadNodeForWalk(uint offset)
|
||||
{
|
||||
lock (_lock)
|
||||
while (true)
|
||||
{
|
||||
// Don't churn the lookup cache with a full walk: use a cached
|
||||
// node if present, otherwise read without caching.
|
||||
if (_interiorNodes.TryGetValue(offset, out var cached)) return cached;
|
||||
if (_leafCache.TryGet(offset, out cached)) return cached;
|
||||
return ReadNodeLocked(offset);
|
||||
var top = stack.Peek().node;
|
||||
if (top.Children == null) return;
|
||||
Node child = ReadForWalk(top.Children[0], stack.Count);
|
||||
if (child == null) return;
|
||||
stack.Push((child, 0));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the lowest file IDs in the dat (in-order walk, stops early),
|
||||
/// for diagnostics.
|
||||
/// </summary>
|
||||
private Node ReadForWalk(uint at, int depth)
|
||||
{
|
||||
if (at == 0 || depth >= DepthLimit) return null;
|
||||
lock (_gate)
|
||||
{
|
||||
if (!IsLoaded) return null;
|
||||
return GetNodeUncached(at);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The lowest file ids in the dat (up to <paramref name="maxCount"/>), for diagnostics.</summary>
|
||||
public List<uint> GetSampleIds(int maxCount = 20)
|
||||
{
|
||||
var ids = new List<uint>();
|
||||
|
|
@ -513,34 +366,150 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
|
|||
return ids;
|
||||
}
|
||||
|
||||
public void Close()
|
||||
// ------------------------------------------------------------------ nodes
|
||||
|
||||
// First entry index whose id is >= id (Length when none).
|
||||
private static int LowerBound(DatBTreeEntry[] e, uint id)
|
||||
{
|
||||
lock (_lock)
|
||||
int a = 0, b = e.Length;
|
||||
while (a < b)
|
||||
{
|
||||
_stream?.Dispose();
|
||||
_stream = null;
|
||||
IsLoaded = false;
|
||||
_recordCount = -1;
|
||||
_leafCache.Clear();
|
||||
_interiorNodes.Clear();
|
||||
int m = (a + b) >> 1;
|
||||
if (e[m].ObjectId < id) a = m + 1; else b = m;
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
||||
public void Dispose() { Close(); }
|
||||
// Cached node. Caller holds _gate.
|
||||
private Node GetNode(uint at)
|
||||
{
|
||||
if (_interior.TryGetValue(at, out Node n)) return n;
|
||||
if (_leaves.TryGet(at, out n)) return n;
|
||||
n = ParseNode(at);
|
||||
if (n == null) return null;
|
||||
if (n.Children != null)
|
||||
{
|
||||
if (_interior.Count < InteriorCap) _interior[at] = n;
|
||||
}
|
||||
else _leaves.Set(at, n);
|
||||
return n;
|
||||
}
|
||||
|
||||
// For full walks: use a cached node if there is one, but don't fill the
|
||||
// caches with the whole tree. Caller holds _gate.
|
||||
private Node GetNodeUncached(uint at)
|
||||
{
|
||||
if (_interior.TryGetValue(at, out Node n)) return n;
|
||||
if (_leaves.TryGet(at, out n)) return n;
|
||||
return ParseNode(at);
|
||||
}
|
||||
|
||||
// Reads and decodes the node at byte offset `at`. Caller holds _gate.
|
||||
private Node ParseNode(uint at)
|
||||
{
|
||||
byte[] buf = _nodeBuf;
|
||||
int got = ReadChain(at, buf);
|
||||
if (got < EntriesOffset) return null;
|
||||
ReadOnlySpan<byte> s = buf;
|
||||
int count = BinaryPrimitives.ReadInt32LittleEndian(s.Slice(CountOffset));
|
||||
if (count < 0 || count > MaxEntriesPerNode || got < EntriesOffset + count * EntryBytes) return null;
|
||||
|
||||
var entries = new DatBTreeEntry[count];
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
var r = s.Slice(EntriesOffset + i * EntryBytes, EntryBytes);
|
||||
entries[i] = new DatBTreeEntry
|
||||
{
|
||||
BitFlags = BinaryPrimitives.ReadUInt32LittleEndian(r),
|
||||
ObjectId = BinaryPrimitives.ReadUInt32LittleEndian(r.Slice(4)),
|
||||
FileOffset = BinaryPrimitives.ReadUInt32LittleEndian(r.Slice(8)),
|
||||
FileSize = BinaryPrimitives.ReadUInt32LittleEndian(r.Slice(12)),
|
||||
};
|
||||
}
|
||||
|
||||
uint[] children = null;
|
||||
if (BinaryPrimitives.ReadUInt32LittleEndian(s) != 0)
|
||||
{
|
||||
children = new uint[count + 1];
|
||||
for (int i = 0; i <= count; i++)
|
||||
children[i] = BinaryPrimitives.ReadUInt32LittleEndian(s.Slice(i * 4));
|
||||
}
|
||||
return new Node { Children = children, Entries = entries };
|
||||
}
|
||||
|
||||
// Node entry counts under `at`, reading only each node's first bytes
|
||||
// (child table + count). Caller holds _gate.
|
||||
private int CountUnder(uint at, int depth)
|
||||
{
|
||||
if (at == 0 || depth >= DepthLimit) return 0;
|
||||
Span<byte> head = stackalloc byte[EntriesOffset];
|
||||
if (ReadChain(at, head) != EntriesOffset) return 0;
|
||||
int count = BinaryPrimitives.ReadInt32LittleEndian(head.Slice(CountOffset));
|
||||
if (count < 0 || count > MaxEntriesPerNode) return 0;
|
||||
int total = count;
|
||||
if (BinaryPrimitives.ReadUInt32LittleEndian(head) != 0)
|
||||
{
|
||||
// Copy the child offsets out: the recursion reuses the stack.
|
||||
Span<uint> kids = stackalloc uint[count + 1];
|
||||
for (int i = 0; i <= count; i++) kids[i] = BinaryPrimitives.ReadUInt32LittleEndian(head.Slice(i * 4));
|
||||
for (int i = 0; i <= count; i++) total += CountUnder(kids[i], depth + 1);
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ blocks
|
||||
|
||||
// Copies the block chain starting at byte offset `first` into `dest`
|
||||
// and returns how many bytes it filled: dest.Length, or less when the
|
||||
// chain ends (a 0 link) first; -1 when a link points outside the file.
|
||||
// Caller holds _gate.
|
||||
private int ReadChain(uint first, Span<byte> dest)
|
||||
{
|
||||
int payload = (int)BlockSize - 4;
|
||||
long block = first;
|
||||
int done = 0;
|
||||
Span<byte> link = stackalloc byte[4];
|
||||
while (done < dest.Length)
|
||||
{
|
||||
if (block == 0) return done;
|
||||
if (block + 4 > _length) return -1;
|
||||
int take = Math.Min(payload, dest.Length - done);
|
||||
if (!ReadAt(block, link) || !ReadAt(block + 4, dest.Slice(done, take))) return -1;
|
||||
done += take;
|
||||
block = BinaryPrimitives.ReadUInt32LittleEndian(link);
|
||||
}
|
||||
return done;
|
||||
}
|
||||
|
||||
// Caller holds _gate (or is Open, before anything else can see the file).
|
||||
private bool ReadAt(long offset, Span<byte> into)
|
||||
{
|
||||
if (offset < 0 || offset + into.Length > _length) return false;
|
||||
_file.Position = offset;
|
||||
int got = 0;
|
||||
while (got < into.Length)
|
||||
{
|
||||
int n = _file.Read(into.Slice(got));
|
||||
if (n <= 0) return false;
|
||||
got += n;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private void Log(string msg)
|
||||
{
|
||||
string line = $"[DatDB] {msg}";
|
||||
string line = "[DatDB] " + msg;
|
||||
System.Diagnostics.Debug.WriteLine(line);
|
||||
if (DiagLog.Count < 100) DiagLog.Add(line);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One directory entry: a file's id, flags, first block and size.</summary>
|
||||
public class DatBTreeEntry
|
||||
{
|
||||
public uint BitFlags;
|
||||
public uint ObjectId;
|
||||
public uint FileOffset; // Byte offset into file
|
||||
public uint FileOffset; // byte offset of the file's first block
|
||||
public uint FileSize;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -32,3 +32,34 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
```
|
||||
|
||||
## Chorizite DatReaderWriter (format reference for the dat reader)
|
||||
|
||||
- What: the layout of Asheron's Call .dat files (header, block chains, the directory B-tree), used as the reference when RynthSuite's own dat reader was written (2026-10-05). The code is RynthSuite's own (MIT); this notice is kept because the library was the format reference.
|
||||
- Where: `Shared/RynthCore.TerrainData/DatDatabase.cs`, compiled into `RynthCore.TerrainData.dll`. The notice is also in that file's header.
|
||||
- Source: https://github.com/Chorizite/DatReaderWriter (ACClientLib)
|
||||
- Licence: MIT, reproduced below.
|
||||
|
||||
```
|
||||
MIT License
|
||||
|
||||
Copyright 2024 ACClientLib
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
```
|
||||
|
|
|
|||
373
Tools/RynthCore.DatReaderCheck/Program.cs
Normal file
373
Tools/RynthCore.DatReaderCheck/Program.cs
Normal file
|
|
@ -0,0 +1,373 @@
|
|||
// RynthCore.DatReaderCheck - proves a dat reader change on the real dat files (read only).
|
||||
// Written for RynthCore (MIT). See the .csproj for the modes; the README-style notes are there.
|
||||
//
|
||||
// Every check goes through the reader's public API only (Open, header properties, RecordCount,
|
||||
// EnumerateEntries, FindFile, GetFileData, GetLandblockCellIds, GetSampleIds), so the same
|
||||
// source builds against any reader that keeps that API, and two builds' manifests can be
|
||||
// compared line by line.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using RynthCore.Plugin.RynthAi.Raycasting;
|
||||
|
||||
namespace RynthCore.DatReaderCheck;
|
||||
|
||||
internal static class Program
|
||||
{
|
||||
private static int Main(string[] args)
|
||||
{
|
||||
if (args.Length >= 3 && args[0] == "manifest") return Manifest(args[1], args[2]);
|
||||
if (args.Length >= 3 && args[0] == "geo") return Geo(args[1], args[2]);
|
||||
if (args.Length >= 3 && args[0] == "diff") return Diff(args[1], args[2]);
|
||||
if (args.Length >= 2 && args[0] == "bench") return Bench(args[1], args.Length > 2 ? int.Parse(args[2]) : 3);
|
||||
Console.WriteLine("usage: manifest <AC folder> <out> | geo <AC folder> <out> | diff <a> <b> | bench <AC folder> [rounds]");
|
||||
return 2;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ manifest
|
||||
|
||||
private static int Manifest(string acDir, string outPath)
|
||||
{
|
||||
using var w = new StreamWriter(outPath, false, new UTF8Encoding(false));
|
||||
w.NewLine = "\n";
|
||||
int rc = 0;
|
||||
rc |= DumpDat(w, Path.Combine(acDir, "client_portal.dat"), cellDat: false);
|
||||
rc |= DumpDat(w, Path.Combine(acDir, "client_cell_1.dat"), cellDat: true);
|
||||
var p = Process.GetCurrentProcess();
|
||||
p.Refresh();
|
||||
w.WriteLine($"#t process peak working set {p.PeakWorkingSet64 / 1048576.0:F1} MB, peak private {p.PeakPagedMemorySize64 / 1048576.0:F1} MB");
|
||||
Console.WriteLine($"peak working set {p.PeakWorkingSet64 / 1048576.0:F1} MB");
|
||||
return rc;
|
||||
}
|
||||
|
||||
private static int DumpDat(StreamWriter w, string path, bool cellDat)
|
||||
{
|
||||
string name = Path.GetFileName(path);
|
||||
Console.WriteLine($"== {name}");
|
||||
w.WriteLine($"== {name}");
|
||||
|
||||
var sw = Stopwatch.StartNew();
|
||||
var db = new DatDatabase();
|
||||
bool ok = db.Open(path);
|
||||
double openMs = sw.Elapsed.TotalMilliseconds;
|
||||
w.WriteLine($"open {ok}");
|
||||
w.WriteLine($"#t open {openMs:F1} ms");
|
||||
if (!ok)
|
||||
{
|
||||
foreach (var l in db.DiagLog) w.WriteLine("#t diag " + l);
|
||||
Console.WriteLine("open failed: " + string.Join(" | ", db.DiagLog));
|
||||
return 1;
|
||||
}
|
||||
w.WriteLine($"header FileType={db.FileType:X8} BlockSize={db.BlockSize} FileSize={db.FileSize} DataSet={db.DataSet:X8} BTreeRoot={db.BTreeRoot:X8} IsLoaded={db.IsLoaded}");
|
||||
|
||||
sw.Restart();
|
||||
int count = db.RecordCount;
|
||||
w.WriteLine($"records {count}");
|
||||
w.WriteLine($"#t RecordCount {sw.Elapsed.TotalMilliseconds:F1} ms");
|
||||
w.WriteLine("samples " + string.Join(",", db.GetSampleIds(30).Select(i => i.ToString("X8"))));
|
||||
|
||||
// 1. Enumerate (ids, flags, offsets, sizes) without reading any file.
|
||||
sw.Restart();
|
||||
var entries = new List<DatBTreeEntry>(count);
|
||||
foreach (var e in db.EnumerateEntries())
|
||||
entries.Add(new DatBTreeEntry { BitFlags = e.BitFlags, ObjectId = e.ObjectId, FileOffset = e.FileOffset, FileSize = e.FileSize });
|
||||
double enumMs = sw.Elapsed.TotalMilliseconds;
|
||||
w.WriteLine($"enumerated {entries.Count}");
|
||||
w.WriteLine($"#t EnumerateEntries {enumMs:F1} ms");
|
||||
bool ascending = true;
|
||||
for (int i = 1; i < entries.Count; i++) if (entries[i].ObjectId <= entries[i - 1].ObjectId) { ascending = false; break; }
|
||||
w.WriteLine($"ascending {ascending}");
|
||||
|
||||
// 2. Every file by id: FindFile must return the same entry, GetFileData its bytes.
|
||||
sw.Restart();
|
||||
long bytes = 0;
|
||||
int nulls = 0, entryMismatch = 0;
|
||||
double findMs = 0, readMs = 0;
|
||||
var swOne = new Stopwatch();
|
||||
foreach (var e in entries)
|
||||
{
|
||||
swOne.Restart();
|
||||
var f = db.FindFile(e.ObjectId);
|
||||
findMs += swOne.Elapsed.TotalMilliseconds;
|
||||
bool same = f != null && f.ObjectId == e.ObjectId && f.FileOffset == e.FileOffset && f.FileSize == e.FileSize && f.BitFlags == e.BitFlags;
|
||||
if (!same) entryMismatch++;
|
||||
swOne.Restart();
|
||||
byte[] data = db.GetFileData(e.ObjectId);
|
||||
readMs += swOne.Elapsed.TotalMilliseconds;
|
||||
string digest;
|
||||
if (data == null) { nulls++; digest = "NULL"; }
|
||||
else { bytes += data.Length; digest = data.Length + " " + Convert.ToHexString(SHA256.HashData(data)); }
|
||||
w.WriteLine($"f {e.ObjectId:X8} {e.BitFlags:X8} {e.FileOffset:X8} {e.FileSize} {(same ? "=" : "!")} {digest}");
|
||||
}
|
||||
double allMs = sw.Elapsed.TotalMilliseconds;
|
||||
w.WriteLine($"files {entries.Count} read-null {nulls} find-mismatch {entryMismatch} bytes {bytes}");
|
||||
w.WriteLine($"#t all files {allMs:F0} ms (FindFile {findMs:F0} ms, GetFileData incl. its own find {readMs:F0} ms, hashing the rest), {bytes / 1048576.0:F0} MB");
|
||||
Console.WriteLine($" {entries.Count} files, {nulls} null, {entryMismatch} find mismatches, {bytes / 1048576.0:F0} MB in {allMs:F0} ms");
|
||||
|
||||
// 3. Misses. Ids next to every real id, and a fixed pseudo-random set.
|
||||
var idSet = new HashSet<uint>(entries.Select(e => e.ObjectId));
|
||||
sw.Restart();
|
||||
int probes = 0, misses = 0, wrongHits = 0, wrongMisses = 0;
|
||||
void Probe(uint id)
|
||||
{
|
||||
probes++;
|
||||
var f = db.FindFile(id);
|
||||
bool expect = idSet.Contains(id);
|
||||
if (f == null) { misses++; if (expect) wrongMisses++; }
|
||||
else if (!expect || f.ObjectId != id) wrongHits++;
|
||||
}
|
||||
foreach (var e in entries)
|
||||
{
|
||||
if (e.ObjectId != uint.MaxValue) Probe(e.ObjectId + 1);
|
||||
if (e.ObjectId != 0) Probe(e.ObjectId - 1);
|
||||
}
|
||||
var rng = new Random(20261005);
|
||||
for (int i = 0; i < 1_000_000; i++) Probe((uint)rng.NextInt64(0, 1L << 32));
|
||||
// The prefix the reader is used for: the portal types 0x01-0x40 near the low ids.
|
||||
for (uint t = 0; t <= 0x40; t++) for (uint lo = 0; lo < 0x400; lo++) Probe((t << 24) | lo);
|
||||
Probe(0); Probe(uint.MaxValue);
|
||||
w.WriteLine($"probes {probes} misses {misses} wrong-hits {wrongHits} wrong-misses {wrongMisses}");
|
||||
w.WriteLine($"#t probes {sw.Elapsed.TotalMilliseconds:F0} ms");
|
||||
|
||||
// 4. Landblocks: the cell dat's per-landblock lookups.
|
||||
sw.Restart();
|
||||
int lbWithCells = 0, cellIds = 0, lbFound = 0, infoFound = 0;
|
||||
for (uint lb = 0; lb <= 0xFFFF; lb++)
|
||||
{
|
||||
var ids = db.GetLandblockCellIds(lb);
|
||||
bool hasLb = db.FindFile((lb << 16) | 0xFFFF) != null;
|
||||
bool hasInfo = db.FindFile((lb << 16) | 0xFFFE) != null;
|
||||
if (hasLb) lbFound++;
|
||||
if (hasInfo) infoFound++;
|
||||
if (ids.Count > 0) lbWithCells++;
|
||||
cellIds += ids.Count;
|
||||
if (cellDat || ids.Count > 0 || hasLb || hasInfo)
|
||||
w.WriteLine($"lb {lb:X4} {(hasLb ? 1 : 0)}{(hasInfo ? 1 : 0)} {ids.Count} {Hash(ids)}");
|
||||
}
|
||||
w.WriteLine($"landblocks with-FFFF {lbFound} with-FFFE {infoFound} with-cells {lbWithCells} cell-ids {cellIds}");
|
||||
w.WriteLine($"#t landblock scan {sw.Elapsed.TotalMilliseconds:F0} ms");
|
||||
|
||||
// Cross-check GetLandblockCellIds against the enumeration.
|
||||
var expected = new Dictionary<uint, int>();
|
||||
foreach (var e in entries)
|
||||
{
|
||||
uint low = e.ObjectId & 0xFFFF;
|
||||
if (low >= 0x0100 && low <= 0xFFFD) expected[e.ObjectId >> 16] = expected.TryGetValue(e.ObjectId >> 16, out int n) ? n + 1 : 1;
|
||||
}
|
||||
int lbMismatch = 0;
|
||||
foreach (var kv in expected) if (db.GetLandblockCellIds(kv.Key).Count != kv.Value) lbMismatch++;
|
||||
w.WriteLine($"landblock-vs-enumeration mismatches {lbMismatch}");
|
||||
|
||||
db.Close();
|
||||
w.WriteLine($"closed IsLoaded={db.IsLoaded} find-after-close={(db.FindFile(0x0E00000E) == null ? "null" : "hit")} data-after-close={(db.GetFileData(0x0E00000E) == null ? "null" : "data")}");
|
||||
db.Dispose();
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static string Hash(List<uint> ids)
|
||||
{
|
||||
if (ids.Count == 0) return "-";
|
||||
var b = new byte[ids.Count * 4];
|
||||
for (int i = 0; i < ids.Count; i++) BitConverter.TryWriteBytes(b.AsSpan(i * 4), ids[i]);
|
||||
return Convert.ToHexString(SHA256.HashData(b), 0, 12);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ bench
|
||||
|
||||
// Timings only (no hashing, no output file): run it a few times against warm OS file cache.
|
||||
private static int Bench(string acDir, int rounds)
|
||||
{
|
||||
foreach (string name in new[] { "client_portal.dat", "client_cell_1.dat" })
|
||||
{
|
||||
string path = Path.Combine(acDir, name);
|
||||
Console.WriteLine($"== {name} (managed heap the open reader holds after the lookups below: {ReaderHeapKb(path):F0} KB)");
|
||||
for (int r = 0; r < rounds; r++)
|
||||
{
|
||||
var sw = Stopwatch.StartNew();
|
||||
var db = new DatDatabase();
|
||||
db.Open(path);
|
||||
double open = sw.Elapsed.TotalMilliseconds;
|
||||
sw.Restart(); int count = db.RecordCount; double rcMs = sw.Elapsed.TotalMilliseconds;
|
||||
sw.Restart();
|
||||
var ids = new List<uint>(count);
|
||||
foreach (var e in db.EnumerateEntries()) ids.Add(e.ObjectId);
|
||||
double enumMs = sw.Elapsed.TotalMilliseconds;
|
||||
sw.Restart();
|
||||
long bytes = 0;
|
||||
foreach (uint id in ids) bytes += db.GetFileData(id)?.Length ?? 0;
|
||||
double readMs = sw.Elapsed.TotalMilliseconds;
|
||||
// A fresh reader for the lookups, so they start cold (like a plugin after Open).
|
||||
db.Dispose();
|
||||
db = new DatDatabase();
|
||||
db.Open(path);
|
||||
var rng = new Random(7);
|
||||
sw.Restart();
|
||||
for (int i = 0; i < 200_000; i++) db.FindFile(ids[rng.Next(ids.Count)]);
|
||||
double findMs = sw.Elapsed.TotalMilliseconds;
|
||||
sw.Restart();
|
||||
int cells = 0;
|
||||
for (uint lb = 0; lb <= 0xFFFF; lb++) { cells += db.GetLandblockCellIds(lb).Count; db.FindFile((lb << 16) | 0xFFFF); db.FindFile((lb << 16) | 0xFFFE); }
|
||||
double lbMs = sw.Elapsed.TotalMilliseconds;
|
||||
db.Dispose();
|
||||
Console.WriteLine($" round {r + 1}: open {open:F1} ms, RecordCount {rcMs:F0} ms, enumerate {enumMs:F0} ms, read all {ids.Count} files ({bytes / 1048576.0:F0} MB) {readMs:F0} ms, " +
|
||||
$"200k random FindFile {findMs:F0} ms, 65,536 landblocks (cell ids + FFFF + FFFE) {lbMs:F0} ms");
|
||||
}
|
||||
}
|
||||
var p = Process.GetCurrentProcess();
|
||||
p.Refresh();
|
||||
Console.WriteLine($"peak working set {p.PeakWorkingSet64 / 1048576.0:F1} MB");
|
||||
return 0;
|
||||
}
|
||||
|
||||
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
|
||||
private static double ReaderHeapKb(string path)
|
||||
{
|
||||
long before = GC.GetTotalMemory(true);
|
||||
var db = Warm(path);
|
||||
long after = GC.GetTotalMemory(true);
|
||||
GC.KeepAlive(db);
|
||||
db.Dispose();
|
||||
return (after - before) / 1024.0;
|
||||
}
|
||||
|
||||
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
|
||||
private static DatDatabase Warm(string path)
|
||||
{
|
||||
var db = new DatDatabase();
|
||||
db.Open(path);
|
||||
_ = db.RecordCount;
|
||||
for (uint lb = 0; lb <= 0xFFFF; lb++) { db.GetLandblockCellIds(lb); db.FindFile((lb << 16) | 0xFFFF); }
|
||||
return db;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ geo
|
||||
|
||||
private static int Geo(string acDir, string outPath)
|
||||
{
|
||||
using var w = new StreamWriter(outPath, false, new UTF8Encoding(false));
|
||||
w.NewLine = "\n";
|
||||
var sw = Stopwatch.StartNew();
|
||||
var geo = new GeometryLoader();
|
||||
if (!geo.Initialize(acDir)) { Console.WriteLine("Geometry loader failed: " + geo.StatusMessage); return 1; }
|
||||
w.WriteLine($"#t GeometryLoader.Initialize {sw.Elapsed.TotalMilliseconds:F0} ms");
|
||||
w.WriteLine("status " + geo.StatusMessage);
|
||||
|
||||
var dungeonLbs = new SortedSet<uint>();
|
||||
foreach (var e in geo.CellDat.EnumerateEntries())
|
||||
{
|
||||
uint low = e.ObjectId & 0xFFFF;
|
||||
if (low >= 0x0100 && low <= 0xFFFD) dungeonLbs.Add(e.ObjectId >> 16);
|
||||
}
|
||||
w.WriteLine($"landblocks-with-cells {dungeonLbs.Count}");
|
||||
|
||||
double dungeonMs = 0, outdoorMs = 0, slowest = 0;
|
||||
uint slowestLb = 0;
|
||||
int vols = 0, polys = 0;
|
||||
foreach (uint lb in dungeonLbs)
|
||||
{
|
||||
var t = Stopwatch.StartNew();
|
||||
var v = geo.GetLandblockGeometry((lb << 16) | 0x0100);
|
||||
var p = geo.DungeonLOS.GetDungeonMapPolygons(lb);
|
||||
var fl = geo.DungeonLOS.GetDungeonMapFloorPolygons(lb);
|
||||
var cells = geo.DungeonLOS.GetDungeonMapCells(lb);
|
||||
double ms = t.Elapsed.TotalMilliseconds;
|
||||
dungeonMs += ms;
|
||||
if (ms > slowest) { slowest = ms; slowestLb = lb; }
|
||||
vols += v.Count; polys += p.Count;
|
||||
w.WriteLine($"d {lb:X4} v{v.Count} {Digest(v)} p{p.Count} {Digest(p)} f{fl.Count} {Digest(fl)} c{cells.Count}");
|
||||
geo.FlushLandblock(lb);
|
||||
}
|
||||
w.WriteLine($"#t dungeon landblocks {dungeonLbs.Count}: {dungeonMs:F0} ms total, {dungeonMs / Math.Max(1, dungeonLbs.Count):F2} ms each, slowest {slowestLb:X4} {slowest:F1} ms");
|
||||
Console.WriteLine($"dungeons: {dungeonLbs.Count} landblocks, {vols} volumes, {polys} polygons, {dungeonMs:F0} ms");
|
||||
|
||||
int outdoor = 0;
|
||||
for (uint x = 0; x < 256; x += 4)
|
||||
for (uint y = 0; y < 256; y += 4)
|
||||
{
|
||||
uint lb = (x << 8) | y;
|
||||
var t = Stopwatch.StartNew();
|
||||
var v = geo.GetLandblockGeometry((lb << 16) | 0x0001);
|
||||
float z = geo.GetTerrainZWorld(x * 192f + 96f, y * 192f + 96f);
|
||||
outdoorMs += t.Elapsed.TotalMilliseconds;
|
||||
outdoor++;
|
||||
w.WriteLine($"o {lb:X4} v{v.Count} {Digest(v)} z{BitConverter.SingleToInt32Bits(z):X8}");
|
||||
geo.FlushLandblock(lb);
|
||||
}
|
||||
w.WriteLine($"#t outdoor landblocks {outdoor}: {outdoorMs:F0} ms total, {outdoorMs / outdoor:F2} ms each");
|
||||
Console.WriteLine($"outdoor: {outdoor} landblocks, {outdoorMs:F0} ms");
|
||||
var proc = Process.GetCurrentProcess();
|
||||
proc.Refresh();
|
||||
w.WriteLine($"#t process peak working set {proc.PeakWorkingSet64 / 1048576.0:F1} MB");
|
||||
geo.Dispose();
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static string Digest(List<BoundingVolume> vs)
|
||||
{
|
||||
using var h = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
|
||||
foreach (var v in vs)
|
||||
{
|
||||
Add(h, (int)v.Type); Add(h, v.Center); Add(h, v.Dimensions); Add(h, v.Min); Add(h, v.Max);
|
||||
Add(h, v.IsDoor ? 1 : 0); Add(h, v.NoAabbFallback ? 1 : 0);
|
||||
Add(h, v.Vertices); Add(h, v.MeshTriangles);
|
||||
}
|
||||
return Convert.ToHexString(h.GetHashAndReset(), 0, 12);
|
||||
}
|
||||
|
||||
private static string Digest(List<DungeonLOS.MapPolygon> ps)
|
||||
{
|
||||
using var h = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
|
||||
foreach (var p in ps)
|
||||
{
|
||||
Add(h, p.Vertices); Add(h, new Vector3(p.CellX, p.CellY, p.CellZ));
|
||||
Add(h, p.IsPortal ? 1 : 0); Add(h, p.IsFloor ? 1 : 0); Add(h, (int)p.CellId);
|
||||
}
|
||||
return Convert.ToHexString(h.GetHashAndReset(), 0, 12);
|
||||
}
|
||||
|
||||
private static void Add(IncrementalHash h, int v) { Span<byte> b = stackalloc byte[4]; BitConverter.TryWriteBytes(b, v); h.AppendData(b); }
|
||||
private static void Add(IncrementalHash h, Vector3 v)
|
||||
{
|
||||
Add(h, BitConverter.SingleToInt32Bits(v.X)); Add(h, BitConverter.SingleToInt32Bits(v.Y)); Add(h, BitConverter.SingleToInt32Bits(v.Z));
|
||||
}
|
||||
private static void Add(IncrementalHash h, Vector3[] vs)
|
||||
{
|
||||
if (vs == null) { Add(h, -1); return; }
|
||||
Add(h, vs.Length);
|
||||
foreach (var v in vs) Add(h, v);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ diff
|
||||
|
||||
private static int Diff(string a, string b)
|
||||
{
|
||||
var la = File.ReadLines(a).Where(l => !l.StartsWith("#t")).GetEnumerator();
|
||||
var lb = File.ReadLines(b).Where(l => !l.StartsWith("#t")).GetEnumerator();
|
||||
long n = 0, diffs = 0;
|
||||
while (true)
|
||||
{
|
||||
bool ha = la.MoveNext(), hb = lb.MoveNext();
|
||||
if (!ha && !hb) break;
|
||||
n++;
|
||||
string sa = ha ? la.Current : "<end>", sb = hb ? lb.Current : "<end>";
|
||||
if (sa != sb)
|
||||
{
|
||||
if (diffs < 40) Console.WriteLine($"line {n}:\n a: {sa}\n b: {sb}");
|
||||
diffs++;
|
||||
}
|
||||
}
|
||||
Console.WriteLine($"{n} lines compared, {diffs} differ");
|
||||
Console.WriteLine("timings a:");
|
||||
foreach (var l in File.ReadLines(a).Where(l => l.StartsWith("#t"))) Console.WriteLine(" " + l);
|
||||
Console.WriteLine("timings b:");
|
||||
foreach (var l in File.ReadLines(b).Where(l => l.StartsWith("#t"))) Console.WriteLine(" " + l);
|
||||
return diffs == 0 ? 0 : 1;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!--
|
||||
Checks a change to the dat reader (Shared\RynthCore.TerrainData\DatDatabase.cs) against the
|
||||
reader it replaces, on the real dat files, read only. It uses only the reader's public API, so
|
||||
the same source builds against the old reader (check out the base commit) and the new one;
|
||||
each build writes a manifest and "diff" compares two manifests:
|
||||
|
||||
manifest <AC folder> <out> every file in client_portal.dat and client_cell_1.dat: id,
|
||||
flags, offset, size and a SHA-256 of its bytes; FindFile misses
|
||||
for every landblock and for a fixed set of random ids;
|
||||
GetLandblockCellIds for all 65,536 landblocks; timings.
|
||||
geo <AC folder> <out> every dungeon landblock (and every 16th outdoor one) through
|
||||
RynthAi's GeometryLoader + DungeonLOS: a digest of the LOS
|
||||
volumes and map polygons, and how long each load took.
|
||||
diff <a> <b> compares two manifests (timing lines, "#t", are skipped).
|
||||
|
||||
Run: dotnet run -c Release (after the usual separator) manifest "C:\Turbine\Asheron's Call" old.txt
|
||||
-->
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0-windows</TargetFramework>
|
||||
<Nullable>disable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<RootNamespace>RynthCore.DatReaderCheck</RootNamespace>
|
||||
<NoWarn>$(NoWarn);CS8632</NoWarn>
|
||||
<ServerGarbageCollection>false</ServerGarbageCollection>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\Raycasting\BoundingVolume.cs" Link="Linked\BoundingVolume.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\Raycasting\DungeonLOS.cs" Link="Linked\DungeonLOS.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\Raycasting\GeometryLoader.cs" Link="Linked\GeometryLoader.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\Raycasting\LandblockStructs.cs" Link="Linked\LandblockStructs.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\Raycasting\ScatterSystem.cs" Link="Linked\ScatterSystem.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" />
|
||||
<ProjectReference Include="..\..\Shared\RynthCore.TerrainData\RynthCore.TerrainData.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
@ -38,6 +38,7 @@ internal static partial class Program
|
|||
TestAddJsonInsert(crlf: false);
|
||||
TestAddJsonInsert(crlf: true);
|
||||
TestAddJsonEdgeCases();
|
||||
TestAddBuiltInReasonWire();
|
||||
TestAddDeployedCopies(args);
|
||||
}
|
||||
finally
|
||||
|
|
@ -46,6 +47,20 @@ internal static partial class Program
|
|||
}
|
||||
}
|
||||
|
||||
// The popup's "why RynthAi takes it anyway" (2026-10-05): on the wire next to OrderNote,
|
||||
// and a payload from a RynthAi without it reads as empty.
|
||||
private static void TestAddBuiltInReasonWire()
|
||||
{
|
||||
Console.WriteLine("\n-- LootAdd: built-in keep reason on the wire --");
|
||||
var st = new LootEditState { ItemDraft = new LootEditItemDraft { Seq = 3, OrderNote = "Goes in at the end. Why.", BuiltInReason = "Why." } };
|
||||
string json = System.Text.Json.JsonSerializer.Serialize(st, LootEditJsonContext.Default.LootEditState);
|
||||
LootEditState? back = System.Text.Json.JsonSerializer.Deserialize(json, LootEditJsonContext.Default.LootEditState);
|
||||
Eq(back?.ItemDraft?.BuiltInReason, "Why.", "BuiltInReason round-trips");
|
||||
Eq(back?.ItemDraft?.OrderNote, "Goes in at the end. Why.", "OrderNote too");
|
||||
LootEditState? old = System.Text.Json.JsonSerializer.Deserialize("{\"ItemDraft\":{\"Seq\":1,\"OrderNote\":\"x\"}}", LootEditJsonContext.Default.LootEditState);
|
||||
Eq(old?.ItemDraft?.BuiltInReason, "", "an older RynthAi's draft: empty");
|
||||
}
|
||||
|
||||
private static string AddFile(string name, byte[] bytes)
|
||||
{
|
||||
string path = Path.Combine(_addDir, name);
|
||||
|
|
|
|||
|
|
@ -81,6 +81,14 @@ internal static unsafe class FakeHost
|
|||
public static int Jumps;
|
||||
public static int Turns;
|
||||
public static readonly List<(uint Target, int SpellId)> Casts = new();
|
||||
/// <summary>Opt-in: wires GiveObjectTo (AC's give action); every call lands in <see cref="Gives"/>.</summary>
|
||||
public static bool GiveCalls;
|
||||
/// <summary>Every GiveObjectTo (item, target, amount; 0 = the whole object), in order.</summary>
|
||||
public static readonly List<(uint Item, uint Target, int Amount)> Gives = new();
|
||||
/// <summary>Opt-in: wires StopCompletely (off by default so no other test sees it).</summary>
|
||||
public static bool StopCalls;
|
||||
/// <summary>StopCompletely calls (opt-in with <see cref="StopCalls"/>).</summary>
|
||||
public static int Stops;
|
||||
/// <summary>Every UseObject (a wield, a use) and RequestId (an identify), in order.</summary>
|
||||
public static readonly List<uint> Uses = new();
|
||||
public static readonly List<uint> IdRequests = new();
|
||||
|
|
@ -100,6 +108,12 @@ internal static unsafe class FakeHost
|
|||
public static bool ServerGates;
|
||||
/// <summary>The count of server UseDone (0x01C7) events the fake reports.</summary>
|
||||
public static int UseDoneSeq;
|
||||
/// <summary>The error code of the last UseDone (GetLastUseDone, v70; 0 = completed, 0x1D = too busy).
|
||||
/// Opt-in with <see cref="LastUseDoneCalls"/> (set before Create, together with ServerGates).</summary>
|
||||
public static uint LastUseDoneError;
|
||||
public static bool LastUseDoneCalls;
|
||||
/// <summary>One more UseDone with <paramref name="error"/> (0 = the action completed).</summary>
|
||||
public static void UseDone(uint error) { UseDoneSeq++; LastUseDoneError = error; }
|
||||
/// <summary>1 while a cast gesture animates (GetCastBusyState), else 0.</summary>
|
||||
public static int CastBusy;
|
||||
public static int VTankSeq;
|
||||
|
|
@ -135,6 +149,12 @@ internal static unsafe class FakeHost
|
|||
public static uint GroundContainer;
|
||||
/// <summary>The item selected in the game (GetSelectedItemId); 0 = none.</summary>
|
||||
public static uint SelectedItem;
|
||||
/// <summary>Opt-in: install SendPluginCommand (the engine's plugin-command broker, API v64).</summary>
|
||||
public static bool PluginCommandCalls;
|
||||
/// <summary>What SendPluginCommand answers: true = delivered (the target plugin is loaded).</summary>
|
||||
public static bool PluginCommandDelivered = true;
|
||||
/// <summary>Every SendPluginCommand (plugin, action, value), in order.</summary>
|
||||
public static readonly List<(string Plugin, string Action, string Value)> PluginCommands = new();
|
||||
|
||||
// ANSI strings handed back to tested code stay alive for the whole run.
|
||||
private static readonly Dictionary<string, IntPtr> _ansi = new();
|
||||
|
|
@ -150,15 +170,16 @@ internal static unsafe class FakeHost
|
|||
Vitals = default; BaseVitals = default; WorldName = ""; AccountName = "";
|
||||
HeadingDeg = 0; Wcids.Clear(); Spellbook.Clear(); PlayerIdValue = 0;
|
||||
Logs.Clear(); Chat.Clear(); ChatCommands.Clear();
|
||||
AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; Turns = 0; Casts.Clear();
|
||||
AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; Turns = 0; Casts.Clear(); StopCalls = false; Stops = 0; GiveCalls = false; Gives.Clear();
|
||||
Uses.Clear(); IdRequests.Clear(); Moves.Clear(); Appraised.Clear(); WeaponCalls = false; CombatModeValue = 1;
|
||||
VTankFlags = -1; VTankSeq = 0; LogCostMicros = 0;
|
||||
ServerGates = false; UseDoneSeq = 0; CastBusy = 0;
|
||||
ServerGates = false; UseDoneSeq = 0; CastBusy = 0; LastUseDoneError = 0; LastUseDoneCalls = false;
|
||||
WieldCalls = false; Wields.Clear();
|
||||
SalvageCalls = false; ExternalMoves.Clear(); SalvageAdds.Clear(); SalvageExecutes.Clear();
|
||||
RefuseSalvageAdd.Clear(); OnSalvageExecute = null; Wielded.Clear(); _panelItems.Clear();
|
||||
CloseContainerCalls = false; Closes.Clear(); GroundContainer = 0;
|
||||
SelectedItem = 0;
|
||||
PluginCommandCalls = false; PluginCommandDelivered = true; PluginCommands.Clear();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -199,6 +220,10 @@ internal static unsafe class FakeHost
|
|||
api.TurnToHeadingFn = (IntPtr)(delegate* unmanaged[Cdecl]<float, int>)&TurnToHeading;
|
||||
api.JumpNonAutonomousFn = (IntPtr)(delegate* unmanaged[Cdecl]<float, int>)&JumpNonAutonomous;
|
||||
api.CastSpellFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int, int>)&CastSpell;
|
||||
if (StopCalls)
|
||||
api.StopCompletelyFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&StopCompletely;
|
||||
if (GiveCalls)
|
||||
api.GiveObjectToFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, int, int>)&GiveObjectTo;
|
||||
if (WeaponCalls)
|
||||
{
|
||||
api.UseObjectFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int>)&UseObject;
|
||||
|
|
@ -256,6 +281,8 @@ internal static unsafe class FakeHost
|
|||
{
|
||||
api.GetUseDoneSeqFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&GetUseDoneSeq;
|
||||
api.GetCastBusyStateFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&GetCastBusyState;
|
||||
if (LastUseDoneCalls)
|
||||
api.GetLastUseDoneFn = (IntPtr)(delegate* unmanaged[Cdecl]<int*, uint*, int>)&GetLastUseDone;
|
||||
}
|
||||
if (VTankFlags >= 0)
|
||||
{
|
||||
|
|
@ -268,6 +295,11 @@ internal static unsafe class FakeHost
|
|||
api.CloseContainerFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int>)&CloseContainer;
|
||||
api.GetGroundContainerIdFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint>)&GetGroundContainerId;
|
||||
}
|
||||
if (PluginCommandCalls)
|
||||
{
|
||||
api.Version = Math.Max(api.Version, 64u);
|
||||
api.SendPluginCommandFn = (IntPtr)(delegate* unmanaged[Cdecl]<IntPtr, IntPtr, IntPtr, int>)&SendPluginCommand;
|
||||
}
|
||||
LastApi = api;
|
||||
return new RynthCoreHost(api);
|
||||
}
|
||||
|
|
@ -327,9 +359,24 @@ internal static unsafe class FakeHost
|
|||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int GetCastBusyState() => CastBusy;
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int GetLastUseDone(int* seq, uint* error)
|
||||
{
|
||||
*seq = UseDoneSeq;
|
||||
*error = UseDoneSeq == 0 ? 0 : LastUseDoneError;
|
||||
return 1;
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int WriteToChat(IntPtr text, int type) { Chat.Add(Marshal.PtrToStringUni(text) ?? ""); return 1; }
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int SendPluginCommand(IntPtr plugin, IntPtr action, IntPtr value)
|
||||
{
|
||||
PluginCommands.Add((Marshal.PtrToStringAnsi(plugin) ?? "", Marshal.PtrToStringAnsi(action) ?? "", Marshal.PtrToStringAnsi(value) ?? ""));
|
||||
return PluginCommandDelivered ? 1 : 0;
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int InvokeChatParser(IntPtr text) { ChatCommands.Add(Marshal.PtrToStringUni(text) ?? ""); return 1; }
|
||||
|
||||
|
|
@ -511,6 +558,10 @@ internal static unsafe class FakeHost
|
|||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int CastSpell(uint target, int spellId) { Casts.Add((target, spellId)); return 1; }
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int StopCompletely() { Stops++; return 1; }
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int GiveObjectTo(uint item, uint target, int amount) { Gives.Add((item, target, amount)); return 1; }
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int GetCurrentCombatMode() => CombatModeValue;
|
||||
|
|
|
|||
|
|
@ -28,6 +28,8 @@ internal static class Program
|
|||
ExpressionEngine.PvarsDir = Path.Combine(TempRoot, "pvars");
|
||||
ExpressionEngine.GvarsPath = Path.Combine(TempRoot, "gvars.txt");
|
||||
ExpressionEngine.ItemGiverDir = Path.Combine(TempRoot, "ItemGiver");
|
||||
// The dungeon map bake writes floor plans under C:\Games\RynthSuite\RynthAi\Maps.
|
||||
RynthCore.Plugin.RynthAi.Maps.DungeonMapBake.CacheDir = Path.Combine(TempRoot, "Maps");
|
||||
|
||||
// Spell names (item spells, spell expiry by name) come from the plugin's embedded table.
|
||||
SpellDatabase.Load();
|
||||
|
|
@ -50,13 +52,18 @@ internal static class Program
|
|||
FloodPerfTests.Register(runner);
|
||||
LootSalvageTests.Register(runner);
|
||||
LootCorpseTests.Register(runner);
|
||||
OwnCorpseTests.Register(runner);
|
||||
VitalsTests.Register(runner);
|
||||
CastSafetyTests.Register(runner);
|
||||
HealLatencyTests.Register(runner);
|
||||
BlastTests.Register(runner);
|
||||
ArcWhenClearTests.Register(runner);
|
||||
UseAtLoginTests.Register(runner);
|
||||
LearnSpellsTests.Register(runner);
|
||||
AttackLatencyTests.Register(runner);
|
||||
LootAddItemTests.Register(runner);
|
||||
GiveTests.Register(runner);
|
||||
DungeonMapBakeTests.Register(runner);
|
||||
return runner.Run("RynthAi host tests", args.Length > 0 ? args[0] : null);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,9 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text.Json;
|
||||
using RynthCore.Loot;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
|
|
@ -48,6 +51,9 @@ internal static class BuffTests
|
|||
r.Add("rebuff: permanent, expired, and two enchantments in one family", RebuffPermanentAndDuplicates);
|
||||
r.Add("rebuff: a higher tier is only chased above the tier that has landed", RebuffTierUpgrade);
|
||||
r.Add("rebuff: a chat-confirmed item spell counts as on", ItemSpellFromChat);
|
||||
r.Add("rebuff: our own lower tier under an expiring higher one counts as on", RebuffUnderExpiringHigherTier);
|
||||
r.Add("rebuff: cast over item-granted buffs (CastBuffsOverItemBuffs on)", RebuffOverItemBuffs);
|
||||
r.Add("rebuff: CastBuffsOverItemBuffs defaults on, loads, saves, bridges", OverItemBuffsSetting);
|
||||
|
||||
r.Add("buff choice: spell names the tables miss (Bludgeon Bane, Nuhmudira's, T'ing, Celdiseth's)", NameGapsResolve); // was a known failure; fixed by 940cb21
|
||||
r.Add("buff choice: a mastery whose name has several spell ids", MultiIdMastery); // was a known failure; fixed by 0aedcee
|
||||
|
|
@ -438,21 +444,26 @@ internal static class BuffTests
|
|||
Check.True(rig.B.NeedsAnyBuff(), "Force Rebuff: everything is due");
|
||||
}
|
||||
|
||||
// CastBuffsOverItemBuffs off: the behaviour before 2026-10-05 (an item-granted permanent
|
||||
// entry at the tier we'd cast satisfies the family). The setting's own cases are below.
|
||||
private static void RebuffPermanentAndDuplicates()
|
||||
{
|
||||
var rig = StrengthRig(300, "Strength Self VI");
|
||||
rig.S.CastBuffsOverItemBuffs = false;
|
||||
rig.Live(("Strength Self VI", double.MaxValue));
|
||||
Check.False(rig.B.NeedsAnyBuff(), "a permanent enchantment counts as on");
|
||||
rig.Live(("Strength Self VI", -5));
|
||||
Check.True(rig.B.NeedsAnyBuff(), "an expired entry is dropped: recast");
|
||||
|
||||
var t7 = StrengthRig(340, "Strength Self VI", "Might of the Lugians"); // 340 buffed: tier 7
|
||||
t7.S.CastBuffsOverItemBuffs = false;
|
||||
t7.Live(("Strength Self VI", double.MaxValue), ("Might of the Lugians", 3000));
|
||||
Check.False(t7.B.NeedsAnyBuff(), "a permanent VI and a timed VII: the VII owns the family");
|
||||
t7.Live(("Might of the Lugians", 3000), ("Strength Self VI", double.MaxValue));
|
||||
Check.False(t7.B.NeedsAnyBuff(), "same in the other order");
|
||||
|
||||
var item = StrengthRig(340, "Strength Self VI", "Might of the Lugians");
|
||||
item.S.CastBuffsOverItemBuffs = false;
|
||||
item.Live(("Strength Self VI", double.MaxValue));
|
||||
Check.True(item.B.NeedsAnyBuff(), "only a permanent (item-granted) VI while VII is castable: cast the VII");
|
||||
}
|
||||
|
|
@ -473,6 +484,118 @@ internal static class BuffTests
|
|||
Check.False(inc.B.NeedsAnyBuff(), "an Incantation that lands as VI isn't recast for ever");
|
||||
}
|
||||
|
||||
// A buff bot's level 8 that runs out while our own lower tier is already under it
|
||||
// (Drakkon, 2026-10-05): the 8 owns the family timer, so the family read "due"
|
||||
// right after our VI landed and every pass recast it until the batch audit parked it.
|
||||
private static void RebuffUnderExpiringHigherTier()
|
||||
{
|
||||
var rig = StrengthRig(300, "Strength Self VI"); // 300 buffed: tier 6
|
||||
rig.Live(("Incantation of Strength Self", 3000));
|
||||
Check.False(rig.B.NeedsAnyBuff(), "a bot's 8 with 3000 s left: fine");
|
||||
rig.Live(("Incantation of Strength Self", 200));
|
||||
Check.True(rig.B.NeedsAnyBuff(), "the 8 is running out and nothing is under it: cast our VI");
|
||||
rig.Live(("Incantation of Strength Self", 200), ("Strength Self VI", 1800));
|
||||
Check.False(rig.B.NeedsAnyBuff(), "our VI is under the expiring 8: covered, no recast");
|
||||
rig.Live(("Strength Self VI", 1800), ("Incantation of Strength Self", 200));
|
||||
Check.False(rig.B.NeedsAnyBuff(), "same in the other order");
|
||||
rig.Live(("Incantation of Strength Self", 200), ("Strength Self VI", 250));
|
||||
Check.True(rig.B.NeedsAnyBuff(), "both under the threshold: recast");
|
||||
|
||||
var low = StrengthRig(300, "Strength Self V", "Strength Self VI");
|
||||
low.Live(("Incantation of Strength Self", 200), ("Strength Self V", 1800));
|
||||
Check.True(low.B.NeedsAnyBuff(), "only a V under it while VI is castable: still cast the VI");
|
||||
low.S.CastBuffsOverItemBuffs = false;
|
||||
low.Live(("Incantation of Strength Self", 200), ("Strength Self VI", double.MaxValue));
|
||||
Check.False(low.B.NeedsAnyBuff(), "setting off: a permanent VI under it covers it");
|
||||
low.S.CastBuffsOverItemBuffs = true;
|
||||
low.Live(("Incantation of Strength Self", 200), ("Strength Self VI", double.MaxValue));
|
||||
Check.True(low.B.NeedsAnyBuff(), "setting on: a permanent (item) VI under it doesn't cover it: cast ours");
|
||||
}
|
||||
|
||||
// "Cast buffs even when an item already gives that buff" (CastBuffsOverItemBuffs, default
|
||||
// on, 2026-10-05). On servers with buff augments a player's own cast is stronger or longer
|
||||
// than the item's, so a permanent item-granted entry must not satisfy the family; the timer
|
||||
// follows our own timed entry, and once that lands it reads on until it runs low.
|
||||
private static void RebuffOverItemBuffs()
|
||||
{
|
||||
var rig = StrengthRig(300, "Strength Self VI"); // tier 6
|
||||
Check.True(rig.S.CastBuffsOverItemBuffs, "on by default");
|
||||
rig.Live(("Strength Self VI", double.MaxValue));
|
||||
Check.True(rig.B.NeedsAnyBuff(), "only an item's permanent VI: cast our own");
|
||||
rig.Live(("Strength Self VI", double.MaxValue), ("Strength Self VI", 3000));
|
||||
Check.False(rig.B.NeedsAnyBuff(), "our VI landed (3000 s) over the item's VI: on, no recast loop");
|
||||
rig.Live(("Strength Self VI", 3000), ("Strength Self VI", double.MaxValue));
|
||||
Check.False(rig.B.NeedsAnyBuff(), "same in the other order");
|
||||
rig.Live(("Strength Self VI", double.MaxValue), ("Strength Self VI", 200));
|
||||
Check.True(rig.B.NeedsAnyBuff(), "ours running low (200 s) with the item's VI still on: recast");
|
||||
rig.Live(("Strength Self VI", 200), ("Strength Self VI", double.MaxValue));
|
||||
Check.True(rig.B.NeedsAnyBuff(), "same in the other order");
|
||||
rig.Live(("Strength Self VI", double.MaxValue), ("Strength Self VI", 2700));
|
||||
Check.False(rig.B.NeedsAnyBuff(), "recast landed: on again");
|
||||
|
||||
// A higher item tier than we can cast: ours is still cast and tracked.
|
||||
var high = StrengthRig(300, "Strength Self VI");
|
||||
high.Live(("Might of the Lugians", double.MaxValue));
|
||||
Check.True(high.B.NeedsAnyBuff(), "an item's permanent VII, we cast VI: cast it");
|
||||
high.Live(("Might of the Lugians", double.MaxValue), ("Strength Self VI", 3000));
|
||||
Check.False(high.B.NeedsAnyBuff(), "our VI under the item's VII: on until it runs low");
|
||||
high.Live(("Might of the Lugians", double.MaxValue), ("Strength Self VI", 100));
|
||||
Check.True(high.B.NeedsAnyBuff(), "our VI running low: recast");
|
||||
|
||||
// The tier-upgrade rule still works on our timed entries.
|
||||
var up = StrengthRig(340, "Strength Self VI", "Might of the Lugians"); // tier 7
|
||||
up.Live(("Might of the Lugians", 3000));
|
||||
up.Live(("Strength Self VI", double.MaxValue), ("Strength Self V", 3000));
|
||||
Check.True(up.B.NeedsAnyBuff(), "VII has landed before: our V is upgraded, the item's VI doesn't stop it");
|
||||
up.Live(("Strength Self VI", double.MaxValue), ("Might of the Lugians", 3000));
|
||||
Check.False(up.B.NeedsAnyBuff(), "our VII on: fine");
|
||||
|
||||
// Switched on between live reads: a permanent that owns the timer no longer counts.
|
||||
var toggled = StrengthRig(300, "Strength Self VI");
|
||||
toggled.S.CastBuffsOverItemBuffs = false;
|
||||
toggled.Live(("Strength Self VI", double.MaxValue));
|
||||
Check.False(toggled.B.NeedsAnyBuff(), "off: the item's VI counts");
|
||||
toggled.S.CastBuffsOverItemBuffs = true;
|
||||
Check.True(toggled.B.NeedsAnyBuff(), "switched on before the next read: cast ours");
|
||||
toggled.S.CastBuffsOverItemBuffs = false;
|
||||
toggled.Live(("Strength Self VI", double.MaxValue));
|
||||
Check.False(toggled.B.NeedsAnyBuff(), "switched back off: the item's VI counts again");
|
||||
}
|
||||
|
||||
private static void OverItemBuffsSetting()
|
||||
{
|
||||
Check.True(new LegacyUiSettings().CastBuffsOverItemBuffs, "a new profile: on");
|
||||
var old = JsonSerializer.Deserialize("{\"EnableBuffing\":true,\"RebuffSecondsRemaining\":300}", RynthAiJsonContext.Default.LegacyUiSettings);
|
||||
Check.True(old != null && old.CastBuffsOverItemBuffs, "a profile saved before the setting: on");
|
||||
var off = JsonSerializer.Deserialize(
|
||||
JsonSerializer.Serialize(new LegacyUiSettings { CastBuffsOverItemBuffs = false }, RynthAiJsonContext.Default.LegacyUiSettings),
|
||||
RynthAiJsonContext.Default.LegacyUiSettings);
|
||||
Check.True(off != null && !off.CastBuffsOverItemBuffs, "off is saved and loaded");
|
||||
|
||||
// Profile switch/load copies it (CopySettings is the hand-written field list).
|
||||
var copy = typeof(LegacyDashboardRenderer).GetMethod("CopySettings", BindingFlags.NonPublic | BindingFlags.Static)!;
|
||||
var dst = new LegacyUiSettings();
|
||||
copy.Invoke(null, new object[] { new LegacyUiSettings { CastBuffsOverItemBuffs = false }, dst });
|
||||
Check.False(dst.CastBuffsOverItemBuffs, "a profile with it off loads off");
|
||||
copy.Invoke(null, new object[] { old!, dst });
|
||||
Check.True(dst.CastBuffsOverItemBuffs, "an old profile loads on");
|
||||
|
||||
// Engine Settings face: the payload carries it; an engine without the field leaves it alone.
|
||||
var payload = JsonSerializer.Deserialize("{\"PatrolOnLogin\":false}", RynthAiJsonContext.Default.SettingsBridgePayload);
|
||||
Check.True(payload != null && payload.CastBuffsOverItemBuffs == null, "an older engine's payload has no value");
|
||||
var s = new LegacyUiSettings { CastBuffsOverItemBuffs = false };
|
||||
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
|
||||
typeof(LegacyDashboardRenderer).GetField("_settings", BindingFlags.NonPublic | BindingFlags.Instance)!.SetValue(dash, s);
|
||||
typeof(LegacyDashboardRenderer).GetField("_advancedSettingsUi", BindingFlags.NonPublic | BindingFlags.Instance)!
|
||||
.SetValue(dash, new LegacyAdvancedSettingsUi(s)); // BuildSettingsJson reads its crafting state
|
||||
var sent = JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload);
|
||||
Check.True(sent != null && sent.CastBuffsOverItemBuffs == false, "sent to the engine face");
|
||||
dash.ApplySettingsJson("{\"PatrolOnLogin\":false}");
|
||||
Check.False(s.CastBuffsOverItemBuffs, "a save without the field leaves it off");
|
||||
dash.ApplySettingsJson("{\"CastBuffsOverItemBuffs\":true}");
|
||||
Check.True(s.CastBuffsOverItemBuffs, "a save with it on turns it on");
|
||||
}
|
||||
|
||||
private static BuffRig ArmorRig()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
|
|
|
|||
457
Tools/RynthCore.RynthAiHostTests/Tests/CastSafetyTests.cs
Normal file
457
Tools/RynthCore.RynthAiHostTests/Tests/CastSafetyTests.cs
Normal file
|
|
@ -0,0 +1,457 @@
|
|||
using System;
|
||||
using System.Linq;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// Cast safeguards after Drakkon's held casts on DreamWeave (2026-10-05,
|
||||
// ops\overnight\2026-10-05-stuck-cast.md): give-up timed from the incantation, a refusal never
|
||||
// counts as the server finishing, the first cast after a stance change waits for the stance,
|
||||
// and a cast the server holds open gets exactly one movement nudge.
|
||||
//
|
||||
// BuffManager's cast-safety timing runs on an injectable clock (BuffManager.Clock), so these
|
||||
// tests move time by hand. The rig is a mage at 10% mana: the only thing CheckVitals can do is
|
||||
// cast Stamina to Mana Self.
|
||||
internal static class CastSafetyTests
|
||||
{
|
||||
private const uint Player = 0x50000B01;
|
||||
private const uint STypeLife = 33;
|
||||
private const uint TooBusy = 0x1D;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("cast safety: a vital's give-up runs from its incantation; from the send without one", GiveUpFromIncantation);
|
||||
r.Add("cast safety: give-up time is capped, and never earlier than the send-timed one", GiveUpCap);
|
||||
r.Add("cast safety: 'You're too busy!' and a 0x1D UseDone don't count as the server finishing", TooBusyIsNotDone);
|
||||
r.Add("cast safety: a result line for another spell doesn't clear the pending cast", ResultForAnotherSpell);
|
||||
r.Add("cast safety: the first cast after a stance change waits for Magic plus the settle", StanceWait);
|
||||
r.Add("cast safety: a cast held open gets exactly one movement nudge", NudgeOnce);
|
||||
// Drakkon's death, 2026-10-05 13:43:20 (ops\overnight\2026-10-05-death-fixes.md).
|
||||
r.Add("cast safety: an emergency heal waits for Magic plus 300 ms only; a top-off heal the full 1 s", EmergencyStanceWait);
|
||||
r.Add("cast safety: the stance clock starts when the client reads Magic, not at the first cast attempt", StanceClockFromObservation);
|
||||
r.Add("cast safety: the 4.1 s settle line: the stance was ready at 1 s, a kit in flight held the cast, and the line says so", StanceLateHolderNamed);
|
||||
r.Add("cast safety: a held heal is nudged at 2.8 s without waiting for a refusal, once", UrgentNudgeForHeal);
|
||||
r.Add("cast safety: any held cast is nudged early while health is under a heal line; not when health is fine", UrgentNudgeForLowHealth);
|
||||
r.Add("cast safety: no kit or potion while a cast is held open until its nudge, then one try per 3 s", HeldCastItemGate);
|
||||
r.Add("move audit: one line per call, repeats counted, subsystem in the line", MoveAuditLines);
|
||||
}
|
||||
|
||||
private sealed class Rig
|
||||
{
|
||||
public DateTime T0 = new(2026, 10, 5, 10, 30, 40);
|
||||
public DateTime NowAt;
|
||||
public readonly BuffManager B;
|
||||
public readonly LegacyUiSettings S;
|
||||
public readonly PlayerVitalsCache V;
|
||||
|
||||
public Rig(int combatMode = CombatMode.Magic)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.WeaponCalls = true;
|
||||
FakeHost.ServerGates = true;
|
||||
FakeHost.LastUseDoneCalls = true;
|
||||
FakeHost.CombatModeValue = combatMode;
|
||||
foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id);
|
||||
FakeHost.Skills[(Player, STypeLife)] = (400, 2);
|
||||
var host = FakeHost.Create();
|
||||
S = new LegacyUiSettings
|
||||
{
|
||||
IsMacroRunning = true, HealAt = 0, TopOffHP = 0, EmergencyHealAt = 0, StaminaToHealthAt = 0,
|
||||
GetManaAt = 50, TopOffMana = 50, RestamAt = 0, TopOffStam = 0, UsePotions = false,
|
||||
EnableBuffing = false,
|
||||
// OnHeartbeat's interval check runs on the real clock: keep it shut so a heartbeat
|
||||
// only resolves the pending cast and never casts again.
|
||||
SpellCastIntervalMs = 600_000,
|
||||
};
|
||||
var skills = new CharacterSkills(host);
|
||||
skills.SetPlayerId(Player);
|
||||
var sm = new SpellManager(host, S);
|
||||
sm.InitializeNatively();
|
||||
sm.SetCharacterSkills(skills);
|
||||
V = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 10 };
|
||||
B = new BuffManager(host, S, sm, V);
|
||||
B.SetCharacterSkills(skills);
|
||||
NowAt = T0;
|
||||
B.Clock = () => NowAt;
|
||||
B.MarkLiveBuffsReadyForTests();
|
||||
}
|
||||
|
||||
public void At(double seconds) => NowAt = T0.AddSeconds(seconds);
|
||||
public void Chat(string text, int type = 0) => B.OnChatWindowText(text, type);
|
||||
public void Incantation() => Chat("You say, \"Puish Zharil\"", 17);
|
||||
public int CastId => FakeHost.Casts.Last().SpellId;
|
||||
public string CastName => SpellTable.ById(CastId)?.Name ?? "";
|
||||
public bool Logged(string part) => FakeHost.Logs.Any(l => l.Contains(part, StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
private static void GiveUpFromIncantation()
|
||||
{
|
||||
// The DreamWeave case: incantation 1.0 s after the send, result 2.3 s after that.
|
||||
var r = new Rig();
|
||||
r.At(0);
|
||||
Check.True(r.B.CheckVitals(), "10% mana: Stamina to Mana is cast");
|
||||
Check.Eq(FakeHost.Casts.Count, 1, "one cast");
|
||||
int pending = r.B.PendingSpellId;
|
||||
Check.True(pending != 0, "the vital is pending");
|
||||
r.At(1.0); r.Incantation();
|
||||
r.At(2.6); r.B.OnHeartbeat();
|
||||
Check.Eq(r.B.PendingSpellId, pending, "2.6 s after the send, 1.6 s after the incantation: still waiting (the old timer gave up at 2.5 s)");
|
||||
r.At(3.9); r.B.OnHeartbeat();
|
||||
Check.Eq(r.B.PendingSpellId, pending, "2.9 s after the incantation: still waiting");
|
||||
r.At(4.1); r.B.OnHeartbeat();
|
||||
Check.Eq(r.B.PendingSpellId, 0, "3.1 s after the incantation: given up");
|
||||
Check.True(r.Logged("after its incantation") && r.Logged("released, no strike"), "the release line says it was timed from the incantation");
|
||||
|
||||
// No incantation at all: the send-timed 2.5 s as before.
|
||||
var q = new Rig();
|
||||
q.At(0);
|
||||
q.B.CheckVitals();
|
||||
int p2 = q.B.PendingSpellId;
|
||||
q.At(2.4); q.B.OnHeartbeat();
|
||||
Check.Eq(q.B.PendingSpellId, p2, "no incantation, 2.4 s: still waiting");
|
||||
q.At(2.6); q.B.OnHeartbeat();
|
||||
Check.Eq(q.B.PendingSpellId, 0, "no incantation, 2.6 s: given up from the send");
|
||||
Check.True(q.Logged("no incantation in"), "the release line says no incantation came");
|
||||
|
||||
// A healthy result inside the window resolves it, and the time is logged.
|
||||
var h = new Rig();
|
||||
h.At(0); h.B.CheckVitals();
|
||||
h.At(0.3); h.Incantation();
|
||||
h.At(2.6); h.Chat($"You cast {h.CastName} on yourself and lose 35 points of stamina and also gain 47 points of mana");
|
||||
Check.Eq(h.B.PendingSpellId, 0, "its result clears the pending cast");
|
||||
Check.True(h.Logged("[CastTime]") && h.Logged("2.30 s after its incantation (send to incantation 300 ms)"),
|
||||
"[CastTime] logs incantation-to-result and send-to-incantation");
|
||||
}
|
||||
|
||||
private static void GiveUpCap()
|
||||
{
|
||||
var t0 = new DateTime(2026, 10, 5);
|
||||
var c = new CastTracker.Cast { SentAt = t0 };
|
||||
Check.Eq(CastTracker.GiveUpAt(c, 2500), t0.AddMilliseconds(2500), "no incantation: the fallback from the send");
|
||||
c.IncantAt = t0.AddMilliseconds(100);
|
||||
Check.Eq(CastTracker.GiveUpAt(c, 2500), t0.AddMilliseconds(3100), "incantation at 0.1 s: 3 s after it");
|
||||
c.IncantAt = t0.AddMilliseconds(4500);
|
||||
Check.Eq(CastTracker.GiveUpAt(c, 2500), t0.AddMilliseconds(6000), "a very late incantation: capped 6 s after the send");
|
||||
c.IncantAt = t0.AddMilliseconds(500);
|
||||
Check.Eq(CastTracker.GiveUpAt(c, 5000), t0.AddMilliseconds(5000), "armor (5 s from the send): an early incantation never makes it earlier");
|
||||
}
|
||||
|
||||
private static void TooBusyIsNotDone()
|
||||
{
|
||||
// The cast is running on the server (incantation seen).
|
||||
var r = new Rig();
|
||||
r.At(0); r.B.CheckVitals();
|
||||
int pending = r.B.PendingSpellId;
|
||||
r.At(0.1);
|
||||
Check.True(r.B.IsAwaitingCastResolution(), "just sent: waiting for the server");
|
||||
FakeHost.UseDone(0);
|
||||
Check.True(r.B.IsAwaitingCastResolution(), "a UseDone(0) before the incantation is some earlier action's, not this cast's (the old wait cleared on it)");
|
||||
r.At(0.5); r.Incantation();
|
||||
FakeHost.UseDone(TooBusy);
|
||||
Check.True(r.B.IsAwaitingCastResolution(), "a 0x1D UseDone is a refusal, not 'done' (the old wait cleared on it)");
|
||||
r.At(1.0); r.Chat("You're too busy!");
|
||||
Check.True(r.B.IsAwaitingCastResolution(), "'You're too busy!' is not 'done'");
|
||||
Check.Eq(r.B.PendingSpellId, pending, "the running cast stays pending: the refusal was for something else");
|
||||
r.At(2.0); FakeHost.UseDone(0);
|
||||
Check.False(r.B.IsAwaitingCastResolution(), "a UseDone(0) after the incantation: the server finished it");
|
||||
Check.True(r.Logged("UseDone #"), "[CastTime] logs the UseDone that finished it");
|
||||
|
||||
// A cast refused before it started: the refusal is not 'done' either; the next UseDone(0)
|
||||
// (whatever the server was busy with, finishing) is.
|
||||
var q = new Rig();
|
||||
q.At(0); q.B.CheckVitals();
|
||||
q.At(0.3); q.Chat("You're too busy!");
|
||||
Check.Eq(q.B.PendingSpellId, 0, "a cast refused before its incantation is parked, as before");
|
||||
FakeHost.UseDone(TooBusy);
|
||||
Check.True(q.B.IsAwaitingCastResolution(), "refused: still waiting for the server to be free");
|
||||
q.At(1.0); FakeHost.UseDone(0);
|
||||
Check.False(q.B.IsAwaitingCastResolution(), "a UseDone(0) after the refusal: the server is free");
|
||||
|
||||
// The cast's own result line ends the wait.
|
||||
var s = new Rig();
|
||||
s.At(0); s.B.CheckVitals();
|
||||
s.At(0.4); s.Incantation();
|
||||
s.At(2.5); s.Chat($"You cast {s.CastName} on yourself and lose 18 points of stamina and also gain 24 points of mana");
|
||||
Check.False(s.B.IsAwaitingCastResolution(), "its result line: done");
|
||||
|
||||
// Mana and stamina casts wait for the server too (heals don't).
|
||||
var w = new Rig();
|
||||
w.At(0); w.B.CheckVitals();
|
||||
w.At(0.4); w.Incantation();
|
||||
w.At(3.5); w.B.OnHeartbeat(); // pending released (incantation + 3 s)
|
||||
Check.Eq(w.B.PendingSpellId, 0, "released");
|
||||
int before = FakeHost.Casts.Count;
|
||||
w.At(3.6);
|
||||
Check.True(w.B.CheckVitals(), "past the give-up the next Stamina to Mana may go");
|
||||
Check.Eq(FakeHost.Casts.Count, before + 1, "and it is cast");
|
||||
}
|
||||
|
||||
private static void ResultForAnotherSpell()
|
||||
{
|
||||
var r = new Rig();
|
||||
r.At(0); r.B.CheckVitals();
|
||||
int pending = r.B.PendingSpellId;
|
||||
r.At(0.2); r.Chat("You cast Strength Self V on yourself, refreshing Strength Self V");
|
||||
Check.Eq(r.B.PendingSpellId, pending, "a late result for Strength Self V doesn't clear the pending Stamina to Mana");
|
||||
Check.True(r.Logged("pending kept"), "and says so");
|
||||
r.At(1.0); r.Chat($"You cast {r.CastName} on yourself and lose 35 points of stamina and also gain 47 points of mana");
|
||||
Check.Eq(r.B.PendingSpellId, 0, "its own result does");
|
||||
}
|
||||
|
||||
private static void StanceWait()
|
||||
{
|
||||
// Peace mode, no wand listed: the bare-handed switch to Magic.
|
||||
var r = new Rig(CombatMode.NonCombat);
|
||||
r.At(0);
|
||||
Check.True(r.B.CheckVitals(), "out of Magic: the vital yields while the stance changes");
|
||||
Check.Eq(FakeHost.Casts.Count, 0, "no cast before the stance");
|
||||
FakeHost.CombatModeValue = CombatMode.Magic; // the client field flips 60 ms later
|
||||
r.At(0.06);
|
||||
Check.True(r.B.CheckVitals(), "client reads Magic: still yielding");
|
||||
Check.Eq(FakeHost.Casts.Count, 0, "no cast 60 ms after the stance request");
|
||||
r.At(0.55);
|
||||
r.B.CheckVitals();
|
||||
Check.Eq(FakeHost.Casts.Count, 0, "no cast at 0.55 s (when the first hung cast went out)");
|
||||
r.At(1.01);
|
||||
r.B.CheckVitals();
|
||||
Check.Eq(FakeHost.Casts.Count, 1, "cast once the stance has settled (1 s after the request, 300 ms after Magic)");
|
||||
Check.True(r.Logged("Magic stance settled"), "the settle is logged");
|
||||
|
||||
// Already in Magic, no stance change from us: no wait.
|
||||
var q = new Rig();
|
||||
q.At(0); q.B.CheckVitals();
|
||||
Check.Eq(FakeHost.Casts.Count, 1, "already in Magic: cast at once");
|
||||
}
|
||||
|
||||
private static void NudgeOnce()
|
||||
{
|
||||
var r = new Rig();
|
||||
MoveAudit.Reset();
|
||||
r.At(0); r.B.CheckVitals();
|
||||
string name = r.CastName;
|
||||
r.At(0.3); r.Incantation();
|
||||
r.At(5.0); r.Chat("You're too busy!");
|
||||
Check.Eq(FakeHost.AutoRunCalls.Count, 0, "4.7 s after the incantation: no nudge yet");
|
||||
r.At(6.5); r.Chat("You're too busy!");
|
||||
Check.True(FakeHost.AutoRunCalls.SequenceEqual(new[] { true, false }), "held 6.2 s and still refused: one nudge, autorun on then off");
|
||||
Check.Eq(r.B.CastNudges, 1, "one nudge counted");
|
||||
Check.True(r.Logged("[CastSafe]") && r.Logged("Buff/Nudge SetAutoRun(True)"), "the nudge is logged, with its subsystem");
|
||||
r.At(8.0); r.Chat("You're too busy!");
|
||||
r.At(12.0); r.Chat("You're too busy!");
|
||||
r.B.OnHeartbeat();
|
||||
Check.Eq(FakeHost.AutoRunCalls.Count, 2, "more refusals: no second nudge for the same held cast");
|
||||
Check.True(r.Logged("HELD"), "the held cast is logged once it passes 6 s");
|
||||
r.At(13.0); r.Chat($"You cast {name} on yourself and lose 97 points of stamina and also gain 131 points of mana");
|
||||
Check.True(r.Logged("(after the movement nudge)"), "its late result is logged as coming after the nudge");
|
||||
|
||||
// Macro off: no nudge.
|
||||
var q = new Rig();
|
||||
q.At(0); q.B.CheckVitals();
|
||||
q.At(0.3); q.Incantation();
|
||||
q.S.IsMacroRunning = false;
|
||||
q.At(7.0); q.Chat("You're too busy!");
|
||||
Check.Eq(FakeHost.AutoRunCalls.Count, 0, "macro off: nothing moves the character");
|
||||
}
|
||||
|
||||
// The same spell at any tier (skill 400 casts a high tier with its own name, e.g. Adja's Intervention).
|
||||
private static bool CastIs(string baseName)
|
||||
{
|
||||
if (FakeHost.Casts.Count == 0) return false;
|
||||
int cat = SpellTable.Named(baseName + " I").First().Category;
|
||||
return SpellTable.ById(FakeHost.Casts.Last().SpellId)?.Category == cat;
|
||||
}
|
||||
|
||||
// Drakkon at 27% under Emergency Heal At 30%: Heal Self waited the full stance settle
|
||||
// (at least 1 s after the request). An emergency heal now waits only for Magic plus 300 ms.
|
||||
private static void EmergencyStanceWait()
|
||||
{
|
||||
var r = new Rig(CombatMode.NonCombat);
|
||||
r.S.EmergencyHealAt = 30; r.S.HealAt = 60; r.S.TopOffHP = 60;
|
||||
r.V.CurrentHealth = 20;
|
||||
r.At(0);
|
||||
Check.True(r.B.CheckVitals(), "20% health out of Magic: Heal Self yields while the stance changes");
|
||||
Check.Eq(FakeHost.Casts.Count, 0, "no cast before the stance");
|
||||
FakeHost.CombatModeValue = CombatMode.Magic;
|
||||
r.At(0.06); r.B.CheckVitals();
|
||||
Check.Eq(FakeHost.Casts.Count, 0, "the client reads Magic: the 300 ms settle still runs");
|
||||
r.At(0.30); r.B.CheckVitals();
|
||||
Check.Eq(FakeHost.Casts.Count, 0, "240 ms after Magic: still settling");
|
||||
r.At(0.37); r.B.CheckVitals();
|
||||
Check.Eq(FakeHost.Casts.Count, 1, "310 ms after Magic (370 ms after the request): Heal Self goes, no 1 s floor");
|
||||
Check.True(CastIs("Heal Self"), "and it is Heal Self");
|
||||
Check.True(r.Logged("emergency heal"), "the stance lines say it was an emergency heal");
|
||||
Check.Eq(r.B.UrgentStanceSettles, 1, "counted");
|
||||
|
||||
// A top-off heal (idle, nothing in range): the full settle, as for a buff.
|
||||
var q = new Rig(CombatMode.NonCombat);
|
||||
q.S.EmergencyHealAt = 30; q.S.HealAt = 60; q.S.TopOffHP = 60;
|
||||
q.V.CurrentHealth = 50;
|
||||
q.At(0); q.B.CheckVitals();
|
||||
FakeHost.CombatModeValue = CombatMode.Magic;
|
||||
q.At(0.06); q.B.CheckVitals();
|
||||
q.At(0.5); q.B.CheckVitals();
|
||||
Check.Eq(FakeHost.Casts.Count, 0, "50% under Top Off HP: no cast at 0.5 s");
|
||||
q.At(1.01); q.B.CheckVitals();
|
||||
Check.Eq(FakeHost.Casts.Count, 1, "cast once 1 s has passed since the request");
|
||||
Check.Eq(q.B.UrgentStanceSettles, 0, "not an emergency");
|
||||
}
|
||||
|
||||
// The settle clock started at the first StanceSettled CALL in Magic, so any gate in front of
|
||||
// it (a busy count here) pushed the 300 ms back. It now starts when a heartbeat sees Magic.
|
||||
private static void StanceClockFromObservation()
|
||||
{
|
||||
var r = new Rig(CombatMode.NonCombat);
|
||||
r.S.SpellCastIntervalMs = 0;
|
||||
r.S.EmergencyHealAt = 30; r.S.HealAt = 60; r.S.TopOffHP = 60;
|
||||
r.V.CurrentHealth = 20;
|
||||
r.At(0); r.B.OnHeartbeat();
|
||||
Check.Eq(FakeHost.Casts.Count, 0, "stance requested");
|
||||
FakeHost.CombatModeValue = CombatMode.Magic;
|
||||
FakeHost.UseDoneSeq = 5;
|
||||
r.B.BusyCount = 1; // a live busy count: the vitals step doesn't run
|
||||
r.At(0.1); r.B.OnHeartbeat();
|
||||
Check.Eq(FakeHost.Casts.Count, 0, "held by the busy count, but the heartbeat saw Magic");
|
||||
FakeHost.UseDone(0); // the server finished it: the count is a leftover now
|
||||
r.At(0.45); r.B.OnHeartbeat();
|
||||
Check.Eq(FakeHost.Casts.Count, 1, "Magic seen at 0.1 s + 300 ms: Heal Self at 0.45 s (the old clock started at 0.45 s)");
|
||||
}
|
||||
|
||||
// 13:43:12.67 stance request, 13:43:13.10 the client reads Magic (ready at 13.67), 13:43:13.56 a
|
||||
// healing kit, 13:43:16.02 its UseDone, 13:43:16.77 Heal Self: "first cast 4097 ms after the
|
||||
// stance request". The stance had settled; the kit in flight (KitPending: its result line plus
|
||||
// a 700 ms grace) held the spell. The settle line now says when it was ready and what held it.
|
||||
private static void StanceLateHolderNamed()
|
||||
{
|
||||
var r = new Rig(CombatMode.NonCombat);
|
||||
r.S.SpellCastIntervalMs = 0;
|
||||
r.S.HealAt = 60; r.S.TopOffHP = 60;
|
||||
r.V.CurrentHealth = 50;
|
||||
r.At(0); r.B.OnHeartbeat();
|
||||
FakeHost.CombatModeValue = CombatMode.Magic;
|
||||
r.At(0.4); r.B.OnHeartbeat();
|
||||
Check.Eq(FakeHost.Casts.Count, 0, "settling");
|
||||
r.At(0.9); r.B.MarkKitUsed(); // a healing kit goes out during the wait
|
||||
r.At(1.2); r.B.OnHeartbeat();
|
||||
r.At(2.0); r.B.OnHeartbeat();
|
||||
Check.Eq(FakeHost.Casts.Count, 0, "the kit in flight holds the spell past the stance's ready time");
|
||||
r.Chat("You heal yourself for 10 Health points.");
|
||||
System.Threading.Thread.Sleep(750); // the kit's grace runs on the real clock
|
||||
r.At(3.1); r.B.OnHeartbeat();
|
||||
Check.Eq(FakeHost.Casts.Count, 1, "the kit landed: Heal Self goes");
|
||||
string? line = FakeHost.Logs.LastOrDefault(l => l.Contains("Magic stance settled", StringComparison.Ordinal));
|
||||
Check.NotNull(line, "the settle is logged");
|
||||
Check.True(line != null && line.Contains("first cast 3100 ms after the stance request")
|
||||
&& line.Contains("the stance was ready 1000 ms after the request and the cast then waited 2100 ms for: healing kit in flight"),
|
||||
$"and says the stance was ready at 1 s and the kit held the cast: {line}");
|
||||
}
|
||||
|
||||
private static void UrgentNudgeForHeal()
|
||||
{
|
||||
var r = new Rig();
|
||||
MoveAudit.Reset();
|
||||
r.S.HealAt = 60; r.S.TopOffHP = 60;
|
||||
r.V.CurrentHealth = 50;
|
||||
r.At(0); r.B.CheckVitals();
|
||||
Check.True(CastIs("Heal Self"), "50% health: Heal Self is cast");
|
||||
r.At(0.2); r.Incantation();
|
||||
r.At(2.7); r.B.OnHeartbeat();
|
||||
Check.Eq(FakeHost.AutoRunCalls.Count, 0, "2.5 s after the incantation (a healthy cast takes 2.2-2.5 s): no nudge");
|
||||
r.At(3.1); r.B.OnHeartbeat();
|
||||
Check.True(FakeHost.AutoRunCalls.SequenceEqual(new[] { true, false }), "2.9 s with no result: one nudge, no refusal needed");
|
||||
Check.Eq(r.B.UrgentNudges, 1, "counted as an early nudge");
|
||||
Check.True(r.Logged("it is a heal: nudged at 2.8 s, not 6 s"), "the line says why it was early");
|
||||
r.At(4.0); r.Chat("You're too busy!");
|
||||
r.At(7.0); r.Chat("You're too busy!");
|
||||
r.B.OnHeartbeat();
|
||||
Check.Eq(FakeHost.AutoRunCalls.Count, 2, "still once per held cast");
|
||||
}
|
||||
|
||||
private static void UrgentNudgeForLowHealth()
|
||||
{
|
||||
// 20% health under Emergency Heal At, nothing that can heal: Stamina to Mana is what's held.
|
||||
var r = new Rig();
|
||||
r.S.EmergencyHealAt = 30;
|
||||
r.V.CurrentHealth = 20;
|
||||
r.At(0); r.B.CheckVitals();
|
||||
Check.True(CastIs("Stamina to Mana Self"), "Stamina to Mana is cast");
|
||||
r.At(0.3); r.Incantation();
|
||||
r.At(3.2); r.B.OnHeartbeat();
|
||||
Check.True(FakeHost.AutoRunCalls.SequenceEqual(new[] { true, false }), "held 2.9 s while health is critical: nudged");
|
||||
Check.True(r.Logged("health 20% is under a heal line"), "and says why");
|
||||
|
||||
// Health fine: the 6 s rule (on a refusal) as before.
|
||||
var q = new Rig();
|
||||
q.At(0); q.B.CheckVitals();
|
||||
q.At(0.3); q.Incantation();
|
||||
q.At(3.2); q.B.OnHeartbeat();
|
||||
q.At(5.0); q.B.OnHeartbeat();
|
||||
Check.Eq(FakeHost.AutoRunCalls.Count, 0, "health fine: no early nudge");
|
||||
}
|
||||
|
||||
// ACE refuses a kit or potion while the player is busy, and every kit Drakkon used while a
|
||||
// Heal Self was held open came back 0x1D.
|
||||
private static void HeldCastItemGate()
|
||||
{
|
||||
var r = new Rig();
|
||||
r.At(0); r.B.CheckVitals();
|
||||
string name = r.CastName;
|
||||
r.At(0.3); r.Incantation();
|
||||
r.At(2.0);
|
||||
Check.False(r.B.HeldCastBlocksItemUse(out _), "inside the normal result window: no gate (the vital is still pending)");
|
||||
r.At(3.5);
|
||||
Check.True(r.B.HeldCastBlocksItemUse(out string why), "held 3.2 s, not nudged yet: no kit or potion");
|
||||
Check.True(why.Contains("nudge first"), $"why: {why}");
|
||||
r.At(6.5); r.Chat("You're too busy!");
|
||||
Check.Eq(FakeHost.AutoRunCalls.Count, 2, "the refusal at 6.2 s nudges it");
|
||||
r.At(6.6);
|
||||
Check.False(r.B.HeldCastBlocksItemUse(out _), "after the nudge: one kit or potion try");
|
||||
r.At(7.0);
|
||||
Check.True(r.B.HeldCastBlocksItemUse(out why), "the next try waits");
|
||||
Check.True(why.Contains("next kit/potion try in"), $"why: {why}");
|
||||
r.At(9.7);
|
||||
Check.False(r.B.HeldCastBlocksItemUse(out _), "3 s later: another try");
|
||||
r.At(10.0); r.Chat($"You cast {name} on yourself and lose 35 points of stamina and also gain 47 points of mana");
|
||||
Check.False(r.B.HeldCastBlocksItemUse(out _), "the cast resolved: no gate");
|
||||
Check.Eq(r.B.HeldItemSkips, 2, "two attempts skipped");
|
||||
}
|
||||
|
||||
private static void MoveAuditLines()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
var host = FakeHost.Create();
|
||||
UseAudit.Reset("RynthAi", null);
|
||||
MoveAudit.Reset();
|
||||
long now = 1000;
|
||||
var oldClock = MoveAudit.NowMs;
|
||||
MoveAudit.NowMs = () => now;
|
||||
try
|
||||
{
|
||||
host.SetAutoRunBy("Nav", true);
|
||||
host.SetAutoRunBy("Nav", true); // a repeat 0 ms later: counted
|
||||
now += 100;
|
||||
host.TurnToHeadingBy("Nav", 10f);
|
||||
now += 30; host.TurnToHeadingBy("Nav", 12f);
|
||||
now += 30; host.TurnToHeadingBy("Nav", 14f);
|
||||
now += 30; host.SetAutoRunBy("Meta", false);
|
||||
var lines = FakeHost.Logs.Where(l => l.StartsWith("[Move]", StringComparison.Ordinal)).ToList();
|
||||
Check.Eq(lines.Count, 3, "three lines: autorun, the first turn (carrying the autorun repeat), the meta stop (carrying the turns)");
|
||||
if (lines.Count == 3)
|
||||
{
|
||||
Check.Eq(lines[0], "[Move] RynthAi/Nav SetAutoRun(True)", "plugin/subsystem and the call");
|
||||
Check.True(lines[1].StartsWith("[Move] RynthAi/Nav TurnToHeading(10.0) (+1 more SetAutoRun(True)", StringComparison.Ordinal), $"the repeat is counted: {lines[1]}");
|
||||
Check.True(lines[2].StartsWith("[Move] RynthAi/Meta SetAutoRun(False) (+2 more TurnToHeading, last 14.0", StringComparison.Ordinal), $"turns collapse whatever the angle: {lines[2]}");
|
||||
}
|
||||
Check.Eq(FakeHost.AutoRunCalls.Count, 3, "every call still reaches the engine");
|
||||
Check.Eq(FakeHost.Turns, 3, "every turn still reaches the engine");
|
||||
|
||||
now += 2000; host.SetAutoRunBy("Meta", false);
|
||||
Check.Eq(FakeHost.Logs.Count(l => l.StartsWith("[Move]", StringComparison.Ordinal)), 4, "the same call after the 1 s window gets its own line");
|
||||
}
|
||||
finally { MoveAudit.NowMs = oldClock; }
|
||||
}
|
||||
}
|
||||
217
Tools/RynthCore.RynthAiHostTests/Tests/DungeonMapBakeTests.cs
Normal file
217
Tools/RynthCore.RynthAiHostTests/Tests/DungeonMapBakeTests.cs
Normal file
|
|
@ -0,0 +1,217 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.RynthAi.Maps;
|
||||
using RynthCore.Plugin.RynthAi.Raycasting;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// Dungeon floor-plan bake (2026-10-05): RynthAi writes <landblock>_<layer>.bin floor plans for
|
||||
// the StatusAgent's /map (DrakRemote's dungeon map). The bake was the disk half of the old
|
||||
// DungeonMapTexture, deleted with the D3D9 textures on 2026-09-30 (f78392b); this is it back,
|
||||
// disk only. The plans already in C:\Games\RynthSuite\RynthAi\Maps are READ here, never
|
||||
// written: every bake in these tests goes to the scratch folder.
|
||||
internal static class DungeonMapBakeTests
|
||||
{
|
||||
private const string AcDir = @"C:\Turbine\Asheron's Call";
|
||||
private const string LiveMaps = @"C:\Games\RynthSuite\RynthAi\Maps";
|
||||
private const uint Matron = 0x6346; // Matron Hive South (PatrolProof / LosProof fixtures)
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("map bake: file format is the StatusAgent's (header, ARGB pixels, north row first)", Format);
|
||||
r.Add("map bake: same bytes are not rewritten, changed bytes are, no temp files left", NoChurn);
|
||||
r.Add("map bake: file names use the short landblock id", Names);
|
||||
r.Add("map bake: 0x6346 from the real dats matches the plan already on disk (if dats and plan are here)", MatchesExisting6346);
|
||||
r.Add("map bake: the plans already on disk keep their names, most byte for byte (if the dats are here)", MatchesAllExisting);
|
||||
}
|
||||
|
||||
private static string Dir(string name)
|
||||
{
|
||||
string d = Path.Combine(Program.TempRoot, "mapbake", name);
|
||||
Directory.CreateDirectory(d);
|
||||
return d;
|
||||
}
|
||||
|
||||
private static void Format()
|
||||
{
|
||||
// A 3x2 block of flat cells at gx 10..12, gy 4..5 plus one ramp cell north of it.
|
||||
var cells = new Dictionary<(int, int), DungeonMapUi.CellType>();
|
||||
for (int gx = 10; gx <= 12; gx++)
|
||||
for (int gy = 4; gy <= 5; gy++)
|
||||
cells[(gx, gy)] = DungeonMapUi.CellType.Flat;
|
||||
cells[(11, 6)] = DungeonMapUi.CellType.SlopeUp;
|
||||
|
||||
byte[]? bytes = DungeonMapBake.BuildFile(cells);
|
||||
Check.NotNull(bytes, "built");
|
||||
if (bytes is null) return;
|
||||
int w = 3, h = 3;
|
||||
Check.Eq(bytes.Length, 20 + w * h * 4, "length = header + w*h*4");
|
||||
Check.Eq(BitConverter.ToUInt32(bytes, 0), 0x524D5458u, "magic XTMR");
|
||||
Check.Eq(BitConverter.ToInt32(bytes, 4), 10, "xMin");
|
||||
Check.Eq(BitConverter.ToInt32(bytes, 8), 4, "yMin");
|
||||
Check.Eq(BitConverter.ToInt32(bytes, 12), w, "w");
|
||||
Check.Eq(BitConverter.ToInt32(bytes, 16), h, "h");
|
||||
|
||||
uint Px(int col, int row) => BitConverter.ToUInt32(bytes, 20 + (row * w + col) * 4);
|
||||
// Row 0 is the northernmost row (gy 6): only the ramp cell at gx 11, an edge cell.
|
||||
Check.Eq(Px(0, 0), 0u, "empty cell is transparent");
|
||||
Check.Eq(Px(1, 0) >> 24, 255u, "edge cell is opaque");
|
||||
Check.Eq((Px(1, 0) >> 16) & 0xFF, 255u, "ramp-up edge is red");
|
||||
// Row 1 (gy 5): (11,5) has neighbours on all four sides, so it is the translucent fill.
|
||||
Check.Eq(Px(1, 1) >> 24, (uint)(0.40f * 255f), "interior cell is the translucent fill");
|
||||
Check.Eq(Px(0, 1) >> 24, 255u, "border cell is an edge");
|
||||
// Row 2 (gy 4): southern edge.
|
||||
Check.Eq(Px(2, 2) >> 24, 255u, "south-east corner is an edge");
|
||||
}
|
||||
|
||||
private static void NoChurn()
|
||||
{
|
||||
string dir = Dir("churn");
|
||||
var cells = new Dictionary<(int, int), DungeonMapUi.CellType> { [(0, 0)] = DungeonMapUi.CellType.Flat, [(1, 0)] = DungeonMapUi.CellType.Flat };
|
||||
byte[] a = DungeonMapBake.BuildFile(cells)!;
|
||||
string path = Path.Combine(dir, "00001234_2.bin");
|
||||
|
||||
Check.Eq(DungeonMapBake.SaveToDisk(dir, 0x1234, 2, a), DungeonMapBake.SaveResult.Written, "first save writes");
|
||||
Check.True(File.ReadAllBytes(path).AsSpan().SequenceEqual(a), "file holds the bytes");
|
||||
var past = new DateTime(2026, 5, 1, 12, 0, 0, DateTimeKind.Utc);
|
||||
File.SetLastWriteTimeUtc(path, past);
|
||||
|
||||
Check.Eq(DungeonMapBake.SaveToDisk(dir, 0x1234, 2, a), DungeonMapBake.SaveResult.Unchanged, "same bytes: unchanged");
|
||||
Check.Eq(File.GetLastWriteTimeUtc(path), past, "same bytes: file not touched (mtime kept, so the agent's ETag holds)");
|
||||
|
||||
cells[(2, 0)] = DungeonMapUi.CellType.SlopeDown;
|
||||
byte[] b = DungeonMapBake.BuildFile(cells)!;
|
||||
Check.Eq(DungeonMapBake.SaveToDisk(dir, 0x1234, 2, b), DungeonMapBake.SaveResult.Written, "changed bytes: written");
|
||||
Check.True(File.ReadAllBytes(path).AsSpan().SequenceEqual(b), "file holds the new bytes");
|
||||
Check.Eq(Directory.GetFiles(dir).Length, 1, "no temp files left: " + string.Join(", ", Directory.GetFiles(dir).Select(Path.GetFileName)));
|
||||
|
||||
// A reader holding the file open the way the agent does (ReadWrite share, no Delete)
|
||||
// makes the replace fail; the save must not throw or leave a temp file.
|
||||
cells[(3, 0)] = DungeonMapUi.CellType.Flat;
|
||||
byte[] c = DungeonMapBake.BuildFile(cells)!;
|
||||
DungeonMapBake.SaveResult held;
|
||||
using (new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
|
||||
held = DungeonMapBake.SaveToDisk(dir, 0x1234, 2, c);
|
||||
Console.WriteLine($" save while the agent holds the file open: {held}");
|
||||
Check.Eq(Directory.GetFiles(dir).Length, 1, "no temp files left after a held file");
|
||||
Check.Eq(DungeonMapBake.SaveToDisk(dir, 0x1234, 2, c), DungeonMapBake.SaveResult.Written, "written once released");
|
||||
}
|
||||
|
||||
private static void Names()
|
||||
{
|
||||
Check.Eq(DungeonMapBake.FileName(0x6346, 1), "00006346_1.bin", "short id");
|
||||
Check.Eq(DungeonMapBake.FileName(0x63460000, 1), "00006346_1.bin", "long id is shortened");
|
||||
Check.Eq(DungeonMapBake.FileName(0x002B, 10), "0000002B_10.bin", "two-digit layer");
|
||||
Check.Eq(DungeonMapBake.ShortLandblock(0x63460000), 0x6346u, "ShortLandblock");
|
||||
}
|
||||
|
||||
private static GeometryLoader? _geo;
|
||||
private static bool _geoTried;
|
||||
|
||||
private static DungeonLOS? Los()
|
||||
{
|
||||
if (!_geoTried)
|
||||
{
|
||||
_geoTried = true;
|
||||
if (Directory.Exists(AcDir))
|
||||
{
|
||||
var g = new GeometryLoader();
|
||||
if (g.Initialize(AcDir)) _geo = g;
|
||||
else Console.WriteLine(" geometry loader failed: " + g.StatusMessage);
|
||||
}
|
||||
}
|
||||
return _geo?.DungeonLOS;
|
||||
}
|
||||
|
||||
/// <summary>Bake one landblock into a scratch folder and compare each layer with the live plan.</summary>
|
||||
private static (int Same, int Differ, int OnlyNew, int OnlyLive, List<string> Notes) Compare(DungeonLOS los, uint lb, string outDir)
|
||||
{
|
||||
var notes = new List<string>();
|
||||
var (zLayers, cells) = DungeonMapUi.BuildFloorCells(los, lb);
|
||||
DungeonMapBake.BakeLayers(outDir, lb, zLayers, cells);
|
||||
string prefix = $"{lb:X8}_";
|
||||
var baked = Directory.GetFiles(outDir, prefix + "*.bin").Select(Path.GetFileName).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
var live = Directory.Exists(LiveMaps)
|
||||
? Directory.GetFiles(LiveMaps, prefix + "*.bin").Select(Path.GetFileName).ToHashSet(StringComparer.OrdinalIgnoreCase)
|
||||
: new HashSet<string?>();
|
||||
int same = 0, differ = 0, onlyNew = 0, onlyLive = 0;
|
||||
foreach (string? name in baked.Union(live).OrderBy(n => n))
|
||||
{
|
||||
if (name is null) continue;
|
||||
bool inNew = baked.Contains(name), inLive = live.Contains(name);
|
||||
if (inNew && !inLive) { onlyNew++; notes.Add($"{name}: new (no live plan)"); continue; }
|
||||
if (!inNew) { onlyLive++; notes.Add($"{name}: live plan has no new counterpart"); continue; }
|
||||
byte[] n = File.ReadAllBytes(Path.Combine(outDir, name));
|
||||
byte[] l = File.ReadAllBytes(Path.Combine(LiveMaps, name));
|
||||
if (n.AsSpan().SequenceEqual(l)) { same++; continue; }
|
||||
differ++;
|
||||
notes.Add($"{name}: differs - new {Header(n)} vs live {Header(l)}, {DiffPixels(n, l)}");
|
||||
}
|
||||
return (same, differ, onlyNew, onlyLive, notes);
|
||||
}
|
||||
|
||||
private static string Header(byte[] b) => b.Length < 20 ? $"({b.Length} bytes)"
|
||||
: $"x{BitConverter.ToInt32(b, 4)} y{BitConverter.ToInt32(b, 8)} {BitConverter.ToInt32(b, 12)}x{BitConverter.ToInt32(b, 16)}";
|
||||
|
||||
private static string DiffPixels(byte[] a, byte[] b)
|
||||
{
|
||||
if (a.Length != b.Length || a.Length < 20 || a.AsSpan(4, 16).SequenceEqual(b.AsSpan(4, 16)) == false) return "different bounds";
|
||||
int diff = 0, total = (a.Length - 20) / 4;
|
||||
for (int i = 20; i < a.Length; i += 4)
|
||||
if (BitConverter.ToUInt32(a, i) != BitConverter.ToUInt32(b, i)) diff++;
|
||||
return $"{diff} of {total} pixels differ";
|
||||
}
|
||||
|
||||
private static void MatchesExisting6346()
|
||||
{
|
||||
var los = Los();
|
||||
if (los is null) { Console.WriteLine(" skipped: no dats at " + AcDir); return; }
|
||||
if (!File.Exists(Path.Combine(LiveMaps, DungeonMapBake.FileName(Matron, 0))))
|
||||
{ Console.WriteLine(" skipped: no live plan for 0x6346"); return; }
|
||||
var (same, differ, onlyNew, onlyLive, notes) = Compare(los, Matron, Dir("6346"));
|
||||
Console.WriteLine($" 0x6346: {same} identical, {differ} differ, {onlyNew} new only, {onlyLive} live only");
|
||||
foreach (string n in notes) Console.WriteLine(" " + n);
|
||||
Check.True(same > 0, "some layers baked");
|
||||
Check.Eq(differ + onlyNew + onlyLive, 0, "every 0x6346 layer is byte-identical to the live plan");
|
||||
}
|
||||
|
||||
private static void MatchesAllExisting()
|
||||
{
|
||||
var los = Los();
|
||||
if (los is null) { Console.WriteLine(" skipped: no dats at " + AcDir); return; }
|
||||
if (!Directory.Exists(LiveMaps)) { Console.WriteLine(" skipped: no live maps folder"); return; }
|
||||
var rx = new Regex(@"^([0-9A-Fa-f]{8})_(\d+)\.bin$");
|
||||
var lbs = Directory.GetFiles(LiveMaps, "*.bin")
|
||||
.Select(f => rx.Match(Path.GetFileName(f)))
|
||||
.Where(m => m.Success)
|
||||
.Select(m => Convert.ToUInt32(m.Groups[1].Value, 16))
|
||||
.Distinct().OrderBy(x => x).ToList();
|
||||
string outDir = Dir("all");
|
||||
int same = 0, differ = 0, onlyNew = 0, onlyLive = 0;
|
||||
foreach (uint lb in lbs)
|
||||
{
|
||||
var c = Compare(los, lb, outDir);
|
||||
same += c.Same; differ += c.Differ; onlyNew += c.OnlyNew; onlyLive += c.OnlyLive;
|
||||
if (c.Notes.Count > 0)
|
||||
{
|
||||
Console.WriteLine($" 0x{lb:X4}: {c.Same} identical, {c.Differ} differ, {c.OnlyNew} new only, {c.OnlyLive} live only");
|
||||
foreach (string n in c.Notes) Console.WriteLine(" " + n);
|
||||
}
|
||||
}
|
||||
Console.WriteLine($" {lbs.Count} landblocks: {same} plans identical, {differ} differ, {onlyNew} new only, {onlyLive} live only");
|
||||
// 2026-10-05: 59 of the 81 plans baked May-June are identical; 22 differ by a few
|
||||
// pixels (or a few cells of bounds) because the floor rasteriser has changed since
|
||||
// they were baked. Those 22 are refreshed once, on the next visit, to what the radar
|
||||
// draws today; the identical ones are left alone. What must hold: the layer numbering
|
||||
// is unchanged (every live plan has a counterpart under the same name), the header
|
||||
// format is the same, and most plans come out identical.
|
||||
Check.Eq(onlyLive, 0, "every live plan has a counterpart under the same file name (layer numbering unchanged)");
|
||||
Check.Eq(onlyNew, 0, "no extra layers compared with the live plans");
|
||||
Check.True(same > differ, $"most live plans are reproduced byte for byte ({same} identical, {differ} differ)");
|
||||
}
|
||||
}
|
||||
121
Tools/RynthCore.RynthAiHostTests/Tests/GiveTests.cs
Normal file
121
Tools/RynthCore.RynthAiHostTests/Tests/GiveTests.cs
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
using System;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.PluginCore;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// /ub give and /mt give (Tom, 2026-10-05): "/ub give ... should give every item that matches the
|
||||
// name in the inventory. /mt give should give the first one it finds." Both use AC's give action
|
||||
// (an NPC ignores MoveItemExternal) and never hand over worn or wielded gear.
|
||||
internal static class GiveTests
|
||||
{
|
||||
private const uint Player = 0x50000F01;
|
||||
private const uint Npc = 0x80281000;
|
||||
private const uint Mote1 = 0x80281101, Mote2 = 0x80281102, Mote3 = 0x80281103, WornMote = 0x80281104, Other = 0x80281105;
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("give: /ub give hands over every matching carried item, never worn gear", UbGivesAll);
|
||||
r.Add("give: /ub give with a count hands over that many", UbGiveCount);
|
||||
r.Add("give: /mt give hands over only the first match", MtGivesFirst);
|
||||
r.Add("give: /ub givep matches part of the name", UbGivePartial);
|
||||
}
|
||||
|
||||
private sealed class World
|
||||
{
|
||||
public readonly RynthAiPlugin P = new();
|
||||
public readonly LegacyUiSettings S = new() { GiveQueueIntervalMs = 0 };
|
||||
public readonly WorldObjectCache Cache;
|
||||
|
||||
public World()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.SalvageCalls = true; // MoveItemExternal + GetObjectWielderInfo (Wielded)
|
||||
FakeHost.GiveCalls = true;
|
||||
FakeHost.Names[Player] = "Giver";
|
||||
FakeHost.PlayerIdValue = Player;
|
||||
FakeHost.Names[Npc] = "Town Crier";
|
||||
FakeHost.Positions[Npc] = (0x1048002Au, 101f, 100f, 0f);
|
||||
FakeHost.ItemTypes[Npc] = 0x10; // a creature (an NPC)
|
||||
FakeHost.NotAttackable.Add(Npc);
|
||||
FakeHost.Positions[Player] = (0x1048002Au, 100f, 100f, 0f);
|
||||
FakeHost.PlayerPose = (0x1048002Au, 100f, 100f, 0f);
|
||||
foreach (var (id, name) in new[] { (Mote1, "Mana Mote"), (Mote2, "Mana Mote"), (Mote3, "Mana Mote"), (WornMote, "Mana Mote"), (Other, "Lesser Mana Mote") })
|
||||
{
|
||||
FakeHost.Names[id] = name;
|
||||
FakeHost.Containers[id] = Player;
|
||||
FakeHost.ItemTypes[id] = 0x80; // misc
|
||||
}
|
||||
FakeHost.Wielded[WornMote] = 0x8000; // worn: never given
|
||||
var host = FakeHost.Create(playerId: Player);
|
||||
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
|
||||
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
|
||||
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S);
|
||||
Set("_dashboard", dash);
|
||||
Cache = new WorldObjectCache(host);
|
||||
Cache.SetPlayerId(Player);
|
||||
Set("_objectCache", Cache);
|
||||
Set("_playerId", Player);
|
||||
Set("_initialized", true);
|
||||
Set("_loginComplete", true);
|
||||
foreach (uint id in new[] { Npc, Mote1, Mote2, Mote3, WornMote, Other }) Cache.OnCreateObject(id);
|
||||
Cache.Tick();
|
||||
}
|
||||
|
||||
public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v);
|
||||
public object? Call(string m, params object?[] a) => typeof(RynthAiPlugin).GetMethod(m, Any)!.Invoke(P, a);
|
||||
|
||||
/// <summary>Runs the chat command, then drains the give queue.</summary>
|
||||
public void Run(string command)
|
||||
{
|
||||
if (command.StartsWith("/ub", StringComparison.Ordinal)) Call("HandleUbCommand", command);
|
||||
else Call("HandleMtCommand", command);
|
||||
for (int i = 0; i < 20; i++) Call("DrainGiveQueue");
|
||||
}
|
||||
|
||||
public uint[] GivenItems => FakeHost.Gives.Select(g => g.Item).ToArray();
|
||||
}
|
||||
|
||||
private static void UbGivesAll()
|
||||
{
|
||||
var w = new World();
|
||||
w.Run("/ub give Mana Mote to Town Crier");
|
||||
Check.Eq(FakeHost.Gives.Count, 3, "all three carried Mana Motes");
|
||||
Check.True(new[] { Mote1, Mote2, Mote3 }.All(id => w.GivenItems.Contains(id)), "each of them");
|
||||
Check.False(w.GivenItems.Contains(WornMote), "the worn one stays on");
|
||||
Check.False(w.GivenItems.Contains(Other), "an exact name doesn't take 'Lesser Mana Mote'");
|
||||
Check.True(FakeHost.Gives.All(g => g.Target == Npc), "all to the NPC, with AC's give action");
|
||||
Check.Eq(FakeHost.ExternalMoves.Count, 0, "never MoveItemExternal (an NPC ignores it)");
|
||||
}
|
||||
|
||||
private static void UbGiveCount()
|
||||
{
|
||||
var w = new World();
|
||||
w.Run("/ub give 2 Mana Mote to Town Crier");
|
||||
Check.Eq(FakeHost.Gives.Count, 2, "a count gives that many");
|
||||
}
|
||||
|
||||
private static void MtGivesFirst()
|
||||
{
|
||||
var w = new World();
|
||||
w.Run("/mt give Mana Mote to Town Crier");
|
||||
Check.Eq(FakeHost.Gives.Count, 1, "/mt give: one item");
|
||||
Check.False(w.GivenItems.Contains(WornMote), "and never the worn one");
|
||||
}
|
||||
|
||||
private static void UbGivePartial()
|
||||
{
|
||||
var w = new World();
|
||||
w.Run("/ub givep Mana Mote to Town");
|
||||
Check.Eq(FakeHost.Gives.Count, 4, "partial: the three Mana Motes and the Lesser Mana Mote");
|
||||
Check.False(w.GivenItems.Contains(WornMote), "still not the worn one");
|
||||
}
|
||||
}
|
||||
331
Tools/RynthCore.RynthAiHostTests/Tests/HealLatencyTests.cs
Normal file
331
Tools/RynthCore.RynthAiHostTests/Tests/HealLatencyTests.cs
Normal file
|
|
@ -0,0 +1,331 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// Heal latency (2026-10-05): a mage's heals "sometimes fine, sometimes several seconds late".
|
||||
// - A war cast's busy count is a leftover once the server's UseDone arrives (AC lowers its own
|
||||
// count inline, unseen), and only combat cleared it. With health under a line the arbiter
|
||||
// hands the tick to vitals, combat stops running, and the heal waited for the 5 s force-clear.
|
||||
// - A healing kit the server refused (too busy, in the air) never gets a result line, so every
|
||||
// vital waited the kit's 8 s result timeout.
|
||||
// - [HealLatency] logs each episode's delay and what held it.
|
||||
// - The activity display says Healing / Restoring mana / Restoring stamina, not "Buffing".
|
||||
internal static class HealLatencyTests
|
||||
{
|
||||
private const uint Player = 0x50000B01;
|
||||
private const uint STypeLife = 33;
|
||||
private const uint TooBusy = 0x1D;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("heal latency: a heal goes ahead of a leftover busy count (a war cast the server finished)", HealBeatsLeftoverBusy);
|
||||
r.Add("heal latency: a live busy count still holds the heal; a leftover doesn't free buffs or mana", LiveBusyStillHolds);
|
||||
r.Add("heal latency: a refused kit ends the kit wait (UseDone error or 'too busy'), Heal Self goes next", KitRefusalEndsWait);
|
||||
r.Add("heal latency: Heal Self refused for mana rests 2 s, not the 15 s a buff rests", LowManaHealRest);
|
||||
r.Add("heal latency: [HealLatency] logs delay, line and blockers per episode, and a summary", TrackerLines);
|
||||
r.Add("heal latency: the heartbeat files a held heal under its blocker", HeartbeatLogsEpisode);
|
||||
r.Add("activity label: the Buffing slot shows Healing / Restoring mana / Buffing; control string unchanged", ActivityLabels);
|
||||
r.Add("heal latency: an emergency heal goes out during the login buff refresh; buffs still wait for it", EmergencyBeatsLoginRefresh);
|
||||
}
|
||||
|
||||
private sealed class Rig
|
||||
{
|
||||
public DateTime T0 = new(2026, 10, 5, 21, 0, 0);
|
||||
public DateTime NowAt;
|
||||
public readonly BuffManager B;
|
||||
public readonly LegacyUiSettings S;
|
||||
public readonly PlayerVitalsCache V;
|
||||
public readonly List<string> StaleResets = new();
|
||||
|
||||
public Rig(int healthPct = 40, int manaPct = 100, bool lastUseDone = true, bool liveBuffsReady = true)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.WeaponCalls = true;
|
||||
FakeHost.ServerGates = true;
|
||||
FakeHost.LastUseDoneCalls = lastUseDone;
|
||||
FakeHost.CombatModeValue = CombatMode.Magic;
|
||||
foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id);
|
||||
FakeHost.Skills[(Player, STypeLife)] = (400, 2);
|
||||
var host = FakeHost.Create();
|
||||
// No combat manager here, so the idle line applies: Heal At = Top Off HP = 60.
|
||||
S = new LegacyUiSettings
|
||||
{
|
||||
IsMacroRunning = true, HealAt = 60, TopOffHP = 60, EmergencyHealAt = 0, StaminaToHealthAt = 0,
|
||||
GetManaAt = 0, TopOffMana = 0, RestamAt = 0, TopOffStam = 0, UsePotions = false,
|
||||
EnableBuffing = false,
|
||||
};
|
||||
var skills = new CharacterSkills(host);
|
||||
skills.SetPlayerId(Player);
|
||||
var sm = new SpellManager(host, S);
|
||||
sm.InitializeNatively();
|
||||
sm.SetCharacterSkills(skills);
|
||||
V = new PlayerVitalsCache
|
||||
{
|
||||
MaxHealth = 100, CurrentHealth = (uint)healthPct, MaxStamina = 100, CurrentStamina = 100,
|
||||
MaxMana = 100, CurrentMana = (uint)manaPct,
|
||||
};
|
||||
B = new BuffManager(host, S, sm, V);
|
||||
B.SetCharacterSkills(skills);
|
||||
B.SetStaleBusyCallback(why => StaleResets.Add(why));
|
||||
NowAt = T0;
|
||||
B.Clock = () => NowAt;
|
||||
if (liveBuffsReady) B.MarkLiveBuffsReadyForTests();
|
||||
}
|
||||
|
||||
public void At(double seconds) => NowAt = T0.AddSeconds(seconds);
|
||||
public bool Logged(string part) => FakeHost.Logs.Any(l => l.Contains(part, StringComparison.Ordinal));
|
||||
public string? Log(string part) => FakeHost.Logs.LastOrDefault(l => l.Contains(part, StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
// Heal Self at any tier (skill 400 casts a high tier with its own name): same category as Heal Self I.
|
||||
private static int HealSelfCasts()
|
||||
{
|
||||
int cat = SpellTable.Named("Heal Self I").First().Category;
|
||||
return FakeHost.Casts.Count(c => SpellTable.ById(c.SpellId)?.Category == cat);
|
||||
}
|
||||
|
||||
// The mage's case: a war cast went out (busy 0 -> 1 at UseDone #5), the server finished it
|
||||
// (UseDone #6, AC lowered its own count unseen), and health dropped under Heal At. Before the
|
||||
// fix the heal waited at BusyCount > 0 until CheckBusyTimeout's 5 s force-clear.
|
||||
private static void HealBeatsLeftoverBusy()
|
||||
{
|
||||
var r = new Rig(healthPct: 40);
|
||||
FakeHost.UseDoneSeq = 5;
|
||||
r.B.BusyCount = 1; // the war cast's increment
|
||||
FakeHost.UseDone(0); // the server finished it; nothing decrements the plugin's count
|
||||
r.At(0.1);
|
||||
r.B.OnHeartbeat();
|
||||
Check.Eq(HealSelfCasts(), 1, "Heal Self goes out on the first heartbeat, not after the 5 s force-clear");
|
||||
Check.Eq(r.B.StaleBusyClears, 1, "the leftover was cleared once");
|
||||
Check.Eq(r.B.BusyCount, 0, "and the shared mirror is 0");
|
||||
Check.Eq(r.StaleResets.Count, 1, "through the same callback combat uses");
|
||||
Check.True(r.StaleResets[0].StartsWith("vitals:", StringComparison.Ordinal), "the reason says it was the heal");
|
||||
}
|
||||
|
||||
private static void LiveBusyStillHolds()
|
||||
{
|
||||
// A count with no UseDone since it rose is real (a swing, a cast still on the server).
|
||||
var r = new Rig(healthPct: 40);
|
||||
FakeHost.UseDoneSeq = 5;
|
||||
r.B.BusyCount = 1;
|
||||
r.B.OnHeartbeat();
|
||||
Check.Eq(FakeHost.Casts.Count, 0, "no UseDone since the count rose: the heal waits");
|
||||
Check.Eq(r.B.StaleBusyClears, 0, "nothing cleared");
|
||||
|
||||
// A gesture still animating: real too, even after a UseDone.
|
||||
FakeHost.UseDone(0);
|
||||
FakeHost.CastBusy = 1;
|
||||
r.B.OnHeartbeat();
|
||||
Check.Eq(FakeHost.Casts.Count, 0, "a cast gesture animating: the heal waits");
|
||||
FakeHost.CastBusy = 0;
|
||||
r.B.OnHeartbeat();
|
||||
Check.Eq(HealSelfCasts(), 1, "gesture done, UseDone seen: the heal goes");
|
||||
|
||||
// Health fine, mana low: the leftover rule is for heals only, so Stamina to Mana still waits.
|
||||
var m = new Rig(healthPct: 100, manaPct: 10);
|
||||
m.S.GetManaAt = 50; m.S.TopOffMana = 50;
|
||||
FakeHost.UseDoneSeq = 5;
|
||||
m.B.BusyCount = 1;
|
||||
FakeHost.UseDone(0);
|
||||
m.B.OnHeartbeat();
|
||||
Check.Eq(FakeHost.Casts.Count, 0, "no heal wanted: a leftover count still holds mana and buffs");
|
||||
Check.Eq(m.B.BusyCount, 1, "and is left for combat / the watchdog");
|
||||
}
|
||||
|
||||
// ACE Healer.cs answers a kit used while busy with UseDone(YoureTooBusy) and no chat result.
|
||||
private static void KitRefusalEndsWait()
|
||||
{
|
||||
// UseDone error.
|
||||
var r = new Rig(healthPct: 40);
|
||||
FakeHost.UseDoneSeq = 10;
|
||||
r.B.MarkKitUsed();
|
||||
Check.True(r.B.KitPending(), "kit just used: waiting for its result");
|
||||
FakeHost.UseDone(TooBusy);
|
||||
Check.False(r.B.KitPending(), "a UseDone error after the kit: refused, no 8 s wait");
|
||||
Check.Eq(r.B.KitRefusals, 1, "counted");
|
||||
Check.True(r.Logged("kit was refused") && r.Logged("UseDone error 0x1D"), "and logged with the error");
|
||||
Check.True(r.B.CheckVitals(), "vitals carry on at once");
|
||||
Check.Eq(HealSelfCasts(), 1, "Heal Self is cast (the kit waits a second after a refusal)");
|
||||
|
||||
// UseDone(0) after the kit is not a refusal: the kit is still healing.
|
||||
var ok = new Rig(healthPct: 40);
|
||||
FakeHost.UseDoneSeq = 10;
|
||||
ok.B.MarkKitUsed();
|
||||
FakeHost.UseDone(0);
|
||||
Check.True(ok.B.KitPending(), "UseDone(0): no refusal, still waiting for the result line");
|
||||
Check.Eq(ok.B.KitRefusals, 0, "not counted");
|
||||
|
||||
// No GetLastUseDone on this engine: the "too busy" line ends it.
|
||||
var c = new Rig(healthPct: 40, lastUseDone: false);
|
||||
c.B.MarkKitUsed();
|
||||
c.B.OnChatWindowText("You're too busy!", 26);
|
||||
Check.False(c.B.KitPending(), "'You're too busy!' right after the kit: refused");
|
||||
Check.Eq(c.B.KitRefusals, 1, "counted");
|
||||
|
||||
// A result line first: a later "too busy" (something else refused) doesn't cut the grace.
|
||||
var g = new Rig(healthPct: 40, lastUseDone: false);
|
||||
g.B.MarkKitUsed();
|
||||
g.B.OnChatWindowText("You heal yourself for 52 Health points.", 0);
|
||||
g.B.OnChatWindowText("You're too busy!", 26);
|
||||
Check.True(g.B.KitPending(), "result seen: the grace for the vitals still runs");
|
||||
Check.Eq(g.B.KitRefusals, 0, "no refusal counted");
|
||||
}
|
||||
|
||||
// A mage out of mana mid-fight: "You don't have enough Mana" parked Heal Self for 15 s, so after
|
||||
// Stamina to Mana refilled it 2-3 s later the mage still couldn't heal for 12 s more.
|
||||
private static void LowManaHealRest()
|
||||
{
|
||||
var r = new Rig(healthPct: 40, manaPct: 2);
|
||||
r.S.GetManaAt = 50; r.S.TopOffMana = 50;
|
||||
Check.True(r.B.CheckVitals(), "40% health: Heal Self is cast");
|
||||
Check.Eq(HealSelfCasts(), 1, "one Heal Self");
|
||||
r.B.OnChatWindowText("You don't have enough Mana to cast this spell.", 0);
|
||||
Check.True(r.Logged("not enough mana; resting the family 2s"), "Heal Self rests 2 s");
|
||||
Check.Eq(r.B.PendingSpellId, 0, "pending cleared");
|
||||
Check.True(r.B.CheckVitals(), "next check: something is done");
|
||||
Check.Eq(HealSelfCasts(), 1, "not Heal Self inside the rest...");
|
||||
Check.Eq(FakeHost.Casts.Count, 2, "...but Stamina to Mana, so the mana comes back");
|
||||
Check.Eq(r.B.BuffingLabel, "Restoring mana", "and the slot reads Restoring mana");
|
||||
r.B.OnChatWindowText("You don't have enough Mana to cast this spell.", 0);
|
||||
Check.True(r.Logged("not enough mana; resting the family 15s"), "a non-heal still rests 15 s");
|
||||
System.Threading.Thread.Sleep(2100);
|
||||
r.V.CurrentMana = 60;
|
||||
Check.True(r.B.CheckVitals(), "2 s later, mana back");
|
||||
Check.Eq(HealSelfCasts(), 2, "Heal Self is cast again");
|
||||
}
|
||||
|
||||
private static void TrackerLines()
|
||||
{
|
||||
var logs = new List<string>();
|
||||
var t = new HealLatencyTracker(logs.Add);
|
||||
DateTime t0 = new(2026, 10, 5, 21, 0, 0);
|
||||
DateTime At(double s) => t0.AddSeconds(s);
|
||||
|
||||
t.Observe(At(0), 41, "Heal At", 60, inCombat: true, healInFlight: false);
|
||||
for (int i = 1; i <= 30; i++)
|
||||
t.EndTick(At(i * 0.1), i <= 28 ? "busy count" : "cast gate (a gesture is animating)", "busy 1", "Buffing");
|
||||
t.HealSent(At(3.1), "Heal Self");
|
||||
string line = logs.Last();
|
||||
Check.True(line.StartsWith("[HealLatency] 3100 ms: health 41% under Heal At 60% (in combat) -> Heal Self", StringComparison.Ordinal), $"episode line: {line}");
|
||||
Check.True(line.Contains("busy count 2800 ms") && line.Contains("cast gate (a gesture is animating) 200 ms"), "blockers with their time, biggest first");
|
||||
Check.Eq(t.Episodes, 1, "one episode");
|
||||
|
||||
// Still under the line: the next episode opens only once the heal has resolved.
|
||||
t.Observe(At(3.2), 45, "Heal At", 60, true, healInFlight: true);
|
||||
Check.False(t.IsOpen, "heal in flight: no new episode yet");
|
||||
t.Observe(At(5.5), 45, "Heal At", 60, true, healInFlight: false);
|
||||
Check.True(t.IsOpen, "resolved and still under: a follow-up episode");
|
||||
t.EndTick(At(5.6), "cast interval", "", "Combat");
|
||||
t.HealSent(At(5.9), "Heal Self");
|
||||
Check.True(logs.Last().Contains("400 ms") && logs.Last().Contains("(follow-up)") && logs.Last().Contains("arbiter gave the tick to Combat 100 ms"),
|
||||
$"follow-up measured from when it became possible: {logs.Last()}");
|
||||
|
||||
// Over the line with no heal: logged when it lasted a second or more.
|
||||
t.Observe(At(6), 80, "", 0, true, false);
|
||||
t.Observe(At(7), 55, "Top Off HP", 95, false, false);
|
||||
t.Observe(At(7.5), 96, "", 0, false, false);
|
||||
Check.False(logs.Last().Contains("no heal"), "a half-second dip isn't logged");
|
||||
t.Observe(At(8), 55, "Top Off HP", 95, false, false);
|
||||
t.EndTick(At(8.5), "nothing could heal", "kit: no healing kit", "Navigating");
|
||||
t.Observe(At(9.5), 96, "", 0, false, false);
|
||||
Check.True(logs.Last().StartsWith("[HealLatency] no heal in 1500 ms", StringComparison.Ordinal) && logs.Last().Contains("nothing could heal"),
|
||||
$"a 1.5 s episode with no heal is: {logs.Last()}");
|
||||
|
||||
// Summary every 10 heals.
|
||||
for (int i = 0; i < 8; i++)
|
||||
{
|
||||
double s0 = 20 + i * 10;
|
||||
t.Observe(At(s0), 50, "Heal At", 60, true, false);
|
||||
t.EndTick(At(s0 + 0.5), "busy count", "", "Buffing");
|
||||
t.HealSent(At(s0 + 0.5), "Heal Self");
|
||||
}
|
||||
string sum = logs.Last();
|
||||
Check.True(sum.StartsWith("[HealLatency] summary of 10 heals:", StringComparison.Ordinal), $"summary line: {sum}");
|
||||
Check.True(sum.Contains("max 3100 ms (Heal Self, busy count)") && sum.Contains("2 over 1 s") == false && sum.Contains("1 over 1 s") && sum.Contains("1 over 3 s") && sum.Contains("1 episode(s) with no heal"),
|
||||
$"summary numbers: {sum}");
|
||||
}
|
||||
|
||||
private static void HeartbeatLogsEpisode()
|
||||
{
|
||||
var r = new Rig(healthPct: 40);
|
||||
r.S.SpellCastIntervalMs = 0;
|
||||
FakeHost.UseDoneSeq = 5;
|
||||
r.B.BusyCount = 1;
|
||||
r.At(0);
|
||||
r.B.OnHeartbeat(); // opens the episode; a live count holds it
|
||||
r.At(0.4);
|
||||
r.B.OnHeartbeat();
|
||||
Check.Eq(FakeHost.Casts.Count, 0, "held by the live busy count");
|
||||
FakeHost.UseDone(0);
|
||||
r.At(0.5);
|
||||
r.B.OnHeartbeat();
|
||||
Check.Eq(HealSelfCasts(), 1, "the UseDone frees it");
|
||||
string? line = r.Log("[HealLatency] 500 ms: health 40% under Top Off HP 60% (idle) -> Heal Self");
|
||||
Check.NotNull(line, "the episode line is logged with the delay and the line");
|
||||
Check.True(line!.Contains("busy count 400 ms"), $"and what held it: {line}");
|
||||
Check.Eq(r.B.BuffingLabel, BuffManager.LabelHealing, "while Heal Self is in flight the slot reads Healing");
|
||||
}
|
||||
|
||||
// Drakkon, 2026-10-05 13:43:09: "[HealLatency] 5831 ms: health 12% under Emergency Heal At 30%
|
||||
// (idle) -> Peerless Healing Kit; held by: login buff refresh 5737 ms". An engine hot reload
|
||||
// made RynthAi wait for its login buff refresh, and the refresh held heals too. It holds buffs
|
||||
// only now. (The registry read never succeeds here: server time 0, as before a time sync.)
|
||||
private static void EmergencyBeatsLoginRefresh()
|
||||
{
|
||||
var r = new Rig(healthPct: 12, liveBuffsReady: false);
|
||||
r.S.EmergencyHealAt = 30;
|
||||
r.S.EnableBuffing = true;
|
||||
r.At(0);
|
||||
r.B.OnHeartbeat();
|
||||
Check.False(r.B.LiveBuffsReady, "the login refresh hasn't got a snapshot");
|
||||
Check.Eq(HealSelfCasts(), 1, "Heal Self goes out on the first heartbeat anyway");
|
||||
string? line = r.Log("[HealLatency]");
|
||||
Check.True(line != null && !line.Contains("login buff refresh"), $"the heal was not held by the refresh: {line}");
|
||||
|
||||
// Health fine: the refresh still holds every buff.
|
||||
var q = new Rig(healthPct: 100, liveBuffsReady: false);
|
||||
q.S.EnableBuffing = true;
|
||||
q.S.SpellCastIntervalMs = 0;
|
||||
q.B.OnHeartbeat();
|
||||
q.B.OnHeartbeat();
|
||||
Check.Eq(FakeHost.Casts.Count, 0, "no buff cast before the refresh is ready");
|
||||
Check.Eq(FakeHost.Uses.Count, 0, "and no buff item used");
|
||||
}
|
||||
|
||||
private static void ActivityLabels()
|
||||
{
|
||||
Check.Eq(ActivityArbiter.DisplayLabel("Buffing", "Healing"), "Healing", "Buffing slot: its label");
|
||||
Check.Eq(ActivityArbiter.DisplayLabel("Buffing", ""), "Buffing", "no label: Buffing");
|
||||
Check.Eq(ActivityArbiter.DisplayLabel("Combat", "Healing"), "Combat", "anything else: the control string");
|
||||
Check.Eq(ActivityArbiter.DisplayLabel(null, "Healing"), "Default", "empty: Default (the dashboard shows Idle)");
|
||||
Check.Eq(ActivityArbiter.ToBotAction(BotActivity.Buffing), "Buffing", "the control string stays Buffing");
|
||||
|
||||
Check.Eq(BuffManager.VitalLabel("Heal Self"), "Healing", "Heal Self");
|
||||
Check.Eq(BuffManager.VitalLabel("Stamina to Health Self"), "Healing", "Stamina to Health");
|
||||
Check.Eq(BuffManager.VitalLabel("Stamina to Mana Self"), "Restoring mana", "Stamina to Mana");
|
||||
Check.Eq(BuffManager.VitalLabel("Revitalize Self"), "Restoring stamina", "Revitalize");
|
||||
|
||||
var mana = new Rig(healthPct: 100, manaPct: 10);
|
||||
mana.S.GetManaAt = 50; mana.S.TopOffMana = 50;
|
||||
Check.True(mana.B.CheckVitals(), "10% mana: Stamina to Mana is cast");
|
||||
Check.Eq(mana.B.BuffingLabel, "Restoring mana", "and the slot reads Restoring mana");
|
||||
|
||||
var heal = new Rig(healthPct: 40);
|
||||
Check.Eq(heal.B.BuffingLabel, "Healing", "health under the line before anything ran: Healing");
|
||||
heal.B.MarkKitUsed();
|
||||
Check.Eq(heal.B.BuffingLabel, "Healing", "a healing kit in flight: Healing");
|
||||
var stam = new Rig(healthPct: 100);
|
||||
stam.B.MarkKitUsed(stamina: true);
|
||||
Check.Eq(stam.B.BuffingLabel, "Restoring stamina", "a stamina kit in flight: Restoring stamina");
|
||||
|
||||
var idle = new Rig(healthPct: 100);
|
||||
Check.Eq(idle.B.BuffingLabel, "Buffing", "nothing vital going on: Buffing");
|
||||
}
|
||||
}
|
||||
|
|
@ -27,6 +27,8 @@ internal static class LootAddItemTests
|
|||
{
|
||||
private const uint Player = 0x50000E01;
|
||||
private const uint Opal = 0x80271101, Taper = 0x80271102, Coin = 0x80271103;
|
||||
private const uint Ring = 0x80271104, Stone = 0x80271105, Sceptre = 0x80271106;
|
||||
private const uint ItemTypeJewelry = 0x8, ItemTypeCaster = 0x8000, ItemTypeManaStone = 0x80000, CurrentMana = 107;
|
||||
private const uint ItemTypeGem = 0x800, ItemTypeComponent = 0x1000;
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
|
||||
|
||||
|
|
@ -39,6 +41,8 @@ internal static class LootAddItemTests
|
|||
r.Add("loot add: refusals (nothing selected, the same rule twice, no profile)", Refusals);
|
||||
r.Add("loot add: the popup's item_preview / item_add / item_close through the editor bridge", BridgePopupFlow);
|
||||
r.Add("loot add: unsaved edits in the Loot Editor block the add (nothing saved behind them)", BridgeRefusesUnderEdits);
|
||||
r.Add("loot add: the popup says when RynthAi's built-in looting takes the item (Mana Tap, mana stones)", BuiltInReasons);
|
||||
r.Add("loot: Mana Tap never loots a wand (ACE won't drain one, so it was kept for good)", ManaTapSkipsWands);
|
||||
}
|
||||
|
||||
// ── World and plugin ──────────────────────────────────────────────────────
|
||||
|
|
@ -48,8 +52,10 @@ internal static class LootAddItemTests
|
|||
public readonly RynthAiPlugin P = new();
|
||||
public readonly LegacyUiSettings S = new();
|
||||
public readonly WorldObjectCache Cache;
|
||||
public readonly RynthCoreHost Host;
|
||||
|
||||
public Bot()
|
||||
/// <summary><paramref name="world"/> adds objects (after the standard ones, before the host); list their ids in <paramref name="extra"/>.</summary>
|
||||
public Bot(Action? world = null, params uint[] extra)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.Names[Player] = "Tester";
|
||||
|
|
@ -62,12 +68,14 @@ internal static class LootAddItemTests
|
|||
FakeHost.Ints[(Taper, 11)] = 100; // MaxStackSize
|
||||
FakeHost.Ints[(Taper, 12)] = 37; // StackCount
|
||||
FakeHost.Names[Coin] = "Pyreal";
|
||||
world?.Invoke();
|
||||
var host = FakeHost.Create(Player);
|
||||
Host = host;
|
||||
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
|
||||
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
|
||||
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S);
|
||||
Set("_dashboard", dash);
|
||||
Cache = FakeHost.MakeCache(host, Player, new[] { Player, Opal, Taper, Coin });
|
||||
Cache = FakeHost.MakeCache(host, Player, new[] { Player, Opal, Taper, Coin }.Concat(extra));
|
||||
Set("_objectCache", Cache);
|
||||
Set("_playerId", Player);
|
||||
Set("_charSkills", new CharacterSkills(host));
|
||||
|
|
@ -340,4 +348,113 @@ internal static class LootAddItemTests
|
|||
Check.Eq(File.ReadAllText(path), SellGems, "nothing saved");
|
||||
Check.Eq(State(b).Rules[1].Name, "half-done", "the edit is still there, unsaved");
|
||||
}
|
||||
|
||||
// ── Built-in keeps (2026-10-05) ───────────────────────────────────────────
|
||||
|
||||
// A ring with 3,001 mana, an empty mana stone in the pack, tapping on at 2,500.
|
||||
private static Bot TapWorld()
|
||||
{
|
||||
var bot = new Bot(() =>
|
||||
{
|
||||
FakeHost.Names[Ring] = "Gold Ring";
|
||||
FakeHost.ItemTypes[Ring] = ItemTypeJewelry;
|
||||
FakeHost.Ints[(Ring, CurrentMana)] = 3001;
|
||||
FakeHost.Names[Stone] = "Mana Stone";
|
||||
FakeHost.ItemTypes[Stone] = ItemTypeManaStone;
|
||||
FakeHost.Ints[(Stone, CurrentMana)] = 0;
|
||||
FakeHost.Names[Sceptre] = "Piercing Sceptre";
|
||||
FakeHost.ItemTypes[Sceptre] = ItemTypeCaster;
|
||||
FakeHost.Ints[(Sceptre, CurrentMana)] = 3001;
|
||||
}, Ring, Stone, Sceptre);
|
||||
bot.S.EnableManaTapping = true;
|
||||
bot.S.ManaTapMinMana = 2500;
|
||||
bot.Set("_manaStoneManager", new ManaStoneManager(bot.Host, bot.S, bot.Cache));
|
||||
return bot;
|
||||
}
|
||||
|
||||
/// <summary>The looter's own call (what [LootEval] logs): taken?, action tag, rule label.</summary>
|
||||
private static (bool Taken, string Action, string Rule) LootEval(Bot bot, uint id)
|
||||
{
|
||||
MethodInfo m = typeof(RynthAiPlugin).GetMethod("ClassifyItemAgainstProfile", Any)!;
|
||||
object?[] args = { bot.Item(id), bot.S, null, null, null };
|
||||
bool taken = (bool)m.Invoke(bot.P, args)!;
|
||||
return (taken, (string)args[2]!, (string)args[4]!);
|
||||
}
|
||||
|
||||
private static void BuiltInReasons()
|
||||
{
|
||||
// Tom, 2026-10-05: "when I click on the wand it says no rule matches" - Mana Tap had
|
||||
// looted it. The popup now says which built-in keep takes an item and where to change it.
|
||||
var bot = TapWorld();
|
||||
string path = Temp("tap.utl", SellGems);
|
||||
bot.S.CurrentLootPath = path;
|
||||
LootEditorBridge b = bot.P.LootEditor;
|
||||
FakeHost.Chat.Clear();
|
||||
|
||||
Send(b, new LootEditCommand { Op = "item_preview", Item = new LootEditItemRequest { ItemId = Ring, Seq = 1 } });
|
||||
LootEditItemDraft? d = State(b).ItemDraft;
|
||||
Check.True(d != null && d.Ok, "draft: " + d?.Error);
|
||||
const string tap = "No rule in the loot profile in use takes it, but RynthAi keeps it anyway: "
|
||||
+ "Mana Tap (3,001 mana >= 2,500), looted to drain into an empty mana stone - change in the Items panel, Mana Stone Tapping.";
|
||||
Check.Eq(d?.BuiltInReason, tap, "the reason, with the numbers and where to change it");
|
||||
Check.True(d != null && d.OrderNote.Contains("at the end") && d.OrderNote.EndsWith(tap, StringComparison.Ordinal),
|
||||
"OrderNote (what every engine's popup shows) carries it: " + d?.OrderNote);
|
||||
Check.True(d != null && d.OrderNote.All(c => c < 128), "ASCII only (the popup's font)");
|
||||
|
||||
// The same function the looter runs: [LootEval] tags it [ManaTap].
|
||||
Check.Eq(bot.Get<System.Collections.Generic.HashSet<int>>("_pendingManaTapIds")?.Count, 0, "the preview recorded nothing");
|
||||
Check.False(bot.ChatText.Contains("Mana tap candidate"), "and said nothing in chat\n" + bot.ChatText);
|
||||
var eval = LootEval(bot, Ring);
|
||||
Check.True(eval.Taken && eval.Action == "ManaTap", "the looter takes it as [ManaTap]: " + eval.Action);
|
||||
Check.True(eval.Rule.StartsWith("ManaTap (mana=3001", StringComparison.Ordinal), "rule label as in the log: " + eval.Rule);
|
||||
|
||||
// A profile rule decides: no built-in reason.
|
||||
Send(b, new LootEditCommand { Op = "item_preview", Item = new LootEditItemRequest { ItemId = Opal, Seq = 2 } });
|
||||
d = State(b).ItemDraft;
|
||||
Check.Eq(d?.BuiltInReason, "", "the gem: rule 1 sells it, nothing built in");
|
||||
Check.True(d != null && d.OrderNote.Contains("just before rule 1 'Sell all gems'"), "order note as before: " + d?.OrderNote);
|
||||
|
||||
// Mana stones are checked ahead of the profile.
|
||||
Send(b, new LootEditCommand { Op = "item_preview", Item = new LootEditItemRequest { ItemId = Stone, Seq = 3 } });
|
||||
d = State(b).ItemDraft;
|
||||
Check.True(d != null && d.BuiltInReason.StartsWith("RynthAi takes it before any loot profile rule: a mana stone,", StringComparison.Ordinal),
|
||||
"mana stone: " + d?.BuiltInReason);
|
||||
Check.True(d != null && d.BuiltInReason.Contains("of 5 kept - change in the Items panel"), "with the keep count");
|
||||
|
||||
// Under the threshold: not taken, nothing to explain.
|
||||
bot.S.ManaTapMinMana = 5000;
|
||||
Send(b, new LootEditCommand { Op = "item_preview", Item = new LootEditItemRequest { ItemId = Ring, Seq = 4 } });
|
||||
Check.Eq(State(b).ItemDraft?.BuiltInReason, "", "3,001 mana under a 5,000 threshold: no reason");
|
||||
bot.S.ManaTapMinMana = 2500;
|
||||
|
||||
// Already in the pack after a Mana Tap pickup, quota full now: still says why it was taken.
|
||||
bot.Get<System.Collections.Generic.HashSet<int>>("_pendingManaTapIds")!.Clear(); // (the LootEval call above approved it)
|
||||
bot.Get<ManaStoneManager>("_manaStoneManager")!.MarkLootedForTap(unchecked((int)Ring));
|
||||
FakeHost.Ints[(Stone, CurrentMana)] = 500; // the only stone is charged: no free slot
|
||||
Send(b, new LootEditCommand { Op = "item_preview", Item = new LootEditItemRequest { ItemId = Ring, Seq = 5 } });
|
||||
Check.Eq(State(b).ItemDraft?.BuiltInReason,
|
||||
"No rule in the loot profile in use takes it, but RynthAi keeps it anyway: it was looted for Mana Tap, to drain into an empty mana stone - change in the Items panel, Mana Stone Tapping.",
|
||||
"looted for tapping earlier");
|
||||
|
||||
// /ra loot add preview shows it in chat too.
|
||||
FakeHost.Ints[(Stone, CurrentMana)] = 0;
|
||||
FakeHost.SelectedItem = Ring;
|
||||
FakeHost.Chat.Clear();
|
||||
bot.Ra("/ra loot add preview");
|
||||
Check.True(bot.ChatText.Contains("RynthAi keeps it anyway: it was looted for Mana Tap"), "/ra loot add preview says it\n" + bot.ChatText);
|
||||
Check.Eq(File.ReadAllText(path), SellGems, "preview saves nothing");
|
||||
}
|
||||
|
||||
private static void ManaTapSkipsWands()
|
||||
{
|
||||
var bot = TapWorld();
|
||||
bot.S.CurrentLootPath = Temp("wand.utl", SellGems);
|
||||
var wand = LootEval(bot, Sceptre);
|
||||
Check.False(wand.Taken, $"a 3,001-mana sceptre is left: [{wand.Action}] {wand.Rule}");
|
||||
Check.Eq(bot.Get<System.Collections.Generic.HashSet<int>>("_pendingManaTapIds")?.Count, 0, "not counted against the tap quota");
|
||||
var ring = LootEval(bot, Ring);
|
||||
Check.True(ring.Taken && ring.Action == "ManaTap", "a ring with the same mana is still tapped: " + ring.Action);
|
||||
Send(bot.P.LootEditor, new LootEditCommand { Op = "item_preview", Item = new LootEditItemRequest { ItemId = Sceptre, Seq = 1 } });
|
||||
Check.Eq(State(bot.P.LootEditor).ItemDraft?.BuiltInReason, "", "the popup has no built-in reason for the wand");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
461
Tools/RynthCore.RynthAiHostTests/Tests/OwnCorpseTests.cs
Normal file
461
Tools/RynthCore.RynthAiHostTests/Tests/OwnCorpseTests.cs
Normal file
|
|
@ -0,0 +1,461 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using RynthCore.Loot;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.PluginCore;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// 2026-10-05, owner: "It needs to loot your corpse and every item on it. If it's a setting default
|
||||
// to true please." Recover My Corpse (LootOwnCorpse, default on) takes every item on your own death
|
||||
// corpse whatever the loot profile and Loot From say; the death spot is remembered; Travel Back To
|
||||
// My Corpse (TravelToOwnCorpse, default off) walks back with RynthNav (/rnav go via the broker).
|
||||
internal static class OwnCorpseTests
|
||||
{
|
||||
private const uint Player = 0x50000D01;
|
||||
private const uint Corpse = 0x80261100;
|
||||
private const uint Gem = 0x80261101;
|
||||
private const uint Cloak = 0x80261102;
|
||||
private const uint Coins = 0x80261103;
|
||||
private const uint ItemTypeClothing = 0x4, ItemTypeMoney = 0x40, ItemTypeContainer = 0x200, ItemTypeGem = 0x800;
|
||||
private const uint LongDescKey = 16;
|
||||
private const string Me = "Dargoth Hera";
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("own corpse: recognised by exact name + 'Killed by' line, never a namesake or another player's", Identification);
|
||||
r.Add("own corpse: every item is taken, the loot profile and Loot From ignored, then closed", RecoveredWhole);
|
||||
r.Add("own corpse: another player's corpse with a similar name is left alone", SimilarNameUntouched);
|
||||
r.Add("own corpse: Recover My Corpse off = the behaviour before (profile only, My Kills skips it)", SettingOffIsOldBehaviour);
|
||||
r.Add("own corpse: beats a nearer corpse of your kill; a timeout retries it instead of writing it off", PriorityAndTimeout);
|
||||
r.Add("own corpse: settings default on/off, an old profile loads on, saved and bridged", SettingsDefaults);
|
||||
r.Add("own corpse: the death spot is remembered and said, server lines read", DeathSpotRemembered);
|
||||
r.Add("own corpse: travel back walks with RynthNav, stops for combat, ends in loot range", TravelBack);
|
||||
r.Add("own corpse: travel back refuses an indoor death and a missing RynthNav", TravelRefusals);
|
||||
}
|
||||
|
||||
// ── World ─────────────────────────────────────────────────────────────
|
||||
|
||||
private static (uint Cell, float X, float Y, float Z) Me0 => (0x1048002Au, 100f, 100f, 0f);
|
||||
|
||||
private static void World(string corpseName, string? longDesc, bool closeCalls = false)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.SalvageCalls = true; // UseObject + MoveItemExternal
|
||||
FakeHost.WeaponCalls = true; // RequestId, HasAppraisalData
|
||||
FakeHost.CloseContainerCalls = closeCalls;
|
||||
FakeHost.Names[Player] = Me;
|
||||
FakeHost.Positions[Player] = Me0;
|
||||
FakeHost.PlayerPose = Me0;
|
||||
FakeHost.Names[Corpse] = corpseName;
|
||||
FakeHost.ItemTypes[Corpse] = ItemTypeContainer;
|
||||
if (longDesc != null)
|
||||
FakeHost.Strings[(Corpse, LongDescKey)] = longDesc;
|
||||
FakeHost.NotAttackable.Add(Corpse);
|
||||
FakeHost.Positions[Corpse] = (Me0.Cell, Me0.X + 1.0f, Me0.Y, Me0.Z);
|
||||
Item(Gem, "Black Opal", ItemTypeGem); // the test profile keeps gems
|
||||
Item(Cloak, "Faran Cloak", ItemTypeClothing); // ...and nothing else
|
||||
Item(Coins, "Pyreal", ItemTypeMoney);
|
||||
}
|
||||
|
||||
private static void Item(uint id, string name, uint type)
|
||||
{
|
||||
FakeHost.Names[id] = name;
|
||||
FakeHost.ItemTypes[id] = type;
|
||||
FakeHost.Containers[id] = Corpse; // also installs GetObjectOwnershipInfo
|
||||
FakeHost.Appraised.Add(id);
|
||||
}
|
||||
|
||||
private sealed class Bot
|
||||
{
|
||||
public readonly RynthAiPlugin P = new();
|
||||
public readonly LegacyUiSettings S = new()
|
||||
{
|
||||
IsMacroRunning = true,
|
||||
EnableLooting = true,
|
||||
EnableCombat = false,
|
||||
LootOwnership = 0, // My Kills Only
|
||||
LootContentSettleMs = 0,
|
||||
LootEmptyCorpseMs = 0,
|
||||
StopLootingWhenPackFull = false,
|
||||
};
|
||||
public readonly WorldObjectCache Cache;
|
||||
|
||||
public Bot(RynthCoreHost host)
|
||||
{
|
||||
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
|
||||
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
|
||||
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S);
|
||||
Set("_dashboard", dash);
|
||||
Cache = new WorldObjectCache(host);
|
||||
Cache.SetPlayerId(Player);
|
||||
Set("_objectCache", Cache);
|
||||
Set("_playerId", Player);
|
||||
|
||||
string profile = Path.Combine(Program.TempRoot, "own-corpse-test.json");
|
||||
var p = new LootProfile { Name = "gems" };
|
||||
var rule = new LootRule { Name = "Gems", Action = LootAction.Keep };
|
||||
rule.Conditions.Add(new ObjectClassCondition { ObjectClass = AcObjectClass.Gem });
|
||||
p.Rules.Add(rule);
|
||||
p.Save(profile);
|
||||
S.CurrentLootPath = profile;
|
||||
}
|
||||
|
||||
public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v);
|
||||
public T Get<T>(string f) => (T)typeof(RynthAiPlugin).GetField(f, Any)!.GetValue(P)!;
|
||||
public object? Call(string m, params object[] a) => typeof(RynthAiPlugin).GetMethod(m, Any)!.Invoke(P, a);
|
||||
public bool HasLootWork() => (bool)Call("HasLootWork", S, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())!;
|
||||
public void Tick(BotActivity act)
|
||||
{
|
||||
Set("_activity", act);
|
||||
Call("TickCorpseOpening");
|
||||
}
|
||||
public bool Completed => Get<Dictionary<int, long>>("_completedCorpses").ContainsKey(unchecked((int)Corpse));
|
||||
public bool ShouldLoot(uint id) => (bool)Call("ShouldLootCorpse", Cache[unchecked((int)id)]!)!;
|
||||
}
|
||||
|
||||
private static Bot NewBot()
|
||||
{
|
||||
var host = FakeHost.Create(Player);
|
||||
var bot = new Bot(host);
|
||||
bot.Cache.OnCreateObject(Corpse);
|
||||
bot.Cache.Tick();
|
||||
return bot;
|
||||
}
|
||||
|
||||
/// <summary>Claims and opens the corpse, then ticks; each item the bot moves lands in the pack.</summary>
|
||||
private static void LootToTheEnd(Bot bot, int maxTicks = 400)
|
||||
{
|
||||
bot.Tick(BotActivity.Looting);
|
||||
Check.True(FakeHost.Uses.Contains(Corpse), "the corpse is opened");
|
||||
foreach (uint id in new[] { Gem, Cloak, Coins })
|
||||
bot.Cache.OnCreateObject(id);
|
||||
bot.Cache.Tick();
|
||||
if (FakeHost.CloseContainerCalls) FakeHost.GroundContainer = Corpse;
|
||||
bot.P.OnViewObjectContents(Corpse);
|
||||
|
||||
for (int i = 0; i < maxTicks && !bot.Completed; i++)
|
||||
{
|
||||
bot.Tick(BotActivity.Looting);
|
||||
foreach (var m in FakeHost.ExternalMoves)
|
||||
FakeHost.Containers[m.Id] = Player; // the server moved it
|
||||
Thread.Sleep(10);
|
||||
}
|
||||
}
|
||||
|
||||
private static string Moves() => string.Join(",", FakeHost.ExternalMoves.Select(m => $"{m.Id:X8}->{m.Target:X8}"));
|
||||
|
||||
// ── Identification ────────────────────────────────────────────────────
|
||||
|
||||
private static void Identification()
|
||||
{
|
||||
OwnCorpseMatch M(string name, string me, string? desc) => RynthAiPlugin.MatchOwnDeathCorpse(name, me, desc);
|
||||
Check.Eq(M("Corpse of Dargoth Hera", Me, "Killed by Drudge Skulker."), OwnCorpseMatch.Yes, "your name, killed by a monster");
|
||||
Check.Eq(M("Corpse of Dargoth Hera", Me, "Killed by misadventure."), OwnCorpseMatch.Yes, "a fall (misadventure)");
|
||||
Check.Eq(M("Corpse of Dargoth Hera", Me, null), OwnCorpseMatch.Pending, "no ID yet: wait for it");
|
||||
Check.Eq(M("Corpse of Dargoth Hera", Me, "Killed by Dargoth Hera."), OwnCorpseMatch.No, "a namesake you killed is not your death corpse");
|
||||
Check.Eq(M("Corpse of Dargoth Hera", Me, "A corpse."), OwnCorpseMatch.No, "no 'Killed by' line: not a death corpse");
|
||||
Check.Eq(M("Corpse of Dargoth Heras", Me, "Killed by Drudge."), OwnCorpseMatch.No, "a longer name");
|
||||
Check.Eq(M("Corpse of Dargoth Her", Me, "Killed by Drudge."), OwnCorpseMatch.No, "a shorter name");
|
||||
Check.Eq(M("Corpse of dargoth hera", Me, "Killed by Drudge."), OwnCorpseMatch.No, "exact case only");
|
||||
Check.Eq(M("Corpse of Dargoth Hera's Wolf", Me, "Killed by Drudge."), OwnCorpseMatch.No, "a pet's corpse");
|
||||
Check.Eq(M("Dargoth Hera's corpse", Me, "Killed by Drudge."), OwnCorpseMatch.No, "another naming");
|
||||
Check.Eq(M("Corpse of +Dargoth Hera", "+Dargoth Hera", "Killed by Drudge."), OwnCorpseMatch.Yes, "a GM's corpse carries the sigil, as the name does");
|
||||
Check.Eq(M("Corpse of Dargoth Hera", "+Dargoth Hera", "Killed by Drudge."), OwnCorpseMatch.No, "a GM never matches the plain name");
|
||||
Check.Eq(M("Corpse of Dargoth Hera", "", "Killed by Drudge."), OwnCorpseMatch.No, "no player name yet: nothing matches");
|
||||
}
|
||||
|
||||
// ── Recovery ──────────────────────────────────────────────────────────
|
||||
|
||||
private static void RecoveredWhole()
|
||||
{
|
||||
World("Corpse of " + Me, "Killed by Ancient Water Elemental.", closeCalls: true);
|
||||
var bot = NewBot();
|
||||
Check.True(bot.ShouldLoot(Corpse), "My Kills Only, killed by a monster: still yours to recover");
|
||||
Check.True(bot.HasLootWork(), "looting wants the tick");
|
||||
|
||||
LootToTheEnd(bot);
|
||||
Check.True(FakeHost.ExternalMoves.Any(m => m.Id == Gem), "the gem (the profile keeps it) is taken: " + Moves());
|
||||
Check.True(FakeHost.ExternalMoves.Any(m => m.Id == Cloak), "the cloak (no profile rule) is taken too: " + Moves());
|
||||
Check.True(FakeHost.ExternalMoves.Any(m => m.Id == Coins), "and the pyreals: " + Moves());
|
||||
Check.True(FakeHost.ExternalMoves.All(m => m.Target == Player), "into the pack");
|
||||
Check.False(FakeHost.Uses.Any(u => u is Gem or Cloak or Coins), "never a use (a use can wield)");
|
||||
var first = FakeHost.ExternalMoves.Select(m => m.Id).ToList();
|
||||
Check.Eq(first.Distinct().Count(), 3, "one move per item (each confirmed before the next)");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("[RynthAi] Own corpse: recovering 3 items.")), "says how many it recovers");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("[RynthAi] Own corpse: recovered everything (3 items).")), "and that it got everything");
|
||||
Check.True(FakeHost.Chat.Any(l => l.Contains("recovered everything")), "in chat too");
|
||||
Check.False(FakeHost.Logs.Any(l => l.Contains("[LootEval]")), "no loot profile evaluation at all");
|
||||
Check.True(bot.Completed, "the corpse is completed");
|
||||
Check.Eq(string.Join(",", FakeHost.Closes.Select(c => $"{c:X8}")), $"{Corpse:X8}", "and closed, once");
|
||||
Check.False(bot.Get<bool>("_currentLootItemIsSalvage"), "nothing queued for salvage");
|
||||
}
|
||||
|
||||
private static void SimilarNameUntouched()
|
||||
{
|
||||
World("Corpse of " + Me + "s", "Killed by Ancient Water Elemental.");
|
||||
var bot = NewBot();
|
||||
Check.False(bot.ShouldLoot(Corpse), "My Kills Only: a similar name is someone else's corpse");
|
||||
Check.False(bot.HasLootWork(), "nothing to loot");
|
||||
bot.Tick(BotActivity.Looting);
|
||||
Check.Eq(bot.Get<int>("_targetCorpseId"), 0, "not claimed");
|
||||
Check.False(FakeHost.Uses.Contains(Corpse), "not opened");
|
||||
|
||||
// Loot From All Corpses: looted by the profile only (the gem), never recovered whole.
|
||||
World("Corpse of " + Me + "s", "Killed by Ancient Water Elemental.");
|
||||
var all = NewBot();
|
||||
all.S.LootOwnership = 2;
|
||||
LootToTheEnd(all);
|
||||
Check.True(FakeHost.ExternalMoves.Any(m => m.Id == Gem), "All Corpses: the profile's gem: " + Moves());
|
||||
Check.False(FakeHost.ExternalMoves.Any(m => m.Id == Cloak || m.Id == Coins), "nothing else: " + Moves());
|
||||
Check.False(FakeHost.Logs.Any(l => l.Contains("Own corpse")), "never treated as your corpse");
|
||||
|
||||
// Your exact name but no ID yet: held, not looted by the profile meanwhile.
|
||||
World("Corpse of " + Me, null);
|
||||
var pending = NewBot();
|
||||
pending.S.LootOwnership = 2;
|
||||
Check.False(pending.ShouldLoot(Corpse), "named like yours, unidentified: waits for its ID");
|
||||
Check.True(FakeHost.IdRequests.Contains(Corpse), "its ID is asked for");
|
||||
}
|
||||
|
||||
private static void SettingOffIsOldBehaviour()
|
||||
{
|
||||
World("Corpse of " + Me, "Killed by Ancient Water Elemental.");
|
||||
var bot = NewBot();
|
||||
bot.S.LootOwnCorpse = false;
|
||||
Check.False(bot.ShouldLoot(Corpse), "My Kills Only: a monster killed you, so it is skipped (as before)");
|
||||
Check.False(bot.HasLootWork(), "nothing to loot");
|
||||
|
||||
World("Corpse of " + Me, "Killed by Ancient Water Elemental.");
|
||||
var all = NewBot();
|
||||
all.S.LootOwnCorpse = false;
|
||||
all.S.LootOwnership = 2;
|
||||
LootToTheEnd(all);
|
||||
Check.True(FakeHost.ExternalMoves.Any(m => m.Id == Gem), "All Corpses: the profile's gem: " + Moves());
|
||||
Check.False(FakeHost.ExternalMoves.Any(m => m.Id == Cloak || m.Id == Coins), "only what the profile keeps: " + Moves());
|
||||
Check.False(FakeHost.Logs.Any(l => l.Contains("Own corpse")), "no own-corpse recovery");
|
||||
}
|
||||
|
||||
private static void PriorityAndTimeout()
|
||||
{
|
||||
const uint Kill = 0x80261200;
|
||||
World("Corpse of " + Me, "Killed by Ancient Water Elemental.");
|
||||
FakeHost.Positions[Corpse] = (Me0.Cell, Me0.X + 4.0f, Me0.Y, Me0.Z); // yours, 4 m
|
||||
FakeHost.Names[Kill] = "Corpse of Drudge Skulker";
|
||||
FakeHost.ItemTypes[Kill] = ItemTypeContainer;
|
||||
FakeHost.Strings[(Kill, LongDescKey)] = $"Killed by {Me}.";
|
||||
FakeHost.NotAttackable.Add(Kill);
|
||||
FakeHost.Positions[Kill] = (Me0.Cell, Me0.X + 1.0f, Me0.Y, Me0.Z); // your kill, 1 m
|
||||
var bot = NewBot();
|
||||
bot.Cache.OnCreateObject(Kill);
|
||||
bot.Cache.Tick();
|
||||
Check.True(bot.ShouldLoot(Kill), "your kill is lootable");
|
||||
bot.Tick(BotActivity.Looting);
|
||||
Check.Eq(bot.Get<int>("_targetCorpseId"), unchecked((int)Corpse), "your own corpse is claimed first, though further");
|
||||
|
||||
// It timed out once it was opened: not completed (that would leave your things for good).
|
||||
bot.P.OnViewObjectContents(Corpse);
|
||||
bot.Call("AbandonCurrentCorpse", Environment.TickCount64, "timeout");
|
||||
Check.False(bot.Completed, "an own corpse that timed out is not written off");
|
||||
Check.True(bot.Get<Dictionary<int, long>>("_corpseCooldownUntil").ContainsKey(unchecked((int)Corpse)), "it is retried after a short wait");
|
||||
for (int i = 1; i < RynthAiPlugin.OwnCorpseMaxAbandons; i++)
|
||||
{
|
||||
bot.P.OnViewObjectContents(Corpse);
|
||||
bot.Call("AbandonCurrentCorpse", Environment.TickCount64, "timeout");
|
||||
}
|
||||
Check.True(bot.Completed, $"after {RynthAiPlugin.OwnCorpseMaxAbandons} timeouts it is given up");
|
||||
Check.True(FakeHost.Chat.Any(l => l.Contains("Own corpse: giving up")), "and it says so");
|
||||
}
|
||||
|
||||
// ── Settings ──────────────────────────────────────────────────────────
|
||||
|
||||
private static void SettingsDefaults()
|
||||
{
|
||||
Check.True(new LegacyUiSettings().LootOwnCorpse, "Recover My Corpse: on for a new profile");
|
||||
Check.False(new LegacyUiSettings().TravelToOwnCorpse, "Travel Back To My Corpse: off for a new profile");
|
||||
var old = JsonSerializer.Deserialize("{\"EnableLooting\":true,\"LootOwnership\":0}", RynthAiJsonContext.Default.LegacyUiSettings);
|
||||
Check.True(old != null && old.LootOwnCorpse, "a profile saved before the setting: on");
|
||||
Check.True(old != null && !old.TravelToOwnCorpse, "and travel off");
|
||||
var saved = JsonSerializer.Deserialize(
|
||||
JsonSerializer.Serialize(new LegacyUiSettings { LootOwnCorpse = false, TravelToOwnCorpse = true }, RynthAiJsonContext.Default.LegacyUiSettings),
|
||||
RynthAiJsonContext.Default.LegacyUiSettings);
|
||||
Check.True(saved != null && !saved.LootOwnCorpse && saved.TravelToOwnCorpse, "both are saved and loaded");
|
||||
|
||||
var copy = typeof(LegacyDashboardRenderer).GetMethod("CopySettings", BindingFlags.NonPublic | BindingFlags.Static)!;
|
||||
var dst = new LegacyUiSettings();
|
||||
copy.Invoke(null, new object[] { new LegacyUiSettings { LootOwnCorpse = false, TravelToOwnCorpse = true }, dst });
|
||||
Check.True(!dst.LootOwnCorpse && dst.TravelToOwnCorpse, "a profile switch copies both");
|
||||
copy.Invoke(null, new object[] { old!, dst });
|
||||
Check.True(dst.LootOwnCorpse && !dst.TravelToOwnCorpse, "an old profile loads the defaults");
|
||||
|
||||
// The engine's Settings face: sent, and an engine without the fields leaves them alone.
|
||||
var payload = JsonSerializer.Deserialize("{\"PatrolOnLogin\":false}", RynthAiJsonContext.Default.SettingsBridgePayload);
|
||||
Check.True(payload != null && payload.LootOwnCorpse == null && payload.TravelToOwnCorpse == null, "an older engine's payload has no value");
|
||||
var s = new LegacyUiSettings { LootOwnCorpse = false, TravelToOwnCorpse = true };
|
||||
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
|
||||
typeof(LegacyDashboardRenderer).GetField("_settings", BindingFlags.NonPublic | BindingFlags.Instance)!.SetValue(dash, s);
|
||||
typeof(LegacyDashboardRenderer).GetField("_advancedSettingsUi", BindingFlags.NonPublic | BindingFlags.Instance)!
|
||||
.SetValue(dash, new LegacyAdvancedSettingsUi(s));
|
||||
var sent = JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload);
|
||||
Check.True(sent != null && sent.LootOwnCorpse == false && sent.TravelToOwnCorpse == true, "sent to the engine face");
|
||||
dash.ApplySettingsJson("{\"PatrolOnLogin\":false}");
|
||||
Check.True(!s.LootOwnCorpse && s.TravelToOwnCorpse, "a save without the fields leaves them");
|
||||
dash.ApplySettingsJson("{\"LootOwnCorpse\":true,\"TravelToOwnCorpse\":false}");
|
||||
Check.True(s.LootOwnCorpse && !s.TravelToOwnCorpse, "a save with them sets them");
|
||||
}
|
||||
|
||||
// ── Death spot ────────────────────────────────────────────────────────
|
||||
|
||||
private static Bot DieAt(double ns, double ew, uint? cell = null, bool broker = false, bool navLoaded = true)
|
||||
{
|
||||
World("Corpse of " + Me, "Killed by Ancient Water Elemental.");
|
||||
FakeHost.PluginCommandCalls = broker;
|
||||
FakeHost.PluginCommandDelivered = navLoaded;
|
||||
FakeHost.SetNavPosition(ns, ew);
|
||||
if (cell is uint c) FakeHost.PlayerPose = (c, 50f, 60f, -12f);
|
||||
FakeHost.Positions[Player] = FakeHost.PlayerPose;
|
||||
var bot = NewBot();
|
||||
var vitals = bot.Get<PlayerVitalsCache>("_vitals");
|
||||
vitals.MaxHealth = 100;
|
||||
vitals.CurrentHealth = 0;
|
||||
bot.Call("CheckPlayerDeath", bot.S);
|
||||
return bot;
|
||||
}
|
||||
|
||||
private static void DeathSpotRemembered()
|
||||
{
|
||||
var bot = DieAt(42.10, 33.60);
|
||||
var spot = bot.P.DeathSpot;
|
||||
Check.True(spot != null, "the death spot is remembered");
|
||||
Check.True(spot != null && Math.Abs(spot.Ns - 42.10) < 0.01 && Math.Abs(spot.Ew - 33.60) < 0.01, $"at the death position ({spot?.Ns:0.00}, {spot?.Ew:0.00})");
|
||||
Check.True(spot != null && spot.Outdoors && spot.Cell == FakeHost.PlayerPose.Cell, "with its landblock and cell");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("[RynthAi] Your corpse is at 42.10N, 33.60E (landblock 0x")), "logged: " + string.Join(" | ", FakeHost.Logs.Where(l => l.Contains("corpse is at"))));
|
||||
Check.True(FakeHost.Chat.Any(l => l.Contains("Your corpse is at 42.10N, 33.60E")), "and said in chat");
|
||||
|
||||
bot.Call("OnOwnCorpseChat", "You have retained all your items. You do not need to recover your corpse!"); // OnChatWindowText hands chat lines here
|
||||
Check.True(bot.P.DeathSpot!.NothingDropped, "the server's 'nothing dropped' line is noted");
|
||||
|
||||
var indoor = DieAt(0, 0, cell: 0x01D90123u);
|
||||
Check.True(indoor.P.DeathSpot != null && !indoor.P.DeathSpot.Outdoors, "a dungeon death is remembered as indoors");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("Your corpse is at landblock 0x01D9, cell 0x0123")), "with landblock and cell");
|
||||
|
||||
// No position at the death: the server's line gives the spot.
|
||||
World("Corpse of " + Me, "Killed by Ancient Water Elemental.");
|
||||
var noPose = NewBot();
|
||||
noPose.Call("OnOwnCorpseChat", "Your corpse is located at (12.3S, 45.6W)."); // OnChatWindowText hands chat lines here
|
||||
var fromChat = noPose.P.DeathSpot;
|
||||
Check.True(fromChat != null && Math.Abs(fromChat.Ns + 12.3) < 0.001 && Math.Abs(fromChat.Ew + 45.6) < 0.001, "taken from the server's line");
|
||||
}
|
||||
|
||||
// ── Travel back ───────────────────────────────────────────────────────
|
||||
|
||||
private static void BackdateIdle(Bot bot) => bot.Set("_travelIdleSince", Environment.TickCount64 - 10_000);
|
||||
|
||||
private static void TravelBack()
|
||||
{
|
||||
var bot = DieAt(42.10, 33.60, broker: true);
|
||||
bot.S.TravelToOwnCorpse = true;
|
||||
|
||||
// Respawned at a lifestone ~100 m away.
|
||||
FakeHost.SetNavPosition(42.50, 33.60);
|
||||
FakeHost.Positions[Player] = FakeHost.PlayerPose;
|
||||
bot.Call("OnRespawnedForOwnCorpse");
|
||||
Check.True(bot.Get<bool>("_ownCorpseTravelManual") == false, "started by the respawn, not by hand");
|
||||
Check.True((bool)typeof(RynthAiPlugin).GetProperty("OwnCorpseTravelHoldsNav", Any)!.GetValue(bot.P)!, "RynthAi's own route is parked meanwhile");
|
||||
|
||||
bot.Set("_activity", BotActivity.Idle);
|
||||
bot.Call("TickOwnCorpseTravel", bot.S);
|
||||
Check.Eq(FakeHost.PluginCommands.Count, 0, "waits a moment of quiet before walking");
|
||||
BackdateIdle(bot);
|
||||
bot.Call("TickOwnCorpseTravel", bot.S);
|
||||
Check.True(FakeHost.PluginCommands.Contains(("RynthNav", "rnav", "go 42.10N, 33.60E")),
|
||||
"walks with RynthNav: " + string.Join(" | ", FakeHost.PluginCommands));
|
||||
|
||||
// A monster: RynthAi fights, the walk stops.
|
||||
bot.Set("_activity", BotActivity.Combat);
|
||||
bot.Call("TickOwnCorpseTravel", bot.S);
|
||||
Check.Eq(FakeHost.PluginCommands.Last(), ("RynthNav", "rnav", "stop"), "the walk stops for combat");
|
||||
int count = FakeHost.PluginCommands.Count;
|
||||
bot.Call("TickOwnCorpseTravel", bot.S);
|
||||
Check.Eq(FakeHost.PluginCommands.Count, count, "one stop, not one per tick");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("travel paused for Combat")), "logged");
|
||||
|
||||
// Fight over: walk on.
|
||||
bot.Set("_activity", BotActivity.Idle);
|
||||
bot.Call("TickOwnCorpseTravel", bot.S);
|
||||
BackdateIdle(bot);
|
||||
bot.Call("TickOwnCorpseTravel", bot.S);
|
||||
Check.Eq(FakeHost.PluginCommands.Last(), ("RynthNav", "rnav", "go 42.10N, 33.60E"), "resumes after the fight");
|
||||
|
||||
// Near the spot, the corpse is in loot range: travel ends, looting takes over.
|
||||
FakeHost.SetNavPosition(42.10, 33.61); // ~2.4 m east... 0.01 coord = 2.4 m
|
||||
FakeHost.Positions[Player] = FakeHost.PlayerPose;
|
||||
var p = FakeHost.PlayerPose;
|
||||
FakeHost.Positions[Corpse] = (p.Cell, p.X + 1.0f, p.Y, p.Z);
|
||||
bot.Cache.OnCreateObject(Corpse);
|
||||
bot.Cache.Tick();
|
||||
bot.Call("TickOwnCorpseTravel", bot.S);
|
||||
Check.Eq(FakeHost.PluginCommands.Last(), ("RynthNav", "rnav", "stop"), "the walk stops");
|
||||
Check.False((bool)typeof(RynthAiPlugin).GetProperty("OwnCorpseTravelHoldsNav", Any)!.GetValue(bot.P)!, "travel is over");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("travel back ended: your corpse") && l.Contains("is in loot range")), "says why");
|
||||
Check.True(bot.HasLootWork(), "and looting wants the tick for it");
|
||||
|
||||
// Timeout with no progress.
|
||||
var stuck = DieAt(42.10, 33.60, broker: true);
|
||||
stuck.S.TravelToOwnCorpse = true;
|
||||
FakeHost.SetNavPosition(42.50, 33.60);
|
||||
FakeHost.Positions[Player] = FakeHost.PlayerPose;
|
||||
stuck.Call("OnRespawnedForOwnCorpse");
|
||||
stuck.Set("_activity", BotActivity.Idle);
|
||||
BackdateIdle(stuck);
|
||||
stuck.Call("TickOwnCorpseTravel", stuck.S);
|
||||
stuck.Call("TickOwnCorpseTravel", stuck.S); // first distance sample
|
||||
stuck.Set("_travelBestAt", Environment.TickCount64 - RynthAiPlugin.OwnCorpseTravelNoProgressMs - 1000);
|
||||
stuck.Call("TickOwnCorpseTravel", stuck.S);
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("travel back ended: gave up: no closer")), "no progress: gives up and says so");
|
||||
Check.Eq(FakeHost.PluginCommands.Last(), ("RynthNav", "rnav", "stop"), "and stops RynthNav");
|
||||
|
||||
// Nothing dropped: no trip.
|
||||
var none = DieAt(42.10, 33.60);
|
||||
none.Call("OnOwnCorpseChat", "You have retained all your items. You do not need to recover your corpse!"); // OnChatWindowText hands chat lines here
|
||||
none.S.TravelToOwnCorpse = true;
|
||||
none.Call("OnRespawnedForOwnCorpse");
|
||||
Check.False((bool)typeof(RynthAiPlugin).GetProperty("OwnCorpseTravelHoldsNav", Any)!.GetValue(none.P)!, "nothing dropped: no trip back");
|
||||
|
||||
// Setting off (the default): no trip.
|
||||
var off = DieAt(42.10, 33.60);
|
||||
off.Call("OnRespawnedForOwnCorpse");
|
||||
Check.False((bool)typeof(RynthAiPlugin).GetProperty("OwnCorpseTravelHoldsNav", Any)!.GetValue(off.P)!, "Travel Back off: no trip back");
|
||||
}
|
||||
|
||||
private static void TravelRefusals()
|
||||
{
|
||||
var indoor = DieAt(0, 0, cell: 0x01D90123u, broker: true);
|
||||
indoor.S.TravelToOwnCorpse = true;
|
||||
indoor.Call("OnRespawnedForOwnCorpse");
|
||||
Check.False((bool)typeof(RynthAiPlugin).GetProperty("OwnCorpseTravelHoldsNav", Any)!.GetValue(indoor.P)!, "an indoor death: no trip");
|
||||
Check.True(FakeHost.Chat.Any(l => l.Contains("you died indoors") && l.Contains("only works outdoors")), "and it says why");
|
||||
|
||||
var noNav = DieAt(42.10, 33.60, broker: true, navLoaded: false); // RynthNav not loaded
|
||||
noNav.S.TravelToOwnCorpse = true;
|
||||
FakeHost.SetNavPosition(42.50, 33.60);
|
||||
FakeHost.Positions[Player] = FakeHost.PlayerPose;
|
||||
noNav.Call("OnRespawnedForOwnCorpse");
|
||||
noNav.Set("_activity", BotActivity.Idle);
|
||||
BackdateIdle(noNav);
|
||||
noNav.Call("TickOwnCorpseTravel", noNav.S);
|
||||
Check.False((bool)typeof(RynthAiPlugin).GetProperty("OwnCorpseTravelHoldsNav", Any)!.GetValue(noNav.P)!, "RynthNav missing: the trip ends");
|
||||
Check.True(FakeHost.Chat.Any(l => l.Contains("RynthNav isn't loaded")), "and it says why");
|
||||
}
|
||||
}
|
||||
|
|
@ -24,6 +24,46 @@ internal static class VitalsTests
|
|||
r.Add("vitals: profiles without the Stamina to Health keys load today's 30 / 20", StaminaToHealthDefaults);
|
||||
r.Add("vitals: after a kit, nothing else heals until the kit's result line lands", KitResultWait);
|
||||
r.Add("vitals: low health wins the arbiter even on a busy tick; backs off when nothing can heal", HealthWinsArbiter);
|
||||
r.Add("vitals: 'You're too busy!' paces vital casts, and a long streak stops the character once", TooBusyVitals);
|
||||
// Drakkon's death, 2026-10-05 13:43:20 (ops\overnight\2026-10-05-death-fixes.md).
|
||||
r.Add("vitals: a hot reload's login refresh trusts its first read; a real login waits for two equal reads", HotReloadRefresh);
|
||||
r.Add("vitals: RynthAi tells the engine a reload is unsafe while engaged, under a heal line or casting", ReloadBlockerReport);
|
||||
}
|
||||
|
||||
// Drakkon, 2026-10-05: stuck in the cast gesture, AC answering "You're too busy!" every
|
||||
// 0.4 s. The buff path backed off; Stamina to Mana didn't, and re-cast on every
|
||||
// SpellCastIntervalMs tick until the player moved. Mana/stamina casts now wait out the
|
||||
// backoff, and a streak of refusals sends one StopCompletely (what moving did).
|
||||
private static void TooBusyVitals()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.WeaponCalls = true;
|
||||
FakeHost.StopCalls = true;
|
||||
FakeHost.CombatModeValue = CombatMode.Magic;
|
||||
foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id);
|
||||
FakeHost.Skills[(Player, STypeLife)] = (400, 2);
|
||||
var host = FakeHost.Create();
|
||||
var s = new LegacyUiSettings { IsMacroRunning = true, HealAt = 0, TopOffHP = 0, EmergencyHealAt = 0, StaminaToHealthAt = 0,
|
||||
GetManaAt = 50, TopOffMana = 50, RestamAt = 0, TopOffStam = 0, UsePotions = false };
|
||||
var skills = new CharacterSkills(host);
|
||||
skills.SetPlayerId(Player);
|
||||
var sm = new SpellManager(host, s);
|
||||
sm.InitializeNatively();
|
||||
sm.SetCharacterSkills(skills);
|
||||
var vitals = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 10 };
|
||||
var b = new BuffManager(host, s, sm, vitals);
|
||||
b.SetCharacterSkills(skills);
|
||||
|
||||
Check.True(b.CheckVitals(), "10% mana: Stamina to Mana is cast");
|
||||
Check.Eq(FakeHost.Casts.Count, 1, "one cast");
|
||||
b.OnChatWindowText("You're too busy!", 26);
|
||||
Check.True(b.CheckVitals(), "too busy: the vital tick still yields (no potion, no buff)");
|
||||
Check.Eq(FakeHost.Casts.Count, 1, "but nothing is re-cast inside the backoff");
|
||||
|
||||
for (int i = 0; i < 3; i++) b.OnChatWindowText("You're too busy!", 26);
|
||||
Check.Eq(FakeHost.Stops, 1, "4 refusals in a row: one StopCompletely to clear the stuck gesture");
|
||||
for (int i = 0; i < 4; i++) b.OnChatWindowText("You're too busy!", 26);
|
||||
Check.Eq(FakeHost.Stops, 1, "only once per streak");
|
||||
}
|
||||
|
||||
// 2026-10-04, "nav and looting have priority over healing, almost dying in packs": the
|
||||
|
|
@ -172,6 +212,80 @@ internal static class VitalsTests
|
|||
Check.False(BuffManager.StaminaToHealthAllowed(d, 31, 99), "predicate: 31 on defaults");
|
||||
}
|
||||
|
||||
private static BuffManager RefreshRig(out LegacyUiSettings s, out PlayerVitalsCache vitals, int healthPct = 100)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.WeaponCalls = true;
|
||||
FakeHost.CombatModeValue = CombatMode.Magic;
|
||||
foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id);
|
||||
FakeHost.Skills[(Player, STypeLife)] = (400, 2);
|
||||
var host = FakeHost.Create();
|
||||
s = new LegacyUiSettings { IsMacroRunning = true, HealAt = 60, TopOffHP = 60, EmergencyHealAt = 30, StaminaToHealthAt = 0,
|
||||
GetManaAt = 0, TopOffMana = 0, RestamAt = 0, TopOffStam = 0, UsePotions = false, EnableBuffing = false };
|
||||
var skills = new CharacterSkills(host);
|
||||
skills.SetPlayerId(Player);
|
||||
var sm = new SpellManager(host, s);
|
||||
sm.InitializeNatively();
|
||||
sm.SetCharacterSkills(skills);
|
||||
vitals = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = (uint)healthPct, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 };
|
||||
var b = new BuffManager(host, s, sm, vitals);
|
||||
b.SetCharacterSkills(skills);
|
||||
return b;
|
||||
}
|
||||
|
||||
// The engine reload at 13:42:55 looked like a login to RynthAi: the buff refresh waited 5.8 s
|
||||
// for two equal reads of a registry that was already complete (the client never left the world).
|
||||
private static void HotReloadRefresh()
|
||||
{
|
||||
int strength = SpellTable.Named("Strength Self I").First().Id;
|
||||
int endurance = SpellTable.Named("Endurance Self I").First().Id;
|
||||
|
||||
var b = RefreshRig(out _, out _);
|
||||
FakeHost.ServerTime = 1000;
|
||||
FakeHost.Enchantments.Add(((uint)strength, 1000 + 3600));
|
||||
FakeHost.Enchantments.Add(((uint)endurance, 1000 + 3600));
|
||||
b.CarriedOverSession = true;
|
||||
b.OnHeartbeat();
|
||||
Check.True(b.LiveBuffsReady, "hot reload: ready on the first successful read");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("login refresh ready") && l.Contains("hot reload")), "and the line says why");
|
||||
|
||||
var real = RefreshRig(out _, out _);
|
||||
FakeHost.ServerTime = 1000;
|
||||
FakeHost.Enchantments.Add(((uint)strength, 1000 + 3600));
|
||||
real.OnHeartbeat();
|
||||
Check.False(real.LiveBuffsReady, "a real login: one read isn't trusted (the registry may still be streaming)");
|
||||
System.Threading.Thread.Sleep(1100);
|
||||
real.OnHeartbeat();
|
||||
Check.True(real.LiveBuffsReady, "two equal reads a second apart: ready");
|
||||
}
|
||||
|
||||
private static void ReloadBlockerReport()
|
||||
{
|
||||
// The pure text.
|
||||
Check.Eq(ReloadSafety.Reason(false, true, "Emergency Heal At", 12, 30, "Heal Self V"), "", "macro off: never blocks a reload");
|
||||
Check.Eq(ReloadSafety.Reason(true, false, "", 100, 0, ""), "", "nothing going on: safe");
|
||||
Check.Eq(ReloadSafety.Reason(true, true, "", 100, 0, ""), "in combat (a monster engaged)", "a monster engaged");
|
||||
Check.Eq(ReloadSafety.Reason(true, false, "Emergency Heal At", 12, 30, ""), "in combat (health 12% under Emergency Heal At 30%)", "under a heal line");
|
||||
Check.Eq(ReloadSafety.Reason(true, false, "", 100, 0, "Strength Self VI"), "casting ('Strength Self VI' awaiting its result)", "a buff in flight");
|
||||
Check.Eq(ReloadSafety.Reason(true, true, "Heal At", 45, 60, "Heal Self V"),
|
||||
"in combat (a monster engaged, health 45% under Heal At 60%, 'Heal Self V' awaiting its result)", "all three");
|
||||
|
||||
// What BuffManager feeds it.
|
||||
var b = RefreshRig(out _, out var v, healthPct: 50);
|
||||
b.MarkLiveBuffsReadyForTests();
|
||||
Check.Eq(b.HealLineNow(out int hp, out int lineValue), "Top Off HP", "50% under Top Off HP (no monster: the idle line)");
|
||||
Check.Eq((hp, lineValue), (50, 60), "with the health and the line");
|
||||
Check.Eq(b.CastInFlightName, "", "nothing cast yet");
|
||||
Check.True(b.CheckVitals(), "Heal Self is cast");
|
||||
int healCat = SpellTable.Named("Heal Self I").First().Category;
|
||||
Check.True(b.CastInFlightName.Length > 0 && SpellTable.Named(b.CastInFlightName).Any(row => row.Category == healCat),
|
||||
$"the cast in flight is a Heal Self tier: {b.CastInFlightName}");
|
||||
v.CurrentHealth = 100;
|
||||
Check.Eq(b.HealLineNow(out _, out _), "", "full health: no line");
|
||||
v.MaxHealth = 0;
|
||||
Check.Eq(b.HealLineNow(out _, out _), "", "vitals not read yet: no line");
|
||||
}
|
||||
|
||||
private static void StaminaToHealthDefaults()
|
||||
{
|
||||
var old = JsonSerializer.Deserialize("{\"EmergencyHealAt\":25}", RynthAiJsonContext.Default.LegacyUiSettings);
|
||||
|
|
|
|||
|
|
@ -37,8 +37,13 @@ internal static class WeaponTests
|
|||
r.Add("element choice: a wand always casts its own element (rule, Damage tab, no match)", ChoiceWandCastsOwn);
|
||||
r.Add("element choice: elements the character can't cast are skipped", ChoiceCastable);
|
||||
r.Add("slayer: beats the weakness and the Monsters rule's damage type", SlayerBeatsWeaknessAndRule);
|
||||
r.Add("slayer: a weapon the player picked (for the monster or on the DEFAULT row) beats it", SlayerVsDamageTab);
|
||||
r.Add("slayer: other creature types, no bonus and other kinds are ignored", SlayerNonMatching);
|
||||
r.Add("slayer: only this monster's own Damage tab weapon beats it, not the DEFAULT row's", SlayerVsDamageTab);
|
||||
r.Add("slayer (owner's rule 2026-10-05): a Slash slayer beats a Pierce weapon the monster is weaker to", SlayerBeatsLowerResist);
|
||||
r.Add("slayer: this monster's own pick that is a slayer is used, labelled", SlayerManualPickIsSlayer);
|
||||
r.Add("slayer: the Damage tab's learned best never beats it", SlayerBeatsLearnedBest);
|
||||
r.Add("slayer: bonus not sent (ACE never sends float 138) still slays, ranked below a known bonus", SlayerBonusUnknown);
|
||||
r.Add("slayer: creature type from the world-database table before the monster's appraisal", SlayerTypeFromTable);
|
||||
r.Add("slayer: other creature types, an x1 bonus and other kinds are ignored", SlayerNonMatching);
|
||||
r.Add("slayer: the bigger bonus wins, then the element order, then the hand", SlayerOrder);
|
||||
r.Add("slayer: creature type unknown, the old choice", SlayerUnknownType);
|
||||
r.Add("slayer: the element follows the chosen weapon", SlayerElement);
|
||||
|
|
@ -376,12 +381,18 @@ internal static class WeaponTests
|
|||
var list = new List<WeaponCandidate> { Wand(1, "Fire"), Slayer(2, CombatMode.Magic, "Cold", Olthoi, 2.0) };
|
||||
|
||||
var pick = WeaponPlanner.Choose(list, "", weak, All, fixedWeaponId: 1, creatureType: Olthoi);
|
||||
Check.Eq(pick.WeaponId, 1, "the Damage tab's weapon for this monster is the player's pick: it wins");
|
||||
Check.Eq(pick.WeaponId, 1, "a non-slayer set on this monster's own Damage tab row: the player's pick wins");
|
||||
Check.Eq(pick.Source, "Damage tab", "source");
|
||||
Check.Eq(pick.Element, "Fire", "and casts its own element");
|
||||
|
||||
var def = WeaponPlanner.Choose(list, "", weak, All, fixedWeaponId: 1, fixedSource: "Damage tab default",
|
||||
creatureType: Olthoi, fixedIsDefault: true);
|
||||
Check.Eq(def.WeaponId, 1, "the Damage tab DEFAULT row's weapon is a player pick too: it beats a matching slayer");
|
||||
Check.Eq(def.WeaponId, 2, "the DEFAULT row's non-slayer weapon: a slayer of this monster still wins");
|
||||
Check.Eq(def.Source, "slayer (Olthoi x2)", "source");
|
||||
|
||||
var defRule = WeaponPlanner.Choose(list, "Fire", weak, All, fixedWeaponId: 1, fixedSource: "Damage tab default",
|
||||
creatureType: Olthoi, fixedIsDefault: true);
|
||||
Check.Eq(defRule.WeaponId, 2, "the DEFAULT row's weapon and a Monsters rule of Fire: still the slayer");
|
||||
|
||||
var defNoSlayer = WeaponPlanner.Choose(list, "", weak, All, fixedWeaponId: 1, fixedSource: "Damage tab default",
|
||||
creatureType: Undead, fixedIsDefault: true);
|
||||
|
|
@ -389,6 +400,109 @@ internal static class WeaponTests
|
|||
Check.Eq(defNoSlayer.Source, "Damage tab default", "source");
|
||||
}
|
||||
|
||||
private static void SlayerBeatsLowerResist()
|
||||
{
|
||||
// Owner, 2026-10-05: an Olthoi slayer that does Slash is picked before a Pierce weapon
|
||||
// even when the Olthoi resists Pierce less, because the slayer outperforms it.
|
||||
var weak = Rank(("Pierce", 0.86), ("Slash", 0.67), ("Fire", 0.65));
|
||||
var spear = new WeaponCandidate(1, "Spear", CombatMode.Melee, "Pierce", "", true);
|
||||
var list = new List<WeaponCandidate> { spear, Slayer(2, CombatMode.Melee, "Slash", Olthoi, 2.0) };
|
||||
|
||||
var p = WeaponPlanner.Choose(list, "", weak, All, creatureType: Olthoi);
|
||||
Check.Eq(p.WeaponId, 2, "the Slash Olthoi slayer, not the Pierce spear in hand");
|
||||
Check.Eq(p.Element, "Slash", "it hits with Slash");
|
||||
Check.Eq(p.Source, "slayer (Olthoi x2)", "source");
|
||||
|
||||
var r = WeaponPlanner.Choose(list, "Pierce", weak, All, creatureType: Olthoi);
|
||||
Check.Eq(r.WeaponId, 2, "a Monsters rule of Pierce: still the slayer");
|
||||
|
||||
Check.Eq(WeaponPlanner.Choose(list, "", weak, All, creatureType: Undead).WeaponId, 1,
|
||||
"not an Olthoi: the Pierce spear (weakness)");
|
||||
}
|
||||
|
||||
private static void SlayerManualPickIsSlayer()
|
||||
{
|
||||
var weak = Rank(("Fire", 1.4), ("Cold", 1.0));
|
||||
var list = new List<WeaponCandidate>
|
||||
{
|
||||
Wand(1, "Fire"),
|
||||
Slayer(2, CombatMode.Magic, "Acid", Olthoi, 3.0),
|
||||
Slayer(3, CombatMode.Magic, "Cold", Olthoi, 2.0),
|
||||
};
|
||||
var p = WeaponPlanner.Choose(list, "", weak, All, fixedWeaponId: 3, creatureType: Olthoi);
|
||||
Check.Eq(p.WeaponId, 3, "this monster's own pick is a slayer: that one, though another has a bigger bonus");
|
||||
Check.Eq(p.Element, "Cold", "its own element");
|
||||
Check.Eq(p.Source, "Damage tab, slayer (Olthoi x2)", "source names the pick and the slayer");
|
||||
|
||||
// The DEFAULT row's pick is a slayer: step 2 finds it like any listed slayer (biggest bonus first).
|
||||
var d = WeaponPlanner.Choose(list, "", weak, All, fixedWeaponId: 3, fixedSource: "Damage tab default",
|
||||
creatureType: Olthoi, fixedIsDefault: true);
|
||||
Check.Eq(d.WeaponId, 2, "DEFAULT row's slayer pick: the best slayer of the monster (x3)");
|
||||
}
|
||||
|
||||
private static void SlayerBeatsLearnedBest()
|
||||
{
|
||||
var weak = Rank(("Fire", 1.4), ("Cold", 1.0));
|
||||
var list = new List<WeaponCandidate> { Wand(1, "Fire"), Slayer(2, CombatMode.Magic, "Cold", Olthoi, 2.0) };
|
||||
Check.Eq(WeaponPlanner.Choose(list, "", weak, All, learnedBestId: 1, creatureType: Olthoi).WeaponId, 2,
|
||||
"weakness known, the learned best is the Fire wand: the slayer");
|
||||
Check.Eq(WeaponPlanner.Choose(list, "", null, All, learnedBestId: 1, creatureType: Olthoi).WeaponId, 2,
|
||||
"weakness unknown, learned best: the slayer");
|
||||
Check.Eq(WeaponPlanner.Choose(list, "", null, All, learnedBestId: 1, creatureType: 0).WeaponId, 1,
|
||||
"creature type unknown: the learned best, as before");
|
||||
|
||||
// Through CombatManager: the store's learned best (GetBestWeapon) doesn't beat a listed slayer.
|
||||
var rig = new Rig(990002, "Olthoi Learner");
|
||||
rig.S.ItemRules.Add(new() { Id = unchecked((int)FireWand), Name = "Fire Wand", Element = "Fire", ElementSource = "icon" });
|
||||
for (int i = 0; i < 4; i++) rig.Store.RecordHit(FireWand, 990002, "Olthoi Learner", "Fire", 7, 300, false);
|
||||
Check.Eq(rig.Store.GetBestWeapon(990002), FireWand, "the Damage tab learned the fire wand as best");
|
||||
rig.C.InHandOverride = () => unchecked((int)FireWand);
|
||||
FakeHost.Ints[(ListedWand, 166)] = Olthoi;
|
||||
FakeHost.Ints[(Monster, 2)] = Olthoi;
|
||||
Check.Eq(unchecked((uint)rig.C.PlanFor(rig.Target, null).WeaponId), ListedWand, "the slayer wand, not the learned best");
|
||||
}
|
||||
|
||||
private static void SlayerBonusUnknown()
|
||||
{
|
||||
var weak = Rank(("Fire", 1.4), ("Cold", 1.0));
|
||||
var unknown = Slayer(2, CombatMode.Magic, "Cold", Olthoi, 0);
|
||||
Check.True(WeaponPlanner.Slays(unknown, Olthoi), "SlayerCreatureType sent, bonus not: it slays");
|
||||
Check.False(WeaponPlanner.Slays(unknown, Undead), "not another type");
|
||||
var p = WeaponPlanner.Choose(new List<WeaponCandidate> { Wand(1, "Fire", inHand: true), unknown }, "", weak, All, creatureType: Olthoi);
|
||||
Check.Eq(p.WeaponId, 2, "the slayer with no bonus sent beats the Fire wand the monster is weak to");
|
||||
Check.Eq(p.Source, "slayer (Olthoi)", "source has no multiplier");
|
||||
|
||||
var both = new List<WeaponCandidate> { unknown, Slayer(3, CombatMode.Magic, "Acid", Olthoi, 2.0) };
|
||||
Check.Eq(WeaponPlanner.Choose(both, "", weak, All, creatureType: Olthoi).WeaponId, 3,
|
||||
"a known x2 bonus ranks above one not sent");
|
||||
var two = new List<WeaponCandidate> { Slayer(4, CombatMode.Magic, "Acid", Olthoi, 0), unknown };
|
||||
Check.Eq(WeaponPlanner.Choose(two, "", weak, All, creatureType: Olthoi).WeaponId, 2,
|
||||
"two with no bonus sent: the element order (Cold before Acid)");
|
||||
}
|
||||
|
||||
private static void SlayerTypeFromTable()
|
||||
{
|
||||
// wcid 3 "Olthoi Worker" is type 1 (Olthoi) in creature_resists.tsv. The monster isn't
|
||||
// appraised (no int 2) and the creature store doesn't know it: the table answers.
|
||||
var rig = new Rig(3, "Olthoi Worker");
|
||||
rig.S.ItemRules.Add(new() { Id = unchecked((int)FireWand), Name = "Fire Wand", Element = "Fire", ElementSource = "icon" });
|
||||
rig.C.InHandOverride = () => unchecked((int)FireWand);
|
||||
FakeHost.Ints[(ListedWand, 166)] = Olthoi; // no float 138, as ACE sends it
|
||||
Check.Eq(CreatureWeakness.TableCreatureType(3, "Olthoi Worker"), Olthoi, "table: wcid 3 is an Olthoi");
|
||||
Check.Eq(CreatureWeakness.TableCreatureType(3, "Not An Olthoi"), 0, "a custom monster reusing the wcid: no type");
|
||||
Check.Eq(rig.C.CreatureTypeOf(3, "Olthoi Worker"), Olthoi, "CreatureTypeOf falls back to the table");
|
||||
var p = rig.C.PlanFor(rig.Target, null);
|
||||
Check.Eq(unchecked((uint)p.WeaponId), ListedWand, "first sight of an Olthoi Worker: the slayer wand");
|
||||
Check.Eq(p.Source, "slayer (Olthoi)", "source");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("slays Olthoi (bonus not sent)")), "the weapon's slayer is logged");
|
||||
|
||||
// A listed slayer and a monster of unknown type: logged once, no slayer step.
|
||||
var odd = new WorldObject(unchecked((int)Monster) + 5, "Custom Thing", AcObjectClass.Monster);
|
||||
FakeHost.Wcids[Monster + 5] = 990005;
|
||||
Check.Eq(unchecked((uint)rig.C.PlanFor(odd, null).WeaponId), FireWand, "type unknown: the weakness choice");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("creature type not known yet")), "and it is logged");
|
||||
}
|
||||
|
||||
private static void SlayerNonMatching()
|
||||
{
|
||||
var weak = Rank(("Fire", 1.4), ("Cold", 1.0));
|
||||
|
|
@ -396,7 +510,6 @@ internal static class WeaponTests
|
|||
{
|
||||
Wand(1, "Fire"),
|
||||
Slayer(2, CombatMode.Magic, "Cold", Undead, 2.0), // another type
|
||||
Slayer(3, CombatMode.Magic, "Cold", Olthoi, 0), // no bonus property (ACE needs both)
|
||||
Slayer(4, CombatMode.Magic, "Cold", Olthoi, 1.0), // x1: no gain
|
||||
Slayer(5, CombatMode.Melee, "Slash", Olthoi, 3.0), // not the main kind (magic)
|
||||
};
|
||||
|
|
@ -455,6 +568,9 @@ internal static class WeaponTests
|
|||
Check.Eq(p.Source, "weak to Fire (test)", "source");
|
||||
var r = WeaponPlanner.Choose(list, "Cold", weak, All, creatureType: 0);
|
||||
Check.Eq(r.Source, "Monsters rule Cold", "and the rule as before");
|
||||
var d = WeaponPlanner.Choose(list, "", weak, All, fixedWeaponId: 1, fixedSource: "Damage tab default", creatureType: 0, fixedIsDefault: true);
|
||||
Check.Eq(d.WeaponId, 1, "type unknown and a DEFAULT row weapon: the default, as before");
|
||||
Check.Eq(d.Source, "Damage tab default", "source");
|
||||
}
|
||||
|
||||
private static void SlayerElement()
|
||||
|
|
@ -488,6 +604,9 @@ internal static class WeaponTests
|
|||
|
||||
var before = rig.C.PlanFor(rig.Target, null);
|
||||
Check.Eq(unchecked((uint)before.WeaponId), FireWand, "no slayer properties yet: the Fire wand (weakness)");
|
||||
Check.Eq(rig.C.SlayerOf(unchecked((int)ListedWand)), (0, 0.0), "no int 166: no slayer");
|
||||
FakeHost.Ints[(ListedWand, 166)] = Olthoi;
|
||||
Check.Eq(rig.C.SlayerOf(unchecked((int)ListedWand)), (Olthoi, 0.0), "int 166 alone (what ACE sends): a slayer, bonus not known");
|
||||
|
||||
FakeHost.Ints[(ListedWand, 166)] = Olthoi;
|
||||
FakeHost.Doubles[(ListedWand, 138)] = 2.0;
|
||||
|
|
|
|||
Loading…
Reference in a new issue