diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/AcStubs.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/AcStubs.cs index 562b673..0440c0e 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/AcStubs.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/AcStubs.cs @@ -175,9 +175,26 @@ 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 SlayerBonusOr(key, live); + } + + /// + /// SlayerDamageBonus (float 138) from the weapon's text when the server sent none: ACE never sends it, servers + /// built on ACECustom write "- Shadow Slayer: 1.5x Damage" (2026-11-27, RynthCore.Loot.SlayerText). A sent value + /// wins; any other key reads . + /// + private double SlayerBonusOr(DoubleValueKey key, double value) + { + if ((int)key != RynthCore.Loot.SlayerText.SlayerDamageBonusKey) return value; + try + { + return RynthCore.Loot.SlayerText.Resolve((int)key, value, + () => new string?[] { Values(StringValueKey.LongDesc, string.Empty), Values(StringValueKey.Use, string.Empty) }); + } + catch { return value; } } } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.BuffProfile.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.BuffProfile.cs index 2449847..e5d1eea 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.BuffProfile.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.BuffProfile.cs @@ -70,16 +70,26 @@ public partial class BuffManager { _profileByKey.Clear(); var keys = new List(profile.Entries.Count); + var notBuffs = new List(); 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 heal, a transfer or a dispel never stays on: as a "buff" it would be cast on every + // pass. Buffing never casts one (IsLastingBuff); the vitals do the heals. + if (e.SpellId != 0 && !IsLastingBuff(e.SpellId)) + { + notBuffs.Add(e.Name); + continue; + } _profileByKey[e.Key] = e; keys.Add(e.Key); } _profileKeys = keys; ActiveBuffProfileName = profile.Name; + if (notBuffs.Count > 0) + _host.Log($"[RynthAi] Buff profile '{profile.Name}': left out {string.Join(", ", notBuffs)} (a heal or dispel, not a buff: the vitals do heals)."); } private void ClearBuffProfile(string chatLine) @@ -118,12 +128,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 in a fellowship's to pick (FellowshipVersion), not the profile's. + if (!c.IsBuff || c.Level > maxTier || !_spellManager.IsKnownSpellId(c.Id) || IsFellowshipSpell(c)) continue; + if (LevelLacksComponents(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) && !LevelLacksComponents(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; diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs index de46226..487d8d6 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs @@ -183,14 +183,26 @@ public partial class BuffManager : IDisposable private readonly Dictionary _buffFailCooldownUntil = new(); 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 _noComponentsUntil = new(); - private const double NoComponentsLevelSec = 600.0; - private bool LevelLacksComponents(int spellId) - => _noComponentsUntil.TryGetValue(spellId, out DateTime until) && RynthClock.Now < until; + // A spell LEVEL the server refused for missing components (a vital: Revitalize, Heal, Stamina + // to Mana...; a buff since 2026-11-27): that level is passed over for SpellManager + // .NoComponentsSec and the next lower level 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); a buff still + // did that until 2026-11-27. The list is SpellManager's, shared with combat's spell choice. + private bool LevelLacksComponents(int spellId) => _spellManager.LacksComponents(spellId); + + /// + /// A hard refusal answers the last cast sent (ActionPacer.LastCastSpellId); it is the pending + /// buff's or vital's unless another cast (combat's) went out after it. Before, an attack refused + /// for components while a heal was pending parked the heal. True with nothing to tell. + /// + private static bool RefusalIsForPending(int pendingSpellId) + { + int last = ActionPacer.LastCastSpellId; + return pendingSpellId == 0 || last == 0 || last == pendingSpellId; + } + + /// A spell the server refused for components: (spell name, what RynthAi does instead). The plugin shows it (Huds/CastWarningHud). + internal Action? NoComponentsWarning { get; set; } // Per-family SILENT no-show counter. Distinct from _buffFailCooldownUntil // (which catches chat-explicit hard rejects). This catches the /god case: @@ -3590,12 +3602,93 @@ public partial class BuffManager : IDisposable /// Casts that replaced an active buff of the same family at a lower level (tests, status). internal int BuffUpgrades { get; private set; } + /// + /// The spell a buff casts now: the highest level the skill allows (the Buffing tier lines) that + /// the character knows, passing over a level the server refused for components (the next lower + /// one goes instead); 0 when no level is castable, so the buff is left out until one is. + /// 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, LevelLacksComponents); + if (id == 0) id = ResolveProfileFallback(baseName, skill); + if (id == 0 || !IsLastingBuff(id)) return 0; + return FellowshipVersion(id, skill); } + /// True while the character is in a fellowship (the plugin sets it; null = never). + internal Func? InFellowship { get; set; } + + // The fellowship answer, kept a second: the picker asks per buff per tick. + 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; + } + + /// + /// With Use fellowship buffs in a fellowship on and in a fellowship: 's + /// fellowship version (the same family, so it replaces the self buff rather than stacking, and + /// every member gets it), at the highest level the skill allows that the character knows and that + /// wasn't refused for components, and never a lower level than (that + /// would weaken your own buff). Otherwise, or with none, . + /// Spotted by SilentKelpie (rynth PR #12); re-implemented here. + /// + 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 || IsFellowshipSpell(self)) return selfId; + int maxTier = _spellManager.GetHighestBuffSpellTier(skill); + SpellCatalogEntry? best = null; + foreach (SpellCatalogEntry c in SpellCatalog.Family(self.FamilyId)) + { + if (!IsFellowshipSpell(c) || c.DurationSec <= 0 || c.Level > maxTier || c.Level < self.Level) continue; + if (!_spellManager.IsKnownSpellId(c.Id) || LevelLacksComponents(c.Id)) continue; + if (best == null || c.Level > best.Level || (c.Level == best.Level && c.Power > best.Power)) best = c; + } + return best?.Id ?? selfId; + } + + /// A spell cast on the whole fellowship (ACE's catalog: target Fellowship, or "... all Fellowship members ..."). + internal static bool IsFellowshipSpell(SpellCatalogEntry c) => + c.Target.Equals("Fellowship", StringComparison.OrdinalIgnoreCase) + || c.Description.Contains("fellowship member", StringComparison.OrdinalIgnoreCase); + + /// + /// Buffing casts only spells that stay on (2026-11-27): never a heal for health, stamina or mana + /// (Heal Self, Revitalize, Mana Boost, Stamina to Mana and the other transfers; the vitals do + /// those, at Heal At and the like) and never a dispel, even when a list or a buff profile names + /// one. Lasting boosts (Regeneration, Rejuvenation, Mana Renewal) stay. The spell catalog decides + /// (a duration above 0 and a family that isn't a dispel); a spell it doesn't know goes by name. + /// Spotted by SilentKelpie (rynth PR #12); re-implemented here. + /// + 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); + return !IsVitalOrDispelName(SpellTableStub.GetById(spellId)?.Name ?? ""); + } + + // By name, for a spell the catalog doesn't know: the dispels (Evaporate / Extinguish / ... All + // Magic), the vital heals and the transfers (Stamina to Mana, Mana to Health, ...). + private static readonly System.Text.RegularExpressions.Regex VitalOrDispelName = new( + @"All Magic|Dispel|Heal Self|Revitalize|Mana Boost|\b(Health|Stamina|Mana) to (Health|Stamina|Mana)\b", + System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.CultureInvariant); + + internal static bool IsVitalOrDispelName(string name) => name.Length > 0 && VitalOrDispelName.IsMatch(name); + // 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 @@ -4087,6 +4180,10 @@ public partial class BuffManager : IDisposable internal static int GetSpellLevel(SpellInfo spell) { string n = spell.Name; + // A fellowship version (Use fellowship buffs in a fellowship): its name has no numeral (the + // name rules below read "Superior Volition of the Conclave" as V), so the catalog's level. + if (SpellCatalog.IsLoaded && SpellCatalog.Get(spell.Id) is { } fellow && IsFellowshipSpell(fellow) && fellow.Level > 0) + return fellow.Level; // "Aura of Incantation of Blood Drinker Self" etc. are tier 8 too (5400 s); they // fell to the "Aura of" rule below, got a 3600 s timer and recast 30 min early. if (n.StartsWith("Incantation") || n.Contains("Incantation of")) return 8; @@ -5078,22 +5175,48 @@ 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 while a buff or heal was pending), it is that cast's + // (CombatManager takes it) and ours is still in flight. + if (!RefusalIsForPending(_pendingSpellId)) + { + _host.Log($"[BuffChat] refusal is for the last cast sent ({SpellTableStub.GetById(ActionPacer.LastCastSpellId)?.Name ?? ActionPacer.LastCastSpellId.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 level refused for components is passed over (vitals, buffs and combat alike). + if (noComps) _spellManager.MarkNoComponents(_pendingSpellId); + if (noComps && pendingSpell != null) + NoComponentsWarning?.Invoke(pendingSpell.Name, noCompsVital + ? "RynthAi heals with a lower level of it instead, or a kit or potion." + : "RynthAi buffs with a lower level of it instead."); 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. FindBestSpellId passes over the 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, then tried + // the same top level again, 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); @@ -5111,9 +5234,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}'"); } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs index ed95b89..5982fcd 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs @@ -509,6 +509,10 @@ 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 _recentlyKilled = new(); + /// Attack spells already said in chat to lack components (once per spell per session). + private readonly HashSet _noComponentsAnnounced = new(); + /// An attack spell the server refused for components: (spell name, what RynthAi does instead). The plugin shows it (Huds/CastWarningHud). + internal Action? NoComponentsWarning { get; set; } private readonly List _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) @@ -650,6 +654,20 @@ public partial class CombatManager : IDisposable private readonly Dictionary _predictedDeathPending = new(); private readonly List _predictedDeathScratch = new(); + // A predicted kill that lived, and the bot not going back to it (R-20261127-144058-8cb2): the + // third Force Bolt at a Guardian Armoredillo was the predicted kill (hp~1800, dealt~1393), the + // swap locked a fresh Tamed Armoredillo, the bolt was resisted, and with Target Lock on the + // bot fought the fresh one to its death (13 s) before it finished the Guardian, at 23%. Now + // the predicted kill takes the lock back from the monster the swap locked once it is known to + // be alive (a damage, resist or evade line on it after the swap, or still alive when the swap's + // window ends), for ReclaimWindowMs after the swap. Fought again, it is never predicted again + // (PredictionFailed), so the two can't trade the lock. + private int _reclaimSurvivorId; // swapped off as a predicted kill (0: none) + private int _reclaimFromId; // the monster locked after that swap (0: none yet) + private DateTime _reclaimSwapAt = DateTime.MinValue; + private bool _reclaimReady; // the survivor is known to be alive + internal const double ReclaimWindowMs = 10_000; + internal void SetDamageStores(CreatureProfileStore? creatures, MonsterDamageStore? damage) { _creatureStore = creatures; @@ -853,6 +871,7 @@ public partial class CombatManager : IDisposable // says (TargetClock is that clock outside tests). A confirmed kill took the id out of // this map in OnKillNotification, so its longer suppression is never lifted here. _recentlyKilled.Remove(kv.Key); + NoteReclaimAlive(kv.Key); _host.Log(guessed ? $"[RynthAi] Kill notice matched by name to 0x{(uint)kv.Key:X8} '{_worldFilter[kv.Key]?.Name}' not confirmed " + $"{(now - kv.Value).TotalSeconds:0.0} s later and it is still alive: it is a target again." @@ -873,6 +892,7 @@ public partial class CombatManager : IDisposable if (id == 0 || !_predictedDeathPending.Remove(id)) return; _recentlyKilled.Remove(id); bool guessed = _guessedDeaths.Remove(id); + NoteReclaimAlive(id); _host.Log(guessed ? $"[RynthAi] Kill notice matched by name to 0x{(uint)id:X8} '{_worldFilter[id]?.Name}', but it took a {amount}-point hit: " + "it is alive, a target again." @@ -880,6 +900,88 @@ public partial class CombatManager : IDisposable "it is alive, a target again."); } + /// + /// "X resists your spell" or "X evaded your attack" (: "resisted" or + /// "evaded"): the attack reached X and didn't kill it (R-20261127-144058-8cb2: the predicted + /// kill's bolt was resisted 640 ms after the swap). The armed swap whose own cast it is is + /// called off, as its hit does (NoteFightHit); a predicted kill already swapped off is alive. + /// Matched by name, so nothing is done when another monster of that name could be the one. + /// + private void NoteMissOnPredicted(string who, string missed) + { + if (_predictKillSwapArmed && _fightTargetId != 0 && _predictArmTargetId == _fightTargetId && NameIs(_fightTargetId, who)) + { + double sinceCast = (RynthClock.Now - _predictArmCastAt).TotalMilliseconds; + if (sinceCast >= ArmedHitMinMs) + { + _predictKillSwapArmed = false; + _host.Log($"[RynthAi] Predicted kill shot 0x{(uint)_fightTargetId:X8} '{_worldFilter[_fightTargetId]?.Name}' called off: " + + $"it {missed} the cast {sinceCast:0} ms after it went out and is still alive " + + $"(cast#{_fightCastCount} hp~{_fightTargetMaxHp:0} dealt~{_fightDamage:0})."); + } + return; + } + if (_predictedDeathPending.Count == 0) return; + // The target's own miss (or can't tell): its name is the line's. The fight starts at the first + // cast, so the target just locked is checked too. + if (NameIs(_fightTargetId, who) || NameIs(activeTargetId, who) || NameIs(_lockedTargetId, who)) return; + int match = 0; + foreach (var kv in _predictedDeathPending) + { + if (!NameIs(kv.Key, who)) continue; + if (match != 0) return; // two of that name pending: can't tell which + match = kv.Key; + } + if (match == 0) return; + _predictedDeathPending.Remove(match); + _recentlyKilled.Remove(match); + bool guessed = _guessedDeaths.Remove(match); + NoteReclaimAlive(match); + _host.Log(guessed + ? $"[RynthAi] Kill notice matched by name to 0x{(uint)match:X8} '{_worldFilter[match]?.Name}', but it {missed} an attack: " + + "it is alive, a target again." + : $"[RynthAi] Predicted kill of 0x{(uint)match:X8} '{_worldFilter[match]?.Name}' {missed} an attack after the swap: " + + "it is alive, a target again."); + } + + /// The predicted kill swapped off last is alive: the selection may take the lock back to it. + private void NoteReclaimAlive(int id) + { + if (id == 0 || id != _reclaimSurvivorId) return; + if ((TargetClock() - _reclaimSwapAt).TotalMilliseconds > ReclaimWindowMs) { ClearReclaim(); return; } + _reclaimReady = true; + } + + private void ClearReclaim() + { + _reclaimSurvivorId = 0; + _reclaimFromId = 0; + _reclaimReady = false; + _reclaimSwapAt = DateTime.MinValue; + } + + /// + /// Target selection: the predicted kill swapped off last turned out alive, and the target is + /// still the monster that swap locked: the survivor, in the scan, inside Monster Range and of + /// at least the target's Priority, takes the lock back (Target Lock or not; not over a target + /// the player picked, and not while an attack at the target is on its way). Null: no switch. + /// + private string? ReclaimSurvivor(DateTime now, double acquireRange, out ScannedTarget back) + { + back = default; + if (_reclaimSurvivorId == 0) return null; + if ((now - _reclaimSwapAt).TotalMilliseconds > ReclaimWindowMs) { ClearReclaim(); return null; } + if (!_reclaimReady || _lockByPlayer || _lockedTargetId == 0 || _lockedTargetId != _reclaimFromId) return null; + bool found = false; + foreach (var c in _scannedTargets) + if (c.Id == _reclaimSurvivorId) { back = c; found = true; break; } + if (!found || back.Distance > acquireRange || PriorityOf(back.Id) < _lockedPriority) return null; + if (_blacklistManager.IsBlacklisted(back.Id) || _recentlyKilled.ContainsKey(back.Id)) return null; + if (AttackInFlightAtLocked(now)) return null; + return $"the predicted kill 0x{(uint)back.Id:X8} '{_worldFilter[back.Id]?.Name}' survived: back to it, " + + $"{(now - _reclaimSwapAt).TotalSeconds:0.0} s after the swap"; + } + /// True only when actively attacking a specific target. Unlike HasTargets, this is false between kills even when more monsters are scanned nearby. public bool IsActivelyEngaged => activeTargetId != 0; @@ -1229,6 +1331,7 @@ public partial class CombatManager : IDisposable { if (hasPlayerPos) Ghosts.OnPlayerLandblock(meCell >> 16); Ghosts.CheckMoved(TargetSpot); + Ghosts.ExpireSuspects(RynthClock.Now); } foreach (var wo in _worldFilter.GetLandscape()) @@ -2145,16 +2248,36 @@ public partial class CombatManager : IDisposable _predictKillSwapArmed = false; } // Hard reject: no components / unknown / no target. Same phrases the - // buff path treats as a hard rejection. Mark unresolvable so the - // tier loop drops down (faster than waiting out the no-chat valve). + // buff path treats as a hard rejection. The refusal names no spell: it + // answers the LAST cast sent, so a heal or buff sent after this attack is + // the one refused (BuffManager takes it) and ours stays pending. + else if ((lo.Contains("missing some required") || + lo.Contains("you do not have the") || + lo.Contains("have all the components for this spell")) + && ActionPacer.LastCastSpellId != 0 && ActionPacer.LastCastSpellId != _pendingOffensiveSpellId) + { + _host.Log($"[CombatCast] refusal '{text.Trim()}' is for the last cast sent " + + $"({SpellTableStub.GetById(ActionPacer.LastCastSpellId)?.Name ?? ActionPacer.LastCastSpellId.ToString()}), " + + $"not attack {_pendingOffensiveSpellId}: pending kept."); + } else if (lo.Contains("missing some required") || 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."); + // A known spell refused for components goes on SpellManager's no-components list, + // which TrySpellByName passes over, so the tier loop drops a level. The unresolvable + // set is purged of known spells and not read with a warm spellbook, so the same + // refused attack was cast again and again. Anything else stays unresolvable. + bool noComps = lo.Contains("components") || lo.Contains("missing some required"); + 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 && _noComponentsAnnounced.Add(_pendingOffensiveSpellId)) + _host.WriteToChat($"[RynthAi] No components for {name}: attacking with a lower level for {SpellManager.NoComponentsSec / 60:0} min.", 2); + if (noComps) + NoComponentsWarning?.Invoke(name, "RynthAi attacks with a lower level of it instead."); _pendingOffensiveSpellId = 0; _predictKillSwapArmed = false; // the cast never went out — don't swap off a live mob } @@ -2353,25 +2476,46 @@ public partial class CombatManager : IDisposable // ── 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. + // dangers (RynthILT: Infinite Leaftide's Empyrean Handler ring; the detection and its setting moved + // there 2026-10-20). 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. + // + // It runs away (2026-11-27): stop attacking, face directly away from the danger point and autorun + // (forward is the fastest motion), re-aiming away from it as it goes, until outside the radius plus + // BackAwayMarginYards (or BackAwayRunMaxMs, or the object is gone); attacks are held until then, and + // the same target is re-engaged. It was a single run-back jump, which covers a yard or two: never + // out of a 12-yard ring. The jump (face the object, Jumper "xs") stays only for an engine without + // heading snap or autorun. Spotted by SilentKelpie (Forgejo rynth PR #12); re-implemented here. /// BackAwayFrom results (RynthAi.Hub BackAwayFrom passes them on as they are). internal const int BackAwayStarted = 1, BackAwayNotNow = 0, BackAwayOutside = 2, BackAwayUnknownObject = 3, BackAwayJumpRefused = -1; - /// The jump charge range a caller may ask for (ms). + /// The jump charge range a caller may ask for (ms; the jump fallback only). internal const int BackAwayMinHoldMs = 100, BackAwayMaxHoldMs = 3000; /// After the jump: turn, land and one re-engage tick before attacks resume (ms). private const int BackAwaySettleMs = 2_200; + /// Yards past the radius the run goes before it stops. + internal const double BackAwayMarginYards = 4.0; + /// The longest a run lasts (blocked, or the danger keeps up). + internal const double BackAwayRunMaxMs = 6_000; + private const double BackAwayTurnRefreshMs = 250, BackAwayRunRefreshMs = 1_000; + /// Think last drove the run this long ago (another activity has the tick): the combat poll drives it. + private const double BackAwayOrphanMs = 150; + private const string BackAwaySource = "Combat/BackAway"; + private DateTime _backAwayUntil = DateTime.MinValue; private bool _backAwayJumpStarted; + // The run. + private bool _backAwayRunning; + private int _backAwayId; + private string _backAwayName = ""; + private double _backAwaySafeYards; + private DateTime _backAwayRunStart = DateTime.MinValue, _backAwayTurnAt = DateTime.MinValue, + _backAwayAutoRunAt = DateTime.MinValue, _backAwayTickAt = DateTime.MinValue; + /// /// Plugin wires this to Jumper.Start("xs", faceHeading, ms) — face the danger, then /// run-back jump (x+s) so the body moves away. Returns false if the jumper refused. @@ -2381,17 +2525,18 @@ public partial class CombatManager : IDisposable /// True while the wired jumper is mid-turn / charge / settle. public Func? JumpBusy { get; set; } - /// True while a back-away is holding combat (jump or settle). + /// True while a back-away is holding combat (the run, or the jump and its settle). public bool BackAwayActive => - _backAwayUntil != DateTime.MinValue && RynthClock.Now < _backAwayUntil; + _backAwayRunning || (_backAwayUntil != DateTime.MinValue && RynthClock.Now < _backAwayUntil); /// /// Backs the character away from when it is within the danger radius: /// , or Ring Range when that is larger (anything a ring reaches). - /// is the jump's charge (clamped to 100-3000 ms). Cancels the swing or - /// cast in progress, keeps the target. 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. + /// Runs away (see the section header); is only the fallback jump's charge + /// (clamped to 100-3000 ms). Cancels the swing or cast in progress, keeps the target. + /// 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 fallback jump didn't start. Pump thread. /// public int BackAwayFrom(int objectId, double radiusYards, int holdMs, string reason) { @@ -2414,9 +2559,27 @@ public partial class CombatManager : IDisposable return BackAwayOutside; } - // Face the danger, then Jumper "xs" (back + run) moves the body away from it. + bool haveHeading = TryGetHeadingTo(objectId, out double toIt, out _); + + // Stop the bound melee/missile attack (and a kite or an approach run, which steer too). + try + { + if (_host.HasCancelAttack) _host.CancelAttack(); + ReleaseHeldTurn(); + EndKite("back away"); + EndEnvironmentApproach("back away"); + } + catch { } + + if (haveHeading && _host.HasTurnToHeading && _host.HasSetAutoRun) + { + StartBackAwayRun(objectId, name, dist, danger, toIt, why); + return BackAwayStarted; + } + + // No heading snap or autorun on this engine: face the danger, then Jumper "xs" (back + run). float face = 0f; - if (TryGetHeadingTo(objectId, out double toIt, out _)) + if (haveHeading) face = (float)(toIt % 360.0); else if (PlayerCompass.TryGet(_host, out float curr)) face = curr; @@ -2426,19 +2589,11 @@ public partial class CombatManager : IDisposable // 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."); + $"at {dist:0.0} m (danger {danger:0.#} m), face {face:0} then xs (no heading snap / autorun on this engine)."); return BackAwayStarted; } _backAwayUntil = DateTime.MinValue; @@ -2446,12 +2601,99 @@ public partial class CombatManager : IDisposable return BackAwayJumpRefused; } + /// The run: face directly away from the danger and autorun; keeps it going. + private void StartBackAwayRun(int objectId, string name, double dist, double danger, double toIt, string why) + { + DateTime now = RynthClock.Now; + float away = (float)((toIt + 180.0) % 360.0); + _host.TurnToHeadingBy(BackAwaySource, away); + bool running = _host.SetAutoRunBy(BackAwaySource, true); + _backAwayRunning = true; + _backAwayId = objectId; + _backAwayName = name; + _backAwaySafeYards = danger + BackAwayMarginYards; + _backAwayRunStart = _backAwayTurnAt = _backAwayTickAt = now; + _backAwayAutoRunAt = running ? now : DateTime.MinValue; + _backAwayUntil = DateTime.MinValue; + _backAwayJumpStarted = false; + _host.Log($"[CombatEvade] Back away ({why}): running away from '{name}' at {dist:0.0} m " + + $"(danger {danger:0.#} m, stops at {_backAwaySafeYards:0.#} m), heading {away:0}" + + (running ? "." : " (autorun held; trying again).")); + } + /// - /// Holds Think from attacking while a back-away jump runs. Keeps the target so combat - /// re-engages as soon as the jumper settles. + /// One step of the run: stop when outside the radius plus the margin, when the danger is gone or + /// after ; else re-aim away from it and keep autorun on. True while it + /// holds attacks. + /// + private bool StepBackAwayRun(DateTime now) + { + _backAwayTickAt = now; + double elapsed = (now - _backAwayRunStart).TotalMilliseconds; + uint me = _host.GetPlayerId(); + double d = me != 0 && _backAwayId != 0 ? _worldFilter.Distance(unchecked((int)me), _backAwayId) : -1; + bool gone = d < 0 || d == double.MaxValue || double.IsNaN(d); + string? done = gone ? "the danger is gone" + : d >= _backAwaySafeYards ? $"clear at {d:0.0} m" + : elapsed >= BackAwayRunMaxMs ? $"run timed out at {d:0.0} m" + : null; + if (done != null) + { + EndBackAwayRun(); + _host.Log($"[CombatEvade] Back away done after {elapsed:0} ms ({done}) - re-engaging."); + return false; + } + if ((now - _backAwayTurnAt).TotalMilliseconds >= BackAwayTurnRefreshMs && TryGetHeadingTo(_backAwayId, out double toward, out _)) + { + if (_host.TurnToHeadingBy(BackAwaySource, (float)((toward + 180.0) % 360.0))) _backAwayTurnAt = now; + } + if ((now - _backAwayAutoRunAt).TotalMilliseconds >= BackAwayRunRefreshMs && _host.SetAutoRunBy(BackAwaySource, true)) + _backAwayAutoRunAt = now; + return true; + } + + /// Ends the run: autorun off. + private void EndBackAwayRun() + { + if (!_backAwayRunning) return; + _backAwayRunning = false; + _backAwayId = 0; + _backAwayRunStart = _backAwayTurnAt = _backAwayAutoRunAt = _backAwayTickAt = DateTime.MinValue; + try { _host.SetAutoRunBy(BackAwaySource, false); } catch { } + } + + /// + /// Pump-thread watch (each combat poll): combat or the macro off ends the run (autorun must not be + /// left on); Think not driving it (another activity has the tick) doesn't: the run steps from here, + /// bounded by its own limits. + /// + internal void PollBackAway() + { + if (!_backAwayRunning) return; + if (!_settings.EnableCombat || !_settings.IsMacroRunning) + { + EndBackAwayRun(); + _host.Log("[CombatEvade] Back away stopped: combat or the macro is off."); + return; + } + DateTime now = RynthClock.Now; + if ((now - _backAwayTickAt).TotalMilliseconds >= BackAwayOrphanMs) StepBackAwayRun(now); + } + + /// + /// Holds Think from attacking while a back-away runs (the run, or the jump and its settle). Keeps the + /// target so combat re-engages as soon as it is over. /// private bool TickBackAway() { + if (_backAwayRunning) + { + if (!StepBackAwayRun(RynthClock.Now)) return false; + LastCombatSkipReason = "back-away-run"; + _tickWait = CombatLatencyTracker.Wait.Other; + _stallWatch.Hold(RynthClock.Now); + return true; + } if (_backAwayUntil == DateTime.MinValue) return false; DateTime now = RynthClock.Now; bool jumperBusy = JumpBusy?.Invoke() == true; @@ -2503,12 +2745,14 @@ public partial class CombatManager : IDisposable private void NoteAttackReachedFromChat(string text) { int i = text.IndexOf(" evaded your attack", StringComparison.OrdinalIgnoreCase); - if (i < 0) i = text.IndexOf(" resists your spell", StringComparison.OrdinalIgnoreCase); + bool resisted = false; + if (i < 0) { i = text.IndexOf(" resists your spell", StringComparison.OrdinalIgnoreCase); resisted = true; } if (i <= 0) return; NoteEnvironmentEvidence(); // the spell or swing reached a monster string who = text.Substring(0, i).Trim(); if (who.StartsWith("The ", StringComparison.Ordinal)) who = who.Substring(4); if (who.Length == 0) return; + NoteMissOnPredicted(who, resisted ? "resisted" : "evaded"); // a predicted kill that lives (R-20261127-144058-8cb2) if (_pendingJudgeCastAt != DateTime.MinValue && NameIs(_pendingJudgeTargetId, who)) _damageSincePendingCast = true; @@ -2936,6 +3180,10 @@ public partial class CombatManager : IDisposable ForgetScanned(swapId); _predictedSwapAt[swapId] = TargetClock(); // fought again later = it didn't die (PredictionFailed) _predictedDeathPending[swapId] = TargetClock(); // still a monster in range until its death is confirmed + _reclaimSurvivorId = swapId; // goes back to it if it turns out alive (R-20261127-144058-8cb2) + _reclaimFromId = 0; + _reclaimSwapAt = TargetClock(); + _reclaimReady = false; _guessedDeaths.Remove(swapId); // Queue this predicted one-shot so it's CREDITED when its death confirms — // we may swap away before its KillerNotification. Capture the name LIVE @@ -4657,6 +4905,7 @@ public partial class CombatManager : IDisposable $"Skipped until the server sends anything about it or the landblock changes (ghosts now: {Ghosts.Count})."); if (id == activeTargetId || id == _lockedTargetId) DropTarget("ghost (the server doesn't have it)"); + MarkGhostPack(id, spot, lb); if (_host.HasRemoveClientObject) { int r = _host.RemoveClientObject((uint)id); @@ -4670,6 +4919,39 @@ public partial class CombatManager : IDisposable } } + // Ghosts come in packs (R-20261127-183401-bc02): a missile character shot at five Butcherous + // Eaters 11 m down behind a hill, one after another, each found to be a ghost only after 10-30 s + // of arrows into the hillside (the server silent about all of them for 65-115 s, none moving). + // A ghost's neighbours that the server has been as quiet about are skipped with it as suspects: + // never removed from the client, real again on any word from the server or a move (as a ghost + // is), and tried again after GhostTracker.SuspectMs. + internal const double GhostPackM = 10.0; + internal const double GhostPackSilentMs = 30_000; + + private void MarkGhostPack(int ghostId, GhostSpot spot, uint lb) + { + if (double.IsNaN(spot.X)) return; + DateTime now = RynthClock.Now; + int me = unchecked((int)(_playerId != 0 ? _playerId : _host.GetPlayerId())); + List? names = null; + foreach (var wo in _worldFilter.GetLandscape()) + { + if (wo.Id == ghostId || wo.Id == me || (int)wo.ObjectClass != (int)AcObjectClass.Monster) continue; + if (Ghosts.IsGhost(wo.Id) || TargetSpot(wo.Id) is not GhostSpot at) continue; + double dx = at.X - spot.X, dy = at.Y - spot.Y, dz = at.Z - spot.Z; + if (dx * dx + dy * dy + dz * dz > GhostPackM * GhostPackM) continue; + double silent = ServerSilentMs(wo.Id, now); + if (silent < GhostPackSilentMs) continue; // heard from lately, or no record (an idle monster says nothing too) + if (!Ghosts.MarkSuspect(wo.Id, wo.Name ?? "", at, lb, now)) continue; + (names ??= new()).Add($"0x{(uint)wo.Id:X8} '{wo.Name}' ({silent / 1000:0}s)"); + if (wo.Id == activeTargetId || wo.Id == _lockedTargetId) + DropTarget("likely ghost (silent next to a ghost)"); + } + if (names != null) + _host.Log($"[Ghost] {names.Count} more next to it (within {GhostPackM:0} m, nothing from the server for {GhostPackSilentMs / 1000:0}s or more) " + + $"skipped as likely ghosts too, until the server says anything about them or they move (not removed from the client): {string.Join(", ", names)}."); + } + /// The server sent an update for (RynthAiPlugin.OnUpdateObject). public void OnServerObjectUpdate(uint objectId) => Ghosts.NoteServerUpdate((int)objectId, RynthClock.Now); @@ -4929,6 +5211,7 @@ public partial class CombatManager : IDisposable ClearCombatTurnMotions(); ResetEnvironmentImpact("macro stopped"); ResetKite("macro stopped"); + EndBackAwayRun(); } return; } @@ -4944,6 +5227,8 @@ public partial class CombatManager : IDisposable catch (Exception ex) { _host.Log($"[EnvImpact] poll crashed: {ex.Message}"); } try { PollKite(); } catch (Exception ex) { _host.Log($"[Kite] poll crashed: {ex.Message}"); } + try { PollBackAway(); } + catch (Exception ex) { _host.Log($"[CombatEvade] back-away poll crashed: {ex.Message}"); } // A combat mode change ends the server's attack (HandleActionChangeCombatMode → // HandleActionCancelAttack), so out of Melee/Missile there is nothing bound to release. @@ -5183,6 +5468,16 @@ public partial class CombatManager : IDisposable : null; } + // A predicted kill that lived takes the lock back from the monster its swap locked + // (R-20261127-144058-8cb2), Target Lock or not. + if (_lockedTargetId != 0 && invalidWhy == null + && ReclaimSurvivor(now, acquireRange, out ScannedTarget survivor) is string reclaimWhy) + { + int sp = PriorityOf(survivor.Id); + LockTarget(survivor, sp, $"{SchemeName(scheme)}: {DescribeSchemeValue(scheme, survivor)}, priority {sp}, {DescribeTargetPos(survivor.Id)}", reclaimWhy); + return; + } + string? switchWhy = null; if (_lockedTargetId != 0 && invalidWhy == null) { @@ -5267,6 +5562,13 @@ public partial class CombatManager : IDisposable int bestId = best.Id; _lockByPlayer = false; // TryLockForcedTarget sets it after its own LockTarget _lockWasSwitch = _lockedTargetId != 0 && _lockedTargetId != bestId; + // The monster locked after a predicted-kill swap is the one the survivor may take the lock + // back from; the survivor locked again ends that (ReclaimSurvivor). + if (_reclaimSurvivorId != 0) + { + if (bestId == _reclaimSurvivorId) ClearReclaim(); + else if (_reclaimFromId == 0) _reclaimFromId = bestId; + } // A higher-priority monster that wasn't a candidate (out of sight, past Monster Range, // blacklisted...): named with why, so a report shows whether the priority was ignored. string passedOver = PassedOverNoteForLock(bestId, bestPriority); @@ -8543,6 +8845,10 @@ public partial class CombatManager : IDisposable // self-poisons. if (!_spellManager.TryResolveKnownSpellId(name, out int id)) return 0; + // Refused by the server for components (SpellManager.MarkNoComponents): the tier loop + // drops to the next lower level until it expires or more scarabs or tapers come in. + if (_spellManager.LacksComponents(id)) return 0; + // Scarab gate DISABLED (EnablePredictiveComponentGate=false). Field- // tested 2026-05-17, pid 15372: it rejected every KNOWN Force Arc // tier ("NO-SCARAB" 2724/2723) while the char had the scarab — the diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/GhostCheck.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/GhostCheck.cs index 0c681b7..c9bfd7a 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/GhostCheck.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/GhostCheck.cs @@ -87,7 +87,8 @@ internal sealed class GhostCheck /// internal sealed class GhostTracker { - public readonly record struct Ghost(int Id, string Name, GhostSpot Spot, uint Landblock, DateTime MarkedAt); + /// : not caught itself, skipped for standing silent next to a ghost (MarkSuspect). + public readonly record struct Ghost(int Id, string Name, GhostSpot Spot, uint Landblock, DateTime MarkedAt, bool Suspect = false); private readonly Dictionary _ghosts = new(); private readonly Dictionary _lastUpdate = new(); @@ -101,15 +102,52 @@ internal sealed class GhostTracker public IEnumerable All => _ghosts.Values; public int MarkedTotal { get; private set; } + public int SuspectTotal { get; private set; } + + /// A ghost, or a suspect (skipped by targeting either way). public bool IsGhost(int id) => id != 0 && _ghosts.ContainsKey(id); + /// A suspect, not a caught ghost: never removed from the client. + public bool IsSuspect(int id) => id != 0 && _ghosts.TryGetValue(id, out Ghost g) && g.Suspect; + public void Mark(int id, string name, GhostSpot spot, uint landblock, DateTime now) { if (id == 0) return; - if (!_ghosts.ContainsKey(id)) MarkedTotal++; + if (!_ghosts.TryGetValue(id, out Ghost was) || was.Suspect) MarkedTotal++; _ghosts[id] = new Ghost(id, name, spot, landblock, now); } + /// + /// A monster standing silent next to a ghost (R-20261127-183401-bc02): skipped as one too, cleared + /// the same ways (a server update or create, it moves, another landblock), and after + /// with no word either way it is tried again (ExpireSuspects). False when + /// it is already a ghost or a suspect. + /// + public bool MarkSuspect(int id, string name, GhostSpot spot, uint landblock, DateTime now) + { + if (id == 0 || _ghosts.ContainsKey(id)) return false; + SuspectTotal++; + _ghosts[id] = new Ghost(id, name, spot, landblock, now, Suspect: true); + return true; + } + + /// How long a suspect is skipped with no word about it either way. + public const double SuspectMs = 180_000; + + /// Suspects marked more than ago are tried again. + public void ExpireSuspects(DateTime now) + { + if (_ghosts.Count == 0) return; + _scratch.Clear(); + foreach (Ghost g in _ghosts.Values) + if (g.Suspect && (now - g.MarkedAt).TotalMilliseconds > SuspectMs) _scratch.Add(g.Id); + foreach (int id in _scratch) + { + _ghosts.Remove(id); + Cleared?.Invoke(id, "skipped 3 min next to a ghost with no word either way: tried again"); + } + } + /// The server sent something about (OnUpdateObject / OnCreateObject). public void NoteServerUpdate(int id, DateTime now, string what = "the server sent an update for it") { diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/SpellManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/SpellManager.cs index 57e5802..1126a87 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/SpellManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/SpellManager.cs @@ -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,43 @@ 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 above can't hold them: every + // known-spell refresh purges known ids from it, and with a warm spellbook the pickers never read + // it, so combat cast the same refused attack again and again. Combat (TrySpellByName), the vital + // and buff pickers and the above-tier heal pass a spell here over (the next lower level goes + // instead) until it expires or the pack gains scarabs or tapers. It goes on the server's answer, + // never a check of the pack: portal.dat's scarab names don't match ACE's inventory names + // (CombatManager.EnablePredictiveComponentGate). Spotted by SilentKelpie (rynth PR #12). + private readonly Dictionary _noComponentsUntil = new(); + private int _lastScarabs = -1, _lastTapers = -1; + + /// How long a spell the server refused for components is passed over. + public const double NoComponentsSec = 600.0; + + /// The server refused for missing components: pass it over for . + public void MarkNoComponents(int spellId) + { + if (spellId > 0) _noComponentsUntil[spellId] = RynthClock.Now.AddSeconds(NoComponentsSec); + } + + /// True while is passed over for missing components. + public bool LacksComponents(int spellId) + => _noComponentsUntil.TryGetValue(spellId, out DateTime until) && RynthClock.Now < until; + + /// + /// The pack's scarab and taper counts (the plugin's inventory scan): more of either than last + /// time (bought, looted, handed over) lets every spell refused for components be tried again. + /// The first reading only sets the base. + /// + 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(); + } + /// Persisted by BuffManager so the tier-7→6 drop is learned once /// (first rebuff per char) then instant on every later session/RL. public IReadOnlyCollection UnresolvableSpellIds => _unresolvableSpellIds; diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs index 2b3b274..f888a67 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs @@ -2054,7 +2054,16 @@ public class WorldObjectCache /// reported it DELETE-BEFORE-CLASSIFY when the corpse went away). /// public List RescueContainedItems(int containerId, IReadOnlyCollection known) + => RescueContainedItems(containerId, known, out _); + + /// + /// , and + /// : how many listed items can't be read yet (no name or position), + /// so the caller can wait for them instead of finishing the container without them. + /// + public List RescueContainedItems(int containerId, IReadOnlyCollection known, out int unread) { + unread = 0; var rescued = new List(); if (containerId == 0 || !_host.HasGetContainerContents) return rescued; @@ -2072,7 +2081,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); } diff --git a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs index ee6ca91..1cfc613 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs @@ -58,6 +58,13 @@ public sealed partial class RynthAiPlugin private const long AppraisalWaitMs = 3_000; // extra wait past the assess window for an item's appraisal private const long ContentsSweepMs = 500; // how often an open corpse's contents are checked for items the cache missed private long _lastContentsSweepAt; + // Before a corpse is finished, one more look at what the client says it holds. A corpse finished + // 130 ms after it opened, from the cache's items alone, left an item the client listed but could not + // read yet unjudged. The finish waits until FinalSweepMinMs after the open, and an unreadable listed + // item holds it up to UnreadContentsWaitMs after the open. + internal const long FinalSweepMinMs = 200; // the empty-corpse floor already + internal const long UnreadContentsWaitMs = 2_500; + private int _unreadHoldLoggedFor; private int _lastContentsSweepCorpse; private const long AppraisalHoldTimeoutMarginMs = 1_000; // stop holding this long before the corpse timeout @@ -1999,7 +2006,8 @@ 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."); MarkCorpseCompleted(corpseId); @@ -2013,6 +2021,19 @@ public sealed partial class RynthAiPlugin // moves (AC's one-item-at-a-time gate is the pending inventory request, not m_cBusy). if (firstMatchId != 0) { + // Gone from the client already (2026-11-28, Item Tool on a DreamWeave Legendary Chest): the + // server had cleared a leftover 'Platemail Gauntlets' out of the chest, the cache still + // listed it there, and judged on what was left of it (wcid 0) it matched a Keep rule. The + // pickup went out for an object that no longer existed and its absence read as "merged + // into a stack". Not sent, not counted as wanted (the Item Tool's nothing-taken stop). + if (ObjectGoneFromClient(firstMatchId)) + { + LootDiag($"[RynthAi] {LootTag}: skipping 0x{(uint)firstMatchId:X8} '{matchItemName}' on 0x{(uint)corpseId:X8} - gone from the client (the server removed it; the cache still listed it there)."); + _processedCorpseItems.Add(firstMatchId); + _corpseMatchedIds.Remove(firstMatchId); + return; + } + // Keep room for weapon swaps: with a full pack the bow can't be put away to // switch to the wand, so buffs and spell heals stop (2026-09-28 death). Leave // the corpse rather than filling the last slots; -1 = side-pack capacity unknown. @@ -2075,6 +2096,11 @@ public sealed partial class RynthAiPlugin return; } + // The main pack is full and a side pack has room: one item goes from the main pack to + // the side pack first (the client takes loot only into the main pack), then this one. + if (HoldForLootRoom(firstMatchId, matchItemName)) + return; + ChatLine($"[RynthAi] Loot rule: {matchItemName} -> [{matchActionLabel}] {matchRuleLabel}"); _currentLootItemId = firstMatchId; RynthCore.Plugin.RynthAi.ItemInfo.SelfSelect.Mark(unchecked((uint)firstMatchId)); @@ -2147,6 +2173,7 @@ public sealed partial class RynthAiPlugin _scrollLearner?.NoteLooted(firstMatchId, matchItemName, fromProfile: matchRuleLabel != ScrollLearner.RuleLabel); // Keep # per day: on its way, so it counts until it lands (then it is recorded). NotePerDaySent(firstMatchId); + NoteLootBroughtIn(firstMatchId); _currentLootItemMovePending = true; _currentLootItemMoveRequestedAt = now; // A queued move that the client or server turned away (the client's one-request @@ -2173,11 +2200,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."); MarkCorpseCompleted(corpseId); } } + /// + /// True while the corpse mustn't be finished yet: it opened under ago, the + /// client lists an item in it the cache hasn't got (looked up now; the next tick's sweep judges it), or it + /// lists one that can't be read yet (held up to after the open). + /// + private bool HoldForContentsNotSeen(int corpseId, List containedItems, long openAge) + { + if (_objectCache == null) return false; + if (openAge < FinalSweepMinMs) return true; + List 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 @@ -2858,6 +2917,20 @@ public sealed partial class RynthAiPlugin bool jumpAnswer = _currentLootItemJumped && inPack; bool believable = jumpAnswer || now - _currentLootItemMoveRequestedAt >= PickupAnswerMinMs; long since = now - _currentLootItemLeftAt; + + // Only a stack merges away. An item that is not one and is gone from the client without + // ever showing in a pack was not looted (2026-11-28: a Legendary Chest's 'Helmet' and + // 'Olthoi Sollerets' the client was letting go of were "merged into a stack in the pack"). + if (believable && !inPack && mergedInto == 0 && !_currentLootItemStackable + && (currentItem == null || ObjectGoneFromClient(_currentLootItemId))) + { + LootDiag($"[RynthAi] {LootTag}: 0x{(uint)_currentLootItemId:X8} '{_currentLootItemName}' is gone from the client without showing in a pack " + + $"({now - _currentLootItemMoveRequestedAt} ms after the send); not a stack, so it didn't merge: not looted."); + _processedCorpseItems.Add(_currentLootItemId); + ResetCurrentLootItem(); + _lastLootActionAt = now; + return; + } bool answered = landed && believable; if (!answered && since < PickupArriveMaxMs) return; @@ -3045,6 +3118,8 @@ public sealed partial class RynthAiPlugin } if (PickupHeldByServerAction()) return; // a retry now would be refused as too busy and use up an attempt + if (HoldForLootRoom(_currentLootItemId, _currentLootItemName)) + return; // the main pack filled meanwhile: room first, then the resend RynthCore.Plugin.RynthAi.ItemInfo.SelfSelect.Mark(unchecked((uint)_currentLootItemId)); Host.SelectItem(unchecked((uint)_currentLootItemId)); @@ -3171,7 +3246,98 @@ public sealed partial class RynthAiPlugin if ((RynthClock.Now - _mainPackFullWarnedAt).TotalMinutes < 5) return; _mainPackFullWarnedAt = RynthClock.Now; ChatLine($"[RynthAi] Main pack full: '{itemName}' is left. AC loots only into the main pack (or onto a stack you already carry), " + - "not straight into a side pack. Move items out of the main pack (RynthSort, cram) and looting takes everything again."); + "and nothing in the main pack could be moved to a side pack to make room. Free a main-pack slot and looting takes everything again."); + } + + // ── Room for loot in a full main pack (2026-11-28) ──────────────────── + // Since 8c14ea53 a pickup goes only into the main pack (the client refuses a corpse or chest item + // aimed straight at a side pack), so with the main pack full every item that joined no stack was + // left, even with side packs empty: looting looked stopped. Now the pickup first has one loose item + // moved from the main pack to a side pack (InventoryManager.MakeLootRoom), waits for that move's + // answer (the client refuses a pickup while it is out), and then takes the freed slot. Up to + // LootRoomMovesPerItem room moves per item; after that, or with nothing that may move, the item is + // left as before. + + private readonly List _lootBroughtIn = new(); // items the looter sent for, oldest first + private readonly Dictionary _lootRoomMoves = new(); // corpse item -> room moves made for it + private const int LootRoomMovesPerItem = 2; + private bool _lootRoomHoldLogged; + private long _lootRoomHoldTickAt; + + /// A pickup went out for : it is loot, so it is first to move when the main pack needs room. + private void NoteLootBroughtIn(int itemId) + { + _lootBroughtIn.Remove(itemId); + _lootBroughtIn.Add(itemId); + if (_lootBroughtIn.Count > 200) _lootBroughtIn.RemoveRange(0, _lootBroughtIn.Count - 200); + } + + private IEnumerable LootBroughtInNewestFirst(int except) + { + for (int i = _lootBroughtIn.Count - 1; i >= 0; i--) + if (_lootBroughtIn[i] != except) yield return _lootBroughtIn[i]; + } + + /// + /// True while the pickup of waits for room in the main pack: a room move + /// was just sent, or the last one has no answer yet. False when the item fits (a free main-pack + /// slot, or a stack it joins), when no side pack has room (the pickup's NoRoom finishes the corpse, + /// as before), or when no room move can be made (the item is left, as before). + /// + private bool HoldForLootRoom(int itemId, string itemName) + { + var inventory = _inventoryManager; + if (inventory == null || _objectCache == null || _playerId == 0 || !Host.HasMoveItemExternal) + return false; + if (inventory.MoveUnanswered(out string waiting)) + { + if (!_lootRoomHoldLogged) + { + _lootRoomHoldLogged = true; + LootDiag($"[RynthAi] {LootTag}: the pickup of '{itemName}' 0x{(uint)itemId:X8} waits: {waiting}."); + } + PauseCorpseClockForLootRoom(); + return true; + } + _lootRoomHoldLogged = false; + _lootRoomHoldTickAt = 0; + + int pid = unchecked((int)_playerId); + Func refused = id => _packRefusals.IsRefused(id, CorpseNowMs); + var item = _objectCache[itemId]; + if (WorldObjectCache.FindLootDestination(_objectCache.GetDirectInventory(forceRefresh: false), pid, Host, refused, item) != 0) + return false; + // Read afresh before moving anything: the last room move may have landed since the cached list + // was built (the pickup's own read then sees this list too). + var inv = _objectCache.GetDirectInventory(forceRefresh: true); + if (WorldObjectCache.FindLootDestination(inv, pid, Host, refused, item) != 0) + return false; + if (!WorldObjectCache.SidePackHasRoom(inv, pid, Host)) + return false; + _lootRoomMoves.TryGetValue(itemId, out int made); + if (made >= LootRoomMovesPerItem) + return false; + if (!inventory.MakeLootRoom(LootBroughtInNewestFirst(itemId), out string moved)) + return false; + + if (_lootRoomMoves.Count > 200) _lootRoomMoves.Clear(); + _lootRoomMoves[itemId] = made + 1; + LootDiag($"[RynthAi] {LootTag}: the main pack is full: moving {moved} so '{itemName}' 0x{(uint)itemId:X8} fits there."); + PauseCorpseClockForLootRoom(); + return true; + } + + /// The corpse's timeout clock stands still while a pickup waits for room (as PauseCorpseClockWhileHeld does for a server answer). + private void PauseCorpseClockForLootRoom() + { + long now = CorpseNowMs; + long last = _lootRoomHoldTickAt; + _lootRoomHoldTickAt = now; + if (last == 0 || _targetCorpseId == 0 || _corpseTargetSince == 0) + return; + long gap = now - last; + if (gap > 0 && gap <= PickupHoldMaxGapMs) + _corpseTargetSince += gap; } /// diff --git a/Plugins/RynthCore.Plugin.RynthAi/Dashboard/InstrumentDashboard.cs b/Plugins/RynthCore.Plugin.RynthAi/Dashboard/InstrumentDashboard.cs index e00d6a3..13d1dc8 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Dashboard/InstrumentDashboard.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Dashboard/InstrumentDashboard.cs @@ -1890,12 +1890,15 @@ internal sealed unsafe class InstrumentDashboard private Vector2 _filesAnchor; private string _filesName = string.Empty; - private enum FilesAsk { None, Replace, Delete } + private enum FilesAsk { None, Replace, Delete, ClearMonsters } private FilesAsk _filesAsk; private string _filesAskName = string.Empty; // the name Replace was asked for private string _filesStatus = string.Empty; private bool _filesStatusOk = true; private bool _filesBusy; // a button's action is queued + // A new settings profile starts from a copy of the one in use (Save As) or fresh (New): Copy + // each time the menu opens (2026-11-27, R-20261127-124531-b5d3). + private bool _filesFresh; /// The last result from the tick (a new object each time), applied on the next frame. private sealed record FilesOutcome(int Kind, ProfileVerb Verb, string Name, ProfileResult Result); @@ -1903,7 +1906,7 @@ internal sealed unsafe class InstrumentDashboard private static string FilesMenuTip(int kind) => kind switch { - 3 => "Settings profile: Save, Save As, Rename, Move to Deleted, Open folder.", + 3 => "Settings profile: Save, a new profile (a copy of this one, or fresh), Rename, Move to Deleted, Open folder, Clear the Monsters list.", 0 => "Nav: Save, Save As, New, Rename, Move to Deleted, Open folder.", 2 => "Meta: Save, Save As, New, Rename, Move to Deleted, Open folder.", 1 => "Loot profile: Loot Editor, Save As (a copy), New, Rename, Move to Deleted, Open folder.", @@ -1927,6 +1930,7 @@ internal sealed unsafe class InstrumentDashboard _filesAnchor = anchor; _filesAsk = FilesAsk.None; _filesBusy = false; // an action whose answer never came (a full queue) doesn't hold the buttons + _filesFresh = false; ImGui.OpenPopup(FilesMenuId); } @@ -2064,11 +2068,40 @@ internal sealed unsafe class InstrumentDashboard string name = _filesName.Trim(); bool named = idle && name.Length > 0; x = p.X; + if (settings) + { + // What a new profile starts from (2026-11-27): a copy of this one, Monsters list + // and all, or fresh. Copy unless Fresh is picked. + ImFontPtr sf = Font(RynthUiFont.Narrow11); + const string startLabel = "Start from:"; + dl.AddText(sf, sf.FontSize, new Vector2(x + Px(2), MathF.Round(p.Y + (h - sf.FontSize) * 0.5f)), _dim, startLabel); + x += sf.CalcTextSizeA(sf.FontSize, float.MaxValue, 0f, startLabel).X + Px(8); + string shortName = info.Name.Length > 16 ? info.Name[..15] + "..." : info.Name; // the row stays in the menu's width + if (FilesKey(dl, ref x, p.Y, h, "a copy of " + shortName, "##f_copy", true, + $"The new profile is a copy of '{info.Name}': every setting, its Monsters list, weapons and consumables.", on: !_filesFresh)) + _filesFresh = false; + if (FilesKey(dl, ref x, p.Y, h, "Fresh", "##f_fresh", true, + $"The new profile keeps '{info.Name}''s settings, but its Monsters list has only the Default row and it has no\n" + + "weapons, items or consumables: the weapons and consumables in your pack are added once it has loaded.\n" + + "Your buffs stay as they are (the buff profile isn't part of a settings profile).", on: _filesFresh)) + _filesFresh = true; + p.Y += h + gap; + x = p.X; + } string asTip = loot ? "Copy the loot profile in use to this name; RynthAi loots with the copy." - : settings ? "Save these settings as a profile with this name; it becomes the one in use." + : settings ? $"Save these settings as a new profile with this name, a copy of '{info.Name}' (its Monsters list too); it becomes the one in use." : $"Save the {(nav ? "route" : "meta")} under this name; it becomes the one in use."; - bool saveAs = FilesKey(dl, ref x, p.Y, h, "Save As", "##f_saveas", named && (!loot || info.HasFile), asTip); - if (saveAs || (enter && named && (!loot || info.HasFile))) RunFiles(ProfileVerb.SaveAs, name); + if (settings && _filesFresh) + { + bool fresh = FilesKey(dl, ref x, p.Y, h, "New", "##f_new", named, + "A fresh profile with this name (these settings, no monsters or items; weapons fill from your pack); it becomes the one in use."); + if (fresh || (enter && named)) RunFiles(ProfileVerb.New, name); + } + else + { + bool saveAs = FilesKey(dl, ref x, p.Y, h, "Save As", "##f_saveas", named && (!loot || info.HasFile), asTip); + if (saveAs || (enter && named && (!loot || info.HasFile))) RunFiles(ProfileVerb.SaveAs, name); + } if (!settings) { string newTip = loot ? "A new, empty loot profile with this name, opened in the Loot Editor (its Save creates the file)." @@ -2079,6 +2112,21 @@ internal sealed unsafe class InstrumentDashboard isDefault ? "The Default profile keeps its name." : "Rename the file in use to this name.")) RunFiles(ProfileVerb.Rename, name); p.Y += h + gap; + + if (settings && info.MonsterRules >= 0) + { + // The profile's Monsters list, and a Clear list that keeps the Default row (2026-11-27, + // R-20261127-124531-b5d3: a list copied into a new profile went one rule at a time). + ImFontPtr mf = Font(RynthUiFont.Narrow11); + string ml = info.MonsterRules == 1 ? "Monsters list: 1 rule" : $"Monsters list: {info.MonsterRules} rules"; + x = p.X; + dl.AddText(mf, mf.FontSize, new Vector2(x + Px(2), MathF.Round(p.Y + (h - mf.FontSize) * 0.5f)), _dim, ml); + x += mf.CalcTextSizeA(mf.FontSize, float.MaxValue, 0f, ml).X + Px(8); + if (FilesKey(dl, ref x, p.Y, h, "Clear list...", "##f_clearmon", idle && info.MonsterRules > 0, + info.MonsterRules > 0 ? $"Remove every Monsters rule of '{info.Name}' but the Default row (asks first)." : "Only the Default row is left.")) + _filesAsk = FilesAsk.ClearMonsters; + p.Y += h + gap; + } } // A question, when one is open. @@ -2099,6 +2147,15 @@ internal sealed unsafe class InstrumentDashboard if (FilesKey(dl, ref x, p.Y, h, "Cancel", "##f_no", true, "Keep it.")) _filesAsk = FilesAsk.None; p.Y += h + gap; } + else if (_filesAsk == FilesAsk.ClearMonsters) + { + string rules = info.MonsterRules == 1 ? "1 rule" : $"{info.MonsterRules} rules"; + p = FilesText(p, w, $"Clear the Monsters list of '{info.Name}'? Its {rules} go; the Default row stays.", _accent); + x = p.X; + if (FilesKey(dl, ref x, p.Y, h, "Clear list", "##f_yes", idle, "Remove them (the profile and the Monsters file are saved at once).")) RunFiles(ProfileVerb.ClearMonsters, string.Empty); + if (FilesKey(dl, ref x, p.Y, h, "Cancel", "##f_no", true, "Keep the list.")) _filesAsk = FilesAsk.None; + p.Y += h + gap; + } if (_filesBusy) p = FilesText(p, w, "Working...", _dim); else if (_filesStatus.Length > 0) p = FilesText(p, w, _filesStatus, _filesStatusOk ? _dim : HpText); @@ -2141,7 +2198,7 @@ internal sealed unsafe class InstrumentDashboard } /// A text key in the file menu at (, ), x moved past it. True when clicked (and enabled). - private bool FilesKey(ImDrawListPtr dl, ref float x, float y, float h, string label, string id, bool enabled, string tip) + private bool FilesKey(ImDrawListPtr dl, ref float x, float y, float h, string label, string id, bool enabled, string tip, bool on = false) { ImFontPtr f = Font(RynthUiFont.Narrow11); float tw = f.CalcTextSizeA(f.FontSize, float.MaxValue, 0f, label).X; @@ -2151,10 +2208,11 @@ internal sealed unsafe class InstrumentDashboard bool hot = ImGui.IsItemHovered(); SafeImGui.SetItemTooltip(tip); float r = Px(3); - dl.AddRectFilled(pos, pos + size, hot && enabled ? Mix(_key, _accent, 0.12f) : _key, r); - dl.AddRect(pos, pos + size, hot && enabled ? Mix(_line, _accent, 0.45f) : _line, r); + // on: the picked one of a choice (Start from: a copy / Fresh). + dl.AddRectFilled(pos, pos + size, on ? Mix(_key, _accent, 0.28f) : hot && enabled ? Mix(_key, _accent, 0.12f) : _key, r); + dl.AddRect(pos, pos + size, on ? _accent : hot && enabled ? Mix(_line, _accent, 0.45f) : _line, r); dl.AddText(f, f.FontSize, new Vector2(MathF.Round(pos.X + Px(7)), MathF.Round(pos.Y + (h - f.FontSize) * 0.5f)), - enabled ? _text : _faint, label); + on ? _accent : enabled ? _text : _faint, label); x += size.X + Px(4); return clicked && enabled; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/DoorInteractionController.cs b/Plugins/RynthCore.Plugin.RynthAi/DoorInteractionController.cs index 5636fc0..7833e13 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/DoorInteractionController.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/DoorInteractionController.cs @@ -2,15 +2,23 @@ // DoorInteractionController.cs — partial class RynthAiPlugin // // Detects closed doors while the macro is running and automatically opens them. -// Optionally uses lockpicks from the Consumable Items list on a door the server -// says is locked. +// Optionally (Auto-Unlock Doors) unlocks a door the server says is locked: a carried +// key first, then a lockpick from the Consumable Items list. // // State machine: // None -> Pending (a use waits for its turn) -> Opening (the use is out) -> // Settling (the server answered; the door gets a moment to swing) -> done, -// or back to Pending for another use, or Unlocking (a lockpick is out) -> Pending, +// or back to Pending for another use, or Unlocking (a key or a lockpick is out) -> Pending, // or Cooldown. // +// Keys before lockpicks (2026-11-27): the client can't tell which key fits (a key's KeyCode and a +// lock's LockCode are server-only), so each carried key not yet tried on this door goes on it, one +// at a time (at most DoorMaxKeyTries). ACE answers a key that doesn't fit with error 0x4B2 +// (KeyDoesntFitThisLock) and spends nothing, so the next key goes at once; a key that fits (0) is +// followed by an open. When no key is left, the lockpick as before. AC gives lockpicks the key item +// type too, so a lockpick is never tried as a key (IsLockpickObject). Spotted by SilentKelpie (Forgejo +// rynth PR #12); re-implemented here. +// // Two ways in: the proximity scan (OpenDoors setting, nearest closed door in // range), and a requested door (RequestDoorOpen): the nav engine's recovery // detour asks for the closed door on its next leg. A requested door is opened @@ -58,7 +66,12 @@ 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 - private long _doorSentAt; // when the last door use / lockpick went out + private int _doorWantKeyId; // Pending sends this carried key (the server said locked), not an open + private bool _doorUnlockingWithKey; // the use out in Unlocking is a key (else a lockpick) + private string _doorKeyName = ""; // that key's name + // Keys tried on the current door, by name (one of each name; the same key in another stack fits the same). + private readonly System.Collections.Generic.HashSet _doorKeysTried = new(StringComparer.OrdinalIgnoreCase); + 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) private bool _doorWaitLogged; // one "waits" line per Pending @@ -91,7 +104,11 @@ public sealed partial class RynthAiPlugin private const long DoorLockedSkipMs = 30000; private const int DoorMaxAttempts = 3; private const int DoorMaxPicks = 3; + /// Different carried keys tried on one door before the lockpick. + private const int DoorMaxKeyTries = 4; private const uint DoorTooBusyErr = 0x1D; + /// ACE WeenieError.KeyDoesntFitThisLock: nothing spent, try the next key. + private const uint DoorKeyDoesntFitErr = 0x4B2; private const float YardsToMeters = 0.9144f; // ACE: "The door is locked!"; other servers name the door ("The Gate is locked."). Server text only. @@ -169,6 +186,7 @@ public sealed partial class RynthAiPlugin _doorAttempts = 0; _doorPicks = 0; _doorWantLockpick = false; + ClearDoorKeys(); _navigationEngine?.Stop(); if (Host.HasStopCompletely) Host.StopCompletelyBy("Door"); @@ -233,8 +251,25 @@ public sealed partial class RynthAiPlugin MarkDoorOpenedAndReset(now); return false; } - bool answered = DoorUseAnswered(out _); + bool answered = DoorUseAnswered(out uint unlockErr); if (!answered && now - _doorSentAt < DoorAnswerMaxMs) return true; + if (_doorUnlockingWithKey) + { + _doorUnlockingWithKey = false; + if (answered && unlockErr == 0) + { + Host.Log($"[RynthAi] Door: {_doorKeyName} answered, opening 0x{(uint)_doorTargetId:X8} again"); + EnterDoorPending(now); + return true; + } + // Didn't fit (nothing spent), refused, or no answer: the next key, else the lockpick. + Host.Log(!answered + ? $"[RynthAi] Door: no answer to {_doorKeyName} in {now - _doorSentAt} ms; trying the next key or a lockpick" + : unlockErr == DoorKeyDoesntFitErr + ? $"[RynthAi] Door: {_doorKeyName} doesn't fit 0x{(uint)_doorTargetId:X8}; trying the next key or a lockpick" + : $"[RynthAi] Door: the server answered {_doorKeyName} with error 0x{unlockErr:X}; trying the next key or a lockpick"); + return OnDoorLocked(settings, now); + } Host.Log(answered ? $"[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"); @@ -294,7 +329,20 @@ public sealed partial class RynthAiPlugin int seqBefore = ActionPacer.UseDoneSeqNow(Host); bool sent; - if (_doorWantLockpick) + if (_doorWantKeyId != 0) + { + int keyId = _doorWantKeyId; + if (_objectCache?[keyId] is not WorldObject key || !IsCarriedByPlayer(keyId)) + { + Host.Log($"[RynthAi] Door: {_doorKeyName} is no longer in the pack; the next key or a lockpick"); + _doorWantKeyId = 0; + return OnDoorLocked(settings, now); + } + Host.Log($"[RynthAi] Door: using key {key.Name} on 0x{(uint)_doorTargetId:X8}"); + sent = Host.UseOnFor(unchecked((uint)keyId), unchecked((uint)_doorTargetId), "Door", "Auto Unlock Doors: the server says this door is locked; a carried key first"); + if (sent) { _doorWantKeyId = 0; _doorUnlockingWithKey = true; _doorState = DoorState.Unlocking; } + } + else if (_doorWantLockpick) { var lockpick = FindLockpickInConsumables(); if (lockpick == null) @@ -312,6 +360,7 @@ public sealed partial class RynthAiPlugin string reason = _doorAttempts > 0 ? $"try {_doorAttempts + 1}: still closed after the last use" : _doorPicks > 0 ? "open after the lockpick" + : _doorKeysTried.Count > 0 ? "open after the key" : _doorTargetRequested ? "the nav detour asked to open this door" : settings.OpenDoorsOnPathOnly ? $"Open Doors: closed door on the path, within {settings.OpenDoorRange:0} yd" : $"Open Doors: closed door within {settings.OpenDoorRange:0} yd"; @@ -389,7 +438,10 @@ public sealed partial class RynthAiPlugin return true; } - /// The server said the door is locked: a lockpick if allowed and carried, else leave it for a while. + /// + /// The server said the door is locked (or the last key didn't open it): with Auto Unlock Doors, the next + /// carried key not tried on it, else a lockpick if carried, else leave it for a while. + /// private bool OnDoorLocked(LegacyUiSettings settings, long now) { if (!settings.AutoUnlockDoors) @@ -398,6 +450,16 @@ public sealed partial class RynthAiPlugin EnterDoorCooldown(now, locked: true); return true; } + if (_doorKeysTried.Count < DoorMaxKeyTries && NextDoorKey() is WorldObject key) + { + _doorKeysTried.Add(key.Name); + _doorWantKeyId = key.Id; + _doorKeyName = key.Name; + _doorWantLockpick = false; + Host.Log($"[RynthAi] Door: 0x{(uint)_doorTargetId:X8} is locked - trying the carried key {key.Name} ({_doorKeysTried.Count} of at most {DoorMaxKeyTries})"); + EnterDoorPending(now); + return true; + } if (_doorPicks >= DoorMaxPicks) { Host.Log($"[RynthAi] Door: 0x{(uint)_doorTargetId:X8} still locked after {_doorPicks} lockpick(s), cooldown"); @@ -407,7 +469,8 @@ public sealed partial class RynthAiPlugin var lockpick = FindLockpickInConsumables(); if (lockpick == null) { - Host.Log($"[RynthAi] Door: the server says 0x{(uint)_doorTargetId:X8} is locked but there's no lockpick in consumables, cooldown"); + string keys = _doorKeysTried.Count > 0 ? $"none of the {_doorKeysTried.Count} carried key(s) opened it and " : ""; + Host.Log($"[RynthAi] Door: the server says 0x{(uint)_doorTargetId:X8} is locked but {keys}there's no lockpick in consumables, cooldown"); EnterDoorCooldown(now, locked: true); return true; } @@ -459,9 +522,26 @@ public sealed partial class RynthAiPlugin _doorAttempts = 0; _doorPicks = 0; _doorWantLockpick = false; + ClearDoorKeys(); _doorTargetRequested = false; } + private void ClearDoorKeys() + { + _doorWantKeyId = 0; + _doorUnlockingWithKey = false; + _doorKeyName = ""; + _doorKeysTried.Clear(); + } + + /// The next carried key (never a lockpick) whose name hasn't been tried on this door, or null. + private WorldObject? NextDoorKey() + { + foreach (WorldObject wo in CarriedKeys()) + if (!_doorKeysTried.Contains(wo.Name)) return wo; + return null; + } + /// /// Nav recovery: open this door on the next tick, whether or not OpenDoors is on. /// Ignored while another door is being handled (the detour asks again later). diff --git a/Plugins/RynthCore.Plugin.RynthAi/Huds/CastWarningHud.cs b/Plugins/RynthCore.Plugin.RynthAi/Huds/CastWarningHud.cs new file mode 100644 index 0000000..282d299 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Huds/CastWarningHud.cs @@ -0,0 +1,104 @@ +// CastWarningHud.cs — the "Out of components" warning: a small window at the top of the game view +// when the server refuses one of RynthAi's spells for missing components, naming the spell and +// what RynthAi does instead (a lower level of it). OK closes it; it closes by itself after +// ShownForMs; the same spell warns again at most once every RepeatSameMs (its refusals repeat +// until the level is tried again). Settings > General > Show No Components Warning turns it off; +// the chat lines stay either way. Drawn by RynthAi itself (the layer rule: plugins own their screens). +// Spotted by SilentKelpie (rynth PR #12); re-implemented here. +// Post: the pump thread (the chat handlers). Render: the render thread (OnRender / OnRenderOverlay). +using System; +using System.Numerics; +using ImGuiNET; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthAi.Huds; + +internal sealed class CastWarningHud +{ + /// How long a warning stays up without OK. + internal const long ShownForMs = 30_000; + /// The same spell warns again at most this often. + internal const long RepeatSameMs = 120_000; + + private static readonly Vector4 ColTitle = new(1.00f, 0.55f, 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 readonly Func _nowMs; + private readonly Func _enabled; + private readonly object _gate = new(); + private string _spell = "", _body = ""; + private long _shownAt; + private bool _up; + private string _lastSpell = ""; + private long _lastSpellAt; + + public CastWarningHud(Func enabled, Func? nowMs = null) + { + _enabled = enabled; + _nowMs = nowMs ?? (() => Environment.TickCount64); + } + + /// + /// Shows the warning for ; says what + /// RynthAi does instead. Nothing with the setting off, or for the same spell within + /// . Any thread. + /// + public void Post(string spellName, string whatNext) + { + if (string.IsNullOrWhiteSpace(spellName) || !_enabled()) return; + long now = _nowMs(); + lock (_gate) + { + if (string.Equals(spellName, _lastSpell, StringComparison.OrdinalIgnoreCase) && now - _lastSpellAt < RepeatSameMs) return; + _lastSpell = spellName; + _lastSpellAt = now; + _spell = spellName; + _body = whatNext ?? ""; + _shownAt = now; + _up = true; + } + } + + /// The warning up now (spell, what RynthAi does), or null. Closes an expired one, or any with the setting off. + internal (string Spell, string Body)? Current() + { + lock (_gate) + { + if (!_up) return null; + if (!_enabled() || _nowMs() - _shownAt > ShownForMs) { _up = false; return null; } + return (_spell, _body); + } + } + + /// OK: closes the warning up now. + public void Dismiss() + { + lock (_gate) _up = false; + } + + /// The warning window, while one is up. Render thread, RynthAi's ImGui context current. + public void Render() + { + if (Current() is not { } w) return; + + // Top centre of the game view, clear of the character and the chat. It isn't moved, so it + // keeps no saved place. + 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); + const ImGuiWindowFlags flags = ImGuiWindowFlags.NoTitleBar | ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoSavedSettings + | ImGuiWindowFlags.NoFocusOnAppearing | ImGuiWindowFlags.NoNav | ImGuiWindowFlags.NoMove; + bool visible = ImGui.Begin("Out of components##rynthcastwarn", flags); + if (visible) + { + SafeImGui.TextColored(ColTitle, "Out of components: " + w.Spell); + if (w.Body.Length > 0) SafeImGui.TextColored(ColBody, w.Body); + SafeImGui.TextColored(ColHint, "Restock scarabs and tapers to cast it again."); + if (ImGui.Button("OK##rynthcastwarn")) Dismiss(); + ImGui.SameLine(); + ImGui.TextDisabled("(Settings > General turns this off)"); + } + ImGui.End(); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/ItemTool/ChestKeyLooter.cs b/Plugins/RynthCore.Plugin.RynthAi/ItemTool/ChestKeyLooter.cs index f27ec88..a672e80 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/ItemTool/ChestKeyLooter.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/ItemTool/ChestKeyLooter.cs @@ -26,10 +26,29 @@ // on a later cycle means the timer has not run yet (nothing is spent): it waits ProbeEveryMs // (the wait, 5..30 s) and asks again, for at most MaxProbes * ProbeMs (4 min) of asking. So // a wait shorter than the chest's own timer costs one unspent key use per probe, never a key. +// * The re-lock seen (2026-11-28: the 5 s between chests was far too long; a +// DreamWeave Legendary Chest re-locked and refilled as it closed, and every cycle sat out the +// 5 s floor): the server says Locked=false when the key unlocks the chest (LockHelper.Unlock) +// and Locked=true when it resets (Chest.Reset, which a ChestRegenOnClose chest runs inside its +// close). A chest the client read unlocked after this cycle's key and now reads locked has +// reset, whatever the wait: the next key goes once the client shows it closed (CloseSettleMs). +// A Locked=true never seen after an unlocked read may be stale, so it still counts only past +// MinRelockMs, as before. The after-loot floor is the close seen + CloseSettleMs (AfterLootMaxMs +// where the client can't tell), and the wait itself goes down to 1 s. // // Out of keys: the key item is gone (used up: "Your key is used up."; no other carried item has // its name) after a cycle, or before one. A key with unlimited uses never runs out: MaxCycles -// ends the run. +// ends the run. Until 2026-11-28 MaxCycles (300) counted every chest, so a long run on keys that +// do run out stopped at 300 ("after 300 keys it stops"); it now counts chests in a row where no +// key use was seen spent ("Your key has N uses left" / "is used up", the key changing or going). +// ACE sends the unlock and the uses-left text as ONE two-line message, which the old parser read +// only to the first line, so OnChat now reads every line. +// +// Nothing taken (2026-11-28, "after a certain amount of time it stops picking up items, chest +// opens, but items don't get picked up"): the corpse looter's tally says, per chest, how many +// items the loot profile wanted and how many pickups landed. MaxStarvedChests chests in a row +// that had wanted loot and gave none end the run with the item and the reason in chat (too heavy, +// packs full, the server refusing), so no more keys go on loot that is left behind. // // Never spams the server: one request at a time, each waits for its UseDone (AnswerMaxMs), the // client must be free (HoldReason) and a failed step is retried a few times at most. @@ -72,8 +91,15 @@ internal interface IChestKeyEnv bool Looting(int chestId); /// Ends the loot session and closes the chest. void AbortLooting(int chestId); + /// + /// The last loot session on this chest: items the loot profile wanted (left at a keep count not + /// counted), pickups that landed, and the first wanted item's name. False = not known. + /// + bool LastLootTally(int chestId, out int wanted, out int taken, out string firstWanted); /// The client reads the chest as locked (true), unlocked (false) or doesn't know (null). bool? ChestLockedHint(int chestId); + /// The client shows the chest open (its ViewContents, until the server's close): true, false, or null = can't tell. + bool? ChestShownOpen(int chestId); void Say(string text); void Log(string text); } @@ -95,22 +121,28 @@ internal sealed class ChestKeyLooter /// After the chest's answer, it gets this long to read open before the open counts as failed. public const long OpenSettleMs = 1500; /// - /// "Chest re-lock wait (s)": the next cycle starts this long after the chest was opened. The - /// default covers ACE's default chest reset (120 s). The least, 5 s, still sends nothing faster - /// than one key use per 5 s: each waits for its answer, a too-early one answers "already - /// unlocked" and spends nothing, and the asking is bounded (MaxProbes * ProbeMs). Under 15 s - /// only a chest that resets as it closes (ChestRegenOnClose) can be ready; ACE floors every - /// timed reset at 15 s. + /// "Chest re-lock wait (s)": the next cycle starts this long after the chest was opened (sooner + /// when the client sees it re-lock). The default covers ACE's default chest reset (120 s). The + /// least, 1 s (5 s until 2026-11-28), is for a chest that resets as it closes + /// (ChestRegenOnClose): ACE floors every timed reset at 15 s. A too-early key use answers + /// "already unlocked" and spends nothing, and those asks stay MinProbeMs apart and bounded + /// (MaxProbes * ProbeMs). /// - public const int DefaultRelockWaitSec = 125, MinRelockWaitSec = 5, MaxRelockWaitSec = 600; + public const int DefaultRelockWaitSec = 125, MinRelockWaitSec = 1, MaxRelockWaitSec = 600; /// The default wait in ms (DefaultRelockWaitSec). public const long RegenWaitMs = DefaultRelockWaitSec * 1000L; - /// A chest the client reads as locked is tried again this soon after it was opened. + /// A chest the client reads as locked, never read unlocked this cycle (the value may be stale), is tried again this soon after it was opened. public const long MinRelockMs = 15_000; /// Asking a chest that was still unlocked again: at most this long apart (ProbeEveryMs follows a shorter wait). public const long ProbeMs = 30_000; - /// ... and at least this long apart. - public const long MinProbeMs = MinRelockWaitSec * 1000L; + /// ... and at least this long apart, however short the wait. + public const long MinProbeMs = 5_000; + /// After the loot, the next key goes no sooner than this after the client shows the chest closed (the server's close answered). + public const long CloseSettleMs = 300; + /// ... or this long after the loot ended, where the client can't tell (or still shows it open). + public const long AfterLootMaxMs = 2000; + /// The chest is opened this long after the key's answer (the unlock's Locked=false reaches the client first). + public const long UnlockSettleMs = 400; /// The asking lasts MaxProbes * ProbeMs (MaxProbes asks at the default wait). public const int MaxProbes = 8; @@ -123,7 +155,10 @@ internal sealed class ChestKeyLooter public const long LootStartMs = 8_000; /// The chest is out of the object cache this long: it is gone. public const long GoneMs = 5_000; + /// Chests in a row with no key use seen spent (a key that never runs out) before the run ends. public const int MaxCycles = 300; + /// Chests in a row whose wanted loot could not be picked up before the run ends. + public const int MaxStarvedChests = 3; public const int MaxTimeouts = 3, MaxBusy = 8, MaxOpenFails = 3, MaxSendFails = 5, MaxRefusals = 3, MaxOpenElsewhere = 3; private const long ThinkMs = 100, RetryMs = 1500, SendRetryMs = 1000, BusyBackoffMs = 2000; private const long NoUseDoneFallbackMs = 3000; @@ -147,6 +182,12 @@ internal sealed class ChestKeyLooter public int UsesLeft { get; private set; } = -1; /// What the run did last, for the status line when it is not running. public string LastResult { get; private set; } = ""; + /// + /// This run saw the chest re-lock (unlocked after the key, locked again once closed), so the + /// re-lock wait isn't what times it: the panel hides the wait's control and the status shows no + /// countdown (2026-11-28: the wait's timer bar showed although the looter no longer went by it). + /// + public bool RelockSeen { get; private set; } /// "Chest re-lock wait (s)" (the host sets it from the settings each tick; clamped). A change applies to a wait already running. public int RelockWaitSec @@ -169,6 +210,15 @@ internal sealed class ChestKeyLooter private bool _answerSeen, _sawUnlocked, _keyUsedUp, _lootSeen, _relockExpected, _regenWait; private int _timeouts, _busy, _openFails, _sendFails, _probes, _refusals, _openElsewhere, _cycles, _keyUsesThisCycle; private string _holdWhy = ""; + // A key use seen spent this cycle; chests in a row without one (MaxCycles). + private bool _spentThisCycle; + private int _unspentCycles; + // The client read the chest unlocked after this cycle's key (a later Locked=true is the re-lock). + private bool _hintSawUnlocked; + // When the client was first seen with the chest closed after the loot (0 = not yet). + private long _closedSeenAt; + // Chests in a row with wanted loot and nothing taken (MaxStarvedChests). + private int _starved; public void SetChest(int id, string name) { if (!Running) { ChestId = id; ChestName = name; } } public void SetKey(int id, string name) { if (!Running) { KeyId = id; KeyName = name; UsesLeft = -1; } } @@ -189,6 +239,8 @@ internal sealed class ChestKeyLooter Looted = 0; _cycles = 0; _probes = 0; _relockExpected = false; _goneSince = 0; _holdSince = 0; _timeouts = _busy = _openFails = _sendFails = _refusals = _openElsewhere = 0; + _unspentCycles = 0; _starved = 0; _spentThisCycle = false; _hintSawUnlocked = false; _closedSeenAt = 0; + RelockSeen = false; _lastThink = 0; _nextTryAt = 0; LastResult = ""; State = Phase.Ready; _env.Say($"[RynthAi] Chest looter: starting on {ChestName} with {KeyName}. It uses the key, opens the chest, loots it with the current loot profile and repeats until the key is used up. Stop: /ra itemtool chest stop."); @@ -225,13 +277,19 @@ internal sealed class ChestKeyLooter /// A chat line from the server (the key's answers). public void OnChat(string? text) { - if (!Running || string.IsNullOrEmpty(text) || text.Length > 160) return; + if (!Running || string.IsNullOrEmpty(text) || text.Length > 320) return; if (State is not (Phase.KeyOut or Phase.KeyPending)) return; - if (UnlockedText.IsMatch(text)) { _sawUnlocked = true; return; } - Match m = KeyUsedUpText.Match(text); - if (!m.Success) return; - if (m.Groups["n"].Success && int.TryParse(m.Groups["n"].Value, out int n)) UsesLeft = n; - else { _keyUsedUp = true; UsesLeft = 0; } + // ACE: "The X has been unlocked.\nYour key has N uses left." comes as one message. + foreach (string line in text.Split('\n')) + { + if (line.Length == 0 || line.Length > 160) continue; + if (UnlockedText.IsMatch(line)) { _sawUnlocked = true; continue; } + Match m = KeyUsedUpText.Match(line); + if (!m.Success) continue; + _spentThisCycle = true; + if (m.Groups["n"].Success && int.TryParse(m.Groups["n"].Value, out int n)) UsesLeft = n; + else { _keyUsedUp = true; UsesLeft = 0; } + } } /// One line for the panel. @@ -248,7 +306,9 @@ internal sealed class ChestKeyLooter { case Phase.Idle: return LastResult.Length > 0 ? $"Chest looter {LastResult}." : "Idle."; case Phase.Waiting: - return $"Waiting for {ChestName} to re-lock ({Math.Max(0, (_waitUntil - now + 999) / 1000)} s) - {key}, {tail}."; + return RelockSeen && _probes == 0 + ? $"Waiting for {ChestName} to re-lock (it re-locks as it closes) - {key}, {tail}." + : $"Waiting for {ChestName} to re-lock ({Math.Max(0, (_waitUntil - now + 999) / 1000)} s) - {key}, {tail}."; case Phase.Looting: return $"Looting {ChestName} - {key}, {tail}."; case Phase.KeyPending or Phase.KeyOut: return $"Using {KeyName} on {ChestName} - {tail}."; case Phase.OpenPending or Phase.OpenOut: return $"Opening {ChestName} - {key}, {tail}."; @@ -273,6 +333,12 @@ internal sealed class ChestKeyLooter } _goneSince = 0; + // From the open on, an unlocked read is this cycle's unlock (the server's Locked=false), so a + // locked read after it is the re-lock (TickWaiting). + if (State is Phase.OpenPending or Phase.OpenOut or Phase.Looting or Phase.Waiting + && _env.ChestLockedHint(ChestId) == false) + _hintSawUnlocked = true; + switch (State) { case Phase.Ready: TickReady(now, meters); break; @@ -289,7 +355,7 @@ internal sealed class ChestKeyLooter private void TickReady(long now, double meters) { - if (_cycles >= MaxCycles) { Finish($"reached {MaxCycles} cycles (a key with unlimited uses never runs out)"); return; } + if (_unspentCycles >= MaxCycles) { Finish($"{MaxCycles} chests in a row without a key use spent (a key with unlimited uses never runs out)"); return; } int key = _env.FindKey(KeyId, KeyName, 0); if (key == 0) { Finish($"out of keys - no '{KeyName}' left"); return; } if (key != KeyId) @@ -297,12 +363,15 @@ internal sealed class ChestKeyLooter _env.Log($"[RynthAi] Chest looter: key 0x{(uint)KeyId:X8} is gone; using 0x{(uint)key:X8} '{KeyName}'"); KeyId = key; UsesLeft = -1; + _unspentCycles = 0; // the last key was used up: keys are being spent } if (meters > MaxStartMeters) { Finish($"{ChestName} is {meters:0} m away (more than {MaxStartMeters:0} m)"); return; } _keyUsesThisCycle = 0; _openFails = 0; _sawUnlocked = false; _keyUsedUp = false; + _spentThisCycle = false; + _hintSawUnlocked = false; State = Phase.KeyPending; } @@ -402,7 +471,8 @@ internal sealed class ChestKeyLooter if (!_sawUnlocked) _env.Log("[RynthAi] Chest looter: the key use was answered with no 'has been unlocked' line; trying the chest anyway"); State = Phase.OpenPending; - _nextTryAt = now + 400; + // Counted from the answer (the chat settle is part of it), not from now. + _nextTryAt = Math.Max(now, _answeredAt + UnlockSettleMs); return; case ErrLockAlreadyUnlocked: @@ -411,7 +481,7 @@ internal sealed class ChestKeyLooter if (!_relockExpected) { State = Phase.OpenPending; - _nextTryAt = now + 400; + _nextTryAt = Math.Max(now, _answeredAt + UnlockSettleMs); return; } int limit = ProbeLimit; @@ -438,6 +508,7 @@ internal sealed class ChestKeyLooter case ErrCannotUseThatItem: // A key with no uses left: ACE deletes it. _keyUsedUp = true; + _spentThisCycle = true; _env.Log("[RynthAi] Chest looter: the server says the key can't be used (spent); looking for another"); State = Phase.KeyPending; _nextTryAt = now + SendRetryMs; @@ -525,20 +596,61 @@ internal sealed class ChestKeyLooter Looted++; _cycles++; _probes = 0; + _openElsewhere = 0; // "stays open" means that many in a row, not in the whole run _relockExpected = true; - _env.Say($"[RynthAi] Chest looter: looted {ChestName} ({Looted} so far)."); + if (_spentThisCycle || _keyUsedUp) _unspentCycles = 0; + else _unspentCycles++; + + // What the loot profile wanted from this chest, and what landed. + string tally = ""; + if (_env.LastLootTally(ChestId, out int wanted, out int taken, out string firstWanted)) + { + tally = wanted > 0 ? $" - took {taken} of {wanted} wanted" : " - nothing the profile wants"; + if (wanted > 0 && taken == 0) + { + _starved++; + _env.Log($"[RynthAi] Chest looter: {ChestName}: the profile wanted {wanted} item(s) (first '{firstWanted}') and none was picked up ({_starved} of {MaxStarvedChests} in a row)"); + if (_starved >= MaxStarvedChests) + { + _env.Say($"[RynthAi] Chest looter: looted {ChestName} ({Looted} so far){tally}."); + Finish($"{MaxStarvedChests} chests in a row had loot your profile wants (e.g. '{firstWanted}') and none of it could be picked up - too heavy, no pack room, or the server refused it (see the loot lines in chat); no more keys spent"); + return; + } + } + else _starved = 0; + } + _env.Say($"[RynthAi] Chest looter: looted {ChestName} ({Looted} so far){tally}."); int key = _env.FindKey(KeyId, KeyName, _keyUsedUp ? KeyId : 0); if (key == 0) { Finish($"out of keys after {Looted} chest(s)"); return; } - if (_cycles >= MaxCycles) { Finish($"reached {MaxCycles} cycles (a key with unlimited uses never runs out)"); return; } + if (key != KeyId) _unspentCycles = 0; // the key went: it was used up + if (_unspentCycles >= MaxCycles) { Finish($"{MaxCycles} chests in a row without a key use spent (a key with unlimited uses never runs out)"); return; } KeyId = key; _keyUsedUp = false; // that was the old key; the one chosen now has not been used _lootDoneAt = now; + _closedSeenAt = _env.ChestShownOpen(ChestId) == false ? now : 0; EnterWaiting(RegenWaitUntil()); _regenWait = true; } - /// The re-lock wait's end: RelockWaitSec after the open, and never sooner than 2 s after the loot ended. - private long RegenWaitUntil() => Math.Max(_lootDoneAt + 2000, _openedAt + RelockWaitMs); + /// + /// The re-lock wait's end: RelockWaitSec after the open, and never before the chest is closed: + /// CloseSettleMs after the client showed it closed, or AfterLootMaxMs after the loot ended when + /// that isn't seen (an engine that can't tell, or a close that isn't answered). + /// + private long RegenWaitUntil() + { + long closed = _closedSeenAt != 0 + ? Math.Min(_closedSeenAt + CloseSettleMs, _lootDoneAt + AfterLootMaxMs) + : _lootDoneAt + AfterLootMaxMs; + return Math.Max(closed, _openedAt + RelockWaitMs); + } + + /// The loot is over and the client shows the chest closed (or can't tell, AfterLootMaxMs on): a key may go on it. + private bool ClosedAfterLoot(long now) + { + if (_closedSeenAt != 0) return now >= _closedSeenAt + CloseSettleMs; + return now >= _lootDoneAt + AfterLootMaxMs; + } private void EnterWaiting(long until) { @@ -551,9 +663,23 @@ internal sealed class ChestKeyLooter { // The key may leave the pack meanwhile (traded, dropped): nothing to wait for then. if (_env.FindKey(KeyId, KeyName, _keyUsedUp ? KeyId : 0) == 0) { Finish($"out of keys - no '{KeyName}' left"); return; } - if (_regenWait) _waitUntil = RegenWaitUntil(); // the setting may have changed meanwhile + if (_closedSeenAt == 0 && _env.ChestShownOpen(ChestId) == false) _closedSeenAt = now; + if (_regenWait) _waitUntil = RegenWaitUntil(); // the setting (or the close) may have changed meanwhile if (now >= _waitUntil) { State = Phase.Ready; return; } - if (_probes == 0 && now >= _openedAt + MinRelockMs && _env.ChestLockedHint(ChestId) == true) + + bool? locked = _env.ChestLockedHint(ChestId); + if (locked != true) return; + // Read unlocked after this cycle's key, now locked: the server re-locked (reset) it. + if (_hintSawUnlocked && ClosedAfterLoot(now)) + { + if (!RelockSeen) _env.Say($"[RynthAi] Chest looter: {ChestName} re-locks as it closes; the next key goes on it as soon as it does (the re-lock wait isn't needed for it)."); + RelockSeen = true; + _env.Log($"[RynthAi] Chest looter: {ChestName} re-locked {Math.Max(0, now - _openedAt) / 1000.0:0.0} s after the open; next cycle"); + State = Phase.Ready; + return; + } + // A locked read never preceded by an unlocked one may be stale: only past ACE's timer floor. + if (_probes == 0 && now >= _openedAt + MinRelockMs) { _env.Log($"[RynthAi] Chest looter: {ChestName} reads locked again; next cycle"); State = Phase.Ready; diff --git a/Plugins/RynthCore.Plugin.RynthAi/ItemTool/QuickGive.cs b/Plugins/RynthCore.Plugin.RynthAi/ItemTool/QuickGive.cs index ad754e0..ad9e55c 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/ItemTool/QuickGive.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/ItemTool/QuickGive.cs @@ -19,6 +19,15 @@ // // 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-27). Amount: how many units a round gives (0 = all of them). A stack +// bigger than what is left of the round is split with AC's give amount, and the rest of it stays in +// the pack, as a stack the target took only part of does. Every: 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: +// between rounds, none of the item left, the target out of range or out of view, or a fight only +// holds the next round (the status says why); during a round they end that round, not the run. A +// changed target, MaxRefusals in a row or a client that won't send still end the run. Spotted by +// SilentKelpie (Forgejo rynth PR #12); re-implemented here. // ============================================================================ using System; @@ -44,8 +53,8 @@ internal interface IQuickGiveEnv /// The item left the pack, or its stack shrank below ; /// : the units still in that stack in the pack (0 when it is gone). bool Landed(int itemId, int count, out int left); - /// AC's give action for the whole object. False when the engine refused to send it. - bool Send(int itemId, int targetId); + /// AC's give action: units of the stack, 0 = the whole object. False when the engine refused to send it. + bool Send(int itemId, int targetId, int amount); /// A count of the server's refusals so far (rises when one arrives). int RefusalSeq(); void Say(string text); @@ -54,12 +63,14 @@ internal interface IQuickGiveEnv internal sealed class QuickGive { - public enum Phase { Idle, Pending, InFlight } + public enum Phase { Idle, Pending, InFlight, Waiting } /// The target must be this near to start; it ends the run if it gets farther than . 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; + /// The largest Amount (units a round) and Every (seconds between rounds). + public const int MaxAmount = 1_000_000, MaxEverySec = 86_400; private const long ThinkMs = 50; private readonly IQuickGiveEnv _env; @@ -77,10 +88,23 @@ internal sealed class QuickGive public int Given { get; private set; } public int Units { get; private set; } public string LastResult { get; private set; } = ""; + /// Units a round gives; 0 = every one carried. A running round takes a new value at its next give. + public int Amount { get; private set; } + /// Seconds from the end of one round to the start of the next; 0 = one round. A running give takes a new value at its next round. + public int EverySec { get; private set; } + /// Rounds started this run, and the units given in the current (or last) one. + public int Rounds { get; private set; } + public int RoundUnits { get; private set; } + /// Between rounds: milliseconds until the next is due (0 otherwise). + public long NextRoundInMs => State == Phase.Waiting ? Math.Max(0, _roundAt - _env.Now) : 0; - private long _lastThink, _nextAt, _sentAt, _goneSince, _holdSince, _leftAt; - private int _inFlightId, _inFlightCount, _refusalSeqAtSend, _refusals, _sendFails, _left; - private string _holdWhy = ""; + 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, _roundAt; + private int _inFlightId, _inFlightCount, _refusalSeqAtSend, _refusals, _sendFails, _left, _roundGives; + private string _holdWhy = "", _waitWhy = ""; public void SetItem(int id, GiveItemKey key) { if (!Running) { ItemId = id; Item = key; } } public void SetTarget(int id, string name) { if (!Running) { TargetId = id; TargetName = name; } } @@ -97,17 +121,43 @@ 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(); + Given = 0; Units = 0; Rounds = 0; _sendFails = 0; _goneSince = 0; _nextAt = 0; _lastThink = 0; _left = have; _leftAt = _env.Now; 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; + } + + /// The round is over: with Every set the next is due EverySec later; without, the run ends. + private void EndRound(string why) + { + if (!Repeats) { Finish(why); return; } + _inFlightId = 0; + _roundAt = _env.Now + EverySec * 1000L; + _waitWhy = ""; + State = Phase.Waiting; + _env.Say($"[RynthAi] Quick give: round {Rounds} - {why} ({RoundUnits} unit(s)). Next round in {EverySec} s."); + _env.Log($"[RynthAi] Quick give: round {Rounds} over - {why}; {RoundUnits} unit(s); next in {EverySec} s"); + } + private bool Refuse(string why) { _env.Say($"[RynthAi] Quick give: can't start - {why}."); @@ -124,9 +174,10 @@ internal sealed class QuickGive { State = Phase.Idle; _inFlightId = 0; - LastResult = $"stopped: {why} ({Given} item(s), {Units} unit(s) given to {TargetName})"; + string rounds = Rounds > 1 ? $" in {Rounds} rounds" : ""; + LastResult = $"stopped: {why} ({Given} item(s), {Units} unit(s) given to {TargetName}{rounds})"; _env.Say($"[RynthAi] Quick give {LastResult}."); - _env.Log($"[RynthAi] Quick give: finish - {why}; gave {Given} ({Units} units)"); + _env.Log($"[RynthAi] Quick give: finish - {why}; gave {Given} ({Units} units) in {Rounds} round(s)"); } public string Status @@ -136,9 +187,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}"; } } } @@ -150,24 +205,46 @@ 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); } + /// Between rounds: the next starts when it is due, the target is back in range and out of a fight, and some of the item is carried. + 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; + } + _goneSince = 0; + StartRound(); + _env.Log($"[RynthAi] Quick give: round {Rounds} starts ({_left} carried)"); + } + private void TickPending(long now) { if (now < _nextAt) return; @@ -176,20 +253,23 @@ 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 amount = Amount > 0 && count > Amount - RoundUnits ? Amount - RoundUnits : 0; _refusalSeqAtSend = _env.RefusalSeq(); - if (!_env.Send(id, TargetId)) + if (!_env.Send(id, TargetId, amount)) { if (++_sendFails >= MaxSendFails) Finish("the client wouldn't send the give"); else _nextAt = now + RefuseBackoffMs; @@ -207,13 +287,20 @@ internal sealed class QuickGive if (_env.Landed(_inFlightId, _inFlightCount, out int left)) { Given++; - Units += left > 0 ? _inFlightCount - left : _inFlightCount; + _roundGives++; + int units = left > 0 ? _inFlightCount - left : _inFlightCount; + Units += units; + RoundUnits += units; // An NPC that takes one per give (R-20261125-205340-1218, DreamWeave: a Collector took one // Kirit Zefir Wing from each stack): the rest stays in the pack and is given again. Skipping - // it ended the run after one give per stack ("gave 6", with 446 wings left). - if (left <= 0) _skip.Add(_inFlightId); // it is the target's now, whatever a stale inventory read still says + // it ended the run after one give per stack ("gave 6", with 446 wings left). A stack split + // for Amount is the same: the rest is the next give's (or the next round's). + if (left <= 0) + { + _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; diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs index 40fb6d9..6a82995 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs @@ -890,7 +890,7 @@ internal sealed class LegacyAdvancedSettingsUi ImGui.Checkbox("Auto-Unlock Doors", ref _settings.AutoUnlockDoors); if (ImGui.IsItemHovered()) - ImGui.SetTooltip("If a door is locked, try to use a lockpick from your Consumable Items list."); + ImGui.SetTooltip("If a door is locked, try the keys you carry first (up to 4, one at a time), then a lockpick from your Consumable Items list."); } ImGui.Spacing(); @@ -1050,6 +1050,13 @@ 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( + "In a fellowship, a buff with a fellowship version casts that version instead\n" + + "(the Conclave attributes, the Clutch defenses, the Chants masteries, the Wards,\n" + + "the Winds, the Endless Well), so every member gets it. Never a lower level than\n" + + "the self buff it replaces. Solo it never applies. Off by default."); ImGui.Spacing(); if (ImGui.Button("Force Buff##forceBuff") && _forceBuff != null) _forceBuff(); diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.ProfileFiles.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.ProfileFiles.cs index b28604a..90e2437 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.ProfileFiles.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.ProfileFiles.cs @@ -10,7 +10,7 @@ namespace RynthCore.Plugin.RynthAi.LegacyUi; internal enum ProfileKind { Nav = 0, Loot = 1, Meta = 2, Settings = 3, Buffs = 4 } /// What a profile button or its /ra verb does. -internal enum ProfileVerb { Save, SaveAs, New, Rename, Delete, Folder, Edit } +internal enum ProfileVerb { Save, SaveAs, New, Rename, Delete, Folder, Edit, ClearMonsters } /// /// The result of a profile button or verb: the chat line ("[RynthAi] ..."), whether it worked, and @@ -22,8 +22,11 @@ internal readonly record struct ProfileResult(bool Ok, string Text, bool NeedsRe public static ProfileResult Failed(string text) => new(false, "[RynthAi] " + text); } -/// What the profile row shows: the name in use, its file, unsaved changes, the folder. -internal sealed record ProfileFileInfo(string Name, string Path, bool HasFile, bool Unsaved, string Folder); +/// +/// What the profile row shows: the name in use, its file, unsaved changes, the folder; for the +/// settings profile, its Monsters rules other than Default (-1 for the other kinds). +/// +internal sealed record ProfileFileInfo(string Name, string Path, bool HasFile, bool Unsaved, string Folder, int MonsterRules = -1); // The Loaded files drawer's profile buttons (2026-11-11): Save, Save As, New, Rename, Move to // Deleted and Open folder for the settings profile, the nav, the meta and the loot profile, and @@ -102,10 +105,13 @@ internal sealed partial class LegacyDashboardRenderer bool hasFile = path.Length > 0; // no disk look: the menu reads this every frame (a missing file is said by the button) string name = path.Length > 0 ? Path.GetFileNameWithoutExtension(path) : "None"; bool unsaved = false; + int monsterRules = -1; switch (k) { case ProfileKind.Settings: name = _settings.SelectedProfile ?? DefaultProfileName; + // The count only (any thread: the list isn't walked); EnsureDefaultRule keeps one Default row. + monsterRules = Math.Max(0, (_settings.MonsterRules?.Count ?? 1) - 1); break; case ProfileKind.Nav: { @@ -128,7 +134,7 @@ internal sealed partial class LegacyDashboardRenderer if (path.Length == 0) name = BuiltInBuffProfileLabel; break; } - return new ProfileFileInfo(name, path, hasFile, unsaved, ProfileFolder(k)); + return new ProfileFileInfo(name, path, hasFile, unsaved, ProfileFolder(k), monsterRules); } // ── Save ───────────────────────────────────────────────────────────── @@ -219,10 +225,16 @@ internal sealed partial class LegacyDashboardRenderer { case ProfileKind.Settings: { + // Says what the copy carries over: the Monsters rules come with it (2026-11-27, + // R-20261127-124531-b5d3: a T11 profile made this way fought with the T10 rules). + string from = _settings.SelectedProfile ?? DefaultProfileName; + bool replacing = File.Exists(target) && !ProfileFileOps.SamePath(target, current); string r = SaveAsProfile(name); - return r.StartsWith("Saved profile", StringComparison.Ordinal) - ? ProfileResult.Done($"Saved these settings as profile '{name}'; it is the profile in use now.") - : ProfileResult.Failed(r); + if (!r.StartsWith("Saved profile", StringComparison.Ordinal)) return ProfileResult.Failed(r); + string copy = $"a copy of '{from}' ({MonsterRuleCount(NamedMonsterRules(_settings.MonsterRules))})"; + return ProfileResult.Done(replacing + ? $"Profile '{name}' replaced with {copy}." + : $"New profile '{name}': {copy}."); } case ProfileKind.Nav: { @@ -259,8 +271,9 @@ internal sealed partial class LegacyDashboardRenderer // ── New ────────────────────────────────────────────────────────────── /// - /// The New button and /ra nav|meta new <name>: a blank nav (Circular, no points) or meta (one - /// state "Default", no rules), loaded. Never over an existing one (that is picked in the list). + /// The New button and /ra nav|meta|settings new <name>: a blank nav (Circular, no points) or meta + /// (one state "Default", no rules), loaded; a fresh settings profile (). + /// Never over an existing one (that is picked in the list). /// Loot profiles: , opened in the Loot Editor by the plugin. /// internal ProfileResult NewProfile(ProfileKind k, string? raw) @@ -282,7 +295,7 @@ internal sealed partial class LegacyDashboardRenderer return new ProfileResult(msg.Contains("Created new meta", StringComparison.Ordinal), msg); } case ProfileKind.Settings: - return ProfileResult.Failed("Save As makes a new settings profile (a copy of these settings)."); + return NewFreshSettingsProfile(raw); case ProfileKind.Buffs: return ProfileResult.Failed("New buff profiles are made in the Spells window (its New button)."); default: @@ -306,6 +319,130 @@ internal sealed partial class LegacyDashboardRenderer return null; } + // ── A new settings profile: a copy, or fresh ───────────────────────── + // + // 2026-11-27 (R-20261127-124531-b5d3): a new settings profile was always a copy of the one in + // use, and since 2026-11-18 the Monsters rules belong to the profile, so a T11 profile made from + // the T10 one had every T10 monster rule in it. The PROFILE menu now asks what a new profile + // starts from: a copy of the one in use (Save As, as before), or fresh (New): the Monsters list + // down to its Default row, no weapons or consumables (they fill from the pack, as a character's + // first profile does), every other setting as it is. The buffs aren't touched: the buff profile + // is a shared file the settings only name, not a list the profile owns. + + /// The Monsters rules other than the catch-all Default row. + internal static int NamedMonsterRules(List? rules) + { + int n = 0; + if (rules != null) + foreach (MonsterRule r in rules) + if (!r.Name.Equals("Default", StringComparison.OrdinalIgnoreCase)) n++; + return n; + } + + private static string MonsterRuleCount(int n) => n == 1 ? "1 monster rule" : $"{n} monster rules"; + + /// + /// A new list holding only ' Default row, as it is (a new one, as + /// makes it, when there is none). A new list, + /// not the old one emptied, so combat or a panel reading the old one is never cut short. + /// + internal static List DefaultRuleOnly(List? rules) + { + MonsterRule? keep = null; + if (rules != null) + foreach (MonsterRule r in rules) + if (r.Name.Equals("Default", StringComparison.OrdinalIgnoreCase)) { keep = r; break; } + return new List { keep ?? new MonsterRule { Name = "Default", Priority = 1, DamageType = "Auto", WeaponId = 0 } }; + } + + /// + /// What a fresh profile leaves out, on (nothing is saved): the Monsters + /// rules but Default, the weapons and other items, the consumables, and the old per-profile buff + /// list (BuffRules, which nothing reads any more). Weapons and consumables are filled from the + /// pack afterwards (ProfileItemsChecked off, see TickPackSetup). + /// + internal static void ResetForFreshProfile(LegacyUiSettings s) + { + s.MonsterRules = DefaultRuleOnly(s.MonsterRules); + s.ItemRules = new List(); + s.ConsumableRules = new List(); + s.BuffRules = new List(); + s.ProfileItemsChecked = false; + } + + /// + /// The PROFILE menu's New (Start from: Fresh) and /ra settings new <name>: a new settings + /// profile with the settings in use but none of their monsters or items (), + /// which is then the one in use; its weapons fill from the pack once the inventory has loaded. + /// The profile left keeps everything: its last changes are saved first. Never over an existing one. + /// + internal ProfileResult NewFreshSettingsProfile(string? raw) + { + string? why = ProfileFileOps.CleanName(raw, SettingsExtensions, out string name); + if (why != null) return ProfileResult.Failed($"Can't use '{name}' as a settings profile name: {why}."); + if (IsReservedSettingsName(name)) + return ProfileResult.Failed($"Can't use '{name}' as a settings profile name: RynthAi keeps its own {name}.json there."); + if (string.IsNullOrEmpty(_charFolder) || string.IsNullOrEmpty(_settingsFilePath)) + return ProfileResult.Failed("Not logged in: settings profiles are per character."); + if (File.Exists(GetProfileFilePath(name))) + return ProfileResult.Failed($"Settings profile '{name}' already exists. Pick it under PROFILE, or use another name."); + + CheckAndSave(); // the profile left keeps its last changes (and nothing of the reset below) + var monsters = _settings.MonsterRules; + var items = _settings.ItemRules; + var consumables = _settings.ConsumableRules; + var buffs = _settings.BuffRules; + bool itemsChecked = _settings.ProfileItemsChecked; + ResetForFreshProfile(_settings); + + string r = SaveAsProfile(name); + if (!r.StartsWith("Saved profile", StringComparison.Ordinal)) + { + // Not written: the profile in use gets its lists back (autosave would save the reset into it). + _settings.MonsterRules = monsters; + _settings.ItemRules = items; + _settings.ConsumableRules = consumables; + _settings.BuffRules = buffs; + _settings.ProfileItemsChecked = itemsChecked; + return ProfileResult.Failed(r); + } + + SaveMonstersFile(); // the Monsters file (and the Monster Editor) hold the new profile's Default row + _packSetup = PackSetup.FillNew; + _packSetupStart = 0; + _packLastCount = -1; + _packNextPoll = 0; + return ProfileResult.Done($"New profile '{name}': fresh (no monsters or items; weapons fill from your pack)."); + } + + // ── The Monsters list's Clear list ─────────────────────────────────── + + /// + /// The Monsters list's Clear list (the PROFILE menu's Clear list, after its yes, and the plugin + /// export for the engine's Damage panel): every rule but the + /// Default row removed from the profile in use, saved to the profile and the Monsters file + /// (2026-11-27, R-20261127-124531-b5d3: a list copied into a new profile was cleared one rule at a time). + /// + internal ProfileResult ClearMonsterRules() + { + if (string.IsNullOrEmpty(_settingsFilePath)) return ProfileResult.Failed("Not logged in: no Monsters list to clear."); + int removed = NamedMonsterRules(_settings.MonsterRules); + _settings.MonsterRules = DefaultRuleOnly(_settings.MonsterRules); + SaveSettings(); + SaveMonstersFile(); + string profile = _settings.SelectedProfile ?? DefaultProfileName; + return ProfileResult.Done(removed == 0 + ? $"The Monsters list of profile '{profile}' has only its Default row; nothing to clear." + : $"Cleared the Monsters list of profile '{profile}': removed {MonsterRuleCount(removed)}; the Default row stays."); + } + + /// , said in chat (the plugin export the engine's button calls). + public void ClearMonsterRulesAndSay() + { + ProfileResult r = ClearMonsterRules(); + _host.WriteToChat(r.Text, r.Ok ? 1 : 2); + } + // ── Rename ─────────────────────────────────────────────────────────── /// The Rename button and /ra <kind> rename <name>: the file in use gets the new name and stays in use. diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs index af59722..3ce5a1a 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs @@ -1359,6 +1359,7 @@ internal sealed partial class LegacyDashboardRenderer DeathRecallSpellId = s.DeathRecallSpellId, DeathRecallItem = s.DeathRecallItem, StopMacroOnNoComponents = s.StopMacroOnNoComponents, + ShowNoComponentsWarning = s.ShowNoComponentsWarning, LowCompsRecall = s.LowCompsRecall, LowCompsTaperMin = s.LowCompsTaperMin, LowCompsScarabMin = s.LowCompsScarabMin, @@ -1484,6 +1485,7 @@ internal sealed partial class LegacyDashboardRenderer RebuffIdleMarginMinutes = s.RebuffIdleMarginMinutes, CastBuffsOverItemBuffs = s.CastBuffsOverItemBuffs, SkipUnusableBuffs = s.SkipUnusableBuffs, + UseFellowshipBuffs = s.UseFellowshipBuffs, DisabledBuffs = new List(s.DisabledBuffs), BlockedBuffItems = new List(s.BlockedBuffItems), CustomBuffItems = s.CustomBuffItems.ConvertAll(c => c.Copy()), @@ -1653,6 +1655,7 @@ internal sealed partial class LegacyDashboardRenderer if (p.DeathRecallSpellId is int recallSpell && recallSpell > 0) s.DeathRecallSpellId = recallSpell; if (p.DeathRecallItem is string recallItem) s.DeathRecallItem = recallItem.Trim(); s.StopMacroOnNoComponents = p.StopMacroOnNoComponents; + if (p.ShowNoComponentsWarning is bool noCompsWarn) s.ShowNoComponentsWarning = noCompsWarn; // absent = unchanged if (p.LowCompsRecall is bool lowComps) s.LowCompsRecall = lowComps; if (p.LowCompsTaperMin is int taperMin) s.LowCompsTaperMin = Math.Clamp(taperMin, 0, 1000); if (p.LowCompsScarabMin is int scarabMin) s.LowCompsScarabMin = Math.Clamp(scarabMin, 0, 100); @@ -1783,6 +1786,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(disabledBuffs); // absent = unchanged if (p.BlockedBuffItems is { } blockedItems) s.BlockedBuffItems = new List(blockedItems); // absent = unchanged if (p.CustomBuffItems is { } customItems) s.CustomBuffItems = customItems.FindAll(c => c != null); // absent = unchanged @@ -2257,6 +2261,7 @@ internal sealed partial class LegacyDashboardRenderer dst.DeathRecallSpellId = tmp.DeathRecallSpellId > 0 ? tmp.DeathRecallSpellId : 48; dst.DeathRecallItem = tmp.DeathRecallItem ?? string.Empty; dst.StopMacroOnNoComponents = tmp.StopMacroOnNoComponents; + dst.ShowNoComponentsWarning = tmp.ShowNoComponentsWarning; dst.LowCompsRecall = tmp.LowCompsRecall; dst.LowCompsTaperMin = Math.Clamp(tmp.LowCompsTaperMin, 0, 1000); dst.LowCompsScarabMin = Math.Clamp(tmp.LowCompsScarabMin, 0, 100); @@ -2328,6 +2333,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)); diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs index c77a32a..7fe3667 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs @@ -262,9 +262,9 @@ public sealed class LegacyUiSettings public bool LootNearbyChests = false; /// /// Item Tool > Chest re-lock wait (s) (2026-11-05): the chest looter's next key goes on the chest - /// this long after it was opened (sooner when the client reads it locked again). 125 s covers ACE's - /// default chest reset (120 s); a chest with a shorter timer can use less. 5..600 - /// (ItemTool.ChestKeyLooter.ClampRelockWaitSec). + /// this long after it was opened (sooner when the client sees it re-lock). 125 s covers ACE's + /// default chest reset (120 s); a chest with a shorter timer can use less, and one that resets as + /// it closes 1 s. 1..600 (5..600 until 2026-11-28; ItemTool.ChestKeyLooter.ClampRelockWaitSec). /// public int ChestRelockWaitSec = ItemTool.ChestKeyLooter.DefaultRelockWaitSec; public int LootJumpHeight = 10; // kept for old profiles and metas; jump-loot uses the keyboard tap jump (fixed height) @@ -370,6 +370,9 @@ public sealed class LegacyUiSettings public int DeathRecallSpellId = 48; // Primary Portal Recall public string DeathRecallItem = string.Empty; public bool StopMacroOnNoComponents = false; + // Settings > General > Show No Components Warning (Huds/CastWarningHud): the "Out of components" + // window when the server refuses one of RynthAi's spells for components. On by default. + public bool ShowNoComponentsWarning = true; // Recall When Low On Components (RynthAiPlugin.LowComponents.cs): tapers at or under LowCompsTaperMin, // or a scarab kind (not Diamond) at or under LowCompsScarabMin, stops the macro and recalls home. public bool LowCompsRecall = false; @@ -614,6 +617,13 @@ public sealed class LegacyUiSettings /// public bool SkipUnusableBuffs = true; /// + /// Buffing > Use fellowship buffs in a fellowship (off by default): in a fellowship, a buff with a + /// fellowship version (the Conclave attributes, the Clutch defenses, the Chants masteries, the Wards + /// protections, the Winds, the Endless Well) casts that version instead, at the same level rules and + /// never lower than the self buff it replaces (BuffManager.FellowshipVersion). Solo it never applies. + /// + public bool UseFellowshipBuffs; + /// /// 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 @@ -1509,6 +1519,7 @@ public sealed class SettingsBridgePayload public int StaminaToHealthMinStamina { get; set; } = 20; public bool StopMacroOnDeath { get; set; } public bool StopMacroOnNoComponents { get; set; } + public bool? ShowNoComponentsWarning { get; set; } // Show No Components Warning (2026-11-27); absent = unchanged // Absent from an older engine: null keeps the plugin's values. public bool? LowCompsRecall { get; set; } public int? LowCompsTaperMin { get; set; } @@ -1656,6 +1667,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; } // Use fellowship buffs in a fellowship (2026-11-27); absent = unchanged // Null (absent) likewise leaves the unticked prots/banes alone; an empty list ticks them all. public List? DisabledBuffs { get; set; } // The Buff Items lists (RynthAi's Spells window draws them; the engine's face has no rows for diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/InventoryManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/InventoryManager.cs index b2e4aad..2e77627 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Loot/InventoryManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/InventoryManager.cs @@ -335,6 +335,97 @@ public sealed class InventoryManager // tip a near-full sub-pack). It reuses AutoCram's single per-tick `inv` snapshot via // the snapshot overload (no extra BFS / no double-refresh). + // ── Room for loot (2026-11-28) ──────────────────────────────────────── + // The client takes a corpse or chest item only into the main pack (8c14ea53, "You must first pick + // up the Silver Pea"), so with the main pack full the looter left every item that joins no stack, + // side packs empty or not. With RynthSort's auto-sort on (Auto Cram off) nothing ever emptied the + // main pack, and Auto Cram never runs while a corpse is open, so a big corpse lost what didn't fit. + // Now a pickup that finds the main pack full and a side pack with room first moves one loose item + // from the main pack into that side pack (a pack-to-pack move, which the client sends); the pickup + // then takes the freed slot. Loot the looter brought in goes first, newest first; then other loose + // items, newest first, with kits, stones and food last. Never a worn or wielded item, a pack, a + // focus, a weapon or wand, a UST, a Weapons-tab item, or one whose move failed lately. + + private int _roomMoveId; + + /// + /// Moves one loose item out of the main pack into the side pack with the most room, so a loot + /// pickup fits there. : the items the looter brought in, newest + /// first; they go first. False when no side pack has a free slot or nothing may move. The move is + /// noted like a cram move: holds the pickup until its answer. + /// + public bool MakeLootRoom(IEnumerable lootedNewestFirst, out string what) + { + what = ""; + if (!_host.HasMoveItemInternal) return false; + uint player = _host.GetPlayerId(); + if (player == 0) return false; + int pid = unchecked((int)player); + var inv = _cache.GetDirectInventory(forceRefresh: true).ToList(); + + // The last room move: still in the main pack after its answer, so it did not go. + if (_roomMoveId != 0) + { + var last = inv.FirstOrDefault(o => o.Id == _roomMoveId); + if (last != null && last.Container == pid) + { + RegisterFailure(_cramBackoff, _roomMoveId); + _host.Log($"[RynthAi] Loot room: '{last.Name}' 0x{_roomMoveId:X8} is still in the main pack after its move; trying another item."); + } + else + _cramBackoff.Remove(_roomMoveId); + _roomMoveId = 0; + } + + int pack = WorldObjectCache.FindPackFor(inv, pid, includeMainPack: false, requireFree: 1, _host); + if (pack == 0) return false; + + WorldObject? pick = null; + var byId = new Dictionary(); + foreach (var o in inv) byId[o.Id] = o; + foreach (int id in lootedNewestFirst) + if (byId.TryGetValue(id, out var wo) && MayMoveForRoom(wo, pid, looted: true)) { pick = wo; break; } + pick ??= inv.Where(o => MayMoveForRoom(o, pid, looted: false)) + .OrderBy(o => IsHandyKind(o) ? 1 : 0) + .ThenByDescending(o => unchecked((uint)o.Id)) + .FirstOrDefault(); + if (pick == null) return false; + + int amount = Math.Max(1, pick.Values(LongValueKey.StackCount, 1)); + if (!_host.MoveItemInternal(unchecked((uint)pick.Id), unchecked((uint)pack), slot: 0, amount: amount)) + { + RegisterFailure(_cramBackoff, pick.Id); + _host.Log($"[RynthAi] Loot room: the move of '{pick.Name}' 0x{pick.Id:X8} to pack 0x{(uint)pack:X8} was turned down; backing off that item."); + return false; + } + _roomMoveId = pick.Id; + NoteMoveSent(unchecked((uint)pick.Id), pid, amount, merge: false, $"'{pick.Name}'"); + what = $"'{pick.Name}' 0x{pick.Id:X8} to pack 0x{(uint)pack:X8}"; + return true; + } + + /// A loose main-pack item a loot room move may take (: one the looter brought in). + private bool MayMoveForRoom(WorldObject wo, int playerId, bool looted) + { + if (wo.Container != playerId) return false; + if (wo.Values(LongValueKey.EquippedSlots, 0) != 0) return false; + if (WorldObjectCache.IsWieldedByPlayer(_host, wo)) return false; + if (wo.ObjectClass is AcObjectClass.Container or AcObjectClass.Foci or AcObjectClass.Ust) return false; + if (!string.IsNullOrEmpty(wo.Name) && wo.Name.IndexOf("Foci", StringComparison.OrdinalIgnoreCase) >= 0) return false; + if (wo.Values(LongValueKey.ItemsCapacity, 0) > 0 || wo.Values(LongValueKey.ContainersCapacity, 0) > 0) return false; + if (_cramPending.ContainsKey(wo.Id)) return false; + if (_cramBackoff.TryGetValue(wo.Id, out var b) && RynthClock.Now < b.NextRetry) return false; + if (_settings.ItemRules.Any(r => r.Id == wo.Id)) return false; // the Weapons tab keeps these at hand + // The character's own weapons and wands stay where the swaps find them; looted ones are loot. + if (!looted && wo.ObjectClass is AcObjectClass.MeleeWeapon or AcObjectClass.MissileWeapon or AcObjectClass.WandStaffOrb) + return false; + return true; + } + + /// Things a player reaches for (RynthSort's default handy kinds): moved for room only when nothing else may go. + private static bool IsHandyKind(WorldObject wo) => + wo.ObjectClass is AcObjectClass.HealingKit or AcObjectClass.ManaStone or AcObjectClass.Food; + // ── AutoStack ───────────────────────────────────────────────────────── private bool ProcessAutoStack(List inv, int playerId) diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/VTankLootEvaluator.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/VTankLootEvaluator.cs index 1241247..70a2c1a 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Loot/VTankLootEvaluator.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/VTankLootEvaluator.cs @@ -95,6 +95,13 @@ public sealed class VTankLootContext private readonly Dictionary _paletteCache = new(); + /// + /// The engine can read an object's palettes (captured from its CreateObject). When it can, an + /// item with none is one the engine has none for (released or deleted by the client, or created + /// before this engine loaded): a palette condition fails for it (MatchSlotExactPalette). + /// + public bool PalettesReadable => Host.HasGetObjectPalettes; + public (uint[] SubIds, uint[] Offsets) GetItemPalettes(uint itemId) { if (_paletteCache.TryGetValue(itemId, out var cached)) return cached; @@ -437,7 +444,7 @@ public static class VTankLootEvaluator if (ctx is null) return "no palettes"; var (subIds, _) = ctx.GetItemPalettes(itemId); int slot = ReadInt(d, 0); - return subIds.Length == 0 ? "no palette data" : slot >= 0 && slot < subIds.Length ? (subIds[slot] & 0x00FFFFFFu).ToString(CultureInfo.InvariantCulture) : "no slot " + slot; + return subIds.Length == 0 ? (ctx.PalettesReadable ? "no palette data (released by the client): no match" : "no palette data (this engine can't read palettes): passes") : slot >= 0 && slot < subIds.Length ? (subIds[slot] & 0x00FFFFFFu).ToString(CultureInfo.InvariantCulture) : "no slot " + slot; } case VTankNodeTypes.DisabledRule: return d.Count > 0 && string.Equals(d[0].Trim(), "true", StringComparison.OrdinalIgnoreCase) ? "rule disabled" : "enabled"; @@ -455,8 +462,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 +472,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 @@ -556,7 +563,13 @@ public static class VTankLootEvaluator uint targetPaletteId = (uint)ReadInt(d, 1); if (ctx is null) return true; var (subIds, _) = ctx.GetItemPalettes(itemId); - if (subIds.Length == 0) return true; + // No palette data: a match only where the engine can't read palettes at all (as before). + // Where it can, "none" means the engine dropped them (the client released or deleted the + // object): 2026-11-28, a DreamWeave Legendary Chest's leftover 'Helmet', 'Platemail Gauntlets' + // and 'Olthoi Sollerets' were each left for many opens on their real palettes, then matched + // "PP Olthoi Helm" / "Galvanic ... Exact" the moment their palettes were gone, and the pickup + // went out for an object that was leaving. + if (subIds.Length == 0) return !ctx.PalettesReadable; if (slot < 0 || slot >= subIds.Length) return false; uint actual = subIds[slot]; return (actual & 0x00FFFFFFu) == (targetPaletteId & 0x00FFFFFFu); @@ -685,7 +698,7 @@ public static class VTankLootEvaluator { if (item.Values(MaterialTypeKey, 0) == 0) return 0; int left = Math.Max(0, 10 - item.Values(NumTimesTinkeredKey, 0)); - if (item.Values(ImbuedEffectKey, 0) == 0) left = Math.Max(0, left - 1); + if (LongOf(item, ImbuedEffectKey) == 0) left = Math.Max(0, left - 1); return left; } @@ -762,6 +775,21 @@ public static class VTankLootEvaluator // (value, key) pair for the LongValKey* family. private static (int Val, int Key) Long(IList d) => (ReadInt(d, 0), ReadInt(d, 1)); + + /// ImbuedEffect (179) and ImbuedEffect2..5 (303-306): ACE keeps an item's second and later imbues apart. + internal static readonly int[] ImbueKeys = { ImbuedEffectKey, 303, 304, 305, 306 }; + + /// + /// A long key's value for a LongValKey test. ImbuedEffect is every imbue the item has, 179 ORed with + /// 303-306 as ACE's GetImbuedEffects reads it, so "has Fire Rending" sees a rend in the second slot. + /// + internal static int LongOf(WorldObject item, int key) + { + if (key != ImbuedEffectKey) 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 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 d) => (ReadDouble(d, 0), ReadInt(d, 1)); diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs index a091c6f..2d5dc94 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs @@ -3709,6 +3709,7 @@ internal sealed partial class ExpressionEngine ["DeathRecallSpellId"] = (() => I(s.DeathRecallSpellId), v => { if (int.TryParse(v, out int i) && i > 0) s.DeathRecallSpellId = i; }), ["DeathRecallItem"] = (() => s.DeathRecallItem, v => s.DeathRecallItem = v?.Trim() ?? string.Empty), ["StopMacroOnNoComponents"] = (() => B(s.StopMacroOnNoComponents), v => s.StopMacroOnNoComponents = ToDouble(v) != 0), + ["ShowNoComponentsWarning"] = (() => B(s.ShowNoComponentsWarning), v => s.ShowNoComponentsWarning = ToDouble(v) != 0), ["StopLootingWhenPackFull"] = (() => B(s.StopLootingWhenPackFull), v => s.StopLootingWhenPackFull = ToDouble(v) != 0), ["LootOwnCorpse"] = (() => B(s.LootOwnCorpse), v => s.LootOwnCorpse = ToDouble(v) != 0), ["EscapeHazards"] = (() => B(s.EscapeHazards), v => s.EscapeHazards = ToDouble(v) != 0), @@ -3795,6 +3796,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), diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/MyQuestsParser.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/MyQuestsParser.cs index 2bcd9b3..ab5a28b 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Meta/MyQuestsParser.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/MyQuestsParser.cs @@ -46,8 +46,9 @@ internal static class MyQuestsParser { // The name is lowercase and has no spaces in practice; allow anything up to " - N solves (". // The message is greedy up to the last '" ' so a quote inside it can't cut it short. + // Some servers put a space between the timestamp and the message: (1759276800) "Monthly stipend". private static readonly Regex QuestLine = new( - "^(?\\S.*?) - (?-?\\d+) solves \\((?\\d+)\\)\"(?.*)\" (?-?\\d+) (?\\d+)$", + "^(?\\S.*?) - (?-?\\d+) solves \\((?\\d+)\\)\\s*\"(?.*)\" (?-?\\d+) (?\\d+)$", RegexOptions.CultureInvariant); public const string EmptyText = "Quest list is empty."; diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/QuestTracker.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/QuestTracker.cs index 7c46896..c0d0d0b 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Meta/QuestTracker.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/QuestTracker.cs @@ -45,8 +45,10 @@ 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 + // Some servers put a space after the timestamp: (1609459200) "Blank Aug" -1 571000. Without the + // "\s*" there the description, max solves and repeat time went unread, so the flag had no cooldown. private static readonly Regex QuestLineRegex = new Regex( - @"(?\S+) \- (?\d+) solves \((?\d{0,11})\)""?((?.*)"" (?.*) (?\d{0,11}))?.*$", + @"(?\S+) \- (?\d+) solves \((?\d{0,11})\)\s*""?((?.*)"" (?-?\d+) (?\d{0,11}))?.*$", RegexOptions.Compiled); private readonly RynthCoreHost _host; diff --git a/Plugins/RynthCore.Plugin.RynthAi/NavRecovery.cs b/Plugins/RynthCore.Plugin.RynthAi/NavRecovery.cs index 459cd67..72b5fe3 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/NavRecovery.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/NavRecovery.cs @@ -65,7 +65,20 @@ internal enum NavAreaCheck internal interface INavRecoveryPlanner { NavRecoveryPlan? TryPlan(NavPoint target, out string why); + /// + /// How far the character walks to , for choosing the waypoint a route starts at: a plan's + /// length, or for a waypoint in the character's own room with nothing placed in the way, the straight line (TryPlan + /// has no plan for that one: there is nothing to walk round). Null when the map has no way there. + /// + double? WalkLengthYd(NavPoint target) => TryPlan(target, out _)?.LengthYd; NavAreaCheck CheckArea(uint playerCell, double tNs, double tEw, out string routeArea, out string playerArea); + /// + /// Whether the character can walk straight to with nothing in the way, on the dungeon map + /// (NavRecoveryPlanner.WalkInSightOn: no wall across the walk at a body's height and width, on the floor all the way, + /// through nothing placed). Null where the map can't say (outside a dungeon, the map not loaded, the character not + /// on its floor): the caller then walks as it did before. + /// + bool? StraightWalkInSight(NavPoint target) => null; } internal sealed class NavRecoveryPlanner : INavRecoveryPlanner @@ -118,9 +131,82 @@ internal sealed class NavRecoveryPlanner : INavRecoveryPlanner /// with set when no pathfinder can help (the caller then uses /// the old escape ladder). /// - public NavRecoveryPlan? TryPlan(NavPoint target, out string why) + public NavRecoveryPlan? TryPlan(NavPoint target, out string why) => Plan(target, out why, out _); + + /// + /// The walk to for the start pick (INavRecoveryPlanner.WalkLengthYd). A waypoint in your own + /// room with a clear walk to it counts as the straight line: with no plan for it, the pick used to leave it out, so + /// the one you stand on lost to one a floor below with a way down (Desert Mine 0x0182, 2026-11-27: the loop's [0] at + /// the arrival lost to [132], 12 m under it, a 99 yd walk; reached at once from above, since arriving doesn't look at + /// height, it sent the bot at the wall toward [133]). + /// + public double? WalkLengthYd(NavPoint target) + { + var plan = Plan(target, out _, out double inRoomYd); + if (plan != null) return plan.LengthYd; + return inRoomYd >= 0 ? inRoomYd : null; + } + + /// INavRecoveryPlanner.StraightWalkInSight: in a dungeon's cell, on that dungeon's map (WalkInSightOn). + public bool? StraightWalkInSight(NavPoint target) + { + if (!_host.HasGetPlayerPose || + !_host.TryGetPlayerPose(out uint cell, out float lx, out float ly, out float lz, out _, out _, out _, out _) || + (cell & 0xFFFF) < 0x0100 || + !NavCoordinateHelper.TryConvertPoseToCoords(cell, lx, ly, out double pNs, out double pEw)) + return null; + var cellDat = CellDat; + if (cellDat == null) return null; + uint lb = cell >> 16; + if (!IsDungeonLandblock(lb, cellDat)) return null; + try + { + var geo = DungeonPathfinder.GetGeometry(lb, cellDat, _raycast()?.GeometryLoader?.DungeonLOS); + return geo == null ? null : WalkInSightOn(geo, pNs, pEw, lz, target); + } + catch { return null; } + } + + /// Half a body's width: the sight lines either side of the walk's middle (metres). + internal const double InSightSide = 0.35; + /// The side lines leave out this much at each end, where the body stands (a character against a wall after a fight). + internal const double InSightEndSkip = 0.5; + + /// + /// The straight walk from the character at (pNs, pEw), height pz (world), to on the dungeon + /// map: no wall reaching knee to head height across it (DungeonGeometry.SightClear) on its middle line and on a line + /// to either side, and on the floor all the way through nothing placed + /// (DungeonPathfinder.StraightWalkClear). A route waypoint's Z of 0 (not recorded) is taken at the character's height. + /// Null when the character isn't on the map's floor (the map can't say). + /// + internal static bool? WalkInSightOn(DungeonGeometry geo, double pNs, double pEw, double pz, NavPoint target) + { + double px = DungeonGeometry.NavToWorld(pEw), py = DungeonGeometry.NavToWorld(pNs); + if (!geo.TryFloorHeight(px, py, pz, 3.0, out double ph)) return null; + double tx = DungeonGeometry.NavToWorld(target.EW), ty = DungeonGeometry.NavToWorld(target.NS); + double tz = target.Z != 0.0 ? target.Z * 240.0 : pz; + if (!geo.TryFloorHeight(tx, ty, tz, 3.0, out double th)) th = tz; + + double dx = tx - px, dy = ty - py, len = Math.Sqrt(dx * dx + dy * dy); + if (len < 0.5) return true; + if (!geo.SightClear(px, py, ph, tx, ty, th)) return false; + if (len > 2 * InSightEndSkip + 0.1) + { + double ux = dx / len, uy = dy / len, ox = -uy * InSightSide, oy = ux * InSightSide; + double ax = px + ux * InSightEndSkip, ay = py + uy * InSightEndSkip, az = ph + (th - ph) * InSightEndSkip / len; + double bx = tx - ux * InSightEndSkip, by = ty - uy * InSightEndSkip, bz = th - (th - ph) * InSightEndSkip / len; + if (!geo.SightClear(ax + ox, ay + oy, az, bx + ox, by + oy, bz)) return false; + if (!geo.SightClear(ax - ox, ay - oy, az, bx - ox, by - oy, bz)) return false; + } + var from = new NavPoint { Type = NavPointType.Point, NS = pNs, EW = pEw, Z = ph / 240.0 }; + var to = new NavPoint { Type = NavPointType.Point, NS = target.NS, EW = target.EW, Z = th / 240.0 }; + return DungeonPathfinder.StraightWalkClear(geo, from, to); + } + + private NavRecoveryPlan? Plan(NavPoint target, out string why, out double inRoomYd) { why = string.Empty; + inRoomYd = -1; if (!_host.HasGetPlayerPose || !_host.TryGetPlayerPose(out uint cell, out float lx, out float ly, out float lz, out _, out _, out _, out _) || !NavCoordinateHelper.TryConvertPoseToCoords(cell, lx, ly, out double pNs, out double pEw)) @@ -136,7 +222,7 @@ internal sealed class NavRecoveryPlanner : INavRecoveryPlanner string indoorWhy = string.Empty; if (inEnvCell) { - var plan = PlanIndoor(cell, pNs, pEw, lz, target.NS, target.EW, tz, out bool applicable, out indoorWhy); + var plan = PlanIndoor(cell, pNs, pEw, lz, target.NS, target.EW, tz, out bool applicable, out indoorWhy, out inRoomYd); if (plan != null) return plan; if (applicable) { why = indoorWhy; return null; } // In a dungeon the landscape navmesh is meaningless: a tile baked for this @@ -159,10 +245,11 @@ internal sealed class NavRecoveryPlanner : INavRecoveryPlanner private NavRecoveryPlan? PlanIndoor(uint playerCell, double pNs, double pEw, float pz, double tNs, double tEw, float tz, - out bool applicable, out string why) + out bool applicable, out string why, out double inRoomYd) { applicable = false; why = string.Empty; + inRoomYd = -1; var cellDat = CellDat; if (cellDat == null) { why = "dungeon data not loaded yet"; return null; } @@ -197,6 +284,8 @@ internal sealed class NavRecoveryPlanner : INavRecoveryPlanner string roomWhy = string.Empty; var inRoom = geo != null ? PlanInRoom(geo, pNs, pEw, pz, tNs, tEw, tz, out roomWhy) : null; if (inRoom != null) return inRoom; + // Nothing in the way (or no map of what is placed): the walk there is the straight line. + if (geo == null || roomWhy == StraightWalkClearWhy) inRoomYd = NavYd(tNs - pNs, tEw - pEw); why = geo == null ? "already in the waypoint's room, the map has no way around" : $"already in the waypoint's room, the map has no way around ({roomWhy})"; return null; @@ -226,6 +315,8 @@ internal sealed class NavRecoveryPlanner : INavRecoveryPlanner internal const double InRoomTargetClearance = 1.0; /// ... at most this far (0x00C1's statue is 9 x 9 m: its waypoint came 2.5 m out). internal const double InRoomTargetPushMax = 8.0; + /// PlanInRoom's answer when nothing placed is in the way (the start pick counts that walk as the straight line). + internal const string StraightWalkClearWhy = "the straight walk is clear on the map (the snag isn't on it)"; /// /// The walk from the character (pNs, pEw, pz) to the waypoint (tNs, tEw, tz) within one room, on the dungeon map: @@ -284,7 +375,7 @@ internal sealed class NavRecoveryPlanner : INavRecoveryPlanner int left0 = DungeonPathfinder.HolesLeft; int round = DungeonPathfinder.WalkRoundHoles(pts, geo, objectsOnly: true); if (round == 0 && DungeonPathfinder.HolesLeft > left0) { why = "no way round what is placed there"; return null; } - if (round == 0 && !moved) { why = "the straight walk is clear on the map (the snag isn't on it)"; return null; } + if (round == 0 && !moved) { why = StraightWalkClearWhy; return null; } var plan = new NavRecoveryPlan { Planner = moved ? "dungeon map (room, waypoint moved out of an object)" : "dungeon map (room)", TargetMoved = moved }; // The character's own spot is not walked to; the waypoint is the engine's, unless it was moved. diff --git a/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs b/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs index e56f07f..7464155 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs @@ -162,6 +162,7 @@ internal sealed partial class NavigationEngine public string Planner = string.Empty; public bool Navmesh; // RynthNav navmesh corners: the corner gate applies (NavmeshRaycast) public bool TargetMoved; // the rejoin waypoint is inside something placed: the last point stands in for it + public bool InSight; // a walk back to the route in sight after a pause (RejoinInSight), not a stuck recovery public List Points = new(); public int Index; // next detour point to reach public int StartIdx; // ActiveNavIndex when it began (a change cancels it) @@ -840,20 +841,205 @@ internal sealed partial class NavigationEngine /// Nav took over again after a pause. With NavResumeNearest on and the pause having /// moved the character or more (a chase, a corpse run), the /// route re-picks its closest waypoint instead of walking back to the one it was heading for. - /// A detour or area hold in progress owns getting back, so it is left alone. + /// A detour or area hold in progress owns getting back, so it is left alone. Then, in a dungeon, + /// a waypoint with no clear straight walk to it is reached by way of the route in sight first + /// (), whichever waypoint that is and whatever NavResumeNearest says. /// private void ResumeAfterPause() { double pNs = _pauseNs, pEw = _pauseEw; ClearPausePosition(); - if (!_settings.NavResumeNearest || double.IsNaN(pNs)) return; - if (_detour != null || _areaMismatch) return; - if (KeepWaypointAfterPause?.Invoke() == true) return; + if (double.IsNaN(pNs) || _areaMismatch) return; + // A walk back to the route in sight that this pause broke into: looked at again from where we are now. + bool inSightWalk = _detour is { InSight: true }; + if (inSightWalk) EndDetour("cancelled, another pause: looked at again from here", success: false); + if (_detour != null) return; if (!TryGetPos(out double ns, out double ew)) return; double movedYd = Math.Sqrt(Sq(ns - pNs) + Sq(ew - pEw)) * 240.0; - if (movedYd < ResumeMovedYards || movedYd > ResumeTeleportYards) return; - RepickNearestWaypoint($"back from a pause that moved {movedYd:F0}yd", resetRecovery: false); + if (movedYd > ResumeTeleportYards) return; + if (_settings.NavResumeNearest && movedYd >= ResumeMovedYards && KeepWaypointAfterPause?.Invoke() != true) + RepickNearestWaypoint($"back from a pause that moved {movedYd:F0}yd", resetRecovery: false); + if (movedYd >= InSightMinMovedYd || inSightWalk) RejoinInSight(movedYd); + } + + // ── Back to the route in sight (2026-11-28) ────────────────────────────── + // Lugian Excavations (0x02E7), a melee character on the dungeon patrol with Monster Range at 20 m so the Deepvein + // Hurlers (rock throwers) die before the melee lugians: the fights took it off the route, into side rooms and round + // corners, and once everything was dead and looted nav steered straight at the waypoint it had been heading for (the + // patrol keeps it: KeepWaypointAfterPause) and ran into the wall between. The stuck ladder only caught it after 5 s at + // the wall, jumped, and planned a way 5 s later (18:56:16 back from looting, 18:56:31 stuck x1, 18:56:36 a detour, the + // waypoint reached 18:56:56). Now, back from a pause that moved + // the character, a waypoint the dungeon map shows no clear straight walk to (INavRecoveryPlanner.StraightWalkInSight) + // is reached by way of the route: the cheapest spot of the route it can walk to straight, on the legs into the waypoint + // (back at most InSightLegsBack legs, InSightBackYd of route) or the legs out of it (InSightLegsAhead, passing over at + // most InSightAheadYd of route first). A spot behind costs the route walked again to the waypoint, a spot ahead half + // the route it passes over, so a near spot on the leg into the waypoint wins over a nearer one far back or far on. + // The 18:56 stuck there (cell 02E70125, 39.5 m from waypoint [15] across a wall) had the route in sight only two legs + // on ([16]->[17]) and on the loop's way back; the way back stays out of reach (the patrol's order). Nothing in sight: + // the map's way to the waypoint (a recovery detour, through the doorways). The map can't say (outdoors, not loaded): + // as before. + + private const int InSightLegsBack = 8; // legs into the waypoint looked along, back along the route + private const double InSightBackYd = 80.0; // ... at most this much route behind it + private const int InSightLegsAhead = 3; // legs out of it looked along + private const double InSightAheadYd = 45.0; // ... passing over at most this much route before one starts + private const double InSightSkipCost = 0.5; // a spot ahead costs this much of the route it passes over + private const double InSightStepYd = 3.0; // spots along a leg this far apart (and the one nearest the character) + private const double InSightMaxYd = 60.0; // spots farther than this from the character aren't tried + private const int InSightMaxTests = 40; // walk tests at most, cheapest spot first + private const double InSightMinMovedYd = 1.0; // a pause that moved the character less put nothing between + + /// A spot of the route to walk back to: on the leg [From]→[Rejoin], Yd from the character; Over: the + /// waypoints it passes over (a spot ahead), 0 for one on a leg into the waypoint. + private readonly record struct InSightSpot(NavPoint Spot, int From, int Rejoin, double Yd, double Cost, int Over); + + /// + /// Back from a pause: when the dungeon map has no clear straight walk to the current waypoint, walks to the cheapest + /// spot of the route near it that it has one to (an InSight detour, then the route goes on from its leg's end), or + /// failing that plans the map's way to the waypoint. True when it started something. + /// + private bool RejoinInSight(double movedYd) + { + var route = _settings.CurrentRoute; + if (route == null || !RecoveryEnabled || _planner == null) return false; + if (route.RouteType == NavRouteType.Follow || route.NavmeshCorners || route.OutdoorHuntWalk) 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)) return false; + + var target = route.Points[idx]; + if (_planner.StraightWalkInSight(target) != false) return false; // a clear walk, or the map can't say + + var spots = InSightSpots(route, idx, ns, ew); + int tests = 0; + InSightSpot? found = null; + foreach (var s in spots) + { + if (tests++ >= InSightMaxTests) break; + if (_planner.StraightWalkInSight(s.Spot) == true) { found = s; break; } + } + + double toTarget = NavYd(target.NS - ns, target.EW - ew); + if (found is not { } f) + { + _host.Log($"Nav: back from a pause (moved {movedYd:F0}yd): no clear walk to [{idx}] ({toTarget:F0}yd) on the dungeon map, and no spot of the route near it in sight ({Math.Min(tests, spots.Count)} of {spots.Count} tried): the map's way there"); + return TryStartDetour(route, idx, $"back from a pause, [{idx}] is behind a wall and the route near it is out of sight"); + } + + string leg = $"the leg [{f.From}]->[{f.Rejoin}]"; + string over = f.Over switch + { + 0 => "", + 1 => $", passing over [{idx}]", + _ => $", passing over [{idx}] to [{f.From}] ({f.Over} waypoints)", + }; + if (f.Yd < ArrivalYards) + { + // Already on the route there: go on from that leg's end. + if (f.Rejoin != idx) + { + _host.Log($"Nav: back from a pause (moved {movedYd:F0}yd): no clear walk to [{idx}] on the dungeon map; on {leg} already, going on from [{f.Rejoin}]{over}"); + _settings.ActiveNavIndex = f.Rejoin; + _closestDist = double.MaxValue; + } + return false; + } + + long now = Now; + _detour = new Detour + { + Number = ++_recoveryNumber, + Reason = $"back from a pause, no clear walk to [{idx}]", + Planner = "the route in sight", + InSight = true, + Points = new List { f.Spot }, + StartIdx = idx, + RejoinIdx = f.Rejoin, + Skipped = f.Over, + LengthYd = f.Yd, + StartedAt = now, + DeadlineAt = now + 15000 + (long)(f.Yd * 600.0), + }; + _closestDist = double.MaxValue; + _host.Log($"Nav: back from a pause (moved {movedYd:F0}yd): no clear walk to [{idx}] ({toTarget:F0}yd) on the dungeon map (a wall or a drop in the way) - " + + $"walking to the route in sight first: {f.Yd:F0}yd to {leg}, then on from [{f.Rejoin}]{over} (recovery #{_detour.Number})"); + return true; + } + + /// + /// The spots RejoinInSight tries, cheapest first: on each leg into back along the route (the + /// spot nearest the character and one every InSightStepYd, the waypoint itself left out: its walk is the one that + /// failed), costing their distance plus the route from them on to the waypoint; and on the legs out of it, costing + /// their distance plus InSightSkipCost of the route they pass over. Never past a step (a portal, a recall, a chat, a + /// pause point), never round a whole loop, never on past a Jump point (it jumps on arrival). + /// + private List InSightSpots(NavRouteParser route, int idx, double ns, double ew) + { + var list = new List(); + int r = idx; + double along = 0; // route from r on to idx + for (int k = 0; k < InSightLegsBack && along <= InSightBackYd; k++) + { + int prev = PrevIndex(r, route); + if (prev < 0 || prev == idx) break; + var a = route.Points[prev]; + if (!IsWalkTarget(a.Type)) break; + var b = route.Points[r]; + AddLegSpots(list, a, b, prev, r, along, over: 0, skipEnd: r == idx, ns, ew); + along += NavYd(b.NS - a.NS, b.EW - a.EW); + if (!NavRouteParser.IsPlainWaypoint(a.Type)) break; // a Jump: its leg is the landing, not walked back past + r = prev; + } + + int cur = idx; + double passed = 0; // route from idx to cur, passed over + for (int k = 0; k < InSightLegsAhead && passed <= InSightAheadYd; k++) + { + var a = route.Points[cur]; + if (a.Type == NavPointType.Jump) break; + int next = NextInOrder(cur, route); + if (next < 0 || next == idx) break; + var b = route.Points[next]; + if (!IsWalkTarget(b.Type)) break; + AddLegSpots(list, a, b, cur, next, passed, over: k + 1, skipEnd: false, ns, ew); + passed += NavYd(b.NS - a.NS, b.EW - a.EW); + cur = next; + } + + list.Sort((x, y) => x.Cost.CompareTo(y.Cost)); + return list; + } + + /// Spots on the leg a→b ([from]→[rejoin]): the one nearest (ns, ew) and one every InSightStepYd. Behind + /// (over 0): is the route from b on to the waypoint; ahead: the route passed over before a. + private static void AddLegSpots(List list, NavPoint a, NavPoint b, int from, int rejoin, double routeYd, + int over, bool skipEnd, double ns, double ew) + { + bool ahead = over > 0; + double vN = b.NS - a.NS, vE = b.EW - a.EW; + double legYd = NavYd(vN, vE); + var ts = new List(); + if (legYd < 0.1) ts.Add(1.0); + else + { + double len2 = vN * vN + vE * vE; + ts.Add(Math.Clamp(((ns - a.NS) * vN + (ew - a.EW) * vE) / len2, 0, 1)); + for (double d = 0; d < legYd; d += InSightStepYd) ts.Add(d / legYd); + ts.Add(1.0); + } + foreach (double t in ts) + { + // The waypoint itself (its walk is the one that failed); an ahead leg's start is the leg before's end. + if ((skipEnd && t > 1 - 1e-9) || (ahead && t < 1e-9)) continue; + double sN = a.NS + vN * t, sE = a.EW + vE * t; + double yd = NavYd(sN - ns, sE - ew); + if (yd > InSightMaxYd) continue; + double z = a.Z != 0 && b.Z != 0 ? a.Z + (b.Z - a.Z) * t : (a.Z != 0 ? a.Z : b.Z); + var spot = new NavPoint { Type = NavPointType.Point, NS = sN, EW = sE, Z = z }; + double cost = ahead ? yd + InSightSkipCost * (routeYd + t * legYd) : yd + (1 - t) * legYd + routeYd; + list.Add(new InSightSpot(spot, from, rejoin, yd, cost, over)); + } } /// @@ -1009,9 +1195,11 @@ internal sealed partial class NavigationEngine double bestYd = double.MaxValue; foreach (int i in candidates) { - var plan = _planner.TryPlan(route.Points[i], out _); - if (plan == null) continue; - if (plan.LengthYd < bestYd) { bestYd = plan.LengthYd; best = i; } + // The planner's walk length: a waypoint in your own room with nothing in the way is the straight line to it + // (TryPlan has no plan for it, and it was left out: Desert Mine 2026-11-27). + double? yd = _planner.WalkLengthYd(route.Points[i]); + if (yd == null) continue; + if (yd.Value < bestYd) { bestYd = yd.Value; best = i; } } walkYd = best >= 0 ? bestYd : 0; return best; @@ -3421,11 +3609,14 @@ internal sealed partial class NavigationEngine _lastDistYd = dist; _lastHeadingErr = headingErr; _lastSteerAt = Now; - _settings.NavIsStuck = true; + // A walk back to the route in sight after a fight is no trouble: not shown as stuck. + _settings.NavIsStuck = !d.InSight; string modeStr = _isTurning ? " [TURN]" : string.Empty; string errStr = Math.Abs(headingErr) > 0.5 ? $" err={headingErr:+0.0;-0.0}°" : string.Empty; - _settings.NavStatusLine = $"Nav: recovering - detour {d.Index + 1}/{d.Points.Count} to waypoint {d.RejoinIdx + 1} {dist:F1}yd{errStr}{modeStr}"; + _settings.NavStatusLine = d.InSight + ? $"Nav: back to the route in sight, then waypoint {d.RejoinIdx + 1} {dist:F1}yd{errStr}{modeStr}" + : $"Nav: recovering - detour {d.Index + 1}/{d.Points.Count} to waypoint {d.RejoinIdx + 1} {dist:F1}yd{errStr}{modeStr}"; } // ══════════════════════════════════════════════════════════════════════════ diff --git a/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs index 2bdbdc1..f04ab2f 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs @@ -715,6 +715,16 @@ public static unsafe class PluginExports catch { } } + /// + /// The Monsters list's Clear list (the engine's Damage panel, after its yes): every rule but + /// Default removed from the profile in use and saved, said in chat (2026-11-27). + /// + [UnmanagedCallersOnly(EntryPoint = "RynthPluginClearMonsterRules", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void ClearMonsterRules() + { + try { Runtime.Plugin?.DashboardRenderer?.ClearMonsterRulesAndSay(); } catch { } + } + // ── Settings bridge (engine-side Avalonia SettingsPanel) ──────────────── private static IntPtr _settingsPtr = IntPtr.Zero; diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs index 4b9ef28..2d18f47 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs @@ -127,7 +127,7 @@ public sealed partial class RynthAiPlugin ChatLine("[RynthAi] /ra petelement [status|any|fire|cold|acid|lightning|nether|slash|pierce|bludgeon] — the element combat pets are summoned for (Mini Remote > Pets)"); ChatLine("[RynthAi] /ra offhand [auto|shield|weapon|none] [rule] — the off hand (shield / dual wield), global or for a Monsters rule; dual on|off"); ChatLine("[RynthAi] /ra dunnav — navigate to NS/EW coords through dungeon (no nav file needed)"); - ChatLine("[RynthAi] /ra dunnav-to — walk to an object in this dungeon, any floor (a monster, say)"); + ChatLine("[RynthAi] /ra dunnav-to | cell — walk to an object (or a cell) in this dungeon, any floor (a monster, say)"); ChatLine("[RynthAi] /ra dunnav-patrol — circular hunt patrol through the whole dungeon (no nav file needed)"); ChatLine("[RynthAi] /ra dunnav-explore [stop|status|resume|done] — walk through every room of this dungeon once, then stop (fights, loots, buffs as set)"); ChatLine("[RynthAi] /ra dunnav-explore lever [door ] [at ] [plate] — pull a lever (or step on a plate) for a shut door, then carry on"); @@ -1431,7 +1431,7 @@ public sealed partial class RynthAiPlugin private const string MetaUsage = "/ra meta load | new | save | saveas | rename | delete | folder | list | repair"; private const string SettingsUsage = - "/ra settings loadchar | savechar | save | saveas | rename | delete | folder | list"; + "/ra settings loadchar | savechar | save | saveas (a copy) | new (fresh: no monsters or items) | rename | delete | folder | list"; private const string LootFileUsage = "/ra loot new | saveas | rename | delete | folder | edit"; @@ -1884,10 +1884,13 @@ 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)), + // Values only the text carries (the slayer bonus, RynthCore.Loot.SlayerText). + ItemText = wo.Values(StringValueKey.LongDesc, string.Empty) + "\n" + wo.Values(StringValueKey.Use, string.Empty), }; foreach (int key in RynthCore.Loot.Editing.LootItemRules.IntKeys) { - int v = wo.Values(key, 0); + // ImbuedEffect as the loot rules read it: 179 with ImbuedEffect2-5 folded in. + int v = key == 179 ? VTankLootEvaluator.LongOf(wo, key) : wo.Values(key, 0); if (v != 0) f.Ints[key] = v; } foreach (int key in RynthCore.Loot.Editing.LootItemRules.DoubleKeys) @@ -2313,7 +2316,7 @@ public sealed partial class RynthAiPlugin { if (!canRemove) { ReplyFail("[RynthAi] This engine can't remove objects from the client (needs plugin API v83)."); return; } int sent = 0, refused = 0; - foreach (var g in ghosts.All.ToList()) + foreach (var g in ghosts.All.Where(g => !g.Suspect).ToList()) // suspects are only skipped, never removed { int r = Host.RemoveClientObject((uint)g.Id); if (r == 1 || r == 2) sent++; else refused++; @@ -2648,7 +2651,7 @@ public sealed partial class RynthAiPlugin { string sub = parts.Length > 2 ? parts[2].ToLowerInvariant() : string.Empty; string rest = parts.Length > 3 ? string.Join(" ", parts, 3, parts.Length - 3).Trim() : string.Empty; - if (sub is "save" or "saveas" or "rename" or "delete" or "folder") + if (sub is "save" or "saveas" or "new" or "rename" or "delete" or "folder") { // The Loaded files drawer's PROFILE buttons (RynthAiPlugin.ProfileFiles.cs). TryProfileVerb(ProfileKind.Settings, sub, rest, SettingsUsage); @@ -3276,7 +3279,21 @@ public sealed partial class RynthAiPlugin : $"[RynthAi] No items in inventory matched profile '{System.IO.Path.GetFileName(profilePath)}'"); } - internal const string DunNavToUsage = "[RynthAi] Usage: /ra dunnav-to [jump] — walk to an object in this dungeon (any floor), e.g. a monster: /ra dunnav-to 0x80123456; with jump, a jump down a ledge may be taken when there's no walk (one way: no climbing back)"; + internal const string DunNavToUsage = "[RynthAi] Usage: /ra dunnav-to [jump] | cell [name] [jump] [walkonly] — walk to an object (or a cell) in this dungeon (any floor), e.g. a monster: /ra dunnav-to 0x80123456; with jump, a jump down a ledge may be taken when there's no walk (one way: no climbing back); with walkonly, no fighting, looting, buffing or meta on the way (put back after)"; + + /// "/ra dunnav-to cell 009C0270 [a name] [jump]": the cell (8 hex digits, a dungeon cell) and the words after it as its label. + internal static bool TryParseDunNavCell(string[] parts, out uint cell, out string label) + { + cell = 0; label = ""; + if (parts.Length < 4) return false; + string c = parts[3].Trim(); + if (c.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) c = c[2..]; + if (c.Length != 8 || !uint.TryParse(c, System.Globalization.NumberStyles.HexNumber, System.Globalization.CultureInfo.InvariantCulture, out cell) + || (cell & 0xFFFF) < 0x0100) { cell = 0; return false; } + label = string.Join(" ", parts.Skip(4).Where(p => !p.Trim().Equals("jump", StringComparison.OrdinalIgnoreCase) + && !p.Trim().Equals(WalkOnlyWord, StringComparison.OrdinalIgnoreCase))).Trim(); + return true; + } /// /// /ra dunnav-to <object id> [jump] (2026-11-15): walks to an object in the dungeon the character is @@ -3294,28 +3311,54 @@ public sealed partial class RynthAiPlugin // Off in a Thread on DreamWeave, as the patrol and the explore are (its owners asked for that: ServerPolicy). if (ServerPolicy.PatrolOff(Host)) { ReplyFail(ServerPolicy.DunNavToOffMessage); return; } string arg = parts.Length > 2 ? parts[2].Trim() : ""; - bool hex = arg.StartsWith("0x", StringComparison.OrdinalIgnoreCase); - if (!uint.TryParse(hex ? arg[2..] : arg, hex ? System.Globalization.NumberStyles.HexNumber : System.Globalization.NumberStyles.Integer, - System.Globalization.CultureInfo.InvariantCulture, out uint target) || target == 0) + // "cell [name]" (2026-11-27): a cell of this dungeon rather than an object, for someone + // the client hasn't been sent yet (RynthNav's go to a person inside a dungeon hands over this walk). + bool byCell = arg.Equals("cell", StringComparison.OrdinalIgnoreCase); + uint target = 0, cellTarget = 0; + string cellLabel = ""; + if (byCell) { - ReplyFail(DunNavToUsage); - return; + if (!TryParseDunNavCell(parts, out cellTarget, out cellLabel)) { ReplyFail(DunNavToUsage); return; } + } + else + { + bool hex = arg.StartsWith("0x", StringComparison.OrdinalIgnoreCase); + if (!uint.TryParse(hex ? arg[2..] : arg, hex ? System.Globalization.NumberStyles.HexNumber : System.Globalization.NumberStyles.Integer, + System.Globalization.CultureInfo.InvariantCulture, out target) || target == 0) + { + ReplyFail(DunNavToUsage); + return; + } } if (!Host.TryGetPlayerPose(out uint playerCell, out float plx, out float ply, out float playerZ, out _, out _, out _, out _) || (playerCell & 0xFFFF) < 0x0100) { ReplyFail("[RynthAi] DunNav-To: you're not in a dungeon."); return; } - if (!Host.HasGetObjectPosition || !Host.TryGetObjectPosition(target, out uint objCell, out float ox, out float oy, out float oz) || objCell == 0) - { - ReplyFail($"[RynthAi] DunNav-To: 0x{target:X8} has no position the client knows."); - return; - } uint landblockKey = playerCell >> 16; - if ((objCell >> 16) != landblockKey || (objCell & 0xFFFF) < 0x0100) + uint objCell = 0; + float ox = 0, oy = 0, oz = 0; + if (byCell) { - ReplyFail($"[RynthAi] DunNav-To: 0x{target:X8} isn't in this dungeon (cell {objCell:X8})."); - return; + objCell = cellTarget; + if ((objCell >> 16) != landblockKey) + { + ReplyFail($"[RynthAi] DunNav-To: cell {objCell:X8} isn't in this dungeon (you're in landblock {landblockKey:X4})."); + return; + } + } + else + { + if (!Host.HasGetObjectPosition || !Host.TryGetObjectPosition(target, out objCell, out ox, out oy, out oz) || objCell == 0) + { + ReplyFail($"[RynthAi] DunNav-To: 0x{target:X8} has no position the client knows."); + return; + } + if ((objCell >> 16) != landblockKey || (objCell & 0xFFFF) < 0x0100) + { + ReplyFail($"[RynthAi] DunNav-To: 0x{target:X8} isn't in this dungeon (cell {objCell:X8})."); + return; + } } var map = DungeonMapOverride?.Invoke(landblockKey); var cellDat = _raycast?.GeometryLoader.CellDat; @@ -3325,13 +3368,37 @@ public sealed partial class RynthAiPlugin var geo = map != null ? map.Value.Geo : DungeonPathfinder.GetGeometry(landblockKey, cellDat!, _raycast?.GeometryLoader?.DungeonLOS); // closes the ledges first double lbX = ((playerCell >> 24) & 0xFF) * 192.0, lbY = ((playerCell >> 16) & 0xFF) * 192.0; double playerEW = DungeonGeometry.WorldToNav(lbX + plx), playerNS = DungeonGeometry.WorldToNav(lbY + ply); - double destEW = DungeonGeometry.WorldToNav(lbX + ox), destNS = DungeonGeometry.WorldToNav(lbY + oy); + double destEW, destNS; + if (byCell) + { + // The cell's own spot on the map: where the dats place it. + if (!graph.TryGetValue(objCell, out DungeonNavNode? node)) + { + ReplyFail($"[RynthAi] DunNav-To: cell {objCell:X8} isn't on this dungeon's map."); + return; + } + destNS = node.NS; destEW = node.EW; oz = node.Z; + } + else + { + destEW = DungeonGeometry.WorldToNav(lbX + ox); destNS = DungeonGeometry.WorldToNav(lbY + oy); + } uint startCell = graph.ContainsKey(playerCell) ? playerCell : DungeonPathfinder.NearestCell(graph, playerNS, playerEW, playerZ); uint goalCell = graph.ContainsKey(objCell) ? objCell : DungeonPathfinder.NearestCell(graph, destNS, destEW, oz); var hazards = _objectCache?.GetHazardCells(); var path = startCell != 0 && goalCell != 0 ? DungeonPathfinder.FindPath(startCell, goalCell, graph, hazards) : new List(); - Host.TryGetObjectName(target, out string name); + string name = ""; + if (byCell) name = cellLabel.Length > 0 ? cellLabel : $"cell {objCell:X8}"; + else Host.TryGetObjectName(target, out name); bool mayJump = parts.Skip(3).Any(p => p.Trim().Equals("jump", StringComparison.OrdinalIgnoreCase)); + // "walkonly" (2026-11-27): walk there without fighting, looting, buffing or the meta (RynthAiPlugin.WalkTrip.cs). + bool walkOnly = parts.Skip(3).Any(p => p.Trim().Equals(WalkOnlyWord, StringComparison.OrdinalIgnoreCase)); + if (byCell && goalCell == startCell && path.Count <= 1) + { + ReplyOk($"[RynthAi] DunNav-To: already in {objCell:X8} ({name})."); + return; + } + string what = byCell ? $"'{name}'" : $"'{name}' 0x{target:X8}"; NavRouteParser route; string how; if (path.Count == 0) @@ -3342,7 +3409,7 @@ public sealed partial class RynthAiPlugin : new List<(uint Cell, DungeonJump? Jump)>(); if (jumpPath.Count == 0) { - ReplyFail($"[RynthAi] DunNav-To: no walk from {startCell:X8} to '{name}' 0x{target:X8} in {goalCell:X8} on the dungeon map (behind a ledge or a hazard?)" + ReplyFail($"[RynthAi] DunNav-To: no walk from {startCell:X8} to {what} in {goalCell:X8} on the dungeon map (behind a ledge or a hazard?)" + (mayJump ? ", and no jump down gets there either." : ".")); return; } @@ -3351,21 +3418,23 @@ public sealed partial class RynthAiPlugin route.Points.Add(new NavPoint { Type = NavPointType.Point, NS = destNS, EW = destEW, Z = oz / 240.0 }); var first = jumpPath.First(p => p.Jump != null).Jump!.Value; how = $"{jumpPath.Count} cells, {jumps} jump{(jumps == 1 ? "" : "s")} down (the first {first.Drop:F1} m off {first.From:X8} into {first.Land:X8})"; - Host.Log($"[RynthAi] DunNav-To: no walk to 0x{target:X8}; jumping down: {how}."); + Host.Log($"[RynthAi] DunNav-To: no walk to {what}; jumping down: {how}."); } else { route = DungeonPathfinder.BuildNavRoute(path, graph, destNS, destEW, geo, hazards, playerNS, playerEW, playerZ, oz); how = $"{path.Count} cells"; } - if (route.Points.Count == 0) { ReplyFail($"[RynthAi] DunNav-To: no walk laid to '{name}' 0x{target:X8}."); return; } + if (route.Points.Count == 0) { ReplyFail($"[RynthAi] DunNav-To: no walk laid to {what}."); return; } if (!settings.IsMacroRunning && RefuseMacroStartForVTank()) return; // one bot per client (Decal bridge) + if (walkOnly) BeginWalkTrip(settings, route, landblockKey, byCell ? $"'{name}'" : what); // before the macro start: its state is the player's settings.SetMacroRunning(true, "/ra dunnav-to"); settings.CurrentRoute = route; settings.ActiveNavIndex = 0; settings.EnableNavigation = true; - ReplyOk($"[RynthAi] DunNav-To: '{name}' 0x{target:X8} in {goalCell:X8}: {how}, {route.Points.Count} points → walking there"); + ReplyOk($"[RynthAi] DunNav-To: {what} in {goalCell:X8}: {how}, {route.Points.Count} points → walking there" + + (walkOnly ? " (walk only: fighting, looting, buffing and the meta off until it ends, then put back)" : "")); } /// diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ChestLoot.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ChestLoot.cs index e5dc1aa..86d19ac 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ChestLoot.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ChestLoot.cs @@ -268,6 +268,7 @@ public sealed partial class RynthAiPlugin /// private void FinishChestLoot(int chestId, string why, bool close, bool sayNothingMatched) { + NoteChestLootTally(chestId); // the Item Tool's chest looter reads it (RynthAiPlugin.ItemTool.cs) 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. diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ItemTool.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ItemTool.cs index 2879c88..56c6123 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ItemTool.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ItemTool.cs @@ -28,6 +28,8 @@ namespace RynthCore.Plugin.RynthAi; // chest set | key | start | stop | status | clear // relock (also "chest relock"): "Chest re-lock wait (s)", saved in the profile (2026-11-05) // giveitem | givetarget | give | givestop | givestatus | clear +// giveamount | giveevery : how a give goes (2026-11-27; this +// session only, like the picks; any source may set them, only a trusted one starts a give) // stop (both) // // Threads: a chat command arrives on AC's thread and the panel's on the engine pump, but the tick @@ -53,6 +55,9 @@ public sealed partial class RynthAiPlugin private long _chestKeyOpenedAt; private long _itemToolBusySince; private int _giveTargetClass; // what the picked target is (for the status line) + // FinishChestLoot: the last chest session's tally, for the chest looter (IChestKeyEnv.LastLootTally). + private int _chestKeyTallyId, _chestKeyTallyWanted, _chestKeyTallyTaken; + private string _chestKeyTallyFirst = ""; private const long ItemToolBusyGraceMs = 2500; private const uint ItemToolBfPlayer = 0x00000008, ItemToolBfAttackable = 0x00000010, ItemToolBfVendor = 0x00000200; @@ -133,7 +138,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 and /ra itemtool giveitem|givetarget|give|givestop|givestatus"); + ChatLine("[RynthAi] /ra itemtool chest set|key|start|stop|status /ra itemtool relock and /ra itemtool giveitem|givetarget|give|givestop|givestatus /ra itemtool giveamount /ra itemtool giveevery "); return; case "stop": if (_chestKey!.Running) _chestKey.Stop("stopped by you"); @@ -156,6 +161,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 +177,34 @@ public sealed partial class RynthAiPlugin } } + /// + /// "giveamount N" (units a round, 0 = all) and "giveevery N" (seconds between rounds, 0 = one round). They only + /// shape a give, so any source may set them; starting one stays the player's alone. A running give takes a + /// new Amount at its next give and a new Every at its next round. This session only, like the picks. + /// + 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 (arg.Length == 0) + { + ChatLine($"[RynthAi] Quick give: {what} is {(every ? qg.EverySec : qg.Amount)}. Set it with a number 0-{max}."); + return; + } + if (!int.TryParse(arg, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out int n) || n < 0) + { + ChatLine($"[RynthAi] Quick give: '{arg}' isn't a number 0-{max}; {what} stays {(every ? qg.EverySec : qg.Amount)}."); + return; + } + if (every) qg.SetEvery(n); else qg.SetAmount(n); + int v = every ? qg.EverySec : qg.Amount; + string clamped = v != n ? $" ({n} is past the most, {max})" : ""; + ChatLine(every + ? (v == 0 ? "[RynthAi] Quick give: one round (Every 0)." : $"[RynthAi] Quick give: a round every {v} s, until you stop it{clamped}.") + : (v == 0 ? "[RynthAi] Quick give: gives every matching item (Amount 0)." : $"[RynthAi] Quick give: gives {v} a round{clamped}.")); + } + private void RunChestCommand(string sub) { var ck = _chestKey!; @@ -287,7 +322,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() @@ -364,6 +401,27 @@ public sealed partial class RynthAiPlugin _chestKeyOpenedAt = ItemToolClock(); } + /// + /// FinishChestLoot, before anything is cleared: what the loot profile wanted from the chest (items + /// left at a Keep # / keep count are not wanted) and how many pickups landed, for the chest + /// looter's "nothing taken" stop (ChestKeyLooter.MaxStarvedChests). + /// + private void NoteChestLootTally(int chestId) + { + int wanted = 0; + string first = ""; + foreach (int id in _corpseMatchedIds) + { + if (_corpseCappedIds.Contains(id)) continue; + wanted++; + if (first.Length == 0) first = ItemToolName(id); + } + _chestKeyTallyId = chestId; + _chestKeyTallyWanted = wanted; + _chestKeyTallyTaken = _corpseItemsLooted; + _chestKeyTallyFirst = first; + } + /// /// TickCorpseOpening, every tick: the chest looter asked for its open chest to be looted. Like /// /ra lootthis: the container is flagged so the loot tick runs for it with the macro or @@ -415,7 +473,11 @@ public sealed partial class RynthAiPlugin sb.Append("\"running\":").Append(ck?.Running == true ? "true" : "false").Append(','); sb.Append("\"looted\":").Append(ck?.Looted ?? 0).Append(','); // "Chest re-lock wait (s)": the panel's control (absent from an older RynthAi: the panel hides it). - sb.Append("\"relockSec\":").Append(_dashboard?.Settings?.ChestRelockWaitSec ?? ChestKeyLooter.DefaultRelockWaitSec).Append(','); + // 0 while a run that saw the chest re-lock as it closes is going: the wait doesn't time it, and + // the panel hides the control for a value <= 0 (2026-11-28). + bool relockSeen = ck?.Running == true && ck.RelockSeen; + sb.Append("\"relockSec\":").Append(relockSeen ? 0 : _dashboard?.Settings?.ChestRelockWaitSec ?? ChestKeyLooter.DefaultRelockWaitSec).Append(','); + sb.Append("\"relockSeen\":").Append(relockSeen ? "true" : "false").Append(','); sb.Append("\"relockMin\":").Append(ChestKeyLooter.MinRelockWaitSec).Append(','); sb.Append("\"relockMax\":").Append(ChestKeyLooter.MaxRelockWaitSec).Append(','); sb.Append("\"relockReady\":").Append(_dashboard?.ProfileLoaded == true ? "true" : "false"); @@ -424,7 +486,16 @@ 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-27); a face that predates them ignores these, one that knows them + // shows its fields only when "amountMax" is here (an older RynthAi has none). + 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(); } @@ -490,6 +561,14 @@ public sealed partial class RynthAiPlugin public string? HoldReason() => _p.ItemToolHoldReason(yieldToLooter: true); + /// + /// No room for the chest's loot anywhere. Since 2026-11-28 the looter makes room itself when + /// only the main pack is full (one item goes to a side pack, then the pickup: HoldForLootRoom), + /// so a full main pack alone holds no key any more (it stopped with room left in the side + /// packs). Held: the main pack full and no side + /// pack with a free slot, or fewer free slots in all packs than the looter keeps for weapon + /// swaps (it would leave everything). + /// public string? NoRoomReason() { var cache = _p._objectCache; @@ -497,8 +576,14 @@ public sealed partial class RynthAiPlugin if (cache == null || playerId == 0) return null; try { - int free = WorldObjectCache.MainPackFreeSlots(cache.GetDirectInventory(forceRefresh: false), playerId, Host); - return free <= 0 ? "the main pack is full (loot goes only into the main pack); Auto Cram or you can make room" : null; + var inv = cache.GetDirectInventory(forceRefresh: false); + int total = WorldObjectCache.CountFreeItemSlots(Host, cache); + if (total >= 0 && total < WorldObjectCache.LootReserveFreeSlots) + return $"{total} free slot(s) left in all your packs (looting keeps {WorldObjectCache.LootReserveFreeSlots} free for weapon swaps); sell, salvage or drop something"; + int mainFree = WorldObjectCache.MainPackFreeSlots(inv, playerId, Host); + if (mainFree > 0) return null; + if (Host.HasMoveItemExternal && WorldObjectCache.SidePackHasRoom(inv, playerId, Host)) return null; // the looter moves one item to a side pack, then picks up + return "the main pack is full and no side pack has a free slot; sell, salvage or drop something"; } catch { return null; } } @@ -519,7 +604,22 @@ public sealed partial class RynthAiPlugin public long ChestOpenedAt(int chestId) => _p._chestKeyOpenedId == chestId ? _p._chestKeyOpenedAt : 0; - public void StartLooting(int chestId) => _p._chestKeyForceId = chestId; + public void StartLooting(int chestId) + { + _p._chestKeyForceId = chestId; + _p._chestKeyTallyId = 0; // the tally read after this session is this session's + } + + public bool LastLootTally(int chestId, out int wanted, out int taken, out string firstWanted) + { + wanted = _p._chestKeyTallyWanted; + taken = _p._chestKeyTallyTaken; + firstWanted = _p._chestKeyTallyFirst; + return _p._chestKeyTallyId == chestId; + } + + public bool? ChestShownOpen(int chestId) + => Host.HasGetGroundContainerId ? unchecked((int)Host.GetGroundContainerId()) == chestId : null; public bool Looting(int chestId) => _p._chestKeyForceId == chestId @@ -643,8 +743,8 @@ public sealed partial class RynthAiPlugin return true; } - 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; diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LocalFeatures.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LocalFeatures.cs index 544cfc3..abf4e51 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LocalFeatures.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LocalFeatures.cs @@ -23,6 +23,8 @@ public sealed partial class RynthAiPlugin // The server plugin's side of the Mini Remote (its tabs, sections, feature bits, verbs; RynthILT on ILT); lives for the plugin. private MiniRemote.ServerHubClient? _serverHub; private Huds.HudController? _huds; + // The "Out of components" warning (Settings > General > Show No Components Warning). + private Huds.CastWarningHud? _castWarning; private Huds.HudIconCache? _hudIcons; private Translate.ChatTranslator? _translator; private Translate.TranslateUi? _translateUi; @@ -285,6 +287,7 @@ public sealed partial class RynthAiPlugin _spellsUi?.Render(); _miniRemote?.Render(); _huds?.Render(); + _castWarning?.Render(); RenderTranslateWindow(); RenderLootWhyWindow(); RenderHuntPanel(); @@ -333,6 +336,7 @@ public sealed partial class RynthAiPlugin try { _miniRemote?.Render(); } finally { ImGui.PopStyleColor(pushedColors); } _huds?.Render(); + _castWarning?.Render(); RenderTranslateWindow(); _navOverlay?.Render(); _itemInfoUi?.Render(); diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.NearbyChests.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.NearbyChests.cs index 6caf973..7400665 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.NearbyChests.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.NearbyChests.cs @@ -219,10 +219,8 @@ public sealed partial class RynthAiPlugin public IReadOnlyList Keys() { var keys = new List(); - var names = new HashSet(StringComparer.OrdinalIgnoreCase); - foreach (var wo in _p.NearbyCarried()) - if (wo.ObjectClass == AcObjectClass.Key && names.Add(wo.Name)) - keys.Add(new ChestTool(wo.Id, wo.Name)); + foreach (var wo in _p.CarriedKeys()) + keys.Add(new ChestTool(wo.Id, wo.Name)); return keys; } @@ -232,7 +230,7 @@ public sealed partial class RynthAiPlugin if (_p.FindLockpickInConsumables() is WorldObject listed && _p.IsCarriedByPlayer(listed.Id)) return new ChestTool(listed.Id, listed.Name); foreach (var wo in _p.NearbyCarried()) - if (wo.ObjectClass == AcObjectClass.Lockpick) + if (wo.ObjectClass == AcObjectClass.Lockpick || (wo.ObjectClass == AcObjectClass.Key && _p.IsLockpickObject(wo))) return new ChestTool(wo.Id, wo.Name); return null; } @@ -287,6 +285,30 @@ public sealed partial class RynthAiPlugin return NearbyChestLooter.ChestRefusal(cls, bfKnown, bf, houseOwner, name, ownKnown, container, wielder); } + /// + /// The carried keys, one per name, for a locked chest (Loot Nearby Chests) or door (Auto-Unlock Doors). + /// AC gives lockpicks the key item type too, so those are left out (). + /// + private List CarriedKeys() + { + var keys = new List(); + var names = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var wo in NearbyCarried()) + if (wo.ObjectClass == AcObjectClass.Key && !IsLockpickObject(wo) && names.Add(wo.Name)) + keys.Add(wo); + return keys; + } + + private const uint BitfieldLockpick = 0x20000; // PublicWeenieDesc BF_LOCKPICK + + /// A lockpick: BF_LOCKPICK when the bitfield reads, else "lockpick" in its name. + private bool IsLockpickObject(WorldObject wo) + { + if (Host.HasGetObjectBitfield && Host.TryGetObjectBitfield(unchecked((uint)wo.Id), out uint bf) && (bf & BitfieldLockpick) != 0) + return true; + return (wo.Name ?? string.Empty).IndexOf("lockpick", StringComparison.OrdinalIgnoreCase) >= 0; + } + /// What the character carries (the pack walk, else the cache's inventory). private IEnumerable NearbyCarried() { diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.OwnCorpse.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.OwnCorpse.cs index 293ad6d..aaccd83 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.OwnCorpse.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.OwnCorpse.cs @@ -208,6 +208,10 @@ public sealed partial class RynthAiPlugin if (_busyCount > 0 && _lastLootActionAt != 0 && now - _lastLootActionAt < OwnCorpseBusyWaitMs) return; + // A full main pack: one item goes to a side pack first (the client loots only into the main pack). + if (HoldForLootRoom(next.Id, string.IsNullOrWhiteSpace(next.Name) ? $"0x{(uint)next.Id:X8}" : next.Name)) + return; + // Still animating: right after a pickup's answer that is its Return, and ACE queues one // move that arrives then (see TickOpenCorpseLooting); anything else, wait. bool pipelined = false; @@ -227,7 +231,7 @@ public sealed partial class RynthAiPlugin int errSeqAtSend = LastWeenieErrorSeq(); bool stackable = IsStackAtSend(next.Id); LootPickupResult pickup = SendLootPickup(next.Id, name, corpseId); - if (pickup == LootPickupResult.NoRoom || pickup == LootPickupResult.Refused) + if (pickup is LootPickupResult.NoRoom or LootPickupResult.Refused or LootPickupResult.MainPackFull) return; // SendLootPickup paused the corpse / left the item if (pickup != LootPickupResult.Moved && pickup != LootPickupResult.Used) { diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ProfileFiles.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ProfileFiles.cs index b131a5a..71b7490 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ProfileFiles.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ProfileFiles.cs @@ -80,6 +80,10 @@ public sealed partial class RynthAiPlugin } case ProfileVerb.Folder: return dash.OpenProfileFolder(kind); + case ProfileVerb.ClearMonsters: + return kind == ProfileKind.Settings + ? dash.ClearMonsterRules() + : ProfileResult.Failed("Only a settings profile has a Monsters list."); default: return OpenProfileEditor(kind); } @@ -139,7 +143,8 @@ public sealed partial class RynthAiPlugin case "delete": verb = ProfileVerb.Delete; break; case "folder": verb = ProfileVerb.Folder; break; case "save" when kind is ProfileKind.Meta or ProfileKind.Settings: verb = ProfileVerb.Save; break; - case "new" when kind is ProfileKind.Nav or ProfileKind.Loot: verb = ProfileVerb.New; break; + // /ra settings new : a fresh settings profile (saveas makes a copy; 2026-11-27). + case "new" when kind is ProfileKind.Nav or ProfileKind.Loot or ProfileKind.Settings: verb = ProfileVerb.New; break; case "edit" when kind == ProfileKind.Loot: verb = ProfileVerb.Edit; break; default: return false; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.WalkTrip.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.WalkTrip.cs new file mode 100644 index 0000000..2c81d3c --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.WalkTrip.cs @@ -0,0 +1,111 @@ +using System; +using RynthCore.Plugin.RynthAi.LegacyUi; + +namespace RynthCore.Plugin.RynthAi; + +/// +/// A walk-only trip (2026-11-27): "/ra dunnav-to ... walkonly". RynthAi's navigation only walks while the macro +/// runs, so the trip turns the macro on with fighting, looting, buffing and the meta OFF, and puts those four +/// switches (and the macro, when it was off) back exactly as they were when the trip ends: arrived, the macro +/// stopped, nav turned off, another route loaded, or the character left the dungeon. RynthNav's go to someone +/// inside a dungeon hands its last stretch over this way unless "Fight on the way in" is on (RynthNav insideFight). +/// Heals still run (a vital recharge isn't buffing). Tick thread, like the dungeon walks. +/// +public sealed partial class RynthAiPlugin +{ + internal sealed class WalkOnlyTrip + { + public NavRouteParser Route = new(); + public string Label = ""; + public uint Landblock; + public bool Combat, Looting, Buffing, Meta, MacroWasOn; + } + + private WalkOnlyTrip? _walkTrip; + + internal const string WalkOnlyWord = "walkonly"; + + /// Starts the trip: the player's switches remembered, then fighting, looting, buffing and the meta off. + /// Call before the macro is switched on, so the macro's state remembered is the player's. + private void BeginWalkTrip(LegacyUiSettings s, NavRouteParser route, uint landblock, string label) + { + // A trip over a trip: the player's switches and macro from before the first, not the first trip's offs. + bool macroWasOn = s.IsMacroRunning; + if (_walkTrip != null) { macroWasOn = _walkTrip.MacroWasOn; RestoreWalkTripSwitches(s, _walkTrip); _walkTrip = null; } + _walkTrip = new WalkOnlyTrip + { + Route = route, Label = label, Landblock = landblock, + Combat = s.EnableCombat, Looting = s.EnableLooting, Buffing = s.EnableBuffing, Meta = s.EnableMeta, + MacroWasOn = macroWasOn, + }; + s.EnableCombat = false; + s.EnableLooting = false; + s.EnableBuffing = false; + s.EnableMeta = false; + Host.Log($"[RynthAi] Walk-only trip to {label}: combat {TripOn(_walkTrip.Combat)}, looting {TripOn(_walkTrip.Looting)}, buffing {TripOn(_walkTrip.Buffing)}, meta {TripOn(_walkTrip.Meta)}, macro {TripOn(_walkTrip.MacroWasOn)} remembered; all off for the walk."); + } + + /// Why the trip is over, or null while it carries on. Host-free. + internal static string? WalkTripEndReason(LegacyUiSettings s, WalkOnlyTrip t, bool havePose, uint landblock) + { + if (!ReferenceEquals(s.CurrentRoute, t.Route)) return "another route was loaded"; + if (s.NavRouteFinished()) return "arrived"; + if (!s.IsMacroRunning) return "the macro was stopped"; + if (!s.EnableNavigation) return "navigation was turned off"; + if (havePose && landblock != t.Landblock) return "you left the dungeon"; + return null; + } + + /// The trip's end, once a tick (no-op unless one runs). + private void TickWalkTrip() + { + var t = _walkTrip; + var s = _dashboard?.Settings; + if (t == null || s == null) return; + uint cell = 0; + bool pose = Host.HasGetPlayerPose && Host.TryGetPlayerPose(out cell, out _, out _, out _, out _, out _, out _, out _); + string? why = WalkTripEndReason(s, t, pose, cell >> 16); + if (why == null) return; + // Someone else's route now (a meta, a script, the player): the macro is theirs; only the switches go back. + EndWalkTrip(s, why, stopMacro: why != "another route was loaded"); + } + + /// Puts the remembered switches back; the macro goes off again when it was off before the trip. + private void EndWalkTrip(LegacyUiSettings s, string why, bool stopMacro) + { + var t = _walkTrip; + if (t == null) return; + _walkTrip = null; + RestoreWalkTripSwitches(s, t); + bool stopped = false; + if (stopMacro && !t.MacroWasOn && s.IsMacroRunning) + { + s.SetMacroRunning(false, "the walk-only trip's end (the macro was off before it)"); + _navigationEngine?.Stop(); + stopped = true; + } + string line = $"[RynthAi] Walk-only trip to {t.Label} ended ({why}): combat {TripOn(t.Combat)}, looting {TripOn(t.Looting)}, buffing {TripOn(t.Buffing)}, meta {TripOn(t.Meta)} as before" + + (stopped ? ", macro off again." : "."); + Host.Log(line); + ChatLine(line); + } + + /// Shutdown / logout: the switches back before the profile is saved, quietly. + private void ForgetWalkTrip() + { + var t = _walkTrip; + var s = _dashboard?.Settings; + _walkTrip = null; + if (t != null && s != null) RestoreWalkTripSwitches(s, t); + } + + private static void RestoreWalkTripSwitches(LegacyUiSettings s, WalkOnlyTrip t) + { + s.EnableCombat = t.Combat; + s.EnableLooting = t.Looting; + s.EnableBuffing = t.Buffing; + s.EnableMeta = t.Meta; + } + + private static string TripOn(bool b) => b ? "on" : "off"; +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs index 1cfa258..d726072 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs @@ -187,7 +187,10 @@ 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 the target looked at and handed back ("You allow X to examine your Y.": ACE's Refuse emote, + // e.g. an NPC that stamps a parchment). An answer, so no re-send; counted apart from items given. + private int _giveRunShown; private int _giveChatVerdict; // a GiveChat, handed from OnChatWindowText to the tick with Interlocked private string _giveChatLine = string.Empty; private bool _giveSawAcceptLine; @@ -312,6 +315,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase public override void Shutdown() { long t0 = Environment.TickCount64; + try { ForgetWalkTrip(); } catch { } // a walk-only trip's switches back before they're saved try { _dashboard?.SaveSettings(); } catch { } try { _sessionStats?.Shutdown(); } catch { } try { ShutdownMonsterStats(); } catch { } // kept for the next copy, with the session @@ -372,6 +376,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase public override void OnLogout() { Log("RynthAi: logout — tearing down session."); + try { ForgetWalkTrip(); } catch { } // a walk-only trip's switches back before they're saved try { _dashboard?.SaveSettings(); } catch { } try { _sessionStats?.OnLogout(); } catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "session stats logout"); } try { OnLogoutMonsterStats(); } catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "monster stats logout"); } @@ -753,7 +758,9 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _weaponSwapGate.ServerIdle = () => RynthCore.Plugin.Shared.ActionPacer.Enabled && RynthCore.Plugin.Shared.ActionPacer.Current(Host) == null; _weaponSwapGate.IsWielded = id => RynthCore.Plugin.Shared.ActionPacer.IsWieldedByPlayer(Host, unchecked((uint)id)); + _castWarning = new Huds.CastWarningHud(() => _dashboard?.Settings?.ShowNoComponentsWarning != false); _buffManager = new BuffManager(Host, _dashboard.Settings, _spellManager, _vitals); + _buffManager.NoComponentsWarning = (spell, next) => _castWarning?.Post(spell, next); // 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 = () => @@ -803,6 +810,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _currentCombatMode = Host.GetCurrentCombatMode(); _combatManager = new CombatManager(Host, _dashboard.Settings, _objectCache!, _spellManager); + _combatManager.NoComponentsWarning = (spell, next) => _castWarning?.Post(spell, next); _combatManager.SetWeaponSwapGate(_weaponSwapGate); _combatManager.Vitals = _vitals; // the script hook's request carries the player's vitals _combatManager.HoldIdlePeace = LootHoldsIdlePeace; @@ -855,6 +863,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _fellowshipTracker?.Dispose(); _fellowshipTracker = new FellowshipTracker(); + if (_buffManager != null) _buffManager.InFellowship = () => _fellowshipTracker?.IsInFellowship == true; _dashboard?.SetFellowshipTracker(_fellowshipTracker); _questTracker = new QuestTracker(Host); @@ -1895,6 +1904,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase TickDunExplore(); // Outdoor hunting's next walk (no-op unless /ra hunt is on). TickOutdoorHunt(); + // A walk-only trip's end: the switches put back (no-op unless one runs; RynthAiPlugin.WalkTrip.cs). + TickWalkTrip(); }); // ── Activity arbiter — STEP 5: AUTHORITATIVE, full stop ── @@ -2452,6 +2463,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. @@ -3770,6 +3783,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase Interlocked.Exchange(ref _giveChatVerdict, 0); _giveRunActive = false; _giveRunItems = 0; + _giveRunShown = 0; _giveRunSkips.Clear(); } @@ -3781,6 +3795,9 @@ public sealed partial class RynthAiPlugin : RynthPluginBase private static GiveChat ClassifyGiveChat(string text) { string t = text.ToLowerInvariant(); + // "You allow to examine your .": the give reached the target, whose Refuse emote ran + // and left the item with you. An answer, not silence (a re-send would run the emote again). + if (t.StartsWith("you allow ", StringComparison.Ordinal) && t.Contains(" to examine your ")) return GiveChat.Examined; // Busy class first: " 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; @@ -3874,6 +3891,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _giveRunStartAt = now; _giveRunLastAnswerAt = now; _giveRunItems = 0; + _giveRunShown = 0; _giveRunSkips.Clear(); } if (!SendGive(itemId, targetId, amount, 1, resent: false, now)) @@ -3959,6 +3977,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 (looked at and handed back)"); + _giveRunShown++; + CompleteGiveStack(0, now); + return true; + } if (chat == GiveChat.Permanent) { Host.Log($"[RynthAi] Give answer: permanent {tag} '{_giveChatLine}' after {sinceSend} ms"); @@ -4090,10 +4115,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(); } diff --git a/Plugins/RynthCore.Plugin.RynthDefective/Appraisal/AppraisalText.cs b/Plugins/RynthCore.Plugin.RynthDefective/Appraisal/AppraisalText.cs new file mode 100644 index 0000000..abfb9f8 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthDefective/Appraisal/AppraisalText.cs @@ -0,0 +1,643 @@ +// ============================================================================ +// RynthDefective - Appraisal/AppraisalText.cs +// What the Appraisal window says about an object (2026-11-28: all the data, +// roughly in the retail layout): the retail examine panel's +// lines in its order and words where retail has them ("Value:", "Damage: +// 25 - 50, Slashing", "Bonus to Melee Defense: +15%.", "Spellcraft: 400.", +// "Wield requires Heavy Weapons 400", ...), grouped under small headings, and +// every property the engine holds at the end (the "All properties" list). +// +// Pure: an AppraisalInput (the engine's ObjectProperties dictionaries, the +// creature's vitals and attributes, a spell name lookup) in, an AppraisalDoc +// out. The tests run it (Tools/RynthDefective.Tests). +// +// Property ids are ACE's (PropertyInt/Float/String/Bool/DataId); the name +// tables are RynthAi's (MagItemInfoTables, PropertyNames, linked in). +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text; +using RynthCore.Plugin.RynthAi.ItemInfo; +using RynthCore.Plugin.RynthAi.Meta; + +namespace RynthCore.Plugin.RynthDefective.Appraisal; + +/// How a line is coloured. +internal enum AppraiseTone { Text, Dim, Good, Bad, Magic, Gold } + +internal readonly record struct AppraiseLine(string Text, AppraiseTone Tone = AppraiseTone.Text); + +internal sealed class AppraiseSection +{ + public AppraiseSection(string title) { Title = title; } + public string Title { get; } + public List Lines { get; } = new(); + public void Add(string text, AppraiseTone tone = AppraiseTone.Text) { if (text.Length > 0) Lines.Add(new AppraiseLine(text, tone)); } +} + +/// A bar under the name: a creature's Health / Stamina / Mana, an item's mana. Max 0 = only the ratio is known. +internal readonly record struct AppraiseBar(string Label, uint Current, uint Max, float Ratio, AppraiseBarKind Kind); +internal enum AppraiseBarKind { Health, Stamina, Mana } + +/// One raw property for the "All properties" list. +internal readonly record struct AppraiseRaw(string Kind, uint Key, string Name, string Value); + +internal sealed class AppraisalDoc +{ + public uint Id { get; init; } + public string Name { get; init; } = string.Empty; + /// What it is, under the name: "Heavy Weapons (Sword)", "Level 112 Olthoi", "Jewelry". + public string Kind { get; init; } = string.Empty; + /// The short facts beside the picture: Value, Burden, a stack, uses. + public List<(string Label, string Value)> Facts { get; } = new(); + public List Bars { get; } = new(); + /// A creature's six attributes (Strength .. Self), when assessed; empty otherwise. + public List<(string Label, uint Value, bool Buffed, bool Up)> Attributes { get; } = new(); + public List Sections { get; } = new(); + public string Description { get; init; } = string.Empty; + public List Raw { get; } = new(); + public bool Identified { get; init; } + public bool IsCreature { get; init; } + + /// The whole appraisal as text (the window's Copy). + public string ToText() + { + var sb = new StringBuilder(); + sb.AppendLine(Name); + if (Kind.Length > 0) sb.AppendLine(Kind); + foreach (var (label, value) in Facts) sb.AppendLine(label + ": " + value); + foreach (var b in Bars) + sb.AppendLine(b.Max > 0 ? $"{b.Label}: {b.Current:N0} / {b.Max:N0}" : $"{b.Label}: {MathF.Round(b.Ratio * 100f):0}%"); + foreach (var a in Attributes) sb.AppendLine($"{a.Label}: {a.Value}"); + foreach (var s in Sections) + { + sb.AppendLine().AppendLine(s.Title); + foreach (var l in s.Lines) sb.AppendLine(" " + l.Text); + } + if (Description.Length > 0) sb.AppendLine().AppendLine(Description); + return sb.ToString(); + } +} + +/// What the builder reads: the engine's view of the object. +internal sealed class AppraisalInput +{ + public uint Id; + public string Name = string.Empty; + /// The ItemType flags (TryGetItemType) when the properties have none. + public uint ItemType; + public bool Identified; + public bool IsPlayer; + public Dictionary Ints = new(); + public Dictionary Int64s = new(); + public Dictionary Bools = new(); + public Dictionary Floats = new(); + public Dictionary Strings = new(); + public Dictionary DataIds = new(); + public Dictionary InstanceIds = new(); + public List Spells = new(); + /// Health, Stamina, Mana (current, max) from the last assess; null none. + public (uint H, uint HMax, uint S, uint SMax, uint M, uint MMax)? Vitals; + /// The server's last health ratio for it, -1 none. + public float HealthRatio = -1f; + /// Strength, Endurance, Quickness, Coordination, Focus, Self; null not assessed. + public uint[]? Attributes; + public uint EnchantBits; + public Func SpellName = id => "Spell " + id.ToString(CultureInfo.InvariantCulture); +} + +internal static class AppraisalText +{ + // ── ACE property ids ───────────────────────────────────────────────────── + private const uint IItemType = 1, ICreatureType = 2, IClothingPriority = 4, IBurden = 5, IItemsCapacity = 6, + IContainersCapacity = 7, IValidLocations = 9, IMaxStack = 11, IStack = 12, IRareId = 17, IValue = 19, ILevel = 25, + IArmorLevel = 28, IAllegianceRank = 30, IBonded = 33, IResistMagic = 36, INumDeaths = 43, IDamage = 44, + IDamageType = 45, IWeaponSkill = 48, IWeaponTime = 49, IAmmoType = 50, IMinLevel = 86, IMaxLevel = 87, + ILockpickMod = 88, IBoostValue = 90, IMaxStructure = 91, IStructure = 92, IWorkmanship = 105, ISpellcraft = 106, + ICurMana = 107, IMaxMana = 108, IArcaneLore = 109, IAllegianceRankLimit = 110, IGender = 113, IAttuned = 114, + ISkillLevelLimit = 115, IMaterial = 131, IPkStatus = 134, ISlayerType = 166, INumItemsInMaterial = 170, + ITinkered = 171, IImbued = 179, IHeritage = 188, IElementalBonus = 204, ISet = 265, IRemainingLifespan = 268, + IUnique = 279, ICleaving = 292, IItemMaxLevel = 319, IWeaponType = 353, IUseRequiresLevel = 369; + private static readonly uint[] WieldReq = { 158, 270, 273, 276 }, WieldSkill = { 159, 271, 274, 277 }, WieldDiff = { 160, 272, 275, 278 }; + private static readonly uint[] MoreImbues = { 303, 304, 305, 306 }; + + private const uint FManaRate = 5, FDamageVariance = 22, FWeaponDefense = 29, FWeaponOffense = 62, FDamageMod = 63, + FHealkitMod = 100, FSlayerBonus = 138, FManaConversion = 144, FMissileDefense = 149, FMagicDefense = 150, + FElementalMod = 152, FArmorVsNether = 165; + private static readonly (uint Key, string Name)[] ArmorMods = + { + (13, "Slashing"), (14, "Piercing"), (15, "Bludgeoning"), (16, "Cold"), (17, "Fire"), (18, "Acid"), (19, "Electric"), (FArmorVsNether, "Nether"), + }; + + private const uint SName = 1, STitle = 2, STemplate = 5, SInscription = 7, SScribe = 8, SFellowship = 10, SMonarch = 11, + SUse = 14, SShortDesc = 15, SLongDesc = 16, SCraftsman = 25, SPortalDest = 38, STinker = 39, SImbuer = 40, + SDateOfBirth = 43, SAllegiance = 47, SPlating = 52; + private const uint BRetained = 91, BIvoryable = 99, BDyable = 100, BUnlimitedUse = 63, BLocked = 3, BInscribable = 22; + private const uint DSpell = 28, DSkillLimit = 37, DSpecializedOnly = 41, DProcSpell = 55; + + private const uint TypeMelee = 0x1, TypeArmor = 0x2, TypeClothing = 0x4, TypeJewelry = 0x8, TypeCreature = 0x10, + TypeMissile = 0x100, TypeContainer = 0x200, TypeCaster = 0x8000, TypePortal = 0x10000, TypeManaStone = 0x80000; + + private static readonly CultureInfo Inv = CultureInfo.InvariantCulture; + + public static AppraisalDoc Build(AppraisalInput o) + { + int type = I(o, IItemType, (int)o.ItemType); + uint t = unchecked((uint)type); + bool creature = (t & TypeCreature) != 0 || o.IsPlayer || o.Attributes != null || o.Vitals != null; + string name = S(o, SName, o.Name); + if (name.Length == 0) name = $"0x{o.Id:X8}"; + + var doc = new AppraisalDoc + { + Id = o.Id, + Name = name, + Kind = creature ? CreatureKind(o) : ItemKind(o, t), + Description = S(o, SLongDesc, S(o, SShortDesc, "")), + Identified = o.Identified, + IsCreature = creature, + }; + + if (creature) CreatureBody(o, doc); + else ItemBody(o, t, doc); + + Raw(o, doc); + return doc; + } + + // ── Creatures and players ───────────────────────────────────────────────── + + private static string CreatureKind(AppraisalInput o) + { + var parts = new List(3); + int level = I(o, ILevel, 0); + if (level > 0) parts.Add("Level " + level.ToString(Inv)); + if (o.IsPlayer) + { + string heritage = Heritage(I(o, IHeritage, 0)); + string gender = I(o, IGender, 0) switch { 1 => "Male", 2 => "Female", _ => "" }; + string who = (heritage + " " + gender).Trim(); + if (who.Length > 0) parts.Add(who); + } + else if (MagItemInfoTables.CreatureTypeName(I(o, ICreatureType, 0)) is { } kind) parts.Add(kind); + return string.Join(" · ", parts); + } + + private static readonly string[] AttributeNames = { "Strength", "Endurance", "Quickness", "Coordination", "Focus", "Self" }; + + private static void CreatureBody(AppraisalInput o, AppraisalDoc doc) + { + if (o.Vitals is { } v && v.HMax > 0) + { + doc.Bars.Add(new AppraiseBar("Health", v.H, v.HMax, Ratio(v.H, v.HMax, o.HealthRatio), AppraiseBarKind.Health)); + if (v.SMax > 0) doc.Bars.Add(new AppraiseBar("Stamina", v.S, v.SMax, v.S / (float)v.SMax, AppraiseBarKind.Stamina)); + if (v.MMax > 0) doc.Bars.Add(new AppraiseBar("Mana", v.M, v.MMax, v.M / (float)v.MMax, AppraiseBarKind.Mana)); + } + else if (o.HealthRatio >= 0f) + doc.Bars.Add(new AppraiseBar("Health", 0, 0, o.HealthRatio, AppraiseBarKind.Health)); + + if (o.Attributes is { Length: >= 6 } a) + for (int i = 0; i < 6; i++) + { + bool buffed = (o.EnchantBits & (1u << i)) != 0, up = (o.EnchantBits & (1u << (16 + i))) != 0; + doc.Attributes.Add((AttributeNames[i], a[i], buffed, up)); + } + + var who = new AppraiseSection(o.IsPlayer ? "Character" : "Creature"); + if (o.IsPlayer) + { + who.Add(S(o, STitle, "") is { Length: > 0 } title ? "Title: " + title : ""); + who.Add(S(o, STemplate, "") is { Length: > 0 } tpl ? "Template: " + tpl : ""); + who.Add(PkStatus(I(o, IPkStatus, 0))); + who.Add(S(o, SAllegiance, "") is { Length: > 0 } al ? "Allegiance: " + al : ""); + who.Add(S(o, SMonarch, "") is { Length: > 0 } mon ? "Monarch: " + mon : ""); + who.Add(I(o, IAllegianceRank, 0) is > 0 and var rank ? "Rank: " + rank.ToString(Inv) : ""); + who.Add(S(o, SFellowship, "") is { Length: > 0 } fel ? "Fellowship: " + fel : ""); + who.Add(I(o, INumDeaths, 0) is > 0 and var deaths ? "Deaths: " + deaths.ToString("N0", Inv) : "", AppraiseTone.Dim); + who.Add(S(o, SDateOfBirth, "") is { Length: > 0 } dob ? "Born: " + dob : "", AppraiseTone.Dim); + } + else + { + if (MagItemInfoTables.CreatureTypeName(I(o, ICreatureType, 0)) is { } kind) who.Add("Type: " + kind); + if (o.Attributes == null && o.Identified) + who.Add("Your assess failed: only its health is known.", AppraiseTone.Dim); + } + if (who.Lines.Count > 0) doc.Sections.Add(who); + if (!o.Identified) + doc.Sections.Add(Note("Not assessed yet: asked the server.")); + } + + // ── Items ───────────────────────────────────────────────────────────────── + + private static string ItemKind(AppraisalInput o, uint t) + { + if ((t & (TypeMelee | TypeMissile | TypeCaster)) != 0) + { + string skill = Skill(I(o, IWeaponSkill, 0)); + string mastery = MagItemInfoTables.Masteries.TryGetValue(I(o, IWeaponType, 0), out string? m) ? m : ""; + if ((t & TypeCaster) != 0) return "Caster" + (mastery.Length > 0 && mastery != "Wand" ? " (" + mastery + ")" : ""); + if (skill.Length > 0) return mastery.Length > 0 ? $"{skill} ({mastery})" : skill; + return (t & TypeMissile) != 0 ? "Missile weapon" : "Melee weapon"; + } + if ((t & TypeArmor) != 0) return (I(o, IValidLocations, 0) & 0x200000) != 0 ? "Shield" : "Armor"; + if ((t & TypeClothing) != 0) return "Clothing"; + if ((t & TypeJewelry) != 0) return "Jewelry"; + if ((t & TypePortal) != 0) return "Portal"; + if ((t & TypeContainer) != 0) return "Container"; + if ((t & TypeManaStone) != 0) return "Mana stone"; + return MagItemInfoTables.Materials.TryGetValue(I(o, IMaterial, 0), out string? mat) && I(o, INumItemsInMaterial, 0) > 0 + ? "Salvage (" + mat + ")" : ""; + } + + private static void ItemBody(AppraisalInput o, uint t, AppraisalDoc doc) + { + // The facts beside the picture. + if (Has(o, IValue)) doc.Facts.Add(("Value", I(o, IValue, 0).ToString("N0", Inv))); + if (Has(o, IBurden)) doc.Facts.Add(("Burden", I(o, IBurden, 0).ToString("N0", Inv))); + int stack = I(o, IStack, 0), maxStack = I(o, IMaxStack, 0); + if (stack > 1 || maxStack > 1) doc.Facts.Add(("Stack", maxStack > 1 ? $"{stack:N0} / {maxStack:N0}" : stack.ToString("N0", Inv))); + int uses = I(o, IStructure, -1), maxUses = I(o, IMaxStructure, 0); + if (maxUses > 0 && uses >= 0) doc.Facts.Add(("Uses", $"{uses:N0} / {maxUses:N0}")); + else if (B(o, BUnlimitedUse)) doc.Facts.Add(("Uses", "unlimited")); + + int maxMana = I(o, IMaxMana, 0); + if (maxMana > 0) + { + int cur = Math.Clamp(I(o, ICurMana, 0), 0, maxMana); + doc.Bars.Add(new AppraiseBar("Mana", (uint)cur, (uint)maxMana, cur / (float)maxMana, AppraiseBarKind.Mana)); + } + + Combat(o, t, doc); + Armor(o, t, doc); + Magic(o, doc); + Requirements(o, doc); + Properties(o, doc); + + if (!o.Identified) + doc.Sections.Add(Note("Not appraised yet: asked the server. Only what the client saw is shown.")); + } + + private static void Combat(AppraisalInput o, uint t, AppraisalDoc doc) + { + bool melee = (t & TypeMelee) != 0, missile = (t & TypeMissile) != 0, caster = (t & TypeCaster) != 0; + bool anyDefense = HasF(o, FWeaponDefense) || HasF(o, FMissileDefense) || HasF(o, FMagicDefense); + if (!melee && !missile && !caster && !anyDefense) return; + var s = new AppraiseSection(caster ? "Caster" : "Weapon"); + + string skill = Skill(I(o, IWeaponSkill, 0)); + if (skill.Length > 0 && !caster) + { + string mastery = MagItemInfoTables.Masteries.TryGetValue(I(o, IWeaponType, 0), out string? m) ? " (" + m + ")" : ""; + s.Add("Skill: " + skill + mastery); + } + + string dtype = DamageTypes(I(o, IDamageType, 0)); + if (melee && Has(o, IDamage)) + { + double max = I(o, IDamage, 0), variance = F(o, FDamageVariance, 0); + double min = max * (1 - variance); + s.Add($"Damage: {Num(min)} - {Num(max)}{(dtype.Length > 0 ? ", " + dtype : "")}"); + } + if (missile) + { + if (HasF(o, FDamageMod)) s.Add($"Damage Modifier: {Pct(F(o, FDamageMod, 1) - 1)}."); + if (I(o, IElementalBonus, 0) is > 0 and var eb) s.Add($"Elemental Damage Bonus: {eb.ToString(Inv)}{(dtype.Length > 0 ? ", " + dtype : "")}."); + string ammo = I(o, IAmmoType, 0) switch { 1 => "arrows", 2 => "quarrels", 4 => "atlatl darts", _ => "" }; + if (ammo.Length > 0) s.Add($"Uses {ammo} as ammunition.", AppraiseTone.Dim); + } + if ((melee || missile) && Has(o, IWeaponTime)) + { + int speed = I(o, IWeaponTime, 0); + s.Add($"Speed: {SpeedName(speed)} ({speed.ToString(Inv)})"); + } + if (HasF(o, FWeaponOffense) && Math.Abs(F(o, FWeaponOffense, 1) - 1) > 1e-6) + s.Add($"Bonus to Attack Skill: {Pct(F(o, FWeaponOffense, 1) - 1)}.", AppraiseTone.Good); + if (caster && HasF(o, FManaConversion) && F(o, FManaConversion, 0) > 1e-6) + s.Add($"Bonus to Mana Conversion: {Pct(F(o, FManaConversion, 0))}.", AppraiseTone.Good); + if (caster && HasF(o, FElementalMod) && F(o, FElementalMod, 1) > 1 + 1e-6) + { + double b = F(o, FElementalMod, 1) - 1; + string element = dtype.Length > 0 ? dtype : "all"; + s.Add($"Damage bonus for {element} spells: {Pct(b)} vs. Monsters, {Pct(b / 4)} vs. Players.", AppraiseTone.Good); + } + if (HasF(o, FWeaponDefense) && Math.Abs(F(o, FWeaponDefense, 1) - 1) > 1e-6) + s.Add($"Bonus to Melee Defense: {Pct(F(o, FWeaponDefense, 1) - 1)}.", AppraiseTone.Good); + if (HasF(o, FMissileDefense) && Math.Abs(F(o, FMissileDefense, 1) - 1) > 1e-6) + s.Add($"Bonus to Missile Defense: {Pct(F(o, FMissileDefense, 1) - 1)}.", AppraiseTone.Good); + if (HasF(o, FMagicDefense) && Math.Abs(F(o, FMagicDefense, 1) - 1) > 1e-6) + s.Add($"Bonus to Magic Defense: {Pct(F(o, FMagicDefense, 1) - 1)}.", AppraiseTone.Good); + + if (MagItemInfoTables.CreatureTypeName(I(o, ISlayerType, 0)) is { } slayer) + s.Add($"Slayer: {slayer}{(HasF(o, FSlayerBonus) ? $" (x{F(o, FSlayerBonus, 1).ToString("0.##", Inv)} damage)" : "")}", AppraiseTone.Good); + if (I(o, ICleaving, 0) is > 1 and var cleave) s.Add($"Cleaving: hits up to {cleave.ToString(Inv)} enemies.", AppraiseTone.Good); + + string imbues = Imbues(o); + if (imbues.Length > 0) s.Add("Imbued: " + imbues, AppraiseTone.Good); + + if (s.Lines.Count > 0) doc.Sections.Add(s); + } + + private static void Armor(AppraisalInput o, uint t, AppraisalDoc doc) + { + if (!Has(o, IArmorLevel) && (t & (TypeArmor | TypeClothing)) == 0) return; + var s = new AppraiseSection("Armor"); + int al = I(o, IArmorLevel, 0); + if (Has(o, IArmorLevel)) s.Add("Armor Level: " + al.ToString("N0", Inv)); + if (al > 0) + foreach (var (key, label) in ArmorMods) + { + if (!HasF(o, key)) continue; + double mod = F(o, key, 1); + s.Add($"{label}: {ProtectionName(mod)} ({Math.Round(al * mod).ToString("N0", Inv)})", mod >= 1.2 ? AppraiseTone.Good : mod < 0.8 ? AppraiseTone.Bad : AppraiseTone.Text); + } + string covers = Coverage(I(o, IClothingPriority, 0)); + if (covers.Length > 0) s.Add("Covers: " + covers, AppraiseTone.Dim); + if (s.Lines.Count > 0) doc.Sections.Add(s); + } + + private static void Magic(AppraisalInput o, AppraisalDoc doc) + { + var s = new AppraiseSection("Magic"); + if (o.Spells.Count > 0) + { + var names = new List(o.Spells.Count); + foreach (uint id in o.Spells) names.Add(o.SpellName(id)); + s.Add("Spells: " + string.Join(", ", names), AppraiseTone.Magic); + } + if (o.DataIds.TryGetValue(DSpell, out uint spell) && spell != 0 && !o.Spells.Contains(spell)) + s.Add("Spell: " + o.SpellName(spell), AppraiseTone.Magic); + if (o.DataIds.TryGetValue(DProcSpell, out uint proc) && proc != 0) + s.Add("Casts on a hit: " + o.SpellName(proc), AppraiseTone.Magic); + int maxMana = I(o, IMaxMana, 0); + if (maxMana > 0) s.Add($"Mana: {Math.Clamp(I(o, ICurMana, 0), 0, maxMana):N0} / {maxMana:N0}"); + double rate = F(o, FManaRate, 0); + if (rate < -1e-9) + { + double seconds = -1 / rate; + s.Add($"Mana Cost: 1 point per {Num(seconds)} seconds.", AppraiseTone.Dim); + } + if (I(o, ISpellcraft, 0) is > 0 and var sc) s.Add($"Spellcraft: {sc.ToString(Inv)}."); + if (s.Lines.Count > 0) doc.Sections.Add(s); + } + + private static void Requirements(AppraisalInput o, AppraisalDoc doc) + { + var s = new AppraiseSection("Requirements"); + for (int i = 0; i < WieldReq.Length; i++) + { + int req = I(o, WieldReq[i], 0); + if (req == 0) continue; + int what = I(o, WieldSkill[i], 0), diff = I(o, WieldDiff[i], 0); + s.Add(WieldLine(req, what, diff)); + } + if (I(o, IArcaneLore, 0) is > 0 and var lore) s.Add($"Activation requires Arcane Lore: {lore.ToString(Inv)}"); + if (o.DataIds.TryGetValue(DSkillLimit, out uint sk) && sk != 0) + { + int level = I(o, ISkillLevelLimit, 0); + s.Add($"Activation requires {Skill((int)sk)}{(level > 0 ? ": " + level.ToString(Inv) : "")}"); + } + if (o.DataIds.TryGetValue(DSpecializedOnly, out uint spec) && spec != 0) + s.Add($"Activation requires specialized {Skill((int)spec)}"); + if (I(o, IAllegianceRankLimit, 0) is > 0 and var rank) s.Add($"Activation requires Allegiance Rank: {rank.ToString(Inv)}"); + if (I(o, IUseRequiresLevel, 0) is > 0 and var ul) s.Add($"Use requires level {ul.ToString(Inv)}"); + int min = I(o, IMinLevel, 0), max = I(o, IMaxLevel, 0); + if (min > 0 && max > 0) s.Add($"Restricted to characters of levels {min.ToString(Inv)} to {max.ToString(Inv)}."); + else if (min > 0) s.Add($"Restricted to characters of level {min.ToString(Inv)} or greater."); + else if (max > 0) s.Add($"Restricted to characters of level {max.ToString(Inv)} or below."); + if (S(o, SPortalDest, "") is { Length: > 0 } dest) s.Add("Destination: " + dest); + if (s.Lines.Count > 0) doc.Sections.Add(s); + } + + private static void Properties(AppraisalInput o, AppraisalDoc doc) + { + var s = new AppraiseSection("Properties"); + int work = I(o, IWorkmanship, 0), items = I(o, INumItemsInMaterial, 0); + string material = MagItemInfoTables.Materials.TryGetValue(I(o, IMaterial, 0), out string? mat) ? mat : ""; + if (work > 0 && items > 0) + s.Add($"Workmanship: {(work / (double)items).ToString("0.00", Inv)} (salvaged from {items.ToString(Inv)} item{(items == 1 ? "" : "s")})"); + else if (work > 0) s.Add($"Workmanship: {WorkmanshipName(work)} ({work.ToString(Inv)})"); + if (material.Length > 0) s.Add("Material: " + material); + if (MagItemInfoTables.EquipmentSets.TryGetValue(I(o, ISet, 0), out string? set)) s.Add("Set: " + set, AppraiseTone.Gold); + + // Ratings (gear): "Damage Rating +3". + var ratings = new List(); + foreach (var (key, label) in Ratings) + if (I(o, key, 0) is > 0 and var r) ratings.Add($"{label} +{r.ToString(Inv)}"); + if (ratings.Count > 0) s.Add("Ratings: " + string.Join(", ", ratings), AppraiseTone.Good); + + if (I(o, IItemMaxLevel, 0) is > 0 and var maxLevel) s.Add($"Item levels: up to {maxLevel.ToString(Inv)}", AppraiseTone.Dim); + if (I(o, ITinkered, 0) is > 0 and var tinkered) s.Add($"This item has been tinkered {tinkered.ToString(Inv)} time{(tinkered == 1 ? "" : "s")}."); + if (S(o, SImbuer, "") is { Length: > 0 } imbuer) s.Add("Imbued by " + imbuer + ".", AppraiseTone.Dim); + if (S(o, STinker, "") is { Length: > 0 } tinker) s.Add("Last tinkered by " + tinker + ".", AppraiseTone.Dim); + if (S(o, SCraftsman, "") is { Length: > 0 } maker) s.Add("Created by " + maker + ".", AppraiseTone.Dim); + if (S(o, SPlating, "") is { Length: > 0 } plating) s.Add("Plating: " + plating, AppraiseTone.Dim); + + var flags = new List(); + switch (I(o, IBonded, 0)) + { + case 1: flags.Add("Bonded"); break; + case -1: flags.Add("Dropped on death"); break; + case -2: flags.Add("Destroyed on death"); break; + } + if (I(o, IAttuned, 0) == 1) flags.Add("Attuned (can't be given)"); + if (B(o, BRetained)) flags.Add("Retained"); + if (I(o, IResistMagic, 0) >= 9999) flags.Add("Unenchantable"); + if (B(o, BIvoryable)) flags.Add("Ivoryable"); + if (B(o, BDyable)) flags.Add("Dyeable"); + if (B(o, BLocked)) flags.Add("Locked"); + if (B(o, BInscribable)) flags.Add("Inscribable"); + if (I(o, IUnique, 0) is > 0 and var unique) flags.Add($"Unique (carry {unique.ToString(Inv)})"); + if (flags.Count > 0) s.Add("Properties: " + string.Join(", ", flags)); + + if (I(o, IRareId, 0) is > 0 and var rare) s.Add($"Rare #{rare.ToString(Inv)}", AppraiseTone.Gold); + if (I(o, IRemainingLifespan, 0) is > 0 and var life) s.Add("Time left: " + Duration(life), AppraiseTone.Bad); + if (I(o, ILockpickMod, 0) is > 0 and var pick) s.Add($"Bonus to Lockpick Skill: +{pick.ToString(Inv)}", AppraiseTone.Good); + if (HasF(o, FHealkitMod) && F(o, FHealkitMod, 1) > 1 + 1e-6) s.Add($"Bonus to Healing Skill: {Pct(F(o, FHealkitMod, 1) - 1)}", AppraiseTone.Good); + if (I(o, IBoostValue, 0) is var boost && boost != 0) s.Add($"Restores {Math.Abs(boost).ToString("N0", Inv)} points.", AppraiseTone.Good); + if (I(o, IItemsCapacity, 0) is > 0 and var cap) + s.Add($"Holds {cap.ToString(Inv)} items{(I(o, IContainersCapacity, 0) is > 0 and var packs ? $" and {packs.ToString(Inv)} packs" : "")}.", AppraiseTone.Dim); + if (S(o, SInscription, "") is { Length: > 0 } ins) + s.Add($"Inscription: \"{ins}\"{(S(o, SScribe, "") is { Length: > 0 } scribe ? " - " + scribe : "")}", AppraiseTone.Dim); + if (S(o, SUse, "") is { Length: > 0 } use) s.Add(use, AppraiseTone.Dim); + if (s.Lines.Count > 0) doc.Sections.Add(s); + } + + private static readonly (uint Key, string Label)[] Ratings = + { + (370, "Damage"), (371, "Damage Resist"), (372, "Crit"), (373, "Crit Resist"), (374, "Crit Damage"), + (375, "Crit Damage Resist"), (376, "Healing Boost"), (377, "Nether Resist"), (378, "Life Resist"), + (379, "Max Health"), (383, "PK Damage"), (384, "PK Damage Resist"), (388, "Overpower"), (389, "Overpower Resist"), + }; + + // ── All properties ──────────────────────────────────────────────────────── + + private static void Raw(AppraisalInput o, AppraisalDoc doc) + { + foreach (var kv in Sorted(o.Ints)) doc.Raw.Add(new("Int", kv.Key, PropertyNames.GetIntName(kv.Key) ?? "?", kv.Value.ToString(Inv))); + foreach (var kv in Sorted(o.Int64s)) doc.Raw.Add(new("Int64", kv.Key, PropertyNames.GetInt64Name(kv.Key) ?? "?", kv.Value.ToString(Inv))); + foreach (var kv in Sorted(o.Floats)) doc.Raw.Add(new("Float", kv.Key, PropertyNames.GetFloatName(kv.Key) ?? "?", kv.Value.ToString("0.#####", Inv))); + foreach (var kv in Sorted(o.Bools)) doc.Raw.Add(new("Bool", kv.Key, PropertyNames.GetBoolName(kv.Key) ?? "?", kv.Value ? "true" : "false")); + foreach (var kv in Sorted(o.Strings)) doc.Raw.Add(new("String", kv.Key, PropertyNames.GetStringName(kv.Key) ?? "?", kv.Value)); + foreach (var kv in Sorted(o.DataIds)) doc.Raw.Add(new("DataId", kv.Key, PropertyNames.GetDataIdName(kv.Key) ?? "?", $"0x{kv.Value:X8}")); + foreach (var kv in Sorted(o.InstanceIds)) doc.Raw.Add(new("InstanceId", kv.Key, PropertyNames.GetInstanceIdName(kv.Key) ?? "?", $"0x{kv.Value:X8}")); + for (int i = 0; i < o.Spells.Count; i++) doc.Raw.Add(new("Spell", o.Spells[i], o.SpellName(o.Spells[i]), o.Spells[i].ToString(Inv))); + } + + private static List> Sorted(Dictionary d) + { + var l = new List>(d); + l.Sort((a, b) => a.Key.CompareTo(b.Key)); + return l; + } + + // ── Wording ─────────────────────────────────────────────────────────────── + + /// "Wield requires Heavy Weapons 400", "... Strength 200", "... level 180", "... specialized Sword", "... Aluvian race". + internal static string WieldLine(int req, int what, int diff) => req switch + { + 1 or 2 => $"Wield requires {(req == 2 ? "base " : "")}{Skill(what)} {diff.ToString(Inv)}", + 3 or 4 => $"Wield requires {(req == 4 ? "base " : "")}{Attribute(what)} {diff.ToString(Inv)}", + 5 or 6 => $"Wield requires {(req == 6 ? "base " : "")}{Vital(what)} {diff.ToString(Inv)}", + 7 => $"Wield requires level {diff.ToString(Inv)}", + 8 => $"Wield requires {(diff >= 3 ? "specialized" : "trained")} {Skill(what)}", + 11 => $"Wield requires {MagItemInfoTables.CreatureTypeName(diff) ?? "creature " + diff.ToString(Inv)} type", + 12 => $"Wield requires {Heritage(diff)} race", + _ => $"Wield requires {PropertyNames.GetIntName((uint)what) ?? "property " + what.ToString(Inv)} {diff.ToString(Inv)}", + }; + + private static string Skill(int id) => id > 0 && MagItemInfoTables.Skills.TryGetValue(id, out string? s) ? s : id > 0 ? "skill " + id.ToString(Inv) : ""; + + private static string Attribute(int id) => id switch + { + 1 => "Strength", 2 => "Endurance", 3 => "Quickness", 4 => "Coordination", 5 => "Focus", 6 => "Self", _ => "attribute " + id.ToString(Inv), + }; + + private static string Vital(int id) => id switch + { + 1 or 2 => "Health", 3 or 4 => "Stamina", 5 or 6 => "Mana", _ => "vital " + id.ToString(Inv), + }; + + private static string Heritage(int id) => id switch + { + 1 => "Aluvian", 2 => "Gharu'ndim", 3 => "Sho", 4 => "Viamontian", 5 => "Umbraen", 6 => "Gear Knight", 7 => "Tumerok", + 8 => "Lugian", 9 => "Empyrean", 10 => "Penumbraen", 11 => "Undead", 12 => "Olthoi", 13 => "Olthoi", _ => "", + }; + + private static string PkStatus(int status) => status switch + { + 0x04 => "Player Killer", + 0x40 => "PK Lite", + 0x02 or 0x01 => "Non-Player Killer", + _ => "", + }; + + internal static string SpeedName(int speed) => speed switch + { + < 11 => "Very Fast", + < 31 => "Fast", + < 50 => "Average", + < 80 => "Slow", + _ => "Very Slow", + }; + + internal static string ProtectionName(double mod) => mod switch + { + < 0.4 => "Poor", + < 0.8 => "Below Average", + < 1.2 => "Average", + < 1.6 => "Above Average", + < 2.0 => "Excellent", + _ => "Superb", + }; + + internal static string WorkmanshipName(int w) => w switch + { + 1 => "Poorly crafted", 2 => "Well-crafted", 3 => "Finely crafted", 4 => "Exquisitely crafted", 5 => "Magnificent", + 6 => "Nearly flawless", 7 => "Flawless", 8 => "Utterly flawless", 9 => "Incomparable", 10 => "Priceless", _ => "", + }; + + /// DamageType flags as retail words: "Slashing/Piercing", "Fire". + internal static string DamageTypes(int flags) + { + if (flags <= 0) return string.Empty; + var parts = new List(2); + if ((flags & 0x001) != 0) parts.Add("Slashing"); + if ((flags & 0x002) != 0) parts.Add("Piercing"); + if ((flags & 0x004) != 0) parts.Add("Bludgeoning"); + if ((flags & 0x008) != 0) parts.Add("Cold"); + if ((flags & 0x010) != 0) parts.Add("Fire"); + if ((flags & 0x020) != 0) parts.Add("Acid"); + if ((flags & 0x040) != 0) parts.Add("Electric"); + if ((flags & 0x400) != 0) parts.Add("Nether"); + return string.Join("/", parts); + } + + /// ClothingPriority (CoverageMask) as body parts, outer layers first: "Chest, Abdomen, Upper Arms". + internal static string Coverage(int mask) + { + if (mask <= 0) return string.Empty; + var parts = new List(); + void Part(int bits, string name) { if ((mask & bits) != 0 && !parts.Contains(name)) parts.Add(name); } + Part(0x4000, "Head"); + Part(0x0400 | 0x0008, "Chest"); + Part(0x0800 | 0x0010, "Abdomen"); + Part(0x1000 | 0x0020, "Upper Arms"); + Part(0x2000 | 0x0040, "Lower Arms"); + Part(0x8000, "Hands"); + Part(0x0100 | 0x0002, "Upper Legs"); + Part(0x0200 | 0x0004, "Lower Legs"); + Part(0x10000, "Feet"); + return string.Join(", ", parts); + } + + private static string Imbues(AppraisalInput o) + { + int bits = I(o, IImbued, 0); + foreach (uint k in MoreImbues) bits |= I(o, k, 0); + if (bits == 0) return string.Empty; + var parts = new List(); + void Bit(int b, string name) { if ((bits & b) != 0) parts.Add(name); } + Bit(0x1, "Critical Strike"); Bit(0x2, "Crippling Blow"); Bit(0x4, "Armor Rending"); Bit(0x8, "Slash Rending"); + Bit(0x10, "Pierce Rending"); Bit(0x20, "Bludgeon Rending"); Bit(0x40, "Acid Rending"); Bit(0x80, "Cold Rending"); + Bit(0x100, "Lightning Rending"); Bit(0x200, "Fire Rending"); Bit(0x400, "Melee Defense"); Bit(0x800, "Missile Defense"); + Bit(0x1000, "Magic Defense"); Bit(0x2000, "Spellbook"); Bit(0x4000, "Nether Rending"); + return string.Join(", ", parts); + } + + private static string Duration(int seconds) + { + var t = TimeSpan.FromSeconds(seconds); + if (t.TotalDays >= 1) return $"{(int)t.TotalDays}d {t.Hours}h"; + if (t.TotalHours >= 1) return $"{(int)t.TotalHours}h {t.Minutes}m"; + return $"{t.Minutes}m {t.Seconds}s"; + } + + private static AppraiseSection Note(string text) + { + var s = new AppraiseSection(""); + s.Add(text, AppraiseTone.Dim); + return s; + } + + private static float Ratio(uint cur, uint max, float serverRatio) => + serverRatio >= 0f ? serverRatio : max > 0 ? Math.Clamp(cur / (float)max, 0f, 1f) : 0f; + + /// A fraction as retail's signed percent: 0.12 -> "+12%", -0.05 -> "-5%", 0.0375 -> "+3.75%". + internal static string Pct(double fraction) + { + double p = fraction * 100.0; + string s = Math.Abs(p - Math.Round(p)) < 0.005 ? Math.Round(p).ToString("0", Inv) : p.ToString("0.##", Inv); + return (p >= 0 ? "+" : "") + s + "%"; + } + + private static string Num(double v) => Math.Abs(v - Math.Round(v)) < 0.05 ? Math.Round(v).ToString("0", Inv) : v.ToString("0.#", Inv); + + private static bool Has(AppraisalInput o, uint intKey) => o.Ints.ContainsKey(intKey); + private static bool HasF(AppraisalInput o, uint floatKey) => o.Floats.ContainsKey(floatKey); + private static int I(AppraisalInput o, uint key, int fallback) => o.Ints.TryGetValue(key, out int v) ? v : fallback; + private static double F(AppraisalInput o, uint key, double fallback) => o.Floats.TryGetValue(key, out double v) ? v : fallback; + private static bool B(AppraisalInput o, uint key) => o.Bools.TryGetValue(key, out bool v) && v; + private static string S(AppraisalInput o, uint key, string fallback) => o.Strings.TryGetValue(key, out string? v) && v.Length > 0 ? v : fallback; +} diff --git a/Plugins/RynthCore.Plugin.RynthDefective/Appraisal/AppraisalWindow.cs b/Plugins/RynthCore.Plugin.RynthDefective/Appraisal/AppraisalWindow.cs new file mode 100644 index 0000000..5cffbbc --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthDefective/Appraisal/AppraisalWindow.cs @@ -0,0 +1,441 @@ +// ============================================================================ +// RynthDefective - Appraisal/AppraisalWindow.cs +// The Appraisal window (2026-11-28): it stays when the bot selects another +// item and follows only the player's own clicks. Retail's examine panel, roughly: the picture, the name, what +// it is and its value and burden, the bars (a creature's health, stamina and +// mana; an item's mana), a creature's attributes, then the appraisal's lines +// under small headings, the description, and every property the engine holds +// ("All properties", folded). +// +// It shows what YOU picked (RynthDefectivePlugin.Appraisal.cs): a middle-click +// on something in the world (your selection doesn't change), or something you +// select yourself with a click. The bot's selections never change it. +// +// the title row drag to move; Ctrl+wheel: bigger or smaller (30-250%); +// right-click: the menu (copy, appraise again, select it, +// pin, all properties, hide). +// the pin pinned: your own clicks don't change it, only a middle-click. +// the square pop it out of the game window into its own window (another +// screen), or dock it back (2026-11-28); /rdef appraisal popout | dock. +// the arrows appraise it again (ask the server). +// +// AC's render thread; reads the view the tick built (AppraisalView). +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Numerics; +using ImGuiNET; +using RynthCore.Plugin.Shared; +using RynthCore.Plugin.Shared.RynthUi; +using RynthCore.PluginSdk; +using static RynthCore.Plugin.Shared.RynthUi.RynthUi; + +namespace RynthCore.Plugin.RynthDefective.Appraisal; + +/// What the window draws (built on the plugin tick). +internal sealed record AppraisalView(bool Ready, AppraisalDoc? Doc, string Source, bool Pinned, bool Gone) +{ + public static readonly AppraisalView NotReady = new(false, null, string.Empty, false, false); +} + +internal sealed class AppraisalWindow +{ + public const string Title = "Appraisal"; + + private readonly RynthCoreHost _host; + private float _k = 1f, _r = 1f; + private bool _rawOpen, _popped; + private float _bodyContentH; + + /// The menu's and chips' actions (the plugin runs them on its tick). + public Action? Refresh { get; set; } + public Action? TogglePin { get; set; } + public Action? Select { get; set; } + + public AppraisalWindow(RynthCoreHost host) { _host = host; } + + private float Px(float v) => v * _k; + private float Fs(ImFontPtr f) => f.FontSize * _r; + + private void Scale() + { + float fontK = Math.Max(0.5f, Font(RynthUiFont.Ui10).FontSize / 10f); + int pct = _host.PanelScale(Title); + _k = pct > 0 ? pct / 100f : fontK; + _r = _k / fontK; + } + + private const float Pad = 7, Icon = 40, Gap = 7, Radius = 4, ChipSize = 16, BarH = 9, MaxBodyH = 430; + + private uint _bg, _key, _inset, _line, _text, _dim, _faint, _accent, _good, _bad, _gold; + private static readonly uint HealthColor = Argb(0xFFE0564E), StaminaColor = Argb(0xFFE0B54E), ManaColor = Argb(0xFF4F8DF0), + MagicColor = Argb(0xFF9DB8F5), White = Argb(0xFFFFFFFF); + private static uint A(uint c, float alpha) => WithAlpha(c, (uint)Math.Clamp(MathF.Round(alpha * 255f), 0f, 255f)); + + /// Draws into the host's window (: its own OS window); returns the height it needs (pixels). Render thread. + public float Draw(AppraisalView v, bool popped = false) + { + _popped = popped; + Scale(); + _bg = Color(RynthUiColor.Background); + _key = Color(RynthUiColor.KeyFace); + _inset = Color(RynthUiColor.Inset); + _line = Color(RynthUiColor.Hairline); + _text = Color(RynthUiColor.Text); + _dim = Color(RynthUiColor.Muted); + _faint = Color(RynthUiColor.Faint); + _accent = Color(RynthUiColor.Accent); + _good = Color(RynthUiColor.Green); + _bad = Color(RynthUiColor.Red); + _gold = Color(RynthUiColor.Highlight); + + Vector2 origin = ImGui.GetCursorScreenPos(); + origin = new Vector2(MathF.Round(origin.X), MathF.Round(origin.Y)); + float width = MathF.Floor(ImGui.GetContentRegionAvail().X); + if (width < 80) return Px(40); + ImDrawListPtr dl = ImGui.GetWindowDrawList(); + AppraisalDoc? doc = v.Ready ? v.Doc : null; + + float pad = Px(Pad), icon = Px(Icon); + ImFontPtr nf = Font(RynthUiFont.NarrowBold13), kf = Font(RynthUiFont.Narrow10), sf = Font(RynthUiFont.Narrow9); + + // ── The header: picture, name, what it is, the facts ── + float headH = MathF.Ceiling(2 * pad + icon); + float barsH = doc == null ? 0 : doc.Bars.Count * (Px(BarH) + Px(4)); + float attrH = doc == null || doc.Attributes.Count == 0 ? 0 : 2 * (Fs(kf) + Px(3)) + Px(4); + float topH = headH + barsH + attrH; + float footH = Fs(sf) + Px(6); + + float bodyWant = doc == null ? 0 : _bodyContentH; + float bodyH = MathF.Min(bodyWant, Px(MaxBodyH)); + float total = topH + (bodyH > 0 ? bodyH + Px(2) : 0) + footH; + + Vector2 max = origin + new Vector2(width, total); + dl.AddRectFilled(origin, max, A(_bg, 0.95f), Px(Radius)); + dl.AddRect(origin, max, _line, Px(Radius)); + + float chipsW = 3 * Px(ChipSize) + 2 * Px(4); + ImGui.SetCursorScreenPos(origin); + ImGui.InvisibleButton("##appr_drag", new Vector2(Math.Max(1, width - chipsW - pad), headH)); + _host.PanelDragWithLastItem(); + if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) ImGui.OpenPopup(MenuId); + SafeImGui.SetItemTooltip(doc == null + ? "Middle-click anything in the world to appraise it here (your selection doesn't change), or select something yourself.\nThe bot's selections never change this window.\nDrag to move; Ctrl+wheel: bigger or smaller; right-click: the menu." + : $"{doc.Name}\nMiddle-click something else to appraise it; {(v.Pinned ? "pinned: your own clicks don't change it" : "your own clicks change it too")}.\nDrag to move; Ctrl+wheel: bigger or smaller; right-click: the menu."); + Menu(v); + + Vector2 ip = origin + new Vector2(pad, pad); + dl.AddRectFilled(ip, ip + new Vector2(icon, icon), doc == null ? _inset : _key, Px(3)); + IntPtr tex = doc != null ? _host.GetIconTexture(RynthIconKind.Object, doc.Id) : IntPtr.Zero; + if (tex != IntPtr.Zero) + dl.AddImageRounded(tex, ip + new Vector2(Px(3), Px(3)), ip + new Vector2(icon - Px(3), icon - Px(3)), Vector2.Zero, Vector2.One, White, Px(2)); + else if (doc == null) + DrawIcon(dl, RynthIcons.MagnifyingGlass, ip, new Vector2(icon, icon), Px(18), _faint); + dl.AddRect(ip, ip + new Vector2(icon, icon), _line, Px(3)); + + float tx = ip.X + icon + Px(Gap); + float right = origin.X + width - pad; + + // The chips: pin, pop out / dock, appraise again. + Vector2 chip = new(right - Px(ChipSize), ip.Y); + if (Chip("##appr_refresh", RynthIcons.ArrowsClockwise, chip, _faint, doc == null ? "Nothing to appraise yet." : "Appraise it again (ask the server).") && doc != null) + Refresh?.Invoke(); + chip.X -= Px(ChipSize) + Px(4); + if (Chip("##appr_popout", popped ? RynthIcons.ArrowSquareIn : RynthIcons.ArrowSquareOut, chip, _faint, + popped ? "Dock it back into the game window (/rdef appraisal dock)." + : "Pop it out of the game window into its own window: put it on another screen (/rdef appraisal popout).")) + _host.SetPanelPopOut(Title, RynthPanelPopOut.Toggle); + chip.X -= Px(ChipSize) + Px(4); + if (Chip("##appr_pin", RynthIcons.PushPin, chip, v.Pinned ? _accent : _faint, + v.Pinned ? "Pinned: only a middle-click changes this window. Click: follow your own clicks too." + : "Follows your own clicks and middle-clicks. Click: pin it (only a middle-click changes it).", v.Pinned)) + TogglePin?.Invoke(); + float textRight = chip.X - Px(6); + + if (doc == null) + { + Clip(dl, nf, Fs(nf), new Vector2(tx, ip.Y), _faint, "Appraisal", textRight - tx); + Clip(dl, kf, Fs(kf), new Vector2(tx, ip.Y + Fs(nf) + Px(2)), _faint, "Middle-click something in the world", right - tx); + Clip(dl, sf, Fs(sf), new Vector2(tx, ip.Y + icon - Fs(sf)), _faint, "or select it yourself: the bot's picks don't count", right - tx); + ImGui.SetCursorScreenPos(origin); + ImGui.Dummy(new Vector2(width, total)); + return total; + } + + Clip(dl, nf, Fs(nf), new Vector2(tx, ip.Y), v.Gone ? _faint : _text, doc.Name, textRight - tx); + float y2 = ip.Y + Fs(nf) + Px(2); + if (doc.Kind.Length > 0) Clip(dl, kf, Fs(kf), new Vector2(tx, y2), _accent, doc.Kind, right - tx); + string facts = Facts(doc); + if (facts.Length > 0) Clip(dl, sf, Fs(sf), new Vector2(tx, ip.Y + icon - Fs(sf)), _dim, facts, right - tx); + + // ── The bars ── + float y = origin.Y + headH; + foreach (AppraiseBar b in doc.Bars) + { + float lw = Px(48); + Clip(dl, sf, Fs(sf), new Vector2(origin.X + pad, y + (Px(BarH) - Fs(sf)) * 0.5f), _dim, b.Label, lw); + Vector2 b0 = new(origin.X + pad + lw, y), b1 = new(right, y + Px(BarH)); + dl.AddRectFilled(b0, b1, _inset, Px(2)); + float f = Math.Clamp(b.Ratio, 0f, 1f); + uint fill = b.Kind switch { AppraiseBarKind.Health => HealthColor, AppraiseBarKind.Stamina => StaminaColor, _ => ManaColor }; + if (f > 0f) dl.AddRectFilled(b0, new Vector2(b0.X + (b1.X - b0.X) * f, b1.Y), fill, Px(2)); + dl.AddRect(b0, b1, _line, Px(2)); + string label = (b.Max > 0 ? $"{b.Current.ToString("N0", CultureInfo.InvariantCulture)} / {b.Max.ToString("N0", CultureInfo.InvariantCulture)} " : "") + + MathF.Round(f * 100f).ToString(CultureInfo.InvariantCulture) + "%"; + float w = sf.CalcTextSizeA(Fs(sf), float.MaxValue, 0f, label).X; + if (w + Px(8) < b1.X - b0.X) + dl.AddText(sf, Fs(sf), new Vector2(MathF.Round(b1.X - w - Px(4)), MathF.Round(y + (Px(BarH) - Fs(sf)) * 0.5f)), White, label); + y += Px(BarH) + Px(4); + } + + // ── A creature's attributes: three columns, two rows ── + if (doc.Attributes.Count > 0) + { + float colW = (right - origin.X - pad) / 3f; + for (int i = 0; i < doc.Attributes.Count; i++) + { + var (label, value, buffed, up) = doc.Attributes[i]; + float cx = origin.X + pad + (i % 3) * colW, cy = y + (i / 3) * (Fs(kf) + Px(3)); + dl.AddText(kf, Fs(kf), new Vector2(cx, cy), _dim, Short(label)); + string num = value.ToString(CultureInfo.InvariantCulture); + uint c = !buffed ? _text : up ? _good : _bad; + dl.AddText(kf, Fs(kf), new Vector2(cx + Px(34), cy), c, num); + } + y += attrH; + } + + // ── The body: sections, description, every property (scrolls past MaxBodyH) ── + if (bodyWant <= 0) bodyH = Px(1); + ImGui.SetCursorScreenPos(new Vector2(origin.X + Px(1), y)); + ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, Vector2.Zero); + ImGui.PushStyleColor(ImGuiCol.ScrollbarBg, 0u); + bool child = ImGui.BeginChild("##appr_body", new Vector2(width - Px(2), Math.Max(Px(1), bodyH)), ImGuiChildFlags.None, + ImGuiWindowFlags.NoBackground | (bodyWant > Px(MaxBodyH) ? ImGuiWindowFlags.None : ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse)); + ImGui.PopStyleColor(); + ImGui.PopStyleVar(); + if (child) + { + try { _bodyContentH = Body(doc, width - Px(2) - (bodyWant > Px(MaxBodyH) ? ImGui.GetStyle().ScrollbarSize : 0)); } + finally { ImGui.EndChild(); } + } + else ImGui.EndChild(); + y += bodyH > Px(1) ? bodyH + Px(2) : 0; + + // ── The footer: how it was picked, and whether it is appraised ── + string foot = v.Source + (v.Gone ? " · no longer in view" : doc.Identified ? "" : " · not appraised yet"); + Clip(dl, sf, Fs(sf), new Vector2(origin.X + pad, origin.Y + total - footH + Px(2)), _faint, foot, width - 2 * pad); + + ImGui.SetCursorScreenPos(origin); + ImGui.Dummy(new Vector2(width, total)); + return total; + } + + /// The body's lines in the child window; returns their height. Render thread. + private float Body(AppraisalDoc doc, float width) + { + ImDrawListPtr dl = ImGui.GetWindowDrawList(); + Vector2 o = ImGui.GetCursorScreenPos(); + float pad = Px(Pad), x = o.X + pad - Px(1), wrapW = width - 2 * pad; + float y = o.Y; + ImFontPtr hf = Font(RynthUiFont.Narrow9), lf = Font(RynthUiFont.Ui10), mf = Font(RynthUiFont.Dash9); + + foreach (AppraiseSection s in doc.Sections) + { + if (s.Title.Length > 0) + { + y += Px(3); + string t = s.Title.ToUpperInvariant(); + dl.AddText(hf, Fs(hf), new Vector2(x, y), _faint, t); + float tw = hf.CalcTextSizeA(Fs(hf), float.MaxValue, 0f, t).X; + float ly = MathF.Round(y + Fs(hf) * 0.55f); + dl.AddLine(new Vector2(x + tw + Px(6), ly), new Vector2(x + wrapW, ly), _line); + y += Fs(hf) + Px(2); + } + foreach (AppraiseLine l in s.Lines) + y = Wrapped(dl, lf, new Vector2(x, y), wrapW, l.Text, Tone(l.Tone)) + Px(1); + } + + if (doc.Description.Length > 0) + { + y += Px(4); + y = Wrapped(dl, lf, new Vector2(x, y), wrapW, doc.Description, _dim) + Px(2); + } + + // Every property, folded. + if (doc.Raw.Count > 0) + { + y += Px(4); + string head = (_rawOpen ? "v " : "> ") + "All properties (" + doc.Raw.Count.ToString(CultureInfo.InvariantCulture) + ")"; + ImGui.SetCursorScreenPos(new Vector2(x, y)); + if (ImGui.InvisibleButton("##appr_raw", new Vector2(wrapW, Fs(hf) + Px(2)))) _rawOpen = !_rawOpen; + bool hot = ImGui.IsItemHovered(); + SafeImGui.SetItemTooltip("Every property the engine holds for it, by ACE's names (what /ub propertydump lists)."); + dl.AddText(hf, Fs(hf), new Vector2(x, y), hot ? _text : _faint, head); + y += Fs(hf) + Px(3); + if (_rawOpen) + { + float kindW = mf.CalcTextSizeA(Fs(mf), float.MaxValue, 0f, "InstanceId 9999 ").X; + foreach (AppraiseRaw r in doc.Raw) + { + string k = r.Kind + " " + r.Key.ToString(CultureInfo.InvariantCulture); + dl.AddText(mf, Fs(mf), new Vector2(x, y), _faint, k); + float nx = x + kindW; + string nv = r.Name + " = " + r.Value; + y = Wrapped(dl, mf, new Vector2(nx, y), wrapW - kindW, nv, r.Name == "?" ? _faint : _dim) + Px(1); + } + } + } + + y += Px(4); + float h = y - o.Y; + ImGui.SetCursorScreenPos(o); + ImGui.Dummy(new Vector2(Math.Max(1, width), Math.Max(1, h))); + return h; + } + + private uint Tone(AppraiseTone t) => t switch + { + AppraiseTone.Dim => _dim, + AppraiseTone.Good => _good, + AppraiseTone.Bad => _bad, + AppraiseTone.Magic => MagicColor, + AppraiseTone.Gold => _gold, + _ => _text, + }; + + private static string Facts(AppraisalDoc doc) + { + var parts = new List(doc.Facts.Count); + foreach (var (label, value) in doc.Facts) parts.Add(label + " " + value); + return string.Join(" · ", parts); + } + + private static string Short(string attribute) => attribute switch + { + "Strength" => "Str", "Endurance" => "End", "Quickness" => "Quick", "Coordination" => "Coord", "Focus" => "Focus", "Self" => "Self", _ => attribute, + }; + + // ── The menu ───────────────────────────────────────────────────────────── + + private const string MenuId = "##appr_menu"; + + private void Menu(AppraisalView v) + { + if (!ImGui.IsPopupOpen(MenuId)) return; + ImGui.PushStyleColor(ImGuiCol.PopupBg, A(_bg, 0.98f)); + ImGui.PushStyleColor(ImGuiCol.Border, _line); + ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, Px(4)); + ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(Px(6), Px(5))); + bool open = ImGui.BeginPopup(MenuId); + ImGui.PopStyleVar(2); + ImGui.PopStyleColor(2); + if (!open) return; + try + { + AppraisalDoc? doc = v.Ready ? v.Doc : null; + if (doc != null) SafeImGui.TextDisabled(doc.Name); + else ImGui.TextDisabled("Nothing appraised yet"); + ImGui.Separator(); + if (ImGui.MenuItem("Copy as text", null, false, doc != null) && doc != null) ImGui.SetClipboardText(doc.ToText()); + SafeImGui.SetItemTooltip("The whole appraisal, to paste in chat or a note."); + if (ImGui.MenuItem("Appraise again", null, false, doc != null && !v.Gone)) Refresh?.Invoke(); + if (ImGui.MenuItem("Select it", null, false, doc != null && !v.Gone) && doc != null) Select?.Invoke(doc.Id); + SafeImGui.SetItemTooltip("Make it the game's selection (as a click on it does)."); + if (ImGui.MenuItem("Pinned (only a middle-click changes it)", null, v.Pinned)) TogglePin?.Invoke(); + if (ImGui.MenuItem("Show every property", null, _rawOpen, doc != null)) _rawOpen = !_rawOpen; + if (ImGui.MenuItem(_popped ? "Dock back into the game window" : "Pop out of the game window")) + _host.SetPanelPopOut(Title, RynthPanelPopOut.Toggle); + SafeImGui.SetItemTooltip(_popped ? "Back inside the game window, where it was." : "Its own window, which you can put on another screen (/rdef appraisal popout)."); + ImGui.Separator(); + if (ImGui.MenuItem("Hide the Appraisal window")) _host.SetPanelOpen(Title, RynthPanelOpen.Close); + SafeImGui.SetItemTooltip("/rdef appraisal shows it again; a middle-click on something does too."); + } + finally { ImGui.EndPopup(); } + } + + // ── Drawing helpers ────────────────────────────────────────────────────── + + private bool Chip(string id, string icon, Vector2 pos, uint color, string tip, bool held = false) + { + Vector2 size = new(Px(ChipSize), Px(ChipSize)); + ImGui.SetCursorScreenPos(pos); + bool clicked = ImGui.InvisibleButton(id, size); + bool hot = ImGui.IsItemHovered(); + SafeImGui.SetItemTooltip(tip); + ImDrawListPtr dl = ImGui.GetWindowDrawList(); + if (hot || held) dl.AddRectFilled(pos, pos + size, _key, Px(3)); + DrawIcon(dl, icon, pos, size, Px(11), hot ? _text : color); + return clicked; + } + + /// Word-wrapped text from within ; returns the y under it. + private float Wrapped(ImDrawListPtr dl, ImFontPtr f, Vector2 pos, float width, string text, uint color) + { + float size = Fs(f); + float y = pos.Y; + foreach (string line in WrapLines(f, size, text, Math.Max(Px(20), width))) + { + dl.AddText(f, size, new Vector2(MathF.Round(pos.X), MathF.Round(y)), color, line); + y += size + Px(1); + } + return y; + } + + private static IEnumerable WrapLines(ImFontPtr f, float size, string text, float width) + { + foreach (string para in text.Replace("\r", "").Split('\n')) + { + if (para.Length == 0) { yield return ""; continue; } + int start = 0; + while (start < para.Length) + { + int end = para.Length; + if (f.CalcTextSizeA(size, float.MaxValue, 0f, para[start..end]).X > width) + { + // The longest run of whole words that fits, else as many characters as fit. + int lastSpace = -1, i = start + 1; + for (; i <= para.Length; i++) + { + if (f.CalcTextSizeA(size, float.MaxValue, 0f, para[start..i]).X > width) break; + if (i < para.Length && para[i] == ' ') lastSpace = i; + } + end = lastSpace > start ? lastSpace : Math.Max(start + 1, i - 1); + } + yield return para[start..end].TrimEnd(); + start = end; + while (start < para.Length && para[start] == ' ') start++; + } + } + } + + private static void Clip(ImDrawListPtr dl, ImFontPtr f, float size, Vector2 pos, uint color, string text, float room) + { + if (text.Length == 0 || room <= 4) return; + float w = f.CalcTextSizeA(size, float.MaxValue, 0f, text).X; + if (w > room) + { + int n = text.Length; + while (n > 1 && f.CalcTextSizeA(size, float.MaxValue, 0f, text[..n] + "...").X > room) n--; + text = text[..n] + "..."; + } + dl.AddText(f, size, new Vector2(MathF.Round(pos.X), MathF.Round(pos.Y)), color, text); + } + + private static unsafe void DrawIcon(ImDrawListPtr dl, string glyph, Vector2 min, Vector2 size, float px, uint color) + { + if (string.IsNullOrEmpty(glyph)) return; + ImFontPtr font = Font(RynthUiFont.Ui18); + if (font.NativePtr == null) return; + byte* g = (byte*)ImGuiNative.ImFont_FindGlyphNoFallback(font.NativePtr, glyph[0]); + if (g == null) return; + float advance = *(float*)(g + 4); + if (advance <= 0) return; + float* box = (float*)(g + 8); + float scale = px / advance; + Vector2 centre = new((box[0] + box[2]) * 0.5f * scale, (box[1] + box[3]) * 0.5f * scale); + Vector2 at = min + size * 0.5f - centre; + dl.AddText(font, font.FontSize * scale, new Vector2(MathF.Round(at.X), MathF.Round(at.Y)), color, glyph); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthDefective/Model/DefCommand.cs b/Plugins/RynthCore.Plugin.RynthDefective/Model/DefCommand.cs index c910512..54079d3 100644 --- a/Plugins/RynthCore.Plugin.RynthDefective/Model/DefCommand.cs +++ b/Plugins/RynthCore.Plugin.RynthDefective/Model/DefCommand.cs @@ -3,7 +3,7 @@ using System; namespace RynthCore.Plugin.RynthDefective.Model; internal enum DefVerb { Toggle, Help, Use, Set, Clear, Bind, Unbind, Weapons, Favourite, Slots, List, Status, Error, Panels, Selection, Settings, Spell, Corpses, - Quantity, Split, Give, Buy, DayNight, Bars, Shortcuts } + Quantity, Split, Give, Buy, DayNight, Bars, Shortcuts, Appraisal } /// /// A parsed "/rdef ..." line. Use: (1-based) or (an item name). @@ -19,7 +19,7 @@ internal static class DefCommandParser { public const string Usage = "/rdef [use | set [item name] | spell | clear | bind | unbind | " - + "weapons [search] | fav | slots | list | status | settings | panels (the game panel buttons) | selection | corpses [clear] | " + + "weapons [search] | fav | slots | list | status | settings | panels (the game panel buttons) | selection | appraisal [pin|unpin|again|popout|dock] | corpses [clear] | " + "bars [add | remove | slots | show ] | shortcuts clearbusy [on|off] | " + "qty [number|max|half] | split [number] [into ] | give [number] | buy [number] [item name] | daynight [show|hide]]"; @@ -54,6 +54,8 @@ internal static class DefCommandParser case "panels": case "panel": return new DefCommand(DefVerb.Panels); case "settings": case "options": case "setup": return new DefCommand(DefVerb.Settings); case "corpses": case "corpse": return new DefCommand(DefVerb.Corpses, Text: rest); + // The Appraisal window (2026-11-28): Text "", "pin", "unpin", "again", or an object id (a test hook). + case "appraisal": case "appraise": case "examine": return new DefCommand(DefVerb.Appraisal, Text: rest); case "selection": case "target": // "/rdef selection 0x80001234": select that object (a test hook for the Selection window). return new DefCommand(DefVerb.Selection, Text: rest); diff --git a/Plugins/RynthCore.Plugin.RynthDefective/Model/DefData.cs b/Plugins/RynthCore.Plugin.RynthDefective/Model/DefData.cs index 526286c..b4c734f 100644 --- a/Plugins/RynthCore.Plugin.RynthDefective/Model/DefData.cs +++ b/Plugins/RynthCore.Plugin.RynthDefective/Model/DefData.cs @@ -128,6 +128,11 @@ internal sealed class DefSettings /// within 4 s; this only saves those seconds. /// public bool ClearStuckBusy; + /// + /// The Appraisal window is pinned (2026-11-28): only a middle-click changes what it shows, not the + /// player's own selections. Off (the default, and what a file from before reads as): both do. + /// + public bool AppraisalPinned; public bool BarOpen; public bool PickerOpen; diff --git a/Plugins/RynthCore.Plugin.RynthDefective/Model/DefReplies.cs b/Plugins/RynthCore.Plugin.RynthDefective/Model/DefReplies.cs index 8a947c3..3cd25c8 100644 --- a/Plugins/RynthCore.Plugin.RynthDefective/Model/DefReplies.cs +++ b/Plugins/RynthCore.Plugin.RynthDefective/Model/DefReplies.cs @@ -18,6 +18,14 @@ internal static class DefReplies _ => (false, $"This RynthCore has no {title} window (it needs plugin API v90)."), }; + /// A window after a pop out / dock: 1 popped out, 0 docked, -1 not open (or no such window). + public static (bool Ok, string Text) PoppedOut(string title, int state) => state switch + { + 1 => (true, $"{title} popped out: its own window, which you can put on another screen."), + 0 => (true, $"{title} docked back into the game window."), + _ => (false, $"The {title} isn't open: open it first (/rdef appraisal), then pop it out."), + }; + /// /// /rdef daynight [show|hide]: the Day/Night timer after it ( as ), /// then the time now when the clock can be read (null = not in world): "Day/Night timer shown. Night now diff --git a/Plugins/RynthCore.Plugin.RynthDefective/Model/DefStore.cs b/Plugins/RynthCore.Plugin.RynthDefective/Model/DefStore.cs index e761706..b1c806c 100644 --- a/Plugins/RynthCore.Plugin.RynthDefective/Model/DefStore.cs +++ b/Plugins/RynthCore.Plugin.RynthDefective/Model/DefStore.cs @@ -70,6 +70,7 @@ internal sealed class DefStore st.IndependentBar = Bool(s, "independentBar", st.IndependentBar); // missing (a file from before 2026-10-27): off st.QuantityBox = Bool(s, "quantityBox", st.QuantityBox); // missing (a file from before 2026-10-30): on st.ClearStuckBusy = Bool(s, "clearStuckBusy", st.ClearStuckBusy); // missing (a file from before 2026-11-04): off + st.AppraisalPinned = Bool(s, "appraisalPinned", st.AppraisalPinned); // missing (a file from before 2026-11-28): off st.BarOpen = Bool(s, "barOpen", st.BarOpen); st.PickerOpen = Bool(s, "pickerOpen", st.PickerOpen); st.Clamp(); @@ -192,6 +193,7 @@ internal sealed class DefStore w.WriteBoolean("independentBar", s.IndependentBar); w.WriteBoolean("quantityBox", s.QuantityBox); w.WriteBoolean("clearStuckBusy", s.ClearStuckBusy); + w.WriteBoolean("appraisalPinned", s.AppraisalPinned); w.WriteBoolean("barOpen", s.BarOpen); w.WriteBoolean("pickerOpen", s.PickerOpen); w.WriteEndObject(); diff --git a/Plugins/RynthCore.Plugin.RynthDefective/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthDefective/PluginExports.cs index 1589698..1ebea56 100644 --- a/Plugins/RynthCore.Plugin.RynthDefective/PluginExports.cs +++ b/Plugins/RynthCore.Plugin.RynthDefective/PluginExports.cs @@ -105,6 +105,7 @@ public static unsafe class PluginExports if (name == RynthDefectivePlugin.BarSurface) result = plugin.RenderBar(popped, out wantH); else if (name == RynthDefectivePlugin.PanelsSurface) result = plugin.RenderPanels(out wantH); else if (name == RynthDefectivePlugin.SelectionSurface) result = plugin.RenderSelection(out wantH); + else if (name == RynthDefectivePlugin.AppraisalSurface) result = plugin.RenderAppraisal(popped, out wantH); else if (name == RynthDefectivePlugin.CorpsesSurface) result = plugin.RenderCorpses(out wantH); else if (name == RynthDefectivePlugin.DayNightSurface) result = plugin.RenderDayNight(out wantH); else if (RynthDefectivePlugin.TryExtraSurface(name, out int extra)) result = plugin.RenderExtraBar(extra, popped, out wantH); diff --git a/Plugins/RynthCore.Plugin.RynthDefective/README.md b/Plugins/RynthCore.Plugin.RynthDefective/README.md index c983d27..01c38bd 100644 --- a/Plugins/RynthCore.Plugin.RynthDefective/README.md +++ b/Plugins/RynthCore.Plugin.RynthDefective/README.md @@ -129,6 +129,32 @@ Foredawn-and-Half) are 63.5 real minutes each; the clock and calendar are RynthA (`getisday`, `getminutesuntilnight`). It shows "—" until you're in the world: the game clock isn't read before. `/rdef daynight` also says the time in chat. Drag it anywhere; Ctrl+wheel resizes it; right-click hides it. +## The Appraisal window + +Retail's examine panel, roughly, that stays on **your** pick (its RynthCore bar button is the magnifying glass; +`/rdef appraisal`): the picture and name, what it is (Heavy Weapons (Sword), Armor, Level 112 · Olthoi), +value, burden, stack and uses, the bars (a creature's health, stamina and mana; an item's mana), a creature's +six attributes (green when buffed, red when debuffed), then the appraisal's lines in retail's words under small +headings (Weapon / Caster, Armor, Magic, Requirements, Properties), the description, and **All properties** +(every property the engine holds, by ACE's names, folded). + +What changes it: + +* **A middle-click** on anything in the 3D world: the object under the cursor, the one whose name AC shows. + Your selection doesn't change, so a running bot keeps its target. A middle **drag** is still mouse look. + A middle-click opens the window when it's shut. In RynthCore's own inventory window a middle-click works too. +* **Your own selection**: a click in the world or a pack, the selection keys, a radar dot or nameplate. + Pinned (the pin in its title, or `/rdef appraisal pin`), only a middle-click changes it. +* **Never the bot's selections**: anything a plugin selects through the API (RynthAi's targets, its looting). + +A new pick is appraised (the server is asked unless it just answered); a creature's health is asked for every +2 s while it shows, and it is assessed again every 15 s. The arrows in its title appraise it again. Right-click +the title: copy the appraisal as text, appraise again, select it, pin, show every property, pop out, hide. The +square in its title (or `/rdef appraisal popout`, `/rdef appraisal dock`) pops it out of the game window into its +own window, for another screen, and docks it back. Something +that leaves view keeps its last appraisal ("no longer in view"). Needs engine API 100 (the player's picks); the +window isn't there on an older engine. + ## Busy, combat and RynthAi * One item action at a time: a request waits while the client is busy, a gesture animates, RynthAi waits on @@ -165,6 +191,7 @@ Foredawn-and-Half) are 63.5 real minutes each; the clock and calendar are RynthA /rdef show / hide the bar /rdef settings RynthDefective's settings window /rdef panels | selection show / hide the Game Panels buttons, the Selection window +/rdef appraisal [pin|unpin|again|popout|dock] show / hide the Appraisal window; pin it; appraise again; pop out /rdef use use the slot's item, or the carried item with that name /rdef set [item name] put the selected item (or the named one) in a slot /rdef spell put one of your spells in a slot (it casts it) @@ -206,5 +233,5 @@ Pages, arrow auto-equip, gear highlight, summon cooldown counters and the war-ma ## Needs RynthCore engine API 71 with ImGui for the windows (op level 2 for pictures; text buttons without it); -API 90 for the Shortcuts bar, Game Panels and Selection. `/rdef use` works on any engine with UseObject. +API 90 for the Shortcuts bar, Game Panels and Selection; API 100 for the Appraisal window. `/rdef use` works on any engine with UseObject. The quantity commands: splitting on any engine, giving with a count API 62, buying API 67. diff --git a/Plugins/RynthCore.Plugin.RynthDefective/RynthCore.Plugin.RynthDefective.csproj b/Plugins/RynthCore.Plugin.RynthDefective/RynthCore.Plugin.RynthDefective.csproj index f406de2..314fdd8 100644 --- a/Plugins/RynthCore.Plugin.RynthDefective/RynthCore.Plugin.RynthDefective.csproj +++ b/Plugins/RynthCore.Plugin.RynthDefective/RynthCore.Plugin.RynthDefective.csproj @@ -31,7 +31,7 @@ pictures) are checked first; so are the UseDone count (v63), wield/refusal info (v70) and the chat parser the key binding goes through. Below v71 it still uses items (/rdef use). --> 66 - Draws the Shortcuts bar (the game's 18 slots and its own), the Game Panels buttons and the Selection window (with a quantity box: split, give or buy that many), and a Day/Night timer: one-touch kits, potions, weapons and spells by slot or key, and a fast weapon picker. Settings: the bar's gear or /rdef settings. + Draws the Shortcuts bar (the game's 18 slots and its own), the Game Panels buttons and the Selection window (with a quantity box: split, give or buy that many), the Appraisal window (what you middle-click or select yourself, never the bot's picks), and a Day/Night timer: one-touch kits, potions, weapons and spells by slot or key, and a fast weapon picker. Settings: the bar's gear or /rdef settings. @@ -57,6 +57,12 @@ (linked as RynthInventory and RynthOracle link it; Model/Spells.cs reads it). --> + + + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Blocked.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Blocked.cs index a226d76..b03193e 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Blocked.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Blocked.cs @@ -11,7 +11,7 @@ namespace RynthCore.Plugin.RynthNav; // little islands (Shoushi's plaza, where the Town Network drops you, 10-08); where the plan runs // out the walk heads straight for its goal for a moment (BlindPushTicks), and that, or a wall the // mesh doesn't show, used to mean running into it until the 30 s progress watchdog. Now: blocked -// for StuckWindowMs = turn away toward open ground (WalkSteer.UnstickHeading), remember the spot as +// (StuckWatch) = turn away toward open ground (WalkSteer.UnstickHeading), remember the spot as // something to keep out of (the next plan bends round it, like round a portal), plan again, and // after StuckMaxTries on one leg without progress stop and say where. // @@ -19,10 +19,11 @@ namespace RynthCore.Plugin.RynthNav; // it turned 120 degrees off, alternating sides, ran 1.6 s, planned the same path again and ran back // into the same spot, four times in 20 s, then stopped. The remembered spots now make each new // plan go round what it ran into. +// +// 11-27: a walk swinging between headings against a wall (run a moment, turn a moment) was never +// blocked, as a tick turning in place started the watch again. StuckWatch counts turning too. public sealed partial class RynthNavPlugin { - private const long StuckWindowMs = 1200; // running this long... - private const double StuckMoveUnits = 0.6; // ...and moved less than this = blocked (a run covers 4+ u/s) private const long UnstickMs = 1600; // then turn away from it and run this long (~0.5 s of it turning) private const int StuckMaxTries = 4; // blocked this often on a leg without progress = stop private const double BlockedAheadUnits = 3.5; // the remembered spot: this far ahead of where it stuck... @@ -30,20 +31,20 @@ public sealed partial class RynthNavPlugin private const int BlockedMaxSpots = 12; private const double UnstickOpenUnits = 6.0; // a way out is open ground this far along it - private bool _ranLastTick; // the walk asked to run last tick (not standing, not turning in place) private double _lastDriveDeg; - private long _stuckWinMs, _unstickUntilMs; - private double _stuckWx, _stuckWy, _unstickDeg; + private long _unstickUntilMs; + private double _unstickDeg; private int _stuckTries, _stuckSide = 1; + private readonly StuckWatch _stuck = new(); private readonly List _blockedSpots = new(); - /// DriveTo for the walk's own steering: remembers that it ran and which way. + /// DriveTo for the walk's own steering: remembers which way, and that it drove (running or turning). private void WalkDrive(double deg, bool tight = false) { WalkSteer servo = tight ? _steerTight : _steerOpen; DriveTo(deg, servo); _lastDriveDeg = deg; - _ranLastTick = !servo.TurnInPlace; + _stuck.Drove(running: !servo.TurnInPlace); } /// @@ -93,8 +94,8 @@ public sealed partial class RynthNavPlugin /// A new leg (or goto): nothing blocked yet. private void ResetBlocked() { - _ranLastTick = false; - _stuckWinMs = 0; _unstickUntilMs = 0; _stuckTries = 0; + _stuck.Reset(); + _unstickUntilMs = 0; _stuckTries = 0; _blockedSpots.Clear(); } @@ -105,8 +106,6 @@ public sealed partial class RynthNavPlugin private bool StepBlocked() { long now = NowMs; - bool ran = _ranLastTick; - _ranLastTick = false; if (_unstickUntilMs > now) { DriveTo(_unstickDeg, _steerOpen); @@ -119,14 +118,10 @@ public sealed partial class RynthNavPlugin _unstickUntilMs = 0; lock (_gotoGate) _gotoPath = null; _blindTicks = 0; _replanTick = 0; - _stuckWinMs = 0; + _stuck.Reset(); return false; } - if (!ran || _stuckWinMs == 0) { _stuckWinMs = now; _stuckWx = _wx; _stuckWy = _wy; return false; } - if (now - _stuckWinMs < StuckWindowMs) return false; - double moved = Math.Sqrt((_wx - _stuckWx) * (_wx - _stuckWx) + (_wy - _stuckWy) * (_wy - _stuckWy)); - _stuckWinMs = now; _stuckWx = _wx; _stuckWy = _wy; - if (moved >= StuckMoveUnits) return false; + if (!_stuck.Check(now, _wx, _wy, out double moved, out long windowMs)) return false; string at = NavCoords.Fmt(NavCoords.NsFromWorld(_wy), NavCoords.EwFromWorld(_wx)); if (++_stuckTries > StuckMaxTries) @@ -149,7 +144,7 @@ public sealed partial class RynthNavPlugin return WalkableStraight(_wx, _wy, _wx + Math.Sin(r) * UnstickOpenUnits, _wy + Math.Cos(r) * UnstickOpenUnits); }); _unstickUntilMs = now + UnstickMs; - Host.Log($"[RynthNav] walk: blocked at {at} heading {_lastDriveDeg:F0} (moved {moved:F1}u in {StuckWindowMs / 1000.0:F1} s); " + Host.Log($"[RynthNav] walk: blocked at {at} heading {_lastDriveDeg:F0} (moved {moved:F1}u in {windowMs / 1000.0:F1} s); " + $"turning to {_unstickDeg:F0}, keeping out of that spot ({_blockedSpots.Count} so far) and planning again ({_stuckTries}/{StuckMaxTries})"); DriveTo(_unstickDeg, _steerOpen); lock (_gate) _status = $"blocked: stepping round it ({_stuckTries}/{StuckMaxTries})"; diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.CustomPortals.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.CustomPortals.cs new file mode 100644 index 0000000..48bb93e --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.CustomPortals.cs @@ -0,0 +1,301 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Threading.Tasks; +using RynthNav.Routing; + +namespace RynthCore.Plugin.RynthNav; + +// This server's own portals (CustomPortals.cs, 2026-11-27): written down by a scan or when you take one, and given +// to the route planner as plain portal links next to portals.tsv's, so go / route / the arrow use them. Our graph is +// PortalRoute's (the same plan, costs and rules as every other portal); the walk to a custom portal aims at the +// spot the live object stood on, as for a portals.tsv portal with a spot. Tick thread. +// /rnav portals scan [yd] | list | forget | clear confirm | custom on|off +// Spotted by SilentKelpie (Forgejo rynth PR #12); re-implemented here. +public sealed partial class RynthNavPlugin +{ + private const string CustomPortalsFile = "custom-portals.txt"; + private const long NearPortalEveryMs = 400; + /// A live portal this close to you (yards) is the one you'd be taking. + private const double NearPortalUnits = 6.0; + /// The portal seen beside you counts for a teleport this long after it was seen. + private const long NearPortalFreshMs = 5000; + public const double ScanDefaultUnits = 250.0; + + private CustomPortalStore _custom = new(); + private volatile CustomPortalStore? _loadedCustom; + private bool _customLoaded; + private int _savedCustomVersion = -1; + private volatile bool _customOn = true; // rynthnav.json customPortals + private string _server = ""; + private List? _tsvPortals; // portals.tsv only (the "built in" ones) + private string _routeLinksKey = ""; + private string _customLast = ""; // the panel's line: what the last scan or learn did + private volatile int _customSaved, _customRoutable; // this server's counts, for the panel (counted on the tick) + private string _countedKey = ""; + private long _lastDeadMs; // HP 0 seen: the trip to the lifestone that follows isn't a portal + + // The live portal right beside you, looked for every NearPortalEveryMs on the map (a teleport then is that portal). + private long _nextNearPortalMs; + private (string Name, uint Wcid, uint Cell, double X, double Y, double Z, double Wx, double Wy, long Ms)? _nearPortal; + + private void LoadCustomPortals() + { + _customOn = NavDataConfig.ReadSwitch("customPortals", true); + string path = NavFile(CustomPortalsFile); + Task.Run(() => + { + CustomPortalStore s = new(); + try { if (File.Exists(path)) s = CustomPortalStore.Parse(File.ReadAllText(path)); } + catch (Exception ex) { Host.Log($"[RynthNav] {CustomPortalsFile}: {ex.Message}"); } + _loadedCustom = s; + }); + } + + /// Every tick: the loaded file taken in, the server, the portal beside you, the route links, the save. + private void TickCustomPortals(long now, bool save) + { + if (!_customLoaded && _loadedCustom is CustomPortalStore loaded) + { + _custom = loaded; _customLoaded = true; _savedCustomVersion = loaded.Version; + int n = loaded.All.Count; + if (n > 0) Host.Log($"[RynthNav] {CustomPortalsFile}: {n} custom portal(s)"); + } + if (_server.Length == 0 && Host.TryGetWorldName(out string world) && world.Trim().Length > 0) _server = world.Trim(); + if (now >= _nextNearPortalMs) { _nextNearPortalMs = now + NearPortalEveryMs; NoteNearPortal(now); } + RefreshRoutePortals(); + string ck = $"{_server}|{_custom.Version}|{_customLoaded}"; + if (ck != _countedKey) + { + _countedKey = ck; + var (saved, routable) = _server.Length > 0 && _customLoaded ? _custom.Counts(_server) : (0, 0); + _customSaved = saved; _customRoutable = routable; + } + if (save && _customLoaded && _custom.Version != _savedCustomVersion) SaveCustomPortals(); + } + + private void OnLogoutCustom() + { + if (_customLoaded && _custom.Version != _savedCustomVersion) SaveCustomPortals(); + _server = ""; _nearPortal = null; + } + + private void SaveCustomPortals() + { + // Every client writes the one file: take in what the others saved since, then write. + try + { + string path = NavFile(CustomPortalsFile); + if (File.Exists(path)) _custom.MergeFrom(CustomPortalStore.Parse(File.ReadAllText(path))); + } + catch (Exception ex) { Host.Log($"[RynthNav] {CustomPortalsFile} (merging before a save): {ex.Message}"); } + _savedCustomVersion = _custom.Version; + WriteLater(CustomPortalsFile, _custom.Serialize()); + } + + /// + /// The route planner's portals: portals.tsv's, then this server's custom ones with both ends on the map (custom + /// on). Rebuilt when they change; the tsv ones keep their place, so a trip's portal keys stay the same. + /// + private void RefreshRoutePortals() + { + if (_tsvPortals == null) return; + string key = _customOn ? $"{_server}|{_custom.Version}" : "off"; + if (key == _routeLinksKey && _portals != null) return; + _routeLinksKey = key; + var all = new List(_tsvPortals); + if (_customOn && _server.Length > 0) + { + List mine = _custom.Links(_server); + all.AddRange(mine); + if (mine.Count > 0) Host.Log($"[RynthNav] routes: {mine.Count} custom portal(s) for {_server} with the {_tsvPortals.Count} of portals.tsv"); + } + _portals = all; + } + + /// The nearest live portal object within NearPortalUnits, on the map, noted with its spot. + private void NoteNearPortal(long now) + { + if (Host.TryGetPlayerVitals(out uint hp, out uint maxHp, out _, out _, out _, out _) && maxHp > 0 && hp == 0) _lastDeadMs = now; + if (!_hasPose || !IsOnMap(_cellId) || !Host.HasGetLiveObjectIds || (Host.HasIsPortaling && Host.IsPortaling())) return; + double best = NearPortalUnits * NearPortalUnits; + uint bestId = 0, bestCell = 0; float bx = 0, by = 0, bz = 0; + foreach (uint id in Host.GetLiveObjectIds()) + { + if (!Host.TryGetItemType(id, out uint type) || (type & ItemTypePortal) == 0) continue; + if (!Host.TryGetObjectPosition(id, out uint cell, out float x, out float y, out float z) || cell == 0 || !IsOnMap(cell)) continue; + double ox = ((cell >> 24) & 0xFF) * 192.0 + x, oy = ((cell >> 16) & 0xFF) * 192.0 + y; + double d2 = (ox - _wx) * (ox - _wx) + (oy - _wy) * (oy - _wy); + if (d2 >= best) continue; + best = d2; bestId = id; bestCell = cell; bx = x; by = y; bz = z; + } + if (bestId == 0) return; // the last one stays until it is too old to count + Host.TryGetObjectName(bestId, out string name); + Host.TryGetObjectWcid(bestId, out uint wcid); + if (name.Length == 0) return; + _nearPortal = (name, wcid, bestCell, bx, by, bz, ((bestCell >> 24) & 0xFF) * 192.0 + bx, ((bestCell >> 16) & 0xFF) * 192.0 + by, now); + } + + /// + /// OnTeleported, a portal (not a recall): the live portal seen right beside where you stood before the jump + /// was the one taken; its landing is learned (CustomPortalStore.Learned). portals.tsv's are left alone. + /// + /// : your own spell words just before (a recall cast beside a portal isn't the portal). + private void LearnCustomPortal(bool havePre, uint preCell, double preWx, double preWy, long startMs, RecallSpot landing, bool spellWords) + { + if (!_customLoaded || _server.Length == 0 || !havePre || !IsOnMap(preCell) || _nearPortal is not { } near) return; + if (spellWords || (_lastDeadMs != 0 && startMs - _lastDeadMs < 60000)) { _nearPortal = null; return; } + if (startMs - near.Ms > NearPortalFreshMs || near.Ms > startMs + 500) return; + if ((near.Cell >> 16) != (preCell >> 16) && Math.Abs(near.Wx - preWx) + Math.Abs(near.Wy - preWy) > 2 * NearPortalUnits) return; + double dx = near.Wx - preWx, dy = near.Wy - preWy; + if (dx * dx + dy * dy > NearPortalUnits * NearPortalUnits) return; + _nearPortal = null; + double ns = NavCoords.NsFromWorld(near.Wy), ew = NavCoords.EwFromWorld(near.Wx); + CustomLearn r = _custom.Learned(_server, near.Name, near.Wcid, near.Cell, near.X, near.Y, near.Z, ns, ew, + landing.OnMap, landing.Ns, landing.Ew, landing.OnMap ? 0 : _cellId, _tsvPortals, DateTime.UtcNow, out CustomPortal? p); + switch (r) + { + case CustomLearn.New: + case CustomLearn.LandingChanged: + string what = r == CustomLearn.New ? "learned" : "updated"; + _customLast = $"{what} {p!.Name} → {p.Where}"; + Host.Log($"[RynthNav] custom portal {what}: {p.Name} at {NavCoords.Fmt(ns, ew)} → {p.Where} ({_server})"); + Say($"{what} portal {p.Name}: it goes to {p.Where}" + (p.Routable ? "; routes can use it now" : "")); + break; + case CustomLearn.AlreadyKnown: + Host.Log($"[RynthNav] custom portal {near.Name}: already known ({p?.Where})"); + break; + } + } + + // ── /rnav portals ... ──────────────────────────────────────────────── + + private void CmdPortals(string rest) + { + string[] a = rest.Trim().Split(' ', 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + string verb = a.Length > 0 ? a[0].ToLowerInvariant() : ""; + string arg = a.Length > 1 ? a[1] : ""; + switch (verb) + { + case "on": + case "off": + _portalsEnabled = verb == "on"; + NavDataConfig.WriteSwitch("portals", _portalsEnabled); + Say($"portal and recall routing {(_portalsEnabled ? "ON" : "OFF")} for walking (go/goto)"); + return; + case "": + Say($"portal and recall routing {(_portalsEnabled ? "ON" : "OFF")}; {CustomSummary()} — /rnav portals on|off | scan [yd] | list | forget | clear confirm | custom on|off"); + return; + case "custom": + string v = arg.ToLowerInvariant(); + if (v is "on" or "off") { _customOn = v == "on"; NavDataConfig.WriteSwitch("customPortals", _customOn); } + else if (v.Length > 0) { SayFail("/rnav portals custom on|off — this server's own portals in routes"); return; } + Say($"custom portals in routes: {(_customOn ? "ON" : "OFF")}; {CustomSummary()}"); + return; + case "scan": CmdPortalScan(arg); return; + case "list": CmdPortalList(); return; + case "forget": + if (!CustomReady(out string server)) return; + if (arg.Length == 0) { SayFail("/rnav portals forget "); return; } + int n = _custom.Forget(server, arg); + if (n == 0) SayFail($"portals: no custom portal called {arg} on {server}"); + else Say($"portals: forgot {n} custom portal(s) called {arg} on {server}"); + return; + case "clear": + if (!CustomReady(out server)) return; + if (!arg.Equals("confirm", StringComparison.OrdinalIgnoreCase)) + { + var (saved, _) = _custom.Counts(server); + SayFail($"portals: /rnav portals clear confirm forgets all {saved} custom portal(s) of {server}"); + return; + } + Say($"portals: forgot all {_custom.Clear(server)} custom portal(s) of {server}"); + _customLast = "cleared"; + return; + default: + SayFail("/rnav portals on|off | scan [yd] | list | forget | clear confirm | custom on|off"); + return; + } + } + + private bool CustomReady(out string server) + { + server = _server; + if (!_customLoaded) { SayFail($"portals: {CustomPortalsFile} isn't loaded yet"); return false; } + if (server.Length == 0) { SayFail("portals: not logged in to a server yet"); return false; } + return true; + } + + private string CustomSummary() + { + if (_server.Length == 0) return "custom portals: not logged in yet"; + var (saved, routable) = _custom.Counts(_server); + return $"{saved} custom portal(s) saved for {_server}, {routable} routable{(_customOn ? "" : " (not used: custom off)")}"; + } + + /// /rnav portals scan [yd]: every live portal object on the map within that range, written down. + private void CmdPortalScan(string arg) + { + if (!CustomReady(out string server)) return; + if (!_hasPose) { SayFail("portals scan: no player position yet"); return; } + double range = ScanDefaultUnits; + if (arg.Length > 0 && (!double.TryParse(arg, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out range) || range <= 0)) + { SayFail("/rnav portals scan [yards] — e.g. /rnav portals scan 200"); return; } + range = Math.Clamp(range, 10, 2000); + if (!Host.HasGetLiveObjectIds) { SayFail("portals scan: this RynthCore can't list objects"); return; } + EnsurePortalsLoaded(); + int added = 0, refreshed = 0, builtIn = 0, inDungeon = 0; + var names = new List(); + DateTime now = DateTime.UtcNow; + foreach (uint id in Host.GetLiveObjectIds()) + { + if (!Host.TryGetItemType(id, out uint type) || (type & ItemTypePortal) == 0) continue; + if (!Host.TryGetObjectPosition(id, out uint cell, out float x, out float y, out float z) || cell == 0) continue; + if (!IsOnMap(cell)) { inDungeon++; continue; } + double wx = ((cell >> 24) & 0xFF) * 192.0 + x, wy = ((cell >> 16) & 0xFF) * 192.0 + y; + if (Math.Sqrt((wx - _wx) * (wx - _wx) + (wy - _wy) * (wy - _wy)) > range) continue; + if (!Host.TryGetObjectName(id, out string name) || name.Length == 0 || Entrance.IsDestroyed(name)) continue; + Host.TryGetObjectWcid(id, out uint wcid); + switch (_custom.Saw(server, name, wcid, cell, x, y, z, NavCoords.NsFromWorld(wy), NavCoords.EwFromWorld(wx), _tsvPortals, now)) + { + case CustomSeen.Added: added++; if (names.Count < 6) names.Add(name); break; + case CustomSeen.Refreshed: refreshed++; break; + default: builtIn++; break; + } + } + var (saved, routable) = _custom.Counts(server); + _customLast = $"scan: {added} new, {refreshed} known, {builtIn} in the world data"; + Host.Log($"[RynthNav] portals scan ({range:F0} yd, {server}): {added} new, {refreshed} known, {builtIn} in portals.tsv, {inDungeon} in dungeons (not mapped)"); + Say($"portals scan ({range:F0} yd): {added} new{(names.Count > 0 ? " (" + string.Join(", ", names) + (added > names.Count ? ", …" : "") + ")" : "")}, " + + $"{refreshed} already saved, {builtIn} already in the world data. {saved} saved for {server}, {routable} routable" + + (added > 0 ? "; take each once and routes can use it" : "")); + } + + private void CmdPortalList() + { + if (!CustomReady(out string server)) return; + List list = _custom.For(server); + if (list.Count == 0) { Say($"portals: no custom portals saved for {server} — /rnav portals scan writes down the ones around you"); return; } + Say($"portals: {CustomSummary()}:"); + bool hasPos = PlayerMapPos(out double pns, out double pew); + list.Sort((x, y) => (hasPos ? NavCoords.Distance(pns, pew, x.Ns, x.Ew) : 0).CompareTo(hasPos ? NavCoords.Distance(pns, pew, y.Ns, y.Ew) : 0)); + int shown = 0; + foreach (CustomPortal p in list) + { + if (++shown > 20) { Say($" … and {list.Count - 20} more"); break; } + Say($" {p.Name} at {NavCoords.Fmt(p.Ns, p.Ew)}{(hasPos ? ", " + NavCoords.FmtDistance(NavCoords.Distance(pns, pew, p.Ns, p.Ew)) : "")} → {p.Where}"); + } + } + + /// The panel's custom portals fields (status JSON "custom"). Any thread: the counts are the tick's. + private void AppendCustomJson(StringBuilder sb) + { + string server = _server; + int saved = _customSaved, routable = _customRoutable; + sb.Append(",\"custom\":{\"on\":").Append(_customOn ? 1 : 0).Append(",\"server\":\"").Append(Esc(server)) + .Append("\",\"saved\":").Append(saved).Append(",\"routable\":").Append(routable) + .Append(",\"range\":").Append(((int)ScanDefaultUnits).ToString(System.Globalization.CultureInfo.InvariantCulture)) + .Append(",\"last\":\"").Append(Esc(_customLast)).Append("\"}"); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Follow.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Follow.cs new file mode 100644 index 0000000..e4bad4b --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Follow.cs @@ -0,0 +1,74 @@ +using System; + +namespace RynthCore.Plugin.RynthNav; + +// Walks keep to the trip's own path (TripFollow.cs, 2026-11-27): each re-plan of a walking step aims a few yards +// along the walk the path markers draw, rather than at the route graph's next crossing. On by default; +// /rnav follow on|off (rynthnav.json followTrip; the status JSON's "follow"). The trip's path is worked out for a +// goto with follow on even when the markers are off. Tick thread. +// Spotted by SilentKelpie (Forgejo rynth PR #12); re-implemented here. +public sealed partial class RynthNavPlugin +{ + private volatile bool _followTrip = true; + private TripFollow? _follow; + private bool _offTripSaid; + + private void LoadFollowSettings() => _followTrip = NavDataConfig.ReadSwitch("followTrip", true); + + /// The trip's path is wanted for walking (follow on, a goto's own trip). + private bool FollowWantsPath(PlannedTrip? trip) => _followTrip && trip != null && trip.Live; + + /// /rnav follow [on|off] + private void CmdFollow(string rest) + { + string a = rest.Trim().ToLowerInvariant(); + if (a is "on" or "off") + { + _followTrip = a == "on"; + NavDataConfig.WriteSwitch("followTrip", _followTrip); + _follow = null; + lock (_gotoGate) _gotoPath = null; // re-plan the walk in hand the new way + if (_followTrip && _gotoActive) StartPathBuild(); + } + else if (a.Length > 0) { SayFail("/rnav follow on|off — walks keep to the trip's path (the markers), or plan their own way"); return; } + Say(_followTrip ? "follow ON: walks keep to the trip's path (the markers)" + : "follow OFF: walks plan their own way to the route's crossings"); + } + + /// + /// The walk to follow for the running goto's step, or null: follow off, no live trip, its path not worked out + /// yet, not on the map, no walk for this step, or a walk that is only a straight line (nothing to keep to). + /// + private TripFollow? CurrentFollow() + { + PlannedTrip? trip = _trip; + TripPath? path = _tripPath; + if (!_followTrip || trip == null || !trip.Live || path == null || path.TripId != trip.Id || !IsOnMap(_cellId)) return null; + int step = _route != null ? _routeIdx : 0; + if (step < 0 || step >= path.Walks.Length || path.Walks[step] is not { Length: >= 2 } walk) return null; + if (_follow != null && _follow.TripId == trip.Id && _follow.Step == step) return _follow; + string tag = $"step {step + 1}:"; + foreach (string n in path.Notes) + if (n.StartsWith(tag, StringComparison.Ordinal) && n.Contains("straight line", StringComparison.Ordinal)) return null; + _follow = new TripFollow(trip.Id, step, walk); + _offTripSaid = false; + Host.Log($"[RynthNav] walk: keeping to the trip's path for step {step + 1} ({_follow.Length:F0}u, {walk.Length} points)"); + return _follow; + } + + /// Replan: the steer along the trip's path, when this step has one and its end isn't next. Null = plan as before. + private (float Ew, float Up, float Ns)? FollowSteer() + { + if (CurrentFollow() is not TripFollow follow) return null; + WorldPt aim = follow.Aim(_wx, _wy, out double off, out bool atEnd); + if (atEnd) return null; + if (off > TripFollow.OffUnits && !_offTripSaid) + { + _offTripSaid = true; + Host.Log($"[RynthNav] walk: {off:F0}u off the trip's path at {NavCoords.Fmt(NavCoords.NsFromWorld(_wy), NavCoords.EwFromWorld(_wx))}: heading back to it"); + } + else if (off <= TripFollow.OffUnits) _offTripSaid = false; + double up = double.IsNaN(aim.H) ? _wz : aim.H; + return ((float)aim.X, (float)up, (float)aim.Y); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Inside.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Inside.cs new file mode 100644 index 0000000..01803a2 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Inside.cs @@ -0,0 +1,237 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Text; +using RynthCore.Plugin.Shared; +using RynthNav.Routing; + +namespace RynthCore.Plugin.RynthNav; + +// Going to someone INSIDE a dungeon (2026-11-27; InsidePlaces.cs has the choices). /rnav go for a person, +// vendor, lifestone or landmark the Atlas has in a dungeon cell: +// * already in that dungeon: arrived; +// * a portal on the map into it: the usual go into that portal (a route with portals and recalls when far); +// * a recall you know that lands in it: cast, as a one-step route. +// Arriving, the line ends "( is in cell XXXXXXXX)", and (Walk inside on, the default) the walk to that +// cell is handed to RynthAi's dungeon map: /ra dunnav-to cell walkonly , a walk with fighting, +// looting, buffing and the meta off, put back after (2026-11-27). "Fight on the way in" (/rnav inside fight on, +// off by default) hands it over without walkonly: the macro as set, fighting and looting on the way, as its +// other dungeon walks do. RynthNav has no navmesh in dungeons. "/rnav inside a || b" says which of those +// people is in the dungeon you're in, and never travels. Tick thread. +// Spotted by SilentKelpie (Forgejo rynth PR #12); re-implemented here. +public sealed partial class RynthNavPlugin +{ + /// The go's target inside a dungeon: the name (the goto's own name) and its cell (0 = none). + private string _insideName = ""; + private uint _insideCell; + /// Hand the walk inside to RynthAi on arrival (rynthnav.json insideWalk). + private volatile bool _insideWalkOn = true; + /// The walk inside fights, loots and buffs on the way, the macro as set (rynthnav.json insideFight, off: + /// a walk only). + private volatile bool _insideFightOn; + /// A walk inside waiting to go to RynthAi: once the landing has settled. + private string _handoffName = ""; + private uint _handoffCell; + private long _handoffDueMs, _handoffGiveUpMs; + + private const long HandoffSettleMs = 2500, HandoffGiveUpMs = 30000; + + private void LoadInsideSettings() + { + _insideWalkOn = NavDataConfig.ReadSwitch("insideWalk", true); + _insideFightOn = NavDataConfig.ReadSwitch("insideFight", false); + } + + /// "a || b" for go: someone inside a dungeon, when no earlier candidate is on the map. True when handled. + private bool TryGoInsideAlternative(string text) + { + bool hasPos = PlayerMapPos(out double pns, out double pew); + AtlasLocation? inside = InsidePlaces.FromAlternatives(_atlas, text, hasPos, pns, pew, CurrentLandblock); + return inside != null && GoInside(inside); + } + + /// One name for go: someone inside a dungeon when the map has nothing better for it. True when handled. + private bool TryGoInside(string text) + { + if (text.Length == 0 || _store.FindFavorite(text) != null || NavCoords.TrySplitCoordsAndName(text, out _, out _, out _)) return false; + bool hasPos = PlayerMapPos(out double pns, out double pew); + AtlasLocation? inside = InsidePlaces.Prefer(_atlas, text, hasPos, pns, pew, CurrentLandblock, out _); + return inside != null && GoInside(inside); + } + + /// + /// route / arrow for someone inside a dungeon: the portal into it, as the target (its name says who for). + /// False when the name isn't someone inside, or there's no portal on the map into their dungeon (said). + /// + private bool InsideTarget(string text, out string name, out string type, out double ns, out double ew, out bool handled) + { + name = ""; type = ""; ns = 0; ew = 0; handled = false; + if (text.Length == 0 || _store.FindFavorite(text) != null || NavCoords.TrySplitCoordsAndName(text, out _, out _, out _)) return false; + bool hasPos = PlayerMapPos(out double pns, out double pew); + AtlasLocation? inside = InsidePlaces.Prefer(_atlas, text, hasPos, pns, pew, CurrentLandblock, out _); + if (inside == null) return false; + handled = true; + InsideWay w = InsidePlaces.WayIn(_atlas, inside, _cellId, hasPos, pns, pew, _known, _recallsEnabled); + if (w.Portal == null) + { + Note(w.Kind == InsideWayKind.Here ? $"{inside.Name} is inside {w.Dungeon}, where you are{InsidePlaces.Tail(inside.Name, w.Cell)}" + : w.Kind == InsideWayKind.Recall ? $"{inside.Name} is inside {w.Dungeon}; no portal on the map leads there, but {w.Recall!.Name} does: /rnav go {inside.Name}" + : InsidePlaces.NoWayText(w)); + return false; + } + name = $"{w.Portal.Name} (into {w.Dungeon}, for {inside.Name})"; type = "Portal"; ns = w.Portal.Ns; ew = w.Portal.Ew; + return true; + } + + /// The way into 's dungeon, started. True when handled (gone, or why not said). + private bool GoInside(AtlasLocation place) + { + if (!_hasPose) { Note("goto: no player position yet"); return true; } + bool hasPos = PlayerMapPos(out double pns, out double pew); + InsideWay w = InsidePlaces.WayIn(_atlas, place, _cellId, hasPos, pns, pew, _known, _recallsEnabled); + if (w.Cell == 0) return false; + switch (w.Kind) + { + case InsideWayKind.Here: + _insideName = place.Name; _insideCell = w.Cell; + _gotoName = place.Name; + Host.Log($"[RynthNav] goto {place.Name}: already in {w.Dungeon} (cell {w.Cell:X8})"); + Say($"goto: you're in {w.Dungeon}: {place.Name} is inside{InsidePlaces.Tail(place.Name, w.Cell)}"); + QueueHandoff(place.Name, w.Cell, 0); + return true; + case InsideWayKind.Portal: + _insideName = place.Name; _insideCell = w.Cell; + _nextEnterPortal = w.Portal!.Name; // the portal object a saved nav route names (RynthNavPlugin.SaveRoute.cs) + Say($"goto: {place.Name} is inside {w.Dungeon}: going in by {w.Portal.Name} at {NavCoords.Fmt(w.Portal.Ns, w.Portal.Ew)}"); + StartGoto(place.Name, place.Type, w.Portal.Ns, w.Portal.Ew, w.Dungeon, "Dungeon"); + return true; + case InsideWayKind.Recall: + StartRecallInto(place, w); + return true; + default: + Note("goto: " + InsidePlaces.NoWayText(w)); + return true; + } + } + + /// A goto of one recall step into the dungeon: cast, wait for the teleport, arrive (the usual recall step and settle). + private void StartRecallInto(AtlasLocation place, InsideWay w) + { + AtlasRecall r = w.Recall!; + if (_gotoActive) { _gotoActive = false; _route = null; _portalWait = false; ResetHub(); AutoRun.Stop(); HideMarkers("a new goto"); } + if (_recallWait) EndRecall(); + _goJobId = 0; _paused = false; + _landReplanned = false; _tripReplans = 0; _enterPortal = ""; _nextEnterPortal = ""; + _portalWait = false; _portalWaitTicks = 0; _wasPortaling = false; _settling = false; + _enterName = ""; _enterType = ""; + _finalTew = _wx; _finalTns = _wy; + ResetHub(); + _routeRecalls = new List { new() { Name = r.Name, SpellId = r.SpellId, CastSeconds = RecallPlanner.SpellCastSeconds } }; + bool hasPos = PlayerMapPos(out double pns, out double pew); + _route = new List { new(hasPos ? pns : 0, hasPos ? pew : 0, usePortal: false, useRecall: true, r.Name, 0, double.NaN, double.NaN) }; + _routeIdx = 0; + _tripEst = double.NaN; + _shownRoute = _route; _shownRouteFor = place.Name; _shownRouteEst = 0; _shownRouteLive = true; _routeVersion++; + _insideName = place.Name; _insideCell = w.Cell; + _gotoActive = true; + _gotoName = place.Name; _gotoType = place.Type; + _walkHaveLast = false; + AutoRun.Forget(); + Host.Log($"[RynthNav] goto {place.Name} (inside {w.Dungeon}, cell {w.Cell:X8}) by {r.Name}"); + Say($"goto: {place.Name} is inside {w.Dungeon}: casting {r.Name} — /rnav stop to cancel"); + BeginRecallStep(); + } + + /// + /// FinishGoto: the arrival line's tail for a target inside a dungeon, and the walk inside queued for RynthAi. + /// The target is forgotten either way. "" when this goto wasn't for someone inside, or didn't get there. + /// + private string TakeInsideTail(string status) + { + string name = _insideName; + uint cell = _insideCell; + _insideName = ""; _insideCell = 0; + if (cell == 0 || !status.StartsWith("arrived", StringComparison.Ordinal) || !name.Equals(_gotoName, StringComparison.Ordinal)) return ""; + if (CurrentLandblock != cell >> 16) return ""; + QueueHandoff(name, cell, HandoffSettleMs); + return InsidePlaces.Tail(name, cell); + } + + private void QueueHandoff(string name, uint cell, long settleMs) + { + if (!_insideWalkOn) return; + _handoffName = name; _handoffCell = cell; + _handoffDueMs = NowMs + settleMs; _handoffGiveUpMs = NowMs + HandoffGiveUpMs; + } + + /// The walk inside, handed to RynthAi once the landing has settled (out of portal space). Tick thread. + private void TickInsideHandoff() + { + if (_handoffCell == 0) return; + long now = NowMs; + if (now > _handoffGiveUpMs || (_hasPose && CurrentLandblock != _handoffCell >> 16 && now > _handoffDueMs)) { _handoffCell = 0; return; } + if (now < _handoffDueMs || !_hasPose || (Host.HasIsPortaling && Host.IsPortaling())) return; + if (_gotoActive) { _handoffCell = 0; return; } // another goto started meanwhile: it wins + string cmd = InsidePlaces.WalkCommand(_handoffCell, _handoffName, _insideFightOn); + string name = _handoffName; + _handoffCell = 0; + if (SubmitToRynthAi(cmd)) Host.Log($"[RynthNav] inside: handed the walk to RynthAi: {cmd}"); + else Note($"goto: {name} is further in; RynthAi isn't loaded to walk the dungeon map there ({cmd})"); + } + + /// A command line through RynthAi's "RynthAi.Script" interface (its own commands run at once). False when RynthAi isn't there. + private unsafe bool SubmitToRynthAi(string line) + { + if (!Host.HasGetPluginInterface) return false; + var t = (RynthAiScriptApiV1*)Host.GetPluginInterface("RynthAi", RynthAiScriptApiV1.InterfaceName, RynthAiScriptApiV1.InterfaceVersion); + if (t == null || t->Version < 1 || t->StructSize < (uint)sizeof(RynthAiScriptApiV1) || t->SubmitCommand == null) return false; + byte[] utf8 = new byte[Encoding.UTF8.GetByteCount(line) + 1]; + Encoding.UTF8.GetBytes(line, 0, line.Length, utf8, 0); + fixed (byte* p = utf8) return t->SubmitCommand(p) != 0; + } + + /// + /// /rnav inside a || b: which of these people is in THIS dungeon, and in which cell (a script, already inside, + /// before it walks the dungeon). Never travels. /rnav inside walk on|off: hand the walk inside to RynthAi. + /// + private void CmdInside(string text) + { + string t = text.Trim(); + if (t.StartsWith("walk", StringComparison.OrdinalIgnoreCase) && (t.Length == 4 || t[4] == ' ')) + { + string a = t.Substring(4).Trim().ToLowerInvariant(); + if (a is "on" or "off") { _insideWalkOn = a == "on"; NavDataConfig.WriteSwitch("insideWalk", _insideWalkOn); } + else if (a.Length > 0) { SayFail("/rnav inside walk on|off — hand the walk inside a dungeon to RynthAi's dungeon map"); return; } + Say(_insideWalkOn ? "walk inside: ON — a go to someone inside a dungeon hands the last stretch to RynthAi's dungeon map (" + + (_insideFightOn ? "fighting on the way in: the macro as set)" : "a walk only: no fighting, looting or buffing)") + : "walk inside: OFF — a go to someone inside a dungeon stops at the way in"); + return; + } + // /rnav inside fight on|off (2026-11-27): the walk inside fights, loots and buffs on the way (off: a walk only). + if (t.StartsWith("fight", StringComparison.OrdinalIgnoreCase) && (t.Length == 5 || t[5] == ' ')) + { + string a = t.Substring(5).Trim().ToLowerInvariant(); + if (a is "on" or "off") { _insideFightOn = a == "on"; NavDataConfig.WriteSwitch("insideFight", _insideFightOn); } + else if (a.Length > 0) { SayFail("/rnav inside fight on|off — the walk inside a dungeon fights, loots and buffs on the way (off: a walk only)"); return; } + Say(_insideFightOn ? "fight on the way in: ON — RynthAi's walk inside a dungeon runs its macro as set (fights, loots and buffs on the way)" + : "fight on the way in: OFF — RynthAi's walk inside a dungeon is a walk only (fighting, looting, buffing and the meta off, put back after)"); + return; + } + if (t.Length == 0) { SayFail("/rnav inside [|| ...] — which of these is in this dungeon | inside walk on|off | inside fight on|off"); return; } + uint here = CurrentLandblock; + bool inDungeon = (_cellId & 0xFFFF) >= InsidePlaces.FirstDungeonCell; + string elsewhere = ""; + foreach (string raw in t.Split("||", StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + { + AtlasLocation? l = _atlas.FindInside(raw, here); + if (l == null || !Atlas.TryCell(l.Cell, out uint cell)) continue; + if (inDungeon && cell >> 16 == here) + { + Say($"inside: {l.Name} is here{InsidePlaces.Tail(l.Name, cell)}"); + return; + } + if (elsewhere.Length == 0) elsewhere = $"{l.Name} is in {InsidePlaces.DungeonName(_atlas, cell >> 16)}, not here"; + } + SayFail("inside: " + (elsewhere.Length > 0 ? elsewhere : "none of these is someone inside a dungeon: " + t.Replace("||", ","))); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Markers.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Markers.cs index 2f0a105..2e4ce8c 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Markers.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Markers.cs @@ -117,7 +117,7 @@ public sealed partial class RynthNavPlugin _markLb = CurrentLandblock; _saveConflict = ""; _saveDefault = NavRouteExport.SafeName("To " + goal); - if (_markersOn && buildPath) StartPathBuild(); + if ((_markersOn || FollowWantsPath(trip)) && buildPath) StartPathBuild(); // a goto keeps to it (RynthNavPlugin.Follow.cs) _markerStatus = "working out the path…"; return trip; } @@ -176,7 +176,7 @@ public sealed partial class RynthNavPlugin return; } var (path, ms, tiles) = task.Result; - if (_trip == null || path.TripId != _trip.Id) { if (_markersOn || _pendingSave != null) StartPathBuild(); return; } // planned for an older trip + if (_trip == null || path.TripId != _trip.Id) { if (_markersOn || _pendingSave != null || FollowWantsPath(_trip)) StartPathBuild(); return; } // planned for an older trip _tripPath = path; int points = 0; foreach (WorldPt[]? w in path.Walks) points += w?.Length ?? 0; diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Panel.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Panel.cs index 10b5e0b..cfe3b8d 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Panel.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Panel.cs @@ -170,6 +170,13 @@ public sealed partial class RynthNavPlugin sb.Append(",\"markers\":{\"on\":").Append(_markersOn ? 1 : 0).Append(",\"labels\":").Append(_markerLabels ? 1 : 0) .Append(",\"guide\":").Append(_markerGuide ? 1 : 0).Append(",\"shown\":").Append(trip != null && _tripShown ? 1 : 0) .Append(",\"status\":\"").Append(Esc(_markerStatus)).Append("\"}"); + // Someone inside a dungeon (RynthNavPlugin.Inside.cs): the walk inside handed to RynthAi, on or off, and + // whether it fights on the way (off: a walk only). + sb.Append(",\"inside\":{\"walk\":").Append(_insideWalkOn ? 1 : 0).Append(",\"fight\":").Append(_insideFightOn ? 1 : 0).Append('}'); + // This server's own portals (RynthNavPlugin.CustomPortals.cs). + AppendCustomJson(sb); + // Walks keep to the trip's path (RynthNavPlugin.Follow.cs). + sb.Append(",\"follow\":{\"on\":").Append(_followTrip ? 1 : 0).Append('}'); string pathJson = PathJson(); // the walking path, for the engine's World Map if (pathJson.Length > 0) sb.Append(",\"path\":").Append(pathJson); sb.Append(",\"save\":{\"can\":").Append(trip != null ? 1 : 0).Append(",\"for\":\"").Append(Esc(trip?.Goal ?? "")) diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Travel.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Travel.cs index 18110ed..183533b 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Travel.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Travel.cs @@ -120,6 +120,7 @@ public sealed partial class RynthNavPlugin private void InitTravel() { + LoadCustomPortals(); // this server's own portals (RynthNavPlugin.CustomPortals.cs) string path = NavFile("locations.json"); Task.Run(() => { @@ -156,7 +157,7 @@ public sealed partial class RynthNavPlugin private void OnLoginTravel() { - _charKey = ""; _playerName = ""; _known = null; _nextKnownMs = 0; + _charKey = ""; _playerName = ""; _known = null; _nextKnownMs = 0; _server = ""; _nearPortal = null; _pendingRecallSlot = null; _castRecallSpell = 0; _pendingTie = null; _selfCastMs = 0; _trkHaveLast = false; _trkPortaling = false; } @@ -168,6 +169,7 @@ public sealed partial class RynthNavPlugin _trkHaveLast = false; _trkPortaling = false; _known = null; _charKey = ""; SaveStores(force: true); + OnLogoutCustom(); } // ── Tick ───────────────────────────────────────────────────────────────── @@ -203,7 +205,9 @@ public sealed partial class RynthNavPlugin bool teleported = TrackTeleport(now); UpdateArrow(teleported); + TickInsideHandoff(); // the walk inside a dungeon, handed to RynthAi (RynthNavPlugin.Inside.cs) + TickCustomPortals(now, save: now >= _nextSaveMs); // RynthNavPlugin.CustomPortals.cs if (now >= _nextSaveMs) { _nextSaveMs = now + 3000; SaveStores(force: false); } RebuildTravelJson(); } @@ -321,6 +325,7 @@ public sealed partial class RynthNavPlugin // Your spell words shortly before portal space, standing still since, not dead, no portal // right beside you: a recall cast by hand (walking into a portal moves you; using one you // stand at doesn't, hence the portal check; dying is a trip, not a recall). + bool spellWords = _selfCastMs != 0 && startMs - _selfCastMs >= 0 && startMs - _selfCastMs < HandCastWindowMs; bool handCast = _selfCastMs != 0 && startMs - _selfCastMs >= 0 && startMs - _selfCastMs < HandCastWindowMs && !_selfCastDied && havePre && !portalBeside && Math.Sqrt((preWx - _selfCastWx) * (preWx - _selfCastWx) + (preWy - _selfCastWy) * (preWy - _selfCastWy)) < HandCastStillUnits; @@ -364,6 +369,9 @@ public sealed partial class RynthNavPlugin // Not a recall we know of: a portal, most likely. Portal Recall goes back to where // the last portal dropped you. A landing at a known recall's spot (a recall cast by // hand, or dying and waking at the lifestone) isn't a portal. + // A custom server's own portal you stood beside: its landing (RynthNavPlugin.CustomPortals.cs). Before the + // recall check: a portal into a town lands beside its recall spot. + LearnCustomPortal(havePre, preCell, preWx, preWy, startMs, landing, spellWords); if (landing.OnMap && LandsLikeARecall(landing)) return; string label = landing.Label; int? bitmask = null; @@ -1062,11 +1070,14 @@ public sealed partial class RynthNavPlugin private const string HelpText = "/rnav arrow | arrow off | arrow route — the arrow (one target: a new one replaces the route, and a walk elsewhere)\n" + "/rnav clear — no target: the walk stops, the route goes, the arrow goes off\n" + - "/rnav go — walk there (route with portals/recalls when /rnav portals on)\n" + + "/rnav go — walk there (route with portals/recalls when /rnav portals on); someone inside a dungeon: the way in, then RynthAi's dungeon map to them\n" + + "/rnav inside [|| ] — which of these is in this dungeon | inside walk on|off — hand the walk inside to RynthAi\n" + "/rnav route — plan a route (portals and recalls), no walking\n" + "/rnav route next — another way to the same place (switches a running goto) | route go — walk the way shown\n" + "/rnav atlas — find places | fav [place] — favorite | recalls [on|off] | tie 1|2|lifestone\n" + "/rnav goto | preview | portals on|off | stop | here | load | test | navdata\n" + + "/rnav portals scan [yd] | list | forget | clear confirm | custom on|off — this server's own portals (a landing is learned the first time you take one)\n" + + "/rnav follow on|off — walks keep to the trip's path (the markers), or plan their own way to the route's crossings\n" + "/rnav pause — stop walking, keep the trip on the map (drive by hand meanwhile) | resume — carry on\n" + "/rnav times — how long this character's trips take (run speed, portals, recalls, portal space)\n" + "/rnav avoid — show; avoid portals on|off| | walls on|off| | corners \n" + @@ -1087,6 +1098,8 @@ public sealed partial class RynthNavPlugin // "go a || b || c" (Oracle's Dynamic Stamps, any caller): the first candidate on the map. if (cmd is "go" or "goto" or "route" or "arrow" && rest.Contains("||", StringComparison.Ordinal)) { + // Someone inside a dungeon (RynthNavPlugin.Inside.cs), when no earlier candidate is on the map: the way in. + if (cmd is "go" or "goto") { _insideName = ""; _insideCell = 0; if (TryGoInsideAlternative(rest)) return; } if (!PickAlternative(rest, out string picked, out string why)) { Note(why); return; } rest = picked; } @@ -1105,11 +1118,7 @@ public sealed partial class RynthNavPlugin case "navdata": Say($"tiles and Atlas folder: {NavDataDir} ({NavConfig.Source}); route graph: {_graphStatus}; Town Network: {_townNetStatus}"); break; case "avoid": CmdAvoid(rest); break; case "aphus": CmdAphus(rest.Trim().ToLowerInvariant()); break; - case "portals": - _portalsEnabled = !rest.Equals("off", StringComparison.OrdinalIgnoreCase); - NavDataConfig.WriteSwitch("portals", _portalsEnabled); - Say($"portal and recall routing {(_portalsEnabled ? "ON" : "OFF")} for walking (go/goto)"); - break; + case "portals": CmdPortals(rest); break; // on|off, and this server's own portals (RynthNavPlugin.CustomPortals.cs) case "stop": DoMove(5); Say("stopped"); break; case "pause": CmdPause(); break; // RynthNavPlugin.Pause.cs case "times": CmdTimes(); break; // RynthNavPlugin.TripTime.cs @@ -1119,6 +1128,8 @@ public sealed partial class RynthNavPlugin CmdGo(rest); break; case "route": CmdRoute(rest); break; + case "inside": CmdInside(rest); break; // RynthNavPlugin.Inside.cs + case "follow": CmdFollow(rest); break; // RynthNavPlugin.Follow.cs case "arrow": CmdArrow(rest); break; case "clear": CmdClear(); break; // RynthNavPlugin.Target.cs case "atlas": CmdAtlas(rest); break; @@ -1180,7 +1191,11 @@ public sealed partial class RynthNavPlugin Say($"arrow route to {n}: {used} teleport(s). First: {StepText(_arrow.Current!)}{(rended.Length > 0 ? $" ({rended})" : "")}."); return; } - if (!ResolveTarget(rest, out string name, out string type, out double ns, out double ew, out string error)) { Note(error); return; } + string name, type; double ns, ew; + // Someone inside a dungeon: the arrow points at the portal into it (RynthNavPlugin.Inside.cs). + if (InsideTarget(rest, out name, out type, out ns, out ew, out bool inside)) { } + else if (inside) return; + else if (!ResolveTarget(rest, out name, out type, out ns, out ew, out string error)) { Note(error); return; } HeldTarget held = Held(); TargetChange c = TargetSwitch.For(NewTarget.Arrow, held, ns, ew); if (c.KeepArrow) @@ -1195,6 +1210,9 @@ public sealed partial class RynthNavPlugin private void CmdGo(string rest) { + // Someone inside a dungeon, when the map has nothing better for the name (RynthNavPlugin.Inside.cs). + _insideName = ""; _insideCell = 0; + if (TryGoInside(rest)) return; if (!ResolveGo(rest, out string name, out string type, out double ns, out double ew, out string enter, out string enterType, out string error)) { Note(error); @@ -1253,7 +1271,11 @@ public sealed partial class RynthNavPlugin // "route next": another way to the last place planned for; "route go": walk the way shown. if (rest.Equals("next", StringComparison.OrdinalIgnoreCase) || rest.Equals("another", StringComparison.OrdinalIgnoreCase)) { CmdRouteNext(); return; } if (rest.Equals("go", StringComparison.OrdinalIgnoreCase)) { CmdRouteGo(); return; } - if (!ResolveTarget(rest, out string name, out string type, out double ns, out double ew, out string error)) { Note(error); return; } + string name, type; double ns, ew; + // Someone inside a dungeon: the route to the portal into it (RynthNavPlugin.Inside.cs). + if (InsideTarget(rest, out name, out type, out ns, out ew, out bool inside)) { } + else if (inside) return; + else if (!ResolveTarget(rest, out name, out type, out ns, out ew, out string error)) { Note(error); return; } if (!_hasPose) { Note("no player pose yet"); return; } ShowRoute(name, type, ns, ew); } diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.cs index 99a636d..4821d1f 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.cs @@ -155,6 +155,8 @@ public sealed partial class RynthNavPlugin : RynthPluginBase _portalsEnabled = NavDataConfig.ReadSwitch("portals", true); _recallsEnabled = NavDataConfig.ReadSwitch("recalls", true); LoadAvoidSettings(); + LoadInsideSettings(); // RynthNavPlugin.Inside.cs + LoadFollowSettings(); // RynthNavPlugin.Follow.cs LoadMarkerSettings(); LoadMeshSettings(); Host.Log($"[RynthNav] Initialized v{PluginVersion} (tiled streaming + long-range goto + portal/recall routing + arrow + atlas + route maker). Panel: RynthNav. Tiles: {NavDataDir} ({NavConfig.Source})"); @@ -899,8 +901,10 @@ public sealed partial class RynthNavPlugin : RynthPluginBase AutoRun.Stop(); lock (_gate) _status = status; _gotoEndStatus = status; _gotoEndSeq++; // a route maker go job reads how it ended (RynthNavPlugin.RouteMaker.cs) - Host.Log($"[RynthNav] goto: {status}"); - Say(status == "arrived" && _gotoName.Length > 0 ? $"goto: arrived at {_gotoName}" : $"goto: {status}"); + // Someone inside a dungeon (RynthNavPlugin.Inside.cs): where in it, and the walk there handed on. + string inside = TakeInsideTail(status); + Host.Log($"[RynthNav] goto: {status}{inside}"); + Say((status == "arrived" && _gotoName.Length > 0 ? $"goto: arrived at {_gotoName}" : $"goto: {status}") + inside); _goNote = status == "arrived" && _gotoName.Length > 0 ? $"arrived at {_gotoName}" : status; if (status == "arrived") _wayChosenMs = 0; // there: the next trip there is planned afresh (RynthNavPlugin.Ways.cs) _enterName = ""; _enterType = ""; @@ -979,7 +983,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase private void EnsurePortalsLoaded() { - if (_portals != null) return; + if (_tsvPortals != null) return; var list = new List(); int withRules = 0; try @@ -1003,7 +1007,9 @@ public sealed partial class RynthNavPlugin : RynthPluginBase else Host.Log("[RynthNav] portals.tsv not found — portal routing off"); } catch (Exception ex) { Host.Log($"[RynthNav] portals load failed: {ex.Message}"); } - _portals = list; + // The route planner's list: these, then this server's custom portals (RynthNavPlugin.CustomPortals.cs). + _tsvPortals = list; _routeLinksKey = ""; + RefreshRoutePortals(); } // Returns the leg list if portals or recalls beat walking, else null (pure navmesh goto). @@ -1103,6 +1109,9 @@ public sealed partial class RynthNavPlugin : RynthPluginBase bool loadedMore = false; var steer = CoarseSteer(sRef, sPt, ref loadedMore); if (loadedMore) _query = new DtNavMeshQuery(_navMesh!); + // The trip's own path (RynthNavPlugin.Follow.cs): a few yards along the walk the markers draw, so the + // walk keeps to it instead of finding its own way to the route graph's next crossing. + if (FollowSteer() is { } along) steer = along; // Prefer a DIRECT path to the actual target when its tile is loaded — one stable // corridor we follow steadily. Only fall back to the 500u line-probe leapfrog when diff --git a/Plugins/RynthCore.Plugin.RynthNav/StuckWatch.cs b/Plugins/RynthCore.Plugin.RynthNav/StuckWatch.cs new file mode 100644 index 0000000..a780ee8 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthNav/StuckWatch.cs @@ -0,0 +1,72 @@ +using System; + +namespace RynthCore.Plugin.RynthNav; + +/// +/// Is the walk blocked? Until 2026-11-27 only a tick that ran counted, and a tick turning in place +/// started the watch again. A walk swinging between headings against a wall (run a moment, turn a +/// moment) never ran in a row, so it was never seen as blocked and stood +/// there until the 30 s progress watchdog stopped the goto. Now every tick the walk drives counts, +/// running or turning: moved less than over with +/// some running in it, or over of turning only, is blocked. A tick that +/// doesn't drive (standing, waiting for a plan) starts the watch again. Host-free: the route tests +/// drive it. +/// +internal sealed class StuckWatch +{ + /// A window with running in it: this long... + public const long RunWindowMs = 1200; + /// ...or this long turning only (a half turn on the spot takes about a second)... + public const long TurnWindowMs = 3000; + /// ...and moved less than this = blocked (a run covers 4+ u/s). + public const double MoveUnits = 0.6; + + private long _winMs; + private double _x, _y; + private bool _drove, _ranInWindow; + + /// The walk drove this tick: running, or turning in place ( false). + public void Drove(bool running) + { + _drove = true; + if (running) _ranInWindow = true; + } + + public void Reset() + { + _winMs = 0; + _drove = false; + _ranInWindow = false; + } + + /// + /// Once a walking tick, before steering: true when blocked (a window ended and the character + /// moved less than in it). and + /// describe the window that ended; both 0 when none did. + /// + public bool Check(long now, double x, double y, out double moved, out long windowMs) + { + moved = 0; + windowMs = 0; + bool drove = _drove; + _drove = false; + if (!drove || _winMs == 0) + { + Start(now, x, y); + return false; + } + long elapsed = now - _winMs; + if (elapsed < (_ranInWindow ? RunWindowMs : TurnWindowMs)) return false; + windowMs = elapsed; + moved = Math.Sqrt((x - _x) * (x - _x) + (y - _y) * (y - _y)); + Start(now, x, y); + return moved < MoveUnits; + } + + private void Start(long now, double x, double y) + { + _winMs = now; + _x = x; _y = y; + _ranInWindow = false; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthNav/TripFollow.cs b/Plugins/RynthCore.Plugin.RynthNav/TripFollow.cs new file mode 100644 index 0000000..dcee2e9 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthNav/TripFollow.cs @@ -0,0 +1,104 @@ +using System; + +namespace RynthCore.Plugin.RynthNav; + +/// +/// Keeps a goto on its trip's own path (2026-11-27). The trip's ground (TripPath: the walk the path markers draw +/// and "save as nav route" writes) is worked out once per step, but the walker never used it: every re-plan aimed +/// at the route graph's next border crossing (or straight at the step's point), so the walk took its own way, +/// across a field or round the far side of a building, away from the markers. +/// +/// Now each re-plan aims along the step's walk past where you are on it, and the navmesh +/// plans just those yards, so walls and the portal circles are kept out of as before. More than +/// off the walk (knocked off it, stepped round something), the aim is the walk again, a +/// little past its nearest point. How far along you are only ever grows, and the nearest point is looked for only +/// a little behind it, so a walk that comes back close to itself is never cut across. +/// Host-free: the route tests drive it. Spotted by SilentKelpie (Forgejo rynth PR #12); re-implemented here. +/// +internal sealed class TripFollow +{ + /// How far along the walk past where you are each re-plan aims (yards). + public const double AheadUnits = 28.0; + /// Farther than this from the walk is off it: aim back at it. + public const double OffUnits = 14.0; + /// Off the walk: aim this far past its nearest point. + public const double RejoinUnits = 6.0; + /// The nearest point on the walk is looked for this far behind the progress so far... + public const double BackUnits = 12.0; + /// ...and this far ahead of it. + public const double ForwardUnits = 90.0; + + private readonly WorldPt[] _pts; + private readonly double[] _along; // yards from the start to each point + private double _progress; + + public int TripId { get; } + public int Step { get; } + public double Length => _along[^1]; + /// How far along the walk you are (yards; never goes back). + public double Progress => _progress; + + public TripFollow(int tripId, int step, WorldPt[] pts) + { + if (pts == null || pts.Length < 2) throw new ArgumentException("a walk needs two points", nameof(pts)); + TripId = tripId; Step = step; + _pts = pts; + _along = new double[pts.Length]; + for (int i = 1; i < pts.Length; i++) _along[i] = _along[i - 1] + pts[i].FlatDistance(pts[i - 1]); + } + + /// + /// Where to plan to from (x, y): along the walk past where you are, or (more than + /// from it) a little past its nearest point. : yards from the walk. + /// : the aim is the walk's end (the step's own point: plan to it as before). + /// + public WorldPt Aim(double x, double y, out double off, out bool atEnd) + { + double s = NearestAlong(x, y, out off); + double aim; + if (off > OffUnits) aim = s + RejoinUnits; + else + { + if (s > _progress) _progress = s; + aim = _progress + AheadUnits; + } + atEnd = aim >= Length; + return atEnd ? _pts[^1] : At(aim); + } + + /// The point yards along the walk (its height between the points' heights). + public WorldPt At(double s) + { + s = Math.Clamp(s, 0, Length); + int i = 1; + while (i < _pts.Length - 1 && _along[i] < s) i++; + double seg = _along[i] - _along[i - 1]; + double t = seg < 1e-9 ? 0 : (s - _along[i - 1]) / seg; + WorldPt a = _pts[i - 1], b = _pts[i]; + return new WorldPt(a.X + (b.X - a.X) * t, a.Y + (b.Y - a.Y) * t, a.H + (b.H - a.H) * t); + } + + /// How far along the walk its nearest point to (x, y) is, within BackUnits behind and ForwardUnits ahead of the progress. + private double NearestAlong(double x, double y, out double dist) + { + double lo = Math.Max(0, _progress - BackUnits), hi = _progress + ForwardUnits; + double best = double.MaxValue, bestS = _progress; + for (int i = 1; i < _pts.Length; i++) + { + double s0 = _along[i - 1], s1 = _along[i]; + if (s1 < lo) continue; + if (s0 > hi) break; + double ax = _pts[i - 1].X, ay = _pts[i - 1].Y, vx = _pts[i].X - ax, vy = _pts[i].Y - ay; + double len = s1 - s0; + double t = len < 1e-9 ? 0 : Math.Clamp(((x - ax) * vx + (y - ay) * vy) / (len * len), 0, 1); + // Only the part of the segment inside the window counts. + double tLo = len < 1e-9 ? 0 : Math.Clamp((lo - s0) / len, 0, 1), tHi = len < 1e-9 ? 1 : Math.Clamp((hi - s0) / len, 0, 1); + t = Math.Clamp(t, tLo, tHi); + double px = ax + vx * t - x, py = ay + vy * t - y; + double d = Math.Sqrt(px * px + py * py); + if (d < best) { best = d; bestS = s0 + len * t; } + } + dist = best; + return bestS; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Data/CommunityWikiFeed.cs b/Plugins/RynthCore.Plugin.RynthOracle/Data/CommunityWikiFeed.cs new file mode 100644 index 0000000..a22bd43 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthOracle/Data/CommunityWikiFeed.cs @@ -0,0 +1,313 @@ +// The AC Community Wiki feed (2026-11-27): RynthOracle's own quest guide, read from asheron.fandom.com's public +// MediaWiki API (no login), on every server. OFF by default: nothing is fetched until the player turns it on, and +// the About tab, the Guide tab and "/ro wiki on" say what is read and from where before the first read. +// Only the reader ships: no wiki text is bundled. The read follows SilentKelpie's (Forgejo rynth PR #12); +// re-implemented here. What it reads: +// - the quests: every page with the {{Quest Summary}} box, and the pages under Category:Quests (its +// sub-categories followed, item / NPC / image lists left out); +// - the kill tasks: Category:Kill_Tasks and its sub-categories; +// - the society quests: Category:Society_Quests, each page's rank from the sub-category it is in; +// - the contracts: Category:Contracts' item pages. +// Only pages edited since the last read are fetched (their revision ids), unless the page reader is newer +// (QuestWikiText.ReaderVersion). Saved to %APPDATA%\RynthCore\RynthOracle\community-wiki-guide.json. The read runs +// on a pool thread and only builds a new guide and writes the file; the pump takes it (TakeResult). With the feed +// on, it reads at login when the saved copy is a day old (or none), and on "Read now". +using System; +using System.Collections.Generic; +using System.IO; +using System.Net.Http; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthOracle.Data; + +internal sealed class CommunityWikiFeed +{ + public const string Host = "asheron.fandom.com"; + public const string Api = "https://asheron.fandom.com/api.php"; + public const string WikiBase = "https://asheron.fandom.com/wiki/"; + public const string QuestTemplate = "Template:Quest_Summary"; + public const string QuestsCategory = "Category:Quests"; + public const string KillTasksCategory = "Category:Kill_Tasks"; + public const string SocietyCategory = "Category:Society_Quests"; + public const string ContractsCategory = "Category:Contracts"; + public static readonly TimeSpan RefreshAfter = TimeSpan.FromHours(24); + /// Category:Quests is a tree: at most this many categories are followed. + internal const int MaxCategories = 400; + /// No read lists more pages than this (a wiki that grew wildly, or a loop). + internal const int MaxPages = 5000; + private const int RequestGapMs = 250; + + /// What the feed reads and from where: said before the first read (About, Guide, /ro wiki on). + public const string WhatItReads = + "the quest, kill task, society quest and contract pages of the AC Community Wiki, from " + Api + + " (public pages, no login; about a thousand pages the first time, then only the pages edited since; " + + "requests a quarter second apart). Nothing about you or your character is sent."; + + /// Where the tests keep the guide file (a scratch path); null is the player's %APPDATA% copy. + internal static string? PathOverride; + + public static string DefaultPath => PathOverride ?? Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "RynthOracle", "community-wiki-guide.json"); + + private readonly string _path; + private CancellationTokenSource? _cts; + private Task? _task; + private volatile QuestGuide? _ready; + private volatile string _status; + private bool _loginReadDone; + + /// The guide in use (pump thread): the saved one until a read replaces it. + public QuestGuide Guide { get; private set; } = new(); + /// Goes up when is replaced. + public int Revision { get; private set; } + public bool Running => _task is { IsCompleted: false }; + public string Status => _status; + public string FilePath => _path; + + public CommunityWikiFeed(string? path = null) + { + _path = path ?? DefaultPath; + try + { + if (File.Exists(_path)) Guide = QuestGuide.Parse(File.ReadAllText(_path)); + } + catch { Guide = new QuestGuide(); } + _status = Guide.IsEmpty ? "not read yet" : Summary(Guide); + } + + public static string Summary(QuestGuide g) => + $"{g.Quests.Count} quests, {g.KillTasks.Count} kill tasks, {g.Society.Count} society quests, {g.Contracts.Count} contracts" + + (g.UpdatedUtc == DateTime.MinValue ? "" : $" (read {g.UpdatedUtc.ToLocalTime():yyyy-MM-dd HH:mm})"); + + /// The saved guide wants reading: none yet, a day old, or made by an older page reader. + internal static bool Due(QuestGuide g, DateTime utcNow) => + g.IsEmpty || g.Reader < QuestWikiText.ReaderVersion || utcNow - g.UpdatedUtc >= RefreshAfter; + + /// Pump thread, at login with the feed on: one read a session, when the saved guide is due. True when it started one. + public bool LoginRead(bool on, bool daily, DateTime utcNow) + { + if (!on || !daily || _loginReadDone) return false; + _loginReadDone = true; + return Due(Guide, utcNow) && Start(on); + } + + /// Starts a read: only with the feed on, and not while one runs. Pump thread. + public bool Start(bool on) + { + if (!on || Running) return false; + _cts?.Dispose(); + _cts = new CancellationTokenSource(); + CancellationToken token = _cts.Token; + QuestGuide old = Guide; + _status = "reading..."; + _task = Task.Run(async () => + { + try { _status = await ReadAsync(old, token).ConfigureAwait(false); } + catch (OperationCanceledException) { _status = "stopped"; } + catch (Exception ex) { _status = "couldn't read the wiki: " + ex.GetType().Name + ": " + ex.Message; } + }, token); + return true; + } + + /// Stops a read under way (the feed turned off). Pump thread. + public void Stop() + { + try { _cts?.Cancel(); } catch { } + } + + /// Pump thread: takes a finished read's guide; true when the guide changed. + public bool TakeResult() + { + QuestGuide? g = _ready; + if (g == null) return false; + _ready = null; + Guide = g; + Revision++; + return true; + } + + /// Uses a guide (the tests). + internal void Use(QuestGuide g) + { + Guide = g; + Revision++; + } + + public void Shutdown() + { + try { _cts?.Cancel(); _task?.Wait(2000); } catch { } + } + + // ── The read (pool thread) ────────────────────────────────────────────── + + private static readonly Regex RankRx = new(@"(?:^|:\s*)(\w+)\s+Rank\b", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + + /// The society rank a society sub-category stands for ("Society Quests: Knight Rank" is Knight), or "". + internal static string RankOf(string category) + { + Match m = RankRx.Match(category); + if (m.Success) return char.ToUpperInvariant(m.Groups[1].Value[0]) + m.Groups[1].Value.Substring(1).ToLowerInvariant(); + return category.Contains("Joining", StringComparison.OrdinalIgnoreCase) ? "Joining" : ""; + } + + /// A sub-category not followed: item, NPC, image and map lists, not quests. + internal static bool SkipCategory(string category) => + category.Contains("Quest Items", StringComparison.OrdinalIgnoreCase) + || category.Contains("Items", StringComparison.OrdinalIgnoreCase) && !category.Contains("Quest", StringComparison.OrdinalIgnoreCase) + || category.Contains("NPC", StringComparison.OrdinalIgnoreCase) + || category.Contains("Images", StringComparison.OrdinalIgnoreCase) + || category.Contains("Maps", StringComparison.OrdinalIgnoreCase); + + private async Task ReadAsync(QuestGuide old, CancellationToken token) + { + using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(30) }; + http.DefaultRequestHeaders.UserAgent.ParseAdd("RynthOracle/" + RynthOraclePlugin.Version + " (RynthCore quest guide)"); + + var titles = new SortedSet(StringComparer.Ordinal); + var killTasks = new SortedSet(StringComparer.Ordinal); + var contracts = new SortedSet(StringComparer.Ordinal); + var society = new Dictionary(StringComparer.OrdinalIgnoreCase); + void Add(string p) { if (titles.Count < MaxPages) titles.Add(p); } + + _status = "listing the quest pages..."; + await ListAsync(http, "embeddedin", new[] { ("list", "embeddedin"), ("eititle", QuestTemplate), ("einamespace", "0"), ("eilimit", "max") }, + Add, _ => { }, token).ConfigureAwait(false); + await WalkAsync(http, QuestsCategory, (p, _) => Add(p), token).ConfigureAwait(false); + _status = "listing the kill tasks..."; + await WalkAsync(http, KillTasksCategory, (p, _) => { killTasks.Add(p); Add(p); }, token).ConfigureAwait(false); + _status = "listing the society quests..."; + await WalkAsync(http, SocietyCategory, (p, cat) => + { + Add(p); + string rank = RankOf(cat); + if (rank.Length > 0) society.TryAdd(p, rank); + }, token).ConfigureAwait(false); + _status = "listing the contracts..."; + await ListAsync(http, "categorymembers", new[] { ("list", "categorymembers"), ("cmtitle", ContractsCategory), ("cmlimit", "max"), ("cmtype", "page") }, + p => { contracts.Add(p); Add(p); }, _ => { }, token).ConfigureAwait(false); + if (titles.Count == 0) return "the wiki listed no quest pages"; + + var list = new List(titles); + var revs = new Dictionary(StringComparer.Ordinal); + int done = 0; + foreach (string batch in QuestWikiText.Batches(list)) + { + _status = $"checking pages ({done}/{list.Count})..."; + string json = await GetAsync(http, QuestWikiText.ApiUrl(Api, ("action", "query"), ("prop", "info"), ("titles", batch)), token).ConfigureAwait(false); + foreach (KeyValuePair kv in QuestWikiText.LastRevisions(json)) revs[kv.Key] = kv.Value; + done += QuestWikiText.TitlesPerRequest; + } + List changed = PagesToRead(old, revs); + + var fresh = new Dictionary(StringComparer.Ordinal); + var freshContracts = new Dictionary(StringComparer.Ordinal); + int read = 0; + foreach (string batch in QuestWikiText.Batches(changed)) + { + _status = $"reading pages ({read}/{changed.Count})..."; + string json = await GetAsync(http, QuestWikiText.ApiUrl(Api, ("action", "query"), ("prop", "revisions"), ("rvprop", "content|ids"), + ("rvslots", "main"), ("titles", batch)), token).ConfigureAwait(false); + foreach (var (title, rev, text) in QuestWikiText.Contents(json)) + { + if (QuestWikiText.IsQuestPage(text)) fresh[title] = QuestWikiText.ParseQuest(title, text, rev, WikiBase); + else if (contracts.Contains(title) && QuestWikiText.IsContractPage(title, text)) + freshContracts[title] = QuestWikiText.ParseContract(title, text, rev, WikiBase); + } + read += QuestWikiText.TitlesPerRequest; + } + + QuestGuide g = Merge(old, revs, fresh, freshContracts, DateTime.UtcNow); + g.KillTasks = new List(killTasks); + g.Society = society; + token.ThrowIfCancellationRequested(); + string saved = ""; + try + { + Directory.CreateDirectory(Path.GetDirectoryName(_path)!); + File.WriteAllText(_path + ".tmp", g.ToJson()); + File.Move(_path + ".tmp", _path, overwrite: true); + } + catch (Exception ex) { saved = "; couldn't save it: " + ex.Message; } + _ready = g; + return $"{Summary(g)}; {fresh.Count + freshContracts.Count} pages read now{saved}"; + } + + /// The pages to read: new or edited since the saved guide; every one when it came from an older reader. + internal static List PagesToRead(QuestGuide old, IReadOnlyDictionary revs) + { + var known = new Dictionary(StringComparer.Ordinal); + foreach (GuideQuest q in old.Quests) known[q.Title] = q.Rev; + foreach (GuideContract c in old.Contracts) known[c.Title] = c.Rev; + bool whole = old.Reader < QuestWikiText.ReaderVersion; + var changed = new List(); + foreach (KeyValuePair kv in revs) + if (whole || kv.Value == 0 || !known.TryGetValue(kv.Key, out long rev) || rev != kv.Value) changed.Add(kv.Key); + return changed; + } + + /// + /// The new guide: the pages listed now, each the fresh read when there is one, else the saved one. A page no longer + /// listed goes; a page that isn't a quest or contract isn't kept (it is checked again next time). + /// + internal static QuestGuide Merge(QuestGuide old, IReadOnlyDictionary listed, + IReadOnlyDictionary fresh, IReadOnlyDictionary freshContracts, DateTime utcNow) + { + var oldQuests = new Dictionary(StringComparer.Ordinal); + foreach (GuideQuest q in old.Quests) oldQuests[q.Title] = q; + var oldContracts = new Dictionary(StringComparer.Ordinal); + foreach (GuideContract c in old.Contracts) oldContracts[c.Title] = c; + var g = new QuestGuide { Source = Host, UpdatedUtc = utcNow, Reader = QuestWikiText.ReaderVersion, KillTasks = old.KillTasks, Society = old.Society }; + foreach (string title in listed.Keys) + { + if (fresh.TryGetValue(title, out GuideQuest? f)) g.Quests.Add(f); + else if (oldQuests.TryGetValue(title, out GuideQuest? o)) g.Quests.Add(o); + if (freshContracts.TryGetValue(title, out GuideContract? fc)) g.Contracts.Add(fc); + else if (oldContracts.TryGetValue(title, out GuideContract? oc)) g.Contracts.Add(oc); + } + g.Quests.Sort((a, b) => string.Compare(a.Title, b.Title, StringComparison.OrdinalIgnoreCase)); + g.Contracts.Sort((a, b) => string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase)); + return g; + } + + /// A category's pages and, breadth first, its sub-categories' (each page with the category it was in). + private static async Task WalkAsync(HttpClient http, string root, Action page, CancellationToken token) + { + var queue = new Queue(); + var seen = new HashSet(StringComparer.OrdinalIgnoreCase) { root.Replace('_', ' '), root }; + queue.Enqueue(root); + while (queue.Count > 0 && seen.Count <= MaxCategories) + { + string cat = queue.Dequeue(); + await ListAsync(http, "categorymembers", new[] { ("list", "categorymembers"), ("cmtitle", cat), ("cmlimit", "max"), ("cmtype", "page|subcat") }, + p => page(p, cat), sub => { if (!SkipCategory(sub) && seen.Add(sub)) queue.Enqueue(sub); }, token).ConfigureAwait(false); + } + } + + private static async Task ListAsync(HttpClient http, string listName, (string, string)[] args, Action page, Action sub, CancellationToken token) + { + var cont = new List<(string, string)>(); + for (int i = 0; i < 100; i++) + { + var all = new List<(string, string)> { ("action", "query") }; + all.AddRange(args); + all.AddRange(cont); + string json = await GetAsync(http, QuestWikiText.ApiUrl(Api, all.ToArray()), token).ConfigureAwait(false); + var (pages, subs, next) = QuestWikiText.Members(json, listName); + foreach (string p in pages) page(p); + foreach (string s in subs) sub(s); + if (next.Count == 0) return; + cont = next; + } + } + + private static async Task GetAsync(HttpClient http, string url, CancellationToken token) + { + await Task.Delay(RequestGapMs, token).ConfigureAwait(false); + using HttpResponseMessage resp = await http.GetAsync(url + "&maxlag=5", token).ConfigureAwait(false); + resp.EnsureSuccessStatusCode(); + return await resp.Content.ReadAsStringAsync(token).ConfigureAwait(false); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Data/GuideProgress.cs b/Plugins/RynthCore.Plugin.RynthOracle/Data/GuideProgress.cs new file mode 100644 index 0000000..a40a57d --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthOracle/Data/GuideProgress.cs @@ -0,0 +1,383 @@ +// Where a guide quest stands for this character (2026-11-27), worked out from the quest flags (/myquests) and the +// stamps seen in chat this session. The four states, the kill tasks' counts and "first time / done before", and the +// kill lines in chat follow SilentKelpie's Guide (Forgejo rynth PR #12); re-implemented here. +// - A stamp is held when /myquests has its flag (any spelling: GuideStamp.Key) or it was stamped this session. +// - For a repeatable quest, a held stamp counts for this run while its flag's timer runs (or, with no timer on the +// flag, while the quest's repeat time since it was stamped hasn't passed); after that it was done "earlier". +// - The quest's wait is the longest redo time left on any held stamp. +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text.RegularExpressions; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthOracle.Data; + +/// A quest's state in the guide's lists. +internal enum GuideState +{ + /// No stamp held. + NotDone, + /// Some stamps held, some still to get, the held ones' redo timer still running. + PartWaiting, + /// Some stamps held, some still to get, no timer left. + PartReady, + /// Every stamp held. + Done, +} + +/// A stamp of a quest for this run. +internal enum StampState { Missing, Done, Earlier } + +/// A kill task's progress, in the order the Kill Tasks list shows them. +internal enum KillState { TurnIn, Counting, Ready, NotStarted, Waiting, Completed } + +/// What the guide knows of this character: its flags, the stamps seen this session and the kill lines. +internal sealed class GuideProgress +{ + private readonly QuestFlagStore _flags; + private readonly HashSet _sessionStamps; + private readonly KillChat _kills; + private Dictionary? _byKey; + private int _byKeyRevision = -1; + + public GuideProgress(QuestFlagStore flags, HashSet sessionStamps, KillChat kills) + { + _flags = flags; + _sessionStamps = sessionStamps; + _kills = kills; + } + + /// The flag a stamp is in /myquests, by any spelling of it, or null. + public QuestFlag? FlagOf(string stamp) + { + if (_flags.TryGet(stamp, out QuestFlag f)) return f; + if (_byKeyRevision != _flags.Revision || _byKey == null) + { + _byKey = new Dictionary(StringComparer.Ordinal); + foreach (KeyValuePair kv in _flags.Flags) _byKey.TryAdd(GuideStamp.Key(kv.Key), kv.Value); + _byKeyRevision = _flags.Revision; + } + return _byKey.TryGetValue(GuideStamp.Key(stamp), out QuestFlag? byKey) ? byKey : null; + } + + public bool StampedThisSession(string stamp) => _sessionStamps.Contains(GuideStamp.Key(stamp)); + + /// A stamp of for this run (see the file's note). + public StampState StateOf(GuideQuest q, string stamp, DateTime utcNow) + { + if (StampedThisSession(stamp)) return StampState.Done; + if (FlagOf(stamp) is not QuestFlag f) return StampState.Missing; + if (q.RepeatSec == 0) return StampState.Done; + if (f.RepeatTime > TimeSpan.Zero) return f.NextAvailableTime(utcNow) > TimeSpan.Zero ? StampState.Done : StampState.Earlier; + if (q.RepeatSec > 0 && f.CompletedOnUtc != DateTime.MinValue) + return f.CompletedOnUtc.AddSeconds(q.RepeatSec) > utcNow ? StampState.Done : StampState.Earlier; + return StampState.Done; + } + + /// The longest redo time left on the quest's held stamps; zero when none runs. + public TimeSpan Wait(GuideQuest q, DateTime utcNow) + { + TimeSpan wait = TimeSpan.Zero; + foreach (string st in q.AllStamps()) + { + if (FlagOf(st) is not QuestFlag f) continue; + TimeSpan left = TimeSpan.Zero; + if (f.RepeatTime > TimeSpan.Zero) left = f.NextAvailableTime(utcNow); + else if (q.RepeatSec > 0 && f.CompletedOnUtc != DateTime.MinValue) left = f.CompletedOnUtc.AddSeconds(q.RepeatSec) - utcNow; + if (left > wait) wait = left; + } + return wait; + } + + /// A quest's row: its state, the list's short text, the tooltip's sentence, and whether "Hide done" leaves it out. + public readonly record struct Row(GuideState State, string Status, string Tip, bool HideWhenDone, int Held, int All); + + /// + /// A quest with stamps: the four states from the stamps held and the wait. Without stamps (the AC Community Wiki + /// lists none for most quests), (the quest list's flag of its name) gives Done or Not done, + /// and null means its state isn't known. + /// + public Row RowOf(GuideQuest q, DateTime utcNow, bool? flagDone = null) + { + List stamps = q.AllStamps(); + if (stamps.Count == 0) + { + if (flagDone is bool fd) + return fd ? new Row(GuideState.Done, "Done", "Done: the quest list's flag for it is held.", q.RepeatSec == 0, 1, 1) + : new Row(GuideState.NotDone, "Not done", "Not done: the quest list's flag for it isn't held yet.", false, 0, 1); + return new Row(GuideState.NotDone, "no stamps", "The wiki lists no stamps for this quest and the quest list has no flag of its name, so its state isn't known.", false, 0, 0); + } + int held = 0, now = 0; + foreach (string st in stamps) + { + StampState s = StateOf(q, st, utcNow); + if (s != StampState.Missing) held++; + if (s == StampState.Done) now++; + } + TimeSpan wait = Wait(q, utcNow); + bool repeats = q.RepeatSec != 0 || wait > TimeSpan.Zero; + GuideState state = held == 0 ? GuideState.NotDone : held >= stamps.Count ? GuideState.Done + : wait > TimeSpan.Zero ? GuideState.PartWaiting : GuideState.PartReady; + (string status, string tip) = Text(state, held, stamps.Count, wait, repeats); + bool hide = state == GuideState.Done && (!repeats || wait > TimeSpan.Zero || now == stamps.Count); + return new Row(state, status, tip, hide, held, stamps.Count); + } + + /// The list's short status and the tooltip's sentence. + public static (string Status, string Tip) Text(GuideState s, int held, int all, TimeSpan wait, bool repeats) => s switch + { + GuideState.Done when wait > TimeSpan.Zero => ("Done " + Short(wait), $"Done: all {all} stamps held. It can be done again in {Short(wait)}."), + GuideState.Done when repeats => ("Done, redo", $"Done: all {all} stamps held, and its timer is up: it can be done again now."), + GuideState.Done => ("Done", $"Done: all {all} stamps held."), + GuideState.PartWaiting => ($"{held}/{all} wait {Short(wait)}", $"Part done: {held} of {all} stamps held, {all - held} still to get. The redo timer has {Short(wait)} left."), + GuideState.PartReady => ($"{held}/{all} ready", $"Part done: {held} of {all} stamps held, {all - held} still to get. No timer is running: go get them."), + _ => ("Not done", $"Not done: none of its {all} stamps held yet."), + }; + + /// "3d 4h", "5h 12m", "9m". + public static string Short(TimeSpan t) + { + if (t.TotalDays >= 1) return $"{(int)t.TotalDays}d {t.Hours}h"; + if (t.TotalHours >= 1) return $"{(int)t.TotalHours}h {t.Minutes:00}m"; + return $"{Math.Max(1, (int)Math.Ceiling(t.TotalMinutes))}m"; + } + + /// "Daily (every 20h 00m)", "Weekly (every 7d 0h)", "One-time", or the wiki's own words. + public static string RepeatText(GuideQuest q) + { + if (q.RepeatSec == 0) return q.Repeat.Length > 0 ? "One-time (" + q.Repeat + ")" : "One-time"; + if (q.RepeatSec < 0) return "Repeats: " + q.Repeat; + string every = Short(TimeSpan.FromSeconds(q.RepeatSec)); + return q.IsDaily ? $"Daily (every {every})" : q.IsWeekly ? $"Weekly (every {every})" : $"Repeats every {every}"; + } + + // ── Kill tasks ────────────────────────────────────────────────────────── + + /// A kill task's progress: kills and goal, where the count came from, its state and whether it was done before. + public sealed record Kill(KillState State, int Kills, int Goal, QuestFlag? Counter, bool FromChat, string Status, bool DoneBefore); + + /// + /// The task's counter flag: a stamp of it /myquests holds with a solve limit over 1, else a kill-task flag that names its creature. + /// + public QuestFlag? KillCounter(GuideQuest q) + { + foreach (string st in q.AllStamps()) + if (FlagOf(st) is QuestFlag f && f.MaxSolves > 1) return f; + string key = q.KillCreatureKey; + if (key.Length < 5) return null; + foreach (QuestFlag f in _flags.Flags.Values) + if (QuestTimer.IsKillTask(f) && GuideStamp.Key(f.Key).Contains(key, StringComparison.Ordinal)) return f; + return null; + } + + public Kill KillOf(GuideQuest q, DateTime utcNow, bool? flagDone = null) + { + int goal = q.KillTarget, kills = 0; + QuestFlag? counter = KillCounter(q); + if (counter != null) + { + kills = counter.Solves; + if (counter.MaxSolves > 1) goal = counter.MaxSolves; + } + bool fromChat = false; + // A kill line newer than the last /myquests read wins: it moves with every kill. + if (_kills.For(q.KillCreatureKey) is KillCount k && k.AtUtc > _flags.LastReadUtc && (k.Goal > 0 || k.Kills > 0)) + { + kills = k.Kills; + if (k.Goal > 0) goal = k.Goal; + fromChat = true; + } + Row row = RowOf(q, utcNow, flagDone); + TimeSpan wait = Wait(q, utcNow); + bool counted = counter != null || fromChat; + KillState state; + string status; + if (counted && goal > 0 && kills < goal && !(row.HideWhenDone && wait > TimeSpan.Zero)) { state = KillState.Counting; status = $"{kills} / {goal}"; } + else if (counted && goal > 0 && kills >= goal && wait <= TimeSpan.Zero && row.State != GuideState.Done) { state = KillState.TurnIn; status = "Turn in"; } + else if (row.State == GuideState.Done && wait > TimeSpan.Zero) { state = KillState.Waiting; status = "Done " + Short(wait); } + else if (row.State == GuideState.Done && q.RepeatSec == 0) { state = KillState.Completed; status = "Completed"; } + else if (row.State == GuideState.Done || counter != null) { state = KillState.Ready; status = "Ready"; } + else { state = KillState.NotStarted; status = goal > 0 ? $"0 / {goal}" : "Not started"; } + bool before = state is KillState.Waiting or KillState.Completed || DoneBefore(q, counter, flagDone); + return new Kill(state, kills, goal, counter, fromChat, status, before); + } + + /// + /// Done before: a stamp of the task is held other than those a first run holds too (the live counter, a "start" flag, + /// the first step's), a flag of it is on a redo timer, or the quest list's flag of its name is held. + /// + private bool DoneBefore(GuideQuest q, QuestFlag? counter, bool? flagDone) + { + string counterKey = counter != null ? GuideStamp.Key(counter.Key) : ""; + var first = new HashSet(StringComparer.Ordinal); + if (q.Steps.Count > 1) + foreach (string st in q.Steps[0].Stamps) first.Add(GuideStamp.Key(st)); + foreach (string st in q.AllStamps()) + { + string k = GuideStamp.Key(st); + if (k == counterKey || first.Contains(k) || k.Contains("start", StringComparison.Ordinal)) continue; + if (StampedThisSession(st) || FlagOf(st) != null) return true; + } + return flagDone == true; + } + + /// The two-word tag a kill task row shows, and its tooltip. + public static (string Tag, string Tip) KillTag(bool doneBefore) => doneBefore + ? ("Again", "Done before: a stamp or flag of this kill task is held.") + : ("1st", "First time: no stamp or flag of this kill task held yet."); + + /// "KillTaskSampleBeasts_0101" -> "Kill Task Sample Beasts 0101". + public static string FlagLabel(string flag) + { + var sb = new System.Text.StringBuilder(flag.Length + 8); + for (int i = 0; i < flag.Length; i++) + { + char c = flag[i]; + if (c == '_') { if (sb.Length > 0 && sb[^1] != ' ') sb.Append(' '); continue; } + bool brk = i > 0 && (char.IsUpper(c) && (char.IsLower(flag[i - 1]) || char.IsDigit(flag[i - 1])) || char.IsDigit(c) && char.IsLetter(flag[i - 1])); + if (brk && sb.Length > 0 && sb[^1] != ' ') sb.Append(' '); + sb.Append(c); + } + return sb.ToString().Trim(); + } +} + +/// One creature's last kill line this session: the count and the goal (0: the line gave none), and when. +internal readonly record struct KillCount(string Creature, int Kills, int Goal, DateTime AtUtc); + +/// +/// Kill task counts from chat: the server's "You have killed 27 Sample Beasts! You must kill 50 to complete your task." +/// (and "You have killed some ..."), so the Kill Tasks list moves with every kill though /myquests is read at most once a +/// minute. The last line per creature this session. Pump thread. +/// +internal sealed class KillChat +{ + private static readonly Regex CountRx = new( + @"^You have killed (?\d{1,6}) (?.+?)! You must kill (?\d{1,6}) to complete your task", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); + private static readonly Regex SomeRx = new(@"^You have killed (?:some|enough|all(?: the)?) (?.+?)[.!]*$", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); + + private readonly Dictionary _byKey = new(StringComparer.Ordinal); + + /// Goes up with every kill line taken. + public int Revision { get; private set; } + + public void Clear() + { + if (_byKey.Count == 0) return; + _byKey.Clear(); + Revision++; + } + + /// Takes a chat line; true when it was a kill task's kill line. + public bool OnChatLine(string? line, DateTime utcNow) + { + if (string.IsNullOrEmpty(line) || !line.StartsWith("You have killed ", StringComparison.OrdinalIgnoreCase)) return false; + string text = line.Trim(); + Match m = CountRx.Match(text); + if (m.Success) + { + string what = m.Groups["what"].Value.Trim(); + _byKey[GuideQuest.KillKey(what)] = new KillCount(what, + int.Parse(m.Groups["n"].Value, NumberStyles.None, CultureInfo.InvariantCulture), + int.Parse(m.Groups["max"].Value, NumberStyles.None, CultureInfo.InvariantCulture), utcNow); + Revision++; + return true; + } + m = SomeRx.Match(text); + if (!m.Success) return false; + string some = m.Groups["what"].Value.Trim(); + string key = GuideQuest.KillKey(some); + _byKey[key] = _byKey.TryGetValue(key, out KillCount had) ? had with { AtUtc = utcNow } : new KillCount(some, 0, 0, utcNow); + Revision++; + return true; + } + + /// The last line for a creature key: the same key, else one holding the other (keys of 5+ letters only), newest first. + public KillCount? For(string creatureKey) + { + if (creatureKey.Length == 0) return null; + if (_byKey.TryGetValue(creatureKey, out KillCount k)) return k; + if (creatureKey.Length < 5) return null; + KillCount? best = null; + foreach (KeyValuePair kv in _byKey) + if (kv.Key.Length >= 5 && (kv.Key.Contains(creatureKey, StringComparison.Ordinal) || creatureKey.Contains(kv.Key, StringComparison.Ordinal)) + && (best == null || kv.Value.AtUtc > best.Value.AtUtc)) + best = kv.Value; + return best; + } +} + +/// +/// The guides in use, merged: the active server plugin's own guide first (its quests replace the AC Community Wiki's of the +/// same name), then the AC Community Wiki's. Kill tasks, society ranks and contracts come from either. +/// +internal sealed class GuideSet +{ + public readonly List Quests = new(); + public readonly List Contracts = new(); + private readonly QuestGuide? _server; + private readonly QuestGuide _wiki; + private readonly HashSet _fromServer = new(); + + public GuideSet(QuestGuide? server, QuestGuide wiki) + { + _server = server is { IsEmpty: false } ? server : null; + _wiki = wiki; + var names = new HashSet(StringComparer.OrdinalIgnoreCase); + if (_server != null) + foreach (GuideQuest q in _server.Quests) + if (names.Add(q.Title)) { Quests.Add(q); _fromServer.Add(q); } + foreach (GuideQuest q in wiki.Quests) + if (names.Add(q.Title)) Quests.Add(q); + var contracts = new HashSet(StringComparer.OrdinalIgnoreCase); + if (_server != null) + foreach (GuideContract c in _server.Contracts) if (contracts.Add(c.Title)) Contracts.Add(c); + foreach (GuideContract c in wiki.Contracts) if (contracts.Add(c.Title)) Contracts.Add(c); + } + + public bool IsEmpty => Quests.Count == 0 && Contracts.Count == 0; + + /// The quest came from the server plugin's guide. + public bool FromServer(GuideQuest q) => _fromServer.Contains(q); + + public bool IsKillTask(GuideQuest q) => (_server?.IsKillTask(q) ?? false) || _wiki.IsKillTask(q); + + public string SocietyRankOf(GuideQuest q) + { + string r = _server?.SocietyRankOf(q) ?? ""; + return r.Length > 0 ? r : _wiki.SocietyRankOf(q); + } + + public GuideQuest? Find(string title) + { + foreach (GuideQuest q in Quests) + if (string.Equals(q.Title, title, StringComparison.OrdinalIgnoreCase)) return q; + return null; + } + + /// Society ranks in order (the wiki's names); a rank not in the list sorts last. + public static readonly string[] SocietyRanks = { "Joining", "Initiate", "Adept", "Knight", "Lord", "Master" }; + + public static int RankOrder(string rank) + { + for (int i = 0; i < SocietyRanks.Length; i++) + if (string.Equals(SocietyRanks[i], rank, StringComparison.OrdinalIgnoreCase)) return i; + return SocietyRanks.Length; + } +} + +/// +/// The seam for running a guide quest later (RynthNav walking its steps; not in this version). Nothing implements it +/// yet: the Guide tab draws run controls only when is set. +/// +internal interface IGuideQuestRunner +{ + /// The quest being run, or null. + GuideQuest? Running { get; } + /// The step under way (0-based), -1 none. + int Step { get; } + /// Starts the quest at a step; the answer to show. + string Start(GuideQuest q, int fromStep); + void Stop(); +} diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Data/QuestCatalogUpdater.cs b/Plugins/RynthCore.Plugin.RynthOracle/Data/QuestCatalogUpdater.cs index 2d251ad..e411b60 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/Data/QuestCatalogUpdater.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/Data/QuestCatalogUpdater.cs @@ -25,6 +25,9 @@ internal sealed class QuestCatalogUpdater public bool Running => _task is { IsCompleted: false }; + /// A day or more since the last check started. + public static bool Due(DateTime nowUtc, DateTime lastCheckUtc) => nowUtc - lastCheckUtc >= Interval; + /// Starts a check unless one is running. Pump thread. public void Start() { diff --git a/Plugins/RynthCore.Plugin.RynthOracle/OracleCommand.cs b/Plugins/RynthCore.Plugin.RynthOracle/OracleCommand.cs index 79d6520..933b4ad 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/OracleCommand.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/OracleCommand.cs @@ -3,7 +3,7 @@ using RynthCore.Plugin.Shared; namespace RynthCore.Plugin.RynthOracle; -internal enum OracleVerb { Window, Void, Timers, Quests, Tab, Trackers, Status, About, Help, Unknown } +internal enum OracleVerb { Window, Void, Timers, Quests, Tab, Trackers, Status, About, Help, Wiki, Unknown } /// A parsed "/ro ..." (the words after /ro, lower case): its verb, and the tab or the trackers it shows. internal readonly record struct OracleCommand(OracleVerb Verb, string Tab = "", QuestKind? Trackers = null, string Word = "") @@ -35,9 +35,17 @@ internal readonly record struct OracleCommand(OracleVerb Verb, string Tab = "", "skills" or "skill" => new(OracleVerb.Tab, OracleView.TabSkills), "attributes" or "attrs" or "attribute" or "vitals" => new(OracleVerb.Tab, OracleView.TabAttributes), "progress" or "progression" => new(OracleVerb.Tab, OracleView.TabProgress), + // The Guide tab (wiki quests with their steps), on one of its lists. + "guide" => new(OracleVerb.Tab, OracleView.TabGuide), + "killtasks" or "kill tasks" or "guide kill tasks" or "guide killtasks" => new(OracleVerb.Tab, OracleView.TabGuide, Word: "killtasks"), + "guide society" => new(OracleVerb.Tab, OracleView.TabGuide, Word: "society"), + "contracts" or "guide contracts" => new(OracleVerb.Tab, OracleView.TabGuide, Word: "contracts"), "status" => new(OracleVerb.Status), "about" => new(OracleVerb.About, OracleView.TabAbout), "help" or "?" => new(OracleVerb.Help), + // The AC Community Wiki feed (off by default): /ro wiki [on|off|read|status]. + "wiki" or "wiki status" => new(OracleVerb.Wiki, Word: "status"), + "wiki on" or "wiki off" or "wiki read" or "wiki refresh" => new(OracleVerb.Wiki, Word: a.Substring(5)), _ => new(OracleVerb.Unknown, Word: a), }; } @@ -47,7 +55,7 @@ internal readonly record struct OracleCommand(OracleVerb Verb, string Tab = "", + "/ro skills|attributes|progress (those tabs), /ro void (Void window), " + "/ro timers (Quest Timers window), /ro fellowship (Fellowship tab), " + "/ro trackers (Quests tab, trackers only), /ro legendary (John's 30 key quests), /ro markers, " - + "/ro quests (read quest flags), /ro status, " + + "/ro guide (Guide tab: wiki quests with steps; /ro killtasks, /ro guide society, /ro contracts), /ro quests (read quest flags), /ro wiki on|off|read|status (the AC Community Wiki feed, off until turned on), /ro status, " + "/ro about (About tab: settings, server, quest list). A server's own pages are its server plugin's (/rserver)."; public const string NoWindows = @@ -57,7 +65,7 @@ internal readonly record struct OracleCommand(OracleVerb Verb, string Tab = "", public static string Shown(string window, bool shown) => CommandReply.Shown(window, shown); - public static string OnTab(string tab) => $"Oracle window shown on its {tab} tab."; + public static string OnTab(string tab, string list = "") => list.Length > 0 ? $"Oracle window shown on its {tab} tab: {list}." : $"Oracle window shown on its {tab} tab."; public static string OnTrackers(QuestKind? kind) => kind switch { diff --git a/Plugins/RynthCore.Plugin.RynthOracle/OracleContext.cs b/Plugins/RynthCore.Plugin.RynthOracle/OracleContext.cs index fe5d8c4..a39d02c 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/OracleContext.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/OracleContext.cs @@ -35,6 +35,73 @@ internal sealed class OracleContext /// public readonly RynthCore.Plugin.Shared.ServerQuestPackClient QuestPacks = new(); /// + /// The active server plugin's own quest guide ("RynthServer.QuestGuide", 2026-11-27): its wiki's quests + /// with their steps, shown in the Guide tab over the AC Community Wiki's. None without one. + /// + public readonly RynthCore.Plugin.Shared.ServerQuestGuideClient ServerGuide = new(); + /// The AC Community Wiki feed (off by default; Settings.WikiFeedOn): the Guide tab's quests on every server. + public readonly CommunityWikiFeed Wiki = new(); + /// Stamps seen in chat this session ("You've stamped X!"), as GuideStamp keys; SessionStampRevision goes up with each. + public readonly System.Collections.Generic.HashSet SessionStamps = new(StringComparer.Ordinal); + public int SessionStampRevision; + /// Kill task lines seen in chat this session. + public readonly KillChat Kills = new(); + /// Where guide quests stand for this character (the flags, the session's stamps and kill lines). + public readonly GuideProgress Progress; + /// The seam for running a guide quest later; null in this version (no run controls drawn). + public IGuideQuestRunner? GuideRunner; + + public OracleContext() + { + Progress = new GuideProgress(Flags, SessionStamps, Kills); + } + + /// A chat line for the guide: a stamp ("You've stamped X!") or a kill task's kill line. True when it was one. + public bool OnGuideChatLine(string line, DateTime utcNow) + { + if (GuideStamp.FromChat(line) is string stamp && line.TrimStart().StartsWith("You've stamped ", StringComparison.OrdinalIgnoreCase)) + { + if (SessionStamps.Add(GuideStamp.Key(stamp))) SessionStampRevision++; + return true; + } + return Kills.OnChatLine(line, utcNow); + } + + /// + /// Turns the AC Community Wiki feed on or off (the About and Guide tabs' buttons, /ro wiki on|off). Turning it on + /// says what it reads and from where, then starts the first read. The answer, for the caller to show. + /// + public (bool Ok, string Text) SetWikiFeed(bool on) + { + if (Settings.WikiFeedOn == on) + return (true, on ? "The AC Community Wiki feed is already on. " + WikiStatus() : "The AC Community Wiki feed is already off: nothing is fetched."); + Settings.WikiFeedOn = on; + Settings.Save(); + if (!on) + { + Wiki.Stop(); + return (true, "AC Community Wiki feed off: nothing more is fetched (the copy already saved stays in the Guide tab)."); + } + bool started = Wiki.Start(on: true); + return (true, "AC Community Wiki feed on. It reads " + CommunityWikiFeed.WhatItReads + + (started ? " Reading it now." : " A read is already under way.")); + } + + /// Reads the wiki now (the Guide tab's Read now, /ro wiki read): only with the feed on. + public (bool Ok, string Text) ReadWikiNow() + { + if (!Settings.WikiFeedOn) + return (false, "The AC Community Wiki feed is off, so nothing is fetched. Turn it on first (About tab, Guide tab, or /ro wiki on); it reads " + + CommunityWikiFeed.WhatItReads); + if (Wiki.Running) return (false, "The AC Community Wiki is being read already: " + Wiki.Status); + return Wiki.Start(on: true) + ? (true, "Reading the AC Community Wiki (" + CommunityWikiFeed.Host + "): only the pages edited since the last read.") + : (false, "Couldn't start reading the AC Community Wiki."); + } + + /// "on: 812 quests, ... (read ...)" or "off". + public string WikiStatus() => (Settings.WikiFeedOn ? "On: " : "Off (nothing is fetched). Saved copy: ") + Wiki.Status + "."; + /// /// The active server's Void DoT duration rule: its plugin's profile value "voidDotDurationScale" /// (RynthConquest publishes Conquest's), 1 on every other server or without the plugin. /// diff --git a/Plugins/RynthCore.Plugin.RynthOracle/OracleSettings.cs b/Plugins/RynthCore.Plugin.RynthOracle/OracleSettings.cs index b251aaf..83c66d2 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/OracleSettings.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/OracleSettings.cs @@ -31,6 +31,15 @@ internal sealed class OracleSettings public bool AlertTimers = true; /// false: only tracked quests are watched; true: every quest the character holds. public bool AlertAllTimers; + /// + /// Read the AC Community Wiki's quest pages for the Guide tab (CommunityWikiFeed). OFF by default: nothing is + /// fetched until the player turns it on, and the About and Guide tabs say what it reads and from where first. + /// + public bool WikiFeedOn; + /// With the feed on: read it again at login when the saved copy is a day old. + public bool WikiFeedDaily = true; + /// The Guide tab's "Hide done" (quests with nothing to do now). + public bool GuideHideDone; /// Where the tests keep the settings file (a scratch path); null means the rynthoracle.json in RynthCore's %APPDATA% folder. internal static string? PathOverride; @@ -42,7 +51,7 @@ internal sealed class OracleSettings private static readonly string[] KnownNames = { "readQuestsAtLogin", "hideOwnQuestReplies", "checkQuestListDaily", "lastQuestListCheck", "autoShowVoidWindow", - "mainWindowOpen", "questTimersOpen", "alertTimers", "alertAllTimers", "tabName", + "mainWindowOpen", "questTimersOpen", "alertTimers", "alertAllTimers", "tabName", "wikiFeedOn", "wikiFeedDaily", "guideHideDone", }; // "conquestAutoDeposit" moved to RynthConquest (2026-10-20), which takes it over from this file once; // it is kept here (as any value this version doesn't use) until then. @@ -72,6 +81,9 @@ internal sealed class OracleSettings QuestTimersOpen = Bool(r, "questTimersOpen", QuestTimersOpen); AlertTimers = Bool(r, "alertTimers", AlertTimers); AlertAllTimers = Bool(r, "alertAllTimers", AlertAllTimers); + WikiFeedOn = Bool(r, "wikiFeedOn", WikiFeedOn); + WikiFeedDaily = Bool(r, "wikiFeedDaily", WikiFeedDaily); + GuideHideDone = Bool(r, "guideHideDone", GuideHideDone); if (r.TryGetProperty("tabName", out JsonElement t) && t.ValueKind == JsonValueKind.String) TabName = t.GetString() ?? TabName; if (r.TryGetProperty("lastQuestListCheck", out JsonElement c) && c.ValueKind == JsonValueKind.String && DateTime.TryParse(c.GetString(), CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out DateTime when)) @@ -98,6 +110,9 @@ internal sealed class OracleSettings sb.Append(" \"questTimersOpen\": ").Append(QuestTimersOpen ? "true" : "false").Append(",\n"); sb.Append(" \"alertTimers\": ").Append(AlertTimers ? "true" : "false").Append(",\n"); sb.Append(" \"alertAllTimers\": ").Append(AlertAllTimers ? "true" : "false").Append(",\n"); + sb.Append(" \"wikiFeedOn\": ").Append(WikiFeedOn ? "true" : "false").Append(",\n"); + sb.Append(" \"wikiFeedDaily\": ").Append(WikiFeedDaily ? "true" : "false").Append(",\n"); + sb.Append(" \"guideHideDone\": ").Append(GuideHideDone ? "true" : "false").Append(",\n"); sb.Append(" \"tabName\": \"").Append(JsonEncodedText.Encode(TabName).ToString()).Append('"'); foreach ((string name, string raw) in _kept) sb.Append(",\n \"").Append(JsonEncodedText.Encode(name).ToString()).Append("\": ").Append(raw); diff --git a/Plugins/RynthCore.Plugin.RynthOracle/RynthCore.Plugin.RynthOracle.csproj b/Plugins/RynthCore.Plugin.RynthOracle/RynthCore.Plugin.RynthOracle.csproj index 3a0f59d..be8ef41 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/RynthCore.Plugin.RynthOracle.csproj +++ b/Plugins/RynthCore.Plugin.RynthOracle/RynthCore.Plugin.RynthOracle.csproj @@ -64,6 +64,13 @@ + + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthOracle/RynthOraclePlugin.cs b/Plugins/RynthCore.Plugin.RynthOracle/RynthOraclePlugin.cs index a201789..a1c0a5a 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/RynthOraclePlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/RynthOraclePlugin.cs @@ -52,12 +52,12 @@ public sealed class RynthOraclePlugin : RynthPluginBase private long _nextCharacterReadMs; private long _nextCharacterExtrasMs; private bool _voidAutoDecided; - private bool _dailyCheckStarted; private int _seenFlagRevision = -1, _seenCatalogRevision = -1, _seenVoidRevision = -1; // RynthCore's server list (ServerStateClient.Revision) last applied to the server identity. private int _seenServerStateRevision = -1; private string? _catalogKey; // what the catalog was loaded for (QuestPackSource.Key; "" = retail only) private int _seenPackRevision = -1; // the active server plugin's quest pack (ServerQuestPackClient.Revision) + private int _seenServerGuideRevision = -1; // its quest guide (ServerQuestGuideClient.Revision) private int _titleCount = -2; private uint _titleCurrent; private long _nextAutoReadMs; @@ -144,6 +144,11 @@ public sealed class RynthOraclePlugin : RynthPluginBase _c.QuestPacks.Clear(); _c.QuestPacks.Poll(Host, Shared.ServerQuestPackClient.OwnerOf(_c.ServerState.State), Environment.TickCount64, force: true); _seenPackRevision = _c.QuestPacks.Revision; + _c.ServerGuide.Clear(); + _c.SessionStamps.Clear(); + _c.SessionStampRevision++; + _c.Kills.Clear(); + _c.ServerGuide.Poll(Host, Shared.ServerQuestPackClient.OwnerOf(_c.ServerState.State), Environment.TickCount64, force: true); _catalogKey = null; ApplyServer(); _titleCount = -2; @@ -157,7 +162,6 @@ public sealed class RynthOraclePlugin : RynthPluginBase _nextCharacterExtrasMs = now; ClearCharacterExtras(); _voidAutoDecided = false; - _dailyCheckStarted = false; if (_main != null) { _main.Visible = _c.Settings.MainWindowOpen; _main.NeedsPass = true; } if (_void != null) { _void.Visible = false; _void.NeedsPass = true; } // The quest book loads once the character's name (and world) are known (TickData). @@ -194,6 +198,7 @@ public sealed class RynthOraclePlugin : RynthPluginBase _c.VoidDotScale = 1.0; _c.ServerState.Clear(); _c.QuestPacks.Clear(); + _c.ServerGuide.Clear(); _c.TitlesKnown = false; _c.EarnedTitles.Clear(); ClearCharacterExtras(); @@ -269,6 +274,7 @@ public sealed class RynthOraclePlugin : RynthPluginBase _skills?.Shutdown(); _ui.SubmitEmpty(Host); _c.Updater.Shutdown(); + _c.Wiki.Shutdown(); _c.Settings.Save(); } @@ -300,6 +306,15 @@ public sealed class RynthOraclePlugin : RynthPluginBase } if (!_c.InWorld) return; + // The Guide: a stamp ("You've stamped X!") or a kill task's kill line. Kills with the Kill Tasks list on + // screen ask for a fresh /myquests (RereadIfStale sends it, at most once a minute). + if (_c.OnGuideChatLine(line.Trim(), DateTime.UtcNow)) + { + if (_mainView?.KillTasksShowing == true && _main?.Visible == true) _c.Flags.WantReread(); + if (_main != null) _main.NeedsPass = true; + return; + } + // A server's own command replies (Conquest's /b, Aelrynth's /top, ...) are its server plugin's. // A server's own Void DoT duration rule comes from its plugin's profile (RynthConquest's for // Conquest); 1 everywhere else (VoidScaleFrom). @@ -375,7 +390,13 @@ public sealed class RynthOraclePlugin : RynthPluginBase case OracleVerb.Tab: // RynthAi, the server plugins and RynthCore's menus link to these; they show, never toggle off. ShowTab(c.Tab); - Shown(OracleCommand.OnTab(c.Tab)); + if (c.Tab == OracleView.TabGuide && c.Word.Length > 0 && _mainView != null) + { + GuideList list = c.Word switch { "killtasks" => GuideList.KillTasks, "society" => GuideList.Society, _ => GuideList.Contracts }; + _mainView.ShowGuide(list); + Shown(OracleCommand.OnTab(c.Tab, list == GuideList.KillTasks ? "Kill Tasks" : list.ToString())); + } + else Shown(OracleCommand.OnTab(c.Tab)); break; case OracleVerb.Trackers: // A server's own trackers and tabs are its server plugin's pages (since 2026-10-21). @@ -396,6 +417,20 @@ public sealed class RynthOraclePlugin : RynthPluginBase case OracleVerb.Help: _c.Print(OracleCommand.Usage); break; + case OracleVerb.Wiki: + { + // The AC Community Wiki feed: off until turned on; "on" says what it reads and from where first. + var (ok, text) = c.Word switch + { + "on" => _c.SetWikiFeed(true), + "off" => _c.SetWikiFeed(false), + "read" or "refresh" => _c.ReadWikiNow(), + _ => (true, "AC Community Wiki feed: " + _c.WikiStatus() + (_c.Settings.WikiFeedOn ? "" : " /ro wiki on reads " + CommunityWikiFeed.WhatItReads)), + }; + if (ok) _c.Print(text); else _c.PrintFail(text); + if (_main != null) _main.NeedsPass = true; + break; + } default: _c.PrintFail(OracleCommand.Unknown(c.Word)); break; @@ -437,7 +472,7 @@ public sealed class RynthOraclePlugin : RynthPluginBase if (_timers?.Visible == true) return true; if (_main?.Visible != true || _mainView == null) return false; string tab = _mainView.Tab; - return tab == OracleView.TabQuests || tab == OracleView.TabAugs || tab == OracleView.TabSociety; + return tab == OracleView.TabQuests || tab == OracleView.TabGuide || tab == OracleView.TabAugs || tab == OracleView.TabSociety; } /// Re-reads /myquests when the flags are known stale, or old and on screen; at most once a minute. @@ -615,6 +650,13 @@ public sealed class RynthOraclePlugin : RynthPluginBase if (_main != null) _main.NeedsPass = true; } + // A finished read of the AC Community Wiki (the feed is off by default; nothing reads it then). + if (_c.Wiki.TakeResult()) + { + Host.Log("[RynthOracle] AC Community Wiki read: " + _c.Wiki.Status); + if (_main != null) _main.NeedsPass = true; + } + if (!_c.InWorld) return; ReadCharacterExtras(now); @@ -636,6 +678,13 @@ public sealed class RynthOraclePlugin : RynthPluginBase ApplyServer(); if (_main != null) _main.NeedsPass = true; } + // The active server plugin's quest guide (every 2 s; the guide is read only when it changed). + _c.ServerGuide.Poll(Host, Shared.ServerQuestPackClient.OwnerOf(_c.ServerState.State), now, force: serverChanged); + if (_c.ServerGuide.Revision != _seenServerGuideRevision) + { + _seenServerGuideRevision = _c.ServerGuide.Revision; + if (_main != null) _main.NeedsPass = true; + } if (_questReadAtMs >= 0 && now >= _questReadAtMs) { @@ -645,10 +694,16 @@ public sealed class RynthOraclePlugin : RynthPluginBase } RereadIfStale(now); - if (!_dailyCheckStarted && _c.Settings.CheckQuestListDaily - && _c.UtcNow - _c.Settings.LastQuestListCheckUtc >= QuestCatalogUpdater.Interval) + // With the feed on (and its daily read on): once a session, after the login read's delay, when the copy is a day old. + if (_questReadAtMs < 0 && now - _loginMs >= QuestReadDelayMs + && _c.Wiki.LoginRead(_c.Settings.WikiFeedOn, _c.Settings.WikiFeedDaily, _c.UtcNow)) + Host.Log($"[RynthOracle] Reading the AC Community Wiki ({CommunityWikiFeed.Host}): the saved copy is a day old or missing."); + + // Once a day, however long the session (it ran once per login only, so a client that stayed + // logged in never checked again). + if (_c.Settings.CheckQuestListDaily && !_c.Updater.Running + && QuestCatalogUpdater.Due(_c.UtcNow, _c.Settings.LastQuestListCheckUtc)) { - _dailyCheckStarted = true; _c.Settings.LastQuestListCheckUtc = _c.UtcNow; _c.Settings.Save(); _c.Updater.Start(); diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Views/AboutTab.cs b/Plugins/RynthCore.Plugin.RynthOracle/Views/AboutTab.cs index b492b88..b77f313 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/Views/AboutTab.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/Views/AboutTab.cs @@ -30,6 +30,11 @@ internal sealed partial class OracleView w.Checkbox("Check once a day for a newer quest list", "o.daily", s.CheckQuestListDaily, v => { s.CheckQuestListDaily = v; s.Save(); }); w.Tooltip("Downloads Oracle of Dereth's master quest list from GitHub, as the original plugin does."); + w.SeparatorText("Quest guide (the Guide tab)"); + DrawWikiFeedControls(w, "o", full: true); + if (_c.ServerGuide.Available) + w.TextDisabled($"{_c.ServerGuide.Tag}'s own guide (from its server plugin): {_c.ServerGuide.Guide.Quests.Count} quests. {_c.ServerGuide.Info?.Status}"); + w.SeparatorText("Server"); ServerIdentity sv = _c.Server; QuestCatalog pc = _c.Catalog; @@ -83,6 +88,8 @@ internal sealed partial class OracleView w.BulletText("/ro about this tab (settings, server, quest list)"); w.BulletText("/ro void open or close the Void window"); w.BulletText("/ro quests read your quest flags now"); + w.BulletText("/ro guide the Guide tab: wiki quests with their steps (/ro killtasks, /ro guide society, /ro contracts)"); + w.BulletText("/ro wiki on|off|read|status the AC Community Wiki feed (off until you turn it on)"); w.BulletText("/ro help list the commands in chat"); w.TextDisabled("A server quest pack can be replaced without a rebuild: put quests..csv in %APPDATA%\\RynthCore\\RynthOracle\\packs."); } diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Views/GuideTab.cs b/Plugins/RynthCore.Plugin.RynthOracle/Views/GuideTab.cs new file mode 100644 index 0000000..2655192 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthOracle/Views/GuideTab.cs @@ -0,0 +1,640 @@ +// The Guide tab (2026-11-27): wiki quests with their steps. The list on the left with where each quest stands, the +// opened quest on the right: its timer, where it starts (Go), its steps with their coordinates (Go) and the stamps each +// gives (ticked when held), its loot and rewards. Lists: All / Story / Dailies / Weekly, Kill Tasks, Society, Contracts. +// The quests come from the active server plugin's own guide ("RynthServer.QuestGuide") and the AC Community Wiki feed +// (off until the player turns it on). The layout follows SilentKelpie's Guide (Forgejo rynth PR #12); re-implemented +// here, without "Run this quest" (IGuideQuestRunner is the seam for it). +using System; +using System.Collections.Generic; +using RynthCore.Plugin.RynthOracle.Data; +using RynthCore.Plugin.RynthOracle.Ui; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthOracle.Views; + +/// The Guide tab's lists. +internal enum GuideList { All, Story, Dailies, Weekly, KillTasks, Society, Contracts } + +internal sealed partial class OracleView +{ + private static readonly string[] GuideListNames = { "All", "Story", "Dailies", "Weekly", "Kill Tasks", "Society", "Contracts" }; + private const int GuidePageSize = 40; + private const float GuideListWidth = 310f; + private const int GuideMaxSteps = 40; + private const int ColText = 0; // ImGuiCol_Text + + private GuideList _gList; + private string _gSearch = ""; + private int _gPage; + private string _gSel = ""; + private string _gMsg = ""; + private GuideSet? _gSet; + private string _gSetKey = ""; + private readonly List _gRows = new(); + private string _gRowsKey = ""; + private Dictionary _catalogByName = new(StringComparer.OrdinalIgnoreCase); + private int _catalogByNameRev = -1; + + private sealed class GuideRow + { + public string Key = ""; + public string Label = ""; + public string Status = ""; + public string Tip = ""; + public uint Color = UiColors.Grey; + /// "Hide done" leaves it out (done, with nothing to do now). + public bool Hide; + public string Tag = ""; + public string TagTip = ""; + public uint TagColor = UiColors.Grey; + public int Order; + public GuideQuest? Q; + public QuestFlag? Flag; + public GuideContract? C; + } + + /// Shows the Guide tab on a list (and a row). Internal for /ro and the tests. + internal void ShowGuide(GuideList list, string? select = null) + { + _gList = list; + _gPage = 0; + if (select != null) _gSel = select; + Tab = TabGuide; + } + + /// The Kill Tasks list is on screen (kill lines then ask for a fresh /myquests). + public bool KillTasksShowing => Tab == TabGuide && _gList == GuideList.KillTasks; + + /// The guides in use, merged (rebuilt when either changes). Internal for the tests. + internal GuideSet GuideSources() + { + string key = $"{_c.ServerGuide.Revision}|{_c.Wiki.Revision}"; + if (_gSet == null || key != _gSetKey) + { + _gSetKey = key; + _gSet = new GuideSet(_c.ServerGuide.Guide, _c.Wiki.Guide); + } + return _gSet; + } + + /// The quest list's flag for a quest of this name: done or not; null when the list has no quest of that name. + private bool? CatalogDone(string title) + { + if (_catalogByNameRev != _c.Catalog.Revision) + { + var map = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (Quest q in _c.Catalog.Quests) + if (!q.IsNew && q.Name.Length > 0) map.TryAdd(q.Name, q); + _catalogByName = map; + _catalogByNameRev = _c.Catalog.Revision; + } + return _catalogByName.TryGetValue(title, out Quest? found) ? found.IsComplete(_c.Flags) : null; + } + + private static uint StateColor(GuideState s) => s switch + { + GuideState.Done => UiColors.Green, + GuideState.PartWaiting => UiColors.Yellow, + GuideState.PartReady => UiColors.Gold, + _ => UiColors.Grey, + }; + + private static uint KillColor(KillState s) => s switch + { + KillState.TurnIn => UiColors.Gold, + KillState.Counting or KillState.Waiting => UiColors.Yellow, + KillState.Ready or KillState.Completed => UiColors.Green, + _ => UiColors.Grey, + }; + + // ── The page ──────────────────────────────────────────────────────────── + + private void DrawGuide(UiWindow w) + { + GuideSet set = GuideSources(); + DrawGuideSources(w, set); + if (set.IsEmpty) + { + w.Spacing(); + w.TextWrapped("No quest guide yet. The AC Community Wiki feed gives one on every server once you turn it on;" + + " a server plugin can also hand RynthOracle its own server's guide."); + DrawWikiFeedControls(w, "g", full: false); + return; + } + + for (int i = 0; i < GuideListNames.Length; i++) + { + var list = (GuideList)i; + if (i > 0) w.SameLine(); + w.ToggleButton(GuideListNames[i], "g.list." + i, _gList == list, () => { _gList = list; _gPage = 0; }, small: true); + } + w.Checkbox("Hide done", "g.hide", _c.Settings.GuideHideDone, v => { _c.Settings.GuideHideDone = v; _c.Settings.Save(); _gPage = 0; }); + w.Tooltip("Leave out the quests that are done with nothing to do now: one-time quests done, and quests whose timer is running."); + w.SameLine(); + w.InputText("Search", "g.search", _gSearch, 64, s => { _gSearch = s; _gPage = 0; }); + w.Tooltip("Words to find: a quest's name, who and where it starts, its items or stamps."); + if (_gMsg.Length > 0) w.TextDisabled(_gMsg); + if (_gList == GuideList.KillTasks) DrawKillSummary(w, set); + + List rows = GuideRows(set); + w.BeginChild("g.rows", GuideListWidth, 0f, border: true); + if (rows.Count > GuidePageSize) _gPage = Pager(w, "g.page", _gPage, rows.Count, GuidePageSize, p => _gPage = p); + else _gPage = 0; + bool tags = rows.Exists(r => r.Tag.Length > 0); + float statusX = GuideListWidth - 112f, tagX = statusX - 40f; + float labelEnd = tags ? tagX : statusX; + int chars = Math.Max(16, (int)((labelEnd - 14f) / 6.4f)); + int start = _gPage * GuidePageSize; + for (int i = start; i < rows.Count && i < start + GuidePageSize; i++) + { + GuideRow r = rows[i]; + string key = r.Key; + w.Selectable(Cut(r.Label, chars), "g.r." + key, key == _gSel, () => _gSel = key, labelEnd - 12f); + if (r.Label.Length > chars) w.Tooltip(r.Label); + if (r.Tag.Length > 0) + { + w.SameLine(tagX); + w.TextColored(r.TagColor, r.Tag); + w.Tooltip(r.TagTip); + } + if (r.Status.Length > 0) + { + w.SameLine(statusX); + w.TextColored(r.Color, r.Status); + if (r.Tip.Length > 0) w.Tooltip(r.Tip); + } + } + if (rows.Count == 0) w.TextDisabled("Nothing here matches."); + w.EndChild(); + + w.SameLine(); + w.BeginChild("g.detail", 0f, 0f, border: true); + GuideRow? sel = rows.Find(r => r.Key == _gSel) ?? FindGuideRow(set, _gSel); + if (sel == null) w.TextDisabled("Pick a quest on the left."); + else if (sel.Q != null) DrawGuideQuest(w, set, sel.Q); + else if (sel.Flag != null) DrawKillFlag(w, sel.Flag); + else if (sel.C != null) DrawGuideContract(w, set, sel.C); + w.EndChild(); + } + + /// One line per source: the server plugin's guide (with its own commands) and the AC Community Wiki feed. + private void DrawGuideSources(UiWindow w, GuideSet set) + { + ServerQuestGuideClient sg = _c.ServerGuide; + if (sg.Available) + { + ServerQuestGuideInfo info = sg.Info!; + w.TextDisabled(Cut($"{sg.Tag} Wiki ({info.Plugin}): {(info.Running ? "reading... " : "")}{sg.Guide.Quests.Count} quests. {info.Status}", 90)); + w.Tooltip($"{sg.Tag}'s own quests, from its server plugin; they come first, over the AC Community Wiki's of the same name."); + if (info.Takes(RynthServerQuestGuide.CommandRefresh)) + { + w.SameLine(); + w.SmallButton("Read it again", "g.sg.refresh", () => _gMsg = sg.Command(RynthServerQuestGuide.CommandRefresh) + ? $"Asked {info.Plugin} to read {sg.Tag}'s guide again." : $"{info.Plugin} didn't take the request."); + } + if (info.Takes(RynthServerQuestGuide.CommandSettings)) + { + w.SameLine(); + w.SmallButton("Its settings", "g.sg.settings", () => _gMsg = sg.Command(RynthServerQuestGuide.CommandSettings) + ? $"{info.Plugin}'s guide settings are open." : $"{info.Plugin} didn't take the request."); + } + } + CommunityWikiFeed feed = _c.Wiki; + string line = _c.Settings.WikiFeedOn + ? "AC Community Wiki: " + (feed.Running ? "reading... " : "") + feed.Status + : feed.Guide.IsEmpty ? "AC Community Wiki feed: off (nothing is fetched)." : "AC Community Wiki feed: off; the copy saved earlier: " + feed.Status; + w.TextDisabled(Cut(line, 100)); + if (!set.IsEmpty && w.CollapsingHeader("AC Community Wiki feed", "g.feed")) + DrawWikiFeedControls(w, "g", full: false); + } + + // ── Rows ──────────────────────────────────────────────────────────────── + + private static bool Matches(string hay, string[] terms) + { + foreach (string t in terms) + if (hay.IndexOf(t, StringComparison.OrdinalIgnoreCase) < 0) return false; + return true; + } + + private static string Hay(GuideQuest q) => + $"{q.Title} {q.StartsWith} {q.StartsAt} {q.Type} {string.Join(" ", q.Loot)} {string.Join(" ", q.AllStamps())}"; + + private GuideRow GuideQuestRow(GuideQuest q) + { + GuideProgress.Row p = _c.Progress.RowOf(q, _c.UtcNow, CatalogDone(q.Title)); + return new GuideRow { Key = "w:" + q.Title, Label = q.Title, Q = q, Status = p.Status, Tip = p.Tip, Color = StateColor(p.State), Hide = p.HideWhenDone }; + } + + private GuideRow? FindGuideRow(GuideSet set, string key) + { + if (key.StartsWith("w:", StringComparison.Ordinal) && set.Find(key.Substring(2)) is GuideQuest q) return GuideQuestRow(q); + if (key.StartsWith("c:", StringComparison.Ordinal) && set.Contracts.Find(x => x.Title == key.Substring(2)) is GuideContract c) return ContractRow(set, c); + if (key.StartsWith("k:", StringComparison.Ordinal) && _c.Flags.TryGet(key.Substring(2), out QuestFlag f)) + return new GuideRow { Key = key, Label = KillFlagLabel(f), Flag = f }; + return null; + } + + /// The rows of the list shown (rebuilt when anything they show changes, or each minute for the timers). Internal for the tests. + private List GuideRows(GuideSet set) + { + string key = $"{_gList}|{_gSearch}|{_c.Settings.GuideHideDone}|{_gSetKey}|{_c.Flags.Revision}|{_c.SessionStampRevision}|{_c.Kills.Revision}|{_c.Catalog.Revision}|{_c.UtcNow:yyyyMMddHHmm}"; + if (key == _gRowsKey) return _gRows; + _gRowsKey = key; + _gRows.Clear(); + string[] terms = _gSearch.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + bool hide = _c.Settings.GuideHideDone; + switch (_gList) + { + case GuideList.KillTasks: KillRows(set, terms, hide); break; + case GuideList.Society: SocietyRows(set, terms, hide); break; + case GuideList.Contracts: ContractRows(set, terms, hide); break; + default: + foreach (GuideQuest q in set.Quests) + { + bool inList = _gList switch + { + GuideList.Story => q.IsOneTime, + GuideList.Dailies => q.IsDaily, + GuideList.Weekly => q.IsWeekly, + _ => true, + }; + if (!inList || !Matches(Hay(q), terms)) continue; + GuideRow r = GuideQuestRow(q); + if (hide && r.Hide) continue; + _gRows.Add(r); + } + break; + } + return _gRows; + } + + private void KillRows(GuideSet set, string[] terms, bool hide) + { + var named = new HashSet(StringComparer.Ordinal); + foreach (GuideQuest q in set.Quests) + { + if (!set.IsKillTask(q)) continue; + GuideProgress.Kill p = _c.Progress.KillOf(q, _c.UtcNow, CatalogDone(q.Title)); + if (p.Counter != null) named.Add(GuideStamp.Key(p.Counter.Key)); + foreach (string st in q.AllStamps()) named.Add(GuideStamp.Key(st)); + if (!Matches(Hay(q), terms)) continue; + bool done = p.State is KillState.Waiting or KillState.Completed; + if (hide && done) continue; + var r = new GuideRow { Key = "w:" + q.Title, Label = q.Title, Q = q, Status = p.Status, Color = KillColor(p.State), Order = (int)p.State }; + SetKillTag(r, p.DoneBefore); + _gRows.Add(r); + } + // Counters the server keeps that no guide's kill task names: listed too, so nothing counted is left out. + foreach (QuestFlag f in _c.Flags.Flags.Values) + { + if (!QuestTimer.IsKillTask(f) || named.Contains(GuideStamp.Key(f.Key)) || !Matches(f.Key + " " + f.Description, terms)) continue; + QuestTimerState st = QuestTimer.State(f, true, _c.UtcNow, out string text); + KillState ks = st switch + { + QuestTimerState.InProgress => KillState.Counting, + QuestTimerState.Waiting => KillState.Waiting, + QuestTimerState.Done => KillState.Completed, + _ => KillState.Ready, + }; + if (hide && ks is KillState.Waiting or KillState.Completed) continue; + var r = new GuideRow + { + Key = "k:" + f.Key, Label = KillFlagLabel(f), Flag = f, Color = KillColor(ks), Order = (int)ks, + Status = ks switch { KillState.Counting => $"{f.Solves} / {f.MaxSolves}", KillState.Waiting => "Done " + text, KillState.Completed => "Completed", _ => "Ready" }, + }; + SetKillTag(r, ks != KillState.Counting); + _gRows.Add(r); + } + _gRows.Sort((a, b) => a.Order != b.Order ? a.Order.CompareTo(b.Order) : string.Compare(a.Label, b.Label, StringComparison.OrdinalIgnoreCase)); + } + + /// A counter flag's row: the server's description of it, else the flag split into words. + private static string KillFlagLabel(QuestFlag f) => f.Description.Length > 1 ? f.Description : GuideProgress.FlagLabel(f.Key); + + private static void SetKillTag(GuideRow r, bool doneBefore) + { + (r.Tag, r.TagTip) = GuideProgress.KillTag(doneBefore); + r.TagColor = doneBefore ? UiColors.Green : UiColors.Gold; + } + + private void SocietyRows(GuideSet set, string[] terms, bool hide) + { + foreach (GuideQuest q in set.Quests) + { + string rank = set.SocietyRankOf(q); + if (rank.Length == 0 || !Matches(rank + " " + Hay(q), terms)) continue; + GuideRow r = GuideQuestRow(q); + if (hide && r.Hide) continue; + r.Label = rank + ": " + q.Title; + r.Order = GuideSet.RankOrder(rank); + _gRows.Add(r); + } + _gRows.Sort((a, b) => a.Order != b.Order ? a.Order.CompareTo(b.Order) : string.Compare(a.Label, b.Label, StringComparison.OrdinalIgnoreCase)); + } + + private GuideRow ContractRow(GuideSet set, GuideContract c) + { + var r = new GuideRow { Key = "c:" + c.Title, Label = c.Name, C = c }; + // The state of the quest it is for (the first one a guide has). + foreach (string t in c.Quests) + if (set.Find(t) is GuideQuest q) + { + GuideRow qr = GuideQuestRow(q); + r.Status = qr.Status; + r.Tip = q.Title + ": " + qr.Tip; + r.Color = qr.Color; + r.Hide = qr.Hide; + return r; + } + if (c.Level.Length > 0) r.Status = "L" + c.Level; + return r; + } + + private void ContractRows(GuideSet set, string[] terms, bool hide) + { + foreach (GuideContract c in set.Contracts) + { + if (!Matches($"{c.Name} {c.Description} {c.Where} {string.Join(" ", c.Quests)}", terms)) continue; + GuideRow r = ContractRow(set, c); + if (hide && r.Hide) continue; + _gRows.Add(r); + } + _gRows.Sort((a, b) => string.Compare(a.Label, b.Label, StringComparison.OrdinalIgnoreCase)); + } + + // ── The opened quest ──────────────────────────────────────────────────── + + private void DrawGuideQuest(UiWindow w, GuideSet set, GuideQuest q) + { + GuideProgress p = _c.Progress; + DateTime now = _c.UtcNow; + w.TextColored(UiColors.Gold, q.Title); + TimeSpan wait = p.Wait(q, now); + w.TextDisabled(GuideProgress.RepeatText(q) + (wait > TimeSpan.Zero ? " - again in " + GuideProgress.Short(wait) : "")); + GuideProgress.Row row = p.RowOf(q, now, CatalogDone(q.Title)); + w.TextColored(StateColor(row.State), row.Tip); + var facts = new List(); + if (q.Level.Length > 0) facts.Add("Level " + q.Level); + if (q.RecommendedLevel.Length > 0) facts.Add("rec. " + q.RecommendedLevel); + if (q.Type.Length > 0) facts.Add(q.Type); + if (q.TimeToComplete.Length > 0) facts.Add(q.TimeToComplete); + if (set.SocietyRankOf(q) is { Length: > 0 } rank) facts.Add("Society: " + rank); + if (facts.Count > 0) w.TextDisabled(string.Join(" | ", facts)); + if (set.IsKillTask(q)) DrawKillLine(w, q); + + // Running a quest along its steps comes later; the seam draws nothing until a runner is set. + if (_c.GuideRunner is IGuideQuestRunner runner) DrawRunControls(w, runner, q); + if (q.Url.Length > 0) + { + w.SmallButton("Wiki page", "g.url", () => _c.Print(q.Url)); + w.Tooltip("Prints the page's address in chat: " + q.Url); + w.SameLine(); + } + w.TextDisabled(set.FromServer(q) ? $"From {_c.ServerGuide.Tag}'s guide" : "From the AC Community Wiki"); + + if (q.StartsWith.Length > 0 || q.StartsAt.Length > 0) + { + w.Text("Starts" + (q.StartsWith.Length > 0 ? " with " + q.StartsWith : "") + (q.StartsAt.Length > 0 ? " at " + q.StartsAt : "")); + string place = q.StartsAt.Length > 0 ? q.StartsAt : q.StartsWith; + w.SameLine(); + w.SmallButton("Go", "g.start.go", () => _gMsg = SendRynthNav("go", new[] { place })); + w.Tooltip("RynthNav goes to " + place + " (a place on its Atlas), walking and taking portals."); + } + if (q.Overview.Length > 0) w.TextWrapped(q.Overview); + + DrawStampSummary(w, q); + (bool[] done, bool[] passed, int next) = StepStates(q); + w.SeparatorText(q.Steps.Count > 0 ? "Steps" : "Steps (the page has no walkthrough)"); + int current = _c.GuideRunner?.Running == q ? _c.GuideRunner.Step : -1; + for (int i = 0; i < q.Steps.Count && i < GuideMaxSteps; i++) DrawGuideStep(w, q, i, done[i], passed[i], i == next, i == current); + if (q.Steps.Count > GuideMaxSteps) w.TextDisabled($"... {q.Steps.Count - GuideMaxSteps} more steps on the wiki page."); + if (q.ExtraStamps.Count > 0) + { + w.TextDisabled("Also stamps (the page doesn't say which step):"); + foreach (string st in q.ExtraStamps) StampLine(w, q, st); + } + if (q.Loot.Count > 0) + { + w.SeparatorText("Loot"); + w.TextWrapped(string.Join(", ", q.Loot)); + } + if (q.Rewards.Count > 0 && w.CollapsingHeader("Rewards", "g.rewards")) + foreach (string r in q.Rewards) + if (r.EndsWith(':')) w.Text(r); else w.BulletText(r); + } + + private void DrawRunControls(UiWindow w, IGuideQuestRunner runner, GuideQuest q) + { + if (runner.Running == q) + { + w.Button("Stop", "g.run.stop", runner.Stop); + w.SameLine(); + } + else + { + w.Button("Run this quest", "g.run", () => _gMsg = runner.Start(q, 0)); + w.SameLine(); + } + } + + /// Each step done (its stamps count now), passed (no stamp of its own, and a later step is done), and the next to do (-1: none). + private (bool[] Done, bool[] Passed, int Next) StepStates(GuideQuest q) + { + int n = q.Steps.Count, last = -1; + var done = new bool[n]; + var passed = new bool[n]; + for (int i = 0; i < n; i++) + { + GuideStep s = q.Steps[i]; + done[i] = s.Stamps.Count > 0 && s.Stamps.TrueForAll(st => _c.Progress.StateOf(q, st, _c.UtcNow) == StampState.Done); + if (done[i]) last = i; + } + for (int i = 0; i < last; i++) + if (!done[i] && q.Steps[i].Stamps.Count == 0) passed[i] = true; + int next = -1; + for (int i = 0; i < n; i++) + if (!done[i] && !passed[i]) { next = i; break; } + return (done, passed, next); + } + + /// How many stamps count now, and each one still to get with its step. + private void DrawStampSummary(UiWindow w, GuideQuest q) + { + List all = q.AllStamps(); + if (all.Count == 0) + { + w.TextDisabled("The page lists no stamps for this quest, so its steps can't be ticked: they are a guide only."); + return; + } + var stepOf = new Dictionary(StringComparer.Ordinal); + for (int i = 0; i < q.Steps.Count; i++) + foreach (string st in q.Steps[i].Stamps) stepOf.TryAdd(GuideStamp.Key(st), i + 1); + int now = 0; + var missing = new List<(string Text, bool Earlier)>(); + foreach (string st in all) + { + StampState s = _c.Progress.StateOf(q, st, _c.UtcNow); + if (s == StampState.Done) { now++; continue; } + string where = stepOf.TryGetValue(GuideStamp.Key(st), out int n) ? "step " + n : "no step"; + missing.Add(($"{st} ({where}{(s == StampState.Earlier ? ", done on an earlier run: ready again" : "")})", s == StampState.Earlier)); + } + string run = q.RepeatSec != 0 ? " this run" : ""; + if (missing.Count == 0) { w.TextColored(UiColors.Green, $"All {all.Count} stamps done{run}."); return; } + w.TextColored(now > 0 ? UiColors.Yellow : UiColors.Grey, $"{now} of {all.Count} stamps done{run}. Still to get:"); + for (int i = 0; i < missing.Count && i < 12; i++) w.TextColored(missing[i].Earlier ? UiColors.Yellow : UiColors.Red, " - " + missing[i].Text); + if (missing.Count > 12) w.TextDisabled($" ... and {missing.Count - 12} more."); + if (_c.Flags.LastReadUtc == DateTime.MinValue) w.TextDisabled("Your quest flags haven't been read yet: press Refresh."); + } + + private void DrawGuideStep(UiWindow w, GuideQuest q, int i, bool done, bool passed, bool isNext, bool isCurrent) + { + GuideStep s = q.Steps[i]; + // [x] done, [~] passed (no stamp of its own; a later step is done), [>] the next to do, [ ] still to do. + string mark = done ? "[x]" : passed ? "[~]" : isNext ? "[>]" : "[ ]"; + uint color = isCurrent || isNext ? UiColors.Yellow : done ? UiColors.Green : passed ? UiColors.Grey : 0; + if (color != 0) w.PushStyleColor(ColText, color); + w.TextWrapped($"{mark} {i + 1}. {s.Text}"); + if (color != 0) w.PopStyleColor(); + if (passed) w.Tooltip("No stamp of its own; a step after it is done, so the quest went past it."); + else if (isNext) w.Tooltip("The next step to do."); + for (int k = 0; k < s.Coords.Count && k < 4; k++) + { + string c = s.Coords[k]; + if (k > 0) w.SameLine(); + w.SmallButton("Go " + c, $"g.s{i}.c{k}", () => _gMsg = SendRynthNav("go", new[] { c })); + w.Tooltip("RynthNav plans the way to " + c + " and walks it."); + } + for (int k = 0; k < s.Notes.Count && k < 4; k++) + { + w.PushStyleColor(ColText, UiColors.Grey); + w.TextWrapped(" " + s.Notes[k]); + w.PopStyleColor(); + } + foreach (string st in s.Stamps) StampLine(w, q, st); + } + + private void StampLine(UiWindow w, GuideQuest q, string stamp) + { + switch (_c.Progress.StateOf(q, stamp, _c.UtcNow)) + { + case StampState.Done: w.TextColored(UiColors.Green, " [x] stamped " + stamp); break; + case StampState.Earlier: w.TextColored(UiColors.Yellow, " [ ] " + stamp + " - done on an earlier run; ready again"); break; + default: w.TextColored(UiColors.Red, " [ ] " + stamp + " - not stamped yet"); break; + } + w.Tooltip(StampWhy(stamp)); + } + + /// Why a stamp reads the way it does: the flag it matched and its times, or that none did. + private string StampWhy(string stamp) + { + if (_c.Progress.StampedThisSession(stamp)) return "Stamped this session (the server said so in chat)."; + if (_c.Progress.FlagOf(stamp) is QuestFlag f) + { + string when = f.CompletedOnUtc == DateTime.MinValue ? "" : $", last {f.CompletedOnUtc.ToLocalTime():yyyy-MM-dd HH:mm}"; + string timer = f.RepeatTime <= TimeSpan.Zero ? "" + : f.NextAvailableTime(_c.UtcNow) > TimeSpan.Zero ? "; again in " + GuideProgress.Short(f.NextAvailableTime(_c.UtcNow)) : "; its timer is up"; + return $"Your quest flag '{f.Key}': {f.Solves} solve(s){when}{timer}."; + } + return _c.Flags.LastReadUtc == DateTime.MinValue + ? "Your quest flags haven't been read yet (Refresh)." + : $"No quest flag named like '{stamp}' in your /myquests ({_c.Flags.Flags.Count} flags, read {_c.Flags.LastReadUtc.ToLocalTime():HH:mm})."; + } + + // ── Kill tasks ────────────────────────────────────────────────────────── + + private void DrawKillSummary(UiWindow w, GuideSet set) + { + int counting = 0, turnIn = 0, ready = 0; + foreach (GuideQuest q in set.Quests) + { + if (!set.IsKillTask(q)) continue; + switch (_c.Progress.KillOf(q, _c.UtcNow, CatalogDone(q.Title)).State) + { + case KillState.Counting: counting++; break; + case KillState.TurnIn: turnIn++; break; + case KillState.Ready: ready++; break; + } + } + string read = _c.Flags.LastReadUtc == DateTime.MinValue ? "not read yet" : "read " + GuideProgress.Short(_c.UtcNow - _c.Flags.LastReadUtc) + " ago"; + w.TextDisabled($"Kill tasks: {counting} counting, {turnIn} to turn in, {ready} ready | /myquests {read}"); + w.Tooltip("The kills come from your quest flags (/myquests): each task's counter. A kill line in chat moves the count at once,\n" + + "and with this list open the flags are read again after kills (at most once a minute, the server's limit)."); + } + + private void DrawKillLine(UiWindow w, GuideQuest q) + { + GuideProgress.Kill p = _c.Progress.KillOf(q, _c.UtcNow, CatalogDone(q.Title)); + string goal = p.Goal > 0 ? p.Goal.ToString(System.Globalization.CultureInfo.InvariantCulture) : "?"; + string count = p.Counter != null || p.FromChat + ? $"Kills: {p.Kills} / {goal}" + (p.Goal > p.Kills ? $" ({p.Goal - p.Kills} left)" : "") + : p.Goal > 0 ? $"Kills: not started (the task is {p.Goal} kills)" : "Kills: not started"; + w.TextColored(KillColor(p.State), count + " - " + p.Status); + w.SameLine(); + w.TextColored(p.DoneBefore ? UiColors.Green : UiColors.Gold, p.DoneBefore ? "(done before)" : "(first time)"); + w.TextDisabled(p.FromChat ? "From the last kill line in chat." + : p.Counter != null ? $"From /myquests: {p.Counter.Key} ({p.Counter.Solves} of {p.Counter.MaxSolves})." + : "No counter flag in /myquests yet" + (q.StartsWith.Length > 0 ? $" (talk to {q.StartsWith} to start it)." : ".")); + } + + /// A kill counter only /myquests knows. + private void DrawKillFlag(UiWindow w, QuestFlag f) + { + w.TextColored(UiColors.Gold, KillFlagLabel(f)); + QuestTimerState st = QuestTimer.State(f, true, _c.UtcNow, out string text); + w.Text($"Kills: {f.Solves} / {f.MaxSolves}" + (f.Solves < f.MaxSolves ? $" ({f.MaxSolves - f.Solves} left)" : "")); + w.TextDisabled("State: " + (st == QuestTimerState.Waiting ? "again in " + text : text)); + if (f.Description.Length > 0) w.TextWrapped(f.Description); + w.TextDisabled("Flag " + f.Key + ": no guide's kill task names this counter."); + } + + // ── Contracts ─────────────────────────────────────────────────────────── + + private void DrawGuideContract(UiWindow w, GuideSet set, GuideContract c) + { + w.TextColored(UiColors.Gold, c.Name); + if (c.Level.Length > 0) w.TextDisabled("Recommended level " + c.Level); + if (c.Description.Length > 0) w.TextWrapped(c.Description); + if (c.Where.Length > 0) w.TextWrapped("Where: " + c.Where); + if (c.Npc.Length > 0) + { + w.SmallButton("Go to " + Cut(c.Npc, 28), "g.c.go", () => _gMsg = SendRynthNav("go", new[] { c.Npc })); + w.Tooltip("RynthNav goes to " + c.Npc + "."); + } + if (c.Quests.Count > 0) + { + w.SeparatorText(c.Quests.Count == 1 ? "The quest it is for" : "The quests it is for"); + for (int i = 0; i < c.Quests.Count && i < 10; i++) + { + string t = c.Quests[i]; + if (set.Find(t) is not GuideQuest q) { w.TextDisabled(" " + t + " (no page in the guide)"); continue; } + GuideRow qr = GuideQuestRow(q); + w.SmallButton("Open", "g.c.q." + i, () => ShowGuide(GuideList.All, "w:" + q.Title)); + w.Tooltip("Opens the quest in the All list: its steps and where it stands."); + w.SameLine(); + w.Text(q.Title); + w.SameLine(); + w.TextColored(qr.Color, qr.Status); + } + } + if (c.Url.Length > 0) + { + w.SmallButton("Wiki page", "g.c.url", () => _c.Print(c.Url)); + w.Tooltip("Prints the page's address in chat: " + c.Url); + } + } + + // ── Refresh ───────────────────────────────────────────────────────────── + + /// The Guide's Refresh: /myquests, the server plugin's guide (when it takes "refresh") and the wiki feed (when on). + private RefreshResult RefreshGuide() + { + string more = ""; + if (_c.ServerGuide.Available && _c.ServerGuide.Info!.Takes(RynthServerQuestGuide.CommandRefresh) + && _c.ServerGuide.Command(RynthServerQuestGuide.CommandRefresh)) + more += $" Asked {_c.ServerGuide.Info.Plugin} to read {_c.ServerGuide.Tag}'s guide again."; + if (_c.Settings.WikiFeedOn && !_c.Wiki.Running && _c.Wiki.Start(on: true)) more += " Reading the AC Community Wiki (only pages edited since)."; + RefreshResult r = RefreshQuests(); + return r with { What = r.What + more }; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Views/OracleView.cs b/Plugins/RynthCore.Plugin.RynthOracle/Views/OracleView.cs index 9b36180..073dfba 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/Views/OracleView.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/Views/OracleView.cs @@ -9,7 +9,7 @@ namespace RynthCore.Plugin.RynthOracle.Views; /// internal sealed partial class OracleView { - public const string TabQuests = "Quests", TabCharacter = "Character", + public const string TabQuests = "Quests", TabGuide = "Guide", TabCharacter = "Character", TabSkills = "Skills", TabAttributes = "Attributes", TabProgress = "Progress", TabAugs = "Augs", TabSociety = "Society", TabTitles = "Titles", TabVoid = "Void", TabFellowship = "Fellowship", @@ -40,6 +40,9 @@ internal sealed partial class OracleView { new(TabQuests, DrawQuests, true, () => RefreshQuests(), () => "Sends /myquests to the server and reads the reply."), + // The quest guide (2026-11-27): wiki quests with their steps (the server plugin's guide and the AC Community Wiki feed). + new(TabGuide, DrawGuide, true, RefreshGuide, + () => "Reads your quest flags again (/myquests), and the guides: the server plugin's and, when its feed is on, the AC Community Wiki's."), new(TabCharacter, DrawCharacter, true, RefreshCharacter, () => "Re-reads your level, experience, buffs and skills from the game now (and RynthAi's session)."), // Skills / Attributes / Progress: RynthCore draws its Skills panel body under the tab diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Views/WikiFeedPanel.cs b/Plugins/RynthCore.Plugin.RynthOracle/Views/WikiFeedPanel.cs new file mode 100644 index 0000000..0e07af0 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthOracle/Views/WikiFeedPanel.cs @@ -0,0 +1,45 @@ +// The AC Community Wiki feed's controls (2026-11-27): on the About tab and atop the Guide tab. The feed is off by +// default, and these say what it reads and from where before anything is fetched (CommunityWikiFeed.WhatItReads). +using RynthCore.Plugin.RynthOracle.Data; +using RynthCore.Plugin.RynthOracle.Ui; + +namespace RynthCore.Plugin.RynthOracle.Views; + +internal sealed partial class OracleView +{ + private string _wikiMsg = ""; + + /// The feed's on/off, Read now and its status. keeps the two copies' widgets apart. + private void DrawWikiFeedControls(UiWindow w, string id, bool full) + { + OracleSettings s = _c.Settings; + CommunityWikiFeed feed = _c.Wiki; + if (!s.WikiFeedOn) + { + w.TextColored(UiColors.Yellow, "AC Community Wiki feed: off. Nothing is fetched."); + w.TextWrapped("When on, RynthOracle reads " + CommunityWikiFeed.WhatItReads + + " The copy is saved on this PC: " + feed.FilePath + "."); + w.Button("Turn the feed on and read it", id + ".wiki.on", () => _wikiMsg = _c.SetWikiFeed(true).Text); + w.Tooltip("Reads " + CommunityWikiFeed.Api + " now, and again at login once the copy is a day old (the setting below)."); + } + else + { + w.TextColored(UiColors.Green, "AC Community Wiki feed: on (" + CommunityWikiFeed.Host + ")."); + w.TextDisabled((feed.Running ? "Reading: " : "") + feed.Status); + if (!feed.Running) + { + w.Button("Read now", id + ".wiki.read", () => _wikiMsg = _c.ReadWikiNow().Text); + w.Tooltip("Reads the pages edited since the last read, from " + CommunityWikiFeed.Api + "."); + w.SameLine(); + } + w.Button("Turn the feed off", id + ".wiki.off", () => _wikiMsg = _c.SetWikiFeed(false).Text); + w.Tooltip("Nothing more is fetched. The copy already saved stays in the Guide tab."); + if (full) + { + w.Checkbox("Read it again at login once the copy is a day old", id + ".wiki.daily", s.WikiFeedDaily, v => { s.WikiFeedDaily = v; s.Save(); }); + w.Tooltip("Off: only Read now (or /ro wiki read) reads the wiki."); + } + } + if (_wikiMsg.Length > 0) w.TextWrapped(_wikiMsg); + } +} diff --git a/Plugins/Shared/ActionPacer.cs b/Plugins/Shared/ActionPacer.cs index a8a20b9..6d9f21a 100644 --- a/Plugins/Shared/ActionPacer.cs +++ b/Plugins/Shared/ActionPacer.cs @@ -222,6 +222,7 @@ internal static class ActionPacer _jumpAt = 0; _lootJumpAt = 0; _cycleBySpell.Clear(); + LastCastSpellId = 0; _lastSeenSeq = int.MinValue; _lastFrameMs = 0; _gapEnd = 0; @@ -1539,6 +1540,7 @@ internal static class ActionPacer if (ok) { CastsSent++; + LastCastSpellId = spellId; LastCastSeqAtSend = host.HasUseDoneSeq ? seq : -1; Begin(host, PacedKind.Cast, unchecked((uint)spellId), label, who, seq); lock (Gate) { if (_cur is { Kind: PacedKind.Cast } c && c.Id == unchecked((uint)spellId)) c.Target = targetId; } @@ -1565,6 +1567,14 @@ internal static class ActionPacer /// public static long CastsSent { get; private set; } + /// + /// The spell of the last cast sent (0 before the first, and after + /// ). A server refusal ("You don't have all the components for this spell.") + /// names no spell: it answers this one, so the buff and combat paths each take a refusal only + /// when it is their own cast. Spotted by SilentKelpie (rynth PR #12). + /// + public static int LastCastSpellId { get; private set; } + /// /// ChangeCombatMode with the pacing rules: nothing is sent when the client already reads that /// mode (the engine would push a raw 0x53 to the server anyway, and on ACE every mode change diff --git a/Plugins/Shared/QuestGuideData.cs b/Plugins/Shared/QuestGuideData.cs new file mode 100644 index 0000000..a7a66a3 --- /dev/null +++ b/Plugins/Shared/QuestGuideData.cs @@ -0,0 +1,440 @@ +// ============================================================================ +// RynthSuite - Plugins/Shared/QuestGuideData.cs +// A quest guide (2026-11-27): wiki quests as a quest reader shows them, each +// with its summary, its walkthrough as steps (the coordinates, the quest flags +// ("stamps") each step gives, the items it names), its loot and its rewards; +// plus a wiki's kill task list, society quests by rank, and contracts. +// One JSON form, written by whoever reads a wiki (RynthOracle's AC Community +// Wiki feed, or a server plugin for its own wiki, handed over through +// "RynthServer.QuestGuide") and read by RynthOracle's Guide tab. Linked source, +// so writer and reader can't drift. No reflection serializer (NativeAOT +// plugins): written with Utf8JsonWriter, read with JsonDocument, leniently. +// The shape follows SilentKelpie's guide (Forgejo rynth PR #12); re-implemented. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; + +namespace RynthCore.Plugin.Shared; + +/// One walkthrough step: what to do, where, the stamps it gives and the items it names. +internal sealed class GuideStep +{ + public string Text = ""; + /// The step's sub-lines (tips), plain text. + public List Notes = new(); + /// Coordinates the step gives, written "28.5S, 90.9W". + public List Coords = new(); + /// The quest flags the step gives, as the wiki writes them. + public List Stamps = new(); + /// The items the step names. + public List Items = new(); +} + +/// One quest of a guide. +internal sealed class GuideQuest +{ + public string Title = ""; + public string Url = ""; + /// The page's revision id (an unchanged page isn't fetched again); 0 unknown. + public long Rev; + public string Level = ""; + public string RecommendedLevel = ""; + public string Type = ""; + /// The summary box's "Kill Task" value as written ("Yes", "No", ""), see . + public string KillTask = ""; + public string StartsWith = ""; + public string StartsAt = ""; + /// The repeat timer as the wiki writes it ("20 Hours"); "" = none given. + public string Repeat = ""; + /// The repeat timer in seconds: 0 one-time (or none given), -1 given but not understood. + public long RepeatSec; + public string TimeToComplete = ""; + /// The society rank the quest is for ("Initiate", ...), from the summary box; "" none. + public string SocietyRank = ""; + public List Categories = new(); + public string Overview = ""; + public List Steps = new(); + /// Stamps the page lists that no step could be tied to. + public List ExtraStamps = new(); + /// Items to pick up on the way (named in a step that kills, loots or finds something). + public List Loot = new(); + public List Rewards = new(); + + /// Every stamp of the quest, steps first, each once. + public List AllStamps() + { + var seen = new HashSet(StringComparer.Ordinal); + var list = new List(); + foreach (GuideStep s in Steps) + foreach (string st in s.Stamps) + if (seen.Add(GuideStamp.Key(st))) list.Add(st); + foreach (string st in ExtraStamps) + if (seen.Add(GuideStamp.Key(st))) list.Add(st); + return list; + } + + /// Repeats within a day (26 h allows for the wiki's "about a day"). + public bool IsDaily => RepeatSec > 0 && RepeatSec <= 26 * 3600; + /// Repeats in more than a day, up to about a month. + public bool IsWeekly => RepeatSec > 26 * 3600 && RepeatSec <= 31L * 86400; + /// No repeat timer given: a one-time (story) quest. + public bool IsOneTime => RepeatSec == 0; + + /// + /// A kill task by its own page: the summary box says "Kill Task = Yes" (or True), or, when the box doesn't + /// say, the title does ("... Kill Task", "Kill: ..."). The guide's Kill Tasks category also counts + /// (). + /// + public bool IsKillTaskPage + { + get + { + string k = KillTask.Trim(); + if (k.Length > 0) return k.StartsWith("y", StringComparison.OrdinalIgnoreCase) || k.StartsWith("t", StringComparison.OrdinalIgnoreCase); + return Title.Contains("Kill Task", StringComparison.OrdinalIgnoreCase) + || Title.Contains("Killtask", StringComparison.OrdinalIgnoreCase) + || Title.StartsWith("Kill:", StringComparison.OrdinalIgnoreCase); + } + } + + private static readonly Regex KillCountRx = new( + @"\b(?:kill|slay|hunt|defeat|destroy)\s+(?:a\s+total\s+of\s+)?(?\d{1,5})\b", + RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + + /// How many kills the walkthrough asks for ("Kill 100 Drudge Lurkers"), from the first step that says; 0 none. + public int KillTarget + { + get + { + foreach (GuideStep s in Steps) + { + Match m = KillCountRx.Match(s.Text); + if (m.Success && int.TryParse(m.Groups["n"].Value, NumberStyles.None, CultureInfo.InvariantCulture, out int n) && n > 0) return n; + } + return 0; + } + } + + /// The creature a kill task names, as a key ("Drudge Lurker Kill Task" -> "drudgelurker"). + public string KillCreatureKey + { + get + { + string t = Title; + foreach (string cut in new[] { "Kill Task", "Killtask", "Kill:" }) + t = t.Replace(cut, " ", StringComparison.OrdinalIgnoreCase); + return KillKey(t); + } + } + + /// A creature name as a key, a plural "s" dropped ("Drudge Lurkers" -> "drudgelurker"). + public static string KillKey(string name) + { + string k = GuideStamp.Key(name); + return k.Length > 4 && k.EndsWith('s') ? k[..^1] : k; + } +} + +/// A contract: the item bought or given that starts or repeats a quest, where it comes from, and its quests. +internal sealed class GuideContract +{ + public string Title = ""; + public string Name = ""; + public string Url = ""; + public long Rev; + public string Description = ""; + public string Level = ""; + /// Where it comes from, as the page's notes say. + public string Where = ""; + /// The person it comes from (the first link in ), for RynthNav. + public string Npc = ""; + /// The quests it is for. + public List Quests = new(); +} + +/// Stamp names as the server and the wikis write them, compared alike. +internal static class GuideStamp +{ + /// Lower-case letters and digits only: "Shiny_Red_Stone", "shinyredstone" and "Shiny Red Stone" are one stamp. + public static string Key(string? stamp) + { + if (string.IsNullOrEmpty(stamp)) return ""; + var sb = new StringBuilder(stamp.Length); + foreach (char ch in stamp) + if (char.IsLetterOrDigit(ch)) sb.Append(char.ToLowerInvariant(ch)); + return sb.ToString(); + } + + private static readonly Regex Qualifier = new( + @"^(?\S+)\s+(?:(?:on|after|when|at|for|per|if|once|each|every|until|then|from)\b|\().*$", + RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + + /// + /// A stamp as a page writes it, cut to the flag: "KillTaskFoo_0101 on first completion" is the flag, and so + /// is "You've stamped Foo!". A stamp of plain words ("Shiny Red Stone Found") is left whole. + /// + public static string Clean(string? stamp) + { + if (string.IsNullOrWhiteSpace(stamp)) return ""; + string s = stamp.Trim(); + if (FromChat(s) is string chat) s = chat; + Match m = Qualifier.Match(s); + if (m.Success) s = m.Groups["stamp"].Value; + return s.TrimEnd('!', '.', ',', ';', ':', ' '); + } + + /// The stamp in a "You've stamped X!" chat line, or null. + public static string? FromChat(string? line) + { + if (string.IsNullOrEmpty(line)) return null; + const string Lead = "You've stamped "; + int i = line.IndexOf(Lead, StringComparison.OrdinalIgnoreCase); + if (i < 0) return null; + string rest = line.Substring(i + Lead.Length).Trim().TrimEnd('!', '.', ' '); + return rest.Length is > 0 and <= 120 ? rest : null; + } +} + +/// A whole guide: its quests and lists, where they came from and when. +internal sealed class QuestGuide +{ + public const int Schema = 1; + + /// The page reader that made it (QuestWikiText.ReaderVersion): a guide from an older reader is read again whole. + public int Reader = 1; + /// Where it was read from, for the reader to show ("asheron.fandom.com"). + public string Source = ""; + public DateTime UpdatedUtc = DateTime.MinValue; + public List Quests = new(); + /// The wiki's kill task list (page titles). + public List KillTasks = new(); + /// Society quests by the rank they are for (title -> "Initiate", ...), from the wiki's society categories. + public Dictionary Society = new(StringComparer.OrdinalIgnoreCase); + public List Contracts = new(); + + public bool IsEmpty => Quests.Count == 0 && Contracts.Count == 0; + + /// The society rank a quest is for: its summary box's, else its society category's; "" none. + public string SocietyRankOf(GuideQuest q) => + q.SocietyRank.Length > 0 ? q.SocietyRank : Society.TryGetValue(q.Title, out string? r) ? r : ""; + + private HashSet? _killSet; + private List? _killSetOf; + + /// A kill task: its own page says so, or the guide's kill task list names it. + public bool IsKillTask(GuideQuest q) + { + if (q.IsKillTaskPage) return true; + if (KillTasks.Count == 0) return false; + if (!ReferenceEquals(_killSetOf, KillTasks)) + { + _killSet = new HashSet(KillTasks, StringComparer.OrdinalIgnoreCase); + _killSetOf = KillTasks; + } + return _killSet!.Contains(q.Title); + } + + public GuideQuest? Find(string title) + { + foreach (GuideQuest q in Quests) + if (string.Equals(q.Title, title, StringComparison.OrdinalIgnoreCase)) return q; + return null; + } + + // ── JSON ──────────────────────────────────────────────────────────────── + + public string ToJson() + { + using var ms = new MemoryStream(); + using (var w = new Utf8JsonWriter(ms)) + { + w.WriteStartObject(); + w.WriteNumber("schema", Schema); + w.WriteNumber("reader", Reader); + w.WriteString("source", Source); + w.WriteString("updated", UpdatedUtc == DateTime.MinValue ? "" : UpdatedUtc.ToString("o", CultureInfo.InvariantCulture)); + w.WriteStartArray("quests"); + foreach (GuideQuest q in Quests) + { + w.WriteStartObject(); + w.WriteString("title", q.Title); + Opt(w, "url", q.Url); + if (q.Rev != 0) w.WriteNumber("rev", q.Rev); + Opt(w, "level", q.Level); + Opt(w, "recLevel", q.RecommendedLevel); + Opt(w, "type", q.Type); + Opt(w, "killTask", q.KillTask); + Opt(w, "startsWith", q.StartsWith); + Opt(w, "startsAt", q.StartsAt); + Opt(w, "repeat", q.Repeat); + if (q.RepeatSec != 0) w.WriteNumber("repeatSec", q.RepeatSec); + Opt(w, "time", q.TimeToComplete); + Opt(w, "societyRank", q.SocietyRank); + Arr(w, "categories", q.Categories); + Opt(w, "overview", q.Overview); + if (q.Steps.Count > 0) + { + w.WriteStartArray("steps"); + foreach (GuideStep s in q.Steps) + { + w.WriteStartObject(); + w.WriteString("text", s.Text); + Arr(w, "notes", s.Notes); + Arr(w, "coords", s.Coords); + Arr(w, "stamps", s.Stamps); + Arr(w, "items", s.Items); + w.WriteEndObject(); + } + w.WriteEndArray(); + } + Arr(w, "extraStamps", q.ExtraStamps); + Arr(w, "loot", q.Loot); + Arr(w, "rewards", q.Rewards); + w.WriteEndObject(); + } + w.WriteEndArray(); + Arr(w, "killTasks", KillTasks); + if (Society.Count > 0) + { + w.WriteStartObject("society"); + foreach (KeyValuePair kv in Society) w.WriteString(kv.Key, kv.Value); + w.WriteEndObject(); + } + if (Contracts.Count > 0) + { + w.WriteStartArray("contracts"); + foreach (GuideContract c in Contracts) + { + w.WriteStartObject(); + w.WriteString("title", c.Title); + Opt(w, "name", c.Name == c.Title ? "" : c.Name); + Opt(w, "url", c.Url); + if (c.Rev != 0) w.WriteNumber("rev", c.Rev); + Opt(w, "description", c.Description); + Opt(w, "level", c.Level); + Opt(w, "where", c.Where); + Opt(w, "npc", c.Npc); + Arr(w, "quests", c.Quests); + w.WriteEndObject(); + } + w.WriteEndArray(); + } + w.WriteEndObject(); + } + return Encoding.UTF8.GetString(ms.ToArray()); + } + + private static void Opt(Utf8JsonWriter w, string name, string value) + { + if (!string.IsNullOrEmpty(value)) w.WriteString(name, value); + } + + private static void Arr(Utf8JsonWriter w, string name, List items) + { + if (items.Count == 0) return; + w.WriteStartArray(name); + foreach (string s in items) w.WriteStringValue(s); + w.WriteEndArray(); + } + + /// Reads a guide; an empty guide when the text isn't one (missing fields read as empty). + public static QuestGuide Parse(string? json) + { + var g = new QuestGuide(); + if (string.IsNullOrWhiteSpace(json)) return g; + try + { + using JsonDocument doc = JsonDocument.Parse(json); + JsonElement root = doc.RootElement; + if (root.ValueKind != JsonValueKind.Object) return g; + if (Long(root, "schema") is long schema && schema != 0 && schema != Schema) return g; + g.Reader = (int)Math.Max(1, Long(root, "reader")); + g.Source = Str(root, "source"); + if (DateTime.TryParse(Str(root, "updated"), CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out DateTime t)) + g.UpdatedUtc = t.ToUniversalTime(); + if (root.TryGetProperty("quests", out JsonElement qs) && qs.ValueKind == JsonValueKind.Array) + foreach (JsonElement e in qs.EnumerateArray()) + if (ReadQuest(e) is GuideQuest q) g.Quests.Add(q); + g.KillTasks = Strs(root, "killTasks"); + if (root.TryGetProperty("society", out JsonElement so) && so.ValueKind == JsonValueKind.Object) + foreach (JsonProperty p in so.EnumerateObject()) + if (p.Value.ValueKind == JsonValueKind.String) g.Society[p.Name] = p.Value.GetString() ?? ""; + if (root.TryGetProperty("contracts", out JsonElement cs) && cs.ValueKind == JsonValueKind.Array) + foreach (JsonElement e in cs.EnumerateArray()) + { + if (e.ValueKind != JsonValueKind.Object) continue; + var c = new GuideContract + { + Title = Str(e, "title"), Url = Str(e, "url"), Rev = Long(e, "rev"), Description = Str(e, "description"), + Level = Str(e, "level"), Where = Str(e, "where"), Npc = Str(e, "npc"), Quests = Strs(e, "quests"), + }; + string n = Str(e, "name"); + c.Name = n.Length > 0 ? n : c.Title; + if (c.Title.Length > 0) g.Contracts.Add(c); + } + } + catch (JsonException) + { + return new QuestGuide(); + } + return g; + } + + private static GuideQuest? ReadQuest(JsonElement e) + { + if (e.ValueKind != JsonValueKind.Object) return null; + var q = new GuideQuest + { + Title = Str(e, "title"), Url = Str(e, "url"), Rev = Long(e, "rev"), + Level = Str(e, "level"), RecommendedLevel = Str(e, "recLevel"), Type = Str(e, "type"), KillTask = Str(e, "killTask"), + StartsWith = Str(e, "startsWith"), StartsAt = Str(e, "startsAt"), Repeat = Str(e, "repeat"), RepeatSec = Long(e, "repeatSec"), + TimeToComplete = Str(e, "time"), SocietyRank = Str(e, "societyRank"), Categories = Strs(e, "categories"), + Overview = Str(e, "overview"), ExtraStamps = Stamps(Strs(e, "extraStamps")), Loot = Strs(e, "loot"), Rewards = Strs(e, "rewards"), + }; + if (q.Title.Length == 0) return null; + if (e.TryGetProperty("steps", out JsonElement ss) && ss.ValueKind == JsonValueKind.Array) + foreach (JsonElement s in ss.EnumerateArray()) + { + if (s.ValueKind != JsonValueKind.Object) continue; + q.Steps.Add(new GuideStep + { + Text = Str(s, "text"), Notes = Strs(s, "notes"), Coords = Strs(s, "coords"), + Stamps = Stamps(Strs(s, "stamps")), Items = Strs(s, "items"), + }); + } + return q; + } + + /// Stamps cut to their flags (GuideStamp.Clean), each once. + private static List Stamps(List raw) + { + var list = new List(raw.Count); + foreach (string r in raw) + { + string s = GuideStamp.Clean(r); + if (s.Length > 0 && !list.Exists(x => GuideStamp.Key(x) == GuideStamp.Key(s))) list.Add(s); + } + return list; + } + + private static string Str(JsonElement o, string name) => + o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? "" : ""; + + private static long Long(JsonElement o, string name) => + o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt64(out long n) ? n : 0; + + private static List Strs(JsonElement o, string name) + { + var list = new List(); + if (!o.TryGetProperty(name, out JsonElement a) || a.ValueKind != JsonValueKind.Array) return list; + foreach (JsonElement e in a.EnumerateArray()) + if (e.ValueKind == JsonValueKind.String && e.GetString() is { Length: > 0 } s) list.Add(s); + return list; + } +} diff --git a/Plugins/Shared/QuestWikiText.cs b/Plugins/Shared/QuestWikiText.cs new file mode 100644 index 0000000..41159d1 --- /dev/null +++ b/Plugins/Shared/QuestWikiText.cs @@ -0,0 +1,623 @@ +// ============================================================================ +// RynthSuite - Plugins/Shared/QuestWikiText.cs +// Reading MediaWiki quest pages into a quest guide (QuestGuideData.cs), 2026-11-27. +// Pure text work: whoever fetches the pages (RynthOracle's AC Community Wiki feed, +// or a server plugin for a wiki of its own built on the same templates) hands the +// wikitext here, and the offline tests feed it made-up pages. Linked source. +// +// What a quest page looks like on the AC Community Wiki and the wikis made from it: +// {{Quest Summary | Level = 50+ | Quest Type = Solo | Starts With = [[Someone]] +// | Starts At = [[Some Town]] | Repeat Timer = 20 Hours | Kill Task = Yes }} +// == Overview == a paragraph +// == Walkthrough == numbered "# " steps with "#* " tips, or bullets, or paragraphs; +// {{stamped|Flag}} marks a step's quest flag, {{Itemlink|Item}} an item +// == Stamps == stamps listed apart from the steps +// == Rewards == {{Rewards Table | ...}} or a plain list +// [[Category:...]] +// Coordinates are written every which way ("28.5S, 90.9W", "62.7s 66.6W"). +// Also the MediaWiki API's JSON answers (list=categorymembers, list=embeddedin, +// prop=info, prop=revisions), read without the HTTP so the tests can feed them. +// The reader follows SilentKelpie's (Forgejo rynth PR #12); re-implemented here. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; + +namespace RynthCore.Plugin.Shared; + +internal static class QuestWikiText +{ + /// + /// This reader's version, saved in a guide (QuestGuide.Reader). Raise it when the reader changes what it takes + /// from a page: a feed then reads every page again, not only those edited since. + /// + public const int ReaderVersion = 1; + + private const RegexOptions Ci = RegexOptions.IgnoreCase | RegexOptions.CultureInvariant; + + private static readonly Regex CommentRx = new(@"", RegexOptions.Singleline | RegexOptions.CultureInvariant); + private static readonly Regex RefRx = new(@"/]*/>|]*>.*?", RegexOptions.Singleline | Ci); + private static readonly Regex HeadingRx = new(@"^\s*==\s*([^=].*?)\s*==\s*$", RegexOptions.CultureInvariant); + private static readonly Regex StampRx = new(@"\{\{\s*stamped\s*\|\s*([^}|]+?)\s*\}\}", Ci); + private static readonly Regex ItemRx = new(@"\{\{\s*Item\s*link\s*\|\s*([^}|]+?)\s*(?:\|[^}]*)?\}\}", Ci); + private static readonly Regex CategoryRx = new(@"\[\[\s*Category\s*:\s*([^\]|]+?)\s*(?:\|[^\]]*)?\]\]", Ci); + private static readonly Regex FirstLinkRx = new(@"\[\[([^\[\]|#]+)(?:\|[^\[\]]*)?\]\]", RegexOptions.CultureInvariant); + private static readonly Regex CoordsRx = new( + @"(?\d+(?:\.\d+)?)\s*(?[NnSs])[\s,]*(?\d+(?:\.\d+)?)\s*(?[EeWw])\b", RegexOptions.CultureInvariant); + + /// The page is a quest page (it has the Quest Summary box). + public static bool IsQuestPage(string? wikitext) => + !string.IsNullOrEmpty(wikitext) && wikitext.IndexOf("{{Quest Summary", StringComparison.OrdinalIgnoreCase) >= 0; + + /// A contract's item page: the {{Item}} box, and a contract's title or category. + public static bool IsContractPage(string title, string? wikitext) => + !string.IsNullOrEmpty(wikitext) && wikitext.IndexOf("{{Item", StringComparison.OrdinalIgnoreCase) >= 0 + && (title.StartsWith("Contract for ", StringComparison.OrdinalIgnoreCase) + || wikitext.IndexOf("[[Category:Contracts", StringComparison.OrdinalIgnoreCase) >= 0); + + /// A page's address: the wiki's article path plus the title with underscores. + public static string UrlOf(string wikiBase, string title) => + wikiBase + Uri.EscapeDataString(title.Trim().Replace(' ', '_')).Replace("%2F", "/"); + + private static string Prepare(string? wikitext) => + RefRx.Replace(CommentRx.Replace(wikitext ?? "", ""), "").Replace("\r\n", "\n").Replace('\r', '\n'); + + /// Reads a quest page (: its revision id, 0 unknown). + public static GuideQuest ParseQuest(string title, string wikitext, long rev, string wikiBase) + { + var q = new GuideQuest { Title = title.Trim(), Url = UrlOf(wikiBase, title), Rev = rev }; + string text = Prepare(wikitext); + + foreach (Match m in CategoryRx.Matches(text)) + { + string c = m.Groups[1].Value.Trim(); + if (c.Length > 0 && !q.Categories.Contains(c)) q.Categories.Add(c); + } + + Dictionary box = TemplateParams(text, "Quest Summary"); + q.Level = Clean(Param(box, "Level")); + q.RecommendedLevel = Clean(Param(box, "Recommended Level", "Recommended")); + q.Type = Clean(Param(box, "Quest Type", "Type")); + q.KillTask = Clean(Param(box, "Kill Task")); + q.StartsWith = Clean(Param(box, "Starts With", "NPC")); + q.StartsAt = Clean(Param(box, "Starts At", "Location")); + q.Repeat = Clean(Param(box, "Repeat Timer", "Timer", "Repeat")); + q.RepeatSec = RepeatSeconds(q.Repeat); + q.TimeToComplete = Clean(Param(box, "Time to Complete")); + q.SocietyRank = Clean(Param(box, "Society Rank")); + + string overview = ""; + List? walk = null; + var loose = new List(); + foreach (var (heading, lines) in Sections(text)) + { + string h = heading.ToLowerInvariant(); + if (h.StartsWith("overview", StringComparison.Ordinal) || h.Contains("description", StringComparison.Ordinal)) + { + string o = Clean(string.Join(" ", lines)); + if (o.Length > 0 && (h.StartsWith("overview", StringComparison.Ordinal) || overview.Length == 0)) overview = o; + } + else if (h.StartsWith("walkthrough", StringComparison.Ordinal) || h == "steps" || h.StartsWith("quest steps", StringComparison.Ordinal) + || h == "notes" && walk == null) + walk = lines; + else if (h.Contains("stamp", StringComparison.Ordinal)) + { + foreach (string l in lines) + foreach (Match m in StampRx.Matches(l)) + if (GuideStamp.Clean(m.Groups[1].Value) is { Length: > 0 } s) loose.Add(s); + } + else if (h.StartsWith("reward", StringComparison.Ordinal)) + q.Rewards = Rewards(string.Join("\n", lines)); + } + q.Overview = overview.Length > 700 ? overview.Substring(0, 700).TrimEnd() + "..." : overview; + if (walk != null) q.Steps = Steps(walk); + + // Stamps listed apart: tied to the step that names them, else (one per stampless step) in order, else kept apart. + var have = new HashSet(StringComparer.Ordinal); + foreach (GuideStep s in q.Steps) foreach (string st in s.Stamps) have.Add(GuideStamp.Key(st)); + var left = new List(); + foreach (string st in loose) + { + if (!have.Add(GuideStamp.Key(st))) continue; + if (StepNamed(q.Steps, st) is GuideStep byName) byName.Stamps.Add(st); + else left.Add(st); + } + List bare = q.Steps.FindAll(s => s.Stamps.Count == 0); + if (left.Count > 0 && left.Count == bare.Count) + { + for (int i = 0; i < left.Count; i++) bare[i].Stamps.Add(left[i]); + left.Clear(); + } + q.ExtraStamps = left; + q.Loot = LootItems(q.Steps); + return q; + } + + /// A contract's item page: {{Item | Name, Description, Recommended Level}}, {{Intro | Related Quests}}, the notes' "Purchased from [[X]]". + public static GuideContract ParseContract(string title, string wikitext, long rev, string wikiBase) + { + string text = Prepare(wikitext); + var c = new GuideContract { Title = title.Trim(), Url = UrlOf(wikiBase, title), Rev = rev }; + Dictionary item = TemplateParams(text, "Item"); + Dictionary intro = TemplateParams(text, "Intro"); + string name = Clean(Param(item, "Name")); + c.Name = name.Length > 0 ? name : c.Title; + c.Description = Clean(Param(item, "Description")); + c.Level = Clean(Param(item, "Recommended Level", "Level")); + foreach (Match m in FirstLinkRx.Matches(Param(intro, "Related Quests", "Related Quest", "Quest"))) + { + string t = m.Groups[1].Value.Trim().TrimStart(':'); + if (t.Length > 0 && !c.Quests.Contains(t)) c.Quests.Add(t); + } + foreach (var (heading, lines) in Sections(text)) + { + if (!heading.StartsWith("note", StringComparison.OrdinalIgnoreCase)) continue; + foreach (string l in lines) + { + if (l.IndexOf("purchase", StringComparison.OrdinalIgnoreCase) < 0 && l.IndexOf("sold by", StringComparison.OrdinalIgnoreCase) < 0 + && l.IndexOf("given by", StringComparison.OrdinalIgnoreCase) < 0 && l.IndexOf("from [[", StringComparison.OrdinalIgnoreCase) < 0) continue; + c.Where = Clean(l.TrimStart('*', '#', ':', ' ')); + Match m = FirstLinkRx.Match(l); + if (m.Success) c.Npc = Clean("[[" + m.Groups[1].Value + "]]"); + break; + } + if (c.Where.Length > 0) break; + } + return c; + } + + // ── Sections and steps ────────────────────────────────────────────────── + + /// The page's "== X ==" sections with their lines (the text before the first heading is ""). + internal static List<(string Heading, List Lines)> Sections(string text) + { + var list = new List<(string, List)>(); + string heading = ""; + var lines = new List(); + foreach (string raw in text.Split('\n')) + { + Match m = HeadingRx.Match(raw); + if (m.Success) + { + list.Add((heading, lines)); + heading = m.Groups[1].Value.Trim(); + lines = new List(); + continue; + } + lines.Add(raw); + } + list.Add((heading, lines)); + return list; + } + + /// + /// The walkthrough's steps: its numbered "# " lines with the "#*", "#:" and "##" lines under them; with no + /// numbered lines, its top-level bullets; with neither, its paragraphs (one step each). + /// + internal static List Steps(List lines) + { + var steps = new List(); + bool numbered = lines.Exists(l => IsTopLevel(l, '#')); + bool bullets = !numbered && lines.Exists(l => IsTopLevel(l, '*')); + if (numbered || bullets) + { + char lead = numbered ? '#' : '*'; + GuideStep? cur = null; + foreach (string raw in lines) + { + string l = raw.TrimEnd(); + if (l.Length == 0) continue; + if (IsTopLevel(l, lead)) steps.Add(cur = NewStep(l.Substring(1))); + else if (cur != null && (l[0] == lead || l[0] == '*' || l[0] == ':')) AddSub(cur, l.TrimStart('#', '*', ':', ';')); + // A paragraph or a table between steps is left out. + } + } + else + { + var para = new StringBuilder(); + void Flush() + { + string p = para.ToString().Trim(); + para.Clear(); + if (p.Length > 0) steps.Add(NewStep(p)); + } + foreach (string raw in lines) + { + string l = raw.Trim(); + if (l.Length == 0 || l.StartsWith("===", StringComparison.Ordinal) || l.StartsWith("{|", StringComparison.Ordinal) + || l.StartsWith("|}", StringComparison.Ordinal) || l.StartsWith("[[File:", StringComparison.OrdinalIgnoreCase)) + { + Flush(); + continue; + } + if (para.Length > 0) para.Append(' '); + para.Append(l); + } + Flush(); + } + steps.RemoveAll(s => s.Text.Length == 0 && s.Stamps.Count == 0 && s.Coords.Count == 0); + return steps; + } + + private static bool IsTopLevel(string l, char lead) => + l.Length > 1 && l[0] == lead && l[1] != '*' && l[1] != '#' && l[1] != ':' && l[1] != ';'; + + private static GuideStep NewStep(string raw) + { + var s = new GuideStep(); + Collect(s, raw); + s.Text = Clean(raw); + return s; + } + + private static void AddSub(GuideStep s, string raw) + { + Collect(s, raw); + string note = Clean(raw); + if (note.Length > 0) s.Notes.Add(note); + } + + /// The stamps, items and coordinates in one line of a step. + private static void Collect(GuideStep s, string raw) + { + foreach (Match m in StampRx.Matches(raw)) + { + string st = GuideStamp.Clean(m.Groups[1].Value); + if (st.Length > 0 && !s.Stamps.Exists(x => GuideStamp.Key(x) == GuideStamp.Key(st))) s.Stamps.Add(st); + } + foreach (Match m in ItemRx.Matches(raw)) + { + string it = m.Groups[1].Value.Trim(); + if (it.Length > 0 && !s.Items.Exists(x => x.Equals(it, StringComparison.OrdinalIgnoreCase))) s.Items.Add(it); + } + foreach (string c in Coords(Clean(raw))) + if (!s.Coords.Contains(c)) s.Coords.Add(c); + } + + /// Every coordinate pair in the text, written "12.3N, 45.6E", in order. + public static List Coords(string? text) + { + var list = new List(); + if (string.IsNullOrEmpty(text)) return list; + foreach (Match m in CoordsRx.Matches(text)) + { + string c = string.Create(CultureInfo.InvariantCulture, + $"{m.Groups["ns"].Value}{char.ToUpperInvariant(m.Groups["nsc"].Value[0])}, {m.Groups["ew"].Value}{char.ToUpperInvariant(m.Groups["ewc"].Value[0])}"); + if (!list.Contains(c)) list.Add(c); + } + return list; + } + + private static readonly Regex LootVerbRx = new( + @"\b(kill|kills|killing|loot|loots|looted|drop|drops|dropped|collect|collects|gather|find|finds|obtain|obtains|pick\s+up|grab|hunt|hunts)\b", Ci); + private static readonly Regex HandInRx = new(@"^\s*(instead|return|turn\s+in|hand\s+in|give|bring|upgrade)\b", Ci); + + /// The items worth picking up: named in a step that kills, loots or finds something (not one only handed in), each once. + internal static List LootItems(List steps) + { + var loot = new List(); + foreach (GuideStep s in steps) + { + if (s.Items.Count == 0) continue; + if (!LootVerbRx.IsMatch(s.Text + " " + string.Join(" ", s.Notes)) || HandInRx.IsMatch(s.Text)) continue; + foreach (string it in s.Items) + if (!loot.Exists(x => x.Equals(it, StringComparison.OrdinalIgnoreCase))) loot.Add(it); + } + return loot; + } + + private static readonly HashSet StampNoise = new(StringComparer.Ordinal) + { "quest", "stamp", "found", "turnin", "turned", "done", "complete", "completed", "kill", "killed", "the", "obtained", "timer", "flag", "started", "start" }; + + /// The one step a stamp listed apart belongs to by its words ("SampleFang" goes with the step about the fang), or null. + internal static GuideStep? StepNamed(List steps, string stamp) + { + List tokens = StampTokens(stamp); + if (tokens.Count == 0) return null; + GuideStep? best = null; + int bestScore = 0; + bool tie = false; + foreach (GuideStep s in steps) + { + var words = Words(s.Text + " " + string.Join(" ", s.Notes) + " " + string.Join(" ", s.Items)); + int score = 0; + foreach (string t in tokens) + foreach (string w in words) + if (w.Length >= 4 && (w == t || w.StartsWith(t, StringComparison.Ordinal) || t.StartsWith(w, StringComparison.Ordinal))) { score++; break; } + if (score > bestScore) { best = s; bestScore = score; tie = false; } + else if (score == bestScore && score > 0) tie = true; + } + return tie ? null : best; + } + + /// "Shiny_Red_Stone_Found" -> shiny, red, stone; "SampleFangs" -> sample, fang (3+ letters, noise words left out). + internal static List StampTokens(string stamp) + { + string spaced = Regex.Replace(stamp, @"(?<=[a-z0-9])(?=[A-Z])", " "); + var list = new List(); + foreach (string w in Words(spaced)) + { + string t = w.Length > 4 && w.EndsWith('s') ? w[..^1] : w; + if (t.Length >= 3 && !StampNoise.Contains(t) && !list.Contains(t)) list.Add(t); + } + return list; + } + + private static HashSet Words(string text) + { + var set = new HashSet(StringComparer.Ordinal); + foreach (Match m in Regex.Matches(text.ToLowerInvariant(), "[a-z0-9]+")) set.Add(m.Value); + return set; + } + + // ── Rewards ───────────────────────────────────────────────────────────── + + /// The rewards section as short lines ("For X:", then each reward); a plain list when there is no table. At most 30. + internal static List Rewards(string section) + { + var lines = new List(); + int at = 0; + bool anyTable = false; + while (true) + { + int i = section.IndexOf("{{Rewards Table", at, StringComparison.OrdinalIgnoreCase); + if (i < 0) break; + int end = TemplateEnd(section, i); + if (end < 0) break; + anyTable = true; + Dictionary p = SplitParams(section.Substring(i + 2, end - i - 4)); + string task = Clean(Param(p, "Quest Task", "Task")); + if (task.Length > 0) lines.Add("For " + task + ":"); + foreach (string key in new[] { "Item Reward", "Items", "XP Reward", "Experience", "Luminance Reward", "Luminance", "Other Reward", "Other" }) + { + string v = Param(p, key); + foreach (string part in v.Split('\n')) + { + string c = Clean(part.TrimStart('*', ' ', '#')); + if (c.Length == 0) continue; + lines.Add(key.StartsWith("XP", StringComparison.Ordinal) || key.StartsWith("Exp", StringComparison.Ordinal) ? "XP: " + c + : key.StartsWith("Lum", StringComparison.Ordinal) ? "Luminance: " + c : c); + } + } + at = end; + } + if (!anyTable) + foreach (string l in section.Split('\n')) + if (Clean(l.TrimStart('*', '#', ':', ' ')) is { Length: > 0 } c) lines.Add(c); + if (lines.Count > 30) lines.RemoveRange(30, lines.Count - 30); + return lines; + } + + // ── Templates ─────────────────────────────────────────────────────────── + + /// The first {{name ...}} template's named parameters (keys trimmed, any case). + internal static Dictionary TemplateParams(string text, string name) + { + var none = new Dictionary(StringComparer.OrdinalIgnoreCase); + int i = text.IndexOf("{{" + name, StringComparison.OrdinalIgnoreCase); + if (i < 0) return none; + int end = TemplateEnd(text, i); + if (end < 0) end = text.Length; + int bodyEnd = Math.Max(i + 2, end - 2); + return SplitParams(text.Substring(i + 2, bodyEnd - (i + 2))); + } + + /// Just past the "}}" that closes the template starting at , or -1. + private static int TemplateEnd(string text, int start) + { + int depth = 0; + for (int i = start; i < text.Length - 1; i++) + { + if (text[i] == '{' && text[i + 1] == '{') { depth++; i++; } + else if (text[i] == '}' && text[i + 1] == '}') { depth--; i++; if (depth == 0) return i + 1; } + } + return -1; + } + + /// "| key = value" parameters split at the top level only (links and inner templates kept whole). + private static Dictionary SplitParams(string body) + { + var parts = new List(); + int depthT = 0, depthL = 0, from = 0; + for (int i = 0; i < body.Length; i++) + { + char c = body[i]; + char n = i + 1 < body.Length ? body[i + 1] : '\0'; + if (c == '{' && n == '{') { depthT++; i++; } + else if (c == '}' && n == '}') { depthT--; i++; } + else if (c == '[' && n == '[') { depthL++; i++; } + else if (c == ']' && n == ']') { depthL--; i++; } + else if (c == '|' && depthT == 0 && depthL == 0) + { + parts.Add(body.Substring(from, i - from)); + from = i + 1; + } + } + parts.Add(body.Substring(from)); + var map = new Dictionary(StringComparer.OrdinalIgnoreCase); + for (int k = 1; k < parts.Count; k++) + { + int eq = parts[k].IndexOf('='); + if (eq <= 0) continue; + string key = Regex.Replace(parts[k].Substring(0, eq), @"\s+", " ").Trim(); + if (key.Length > 0 && !map.ContainsKey(key)) map[key] = parts[k].Substring(eq + 1).Trim(); + } + return map; + } + + private static string Param(Dictionary p, params string[] names) + { + foreach (string n in names) + if (p.TryGetValue(n, out string? v) && v.Trim().Length > 0) return v.Trim(); + return ""; + } + + // ── Text ──────────────────────────────────────────────────────────────── + + private static readonly Regex FileRx = new(@"\[\[\s*(File|Image)\s*:[^\[\]]*(\[\[[^\]]*\]\][^\[\]]*)*\]\]", Ci); + private static readonly Regex LinkRx = new(@"\[\[([^\[\]|]*)\|([^\[\]]*)\]\]", RegexOptions.CultureInvariant); + private static readonly Regex PlainLinkRx = new(@"\[\[([^\[\]|]*)\]\]", RegexOptions.CultureInvariant); + private static readonly Regex ExtLinkRx = new(@"\[(https?://[^\s\]]+)(?:\s+([^\]]*))?\]", RegexOptions.CultureInvariant); + private static readonly Regex NamedTemplateRx = new(@"\{\{\s*(?:Item\s*link|Icon\s*Link|Creature\s*link|NPC\s*link|Link)\s*\|\s*([^}|]+?)\s*(?:\|[^{}]*)?\}\}", Ci); + private static readonly Regex AnyTemplateRx = new(@"\{\{[^{}]*\}\}", RegexOptions.CultureInvariant); + private static readonly Regex BrRx = new(@"", Ci); + private static readonly Regex TagRx = new(@"<[^>]+>", RegexOptions.CultureInvariant); + private static readonly Regex SpaceRx = new(@"\s+", RegexOptions.CultureInvariant); + + /// Wikitext as plain text: links as their words, item templates as the item; other templates, files, bold and tags dropped. + public static string Clean(string? wikitext) + { + if (string.IsNullOrEmpty(wikitext)) return ""; + string s = StampRx.Replace(wikitext, ""); + s = FileRx.Replace(s, ""); + s = CategoryRx.Replace(s, ""); + s = LinkRx.Replace(s, "$2"); + s = PlainLinkRx.Replace(s, m => m.Groups[1].Value.TrimStart(':')); + s = ExtLinkRx.Replace(s, m => m.Groups[2].Success && m.Groups[2].Value.Length > 0 ? m.Groups[2].Value : m.Groups[1].Value); + s = NamedTemplateRx.Replace(s, "$1"); + for (int pass = 0; pass < 4 && s.Contains("{{", StringComparison.Ordinal); pass++) s = AnyTemplateRx.Replace(s, ""); + s = BrRx.Replace(s, " "); + s = TagRx.Replace(s, ""); + s = s.Replace("'''", "").Replace("''", ""); + s = s.Replace(" ", " ").Replace("&", "&").Replace("<", "<").Replace(">", ">").Replace(""", "\""); + return SpaceRx.Replace(s, " ").Trim().TrimStart('*', '#', ':', ' ').Trim(); + } + + /// + /// A repeat timer in seconds: "20 Hours", "7 days", "1 Week", "3d 12h", "Daily", "Weekly"; 0 for none + /// ("", "None", "Once", "One time", "Non Repeatable"); -1 for words it doesn't understand. + /// + public static long RepeatSeconds(string? repeat) + { + if (string.IsNullOrWhiteSpace(repeat)) return 0; + string r = repeat.Trim().ToLowerInvariant(); + if (r is "none" or "n/a" or "na" or "-" or "once" or "no" or "never" + || r.StartsWith("one time", StringComparison.Ordinal) || r.StartsWith("one-time", StringComparison.Ordinal) + || r.StartsWith("not repeatable", StringComparison.Ordinal) || r.StartsWith("non repeatable", StringComparison.Ordinal) + || r.StartsWith("non-repeatable", StringComparison.Ordinal) || r.StartsWith("unrepeatable", StringComparison.Ordinal)) return 0; + if (r.StartsWith("daily", StringComparison.Ordinal)) return 86400; + if (r.StartsWith("weekly", StringComparison.Ordinal)) return 7 * 86400; + long total = 0; + foreach (Match m in Regex.Matches(r, @"(\d+(?:\.\d+)?)\s*(weeks?|w|days?|d|hours?|hrs?|h|minutes?|mins?|m|seconds?|secs?|s)\b")) + { + double n = double.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture); + double mult = m.Groups[2].Value[0] switch { 'w' => 7 * 86400, 'd' => 86400, 'h' => 3600, 'm' => 60, _ => 1 }; + total += (long)Math.Round(n * mult); + } + return total > 0 ? total : -1; + } + + // ── The MediaWiki API's answers ───────────────────────────────────────── + + /// Titles per prop=info / prop=revisions request (the API's limit for an anonymous reader). + public const int TitlesPerRequest = 50; + + /// A GET URL with these parameters (format=json, formatversion=2 added; every value escaped). + public static string ApiUrl(string api, params (string Key, string Value)[] args) + { + var sb = new StringBuilder(api); + sb.Append(api.Contains('?') ? '&' : '?').Append("format=json&formatversion=2"); + foreach (var (k, v) in args) sb.Append('&').Append(Uri.EscapeDataString(k)).Append('=').Append(Uri.EscapeDataString(v)); + return sb.ToString(); + } + + /// list=categorymembers / list=embeddedin: the pages (namespace 0), sub-categories (14), and the "continue" parameters (empty = done). + public static (List Pages, List SubCats, List<(string Key, string Value)> Continue) Members(string json, string listName) + { + var pages = new List(); + var cats = new List(); + var cont = new List<(string, string)>(); + try + { + using JsonDocument d = JsonDocument.Parse(json); + JsonElement root = d.RootElement; + if (root.TryGetProperty("query", out JsonElement q) && q.TryGetProperty(listName, out JsonElement list) && list.ValueKind == JsonValueKind.Array) + foreach (JsonElement m in list.EnumerateArray()) + { + string title = Str(m, "title"); + if (title.Length == 0) continue; + int ns = m.TryGetProperty("ns", out JsonElement n) && n.TryGetInt32(out int v) ? v : 0; + if (ns == 14) cats.Add(title); + else if (ns == 0) pages.Add(title); + } + if (root.TryGetProperty("continue", out JsonElement c) && c.ValueKind == JsonValueKind.Object) + foreach (JsonProperty p in c.EnumerateObject()) + cont.Add((p.Name, p.Value.ValueKind == JsonValueKind.String ? p.Value.GetString() ?? "" : p.Value.GetRawText())); + } + catch (JsonException) { } + return (pages, cats, cont); + } + + /// prop=info: each page's last revision id (missing pages left out). + public static Dictionary LastRevisions(string json) + { + var map = new Dictionary(StringComparer.Ordinal); + foreach (JsonElement p in Pages(json)) + { + if (p.TryGetProperty("missing", out _)) continue; + string title = Str(p, "title"); + if (title.Length > 0) map[title] = p.TryGetProperty("lastrevid", out JsonElement r) && r.TryGetInt64(out long v) ? v : 0; + } + return map; + } + + /// prop=revisions (rvprop=content|ids, rvslots=main): each page's title, revision id and wikitext. + public static List<(string Title, long Rev, string Text)> Contents(string json) + { + var list = new List<(string, long, string)>(); + foreach (JsonElement p in Pages(json)) + { + string title = Str(p, "title"); + if (title.Length == 0 || !p.TryGetProperty("revisions", out JsonElement revs) || revs.ValueKind != JsonValueKind.Array) continue; + foreach (JsonElement r in revs.EnumerateArray()) + { + long id = r.TryGetProperty("revid", out JsonElement i) && i.TryGetInt64(out long v) ? v : 0; + string text = r.TryGetProperty("slots", out JsonElement slots) && slots.TryGetProperty("main", out JsonElement main) + ? Str(main, "content") : Str(r, "content"); + list.Add((title, id, text)); + break; + } + } + return list; + } + + /// query.pages (an array in formatversion=2, keyed by id in 1), copied out so the document can go. + private static List Pages(string json) + { + var list = new List(); + try + { + using JsonDocument d = JsonDocument.Parse(json); + if (d.RootElement.TryGetProperty("query", out JsonElement q) && q.TryGetProperty("pages", out JsonElement pages)) + { + if (pages.ValueKind == JsonValueKind.Array) + foreach (JsonElement p in pages.EnumerateArray()) list.Add(p.Clone()); + else if (pages.ValueKind == JsonValueKind.Object) + foreach (JsonProperty p in pages.EnumerateObject()) list.Add(p.Value.Clone()); + } + } + catch (JsonException) { } + return list; + } + + /// Titles in requests of at most , joined with '|'. + public static List Batches(IReadOnlyList titles) + { + var list = new List(); + for (int i = 0; i < titles.Count; i += TitlesPerRequest) + { + int n = Math.Min(TitlesPerRequest, titles.Count - i); + var part = new string[n]; + for (int k = 0; k < n; k++) part[k] = titles[i + k]; + list.Add(string.Join("|", part)); + } + return list; + } + + private static string Str(JsonElement o, string name) => + o.ValueKind == JsonValueKind.Object && o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? "" : ""; +} diff --git a/Plugins/Shared/RynthAiHubApi.cs b/Plugins/Shared/RynthAiHubApi.cs index d72ab6b..981013d 100644 --- a/Plugins/Shared/RynthAiHubApi.cs +++ b/Plugins/Shared/RynthAiHubApi.cs @@ -30,7 +30,7 @@ public static class RynthAiHub public const string SectionVTankImport = "vtank-import"; // BackAwayFrom results. - /// The back-jump started; attacks wait until it settles. + /// The back-away started (a run away, or the fallback back-jump); attacks wait until it is over. public const int BackAwayStarted = 1; /// Not now: RynthAi's macro isn't running with combat on, it is backing away already, or it isn't logged in. public const int BackAwayNotNow = 0; @@ -205,9 +205,11 @@ public unsafe struct RynthAiHubApiV1 /// /// BackAwayFrom(objectId, radiusYards, holdMs): a server plugin's "get out of this radius now" (RynthILT: - /// the Empyrean Handler's lethal ring). RynthAi faces the object, run-back jumps away from it (holdMs = - /// the jump's charge, 100-3000) and holds its attacks until the jump settles, then re-engages the same - /// target; the radius is at least the player's Ring Range. Only while RynthAi's macro runs with combat + /// the Empyrean Handler's lethal ring). RynthAi stops attacking, faces directly away from the object and + /// runs until outside the radius plus a margin (re-aiming as it goes; at most a few seconds), holds its + /// attacks until then and re-engages the same target; the radius is at least the player's Ring Range. + /// On an engine without heading snap or autorun it run-back jumps instead (holdMs = the jump's charge, + /// 100-3000). Only while RynthAi's macro runs with combat /// on. Returns and the other BackAway* results. Pump thread. /// public delegate* unmanaged[Cdecl] BackAwayFrom; diff --git a/Plugins/Shared/RynthServerQuestGuideApi.cs b/Plugins/Shared/RynthServerQuestGuideApi.cs new file mode 100644 index 0000000..f8f1009 --- /dev/null +++ b/Plugins/Shared/RynthServerQuestGuideApi.cs @@ -0,0 +1,130 @@ +// ============================================================================ +// RynthSuite - Plugins/Shared/RynthServerQuestGuideApi.cs +// The "RynthServer.QuestGuide" interface (2026-11-27): a server plugin's own +// quest guide (its wiki's quests with their steps, stamps, places and loot), +// for a quest reader such as RynthOracle's Guide tab, which shows it without +// knowing the server. Server-specific guide data (a server's own wiki, read +// however that wiki needs) stays in the server's plugin; the reader only takes +// the finished guide. Same idea as "RynthServer.QuestPack" (the quest list): +// RynthCore says which plugin owns the active server (plugin API v86, +// GetServerStateJson "activePlugin"), and the reader asks only that plugin +// (host GetPluginInterface), so a guide shows only while its server is active. +// No interface = no server guide. +// +// The idea and the first version came from SilentKelpie's backlog (Forgejo +// rynth PR #12, "RynthServer.QuestGuide" over a guide file); this one hands +// the guide over in a buffer instead of a file path and adds a command line. +// Compiled into the server plugins and their readers (linked source), so the +// layout can't drift. The guide's own format: QuestGuideData.cs. +// +// Rules (as the other shared interfaces): +// - Append-only: new functions go at the end, and Version goes up. +// - Strings are UTF-8, NUL-terminated. The info JSON is plain ASCII. +// - Every function returns safely (no exception crosses the boundary). +// - The table is allocated once per loaded copy of the plugin and never freed; +// shutdown sets Version to 0, and a reader re-queries when it sees that. +// +// GetGuideInfoJson payload (schema 1; read leniently, fields may be added): +// { +// "schema": 1, +// "tag": "My Server", // what the reader calls the guide ("My Server Wiki") +// "plugin": "RynthMyServer", +// "revision": 3, // goes up whenever the guide changes (read GetGuideJson again) +// "bytes": 123456, // GetGuideJson's length in UTF-8 bytes (0 = no guide yet) +// "quests": 317, // quests in the guide +// "running": false, // the plugin is reading its source right now +// "status": "317 quests ...",// one line for the reader to show +// "commands": ["refresh"] // GuideCommand words this plugin takes ("refresh", "settings") +// } +// +// GetGuideJson payload: the guide (QuestGuideData.cs, QuestGuide.ToJson). +// GuideCommand(line): a word from "commands" (UTF-8, NUL-terminated); 1 = taken +// (queued for the plugin's own tick), 0 = not a command it takes. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Text.Json; + +namespace RynthCore.Plugin.Shared; + +/// Constants of the "RynthServer.QuestGuide" interface. +public static class RynthServerQuestGuide +{ + /// The info JSON's schema. + public const int Schema = 1; + + /// The biggest guide a reader takes (bytes); a bigger one is refused, not cut. + public const int MaxGuideBytes = 16 * 1024 * 1024; + + /// The longest info JSON a reader takes. + public const int MaxInfoBytes = 64 * 1024; + + /// Ask the plugin to read its source again. + public const string CommandRefresh = "refresh"; + + /// Ask the plugin to show its own settings for the guide (a login, a file to import). + public const string CommandSettings = "settings"; +} + +[StructLayout(LayoutKind.Sequential)] +public unsafe struct RynthServerQuestGuideApiV1 +{ + public const string InterfaceName = "RynthServer.QuestGuide"; + public const uint InterfaceVersion = 1; + + public uint Version; // InterfaceVersion of the table the plugin filled; 0 once it has shut down + public uint StructSize; // sizeof(RynthServerQuestGuideApiV1) as the plugin built it + + /// + /// GetGuideInfoJson(buffer, capacity): writes the info JSON (UTF-8, NUL-terminated) into buffer when it + /// fits, and returns its length in bytes without the NUL. A return value of capacity or more means + /// nothing was written: call again with a bigger buffer. 0 = no guide (or shutting down). Any thread. + /// + public delegate* unmanaged[Cdecl] GetGuideInfoJson; + + /// GetGuideJson(buffer, capacity): the guide, with GetGuideInfoJson's buffer rules. 0 = none. Any thread. + public delegate* unmanaged[Cdecl] GetGuideJson; + + /// GuideCommand(line): 1 when the plugin takes the command (it runs it on its own tick), 0 when not. Any thread. + public delegate* unmanaged[Cdecl] GuideCommand; +} + +/// The "RynthServer.QuestGuide" info JSON, read leniently. +internal sealed record ServerQuestGuideInfo(string Tag, string Plugin, long Revision, int Bytes, int Quests, + bool Running, string Status, List Commands) +{ + /// The info, or null for junk or another schema. A guide not ready yet has Bytes 0. + public static ServerQuestGuideInfo? Parse(string? json) + { + if (string.IsNullOrWhiteSpace(json)) return null; + try + { + using JsonDocument doc = JsonDocument.Parse(json); + JsonElement r = doc.RootElement; + if (r.ValueKind != JsonValueKind.Object) return null; + if (!r.TryGetProperty("schema", out JsonElement s) || s.ValueKind != JsonValueKind.Number + || !s.TryGetInt32(out int schema) || schema != RynthServerQuestGuide.Schema) return null; + var commands = new List(); + if (r.TryGetProperty("commands", out JsonElement c) && c.ValueKind == JsonValueKind.Array) + foreach (JsonElement e in c.EnumerateArray()) + if (e.ValueKind == JsonValueKind.String && e.GetString() is { Length: > 0 } word) commands.Add(word.Trim().ToLowerInvariant()); + return new ServerQuestGuideInfo(Str(r, "tag"), Str(r, "plugin"), Long(r, "revision"), (int)Math.Max(0, Long(r, "bytes")), + (int)Math.Max(0, Long(r, "quests")), r.TryGetProperty("running", out JsonElement ru) && ru.ValueKind == JsonValueKind.True, + Str(r, "status"), commands); + } + catch (JsonException) + { + return null; + } + } + + public bool Takes(string command) => Commands.Contains(command.Trim().ToLowerInvariant()); + + private static string Str(JsonElement r, string name) => + r.TryGetProperty(name, out JsonElement e) && e.ValueKind == JsonValueKind.String ? (e.GetString() ?? string.Empty).Trim() : string.Empty; + + private static long Long(JsonElement r, string name) => + r.TryGetProperty(name, out JsonElement e) && e.ValueKind == JsonValueKind.Number && e.TryGetInt64(out long v) ? v : 0; +} diff --git a/Plugins/Shared/ServerQuestGuideClient.cs b/Plugins/Shared/ServerQuestGuideClient.cs new file mode 100644 index 0000000..259bd4f --- /dev/null +++ b/Plugins/Shared/ServerQuestGuideClient.cs @@ -0,0 +1,162 @@ +// ============================================================================ +// RynthSuite - Plugins/Shared/ServerQuestGuideClient.cs +// A quest reader's side of "RynthServer.QuestGuide" (RynthServerQuestGuideApi.cs): +// the active server's own quest guide, from the plugin RynthCore names as its +// owner (GetServerStateJson "activePlugin"). The reader never names a server: +// whatever guide the active server's plugin offers is the server guide, and a +// plugin that offers none means no server guide. +// +// The info JSON is polled (every 2 s, cheap); the guide itself is read only +// when the owner, its table or the info's revision changes. Revision goes up +// whenever the guide or its status line changes (the reader redraws). +// Needs, linked into the reader: RynthServerQuestGuideApi.cs, QuestGuideData.cs. +// Pump thread only. +// ============================================================================ + +using System; +using System.Text; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.Shared; + +internal sealed unsafe class ServerQuestGuideClient +{ + private const long PollMs = 2000; + private const long RequeryMs = 10_000; + + private string _owner = string.Empty; + private RynthServerQuestGuideApiV1* _table; + private long _nextPollAt, _nextQueryAt; + private string _infoJson = string.Empty; + private long _readRevision = long.MinValue; + + /// The server's guide as last read (empty when it offers none). + public QuestGuide Guide { get; private set; } = new(); + + /// The offered info (tag, status, commands); null without a server guide. + public ServerQuestGuideInfo? Info { get; private set; } + + /// Goes up when or changes. + public int Revision { get; private set; } + + /// The active server's plugin offers a guide (it may still be empty while it reads). + public bool Available => Info != null; + + /// What the reader calls the guide: the plugin's tag, else "Server". + public string Tag => Info is { Tag.Length: > 0 } i ? i.Tag : "Server"; + + /// Logout: forget everything; the next poll reads fresh. + public void Clear() + { + _table = null; + _owner = string.Empty; + _nextPollAt = _nextQueryAt = 0; + SetNone(); + } + + /// Polls 's guide when due; polls now. Pump thread. + public void Poll(RynthCoreHost host, string? owner, long now, bool force = false) + { + if (!force && now < _nextPollAt) return; + _nextPollAt = now + PollMs; + owner = (owner ?? string.Empty).Trim(); + if (!owner.Equals(_owner, StringComparison.OrdinalIgnoreCase)) + { + _table = null; + _owner = owner; + _nextQueryAt = 0; + SetNone(); + } + if (owner.Length == 0) return; + if (_table != null && _table->Version == 0) + { + _table = null; // the plugin shut down (a reload): ask the new copy + _nextQueryAt = 0; + } + if (_table == null) + { + if (force) _nextQueryAt = 0; + if (now < _nextQueryAt || !host.HasGetPluginInterface) return; + _nextQueryAt = now + RequeryMs; + var p = (RynthServerQuestGuideApiV1*)host.GetPluginInterface(owner, RynthServerQuestGuideApiV1.InterfaceName, RynthServerQuestGuideApiV1.InterfaceVersion); + if (!Usable(p)) { SetNone(); return; } + _table = p; + } + ReadTable(); + } + + /// Reads a table directly (the tests hand one in; Poll uses it once the host gave one). + internal void Use(RynthServerQuestGuideApiV1* table, string owner) + { + if (!Usable(table)) { _table = null; SetNone(); return; } + _owner = owner; + _table = table; + ReadTable(); + } + + private static bool Usable(RynthServerQuestGuideApiV1* p) => + p != null && p->Version >= 1 && p->StructSize >= (uint)sizeof(RynthServerQuestGuideApiV1) + && p->GetGuideInfoJson != null && p->GetGuideJson != null && p->GuideCommand != null; + + private void ReadTable() + { + string info = Read(_table->GetGuideInfoJson, 1024, RynthServerQuestGuide.MaxInfoBytes); + if (info == _infoJson) return; + _infoJson = info; + ServerQuestGuideInfo? parsed = ServerQuestGuideInfo.Parse(info); + if (parsed == null) { SetNone(); return; } + Info = parsed; + Revision++; + if (parsed.Revision == _readRevision) return; + if (parsed.Bytes <= 0 || parsed.Bytes > RynthServerQuestGuide.MaxGuideBytes) + { + // Not ready yet (or too big to take): no quests, the status line says why. + Guide = new QuestGuide(); + _readRevision = parsed.Revision; + return; + } + string json = Read(_table->GetGuideJson, parsed.Bytes + 1, RynthServerQuestGuide.MaxGuideBytes + 1); + if (json.Length == 0) + { + _infoJson = string.Empty; // try again on the next poll + return; + } + Guide = QuestGuide.Parse(json); + _readRevision = parsed.Revision; + } + + /// Asks the server's plugin to run a guide command ("refresh", "settings"); false when it doesn't take it. + public bool Command(string word) + { + if (_table == null || _table->Version == 0 || Info == null || !Info.Takes(word)) return false; + byte[] bytes = Encoding.UTF8.GetBytes(word.Trim().ToLowerInvariant() + "\0"); + fixed (byte* b = bytes) return _table->GuideCommand(b) != 0; + } + + /// Copies a string out, growing the buffer once when the plugin says it didn't fit ("" = none). + private static string Read(delegate* unmanaged[Cdecl] fn, int first, int max) + { + if (fn == null) return string.Empty; + var buffer = new byte[Math.Max(16, Math.Min(first, max))]; + for (int attempt = 0; attempt < 2; attempt++) + { + int len; + fixed (byte* b = buffer) len = fn(b, buffer.Length); + if (len <= 0) return string.Empty; + if (len < buffer.Length) return Encoding.UTF8.GetString(buffer, 0, len); + if (len + 1 > max) return string.Empty; + buffer = new byte[len + 1]; + } + return string.Empty; + } + + private void SetNone() + { + _infoJson = string.Empty; + _readRevision = long.MinValue; + if (Info == null && Guide.IsEmpty) return; + Info = null; + Guide = new QuestGuide(); + Revision++; + } +} diff --git a/Plugins/Shared/ServerQuestGuideHost.cs b/Plugins/Shared/ServerQuestGuideHost.cs new file mode 100644 index 0000000..376a588 --- /dev/null +++ b/Plugins/Shared/ServerQuestGuideHost.cs @@ -0,0 +1,172 @@ +// ============================================================================ +// RynthSuite - Plugins/Shared/ServerQuestGuideHost.cs +// A server plugin's side of "RynthServer.QuestGuide" (RynthServerQuestGuideApi.cs): +// the plugin builds its guide (QuestGuideData.cs) however its server's wiki needs +// and hands it here with Publish; readers (RynthOracle) take it through the table. +// +// How a server plugin uses it: +// - its RynthPluginQueryInterface answers RynthServerQuestGuideApiV1.InterfaceName +// with ServerQuestGuideHost.Query(version); +// - Publish(...) whenever its guide or status changes (pump thread); +// - in its tick, TryTakeCommand drains what readers asked for ("refresh", "settings"); +// - Release() at shutdown. +// The table is allocated once per loaded copy and never freed; after Release it +// reports Version 0 and its functions answer 0. Everything handed out is a snapshot +// swapped in whole, so any thread may read while the pump publishes. +// ============================================================================ + +using System; +using System.Collections.Concurrent; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; + +namespace RynthCore.Plugin.Shared; + +internal static unsafe class ServerQuestGuideHost +{ + private sealed record Snapshot(string Info, string Guide, string[] Commands); + + private static RynthServerQuestGuideApiV1* _table; + private static volatile bool _released; + private static Snapshot? _snap; + private static long _revision; + private static readonly ConcurrentQueue _commands = new(); + private const int MaxQueued = 16; + + /// The revision of what was published last (goes up with every Publish). + public static long Revision => Interlocked.Read(ref _revision); + + /// + /// Publishes the guide and its status. null (or empty) is "no guide yet": readers + /// see the status and no quests. : the GuideCommand words this plugin takes. + /// + public static void Publish(string tag, string plugin, QuestGuide? guide, string status, bool running, params string[] commands) + { + string json = guide == null || guide.IsEmpty ? string.Empty : guide.ToJson(); + long rev = Interlocked.Increment(ref _revision); + string[] words = Array.ConvertAll(commands ?? Array.Empty(), c => (c ?? string.Empty).Trim().ToLowerInvariant()); + Volatile.Write(ref _snap, new Snapshot(InfoJson(tag, plugin, rev, json, guide?.Quests.Count ?? 0, running, status, words), json, words)); + } + + /// Takes nothing more: readers see no guide (a server whose wiki was turned off). + public static void Withdraw() + { + Interlocked.Increment(ref _revision); + Volatile.Write(ref _snap, null); + } + + /// The table for a reader asking for , or 0 (released, or a version this doesn't have). + public static IntPtr Query(uint version) + { + if (version < 1 || version > RynthServerQuestGuideApiV1.InterfaceVersion || _released) return IntPtr.Zero; + if (_table == null) + { + var t = (RynthServerQuestGuideApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthServerQuestGuideApiV1)); + t->StructSize = (uint)sizeof(RynthServerQuestGuideApiV1); + t->GetGuideInfoJson = &GetGuideInfoJson; + t->GetGuideJson = &GetGuideJson; + t->GuideCommand = &GuideCommand; + t->Version = RynthServerQuestGuideApiV1.InterfaceVersion; + _table = t; + } + return (IntPtr)_table; + } + + /// A command a reader sent (oldest first); the plugin runs it on its own tick. + public static bool TryTakeCommand(out string word) => _commands.TryDequeue(out word!); + + /// Plugin shutdown: readers see Version 0 and re-query; the functions answer 0. + public static void Release() + { + _released = true; + if (_table != null) _table->Version = 0; + while (_commands.TryDequeue(out _)) { } + } + + /// The tests: a fresh start (a new "copy" of the plugin). + internal static void ResetForTests() + { + _released = false; + Volatile.Write(ref _snap, null); + while (_commands.TryDequeue(out _)) { } + if (_table != null) _table->Version = RynthServerQuestGuideApiV1.InterfaceVersion; + } + + internal static string InfoJson(string tag, string plugin, long revision, string guideJson, int quests, bool running, string status, string[] commands) + { + var sb = new StringBuilder(256); + sb.Append("{\"schema\":").Append(RynthServerQuestGuide.Schema); + Field(sb, "tag", tag); + Field(sb, "plugin", plugin); + sb.Append(",\"revision\":").Append(revision); + sb.Append(",\"bytes\":").Append(Encoding.UTF8.GetByteCount(guideJson)); + sb.Append(",\"quests\":").Append(quests); + sb.Append(",\"running\":").Append(running ? "true" : "false"); + Field(sb, "status", status); + sb.Append(",\"commands\":["); + for (int i = 0; i < commands.Length; i++) + { + if (i > 0) sb.Append(','); + sb.Append('"').Append(Ascii(commands[i])).Append('"'); + } + sb.Append("]}"); + return sb.ToString(); + } + + private static void Field(StringBuilder sb, string name, string? value) => + sb.Append(",\"").Append(name).Append("\":\"").Append(Ascii(value)).Append('"'); + + /// JSON string content in plain ASCII (the info JSON's rule). + private static string Ascii(string? value) + { + var sb = new StringBuilder((value ?? string.Empty).Length); + foreach (char c in value ?? string.Empty) + { + if (c == '"') sb.Append("\\\""); + else if (c == '\\') sb.Append("\\\\"); + else if (c < 0x20 || c > 0x7e) sb.Append("\\u").Append(((int)c).ToString("x4")); + else sb.Append(c); + } + return sb.ToString(); + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetGuideInfoJson(byte* buffer, int capacity) + { + try { return _released || Volatile.Read(ref _snap) is not Snapshot s ? 0 : Write(s.Info, buffer, capacity); } + catch { return 0; } + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetGuideJson(byte* buffer, int capacity) + { + try { return _released || Volatile.Read(ref _snap) is not Snapshot s || s.Guide.Length == 0 ? 0 : Write(s.Guide, buffer, capacity); } + catch { return 0; } + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GuideCommand(byte* line) + { + try + { + if (_released || line == null || Volatile.Read(ref _snap) is not Snapshot s) return 0; + string word = (Marshal.PtrToStringUTF8((IntPtr)line) ?? string.Empty).Trim().ToLowerInvariant(); + if (word.Length == 0 || Array.IndexOf(s.Commands, word) < 0 || _commands.Count >= MaxQueued) return 0; + _commands.Enqueue(word); + return 1; + } + catch { return 0; } + } + + /// NUL-terminated UTF-8 into the caller's buffer when it fits; the byte length either way. + private static int Write(string text, byte* buffer, int capacity) + { + int length = Encoding.UTF8.GetByteCount(text); + if (buffer == null || capacity <= length) return length; + fixed (char* src = text) Encoding.UTF8.GetBytes(src, text.Length, buffer, capacity); + buffer[length] = 0; + return length; + } +} diff --git a/Shared/RynthCore.LootSdk/Editing/LootEditSession.cs b/Shared/RynthCore.LootSdk/Editing/LootEditSession.cs index 48e4763..8664a17 100644 --- a/Shared/RynthCore.LootSdk/Editing/LootEditSession.cs +++ b/Shared/RynthCore.LootSdk/Editing/LootEditSession.cs @@ -105,7 +105,9 @@ public sealed class LootEditSession _bom = bom; _crlf = text.Contains("\r\n", StringComparison.Ordinal); _finalNewline = finalNewline; - return Ok(reason.Length == 0 ? $"Opened {FileName(path)} ({RuleCount} rules)." : $"Opened {FileName(path)} ({RuleCount} rules), read-only."); + string opened = reason.Length == 0 ? $"Opened {FileName(path)} ({RuleCount} rules)." : $"Opened {FileName(path)} ({RuleCount} rules), read-only."; + foreach (string hint in LootRuleText.ProfileHints(profile.Rules)) opened += " " + hint; + return Ok(opened); } catch (Exception ex) { @@ -286,7 +288,9 @@ public sealed class LootEditSession if (cmd.Rule == null) { Fail("No rule in the update."); return Outcome.Refused; } string? error = ApplyRule(rule, cmd.Rule); if (error != null) { Fail(error); return Outcome.Refused; } - return Changed($"Updated \"{rule.Name}\" (not saved yet).", cmd.Index); + string updated = $"Updated \"{rule.Name}\" (not saved yet)."; + foreach (string hint in LootRuleText.Hints(rule)) updated += " " + hint; + return Changed(updated, cmd.Index); } } Fail($"Unknown loot edit command '{cmd.Op}'."); diff --git a/Shared/RynthCore.LootSdk/Editing/LootItemAttributes.cs b/Shared/RynthCore.LootSdk/Editing/LootItemAttributes.cs index 35188a2..40a83b0 100644 --- a/Shared/RynthCore.LootSdk/Editing/LootItemAttributes.cs +++ b/Shared/RynthCore.LootSdk/Editing/LootItemAttributes.cs @@ -66,7 +66,7 @@ public sealed class LootItemAttribute public static class LootItemAttributes { - public const string GroupItem = "Item", GroupGear = "Weapon / Armor", GroupRatings = "Ratings", GroupSpells = "Spells", + public const string GroupItem = "Item", GroupGear = "Weapon / Armor", GroupSpecials = "Weapon specials", GroupRatings = "Ratings", GroupSpells = "Spells", GroupPet = "Pet essence", GroupT11 = "T11", GroupRequirements = "Requirements"; /// Cantrip tiers, lowest first: "Major Strength" is tier 2. @@ -96,10 +96,17 @@ public static class LootItemAttributes new(GroupItem, 92, false, "Uses left", Cmp.Min), new(GroupItem, 91, false, "Max uses", Cmp.Min), new(GroupItem, 265, false, "Armor set", Cmp.Named, "The set id (the same set's pieces share it)."), - new(GroupItem, 353, false, "Imbue", Cmp.Named), + new(GroupItem, 179, false, "Imbue", Cmp.Named, "The item's imbues (ImbuedEffect, with ImbuedEffect2-5 folded in)."), new(GroupItem, 166, false, "Slayer", Cmp.Named), new(GroupItem, 45, false, "Damage type", Cmp.Named), + // ACE appraisal properties (2026-11-27; spotted by SilentKelpie, Forgejo rynth PR #12). + new(GroupItem, 171, false, "Times tinkered", Cmp.Max, "How many tinks it has had (fewer leaves more room)."), + new(GroupItem, 17, false, "Rare", Cmp.Min, "A rare's id; any rare: at least 1."), + new(GroupItem, 114, false, "Attuned", Cmp.Min, "1 when attuned (it can't be traded)."), + new(GroupItem, 33, false, "Bonded", Cmp.Min, "1 when bonded (it stays on death)."), + new(GroupItem, 319, false, "Max item level", Cmp.Min, "Items that level up (Aetheria, some keys and weapons)."), + new(GroupGear, 353, false, "Weapon type", Cmp.Named, "The weapon's mastery: sword, axe, bow, crossbow..."), new(GroupGear, LootItemRules.KeyWieldSkill, false, "Wield skill", Cmp.Named), new(GroupGear, LootItemRules.KeyWeaponSkill, false, "Weapon skill", Cmp.Named), new(GroupGear, LootItemRules.KeyDamage, false, "Max damage", Cmp.Min), @@ -111,9 +118,18 @@ public static class LootItemAttributes new(GroupGear, 150, true, "Magic defense modifier", Cmp.Min), new(GroupGear, 144, true, "Mana conversion modifier", Cmp.Min), new(GroupGear, LootItemRules.KeyElementalDamageMod, true, "Elemental damage vs monsters", Cmp.Min), + new(GroupGear, 204, false, "Elemental damage bonus", Cmp.Min, "A caster's or launcher's flat elemental damage bonus."), + new(GroupGear, 159, true, "Absorb magic damage", Cmp.Min, "The share of magic damage absorbed (0.25 = 25%)."), new(GroupGear, LootItemRules.KeyEquipSlots, false, "Equip slots", Cmp.Named, "Where it is worn or wielded."), new(GroupGear, LootItemRules.KeyArmorLevel, false, "Armor level", Cmp.Min), + // A weapon's special properties, as the appraisal names them (2026-11-27). + new(GroupSpecials, 147, true, "Biting Strike", Cmp.Min, "Its critical chance (0.4 = 40%)."), + new(GroupSpecials, 136, true, "Crushing Blow", Cmp.Min, "Its critical damage multiplier."), + new(GroupSpecials, 155, true, "Armor Cleaving", Cmp.Min, "The share of armor it ignores (any: at least 0.01)."), + new(GroupSpecials, 157, true, "Resistance Cleaving", Cmp.Min, "The resistance it takes off its element."), + new(GroupSpecials, 292, false, "Cleaving", Cmp.Min, "How many targets a swing hits."), + // The rating total comes first in this group (built separately); then each rating. new(GroupRatings, 370, false, "Damage rating", Cmp.Min), new(GroupRatings, 371, false, "Damage resist rating", Cmp.Min), @@ -124,6 +140,9 @@ public static class LootItemAttributes new(GroupRatings, 376, false, "Heal boost rating", Cmp.Min), new(GroupRatings, 377, false, "Nether resist rating", Cmp.Min), new(GroupRatings, 379, false, "Vitality rating", Cmp.Min), + new(GroupRatings, 378, false, "Life resist rating", Cmp.Min), + new(GroupRatings, 388, false, "Overpower rating", Cmp.Min), + new(GroupRatings, 389, false, "Overpower resist rating", Cmp.Min), new(GroupPet, KeyBond, false, "Bond level", Cmp.Min), new(GroupPet, KeyUseRequiresLevel, false, "Level", Cmp.Min), diff --git a/Shared/RynthCore.LootSdk/Editing/LootItemRules.cs b/Shared/RynthCore.LootSdk/Editing/LootItemRules.cs index 60b58c0..de263c0 100644 --- a/Shared/RynthCore.LootSdk/Editing/LootItemRules.cs +++ b/Shared/RynthCore.LootSdk/Editing/LootItemRules.cs @@ -35,10 +35,22 @@ public sealed class LootItemFacts /// The plugin knows it for a summoning essence (by WCID, icon, use requirement; added 2026-10-18). public bool IsPetEssence { get; set; } + /// + /// The item's description and use text (LongDesc, Use), for values only the text carries; empty when + /// unknown (added 2026-11-27: the slayer bonus, ). + /// + public string ItemText { get; set; } = string.Empty; + public bool Stackable => MaxStackSize > 1 || StackSize > 1; public int Int(int key) => Ints.TryGetValue(key, out int v) ? v : 0; - public double Double(int key) => Doubles.TryGetValue(key, out double v) ? v : 0; + + /// A float property; the slayer bonus (138) falls back to the item text when none was sent. + public double Double(int key) + { + double v = Doubles.TryGetValue(key, out double d) ? d : 0; + return SlayerText.Resolve(key, v, () => new string?[] { ItemText }); + } } /// How the rule recognises the item. diff --git a/Shared/RynthCore.LootSdk/Editing/LootRuleText.cs b/Shared/RynthCore.LootSdk/Editing/LootRuleText.cs index b55ee99..3c540c3 100644 --- a/Shared/RynthCore.LootSdk/Editing/LootRuleText.cs +++ b/Shared/RynthCore.LootSdk/Editing/LootRuleText.cs @@ -64,10 +64,14 @@ public static class LootRuleText (314, "Pet CritDamageRating"), (315, "Pet CritResistRating"), (316, "Pet CritDamageResistRating"), (362, "SummoningMastery"), (364, "UseLevelRequirement"), (366, "UseRequiresSkill"), (368, "UseRequiresSkillSpec"), (369, "UseRequiresLevel"), - (179, "Imbued (Decal)"), (265, "EquipmentSetId (armor set)"), - (218, "EquippedSlots"), (353, "ImbuedEffect"), (370, "DamageRating"), (371, "DamageResistRating"), + (179, "ImbuedEffect"), (265, "EquipmentSetId (armor set)"), + (218, "EquippedSlots"), (353, "WeaponType"), (370, "DamageRating"), (371, "DamageResistRating"), (372, "CritRating"), (373, "CritResistRating"), (374, "CritDamageRating"), (375, "CritDamageResistRating"), (376, "HealBoostRating"), (377, "NetherResistRating"), (379, "VitalityRating"), + // The checklist's newer rows (2026-11-27). + (17, "RareId"), (33, "Bonded"), (114, "Attuned"), (171, "NumTimesTinkered"), (204, "ElementalDamageBonus"), + (292, "Cleaving (targets)"), (319, "ItemMaxLevel"), (378, "LifeResistRating"), (388, "OverpowerRating"), + (389, "OverpowerResistRating"), (0x0D000000, "Type (WCID)"), // Decal's synthetic key: the weenie class id // Decal's other synthetic keys (Decal.Adapter LongValueKey), as VTank's editor names them; // RynthAi reads each as the game property it is (WorldObjectCache.GetDecalLongKey). @@ -97,9 +101,11 @@ public static class LootRuleText public static readonly (int Id, string Name)[] DoubleKeys = { (5, "ManaRate"), (22, "DamageVariance"), (29, "WeaponDefense"), (62, "WeaponOffense"), - (63, "DamageMod"), (138, "Slayer Damage Bonus"), // often unset on ACE appraisal; prefer LongDesc / int 166 + (63, "DamageMod"), (138, "Slayer Damage Bonus"), // never sent by ACE; read from the item text where a server writes it (SlayerText) (144, "ManaConversionMod"), (149, "WeaponMissileDefense"), (150, "WeaponMagicDefense"), (152, "ElementalDamageVsMonsters"), (167, "CooldownDuration"), + (136, "CriticalMultiplier (Crushing Blow)"), (147, "CriticalFrequency (Biting Strike)"), + (155, "IgnoreArmor (Armor Cleaving)"), (157, "ResistanceModifier (Resistance Cleaving)"), (159, "AbsorbMagicDamage"), (0x0A000009, "SalvageWorkmanship"), (0x0A00000B, "Variance"), (0x0A00000C, "AttackBonus"), (0x0A00000E, "DamageBonus"), }; @@ -216,8 +222,8 @@ public static class LootRuleText /// number. Unknown values are still valid: show them as "value N". /// /// - /// ImbuedEffect (353): ACE's ImbuedEffectType flags. A combination (two imbues) shows as - /// "value N". + /// ImbuedEffect (179): ACE's ImbuedEffectType flags. A combination (two imbues) shows as + /// "value N". These names sat on 353 until 2026-11-27; 353 is the weapon type. /// public static readonly (int Id, string Name)[] ImbuedEffects = { @@ -227,6 +233,13 @@ public static class LootRuleText (4096, "Magic Defense"), (8192, "Spellbook"), (16384, "Nether Rending"), }; + /// WeaponType (353): the weapon's mastery (ACE WeaponType). A crossbow is "353 = 9". + public static readonly (int Id, string Name)[] WeaponTypes = + { + (1, "Unarmed"), (2, "Sword"), (3, "Axe"), (4, "Mace"), (5, "Spear"), (6, "Dagger"), (7, "Staff"), + (8, "Bow"), (9, "Crossbow"), (10, "Thrown"), (11, "Two Handed"), (12, "Magic"), + }; + /// SummoningMastery (362): the pet school an essence needs (ACE SummoningMastery). public static readonly (int Id, string Name)[] SummoningMasteries = { @@ -241,7 +254,8 @@ public static class LootRuleText 158 => WieldRequirements, 159 or 366 or 368 => Skills, 166 => CreatureTypes, - 353 => ImbuedEffects, + 179 => ImbuedEffects, + 353 => WeaponTypes, 362 => SummoningMasteries, T11.T11Keys.WeaponGrade => T11.T11Catalog.Grades, T11.T11Keys.GearGrade => T11.T11Catalog.Grades, @@ -249,11 +263,11 @@ public static class LootRuleText }; /// True when the long key's value is a set of flags (a named value is one flag or a common pair). - public static bool ValueTableIsFlags(int longKey) => longKey is 45 or 0x0D000021 or 9054 or 353; + public static bool ValueTableIsFlags(int longKey) => longKey is 45 or 0x0D000021 or 9054 or 179; /// The long keys that have a value table, for the vocabulary. public static readonly int[] KeysWithValueTables = - { 45, 48, 131, 158, 159, 166, 353, 362, 366, 368, 9054, 0x0D000020, 0x0D000021, T11.T11Keys.WeaponGrade, T11.T11Keys.GearGrade }; + { 45, 48, 131, 158, 159, 166, 179, 353, 362, 366, 368, 9054, 0x0D000020, 0x0D000021, T11.T11Keys.WeaponGrade, T11.T11Keys.GearGrade }; /// /// True for the conditions whose value is picked by name when the key has a @@ -425,6 +439,34 @@ public static class LootRuleText return sb.Length > maxLength ? sb.ToString(0, maxLength - 3) + "..." : sb.ToString(); } + /// + /// What the author of should know about its conditions (2026-11-27): a test of the + /// slayer bonus (float 138) works only where the server writes the bonus in the item text. + /// + public static List Hints(VTankLootRule rule) + { + var hints = new List(); + foreach (VTankLootCondition c in rule.Conditions) + if (c.NodeType is VTankNodeTypes.DoubleValKeyGE or VTankNodeTypes.DoubleValKeyLE or VTankNodeTypes.BuffedDoubleValKeyGE + && c.DataLines.Count > 1 && TryParseValue(c.DataLines[1], out int key) && key == SlayerText.SlayerDamageBonusKey) + { + hints.Add(SlayerText.Hint); + break; + } + return hints; + } + + /// The rules of a profile whose aren't empty, as "N rule(s) ...: hint" lines. + public static List ProfileHints(IEnumerable rules) + { + var names = new List(); + foreach (VTankLootRule r in rules) + if (Hints(r).Count > 0) names.Add(r.Name ?? string.Empty); + if (names.Count == 0) return new List(); + string list = string.Join(", ", names.GetRange(0, Math.Min(3, names.Count))) + (names.Count > 3 ? ", ..." : ""); + return new List { $"{names.Count} rule(s) test Slayer damage bonus ({list}). {SlayerText.Hint}" }; + } + /// One condition in words. public static string Condition(VTankLootCondition c) { diff --git a/Shared/RynthCore.LootSdk/SlayerText.cs b/Shared/RynthCore.LootSdk/SlayerText.cs new file mode 100644 index 0000000..85fc36e --- /dev/null +++ b/Shared/RynthCore.LootSdk/SlayerText.cs @@ -0,0 +1,60 @@ +using System; +using System.Globalization; +using System.Text.RegularExpressions; + +namespace RynthCore.Loot; + +/// +/// A slayer weapon's damage bonus as its appraisal text gives it (2026-11-27). +/// +/// ACE never sends SlayerDamageBonus (float 138) in an appraisal: the property isn't an assessment +/// property, so a loot rule's "Slayer damage bonus at least 1.01" read 0 on every weapon and never +/// matched. Servers built on ACECustom write the bonus into the weapon's text instead +/// ("- Shadow Slayer: 1.5x Damage"). The loot readers (RynthAi's WorldObject and LootItemFacts) fall +/// back to that text for key 138 when no value was sent; a value the server does send still wins. +/// Where no server writes the line the bonus stays unreadable: the slayer type (int 166) is the test +/// that works everywhere (). +/// +/// Spotted by SilentKelpie (Forgejo rynth PR #12); re-implemented here. +/// +public static class SlayerText +{ + /// SlayerDamageBonus (STypeFloat 138). + public const int SlayerDamageBonusKey = 138; + + /// SlayerCreatureType (STypeInt 166), the test every ACE server answers. + public const int SlayerTypeKey = 166; + + /// What the Loot Editor says about a rule that tests the bonus. + public const string Hint = + "Slayer damage bonus can only be read on servers that write it in the item text (\"Shadow Slayer: 1.5x Damage\"); elsewhere use Slayer type."; + + // "- Shadow Slayer: 1.5x Damage", "Olthoi Slayer: 2x". One line each; the dash is optional. + private static readonly Regex Line = new(@"^[ \t]*-?[ \t]*(?[^\r\n:]+?)[ \t]+Slayer:[ \t]*(?\d+(?:\.\d+)?)[ \t]*x", + RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled); + + /// The best "<creature> Slayer: N.Nx" multiplier in the texts (1.5 for "1.5x"), or 0 when none says one. + public static double BonusOf(params string?[] texts) + { + double best = 0; + foreach (string? t in texts) + { + if (string.IsNullOrEmpty(t) || t.IndexOf("Slayer", StringComparison.OrdinalIgnoreCase) < 0) continue; + foreach (Match m in Line.Matches(t)) + if (double.TryParse(m.Groups["x"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out double x) && x > best) + best = x; + } + return best; + } + + /// + /// Key 138's value for a loot rule: the sent value when there is one (above 0), else the text's. + /// Any other key: unchanged. + /// + public static double Resolve(int key, double sent, Func texts) + { + if (key != SlayerDamageBonusKey || sent > 0) return sent; + double x = BonusOf(texts()); + return x > 0 ? x : sent; + } +} diff --git a/Tools/RynthCore.LootSdkTests/LootAddAttributeTests.cs b/Tools/RynthCore.LootSdkTests/LootAddAttributeTests.cs index d36b6ce..55c87d5 100644 --- a/Tools/RynthCore.LootSdkTests/LootAddAttributeTests.cs +++ b/Tools/RynthCore.LootSdkTests/LootAddAttributeTests.cs @@ -24,6 +24,42 @@ internal static partial class Program TestAttrPetEssence(); TestAttrNativeAndWire(); TestAttrVocab(); + TestAttrWeaponSpecials(); + } + + // 2026-11-27 (spotted by SilentKelpie, Forgejo rynth PR #12): ACE's tinks, rare, attuned, bonded and max + // level; elemental damage bonus and absorb magic; the weapon specials; life resist and overpower ratings. + private static void TestAttrWeaponSpecials() + { + LootItemFacts f = Sword(); + f.Ints[171] = 3; f.Ints[17] = 30012; f.Ints[114] = 1; f.Ints[33] = 1; f.Ints[319] = 5; f.Ints[204] = 12; + f.Ints[292] = 2; f.Ints[378] = 1; f.Ints[388] = 2; f.Ints[389] = 3; + f.Doubles[147] = 0.4; f.Doubles[136] = 3; f.Doubles[155] = 0.1; f.Doubles[157] = 0.5; f.Doubles[159] = 0.25; + LootItemRuleDraft d = BuildOk(f); + List rows = d.Attributes; + Eq(string.Join(",", rows.Select(r => r.Group).Distinct()), "Item,Weapon / Armor,Weapon specials,Ratings,Spells,Requirements", + "specials: their group sits after Weapon / Armor"); + Eq(string.Join(",", rows.Where(r => r.Group == LootItemAttributes.GroupSpecials).Select(r => r.Label)), + "Biting Strike,Crushing Blow,Armor Cleaving,Resistance Cleaving,Cleaving", "specials: the rows, in order"); + foreach (string id in new[] { "L:171", "L:17", "L:114", "L:33", "L:319", "L:204", "D:159", "L:378", "L:388", "L:389" }) + Check(rows.Any(r => r.Id == id), "specials: row " + id); + Eq(rows.Single(r => r.Id == "L:171").Ops[0], LootItemAttributeOp.AtMost, "specials: times tinkered defaults to at most"); + Check(!rows.Any(r => r.On), "specials: none ticked by default"); + + LootItemRuleDraft like = BuildOk(f, new() { Match = LootItemMatch.Like }); + Check(!like.Attributes.Any(r => r.On && (r.Group == LootItemAttributes.GroupSpecials || r.Id is "L:171" or "L:17" or "L:378")), + "specials: 'items like this' still ticks only what it always did"); + + var c = Pick(("D:147", true, LootItemAttributeOp.AtLeast, "0.3"), ("L:17", true, LootItemAttributeOp.AtLeast, "1"), + ("L:171", true, LootItemAttributeOp.AtMost, "")); + LootItemRuleDraft picked = BuildOk(f, new() { Choices = c }); + string conds = string.Join(" ; ", picked.Rule.Conditions.Skip(2).Select(Lines)); + Eq(conds, "2:3|171 ; 3:1|17 ; 5:0.3|147", "specials: tinks at most 3, any rare, Biting Strike at least 0.3 (row order)"); + Check(LootRuleText.Summary(picked.Rule).Contains("CriticalFrequency (Biting Strike) >= 0.3"), "specials: the summary names the key: " + LootRuleText.Summary(picked.Rule)); + Check(LootItemRules.IntKeys.Contains(292) && LootItemRules.DoubleKeys.Contains(147), "specials: RynthAi reads the new keys into the facts"); + + // An item without them: no such rows. + Check(!BuildOk(Sword()).Attributes.Any(r => r.Group == LootItemAttributes.GroupSpecials), "specials: none on an ordinary sword"); } private static LootItemFacts Sword() => new() @@ -181,7 +217,17 @@ internal static partial class Program private static void TestAttrVocab() { - Eq(LootRuleText.ValueName(353, "4"), "Armor Rending", "vocab: imbue names"); + Eq(LootRuleText.ValueName(179, "4"), "Armor Rending", "vocab: imbue names (ImbuedEffect is 179)"); + Eq(LootRuleText.ValueName(353, "9"), "Crossbow", "vocab: 353 is the weapon type"); + Eq(LootRuleText.ValueName(353, "4"), "Mace", "vocab: 353 = 4 is a mace, not Armor Rending"); + Check(LootRuleText.ValueTableIsFlags(179) && !LootRuleText.ValueTableIsFlags(353), "vocab: imbues are flags, weapon type isn't"); + // The checklist: Imbue reads 179, Weapon type 353 (an Armor Rending sword was "Imbue: value 2" before). + var imbued = Sword(); + imbued.Ints[179] = 4; + imbued.Ints[353] = 2; + List rows = BuildOk(imbued).Attributes; + Check(rows.Any(r => r.Id == "L:179" && r.Label == "Imbue" && r.ItemText == "Armor Rending"), "attr: the Imbue row is 179, by name"); + Check(rows.Any(r => r.Id == "L:353" && r.Label == "Weapon type" && r.ItemText == "Sword"), "attr: 353 is the weapon type row"); Eq(LootRuleText.ValueName(362, "3"), "Naturalist", "vocab: summoning mastery"); Check(LootRuleText.LongKeys.Any(k => k.Id == 9053) && LootRuleText.LongKeys.Any(k => k.Id == 9075), "vocab: pet keys named"); Check(LootRuleText.LongKeys.Any(k => k.Id == 92 && k.Name.StartsWith("UsesRemaining")), "vocab: 92 is uses remaining"); diff --git a/Tools/RynthCore.LootSdkTests/LootSlayerTextTests.cs b/Tools/RynthCore.LootSdkTests/LootSlayerTextTests.cs new file mode 100644 index 0000000..66e8861 --- /dev/null +++ b/Tools/RynthCore.LootSdkTests/LootSlayerTextTests.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections.Generic; +using System.Text; +using RynthCore.Loot; +using RynthCore.Loot.Editing; +using RynthCore.Loot.VTank; + +namespace RynthCore.LootSdkTests; + +// The slayer bonus from the item text (2026-11-27; spotted by SilentKelpie, Forgejo rynth PR #12): ACE never +// sends float 138, servers built on ACECustom write "- Shadow Slayer: 1.5x Damage". The loot readers fall back +// to the text when no value was sent; a sent value wins; the Loot Editor says where the test can't work. +internal static partial class Program +{ + private static void RunSlayerTextTests() + { + Console.WriteLine("\n-- Slayer damage bonus from the item text --"); + + Eq(SlayerText.BonusOf("Property Details:\n- Shadow Slayer: 1.5x Damage\n- Biting Strike"), 1.5, "slayer: the line's multiplier"); + Eq(SlayerText.BonusOf("Olthoi Slayer: 2x"), 2.0, "slayer: no dash, a whole multiplier"); + Eq(SlayerText.BonusOf("- Drudge Slayer: 1.25x Damage", "- All Creatures Slayer: 2.1x Damage"), 2.1, "slayer: the best of several texts"); + Eq(SlayerText.BonusOf("A fine blade.", null, ""), 0.0, "slayer: no line, 0"); + Eq(SlayerText.BonusOf("Slayer of drudges, 2x the fun"), 0.0, "slayer: prose mentioning a slayer is not a bonus line"); + + var f = new LootItemFacts { Name = "Shadow Slayer Sword", ObjectClass = (int)AcObjectClass.MeleeWeapon, ItemText = "- Shadow Slayer: 1.5x Damage" }; + Eq(f.Double(SlayerText.SlayerDamageBonusKey), 1.5, "slayer facts: nothing sent, the text's bonus"); + f.Doubles[SlayerText.SlayerDamageBonusKey] = 3.0; + Eq(f.Double(SlayerText.SlayerDamageBonusKey), 3.0, "slayer facts: a sent value wins"); + f.Doubles.Remove(SlayerText.SlayerDamageBonusKey); + f.Doubles[62] = 1.2; + Eq(f.Double(62), 1.2, "slayer facts: other keys unchanged"); + Eq(f.Double(63), 0.0, "slayer facts: an unsent other key is still 0, whatever the text"); + Eq(new LootItemFacts().Double(SlayerText.SlayerDamageBonusKey), 0.0, "slayer facts: no text, no bonus"); + + // The Loot Editor's hint. + var slayerRule = new VTankLootRule { Name = "Any slayer bonus", Action = VTankLootAction.Keep, CustomExpression = string.Empty }; + slayerRule.Conditions.Add(new VTankLootCondition(VTankNodeTypes.ObjectClass, "0", new[] { "1" })); + slayerRule.Conditions.Add(new VTankLootCondition(VTankNodeTypes.DoubleValKeyGE, "0", new[] { "1.01", "138" })); + var plain = new VTankLootRule { Name = "Any slayer type", Action = VTankLootAction.Keep, CustomExpression = string.Empty }; + plain.Conditions.Add(new VTankLootCondition(VTankNodeTypes.LongValKeyGE, "0", new[] { "1", "166" })); + Check(LootRuleText.Hints(slayerRule).Count == 1 && LootRuleText.Hints(slayerRule)[0].Contains("use Slayer type"), "slayer hint: a rule testing the bonus gets it"); + Check(LootRuleText.Hints(plain).Count == 0, "slayer hint: a Slayer type rule doesn't"); + List ph = LootRuleText.ProfileHints(new[] { plain, slayerRule }); + Check(ph.Count == 1 && ph[0].StartsWith("1 rule(s) test Slayer damage bonus (Any slayer bonus)"), "slayer hint: the profile line names the rule: " + string.Join("|", ph)); + + var profile = new VTankLootProfile { FileVersion = 1, Rules = { plain, slayerRule } }; + string dir = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "RynthLootSlayerTests_" + Guid.NewGuid().ToString("N")); + System.IO.Directory.CreateDirectory(dir); + try + { + string path = System.IO.Path.Combine(dir, "slayer-hint.utl"); + System.IO.File.WriteAllText(path, VTankLootWriter.Serialize(profile)); + var s = new LootEditSession(); + Check(s.Open(path), "slayer hint: the profile opens: " + s.Message); + Check(s.Message.Contains("Slayer damage bonus can only be read on servers that write it in the item text"), "slayer hint: opening it says so: " + s.Message); + var p2 = new VTankLootProfile { FileVersion = 1, Rules = { plain } }; + string path2 = System.IO.Path.Combine(dir, "slayer-none.utl"); + System.IO.File.WriteAllText(path2, VTankLootWriter.Serialize(p2)); + Check(s.Open(path2) && !s.Message.Contains("Slayer damage bonus"), "slayer hint: not for a profile without the test: " + s.Message); + } + finally { try { System.IO.Directory.Delete(dir, recursive: true); } catch { } } + } +} diff --git a/Tools/RynthCore.LootSdkTests/Program.cs b/Tools/RynthCore.LootSdkTests/Program.cs index 686e9a3..ac60fee 100644 --- a/Tools/RynthCore.LootSdkTests/Program.cs +++ b/Tools/RynthCore.LootSdkTests/Program.cs @@ -49,6 +49,7 @@ internal static partial class Program RunLootAddAttributeTests(); RunUnknownNodeTests(); RunPerDayTests(); + RunSlayerTextTests(); Console.WriteLine($"\nGolden tests: {_asserts} assertions, {_fails} failed."); diff --git a/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs b/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs index d5e195f..ff02c00 100644 --- a/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs +++ b/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs @@ -105,6 +105,8 @@ internal static unsafe class FakeHost /// Every SetAutoRun call, in order; AutoRun is the last value sent. public static readonly List AutoRunCalls = new(); public static bool AutoRun; + /// An engine without SetAutoRun and TurnToHeading (the back-away's jump fallback). + public static bool NoTurnOrAutoRun; public static int Jumps; /// Runs inside CastSpell, after the cast is recorded (a UseDone that lands during the send). public static Action? AfterCastSpell; @@ -326,7 +328,7 @@ internal static unsafe class FakeHost Vitals = default; BaseVitals = default; WorldName = ""; AccountName = ""; HeadingDeg = 0; Wcids.Clear(); Spellbook.Clear(); PlayerIdValue = 0; Logs.Clear(); Chat.Clear(); ChatTypes.Clear(); ChatCommands.Clear(); AfterCastSpell = null; - AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; TapJumpCalls = false; TapJumps = 0; TapJumpRefuse = false; Order.Clear(); Turns = 0; Casts.Clear(); CastRefused = false; CastsRefused = 0; StopCalls = false; Stops = 0; SetMotionCalls = false; MotionCalls.Clear(); AttackSendCalls = false; AttackCalls.Clear(); NativeAttackCalls = false; CancelAttackCalls = false; CancelAttacks = 0; Sent.Clear(); GiveCalls = false; Gives.Clear(); GiveLands = true; GiveHandler = null; + AutoRunCalls.Clear(); AutoRun = false; NoTurnOrAutoRun = false; Jumps = 0; TapJumpCalls = false; TapJumps = 0; TapJumpRefuse = false; Order.Clear(); Turns = 0; Casts.Clear(); CastRefused = false; CastsRefused = 0; StopCalls = false; Stops = 0; SetMotionCalls = false; MotionCalls.Clear(); AttackSendCalls = false; AttackCalls.Clear(); NativeAttackCalls = false; CancelAttackCalls = false; CancelAttacks = 0; Sent.Clear(); GiveCalls = false; Gives.Clear(); GiveLands = true; GiveHandler = null; Uses.Clear(); IdRequests.Clear(); TargetCalls = false; HealthQueries.Clear(); IdTimes.Clear(); Moves.Clear(); Appraised.Clear(); WeaponCalls = false; ContentsCalls = false; CombatModeValue = 1; RequestIdAccepts = true; RefusedIdRequests = 0; UseObjectAccepts = true; VTankFlags = -1; VTankSeq = 0; LogCostMicros = 0; @@ -396,8 +398,11 @@ internal static unsafe class FakeHost api.GetObjectStateFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetObjectState; if (InstanceIds.Count > 0) api.GetObjectInstanceIdPropertyFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetObjectInstanceIdProperty; - api.SetAutoRunFn = (IntPtr)(delegate* unmanaged[Cdecl])&SetAutoRun; - api.TurnToHeadingFn = (IntPtr)(delegate* unmanaged[Cdecl])&TurnToHeading; + if (!NoTurnOrAutoRun) + { + api.SetAutoRunFn = (IntPtr)(delegate* unmanaged[Cdecl])&SetAutoRun; + api.TurnToHeadingFn = (IntPtr)(delegate* unmanaged[Cdecl])&TurnToHeading; + } api.GetPlayerHeadingFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetPlayerHeading; api.JumpNonAutonomousFn = (IntPtr)(delegate* unmanaged[Cdecl])&JumpNonAutonomous; if (TapJumpCalls) diff --git a/Tools/RynthCore.RynthAiHostTests/Program.cs b/Tools/RynthCore.RynthAiHostTests/Program.cs index 1443c98..362d22a 100644 --- a/Tools/RynthCore.RynthAiHostTests/Program.cs +++ b/Tools/RynthCore.RynthAiHostTests/Program.cs @@ -212,6 +212,7 @@ internal static class Program InventoryAttributeFilterTests.Register(runner); StuckCastTests.Register(runner); KillNoticeTests.Register(runner); + PredictedKillReclaimTests.Register(runner); PacerEdgeTests.Register(runner); RecoveryRetryTests.Register(runner); HpFailsafeTests.Register(runner); @@ -237,6 +238,7 @@ internal static class Program CallStateRepairTests.Register(runner); ProfileButtonTests.Register(runner); MonsterProfileTests.Register(runner); + ProfileStartTests.Register(runner); GiveProfileTests.Register(runner); TinkerTests.Register(runner); KitRunnerTests.Register(runner); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/BackAwayTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/BackAwayTests.cs index 3f58a10..5fb1a93 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/BackAwayTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/BackAwayTests.cs @@ -10,9 +10,11 @@ namespace RynthCore.RynthAiHostTests.Tests; // The back-away combat does on a server plugin's request (CombatManager.BackAwayFrom, RynthAi.Hub // BackAwayFrom). It was the Empyrean Handler lethal-ring evade (Silentkelpie's PR 12) until 2026-10-20, // when the Handler's detection and its setting went to RynthILT (Infinite Leaftide content); RynthAi -// keeps the generic part: face the object, back-jump, hold attacks until it settles. Gated: only while -// the macro is running with combat on, and only inside the radius (at least Ring Range). RynthAi alone -// never reacts to the Handler's line any more. +// keeps the generic part: stop attacking, run away (face directly away, autorun until outside the radius +// plus a margin, re-aiming as it goes), hold attacks until clear, then re-engage. A single back-jump until +// 2026-11-27 (it covers a yard or two); it stays only for an engine without heading snap / autorun +// (spotted by SilentKelpie, Forgejo rynth PR #12). Gated: only while the macro is running with combat on, +// and only inside the radius (at least Ring Range). RynthAi alone never reacts to the Handler's line. internal static class BackAwayTests { private const uint Player = 0x50000D11; @@ -22,7 +24,10 @@ internal static class BackAwayTests public static void Register(Runner r) { - r.Add("back away: inside the radius with the macro running and combat on, one back-jump (and none while it runs)", Jumps); + r.Add("back away: inside the radius with the macro running and combat on, runs away (faces away, autorun on, no back-jump); not now while it runs", Runs); + r.Add("back away: the run re-aims away, holds attacks, stops outside the radius plus the margin (autorun off) and re-engages", RunEnds); + r.Add("back away: the run ends with autorun off when the macro stops, combat goes off, the danger is gone or it times out", RunStops); + r.Add("back away: an engine without heading snap or autorun gets the old back-jump", JumpFallback); r.Add("back away: not with the macro stopped or combat off", Gated); r.Add("back away: outside the radius (Ring Range widens it), or an object without a position: no jump", NotThese); r.Add("back away: RynthAi alone ignores the Empyrean Handler's ring line (RynthILT's now)", HandlerLineIgnored); @@ -36,7 +41,7 @@ internal static class BackAwayTests public float Heading = -1; public bool Busy; - public Rig(float dangerYards, bool place = true) + public Rig(float dangerYards, bool place = true, Action? beforeCreate = null) { FakeHost.Reset(); FakeHost.Names[Player] = "Evader"; @@ -45,6 +50,7 @@ internal static class BackAwayTests FakeHost.Names[Danger] = "Empyrean Handler"; if (place) FakeHost.Positions[Danger] = (Lb | 0x1C, 96f, 96f + dangerYards, 0f); FakeHost.ItemTypes[Danger] = 0x10; + beforeCreate?.Invoke(); var host = FakeHost.Create(Player); var cache = FakeHost.MakeCache(host, Player, new[] { Danger }); S.IsMacroRunning = true; @@ -58,20 +64,120 @@ internal static class BackAwayTests public int Ask(double radius = 12, int holdMs = 750) => Combat.BackAwayFrom(unchecked((int)Danger), radius, holdMs, "test"); } - private static void Jumps() + private static readonly System.Reflection.BindingFlags Any = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic; + private static DateTime _now = new(2026, 11, 27, 12, 0, 0, DateTimeKind.Utc); + + /// Runs on a test clock (RynthClock.TestNow), restored after. + private static void OnClock(Action body) + { + RynthClock.TestNow = () => _now; + try { body(); } + finally { RynthClock.TestNow = null; } + } + + private static bool Think(Rig rig) => (bool)typeof(CombatManager).GetMethod("TickBackAway", Any)!.Invoke(rig.Combat, null)!; + + /// Puts the character yards south of where it started. + private static void MoveSouth(float south) + { + FakeHost.Positions[Player] = (Lb | 0x1C, 96f, 96f - south, 0f); + FakeHost.PlayerPose = (Lb | 0x1C, 96f, 96f - south, 0f); + } + + private static void Runs() => OnClock(() => { var rig = new Rig(dangerYards: 5); Check.Eq(rig.Ask(), RynthAiHub.BackAwayStarted, "5 yards inside 12: started"); - Check.Eq(rig.Jumps, 1, "one back-jump"); + Check.Eq(rig.Jumps, 0, "no back-jump (a jump covers a yard or two)"); + Check.True(FakeHost.AutoRun, "autorun on"); + Check.True(Math.Abs(FakeHost.HeadingDeg - 180.0) < 1.0, $"faces directly away (the danger is north; heading {FakeHost.HeadingDeg:0})"); Check.True(rig.Combat.BackAwayActive, "combat holds while it runs"); + Check.Eq(rig.Ask(), RynthAiHub.BackAwayNotNow, "a second request while running: not now"); + Check.True(FakeHost.Logs.Exists(l => l.Contains("[CombatEvade]") && l.Contains("running away")), "logged as a run"); + }); + + private static void RunEnds() => OnClock(() => + { + var rig = new Rig(dangerYards: 5); + rig.Ask(radius: 12); + _now = _now.AddMilliseconds(100); + Check.True(Think(rig), "Think holds attacks while it runs"); + Check.Eq(rig.Combat.LastCombatSkipReason, "back-away-run", "and says why"); + + // Halfway, a little to the east: it re-aims away from the danger. + FakeHost.Positions[Player] = (Lb | 0x1C, 100f, 90f, 0f); + FakeHost.PlayerPose = (Lb | 0x1C, 100f, 90f, 0f); + FakeHost.HeadingDeg = 0; + _now = _now.AddMilliseconds(300); + Check.True(Think(rig), "still inside 12 + 4: holding"); + Check.True(FakeHost.HeadingDeg > 150 && FakeHost.HeadingDeg < 180, $"re-aimed away from the danger (heading {FakeHost.HeadingDeg:0})"); + Check.True(FakeHost.AutoRun, "still running"); + + MoveSouth(12f); // 17 yards from it: outside 12 + 4 + _now = _now.AddMilliseconds(300); + Check.False(Think(rig), "clear: Think re-engages"); + Check.False(FakeHost.AutoRun, "autorun off"); + Check.False(rig.Combat.BackAwayActive, "no longer held"); + Check.True(FakeHost.Logs.Exists(l => l.Contains("Back away done") && l.Contains("clear at")), "logged as clear"); + Check.Eq(rig.Ask(), RynthAiHub.BackAwayOutside, "a new request out here: outside"); + }); + + private static void RunStops() => OnClock(() => + { + var macro = new Rig(5); + macro.Ask(); + macro.S.IsMacroRunning = false; + macro.Combat.PollBackAway(); + Check.False(FakeHost.AutoRun, "macro stopped: autorun off"); + Check.False(macro.Combat.BackAwayActive, "macro stopped: over"); + + var combat = new Rig(5); + combat.Ask(); + combat.S.EnableCombat = false; + combat.Combat.PollBackAway(); + Check.False(FakeHost.AutoRun, "combat off: autorun off"); + Check.False(combat.Combat.BackAwayActive, "combat off: over"); + + var gone = new Rig(5); + gone.Ask(); + FakeHost.Positions.Remove(Danger); + _now = _now.AddMilliseconds(100); + Check.False(Think(gone), "the danger is gone: re-engage"); + Check.False(FakeHost.AutoRun, "gone: autorun off"); + + var stuck = new Rig(5); + stuck.Ask(); + _now = _now.AddMilliseconds(CombatManager.BackAwayRunMaxMs + 100); + Check.False(Think(stuck), "blocked (no progress): it times out"); + Check.False(FakeHost.AutoRun, "timed out: autorun off"); + Check.True(FakeHost.Logs.Exists(l => l.Contains("run timed out")), "logged"); + + // Think not driving it (another activity has the tick): the poll steps it, so it still ends when clear. + var orphan = new Rig(5); + orphan.Ask(); + MoveSouth(12f); + _now = _now.AddMilliseconds(500); + orphan.Combat.PollBackAway(); + Check.False(orphan.Combat.BackAwayActive, "the poll ended it once clear"); + Check.False(FakeHost.AutoRun, "autorun off"); + }); + + private static void JumpFallback() => OnClock(() => + { + FakeHost.Reset(); + var rig = new Rig(5, beforeCreate: () => FakeHost.NoTurnOrAutoRun = true); + Check.Eq(rig.Ask(), RynthAiHub.BackAwayStarted, "started"); + Check.Eq(rig.Jumps, 1, "one back-jump"); + Check.False(FakeHost.AutoRun, "no autorun"); + Check.True(rig.Combat.BackAwayActive, "combat holds while it jumps"); Check.Eq(rig.Ask(), RynthAiHub.BackAwayNotNow, "a second request while backing away: not now"); Check.Eq(rig.Jumps, 1, "still one jump"); - var refused = new Rig(5); + var refused = new Rig(5, beforeCreate: () => FakeHost.NoTurnOrAutoRun = true); refused.Combat.RequestBackJump = (_, _) => false; Check.Eq(refused.Ask(), RynthAiHub.BackAwayJumpRefused, "the jumper refused: said so"); Check.False(refused.Combat.BackAwayActive, "and combat isn't held"); - } + }); private static void Gated() { diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/BuffTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/BuffTests.cs index b68c6d3..775af37 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/BuffTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/BuffTests.cs @@ -101,6 +101,13 @@ internal static class BuffTests r.Add("buff upgrade: a confirmed upgrade resets the no-show count", UpgradeConfirmedResetsNoShows); r.Add("buff upgrade: Cancel Buffing ends the pending upgrade", UpgradeCancelEndsPending); r.Add("buff upgrade: an upgrade that would leave mana under the reserve waits for Stamina to Mana, then goes", UpgradeWaitsForManaReserve); + + // Spotted by SilentKelpie (rynth PR #12); re-implemented here. + r.Add("no components: a buff refused for components drops a level, not the buff; none left leaves it out", NoComponentsBuffDropsALevel); + r.Add("no components: more scarabs or tapers lift the list; the first reading only sets the base", NoComponentsLiftedByRestock); + r.Add("no components: a refusal after a later cast (combat's) leaves the pending buff alone", NoComponentsRefusalForTheLastCast); + r.Add("no components: the warning shows once per spell per 2 min, closes on OK or after 30 s, and not with the setting off", NoComponentsWarningHud); + r.Add("no components: Show No Components Warning defaults on, copies with the profile, is in the settings map", NoComponentsWarningSetting); } // ── Rig ─────────────────────────────────────────────────────────────────── @@ -2162,4 +2169,158 @@ internal static class BuffTests entry.Set("0"); Check.False(live.SkipUnusableBuffs, "and sets off"); } + + // ── Missing components (Spotted by SilentKelpie, rynth PR #12; re-implemented here) ── + + private const string NoComps = "You don't have all the components for this spell."; + + /// Tier 6 Creature Enchantment in Magic stance, knowing Strength Self IV to VI and nothing else. + private static BuffRig StrengthRig() + { + FakeHost.Reset(); + Know("Strength Self IV", "Strength Self V", "Strength Self VI"); + FakeHost.Skills[(Player, STypeCreature)] = (300, 2); + FakeHost.WeaponCalls = true; + FakeHost.CombatModeValue = CombatMode.Magic; + var rig = new BuffRig(); + rig.S.SpellCastIntervalMs = 0; + rig.Live(("Fire Protection Self I", 3000)); // a registry read, with none of ours on + return rig; + } + + /// One pass of the buff loop (a few tries); the spell it cast, or null. + private static string? CastOnce(BuffRig rig) + { + for (int i = 0; i < 30; i++) + { + int before = FakeHost.Casts.Count; + CastSelfBuffs.Invoke(rig.B, null); + if (FakeHost.Casts.Count > before) return NameOf(FakeHost.Casts[^1].SpellId); + System.Threading.Thread.Sleep(20); + } + return null; + } + + private static void NoComponentsBuffDropsALevel() + { + var rig = StrengthRig(); + Check.Eq(CastOnce(rig), "Strength Self VI", "the top level the skill allows"); + rig.B.OnChatWindowText(NoComps, 0); + Check.True(rig.Sm.LacksComponents(Id("Strength Self VI")), "that level is passed over"); + Check.True(FakeHost.Chat.Any(c => c.Contains("No components for Strength Self VI: buffing with a lower level")), "chat says so"); + Check.False(FakeHost.Chat.Any(c => c.Contains("Skipping Strength Self VI")), "the buff is not parked"); + Check.Eq(NameOf(rig.B.FindBestSpellId("Strength Self", AcSkillType.CreatureEnchantment)), "Strength Self V", "the picker drops a level"); + Check.Eq(CastOnce(rig), "Strength Self V", "and the next pass casts it"); + + rig.B.OnChatWindowText(NoComps, 0); + Check.Eq(NameOf(rig.B.FindBestSpellId("Strength Self", AcSkillType.CreatureEnchantment)), "Strength Self IV", "refused again: one more level down"); + rig.Sm.MarkNoComponents(Id("Strength Self IV")); + Check.Eq(rig.B.FindBestSpellId("Strength Self", AcSkillType.CreatureEnchantment), 0, "no castable level left: the buff is left out"); + + // The other refusals still park the buff as before. + var other = StrengthRig(); + Check.Eq(CastOnce(other), "Strength Self VI", "control: cast"); + other.B.OnChatWindowText("You must specify a target for this spell.", 0); + Check.False(other.Sm.LacksComponents(Id("Strength Self VI")), "not a components refusal: no level is passed over"); + Check.True(FakeHost.Chat.Any(c => c.Contains("Skipping Strength Self VI") && c.Contains("the server refused it")), "it is parked, as before"); + } + + private static void NoComponentsLiftedByRestock() + { + var rig = StrengthRig(); + int vi = Id("Strength Self VI"); + rig.Sm.NoteComponentCounts(20, 10); // the base + rig.Sm.MarkNoComponents(vi); + rig.Sm.NoteComponentCounts(20, 10); + Check.True(rig.Sm.LacksComponents(vi), "the same counts: still passed over"); + rig.Sm.NoteComponentCounts(19, 9); + Check.True(rig.Sm.LacksComponents(vi), "fewer (spent): still passed over"); + rig.Sm.NoteComponentCounts(19, 10); + Check.False(rig.Sm.LacksComponents(vi), "a taper more: lifted"); + rig.Sm.MarkNoComponents(vi); + rig.Sm.NoteComponentCounts(25, 10); + Check.False(rig.Sm.LacksComponents(vi), "scarabs more: lifted"); + Check.Eq(NameOf(rig.B.FindBestSpellId("Strength Self", AcSkillType.CreatureEnchantment)), "Strength Self VI", "the top level again"); + + var fresh = StrengthRig(); + fresh.Sm.MarkNoComponents(vi); + fresh.Sm.NoteComponentCounts(50, 50); + Check.True(fresh.Sm.LacksComponents(vi), "the first reading is only the base"); + Check.Eq(SpellManager.NoComponentsSec, 600.0, "ten minutes"); + } + + private static void NoComponentsRefusalForTheLastCast() + { + var rig = StrengthRig(); + Check.Eq(CastOnce(rig), "Strength Self VI", "the buff goes out"); + int vi = Id("Strength Self VI"); + Check.Eq(rig.B.PendingSpellId, vi, "and is pending"); + // Combat sends an attack after it; the refusal that follows answers the attack. + Check.True(RynthCore.Plugin.Shared.ActionPacer.CastSpellFor(rig.Host, 0x50000F00, Id("Flame Bolt VI"), "Combat", "Flame Bolt VI"), "an attack goes out after it"); + rig.B.OnChatWindowText(NoComps, 0); + Check.Eq(rig.B.PendingSpellId, vi, "the buff is still pending"); + Check.False(rig.Sm.LacksComponents(vi), "the buff's level is not passed over"); + Check.True(FakeHost.Logs.Any(l => l.Contains("refusal is for the last cast sent (Flame Bolt VI)")), "logged whose it is"); + } + + private static void NoComponentsWarningHud() + { + long now = 1_000_000; + bool on = true; + var hud = new RynthCore.Plugin.RynthAi.Huds.CastWarningHud(() => on, () => now); + Check.True(hud.Current() == null, "nothing up at first"); + hud.Post("Strength Self VI", "RynthAi buffs with a lower level of it instead."); + Check.Eq(hud.Current()?.Spell, "Strength Self VI", "up, naming the spell"); + now += 10_000; + hud.Post("Strength Self VI", "again"); + Check.Eq(hud.Current()?.Body, "RynthAi buffs with a lower level of it instead.", "the same spell within 2 min changes nothing"); + hud.Dismiss(); + Check.True(hud.Current() == null, "OK closes it"); + hud.Post("Strength Self VI", "again"); + Check.True(hud.Current() == null, "and the same spell doesn't bring it back within 2 min"); + hud.Post("Flame Bolt VI", "RynthAi attacks with a lower level of it instead."); + Check.Eq(hud.Current()?.Spell, "Flame Bolt VI", "another spell shows"); + now += RynthCore.Plugin.RynthAi.Huds.CastWarningHud.ShownForMs + 1; + Check.True(hud.Current() == null, "it closes by itself after 30 s"); + now += RynthCore.Plugin.RynthAi.Huds.CastWarningHud.RepeatSameMs; + hud.Post("Strength Self VI", "later"); + Check.Eq(hud.Current()?.Body, "later", "after 2 min the same spell shows again"); + on = false; + Check.True(hud.Current() == null, "turning the setting off closes it"); + hud.Post("Focus Self VI", "x"); + Check.True(hud.Current() == null, "and nothing shows while off"); + } + + private static void NoComponentsWarningSetting() + { + Check.True(new LegacyUiSettings().ShowNoComponentsWarning, "a new profile: on"); + var old = JsonSerializer.Deserialize("{\"EnableBuffing\":true}", RynthAiJsonContext.Default.LegacyUiSettings); + Check.True(old != null && old.ShowNoComponentsWarning, "a profile saved before the setting: on"); + var copy = typeof(LegacyDashboardRenderer).GetMethod("CopySettings", BindingFlags.NonPublic | BindingFlags.Static)!; + var dst = new LegacyUiSettings(); + copy.Invoke(null, new object[] { new LegacyUiSettings { ShowNoComponentsWarning = false }, dst }); + Check.False(dst.ShowNoComponentsWarning, "a profile with it off loads off"); + + var payload = JsonSerializer.Deserialize("{\"PatrolOnLogin\":false}", RynthAiJsonContext.Default.SettingsBridgePayload); + Check.True(payload != null && payload.ShowNoComponentsWarning == null, "an older engine's payload has no value"); + var s = new LegacyUiSettings { ShowNoComponentsWarning = false }; + var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer)); + typeof(LegacyDashboardRenderer).GetField("_profileLoaded", BindingFlags.Instance | BindingFlags.NonPublic)!.SetValue(dash, true); + typeof(LegacyDashboardRenderer).GetField("_settings", BindingFlags.NonPublic | BindingFlags.Instance)!.SetValue(dash, s); + typeof(LegacyDashboardRenderer).GetField("_advancedSettingsUi", BindingFlags.NonPublic | BindingFlags.Instance)! + .SetValue(dash, new LegacyAdvancedSettingsUi(s)); + var sent = JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload); + Check.True(sent != null && sent.ShowNoComponentsWarning == false, "sent to the engine face"); + dash.ApplySettingsJson("{\"PatrolOnLogin\":false}"); + Check.False(s.ShowNoComponentsWarning, "a save without the field leaves it off"); + dash.ApplySettingsJson("{\"ShowNoComponentsWarning\":true}"); + Check.True(s.ShowNoComponentsWarning, "a save with it on turns it on"); + + var live = new LegacyUiSettings(); + var map = ExpressionTests.Engine(settings: live).BuildSettingsMapPublic(); + Check.True(map.TryGetValue("ShowNoComponentsWarning", out var entry), "in the settings map"); + Check.Eq(entry.Get(), "1", "reads on"); + entry.Set("0"); + Check.False(live.ShowNoComponentsWarning, "and sets off"); + } } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/ChestLootTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/ChestLootTests.cs index 98c8be8..e55898a 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/ChestLootTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/ChestLootTests.cs @@ -59,6 +59,8 @@ internal static class ChestLootTests r.Add("chest loot: no jump-loot from a chest (a hop can take the character out of its use radius)", NoJumpLootFromChest); r.Add("chest loot: a chest gets 2 minutes (not the 12 s corpse timeout), restarted by each pickup", ChestTimeoutLongAndRestarted); r.Add("chest loot: an item the server would refuse for burden (past 300%) is left unsent, with a chat line; one that fits still goes", OverBurdenLeft); + r.Add("chest loot (2026-11-28): a matched item the client no longer has (the cache still lists it in the chest) is skipped, not sent, not counted as wanted; the rest still goes", GoneFromClientSkipped); + r.Add("chest loot (2026-11-28): a non-stack item that vanishes from the client after its send without showing in a pack is 'not looted', never 'merged into a stack'", VanishedNonStackNotLooted); r.Add("loot burden: ACE's carrying capacity and 300% limit", OverBurdenMath); } @@ -264,6 +266,54 @@ internal static class ChestLootTests } } + // 2026-11-28, Item Tool on a DreamWeave Legendary Chest: the server cleared a leftover 'Platemail + // Gauntlets' out of the chest; the cache still listed it there, it matched a Keep rule, the pickup + // went out for an object that no longer existed and its absence was read as "merged into a stack". + private static void GoneFromClientSkipped() + { + BaseWorld(); + AddItem(Gem2, "Fire Opal", ItemTypeGem, Chest); + var host = FakeHost.Create(Player); + var bot = new Bot(host); + bot.Create(Chest, Gem, Gem2, Spoon); + // The client drops the gem (no name, no position); RynthAi's cache still has it in the chest. + FakeHost.Names.Remove(Gem); + FakeHost.Positions.Remove(Gem); + bot.ServerOpens(Chest); + LootGemAndFinish(bot, Gem2); + bot.TickUntil(() => FakeHost.Closes.Count > 0); + Check.False(FakeHost.ExternalMoves.Any(m => m.Item1 == Gem), $"no move for the gone gem (moves: {Moves()})"); + Check.True(FakeHost.Logs.Any(l => l.Contains("gone from the client") && l.Contains($"{Gem:X8}")), "the skip is logged"); + Check.False(FakeHost.Logs.Any(l => l.Contains($"pickup confirmed for 0x{Gem:X8}")), "never 'confirmed'"); + Check.Eq(bot.Get("_chestKeyTallyWanted"), 1, "the chest looter's tally: one wanted (the gone gem is not)"); + Check.Eq(bot.Get("_chestKeyTallyTaken"), 1, "and one taken"); + Check.Eq(FakeHost.Closes.Count, 1, "the chest is finished and closed"); + } + + // 2026-11-28: a Legendary Chest's 'Helmet' the client was letting go of was picked up and the + // pickup "confirmed; merged into a stack in the pack" - a helmet is no stack, and it never landed. + private static void VanishedNonStackNotLooted() + { + BaseWorld(); + var host = FakeHost.Create(Player); + var bot = new Bot(host); + bot.Create(Chest, Gem, Spoon); + bot.ServerOpens(Chest); + bot.TickUntil(() => bot.Moved(Gem)); + Check.True(bot.Moved(Gem), $"the gem's pickup is sent (moves: {Moves()})"); + // The client lets the gem go: no name, no position, and the cache is told it was deleted. + FakeHost.Names.Remove(Gem); + FakeHost.Positions.Remove(Gem); + FakeHost.Containers.Remove(Gem); + bot.P.OnDeleteObject(Gem); + bot.TickUntil(() => FakeHost.Closes.Count > 0, max: 400); + Check.False(FakeHost.Logs.Any(l => l.Contains($"pickup confirmed for 0x{Gem:X8}")), "not 'confirmed' (" + string.Join(" | ", FakeHost.Logs.Where(l => l.Contains($"{Gem:X8}"))) + ")"); + Check.True(FakeHost.Logs.Any(l => l.Contains($"{Gem:X8}") && l.Contains("not looted")), "logged as not looted"); + Check.Eq(bot.Get("_chestKeyTallyTaken"), 0, "the chest looter's tally: nothing taken"); + Check.Eq(bot.Get("_chestKeyTallyWanted"), 1, "and one wanted (the Item Tool's nothing-taken stop counts it)"); + Check.Eq(FakeHost.Closes.Count, 1, "the chest is finished and closed"); + } + private static void OverBurdenMath() { Check.Eq(RynthAiPlugin.CarryCapacity(100, 0), 15_000L, "150 per Strength"); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/CombatHookTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/CombatHookTests.cs index 42f1102..5225558 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/CombatHookTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/CombatHookTests.cs @@ -69,6 +69,8 @@ internal static class CombatHookTests r.Add("combat hook: a script cast at the fight target is tagged for the Damage tab (element and tier from its spell)", ScriptCastAttribution); r.Add("combat hook: a heal request names the fight target and its health; a nil answer target still heals the player", HealRequestNamesFightTarget); r.Add("combat hook: a refusal after another cast (a heal) or after the script spell landed does not park the script spell", RefusalNotMisattributed); + // Spotted by SilentKelpie (rynth PR #12); re-implemented here. + r.Add("no components: an attack spell refused for components drops a level (not cast again); a refusal after a later cast is not the attack's", AttackNoComponentsDropsALevel); r.Add("combat hook: a script bolt predicted to kill swaps to the next target like RynthAi's own (not without an alternate, not NOJUDGE)", ScriptKillShotSwaps); r.Add("combat hook: with War and Void untrained, a held attack kind makes the listed wand the weapon: Magic stance, not unarmed Melee", HookMakesWandTheWeapon); } @@ -1654,7 +1656,7 @@ internal static class CombatHookTests MethodInfo issue = typeof(CombatManager).GetMethod("IssueScriptCast", BindingFlags.NonPublic | BindingFlags.Instance)!; void ScriptAttack(HealRig rig) => Check.True((bool)issue.Invoke(rig.C, new object[] { drain, (uint)Target, RynthAiCombat.FlagArea, "Fire" })!, "the script's attack cast went out"); - bool HealParked(HealRig rig, int id) => Field>(rig.B, "_noComponentsUntil").ContainsKey(id); + bool HealParked(HealRig rig, int id) => Field(rig.B, "_spellManager").LacksComponents(id); // Control: the refusal right after the script's cast is the script spell's. var ctl = new HealRig(); @@ -1684,6 +1686,32 @@ internal static class CombatHookTests Check.False(landed.C.ScriptSpellParked(drain), "landed: not parked"); }); + private static void AttackNoComponentsDropsALevel() => Guard(() => + { + int vi = Id("Flame Bolt VI"), v = Id("Flame Bolt V"); + void KnowV() { foreach (var row in SpellTable.Named("Flame Bolt V")) FakeHost.Spellbook.Add((uint)row.Id); } + + var rig = new AttackRig(setup: KnowV); + rig.Attack(); + Check.Eq(rig.LastCast, "Flame Bolt VI", "the top level first"); + rig.C.HandleChatForDebuffs(NoComponents); + Check.True(rig.Sm.LacksComponents(vi), "refused for components: that level is passed over"); + Check.Eq(rig.PendingOffensive, 0, "and the pending cast is cleared"); + Check.True(FakeHost.Chat.Count(c => c.Contains("No components for Flame Bolt VI: attacking with a lower level")) == 1, "chat says so once"); + rig.Attack(); + Check.Eq(rig.LastCast, "Flame Bolt V", "the next attack is a level lower, not the refused level again"); + Check.Eq(FakeHost.Casts.Count(c => c.SpellId == vi), 1, "the refused level went out once"); + + // A heal sent after the attack: the refusal is the heal's, and the attack stays pending. + var mixed = new AttackRig(setup: KnowV); + mixed.Attack(); + Check.Eq(mixed.LastCast, "Flame Bolt VI", "mixed: the attack went out"); + Check.True(ActionPacer.CastSpellFor(mixed.Host, Player, Id("Heal Self V"), "Buff", "Heal Self V"), "mixed: then a heal"); + mixed.C.HandleChatForDebuffs(NoComponents); + Check.False(mixed.Sm.LacksComponents(vi), "mixed: the attack level is not passed over"); + Check.Eq(mixed.PendingOffensive, vi, "mixed: the attack is still pending"); + }); + private static void ScriptKillShotSwaps() => Guard(() => { int bolt = Id("Flame Bolt VI"); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/DoorTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/DoorTests.cs index 8387e5e..dd2731e 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/DoorTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/DoorTests.cs @@ -36,6 +36,9 @@ internal static class DoorTests r.Add("door: still closed after an answered use, no 'locked' from the server: used again, never picked", NotLockedWithoutServer); r.Add("door: the server says locked: a lockpick goes on it, then the door is opened again", LockedUsesLockpick); r.Add("door: locked and no lockpick: cooldown, and the door is skipped a while", LockedNoPick); + r.Add("door: the server says locked: carried keys go first, one at a time (a key that doesn't fit, 0x4B2, goes straight to the next), then the lockpick", LockedKeysThenLockpick); + r.Add("door: the server says locked: a key that fits is followed by an open, no lockpick; a lockpick is never tried as a key", LockedKeyFits); + r.Add("door: Auto-Unlock Doors off: no key and no lockpick on a locked door", LockedKeysNeedAutoUnlock); r.Add("door: nothing in portal space, nor just after it", NothingInPortalSpace); r.Add("door: a door that opens is released at once (no fixed waits)", OpensFast); r.Add("door: 'locked' from chat counts only as the server's line, not a player's", LockedChatLine); @@ -83,7 +86,7 @@ internal static class DoorTests public long Now = 50_000_000; public readonly RynthCoreHost Host; - public Bot(bool lockpick = true) + public Bot(bool lockpick = true, Action? beforeCreate = null) { FakeHost.Reset(); FakeHost.WeaponCalls = true; // UseObject @@ -100,6 +103,7 @@ internal static class DoorTests FakeHost.ObjectStates[Door] = Closed; FakeHost.Names[Pick] = "Plain Lockpick"; FakeHost.Names[Kit] = "Treated Healing Kit"; + beforeCreate?.Invoke(); Host = FakeHost.Create(Player); ActionPacer.Reset(); @@ -127,6 +131,8 @@ internal static class DoorTests Cache.OnCreateObject(Door); _ = Cache[unchecked((int)Pick)]; _ = Cache[unchecked((int)Kit)]; + foreach (uint k in new[] { KeyA, KeyB, KeyC, PackPick }) + if (FakeHost.Names.ContainsKey(k)) _ = Cache[unchecked((int)k)]; Cache.Tick(); if (lockpick) S.ConsumableRules.Add(new ConsumableRule { Id = unchecked((int)Pick), Name = "Plain Lockpick", Type = "Lockpick" }); @@ -280,6 +286,98 @@ internal static class DoorTests Check.Eq(b.State, "None", "done"); }); + // ── Carried keys before lockpicks (2026-11-27; spotted by SilentKelpie, Forgejo rynth PR #12) ── + + private const uint KeyA = 0x80000D13, KeyB = 0x80000D14, KeyC = 0x80000D15, PackPick = 0x80000D16; + private const uint TypeKey = 0x4000; // AC ItemType.Key (lockpicks have it too) + + /// Puts a key (or a key-typed lockpick) in the pack before the rig is made. + private static void Carry(uint id, string name, bool lockpickBit = false) + { + FakeHost.Names[id] = name; + FakeHost.ItemTypes[id] = TypeKey; + FakeHost.Containers[id] = Player; + if (lockpickBit) FakeHost.Bitfields[id] = 0x20000; // BF_LOCKPICK + } + + private static int KeyUses(uint key) => FakeHost.UsesOn.Count(u => u.Source == key && u.Target == Door); + + /// Uses the door, and the server says it is locked. + private static void LockedAnswer(Bot b) + { + b.Run(1500, 100); + b.Say("The door is locked!"); + b.Answer(open: false); + b.Run(300); + } + + private static void LockedKeysThenLockpick() => With(() => + { + var b = new Bot(lockpick: true, beforeCreate: () => + { + Carry(KeyA, "Rusty Key"); + Carry(KeyB, "Cave Door Key"); + }); + b.Tick(); + b.Run(300); + Check.Eq(DoorUses(), 1, "first use"); + LockedAnswer(b); + int first = KeyUses(KeyA) + KeyUses(KeyB); + Check.Eq(first, 1, "locked: one carried key goes on the door first"); + Check.Eq(Picks(), 0, "...not the lockpick"); + Check.Eq(DoorUses(), 1, "...and no open over it"); + + FakeHost.UseDone(0x4B2); // KeyDoesntFitThisLock: nothing spent + b.Run(300); + Check.Eq(KeyUses(KeyA) + KeyUses(KeyB), 2, "didn't fit: the other key goes at once"); + Check.True(KeyUses(KeyA) == 1 && KeyUses(KeyB) == 1, "each key once"); + Check.Eq(DoorUses(), 1, "no open between keys that don't fit"); + + FakeHost.UseDone(0x4B2); + b.Run(300); + Check.Eq(Picks(), 1, "no key left: the lockpick"); + Check.True(FakeHost.Logs.Any(l => l.Contains("doesn't fit")), "the keys that didn't fit are logged"); + FakeHost.UseDone(0); + b.Run(300); + Check.Eq(DoorUses(), 2, "opened again after the lockpick"); + Check.Eq(KeyUses(KeyA) + KeyUses(KeyB), 2, "no key tried twice"); + }); + + private static void LockedKeyFits() => With(() => + { + var b = new Bot(lockpick: true, beforeCreate: () => + { + Carry(PackPick, "Reliable Lockpick", lockpickBit: true); // key-typed, but a lockpick + Carry(KeyC, "Black Gate Key"); + }); + b.Tick(); + b.Run(300); + LockedAnswer(b); + Check.Eq(KeyUses(KeyC), 1, "the key goes on the door"); + Check.Eq(KeyUses(PackPick), 0, "a lockpick is never tried as a key"); + FakeHost.UseDone(0); // it fit + b.Run(300); + Check.Eq(DoorUses(), 2, "opened again after the key"); + Check.Eq(Picks(), 0, "no lockpick"); + b.Run(800); + b.Answer(open: true); + b.Now += 50; + Check.False(b.Tick(), "opened: nav released"); + Check.Eq(b.State, "None", "done"); + }); + + private static void LockedKeysNeedAutoUnlock() => With(() => + { + var b = new Bot(lockpick: true, beforeCreate: () => Carry(KeyA, "Rusty Key")); + b.S.AutoUnlockDoors = false; + b.Tick(); + b.Run(300); + LockedAnswer(b); + Check.Eq(KeyUses(KeyA), 0, "no key"); + Check.Eq(Picks(), 0, "no lockpick"); + Check.Eq(b.State, "Cooldown", "cooldown"); + }); + private static void LockedNoPick() => With(() => { var b = new Bot(lockpick: false); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/DunNavToTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/DunNavToTests.cs index 52a76af..ea9a1b7 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/DunNavToTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/DunNavToTests.cs @@ -16,6 +16,147 @@ internal static class DunNavToTests public static void Register(Runner r) { r.Add("dunnav-to: walks to an object's cell on the dungeon map, the macro on; refuses an unknown one or one outside the dungeon", WalksToObject); + r.Add("dunnav-to cell: walks to a cell of the dungeon by its number (a person the client hasn't been sent yet), labelled; refuses another dungeon's or a bad cell", WalksToCell); + r.Add("dunnav-to walkonly: fighting, looting, buffing and the meta off for the walk, put back exactly as they were when it ends, stops or fails", WalkOnlyTrip); + } + + // RynthNav's go to someone inside a dungeon hands the walk on as "/ra dunnav-to cell walkonly " + // by default (2026-11-27): a run to the target with no fighting, looting or buffing on the way. + private static void WalkOnlyTrip() + { + var rig = new DunRouteTests.Rig("NavProfiles-dunnav-to-walkonly"); + string cell = rig.D.West.ToString("X8"); + void Switches(bool combat, bool loot, bool buff, bool meta) + { + rig.S.EnableCombat = combat; rig.S.EnableLooting = loot; rig.S.EnableBuffing = buff; rig.S.EnableMeta = meta; + } + string Now() => $"combat {rig.S.EnableCombat} loot {rig.S.EnableLooting} buff {rig.S.EnableBuffing} meta {rig.S.EnableMeta} macro {rig.S.IsMacroRunning}"; + List Tick() + { + int before = FakeHost.Chat.Count; + rig.Call("TickWalkTrip"); + return FakeHost.Chat.Skip(before).ToList(); + } + + // 1. Arrives: everything back, and the macro off again (it was off). + rig.S.IsMacroRunning = false; + Switches(true, true, true, true); + var said = rig.Typed($"/ra dunnav-to cell {cell} walkonly Hall Keeper"); + Check.True(said.Count == 1 && said[0].StartsWith("[RynthAi] DunNav-To: 'Hall Keeper' in " + cell) && said[0].Contains("walk only"), + "it answers, the label without the word walkonly: " + string.Join(" | ", said)); + Check.True(rig.S.IsMacroRunning && rig.S.EnableNavigation, "macro and navigation on for the walk"); + Check.False(rig.S.EnableCombat || rig.S.EnableLooting || rig.S.EnableBuffing || rig.S.EnableMeta, "no fighting, looting, buffing or meta on the way: " + Now()); + Check.True(Tick().Count == 0, "walking: nothing said"); + Check.False(rig.S.EnableCombat, "still walking: combat stays off"); + rig.S.ActiveNavIndex = rig.S.CurrentRoute.Points.Count; // the nav engine walked off the last point + rig.S.EnableNavigation = false; + said = Tick(); + Check.True(said.Count == 1 && said[0].Contains("ended (arrived)") && said[0].Contains("macro off again"), "arrived: said: " + string.Join(" | ", said)); + Check.True(rig.S.EnableCombat && rig.S.EnableLooting && rig.S.EnableBuffing && rig.S.EnableMeta && !rig.S.IsMacroRunning, "all back as before: " + Now()); + Check.True(Tick().Count == 0, "over: nothing more"); + + // 2. The player stops the macro mid-walk: a mixed set back as it was, the macro stays off. + rig.S.IsMacroRunning = true; + Switches(false, true, false, true); + rig.Typed($"/ra dunnav-to cell {cell} walkonly"); + Check.False(rig.S.EnableLooting || rig.S.EnableMeta, "off for the walk"); + rig.S.IsMacroRunning = false; + said = Tick(); + Check.True(said.Count == 1 && said[0].Contains("the macro was stopped"), "stopped: said: " + string.Join(" | ", said)); + Check.True(!rig.S.EnableCombat && rig.S.EnableLooting && !rig.S.EnableBuffing && rig.S.EnableMeta && !rig.S.IsMacroRunning, "back exactly: " + Now()); + + // 3. The macro was on before: it stays on at the end; nav switched off counts as the end. + rig.S.IsMacroRunning = true; + Switches(true, false, true, false); + rig.Typed($"/ra dunnav-to cell {cell} walkonly"); + rig.S.EnableNavigation = false; + said = Tick(); + Check.True(said.Count == 1 && said[0].Contains("navigation was turned off") && !said[0].Contains("macro off"), "nav off: " + string.Join(" | ", said)); + Check.True(rig.S.EnableCombat && !rig.S.EnableLooting && rig.S.EnableBuffing && !rig.S.EnableMeta && rig.S.IsMacroRunning, "back, the macro still on: " + Now()); + + // 4. Another route loaded (a meta, a script, the player): the switches back, the macro left to its new owner. + rig.S.IsMacroRunning = false; + Switches(true, true, true, true); + rig.Typed($"/ra dunnav-to cell {cell} walkonly"); + rig.S.CurrentRoute = new NavRouteParser { RouteType = NavRouteType.Circular }; + said = Tick(); + Check.True(said.Count == 1 && said[0].Contains("another route was loaded"), "another route: " + string.Join(" | ", said)); + Check.True(rig.S.EnableCombat && rig.S.EnableLooting && rig.S.EnableBuffing && rig.S.EnableMeta && rig.S.IsMacroRunning, "switches back, macro left on: " + Now()); + + // 5. Out of the dungeon mid-walk (a portal, a recall, a death): back, the macro off again. + rig.S.IsMacroRunning = false; + Switches(true, true, true, true); + rig.Typed($"/ra dunnav-to cell {cell} walkonly"); + rig.At(10, 10, 0xA9B40020); + said = Tick(); + Check.True(said.Count == 1 && said[0].Contains("you left the dungeon"), "left: " + string.Join(" | ", said)); + Check.True(rig.S.EnableCombat && rig.S.EnableLooting && rig.S.EnableBuffing && rig.S.EnableMeta && !rig.S.IsMacroRunning, "back: " + Now()); + rig.At(15, 15, rig.D.Start); + + // 6. A second walk-only trip over the first: the player's switches are kept, not the first trip's offs. + rig.S.IsMacroRunning = false; + Switches(true, true, false, true); + rig.Typed($"/ra dunnav-to cell {cell} walkonly"); + rig.Typed($"/ra dunnav-to cell {cell} walkonly"); + rig.S.IsMacroRunning = false; + Tick(); + Check.True(rig.S.EnableCombat && rig.S.EnableLooting && !rig.S.EnableBuffing && rig.S.EnableMeta, "the player's own, after two trips: " + Now()); + + // 7. Unloaded or logged out mid-walk: the switches back before the profile is saved. + Switches(true, true, true, true); + rig.S.IsMacroRunning = false; + rig.Typed($"/ra dunnav-to cell {cell} walkonly"); + rig.Call("ForgetWalkTrip"); + Check.True(rig.S.EnableCombat && rig.S.EnableLooting && rig.S.EnableBuffing && rig.S.EnableMeta, "back for the save: " + Now()); + Check.True(rig.Get("_walkTrip") == null, "the trip is forgotten"); + + // Without walkonly the walk runs the macro as set (fight on the way in), the switches untouched. + rig.S.IsMacroRunning = false; + Switches(true, true, true, false); + rig.Typed($"/ra dunnav-to cell {cell} Hall Keeper"); + Check.True(rig.S.EnableCombat && rig.S.EnableLooting && rig.S.EnableBuffing && rig.S.IsMacroRunning, "no walkonly: as set: " + Now()); + Check.True(rig.Get("_walkTrip") == null, "no trip"); + } + + // RynthNav's go to someone inside a dungeon hands the walk on as "/ra dunnav-to cell " (2026-11-27). + // Spotted by SilentKelpie (Forgejo rynth PR #12); re-implemented here. + private static void WalksToCell() + { + var rig = new DunRouteTests.Rig("NavProfiles-dunnav-to-cell"); + rig.S.IsMacroRunning = false; + string cell = rig.D.West.ToString("X8"); + + var said = rig.Typed($"/ra dunnav-to cell {cell} Hall Keeper"); + Check.True(said.Count == 1 && said[0].StartsWith("[RynthAi] DunNav-To: 'Hall Keeper' in " + cell) && said[0].Contains("walking there"), + "it answers with the label: " + string.Join(" | ", said)); + var pts = rig.S.CurrentRoute.Points; + Check.True(pts.Count >= 2, $"a walk ({pts.Count} points)"); + Check.True(rig.S.IsMacroRunning && rig.S.EnableNavigation, "macro and navigation on"); + var last = pts[^1]; + double lx = DungeonGeometry.NavToWorld(last.EW) - DunRouteTests.Ox, ly = DungeonGeometry.NavToWorld(last.NS) - DunRouteTests.Oy; + Check.True(Math.Abs(lx - -17.5) < 3 && Math.Abs(ly - 25) < 3, $"it ends in the west room's middle ({lx:F1}, {ly:F1})"); + + // No label: the cell names itself. Lower case and 0x work. + rig.S.IsMacroRunning = false; + said = rig.Typed($"/ra dunnav-to cell 0x{cell.ToLowerInvariant()}"); + Check.True(said.Count == 1 && said[0].Contains($"'cell {cell}'"), "unlabelled: " + string.Join(" | ", said)); + + var before = rig.S.CurrentRoute; + said = rig.Typed("/ra dunnav-to cell 009C0270 Someone"); + Check.True(said.Count == 1 && said[0].Contains("isn't in this dungeon"), "another dungeon's cell: " + string.Join(" | ", said)); + said = rig.Typed($"/ra dunnav-to cell {(DunRouteTests.Lb << 16 | 0x0F00):X8}"); + Check.True(said.Count == 1 && said[0].Contains("isn't on this dungeon's map"), "a cell the map hasn't: " + string.Join(" | ", said)); + said = rig.Typed("/ra dunnav-to cell 12"); + Check.True(said.Count == 1 && said[0].Contains("Usage: /ra dunnav-to"), "a bad cell: the usage"); + said = rig.Typed($"/ra dunnav-to cell {(DunRouteTests.Lb << 16 | 0x0020):X8}"); + Check.True(said.Count == 1 && said[0].Contains("Usage: /ra dunnav-to"), "an outdoor cell: the usage"); + Check.True(ReferenceEquals(rig.S.CurrentRoute, before), "the walk in hand is left alone"); + + // Standing in that cell already: said so, nothing laid. + rig.At(-17.5, 25, rig.D.West); + said = rig.Typed($"/ra dunnav-to cell {cell}"); + Check.True(said.Count == 1 && said[0].Contains("already in"), "there already: " + string.Join(" | ", said)); + Check.True(ReferenceEquals(rig.S.CurrentRoute, before), "nothing laid when there"); } private const uint Rat = 0x7E7E9101, Outside = 0x7E7E9102, Unknown = 0x7E7E9103; diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/ExpressionTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/ExpressionTests.cs index 51326f7..9e7d4c9 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/ExpressionTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/ExpressionTests.cs @@ -710,10 +710,10 @@ internal static class ExpressionTests Is(e, "vtgetsetting[ChestRelockWaitSec]", "125"); Is(e, "vtsetsetting[ChestRelockWaitSec, 30]", "1"); Check.Eq(s.ChestRelockWaitSec, 30, "ChestRelockWaitSec (Item Tool's re-lock wait) set"); - Is(e, "vtsetsetting[ChestRelockWaitSec, 2]", "1"); - Check.Eq(s.ChestRelockWaitSec, 5, "ChestRelockWaitSec clamps to at least 5"); + Is(e, "vtsetsetting[ChestRelockWaitSec, 0]", "1"); + Check.Eq(s.ChestRelockWaitSec, 1, "ChestRelockWaitSec clamps to at least 1 (MinRelockWaitSec since the fast re-lock)"); Is(e, "vtsetsetting[ChestRelockWaitSec, soon]", "1"); - Check.Eq(s.ChestRelockWaitSec, 5, "unparsable leaves the value"); + Check.Eq(s.ChestRelockWaitSec, 1, "unparsable leaves the value"); Is(e, "vtsetsetting[BowArcVelocity, NaN]", "1"); Check.True(float.IsFinite(s.BowArcVelocity), "NaN is refused"); Is(e, "vtsetsetting[NotASetting, 7]", "1"); @@ -920,7 +920,13 @@ internal static class ExpressionTests qt.OnChatLine("blankaug - 1 solves (1609459200)\"Blank Aug\" 1 0"); qt.OnChatLine($"killtask - 12 solves ({recent})\"Kill task\" 50 3600"); qt.OnChatLine("oldtimer - 3 solves (1609459200)\"Old timer\" 10 3600"); + // A space after the timestamp and -1 max solves (unlimited): still read, timer and all. + qt.OnChatLine($"spacedwait - 42 solves ({recent}) \"Spaced wait\" -1 3600"); qt.OnChatLine("You say, \"hello\""); + Check.True(qt.TryGetFlag("spacedwait", out var spaced) && spaced.Description == "Spaced wait" + && spaced.MaxSolves == -1 && spaced.RepeatTime == TimeSpan.FromSeconds(3600), + "a line with a space after the timestamp keeps its description, max solves and repeat time"); + Is(e, "getqueststatus[spacedwait]", "0"); // its timer is still running Is(e, "testquestflag[BlankAug]", "1"); Is(e, "testquestflag[nothere]", "0"); Is(e, "getqueststatus[blankaug]", "0"); // once-only, done: never ready again diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/GiveTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/GiveTests.cs index d4e35d5..cfdf7aa 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/GiveTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/GiveTests.cs @@ -40,6 +40,7 @@ internal static class GiveTests r.Add("give: busy refusals re-send with no cap", BusyResendsUncapped); r.Add("give: a permanent refusal skips the stack at once and moves on", PermanentSkips); r.Add("give: item not found after a re-send counts as given", ItemNotFoundAfterResendCounts); + r.Add("give: 'You allow X to examine your Y' is an answer: no re-send, the next stack goes, counted apart", ExaminedIsAnAnswer); r.Add("give: the summary counts items, not stacks", SummaryCountsItems); r.Add("give: no answer at all re-sends once, then skips", NoAnswerSkips); r.Add("give: an unreadable stack count is no information, not a shrink", UnreadableStackIsNotAShrink); @@ -408,6 +409,27 @@ internal static class GiveTests Check.True(w.ChatHas("1 item(s) given, 1 stack(s) skipped"), "summary: one given, one skipped with its reason"); } + // ACE's Refuse emote (an NPC that only looks at an item, e.g. to stamp a parchment) leaves the item with + // the player and says "You allow X to examine your Y." That was no answer: re-sent, then skipped. + private static void ExaminedIsAnAnswer() + { + var w = new World(); + FakeHost.GiveLands = false; + w.Call("EnqueueGive", Mote1, Npc, 1); + w.Call("EnqueueGive", Mote2, Npc, 1); + w.Tick(); + Check.Eq(FakeHost.Gives.Count, 1, "first stack out"); + w.Chat("You allow Town Crier to examine your Mana Mote."); + w.Tick(); + Check.Eq(FakeHost.Gives.Count, 2, "answered: the next stack goes on that same tick"); + Check.Eq(FakeHost.Gives[1].Item, Mote2, "the second stack, not a re-send of the first"); + w.Chat("You allow Town Crier to examine your Mana Mote."); + w.Tick(); + w.Tick(3001); + Check.Eq(FakeHost.Gives.Count, 2, "no re-send after the confirm time"); + Check.True(w.ChatHas("0 item(s) given, 2 examined and handed back, 0 stack(s) skipped"), "summary: examined, not given or skipped"); + } + private static void ItemNotFoundAfterResendCounts() { var w = new World(); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/ItemToolTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/ItemToolTests.cs index 03a7fe4..f956057 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/ItemToolTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/ItemToolTests.cs @@ -40,7 +40,10 @@ internal static class ItemToolTests r.Add("chest looter: combat/busy holds every send, then the run stops after the cap", ChestHoldsThenStops); r.Add("chest looter: can't start without a chest, a key, a loaded near chest; Stop always works and ends the loot session", ChestStartRefusalsAndStop); r.Add("chest looter: a key that never runs out is cut off at MaxCycles", ChestMaxCycles); - r.Add("chest looter: the re-lock wait is the 'Chest re-lock wait (s)' setting, clamped 5..600; a change applies to the wait running", ChestRelockSetting); + r.Add("chest looter: keys that are spent go past 300 chests until they are gone; the two-line uses-left message is read (2026-11-28 'after 300 keys it stops')", ChestSpentKeysPastMaxCycles); + r.Add("chest looter: a chest seen re-locking (unlocked after the key, locked again, shown closed) is keyed again at once, whatever the wait; a stale locked read is not (2026-11-28 'the 5s ... is way too long')", ChestRelockSeenGoesAtOnce); + r.Add("chest looter: 3 chests in a row with wanted loot and nothing picked up stop the run with the item and why (2026-11-28)", ChestStopsWhenNothingTaken); + r.Add("chest looter: the re-lock wait is the 'Chest re-lock wait (s)' setting, clamped 1..600; after the loot it waits for the close seen (or 2 s); a change applies to the wait running", ChestRelockSetting); r.Add("chest looter: after a short re-lock wait the asks follow it (never under 5 s apart), bounded; a long wait still ends when the chest reads locked", ChestRelockProbes); // Quick give state machine r.Add("quick give: one give at a time, each after the last landed, paced; done when none is left", GiveOneAtATime); @@ -48,12 +51,18 @@ internal static class ItemToolTests r.Add("quick give: a refused item is left out; three refusals in a row stop it", GiveRefusals); r.Add("quick give: stops when the target vanishes, changes, moves away or a fight starts", GiveStopConditions); r.Add("quick give: refuses to start with the target far, unloaded, no item or in a fight; busy client waits", GiveStartRefusals); + r.Add("quick give Amount: a round gives that many units, splitting a bigger stack (the rest stays in the pack)", GiveAmountSplits); + r.Add("quick give Amount: with an NPC that takes one per give, the round still stops at the amount", GiveAmountOnePerGive); + r.Add("quick give Every: rounds repeat after the interval until Stop; none left, out of range or a fight only hold the next round", GiveEveryRounds); + r.Add("quick give Every: a fight or the target leaving mid-round ends the round, not the run; a changed target ends the run", GiveEveryMidRound); // Plugin glue r.Add("item tool: the chest looter picks the selected chest and key, unlocks, opens and loots with the macro off, stops when out of keys", PluginChestRun); r.Add("item tool: chest/key picks refuse the wrong things (a pack item as chest, a world object as key, house storage)", PluginChestPicks); + r.Add("item tool: a full main pack holds no key while a side pack has room (the looter makes room); every pack full or under the 2-slot reserve holds it (2026-11-28)", PluginNoRoomOnlyWhenAllFull); r.Add("item tool: Quick give hands over exactly the picked item to the picked NPC, never worn gear or other names", PluginQuickGive); r.Add("item tool: Quick give starts only from the panel or a typed line, never from a meta, a script or a remote line; stop works from anywhere", PluginGiveTrust); r.Add("item tool: Quick give targets are players or NPCs only", PluginGiveTargets); + r.Add("item tool: /ra itemtool giveamount / giveevery set, clamp and answer (any source); the panel's data carries them", PluginGiveAmountEvery); r.Add("item tool: /ra itemtool relock sets, clamps and saves the re-lock wait and always answers with the value; refused before the profile loads", PluginRelockCommand); r.Add("item tool: the re-lock wait is saved in the profile and loaded (old profiles: 125 s), sent to the engine and left alone by an engine without it", RelockSavedAndLoaded); } @@ -82,6 +91,7 @@ internal static class ItemToolTests /// > 0: the corpse looter is played: it takes a requested chest and lets go this long after. public long AutoLootMs; public bool IgnoreStart; // StartLooting does nothing (the looter never takes the chest) + public bool RelockOnClose; // the loot's end sets Locked = true (a chest that resets as it closes) private long _lootEnd; // The server's script for the next key use / open: filled by the test, run on send. @@ -126,6 +136,18 @@ internal static class ItemToolTests public bool Looting(int chestId) => LootPending || LootingNow; public void AbortLooting(int chestId) { Aborts++; LootPending = LootingNow = false; } public bool? ChestLockedHint(int chestId) => Locked; + public bool? ShownOpen; + public bool? ChestShownOpen(int chestId) => ShownOpen; + // The corpse looter's tally of the last session (null = not known). + public Func<(int Wanted, int Taken)>? Tally; + public bool LastLootTally(int chestId, out int wanted, out int taken, out string firstWanted) + { + wanted = taken = 0; firstWanted = ""; + if (Tally == null) return false; + (wanted, taken) = Tally(); + firstWanted = "Olthoi Breastplate"; + return true; + } public void Say(string text) => Said.Add(text); public void Log(string text) => Logs.Add(text); @@ -139,7 +161,11 @@ internal static class ItemToolTests if (AutoLootMs > 0) { if (LootPending) { LootPending = false; LootingNow = true; _lootEnd = T + AutoLootMs; } - else if (LootingNow && T >= _lootEnd) LootingNow = false; + else if (LootingNow && T >= _lootEnd) + { + LootingNow = false; + if (RelockOnClose) Locked = true; // ChestRegenOnClose: the close resets it (Locked=true) + } } Looter.Tick(); } @@ -451,15 +477,145 @@ internal static class ItemToolTests ck.Start(out _); env.Run(60_000_000, () => !ck.Running); Check.False(ck.Running, "ended"); - Check.Eq(ck.Looted, ChestKeyLooter.MaxCycles, "after MaxCycles chests"); + Check.Eq(ck.Looted, ChestKeyLooter.MaxCycles, "after MaxCycles chests with no key use spent"); string said = Said(env); - Check.True(said.Contains($"{ChestKeyLooter.MaxCycles} cycles"), "says why: " + said.Substring(Math.Max(0, said.Length - 200))); + Check.True(said.Contains($"{ChestKeyLooter.MaxCycles} chests in a row without a key use spent"), "says why: " + said.Substring(Math.Max(0, said.Length - 200))); + } + + // "after 300 keys it stops" (2026-11-28): keys that are spent run on until they are gone. + private static void ChestSpentKeysPastMaxCycles() + { + const int uses = ChestKeyLooter.MaxCycles + 50; + var env = NewChest(out var ck); + env.Keys.Clear(); env.Keys.Add(11); + env.AutoLootMs = 300; + // ACE's one two-line message per unlock: "The X has been unlocked.\nYour key has N uses left." + int left = uses; + env.OnKey = key => + { + left--; + ck.OnChat(left > 0 ? $"The Mana Forge Chest has been unlocked.\nYour key has {left} use{(left == 1 ? "" : "s")} left." : "The Mana Forge Chest has been unlocked.\nYour key is used up."); + if (left <= 0) env.Keys.Remove(key); + env.Locked = false; + return 0u; + }; + env.OnOpen = () => true; + ck.RelockWaitSec = 1; + ck.Start(out _); + env.Run(3000, () => env.LootStarts > 0); + Check.Eq(ck.UsesLeft, uses - 1, "the uses-left line inside the two-line message is read (" + ck.UsesLeft + ")"); + env.Run(60_000_000, () => !ck.Running); + Check.False(ck.Running, "ended"); + Check.Eq(ck.Looted, uses, $"all {uses} uses looted, past {ChestKeyLooter.MaxCycles}"); + Check.True(Said(env).Contains($"out of keys after {uses} chest(s)"), "ends out of keys: " + Said(env).Substring(Math.Max(0, Said(env).Length - 200))); + + // A key that is used up and replaced by another of the same name counts as spent too, even with no chat line. + var e2 = NewChest(out var c2); + e2.Keys.Clear(); + for (int k = 0; k < ChestKeyLooter.MaxCycles + 20; k++) e2.Keys.Add(100 + k); + c2.SetKey(100, "Aged Key"); + e2.AutoLootMs = 300; + e2.OnKey = key => { e2.Keys.Remove(key); return 0u; }; // one use per key, no chat + c2.RelockWaitSec = 1; + c2.Start(out _); + e2.Run(60_000_000, () => !c2.Running); + Check.Eq(c2.Looted, ChestKeyLooter.MaxCycles + 20, "one-use keys with no chat line: every key used, past the cap"); + } + + // 2026-11-28: a chest that re-locks as it closes is keyed again as soon as the client sees that, + // whatever the wait (the server's Locked=false on the unlock, Locked=true on the reset). + private static void ChestRelockSeenGoesAtOnce() + { + var env = NewChest(out var ck); + env.Unlimited = true; + env.AutoLootMs = 1000; + env.ShownOpen = false; + env.RelockOnClose = true; + var keyAt = new List(); + env.Locked = true; + env.OnKey = _ => { keyAt.Add(env.T); env.Locked = false; return 0u; }; // the unlock's Locked=false + ck.Start(out _); + Check.Eq(ck.RelockWaitSec, ChestKeyLooter.DefaultRelockWaitSec, "the default 125 s wait"); + env.Run(5000, () => ck.State == ChestKeyLooter.Phase.Waiting); + Check.Eq(ck.State, ChestKeyLooter.Phase.Waiting, "looted, waiting"); + long lootDone = env.T; + env.Run(10_000, () => keyAt.Count >= 2); + Check.Eq(keyAt.Count, 2, "the next key went"); + Check.True(env.T - lootDone < 1_000, $"within a second of the re-lock, not 125 s ({env.T - lootDone} ms)"); + Check.True(env.Logs.Any(l => l.Contains("re-locked")), "the re-lock is logged"); + Check.True(ck.RelockSeen, "the run knows the chest re-locks as it closes (the panel hides the wait)"); + Check.Eq(env.Said.Count(s => s.Contains("re-locks as it closes")), 1, "said in chat once"); + env.Run(5000, () => ck.State == ChestKeyLooter.Phase.Waiting); + Check.True(ck.Status.Contains("it re-locks as it closes") && !ck.Status.Contains(" s) -"), "no countdown in the status: " + ck.Status); + + // A whole cycle on such a chest takes ~the loot time plus a little, not the 5 s floor of before. + env.Run(60_000, () => keyAt.Count >= 12); + long per = (keyAt[11] - keyAt[1]) / 10; + Check.True(per < 3_000, $"a cycle takes {per} ms (loot 1 s + open + settle)"); + + // The re-lock waits for the close: shown open, the key does not go. + var e2 = NewChest(out var c2); + e2.Unlimited = true; e2.AutoLootMs = 1000; e2.ShownOpen = true; + int keys2 = 0; + e2.OnKey = _ => { keys2++; e2.Locked = false; return 0u; }; + c2.Start(out _); + e2.Run(5000, () => c2.State == ChestKeyLooter.Phase.Waiting); + e2.Locked = true; + e2.Run(1_500); + Check.Eq(keys2, 1, "the client still shows the chest open: no key yet"); + e2.ShownOpen = false; + e2.Run(2_000, () => keys2 >= 2); + Check.Eq(keys2, 2, "shown closed: it goes"); + + // A locked read never preceded by an unlocked one (stale) does not cut the wait short. + var e3 = NewChest(out var c3); + e3.Unlimited = true; e3.AutoLootMs = 1000; e3.ShownOpen = false; e3.Locked = true; + int keys3 = 0; + e3.OnKey = _ => { keys3++; return 0u; }; // no Locked=false ever arrives + c3.Start(out _); + e3.Run(5000, () => c3.State == ChestKeyLooter.Phase.Waiting); + e3.Run(ChestKeyLooter.MinRelockMs - 3000); + Check.Eq(keys3, 1, "a stale locked read: no key before MinRelockMs"); + } + + // "after a certain amount of time it stops picking up items, chest opens, but items don't get picked up" (2026-11-28). + private static void ChestStopsWhenNothingTaken() + { + var env = NewChest(out var ck); + env.Unlimited = true; + env.AutoLootMs = 300; + Serve(env, ck, spendKey: false); + int chest = 0; + env.Tally = () => chest switch { 1 => (2, 1), 2 => (0, 0), _ => (2, 0) }; // 1: took 1 of 2; 2: nothing wanted; then: wanted, none taken + env.OnOpen = () => { chest++; return true; }; + ck.RelockWaitSec = 1; + ck.Start(out _); + env.Run(600_000, () => !ck.Running); + Check.False(ck.Running, "stopped"); + Check.Eq(ck.Looted, 2 + ChestKeyLooter.MaxStarvedChests, $"after {ChestKeyLooter.MaxStarvedChests} chests in a row with wanted loot and none taken"); + string said = Said(env); + Check.True(said.Contains("none of it could be picked up") && said.Contains("Olthoi Breastplate") && said.Contains("no more keys spent"), "says why and names the item: " + said); + Check.True(said.Contains("took 1 of 2 wanted"), "each chest says what it took: " + said); + + // One chest that gives something resets the count. + var e2 = NewChest(out var c2); + e2.Unlimited = true; e2.AutoLootMs = 300; + Serve(e2, c2, spendKey: false); + int n2 = 0; + e2.Tally = () => n2 % 2 == 0 ? (1, 1) : (1, 0); // every other chest gives nothing + e2.OnOpen = () => { n2++; return true; }; + c2.RelockWaitSec = 1; + c2.Start(out _); + e2.Run(200_000, () => c2.Looted >= 20 || !c2.Running); + Check.True(c2.Running && c2.Looted >= 20, $"no {ChestKeyLooter.MaxStarvedChests} in a row: it keeps going ({c2.Looted})"); + c2.Stop(); } /// Runs one cycle on two same-named keys and returns how long after the open the second key went. - private static long NextKeyAfterOpen(int relockSec, Action? duringWait = null) + private static long NextKeyAfterOpen(int relockSec, Action? duringWait = null, bool? shownOpen = null) { var env = NewChest(out var ck); + env.ShownOpen = shownOpen; env.Keys.Clear(); env.Keys.Add(11); env.Keys.Add(12); Serve(env, ck); env.AutoLootMs = 1000; @@ -482,10 +638,10 @@ internal static class ItemToolTests NewChest(out var c0); Check.Eq(c0.RelockWaitSec, ChestKeyLooter.DefaultRelockWaitSec, "default 125 s (the wait before the setting)"); Check.Eq(ChestKeyLooter.RegenWaitMs, 125_000L, "the default is the old wait"); - c0.RelockWaitSec = 1; - Check.Eq(c0.RelockWaitSec, ChestKeyLooter.MinRelockWaitSec, "1 s is raised to the least, 5 s"); + c0.RelockWaitSec = 0; + Check.Eq(c0.RelockWaitSec, ChestKeyLooter.MinRelockWaitSec, "0 s is raised to the least, 1 s"); c0.RelockWaitSec = -40; - Check.Eq(c0.RelockWaitSec, 5, "a negative value too"); + Check.Eq(c0.RelockWaitSec, 1, "a negative value too"); c0.RelockWaitSec = 100_000; Check.Eq(c0.RelockWaitSec, ChestKeyLooter.MaxRelockWaitSec, "100000 s is cut to the most, 600 s"); Check.Eq(ChestKeyLooter.ClampRelockWaitSec(45), 45, "in range: kept"); @@ -497,8 +653,15 @@ internal static class ItemToolTests Check.True(at >= 125_000 && at < 127_000, $"default: ~125 s after the open, as before ({at} ms)"); at = NextKeyAfterOpen(5); Check.True(at >= 5_000 && at < 7_000, $"5 s: ~5 s after the open ({at} ms)"); + // 1 s: the loot (1 s here) ends after that; with no close seen the old 2 s after the loot holds. at = NextKeyAfterOpen(1); - Check.True(at >= 5_000, $"1 s is used as 5 s ({at} ms)"); + Check.True(at >= 1_000 + ChestKeyLooter.AfterLootMaxMs && at < 1_000 + ChestKeyLooter.AfterLootMaxMs + 1_500, $"1 s, close not seen: ~2 s after the loot ({at} ms)"); + // ... and with the close seen (the client shows the chest shut at once), CloseSettleMs after it. + at = NextKeyAfterOpen(1, (env, _) => { }, shownOpen: false); + Check.True(at >= 1_000 + ChestKeyLooter.CloseSettleMs && at < 1_000 + ChestKeyLooter.CloseSettleMs + 1_000, $"1 s, close seen: ~{ChestKeyLooter.CloseSettleMs} ms after the loot ({at} ms)"); + // A close that isn't seen in time: AfterLootMaxMs still ends the wait. + at = NextKeyAfterOpen(1, (env, _) => { }, shownOpen: true); + Check.True(at >= 1_000 + ChestKeyLooter.AfterLootMaxMs && at < 1_000 + ChestKeyLooter.AfterLootMaxMs + 1_500, $"1 s, the client still shows it open: ~2 s after the loot ({at} ms)"); // Changed while the wait runs (the panel, mid-run): the running wait follows. at = NextKeyAfterOpen(ChestKeyLooter.DefaultRelockWaitSec, (env, ck) => { env.Run(10_000); ck.RelockWaitSec = 30; }); @@ -509,7 +672,7 @@ internal static class ItemToolTests private static void ChestRelockProbes() { - foreach (int sec in new[] { 20, 5, ChestKeyLooter.DefaultRelockWaitSec }) + foreach (int sec in new[] { 20, 5, 1, ChestKeyLooter.DefaultRelockWaitSec }) { var env = NewChest(out var ck); env.Unlimited = true; @@ -529,7 +692,7 @@ internal static class ItemToolTests Check.Eq(keyAt.Count, 1 + limit + 1, $"{sec} s: bounded: the first use, the one after the wait, one per ask"); for (int i = 2; i < keyAt.Count; i++) Check.True(keyAt[i] - keyAt[i - 1] >= every, $"{sec} s: ask {i} came {keyAt[i] - keyAt[i - 1]} ms after the last (at least {every})"); - Check.True(keyAt.Zip(keyAt.Skip(1), (a, b) => b - a).All(d => d >= ChestKeyLooter.MinProbeMs), $"{sec} s: never two key uses under 5 s apart"); + Check.True(keyAt.Skip(1).Zip(keyAt.Skip(2), (a, b) => b - a).All(d => d >= ChestKeyLooter.MinProbeMs), $"{sec} s: never two asks under 5 s apart"); Check.Eq(env.Sent.Count(s => s == "open"), 1, $"{sec} s: the empty chest is not opened again"); Check.True(Said(env).Contains("hasn't re-locked"), $"{sec} s: says why: " + Said(env)); } @@ -582,12 +745,15 @@ internal static class ItemToolTests left = Items.Contains(itemId) ? (Counts.TryGetValue(itemId, out int c) ? c : 1) : 0; return !Items.Contains(itemId) || left < count; } - public bool Send(int itemId, int targetId) + public readonly List Amounts = new(); // each give's amount (0 = the whole object) + public int PendingAmount; + public bool Send(int itemId, int targetId, int amount) { Sent.Add((T, itemId)); + Amounts.Add(amount); if (Silent) return true; if (Refuses.Contains(itemId)) { Refusals++; return true; } - PendingLand = itemId; LandAt = T + LandMs; + PendingLand = itemId; PendingAmount = amount; LandAt = T + LandMs; return true; } public int RefusalSeq() => Refusals; @@ -602,7 +768,9 @@ internal static class ItemToolTests T += 50; if (PendingLand != 0 && T >= LandAt) { - if (TakesOneAtATime && Counts.TryGetValue(PendingLand, out int c) && c > 1) Counts[PendingLand] = c - 1; + int have = Counts.TryGetValue(PendingLand, out int c) ? c : 1; + int take = TakesOneAtATime ? 1 : PendingAmount > 0 ? PendingAmount : have; // a split give takes its amount + if (take < have) Counts[PendingLand] = have - take; else Items.Remove(PendingLand); PendingLand = 0; } @@ -712,6 +880,131 @@ internal static class ItemToolTests Check.False(q2.Running, "Stop always works"); } + // ── Amount and Every (2026-11-27; spotted by SilentKelpie, Forgejo rynth PR #12) ── + + private static void GiveAmountSplits() + { + var env = NewGive(out var qg); + env.Items.Clear(); env.Items.AddRange(new[] { 1, 2 }); + env.Counts[1] = 3; env.Counts[2] = 50; + qg.SetAmount(20); + Check.True(qg.Start(out _), "starts"); + Check.True(env.Said[0].Contains("20 of 'Mana Mote'"), "the start line says the amount: " + env.Said[0]); + env.Run(30_000, () => !qg.Running); + Check.Eq(string.Join(",", env.Sent.Select(s => s.Item)), "1,2", "the small stack whole, then the big one"); + Check.Eq(string.Join(",", env.Amounts), "0,17", "the 3-stack goes whole (amount 0); 17 split off the 50"); + Check.Eq(qg.Units, 20, "20 units in all"); + Check.Eq(env.Counts[2], 33, "33 stay in the pack"); + Check.True(env.Said.Last().Contains("gave 20"), "the round ends at the amount: " + env.Said.Last()); + Check.False(qg.Running, "one round (Every 0): done"); + + // Amount 0 is the old behaviour: every unit. + var e2 = NewGive(out var q2); + e2.Counts[2] = 5; + q2.Start(out _); + e2.Run(30_000, () => !q2.Running); + Check.Eq(q2.Units, 7, "Amount 0: everything (1 + 5 + 1)"); + Check.True(e2.Amounts.All(a => a == 0), "whole objects only"); + + Check.Eq(new QuickGive(new GiveEnv()).Amount, 0, "Amount starts at 0 (all)"); + q2.SetAmount(-5); Check.Eq(q2.Amount, 0, "clamped at 0"); + q2.SetAmount(int.MaxValue); Check.Eq(q2.Amount, QuickGive.MaxAmount, "clamped at the most"); + } + + private static void GiveAmountOnePerGive() + { + var env = NewGive(out var qg); + env.Items.Clear(); env.Items.Add(1); + env.Counts[1] = 10; + env.TakesOneAtATime = true; + qg.SetAmount(3); + qg.Start(out _); + env.Run(60_000, () => !qg.Running); + Check.Eq(qg.Units, 3, "three units, one a give"); + Check.Eq(env.Counts[1], 7, "seven left in the pack"); + Check.Eq(env.Sent.Count, 3, "three gives"); + } + + private static void GiveEveryRounds() + { + var env = NewGive(out var qg); + env.Items.Clear(); env.Items.Add(1); + env.Counts[1] = 10; + qg.SetAmount(2); + qg.SetEvery(30); + qg.Start(out _); + Check.True(env.Said[0].Contains("every 30 s until you stop it"), "the start line says it repeats: " + env.Said[0]); + env.Run(5_000); + Check.Eq(qg.Units, 2, "round 1: 2 units"); + Check.Eq(qg.State, QuickGive.Phase.Waiting, "then waits"); + Check.True(qg.Status.Contains("next round in"), "the status counts down: " + qg.Status); + Check.True(qg.NextRoundInMs > 20_000, "about 30 s to go"); + env.Run(30_000); + Check.Eq(qg.Units, 4, "round 2 after the interval"); + Check.Eq(qg.Rounds, 2, "two rounds"); + + // Between rounds: out of range holds the next one, it goes when the target is back. + env.Meters = 12; + env.Run(40_000); + Check.Eq(qg.Units, 4, "target 12 m away: no round"); + Check.True(qg.Running, "still running"); + Check.True(qg.Status.Contains("then waits"), "the status says why: " + qg.Status); + env.Meters = 2; + env.Run(3_000); + Check.Eq(qg.Units, 6, "back in range: the round goes"); + + // A fight holds it too. + env.Combat = true; + env.Run(40_000); + Check.Eq(qg.Units, 6, "in a fight: no round"); + env.Combat = false; + env.Run(3_000); + Check.Eq(qg.Units, 8, "after the fight: the round goes"); + + // None left: the run waits for more. + env.Items.Clear(); + env.Run(40_000); + Check.True(qg.Running, "none left: still running, waiting for more"); + Check.True(qg.Status.Contains("no 'Mana Mote' in your packs"), "says so: " + qg.Status); + env.Items.Add(5); env.Counts[5] = 4; + env.Run(3_000); + Check.Eq(qg.Units, 10, "new ones go in the next round"); + + qg.Stop("stopped by you"); + Check.False(qg.Running, "Stop ends it"); + Check.True(env.Said.Last().Contains("rounds"), "the result counts the rounds: " + env.Said.Last()); + + // Every with nothing carried still starts (the first round waits). + var e2 = NewGive(out var q2); + e2.Items.Clear(); + q2.SetEvery(10); + Check.True(q2.Start(out _), "Every set: starts with none carried"); + q2.SetEvery(0); + var e3 = NewGive(out var q3); + e3.Items.Clear(); + Check.False(q3.Start(out _), "Every 0: refused with none carried, as before"); + } + + private static void GiveEveryMidRound() + { + void Case(string name, Action change, bool runEnds) + { + var env = NewGive(out var qg); + env.Items.Clear(); env.Items.AddRange(Enumerable.Range(1, 30)); + qg.SetEvery(20); + qg.Start(out _); + env.Run(600); + change(env); + env.Run(5000); + Check.Eq(qg.Running, !runEnds, $"{name}: {(runEnds ? "the run ends" : "the run goes on")}"); + if (!runEnds) Check.Eq(qg.State, QuickGive.Phase.Waiting, $"{name}: the round ended, the next is due"); + } + Case("fight", e => e.Combat = true, runEnds: false); + Case("vanishes", e => e.Loaded = false, runEnds: false); + Case("moves away", e => e.Meters = 30, runEnds: false); + Case("renamed", e => e.TargetName = "Somebody Else", runEnds: true); + } + private static void GiveStartRefusals() { var env = NewGive(out var qg); @@ -819,7 +1112,7 @@ internal static class ItemToolTests } /// The player types / presses: a trusted command. - public void Cmd(string args) => P.QueueItemToolCommand(args, trusted: true); + public void Cmd(string args, bool trusted = true) => P.QueueItemToolCommand(args, trusted); } private static string ProfilePath(string name) @@ -882,6 +1175,49 @@ internal static class ItemToolTests private static string Chat() => string.Join(" | ", FakeHost.Chat); + private const uint SidePack = 0x80290200, JunkBase = 0x80291000, SideJunkBase = 0x80292000; + + /// The chest looter's room check with the main pack full and of a 24-slot side pack's slots used. + private static string? NoRoomWithFullMain(int sideUsed, bool mainFull = true) + { + BaseWorld(); + FakeHost.Names[SidePack] = "Backpack"; + FakeHost.ItemTypes[SidePack] = 0x200; + FakeHost.Ints[(SidePack, 6u)] = 24; // ItemsCapacity + FakeHost.Containers[SidePack] = Player; + var ids = new List { Chest, Key, Key2, Gem, SidePack }; + for (uint i = 0; i < (mainFull ? 102u : 50u); i++) + { + uint j = JunkBase + i; + FakeHost.Names[j] = $"Junk {i}"; FakeHost.ItemTypes[j] = 0x80; FakeHost.Containers[j] = Player; + ids.Add(j); + } + for (uint i = 0; i < sideUsed; i++) + { + uint j = SideJunkBase + i; + FakeHost.Names[j] = $"Side junk {i}"; FakeHost.ItemTypes[j] = 0x80; FakeHost.Containers[j] = SidePack; + ids.Add(j); + } + var bot = new Bot(FakeHost.Create(Player), ProfilePath("itemtool-chest.json"), ids.ToArray()); + bot.Cache.GetDirectInventory(forceRefresh: true); + bot.Call("EnsureItemTool"); + var env = (IChestKeyEnv)typeof(ChestKeyLooter).GetField("_env", Any)!.GetValue(bot.Get("_chestKey"))!; + return env.NoRoomReason(); + } + + // 2026-11-28: looting stopped with a full main pack although the side packs had room; it should + // fill the side packs (the looter makes room since e026c97c). + private static void PluginNoRoomOnlyWhenAllFull() + { + Check.Eq(NoRoomWithFullMain(0, mainFull: false), null, "room in the main pack: keys go"); + Check.Eq(NoRoomWithFullMain(0), null, "main pack full, an empty side pack: keys go (the looter moves one item to the side pack, then picks up)"); + Check.Eq(NoRoomWithFullMain(22), null, "2 side slots left: still goes"); + string? one = NoRoomWithFullMain(23); + Check.True(one != null && one.Contains("1 free slot(s) left in all your packs"), "1 slot left in all: held (looting keeps 2 for weapon swaps): " + one); + string? none = NoRoomWithFullMain(24); + Check.True(none != null && none.Contains("0 free slot(s)"), "every pack full: held: " + none); + } + private static void PluginChestRun() { BaseWorld(); @@ -1064,6 +1400,43 @@ internal static class ItemToolTests // ── Chest re-lock wait (the setting) ───────────────────────────────────── + private static void PluginGiveAmountEvery() + { + BaseWorld(); + var bot = MakeBot("itemtool-giveamount.json"); + string Run(string words, bool trusted = true) + { + FakeHost.Chat.Clear(); + bot.Cmd(words, trusted); + bot.Tick(); + return Chat(); + } + string said = Run("giveamount 20"); + var qg = bot.Get("_quickGive"); + Check.Eq(qg.Amount, 20, "giveamount 20"); + Check.True(said.Contains("gives 20 a round"), "answers: " + said); + said = Run("giveevery 45"); + Check.Eq(qg.EverySec, 45, "giveevery 45"); + Check.True(said.Contains("a round every 45 s"), "answers: " + said); + said = Run("giveamount"); + Check.True(said.Contains("Amount") && said.Contains("is 20"), "no number: says the value: " + said); + said = Run("giveevery soon"); + Check.Eq(qg.EverySec, 45, "not a number: unchanged"); + Check.True(said.Contains("'soon' isn't a number"), "says why: " + said); + said = Run("giveevery 999999"); + Check.Eq(qg.EverySec, QuickGive.MaxEverySec, "clamped to the most"); + Check.True(said.Contains("past the most"), "says it was clamped: " + said); + said = Run("giveamount 0", trusted: false); + Check.Eq(qg.Amount, 0, "a meta may set them (they only shape a give)"); + Check.True(said.Contains("every matching item"), "answers: " + said); + Run("giveevery 0"); + + string json = bot.P.BuildItemToolJson(); + Check.True(json.Contains("\"amount\":0") && json.Contains("\"everySec\":0") && json.Contains("\"amountMax\":" + QuickGive.MaxAmount) + && json.Contains("\"everyMax\":" + QuickGive.MaxEverySec) && json.Contains("\"rounds\":0") && json.Contains("\"nextInSec\":0"), + "the Item Tool panel's data carries Amount and Every: " + json); + } + private static void PluginRelockCommand() { BaseWorld(); @@ -1083,9 +1456,11 @@ internal static class ItemToolTests Check.True(said.Contains("re-lock wait = 30 s"), "answers with the value now: " + said); Check.Eq(bot.Get("_chestKey").RelockWaitSec, 30, "the looter has it"); + said = Run("relock 0"); + Check.Eq(bot.S.ChestRelockWaitSec, ChestKeyLooter.MinRelockWaitSec, "0 s is raised to 1 s"); + Check.True(said.Contains("re-lock wait = 1 s") && said.Contains("the least is 1 s"), "says it was clamped: " + said); said = Run("relock 2"); - Check.Eq(bot.S.ChestRelockWaitSec, ChestKeyLooter.MinRelockWaitSec, "2 s is raised to 5 s"); - Check.True(said.Contains("re-lock wait = 5 s") && said.Contains("the least is 5 s"), "says it was clamped: " + said); + Check.Eq(bot.S.ChestRelockWaitSec, 2, "2 s is kept (the least was 5 s until 2026-11-28)"); said = Run("chest relock 9999"); Check.Eq(bot.S.ChestRelockWaitSec, ChestKeyLooter.MaxRelockWaitSec, "'chest relock' works too; 9999 is cut to 600"); @@ -1099,13 +1474,25 @@ internal static class ItemToolTests Check.True(said.Contains("'soon' isn't a number") && said.Contains("still 45 s") && said.Contains("/ra itemtool relock "), "says why, the value and the usage: " + said); said = Run("relock"); - Check.True(said.Contains("re-lock wait = 45 s") && said.Contains("5-600 s, default 125"), "no number: says the value and the range: " + said); + Check.True(said.Contains("re-lock wait = 45 s") && said.Contains("1-600 s, default 125"), "no number: says the value and the range: " + said); Check.Eq(bot.S.ChestRelockWaitSec, 45, "and changes nothing"); - // The panel reads it. + // The panel reads it (the engine's slider takes its least from relockMin, never under 1). string json = bot.P.BuildItemToolJson(); - Check.True(json.Contains("\"relockSec\":45") && json.Contains("\"relockMin\":5") && json.Contains("\"relockMax\":600") && json.Contains("\"relockReady\":true"), + Check.True(json.Contains("\"relockSec\":45") && json.Contains("\"relockMin\":1") && json.Contains("\"relockMax\":600") && json.Contains("\"relockReady\":true"), "the Item Tool panel's data carries the setting: " + json); + Check.True(json.Contains("\"relockSeen\":false"), "no run has seen a re-lock"); + + // A running looter that saw the chest re-lock as it closes: the panel's wait control goes + // (relockSec 0 hides it), the setting itself is kept. + var ck = bot.Get("_chestKey"); + typeof(ChestKeyLooter).GetField("k__BackingField", Any)!.SetValue(ck, ChestKeyLooter.Phase.Waiting); + typeof(ChestKeyLooter).GetField("k__BackingField", Any)!.SetValue(ck, true); + json = bot.P.BuildItemToolJson(); + Check.True(json.Contains("\"relockSec\":0,") && json.Contains("\"relockSeen\":true"), "re-lock seen while running: the control is hidden: " + json); + Check.Eq(bot.S.ChestRelockWaitSec, 45, "the setting is unchanged"); + typeof(ChestKeyLooter).GetField("k__BackingField", Any)!.SetValue(ck, ChestKeyLooter.Phase.Idle); + Check.True(bot.P.BuildItemToolJson().Contains("\"relockSec\":45"), "stopped: the control is back"); // The wait the running looter uses is the setting's (the tick hands it over). bot.S.ChestRelockWaitSec = 77; @@ -1141,7 +1528,7 @@ internal static class ItemToolTests Check.Eq(dst.ChestRelockWaitSec, 125, "an old profile loads 125 s"); var edited = JsonSerializer.Deserialize("{\"ChestRelockWaitSec\":0}", RynthAiJsonContext.Default.LegacyUiSettings)!; copy.Invoke(null, new object[] { edited, dst }); - Check.Eq(dst.ChestRelockWaitSec, ChestKeyLooter.MinRelockWaitSec, "a hand-edited 0 loads as 5 s"); + Check.Eq(dst.ChestRelockWaitSec, ChestKeyLooter.MinRelockWaitSec, "a hand-edited 0 loads as 1 s"); // The engine's settings payload: carries it; an engine that has no row for it leaves it alone. var payload = JsonSerializer.Deserialize("{\"PatrolOnLogin\":false}", RynthAiJsonContext.Default.SettingsBridgePayload); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/LootCorpseTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/LootCorpseTests.cs index 984b3db..7e201d6 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/LootCorpseTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/LootCorpseTests.cs @@ -47,6 +47,8 @@ internal static class LootCorpseTests r.Add("loot chain: 'My Kills Only' loots your kill and skips another player's", OwnershipModes); r.Add("loot chain: an item the cache never saw created is found in the corpse's contents and looted", UnseenItemRescued); r.Add("loot chain: without GetContainerContents an unseen item stays unseen (no crash)", UnseenItemOldEngine); + r.Add("loot chain: an item the client lists but can't read yet holds the finish, and is looted once it reads", UnreadItemHoldsFinish); + r.Add("loot chain: an item that never reads holds the finish only UnreadContentsWaitMs", UnreadItemHoldIsCapped); r.Add("loot starvation: a corpse waiting behind far-off combat gets a turn, a close monster keeps combat", LootStarvation); r.Add("loot starvation (R-20261115-165857-1de7): a starved open waits for combat's first attack at a fresh lock, at most 3 s", StarvedOpenWaitsForFirstAttack); r.Add("loot logging: a corpse held by combat is logged once, with the reason", HeldByCombatLoggedOnce); @@ -295,6 +297,63 @@ internal static class LootCorpseTests Check.True(FakeHost.ExternalMoves.Contains((Gem, Player, 0)), "the unseen gem is looted"); } + // A corpse finished 130 ms after it opened, from the items the cache already had: the second item the + // client listed in it couldn't be read yet, so it was never judged and was left behind. + private static Bot CorpseWithUnreadItem() + { + BaseWorld(corpsePositioned: true); + FakeHost.ContentsCalls = true; + FakeHost.Ints[(Gem, 11)] = 100; FakeHost.Ints[(Gem, 12)] = 1; + FakeHost.Containers[Gem2] = Corpse; // listed in the corpse, no name or position yet + var host = FakeHost.Create(Player); + var bot = new Bot(host); + bot.S.LootCorpseTimeoutMs = 60_000; + bot.Cache.OnCreateObject(Corpse); + bot.Cache.Tick(); + bot.Tick(BotActivity.Looting); + bot.Cache.OnCreateObject(Gem); // the cache has the first gem only + bot.Cache.Tick(); + FakeHost.GroundContainer = Corpse; + bot.P.OnViewObjectContents(Corpse); + return bot; + } + + private static bool CorpseFinished(Bot bot) => + bot.Get>("_completedCorpses").ContainsKey(unchecked((int)Corpse)); + + private static void UnreadItemHoldsFinish() + { + var bot = CorpseWithUnreadItem(); + LootWithMerges(bot, 2000, wantMoves: 99); // past the empty-corpse wait, short of the hold's cap + Check.True(FakeHost.ExternalMoves.Any(m => m.Id == Gem), "the gem the cache had is looted"); + Check.False(CorpseFinished(bot), "not finished while the client lists an item that can't be read"); + Check.True(FakeHost.Logs.Any(l => l.Contains("can't be read yet")), "the hold is logged"); + + FakeHost.Names[Gem2] = "Black Opal"; + FakeHost.ItemTypes[Gem2] = ItemTypeGem; + FakeHost.Appraised.Add(Gem2); + FakeHost.Ints[(Gem2, 11)] = 100; FakeHost.Ints[(Gem2, 12)] = 1; + LootWithMerges(bot, 3000, wantMoves: 2); + Check.True(FakeHost.ExternalMoves.Any(m => m.Id == Gem2), "once it reads, it is found and looted"); + Check.True(FakeHost.Logs.Any(l => l.Contains("the object cache had missed") && l.Contains($"0x{Gem2:X8}")), "the rescue names it"); + } + + private static void UnreadItemHoldIsCapped() + { + var bot = CorpseWithUnreadItem(); + long start = Environment.TickCount64; + while (!CorpseFinished(bot) && Environment.TickCount64 - start < 6000) + { + foreach (var m in FakeHost.ExternalMoves) FakeHost.Containers[m.Id] = 0; + bot.Tick(BotActivity.Looting); + Thread.Sleep(10); + } + long took = Environment.TickCount64 - start; + long cap = RynthAiPlugin.UnreadContentsWaitMs; + Check.True(CorpseFinished(bot), "the corpse is finished in the end"); + Check.True(took >= cap - 200 && took < cap + 2000, $"after about {cap} ms (took {took} ms)"); + } + private static void UnseenItemOldEngine() { BaseWorld(corpsePositioned: true); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/LootRetryTimingTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/LootRetryTimingTests.cs index a074b80..a0f1de0 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/LootRetryTimingTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/LootRetryTimingTests.cs @@ -44,6 +44,7 @@ internal static class LootRetryTimingTests r.Add("loot retry (R-20261029-122319-321f): a full main pack's refusals after the pickup count as tries (no free resends); a second item refused there keeps it marked full; nothing goes to a side pack", FullMainPackRefusals); r.Add("loot retry (R-20261029-122319-321f): unanswered moves are retried only after the answer wait, three tries, then given up (no side-pack round); their pack marks end with the item, the next item starts fresh", UnansweredMovesDontPoison); r.Add("loot pickup, main pack full (2026-11-12 'You must first pick up the Silver Pea'): a pea joins the stack you carry, a gem is left at once with one chat line, nothing is aimed at a side pack, the corpse completes", FullMainPackPeaJoinsGemLeft); + r.Add("loot pickup, main pack full, a side pack with room (2026-11-28): one main-pack item moves to the side pack per pickup (loot it brought in first), the pickup waits for that move's answer, every gem lands in the main pack, nothing is left", FullMainPackMakesRoom); r.Add("loot retry (R-20261029-122319-321f): an item that lands late, after its pack was given up on, un-marks that pack", LateLandingUnmarks); r.Add("loot retry (R-20261029-122319-321f): a refusal on arrival is 'too busy' (free resend), one after the pickup is the pack's answer", RefusalTiming); r.Add("loot retry (R-20261029-122319-321f): the answer wait grows with the server's measured answers, within 4-8 s", AnswerWaitAdapts); @@ -114,6 +115,7 @@ internal static class LootRetryTimingTests LootContentSettleMs = 0, LootEmptyCorpseMs = 0, StopLootingWhenPackFull = false, }; public readonly WorldObjectCache Cache; + public readonly RynthCoreHost Host; public SlowAce? Sim; public BotActivity Activity = BotActivity.Looting; // what the arbiter gave the tick @@ -124,6 +126,7 @@ internal static class LootRetryTimingTests typeof(LegacyDashboardRenderer).GetField("_profileLoaded", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!.SetValue(dash, true); // a stand-in with its profile in memory typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S); Set("_dashboard", dash); + Host = host; Cache = new WorldObjectCache(host); Cache.SetPlayerId(Player); Set("_objectCache", Cache); @@ -200,6 +203,9 @@ internal static class LootRetryTimingTests public long ClientPendingTimeoutMs = 10_000; public int TooBusy, LocalRefused, Queued, RoomRefusals; public readonly List<(uint Id, uint Pack, long At)> Landed = new(); + /// Pack-to-pack moves (MoveItemInternal) the server carried out: they take the client's one pending request too. + public readonly List<(uint Id, uint Pack, long At)> PackMoves = new(); + private int _seenPackMoves; private enum St { Idle, Pickup, Return } private St _st; @@ -231,6 +237,24 @@ internal static class LootRetryTimingTests if (Lag.Remove(m.Id, out long lag)) arrive += lag; At(arrive, () => Receive(m.Id, m.Target, arrive)); } + while (_seenPackMoves < FakeHost.Moves.Count) + { + var m = FakeHost.Moves[_seenPackMoves++]; + if (_clientPending != 0 && now - _clientPendingAt >= ClientPendingTimeoutMs) _clientPending = 0; + if (_clientPending != 0) { LocalRefused++; continue; } + _clientPending = m.Id; + _clientPendingAt = now; + long done = now - TickMs + Rtt; + At(done, () => + { + uint from = FakeHost.Containers.TryGetValue(m.Id, out uint c) ? c : 0; + FakeHost.Containers[m.Id] = m.Pack; + if (Room.TryGetValue(from, out int freeFrom)) Room[from] = freeFrom + 1; + if (Room.TryGetValue(m.Pack, out int freeTo)) Room[m.Pack] = freeTo - 1; + PackMoves.Add((m.Id, m.Pack, done)); + Answered(m.Id); + }); + } while (true) { var due = _events.Where(e => e.At <= now).OrderBy(e => e.At).ThenBy(e => e.Seq).ToList(); @@ -483,6 +507,59 @@ internal static class LootRetryTimingTests Check.True(_now - started < 10_000, $"quickly ({_now - started} ms), not after 3 + 3 tries per item"); }); + // ── 3c. A full main pack, room in a side pack (2026-11-28) ──────────────── + // "Why does Rynth stop looting when the main pack is full? It should continue looting and fill the + // side packs." Since 3b every item that joined no stack was left once the main pack was full, side + // packs empty or not. Now the looter first moves one loose item from the main pack to the side pack + // (a pack-to-pack move, which the client sends), waits for its answer (the client refuses a pickup + // while it is out), then picks the item up into the freed slot. 3b runs with no inventory manager, + // so it still shows what happens when no room move can be made. + + private static void FullMainPackMakesRoom() => Clocked(() => + { + const uint G1 = 0x80263181, G2 = 0x80263182, G3 = 0x80263183, JunkBase = 0x80264100; + World(sidePack: true, G1, G2, G3); + var ids = new List { G1, G2, G3 }; + for (uint i = 0; i < 102; i++) // a full main pack + { + uint j = JunkBase + i; + FakeHost.Names[j] = $"Junk {i}"; + FakeHost.ItemTypes[j] = 0x80; + FakeHost.Containers[j] = Player; + ids.Add(j); + } + var oldClock = RynthClock.TestNow; + var t0 = new DateTime(2026, 11, 28, 12, 0, 0); + RynthClock.TestNow = () => t0.AddMilliseconds(_now); + try + { + var sim = new SlowAce(); + sim.Room[Player] = 0; // the server's main pack is full too + var bot = Open(sim, sidePack: true, ids.ToArray()); + bot.Set("_inventoryManager", new RynthCore.Plugin.RynthAi.Loot.InventoryManager(bot.Host, bot.S, bot.Cache)); + + long started = _now; + Run(bot, () => bot.Completed, 60_000); + + foreach (uint g in new[] { G1, G2, G3 }) + Check.True(sim.Landed.Any(l => l.Id == g && l.Pack == Player), $"0x{g:X8} is looted into the main pack"); + Check.True(FakeHost.ExternalMoves.All(m => m.Target == Player), "every pickup is aimed at the main pack"); + Check.Eq(FakeHost.Moves.Count, 3, "one room move per gem"); + Check.True(FakeHost.Moves.All(m => m.Pack == SidePack), "each into the side pack"); + Check.Eq(sim.PackMoves.Count, 3, "and the server carries each out"); + Check.Eq(FakeHost.Moves[0].Id, JunkBase + 101, "the first room move takes the newest loose item (nothing looted yet)"); + Check.Eq(FakeHost.Moves[1].Id, sim.Landed[0].Id, "the next takes the loot just brought in"); + Check.Eq(sim.LocalRefused, 0, "no pickup goes out while a room move has no answer"); + Check.Eq(sim.RoomRefusals, 0, "and the server refuses none for room"); + Check.False(Logged("leaving 'Gem"), "nothing is left on the corpse"); + Check.Eq(FakeHost.Chat.Count(c => c.Contains("Main pack full")), 0, "no main-pack-full chat line"); + Check.True(Logged("the main pack is full: moving"), "the log says why each room move went"); + Check.True(bot.Completed, "the corpse completes"); + Check.True(_now - started < 20_000, $"in good time ({_now - started} ms)"); + } + finally { RynthClock.TestNow = oldClock; } + }); + // ── 4. A late landing ───────────────────────────────────────────────────── private static void LateLandingUnmarks() => Clocked(() => diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/LootRuleMatchTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/LootRuleMatchTests.cs index 59d4768..0860a1c 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/LootRuleMatchTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/LootRuleMatchTests.cs @@ -34,10 +34,36 @@ internal static class LootRuleMatchTests r.Add("loot rule match: double keys compare as floats (1.20 + 0.09 >= 1.29)", FloatCompare); r.Add("loot rule match: tinked damage and tinked target melee (VTank's worked examples)", TinkedNodes); r.Add("loot rule match: which conditions need the ID", ConditionsNeedingId); + r.Add("loot rule match: ImbuedEffect tests see ImbuedEffect2-5 (303-306) too", ImbuesInLaterSlots); r.Add("loot rule match: Decide passes over a rule a known condition fails, in any order", DecideOrder); r.Add("loot rule match (R-20261101-133624-7eeb): a name rule 'Trade Note' first keeps none of a corpse's plain items, ID or not", TradeNoteRuleFirst); r.Add("loot rule match: /ra loot why lists the rules above that came close, with the value read", LootWhyExplains); r.Add("loot rule match: /ra loot why's words, in chat and in the 'Why this loot rule?' window", LootWhyReportWords); + r.Add("loot rule match: Slayer damage bonus (float 138) reads the weapon's text when the server sent none; a sent value wins", SlayerBonusFromText); + } + + // 2026-11-27 (spotted by SilentKelpie, Forgejo rynth PR #12): ACE never sends float 138; servers built on + // ACECustom write "- Shadow Slayer: 1.5x Damage" in the weapon's text. + private static void SlayerBonusFromText() + { + FakeHost.Reset(); + var rule = new VTankLootRule { Name = "Slayer weapons", Action = VTankLootAction.Keep, CustomExpression = string.Empty }; + rule.Conditions.Add(new VTankLootCondition(N.ObjectClass, "0", new[] { ((int)AcObjectClass.MeleeWeapon).ToString() })); + rule.Conditions.Add(new VTankLootCondition(N.DoubleValKeyGE, "0", new[] { "1.01", "138" })); + var profile = new VTankLootProfile { FileVersion = 1, Rules = { rule } }; + var ctx = Ctx(); + bool Keeps(Item i) => VTankLootEvaluator.FirstMatch(profile, i, ctx, out _) != null; + + var desc = new Item("Shadow Slayer Sword", AcObjectClass.MeleeWeapon).Int(166, 22).Str(16, "Property Details:\n- Shadow Slayer: 1.5x Damage"); + Check.True(Keeps(desc), "the bonus from the description: kept"); + Check.Near(desc.Wo.Values((DoubleValueKey)138, 0.0), 1.5, 1e-9, "the item reader gives 1.5"); + var use = new Item("Olthoi Slayer Axe", AcObjectClass.MeleeWeapon).Int(166, 1).Str(14, "Olthoi Slayer: 2x Damage"); + Check.True(Keeps(use), "the bonus from the use text: kept"); + var sent = new Item("Sent Bonus Mace", AcObjectClass.MeleeWeapon).Dbl(138, 1.0).Str(16, "- Shadow Slayer: 1.5x Damage"); + Check.False(Keeps(sent), "a sent 1.0 wins over the text's 1.5: left"); + var none = new Item("Plain Sword", AcObjectClass.MeleeWeapon).Str(16, "A fine blade."); + Check.False(Keeps(none), "no bonus anywhere: left"); + Check.Near(none.Wo.Values((DoubleValueKey)138, -1.0), -1.0, 1e-9, "no bonus: the caller's default"); } private static VTankLootProfile Excerpt() @@ -204,6 +230,23 @@ internal static class LootRuleMatchTests Check.True(VTankLootEvaluator.Match(new VTankLootRule { Conditions = { C(N.CalcedBuffedTinkedTargetMeleeGE, "109", "1.17", "1.17") } }, mace), "an 80 mace at 1.17/1.17 reaches 109"); } + // ACE keeps an item's second and later imbues in 303-306; a rule on 179 reads them all, ORed. + private static void ImbuesInLaterSlots() + { + FakeHost.Reset(); + static VTankLootCondition C(int node, params string[] data) => new(node, "0", data); + static VTankLootRule R(VTankLootCondition c) => new() { Conditions = { c } }; + var knife = new Item("Knife", AcObjectClass.MeleeWeapon).Int(179, 4).Int(303, 128); + Check.True(VTankLootEvaluator.Match(R(C(N.LongValKeyFlagExists, "128", "179")), knife), "has Cold Rending: the rend in ImbuedEffect2 counts"); + Check.True(VTankLootEvaluator.Match(R(C(N.LongValKeyFlagExists, "4", "179")), knife), "has Armor Rending: the first slot still counts"); + Check.False(VTankLootEvaluator.Match(R(C(N.LongValKeyFlagExists, "512", "179")), knife), "no Fire Rending on it"); + Check.True(VTankLootEvaluator.Match(R(C(N.LongValKeyE, "132", "179")), knife), "179 = both imbues ORed"); + Check.True(VTankLootEvaluator.Match(R(C(N.LongValKeyE, "128", "303")), knife), "303 on its own reads as itself"); + var plain = new Item("Knife", AcObjectClass.MeleeWeapon).Int(353, 6); + Check.False(VTankLootEvaluator.Match(R(C(N.LongValKeyGE, "1", "179")), plain), "an unimbued dagger has no imbue"); + Check.True(VTankLootEvaluator.Match(R(C(N.LongValKeyE, "6", "353")), plain), "353 is the weapon type (dagger)"); + } + private static void ConditionsNeedingId() { static VTankLootCondition C(int node, params string[] data) => new(node, "0", data); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/MeleeStallTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/MeleeStallTests.cs index cbfd101..1797477 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/MeleeStallTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/MeleeStallTests.cs @@ -24,6 +24,8 @@ internal static class MeleeStallTests r.Add("ghost: a swing, a move, a server message or another target means it is alive", GhostAlive); r.Add("ghost: skipped until the server updates or creates it, it moves, or the landblock changes", GhostTrackerClears); r.Add("ghost: combat skips a marked ghost, counts it in the lock line, and takes it back when the server updates it", GhostSkippedByCombat); + r.Add("ghost pack (R-20261127 bc02): silent monsters next to a ghost are skipped too, never removed; a heard-from or far one isn't", GhostPackSkipped); + r.Add("ghost pack (R-20261127 bc02): a suspect is real again on an update or a move, tried again after 3 min", GhostSuspectClears); r.Add("melee interval: the first swing at a new target doesn't wait out the old 1000 ms", PhysicalNewTargetInterval); r.Add("melee reach: no closer after the re-issue = out of reach, left longer each time", ReachVerdict); r.Add("melee reach: walking closer, next to it, or another target is not out of reach", ReachWorking); @@ -236,6 +238,73 @@ internal static class MeleeStallTests Check.True(c.ScannedTargets.Any(t => (uint)t.Id == ghost), "scanned again"); } + // ── Ghosts come in packs (R-20261127-183401-bc02) ───────────────────────────────────────── + // Five Butcherous Eaters 11 m down behind a hill, all ghosts: each cost 10-30 s of arrows into + // the hillside before it was caught. Now the silent ones next to a caught ghost go with it. + private static void GhostPackSkipped() + { + FakeHost.Reset(); + Place(Player, "Me", 96, 96, creature: false); + FakeHost.PlayerPose = (Lb | 0x0329, 96f, 96f, 0f); + uint ghost = 0xF08416EA, mate = 0xF043353B, mate2 = 0xF0841273, heard = 0xF0845E91, far = 0xF083C6E9; + Place(ghost, "Butcherous Eater", 96, 130f); + Place(mate, "Butcherous Eater", 99, 131f); // 3.2 m from it, silent 80 s + Place(mate2, "Butcherous Eater", 90, 128f); // 6.3 m, silent 65 s + Place(heard, "Butcherous Eater", 97, 133f); // 3.2 m, but the server spoke of it 5 s ago + Place(far, "Butcherous Eater", 96, 150f); // 20 m off, silent + var s = new LegacyUiSettings { MonsterRange = 60 }; + var host = FakeHost.Create(); + var cache = FakeHost.MakeCache(host, Player, new[] { ghost, mate, mate2, heard, far }); + var c = new CombatManager(host, s, cache); + c.SetPlayerId(Player); + c.SetDamageStores(null, new RynthCore.Plugin.RynthAi.CreatureData.MonsterDamageStore()); + DateTime now = RynthCore.Plugin.RynthAi.RynthClock.Now; + c.Ghosts.NoteServerUpdate((int)mate, now.AddSeconds(-80)); + c.Ghosts.NoteServerUpdate((int)mate2, now.AddSeconds(-65)); + c.Ghosts.NoteServerUpdate((int)heard, now.AddSeconds(-5)); + c.Ghosts.NoteServerUpdate((int)far, now.AddSeconds(-90)); + + c.MarkGhost((int)ghost, "Butcherous Eater", 65_000, "test"); + Check.True(c.Ghosts.IsGhost((int)mate) && c.Ghosts.IsSuspect((int)mate), "the silent one 3 m away: skipped as a suspect"); + Check.True(c.Ghosts.IsSuspect((int)mate2), "and the one 6 m away"); + Check.False(c.Ghosts.IsGhost((int)heard), "the server spoke of this one 5 s ago: not a suspect"); + Check.False(c.Ghosts.IsGhost((int)far), "20 m off: not part of the pack"); + Check.False(c.Ghosts.IsSuspect((int)ghost), "the caught one is a ghost, not a suspect"); + Check.True(FakeHost.Logs.Any(l => l.Contains("[Ghost] 2 more next to it") && l.Contains("0xF043353B") && l.Contains("not removed from the client")), + "one line names the two"); + + Thread.Sleep(80); + c.ScanNearbyTargets(); + Check.False(c.ScannedTargets.Any(t => (uint)t.Id == mate || (uint)t.Id == mate2), "suspects aren't scanned"); + Check.True(c.ScannedTargets.Any(t => (uint)t.Id == heard), "the heard-from one is"); + } + + private static void GhostSuspectClears() + { + var g = new GhostTracker(); + const uint Lb = 0xF864; + Check.True(g.MarkSuspect(5, "Butcherous Eater", Mob, Lb, T0), "marked"); + Check.False(g.MarkSuspect(5, "Butcherous Eater", Mob, Lb, T0), "once"); + g.NoteServerUpdate(5, T0.AddSeconds(10)); + Check.False(g.IsGhost(5), "a server update: real"); + + g.MarkSuspect(6, "Butcherous Eater", Mob, Lb, T0); + g.CheckMoved(id => new GhostSpot(Mob.X + 1, Mob.Y, Mob.Z)); + Check.False(g.IsGhost(6), "it moved: real"); + + g.MarkSuspect(7, "Butcherous Eater", Mob, Lb, T0); + g.Mark(8, "Butcherous Eater", Mob, Lb, T0); + g.ExpireSuspects(T0.AddMinutes(2)); + Check.True(g.IsGhost(7), "2 min: still skipped"); + g.ExpireSuspects(T0.AddMinutes(3).AddSeconds(1)); + Check.False(g.IsGhost(7), "3 min with no word: tried again"); + Check.True(g.IsGhost(8), "a caught ghost doesn't expire"); + + g.MarkSuspect(9, "Butcherous Eater", Mob, Lb, T0); + g.Mark(9, "Butcherous Eater", Mob, Lb, T0); + Check.False(g.IsSuspect(9), "caught after all: a ghost now"); + } + private static void Place(uint id, string name, float x, float y, bool creature = true) { FakeHost.Names[id] = name; diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/MetaSchedulerTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/MetaSchedulerTests.cs index e1f2dd6..e12efa0 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/MetaSchedulerTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/MetaSchedulerTests.cs @@ -105,6 +105,12 @@ internal static class MetaSchedulerTests MyQuestsLineKind.Quest, "underscores in the name"); Check.Eq(e.Name, "stipendtimer_monthly", "underscored name"); + // A space between the timestamp and the message (some servers send it so). + Check.Eq(MyQuestsParser.Parse("stipendtimer_monthly - 12 solves (1759276800) \"Monthly Stipend\" -1 2592000", out e), + MyQuestsLineKind.Quest, "a space after the timestamp"); + Check.Eq(e.Message, "Monthly Stipend", "message after the space"); + Check.Eq(e.MinDeltaSeconds, 2592000L, "delta after the space"); + // The message may hold quotes and the line may carry the client's trailing newline. Check.Eq(MyQuestsParser.Parse("taskmoarsmenartifactswait - 1 solves (1759000000)\"Bring \"artifacts\" to Kanji\" -1 72000\n", out e), MyQuestsLineKind.Quest, "quotes in the message, trailing newline"); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/NavEngineTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/NavEngineTests.cs index 400b671..63f111e 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/NavEngineTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/NavEngineTests.cs @@ -1,10 +1,12 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using RynthCore.Plugin.RynthAi; using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.RynthAi.Raycasting; using RynthCore.RynthAiHostTests.Fakes; using RynthCore.RynthAiTests.Harness; using T = RynthCore.Plugin.RynthAi.LegacyUi.NavPointType; @@ -39,10 +41,17 @@ internal static class NavEngineTests r.Add("nav engine: a recall that never fires, next waypoint close: moves on after 60 s", RecallTimeoutNear); r.Add("nav engine: macro start picks the nearest plain waypoint", ResumeNearest); r.Add("nav engine: indoors, macro start picks the nearest waypoint on foot, not through a wall", ResumeNearestByWalk); + r.Add("nav engine (11-27): indoors, macro start keeps the waypoint in your own room (no plan, a clear walk) over one a floor below", ResumeNearestOwnRoom); r.Add("nav engine: macro start skips a nearest waypoint already walked past, not one still ahead", ResumeNearestPassed); r.Add("nav engine: back from a pause that moved 10+ yd, nav heads for the closest waypoint", ResumeAfterPauseMoved); r.Add("nav engine: back from a pause that moved under 10 yd, nav keeps its waypoint", ResumeAfterPauseStill); r.Add("nav engine: the dungeon patrol keeps its waypoint after a pause that moved it (no closest-waypoint pick)", ResumeAfterPausePatrol); + r.Add("nav engine (11-28): back from a fight in a side room, the patrol's waypoint behind a wall: walks to the route in sight first, then on to it", InSightSideRoom); + r.Add("nav engine (11-28): back from a fight, a clear walk to the waypoint (or a map that can't say): nothing changes", InSightClearOrUnknown); + r.Add("nav engine (11-28): back from a fight, only the leg out of the waypoint in sight: goes on from there, passing over it", InSightAhead); + r.Add("nav engine (11-28): back from a fight, nothing of the route near in sight: the map's way to the waypoint", InSightNoneFallsBack); + r.Add("nav engine (11-28): a fight during the walk to the route in sight: looked at again from where it ends", InSightInterrupted); + r.Add("nav engine (11-28): Lugian Excavations 0x02E7 on the real dats: the patrol's legs are clear walks, the 18:56 wall stuck isn't, and the route in sight is found from there and from the rooms off the route (if the dats are here)", InSightLugianRealDats); r.Add("nav engine: Go To Closest Waypoint off keeps the last waypoint (hazard/corpse still rejoin)", ResumeNearestOff); r.Add("nav engine: a loaded route starts at [0] for Once/Follow, or for any route with the option off", StartsAtFirstPoint); r.Add("nav engine: nearest waypoint lookup", FindNearest); @@ -98,7 +107,7 @@ internal static class NavEngineTests public readonly FakePlanner? P; /// Call FakeHost.Reset() and At(...) first. - public Nav(NavRouteParser route, int idx = 0, FakePlanner? planner = null) + public Nav(NavRouteParser route, int idx = 0, FakePlanner? planner = null, INavRecoveryPlanner? other = null) { _now = 1_000_000; NavigationEngine.Clock = static () => _now; @@ -107,6 +116,7 @@ internal static class NavEngineTests E = new NavigationEngine(host, S); P = planner; if (planner != null) E.SetRecoveryPlanner(planner); + else if (other != null) E.SetRecoveryPlanner(other); } public void Tick(int ms = 40) { _now += ms; E.Tick(); } @@ -133,6 +143,24 @@ internal static class NavEngineTests /// Per-target walk length (yd); null = no path. Used instead of GivePlan when set. public Func? WalkYd; public readonly List PlanTargets = new(); + /// + /// Per-target walk for a waypoint in your own room with a clear walk (TryPlan has no plan for it): what the real + /// planner's WalkLengthYd answers there. Null = not in your room. + /// + public Func? InRoomYd; + /// The dungeon map's straight walk from where the fake character stands (null: the map can't say). + public Func? InSight; + /// Every StraightWalkInSight asked, with its answer. + public readonly List<(NavPoint Target, bool? Answer)> SightAsks = new(); + + public double? WalkLengthYd(NavPoint target) => TryPlan(target, out _)?.LengthYd ?? InRoomYd?.Invoke(target); + + public bool? StraightWalkInSight(NavPoint target) + { + bool? a = InSight?.Invoke(target); + SightAsks.Add((target, a)); + return a; + } public NavRecoveryPlan? TryPlan(NavPoint target, out string why) { @@ -559,6 +587,36 @@ internal static class NavEngineTests Check.Eq(blind.Idx, 1, "no position: untouched"); } + private static void ResumeNearestOwnRoom() + { + // Desert Mine 0x0182, 2026-11-27: [0] is beside you in your own room, where the planner has no plan (nothing + // to walk round); [2] is nearer on the map but a floor below, a 99 yd walk. The walk pick left [0] out and took + // [2] (reached at once from above, the bot then ran at the wall toward [3]). + FakeHost.Reset(); At(0, 0); + var pose = FakeHost.PlayerPose; + FakeHost.PlayerPose = ((pose.Cell & 0xFFFF0000) | 0x017B, pose.X, pose.Y, pose.Z); + var route = Route(RT.Circular, Pt(3, 0), Pt(200, 0), Pt(1, 0), Pt(8, 0), Pt(300, 0)); + Func walk = t => t.NS == route.Points[2].NS ? 99 : t.NS == route.Points[3].NS ? 110 : null; + Func room = t => t.NS == route.Points[0].NS ? 3 : null; + var nav = new Nav(route, idx: 0, planner: new FakePlanner { WalkYd = walk, InRoomYd = room }); + nav.E.ResumeFromNearestWaypoint(); + Check.Eq(nav.Idx, 0, "loaded at [0]: the waypoint in your own room (3 yd) stays over [2] a floor below (99 yd walk)"); + + // Old Mine 0x0190, 2026-11-26: the load's map pick put it a floor below ([2]); the macro start takes [0]. + FakeHost.Reset(); At(0, 0); + FakeHost.PlayerPose = ((pose.Cell & 0xFFFF0000) | 0x017B, pose.X, pose.Y, pose.Z); + var nav2 = new Nav(route, idx: 2, planner: new FakePlanner { WalkYd = walk, InRoomYd = room }); + nav2.E.ResumeFromNearestWaypoint(); + Check.Eq(nav2.Idx, 0, "loaded at [2] a floor below: the macro start moves it to [0] in your room"); + + // With nothing in your room the walks decide, as before. + FakeHost.Reset(); At(0, 0); + FakeHost.PlayerPose = ((pose.Cell & 0xFFFF0000) | 0x017B, pose.X, pose.Y, pose.Z); + var nav3 = new Nav(route, idx: 0, planner: new FakePlanner { WalkYd = walk }); + nav3.E.ResumeFromNearestWaypoint(); + Check.Eq(nav3.Idx, 2, "no waypoint in your room: the shortest walk ([2], 99 yd)"); + } + private static void ResumeNearestByWalk() { // In a dungeon cell: [2] is 5 yd away through a wall (a 300 yd walk), [1] (current) is @@ -649,6 +707,321 @@ internal static class NavEngineTests Check.Eq(LogCount("back from a pause"), 0, "nothing re-picked"); } + // ── Back to the route in sight (11-28) ─────────────────────────────────── + // Lugian Excavations, a melee patrol with Monster Range 20 m: after the fights nav steered straight at the patrol's + // waypoint behind a wall and ran into it. The dungeon map's straight-walk answer is faked here by walls on the plan. + + /// A fake dungeon map: the straight walk from the fake character to a point is clear unless it crosses one of + /// these walls ((north, east) yd, end to end). + private static Func Walls(params (double N0, double E0, double N1, double E1)[] walls) + => t => + { + var (tn, te) = NE(t); + foreach (var w in walls) + if (Crosses(_n, _e, tn, te, w.N0, w.E0, w.N1, w.E1)) return false; + return true; + }; + + private static bool Crosses(double ax, double ay, double bx, double by, double cx, double cy, double dx, double dy) + { + static double O(double ax, double ay, double bx, double by, double px, double py) => (bx - ax) * (py - ay) - (by - ay) * (px - ax); + return O(cx, cy, dx, dy, ax, ay) * O(cx, cy, dx, dy, bx, by) < 0 && O(ax, ay, bx, by, cx, cy) * O(ax, ay, bx, by, dx, dy) < 0; + } + + private static (double N, double E) NE(NavPoint p) => ((p.NS - NS0) * 240.0, (p.EW - EW0) * 240.0); + + /// A side room east of the Square's leg [1]→[2] (east 40, north 0..40): its west wall at east 44 with an + /// opening from north 18 to 22, its other walls at north 10, north 30 and east 60. + private static readonly (double, double, double, double)[] SideRoom = + { (10, 44, 18, 44), (22, 44, 30, 44), (30, 44, 30, 60), (10, 44, 10, 60), (10, 60, 30, 60) }; + + private static void InSightSideRoom() + { + FakeHost.Reset(); At(14, 40); // on the leg [1]->[2], heading for [2] + var p = new FakePlanner { InSight = Walls(SideRoom) }; + var nav = new Nav(Square(), idx: 2, planner: p); + nav.E.KeepWaypointAfterPause = () => true; // the dungeon patrol + nav.Tick(); + nav.E.Stop(); // a rock thrower in the side room + At(14, 52); // the fight ends in there: [2] is behind its north wall + nav.Run(1.0); + Check.Eq(LogCount("walking to the route in sight first"), 1, "one walk to the route in sight, said once"); + Check.True(nav.Recovery.Contains("via the route in sight") && nav.Recovery.Contains("-> [2]"), $"walking it, then [2] ({nav.Recovery})"); + Check.Eq(nav.Idx, 2, "the patrol's waypoint is kept meanwhile"); + Check.False(nav.S.NavIsStuck, "not shown as stuck"); + var spot = p.SightAsks.Last(a => a.Answer == true).Target; + var (sn, se) = NE(spot); + Check.True(Math.Abs(se - 40) < 0.01 && sn > 20 && sn < 26, $"the spot is on the leg into [2], seen through the opening ({sn:F1}, {se:F1})"); + Check.True(p.SightAsks.Count <= 41, $"at most 40 spots tried after the waypoint ({p.SightAsks.Count - 1})"); + + At(sn, se); // walked out through the opening + nav.Tick(); + Check.Eq(LogCount("rejoined the route at [2]"), 1, "back on the route, going on to [2]"); + Check.Eq(nav.Idx, 2, "on to [2]"); + Check.Eq(nav.Recovery, "none", "no recovery counted against [2]"); + } + + private static void InSightClearOrUnknown() + { + foreach (bool? answer in new bool?[] { true, null }) + { + FakeHost.Reset(); At(14, 40); + var p = new FakePlanner { InSight = _ => answer }; + var nav = new Nav(Square(), idx: 2, planner: p); + nav.E.KeepWaypointAfterPause = () => true; + nav.Tick(); + nav.E.Stop(); + At(14, 52); + nav.Run(1.0); + string what = answer == true ? "a clear walk" : "the map can't say"; + Check.Eq(p.SightAsks.Count, 1, $"{what}: only the waypoint asked about"); + Check.Eq(LogCount("back from a pause"), 0, $"{what}: nothing said"); + Check.Eq(nav.Recovery, "none", $"{what}: no walk"); + Check.Eq(nav.Idx, 2, $"{what}: on to [2] as before"); + } + + // A pause that hardly moved the character (half a yard): nothing between, nothing asked. + FakeHost.Reset(); At(14, 40); + var q = new FakePlanner { InSight = _ => false }; + var still = new Nav(Square(), idx: 2, planner: q); + still.Tick(); + still.E.Stop(); + At(14.5, 40); + still.Run(1.0); + Check.Eq(q.SightAsks.Count, 0, "a pause that moved under 1 yd: not asked"); + } + + private static void InSightAhead() + { + // The chase went on past [2] to the north-west: only the leg [2]->[3] (north 40, east 40 down to 0) is in sight. + FakeHost.Reset(); At(30, 40); + var p = new FakePlanner { InSight = t => { var (n, e) = NE(t); return Math.Abs(n - 40) < 0.01 && e < 39.99; } }; + var nav = new Nav(Square(), idx: 2, planner: p); + nav.E.KeepWaypointAfterPause = () => true; + nav.Tick(); + nav.E.Stop(); + At(46, 20); + nav.Run(1.0); + Check.Eq(LogCount("passing over [2]"), 1, "said: it passes over [2]"); + Check.True(nav.Recovery.Contains("-> [3]"), $"then [3] ({nav.Recovery})"); + var (sn, se) = NE(p.SightAsks.Last(a => a.Answer == true).Target); + // Nearest is (40, 20), 6 yd; (40, 25) is 7.8 yd but passes over 5 yd less of the route (half of it counts). + Check.True(Math.Abs(sn - 40) < 0.01 && se >= 20 && se <= 30, $"a spot on that leg near the character, passing over little ({sn:F1}, {se:F1})"); + At(sn, se); + nav.Tick(); + Check.Eq(nav.Idx, 3, "goes on from [3]"); + } + + private static void InSightNoneFallsBack() + { + FakeHost.Reset(); At(14, 40); + var p = new FakePlanner { InSight = _ => false, GivePlan = true }; + var nav = new Nav(Square(), idx: 2, planner: p); + nav.E.KeepWaypointAfterPause = () => true; + nav.Tick(); + nav.E.Stop(); + At(14, 52); + nav.Run(1.0); + Check.Eq(LogCount("no spot of the route near it in sight"), 1, "said: nothing in sight"); + Check.Eq(LogCount("started (back from a pause, [2] is behind a wall"), 1, "the map's way to [2] instead"); + Check.True(nav.Recovery.Contains("via fake planner"), $"walking it ({nav.Recovery})"); + + // And no way on the map either: as before (straight on, the stuck escapes if it sticks). + FakeHost.Reset(); At(14, 40); + var q = new FakePlanner { InSight = _ => false }; + var nav2 = new Nav(Square(), idx: 2, planner: q); + nav2.E.KeepWaypointAfterPause = () => true; + nav2.Tick(); + nav2.E.Stop(); + At(14, 52); + nav2.Run(1.0); + Check.Eq(LogCount("result: no plan"), 1, "no plan: said so"); + Check.Eq(nav2.Idx, 2, "still on to [2]"); + } + + private static void InSightInterrupted() + { + FakeHost.Reset(); At(14, 40); + var p = new FakePlanner { InSight = Walls(SideRoom) }; + var nav = new Nav(Square(), idx: 2, planner: p); + nav.E.KeepWaypointAfterPause = () => true; + nav.Tick(); + nav.E.Stop(); + At(14, 52); + nav.Run(1.0); + Check.Eq(LogCount("walking to the route in sight first"), 1, "the walk started"); + + // Another rock thrower before it gets out, fought where it stands: looked at again (still in the side room). + nav.E.Stop(); + nav.Run(1.0); + Check.Eq(LogCount("cancelled, another pause"), 1, "the walk was dropped for the fight"); + Check.Eq(LogCount("walking to the route in sight first"), 2, "and laid again from where the fight ended"); + + // A third fight that ends out on the leg: [2] is in sight from there, so no walk at all. + nav.E.Stop(); + At(30, 40); + nav.Run(1.0); + Check.Eq(LogCount("cancelled, another pause"), 2, "dropped again"); + Check.Eq(LogCount("walking to the route in sight first"), 2, "nothing new laid: [2] is in sight"); + Check.Eq(nav.Recovery, "none", "straight on to [2]"); + Check.Eq(nav.Idx, 2, "on to [2]"); + } + + // ── The same on the real map: Lugian Excavations (0x02E7) ─────────────── + + /// The dungeon patrol laid 2026-11-28 18:50:47 from cell 02E70285 (71 points; world x, y, z). + private static readonly (double X, double Y, double Z)[] LugianPatrol = + { + (401.5, 43802.0, 18.0), (404.0, 43804.5, 18.0), (404.0, 43849.5, 18.0), (406.5, 43852.0, 18.0), (513.0, 43852.0, 18.0), (524.0, 43863.0, 18.0), + (524.0, 43899.5, 18.0), (526.5, 43902.0, 18.0), (631.5, 43902.0, 12.0), (634.0, 43904.5, 12.0), (634.0, 43922.0, 12.0), (634.0, 43904.5, 12.0), + (636.5, 43902.0, 12.0), (703.0, 43902.0, 0.0), (724.0, 43907.0, 0.0), (744.0, 43927.0, 0.0), (734.0, 43957.0, 0.0), (739.0, 44012.0, 0.0), + (754.0, 44017.0, 0.0), (774.0, 44047.0, 0.0), (784.0, 44057.0, 0.0), (774.0, 44087.0, 0.0), (784.0, 44117.0, 0.0), (774.0, 44147.0, 0.0), + (784.0, 44177.0, 0.0), (814.0, 44187.0, 0.0), (824.0, 44197.0, 0.0), (824.0, 44217.0, 0.0), (844.0, 44237.0, 0.0), (834.0, 44267.0, 0.0), + (845.0, 44312.0, 0.0), (854.0, 44312.0, 0.0), (845.0, 44312.0, 0.0), (834.0, 44267.0, 0.0), (844.0, 44237.0, 0.0), (824.0, 44217.0, 0.0), + (824.0, 44197.0, 0.0), (784.0, 44167.0, 0.0), (774.0, 44157.0, 0.0), (774.0, 44137.0, 0.0), (784.0, 44127.0, 0.0), (784.0, 44107.0, 0.0), + (774.0, 44097.0, 0.0), (774.0, 44077.0, 0.0), (784.0, 44067.0, 0.0), (779.0, 44052.0, 0.0), (749.0, 44012.0, 0.0), (734.0, 43997.0, 0.0), + (734.0, 43947.0, 0.0), (744.0, 43937.0, 0.0), (739.0, 43922.0, 0.0), (719.0, 43902.0, 0.0), (656.5, 43902.0, 12.0), (654.0, 43899.5, 12.0), + (654.0, 43872.0, 12.0), (654.0, 43899.5, 12.0), (651.5, 43902.0, 12.0), (616.5, 43902.0, 12.0), (614.0, 43899.5, 12.0), (614.0, 43872.0, 12.0), + (614.0, 43899.5, 12.0), (611.5, 43902.0, 12.0), (526.5, 43902.0, 18.0), (524.0, 43899.5, 18.0), (524.0, 43863.0, 18.0), (513.0, 43852.0, 18.0), + (406.5, 43852.0, 18.0), (404.0, 43849.5, 18.0), (404.0, 43804.5, 18.0), (401.5, 43802.0, 18.0), (394.0, 43802.0, 18.0), + }; + + private static NavPoint World(double x, double y, double z) + => new() { Type = T.Point, NS = DungeonGeometry.WorldToNav(y), EW = DungeonGeometry.WorldToNav(x), Z = z / 240.0 }; + + /// Puts the fake character at a route point's nav coordinates. + private static void AtNav(NavPoint p) + { + _n = (p.NS - NS0) * 240.0; _e = (p.EW - EW0) * 240.0; + FakeHost.SetNavPosition(p.NS, p.EW); + } + + /// The real planner's straight-walk answer (NavRecoveryPlanner.WalkInSightOn) on a real dungeon map, from the + /// fake character at height Z. No plans: a fallback shows as "no plan". + private sealed class GeoPlanner : INavRecoveryPlanner + { + public DungeonGeometry Geo = null!; + public double Z; + public NavPoint? LastClear; + public NavRecoveryPlan? TryPlan(NavPoint target, out string why) { why = "test planner: no plans"; return null; } + public NavAreaCheck CheckArea(uint playerCell, double tNs, double tEw, out string routeArea, out string playerArea) + { routeArea = playerArea = string.Empty; return NavAreaCheck.Match; } + public bool? StraightWalkInSight(NavPoint target) + { + bool? a = NavRecoveryPlanner.WalkInSightOn(Geo, NS0 + _n / 240.0, EW0 + _e / 240.0, Z, target); + if (a == true) LastClear = target; + return a; + } + } + + private static void InSightLugianRealDats() + { + string acDir = DunRouteTests.AcDir; + if (!Directory.Exists(acDir)) { Console.WriteLine(" (no dats on this PC: skipped)"); return; } + var loader = new GeometryLoader(); + if (!loader.Initialize(acDir)) { Console.WriteLine(" (geometry loader failed: " + loader.StatusMessage + ")"); return; } + try + { + const uint lb = 0x02E7; + var graph = DungeonPathfinder.GetGraph(lb, loader.CellDat); + var geo = DungeonPathfinder.GetGeometry(lb, loader.CellDat, loader.DungeonLOS); + Check.True(geo != null && graph.Count > 250, $"Lugian Excavations loaded ({graph.Count} cells)"); + if (geo == null) return; + var pts = LugianPatrol.Select(p => World(p.X, p.Y, p.Z)).ToList(); + int n = pts.Count; + + // The patrol's own legs: walked straight, so the map should call (nearly) all of them clear. + int clear = 0; + var notClear = new List(); + for (int i = 0; i < n; i++) + { + var a = pts[i]; + bool? w = NavRecoveryPlanner.WalkInSightOn(geo, a.NS, a.EW, a.Z * 240.0, pts[(i + 1) % n]); + if (w == true) clear++; else notClear.Add($"[{i}]->[{(i + 1) % n}]={(w == null ? "?" : "no")}"); + } + Console.WriteLine($" patrol legs: {clear}/{n} clear walks{(notClear.Count > 0 ? "; not: " + string.Join(" ", notClear) : "")}"); + Check.True(clear >= n - 3, $"the patrol's legs are clear walks on the map ({clear}/{n})"); + + // The 18:56:31 stuck: cell 02E70125 at local (332.13, -397.02, 0), heading for [15] 39.5 m off, standing at a wall. + var stuck = World(2 * 192 + 332.13, 0xE7 * 192 - 397.02, 0); + Check.Eq(NavRecoveryPlanner.WalkInSightOn(geo, stuck.NS, stuck.EW, 0, pts[15]), (bool?)false, "from where it stuck, no clear walk to [15]"); + + var route = new NavRouteParser { RouteType = RT.Circular }; + route.Points.AddRange(pts); + FakeHost.Reset(); + AtNav(World(734, 43917, 0)); // on the leg [14]->[15] when the fight began + var gp = new GeoPlanner { Geo = geo, Z = 0 }; + var nav = new Nav(route, idx: 15, other: gp); + nav.E.KeepWaypointAfterPause = () => true; + nav.Tick(); + nav.E.Stop(); + AtNav(stuck); + var sw = System.Diagnostics.Stopwatch.StartNew(); + nav.Run(0.3); + sw.Stop(); + string line = FakeHost.Logs.FirstOrDefault(l => l.Contains("walking to the route in sight first")) ?? "(none)"; + if (line == "(none)") foreach (var l in FakeHost.Logs.Where(l => l.Contains("Nav:"))) Console.WriteLine(" " + l); + Check.True(line.Contains("[16]->[17]"), "from there the route is in sight on [16]->[17] (also on the loop's way back, [47]->[48], out of reach)"); + Console.WriteLine($" from the 18:56 stuck: {line.Replace("Nav: ", "")} [{sw.ElapsedMilliseconds} ms for the ticks]"); + Check.True(line != "(none)" && gp.LastClear != null, "from there it walks to the route in sight"); + if (gp.LastClear is { } spot) + Check.Eq(NavRecoveryPlanner.WalkInSightOn(geo, stuck.NS, stuck.EW, 0, spot), (bool?)true, "a spot it can walk to straight"); + + // Every room off the route on the patrol's levels: the patrol heading for the waypoint nearest it, but no clear walk + // there. How often is a route spot in sight found (the rest go to the map's way, through the doorways)? + int rooms = 0, blocked = 0, found = 0, none = 0; + long worstMs = 0; + foreach (uint cell in graph.Keys) + { + if (!geo.TryCellFloorCentre(cell, out double cx, out double cy, out double cz)) continue; + var c = World(cx, cy, cz); + int best = -1; + double bestD = double.MaxValue, onRoute = double.MaxValue; + for (int i = 0; i < n; i++) + { + var p = pts[i]; + if (Math.Abs(p.Z * 240.0 - cz) > 3.0) continue; + double d = Math.Sqrt(Math.Pow(DungeonGeometry.NavToWorld(p.EW) - cx, 2) + Math.Pow(DungeonGeometry.NavToWorld(p.NS) - cy, 2)); + if (d < bestD) { bestD = d; best = i; } + var q = pts[(i + 1) % n]; + onRoute = Math.Min(onRoute, SegmentDistance(DungeonGeometry.NavToWorld(p.EW), DungeonGeometry.NavToWorld(p.NS), + DungeonGeometry.NavToWorld(q.EW), DungeonGeometry.NavToWorld(q.NS), cx, cy)); + } + if (best < 0 || bestD > 50 || onRoute < 3.0) continue; + rooms++; + if (NavRecoveryPlanner.WalkInSightOn(geo, c.NS, c.EW, cz, pts[best]) != false) continue; + blocked++; + + FakeHost.Reset(); + AtNav(World(cx + 2, cy, cz)); + var g = new GeoPlanner { Geo = geo, Z = cz }; + var nv = new Nav(route, idx: best, other: g); + nv.E.KeepWaypointAfterPause = () => true; + nv.Tick(); + nv.E.Stop(); + AtNav(c); + var t0 = System.Diagnostics.Stopwatch.StartNew(); + nv.Tick(); + worstMs = Math.Max(worstMs, t0.ElapsedMilliseconds); + if (FakeHost.Logs.Any(l => l.Contains("walking to the route in sight first"))) found++; + else if (FakeHost.Logs.Any(l => l.Contains("no spot of the route near it in sight"))) none++; + } + Console.WriteLine($" rooms off the route: {rooms}; no clear walk to the nearest waypoint from {blocked}; the route in sight found from {found}, " + + $"nothing in sight (the map's way) from {none}; slowest resume {worstMs} ms"); + Check.Eq(found + none, blocked, "every blocked case ends in a walk to the route in sight or the map's way"); + Check.True(blocked == 0 || found * 2 >= blocked, $"the route in sight is found from most of them ({found}/{blocked})"); + Check.True(worstMs < 100, $"a resume's search takes under 100 ms ({worstMs} ms)"); + } + finally { DungeonPathfinder.InvalidateCache(); } + } + + private static double SegmentDistance(double ax, double ay, double bx, double by, double x, double y) + { + double dx = bx - ax, dy = by - ay, l2 = dx * dx + dy * dy; + double t = l2 < 1e-12 ? 0 : Math.Clamp(((x - ax) * dx + (y - ay) * dy) / l2, 0, 1); + return Math.Sqrt(Math.Pow(ax + dx * t - x, 2) + Math.Pow(ay + dy * t - y, 2)); + } + private static void ResumeNearestOff() { FakeHost.Reset(); At(0, 10); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/PlannerObjectTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/PlannerObjectTests.cs index df16892..4422ec2 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/PlannerObjectTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/PlannerObjectTests.cs @@ -37,6 +37,7 @@ internal static class PlannerObjectTests r.Add("planner objects (11-18): a stuck escape burst heading into a wall or an object within 2 m turns to where the dungeon map has room", EscapeRoomTest); r.Add("planner objects (11-18): 0x0190 room 88's table and 0x00C1 room 81's statue on the real dats - an in-room recovery plan, no sample inside (if the dats are here)", InRoomReal); r.Add("planner objects (11-18): Thread patrols with an exit portal at the entry cell on the real dats - no leg through an object, none into the portal (if the dats are here)", PortalPatrolsReal); + r.Add("planner objects (11-27): 0x0182's arrival on the real dats - its loop's [0] is in your room with a clear walk (the start pick counts it), [132] is in a room under it (if the dats are here)", OwnRoomStartReal); r.Add("planner objects (review): the room planner never moves a waypoint up on a dais, a ramp or a platform, or in a step, off it (TargetMoved skipped it); a statue's still", OnTopTargets); r.Add("planner objects (review): the walk test from a spot up on a dais is judged from where the leg leaves it, not failed at its first sample", WalkTestFromOnTop); } @@ -497,6 +498,39 @@ internal static class PlannerObjectTests // ── Real dats ───────────────────────────────────────────────────────────────────────────── + // Desert Mine 0x0182, 2026-11-27: arrived in cell 0x0182017B at about (41, -25.5, 0); the Thread route's [0] is + // (40, -30, 0), its [132] (39.13, -25.97, -11.97) is on the floor under it. The planner's start-pick answer for [0] + // comes from these pieces: the same containing cell as yours, and the in-room walk clear (StraightWalkClearWhy). + private static void OwnRoomStartReal() + { + var loader = Loader(out var before); + if (loader == null) return; + try + { + const uint lb = 0x0182; + DungeonPathfinder.InvalidateCache(); + var geo = DungeonPathfinder.GetGeometry(lb, loader.CellDat, loader.DungeonLOS)!; + Check.NotNull(geo, "0x0182: the dungeon map"); + var floors = new List<(uint, RynthCore.Plugin.RynthAi.Raycasting.Vector3[])>(); + foreach (var poly in loader.DungeonLOS!.GetDungeonMapFloorPolygons(lb)) + if (!poly.IsPortal && poly.Vertices != null && DungeonGeometry.IsUpwardFloor(poly.Vertices)) floors.Add((poly.CellId, poly.Vertices)); + double ox = 0x01 * 192.0, oy = 0x82 * 192.0; + (double X, double Y, double Z) me = (ox + 41.15, oy - 25.52, 0.0), first = (ox + 40.0, oy - 30.0, 0.03), under = (ox + 39.13, oy - 25.97, -11.97); + uint cMe = NavRecoveryPlanner.PickContainingCell(floors, me.X, me.Y, (float)me.Z); + uint cFirst = NavRecoveryPlanner.PickContainingCell(floors, first.X, first.Y, (float)first.Z); + uint cUnder = NavRecoveryPlanner.PickContainingCell(floors, under.X, under.Y, (float)under.Z); + Console.WriteLine($" cells: you 0x{cMe:X8}, [0] 0x{cFirst:X8}, [132] 0x{cUnder:X8}"); + Check.Eq(cMe & 0xFFFF, 0x017Bu, "you are in 0x017B (the arrival's cell in the log)"); + Check.Eq(cFirst, cMe, "[0] is in your room"); + Check.True(cUnder != 0 && cUnder != cMe, "[132] is in another room"); + var plan = NavRecoveryPlanner.PlanInRoom(geo, DungeonGeometry.WorldToNav(me.Y), DungeonGeometry.WorldToNav(me.X), me.Z, + DungeonGeometry.WorldToNav(first.Y), DungeonGeometry.WorldToNav(first.X), first.Z, out string why); + Check.Null(plan, "you to [0]: no in-room plan (nothing to walk round)"); + Check.Eq(why, NavRecoveryPlanner.StraightWalkClearWhy, "you to [0]: the straight walk is clear, so the start pick counts it"); + } + finally { DungeonPathfinder.StaticMeshSource = before; DungeonPathfinder.InvalidateCache(); loader.Dispose(); } + } + private static GeometryLoader? Loader(out Func>? before) { before = DungeonPathfinder.StaticMeshSource; diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/PredictedKillReclaimTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/PredictedKillReclaimTests.cs new file mode 100644 index 0000000..a0cdb4d --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/PredictedKillReclaimTests.cs @@ -0,0 +1,191 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.CreatureData; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// R-20261127-144058-8cb2: "when a monster is close to death it will switch to another prior to +// finishing off its target, then once the next monster is dead it will finish off the one it was +// originally targetting". The third Force Bolt at a Guardian Armoredillo was the predicted kill +// (hp~1800, dealt~1393): the swap locked a fresh Tamed Armoredillo, the bolt was resisted 640 ms +// later, and with Target Lock on the bot fought the fresh one for 13 s before it went back to the +// Guardian, at 23%. Now the survivor takes the lock back once it is known to be alive. +internal static class PredictedKillReclaimTests +{ + private const uint Player = 0x50000F41; + private const uint Lb = 0x88650000; + private const uint GuardianWcid = 3101, TamedWcid = 3102; + private const string Guardian = "Guardian Armoredillo", Tamed = "Tamed Armoredillo"; + private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; + + public static void Register(Runner r) + { + r.Add("predicted kill (R-20261127 8cb2): resisted after the swap -> the lock goes back to it", ResistedTakesLockBack); + r.Add("predicted kill (R-20261127 8cb2): still alive when the swap's window ends -> back to it", AliveAtWindowEndTakesLockBack); + r.Add("predicted kill (R-20261127 8cb2): it died after all -> the new target is kept", DiedKeepsNewTarget); + r.Add("predicted kill (R-20261127 8cb2): alive only after 10 s -> the new target is kept", LateSurvivalKeepsNewTarget); + r.Add("predicted kill (R-20261127 8cb2): the armed cast resisted calls the swap off; a same-named target's miss doesn't reclaim", ArmedResistAndSameName); + } + + private sealed class Rig + { + public readonly LegacyUiSettings S = new() { MonsterRange = 10, TargetSelection = 1, TargetLock = true, EnableCombat = true }; + public CombatManager C = null!; + public WorldObjectCache Cache = null!; + public DateTime Now = RynthClock.Now; + private readonly List _ids = new(); + private uint _next = 0x80000601; + + public Rig() + { + FakeHost.Reset(); + FakeHost.WeaponCalls = true; + FakeHost.CombatModeValue = CombatMode.Magic; + FakeHost.Names[Player] = "Me"; + FakeHost.Positions[Player] = (Lb | 0x1E, 96f, 96f, 0f); + FakeHost.PlayerPose = (Lb | 0x1E, 96f, 96f, 0f); + } + + public uint Mob(string name, uint wcid, float north, float east = 0) + { + uint id = _next++; + FakeHost.Names[id] = name; + FakeHost.Positions[id] = (Lb | 0x1E, 96f + east, 96f + north, 0f); + FakeHost.ItemTypes[id] = 0x10; + FakeHost.Wcids[id] = wcid; + _ids.Add(id); + return id; + } + + public void Build(uint fightTarget) + { + var host = FakeHost.Create(); + Cache = FakeHost.MakeCache(host, Player, _ids); + C = new CombatManager(host, S, Cache); + C.SetPlayerId(Player); + C.SetDamageStores(null, new MonsterDamageStore()); + C.TargetClock = () => Now; + C.EngageForTest(unchecked((int)fightTarget)); + } + + public void Rescan() + { + typeof(CombatManager).GetField("_lastScanTime", Any)!.SetValue(C, DateTime.MinValue); + C.ScanNearbyTargets(); + } + + /// The predicted kill's cast was accepted: the swap off the target, then the next lock. + public void SwapAndLockNext() + { + C.ArmPredictedSwapForTest(castAgoMs: 2000); + C.PredictedSwapForTest(); + Rescan(); + C.HandleCombatTrigger(); + } + + public void Tick() { Rescan(); C.HandleCombatTrigger(); } + public int Target => C.activeTargetId; + public int LogCount(string part) => FakeHost.Logs.Count(l => l.Contains(part, StringComparison.Ordinal)); + } + + private static int Id(uint id) => unchecked((int)id); + + private static void ResistedTakesLockBack() + { + var r = new Rig(); + uint guardian = r.Mob(Guardian, GuardianWcid, 3); + uint tamed = r.Mob(Tamed, TamedWcid, 3.5f, 0.5f); + r.Build(guardian); + + r.SwapAndLockNext(); + Check.Eq(r.Target, Id(tamed), "the swap locks the Tamed Armoredillo"); + + r.Now = r.Now.AddMilliseconds(640); + r.C.HandleChatForDamage("Guardian Armoredillo resists your spell", 7); + Check.Eq(r.LogCount("Predicted kill of 0x80000601 'Guardian Armoredillo' resisted an attack after the swap"), 1, "the resist says it lives"); + r.Tick(); + Check.Eq(r.Target, Id(guardian), "the Guardian takes the lock back (Target Lock on)"); + Check.Eq(r.LogCount("survived: back to it"), 1, "the switch says why"); + + r.Tick(); + Check.Eq(r.Target, Id(guardian), "and keeps it: no trading back"); + } + + private static void AliveAtWindowEndTakesLockBack() + { + var r = new Rig(); + uint guardian = r.Mob(Guardian, GuardianWcid, 3); + uint tamed = r.Mob(Tamed, TamedWcid, 3.5f, 0.5f); + r.Build(guardian); + r.SwapAndLockNext(); + Check.Eq(r.Target, Id(tamed), "the swap locks the Tamed Armoredillo"); + + r.Now = r.Now.AddMilliseconds(1500); + r.Tick(); + Check.Eq(r.Target, Id(tamed), "inside the swap's window nothing is known yet"); + + r.Now = r.Now.AddMilliseconds(600); + r.Tick(); + Check.Eq(r.LogCount("still alive: it is a target again"), 1, "alive when the window ends"); + Check.Eq(r.Target, Id(guardian), "the Guardian takes the lock back"); + } + + private static void DiedKeepsNewTarget() + { + var r = new Rig(); + uint guardian = r.Mob(Guardian, GuardianWcid, 3); + uint tamed = r.Mob(Tamed, TamedWcid, 3.5f, 0.5f); + r.Build(guardian); + r.SwapAndLockNext(); + r.Cache.OnUpdateHealth(guardian, 0f); // the server says it died + r.Now = r.Now.AddMilliseconds(2100); + r.Tick(); + Check.Eq(r.Target, Id(tamed), "a dead prediction: the Tamed Armoredillo stays the target"); + Check.Eq(r.LogCount("survived: back to it"), 0, "no switch"); + } + + private static void LateSurvivalKeepsNewTarget() + { + var r = new Rig(); + uint guardian = r.Mob(Guardian, GuardianWcid, 3); + uint tamed = r.Mob(Tamed, TamedWcid, 3.5f, 0.5f); + r.Build(guardian); + r.SwapAndLockNext(); + r.Now = r.Now.AddMilliseconds(CombatManager.ReclaimWindowMs + 500); + r.Tick(); + Check.Eq(r.Target, Id(tamed), "10 s on, the fight with the Tamed Armoredillo is kept (Target Lock on)"); + Check.Eq(r.LogCount("survived: back to it"), 0, "no switch"); + } + + private static void ArmedResistAndSameName() + { + var r = new Rig(); + uint guardian = r.Mob(Guardian, GuardianWcid, 3); + r.Mob(Tamed, TamedWcid, 3.5f, 0.5f); + r.Build(guardian); + r.C.ArmPredictedSwapForTest(castAgoMs: 2600); + r.C.HandleChatForDamage("Guardian Armoredillo resists your spell", 7); + Check.False(r.C.PredictedSwapArmed, "its own cast was resisted: the swap is called off"); + Check.Eq(r.LogCount("called off: it resisted the cast"), 1, "and logged"); + Check.Eq(r.Target, Id(guardian), "still on the Guardian"); + + // Two of a name: the swap went from one Tamed Armoredillo to the other; a resist naming + // "Tamed Armoredillo" may be the new target's, so it proves nothing about the first. + var s = new Rig(); + uint first = s.Mob(Tamed, TamedWcid, 3); + uint second = s.Mob(Tamed, TamedWcid, 3.5f, 0.5f); + s.Build(first); + s.SwapAndLockNext(); + Check.Eq(s.Target, Id(second), "the swap locks the other one"); + s.C.HandleChatForDamage("Tamed Armoredillo resists your spell", 7); + s.Tick(); + Check.Eq(s.Target, Id(second), "a same-named miss takes nothing back"); + Check.Eq(s.LogCount("resisted an attack after the swap"), 0, "and isn't taken as the first one's"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/ProfileStartTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/ProfileStartTests.cs new file mode 100644 index 0000000..15b1d00 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/ProfileStartTests.cs @@ -0,0 +1,246 @@ +using System; +using System.IO; +using System.Linq; +using System.Reflection; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.Shared; +using RynthCore.PluginCore; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// 2026-11-27 (R-20261127-124531-b5d3): a new settings profile was always a copy of the one in use, +// and the Monsters rules belong to the profile (2026-11-18), so a T11 profile made from a T10 one +// had every T10 monster rule in it. A new profile now starts from a copy (Save As, which says what +// it copied) or fresh (New: the Monsters list down to Default, no items or consumables, weapons +// filled from the pack, every other setting kept). The Monsters list also has a Clear list, which +// keeps the Default row and saves. +internal static class ProfileStartTests +{ + private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; + private const int HandWraps = unchecked((int)0x801A1F0D); + private const int Sword = 0x50000101, Kit = 0x50000202; + + public static void Register(Runner r) + { + r.Add("new profile: the fresh reset keeps Default (or makes one) and only empties the lists", ResetUnit); + r.Add("new profile: Save As says it is a copy and how many monster rules came with it", CopySays); + r.Add("new profile: Fresh has only the Default row and no items, keeps the other settings", FreshProfile); + r.Add("new profile: Fresh never replaces an existing profile, and the one left keeps its lists", FreshRefusesExisting); + r.Add("monsters: Clear list keeps the Default row and saves the profile and the Monsters file", ClearList); + r.Add("new profile: /ra settings new is fresh, saveas a copy; the menu's Clear list verb", CommandsAndVerbs); + } + + private sealed class Scratch : IDisposable + { + private readonly string? _buffs = BuffProfileStore.FolderOverride; + public readonly string CharDir, MonstersFile; + + public Scratch(string name) + { + string root = Path.Combine(Program.TempRoot, "profile-start", name); + if (Directory.Exists(root)) Directory.Delete(root, recursive: true); + Directory.CreateDirectory(root); + LegacyDashboardRenderer.ProfilesBase = Path.Combine(root, "SettingsProfiles"); + LegacyDashboardRenderer.MonstersBase = Path.Combine(root, "MonsterProfiles"); + BuffProfileStore.FolderOverride = Path.Combine(root, "BuffProfiles"); + CharDir = Path.Combine(LegacyDashboardRenderer.ProfilesBase, "TestWorld", "Tester"); + MonstersFile = Path.Combine(LegacyDashboardRenderer.MonstersBase, "TestWorld", "Tester.json"); + } + + public string Tag => File.Exists(MonstersFile + ".profile") ? File.ReadAllText(MonstersFile + ".profile").Trim() : ""; + public string Profile(string name) => File.ReadAllText(Path.Combine(CharDir, name + ".json")); + + public void Dispose() => BuffProfileStore.FolderOverride = _buffs; + } + + private static LegacyDashboardRenderer Login(out LegacyUiSettings s) + { + FakeHost.Reset(); + DataWriteGuard.Reset(); + FakeHost.WorldName = "TestWorld"; + var dash = new LegacyDashboardRenderer(FakeHost.Create()); + FakeHost.WorldName = "TestWorld"; + dash.LoadSettings("Tester"); + s = (LegacyUiSettings)typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.GetValue(dash)!; + return dash; + } + + private static MonsterRule DefaultRow(LegacyUiSettings s) => + s.MonsterRules.Single(r => r.Name.Equals("Default", StringComparison.OrdinalIgnoreCase)); + + private static void Select(LegacyDashboardRenderer dash, string profile) => + dash.SelectProfileAtIndex(3, Array.IndexOf(dash.ReadDashboardFiles().Profiles, profile)); + + private static string PackSetup(LegacyDashboardRenderer dash) => + typeof(LegacyDashboardRenderer).GetField("_packSetup", Any)!.GetValue(dash)!.ToString()!; + + /// A T10 profile in use: Default's off hand set, two named rules, a weapon, a kit, a buff row, Monster Range 33. + private static LegacyDashboardRenderer T10(out LegacyUiSettings s) + { + var dash = Login(out s); + DefaultRow(s).OffhandId = HandWraps; + s.MonsterRules.Add(new MonsterRule { Name = "Tusker", Priority = 3 }); + s.MonsterRules.Add(new MonsterRule { Name = "Olthoi", Priority = 4 }); + s.ItemRules.Add(new ItemRule { Id = Sword, Name = "T10 Sword", Action = "Weapon" }); + s.ConsumableRules.Add(new ConsumableRule { Id = Kit, Name = "Healing Kit", Type = "Heal" }); + s.BuffRules.Add(new BuffRule { SpellName = "Strength Self VII" }); + s.MonsterRange = 33; + s.ProfileItemsChecked = true; + dash.SaveMonsterRules(); + ProfileResult r = dash.SaveProfileAs(ProfileKind.Settings, "T10", replace: false); + Check.True(r.Ok, "Save As T10: " + r.Text); + Check.Eq(s.SelectedProfile, "T10", "T10 in use"); + return dash; + } + + private static void ResetUnit() + { + var s = new LegacyUiSettings { MonsterRange = 41 }; + s.MonsterRules.Add(new MonsterRule { Name = "Tusker" }); + s.MonsterRules.Add(new MonsterRule { Name = "default", OffhandId = HandWraps }); + s.ItemRules.Add(new ItemRule { Id = Sword, Name = "T10 Sword" }); + s.ConsumableRules.Add(new ConsumableRule { Id = Kit, Name = "Healing Kit" }); + s.BuffRules.Add(new BuffRule { SpellName = "Strength Self VII" }); + s.ProfileItemsChecked = true; + var oldMonsters = s.MonsterRules; + + LegacyDashboardRenderer.ResetForFreshProfile(s); + Check.Eq(s.MonsterRules.Count, 1, "one rule left"); + Check.Eq(s.MonsterRules[0].OffhandId, HandWraps, "the Default row itself is kept, as it was"); + Check.Eq(oldMonsters.Count, 2, "a new list: the old one isn't emptied under a reader"); + Check.Eq(s.ItemRules.Count + s.ConsumableRules.Count + s.BuffRules.Count, 0, "items, consumables and the buff rows emptied"); + Check.False(s.ProfileItemsChecked, "the weapons are filled from the pack again"); + Check.Eq(s.MonsterRange, 41, "other settings kept"); + + var none = LegacyDashboardRenderer.DefaultRuleOnly(new() { new MonsterRule { Name = "Tusker" } }); + Check.Eq(none.Count, 1, "no Default row: one is made"); + Check.Eq(none[0].Name, "Default", "named Default"); + Check.Eq(LegacyDashboardRenderer.NamedMonsterRules(none), 0, "Default isn't counted as a monster rule"); + } + + private static void CopySays() + { + using var t = new Scratch("copy"); + var dash = T10(out var s); + ProfileResult r = dash.SaveProfileAs(ProfileKind.Settings, "T11", replace: false); + Check.True(r.Ok, "Save As T11"); + Check.Eq(r.Text, "[RynthAi] New profile 'T11': a copy of 'T10' (2 monster rules).", "the chat line"); + Check.Eq(s.MonsterRules.Count, 3, "a copy keeps the monster rules"); + Check.Eq(s.ItemRules.Count, 1, "and the weapons"); + + Select(dash, "T10"); + r = dash.SaveProfileAs(ProfileKind.Settings, "T11", replace: true); + Check.Eq(r.Text, "[RynthAi] Profile 'T11' replaced with a copy of 'T10' (2 monster rules).", "a replace says so"); + } + + private static void FreshProfile() + { + using var t = new Scratch("fresh"); + var dash = T10(out var s); + ProfileResult r = dash.NewProfile(ProfileKind.Settings, "T11"); + Check.True(r.Ok, "New T11: " + r.Text); + Check.Eq(r.Text, "[RynthAi] New profile 'T11': fresh (no monsters or items; weapons fill from your pack).", "the chat line"); + Check.Eq(s.SelectedProfile, "T11", "T11 in use"); + Check.Eq(s.MonsterRules.Count, 1, "only the Default row"); + Check.Eq(DefaultRow(s).OffhandId, HandWraps, "Default as it was"); + Check.Eq(s.ItemRules.Count, 0, "no weapons yet"); + Check.Eq(s.ConsumableRules.Count, 0, "no consumables yet"); + Check.Eq(s.BuffRules.Count, 0, "no per-profile buff rows"); + Check.Eq(s.MonsterRange, 33, "Monster Range kept"); + Check.Eq(PackSetup(dash), "FillNew", "weapons and consumables fill from the pack, as a new profile's do"); + + string json = t.Profile("T11"); + Check.False(json.Contains("Tusker") || json.Contains("T10 Sword"), "T11.json holds no T10 monsters or weapons"); + Check.Eq(t.Tag, "T11", "the Monsters file is T11's"); + Check.False(File.ReadAllText(t.MonstersFile).Contains("Tusker"), "and holds only Default"); + + Select(dash, "T10"); + Check.Eq(s.SelectedProfile, "T10", "back on T10"); + Check.Eq(s.MonsterRules.Count, 3, "T10 kept its monster rules"); + Check.Eq(s.ItemRules.Count, 1, "and its weapon"); + Check.Eq(s.ConsumableRules.Count, 1, "and its kit"); + + Select(dash, "T11"); + Check.Eq(s.MonsterRules.Count, 1, "T11 is still fresh after a switch"); + } + + private static void FreshRefusesExisting() + { + using var t = new Scratch("fresh-exists"); + var dash = T10(out var s); + Check.True(dash.SaveProfileAs(ProfileKind.Settings, "T11", replace: false).Ok, "a T11 copy"); + Select(dash, "T10"); + string before = t.Profile("T11"); + + ProfileResult r = dash.NewProfile(ProfileKind.Settings, "T11"); + Check.False(r.Ok, "New over an existing profile is refused"); + Check.True(r.Text.Contains("already exists"), r.Text); + Check.Eq(t.Profile("T11"), before, "T11 untouched"); + Check.Eq(s.SelectedProfile, "T10", "T10 still in use"); + Check.Eq(s.MonsterRules.Count, 3, "with its rules"); + Check.False(dash.NewProfile(ProfileKind.Settings, "monsters").Ok, "a name RynthAi keeps is refused"); + Check.False(dash.NewProfile(ProfileKind.Settings, " ").Ok, "a blank name is refused"); + Check.Eq(s.ItemRules.Count, 1, "nothing was reset"); + } + + private static void ClearList() + { + using var t = new Scratch("clear"); + var dash = T10(out var s); + ProfileResult r = dash.ClearMonsterRules(); + Check.True(r.Ok, "Clear list: " + r.Text); + Check.Eq(r.Text, "[RynthAi] Cleared the Monsters list of profile 'T10': removed 2 monster rules; the Default row stays.", "the chat line"); + Check.Eq(s.MonsterRules.Count, 1, "only Default left"); + Check.Eq(DefaultRow(s).OffhandId, HandWraps, "the Default row as it was"); + Check.Eq(s.ItemRules.Count, 1, "the weapons stay"); + Check.False(t.Profile("T10").Contains("Tusker"), "saved to T10.json at once"); + Check.False(File.ReadAllText(t.MonstersFile).Contains("Tusker"), "and to the Monsters file"); + Check.Eq(t.Tag, "T10", "tagged T10"); + Check.Eq(dash.ProfileInfo(ProfileKind.Settings).MonsterRules, 0, "the PROFILE menu counts no rules"); + + Check.True(dash.ClearMonsterRules().Text.Contains("nothing to clear"), "a second clear has nothing to do"); + + Login(out s); + Check.Eq(s.SelectedProfile, "T10", "relogged on T10"); + Check.Eq(s.MonsterRules.Count, 1, "still cleared after a relog"); + Check.Eq(DefaultRow(s).OffhandId, HandWraps, "Default kept after a relog"); + } + + private static void CommandsAndVerbs() + { + using var t = new Scratch("commands"); + var dash = T10(out var s); + Check.Eq(dash.ProfileInfo(ProfileKind.Settings).MonsterRules, 2, "the PROFILE menu counts T10's two rules"); + Check.Eq(dash.ProfileInfo(ProfileKind.Nav).MonsterRules, -1, "other kinds have no Monsters list"); + var plugin = new RynthAiPlugin(); + typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(plugin, new object[] { FakeHost.LastApi }); + typeof(RynthAiPlugin).GetField("_dashboard", Any)!.SetValue(plugin, dash); + MethodInfo dispatch = typeof(RynthAiPlugin).GetMethod("DispatchRaCommand", Any)!; + string Ra(string line) + { + FakeHost.Chat.Clear(); + string[] parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries); + dispatch.Invoke(plugin, new object[] { parts[1].ToLowerInvariant(), parts, 0 }); + return string.Join(" / ", FakeHost.Chat); + } + + string chat = Ra("/ra settings saveas T10 Copy"); + Check.True(chat.Contains("New profile 'T10 Copy': a copy of 'T10' (2 monster rules)."), "/ra settings saveas copies: " + chat); + Check.Eq(s.MonsterRules.Count, 3, "the copy has T10's rules"); + chat = Ra("/ra settings new T11"); + Check.True(chat.Contains("New profile 'T11': fresh"), "/ra settings new: " + chat); + Check.Eq(s.MonsterRules.Count, 1, "fresh"); + chat = Ra("/ra settings new"); + Check.True(chat.Contains("needs a name") && chat.Contains("new "), "no name: why + usage: " + chat); + + Select(dash, "T10"); + var run = typeof(RynthAiPlugin).GetMethod("RunProfileAction", Any)!; + var r = (ProfileResult)run.Invoke(plugin, new object?[] { ProfileKind.Settings, ProfileVerb.ClearMonsters, "", false })!; + Check.True(r.Ok && r.Text.Contains("removed 2 monster rules"), "the menu's Clear list verb: " + r.Text); + r = (ProfileResult)run.Invoke(plugin, new object?[] { ProfileKind.Nav, ProfileVerb.ClearMonsters, "", false })!; + Check.False(r.Ok, "only a settings profile has a Monsters list"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/SpellCatalogTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/SpellCatalogTests.cs index e5f29ef..51b58b0 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/SpellCatalogTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/SpellCatalogTests.cs @@ -36,6 +36,10 @@ internal static class SpellCatalogTests r.Add("built-in buffs (R-20261119-195743-1993): Mana Conversion Mastery right after the four that raise casting skill, before the rest", ManaConversionEarly); r.Add("buff profile: a profile spell casts the best level known", ProfileResolvesTier); r.Add("buff profile: a name with no tier ladder falls back to its spell family", ProfileFamilyFallback); + // Spotted by SilentKelpie (rynth PR #12); re-implemented here. + r.Add("buffing: never a heal for health, stamina or mana, nor a dispel (list or profile); lasting boosts stay", BuffingNeverHealsOrDispels); + r.Add("fellowship buffs: only with the setting on and in a fellowship; capped by the skill, never below the self level, refused levels passed over", FellowshipBuffs); + r.Add("fellowship buffs: UseFellowshipBuffs defaults off, loads, saves, bridges, is in the settings map", FellowshipBuffsSetting); r.Add("buff profile: Loaded Files lists profiles, picks one by index, and the snapshot reports it", LoadedFilesPicker); } @@ -281,4 +285,146 @@ internal static class SpellCatalogTests dash.SelectProfileAtIndex(4, 0); Check.Eq(dash.Settings.CurrentBuffProfilePath, "", "index 0 goes back to the built-in list"); }); + + private static void BuffingNeverHealsOrDispels() + { + SpellCatalog.EnsureLoaded(); + int Named(string n) => SpellCatalog.GetByName(n)?.Id ?? 0; + foreach (string n in new[] { "Heal Self VI", "Revitalize Self VI", "Mana Boost Self VI", "Stamina to Mana Self VI", + "Incantation of Heal Self", "Evaporate All Magic Other" }) + { + Check.True(Named(n) != 0, $"{n} is in the catalog"); + Check.False(BuffManager.IsLastingBuff(Named(n)), $"{n} is never cast as a buff"); + } + int dispels = 0; + foreach (var c in SpellCatalog.All) + if (c.FamilyName.Contains("Dispel", StringComparison.OrdinalIgnoreCase)) + { + dispels++; + if (BuffManager.IsLastingBuff(c.Id)) Check.True(false, $"dispel {c.Name} ({c.Id}) counted as a buff"); + } + Check.True(dispels > 10, $"every dispel in the catalog is refused ({dispels})"); + foreach (string n in new[] { "Strength Self VI", "Regeneration Self VI", "Rejuvenation Self VI", "Mana Renewal Self VI", + "Blade Bane VI", "Aura of Blood Drinker Self VI" }) + Check.True(BuffManager.IsLastingBuff(Named(n)), $"{n} stays a buff"); + + // A spell the catalog doesn't know goes by name. + foreach (string n in new[] { "Heal Self IX", "Mana to Health Other II", "Extinguish All Magic Self", "Dispel Creature" }) + Check.True(BuffManager.IsVitalOrDispelName(n), $"by name: {n} is a heal or dispel"); + foreach (string n in new[] { "Mana Renewal Self IX", "Regeneration Other", "Strength Self", "" }) + Check.False(BuffManager.IsVitalOrDispelName(n), $"by name: '{n}' is not"); + + // The built-in list, every spell known at skill 500: none of these is ever picked. + var all = new System.Collections.Generic.List(); + foreach (var c in SpellCatalog.All) all.Add(c.Id); + var buffs = NewBuffs(500, all.ToArray()); + foreach (string buff in buffs.BuildBuiltInBuffList()) + { + int id = buffs.FindBestSpellId(buff, buffs.SkillFor(buff)); + if (id != 0 && !BuffManager.IsLastingBuff(id)) Check.True(false, $"built-in {buff} resolved to a heal or dispel ({id})"); + } + + // A profile that names Mana Boost and Heal Self: left out, and logged once. + buffs = NewBuffs(500, all.ToArray()); + var profile = new BuffProfile { Name = "heals" }; + profile.Entries.Add(BuffProfileStore.EntryFor(Spell(Named("Mana Boost Self VI")))); + profile.Entries.Add(BuffProfileStore.EntryFor(Spell(Named("Heal Self VI")))); + profile.Entries.Add(BuffProfileStore.EntryFor(Spell(Named("Regeneration Self VI")))); + profile.Entries.Add(BuffProfileStore.EntryFor(Spell(StrengthSelfVI))); + buffs.ApplyBuffProfile(profile); + Check.Eq(buffs.ActiveBuffProfileCount, 2, "only the two buffs are in use"); + Check.False(buffs.BuildDynamicBuffList().Any(b => b.Contains("Mana Boost") || b.Contains("Heal Self")), "the heals are not in the list"); + Check.True(FakeHost.Logs.Any(l => l.Contains("left out") && l.Contains("Mana Boost Self VI") && l.Contains("Heal Self VI")), "logged what was left out"); + Check.Eq(buffs.FindBestSpellId("Mana Boost Self", AcSkillType.LifeMagic), 0, "and the picker never resolves Mana Boost for buffing"); + } + + private const int GreaterEmpoweringConclave = 3177, SuperiorEmpoweringConclave = 3178; + + private static void FellowshipBuffs() + { + SpellCatalog.EnsureLoaded(); + Check.True(BuffManager.IsFellowshipSpell(Spell(SuperiorEmpoweringConclave)), "Superior Empowering the Conclave is a fellowship spell"); + Check.False(BuffManager.IsFellowshipSpell(Spell(MightOfTheLugians)), "Might of the Lugians is not"); + Check.Eq(Spell(SuperiorEmpoweringConclave).FamilyId, StrengthFamily, "same family as Strength Self"); + + bool inFellow = true; + BuffManager Rig(int buffed, bool on, params int[] known) + { + var b = NewBuffs(buffed, known); + Settings(b).UseFellowshipBuffs = on; + b.InFellowship = () => inFellow; + return b; + } + int Pick(BuffManager b) => b.FindBestSpellId("Strength Self", AcSkillType.CreatureEnchantment); + + int[] all = { StrengthSelfVI, MightOfTheLugians, GreaterEmpoweringConclave, SuperiorEmpoweringConclave }; + Check.Eq(Pick(Rig(500, on: false, all)), MightOfTheLugians, "setting off: the self buff"); + Check.Eq(Pick(Rig(500, on: true, all)), SuperiorEmpoweringConclave, "on, in a fellowship, skill 500: the level-7 fellowship version"); + inFellow = false; + Check.Eq(Pick(Rig(500, on: true, all)), MightOfTheLugians, "solo: never"); + inFellow = true; + Check.Eq(Pick(Rig(300, on: true, all)), GreaterEmpoweringConclave, "skill 300 (tier 6): the level-6 fellowship version, as the self buff is VI"); + Check.Eq(Pick(Rig(500, on: true, StrengthSelfVI, MightOfTheLugians, GreaterEmpoweringConclave)), MightOfTheLugians, + "only a lower fellowship level known: the self buff (never weaker)"); + Check.Eq(Pick(Rig(500, on: true, StrengthSelfVI, MightOfTheLugians)), MightOfTheLugians, "no fellowship version known: the self buff"); + + var refused = Rig(500, on: true, all); + Spells(refused).MarkNoComponents(SuperiorEmpoweringConclave); + Check.Eq(Pick(refused), MightOfTheLugians, "the fellowship level refused for components: the self buff (the lower fellowship level is weaker)"); + + // A buff profile goes through the same picker; its family fallback never picks a fellowship spell itself. + var prof = Rig(500, on: false, all); + var profile = new BuffProfile { Name = "fellow" }; + profile.Entries.Add(BuffProfileStore.EntryFor(Spell(StrengthOtherVI))); + prof.ApplyBuffProfile(profile); + Check.Eq(Pick(prof), MightOfTheLugians, "profile, setting off: the self buff"); + Settings(prof).UseFellowshipBuffs = true; + Check.Eq(Pick(prof), SuperiorEmpoweringConclave, "profile, setting on: the fellowship version"); + + // The fellowship version's level is the catalog's, not the name's (no numeral in its name). + Check.Eq(BuffManager.GetSpellLevel(SpellTableStub.GetById(SuperiorEmpoweringConclave)!), 7, "Superior Empowering the Conclave is level 7"); + int volition = SpellCatalog.GetByName("Superior Volition of the Conclave")!.Id; + Check.Eq(BuffManager.GetSpellLevel(SpellTableStub.GetById(volition)!), 7, "Superior Volition of the Conclave is 7, not V"); + } + + private static LegacyUiSettings Settings(BuffManager b) => + (LegacyUiSettings)typeof(BuffManager).GetField("_settings", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)!.GetValue(b)!; + + private static SpellManager Spells(BuffManager b) => + (SpellManager)typeof(BuffManager).GetField("_spellManager", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)!.GetValue(b)!; + + private static void FellowshipBuffsSetting() + { + Check.False(new LegacyUiSettings().UseFellowshipBuffs, "a new profile: off"); + var on = System.Text.Json.JsonSerializer.Deserialize( + System.Text.Json.JsonSerializer.Serialize(new LegacyUiSettings { UseFellowshipBuffs = true }, RynthAiJsonContext.Default.LegacyUiSettings), + RynthAiJsonContext.Default.LegacyUiSettings); + Check.True(on != null && on.UseFellowshipBuffs, "on is saved and loaded"); + var copy = typeof(LegacyDashboardRenderer).GetMethod("CopySettings", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static)!; + var dst = new LegacyUiSettings(); + copy.Invoke(null, new object[] { new LegacyUiSettings { UseFellowshipBuffs = true }, dst }); + Check.True(dst.UseFellowshipBuffs, "a profile with it on loads on"); + + var payload = System.Text.Json.JsonSerializer.Deserialize("{\"PatrolOnLogin\":false}", RynthAiJsonContext.Default.SettingsBridgePayload); + Check.True(payload != null && payload.UseFellowshipBuffs == null, "an older engine's payload has no value"); + var s = new LegacyUiSettings { UseFellowshipBuffs = true }; + var dash = (LegacyDashboardRenderer)System.Runtime.CompilerServices.RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer)); + typeof(LegacyDashboardRenderer).GetField("_profileLoaded", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!.SetValue(dash, true); + typeof(LegacyDashboardRenderer).GetField("_settings", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)!.SetValue(dash, s); + typeof(LegacyDashboardRenderer).GetField("_advancedSettingsUi", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)! + .SetValue(dash, new LegacyAdvancedSettingsUi(s)); + var sent = System.Text.Json.JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload); + Check.True(sent != null && sent.UseFellowshipBuffs == true, "sent to the engine face"); + dash.ApplySettingsJson("{\"PatrolOnLogin\":false}"); + Check.True(s.UseFellowshipBuffs, "a save without the field leaves it on"); + dash.ApplySettingsJson("{\"UseFellowshipBuffs\":false}"); + Check.False(s.UseFellowshipBuffs, "a save with it off turns it off"); + + var live = new LegacyUiSettings(); + var map = ExpressionTests.Engine(settings: live).BuildSettingsMapPublic(); + Check.True(map.TryGetValue("UseFellowshipBuffs", out var entry), "in the settings map"); + Check.Eq(entry.Get(), "0", "reads off"); + entry.Set("1"); + Check.True(live.UseFellowshipBuffs, "and sets on"); + } } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/VTankLootTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/VTankLootTests.cs index 4f8074f..4b6355d 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/VTankLootTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/VTankLootTests.cs @@ -401,8 +401,14 @@ internal static class VTankLootTests Check.False(MC(robe, ctx, C(N.SlotExactPalette, "0", "22136")), "wrong palette for the slot"); Check.False(MC(robe, ctx, C(N.SlotExactPalette, "2", "4660")), "slot past the end"); Check.False(MC(robe, ctx, C(N.SlotExactPalette, "-1", "4660")), "negative slot"); + // 2026-11-28: with an engine that reads palettes, an item it has none for (the client released + // or deleted it) fails: a Legendary Chest's plain 'Helmet' matched "PP Olthoi Helm" that way. var plain = new Item("Plain"); - Check.True(MC(plain, ctx, C(N.SlotExactPalette, "5", "1")), "an item with no palette data passes"); + Check.False(MC(plain, ctx, C(N.SlotExactPalette, "5", "1")), "an item with no palette data fails where the engine reads palettes"); + Check.False(MC(plain, ctx, C(N.SlotExactPalette, "0", "3665")), "whatever the slot and palette"); + // The palettes come back (the object is created again): judged on them. + FakeHost.Palettes[unchecked((uint)plain.Wo.Id)] = new uint[] { 0x04000E51 }; + Check.True(MC(plain, new VTankLootContext(FakeHost.Create(), Player), C(N.SlotExactPalette, "0", "3665")), "palettes read again: 0xE51 = 3665 matches"); } private static void MalformedData() diff --git a/Tools/RynthDefective.Tests/AppraisalTests.cs b/Tools/RynthDefective.Tests/AppraisalTests.cs new file mode 100644 index 0000000..37fd0f4 --- /dev/null +++ b/Tools/RynthDefective.Tests/AppraisalTests.cs @@ -0,0 +1,164 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using RynthCore.Plugin.RynthDefective.Appraisal; +using RynthCore.Plugin.RynthDefective.Model; + +namespace RynthDefective.Tests +{ + // The Appraisal window's words (2026-11-28): retail's examine lines for a weapon, armor, a caster, a + // creature and a player, the wield requirements, the flags, and the "All properties" list. + internal static partial class Program + { + private static AppraisalInput Item(uint itemType, params (uint Key, int Value)[] ints) + { + var o = new AppraisalInput { Id = 0x8000_1234, Name = "Test Item", ItemType = itemType, Identified = true, SpellName = SpellTable.Name }; + o.Ints[1] = (int)itemType; + foreach (var (k, v) in ints) o.Ints[k] = v; + return o; + } + + private static List Lines(AppraisalDoc d, string section) => + d.Sections.FirstOrDefault(s => s.Title == section)?.Lines.Select(l => l.Text).ToList() ?? new List(); + + private static void AppraiseWeapon() + { + // A heavy sword: 50 max, variance 0.5, slash/pierce, speed 35, +12% attack, +15% melee defense. + var o = Item(0x1, (19, 12345), (5, 150), (48, 0x2C), (353, 2), (44, 50), (45, 0x3), (49, 35), + (158, 1), (159, 0x2C), (160, 400), (270, 7), (272, 180), (105, 8), (131, 64), (265, 13), (370, 3), (372, 1), (179, 0x4), (166, 1)); + o.Floats[22] = 0.5; o.Floats[62] = 1.12; o.Floats[29] = 1.15; o.Floats[138] = 2.5; + o.Spells.Add(6); + AppraisalDoc d = AppraisalText.Build(o); + + Eq(d.Kind, "Heavy Weapons (Sword)", "kind"); + Check(d.Facts.Contains(("Value", "12,345")) && d.Facts.Contains(("Burden", "150")), "value and burden: " + string.Join("; ", d.Facts)); + var w = Lines(d, "Weapon"); + Check(w.Contains("Skill: Heavy Weapons (Sword)"), "skill line: " + string.Join(" | ", w)); + Check(w.Contains("Damage: 25 - 50, Slashing/Piercing"), "damage line"); + Check(w.Contains("Speed: Average (35)"), "speed line"); + Check(w.Contains("Bonus to Attack Skill: +12%."), "attack bonus"); + Check(w.Contains("Bonus to Melee Defense: +15%."), "melee defense bonus"); + Check(w.Contains("Slayer: Olthoi (x2.5 damage)"), "slayer"); + Check(w.Contains("Imbued: Armor Rending"), "imbue"); + var r = Lines(d, "Requirements"); + Check(r.Contains("Wield requires Heavy Weapons 400") && r.Contains("Wield requires level 180"), "wield lines: " + string.Join(" | ", r)); + var p = Lines(d, "Properties"); + Check(p.Contains("Workmanship: Utterly flawless (8)") && p.Contains("Material: Steel") && p.Contains("Set: Soldier's Set"), "workmanship, material, set: " + string.Join(" | ", p)); + Check(p.Contains("Ratings: Damage +3, Crit +1"), "ratings"); + Check(Lines(d, "Magic").Contains("Spells: Heal Self I"), "spells by name"); + Check(!d.IsCreature && d.Bars.Count == 0, "an item without mana has no bars"); + } + + private static void AppraiseArmorAndMana() + { + var o = Item(0x2, (28, 600), (4, 0x0400 | 0x0800 | 0x1000 | 0x2000), (107, 1234), (108, 2000), (106, 400), (109, 300), (33, 1), (114, 1), (36, 9999)); + o.Floats[13] = 1.2; o.Floats[14] = 0.6; o.Floats[5] = -1.0 / 20.0; + o.Bools[91] = true; + AppraisalDoc d = AppraisalText.Build(o); + + Eq(d.Kind, "Armor", "kind"); + var a = Lines(d, "Armor"); + Check(a.Contains("Armor Level: 600") && a.Contains("Slashing: Above Average (720)") && a.Contains("Piercing: Below Average (360)"), "protections: " + string.Join(" | ", a)); + Check(a.Contains("Covers: Chest, Abdomen, Upper Arms, Lower Arms"), "coverage"); + var m = Lines(d, "Magic"); + Check(m.Contains("Mana: 1,234 / 2,000") && m.Contains("Mana Cost: 1 point per 20 seconds.") && m.Contains("Spellcraft: 400."), "mana lines: " + string.Join(" | ", m)); + Check(Lines(d, "Requirements").Contains("Activation requires Arcane Lore: 300"), "arcane lore"); + Check(Lines(d, "Properties").Contains("Properties: Bonded, Attuned (can't be given), Retained, Unenchantable"), "flags: " + string.Join(" | ", Lines(d, "Properties"))); + Check(d.Bars.Count == 1 && d.Bars[0].Kind == AppraiseBarKind.Mana && d.Bars[0].Current == 1234 && d.Bars[0].Max == 2000, "the mana bar"); + } + + private static void AppraiseCaster() + { + var o = Item(0x8000, (45, 0x10)); + o.Floats[144] = 0.05; o.Floats[152] = 1.15; o.Floats[150] = 1.10; + AppraisalDoc d = AppraisalText.Build(o); + var c = Lines(d, "Caster"); + Check(c.Contains("Bonus to Mana Conversion: +5%."), "mana conversion: " + string.Join(" | ", c)); + Check(c.Contains("Damage bonus for Fire spells: +15% vs. Monsters, +3.75% vs. Players."), "elemental bonus"); + Check(c.Contains("Bonus to Magic Defense: +10%."), "magic defense"); + } + + private static void AppraiseCreatureAndPlayer() + { + var m = Item(0x10, (25, 112), (2, 1)); + m.Name = "Olthoi Soldier"; + m.Vitals = (500, 1000, 200, 400, 0, 0); + m.HealthRatio = 0.4f; + m.Attributes = new uint[] { 200, 180, 190, 210, 100, 90 }; + m.EnchantBits = (1u << 0) | (1u << 16) | (1u << 3); // Strength up, Coordination down + AppraisalDoc d = AppraisalText.Build(m); + Check(d.IsCreature, "a creature"); + Eq(d.Kind, "Level 112 · Olthoi", "creature kind"); + Check(d.Bars.Count == 2 && d.Bars[0].Label == "Health" && Math.Abs(d.Bars[0].Ratio - 0.4f) < 1e-6 && d.Bars[1].Label == "Stamina", "health (the server's ratio) and stamina; no mana bar without max mana"); + Check(d.Attributes.Count == 6 && d.Attributes[0] == ("Strength", 200u, true, true) && d.Attributes[3] == ("Coordination", 210u, true, false), "attributes and their buffs"); + Check(d.Facts.Count == 0, "no value or burden for a creature"); + + var p = Item(0x10, (25, 275), (188, 1), (113, 1), (134, 4), (30, 5)); + p.IsPlayer = true; + p.Strings[2] = "the Bold"; p.Strings[47] = "Test Allegiance"; + AppraisalDoc pd = AppraisalText.Build(p); + Eq(pd.Kind, "Level 275 · Aluvian Male", "player kind"); + var c = Lines(pd, "Character"); + Check(c.Contains("Title: the Bold") && c.Contains("Player Killer") && c.Contains("Allegiance: Test Allegiance") && c.Contains("Rank: 5"), "character lines: " + string.Join(" | ", c)); + + var unknown = Item(0x10); + unknown.Identified = false; + AppraisalDoc ud = AppraisalText.Build(unknown); + Check(ud.Sections.Any(s => s.Lines.Any(l => l.Text.StartsWith("Not assessed yet", StringComparison.Ordinal))), "an unassessed creature says so"); + } + + private static void AppraiseWordsAndRaw() + { + Eq(AppraisalText.WieldLine(8, 0x0B, 3), "Wield requires specialized Sword", "training requirement"); + Eq(AppraisalText.WieldLine(3, 1, 200), "Wield requires Strength 200", "attribute requirement"); + Eq(AppraisalText.WieldLine(12, 0, 3), "Wield requires Sho race", "heritage requirement"); + Eq(AppraisalText.SpeedName(10), "Very Fast", "speed 10"); + Eq(AppraisalText.SpeedName(80), "Very Slow", "speed 80"); + Eq(AppraisalText.Pct(0.0375), "+3.75%", "a fractional percent"); + Eq(AppraisalText.Pct(-0.05), "-5%", "a negative percent"); + Eq(AppraisalText.Coverage(0x4000 | 0x8000 | 0x10000), "Head, Hands, Feet", "coverage order"); + + var o = Item(0x8, (19, 10)); + o.Strings[16] = "A long description."; + o.Floats[5] = -0.05; + o.DataIds[37] = 0x21; // ItemSkillLimit: Life Magic + o.Ints[115] = 250; + o.InstanceIds[2] = 0x5000_0001; + o.Spells.Add(6); + AppraisalDoc d = AppraisalText.Build(o); + Eq(d.Description, "A long description.", "the long description"); + Check(Lines(d, "Requirements").Contains("Activation requires Life Magic: 250"), "activation skill"); + Check(d.Raw.Any(r => r.Kind == "Int" && r.Key == 19 && r.Name == "Value" && r.Value == "10"), "raw: an int by name"); + Check(d.Raw.Any(r => r.Kind == "Float" && r.Name == "ManaRate" && r.Value == "-0.05"), "raw: a float"); + Check(d.Raw.Any(r => r.Kind == "InstanceId" && r.Value == "0x50000001"), "raw: an instance id"); + Check(d.Raw.Any(r => r.Kind == "Spell" && r.Name == "Heal Self I"), "raw: the spell by name"); + int ints = d.Raw.Count(r => r.Kind == "Int"); + Eq(ints, o.Ints.Count, "every int listed once"); + string text = d.ToText(); + Check(text.StartsWith("Test Item", StringComparison.Ordinal) && text.Contains("Value: 10") && text.Contains("A long description."), "copy as text"); + } + + private static void AppraiseCommand() + { + DefCommand c = DefCommandParser.Parse("appraisal"); + Check(c.Verb == DefVerb.Appraisal && c.Text == "", "/rdef appraisal"); + c = DefCommandParser.Parse("appraise pin"); + Check(c.Verb == DefVerb.Appraisal && c.Text == "pin", "/rdef appraise pin"); + c = DefCommandParser.Parse("examine 0x80001234"); + Check(c.Verb == DefVerb.Appraisal && c.Text == "0x80001234", "/rdef examine "); + c = DefCommandParser.Parse("appraisal popout"); + Check(c.Verb == DefVerb.Appraisal && c.Text == "popout", "/rdef appraisal popout"); + + // Pop out / dock answers. + Check(DefReplies.PoppedOut("Appraisal window", 1).Ok && DefReplies.PoppedOut("Appraisal window", 1).Text.Contains("popped out"), "popped out"); + Check(DefReplies.PoppedOut("Appraisal window", 0).Ok && DefReplies.PoppedOut("Appraisal window", 0).Text.Contains("docked"), "docked"); + Check(!DefReplies.PoppedOut("Appraisal window", -1).Ok && DefReplies.PoppedOut("Appraisal window", -1).Text.Contains("open it first"), "not open: says to open it"); + + // The pin, in the character's file. + var d = new DefData(); + d.Settings.AppraisalPinned = true; + Check(DefStore.Parse(System.Text.Json.JsonDocument.Parse(DefStore.ToJson(d)).RootElement).Settings.AppraisalPinned, "pinned: saved and read"); + Check(!DefStore.Parse(System.Text.Json.JsonDocument.Parse("{\"settings\":{\"quantityBox\":true}}").RootElement).Settings.AppraisalPinned, "a file from before: not pinned"); + } + } +} diff --git a/Tools/RynthDefective.Tests/Program.cs b/Tools/RynthDefective.Tests/Program.cs index a727033..2efed92 100644 --- a/Tools/RynthDefective.Tests/Program.cs +++ b/Tools/RynthDefective.Tests/Program.cs @@ -130,6 +130,12 @@ namespace RynthDefective.Tests Run("day/night: the same as RynthAi's meta expressions, a countdown with no jumps", ClockMatchesRynthAi); Run("day/night: the countdown text (23m, 4m 10s, 45s)", ClockCountdownText); Run("day/night: the window's view and tooltip, /rdef daynight and its answers", ClockWindowAndCommand); + Run("appraisal: a weapon's lines (skill, damage, speed, bonuses, slayer, wield, workmanship, set, ratings)", AppraiseWeapon); + Run("appraisal: armor's protections and coverage, mana, spellcraft, the flags", AppraiseArmorAndMana); + Run("appraisal: a caster's bonuses", AppraiseCaster); + Run("appraisal: a creature's bars and attributes, a player's lines", AppraiseCreatureAndPlayer); + Run("appraisal: retail words, activation skill, description, every property, copy", AppraiseWordsAndRaw); + Run("appraisal: /rdef appraisal parsing and the pin in the file", AppraiseCommand); } finally { diff --git a/Tools/RynthDefective.Tests/ReplyTests.cs b/Tools/RynthDefective.Tests/ReplyTests.cs index 71df159..724b8df 100644 --- a/Tools/RynthDefective.Tests/ReplyTests.cs +++ b/Tools/RynthDefective.Tests/ReplyTests.cs @@ -108,6 +108,7 @@ namespace RynthDefective.Tests ("daynight", DefVerb.DayNight), ("daynight show", DefVerb.DayNight), ("daynight hide", DefVerb.DayNight), ("bars", DefVerb.Bars), ("bars add", DefVerb.Bars), ("bars remove 2", DefVerb.Bars), ("bars slots 2 12", DefVerb.Bars), ("bars show 3", DefVerb.Bars), ("shortcuts clearbusy on", DefVerb.Shortcuts), ("shortcuts clearbusy", DefVerb.Shortcuts), + ("appraisal", DefVerb.Appraisal), ("appraisal pin", DefVerb.Appraisal), ("appraisal popout", DefVerb.Appraisal), ("examine 0x80001234", DefVerb.Appraisal), }; var seen = new HashSet(); foreach (var (typed, verb) in right) diff --git a/Tools/RynthDefective.Tests/RynthDefective.Tests.csproj b/Tools/RynthDefective.Tests/RynthDefective.Tests.csproj index 50a7ff2..3dd07e7 100644 --- a/Tools/RynthDefective.Tests/RynthDefective.Tests.csproj +++ b/Tools/RynthDefective.Tests/RynthDefective.Tests.csproj @@ -53,6 +53,9 @@ + + + diff --git a/Tools/RynthNav.RouteTests/CustomPortalTests.cs b/Tools/RynthNav.RouteTests/CustomPortalTests.cs new file mode 100644 index 0000000..247b913 --- /dev/null +++ b/Tools/RynthNav.RouteTests/CustomPortalTests.cs @@ -0,0 +1,128 @@ +using System; +using System.Collections.Generic; +using RynthCore.Plugin.RynthNav; +using RynthNav.Routing; + +namespace RynthNav.RouteTests; + +// A custom server's own portals (CustomPortals.cs, 2026-11-27): written down by a scan, learned by taking them, per +// server, saved, and planned with on our own graph (PortalRoute) next to the world data's portals. +// Spotted by SilentKelpie (Forgejo rynth PR #12); re-implemented here. +internal static partial class Program +{ + private static void RunCustomPortals() + { + Run(nameof(CustomScanAndLearn), CustomScanAndLearn); + Run(nameof(CustomKnownPortalNotRelearned), CustomKnownPortalNotRelearned); + Run(nameof(CustomPerServerForgetClear), CustomPerServerForgetClear); + Run(nameof(CustomSaveAndMerge), CustomSaveAndMerge); + Run(nameof(CustomPortalsRoute), CustomPortalsRoute); + } + + private static readonly List BuiltIn = new() { new(10.0, 10.0, -30.0, -30.0, "Portal to the World Data") }; + private static readonly DateTime T0 = new(2026, 11, 27, 12, 0, 0, DateTimeKind.Utc); + + private static void CustomScanAndLearn() + { + var s = new CustomPortalStore(); + int v0 = s.Version; + Check(s.Saw("Test Server", "Portal to the Spire", 9001, 0xA9B40021, 12.5, 30.25, 40.0, 20.0, 30.0, BuiltIn, T0) == CustomSeen.Added, "a scan adds a new one"); + Check(s.Version > v0, "and it's a change to save"); + Check(s.Saw("Test Server", "Portal to the Spire", 9001, 0xA9B40021, 12.5, 30.25, 40.0, 20.0, 30.0, BuiltIn, T0) == CustomSeen.Refreshed, "seen again: refreshed"); + Check(s.Saw("Test Server", "Portal to the World Data", 0, 0xA9B40022, 1, 1, 0, 10.02, 10.01, BuiltIn, T0) == CustomSeen.BuiltIn, "the world data has it: left alone"); + Check(s.Saw("Test Server", "Some Other Portal", 0, 0xA9B40022, 1, 1, 0, 10.01, 10.0, BuiltIn, T0) == CustomSeen.BuiltIn, "any portal right on a world-data one: left alone"); + var (saved, routable) = s.Counts("Test Server"); + Check(saved == 1 && routable == 0, $"one saved, not routable until taken ({saved}, {routable})"); + Check(s.Links("Test Server").Count == 0, "no link yet"); + + CustomLearn r = s.Learned("Test Server", "Portal to the Spire", 9001, 0xA9B40021, 12.5, 30.25, 40.0, 20.0, 30.0, + true, -5.5, 60.25, 0, BuiltIn, T0.AddMinutes(1), out CustomPortal? p); + Check(r == CustomLearn.New && p != null && p.Routable, "taking it learns the landing"); + List links = s.Links("Test Server"); + Check(links.Count == 1 && links[0].Name == "Portal to the Spire" && links[0].DstNs == -5.5 && links[0].DstEw == 60.25, "a route link"); + Check(links[0].HasSpot && links[0].Cell == 0xA9B40021 && links[0].Z == 40.0, "the link walks to where the object stood"); + Check(!links[0].HasRules, "open to anyone (a refusal is learned as for any portal)"); + + // A portal never scanned: added when taken. + r = s.Learned("Test Server", "Hidden Portal", 0, 0xA9B40023, 2, 2, 0, 21.0, 31.0, true, 50, 50, 0, BuiltIn, T0, out p); + Check(r == CustomLearn.New && s.Counts("Test Server").Saved == 2, "an unscanned one is added when taken"); + // Into a dungeon: kept, listed, not routed. + r = s.Learned("Test Server", "Pit Portal", 0, 0xA9B40024, 3, 3, 0, 22.0, 32.0, false, 0, 0, 0x01230105, BuiltIn, T0, out p); + Check(r == CustomLearn.New && p != null && !p.Routable && p.Where.Contains("0123"), "a dungeon landing: kept, not routed"); + Check(s.Links("Test Server").Count == 2, "two map-to-map links"); + // A world-data portal taken: nothing learned. + r = s.Learned("Test Server", "Portal to the World Data", 0, 0xA9B40022, 1, 1, 0, 10.0, 10.0, true, -30, -30, 0, BuiltIn, T0, out p); + Check(r == CustomLearn.BuiltIn && p == null, "a world-data portal isn't learned"); + // Landing right beside it: not a teleport through it. + r = s.Learned("Test Server", "Fountain Portal", 0, 0xA9B40025, 1, 1, 0, 23.0, 33.0, true, 23.05, 33.05, 0, BuiltIn, T0, out p); + Check(r == CustomLearn.NotAPortal && s.Counts("Test Server").Saved == 3, "a landing beside it isn't learned"); + } + + private static void CustomKnownPortalNotRelearned() + { + var s = new CustomPortalStore(); + s.Learned("S", "Portal A", 0, 0xA9B40021, 1, 1, 0, 20.0, 30.0, true, -5.5, 60.25, 0, null, T0, out _); + int v = s.Version; + CustomLearn r = s.Learned("S", "Portal A", 0, 0xA9B40021, 1, 1, 0, 20.02, 30.01, true, -5.52, 60.3, 0, null, T0.AddHours(1), out _); + Check(r == CustomLearn.AlreadyKnown && s.Version == v, "taken again, same landing: already known, nothing to write"); + r = s.Learned("S", "Portal A", 0, 0xA9B40021, 1, 1, 0, 20.0, 30.0, true, 40.0, -40.0, 0, null, T0.AddHours(2), out CustomPortal? p); + Check(r == CustomLearn.LandingChanged && p!.DestNs == 40.0 && s.Version > v, "a new landing: updated"); + } + + private static void CustomPerServerForgetClear() + { + var s = new CustomPortalStore(); + s.Learned("One", "Gate", 0, 0xA9B40021, 1, 1, 0, 20.0, 30.0, true, -5, 60, 0, null, T0, out _); + s.Learned("One", "Gate of Ash", 0, 0xA9B40022, 1, 1, 0, 25.0, 35.0, true, -15, 70, 0, null, T0, out _); + s.Learned("Two", "Gate", 0, 0xA9B40021, 1, 1, 0, 20.0, 30.0, true, 45, -60, 0, null, T0, out _); + Check(s.Links("One").Count == 2 && s.Links("two").Count == 1, "each server has its own (the name in any case)"); + Check(s.Links("Three").Count == 0, "another server has none"); + Check(s.Forget("One", "Gate") == 1 && s.Links("One").Count == 1, "forget: the exact name only, when there is one"); + Check(s.Forget("One", "ash") == 1 && s.Links("One").Count == 0, "forget: else the names containing it"); + Check(s.Forget("One", "Nothing") == 0, "forget: none"); + Check(s.Clear("Two") == 1 && s.All.Count == 0, "clear: that server's all"); + } + + private static void CustomSaveAndMerge() + { + var s = new CustomPortalStore(); + s.Saw("Test Server", "Scanned Only", 77, 0xA9B40021, 10.5, 20.25, 30.0, 20.0, 30.0, null, T0); + s.Learned("Test Server", "To Town", 78, 0xA9B40022, 1, 2, 3, 21.0, 31.0, true, -5.5, 60.25, 0, null, T0, out _); + s.Learned("Other", "Down", 0, 0xA9B40023, 1, 2, 3, 22.0, 32.0, false, 0, 0, 0x01230105, null, T0, out _); + string text = s.Serialize(); + CustomPortalStore back = CustomPortalStore.Parse(text); + Check(back.All.Count == 3, $"three read back ({back.All.Count})"); + CustomPortal? a = back.Find("Test Server", "Scanned Only", 20.0, 30.0), b = back.Find("Test Server", "To Town", 21.0, 31.0), c = back.Find("Other", "Down", 22.0, 32.0); + Check(a != null && !a.DestKnown && a.Wcid == 77 && a.Cell == 0xA9B40021 && a.X == 10.5 && a.Y == 20.25 && a.Z == 30.0, "a scanned one, with its spot"); + Check(b != null && b.Routable && b.DestNs == -5.5 && b.DestEw == 60.25 && b.LearnedUtc == T0, "a learned one, with its landing"); + Check(c != null && c.DestKnown && !c.DestOnMap && c.DestCell == 0x01230105, "a dungeon landing"); + Check(CustomPortalStore.Parse("# notes\n\nbad line\nS\tN\tx\n").All.Count == 0, "notes and bad lines are skipped"); + Check(CustomPortalStore.Clean("A\tB\nC ") == "A B C", "names are one field"); + + // Another client's file: its new portal and later landing are taken in, a portal this one forgot isn't. + var mine = CustomPortalStore.Parse(text); + mine.Forget("Test Server", "Scanned Only"); + var disk = CustomPortalStore.Parse(text); + disk.Learned("Test Server", "To Town", 78, 0xA9B40022, 1, 2, 3, 21.0, 31.0, true, 44.0, 44.0, 0, null, T0.AddDays(1), out _); + disk.Learned("Test Server", "New Elsewhere", 0, 0xA9B40024, 1, 2, 3, 26.0, 36.0, true, -40, 40, 0, null, T0, out _); + mine.MergeFrom(disk); + Check(mine.Find("Test Server", "Scanned Only", 20.0, 30.0) == null, "what this client forgot stays forgotten"); + Check(mine.Find("Test Server", "New Elsewhere", 26.0, 36.0) != null, "another client's new portal is taken in"); + Check(mine.Find("Test Server", "To Town", 21.0, 31.0)!.DestNs == 44.0, "a landing learned later wins"); + } + + private static void CustomPortalsRoute() + { + // The world data has no way across; the server's own portal does: the plan takes it (our graph, PortalRoute). + var s = new CustomPortalStore(); + s.Learned("S", "Server Portal", 0, 0xA9B40021, 1, 1, 0, 0.5, 0.5, true, 39.5, 39.5, 0, BuiltIn, T0, out _); + var portals = new List(BuiltIn); + portals.AddRange(s.Links("S")); + var steps = PortalRoute.Plan(portals, null, 0, 0, 40, 40, out _, out int used); + Check(used == 1 && steps.Count == 2 && steps[0].UsePortal && steps[0].Label == "Server Portal", "the custom portal is taken"); + Near(steps[0].LandNs, 39.5, 1e-9, "it lands where it was learned to"); + // Without it (custom off, or another server): walk. + steps = PortalRoute.Plan(BuiltIn, null, 0, 0, 40, 40, out _, out used); + Check(used == 0, "without it: no portal"); + } +} diff --git a/Tools/RynthNav.RouteTests/FollowTests.cs b/Tools/RynthNav.RouteTests/FollowTests.cs new file mode 100644 index 0000000..e9c7128 --- /dev/null +++ b/Tools/RynthNav.RouteTests/FollowTests.cs @@ -0,0 +1,84 @@ +using System; +using RynthCore.Plugin.RynthNav; + +namespace RynthNav.RouteTests; + +// Walks keep to the trip's own path (TripFollow.cs, 2026-11-27): each re-plan aims a few yards along the walk the +// markers draw; off it, back to it; progress never goes back, so a walk that doubles back isn't cut across. +// Spotted by SilentKelpie (Forgejo rynth PR #12); re-implemented here. +internal static partial class Program +{ + private static void RunFollow() + { + Run(nameof(FollowAimsAlongTheWalk), FollowAimsAlongTheWalk); + Run(nameof(FollowRejoinsWhenOff), FollowRejoinsWhenOff); + Run(nameof(FollowNeverCutsBack), FollowNeverCutsBack); + Run(nameof(FollowHeights), FollowHeights); + } + + // An L: 100 yd east, then 100 yd north. + private static WorldPt[] LWalk() => new[] { new WorldPt(1000, 1000, 0), new WorldPt(1100, 1000, 0), new WorldPt(1100, 1100, 0) }; + + private static void FollowAimsAlongTheWalk() + { + var f = new TripFollow(1, 0, LWalk()); + Near(f.Length, 200, 1e-6, "the walk's length"); + WorldPt a = f.Aim(1000, 1000, out double off, out bool atEnd); + Near(a.X, 1000 + TripFollow.AheadUnits, 1e-6, "from the start: AheadUnits along"); + Check(!atEnd && off < 1e-6, "on the walk, not at its end"); + // At the corner, the aim goes round it (north), not straight on east across the field. + a = f.Aim(1090, 1000, out off, out atEnd); + Near(a.X, 1100, 1e-6, "past the corner: on the north leg (x)"); + Near(a.Y, 1000 + (90 + TripFollow.AheadUnits - 100), 1e-6, "past the corner: on the north leg (y)"); + // A little to the side of the walk still counts as on it. + a = f.Aim(1100 - 5, 1050, out off, out atEnd); + Near(off, 5, 1e-6, "5 yd to the side"); + Near(a.Y, 1050 + TripFollow.AheadUnits, 1e-6, "aims along from the nearest point"); + // Near the end: the step's own point, and planned to it as before. + a = f.Aim(1100, 1090, out off, out atEnd); + Check(atEnd && a.X == 1100 && a.Y == 1100, "near the end: the end itself"); + Near(f.Progress, 190, 1e-6, "progress is where you are on it"); + } + + private static void FollowRejoinsWhenOff() + { + var f = new TripFollow(1, 0, LWalk()); + f.Aim(1050, 1000, out _, out _); + // Knocked 30 yd off the walk: aim back at it, a little past its nearest point, not 28 yd ahead. + WorldPt a = f.Aim(1060, 970, out double off, out bool atEnd); + Near(off, 30, 1e-6, "30 yd off"); + Near(a.X, 1060 + TripFollow.RejoinUnits, 1e-6, "back to the walk, just past its nearest point"); + Near(a.Y, 1000, 1e-6, "on the walk"); + Near(f.Progress, 50, 1e-6, "progress doesn't move while off"); + Check(!atEnd, "not the end"); + } + + private static void FollowNeverCutsBack() + { + // A hairpin: 100 east, 10 north, 100 back west. From the start of the way back, the first leg is 10 yd away. + var hairpin = new[] { new WorldPt(0, 0, 0), new WorldPt(100, 0, 0), new WorldPt(100, 10, 0), new WorldPt(0, 10, 0) }; + var f = new TripFollow(1, 0, hairpin); + for (double x = 0; x <= 100; x += 10) f.Aim(x, 0, out _, out _); + f.Aim(100, 10, out _, out _); + f.Aim(80, 10, out _, out _); + Near(f.Progress, 130, 1e-6, "on the way back, 130 yd along"); + // Standing between the legs, nearer the first: the first leg is behind the window, so it isn't picked. + WorldPt a = f.Aim(60, 4, out double off, out _); + Check(Math.Abs(off - 6) < 1e-6, $"measured from the way back (6 yd), not the first leg (4 yd): {off:F2}"); + Check(a.Y == 10 && a.X < 60, $"the aim keeps going west on the way back ({a.X:F1}, {a.Y:F1})"); + Check(f.Progress >= 130, "progress never goes back"); + // Two points are the least a walk is. + bool threw = false; + try { _ = new TripFollow(1, 0, new[] { new WorldPt(0, 0, 0) }); } catch (ArgumentException) { threw = true; } + Check(threw, "one point isn't a walk"); + } + + private static void FollowHeights() + { + var ramp = new[] { new WorldPt(0, 0, 10), new WorldPt(100, 0, 30) }; + var f = new TripFollow(1, 0, ramp); + Near(f.At(50).H, 20, 1e-6, "the height between the points"); + var flat = new[] { new WorldPt(0, 0, double.NaN), new WorldPt(100, 0, double.NaN) }; + Check(double.IsNaN(new TripFollow(1, 0, flat).At(50).H), "no heights given: none made up (the walker uses its own)"); + } +} diff --git a/Tools/RynthNav.RouteTests/InsideTests.cs b/Tools/RynthNav.RouteTests/InsideTests.cs new file mode 100644 index 0000000..05e828f --- /dev/null +++ b/Tools/RynthNav.RouteTests/InsideTests.cs @@ -0,0 +1,133 @@ +using System; +using System.Collections.Generic; +using RynthCore.Plugin.RynthNav; + +namespace RynthNav.RouteTests; + +// A go to someone INSIDE a dungeon (InsidePlaces.cs, Atlas.FindInside, Entrance.PortalInto; 2026-11-27): +// which name means someone inside, and the way in: already there, a portal on the map, a recall you know. +// Spotted by SilentKelpie (Forgejo rynth PR #12); re-implemented here. +internal static partial class Program +{ + private static void RunInside() + { + Run(nameof(InsideFindsPeopleInDungeons), InsideFindsPeopleInDungeons); + Run(nameof(InsideMapWinsWhenItAnswers), InsideMapWinsWhenItAnswers); + Run(nameof(InsideWayIn), InsideWayIn); + Run(nameof(InsideAlternatives), InsideAlternatives); + Run(nameof(InsideLines), InsideLines); + } + + // Landblock 0x0A0B: the Deep Vault (two portals in on the map, one needs a quest; a third is destroyed). + // Landblock 0x0C0D: reached only by Vault Recall. Holtburg is on the map; "Gate Keeper" is both a map NPC + // in Holtburg and a person inside. + private const string InsideJson = """ + {"generated":"test","locations":[ + {"id":1,"name":"Holtburg","type":"Town","cell":"A9B40001","place":"outdoor","ns":42.1,"ew":33.6}, + {"id":2,"name":"Quest Portal to the Deep Vault","type":"Portal","cell":"A9B30001","place":"outdoor","ns":41.9,"ew":33.5,"quest":true, + "dest":{"cell":"0A0B0110","place":"dungeon","name":"Deep Vault"}}, + {"id":3,"name":"Deep Vault Portal","type":"Portal","cell":"A8B30001","place":"outdoor","ns":40.0,"ew":32.0, + "dest":{"cell":"0A0B0110","place":"dungeon","name":"Deep Vault"}}, + {"id":4,"name":"Destroyed Deep Vault Portal","type":"Portal","cell":"A9B40002","place":"outdoor","ns":42.0,"ew":33.6, + "dest":{"cell":"0A0B0110","place":"dungeon","name":"Deep Vault"}}, + {"id":5,"name":"Brannoc the Smith","type":"NPC","cell":"0A0B0123","place":"dungeon"}, + {"id":6,"name":"Brannoc","type":"Vendor","cell":"0C0D0101","place":"dungeon"}, + {"id":7,"name":"Ulla","type":"NPC","cell":"0C0D0140","place":"dungeon"}, + {"id":8,"name":"Inner Portal","type":"Portal","cell":"0A0B0130","place":"dungeon"}, + {"id":9,"name":"Gate Keeper","type":"NPC","cell":"A9B40003","place":"outdoor","ns":42.2,"ew":33.7}, + {"id":10,"name":"Gate Keeper","type":"NPC","cell":"0A0B0150","place":"dungeon"}, + {"id":11,"name":"Brannocka","type":"NPC","cell":"0A0B0151","place":"dungeon"}, + {"id":12,"name":"Holtburg Guard","type":"NPC","cell":"0A0B0152","place":"dungeon"}, + {"id":13,"name":"Holtburg Guard Tower","type":"Landmark","cell":"A9B40004","place":"outdoor","ns":42.3,"ew":33.8} + ],"recalls":[ + {"spell":4084,"name":"Vault Recall","cell":"0C0D0101","place":"dungeon"}, + {"spell":2020,"name":"Recall Holtburg","cell":"A9B40001","place":"outdoor","ns":42.1,"ew":33.6} + ]} + """; + + private static void InsideFindsPeopleInDungeons() + { + Atlas atlas = Atlas.Parse(InsideJson); + Check(atlas.Recalls[0].Cell == "0C0D0101", "a recall's landing cell is read"); + AtlasLocation? d = atlas.FindInside("Brannoc the Smith"); + Check(d?.Id == 5, $"the exact name (got {d?.Id})"); + d = atlas.FindInside("brannoc"); + Check(d?.Id == 6, $"exact beats starts-with (got {d?.Id})"); + d = atlas.FindInside("Brannoc", hereLb: 0x0A0B); + Check(d?.Id == 5, $"one in the landblock you're in wins (got {d?.Id})"); + Check(atlas.FindInside("Bran") == null, "a part of a word isn't a name (Bran, not Brannoc / Brannocka)"); + Check(atlas.FindInside("Inner Portal") == null, "a portal inside isn't someone to go to"); + Check(atlas.FindInside("Ul") == null, "two letters are too few"); + Check(atlas.FindInside("Holtburg")?.Id == 12, "a whole-word start counts inside (Holtburg Guard); Prefer leaves a map place to the map"); + AtlasLocation? p = Entrance.PortalInto(atlas, 0x0A0B, true, 42.1, 33.6); + Check(p?.Id == 3, $"the portal in: no quest first beats nearer, never the destroyed one (got {p?.Id})"); + Check(Entrance.PortalInto(atlas, 0x0C0D, true, 42, 33) == null, "no portal on the map into the other dungeon"); + } + + private static void InsideMapWinsWhenItAnswers() + { + Atlas atlas = Atlas.Parse(InsideJson); + // The map's exact name wins: Gate Keeper is in Holtburg as well as inside. + Check(InsidePlaces.Prefer(atlas, "Gate Keeper", true, 42, 33, 0, out bool onMap) == null && onMap, "an exact map name wins"); + // Someone inside by their exact name beats a map place that only half matches ("Holtburg Guard" vs Holtburg). + AtlasLocation? g = InsidePlaces.Prefer(atlas, "Holtburg Guard", true, 42, 33, 0, out onMap); + Check(g?.Id == 12 && onMap, $"an exact inside name beats a part-match on the map, Holtburg Guard Tower (got {g?.Id})"); + // Only a starts-with match inside, and a whole-word match on the map: the map. + Check(InsidePlaces.Prefer(atlas, "Holtburg Gu", true, 42, 33, 0, out onMap) == null, "a partial name inside loses to the map's match"); + g = InsidePlaces.Prefer(atlas, "Ulla", true, 42, 33, 0, out onMap); + Check(g?.Id == 7 && !onMap, $"nothing on the map: the one inside (got {g?.Id})"); + Check(InsidePlaces.Prefer(atlas, "Holtburg", true, 42, 33, 0, out onMap) == null && onMap, "a town is the town"); + Check(InsidePlaces.Prefer(atlas, "Nobody Here", true, 42, 33, 0, out onMap) == null && !onMap, "no one: null, nothing on the map"); + } + + private static void InsideWayIn() + { + Atlas atlas = Atlas.Parse(InsideJson); + AtlasLocation smith = atlas.ById(5)!, ulla = atlas.ById(7)!; + var known = new HashSet { 4084 }; + const uint outdoors = 0xA9B4001A, inVault = 0x0A0B0105, inOther = 0x0C0D0120; + + InsideWay w = InsidePlaces.WayIn(atlas, smith, outdoors, true, 42.1, 33.6, known, true); + Check(w.Kind == InsideWayKind.Portal && w.Portal?.Id == 3 && w.Cell == 0x0A0B0123 && w.Dungeon == "Deep Vault", + $"on the map: the portal into the Deep Vault ({w.Kind}, {w.Portal?.Id}, {w.Cell:X8}, {w.Dungeon})"); + w = InsidePlaces.WayIn(atlas, smith, inVault, false, 0, 0, known, true); + Check(w.Kind == InsideWayKind.Here, "in that dungeon already: here"); + w = InsidePlaces.WayIn(atlas, smith, inOther, false, 0, 0, known, true); + Check(w.Kind == InsideWayKind.Portal && w.Portal?.Id == 3, "in another dungeon with no recall in: still the portal (the route out starts with a recall)"); + + w = InsidePlaces.WayIn(atlas, ulla, outdoors, true, 42, 33, known, true); + Check(w.Kind == InsideWayKind.Recall && w.Recall?.SpellId == 4084 && w.Dungeon == "where Vault Recall lands", + $"no portal in: the recall you know ({w.Kind}, {w.Dungeon})"); + w = InsidePlaces.WayIn(atlas, ulla, outdoors, true, 42, 33, new HashSet(), true); + Check(w.Kind == InsideWayKind.None && InsidePlaces.NoWayText(w).Contains("no portal on the map or recall you know"), "a recall you don't know: none"); + w = InsidePlaces.WayIn(atlas, ulla, outdoors, true, 42, 33, known, recallsOn: false); + Check(w.Kind == InsideWayKind.None, "recalls off: none"); + w = InsidePlaces.WayIn(atlas, ulla, outdoors, true, 42, 33, null, true); + Check(w.Kind == InsideWayKind.None, "the spellbook not read yet: none"); + w = InsidePlaces.WayIn(atlas, ulla, inOther, false, 0, 0, known, true); + Check(w.Kind == InsideWayKind.Here && w.Cell == 0x0C0D0140, "Ulla's dungeon, where you are: here"); + } + + private static void InsideAlternatives() + { + Atlas atlas = Atlas.Parse(InsideJson); + Check(InsidePlaces.FromAlternatives(atlas, "Nobody || Ulla || Holtburg", true, 42, 33, 0)?.Id == 7, "the first inside candidate, before a later map one"); + Check(InsidePlaces.FromAlternatives(atlas, "Holtburg || Ulla", true, 42, 33, 0) == null, "a map place first: the usual go"); + Check(InsidePlaces.FromAlternatives(atlas, "10.0N, 20.0E || Ulla", true, 42, 33, 0) == null, "coordinates first: the usual go"); + Check(InsidePlaces.FromAlternatives(atlas, "Nobody || Nothing", true, 42, 33, 0) == null, "none at all: the usual go says why"); + } + + private static void InsideLines() + { + Check(InsidePlaces.Tail("Brannoc", 0x009C0270) == " (Brannoc is in cell 009C0270)", "the arrival line's tail"); + // A walk only by default (2026-11-27): RynthAi turns fighting, looting, buffing and the meta off for it. + Check(InsidePlaces.WalkCommand(0x009C0270, "Brannoc the Smith") == "/ra dunnav-to cell 009C0270 walkonly Brannoc the Smith", "RynthAi's walk to the cell, a walk only"); + Check(InsidePlaces.WalkCommand(0x009C0270, "") == "/ra dunnav-to cell 009C0270 walkonly", "no name: just the cell, a walk only"); + // Fight on the way in: the macro as set, as before. + Check(InsidePlaces.WalkCommand(0x009C0270, "Brannoc the Smith", fight: true) == "/ra dunnav-to cell 009C0270 Brannoc the Smith", "fight on the way in: no walkonly"); + Check(InsidePlaces.WalkCommand(0x009C0270, "", fight: true) == "/ra dunnav-to cell 009C0270", "fight, no name: just the cell"); + Atlas atlas = Atlas.Parse(InsideJson); + Check(InsidePlaces.DungeonName(atlas, 0x0A0B) == "Deep Vault", "named by the portals into it"); + Check(InsidePlaces.DungeonName(atlas, 0x0E0F) == "dungeon 0E0F", "unknown: its landblock"); + } +} diff --git a/Tools/RynthNav.RouteTests/Program.cs b/Tools/RynthNav.RouteTests/Program.cs index 587044d..30d7bdd 100644 --- a/Tools/RynthNav.RouteTests/Program.cs +++ b/Tools/RynthNav.RouteTests/Program.cs @@ -64,11 +64,15 @@ internal static partial class Program RunAutoRunGate(); RunRouteMaker(); RunSteering(); + RunStuckWatch(); RunWays(); RunArrival(); RunRealWalks(); RunTripTimes(); RunTargetSwitch(); + RunInside(); // someone inside a dungeon (InsideTests.cs) + RunFollow(); // walks keep to the trip's path (FollowTests.cs) + RunCustomPortals(); // a custom server's own portals (CustomPortalTests.cs) Console.WriteLine(); Console.WriteLine(_fails == 0 && _asserts > 0 diff --git a/Tools/RynthNav.RouteTests/RynthNav.RouteTests.csproj b/Tools/RynthNav.RouteTests/RynthNav.RouteTests.csproj index 65d78ab..1f6d62d 100644 --- a/Tools/RynthNav.RouteTests/RynthNav.RouteTests.csproj +++ b/Tools/RynthNav.RouteTests/RynthNav.RouteTests.csproj @@ -36,6 +36,8 @@ + + @@ -52,6 +54,12 @@ + + + + + + diff --git a/Tools/RynthNav.RouteTests/StuckWatchTests.cs b/Tools/RynthNav.RouteTests/StuckWatchTests.cs new file mode 100644 index 0000000..ea25e1a --- /dev/null +++ b/Tools/RynthNav.RouteTests/StuckWatchTests.cs @@ -0,0 +1,90 @@ +using System; +using RynthCore.Plugin.RynthNav; + +namespace RynthNav.RouteTests; + +// Is the walk blocked (StuckWatch)? A walk against a wall that ran a moment and turned a moment, +// swinging between headings, never ran 1.2 s in a row, so it was never blocked; it stood until the +// 30 s progress watchdog stopped the goto. Turning ticks now count too. +internal static partial class Program +{ + private static void RunStuckWatch() + { + Run(nameof(StuckRunningIntoAWall), StuckRunningIntoAWall); + Run(nameof(StuckRunTurnFlipFlop), StuckRunTurnFlipFlop); + Run(nameof(StuckTurningOnly), StuckTurningOnly); + Run(nameof(StuckNotWhileMoving), StuckNotWhileMoving); + Run(nameof(StuckNotWhenNotDriving), StuckNotWhenNotDriving); + } + + private const long StuckTickMs = 30; + + /// Ticks for : Check, then drive (running or not) as the walk does. True once blocked. + private static bool StuckTicks(StuckWatch w, ref long now, long ms, Func running, Func at, + bool drive = true) + { + long end = now + ms; + for (; now < end; now += StuckTickMs) + { + var (x, y) = at(now); + if (w.Check(now, x, y, out _, out _)) return true; + if (drive) w.Drove(running(now)); + } + return false; + } + + private static void StuckRunningIntoAWall() + { + var w = new StuckWatch(); + long now = 1_000_000; + bool stuck = StuckTicks(w, ref now, 1500, _ => true, _ => (10, 10)); + Check(stuck, "running and not moving for 1.2 s is blocked"); + } + + private static void StuckRunTurnFlipFlop() + { + // Run 300 ms, turn 300 ms, over and over, against a wall: it used to start the watch again at + // every turn and was never blocked. + var w = new StuckWatch(); + long now = 1_000_000, start = now; + bool stuck = StuckTicks(w, ref now, 4000, t => (t - start) / 300 % 2 == 0, _ => (10, 10)); + Check(stuck, "running and turning by turns against a wall is blocked"); + Check(now - start <= StuckWatch.RunWindowMs + 2 * StuckTickMs, $"within a run window ({now - start} ms)"); + } + + private static void StuckTurningOnly() + { + var w = new StuckWatch(); + long now = 1_000_000, start = now; + bool early = StuckTicks(w, ref now, 1500, _ => false, _ => (10, 10)); + Check(!early, "turning on the spot for 1.5 s is not blocked (a half turn takes about a second)"); + bool stuck = StuckTicks(w, ref now, 3000, _ => false, _ => (10, 10)); + Check(stuck, "turning on the spot for 3 s is blocked"); + Check(now - start >= StuckWatch.TurnWindowMs, $"only after the turn window ({now - start} ms)"); + } + + private static void StuckNotWhileMoving() + { + var w = new StuckWatch(); + long now = 1_000_000, start = now; + // 4 u/s, running and turning by turns: always getting somewhere. + bool stuck = StuckTicks(w, ref now, 5000, t => (t - start) / 300 % 2 == 0, t => (10 + (t - start) * 0.004, 10)); + Check(!stuck, "a walk that moves is never blocked"); + } + + private static void StuckNotWhenNotDriving() + { + // Standing (waiting for a plan) between drives starts the watch again each time. + var w = new StuckWatch(); + long now = 1_000_000; + bool stuck = false; + for (int i = 0; i < 10 && !stuck; i++) + { + stuck |= StuckTicks(w, ref now, 600, _ => true, _ => (10, 10)); + stuck |= StuckTicks(w, ref now, 300, _ => true, _ => (10, 10), drive: false); + } + Check(!stuck, "short drives with standing between them are not blocked"); + w.Reset(); + Check(!w.Check(now, 10, 10, out double moved, out long windowMs) && moved == 0 && windowMs == 0, "after a reset: no window"); + } +} diff --git a/Tools/RynthOracle.Tests/GuideTabTests.cs b/Tools/RynthOracle.Tests/GuideTabTests.cs new file mode 100644 index 0000000..135fcca --- /dev/null +++ b/Tools/RynthOracle.Tests/GuideTabTests.cs @@ -0,0 +1,155 @@ +using System; +using System.Text; +using RynthCore.Plugin.RynthOracle; +using RynthCore.Plugin.RynthOracle.Data; +using RynthCore.Plugin.RynthOracle.Ui; +using RynthCore.Plugin.RynthOracle.Views; +using RynthCore.Plugin.Shared; + +namespace RynthOracle.Tests +{ + /// + /// The Guide tab (2026-11-27): the lists (All / Story / Dailies / Weekly, Kill Tasks, Society, Contracts), the four + /// states, kill counts from /myquests and chat, "first time / done before", the server plugin's guide over the + /// wiki's, and every page through the engine's parser. The guide is the made-up one of QuestGuideTests. + /// + internal static partial class Program + { + private static unsafe void GuideTab() + { + OracleContext c = Context(); + long now = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + c.Flags.OnChatLine($"TestErrandStarted - 1 solves ({now - 3600})\"Started\" -1 72000", 1000); + c.Flags.OnChatLine($"KillTaskSampleBeasts_0101 - 12 solves ({now - 600})\"Beasts\" 50 0", 1000); + c.Flags.OnChatLine($"KillTaskOtherThings_0202 - 3 solves ({now - 600})\"Others\" 10 0", 1000); + c.Flags.Tick(6000); + c.UtcNow = DateTime.UtcNow; + c.Wiki.Use(SampleGuide()); + GuideProgress p = c.Progress; + + // ── The four states ── + QuestGuide g = c.Wiki.Guide; + GuideQuest daily = g.Find("Test Daily Errand")!; + GuideProgress.Row r = p.RowOf(daily, c.UtcNow); + Check(r.State == GuideState.PartWaiting && r.Held == 1 && r.All == 3 && r.Status.StartsWith("1/3 wait ") && r.Tip.Contains("2 still to get"), + $"one stamp of three held, its timer running: part done, waiting ({r.Status})"); + Check(p.StateOf(daily, "TestErrandStarted", c.UtcNow) == StampState.Done && p.StateOf(daily, "TestErrandFang", c.UtcNow) == StampState.Missing, + "a held stamp inside its timer counts; a missing one doesn't"); + Check(p.StateOf(daily, "testerrandstarted", c.UtcNow) == StampState.Done, "a stamp matches its flag by any spelling"); + Check(p.StateOf(daily, "TestErrandStarted", c.UtcNow.AddDays(1)) == StampState.Earlier, "after its timer it was done on an earlier run"); + Check(p.RowOf(daily, c.UtcNow.AddDays(1)).State == GuideState.PartReady, "the timer up: part done, ready"); + Check(c.OnGuideChatLine("You've stamped TestErrandFang!", c.UtcNow) && c.SessionStamps.Contains("testerrandfang"), "a stamp line in chat is held at once"); + Check(p.RowOf(daily, c.UtcNow).Held == 2, "two of three held now"); + c.OnGuideChatLine("You've stamped TestErrandDone!", c.UtcNow); + GuideProgress.Row full = p.RowOf(daily, c.UtcNow); + Check(full.State == GuideState.Done && full.HideWhenDone && full.Status.StartsWith("Done "), "every stamp held, its timer running: done, hidden by Hide done"); + GuideQuest story = g.Find("Test Story Quest")!; + Check(p.RowOf(story, c.UtcNow).Status == "no stamps" && p.RowOf(story, c.UtcNow, flagDone: true).State == GuideState.Done + && p.RowOf(story, c.UtcNow, flagDone: false).State == GuideState.NotDone, "a quest without stamps: the quest list's flag, else unknown"); + Check(GuideProgress.RepeatText(daily).StartsWith("Daily (every 20h") && GuideProgress.RepeatText(story) == "One-time", "the timer text"); + + // ── Kill tasks ── + GuideQuest kt = g.Find("Sample Beast Kill Task")!; + GuideProgress.Kill k = p.KillOf(kt, c.UtcNow); + Check(k.State == KillState.Counting && k.Kills == 12 && k.Goal == 50 && string.Equals(k.Counter?.Key, "KillTaskSampleBeasts_0101", StringComparison.OrdinalIgnoreCase) && !k.DoneBefore, + $"a kill task counting from its /myquests counter, the first time ({k.Status})"); + Check(c.OnGuideChatLine("You have killed 13 Sample Beasts! You must kill 50 to complete your task.", DateTime.UtcNow.AddSeconds(5)), "a kill line is taken"); + k = p.KillOf(kt, c.UtcNow); + Check(k.Kills == 13 && k.FromChat && k.Status == "13 / 50", "the kill line moves the count at once"); + c.OnGuideChatLine("You have killed 50 Sample Beasts! You must kill 50 to complete your task.", DateTime.UtcNow.AddSeconds(6)); + Check(p.KillOf(kt, c.UtcNow).State == KillState.TurnIn, "all kills made: turn in"); + Check(GuideProgress.FlagLabel("KillTaskOtherThings_0202") == "Kill Task Other Things 0202", "a counter flag's label"); + Check(!c.OnGuideChatLine("You have killed a Sample Beast.", c.UtcNow), "an ordinary kill line isn't a kill task's"); + + // ── The page ── + var view = new OracleView(c); + var host = new UiHost(); + UiWindow main = host.Add(new UiWindow("RynthOracle/Oracle", "Oracle") { Visible = true, DefaultWidth = 760, DefaultHeight = 600 }); + string Draw(string what) + { + main.Begin(); view.Draw(main); main.End(); + ParseAll(host, what, out int ops); + Check(ops > 5 && ops < 1400, $"{what}: {ops} ops"); + string body = Encoding.UTF8.GetString(main.Body); + main.MarkSubmitted(true); + return body; + } + Check(Array.IndexOf(view.VisibleTabs(), OracleView.TabGuide) == 1, "the Guide tab is the second tab"); + view.ShowGuide(GuideList.All); + string all = Draw("Guide: All"); + Check(all.Contains("Test Daily Errand") && all.Contains("Test Story Quest") && all.Contains("AC Community Wiki feed: off"), + "All lists the guide's quests and says the feed is off"); + view.ShowGuide(GuideList.Dailies, "w:Test Daily Errand"); + string opened = Draw("Guide: a quest opened"); + Check(opened.Contains("Daily (every 20h") && opened.Contains("Go 12.3N, 45.6E") && opened.Contains("[x] stamped TestErrandStarted") + && opened.Contains("Sample Fang") && opened.Contains("Wiki page") && !opened.Contains("Run this quest"), + "the opened quest: timer, Go buttons, ticked stamps, loot; no run controls in this version"); + view.ShowGuide(GuideList.Story, ""); + string storyPage = Draw("Guide: Story"); + Check(storyPage.Contains("Test Story Quest") && !storyPage.Contains("Test Daily Errand"), "Story holds the one-time quests only"); + + view.ShowGuide(GuideList.KillTasks); + Check(view.KillTasksShowing, "the Kill Tasks list is on screen"); + string kills = Draw("Guide: Kill Tasks"); + Check(kills.Contains("Sample Beast Kill Task") && kills.Contains("Turn in") && kills.Contains("1st"), "a wiki kill task: turn in, first time"); + Check(kills.Contains("Others") && kills.Contains("3 / 10"), "a counter no wiki task names is listed too"); + Check(kills.Contains("Kill tasks: 0 counting, 1 to turn in"), "the summary line"); + + view.ShowGuide(GuideList.Society, "w:Test Story Quest"); + string society = Draw("Guide: Society"); + Check(society.Contains("Initiate: Test Story Quest") && society.Contains("Society: Initiate"), "society quests by rank"); + view.ShowGuide(GuideList.Contracts, "c:Contract for Test Daily Errand"); + string contracts = Draw("Guide: Contracts"); + Check(contracts.Contains("Contract for Test Daily Errand") && contracts.Contains("Go to Sample Barkeep") && contracts.Contains("Open"), + "a contract: where it comes from (Go) and its quest (Open)"); + // Open goes to the quest in All. + main.Begin(); view.Draw(main); main.End(); + Apply(host, Event(1, 300, main.Hash, main.KeyOf("g.c.q.0"), new byte[] { 1, 0, 0 })); + string afterOpen = Draw("Guide: Open from a contract"); + Check(afterOpen.Contains("Daily (every 20h") && afterOpen.Contains("[x] stamped"), "Open shows the contract's quest"); + + // Hide done leaves the finished daily out (every stamp held, its timer running). + c.Settings.GuideHideDone = true; + view.ShowGuide(GuideList.All, ""); + string hidden = Draw("Guide: hide done"); + Check(!hidden.Contains("Test Daily Errand") && hidden.Contains("Test Story Quest"), "Hide done leaves out the done daily"); + c.Settings.GuideHideDone = false; + + // ── A server plugin's guide comes first, over the wiki's quest of the same name ── + var serverGuide = new QuestGuide(); + serverGuide.Quests.Add(new GuideQuest { Title = "Test Story Quest", Steps = { new GuideStep { Text = "The server's own way", Stamps = { "ServerStoryStamp" } } } }); + serverGuide.Quests.Add(new GuideQuest { Title = "Server Only Quest", RepeatSec = 7 * 86400 }); + ServerQuestGuideHost.ResetForTests(); + var table = (RynthServerQuestGuideApiV1*)ServerQuestGuideHost.Query(1); + ServerQuestGuideHost.Publish("Test Server", "RynthTestServer", serverGuide, "2 quests", running: false, RynthServerQuestGuide.CommandRefresh); + c.ServerGuide.Use(table, "RynthTestServer"); + GuideSet set = view.GuideSources(); + Check(set.Quests.Count == 4 && set.Find("Test Story Quest")!.Steps.Count == 1 && set.FromServer(set.Find("Server Only Quest")!) + && !set.FromServer(set.Find("Test Daily Errand")!), "merged: the server's quests first and over the wiki's of the same name"); + Check(set.SocietyRankOf(set.Find("Test Story Quest")!) == "Initiate", "the wiki's society rank still applies"); + view.ShowGuide(GuideList.Weekly, "w:Server Only Quest"); + string weekly = Draw("Guide: a server quest"); + Check(weekly.Contains("Test Server Wiki (RynthTestServer)") && weekly.Contains("Read it again") && weekly.Contains("From Test Server's guide"), + "the server guide's line, its command button and the quest's source"); + ServerQuestGuideHost.Release(); + c.ServerGuide.Use(table, "RynthTestServer"); + Check(view.GuideSources().Quests.Count == 3, "the server's guide gone: the wiki's alone"); + ServerQuestGuideHost.ResetForTests(); + + // ── No guide at all: the feed's controls, saying what it reads ── + OracleContext empty = Context(); + var emptyView = new OracleView(empty); + UiWindow ew = new UiHost().Add(new UiWindow("RynthOracle/Oracle", "Oracle") { Visible = true }); + empty.Settings.TabName = OracleView.TabGuide; + ew.Begin(); emptyView.Draw(ew); ew.End(); + string none = Encoding.UTF8.GetString(ew.Body); + Check(none.Contains("No quest guide yet") && none.Contains("Turn the feed on and read it") && none.Contains("asheron.fandom.com/api.php"), + "no guide: the feed's button, and what it reads and from where"); + + // ── /ro guide ── + Check(OracleCommand.Parse("guide") is { Verb: OracleVerb.Tab, Tab: OracleView.TabGuide, Word: "" } + && OracleCommand.Parse("killtasks") is { Tab: OracleView.TabGuide, Word: "killtasks" } + && OracleCommand.Parse("guide society").Word == "society" && OracleCommand.Parse("contracts").Word == "contracts", "/ro guide words"); + } + } +} diff --git a/Tools/RynthOracle.Tests/Program.cs b/Tools/RynthOracle.Tests/Program.cs index 05aa752..66bc4e2 100644 --- a/Tools/RynthOracle.Tests/Program.cs +++ b/Tools/RynthOracle.Tests/Program.cs @@ -41,6 +41,8 @@ namespace RynthOracle.Tests { // Tab clicks save the settings: into a scratch file, never the player's %APPDATA% copy. OracleSettings.PathOverride = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "RynthOracleTests-" + Guid.NewGuid().ToString("N") + "-settings.json"); + // The wiki feed's saved guide: a scratch path too (none there, so the feed starts empty). + CommunityWikiFeed.PathOverride = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "RynthOracleTests-" + Guid.NewGuid().ToString("N") + "-guide.json"); Lists(); QuestLines(); Catalog(); @@ -68,6 +70,10 @@ namespace RynthOracle.Tests ServerMove(); Replies(); ReadyEarly(); + QuestListDaily(); + QuestGuideInterface(); + WikiFeed(); + GuideTab(); Console.WriteLine($"{_pass} passed, {_fail} failed"); return _fail == 0 ? 0 : 1; } diff --git a/Tools/RynthOracle.Tests/QuestGuideTests.cs b/Tools/RynthOracle.Tests/QuestGuideTests.cs new file mode 100644 index 0000000..4b8d768 --- /dev/null +++ b/Tools/RynthOracle.Tests/QuestGuideTests.cs @@ -0,0 +1,101 @@ +using System; +using System.Collections.Generic; +using System.Text; +using RynthCore.Plugin.Shared; + +namespace RynthOracle.Tests +{ + /// + /// The quest guide (2026-11-27; SilentKelpie's PR 12 idea, re-implemented): the "RynthServer.QuestGuide" + /// interface a server plugin serves its guide through, the guide's JSON, and RynthOracle's reader of it. + /// The server side runs in-process (ServerQuestGuideHost's table, as a server plugin would hand it out). + /// + internal static partial class Program + { + /// A small guide in the shared format: two quests (one with steps and stamps), a kill task, a contract. + internal static QuestGuide SampleGuide() + { + var g = new QuestGuide { Source = "test wiki", UpdatedUtc = new DateTime(2026, 11, 27, 12, 0, 0, DateTimeKind.Utc) }; + g.Quests.Add(new GuideQuest + { + Title = "Test Daily Errand", Url = "https://wiki.example/Test_Daily_Errand", Rev = 11, Level = "50+", Repeat = "20 Hours", + RepeatSec = 20 * 3600, StartsWith = "Sample Questgiver", StartsAt = "Sampletown", + Steps = + { + new GuideStep { Text = "Talk to Sample Questgiver", Coords = { "12.3N, 45.6E" }, Stamps = { "TestErrandStarted" } }, + new GuideStep { Text = "Kill the Sample Beast and loot its Sample Fang", Items = { "Sample Fang" }, Stamps = { "TestErrandFang" } }, + new GuideStep { Text = "Hand the fang in", Stamps = { "TestErrandDone" } }, + }, + Loot = { "Sample Fang" }, Rewards = { "Luminance: 1,000" }, + }); + g.Quests.Add(new GuideQuest { Title = "Test Story Quest", Overview = "A one-time quest." }); + g.Quests.Add(new GuideQuest + { + Title = "Sample Beast Kill Task", KillTask = "Yes", RepeatSec = 20 * 3600, Repeat = "20 hours", + Steps = { new GuideStep { Text = "Kill 50 Sample Beasts", Stamps = { "KillTaskSampleBeasts_0101 on first completion" } } }, + }); + g.KillTasks.Add("Sample Beast Kill Task"); + g.Society["Test Story Quest"] = "Initiate"; + g.Contracts.Add(new GuideContract { Title = "Contract for Test Daily Errand", Name = "Contract for Test Daily Errand", Npc = "Sample Barkeep", Quests = { "Test Daily Errand" } }); + return g; + } + + private static unsafe void QuestGuideInterface() + { + // The guide's JSON round trip, stamps cut to their flags on the way in. + QuestGuide g = SampleGuide(); + QuestGuide back = QuestGuide.Parse(g.ToJson()); + Check(back.Quests.Count == 3 && back.Contracts.Count == 1 && back.KillTasks.Count == 1, "the guide reads back: quests, kill tasks, contracts"); + GuideQuest? daily = back.Find("test daily errand"); + Check(daily != null && daily.Steps.Count == 3 && daily.Steps[0].Coords[0] == "12.3N, 45.6E" && daily.RepeatSec == 72000 && daily.IsDaily, + "a quest's steps, coordinates and timer read back"); + Check(back.Find("Sample Beast Kill Task")!.Steps[0].Stamps[0] == "KillTaskSampleBeasts_0101", "a stamp with words after it is cut to the flag"); + Check(back.IsKillTask(back.Find("Sample Beast Kill Task")!) && !back.IsKillTask(daily!), "kill tasks by the summary box and the list"); + Check(back.SocietyRankOf(back.Find("Test Story Quest")!) == "Initiate", "society rank from the guide's society list"); + Check(QuestGuide.Parse("not json").IsEmpty && QuestGuide.Parse("{\"schema\":9,\"quests\":[{\"title\":\"x\"}]}").IsEmpty, + "junk or another schema is an empty guide"); + Check(GuideStamp.Clean("You've stamped TestErrandFang!") == "TestErrandFang" && GuideStamp.Clean("Shiny Red Stone") == "Shiny Red Stone", + "a chat line's stamp, and a stamp of plain words left whole"); + Check(GuideStamp.Key("Shiny_Red_Stone") == GuideStamp.Key("shiny red stone"), "stamp names compare alike"); + + // A server plugin serves it; the reader takes it through the table. + ServerQuestGuideHost.ResetForTests(); + var table = (RynthServerQuestGuideApiV1*)ServerQuestGuideHost.Query(1); + Check(table != null && table->Version == 1 && ServerQuestGuideHost.Query(2) == IntPtr.Zero, "the table answers version 1 only"); + var client = new ServerQuestGuideClient(); + client.Use(table, "RynthTestServer"); + Check(!client.Available && client.Guide.IsEmpty, "nothing published: no guide"); + + ServerQuestGuideHost.Publish("Test Server", "RynthTestServer", null, "reading the wiki...", running: true, RynthServerQuestGuide.CommandRefresh); + client.Use(table, "RynthTestServer"); + Check(client.Available && client.Guide.IsEmpty && client.Info!.Running && client.Info.Status == "reading the wiki...", + "a guide still being read: its status, no quests"); + + ServerQuestGuideHost.Publish("Test Server", "RynthTestServer", g, "3 quests", running: false, RynthServerQuestGuide.CommandRefresh, RynthServerQuestGuide.CommandSettings); + int rev = client.Revision; + client.Use(table, "RynthTestServer"); + Check(client.Guide.Quests.Count == 3 && client.Tag == "Test Server" && client.Revision != rev, "the published guide is read"); + rev = client.Revision; + client.Use(table, "RynthTestServer"); + Check(client.Revision == rev, "unchanged info: nothing read again"); + + Check(client.Command("refresh") && ServerQuestGuideHost.TryTakeCommand(out string word) && word == "refresh", "a command goes to the plugin's queue"); + Check(!client.Command("delete-everything") && !ServerQuestGuideHost.TryTakeCommand(out _), "a word the plugin doesn't list isn't sent"); + + // A name outside ASCII survives the info JSON's escaping. + ServerQuestGuideHost.Publish("Café \"Q\"", "RynthTestServer", g, "ok", running: false); + client.Use(table, "RynthTestServer"); + Check(client.Tag == "Café \"Q\"" && !client.Info!.Takes("refresh"), "the tag's escaping, and no commands listed"); + + ServerQuestGuideHost.Release(); + Check(table->Version == 0, "shutdown: the table says so"); + client.Use(table, "RynthTestServer"); + Check(!client.Available && client.Guide.IsEmpty, "a shut-down plugin's guide goes away"); + ServerQuestGuideHost.ResetForTests(); + + Check(ServerQuestGuideInfo.Parse("{\"schema\":1,\"bytes\":-5,\"commands\":[\"Refresh\",3]}") is { Bytes: 0 } i && i.Takes("refresh"), + "the info is read leniently"); + Check(ServerQuestGuideInfo.Parse("{\"schema\":2}") == null && ServerQuestGuideInfo.Parse("[]") == null, "another schema, or junk, is no info"); + } + } +} diff --git a/Tools/RynthOracle.Tests/QuestListDailyTests.cs b/Tools/RynthOracle.Tests/QuestListDailyTests.cs new file mode 100644 index 0000000..e42600f --- /dev/null +++ b/Tools/RynthOracle.Tests/QuestListDailyTests.cs @@ -0,0 +1,20 @@ +using System; +using RynthCore.Plugin.RynthOracle.Data; + +namespace RynthOracle.Tests +{ + // "Check once a day for a newer quest list" ran once per login: a client that stayed logged in for + // days never checked again. It is due a day after the last check started, however long the session. + internal static partial class Program + { + private static void QuestListDaily() + { + DateTime last = new DateTime(2026, 11, 20, 9, 0, 0, DateTimeKind.Utc); + Check(QuestCatalogUpdater.Due(last.AddDays(1), last), "quest list: due a day after the last check"); + Check(!QuestCatalogUpdater.Due(last.AddHours(23), last), "quest list: not due within the day"); + Check(QuestCatalogUpdater.Due(last.AddDays(3), last), "quest list: still due days later in the same session"); + Check(QuestCatalogUpdater.Due(last, DateTime.MinValue), "quest list: never checked: due"); + Check(!new QuestCatalogUpdater().Running, "quest list: a new updater isn't running"); + } + } +} diff --git a/Tools/RynthOracle.Tests/ReplyTests.cs b/Tools/RynthOracle.Tests/ReplyTests.cs index 3f2f41b..5a38862 100644 --- a/Tools/RynthOracle.Tests/ReplyTests.cs +++ b/Tools/RynthOracle.Tests/ReplyTests.cs @@ -25,6 +25,10 @@ namespace RynthOracle.Tests ("progress", OracleVerb.Tab, OracleView.TabProgress), ("progression", OracleVerb.Tab, OracleView.TabProgress), ("status", OracleVerb.Status, ""), ("about", OracleVerb.About, OracleView.TabAbout), ("help", OracleVerb.Help, ""), ("?", OracleVerb.Help, ""), ("STATUS", OracleVerb.Status, ""), ("questz", OracleVerb.Unknown, ""), ("dynamic", OracleVerb.Unknown, ""), + ("wiki", OracleVerb.Wiki, ""), ("wiki on", OracleVerb.Wiki, ""), ("wiki off", OracleVerb.Wiki, ""), ("wiki read", OracleVerb.Wiki, ""), + ("wiki status", OracleVerb.Wiki, ""), ("wiki delete", OracleVerb.Unknown, ""), + ("guide", OracleVerb.Tab, OracleView.TabGuide), ("killtasks", OracleVerb.Tab, OracleView.TabGuide), ("kill tasks", OracleVerb.Tab, OracleView.TabGuide), + ("guide society", OracleVerb.Tab, OracleView.TabGuide), ("contracts", OracleVerb.Tab, OracleView.TabGuide), }; var seen = new HashSet(); foreach (var (typed, verb, tab) in words) diff --git a/Tools/RynthOracle.Tests/RynthOracle.Tests.csproj b/Tools/RynthOracle.Tests/RynthOracle.Tests.csproj index 039b3df..383d7cc 100644 --- a/Tools/RynthOracle.Tests/RynthOracle.Tests.csproj +++ b/Tools/RynthOracle.Tests/RynthOracle.Tests.csproj @@ -38,6 +38,12 @@ + + + + + + diff --git a/Tools/RynthOracle.Tests/ServerMoveTests.cs b/Tools/RynthOracle.Tests/ServerMoveTests.cs index 5bea750..dbbb083 100644 --- a/Tools/RynthOracle.Tests/ServerMoveTests.cs +++ b/Tools/RynthOracle.Tests/ServerMoveTests.cs @@ -46,7 +46,7 @@ namespace RynthOracle.Tests { c.Server.Force(tag, world); string[] tabs = view.VisibleTabs(); - Check(Array.IndexOf(tabs, "Pet Breeding") < 0 && tabs.Length == 11, $"ilt: {world}: the same eleven tabs: " + string.Join(",", tabs)); + Check(Array.IndexOf(tabs, "Pet Breeding") < 0 && tabs.Length == 12, $"ilt: {world}: the same twelve tabs: " + string.Join(",", tabs)); } } diff --git a/Tools/RynthOracle.Tests/WikiFeedTests.cs b/Tools/RynthOracle.Tests/WikiFeedTests.cs new file mode 100644 index 0000000..3dbf80c --- /dev/null +++ b/Tools/RynthOracle.Tests/WikiFeedTests.cs @@ -0,0 +1,153 @@ +using System; +using System.Collections.Generic; +using RynthCore.Plugin.RynthOracle; +using RynthCore.Plugin.RynthOracle.Data; +using RynthCore.Plugin.Shared; + +namespace RynthOracle.Tests +{ + /// + /// The wiki page reader (Plugins/Shared/QuestWikiText.cs) and the AC Community Wiki feed's pure parts + /// (2026-11-27). The pages here are made up in the wiki's template style; no wiki text is copied in. + /// The feed is off by default and never fetches in these tests. + /// + internal static partial class Program + { + private const string TestWiki = "https://wiki.example/wiki/"; + + /// A made-up quest page: summary box, overview, numbered steps with stamps and items, a stamp listed apart, rewards. + internal const string SampleQuestPage = @"{{Quest Summary +| Level = 50+ +| Recommended Level = 80+ +| Quest Type = Solo +| Starts With = [[Sample Questgiver]] +| Starts At = [[Sampletown]] +| Repeat Timer = 20 Hours +}} + +== Overview == +Sample Questgiver wants a '''fang''' from the [[Sample Beast|beast]] in the hills.a footnote +== Walkthrough == +# Talk to [[Sample Questgiver]] in Sampletown (12.3N, 45.6E). +#* {{stamped|TestErrandStarted}} +# Travel to the hills at 20.1s 30.2w and kill the Sample Beast to loot a {{Itemlink|Sample Fang}}. +#* It hits hard. +# Hand the {{Itemlink|Sample Fang}} to [[Sample Questgiver]]. +== QB Stamps == +{{stamped|TestErrandFang}} {{stamped|TestErrandDone on first completion}} +== Rewards == +{{Rewards Table +| Quest Task = Hand in the fang +| Item Reward = * {{Itemlink|Sample Trinket}} (x2) +| XP Reward = 1,000,000 +}} +[[Category:Quests]] +[[Category:Sample Quests]]"; + + private const string SampleKillPage = @"{{Quest Summary | Level = 30+ | Kill Task = Yes | Repeat Timer = Non Repeatable | Starts With = [[Sample Hunter]] }} +== Walkthrough == +* Kill 50 [[Sample Beast]]s for the hunter. {{stamped|KillTaskSampleBeasts_0101 on first completion}} +* Return to the hunter."; + + private const string SampleContractPage = @"{{Intro | Related Quests = [[Test Daily Errand]], [[Test Story Quest|the story]] }} +{{Item | Name = Contract for Test Daily Errand | Description = Starts the errand again. | Recommended Level = 50 }} +== Notes == +* Purchased from [[Sample Barkeep]] in the Sampletown inn. +[[Category:Contracts]]"; + + private static void WikiFeed() + { + // ── The page reader ── + Check(QuestWikiText.IsQuestPage(SampleQuestPage) && !QuestWikiText.IsQuestPage("just text"), "a quest page has the summary box"); + GuideQuest q = QuestWikiText.ParseQuest("Test Daily Errand", SampleQuestPage, 77, TestWiki); + Check(q.Url == "https://wiki.example/wiki/Test_Daily_Errand" && q.Rev == 77, "the page's address and revision: " + q.Url); + Check(q.Level == "50+" && q.RecommendedLevel == "80+" && q.Type == "Solo" && q.StartsWith == "Sample Questgiver" && q.StartsAt == "Sampletown", + "the summary box: level, type, where it starts"); + Check(q.RepeatSec == 20 * 3600 && q.IsDaily && !q.IsOneTime, "a 20 hour timer is a daily"); + Check(q.Overview == "Sample Questgiver wants a fang from the beast in the hills.", "the overview, links and markup cleaned: " + q.Overview); + Check(q.Steps.Count == 3, $"three numbered steps ({q.Steps.Count})"); + Check(q.Steps[0].Coords.Count == 1 && q.Steps[0].Coords[0] == "12.3N, 45.6E" && q.Steps[0].Stamps[0] == "TestErrandStarted", + "step 1: its coordinates and stamp"); + Check(q.Steps[1].Coords[0] == "20.1S, 30.2W" && q.Steps[1].Notes.Count == 1 && q.Steps[1].Items[0] == "Sample Fang", + "step 2: lower-case coordinates, its tip and its item"); + Check(q.Steps[1].Stamps.Contains("TestErrandFang"), "a stamp listed apart goes with the step that names it"); + Check(q.Steps[2].Stamps.Contains("TestErrandDone"), "the last stamp left goes to the last stampless step, cut to its flag"); + Check(q.ExtraStamps.Count == 0 && q.AllStamps().Count == 3, "every stamp tied to a step"); + Check(q.Loot.Count == 1 && q.Loot[0] == "Sample Fang", "loot: the item a kill step names, not the hand-in"); + Check(q.Rewards.Count == 3 && q.Rewards[0] == "For Hand in the fang:" && q.Rewards[1] == "Sample Trinket (x2)" && q.Rewards[2] == "XP: 1,000,000", + "the rewards table: " + string.Join(" | ", q.Rewards)); + Check(q.Categories.Contains("Sample Quests"), "the categories"); + + GuideQuest k = QuestWikiText.ParseQuest("Sample Beast Kill Task", SampleKillPage, 5, TestWiki); + Check(k.IsKillTaskPage && k.KillTarget == 50 && k.KillCreatureKey == "samplebeast", "a kill task: the box, the count, the creature"); + Check(k.RepeatSec == 0 && k.IsOneTime, "\"Non Repeatable\" is one-time"); + Check(k.Steps.Count == 2 && k.Steps[0].Stamps[0] == "KillTaskSampleBeasts_0101", "bullet steps, the counter stamp cut to its flag"); + + Check(QuestWikiText.IsContractPage("Contract for Test Daily Errand", SampleContractPage), "a contract page"); + GuideContract c = QuestWikiText.ParseContract("Contract for Test Daily Errand", SampleContractPage, 9, TestWiki); + Check(c.Name == "Contract for Test Daily Errand" && c.Level == "50" && c.Description == "Starts the errand again.", "the contract's item box"); + Check(c.Quests.Count == 2 && c.Quests[0] == "Test Daily Errand" && c.Quests[1] == "Test Story Quest", "the quests it is for"); + Check(c.Npc == "Sample Barkeep" && c.Where.StartsWith("Purchased from Sample Barkeep"), "where it comes from: " + c.Where); + + // Paragraph walkthroughs, repeat timers. + GuideQuest para = QuestWikiText.ParseQuest("P", "{{Quest Summary}}\n== Walkthrough ==\nFirst go here.\nStill the first.\n\nThen go there 1.0N 2.0E.", 0, TestWiki); + Check(para.Steps.Count == 2 && para.Steps[1].Coords[0] == "1.0N, 2.0E", "paragraphs are steps"); + Check(QuestWikiText.RepeatSeconds("7 days") == 7 * 86400 && QuestWikiText.RepeatSeconds("3d 12h") == 3 * 86400 + 12 * 3600 + && QuestWikiText.RepeatSeconds("Weekly") == 7 * 86400 && QuestWikiText.RepeatSeconds("None") == 0 + && QuestWikiText.RepeatSeconds("whenever") == -1, "repeat timers"); + Check(QuestWikiText.Clean("[[File:x.png|thumb|a [[link]]]] [[Foo|bar]] {{Itemlink|Baz}} &
end") == "bar Baz & end", "markup cleaned"); + + // ── The API's answers ── + var members = QuestWikiText.Members( + "{\"continue\":{\"cmcontinue\":\"page|X\",\"continue\":\"-||\"},\"query\":{\"categorymembers\":[{\"ns\":0,\"title\":\"A\"},{\"ns\":14,\"title\":\"Category:B\"},{\"ns\":6,\"title\":\"File:C\"}]}}", + "categorymembers"); + Check(members.Pages.Count == 1 && members.Pages[0] == "A" && members.SubCats.Count == 1 && members.Continue.Count == 2, + "category members: pages, sub-categories, continue"); + Dictionary revs = QuestWikiText.LastRevisions("{\"query\":{\"pages\":[{\"title\":\"A\",\"lastrevid\":12},{\"title\":\"Gone\",\"missing\":true}]}}"); + Check(revs.Count == 1 && revs["A"] == 12, "page revisions, missing pages left out"); + var contents = QuestWikiText.Contents("{\"query\":{\"pages\":[{\"title\":\"A\",\"revisions\":[{\"revid\":12,\"slots\":{\"main\":{\"content\":\"hello\"}}}]}]}}"); + Check(contents.Count == 1 && contents[0].Rev == 12 && contents[0].Text == "hello", "page contents"); + Check(QuestWikiText.Members("not json", "x").Pages.Count == 0 && QuestWikiText.LastRevisions("[").Count == 0, "junk answers are empty"); + var titles = new List(); + for (int i = 0; i < 120; i++) titles.Add("T" + i); + Check(QuestWikiText.Batches(titles).Count == 3, "titles in batches of 50"); + string url = QuestWikiText.ApiUrl(CommunityWikiFeed.Api, ("action", "query"), ("titles", "A B|C&D")); + Check(url.StartsWith("https://asheron.fandom.com/api.php?format=json&formatversion=2&action=query&titles=A%20B%7CC%26D"), "the API address, values escaped: " + url); + + // ── The feed's pure parts ── + Check(CommunityWikiFeed.RankOf("Category:Society Quests: Knight Rank") == "Knight" && CommunityWikiFeed.RankOf("Category:Joining a Society Quests") == "Joining" + && CommunityWikiFeed.RankOf("Category:Other") == "", "society ranks from category names"); + Check(CommunityWikiFeed.SkipCategory("Category:Quest Items") && CommunityWikiFeed.SkipCategory("Category:Quest NPCs") + && !CommunityWikiFeed.SkipCategory("Category:Society Quests"), "item and NPC lists aren't followed"); + var old = new QuestGuide { Reader = QuestWikiText.ReaderVersion, UpdatedUtc = DateTime.UtcNow.AddHours(-1) }; + old.Quests.Add(new GuideQuest { Title = "Same", Rev = 1 }); + old.Quests.Add(new GuideQuest { Title = "Edited", Rev = 1 }); + old.Quests.Add(new GuideQuest { Title = "Dropped", Rev = 1 }); + var listed = new Dictionary { ["Same"] = 1, ["Edited"] = 2, ["New"] = 3 }; + List toRead = CommunityWikiFeed.PagesToRead(old, listed); + Check(toRead.Count == 2 && toRead.Contains("Edited") && toRead.Contains("New"), "only new and edited pages are read"); + Check(CommunityWikiFeed.PagesToRead(new QuestGuide { Reader = 0, Quests = { new GuideQuest { Title = "Same", Rev = 1 } } }, new Dictionary { ["Same"] = 1 }).Count == 1, + "a guide from an older reader is read again whole"); + var fresh = new Dictionary { ["Edited"] = new GuideQuest { Title = "Edited", Rev = 2 }, ["New"] = new GuideQuest { Title = "New", Rev = 3 } }; + QuestGuide merged = CommunityWikiFeed.Merge(old, listed, fresh, new Dictionary(), DateTime.UtcNow); + Check(merged.Quests.Count == 3 && merged.Find("Edited")!.Rev == 2 && merged.Find("Same") != null && merged.Find("Dropped") == null + && merged.Source == CommunityWikiFeed.Host, "the merge: fresh pages, kept pages, dropped pages gone"); + Check(!CommunityWikiFeed.Due(old, DateTime.UtcNow) && CommunityWikiFeed.Due(old, DateTime.UtcNow.AddDays(1)) && CommunityWikiFeed.Due(new QuestGuide(), DateTime.UtcNow), + "read again once a day old (or when there is none)"); + + // ── Off by default; it says what it reads and from where ── + Check(!new OracleSettings().WikiFeedOn, "the feed is off by default"); + var feed = new CommunityWikiFeed(System.IO.Path.Combine(System.IO.Path.GetTempPath(), "RynthOracleTests-" + Guid.NewGuid().ToString("N") + "-feed.json")); + Check(!feed.Start(on: false) && !feed.Running && !feed.LoginRead(on: false, daily: true, DateTime.UtcNow), "off: no read starts"); + Check(CommunityWikiFeed.WhatItReads.Contains("https://asheron.fandom.com/api.php") && CommunityWikiFeed.WhatItReads.Contains("no login"), + "the disclosure names the address"); + OracleContext ctx = Context(); + ctx.Settings.WikiFeedOn = false; + var (readOk, readText) = ctx.ReadWikiNow(); + Check(!readOk && readText.Contains("off") && readText.Contains("asheron.fandom.com/api.php") && !ctx.Wiki.Running, "Read now with the feed off fetches nothing and says why"); + Check(ctx.SetWikiFeed(false).Text.Contains("already off"), "turning it off when off says so"); + Check(OracleCommand.Parse("wiki on") is { Verb: OracleVerb.Wiki, Word: "on" } && OracleCommand.Parse("wiki") is { Verb: OracleVerb.Wiki, Word: "status" } + && OracleCommand.Parse("wiki read") is { Verb: OracleVerb.Wiki, Word: "read" }, "/ro wiki words"); + } + } +}