feat: SK backlog from test through 2026.11.22.48 (Trade Shop, Oracle, quests, loot, nav)

Squash of test/main-merge-2026-10-25 onto aelrynth main 2026.11.19.1 for the standing sk PR. Includes Trade Shop, Oracle wiki/ILT tracker, quest runs, loot checklist, RynthNav, VTank import. HandWrittenVersion remains 0.5.0-legacy-ui. See Changelog/2026-11-22-sk-backlog-test-merge.md.
This commit is contained in:
BlankenshipG 2026-11-23 00:08:38 -05:00
commit dc08e1abba
521 changed files with 47247 additions and 795 deletions

View file

@ -175,9 +175,25 @@ public class WorldObject
if (o != null)
{
if (o.Doubles.TryGetValue((uint)key, out double v)) return v;
if (!o.LiveFallback) return defaultValue;
if (!o.LiveFallback) return SlayerBonusOr(key, defaultValue);
}
return Cache?.GetDoubleProperty(Id, (uint)key, defaultValue) ?? defaultValue;
double live = Cache?.GetDoubleProperty(Id, (uint)key, defaultValue) ?? defaultValue;
return live == 0 || live == defaultValue ? SlayerBonusOr(key, live) : live;
}
/// <summary>
/// SlayerDamageBonus (float 138) from the weapon's text when the appraisal has none: ACECustom never sends it, only
/// "- Shadow Slayer: 1.5x Damage" (2026-11-15; RynthCore.Loot.SlayerText). Any other key: <paramref name="fallback"/>.
/// </summary>
private double SlayerBonusOr(DoubleValueKey key, double fallback)
{
if ((int)key != RynthCore.Loot.SlayerText.SlayerDamageBonusKey) return fallback;
try
{
double x = RynthCore.Loot.SlayerText.BonusOf(Values(StringValueKey.LongDesc, string.Empty), Values(StringValueKey.Use, string.Empty));
return x > 0 ? x : fallback;
}
catch { return fallback; }
}
}

View file

@ -68,18 +68,29 @@ public partial class BuffManager
/// <summary>Uses <paramref name="profile"/>'s enabled entries as the buff list (tests call this directly).</summary>
internal void ApplyBuffProfile(BuffProfile profile)
{
SpellCatalog.EnsureLoaded(m => _host.Log(m));
_profileByKey.Clear();
var keys = new List<string>(profile.Entries.Count);
var instant = new List<string>();
foreach (var e in profile.Entries)
{
if (!e.Enabled || string.IsNullOrWhiteSpace(e.Key)) continue;
// One cast per base name: two tiers of the same line would fight over one family.
if (_profileByKey.ContainsKey(e.Key)) continue;
// A spell with no duration (Mana Boost restores mana at once) never stays on, so as a buff
// it would be cast again on every pass.
if (SpellCatalog.Get(e.SpellId) is { DurationSec: < 0 })
{
instant.Add(e.Name);
continue;
}
_profileByKey[e.Key] = e;
keys.Add(e.Key);
}
_profileKeys = keys;
ActiveBuffProfileName = profile.Name;
if (instant.Count > 0)
_host.Log($"[RynthAi] Buff profile '{profile.Name}': left out {string.Join(", ", instant)} (no duration: not a buff, it would be recast every pass).");
}
private void ClearBuffProfile(string chatLine)
@ -118,12 +129,14 @@ public partial class BuffManager
SpellCatalogEntry? best = null;
foreach (var c in SpellCatalog.Family(entry.FamilyId))
{
if (!c.IsBuff || c.Level > maxTier || !_spellManager.IsKnownSpellId(c.Id)) continue;
// Fellowship versions are Use Fellowship Buffs' to pick (FellowshipVersion), not the profile's.
if (!c.IsBuff || c.Level > maxTier || !_spellManager.IsKnownSpellId(c.Id) || IsFellowshipSpell(c)) continue;
if (LevelUnusable(c.Id)) continue; // refused by the server for components: a lower level
if (best == null || Rank(c) > Rank(best)) best = c;
}
if (best != null) return best.Id;
// Family unknown to the catalog: the exact spell picked in the Spells window.
return entry.SpellId != 0 && _spellManager.IsKnownSpellId(entry.SpellId) ? entry.SpellId : 0;
return entry.SpellId != 0 && _spellManager.IsKnownSpellId(entry.SpellId) && !LevelUnusable(entry.SpellId) ? entry.SpellId : 0;
static long Rank(SpellCatalogEntry c) =>
(long)c.Level * 1_000_000 + (c.IsSelf || c.IsItemTarget ? 100_000 : 0) + c.Power;

View file

@ -184,13 +184,11 @@ public partial class BuffManager : IDisposable
private const double BuffFailCooldownSec = 120.0;
// A vital spell LEVEL the server refused for missing components (Revitalize, Heal, Stamina
// to Mana...): that level is passed over for NoComponentsLevelSec and the next lower level
// with components is cast instead. It used to park the whole family, then retry the same
// top level the character had no components for (2026-10-08).
private readonly Dictionary<int, DateTime> _noComponentsUntil = new();
private const double NoComponentsLevelSec = 600.0;
private bool LevelLacksComponents(int spellId)
=> _noComponentsUntil.TryGetValue(spellId, out DateTime until) && RynthClock.Now < until;
// to Mana...): that level is passed over for SpellManager.NoComponentsSec and the next lower
// level with components is cast instead. It used to park the whole family, then retry the
// same top level the character had no components for (2026-10-08). The memory is
// SpellManager's since 2026-10-18, shared with combat's spell choice.
private bool LevelLacksComponents(int spellId) => _spellManager.LacksComponents(spellId);
// Per-family SILENT no-show counter. Distinct from _buffFailCooldownUntil
// (which catches chat-explicit hard rejects). This catches the /god case:
@ -2463,6 +2461,31 @@ public partial class BuffManager : IDisposable
private bool VitalNo(string why) { _vitalWhy = why; return false; }
// The last time a refused vital use was logged (one line per RefusedUseLogMs, not per tick).
private DateTime _lastRefusedUseLog = DateTime.MinValue;
private const double RefusedUseLogMs = 5000;
/// <summary>Vital item uses the engine refused to send (tests, status).</summary>
internal int VitalUsesRefused { get; private set; }
/// <summary>
/// The engine didn't send a kit or potion use: it refuses new game actions while it holds
/// them, for 5 s after a portal, a teleport or a respawn (WorldTransitionState), and when its
/// action queue is full. Nothing is marked as used, so the vitals keep trying on the next ticks
/// (and the other heals keep their turn) instead of waiting up to 8 s for a kit result that
/// can't come: Silentkelpie respawned into a fight, his kit 3.5 s after the portal was refused,
/// and he died 3.4 s later with every heal still waiting for it (2026-10-19 18:21).
/// </summary>
private bool VitalUseRefused(string what)
{
VitalUsesRefused++;
if ((RynthClock.Now - _lastRefusedUseLog).TotalMilliseconds >= RefusedUseLogMs)
{
_lastRefusedUseLog = RynthClock.Now;
_host.Log($"[RynthAi] Vitals: the engine didn't send {what} (it holds game actions for 5 s after a portal, teleport or respawn): trying again next tick.");
}
return VitalNo($"the engine didn't send {what}");
}
// The pending cast is a vital one when _pendingSpellId equals this (set by AttemptVitalCast).
private int _pendingVitalSpellId;
private DateTime _lastManaFloorLogAt = DateTime.MinValue;
@ -2665,7 +2688,8 @@ public partial class BuffManager : IDisposable
if (Array.FindIndex(types, t => t.Equals(DrinkType(rule, potion), StringComparison.OrdinalIgnoreCase)) < 0) continue;
if (HeldCastBlocksItemUse(out string heldWhy)) return VitalNo(heldWhy);
_host.Log($"[RynthAi] Vitals: drinking {rule.Name} ({rule.Type})" + (potion.Id != rule.Id ? " from a new stack." : "."));
_host.UseFor(unchecked((uint)potion.Id), "Buff", $"vitals: drink {rule.Name} ({rule.Type}) from the Items list");
if (!_host.UseFor(unchecked((uint)potion.Id), "Buff", $"vitals: drink {rule.Name} ({rule.Type}) from the Items list"))
return VitalUseRefused(rule.Name);
_lastPotionAt = RynthClock.Now;
_vitalActionsSent++;
_lastCastAttempt = RynthClock.Now;
@ -2682,7 +2706,8 @@ public partial class BuffManager : IDisposable
if (IsKitName(wo.Name)) continue;
if (HeldCastBlocksItemUse(out string heldWhy)) return VitalNo(heldWhy);
_host.Log($"[RynthAi] Vitals: using {wo.Name} from the pack ({kind}).");
_host.UseFor(unchecked((uint)wo.Id), "Buff", $"vitals: {kind} potion from the pack");
if (!_host.UseFor(unchecked((uint)wo.Id), "Buff", $"vitals: {kind} potion from the pack"))
return VitalUseRefused(wo.Name ?? kind + " potion");
_lastPotionAt = RynthClock.Now;
_vitalActionsSent++;
_lastCastAttempt = RynthClock.Now;
@ -2792,7 +2817,8 @@ public partial class BuffManager : IDisposable
if (playerId == 0) return false;
if (HeldCastBlocksItemUse(out string heldWhy)) return VitalNo(heldWhy);
if (fromPack) _host.Log($"[RynthAi] Vitals: using {kit.Name} from the pack.");
_host.UseOnFor(unchecked((uint)kit.Id), playerId, "Buff", "vitals: healing kit on yourself");
if (!_host.UseOnFor(unchecked((uint)kit.Id), playerId, "Buff", "vitals: healing kit on yourself"))
return VitalUseRefused(kit.Name ?? "the healing kit");
_lastCastAttempt = RynthClock.Now;
MarkKitUsed();
NoteKitInFlight(kit);
@ -2837,7 +2863,8 @@ public partial class BuffManager : IDisposable
if (playerId == 0) return false;
if (HeldCastBlocksItemUse(out _)) return false;
_host.Log($"[RynthAi] Vitals: using {kit.Name} from the pack.");
_host.UseOnFor(unchecked((uint)kit.Id), playerId, "Buff", "vitals: stamina kit on yourself");
if (!_host.UseOnFor(unchecked((uint)kit.Id), playerId, "Buff", "vitals: stamina kit on yourself"))
return VitalUseRefused(kit.Name ?? "the stamina kit");
_vitalActionsSent++;
_lastCastAttempt = RynthClock.Now;
MarkKitUsed(stamina: true);
@ -3340,12 +3367,106 @@ public partial class BuffManager : IDisposable
/// <summary>Casts that replaced an active buff of the same family at a lower level (tests, status).</summary>
internal int BuffUpgrades { get; private set; }
/// <summary>
/// The spell a buff casts now: the highest level the skill allows (the Buffing tier lines) that
/// the character knows and can cast, else the next lower one; 0 when no level is castable. A
/// level the server refused for components is passed over (<see cref="LevelUnusable"/>), so the
/// buff drops to the next lower level. With Use Fellowship Buffs on and in a fellowship,
/// the buff's fellowship version replaces it (<see cref="FellowshipVersion"/>).
/// </summary>
internal int FindBestSpellId(string baseName, AcSkillType skill)
{
int id = _spellManager.GetDynamicSelfBuffId(baseName, skill);
return id != 0 ? id : ResolveProfileFallback(baseName, skill);
int id = _spellManager.GetDynamicSelfBuffId(baseName, skill, LevelUnusable);
if (id == 0) id = ResolveProfileFallback(baseName, skill);
if (id == 0 || !IsLastingBuff(id)) return 0;
return FellowshipVersion(id, skill);
}
/// <summary>
/// Buffing casts only buffs that stay on (owner, 2026-10-19): never a heal for health, stamina
/// or mana (Heal Self, Revitalize, Mana Boost, Stamina to Mana: the vitals do those, at Heal At
/// and the like) and never a dispel. Those have no duration (the spell catalog's -1), and
/// dispels are refused by family too. A spell the catalog doesn't know is judged by name only.
/// </summary>
internal static bool IsLastingBuff(int spellId)
{
SpellCatalog.EnsureLoaded();
SpellCatalogEntry? c = SpellCatalog.Get(spellId);
if (c != null)
return c.DurationSec > 0 && !c.FamilyName.Contains("Dispel", StringComparison.OrdinalIgnoreCase);
string name = SpellTableStub.GetById(spellId)?.Name ?? "";
return !IsVitalOrDispelName(name);
}
// The instant spell families by name: dispels (Evaporate / Extinguish / ... All Magic), the
// vital heals and the transfers (Stamina to Mana, Mana to Health, ...).
private static bool IsVitalOrDispelName(string name) =>
name.Contains("All Magic", StringComparison.OrdinalIgnoreCase)
|| name.Contains("Dispel", StringComparison.OrdinalIgnoreCase)
|| name.Contains("Heal Self", StringComparison.OrdinalIgnoreCase)
|| name.Contains("Revitalize", StringComparison.OrdinalIgnoreCase)
|| name.Contains("Mana Boost", StringComparison.OrdinalIgnoreCase)
|| System.Text.RegularExpressions.Regex.IsMatch(name, @"\b(Health|Stamina|Mana) to (Health|Stamina|Mana)\b",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
/// <summary>True while the character is in a fellowship (set by the plugin; null = never).</summary>
internal Func<bool>? InFellowship { get; set; }
// The fellowship answer, kept a second: the picker asks per buff per tick, and the tracker
// reads client memory.
private bool _inFellowshipCached;
private long _inFellowshipAt = long.MinValue / 2;
private bool InFellowshipNow()
{
long now = Environment.TickCount64;
if (now - _inFellowshipAt >= 1000)
{
_inFellowshipAt = now;
try { _inFellowshipCached = InFellowship?.Invoke() == true; }
catch { _inFellowshipCached = false; }
}
return _inFellowshipCached;
}
/// <summary>
/// A level the buff picker passes over: the server refused it for components ("You don't have
/// all the components for this spell."), for SpellManager.NoComponentsSec or until more scarabs
/// or tapers are picked up. It goes on the server's answer, not a prediction: portal.dat's
/// scarab names don't match ACE's inventory names, and the same check in combat rejected every
/// level of spells the character had the scarab for (CombatManager.EnablePredictiveComponentGate).
/// </summary>
private bool LevelUnusable(int spellId) => LevelLacksComponents(spellId);
/// <summary>
/// With Use Fellowship Buffs on and in a fellowship: the fellowship version of
/// <paramref name="selfId"/>'s family (Empowering the Conclave for Strength, the Wards for the
/// protections, ...), at the highest level the skill allows that the character knows and can
/// cast, and never a lower level than <paramref name="selfId"/> (it would weaken your own buff).
/// Same family, so it replaces the self buff rather than stacking. Otherwise <paramref name="selfId"/>.
/// </summary>
private int FellowshipVersion(int selfId, AcSkillType skill)
{
if (!_settings.UseFellowshipBuffs || !_spellManager.IsKnownSnapshotWarm || !InFellowshipNow()) return selfId;
SpellCatalog.EnsureLoaded(m => _host.Log(m)); // the built-in list never loads it otherwise
SpellCatalogEntry? self = SpellCatalog.Get(selfId);
if (self == null || self.IsItemTarget) return selfId;
int maxTier = _spellManager.GetHighestBuffSpellTier(skill);
SpellCatalogEntry? best = null;
foreach (SpellCatalogEntry c in SpellCatalog.Family(self.FamilyId))
{
if (!IsFellowshipSpell(c) || !c.IsBuff || c.DurationSec <= 0 || c.Level > maxTier || c.Level < self.Level) continue;
if (!_spellManager.IsKnownSpellId(c.Id) || LevelUnusable(c.Id)) continue;
if (best == null || c.Level > best.Level || (c.Level == best.Level && c.Power > best.Power)) best = c;
}
return best?.Id ?? selfId;
}
/// <summary>A spell cast on the whole fellowship ("... all Fellowship members ..." in ACE's catalog).</summary>
internal static bool IsFellowshipSpell(SpellCatalogEntry c) =>
c.Target.Equals("Fellowship", StringComparison.OrdinalIgnoreCase)
|| c.Description.Contains("fellowship member", StringComparison.OrdinalIgnoreCase);
// True for enchantments that live on an ITEM (armor or weapon), NOT on the
// player. These do NOT appear in ReadPlayerEnchantments, so they must be
// confirmed via chat, stored in _itemSpellTimers, and PRESERVED across a
@ -4825,22 +4946,50 @@ public partial class BuffManager : IDisposable
lower.Contains("you must specify") ||
lower.Contains("have all the components for this spell"))
{
// The refusal names no spell: it answers the LAST cast sent. With a combat cast sent
// after this one (an attack spell while a heal was pending), it is that cast's
// (CombatManager takes it) and this one is still in flight. Blaming the pending heal
// parked Sk's only castable Heal Self I for a Flame Arc II refusal (2026-10-18).
int lastSent = ActionPacer.LastCastSpellId;
if (_pendingSpellId != 0 && lastSent != 0 && lastSent != _pendingSpellId)
{
_host.Log($"[BuffChat] refusal is for the last cast sent ({SpellTableStub.GetById(lastSent)?.Name ?? lastSent.ToString()}), " +
$"not pending {SpellTableStub.GetById(_pendingSpellId)?.Name ?? _pendingSpellId.ToString()}: pending kept.");
return;
}
_cast.Result(null, "refused by the server", atStart: true);
if (_pendingSpellId != 0)
{
var pendingSpell = SpellTableStub.GetById(_pendingSpellId);
bool noCompsVital = _pendingSpellId == _pendingVitalSpellId
&& (lower.Contains("components") || lower.Contains("missing some required"));
bool noComps = lower.Contains("components") || lower.Contains("missing some required");
bool noCompsVital = _pendingSpellId == _pendingVitalSpellId && noComps;
// Every spell refused for components is remembered (combat skips it too).
if (noComps) _spellManager.MarkNoComponents(_pendingSpellId);
if (noComps && pendingSpell != null)
Huds.CastWarningHud.Post(pendingSpell.Name, noCompsVital
? $"RynthAi casts a lower level of it instead, or a kit or potion ({SpellManager.NoComponentsSec / 60:0} min)."
: $"RynthAi buffs with a lower level of it instead ({SpellManager.NoComponentsSec / 60:0} min).");
if (pendingSpell != null && noCompsVital)
{
// A vital spell: pass over this level only; the next lower one goes next.
_noComponentsUntil[_pendingSpellId] = RynthClock.Now.AddSeconds(NoComponentsLevelSec);
_host.WriteToChat($"[RynthAi] No components for {pendingSpell.Name}: using a lower level for {NoComponentsLevelSec / 60:0} min.", 2);
_host.WriteToChat($"[RynthAi] No components for {pendingSpell.Name}: using a lower level for {SpellManager.NoComponentsSec / 60:0} min.", 2);
}
else if (pendingSpell != null && noComps && !PendingIsShield)
{
// A buff: the same. The picker (FindBestSpellId) passes over a level marked
// above, so the next lower level of this buff goes next; with none left the buff
// is left out. Parking the whole family here skipped the buff for the cooldown
// although a lower level was castable.
if (IsItemEnchantment(pendingSpell.Name))
{
_itemSpellTimers.Remove(pendingSpell.Family);
SaveBuffTimers();
}
_host.WriteToChat($"[RynthAi] No components for {pendingSpell.Name}: buffing with a lower level for {SpellManager.NoComponentsSec / 60:0} min.", 2);
}
else if (pendingSpell != null && PendingIsShield)
{
// Aimed at the shield: the family rests on the shield only; the armor's is on.
bool noComps = lower.Contains("components") || lower.Contains("missing some required");
ShieldCastRefused(pendingSpell, "hard rejection", BuffFailCooldownSec);
_host.WriteToChat($"[RynthAi] Skipping {pendingSpell.Name} on the shield for {BuffFailCooldownSec / 60:0} min " +
$"({(noComps ? "no components for it" : "the server refused it")}).", 2);
@ -4858,9 +5007,7 @@ public partial class BuffManager : IDisposable
// "Casting:" line, so say which one. The server's text is not
// echoed: this line comes back through this handler, and it must
// not match the refusal phrases above.
bool noComps = lower.Contains("components") || lower.Contains("missing some required");
_host.WriteToChat($"[RynthAi] Skipping {pendingSpell.Name} for {BuffFailCooldownSec / 60:0} min " +
$"({(noComps ? "no components for it" : "the server refused it")}).", 2);
_host.WriteToChat($"[RynthAi] Skipping {pendingSpell.Name} for {BuffFailCooldownSec / 60:0} min (the server refused it).", 2);
}
_host.Log($"[BuffChat] CLEARED+COOLED pending={_pendingSpellId} ({BuffFailCooldownSec:0}s) — hard rejection in '{text}'");
}

View file

@ -65,6 +65,27 @@ public partial class CombatManager
/// </summary>
internal double AmmoOffSettleMs { get; set; } = 400;
/// <summary>
/// ACECustom's Universal Quiver charm (WCID 78780032, 2026-11-11): while it is active (the player's PropertyBool
/// HasUniversalQuiverCharm) and the ammunition slot is EMPTY, the server fires the matching Infinite Deadly Prismatic
/// projectile for any bow, crossbow or atlatl. Ammo that is equipped is used first.
/// </summary>
internal const uint BoolHasUniversalQuiverCharm = 50061;
/// <summary>Tests: the charm's state (default: the player's PropertyBool).</summary>
internal Func<bool>? UniversalQuiverOverride { get; set; }
/// <summary>The Universal Quiver charm is on: an empty ammunition slot shoots (prismatic, so the target's best element).</summary>
public bool UniversalQuiverActive
{
get
{
if (UniversalQuiverOverride != null) return UniversalQuiverOverride();
return _host.HasGetObjectBoolProperty
&& _host.TryGetObjectBoolProperty(_host.GetPlayerId(), BoolHasUniversalQuiverCharm, out bool on) && on;
}
}
private bool _quiverSaid;
private readonly HashSet<int> _noAmmoNoted = new();
// Launchers whose "no ammo to shoot" was said in chat (until ammo is on it again).
private readonly HashSet<int> _noAmmoSaid = new();
@ -96,6 +117,7 @@ public partial class CombatManager
_ammoTakenOffId = _ammoTakenOffFor = 0;
_noAmmoNoted.Clear();
_noAmmoSaid.Clear();
_quiverSaid = false;
}
/// <summary>Arrows, quarrels, darts: ValidLocations has the ammunition slot; by name when that isn't known.</summary>
@ -145,9 +167,11 @@ public partial class CombatManager
uint uid = unchecked((uint)wo.Id);
int? dt = _host.HasGetObjectIntProperty && _host.TryGetObjectIntProperty(uid, WeaponElements.PropDamageType, out int d) ? d : null;
int? fx = _host.HasGetObjectIntProperty && _host.TryGetObjectIntProperty(uid, WeaponElements.PropUiEffects, out int f) ? f : null;
bool prismatic = MissileAmmo.IsPrismatic(dt, wo.Name);
string elem = prismatic ? "" : WeaponElements.Detect(dt, null, fx, wo.Name).Element;
int listIdx = rules.FindIndex(r => r.Id == wo.Id);
// Prismatic: its properties or name say so, or the Items panel marks this ammo Prismatic.
bool prismatic = MissileAmmo.IsPrismatic(dt, wo.Name)
|| (listIdx >= 0 && MissileAmmo.IsUniversal(rules[listIdx].Element));
string elem = prismatic ? "" : WeaponElements.Detect(dt, null, fx, wo.Name).Element;
int quality = AmmoRecipes.OutputRank(wo.Name, MissileAmmo.CategoryOf(type));
bool wielded = WorldObjectCache.IsWieldedByPlayer(_host, wo);
list.Add(new AmmoCandidate(wo.Id, wo.Name, type, elem, prismatic, quality, listIdx, wielded, IsInfiniteAmmo(_host, wo)));
@ -180,35 +204,55 @@ public partial class CombatManager
List<AmmoCandidate>? pack = null;
var rank = AmmoRank(ruleElement, weak);
// Universal damage (prismatic ammo, or a launcher set to Prismatic in the Items panel) does
// whatever this target is weakest to: the Monsters rule's damage type, else the weakest element.
string best = MissileAmmo.BestElement(WeaponElements.Normalize(ruleElement),
weak != null && weak.Order.Count > 0 ? WeaponPlanner.TieGroups(weak) : null);
WeaponCandidate Resolve(WeaponCandidate c) => MissileAmmo.IsUniversal(c.Element) ? c with { Element = best } : c;
var result = new List<WeaponCandidate>(listed.Count);
var dropped = new List<(WeaponCandidate C, int Type)>();
bool quiver = UniversalQuiverActive;
foreach (var c in listed)
{
if (c.Kind != CombatMode.Missile) { result.Add(c); continue; }
int lt = LauncherTypeOf(_worldFilter[c.Id]);
if (lt == 0) { result.Add(c); continue; } // thrown, or a type not known: as before
if (lt == 0) { result.Add(Resolve(c)); continue; } // thrown, or a type not known: as before
string launcherElement = MissileAmmo.IsUniversal(c.Element) ? "" : c.Element;
pack ??= PackAmmo();
var wielded = pack.FirstOrDefault(a => a.Wielded);
var use = wielded != null && MissileAmmo.CanShoot(lt, wielded.AmmoType)
? wielded
: MissileAmmo.Choose(lt, c.Element, pack, rank);
: MissileAmmo.Choose(lt, launcherElement, pack, rank, best);
if (use == null && quiver)
{
// The Universal Quiver shoots from the empty slot: prismatic, the target's best element (unless the
// Items panel set one).
_noAmmoNoted.Remove(c.Id);
bool set = _settings.ItemRules.FirstOrDefault(x => x.Id == c.Id)?.ElementSource == WeaponList.SourceSet;
WeaponCandidate q = Resolve(c);
result.Add(set || best.Length == 0 || q.Element == best ? q : q with { Element = best });
continue;
}
if (use == null)
{
if (c.InHand) { result.Add(c); continue; } // ran out in hand: crafting's job, as before
if (c.InHand) { result.Add(Resolve(c)); continue; } // ran out in hand: crafting's job, as before
dropped.Add((c, lt));
continue;
}
_noAmmoNoted.Remove(c.Id);
// An element the user picked in the Items panel wins over the ammo's (owner's call,
// 2026-10-01), although the server uses the ammo's element for the damage.
// 2026-10-01), although the server uses the ammo's element for the damage. Prismatic
// there means universal: the best element for this target.
if (_settings.ItemRules.FirstOrDefault(x => x.Id == c.Id)?.ElementSource == WeaponList.SourceSet)
{
result.Add(c);
result.Add(Resolve(c));
continue;
}
string e = MissileAmmo.EffectiveElement(use, c.Element);
result.Add(e.Length > 0 && e != c.Element ? c with { Element = e } : c);
string e = MissileAmmo.EffectiveElement(use, launcherElement, best);
WeaponCandidate r = Resolve(c);
result.Add(e.Length > 0 && e != r.Element ? r with { Element = e } : r);
}
if (dropped.Count == 0) return result;
@ -216,7 +260,7 @@ public partial class CombatManager
// still wielded and ammo crafting makes ammo for it), rather than turning an archer into a
// swordsman or a mage because the pack ran dry.
if (listed[0].Kind == CombatMode.Missile && !result.Any(c => c.Kind == CombatMode.Missile))
return listed;
return listed.Select(Resolve).ToList();
foreach (var (c, lt) in dropped)
if (_noAmmoNoted.Add(c.Id))
_host.Log($"[EquipDiag] 0x{(uint)c.Id:X8} '{c.Name}' has no {MissileAmmo.Label(lt)} in the pack — not swapping to it");
@ -417,8 +461,27 @@ public partial class CombatManager
// leave it alone, as before.
if (AmmoTracker.PendingId == 0 && HasWieldedAmmo()) { canShoot = true; return false; }
// The Universal Quiver: the slot is empty, so the server shoots its infinite prismatic ammo. Nothing is
// wielded (pack ammo would be used up first, and the quiver's is free and the best tier).
if (UniversalQuiverActive)
{
EndAmmoFollowUp();
_noAmmoSaid.Remove(launcherId);
if (!_quiverSaid)
{
_quiverSaid = true;
_host.Log($"[EquipDiag] ammo: Universal Quiver charm on — 0x{(uint)launcherId:X8} '{wo.Name}' shoots from the empty {MissileAmmo.Label(lt)} slot");
}
canShoot = true;
return false;
}
var usable = pack.Where(a => !AmmoTracker.Resting(a.Id, now)).ToList();
var pick = MissileAmmo.Choose(lt, LauncherElement(launcherId, wo), usable, AmmoRank(RuleElementOf(rule), WeaknessFor(target)),
var weakFor = WeaknessFor(target);
string ruleElem = RuleElementOf(rule);
// Prismatic (universal) ammo does the target's best element: it ranks as that element here too.
string bestElem = MissileAmmo.BestElement(ruleElem, weakFor != null && weakFor.Order.Count > 0 ? WeaponPlanner.TieGroups(weakFor) : null);
var pick = MissileAmmo.Choose(lt, LauncherElement(launcherId, wo), usable, AmmoRank(ruleElem, weakFor), bestElem,
demoteId: _ammoTakenOffFor == launcherId ? _ammoTakenOffId : 0);
if (pick == null)
{

View file

@ -234,6 +234,9 @@ public partial class CombatManager
/// </summary>
internal void PollKite()
{
// The Handler-ring run-away has the same orphan rule (autorun must not outlive Think).
// Lost in the 2026-10-25 merge; back 2026-10-28.
PollRingEscape();
if (_kitePhase == KitePhase.None) return;
DateTime now = KiteClock();
if ((now - _kiteTickAt).TotalMilliseconds > KiteOrphanMs

View file

@ -501,6 +501,8 @@ public partial class CombatManager : IDisposable
// the scanner would re-lock the dead-but-not-yet-corpse mob and burn another
// cast on it. Self-prunes at the top of ScanNearbyTargets.
private readonly Dictionary<int, DateTime> _recentlyKilled = new();
/// <summary>Attack spells already announced in chat as lacking components (once per spell per session).</summary>
private readonly HashSet<int> _noCompsAnnounced = new();
private readonly List<int> _killPruneScratch = new();
private const double RECENTLY_KILLED_SUPPRESS_MS = 4000.0; // confirmed kill
private const double PREDICTED_SWAP_SUPPRESS_MS = 2000.0; // predicted kill (re-acquirable if it survived)
@ -2036,12 +2038,33 @@ public partial class CombatManager : IDisposable
lo.Contains("you do not have the") ||
lo.Contains("have all the components for this spell"))
{
_spellManager?.MarkSpellUnresolvable(_pendingOffensiveSpellId);
_host.Log($"[CombatCast] NO-COMPONENTS id={_pendingOffensiveSpellId} " +
$"'{SpellTableStub.GetById(_pendingOffensiveSpellId)?.Name}' — '{text.Trim()}'. " +
$"Marked unresolvable → tiering down to an alternative.");
// The refusal names no spell: it answers the LAST cast sent. A heal or buff sent
// after this attack is the one refused (BuffManager takes it); ours is in flight.
int lastSent = ActionPacer.LastCastSpellId;
if (lastSent != 0 && lastSent != _pendingOffensiveSpellId)
{
// Not ours: nothing marked, pending kept; the debuff handling below still runs.
_host.Log($"[CombatCast] refusal '{text.Trim()}' is for the last cast sent " +
$"({SpellTableStub.GetById(lastSent)?.Name ?? lastSent.ToString()}), not attack {_pendingOffensiveSpellId}: pending kept.");
}
else
{
bool noComps = lo.Contains("components") || lo.Contains("missing some required");
// A known spell refused for components goes on SpellManager's no-components list,
// which TrySpellByName skips (the unresolvable set is purged for known spells, so
// Flame Arc II was recast 228 times, 2026-10-18); anything else stays unresolvable.
if (noComps) _spellManager?.MarkNoComponents(_pendingOffensiveSpellId);
else _spellManager?.MarkSpellUnresolvable(_pendingOffensiveSpellId);
string name = SpellTableStub.GetById(_pendingOffensiveSpellId)?.Name ?? _pendingOffensiveSpellId.ToString();
_host.Log($"[CombatCast] NO-COMPONENTS id={_pendingOffensiveSpellId} '{name}' — '{text.Trim()}'. " +
$"{(noComps ? $"Passed over for {SpellManager.NoComponentsSec / 60:0} min" : "Marked unresolvable")} → tiering down to an alternative.");
if (noComps && _noCompsAnnounced.Add(_pendingOffensiveSpellId))
_host.WriteToChat($"[RynthAi] No components for {name}: attacking with a lower level or another spell for {SpellManager.NoComponentsSec / 60:0} min.", 2);
if (noComps)
Huds.CastWarningHud.Post(name, $"RynthAi attacks with a lower level or another spell it can pay for ({SpellManager.NoComponentsSec / 60:0} min).");
_pendingOffensiveSpellId = 0;
_predictKillSwapArmed = false; // the cast never went out — don't swap off a live mob
}
}
else
{
@ -2234,26 +2257,61 @@ public partial class CombatManager : IDisposable
/// <summary>Test seam: one judged magic cast with no damage.</summary>
internal void MagicMissForTest(int tid) => NoteMagicMissForResync(tid);
// ── Back away from a danger point (RynthAi.Hub BackAwayFrom) ──────────────
// A generic "get out of this radius now", asked for by a server plugin that knows its server's
// dangers: face the object, run-back jump away from it (Jumper "xs"; facing away and jumping back
// would leap into it), hold attacks until the jump settles, then re-engage the same target.
// RynthILT asks for it when Infinite Leaftide's Empyrean Handler channels its lethal ring (the
// detection and its setting moved there 2026-10-20; Silentkelpie's PR 12). Only while the macro is
// running with combat on: an idle character, or one driven by hand or by a meta, never has the
// keyboard taken.
// ── Empyrean Handler / Chaser lethal-ring evade (chat-triggered run-away) ──
// ACECustom Handler emote: "The handler briefly channels infused Empyrean hatred
// to release a lethal ring." The ring can't be melee-evaded — if the character is
// inside its cast radius they die. On that line, when still in range of a Handler,
// cancel the current swing/cast and back-jump away, then resume combat (target kept).
private const string HandlerRingChannelHint = "channels infused Empyrean hatred to release a lethal ring";
private const string HandlerRingChannelStart = "The handler briefly channels";
// 2026-10-17: Empyrean Chasers cast the same lethal ring. Their emote isn't in any log yet, so
// the line is matched loosely: "The handler ..." / "The chaser ..." naming a lethal ring, or
// (any non-speech line) the ring phrase itself. The emote heard is logged once per session.
private const string RingReleaseHint = "release a lethal ring";
/// <summary>The ring casters: the monster name and the word their emote starts with ("The handler").</summary>
private static readonly (string Name, string Subject)[] RingCasters =
{
("Empyrean Handler", "handler"),
("Empyrean Chaser", "chaser"),
};
private bool _ringLineLogged;
/// <summary>Yards: Handler lethal ring is treated as at least this wide (RingRange when larger).</summary>
internal const double HandlerRingDangerYards = 12.0;
/// <summary>Back-jump charge (ms) — run-back + jump must clear ~ring radius.</summary>
private const int HandlerRingJumpHoldMs = 750;
private const double HandlerRingEvadeCooldownMs = 4_000;
/// <summary>BackAwayFrom results (RynthAi.Hub BackAwayFrom passes them on as they are).</summary>
internal const int BackAwayStarted = 1, BackAwayNotNow = 0, BackAwayOutside = 2, BackAwayUnknownObject = 3, BackAwayJumpRefused = -1;
private DateTime _handlerRingEvadeAt = DateTime.MinValue;
private DateTime _handlerRingEvadeUntil = DateTime.MinValue;
private int _handlerRingEvadeId;
private bool _handlerRingJumpStarted;
/// <summary>The jump charge range a caller may ask for (ms).</summary>
internal const int BackAwayMinHoldMs = 100, BackAwayMaxHoldMs = 3000;
/// <summary>After the jump: turn, land and one re-engage tick before attacks resume (ms).</summary>
private const int BackAwaySettleMs = 2_200;
private DateTime _backAwayUntil = DateTime.MinValue;
private bool _backAwayJumpStarted;
// Run-away escape (2026-10-17): one back-jump covered a few metres (backwards is AC's slowest
// motion, and the 150 ms turn settle let it jump the wrong way): Silentkelpie died 1.5 m from
// the Handler 3.2 s after the channel line. Now: face away and run forward (the fastest
// motion), re-aiming away from the Handler, until outside the ring plus a margin.
/// <summary>Yards past the ring radius to run before stopping.</summary>
private const double HandlerRingSafeMarginYards = 4.0;
/// <summary>Longest the run lasts (the ring has gone off by then).</summary>
private const double HandlerRingRunMaxMs = 5_000;
/// <summary>Attacks are held at least this long after the channel line (the ring's cast time).</summary>
private const double HandlerRingHoldMinMs = 3_500;
private const double HandlerRingTurnRefreshMs = 250;
private const double HandlerRingRunRefreshMs = 1_000;
/// <summary>Think last drove the run this long ago: the combat heartbeat drives it (PollRingEscape).</summary>
private const double HandlerRingOrphanMs = 100;
private const string RingEscapeSource = "Combat/RingEscape";
private bool _ringRunActive;
private bool _ringRunning; // autorun is on (else holding at a safe distance)
private double _ringSafeYards;
private double _ringDanger;
private DateTime _ringRunAt = DateTime.MinValue, _ringTurnAt = DateTime.MinValue, _ringTickAt = DateTime.MinValue;
// Where the caster was last seen (2026-10-30): a Handler killed as it channels leaves the
// world (its corpse is another object) while the ring still goes off. The run went on from
// the spot it stood on, not "the caster is gone" at once.
private bool _ringHaveLast;
private uint _ringLastLb;
private float _ringLastX, _ringLastY;
/// <summary>
/// Plugin wires this to <c>Jumper.Start("xs", faceHeading, ms)</c> — face the danger, then
@ -2264,103 +2322,464 @@ public partial class CombatManager : IDisposable
/// <summary>True while the wired jumper is mid-turn / charge / settle.</summary>
public Func<bool>? JumpBusy { get; set; }
/// <summary>True while a back-away is holding combat (jump or settle).</summary>
public bool BackAwayActive =>
_backAwayUntil != DateTime.MinValue && RynthClock.Now < _backAwayUntil;
/// <summary>True while a Handler-ring evade is holding combat (run, wait, or jump/settle).</summary>
public bool RingEvadeActive =>
_ringRunActive || (_handlerRingEvadeUntil != DateTime.MinValue && RynthClock.Now < _handlerRingEvadeUntil);
/// <summary>
/// Backs the character away from <paramref name="objectId"/> when it is within the danger radius:
/// <paramref name="radiusYards"/>, or Ring Range when that is larger (anything a ring reaches).
/// <paramref name="holdMs"/> is the jump's charge (clamped to 100-3000 ms). Cancels the swing or
/// cast in progress, keeps the target. <paramref name="reason"/> is only for the log. Returns a
/// BackAway* result: started, not now (macro stopped, combat off, already backing away), outside
/// the radius, unknown object (no position), or the jump didn't start. Pump thread.
/// </summary>
public int BackAwayFrom(int objectId, double radiusYards, int holdMs, string reason)
// ── Back away from a danger point (RynthAi.Hub BackAwayFrom) ──────────────
// rynth's generic "get out of this radius now" for a server plugin that knows its server's
// dangers (2026-10-21; RynthILT asks it for the Empyrean Handler's lethal ring). It runs away
// (the escape below: stop attacking, face away, autorun until outside the ring plus a margin,
// hold until the ring has gone off). It was the single back-jump until 2026-10-28: a run-back
// jump covers a yard or two, so the character died inside the 12-yard ring every time. The
// back-jump stays for an engine without heading snap / autorun. Only while the macro runs with
// combat on.
/// <summary>BackAwayFrom results (RynthAi.Hub BackAwayFrom passes them on as they are).</summary>
internal const int BackAwayStarted = 1, BackAwayNotNow = 0, BackAwayOutside = 2, BackAwayUnknownObject = 3, BackAwayJumpRefused = -1;
/// <summary>The jump charge range a caller may ask for (ms).</summary>
internal const int BackAwayMinHoldMs = 100, BackAwayMaxHoldMs = 3000;
/// <summary>True while a back-away or a ring evade is holding combat.</summary>
public bool BackAwayActive => RingEvadeActive;
public int BackAwayFrom(int objectId, double radiusYards, int holdMs, string? reason)
{
string why = string.IsNullOrWhiteSpace(reason) ? "a server plugin's request" : reason.Trim();
if (!_settings.IsMacroRunning || !_settings.EnableCombat) return BackAwayNotNow;
if (BackAwayActive) return BackAwayNotNow;
if (!_settings.IsMacroRunning || !_settings.EnableCombat || RingEvadeActive) return BackAwayNotNow;
uint me = _host.GetPlayerId();
if (me == 0 || objectId == 0) return BackAwayUnknownObject;
double dist = _worldFilter.Distance(unchecked((int)me), objectId);
if (dist < 0 || dist == double.MaxValue || double.IsNaN(dist))
if (dist < 0 || dist == double.MaxValue || double.IsNaN(dist)) return BackAwayUnknownObject;
double danger = Math.Max(radiusYards, Math.Max(1, _settings.RingRange));
if (dist > danger) return BackAwayOutside;
bool haveHeading = TryGetHeadingTo(objectId, out double toIt, out _);
DateTime now = RynthClock.Now;
_handlerRingEvadeAt = now;
_handlerRingEvadeId = objectId;
_handlerRingJumpStarted = false;
StopAttackForEscape("back away");
if (haveHeading && _host.HasTurnToHeading && _host.HasSetAutoRun)
{
_host.Log($"[CombatEvade] Back away ({why}): 0x{objectId:X8} has no position - no jump.");
return BackAwayUnknownObject;
}
string name = _worldFilter[objectId]?.Name ?? $"0x{objectId:X8}";
double danger = Math.Max(double.IsNaN(radiusYards) ? 0 : radiusYards, Math.Max(1, _settings.RingRange));
if (dist > danger)
{
_host.Log($"[CombatEvade] Back away ({why}): '{name}' at {dist:0.0} m (outside {danger:0.#} m) - staying put.");
return BackAwayOutside;
}
// Face the danger, then Jumper "xs" (back + run) moves the body away from it.
float face = 0f;
if (TryGetHeadingTo(objectId, out double toIt, out _))
face = (float)(toIt % 360.0);
else if (PlayerCompass.TryGet(_host, out float curr))
face = curr;
int hold = Math.Clamp(holdMs, BackAwayMinHoldMs, BackAwayMaxHoldMs);
_backAwayJumpStarted = false;
// Hold combat long enough for turn + charge + land + one re-engage tick.
_backAwayUntil = RynthClock.Now.AddMilliseconds(hold + BackAwaySettleMs);
// Stop the bound melee/missile attack so the jump isn't eaten by the swing servo.
try
{
if (_host.HasCancelAttack) _host.CancelAttack();
ReleaseHeldTurn();
}
catch { }
if (RequestBackJump?.Invoke(face, hold) == true)
{
_backAwayJumpStarted = true;
_host.Log($"[CombatEvade] Back away ({why}): back-jump away from '{name}' " +
$"at {dist:0.0} m (danger {danger:0.#} m), face {face:0} then xs.");
StartRingRun(objectId, _worldFilter[objectId]?.Name ?? $"0x{(uint)objectId:X8}", dist, danger, toIt, now, why);
return BackAwayStarted;
}
_backAwayUntil = DateTime.MinValue;
_host.Log($"[CombatEvade] Back away ({why}): '{name}' in range, but the back-jump did not start.");
float face = haveHeading ? (float)(toIt % 360.0)
: _host.TryGetPlayerHeading(out float curr) ? curr : 0f;
int hold = Math.Clamp(holdMs, BackAwayMinHoldMs, BackAwayMaxHoldMs);
_handlerRingEvadeUntil = now.AddMilliseconds(hold + 2_200);
if (RequestBackJump?.Invoke(face, hold) == true)
{
_handlerRingJumpStarted = true;
_host.Log($"[CombatEvade] Back away ({why}): back-jump from 0x{(uint)objectId:X8} at {dist:0.0} m (radius {danger:0.#} m; no heading snap / autorun on this engine).");
return BackAwayStarted;
}
_handlerRingEvadeUntil = DateTime.MinValue;
_handlerRingEvadeId = 0;
_host.Log($"[CombatEvade] Back away ({why}): the back-jump did not start.");
return BackAwayJumpRefused;
}
/// <summary>
/// Holds Think from attacking while a back-away jump runs. Keeps the target so combat
/// re-engages as soon as the jumper settles.
/// Chat line from RynthAiPlugin.OnChatWindowText. Starts a back-jump evade when the
/// Handler channels its lethal ring and the character is still inside ring range.
/// </summary>
private bool TickBackAway()
public void HandleChatForRingEvade(string? text, int chatType = -1)
{
if (_backAwayUntil == DateTime.MinValue) return false;
if (string.IsNullOrEmpty(text)) return;
// Gate: only while the macro is running with combat on, and only if the setting allows it.
// Otherwise a ring line heard while the character is idle or being driven by hand (or by a
// meta) would take over the keyboard for the escape run.
if (!_settings.HandlerRingEvade || !_settings.IsMacroRunning || !_settings.EnableCombat) return;
// Handler channel is an Emote (0x0C). ChatSource.IsPlayerAuthored treats Emote as
// player speech, which would skip every real Handler line — anchor on the unique
// phrase starting the line instead (player copies are "Name says, \"...\").
bool mentionsRing = text.IndexOf(HandlerRingChannelHint, StringComparison.OrdinalIgnoreCase) >= 0
|| text.IndexOf(RingReleaseHint, StringComparison.OrdinalIgnoreCase) >= 0;
if (!mentionsRing) return;
// Which caster the emote names ("The handler ..." / "The chaser ..."), or null.
string? subject = null;
foreach ((string _, string word) in RingCasters)
if (RynthCore.Plugin.Shared.ChatSource.StartsWithMarker(text, "The " + word, StringComparison.OrdinalIgnoreCase))
{
subject = word;
break;
}
bool anchored = subject != null
|| RynthCore.Plugin.Shared.ChatSource.StartsWithMarker(text, HandlerRingChannelStart, StringComparison.OrdinalIgnoreCase);
if (!anchored)
{
// Mid-line only when the type is clearly not player speech (some clients strip "The ").
if (chatType is RynthCore.Plugin.Shared.ChatSource.Speech
or RynthCore.Plugin.Shared.ChatSource.Tell
or RynthCore.Plugin.Shared.ChatSource.OutgoingTell
or RynthCore.Plugin.Shared.ChatSource.Channel
or RynthCore.Plugin.Shared.ChatSource.ChannelSend
or RynthCore.Plugin.Shared.ChatSource.Allegiance
or RynthCore.Plugin.Shared.ChatSource.Fellowship)
return;
if (text.IndexOf(" says,", StringComparison.OrdinalIgnoreCase) >= 0
|| text.IndexOf(" tells you,", StringComparison.OrdinalIgnoreCase) >= 0)
return;
}
// The wording that triggered, once per session (the Chaser's emote wasn't known when this
// was written; the log shows it the first time one is heard).
if (!_ringLineLogged)
{
_ringLineLogged = true;
_host.Log($"[CombatEvade] lethal-ring line heard (type 0x{chatType:X2}): \"{text.Trim()}\"");
}
DateTime now = RynthClock.Now;
if (_handlerRingEvadeAt != DateTime.MinValue
&& (now - _handlerRingEvadeAt).TotalMilliseconds < HandlerRingEvadeCooldownMs)
return;
if (!TryFindHandlerForRingEvade(subject, out int handlerId, out double dist, out string name))
{
_host.Log("[CombatEvade] Lethal-ring channel heard, but no Empyrean Handler or Chaser is nearby — no evade.");
return;
}
double danger = Math.Max(HandlerRingDangerYards, Math.Max(1, _settings.RingRange));
if (dist > danger)
{
_host.Log($"[CombatEvade] Lethal-ring channel; '{name}' at {dist:0.0} m (outside {danger:0.#} m) — staying put.");
return;
}
bool haveHeading = TryGetHeadingTo(handlerId, out double toHandler, out _);
_handlerRingEvadeAt = now;
_handlerRingEvadeId = handlerId;
_handlerRingJumpStarted = false;
StopAttackForEscape("Handler lethal ring");
// Run away: face directly away from the Handler and autorun (forward is the fastest motion).
if (haveHeading && _host.HasTurnToHeading && _host.HasSetAutoRun)
{
StartRingRun(handlerId, name, dist, danger, toHandler, now, "Lethal ring");
return;
}
// No heading snap / autorun on this engine: the older back-jump. Face the Handler, then
// Jumper "xs" (back + run) moves the body away from it.
float faceHandler = haveHeading ? (float)(toHandler % 360.0)
: _host.TryGetPlayerHeading(out float curr) ? curr : 0f;
// Hold combat long enough for turn + charge + land + one re-engage tick.
_handlerRingEvadeUntil = now.AddMilliseconds(HandlerRingJumpHoldMs + 2_200);
bool started = RequestBackJump?.Invoke(faceHandler, HandlerRingJumpHoldMs) == true;
if (started)
{
_handlerRingJumpStarted = true;
_host.Log($"[CombatEvade] Lethal ring — back-jump away from '{name}' " +
$"at {dist:0.0} m (danger {danger:0.#} m), face {faceHandler:0}° then xs.");
}
else
{
_handlerRingEvadeUntil = DateTime.MinValue;
_handlerRingEvadeId = 0;
_host.Log("[CombatEvade] Lethal ring heard in range, but the back-jump did not start.");
}
}
/// <summary>Stops the bound melee/missile attack (and any kite run) so an escape isn't eaten by
/// the swing servo or steered by the pull-away.</summary>
private void StopAttackForEscape(string why)
{
try
{
if (_host.HasCancelAttack) _host.CancelAttack();
ReleaseHeldTurn();
EndKite(why);
}
catch { }
}
/// <summary>The run-away escape: face directly away from the caster and autorun (forward is the
/// fastest motion); TickRingRun keeps it going until outside <paramref name="danger"/> plus a margin.</summary>
private void StartRingRun(int casterId, string name, double dist, double danger, double toCaster, DateTime now, string why)
{
float away = (float)((toCaster + 180.0) % 360.0);
_host.TurnToHeadingBy(RingEscapeSource, away);
bool running = _host.SetAutoRunBy(RingEscapeSource, true);
_handlerRingEvadeId = casterId;
_ringRunActive = true;
_ringRunning = running;
_ringDanger = danger;
_ringSafeYards = danger + HandlerRingSafeMarginYards;
_ringRunAt = running ? now : DateTime.MinValue;
_ringTurnAt = _ringTickAt = now;
_ringHaveLast = false;
NoteRingCaster();
_handlerRingEvadeUntil = DateTime.MinValue;
_host.Log($"[CombatEvade] {why} — running away from '{name}' at {dist:0.0} m " +
$"(ring {danger:0.#} m, stop at {_ringSafeYards:0.#} m), heading {away:0}°" +
(running ? "." : " (autorun refused; holding and re-trying)."));
}
/// <summary>
/// Holds Think from attacking while the Handler-ring back-jump runs. Keeps the target
/// so combat re-engages as soon as the jumper settles.
/// </summary>
private bool TickRingEvade()
{
if (_ringRunActive) return TickRingRun();
if (_handlerRingEvadeUntil == DateTime.MinValue) return false;
DateTime now = RynthClock.Now;
bool jumperBusy = JumpBusy?.Invoke() == true;
// Jump never started / failed: clear early.
if (_backAwayJumpStarted && !jumperBusy && now >= _backAwayUntil)
if (_handlerRingJumpStarted && !jumperBusy && now >= _handlerRingEvadeUntil)
{
_backAwayUntil = DateTime.MinValue;
_backAwayJumpStarted = false;
_host.Log("[CombatEvade] Back away done - re-engaging.");
_handlerRingEvadeUntil = DateTime.MinValue;
_handlerRingEvadeId = 0;
_handlerRingJumpStarted = false;
_host.Log("[CombatEvade] Ring evade done — re-engaging.");
return false;
}
if (jumperBusy || now < _backAwayUntil)
if (jumperBusy || now < _handlerRingEvadeUntil)
{
LastCombatSkipReason = "back-away";
LastCombatSkipReason = "handler-ring-evade";
_tickWait = CombatLatencyTracker.Wait.Other;
return true;
}
_backAwayUntil = DateTime.MinValue;
_backAwayJumpStarted = false;
_host.Log("[CombatEvade] Back away done - re-engaging.");
_handlerRingEvadeUntil = DateTime.MinValue;
_handlerRingEvadeId = 0;
_handlerRingJumpStarted = false;
_host.Log("[CombatEvade] Ring evade done — re-engaging.");
return false;
}
/// <summary>rynth's name for the evade tick (Think calls it): the ring evade / back-away above.</summary>
private bool TickBackAway() => TickRingEvade();
/// <summary>
/// The run-away escape, from Think: run (re-aiming away from the Handler) until outside the
/// ring plus a margin or the run times out, then hold attacks until the ring has gone off
/// (running again if the Handler closes back inside the ring). Keeps the target, so combat
/// re-engages after.
/// </summary>
private bool TickRingRun()
{
DateTime now = RynthClock.Now;
_ringTickAt = now;
double elapsed = (now - _handlerRingEvadeAt).TotalMilliseconds;
int me = _host.GetPlayerId() == 0 ? 0 : (int)_host.GetPlayerId();
double d = me != 0 && _handlerRingEvadeId != 0 ? _worldFilter.Distance(me, _handlerRingEvadeId) : -1;
if (d >= 0 && d != double.MaxValue) NoteRingCaster();
else d = RingDistanceFromLast(out _);
bool gone = d < 0;
if (_ringRunning)
{
string? stopWhy = gone ? "the caster is gone"
: d >= _ringSafeYards ? "outside the ring"
: elapsed >= HandlerRingRunMaxMs ? "run timed out"
: null;
if (stopWhy != null)
{
_host.SetAutoRunBy(RingEscapeSource, false);
_ringRunning = false;
_ringRunAt = DateTime.MinValue;
_host.Log($"[CombatEvade] Ring run stopped after {elapsed:0} ms: {stopWhy}" +
(gone ? "." : $" ({d:0.0} m from the caster)."));
}
}
else if (!gone && d < _ringDanger && elapsed < HandlerRingHoldMinMs)
{
// Holding, but the Handler came back inside the ring before it went off: run again.
_ringRunning = true;
_ringTurnAt = _ringRunAt = DateTime.MinValue;
_host.Log($"[CombatEvade] Caster back inside the ring ({d:0.0} m) — running again.");
}
if (_ringRunning)
{
if ((now - _ringTurnAt).TotalMilliseconds >= HandlerRingTurnRefreshMs
&& RingHeadingToCaster(out double toward))
{
_host.TurnToHeadingBy(RingEscapeSource, (float)((toward + 180.0) % 360.0));
_ringTurnAt = now;
}
if ((now - _ringRunAt).TotalMilliseconds >= HandlerRingRunRefreshMs
&& _host.SetAutoRunBy(RingEscapeSource, true))
_ringRunAt = now;
LastCombatSkipReason = "handler-ring-run";
_tickWait = CombatLatencyTracker.Wait.Other;
_stallWatch.Hold(now);
return true;
}
if (!gone && elapsed < HandlerRingHoldMinMs)
{
LastCombatSkipReason = "handler-ring-wait";
_tickWait = CombatLatencyTracker.Wait.Other;
_stallWatch.Hold(now);
return true;
}
EndRingRun();
_host.Log($"[CombatEvade] Ring evade done after {elapsed:0} ms" +
(gone ? "." : $" ({d:0.0} m away) — re-engaging."));
return false;
}
/// <summary>Remembers where the ring caster stands (when the client still has it).</summary>
private void NoteRingCaster()
{
if (_handlerRingEvadeId == 0) return;
try
{
if (!_host.TryGetObjectPosition((uint)_handlerRingEvadeId, out uint cell, out float x, out float y, out _) || cell == 0) return;
_ringLastLb = cell >> 16;
_ringLastX = x; _ringLastY = y;
_ringHaveLast = true;
}
catch { }
}
/// <summary>Yards from where the caster was last seen (same landblock only), or -1.</summary>
private double RingDistanceFromLast(out double headingTo)
{
headingTo = 0;
if (!_ringHaveLast) return -1;
try
{
if (!_host.TryGetPlayerPose(out uint cell, out float px, out float py, out _, out _, out _, out _, out _)
|| (cell >> 16) != _ringLastLb) return -1;
double dx = _ringLastX - px, dy = _ringLastY - py;
headingTo = Math.Atan2(dx, dy) * (180.0 / Math.PI);
if (headingTo < 0) headingTo += 360.0;
return Math.Sqrt(dx * dx + dy * dy);
}
catch { return -1; }
}
/// <summary>The heading toward the caster, or toward where it was last seen.</summary>
private bool RingHeadingToCaster(out double toward)
{
if (TryGetHeadingTo(_handlerRingEvadeId, out toward, out _)) return true;
return RingDistanceFromLast(out toward) >= 0;
}
/// <summary>Clears the run-away escape (autorun off if it was on).</summary>
private void EndRingRun()
{
if (_ringRunning) _host.SetAutoRunBy(RingEscapeSource, false);
_ringRunActive = _ringRunning = _ringHaveLast = false;
_ringRunAt = _ringTurnAt = DateTime.MinValue;
_handlerRingEvadeUntil = DateTime.MinValue;
_handlerRingEvadeId = 0;
}
/// <summary>Stops a Handler-ring escape now (macro stop, death). Safe to call when none is running.</summary>
public void StopRingEscape(string why)
{
if (!_ringRunActive) return;
EndRingRun();
_host.Log($"[CombatEvade] Ring escape stopped: {why}.");
}
/// <summary>
/// Pump-thread watch (each combat heartbeat): combat or the macro off ends the run (autorun
/// must not be left on). Think not driving it (another activity has the tick: looting with
/// Loot priority, buffing) no longer ends it (2026-10-30): the run's own tick goes on from
/// here, bounded by its own limits (run until outside the ring or 5 s, hold until the ring
/// has gone off). It was stopped after 1.5 s, inside the ring.
/// </summary>
internal void PollRingEscape()
{
if (!_ringRunActive) return;
if (!_settings.EnableCombat || !_settings.IsMacroRunning)
{
StopRingEscape("combat or the macro is off");
return;
}
if ((RynthClock.Now - _ringTickAt).TotalMilliseconds > HandlerRingOrphanMs)
TickRingRun();
}
/// <summary>
/// Another part of RynthAi just stopped movement (nav's stop on a change of activity): while
/// the ring run is running, turn away and autorun again now, not at the next refresh.
/// </summary>
public void ReassertRingRun()
{
if (!_ringRunActive || !_ringRunning) return;
if (RingHeadingToCaster(out double toward))
_host.TurnToHeadingBy(RingEscapeSource, (float)((toward + 180.0) % 360.0));
if (_host.SetAutoRunBy(RingEscapeSource, true)) _ringRunAt = RynthClock.Now;
_ringTurnAt = RynthClock.Now;
}
/// <summary>
/// The nearest ring caster (Empyrean Handler or Chaser). When the emote named one ("The chaser
/// ..."), the nearest of that kind is taken if there is one in range of the scan; otherwise the
/// nearest of either kind.
/// </summary>
private bool TryFindHandlerForRingEvade(string? subject, out int handlerId, out double dist, out string name)
{
handlerId = 0; dist = double.MaxValue; name = "";
int me = _host.GetPlayerId() == 0 ? 0 : (int)_host.GetPlayerId();
if (me == 0) return false;
string? preferred = null;
if (subject != null)
foreach ((string n, string word) in RingCasters)
if (word == subject) preferred = n;
int bestId = 0, prefId = 0;
double bestDist = double.MaxValue, prefDist = double.MaxValue;
string bestName = "", prefName = "";
void Consider(int id, string? nm)
{
if (id == 0 || string.IsNullOrEmpty(nm)) return;
bool caster = false;
foreach ((string n, string _) in RingCasters)
if (nm.IndexOf(n, StringComparison.OrdinalIgnoreCase) >= 0) { caster = true; break; }
if (!caster) return;
double d = _worldFilter.Distance(me, id);
if (d < 0) return;
if (d < bestDist) { bestDist = d; bestId = id; bestName = nm; }
if (preferred != null && nm.IndexOf(preferred, StringComparison.OrdinalIgnoreCase) >= 0 && d < prefDist)
{ prefDist = d; prefId = id; prefName = nm; }
}
if (activeTargetId != 0)
Consider(activeTargetId, _worldFilter[activeTargetId]?.Name);
foreach (var s in _scannedTargets)
Consider(s.Id, s.Name);
// Landscape fallback when the scan hasn't listed it yet (channel can land mid-approach).
if (bestId == 0)
{
try
{
foreach (WorldObject wo in _worldFilter.GetLandscape())
{
if ((int)wo.ObjectClass != (int)AcObjectClass.Monster) continue;
Consider(wo.Id, wo.Name);
}
}
catch { }
}
if (prefId != 0) { handlerId = prefId; dist = prefDist; name = prefName; return true; }
if (bestId == 0) return false;
handlerId = bestId; dist = bestDist; name = bestName;
return true;
}
public void ReportDamageOnTarget(int targetId)
{
_magicMissesSinceHit = 0; // something we cast landed: the server's position is fine
@ -4807,6 +5226,7 @@ public partial class CombatManager : IDisposable
ClearCombatTurnMotions();
ResetEnvironmentImpact("macro stopped");
ResetKite("macro stopped");
StopRingEscape("macro stopped");
}
return;
}
@ -5638,10 +6058,13 @@ public partial class CombatManager : IDisposable
if (wo.ObjectClass == AcObjectClass.MissileWeapon && IsAmmoItem(wo)) return null; // listed arrows are the ammo choice, never a weapon to wield
if (IsShieldItem(wo)) return null; // listed shields are the off hand's (CombatManager.Offhand.cs)
var info = ElementTracker.Read(id, wo.Name);
int kind = WeaponKind(id);
string elem = WeaponElements.Normalize(setElement);
// Prismatic (missile weapons only): universal damage, resolved per target in ApplyAmmo.
if (kind == CombatMode.Missile && MissileAmmo.IsUniversal(setElement)) elem = MissileAmmo.Universal;
if (elem.Length == 0) elem = info.Element;
var (slayType, slayBonus) = SlayerOf(id);
return new WeaponCandidate(id, wo.Name, WeaponKind(id), elem, info.Rending, id == inHand, slayType, slayBonus);
return new WeaponCandidate(id, wo.Name, kind, elem, info.Rending, id == inHand, slayType, slayBonus);
}
/// <summary>
@ -8357,6 +8780,9 @@ public partial class CombatManager : IDisposable
// mis-bound engine oracle — selection is purely predictive so nothing
// self-poisons.
if (!_spellManager.TryResolveKnownSpellId(name, out int id)) return 0;
// Refused by the server for missing components: the tier loop drops to a level (or
// another spell) the character can pay for. The server's answer, not a prediction.
if (_spellManager.LacksComponents(id)) return 0;
// Scarab gate DISABLED (EnablePredictiveComponentGate=false). Field-
// tested 2026-05-17, pid 15372: it rejected every KNOWN Force Arc
@ -8821,13 +9247,13 @@ public partial class CombatManager : IDisposable
if (!TryGetShapeBase(element, shapeIdx, useVoid, out string baseName, out string? t7, out bool forcedWar)) return 0;
if (forcedWar) skill = AcSkillType.WarMagic;
// Strict TYPE adherence: cast ONLY the shape configured in the
// Monsters tab (Arc/Bolt/Streak/Blast) — plus the ring override handled
// above. No cross-shape fallthrough; that was casting Streak when
// Arc was configured but its tiers weren't resolvable.
// One exception: Blast falls back to Bolt of the same element when the
// character knows no blast at all — retail has no blast I or II, so a low
// character set to Blast would otherwise never attack.
// The shape configured in the Monsters tab (Arc/Bolt/Streak/Blast) comes first, at the
// highest level the character knows and has components for, plus the ring override above.
// Only when no level of it can be cast (unknown, or refused for components) does another
// shape of the same element stand in (FallbackToCastableShape, 2026-10-18). The old
// cross-shape fallthrough cast Streak for Arc because Arc's tiers didn't RESOLVE (the
// resolver trusted a lying IsSpellKnown); resolution is now known-spells only.
// Blast still tries Bolt first: retail has no blast I or II.
int id = FindBestOffensiveSpellId(baseName, skill, t7);
castShape = id != 0 ? shapeIdx : -1;
// A blocked Arc whose other shape isn't known casts the same element's Bolt (never the arc).
@ -8848,9 +9274,73 @@ public partial class CombatManager : IDisposable
_host.Log($"[CombatCast] no {baseName} known (blasts start at III): casting {boltBase} instead");
}
}
// Nothing of the configured shape the character can cast (no level known, or every known
// level refused for components): another shape of the same element it knows and can pay
// for, rather than no attack at all (2026-10-18).
// A blocked arc never stands in for itself: that is the arc into the obstacle.
if (id == 0) id = FallbackToCastableShape(element, shapeIdx, useVoid, skill, baseName, arcGaveWay, ref castShape);
return id;
}
// War volleys (several bolts at once; levels I-VI, not every element has the low ones): not a
// configurable shape, only a fallback after the other shapes.
private static readonly Dictionary<string, string> WarVolleyBase = new(StringComparer.OrdinalIgnoreCase)
{
{ "Fire", "Flame Volley" }, { "Cold", "Frost Volley" }, { "Lightning", "Lightning Volley" },
{ "Acid", "Acid Volley" }, { "Blade", "Blade Volley" }, { "Pierce", "Force Volley" },
{ "Bludgeon", "Bludgeoning Volley" }, { "Slash", "Blade Volley" },
};
/// <summary>The order the fallback tries the other shapes in: single-target first. Rings are the
/// "pack in range" override (ChooseCastShape), never a stand-in.</summary>
private static readonly int[] FallbackShapeOrder = { ShapeBolt, ShapeArc, ShapeStreak, ShapeBlast };
private readonly Dictionary<string, DateTime> _shapeFallbackSaidAt = new(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// The best castable spell of another shape of <paramref name="element"/> (FallbackShapeOrder, then
/// a war volley): known, and not refused for components lately (TrySpellByName). 0 = none.
/// <paramref name="castShape"/> gets the shape cast (a volley counts as a blast).
/// </summary>
private int FallbackToCastableShape(string element, int wantedShape, bool useVoid, AcSkillType skill, string wantedBase, bool arcBlocked, ref int castShape)
{
foreach (int shape in FallbackShapeOrder)
{
if (shape == wantedShape) continue;
if (shape == ShapeArc && arcBlocked) continue; // the arc gave way to the obstacle
if (!TryGetShapeBase(element, shape, useVoid, out string b, out string? t7, out bool forcedWar)) continue;
if (string.Equals(b, wantedBase, StringComparison.OrdinalIgnoreCase)) continue;
int id = FindBestOffensiveSpellId(b, forcedWar ? AcSkillType.WarMagic : skill, t7);
if (id == 0) continue;
castShape = shape;
NoteShapeFallback(element, wantedBase, id);
return id;
}
if (!useVoid && WarVolleyBase.TryGetValue(element, out string? volley))
{
int id = FindBestOffensiveSpellId(volley, skill);
if (id != 0)
{
castShape = ShapeBlast;
NoteShapeFallback(element, wantedBase, id);
return id;
}
}
return 0;
}
/// <summary>Says (chat + log) once per element and shape per NoSpellChatIntervalMs which spell stands in.</summary>
private void NoteShapeFallback(string element, string wantedBase, int id)
{
string key = element + "|" + wantedBase;
DateTime now = RynthClock.Now;
if (_shapeFallbackSaidAt.TryGetValue(key, out DateTime last) && (now - last).TotalMilliseconds < NoSpellChatIntervalMs) return;
_shapeFallbackSaidAt[key] = now;
string name = SpellTableStub.GetById(id)?.Name ?? id.ToString();
_host.Log($"[CombatCast] no castable {wantedBase} (no level known, or out of components): casting {name} instead");
_host.WriteToChat($"[RynthAi] No {wantedBase} you can cast (not known, or out of components): attacking with {name}.", 2);
}
private readonly HashSet<string> _blastFallbackLogged = new(StringComparer.OrdinalIgnoreCase);
private readonly HashSet<string> _noRingLogged = new(StringComparer.OrdinalIgnoreCase);

View file

@ -122,12 +122,26 @@ internal static class MissileAmmo
|| (name ?? "").IndexOf("Prismatic", StringComparison.OrdinalIgnoreCase) >= 0;
/// <summary>
/// The element the launcher does with this ammo: prismatic takes the launcher's (Pierce
/// when it has none); other ammo its own ("" when not known).
/// The Items panel's element for universal damage (missile weapons and ammo only, 2026-10-19):
/// on Infinite Leaftide prismatic ammo deals every damage type, so it is always the element the
/// target is weakest to. Not an element of its own: <see cref="WeaponElements.Normalize"/> drops it.
/// </summary>
public static string EffectiveElement(AmmoCandidate ammo, string launcherElement)
public const string Universal = "Prismatic";
/// <summary>True for the Items panel's universal-damage element (any case).</summary>
public static bool IsUniversal(string? element) =>
string.Equals(element?.Trim(), Universal, StringComparison.OrdinalIgnoreCase);
/// <summary>
/// The element the launcher does with this ammo: prismatic is universal, so it takes
/// <paramref name="bestElement"/> (what the target is weakest to, or the Monsters rule's) when
/// that is known, else the launcher's (Pierce when it has none); other ammo its own ("" when
/// not known).
/// </summary>
public static string EffectiveElement(AmmoCandidate ammo, string launcherElement, string bestElement = "")
{
if (ammo.Prismatic) return launcherElement.Length > 0 ? launcherElement : "Pierce";
if (ammo.Prismatic)
return bestElement.Length > 0 ? bestElement : launcherElement.Length > 0 ? launcherElement : "Pierce";
return ammo.Element;
}
@ -142,8 +156,10 @@ internal static class MissileAmmo
/// launcher would do with it; ammo of no known element counts as Pierce;
/// 5. quality (Deadly > Greater > plain), then the stack already wielded, then list / pack order.
/// </summary>
/// <param name="bestElement">What the target is weakest to (or the Monsters rule's), "" when not known:
/// prismatic ammo does that element, so it ranks as the best match.</param>
public static AmmoCandidate? Choose(int launcherType, string launcherElement, IReadOnlyList<AmmoCandidate> pack,
Func<string, int> elementRank, int demoteId = 0)
Func<string, int> elementRank, string bestElement = "", int demoteId = 0)
{
AmmoCandidate? best = null;
(int, int, int, int, int, int, int, int) bestKey = default;
@ -151,7 +167,7 @@ internal static class MissileAmmo
{
var a = pack[i];
if (!CanShoot(launcherType, a.AmmoType)) continue;
string e = EffectiveElement(a, launcherElement);
string e = EffectiveElement(a, launcherElement, bestElement);
var key = (a.Listed ? 0 : 1,
a.Infinite ? 0 : 1,
a.Untyped ? 1 : 0,
@ -165,6 +181,19 @@ internal static class MissileAmmo
return best;
}
/// <summary>
/// The element a universal (prismatic) launcher or ammo does against a target: the Monsters
/// rule's damage type when set, else the first of the weakest tie group; "" when neither is known.
/// </summary>
public static string BestElement(string ruleElement, IReadOnlyList<List<string>>? weakGroups)
{
if (ruleElement.Length > 0) return ruleElement;
if (weakGroups != null)
foreach (List<string> g in weakGroups)
if (g.Count > 0) return g[0];
return "";
}
/// <summary>
/// An element ranking for <see cref="Choose"/>: the Monsters rule's damage type first (when
/// set), then the weakness tie groups from weakest; anything else after. With neither, all equal.

View file

@ -43,6 +43,18 @@ public static class SpellDatabase
public static bool IsLoaded => _loaded;
/// <summary>Every spell in SpellData.txt with its family and power (a copy), for the loot popups' spell lists.</summary>
public static List<RynthCore.Loot.Editing.LootSpellEntry> AllSpells()
{
var list = new List<RynthCore.Loot.Editing.LootSpellEntry>(_spellNames.Count);
foreach (KeyValuePair<int, string> kv in _spellNames)
{
_spellMeta.TryGetValue(kv.Key, out var meta);
list.Add(new RynthCore.Loot.Editing.LootSpellEntry(kv.Value, meta.Category, meta.Power));
}
return list;
}
public static void Load(Action<string>? log = null)
{
_spellNames.Clear();

View file

@ -190,8 +190,9 @@ public class SpellManager
BaseNameAliases.TryGetValue(cleanBase, out string? alias);
for (int tier = maxTier + 1; tier <= 8; tier++)
{
if (TryGetTierId(cleanBase, tier, out int id)) return id;
if (alias != null && TryGetTierId(alias, tier, out int idAlias)) return idAlias;
// A level the server refused for components is no better than none.
if (TryGetTierId(cleanBase, tier, out int id) && !LacksComponents(id)) return id;
if (alias != null && TryGetTierId(alias, tier, out int idAlias) && !LacksComponents(idAlias)) return idAlias;
}
return 0;
}
@ -267,6 +268,39 @@ public class SpellManager
if (spellId > 0) _unresolvableSpellIds.Add(spellId);
}
// Spells the server refused for missing components ("You don't have all the components for
// this spell."). The character KNOWS them, so the unresolvable set can't hold them (every
// refresh purges known spells from it, and combat never reads it): Sk's Flame Arc II was
// "marked unresolvable" 228 times and recast every time, and Heal Self V was retried every
// 0.4 s (2026-10-18). Combat (TrySpellByName) and the vital / buff pickers skip a spell here
// until it expires or the character picks up more scarabs or tapers.
private readonly Dictionary<int, DateTime> _noComponentsUntil = new();
/// <summary>How long a spell the server refused for components is passed over.</summary>
public const double NoComponentsSec = 600.0;
private int _lastScarabs = -1, _lastTapers = -1;
/// <summary>The server refused <paramref name="spellId"/> for missing components: pass it over for <see cref="NoComponentsSec"/>.</summary>
public void MarkNoComponents(int spellId)
{
if (spellId > 0) _noComponentsUntil[spellId] = RynthClock.Now.AddSeconds(NoComponentsSec);
}
/// <summary>True while <paramref name="spellId"/> is passed over for missing components.</summary>
public bool LacksComponents(int spellId)
=> _noComponentsUntil.TryGetValue(spellId, out DateTime until) && RynthClock.Now < until;
/// <summary>
/// The pack's scarab and taper counts (the plugin's 3 s inventory scan): more of either than
/// last time (bought or looted) lets every spell refused for components be tried again.
/// </summary>
public void NoteComponentCounts(int scarabs, int tapers)
{
bool more = (_lastScarabs >= 0 && scarabs > _lastScarabs) || (_lastTapers >= 0 && tapers > _lastTapers);
_lastScarabs = scarabs;
_lastTapers = tapers;
if (more && _noComponentsUntil.Count > 0) _noComponentsUntil.Clear();
}
/// <summary>Persisted by BuffManager so the tier-7→6 drop is learned once
/// (first rebuff per char) then instant on every later session/RL.</summary>
public IReadOnlyCollection<int> UnresolvableSpellIds => _unresolvableSpellIds;

View file

@ -1953,7 +1953,12 @@ public class WorldObjectCache
/// reported it DELETE-BEFORE-CLASSIFY when the corpse went away).
/// </summary>
public List<WorldObject> RescueContainedItems(int containerId, IReadOnlyCollection<WorldObject> known)
=> RescueContainedItems(containerId, known, out _);
/// <summary>As above; <paramref name="unread"/> counts the listed items that can't be looked up yet (no name or position).</summary>
public List<WorldObject> RescueContainedItems(int containerId, IReadOnlyCollection<WorldObject> known, out int unread)
{
unread = 0;
var rescued = new List<WorldObject>();
if (containerId == 0 || !_host.HasGetContainerContents) return rescued;
@ -1971,7 +1976,7 @@ public class WorldObjectCache
int id = unchecked((int)buf[i]);
if (id == 0 || have.Contains(id)) continue;
WorldObject? wo = this[id];
if (wo == null) continue;
if (wo == null) { unread++; continue; }
if (wo.ObjectClass == AcObjectClass.Corpse || wo.ObjectClass == AcObjectClass.Monster) continue;
rescued.Add(wo);
}

View file

@ -59,6 +59,14 @@ public sealed partial class RynthAiPlugin
private const long ContentsSweepMs = 500; // how often an open corpse's contents are checked for items the cache missed
private long _lastContentsSweepAt;
private int _lastContentsSweepCorpse;
// Before a corpse is finished, one more look at what the client says it holds
// (2026-11-14, Silentkelpie missed Necrolytic Extracts: two corpses were finished 130 and 230 ms after they
// opened from the cache's items alone; the extract the client had in each was never judged, and the cache later
// reported it DELETE-BEFORE-CLASSIFY with no create seen). The last sweep is at least FinalSweepMinMs after the
// open, and an item the client lists that can't be read yet holds the finish up to UnreadContentsWaitMs.
internal const long FinalSweepMinMs = 200; // the empty-corpse floor: a corpse emptied by jump pickups is no slower
internal const long UnreadContentsWaitMs = 2_500;
private int _unreadHoldLoggedFor;
private const long AppraisalHoldTimeoutMarginMs = 1_000; // stop holding this long before the corpse timeout
// Wedge detection: when AC's item-action state locks up (server-side, e.g.
@ -1898,9 +1906,11 @@ public sealed partial class RynthAiPlugin
// Empty corpse check
if (visibleItemCount == 0)
{
if (openAge >= Math.Max(200, settings.LootEmptyCorpseMs) && !LastPickupSettling(now))
if (openAge >= Math.Max(200, settings.LootEmptyCorpseMs) && !LastPickupSettling(now)
&& !HoldForContentsNotSeen(corpseId, containedItems, openAge))
{
LootDiag($"[RynthAi] {LootTag}: no items on 0x{(uint)corpseId:X8} after {openAge}ms; marking complete.");
_lootItemsLeftAtFinish = 0;
MarkCorpseCompleted(corpseId);
}
return;
@ -2059,11 +2069,43 @@ public sealed partial class RynthAiPlugin
// has played out (closing while it was under way: 2026-10-07).
if (pendingDataCount == 0 && !LastPickupSettling(now))
{
if (HoldForContentsNotSeen(corpseId, containedItems, openAge))
return;
LootDiag($"[RynthAi] {LootTag}: all {visibleItemCount} items on 0x{(uint)corpseId:X8} evaluated; marking complete.");
_lootItemsLeftAtFinish = visibleItemCount; // what is still in it (a chest the player opened stays open for these)
MarkCorpseCompleted(corpseId);
}
}
/// <summary>
/// True while the corpse mustn't be finished yet: it opened under <see cref="FinalSweepMinMs"/> ago, the client
/// lists an item in it the cache hasn't got (now looked up: the next tick judges it), or it lists one that can't
/// be read yet (held up to <see cref="UnreadContentsWaitMs"/> after the open).
/// </summary>
private bool HoldForContentsNotSeen(int corpseId, List<WorldObject> containedItems, long openAge)
{
if (_objectCache == null) return false;
if (openAge < FinalSweepMinMs) return true;
List<WorldObject> missed = _objectCache.RescueContainedItems(corpseId, containedItems, out int unread);
if (missed.Count > 0)
{
_lastContentsSweepAt = 0; // the next tick's sweep adds them to what is judged
LootDiag($"[RynthAi] Corpse loot: before finishing 0x{(uint)corpseId:X8}, found {missed.Count} item(s) the object cache had missed: " +
string.Join(", ", missed.Select(w => $"0x{(uint)w.Id:X8} '{w.Name}' {w.ObjectClass}")) + ".");
return true;
}
if (unread > 0 && openAge < UnreadContentsWaitMs)
{
if (_unreadHoldLoggedFor != corpseId)
{
_unreadHoldLoggedFor = corpseId;
LootDiag($"[RynthAi] Corpse loot: 0x{(uint)corpseId:X8} holds {unread} item(s) that can't be read yet; waiting up to {UnreadContentsWaitMs} ms after the open before finishing.");
}
return true;
}
return false;
}
// A pickup that merges into a stack already in the pack (a Silver Pea onto the Silver Peas):
// the server removes the corpse item (InventoryRemoveObject) and raises the pack stack's size,
// so the picked object never shows up in the inventory and the arrival check waited out
@ -3112,6 +3154,7 @@ public sealed partial class RynthAiPlugin
WriteItemInfoLine(described.Line, described.ChatType);
else if (!string.IsNullOrWhiteSpace(_currentLootItemName))
ChatLine($"[RynthAi] Looted [{_currentLootItemActionLabel}] {_currentLootItemName}");
NoteQuestItemGot(_currentLootItemName); // a quest run's item step ends on it (RynthAiPlugin.QuestNpc.cs)
if (_currentLootItemIsSalvage)
_salvageManager?.EnqueueItem(unchecked((uint)_currentLootItemId));
@ -3590,6 +3633,15 @@ public sealed partial class RynthAiPlugin
ruleLabel = string.Empty;
builtIn = string.Empty;
// The quest loot list (RynthOracle's Run this quest, /ra questloot): a quest item by name, first.
if (QuestLootList.Wants(item.Name))
{
actionLabel = "Keep";
ruleLabel = QuestLootList.RuleLabel;
builtIn = "Quest loot list (RynthOracle's Run this quest) - /ra questloot remove <name> or clear";
return true;
}
// Loot Mode "Rares and needed mana stones only": the loot profile and the other built-in
// keeps are not used (ClassifyRaresMode).
if (LootModes.IsRares(settings.LootMode))

View file

@ -40,6 +40,12 @@ internal sealed class DifficultyTier
}
private readonly ServerStateClient _server = new();
/// <summary>
/// RynthCore's active server is Infinite Leaftide (as of the last Refresh). True only with an engine
/// too old to say (no server list): the loot editors' T11 rows stay as they were there.
/// </summary>
internal bool OnIlt => _server.State is not EngineServerState st || st.IsActive(EngineServerState.IltId);
private volatile Reading _reading = Reading.None;
private volatile string _serverKey = string.Empty;
private long _nextRefreshMs;

View file

@ -46,6 +46,7 @@ internal enum TickStep
PatrolReroute,
AutoVendor,
AutoTrade,
TradeShop,
WeaponElements,
CramStack,
InventoryStatus,
@ -137,6 +138,7 @@ internal sealed class TickGuard
Add(TickStep.PatrolReroute, "patrol reroute", LogCat.Navigation);
Add(TickStep.AutoVendor, "AutoVendor", LogCat.Vendor);
Add(TickStep.AutoTrade, "AutoTrade", LogCat.Vendor);
Add(TickStep.TradeShop, "TradeShop", LogCat.Vendor);
Add(TickStep.WeaponElements, "weapon elements", LogCat.Combat);
Add(TickStep.CramStack, "AutoCram/AutoStack", LogCat.Inventory);
Add(TickStep.InventoryStatus, "inventory status", LogCat.Inventory);

View file

@ -58,6 +58,10 @@ public sealed partial class RynthAiPlugin
private int _doorRequestedId; // asked for by the nav recovery detour; taken on the next idle tick
private bool _doorTargetRequested; // the current target came from a request
private bool _doorWantLockpick; // Pending sends a lockpick (the server said locked), not an open
// 2026-11-07: a key first. A quest run in a dungeon (RynthAiPlugin.QuestDungeon.cs), or Auto Unlock Doors,
// tries the carried keys on a door the server says is locked, the quest's own keys first, then lockpicks.
private int _doorWantKeyId; // Pending sends this key on the door
private readonly System.Collections.Generic.HashSet<int> _doorKeysTried = new();
private long _doorSentAt; // when the last door use / lockpick went out
private int _doorSeqAtSend; // the UseDone count read just before it went out
private uint _doorAnswerErr; // the error of the UseDone that answered it (0 = done)
@ -169,6 +173,8 @@ public sealed partial class RynthAiPlugin
_doorAttempts = 0;
_doorPicks = 0;
_doorWantLockpick = false;
_doorWantKeyId = 0;
_doorKeysTried.Clear();
_navigationEngine?.Stop();
if (Host.HasStopCompletely) Host.StopCompletelyBy("Door");
@ -239,6 +245,7 @@ public sealed partial class RynthAiPlugin
? $"[RynthAi] Door: lockpick answered, opening 0x{(uint)_doorTargetId:X8} again"
: $"[RynthAi] Door: no answer to the lockpick in {now - _doorSentAt} ms, opening 0x{(uint)_doorTargetId:X8} again");
_doorWantLockpick = false;
_doorWantKeyId = 0;
EnterDoorPending(now);
return true;
}
@ -294,7 +301,21 @@ public sealed partial class RynthAiPlugin
int seqBefore = ActionPacer.UseDoneSeqNow(Host);
bool sent;
if (_doorWantLockpick)
if (_doorWantKeyId != 0)
{
int keyId = _doorWantKeyId;
_doorWantKeyId = 0;
if (!Host.TryGetObjectName(unchecked((uint)keyId), out string keyName))
{
Host.Log("[RynthAi] Door: the key is gone; opening it again");
EnterDoorPending(now);
return true;
}
Host.Log($"[RynthAi] Door: using key {keyName} on 0x{(uint)_doorTargetId:X8}");
sent = Host.UseOnFor(unchecked((uint)keyId), unchecked((uint)_doorTargetId), "Door", "the server says this door is locked: a key in the pack");
if (sent) _doorState = DoorState.Unlocking;
}
else if (_doorWantLockpick)
{
var lockpick = FindLockpickInConsumables();
if (lockpick == null)
@ -392,6 +413,15 @@ public sealed partial class RynthAiPlugin
/// <summary>The server said the door is locked: a lockpick if allowed and carried, else leave it for a while.</summary>
private bool OnDoorLocked(LegacyUiSettings settings, long now)
{
// A key from the pack first: the quest's own keys, then any key (2026-11-07).
if ((_questDungeonActive || settings.AutoUnlockDoors) && NextDoorKey() is WorldObject key)
{
_doorKeysTried.Add(key.Id);
_doorWantKeyId = key.Id;
Host.Log($"[RynthAi] Door: the server says 0x{(uint)_doorTargetId:X8} is locked - trying {key.Name}");
EnterDoorPending(now);
return true;
}
if (!settings.AutoUnlockDoors)
{
Host.Log($"[RynthAi] Door: the server says 0x{(uint)_doorTargetId:X8} is locked; Auto Unlock Doors is off, cooldown");
@ -459,6 +489,8 @@ public sealed partial class RynthAiPlugin
_doorAttempts = 0;
_doorPicks = 0;
_doorWantLockpick = false;
_doorWantKeyId = 0;
_doorKeysTried.Clear();
_doorTargetRequested = false;
}
@ -705,6 +737,27 @@ public sealed partial class RynthAiPlugin
return "no-state";
}
/// <summary>
/// The next carried key not tried on this door: the quest run's keys by name first
/// (<see cref="_questDungeonKeys"/>), then anything carried called a key or keyring; never a lockpick.
/// </summary>
private WorldObject? NextDoorKey()
{
if (_objectCache == null) return null;
var carried = GiveCandidates(n => n.IndexOf("key", StringComparison.OrdinalIgnoreCase) >= 0
&& n.IndexOf("lockpick", StringComparison.OrdinalIgnoreCase) < 0);
foreach (string want in _questDungeonKeys)
foreach (WorldObject wo in carried)
if (!_doorKeysTried.Contains(wo.Id) && QuestItemNameMatches(wo.Name, want)) return wo;
foreach (WorldObject wo in carried)
if (!_doorKeysTried.Contains(wo.Id) && IsKeyName(wo.Name)) return wo;
return null;
}
/// <summary>"Cave Door Key", "Bonecrunch's Chest Key", "Keyring": a key (not "Keystone", "Monkey").</summary>
internal static bool IsKeyName(string name) =>
System.Text.RegularExpressions.Regex.IsMatch(name ?? "", @"(?<![\p{L}])(?:key|keys|keyring)(?![\p{L}])", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
/// <summary>The first listed lockpick still carried: its own stack, else one of the same name (ConsumableLookup).</summary>
private WorldObject? FindLockpickInConsumables()
{

View file

@ -0,0 +1,93 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// RynthAi's side of the "RynthAi.DungeonPath" interface (Shared/RynthAiDungeonPathApi.cs,
/// 2026-10-29): the Dungeon Patrol's pathfinder (DungeonPathfinder.NavigateTo on the client's cell
/// dat) for another plugin. RynthNav walks to a dungeon portal with it when it has no walk of its
/// own there. Runs on the plugin pump thread (the caller's OnTick), on the current plugin instance.
/// </summary>
internal static unsafe class DungeonPathInterface
{
private static RynthAiDungeonPathApiV1* _table;
public static IntPtr Query(string iface, uint version)
{
if (iface != RynthAiDungeonPathApiV1.InterfaceName || version == 0 || version > RynthAiDungeonPathApiV1.InterfaceVersion) return IntPtr.Zero;
if (_table == null)
{
var t = (RynthAiDungeonPathApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthAiDungeonPathApiV1));
t->Version = RynthAiDungeonPathApiV1.InterfaceVersion;
t->StructSize = (uint)sizeof(RynthAiDungeonPathApiV1);
t->FindPath = &FindPath;
t->FindPath2 = &FindPath2;
t->ObstacleAhead = &ObstacleAhead;
_table = t;
}
return (IntPtr)_table;
}
/// <summary>Frees the table (plugin shutdown). Callers resolve it every tick.</summary>
public static void Release()
{
var t = _table;
_table = null;
if (t != null) NativeMemory.Free(t);
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int FindPath(uint landblock, double sx, double sy, double sz, double gx, double gy, double gz,
double* points, int maxPoints, int* count)
{
try
{
if (count != null) *count = 0;
RynthAiPlugin? p = PluginExports.Runtime.Plugin;
if (p == null || points == null || maxPoints < 2 || count == null) return RynthAiDungeonPathApiV1.ResultNoData;
return p.DungeonPathForPlugin(landblock, sx, sy, sz, gx, gy, gz, points, maxPoints, count);
}
catch
{
return RynthAiDungeonPathApiV1.ResultNoData;
}
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ObstacleAhead(uint landcell, double x, double y, double z, double headingDeg, double ahead, double maxHeight, double* topAbove)
{
try
{
if (topAbove != null) *topAbove = 0;
RynthAiPlugin? p = PluginExports.Runtime.Plugin;
if (p == null || topAbove == null) return RynthAiDungeonPathApiV1.ResultNoData;
return p.ObstacleAheadForPlugin(landcell, x, y, z, headingDeg, ahead, maxHeight, out *topAbove);
}
catch
{
return RynthAiDungeonPathApiV1.ResultNoData;
}
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int FindPath2(uint landblock, double sx, double sy, double sz, double gx, double gy, double gz,
double maxDrop, double* avoid, int avoidCount, double* points, int* kinds, int maxPoints, int* count)
{
try
{
if (count != null) *count = 0;
RynthAiPlugin? p = PluginExports.Runtime.Plugin;
if (p == null || points == null || maxPoints < 2 || count == null) return RynthAiDungeonPathApiV1.ResultNoData;
if (avoid == null) avoidCount = 0;
return p.DungeonPathForPlugin(landblock, sx, sy, sz, gx, gy, gz, points, maxPoints, count,
Math.Max(0, maxDrop), avoid, Math.Clamp(avoidCount, 0, 64), kinds);
}
catch
{
return RynthAiDungeonPathApiV1.ResultNoData;
}
}
}

View file

@ -0,0 +1,132 @@
// Dungeon levels (2026-11-08, Silentkelpie: "the route is not taking into account for elevation or pits to jump in
// it should build in auto jumps to go down in levels and if one gets stuck in a pit ... it should use backtrack to
// get unstuck"). A drop (a pit, a shaft, a ledge: IsDropEdge) is a one-way step down. The dungeon map's own routes
// (dunnav, the quest's dungeon goto) take drops of up to PlannedMaxDropZ, with a Jump point at the edge; the patrol
// walks one level (the cells walkable from where it starts) and, once round, goes down the drop to the biggest part
// of the dungeon it hasn't patrolled (DescentPath) and patrols there. Log of the run that asked for it: 11-08 10:39,
// dungeon 0x02D4, the patrol looped 43 of the dungeon's cells for ten minutes; a chase into the pit at 10:41:50
// (17 m down) left nav steering at waypoints overhead.
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi;
internal static partial class DungeonPathfinder
{
/// <summary>How far down a planned drop may go (world units): a floor or two; farther costs too much health.</summary>
internal const double PlannedMaxDropZ = 25.0;
/// <summary>Two heights this far apart (world units) are different levels (a waypoint up there isn't reached down here).</summary>
internal const double LevelApartZ = 8.0;
/// <summary>The cells walkable from <paramref name="start"/>: no drops, no hazard cells (the start's level).</summary>
internal static HashSet<uint> WalkableFrom(Dictionary<uint, DungeonNavNode> graph, uint start, IReadOnlySet<uint>? hazards = null)
{
var seen = new HashSet<uint>();
if (!graph.ContainsKey(start)) return seen;
var q = new Queue<uint>();
seen.Add(start);
q.Enqueue(start);
while (q.Count > 0)
{
uint c = q.Dequeue();
DungeonNavNode n = graph[c];
foreach (uint nb in n.Neighbors)
{
if (seen.Contains(nb) || !graph.TryGetValue(nb, out var o) || IsDropEdge(n, o)) continue;
if (hazards != null && hazards.Contains(nb)) continue;
seen.Add(nb);
q.Enqueue(nb);
}
}
return seen;
}
/// <summary>
/// The way down to the most of the dungeon not yet patrolled: from <paramref name="start"/> over its level to the
/// edge of a drop (down by at most <see cref="PlannedMaxDropZ"/>) whose bottom's level has the most cells outside
/// <paramref name="patrolled"/> (the nearer drop on a tie). The cell path (start ... edge, bottom) and that level's
/// cells; null when every drop from here leads somewhere patrolled, or there are none.
/// </summary>
internal static List<uint>? DescentPath(Dictionary<uint, DungeonNavNode> graph, uint start, IReadOnlySet<uint> patrolled,
IReadOnlySet<uint>? hazards, out HashSet<uint> below)
{
below = new HashSet<uint>();
HashSet<uint> level = WalkableFrom(graph, start, hazards);
if (level.Count == 0) return null;
uint bestEdge = 0, bestBottom = 0;
int bestNew = 0;
double bestDist = double.MaxValue;
var levelOf = new Dictionary<uint, HashSet<uint>>();
DungeonNavNode s = graph[start];
foreach (uint c in level)
{
DungeonNavNode a = graph[c];
foreach (uint nb in a.Neighbors)
{
if (level.Contains(nb) || !graph.TryGetValue(nb, out var b) || !IsDropEdge(a, b)) continue;
if (!DropAllowed(a, b, PlannedMaxDropZ) || (hazards != null && hazards.Contains(nb))) continue;
if (!levelOf.TryGetValue(nb, out var lv)) { lv = WalkableFrom(graph, nb, hazards); levelOf[nb] = lv; }
int fresh = 0;
foreach (uint x in lv) if (!patrolled.Contains(x) && !level.Contains(x)) fresh++;
if (fresh == 0) continue;
double d = H(s, a);
if (fresh > bestNew || (fresh == bestNew && d < bestDist))
{
bestNew = fresh; bestDist = d; bestEdge = c; bestBottom = nb;
}
}
}
if (bestEdge == 0) return null;
List<uint> path = FindPath(start, bestEdge, graph, hazards);
if (path.Count == 0) return null;
path.Add(bestBottom);
below = levelOf[bestBottom];
return path;
}
/// <summary>
/// A cell path walked with its drops jumped (a Once route): the walk to each drop's edge (the map's points), a Jump
/// point there facing the way down, then on from where you land; the destination last.
/// </summary>
internal static NavRouteParser BuildDropRoute(List<uint> cellPath, Dictionary<uint, DungeonNavNode> graph,
DungeonGeometry? geo, IReadOnlySet<uint>? hazards,
double startNS, double startEW, double startZ, double destNS, double destEW, double destZ, out int drops)
{
drops = 0;
var route = new NavRouteParser { RouteType = NavRouteType.Once };
double sNs = startNS, sEw = startEW, sZ = startZ;
int runStart = 0;
for (int i = 0; i < cellPath.Count; i++)
{
bool last = i == cellPath.Count - 1;
bool dropNext = !last && graph.TryGetValue(cellPath[i], out var na) && graph.TryGetValue(cellPath[i + 1], out var nb) && IsDropEdge(na, nb);
if (!last && !dropNext) continue;
var run = cellPath.GetRange(runStart, i - runStart + 1);
if (last)
{
NavRouteParser leg = BuildNavRoute(run, graph, destNS, destEW, geo, hazards, sNs, sEw, sZ, destZ);
route.Points.AddRange(leg.Points);
break;
}
DungeonNavNode a = graph[cellPath[i]], b = graph[cellPath[i + 1]];
DropEdgePoints(geo, a, b, out double ex, out double ey, out double ez, out double lx, out double ly, out double lz);
NavRouteParser walk = BuildNavRoute(run, graph, NsOf(ey), EwOf(ex), geo, hazards, sNs, sEw, sZ, ez);
// The walk's last point is the edge itself: it becomes the jump.
if (walk.Points.Count > 0) walk.Points.RemoveAt(walk.Points.Count - 1);
route.Points.AddRange(walk.Points);
double heading = Math.Atan2(EwOf(lx) - EwOf(ex), NsOf(ly) - NsOf(ey)) * (180.0 / Math.PI);
route.Points.Add(new NavPoint
{
Type = NavPointType.Jump, NS = NsOf(ey), EW = EwOf(ex), Z = ez / 240.0,
JumpHeading = (heading + 360.0) % 360.0, JumpShift = false, JumpMs = 0,
});
route.Points.Add(new NavPoint { Type = NavPointType.Point, NS = NsOf(ly), EW = EwOf(lx), Z = lz / 240.0 });
drops++;
sNs = NsOf(ly); sEw = EwOf(lx); sZ = lz;
runStart = i + 1;
}
return route;
}
}

View file

@ -274,16 +274,30 @@ internal static partial class DungeonPathfinder
// ── A* ───────────────────────────────────────────────────────────────────
/// <summary>Extra cost (nav units, ~10 m) of a drop taken on purpose: stairs or a ramp of about
/// the same length are walked instead.</summary>
internal const double DropPenaltyNav = 1.0 / 24.0;
/// <summary>
/// A drop edge <paramref name="maxDropZ"/> allows: downward only (a fall can't be climbed),
/// and no farther down than that (world units; fall damage). 0 = no drops.
/// </summary>
internal static bool DropAllowed(DungeonNavNode from, DungeonNavNode to, double maxDropZ) =>
maxDropZ > 0 && to.Z < from.Z - 0.5 && from.Z - to.Z <= maxDropZ;
/// <summary>
/// Finds the shortest portal-connected path from startCell to goalCell,
/// skipping any edge classified as a drop by IsDropEdge and any neighbor cell
/// in <paramref name="hazardCells"/> (lava / acid pools, etc.).
/// <paramref name="maxDropZ"/> &gt; 0 (2026-10-30, RynthNav's routes): a drop down of up to that
/// many world units is a way too (one way: never up), at <see cref="DropPenaltyNav"/> extra.
/// Returns ordered List of cell IDs, or empty if unreachable.
/// </summary>
public static List<uint> FindPath(
uint startCell, uint goalCell,
Dictionary<uint, DungeonNavNode> graph,
IReadOnlySet<uint>? hazardCells = null)
IReadOnlySet<uint>? hazardCells = null,
double maxDropZ = 0)
{
if (!graph.ContainsKey(startCell) || !graph.ContainsKey(goalCell))
return new List<uint>();
@ -311,13 +325,14 @@ internal static partial class DungeonPathfinder
{
if (closed.Contains(nbId)) continue;
if (!graph.TryGetValue(nbId, out var nbNode)) continue;
if (IsDropEdge(curNode, nbNode)) continue;
bool drop = IsDropEdge(curNode, nbNode);
if (drop && !DropAllowed(curNode, nbNode, maxDropZ)) continue;
// Goal cell is allowed even if marked hazardous (the player asked to go there).
if (nbId != goalCell && hazardCells != null && hazardCells.Contains(nbId)) continue;
double dNS = curNode.NS - nbNode.NS;
double dEW = curNode.EW - nbNode.EW;
double tentG = gCur + Math.Sqrt(dNS * dNS + dEW * dEW);
double tentG = gCur + Math.Sqrt(dNS * dNS + dEW * dEW) + (drop ? DropPenaltyNav : 0);
if (tentG < gScore.GetValueOrDefault(nbId, double.MaxValue))
{
@ -1079,14 +1094,14 @@ internal static partial class DungeonPathfinder
uint goalCell = NearestCell(graph, destNS, destEW, playerZ);
if (startCell == 0 || goalCell == 0) return null;
// IsDropEdge filters out jumps — AC requires a jump to initiate a drop
// and the navigation engine has no jump primitive yet.
// If the destination is only reachable via a drop this returns null.
var path = FindPath(startCell, goalCell, graph, hazardCells);
// Drops down (a pit, a shaft, a ledge) of up to PlannedMaxDropZ are ways too (2026-11-08): walked to the
// edge and jumped (DungeonPathfinder.Levels.cs BuildDropRoute). Never up: a drop can't be climbed.
var path = FindPath(startCell, goalCell, graph, hazardCells, PlannedMaxDropZ);
pathLength = path.Count;
if (pathLength == 0) return null;
var geo = GetGeometry(landblockKey, cellDat, los);
return BuildNavRoute(path, graph, destNS, destEW, geo, hazardCells, playerNS, playerEW, playerZ, playerZ);
float destZ = graph.TryGetValue(goalCell, out var gn) ? gn.Z : playerZ;
return BuildDropRoute(path, graph, geo, hazardCells, playerNS, playerEW, playerZ, destNS, destEW, destZ, out _);
}
}

View file

@ -11,6 +11,9 @@
// walks the character to the item and picks it up. Confirmed when the item leaves the
// ground, retried up to GroundMaxPickupAttempts, then put on a long cooldown.
// * Corpses always win: ground loot only runs when no corpse is claimed or open.
// * Quest items (2026-11-08, Acid Axe Quest: "it didn't loot the item off the ground"): while the quest
// loot list has items (RynthOracle's Run this quest), they are picked up off the ground with Ground Loot
// off too (only they, then), within QuestGroundRange or the corpse range if that is wider.
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthAi.LegacyUi;
@ -49,11 +52,21 @@ public sealed partial class RynthAiPlugin
private readonly Dictionary<int, long> _groundAppraiseAt = new();
/// <summary>A pickup request is out and not yet confirmed — corpse claims wait for it.</summary>
/// <summary>How far a quest item on the ground is gone for (metres; the corpse range when that is wider).</summary>
internal const double QuestGroundRange = 40.0;
/// <summary>Ground loot runs: the setting, or a quest run's items on the quest loot list.</summary>
private static bool GroundLootOn(LegacyUiSettings settings) =>
settings.EnableGroundLoot || (QuestLootList.Enabled && QuestLootList.Count > 0);
/// <summary>The claimed item is a quest item (its range is the quest's).</summary>
private bool _groundTargetQuest;
private bool GroundPickupInFlight => _groundTargetId != 0 && _groundPickupRequestedAt != 0;
/// <summary>Arbiter input: a claimed ground item, or matching ground items seen by the last scan.</summary>
private bool HasGroundLootWork(LegacyUiSettings settings)
=> settings.EnableGroundLoot && (_groundTargetId != 0 || _groundMatchesInRange > 0);
=> GroundLootOn(settings) && (_groundTargetId != 0 || _groundMatchesInRange > 0);
/// <summary>
/// One ground-loot step (pump thread, called from TickCorpseOpening when no corpse is
@ -61,7 +74,7 @@ public sealed partial class RynthAiPlugin
/// </summary>
private void TickGroundLoot(LegacyUiSettings settings, double maxMeters)
{
if (!settings.EnableGroundLoot || _objectCache == null || _playerId == 0)
if (!GroundLootOn(settings) || _objectCache == null || _playerId == 0)
{
ResetGroundLoot(clearCaches: false);
return;
@ -70,7 +83,7 @@ public sealed partial class RynthAiPlugin
long now = CorpseNowMs;
if (_groundTargetId != 0)
{
TickGroundTarget(maxMeters, now);
TickGroundTarget(_groundTargetQuest ? Math.Max(maxMeters, QuestGroundRange) : maxMeters, now);
return;
}
@ -96,6 +109,7 @@ public sealed partial class RynthAiPlugin
_groundTargetAction = action;
_groundTargetRule = rule;
_groundTargetIsSalvage = salvage;
_groundTargetQuest = rule == QuestLootList.RuleLabel;
if (!(_navStopIssued && _navStoppedFor == BotActivity.Looting))
StopNavFor(BotActivity.Looting);
LootDiag($"[RynthAi] Ground loot: claimed 0x{(uint)best.Id:X8} '{_groundTargetName}' dist={bestDist:F1}m [{action}] rule='{rule}'.");
@ -115,10 +129,13 @@ public sealed partial class RynthAiPlugin
_groundMatchesInRange = 0;
if (_objectCache == null || maxMeters <= 0.25)
return null;
// Ground Loot off, a quest run on: its items only, by name (no profile needed).
bool questOnly = !settings.EnableGroundLoot;
double questMeters = Math.Max(maxMeters, QuestGroundRange);
// The profile loaders chat on every failed load; a 300 ms scan must not trigger that.
// Rares mode loads no profile (rares and needed mana stones only).
string profilePath = (settings.CurrentLootPath ?? string.Empty).Trim().Trim('"');
if (!Loot.LootModes.IsRares(settings.LootMode) && (profilePath.Length == 0 || !System.IO.File.Exists(profilePath)))
if (!questOnly && !Loot.LootModes.IsRares(settings.LootMode) && (profilePath.Length == 0 || !System.IO.File.Exists(profilePath)))
return null;
int playerId = unchecked((int)_playerId);
@ -137,12 +154,26 @@ public sealed partial class RynthAiPlugin
if (string.IsNullOrWhiteSpace(wo.Name))
continue;
bool quest = QuestLootList.Wants(wo.Name);
if (questOnly && !quest)
continue;
// Carried / contained items have no world position, so Distance is MaxValue for them.
double dist = _objectCache.Distance(playerId, wo.Id);
if (dist > maxMeters)
if (dist > (quest ? questMeters : maxMeters))
continue;
if (!_objectCache.IsOnGround(wo.Id))
continue;
if (quest)
{
// The quest loot list takes it by name (ClassifyLootItem's first rule): no appraisal needed.
LootDiag($"[LootEval] ground '{wo.Name}' cls={wo.ObjectClass} dist={dist:F1}m -> KEEP [Keep] rule='{QuestLootList.RuleLabel}'");
_groundMatchesInRange++;
if (dist < bestDist)
{
best = wo; bestDist = dist; bestAction = "Keep"; bestRule = QuestLootList.RuleLabel; bestSalvage = false;
}
continue;
}
uint uid = unchecked((uint)wo.Id);
bool appraised = Host.HasHasAppraisalData && Host.HasAppraisalData(uid);
@ -219,6 +250,7 @@ public sealed partial class RynthAiPlugin
WriteItemInfoLine(described.Line, described.ChatType);
else
ChatLine($"[RynthAi] Looted [{_groundTargetAction}] {_groundTargetName} (ground)");
NoteQuestItemGot(_groundTargetName); // a quest run's item step ends on it
if (_groundTargetIsSalvage)
_salvageManager?.EnqueueItem(unchecked((uint)id));
FinishGroundTarget(now, GroundFailCooldownMs);
@ -301,6 +333,7 @@ public sealed partial class RynthAiPlugin
_groundPickupAttempts = 0;
_groundTargetName = _groundTargetAction = _groundTargetRule = string.Empty;
_groundTargetIsSalvage = false;
_groundTargetQuest = false;
_groundLastScanAt = 0; // rescan straight away for the next item
}
@ -313,6 +346,7 @@ public sealed partial class RynthAiPlugin
_groundPickupAttempts = 0;
_groundTargetName = _groundTargetAction = _groundTargetRule = string.Empty;
_groundTargetIsSalvage = false;
_groundTargetQuest = false;
_groundMatchesInRange = 0;
if (!clearCaches)
return;

View file

@ -0,0 +1,77 @@
// CastWarningHud.cs — the "Out of components" pop-up: a small window at the top of the screen
// when the server refuses a spell for missing components, saying which spell and what RynthAi
// does instead (a lower level, or another spell it can pay for). OK closes it; it closes by
// itself after ShownForMs, and comes back for the next spell that runs out.
// Post: any thread (the pump's chat handlers). Render: render thread (OnRender / OnRenderOverlay).
using System;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi.Huds;
internal static class CastWarningHud
{
/// <summary>How long a warning stays up without OK.</summary>
private const long ShownForMs = 30_000;
/// <summary>The same spell warns again at most this often (its refusals repeat until it expires).</summary>
private const long RepeatSameMs = 120_000;
private static readonly Vector4 ColTitle = new(1.00f, 0.45f, 0.35f, 1f);
private static readonly Vector4 ColBody = new(0.92f, 0.92f, 0.92f, 1f);
private static readonly Vector4 ColHint = new(0.70f, 0.75f, 0.80f, 1f);
private static readonly object Gate = new();
private static string _spell = "";
private static string _body = "";
private static long _shownAt;
private static bool _dismissed = true;
private static string _lastSpell = "";
private static long _lastSpellAt;
/// <summary>
/// Shows the warning for <paramref name="spellName"/>: <paramref name="whatNext"/> says what RynthAi
/// does instead. A repeat for the same spell within RepeatSameMs is ignored. Any thread.
/// </summary>
public static void Post(string spellName, string whatNext)
{
long now = Environment.TickCount64;
lock (Gate)
{
if (spellName == _lastSpell && now - _lastSpellAt < RepeatSameMs) return;
_lastSpell = spellName;
_lastSpellAt = now;
_spell = spellName;
_body = whatNext;
_shownAt = now;
_dismissed = false;
}
}
/// <summary>The warning window, while one is up. Render thread.</summary>
public static void Render()
{
string spell, body;
lock (Gate)
{
if (_dismissed || _spell.Length == 0) return;
if (Environment.TickCount64 - _shownAt > ShownForMs) { _dismissed = true; return; }
spell = _spell;
body = _body;
}
// Top centre, clear of the character and the chat.
ImGuiViewportPtr vp = ImGui.GetMainViewport();
ImGui.SetNextWindowPos(new Vector2(vp.WorkPos.X + vp.WorkSize.X * 0.5f, vp.WorkPos.Y + 60f), ImGuiCond.Always, new Vector2(0.5f, 0f));
ImGui.SetNextWindowBgAlpha(0.85f);
var flags = ImGuiWindowFlags.NoTitleBar | ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoSavedSettings
| ImGuiWindowFlags.NoFocusOnAppearing | ImGuiWindowFlags.NoNav | ImGuiWindowFlags.NoMove;
if (!ImGui.Begin("Out of components##rynthcastwarn", flags)) { ImGui.End(); return; }
SafeImGui.TextColored(ColTitle, "Out of components: " + spell);
SafeImGui.TextColored(ColBody, body);
SafeImGui.TextColored(ColHint, "Restock scarabs and tapers (or Prismatic Tapers) to cast it again.");
if (ImGui.Button("OK##rynthcastwarn"))
lock (Gate) _dismissed = true;
ImGui.End();
}
}

View file

@ -590,7 +590,7 @@ internal sealed class HudController
/// Mini Remote drawer, or with <paramref name="window"/> the engine's Mini Remote window)
/// and returns the content size it wants. Render thread.
/// </summary>
public System.Numerics.Vector2 RenderEmbedded(bool window = false, bool tabs = true)
public System.Numerics.Vector2 RenderEmbedded(bool window = false, bool tabs = true, bool popped = false)
{
long now = NowMs;
System.Threading.Interlocked.Exchange(ref _embeddedDrawnAt, now);
@ -598,7 +598,7 @@ internal sealed class HudController
int pushed = LegacyDashboardRenderer.PushDashboardStyle();
try
{
return _miniRemote.RenderEmbedded(window, tabs);
return _miniRemote.RenderEmbedded(window, tabs, popped);
}
finally
{

View file

@ -25,6 +25,8 @@ internal sealed class HudSetupUi
private string _packFilter = string.Empty;
private int _slot;
// Where the player left this window, per character (Plugins/Shared/SavedWindow.cs).
private readonly SavedWindow _spot = new("RynthAi.InventoryHuds");
public HudSetupUi(HudController hud) => _hud = hud;
public void Render()
@ -32,9 +34,11 @@ internal sealed class HudSetupUi
var s = _hud.State;
ImGui.SetNextWindowSize(new Vector2(640, 520), ImGuiCond.FirstUseEver);
bool open = true;
_spot.Apply();
bool visible = ImGui.Begin("Inventory HUDs##rynthhudsetup", ref open);
if (!open) s.ShowSetup = false;
if (!visible) { ImGui.End(); return; }
_spot.Track();
RenderHudToggles(s);
ImGui.Separator();
@ -60,7 +64,7 @@ internal sealed class HudSetupUi
private void RenderItemLists(HudState s)
{
ImGui.TextWrapped("Left = shown on the HUD. Right = in your pack but not on the HUD. "
SafeImGui.TextWrapped("Left = shown on the HUD. Right = in your pack but not on the HUD. "
+ "< pins the highlighted right row; > removes the highlighted left row. "
+ "Add from inventory uses the item selected in the game.");

View file

@ -38,6 +38,11 @@ public sealed class HudState
public bool MiniShowTarget = true;
/// <summary>Pet row: the summon that is out (health, time left), else the next combat essence.</summary>
public bool MiniShowPet = true;
/// <summary>
/// Pet capture row (ILT / ACECustom): auto-capture enable, lens pick, and status.
/// The same AutoCaptureEnabled setting as Mini Remote > Pets > Monster capture.
/// </summary>
public bool MiniShowCapture = true;
public bool MiniShowGems = true;
public bool MiniShowToggles = true;
/// <summary>Obsolete since 2026-10-20 (kept so huds.json loads): the Bank section's switch is RynthILT's (copied once).</summary>

View file

@ -16,11 +16,17 @@ internal sealed class ItemCountHud
private readonly HudController _hud;
private bool _rescueChecked; // off-screen check done for the current show
// Where the player left it, per character (the engine's store, not the shared imgui.ini).
private readonly SavedWindow _placement = new("RynthAi.ItemHud", trackSize: false);
public ItemCountHud(HudController hud) => _hud = hud;
/// <summary>The HUD was not drawn this frame: check its position again on the next show.</summary>
public void OnHidden() => _rescueChecked = false;
public void OnHidden()
{
_rescueChecked = false;
_placement.Reset();
}
public void Render()
{
@ -37,10 +43,12 @@ internal sealed class ItemCountHud
ImGui.SetNextWindowBgAlpha(0.55f);
ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(4, 4));
ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(4, 2));
_placement.Apply(); // auto-sized: the spot only
bool visible = ImGui.Begin("Item HUD##rynthitemhud", flags);
ImGui.PopStyleVar(2);
if (!visible) { ImGui.End(); return; }
UiPlacement.RescueOncePerShow(ref _rescueChecked);
_placement.Track();
if (entries.Length == 0)
{

View file

@ -74,6 +74,7 @@ internal sealed class MiniRemoteHud
private bool _columnOpen; // horizontal layout: a column was already started this frame (next one goes SameLine)
private bool _embedded; // true only inside RenderEmbedded (an engine surface)
private bool _inWindow; // with _embedded: the engine's Mini Remote window, not the dashboard drawer
private bool _popped; // engine Mini Remote is in its own floating window (:popout)
// A tab switch asked for by a command or the engine (any thread), applied by the next tab bar;
// null = none. Starts as the saved tab so the first tab bar restores it.
private string? _pendingTab;
@ -96,7 +97,15 @@ internal sealed class MiniRemoteHud
public MiniRemoteHud(HudController hud) => _hud = hud;
/// <summary>The remote was not drawn this frame: check its position again on the next show.</summary>
public void OnHidden() => _rescueChecked = false;
public void OnHidden()
{
_rescueChecked = false;
_placement.Reset();
}
// Where the player left the floating window and its size, per character (the engine's store,
// not the imgui.ini every client shares).
private readonly SavedWindow _placement = new("RynthAi.MiniRemote");
/// <summary>
/// Switches to tab <paramref name="tab"/> ("" = the remote, else a tab id) on the next
@ -111,20 +120,22 @@ internal sealed class MiniRemoteHud
public void Render()
{
var s = _hud.State;
var flags = ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoCollapse | ImGuiWindowFlags.NoScrollbar
| ImGuiWindowFlags.NoFocusOnAppearing;
if (s.MiniRemoteLocked) flags |= ImGuiWindowFlags.NoMove;
var flags = ImGuiWindowFlags.NoCollapse | ImGuiWindowFlags.NoFocusOnAppearing;
if (s.MiniRemoteLocked) flags |= ImGuiWindowFlags.NoMove | ImGuiWindowFlags.NoResize;
// Left of and above centre, mirroring the Item HUD's first spot.
UiPlacement.CenterFirstUse(new Vector2(-220, -160));
ImGui.SetNextWindowSizeConstraints(new Vector2(180, 120), new Vector2(800, 1200));
ImGui.SetNextWindowBgAlpha(0.70f);
bool open = true;
ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(4, 3));
_placement.Apply();
bool visible = ImGui.Begin("Mini Remote##rynthminiremote", ref open, flags);
ImGui.PopStyleVar();
if (!open) s.ShowMiniRemote = false;
if (!visible) { ImGui.End(); return; }
UiPlacement.RescueOncePerShow(ref _rescueChecked);
_placement.Track();
RenderBody(s, _hud.Remote(), allowTabs: true);
@ -144,12 +155,13 @@ internal sealed class MiniRemoteHud
/// themselves from the result) instead of a window of their own. Returns the content size it
/// wants: the selected tab's width, and the height drawn.
/// </summary>
public Vector2 RenderEmbedded(bool window = false, bool tabs = true)
public Vector2 RenderEmbedded(bool window = false, bool tabs = true, bool popped = false)
{
var s = _hud.State;
_slotMenuIndex = -1;
_embedded = true;
_inWindow = window;
_popped = popped;
float startY = ImGui.GetCursorPosY();
ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(4, 3));
try
@ -171,6 +183,7 @@ internal sealed class MiniRemoteHud
_slotMenuIndex = -1;
_embedded = false;
_inWindow = false;
_popped = false;
}
}
@ -848,6 +861,21 @@ internal sealed class MiniRemoteHud
RenderSlotSizeSlider(s);
if (embedded && _inWindow)
{
// Docked Options used to jump straight to Settings; undocked left-click opens this
// popup, so keep a Settings entry here.
if (_popped && _hud.Host.HasInvokeChatParser
&& ImGui.MenuItem("RynthAi Settings...", MovedTabs.Settings))
_hud.RunEngineCommand(MovedTabs.Settings);
if (_hud.Host.HasInvokeChatParser)
{
if (ImGui.MenuItem(_popped ? "Dock Mini Remote" : "Undock Mini Remote",
_popped ? "/rc miniremote dock" : "/rc miniremote undock"))
_hud.RunEngineCommand(_popped ? "/rc miniremote dock" : "/rc miniremote undock");
if (ImGui.IsItemHovered())
ImGui.SetTooltip(_popped
? "Dock back into the game window."
: "Pop out so this Options menu has more room.");
}
if (ImGui.MenuItem("Inventory HUDs setup...")) s.ShowSetup = true;
}
else if (embedded)
@ -923,17 +951,31 @@ internal sealed class MiniRemoteHud
// server's own screens are its plugin's (the server section below).
if (ImGui.MenuItem("Character##mrcharacter", MovedTabs.OracleCharacter)) _hud.RunEngineCommand(MovedTabs.OracleCharacter);
if (ImGui.IsItemHovered()) ImGui.SetTooltip("RynthOracle's Character tab: the character and this session.");
// Every character's saved packs / storage: RynthInventory's Global Inventory.
if (ImGui.MenuItem("Global Inventory##mrginv", MovedTabs.GlobalInventory))
_hud.RunEngineCommand(MovedTabs.GlobalInventory);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Global Inventory (/ginv): every character's saved packs and storage.");
if (ImGui.MenuItem("Quests##mrquests", "/ro")) _hud.RunEngineCommand("/ro");
if (ImGui.IsItemHovered()) ImGui.SetTooltip("RynthOracle: quest timers, tracking and rewards.");
if (ImGui.MenuItem("Quest Timers##mrqtimers", "/ro timers")) _hud.RunEngineCommand("/ro timers");
if (ImGui.IsItemHovered()) ImGui.SetTooltip("RynthOracle's Quest Timers window: your tracked quests and the time left on each.");
if (ImGui.MenuItem("Fellowship##mrfellow", "/ro fellowship")) _hud.RunEngineCommand("/ro fellowship");
if (ImGui.IsItemHovered()) ImGui.SetTooltip("RynthOracle's Fellowship tab: members, levels and XP sharing.");
if (ImGui.MenuItem("Skills##mrskills", "/rc skills")) _hud.RunEngineCommand("/rc skills toggle");
if (ImGui.IsItemHovered()) ImGui.SetTooltip("RynthOracle's Fellowship tab: members, levels, XP sharing.");
// Skills live under RynthOracle (Skills / Attributes / Progress tabs).
if (ImGui.MenuItem("Skills##mrskills", "/ro skills")) _hud.RunEngineCommand("/ro skills");
if (ImGui.IsItemHovered()) ImGui.SetTooltip("RynthOracle's Skills tab: raise and train skills.");
if (ImGui.MenuItem("Attributes##mrattrs", "/ro attrs")) _hud.RunEngineCommand("/ro attrs");
if (ImGui.IsItemHovered()) ImGui.SetTooltip("RynthOracle's Attributes tab: attributes and vitals.");
if (ImGui.MenuItem("Progress##mrprogress", "/ro progress")) _hud.RunEngineCommand("/ro progress");
if (ImGui.IsItemHovered()) ImGui.SetTooltip("RynthOracle's Progress tab: progression planners (where the server has them).");
if (ImGui.MenuItem("Inventory##mrinv", "/rc inventory")) _hud.RunEngineCommand("/rc inventory");
if (ImGui.IsItemHovered()) ImGui.SetTooltip("This character's packs (Inventory panel). Count / GInv buttons there open Item Count and Global Inventory.");
if (ImGui.MenuItem("Item Count##mritemcount", "/rc itemcount")) _hud.RunEngineCommand("/rc itemcount");
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Item Count panel (/rc itemcount): how many of each named item you carry. Distinct from the floating pack item count HUD.");
}
if (ImGui.MenuItem("Inventory HUDs setup...##mrsetup")) s.ShowSetup = true;
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Show / hide the floating pack item count HUD and the Mini Remote (/ra huds).");
}
/// <summary>

View file

@ -1,11 +1,13 @@
// MovedTabs.cs - Mini Remote tabs that moved out of the Mini Remote (2026-10-13), and where to.
//
// RynthILT's Character tab left the Mini Remote: its character overview and session went to
// RynthOracle's Character tab ("/ro character"), its ILT session rates to RynthCore's Mini Remote
// "Session Stats" section (RynthILT's own "section:ilt-rates"), and the force-server override to
// RynthCore Settings > Game Client ("/rc diagnostics", the server picker). Infinite Leaftide's own screens stay
// RynthILT's: Charms and Banking are still Mini Remote ILT tabs (RynthILT's own manifest places
// them on the rail since 2026-10-20), drawn by RynthILT.
// RynthILT's Character, Charms and Banking tabs left the Mini Remote:
// Character, Charms -> RynthOracle's Character tab ("/ro character"): the character, its
// session and the ILT charms list (fed by "RynthILT.Data");
// Banking -> RynthInventory's Global Inventory ("/ginv bank"): every character's
// saved packs and storage (including banks when Include Storage is on).
// RynthCore's Mini Remote "Char" section is "Session Stats" now (RynthAi's session stats, with RynthILT's
// "section:ilt-rates"), and a server is forced only in RynthCore Settings > Game Client ("/rc diagnostics",
// the server picker; on Diagnostics until 2026-11-11).
// Old saved tab ids, links and "/ra hub open|tab <name>" land on the new home through CommandFor.
//
// Pure: the host tests check the mapping offline.
@ -15,9 +17,18 @@ namespace RynthCore.Plugin.RynthAi.Huds;
internal static class MovedTabs
{
/// <summary>RynthOracle's Character tab (the character overview and this session).</summary>
/// <summary>RynthOracle's Character tab.</summary>
public const string OracleCharacter = "/ro character";
/// <summary>RynthOracle's Pet Breeding tab (Infinite Leaftide; the same tracker as the Pets tab's Breeding sub-tab).</summary>
public const string OracleBreeding = "/ro breeding";
/// <summary>RynthInventory's Global Inventory (alias used by the old Banking tab).</summary>
public const string GlobalBank = "/ginv bank";
/// <summary>RynthInventory's Global Inventory window.</summary>
public const string GlobalInventory = "/ginv";
/// <summary>The server picker: RynthCore Settings > Game Client (on Diagnostics until 2026-11-11, hence the name; RynthCore 2026.10.5.54+).</summary>
public const string Diagnostics = "/rc diagnostics";
@ -33,7 +44,8 @@ internal static class MovedTabs
/// </summary>
public static string? CommandFor(string? tab) => (tab ?? string.Empty).Trim().ToLowerInvariant() switch
{
"character" or "char" or "rates" => OracleCharacter,
"character" or "char" or "rates" or "charms" or "charm" => OracleCharacter,
"banking" or "bank" => GlobalBank,
_ => null,
};
@ -41,6 +53,8 @@ internal static class MovedTabs
public static string HomeOf(string command) => command switch
{
OracleCharacter => "RynthOracle's Character tab",
OracleBreeding => "RynthOracle's Pet Breeding tab",
GlobalBank or GlobalInventory => "Global Inventory",
Diagnostics => "RynthCore Settings > Game Client",
Settings => "RynthAi Settings (Advanced Settings)",
_ => command,

View file

@ -320,7 +320,10 @@ internal static class MagItemDescriber
Int(T11Catalog.PropZcTier),
Int(T11Catalog.PropWeaponAugScaleTier),
item.TryGetInt(T11Catalog.PropWeaponAugScaleQuality, out int quality) ? quality : -1);
T11ItemInfo t11 = T11ItemInfo.Parse(item.Name, longDesc, item.GetString(StringUse), t11Server);
// T11 is Infinite Leaftide's (T11ItemSupport.Enabled follows the active server).
T11ItemInfo t11 = RynthCore.Plugin.RynthAi.Loot.T11ItemSupport.Enabled
? T11ItemInfo.Parse(item.Name, longDesc, item.GetString(StringUse), t11Server)
: T11ItemInfo.None;
// ── Set ─────────────────────────────────────────────────────────────────
int set = Int(IntEquipmentSet);

View file

@ -19,6 +19,13 @@
//
// Items are matched by exactly what Tom picked: the same weenie class id (when the engine can
// read it) and the same name. Nothing else is ever given.
//
// Amount and Every (2026-11-15, Silentkelpie: "add in a option to give x number of a item and a
// timer of how often every x seconds"). Amount is how many units a round gives (0 = all of them);
// a stack bigger than what is left of the round is split (AC's give with an amount). Every is the
// seconds from the end of one round to the start of the next (0 = one round, as before). With Every
// set the run goes on until Stop: having none of the item, the target out of range or a fight only
// skip to the next round; a changed target, refusals or a client that won't send still end it.
// ============================================================================
using System;
@ -37,14 +44,14 @@ internal interface IQuickGiveEnv
bool InCombat();
/// <summary>Why a give can't go out now (the client is busy, the server owes an answer); null = free.</summary>
string? HoldReason();
/// <summary>The next carried (never worn) item matching <paramref name="key"/> that is not in <paramref name="skip"/>.</summary>
/// <summary>The next carried (never worn) item matching <paramref name="key"/> that is not in <paramref name="skip"/>; <paramref name="count"/> is its stack size.</summary>
bool NextItem(GiveItemKey key, ISet<int> skip, out int itemId, out int count);
/// <summary>How many matching items are still carried (whole objects).</summary>
int CountCarried(GiveItemKey key);
/// <summary>The item left the pack, or its stack shrank below <paramref name="count"/>.</summary>
bool Landed(int itemId, int count);
/// <summary>AC's give action for the whole object. False when the engine refused to send it.</summary>
bool Send(int itemId, int targetId);
/// <summary>AC's give action: <paramref name="amount"/> units of the stack, 0 = the whole object. False when the engine refused to send it.</summary>
bool Send(int itemId, int targetId, int amount);
/// <summary>A count of the server's refusals so far (rises when one arrives).</summary>
int RefusalSeq();
void Say(string text);
@ -53,12 +60,14 @@ internal interface IQuickGiveEnv
internal sealed class QuickGive
{
public enum Phase { Idle, Pending, InFlight }
public enum Phase { Idle, Pending, InFlight, Waiting }
/// <summary>The target must be this near to start; it ends the run if it gets farther than <see cref="StopMeters"/>.</summary>
public const double StartMeters = 10, StopMeters = 15;
public const long PaceMs = 350, ConfirmMs = 6000, RefuseBackoffMs = 1000, HoldMaxMs = 60_000, GoneMs = 1500;
public const int MaxRefusals = 3, MaxSendFails = 5, MaxGives = 2000;
/// <summary>The largest Amount (units a round) and Every (seconds between rounds).</summary>
public const int MaxAmount = 1_000_000, MaxEverySec = 86_400;
private const long ThinkMs = 50;
private readonly IQuickGiveEnv _env;
@ -76,9 +85,24 @@ internal sealed class QuickGive
public int Given { get; private set; }
public int Units { get; private set; }
public string LastResult { get; private set; } = "";
/// <summary>Units a round gives; 0 = every one carried. Changed any time; a running round uses the new value.</summary>
public int Amount { get; private set; }
/// <summary>Seconds from the end of a round to the start of the next; 0 = one round.</summary>
public int EverySec { get; private set; }
/// <summary>Rounds started this run, and the units given in the current one.</summary>
public int Rounds { get; private set; }
public int RoundUnits { get; private set; }
/// <summary>Waiting: milliseconds until the next round (0 when not waiting).</summary>
public long NextRoundInMs => State == Phase.Waiting ? Math.Max(0, _roundAt - _env.Now) : 0;
public void SetAmount(int units) => Amount = Math.Clamp(units, 0, MaxAmount);
public void SetEvery(int seconds) => EverySec = Math.Clamp(seconds, 0, MaxEverySec);
private bool Repeats => EverySec > 0;
private long _lastThink, _nextAt, _sentAt, _goneSince, _holdSince, _leftAt;
private int _inFlightId, _inFlightCount, _refusalSeqAtSend, _refusals, _sendFails, _left;
private int _inFlightId, _inFlightCount, _inFlightUnits, _refusalSeqAtSend, _refusals, _sendFails, _left, _roundGives;
private long _roundAt;
private string _waitWhy = "";
private string _holdWhy = "";
public void SetItem(int id, GiveItemKey key) { if (!Running) { ItemId = id; Item = key; } }
@ -96,17 +120,44 @@ internal sealed class QuickGive
if (meters < 0 || meters > StartMeters) { why = $"{TargetName} is {(meters < 0 ? "too far" : meters.ToString("0") + " m away")} (give range is {StartMeters:0} m); walk closer"; return Refuse(why); }
if (_env.InCombat()) { why = "you are in a fight"; return Refuse(why); }
int have = _env.CountCarried(Item);
if (have == 0) { why = $"no '{Item.Name}' in your packs"; return Refuse(why); }
if (have == 0 && !Repeats) { why = $"no '{Item.Name}' in your packs"; return Refuse(why); }
Given = 0; Units = 0; _refusals = 0; _sendFails = 0; _goneSince = 0; _holdSince = 0; _nextAt = 0; _lastThink = 0; _left = have; _leftAt = _env.Now;
_skip.Clear();
Rounds = 0;
LastResult = "";
State = Phase.Pending;
_env.Say($"[RynthAi] Quick give: giving every '{Item.Name}' ({have} in your packs) to {TargetName}. Stop: /ra itemtool givestop.");
_env.Log($"[RynthAi] Quick give: start item '{Item.Name}' wcid 0x{Item.Wcid:X} x{have} -> 0x{(uint)TargetId:X8} '{TargetName}' ({meters:0.0} m)");
StartRound();
string what = Amount > 0 ? $"{Amount} of '{Item.Name}'" : $"every '{Item.Name}'";
string when = Repeats ? $", then again every {EverySec} s until you stop it" : "";
_env.Say($"[RynthAi] Quick give: giving {what} ({have} in your packs) to {TargetName}{when}. Stop: /ra itemtool givestop.");
_env.Log($"[RynthAi] Quick give: start item '{Item.Name}' wcid 0x{Item.Wcid:X} x{have} amount {Amount} every {EverySec}s -> 0x{(uint)TargetId:X8} '{TargetName}' ({meters:0.0} m)");
return true;
}
private void StartRound()
{
Rounds++;
RoundUnits = 0;
_roundGives = 0;
_refusals = 0;
_holdSince = 0;
_holdWhy = "";
_waitWhy = "";
_skip.Clear();
State = Phase.Pending;
}
/// <summary>The round is over: with Every set, the next one starts EverySec later; without, the run ends.</summary>
private void EndRound(string why)
{
if (!Repeats) { Finish(why); return; }
_inFlightId = 0;
_roundAt = _env.Now + EverySec * 1000L;
_waitWhy = "";
State = Phase.Waiting;
_env.Log($"[RynthAi] Quick give: round {Rounds} over - {why}; {RoundUnits} unit(s) this round; next in {EverySec} s");
_env.Say($"[RynthAi] Quick give: round {Rounds} - {why} ({RoundUnits} unit(s)). Next round in {EverySec} s.");
}
private bool Refuse(string why)
{
_env.Say($"[RynthAi] Quick give: can't start - {why}.");
@ -135,9 +186,13 @@ internal sealed class QuickGive
switch (State)
{
case Phase.Idle: return LastResult.Length > 0 ? $"Quick give {LastResult}." : "Idle.";
case Phase.Waiting:
string wait = _waitWhy.Length > 0 ? $" (then waits: {_waitWhy})" : "";
return $"'{Item.Name}' to {TargetName}: {Units} unit(s) in {Rounds} round(s); next round in {(NextRoundInMs + 999) / 1000} s{wait}, {_left} in your packs.";
default:
string hold = _holdWhy.Length > 0 ? $" (waiting: {_holdWhy})" : "";
return $"Giving '{Item.Name}' to {TargetName}: {Given} given ({Units} units), {_left} left{hold}.";
string round = Amount > 0 ? $" Round {Rounds}: {RoundUnits} of {Amount}." : Repeats ? $" Round {Rounds}." : "";
return $"Giving '{Item.Name}' to {TargetName}: {Given} given ({Units} units), {_left} left{hold}.{round}";
}
}
}
@ -149,24 +204,45 @@ internal sealed class QuickGive
if (now - _lastThink < ThinkMs) return;
_lastThink = now;
if (now - _leftAt >= 500) { _left = _env.CountCarried(Item); _leftAt = now; }
if (State == Phase.Waiting) { TickWaiting(now); return; }
// The target must stay the one Tom picked, loaded and near.
if (!_env.TargetLoaded(TargetId, out string name, out double meters))
{
if (_goneSince == 0) _goneSince = now;
else if (now - _goneSince >= GoneMs) Finish($"{TargetName} is gone");
else if (now - _goneSince >= GoneMs) EndRound($"{TargetName} is gone");
return;
}
_goneSince = 0;
if (!string.Equals(name, TargetName, StringComparison.OrdinalIgnoreCase)) { Finish($"the target changed ('{TargetName}' is now '{name}')"); return; }
if (meters < 0 || meters > StopMeters) { Finish($"{TargetName} is out of give range ({(meters < 0 ? "position unknown" : meters.ToString("0") + " m")})"); return; }
if (_env.InCombat()) { Finish("a fight started"); return; }
if (now - _leftAt >= 500) { _left = _env.CountCarried(Item); _leftAt = now; }
if (meters < 0 || meters > StopMeters) { EndRound($"{TargetName} is out of give range ({(meters < 0 ? "position unknown" : meters.ToString("0") + " m")})"); return; }
if (_env.InCombat()) { EndRound("a fight started"); return; }
if (State == Phase.InFlight) { TickInFlight(now); return; }
TickPending(now);
}
/// <summary>Between rounds: the next starts when it is due and the target is back in range, out of a fight.</summary>
private void TickWaiting(long now)
{
if (now < _roundAt) return;
string? why = null;
if (!_env.TargetLoaded(TargetId, out string name, out double meters)) why = $"{TargetName} isn't in view";
else if (!string.Equals(name, TargetName, StringComparison.OrdinalIgnoreCase)) { Finish($"the target changed ('{TargetName}' is now '{name}')"); return; }
else if (meters < 0 || meters > StartMeters) why = $"{TargetName} is {(meters < 0 ? "too far" : meters.ToString("0") + " m away")} (give range {StartMeters:0} m)";
else if (_env.InCombat()) why = "you are in a fight";
else if (_left == 0) why = $"no '{Item.Name}' in your packs";
if (why != null)
{
if (_waitWhy != why) _env.Log($"[RynthAi] Quick give: round {Rounds + 1} waits - {why}");
_waitWhy = why;
return;
}
StartRound();
_env.Log($"[RynthAi] Quick give: round {Rounds} starts ({_left} carried)");
}
private void TickPending(long now)
{
if (now < _nextAt) return;
@ -175,20 +251,24 @@ internal sealed class QuickGive
{
_holdWhy = why;
if (_holdSince == 0) _holdSince = now;
else if (now - _holdSince >= HoldMaxMs) Finish($"waited {HoldMaxMs / 1000} s: {why}");
else if (now - _holdSince >= HoldMaxMs) EndRound($"waited {HoldMaxMs / 1000} s: {why}");
return;
}
_holdSince = 0;
_holdWhy = "";
if (Given + _refusals >= MaxGives) { Finish($"reached {MaxGives} gives"); return; }
if (Amount > 0 && RoundUnits >= Amount) { EndRound($"gave {RoundUnits}"); return; }
if (_roundGives + _refusals >= MaxGives) { EndRound($"reached {MaxGives} gives"); return; }
if (!_env.NextItem(Item, _skip, out int id, out int count))
{
Finish(Given > 0 ? "done - no more of that item" : "no more of that item to give");
EndRound(RoundUnits > 0 ? "done - no more of that item" : "no more of that item to give");
return;
}
// A stack bigger than what is left of the round is split: AC's give with an amount.
int units = count;
if (Amount > 0 && count > Amount - RoundUnits) units = Amount - RoundUnits;
_refusalSeqAtSend = _env.RefusalSeq();
if (!_env.Send(id, TargetId))
if (!_env.Send(id, TargetId, units < count ? units : 0))
{
if (++_sendFails >= MaxSendFails) Finish("the client wouldn't send the give");
else _nextAt = now + RefuseBackoffMs;
@ -197,6 +277,7 @@ internal sealed class QuickGive
_sendFails = 0;
_inFlightId = id;
_inFlightCount = count;
_inFlightUnits = units;
_sentAt = now;
State = Phase.InFlight;
}
@ -206,10 +287,15 @@ internal sealed class QuickGive
if (_env.Landed(_inFlightId, _inFlightCount))
{
Given++;
Units += _inFlightCount;
_skip.Add(_inFlightId); // it is the target's now, whatever a stale inventory read still says
_roundGives++;
Units += _inFlightUnits;
RoundUnits += _inFlightUnits;
if (_inFlightUnits >= _inFlightCount)
{
_skip.Add(_inFlightId); // it is the target's now, whatever a stale inventory read still says
_left = Math.Max(0, _left - 1);
}
_refusals = 0;
_left = Math.Max(0, _left - 1);
State = Phase.Pending;
_nextAt = now + PaceMs;
return;

View file

@ -7,6 +7,9 @@ namespace RynthCore.Plugin.RynthAi.LegacyUi;
internal sealed class LegacyAdvancedSettingsUi
{
// Where the player left the window, per character (Plugins/Shared/SavedWindow.cs).
private readonly SavedWindow _spot = new("RynthAi.AdvancedSettings");
private readonly LegacyUiSettings _settings;
private MissileCraftingManager? _missileCraftingManager;
@ -88,6 +91,10 @@ internal sealed class LegacyAdvancedSettingsUi
public void SetAutoTradeStatusProvider(Func<string> status) => _autoTradeStatus = status;
private string _newAutoAcceptPattern = "";
private Func<string>? _tradeShopStatus;
private Func<bool>? _tradeShopBanking;
public void SetTradeShopStatusProvider(Func<string> status) => _tradeShopStatus = status;
public void SetTradeShopBankingProvider(Func<bool> banking) => _tradeShopBanking = banking;
public string MissileCraftingState => _missileCraftingManager?.State.ToString() ?? string.Empty;
public bool MissileCraftingActive => _missileCraftingManager?.IsCrafting ?? false;
public string MissileCraftingStatus => _missileCraftingManager?.StatusMessage ?? string.Empty;
@ -99,8 +106,10 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.SetNextWindowSize(new Vector2(600, 400), ImGuiCond.FirstUseEver);
_spot.Apply();
if (ImGui.Begin("RynthAi Advanced Settings", ref _settings.ShowAdvancedWindow))
{
_spot.Track();
ImGui.BeginChild("AdvancedSidebar", new Vector2(150, 0), ImGuiChildFlags.Borders);
for (int i = 0; i < _settings.AdvancedTabs.Length; i++)
{
@ -170,6 +179,7 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.TextDisabled("inscribed, rare, zero value, packs, or anything a Keep rule could match.");
RenderAutoTrade();
RenderTradeShop();
}
private void RenderAutoTrade()
@ -236,20 +246,45 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.TextDisabled("packs, unidentified items, or items on RynthAi's weapon/consumable lists.");
}
/// <summary>
/// Trade Shop catalog (ungated). Conversion rates from UB-IT. Banking hook row only when
/// the server hub reports this world supports banking payments.
/// </summary>
private void RenderTradeShop()
{
ImGui.Spacing();
ImGui.Spacing();
ImGui.Text("Trade Shop (priced catalog)");
ImGui.Separator();
ImGui.Spacing();
string status = _tradeShopStatus?.Invoke() ?? "Not logged in";
SafeImGui.TextDisabled($"Status: {status}");
ImGui.Spacing();
ImGui.Checkbox("Enabled##TS", ref _settings.TradeShopEnabled);
ImGui.SameLine();
ImGui.Checkbox("Test Mode##TS", ref _settings.TradeShopTestMode);
if (ImGui.Button(_settings.ShowTradeShopWindow ? "Focus Trade Shop window##TS" : "Open Trade Shop window##TS"))
_settings.ShowTradeShopWindow = true;
if (ImGui.IsItemHovered())
SafeImGui.SetTooltip("Opens the Trade Shop editor: item prices and bank/payment conversion rates.\n" +
"Also: Inventory panel Storefront button, or /ra tradeshop ui.");
SafeImGui.TextDisabled("Edit prices and conversion rates in the Trade Shop window.");
SafeImGui.TextDisabled("Inventory → Storefront icon, or /ra tradeshop ui.");
var rates = _settings.TradeShopRates ??= new Trade.TradeShopRates();
SafeImGui.TextDisabled(rates.RatesHelpLine());
int n = _settings.TradeShopListings?.Count ?? 0;
SafeImGui.TextDisabled($"{n} catalog listing(s).");
}
private static bool IsValidRegex(string pattern)
{
try { _ = System.Text.RegularExpressions.Regex.Match(string.Empty, pattern); return true; }
catch { return false; }
}
/// <summary>One cell of the Protections and Banes grid: ticked = cast it.</summary>
private void BuffToggle((string Buff, string Label) toggle)
{
bool on = !_settings.IsBuffDisabled(toggle.Buff);
if (ImGui.Checkbox($"{toggle.Label}##buff_{toggle.Buff}", ref on))
_settings.SetBuffEnabled(toggle.Buff, on);
}
/// <summary>
/// One loot timer: the input, then "baseline" when it matches LootBaseline, or "baseline N" when
/// it doesn't (hover for what the timer does).
@ -259,12 +294,12 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.SetNextItemWidth(120);
ImGui.InputInt(label, ref value);
if (ImGui.IsItemHovered())
SafeImGui.SetTooltip(tip);
ImGui.SetTooltip(tip);
ImGui.SameLine();
if (value == baseline)
ImGui.TextDisabled("baseline");
else
SafeImGui.TextColored(new Vector4(0.9f, 0.7f, 0.2f, 1.0f), $"baseline {baseline}");
ImGui.TextColored(new Vector4(0.9f, 0.7f, 0.2f, 1.0f), $"baseline {baseline}");
}
/// <summary>Writes the six loot timers' baseline values (LootBaseline.cs) into the settings.</summary>
@ -1043,6 +1078,14 @@ internal sealed class LegacyAdvancedSettingsUi
string skipped = _buffSkips?.Invoke() ?? "";
if (_settings.SkipUnusableBuffs && skipped.Length > 0)
SafeImGui.TextWrapped("Skipping: " + skipped);
ImGui.Checkbox("Use fellowship buffs in a fellowship", ref _settings.UseFellowshipBuffs);
if (ImGui.IsItemHovered())
ImGui.SetTooltip(
"While you're in a fellowship, cast the fellowship version of a buff where one exists\n" +
"(Empowering the Conclave for Strength, the Clutch defenses, the Chants, the Wards,\n" +
"the Winds): it replaces your own buff and buffs every member too. The highest level\n" +
"your skill allows that you know and can cast; otherwise the self buff.\n" +
"Off by default. Solo, it never applies. Works with buff profiles too.");
ImGui.Spacing();
if (ImGui.Button("Force Buff##forceBuff") && _forceBuff != null) _forceBuff();
@ -1054,34 +1097,13 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.SameLine();
if (ImGui.Button("Cancel##cancelBuff") && _cancelBuff != null) _cancelBuff();
// Protections and Banes grid removed: spell buff profiles (Spells window) own
// which prots/banes to cast. DisabledBuffs still loads for old profiles.
ImGui.Spacing();
ImGui.Separator();
ImGui.Text("Protections and Banes");
if (ImGui.IsItemHovered())
ImGui.SetTooltip(
"Untick a protection or bane to stop the bot casting it.\n" +
"Unticked buffs are skipped and never hold the bot in Buffing.\n" +
"All on by default.");
if (ImGui.BeginTable("##protsBanes", 2, ImGuiTableFlags.SizingStretchSame))
{
ImGui.TableSetupColumn("Protections");
ImGui.TableSetupColumn("Banes");
ImGui.TableHeadersRow();
int rows = Math.Max(BuffManager.ToggleProtections.Length, BuffManager.ToggleBanes.Length);
for (int i = 0; i < rows; i++)
{
ImGui.TableNextRow();
ImGui.TableSetColumnIndex(0);
if (i < BuffManager.ToggleProtections.Length) BuffToggle(BuffManager.ToggleProtections[i]);
ImGui.TableSetColumnIndex(1);
if (i < BuffManager.ToggleBanes.Length) BuffToggle(BuffManager.ToggleBanes[i]);
}
ImGui.EndTable();
}
ImGui.Checkbox("Buff the shield", ref _settings.BuffShield);
if (ImGui.IsItemHovered())
ImGui.SetTooltip(
"Cast the ticked Impenetrability and Banes on your shield too, after\n" +
"Cast the Impenetrability and Banes your buff profile casts on your shield too, after\n" +
"the armor, renewed with it. The shield is the one in the Items list\n" +
"(Shield) that you wear: buffing puts it in a pack for the wand, so it\n" +
"is buffed there. On by default. No shield listed: nothing changes.");

View file

@ -332,6 +332,8 @@ internal sealed partial class LegacyDashboardRenderer
public void SetAutoVendorStatusProvider(Func<string> status) => _advancedSettingsUi.SetAutoVendorStatusProvider(status);
public void SetBuffActions(Action? force, Action? cancel, Func<string>? skips) => _advancedSettingsUi.SetBuffActions(force, cancel, skips);
public void SetAutoTradeStatusProvider(Func<string> status) => _advancedSettingsUi.SetAutoTradeStatusProvider(status);
public void SetTradeShopStatusProvider(Func<string> status) => _advancedSettingsUi.SetTradeShopStatusProvider(status);
public void SetTradeShopBankingProvider(Func<bool> banking) => _advancedSettingsUi.SetTradeShopBankingProvider(banking);
// The open vendor's AutoVendor profile path (null when no vendor is open), for the
// dashboard snapshot's vendorProfilePath.
@ -1482,6 +1484,7 @@ internal sealed partial class LegacyDashboardRenderer
RebuffIdleMarginMinutes = s.RebuffIdleMarginMinutes,
CastBuffsOverItemBuffs = s.CastBuffsOverItemBuffs,
SkipUnusableBuffs = s.SkipUnusableBuffs,
UseFellowshipBuffs = s.UseFellowshipBuffs,
DisabledBuffs = new List<string>(s.DisabledBuffs),
BlockedBuffItems = new List<string>(s.BlockedBuffItems),
CustomBuffItems = s.CustomBuffItems.ConvertAll(c => c.Copy()),
@ -1779,6 +1782,7 @@ internal sealed partial class LegacyDashboardRenderer
if (p.RebuffIdleMarginMinutes is int idleMargin) s.RebuffIdleMarginMinutes = Math.Max(0, idleMargin); // absent = unchanged
if (p.CastBuffsOverItemBuffs is bool castOverItems) s.CastBuffsOverItemBuffs = castOverItems; // absent = unchanged
if (p.SkipUnusableBuffs is bool skipUnusable) s.SkipUnusableBuffs = skipUnusable; // absent = unchanged
if (p.UseFellowshipBuffs is bool fellowBuffs) s.UseFellowshipBuffs = fellowBuffs; // absent = unchanged
if (p.DisabledBuffs is { } disabledBuffs) s.DisabledBuffs = new List<string>(disabledBuffs); // absent = unchanged
if (p.BlockedBuffItems is { } blockedItems) s.BlockedBuffItems = new List<string>(blockedItems); // absent = unchanged
if (p.CustomBuffItems is { } customItems) s.CustomBuffItems = customItems.FindAll(c => c != null); // absent = unchanged
@ -1903,6 +1907,7 @@ internal sealed partial class LegacyDashboardRenderer
}
public void AddSelectedWeapon() { _weaponsUi.AddSelectedWeapon(); SaveSettings(); }
public void AddWeapon(uint id) { _weaponsUi.AddWeapon(id); SaveSettings(); }
public void AddSelectedConsumable() { _weaponsUi.AddSelectedConsumable(); SaveSettings(); }
/// <summary>Launches the standalone Monster Rules editor for the current char folder.</summary>
@ -2306,6 +2311,7 @@ internal sealed partial class LegacyDashboardRenderer
dst.CastBuffsOverItemBuffs = tmp.CastBuffsOverItemBuffs;
dst.FastBuffChain = tmp.FastBuffChain;
dst.SkipUnusableBuffs = tmp.SkipUnusableBuffs;
dst.UseFellowshipBuffs = tmp.UseFellowshipBuffs;
dst.DisabledBuffs = tmp.DisabledBuffs;
dst.BlockedBuffItems = tmp.BlockedBuffItems;
dst.CustomBuffItems = tmp.CustomBuffItems.FindAll(c => c != null && !string.IsNullOrWhiteSpace(c.Name));
@ -2421,6 +2427,17 @@ internal sealed partial class LegacyDashboardRenderer
dst.AutoTradeOnlyFromMainPack = tmp.AutoTradeOnlyFromMainPack;
dst.AutoTradeAutoAccept = tmp.AutoTradeAutoAccept;
dst.AutoTradeAutoAcceptChars = tmp.AutoTradeAutoAcceptChars ?? new();
dst.TradeShopEnabled = tmp.TradeShopEnabled;
dst.TradeShopTestMode = tmp.TradeShopTestMode;
dst.TradeShopMode = tmp.TradeShopMode;
dst.TradeShopListings = tmp.TradeShopListings ?? new();
dst.TradeShopRates = tmp.TradeShopRates ?? new();
dst.TradeShopBankingHook = tmp.TradeShopBankingHook;
dst.ShowTradeShopWindow = tmp.ShowTradeShopWindow;
dst.TradeShopAdvertiseEnabled = tmp.TradeShopAdvertiseEnabled;
dst.TradeShopAdvertiseChannel = tmp.TradeShopAdvertiseChannel;
dst.TradeShopAdvertiseIntervalSec = tmp.TradeShopAdvertiseIntervalSec;
dst.TradeShopAdvertisePrefix = tmp.TradeShopAdvertisePrefix ?? "";
dst.MetaDebug = tmp.MetaDebug;
dst.AllowMetaKeystrokes = tmp.AllowMetaKeystrokes;
dst.StartMacroOnLogin = tmp.StartMacroOnLogin;
@ -2756,6 +2773,9 @@ internal sealed partial class LegacyDashboardRenderer
SaveSettings();
}
/// <summary>Reload the settings-profile name list (after VTank import writes new *.json profiles).</summary>
public void RefreshSettingsProfileList() => RefreshProfilesList();
private void RefreshProfilesList()
{
var list = new List<string> { "Default" };

View file

@ -14,6 +14,9 @@ namespace RynthCore.Plugin.RynthAi.LegacyUi;
/// </summary>
internal sealed class LegacyItemInfoUi
{
// Where the player left the window, per character (Plugins/Shared/SavedWindow.cs).
private readonly SavedWindow _spot = new("RynthAi.ItemInfo");
private readonly LegacyUiSettings _settings;
// Supplied by RynthAiPlugin (it owns the host + object cache).
@ -47,8 +50,10 @@ internal sealed class LegacyItemInfoUi
if (!s.ShowWindow) return;
ImGui.SetNextWindowSize(new Vector2(560, 600), ImGuiCond.FirstUseEver);
_spot.Apply();
if (ImGui.Begin("RynthAi Item Info##ItemInfoSettings", ref s.ShowWindow))
{
_spot.Track();
RenderPreview(s);
RenderWhen(s);
RenderFields(s);

View file

@ -12,6 +12,11 @@ namespace RynthCore.Plugin.RynthAi.LegacyUi;
internal sealed class LegacyMetaUi
{
// Where the player left the window, per character (Plugins/Shared/SavedWindow.cs).
private readonly SavedWindow _rulesSpot = new("RynthAi.MacroRules");
private readonly SavedWindow _editorSpot = new("RynthAi.EditMetaRule");
private readonly SavedWindow _exprSpot = new("RynthAi.ExpressionEditor");
private readonly LegacyUiSettings _settings;
private readonly List<string> _navFiles;
@ -95,11 +100,15 @@ internal sealed class LegacyMetaUi
try
{
ImGui.SetNextWindowSize(new Vector2(600, 460), ImGuiCond.FirstUseEver);
_rulesSpot.Apply();
bool windowOpen = ImGui.Begin("Macro Rules##RynthAiMacroRules", ref DashWindows.ShowMacroRules);
try
{
if (windowOpen)
{
_rulesSpot.Track();
RenderContents();
}
}
catch (Exception ex)
{
@ -491,11 +500,13 @@ internal sealed class LegacyMetaUi
// imgui.ini. ImGuiCond.Appearing was forcing the size every time the
// popup re-opened, throwing away the user's resize.
ImGui.SetNextWindowSize(new Vector2(650, 450), ImGuiCond.FirstUseEver);
_editorSpot.Apply();
if (!ImGui.Begin("Edit Meta Rule##RynthAiEditor", ref _showMetaEditor, ImGuiWindowFlags.NoCollapse))
{
ImGui.End();
return;
}
_editorSpot.Track();
float halfWidth = ImGui.GetContentRegionAvail().X / 2f - 4f;
@ -972,8 +983,10 @@ internal sealed class LegacyMetaUi
ImGui.SetNextWindowSize(new Vector2(720, 380), ImGuiCond.FirstUseEver);
if (_exprPopupRequestFocus)
ImGui.SetNextWindowFocus();
_exprSpot.Apply();
if (ImGui.Begin($"Expression Editor - {_exprPopupTitle}##ExpressionPopup", ref _exprPopupOpen))
{
_exprSpot.Track();
ImGui.TextDisabled("Edit the expression here. Apply writes it back to the rule.");
ImGui.Separator();

View file

@ -9,6 +9,9 @@ namespace RynthCore.Plugin.RynthAi.LegacyUi;
internal sealed class LegacyNavigationUi
{
// Where the player left the window, per character (Plugins/Shared/SavedWindow.cs).
private readonly SavedWindow _spot = new("RynthAi.Navigation");
private readonly LegacyUiSettings _settings;
private readonly RynthCoreHost _host;
@ -31,11 +34,13 @@ internal sealed class LegacyNavigationUi
public void Render()
{
ImGui.SetNextWindowSize(new Vector2(400, 480), ImGuiCond.FirstUseEver);
_spot.Apply();
if (!ImGui.Begin("Navigation##RynthAiNav", ref DashWindows.ShowNavigation))
{
ImGui.End();
return;
}
_spot.Track();
string activeNavName = string.IsNullOrEmpty(_settings.CurrentNavPath) ? "None (Unsaved)" : Path.GetFileName(_settings.CurrentNavPath);
SafeImGui.TextColored(new Vector4(1, 1, 0, 1), $"Active Nav: {activeNavName}");

View file

@ -20,6 +20,9 @@ namespace RynthCore.Plugin.RynthAi.LegacyUi;
internal sealed unsafe partial class LegacySpellsUi
{
// Where the player left the window, per character (Plugins/Shared/SavedWindow.cs).
private readonly SavedWindow _spot = new("RynthAi.Spells");
private const string WindowTitle = "RynthAi Spells##RynthAiSpells";
private const string ConfirmPopupId = "Confirm##rynthaispells";
@ -124,9 +127,11 @@ internal sealed unsafe partial class LegacySpellsUi
UiPlacement.CenterFirstUse(new Vector2(40, 40));
ImGui.SetNextWindowSize(new Vector2(1140, 660), ImGuiCond.FirstUseEver);
_spot.Apply();
if (ImGui.Begin(WindowTitle, ref _settings.ShowSpellsWindow))
{
UiPlacement.RescueOncePerShow(ref _rescueChecked);
_spot.Track();
RenderBody();
}
ImGui.End();

View file

@ -523,6 +523,15 @@ public sealed class LegacyUiSettings
/// </summary>
public bool SkipUnusableBuffs = true;
/// <summary>
/// While in a fellowship, a buff with a fellowship version (Empowering the Conclave for
/// Strength, the Clutch defenses, the Chants, the Wards, the Winds) casts that one instead: the
/// same family, so it replaces the self buff on you and buffs every member too. Same rules as
/// any buff: the highest level the skill allows that the character knows and the server hasn't
/// refused for components; without a usable fellowship level the self buff is cast. Off by
/// default; solo it never applies.
/// </summary>
public bool UseFellowshipBuffs;
/// <summary>
/// Buff base names the player unticked in Buffing settings (the Protections and Banes grid,
/// e.g. "Fire Protection Self", "Flame Bane"): left out of the buff list, so never cast and
/// never waited on. Empty = every buff on, which is also what a profile saved before this
@ -874,6 +883,35 @@ public sealed class LegacyUiSettings
/// The autoAcceptList.json files (/ub autotrade autoaccept ...) are read as well.</summary>
public List<string> AutoTradeAutoAcceptChars { get; set; } = new();
// ── Trade Shop (priced catalog + payment→complete; Mode 1 stock / Mode 2 text) ──
// Ungated: available on every world. Banking hook only applies when the server supports payments.
/// <summary>Sell from the Trade Shop catalog when a trade opens (separate from UB AutoTrade).</summary>
public bool TradeShopEnabled = false;
/// <summary>Only log what the shop would do (no TradeAdd / TradeAccept).</summary>
public bool TradeShopTestMode = false;
/// <summary>Mode1Stock = items on this character; Mode2TextMultiAccount = text listings only.</summary>
public RynthCore.Plugin.RynthAi.Trade.TradeShopMode TradeShopMode = RynthCore.Plugin.RynthAi.Trade.TradeShopMode.Mode1Stock;
/// <summary>Priced listings (add selected / typed). Payment on the partner's trade side completes the sale.</summary>
public List<RynthCore.Plugin.RynthAi.Trade.TradeShopListing> TradeShopListings { get; set; } = new();
/// <summary>UB-IT conversion rates (Py/MMD + EC table) and accepted payment currencies.</summary>
public RynthCore.Plugin.RynthAi.Trade.TradeShopRates TradeShopRates { get; set; } = new();
/// <summary>
/// When the server supports banking payments (ILT hub on this world), log / use the banking hook
/// after Mode 2 sales. Ignored when banking is unavailable.
/// </summary>
public bool TradeShopBankingHook = false;
/// <summary>Trade Shop editor window (Inventory Storefront button / /ra tradeshop ui).</summary>
public bool ShowTradeShopWindow = false;
/// <summary>Periodically post the catalog into an AC chat window.</summary>
public bool TradeShopAdvertiseEnabled = false;
/// <summary>Which chat window receives auto-advertise (Trade / General / LFG / …).</summary>
public RynthCore.Plugin.RynthAi.Trade.TradeShopAdvertiseChannel TradeShopAdvertiseChannel
= RynthCore.Plugin.RynthAi.Trade.TradeShopAdvertiseChannel.Trade;
/// <summary>Seconds between advertise blasts (clamped 30–3600).</summary>
public int TradeShopAdvertiseIntervalSec = 180;
/// <summary>Optional prefix text on each advertise line (e.g. "WTS — ").</summary>
public string TradeShopAdvertisePrefix = "";
public List<MonsterRule> MonsterRules { get; set; } = new();
public List<ItemRule> ItemRules { get; set; } = new();
/// <summary>Loose ammo the monster rules can prefer. Edited by the local monsters window.</summary>
@ -1541,6 +1579,7 @@ public sealed class SettingsBridgePayload
// Settings face must leave the setting alone rather than force it either way.
public bool? CastBuffsOverItemBuffs { get; set; }
public bool? SkipUnusableBuffs { get; set; }
public bool? UseFellowshipBuffs { get; set; }
// Null (absent) likewise leaves the unticked prots/banes alone; an empty list ticks them all.
public List<string>? DisabledBuffs { get; set; }
// The Buff Items lists (RynthAi's Spells window draws them; the engine's face has no rows for

View file

@ -32,6 +32,17 @@ internal sealed class LegacyWeaponsUi
_host.WriteToChat("[RynthAi] No item selected — click a weapon in your inventory first.", 1);
return;
}
AddWeapon(selId);
}
/// <summary>
/// Adds the weapon, wand or shield <paramref name="selId"/> to the Items list (the weapons the
/// Damage panel and combat may use): Add Selected, and the Inventory panel's right-click
/// "Add to Damage panel weapons" (RynthPluginAddWeaponById, 2026-10-25). Says in chat what it did.
/// </summary>
public void AddWeapon(uint selId)
{
if (selId == 0) return;
if (_worldFilter == null) { _host.WriteToChat("[RynthAi] Object cache not ready.", 1); return; }
var wo = _worldFilter[(int)selId];

View file

@ -23,7 +23,10 @@ internal sealed class RynthRadarUi
// resolution). Cleared whenever the player transitions landblocks, so
// re-entering a dungeon resets the coloring.
private const float GridCell = 0.5f;
private readonly System.Collections.Generic.HashSet<(int gx, int gy)> _visitedCells = new();
// Keyed by the floor (layer Z) as well (2026-11-11, Silentkelpie: the dungeon map's trail "isn't tracking the z
// coords elevation level changes and overlaps"): walking one floor painted the same spot on the floors above and
// below it. Each floor now has its own painted cells.
private readonly System.Collections.Generic.HashSet<(float z, int gx, int gy)> _visitedCells = new();
private uint _visitedLandblock;
// Visited cells merged into strips — rebuilt only when _visitedCells grows.
private System.Collections.Generic.Dictionary<float, System.Collections.Generic.List<(float x0, float y0, float x1, float y1)>>? _visitedFillStrips;
@ -85,18 +88,39 @@ internal sealed class RynthRadarUi
var map = _mapData;
if (map?._floorCells is null || map._cachedLandblock != landblock || _visitedLandblock != landblock) return null;
int total = 0, seen = 0;
foreach (var (_, cells) in map._floorCells)
foreach (var (layerZ, cells) in map._floorCells)
foreach (var ((gx, gy), ctype) in cells)
{
if (ctype != DungeonMapUi.CellType.Flat) continue;
total++;
if (_visitedCells.Contains((gx, gy))) seen++;
if (_visitedCells.Contains((layerZ, gx, gy))) seen++;
}
return total == 0 ? null : (double)seen / total;
}
// ── Visited strip cache ─────────────────────────────────────────────
/// <summary>
/// The floor (layer Z) under the player: of the floors that have floor at the player's grid cell, the one
/// nearest their Z (stacked floors share x/y); none has: the nearest by Z. Null without layers.
/// </summary>
internal static float? PlayerLayer(DungeonMapUi map, int gx, int gy, float z)
{
var layers = map._zLayers;
if (layers is not { Count: > 0 }) return null;
float? best = null, nearest = null;
float bestD = float.MaxValue, nearestD = float.MaxValue;
foreach (float lz in layers)
{
float d = MathF.Abs(lz - z);
if (d < nearestD) { nearestD = d; nearest = lz; }
if (map._floorCells != null && map._floorCells.TryGetValue(lz, out var cells) && cells.ContainsKey((gx, gy)) && d < bestD)
{ bestD = d; best = lz; }
}
// A floor more than a storey off isn't the one you're on (a cell above you shares your x/y).
return best is float b && bestD <= 6f ? b : nearest;
}
private void RebuildRadarVisitedStrips()
{
if (_mapData?._floorCells is null || _visitedCells.Count == 0 || _mapData._zLayers is null)
@ -111,7 +135,7 @@ internal sealed class RynthRadarUi
{
var flatVisited = new System.Collections.Generic.List<(int, int)>();
foreach (var ((gx, gy), ctype) in cells)
if (ctype == DungeonMapUi.CellType.Flat && _visitedCells.Contains((gx, gy)))
if (ctype == DungeonMapUi.CellType.Flat && _visitedCells.Contains((layerZ, gx, gy)))
flatVisited.Add((gx, gy));
if (flatVisited.Count == 0) continue;
var strips = DungeonMapUi.BuildVisitedStripsFrom(flatVisited);
@ -262,14 +286,21 @@ internal sealed class RynthRadarUi
_corpseKillers.Clear();
}
if (isIndoor)
if (isIndoor && _mapData != null)
{
_mapData.EnsureCache(landblock);
int pgx = (int)MathF.Floor(playerWX / GridCell);
int pgy = (int)MathF.Floor(playerWY / GridCell);
int r = Math.Clamp(_settings.RadarWallPaintRadius, 0, 40);
for (int oy = -r; oy <= r; oy++)
for (int ox = -r; ox <= r; ox++)
_visitedCells.Add((pgx + ox, pgy + oy));
// The floor you stand on: painted there only, and only where that floor has floor.
if (PlayerLayer(_mapData, pgx, pgy, pz) is float layerZ)
{
var floor = _mapData._floorCells != null && _mapData._floorCells.TryGetValue(layerZ, out var fc) ? fc : null;
int r = Math.Clamp(_settings.RadarWallPaintRadius, 0, 40);
for (int oy = -r; oy <= r; oy++)
for (int ox = -r; ox <= r; ox++)
if (floor == null || floor.ContainsKey((pgx + ox, pgy + oy)))
_visitedCells.Add((layerZ, pgx + ox, pgy + oy));
}
}
if (_visitedCells.Count != _lastVisitedCount && _mapData != null)

View file

@ -392,6 +392,9 @@ public sealed class InventoryManager
{
for (int si = parts.Count - 1; si > ti; si--)
{
// Server rejects merges that would overflow MaxStackSize.
if (parts[ti].Count + parts[si].Count > max)
continue;
string key = parts[ti].Item.Id + "_" + parts[si].Item.Id;
// Confirm-via-snapshot: a prior merge of this pair either consumed
// the source (id vanished from inv) or grew the target. Either =>

View file

@ -39,6 +39,18 @@ internal sealed class LootEditorBridge
private long _draftRevision;
private LootEditSession? _other;
// "Filter like this" (2026-10-24): the last result the state shows (either scope), and the
// Inventory panel's filter (its rule and last result). find_refresh judges the panel's items
// again with that rule, so it outlives the item it was made from; a Global Inventory find
// in between doesn't disturb it.
private LootEditItemFind? _find;
private VTankLootRule? _findRule;
private LootEditItemFind? _findMeta;
private long _findRevision;
/// <summary>The most items one find judges (a full character carries a few hundred).</summary>
private const int MaxFindCandidates = 4096;
/// <summary>RynthAi's item lookups for "Add to loot profile". Set once by the plugin.</summary>
public LootItemHooks Items { get; set; } = new();
@ -69,12 +81,27 @@ internal sealed class LootEditorBridge
if (_followInUse && !_session.IsDirty && inUse.Length > 0 && !LootEditSession.SamePath(inUse, _session.Path))
_session.Open(inUse);
}
CheckServer();
return unchecked((int)StateRevision);
}
}
// The session's revision plus the popup draft's: both only grow, so the sum moves when either does.
private long StateRevision => _session.Revision + _draftRevision;
// The session's revision plus the popup draft's and the filter's: all only grow, so the sum moves when any does.
private long StateRevision => _session.Revision + _draftRevision + _findRevision;
/// <summary>On Infinite Leaftide now (the server RynthCore says is active).</summary>
private bool Ilt => Items.IsIlt?.Invoke() ?? true;
private bool _lastIlt = true;
/// <summary>The server changed to or from Leaftide: the vocabulary is built again and the state's revision moves.</summary>
private void CheckServer()
{
bool ilt = Ilt;
if (ilt == _lastIlt) return;
_lastIlt = ilt;
_vocabJson = null;
_draftRevision++;
}
public string StateJson()
{
@ -84,7 +111,9 @@ internal sealed class LootEditorBridge
if (!_session.IsOpen && _followInUse && inUse.Length > 0) _session.Open(inUse);
LootEditState state = _session.BuildState(inUse, ListFiles());
state.Revision = StateRevision;
state.Ilt = Ilt;
state.ItemDraft = _draft;
state.ItemFind = _find;
return JsonSerializer.Serialize(state, LootEditJsonContext.Default.LootEditState);
}
}
@ -98,8 +127,15 @@ internal sealed class LootEditorBridge
}
}
public string VocabJson() =>
_vocabJson ??= JsonSerializer.Serialize(LootRuleText.BuildVocab(), LootEditJsonContext.Default.LootEditVocab);
public string VocabJson()
{
if (_vocabJson != null) return _vocabJson;
// Kept once the spell table is in (the popups' spell lists come with it).
LootSpellCatalog? spells = Items.Spells();
string json = JsonSerializer.Serialize(LootRuleText.BuildVocab(spells, Ilt), LootEditJsonContext.Default.LootEditVocab);
if (spells != null) _vocabJson = json;
return json;
}
public void Command(string json)
{
@ -110,6 +146,11 @@ internal sealed class LootEditorBridge
ItemCommand(cmd);
return;
}
if (cmd.Op is "item_find" or "find_refresh" or "find_close")
{
FindCommand(cmd);
return;
}
string? saved = null;
lock (_sync)
{
@ -204,6 +245,17 @@ internal sealed class LootEditorBridge
private LootEditItemDraft BuildDraft(LootEditItemRequest req, bool add)
{
var d = new LootEditItemDraft { Seq = req.Seq };
if (req.Find && req.Blank)
{
// The panel's own filter: every attribute, no item.
d.Find = true;
d.AttributesSupported = true;
d.ItemName = "any item";
BuildFindRule(d, null, req, LootItemMatch.Like);
d.Ok = true;
return d;
}
if (req.Blank) return BuildBlankRuleDraft(d, req, add);
uint id = req.ItemId != 0 ? req.ItemId : Items.SelectedItemId();
if (id == 0) return Refuse(d, "No item selected. Click an item first.");
d.ItemId = id;
@ -217,6 +269,14 @@ internal sealed class LootEditorBridge
d.ItemName = facts.Name;
d.ClassName = LootItemRules.ClassName(facts.ObjectClass);
d.Stackable = facts.Stackable;
if (req.Find)
{
// A filter: the checklist and the conditions in words; no profile, action or place.
d.Find = true;
if (BuildFindRule(d, facts, req, match) == null) return d;
d.Ok = true;
return d;
}
d.BuiltInReason = BuiltInSentence(Items.BuiltInKeep(id));
string inUse = InUse;
@ -239,6 +299,9 @@ internal sealed class LootEditorBridge
RuleName = req.RuleName,
IncludeT11 = req.IncludeT11,
Choices = req.Choices,
Extras = req.Extras,
Spells = Items.Spells(),
Ilt = Ilt,
};
LootItemRuleDraft? draft = LootItemRules.Build(facts, options, out string error);
if (draft == null) return Refuse(d, error);
@ -296,6 +359,281 @@ internal sealed class LootEditorBridge
return d;
}
/// <summary>
/// The Loot Editor's Add rule (2026-11-07, Silentkelpie: "standardize the loot editor add rule to follow
/// the same logic used to filter for inventory"): the Inventory filter's blank checklist (every
/// attribute, spells and cantrips from the lists) with an action, a count and a name, added at the end
/// of the profile (no item to place it by). Under the lock.
/// </summary>
private LootEditItemDraft BuildBlankRuleDraft(LootEditItemDraft d, LootEditItemRequest req, bool add)
{
d.Blank = true;
d.AttributesSupported = true;
d.ItemName = "any item";
string inUse = InUse;
string target = req.ToOpenProfile && _session.IsOpen ? _session.Path : inUse;
if (target.Length == 0) return Refuse(d, "No loot profile selected. Pick one in RynthAi first.");
d.TargetPath = target;
d.TargetFile = Path.GetFileName(target);
d.TargetInUse = LootEditSession.SamePath(target, inUse);
if (!File.Exists(target)) return Refuse(d, $"Loot profile not found: {target}");
LootEditSession s = SessionFor(target);
if (!s.IsOpen || !LootEditSession.SamePath(s.Path, target)) return Refuse(d, s.Message);
d.Format = s.Format;
if (!s.CanInsert) return Refuse(d, $"{d.TargetFile} is read-only here: {s.ReadOnlyReason}");
// Editing a rule (2026-11-07): the checklist starts from its conditions; what no row can say is kept as written.
VTankLootRule? editing = null;
List<VTankLootCondition>? kept = null;
List<LootEditItemChoice>? choices = req.Choices;
if (req.EditIndex >= 0)
{
d.EditIndex = req.EditIndex;
if (!req.ToOpenProfile || !LootEditSession.SamePath(target, _session.Path))
return Refuse(d, "Open the profile in the Loot Editor to edit its rules.");
if (s.Format == "json") return Refuse(d, "Native-format rules are edited in the rule view (Start empty edits by hand).");
editing = s.UtlRule(req.EditIndex);
if (editing == null || (editing.Name ?? string.Empty) != req.EditName)
return Refuse(d, "That rule is no longer there. The list has been refreshed.");
List<VTankLootCondition> all = editing.Conditions;
List<LootEditItemChoice> fromRule = LootItemAttributes.ChoicesFromRule(LootItemAttributes.ForBlank(Ilt), all, out kept);
// The popup sends only the rows it changed: they go over the rule's own.
if (req.Choices != null)
foreach (LootEditItemChoice c in req.Choices)
{
fromRule.RemoveAll(x => x.Id == c.Id);
fromRule.Add(c);
}
choices = fromRule;
}
LootItemRuleDraft draft = LootItemRules.BuildBlank(new LootItemRuleOptions
{
Match = LootItemMatch.Like,
Action = req.Action != 0 ? (VTankLootAction)req.Action : editing?.Action,
KeepCount = req.KeepCount >= 0 ? req.KeepCount : editing?.KeepCount,
RuleName = req.RuleName.Length > 0 ? req.RuleName : editing?.Name,
BlankRule = true,
Ilt = Ilt,
Choices = choices,
Extras = req.Extras,
Spells = Items.Spells(),
KeepConditions = kept,
});
foreach (LootItemAttribute row in draft.Attributes) d.Attributes.Add(row.ToWire());
d.Match = (int)LootItemMatch.Like;
d.Action = (int)draft.Action;
d.KeepCount = draft.KeepCount;
d.RuleName = draft.Rule.Name;
d.DefaultRuleName = draft.DefaultName;
d.Preview = LootItemRules.PreviewLines(draft.Rule);
d.Notes.AddRange(draft.Notes);
bool any = draft.Rule.Conditions.Exists(c => c.NodeType != VTankNodeTypes.DisabledRule);
bool json = s.Format == "json";
LootRule? native = null;
if (json && any)
{
var dropped = new List<string>();
native = LootItemRules.ToNative(draft.Rule, dropped);
foreach (string c in dropped) d.Notes.Add($"Left out (the native format has no such condition): {c}");
if (native == null) return Refuse(d, "The native format can't hold any of this rule's conditions.");
}
int count = s.RuleCount;
d.InsertAt = editing != null ? req.EditIndex : count;
d.RuleCount = count;
d.OrderNote = editing != null
? $"Replaces rule {req.EditIndex + 1} of {count} in place (its place in the list stays)."
: $"Goes in at the end ({count + 1} of {count + 1}). Rules are checked top to bottom and the first match wins, "
+ "so it only gets items no rule above it takes; move it up the list to make it decide first.";
if (editing != null) d.DefaultRuleName = editing.Name ?? string.Empty;
if (!any) { d.Ok = false; return d; } // the note says to tick something
if (s.IsDirty) return Refuse(d, $"The Loot Editor has unsaved changes in {d.TargetFile}. Save or discard them first.");
d.Ok = true;
if (!add) return d;
if (editing != null)
{
if (!s.ReplaceAndSave(req.EditIndex, req.EditName, draft.Rule))
{
ReportWriteError(s);
return Refuse(d, s.Message);
}
d.Added = true;
d.Message = $"Saved loot rule '{draft.Rule.Name}' in {d.TargetFile}";
return d;
}
if (!s.InsertAndSave(draft.Rule, native, count))
{
ReportWriteError(s);
return Refuse(d, s.Message);
}
d.Added = true;
d.Message = $"Added loot rule '{draft.Rule.Name}' to {d.TargetFile}";
return d;
}
// =====================================================================
// Filter like this (the Inventory panel's right-click, 2026-10-24)
// =====================================================================
/// <summary>
/// The checklist's rule for a filter, into <paramref name="d"/> (rows, match, the conditions
/// as Preview, notes); null (and d's Error) when the item can't make one. Under the lock.
/// </summary>
private VTankLootRule? BuildFindRule(LootEditItemDraft d, LootItemFacts? facts, LootEditItemRequest req, LootItemMatch match)
{
var options = new LootItemRuleOptions
{
Match = match,
Action = VTankLootAction.Keep, // not used: a filter only has conditions
IncludeT11 = req.IncludeT11,
Choices = req.Choices,
Extras = req.Extras,
Spells = Items.Spells(),
Ilt = Ilt,
};
string error = string.Empty;
LootItemRuleDraft? draft = facts == null ? LootItemRules.BuildBlank(options) : LootItemRules.Build(facts, options, out error);
if (draft == null)
{
d.Ok = false;
d.Error = error;
return null;
}
foreach (LootItemAttribute row in draft.Attributes) d.Attributes.Add(row.ToWire());
d.Match = (int)draft.Match;
d.Action = (int)draft.Action;
d.Preview = FindLines(draft.Rule);
d.Notes.AddRange(draft.Notes);
d.RuleName = facts == null ? "attribute filter" : FindLabel(facts, draft.Match);
d.DefaultRuleName = d.RuleName;
return draft.Rule;
}
/// <summary>"like Gold Ring", "named Gold Ring", "Gold Ring (Jewelry)".</summary>
private static string FindLabel(LootItemFacts facts, LootItemMatch match)
{
string name = (facts.Name ?? string.Empty).Replace('\r', ' ').Replace('\n', ' ').Trim();
if (name.Length == 0) name = LootItemRules.ClassName(facts.ObjectClass);
return match switch
{
LootItemMatch.Like => "like " + name,
LootItemMatch.Name => "named " + name,
_ => name + " (" + LootItemRules.ClassName(facts.ObjectClass) + ")",
};
}
/// <summary>The rule's conditions in words: "Where: Class is Jewelry", "and Workmanship >= 7".</summary>
private static List<string> FindLines(VTankLootRule rule)
{
var lines = new List<string>();
foreach (VTankLootCondition c in rule.Conditions)
{
if (c.NodeType == VTankNodeTypes.DisabledRule) continue;
lines.Add((lines.Count == 0 ? "Where: " : "and ") + LootRuleText.Condition(c));
}
if (lines.Count == 0) lines.Add("Where: (every item)");
return lines;
}
private void FindCommand(LootEditCommand cmd)
{
lock (_sync)
{
LootEditItemRequest req = cmd.Item ?? new LootEditItemRequest();
if (cmd.Op == "find_close")
{
if (_find == null && _findRule == null) return;
_find = null;
_findRule = null;
_findMeta = null;
_findRevision++;
return;
}
LootEditItemFind f;
if (cmd.Op == "find_refresh")
{
if (_findRule == null || _findMeta == null)
{
f = new LootEditItemFind { Seq = req.Seq, Scope = LootFindScopes.Inventory, Error = "The filter was lost (RynthAi reloaded). Right-click the item again." };
}
else
{
f = new LootEditItemFind
{
Seq = req.Seq, Ok = true, Scope = LootFindScopes.Inventory, ItemId = _findMeta.ItemId, ItemName = _findMeta.ItemName,
Label = _findMeta.Label, Lines = _findMeta.Lines, NeedsIdentify = _findMeta.NeedsIdentify,
};
Judge(f, _findRule, req.Candidates);
// Nothing new: leave the state alone (the engine re-reads every rule on a change).
if (ReferenceEquals(_find, _findMeta) && SameResult(f, _findMeta)) return;
_findMeta = f;
}
}
else
f = BuildFind(req);
_find = f;
_findRevision++;
}
}
/// <summary>item_find: the rule from the item and the checklist, then the panel's items judged, or the spec for Global Inventory.</summary>
private LootEditItemFind BuildFind(LootEditItemRequest req)
{
string scope = req.Scope == LootFindScopes.Global ? LootFindScopes.Global : LootFindScopes.Inventory;
var f = new LootEditItemFind { Seq = req.Seq, Scope = scope };
LootItemFacts? facts = null;
if (!req.Blank)
{
uint id = req.ItemId != 0 ? req.ItemId : Items.SelectedItemId();
if (id == 0) { f.Error = "No item selected. Click an item first."; return f; }
f.ItemId = id;
facts = Items.Facts(id, true, true);
if (facts == null) { f.Error = $"RynthAi doesn't know item 0x{id:X8} yet. Try again in a moment."; return f; }
f.ItemName = facts.Name;
}
var d = new LootEditItemDraft { Seq = req.Seq, Find = true };
var match = (LootItemMatch)Math.Clamp(req.Match, 0, 2);
VTankLootRule? rule = BuildFindRule(d, facts, req, match);
if (rule == null) { f.Error = d.Error; return f; }
f.Label = d.RuleName;
f.Lines = d.Preview;
f.NeedsIdentify = LootFactsMatcher.NeedsIdentify(rule.Conditions);
f.Ok = true;
if (scope == LootFindScopes.Global)
{
// Global Inventory keeps its own copy (the spec); the panel's filter stays as it is.
f.Spec = LootFindSpec.Encode(f.Label, rule.Conditions);
return f;
}
Judge(f, rule, req.Candidates);
_findRule = rule;
_findMeta = f;
return f;
}
/// <summary>The candidates the rule takes (Ids) and the ones it can't judge yet (Unknown).</summary>
private void Judge(LootEditItemFind f, VTankLootRule rule, List<uint>? candidates)
{
f.Ids = new List<uint>();
f.Unknown = new List<uint>();
if (candidates == null || candidates.Count == 0) return;
List<uint> list = candidates.Count > MaxFindCandidates ? candidates.GetRange(0, MaxFindCandidates) : candidates;
Items.Judge(rule, list, f.NeedsIdentify, f.Ids, f.Unknown);
f.Checked = list.Count;
}
private static bool SameResult(LootEditItemFind a, LootEditItemFind b) =>
a.Ok == b.Ok && a.Error == b.Error && a.Checked == b.Checked && Same(a.Ids, b.Ids) && Same(a.Unknown, b.Unknown);
private static bool Same(List<uint> a, List<uint> b)
{
if (a.Count != b.Count) return false;
for (int i = 0; i < a.Count; i++) if (a[i] != b[i]) return false;
return true;
}
/// <summary>
/// A save the disk refused (folder not writable, file in use, ...): the editor shows the
/// session's message; this adds the chat line (once per folder) and the log line with the
@ -381,6 +719,11 @@ internal sealed class LootItemHooks
/// <summary>The item selected in the game, or 0.</summary>
public Func<uint> SelectedItemId { get; set; } = () => 0;
/// <summary>
/// RynthCore's active server is Infinite Leaftide (2026-11-07): the checklists offer the T11, weapon-card
/// and pet rows and the pickers the ACECustom keys only there. Null: treated as Leaftide.
/// </summary>
public Func<bool>? IsIlt { get; set; }
/// <summary>
/// The item's facts from the object cache, or null. The bools: "items like this" and
/// "include T11 attributes"; either asks for an ID when the item isn't identified.
/// </summary>
@ -396,6 +739,14 @@ internal sealed class LootItemHooks
/// (the looter's own classification, run as a preview), or null.
/// </summary>
public Func<uint, LootBuiltInKeep?> BuiltInKeep { get; set; } = _ => null;
/// <summary>
/// "Filter like this": judges the items (in order) with the rule as the looter would, adding
/// the ones it takes to the first list and, when the rule needs an identify (the bool), the
/// unidentified or unknown ones it doesn't take to the second.
/// </summary>
public Action<VTankLootRule, IReadOnlyList<uint>, bool, List<uint>, List<uint>> Judge { get; set; } = (_, _, _, _, _) => { };
/// <summary>The standard spell lists from RynthAi's spell table, or null until it is read.</summary>
public Func<LootSpellCatalog?> Spells { get; set; } = () => null;
}
/// <summary>

View file

@ -45,9 +45,17 @@ internal static class T11ItemSupport
public static bool HasT11Name(string? name)
=> !string.IsNullOrEmpty(name) && name.StartsWith(T11Catalog.NamePrefix, StringComparison.Ordinal);
/// <summary>The parsed T11 view of <paramref name="item"/> (<see cref="T11ItemInfo.None"/> for other items).</summary>
/// <summary>
/// On Infinite Leaftide (2026-11-07, "make sure all t11 attributes stuff is gated behind infinite leaftide"):
/// set from the active server once a second. Off it every item reads as not T11 (its virtual keys 0, no T11
/// info lines, no T11 checklist rows), whatever its text says.
/// </summary>
public static volatile bool Enabled = true;
/// <summary>The parsed T11 view of <paramref name="item"/> (<see cref="T11ItemInfo.None"/> for other items, and off Leaftide).</summary>
public static T11ItemInfo Get(WorldObject item)
{
if (!Enabled) return T11ItemInfo.None;
string name = item.Name.Length > 0 ? item.Name : item.Values(StringValueKey.Name, string.Empty);
string longDesc = item.Values(StringValueKey.LongDesc, string.Empty);
string use = item.Values(StringValueKey.Use, string.Empty);
@ -77,6 +85,16 @@ internal static class T11ItemSupport
{
try
{
// ACECustom's newer loot items (2026-11-11): by WCID (an item bounty by its description), Leaftide only.
if (key is T11Keys.ItemKind or T11Keys.ItemTier or T11Keys.InfusionCoins)
{
if (!Enabled) return 0;
uint wcid = unchecked((uint)item.Values(unchecked((int)WorldObjectCache.DecalTypeKey), 0));
if (key == T11Keys.InfusionCoins) return T11Items.CoinsOf(wcid);
string desc = item.Values(StringValueKey.LongDesc, string.Empty);
int kind = T11Items.KindOf(wcid, desc);
return key == T11Keys.ItemKind ? kind : T11Items.TierOf(kind, desc, item.Values(T11Items.PropEarnedGemTier, 0));
}
return T11Keys.TryGetValue(Get(item), key, Player, out int value) ? value : defaultValue;
}
catch

View file

@ -455,8 +455,8 @@ public static class VTankLootEvaluator
{
VTankNodeTypes.SpellNameMatch => MatchSpellNameMatch(itemId, ctx, d),
VTankNodeTypes.StringValueMatch => MatchStringValue(item, d),
VTankNodeTypes.LongValKeyLE => Long(d) is var (val,key) && item.Values((LongValueKey)key, 0) <= val,
VTankNodeTypes.LongValKeyGE => Long(d) is var (val,key) && item.Values((LongValueKey)key, 0) >= val,
VTankNodeTypes.LongValKeyLE => Long(d) is var (val,key) && LongOf(item, key) <= val,
VTankNodeTypes.LongValKeyGE => Long(d) is var (val,key) && LongOf(item, key) >= val,
// VTank compares double keys as floats: 1.2 + 0.09 must still be >= 1.29.
VTankNodeTypes.DoubleValKeyLE => Double(d) is var (val,key) && (float)item.Values(FloatKey(key), 0.0) <= (float)val,
VTankNodeTypes.DoubleValKeyGE => Double(d) is var (val,key) && (float)item.Values(FloatKey(key), 0.0) >= (float)val,
@ -465,9 +465,9 @@ public static class VTankLootEvaluator
VTankNodeTypes.SpellCountGE => ctx is null || ctx.GetItemSpellIds(itemId).Length >= ReadInt(d, 0),
VTankNodeTypes.SpellMatch => MatchSpellMatch(itemId, ctx, d),
VTankNodeTypes.MinDamageGE => MatchMinDamageGE(item, d),
VTankNodeTypes.LongValKeyFlagExists => Long(d) is var (flag,fkey) && (item.Values((LongValueKey)fkey, 0) & flag) != 0,
VTankNodeTypes.LongValKeyE => Long(d) is var (val,key) && item.Values((LongValueKey)key, 0) == val,
VTankNodeTypes.LongValKeyNE => Long(d) is var (val,key) && item.Values((LongValueKey)key, 0) != val,
VTankNodeTypes.LongValKeyFlagExists => Long(d) is var (flag,fkey) && (LongOf(item, fkey) & flag) != 0,
VTankNodeTypes.LongValKeyE => Long(d) is var (val,key) && LongOf(item, key) == val,
VTankNodeTypes.LongValKeyNE => Long(d) is var (val,key) && LongOf(item, key) != val,
VTankNodeTypes.AnySimilarColor => true, // needs portal.dat — optimistic
VTankNodeTypes.SimilarColorArmorType => true, // needs portal.dat — optimistic
VTankNodeTypes.SlotSimilarColor => true, // needs portal.dat — optimistic
@ -762,6 +762,21 @@ public static class VTankLootEvaluator
// (value, key) pair for the LongValKey* family.
private static (int Val, int Key) Long(IList<string> d) => (ReadInt(d, 0), ReadInt(d, 1));
/// <summary>ImbuedEffect and ImbuedEffect2..5 (ACE keeps a second imbue in 303-306).</summary>
internal static readonly int[] ImbueKeys = { 179, 303, 304, 305, 306 };
/// <summary>
/// A long key's value for a rule. ImbuedEffect (179) is every imbue the item has, ORed over 179 and
/// 303-306 as ACE's GetImbuedEffects does (2026-11-07): a "has" test then sees a second imbue too.
/// </summary>
private static int LongOf(WorldObject item, int key)
{
if (key != ImbueKeys[0]) return item.Values((LongValueKey)key, 0);
int v = 0;
foreach (int k in ImbueKeys) v |= item.Values((LongValueKey)k, 0);
return v;
}
private static (double Val, int Key) Double(IList<string> d) => (ReadDouble(d, 0), ReadInt(d, 1));
// Buffed long/double helpers store value as double in slot 0 (matching VTank's "Read" of doubles).
private static (double Val, int Key) DoubleKey(IList<string> d) => (ReadDouble(d, 0), ReadInt(d, 1));

View file

@ -297,6 +297,12 @@ public sealed partial class RynthAiPlugin
["autotrade.testmode"] = "AutoTradeTestMode",
["autotrade.think"] = "AutoTradeThink",
["autotrade.onlyfrommainpack"] = "AutoTradeOnlyFromMainPack",
["tradeshop.enabled"] = "TradeShopEnabled",
["tradeshop.testmode"] = "TradeShopTestMode",
["tradeshop.bankinghook"] = "TradeShopBankingHook",
["tradeshop.advertise"] = "TradeShopAdvertiseEnabled",
["tradeshop.advertise.interval"]= "TradeShopAdvertiseIntervalSec",
["tradeshop.advertise.prefix"] = "TradeShopAdvertisePrefix",
["autotrade.autoaccept"] = "AutoTradeAutoAccept",
};

View file

@ -3101,7 +3101,7 @@ internal sealed partial class ExpressionEngine
DateTime mtime = File.GetLastWriteTime(profilePath);
// Each pulse: fire MoveItemExternal for the first matching item still in inventory.
// Each pulse: give (whole object) the first matching item still in inventory.
// We retry the same item until it vanishes from the cache (server confirmed).
// Once gone, the next iteration naturally picks up the next item.
// Returns 1 while matching items remain, 0 when inventory is clear.
@ -3757,6 +3757,7 @@ internal sealed partial class ExpressionEngine
["CastBuffsOverItemBuffs"] = (() => B(s.CastBuffsOverItemBuffs), v => s.CastBuffsOverItemBuffs = ToDouble(v) != 0),
["FastBuffChain"] = (() => B(s.FastBuffChain), v => s.FastBuffChain = ToDouble(v) != 0),
["SkipUnusableBuffs"] = (() => B(s.SkipUnusableBuffs), v => s.SkipUnusableBuffs = ToDouble(v) != 0),
["UseFellowshipBuffs"] = (() => B(s.UseFellowshipBuffs), v => s.UseFellowshipBuffs = ToDouble(v) != 0),
["BuffShield"] = (() => B(s.BuffShield), v => s.BuffShield = ToDouble(v) != 0),
// AutoVendor (UB names map here through /ub opt: AutoVendor.Enabled -> AutoVendorEnabled, ...)
["AutoVendorEnabled"] = (() => B(s.AutoVendorEnabled), v => s.AutoVendorEnabled = ToDouble(v) != 0),

View file

@ -1609,7 +1609,9 @@ ITEM GIVING
actiontrygiveprofile[lootprofile, target]
Gives all inventory items matching Keep rules in the specified loot profile to a
nearby player or NPC named target.
nearby NPC or vendor named target, with AC's give action. Never to a player: a
shared meta must not be able to hand your inventory to someone's character.
To give to a player, type /ra ig <profile> to <player>.
Supports both VTank .utl profiles and native RynthAi .json profiles.
Profile files are loaded from:
@ -1621,10 +1623,13 @@ actiontrygiveprofile[lootprofile, target]
the target was not found in the nearby world, no items matched, or the profile
could not be loaded.
Param #0: lootprofile — filename (or full path) of the loot profile (.utl or .json).
Param #0: lootprofile — filename of the loot profile (.utl or .json), inside ItemGiver\
(a subfolder of it is fine). Full paths, drive letters, ':' and anything
that climbs out with ..\ are refused (logged once, returns "0").
Bare names without extension resolve as .utl from ItemGiver\.
Regex-escaped dots in UB examples (e.g. salvage\.utl) are just literal dots.
Param #1: target — exact name (case-insensitive) of the player or NPC to give to.
Param #1: target — exact name (case-insensitive) of the NPC or vendor to give to.
A player with that name is skipped.
Known limitations (TODO):
- Currently gives one item per meta pulse. Full rapid-fire batch transfer not yet
@ -1633,10 +1638,10 @@ actiontrygiveprofile[lootprofile, target]
all item types correctly (e.g. salvage ObjectClass known issue).
- Only .utl and .json profiles are supported; no fallback between profile directories.
Test in chat: /ra mexec actiontrygiveprofile[salvage.utl,My Salvage Mule]
Example: actiontrygiveprofile[salvage.utl,My Salvage Mule]
Test in chat: /ra mexec actiontrygiveprofile[salvage.utl,Town Crier]
Example: actiontrygiveprofile[salvage.utl,Town Crier]
→ "1" if items were given (VTank profile)
Example: actiontrygiveprofile[mysalvage.json,My Salvage Mule]
Example: actiontrygiveprofile[mysalvage.json,Town Crier]
→ "1" if items were given (native JSON profile)

View file

@ -45,8 +45,12 @@ internal sealed class QuestTracker
// Matches lines produced by the AC /myquests command.
// Format: key - N solves (unixTimestamp)"description" maxSolves repeatSeconds
// Example: blankaug - 1 solves (1609459200)"Blank Aug" 1 0
// Infinite Leaftide (ACECustom) puts a space after the timestamp:
// templeattributefocuswait - 42 solves (1792844530) "TempleAttributeFocusWait" -1 571000
// Without "\s*" there the description, max solves and repeat time went unread, every flag had
// no cooldown and RynthILT's Guardian rows all said "Ready now" (2026-10-30).
private static readonly Regex QuestLineRegex = new Regex(
@"(?<key>\S+) \- (?<solves>\d+) solves \((?<completedOn>\d{0,11})\)""?((?<description>.*)"" (?<maxSolves>.*) (?<repeatTime>\d{0,11}))?.*$",
@"(?<key>\S+) \- (?<solves>\d+) solves \((?<completedOn>\d{0,11})\)\s*""?((?<description>.*)"" (?<maxSolves>-?\d+) (?<repeatTime>\d{0,11}))?.*$",
RegexOptions.Compiled);
private readonly RynthCoreHost _host;
@ -57,6 +61,10 @@ internal sealed class QuestTracker
private bool _quietRefresh;
private DateTime _lastLineTime;
private DateTime _refreshStarted;
private int _linesThisRefresh;
// Past this many lines a reply waits LongReplyQuietSec of silence before it counts as done.
private const int LongReplyLines = 500;
private const double LongReplyQuietSec = 5.0;
public bool IsRefreshing => _refreshing;
@ -112,6 +120,7 @@ internal sealed class QuestTracker
{
_refreshing = true;
_gotFirstQuest = false;
_linesThisRefresh = 0;
_lastLineTime = DateTime.UtcNow;
_refreshStarted = DateTime.UtcNow;
}
@ -123,7 +132,15 @@ internal sealed class QuestTracker
public bool OnChatLine(string text)
{
if (!_refreshing)
return false;
{
// A /myquests reply someone else asked for (RynthOracle polls every 10 minutes, the
// player types it): read it too, or the flags stay as they were at login and RynthILT's
// Guardian rows never move (2026-10-28). Never eaten here: the asker hides its own.
if (!QuestLineRegex.IsMatch(text))
return false;
ExpectReply();
_quietRefresh = false;
}
if (text.Contains("Quest list is empty"))
{
@ -153,6 +170,7 @@ internal sealed class QuestTracker
_gotFirstQuest = true;
_lastLineTime = DateTime.UtcNow;
_linesThisRefresh++;
var rec = new QuestRecord();
rec.Key = m.Groups["key"].Value.ToLowerInvariant();
@ -189,7 +207,10 @@ internal sealed class QuestTracker
var now = DateTime.UtcNow;
if (_gotFirstQuest)
{
if ((now - _lastLineTime).TotalSeconds >= 1.0)
// A long reply (15,000-25,000+ flags on ACECustom) reaches the client in pieces with
// pauses between them: wait longer once it is big, so one reply isn't ended mid-way.
double quietSec = _linesThisRefresh >= LongReplyLines ? LongReplyQuietSec : 1.0;
if ((now - _lastLineTime).TotalSeconds >= quietSec)
Finish($"{Count} flags", gotData: true);
}
else

View file

@ -0,0 +1,124 @@
// PetDamageTint.cs — damage-type colours and pet essence school picking, after UB-ILT.
//
// Palette: UB-ILT Lib\LeaftideDamageTypeVtColors.ForDamageTypeFlag (the Virindi Tank / Leaftide
// label colours its Items, Spell and Pets tabs share). The engine's Items panel uses the same
// values (RynthCore ImGui\Panels\DamageTypeColors.cs); keep the two tables in step.
// School picking: UB-ILT Lib\PetDamageTypeTintPolicy.PickFlag (v2.0.1119).
using System;
using System.Numerics;
namespace RynthCore.Plugin.RynthAi.MiniRemote;
/// <summary>ACE damage-type flags, colours per school, and the pet essence school pick.</summary>
internal static class PetDamageTint
{
public const uint Slash = 1, Pierce = 2, Bludgeon = 4, SlashPierce = 3, Cold = 8, Fire = 16,
Acid = 32, Lightning = 64, Nether = 1024;
/// <summary>Text colour when the school is unknown (white, as UB for an essence in the pack).</summary>
public static readonly Vector4 Unknown = new(0.95f, 0.95f, 0.95f, 1f);
// Combined masks are read in this order (UB DamageProbeOrder): elements before physical.
private static readonly uint[] ProbeOrder = { Nether, Lightning, Acid, Fire, Cold, Bludgeon, SlashPierce, Pierce, Slash };
/// <summary>Colour for a school name as RynthAi writes it (Slash, Pierce, Bludgeon, Fire, Cold, Lightning, Acid, Nether).</summary>
public static Vector4 ForName(string? school) => school switch
{
"Slash" or "Slashing" => Rgb(255, 180, 120),
"Pierce" or "Piercing" => Rgb(240, 200, 140),
"Bludgeon" or "Bludgeoning" => Rgb(220, 190, 140),
"Slash/Pierce" => Rgb(255, 160, 100),
"Cold" or "Frost" => Rgb(160, 210, 255),
"Fire" => Rgb(255, 130, 70),
"Acid" => Rgb(160, 255, 140),
"Lightning" or "Electric" or "Storm" => Rgb(255, 240, 120),
"Nether" => Rgb(200, 160, 255),
_ => Unknown,
};
/// <summary>School name for one flag (empty for 0 or an undefined value).</summary>
public static string Name(uint flag) => flag switch
{
Slash => "Slash",
Pierce => "Pierce",
Bludgeon => "Bludgeon",
SlashPierce => "Slash/Pierce",
Cold => "Cold",
Fire => "Fire",
Acid => "Acid",
Lightning => "Lightning",
Nether => "Nether",
_ => string.Empty,
};
/// <summary>
/// One school for a pet essence: the captured source's damage (ACE 9054), else the essence's
/// DamageType mask (45), else the name ("Fire Banshee Essence", "Incendiary Knight"). 0 = unknown.
/// ILT reuses 9054 as the min-summon-aug id on some builds, where 1/2/4 read as Slash/Pierce/
/// Bludgeon; an elemental name wins over such a physical-only property read.
/// </summary>
public static uint PickPetFlag(int capturedSourceDamageType, int damageTypeMask, string? displayName)
{
uint fromProps = PickFromProperties(capturedSourceDamageType, damageTypeMask);
uint fromName = InferFromName(displayName);
if (fromName != 0 && IsPhysicalOnly(fromProps)) return fromName;
return fromProps != 0 ? fromProps : fromName;
}
/// <summary>School from Mag-Tools essence names and ILT catalog adjectives (whole words only).</summary>
public static uint InferFromName(string? displayName)
{
if (string.IsNullOrWhiteSpace(displayName)) return 0;
string n = displayName.ToLowerInvariant();
if (HasAny(n, "nether")) return Nether;
if (HasAny(n, "lightning", "electric", "voltaic", "galvanic", "electrified", "shocked", "excited", "volt", "shock"))
return Lightning;
if (HasAny(n, "acid", "caustic", "corrosion", "blistered", "blistering", "corrosive")) return Acid;
if (HasAny(n, "fire", "flaming", "incendiary", "charred", "volcanic", "scorched", "pyre", "magma", "ember"))
return Fire;
if (HasAny(n, "frost", "glacial", "frozen", "frigid", "freezing", "arctic", "blizzard", "ice", "chill"))
return Cold;
if (HasAny(n, "bludgeon", "bludgeoning")) return Bludgeon;
if (HasAny(n, "slash", "slashing")) return Slash;
if (HasAny(n, "pierce", "piercing")) return Pierce;
return 0;
}
private static uint PickFromProperties(int captured, int mask)
{
if (IsDefined(captured)) return (uint)captured;
if (IsDefined(mask)) return (uint)mask;
if (mask <= 0) return 0;
uint m = unchecked((uint)mask);
foreach (uint v in ProbeOrder)
if ((m & v) == v) return v;
return 0;
}
private static bool IsDefined(int raw) => raw > 0 && Name(unchecked((uint)raw)).Length > 0;
private static bool IsPhysicalOnly(uint flag) => flag is Slash or Pierce or Bludgeon or SlashPierce;
private static bool HasAny(string haystack, params string[] tokens)
{
foreach (string t in tokens)
if (HasToken(haystack, t)) return true;
return false;
}
/// <summary>True when <paramref name="token"/> appears as a whole word ("ice" not in "Novice").</summary>
private static bool HasToken(string haystack, string token)
{
int i = 0;
while ((i = haystack.IndexOf(token, i, StringComparison.Ordinal)) >= 0)
{
int end = i + token.Length;
if ((i == 0 || !char.IsLetter(haystack[i - 1])) && (end >= haystack.Length || !char.IsLetter(haystack[end])))
return true;
i++;
}
return false;
}
private static Vector4 Rgb(int r, int g, int b) => new(r / 255f, g / 255f, b / 255f, 1f);
}

View file

@ -152,9 +152,9 @@ internal static class PetStatsReader
_ => string.Empty,
};
int dmg = inv.Int(wo, IntCapturedDamageType);
if (dmg <= 0) dmg = inv.Int(wo, IntDamageType);
s.DamageType = DamageTypeName(dmg);
// Most essences carry neither property; the name then gives the school (UB-ILT v2.0.1119).
s.DamageType = PetDamageTint.Name(PetDamageTint.PickPetFlag(
inv.Int(wo, IntCapturedDamageType), inv.Int(wo, IntDamageType), wo.Name));
// Gear ratings first (what Mag ItemInfo shows), else the base rating ids.
s.D = inv.Int(wo, IntGearDamage);
@ -290,20 +290,6 @@ internal static class PetStatsReader
return sb.Length > 0 ? "[" + sb + "]" : string.Empty;
}
/// <summary>Single AC DamageType flag → name (combined flags return empty).</summary>
private static string DamageTypeName(int flags) => flags switch
{
1 => "Slash",
2 => "Pierce",
4 => "Bludgeon",
8 => "Cold",
16 => "Fire",
32 => "Acid",
64 => "Lightning",
1024 => "Nether",
_ => string.Empty,
};
private static bool TryBool(RynthCoreHost host, uint id, uint stype, out bool v)
{
v = false;

View file

@ -93,6 +93,9 @@ internal sealed class NavBreadcrumbTracker
_lastNS = ns; _lastEW = ew; _lastZ = z;
if (teleported) _breakNext = true;
// A drop or a lift to another floor between two ticks (a pit, a jump down): the trail breaks there, so no
// line runs from one floor to the next (2026-11-11).
if (hadLast && !teleported && MathF.Abs(z - (float)preZ) > NavOverlayRenderer.TrailOtherFloorZ) _breakNext = true;
// While tracking is off, keep a break pending so the trail resumes as a new segment
// instead of joining across the untracked stretch.
@ -105,13 +108,18 @@ internal sealed class NavBreadcrumbTracker
// Breadcrumb trail
// ═══════════════════════════════════════════════════════════════════
/// <summary>A rise or drop of this much (world units) since the last crumb samples one, whatever the distance.</summary>
internal const float TrailRiseSample = 1.5f;
private void SampleCrumb(double ns, double ew, float z, NavOverlaySettings o)
{
if (_crumbs.Count > 0 && !_breakNext)
{
var last = _crumbs[^1];
double d = NavRouteEditing.DistanceYards(last.NS, last.EW, ns, ew);
if (d < o.BreadcrumbSpacingYards) return;
// Height counts too (2026-11-11): a ramp or stairs climbed in a short way is sampled, so the trail
// follows the floors' heights instead of cutting from one to the next.
if (d < o.BreadcrumbSpacingYards && MathF.Abs(z - last.Z) < TrailRiseSample) return;
_trailYards += d;
}
_crumbs.Add(new NavCrumb(ns, ew, z, _breakNext || _crumbs.Count == 0));

View file

@ -39,7 +39,7 @@ internal sealed class NavOverlayRenderer
}
/// <summary>Player frame shared by every pass (marker world frame: X=EW, Y=up, Z=NS).</summary>
private readonly record struct Frame(double NS, double EW, float Px, float Py, float Pz, float HeadingDeg);
private readonly record struct Frame(double NS, double EW, float Px, float Py, float Pz, float HeadingDeg, bool Indoor = false);
private bool TryGetFrame(out Frame f)
{
@ -51,7 +51,7 @@ internal sealed class NavOverlayRenderer
if ((cell >> 16) == 0) return false;
// Physics yaw (CCW from north) → compass heading (0 = north, clockwise), as NavigationEngine.
double yaw = 2.0 * Math.Atan2(qz, qw) * (180.0 / Math.PI);
f = new Frame(ns, ew, px, py, pz, (float)((-yaw + 720.0) % 360.0));
f = new Frame(ns, ew, px, py, pz, (float)((-yaw + 720.0) % 360.0), (cell & 0xFFFF) >= 0x100);
return true;
}
@ -103,6 +103,16 @@ internal sealed class NavOverlayRenderer
/// Newest-first walk of the trail within draw range, capped at <see cref="MaxTrailLines"/>;
/// no segment crosses a teleport break. <c>fade</c> is 1 for the newest segment.
/// </summary>
/// <summary>
/// Indoors, a trail segment this far above or below you (world units, about half a storey) is another floor's:
/// not drawn, since the overlay isn't hidden by floors and would lie over this one (2026-11-11).
/// </summary>
internal const float TrailOtherFloorZ = 3.0f;
/// <summary>The segment is on your floor (outdoors: always).</summary>
internal static bool TrailOnMyFloor(bool indoor, float playerZ, float az, float bz) =>
!indoor || (MathF.Abs(az - playerZ) <= TrailOtherFloorZ && MathF.Abs(bz - playerZ) <= TrailOtherFloorZ);
private void ForEachTrailSegment(in Frame f, NavOverlaySettings o, Action<Vector3, Vector3, float> draw)
{
NavCrumb[] trail = _trail.Trail;
@ -113,6 +123,7 @@ internal sealed class NavOverlayRenderer
{
NavCrumb b = trail[i], a = trail[i - 1];
if (b.SegmentStart) continue;
if (!TrailOnMyFloor(f.Indoor, f.Pz, a.Z, b.Z)) continue;
if (NavRouteEditing.DistanceYards(f.NS, f.EW, b.NS, b.EW) > o.BreadcrumbDrawRangeYards) continue;
float fade = o.BreadcrumbFade ? 1f - 0.8f * drawn / Math.Max(1, total) : 1f;
draw(ToWorld(f, a.NS, a.EW, a.Z + lift), ToWorld(f, b.NS, b.EW, b.Z + lift), fade);
@ -231,10 +242,14 @@ internal sealed class NavOverlayRenderer
}
}
// Where the player left the Nav HUD, per character (Plugins/Shared/SavedWindow.cs); it sizes itself.
private readonly SavedWindow _hudSpot = new("RynthAi.NavHud", trackSize: false);
private void RenderHud(in Frame f, NavOverlaySettings o)
{
ImGui.SetNextWindowPos(new Vector2(20, 220), ImGuiCond.FirstUseEver);
ImGui.SetNextWindowBgAlpha(0.65f);
_hudSpot.Apply();
if (!ImGui.Begin("Nav HUD##RynthAiNavHud", ref o.ShowHud,
ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoCollapse |
ImGuiWindowFlags.NoFocusOnAppearing | ImGuiWindowFlags.NoNav))
@ -242,6 +257,7 @@ internal sealed class NavOverlayRenderer
ImGui.End();
return;
}
_hudSpot.Track();
var route = _settings.CurrentRoute;
var pts = route.Points;

View file

@ -60,10 +60,19 @@ internal interface INavRecoveryPlanner
{
NavRecoveryPlan? TryPlan(NavPoint target, out string why);
NavAreaCheck CheckArea(uint playerCell, double tNs, double tEw, out string routeArea, out string playerArea);
/// <summary>
/// Outdoors: does the straight walk from (aNs, aEw) to (bNs, bEw) climb ground too steep to
/// walk (RynthVision's red slopes)? <paramref name="atYd"/> is how far along; false indoors
/// or when the landscape isn't loaded.
/// </summary>
bool CrossesSteepGround(double aNs, double aEw, double bNs, double bEw, out double atYd);
}
internal sealed class NavRecoveryPlanner : INavRecoveryPlanner
{
/// <summary>TryPlan's why when the waypoint is a level above or below with no walk to it.</summary>
internal const string OtherLevelWhy = "the waypoint is on another level, no walk leads there";
// A dungeon waypoint is always inside some cell; its distance to that cell's centre
// is at most about half the biggest room. Used to decide "this waypoint is in that
// cell graph" for both planning and the area check.
@ -181,10 +190,13 @@ internal sealed class NavRecoveryPlanner : INavRecoveryPlanner
applicable = true;
uint start = graph.ContainsKey(playerCell) ? playerCell : DungeonPathfinder.NearestCell(graph, pNs, pEw, pz);
if (start == 0) { why = "can't place you on the dungeon map"; return null; }
if (start == goal) { why = "already in the waypoint's room, the map has no way around"; return null; }
// The waypoint over or under you by a level (2026-11-08: a chase into a pit, 17 m down, and the route's
// waypoints up on the floor above): no walk gets there; NavigationEngine hands it on (WaypointOnOtherLevel).
bool otherLevel = Math.Abs(pz - tz) > DungeonPathfinder.LevelApartZ;
if (start == goal) { why = otherLevel ? OtherLevelWhy : "already in the waypoint's room, the map has no way around"; return null; }
var path = DungeonPathfinder.FindPath(start, goal, graph, _hazards());
if (path.Count < 2) { why = "no walkable way on the dungeon map"; return null; }
if (path.Count < 2) { why = otherLevel ? OtherLevelWhy : "no walkable way on the dungeon map"; return null; }
// The same points the dungeon patrol uses: an approach and an exit point centred on
// every narrow opening (flagged, so the engine goes through straight), rooms crossed
@ -250,6 +262,31 @@ internal sealed class NavRecoveryPlanner : INavRecoveryPlanner
return plan;
}
// ══════════════════════════════════════════════════════════════════════
// STEEP GROUND AHEAD (the red slope overlay's rule, on a straight leg)
// ══════════════════════════════════════════════════════════════════════
// Where the character stands and where the waypoint sits are not checked (either may sit
// on the edge of a slope), nor anything farther ahead than SteepLookaheadYd: the engine
// asks again as the character comes closer.
private const double SteepSkipStartYd = 0.5;
private const double SteepSkipEndYd = 2.0;
private const double SteepLookaheadYd = 150.0;
public bool CrossesSteepGround(double aNs, double aEw, double bNs, double bEw, out double atYd)
{
atYd = -1;
if (!_host.HasGetPlayerPose ||
!_host.TryGetPlayerPose(out uint cell, out _, out _, out _, out _, out _, out _, out _))
return false;
if (cell == 0 || (cell & 0xFFFF) >= 0x0100) return false; // indoors: the dungeon map's job
var geo = _raycast()?.GeometryLoader;
if (geo == null) return false;
atYd = NavSteepGround.FirstBlockedYd(NavToWorld(aEw), NavToWorld(aNs), NavToWorld(bEw), NavToWorld(bNs),
key => geo.GetLandblockData(key)?.HeightsZ, SteepSkipStartYd, SteepSkipEndYd, SteepLookaheadYd);
return atYd >= 0;
}
// ══════════════════════════════════════════════════════════════════════
// AREA CHECK (route in another dungeon / on the landscape)
// ══════════════════════════════════════════════════════════════════════

View file

@ -0,0 +1,96 @@
// ============================================================================
// NavSteepGround.cs — does a straight walk climb ground too steep to walk?
//
// The same rule that paints RynthVision's red slope overlay and keeps the
// RynthNav navmesh off those slopes: a landscape triangle whose normal Z is
// below ACE PhysicsGlobals.FloorZ (TerrainSampler.FloorZ, about 48°) can't be
// walked up. Each 24 m cell is split along the diagonal AC picks per cell
// (TerrainSampler.SwToNeCut), so the triangle under a point is the real one.
// Going down such a slope works in AC, so a leg that runs clearly downhill
// over it is not blocked; climbing it, or crossing it sideways, is.
//
// NavigationEngine asks this (through the recovery planner) before walking a
// route leg, so a straight run that would end against a red block is replaced
// by a RynthNav navmesh way round before the character gets stuck there.
// Pure functions over the landblocks' vertex heights: the tests drive them.
// ============================================================================
using System;
using RynthCore.TerrainData;
namespace RynthCore.Plugin.RynthAi;
internal static class NavSteepGround
{
/// <summary>Distance between samples along a leg, in yards (world units).</summary>
internal const double StepYd = 1.0;
private const double CellYd = 24.0;
private const double BlockYd = 192.0;
// A steep triangle is only passable going down it: the leg must head within 60° of
// straight downhill (its fall per yard at least half the triangle's steepest fall).
private const double DownhillShare = 0.5;
/// <summary>
/// Yards along the straight line (ax, ay) → (bx, by) (world units, east / north) to the
/// first spot where it climbs or crosses ground too steep to walk; -1 when it never does.
/// The first <paramref name="skipStartYd"/> and last <paramref name="skipEndYd"/> are not
/// checked (where the character and the waypoint stand), nor anything past
/// <paramref name="maxYd"/>. <paramref name="heights"/> gives a landblock's 9×9 vertex
/// heights (HeightsZ[ix, iy]) by landblock key (x &lt;&lt; 8 | y), or null when it isn't known.
/// </summary>
internal static double FirstBlockedYd(double ax, double ay, double bx, double by,
Func<uint, float[,]?> heights, double skipStartYd, double skipEndYd, double maxYd)
{
double dx = bx - ax, dy = by - ay;
double len = Math.Sqrt(dx * dx + dy * dy);
if (len < 1e-6) return -1;
double ux = dx / len, uy = dy / len;
double end = Math.Min(len - skipEndYd, maxYd);
uint lastKey = uint.MaxValue;
float[,]? grid = null;
for (double s = Math.Max(0, skipStartYd); s <= end; s += StepYd)
{
double x = ax + ux * s, y = ay + uy * s;
if (x < 0 || y < 0 || x >= 256 * BlockYd || y >= 256 * BlockYd) continue;
int lbX = (int)(x / BlockYd), lbY = (int)(y / BlockYd);
uint key = (uint)((lbX << 8) | lbY);
if (key != lastKey) { grid = heights(key); lastKey = key; }
if (grid == null || grid.GetLength(0) < 9 || grid.GetLength(1) < 9) continue;
if (BlocksAt(grid, key, x - lbX * BlockYd, y - lbY * BlockYd, ux, uy)) return s;
}
return -1;
}
/// <summary>
/// True when walking in direction (ux, uy) at landblock-local (lx, ly) is blocked: the
/// triangle there is too steep to walk and the direction doesn't run clearly downhill.
/// </summary>
internal static bool BlocksAt(float[,] h, uint landblockKey, double lx, double ly, double ux, double uy)
{
int cx = Math.Clamp((int)(lx / CellYd), 0, 7);
int cy = Math.Clamp((int)(ly / CellYd), 0, 7);
double fx = lx - cx * CellYd, fy = ly - cy * CellYd;
double h00 = h[cx, cy], h10 = h[cx + 1, cy], h01 = h[cx, cy + 1], h11 = h[cx + 1, cy + 1];
// The plane's rise per yard east (gx) and north (gy) on the triangle under the point,
// with the triangles TerrainSampler.GetTrianglePassability names for each split.
double gx, gy;
if (TerrainSampler.SwToNeCut(landblockKey, cx, cy))
{
if (fy <= fx) { gx = (h10 - h00) / CellYd; gy = (h11 - h10) / CellYd; } // SE half: SW, SE, NE
else { gx = (h11 - h01) / CellYd; gy = (h01 - h00) / CellYd; } // NW half: SW, NE, NW
}
else
{
if (fx + fy <= CellYd) { gx = (h10 - h00) / CellYd; gy = (h01 - h00) / CellYd; } // SW half: SW, SE, NW
else { gx = (h11 - h01) / CellYd; gy = (h11 - h10) / CellYd; } // NE half: SE, NE, NW
}
double slope = Math.Sqrt(gx * gx + gy * gy);
double normalZ = 1.0 / Math.Sqrt(1.0 + slope * slope);
if (normalZ >= TerrainSampler.FloorZ) return false;
double rise = gx * ux + gy * uy; // yards up per yard walked
return rise > -DownhillShare * slope;
}
}

View file

@ -181,6 +181,21 @@ internal sealed class NavigationEngine
private const int StuckSpotRepeat = 3; // stucks within StuckSpotYards: go straight to a detour
private const double StuckSpotYards = 5.0;
private const double DetourReplanMovedYd = 5.0; // moved this far while paused: plan again
// Backtrack (2026-11-08, "if navigation in the map gets stuck it should use backtrack to get unstuck"): the way
// just walked, kept as a short trail; a stuck spot the map has no way round is left by walking back along it
// (BacktrackYd), on the same level, once per spot, before the side-step escapes.
private readonly List<(double Ns, double Ew, float Z)> _trail = new();
private const double TrailStepYd = 1.5;
private const int TrailMax = 40;
private const double BacktrackYd = 8.0;
private double _backtrackSpotNs = double.NaN, _backtrackSpotEw = double.NaN;
/// <summary>
/// The waypoint is a level above or below with no walk to it (NavRecoveryPlanner.OtherLevelWhy): the route's owner
/// may plan again from here (the dungeon patrol and dunnav do). The argument is the waypoint's index.
/// </summary>
public Action<int>? WaypointOnOtherLevel;
private const int DetourMaxReplans = 3;
private const double DetourDoorCheckMs = 400.0;
private const double DetourDoorLookYd = 12.0; // look for doors this far along the next leg
@ -198,6 +213,10 @@ internal sealed class NavigationEngine
private INavRecoveryPlanner? _planner;
private Detour? _detour;
// Steep ground ahead (CheckSteepAhead): the waypoint and spot the leg was last checked from.
private const double SteepRecheckYards = 10.0;
private int _steepCheckIdx = -1;
private double _steepCheckNs, _steepCheckEw;
private int _detourAttempts; // detours tried (or failed to plan) for the current waypoint
private bool _detourGaveUpNotified;
private int _recoveryNumber;
@ -631,6 +650,7 @@ internal sealed class NavigationEngine
_firedRoute = null;
if (!TryGetPos(out double ns, out double ew)) return;
NoteTrail(ns, ew);
// Route recovery. The area hold comes first: when the waypoint is in another
// dungeon (or dungeon vs landscape) no detour or escape can reach it.
@ -640,6 +660,8 @@ internal sealed class NavigationEngine
if (_detour != null) { TickDetour(route, ns, ew); return; }
CheckOffTrack(route, idx, ns, ew);
if (_detour != null) return;
CheckSteepAhead(route, idx, pt, ns, ew);
if (_detour != null) return;
}
else if (_detour != null || _areaMismatch)
{
@ -662,8 +684,12 @@ internal sealed class NavigationEngine
}
_campHoldAnnounced = false;
// A dungeon waypoint a level above or below (a pit under it, a ledge over it) isn't reached by standing
// under or over it (2026-11-08: "arrived" at waypoints 17 m overhead from the bottom of a pit).
bool levelOk = !OnOtherLevel(pt);
// Arrival check
if (dist < ReachFor(pt))
if (levelOk && dist < ReachFor(pt))
{
_host.Log($"Nav: arrived at [{idx}] dist={dist:F1}yd → advancing");
_closestDist = double.MaxValue;
@ -681,7 +707,7 @@ internal sealed class NavigationEngine
// Went past it: the point is behind, close enough to the side. Counts as reached
// instead of turning round to walk back to it.
if (PassedThrough(pt, ns, ew))
if (levelOk && PassedThrough(pt, ns, ew))
{
_host.Log($"Nav: passed [{idx}] dist={dist:F1}yd → advancing");
_closestDist = double.MaxValue;
@ -693,7 +719,7 @@ internal sealed class NavigationEngine
// Closest-approach detection — prevents circling: within the sweep radius, then
// 0.3 yd farther out than the closest it came.
if (_closestDist < SweepFor(pt) && dist > _closestDist + 0.3)
if (levelOk && _closestDist < SweepFor(pt) && dist > _closestDist + 0.3)
{
_host.Log($"Nav: sweep-pass [{idx}] closest={_closestDist:F1} now={dist:F1}yd → advancing");
_closestDist = double.MaxValue;
@ -2504,6 +2530,9 @@ internal sealed class NavigationEngine
EndDetour("stuck on the detour", success: false);
else if (TryStuckDetour(route))
return;
// The map had no way round (or its way snagged too): walk back the way we came, then on again.
if (_stuckCount >= 2 && TryBacktrack(route))
return;
// Rungs 2+ need a heading we can command. Without TurnToHeading the only
// primitive we have is the jump, so stay on rung 1 rather than autorunning
@ -2852,6 +2881,27 @@ internal sealed class NavigationEngine
TryStartDetour(route, idx, $"off track, {off:F0}yd from the route for {OffTrackGraceMs / 1000:F0}s");
}
// ── Steep ground ahead ───────────────────────────────────────────────────
/// <summary>
/// Before the character runs into it: when the straight way to the waypoint climbs ground
/// too steep to walk (RynthVision's red slopes, on land or under water), walk a RynthNav
/// navmesh way round instead (a detour from the same budget as the stuck ones). Checked for
/// each new waypoint and again every <see cref="SteepRecheckYards"/> walked toward it.
/// </summary>
private void CheckSteepAhead(NavRouteParser route, int idx, NavPoint pt, double ns, double ew)
{
if (_planner == null || !IsWalkTarget(pt.Type)) return;
if (idx == _steepCheckIdx && NavYd(ns - _steepCheckNs, ew - _steepCheckEw) < SteepRecheckYards) return;
_steepCheckIdx = idx;
_steepCheckNs = ns;
_steepCheckEw = ew;
// Out of tries for this waypoint: walk straight as before (the stuck escapes still apply).
if (_detourAttempts >= MaxDetourAttempts) return;
if (!_planner.CrossesSteepGround(ns, ew, pt.NS, pt.EW, out double atYd)) return;
TryStartDetour(route, idx, $"steep ground {atYd:F0}yd ahead on the way to waypoint {idx + 1}");
}
/// <summary>Yards from the character to the leg that ends at waypoint <paramref name="idx"/>.</summary>
private double DistanceToSegmentYd(NavRouteParser route, int idx, double ns, double ew)
{
@ -3005,9 +3055,19 @@ internal sealed class NavigationEngine
string skipNote = skipped > 0 ? $" (passes over {skipped} waypoint(s))" : "";
var plan = _planner.TryPlan(route.Points[rejoin], out string why);
// The navmesh path starts where the character's spot snaps onto the mesh, which can be
// on the far side of the slope it stands against: a first leg up that slope gets stuck
// again at once (Silentkelpie 2026-10-19, "reached 2/9 ... stuck on the detour").
if (plan != null && plan.Points.Count > 0
&& _planner.CrossesSteepGround(ns, ew, plan.Points[0].NS, plan.Points[0].EW, out double firstAt))
{
why = $"its first leg climbs steep ground {firstAt:F0}yd ahead";
plan = null;
}
if (plan == null)
{
_host.Log($"Nav: recovery #{number} ({reason}) rejoin=[{rejoin}]{skipNote} planner=none - result: no plan ({why}); attempt {_detourAttempts}/{MaxDetourAttempts}, using the stuck escapes");
if (why == NavRecoveryPlanner.OtherLevelWhy) WaypointOnOtherLevel?.Invoke(rejoin);
if (_detourAttempts >= MaxDetourAttempts) NotifyGaveUp(idx);
return false;
}
@ -3302,6 +3362,79 @@ internal sealed class NavigationEngine
private bool TryGetPos(out double ns, out double ew)
=> NavCoordinateHelper.TryGetNavCoords(_host, out ns, out ew);
/// <summary>The character's height and cell (world units), when the engine has them.</summary>
private bool TryGetZ(out float z, out uint cell)
{
z = 0; cell = 0;
return _host.HasGetPlayerPose && _host.TryGetPlayerPose(out cell, out _, out _, out z, out _, out _, out _, out _);
}
/// <summary>In a dungeon, the waypoint (with a height) is a level above or below (DungeonPathfinder.LevelApartZ).</summary>
private bool OnOtherLevel(NavPoint pt)
{
if (pt.Z == 0.0 || !TryGetZ(out float z, out uint cell) || (cell & 0xFFFF) < 0x0100) return false;
return Math.Abs(z - pt.Z * 240.0) > DungeonPathfinder.LevelApartZ;
}
/// <summary>The trail of where the steering walked (for TryBacktrack); a jump of 30 yd or more starts it over.</summary>
private void NoteTrail(double ns, double ew)
{
if (!TryGetZ(out float z, out _)) return;
if (_trail.Count > 0)
{
var l = _trail[^1];
double d = NavYd(ns - l.Ns, ew - l.Ew);
if (d < TrailStepYd) return;
if (d > 30.0) _trail.Clear();
}
_trail.Add((ns, ew, z));
if (_trail.Count > TrailMax) _trail.RemoveAt(0);
}
/// <summary>
/// Stuck where the map has no way round: back along the trail (same level, up to BacktrackYd), as a detour that
/// rejoins the same waypoint. Once per stuck spot.
/// </summary>
private bool TryBacktrack(NavRouteParser route)
{
if (!RecoveryEnabled || _detour != null || _areaMismatch) return false;
int idx = _settings.ActiveNavIndex;
if (!IndexValid(idx, route) || !IsWalkTarget(route.Points[idx].Type)) return false;
if (!TryGetPos(out double ns, out double ew) || !TryGetZ(out float z, out _)) return false;
if (!double.IsNaN(_backtrackSpotNs) && NavYd(ns - _backtrackSpotNs, ew - _backtrackSpotEw) <= StuckSpotYards) return false;
var pts = new List<NavPoint>();
double went = 0, lastNs = ns, lastEw = ew;
for (int i = _trail.Count - 1; i >= 0 && went < BacktrackYd; i--)
{
var c = _trail[i];
if (Math.Abs(c.Z - z) > 3.0) break; // not down off a ledge, nor up one
double step = NavYd(c.Ns - lastNs, c.Ew - lastEw);
if (step < 1.0 && pts.Count == 0) continue; // the spot we're stuck on
went += step;
lastNs = c.Ns; lastEw = c.Ew;
pts.Add(new NavPoint { Type = NavPointType.Point, NS = c.Ns, EW = c.Ew, Z = c.Z / 240.0 });
}
if (pts.Count == 0 || went < 2.0) return false;
_backtrackSpotNs = ns;
_backtrackSpotEw = ew;
long now = Now;
int number = ++_recoveryNumber;
_detour = new Detour
{
Number = number, Reason = "stuck, the map has no way round: backtracking", Planner = "backtrack",
Points = pts, StartIdx = idx, RejoinIdx = idx, LengthYd = went, StartedAt = now,
DeadlineAt = now + 10000 + (long)(went * 600.0),
};
_host.Log($"Nav: recovery #{number} started (stuck at [{idx}]) via backtrack: {pts.Count} pts, {went:F0}yd back along the way we came");
StopMovement();
_inRecovery = false;
_closestDist = double.MaxValue;
_settings.NavIsStuck = true;
return true;
}
private static bool IndexValid(int i, NavRouteParser r)
=> r?.Points != null && i >= 0 && i < r.Points.Count;

View file

@ -20,7 +20,8 @@ public static unsafe class PluginExports
// "RynthAi.Hub" v1 for RynthILT (the Mini Remote hosting its ILT tabs, /myquests, spell names, loot
// matching, the .usd importer, session stats; Shared/RynthAiHubApi.cs, HubInterface.cs),
// "RynthAi.Yield" v1 for RynthDefective (the player's key press goes before RynthAi's next action;
// Shared/RynthAiYieldApi.cs, YieldInterface.cs),
// Shared/RynthAiYieldApi.cs, YieldInterface.cs), "RynthAi.DungeonPath" v1 for RynthNav (the Dungeon
// Patrol's pathfinder inside a dungeon; Shared/RynthAiDungeonPathApi.cs, DungeonPathInterface.cs),
// "RynthAi.Routes" v1 for a plugin that has RynthAi make dungeon routes (/ra dunroute, dunpatrol-save;
// JSON in and out, Shared/RynthAiRoutesApi.cs, RoutesInterface.cs).
// Fixed signature: void* (const char* iface, uint version).
@ -35,6 +36,7 @@ public static unsafe class PluginExports
if (table == IntPtr.Zero) table = ActivityInterface.Query(iface, version);
if (table == IntPtr.Zero) table = HubInterface.Query(iface, version);
if (table == IntPtr.Zero) table = YieldInterface.Query(iface, version);
if (table == IntPtr.Zero) table = DungeonPathInterface.Query(iface, version);
if (table == IntPtr.Zero) table = RoutesInterface.Query(iface, version);
return table != IntPtr.Zero ? table : CombatHookInterface.Query(iface, version);
}
@ -61,6 +63,8 @@ public static unsafe class PluginExports
catch (Exception ex) { LogShutdownError(plugin, "ActivityInterface.Release", ex); }
try { YieldInterface.Release(); }
catch (Exception ex) { LogShutdownError(plugin, "YieldInterface.Release", ex); }
try { DungeonPathInterface.Release(); }
catch (Exception ex) { LogShutdownError(plugin, "DungeonPathInterface.Release", ex); }
try { RoutesInterface.Release(); }
catch (Exception ex) { LogShutdownError(plugin, "RoutesInterface.Release", ex); }
try { HubInterface.Release(); } // Version 0; the table stays (RynthILT's render thread may hold it)
@ -150,6 +154,8 @@ public static unsafe class PluginExports
{
if (surface == null) return 0;
ReadOnlySpan<byte> name = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(surface);
// Engine tags popped-out embeds with ":popout" so the Mini Remote can show Dock
// and open expanded Options in the floating window.
bool popped = name.EndsWith(":popout"u8);
if (popped) name = name[..^":popout"u8.Length];
var plugin = Runtime.Plugin;
@ -202,7 +208,7 @@ public static unsafe class PluginExports
bool remote = name.SequenceEqual("miniremote-remote"u8);
bool window = remote || name.SequenceEqual("miniremote-window"u8);
if (!window && !name.SequenceEqual("miniremote"u8)) return 0;
if (!plugin.RenderEmbeddedMiniRemote(window, out want, tabs: !remote)) return 0;
if (!plugin.RenderEmbeddedMiniRemote(window, out want, tabs: !remote, popped: popped)) return 0;
}
if (wantWidth != null) *wantWidth = want.X;
if (wantHeight != null) *wantHeight = want.Y;
@ -1009,6 +1015,15 @@ public static unsafe class PluginExports
catch { }
}
// The Inventory panel's right-click "Add to Damage panel weapons" (2026-10-25): a weapon,
// wand or shield by id, without selecting it first. Shields go in as off-hand items.
[UnmanagedCallersOnly(EntryPoint = "RynthPluginAddWeaponById", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void AddWeaponById(uint id)
{
try { Runtime.Plugin?.DashboardRenderer?.AddWeapon(id); }
catch { }
}
[UnmanagedCallersOnly(EntryPoint = "RynthPluginAddSelectedConsumable", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void AddSelectedConsumable()
{

View file

@ -0,0 +1,81 @@
// FolderPicker.cs — native Windows folder browse (SHBrowseForFolderW).
// Used by the VirindiTank import window so the player can pick Monsters / Loot / Nav / Meta folders.
// Blocks the calling thread until the dialog closes (pump or render).
using System;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
namespace RynthCore.Plugin.RynthAi.ProfileImport;
[SupportedOSPlatform("windows")]
internal static class FolderPicker
{
/// <summary>
/// Opens the system folder picker. Returns the chosen path, or null when cancelled / unavailable.
/// </summary>
public static string? Pick(string title, string? startingFolder = null)
{
IntPtr pidlRoot = IntPtr.Zero;
try
{
if (!string.IsNullOrWhiteSpace(startingFolder) && System.IO.Directory.Exists(startingFolder))
pidlRoot = ILCreateFromPathW(startingFolder);
var bi = new BROWSEINFO
{
hwndOwner = GetActiveWindow(),
pidlRoot = pidlRoot,
pszDisplayName = Marshal.AllocHGlobal(260 * 2),
lpszTitle = title ?? "Choose folder",
ulFlags = BifReturnOnlyFsDirs | BifNewDialogStyle | BifEditBox,
};
IntPtr pidl = SHBrowseForFolderW(ref bi);
Marshal.FreeHGlobal(bi.pszDisplayName);
if (pidl == IntPtr.Zero) return null;
var sb = new StringBuilder(260);
bool ok = SHGetPathFromIDListW(pidl, sb);
Marshal.FreeCoTaskMem(pidl);
return ok ? sb.ToString() : null;
}
catch
{
return null;
}
finally
{
if (pidlRoot != IntPtr.Zero) Marshal.FreeCoTaskMem(pidlRoot);
}
}
private const uint BifReturnOnlyFsDirs = 0x0001;
private const uint BifNewDialogStyle = 0x0040;
private const uint BifEditBox = 0x0010;
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct BROWSEINFO
{
public IntPtr hwndOwner;
public IntPtr pidlRoot;
public IntPtr pszDisplayName;
[MarshalAs(UnmanagedType.LPWStr)] public string lpszTitle;
public uint ulFlags;
public IntPtr lpfn;
public IntPtr lParam;
public int iImage;
}
[DllImport("user32.dll")]
private static extern IntPtr GetActiveWindow();
[DllImport("shell32.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr SHBrowseForFolderW(ref BROWSEINFO lpbi);
[DllImport("shell32.dll", CharSet = CharSet.Unicode)]
private static extern bool SHGetPathFromIDListW(IntPtr pidl, StringBuilder pszPath);
[DllImport("shell32.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr ILCreateFromPathW([MarshalAs(UnmanagedType.LPWStr)] string pszPath);
}

View file

@ -0,0 +1,227 @@
// VTankImportWindow.cs — ImGui window: pick VirindiTank source folders then Import.
// Rows: Monsters, Loot, Nav, Meta, and Settings profiles (.usd → SettingsProfiles).
// Opened from Settings → Game Client → VirindiTank → Import…, or /ra vtimport.
// Render thread only.
using System;
using System.IO;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi.ProfileImport;
internal sealed class VTankImportWindow
{
private const string Title = "VirindiTank Import##rynthvtimport";
private readonly SavedWindow _spot = new("RynthAi.VTankImport");
private readonly Func<LegacyUiSettings?> _settings;
private readonly Func<string?> _charFolder;
private readonly Action? _refreshProfiles;
private readonly Action<string> _chat;
private readonly Action<string> _log;
private readonly Action? _afterImportSave;
private bool _open;
private string _monsters = string.Empty;
private string _loot = string.Empty;
private string _nav = string.Empty;
private string _meta = string.Empty;
private string _profiles = string.Empty;
private bool _mergeMonsters = true;
private string _status = string.Empty;
private bool _busy;
public VTankImportWindow(
Func<LegacyUiSettings?> settings,
Func<string?> charFolder,
Action? refreshProfiles,
Action<string> chat,
Action<string> log,
Action? afterImportSave = null)
{
_settings = settings;
_charFolder = charFolder;
_refreshProfiles = refreshProfiles;
_chat = chat;
_log = log;
_afterImportSave = afterImportSave;
}
public bool IsOpen => _open;
/// <summary>Show the window; fill blank rows from the first existing VirindiTank install folder.</summary>
public void Show()
{
_open = true;
_status = string.Empty;
PrefillDefaultsIfEmpty();
}
public void Hide() => _open = false;
/// <summary>Render thread: draw while open.</summary>
public void Render()
{
if (!_open) return;
ImGui.SetNextWindowSize(new Vector2(680, 380), ImGuiCond.FirstUseEver);
bool open = _open;
_spot.Apply();
if (!ImGui.Begin(Title, ref open, ImGuiWindowFlags.NoCollapse))
{
ImGui.End();
if (!open) _open = false;
return;
}
_spot.Track();
if (!open) { _open = false; ImGui.End(); return; }
SafeImGui.TextWrapped(
"Choose where to import from. Each row is optional (blank = skip that kind). "
+ "Browse opens a folder picker. Defaults fill from C:\\Games\\VirindiPlugins\\VirindiTank when it exists.");
ImGui.Spacing();
FolderRow("Monsters (.usd / monsters.json)", ref _monsters, "Choose Monsters folder");
FolderRow("Loot profiles (.utl)", ref _loot, "Choose Loot profiles folder");
FolderRow("Nav profiles (.nav)", ref _nav, "Choose Nav folder");
FolderRow("Meta files (.met)", ref _meta, "Choose Meta folder");
FolderRow("Settings profiles (.usd → Profiles)", ref _profiles, "Choose VTank profiles folder");
if (ImGui.IsItemHovered())
ImGui.SetTooltip(
"Each top-level .usd becomes a named settings profile under this character's SettingsProfiles "
+ "(MyMonsters + ring options on a copy of your current settings). Does not switch the active profile.");
ImGui.Spacing();
ImGui.Checkbox("Merge MyMonsters into this character's combat settings", ref _mergeMonsters);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Off: copy loot / nav / meta files only (same as /ra vtimport files). Settings-profile import still runs when that folder is set.");
ImGui.Spacing();
ImGui.BeginDisabled(_busy);
if (ImGui.Button("Fill from VirindiTank default"))
{
string? root = FirstDefaultRoot();
if (root == null)
_status = "No VirindiTank folder found under Games / Documents.";
else
{
_monsters = _loot = _nav = _meta = _profiles = root;
_status = "Filled from " + root;
}
}
ImGui.SameLine();
if (ImGui.Button("Import"))
RunImport();
ImGui.SameLine();
if (ImGui.Button("Close"))
_open = false;
ImGui.EndDisabled();
if (_status.Length > 0)
{
ImGui.Spacing();
SafeImGui.TextWrapped(_status);
}
ImGui.End();
}
private void FolderRow(string label, ref string path, string browseTitle)
{
ImGui.AlignTextToFramePadding();
ImGui.TextUnformatted(label);
ImGui.SameLine(280f);
ImGui.SetNextItemWidth(Math.Max(160f, ImGui.GetContentRegionAvail().X - 80f));
string id = "##vt_" + label;
ImGui.InputText(id, ref path, 512u);
ImGui.SameLine();
if (ImGui.SmallButton("Browse##" + label))
{
string? start = Directory.Exists(path) ? path : FirstDefaultRoot();
string? picked = FolderPicker.Pick(browseTitle, start);
if (picked != null) path = picked;
}
}
private void PrefillDefaultsIfEmpty()
{
if (_monsters.Length + _loot.Length + _nav.Length + _meta.Length + _profiles.Length > 0) return;
string? root = FirstDefaultRoot();
if (root == null) return;
_monsters = _loot = _nav = _meta = _profiles = root;
}
private static string? FirstDefaultRoot()
{
foreach (string root in VirindiTankProfileImporter.DefaultVirindiTankRoots())
if (Directory.Exists(root)) return root;
const string games = @"C:\Games\VirindiPlugins\VirindiTank";
return Directory.Exists(games) ? games : null;
}
private void RunImport()
{
if (_busy) return;
var sources = new VirindiTankProfileImporter.ImportSources
{
MonstersFolder = BlankToNull(_monsters),
LootFolder = BlankToNull(_loot),
NavFolder = BlankToNull(_nav),
MetaFolder = BlankToNull(_meta),
ProfilesFolder = BlankToNull(_profiles),
};
if (sources.MonstersFolder == null && sources.LootFolder == null
&& sources.NavFolder == null && sources.MetaFolder == null
&& sources.ProfilesFolder == null)
{
_status = "Pick at least one folder (or Fill from VirindiTank default).";
return;
}
_busy = true;
_status = "Importing…";
try
{
LegacyUiSettings? settings = _settings();
string? charFolder = _charFolder();
var result = VirindiTankProfileImporter.ImportFromSources(
sources, settings, _mergeMonsters, charFolder);
if (_mergeMonsters && settings != null
&& (result.MonsterRulesAdded > 0 || result.RingSettingsSet.Length > 0))
{
try { _afterImportSave?.Invoke(); }
catch (Exception ex) { _log("VTank import: save settings failed: " + ex.Message); }
}
if (result.SettingsProfilesWritten > 0)
{
try { _refreshProfiles?.Invoke(); }
catch (Exception ex) { _log("VTank import: refresh profiles failed: " + ex.Message); }
}
_status = result.SummaryLine();
_chat("[RynthAi] " + result.SummaryLine());
foreach (string line in result.LogLines)
_log("VTank import: " + line);
if (result.LootFilesCopied + result.NavFilesCopied + result.MetaFilesCopied
+ result.MonsterRulesAdded + result.SettingsProfilesWritten == 0)
_status += " Nothing new found in the chosen folders.";
}
catch (Exception ex)
{
_status = "Import failed: " + ex.Message;
_chat("[RynthAi] VTank import failed: " + ex.Message);
_log("VTank import exception: " + ex);
}
finally
{
_busy = false;
}
}
private static string? BlankToNull(string s) =>
string.IsNullOrWhiteSpace(s) ? null : s.Trim();
}

View file

@ -9,7 +9,11 @@ using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi.ProfileImport;
/// <summary>
/// Copies VirindiTank-style loot files (.utl) and merges Rynth-format monster JSON found under common VT install paths.
/// Imports VirindiTank profiles from the common VT install folders into RynthAi:
/// loot (.utl) → LootProfiles, nav (.nav) → NavProfiles, metas (.met) → MetaFiles,
/// merges MyMonsters from text .usd / monsters.json into the live combat settings,
/// and can write each .usd as a named SettingsProfiles JSON for this character.
/// Used by Settings → Game Client (every server) and /ra vtimport — not ILT-only.
/// </summary>
public static class VirindiTankProfileImporter
{
@ -46,7 +50,11 @@ public static class VirindiTankProfileImporter
public sealed class Result
{
public int LootFilesCopied;
public int NavFilesCopied;
public int MetaFilesCopied;
public int MonsterRulesAdded;
/// <summary>Named SettingsProfiles written from VTank .usd character profiles.</summary>
public int SettingsProfilesWritten;
/// <summary>Full paths of .utl files copied into the Rynth loot folder this run (for activating loot).</summary>
public List<string> CopiedLootDestPaths { get; } = new();
public List<string> LogLines { get; } = new();
@ -54,11 +62,68 @@ public static class VirindiTankProfileImporter
internal List<(string File, VtRingSettings Ring)> RingSettingsFound { get; } = new();
/// <summary>"Min Ring Targets 2, Ring Range 5 (from the profile)" when they were set; else "".</summary>
public string RingSettingsSet { get; internal set; } = string.Empty;
/// <summary>One chat line: counts of what this run brought in.</summary>
public string SummaryLine()
{
string ring = string.IsNullOrEmpty(RingSettingsSet) ? "" : $"; {RingSettingsSet}";
string profiles = SettingsProfilesWritten > 0 ? $", {SettingsProfilesWritten} settings profile(s)" : "";
return $"VTank import: {LootFilesCopied} loot, {NavFilesCopied} nav, {MetaFilesCopied} meta, {MonsterRulesAdded} monster rule(s){profiles}{ring}.";
}
}
/// <param name="lootDestDir">RynthAi LootProfiles folder.</param>
/// <param name="mergeMonsterRules">When true, deserialized rules are merged into <paramref name="settings"/>.</param>
public static Result Import(string lootDestDir, LegacyUiSettings settings, bool mergeMonsterRules)
/// <summary>Source folders the import window (or a script) chooses; null / empty skips that kind.</summary>
public sealed class ImportSources
{
public string? MonstersFolder;
public string? LootFolder;
public string? NavFolder;
public string? MetaFolder;
/// <summary>VTank .usd character profiles → RynthAi SettingsProfiles (named JSON).</summary>
public string? ProfilesFolder;
}
/// <summary>
/// Full import into the live RynthAi folders (LootProfiles, NavProfiles, MetaFiles) and optional
/// monster/ring merge into <paramref name="settings"/>. Destinations default to
/// <see cref="RynthCore.Install.RynthInstallPaths.RynthAiDir"/>. Scans
/// <see cref="DefaultVirindiTankRoots"/> (no folder picker).
/// </summary>
public static Result ImportAll(LegacyUiSettings? settings, bool mergeMonsterRules = true,
string? lootDestDir = null, string? navDestDir = null, string? metaDestDir = null)
{
string ai = RynthCore.Install.RynthInstallPaths.RynthAiDir;
lootDestDir ??= Path.Combine(ai, "LootProfiles");
navDestDir ??= Path.Combine(ai, "NavProfiles");
metaDestDir ??= Path.Combine(ai, "MetaFiles");
return Import(lootDestDir, navDestDir, metaDestDir, settings, mergeMonsterRules);
}
/// <summary>
/// Import from the folders the player picked (blank = skip). Destinations stay RynthAi's.
/// <paramref name="settingsProfilesCharDir"/> is SettingsProfiles\&lt;server&gt;\&lt;character&gt; for .usd → named profiles.
/// </summary>
public static Result ImportFromSources(ImportSources sources, LegacyUiSettings? settings, bool mergeMonsterRules,
string? settingsProfilesCharDir = null)
{
string ai = RynthCore.Install.RynthInstallPaths.RynthAiDir;
string lootDest = Path.Combine(ai, "LootProfiles");
string navDest = Path.Combine(ai, "NavProfiles");
string metaDest = Path.Combine(ai, "MetaFiles");
return Import(lootDest, navDest, metaDest, settings, mergeMonsterRules, sources, settingsProfilesCharDir);
}
/// <param name="lootDestDir">RynthAi LootProfiles folder (.utl).</param>
/// <param name="navDestDir">RynthAi NavProfiles folder (.nav); null skips navs.</param>
/// <param name="metaDestDir">RynthAi MetaFiles folder (.met); null skips metas.</param>
/// <param name="mergeMonsterRules">When true and <paramref name="settings"/> is set, merge MyMonsters from .usd / monsters.json.</param>
public static Result Import(string lootDestDir, LegacyUiSettings settings, bool mergeMonsterRules) =>
Import(lootDestDir, Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "NavProfiles"),
Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "MetaFiles"), settings, mergeMonsterRules);
public static Result Import(string lootDestDir, string? navDestDir, string? metaDestDir,
LegacyUiSettings? settings, bool mergeMonsterRules, ImportSources? sources = null,
string? settingsProfilesCharDir = null)
{
var result = new Result();
if (string.IsNullOrEmpty(lootDestDir))
@ -67,60 +132,254 @@ public static class VirindiTankProfileImporter
return result;
}
try { Directory.CreateDirectory(lootDestDir); }
catch (Exception ex)
{
result.LogLines.Add($"Cannot create loot folder: {ex.Message}");
return result;
}
if (!TryEnsureDir(lootDestDir, "loot", result)) return result;
if (!string.IsNullOrEmpty(navDestDir) && !TryEnsureDir(navDestDir, "nav", result)) navDestDir = null;
if (!string.IsNullOrEmpty(metaDestDir) && !TryEnsureDir(metaDestDir, "meta", result)) metaDestDir = null;
var seenSrc = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (string root in DefaultVirindiTankRoots())
{
foreach (string utl in EnumerateFilesRecursive(root, "*.utl", maxDepth: 6))
{
if (!seenSrc.Add(utl)) continue;
string baseName = Path.GetFileName(utl);
string dest = Path.Combine(lootDestDir, baseName);
int suffix = 0;
while (File.Exists(dest))
{
suffix++;
dest = Path.Combine(lootDestDir, $"VT_{suffix}_{baseName}");
}
try
{
File.Copy(utl, dest, overwrite: false);
result.LootFilesCopied++;
result.CopiedLootDestPaths.Add(dest);
result.LogLines.Add($"Loot: {baseName} -> {Path.GetFileName(dest)}");
}
catch (Exception ex)
{
result.LogLines.Add($"Loot skip {baseName}: {ex.Message}");
}
// Picked folders: each kind has its own root (import window). Else scan default VT installs.
if (sources != null)
{
ScanOne(sources.LootFolder, "*.utl", lootDestDir, "Loot", seenSrc, result,
() => result.LootFilesCopied++, dest => result.CopiedLootDestPaths.Add(dest));
if (!string.IsNullOrEmpty(navDestDir))
ScanOne(sources.NavFolder, "*.nav", navDestDir, "Nav", seenSrc, result, () => result.NavFilesCopied++);
if (!string.IsNullOrEmpty(metaDestDir))
ScanOne(sources.MetaFolder, "*.met", metaDestDir, "Meta", seenSrc, result, () => result.MetaFilesCopied++);
if (mergeMonsterRules && settings != null && !string.IsNullOrEmpty(sources.MonstersFolder)
&& Directory.Exists(sources.MonstersFolder))
{
result.LogLines.Add($"Scanning monsters {sources.MonstersFolder}");
foreach (string jsonPath in EnumerateFilesRecursive(sources.MonstersFolder, "monsters.json", maxDepth: 8))
TryMergeMonsterFile(jsonPath, settings, result);
foreach (string usdPath in EnumerateFilesRecursive(sources.MonstersFolder, "*.usd", maxDepth: 6))
TryMergeUsdMyMonstersScf(usdPath, settings, result);
}
if (mergeMonsterRules)
// VTank .usd character profiles → named SettingsProfiles for this character (does not switch the active one).
if (!string.IsNullOrWhiteSpace(sources.ProfilesFolder) && Directory.Exists(sources.ProfilesFolder))
ImportUsdFolderAsSettingsProfiles(sources.ProfilesFolder, settingsProfilesCharDir, settings, result);
}
else
{
foreach (string root in DefaultVirindiTankRoots())
{
foreach (string jsonPath in EnumerateFilesRecursive(root, "monsters.json", maxDepth: 8))
TryMergeMonsterFile(jsonPath, settings, result);
result.LogLines.Add($"Scanning {root}");
CopyPattern(root, "*.utl", lootDestDir, "Loot", seenSrc, result, () => result.LootFilesCopied++,
dest => result.CopiedLootDestPaths.Add(dest));
if (!string.IsNullOrEmpty(navDestDir))
CopyPattern(root, "*.nav", navDestDir, "Nav", seenSrc, result, () => result.NavFilesCopied++);
if (!string.IsNullOrEmpty(metaDestDir))
CopyPattern(root, "*.met", metaDestDir, "Meta", seenSrc, result, () => result.MetaFilesCopied++);
foreach (string usdPath in EnumerateFilesRecursive(root, "*.usd", maxDepth: 6))
TryMergeUsdMyMonstersScf(usdPath, settings, result);
if (mergeMonsterRules && settings != null)
{
foreach (string jsonPath in EnumerateFilesRecursive(root, "monsters.json", maxDepth: 8))
TryMergeMonsterFile(jsonPath, settings, result);
foreach (string usdPath in EnumerateFilesRecursive(root, "*.usd", maxDepth: 6))
TryMergeUsdMyMonstersScf(usdPath, settings, result);
}
}
}
if (mergeMonsterRules)
if (mergeMonsterRules && settings != null)
ApplyRingSettings(settings, result);
if (result.LootFilesCopied == 0 && result.MonsterRulesAdded == 0)
result.LogLines.Add("No .utl loot files, Rynth monsters.json, or text MyMonsters .usd found under VirindiTank paths.");
if (result.LootFilesCopied == 0 && result.NavFilesCopied == 0 && result.MetaFilesCopied == 0
&& result.MonsterRulesAdded == 0 && result.SettingsProfilesWritten == 0)
result.LogLines.Add("No .utl / .nav / .met / monsters.json / text MyMonsters .usd found under the chosen paths.");
return result;
}
/// <summary>
/// Each text .usd in <paramref name="usdFolder"/> (top-level files only) becomes a named settings
/// profile under <paramref name="settingsProfilesCharDir"/>: clone of the live template with that
/// profile's MyMonsters + ring options. Does not change the active profile.
/// </summary>
private static void ImportUsdFolderAsSettingsProfiles(string usdFolder, string? settingsProfilesCharDir,
LegacyUiSettings? template, Result result)
{
if (string.IsNullOrWhiteSpace(settingsProfilesCharDir))
{
result.LogLines.Add("Profiles: skipped (not logged in — no SettingsProfiles character folder).");
return;
}
if (!TryEnsureDir(settingsProfilesCharDir, "settings profiles", result)) return;
result.LogLines.Add($"Scanning profiles {usdFolder}");
IEnumerable<string> files;
try { files = Directory.EnumerateFiles(usdFolder, "*.usd"); }
catch (Exception ex)
{
result.LogLines.Add($"Profiles: cannot list {usdFolder}: {ex.Message}");
return;
}
foreach (string usdPath in files)
{
if (LooksLikeSqliteFile(usdPath))
{
result.LogLines.Add($"Profiles: skip SQLite .usd (use Monster Editor): {Path.GetFileName(usdPath)}");
continue;
}
string profileName = SanitizeProfileName(Path.GetFileNameWithoutExtension(usdPath));
if (profileName.Length == 0)
{
result.LogLines.Add($"Profiles: skip empty name from {Path.GetFileName(usdPath)}");
continue;
}
// Reserved: Default is the live character profile; don't overwrite it from a VTank dump.
if (profileName.Equals("Default", StringComparison.OrdinalIgnoreCase)
|| profileName.Equals("active_profile", StringComparison.OrdinalIgnoreCase))
profileName = "VT_" + profileName;
string dest = Path.Combine(settingsProfilesCharDir, profileName + ".json");
int suffix = 0;
while (File.Exists(dest))
{
suffix++;
dest = Path.Combine(settingsProfilesCharDir, $"VT_{suffix}_{profileName}.json");
}
string writtenName = Path.GetFileNameWithoutExtension(dest);
LegacyUiSettings? clone = CloneSettings(template);
if (clone == null)
{
result.LogLines.Add($"Profiles: skip {Path.GetFileName(usdPath)} (could not clone settings).");
continue;
}
// This profile is that VTank .usd: replace monsters with its MyMonsters (keep a Default row).
clone.MonsterRules = new List<MonsterRule>();
clone.EnsureDefaultRule();
clone.SelectedProfile = writtenName;
string allText;
try { allText = File.ReadAllText(usdPath, Encoding.UTF8); }
catch (Exception ex)
{
result.LogLines.Add($"Profiles: skip read {Path.GetFileName(usdPath)}: {ex.Message}");
continue;
}
var tmp = new List<MonsterRule>();
VirindiTankUsdMyMonstersScfParser.TryParseMyMonsters(allText, tmp, out string? note);
int monstersBefore = result.MonsterRulesAdded;
if (tmp.Count > 0)
MergeVtMonsterRows(tmp, clone, result);
// MonsterRulesAdded counts live merge; for profiles we track SettingsProfilesWritten separately.
result.MonsterRulesAdded = monstersBefore;
var ring = VtRingSettings.Read(allText.Split(new[] { "\r\n", "\n" }, StringSplitOptions.None));
if (ring.Any) ring.ApplyTo(clone);
string json;
try { json = JsonSerializer.Serialize(clone, RynthAiJsonContext.Default.LegacyUiSettings); }
catch (Exception ex)
{
result.LogLines.Add($"Profiles: skip serialize {writtenName}: {ex.Message}");
continue;
}
try
{
File.WriteAllText(dest, json, Encoding.UTF8);
result.SettingsProfilesWritten++;
result.LogLines.Add(
$"Profiles: {Path.GetFileName(usdPath)} -> {writtenName}.json"
+ (tmp.Count > 0 ? $" ({tmp.Count} monster rule(s)" + (ring.Any ? $", {ring.Describe()}" : "") + ")" : "")
+ (string.IsNullOrEmpty(note) ? "" : "; " + note));
}
catch (Exception ex)
{
result.LogLines.Add($"Profiles: write failed {writtenName}: {ex.Message}");
}
}
}
/// <summary>Safe settings-profile file stem (letters, digits, apostrophe, hyphen; else underscore).</summary>
private static string SanitizeProfileName(string name)
{
if (string.IsNullOrWhiteSpace(name)) return string.Empty;
// VTank dumps often prefix with "--"; strip leading dashes/underscores for a cleaner profile name.
name = name.Trim().TrimStart('-', '_', ' ');
var sb = new StringBuilder(name.Length);
foreach (char c in name)
sb.Append(char.IsLetterOrDigit(c) || c == '\'' || c == '-' || c == '_' || c == ' ' ? c : '_');
string cleaned = sb.ToString().Trim();
// Spaces → underscores so the dashboard list stays tidy.
return cleaned.Replace(' ', '_');
}
private static LegacyUiSettings? CloneSettings(LegacyUiSettings? template)
{
try
{
if (template == null) return new LegacyUiSettings();
string json = JsonSerializer.Serialize(template, RynthAiJsonContext.Default.LegacyUiSettings);
return JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.LegacyUiSettings) ?? new LegacyUiSettings();
}
catch
{
return new LegacyUiSettings();
}
}
private static void ScanOne(string? root, string pattern, string destDir, string label,
HashSet<string> seenSrc, Result result, Action onCopied, Action<string>? onDest = null)
{
if (string.IsNullOrWhiteSpace(root) || !Directory.Exists(root)) return;
result.LogLines.Add($"Scanning {label.ToLowerInvariant()} {root}");
CopyPattern(root, pattern, destDir, label, seenSrc, result, onCopied, onDest);
}
private static bool TryEnsureDir(string dir, string label, Result result)
{
try { Directory.CreateDirectory(dir); return true; }
catch (Exception ex)
{
result.LogLines.Add($"Cannot create {label} folder ({dir}): {ex.Message}");
return false;
}
}
/// <summary>Copies every matching file under <paramref name="root"/> into <paramref name="destDir"/> (no overwrite; VT_n_ prefix on clash).</summary>
private static void CopyPattern(string root, string pattern, string destDir, string label,
HashSet<string> seenSrc, Result result, Action onCopied, Action<string>? onDest = null)
{
foreach (string src in EnumerateFilesRecursive(root, pattern, maxDepth: 6))
{
if (!seenSrc.Add(src)) continue;
string baseName = Path.GetFileName(src);
// Skip VTank's empty placeholder nav name if it shows up as a file.
if (baseName.Equals("[None].nav", StringComparison.OrdinalIgnoreCase)) continue;
string dest = Path.Combine(destDir, baseName);
int suffix = 0;
while (File.Exists(dest))
{
suffix++;
dest = Path.Combine(destDir, $"VT_{suffix}_{baseName}");
}
try
{
File.Copy(src, dest, overwrite: false);
onCopied();
onDest?.Invoke(dest);
result.LogLines.Add($"{label}: {baseName} -> {Path.GetFileName(dest)}");
}
catch (Exception ex)
{
result.LogLines.Add($"{label} skip {baseName}: {ex.Message}");
}
}
}
/// <summary>SQLite-backed VT profiles are skipped here; use Monster Editor import for those.</summary>
private static bool LooksLikeSqliteFile(string path)
{
@ -198,7 +457,7 @@ public static class VirindiTankProfileImporter
{
if (ring.SameAs(first)) continue;
result.LogLines.Add($"Ring settings: the profiles differ ({found[0].File}: {first.Describe()}; {file}: {ring.Describe()}): " +
"Min Ring Targets and Ring Range left alone. Import one profile from the Hub's VTank import to take its values.");
"Min Ring Targets and Ring Range left alone. Import one .usd from the Mini Remote / Hub importer to take its values.");
return;
}
foreach (string c in first.Clamped) result.LogLines.Add($"Ring settings: {c} (the settings' range)");

View file

@ -0,0 +1,64 @@
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthAi;
// The quest loot list (2026-11-01): items to pick up by name, on top of the loot profile, for a quest being
// run. RynthOracle's "Run this quest" / "Loot map" puts the wiki quest's items here (the {{Itemlink}} items
// its steps kill or loot for) through the plugin-command broker ("questloot", "add <name>") and takes them
// off when the run ends; "/ra questloot add|remove|clear|list|on|off" does the same by hand. Kept for the
// session only (the loot profile is where lasting rules go). Checked first in ClassifyLootItem
// (CorpseOpenController.cs), so corpses and the ground both take them. Pump thread.
internal static class QuestLootList
{
public const string RuleLabel = "quest loot";
public const int MaxItems = 64;
private static readonly HashSet<string> Names = new(StringComparer.OrdinalIgnoreCase);
/// <summary>The list applies (on by default; "/ra questloot off" pauses it without forgetting it).</summary>
public static bool Enabled = true;
public static int Count => Names.Count;
public static IEnumerable<string> Items => Names;
/// <summary>The item is on the list (its exact name, any case) and the list is on.</summary>
public static bool Wants(string? itemName) =>
Enabled && Names.Count > 0 && !string.IsNullOrWhiteSpace(itemName) && Names.Contains(itemName.Trim());
public static void Clear() => Names.Clear();
/// <summary>"add Shiny Red Stone", "remove X", "clear", "list", "on", "off": what to say, and whether it worked.</summary>
public static (bool Ok, string Text) Apply(string line)
{
line = (line ?? "").Trim();
int sp = line.IndexOf(' ');
string verb = (sp < 0 ? line : line.Substring(0, sp)).ToLowerInvariant();
string name = sp < 0 ? "" : line.Substring(sp + 1).Trim().Trim('"').Trim();
switch (verb)
{
case "add":
if (name.Length == 0) return (false, "[RynthAi] /ra questloot add <exact item name>");
if (Names.Count >= MaxItems && !Names.Contains(name)) return (false, $"[RynthAi] The quest loot list is full ({MaxItems} items): /ra questloot clear.");
return Names.Add(name) ? (true, $"[RynthAi] Quest loot: picking up '{name}' ({Names.Count} on the list).") : (true, $"[RynthAi] Quest loot: '{name}' is on the list already.");
case "remove":
case "del":
return Names.Remove(name) ? (true, $"[RynthAi] Quest loot: '{name}' off the list ({Names.Count} left).") : (false, $"[RynthAi] Quest loot: '{name}' isn't on the list.");
case "clear":
int n = Names.Count;
Names.Clear();
return (true, $"[RynthAi] Quest loot list cleared ({n} items).");
case "on":
case "off":
Enabled = verb == "on";
return (true, $"[RynthAi] Quest loot list {(Enabled ? "on" : "off")} ({Names.Count} items).");
case "":
case "list":
return (true, Names.Count == 0
? "[RynthAi] The quest loot list is empty. /ra questloot add <name> (RynthOracle's Run this quest fills it)."
: $"[RynthAi] Quest loot ({(Enabled ? "on" : "off")}): " + string.Join(", ", Names));
default:
return (false, "[RynthAi] /ra questloot add <name> | remove <name> | clear | list | on | off | profile [off]");
}
}
}

View file

@ -25,6 +25,10 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
public BlacklistManager Blacklist => _blacklist;
public TargetingFSM TargetingFSM => _targetingFSM;
public bool IsInitialized => _geoLoader?.IsInitialized ?? false;
/// <summary>The static geometry of the landblock holding <paramref name="landcell"/> (null without dats).</summary>
public System.Collections.Generic.List<BoundingVolume>? GeometryAt(uint landcell)
=> IsInitialized ? _geoLoader.GetLandblockGeometry(landcell) : null;
public string StatusMessage => _geoLoader?.StatusMessage ?? "Not created";
public MainLogic()

View file

@ -142,6 +142,7 @@ public sealed partial class RynthAiPlugin
ChatLine("[RynthAi] /ra loot why — which loot rule takes the selected item, and why the rules above it didn't");
ChatLine("[RynthAi] /ra loot mode [profile|rares] — loot by the loot profile, or rares and needed mana stones only");
ChatLine("[RynthAi] /ra loot add [keep|keep N|salvage|sell|read] [name|like] [preview] — add a loot rule for the selected item");
ChatLine("[RynthAi] /ra questloot add <name>|remove <name>|clear|list|on|off — items to pick up by name for a quest (RynthOracle's Run this quest fills it; this session only)");
ChatLine("[RynthAi] /ra dumpinv — dump all inventory items (cache + direct)");
ChatLine("[RynthAi] /ra combat — dump combat state machine snapshot");
ChatLine("[RynthAi] /ra mstats [monster] — its evades, resists, hits, spells and kills this session (list | reset | show | hide)");
@ -151,6 +152,7 @@ public sealed partial class RynthAiPlugin
ChatLine("[RynthAi] /ra start | stop — start/stop the macro from chat");
ChatLine("[RynthAi] /ra pause [sec] — stop the macro, auto-resume after sec (default 60)");
ChatLine("[RynthAi] /ra vtankyield [on|off] — with Decal: stop when VTank starts (one bot per client)");
ChatLine("[RynthAi] /ra vtimport — open VirindiTank Import window (Monsters / Loot / Nav / Meta / Settings profiles). /ra vtimport go [files] imports from default VT folders. Also: Settings > Game Client");
ChatLine("[RynthAi] /ra metamgr on|off|status — Meta Manager: load a meta when a timer or a /myquests quest timer runs out (Meta panel, Schedule)");
ChatLine("[RynthAi] /ra metamgr poll [min] — check /myquests now, or set how often it checks (default 5 min)");
ChatLine("[RynthAi] /ra metamgr start <#> [min] | stop <#> | reset <#|all> — run a countdown rule, stop it, re-arm a rule");
@ -1687,14 +1689,50 @@ public sealed partial class RynthAiPlugin
Items = new LootItemHooks
{
SelectedItemId = () => Host.HasGetSelectedItemId ? Host.GetSelectedItemId() : 0,
IsIlt = () => _tier.OnIlt,
Facts = BuildLootItemFacts,
FirstMatchUtl = FirstLootRuleFor,
FirstMatchNative = FirstLootRuleFor,
Added = OnLootRuleAdded,
BuiltInKeep = LootBuiltInKeepFor,
Judge = JudgeLootFindItems,
Spells = LootSpellCatalogOnce,
},
};
private RynthCore.Loot.Editing.LootSpellCatalog? _lootSpellCatalog;
/// <summary>The loot popups' standard spell lists, built once the spell table is read.</summary>
private RynthCore.Loot.Editing.LootSpellCatalog? LootSpellCatalogOnce()
{
if (_lootSpellCatalog != null) return _lootSpellCatalog;
if (!SpellDatabase.IsLoaded) return null;
return _lootSpellCatalog = RynthCore.Loot.Editing.LootSpellCatalog.Build(SpellDatabase.AllSpells());
}
/// <summary>
/// "Filter like this" (the Inventory panel's right-click, 2026-10-24): the items the rule
/// takes, judged by the looter's own evaluator; with <paramref name="needsId"/>, the ones it
/// doesn't take that aren't identified yet (or that the object cache doesn't know) are unknown.
/// </summary>
private void JudgeLootFindItems(VTankLootRule rule, IReadOnlyList<uint> ids, bool needsId, List<uint> match, List<uint> unknown)
{
if (_objectCache == null) return;
var ctx = new VTankLootContext(Host, _playerId) { Cache = _objectCache };
bool canAsk = Host.HasHasAppraisalData;
foreach (uint id in ids)
{
WorldObject? wo = _objectCache[unchecked((int)id)];
if (wo == null)
{
unknown.Add(id);
continue;
}
if (VTankLootEvaluator.Match(rule, wo, ctx)) match.Add(id);
else if (needsId && canAsk && !Host.HasAppraisalData(id)) unknown.Add(id);
}
}
/// <summary>
/// Why RynthAi's looting takes the item without a loot profile rule, for the "Add to
/// loot profile" popup: the looter's own ClassifyItemAgainstProfile as a preview (nothing
@ -1774,8 +1812,9 @@ public sealed partial class RynthAiPlugin
}
/// <summary>
/// What a loot rule can be built from: the item's name, class, stack, key properties and
/// T11 reading, from the object cache. <paramref name="like"/> adds its spells;
/// What a loot rule can be built from: the item's name, class, stack, every property the
/// attribute checklist offers (LootItemAttributes) and T11 reading, from the object cache.
/// <paramref name="like"/> adds its spells (the popup always asks: its checklist lists them);
/// <paramref name="t11"/> asks for an ID when a T11 item's text hasn't arrived.
/// </summary>
private RynthCore.Loot.Editing.LootItemFacts? BuildLootItemFacts(uint itemId, bool like, bool t11)
@ -1789,6 +1828,8 @@ public sealed partial class RynthAiPlugin
ObjectClass = (int)wo.ObjectClass,
StackSize = Math.Max(1, wo.Values(LongValueKey.StackCount, 1)),
MaxStackSize = Math.Max(1, wo.Values(LongValueKey.MaxStackSize, 1)),
// The Pets tab's test (WCID block, summoning-gem icon, Summoning use requirement): the essence group.
IsPetEssence = _miniRemote?.Pets.IsPetDevice(wo) == true,
};
foreach (int key in RynthCore.Loot.Editing.LootItemRules.IntKeys)
{
@ -1808,6 +1849,12 @@ public sealed partial class RynthAiPlugin
// Material, workmanship and spells need an ID: ask for one, so the next preview has them.
if (Host.HasRequestId && Host.HasHasAppraisalData && !Host.HasAppraisalData(itemId)) Host.RequestId(itemId);
}
// ACECustom's newer loot items (2026-11-11): what it is, its tier, a gem's coins (the checklist's T11 item rows).
foreach (int key in new[] { RynthCore.Loot.T11.T11Keys.ItemKind, RynthCore.Loot.T11.T11Keys.ItemTier, RynthCore.Loot.T11.T11Keys.InfusionCoins })
{
int v = wo.Values(key, 0);
if (v != 0) f.Ints[key] = v;
}
// Always read (a cached parse), so the popup knows whether the T11 option applies.
f.T11 = Loot.T11ItemSupport.Get(wo);
// T11 tier, grade and modifiers are appraisal text: ask for it, so the next preview has them.
@ -3297,7 +3344,7 @@ public sealed partial class RynthAiPlugin
if (route == null)
{
ReplyFail($"[RynthAi] DunNav: no walkable path found — destination may only be reachable via a drop (graph={nodeCount} nodes, dest={destNS:F2}N/{destEW:F2}E).");
ReplyFail($"[RynthAi] DunNav: no way there from here (drops down are taken; a level above may need stairs this map doesn't join) (graph={nodeCount} nodes, dest={destNS:F2}N/{destEW:F2}E).");
return;
}
@ -3306,7 +3353,11 @@ public sealed partial class RynthAiPlugin
settings.CurrentRoute = route;
settings.ActiveNavIndex = 0;
settings.EnableNavigation = true;
NoteDunNavRoute(route, destNS, destEW);
int jumps = 0;
foreach (var p in route.Points) if (p.Type == NavPointType.Jump) jumps++;
if (jumps > 0) ChatLine($"[RynthAi] DunNav: the way goes down {jumps} drop(s): walked to the edge and jumped.");
ReplyOk($"[RynthAi] DunNav: {nodeCount} cells, path={pathLength} steps → navigating to {destNS:F2}N/{destEW:F2}E");
}
@ -3708,7 +3759,7 @@ public sealed partial class RynthAiPlugin
};
}
private void BuildDunPatrol(bool isRebuild, bool settingsChanged = false, bool portalAppeared = false, bool followedIn = false, bool stuckOpening = false)
private void BuildDunPatrol(bool isRebuild, bool settingsChanged = false, bool portalAppeared = false, bool followedIn = false, string? levelNote = null, bool stuckOpening = false)
{
var b = TryBuildDunPatrol("dunnav-patrol", out string error, out var refusal);
if (b == null)
@ -3755,6 +3806,8 @@ public sealed partial class RynthAiPlugin
// hazard is sighted in this same landblock.
_dunPatrolActive = true;
_dunPatrolRoute = route;
// The level this patrol walks (DungeonPathfinder.Levels.cs): a lap done goes down to the next one.
NotePatrolLevel(b.World.Graph, b.StartCell, hazards, b.World.Landblock, fresh: !isRebuild);
_dunPatrolLandblock = b.World.Landblock;
_dunPatrolFollowTriedLb = uint.MaxValue;
_dunPatrolHazardVersion = _objectCache?.HazardVersion ?? 0;
@ -3764,7 +3817,11 @@ public sealed partial class RynthAiPlugin
int hazardCount = hazards?.Count ?? 0;
string hazardNote = hazardCount > 0 ? $", {hazardCount} hazard cell(s) avoided" : "";
string portalNote = portals.Count > 0 ? $", kept out of {portals.Count} portal(s)" : "";
if (isRebuild && followedIn)
if (isRebuild && levelNote != null)
{
ChatLine($"[RynthAi] DunNav-Patrol: {levelNote} → patrolling this level from here, {route.Points.Count} waypoints{hazardNote}{portalNote}.");
}
else if (isRebuild && followedIn)
{
ChatLine($"[RynthAi] DunNav-Patrol: followed you into dungeon 0x{b.World.Landblock:X4} → {route.Points.Count} waypoints, patrolling here{hazardNote}{portalNote}. Stop the macro or load a route to end it.");
}
@ -3817,7 +3874,7 @@ public sealed partial class RynthAiPlugin
bool replaced = settings != null && _dunPatrolRoute != null && !ReferenceEquals(settings.CurrentRoute, _dunPatrolRoute);
if (settings == null || replaced
|| !string.IsNullOrEmpty(settings.CurrentNavPath)
|| settings.CurrentRoute?.RouteType != NavRouteType.Circular)
|| (settings.CurrentRoute?.RouteType != NavRouteType.Circular && !DunPatrolDescending))
{
if (settings != null && (replaced || !string.IsNullOrEmpty(settings.CurrentNavPath)))
{

View file

@ -261,7 +261,14 @@ public sealed partial class RynthAiPlugin
if (why == "completed")
_lastChestLootedId = unchecked((uint)chestId); // ralastchestlooted[]
// Pickup with macro off > Leave the chest open: a chest the player opened stays open, and chat says so.
bool leaveOpen = close && chestId == _manualChestLootId && (_dashboard?.Settings?.LootChestsMacroOffLeaveOpen ?? false);
// With that option off it still stays open while anything the profile didn't take is in it
// (2026-11-05): Silentkelpie opened a Standing Stone a dozen times for its Bandit Rune
// Transcription; the profile left it and the stone was closed 1 ms later every time.
bool manual = close && chestId == _manualChestLootId;
int left = why == "completed" ? Math.Max(0, _lootItemsLeftAtFinish) : 0;
_lootItemsLeftAtFinish = 0;
bool optionOpen = manual && (_dashboard?.Settings?.LootChestsMacroOffLeaveOpen ?? false);
bool leaveOpen = optionOpen || (manual && left > 0);
if (chestId == _manualChestLootId)
_manualChestLootId = 0;
if (close && !leaveOpen)
@ -275,7 +282,8 @@ public sealed partial class RynthAiPlugin
string done = why == "completed"
? _corpseItemsLooted > 0 ? $"done with {chestName}: took {_corpseItemsLooted} item(s)." : $"done with {chestName}."
: $"stopped on {chestName} ({why}).";
ChatLine($"[RynthAi] Pickup with macro off: {done} Left it open: close it when you're done.");
string leftNote = left > 0 ? $" {left} item(s) the loot profile doesn't take are still in it." : "";
ChatLine($"[RynthAi] Pickup with macro off: {done}{leftNote} Left it open: close it when you're done.");
}
LootDiag($"[RynthAi] Chest loot: done with chest 0x{(uint)chestId:X8} ({why}); not marked, so opening it again loots it again.");
@ -493,6 +501,8 @@ public sealed partial class RynthAiPlugin
private long _manualChestSince;
/// <summary>The chest Pickup with macro off is looting (0 = none): FinishChestLoot leaves it open when set to.</summary>
private int _manualChestLootId;
// How many items were still in the loot container when it was finished (CorpseOpenController).
private int _lootItemsLeftAtFinish;
/// <summary>OnViewObjectContents for a non-corpse container: a chest the player may have opened.</summary>
private void NoteManualChestOpened(int id)

View file

@ -0,0 +1,156 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi;
// The Dungeon Patrol over a dungeon's levels (2026-11-08; DungeonPathfinder.Levels.cs). The patrol walks the level it
// is built on (the cells walkable from there). Once round it goes down the drop (a pit, a shaft, a ledge: walked to the
// edge and jumped) to the biggest part of the dungeon not patrolled yet and patrols there; and a character who ends up
// on another level (a chase into a pit: 11-08 10:41, dungeon 0x02D4, 17 m down) has the patrol rebuilt where it is,
// instead of steering at waypoints overhead. The levels patrolled are remembered until the patrol is started anew or
// the dungeon changes. Pump thread.
public sealed partial class RynthAiPlugin
{
private HashSet<uint> _dunPatrolLevel = new(); // the cells the current patrol's level has
private readonly HashSet<uint> _dunPatrolSeen = new(); // every level patrolled in this dungeon
private uint _dunLevelsLb = uint.MaxValue;
private int _dunLastIdx = -1;
private bool _dunDescending;
private HashSet<uint> _dunDescentBelow = new();
private long _dunDescentUntil, _dunLevelsNextAt;
private bool _dunNoDescentSaid;
private const long DunDescentMaxMs = 120_000, DunLevelsEveryMs = 1000;
/// <summary>BuildDunPatrol's part: the level the new patrol walks, added to the ones patrolled.</summary>
private void NotePatrolLevel(Dictionary<uint, DungeonNavNode> graph, uint startCell, IReadOnlySet<uint>? hazards, uint landblock, bool fresh)
{
if (fresh || _dunLevelsLb != landblock) { _dunPatrolSeen.Clear(); _dunNoDescentSaid = false; }
_dunLevelsLb = landblock;
_dunPatrolLevel = DungeonPathfinder.WalkableFrom(graph, startCell, hazards);
_dunPatrolSeen.UnionWith(_dunPatrolLevel);
_dunLastIdx = -1;
_dunDescending = false;
}
/// <summary>The descent's route is the patrol's for the while (TickDunPatrolHazardReroute doesn't stand down for it).</summary>
private bool DunPatrolDescending => _dunDescending;
/// <summary>Each tick while the patrol is on: the level it is on, a lap done, a descent landed.</summary>
private void TickDunPatrolLevels()
{
if (!_dunPatrolActive) return;
var settings = _dashboard?.Settings;
if (settings == null || !settings.IsMacroRunning) return;
long now = Environment.TickCount64;
if (now < _dunLevelsNextAt) return;
_dunLevelsNextAt = now + DunLevelsEveryMs;
if (!Host.TryGetPlayerPose(out uint cell, out _, out _, out _, out _, out _, out _, out _)) return;
if ((cell >> 16) != _dunLevelsLb || (cell & 0xFFFF) < 0x0100) return;
var cellDat = _raycast?.GeometryLoader?.CellDat;
if (cellDat == null || !cellDat.IsLoaded) return;
var graph = DungeonPathfinder.GetGraph(_dunLevelsLb, cellDat);
if (!graph.ContainsKey(cell)) return;
if (_dunDescending)
{
// Landed (or the walk ended or ran out of time): the patrol goes on from here.
bool landed = _dunDescentBelow.Contains(cell);
if (landed || !settings.EnableNavigation || now > _dunDescentUntil)
{
_dunDescending = false;
BuildDunPatrol(isRebuild: true, levelNote: landed ? "down a level" : "the way down ended here");
}
return;
}
if (!settings.EnableNavigation) return;
// On another level than the patrol's (fell into a pit, chased something down a drop): patrol this one.
if (_dunPatrolLevel.Count > 0 && !_dunPatrolLevel.Contains(cell))
{
HashSet<uint> here = DungeonPathfinder.WalkableFrom(graph, cell, _objectCache?.GetHazardCells());
if (!here.Overlaps(_dunPatrolLevel))
{
Log($"[RynthAi] DunNav-Patrol: on another level (cell {cell:X8}, {here.Count} cells, none of the patrol's): rebuilding here.");
BuildDunPatrol(isRebuild: true, levelNote: "on a lower level (a drop or a pit)");
return;
}
}
// A lap done (the index came round to the start): down to a level not patrolled yet, if a drop leads to one.
int idx = settings.ActiveNavIndex;
int n = settings.CurrentRoute?.Points.Count ?? 0;
bool lap = _dunLastIdx >= 0 && n > 2 && idx < _dunLastIdx && _dunLastIdx >= n - 2 && idx <= 1;
_dunLastIdx = idx;
if (lap) TryPatrolDescend(settings, graph, cell);
}
private void TryPatrolDescend(LegacyUiSettings settings, Dictionary<uint, DungeonNavNode> graph, uint cell)
{
var hazards = _objectCache?.GetHazardCells();
List<uint>? path = DungeonPathfinder.DescentPath(graph, cell, _dunPatrolSeen, hazards, out HashSet<uint> below);
if (path == null)
{
if (!_dunNoDescentSaid) Log("[RynthAi] DunNav-Patrol: a lap done; no drop leads to a level not patrolled yet: patrolling on here.");
_dunNoDescentSaid = true;
return;
}
if (!Host.TryGetPlayerPose(out _, out _, out _, out float pz, out _, out _, out _, out _)) return;
if (!NavCoordinateHelper.TryGetNavCoords(Host, out double pNs, out double pEw)) return;
var cellDat = _raycast?.GeometryLoader?.CellDat;
if (cellDat == null) return;
var geo = DungeonPathfinder.GetGeometry(_dunLevelsLb, cellDat, _raycast?.GeometryLoader?.DungeonLOS);
DungeonNavNode bottom = graph[path[^1]];
NavRouteParser route = DungeonPathfinder.BuildDropRoute(path, graph, geo, hazards, pNs, pEw, pz, bottom.NS, bottom.EW, bottom.Z, out int drops);
if (route.Points.Count == 0 || drops == 0) return;
_dunDescending = true;
_dunDescentBelow = below;
_dunDescentUntil = Environment.TickCount64 + DunDescentMaxMs;
_dunPatrolRoute = route;
settings.CurrentNavPath = string.Empty;
settings.CurrentRoute = route;
settings.ActiveNavIndex = 0;
settings.EnableNavigation = true;
int fresh = 0;
foreach (uint c in below) if (!_dunPatrolSeen.Contains(c)) fresh++;
ChatLine($"[RynthAi] DunNav-Patrol: this level is patrolled; going down a drop ({graph[path[^2]].Z - bottom.Z:F0} m) to {fresh} cells not patrolled yet.");
}
// ── dunnav (the quest's dungeon goto) on another level ──
private NavRouteParser? _dunNavRoute;
private double _dunNavDestNs = double.NaN, _dunNavDestEw;
private long _dunNavReplanAt;
private const long DunNavReplanMs = 20_000;
private void NoteDunNavRoute(NavRouteParser route, double ns, double ew)
{
_dunNavRoute = route;
_dunNavDestNs = ns;
_dunNavDestEw = ew;
}
/// <summary>
/// NavigationEngine: the waypoint is a level above or below with no walk to it (a fall into a pit). The patrol is
/// rebuilt on this level; a dunnav walk is planned again from here (drops down taken), at most every 20 s.
/// </summary>
private void OnWaypointOtherLevel(int idx)
{
var settings = _dashboard?.Settings;
if (settings == null) return;
long at = Environment.TickCount64;
if (_dunPatrolActive)
{
if (at < _dunNavReplanAt) return;
_dunNavReplanAt = at + DunNavReplanMs;
if (!_dunDescending) BuildDunPatrol(isRebuild: true, levelNote: "the patrol's waypoints are on another level");
return;
}
if (_dunNavRoute == null || !ReferenceEquals(settings.CurrentRoute, _dunNavRoute) || double.IsNaN(_dunNavDestNs)) return;
long now = Environment.TickCount64;
if (now < _dunNavReplanAt) return;
_dunNavReplanAt = now + DunNavReplanMs;
var inv = System.Globalization.CultureInfo.InvariantCulture;
Log($"[RynthAi] DunNav: waypoint {idx + 1} is on another level: planning again from here.");
HandleDungeonNavCommand(new[] { "/ra", "dunnav", _dunNavDestNs.ToString("0.#####", inv), _dunNavDestEw.ToString("0.#####", inv) });
}
}

View file

@ -0,0 +1,159 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
// The "RynthAi.DungeonPath" interface's work (DungeonPathInterface.cs, 2026-10-29): a walk inside a
// dungeon between two points, as the Dungeon Patrol and /ra dunnav find it (the cell graph and the
// doorways from the cell dat). Pump thread.
// v2 (2026-10-30, RynthNav routes through dungeons): drops down a ledge or shaft as a one-way step
// (the walk is split there: up to its edge, then on from where you land), and cells to keep out of
// (a locked door's doorway).
public sealed partial class RynthAiPlugin
{
internal unsafe int DungeonPathForPlugin(uint landblock, double sx, double sy, double sz, double gx, double gy, double gz,
double* points, int maxPoints, int* count,
double maxDrop = 0, double* avoid = null, int avoidCount = 0, int* kinds = null)
{
var cellDat = _raycast?.GeometryLoader?.CellDat;
if (cellDat == null || !cellDat.IsLoaded) return RynthAiDungeonPathApiV1.ResultNoData;
landblock &= 0xFFFF;
var graph = DungeonPathfinder.GetGraph(landblock, cellDat);
if (graph.Count == 0) return RynthAiDungeonPathApiV1.ResultNoData;
var geo = DungeonPathfinder.GetGeometry(landblock, cellDat, _raycast?.GeometryLoader?.DungeonLOS);
var avoidList = new List<(double X, double Y, double Z)>();
for (int i = 0; i < avoidCount; i++) avoidList.Add((avoid[i * 3], avoid[i * 3 + 1], avoid[i * 3 + 2]));
var walk = DungeonPathfinder.PluginWalk(graph, geo, sx, sy, sz, gx, gy, gz, maxDrop, avoidList, out int result);
if (walk == null) return result;
int n = 0;
foreach (var p in walk)
{
if (n >= maxPoints) break;
points[n * 3] = p.X; points[n * 3 + 1] = p.Y; points[n * 3 + 2] = p.Z;
if (kinds != null) kinds[n] = p.Kind;
n++;
}
if (n == maxPoints && walk.Count > maxPoints)
{
var last = walk[^1];
points[(n - 1) * 3] = last.X; points[(n - 1) * 3 + 1] = last.Y; points[(n - 1) * 3 + 2] = last.Z;
if (kinds != null) kinds[n - 1] = RynthAiDungeonPathApiV1.KindWalk;
}
*count = n;
return n >= 2 ? RynthAiDungeonPathApiV1.ResultOk : RynthAiDungeonPathApiV1.ResultNoPath;
}
}
internal static partial class DungeonPathfinder
{
/// <summary>How far past a drop's edge the landing point is put (world units), so the walk carries on off it.</summary>
internal const double DropRunOffMeters = 1.5;
private static double NsOf(double y) => (y / 24.0 - 1019.5) / 10.0;
private static double EwOf(double x) => (x / 24.0 - 1019.5) / 10.0;
private static double YOf(double ns) => (ns * 10.0 + 1019.5) * 24.0;
private static double XOf(double ew) => (ew * 10.0 + 1019.5) * 24.0;
/// <summary>
/// A walk for another plugin (RynthNav), world units, start first and goal last, with each
/// point's kind (RynthAiDungeonPathApiV1.KindWalk, or KindDrop: the edge of a drop, the next
/// point is where you land). Null with <paramref name="result"/> NoData / NoPath when there is none.
/// </summary>
internal static List<(double X, double Y, double Z, int Kind)>? PluginWalk(
Dictionary<uint, DungeonNavNode> graph, DungeonGeometry? geo,
double sx, double sy, double sz, double gx, double gy, double gz,
double maxDrop, IReadOnlyList<(double X, double Y, double Z)>? avoid, out int result)
{
result = RynthAiDungeonPathApiV1.ResultNoData;
uint startCell = NearestCell(graph, NsOf(sy), EwOf(sx), (float)sz);
uint goalCell = NearestCell(graph, NsOf(gy), EwOf(gx), (float)gz);
if (startCell == 0 || goalCell == 0) return null;
HashSet<uint>? keepOut = null;
if (avoid != null)
foreach (var a in avoid)
{
uint c = NearestCell(graph, NsOf(a.Y), EwOf(a.X), (float)a.Z);
if (c == 0 || c == startCell || c == goalCell) continue;
(keepOut ??= new HashSet<uint>()).Add(c);
}
List<uint> path = FindPath(startCell, goalCell, graph, keepOut, maxDrop);
if (path.Count == 0) { result = RynthAiDungeonPathApiV1.ResultNoPath; return null; }
var walk = new List<(double X, double Y, double Z, int Kind)>();
void Put(double x, double y, double z, int kind)
{
if (walk.Count > 0)
{
var l = walk[^1];
if (Math.Abs(l.X - x) < 0.05 && Math.Abs(l.Y - y) < 0.05 && Math.Abs(l.Z - z) < 0.5)
{
if (kind != RynthAiDungeonPathApiV1.KindWalk) walk[^1] = (l.X, l.Y, l.Z, kind);
return;
}
}
walk.Add((x, y, z, kind));
}
// Runs without drops, joined at each drop (walk off its edge, land, go on).
double px = sx, py = sy, pz = sz;
Put(sx, sy, sz, RynthAiDungeonPathApiV1.KindWalk);
int runStart = 0;
for (int i = 0; i < path.Count; i++)
{
bool last = i == path.Count - 1;
bool dropNext = !last && graph.TryGetValue(path[i], out var na) && graph.TryGetValue(path[i + 1], out var nb) && IsDropEdge(na, nb);
if (!last && !dropNext) continue;
var run = path.GetRange(runStart, i - runStart + 1);
double tx, ty, tz, lx = 0, ly = 0, lz = 0;
if (last) { tx = gx; ty = gy; tz = gz; }
else
{
DungeonNavNode a = graph[path[i]], b = graph[path[i + 1]];
DropEdgePoints(geo, a, b, out tx, out ty, out tz, out lx, out ly, out lz);
}
NavRouteParser route = BuildNavRoute(run, graph, NsOf(ty), EwOf(tx), geo, keepOut, NsOf(py), EwOf(px), pz, tz);
foreach (NavPoint p in route.Points)
{
if (p.Type != NavPointType.Point && p.Type != NavPointType.Checkpoint) continue;
Put(XOf(p.EW), YOf(p.NS), p.Z * 240.0, RynthAiDungeonPathApiV1.KindWalk);
}
if (last) { Put(gx, gy, gz, RynthAiDungeonPathApiV1.KindWalk); break; }
Put(tx, ty, tz, RynthAiDungeonPathApiV1.KindDrop);
Put(lx, ly, lz, RynthAiDungeonPathApiV1.KindWalk);
px = lx; py = ly; pz = lz;
runStart = i + 1;
}
if (walk.Count < 2) { result = RynthAiDungeonPathApiV1.ResultNoPath; return null; }
result = RynthAiDungeonPathApiV1.ResultOk;
return walk;
}
/// <summary>
/// Where a drop from <paramref name="a"/> down to <paramref name="b"/> is walked off (the opening's
/// centre when the map geometry has it, else halfway between the cells, at a's height) and where
/// you land (a little past it towards b, at b's height).
/// </summary>
internal static void DropEdgePoints(DungeonGeometry? geo, DungeonNavNode a, DungeonNavNode b,
out double ex, out double ey, out double ez, out double lx, out double ly, out double lz)
{
double ax = XOf(a.EW), ay = YOf(a.NS), bx = XOf(b.EW), by = YOf(b.NS);
if (geo != null && geo.TryGetDoorway(a.CellId, b.CellId, out DungeonDoorway d)) { ex = d.X; ey = d.Y; }
else { ex = (ax + bx) / 2; ey = (ay + by) / 2; }
ez = a.Z;
double hx = bx - ax, hy = by - ay, hl = Math.Sqrt(hx * hx + hy * hy);
if (hl > 1e-3) { lx = ex + hx / hl * DropRunOffMeters; ly = ey + hy / hl * DropRunOffMeters; }
else { lx = ex; ly = ey; }
lz = b.Z;
}
}

View file

@ -2,6 +2,7 @@ using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;
using System.Globalization;
using RynthCore.Plugin.RynthAi.ItemTool;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.Shared;
@ -28,6 +29,8 @@ namespace RynthCore.Plugin.RynthAi;
// chest set | key | start | stop | status | clear
// relock <seconds> (also "chest relock"): "Chest re-lock wait (s)", saved in the profile (2026-11-05)
// giveitem | givetarget | give | givestop | givestatus | clear
// giveamount <units, 0 = all> | giveevery <seconds, 0 = one round>: how a give goes (2026-11-15; this
// session only, like the picks)
// stop (both)
//
// Threads: a chat command arrives on AC's thread and the panel's on the engine pump, but the tick
@ -133,7 +136,7 @@ public sealed partial class RynthAiPlugin
case "":
case "status":
ChatLine("[RynthAi] Item Tool - " + _chestKey!.Status + " | " + _quickGive!.Status);
ChatLine("[RynthAi] /ra itemtool chest set|key|start|stop|status /ra itemtool relock <seconds> and /ra itemtool giveitem|givetarget|give|givestop|givestatus");
ChatLine("[RynthAi] /ra itemtool chest set|key|start|stop|status /ra itemtool relock <seconds> and /ra itemtool giveitem|givetarget|give|givestop|givestatus /ra itemtool giveamount <units, 0 = all> /ra itemtool giveevery <seconds, 0 = once>");
return;
case "stop":
if (_chestKey!.Running) _chestKey.Stop("stopped by you");
@ -156,6 +159,8 @@ public sealed partial class RynthAiPlugin
case "givetarget": PickGiveTarget(); return;
case "givestatus": ChatLine("[RynthAi] Quick give - " + _quickGive!.Status); return;
case "givestop": _quickGive!.Stop("stopped by you"); return;
case "giveamount": RunGiveNumber(sub, every: false); return;
case "giveevery": RunGiveNumber(sub, every: true); return;
case "give":
if (!trusted)
{
@ -170,6 +175,28 @@ public sealed partial class RynthAiPlugin
}
}
/// <summary>
/// "giveamount N" (units a round, 0 = all) and "giveevery N" (seconds between rounds, 0 = one round). Only
/// set how a give goes, so any source may; starting one stays the player's alone. A running give uses them
/// from its next give (the amount) or its next round (the interval).
/// </summary>
private void RunGiveNumber(string arg, bool every)
{
var qg = _quickGive!;
int max = every ? QuickGive.MaxEverySec : QuickGive.MaxAmount;
string what = every ? "Every (seconds between rounds; 0 = one round)" : "Amount (units a round; 0 = all of them)";
if (!int.TryParse(arg, NumberStyles.Integer, CultureInfo.InvariantCulture, out int n) || n < 0)
{
ChatLine($"[RynthAi] Quick give: {what} is {(every ? qg.EverySec : qg.Amount)}. Set it with a number 0-{max}.");
return;
}
if (every) qg.SetEvery(n); else qg.SetAmount(n);
int v = every ? qg.EverySec : qg.Amount;
ChatLine(every
? (v == 0 ? "[RynthAi] Quick give: one round (Every 0)." : $"[RynthAi] Quick give: a round every {v} s, until you stop it.")
: (v == 0 ? "[RynthAi] Quick give: gives every matching item (Amount 0)." : $"[RynthAi] Quick give: gives {v} a round."));
}
private void RunChestCommand(string sub)
{
var ck = _chestKey!;
@ -287,7 +314,9 @@ public sealed partial class RynthAiPlugin
if (_objectCache?[id] is not WorldObject wo || !IsCarriedByPlayer(id)) { ChatLine("[RynthAi] Quick give: the item must be in your pack; select it there."); return; }
if (WorldObjectCache.IsWieldedByPlayer(Host, wo)) { ChatLine("[RynthAi] Quick give: that is worn or wielded; take it off first."); return; }
qg.SetItem(id, new GiveItemKey(ItemToolWcid(id), wo.Name));
ChatLine($"[RynthAi] Quick give: item = {wo.Name} (every '{wo.Name}' in your packs will go).");
ChatLine(qg.Amount > 0
? $"[RynthAi] Quick give: item = {wo.Name} ({qg.Amount} a round)."
: $"[RynthAi] Quick give: item = {wo.Name} (every '{wo.Name}' in your packs will go).");
}
private void PickGiveTarget()
@ -424,7 +453,15 @@ public sealed partial class RynthAiPlugin
AppendJson(sb, "target", qg == null || qg.TargetId == 0 ? "" : (_giveTargetClass == (int)AcObjectClass.Player ? "PLAYER " : "") + qg.TargetName); sb.Append(',');
AppendJson(sb, "status", qg?.Status ?? "Idle."); sb.Append(',');
sb.Append("\"running\":").Append(qg?.Running == true ? "true" : "false").Append(',');
sb.Append("\"given\":").Append(qg?.Given ?? 0);
sb.Append("\"given\":").Append(qg?.Given ?? 0).Append(',');
// Amount and Every (2026-11-15); absent from an older RynthAi: the panel hides them.
sb.Append("\"amount\":").Append(qg?.Amount ?? 0).Append(',');
sb.Append("\"everySec\":").Append(qg?.EverySec ?? 0).Append(',');
sb.Append("\"amountMax\":").Append(QuickGive.MaxAmount).Append(',');
sb.Append("\"everyMax\":").Append(QuickGive.MaxEverySec).Append(',');
sb.Append("\"rounds\":").Append(qg?.Rounds ?? 0).Append(',');
sb.Append("\"units\":").Append(qg?.Units ?? 0).Append(',');
sb.Append("\"nextInSec\":").Append(qg == null ? 0 : (qg.NextRoundInMs + 999) / 1000);
sb.Append("}}");
return sb.ToString();
}
@ -626,8 +663,8 @@ public sealed partial class RynthAiPlugin
return Math.Max(1, wo.Values(LongValueKey.StackCount, 1)) < count;
}
public bool Send(int itemId, int targetId)
=> Host.GiveObjectTo(unchecked((uint)itemId), unchecked((uint)targetId), 0); // amount 0 = the whole object
public bool Send(int itemId, int targetId, int amount)
=> Host.GiveObjectTo(unchecked((uint)itemId), unchecked((uint)targetId), Math.Max(0, amount)); // amount 0 = the whole object
public int RefusalSeq()
=> Host.HasGetLastWeenieError && Host.TryGetLastWeenieError(out int seq, out _, out _, out _) ? seq : 0;

View file

@ -280,10 +280,13 @@ public sealed partial class RynthAiPlugin
_spellsUi?.Render();
_miniRemote?.Render();
_huds?.Render();
Huds.CastWarningHud.Render(); // "Out of components" pop-up
RenderTranslateWindow();
RenderLootWhyWindow();
RenderHuntPanel();
RenderDfHeightPanel();
RenderVTankImportWindow();
RenderTradeShopWindow();
}
catch (Exception ex)
{
@ -327,6 +330,7 @@ public sealed partial class RynthAiPlugin
try { _miniRemote?.Render(); }
finally { ImGui.PopStyleColor(pushedColors); }
_huds?.Render();
Huds.CastWarningHud.Render(); // "Out of components" pop-up
RenderTranslateWindow();
_navOverlay?.Render();
_itemInfoUi?.Render();
@ -334,6 +338,8 @@ public sealed partial class RynthAiPlugin
RenderLootWhyWindow();
RenderHuntPanel();
RenderDfHeightPanel();
RenderVTankImportWindow();
RenderTradeShopWindow();
}
catch (Exception ex)
{
@ -357,14 +363,16 @@ public sealed partial class RynthAiPlugin
return current != IntPtr.Zero ? current : Host.ImGuiContext;
}
/// <summary>
/// <summary>
/// RynthPluginRenderEmbed "miniremote" / "miniremote-window": the Mini Remote inside the
/// engine's RynthAi dashboard drawer, or (<paramref name="window"/>) inside the engine's Mini
/// Remote window, docked or popped out, drawn into the engine's current ImGui window (and
/// context, see <see cref="EmbedContext"/>). False (nothing drawn) until login and the HUDs
/// context, see <see cref="EmbedContext"/>). <paramref name="popped"/> is true when the
/// engine tagged the surface with ":popout". False (nothing drawn) until login and the HUDs
/// exist. Render thread.
/// </summary>
public bool RenderEmbeddedMiniRemote(bool window, out System.Numerics.Vector2 want, bool tabs = true)
public bool RenderEmbeddedMiniRemote(bool window, out System.Numerics.Vector2 want, bool tabs = true, bool popped = false)
{
want = default;
var huds = _huds;
@ -375,7 +383,7 @@ public sealed partial class RynthAiPlugin
ImGui.SetCurrentContext(EmbedContext());
try
{
want = huds.RenderEmbedded(window, tabs);
want = huds.RenderEmbedded(window, tabs, popped);
return true;
}
catch (Exception ex)

View file

@ -0,0 +1,62 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthAi.Raycasting;
using Vector3 = RynthCore.Plugin.RynthAi.Raycasting.Vector3;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
// "RynthAi.DungeonPath" v3 ObstacleAhead (2026-11-07): how high the thing in front of RynthNav's walker is,
// from the static geometry the client's dats place there (Raycasting/GeometryLoader, what line of sight uses).
// Silentkelpie: "the jump on routes should take your buffed jump into account as well as your burden ... a
// jump to get over things". Horizontal rays from the walker's feet forward, at rising heights: the lowest one
// that passes is the top of what is in the way. Pump thread (RynthNav's tick).
public sealed partial class RynthAiPlugin
{
/// <summary>The first ray's height above the feet (lower is the ground's own bumps).</summary>
internal const double ObstacleFirstRay = 0.3;
/// <summary>Rays this far apart going up.</summary>
internal const double ObstacleRayStep = 0.2;
/// <summary>The rays start this far behind the walker.</summary>
internal const double ObstacleBehind = 1.0;
internal int ObstacleAheadForPlugin(uint landcell, double x, double y, double z, double headingDeg, double ahead, double maxHeight, out double topAbove)
{
topAbove = 0;
List<BoundingVolume>? geometry = _raycast?.GeometryAt(landcell);
if (geometry == null) return RynthAiDungeonPathApiV1.ResultNoData;
return MeasureObstacle(geometry, x, y, z, headingDeg, ahead, maxHeight, out topAbove);
}
/// <summary>
/// The lowest height above (x, y, z) at which a ray <paramref name="ahead"/> long, heading
/// <paramref name="headingDeg"/>, passes every volume: ResultOk with it (or maxHeight + 1 when none up to
/// <paramref name="maxHeight"/> does), ResultNoPath when the first ray already passes. Host-free.
/// </summary>
internal static int MeasureObstacle(List<BoundingVolume> geometry, double x, double y, double z, double headingDeg, double ahead, double maxHeight, out double topAbove)
{
topAbove = 0;
if (geometry.Count == 0) return RynthAiDungeonPathApiV1.ResultNoPath;
ahead = Math.Clamp(ahead, 0.5, 20.0);
maxHeight = Math.Clamp(maxHeight, ObstacleFirstRay, 12.0);
double rad = headingDeg * Math.PI / 180.0;
double ux = Math.Sin(rad), uy = Math.Cos(rad);
// From a metre behind the feet: the ray test leaves out hits within 0.5 m of its start, and a walker
// stuck against a wall stands about that close to it.
float sx = (float)(x - ux * ObstacleBehind), sy = (float)(y - uy * ObstacleBehind);
float ex = (float)(x + ux * ahead), ey = (float)(y + uy * ahead);
for (double h = ObstacleFirstRay; h <= maxHeight + 1e-6; h += ObstacleRayStep)
{
var from = new Vector3(sx, sy, (float)(z + h));
var to = new Vector3(ex, ey, (float)(z + h));
if (!RaycastEngine.IsLinearPathBlocked(from, to, geometry))
{
if (h <= ObstacleFirstRay + 1e-6) return RynthAiDungeonPathApiV1.ResultNoPath;
topAbove = h;
return RynthAiDungeonPathApiV1.ResultOk;
}
}
topAbove = maxHeight + 1;
return RynthAiDungeonPathApiV1.ResultOk;
}
}

View file

@ -0,0 +1,147 @@
using System;
using System.Collections.Generic;
using RynthCore.Loot;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi;
// Buying an item a quest hands over (2026-11-08, Silentkelpie: "for the dynamic quests, it should also auto hand in
// the parchment and if one does not have any it should buy one from a vendor"). RynthOracle sends, through the
// "questloot" broker action:
// "buy <item>" one <item> from a vendor near you (within QuestVendorRange): the vendors are opened in turn,
// a Scribe or a shop first, then the nearest (ACE walks you to each), until one sells it; one is
// bought. Then "[RynthAi] Quest: bought <item>." once it is in the pack, or "[RynthAi] Quest:
// couldn't buy <item>: <why>." (RynthOracle's Dynamic Stamps hand-in reads both).
// Carried already: "bought <item> (already in your pack)." at once. Pump thread.
public sealed partial class RynthAiPlugin
{
/// <summary>How near a vendor must be (metres).</summary>
internal const double QuestVendorRange = 80.0;
internal const int QuestVendorMax = 6;
private const long QuestVendorOpenMs = 15000, QuestBuyConfirmMs = 8000, QuestVendorNextMs = 600;
internal const string QuestBoughtPrefix = "[RynthAi] Quest: bought ";
internal const string QuestBuyFailPrefix = "[RynthAi] Quest: couldn't buy ";
private enum QuestBuyState { Idle, Open, Wait, Bought }
private QuestBuyState _qbState;
private string _qbItem = "";
private readonly List<(uint Id, string Name)> _qbVendors = new();
private int _qbIndex;
private long _qbAt;
private string _qbFrom = "";
/// <summary>"buy &lt;item&gt;": starts the vendor walk (see the file's head).</summary>
private (bool Ok, string Text)? TryQuestBuy(string line)
{
line = (line ?? "").Trim();
if (!line.StartsWith("buy ", StringComparison.OrdinalIgnoreCase) && !line.Equals("buy", StringComparison.OrdinalIgnoreCase)) return null;
string item = line.Length > 3 ? line.Substring(3).Trim().Trim('"') : "";
if (item.Length == 0) return (false, "[RynthAi] questloot buy <item> (RynthOracle's Dynamic Stamps send this)");
if (_objectCache == null) return Fail(item, "the object cache isn't ready");
if (!Host.HasVendorTrade || !Host.HasUseObject) return Fail(item, "vendor trading needs a newer RynthCore engine");
if (GiveCandidates(n => QuestItemNameMatches(n, item)).Count > 0)
{
ChatLine($"{QuestBoughtPrefix}{item} (already in your pack).");
return (true, $"[RynthAi] Quest: {item} is in your pack already.");
}
_qbVendors.Clear();
var near = new List<(WorldObject Wo, int Rank, double Dist)>();
foreach (WorldObject wo in _objectCache.GetLandscapeObjects())
{
if (wo.ObjectClass != AcObjectClass.Vendor) continue;
double d = _playerId != 0 ? _objectCache.Distance((int)_playerId, wo.Id) : double.MaxValue;
if (d > QuestVendorRange) continue;
near.Add((wo, VendorRank(wo.Name), d));
}
near.Sort((a, b) => a.Rank != b.Rank ? a.Rank.CompareTo(b.Rank) : a.Dist.CompareTo(b.Dist));
foreach (var v in near)
{
_qbVendors.Add((unchecked((uint)v.Wo.Id), v.Wo.Name));
if (_qbVendors.Count >= QuestVendorMax) break;
}
if (_qbVendors.Count == 0) return Fail(item, $"no vendor within {QuestVendorRange:F0} m of you (a town's Scribe or shop sells it)");
_qbItem = item;
_qbIndex = 0;
_qbState = QuestBuyState.Open;
_qbAt = 0;
return (true, $"[RynthAi] Quest: looking for {item} at {_qbVendors.Count} vendor(s) near you.");
}
private (bool, string) Fail(string item, string why)
{
ChatLine($"{QuestBuyFailPrefix}{item}: {why}.");
return (false, $"[RynthAi] Quest: {item}: {why}.");
}
/// <summary>A Scribe first (they sell parchment), then a shop, then the others.</summary>
internal static int VendorRank(string? name)
{
string n = name ?? "";
if (n.IndexOf("Scribe", StringComparison.OrdinalIgnoreCase) >= 0) return 0;
foreach (string w in new[] { "Shopkeep", "Shopkeeper", "Provisioner", "Trader", "Merchant", "Peddler", "Grocer" })
if (n.IndexOf(w, StringComparison.OrdinalIgnoreCase) >= 0) return 1;
return 2;
}
/// <summary>Each tick: the vendor walk's next move. Pump thread.</summary>
private void TickQuestBuy()
{
if (_qbState == QuestBuyState.Idle) return;
long now = Environment.TickCount64;
switch (_qbState)
{
case QuestBuyState.Open:
if (now < _qbAt) return;
if (_qbIndex >= _qbVendors.Count) { EndQuestBuy(false, $"none of the {_qbVendors.Count} vendor(s) near you sells it"); return; }
var (id, name) = _qbVendors[_qbIndex];
Host.UseFor(id, "Quest", $"quest: open {name} to buy {_qbItem}", UseKind.Asked);
_qbAt = now;
_qbState = QuestBuyState.Wait;
return;
case QuestBuyState.Wait:
{
var (vid, vname) = _qbVendors[_qbIndex];
if (Host.TryGetVendorInfo(out VendorInfo info) && info.VendorId == vid && info.ItemCount > 0)
{
VendorItem? want = null;
foreach (VendorItem it in Host.GetVendorItems())
if (QuestItemNameMatches(it.Name, _qbItem)) { want = it; break; }
if (want == null) { NextVendor(now); return; }
uint sent = Host.VendorBuy(vid, new List<VendorTradeEntryNative> { new(want.ObjectId, 1) });
if (sent == 0) { EndQuestBuy(false, $"{vname} sells it, but the buy could not be sent"); return; }
Log($"[Quest] buying 1 x {want.Name} from {vname} 0x{vid:X8}");
_qbFrom = vname;
_qbAt = now;
_qbState = QuestBuyState.Bought;
return;
}
if (now - _qbAt > QuestVendorOpenMs) NextVendor(now); // never opened (out of reach, busy)
return;
}
case QuestBuyState.Bought:
if (GiveCandidates(n => QuestItemNameMatches(n, _qbItem)).Count > 0) { EndQuestBuy(true, ""); return; }
if (now - _qbAt > QuestBuyConfirmMs) EndQuestBuy(false, $"{_qbFrom} didn't sell it (pyreals?)");
return;
}
}
private void NextVendor(long now)
{
_qbIndex++;
_qbAt = now + QuestVendorNextMs;
_qbState = QuestBuyState.Open;
}
private void EndQuestBuy(bool ok, string why)
{
string item = _qbItem;
_qbState = QuestBuyState.Idle;
_qbVendors.Clear();
ChatLine(ok ? $"{QuestBoughtPrefix}{item}." : $"{QuestBuyFailPrefix}{item}: {why}.");
}
}

View file

@ -0,0 +1,223 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
// A quest run inside a dungeon (2026-11-07, Silentkelpie: "when creating a route for a quest and enters a portal
// to a dungeon, look if a map is loaded if so use that map to then create a route to continue the quest inside
// the dungeon, to fight, pickup items, unlock doors, open doors etc."). RynthOracle's Run this quest sends, through
// the "questloot" broker action, once the character is in a dungeon:
// "dungeon patrol [| key | key]" the dungeon's map (its cells from the client's dats, as the Dungeon
// Patrol and /ra dunnav use) walked all over with the macro on:
// fighting, looting (the quest's loot profile), opening doors
// "dungeon goto <NS> <EW> [| key | key]" the map's walk to that point (/ra dunnav), the same way
// "dungeon stop" the walk ends; the macro and Open Doors go back as they were
// "dungeon enter" outdoors at a step's place ("Enter the Keep at ..."): the nearest
// portal within QuestPortalRange is used
// The keys are the quest's (a locked door tries them first, then any carried key, then lockpicks:
// DoorInteractionController). No map (no dungeon cells here, the dats not loaded): the reply says so, and the
// run waits for the player. Pump thread.
public sealed partial class RynthAiPlugin
{
private bool _questDungeonActive;
private readonly List<string> _questDungeonKeys = new();
private bool? _questDungeonMacroWas, _questDungeonDoorsWas;
/// <summary>A quest dungeon verb's answer, or null when <paramref name="line"/> isn't one.</summary>
private (bool Ok, string Text)? TryQuestDungeon(string line)
{
line = (line ?? "").Trim();
if (!line.StartsWith("dungeon", StringComparison.OrdinalIgnoreCase)) return null;
string rest = line.Length > 7 ? line.Substring(7).Trim() : "";
string[] parts = rest.Split('|');
string[] words = parts[0].Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries);
string verb = words.Length > 0 ? words[0].ToLowerInvariant() : "";
var keys = new List<string>();
for (int i = 1; i < parts.Length; i++) if (parts[i].Trim().Length > 0) keys.Add(parts[i].Trim());
var settings = _dashboard?.Settings;
if (settings == null) return (false, "[RynthAi] Quest: RynthAi's settings aren't loaded yet.");
if (verb == "stop") return QuestDungeonStop();
if (verb == "enter")
{
// "enter near [hints]": only a portal right here (QuestPortalNearRange), no scan (2026-11-10: a step's
// coordinates at a dungeon's portal, the next step inside it).
bool near = words.Length > 1 && words[1].Equals("near", StringComparison.OrdinalIgnoreCase);
int from = near ? 2 : 1;
return QuestDungeonEnter(words.Length > from ? string.Join(" ", words, from, words.Length - from) : "", near: near);
}
if (verb is not ("patrol" or "goto" or "to"))
return (false, "[RynthAi] questloot dungeon patrol | goto <NS> <EW> | to <cell> | stop [| key | key] (RynthOracle's quest run sends these)");
if (!Host.TryGetPlayerPose(out uint cell, out _, out _, out _, out _, out _, out _, out _) || (cell & 0xFFFF) < 0x0100)
return (false, "[RynthAi] Quest: not inside a dungeon.");
if (_raycast?.GeometryLoader?.CellDat is not { IsLoaded: true } cellDat)
return (false, "[RynthAi] Quest: no map of this dungeon yet (the client's dats aren't loaded): walk it yourself, then Next.");
// An indoor cell in a town's landblock is a building, not a dungeon (2026-11-07, 21:33 at the Tusker Burrow).
if (_navPlanner != null && !_navPlanner.IsDungeonLandblock(cell >> 16, cellDat))
return (false, "[RynthAi] Quest: in a building, not a dungeon: nothing to patrol here.");
// Remember how the macro and Open Doors were, once per run in the dungeon.
if (!_questDungeonActive)
{
_questDungeonMacroWas = settings.IsMacroRunning;
_questDungeonDoorsWas = settings.OpenDoors;
}
_questDungeonActive = true;
_questDungeonKeys.Clear();
_questDungeonKeys.AddRange(keys);
settings.OpenDoors = true;
string keyNote = keys.Count > 0 ? $"; keys first on locked doors: {string.Join(", ", keys)}" : "";
if (verb == "to")
{
// "dungeon to 009C0270": the map's walk to that cell (2026-11-11: a quest's person inside a dungeon or the
// Bur; RynthNav's arrival names the cell). Its centre on the map, as the patrol's graph has it.
if (words.Length < 2 || !uint.TryParse(words[1], System.Globalization.NumberStyles.HexNumber, System.Globalization.CultureInfo.InvariantCulture, out uint toCell))
return (false, "[RynthAi] questloot dungeon to <cell, 8 hex digits>");
if (toCell >> 16 != cell >> 16)
return (false, $"[RynthAi] Quest: cell {toCell:X8} isn't in this dungeon (0x{cell >> 16:X4}).");
var graph = DungeonPathfinder.GetGraph(cell >> 16, cellDat);
if (graph == null || !graph.TryGetValue(toCell, out DungeonNavNode? node))
return (false, $"[RynthAi] Quest: cell {toCell:X8} isn't on this dungeon's map.");
string ns = node.NS.ToString("0.####", System.Globalization.CultureInfo.InvariantCulture);
string ew = node.EW.ToString("0.####", System.Globalization.CultureInfo.InvariantCulture);
HandleDungeonNavCommand(new[] { "/ra", "dunnav", ns, ew });
return (true, $"[RynthAi] Quest: walking the dungeon's map to cell {toCell:X8}, fighting and looting on the way, opening doors{keyNote}.");
}
if (verb == "goto")
{
if (words.Length < 3) return (false, "[RynthAi] questloot dungeon goto <NS> <EW>");
HandleDungeonNavCommand(new[] { "/ra", "dunnav", words[1], words[2] });
return (true, $"[RynthAi] Quest: walking the dungeon's map to {words[1]}, {words[2]}, fighting and looting on the way, opening doors{keyNote}.");
}
HandleDungeonNavPatrol();
return (true, $"[RynthAi] Quest: patrolling dungeon 0x{cell >> 16:X4} with its map: fighting, looting the quest's items, opening doors{keyNote}. The quest's stamp or Next ends it.");
}
/// <summary>How near the portal of an "Enter ..." step must be (metres).</summary>
internal const double QuestPortalRange = 60.0;
// 2026-11-08 ("when you get to the portal spot it should scan to find it and walk to enter the portal"): a portal
// not in sight yet (drawn a moment after RynthNav arrives, or just out of range) is looked for again every
// QuestPortalRetryMs for QuestPortalScanMs; the one found is used (ACE walks you to it and in).
private string? _questPortalHints;
private long _questPortalNextAt, _questPortalUntil;
internal const long QuestPortalRetryMs = 1500, QuestPortalScanMs = 20000;
internal const double QuestPortalNearRange = 15.0;
// 2026-11-10 ("the route isn't going in the portal like it should"): one use of the portal could be lost (a fight
// stops ACE's walk to it, the portal still out of reach). Used again every QuestPortalUseAgainMs while the
// character is still in the same landblock, up to QuestPortalUses times.
private uint _questPortalUseId, _questPortalUseLb;
private int _questPortalUses;
private long _questPortalUseAt;
internal const long QuestPortalUseAgainMs = 7000;
internal const int QuestPortalUses = 4;
/// <summary>Each tick: the portal scan, when one is due. Pump thread.</summary>
private void TickQuestPortalScan()
{
TickQuestPortalUse();
if (_questPortalHints == null) return;
long now = Environment.TickCount64;
if (now < _questPortalNextAt) return;
string hints = _questPortalHints;
_questPortalHints = null;
var (ok, text) = QuestDungeonEnter(hints, scanning: now < _questPortalUntil);
if (_questPortalHints == null) ChatLine(text); // found it, or the scan ran out (quiet while scanning)
}
/// <summary>
/// "dungeon enter [word || word]": the nearest portal within QuestPortalRange, one whose name has a word
/// the step gives ("Hidden", "Keep") before the others (2026-11-07: RynthNav arrives a few metres short).
/// </summary>
/// <summary>The portal used for the step: used again while we're still here (see QuestPortalUseAgainMs).</summary>
private void TickQuestPortalUse()
{
if (_questPortalUseId == 0) return;
long now = Environment.TickCount64;
if (now - _questPortalUseAt < QuestPortalUseAgainMs) return;
if (!Host.TryGetPlayerPose(out uint cell, out _, out _, out _, out _, out _, out _, out _) || (cell >> 16) != _questPortalUseLb)
{
_questPortalUseId = 0; // through it (or teleported anyway)
return;
}
if (_questPortalUses >= QuestPortalUses || _objectCache?.GetLandscapeObjects().Any(w => unchecked((uint)w.Id) == _questPortalUseId) != true)
{
ChatLine($"[RynthAi] Quest: the portal wasn't taken after {_questPortalUses} tries; walk into it, or Next.");
_questPortalUseId = 0;
return;
}
_questPortalUses++;
_questPortalUseAt = now;
Host.UseFor(_questPortalUseId, "Quest", $"quest run: the step's portal again (try {_questPortalUses})", UseKind.Asked);
}
private (bool Ok, string Text) QuestDungeonEnter(string hints, bool scanning = false, bool near = false)
{
if (_objectCache == null) return (false, "[RynthAi] Quest: the object cache isn't ready.");
var words = new List<string>();
foreach (string h in (hints ?? "").Replace("||", "\u0001").Split('\u0001'))
if (h.Trim().Length >= 3) words.Add(h.Trim());
WorldObject? best = null;
double bestDist = double.MaxValue;
// How many hint words match the portal name (2026-11-22): Town Network has three "Stronghold"
// portals (CH/EW/RB). Prefer "Celestial Hand Stronghold" (score 3) over a bare "Stronghold" (1).
int bestScore = -1;
foreach (WorldObject wo in _objectCache.GetLandscapeObjects())
{
if (wo.ObjectClass != RynthCore.Loot.AcObjectClass.Portal) continue;
double d = _playerId != 0 ? _objectCache.Distance((int)_playerId, wo.Id) : double.MaxValue;
if (d > (near ? QuestPortalNearRange : QuestPortalRange)) continue;
int score = 0;
foreach (string w in words)
if (wo.Name.Contains(w, StringComparison.OrdinalIgnoreCase)) score++;
if (best != null && (score < bestScore || (score == bestScore && d >= bestDist))) continue;
best = wo; bestDist = d; bestScore = score;
}
if (best == null && near) return (true, "[RynthAi] Quest: no portal right here.");
if (best == null)
{
// Not in sight yet: scan again for a while (the first try starts the clock).
long now = Environment.TickCount64;
if (!scanning) _questPortalUntil = now + QuestPortalScanMs;
if (now < _questPortalUntil)
{
_questPortalHints = hints ?? "";
_questPortalNextAt = now + QuestPortalRetryMs;
return (true, $"[RynthAi] Quest: looking for the portal here (scanning for {QuestPortalScanMs / 1000} s).");
}
return (false, $"[RynthAi] Quest: no portal within {QuestPortalRange:F0} m here to go in by.");
}
_questPortalHints = null;
Host.UseFor(unchecked((uint)best.Id), "Quest", "quest run: the step goes in by this portal", UseKind.Asked);
_questPortalUseId = unchecked((uint)best.Id);
_questPortalUses = 1;
_questPortalUseAt = Environment.TickCount64;
_questPortalUseLb = Host.TryGetPlayerPose(out uint pc, out _, out _, out _, out _, out _, out _, out _) ? pc >> 16 : 0;
return (true, $"[RynthAi] Quest: going in by {best.Name} ({bestDist:F0} m).");
}
private (bool Ok, string Text) QuestDungeonStop()
{
_questPortalHints = null; // a portal scan ends with the run's dungeon part
_questPortalUseId = 0;
if (!_questDungeonActive) return (true, "[RynthAi] Quest: no dungeon walk to stop.");
_questDungeonActive = false;
_questDungeonKeys.Clear();
var settings = _dashboard?.Settings;
if (settings != null)
{
if (_dunPatrolActive) StopPatrolForServer();
else { settings.EnableNavigation = false; settings.CurrentRoute = new LegacyUi.NavRouteParser(); _navigationEngine?.Stop(); }
if (_questDungeonDoorsWas is bool doors) settings.OpenDoors = doors;
if (_questDungeonMacroWas == false) settings.IsMacroRunning = false;
}
_questDungeonMacroWas = _questDungeonDoorsWas = null;
return (true, "[RynthAi] Quest: the dungeon walk ended; the macro and Open Doors are as they were.");
}
}

View file

@ -0,0 +1,100 @@
using System;
using System.Collections.Generic;
using RynthCore.Loot.Editing;
namespace RynthCore.Plugin.RynthAi;
// Quest loot profiles (2026-11-05): a loot profile per wiki quest, built from LootProfiles\base-quest-dynamic.utl
// and the quest's items (RynthCore.LootSdk QuestLootProfiles). RynthOracle's quest guide sends them through the
// "questloot" broker action, as it does the quest loot list:
// "build <quest>|<item>|<item>..." writes LootProfiles\Quests\<quest>.utl
// "profile <quest>|<item>|<item>..." writes it and makes it the loot profile in use (Run this quest)
// "profile off" back to the loot profile that was in use before
// "/ra questloot profile off" does the last by hand. Pump thread.
public sealed partial class RynthAiPlugin
{
// The loot profile in use before a quest's profile took over ("" for none); null while no quest profile is in use.
private string? _questProfilePrevious;
private string _questProfileQuest = "";
/// <summary>The loot profile folder (RynthAi's LootProfiles); the tests point it at a temp folder.</summary>
internal static string QuestLootFolder = Loot.LootEditorBridge.LootFolder;
/// <summary>A quest loot profile verb's answer, or null when <paramref name="line"/> isn't one (the quest loot list's).</summary>
private (bool Ok, string Text)? TryQuestLootProfile(string line)
{
line = (line ?? "").Trim();
int sp = line.IndexOf(' ');
string verb = (sp < 0 ? line : line.Substring(0, sp)).ToLowerInvariant();
string rest = sp < 0 ? "" : line.Substring(sp + 1).Trim();
if (verb is not ("build" or "profile")) return null;
if (verb == "profile" && (rest.Length == 0 || rest.Equals("off", StringComparison.OrdinalIgnoreCase)))
return rest.Length == 0 ? QuestProfileStatus() : QuestProfileOff();
string[] parts = rest.Split('|');
string quest = parts[0].Trim();
var items = new List<string>();
for (int i = 1; i < parts.Length; i++)
if (parts[i].Trim().Length > 0) items.Add(parts[i].Trim());
// No items (a kill or a fetch the wiki lists none for): the quest's profile is base-quest-dynamic alone (2026-11-07).
if (quest.Length == 0)
return (false, $"[RynthAi] questloot {verb} <quest>|<item>|<item>... (RynthOracle's quest guide sends these)");
string path;
int rules;
string note;
try { path = QuestLootProfiles.Write(QuestLootFolder, quest, items, out rules, out note); }
catch (Exception ex) { return (false, $"[RynthAi] Quest loot profile for {quest}: not written ({ex.Message})."); }
string file = System.IO.Path.GetFileName(path);
string extra = note.Length > 0 ? $" ({note})" : "";
if (verb == "build")
return (true, $"[RynthAi] Quest loot profile written: Quests\\{file}, {rules} quest item(s){extra}.");
var settings = _dashboard?.Settings;
if (settings == null) return (false, "[RynthAi] Quest loot profile: RynthAi's settings aren't loaded yet.");
string current = (settings.CurrentLootPath ?? "").Trim().Trim('"');
// The first quest profile remembers what was in use; switching quests keeps that.
if (_questProfilePrevious == null && !QuestLootProfiles.IsQuestProfile(current, QuestLootFolder))
_questProfilePrevious = current;
_questProfilePrevious ??= "";
_questProfileQuest = quest;
settings.CurrentLootPath = path;
string back = _questProfilePrevious.Length > 0 ? System.IO.Path.GetFileName(_questProfilePrevious) : "no loot profile";
return (true, $"[RynthAi] Loot profile for {quest}: Quests\\{file} ({rules} quest item(s) and {QuestTemplateName()}){extra}. "
+ $"Back to {back} when the run ends, or /ra questloot profile off.");
}
private (bool Ok, string Text) QuestProfileOff()
{
var settings = _dashboard?.Settings;
if (settings == null) return (false, "[RynthAi] Quest loot profile: RynthAi's settings aren't loaded yet.");
string current = (settings.CurrentLootPath ?? "").Trim().Trim('"');
if (_questProfilePrevious == null)
{
return QuestLootProfiles.IsQuestProfile(current, QuestLootFolder)
? (false, $"[RynthAi] The loot profile is a quest's ({System.IO.Path.GetFileName(current)}), but which one was in use before isn't known (a restart since): pick one in the dashboard.")
: (true, "[RynthAi] No quest loot profile is in use.");
}
string previous = _questProfilePrevious;
string quest = _questProfileQuest;
_questProfilePrevious = null;
_questProfileQuest = "";
// Only put it back while the quest's profile is still the one in use (the player may have picked another).
if (!QuestLootProfiles.IsQuestProfile(current, QuestLootFolder))
return (true, $"[RynthAi] Quest loot profile for {quest} ended; the loot profile in use ({System.IO.Path.GetFileName(current)}) was picked since, so it stays.");
settings.CurrentLootPath = previous;
return (true, previous.Length > 0
? $"[RynthAi] Quest loot profile for {quest} ended: back to {System.IO.Path.GetFileName(previous)}."
: $"[RynthAi] Quest loot profile for {quest} ended: no loot profile, as before.");
}
private (bool Ok, string Text) QuestProfileStatus()
{
string current = (_dashboard?.Settings?.CurrentLootPath ?? "").Trim().Trim('"');
if (_questProfilePrevious != null)
return (true, $"[RynthAi] Quest loot profile in use: {System.IO.Path.GetFileName(current)} ({_questProfileQuest}); /ra questloot profile off goes back.");
return (true, $"[RynthAi] No quest loot profile in use. RynthOracle's Run this quest builds one from {QuestTemplateName()} (/ro lootprofiles builds every quest's).");
}
private static string QuestTemplateName() => System.IO.Path.GetFileNameWithoutExtension(QuestLootProfiles.TemplateFileName);
}

View file

@ -0,0 +1,258 @@
using System;
using System.Collections.Generic;
using RynthCore.Loot;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
// The quest run's NPCs (2026-11-07). RynthOracle's Run this quest goes to the person a wiki step names
// ("Talk to Xsao Lann in Fort Tethana", "Return the collar to Xsao") and, there, sends through the
// "questloot" broker action:
// "talk <name> || <name> ..." use the first of them standing near you (talk to them)
// "handin <name> || <name> ... | <item> | <item>" give them every carried item of those names (AC's give,
// the give queue); none carried: talk to them instead
// The names are the step's candidates; the NPC that answers one best is taken (Mara al-Luq herself before a
// "Yaraq Guard" for the name Yaraq), only an NPC, a vendor or a creature that can't be attacked, within QuestNpcRange
// (a portal or a player of that name never is). An item's name matches as the wiki writes it or without
// a note in brackets at the end ("Darling's Collar (Quest Item)" is "Darling's Collar" in the game).
// RynthAi's own items, attuned and equipped ones are never handed over.
// "have <item> | <item> ..." (2026-11-08) each one already carried says "Quest: got <item>
// (already in your pack)." for the run's step; the others are
// picked up off corpses and the ground (the quest loot list:
// GroundLootController takes quest items with Ground Loot off)
// Every quest item picked up says "[RynthAi] Quest: got <name>." (NoteQuestItemGot): the run's item steps end on it.
// Pump thread.
public sealed partial class RynthAiPlugin
{
/// <summary>How near the NPC must be (metres).</summary>
internal const double QuestNpcRange = 60.0;
/// <summary>
/// A talk / hand-in whose NPC wasn't in sight yet (2026-11-07: RynthNav arrives before the NPC is
/// drawn, or a few metres short): tried again every QuestNpcRetryMs for QuestNpcRetryForMs.
/// </summary>
private string _questNpcPending = string.Empty;
private long _questNpcNextAt, _questNpcUntil;
internal const long QuestNpcRetryMs = 2000, QuestNpcRetryForMs = 20000;
// While RynthAi walks a dungeon for the run (a person inside it, 2026-11-11), looked for this long: the walk
// there takes minutes, and the person is met on the way or at its end.
internal const long QuestNpcDungeonRetryForMs = 240000;
/// <summary>Each tick: the pending talk / hand-in, tried again when it is due. Pump thread.</summary>
private void TickQuestNpcRetry()
{
if (_questNpcPending.Length == 0) return;
long now = Environment.TickCount64;
if (now < _questNpcNextAt) return;
string line = _questNpcPending;
bool last = now >= _questNpcUntil;
_questNpcPending = string.Empty;
var r = TryQuestNpc(line, retrying: !last);
if (r is { } res && (res.Ok || last)) ChatLine(res.Text);
}
/// <summary>A quest NPC verb's answer, or null when <paramref name="line"/> isn't one.</summary>
private (bool Ok, string Text)? TryQuestNpc(string line) => TryQuestNpc(line, retrying: false);
private (bool Ok, string Text)? TryQuestNpc(string line, bool retrying)
{
line = (line ?? "").Trim();
int sp = line.IndexOf(' ');
string verb = (sp < 0 ? line : line.Substring(0, sp)).ToLowerInvariant();
string rest = sp < 0 ? "" : line.Substring(sp + 1).Trim();
if (verb is not ("talk" or "handin" or "have")) return null;
if (verb == "have") return QuestHave(rest);
ParseQuestNpcLine(rest, out List<string> names, out List<string> items);
if (names.Count == 0)
return (false, "[RynthAi] questloot talk <name> || <name> | questloot handin <name> || <name> | <item> | <item> (RynthOracle's quest run sends these)");
if (_objectCache == null) return (false, "[RynthAi] Quest: the object cache isn't ready.");
WorldObject? npc = FindQuestNpc(names);
if (npc == null)
{
// Not in sight yet: look again for a while (the first try starts the clock).
long now = Environment.TickCount64;
long window = _questDungeonActive ? QuestNpcDungeonRetryForMs : QuestNpcRetryForMs;
if (!retrying) _questNpcUntil = now + window;
if (now < _questNpcUntil)
{
_questNpcPending = line;
_questNpcNextAt = now + QuestNpcRetryMs;
return (true, _questDungeonActive
? $"[RynthAi] Quest: looking for {string.Join(" or ", names)} on the way through the dungeon (for up to {window / 60000} min)."
: $"[RynthAi] Quest: looking for {string.Join(" or ", names)} (trying for {window / 1000} s).");
}
_questNpcUntil = 0;
return (false, $"[RynthAi] Quest: no {string.Join(" or ", names)} near you to {(verb == "talk" ? "talk to" : "hand the items to")}.");
}
_questNpcPending = string.Empty;
_questNpcUntil = 0;
// Met on a dungeon walk: the walk stops so the server's own walk to them (the talk, the give) isn't fought.
if (_questDungeonActive)
{
Log($"[Quest] {npc.Name} found on the dungeon walk: the walk stops for the {(verb == "talk" ? "talk" : "hand-in")}");
QuestDungeonStop();
}
if (verb == "handin" && items.Count > 0)
{
var given = new List<string>();
var seen = new HashSet<int>();
foreach (string item in items)
{
foreach (WorldObject wo in GiveCandidates(n => QuestItemNameMatches(n, item)))
{
if (!seen.Add(wo.Id)) continue;
string? why = ItemProtectionReason(wo, includeLootKeep: false);
if (why != null) { Log($"[Quest] not handing 0x{(uint)wo.Id:X8} '{wo.Name}' to {npc.Name}: {why}"); continue; }
EnqueueGive((uint)wo.Id, (uint)npc.Id, 0); // the whole stack
Log($"[Quest] queued 0x{(uint)wo.Id:X8} '{wo.Name}' -> {npc.Name}");
given.Add(wo.Name);
}
}
if (given.Count > 0)
return (true, $"[RynthAi] Quest: handing {string.Join(", ", given)} to {npc.Name}.");
// Nothing of the quest's carried: talking is what's left to do there.
Host.UseFor((uint)npc.Id, "Quest", "quest talk", UseKind.Asked);
return (true, $"[RynthAi] Quest: none of {string.Join(", ", items)} is in your pack; talking to {npc.Name}.");
}
Host.UseFor((uint)npc.Id, "Quest", "quest talk", UseKind.Asked);
return (true, $"[RynthAi] Quest: talking to {npc.Name}.");
}
/// <summary>
/// "have item | item": the ones carried say so ("Quest: got X (already in your pack).", a line each, for
/// RynthOracle's run); the reply names the rest, which the quest loot list picks up.
/// </summary>
private (bool Ok, string Text) QuestHave(string rest)
{
var items = new List<string>();
foreach (string part in (rest ?? "").Replace("||", "|").Split('|'))
{
string it = part.Trim();
if (it.Length > 0 && !items.Exists(x => x.Equals(it, StringComparison.OrdinalIgnoreCase))) items.Add(it);
}
if (items.Count == 0) return (false, "[RynthAi] questloot have <item> | <item> (RynthOracle's quest run sends this)");
if (_objectCache == null) return (false, "[RynthAi] Quest: the object cache isn't ready.");
var missing = new List<string>();
foreach (string it in items)
{
if (GiveCandidates(n => QuestItemNameMatches(n, it)).Count > 0) ChatLine($"{QuestGotPrefix}{it} (already in your pack).");
else missing.Add(it);
}
if (missing.Count == 0) return (true, "[RynthAi] Quest: the step's items are all in your pack.");
return (true, $"[RynthAi] Quest: {string.Join(", ", missing)} not in your pack yet: picking {(missing.Count == 1 ? "it" : "them")} up off corpses and the ground near you (within {QuestGroundRange:F0} m).");
}
/// <summary>The line a quest item got starts with (RynthOracle's QuestRunner reads it).</summary>
internal const string QuestGotPrefix = "[RynthAi] Quest: got ";
/// <summary>A quest loot list item came into the pack (a corpse or the ground): say so, for the run's step.</summary>
private void NoteQuestItemGot(string? name)
{
if (!string.IsNullOrWhiteSpace(name) && QuestLootList.Wants(name)) ChatLine($"{QuestGotPrefix}{name.Trim()}.");
}
/// <summary>"A || B | item | item": the names before the first single '|', the items after it.</summary>
internal static void ParseQuestNpcLine(string rest, out List<string> names, out List<string> items)
{
names = new List<string>();
items = new List<string>();
string[] parts = (rest ?? "").Replace("||", "\u0001").Split('|');
foreach (string n in parts[0].Split('\u0001'))
if (n.Trim().Length > 0 && !names.Contains(n.Trim())) names.Add(n.Trim());
for (int i = 1; i < parts.Length; i++)
{
string it = parts[i].Replace("\u0001", "").Trim();
if (it.Length > 0 && !items.Contains(it)) items.Add(it);
}
}
/// <summary>An item's name as the game shows it against the name the wiki writes (any case; a bracketed note optional).</summary>
internal static bool QuestItemNameMatches(string gameName, string wikiName)
{
if (string.Equals(gameName, wikiName, StringComparison.OrdinalIgnoreCase)) return true;
string bare = BareQuestName(wikiName);
return bare.Length > 0 && string.Equals(BareQuestName(gameName), bare, StringComparison.OrdinalIgnoreCase);
}
private static string BareQuestName(string name)
{
name = (name ?? "").Trim();
int open = name.LastIndexOf(" (", StringComparison.Ordinal);
return open > 0 && name.EndsWith(")", StringComparison.Ordinal) ? name.Substring(0, open).Trim() : name;
}
/// <summary>
/// How well a landscape object's name answers a step's name: 3 the same, 2 the object's name starts with
/// it ("Xsao" is Xsao Lann), 1 it is a whole word of it, 0 no.
/// </summary>
internal static int QuestNpcScore(string objectName, string name)
{
if (string.Equals(objectName, name, StringComparison.OrdinalIgnoreCase)) return 3;
if (name.Length < 3) return 0;
if (objectName.StartsWith(name + " ", StringComparison.OrdinalIgnoreCase)) return 2;
int at = objectName.IndexOf(name, StringComparison.OrdinalIgnoreCase);
while (at >= 0)
{
bool startOk = at == 0 || !char.IsLetterOrDigit(objectName[at - 1]);
int end = at + name.Length;
bool endOk = end >= objectName.Length || !char.IsLetterOrDigit(objectName[end]);
if (startOk && endOk) return 1;
at = objectName.IndexOf(name, at + 1, StringComparison.OrdinalIgnoreCase);
}
return 0;
}
/// <summary>An NPC, a vendor, or a creature that can't be attacked (how AC files most quest givers).</summary>
private bool IsQuestPerson(WorldObject wo) =>
wo.ObjectClass is AcObjectClass.Npc or AcObjectClass.Vendor
|| (wo.ObjectClass == AcObjectClass.Monster && Host.HasObjectIsAttackable && !Host.ObjectIsAttackable(unchecked((uint)wo.Id)));
/// <summary>
/// The NPC the names mean: the best match over all of them (the same name before one that starts with
/// it, before a word of it; then the earlier name, then the nearest), an NPC or a vendor in range.
/// </summary>
/// <summary>
/// On a dungeon walk the person must be this near before the walk stops for them (metres): one 50 m off may be
/// behind walls or a level away, where the server's own walk to them gets stuck; the map's walk gets nearer.
/// </summary>
internal const double QuestNpcDungeonRange = 15.0;
/// <summary>RynthAi's map walk of the dungeon still has points to go (the run's "dungeon to" or "goto").</summary>
private bool QuestDungeonWalking()
{
var st = _dashboard?.Settings;
if (!_questDungeonActive || st == null || !st.EnableNavigation) return false;
var route = st.CurrentRoute;
return route != null && route.Points.Count > 0 && st.ActiveNavIndex < route.Points.Count - 1;
}
private WorldObject? FindQuestNpc(List<string> names)
{
double range = QuestDungeonWalking() ? QuestNpcDungeonRange : QuestNpcRange;
if (_objectCache == null) return null;
WorldObject? best = null;
int bestScore = 0, bestOrder = int.MaxValue;
double bestDist = double.MaxValue;
foreach (WorldObject wo in _objectCache.GetLandscapeObjects())
{
if (!IsQuestPerson(wo)) continue;
int score = 0, order = int.MaxValue;
for (int i = 0; i < names.Count; i++)
{
int sc = QuestNpcScore(wo.Name, names[i]);
if (sc > score) { score = sc; order = i; }
}
if (score == 0) continue;
double dist = _playerId != 0 ? _objectCache.Distance((int)_playerId, wo.Id) : double.MaxValue;
if (dist != double.MaxValue && dist > range) continue;
bool better = score > bestScore
|| (score == bestScore && order < bestOrder)
|| (score == bestScore && order == bestOrder && dist < bestDist);
if (better) { best = wo; bestScore = score; bestOrder = order; bestDist = dist; }
}
return best;
}
}

View file

@ -115,6 +115,8 @@ public sealed partial class RynthAiPlugin
{
Log("[RynthAi] Died — holding all actions until respawned and out of portal space.");
_combatManager?.ReleaseHeldTurn();
// A Handler-ring run-away holds autorun: never carry it through the death portal.
_combatManager?.StopRingEscape("died");
_navigationEngine?.Stop();
RynthCore.Plugin.Shared.ActionPacer.Forget("death"); // the server dropped whatever was open
RynthCore.Plugin.Shared.ActionPacer.ForgetLootJump(); // no landing to wait for after a death

View file

@ -0,0 +1,88 @@
// /ra vtimport — open the VirindiTank Import window (pick Monsters / Loot / Nav / Meta / Profiles folders).
// Settings → Game Client runs the same. /ra vtimport go imports from default VT folders without the window.
using System;
using RynthCore.Plugin.RynthAi.ProfileImport;
namespace RynthCore.Plugin.RynthAi;
public sealed partial class RynthAiPlugin
{
private VTankImportWindow? _vtImportUi;
/// <summary>Ensure the import window exists (after login / dashboard ready).</summary>
private void EnsureVTankImportWindow()
{
if (_vtImportUi != null) return;
_vtImportUi = new VTankImportWindow(
() => _dashboard?.Settings,
() => _dashboard?.CharFolder,
() => _dashboard?.RefreshSettingsProfileList(),
ChatLine,
msg => Host.Log("[RynthAi] " + msg),
() => _dashboard?.SaveSettings());
}
/// <summary>
/// /ra vtimport — open the folder-picker window.
/// /ra vtimport go [files] — import immediately from default VirindiTank roots (no window).
/// </summary>
private void HandleVTankImportCommand(string[] parts)
{
EnsureVTankImportWindow();
// "go" / "now" / "run": headless import from default folders (scripts / old behaviour).
bool go = parts.Length >= 3 && (
parts[2].Equals("go", StringComparison.OrdinalIgnoreCase)
|| parts[2].Equals("now", StringComparison.OrdinalIgnoreCase)
|| parts[2].Equals("run", StringComparison.OrdinalIgnoreCase));
if (!go)
{
_vtImportUi!.Show();
ChatLine("[RynthAi] VirindiTank Import window opened — pick Monsters, Loot, Nav, Meta and Settings profiles folders, then Import.");
return;
}
var dash = _dashboard;
if (dash == null) { ReplyFail("[RynthAi] Settings not ready."); return; }
// Optional "files" after go = copy only (no monster merge).
bool merge = !(parts.Length >= 4 && parts[3].Equals("files", StringComparison.OrdinalIgnoreCase))
&& !(parts.Length >= 3 && parts[2].Equals("files", StringComparison.OrdinalIgnoreCase));
// /ra vtimport go files OR legacy /ra vtimport files (treat as go files)
if (parts.Length >= 3 && parts[2].Equals("files", StringComparison.OrdinalIgnoreCase))
merge = false;
Host.Log("[RynthAi] VTank import: scanning default VirindiTank folders"
+ (merge ? " (loot, nav, meta, MyMonsters)." : " (loot, nav, meta files only)."));
VirindiTankProfileImporter.Result result;
try
{
result = VirindiTankProfileImporter.ImportAll(dash.Settings, mergeMonsterRules: merge);
}
catch (Exception ex)
{
ReplyFail("[RynthAi] VTank import failed: " + ex.Message);
Host.Log("[RynthAi] VTank import exception: " + ex);
return;
}
if (merge && (result.MonsterRulesAdded > 0 || result.RingSettingsSet.Length > 0))
{
try { dash.SaveSettings(); }
catch (Exception ex) { Host.Log("[RynthAi] VTank import: save settings failed: " + ex.Message); }
}
ReplyOk("[RynthAi] " + result.SummaryLine());
foreach (string line in result.LogLines)
Host.Log("[RynthAi] VTank import: " + line);
if (result.LootFilesCopied + result.NavFilesCopied + result.MetaFilesCopied + result.MonsterRulesAdded == 0)
ChatLine("[RynthAi] Nothing new found. Put VirindiTank under C:\\Games\\VirindiPlugins\\VirindiTank (or use the Import window to pick folders).");
}
/// <summary>Render thread: the VirindiTank Import folder window.</summary>
private void RenderVTankImportWindow()
{
try { _vtImportUi?.Render(); }
catch (Exception ex) { Host.Log("[RynthAi] VTank import window: " + ex.Message); }
}
}

View file

@ -186,7 +186,12 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
private int _giveGoneStreak;
private int _giveUnclassified; // unclassified chat lines logged for this give (max 5)
// Chat verdict on the in-flight give, set by OnChatWindowText and read on the tick.
private enum GiveChat { None, Busy, Permanent, ItemNotFound }
private enum GiveChat { None, Busy, Permanent, ItemNotFound, Examined }
// Items an NPC looked at and handed back ("You allow X to examine your Y.": ACE's Refuse emote, how a
// dynamic-quest NPC stamps a Parchment). Answered, not skipped; counted apart from items given.
private int _giveRunShown;
// How long the in-flight give may go unanswered: GiveConfirmMs plus AC's walk to a target that is far.
private long _giveInFlightConfirmMs = GiveConfirmMs;
private int _giveChatVerdict; // a GiveChat, handed from OnChatWindowText to the tick with Interlocked
private string _giveChatLine = string.Empty;
private bool _giveSawAcceptLine;
@ -228,6 +233,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
public override int Initialize()
{
// Floating windows keep their spot per character through the engine (Plugins/Shared/SavedWindow.cs).
RynthCore.Plugin.Shared.SavedWindow.Host = Host;
// RynthAi draws nothing itself: its windows are the engine's ImGui faces,
// fed through the C exports in PluginExports.cs. The "dashboard" object is
// the settings store, sub-managers and the bridge those exports call; its
@ -533,6 +540,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_autoVendor = null;
_autoTrade?.Reset();
_autoTrade = null;
_tradeShop?.Reset();
_tradeShop = null;
TeardownLocalFeatures(disposeTranslator: false);
_playerId = 0;
_loginComplete = false;
@ -572,6 +581,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_metaManager?.SetPlayerId(id);
_autoVendor?.SetPlayerId(id);
_autoTrade?.SetPlayerId(id);
_tradeShop?.SetPlayerId(id);
if (Host.HasQueryHealth) Host.QueryHealth(id);
Log($"RynthAi: player id 0x{id:X8} read late (it was 0 at login) - combat, looting and inventory now see it.");
}
@ -628,6 +638,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
// The dungeon patrol keeps its order after a fight (Go To Closest Waypoint is for
// routes; on a patrol loop the closest point can be near the end).
KeepWaypointAfterPause = () => _dunPatrolActive,
WaypointOnOtherLevel = OnWaypointOtherLevel, // a level above or below: plan again from here (DungeonLevels)
// Stuck escapes keep out of portals (RynthAiPlugin.PatrolPortals.cs).
EscapePortals = EscapePortalsNear,
};
@ -741,6 +752,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_weaponSwapGate.IsWielded = id => RynthCore.Plugin.Shared.ActionPacer.IsWieldedByPlayer(Host, unchecked((uint)id));
_buffManager = new BuffManager(Host, _dashboard.Settings, _spellManager, _vitals);
// Use Fellowship Buffs: the fellowship versions only while in one (the tracker is made below).
_buffManager.InFellowship = () => _fellowshipTracker?.IsInFellowship == true;
// The HP failsafe's recall stops the macro as /ra stop does (the macro-stop edge in OnTick
// then cancels the attack and stops movement): a move during the recall cancels it.
_buffManager.MacroStopForRecall = () =>
@ -831,7 +844,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_missileCraftingManager = new MissileCraftingManager(Host, _dashboard.Settings);
_missileCraftingManager.SetObjectCache(_objectCache!);
_missileCraftingManager.SetCharacterSkills(_charSkills);
_missileCraftingManager.HoldWhile = () => _combatManager?.AmmoSwapInProgress == true;
// The Universal Quiver charm (ACECustom 2026-11-11) shoots from the empty slot: no ammo to make or wield.
_missileCraftingManager.HoldWhile = () => _combatManager?.AmmoSwapInProgress == true || _combatManager?.UniversalQuiverActive == true;
_missileCraftingManager.FightIsOn = () => FightIsOn(); // optional crafts wait for the fight (RynthAiPlugin.Chores.cs)
_combatManager.AmmoWieldedElsewhereAt = () => _missileCraftingManager?.LastAmmoEquipAt ?? DateTime.MinValue; // no second wield on top of crafting's
_dashboard.SetMissileCraftingManager(_missileCraftingManager);
@ -915,6 +929,13 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
() => dashForAv?.CharFolder ?? string.Empty);
var atForUi = _autoTrade;
_dashboard.SetAutoTradeStatusProvider(() => atForUi.Status);
// Trade Shop is ungated; banking hook only when the server hub says this world supports it.
_tradeShop = new Trade.TradeShopManager(Host, _dashboard.Settings, _objectCache, _playerId,
() => _miniRemote?.ServerHub.ServerActive == true);
var tsForUi = _tradeShop;
_dashboard.SetTradeShopStatusProvider(() => tsForUi.Status);
_dashboard.SetTradeShopBankingProvider(() => tsForUi.BankingSupported);
}
Log("RynthAi: login complete, legacy ImGui dashboard ready.");
@ -1002,6 +1023,14 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
bool ownMovement = RynthCore.Plugin.Shared.MoveAudit.OwnMovementActive; // before nav's own stops clear it
_navigationEngine?.Stop();
// A lethal-ring escape is running: nav's stops just turned its autorun off. Run on, and
// no StopCompletely (2026-10-30).
if (_combatManager?.RingEvadeActive == true)
{
_combatManager.ReassertRingRun();
if (owner == BotActivity.Combat) ResetDoorState();
return;
}
// A StopCompletely only when RynthAi itself has the character moving (2026-10-06): with
// nothing of ours moving it is one more movement packet on the server's motion - 116 in 46
// minutes on 10-06, on every change of activity - and it cut off movement another plugin
@ -1074,6 +1103,26 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
Huds.ServerCommandModel.Apply(value);
return;
}
// RynthOracle's Run this quest: the quest's items on the quest loot list ("add <name>", "remove <name>", "clear").
if (action.Equals("questloot", StringComparison.OrdinalIgnoreCase))
{
// "build|profile <quest>|<item>..." and "profile off": the quest loot profiles (RynthAiPlugin.QuestLootProfiles.cs).
// RynthOracle up to 2026-11-05 sent "questloot add X" as the value (the verb read as "questloot", refused).
value = (value ?? "").Trim();
if (value.StartsWith("questloot ", StringComparison.OrdinalIgnoreCase)) value = value.Substring(10).Trim();
// "talk|handin <npc>..." (2026-11-07): the quest run's NPCs (RynthAiPlugin.QuestNpc.cs).
// "dungeon patrol|goto|stop" (2026-11-07): the quest run inside a dungeon (RynthAiPlugin.QuestDungeon.cs).
var (ok, text) = TryQuestLootProfile(value) ?? TryQuestNpc(value) ?? TryQuestDungeon(value) ?? TryQuestBuy(value) ?? QuestLootList.Apply(value);
Host.Log(text);
if (!ok) ReplyFail(text);
else if (value.TrimStart().StartsWith("profile", StringComparison.OrdinalIgnoreCase)
|| value.TrimStart().StartsWith("talk", StringComparison.OrdinalIgnoreCase)
|| value.TrimStart().StartsWith("handin", StringComparison.OrdinalIgnoreCase)
|| value.TrimStart().StartsWith("have", StringComparison.OrdinalIgnoreCase)
|| value.TrimStart().StartsWith("buy", StringComparison.OrdinalIgnoreCase)
|| value.TrimStart().StartsWith("dungeon", StringComparison.OrdinalIgnoreCase)) ChatLine(text); // the loot profile changed, or an NPC is being talked to: say so
return;
}
var dash = _dashboard;
if (dash == null) return;
bool on = value is "1" or "true" or "on" or "True" or "TRUE"
@ -1560,6 +1609,9 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
if (_loginComplete) Guard(TickStep.DataWriteProblems, PostDataWriteProblems); // a save that failed / folder not writable: say so in chat
Guard(TickStep.CombatHook, CombatHook.ObserveUseDone); // ctx.last.err: the answer to the hook's last cast
Guard(TickStep.DelayedCommands, TickDelayedCommands); // /ub delay
if (_loginComplete) Guard(TickStep.DelayedCommands, TickQuestNpcRetry); // a quest talk / hand-in waiting for its NPC
if (_loginComplete) Guard(TickStep.DelayedCommands, TickQuestBuy); // a quest item being bought from a vendor near you
if (_loginComplete) Guard(TickStep.DelayedCommands, TickQuestPortalScan); // a quest step's portal not in sight yet
if (_loginComplete) Guard(TickStep.FellowOpen, TickFellowOpen); // Open fellowship on create (RynthAiPlugin.FellowOpen.cs)
Guard(TickStep.GameInput, GameInput.Pump); // release keys held for /mt movement | jump | strafe
Guard(TickStep.Dashboard, TickDashboard); // the dashboard window's clicks, vitals and prefs
@ -1866,6 +1918,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
// looping through it — or with the Dungeon Patrol settings changed since.
// Cheap no-op unless a new hazard cell was registered or a setting changed.
TickDunPatrolHazardReroute();
// The patrol over the dungeon's levels: down a drop once round, rebuilt after a fall.
TickDunPatrolLevels();
// The dungeon explore: rooms entered, reroutes, its end (no-op unless one runs).
TickDunExplore();
// Outdoor hunting's next walk (no-op unless /ra hunt is on).
@ -1976,11 +2030,24 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
// the area emptied and were usually left behind (2026-10-03).
// An open chest goes first too (it closes when you walk away; RynthAiPlugin.ChestLoot.cs).
bool lootStarved = IsLootStarvedTurn(wantLoot, wantCombat) || IsOpenChestTurn(wantLoot, wantCombat);
// A lethal-ring escape (the Empyrean Handler's ring, RynthILT's BackAwayFrom)
// keeps the tick for combat until it is done (2026-10-30). It is driven from
// combat's tick; given to Looting with Loot priority on (or Buffing, or Nav
// priority) combat's Think stopped, the orphan watch turned autorun off after
// 1.5 s, and the character stood in the ring opening a corpse.
bool ringEscape = settings.EnableCombat && _combatManager?.RingEvadeActive == true;
if (ringEscape)
{
wantBuff = false;
wantCombat = true;
engaged = true;
lootStarved = false;
}
var inputs = new ArbiterInputs(
settings.IsMacroRunning, wantBuff, wantCombat, wantLoot, wantSalvage, wantNav,
combatEngaged: engaged,
boostNav: BoostNavRule.Active(settings), // only while a nav route runs (R-20261103-000159-a65e)
boostLoot: settings.BoostLootPriority,
boostNav: BoostNavRule.Active(settings) && !ringEscape, // only while a nav route runs (R-20261103-000159-a65e)
boostLoot: settings.BoostLootPriority && !ringEscape,
followActive: followActive,
lootStarved: lootStarved,
forcedLoot: wantLoot && ForcedLootHolds(),
@ -2072,6 +2139,19 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
return;
}
// ── Trade Shop (priced catalog; ungated; banking hook only if server supports) ──
var tradeShop = _tradeShop;
if (tradeShop != null
&& GuardHold(TickStep.TradeShop, () => { tradeShop.Tick(_busyCount); return tradeShop.HoldsBot; }))
{
if (settings.IsMacroRunning)
StopNavFor(BotActivity.Idle);
KeepThreatScanFresh(settings);
FreezeCorpseTimeout(CorpseNowMs);
ThinkMeta();
return;
}
Guard(TickStep.WeaponElements, TickWeaponElements);
// ── Priority 1: Buffing ───────────────────────────────────────────
@ -2377,6 +2457,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
ScanInventoryStatus(out int freeSlots, out int scarabs, out int tapers, out var scarabsByType, out var equipment);
_dashboard?.SetFreeSlots(freeSlots);
_dashboard?.SetComponentCounts(scarabs, tapers, scarabsByType);
// More scarabs or tapers (bought, looted): spells refused for components are tried again.
_spellManager?.NoteComponentCounts(scarabs, tapers);
_dashboard?.SetEquipment(AppraiseEquipment(equipment));
// Remote full-inventory snapshot (P1) — same 3s gate, reuses the cached walk.
@ -2560,6 +2642,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_aetheriaUnboxer?.OnChat(text);
_metaManager?.HandleChat(text, chatType);
_questTracker?.OnChatLine(text);
try { _tradeShop?.OnChatWindowText(text, chatType); }
catch (Exception ex) { Host.Log($"[RynthAi] TradeShop chat failed: {ex.Message}"); }
CheckChatForSafetyStops(text);
try { OnOwnCorpseChat(text); } catch { }
}
@ -3465,6 +3549,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
bool wasActive = _tier.Active;
int was = _tier.Current;
_tier.Refresh(Host);
Loot.T11ItemSupport.Enabled = _tier.OnIlt; // T11 only on Infinite Leaftide (2026-11-07)
if (_damageStore != null) _damageStore.Difficulty = _tier.Current;
if (_creatureStore != null && _tier.ServerKey.Length > 0
@ -3694,6 +3779,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
Interlocked.Exchange(ref _giveChatVerdict, 0);
_giveRunActive = false;
_giveRunItems = 0;
_giveRunShown = 0;
_giveRunSkips.Clear();
}
@ -3705,6 +3791,9 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
private static GiveChat ClassifyGiveChat(string text)
{
string t = text.ToLowerInvariant();
// "You allow <npc> to examine your <item>.": the NPC took the give and answered with its Refuse
// emote (the item comes back). A dynamic-quest stamp is exactly this, so it is an answer, not silence.
if (t.StartsWith("you allow ", StringComparison.Ordinal) && t.Contains(" to examine your ")) return GiveChat.Examined;
// Busy class first: "<npc> is too busy to accept gifts" must not read as "not accepting gifts".
if (t.Contains("too busy") || t.Contains("is busy right now")) return GiveChat.Busy;
if (t.Contains("item not found")) return GiveChat.ItemNotFound;
@ -3883,6 +3972,13 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
SkipGiveStack("item not found", tag, now);
return true;
}
if (chat == GiveChat.Examined)
{
Host.Log($"[RynthAi] Give answer: examined {tag} '{_giveChatLine}' after {sinceSend} ms (the target looked at it and handed it back)");
_giveRunShown++;
CompleteGiveStack(0, now);
return true;
}
if (chat == GiveChat.Permanent)
{
Host.Log($"[RynthAi] Give answer: permanent {tag} '{_giveChatLine}' after {sinceSend} ms");
@ -3923,7 +4019,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
}
// 3. No answer at all.
if (sinceSend < GiveConfirmMs) return false;
if (sinceSend < _giveInFlightConfirmMs) return false;
if (_giveInFlightTries < GiveMaxTries)
{
Host.Log($"[RynthAi] Give answer: no-answer {tag} after {sinceSend} ms; re-sending");
@ -3998,6 +4094,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_giveInFlightName = name;
_giveInFlightAt = now;
_giveLastSendAt = now;
_giveInFlightConfirmMs = GiveConfirmMsFor(targetId);
Interlocked.Exchange(ref _giveChatVerdict, 0);
_giveSawAcceptLine = false;
_giveGoneStreak = 0;
@ -4007,6 +4104,18 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
return true;
}
/// <summary>
/// GiveConfirmMs, plus the time AC needs to walk the player to a target that is not in reach (about
/// 3 m/s, past 3 m, capped at 20 s): a give to an NPC 15 m off answers only once the walk ends, and a
/// re-send before that cancels the walk ("Action cancelled!").
/// </summary>
private long GiveConfirmMsFor(uint targetId)
{
double d = _objectCache?.Distance(unchecked((int)_playerId), unchecked((int)targetId)) ?? -1;
if (d is not (> 3 and < 200)) return GiveConfirmMs; // unknown (MaxValue), in reach, or not a walk AC makes
return GiveConfirmMs + (long)Math.Min(20000, (d - 3) / 3.0 * 1000);
}
private void FinishGiveRun(long now)
{
if (!_giveRunActive) return;
@ -4014,10 +4123,12 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
long elapsed = Math.Max(0, _giveRunLastAnswerAt - _giveRunStartAt);
string avg = _giveRunItems > 0 ? $"{elapsed / _giveRunItems} ms" : "n/a";
string why = _giveRunSkips.Count == 0 ? string.Empty : $" ({string.Join("; ", _giveRunSkips)})";
string line = $"[RynthAi] Give queue complete: {_giveRunItems} item(s) given, {_giveRunSkips.Count} stack(s) skipped{why}, {elapsed / 1000.0:0.0}s total, {avg} per give.";
string shown = _giveRunShown > 0 ? $", {_giveRunShown} examined and handed back" : string.Empty;
string line = $"[RynthAi] Give queue complete: {_giveRunItems} item(s) given{shown}, {_giveRunSkips.Count} stack(s) skipped{why}, {elapsed / 1000.0:0.0}s total, {avg} per give.";
Host.Log(line);
ChatLine(line);
_giveRunItems = 0;
_giveRunShown = 0;
_giveRunSkips.Clear();
}
@ -4159,6 +4270,13 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
case "lootcheckinv": HandleLootCheckInventoryCommand(trimmed); break;
case "lootcheck": HandleLootCheckSelectedCommand(parts); break;
case "loot": HandleLootCommand(parts); break;
case "questloot":
{
string ql = parts.Length > 2 ? string.Join(" ", parts, 2, parts.Length - 2) : "list";
var (ok, text) = TryQuestLootProfile(ql) ?? TryQuestNpc(ql) ?? TryQuestDungeon(ql) ?? TryQuestBuy(ql) ?? QuestLootList.Apply(ql);
if (ok) ReplyOk(text); else ReplyFail(text);
break;
}
case "corpseinfo": HandleCorpseInfoCommand(); break;
case "pace": HandlePaceCommand(); break;
case "corpsecheck": HandleCorpseCheckCommand(parts); break;
@ -4184,6 +4302,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
case "stop":
case "pause": HandleMacroRunCommand(cmd, parts); break;
case "vtankyield": HandleVTankYieldCommand(parts); break;
case "vtimport":
case "vtankimport": HandleVTankImportCommand(parts); break;
case "navstate": HandleNavStateCommand(); break;
case "salvstate": HandleSalvageStateCommand(); break;
case "mapdump": HandleMapDumpCommand(); break;
@ -4215,6 +4335,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
// /ra equipfor <monster>: VTank's /vt equipitemsfor (MagToolsCommands.Extra.cs)
case "equipfor": HandleEquipForCommand(parts); break;
case "autotrade": HandleAutoTradeRaCommand(parts); break;
case "tradeshop": HandleTradeShopRaCommand(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)

View file

@ -44,6 +44,7 @@ public sealed partial class RynthAiPlugin
private static unsafe class PluginModule
{
/// <summary>RynthPluginVersion's hand-written string (it never changes between builds).</summary>
// Previous release: 0.5.105-legacy-ui.
public const string HandWrittenVersion = "0.5.0-legacy-ui";
private const uint FromAddress = 0x4, UnchangedRefCount = 0x2;

View file

@ -46,6 +46,7 @@
<Compile Include="..\Shared\RynthAiCombatApi.cs" Link="Shared\RynthAiCombatApi.cs" />
<!-- RynthNav's navmesh path queries (stuck-recovery detours outdoors). -->
<Compile Include="..\Shared\RynthNavPathApi.cs" Link="Shared\RynthNavPathApi.cs" />
<Compile Include="..\Shared\RynthAiDungeonPathApi.cs" Link="Shared\RynthAiDungeonPathApi.cs" />
<!-- Reading our hits out of the combat log (victim + amount); RynthTracker reads the same lines. -->
<Compile Include="..\Shared\CombatText.cs" Link="Shared\CombatText.cs" />
<!-- One logged, guarded way to use an object (who used what, and why). -->
@ -56,6 +57,9 @@
<Compile Include="..\Shared\ActionPacer.cs" Link="Shared\ActionPacer.cs" />
<!-- Text in the world on the Nav3D buffer (waypoint labels; RynthNav's path markers use it too). -->
<Compile Include="..\Shared\Nav3DText.cs" Link="Shared\Nav3DText.cs" />
<!-- ImGui text calls for non-literal text ('%' escaped): see the file's header. -->
<Compile Include="..\Shared\SafeImGui.cs" Link="Shared\SafeImGui.cs" />
<Compile Include="..\Shared\SavedWindow.cs" Link="Shared\SavedWindow.cs" />
<!-- Server signal vs a player's copy of it (chat type + line-start anchor). -->
<Compile Include="..\Shared\ChatSource.cs" Link="Shared\ChatSource.cs" />
<!-- Server commands a server plugin sends for a section (RynthILT's /fship for Fellowship), and their buttons. -->
@ -68,8 +72,6 @@
<Compile Include="..\Shared\SessionStatsTracker.cs" Link="Shared\SessionStatsTracker.cs" />
<!-- ImGui.NET bound to the engine's cimgui (RynthILT links the same file). -->
<Compile Include="..\Shared\ImGuiNativeBinding.cs" Link="Shared\ImGuiNativeBinding.cs" />
<!-- ImGui text calls for non-literal text ('%' escaped; RynthILT links the same file). -->
<Compile Include="..\Shared\SafeImGui.cs" Link="Shared\SafeImGui.cs" />
<!-- The engine's look for RynthAi's own windows (the instrument dashboard, 2026-10-21; RynthNet links them too). -->
<Compile Include="..\Shared\RynthUi\RynthUi.cs" Link="Shared\RynthUi\RynthUi.cs" />
<Compile Include="..\Shared\RynthUi\RynthIcons.cs" Link="Shared\RynthUi\RynthIcons.cs" />

View file

@ -0,0 +1,92 @@
// Auto-advertise helpers: which AC chat window and how often (pure; unit-testable).
using System;
using RynthCore.Plugin.RynthAi.Translate;
namespace RynthCore.Plugin.RynthAi.Trade;
/// <summary>Chat windows Trade Shop may auto-advertise into.</summary>
public enum TradeShopAdvertiseChannel
{
Trade = 0,
General = 1,
Lfg = 2,
Fellowship = 3,
Allegiance = 4,
Local = 5,
Roleplay = 6,
Society = 7,
}
/// <summary>Maps advertise channel → slash prefix / display name (no host deps).</summary>
public static class TradeShopAdvertise
{
public const int MinIntervalSec = 30;
public const int MaxIntervalSec = 3600;
public const int DefaultIntervalSec = 180;
public static string DisplayName(TradeShopAdvertiseChannel ch) => ch switch
{
TradeShopAdvertiseChannel.Trade => "Trade (/ct)",
TradeShopAdvertiseChannel.General => "General (/cg)",
TradeShopAdvertiseChannel.Lfg => "LFG (/clfg)",
TradeShopAdvertiseChannel.Fellowship => "Fellowship (/f)",
TradeShopAdvertiseChannel.Allegiance => "Allegiance (/a)",
TradeShopAdvertiseChannel.Local => "Local (say)",
TradeShopAdvertiseChannel.Roleplay => "Roleplay (/crp)",
TradeShopAdvertiseChannel.Society => "Society (/cs)",
_ => ch.ToString(),
};
/// <summary>Slash prefix for InvokeChatParser (empty = local say).</summary>
public static string SendPrefix(TradeShopAdvertiseChannel ch)
{
TranslateChannel tc = ch switch
{
TradeShopAdvertiseChannel.Trade => TranslateChannel.Trade,
TradeShopAdvertiseChannel.General => TranslateChannel.General,
TradeShopAdvertiseChannel.Lfg => TranslateChannel.Lfg,
TradeShopAdvertiseChannel.Fellowship => TranslateChannel.Fellowship,
TradeShopAdvertiseChannel.Allegiance => TranslateChannel.Allegiance,
TradeShopAdvertiseChannel.Local => TranslateChannel.Local,
TradeShopAdvertiseChannel.Roleplay => TranslateChannel.Roleplay,
TradeShopAdvertiseChannel.Society => TranslateChannel.Society,
_ => TranslateChannel.Trade,
};
return TranslateChannels.SendPrefix(tc, null);
}
public static int ClampIntervalSec(int sec)
{
if (sec < MinIntervalSec) return MinIntervalSec;
if (sec > MaxIntervalSec) return MaxIntervalSec;
return sec;
}
public static bool TryParseChannel(string? text, out TradeShopAdvertiseChannel ch)
{
ch = TradeShopAdvertiseChannel.Trade;
if (string.IsNullOrWhiteSpace(text)) return false;
if (Enum.TryParse(text.Trim(), ignoreCase: true, out TradeShopAdvertiseChannel parsed))
{
ch = parsed;
return true;
}
if (TranslateChannels.TryParse(text, out TranslateChannel tc))
{
ch = tc switch
{
TranslateChannel.Trade => TradeShopAdvertiseChannel.Trade,
TranslateChannel.General => TradeShopAdvertiseChannel.General,
TranslateChannel.Lfg => TradeShopAdvertiseChannel.Lfg,
TranslateChannel.Fellowship => TradeShopAdvertiseChannel.Fellowship,
TranslateChannel.Allegiance => TradeShopAdvertiseChannel.Allegiance,
TranslateChannel.Local => TradeShopAdvertiseChannel.Local,
TranslateChannel.Roleplay => TradeShopAdvertiseChannel.Roleplay,
TranslateChannel.Society => TradeShopAdvertiseChannel.Society,
_ => TradeShopAdvertiseChannel.Trade,
};
return true;
}
return false;
}
}

View file

@ -0,0 +1,337 @@
// /ra tradeshop ... — enable, list, add selected / typed listing, set rates help.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using RynthCore.Loot;
using RynthCore.Plugin.RynthAi.Trade;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi;
public sealed partial class RynthAiPlugin
{
private TradeShopManager? _tradeShop;
/// <summary>/ra tradeshop [on|off|status|list|add|addids|advertise|rates|mode1|mode2|ui]</summary>
private void HandleTradeShopRaCommand(string[] parts)
{
string verb = parts.Length > 2 ? parts[2].ToLowerInvariant() : "status";
string rest = parts.Length > 3 ? string.Join(" ", parts, 3, parts.Length - 3).Trim() : string.Empty;
var s = _dashboard?.Settings;
if (s == null)
{
ReplyFail("[RynthAi] Settings aren't ready.");
return;
}
switch (verb)
{
case "ui":
case "window":
case "open":
if (rest is "off" or "0" or "false" or "close")
s.ShowTradeShopWindow = false;
else if (rest is "on" or "1" or "true")
s.ShowTradeShopWindow = true;
else
s.ShowTradeShopWindow = !s.ShowTradeShopWindow; // bare / toggle
ReplyOk(s.ShowTradeShopWindow
? "[RynthAi] Trade Shop window open (prices + conversion rates)."
: "[RynthAi] Trade Shop window closed.");
break;
case "on":
case "enable":
s.TradeShopEnabled = true;
ReplyOk("[RynthAi] Trade Shop ON.");
break;
case "off":
case "disable":
s.TradeShopEnabled = false;
ReplyOk("[RynthAi] Trade Shop OFF.");
break;
case "test":
s.TradeShopTestMode = rest is not ("off" or "0" or "false");
ReplyOk($"[RynthAi] Trade Shop test mode {(s.TradeShopTestMode ? "ON" : "OFF")}.");
break;
case "mode1":
case "stock":
s.TradeShopMode = TradeShopMode.Mode1Stock;
ReplyOk("[RynthAi] Trade Shop Mode 1 (stock + trade window + !buy tells).");
break;
case "mode2":
case "text":
s.TradeShopMode = TradeShopMode.Mode2TextMultiAccount;
ReplyOk("[RynthAi] Trade Shop Mode 2 (text / multi-account listings).");
break;
case "list":
case "listings":
ListTradeShop(s);
break;
case "add":
AddTradeShopListing(s, rest);
break;
case "addids":
case "addmulti":
AddTradeShopIds(s, rest);
break;
case "advertise":
case "ad":
HandleTradeShopAdvertise(s, rest);
break;
case "rates":
ReplyOk("[RynthAi] " + (s.TradeShopRates ?? new TradeShopRates()).RatesHelpLine());
break;
case "status":
default:
string st = _tradeShop?.Status ?? "not ready";
string bank = _tradeShop != null && _tradeShop.BankingSupported
? (s.TradeShopBankingHook ? "banking hook ON" : "banking available (hook off)")
: "no banking on this world";
string ad = s.TradeShopAdvertiseEnabled
? $"ad {TradeShopAdvertise.DisplayName(s.TradeShopAdvertiseChannel)} every {TradeShopAdvertise.ClampIntervalSec(s.TradeShopAdvertiseIntervalSec)}s"
: "ad off";
ReplyOk($"[RynthAi] Trade Shop: {(s.TradeShopEnabled ? "ON" : "OFF")} {s.TradeShopMode} | {st} | {bank} | {ad}");
break;
}
}
/// <summary>/ra tradeshop advertise [on|off|now|channel Trade|interval 120|prefix text]</summary>
private void HandleTradeShopAdvertise(LegacyUi.LegacyUiSettings s, string rest)
{
if (rest.Length == 0 || rest is "status")
{
ReplyOk(s.TradeShopAdvertiseEnabled
? $"[RynthAi] Advertise ON → {TradeShopAdvertise.DisplayName(s.TradeShopAdvertiseChannel)} every {TradeShopAdvertise.ClampIntervalSec(s.TradeShopAdvertiseIntervalSec)}s."
: "[RynthAi] Advertise OFF. Usage: /ra tradeshop advertise on|off|now|channel Trade|interval 180|prefix WTS");
return;
}
string[] bits = rest.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries);
string v = bits[0].ToLowerInvariant();
string arg = bits.Length > 1 ? bits[1].Trim() : "";
switch (v)
{
case "on":
case "1":
case "true":
s.TradeShopAdvertiseEnabled = true;
ReplyOk($"[RynthAi] Advertise ON ({TradeShopAdvertise.DisplayName(s.TradeShopAdvertiseChannel)}, every {TradeShopAdvertise.ClampIntervalSec(s.TradeShopAdvertiseIntervalSec)}s).");
break;
case "off":
case "0":
case "false":
s.TradeShopAdvertiseEnabled = false;
ReplyOk("[RynthAi] Advertise OFF.");
break;
case "now":
case "send":
if (_tradeShop == null) { ReplyFail("[RynthAi] Trade Shop not ready."); break; }
string body = _tradeShop.BuildAdvertiseMessage();
string prefix = TradeShopAdvertise.SendPrefix(s.TradeShopAdvertiseChannel);
if (Host.HasInvokeChatParser) Host.InvokeChatParser(prefix + body);
ReplyOk($"[RynthAi] Sent advertise on {TradeShopAdvertise.DisplayName(s.TradeShopAdvertiseChannel)}.");
break;
case "channel":
case "window":
case "chat":
if (!TradeShopAdvertise.TryParseChannel(arg, out var ch))
{
ReplyFail("[RynthAi] Channel: Trade, General, LFG, Fellowship, Allegiance, Local, Roleplay, Society.");
break;
}
s.TradeShopAdvertiseChannel = ch;
ReplyOk($"[RynthAi] Advertise channel → {TradeShopAdvertise.DisplayName(ch)}.");
break;
case "interval":
case "freq":
case "every":
if (!int.TryParse(arg, NumberStyles.Integer, CultureInfo.InvariantCulture, out int sec))
{
ReplyFail("[RynthAi] Usage: /ra tradeshop advertise interval <seconds> (30–3600).");
break;
}
s.TradeShopAdvertiseIntervalSec = TradeShopAdvertise.ClampIntervalSec(sec);
ReplyOk($"[RynthAi] Advertise every {s.TradeShopAdvertiseIntervalSec}s.");
break;
case "prefix":
s.TradeShopAdvertisePrefix = arg;
ReplyOk(arg.Length > 0
? $"[RynthAi] Advertise prefix set to \"{arg}\"."
: "[RynthAi] Advertise prefix cleared.");
break;
default:
ReplyFail("[RynthAi] advertise on|off|now|channel <name>|interval <sec>|prefix <text>");
break;
}
}
/// <summary>/ra tradeshop addids &lt;id,id,...&gt; [pricePy] — multi-select from Inventory menu.</summary>
private void AddTradeShopIds(LegacyUi.LegacyUiSettings s, string rest)
{
s.TradeShopListings ??= new();
if (string.IsNullOrWhiteSpace(rest))
{
ReplyFail("[RynthAi] Usage: /ra tradeshop addids <id>[,id...] [pricePy]");
return;
}
long price = 1;
var idTokens = new List<string>();
foreach (string tok in rest.Split(new[] { ' ', ',', ';' }, StringSplitOptions.RemoveEmptyEntries))
idTokens.Add(tok.Trim());
// Optional trailing price: last token is decimal and every prior token parses as an object id.
if (idTokens.Count >= 2
&& !idTokens[^1].StartsWith("0x", StringComparison.OrdinalIgnoreCase)
&& long.TryParse(idTokens[^1], NumberStyles.Integer, CultureInfo.InvariantCulture, out long trailing)
&& trailing > 0
&& idTokens.Take(idTokens.Count - 1).All(t => TryParseObjectId(t, out _)))
{
price = trailing;
idTokens.RemoveAt(idTokens.Count - 1);
}
int added = 0;
foreach (string tok in idTokens)
{
if (!TryParseObjectId(tok, out uint id) || id == 0) continue;
WorldObject? wo = _objectCache?[(int)id];
string name = !string.IsNullOrWhiteSpace(wo?.Name) ? wo!.Name : $"0x{id:X8}";
// Skip duplicates of the same ObjectId still listed.
if (s.TradeShopListings.Any(l => l != null && l.ObjectId == id))
continue;
s.TradeShopListings.Add(new TradeShopListing
{
Sku = "S" + (s.TradeShopListings.Count + 1).ToString(CultureInfo.InvariantCulture),
Name = name!,
PricePyreals = price,
ObjectId = id,
Enabled = true,
});
added++;
}
ReplyOk(added > 0
? $"[RynthAi] Added {added} listing(s) at {price:N0}p each (edit prices in Trade Shop window)."
: "[RynthAi] No new ids added (check selection / duplicates).");
}
private static bool TryParseObjectId(string tok, out uint id)
{
id = 0;
if (string.IsNullOrWhiteSpace(tok)) return false;
string t = tok.Trim();
if (t.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
return uint.TryParse(t.AsSpan(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out id) && id != 0;
// Decimal object ids from the Inventory menu.
return uint.TryParse(t, NumberStyles.Integer, CultureInfo.InvariantCulture, out id) && id != 0;
}
private void ListTradeShop(LegacyUi.LegacyUiSettings s)
{
var list = s.TradeShopListings;
if (list == null || list.Count == 0)
{
ReplyOk("[RynthAi] Trade Shop catalog is empty.");
return;
}
var rates = s.TradeShopRates;
ReplyOk($"[RynthAi] Trade Shop ({list.Count}):");
for (int i = 0; i < list.Count; i++)
{
var row = list[i];
if (row == null) continue;
ReplyOk($" #{i + 1} {row.Line(rates)}");
}
}
private void AddTradeShopListing(LegacyUi.LegacyUiSettings s, string rest)
{
s.TradeShopListings ??= new();
// add <price> [name...] — uses selected item when name omitted
// add <price> name|sku=X|acct=Y
long price = 0;
string name = "";
string sku = "";
string acct = "";
string desc = "";
if (rest.Length > 0)
{
string[] bits = rest.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries);
if (!long.TryParse(bits[0].Replace(",", "", StringComparison.Ordinal), NumberStyles.Integer,
CultureInfo.InvariantCulture, out price) || price < 0)
{
ReplyFail("[RynthAi] Usage: /ra tradeshop add <pricePy> [name] (or select an item and omit name).");
return;
}
if (bits.Length > 1) name = bits[1].Trim();
}
uint objectId = 0;
int weenieId = 0;
if (name.Length == 0 && Host.HasGetSelectedItemId)
{
uint sel = Host.GetSelectedItemId();
if (sel != 0 && _objectCache != null)
{
WorldObject? wo = _objectCache[(int)sel];
if (wo != null)
{
name = wo.Name ?? "";
objectId = sel;
}
}
}
if (string.IsNullOrWhiteSpace(name) && price <= 0)
{
ReplyFail("[RynthAi] Select an item or pass: /ra tradeshop add <pricePy> <name>.");
return;
}
if (string.IsNullOrWhiteSpace(name)) name = "(unnamed)";
if (price <= 0)
{
ReplyFail("[RynthAi] Price must be > 0 pyreals.");
return;
}
// Optional trailing tags: sku=FOO acct=Toon
ParseListingTags(ref name, ref sku, ref acct, ref desc);
if (sku.Length == 0)
sku = "S" + (s.TradeShopListings.Count + 1).ToString(CultureInfo.InvariantCulture);
var row = new TradeShopListing
{
Sku = sku,
Name = name,
Description = desc,
PricePyreals = price,
ObjectId = objectId,
WeenieId = weenieId,
LocatedOnAccount = acct,
Enabled = true,
};
s.TradeShopListings.Add(row);
ReplyOk($"[RynthAi] Listed {row.Line(s.TradeShopRates)}");
}
private static void ParseListingTags(ref string name, ref string sku, ref string acct, ref string desc)
{
// Pull sku=/acct=/desc= tokens out of the free-text name.
string[] tokens = name.Split(' ', StringSplitOptions.RemoveEmptyEntries);
var kept = new System.Collections.Generic.List<string>();
foreach (string t in tokens)
{
if (t.StartsWith("sku=", StringComparison.OrdinalIgnoreCase))
sku = t.Substring(4);
else if (t.StartsWith("acct=", StringComparison.OrdinalIgnoreCase))
acct = t.Substring(5);
else if (t.StartsWith("desc=", StringComparison.OrdinalIgnoreCase))
desc = t.Substring(5);
else
kept.Add(t);
}
name = string.Join(" ", kept);
}
}

View file

@ -0,0 +1,57 @@
// One priced item on the Trade Shop catalog (Mode 1 = stock on this character; Mode 2 = text listing).
using System;
namespace RynthCore.Plugin.RynthAi.Trade;
/// <summary>
/// How the shop fulfills a sale.
/// Mode1Stock: the item must be in this character's pack; payment → add item → accept.
/// Mode2TextMultiAccount: catalog is description-only (other accounts hold stock); payment → accept;
/// the buyer is told the listing text (fulfillment across accounts is outside this client).
/// </summary>
public enum TradeShopMode
{
Mode1Stock = 0,
Mode2TextMultiAccount = 1,
}
/// <summary>One sellable row in the Trade Shop.</summary>
public sealed class TradeShopListing
{
/// <summary>Short code for tells ("buy SKU") and the UI list.</summary>
public string Sku = "";
/// <summary>Display name (Mode 1: from the item; Mode 2: typed).</summary>
public string Name = "";
/// <summary>Mode 2 (and Mode 1 notes): what the buyer is told.</summary>
public string Description = "";
/// <summary>Price in pyreals (trade notes / converted currencies count via TradeShopRates).</summary>
public long PricePyreals;
/// <summary>Mode 1: last known object id in pack (0 = resolve by weenie/name).</summary>
public uint ObjectId;
/// <summary>Mode 1: weenie type id when known (helps re-find after logout).</summary>
public int WeenieId;
/// <summary>Mode 2: which account / toon holds the stock (informational).</summary>
public string LocatedOnAccount = "";
/// <summary>False = listed but not for sale.</summary>
public bool Enabled = true;
public string PriceLabel() => PricePyreals <= 0 ? "(no price)" : PricePyreals.ToString("N0") + "p";
/// <summary>Price plus conversion alternatives when <paramref name="rates"/> is provided.</summary>
public string PriceLabel(TradeShopRates? rates)
{
if (PricePyreals <= 0) return "(no price)";
if (rates == null) return PriceLabel();
string alt = rates.FormatAlternatives(PricePyreals);
return alt.Length > 0 ? alt : PriceLabel();
}
public string Line() =>
(Sku.Length > 0 ? Sku + " — " : "") + (Name.Length > 0 ? Name : "(unnamed)") + " @ " + PriceLabel()
+ (Enabled ? "" : " [off]");
public string Line(TradeShopRates? rates) =>
(Sku.Length > 0 ? Sku + " — " : "") + (Name.Length > 0 ? Name : "(unnamed)") + " @ " + PriceLabel(rates)
+ (LocatedOnAccount.Length > 0 ? " @" + LocatedOnAccount : "")
+ (Enabled ? "" : " [off]");
}

View file

@ -0,0 +1,730 @@
// Trade Shop bot: priced catalog + tell commands + Rynth trade API (Mode 1 stock / Mode 2 text).
// Mode 1: buyer !list / !price / !buy → tell price from TradeShopRates → TradeOpen/TradeAdd
// to show the item in the trade window → wait for payment → TradeAccept.
// Ungated. Banking hook only when the host says the server supports banking payments.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Loot;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi.Trade;
/// <summary>
/// Mode 1 pairs the trade window (show stock via <see cref="RynthCoreHost.TradeAdd"/>) with
/// tell commands (!help / !list / !price / !buy) and Rynth trade actions (open / add / accept / reset).
/// Prices come from <see cref="TradeShopRates"/> (UB-IT conversion table).
/// Mode 2 stays text / multi-account: payment → tell listing → accept.
/// </summary>
internal sealed class TradeShopManager
{
private const long BailMs = 30_000;
private const long AcceptWaitMs = 10_000;
private const long OpenTradeWaitMs = 15_000;
/// <summary>Gap between outbound tells so AC does not drop the price sheet.</summary>
private const long TellGapMs = 1_200;
private readonly RynthCoreHost _host;
private readonly LegacyUiSettings _settings;
private readonly WorldObjectCache _cache;
private readonly Func<bool> _bankingSupported;
private readonly ConcurrentQueue<(string Sender, string Message)> _tells = new();
private readonly ConcurrentQueue<(string To, string Message)> _outTells = new();
private long _nextTellAt;
private long _nextAdvertiseAt;
private uint _playerId;
private bool _baselined;
private bool _wasOpen;
private uint _generation;
private uint _sessionGeneration;
private uint _traderId;
private string _traderName = "";
private enum Phase
{
Idle,
/// <summary>Mode 1: TradeOpen sent; waiting for the window.</summary>
OpenTrade,
/// <summary>Mode 1: TradeAdd sent; waiting for the item to appear on our side.</summary>
ShowItem,
/// <summary>Item is in the window (Mode 1) or Mode 2 payment watch; waiting for payment.</summary>
WaitPayment,
WaitAccept,
Done,
}
private Phase _phase = Phase.Idle;
private TradeShopListing? _active;
private uint _pendingAddId;
private uint _pendingBuyerId;
private string _pendingBuyerName = "";
private long _bailAt;
private long _acceptDeadline;
private volatile string _status = "Idle";
public TradeShopManager(
RynthCoreHost host,
LegacyUiSettings settings,
WorldObjectCache cache,
uint playerId,
Func<bool>? bankingSupported = null)
{
_host = host;
_settings = settings;
_cache = cache;
_playerId = playerId;
_bankingSupported = bankingSupported ?? (() => false);
}
public string Status => _status;
/// <summary>True while Mode 1 is opening/showing/waiting payment or accepting (holds the bot like AutoTrade).</summary>
public bool HoldsBot => _phase is Phase.OpenTrade or Phase.ShowItem or Phase.WaitPayment or Phase.WaitAccept;
public bool BankingSupported => _bankingSupported();
public void SetPlayerId(uint id) => _playerId = id;
public void Reset()
{
EndSession(clearStatus: true);
_baselined = false;
_wasOpen = false;
_generation = 0;
_traderId = 0;
_traderName = "";
while (_tells.TryDequeue(out _)) { }
while (_outTells.TryDequeue(out _)) { }
_nextTellAt = 0;
_nextAdvertiseAt = 0;
_status = "Idle";
}
/// <summary>Chat thread: queue incoming player tells that look like shop commands.</summary>
public void OnChatWindowText(string? text, int chatType)
{
if (!_settings.TradeShopEnabled) return;
if (string.IsNullOrEmpty(text)) return;
// Prefer Tell colour; still accept a line that clearly matches the tell shape.
if (chatType != ChatSource.Tell && chatType != -1
&& text.IndexOf(" tells you", StringComparison.OrdinalIgnoreCase) < 0)
return;
if (!TradeShopTellParse.TryParseTell(text, out string sender, out string msg)) return;
string cmd = msg.Trim();
if (cmd.Length == 0) return;
// Shop verbs / greeting: queue; bare text also gets the rates + sheet intro.
if (cmd[0] == '!' || TradeShopTellParse.IsShopVerb(cmd) || LooksLikeShopGreeting(cmd))
_tells.Enqueue((sender, cmd));
}
public void Tick(int busyCount)
{
long now = Environment.TickCount64;
DrainOutboundTells(now);
TickAdvertise(now);
DrainTells(now); // !list / !price / rates still work without the trade API
if (!_host.HasTrade)
{
_status = "Needs engine trade API v72+";
return;
}
PollTrade(now);
if (_phase == Phase.Idle) return;
if (now > _bailAt)
{
Tool("timed out");
if (_phase is Phase.OpenTrade or Phase.ShowItem or Phase.WaitPayment)
Tell(_pendingBuyerName.Length > 0 ? _pendingBuyerName : _traderName, "Shop timed out. Tell !buy again.");
EndSession();
return;
}
if (_phase != Phase.OpenTrade)
{
if (!_host.TryGetTradeState(out TradeState st) || !st.IsOpen || st.Generation != _sessionGeneration)
{
EndSession();
return;
}
}
switch (_phase)
{
case Phase.OpenTrade:
TickOpenTrade(now);
break;
case Phase.ShowItem:
TickShowItem(now);
break;
case Phase.WaitPayment:
TickWaitPayment(now);
break;
case Phase.WaitAccept:
TickWaitAccept(now);
break;
}
}
// ── Tell commands (Mode 1 shop front) ───────────────────────────────────
private void DrainTells(long now)
{
// One inbound command per tick so the outbound tell queue can pace replies.
if (!_tells.TryDequeue(out var tell)) return;
HandleTell(tell.Sender, tell.Message, now);
}
private void HandleTell(string sender, string commandLine, long now)
{
if (!_settings.TradeShopEnabled) return;
string raw = commandLine.Trim();
if (raw.StartsWith('!')) raw = raw[1..].Trim();
string[] parts = raw.Split((char[]?)null, 2, StringSplitOptions.RemoveEmptyEntries);
string verb = parts.Length > 0 ? parts[0].ToLowerInvariant() : "";
string arg = parts.Length > 1 ? parts[1].Trim() : "";
// Greeting / empty verb → rates + full price sheet (queued).
if (verb.Length == 0 || LooksLikeShopGreeting(verb) || verb is "help" or "hi" or "hello" or "shop")
{
EnqueueIntro(sender);
return;
}
switch (verb)
{
case "rates":
case "rate":
case "fx":
QueueTell(sender, TradeShopMessages.RatesLine(Rates()));
break;
case "list":
case "sheet":
case "catalog":
case "menu":
EnqueueSheet(sender, includeRates: true);
break;
case "price":
case "cost":
QueueTell(sender, BuildPriceMessage(arg));
break;
case "buy":
if (_settings.TradeShopMode != TradeShopMode.Mode1Stock)
{
QueueTell(sender, "Mode 2: put payment in the trade window (see !list). !buy is Mode 1 only.");
break;
}
BeginMode1Buy(sender, arg, now);
break;
default:
// Unknown: still help them with rates + sheet so a free-form tell gets the catalog.
EnqueueIntro(sender);
break;
}
}
private void EnqueueIntro(string sender)
{
QueueTell(sender, TradeShopMessages.HelpLine());
EnqueueSheet(sender, includeRates: true);
}
private void EnqueueSheet(string sender, bool includeRates)
{
foreach (string chunk in TradeShopMessages.BuildPriceSheetChunks(EnabledListings(), Rates(), includeRates))
QueueTell(sender, chunk);
}
private void BeginMode1Buy(string buyerName, string arg, long now)
{
if (!HasPricedListings())
{
Tell(buyerName, "Shop catalog is empty.");
return;
}
TradeShopListing? listing = ResolveListing(arg);
if (listing == null)
{
Tell(buyerName, "Item not found. Use !list then !buy <id|item>.");
return;
}
uint stockId = ResolveStock(listing);
if (stockId == 0)
{
Tell(buyerName, $"Out of stock: {listing.Name}.");
return;
}
// Busy with another buyer.
if (_phase != Phase.Idle && !NamesEqual(_pendingBuyerName, buyerName) && !NamesEqual(_traderName, buyerName))
{
Tell(buyerName, $"Shop busy with {(_pendingBuyerName.Length > 0 ? _pendingBuyerName : _traderName)}. Try again shortly.");
return;
}
TradeShopRates rates = Rates();
string priceLine = listing.PriceLabel(rates);
Tell(buyerName, $"Buy {listing.Name}: {priceLine}. Open trade (or accept my request); item will appear in the window. Put payment, then I accept.");
_active = listing;
_pendingAddId = stockId;
_pendingBuyerName = buyerName;
_pendingBuyerId = FindPlayerId(buyerName);
if (_settings.TradeShopTestMode)
{
Tool($"TEST Mode1 buy {listing.Line(rates)} for {buyerName} (stock 0x{stockId:X8})");
EndSession();
return;
}
// Trade already open with this buyer → show item via TradeAdd.
if (_host.TryGetTradeState(out TradeState st) && st.IsOpen
&& (NamesEqual(_traderName, buyerName) || (_pendingBuyerId != 0 && st.PartnerId == _pendingBuyerId)))
{
_sessionGeneration = st.Generation;
_traderId = st.PartnerId;
_traderName = ObjectName(st.PartnerId);
StartShowItem(now);
return;
}
// Ask them to trade via Rynth TradeOpen.
if (_pendingBuyerId == 0)
{
Tell(buyerName, "I can't see you nearby to open trade. Walk up and open trade with me, then !buy again.");
EndSession(clearStatus: false);
_status = "Waiting for buyer nearby";
return;
}
if (!_host.TradeOpen(_pendingBuyerId))
{
Tell(buyerName, "Could not send trade request. Open trade with me, then !buy again.");
EndSession();
return;
}
_phase = Phase.OpenTrade;
_bailAt = now + OpenTradeWaitMs;
_status = $"Trade requested → {buyerName}";
_host.Log($"[RynthAi] TradeShop Mode1: TradeOpen → {buyerName} [0x{_pendingBuyerId:X8}] for {listing.Name}");
}
private void StartShowItem(long now)
{
if (_active == null || _pendingAddId == 0)
{
EndSession();
return;
}
// Clear our side first so the window shows only this sale item.
_host.TradeReset();
if (!_host.TradeAdd(_pendingAddId))
{
Tell(_traderName.Length > 0 ? _traderName : _pendingBuyerName, $"Could not put {_active.Name} in the trade window.");
EndSession();
return;
}
_phase = Phase.ShowItem;
_bailAt = now + BailMs;
_status = $"Showing {_active.Name}";
_host.Log($"[RynthAi] TradeShop Mode1: TradeAdd 0x{_pendingAddId:X8} ({_active.Name})");
Tell(_traderName.Length > 0 ? _traderName : _pendingBuyerName,
$"{_active.Name} is in the trade window. Pay {_active.PriceLabel(Rates())} then accept.");
}
// ── Trade poll / phases ─────────────────────────────────────────────────
private void PollTrade(long now)
{
if (!_host.TryGetTradeState(out TradeState st))
return;
if (!_baselined)
{
_baselined = true;
_generation = st.Generation;
_wasOpen = st.IsOpen;
if (st.IsOpen && st.PartnerId != 0)
{
_traderId = st.PartnerId;
_traderName = ObjectName(st.PartnerId);
}
return;
}
if (_wasOpen && (!st.IsOpen || st.Generation != _generation))
OnEndTrade();
if (st.IsOpen && st.Generation != _generation)
OnEnterTrade(st, now);
_generation = st.Generation;
_wasOpen = st.IsOpen;
}
private void OnEnterTrade(TradeState st, long now)
{
_traderId = st.PartnerId;
if (_traderId == 0) return;
_traderName = ObjectName(_traderId);
_sessionGeneration = st.Generation;
_host.Log($"[RynthAi] TradeShop: trade opened with {_traderName} [0x{_traderId:X8}]");
if (!_settings.TradeShopEnabled)
{
_status = "Disabled (trade open)";
return;
}
if (_settings.TradeShopMode == TradeShopMode.Mode1Stock)
{
// Mode 1: tell-driven. If we already have a pending !buy for this buyer, show the item.
if (_phase == Phase.OpenTrade
&& (NamesEqual(_pendingBuyerName, _traderName)
|| (_pendingBuyerId != 0 && _pendingBuyerId == _traderId)))
{
StartShowItem(now);
return;
}
// Spontaneous trade: greet with rates + sheet and wait for !buy (do not auto-match payment).
if (_phase == Phase.Idle)
{
EnqueueIntro(_traderName);
_status = $"Trade open — tell !buy ({_traderName})";
}
return;
}
// Mode 2: watch payment against the catalog.
if (!HasPricedListings())
{
_status = "No priced listings";
return;
}
_phase = Phase.WaitPayment;
_active = null;
_pendingAddId = 0;
_bailAt = now + BailMs;
_status = $"Mode2 waiting payment from {_traderName}";
}
private void OnEndTrade()
{
if (_phase != Phase.Idle)
EndSession();
_traderId = 0;
}
private void TickOpenTrade(long now)
{
if (!_host.TryGetTradeState(out TradeState st) || !st.IsOpen) return;
if (_pendingBuyerId != 0 && st.PartnerId != _pendingBuyerId
&& !NamesEqual(ObjectName(st.PartnerId), _pendingBuyerName))
return;
_sessionGeneration = st.Generation;
_traderId = st.PartnerId;
_traderName = ObjectName(st.PartnerId);
StartShowItem(now);
}
private void TickShowItem(long now)
{
foreach (uint id in _host.GetTradeItems(TradeSide.You))
{
if (id != _pendingAddId) continue;
_phase = Phase.WaitPayment;
_bailAt = now + BailMs;
_status = $"Waiting payment for {_active?.Name}";
_host.Log("[RynthAi] TradeShop Mode1: item visible in trade window; waiting for payment");
return;
}
}
private void TickWaitPayment(long now)
{
uint[] partner = _host.GetTradeItems(TradeSide.Partner);
if (partner.Length == 0) return;
TradeShopRates rates = Rates();
if (_settings.TradeShopMode == TradeShopMode.Mode1Stock)
{
// Payment must cover the listing we showed.
if (_active == null || _active.PricePyreals <= 0) return;
if (!TradeShopPayment.MeetsPrice(_cache, partner, _active.PricePyreals, rates))
return;
_host.Log($"[RynthAi] TradeShop Mode1: payment covers {_active.Line(rates)}");
if (_settings.TradeShopTestMode)
{
Tool($"TEST would accept {_active.Line(rates)}");
EndSession();
return;
}
BeginAccept(now);
return;
}
// Mode 2: any covered listing.
TradeShopListing? hit = FindCoveredListing(partner);
if (hit == null) return;
_active = hit;
_host.Log($"[RynthAi] TradeShop Mode2: payment covers {hit.Line(rates)}");
if (_settings.TradeShopTestMode)
{
Tool($"TEST would sell {hit.Line(rates)}");
EndSession();
return;
}
TellBuyerMode2(hit);
BeginAccept(now);
}
private void TickWaitAccept(long now)
{
if (!_host.TryGetTradeState(out TradeState st)) return;
if (st.YouAccepted)
{
_status = "Accepted";
_phase = Phase.Done;
return;
}
if (now > _acceptDeadline)
{
Tool("accept timed out");
EndSession();
return;
}
_host.TradeAccept();
_status = "Accept sent";
}
private void BeginAccept(long now)
{
_phase = Phase.WaitAccept;
_acceptDeadline = now + AcceptWaitMs;
_bailAt = _acceptDeadline;
_status = "Accepting";
if (_settings.TradeShopTestMode) return;
_host.TradeAccept();
}
// ── Catalog helpers ─────────────────────────────────────────────────────
private bool HasPricedListings()
{
var list = _settings.TradeShopListings;
if (list == null) return false;
return list.Any(l => l != null && l.Enabled && l.PricePyreals > 0
&& (!string.IsNullOrWhiteSpace(l.Name) || !string.IsNullOrWhiteSpace(l.Sku)));
}
private IReadOnlyList<TradeShopListing> EnabledListings()
=> (_settings.TradeShopListings ?? new List<TradeShopListing>())
.Where(l => l != null && l.Enabled && l.PricePyreals > 0
&& (!string.IsNullOrWhiteSpace(l.Name) || !string.IsNullOrWhiteSpace(l.Sku)))
.ToList()!;
private TradeShopListing? ResolveListing(string arg)
=> TradeShopMessages.ResolveListing(EnabledListings(), arg);
private TradeShopListing? FindCoveredListing(uint[] partnerItems)
{
TradeShopRates rates = Rates();
foreach (TradeShopListing listing in EnabledListings().OrderByDescending(l => l.PricePyreals))
{
if (!TradeShopPayment.MeetsPrice(_cache, partnerItems, listing.PricePyreals, rates))
continue;
return listing;
}
return null;
}
private uint ResolveStock(TradeShopListing listing)
{
if (listing.ObjectId != 0)
{
WorldObject? byId = _cache[(int)listing.ObjectId];
if (byId != null && byId.Id != 0 && !IsEquipped(byId))
return (uint)byId.Id;
}
foreach (WorldObject wo in Inventory())
{
if (wo == null || wo.Id == 0 || IsEquipped(wo)) continue;
if (!string.IsNullOrWhiteSpace(listing.Name)
&& string.Equals(wo.Name, listing.Name, StringComparison.OrdinalIgnoreCase))
return (uint)wo.Id;
}
return 0;
}
private uint FindPlayerId(string name)
{
if (string.IsNullOrWhiteSpace(name)) return 0;
int me = unchecked((int)_playerId);
WorldObject? partial = null;
foreach (var wo in _cache.GetLandscapeObjects())
{
if (wo == null || wo.Id == me || wo.ObjectClass != AcObjectClass.Player) continue;
if (string.Equals(wo.Name, name, StringComparison.OrdinalIgnoreCase))
return unchecked((uint)wo.Id);
if (partial == null && wo.Name.IndexOf(name, StringComparison.OrdinalIgnoreCase) >= 0)
partial = wo;
}
return partial != null ? unchecked((uint)partial.Id) : 0;
}
private List<WorldObject> Inventory()
{
try { return _cache.GetDirectInventory(forceRefresh: true).Where(w => w != null && w.Id != 0).ToList(); }
catch { return new List<WorldObject>(); }
}
private static bool IsEquipped(WorldObject wo)
=> wo.WieldedLocation > 0 || wo.Values(LongValueKey.EquippedSlots, 0) > 0;
private TradeShopRates Rates() => _settings.TradeShopRates ?? new TradeShopRates();
private string BuildPriceMessage(string arg)
{
if (string.IsNullOrWhiteSpace(arg))
return "Usage: !price <slot|name|value> e.g. !price #2 | !price Singularity | !price 250000";
TradeShopListing? listing = ResolveListing(arg);
if (listing == null) return "Item not found. Tell !list for the price sheet.";
TradeShopRates rates = Rates();
return $"{listing.Name}: {listing.PriceLabel(rates)}. Rates: {rates.RatesHelpLine()}";
}
/// <summary>Build the auto-advertise line (catalog summary + rates).</summary>
public string BuildAdvertiseMessage()
{
string prefix = (_settings.TradeShopAdvertisePrefix ?? "").Trim();
var list = EnabledListings();
TradeShopRates rates = Rates();
var chunks = TradeShopMessages.BuildPriceSheetChunks(list, rates, includeRates: true,
header: prefix.Length > 0 ? prefix : "[Trade Shop]");
// Advertise sends one chat line per interval; keep the first chunk (already length-capped).
return chunks.Count > 0 ? chunks[0] : "[Trade Shop] (empty catalog)";
}
private void TellBuyerMode2(TradeShopListing hit)
{
string msg = hit.Description.Length > 0
? hit.Description
: $"Sold: {hit.Name}" + (hit.LocatedOnAccount.Length > 0 ? $" (held on {hit.LocatedOnAccount})" : "");
if (msg.Length == 0) msg = hit.Line(Rates());
Tell(_traderName, "[TradeShop] " + msg);
if (BankingSupported && _settings.TradeShopBankingHook)
_host.Log("[RynthAi] TradeShop: banking payments available on this server (hook on).");
}
private void QueueTell(string to, string message)
{
string safe = (message ?? "").Replace("\r", " ").Replace("\n", " ").Trim();
if (string.IsNullOrWhiteSpace(to) || safe.Length == 0) return;
_outTells.Enqueue((to, safe));
}
private void Tell(string to, string message) => QueueTell(to, message);
private void DrainOutboundTells(long now)
{
if (_outTells.IsEmpty) return;
if (now < _nextTellAt) return;
if (!_outTells.TryDequeue(out var next)) return;
SendTellNow(next.To, next.Message);
_nextTellAt = now + TellGapMs;
}
private void SendTellNow(string to, string message)
{
if (string.IsNullOrWhiteSpace(to) || to.StartsWith("0x", StringComparison.Ordinal))
{
_host.Log($"[RynthAi] TradeShop → ?: {message}");
return;
}
if (_host.HasInvokeChatParser)
_host.InvokeChatParser($"/tell {to}, {message}");
else
_host.WriteToChat($"[RynthAi] TradeShop → {to}: {message}", 1);
}
private void TickAdvertise(long now)
{
if (!_settings.TradeShopEnabled || !_settings.TradeShopAdvertiseEnabled) return;
if (_settings.TradeShopTestMode) return;
int intervalSec = TradeShopAdvertise.ClampIntervalSec(_settings.TradeShopAdvertiseIntervalSec);
long intervalMs = intervalSec * 1000L;
if (_nextAdvertiseAt == 0)
_nextAdvertiseAt = now + Math.Min(intervalMs, 5_000); // first blast shortly after enable
if (now < _nextAdvertiseAt) return;
_nextAdvertiseAt = now + intervalMs;
string body = BuildAdvertiseMessage();
if (body.Length == 0) return;
string prefix = TradeShopAdvertise.SendPrefix(_settings.TradeShopAdvertiseChannel);
if (_host.HasInvokeChatParser)
_host.InvokeChatParser(prefix + body);
else
_host.WriteToChat($"[RynthAi] TradeShop ad: {body}", 1);
_host.Log($"[RynthAi] TradeShop advertised on {TradeShopAdvertise.DisplayName(_settings.TradeShopAdvertiseChannel)}");
}
private void EndSession(bool clearStatus = false)
{
_phase = Phase.Idle;
_active = null;
_pendingAddId = 0;
_pendingBuyerId = 0;
_pendingBuyerName = "";
if (clearStatus || string.IsNullOrEmpty(_status)
|| _status.StartsWith("Waiting", StringComparison.Ordinal)
|| _status.StartsWith("Showing", StringComparison.Ordinal)
|| _status.StartsWith("Adding", StringComparison.Ordinal)
|| _status.StartsWith("Accept", StringComparison.Ordinal)
|| _status.StartsWith("Trade requested", StringComparison.Ordinal)
|| _status.StartsWith("Mode2", StringComparison.Ordinal))
_status = _settings.TradeShopEnabled ? "Idle (enabled)" : "Idle";
}
private void Tool(string msg)
{
_host.Log($"[RynthAi] TradeShop: {msg}");
_host.WriteToChat($"[RynthAi] TradeShop: {msg}", 1);
}
private string ObjectName(uint id)
=> id != 0 && _host.TryGetObjectName(id, out string n) && !string.IsNullOrWhiteSpace(n) ? n : $"0x{id:X8}";
private static bool NamesEqual(string? a, string? b)
=> !string.IsNullOrWhiteSpace(a) && !string.IsNullOrWhiteSpace(b)
&& string.Equals(a.Trim(), b.Trim(), StringComparison.OrdinalIgnoreCase);
private static bool LooksLikeShopGreeting(string cmd)
{
string v = cmd.Trim().ToLowerInvariant();
if (v.StartsWith('!')) v = v[1..].Trim();
// First word only for multi-word tells ("hi there").
if (v.IndexOf(' ') > 0) v = v.Split(' ', 2)[0];
return v is "hi" or "hello" or "hey" or "yo" or "sup" or "shop" or "vendor" or "wts" or "prices";
}
}

View file

@ -0,0 +1,130 @@
// Build tell/advertise lines: rates, price sheet chunks, price lookup (pure; unit-testable).
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
namespace RynthCore.Plugin.RynthAi.Trade;
/// <summary>Catalog message builders and price lookup (name / slot / pyreal value).</summary>
public static class TradeShopMessages
{
/// <summary>AC tell / chat line soft limit (leave headroom for /tell Name, ).</summary>
public const int MaxLineChars = 220;
public static string RatesLine(TradeShopRates? rates)
=> "Rates: " + (rates ?? new TradeShopRates()).RatesHelpLine();
/// <summary>One catalog row: #slot name | sku | price alts.</summary>
public static string SheetRow(int slot1Based, TradeShopListing listing, TradeShopRates? rates)
{
string name = string.IsNullOrWhiteSpace(listing.Name) ? "(unnamed)" : listing.Name.Trim();
string sku = string.IsNullOrWhiteSpace(listing.Sku) ? "" : " | sku " + listing.Sku.Trim();
return $"#{slot1Based} {name}{sku} | {listing.PriceLabel(rates)}";
}
/// <summary>Full price sheet as one or more tell-sized chunks (rates first when included).</summary>
public static List<string> BuildPriceSheetChunks(
IReadOnlyList<TradeShopListing> listings,
TradeShopRates? rates,
bool includeRates,
string? header = null)
{
var chunks = new List<string>();
var sb = new StringBuilder();
void Flush()
{
if (sb.Length == 0) return;
chunks.Add(sb.ToString());
sb.Clear();
}
void AppendPart(string part)
{
if (string.IsNullOrEmpty(part)) return;
if (sb.Length == 0)
{
if (part.Length <= MaxLineChars) { sb.Append(part); return; }
// Hard-split oversized part.
for (int i = 0; i < part.Length; i += MaxLineChars)
chunks.Add(part.Substring(i, Math.Min(MaxLineChars, part.Length - i)));
return;
}
if (sb.Length + 3 + part.Length <= MaxLineChars)
{
sb.Append(" || ").Append(part);
return;
}
Flush();
AppendPart(part);
}
if (!string.IsNullOrWhiteSpace(header))
AppendPart(header.Trim());
if (includeRates)
AppendPart(RatesLine(rates));
if (listings == null || listings.Count == 0)
{
AppendPart("Price sheet: (empty)");
Flush();
return chunks;
}
AppendPart($"Price sheet ({listings.Count}):");
for (int i = 0; i < listings.Count; i++)
{
var row = listings[i];
if (row == null) continue;
AppendPart(SheetRow(i + 1, row, rates));
}
Flush();
return chunks;
}
/// <summary>
/// Resolve a listing by slot (#N / id:N / bare 1..Count), pyreal value (bare large N / value:N / py:N),
/// or name / SKU (exact then partial).
/// </summary>
public static TradeShopListing? ResolveListing(IReadOnlyList<TradeShopListing> list, string? arg)
{
if (list == null || list.Count == 0) return null;
var parsed = TradeShopTellParse.ParsePriceSelector(arg);
if (parsed.slot.HasValue)
{
int idx = parsed.slot.Value - 1;
if (idx >= 0 && idx < list.Count) return list[idx];
}
if (parsed.valuePy.HasValue)
{
long v = parsed.valuePy.Value;
TradeShopListing? exact = list.FirstOrDefault(l => l != null && l.PricePyreals == v);
if (exact != null) return exact;
// Closest price at or above the asked value, else nearest.
TradeShopListing? atOrAbove = list
.Where(l => l != null && l.PricePyreals >= v)
.OrderBy(l => l!.PricePyreals)
.FirstOrDefault();
if (atOrAbove != null) return atOrAbove;
return list.Where(l => l != null).OrderBy(l => Math.Abs(l!.PricePyreals - v)).FirstOrDefault();
}
if (!string.IsNullOrWhiteSpace(parsed.text))
{
string needle = parsed.text.Trim();
TradeShopListing? exact = list.FirstOrDefault(l =>
l != null && (string.Equals(l.Name, needle, StringComparison.OrdinalIgnoreCase)
|| string.Equals(l.Sku, needle, StringComparison.OrdinalIgnoreCase)));
if (exact != null) return exact;
return list.FirstOrDefault(l =>
l != null && ((l.Name ?? "").IndexOf(needle, StringComparison.OrdinalIgnoreCase) >= 0
|| (l.Sku ?? "").IndexOf(needle, StringComparison.OrdinalIgnoreCase) >= 0));
}
return null;
}
public static string HelpLine()
=> "Trade Shop: !help !rates !list/!sheet !price <slot|name|value> !buy <slot|name|value>. "
+ "Slot=#3; value=pyreals (e.g. 250000 or value:250000).";
}

View file

@ -0,0 +1,166 @@
// Sum / classify payment items on the partner's trade side (UB-IT conversion-aware).
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
using RynthCore.Loot;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi.Trade;
/// <summary>Values trade-side items as pyreals / currency tallies for Trade Shop payment checks.</summary>
internal static class TradeShopPayment
{
// "Trade Note (250,000)" / "Trade Note (250000)" when Value is missing.
private static readonly Regex NoteNameRx = new(
@"Trade\s+Note\s*\(\s*([\d,]+)\s*\)",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);
/// <summary>
/// Total pyreal value of <paramref name="itemIds"/> using the object cache (notes + pyreals only).
/// Prefer <see cref="Tally"/> + <see cref="TradeShopRates.PaymentMeetsPrice"/> for multi-currency shops.
/// </summary>
public static long SumPyreals(WorldObjectCache? cache, IEnumerable<uint> itemIds)
{
if (cache == null) return 0;
long total = 0;
foreach (uint id in itemIds)
{
WorldObject? wo = cache[(int)id];
if (wo == null) continue;
total += ItemPyreals(wo);
}
return total;
}
/// <summary>
/// Classify and tally accepted payment currencies on the partner's side.
/// Trade notes count as MMD stacks (Value / PyrealPerMmd) plus leftover pyreals from odd face values.
/// </summary>
public static Dictionary<TradeShopCurrency, long> Tally(
WorldObjectCache? cache, IEnumerable<uint> itemIds, TradeShopRates rates)
{
var tallies = new Dictionary<TradeShopCurrency, long>();
if (cache == null || rates == null) return tallies;
long pyPerMmd = Math.Max(1, rates.PyrealPerMmd <= 0 ? 250_000 : rates.PyrealPerMmd);
foreach (uint id in itemIds)
{
WorldObject? wo = cache[(int)id];
if (wo == null) continue;
ClassifyAdd(wo, pyPerMmd, tallies);
}
return tallies;
}
/// <summary>True when partner payment covers <paramref name="pricePyreals"/> at the shop rates.</summary>
public static bool MeetsPrice(
WorldObjectCache? cache, IEnumerable<uint> partnerItemIds, long pricePyreals, TradeShopRates rates)
{
if (pricePyreals <= 0 || rates == null) return false;
var tallies = Tally(cache, partnerItemIds, rates);
return rates.PaymentMeetsPrice(pricePyreals, tallies);
}
/// <summary>Pyreal worth of one world object (stack-aware; notes by Value / name).</summary>
public static long ItemPyreals(WorldObject wo)
{
string name = wo.Name ?? "";
int stack = Math.Max(1, wo.Values(LongValueKey.StackCount, 1));
if (IsPyrealName(name))
return stack;
// IntValueKey.Value = 19 (face value on trade notes / valued currency).
long value = wo.Values((LongValueKey)19, 0);
if (value > 0) return value * (LooksLikeTradeNote(name) ? stack : 1);
Match m = NoteNameRx.Match(name);
if (m.Success
&& long.TryParse(m.Groups[1].Value.Replace(",", "", StringComparison.Ordinal),
NumberStyles.Integer, CultureInfo.InvariantCulture, out long face))
return face * stack;
return 0;
}
/// <summary>Classify one inventory / trade item into a currency bucket (Unknown = not payment).</summary>
public static TradeShopCurrency Classify(string? name)
{
if (string.IsNullOrWhiteSpace(name)) return TradeShopCurrency.Unknown;
string n = name.Trim();
if (IsPyrealName(n)) return TradeShopCurrency.Pyreals;
if (LooksLikeTradeNote(n)) return TradeShopCurrency.Mmd;
if (EqualsCI(n, "Enlightened Coin") || EqualsCI(n, "Enlightened Coins"))
return TradeShopCurrency.EnlightenedCoins;
if (EqualsCI(n, "Weakly Enlightened Coin") || EqualsCI(n, "Weakly Enlightened Coins"))
return TradeShopCurrency.WeaklyEnlightenedCoins;
if (ContainsCI(n, "Legendary Key")) return TradeShopCurrency.LegendaryKeys;
if (ContainsCI(n, "Mythical Key")) return TradeShopCurrency.MythicalKeys;
if (EqualsCI(n, "Luminance") || EqualsCI(n, "Luminance Certificate")
|| EqualsCI(n, "Pack of Luminance"))
return TradeShopCurrency.Luminance;
return TradeShopCurrency.Unknown;
}
private static void ClassifyAdd(WorldObject wo, long pyPerMmd, Dictionary<TradeShopCurrency, long> tallies)
{
string name = wo.Name ?? "";
int stack = Math.Max(1, wo.Values(LongValueKey.StackCount, 1));
TradeShopCurrency kind = Classify(name);
if (kind == TradeShopCurrency.Pyreals)
{
Add(tallies, TradeShopCurrency.Pyreals, stack);
return;
}
if (kind == TradeShopCurrency.Mmd)
{
long face = wo.Values((LongValueKey)19, 0);
if (face <= 0)
{
Match m = NoteNameRx.Match(name);
if (m.Success)
long.TryParse(m.Groups[1].Value.Replace(",", "", StringComparison.Ordinal),
NumberStyles.Integer, CultureInfo.InvariantCulture, out face);
}
if (face <= 0) return;
long totalPy = face * stack;
long mmd = totalPy / pyPerMmd;
long rem = totalPy % pyPerMmd;
if (mmd > 0) Add(tallies, TradeShopCurrency.Mmd, mmd);
if (rem > 0) Add(tallies, TradeShopCurrency.Pyreals, rem);
return;
}
if (kind == TradeShopCurrency.Unknown) return;
Add(tallies, kind, stack);
}
private static void Add(Dictionary<TradeShopCurrency, long> tallies, TradeShopCurrency c, long n)
{
if (n <= 0) return;
tallies.TryGetValue(c, out long cur);
tallies[c] = cur + n;
}
private static bool IsPyrealName(string name)
=> EqualsCI(name, "Pyreal") || EqualsCI(name, "Pyreals");
private static bool LooksLikeTradeNote(string name)
=> name.IndexOf("Trade Note", StringComparison.OrdinalIgnoreCase) >= 0
|| NoteNameRx.IsMatch(name);
private static bool EqualsCI(string a, string b)
=> string.Equals(a, b, StringComparison.OrdinalIgnoreCase);
private static bool ContainsCI(string hay, string needle)
=> hay.IndexOf(needle, StringComparison.OrdinalIgnoreCase) >= 0;
}

View file

@ -0,0 +1,216 @@
// UB-IT InventoryControl conversion table (ConvBuyEc* / PyrealPerMmd) for Trade Shop pricing.
// Pure math — no host / WorldObject deps — so RynthAiTests can link this file.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace RynthCore.Plugin.RynthAi.Trade;
/// <summary>Which currency a payment item (or price alternative) is denominated in.</summary>
public enum TradeShopCurrency
{
Unknown = 0,
Pyreals = 1,
Mmd = 2,
Luminance = 3,
LegendaryKeys = 4,
MythicalKeys = 5,
EnlightenedCoins = 6,
WeaklyEnlightenedCoins = 7,
}
/// <summary>
/// Item-conversion rates ported from UB-IT's Trade Bot / Banking shop defaults.
/// Listings stay priced in pyreals; buyers may pay in any accepted currency at these rates.
/// </summary>
public sealed class TradeShopRates
{
/// <summary>Face value of one MMD trade note in pyreals (UB default 250,000).</summary>
public long PyrealPerMmd = 250_000;
// EC conversion table: how many units of each currency per 1 EC (buy side = what we charge).
public long ConvBuyEcMmd = 4;
public long ConvBuyEcLum = 1000;
public long ConvBuyEcLk = 2;
public long ConvBuyEcMk = 1;
public long ConvBuyEcWec = 10;
// Sell-side (optional; bank-shop / WTB display). Same defaults as UB-IT.
public long ConvSellEcMmd = 4;
public long ConvSellEcLum = 900;
public long ConvSellEcLk = 1;
public long ConvSellEcMk = 1;
public long ConvSellEcWec = 8;
public bool AcceptPyreals = true;
public bool AcceptMmd = true;
public bool AcceptLuminance = true;
public bool AcceptLegendaryKeys = true;
public bool AcceptMythicalKeys = true;
public bool AcceptEnlightenedCoins = true;
public bool AcceptWeaklyEnlightenedCoins = true;
/// <summary>Pyreals per 1 EC at the buy rate (MMDs-per-EC × pyreals-per-MMD).</summary>
public long PyrealsPerEcBuy()
{
long mmd = Math.Max(1, ConvBuyEcMmd);
long py = Math.Max(1, PyrealPerMmd <= 0 ? 250_000 : PyrealPerMmd);
return mmd * py;
}
/// <summary>EC units charged for a listing priced at <paramref name="basePy"/> (ceil, min 1).</summary>
public long EcUnitsForPyreals(long basePy)
{
if (basePy <= 0) return 0;
long perEc = PyrealsPerEcBuy();
long units = (long)Math.Ceiling(basePy / (double)perEc);
return units <= 0 ? 1 : units;
}
/// <summary>How many units of <paramref name="currency"/> equal one EC on the buy side.</summary>
public long UnitsPerEcBuy(TradeShopCurrency currency) => currency switch
{
TradeShopCurrency.EnlightenedCoins => 1,
TradeShopCurrency.Mmd => Math.Max(1, ConvBuyEcMmd),
TradeShopCurrency.Luminance => Math.Max(1, ConvBuyEcLum),
TradeShopCurrency.LegendaryKeys => Math.Max(1, ConvBuyEcLk),
TradeShopCurrency.MythicalKeys => Math.Max(1, ConvBuyEcMk),
TradeShopCurrency.WeaklyEnlightenedCoins => Math.Max(1, ConvBuyEcWec),
_ => 0,
};
/// <summary>True when this shop accepts that currency for payment.</summary>
public bool Accepts(TradeShopCurrency currency) => currency switch
{
TradeShopCurrency.Pyreals => AcceptPyreals,
TradeShopCurrency.Mmd => AcceptMmd,
TradeShopCurrency.Luminance => AcceptLuminance,
TradeShopCurrency.LegendaryKeys => AcceptLegendaryKeys,
TradeShopCurrency.MythicalKeys => AcceptMythicalKeys,
TradeShopCurrency.EnlightenedCoins => AcceptEnlightenedCoins,
TradeShopCurrency.WeaklyEnlightenedCoins => AcceptWeaklyEnlightenedCoins,
_ => false,
};
/// <summary>
/// Required payment amount in <paramref name="currency"/> for a listing at <paramref name="basePy"/>.
/// Pyreals = face price; others = EC units × units-per-EC. Returns 0 when not accepted / unknown.
/// </summary>
public long RequiredAmount(long basePy, TradeShopCurrency currency)
{
if (basePy <= 0 || !Accepts(currency)) return 0;
if (currency == TradeShopCurrency.Pyreals) return basePy;
long perEc = UnitsPerEcBuy(currency);
if (perEc <= 0) return 0;
return EcUnitsForPyreals(basePy) * perEc;
}
/// <summary>
/// Pyreal-equivalent value of <paramref name="units"/> of <paramref name="currency"/> at buy rates.
/// Used when tallying mixed payments in a trade window.
/// </summary>
public long ToPyreals(TradeShopCurrency currency, long units)
{
if (units <= 0) return 0;
if (currency == TradeShopCurrency.Pyreals) return units;
if (currency == TradeShopCurrency.Mmd)
return units * Math.Max(1, PyrealPerMmd <= 0 ? 250_000 : PyrealPerMmd);
long perEc = UnitsPerEcBuy(currency);
if (perEc <= 0) return 0;
// Floor: each full EC-worth of this currency counts as PyrealsPerEcBuy.
long fullEc = units / perEc;
return fullEc * PyrealsPerEcBuy();
}
/// <summary>
/// True when the tallied payment covers <paramref name="basePy"/> via any single accepted currency
/// (UB-IT style alternatives) or via combined pyreal-equivalent.
/// </summary>
public bool PaymentMeetsPrice(long basePy, IReadOnlyDictionary<TradeShopCurrency, long> tallies)
{
if (basePy <= 0 || tallies == null || tallies.Count == 0) return false;
foreach (KeyValuePair<TradeShopCurrency, long> kv in tallies)
{
if (kv.Value <= 0 || !Accepts(kv.Key)) continue;
long need = RequiredAmount(basePy, kv.Key);
if (need > 0 && kv.Value >= need) return true;
}
// Mixed bag: sum pyreal-equivalent of accepted currencies.
long eq = 0;
foreach (KeyValuePair<TradeShopCurrency, long> kv in tallies)
{
if (kv.Value <= 0 || !Accepts(kv.Key)) continue;
eq += ToPyreals(kv.Key, kv.Value);
if (eq >= basePy) return true;
}
return false;
}
/// <summary>Human-readable price alternatives for a listing (UB BuildConversionForItem).</summary>
public string FormatAlternatives(long basePy)
{
if (basePy <= 0) return "";
var parts = new List<string>();
long ec = EcUnitsForPyreals(basePy);
void Add(TradeShopCurrency c, string label)
{
long n = RequiredAmount(basePy, c);
if (n > 0) parts.Add(n.ToString("N0", CultureInfo.InvariantCulture) + " " + label);
}
Add(TradeShopCurrency.Pyreals, "Py");
Add(TradeShopCurrency.Luminance, "Lum");
Add(TradeShopCurrency.LegendaryKeys, "LK");
Add(TradeShopCurrency.MythicalKeys, "MK");
Add(TradeShopCurrency.EnlightenedCoins, "EC");
Add(TradeShopCurrency.WeaklyEnlightenedCoins, "WEC");
Add(TradeShopCurrency.Mmd, "MMD");
if (parts.Count == 0 && ec > 0)
parts.Add(basePy.ToString("N0", CultureInfo.InvariantCulture) + " Py");
return string.Join(" / ", parts);
}
/// <summary>One-line rates summary for !help / UI.</summary>
public string RatesHelpLine()
{
long py = Math.Max(1, PyrealPerMmd <= 0 ? 250_000 : PyrealPerMmd);
var sb = new StringBuilder();
sb.Append("1 EC = ").Append(ConvBuyEcMmd.ToString("N0", CultureInfo.InvariantCulture)).Append(" MMD");
sb.Append(" = ").Append(ConvBuyEcLum.ToString("N0", CultureInfo.InvariantCulture)).Append(" Lum");
sb.Append(" = ").Append(ConvBuyEcLk.ToString("N0", CultureInfo.InvariantCulture)).Append(" LK");
sb.Append(" = ").Append(ConvBuyEcMk.ToString("N0", CultureInfo.InvariantCulture)).Append(" MK");
sb.Append(" = ").Append(ConvBuyEcWec.ToString("N0", CultureInfo.InvariantCulture)).Append(" WEC");
sb.Append(". 1 MMD = ").Append(py.ToString("N0", CultureInfo.InvariantCulture)).Append(" Py.");
return sb.ToString();
}
/// <summary>Copy field values onto <paramref name="dst"/> (settings clone / UI apply).</summary>
public void CopyTo(TradeShopRates dst)
{
if (dst == null) return;
dst.PyrealPerMmd = PyrealPerMmd;
dst.ConvBuyEcMmd = ConvBuyEcMmd;
dst.ConvBuyEcLum = ConvBuyEcLum;
dst.ConvBuyEcLk = ConvBuyEcLk;
dst.ConvBuyEcMk = ConvBuyEcMk;
dst.ConvBuyEcWec = ConvBuyEcWec;
dst.ConvSellEcMmd = ConvSellEcMmd;
dst.ConvSellEcLum = ConvSellEcLum;
dst.ConvSellEcLk = ConvSellEcLk;
dst.ConvSellEcMk = ConvSellEcMk;
dst.ConvSellEcWec = ConvSellEcWec;
dst.AcceptPyreals = AcceptPyreals;
dst.AcceptMmd = AcceptMmd;
dst.AcceptLuminance = AcceptLuminance;
dst.AcceptLegendaryKeys = AcceptLegendaryKeys;
dst.AcceptMythicalKeys = AcceptMythicalKeys;
dst.AcceptEnlightenedCoins = AcceptEnlightenedCoins;
dst.AcceptWeaklyEnlightenedCoins = AcceptWeaklyEnlightenedCoins;
}
}

View file

@ -0,0 +1,93 @@
// Pure tell / !buy parsing for Trade Shop (no host deps — unit-tested).
using System;
using System.Globalization;
using System.Text.RegularExpressions;
namespace RynthCore.Plugin.RynthAi.Trade;
/// <summary>Parse incoming AC tells and !buy selectors for the Trade Shop.</summary>
public static class TradeShopTellParse
{
private static readonly Regex TellLineRx = new(
@"^(?:<Tell:IIDString:\d+:(?<linkName>[^>]+)>[^<]*<\\Tell>|(?<plainName>.+?))\s+tells you,?\s*""(?<msg>.*)""\s*$",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled | RegexOptions.Singleline);
/// <summary>Parse AC "Name tells you, \"msg\"" (optional Tell IIDString link).</summary>
public static bool TryParseTell(string? text, out string sender, out string message)
{
sender = "";
message = "";
if (string.IsNullOrWhiteSpace(text)) return false;
Match m = TellLineRx.Match(text.Trim());
if (!m.Success) return false;
sender = m.Groups["linkName"].Success && m.Groups["linkName"].Length > 0
? m.Groups["linkName"].Value.Trim()
: m.Groups["plainName"].Value.Trim();
message = m.Groups["msg"].Value;
return sender.Length > 0;
}
/// <summary>!buy selector: 3 / #3 / id:3 / "Exact Name" / partial name. Bare numbers are slots.</summary>
public static (int? id, string text) ParseBuySelector(string? raw)
{
var p = ParsePriceSelector(raw);
if (p.slot.HasValue) return (p.slot, "");
return (null, p.text);
}
/// <summary>
/// Price / buy lookup: slot (#N, slot:N, id:N, bare 1..999), value (value:N, py:N, bare ≥1000),
/// or name text.
/// </summary>
public static (int? slot, long? valuePy, string text) ParsePriceSelector(string? raw)
{
string text = (raw ?? "").Trim();
if (text.Length == 0) return (null, null, "");
if ((text.StartsWith('"') && text.EndsWith('"') && text.Length > 1)
|| (text.StartsWith('\'') && text.EndsWith('\'') && text.Length > 1))
text = text[1..^1].Trim();
if (text.StartsWith('#'))
{
if (int.TryParse(text[1..].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int hashId) && hashId > 0)
return (hashId, null, "");
}
if (text.StartsWith("slot:", StringComparison.OrdinalIgnoreCase))
{
if (int.TryParse(text[5..].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int slot) && slot > 0)
return (slot, null, "");
}
if (text.StartsWith("id:", StringComparison.OrdinalIgnoreCase))
{
if (int.TryParse(text[3..].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int prefixed) && prefixed > 0)
return (prefixed, null, "");
}
if (text.StartsWith("value:", StringComparison.OrdinalIgnoreCase)
|| text.StartsWith("py:", StringComparison.OrdinalIgnoreCase)
|| text.StartsWith("price:", StringComparison.OrdinalIgnoreCase))
{
int colon = text.IndexOf(':');
if (long.TryParse(text[(colon + 1)..].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out long val) && val > 0)
return (null, val, "");
}
if (long.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out long n) && n > 0)
{
// Small bare numbers = catalog slot; large = pyreal price ask.
if (n < 1000) return ((int)n, null, "");
return (null, n, "");
}
return (null, null, text);
}
/// <summary>True when the tell body is a shop verb (with or without leading !).</summary>
public static bool IsShopVerb(string? cmd)
{
if (string.IsNullOrWhiteSpace(cmd)) return false;
string raw = cmd.Trim();
if (raw.StartsWith('!')) raw = raw[1..].Trim();
if (raw.Length == 0) return false;
string v = raw.Split((char[]?)null, 2, StringSplitOptions.RemoveEmptyEntries)[0].ToLowerInvariant();
return v is "help" or "hi" or "hello" or "shop" or "rates" or "rate" or "fx"
or "list" or "sheet" or "catalog" or "menu" or "price" or "cost" or "buy";
}
}

View file

@ -0,0 +1,42 @@
// Trade Shop floating window wiring on the plugin (Inventory button / /ra tradeshop ui).
using System;
using RynthCore.Plugin.RynthAi.Trade;
namespace RynthCore.Plugin.RynthAi;
public sealed partial class RynthAiPlugin
{
private TradeShopWindow? _tradeShopUi;
private void EnsureTradeShopWindow()
{
if (_tradeShopUi != null || _dashboard == null) return;
_tradeShopUi = new TradeShopWindow(
_dashboard.Settings,
() => _tradeShop?.Status ?? "Idle",
() => _tradeShop?.BankingSupported == true,
() => Host.HasGetSelectedItemId ? Host.GetSelectedItemId() : 0,
() => _objectCache,
cmd =>
{
if (string.IsNullOrWhiteSpace(cmd)) return;
// Prefer the real chat parser so /ra routes like a typed command.
if (Host.HasInvokeChatParser) Host.InvokeChatParser(cmd.Trim());
else HandleRaCommand(cmd.Trim());
});
}
private void RenderTradeShopWindow()
{
EnsureTradeShopWindow();
try { _tradeShopUi?.Render(); }
catch (Exception ex) { Host.Log($"[RynthAi] TradeShop window: {ex.Message}"); }
}
/// <summary>Toggle the Trade Shop editor (Inventory Storefront / /ra tradeshop ui).</summary>
internal void ToggleTradeShopWindow()
{
if (_dashboard?.Settings == null) return;
_dashboard.Settings.ShowTradeShopWindow = !_dashboard.Settings.ShowTradeShopWindow;
}
}

View file

@ -0,0 +1,280 @@
// Trade Shop ImGui window — catalog prices + bank/payment conversion rates (opened from Inventory).
using System;
using System.Collections.Generic;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi.Trade;
/// <summary>
/// Dedicated Trade Shop editor: list prices, conversion rates, and shop mode.
/// Opened from the Inventory panel Storefront button or <c>/ra tradeshop ui</c>.
/// </summary>
internal sealed class TradeShopWindow
{
private readonly SavedWindow _spot = new("RynthAi.TradeShop");
private readonly LegacyUiSettings _settings;
private readonly Func<string> _status;
private readonly Func<bool> _bankingSupported;
private readonly Func<uint> _selectedItemId;
private readonly Func<WorldObjectCache?> _cache;
private readonly Action<string>? _runCommand;
private string _newName = "";
private string _newSku = "";
private string _newAcct = "";
private string _newDesc = "";
private int _newPrice;
public TradeShopWindow(
LegacyUiSettings settings,
Func<string> status,
Func<bool> bankingSupported,
Func<uint> selectedItemId,
Func<WorldObjectCache?> cache,
Action<string>? runCommand = null)
{
_settings = settings;
_status = status;
_bankingSupported = bankingSupported;
_selectedItemId = selectedItemId;
_cache = cache;
_runCommand = runCommand;
}
public void Render()
{
if (!_settings.ShowTradeShopWindow) return;
ImGui.SetNextWindowSize(new Vector2(520, 560), ImGuiCond.FirstUseEver);
_spot.Apply();
bool open = _settings.ShowTradeShopWindow;
if (!ImGui.Begin("Trade Shop##RynthAiTradeShop", ref open))
{
_spot.Track();
ImGui.End();
_settings.ShowTradeShopWindow = open;
return;
}
_spot.Track();
_settings.ShowTradeShopWindow = open;
DrawBody();
ImGui.End();
}
/// <summary>Shared body (also usable from Advanced Settings).</summary>
public void DrawBody()
{
string status = _status?.Invoke() ?? "Not logged in";
SafeImGui.TextDisabled($"Status: {status}");
ImGui.Spacing();
ImGui.Checkbox("Shop enabled##TSw", ref _settings.TradeShopEnabled);
ImGui.SameLine();
ImGui.Checkbox("Test mode##TSw", ref _settings.TradeShopTestMode);
int mode = (int)_settings.TradeShopMode;
ImGui.RadioButton("Mode 1: stock + trade window + tells##TSw", ref mode, 0);
ImGui.SameLine();
ImGui.RadioButton("Mode 2: text / multi-account##TSw", ref mode, 1);
_settings.TradeShopMode = (TradeShopMode)mode;
bool banking = _bankingSupported?.Invoke() == true;
if (banking)
ImGui.Checkbox("Banking hook (this server supports payments)##TSw", ref _settings.TradeShopBankingHook);
else
SafeImGui.TextDisabled("Banking hook: not available on this world.");
ImGui.Spacing();
ImGui.Separator();
ImGui.Text("Auto-advertise");
ImGui.Separator();
DrawAdvertise();
ImGui.Spacing();
ImGui.Separator();
ImGui.Text("Payment / bank conversion rates (UB-IT)");
ImGui.Separator();
DrawRates();
ImGui.Spacing();
ImGui.Separator();
ImGui.Text("Catalog — set each item's price (pyreals)");
ImGui.Separator();
DrawCatalog();
}
private void DrawAdvertise()
{
ImGui.Checkbox("Auto-advertise catalog##TSad", ref _settings.TradeShopAdvertiseEnabled);
SafeImGui.SetItemTooltip("Posts the price sheet into an AC chat window on a timer (shop must be enabled).");
int ch = (int)_settings.TradeShopAdvertiseChannel;
ImGui.SetNextItemWidth(200);
if (ImGui.Combo("Chat window##TSad", ref ch, "Trade (/ct)\0General (/cg)\0LFG (/clfg)\0Fellowship (/f)\0Allegiance (/a)\0Local (say)\0Roleplay (/crp)\0Society (/cs)\0"))
_settings.TradeShopAdvertiseChannel = (TradeShopAdvertiseChannel)Math.Clamp(ch, 0, 7);
int every = TradeShopAdvertise.ClampIntervalSec(_settings.TradeShopAdvertiseIntervalSec);
ImGui.SetNextItemWidth(100);
if (ImGui.InputInt("Every (seconds)##TSad", ref every))
_settings.TradeShopAdvertiseIntervalSec = TradeShopAdvertise.ClampIntervalSec(every);
SafeImGui.TextDisabled($"Min {TradeShopAdvertise.MinIntervalSec}s, max {TradeShopAdvertise.MaxIntervalSec}s.");
string prefix = _settings.TradeShopAdvertisePrefix ?? "";
ImGui.SetNextItemWidth(280);
if (ImGui.InputText("Prefix##TSad", ref prefix, 64))
_settings.TradeShopAdvertisePrefix = prefix;
if (ImGui.Button("Advertise now##TSad"))
_runCommand?.Invoke("/ra tradeshop advertise now");
ImGui.SameLine();
SafeImGui.TextDisabled("Buyers: tell !help / !list / !price <slot|name|value> / !buy …");
}
private void DrawRates()
{
_settings.TradeShopRates ??= new TradeShopRates();
var rates = _settings.TradeShopRates;
ImGui.SetNextItemWidth(110);
int pyMmd = (int)Math.Clamp(rates.PyrealPerMmd, 1, int.MaxValue);
if (ImGui.InputInt("Pyreals per MMD##TSw", ref pyMmd))
rates.PyrealPerMmd = Math.Max(1, pyMmd);
LongRate("MMD per 1 EC (buy)##TSw", ref rates.ConvBuyEcMmd);
LongRate("Lum per 1 EC (buy)##TSw", ref rates.ConvBuyEcLum);
LongRate("LK per 1 EC (buy)##TSw", ref rates.ConvBuyEcLk);
LongRate("MK per 1 EC (buy)##TSw", ref rates.ConvBuyEcMk);
LongRate("WEC per 1 EC (buy)##TSw", ref rates.ConvBuyEcWec);
ImGui.TextDisabled(rates.RatesHelpLine());
ImGui.Spacing();
ImGui.Text("Accept payment in:");
ImGui.Checkbox("Py##TSwa", ref rates.AcceptPyreals); ImGui.SameLine();
ImGui.Checkbox("MMD##TSwa", ref rates.AcceptMmd); ImGui.SameLine();
ImGui.Checkbox("Lum##TSwa", ref rates.AcceptLuminance); ImGui.SameLine();
ImGui.Checkbox("LK##TSwa", ref rates.AcceptLegendaryKeys);
ImGui.Checkbox("MK##TSwa", ref rates.AcceptMythicalKeys); ImGui.SameLine();
ImGui.Checkbox("EC##TSwa", ref rates.AcceptEnlightenedCoins); ImGui.SameLine();
ImGui.Checkbox("WEC##TSwa", ref rates.AcceptWeaklyEnlightenedCoins);
}
private void DrawCatalog()
{
var rates = _settings.TradeShopRates ??= new TradeShopRates();
var list = _settings.TradeShopListings ??= new();
int removeAt = -1;
if (ImGui.BeginTable("##TScat", 5, ImGuiTableFlags.Borders | ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingStretchProp))
{
ImGui.TableSetupColumn("On", ImGuiTableColumnFlags.WidthFixed, 28);
ImGui.TableSetupColumn("Item", ImGuiTableColumnFlags.WidthStretch);
ImGui.TableSetupColumn("Price (py)", ImGuiTableColumnFlags.WidthFixed, 100);
ImGui.TableSetupColumn("Alt", ImGuiTableColumnFlags.WidthStretch);
ImGui.TableSetupColumn("", ImGuiTableColumnFlags.WidthFixed, 56);
ImGui.TableHeadersRow();
for (int i = 0; i < list.Count; i++)
{
var row = list[i];
if (row == null) continue;
ImGui.PushID(i);
ImGui.TableNextRow();
ImGui.TableNextColumn();
ImGui.Checkbox("##en", ref row.Enabled);
ImGui.TableNextColumn();
string label = (row.Sku.Length > 0 ? row.Sku + " — " : "") + (row.Name.Length > 0 ? row.Name : "(unnamed)");
ImGui.TextUnformatted(label);
if (row.LocatedOnAccount.Length > 0)
SafeImGui.TextDisabled("@" + row.LocatedOnAccount);
ImGui.TableNextColumn();
int price = (int)Math.Clamp(row.PricePyreals, 0, int.MaxValue);
ImGui.SetNextItemWidth(-1);
if (ImGui.InputInt("##price", ref price))
row.PricePyreals = Math.Max(0, price);
ImGui.TableNextColumn();
SafeImGui.TextDisabled(row.PricePyreals > 0 ? rates.FormatAlternatives(row.PricePyreals) : "—");
ImGui.TableNextColumn();
if (ImGui.SmallButton("Del"))
removeAt = i;
ImGui.PopID();
}
ImGui.EndTable();
}
if (removeAt >= 0)
list.RemoveAt(removeAt);
ImGui.Spacing();
ImGui.Text("Add listing");
ImGui.SetNextItemWidth(90);
ImGui.InputInt("Default price (py)##TSwnew", ref _newPrice);
if (ImGui.Button("Add selected item##TSw"))
TryAddSelected(list);
SafeImGui.TextDisabled("Multi-add: Ctrl/Shift-select in Inventory → right-click → Add to Trade Shop (sets default price below).");
ImGui.SetNextItemWidth(160);
ImGui.InputText("Name##TSwnew", ref _newName, 128);
ImGui.SetNextItemWidth(80);
ImGui.InputText("SKU##TSwnew", ref _newSku, 32);
ImGui.SameLine();
ImGui.SetNextItemWidth(100);
ImGui.InputText("Account##TSwnew", ref _newAcct, 64);
ImGui.SetNextItemWidth(280);
ImGui.InputText("Description##TSwnew", ref _newDesc, 256);
if (ImGui.Button("Add typed listing##TSw"))
{
string n = _newName.Trim();
if (n.Length > 0 && _newPrice > 0)
{
list.Add(new TradeShopListing
{
Sku = _newSku.Trim().Length > 0 ? _newSku.Trim() : "S" + (list.Count + 1),
Name = n,
Description = _newDesc.Trim(),
PricePyreals = _newPrice,
LocatedOnAccount = _newAcct.Trim(),
Enabled = true,
});
_newName = "";
_newSku = "";
_newAcct = "";
_newDesc = "";
_newPrice = 0;
}
}
}
private void TryAddSelected(List<TradeShopListing> list)
{
uint sel = _selectedItemId?.Invoke() ?? 0;
if (sel == 0) return;
if (list.Exists(l => l != null && l.ObjectId == sel)) return;
WorldObjectCache? cache = _cache?.Invoke();
WorldObject? wo = cache?[(int)sel];
if (wo == null || string.IsNullOrWhiteSpace(wo.Name)) return;
if (_newPrice <= 0) _newPrice = 1;
list.Add(new TradeShopListing
{
Sku = _newSku.Trim().Length > 0 ? _newSku.Trim() : "S" + (list.Count + 1),
Name = wo.Name,
Description = _newDesc.Trim(),
PricePyreals = _newPrice,
ObjectId = sel,
LocatedOnAccount = _newAcct.Trim(),
Enabled = true,
});
}
private static void LongRate(string label, ref long value)
{
ImGui.SetNextItemWidth(100);
int v = (int)Math.Clamp(value, 1, int.MaxValue);
if (ImGui.InputInt(label, ref v))
value = Math.Max(1, v);
}
}

View file

@ -15,6 +15,9 @@ namespace RynthCore.Plugin.RynthAi.Translate;
internal sealed class TranslateUi
{
// Where the player left the window, per character (Plugins/Shared/SavedWindow.cs).
private readonly SavedWindow _spot = new("RynthAi.ChatTranslate");
private static readonly Vector4 ColIn = new(0.45f, 0.85f, 0.95f, 1f);
private static readonly Vector4 ColOut = new(0.40f, 0.95f, 0.45f, 1f);
private static readonly Vector4 ColTest = new(0.95f, 0.80f, 0.35f, 1f);
@ -43,9 +46,11 @@ internal sealed class TranslateUi
ImGui.SetNextWindowSize(new Vector2(520, 420), ImGuiCond.FirstUseEver);
bool open = true;
_spot.Apply();
bool visible = ImGui.Begin("Chat Translate##rynthtranslate", ref open, ImGuiWindowFlags.NoCollapse);
if (!open) s.ShowWindow = false;
if (!visible) { ImGui.End(); return; }
_spot.Track();
RenderHeader();
RenderLanguageRow("##win", 110f);

View file

@ -15,6 +15,8 @@ namespace RynthCore.Plugin.RynthChat;
///
/// 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.
/// ,"auto":true (0.3.4) marks automated system text (ChatLine.Auto); absent otherwise,
/// and engines before 2026.10.18.30 ignore it.
/// Every non-ASCII character is written as a \uXXXX escape, so the export is
/// pure ASCII and survives the ANSI marshalling on both sides (before 0.2.0 an
/// accented name or the "→" of an outgoing tell arrived as "?").
@ -32,6 +34,19 @@ internal sealed class ChatBuffer
private int _count; // lines stored (<= _ring.Length)
private ulong _nextSeq = 1;
// Quest lists (2026-10-25): the /myquests and /qb list replies plugins ask for by themselves
// are hidden; one the player asked for in chat (RynthChat's input, NoteTypedQuestCommand)
// shows, under All. The window opens on the command and stays open while its lines keep coming.
private const long TypedQuestFirstLineMs = 15_000; // the command -> its first line
private const long QuestListIdleMs = 4_000; // between two lines of one list
private long _questShowUntilMs;
// The same for the /bank balance dump: hidden unless the player typed /bank (RynthILT's and
// ub-Rythai's own reads stay out of every tab, whether or not a plugin ate them).
private long _bankShowUntilMs;
// When the last quest-list line arrived: the eaten lines of a /qb list (its quest names
// match no fixed format) that follow it belong to the same hidden list.
private long _lastQuestListLineMs = long.MinValue / 2;
internal ChatBuffer(int capacity = DefaultCapacity)
{
_ring = new ChatLine?[Math.Clamp(capacity, MinCapacity, MaxCapacity)];
@ -70,7 +85,8 @@ internal sealed class ChatBuffer
}
}
internal void Add(string? text, int chatType)
/// <param name="loginBurst">The character is entering the world: its system text is automated.</param>
internal void Add(string? text, int chatType, bool loginBurst = false)
{
if (string.IsNullOrEmpty(text)) return;
string channel = ChatClassifier.IsItemInfo(text) ? ChatClassifier.Items
@ -78,9 +94,37 @@ internal sealed class ChatBuffer
: ChatClassifier.ChannelFor(text, chatType);
string? sender = ChatClassifier.SenderFor(text, chatType);
string ts = DateTime.Now.ToString("HH:mm:ss");
bool auto = ChatClassifier.IsAutomatedText(text, chatType)
|| ChatClassifier.IsLoginBurst(channel, chatType, loginBurst);
bool questList = ChatClassifier.IsQuestListText(text, chatType);
bool bankDump = ChatClassifier.IsBankBalanceDump(text);
lock (_lock)
{
bool hidden = false;
if (questList)
{
long now = Environment.TickCount64;
_lastQuestListLineMs = now;
if (now < _questShowUntilMs)
{
auto = false; // the player asked for it: under All like any reply
_questShowUntilMs = now + QuestListIdleMs;
}
else
hidden = true;
}
else if (bankDump)
{
long now = Environment.TickCount64;
if (now < _bankShowUntilMs)
{
auto = false;
_bankShowUntilMs = now + QuestListIdleMs;
}
else
hidden = true;
}
// 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] = new ChatLine
@ -91,12 +135,53 @@ internal sealed class ChatBuffer
ChatType = chatType,
Sender = sender,
Text = text,
Auto = auto,
Hidden = hidden,
};
_head = (_head + 1) % _ring.Length;
if (_count < _ring.Length) _count++;
}
}
/// <summary>
/// A plugin ate the line just dispatched (the engine calls this after every plugin has seen
/// it): marks it automated when it is the newest line here, with the same text. Returns
/// whether it was marked. The engine polls the scrollback on the same thread as the chat
/// dispatch, so the mark lands before the line is exported.
/// </summary>
internal bool NoteEaten(string? text)
{
if (string.IsNullOrEmpty(text)) return false;
lock (_lock)
{
if (_count == 0) return false;
ChatLine? newest = _ring[(_head - 1 + _ring.Length) % _ring.Length];
if (newest == null || !string.Equals(newest.Text, text, StringComparison.Ordinal)) return false;
long now = Environment.TickCount64;
bool typedQuestList = now < _questShowUntilMs;
bool bankDump = ChatClassifier.IsBankBalanceDump(text);
bool typed = bankDump ? now < _bankShowUntilMs : typedQuestList;
if (!typed) newest.Auto = true;
// A quiet /bank refresh's balance dump: not even the System tab.
if (bankDump) { if (!typed) newest.Hidden = true; }
// A line of a quest list nobody asked for in chat (a /qb list's quest names).
else if (!typedQuestList && now - _lastQuestListLineMs < QuestListIdleMs) newest.Hidden = true;
return true;
}
}
/// <summary>The player sent /myquests or /qb from the chat input: its list shows (game thread).</summary>
internal void NoteTypedQuestCommand()
{
lock (_lock) _questShowUntilMs = Environment.TickCount64 + TypedQuestFirstLineMs;
}
/// <summary>The player sent /bank (or /b) from the chat input: its balances show (game thread).</summary>
internal void NoteTypedBankCommand()
{
lock (_lock) _bankShowUntilMs = Environment.TickCount64 + TypedQuestFirstLineMs;
}
/// <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
@ -122,7 +207,7 @@ internal sealed class ChatBuffer
bool first = true;
foreach (ChatLine? line in lines)
{
if (line == null || line.Seq <= sinceSeq) continue;
if (line == null || line.Seq <= sinceSeq || line.Hidden) continue;
if (!first) sb.Append(',');
first = false;
@ -147,7 +232,9 @@ internal sealed class ChatBuffer
}
sb.Append(",\"text\":\"");
AppendEscaped(sb, line.Text);
sb.Append("\"}");
sb.Append('"');
if (line.Auto) sb.Append(",\"auto\":true");
sb.Append('}');
}
sb.Append(']');

View file

@ -32,6 +32,111 @@ internal static class ChatClassifier
internal static bool IsItemInfo(string text) =>
text.StartsWith("[RynthAi Item] ", StringComparison.Ordinal);
// ── Automated system text (0.3.4) ──────────────────────────────────────
// Lines the engine shows in the System tab only, not under All: replies to the
// commands plugins send by themselves (/myquests, /qb list), the server's login
// burst, and anything a plugin ate (the engine reports those, RynthChatNoteEaten).
/// <summary>AdminTell: a person typed it, so it is never automated text.</summary>
internal const int AdminTellType = 0x1F;
// A /myquests flag line: "key - N solves (unixtime)"description" max repeat". Its own timeout:
// static fields initialise in file order, and the shared Timeout below isn't set yet here.
private static readonly Regex _questFlagRe = new(@"^\S+ - \d+ solves \(\d*\)",
RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(20));
/// <summary>
/// True for the fixed formats of automated replies, whoever sent the command:
/// /myquests flag lines and their end lines, the /qb list headers and end lines,
/// and ACE's login welcome. Only for system-type lines, so player speech that
/// quotes them is untouched.
/// </summary>
internal static bool IsAutomatedText(string text, int chatType)
{
if (string.IsNullOrEmpty(text) || ChannelForType(chatType) != System || chatType == AdminTellType) return false;
return IsQuestListText(text, chatType)
|| text.StartsWith("Welcome to Asheron's Call", StringComparison.Ordinal);
}
/// <summary>
/// The /myquests and /qb list replies' fixed lines (flag lines, headers, end lines), system
/// type only. Hidden unless the player asked for the list in chat (ChatBuffer, 2026-10-25).
/// </summary>
internal static bool IsQuestListText(string text, int chatType)
{
if (string.IsNullOrEmpty(text) || ChannelForType(chatType) != System || chatType == AdminTellType) return false;
if (text.IndexOf(" solves (", StringComparison.Ordinal) > 0)
{
try { if (_questFlagRe.IsMatch(text)) return true; }
catch (RegexMatchTimeoutException) { }
}
return text.StartsWith("Quest list is empty", StringComparison.Ordinal)
|| text.StartsWith("[MyQuests] ", StringComparison.Ordinal)
|| text.StartsWith("Your completed quest bonus list", StringComparison.OrdinalIgnoreCase)
|| text.StartsWith("Your incomplete quest bonus list", StringComparison.OrdinalIgnoreCase)
|| text.StartsWith("Your current quest bonus count", StringComparison.OrdinalIgnoreCase)
|| text.StartsWith("Quest bonus list is empty", StringComparison.OrdinalIgnoreCase)
|| text.StartsWith("[QB] ", StringComparison.Ordinal)
|| IsDeedsListText(text);
}
// ACECustom's /deeds list (2026-10-24): "Your QB: 12,345 - Deeds bonuses are ON, ..." then one message
// per tier, "1000 QB (unlocked)\n * reward ...". RynthILT reads it for its QB Deeds window.
private static readonly Regex _deedsTierRe = new(@"^\d+ QB( \(unlocked\))?(\n|$)",
RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(20));
private static bool IsDeedsListText(string text)
{
if (text.StartsWith("Your QB: ", StringComparison.Ordinal))
return text.Contains(" - Deeds bonuses are ", StringComparison.Ordinal);
if (text.Length == 0 || !char.IsDigit(text[0])) return false;
try { return _deedsTierRe.IsMatch(text); }
catch (RegexMatchTimeoutException) { return false; }
}
/// <summary>A plain balance read: /bank or /b (or the @ forms) with no verb.</summary>
internal static bool IsBankBalanceCommand(string? text)
{
string t = (text ?? string.Empty).Trim();
return t.Equals("/bank", StringComparison.OrdinalIgnoreCase) || t.Equals("/b", StringComparison.OrdinalIgnoreCase)
|| t.Equals("@bank", StringComparison.OrdinalIgnoreCase) || t.Equals("@b", StringComparison.OrdinalIgnoreCase);
}
/// <summary>A chat command that asks for a quest list: /myquests, /qb, /qb list (or the @ forms).</summary>
internal static bool IsQuestListCommand(string? text)
{
string t = (text ?? string.Empty).Trim();
if (t.Length < 3 || (t[0] != '/' && t[0] != '@')) return false;
t = t.Substring(1);
return t.Equals("myquests", StringComparison.OrdinalIgnoreCase)
|| t.Equals("deeds", StringComparison.OrdinalIgnoreCase)
|| t.Equals("deeds list", StringComparison.OrdinalIgnoreCase)
|| t.Equals("qb", StringComparison.OrdinalIgnoreCase)
|| t.StartsWith("qb ", StringComparison.OrdinalIgnoreCase);
}
// "[BANK] Your balances are:" then "[BANK] Pyreals: 67,908,687,115", ... "[BANK] Prestige Coins: 98 (bound ...)".
private static readonly Regex _bankBalanceRe = new(@"^\[BANK\] (Your balances are:|[A-Za-z ]+: [\d,]+)",
RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(20));
/// <summary>
/// The server's /bank balance dump (its header and "Label: N" lines), not the other [BANK]
/// lines (errors, transfers). Only hidden when a plugin ate it (ChatBuffer.NoteEaten).
/// </summary>
internal static bool IsBankBalanceDump(string? text)
{
if (string.IsNullOrEmpty(text) || !text.StartsWith("[BANK] ", StringComparison.Ordinal)) return false;
try { return _bankBalanceRe.IsMatch(text); }
catch (RegexMatchTimeoutException) { return false; }
}
/// <summary>
/// True when a line counts as the login burst: system text (not an admin's tell) that
/// arrives while the character is entering the world (<paramref name="loginBurst"/>).
/// </summary>
internal static bool IsLoginBurst(string channel, int chatType, bool loginBurst) =>
loginBurst && channel == System && chatType != AdminTellType;
// ── Channel classification ─────────────────────────────────────────────
/// <summary>

View file

@ -9,4 +9,15 @@ internal sealed class ChatLine
internal int ChatType { get; init; }
internal string? Sender { get; init; }
internal string Text { get; init; } = "";
/// <summary>
/// Automated system text (0.3.4): a reply to a plugin's own command, the login burst, or
/// a line a plugin ate. Exported as "auto"; the engine shows it in the System tab only.
/// Set under ChatBuffer's lock (NoteEaten can set it after Add).
/// </summary>
internal bool Auto { get; set; }
/// <summary>
/// Never exported (2026-10-25): a plugin ate it and it is a periodic poll's reply nobody
/// asked to see (the /bank balance dump of RynthILT's quiet refresh). Set by NoteEaten.
/// </summary>
internal bool Hidden { get; set; }
}

View file

@ -88,6 +88,22 @@ public static unsafe class PluginExports
catch { return 0; }
}
/// <summary>
/// The engine, after every plugin has seen a chat line (0.3.4): a plugin ate it, so it is
/// automated text (a reply to a plugin's own command). Marks the newest scrollback line
/// when its text matches; returns 1 when marked. Engines before 2026.10.18.30 never call it.
/// </summary>
[UnmanagedCallersOnly(EntryPoint = "RynthChatNoteEaten", CallConvs = new[] { typeof(CallConvCdecl) })]
public static int NoteEaten(IntPtr textUtf16)
{
try
{
if (textUtf16 == IntPtr.Zero) return 0;
return Runtime.Plugin?.NoteEaten(Marshal.PtrToStringUni(textUtf16)) == true ? 1 : 0;
}
catch { return 0; }
}
[UnmanagedCallersOnly(EntryPoint = "RynthChatSendLine", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void SendLine(IntPtr ansiText)
{

View file

@ -1,4 +1,4 @@
using System;
using System;
using System.Runtime.InteropServices;
using RynthCore.PluginCore;
@ -7,10 +7,19 @@ 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.3.0");
// Previous release: 0.3.4.
internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.3.5");
/// <summary>How long after login completes the server's system text still counts as the login burst.</summary>
internal const long LoginBurstMs = 30_000;
private readonly ChatBuffer _buffer = new();
// The login burst: on until a login completes, then for LoginBurstMs more (the welcome,
// MOTD, house / allegiance notices and the plugins' login probes). On again at logout.
private volatile bool _loggedIn;
private long _loginBurstUntilMs;
public override int Initialize()
{
Host.Log("[RynthChat] Plugin initialized.");
@ -19,20 +28,25 @@ public sealed class RynthChatPlugin : RynthPluginBase
public override void OnLoginComplete()
{
_loggedIn = true;
System.Threading.Interlocked.Exchange(ref _loginBurstUntilMs, Environment.TickCount64 + LoginBurstMs);
Host.Log("[RynthChat] Login complete.");
}
public override void OnLogout()
{
_loggedIn = false;
Host.Log("[RynthChat] Logout.");
}
/// <summary>Entering the world, or within LoginBurstMs of the login completing.</summary>
private bool InLoginBurst =>
!_loggedIn || Environment.TickCount64 < System.Threading.Interlocked.Read(ref _loginBurstUntilMs);
public override void OnChatWindowText(string? text, int chatType, ref int eat)
{
// A plugin earlier in the dispatch ate the line (RynthAi's Meta Manager eats the
// reply to its own /myquests poll): keep it out of the chat window.
if (eat != 0) return;
_buffer.Add(text, chatType);
// Always buffer for RynthChat, even when an earlier plugin ate the line for retail.
_buffer.Add(text, chatType, InLoginBurst);
}
public override void OnChatBarEnter(string? text, ref int eat)
@ -44,12 +58,18 @@ public sealed class RynthChatPlugin : RynthPluginBase
internal int SetScrollbackCapacity(int lines) => _buffer.SetCapacity(lines);
/// <summary>The engine reports that a plugin ate the line just dispatched (RynthChatNoteEaten).</summary>
internal bool NoteEaten(string? text) => _buffer.NoteEaten(text);
// 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).
internal void SendLine(string text)
{
if (!Host.HasInvokeChatParser || string.IsNullOrWhiteSpace(text)) return;
// Typed by the player: a quest list they ask for shows (plugins' own reads stay hidden).
if (ChatClassifier.IsQuestListCommand(text)) _buffer.NoteTypedQuestCommand();
else if (ChatClassifier.IsBankBalanceCommand(text)) _buffer.NoteTypedBankCommand();
Host.InvokeChatParser(text);
}
}

View file

@ -0,0 +1,78 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthInventory.Data;
/// <summary>One character on the Banking tab: its saved balances (null = never read) and account.</summary>
internal sealed record BankRosterEntry(string Name, string Account, bool Current, IltBankRow? Bank);
/// <summary>
/// The Banking tab's character list (2026-10-13; the Mini Remote's Banking tab moved here). Every
/// character RynthILT has bank balances for on this server (its saved per-character state, so every
/// account played on this PC), plus every character Global Inventory has recorded on the same
/// server without a balance yet, so the list covers the same characters as the inventory does.
/// Pure: the tests feed it a parsed bank view and an index.
/// </summary>
internal static class BankRoster
{
/// <summary>
/// The merged list: the logged-in character first, then by name. A name in both lists keeps
/// RynthILT's balances and the inventory's account.
/// </summary>
public static List<BankRosterEntry> Build(IltBankView bank, InventoryIndex? index)
{
var byName = new Dictionary<string, BankRosterEntry>(StringComparer.OrdinalIgnoreCase);
foreach (IltBankRow r in bank.Characters)
byName[r.Name] = new BankRosterEntry(r.Name, string.Empty, r.Current, r);
if (index != null)
{
foreach (CharacterInfo ci in index.Characters)
{
// Same server only: a bank belongs to one world.
if (!SameServer(ci, bank)) continue;
string account = !string.IsNullOrEmpty(ci.Account) && ci.Account != "unknown" ? ci.Account : string.Empty;
if (byName.TryGetValue(ci.Name, out BankRosterEntry? have))
byName[ci.Name] = have with { Account = account, Current = have.Current || ci.IsCurrentCharacter };
else
byName[ci.Name] = new BankRosterEntry(ci.Name, account, ci.IsCurrentCharacter, null);
}
}
var list = new List<BankRosterEntry>(byName.Values);
list.Sort((a, b) => a.Current != b.Current ? (a.Current ? -1 : 1) : string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase));
return list;
}
/// <summary>
/// A recorded character is on the bank's server: the world RynthILT names when it gave one,
/// otherwise the server Global Inventory says you are on now.
/// </summary>
private static bool SameServer(CharacterInfo ci, IltBankView bank) =>
bank.World.Length > 0 ? InventoryIndex.SameName(ci.Server, bank.World) : ci.IsCurrentServer;
/// <summary>The sums over every character with a balance (one row of the same shape).</summary>
public static IltBankRow Totals(IReadOnlyList<BankRosterEntry> roster)
{
long py = 0, lum = 0, lk = 0, mk = 0, ec = 0, wec = 0, pc = 0;
foreach (BankRosterEntry e in roster)
{
if (e.Bank is not { } b) continue;
py += b.Pyreals; lum += b.Luminance; lk += b.LegendaryKeys; mk += b.MythicalKeys;
ec += b.EnlightenedCoins; wec += b.WeaklyEnlightenedCoins; pc += b.PrestigeCoins;
}
return new IltBankRow("Total", false, py, lum, lk, mk, ec, wec, pc, DateTime.MinValue);
}
/// <summary>
/// The withdraw / transfer amount typed in the form: a positive whole number (commas and spaces
/// allowed), or 0 when it isn't one.
/// </summary>
public static long ParseAmount(string? text)
{
if (string.IsNullOrWhiteSpace(text)) return 0;
string digits = text.Replace(",", string.Empty).Replace(" ", string.Empty).Trim();
return long.TryParse(digits, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out long n) && n > 0 ? n : 0;
}
}

View file

@ -56,6 +56,11 @@ internal sealed class InventoryQuery
public bool SearchSpells;
public InventorySort Sort = InventorySort.Name;
public bool Descending;
/// <summary>
/// "Find like this" (/ginv like, 2026-10-24): 1 keeps the item, 0 drops it, -1 drops it as
/// unknown (counted in <see cref="InventoryResult.LikeUnknown"/>). Null: no such filter.
/// </summary>
public Func<ItemRecord, int>? Like;
}
/// <summary>A total for one item name over the results: "Pyreal: 12,345 across 4 characters".</summary>
@ -76,6 +81,8 @@ internal sealed class InventoryResult
public readonly List<InventoryTotal> Totals = new();
public long TotalCount;
public int CharacterCount;
/// <summary>Items the like filter couldn't judge (not identified, or saved by an older RynthInventory).</summary>
public int LikeUnknown;
}
/// <summary>
@ -256,6 +263,12 @@ internal sealed class InventoryIndex
if (!hay.Contains(term, StringComparison.Ordinal)) { all = false; break; }
if (!all) continue;
}
if (q.Like != null)
{
int v = q.Like(r.Item);
if (v < 0) result.LikeUnknown++;
if (v <= 0) continue;
}
result.Rows.Add(r);
}

View file

@ -118,9 +118,45 @@ internal static class InventoryJson
}
}
if (it.Identified) sb.Append(", \"identified\": true");
if (it.HasFacts)
{
sb.Append(", \"class\": ").Append(it.ObjectClass.ToString(Inv));
if (it.Ints != null && it.Ints.Count > 0)
{
sb.Append(", \"ints\": {");
bool first = true;
foreach (KeyValuePair<int, int> kv in Sorted(it.Ints))
{
if (!first) sb.Append(", ");
first = false;
sb.Append('"').Append(kv.Key.ToString(Inv)).Append("\": ").Append(kv.Value.ToString(Inv));
}
sb.Append('}');
}
if (it.Doubles != null && it.Doubles.Count > 0)
{
sb.Append(", \"floats\": {");
bool first = true;
foreach (KeyValuePair<int, double> kv in Sorted(it.Doubles))
{
if (!first) sb.Append(", ");
first = false;
double v = double.IsFinite(kv.Value) ? kv.Value : 0;
sb.Append('"').Append(kv.Key.ToString(Inv)).Append("\": ").Append(v.ToString("R", Inv));
}
sb.Append('}');
}
}
sb.Append('}');
}
private static List<KeyValuePair<int, T>> Sorted<T>(Dictionary<int, T> d)
{
var list = new List<KeyValuePair<int, T>>(d);
list.Sort((a, b) => a.Key.CompareTo(b.Key));
return list;
}
private static void Time(StringBuilder sb, DateTime utc)
{
sb.Append('"');
@ -258,6 +294,25 @@ internal static class InventoryJson
}
string[] names = GetStrings(e, "spellNames");
it.SpellNames = names.Length == it.Spells.Length ? names : Array.Empty<string>();
if (e.TryGetProperty("class", out JsonElement cls) && cls.ValueKind == JsonValueKind.Number && cls.TryGetInt32(out int oc))
{
it.HasFacts = true;
it.ObjectClass = oc;
if (e.TryGetProperty("ints", out JsonElement ints) && ints.ValueKind == JsonValueKind.Object)
{
it.Ints = new Dictionary<int, int>();
foreach (JsonProperty p in ints.EnumerateObject())
if (int.TryParse(p.Name, NumberStyles.Integer, Inv, out int k) && p.Value.ValueKind == JsonValueKind.Number && p.Value.TryGetInt32(out int v))
it.Ints[k] = v;
}
if (e.TryGetProperty("floats", out JsonElement dbl) && dbl.ValueKind == JsonValueKind.Object)
{
it.Doubles = new Dictionary<int, double>();
foreach (JsonProperty p in dbl.EnumerateObject())
if (int.TryParse(p.Name, NumberStyles.Integer, Inv, out int k) && p.Value.ValueKind == JsonValueKind.Number && p.Value.TryGetDouble(out double v))
it.Doubles[k] = v;
}
}
return it;
}

View file

@ -54,6 +54,18 @@ internal sealed class ItemRecord
/// <summary>The client had appraisal data for it when scanned (spells, workmanship, set are then known).</summary>
public bool Identified;
// "Find like this in Global Inventory" (2026-10-24): what a loot rule from the Inventory
// panel's checklist tests, so it can be judged on this saved copy. Written by RynthInventory
// 0.1.5 and later; an older file's items have HasFacts false (only the fields above).
/// <summary>The facts below were read (the scanner is new enough).</summary>
public bool HasFacts;
/// <summary>AcObjectClass, as RynthAi classifies it (LootSdk AcItemClassifier).</summary>
public int ObjectClass;
/// <summary>Int properties a rule can test (LootItemAttributes.IntKeys, T11's virtual keys), non-zero only.</summary>
public Dictionary<int, int>? Ints;
/// <summary>Float properties a rule can test (LootItemAttributes.DoubleKeys), non-zero only.</summary>
public Dictionary<int, double>? Doubles;
public string PathText => Path.Length == 0 ? string.Empty : string.Join(" > ", Path);
}
@ -134,6 +146,25 @@ internal sealed class CharacterSnapshot
h.Add((uint)i.Spells.Length);
foreach (uint s in i.Spells) h.Add(s);
h.Add(i.Identified ? 1u : 0u);
if (!i.HasFacts) return;
h.Add((uint)i.ObjectClass);
if (i.Ints != null)
{
var keys = new List<int>(i.Ints.Keys);
keys.Sort();
foreach (int k in keys) { h.Add((uint)k); h.Add((uint)i.Ints[k]); }
}
h.Add(0xFACEu);
if (i.Doubles != null)
{
var keys = new List<int>(i.Doubles.Keys);
keys.Sort();
foreach (int k in keys)
{
long bits = BitConverter.DoubleToInt64Bits(i.Doubles[k]);
h.Add((uint)k); h.Add((uint)bits); h.Add((uint)(bits >> 32));
}
}
}
}

View file

@ -0,0 +1,278 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.Json;
namespace RynthCore.Plugin.RynthInventory.Data;
/// <summary>
/// A started trade, shared by every client through files (2026-10-25). Each account plays in its
/// own AC client, so the client that built the list can't give another account's items: it
/// writes the job, and the client logged into each account gives that account's items (logging
/// onto the character that holds them with /rc switchchar) and writes back how each went.
///
/// Files, in %APPDATA%\RynthCore\inventory\trades\:
/// &lt;id&gt;.job.json the job; written only by the client that started it (start, cancel)
/// &lt;id&gt;.&lt;account&gt;.status.json one per giving account; written only by that account's client
/// One writer per file, every write a temp file moved into place, so nothing is ever half read.
/// Hand-written JSON read with JsonDocument, like the other RynthInventory files.
/// </summary>
internal sealed class TradeJob
{
public string Id = string.Empty;
public string Server = string.Empty;
public string Recipient = string.Empty;
public string StartedBy = string.Empty;
public DateTime StartedUtc;
public bool Cancelled;
public readonly List<TradeItem> Items = new();
}
/// <summary>One account's report on a job: where its client is and each of its items.</summary>
internal sealed class TradeAccountStatus
{
public string Account = string.Empty;
/// <summary>The character that account's client is on (or switching to).</summary>
public string Character = string.Empty;
public string Message = string.Empty;
public DateTime UpdatedUtc;
/// <summary>Item index in the job -> (status, text).</summary>
public readonly Dictionary<int, (TradeItemStatus Status, string Text)> Items = new();
}
internal static class TradeJobs
{
/// <summary>Jobs (and their status files) this old are deleted by whichever client sees them.</summary>
private static readonly TimeSpan MaxAge = TimeSpan.FromHours(24);
public static string Folder(string inventoryRoot) => Path.Combine(inventoryRoot, "trades");
public static string NewId() =>
DateTime.UtcNow.ToString("yyyyMMdd-HHmmss", CultureInfo.InvariantCulture) + "-" +
Guid.NewGuid().ToString("N").Substring(0, 6);
private static string JobPath(string folder, string id) => Path.Combine(folder, id + ".job.json");
private static string StatusPath(string folder, string id, string account) =>
Path.Combine(folder, id + "." + SafeName(account) + ".status.json");
private static string SafeName(string s)
{
var sb = new StringBuilder();
foreach (char ch in s.Trim().ToLowerInvariant())
sb.Append(char.IsLetterOrDigit(ch) || ch is '-' or '_' ? ch : '_');
return sb.Length > 0 ? sb.ToString() : "unknown";
}
public static bool SameAccount(string a, string b) =>
string.Equals(a.Trim(), b.Trim(), StringComparison.OrdinalIgnoreCase);
// ── Writing ───────────────────────────────────────────────────────────
public static void WriteJob(string folder, TradeJob job)
{
var sb = new StringBuilder();
sb.Append("{\n \"id\": "); InventoryJson.Str(sb, job.Id);
sb.Append(",\n \"server\": "); InventoryJson.Str(sb, job.Server);
sb.Append(",\n \"recipient\": "); InventoryJson.Str(sb, job.Recipient);
sb.Append(",\n \"startedBy\": "); InventoryJson.Str(sb, job.StartedBy);
sb.Append(",\n \"startedUtc\": "); InventoryJson.Str(sb, job.StartedUtc.ToString("o", CultureInfo.InvariantCulture));
sb.Append(",\n \"cancelled\": ").Append(job.Cancelled ? "true" : "false");
sb.Append(",\n \"items\": [");
for (int i = 0; i < job.Items.Count; i++)
{
TradeItem it = job.Items[i];
sb.Append(i == 0 ? "\n {" : ",\n {");
sb.Append("\"characterKey\": "); InventoryJson.Str(sb, it.CharacterKey);
sb.Append(", \"character\": "); InventoryJson.Str(sb, it.CharacterName);
sb.Append(", \"account\": "); InventoryJson.Str(sb, it.Account);
sb.Append(", \"server\": "); InventoryJson.Str(sb, it.Server);
sb.Append(", \"name\": "); InventoryJson.Str(sb, it.ItemName);
sb.Append(", \"wcid\": ").Append(it.Wcid.ToString(CultureInfo.InvariantCulture));
sb.Append(", \"qty\": ").Append(it.Quantity.ToString(CultureInfo.InvariantCulture));
sb.Append(", \"itemId\": ").Append(it.ItemId.ToString(CultureInfo.InvariantCulture));
sb.Append('}');
}
sb.Append("\n ]\n}\n");
WriteAtomic(JobPath(folder, job.Id), sb.ToString());
}
public static void WriteStatus(string folder, string jobId, TradeAccountStatus st)
{
var sb = new StringBuilder();
sb.Append("{\n \"account\": "); InventoryJson.Str(sb, st.Account);
sb.Append(",\n \"character\": "); InventoryJson.Str(sb, st.Character);
sb.Append(",\n \"message\": "); InventoryJson.Str(sb, st.Message);
sb.Append(",\n \"updatedUtc\": "); InventoryJson.Str(sb, st.UpdatedUtc.ToString("o", CultureInfo.InvariantCulture));
sb.Append(",\n \"items\": [");
bool first = true;
foreach (var kv in st.Items)
{
sb.Append(first ? "\n {" : ",\n {");
first = false;
sb.Append("\"i\": ").Append(kv.Key.ToString(CultureInfo.InvariantCulture));
sb.Append(", \"status\": "); InventoryJson.Str(sb, kv.Value.Status.ToString());
sb.Append(", \"text\": "); InventoryJson.Str(sb, kv.Value.Text);
sb.Append('}');
}
sb.Append("\n ]\n}\n");
WriteAtomic(StatusPath(folder, jobId, st.Account), sb.ToString());
}
private static void WriteAtomic(string path, string text)
{
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
string tmp = path + "." + Environment.ProcessId.ToString(CultureInfo.InvariantCulture) + ".tmp";
File.WriteAllText(tmp, text);
File.Move(tmp, path, overwrite: true);
}
/// <summary>Deletes a job and every status file of it (Clear / New on the client that started it).</summary>
public static void Delete(string folder, string id)
{
try
{
if (!Directory.Exists(folder)) return;
foreach (string f in Directory.GetFiles(folder, id + ".*"))
try { File.Delete(f); } catch { }
}
catch { }
}
// ── Reading ───────────────────────────────────────────────────────────
/// <summary>Every job on <paramref name="server"/>, oldest first. Deletes jobs older than a day.</summary>
public static List<TradeJob> ReadJobs(string folder, string server)
{
var jobs = new List<TradeJob>();
try
{
if (!Directory.Exists(folder)) return jobs;
foreach (string path in Directory.GetFiles(folder, "*.job.json"))
{
TradeJob? job = ReadJob(path);
if (job == null) continue;
if (DateTime.UtcNow - job.StartedUtc > MaxAge)
{
Delete(folder, job.Id);
continue;
}
if (InventoryIndex.SameName(job.Server, server)) jobs.Add(job);
}
}
catch { }
jobs.Sort((a, b) => a.StartedUtc.CompareTo(b.StartedUtc));
return jobs;
}
public static TradeJob? ReadJob(string folder, string id) => ReadJob(JobPath(folder, id));
private static TradeJob? ReadJob(string path)
{
try
{
if (!File.Exists(path)) return null;
using var doc = JsonDocument.Parse(File.ReadAllText(path));
JsonElement r = doc.RootElement;
if (r.ValueKind != JsonValueKind.Object) return null;
var job = new TradeJob
{
Id = Str(r, "id"),
Server = Str(r, "server"),
Recipient = Str(r, "recipient"),
StartedBy = Str(r, "startedBy"),
Cancelled = r.TryGetProperty("cancelled", out JsonElement c) && c.ValueKind == JsonValueKind.True,
};
if (DateTime.TryParse(Str(r, "startedUtc"), CultureInfo.InvariantCulture,
DateTimeStyles.RoundtripKind, out DateTime started))
job.StartedUtc = started.ToUniversalTime();
if (job.Id.Length == 0) return null;
if (r.TryGetProperty("items", out JsonElement items) && items.ValueKind == JsonValueKind.Array)
{
foreach (JsonElement e in items.EnumerateArray())
{
if (e.ValueKind != JsonValueKind.Object) continue;
job.Items.Add(new TradeItem
{
CharacterKey = Str(e, "characterKey"),
CharacterName = Str(e, "character"),
Account = Str(e, "account"),
Server = Str(e, "server"),
ItemName = Str(e, "name"),
Wcid = (uint)Long(e, "wcid"),
Quantity = (int)Long(e, "qty"),
ItemId = (uint)Long(e, "itemId"),
});
}
}
return job;
}
catch
{
return null; // half-moved or broken: read again next time
}
}
/// <summary>Every account's status file for a job.</summary>
public static List<TradeAccountStatus> ReadStatuses(string folder, string id)
{
var list = new List<TradeAccountStatus>();
try
{
if (!Directory.Exists(folder)) return list;
foreach (string path in Directory.GetFiles(folder, id + ".*.status.json"))
{
TradeAccountStatus? st = ReadStatus(path);
if (st != null) list.Add(st);
}
}
catch { }
return list;
}
public static TradeAccountStatus? ReadStatus(string folder, string id, string account) =>
ReadStatus(StatusPath(folder, id, account));
private static TradeAccountStatus? ReadStatus(string path)
{
try
{
if (!File.Exists(path)) return null;
using var doc = JsonDocument.Parse(File.ReadAllText(path));
JsonElement r = doc.RootElement;
if (r.ValueKind != JsonValueKind.Object) return null;
var st = new TradeAccountStatus
{
Account = Str(r, "account"),
Character = Str(r, "character"),
Message = Str(r, "message"),
};
if (DateTime.TryParse(Str(r, "updatedUtc"), CultureInfo.InvariantCulture,
DateTimeStyles.RoundtripKind, out DateTime updated))
st.UpdatedUtc = updated.ToUniversalTime();
if (r.TryGetProperty("items", out JsonElement items) && items.ValueKind == JsonValueKind.Array)
{
foreach (JsonElement e in items.EnumerateArray())
{
if (e.ValueKind != JsonValueKind.Object) continue;
int i = (int)Long(e, "i");
if (Enum.TryParse(Str(e, "status"), out TradeItemStatus s))
st.Items[i] = (s, Str(e, "text"));
}
}
return st;
}
catch
{
return null;
}
}
private static string Str(JsonElement e, string name) =>
e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? string.Empty : string.Empty;
private static long Long(JsonElement e, string name) =>
e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt64(out long l) ? l : 0;
}

View file

@ -0,0 +1,173 @@
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthInventory.Data;
/// <summary>Status of one item in the trade queue.</summary>
internal enum TradeItemStatus
{
/// <summary>Waiting to be given (not yet attempted).</summary>
Pending,
/// <summary>GiveObjectTo sent, waiting for confirmation.</summary>
Giving,
/// <summary>Successfully given to the recipient.</summary>
Given,
/// <summary>Item not found on the character (moved, consumed or traded).</summary>
NotFound,
/// <summary>GiveObjectTo failed (target not nearby, API error, etc.).</summary>
Failed,
}
/// <summary>One item (or stack) to give to another player.</summary>
internal sealed class TradeItem
{
/// <summary>CharacterSnapshot.Key (server\u001fcharacter, lowercase).</summary>
public string CharacterKey = string.Empty;
/// <summary>Display name of the character that owns the item.</summary>
public string CharacterName = string.Empty;
/// <summary>Account name the character belongs to.</summary>
public string Account = string.Empty;
/// <summary>Server name.</summary>
public string Server = string.Empty;
/// <summary>Display name of the item.</summary>
public string ItemName = string.Empty;
/// <summary>Weenie class id (for finding by class if the exact object is gone).</summary>
public uint Wcid;
/// <summary>How many to give (0 = give the whole object; positive = split this many off a stack).</summary>
public int Quantity;
/// <summary>The object id at the time it was added (may not exist when the character logs in).</summary>
public uint ItemId;
/// <summary>Current status.</summary>
public TradeItemStatus Status = TradeItemStatus.Pending;
/// <summary>A short message for the player (e.g. "not found", "given").</summary>
public string StatusText = string.Empty;
}
/// <summary>What the trade list is doing.</summary>
internal enum TradePhase
{
/// <summary>The player is building the list (adding/removing items, typing a name).</summary>
Building,
/// <summary>Trade is running: giving items on the current character.</summary>
Executing,
/// <summary>Unused since the shared trade jobs (2026-10-25): each account's client switches itself.</summary>
WaitSwitch,
/// <summary>All items processed (some may have failed).</summary>
Complete,
/// <summary>Player cancelled the trade.</summary>
Cancelled,
}
/// <summary>
/// A list of items to give to another player, built from the Global Inventory window.
/// All items must be on the same server. The plugin executes it by giving each item
/// via GiveObjectTo when the owning character is logged in.
/// </summary>
internal sealed class TradeList
{
/// <summary>The name the player typed as the recipient (resolved to a nearby player id at give time).</summary>
public string Recipient = string.Empty;
/// <summary>The server all items must be on (set from the first item added).</summary>
public string Server = string.Empty;
/// <summary>The items to trade.</summary>
public readonly List<TradeItem> Items = new();
/// <summary>Current phase.</summary>
public TradePhase Phase = TradePhase.Building;
/// <summary>Status message shown at the top of the trade window.</summary>
public string Message = string.Empty;
/// <summary>The shared job this list was started as (TradeJobs); empty while building.</summary>
public string JobId = string.Empty;
public DateTime StartedUtc;
/// <summary>One line per giving account (where its client is, what it is doing), from the status files.</summary>
public readonly List<string> AccountLines = new();
/// <summary>Adds an item from an inventory row. Returns null on success, an error message on failure.</summary>
public string? Add(InventoryRow row, int quantity)
{
if (Phase != TradePhase.Building)
return "Can't add items while a trade is running.";
string server = row.Owner.Server;
if (Server.Length == 0)
Server = server;
else if (!InventoryIndex.SameName(Server, server))
return $"All items must be from the same server. This list is for {Server}.";
Items.Add(new TradeItem
{
CharacterKey = row.Owner.Key,
CharacterName = row.Owner.Name,
Account = row.Owner.Account,
Server = server,
ItemName = row.Item.Name,
Wcid = row.Item.Wcid,
Quantity = quantity,
ItemId = row.Item.Id,
});
return null;
}
/// <summary>Removes the item at <paramref name="index"/>.</summary>
public void RemoveAt(int index)
{
if (index >= 0 && index < Items.Count && Phase == TradePhase.Building)
{
Items.RemoveAt(index);
if (Items.Count == 0) Server = string.Empty;
}
}
/// <summary>Returns the distinct character keys that still have pending items, grouped.</summary>
public List<(string Key, string Name, string Account)> PendingCharacters()
{
var seen = new HashSet<string>(StringComparer.Ordinal);
var result = new List<(string, string, string)>();
foreach (TradeItem item in Items)
{
if (item.Status is TradeItemStatus.Pending or TradeItemStatus.Giving)
{
if (seen.Add(item.CharacterKey))
result.Add((item.CharacterKey, item.CharacterName, item.Account));
}
}
return result;
}
/// <summary>Items on a specific character that are still pending.</summary>
public List<TradeItem> PendingForCharacter(string characterKey)
{
var result = new List<TradeItem>();
foreach (TradeItem item in Items)
{
if (item.Status == TradeItemStatus.Pending
&& string.Equals(item.CharacterKey, characterKey, StringComparison.Ordinal))
result.Add(item);
}
return result;
}
/// <summary>True when every item has a terminal status (Given, NotFound, Failed).</summary>
public bool AllDone()
{
foreach (TradeItem item in Items)
if (item.Status is TradeItemStatus.Pending or TradeItemStatus.Giving) return false;
return true;
}
/// <summary>Counts by status.</summary>
public (int Given, int NotFound, int Failed, int Pending) Counts()
{
int given = 0, notFound = 0, failed = 0, pending = 0;
foreach (TradeItem item in Items)
{
switch (item.Status)
{
case TradeItemStatus.Given: given++; break;
case TradeItemStatus.NotFound: notFound++; break;
case TradeItemStatus.Failed: failed++; break;
default: pending++; break;
}
}
return (given, notFound, failed, pending);
}
}

View file

@ -2,7 +2,7 @@ using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthInventory;
internal enum InventoryVerb { Window, Scan, Keep, Reload, Status, Help, Search }
internal enum InventoryVerb { Window, Scan, Keep, Reload, Status, Help, Search, Bank, Trade }
/// <summary>
/// A parsed "/ginv ..." and the lines it answers with (2026-10-28: every command answers,
@ -22,12 +22,16 @@ internal readonly record struct InventoryCommand(InventoryVerb Verb, string Text
"reload" => new(InventoryVerb.Reload),
"status" => new(InventoryVerb.Status),
"help" or "?" => new(InventoryVerb.Help),
// The test branch's Banking tab (Infinite Leaftide) and trade list.
"bank" or "banking" => new(InventoryVerb.Bank),
"trade" => new(InventoryVerb.Trade),
_ => new(InventoryVerb.Search, a),
};
}
public const string Usage =
"/ginv (window), /ginv <text> (search), /ginv scan (rescan and save now), /ginv keep (record the open container as storage), /ginv reload, /ginv status";
"/ginv (window), /ginv <text> (search), /ginv trade (trade list), /ginv bank (every character's bank, Infinite Leaftide), /ginv scan (rescan and save now), /ginv keep (record the open container as storage), /ginv reload, /ginv status. "
+ "To find items like one you carry, right-click it in the Inventory panel: Find like this in Global Inventory (/ginv like clear removes that filter).";
public const string NoWindows =
"This RynthCore engine can't show plugin windows (it needs script windows, API v71, with ImGui on). Scanning and saving still work; /ginv status shows what was saved.";

View file

@ -1,4 +1,5 @@
using System;
using RynthCore.Plugin.Shared;
using RynthCore.Plugin.RynthInventory.Data;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
@ -41,6 +42,24 @@ internal sealed class InventoryContext
/// <summary>Forgets a character (moves its file aside). Returns a message for the player.</summary>
public Func<CharacterInfo, string> Forget = _ => string.Empty;
// ── Trade ────────────────────────────────────────────────────────────
/// <summary>The active trade list (null when none). Pump thread only.</summary>
public TradeList? Trade;
/// <summary>Action for trade commands from the trade view ("start", "cancel", "clear", "new").</summary>
public Action<string>? TradeCommand;
/// <summary>
/// RynthCore's active server is Infinite Leaftide (EngineServerState.IltId): the Banking page
/// (RynthILT's bank) shows and is read only then. Re-read every couple of seconds.
/// </summary>
public bool Ilt;
/// <summary>RynthILT's data interface (the bank).</summary>
public readonly RynthIltDataClient IltData = new();
/// <summary>The bank as RynthILT last reported it (None off Infinite Leaftide or before the first read).</summary>
public IltBankView Bank = IltBankView.None;
/// <summary>A Banking page action: a verb line for RynthILT (refresh, deposit, withdraw, transfer).</summary>
public Func<string, bool> BankCommand = _ => false;
/// <summary>
/// The plugin's chat lines, queued and written by the tick (Plugins/Shared/CommandReply.cs: the host
/// drops a line within 100 ms of another plugin's). Null before Initialize.

View file

@ -37,7 +37,7 @@ public static unsafe class PluginExports
[UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetVersion()
{
try { return LiteralPointer("0.1.1"u8); }
try { return LiteralPointer("0.1.7"u8); } // = RynthInventoryPlugin.Version
catch { return IntPtr.Zero; }
}

View file

@ -26,11 +26,15 @@
highest API use NOT behind a Has*/version check. Script windows (v71, HasUi) draw the search window and instance ids (v73) fall back to ownership info; below v71 it still scans and saves (/ginv status), as with ImGui off. -->
<RynthPluginMinEngineApi>66</RynthPluginMinEngineApi>
<RynthPluginDescription>Search every character's items.</RynthPluginDescription>
<!-- RynthServers (sibling repo): RynthILT's data interface, read for the Infinite Leaftide Banking page. -->
<RynthServersRoot Condition="'$(RynthServersRoot)' == ''">$(MSBuildThisFileDirectory)..\..\..\RynthServers\</RynthServersRoot>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginCore\RynthCore.PluginCore.csproj" />
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" />
<!-- "Find like this in Global Inventory" (/ginv like): the filter spec, its matcher and T11 parsing (2026-10-24). -->
<ProjectReference Include="..\..\Shared\RynthCore.LootSdk\RynthCore.LootSdk.csproj" />
</ItemGroup>
<ItemGroup>
@ -41,6 +45,10 @@
<ItemGroup>
<!-- Storage another plugin reads for us ("storage" commands: Aelrynth's vault from RynthAelrynth). Also linked by RynthInventory.Tests. -->
<Compile Include="..\Shared\StorageFeed.cs" Link="Shared\StorageFeed.cs" />
<!-- Which server RynthCore says is active: the Banking page shows on Infinite Leaftide only. -->
<Compile Include="..\Shared\EngineServerState.cs" Link="Shared\EngineServerState.cs" />
<!-- RynthILT's "RynthILT.Data" interface (RynthServers): the Banking page's balances for every character on the server. -->
<Compile Include="$(RynthServersRoot)Plugins\Shared\RynthIltDataApi.cs" Link="Shared\RynthIltDataApi.cs" />
<!-- How a chat command answers (2026-10-28): the shared reply queue and colours. -->
<Compile Include="..\Shared\CommandReply.cs" Link="Shared\CommandReply.cs" />
</ItemGroup>

Some files were not shown because too many files have changed in this diff Show more