Snapshot for release 2026.10.12.1 (internal 8d252bd)

This commit is contained in:
Tom Bohar 2026-10-12 00:33:13 -04:00
commit 3c4f093e3d
60 changed files with 5748 additions and 602 deletions

View file

@ -285,6 +285,189 @@ public class BuffManager : IDisposable
private const double LowManaHealRestSec = 2;
private const double LowManaFamilyRestSec = 15;
// ── Mana reserve (2026-10-11) ──
// A void mage at 1/383 mana kept casting Corruption at Rampagers and never Stamina to Mana.
// Combat drained mana under what Stamina to Mana itself costs; the server refused it ("You
// don't have enough Mana"), which rested the family 15 s; no mana potion was listed, so no
// vitals flag held the arbiter, and combat spent every point that regenerated on attacks
// that were refused too. Now, for a character that fights with magic:
// - the refill line is the larger of Get Mana At (Top Off Mana idle) and ManaReserveFactor
// times the cost of the best Stamina to Mana it can cast (ManaUnderLine);
// - under it, while Stamina to Mana or a listed mana potion can refill, vitals hold the tick
// (WantsManaNow, part of WantsVitalRecharge, read every tick so combat can't take the
// tick that follows a UseDone) and combat holds its casts (OffensiveCastHold);
// - under Stamina to Mana's cost, the highest level it can pay for goes; with none, mana
// regenerates while attacks wait, and a vital refused for mana rests only LowManaHealRestSec.
// No peace-stance switch to regenerate faster: ACE's stance modifier skips mana
// (Creature.GetStanceMod returns 1.0 for MaxMana), and the switch back would cost the swap.
internal const double ManaReserveFactor = 1.5;
private const double ManaUnavailableMs = 5000;
private const double ManaRefusalMemoryMs = 5000;
private DateTime _manaUnavailableUntil = DateTime.MinValue;
private DateTime _lastManaRefusalAt = DateTime.MinValue;
private bool _manaStarvedLogged;
private int _topS2MId;
private DateTime _topS2MAt = DateTime.MinValue;
/// <summary>Tests: a spell's mana cost instead of the dat's (0 = unknown). FakeHost.Reset sets
/// it to "unknown" so tests don't depend on a portal.dat on the PC.</summary>
internal static Func<int, int>? ManaCostOverride;
/// <summary>Tests: whether a monster is within Monster Range (else CombatManager decides).</summary>
internal Func<bool>? InCombatOverride { get; set; }
private bool InCombatNow() => InCombatOverride?.Invoke()
?? _combatManager?.HasCloseThreat(System.Math.Max(1, _settings.MonsterRange)) == true;
/// <summary>
/// A spell's mana cost: its BaseMana from the portal.dat SpellTable, the most it can cost
/// (ACE Creature.CalculateManaUsage; Mana Conversion only lowers it on a skill roll, so the
/// base is the one number that is sure to be enough). No dat: an estimate from the spell's
/// level. 0 = unknown.
/// </summary>
internal static int SpellManaCost(int spellId)
{
if (spellId == 0) return 0;
if (ManaCostOverride != null) return Math.Max(0, ManaCostOverride(spellId));
if (ComponentDatabase.TryGetSpellBaseMana(spellId, out int mana)) return mana;
int level = SpellTableStub.GetById(spellId)?.Level ?? 0;
return EstimatedManaCost(level);
}
/// <summary>Retail's base mana by spell level (I 10 ... VI 50, VII 70, VIII 80; the dat can differ
/// per spell). Used only when the dat can't be read.</summary>
internal static int EstimatedManaCost(int level) => level switch
{
<= 0 => 0,
<= 7 => level * 10,
_ => 80,
};
/// <summary>The Stamina to Mana level vitals would cast now (0 = none: unknown, or Life Magic
/// not usable). Cached for a second: the arbiter asks every tick.</summary>
private int TopStaminaToManaId()
{
if ((DateTime.Now - _topS2MAt).TotalMilliseconds < 1000) return _topS2MId;
_topS2MAt = DateTime.Now;
_topS2MId = IsSkillUsable(AcSkillType.LifeMagic)
? _spellManager.GetDynamicSelfBuffId("Stamina to Mana Self", AcSkillType.LifeMagic, LevelLacksComponents)
: 0;
return _topS2MId;
}
/// <summary>The mana the reserve keeps for Stamina to Mana: ManaReserveFactor x its cost, never
/// above halfway between the cost and max mana (a small pool would refill when nearly full).
/// 0 = no reserve (no Stamina to Mana, cost unknown, or more than max mana).</summary>
internal int ManaReserve()
{
int cost = SpellManaCost(TopStaminaToManaId());
int max = (int)_vitals.MaxMana;
if (cost <= 0 || max <= 0 || cost >= max) return 0;
int reserve = (int)Math.Ceiling(cost * ManaReserveFactor);
return Math.Min(reserve, cost + (max - cost) / 2);
}
/// <summary>Combat fights with magic (CombatManager's chosen weapon is a wand; before it chose,
/// the stance). A melee character's attacks don't spend mana, so the reserve doesn't hold them.</summary>
private bool FightsWithMagic() => _combatManager?.FightsWithMagic ?? CurrentCombatMode == CombatMode.Magic;
/// <summary>Mana is under the line vitals refill at: the % line (Get Mana At in combat, Top Off
/// Mana idle; 0 = off) or, for a caster, the reserve. <paramref name="line"/>: the line in points.</summary>
internal bool ManaUnderLine(bool inCombat, out int line)
{
line = 0;
int pctLine = inCombat ? _settings.GetManaAt : _settings.TopOffMana;
int max = (int)_vitals.MaxMana;
if (pctLine <= 0 || max <= 0) return false;
line = (int)Math.Ceiling(max * pctLine / 100.0);
bool under = _vitals.ManaPct < pctLine;
if (FightsWithMagic())
{
int reserve = ManaReserve();
if (reserve > line) line = reserve;
if (reserve > 0 && _vitals.CurrentMana < reserve) under = true;
}
return under;
}
/// <summary>Stamina to Mana (not parked by a hard refusal; the short rest after a mana refusal
/// doesn't count) or a listed mana potion can refill mana.</summary>
private bool ManaRefillPossible()
{
if (_settings.UsePotions && HasListedPotion("ManaPotion")) return true;
int id = TopStaminaToManaId();
if (id == 0 || !StaminaAllowsStaminaToMana()) return false;
int family = SpellTableStub.GetById(id)?.Family ?? 0;
return !(family != 0 && _buffFailCooldownUntil.TryGetValue(family, out DateTime until)
&& (until - DateTime.Now).TotalSeconds > LowManaHealRestSec);
}
/// <summary>Stamina lets Stamina to Mana go: over 15%, or a stamina kit or listed stamina potion
/// can bring it there. Not Revitalize: it costs mana itself, and trading mana for stamina and
/// back while attacks wait could keep a caster from attacking for minutes.</summary>
private bool StaminaAllowsStaminaToMana() => _vitals.StaminaPct > 15
|| BestPackStaminaKit() != null
|| (_settings.UsePotions && HasListedPotion("StaminaPotion", "Stamina"));
/// <summary>
/// Mana can't pay for Stamina to Mana: under the cost of its lowest known level when costs are
/// known (the highest level it can pay for is cast first, see AttemptVitalCast), or refused
/// for mana in the last ManaRefusalMemoryMs when they aren't.
/// </summary>
internal bool ManaStarved(out int cost, out string spellName)
{
int id = TopStaminaToManaId();
cost = SpellManaCost(id);
spellName = id != 0 ? SpellTableStub.GetById(id)?.Name ?? "Stamina to Mana" : "Stamina to Mana";
if (id == 0 || _vitals.MaxMana == 0) return false;
if (cost > 0) return _vitals.CurrentMana < cost && AffordableVitalId("Stamina to Mana Self") == 0;
return (DateTime.Now - _lastManaRefusalAt).TotalMilliseconds < ManaRefusalMemoryMs;
}
/// <summary>The highest level of a vital spell whose known cost current mana can pay (a level
/// with an unknown cost counts as payable). 0 = none.</summary>
private int AffordableVitalId(string baseName)
{
uint cur = _vitals.CurrentMana;
return _spellManager.GetDynamicSelfBuffId(baseName, AcSkillType.LifeMagic,
id => LevelLacksComponents(id) || SpellManaCost(id) > cur);
}
/// <summary>
/// In combat, a caster's mana under the refill line with something able to refill it (now, or
/// once mana regenerates to Stamina to Mana's cost): vitals want the tick. Read by
/// WantsVitalRecharge every tick, like WantsHealNow, so it doesn't depend on CheckVitals having
/// run (it doesn't while a gesture animates or the client is busy). Backs off ManaUnavailableMs
/// after a check that found nothing able to refill.
/// </summary>
internal bool WantsManaNow()
{
if (!_settings.IsMacroRunning || _vitals.MaxMana == 0) return false;
if (DateTime.Now < _manaUnavailableUntil) return false;
if (!InCombatNow() || !FightsWithMagic()) return false;
return ManaUnderLine(true, out _) && ManaRefillPossible();
}
/// <summary>
/// For CombatManager, before an attack or debuff cast: a reason to hold it, or null. Held when
/// mana is under the spell's own cost (it would be refused), or under the refill line while
/// vitals can refill it (Stamina to Mana goes first).
/// </summary>
internal string? OffensiveCastHold(int spellId)
{
if (!_settings.IsMacroRunning || _vitals.MaxMana == 0) return null;
uint cur = _vitals.CurrentMana;
int cost = SpellManaCost(spellId);
if (cost > 0 && cur < cost)
return $"mana {cur}/{_vitals.MaxMana} is under {SpellTableStub.GetById(spellId)?.Name ?? "the spell"}'s cost ({cost})";
if (WantsManaNow())
{
ManaUnderLine(true, out int line);
return $"mana {cur}/{_vitals.MaxMana} is under the reserve ({line}): Stamina to Mana goes first";
}
return null;
}
private readonly Dictionary<int, DateTime> _castIssuedAtByFamily = new();
private readonly Dictionary<int, DateTime> _expiryAtCastByFamily = new();
private const double AuditSettleMs = 15_000.0;
@ -669,7 +852,7 @@ public class BuffManager : IDisposable
/// and they need the same mid-cast protection a buff gets. Side-effect free:
/// CheckVitals repopulates these flags every cycle it reaches.
/// </summary>
public bool WantsVitalRecharge => _isHealingSelf || _isRechargingMana || _isRechargingStamina || WantsHealNow();
public bool WantsVitalRecharge => _isHealingSelf || _isRechargingMana || _isRechargingStamina || WantsHealNow() || WantsManaNow();
// Health below a heal line wins the arbiter's tick by itself. The flags above are only set on
// a tick where CheckVitals actually ran and acted, and it doesn't run while the client is busy
@ -751,7 +934,7 @@ public class BuffManager : IDisposable
return _kitIsStamina ? LabelStamina : LabelHealing;
if (_isHealingSelf || WantsHealNow()) return LabelHealing;
if (_pendingSpellId != 0) return LabelBuffing;
if (_isRechargingMana) return LabelMana;
if (_isRechargingMana || WantsManaNow()) return LabelMana;
if (_isRechargingStamina) return LabelStamina;
return LabelBuffing;
}
@ -1450,7 +1633,7 @@ public class BuffManager : IDisposable
// Otherwise idle → top up to the HIGH (TopOffHP / TopOffStam /
// TopOffMana) thresholds so we re-engage at full. Thresholds are
// strict "<": set a value to 0 to disable that vital in that mode.
bool inCombat = _combatManager?.HasCloseThreat(System.Math.Max(1, _settings.MonsterRange)) == true;
bool inCombat = InCombatNow();
int hpThreshold = inCombat ? _settings.HealAt : _settings.TopOffHP;
int manaThreshold = inCombat ? _settings.GetManaAt : _settings.TopOffMana;
int stamThreshold = StaminaLine(inCombat, curStamPct, _settings, ref _restamRun, ref _restamRunCasts);
@ -1501,12 +1684,44 @@ public class BuffManager : IDisposable
if (HealthUnderAnyLine(curHealthPct, curStamPct))
_healUnavailableUntil = DateTime.Now.AddMilliseconds(HealUnavailableMs);
if (curManaPct < manaThreshold
&& ((curStamPct > 15 && AttemptVitalCast("Stamina to Mana Self")) || AttemptPotion("ManaPotion")))
// Mana: under Get Mana At / Top Off Mana, or (a caster) under the reserve kept for Stamina
// to Mana (ManaUnderLine; see "Mana reserve" at the top).
bool manaLow = curManaPct < manaThreshold || ManaUnderLine(inCombat, out _);
if (manaLow)
{
_isRechargingMana = true;
return true;
_vitalWhy = "";
if ((curStamPct > 15 && AttemptVitalCast("Stamina to Mana Self")) || AttemptPotion("ManaPotion"))
{
_isRechargingMana = true;
return true;
}
// Stamina too low for Stamina to Mana: a stamina kit, Revitalize or a potion first,
// whatever Re-stam At says (it may be under 15 or off).
if (curStamPct <= 15 && TopStaminaToManaId() != 0
&& (AttemptStaminaKitUse() || AttemptVitalCast("Revitalize Self") || AttemptPotion("StaminaPotion", "Stamina")))
{
_isRechargingStamina = true;
return true;
}
// Mana can't pay for any Stamina to Mana and nothing else refilled it: a caster's
// attacks wait while it regenerates (WantsManaNow holds the arbiter, OffensiveCastHold
// the casts), then Stamina to Mana goes. Not for a melee fighter: its attacks cost none.
if (FightsWithMagic() && ManaStarved(out int s2mCost, out string s2mName))
{
_isRechargingMana = true;
Hold("mana regenerating", $"mana {_vitals.CurrentMana}/{_vitals.MaxMana}, {s2mName} costs {s2mCost}");
if (!_manaStarvedLogged)
{
_manaStarvedLogged = true;
string costText = s2mCost > 0 ? $"under {s2mName}'s cost ({s2mCost})" : $"too low for {s2mName} (refused for mana)";
_host.Log($"[RynthAi] Vitals: mana {_vitals.CurrentMana}/{_vitals.MaxMana} is {costText}: attacks wait, regenerating.");
}
return true;
}
// Nothing can refill it (no Stamina to Mana, parked, no potion): don't hold the bot for it.
if (inCombat) _manaUnavailableUntil = DateTime.Now.AddMilliseconds(ManaUnavailableMs);
}
else _manaStarvedLogged = false;
// Stamina kits first, like healing kits for health: Lucy carried Greater Stamina Kits
// and cast Revitalize/Robustification instead, because stamina never looked for a kit.
// Melee first (Tom, 2026-10-06): out of Magic stance, Revitalize means switching the weapon
@ -1664,6 +1879,22 @@ public class BuffManager : IDisposable
}
}
if (spellId == 0) return VitalNo($"no known '{baseName}' spell at the allowed tiers");
// Stamina to Mana / Revitalize under their cost (the mana reserve, 2026-10-11): the server
// would refuse it. The highest level mana can pay for goes instead; with none, not handled
// (a potion gets its turn, or mana regenerates - CheckVitals). Mana Conversion can lower a
// cost only on a skill roll, so the base cost is the line. A heal still tries: it falls to
// its potion within LowManaHealRestSec if refused.
if (baseName is not ("Heal Self" or "Stamina to Health Self") && _vitals.MaxMana > 0)
{
int cost = SpellManaCost(spellId);
if (cost > 0 && _vitals.CurrentMana < cost)
{
int payable = AffordableVitalId(baseName);
if (payable == 0)
return VitalNo($"mana {_vitals.CurrentMana} is under {SpellTableStub.GetById(spellId)?.Name ?? baseName}'s cost ({cost})");
spellId = payable;
}
}
// Parked after a hard server refusal (see OnChatWindowText) — the same
// per-family cooldown the buff selectors honour.
int family = SpellTableStub.GetById(spellId)?.Family ?? 0;
@ -1697,6 +1928,7 @@ public class BuffManager : IDisposable
return VitalNo($"the client refused the cast (spell {spellId})");
}
NoteCastIssued(spellId);
if (_pendingVitalLabel == LabelMana) _manaStarvedLogged = false; // the next starved spell logs again
if (_pendingVitalLabel == LabelHealing)
{
_healSpellIds.Add(spellId);
@ -2140,6 +2372,21 @@ public class BuffManager : IDisposable
return false;
}
// "[FR] skip ..." lines while a rebuff runs: the selector runs every tick (~30 ms), and a
// parked buff logged on each one - 47,000 lines in 10 minutes on 2026-10-11, so the log
// rotated every few minutes and held nothing from before. Once per buff and reason a minute.
private readonly Dictionary<string, DateTime> _diagSkipLoggedAt = new();
private void DiagSkip(string buff, string line)
{
int cut = line.IndexOf(" — ", StringComparison.Ordinal);
string reason = cut >= 0 ? line.Substring(cut, Math.Min(18, line.Length - cut)) : line;
string key = buff + "|" + reason;
DateTime now = DateTime.Now;
if (_diagSkipLoggedAt.TryGetValue(key, out DateTime at) && (now - at).TotalSeconds < 60) return;
_diagSkipLoggedAt[key] = now;
_host.Log(line);
}
private bool CheckAndCastSelfBuffs()
{
// Auto batch-rebuff: when any buff drops below the configured threshold,
@ -2172,7 +2419,7 @@ public class BuffManager : IDisposable
if (!IsSkillUsable(castSkill))
{
LastBuffSkipReason = $"skill not usable: {buffBaseName} ({castSkill})";
if (diagnose) _host.Log($"[FR] skip '{buffBaseName}' — skill {castSkill} not usable");
if (diagnose) DiagSkip(buffBaseName, $"[FR] skip '{buffBaseName}' — skill {castSkill} not usable");
continue;
}
@ -2180,14 +2427,14 @@ public class BuffManager : IDisposable
if (spellId == 0)
{
LastBuffSkipReason = $"not known / unresolvable: {buffBaseName}";
if (diagnose) _host.Log($"[FR] skip '{buffBaseName}' — FindBestSpellId returned 0");
if (diagnose) DiagSkip(buffBaseName, $"[FR] skip '{buffBaseName}' — FindBestSpellId returned 0");
continue;
}
if (IsBuffActive(spellId))
{
LastBuffSkipReason = $"already active: {buffBaseName} (id={spellId})";
if (diagnose) _host.Log($"[FR] skip '{buffBaseName}' (id={spellId}) — already active");
if (diagnose) DiagSkip(buffBaseName, $"[FR] skip '{buffBaseName}' (id={spellId}) — already active");
continue;
}
@ -2200,7 +2447,7 @@ public class BuffManager : IDisposable
&& DateTime.Now < coolUntil)
{
LastBuffSkipReason = $"fail-cooldown: {buffBaseName} (fam={buffFamily}, {(coolUntil - DateTime.Now).TotalSeconds:0}s)";
if (diagnose) _host.Log($"[FR] skip '{buffBaseName}' (id={spellId}) — hard-fail cooldown {(coolUntil - DateTime.Now).TotalSeconds:0}s");
if (diagnose) DiagSkip(buffBaseName, $"[FR] skip '{buffBaseName}' (id={spellId}) — hard-fail cooldown {(coolUntil - DateTime.Now).TotalSeconds:0}s");
continue;
}
@ -3395,6 +3642,7 @@ public class BuffManager : IDisposable
if (lower.Contains("enough mana"))
{
_cast.Result(null, "not enough mana", atStart: true);
_lastManaRefusalAt = DateTime.Now; // a combat cast's refusal too: ManaStarved with costs unknown
if (_pendingSpellId == 0) return;
var pendingSpell = SpellTableStub.GetById(_pendingSpellId);
double restSec = LowManaFamilyRestSec;
@ -3405,11 +3653,13 @@ public class BuffManager : IDisposable
_itemSpellTimers.Remove(pendingSpell.Family);
SaveBuffTimers();
}
// A heal rests only LowManaHealRestSec (2026-10-05): long enough for the mana step
// after it to cast Stamina to Mana or drink, not 15 s with no Heal Self after the
// mana was back (a mage low on mana mid-fight).
bool healSpell = _pendingSpellId == _pendingVitalSpellId && _pendingVitalLabel == LabelHealing;
restSec = healSpell ? LowManaHealRestSec : LowManaFamilyRestSec;
// A vital rests only LowManaHealRestSec. A heal (2026-10-05): long enough for the
// mana step after it to cast Stamina to Mana or drink, not 15 s with no Heal Self
// after the mana was back. Stamina to Mana and Revitalize (2026-10-11): 15 s parked
// the only thing that refills mana, and combat spent what regenerated meanwhile; now
// mana regenerates to its cost while attacks wait (the mana reserve), then it goes.
bool vitalSpell = _pendingSpellId == _pendingVitalSpellId;
restSec = vitalSpell ? LowManaHealRestSec : LowManaFamilyRestSec;
_buffFailCooldownUntil[pendingSpell.Family] = DateTime.Now.AddSeconds(restSec);
}
_host.Log($"[BuffChat] CLEARED pending={_pendingSpellId} - not enough mana; resting the family {restSec:0}s, buffs {LowManaBuffPauseMs / 1000:0}s.");

View file

@ -290,6 +290,45 @@ public partial class CombatManager : IDisposable
public Func<bool>? HoldIdlePeace { get; set; }
private bool _idlePeaceHeldLogged;
/// <summary>
/// RynthAi's mana reserve (BuffManager.OffensiveCastHold): given the attack or debuff spell
/// about to be cast, a reason to hold it (mana under its cost, or under the reserve kept for
/// Stamina to Mana), or null to cast. Null hook = never hold (2026-10-11).
/// </summary>
public Func<int, string?>? ManaReserveHold { get; set; }
private bool _manaCastHeld; // AttackWithMagic held its cast for mana this tick
private bool _manaHoldLogged;
// The kind of weapon EquipWeaponAndSetStance last chose (a CombatMode), -1 before it chose.
private int _chosenWeaponMode = -1;
/// <summary>Combat fights with magic: its chosen weapon is a wand (before it chose, the stance).
/// BuffManager's mana reserve holds only a caster's attacks.</summary>
public bool FightsWithMagic => _chosenWeaponMode >= 0
? _chosenWeaponMode == CombatMode.Magic
: CurrentCombatMode == CombatMode.Magic;
/// <summary>True (and logged once per hold) when the mana reserve holds this cast.</summary>
private bool ManaHoldsCast(int spellId)
{
string? why = null;
try { why = ManaReserveHold?.Invoke(spellId); } catch { why = null; }
if (why == null)
{
if (_manaHoldLogged) _host.Log("[CombatCast] mana is back: attacks resume");
_manaHoldLogged = false;
return false;
}
_manaCastHeld = true;
LastCombatSkipReason = "mana-reserve"; // D4 record-only
if (!_manaHoldLogged)
{
_manaHoldLogged = true;
_host.Log($"[CombatCast] attacks wait: {why}");
}
return true;
}
/// <summary>Current combat mode — read live from AC client each access to avoid event-drop drift.</summary>
public int CurrentCombatMode =>
_host.HasGetCurrentCombatMode ? _host.GetCurrentCombatMode() : CombatMode.NonCombat;
@ -434,6 +473,18 @@ public partial class CombatManager : IDisposable
string Name, uint Wcid, int CastCount, uint WeaponId, string Element, int Tier, double Damage, DateTime Expiry,
DateTime Started = default, string? Summon = null, int Id = 0);
// Predicted kills that never happened (player log, 2026-10-11): two Rampagers side by side,
// each cast landing nothing. The casts-to-kill average said one Nether Arc kills a Rampager, so
// every cast#1 was a "predicted kill" and the bot swapped to the other one, and back, for 30
// minutes (~460 swaps, 533 casts since the last kill). Each swap drops the target, which wipes
// the no-damage judge (DropTarget clears the miss streak and the pending verdict, and a new
// target restarts the streak), so the NO DAMAGE report, the flight recorder and the blacklist
// never ran. A monster we swapped off as dead that is fought again is alive: the prediction
// was wrong, so no more predicted swaps off it — the bot stays on it and the judge can count.
private readonly Dictionary<int, DateTime> _predictedSwapAt = new(); // id -> when we swapped off it as a predicted kill
private readonly Dictionary<int, DateTime> _predictionFailedAt = new(); // id -> when it turned out alive: never predicted again
private const double PredictionMemoryMs = 10 * 60_000; // both forget after 10 min
// Ring of recently-fought objects (by id). The single _lastFight* slot only credits a kill
// that lands one-back; when we've advanced PAST the dying mob (rapid multi-mob melee) its
// death message matches neither the current target nor _lastFight, and the kill is lost
@ -866,7 +917,8 @@ public partial class CombatManager : IDisposable
if (!string.IsNullOrEmpty(wo.Name) && _seenMonsterNameToWcid.Count < 256
&& !_seenMonsterNameToWcid.ContainsKey(wo.Name)
&& (!_host.HasObjectIsAttackable || _host.ObjectIsAttackable((uint)wo.Id))
&& _host.HasGetObjectWcid && _host.TryGetObjectWcid((uint)wo.Id, out uint scanWcid) && scanWcid != 0)
&& _host.HasGetObjectWcid && _host.TryGetObjectWcid((uint)wo.Id, out uint scanWcid) && scanWcid != 0
&& !CreatureData.PlayerWeenies.IsPlayerWcid(scanWcid)) // players the cache classed as monsters
_seenMonsterNameToWcid[wo.Name] = scanWcid;
// Allow the currently-engaged target out to DisengageDistance: AC's
@ -1612,8 +1664,92 @@ public partial class CombatManager : IDisposable
_lastSpellCast = DateTime.Now;
}
// ── Position re-sync after casts that land nothing (2026-10-12) ──────────────────────────
// Flight 63260: after a stray stop burst rode with a cast, every projectile cast (Corruption
// VII, Nether Arc VII) was answered - components burned, UseDone - and nothing landed, until a
// real sidestep (12:32:13) ended it. ACE launches projectiles from the caster's SERVER physics
// position and drops a spawn that fails or collides at once without a word; it re-syncs that
// position only when a reported position differs from the last one (Player_Tick
// UpdatePlayerPosition), and standing still reports the same spot. So after
// ResyncAfterMagicMisses magic casts in a row with no damage (any target: swaps between two
// monsters don't reset it), RynthAi takes one short real sidestep - a movement key down and
// up through the client (MoveToState + AutonomousPositions), alternating sides - once the
// server has answered the last cast, and casts nothing until it is done. At most once per
// ResyncCooldownMs.
internal const int ResyncAfterMagicMisses = 3;
internal const double ResyncStepMs = 300;
internal const double ResyncSettleMs = 400;
internal const double ResyncCooldownMs = 30_000;
private const uint MotionSideStepRight = 0x6500000F;
private const uint MotionSideStepLeft = 0x65000010;
private int _magicMissesSinceHit;
private int _resyncState; // 0 idle, 1 wanted, 2 stepping, 3 settling
private DateTime _resyncAt = DateTime.MinValue;
private DateTime _lastResyncAt = DateTime.MinValue;
private uint _resyncMotion;
private bool _resyncLeftNext;
internal int ResyncSteps { get; private set; }
internal bool ResyncActive => _resyncState != 0;
private void NoteMagicMissForResync(int tid)
{
_magicMissesSinceHit++;
if (_resyncState != 0 || _magicMissesSinceHit < ResyncAfterMagicMisses) return;
DateTime now = TargetClock();
if (_lastResyncAt != DateTime.MinValue && (now - _lastResyncAt).TotalMilliseconds < ResyncCooldownMs) return;
if (!_host.HasSetMotion) return;
_resyncState = 1;
_resyncAt = now;
_host.Log($"[CombatCast] {_magicMissesSinceHit} magic casts in a row landed nothing (last at 0x{(uint)tid:X8}) - " +
"one short sidestep to re-sync the server's copy of our position before the next cast");
}
/// <summary>
/// The re-sync sidestep, one step per call (Think, before a cast). True while it runs: no cast.
/// Starts only when no server action is unanswered and the character isn't animating.
/// </summary>
internal bool TickResyncStep()
{
if (_resyncState == 0) return false;
DateTime now = TargetClock();
switch (_resyncState)
{
case 1:
if (ActionPacer.Enabled
&& (ActionPacer.Current(_host) != null || ActionPacer.GestureHolds(_host, "Combat/Resync", HealNeed.None, out _)))
{
if ((now - _resyncAt).TotalMilliseconds > 10_000) { _resyncState = 0; _host.Log("[CombatCast] re-sync sidestep given up: the server never went idle"); }
return true;
}
_resyncMotion = _resyncLeftNext ? MotionSideStepLeft : MotionSideStepRight;
_resyncLeftNext = !_resyncLeftNext;
if (!_host.SetMotionBy("Combat/Resync", _resyncMotion, true)) { _resyncState = 0; return false; }
_resyncState = 2;
_resyncAt = now;
return true;
case 2:
if ((now - _resyncAt).TotalMilliseconds < ResyncStepMs) return true;
_host.SetMotionBy("Combat/Resync", _resyncMotion, false);
_resyncState = 3;
_resyncAt = now;
return true;
default:
if ((now - _resyncAt).TotalMilliseconds < ResyncSettleMs) return true;
_resyncState = 0;
_lastResyncAt = now;
_magicMissesSinceHit = 0;
ResyncSteps++;
_host.Log("[CombatCast] re-sync sidestep done");
return false;
}
}
/// <summary>Test seam: one judged magic cast with no damage.</summary>
internal void MagicMissForTest(int tid) => NoteMagicMissForResync(tid);
public void ReportDamageOnTarget(int targetId)
{
_magicMissesSinceHit = 0; // something we cast landed: the server's position is fine
// Damage / health change on the cast we're judging → that cast HIT.
if (targetId == _pendingJudgeTargetId)
_damageSincePendingCast = true;
@ -1744,6 +1880,44 @@ public partial class CombatManager : IDisposable
private DateTime _lastNoDamageReportAt = DateTime.MinValue;
private const double NoDamageReportGapMs = 10 * 60_000; // one report per 10 min per client
// ── What the server said about each combat cast (2026-10-11) ─────────────────────────────
// A player log with 30 minutes of casts that landed nothing could not show what the server
// answered: chat is logged only while a buff is pending ([BuffChat]), never around an attack or
// debuff cast. A resist, a fizzle, an out-of-range or a silent nothing all looked the same.
// Now every combat cast logs the lines that arrive within CastChatTraceMs of its send (the
// incantation, the hit or resist, components, refusals), capped per cast; the monsters'
// swings at us and our evades of them are left out.
private int _castTraceSpellId;
private int _castTraceTargetId;
private DateTime _castTraceAt = DateTime.MinValue;
private int _castTraceLines;
private const double CastChatTraceMs = 4000;
private const int CastChatTraceMaxLines = 8;
internal void StartCastChatTrace(int spellId, int targetId)
{
_castTraceSpellId = spellId;
_castTraceTargetId = targetId;
_castTraceAt = TargetClock();
_castTraceLines = 0;
}
/// <summary>Every chat line goes through here (RynthAiPlugin.OnChatWindowText); logs it when a
/// combat cast went out in the last <see cref="CastChatTraceMs"/>.</summary>
internal void TraceCastChat(string? text, int chatType)
{
if (_castTraceAt == DateTime.MinValue || string.IsNullOrEmpty(text)) return;
double ms = (TargetClock() - _castTraceAt).TotalMilliseconds;
if (ms > CastChatTraceMs) { _castTraceAt = DateTime.MinValue; return; }
if (_castTraceLines >= CastChatTraceMaxLines) return;
string line = text.Trim();
if (line.StartsWith("You evaded ", StringComparison.Ordinal)) return; // their swing, our evade
if (!line.StartsWith("You ", StringComparison.Ordinal) && IncomingDamage.IsMatch(line)) return; // their hit on us
_castTraceLines++;
string spell = SpellTableStub.GetById(_castTraceSpellId)?.Name ?? $"spell {_castTraceSpellId}";
_host.Log($"[CombatChat] +{ms:0} ms after '{spell}' at 0x{(uint)_castTraceTargetId:X8}: type={chatType} '{line}'");
}
private void ReportNoDamageCasts(int tid)
{
DateTime now = DateTime.Now;
@ -1775,8 +1949,9 @@ public partial class CombatManager : IDisposable
bool hit = _damageSincePendingCast;
_pendingJudgeCastAt = DateTime.MinValue;
if (hit) { _consecutiveCastMisses = 0; return; }
if (hit) { _consecutiveCastMisses = 0; _magicMissesSinceHit = 0; return; }
if (CurrentCombatMode == CombatMode.Magic) NoteMagicMissForResync(tid);
_consecutiveCastMisses++;
if (_consecutiveCastMisses >= _settings.BlacklistAttempts)
{
@ -1933,6 +2108,7 @@ public partial class CombatManager : IDisposable
_recentlyKilled[swapId] = DateTime.Now.AddMilliseconds(PREDICTED_SWAP_SUPPRESS_MS);
ForgetScanned(swapId);
_predictedSwapAt[swapId] = TargetClock(); // fought again later = it didn't die (PredictionFailed)
// Queue this predicted one-shot so it's CREDITED when its death confirms —
// we may swap away before its KillerNotification. Capture the name LIVE
// from the world filter (_fightTargetName is often empty this early).
@ -2349,6 +2525,7 @@ public partial class CombatManager : IDisposable
_predictKillSwap = false;
if (isRing || _damageStore == null || _fightTargetWcid == 0) return;
if (activeTargetId == 0 || activeTargetId != _fightTargetId) return;
if (PredictionFailed(activeTargetId)) return; // survived a predicted kill — stay on it
if (!HasAlternateTarget(activeTargetId)) return; // nothing to swap to — keep casting
// (A) Casts-to-kill: we've fired the number of casts this wcid typically
@ -2387,6 +2564,56 @@ public partial class CombatManager : IDisposable
return false;
}
/// <summary>
/// True when <paramref name="id"/> survived a predicted kill: we swapped off it as dead and are
/// now casting at it again (the kill-notice match is by name only, so being fought again is the
/// one sure sign). Logs once when that is first seen. Called after each cast at the fight target.
/// </summary>
private bool PredictionFailed(int id)
{
DateTime now = TargetClock();
if (_predictionFailedAt.Count > 0 || _predictedSwapAt.Count > 0)
{
PruneOlderThan(_predictionFailedAt, now);
PruneOlderThan(_predictedSwapAt, now);
}
if (_predictionFailedAt.ContainsKey(id)) return true;
if (!_predictedSwapAt.TryGetValue(id, out DateTime swappedAt)) return false;
_predictedSwapAt.Remove(id);
_predictionFailedAt[id] = now;
float hp = _worldFilter.GetHealthRatio(id);
string health = hp >= 0f ? $"health {hp * 100f:0}%" : "health unknown";
_host.Log($"[RynthAi] Predicted kill of 0x{(uint)id:X8} '{_worldFilter[id]?.Name}' didn't happen: fought again " +
$"{(now - swappedAt).TotalSeconds:0.0} s after the swap ({health}, dealt~{_fightDamage:0} this fight). " +
"No more predicted swaps off it, so its casts are judged for damage.");
return true;
}
private static void PruneOlderThan(Dictionary<int, DateTime> map, DateTime now)
{
List<int>? old = null;
foreach (var kv in map)
if ((now - kv.Value).TotalMilliseconds > PredictionMemoryMs) (old ??= new()).Add(kv.Key);
if (old != null) foreach (int k in old) map.Remove(k);
}
/// <summary>Test seam: a cast at the fight target, then the kill-shot decision (as AttackWithMagic does).</summary>
internal bool CastAndPredictForTest(uint weaponId, string element, int tier)
{
_fightCastCount++;
_lastCastWeaponId = weaponId;
_lastCastElement = element;
_lastCastTier = tier;
EvaluateKillShot(weaponId, element, tier, isRing: false);
bool predicted = _predictKillSwap;
_predictKillSwap = false;
return predicted;
}
/// <summary>Test seam: the confirmed predicted-kill swap off the fight target.</summary>
internal void PredictedSwapForTest() => ExecuteDeferredKillSwap();
/// <summary>Floor between attack commands for the first cast at a new target when the server
/// gates are available (see <see cref="AttackIntervalMs"/>). Only bounds how fast a refused
/// cast could be retried; a refusal sets the target as the last attacked, so the retry waits
@ -2784,6 +3011,15 @@ public partial class CombatManager : IDisposable
return true;
}
// Casts landing nothing: one short real sidestep re-syncs the server's copy of our
// position (TickResyncStep, 2026-10-12); nothing is cast while it runs.
if (CurrentCombatMode == CombatMode.Magic && TickResyncStep())
{
LastCombatSkipReason = "position-resync";
_tickWait = CombatLatencyTracker.Wait.Cast;
return true;
}
// MAGIC and MISSILE: the server turns the player to the target itself,
// as retail did — ACE Rotate(target) before a targeted cast (and again
// after the windup if needed) and before the first missile shot and
@ -2897,6 +3133,13 @@ public partial class CombatManager : IDisposable
_tickWait = CombatLatencyTracker.Wait.Face;
return true;
}
// Held for mana (the reserve, or under the spell's cost): nothing was sent, so
// it isn't an attack either; the next tick asks again.
if (_manaCastHeld)
{
_tickWait = CombatLatencyTracker.Wait.Cast;
return true;
}
// Don't restore the physical weapon on top of a cast just issued this tick
// (AttackWithMagic → MarkCombatCastIssued): the UseObject + re-equip below would
@ -4124,6 +4367,7 @@ public partial class CombatManager : IDisposable
int desiredMode = IsWandObject(weaponObj) ? CombatMode.Magic
: weaponObj.ObjectClass == AcObjectClass.MissileWeapon ? CombatMode.Missile
: CombatMode.Melee;
_chosenWeaponMode = desiredMode;
bool diagNow = (DateTime.Now - _lastEquipDiagAt).TotalSeconds > 5;
@ -5054,6 +5298,7 @@ public partial class CombatManager : IDisposable
private void AttackWithMagic(WorldObject target)
{
_wallFaceHeld = false;
_manaCastHeld = false;
if (_spellManager == null || target == null) return;
// Hard safety veto: never cast offensive magic at something AC's combat
@ -5133,11 +5378,13 @@ public partial class CombatManager : IDisposable
spellId = FindBestDebuffSpellWithTier(debuffKey, out castTier);
if (spellId == 0) continue;
if (ManaHoldsCast(spellId)) return; // mana reserve: Stamina to Mana first, or regenerate
try
{
_host.CastSpellFor((uint)activeTargetId, spellId, "Combat", SpellTableStub.GetById(spellId)?.Name ?? $"spell {spellId}");
MarkCombatCastIssued();
StartCastChatTrace(spellId, activeTargetId);
_lastSpellCast = DateTime.Now;
_lastCastWasRing = false;
_pendingDebuffKey = debuffKey;
@ -5189,6 +5436,7 @@ public partial class CombatManager : IDisposable
}
// A ring or a wall hits several monsters: its damage isn't the fight target's alone.
bool multiTarget = isRing || castShape == ShapeWall;
if (offensiveSpellId != 0 && ManaHoldsCast(offensiveSpellId)) return; // mana reserve
if (offensiveSpellId != 0)
{
LastCombatSkipReason = "cast"; // D4 record-only: offensive cast issued this tick
@ -5202,6 +5450,7 @@ public partial class CombatManager : IDisposable
{
_host.CastSpellFor((uint)activeTargetId, offensiveSpellId, "Combat", SpellTableStub.GetById(offensiveSpellId)?.Name ?? $"spell {offensiveSpellId}");
MarkCombatCastIssued();
StartCastChatTrace(offensiveSpellId, activeTargetId);
SessionAttackCasts++; // D6: offensive attack-cast tally for the casts-per-kill signal
CastsSinceLastKill++; // reset in OnKillNotification when a kill lands
_lastSpellCast = DateTime.Now;

View file

@ -97,6 +97,18 @@ internal static class ComponentDatabase
return false;
}
// spellId → BaseMana from the same SpellTable pass: the most a cast can cost (ACE
// Creature.CalculateManaUsage starts from it; Mana Conversion only lowers it on a roll).
private static readonly Dictionary<int, int> _spellBaseMana = new();
/// <summary>A spell's base mana cost from the portal.dat SpellTable. False when the dat
/// couldn't be read or the spell isn't in it.</summary>
public static bool TryGetSpellBaseMana(int spellId, out int mana)
{
EnsureLoaded();
return _spellBaseMana.TryGetValue(spellId, out mana) && mana > 0;
}
private static bool _loaded;
private static readonly object _lock = new();
private static Action<string>? _log;
@ -339,15 +351,16 @@ internal static class ComponentDatabase
{
if (r.BaseStream.Position + 4 > raw.Length) break;
uint spellId = r.ReadUInt32();
uint[] comps = ReadSpellBaseFormula(r, out uint school, out uint power);
uint[] comps = ReadSpellBaseFormula(r, out uint school, out uint power, out uint baseMana);
_spellComps[(int)spellId] = comps;
_spellMeta[(int)spellId] = ((int)school, (int)power);
_spellBaseMana[(int)spellId] = (int)baseMana;
n++;
}
return n;
}
private static uint[] ReadSpellBaseFormula(BinaryReader r, out uint school, out uint power)
private static uint[] ReadSpellBaseFormula(BinaryReader r, out uint school, out uint power, out uint baseMana)
{
byte[] nameB = ReadObf(r); Align(r);
byte[] descB = ReadObf(r); Align(r);
@ -356,7 +369,7 @@ internal static class ComponentDatabase
r.ReadUInt32(); // Icon
r.ReadUInt32(); // Category
r.ReadUInt32(); // Bitfield
r.ReadUInt32(); // BaseMana
baseMana = r.ReadUInt32(); // BaseMana (the mana cost before Mana Conversion)
r.ReadSingle(); // BaseRangeConstant
r.ReadSingle(); // BaseRangeMod
power = r.ReadUInt32(); // Power (the spell's difficulty; ACE's scroll rule reads it)

View file

@ -148,6 +148,34 @@ internal static class WeaponList
return list;
}
/// <summary>Appended to a listed item's name in the pickers when it isn't carried (<see cref="MissingIds"/>).</summary>
public const string MissingSuffix = " (missing)";
/// <summary>
/// The listed items the character no longer carries: neither in the pack
/// (<paramref name="inventory"/>, WorldObjectCache.GetInventory) nor wielded. The client
/// can still know an object that left (sold, given, on a mule), so the saved name alone
/// looked fine while combat couldn't use it (2026-10-11, Drakkon's buff wand 0x8000EF07,
/// shown as "Wand"). An empty inventory means it isn't known yet (logging in): nothing is
/// reported missing then. For the Items panel's warning and the pickers' "(missing)".
/// </summary>
public static HashSet<int> MissingIds(IEnumerable<ItemRule> rules, IEnumerable<WorldObject> inventory,
Func<int, WorldObject?> lookup, Func<WorldObject, bool> isWielded)
{
var missing = new HashSet<int>();
var carried = new HashSet<int>();
foreach (var wo in inventory) carried.Add(wo.Id);
if (carried.Count == 0) return missing;
foreach (var r in rules)
{
if (r.Id == 0 || carried.Contains(r.Id)) continue;
var wo = lookup(r.Id);
if (wo != null && isWielded(wo)) continue;
missing.Add(r.Id);
}
return missing;
}
/// <summary>
/// The Items panel's edited list, mapped onto the saved one by id: the saved name stays
/// (the panel shows the full name; entries are matched and saved by id), an element the
@ -194,19 +222,37 @@ internal static class WeaponList
{
unlisted = false;
int first = 0;
bool anyListedWand = false;
bool anyListedCarried = false;
// Only a wand the character still carries (in the pack or in hand). A listed wand the
// client saw once but that left the pack (sold, given, on a mule) used to be returned:
// the server ignores a wield of it, every buff got parked "fighting unbuffed", and
// Drakkon died over and over (2026-10-11, wand 0x8000EF07 shown as '?').
var pack = inventory as ICollection<WorldObject> ?? new List<WorldObject>(inventory);
var carried = new HashSet<int>();
foreach (var wo in pack) carried.Add(wo.Id);
var gone = new List<(ItemRule Rule, WorldObject Wo)>();
foreach (var r in rules)
{
var wo = lookup(r.Id);
if (wo == null) continue;
if (!IsWand(wo)) continue;
anyListedWand = true;
if (isWielded(wo)) return r.Id;
if (!carried.Contains(wo.Id)) { gone.Add((r, wo)); continue; }
anyListedCarried = true;
if (first == 0) first = r.Id;
}
if (first != 0) return first;
if (anyListedWand || !allowUnlisted) return 0;
foreach (var wo in inventory)
// A listed wand no longer carried: another of the same name in the pack stands in for it.
foreach (var (r, wo) in gone)
{
string name = !string.IsNullOrWhiteSpace(r.Name) ? r.Name : wo.Name ?? "";
if (name.Length < 3 || name == "?") continue;
foreach (var p in pack)
if (IsWand(p) && string.Equals(p.Name, name, StringComparison.OrdinalIgnoreCase))
return p.Id;
}
if (anyListedCarried || !allowUnlisted) return 0;
foreach (var wo in pack)
if (wo.ObjectClass == AcObjectClass.WandStaffOrb)
{
unlisted = true;

View file

@ -28,7 +28,8 @@ namespace RynthCore.Plugin.RynthAi.CreatureData;
/// </summary>
internal sealed class CreatureProfileStore
{
internal static readonly string Folder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "CreatureData");
/// <summary>Where creatures.json lives (the offline tests point it at a scratch folder).</summary>
internal static string Folder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "CreatureData");
private const string FileName = "creatures.json";
private readonly object _lock = new();
@ -102,7 +103,12 @@ internal sealed class CreatureProfileStore
if (dict != null)
{
foreach (var kv in dict)
_byKey[kv.Key] = kv.Value;
{
// Player characters appraised before e52ccc8 (wcid 1 / 4) are not
// creatures: dropped, and the next save writes the file without them.
if (kv.Value != null && PlayerWeenies.IsPlayerWcid(kv.Value.Wcid)) { _dirty = true; continue; }
_byKey[kv.Key] = kv.Value!;
}
}
_lastSavedJson = json;
}
@ -212,6 +218,7 @@ internal sealed class CreatureProfileStore
public void Upsert(CreatureProfile sample, int difficulty = 0)
{
if (string.IsNullOrEmpty(sample.Name)) return;
if (PlayerWeenies.IsPlayerWcid(sample.Wcid)) return; // a player character, never creature data
lock (_lock)
{

View file

@ -159,6 +159,9 @@ internal sealed class MonsterDamageStore
private static string Num(double d) => d.ToString("0.##", CultureInfo.InvariantCulture);
/// <summary>Nothing is recorded under wcid 0 or a player character's weenie (<see cref="PlayerWeenies"/>).</summary>
private static bool NotMonster(uint wcid) => wcid == 0 || PlayerWeenies.IsPlayerWcid(wcid);
/// <summary>Point the store at a character's folder and load its file. Safe to call again on character change.</summary>
public void SetCharacter(string charFolder)
{
@ -341,9 +344,25 @@ internal sealed class MonsterDamageStore
{
// Corrupt file — start fresh; it rewrites on next save.
}
// Rows a player character left behind (an appraised player or your own character
// listed as a monster) go, and the next save writes the file without them.
if (DropPlayerRowsLocked()) _dirty = true;
}
}
/// <summary>Removes every row under a player weenie. True when any went. Caller holds _lock.</summary>
private bool DropPlayerRowsLocked()
{
var gone = new List<uint>();
foreach (uint w in _byWcid.Keys) if (PlayerWeenies.IsPlayerWcid(w)) gone.Add(w);
foreach (uint w in gone) _byWcid.Remove(w);
var tierGone = new List<(uint, int)>();
foreach (var k in _byTier.Keys) if (PlayerWeenies.IsPlayerWcid(k.Wcid)) tierGone.Add(k);
foreach (var k in tierGone) _byTier.Remove(k);
return gone.Count > 0 || tierGone.Count > 0;
}
/// <summary>One AH/AD/AU/APK/AT row (a difficulty tier above 0). Caller holds _lock.</summary>
private void LoadTierRow(string[] f)
{
@ -529,7 +548,7 @@ internal sealed class MonsterDamageStore
/// </summary>
public void RecordHit(uint weaponId, uint wcid, string name, string element, int tier, double damage, bool crit)
{
if (wcid == 0 || damage <= 0) return;
if (NotMonster(wcid) || damage <= 0) return;
int d = Difficulty;
lock (_lock)
{
@ -561,7 +580,7 @@ internal sealed class MonsterDamageStore
/// </summary>
public void RecordKill(uint weaponId, uint wcid, string name, string element, int tier, int castCount, double totalDamage)
{
if (wcid == 0) return;
if (NotMonster(wcid)) return;
int d = Difficulty;
lock (_lock)
{
@ -607,7 +626,7 @@ internal sealed class MonsterDamageStore
/// <summary>An attack or cast that did nothing: evaded, or the spell was resisted.</summary>
public void RecordMiss(uint weaponId, uint wcid, string name)
{
if (wcid == 0 || weaponId == 0) return;
if (NotMonster(wcid) || weaponId == 0) return;
int d = Difficulty;
lock (_lock)
{
@ -623,7 +642,7 @@ internal sealed class MonsterDamageStore
/// </summary>
public void RecordFightTime(uint weaponId, uint wcid, string name, double seconds, string? summonElement)
{
if (wcid == 0 || seconds <= 0 || seconds > 600) return;
if (NotMonster(wcid) || seconds <= 0 || seconds > 600) return;
int d = Difficulty;
lock (_lock)
{
@ -650,7 +669,7 @@ internal sealed class MonsterDamageStore
/// <summary>The monster hit us for <paramref name="damage"/> of <paramref name="element"/>.</summary>
public void RecordTaken(uint wcid, string name, string element, double damage)
{
if (wcid == 0 || damage <= 0) return;
if (NotMonster(wcid) || damage <= 0) return;
int d = Difficulty;
lock (_lock)
{
@ -758,7 +777,7 @@ internal sealed class MonsterDamageStore
/// collapsed row shows the LATEST tier used. In-memory only (not persisted) — resets per session.</summary>
public void NoteCast(uint wcid, int tier, string? name = null)
{
if (wcid == 0) return;
if (NotMonster(wcid)) return;
lock (_lock)
{
var p = Get(wcid);
@ -859,7 +878,7 @@ internal sealed class MonsterDamageStore
/// <summary>Set (or clear, with hp &lt;= 0) the manual HP override for a wcid. Persists on next save.</summary>
public void SetManualHp(uint wcid, double hp, string? name = null)
{
if (wcid == 0) return;
if (NotMonster(wcid)) return;
lock (_lock)
{
var p = Get(wcid);
@ -880,7 +899,7 @@ internal sealed class MonsterDamageStore
/// <summary>Set (0 clears) the per-monster weapon override. Persists on next save.</summary>
public void SetManualWeapon(uint wcid, uint weaponId, string? name = null)
{
if (wcid == 0) return;
if (NotMonster(wcid)) return;
lock (_lock)
{
var p = Get(wcid);
@ -901,7 +920,7 @@ internal sealed class MonsterDamageStore
/// <summary>Set ("" = Auto) the per-monster pet choice. Persists on next save.</summary>
public void SetManualPet(uint wcid, string choice, string? name = null)
{
if (wcid == 0) return;
if (NotMonster(wcid)) return;
lock (_lock)
{
var p = Get(wcid);
@ -922,7 +941,7 @@ internal sealed class MonsterDamageStore
/// <summary>Set (0 clears) the per-monster offhand override. Persists on next save.</summary>
public void SetManualOffhand(uint wcid, uint offhandId, string? name = null)
{
if (wcid == 0) return;
if (NotMonster(wcid)) return;
lock (_lock)
{
var p = Get(wcid);

View file

@ -0,0 +1,25 @@
namespace RynthCore.Plugin.RynthAi.CreatureData;
/// <summary>
/// Weenie class ids that only player characters use, so they are never monster data: the
/// Damage tab, monster_damage.txt and creatures.json skip them, and the stores drop rows
/// already saved under them when they load.
///
/// On ACE every player character is weenie 1 ("human") whatever the heritage (heritage is a
/// property), and admin / sentinel characters ("+Name") are weenie 4. creatures.json had
/// ~130 player characters under these two (appraisals from before e52ccc8), and no monster in
/// the shipped creature_weakness.json uses either.
/// </summary>
internal static class PlayerWeenies
{
public const uint Human = 1;
public const uint Admin = 4;
public static bool IsPlayerWcid(uint wcid) => wcid == Human || wcid == Admin;
/// <summary>
/// Player object ids (ACE's player guid range, 0x50000001-0x6FFFFFFF). Monsters are
/// dynamic (0x8xxxxxxx) or landblock statics (0x7xxxxxxx), never in this range.
/// </summary>
public static bool IsPlayerGuid(uint objectId) => objectId >= 0x50000000u && objectId < 0x70000000u;
}

View file

@ -282,6 +282,19 @@ internal sealed class LegacyDashboardRenderer
return withElement ? WeaponNames.WithElement(name, r.Element) : name;
}
/// <summary>The listed weapons the character no longer carries (WeaponList.MissingIds); none before the cache is set.</summary>
internal HashSet<int> MissingWeaponIds()
{
var cache = _weaponCache;
if (cache == null) return new HashSet<int>();
return WeaponList.MissingIds(_settings.ItemRules ?? new List<ItemRule>(), cache.GetInventory(),
id => cache[id], wo => WorldObjectCache.IsWieldedByPlayer(_host, wo));
}
/// <summary>A picker's name for a listed weapon: <see cref="WeaponDisplayName"/> plus " (missing)" when it isn't carried.</summary>
private string WeaponPickerName(ItemRule r, HashSet<int> missing) =>
WeaponDisplayName(r, withElement: true) + (missing.Contains(r.Id) ? WeaponList.MissingSuffix : "");
public void SetMissileCraftingManager(MissileCraftingManager mgr) => _advancedSettingsUi.SetMissileCraftingManager(mgr);
public void SetAutoVendorStatusProvider(Func<string> status) => _advancedSettingsUi.SetAutoVendorStatusProvider(status);
public void SetAutoTradeStatusProvider(Func<string> status) => _advancedSettingsUi.SetAutoTradeStatusProvider(status);
@ -788,12 +801,13 @@ internal sealed class LegacyDashboardRenderer
{
try
{
var missing = MissingWeaponIds();
var payload = new MonstersBridgePayload
{
Rules = _settings.MonsterRules ?? new List<MonsterRule>(),
// Full names with the element ("Silver Wand (Fire)"); saved choices are by id.
Items = (_settings.ItemRules ?? new List<ItemRule>())
.Select(r => new MonsterBridgeItem { Id = r.Id, Name = WeaponDisplayName(r, withElement: true) }).ToList(),
.Select(r => new MonsterBridgeItem { Id = r.Id, Name = WeaponPickerName(r, missing) }).ToList(),
CurrentTargetName = _currentTargetId != 0 ? (_targetLabel ?? string.Empty) : string.Empty,
};
@ -833,6 +847,7 @@ internal sealed class LegacyDashboardRenderer
try
{
var items = _settings.ItemRules ?? new List<ItemRule>();
var missing = MissingWeaponIds();
var sb = new System.Text.StringBuilder();
sb.Append('[');
bool first = true;
@ -840,7 +855,7 @@ internal sealed class LegacyDashboardRenderer
{
if (!first) sb.Append(',');
first = false;
sb.Append("{\"id\":").Append(it.Id).Append(",\"name\":").Append(JsonString(WeaponDisplayName(it, withElement: true))).Append('}');
sb.Append("{\"id\":").Append(it.Id).Append(",\"name\":").Append(JsonString(WeaponPickerName(it, missing))).Append('}');
}
sb.Append(']');
return sb.ToString();
@ -1331,6 +1346,8 @@ internal sealed class LegacyDashboardRenderer
ManaTapMinMana = _settings.ManaTapMinMana,
ManaStoneKeepCount = _settings.ManaStoneKeepCount,
CurrentTargetName = _currentTargetId != 0 ? (_targetLabel ?? string.Empty) : string.Empty,
// The engine's Items face marks these "(missing)"; display only (ApplyItemsJson ignores it).
MissingIds = MissingWeaponIds().OrderBy(id => id).ToList(),
};
return JsonSerializer.Serialize(payload, RynthAiJsonContext.Default.ItemsBridgePayload);
}
@ -2949,6 +2966,7 @@ internal sealed class LegacyDashboardRenderer
sb.Append("\"children\":"); AppendMetaRuleArray(sb, r.Children ?? new List<MetaRule>()); sb.Append(',');
sb.Append("\"actionChildren\":"); AppendMetaRuleArray(sb, r.ActionChildren ?? new List<MetaRule>()); sb.Append(',');
sb.Append("\"enabled\":").Append(r.Enabled ? "true" : "false").Append(',');
if (!string.IsNullOrEmpty(r.Name)) { sb.Append("\"name\":\""); AppendEscaped(sb, r.Name); sb.Append("\","); }
long ms = r.LastFiredAt == DateTime.MinValue ? 99999L : (long)(DateTime.Now - r.LastFiredAt).TotalMilliseconds;
sb.Append("\"lastFiredMs\":").Append(ms.ToString(System.Globalization.CultureInfo.InvariantCulture));
sb.Append('}');
@ -3069,7 +3087,8 @@ internal sealed class LegacyDashboardRenderer
case "update_rule":
// The engine's editor saves every change (2026-10-05): keep the running rule's
// latch (no re-fire) and the fields the panel can't send (MetaRuleEdits).
if (cmd.Rule != null && MetaRuleEdits.Replace(_settings.MetaRules, cmd.Index, DtoToMetaRule(cmd.Rule)))
if (cmd.Rule != null && MetaRuleEdits.Replace(_settings.MetaRules, cmd.Index, DtoToMetaRule(cmd.Rule),
keepName: cmd.Rule.Name == null))
TryAutoSaveMetaCmd();
break;
@ -3103,6 +3122,7 @@ internal sealed class LegacyDashboardRenderer
{
var copy = DtoToMetaRule(cmd.Rule);
MetaRuleEdits.KeepHidden(_settings.MetaRules[cmd.Index], copy); // CallState return / ChatCapture colours
if (cmd.Rule.Name == null) copy.Name = _settings.MetaRules[cmd.Index].Name;
_settings.MetaRules.Insert(cmd.Index + 1, copy);
TryAutoSaveMetaCmd();
}
@ -3162,6 +3182,7 @@ internal sealed class LegacyDashboardRenderer
Action = (MetaActionType)dto.Action,
ActionData = dto.ActionData ?? "",
Enabled = dto.Enabled,
Name = AfFileWriter.OneLine(dto.Name),
};
foreach (var c in dto.Children ?? new List<MetaRuleDto>())
r.Children.Add(DtoToMetaRule(c));

View file

@ -326,6 +326,7 @@ internal sealed class LegacyMetaUi
ActionData = rule.ActionData,
CallReturnState = rule.CallReturnState,
ChatColors = rule.ChatColors,
Name = rule.Name,
Children = CloneChildren(rule.Children),
ActionChildren = CloneChildren(rule.ActionChildren)
};
@ -1025,6 +1026,7 @@ internal sealed class LegacyMetaUi
ActionData = r.ActionData,
CallReturnState = r.CallReturnState,
ChatColors = r.ChatColors,
Name = r.Name,
Children = CloneChildren(r.Children),
ActionChildren = CloneChildren(r.ActionChildren)
});

View file

@ -758,6 +758,9 @@ public sealed class ItemsBridgePayload
public int ManaTapMinMana { get; set; }
public int ManaStoneKeepCount { get; set; }
public string CurrentTargetName { get; set; } = string.Empty;
/// <summary>Listed weapons the character no longer carries (not in the pack, not wielded), by
/// id: the engine's Items face shows them as missing. Display only, never read back.</summary>
public List<int> MissingIds { get; set; } = new();
}
// ── Nav bridge types ─────────────────────────────────────────────────────────
@ -1097,6 +1100,11 @@ public sealed class MetaRule
/// (the property initializer runs, so backward-compatible).</summary>
public bool Enabled { get; set; } = true;
/// <summary>A name to find the rule by in the Meta panel (optional; only top-level rules have
/// one). Saved in .af as a "~~ @name ..." line before the rule's IF: (a plain comment to
/// other tools, like "~~ @disabled"); .met has no place for it.</summary>
public string Name { get; set; } = string.Empty;
[JsonIgnore]
public bool HasFired { get; set; }

View file

@ -12,6 +12,9 @@ internal sealed class MetaRuleDto
public List<MetaRuleDto> Children { get; set; } = new();
public List<MetaRuleDto> ActionChildren { get; set; } = new();
public bool Enabled { get; set; } = true;
/// <summary>The rule's name; null from an engine without rule names (an update then keeps the
/// name the rule has, so a mismatched engine never wipes names).</summary>
public string? Name { get; set; }
}
internal sealed class MetaCommand

View file

@ -86,7 +86,10 @@ public sealed partial class RynthAiPlugin
return true;
case "quit":
case "exit":
if (Host.HasInvokeChatParser) Host.InvokeChatParser("/quit");
// Close the client (also /ub quit|exit, which land here). "/quit" is not an AC
// client command and did nothing; the engine's /rc quit closes the client the way
// its close button does, logging the character off.
if (Host.HasInvokeChatParser) Host.InvokeChatParser("/rc quit");
return true;
// ── Send a chat line / slash command (VTank /mt send) ────────────

View file

@ -99,6 +99,7 @@ internal static class AfFileParser
idx++; // consume STATE: line
bool pendingDisabled = false; // set by a "~~ @disabled" marker line
string pendingName = ""; // set by a "~~ @name ..." marker line
while (idx < lines.Length)
{
string trimmed = lines[idx].TrimStart();
@ -113,6 +114,8 @@ internal static class AfFileParser
{
if (trimmed.Equals("~~ @disabled", StringComparison.OrdinalIgnoreCase))
pendingDisabled = true;
else if (TryRuleName(trimmed, out string name))
pendingName = name;
idx++;
continue;
}
@ -120,8 +123,9 @@ internal static class AfFileParser
// Look for IF: line
if (trimmed.StartsWith("IF:"))
{
var rule = new MetaRule { State = stateName, Enabled = !pendingDisabled };
var rule = new MetaRule { State = stateName, Enabled = !pendingDisabled, Name = pendingName };
pendingDisabled = false;
pendingName = "";
int ifIndent = CountLeadingTabs(lines[idx]);
ParseIfBlock(lines, ref idx, rule, ifIndent);
rules.Add(rule);
@ -133,6 +137,19 @@ internal static class AfFileParser
}
}
/// <summary>"~~ @name Rebuff when low" (AfFileWriter's rule name line): the name, trimmed.
/// "~~ @names..." or an empty "~~ @name" is just a comment.</summary>
internal static bool TryRuleName(string trimmedLine, out string name)
{
name = "";
const string marker = "~~ @name";
if (!trimmedLine.StartsWith(marker, StringComparison.OrdinalIgnoreCase)) return false;
string rest = trimmedLine.Substring(marker.Length);
if (rest.Length == 0 || !char.IsWhiteSpace(rest[0])) return false;
name = rest.Trim();
return name.Length > 0;
}
private static void ParseIfBlock(string[] lines, ref int idx, MetaRule rule, int ifIndent)
{
// Parse condition from IF: line

View file

@ -65,10 +65,20 @@ internal static class AfFileWriter
// ── Rule writing ────────────────────────────────────────────────────────
/// <summary>A rule name on one line (it is written as a "~~ @name" comment line).</summary>
internal static string OneLine(string? text)
{
if (string.IsNullOrEmpty(text)) return "";
return text.Replace("\r", " ").Replace("\n", " ").Replace("\t", " ").Trim();
}
private static void WriteRule(TextWriter writer, MetaRule rule)
{
// Disabled marker (backward-compatible: a plain ~~ comment to old
// parsers, recognised by AfFileParser to set Enabled=false).
// Name and disabled markers (backward-compatible: plain ~~ comments to old
// parsers and other tools; AfFileParser reads them back).
string name = OneLine(rule.Name);
if (name.Length > 0)
writer.WriteLine("\t~~ @name " + name);
if (!rule.Enabled)
writer.WriteLine("\t~~ @disabled");

View file

@ -16,15 +16,22 @@ namespace RynthCore.Plugin.RynthAi.Meta;
/// <summary>
/// Evaluates RynthAi expressions.
///
/// Follows the UtilityBelt expression reference (utilitybelt.gitlab.io/docs/expressions).
///
/// Syntax:
/// Infix operators: == > < >= <= + - * / % # &amp;&amp; || ~ &lt;&lt; >> &amp; ^ |
/// Infix operators: == != > < >= <= + - * / % # &amp;&amp; || ~ &lt;&lt; >> &amp; ^ |
/// (&amp;&amp; and || skip the side that can't change the answer)
/// Function calls: funcname[arg1, arg2, ...] (args can be nested expressions)
/// Variables: $name is shorthand for getvar[name]
/// Literals: plain numbers (decimal or 0x hex) or identifiers
/// Sequences: expr; expr; ... (value of the last)
/// Variables: $name / @name / &amp;name = getvar / getpvar / getgvar[name];
/// $name = value assigns; x{i}, x{key}, x{a:b}, $x[a:b], text[a:b]
/// Literals: numbers (decimal or 0x hex), true/false (1/0), `backtick text`,
/// bare text of words and spaces, \x escapes one character
///
/// Boolean convention: "0" and "" are false, everything else is true.
/// All values are strings internally; numeric coercion happens per-operator.
/// Lists are stored by reference; variables hold a list handle (e.g. "L:0").
/// Lists are text ("[a,b]"); the list functions that change a list write it back to the
/// variable it came from. Dictionaries and stopwatches are handles ("D:0", "SW:0").
/// </summary>
internal sealed class ExpressionEngine
{
@ -36,9 +43,42 @@ internal sealed class ExpressionEngine
// Lists are value-typed: serialized as "[item1,item2,...]" strings — no backing store.
// Dict store: handle → (key → value). Handles look like "D:0", "D:1", …
// Dicts are ephemeral: cleared at the start of each top-level Evaluate call.
// A dict lives as long as something holds its handle: "setvar[myDict,dictcreate[]]" and
// later "dictadditem[$myDict,foo,1]" is the reference's own pattern. (Dicts used to be
// cleared after every top-level evaluation and the ids restarted at D:0, so a stored handle
// was dead or, worse, named a newer, unrelated dict.) Unreferenced ones are swept once the
// store grows past _dictSweepAt; handles are never reused.
private readonly Dictionary<string, Dictionary<string, string>> _dicts = new(StringComparer.Ordinal);
private int _nextDictId;
private const int DictSweepMin = 256;
private int _dictSweepAt = DictSweepMin;
private static readonly Regex DictHandleRx = new(@"D:\d+", RegexOptions.CultureInvariant);
/// <summary>Drops dicts no variable (memory, persistent, global), option, pending delayexec
/// or live dict refers to. Runs only between top-level evaluations, so no temporary of an
/// evaluation in progress is lost.</summary>
private void SweepDicts()
{
var live = new HashSet<string>(StringComparer.Ordinal);
var todo = new Queue<string>();
void Scan(string? s)
{
if (string.IsNullOrEmpty(s) || s.IndexOf("D:", StringComparison.Ordinal) < 0) return;
foreach (Match m in DictHandleRx.Matches(s))
if (_dicts.ContainsKey(m.Value) && live.Add(m.Value)) todo.Enqueue(m.Value);
}
foreach (string v in _variables.Values) Scan(v);
if (_pvars != null) foreach (string v in _pvars.Values) Scan(v);
if (_gvars != null) foreach (string v in _gvars.Values) Scan(v);
foreach (string v in _options.Values) Scan(v);
foreach (var (_, expr) in _delayedExecs) Scan(expr);
while (todo.Count > 0)
foreach (var (k, v) in _dicts[todo.Dequeue()]) { Scan(k); Scan(v); }
foreach (string h in _dicts.Keys.ToList())
if (!live.Contains(h)) _dicts.Remove(h);
_dictSweepAt = Math.Max(DictSweepMin, live.Count * 2);
}
private int _evalDepth;
// Hard recursion caps. A .NET StackOverflowException is uncatchable and
@ -177,10 +217,10 @@ internal sealed class ExpressionEngine
/// </summary>
public string Evaluate(string expression)
{
string expr = expression?.Trim() ?? "";
string expr = TrimArg(expression ?? "");
if (expr.Length == 0) return "";
if (_evalDepth >= MaxEvalDepth) return "ERR:Depth:max recursion exceeded";
if (_evalDepth == 0) { _dicts.Clear(); _nextDictId = 0; _parenDepth = 0; }
if (_evalDepth == 0) { _parenDepth = 0; if (_dicts.Count > _dictSweepAt) SweepDicts(); }
_evalDepth++;
try { return new Parser(this, expr).Run(); }
catch (Exception ex) { return $"ERR:{ex.GetType().Name}:{ex.Message}"; }
@ -208,9 +248,12 @@ internal sealed class ExpressionEngine
// ── Lazy (only the taken branch is evaluated) ─────────────────────────
if (funcName == "iif")
{
// "If the first parameter is false or not a number, returns the third argument":
// text is not true here (iif[abc,yes,no] is no). The reference also evaluates both
// branches; we still evaluate only the chosen one (no meta relies on both running).
var raw = SplitArgs(argsStr);
if (raw.Count < 2) return "";
return ToBool(Evaluate(raw[0]))
return IsNumber(Evaluate(raw[0]), out double c) && c != 0
? Evaluate(raw[1])
: (raw.Count >= 3 ? Evaluate(raw[2]) : "");
}
@ -238,6 +281,9 @@ internal sealed class ExpressionEngine
// Raw expression template for higher-order list functions (not pre-evaluated).
string Tmpl(int i) => i < rawArgs.Count ? StripBackticks(rawArgs[i]) : "";
// A name, pattern, state, setting or format argument (see TextArg).
string Text(int i) => i < rawArgs.Count ? TextArg(rawArgs[i]) : "";
return funcName switch
{
// ── Session variables ──────────────────────────────────────────────
@ -302,19 +348,21 @@ internal sealed class ExpressionEngine
// ── List functions ────────────────────────────────────────────────
"listcreate" => EvalListCreate(rawArgs),
"listadd" => EvalListAdd(A(0), A(1)),
"listinsert" => EvalListInsert(A(0), A(1), A(2)),
"listremove" => EvalListRemove(A(0), A(1)),
"listremoveat" => EvalListRemoveAt(A(0), A(1)),
// These change the list (the reference: "Returns the list object"). A list is text
// here, so the changed list is written back to the variable it came from.
"listadd" => ListOp(rawArgs, A(0), l => EvalListAdd(l, A(1))),
"listinsert" => ListOp(rawArgs, A(0), l => EvalListInsert(l, A(1), A(2))),
"listremove" => ListOp(rawArgs, A(0), l => EvalListRemove(l, A(1))),
"listremoveat" => ListOp(rawArgs, A(0), l => EvalListRemoveAt(l, A(1))),
"listgetitem" => EvalListGetItem(A(0), A(1)),
"listcontains" => EvalListContains(A(0), A(1)),
"listindexof" => EvalListIndexOf(A(0), A(1)),
"listlastindexof" => EvalListLastIndexOf(A(0), A(1)),
"listcopy" => EvalListCopy(A(0)),
"listreverse" => EvalListReverse(A(0)),
"listpop" => EvalListPop(A(0), rawArgs.Count >= 2 ? A(1) : "-1"),
"listpop" => EvalListPop(rawArgs, A(0), rawArgs.Count >= 2 ? A(1) : "-1"),
"listcount" => EvalListCount(A(0)),
"listclear" => EvalListClear(A(0)),
"listclear" => ListOp(rawArgs, A(0), EvalListClear),
"listfromrange" => EvalListFromRange(A(0), A(1)),
// Higher-order: expression arg is a raw template evaluated per iteration
@ -341,17 +389,17 @@ internal sealed class ExpressionEngine
"wobjectfindall" => EvalWobjectFindAll(),
"wobjectfindallbyobjectclass" => EvalWobjectFindAllByObjectClass(A(0)),
"wobjectfindallbytemplatetype" => EvalWobjectFindAllByTemplateType(A(0)),
"wobjectfindallbynamerx" => EvalWobjectFindAllByNameRx(Tmpl(0)),
"wobjectfindallbynamerx" => EvalWobjectFindAllByNameRx(Text(0)),
"wobjectfindallinventory" => EvalWobjectFindAllInventory(),
"wobjectfindalllandscape" => EvalWobjectFindAllLandscape(),
"wobjectfindallinventorybytemplatetype" => EvalWobjectFindAllInventoryByTemplateType(A(0)),
"wobjectfindallinventorybyobjectclass" => EvalWobjectFindAllInventoryByObjectClass(A(0)),
"wobjectfindallinventorybynamerx" => EvalWobjectFindAllInventoryByNameRx(Tmpl(0)),
"wobjectfindininventorybyname" => EvalWobjectFindInInventoryByName(Tmpl(0)),
"wobjectfindininventorybynamerx" => EvalWobjectFindInInventoryByNameRx(Tmpl(0)),
"wobjectfindallinventorybynamerx" => EvalWobjectFindAllInventoryByNameRx(Text(0)),
"wobjectfindininventorybyname" => EvalWobjectFindInInventoryByName(Text(0)),
"wobjectfindininventorybynamerx" => EvalWobjectFindInInventoryByNameRx(Text(0)),
"wobjectfindalllandscapebyobjectclass" => EvalWobjectFindAllLandscapeByObjectClass(A(0)),
"wobjectfindalllandscapebytemplatetype" =>EvalWobjectFindAllLandscapeByTemplateType(A(0)),
"wobjectfindalllandscapebynamerx" => EvalWobjectFindAllLandscapeByNameRx(Tmpl(0)),
"wobjectfindalllandscapebynamerx" => EvalWobjectFindAllLandscapeByNameRx(Text(0)),
"wobjectfindallbycontainer" => EvalWobjectFindAllByContainer(A(0)),
"wobjectgetselection" => EvalWobjectGetSelection(),
"wobjectgetplayer" => EvalWobjectGetPlayer(),
@ -366,7 +414,7 @@ internal sealed class ExpressionEngine
"wobjectfindnearestmonster" => EvalWobjectFindNearestMonster(),
"wobjectfindbyid" => EvalWobjectFindById(A(0)),
"wobjectfindnearestbyobjectclass" => EvalWobjectFindNearestByObjectClass(A(0)),
"wobjectfindnearestbynameandobjectclass" => EvalWobjectFindNearestByNameAndObjectClass(A(0), Tmpl(1)),
"wobjectfindnearestbynameandobjectclass" => EvalWobjectFindNearestByNameAndObjectClass(A(0), Text(1)),
"wobjectgetisdooropen" => EvalWobjectGetIsDoorOpen(A(0)),
"wobjectgetphysicsstate" => EvalWobjectGetPhysicsState(A(0)),
"wobjectgetintprop" => EvalWobjectGetIntProp(A(0), A(1)),
@ -386,8 +434,8 @@ internal sealed class ExpressionEngine
"wobjectgetspellids" => EvalWobjectGetSpellIds(A(0)),
"wobjectgetactivespellids" => EvalWobjectGetActiveSpellIds(A(0)),
"wobjectgetactivespelldurations" => EvalWobjectGetActiveSpellDurations(A(0)),
"getitemcountininventorybyname" => EvalItemCountByName(Tmpl(0)),
"getitemcountininventorybynamerx" => EvalItemCountByNameRx(Tmpl(0)),
"getitemcountininventorybyname" => EvalItemCountByName(Text(0)),
"getitemcountininventorybynamerx" => EvalItemCountByNameRx(Text(0)),
"getinventorycountbytemplatetype" => EvalGetInventoryCountByTemplateType(A(0)),
"actiontryselect" => EvalActionTrySelect(A(0)),
"actiontryuseitem" => EvalActionTryUseItem(A(0)),
@ -417,18 +465,20 @@ internal sealed class ExpressionEngine
"spellname" => SpellDatabase.GetSpellName((int)ToDouble(A(0))),
"componentname" => ComponentDatabase.GetComponentName((uint)ToDouble(A(0))),
"componentdata" => EvalComponentData(A(0)),
"getknownspells" => EvalGetKnownSpells(),
"getheadingto" => EvalGetHeadingTo(A(0)),
"getheading" => EvalGetHeading(A(0)),
// ── Math ──────────────────────────────────────────────────────────
"getobjectinternaltype" => EvalGetObjectInternalType(A(0)),
"isfalse" => ToDouble(A(0)) == 0 ? "1" : "0",
"istrue" => ToDouble(A(0)) != 0 ? "1" : "0",
"iif" => EvalIif(A(0), A(1), A(2)),
// "Checks if a value is equal to false (0)" / "equal to true (1)": text is neither
// (isfalse[abc] was 1), and 2 is not 1.
"isfalse" => IsNumber(A(0), out double fv) && fv == 0 ? "1" : "0",
"istrue" => IsNumber(A(0), out double tv) && tv == 1 ? "1" : "0",
"randint" => Random.Shared.Next((int)ToDouble(A(0)), (int)ToDouble(A(1))).ToString(CultureInfo.InvariantCulture),
"cstr" => A(0),
"cstrf" => EvalCstrf(A(0), Tmpl(1)),
"cstrf" => EvalCstrf(A(0), Text(1)),
"cnumber" => ToDouble(A(0)).ToString("G", CultureInfo.InvariantCulture),
"strlen" => A(0).Length.ToString(CultureInfo.InvariantCulture),
"floor" => Fmt(Math.Floor(ToDouble(A(0)))),
@ -469,7 +519,8 @@ internal sealed class ExpressionEngine
// ── Game time (Dereth) ────────────────────────────────────────────
"getgameyear" => GetGameYear().ToString(CultureInfo.InvariantCulture),
"getgamemonth" => GetGameMonth().ToString(CultureInfo.InvariantCulture),
"getgamemonthname" => GetGameMonthName(A(0)),
// The reference's own example calls it getmonthname[1].
"getgamemonthname" or "getmonthname" => GetGameMonthName(A(0)),
"getgameday" => GetGameDay().ToString(CultureInfo.InvariantCulture),
"getgamehour" => GetGameHour().ToString(CultureInfo.InvariantCulture),
"getgamehourname" => GetGameHourName(A(0)),
@ -499,13 +550,13 @@ internal sealed class ExpressionEngine
"raoptset" or "uboptset" => EvalOptSet(A(0), A(1)),
// ── RynthAi settings / meta state (VTank-compatible names) ────────
"rasetmetastate" or "vtsetmetastate" or "setmetastate" => EvalVtSetMetaState(Tmpl(0)),
"rasetmetastate" or "vtsetmetastate" or "setmetastate" => EvalVtSetMetaState(Text(0)),
"ragetmetastate" or "vtgetmetastate" or "getmetastate" => _settings?.CurrentState ?? "",
// UB vtgetmeta[]: the loaded meta's name (file name without extension).
"vtgetmeta" or "ragetmeta" => string.IsNullOrEmpty(_settings?.CurrentMetaPath)
? "" : Path.GetFileNameWithoutExtension(_settings!.CurrentMetaPath),
"rasetsetting" or "vtsetsetting" => EvalVtSetSetting(Tmpl(0), A(1)),
"ragetsetting" or "vtgetsetting" or "vtankgetsetting" => EvalVtGetSetting(Tmpl(0)),
"rasetsetting" or "vtsetsetting" => EvalVtSetSetting(Text(0), A(1)),
"ragetsetting" or "vtgetsetting" or "vtankgetsetting" => EvalVtGetSetting(Text(0)),
// ── Dynamic evaluation ────────────────────────────────────────────
"exec" => Evaluate(A(0)),
@ -527,6 +578,9 @@ internal sealed class ExpressionEngine
"dictclear" => EvalDictClear(A(0)),
"dictcopy" => EvalDictCopy(A(0)),
// "Strings support slices like arrays. ie test[1:]": a word that isn't a function,
// followed by [start:stop].
_ when TopLevelColon(argsStr) >= 0 => SliceBy(expr.Substring(0, lb).Trim(), argsStr),
_ => EvalUnknownFunction(funcName)
};
}
@ -535,9 +589,12 @@ internal sealed class ExpressionEngine
/// missing verb ONCE per distinct name, so a typo'd or unsupported meta function is visible
/// instead of silently evaluating to empty. Rate-limited by the seen-set to avoid log spam.</summary>
private readonly HashSet<string> _loggedUnknownFns = new();
private bool _sawUnknownFn; // set by any unknown call (TextArg asks)
private int _quietUnknownFn; // > 0: don't log (TextArg is only trying an argument)
private string EvalUnknownFunction(string funcName)
{
if (!string.IsNullOrEmpty(funcName) && _loggedUnknownFns.Add(funcName))
_sawUnknownFn = true;
if (_quietUnknownFn == 0 && !string.IsNullOrEmpty(funcName) && _loggedUnknownFns.Add(funcName))
_host.Log($"[Meta] unknown expression function '{funcName}[...]' — evaluates to empty; " +
"check spelling / supported verbs. (logged once per name)");
return "";
@ -754,18 +811,22 @@ internal sealed class ExpressionEngine
catch { return d.ToString("G", CultureInfo.InvariantCulture); }
}
// Both trueVal and falseVal are pre-evaluated by the caller (C# arg eval order) — matches UB behaviour.
private static string EvalIif(string cond, string trueVal, string falseVal)
=> ToDouble(cond) != 0 ? trueVal : falseVal;
private static bool IsNumber(string s, out double d)
=> double.TryParse(s, NumberStyles.Float | NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out d);
// 0=none, 1=number, 3=string, 7=object — matches UB internal type constants.
// 0=none, 1=number, 3=string, 7=object — matches UB internal type constants. Lists and
// coordinates are objects in UB (they read as 3, text, because they are text here).
private static string EvalGetObjectInternalType(string val)
{
if (string.IsNullOrEmpty(val)) return "0";
if (TryParseWobjectHandle(val, out _, out _)) return "7";
// A world object handle. Not a bare number: an id is still a number (any nonzero
// integer used to read as an object, getobjectinternaltype[5] was 7).
if (val.StartsWith("[WorldObject] ", StringComparison.Ordinal) && TryParseWobjectHandle(val, out _, out _)) return "7";
if (val.Length > 3 && val[0] == 'S' && val[1] == 'W' && val[2] == ':') return "7";
if (val.Length > 2 && val[0] == 'D' && val[1] == ':') return "7";
if (double.TryParse(val, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out _)) return "1";
if (GetList(val) != null) return "7";
if (val.Split('|').Length == 3 && TryParseCoordObject(val, out _, out _, out _)) return "7";
return "3";
}
@ -1148,6 +1209,38 @@ internal sealed class ExpressionEngine
return items;
}
/// <summary>
/// A name, pattern, state, setting or format argument. The reference makes these ordinary
/// string arguments, so an expression is evaluated: "$itemname", "getvar[x]",
/// "`^`+$name+`$`", "\(Knight\|Wisp\)\.\+Essence". They used to be taken as typed, so all
/// of those searched for their own source text. Anything else is still taken as typed, so
/// plain text with punctuation keeps working: "The Baron's Key", "High-Stakes Gambling
/// Token", "(Contract)", "Recharge-Norm-Hitp". A lone word[...] that isn't a function
/// (a regex such as "Pack[0-9]") stays as typed too.
/// </summary>
private string TextArg(string raw)
{
string a = raw.Trim();
if (a.Length == 0) return "";
bool expr = a[0] is '`' or '$' or '@'
|| (a[0] == '&' && a.Length > 1 && (char.IsLetterOrDigit(a[1]) || a[1] == '_'))
|| a.IndexOf('\\') >= 0;
if (expr) return Evaluate(a);
int lb = a.IndexOf('[');
if (lb <= 0 || FindClose(a, lb, '[', ']') != a.Length) return a;
for (int i = 0; i < lb; i++)
if (!char.IsLetterOrDigit(a[i]) && a[i] != '_') return a;
_sawUnknownFn = false;
_quietUnknownFn++;
try
{
string v = Evaluate(a);
return _sawUnknownFn ? a : v;
}
finally { _quietUnknownFn--; }
}
private static string StripBackticks(string s)
{
s = s.Trim();
@ -1244,14 +1337,49 @@ internal sealed class ExpressionEngine
return NewList(copy);
}
private static string EvalListPop(string handle, string indexArg)
/// <summary>Removes the item and returns it (it used to stay in the list: listpop on a
/// variable never shrank it).</summary>
private string EvalListPop(List<string> rawArgs, string handle, string indexArg)
{
var list = GetList(handle);
if (list == null || list.Count == 0) return "";
int idx = (int)ToLong(indexArg);
if (idx < 0) idx = list.Count - 1; // -1 = last item
if (idx < 0 || idx >= list.Count) return "";
return list[idx];
string item = list[idx];
list.RemoveAt(idx);
WriteBackList(rawArgs, NewList(list));
return item;
}
/// <summary>Runs a list-changing function and, when its list came from a variable
/// ($x, @x, &amp;x, getvar[x], getpvar[x], getgvar[x]), stores the changed list there, so
/// "listadd[getvar[CharList], Drakkon]" adds to CharList. A list given any other way
/// (listcreate[...], an item of another list) just gives the changed copy.</summary>
private string ListOp(List<string> rawArgs, string handle, Func<string, string> op)
{
string result = op(handle);
if (GetList(handle) != null && GetList(result) != null) WriteBackList(rawArgs, result);
return result;
}
private static readonly Regex ListSourceCall = new(@"^(getvar|getpvar|getgvar)\[(.*)\]$",
RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.CultureInvariant);
private void WriteBackList(List<string> rawArgs, string list)
{
if (rawArgs.Count == 0) return;
string a = rawArgs[0].Trim();
if (a.Length > 1 && a[0] is '$' or '@' or '&' && a.Skip(1).All(c => char.IsLetterOrDigit(c) || c == '_'))
{
WriteVar(a[0], a.Substring(1), list);
return;
}
var m = ListSourceCall.Match(a);
if (!m.Success || FindClose(a, m.Groups[1].Length, '[', ']') != a.Length) return;
char sigil = char.ToLowerInvariant(m.Groups[1].Value[3]) switch { 'p' => '@', 'g' => '&', _ => '$' };
string name = Evaluate(m.Groups[2].Value);
if (name.Length > 0) WriteVar(sigil, name, list);
}
private static string EvalListCount(string handle)
@ -2526,6 +2654,7 @@ internal sealed class ExpressionEngine
if (!int.TryParse(spellArg.Trim(), out int spellId) || spellId == 0) return "2";
if (!_host.HasCastSpell) return "2";
if (!TryParseWobjectHandle(targetArg, out uint targetId, out _) || targetId == 0) return "2";
if (SpellKnownToBeUnknown(spellId)) return "2";
if (!EnsureMagicModeForCast()) return "0";
@ -2799,6 +2928,7 @@ internal sealed class ExpressionEngine
{
if (!int.TryParse(arg.Trim(), out int spellId) || spellId == 0) return "2";
if (!_host.HasCastSpell) return "2";
if (SpellKnownToBeUnknown(spellId)) return "2";
if (!EnsureMagicModeForCast()) return "0";
@ -2810,6 +2940,26 @@ internal sealed class ExpressionEngine
return "1";
}
/// <summary>The character doesn't know the spell (as far as the client can tell): the
/// reference's "2 if the attempt is impossible". It used to wield a wand, cast anyway and
/// report 1 (started). Unreadable counts as known, so nothing is refused by mistake.</summary>
private bool SpellKnownToBeUnknown(int spellId)
=> _playerId != 0 && _host.HasIsSpellKnown
&& _host.IsSpellKnown(_playerId, (uint)spellId, out bool known) && !known;
/// <summary>getknownspells[]: the ids of the spells in the character's spellbook.</summary>
private string EvalGetKnownSpells()
{
if (!_host.HasReadKnownSpells) return "[]";
var buf = new uint[8192];
int count = _host.ReadKnownSpells(buf, buf.Length);
if (count <= 0) return "[]";
var ids = new List<string>(Math.Min(count, buf.Length));
for (int i = 0; i < count && i < buf.Length; i++)
ids.Add(buf[i].ToString(CultureInfo.InvariantCulture));
return NewList(ids);
}
private string EvalActionTryEquipAnyWand()
{
if (_worldObjectCache == null || !_host.HasUseObject) return "0";
@ -3081,11 +3231,15 @@ internal sealed class ExpressionEngine
{
if (!TryParseWobjectHandle(objArg, out uint uid, out _)) return "0";
if (!_host.HasGetPlayerPose) return "0";
if (!_host.TryGetPlayerPose(out _, out float px, out float py, out _, out _, out _, out _, out _)) return "0";
if (!_host.TryGetPlayerPose(out uint pc, out float px, out float py, out _, out _, out _, out _, out _)) return "0";
if (!_host.HasGetObjectPosition) return "0";
if (!_host.TryGetObjectPosition(uid, out _, out float tx, out float ty, out _)) return "0";
if (!_host.TryGetObjectPosition(uid, out uint tc, out float tx, out float ty, out _)) return "0";
double deg = Math.Atan2(tx - px, ty - py) * (180.0 / Math.PI);
// x/y are metres within each one's own landblock (192 m square); add the landblocks'
// offsets, or a target across a landblock edge points the wrong way.
double dx = ((int)(tc >> 24) - (int)(pc >> 24)) * 192.0 + (tx - px);
double dy = ((int)((tc >> 16) & 0xFF) - (int)((pc >> 16) & 0xFF)) * 192.0 + (ty - py);
double deg = Math.Atan2(dx, dy) * (180.0 / Math.PI);
if (deg < 0) deg += 360.0;
return deg.ToString("G", CultureInfo.InvariantCulture);
}
@ -3158,7 +3312,7 @@ internal sealed class ExpressionEngine
private static readonly string[] MonthNames =
{
"Morningthaw","Solclaim","Seedsow","Leafdawning","Verdantine","Thistledown",
"HarvestGain","Leafcull","Frostfell","Snowreap","Coldeve","Wintersebb"
"Harvestgain","Leafcull","Frostfell","Snowreap","Coldeve","Wintersebb"
};
private static readonly string[] HourNames =
@ -3203,7 +3357,8 @@ internal sealed class ExpressionEngine
private int GetGameYear() => (int)(GetGameTicks() / TicksInYear);
private int GetGameMonth() => (int)(GetGameTicks() % TicksInYear / TicksInMonth);
private int GetGameDay() => (int)(GetGameTicks() % TicksInMonth / TicksInDay);
// "the current ingame day of the month. 1-30" (it was 0-29).
private int GetGameDay() => (int)(GetGameTicks() % TicksInMonth / TicksInDay) + 1;
private int GetGameHour() => (int)(GetGameTicks() % TicksInDay / TicksInHour);
private bool GetIsDay() { int h = GetGameHour(); return h >= 4 && h < 12; }
@ -3258,16 +3413,13 @@ internal sealed class ExpressionEngine
}
// VTank getfellowshipstatus[] — the migration keystone (~149 metas use it).
// Contract reverse-engineered from real meta usage across the VTank library
// (512 calls: only ==0 / ==1 / !=0; AutoFellow gates `/ub fellow recruit`
// — a leader-only action — on ==1):
// 0 = not in a fellowship
// 1 = in a fellowship and you are the leader
// 2 = in a fellowship and you are NOT the leader
// Documented: "Returns 1 if you are in a fellowship, 0 otherwise". It used to return 2 for a
// member who isn't the leader (a guess from meta usage), so metas testing ==1 saw a member
// as not in a fellowship (2026-10-11). Leader checks: getfellowshipisleader[].
private string EvalGetFellowshipStatus()
{
if (_fellowshipTracker == null || !_fellowshipTracker.IsInFellowship) return "0";
return _fellowshipTracker.IsLeader ? "1" : "2";
return "1";
}
private string EvalGetFellowId(string arg)
@ -3633,6 +3785,81 @@ internal sealed class ExpressionEngine
return dict != null ? NewDict(dict) : NewDict();
}
// ── Variable shorthand, indexes and slices ────────────────────────────────
/// <summary>Reads a variable by sigil: $ memory, @ persistent, &amp; global. Unset reads "0".</summary>
internal string ReadVar(char sigil, string name)
{
var store = sigil switch { '@' => GetPvars(), '&' => GetGvars(), _ => _variables };
return store.TryGetValue(name, out string? v) ? v ?? "" : "0";
}
/// <summary>Writes a variable by sigil, as setvar / setpvar / setgvar do.</summary>
internal string WriteVar(char sigil, string name, string value) => sigil switch
{
'@' => EvalSetPvar(name, value),
'&' => EvalSetGvar(name, value),
_ => EvalSetVar(name, value),
};
/// <summary>x{i}: a list item, a dictionary value by key, or a character of text. A negative
/// index counts from the end. Missing → "" (the reference throws).</summary>
internal string IndexValue(string value, string key)
{
var dict = GetDict(value.Trim());
if (dict != null) return dict.TryGetValue(key, out string? dv) ? dv : "";
var list = GetList(value);
int count = list?.Count ?? value.Length;
long i = ToLong(key);
if (i < 0) i += count;
if (i < 0 || i >= count) return "";
return list != null ? list[(int)i] : value[(int)i].ToString();
}
/// <summary>x{start:stop} / x[start:stop]: a sub-list or substring, as Python slices
/// (stop excluded, negatives count from the end, empty means the start / the end).</summary>
internal string SliceValue(string value, string start, string stop)
{
var list = GetList(value);
int n = list?.Count ?? value.Length;
int Norm(string s, int dflt)
{
if (s.Trim().Length == 0) return dflt;
long i = ToLong(s);
if (i < 0) i += n;
return (int)Math.Clamp(i, 0, n);
}
int a = Norm(start, 0), b = Norm(stop, n);
if (b < a) b = a;
return list != null ? NewList(list.GetRange(a, b - a)) : value.Substring(a, b - a);
}
/// <summary>Index of a ':' outside brackets and backticks, or -1 (marks a slice).</summary>
internal static int TopLevelColon(string s)
{
int depth = 0;
bool inBacktick = false;
for (int i = 0; i < s.Length; i++)
{
if (IsEscape(s, i, inBacktick)) { i++; continue; }
char c = s[i];
if (c == '`') inBacktick = !inBacktick;
else if (inBacktick) continue;
else if (c is '[' or '{' or '(') depth++;
else if (c is ']' or '}' or ')') depth--;
else if (c == ':' && depth == 0) return i;
}
return -1;
}
/// <summary>Evaluates "start:stop" (either side may be empty) and slices.</summary>
internal string SliceBy(string value, string spec)
{
int colon = TopLevelColon(spec);
string a = spec.Substring(0, colon), b = spec.Substring(colon + 1);
return SliceValue(value, a.Trim().Length > 0 ? Evaluate(a) : "", b.Trim().Length > 0 ? Evaluate(b) : "");
}
// ── Coercions ─────────────────────────────────────────────────────────────
/// <summary>"0" and "" are false; everything else is true.</summary>
@ -3669,7 +3896,8 @@ internal sealed class ExpressionEngine
// ── Argument splitter ─────────────────────────────────────────────────────
/// <summary>Splits a comma-separated argument list, respecting nested bracket depth and backtick strings.</summary>
/// <summary>Splits a comma-separated argument list, respecting nested bracket depth, backtick
/// strings and backslash escapes ("echo[Not here\, sorry,15]" is two arguments).</summary>
private static List<string> SplitArgs(string s)
{
var list = new List<string>();
@ -3678,6 +3906,7 @@ internal sealed class ExpressionEngine
for (int i = 0; i < s.Length; i++)
{
char c = s[i];
if (IsEscape(s, i, inBacktick)) { i++; continue; }
if (c == '`') { inBacktick = !inBacktick; }
else if (!inBacktick)
{
@ -3685,15 +3914,53 @@ internal sealed class ExpressionEngine
else if (c == ']') depth--;
else if (c == ',' && depth == 0)
{
list.Add(s.Substring(start, i - start).Trim());
list.Add(TrimArg(s.Substring(start, i - start)));
start = i + 1;
}
}
}
list.Add(s.Substring(start).Trim());
list.Add(TrimArg(s.Substring(start)));
return list;
}
/// <summary>A backslash escape at <paramref name="i"/>: outside backticks '\' escapes any
/// character; inside them only "\`" and "\\" are escapes (other backslashes are text, so
/// a regex like `\d+` keeps its backslash).</summary>
private static bool IsEscape(string s, int i, bool inBacktick)
=> s[i] == '\\' && i + 1 < s.Length && (!inBacktick || s[i + 1] is '`' or '\\');
/// <summary>Trim, but keep an escaped trailing space ("abc\ ").</summary>
private static string TrimArg(string s)
{
string t = s.Trim();
if (t.Length < s.Length && t.Length > 0 && t[^1] == '\\')
{
int slashes = 0;
for (int i = t.Length - 1; i >= 0 && t[i] == '\\'; i--) slashes++;
int at = s.IndexOf(t, StringComparison.Ordinal) + t.Length;
if (slashes % 2 == 1 && at < s.Length) t += s[at];
}
return t;
}
/// <summary>Index just past the bracket that closes the one at <paramref name="open"/>
/// (or the end of the text), skipping backtick strings and escapes.</summary>
private static int FindClose(string s, int open, char openCh, char closeCh)
{
int depth = 0;
bool inBacktick = false;
for (int i = open; i < s.Length; i++)
{
if (IsEscape(s, i, inBacktick)) { i++; continue; }
char c = s[i];
if (c == '`') inBacktick = !inBacktick;
else if (inBacktick) continue;
else if (c == openCh) depth++;
else if (c == closeCh && --depth == 0) return i + 1;
}
return s.Length;
}
// ── Infix expression parser ───────────────────────────────────────────────
/// <summary>
@ -3708,9 +3975,40 @@ internal sealed class ExpressionEngine
private readonly string _s;
private int _p;
// > 0 while parsing the side of && / || that must not run: function calls and
// assignments are skipped (read for their length only), so "0 && echo[x]" echoes nothing.
private int _skip;
internal Parser(ExpressionEngine eng, string s) { _eng = eng; _s = s; }
internal string Run() => ParseOr();
/// <summary>
/// Expressions separated by ';' run in order; the value is the last one's
/// ("setvar[t, stopwatchcreate[]]; stopwatchstart[$t]"). Everything after the first
/// ';' used to be dropped.
/// </summary>
internal string Run()
{
string last = ParseOr();
while (true)
{
Ws();
if (_p >= _s.Length || _s[_p] != ';') break;
_p++;
Ws();
if (_p >= _s.Length) break;
if (_s[_p] == ';') continue;
last = ParseOr();
}
return last;
}
/// <summary>Parses (and so consumes) one operand without running anything in it.</summary>
private void Skip(Func<string> parse)
{
_skip++;
try { parse(); }
finally { _skip--; }
}
// ── Whitespace ────────────────────────────────────────────────────────
@ -3753,21 +4051,32 @@ internal sealed class ExpressionEngine
// ── Precedence levels ─────────────────────────────────────────────────
// Priority 1 (lowest): ||
// Priority 1 (lowest): || (short-circuit: a true left side skips the right side)
private string ParseOr()
{
var l = ParseAnd();
Ws();
while (Try("||")) { var r = ParseAnd(); l = ToBool(l) || ToBool(r) ? "1" : "0"; Ws(); }
while (Try("||"))
{
if (ToBool(l)) { Skip(ParseAnd); l = "1"; }
else l = ToBool(ParseAnd()) ? "1" : "0";
Ws();
}
return l;
}
// Priority 2: &&
// Priority 2: && (short-circuit: a false left side skips the right side, so
// "$debug && echo[...]" only echoes when debugging; it used to always run)
private string ParseAnd()
{
var l = ParseBitOr();
Ws();
while (Try("&&")) { var r = ParseBitOr(); l = ToBool(l) && ToBool(r) ? "1" : "0"; Ws(); }
while (Try("&&"))
{
if (!ToBool(l)) { Skip(ParseBitOr); l = "0"; }
else l = ToBool(ParseBitOr()) ? "1" : "0";
Ws();
}
return l;
}
@ -3921,7 +4230,7 @@ internal sealed class ExpressionEngine
Ws();
if (_p >= _s.Length) return "";
char c = _s[_p];
if (c is '`' or '$' or '(' or '~' or '-') return ParseUnary();
if (c is '`' or '$' or '@' or '(' or '~' or '-') return ParseUnary();
int wordEnd = _p;
while (wordEnd < _s.Length && (char.IsLetterOrDigit(_s[wordEnd]) || _s[wordEnd] == '_' || _s[wordEnd] == '.'))
@ -3938,7 +4247,7 @@ internal sealed class ExpressionEngine
else if (ch is ']' or ')') { if (depth == 0) break; depth--; }
else if (depth == 0)
{
if (ch == ',') break;
if (ch is ',' or ';') break;
if (q + 1 < _s.Length)
{
char n = _s[q + 1];
@ -3982,9 +4291,9 @@ internal sealed class ExpressionEngine
Ws();
if (_p < _s.Length && _s[_p] == ')') _p++;
_eng._parenDepth--;
return inner;
return ParseIndexes(inner);
}
return ParseAtom();
return ParseIndexes(ParseAtom());
}
/// <summary>
@ -3997,16 +4306,19 @@ internal sealed class ExpressionEngine
if (_p >= _s.Length) return "";
// Backtick string literal: `content` → content (verbatim, no evaluation)
// \` inside the string is an escaped backtick (needed for nested expressions).
// \` inside the string is an escaped backtick (needed for nested expressions), and
// \\ is one backslash: real metas nest "`chatbox[\\/vt forcebuff]`" (the inner text
// is then "\/vt forcebuff") and write the regex `\\d+`. Any other \x stays as is,
// as in the reference's `\d+`.
if (_s[_p] == '`')
{
_p++; // consume opening backtick
var sb = new System.Text.StringBuilder();
while (_p < _s.Length && _s[_p] != '`')
{
if (_s[_p] == '\\' && _p + 1 < _s.Length && _s[_p + 1] == '`')
if (_s[_p] == '\\' && _p + 1 < _s.Length && _s[_p + 1] is '`' or '\\')
{
sb.Append('`');
sb.Append(_s[_p + 1]);
_p += 2;
}
else
@ -4018,18 +4330,10 @@ internal sealed class ExpressionEngine
return sb.ToString();
}
// $name — shorthand for getvar[name]
if (_s[_p] == '$')
{
_p++;
int vs = _p;
while (_p < _s.Length && (char.IsLetterOrDigit(_s[_p]) || _s[_p] == '_'))
_p++;
string varName = _s.Substring(vs, _p - vs);
// Same as getvar[name]: an unset variable reads "0" (it read "", so
// '$kills == 0' was false until kills was first set).
return _eng._variables.TryGetValue(varName, out string? vv) ? vv ?? "" : "0";
}
// $name / @name / &name: getvar / getpvar / getgvar shorthand
if (_s[_p] == '$' || _s[_p] == '@'
|| (_s[_p] == '&' && _p + 1 < _s.Length && (char.IsLetterOrDigit(_s[_p + 1]) || _s[_p + 1] == '_')))
return ParseVariable();
// Hex literal: 0x / 0X (positive or negative)
bool negHex = _s[_p] == '-' && _p + 2 < _s.Length && _s[_p + 1] == '0' && (_s[_p + 2] == 'x' || _s[_p + 2] == 'X');
@ -4058,31 +4362,147 @@ internal sealed class ExpressionEngine
int start = _p;
// Identifier (letters, digits, underscores, dots for decimal numbers)
while (_p < _s.Length && (char.IsLetterOrDigit(_s[_p]) || _s[_p] == '_' || _s[_p] == '.'))
_p++;
// A word: letters, digits, underscores, dots (decimal numbers), and backslash
// escapes, each of which stands for the character after it ("p\@cMan\$" = p@cMan$).
var word = new System.Text.StringBuilder();
bool escaped = false;
ReadWord(word, ref escaped);
if (_p < _s.Length && _s[_p] == '[')
if (!escaped && _p > start && _p < _s.Length && _s[_p] == '[')
{
// Function call: consume '[' and scan to its matching ']'
_p++;
int depth = 1;
while (_p < _s.Length && depth > 0)
{
if (_s[_p] == '[') depth++;
else if (_s[_p] == ']') depth--;
_p++;
}
// Function call: scan to the matching ']' (backticks and escapes skipped)
_p = FindClose(_s, _p, '[', ']');
// Pass the entire "funcname[args]" string to EvaluatePrimary
// (not on the skipped side of && / ||: nothing in it may run)
if (_skip > 0) return "0";
return _eng.EvaluatePrimary(_s.Substring(start, _p - start));
}
if (_p > start)
return _eng.EvaluatePrimary(_s.Substring(start, _p - start));
if (_p == start)
{
// Skip unrecognised characters (guards against infinite loops). A ';' is left
// for Run(), which starts the next expression there.
if (_s[_p] != ';') _p++;
return "";
}
// Skip unrecognised characters (guards against infinite loops)
_p++;
return "";
// Text of letters and spaces needs no escaping, so the words that follow (with
// the spaces between them) are part of it: "echo[Uses dispel gems,15]". Only the
// first word used to be kept. A number stays one word ("\1\2\3 test" is how the
// reference writes text that starts with digits).
bool number = !escaped && char.IsDigit(_s[start]);
bool words = !number && ReadMoreWords(word, ref escaped);
string text = word.ToString();
// "Although there are keywords for true/false, internally they represent number 1/0."
if (!escaped && !words)
{
if (text.Equals("true", StringComparison.OrdinalIgnoreCase)) return "1";
if (text.Equals("false", StringComparison.OrdinalIgnoreCase)) return "0";
}
return text;
}
/// <summary>
/// $name, @name, &amp;name: a memory, persistent or global variable (the reference's
/// shorthand for getvar / getpvar / getgvar; only $ was supported). The name may be a
/// function call whose value is the name ("$wobjectgetname[wobjectgetplayer[]]"), and
/// "$name[1:3]" is a slice. "$name = value" assigns (not in the reference, but UB has
/// it and real metas use it ~500 times): the value is everything up to &amp;&amp;, ||, ';' or
/// the end, so "$x=listfilter[...] &amp;&amp; listcount[$x]>0" sets x to the list.
/// </summary>
private string ParseVariable()
{
char sigil = _s[_p++];
int ns = _p;
while (_p < _s.Length && (char.IsLetterOrDigit(_s[_p]) || _s[_p] == '_')) _p++;
if (_p == ns) return ""; // a stray sigil: as before
string name = _s.Substring(ns, _p - ns);
string? slice = null;
if (_p < _s.Length && _s[_p] == '[')
{
int close = FindClose(_s, _p, '[', ']');
string inner = _s.Substring(_p + 1, Math.Max(0, close - _p - 2));
if (TopLevelColon(inner) >= 0) slice = inner;
else name = _skip > 0 ? "" : _eng.EvaluatePrimary(_s.Substring(ns, close - ns));
_p = close;
}
if (slice == null)
{
int save = _p;
Ws();
if (_p < _s.Length && _s[_p] == '=' && (_p + 1 >= _s.Length || _s[_p + 1] != '='))
{
_p++;
string value = ParseBitOr();
return _skip > 0 ? value : _eng.WriteVar(sigil, name, value);
}
_p = save;
}
string v = _eng.ReadVar(sigil, name);
return slice == null || _skip > 0 ? v : _eng.SliceBy(v, slice);
}
/// <summary>x{key} after a value: list item, dictionary value or character; x{a:b} slices.
/// Repeats: "$commands{$name}{params}".</summary>
private string ParseIndexes(string value)
{
while (_p < _s.Length && _s[_p] == '{')
{
int close = FindClose(_s, _p, '{', '}');
string inner = _s.Substring(_p + 1, Math.Max(0, close - _p - 2));
_p = close;
if (_skip > 0) continue;
value = TopLevelColon(inner) >= 0
? _eng.SliceBy(value, inner)
: _eng.IndexValue(value, _eng.Evaluate(inner));
}
return value;
}
private static bool IsWordChar(char c) => char.IsLetterOrDigit(c) || c == '_' || c == '.';
private void ReadWord(System.Text.StringBuilder sb, ref bool escaped)
{
while (_p < _s.Length)
{
char c = _s[_p];
if (IsWordChar(c)) { sb.Append(c); _p++; }
else if (c == '\\' && _p + 1 < _s.Length) { sb.Append(_s[_p + 1]); _p += 2; escaped = true; }
else break;
}
}
/// <summary>
/// Appends the words that follow the one just read, with the spaces between them.
/// Spaces before a '+' are kept too ("\/vt nav load +getpvar[HuntNav]" is the text
/// "/vt nav load " joined to the nav name); other leading and trailing spaces are not.
/// A word that is a function name ("text func[...]") is not taken.
/// </summary>
private bool ReadMoreWords(System.Text.StringBuilder sb, ref bool escaped)
{
bool any = false;
while (true)
{
int q = _p;
while (q < _s.Length && (_s[q] == ' ' || _s[q] == '\t')) q++;
if (q == _p || q >= _s.Length) break;
char n = _s[q];
if (n == '+') { sb.Append(_s, _p, q - _p); _p = q; break; }
if (!IsWordChar(n) && n != '\\') break;
int save = _p, saveLen = sb.Length;
sb.Append(_s, _p, q - _p);
_p = q;
bool e2 = false;
ReadWord(sb, ref e2);
if (!e2 && _p < _s.Length && _s[_p] == '[') { _p = save; sb.Length = saveLen; break; }
escaped |= e2;
any = true;
}
return any;
}
}
}

View file

@ -135,6 +135,13 @@ internal sealed class MetaManager
public void SetMtCommandHandler(Func<string, bool> handler) => _mtCommandHandler = handler;
public void SetRaCommandHandler(Action<string> handler) => _raCommandHandler = handler;
/// <summary>Embedded Nav Route's "Patrol" (any case): the dungeon patrol instead of a route,
/// unless the meta or NavProfiles has a route by that name.</summary>
internal const string PatrolRoute = "Patrol";
internal static bool IsPatrolRoute(string routeName) =>
string.Equals(routeName?.Trim(), PatrolRoute, StringComparison.OrdinalIgnoreCase);
public void SetObjectCache(WorldObjectCache cache)
{
_objectCache = cache;
@ -923,6 +930,18 @@ internal sealed class MetaManager
}
}
// "Patrol" with no route of that name: the dungeon patrol (/ra dunnav-patrol, a
// circular hunt through every cell of this dungeon, no nav file). The Meta panel
// offers it first in Embedded Nav Route's list. A real route called Patrol wins.
if (IsPatrolRoute(routeName) && !_settings.EmbeddedNavs.ContainsKey(routeName)
&& !File.Exists(Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "NavProfiles", routeName + ".nav")))
{
_host.Log("[Meta] EmbedNav: Patrol -> /ra dunnav-patrol");
if (_raCommandHandler != null) _raCommandHandler("/ra dunnav-patrol");
else _host.WriteToChat("[RynthAi Meta] Patrol: no /ra command handler", 1);
break;
}
if (_settings.EmbeddedNavs.TryGetValue(routeName, out var embedded))
{
var newRoute = NavRouteParser.LoadFromLines(embedded);

View file

@ -19,12 +19,14 @@ namespace RynthCore.Plugin.RynthAi.Meta;
internal static class MetaRuleEdits
{
/// <summary>Puts <paramref name="edited"/> at <paramref name="index"/>, keeping the old rule's
/// runtime latch and the fields the panel can't send. False when the index is out of range.</summary>
public static bool Replace(List<MetaRule> rules, int index, MetaRule edited)
/// runtime latch and the fields the panel can't send. <paramref name="keepName"/>: the edit came
/// from an engine without rule names, so the rule keeps its name. False when the index is out of range.</summary>
public static bool Replace(List<MetaRule> rules, int index, MetaRule edited, bool keepName = false)
{
if (index < 0 || index >= rules.Count) return false;
MetaRule old = rules[index];
KeepHidden(old, edited);
if (keepName) edited.Name = old.Name;
edited.HasFired = old.HasFired;
edited.LastFiredAt = old.LastFiredAt;
rules[index] = edited;

View file

@ -636,6 +636,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_combatManager = new CombatManager(Host, _dashboard.Settings, _objectCache!, _spellManager);
_combatManager.SetWeaponSwapGate(_weaponSwapGate);
_combatManager.HoldIdlePeace = LootHoldsIdlePeace;
_combatManager.ManaReserveHold = spellId => _buffManager?.OffensiveCastHold(spellId); // the mana reserve
_combatManager.SetStaleBusyCallback(OnCombatBusyStale);
_buffManager?.SetStaleBusyCallback(OnCombatBusyStale); // a heal ahead of a leftover busy count
if (_buffManager != null)
@ -1333,6 +1334,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
if (_loginComplete) TickAwakenedTier();
// A stop the action pacing held (nothing of ours moving, a server action unanswered)
// goes out as soon as the server has answered: a stop is never dropped (2026-10-12).
if (_loginComplete) RynthCore.Plugin.Shared.MoveAudit.FlushPendingStops(Host, "once the server answered");
// Periodically flush the creature profile store (~ every 5 seconds at 60Hz).
if (++_creatureSaveTickCounter >= 300)
{
@ -2052,6 +2057,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_buffManager?.OnChatWindowText(text, chatType);
_manaStoneManager?.OnChatWindowText(text);
_petManager?.OnChatWindowText(text);
_combatManager?.TraceCastChat(text, chatType);
_combatManager?.HandleChatForDebuffs(text);
_combatManager?.HandleChatForDamage(text);
_missileCraftingManager?.HandleChat(text);
@ -2149,6 +2155,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
/// </summary>
private bool IsFightableCreature(uint objectId)
{
if (IsPlayerOrPet(objectId)) return false;
WorldObject? obj = _objectCache?[unchecked((int)objectId)];
if (obj != null && obj.ObjectClass is AcObjectClass.Npc or AcObjectClass.Vendor
or AcObjectClass.Player or AcObjectClass.CombatPet)
@ -2156,6 +2163,30 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
return !Host.HasObjectIsAttackable || Host.ObjectIsAttackable(objectId);
}
// PublicWeenieDesc bitfield BF_PLAYER, and PropertyInstanceId PetOwner.
private const uint BfPlayer = 0x8;
private const uint PropIidPetOwner = 44;
/// <summary>
/// Your own character, another player, or someone's pet or summon: never a monster row or
/// a creatures.json entry, whatever the object cache calls it. The cache files any creature
/// whose type reads before anything else as a Monster - other players do, and so did your
/// own character when something looked it up through the cache - and players are
/// attackable, so the class and attackable checks alone let them through (the character's
/// own row in the Damage tab, 2026-10-11). Checked without the cache: the id, the player
/// guid range, the weenie's player flag, a pet owner, and the player weenies.
/// </summary>
private bool IsPlayerOrPet(uint objectId, uint wcid = 0)
{
if (objectId == 0) return false;
if (objectId == _playerId || objectId == Host.GetPlayerId()) return true;
if (CreatureData.PlayerWeenies.IsPlayerGuid(objectId)) return true;
if (Host.HasGetObjectBitfield && Host.TryGetObjectBitfield(objectId, out uint bf) && (bf & BfPlayer) != 0) return true;
if (Host.TryGetObjectInstanceIdProperty(objectId, PropIidPetOwner, out uint owner) && owner != 0) return true;
if (wcid == 0 && Host.HasGetObjectWcid) Host.TryGetObjectWcid(objectId, out wcid);
return CreatureData.PlayerWeenies.IsPlayerWcid(wcid);
}
// Exact per-hit damage from the engine (AttackerNotification 0x01B1). This is
// the only selection-free source of real damage numbers — combat uses it to
// learn per-monster damage and predict kill shots. isAttacker==true = our hit.
@ -2185,6 +2216,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
foreach (var r in rows.OrderByDescending(x => x.KillSamples)
.ThenBy(x => x.Element, StringComparer.OrdinalIgnoreCase))
{
if (CreatureData.PlayerWeenies.IsPlayerWcid(r.Wcid)) continue; // a player character's row, never a monster
string name = "wcid " + r.Wcid.ToString();
double hp = 0;
if (_creatureStore != null && _creatureStore.TryGetByWcid(r.Wcid, out var prof) && prof != null)
@ -2206,9 +2238,20 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
return sb.ToString();
}
/// <summary>Structured per-monster learning for the interactive Damage panel.
/// One JSON object per (monster, weapon, spell) row. Polled live by the engine
/// MonsterDamagePanel via RynthPluginGetMonsterDamageJson.</summary>
/// <summary>Structured per-monster learning for the interactive Damage panel: the Default
/// line, then ONE row per monster name. Polled live by the engine DamageFace via
/// RynthPluginGetMonsterDamageJson.
///
/// Rows come from the learned rows (monster_damage.txt), the monsters appraised this
/// session and the monsters on this landblock. Player characters (yours included) and
/// pets are never rows (<see cref="IsPlayerOrPet"/>, <see cref="CreatureData.PlayerWeenies"/>).
///
/// One row per NAME: a server often has several weenies of one monster (retail has five
/// "Rampager"s: 10810, 10811, 16916, 21526, 22599), and each wcid used to be a row of its
/// own, so two Rampagers side by side were two identical-looking rows, one with the kills
/// and one without (2026-10-11). The learned data stays per wcid; the row adds it up,
/// lists the wcids in "wcids" (the panel shows "(2 kinds)"), and a weapon, offhand, pet,
/// HP or removal on it applies to every one of them (<see cref="DamageGroupOf"/>).</summary>
public string BuildMonsterDamageJson()
{
var store = _damageStore;
@ -2230,13 +2273,13 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
}
string NameOf(uint id, string prefix) => id == 0 ? "" : WeaponLabel(id, prefix);
// Group the per-(weapon,element,tier) stat rows by MONSTER (wcid). The Damage tab now
// shows ONE collapsed row per monster (latest tier used + total kills); the per-tier
// breakdown rides along in a nested "tiers" array for the expand drawer.
// The per-(weapon,element,tier) stat rows by wcid. Rows a player left behind are skipped
// (the store drops them when it loads; this covers a file loaded before that).
var byWcid = new Dictionary<uint, List<CreatureData.MonsterDamageStore.DamageRow>>();
var order = new List<uint>();
foreach (var r in rows)
{
if (CreatureData.PlayerWeenies.IsPlayerWcid(r.Wcid)) continue;
if (!byWcid.TryGetValue(r.Wcid, out var glist)) { glist = new(); byWcid[r.Wcid] = glist; order.Add(r.Wcid); }
glist.Add(r);
}
@ -2250,10 +2293,33 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
return string.IsNullOrEmpty(name) ? "wcid " + wcid : name;
}
// Every monster to list, grouped by name: learned first, then appraised this session
// (not yet fought), then nearby.
uint[] seen;
lock (_seenMonstersThisSession) seen = System.Linq.Enumerable.ToArray(_seenMonstersThisSession);
var groups = new Dictionary<string, List<uint>>(StringComparer.OrdinalIgnoreCase);
var listed = new HashSet<uint>();
void Add(uint w, string rowName)
{
if (w == 0 || CreatureData.PlayerWeenies.IsPlayerWcid(w) || !listed.Add(w)) return;
string n = ResolveName(w, rowName);
if (!groups.TryGetValue(n, out var g)) groups[n] = g = new List<uint>();
g.Add(w);
}
foreach (uint w in order) Add(w, byWcid[w].Count > 0 ? byWcid[w][0].Name : "");
foreach (uint w in seen) Add(w, _jsonNearby.TryGetValue(w, out string? sn) ? sn : "");
foreach (var kv in _jsonNearby) Add(kv.Key, kv.Value);
int KillsOf(uint w)
{
int k = 0;
if (byWcid.TryGetValue(w, out var l)) foreach (var x in l) k += x.KillSamples;
return k;
}
var groupOf = new Dictionary<uint, uint[]>();
var sb = new System.Text.StringBuilder();
sb.Append('[');
bool first = true;
var emittedWcids = new HashSet<uint>();
// The DEFAULT line (top row). Carries the per-character default weapon; the panel renders
// it specially (weapon picker + chevron → the Default debuff/shape rule). isDefault=true.
@ -2269,43 +2335,55 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
.Append("\"bestWid\":0,\"bestWeapon\":\"\",\"assignedOff\":0,\"assignedOffName\":\"\",")
.Append("\"key\":\"__default__\",\"tiers\":[]")
.Append('}');
first = false;
// STABLE order by monster name (then wcid) so rows don't reshuffle as counters tick.
foreach (uint wcid in order.OrderBy(w => ResolveName(w, byWcid[w].Count > 0 ? byWcid[w][0].Name : ""),
StringComparer.OrdinalIgnoreCase).ThenBy(w => w))
foreach (var grp in groups.OrderBy(g => g.Key, StringComparer.OrdinalIgnoreCase).ThenBy(g => g.Value.Min()))
{
var glist = byWcid[wcid];
emittedWcids.Add(wcid);
string name = ResolveName(wcid, glist.Count > 0 ? glist[0].Name : "");
var hpAt = HpAt(wcid, vt);
bool hpManual = hpAt.Manual;
double hp = hpAt.Hp;
string name = grp.Key;
// The row's own wcid (what the panel's edits, details and removal name): the one with
// the most kills, then one with anything learned, then the lowest.
uint[] members = grp.Value.OrderByDescending(KillsOf).ThenByDescending(w => byWcid.ContainsKey(w))
.ThenBy(w => w).ToArray();
uint wcid = members[0];
uint[] wcids = members.OrderBy(w => w).ToArray();
if (wcids.Length > 1) foreach (uint w in wcids) groupOf[w] = wcids;
var glist = new List<CreatureData.MonsterDamageStore.DamageRow>();
foreach (uint w in members) if (byWcid.TryGetValue(w, out var l)) glist.AddRange(l);
// HP: a manual one on any of them wins (they are set together), else the first known.
(double Hp, bool Manual, bool Estimated, string Source) hpAt = default;
foreach (uint w in members)
{
var h = HpAt(w, vt, learned: byWcid.ContainsKey(w));
if (h.Manual) { hpAt = h; break; }
if (hpAt.Hp <= 0 && h.Hp > 0) hpAt = h;
}
int latestTier = store.GetLastTier(wcid); // negative = ring
int totalKills = 0; foreach (var x in glist) totalKills += x.KillSamples;
// Representative entry for the collapsed row's crit/casts = the latest-tier one,
// else the most-killed one.
// Representative entry for the collapsed row's crit/casts = the latest-tier one
// (the row's own wcid first), else the most-killed one.
CreatureData.MonsterDamageStore.DamageRow m = default; bool haveM = false;
foreach (var x in glist) if (x.Tier == latestTier) { m = x; haveM = true; break; }
if (!haveM) { int bk = -1; foreach (var x in glist) if (x.KillSamples > bk) { bk = x.KillSamples; m = x; haveM = true; } }
uint assignedWid = store.GetManualWeapon(wcid);
uint bestWid = BestFor(wcid);
uint assignedOff = store.GetManualOffhand(wcid);
uint assignedWid = 0, assignedOff = 0; string pet = "";
foreach (uint w in members) { assignedWid = store.GetManualWeapon(w); if (assignedWid != 0) break; }
foreach (uint w in members) { assignedOff = store.GetManualOffhand(w); if (assignedOff != 0) break; }
foreach (uint w in members) { pet = store.GetManualPet(w); if (pet.Length > 0) break; }
uint bestWid = BestFor(wcid);
if (!first) sb.Append(',');
first = false;
sb.Append('{')
sb.Append(",{")
.Append("\"wcid\":").Append(wcid).Append(',')
.Append("\"name\":").Append(JsonStr(name)).Append(',')
.Append("\"wid\":").Append(haveM ? m.WeaponId : 0).Append(',')
.Append("\"weapon\":").Append(JsonStr(haveM ? NameOf(m.WeaponId, "Weapon") : "")).Append(',')
.Append("\"elem\":").Append(JsonStr(haveM ? (m.Element ?? "") : "")).Append(',')
.Append("\"tier\":").Append(latestTier).Append(',')
.Append("\"hp\":").Append((int)Math.Round(hp)).Append(',')
.Append("\"hpManual\":").Append(hpManual ? "true" : "false").Append(',')
.Append("\"hp\":").Append((int)Math.Round(hpAt.Hp)).Append(',')
.Append("\"hpManual\":").Append(hpAt.Manual ? "true" : "false").Append(',')
.Append(hpAt.Estimated ? "\"hpEst\":true," : "")
.Append("\"crit\":").Append(JsonNum(haveM ? m.AvgCritDamage : 0)).Append(',')
.Append("\"critN\":").Append(haveM ? m.CritSamples : 0).Append(',')
@ -2319,13 +2397,17 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
.Append("\"bestWeapon\":").Append(JsonStr(NameOf(bestWid, "Weapon"))).Append(',')
.Append("\"assignedOff\":").Append(assignedOff).Append(',')
.Append("\"assignedOffName\":").Append(JsonStr(NameOf(assignedOff, "Offhand"))).Append(',')
.Append("\"pet\":").Append(JsonStr(store.GetManualPet(wcid))).Append(',')
.Append("\"petLabel\":").Append(JsonStr(PetChoiceLabel(store.GetManualPet(wcid)))).Append(',')
.Append(WeakJson(wcid, name))
.Append("\"key\":").Append(JsonStr(wcid.ToString())).Append(',')
.Append("\"pet\":").Append(JsonStr(pet)).Append(',')
.Append("\"petLabel\":").Append(JsonStr(PetChoiceLabel(pet))).Append(',')
.Append(WeakJson(wcid, name, wcids));
if (wcids.Length > 1) sb.Append("\"wcids\":[").Append(string.Join(",", wcids)).Append("],");
sb.Append("\"key\":").Append(JsonStr(wcid.ToString())).Append(',')
.Append("\"tiers\":[");
// The per-tier drawer: one line per (weapon, element, spell tier), the kinds' numbers
// added up (kills summed, averages weighted by their samples).
bool tf = true;
foreach (var x in glist.OrderByDescending(z => z.KillSamples).ThenByDescending(z => z.Tier))
foreach (var x in MergeTierRows(glist).OrderByDescending(z => z.KillSamples).ThenByDescending(z => z.Tier))
{
if (!tf) sb.Append(',');
tf = false;
@ -2344,53 +2426,53 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
sb.Append("]}");
}
// Bare rows for monsters appraised this session but not yet fought (one per wcid), so the
// table populates as you ID nearby mobs. HP from creatures.json (appraised); empty tiers.
uint[] seen;
lock (_seenMonstersThisSession) seen = System.Linq.Enumerable.ToArray(_seenMonstersThisSession);
foreach (uint wcid in seen.Concat(_jsonNearby.Keys))
{
if (emittedWcids.Contains(wcid)) continue;
emittedWcids.Add(wcid);
string name = ResolveName(wcid, _jsonNearby.TryGetValue(wcid, out string? nearName) ? nearName : "");
var hpAt = HpAt(wcid, vt, learned: false);
bool hpManual = hpAt.Manual;
double hp = hpAt.Hp;
uint assignedWid = store.GetManualWeapon(wcid);
uint bestWid = BestFor(wcid);
uint assignedOff = store.GetManualOffhand(wcid);
int latestTier = store.GetLastTier(wcid);
if (!first) sb.Append(',');
first = false;
sb.Append('{')
.Append("\"wcid\":").Append(wcid).Append(',')
.Append("\"name\":").Append(JsonStr(name)).Append(',')
.Append("\"wid\":0,\"weapon\":\"\",\"elem\":\"\",")
.Append("\"tier\":").Append(latestTier).Append(',')
.Append("\"hp\":").Append((int)Math.Round(hp)).Append(',')
.Append("\"hpManual\":").Append(hpManual ? "true" : "false").Append(',')
.Append(hpAt.Estimated ? "\"hpEst\":true," : "")
.Append("\"crit\":0,\"critN\":0,\"noncrit\":0,\"noncritN\":0,\"casts\":0,\"kills\":0,")
.Append("\"assignedWid\":").Append(assignedWid).Append(',')
.Append("\"assignedWeapon\":").Append(JsonStr(NameOf(assignedWid, "Weapon"))).Append(',')
.Append("\"bestWid\":").Append(bestWid).Append(',')
.Append("\"bestWeapon\":").Append(JsonStr(NameOf(bestWid, "Weapon"))).Append(',')
.Append("\"assignedOff\":").Append(assignedOff).Append(',')
.Append("\"assignedOffName\":").Append(JsonStr(NameOf(assignedOff, "Offhand"))).Append(',')
.Append("\"pet\":").Append(JsonStr(store.GetManualPet(wcid))).Append(',')
.Append("\"petLabel\":").Append(JsonStr(PetChoiceLabel(store.GetManualPet(wcid)))).Append(',')
.Append(WeakJson(wcid, name))
.Append("\"key\":").Append(JsonStr(wcid.ToString())).Append(',')
.Append("\"tiers\":[]")
.Append('}');
}
_damageGroups = groupOf;
sb.Append(']');
return sb.ToString();
}
/// <summary>
/// One entry per (weapon, element, spell tier) across a row's wcids: kills and samples
/// summed, casts to kill weighted by kills, crit and non-crit damage by their samples.
/// A single wcid's rows come back as they are (each key is there once).
/// </summary>
private static List<CreatureData.MonsterDamageStore.DamageRow> MergeTierRows(
List<CreatureData.MonsterDamageStore.DamageRow> rows)
{
var merged = new List<CreatureData.MonsterDamageStore.DamageRow>();
var at = new Dictionary<(uint, string, int), int>();
foreach (var x in rows)
{
var key = (x.WeaponId, x.Element ?? "", x.Tier);
if (!at.TryGetValue(key, out int i)) { at[key] = merged.Count; merged.Add(x); continue; }
var a = merged[i];
static double W(double av, int an, double bv, int bn) => an + bn > 0 ? (av * an + bv * bn) / (an + bn) : Math.Max(av, bv);
merged[i] = a with
{
AvgDamage = W(a.AvgDamage, a.DmgSamples, x.AvgDamage, x.DmgSamples),
DmgSamples = a.DmgSamples + x.DmgSamples,
AvgCritDamage = W(a.AvgCritDamage, a.CritSamples, x.AvgCritDamage, x.CritSamples),
CritSamples = a.CritSamples + x.CritSamples,
AvgNonCritDamage = W(a.AvgNonCritDamage, a.NonCritSamples, x.AvgNonCritDamage, x.NonCritSamples),
NonCritSamples = a.NonCritSamples + x.NonCritSamples,
AvgCastsToKill = W(a.AvgCastsToKill, a.KillSamples, x.AvgCastsToKill, x.KillSamples),
KillSamples = a.KillSamples + x.KillSamples,
};
}
return merged;
}
/// <summary>
/// wcid -> every wcid of its Damage-tab row, for rows of more than one kind (same name),
/// from the last <see cref="BuildMonsterDamageJson"/>. Swapped whole, never changed.
/// </summary>
private volatile Dictionary<uint, uint[]> _damageGroups = new();
/// <summary>The wcids a Damage-tab edit on <paramref name="wcid"/>'s row applies to: its row's
/// kinds, or just itself.</summary>
internal uint[] DamageGroupOf(uint wcid)
=> _damageGroups.TryGetValue(wcid, out uint[]? g) ? g : new[] { wcid };
/// <summary>"weak" (top elements with multipliers) and "weakSrc" fields for a Damage-tab row, each followed by a comma.</summary>
private uint _jsonTargetWcid;
private int _jsonViewTier; // the difficulty tier BuildMonsterDamageJson is writing (WeakJson reads it)
@ -2411,9 +2493,12 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
uint uid = unchecked((uint)wo.Id);
// Attackable only: NPCs the object cache classifies as monsters would otherwise
// be added as Damage-tab rows here (e52ccc8 closed the appraisal path only).
// IsFightableCreature also turns away your own character, other players and pets,
// which the cache can class as monsters (IsPlayerOrPet).
if (!IsFightableCreature(uid)) continue;
if (!Host.TryGetObjectPosition(uid, out uint cell, out _, out _, out _) || (cell >> 16) != myBlock) continue;
if (Host.TryGetObjectWcid(uid, out uint w) && w != 0 && !map.ContainsKey(w)) map[w] = wo.Name ?? "";
if (Host.TryGetObjectWcid(uid, out uint w) && w != 0 && !CreatureData.PlayerWeenies.IsPlayerWcid(w)
&& !map.ContainsKey(w)) map[w] = wo.Name ?? "";
}
return map;
}
@ -2427,14 +2512,23 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
return Host.TryGetObjectWcid(unchecked((uint)id), out uint w) ? w : 0;
}
private string WeakJson(uint wcid, string name)
/// <summary>A row's "weak", "weakSrc", "secKill", "hitRate", "targeted" and "nearby" fields, each followed
/// by a comma. Targeted / nearby when any of <paramref name="wcids"/> (the row's kinds) is.</summary>
private string WeakJson(uint wcid, string name, uint[] wcids)
{
var r = _combatManager?.WeaknessFor(wcid, name);
var (sec, hit) = _damageStore?.GetSummary(wcid, _jsonViewTier) ?? (-1, -1);
bool targeted = false, nearby = false;
foreach (uint w in wcids)
{
if (w == 0) continue;
targeted |= w == _jsonTargetWcid;
nearby |= _jsonNearby.ContainsKey(w);
}
return "\"weak\":" + JsonStr(r?.Describe() ?? "") + ",\"weakSrc\":" + JsonStr(r?.Source ?? "")
+ ",\"secKill\":" + JsonNum(sec) + ",\"hitRate\":" + JsonNum(hit)
+ ",\"targeted\":" + (wcid != 0 && wcid == _jsonTargetWcid ? "true" : "false")
+ ",\"nearby\":" + (wcid != 0 && _jsonNearby.ContainsKey(wcid) ? "true" : "false") + ",";
+ ",\"targeted\":" + (targeted ? "true" : "false")
+ ",\"nearby\":" + (nearby ? "true" : "false") + ",";
}
/// <summary>
@ -2542,7 +2636,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
// Off Aelrynth the tier is 0 and this is the value as typed, as before.
int vt = DamageViewDifficulty;
double value = hp > 0 && vt > 0 ? hp / CreatureData.AwakenedTier.HealthScale(vt) : hp;
_damageStore.SetManualHp(wcid, value);
foreach (uint w in DamageGroupOf(wcid)) _damageStore.SetManualHp(w, value); // every kind of the row
_damageStore.SaveIfDirty();
}
@ -2670,7 +2764,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
public void SetMonsterWeapon(uint wcid, uint weaponId)
{
if (_damageStore == null) return;
_damageStore.SetManualWeapon(wcid, weaponId);
foreach (uint w in DamageGroupOf(wcid)) _damageStore.SetManualWeapon(w, weaponId);
_damageStore.SaveIfDirty();
}
@ -2687,7 +2781,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
public void SetMonsterOffhand(uint wcid, uint offhandId)
{
if (_damageStore == null) return;
_damageStore.SetManualOffhand(wcid, offhandId);
foreach (uint w in DamageGroupOf(wcid)) _damageStore.SetManualOffhand(w, offhandId);
_damageStore.SaveIfDirty();
}
@ -2695,7 +2789,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
public void SetMonsterPet(uint wcid, string choice)
{
if (_damageStore == null) return;
_damageStore.SetManualPet(wcid, choice);
foreach (uint w in DamageGroupOf(wcid)) _damageStore.SetManualPet(w, choice);
_damageStore.SaveIfDirty();
}
@ -2764,8 +2858,13 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
// and monsters from another server couldn't be cleared (2026-09-29).
if (uint.TryParse(key, out uint onlyWcid))
{
bool gone = _damageStore.DeleteWcid(onlyWcid);
lock (_seenMonstersThisSession) gone |= _seenMonstersThisSession.Remove(onlyWcid);
// A row of several kinds (same name) goes as a whole.
bool gone = false;
foreach (uint w in DamageGroupOf(onlyWcid))
{
gone |= _damageStore.DeleteWcid(w);
lock (_seenMonstersThisSession) gone |= _seenMonstersThisSession.Remove(w);
}
_damageStore.SaveIfDirty();
return gone;
}
@ -2864,6 +2963,9 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
uint wcid = 0;
if (Host.HasGetObjectWcid) Host.TryGetObjectWcid(targetId, out wcid);
// Appraising yourself, another player or a pet returns health too: never creature
// data, never a Damage-tab row (the caller checks the same; this is the store's door).
if (IsPlayerOrPet(targetId, wcid)) return;
var sample = new CreatureData.CreatureProfile
{
@ -3205,6 +3307,9 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
case "autotrade": HandleAutoTradeRaCommand(parts); break;
case "trade": HandleTradeCommand(parts); break;
case "busyinfo": HandleBusyInfoCommand(); break;
// /ra quit | /ra exit: close the client (the engine's /rc quit: as its close button)
case "quit":
case "exit": if (Host.HasInvokeChatParser) Host.InvokeChatParser("/rc quit"); break;
// give variants — first-match (with optional count prefix)
case "give": HandleGiveCommand(parts, GiveItemMatch.Exact, partialPlayer: false); break;
case "givep": HandleGiveCommand(parts, GiveItemMatch.Partial, partialPlayer: false); break;

View file

@ -4,10 +4,15 @@ using System.Text;
namespace RynthCore.Plugin.RynthChat;
/// <summary>
/// The newest 500 chat lines, exported to the engine as JSON
/// The newest chat lines, exported to the engine as JSON
/// (RynthChatGetScrollbackJson). Add runs on the game thread (chat dispatch),
/// BuildJson on the engine's pump thread; the lock covers both.
///
/// How many: DefaultCapacity until the engine says otherwise
/// (RynthChatSetCapacity, from the chat setting "Chat history"; 0.3.0). It was
/// a fixed 500 before. Changing it keeps the newest lines and never touches the
/// numbering: the engine (and its Discord relay) tell new lines from old by seq.
///
/// JSON per line: {"seq":N,"ts":"HH:mm:ss","chan":"Chat","type":3,"sender":"Bob"|null,"text":"..."}.
/// "type" (AC's ChatMessageType) was added in 0.2.0; engines before it ignore it.
/// Every non-ASCII character is written as a \uXXXX escape, so the export is
@ -16,14 +21,55 @@ namespace RynthCore.Plugin.RynthChat;
/// </summary>
internal sealed class ChatBuffer
{
private const int Capacity = 500;
/// <summary>The engine's default for "Chat history" (ChatHistory.DefaultLines there).</summary>
internal const int DefaultCapacity = 2000;
internal const int MinCapacity = 100;
internal const int MaxCapacity = 10000;
private readonly ChatLine[] _ring = new ChatLine[Capacity];
private readonly object _lock = new();
private int _head; // next write index (mod Capacity)
private int _count; // total items stored (≤ Capacity)
private ChatLine?[] _ring;
private readonly object _lock = new();
private int _head; // next write index (mod _ring.Length)
private int _count; // lines stored (<= _ring.Length)
private ulong _nextSeq = 1;
internal ChatBuffer(int capacity = DefaultCapacity)
{
_ring = new ChatLine?[Math.Clamp(capacity, MinCapacity, MaxCapacity)];
}
internal int Capacity
{
get { lock (_lock) return _ring.Length; }
}
internal int Count
{
get { lock (_lock) return _count; }
}
/// <summary>
/// Keeps up to <paramref name="capacity"/> lines from now on (clamped to
/// MinCapacity..MaxCapacity); when it shrinks, the oldest go. Returns the capacity
/// applied. Any thread.
/// </summary>
internal int SetCapacity(int capacity)
{
capacity = Math.Clamp(capacity, MinCapacity, MaxCapacity);
lock (_lock)
{
if (capacity == _ring.Length) return capacity;
int keep = Math.Min(_count, capacity);
var ring = new ChatLine?[capacity];
int oldCap = _ring.Length;
int start = (_head - keep + oldCap) % oldCap; // the oldest line kept
for (int i = 0; i < keep; i++) ring[i] = _ring[(start + i) % oldCap];
_ring = ring;
_count = keep;
_head = keep % capacity;
return capacity;
}
}
internal void Add(string? text, int chatType)
{
if (string.IsNullOrEmpty(text)) return;
@ -37,7 +83,7 @@ internal sealed class ChatBuffer
{
// Numbered under the lock, so the ring is always in seq order (the
// engine skips anything at or below the last seq it has seen).
_ring[_head % Capacity] = new ChatLine
_ring[_head] = new ChatLine
{
Seq = _nextSeq++,
Timestamp = ts,
@ -46,33 +92,36 @@ internal sealed class ChatBuffer
Sender = sender,
Text = text,
};
_head = (_head + 1) % Capacity;
if (_count < Capacity) _count++;
_head = (_head + 1) % _ring.Length;
if (_count < _ring.Length) _count++;
}
}
// Returns JSON array of lines with Seq > sinceSeq, oldest-first.
/// <summary>
/// The lines with Seq > sinceSeq as a JSON array, oldest first. Only those are
/// copied out under the lock: the ring holds consecutive seqs, so they are the
/// newest (newest seq - sinceSeq) lines. Until 0.3.0 the whole ring was cloned
/// and walked on every poll (10 a second), which grows with the history length.
/// </summary>
internal string BuildJson(ulong sinceSeq)
{
ChatLine[] snapshot;
int count;
int head;
ChatLine?[] lines;
lock (_lock)
{
snapshot = (ChatLine[])_ring.Clone();
count = _count;
head = _head;
ulong newest = _nextSeq - 1;
int n = sinceSeq >= newest ? 0 : (int)Math.Min((ulong)_count, newest - sinceSeq);
if (n == 0) return "[]";
lines = new ChatLine?[n];
int cap = _ring.Length;
int start = (_head - n + cap) % cap;
for (int i = 0; i < n; i++) lines[i] = _ring[(start + i) % cap];
}
var sb = new StringBuilder(256);
var sb = new StringBuilder(64 + lines.Length * 192);
sb.Append('[');
bool first = true;
// Iterate oldest→newest. Oldest entry is at (head - count + Capacity) % Capacity.
int start = (head - count + Capacity) % Capacity;
for (int i = 0; i < count; i++)
foreach (ChatLine? line in lines)
{
var line = snapshot[(start + i) % Capacity];
if (line == null || line.Seq <= sinceSeq) continue;
if (!first) sb.Append(',');

View file

@ -64,6 +64,18 @@ public static unsafe class PluginExports
}
}
/// <summary>
/// How many lines the scrollback keeps (the engine's "Chat history" setting; 0.3.0).
/// Returns the number applied (clamped to 100..10000), or 0 before the plugin is up.
/// Engines before it never call this, and the plugin keeps ChatBuffer.DefaultCapacity.
/// </summary>
[UnmanagedCallersOnly(EntryPoint = "RynthChatSetCapacity", CallConvs = new[] { typeof(CallConvCdecl) })]
public static int SetCapacity(int lines)
{
try { return Runtime.Plugin?.SetScrollbackCapacity(lines) ?? 0; }
catch { return 0; }
}
[UnmanagedCallersOnly(EntryPoint = "RynthChatSendLine", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void SendLine(IntPtr ansiText)
{

View file

@ -7,7 +7,7 @@ namespace RynthCore.Plugin.RynthChat;
public sealed class RynthChatPlugin : RynthPluginBase
{
internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("RynthChat");
internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.2.1");
internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.3.0");
private readonly ChatBuffer _buffer = new();
@ -42,6 +42,8 @@ public sealed class RynthChatPlugin : RynthPluginBase
internal string BuildScrollbackJson(ulong sinceSeq) => _buffer.BuildJson(sinceSeq);
internal int SetScrollbackCapacity(int lines) => _buffer.SetCapacity(lines);
// Called on the game thread from the engine's deferred chat dispatch
// (Win32Backend posts WM_RYNTHCORE_CHAT so this runs on a fresh, non-reentrant
// message dispatch rather than inline inside the Enter keystroke handler).

View file

@ -48,6 +48,9 @@ internal static class UiFormat
// Window flags
public const uint FlagVisible = 1u << 0;
public const uint FlagShowInBar = 1u << 1;
/// <summary>With ShowInBar: a bar button of its own instead of a Scripts menu line (engines from
/// 2026-10-11; older ones ignore it and list the window in the Scripts menu).</summary>
public const uint FlagBarButton = 1u << 11;
public const uint FlagNoScrollbar = 1u << 5;
// Image icon kinds (op level 2)

View file

@ -42,6 +42,9 @@ internal sealed class UiWindow
public string Title;
public bool Visible;
public bool ShowInBar = true;
/// <summary>With ShowInBar: the window has its own button on the RynthCore bar (title as the
/// tooltip) rather than a line in the Scripts menu.</summary>
public bool BarButton = true;
public float DefaultWidth, DefaultHeight, MinWidth, MinHeight;
/// <summary>A pass is wanted at the next chance (input arrived, it was just shown, data changed).</summary>
@ -80,7 +83,8 @@ internal sealed class UiWindow
Title = title;
}
public uint Flags => (Visible ? UiFormat.FlagVisible : 0) | (ShowInBar ? UiFormat.FlagShowInBar : 0);
public uint Flags => (Visible ? UiFormat.FlagVisible : 0) | (ShowInBar ? UiFormat.FlagShowInBar : 0)
| (ShowInBar && BarButton ? UiFormat.FlagBarButton : 0);
public bool HeaderDirty =>
_sentTitle != Title || _sentFlags != Flags || _sentDw != DefaultWidth || _sentDh != DefaultHeight

View file

@ -57,9 +57,12 @@ public sealed class RynthOraclePlugin : RynthPluginBase
{
DefaultWidth = 620f, DefaultHeight = 560f, MinWidth = 420f, MinHeight = 260f,
});
// The Void window is opened from the Oracle window: no bar button (and no Scripts menu
// line, which would bring back the Scripts button just for it).
_void = _ui.Add(new UiWindow("RynthOracle/Void", "Void")
{
DefaultWidth = 220f, DefaultHeight = 150f, MinWidth = 160f, MinHeight = 110f,
ShowInBar = false,
});
_mainView.SetVoidWindow = v => { if (_void != null) { _void.Visible = v; _void.NeedsPass = true; } };
_mainView.VoidWindowVisible = () => _void?.Visible ?? false;

View file

@ -47,6 +47,9 @@ internal static class UiFormat
// Window flags
public const uint FlagVisible = 1u << 0;
public const uint FlagShowInBar = 1u << 1;
/// <summary>With ShowInBar: a bar button of its own instead of a Scripts menu line (engines from
/// 2026-10-11; older ones ignore it and list the window in the Scripts menu).</summary>
public const uint FlagBarButton = 1u << 11;
public const uint FlagNoScrollbar = 1u << 5;
// Event types

View file

@ -42,6 +42,9 @@ internal sealed class UiWindow
public string Title;
public bool Visible;
public bool ShowInBar = true;
/// <summary>With ShowInBar: the window has its own button on the RynthCore bar (title as the
/// tooltip) rather than a line in the Scripts menu.</summary>
public bool BarButton = true;
public float DefaultWidth, DefaultHeight, MinWidth, MinHeight;
/// <summary>A pass is wanted at the next chance (input arrived, it was just shown, data changed).</summary>
@ -80,7 +83,8 @@ internal sealed class UiWindow
Title = title;
}
public uint Flags => (Visible ? UiFormat.FlagVisible : 0) | (ShowInBar ? UiFormat.FlagShowInBar : 0);
public uint Flags => (Visible ? UiFormat.FlagVisible : 0) | (ShowInBar ? UiFormat.FlagShowInBar : 0)
| (ShowInBar && BarButton ? UiFormat.FlagBarButton : 0);
public bool HeaderDirty =>
_sentTitle != Title || _sentFlags != Flags || _sentDw != DefaultWidth || _sentDh != DefaultHeight

View file

@ -29,6 +29,32 @@ internal sealed unsafe class HostSortWorld : ISortWorld
public SortInventory? ReadInventory() => _reader.Read(_host);
// PutItemInContainer answered "not bound" once: plain moves from then on.
private bool _putUnbound;
public SortAbilities Abilities => new()
{
ReadOrder = _host.HasContainerOrder,
PlaceMoves = _host.HasPutItemInContainer && !_putUnbound,
Merge = _host.HasMergeStackInternal,
};
// Diagnostics: a "looting" pause that lasts says what the open container looked like.
private long _lootPauseSince = -1;
private bool _lootPauseLogged;
private int _lootPauseChanges, _lootPauseLastCount = int.MinValue;
private void NoteLongLootPause(bool looting, uint ground, int count, long nowMs)
{
if (!looting) { _lootPauseSince = -1; _lootPauseLogged = false; _lootPauseChanges = 0; _lootPauseLastCount = int.MinValue; return; }
if (_lootPauseSince < 0) _lootPauseSince = nowMs;
if (count != _lootPauseLastCount) { _lootPauseChanges++; _lootPauseLastCount = count; }
if (!_lootPauseLogged && nowMs - _lootPauseSince > 20_000)
{
_lootPauseLogged = true;
try { _host.Log($"[RynthSort] paused for looting over 20 s: open container 0x{ground:X8}, item count now {count}, {_lootPauseChanges} count change(s) in that time"); } catch { }
}
}
public GateInputs ReadGate(bool sortInCombat, long nowMs)
{
var g = new GateInputs { SortInCombat = sortInCombat };
@ -38,10 +64,13 @@ internal sealed unsafe class HostSortWorld : ISortWorld
int count = 0;
if (ground != 0)
{
count = _host.HasGetNumContainedItems ? _host.GetNumContainedItems(ground) : -1;
if (count < 0) count = _host.GetContainerContents(ground, _groundBuf);
// One way of counting only: mixing the two (the item count when it reads, else the
// contents list) could flip between two different numbers and look like looting.
count = _host.HasGetNumContainedItems ? _host.GetNumContainedItems(ground)
: _host.GetContainerContents(ground, _groundBuf);
}
g.Looting = _loot.Update(ground, count, nowMs);
NoteLongLootPause(g.Looting, ground, count, nowMs);
g.VendorOpen = _host.HasVendorTrade ? _host.TryGetVendorInfo(out _) : _vendorOpenByEvent();
g.TradeOpen = _host.HasTrade && _host.TryGetTradeState(out TradeState trade) && trade.IsOpen;
@ -56,12 +85,22 @@ internal sealed unsafe class HostSortWorld : ISortWorld
uint id = move.Item.Id;
if (move.MergeInto != 0 && _host.HasMergeStackInternal)
return _host.MergeStackInternal(id, move.MergeInto);
if (move.Kind == MoveKind.Stack) return false; // a join in place needs the merge
if (move.Placement >= 0 && _host.HasPutItemInContainer && !_putUnbound)
{
int rc = _host.PutItemInContainer(id, move.Dest.Id, move.Placement);
if (rc != -1) return rc == 1;
_putUnbound = true;
try { _host.Log("[RynthSort] this client can't send a move to a slot; items are moved to their packs but not put in order"); } catch { }
}
if (move.Kind == MoveKind.Reorder) return false; // a slot change in place needs PutItemInContainer
return _host.HasMoveItemInternal && _host.MoveItemInternal(id, move.Dest.Id, 0, Math.Max(1, move.Item.Stack));
}
public MoveObservation Observe(uint itemId)
public MoveObservation Observe(in SortMove move)
{
var o = new MoveObservation();
uint itemId = move.Item.Id;
var o = new MoveObservation { Slot = -1 };
if (_host.HasGetObjectOwnershipInfo && _host.TryGetObjectOwnershipInfo(itemId, out uint container, out uint wielder, out _))
{
o.Exists = true;
@ -75,6 +114,8 @@ internal sealed unsafe class HostSortWorld : ISortWorld
o.Container = 0xFFFFFFFF;
}
o.Stack = _host.TryGetObjectIntProperty(itemId, 12, out int s) && s > 0 ? s : 1;
if (move.Kind == MoveKind.Reorder && o.Exists && o.Container == move.Dest.Id)
o.Slot = _reader.SlotOf(_host, move.Dest.Id, itemId);
if (_host.HasGetLastWeenieError && _host.TryGetLastWeenieError(out int seq, out uint error, out uint type, out uint obj))
{
o.ErrorSeq = seq;

View file

@ -27,7 +27,7 @@ public static unsafe class PluginExports
public static IntPtr GetName() => LiteralPointer("RynthSort"u8);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetVersion() => LiteralPointer("0.1.0"u8);
public static IntPtr GetVersion() => LiteralPointer("0.3.0"u8);
private static IntPtr LiteralPointer(ReadOnlySpan<byte> literal)
{

View file

@ -3,7 +3,8 @@
<!--
RynthSort: keeps a character's packs sorted while they play or while RynthAi hunts. New
items that land in the main pack move to the side pack their rule names, after a settle
time; Tidy, Clean and Unpack on demand; /rsort. Replaces the RynthSort Lua script (its saved
time; misplaced items move to theirs, stacks are joined and items are put in order inside
each pack (slot orders, API v80); Sort now, Clean and Unpack on demand; /rsort. Replaces the RynthSort Lua script (its saved
rules are imported on first run). Pack moves wait for RynthAi through its read-only
"RynthAi.Activity" interface (Shared/RynthAiActivityApi.cs). UI: the engine's script
windows (ImGui), no Avalonia.
@ -26,8 +27,8 @@
<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
window; vendor info (v67), plugin interfaces (v68), refusals (v70) and trade (v72) are
each checked first. Below v71 it still sorts (/rsort on|off|now|tidy|clean|unpack). -->
window; vendor info (v67), plugin interfaces (v68), refusals (v70), trade (v72) and slot
orders / moves to a slot (v80: in-pack order, top-to-bottom pack numbers) are each checked first. Below v71 it still sorts (/rsort on|off|now|tidy|clean|unpack). -->
<RynthPluginMinEngineApi>66</RynthPluginMinEngineApi>
<RynthPluginDescription>Keeps your packs sorted: new loot goes to the pack its rule names.</RynthPluginDescription>
</PropertyGroup>

View file

@ -11,12 +11,14 @@ using RynthCore.PluginCore;
namespace RynthCore.Plugin.RynthSort;
/// <summary>
/// RynthSort: keeps your packs sorted while you play or RynthAi hunts. New items that land in the
/// main pack move to the side pack their rule names once they have sat there for the settle time;
/// Tidy also moves misplaced items between side packs, Clean sends items no rule wants back to the
/// main pack, Unpack empties the side packs. Rules are tried in order and the first that matches
/// wins: by item class or by part of the name. Rules and settings are kept per character; the
/// RynthSort Lua script's saved rules are taken over on a character's first run.
/// RynthSort: keeps your packs sorted while you play or RynthAi hunts. Auto-sort keeps every pack
/// tidy: new items that land in the main pack move to the side pack their rule names once they have
/// sat there for the settle time, items in the wrong side pack move to theirs, stacks of one kind
/// are joined and (with the engine's slot orders, API v80) items are put in order, A-Z, inside
/// each pack. Clean also sends items no rule wants back to the main pack; Unpack empties the side
/// packs. A rule lists classes and parts of names and the pack they go to; a name match beats a
/// class match. Rules and settings are kept per character; the RynthSort Lua script's saved rules
/// are taken over on a character's first run.
///
/// It stays out of the way (Sorting/SortGate.cs): nothing moves while a corpse or chest is being
/// looted, a vendor or trade window is open, the character is busy or animating, in portal space,
@ -28,7 +30,7 @@ namespace RynthCore.Plugin.RynthSort;
/// </summary>
public sealed class RynthSortPlugin : RynthPluginBase
{
public const string Version = "0.1.0";
public const string Version = "0.3.0";
private const long IdentityRetryMs = 1000;
private const long SaveDelayMs = 750;
private const long PassIntervalMs = 500;
@ -51,6 +53,7 @@ public sealed class RynthSortPlugin : RynthPluginBase
private long _saveDueMs;
private bool _vendorOpen;
private bool _noUiLogged;
private bool _backupOnSave;
private readonly List<string> _warnings = new();
public override int Initialize()
@ -58,6 +61,7 @@ public sealed class RynthSortPlugin : RynthPluginBase
_ui.Log = msg => Host.Log(msg);
_world = new HostSortWorld(Host, _reader, _loot, () => _vendorOpen);
_sort.SettingsChanged = RequestSave;
_sort.PacksFixed = OnPacksFixed;
_panel = new SortPanel(_sort, RequestSave)
{
Warnings = () => _warnings,
@ -143,8 +147,6 @@ public sealed class RynthSortPlugin : RynthPluginBase
Print("Auto-sort " + word);
break;
case "now":
_sort.StartJob(SortScope.Main);
break;
case "tidy":
_sort.StartJob(SortScope.All);
break;
@ -227,6 +229,7 @@ public sealed class RynthSortPlugin : RynthPluginBase
if (problem != null) Host.Log($"[RynthSort] couldn't read the saved rules ({problem}); using defaults.");
_sort.Data = data;
_identityKnown = true;
_backupOnSave = false;
string own = _store.PathFor(server, name);
if (data.ImportedFrom.Length > 0 && !File.Exists(own))
@ -281,6 +284,25 @@ public sealed class RynthSortPlugin : RynthPluginBase
return false;
}
/// <summary>The one-time pack fix ran: one log line per rule, a chat line, and a save (keeping a .bak of an imported file).</summary>
private void OnPacksFixed(List<string> lines, int changed)
{
bool imported = _sort.Data.ImportedFrom.Length > 0;
foreach (string line in lines) Host.Log("[RynthSort] pack fix: " + line);
if (imported)
{
int left = lines.Count - changed;
Print($"The rules taken over from the RynthSort script counted foci as packs: {changed} now point at the right pack"
+ (left > 0 ? $", {left} left as they were (see the log)." : "."));
_backupOnSave = true;
}
else if (changed > 0)
{
Host.Log($"[RynthSort] pack fix: {changed} rule(s) now remember their pack by id");
}
RequestSave();
}
private void RequestSave()
{
if (_window != null) _window.NeedsPass = true;
@ -292,8 +314,9 @@ public sealed class RynthSortPlugin : RynthPluginBase
_saveDueMs = 0;
if (!_identityKnown) return;
_sort.Data.Settings.Clamp();
string? error = _store.Save(_server, _character, _sort.Data);
string? error = _store.Save(_server, _character, _sort.Data, _backupOnSave);
if (error != null) Host.Log("[RynthSort] save failed: " + error);
else _backupOnSave = false;
}
/// <summary>A pass when one is wanted, or on the refresh interval while visible (the status ticks on).</summary>

View file

@ -13,7 +13,7 @@ internal sealed class SortSettings
{
public const int SettleMin = 0, SettleMax = 30, GapMin = 100, GapMax = 3000;
/// <summary>Auto-sort: new items in the main pack go to their pack after the settle time.</summary>
/// <summary>Auto-sort: keeps every pack tidy (new items from the main pack after the settle time, misplaced items, stacks, order).</summary>
public bool Auto = true;
/// <summary>How long a new item sits in the main pack before it moves (seconds).</summary>
public int SettleSec = 5;
@ -21,8 +21,17 @@ internal sealed class SortSettings
public int GapMs = 300;
/// <summary>Moves may go while RynthAi fights (never while it waits on the server or animates).</summary>
public bool SortInCombat;
/// <summary>The window was open when last seen.</summary>
public bool WindowOpen = true;
/// <summary>Items are put in order inside each pack (A-Z by name), when the engine can read slot orders (API v80).</summary>
public bool OrderInPacks = true;
/// <summary>The order inside a pack groups by kind (class) first, then name.</summary>
public bool OrderKindFirst;
/// <summary>
/// The window was open when last seen. Closed for a character RynthSort hasn't seen (it
/// has a button on the RynthCore bar and /rsort), so a new character or alt doesn't get it
/// popping up at every login until closed once; open once after taking over the Lua
/// script's rules, to show them.
/// </summary>
public bool WindowOpen;
public void Clamp()
{
@ -38,6 +47,17 @@ internal sealed class CharacterSortData
public SortSettings Settings = new();
/// <summary>Where these came from on first run ("" = defaults, else the Lua script's file).</summary>
public string ImportedFrom = string.Empty;
/// <summary>
/// The rules are tied to pack ids (<see cref="PackFix"/> ran once). False for files saved
/// before pack ids, a new character's defaults and a fresh import from the Lua script.
/// </summary>
public bool PacksFixed;
/// <summary>
/// The Lua script's rules as its file has them, while <see cref="PacksFixed"/> is false and the
/// rules came from it: tells untouched imported rules (Lua numbers) from ones picked in
/// RynthSort's window since. Null when unknown. Not saved.
/// </summary>
public List<SortRule>? LuaRules;
}
/// <summary>
@ -87,13 +107,20 @@ internal sealed class SortStore
string own = PathFor(server, character);
if (File.Exists(own))
{
if (TryRead(own, out CharacterSortData? d, out problem)) return d!;
return new CharacterSortData();
if (!TryRead(own, out CharacterSortData? d, out problem)) return new CharacterSortData();
// Imported before pack ids: the Lua script's file says which rules are still its own.
if (!d!.PacksFixed && d.ImportedFrom.Length > 0 && File.Exists(d.ImportedFrom)
&& TryRead(d.ImportedFrom, out CharacterSortData? luaNow, out _))
d.LuaRules = luaNow!.Rules;
return d;
}
string lua = LuaPathFor(server, character);
if (File.Exists(lua) && TryRead(lua, out CharacterSortData? imported, out problem))
{
imported!.ImportedFrom = lua;
imported.PacksFixed = false; // Lua pack numbers: fixed on the first settled read
imported.LuaRules = imported.Rules.ConvertAll(r => r.Clone());
imported.Settings.WindowOpen = true; // show the rules just taken over (the Lua file has no windowOpen)
return imported;
}
return new CharacterSortData();
@ -149,37 +176,67 @@ internal sealed class SortStore
st.SettleSec = Int(s, "settleSec", st.SettleSec);
st.GapMs = Int(s, "gapMs", st.GapMs);
st.SortInCombat = Bool(s, "sortInCombat", st.SortInCombat);
st.OrderInPacks = Bool(s, "orderInPacks", st.OrderInPacks);
st.OrderKindFirst = Bool(s, "orderKindFirst", st.OrderKindFirst);
st.WindowOpen = Bool(s, "windowOpen", st.WindowOpen);
st.Clamp();
}
if (root.TryGetProperty("importedFrom", out JsonElement f) && f.ValueKind == JsonValueKind.String)
d.ImportedFrom = f.GetString() ?? string.Empty;
// Missing (a version 1 file, the Lua script's file): rules by number only, not fixed yet.
d.PacksFixed = Bool(root, "packsFixed", false);
return d;
}
/// <summary>
/// One rule. Version 3 has "classes" and "names" lists; anything older (versions 1 and 2, and the
/// Lua script's file) has one test, { kind = "class" | "name", class, text }, which becomes a
/// rule with that one class or name. Version 3 writes those old fields too (its first entry),
/// so an older RynthSort reading a newer file still gets a sensible rule.
/// </summary>
private static SortRule? ParseRule(JsonElement e)
{
if (e.ValueKind != JsonValueKind.Object) return null;
var r = new SortRule
{
On = Bool(e, "on", true),
Kind = e.TryGetProperty("kind", out JsonElement k) && k.ValueKind == JsonValueKind.String
&& string.Equals(k.GetString(), "name", StringComparison.OrdinalIgnoreCase) ? RuleKind.Name : RuleKind.Class,
Class = Int(e, "class", ObjectClasses.SpellComponent),
Text = e.TryGetProperty("text", out JsonElement t) && t.ValueKind == JsonValueKind.String ? t.GetString() ?? string.Empty : string.Empty,
Pack = Math.Clamp(Int(e, "pack", 1), 1, MaxPack),
PackId = UInt(e, "packId"),
PackNote = e.TryGetProperty("packNote", out JsonElement pn) && pn.ValueKind == JsonValueKind.String ? pn.GetString() ?? string.Empty : string.Empty,
};
if (r.Text.Length > 64) r.Text = r.Text[..64];
bool hasClasses = e.TryGetProperty("classes", out JsonElement cl) && cl.ValueKind == JsonValueKind.Array;
bool hasNames = e.TryGetProperty("names", out JsonElement nm) && nm.ValueKind == JsonValueKind.Array;
if (hasClasses || hasNames)
{
if (hasClasses)
foreach (JsonElement c in cl.EnumerateArray())
if (c.ValueKind == JsonValueKind.Number && c.TryGetDouble(out double v) && v >= 0 && v <= 1000) r.AddClass((int)Math.Round(v));
if (hasNames)
foreach (JsonElement n in nm.EnumerateArray())
if (n.ValueKind == JsonValueKind.String) r.AddName(n.GetString());
}
else
{
bool byName = e.TryGetProperty("kind", out JsonElement k) && k.ValueKind == JsonValueKind.String
&& string.Equals(k.GetString(), "name", StringComparison.OrdinalIgnoreCase);
if (byName) r.AddName(e.TryGetProperty("text", out JsonElement t) && t.ValueKind == JsonValueKind.String ? t.GetString() : null);
else r.AddClass(Int(e, "class", ObjectClasses.SpellComponent));
}
if (r.PackNote.Length > 96) r.PackNote = r.PackNote[..96];
return r;
}
/// <summary>Writes the character's file (temp file, then moved over the old one). Returns an error or null.</summary>
public string? Save(string server, string character, CharacterSortData d)
/// <summary>
/// Writes the character's file (temp file, then moved over the old one). <paramref name="backup"/>:
/// copy the old file to "&lt;file&gt;.bak" first (the one-time pack fix keeps one). Returns an error or null.
/// </summary>
public string? Save(string server, string character, CharacterSortData d, bool backup = false)
{
string path = PathFor(server, character);
try
{
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
if (backup && File.Exists(path)) File.Copy(path, path + ".bak", overwrite: true);
string tmp = path + "." + Environment.ProcessId.ToString(CultureInfo.InvariantCulture) + ".tmp";
File.WriteAllText(tmp, ToJson(d), new UTF8Encoding(false));
File.Move(tmp, path, overwrite: true);
@ -197,16 +254,29 @@ internal sealed class SortStore
using (var w = new Utf8JsonWriter(ms, new JsonWriterOptions { Indented = true }))
{
w.WriteStartObject();
w.WriteNumber("version", 1);
// 3: a rule holds several classes and names. 2: rules carry packId / packNote, and
// packsFixed. Versions 1 and 2 still load (one class or name per rule).
w.WriteNumber("version", 3);
w.WriteStartArray("rules");
foreach (SortRule r in d.Rules)
{
w.WriteStartObject();
w.WriteBoolean("on", r.On);
w.WriteString("kind", r.Kind == RuleKind.Name ? "name" : "class");
w.WriteNumber("class", r.Class);
w.WriteString("text", r.Text ?? string.Empty);
w.WriteStartArray("classes");
foreach (int c in r.Classes) w.WriteNumberValue(c);
w.WriteEndArray();
w.WriteStartArray("names");
foreach (string n in r.Names) w.WriteStringValue(n);
w.WriteEndArray();
// The first entry the old way, for an older RynthSort reading this file (an empty
// rule as a blank name rule, which matches nothing there too).
bool firstIsName = r.Classes.Count == 0;
w.WriteString("kind", firstIsName ? "name" : "class");
w.WriteNumber("class", r.Classes.Count > 0 ? r.Classes[0] : ObjectClasses.SpellComponent);
w.WriteString("text", firstIsName && r.Names.Count > 0 ? r.Names[0] : string.Empty);
w.WriteNumber("pack", r.Pack);
if (r.PackId != 0) w.WriteNumber("packId", r.PackId);
if (r.PackNote.Length > 0) w.WriteString("packNote", r.PackNote);
w.WriteEndObject();
}
w.WriteEndArray();
@ -215,9 +285,12 @@ internal sealed class SortStore
w.WriteNumber("settleSec", d.Settings.SettleSec);
w.WriteNumber("gapMs", d.Settings.GapMs);
w.WriteBoolean("sortInCombat", d.Settings.SortInCombat);
w.WriteBoolean("orderInPacks", d.Settings.OrderInPacks);
w.WriteBoolean("orderKindFirst", d.Settings.OrderKindFirst);
w.WriteBoolean("windowOpen", d.Settings.WindowOpen);
w.WriteEndObject();
if (d.ImportedFrom.Length > 0) w.WriteString("importedFrom", d.ImportedFrom);
w.WriteBoolean("packsFixed", d.PacksFixed);
w.WriteEndObject();
}
return Encoding.UTF8.GetString(ms.ToArray()) + "\n";
@ -228,6 +301,14 @@ internal sealed class SortStore
? v.GetBoolean()
: fallback;
/// <summary>An object id (0 when missing, negative or odd).</summary>
private static uint UInt(JsonElement o, string name)
{
if (!o.TryGetProperty(name, out JsonElement v) || v.ValueKind != JsonValueKind.Number) return 0;
if (v.TryGetUInt32(out uint u)) return u;
return v.TryGetDouble(out double dbl) && dbl >= 0 && dbl <= uint.MaxValue && dbl == Math.Floor(dbl) ? (uint)dbl : 0;
}
private static int Int(JsonElement o, string name, int fallback)
{
if (!o.TryGetProperty(name, out JsonElement v) || v.ValueKind != JsonValueKind.Number) return fallback;

View file

@ -10,6 +10,12 @@ namespace RynthCore.Plugin.RynthSort.Sorting;
/// worn and wielded items; each side pack's items come from GetContainerContents(pack). A side
/// pack is a container that holds items (ItemsCapacity above 0); foci hold none and are skipped,
/// as are worn and wielded items. Names, classes and stack limits are kept per item id once read.
/// GetContainerContents sorts by object id; with the engine's slot orders (API v80
/// GetContainerOrder: what the server sent at login and with every move) each pack's items are put
/// in their real slot order and the side packs in the pack column's order, top first, whenever
/// that order names exactly what was read (<see cref="SortPack.ApplyOrder"/>,
/// <see cref="SortInventory.ApplyPackOrder"/>). Without it the id order stays and nothing is
/// reordered inside packs.
/// </summary>
internal sealed class InventoryReader
{
@ -39,6 +45,7 @@ internal sealed class InventoryReader
private readonly Dictionary<uint, Known> _known = new();
private uint[] _buf = new uint[512];
private uint[] _order = new uint[128];
public void Reset() => _known.Clear();
@ -59,12 +66,17 @@ internal sealed class InventoryReader
foreach (uint id in top)
{
if (id == 0) continue;
if (Wielded(host, id)) continue;
uint type = host.TryGetItemType(id, out uint t) ? t : 0;
if ((type & ItemTypeContainer) != 0)
bool isContainer = (type & ItemTypeContainer) != 0;
int cap = 0;
bool capRead = isContainer && host.TryGetObjectIntProperty(id, IntItemsCapacity, out cap);
// Every container entry, foci too and before the wielded check: the Lua script's count.
if (isContainer) inv.Slots.Add(new SortSlot(id, capRead ? Math.Max(cap, 0) : -1));
if (Wielded(host, id)) continue;
if (isContainer)
{
// A side pack holds items; foci (containers that hold none) aren't packs or items.
if (host.TryGetObjectIntProperty(id, IntItemsCapacity, out int cap) && cap > 0)
if (capRead && cap > 0)
{
var pack = new SortPack { Id = id, Capacity = cap, Name = host.TryGetObjectName(id, out string pn) ? pn : string.Empty };
foreach (uint inner in Contents(host, id))
@ -80,9 +92,23 @@ internal sealed class InventoryReader
}
inv.Main.Items.Add(Item(host, id, type));
}
if (host.HasContainerOrder)
{
if (host.TryGetContainerOrder(player, false, ref _order, out int n)) inv.Main.ApplyOrder(_order, n);
foreach (SortPack p in inv.Packs)
if (host.TryGetContainerOrder(p.Id, false, ref _order, out n)) p.ApplyOrder(_order, n);
if (host.TryGetContainerOrder(player, true, ref _order, out n)) inv.ApplyPackOrder(_order, n);
}
return inv;
}
/// <summary>The slot <paramref name="itemId"/> holds in <paramref name="container"/> (the engine's slot order), or -1.</summary>
public int SlotOf(RynthCoreHost host, uint container, uint itemId)
{
if (!host.HasContainerOrder || !host.TryGetContainerOrder(container, false, ref _order, out int n)) return -1;
return Array.IndexOf(_order, itemId, 0, n);
}
private uint[] Contents(RynthCoreHost host, uint container)
{
int n = host.GetContainerContents(container, _buf);

View file

@ -23,6 +23,8 @@ internal struct MoveObservation
public uint Container;
public uint Wielder;
public int Stack;
/// <summary>Its slot in its container (the engine's slot order), or -1 when unknown. Read for reorders only.</summary>
public int Slot;
/// <summary>The engine's refusal counter (TryGetLastWeenieError seq; 0 when unknown).</summary>
public int ErrorSeq;
public uint Error;
@ -52,16 +54,35 @@ internal static class MoveTracker
/// <summary>The longest hold after refusals in a row.</summary>
public const long MaxBackoffMs = 30_000;
/// <summary>The container reads as this when the engine can't say (no ownership info).</summary>
public const uint UnknownContainer = 0xFFFFFFFF;
public const uint EventInventoryServerSaveFailed = 0x00A0;
public const uint ErrorYoureTooBusy = 0x001D;
public const uint ErrorTooManyActions = 0x0045;
/// <summary>
/// What the client says about the move so far. A move within one pack (a stack joined, a slot
/// changed) can't be judged by the item's container, which it never left: a join is answered
/// when the item is gone or smaller, a reorder when the item sits at its slot (or left the pack).
/// </summary>
public static MoveOutcome Observe(MoveInFlight m, in MoveObservation o, long nowMs)
{
SortMove mv = m.Move;
if (!o.Exists) return MoveOutcome.Done; // merged on arrival
if (o.Container == mv.Dest.Id && o.Wielder == 0) return MoveOutcome.Done;
if (mv.MergeInto != 0 && o.Stack < m.StackAtSend) return MoveOutcome.Done; // part of it joined the stack
switch (mv.Kind)
{
case MoveKind.Stack:
if (o.Stack < m.StackAtSend) return MoveOutcome.Done;
break;
case MoveKind.Reorder:
if (o.Container == mv.Dest.Id && o.Slot == mv.Placement) return MoveOutcome.Done;
if (o.Container != mv.Dest.Id && o.Container != UnknownContainer) return MoveOutcome.Done; // someone moved it away
break;
default:
if (o.Container == mv.Dest.Id && o.Wielder == 0) return MoveOutcome.Done;
if (mv.MergeInto != 0 && o.Stack < m.StackAtSend) return MoveOutcome.Done; // part of it joined the stack
break;
}
if (o.ErrorSeq != 0 && o.ErrorSeq != m.ErrorSeqAtSend)
{
if (o.Error == ErrorYoureTooBusy || o.Error == ErrorTooManyActions) return MoveOutcome.TooBusy;

View file

@ -0,0 +1,131 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace RynthCore.Plugin.RynthSort.Sorting;
/// <summary>
/// Ties rules to their packs' ids. Rules saved before RynthSort kept pack ids only had a number,
/// and the Lua script's numbers counted foci as packs (game.Character.Containers: every container
/// in the main pack, in the same order), so after a focus every imported number pointed one pack
/// too far. Once per character, on a settled read of the packs (<see cref="Apply"/>):
/// <list type="bullet">
/// <item>a rule still as the Lua script had it: Lua number n is the n-th container, foci counted.
/// A pack: the rule takes its id and its number among the real packs. A focus, or nothing there:
/// left as it was, and said so.</item>
/// <item>any other rule (picked in RynthSort's window, or the defaults): its number already counts
/// real packs only, so it takes that pack's id.</item>
/// </list>
/// Pure: the tests drive it with hand-made inventories.
/// </summary>
internal static class PackFix
{
/// <summary>Every side-slot entry's capacity was readable (a focus and a pack can be told apart).</summary>
public static bool Ready(SortInventory inv)
{
foreach (SortSlot s in inv.Slots)
if (s.Capacity < 0) return false;
return true;
}
/// <summary>The side-slot layout (ids and capacities): two reads alike mean the packs have settled.</summary>
public static string Layout(SortInventory inv)
{
var sb = new StringBuilder(inv.Slots.Count * 12);
foreach (SortSlot s in inv.Slots) sb.Append(s.Id.ToString("X8")).Append(':').Append(s.Capacity).Append(';');
return sb.ToString();
}
/// <summary>"Sack - Salvage, Gems".</summary>
public static string NoteOf(SortPack p) => $"{(p.Name.Length > 0 ? p.Name : "Pack")} - {p.Summary()}";
/// <summary>
/// The one-time fix over <paramref name="rules"/> (only rules without a pack id are looked at).
/// <paramref name="imported"/>: the rules came from the Lua script. <paramref name="luaRules"/>:
/// the Lua script's rules as they are in its file (null when it can't be read: every rule is
/// taken as imported). Returns one line per rule it looked at, saying what it did; changed
/// counts the rules it changed.
/// </summary>
public static List<string> Apply(IReadOnlyList<SortRule> rules, SortInventory inv, bool imported, IReadOnlyList<SortRule>? luaRules, out int changed)
{
var lines = new List<string>();
changed = 0;
for (int i = 0; i < rules.Count; i++)
{
SortRule r = rules[i];
if (r.PackId != 0) continue;
string who = $"rule {i + 1} ({SortRules.Describe(r)})";
if (imported && (luaRules == null || Contains(luaRules, r)))
{
int n = r.Pack;
if (n < 1 || n > inv.Slots.Count)
{
lines.Add($"{who}: the Lua script's pack {n} doesn't exist ({Count(inv)}); left as pack {n}");
continue;
}
SortSlot slot = inv.Slots[n - 1];
int idx = inv.IndexOf(slot.Id);
if (!slot.IsPack || idx == 0)
{
lines.Add($"{who}: the Lua script's pack {n} is {(slot.IsPack ? "not a side pack" : "a focus")} (0x{slot.Id:X8}); left as pack {n}");
continue;
}
SortPack p = inv.Packs[idx - 1];
r.PackId = p.Id;
r.Pack = idx;
r.PackNote = NoteOf(p);
changed++;
lines.Add($"{who}: the Lua script's pack {n} -> pack {idx}, {r.PackNote} (0x{p.Id:X8})");
}
else
{
if (r.Pack < 1 || r.Pack > inv.Packs.Count)
{
lines.Add($"{who}: pack {r.Pack}, which you don't have; left as it is");
continue;
}
SortPack p = inv.Packs[r.Pack - 1];
r.PackId = p.Id;
r.PackNote = NoteOf(p);
changed++;
lines.Add($"{who}: pack {r.Pack} kept, now tied to {r.PackNote} (0x{p.Id:X8})");
}
}
return lines;
}
/// <summary>
/// Keeps each rule's number (and note) on its pack when that pack is carried, so the number
/// the window shows and the fallback stay right as packs come and go. True when one changed.
/// </summary>
public static bool Sync(IReadOnlyList<SortRule> rules, SortInventory inv)
{
bool any = false;
foreach (SortRule r in rules)
{
int idx = inv.IndexOf(r.PackId);
if (idx == 0) continue;
if (r.Pack != idx || r.PackNote.Length == 0)
{
r.Pack = idx;
r.PackNote = NoteOf(inv.Packs[idx - 1]);
any = true;
}
}
return any;
}
private static bool Contains(IReadOnlyList<SortRule> list, SortRule r)
{
foreach (SortRule o in list)
if (o.SameAs(r)) return true;
return false;
}
private static string Count(SortInventory inv)
{
int foci = 0;
foreach (SortSlot s in inv.Slots) if (!s.IsPack) foci++;
return $"{inv.Packs.Count} pack{(inv.Packs.Count == 1 ? "" : "s")} and {foci} foc{(foci == 1 ? "us" : "i")}";
}
}

View file

@ -0,0 +1,146 @@
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthSort.Sorting;
/// <summary>
/// The order items keep inside a pack, and the moves that get a pack there. Pure: the tests drive it.
///
/// The order: by name A-Z (any case, then exact), so like items sit together; the same name with
/// another kind of stack (class id) next; then by object id, which never changes. Optionally by
/// kind first (the class's label: "Armor", "Gem", ...), then the same. It is a total order on the
/// items, so a pack has exactly one target order however its items got there.
///
/// The moves: one item at a time to a slot (the engine's PutItemInContainer, API v80: placement =
/// the index it should end at, counted without it, which is how ACE inserts). The items already in
/// order relative to each other (a longest increasing run of target ranks) stay; one of the others
/// is put right after the last of those that comes before it. That run grows by at least one with
/// every move, so a pack of n items is in order after at most n - (longest run) moves, and an
/// item that arrived in the right place costs none.
/// </summary>
internal static class PackOrder
{
/// <summary>The target order (see the class summary). <paramref name="kindFirst"/>: by class label first.</summary>
public static int Compare(SortItem a, SortItem b, bool kindFirst)
{
if (ReferenceEquals(a, b)) return 0;
if (kindFirst && a.ObjectClass != b.ObjectClass)
{
int k = string.Compare(ObjectClasses.Label(a.ObjectClass), ObjectClasses.Label(b.ObjectClass), StringComparison.OrdinalIgnoreCase);
if (k != 0) return k;
k = a.ObjectClass.CompareTo(b.ObjectClass);
if (k != 0) return k;
}
string an = a.Name ?? string.Empty, bn = b.Name ?? string.Empty;
int c = string.Compare(an, bn, StringComparison.OrdinalIgnoreCase);
if (c != 0) return c;
c = string.CompareOrdinal(an, bn);
if (c != 0) return c;
c = a.Wcid.CompareTo(b.Wcid);
return c != 0 ? c : a.Id.CompareTo(b.Id);
}
/// <summary>Every item has a name: an item the client hasn't described yet would sort as "" and move again once named.</summary>
public static bool AllNamed(IReadOnlyList<SortItem> items)
{
foreach (SortItem it in items)
if (string.IsNullOrEmpty(it.Name)) return false;
return true;
}
/// <summary>Each item's place in the target order (0 = first), in the items' current order.</summary>
public static int[] Ranks(IReadOnlyList<SortItem> items, bool kindFirst)
{
int n = items.Count;
var idx = new int[n];
for (int i = 0; i < n; i++) idx[i] = i;
Array.Sort(idx, (x, y) => Compare(items[x], items[y], kindFirst));
var rank = new int[n];
for (int r = 0; r < n; r++) rank[idx[r]] = r;
return rank;
}
/// <summary>
/// Which positions are in a longest increasing run of <paramref name="rank"/> (they stay put).
/// O(n^2) over a pack (at most ~100 items); the earliest-ending run is kept, so the answer is
/// the same for the same list.
/// </summary>
public static bool[] Kept(int[] rank)
{
int n = rank.Length;
var len = new int[n];
var prev = new int[n];
int best = -1;
for (int i = 0; i < n; i++)
{
len[i] = 1;
prev[i] = -1;
for (int j = 0; j < i; j++)
if (rank[j] < rank[i] && len[j] + 1 > len[i]) { len[i] = len[j] + 1; prev[i] = j; }
if (best < 0 || len[i] > len[best]) best = i;
}
var kept = new bool[n];
for (int i = best; i >= 0; i = prev[i]) kept[i] = true;
return kept;
}
/// <summary>How many items are out of place (would move): 0 = in order.</summary>
public static int OutOfPlace(IReadOnlyList<SortItem> items, bool kindFirst)
{
if (items.Count < 2) return 0;
bool[] kept = Kept(Ranks(items, kindFirst));
int n = 0;
foreach (bool k in kept) if (!k) n++;
return n;
}
/// <summary>
/// The next move that puts the pack in order: the out-of-place item with the lowest target rank
/// that <paramref name="movable"/> allows, and the slot it goes to (counted without it). False
/// when the pack is in order, or only items that can't move now are out of place.
/// </summary>
public static bool NextMove(IReadOnlyList<SortItem> items, bool kindFirst, Func<SortItem, bool> movable, out SortItem item, out int placement)
{
item = null!;
placement = -1;
int n = items.Count;
if (n < 2) return false;
int[] rank = Ranks(items, kindFirst);
bool[] kept = Kept(rank);
int pick = -1;
for (int i = 0; i < n; i++)
if (!kept[i] && movable(items[i]) && (pick < 0 || rank[i] < rank[pick])) pick = i;
if (pick < 0) return false;
// Right after the last kept item that comes before it in the target order.
int after = -1;
for (int i = 0; i < n; i++)
if (kept[i] && rank[i] < rank[pick]) after = i; // kept items rise with i: the last one wins
item = items[pick];
placement = after < 0 ? 0 : (after > pick ? after : after + 1);
return true;
}
/// <summary>
/// The slot an item arriving in a pack should take so it lands where the order wants it: after
/// every item there that comes before it. In a pack already in order that is its final place.
/// </summary>
public static int InsertAt(IReadOnlyList<SortItem> items, SortItem arriving, bool kindFirst)
{
int at = 0;
for (int i = 0; i < items.Count; i++)
if (Compare(items[i], arriving, kindFirst) < 0) at = i + 1;
return at;
}
/// <summary>
/// The list after moving <paramref name="item"/> to <paramref name="placement"/> as ACE does it
/// (taken out, the others close up, put in at that index, clamped to the end). For the tests'
/// pretend server and the planner's checks.
/// </summary>
public static void Apply(List<SortItem> items, SortItem item, int placement)
{
items.Remove(item);
items.Insert(Math.Clamp(placement, 0, items.Count), item);
}
}

View file

@ -11,19 +11,36 @@ internal interface ISortWorld
SortInventory? ReadInventory();
/// <summary>The "stay out of the way" inputs now.</summary>
GateInputs ReadGate(bool sortInCombat, long nowMs);
/// <summary>Sends the move to the client (merge or plain move). False = the engine refused it.</summary>
/// <summary>Sends the move to the client (merge, move to a slot, or plain move). False = the engine refused it.</summary>
bool SendMove(in SortMove move);
/// <summary>The moved item and the server's last refusal.</summary>
MoveObservation Observe(uint itemId);
/// <summary>The moved item (its slot too, for a reorder) and the server's last refusal.</summary>
MoveObservation Observe(in SortMove move);
/// <summary>The engine's refusal counter now (0 when the engine can't say).</summary>
int ErrorSeqNow();
/// <summary>What this engine lets the planner do beyond moving items to their packs.</summary>
SortAbilities Abilities { get; }
}
/// <summary>What the engine can do for RynthSort (the plugin asks the host; the tests say).</summary>
internal struct SortAbilities
{
/// <summary>Slot orders are readable (API v80 GetContainerOrder).</summary>
public bool ReadOrder;
/// <summary>A move can name its slot (API v80 PutItemInContainer, bound on this client).</summary>
public bool PlaceMoves;
/// <summary>Stacks can be merged (MergeStackInternal).</summary>
public bool Merge;
public static SortAbilities All => new() { ReadOrder = true, PlaceMoves = true, Merge = true };
}
/// <summary>
/// The sorting loop, one step per plugin tick: one move at a time, each waited on until the
/// server answers it (the item lands, or it is refused, or the time limit passes), then a gap.
/// Auto-sort moves new main-pack items after the settle time, one per gap; a job asked for
/// (Sort now, Tidy, Clean, Unpack) goes as fast as the server answers. Nothing is sent while the
/// Auto-sort keeps every pack tidy (<see cref="SortScope.All"/>): new main-pack items go to their
/// packs after the settle time, misplaced side-pack items to theirs, then stacks are joined and
/// items put in order inside each pack, one move per gap; a job asked for (Sort now, Clean,
/// Unpack) goes as fast as the server answers. Nothing is sent while the
/// gate says why not (<see cref="SortGate"/>). An item that fails is left alone for a minute, and
/// failures in a row hold every move off longer and longer (<see cref="MoveTracker.BackoffMs"/>).
/// </summary>
@ -52,16 +69,25 @@ internal sealed class SortController
public RynthAiActivity? LastBot { get; private set; }
/// <summary>The last few moves and job results, newest first.</summary>
public readonly List<string> Log = new();
/// <summary>What the engine allowed at the last tick (the window says when ordering isn't possible).</summary>
public SortAbilities Abilities { get; private set; }
public int Moved { get; private set; }
public int Failed { get; private set; }
/// <summary>Settings changed by a command (auto-sort off for Unpack): the plugin saves.</summary>
public Action? SettingsChanged;
/// <summary>The one-time pack fix ran (<see cref="PackFix"/>): its lines and how many rules it changed. The plugin logs and saves.</summary>
public Action<List<string>, int>? PacksFixed;
/// <summary>How long the side-slot layout must read the same before the one-time pack fix runs.</summary>
public const long FixSettleMs = 3000;
private MoveInFlight? _inFlight;
private long _nextStepMs;
private long _nextViewMs;
private int _failuresInARow;
private string? _fixLayout;
private long _fixLayoutSince;
public bool HasMoveOut => _inFlight != null;
@ -73,6 +99,7 @@ internal sealed class SortController
_inFlight = null;
_nextStepMs = _nextViewMs = 0;
_failuresInARow = 0;
_fixLayout = null;
Job = null;
UnpackWhich = null;
LastBot = null;
@ -107,6 +134,25 @@ internal sealed class SortController
SettingsChanged?.Invoke();
}
// Items put in order in one pack go in the log as one line that counts up.
private string? _reorderRunLine;
private int _reorderRunPack = -1, _reorderRunCount;
private void NoteReorderRun(in SortMove m)
{
if (_reorderRunLine != null && _reorderRunPack == m.DestIndex && Log.Count > 0 && ReferenceEquals(Log[0], _reorderRunLine))
{
_reorderRunCount++;
Log[0] = _reorderRunLine = $"{_reorderRunCount} items put in order in {m.DestLabel}";
return;
}
_reorderRunPack = m.DestIndex;
_reorderRunCount = 1;
string name = m.Item.Name.Length > 0 ? m.Item.Name : $"0x{m.Item.Id:X8}";
Note($"{name} {m.Done}");
_reorderRunLine = Log[0];
}
public void Note(string line)
{
Log.Insert(0, line);
@ -117,9 +163,10 @@ internal sealed class SortController
public void Tick(ISortWorld world, long nowMs)
{
Abilities = world.Abilities;
if (_inFlight != null)
{
MoveObservation o = world.Observe(_inFlight.Move.Item.Id);
MoveObservation o = world.Observe(in _inFlight.Move);
MoveOutcome outcome = MoveTracker.Observe(_inFlight, in o, nowMs);
if (outcome == MoveOutcome.Pending) return;
Finish(_inFlight.Move, outcome, nowMs);
@ -128,12 +175,12 @@ internal sealed class SortController
}
if (nowMs < _nextStepMs) return;
SortScope? scope = Job ?? (Data.Settings.Auto ? SortScope.Main : null);
SortScope? scope = Job ?? (Data.Settings.Auto ? SortScope.All : null);
if (scope == null)
{
Status = "off";
LastBot = null;
RefreshView(world, SortScope.Main, nowMs);
RefreshView(world, SortScope.All, nowMs);
_nextStepMs = nowMs + PollMs;
return;
}
@ -157,9 +204,17 @@ internal sealed class SortController
return;
}
_nextViewMs = nowMs + ViewMs;
if (!AfterRead(inv, nowMs))
{
// Rules not tied to their packs yet: nothing moves by a number that may be wrong.
Status = "reading your packs";
Planner.Plan(inv, Data.Rules, SortScope.Main, force: false, nowMs, Data.Settings.SettleSec * 1000, Options(world));
_nextStepMs = nowMs + PollMs;
return;
}
List<SortMove> moves = scope == SortScope.Unpack
? Planner.PlanUnpack(inv, UnpackWhich, nowMs)
: Planner.Plan(inv, Data.Rules, scope.Value, force: Job != null, nowMs, Data.Settings.SettleSec * 1000);
: Planner.Plan(inv, Data.Rules, scope.Value, force: Job != null, nowMs, Data.Settings.SettleSec * 1000, Options(world));
if (moves.Count == 0)
{
@ -174,12 +229,26 @@ internal sealed class SortController
Status = scope == SortScope.Unpack ? "unpacking" : "sorting";
SortMove m = moves[0];
int seq = world.ErrorSeqNow();
int stack = m.Item.Stack; // as read before the send (a merge's answer is a smaller stack)
if (!world.SendMove(in m))
{
Finish(m, MoveOutcome.Refused, nowMs, "the engine refused the move");
return;
}
_inFlight = new MoveInFlight { Move = m, SentMs = nowMs, ErrorSeqAtSend = seq, StackAtSend = m.Item.Stack };
_inFlight = new MoveInFlight { Move = m, SentMs = nowMs, ErrorSeqAtSend = seq, StackAtSend = stack };
}
/// <summary>What the planner may do: the engine's abilities and the settings.</summary>
internal PlanOptions Options(ISortWorld world)
{
SortAbilities a = world.Abilities;
return new PlanOptions
{
Order = a.ReadOrder && a.PlaceMoves && Data.Settings.OrderInPacks,
KindFirst = Data.Settings.OrderKindFirst,
Place = a.ReadOrder && a.PlaceMoves,
Merge = a.Merge,
};
}
private void NoteJobDone(SortScope job)
@ -189,7 +258,7 @@ internal sealed class SortController
{
case SortScope.Unpack: Note(v.MainFull ? "Main pack is full: unpacking stopped" : "Side packs emptied"); break;
case SortScope.Clean: Note(v.MainFull ? "Main pack is full: some strays left" : "Packs cleaned"); break;
case SortScope.All: Note(v.Waiting > 0 ? $"Packs tidied ({v.Waiting} can't move yet)" : "Packs tidied"); break;
case SortScope.All: Note(v.Waiting > 0 ? $"Packs sorted ({v.Waiting} can't move yet)" : "Packs sorted"); break;
default: Note(v.Waiting > 0 ? $"Main pack sorted ({v.Waiting} can't move yet)" : "Main pack sorted"); break;
}
}
@ -203,7 +272,16 @@ internal sealed class SortController
case MoveOutcome.Done:
Moved++;
_failuresInARow = 0;
Note($"{name} -> {m.DestLabel}");
if (m.Kind == MoveKind.Reorder)
{
Planner.NoteReorder(m.Item.Id, nowMs);
NoteReorderRun(m);
}
else
{
_reorderRunLine = null;
Note($"{name} {m.Done}");
}
_nextStepMs = nowMs + gap;
return;
case MoveOutcome.TooBusy:
@ -223,6 +301,32 @@ internal sealed class SortController
}
}
/// <summary>
/// After each read: the one-time pack fix once the side slots have read the same for
/// <see cref="FixSettleMs"/> (a pack whose capacity isn't readable yet could pass for a focus),
/// then each rule's number kept on its pack. False while imported rules still wait for the fix
/// (their numbers may name the wrong pack); rules saved by RynthSort meant what they say and
/// sort on meanwhile.
/// </summary>
private bool AfterRead(SortInventory inv, long nowMs)
{
if (!Data.PacksFixed)
{
bool hold = Data.ImportedFrom.Length > 0;
if (!PackFix.Ready(inv)) { _fixLayout = null; return !hold; }
string layout = PackFix.Layout(inv);
if (layout != _fixLayout) { _fixLayout = layout; _fixLayoutSince = nowMs; return !hold; }
if (nowMs - _fixLayoutSince < FixSettleMs) return !hold;
List<string> lines = PackFix.Apply(Data.Rules, inv, hold, Data.LuaRules, out int changed);
Data.PacksFixed = true;
Data.LuaRules = null;
if (hold) Note($"Imported pack numbers fixed: {changed} of {lines.Count} rules");
PacksFixed?.Invoke(lines, changed);
}
if (PackFix.Sync(Data.Rules, inv)) SettingsChanged?.Invoke();
return true;
}
/// <summary>Re-reads the packs for the window now and then while nothing moves.</summary>
private void RefreshView(ISortWorld world, SortScope scope, long nowMs)
{
@ -230,7 +334,8 @@ internal sealed class SortController
_nextViewMs = nowMs + ViewMs;
SortInventory? inv = world.ReadInventory();
if (inv == null) return;
AfterRead(inv, nowMs);
if (scope == SortScope.Unpack) Planner.PlanUnpack(inv, UnpackWhich, nowMs);
else Planner.Plan(inv, Data.Rules, scope, force: false, nowMs, Data.Settings.SettleSec * 1000);
else Planner.Plan(inv, Data.Rules, scope, force: false, nowMs, Data.Settings.SettleSec * 1000, Options(world));
}
}

View file

@ -99,7 +99,10 @@ internal sealed class LootWatch
{
if (containerId != 0)
{
if (containerId != _id || itemCount != _count)
// An unreadable count (-1) is not a change: a count read that flickered between -1 and
// the real number made a corpse left open look like it was being looted for ever
// ("paused: looting" while standing still, 2026-10-11).
if (containerId != _id || (itemCount >= 0 && itemCount != _count))
{
_id = containerId;
_count = itemCount;

View file

@ -1,4 +1,6 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace RynthCore.Plugin.RynthSort.Sorting;
@ -24,11 +26,140 @@ internal sealed class SortPack
/// <summary>How many items it holds (ItemsCapacity; 102 for the main pack and 24 for a side pack when unknown).</summary>
public int Capacity;
public readonly List<SortItem> Items = new();
/// <summary>
/// <see cref="Items"/> are in the pack's real slot order (slot 0 first: the engine's
/// GetContainerOrder, API v80, agreed with the contents read). False: object-id order, and
/// nothing is reordered in this pack.
/// </summary>
public bool OrderKnown;
/// <summary>
/// Puts <see cref="Items"/> in <paramref name="order"/> (the pack's slot order) when that names
/// exactly the items read, each once; else leaves them and <see cref="OrderKnown"/> false (a
/// list a move behind the contents, or a pack the server hasn't listed: never guessed).
/// </summary>
public bool ApplyOrder(IReadOnlyList<uint> order, int count)
{
OrderKnown = false;
if (count != Items.Count) return false;
var byId = new Dictionary<uint, SortItem>(Items.Count);
foreach (SortItem it in Items)
if (!byId.TryAdd(it.Id, it)) return false;
var sorted = new List<SortItem>(count);
for (int i = 0; i < count; i++)
{
if (!byId.Remove(order[i], out SortItem? it)) return false; // unknown here, or listed twice
sorted.Add(it);
}
Items.Clear();
Items.AddRange(sorted);
OrderKnown = true;
return true;
}
/// <summary>
/// What is in it, in a few words: the 2-3 commonest kinds of item ("Salvage, Gems"), by
/// class, or by name for the classes that say little (Misc, Unknown); "empty" when empty.
/// </summary>
public string Summary(int most = 3)
{
if (Items.Count == 0) return "empty";
var counts = new Dictionary<string, int>(StringComparer.Ordinal);
var order = new List<string>();
foreach (SortItem it in Items)
{
string key = KindOf(it);
if (key.Length == 0) continue;
if (counts.TryGetValue(key, out int n)) counts[key] = n + 1;
else { counts[key] = 1; order.Add(key); }
}
if (order.Count == 0) return "unknown items";
// Commonest first; a tie keeps the order the kinds were met in.
var ranked = new List<string>(order);
ranked.Sort((a, b) => counts[a] != counts[b] ? counts[b].CompareTo(counts[a]) : order.IndexOf(a).CompareTo(order.IndexOf(b)));
var sb = new StringBuilder();
for (int i = 0; i < ranked.Count && i < most; i++)
{
if (i > 0) sb.Append(", ");
sb.Append(ranked[i]);
}
return sb.ToString();
}
/// <summary>The kind an item counts as in <see cref="Summary"/>.</summary>
internal static string KindOf(SortItem it)
{
int c = it.ObjectClass;
if (c == ObjectClasses.Misc || c == ObjectClasses.Unknown || c == ObjectClasses.Bundle)
return Shorten(it.Name);
return ObjectClasses.Plural(c);
}
private static string Shorten(string? name)
{
string n = (name ?? string.Empty).Trim();
return n.Length <= 24 ? n : n[..23] + "~";
}
}
/// <summary>The character's packs: the main pack and the side packs in order, top to bottom (pack 1 first).</summary>
/// <summary>A side-slot thing in the main pack (a side pack or a focus), in the client's list order.</summary>
internal readonly struct SortSlot
{
public readonly uint Id;
/// <summary>ItemsCapacity: above 0 for a side pack, 0 for a focus, -1 when it couldn't be read.</summary>
public readonly int Capacity;
public SortSlot(uint id, int capacity)
{
Id = id;
Capacity = capacity;
}
public bool IsPack => Capacity > 0;
}
/// <summary>
/// The character's packs: the main pack and the side packs, pack 1 first. With the engine's slot
/// order (API v80) that is the pack column on screen, top first (<see cref="PackOrderKnown"/>);
/// else GetContainerContents' order, by object id. Rules keep the pack's id either way, so a
/// pack keeps its rules whatever its number.
/// </summary>
internal sealed class SortInventory
{
public SortPack Main = new();
public readonly List<SortPack> Packs = new();
/// <summary>
/// Every container entry in the main pack, foci included, in object-id order (what the Lua
/// script numbered its packs by: game.Character.Containers). Never reordered: the one-time
/// fix of imported Lua pack numbers (<see cref="PackFix"/>) reads the Lua numbers through it.
/// </summary>
public readonly List<SortSlot> Slots = new();
/// <summary><see cref="Packs"/> are in the pack column's order, top first.</summary>
public bool PackOrderKnown;
/// <summary>
/// Puts <see cref="Packs"/> in the pack column's order: <paramref name="order"/> is the main
/// pack's side-slot list (packs and foci, top first). Only when it names every pack read; else
/// the packs keep their order and <see cref="PackOrderKnown"/> is false.
/// </summary>
public bool ApplyPackOrder(IReadOnlyList<uint> order, int count)
{
PackOrderKnown = false;
var rank = new Dictionary<uint, int>(count);
for (int i = 0; i < count; i++) rank.TryAdd(order[i], i);
foreach (SortPack p in Packs)
if (!rank.ContainsKey(p.Id)) return false;
Packs.Sort((a, b) => rank[a.Id].CompareTo(rank[b.Id]));
PackOrderKnown = true;
return true;
}
/// <summary>The 1-based number of side pack <paramref name="id"/>, or 0 when it isn't carried.</summary>
public int IndexOf(uint id)
{
if (id == 0) return 0;
for (int i = 0; i < Packs.Count; i++)
if (Packs[i].Id == id) return i + 1;
return 0;
}
}

View file

@ -6,9 +6,13 @@ namespace RynthCore.Plugin.RynthSort.Sorting;
/// <summary>What a planning pass looks at.</summary>
internal enum SortScope
{
/// <summary>Only the main pack; an item moves once it has sat there for the settle time (unless forced).</summary>
/// <summary>Only the main pack's items to their packs; an item moves once it has sat there for the settle time (unless forced).</summary>
Main,
/// <summary>Every pack, no settling: items in the wrong side pack move to theirs too ("Tidy").</summary>
/// <summary>
/// Every pack: main-pack items to their packs (after the settle time unless forced), items in the
/// wrong side pack to theirs, then (with <see cref="PlanOptions"/>) stacks joined and items put
/// in order inside each pack. Auto-sort ("keep every pack tidy"), and Sort now (forced).
/// </summary>
All,
/// <summary>As <see cref="All"/>, and side-pack items no rule wants go back to the main pack ("Clean").</summary>
Clean,
@ -16,6 +20,17 @@ internal enum SortScope
Unpack,
}
/// <summary>What a move does.</summary>
internal enum MoveKind : byte
{
/// <summary>To another pack (maybe joining a stack there, maybe at a slot).</summary>
Route,
/// <summary>Joins another stack of the same kind in its own pack (<see cref="SortMove.MergeInto"/>).</summary>
Stack,
/// <summary>To another slot in its own pack (<see cref="SortMove.Placement"/>).</summary>
Reorder,
}
/// <summary>One move: <see cref="Item"/> into <see cref="Dest"/> (pack <see cref="DestIndex"/>, 0 = main pack).</summary>
internal readonly struct SortMove
{
@ -24,24 +39,78 @@ internal readonly struct SortMove
public readonly int DestIndex;
/// <summary>A stack in <see cref="Dest"/> the item joins (a merge), or 0 for a plain move.</summary>
public readonly uint MergeInto;
/// <summary>The slot in <see cref="Dest"/> it should end at (counted without it), or -1: the first empty slot.</summary>
public readonly int Placement;
public readonly MoveKind Kind;
public SortMove(SortItem item, SortPack dest, int destIndex, uint mergeInto)
public SortMove(SortItem item, SortPack dest, int destIndex, uint mergeInto, int placement = -1, MoveKind kind = MoveKind.Route)
{
Item = item;
Dest = dest;
DestIndex = destIndex;
MergeInto = mergeInto;
Placement = placement;
Kind = kind;
}
/// <summary>The item is already in <see cref="Dest"/> (a stack joined or a slot changed there).</summary>
public bool InPlace => Kind != MoveKind.Route;
public string DestLabel => DestIndex == 0 ? "main pack" : "pack " + DestIndex;
/// <summary>What the log says it did: "-> pack 2", "stacked in pack 2", "put in order in pack 2".</summary>
public string Done => Kind switch
{
MoveKind.Stack => "stacked in " + DestLabel,
MoveKind.Reorder => "put in order in " + DestLabel,
_ => "-> " + DestLabel,
};
}
/// <summary>What a planning pass may do beyond moving items to their packs (what the engine and the settings allow).</summary>
internal struct PlanOptions
{
/// <summary>Put items in order inside each pack whose slot order is known (API v80 and the "order" setting).</summary>
public bool Order;
/// <summary>The order groups by kind (class) first, then name.</summary>
public bool KindFirst;
/// <summary>Moves can name a slot (API v80): an item going to a pack whose order is known lands in its place.</summary>
public bool Place;
/// <summary>Stacks of the same kind in one pack are joined (the engine can merge stacks).</summary>
public bool Merge;
/// <summary>Everything on: an engine with API v80 and the default settings.</summary>
public static PlanOptions Full => new() { Order = true, Place = true, Merge = true };
}
/// <summary>A side pack as the window lists it.</summary>
internal sealed class PackLine
{
public uint Id;
public string Name = string.Empty;
public int Used;
public int Capacity;
/// <summary>What is in it, in a few words (<see cref="SortPack.Summary"/>).</summary>
public string Summary = string.Empty;
/// <summary>Its slot order is known (it can be put in order).</summary>
public bool OrderKnown;
/// <summary>Items out of place in it (0 = in order; only counted when the order is known and ordering is on).</summary>
public int OutOfPlace;
/// <summary>"Sack (12/24) - Salvage, Gems".</summary>
public string Label => $"{Name} ({Used}/{Capacity}) - {Summary}";
/// <summary>"Sack - Salvage, Gems": what a rule remembers of its pack.</summary>
public string Note => $"{Name} - {Summary}";
}
/// <summary>A rule whose pack isn't carried: it goes nowhere (<see cref="UsedPack"/> 0) or to the pack its number names.</summary>
internal sealed class RulePackIssue
{
public SortRule Rule = null!;
/// <summary>1-based place in the rule list.</summary>
public int RuleNumber;
/// <summary>The side pack used instead (its number), or 0 when the rule has none.</summary>
public int UsedPack;
}
/// <summary>What the window shows about the packs after a planning pass.</summary>
@ -50,30 +119,54 @@ internal sealed class SortView
public readonly List<PackLine> Packs = new();
public int MainUsed;
public int MainCapacity;
/// <summary>The main pack as a line (its order state; Id is the player).</summary>
public PackLine Main = new();
/// <summary>The packs are numbered top to bottom as the pack column shows them (else by object id).</summary>
public bool PackOrderKnown;
/// <summary>The pass could put items in order (the engine reads slot orders and ordering is on).</summary>
public bool Ordering;
/// <summary>Items a rule wants moved that can't go yet (settling, pack full, pack missing, main full).</summary>
public int Waiting;
/// <summary>Side packs (1-based) a rule wants to fill that are full.</summary>
public readonly SortedSet<int> Full = new();
/// <summary>Pack numbers rules use that the character doesn't have.</summary>
/// <summary>Pack numbers rules (that are on) use and the character doesn't have.</summary>
public readonly SortedSet<int> Missing = new();
/// <summary>Rules (that are on) whose pack isn't carried, in rule order.</summary>
public readonly List<RulePackIssue> Issues = new();
/// <summary>Clean or Unpack found the main pack full.</summary>
public bool MainFull;
}
/// <summary>
/// The sorting rules applied to the packs: which items move where, one planning pass at a time.
/// A port of the Lua script's plan/planUnpack: rules are tried in order and the first match wins;
/// worn and wielded items, packs and foci never move; a full pack is only used when the item
/// joins a stack there; an item that failed to move is left alone until its block runs out.
/// Each item has one place: the pack of the rule it follows (<see cref="SortRules.RuleFor"/>; the
/// pack its id names, else its number: <see cref="SortRules.Resolve"/>), or where it is when no
/// rule wants it (Clean: back to the main pack). Worn and wielded items, packs and foci never
/// move; a full pack is only used when the item joins a stack there; an item that failed to move
/// is left alone until its block runs out.
///
/// With <see cref="PlanOptions"/>, once nothing needs to change packs, every pack is tidied in
/// place: two stacks of one kind are joined, then items are put in order (<see cref="PackOrder"/>).
/// The main pack only once every item in it has settled.
///
/// It converges: a route takes an item to its one place and nothing sends it back (its place
/// depends on the rules and the packs carried, not on where it is); a join leaves one stack fewer
/// that isn't full; a reorder grows the run of items already in order. Each kind of move is
/// finite, so a fixed inventory runs out of moves. As a backstop, an item put in order
/// <see cref="MaxReorders"/> times within <see cref="ReorderWindowMs"/> isn't reordered again
/// until that window passes (an order the engine and the server see differently can't loop).
/// Pure (no host calls): the tests drive it with hand-made inventories.
/// </summary>
internal sealed class SortPlanner
{
public const int SideCapacityFallback = 24;
public const int MainCapacityFallback = 102;
public const int MaxReorders = 6;
public const long ReorderWindowMs = 10 * 60_000;
private readonly Dictionary<uint, long> _firstSeen = new();
private readonly Dictionary<uint, long> _blocked = new();
private readonly Dictionary<uint, (int Count, long Since)> _reorders = new();
public SortView View { get; private set; } = new();
@ -82,6 +175,7 @@ internal sealed class SortPlanner
{
_firstSeen.Clear();
_blocked.Clear();
_reorders.Clear();
View = new SortView();
}
@ -97,6 +191,17 @@ internal sealed class SortPlanner
return n;
}
/// <summary>An item was put in order (a reorder move landed).</summary>
public void NoteReorder(uint itemId, long nowMs)
{
if (_reorders.TryGetValue(itemId, out var r) && nowMs - r.Since < ReorderWindowMs) _reorders[itemId] = (r.Count + 1, r.Since);
else _reorders[itemId] = (1, nowMs);
}
/// <summary>The item has been put in order <see cref="MaxReorders"/> times lately: not again for now.</summary>
public bool ReorderLimited(uint itemId, long nowMs) =>
_reorders.TryGetValue(itemId, out var r) && nowMs - r.Since < ReorderWindowMs && r.Count >= MaxReorders;
/// <summary>Worn and wielded items, packs and foci never move.</summary>
public static bool Sortable(SortItem it) =>
!it.Wielded && it.ObjectClass != ObjectClasses.Container && it.ObjectClass != ObjectClasses.Foci;
@ -119,24 +224,69 @@ internal sealed class SortPlanner
return 0;
}
private static bool SameKind(SortItem a, SortItem b) =>
internal static bool SameKind(SortItem a, SortItem b) =>
a.Wcid != 0 && b.Wcid != 0 ? a.Wcid == b.Wcid : string.Equals(a.Name, b.Name, StringComparison.Ordinal) && a.Name.Length > 0;
private static bool HasRoom(SortItem it) => it.MaxStack > 1 && it.Stack < it.MaxStack;
/// <summary>
/// Two stacks of one kind in <paramref name="pack"/> that both have room: the smaller one
/// (<paramref name="from"/>) joins the larger (<paramref name="into"/>). The first such kind in
/// the pack's order; the same answer for the same pack. False when every kind has at most one
/// stack with room.
/// </summary>
public static bool StackJoin(SortPack pack, Func<SortItem, bool> movable, out SortItem from, out SortItem into)
{
from = into = null!;
List<SortItem> items = pack.Items;
var seen = new bool[items.Count];
for (int i = 0; i < items.Count; i++)
{
if (seen[i] || !HasRoom(items[i]) || !Sortable(items[i])) continue;
SortItem? small = null, big = null;
for (int j = i; j < items.Count; j++)
{
SortItem it = items[j];
if (j > i && (seen[j] || !HasRoom(it) || !Sortable(it) || !SameKind(items[i], it))) continue;
seen[j] = true;
if (big == null || it.Stack > big.Stack || (it.Stack == big.Stack && it.Id < big.Id)) big = it;
}
foreach (SortItem it in items)
{
if (ReferenceEquals(it, big) || !HasRoom(it) || !Sortable(it) || !SameKind(items[i], it) || !movable(it)) continue;
if (small == null || it.Stack < small.Stack || (it.Stack == small.Stack && it.Id > small.Id)) small = it;
}
if (small != null && big != null) { from = small; into = big; return true; }
}
return false;
}
/// <summary>The moves to make now (routes only, as before ordering existed). See the overload.</summary>
public List<SortMove> Plan(SortInventory inv, IReadOnlyList<SortRule> rules, SortScope scope, bool force, long nowMs, int settleMs) =>
Plan(inv, rules, scope, force, nowMs, settleMs, default);
/// <summary>
/// The moves to make now for <paramref name="scope"/> (not <see cref="SortScope.Unpack"/>: see
/// <see cref="PlanUnpack"/>), first one first. Also refreshes <see cref="View"/> and the main
/// pack's settle clock (an item's time starts when a pass first sees it in the main pack).
/// <see cref="PlanUnpack"/>), first one first: items to their packs, then (All and Clean, with
/// <paramref name="opt"/>, when no item needs another pack) stacks joined, then items put in
/// order, a pack at a time. Also refreshes <see cref="View"/> and the main pack's settle clock
/// (an item's time starts when a pass first sees it in the main pack).
/// </summary>
public List<SortMove> Plan(SortInventory inv, IReadOnlyList<SortRule> rules, SortScope scope, bool force, long nowMs, int settleMs)
public List<SortMove> Plan(SortInventory inv, IReadOnlyList<SortRule> rules, SortScope scope, bool force, long nowMs, int settleMs, PlanOptions opt)
{
bool everyPack = scope != SortScope.Main;
bool evict = scope == SortScope.Clean;
bool inPack = scope is SortScope.All or SortScope.Clean;
var moves = new List<SortMove>();
var view = new SortView();
var used = new int[inv.Packs.Count + 1];
for (int i = 0; i < inv.Packs.Count; i++) used[i + 1] = inv.Packs[i].Items.Count;
int mainUsed = inv.Main.Items.Count;
int mainCap = CapacityOf(inv.Main, MainCapacityFallback);
bool kindFirst = opt.KindFirst;
int PlaceIn(SortPack dest, SortItem wo, uint joins) =>
opt.Place && joins == 0 && dest.OrderKnown ? PackOrder.InsertAt(dest.Items, wo, kindFirst) : -1;
void Consider(SortItem wo, int from, bool settled)
{
@ -148,7 +298,7 @@ internal sealed class SortPlanner
uint joins = StackTarget(wo, inv.Main);
if (mainUsed < mainCap || joins != 0)
{
moves.Add(new SortMove(wo, inv.Main, 0, joins));
moves.Add(new SortMove(wo, inv.Main, 0, joins, PlaceIn(inv.Main, wo, joins)));
if (joins == 0) mainUsed++;
}
else
@ -158,18 +308,19 @@ internal sealed class SortPlanner
}
return;
}
if (r == null || r.Pack == from) return;
if (r.Pack < 1 || r.Pack > inv.Packs.Count)
if (r == null) return;
int to = SortRules.Resolve(r, inv, out _);
if (to == 0)
{
view.Missing.Add(r.Pack);
view.Waiting++;
view.Waiting++; // reported once per rule below (Issues / Missing)
return;
}
SortPack dest = inv.Packs[r.Pack - 1];
if (to == from) return;
SortPack dest = inv.Packs[to - 1];
uint into = StackTarget(wo, dest);
if (used[r.Pack] >= CapacityOf(dest, SideCapacityFallback) && into == 0)
if (used[to] >= CapacityOf(dest, SideCapacityFallback) && into == 0)
{
view.Full.Add(r.Pack);
view.Full.Add(to);
view.Waiting++;
return;
}
@ -178,16 +329,19 @@ internal sealed class SortPlanner
view.Waiting++;
return;
}
moves.Add(new SortMove(wo, dest, r.Pack, into));
if (into == 0) used[r.Pack]++;
moves.Add(new SortMove(wo, dest, to, into, PlaceIn(dest, wo, into)));
if (into == 0) used[to]++;
}
var inMain = new HashSet<uint>();
bool mainSettled = true;
foreach (SortItem wo in inv.Main.Items)
{
inMain.Add(wo.Id);
if (!_firstSeen.TryGetValue(wo.Id, out long seen)) _firstSeen[wo.Id] = seen = nowMs;
Consider(wo, 0, force || everyPack || nowMs - seen >= settleMs);
bool settled = force || nowMs - seen >= settleMs;
if (!settled) mainSettled = false;
Consider(wo, 0, settled);
}
if (_firstSeen.Count > inMain.Count)
{
@ -201,7 +355,35 @@ internal sealed class SortPlanner
foreach (SortItem wo in inv.Packs[i].Items) Consider(wo, i + 1, true);
}
FillPacks(view, inv);
bool ordering = inPack && opt.Order;
if (inPack && moves.Count == 0)
{
// Nothing changes packs: tidy each pack in place. Side packs first, then the main pack
// once nothing in it is new (loot still settling there would be ordered twice).
bool Movable(SortItem it) => Sortable(it) && !IsBlocked(it.Id, nowMs);
var stacks = new List<SortMove>();
var reorders = new List<SortMove>();
for (int i = 0; i <= inv.Packs.Count; i++)
{
bool main = i == inv.Packs.Count;
if (main && !mainSettled) break;
SortPack pack = main ? inv.Main : inv.Packs[i];
int index = main ? 0 : i + 1;
if (opt.Merge && StackJoin(pack, Movable, out SortItem from, out SortItem into))
{
stacks.Add(new SortMove(from, pack, index, into.Id, -1, MoveKind.Stack));
continue;
}
if (ordering && pack.OrderKnown && PackOrder.AllNamed(pack.Items)
&& PackOrder.NextMove(pack.Items, kindFirst, it => Movable(it) && !ReorderLimited(it.Id, nowMs), out SortItem item, out int at))
reorders.Add(new SortMove(item, pack, index, 0, at, MoveKind.Reorder));
}
moves.AddRange(stacks);
moves.AddRange(reorders);
}
FillPacks(view, inv, ordering, kindFirst);
FillIssues(view, inv, rules);
View = view;
return moves;
}
@ -232,21 +414,44 @@ internal sealed class SortPlanner
}
}
var view = new SortView { Waiting = waiting, MainFull = waiting > 0 };
FillPacks(view, inv);
FillPacks(view, inv, false, false);
View = view;
return moves;
}
private static void FillPacks(SortView view, SortInventory inv)
private static PackLine LineOf(SortPack p, int capacityFallback, bool ordering, bool kindFirst) => new()
{
Id = p.Id,
Name = p.Name.Length > 0 ? p.Name : "Pack",
Used = p.Items.Count,
Capacity = CapacityOf(p, capacityFallback),
Summary = p.Summary(),
OrderKnown = p.OrderKnown,
OutOfPlace = ordering && p.OrderKnown ? PackOrder.OutOfPlace(p.Items, kindFirst) : 0,
};
private static void FillPacks(SortView view, SortInventory inv, bool ordering, bool kindFirst)
{
view.MainUsed = inv.Main.Items.Count;
view.MainCapacity = CapacityOf(inv.Main, MainCapacityFallback);
foreach (SortPack p in inv.Packs)
view.Packs.Add(new PackLine
{
Name = p.Name.Length > 0 ? p.Name : "Pack",
Used = p.Items.Count,
Capacity = CapacityOf(p, SideCapacityFallback),
});
view.Main = LineOf(inv.Main, MainCapacityFallback, ordering, kindFirst);
view.Main.Name = "Main pack";
view.PackOrderKnown = inv.PackOrderKnown;
view.Ordering = ordering;
foreach (SortPack p in inv.Packs) view.Packs.Add(LineOf(p, SideCapacityFallback, ordering, kindFirst));
}
/// <summary>Every rule that is on and whose pack isn't carried (whether or not an item wants it now).</summary>
private static void FillIssues(SortView view, SortInventory inv, IReadOnlyList<SortRule> rules)
{
for (int i = 0; i < rules.Count; i++)
{
SortRule r = rules[i];
if (!r.On) continue;
int to = SortRules.Resolve(r, inv, out bool fellBack);
if (to != 0 && !fellBack) continue;
if (to == 0) view.Missing.Add(r.Pack);
view.Issues.Add(new RulePackIssue { Rule = r, RuleNumber = i + 1, UsedPack = to });
}
}
}

View file

@ -1,35 +1,132 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace RynthCore.Plugin.RynthSort.Sorting;
/// <summary>Which test a rule makes.</summary>
internal enum RuleKind
{
/// <summary>The item's ObjectClass equals <see cref="SortRule.Class"/>.</summary>
Class = 0,
/// <summary>The item's name contains <see cref="SortRule.Text"/> (any case).</summary>
Name = 1,
}
/// <summary>
/// One rule: items it matches go to side pack <see cref="Pack"/> (1 = the first side pack, top to
/// bottom). The same fields as the Lua script's rules: { on, kind = "class" | "name", class, text, pack }.
/// One rule: items whose class is one of <see cref="Classes"/>, or whose name contains one of
/// <see cref="Names"/> (any case), go to the side pack <see cref="PackId"/> names while it is
/// carried, else to side pack number <see cref="Pack"/> (1 = the top side pack when the pack
/// order is known). "Armor, Clothing, name has Shield -> pack 4" is one rule.
/// A rule saved before rules held several entries (the Lua script's { kind, class | text }, and
/// RynthSort's file versions 1 and 2) loads as a rule with one entry.
/// </summary>
internal sealed class SortRule
{
public const int MaxClasses = 32, MaxNames = 16, MaxNameLength = 64;
private static int _nextUid;
/// <summary>Stable for the session (never saved): the window's widget ids, so a rule keeps its row while the list resorts.</summary>
public readonly int Uid = Interlocked.Increment(ref _nextUid);
public bool On = true;
public RuleKind Kind = RuleKind.Class;
/// <summary>An ObjectClass number (<see cref="ObjectClasses"/>).</summary>
public int Class = ObjectClasses.SpellComponent;
public string Text = string.Empty;
/// <summary>ObjectClass numbers (<see cref="ObjectClasses"/>), each once.</summary>
public readonly List<int> Classes = new();
/// <summary>Parts of item names (any case), each once.</summary>
public readonly List<string> Names = new();
/// <summary>The pack's number: the fallback when <see cref="PackId"/> isn't carried (or is 0), and what the window shows.</summary>
public int Pack = 1;
/// <summary>The side pack's object id (0 = none yet: the number decides). Pack order and foci can't shift it.</summary>
public uint PackId;
/// <summary>What the pack was when it was picked ("Sack - Salvage, Gems"), for the warning when it's gone.</summary>
public string PackNote = string.Empty;
public SortRule Clone() => new() { On = On, Kind = Kind, Class = Class, Text = Text, Pack = Pack };
/// <summary>No class and no name: it matches nothing (a rule just added, before anything is put in it).</summary>
public bool IsEmpty => Classes.Count == 0 && Names.Count == 0;
public static SortRule ForClass(int cls, int pack) => new() { Kind = RuleKind.Class, Class = cls, Pack = pack };
public static SortRule ForName(string text, int pack) => new() { Kind = RuleKind.Name, Text = text, Pack = pack };
public bool HasClass(int cls) => Classes.Contains(cls);
public bool HasName(string text) => IndexOfName(text) >= 0;
private int IndexOfName(string text)
{
for (int i = 0; i < Names.Count; i++)
if (string.Equals(Names[i], text, StringComparison.OrdinalIgnoreCase)) return i;
return -1;
}
/// <summary>Adds a class (false when it's there already or the rule is full).</summary>
public bool AddClass(int cls)
{
if (cls < 0 || Classes.Contains(cls) || Classes.Count >= MaxClasses) return false;
Classes.Add(cls);
return true;
}
public bool RemoveClass(int cls) => Classes.Remove(cls);
/// <summary>Adds a name part, trimmed and cut to <see cref="MaxNameLength"/> (false when blank, there already, or the rule is full).</summary>
public bool AddName(string? text)
{
string t = Clean(text);
if (t.Length == 0 || IndexOfName(t) >= 0 || Names.Count >= MaxNames) return false;
Names.Add(t);
return true;
}
public bool RemoveName(string text)
{
int i = IndexOfName(text);
if (i < 0) return false;
Names.RemoveAt(i);
return true;
}
public static string Clean(string? text)
{
string t = (text ?? string.Empty).Trim();
return t.Length > MaxNameLength ? t[..MaxNameLength].TrimEnd() : t;
}
/// <summary>Everything of <paramref name="other"/>'s classes and names this rule doesn't have yet.</summary>
public void TakeEntriesOf(SortRule other)
{
foreach (int c in other.Classes) AddClass(c);
foreach (string n in other.Names) AddName(n);
}
public SortRule Clone()
{
var r = new SortRule { On = On, Pack = Pack, PackId = PackId, PackNote = PackNote };
r.Classes.AddRange(Classes);
r.Names.AddRange(Names);
return r;
}
/// <summary>The same classes and names (in any order, names any case) and the same pack number: what an untouched imported rule looks like.</summary>
public bool SameAs(SortRule o)
{
if (Pack != o.Pack || Classes.Count != o.Classes.Count || Names.Count != o.Names.Count) return false;
foreach (int c in Classes) if (!o.Classes.Contains(c)) return false;
foreach (string n in Names) if (!o.HasName(n)) return false;
return true;
}
public static SortRule ForClass(int cls, int pack)
{
var r = new SortRule { Pack = pack };
r.AddClass(cls);
return r;
}
public static SortRule ForName(string text, int pack)
{
var r = new SortRule { Pack = pack };
r.AddName(text);
return r;
}
/// <summary>A rule with several classes (and names): "Gem, Mana Stone, Key -> pack 3".</summary>
public static SortRule For(int pack, int[] classes, params string[] names)
{
var r = new SortRule { Pack = pack };
foreach (int c in classes) r.AddClass(c);
foreach (string n in names) r.AddName(n);
return r;
}
}
/// <summary>
@ -90,39 +187,130 @@ internal static class ObjectClasses
public static string Label(int cls) =>
cls >= 0 && cls < Names.Length ? Spaced(Names[cls]) : "class " + cls;
/// <summary>A class as a pack's contents read: "Components", "Gems", "Salvage".</summary>
public static string Plural(int cls) => cls switch
{
SpellComponent => "Components",
Salvage => "Salvage",
Gem => "Gems",
ManaStone => "Mana Stones",
Key => "Keys",
HealingKit => "Healing Kits",
Lockpick => "Lockpicks",
Food => "Food",
Scroll => "Scrolls",
TradeNote => "Trade Notes",
Money => "Money",
Plant => "Plants",
Jewelry => "Jewelry",
Armor => "Armor",
Clothing => "Clothing",
MeleeWeapon => "Melee Weapons",
MissileWeapon => "Missile Weapons",
WandStaffOrb => "Casters",
Book => "Books",
Journal => "Journals",
Ust => "Ust",
_ => Label(cls),
};
}
internal static class SortRules
{
/// <summary>The Lua script's defaults: components, salvage, then gems, stones and keys together.</summary>
/// <summary>The Lua script's defaults: components, salvage, then gems, stones and keys together (one rule).</summary>
public static List<SortRule> Defaults() => new()
{
SortRule.ForClass(ObjectClasses.SpellComponent, 1),
SortRule.ForClass(ObjectClasses.Salvage, 2),
SortRule.ForClass(ObjectClasses.Gem, 3),
SortRule.ForClass(ObjectClasses.ManaStone, 3),
SortRule.ForClass(ObjectClasses.Key, 3),
SortRule.For(3, new[] { ObjectClasses.Gem, ObjectClasses.ManaStone, ObjectClasses.Key }),
};
public static bool Matches(SortRule r, SortItem item)
/// <summary>The item's name contains one of the rule's names (any case).</summary>
public static bool MatchesName(SortRule r, SortItem item)
{
if (!r.On) return false;
if (r.Kind == RuleKind.Name)
{
string t = r.Text ?? string.Empty;
return t.Length > 0 && (item.Name ?? string.Empty).Contains(t, StringComparison.OrdinalIgnoreCase);
}
return item.ObjectClass == r.Class;
string name = item.Name ?? string.Empty;
if (name.Length == 0) return false;
foreach (string t in r.Names)
if (t.Length > 0 && name.Contains(t, StringComparison.OrdinalIgnoreCase)) return true;
return false;
}
/// <summary>The first rule that matches (rules are tried in order), or null.</summary>
public static bool MatchesClass(SortRule r, SortItem item) => r.Classes.Contains(item.ObjectClass);
public static bool Matches(SortRule r, SortItem item) => r.On && (MatchesName(r, item) || MatchesClass(r, item));
/// <summary>
/// The rule an item follows, or null. A name match beats a class match (it is the more
/// specific: "Armor -> 4" and "name has Shield -> 5" send shields to 5, whatever the order);
/// between two rules that match the same way, the one saved first wins (the window warns
/// when two rules name the same class or name).
/// </summary>
public static SortRule? RuleFor(IReadOnlyList<SortRule> rules, SortItem item)
{
for (int i = 0; i < rules.Count; i++)
if (Matches(rules[i], item)) return rules[i];
if (rules[i].On && MatchesName(rules[i], item)) return rules[i];
for (int i = 0; i < rules.Count; i++)
if (rules[i].On && MatchesClass(rules[i], item)) return rules[i];
return null;
}
public static string Describe(SortRule r) =>
r.Kind == RuleKind.Name ? $"name has \"{r.Text}\"" : ObjectClasses.Label(r.Class);
/// <summary>"Gem, Key, Mana Stone, name has "Opal"": the classes (A-Z), then the names (A-Z).</summary>
public static string Describe(SortRule r)
{
if (r.IsEmpty) return "(empty: add a class or a name)";
var parts = new List<string>(r.Classes.Count + r.Names.Count);
foreach (string l in ClassLabels(r)) parts.Add(l);
foreach (string n in SortedNames(r)) parts.Add($"name has \"{n}\"");
return string.Join(", ", parts);
}
/// <summary>The rule's classes as labels, A-Z.</summary>
public static List<string> ClassLabels(SortRule r)
{
var labels = r.Classes.ConvertAll(ObjectClasses.Label);
labels.Sort(StringComparer.OrdinalIgnoreCase);
return labels;
}
/// <summary>The rule's classes ordered by label, A-Z.</summary>
public static List<int> SortedClasses(SortRule r)
{
var list = new List<int>(r.Classes);
list.Sort((a, b) => string.Compare(ObjectClasses.Label(a), ObjectClasses.Label(b), StringComparison.OrdinalIgnoreCase));
return list;
}
public static List<string> SortedNames(SortRule r)
{
var list = new List<string>(r.Names);
list.Sort(StringComparer.OrdinalIgnoreCase);
return list;
}
/// <summary>The order rules are listed in under their pack: by <see cref="Describe"/>, A-Z (empty rules last).</summary>
public static int CompareForList(SortRule a, SortRule b)
{
if (a.IsEmpty != b.IsEmpty) return a.IsEmpty ? 1 : -1;
int c = string.Compare(Describe(a), Describe(b), StringComparison.OrdinalIgnoreCase);
return c != 0 ? c : a.Uid.CompareTo(b.Uid);
}
/// <summary>
/// The side pack the rule sends items to: 1-based index into <paramref name="inv"/>'s packs, or 0
/// when it has none. The pack <see cref="SortRule.PackId"/> names when that is carried; else
/// pack number <see cref="SortRule.Pack"/> when there is one (<paramref name="fellBack"/>: its id was set but isn't carried).
/// </summary>
public static int Resolve(SortRule r, SortInventory inv, out bool fellBack)
{
fellBack = false;
int byId = inv.IndexOf(r.PackId);
if (byId > 0) return byId;
if (r.Pack >= 1 && r.Pack <= inv.Packs.Count)
{
fellBack = r.PackId != 0;
return r.Pack;
}
return 0;
}
}

View file

@ -30,6 +30,8 @@ internal static class UiFormat
public const byte OpSameLine = 0x11;
public const byte OpSpacing = 0x13;
public const byte OpDummy = 0x14;
public const byte OpIndent = 0x15;
public const byte OpUnindent = 0x16;
public const byte OpButton = 0x20;
public const byte OpCheckbox = 0x21;
public const byte OpSliderInt = 0x22;
@ -49,6 +51,9 @@ internal static class UiFormat
// Window flags
public const uint FlagVisible = 1u << 0;
public const uint FlagShowInBar = 1u << 1;
/// <summary>With ShowInBar: a bar button of its own instead of a Scripts menu line (engines from
/// 2026-10-11; older ones ignore it and list the window in the Scripts menu).</summary>
public const uint FlagBarButton = 1u << 11;
public const uint FlagNoScrollbar = 1u << 5;
// Image icon kinds (op level 2)
@ -75,6 +80,8 @@ internal static class UiFormat
// InputText flags
public const uint InputAutoSelectAll = 4096;
/// <summary>The text box reports Enter (its event carries submitted = true).</summary>
public const uint InputEnterReturnsTrue = 32;
// CollapsingHeader flags
public const uint TreeDefaultOpen = 32;

View file

@ -42,6 +42,9 @@ internal sealed class UiWindow
public string Title;
public bool Visible;
public bool ShowInBar = true;
/// <summary>With ShowInBar: the window has its own button on the RynthCore bar (title as the
/// tooltip) rather than a line in the Scripts menu.</summary>
public bool BarButton = true;
public float DefaultWidth, DefaultHeight, MinWidth, MinHeight;
/// <summary>A pass is wanted at the next chance (input arrived, it was just shown, data changed).</summary>
@ -80,7 +83,8 @@ internal sealed class UiWindow
Title = title;
}
public uint Flags => (Visible ? UiFormat.FlagVisible : 0) | (ShowInBar ? UiFormat.FlagShowInBar : 0);
public uint Flags => (Visible ? UiFormat.FlagVisible : 0) | (ShowInBar ? UiFormat.FlagShowInBar : 0)
| (ShowInBar && BarButton ? UiFormat.FlagBarButton : 0);
public bool HeaderDirty =>
_sentTitle != Title || _sentFlags != Flags || _sentDw != DefaultWidth || _sentDh != DefaultHeight
@ -208,6 +212,23 @@ internal sealed class UiWindow
EndOp(p);
}
/// <summary>Moves the following items right by <paramref name="w"/> logical units, until <see cref="Unindent"/>.</summary>
public void Indent(float w)
{
if (!Room()) return;
int p = BeginOp(UiFormat.OpIndent);
F32(w);
EndOp(p);
}
public void Unindent(float w)
{
if (!Room()) return;
int p = BeginOp(UiFormat.OpUnindent);
F32(w);
EndOp(p);
}
public void Button(string label, string id, Action onClick, float w = 0f, float h = 0f, bool small = false)
{
if (!Room()) return;
@ -265,7 +286,11 @@ internal sealed class UiWindow
}
/// <summary>A text box; <paramref name="set"/> gets every edit (submitted = Enter was pressed).</summary>
public void InputText(string label, string id, string value, int maxLen, Action<string> set, uint flags = 0)
public void InputText(string label, string id, string value, int maxLen, Action<string> set, uint flags = 0) =>
InputText(label, id, value, maxLen, (text, _) => set(text), flags);
/// <summary>A text box; <paramref name="set"/> gets every edit and whether Enter was pressed.</summary>
public void InputText(string label, string id, string value, int maxLen, Action<string, bool> set, uint flags = 0)
{
if (!Room()) return;
maxLen = Math.Clamp(maxLen, 1, UiFormat.MaxString);
@ -277,7 +302,7 @@ internal sealed class UiWindow
U16((ushort)maxLen);
U32(flags);
EndOp(p);
_next[key] = e => { if (e.Type == UiFormat.EvText) set(e.Text); };
_next[key] = e => { if (e.Type == UiFormat.EvText) set(e.Text, e.Submitted); };
}
public void Combo(string label, string id, int index, IReadOnlyList<string> items, Action<int> set)

View file

@ -7,17 +7,23 @@ using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthSort.Views;
/// <summary>
/// The RynthSort window: the auto-sort box and status, the job buttons, warnings, the rule list
/// (first match wins: enable, select to edit, add, move up or down, remove) and the settings.
/// Recorded on the pump thread, replayed by the engine.
/// The RynthSort window: the auto-sort box and status, the job buttons, then one collapsing
/// section per side pack ("Pack 1: Sack (12/24) - Components", top pack first) holding that
/// pack's warnings and its rules (A-Z), a section for rules whose pack isn't carried, and the
/// settings. A rule is one row (on/off box, its classes and names); selecting it opens its
/// editor beneath: the classes and names as chips (click one to take it out), a class picker and
/// a name box to add, the pack it sends to, and Remove. Recorded on the pump thread, replayed by
/// the engine.
/// </summary>
internal sealed class SortPanel
{
private static readonly string[] Kinds = { "Class", "Name has" };
private const float RowIndent = 6f, EditorIndent = 22f;
private const int ChipsPerLine = 3;
private readonly SortController _c;
private readonly Action _save;
private int _selected = -1;
private SortRule? _selected;
private string _nameDraft = string.Empty;
/// <summary>Extra warnings the plugin knows about (the Lua script set to start too).</summary>
public Func<IReadOnlyList<string>> Warnings = () => Array.Empty<string>();
@ -30,7 +36,8 @@ internal sealed class SortPanel
_save = save;
}
public int Selected => _selected;
/// <summary>The rule whose editor is open, or null.</summary>
public SortRule? Selected => _selected;
public void Draw(UiWindow w)
{
@ -41,47 +48,58 @@ internal sealed class SortPanel
}
SortSettings s = _c.Data.Settings;
List<SortRule> rules = _c.Data.Rules;
if (_selected != null && !rules.Contains(_selected)) _selected = null;
SortView view = _c.Planner.View;
w.Checkbox("Auto-sort", "auto", s.Auto, v => _c.SetAuto(v));
w.Tooltip("New items in the main pack go to their pack after the settle time");
w.Tooltip("Keeps every pack tidy: new items go to their pack after the settle time, items in the wrong pack move to theirs, "
+ "stacks of one kind are joined and items are put in order (A-Z) inside each pack");
w.SameLine();
w.TextColored(_c.Paused ? UiColors.Amber : UiColors.Grey, _c.Status);
if (_c.Planner.View.Waiting > 0)
if (view.Waiting > 0)
{
w.SameLine();
w.TextDisabled($"({_c.Planner.View.Waiting} waiting)");
w.TextDisabled($"({view.Waiting} waiting)");
}
w.Button("Sort main pack", "job.main", () => _c.StartJob(SortScope.Main));
w.Tooltip("Sort the main pack now, without waiting for items to settle");
w.Button("Sort now", "job.all", () => _c.StartJob(SortScope.All));
w.Tooltip("Sort every pack now, without waiting for new items to settle");
w.SameLine();
w.Button("Tidy all packs", "job.all", () => _c.StartJob(SortScope.All));
w.Tooltip("Also move items that are in the wrong side pack");
w.Button("Clean packs", "job.clean", () => _c.StartJob(SortScope.Clean));
w.Tooltip("Sort now, and side-pack items no rule wants go back to the main pack");
w.SameLine();
w.Button("Empty side packs", "job.unpack", () => _c.StartUnpack(null));
w.Tooltip("Move everything from your side packs into the main pack. Turns auto-sort off first, so nothing moves back.");
w.Button("Clean packs", "job.clean", () => _c.StartJob(SortScope.Clean));
w.Tooltip("Side-pack items no rule wants go to the main pack; items in the wrong side pack go to theirs");
SortView view = _c.Planner.View;
w.TextDisabled($"Main pack ({view.Main.Used}/{view.Main.Capacity}){OrderNote(view, view.Main, " - ")}");
w.Tooltip("Items no rule names stay in the main pack");
if (view.MainFull) w.TextColored(UiColors.Amber, "The main pack is full");
foreach (int p in view.Full) w.TextColored(UiColors.Amber, $"Pack {p} is full");
foreach (int p in view.Missing) w.TextColored(UiColors.Amber, $"A rule uses pack {p}, which you don't have");
if (s.Auto && _c.LastBot is RynthAiActivity bot && (bot & RynthAiActivity.AutoCram) != 0 && (bot & RynthAiActivity.MacroRunning) != 0)
w.TextColored(UiColors.Amber, "RynthAi's AutoCram also moves loot out of the main pack; turn one of them off");
foreach (string warning in Warnings()) w.TextColored(UiColors.Amber, warning);
if (w.CollapsingHeader("Rules (first match wins)", "rules", defaultOpen: true))
DrawRules(w, rules, view);
Dictionary<int, List<SortRule>> byPack = Group(rules, view);
Dictionary<int, List<string>> conflicts = Conflicts(rules, view);
for (int i = 1; i <= view.Packs.Count; i++)
DrawPack(w, view, rules, i, byPack.TryGetValue(i, out List<SortRule>? list) ? list : new List<SortRule>(),
conflicts.TryGetValue(i, out List<string>? c) ? c : null);
if (byPack.TryGetValue(0, out List<SortRule>? missing)) DrawMissing(w, view, rules, missing);
if (view.Packs.Count == 0) w.TextDisabled("No side packs: items stay in the main pack.");
if (w.CollapsingHeader("Settings", "settings"))
{
w.SliderInt("Settle (s)", "settle", s.SettleSec, SortSettings.SettleMin, SortSettings.SettleMax, v => { s.SettleSec = v; _save(); });
w.Tooltip("How long a new item sits in the main pack before it is moved");
w.SliderInt("Gap (ms)", "gap", s.GapMs, SortSettings.GapMin, SortSettings.GapMax, v => { s.GapMs = v; _save(); });
w.Tooltip("Auto-sort's pause between two moves, to leave the bot room. Sort, Tidy, Clean and Unpack don't wait.");
w.Tooltip("Auto-sort's pause between two moves, to leave the bot room. Sort now, Clean and Empty don't wait.");
w.Checkbox("Sort during fights", "combat", s.SortInCombat, v => { s.SortInCombat = v; _save(); });
w.Tooltip("Off: nothing moves while RynthAi fights. On: moves go between its attacks and casts (never while one is unanswered)");
w.Checkbox("Put items in order inside packs", "order", s.OrderInPacks, v => { s.OrderInPacks = v; _save(); });
w.Tooltip("Like items side by side, A-Z by name, in every pack. Off: items only go to their packs (and stacks are still joined).");
w.Checkbox("Group by kind first", "orderkind", s.OrderKindFirst, v => { s.OrderKindFirst = v; _save(); });
w.Tooltip("Order by kind (Armor, Gem, Spell Component ...) and then A-Z by name, instead of A-Z by name only");
if (!(_c.Abilities.ReadOrder && _c.Abilities.PlaceMoves))
w.TextWrapped("This RynthCore can't read the order inside packs (it needs plugin API 80): items go to their packs but aren't put in order.");
}
if (_c.Log.Count > 0)
@ -91,105 +109,319 @@ internal sealed class SortPanel
}
}
private void DrawRules(UiWindow w, List<SortRule> rules, SortView view)
// ── Pack sections ───────────────────────────────────────────────────────
private void DrawPack(UiWindow w, SortView view, List<SortRule> rules, int number, List<SortRule> packRules, List<string>? conflicts)
{
if (_selected >= rules.Count) _selected = rules.Count - 1;
for (int i = 0; i < rules.Count; i++)
PackLine p = view.Packs[number - 1];
bool full = view.Full.Contains(number);
List<string> warnings = FallbackWarnings(view, number);
if (conflicts != null) warnings.AddRange(conflicts);
bool attention = full || warnings.Count > 0;
if (attention) w.PushStyleColor(UiFormat.ColText, UiColors.Amber);
bool open = w.CollapsingHeader($"Pack {number}: {p.Label}", $"pack.{p.Id:X8}", defaultOpen: true);
if (attention) w.PopStyleColor();
w.Tooltip(PackTooltip(view));
if (!open) return;
w.Indent(RowIndent);
if (full) w.TextColored(UiColors.Amber, "This pack is full: items for it wait where they are");
foreach (string line in warnings) w.TextColored(UiColors.Amber, line);
packRules.Sort(SortRules.CompareForList);
foreach (SortRule r in packRules) DrawRule(w, view, rules, r);
if (packRules.Count == 0) w.TextDisabled("No rules send items here.");
uint id = p.Id;
w.SmallButton("+ Add rule", $"add.{id:X8}", () => AddRule(rules, view, number));
w.Tooltip("A rule sends items to this pack: items of any of its classes, or with any of its names in their name. A name beats a class.");
int on = 0;
foreach (SortRule r in packRules) if (r.On && !r.IsEmpty) on++;
if (on >= 2)
{
SortRule r = rules[i];
int index = i;
w.Checkbox("", "on." + i, r.On, v => { r.On = v; _save(); });
w.Tooltip("Rule on or off");
w.SameLine();
string pack = r.Pack >= 1 && r.Pack <= view.Packs.Count ? $"pack {r.Pack} ({view.Packs[r.Pack - 1].Name})" : $"pack {r.Pack}";
w.Selectable($"{i + 1}. {SortRules.Describe(r)} -> {pack}", "row." + i, _selected == i,
() => _selected = _selected == index ? -1 : index);
w.SmallButton("Merge rules", $"merge.{id:X8}", () => MergeRules(rules, packRules));
w.Tooltip("Make this pack's rules (the ones that are on) one rule with all their classes and names");
}
if (rules.Count == 0) w.TextDisabled("No rules: nothing moves.");
string order = OrderNote(view, p, "");
if (order.Length > 0) w.TextDisabled(order);
w.Unindent(RowIndent);
}
w.Button("Add rule", "rule.add", () =>
private void DrawMissing(UiWindow w, SortView view, List<SortRule> rules, List<SortRule> missing)
{
w.PushStyleColor(UiFormat.ColText, UiColors.Amber);
bool open = w.CollapsingHeader($"Rules for packs you don't have ({missing.Count})", "missing", defaultOpen: true);
w.PopStyleColor();
if (!open) return;
w.Indent(RowIndent);
w.TextWrapped("Their items stay where they are. Pick one of your packs in a rule's editor, or remove the rule.");
var groups = new List<List<SortRule>>();
foreach (SortRule r in missing)
{
if (rules.Count >= SortStore.MaxRules) return;
rules.Add(SortRule.ForClass(ObjectClasses.SpellComponent, 1));
_selected = rules.Count - 1;
_save();
});
if (_selected < 0 || _selected >= rules.Count) return;
List<SortRule>? g = groups.Find(x => SamePackOf(x[0], r));
if (g == null) groups.Add(g = new List<SortRule>());
g.Add(r);
}
foreach (List<SortRule> g in groups)
{
SortRule first = g[0];
w.TextColored(UiColors.Amber, first.PackNote.Length > 0 ? $"A pack you don't have (it was {first.PackNote}):" : $"Pack {first.Pack}, which you don't have:");
g.Sort(SortRules.CompareForList);
foreach (SortRule r in g) DrawRule(w, view, rules, r);
}
w.Unindent(RowIndent);
}
int sel = _selected;
w.SameLine();
w.Button("Up", "rule.up", () =>
{
if (sel <= 0) return;
(rules[sel - 1], rules[sel]) = (rules[sel], rules[sel - 1]);
_selected = sel - 1;
_save();
});
w.SameLine();
w.Button("Down", "rule.down", () =>
{
if (sel >= rules.Count - 1) return;
(rules[sel + 1], rules[sel]) = (rules[sel], rules[sel + 1]);
_selected = sel + 1;
_save();
});
w.SameLine();
w.Button("Remove", "rule.remove", () =>
{
rules.RemoveAt(sel);
_selected = Math.Min(sel, rules.Count - 1);
_save();
});
private static bool SamePackOf(SortRule a, SortRule b) =>
a.PackId != 0 || b.PackId != 0 ? a.PackId == b.PackId : a.Pack == b.Pack;
SortRule rule = rules[sel];
w.SeparatorText($"Rule {sel + 1}");
w.Combo("Match", "rule.kind", rule.Kind == RuleKind.Name ? 1 : 0, Kinds, v =>
// ── Rules ───────────────────────────────────────────────────────────────
private void DrawRule(UiWindow w, SortView view, List<SortRule> rules, SortRule r)
{
string k = "r" + r.Uid;
w.Checkbox("", k + ".on", r.On, v => { r.On = v; _save(); });
w.Tooltip(r.On ? "Rule on: click to turn it off" : "Rule off: click to turn it on");
w.SameLine();
bool selected = ReferenceEquals(_selected, r);
w.Selectable(Shown(SortRules.Describe(r)), k + ".row", selected, () =>
{
rule.Kind = v == 1 ? RuleKind.Name : RuleKind.Class;
_selected = ReferenceEquals(_selected, r) ? null : r;
_nameDraft = string.Empty;
});
w.Tooltip(selected ? "Click to close the editor" : "Click to change this rule");
if (selected) DrawEditor(w, view, rules, r);
}
private void DrawEditor(UiWindow w, SortView view, List<SortRule> rules, SortRule r)
{
string k = "r" + r.Uid;
w.Indent(EditorIndent);
List<int> classes = SortRules.SortedClasses(r);
if (classes.Count > 0)
{
w.TextDisabled("Classes:");
for (int i = 0; i < classes.Count; i++)
{
if (i % ChipsPerLine != 0 || i == 0) w.SameLine();
int cls = classes[i];
string label = ObjectClasses.Label(cls);
w.SmallButton(label + " x", $"{k}.c{cls}", () => { r.RemoveClass(cls); _save(); });
w.Tooltip($"Take {label} out of this rule");
}
}
var offered = new List<int>();
var labels = new List<string> { "Add a class..." };
foreach (int cls in ObjectClasses.Choices)
{
if (r.HasClass(cls)) continue;
offered.Add(cls);
labels.Add(ObjectClasses.Label(cls));
}
if (offered.Count > 0 && r.Classes.Count < SortRule.MaxClasses)
w.Combo("Class", k + ".addclass", 0, labels, v =>
{
if (v >= 1 && v <= offered.Count && r.AddClass(offered[v - 1])) _save();
});
List<string> names = SortRules.SortedNames(r);
if (names.Count > 0)
{
w.TextDisabled("Names:");
for (int i = 0; i < names.Count; i++)
{
if (i % ChipsPerLine != 0 || i == 0) w.SameLine();
string name = names[i];
w.SmallButton($"\"{Shown(name)}\" x", $"{k}.n{i}", () => { r.RemoveName(name); _save(); });
w.Tooltip($"Take \"{name}\" out of this rule");
}
}
if (r.Names.Count < SortRule.MaxNames)
{
w.InputText("Name has", k + ".draft", _nameDraft, SortRule.MaxNameLength, (text, enter) =>
{
_nameDraft = text;
if (enter) AddDraft(r);
}, UiFormat.InputEnterReturnsTrue);
w.Tooltip("Part of an item's name, any case: \"Opal\" takes every item with Opal in its name. Enter or Add puts it in the rule.");
w.SameLine();
w.SmallButton("Add", k + ".addname", () => AddDraft(r));
}
int shown = ShownPack(view, r);
w.Combo("Pack", k + ".pack", Math.Max((shown > 0 ? shown : r.Pack) - 1, 0), PackChoices(view, r.Pack), v =>
{
SetPack(r, view, v + 1);
_save();
});
if (rule.Kind == RuleKind.Name)
w.Tooltip("Where this rule sends items. " + PackTooltip(view));
w.SmallButton("Remove rule", k + ".remove", () =>
{
w.InputText("Name has", "rule.text", rule.Text, 64, v => { rule.Text = v; _save(); });
w.Tooltip("Part of the item's name, any case");
rules.Remove(r);
if (ReferenceEquals(_selected, r)) _selected = null;
_save();
});
w.Unindent(EditorIndent);
}
private void AddDraft(SortRule r)
{
if (r.AddName(_nameDraft)) _save();
_nameDraft = string.Empty;
}
private void AddRule(List<SortRule> rules, SortView view, int number)
{
if (rules.Count >= SortStore.MaxRules) return;
var added = new SortRule();
SetPack(added, view, number);
rules.Add(added);
_selected = added;
_nameDraft = string.Empty;
_save();
}
/// <summary>The pack's rules that are on become one (the first A-Z keeps its place in the list, so a tie still goes its way).</summary>
private void MergeRules(List<SortRule> rules, List<SortRule> packRules)
{
SortRule? keep = null;
foreach (SortRule r in rules)
{
if (!packRules.Contains(r) || !r.On || r.IsEmpty) continue;
if (keep == null) { keep = r; continue; }
keep.TakeEntriesOf(r);
}
if (keep == null) return;
rules.RemoveAll(r => !ReferenceEquals(r, keep) && packRules.Contains(r) && r.On && !r.IsEmpty);
_selected = keep;
_save();
}
/// <summary>Text as a label shows it: "##" would start ImGui's id part.</summary>
private static string Shown(string text) => text.Replace("##", "# #");
// ── Helpers (pure, for the tests) ───────────────────────────────────────
/// <summary>The pack tooltip: how packs are numbered and that a rule keeps its pack.</summary>
internal static string PackTooltip(SortView view) => view.PackOrderKnown ? PackTooltipTopDown : PackTooltipListOrder;
internal const string PackTooltipTopDown =
"Packs are numbered from the top of the pack column (foci don't count). "
+ "A rule remembers the pack you pick, so adding, moving or emptying packs doesn't change where items go.";
internal const string PackTooltipListOrder =
"A rule remembers the pack you pick, so adding, moving or emptying packs doesn't change where items go. "
+ "Pack numbers count your side packs (not foci) in the client's list order, oldest pack first, "
+ "which can differ from the pack column on screen: go by the name and what's in it.";
/// <summary>" - in order", " - 3 to put in order", " - order not known": a pack's order as the window says it (empty when ordering is off).</summary>
internal static string OrderNote(SortView view, PackLine p, string lead)
{
if (!view.Ordering) return string.Empty;
if (!p.OrderKnown) return lead + "order not known yet: not put in order";
if (p.OutOfPlace == 0) return lead + "in order";
return lead + (p.OutOfPlace == 1 ? "1 item to put in order" : $"{p.OutOfPlace} items to put in order");
}
/// <summary>Rules by the side pack they send to now (1-based; 0 = a pack that isn't carried).</summary>
internal static Dictionary<int, List<SortRule>> Group(IReadOnlyList<SortRule> rules, SortView view)
{
var map = new Dictionary<int, List<SortRule>>();
foreach (SortRule r in rules)
{
int n = ShownPack(view, r);
if (!map.TryGetValue(n, out List<SortRule>? list)) map[n] = list = new List<SortRule>();
list.Add(r);
}
return map;
}
/// <summary>
/// Classes and names that two rules (that are on) send to different packs, by the pack whose
/// rule loses: "Armor: also in a rule for pack 2, which wins". A name beats a class, so only
/// rules that match the same way compete; between those the rule saved first wins.
/// </summary>
internal static Dictionary<int, List<string>> Conflicts(IReadOnlyList<SortRule> rules, SortView view)
{
var map = new Dictionary<int, List<string>>();
void Add(int pack, string line)
{
if (!map.TryGetValue(pack, out List<string>? l)) map[pack] = l = new List<string>();
if (!l.Contains(line)) l.Add(line);
}
string Where(int pack) => pack > 0 ? "pack " + pack : "a pack you don't have";
var classWinner = new Dictionary<int, int>();
var nameWinner = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
foreach (SortRule r in rules)
{
if (!r.On) continue;
int pack = ShownPack(view, r);
foreach (int cls in r.Classes)
{
if (!classWinner.TryGetValue(cls, out int won)) classWinner[cls] = pack;
else if (won != pack) Add(pack, $"{ObjectClasses.Label(cls)}: also in a rule for {Where(won)}, which wins");
}
foreach (string n in r.Names)
{
if (!nameWinner.TryGetValue(n, out int won)) nameWinner[n] = pack;
else if (won != pack) Add(pack, $"\"{n}\": also in a rule for {Where(won)}, which wins");
}
}
return map;
}
/// <summary>
/// For side pack <paramref name="number"/>: rules that use it only because their own pack isn't
/// carried (their number names it): "Gem, Key: its pack (Sack - Gems) isn't carried, so this one is used".
/// </summary>
internal static List<string> FallbackWarnings(SortView view, int number)
{
var lines = new List<string>();
foreach (RulePackIssue issue in view.Issues)
{
if (issue.UsedPack != number) continue;
string note = issue.Rule.PackNote;
lines.Add($"{SortRules.Describe(issue.Rule)}: {(note.Length > 0 ? "its pack (" + note + ")" : "its pack")} isn't carried, so this one is used");
}
return lines;
}
/// <summary>Points <paramref name="rule"/> at side pack <paramref name="number"/> (1-based): that pack's id when it is carried.</summary>
internal static void SetPack(SortRule rule, SortView view, int number)
{
rule.Pack = Math.Clamp(number, 1, SortStore.MaxPack);
if (rule.Pack <= view.Packs.Count)
{
PackLine p = view.Packs[rule.Pack - 1];
rule.PackId = p.Id;
rule.PackNote = p.Note;
}
else
{
int ci = ObjectClasses.ChoiceIndex(rule.Class);
var labels = new List<string>(ObjectClasses.ChoiceLabels);
if (ci < 0)
{
// A class the editor doesn't offer (set by hand or by the Lua script): keep it selectable.
labels.Add(ObjectClasses.Label(rule.Class));
ci = labels.Count - 1;
}
int keep = rule.Class;
w.Combo("Class", "rule.class", ci, labels, v =>
{
rule.Class = v < ObjectClasses.Choices.Length ? ObjectClasses.Choices[v] : keep;
_save();
});
rule.PackId = 0;
rule.PackNote = string.Empty;
}
w.Combo("Pack", "rule.pack", Math.Max(rule.Pack - 1, 0), PackChoices(view, rule.Pack), v =>
{
rule.Pack = Math.Clamp(v + 1, 1, SortStore.MaxPack);
_save();
});
w.Tooltip("Pack numbers are your side packs in order, top to bottom");
}
/// <summary>"Pack 1: Name (used/cap)" for each side pack, then "(none)" up to at least 7.</summary>
/// <summary>The side pack the rule uses now (1-based), as the planner resolves it, or 0.</summary>
internal static int ShownPack(SortView view, SortRule r)
{
if (r.PackId != 0)
for (int i = 0; i < view.Packs.Count; i++)
if (view.Packs[i].Id == r.PackId) return i + 1;
return r.Pack >= 1 && r.Pack <= view.Packs.Count ? r.Pack : 0;
}
/// <summary>"Pack 1: Sack (12/24) - Salvage, Gems" for each side pack, then "(none)" up to at least 7.</summary>
internal static List<string> PackChoices(SortView view, int atLeast)
{
int n = Math.Min(Math.Max(Math.Max(view.Packs.Count, 7), atLeast), SortStore.MaxPack);
var list = new List<string>(n);
for (int i = 1; i <= n; i++)
{
if (i <= view.Packs.Count)
{
PackLine p = view.Packs[i - 1];
list.Add($"Pack {i}: {p.Name} ({p.Used}/{p.Capacity})");
}
if (i <= view.Packs.Count) list.Add($"Pack {i}: {view.Packs[i - 1].Label}");
else list.Add($"Pack {i} (none)");
}
return list;

View file

@ -579,6 +579,10 @@ internal static class ActionPacer
/// </summary>
public static bool CastSpellFor(this RynthCoreHost host, uint targetId, int spellId, string who, string label, bool asked = false)
{
// No cast goes out with a held stop still waiting (2026-10-12): the stop is sent first. The
// engine runs a stop queued before a cast ahead of it, and sends its own pre-cast stop a
// server answer ahead of the cast, so the stop never rides in the cast's frame.
MoveAudit.FlushPendingStops(host, "before a cast", force: true);
int seq = UseDoneSeqNow(host);
bool ok = host.CastSpell(targetId, spellId);
if (ok) Begin(host, PacedKind.Cast, unchecked((uint)spellId), label, who, seq);

View file

@ -51,26 +51,28 @@ internal static class MoveAudit
public static bool SetAutoRunBy(this RynthCoreHost host, string who, bool on)
{
if (on && HeldForUse(host, who, "SetAutoRun(True)")) return false;
if (HeldForAction(host, who, on ? "SetAutoRun(True)" : "SetAutoRun(False)", isStop: !on)) return false;
if (HeldForAction(host, who, on ? "SetAutoRun(True)" : "SetAutoRun(False)", isStop: !on, deferAs: on ? null : PendingStop.AutoRunOff())) return false;
if (on) FlushPendingStops(host, "before a start");
Note(host, who, "SetAutoRun", on ? "True" : "False", collapseByKindOnly: false);
lock (Gate) { _autoRunOn = on; if (on) _lastStartMs = NowMs(); }
lock (Gate) { _autoRunOn = on; if (on) _lastStartMs = NowMs(); else _pendingAutoRunOff = null; }
return host.SetAutoRun(on);
}
public static bool StopCompletelyBy(this RynthCoreHost host, string who)
{
if (HeldForAction(host, who, "StopCompletely()", isStop: true)) return false;
if (HeldForAction(host, who, "StopCompletely()", isStop: true, deferAs: PendingStop.Complete())) return false;
Note(host, who, "StopCompletely", "", collapseByKindOnly: false);
lock (Gate) { _autoRunOn = false; _motionsOn.Clear(); }
lock (Gate) { _autoRunOn = false; _motionsOn.Clear(); ClearPendingLocked(); } // clears everything AC has on
return host.StopCompletely();
}
public static bool SetMotionBy(this RynthCoreHost host, string who, uint motion, bool on)
{
if (on && HeldForUse(host, who, $"SetMotion(0x{motion:X8}, True)")) return false;
if (HeldForAction(host, who, $"SetMotion(0x{motion:X8}, {(on ? "True" : "False")})", isStop: !on, motion)) return false;
if (HeldForAction(host, who, $"SetMotion(0x{motion:X8}, {(on ? "True" : "False")})", isStop: !on, motion, on ? null : PendingStop.MotionOff(motion))) return false;
if (on) FlushPendingStops(host, "before a start");
Note(host, who, "SetMotion", $"0x{motion:X8}, {(on ? "True" : "False")}", collapseByKindOnly: false);
lock (Gate) { if (on) { _motionsOn.Add(motion); _lastStartMs = NowMs(); } else _motionsOn.Remove(motion); }
lock (Gate) { if (on) { _motionsOn.Add(motion); _lastStartMs = NowMs(); } else { _motionsOn.Remove(motion); _pendingMotionOff.Remove(motion); } }
return host.SetMotion(motion, on);
}
@ -78,6 +80,7 @@ internal static class MoveAudit
{
if (HeldForUse(host, who, $"DoMovement(0x{motion:X8})")) return false;
if (HeldForAction(host, who, $"DoMovement(0x{motion:X8})", isStop: false)) return false;
FlushPendingStops(host, "before a start");
Note(host, who, "DoMovement", $"0x{motion:X8}, {speed:0.##}, {holdKey}", collapseByKindOnly: false);
lock (Gate) { _motionsOn.Add(motion); _lastStartMs = NowMs(); }
return host.DoMovement(motion, speed, holdKey);
@ -89,9 +92,16 @@ internal static class MoveAudit
// or a stop cancels the walk/turn to a used object, and a cast's end waits for its gesture.
// While ActionPacer has one outstanding:
// * starting to move or turning is held (returns false, one log line per action and caller);
// * a stop goes through only when RynthAi itself has the character moving (autorun, or the
// motion it turned on); a stop with nothing of ours moving would only send a redundant
// movement packet in the middle of the action, so it is held as well;
// * a stop goes through at once when RynthAi itself turned that movement on (autorun, or the
// motion it turned on) and has not turned it off since - however long ago (2026-10-12: the
// 3 s "fresh" window used to apply to stops too, so a nav stop more than 3 s after the
// last autorun-on that got through was taken as redundant while AC's autorun was still on);
// * any other stop waits, but is never dropped (2026-10-12): it is kept as a pending stop and
// sent as soon as nothing is outstanding (FlushPendingStops, every RynthAi tick, before the
// next start, and always before the next cast - CastSpellFor). RynthAi can't see AC's own
// motion state, and a stop left out leaves AC's autorun/motion on for the cast's
// FreeHandsAndCastSpell -> MaybeStopCompletely to flush in the cast's frame: the stray
// stop burst that came before every run of casts that never landed (flight 63260);
// * the deliberate kick for a held cast (Buff/Nudge), a macro stop and typed commands pass.
// Off unless ActionPacer.Enabled (RynthAi only).
@ -115,20 +125,25 @@ internal static class MoveAudit
get { lock (Gate) return (_autoRunOn || _motionsOn.Count > 0) && NowMs() - _lastStartMs < OwnMovementFreshMs; }
}
/// <summary>True when the call must wait for an unanswered paced action (internal for the tests).</summary>
internal static bool HeldForAction(RynthCoreHost host, string who, string call, bool isStop, uint motion = 0)
/// <summary>
/// True when the call must wait for an unanswered paced action (internal for the tests). A stop
/// that waits is kept as <paramref name="deferAs"/> and sent later (FlushPendingStops): a stop is
/// never dropped.
/// </summary>
internal static bool HeldForAction(RynthCoreHost host, string who, string call, bool isStop, uint motion = 0, PendingStop? deferAs = null)
{
if (!ActionPacer.Enabled || IsExemptFromActionHold(who)) return false;
if (isStop)
{
bool moving;
lock (Gate) moving = (motion != 0 ? _motionsOn.Contains(motion) : (_autoRunOn || _motionsOn.Count > 0))
&& NowMs() - _lastStartMs < OwnMovementFreshMs;
if (moving) return false; // a real stop always goes through
lock (Gate) moving = motion != 0 ? _motionsOn.Contains(motion) : (_autoRunOn || _motionsOn.Count > 0);
if (moving) return false; // a real stop always goes through, however old the start
}
var pending = ActionPacer.Current(host);
if (pending == null) return false;
if (!ActionPacer.HoldsMovement(host, out string what)) return false;
if (isStop && deferAs != null)
lock (Gate) AddPendingLocked(deferAs, who);
bool log;
lock (Gate)
{
@ -137,13 +152,152 @@ internal static class MoveAudit
}
if (log)
{
string kind = isStop ? "redundant stop, nothing of ours is moving" : "move/turn";
try { host.Log($"[Move] {PluginName}/{who} {call} held ({kind}): the server is still answering {what}"); }
string line = isStop
? $"[Move] {PluginName}/{who} {call} waits (nothing of ours is moving; sent once the server has answered, before any cast): the server is still answering {what}"
: $"[Move] {PluginName}/{who} {call} held (move/turn): the server is still answering {what}";
try { host.Log(line); }
catch { }
}
return true;
}
// ── Pending stops (2026-10-12) ──────────────────────────────────────────────
// A stop held by HeldForAction waits here until FlushPendingStops sends it. A StopCompletely
// covers everything else; an autorun-off and each motion-off are kept once (the last caller
// wins). A stop that goes through for real clears what it covers; a start that goes through
// sends the pending stops first, so the order the bot asked for is kept.
internal enum PendingStopKind { AutoRunOff, MotionOff, StopMovement, Complete }
/// <summary>One stop waiting to be sent.</summary>
internal sealed class PendingStop
{
public PendingStopKind Kind;
public uint Motion;
public int HoldKey;
public static PendingStop AutoRunOff() => new() { Kind = PendingStopKind.AutoRunOff };
public static PendingStop MotionOff(uint motion) => new() { Kind = PendingStopKind.MotionOff, Motion = motion };
public static PendingStop StopMovement(uint motion, int holdKey) => new() { Kind = PendingStopKind.StopMovement, Motion = motion, HoldKey = holdKey };
public static PendingStop Complete() => new() { Kind = PendingStopKind.Complete };
}
private static string? _pendingComplete; // who
private static string? _pendingAutoRunOff; // who
private static readonly System.Collections.Generic.Dictionary<uint, string> _pendingMotionOff = new();
private static readonly System.Collections.Generic.Dictionary<uint, (int holdKey, string who)> _pendingStopMovement = new();
private static long _pendingSinceMs;
private static long _deferredStopsSent;
/// <summary>Held stops sent later by FlushPendingStops (status, tests).</summary>
internal static long DeferredStopsSent { get { lock (Gate) return _deferredStopsSent; } }
/// <summary>True while a held stop is waiting to be sent.</summary>
internal static bool HasPendingStop
{
get { lock (Gate) return HasPendingLocked(); }
}
private static bool HasPendingLocked() =>
_pendingComplete != null || _pendingAutoRunOff != null || _pendingMotionOff.Count > 0 || _pendingStopMovement.Count > 0;
private static void AddPendingLocked(PendingStop stop, string who)
{
if (!HasPendingLocked()) _pendingSinceMs = NowMs();
switch (stop.Kind)
{
case PendingStopKind.Complete: _pendingComplete = who; break;
case PendingStopKind.AutoRunOff: _pendingAutoRunOff = who; break;
case PendingStopKind.MotionOff: _pendingMotionOff[stop.Motion] = who; break;
case PendingStopKind.StopMovement: _pendingStopMovement[stop.Motion] = (stop.HoldKey, who); break;
}
}
private static void ClearPendingLocked()
{
_pendingComplete = null;
_pendingAutoRunOff = null;
_pendingMotionOff.Clear();
_pendingStopMovement.Clear();
}
/// <summary>
/// Sends the held stops once nothing is outstanding (or at once with <paramref name="force"/>:
/// a cast is about to go out, and no cast goes out with a stop still held). RynthAi calls it
/// every tick; the starts and CastSpellFor call it first. Returns true when something was sent.
/// </summary>
internal static bool FlushPendingStops(RynthCoreHost host, string why, bool force = false)
{
lock (Gate) { if (!HasPendingLocked()) return false; }
if (!force && ActionPacer.Current(host) != null) return false;
string? complete, autoRunOff;
System.Collections.Generic.KeyValuePair<uint, string>[] motionOff;
System.Collections.Generic.KeyValuePair<uint, (int holdKey, string who)>[] stopMovement;
long waited;
lock (Gate)
{
if (!HasPendingLocked()) return false;
complete = _pendingComplete;
autoRunOff = _pendingAutoRunOff;
motionOff = new System.Collections.Generic.KeyValuePair<uint, string>[_pendingMotionOff.Count];
((System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<uint, string>>)_pendingMotionOff).CopyTo(motionOff, 0);
stopMovement = new System.Collections.Generic.KeyValuePair<uint, (int, string)>[_pendingStopMovement.Count];
((System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<uint, (int, string)>>)_pendingStopMovement).CopyTo(stopMovement, 0);
waited = NowMs() - _pendingSinceMs;
ClearPendingLocked();
}
var sent = new System.Collections.Generic.List<string>();
try
{
if (complete != null)
{
// StopCompletely clears autorun and every motion in AC: nothing else is needed.
if (host.HasStopCompletely)
{
host.StopCompletely();
lock (Gate) { _autoRunOn = false; _motionsOn.Clear(); _deferredStopsSent++; }
sent.Add($"StopCompletely() for {complete}");
}
else
{
autoRunOff ??= complete; // no StopCompletely on this engine: at least autorun off
}
}
if (complete == null || !host.HasStopCompletely)
{
if (autoRunOff != null)
{
host.SetAutoRun(false);
lock (Gate) { _autoRunOn = false; _deferredStopsSent++; }
sent.Add($"SetAutoRun(False) for {autoRunOff}");
}
foreach (var m in motionOff)
{
if (!host.HasSetMotion) break;
host.SetMotion(m.Key, false);
lock (Gate) { _motionsOn.Remove(m.Key); _deferredStopsSent++; }
sent.Add($"SetMotion(0x{m.Key:X8}, False) for {m.Value}");
}
foreach (var s in stopMovement)
{
if (!host.HasStopMovement) break;
host.StopMovement(s.Key, s.Value.holdKey);
lock (Gate) { _motionsOn.Remove(s.Key); _deferredStopsSent++; }
sent.Add($"StopMovement(0x{s.Key:X8}) for {s.Value.who}");
}
}
}
catch { }
if (sent.Count > 0 && Enabled)
{
try { host.Log($"[Move] {PluginName} held stop(s) sent {why} after {waited} ms: {string.Join(", ", sent)}"); }
catch { }
}
return sent.Count > 0;
}
// ── Hold while a door/corpse use is in flight (2026-10-06) ─────────────────────
// A move or a turn sent while the server is still walking/turning the character to a used
// door or corpse cancels that use (ACE stops its move-to chain on a client MoveToState).
@ -175,9 +329,9 @@ internal static class MoveAudit
public static bool StopMovementBy(this RynthCoreHost host, string who, uint motion, int holdKey)
{
if (HeldForAction(host, who, $"StopMovement(0x{motion:X8})", isStop: true, motion)) return false;
if (HeldForAction(host, who, $"StopMovement(0x{motion:X8})", isStop: true, motion, PendingStop.StopMovement(motion, holdKey))) return false;
Note(host, who, "StopMovement", $"0x{motion:X8}, {holdKey}", collapseByKindOnly: false);
lock (Gate) _motionsOn.Remove(motion);
lock (Gate) { _motionsOn.Remove(motion); _pendingStopMovement.Remove(motion); }
return host.StopMovement(motion, holdKey);
}
@ -243,6 +397,9 @@ internal static class MoveAudit
_lastStartMs = long.MinValue / 2;
_actionHoldLogged.Clear();
_actionHoldLoggedFor = long.MinValue;
ClearPendingLocked();
_pendingSinceMs = 0;
_deferredStopsSent = 0;
}
}
}