Snapshot for release 2026.10.28.2 (internal 48c46bd)
This commit is contained in:
parent
b23cabc338
commit
636adfcef2
41 changed files with 3402 additions and 120 deletions
|
|
@ -120,7 +120,7 @@ public partial class BuffManager
|
|||
}
|
||||
_bowDequipAttempts++;
|
||||
if (_worldObjectCache?[bowId] is WorldObject blocker && IsInOffhandSlot(blocker))
|
||||
OffhandStowed?.Invoke(bowId); // a shield: combat puts it back after
|
||||
OffhandPutAway(bowId); // a shield: combat puts it back after (and it is buffed in the pack)
|
||||
_host.MoveItemInternal((uint)bowId, (uint)openPack, 0, 1); // amount>=1 (engine rejects 0)
|
||||
_weaponSwapGate?.NoteMove(bowId, wieldedNow: true);
|
||||
_bowDequipPendingId = bowId;
|
||||
|
|
|
|||
549
Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.Shield.cs
Normal file
549
Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.Shield.cs
Normal file
|
|
@ -0,0 +1,549 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.Shared;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
/// <summary>
|
||||
/// The shield's armor spells (2026-10-28). Impenetrability and the seven Banes are cast on the
|
||||
/// player, and ACE puts them on every worn piece of armor and a worn shield
|
||||
/// (WorldObject_Magic.TryCastItemEnchantment_WithRedirects). But buffing holds a wand, and ACE won't
|
||||
/// wield a caster beside a shield: the wand swap puts the shield into a pack first, so the
|
||||
/// self-cast never reached it. The shield now gets its own casts, aimed at it, after the armor's.
|
||||
///
|
||||
/// * Which shield: one in the Items list (the Shield action, or a shield filed as a weapon) that
|
||||
/// is in use: in the off hand, or put into a pack by buffing's own wand swap (combat puts it
|
||||
/// back). A listed shield that was in a pack before (not worn) is left alone, as armor in a
|
||||
/// pack is; an unlisted shield is never a target. No listed shield: nothing here runs.
|
||||
/// * Which spells: the armor's, Impenetrability and the Banes still in the buff list (the
|
||||
/// Protections and Banes ticks, or a buff profile), at the level the armor gets. Weapon
|
||||
/// enchantments never go on the shield. Buff the shield (LegacyUiSettings.BuffShield, on by
|
||||
/// default) turns it off.
|
||||
/// * When: on the armor's rules (Rebuff With, Also Refresh Under in a batch, Force Rebuff), on the
|
||||
/// shield's own timers, recorded from the "You cast X on <shield>" line.
|
||||
/// * Never at a shield being moved (its pack move or wield not settled, a swap under way).
|
||||
/// * A cast at the shield that gets no answer twice in a row, or that the server says can't be
|
||||
/// cast on it, stops shield buffing for ShieldParkTime; the armor is never held up by it.
|
||||
/// </summary>
|
||||
public partial class BuffManager
|
||||
{
|
||||
/// <summary>The shield's armor spells: keyed by (shield id, spell family), <see cref="ShieldKey"/>.</summary>
|
||||
private readonly Dictionary<long, ItemSpellRecord> _shieldSpellTimers = new();
|
||||
internal static long ShieldKey(int shieldId, int family) => ((long)unchecked((uint)shieldId) << 32) | unchecked((uint)family);
|
||||
|
||||
// The shield the pending cast is aimed at. Means something only while _pendingSpellId is set:
|
||||
// every other cast clears it when it is sent.
|
||||
private int _pendingShieldId;
|
||||
private bool PendingIsShield => _pendingSpellId != 0 && _pendingShieldId != 0;
|
||||
|
||||
// Families confirmed on the shield in this force/batch run, at their level (ClearRunFamilies).
|
||||
private readonly Dictionary<int, int> _shieldRunLevels = new();
|
||||
// A family the server refused on the shield (no components, no mana): rested, the armor's not touched.
|
||||
private readonly Dictionary<int, DateTime> _shieldFamilyRestUntil = new();
|
||||
// Casts at the shield with no answer in a row; at ShieldNoShowsToPark the shield is parked.
|
||||
private int _shieldNoShows;
|
||||
private int _shieldParkedId;
|
||||
private DateTime _shieldParkedUntil = DateTime.MinValue;
|
||||
internal const int ShieldNoShowsToPark = 2;
|
||||
internal static readonly TimeSpan ShieldParkTime = TimeSpan.FromMinutes(30);
|
||||
|
||||
// The off-hand item buffing's wand swap put into a pack (combat puts it back on), and when.
|
||||
// Seen in the off hand again after StowedSightingGraceMs, it is forgotten: the next time it is
|
||||
// in a pack, something else put it there.
|
||||
private int _stowedShieldId;
|
||||
private DateTime _stowedShieldAt = DateTime.MinValue;
|
||||
private const double StowedSightingGraceMs = 10000;
|
||||
|
||||
// ShieldToBuff walks the inventory: its answer is kept ShieldReadMs (the arbiter asks every tick),
|
||||
// and worked out again at once when the Items list or the cache changes. Tests set ShieldReadMs 0.
|
||||
internal long ShieldReadMs = 1000;
|
||||
private int _shieldChoice;
|
||||
private string _shieldChoiceWhy = "";
|
||||
private long _shieldChoiceAt = long.MinValue / 2;
|
||||
private List<ItemRule>? _shieldChoiceRules;
|
||||
private int _shieldChoiceRuleCount;
|
||||
private WorldObjectCache? _shieldChoiceCache;
|
||||
private string _shieldChoiceLogged = "";
|
||||
|
||||
/// <summary>Impenetrability (Brogard's Defiance) and the Banes: the armor spells, which a shield takes too.</summary>
|
||||
internal static bool IsArmorItemSpell(string name) =>
|
||||
name.IndexOf("Impenetrability", StringComparison.OrdinalIgnoreCase) >= 0
|
||||
|| name.IndexOf("Brogard's Defiance", StringComparison.OrdinalIgnoreCase) >= 0
|
||||
|| name.IndexOf(" Bane", StringComparison.OrdinalIgnoreCase) >= 0
|
||||
|| name.StartsWith("Bane", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>
|
||||
/// Buffing's wand swap put <paramref name="id"/> (the off hand) into a pack: combat puts it back
|
||||
/// (OffhandStowed), and a shield there is still the one in use, so it is buffed in the pack.
|
||||
/// </summary>
|
||||
internal void OffhandPutAway(int id)
|
||||
{
|
||||
if (id != 0)
|
||||
{
|
||||
_stowedShieldId = id;
|
||||
_stowedShieldAt = RynthClock.Now;
|
||||
_shieldChoiceAt = long.MinValue / 2;
|
||||
}
|
||||
OffhandStowed?.Invoke(id);
|
||||
}
|
||||
|
||||
/// <summary>The Items list's shields the cache knows, in list order.</summary>
|
||||
private List<int> ListedShields()
|
||||
{
|
||||
var found = new List<int>();
|
||||
var cache = _worldObjectCache;
|
||||
if (cache == null) return found;
|
||||
List<ItemRule> rules;
|
||||
try { rules = new List<ItemRule>(_settings.ItemRules); }
|
||||
catch { return found; } // the list edited mid-copy: next read
|
||||
foreach (var r in rules)
|
||||
{
|
||||
if (r.Id == 0 || found.Contains(r.Id)) continue;
|
||||
var wo = cache[r.Id];
|
||||
if (wo == null) continue;
|
||||
if (CombatManager.IsShieldItem(wo) || (WeaponList.IsShieldRule(r) && wo.ObjectClass == AcObjectClass.Armor))
|
||||
found.Add(r.Id);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
private bool InInventory(int id)
|
||||
{
|
||||
if (_worldObjectCache == null || id == 0) return false;
|
||||
foreach (var wo in _worldObjectCache.GetDirectInventory())
|
||||
if (wo.Id == id) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The listed shield to buff now (0 = none) and where it is: the one in the off hand, else the
|
||||
/// one buffing put into a pack for the wand. <paramref name="fresh"/> reads it again now.
|
||||
/// </summary>
|
||||
internal int ShieldToBuff(out string where, bool fresh = false)
|
||||
{
|
||||
long now = KitClockMs();
|
||||
var rules = _settings.ItemRules;
|
||||
if (!fresh && ReferenceEquals(rules, _shieldChoiceRules) && rules.Count == _shieldChoiceRuleCount
|
||||
&& ReferenceEquals(_worldObjectCache, _shieldChoiceCache) && now >= _shieldChoiceAt && now - _shieldChoiceAt < ShieldReadMs)
|
||||
{
|
||||
where = _shieldChoiceWhy;
|
||||
return _shieldChoice;
|
||||
}
|
||||
int id = FindShieldToBuff(out where, out bool anyListed);
|
||||
_shieldChoice = id;
|
||||
_shieldChoiceWhy = where;
|
||||
_shieldChoiceAt = now;
|
||||
_shieldChoiceRules = rules;
|
||||
_shieldChoiceRuleCount = rules.Count;
|
||||
_shieldChoiceCache = _worldObjectCache;
|
||||
// One log line when the answer changes, only for a character with a shield listed.
|
||||
string line = anyListed ? $"{id:X8}|{where}" : "";
|
||||
if (line != _shieldChoiceLogged)
|
||||
{
|
||||
_shieldChoiceLogged = line;
|
||||
if (anyListed)
|
||||
_host.Log(id != 0
|
||||
? $"[Buff] shield: 0x{(uint)id:X8} '{ItemName(id)}' ({where}) takes the armor spells"
|
||||
: $"[Buff] shield: none buffed ({where})");
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
private int FindShieldToBuff(out string where, out bool anyListed)
|
||||
{
|
||||
anyListed = false;
|
||||
if (!_settings.BuffShield) { where = "Buff the shield is off"; return 0; }
|
||||
var listed = ListedShields();
|
||||
anyListed = listed.Count > 0;
|
||||
if (!anyListed) { where = "no shield listed"; return 0; }
|
||||
foreach (int id in listed)
|
||||
{
|
||||
if (!IsWieldedLive(id)) continue;
|
||||
if (id == _stowedShieldId && !ShieldMidSwap(id, out _)
|
||||
&& (RynthClock.Now - _stowedShieldAt).TotalMilliseconds > StowedSightingGraceMs)
|
||||
_stowedShieldId = 0; // back in the off hand
|
||||
where = "in the off hand";
|
||||
return id;
|
||||
}
|
||||
if (_stowedShieldId != 0 && listed.Contains(_stowedShieldId) && InInventory(_stowedShieldId))
|
||||
{
|
||||
where = "put into a pack for the wand";
|
||||
return _stowedShieldId;
|
||||
}
|
||||
where = "the listed shield is in a pack, not worn";
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True while <paramref name="shieldId"/> may be on its way into or out of a hand: the wand swap
|
||||
/// under way, the shield's move into a pack not confirmed, or a swap the shared gate says just
|
||||
/// moved it (combat's off-hand wield or dequip, a held multi-step swap).
|
||||
/// </summary>
|
||||
private bool ShieldMidSwap(int shieldId, out string why)
|
||||
{
|
||||
if (_wandSwap.Active) { why = "the wand swap is under way"; return true; }
|
||||
if (_pendingWieldId != 0) { why = "the wand's wield is in flight"; return true; }
|
||||
if (_bowDequipPendingId == shieldId && shieldId != 0) { why = "its move into a pack is in flight"; return true; }
|
||||
if (_weaponSwapGate != null && _weaponSwapGate.MayBeMoving(shieldId))
|
||||
{
|
||||
why = $"a swap is moving it ({_weaponSwapGate.LastSwapBy})";
|
||||
return true;
|
||||
}
|
||||
why = "";
|
||||
return false;
|
||||
}
|
||||
|
||||
private bool ShieldParked(int shieldId) =>
|
||||
shieldId != 0 && shieldId == _shieldParkedId && RynthClock.Now < _shieldParkedUntil;
|
||||
|
||||
/// <summary>A family resting after a refusal: on the shield, or for the armor too (no components, a parked family).</summary>
|
||||
private bool ShieldFamilyResting(int family)
|
||||
{
|
||||
DateTime now = RynthClock.Now;
|
||||
return (_shieldFamilyRestUntil.TryGetValue(family, out DateTime s) && now < s)
|
||||
|| (_buffFailCooldownUntil.TryGetValue(family, out DateTime a) && now < a);
|
||||
}
|
||||
|
||||
/// <summary>The armor spells of <paramref name="desiredBuffs"/> this character can cast, resolved like the armor's.</summary>
|
||||
private List<(SpellInfo Spell, string BaseName)> ShieldSpells(List<string> desiredBuffs)
|
||||
{
|
||||
var list = new List<(SpellInfo, string)>();
|
||||
foreach (string baseName in desiredBuffs)
|
||||
{
|
||||
if (!IsArmorItemSpell(baseName)) continue; // weapon enchantments never go on the shield
|
||||
AcSkillType skill = SkillFor(baseName);
|
||||
if (!IsSkillUsable(skill)) continue;
|
||||
int spellId = FindBestSpellId(baseName, skill);
|
||||
if (spellId == 0) continue;
|
||||
var spell = SpellTableStub.GetById(spellId);
|
||||
if (spell == null || !IsArmorItemSpell(spell.Name)) continue;
|
||||
list.Add((spell, baseName));
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>IsBuffActive for the shield: its own timer, the armor's rules.</summary>
|
||||
private bool IsShieldBuffActive(int shieldId, SpellInfo spell, int? rebufferSecOverride = null)
|
||||
{
|
||||
int level = GetSpellLevel(spell);
|
||||
if (_isForceRebuffing)
|
||||
{
|
||||
// Cast on the shield in this run: done, unless a higher level is castable now.
|
||||
if (_shieldRunLevels.TryGetValue(spell.Family, out int ran)) return UpgradeParked(spell.Family) || level <= ran;
|
||||
if (!_isAutoBatchRebuff) return false;
|
||||
rebufferSecOverride = Math.Max(_settings.RebuffTopOffSecondsRemaining, _settings.RebuffSecondsRemaining);
|
||||
}
|
||||
int rebufferSec = Math.Max(0, rebufferSecOverride ?? _settings.RebuffSecondsRemaining);
|
||||
if (!_shieldSpellTimers.TryGetValue(ShieldKey(shieldId, spell.Family), out ItemSpellRecord? rec)) return false;
|
||||
if (rec.SpellLevel < level && !UpgradeParked(spell.Family)) return false; // a higher level: recast, as the armor's
|
||||
return RynthClock.Now < rec.ExpiresAt.AddSeconds(-rebufferSec);
|
||||
}
|
||||
|
||||
/// <summary>AnyBuffBelowThreshold's shield half: an armor spell on the shield to buff under <paramref name="thresholdSec"/>.</summary>
|
||||
private bool ShieldBuffBelowThreshold(List<string> desiredBuffs, int thresholdSec)
|
||||
{
|
||||
int shield = ShieldToBuff(out _);
|
||||
if (shield == 0 || ShieldParked(shield)) return false;
|
||||
foreach (var (spell, _) in ShieldSpells(desiredBuffs))
|
||||
{
|
||||
if (ShieldFamilyResting(spell.Family)) continue;
|
||||
if (!IsShieldBuffActive(shield, spell, thresholdSec)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// CheckAndCastSelfBuffs' last step, once every buff on the character is on: the next armor
|
||||
/// spell the shield needs, aimed at the shield. True when it acted (a cast, or the tick yielded
|
||||
/// to the wand swap or a move of the shield).
|
||||
/// </summary>
|
||||
private bool CastShieldBuffs(List<string> desiredBuffs, bool diagnose)
|
||||
{
|
||||
// This step runs on every buff tick: the kept answer first (no inventory walk while
|
||||
// nothing is due), a fresh read only once a spell is due on the shield.
|
||||
int shield = ShieldToBuff(out string where);
|
||||
if (shield == 0) return false;
|
||||
if (ShieldParked(shield))
|
||||
{
|
||||
LastBuffSkipReason = $"shield buffs parked ({(_shieldParkedUntil - RynthClock.Now).TotalMinutes:0} min left)";
|
||||
return false;
|
||||
}
|
||||
var spells = ShieldSpells(desiredBuffs);
|
||||
if (!spells.Exists(s => !IsShieldBuffActive(shield, s.Spell) && !ShieldFamilyResting(s.Spell.Family))) return false;
|
||||
int read = ShieldToBuff(out where, fresh: true);
|
||||
if (read != shield) return read != 0; // another shield (next tick), or none any more
|
||||
|
||||
foreach (var (spell, baseName) in spells)
|
||||
{
|
||||
if (IsShieldBuffActive(shield, spell)) continue;
|
||||
if (ShieldFamilyResting(spell.Family))
|
||||
{
|
||||
LastBuffSkipReason = $"resting on the shield: {baseName}";
|
||||
if (diagnose) DiagSkip(baseName + "@shield", $"[FR] skip '{baseName}' on the shield — resting after a refusal");
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!EnsureMagicMode(forBuff: true))
|
||||
{
|
||||
if (_wandSwapExhausted)
|
||||
{
|
||||
// The wand can't be wielded now (see the self-buff loop): rest this family on the
|
||||
// shield so buffing lets go and combat runs.
|
||||
_shieldFamilyRestUntil[spell.Family] = RynthClock.Now.AddSeconds(BuffFailCooldownSec);
|
||||
LastBuffSkipReason = $"wand-swap exhausted: {baseName} on the shield";
|
||||
continue;
|
||||
}
|
||||
LastBuffSkipReason = "magic-mode swap in progress (yielding tick)";
|
||||
return true;
|
||||
}
|
||||
|
||||
// The wand swap may just have put the shield into a pack: where is it now?
|
||||
int now = ShieldToBuff(out where, fresh: true);
|
||||
if (now != shield) return now != 0; // another shield (next tick), or none any more
|
||||
if (ShieldMidSwap(shield, out string moving))
|
||||
{
|
||||
LastBuffSkipReason = $"the shield is being moved: {moving}";
|
||||
return true;
|
||||
}
|
||||
|
||||
// The mana reserve holds these as it holds every buff (see the self-buff loop).
|
||||
if (_fastChainTick && BuffNeedsManaFirst(spell.Id, out _, out _))
|
||||
{
|
||||
_fastChainTick = false;
|
||||
_chain.HoldForAnimation();
|
||||
LastBuffSkipReason = "mana reserve before " + baseName + " on the shield: Stamina to Mana waits for the animation";
|
||||
return true;
|
||||
}
|
||||
if (BuffWaitsForMana(spell.Id, baseName))
|
||||
return true;
|
||||
|
||||
SendShieldCast(shield, spell, baseName, where, diagnose);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void SendShieldCast(int shield, SpellInfo spell, string baseName, string where, bool diagnose)
|
||||
{
|
||||
int spellId = spell.Id;
|
||||
string shieldName = ItemName(shield);
|
||||
_pendingSpellId = spellId;
|
||||
_pendingShieldId = shield;
|
||||
_pendingUpgradeSpellId = 0; // the upgrade bookkeeping is the armor's
|
||||
_host.WriteToChat($"[RynthAi] Casting: {spell.Name} on {shieldName}", 5);
|
||||
if (diagnose) _host.Log($"[FR] CAST '{baseName}' on the shield 0x{(uint)shield:X8} '{shieldName}' ({where}) resolvedSpellId={spellId} (pending now set)");
|
||||
NoteBuffCastMana(SpellManaCost(spellId));
|
||||
_host.Log($"[Buff] mana {_vitals.CurrentMana}/{_vitals.MaxMana} ({_vitals.ManaPct}%) before {spell.Name} on the shield '{shieldName}' ({where}) (cost {SpellManaCost(spellId)}, reserve {ManaReserve()}, Get Mana At {_settings.GetManaAt}%)");
|
||||
bool fast = _fastChainTick;
|
||||
if (fast)
|
||||
_host.Log($"[BuffChain] '{spell.Name}' on the shield goes without waiting for the animation: {_fastChainWhy}");
|
||||
int seqAtSend = UseDoneSeqNow();
|
||||
bool castOk = _host.CastSpellFor(unchecked((uint)shield), spellId, "Buff", $"{spell.Name} on the shield");
|
||||
_lastCastAttempt = RynthClock.Now;
|
||||
if (castOk)
|
||||
{
|
||||
NoteCastIssued(spellId);
|
||||
_chain.Sent(spellId, spell.Name, seqAtSend, ActionPacer.Started, ActionPacer.AttacksSent, MoveAudit.MovementSends, fast);
|
||||
}
|
||||
else
|
||||
{
|
||||
_chain.ClientRefused(spellId, spell.Name, fast, s => _host.Log(s));
|
||||
_pendingSpellId = 0; // the packet never went out: no answer will come
|
||||
_pendingShieldId = 0;
|
||||
LastBuffSkipReason = $"local CastSpell rejected: {baseName} on the shield (id={spellId})";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>An armor spell landed on the shield: its timer, and in a force/batch run the family is done on it.</summary>
|
||||
private void ShieldSpellLanded(int shieldId, SpellInfo spell)
|
||||
{
|
||||
RecordShieldSpell(shieldId, spell);
|
||||
int level = GetSpellLevel(spell);
|
||||
if (_isForceRebuffing && (shieldId == _pendingShieldId || shieldId == ShieldToBuff(out _))
|
||||
&& (!_shieldRunLevels.TryGetValue(spell.Family, out int ran) || level > ran))
|
||||
_shieldRunLevels[spell.Family] = level;
|
||||
}
|
||||
|
||||
private void RecordShieldSpell(int shieldId, SpellInfo spell)
|
||||
{
|
||||
int level = GetSpellLevel(spell);
|
||||
double duration = GetCustomSpellDuration(level);
|
||||
var now = RynthClock.Now;
|
||||
_shieldSpellTimers[ShieldKey(shieldId, spell.Family)] = new ItemSpellRecord
|
||||
{
|
||||
CastAt = now,
|
||||
ExpiresAt = now.AddSeconds(duration),
|
||||
SpellName = spell.Name,
|
||||
SpellLevel = level,
|
||||
};
|
||||
_host.Log($"[BuffDiag] RECORD '{spell.Name}' on the shield 0x{(uint)shieldId:X8} (fam={spell.Family}, lvl={level}, durSec={duration:F0}, expiresAt={now.AddSeconds(duration):HH:mm:ss})");
|
||||
SaveBuffTimers();
|
||||
}
|
||||
|
||||
/// <summary>"Flame Bane VI on Kite Shield, refreshing Flame Bane V" -> "Kite Shield"; "" with no target.</summary>
|
||||
internal static string CastTarget(string afterCast)
|
||||
{
|
||||
int on = afterCast.IndexOf(" on ", StringComparison.OrdinalIgnoreCase);
|
||||
if (on < 0) return "";
|
||||
string rest = afterCast.Substring(on + 4);
|
||||
int comma = rest.IndexOf(',');
|
||||
if (comma >= 0) rest = rest.Substring(0, comma);
|
||||
return rest.Trim().TrimEnd('.', '!').Trim();
|
||||
}
|
||||
|
||||
private bool NamesShield(string target, int shieldId)
|
||||
{
|
||||
string name = _worldObjectCache?[shieldId]?.Name ?? "";
|
||||
return name.Length == 0 || target.Equals(name, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>The listed shield a cast line names (the pending one first), 0 = none.</summary>
|
||||
private int ListedShieldNamed(string target)
|
||||
{
|
||||
if (target.Length == 0) return 0;
|
||||
var listed = ListedShields();
|
||||
if (_pendingShieldId != 0 && listed.Contains(_pendingShieldId) && NamesShield(target, _pendingShieldId)
|
||||
&& (_worldObjectCache?[_pendingShieldId]?.Name ?? "").Length > 0)
|
||||
return _pendingShieldId;
|
||||
foreach (int id in listed)
|
||||
{
|
||||
string name = _worldObjectCache?[id]?.Name ?? "";
|
||||
if (name.Length > 0 && target.Equals(name, StringComparison.OrdinalIgnoreCase)) return id;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// OnChatWindowText's "You cast X on Y" for the shield, before the armor's handling: the pending
|
||||
/// shield cast's result, a late line for a listed shield, or a self-cast that reached a worn
|
||||
/// shield. Records the shield's timer. True when the line is done with here.
|
||||
/// </summary>
|
||||
private bool ShieldCastLine(SpellInfo spell, string afterCast)
|
||||
{
|
||||
if (!IsArmorItemSpell(spell.Name)) return false;
|
||||
string target = CastTarget(afterCast);
|
||||
var pending = PendingIsShield ? SpellTableStub.GetById(_pendingSpellId) : null;
|
||||
if (pending != null && pending.Family == spell.Family)
|
||||
{
|
||||
if (target.Length > 0 && !NamesShield(target, _pendingShieldId))
|
||||
{
|
||||
// A late line of the armor's own cast of this family: the armor's; the shield's cast waits.
|
||||
RecordItemSpellCast(spell);
|
||||
_host.Log($"[BuffChat] '{spell.Name}' on '{target}' is the armor's, not pending={_pendingSpellId} on the shield - recorded, pending kept.");
|
||||
return true;
|
||||
}
|
||||
ShieldSpellLanded(_pendingShieldId, spell);
|
||||
_shieldFamilyRestUntil.Remove(spell.Family);
|
||||
_shieldNoShows = 0;
|
||||
NoteCastAccepted();
|
||||
_host.Log($"[BuffChat] CLEARED pending={_pendingSpellId} (on the shield 0x{(uint)_pendingShieldId:X8}) via ou-cast match name='{spell.Name}'");
|
||||
_pendingSpellId = 0;
|
||||
_pendingShieldId = 0;
|
||||
_onCastResolved?.Invoke($"cast '{spell.Name}' on the shield");
|
||||
return true;
|
||||
}
|
||||
|
||||
int named = ListedShieldNamed(target);
|
||||
if (named == 0) return false;
|
||||
ShieldSpellLanded(named, spell);
|
||||
// A self-cast of this family that reached a worn shield: the armor's result as well.
|
||||
var selfPending = _pendingSpellId != 0 && !PendingIsShield ? SpellTableStub.GetById(_pendingSpellId) : null;
|
||||
if (selfPending != null && selfPending.Family == spell.Family) return false;
|
||||
_host.Log($"[BuffChat] '{spell.Name}' on the shield '{target}' - a late line, recorded{(_pendingSpellId != 0 ? $"; pending={_pendingSpellId} kept" : "")}.");
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The pending shield cast was refused or fizzled: the armor's timers and families are left alone.</summary>
|
||||
private void ShieldCastRefused(SpellInfo? spell, string why, double restSec)
|
||||
{
|
||||
if (spell != null && restSec > 0)
|
||||
_shieldFamilyRestUntil[spell.Family] = RynthClock.Now.AddSeconds(restSec);
|
||||
_host.Log($"[BuffChat] CLEARED pending={_pendingSpellId} on the shield 0x{(uint)_pendingShieldId:X8} - {why}" +
|
||||
(restSec > 0 ? $"; {spell?.Name} rests on the shield {restSec:0}s." : "; tried again."));
|
||||
}
|
||||
|
||||
/// <summary>The pending shield cast got no answer in time (the tick's no-chat give-up).</summary>
|
||||
private void ShieldCastNoShow(SpellInfo? spell)
|
||||
{
|
||||
int shield = _pendingShieldId;
|
||||
_shieldNoShows++;
|
||||
if (_shieldNoShows >= ShieldNoShowsToPark)
|
||||
{
|
||||
_shieldNoShows = 0;
|
||||
ParkShield(shield, $"{ShieldNoShowsToPark} casts on it got no answer");
|
||||
}
|
||||
else
|
||||
_host.Log($"[BuffChat] NO-CHAT TIMEOUT (shield) pending={_pendingSpellId} ('{spell?.Name}') on 0x{(uint)shield:X8} - " +
|
||||
$"no answer in {NoChatResolveTimeoutMs:0}ms ({_shieldNoShows}/{ShieldNoShowsToPark} before shield buffing rests).");
|
||||
}
|
||||
|
||||
private void ParkShield(int shield, string why)
|
||||
{
|
||||
_shieldParkedId = shield;
|
||||
_shieldParkedUntil = RynthClock.Now + ShieldParkTime;
|
||||
_host.Log($"[Buff] shield 0x{(uint)shield:X8} '{ItemName(shield)}': {why} - not buffing it for {ShieldParkTime.TotalMinutes:0} min.");
|
||||
_host.WriteToChat($"[RynthAi] Not buffing the shield '{ItemName(shield)}' for {ShieldParkTime.TotalMinutes:0} min ({why}).", 2);
|
||||
}
|
||||
|
||||
/// <summary>Force Rebuff: the shield starts over too.</summary>
|
||||
private void ResetShieldBuffs()
|
||||
{
|
||||
_shieldSpellTimers.Clear();
|
||||
_shieldRunLevels.Clear();
|
||||
_shieldFamilyRestUntil.Clear();
|
||||
_shieldNoShows = 0;
|
||||
_shieldParkedId = 0;
|
||||
_shieldParkedUntil = DateTime.MinValue;
|
||||
_pendingShieldId = 0;
|
||||
}
|
||||
|
||||
/// <summary>bufftimers.txt lines for the shield: "shield|id|family|castTicks|expiresTicks|level|name".</summary>
|
||||
private void SaveShieldTimers(List<string> lines)
|
||||
{
|
||||
foreach (var kvp in _shieldSpellTimers)
|
||||
{
|
||||
var info = kvp.Value;
|
||||
uint id = unchecked((uint)(kvp.Key >> 32));
|
||||
int family = unchecked((int)(kvp.Key & 0xFFFFFFFF));
|
||||
lines.Add($"shield|{id}|{family}|{info.CastAt.Ticks}|{info.ExpiresAt.Ticks}|{info.SpellLevel}|{info.SpellName}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One "shield|..." line of bufftimers.txt; false when the line is something else.</summary>
|
||||
private bool LoadShieldTimer(string[] p)
|
||||
{
|
||||
if (p[0] != "shield") return false;
|
||||
if (p.Length < 7) return true;
|
||||
if (!uint.TryParse(p[1], out uint id) || !int.TryParse(p[2], out int family)
|
||||
|| !long.TryParse(p[3], out long cast) || !long.TryParse(p[4], out long expires) || !int.TryParse(p[5], out int level))
|
||||
return true;
|
||||
var expiresAt = new DateTime(expires);
|
||||
if (expiresAt > RynthClock.Now)
|
||||
_shieldSpellTimers[ShieldKey(unchecked((int)id), family)] = new ItemSpellRecord
|
||||
{
|
||||
CastAt = new DateTime(cast), ExpiresAt = expiresAt, SpellLevel = level, SpellName = p[6],
|
||||
};
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>/ra buffs and /ra buffs item: the shield's timers.</summary>
|
||||
private void PrintShieldSpellTimers()
|
||||
{
|
||||
if (_shieldSpellTimers.Count == 0) return;
|
||||
_host.WriteToChat($"[RynthAi] -- Shield spells ({_shieldSpellTimers.Count}) --", 1);
|
||||
foreach (var kvp in _shieldSpellTimers)
|
||||
{
|
||||
var info = kvp.Value;
|
||||
int id = unchecked((int)(uint)(kvp.Key >> 32));
|
||||
TimeSpan left = info.ExpiresAt - RynthClock.Now;
|
||||
_host.WriteToChat(left.TotalSeconds <= 0
|
||||
? $"[RynthAi] {ItemName(id)}: {info.SpellName} (Lvl {info.SpellLevel}): EXPIRED"
|
||||
: $"[RynthAi] {ItemName(id)}: {info.SpellName} (Lvl {info.SpellLevel}): {Math.Round(left.TotalMinutes, 1)}m left / {Math.Round((info.ExpiresAt - info.CastAt).TotalMinutes, 0)}m total", 1);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Shield spell timers recorded (tests, status).</summary>
|
||||
internal int ShieldSpellCount => _shieldSpellTimers.Count;
|
||||
}
|
||||
|
|
@ -916,6 +916,9 @@ public partial class BuffManager : IDisposable
|
|||
var info = kvp.Value;
|
||||
lines.Add($"item|{kvp.Key}|{info.CastAt.Ticks}|{info.ExpiresAt.Ticks}|{info.SpellLevel}|{info.SpellName}");
|
||||
}
|
||||
// Last: a build from before the shield's lines reads them as old-style lines that
|
||||
// expired long ago (no exception, so the lines above are loaded either way).
|
||||
SaveShieldTimers(lines);
|
||||
// The "char doesn't know this spell" blacklist is NO LONGER persisted.
|
||||
// Persisting it meant one lag-induced no-chat timeout permanently
|
||||
// poisoned a KNOWN spell across all future sessions, collapsing the
|
||||
|
|
@ -934,9 +937,11 @@ public partial class BuffManager : IDisposable
|
|||
{
|
||||
_ramBuffTimers.Clear();
|
||||
_itemSpellTimers.Clear();
|
||||
_shieldSpellTimers.Clear();
|
||||
foreach (string line in System.IO.File.ReadAllLines(_buffTimerPath))
|
||||
{
|
||||
string[] p = line.Split('|');
|
||||
if (LoadShieldTimer(p)) continue;
|
||||
|
||||
if (p[0] == "item" && p.Length >= 6)
|
||||
{
|
||||
|
|
@ -973,9 +978,10 @@ public partial class BuffManager : IDisposable
|
|||
_ramBuffTimers[family] = new RamTimerInfo { Expiration = expiration, SpellLevel = level, SpellName = name };
|
||||
}
|
||||
}
|
||||
int total = _ramBuffTimers.Count + _itemSpellTimers.Count;
|
||||
int total = _ramBuffTimers.Count + _itemSpellTimers.Count + _shieldSpellTimers.Count;
|
||||
if (total > 0)
|
||||
_host.WriteToChat($"[RynthAi] Restored {_ramBuffTimers.Count} player + {_itemSpellTimers.Count} item spell timer(s).", 1);
|
||||
_host.WriteToChat($"[RynthAi] Restored {_ramBuffTimers.Count} player + {_itemSpellTimers.Count} item spell timer(s)" +
|
||||
(_shieldSpellTimers.Count > 0 ? $" + {_shieldSpellTimers.Count} on the shield." : "."), 1);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
|
@ -1020,6 +1026,7 @@ public partial class BuffManager : IDisposable
|
|||
_upgradeParkedUntil.Clear();
|
||||
_ramBuffTimers.Clear();
|
||||
_itemSpellTimers.Clear();
|
||||
ResetShieldBuffs(); // the shield's timers, rests and park too
|
||||
EndPendingUpgrade(_pendingSpellId, "a new Force Rebuff");
|
||||
_pendingSpellId = 0;
|
||||
_lastCastAttempt = DateTime.MinValue;
|
||||
|
|
@ -1522,6 +1529,20 @@ public partial class BuffManager : IDisposable
|
|||
// switch in mid-cast.
|
||||
if (_pendingSpellId != 0) { TryEmergencyHealWhilePending(); Hold("buff cast in flight", pendingSpell.Name); return; }
|
||||
}
|
||||
else if (pendingIsArmor && PendingIsShield)
|
||||
{
|
||||
// An armor spell aimed at the shield (BuffManager.Shield.cs): chat is authoritative,
|
||||
// as for the armor, but a give-up counts against the shield only. No blacklist (the
|
||||
// same spell just went on the armor) and no family park for the armor.
|
||||
if (PendingGiveUpReached(NoChatResolveTimeoutMs))
|
||||
{
|
||||
ShieldCastNoShow(pendingSpell);
|
||||
_pendingSpellId = 0;
|
||||
_pendingShieldId = 0;
|
||||
_onCastResolved?.Invoke("no-chat timeout (shield)");
|
||||
}
|
||||
if (_pendingSpellId != 0) { TryEmergencyHealWhilePending(); Hold("item spell in flight", pendingSpell?.Name ?? ""); return; }
|
||||
}
|
||||
else if (pendingIsArmor)
|
||||
{
|
||||
// ARMOR/ITEM: chat is authoritative. No-chat valve abandons a cast
|
||||
|
|
@ -2299,6 +2320,7 @@ public partial class BuffManager : IDisposable
|
|||
// ever come; setting pending anyway waited 2.5 s and counted a no-show
|
||||
// strike. Mirror the buff path: not handled, so the potion gets its turn.
|
||||
_pendingSpellId = spellId;
|
||||
_pendingShieldId = 0; // on the player, not the shield
|
||||
_pendingVitalSpellId = spellId; // instant: confirmed by chat, never by the registry
|
||||
_pendingVitalLabel = label;
|
||||
_pendingVitalBase = what;
|
||||
|
|
@ -2785,7 +2807,8 @@ public partial class BuffManager : IDisposable
|
|||
continue;
|
||||
if (!IsBuffActive(spellId, thresholdSec)) return true;
|
||||
}
|
||||
return false;
|
||||
// The shield's armor spells start a batch the same way (BuffManager.Shield.cs).
|
||||
return ShieldBuffBelowThreshold(desiredBuffs, thresholdSec);
|
||||
}
|
||||
|
||||
// "[FR] skip ..." lines while a rebuff runs: the selector runs every tick (~30 ms), and a
|
||||
|
|
@ -2912,6 +2935,7 @@ public partial class BuffManager : IDisposable
|
|||
int upgradeFrom = spellInfo != null && buffFamily != 0 ? ActiveLevelBelow(buffFamily, upgradeTo) : 0;
|
||||
|
||||
_pendingSpellId = spellId;
|
||||
_pendingShieldId = 0; // on the player, not the shield
|
||||
if (buffFamily != 0)
|
||||
{
|
||||
_lastCastSpellIdByFamily[buffFamily] = spellId;
|
||||
|
|
@ -2967,7 +2991,8 @@ public partial class BuffManager : IDisposable
|
|||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
// Everything on the character is on: the shield's armor spells (BuffManager.Shield.cs).
|
||||
return CastShieldBuffs(desiredBuffs, diagnose);
|
||||
}
|
||||
|
||||
/// <summary>Casts that replaced an active buff of the same family at a lower level (tests, status).</summary>
|
||||
|
|
@ -3310,6 +3335,7 @@ public partial class BuffManager : IDisposable
|
|||
{
|
||||
_forceRebuffCastFamilies.Clear();
|
||||
_runConfirmedLevelByFamily.Clear();
|
||||
_shieldRunLevels.Clear();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -3572,10 +3598,12 @@ public partial class BuffManager : IDisposable
|
|||
// left them "active" for up to an hour and the bot fought unbuffed (reported as
|
||||
// "buffing skips missile weapons"). The player's registry dropping to zero (a death,
|
||||
// or logging in after one) is the signal: forget them so they get recast.
|
||||
if (count == 0 && _lastLivePlayerEnchantCount != 0 && _itemSpellTimers.Count > 0)
|
||||
if (count == 0 && _lastLivePlayerEnchantCount != 0 && (_itemSpellTimers.Count > 0 || _shieldSpellTimers.Count > 0))
|
||||
{
|
||||
_host.Log($"[BuffDiag] player enchantments dropped to 0 (was {_lastLivePlayerEnchantCount}) - clearing {_itemSpellTimers.Count} item-spell timer(s) so weapon/armor buffs recast");
|
||||
_host.Log($"[BuffDiag] player enchantments dropped to 0 (was {_lastLivePlayerEnchantCount}) - clearing {_itemSpellTimers.Count} item-spell timer(s)" +
|
||||
$"{(_shieldSpellTimers.Count > 0 ? $" and {_shieldSpellTimers.Count} on the shield" : "")} so weapon/armor buffs recast");
|
||||
_itemSpellTimers.Clear();
|
||||
_shieldSpellTimers.Clear();
|
||||
}
|
||||
_lastLivePlayerEnchantCount = count;
|
||||
|
||||
|
|
@ -3808,7 +3836,7 @@ public partial class BuffManager : IDisposable
|
|||
_host.WriteToChat($"[RynthAi] ServerTime={Math.Round(serverNow)} (no live read: serverTime=0 or API missing)", 1);
|
||||
}
|
||||
|
||||
if (_ramBuffTimers.Count == 0 && _itemSpellTimers.Count == 0)
|
||||
if (_ramBuffTimers.Count == 0 && _itemSpellTimers.Count == 0 && _shieldSpellTimers.Count == 0)
|
||||
{
|
||||
_host.WriteToChat("[RynthAi] No buff timers active.", 1);
|
||||
return;
|
||||
|
|
@ -3819,6 +3847,7 @@ public partial class BuffManager : IDisposable
|
|||
_host.WriteToChat($"[RynthAi] -- Item spells ({_itemSpellTimers.Count}) --", 1);
|
||||
PrintItemSpellTimers();
|
||||
}
|
||||
PrintShieldSpellTimers();
|
||||
|
||||
if (_ramBuffTimers.Count > 0)
|
||||
{
|
||||
|
|
@ -3882,13 +3911,17 @@ public partial class BuffManager : IDisposable
|
|||
|
||||
public void PrintItemBuffDebug()
|
||||
{
|
||||
if (_itemSpellTimers.Count == 0)
|
||||
if (_itemSpellTimers.Count == 0 && _shieldSpellTimers.Count == 0)
|
||||
{
|
||||
_host.WriteToChat("[RynthAi] No item spell timers recorded yet.", 1);
|
||||
return;
|
||||
}
|
||||
_host.WriteToChat($"[RynthAi] -- Item spells ({_itemSpellTimers.Count}) --", 1);
|
||||
PrintItemSpellTimers();
|
||||
if (_itemSpellTimers.Count > 0)
|
||||
{
|
||||
_host.WriteToChat($"[RynthAi] -- Item spells ({_itemSpellTimers.Count}) --", 1);
|
||||
PrintItemSpellTimers();
|
||||
}
|
||||
PrintShieldSpellTimers();
|
||||
}
|
||||
|
||||
private void PrintItemSpellTimers()
|
||||
|
|
@ -4228,8 +4261,9 @@ public partial class BuffManager : IDisposable
|
|||
// Only clear pending if this enchantment matches what we were casting.
|
||||
// Armor/item enchantments fire on the item, not the player — clearing
|
||||
// _pendingSpellId unconditionally would lose track of pending item casts
|
||||
// and prevent the chat handler from recording their timers.
|
||||
if (_pendingSpellId != 0)
|
||||
// and prevent the chat handler from recording their timers. A cast at the shield never
|
||||
// lands on the player: only its chat line resolves it.
|
||||
if (_pendingSpellId != 0 && !PendingIsShield)
|
||||
{
|
||||
var pendingSpell = SpellTableStub.GetById(_pendingSpellId);
|
||||
if (pendingSpell != null && pendingSpell.Family == spellInfo.Family)
|
||||
|
|
@ -4368,12 +4402,12 @@ public partial class BuffManager : IDisposable
|
|||
else if (_pendingSpellId != 0)
|
||||
{
|
||||
var pendingSpell = SpellTableStub.GetById(_pendingSpellId);
|
||||
if (pendingSpell != null && IsItemEnchantment(pendingSpell.Name))
|
||||
if (pendingSpell != null && IsItemEnchantment(pendingSpell.Name) && !PendingIsShield) // the shield's refusal leaves the armor's timer
|
||||
{
|
||||
_itemSpellTimers.Remove(pendingSpell.Family);
|
||||
SaveBuffTimers();
|
||||
}
|
||||
_host.Log($"[BuffChat] PARKED pending={_pendingSpellId} — AC too busy (cast gesture in progress); throttle kept, backing off before re-issue.");
|
||||
_host.Log($"[BuffChat] PARKED pending={_pendingSpellId}{(PendingIsShield ? " (on the shield)" : "")} — AC too busy (cast gesture in progress); throttle kept, backing off before re-issue.");
|
||||
if (_pendingSpellId != _pendingVitalSpellId)
|
||||
_chain.TooBusyLine(_pendingSpellId, s => _host.Log(s));
|
||||
}
|
||||
|
|
@ -4432,6 +4466,14 @@ public partial class BuffManager : IDisposable
|
|||
_noComponentsUntil[_pendingSpellId] = RynthClock.Now.AddSeconds(NoComponentsLevelSec);
|
||||
_host.WriteToChat($"[RynthAi] No components for {pendingSpell.Name}: using a lower level for {NoComponentsLevelSec / 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);
|
||||
}
|
||||
else if (pendingSpell != null)
|
||||
{
|
||||
if (IsItemEnchantment(pendingSpell.Name))
|
||||
|
|
@ -4481,7 +4523,9 @@ public partial class BuffManager : IDisposable
|
|||
return;
|
||||
}
|
||||
double restSec = LowManaFamilyRestSec;
|
||||
if (pendingSpell != null)
|
||||
if (pendingSpell != null && PendingIsShield)
|
||||
ShieldCastRefused(pendingSpell, "not enough mana", restSec); // rests on the shield; the armor's timer stays
|
||||
else if (pendingSpell != null)
|
||||
{
|
||||
if (IsItemEnchantment(pendingSpell.Name))
|
||||
{
|
||||
|
|
@ -4515,12 +4559,12 @@ public partial class BuffManager : IDisposable
|
|||
if (_pendingSpellId != 0)
|
||||
{
|
||||
var pendingSpell = SpellTableStub.GetById(_pendingSpellId);
|
||||
if (pendingSpell != null && IsItemEnchantment(pendingSpell.Name))
|
||||
if (pendingSpell != null && IsItemEnchantment(pendingSpell.Name) && !PendingIsShield) // a fizzle at the shield leaves the armor's timer
|
||||
{
|
||||
_itemSpellTimers.Remove(pendingSpell.Family);
|
||||
SaveBuffTimers();
|
||||
}
|
||||
_host.Log($"[BuffChat] CLEARED pending={_pendingSpellId} via soft-fail in '{text}'");
|
||||
_host.Log($"[BuffChat] CLEARED pending={_pendingSpellId}{(PendingIsShield ? " (on the shield)" : "")} via soft-fail in '{text}'");
|
||||
}
|
||||
_lastCastAttempt = DateTime.MinValue;
|
||||
EndPendingUpgrade(_pendingSpellId, "fizzled");
|
||||
|
|
@ -4529,6 +4573,19 @@ public partial class BuffManager : IDisposable
|
|||
return;
|
||||
}
|
||||
|
||||
// "Flame Bane VI cannot be cast on Kite Shield." (ACE IsInvalidTarget: an item that takes no
|
||||
// spells). Read only for a cast at the shield: shield buffing rests; the armor carries on.
|
||||
if (PendingIsShield && lower.Contains(" cannot be cast on "))
|
||||
{
|
||||
_cast.Result(null, "refused by the server", atStart: true);
|
||||
_host.Log($"[BuffChat] CLEARED pending={_pendingSpellId} on the shield 0x{(uint)_pendingShieldId:X8} - '{text}'");
|
||||
ParkShield(_pendingShieldId, "the server says these spells can't be cast on it");
|
||||
_pendingSpellId = 0;
|
||||
_pendingShieldId = 0;
|
||||
_onCastResolved?.Invoke("can't be cast on the shield");
|
||||
return;
|
||||
}
|
||||
|
||||
// A script heal (a transfer such as Vitality Siphon) cast at a monster that resists it:
|
||||
// "Doorheld Surveyor resists your spell" is its only result, no "due to casting" line
|
||||
// follows. Closed here as CombatManager reads the same line for its own casts.
|
||||
|
|
@ -4605,6 +4662,11 @@ public partial class BuffManager : IDisposable
|
|||
if (spellInfo == null && _pendingSpellId != 0)
|
||||
spellInfo = SpellTableStub.GetById(_pendingSpellId);
|
||||
|
||||
// An armor spell's line for the shield (its own cast, a late line, or a self-cast that
|
||||
// reached a worn shield) goes on the shield's timer, not the armor's (BuffManager.Shield.cs).
|
||||
if (spellInfo != null && !viaDueToCasting && ShieldCastLine(spellInfo, afterCast))
|
||||
return;
|
||||
|
||||
// A result that names another spell than the pending one is not the pending cast's
|
||||
// result: the pending cast keeps waiting for its own (or its give-up time).
|
||||
var pendingInfo = _pendingSpellId != 0 ? SpellTableStub.GetById(_pendingSpellId) : null;
|
||||
|
|
@ -5428,7 +5490,7 @@ public partial class BuffManager : IDisposable
|
|||
return WandSwapFailed(_wandSwap.Abandon("no pack with room"), forBuff, wandId, now);
|
||||
}
|
||||
bool offhand = hands.TryGetValue(step.Id, out int slot) && (slot & HandSwapSequence.ShieldSlot) != 0;
|
||||
if (offhand) OffhandStowed?.Invoke(step.Id); // combat puts it back after
|
||||
if (offhand) OffhandPutAway(step.Id); // combat puts it back after (and it is buffed in the pack)
|
||||
_host.MoveItemInternal((uint)step.Id, (uint)pack, 0, 1); // amount>=1 (engine rejects 0)
|
||||
_wandSwap.Sent(step, now);
|
||||
_wandSwapLastMoved = step.Id;
|
||||
|
|
@ -5554,7 +5616,7 @@ public partial class BuffManager : IDisposable
|
|||
if (!_host.ChangeCombatModeFor(CombatMode.NonCombat, "Buff", "wand swap burst: peace, the hands and the wand at once")) return 1;
|
||||
foreach (int id in moves)
|
||||
{
|
||||
if (hands.TryGetValue(id, out int slot) && (slot & HandSwapSequence.ShieldSlot) != 0) OffhandStowed?.Invoke(id);
|
||||
if (hands.TryGetValue(id, out int slot) && (slot & HandSwapSequence.ShieldSlot) != 0) OffhandPutAway(id);
|
||||
_host.PutItemInContainer(unchecked((uint)id), unchecked((uint)pack), 0);
|
||||
}
|
||||
_host.WieldItem(unchecked((uint)wandId), HeldSlot);
|
||||
|
|
|
|||
|
|
@ -147,6 +147,22 @@ public sealed class WeaponSwapGate
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True while <paramref name="itemId"/> may still be on its way into or out of a hand: a
|
||||
/// multi-step swap holds the gate, or the last claimed swap noted a move of this item and the
|
||||
/// next swap would still wait for it (MinIntervalMs). Buffing doesn't aim a spell at a shield
|
||||
/// then (BuffManager.Shield.cs).
|
||||
/// </summary>
|
||||
public bool MayBeMoving(int itemId)
|
||||
{
|
||||
long now = NowMs();
|
||||
lock (_lock)
|
||||
{
|
||||
if (_heldBy.Length > 0 && now < _heldUntilMs) return true;
|
||||
return itemId != 0 && _movingId == itemId && now - _lastSwapTickMs < MinIntervalMs;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Milliseconds since the last successful swap (diagnostics).</summary>
|
||||
public long MsSinceLastSwap
|
||||
{
|
||||
|
|
|
|||
|
|
@ -1006,6 +1006,13 @@ internal sealed class LegacyAdvancedSettingsUi
|
|||
}
|
||||
ImGui.EndTable();
|
||||
}
|
||||
ImGui.Checkbox("Buff the shield", ref _settings.BuffShield);
|
||||
if (ImGui.IsItemHovered())
|
||||
ImGui.SetTooltip(
|
||||
"Cast the ticked Impenetrability and Banes on your shield too, after\n" +
|
||||
"the armor, renewed with it. The shield is the one in the Items list\n" +
|
||||
"(Shield) that you wear: buffing puts it in a pack for the wand, so it\n" +
|
||||
"is buffed there. On by default. No shield listed: nothing changes.");
|
||||
|
||||
ImGui.Spacing();
|
||||
ImGui.Separator();
|
||||
|
|
|
|||
|
|
@ -2055,7 +2055,8 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
dst.FastBuffChain = tmp.FastBuffChain;
|
||||
dst.SkipUnusableBuffs = tmp.SkipUnusableBuffs;
|
||||
dst.DisabledBuffs = tmp.DisabledBuffs;
|
||||
dst.BlacklistAttempts = tmp.BlacklistAttempts;
|
||||
dst.BuffShield = tmp.BuffShield;
|
||||
dst.BlacklistAttempts = tmp.BlacklistAttempts;
|
||||
dst.BlacklistTimeoutSec = tmp.BlacklistTimeoutSec;
|
||||
// 0 is never meant (every UI floors it at 250+) and is what the Settings-panel bug
|
||||
// saved into profiles: it judges each cast before its damage can land.
|
||||
|
|
@ -2870,6 +2871,7 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
switch (cmd.Cmd)
|
||||
{
|
||||
case "startNav":
|
||||
_settings.RearmFinishedNavRoute(); // the player's Start Navigation re-runs a finished Once route
|
||||
_settings.IsMacroRunning = true;
|
||||
_settings.EnableNavigation = true;
|
||||
if (_settings.BotAction != "Navigating")
|
||||
|
|
@ -3202,7 +3204,12 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
{
|
||||
case 0: _settings.EnableCombat = enabled; break;
|
||||
case 1: _settings.EnableBuffing = enabled; break;
|
||||
case 2: _settings.EnableNavigation = enabled; break;
|
||||
case 2:
|
||||
// The player switching nav on over a finished Once route re-runs it (a meta's
|
||||
// enablenav doesn't, NavigationEngine.HandleRouteEnd).
|
||||
if (enabled && !_settings.EnableNavigation) _settings.RearmFinishedNavRoute();
|
||||
_settings.EnableNavigation = enabled;
|
||||
break;
|
||||
case 3: _settings.EnableLooting = enabled; break;
|
||||
case 4: _settings.EnableMeta = enabled; break;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -63,6 +63,7 @@ internal sealed class LegacyNavigationUi
|
|||
ImGui.PushStyleColor(ImGuiCol.ButtonActive, new Vector4(0.08f, 0.28f, 0.08f, 1f));
|
||||
if (ImGui.Button("Start Navigation", new Vector2(-1, 28)))
|
||||
{
|
||||
_settings.RearmFinishedNavRoute(); // a finished Once route runs again
|
||||
_settings.IsMacroRunning = true;
|
||||
_settings.EnableNavigation = true;
|
||||
if (_settings.BotAction != "Navigating")
|
||||
|
|
|
|||
|
|
@ -389,6 +389,14 @@ public sealed class LegacyUiSettings
|
|||
else next.Add(buffBaseName);
|
||||
_disabledBuffs = next;
|
||||
}
|
||||
/// <summary>
|
||||
/// Cast the armor spells (Impenetrability and the Banes still ticked above) on the shield
|
||||
/// listed in the Items list too, after the armor, on the armor's timers (BuffManager.Shield.cs).
|
||||
/// The self-cast never reaches it: ACE won't wield the wand beside a shield, so buffing puts
|
||||
/// the shield into a pack first. On by default; a profile saved before this setting existed
|
||||
/// loads it as on. No shield listed: nothing changes.
|
||||
/// </summary>
|
||||
public bool BuffShield = true;
|
||||
public bool StartMacroOnLogin;
|
||||
public bool PatrolOnLogin;
|
||||
/// <summary>
|
||||
|
|
@ -726,6 +734,32 @@ public sealed class LegacyUiSettings
|
|||
[JsonIgnore] public NavRouteParser CurrentRoute { get; set; } = new();
|
||||
public int ActiveNavIndex;
|
||||
|
||||
/// <summary>
|
||||
/// True for a Once route that has walked off its last point (the nav engine leaves the
|
||||
/// index past the end). It stays finished over a macro stop/start and a meta turning nav
|
||||
/// on, until it is loaded again, edited, or restarted (/ra nav restart, or
|
||||
/// <see cref="RearmFinishedNavRoute"/> from the player's own nav-on controls).
|
||||
/// </summary>
|
||||
public bool NavRouteFinished()
|
||||
{
|
||||
var route = CurrentRoute;
|
||||
return route != null && route.RouteType == NavRouteType.Once
|
||||
&& route.Points.Count > 0 && ActiveNavIndex >= route.Points.Count;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The player turned nav on (the Nav switch, a Start Navigation button): a finished Once
|
||||
/// route runs again from [0], as re-enabling nav did before 2026-10-28. Metas and scripts
|
||||
/// that switch nav on don't call this, so a stop/start replaying a meta's
|
||||
/// "/vt opt set enablenav true" no longer re-runs a finished route. True if it rewound.
|
||||
/// </summary>
|
||||
public bool RearmFinishedNavRoute()
|
||||
{
|
||||
if (!NavRouteFinished()) return false;
|
||||
ActiveNavIndex = 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool ShowAdvancedWindow;
|
||||
public int SelectedAdvancedTab;
|
||||
|
||||
|
|
|
|||
|
|
@ -3701,6 +3701,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),
|
||||
["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),
|
||||
["AutoVendorEnableBuying"] = (() => B(s.AutoVendorEnableBuying), v => s.AutoVendorEnableBuying = ToDouble(v) != 0),
|
||||
|
|
|
|||
|
|
@ -76,6 +76,22 @@ internal sealed class MetaManager
|
|||
private long _evalChatSeq; // newest chat line its condition matched
|
||||
private Match? _lastChatMatch;
|
||||
|
||||
// ── Macro stop/start replay ──────────────────────────────────────────────
|
||||
// Starting the macro re-arms every rule of the state it is in (so a meta puts back a
|
||||
// route the player changed or cleared while it was stopped). The rules that had already
|
||||
// fired in that state before the stop "replay" when they fire again. A replayed nav load
|
||||
// (EmbedNav, /vt nav load, /ra nav load) of the route that is still loaded and unchanged
|
||||
// keeps the route where it was: its waypoint, a Linear route's direction, a finished
|
||||
// Once route finished; a replayed "/ra nav restart" is skipped. Reloading here restarted
|
||||
// Once routes on every stop/start (2026-10-28). Cleared by the next real state entry; a
|
||||
// rule that first fires after the start is not a replay, and its nav load starts the
|
||||
// route fresh as before.
|
||||
private readonly HashSet<MetaRule> _replayRules = new(ReferenceEqualityComparer.Instance);
|
||||
private bool _replaying; // the action running now belongs to a replayed rule
|
||||
|
||||
/// <summary>Where a meta's nav names are looked for as .nav files. Tests point it at a scratch folder.</summary>
|
||||
internal string NavFolder { get; set; } = Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "NavProfiles");
|
||||
|
||||
// ── Call stack (CallMetaState / ReturnFromCall) ──────────────────────────
|
||||
private readonly Stack<string> _stateStack = new();
|
||||
|
||||
|
|
@ -236,6 +252,73 @@ internal sealed class MetaManager
|
|||
? 0
|
||||
: FindNearestWaypoint(route);
|
||||
|
||||
/// <summary>
|
||||
/// A replayed nav load (see <see cref="_replayRules"/>): true, and nothing reloaded, when
|
||||
/// <paramref name="path"/> is the route loaded now and it still has the points of its source
|
||||
/// <paramref name="source"/> (not edited, reversed or swapped for another since). The route
|
||||
/// keeps its waypoint and a Linear route its direction (the engine sees the same route
|
||||
/// object); nav is switched on as the load would, except for a finished Once route, which
|
||||
/// stays finished. False: the caller loads the route fresh, as before.
|
||||
/// </summary>
|
||||
private bool KeepRunningRoute(string path, NavRouteParser source, string what)
|
||||
{
|
||||
var cur = _settings.CurrentRoute;
|
||||
if (cur == null || cur.Points.Count == 0 || source.Points.Count == 0) return false;
|
||||
if (!SameNavPath(_settings.CurrentNavPath, path)) return false;
|
||||
if (!SameLines(cur.ToLines(), source.ToLines())) return false;
|
||||
|
||||
bool finished = _settings.NavRouteFinished();
|
||||
if (!finished) _settings.EnableNavigation = true;
|
||||
RynthLog.Write(LogCat.Meta, finished
|
||||
? $"[Meta] {what}: the macro started again on the same route, which is finished - it stays finished (/ra nav restart re-runs it)"
|
||||
: $"[Meta] {what}: the macro started again on the same route - it carries on at [{_settings.ActiveNavIndex}] instead of starting over");
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>A replayed "/vt nav load" or "/ra nav load" of the .nav file that is still the loaded, unchanged route.</summary>
|
||||
private bool KeepRunningNavFile(string rawName)
|
||||
{
|
||||
string name = NewProfileFiles.Tidy(rawName, NewProfileFiles.NavExtensions, out _);
|
||||
if (NewProfileFiles.Validate(name) != null) return false;
|
||||
string path = Path.Combine(NavFolder, name + ".nav");
|
||||
if (!File.Exists(path)) return false;
|
||||
return KeepRunningRoute(path, NavRouteParser.Load(path), $"nav load '{name}'");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A replayed /ra nav command that would start the route over: "/ra nav load" of the running,
|
||||
/// unchanged route, or "/ra nav restart". True: skipped, the nav stays where it was.
|
||||
/// </summary>
|
||||
private bool SkipReplayedNavCommand(string cmd)
|
||||
{
|
||||
string[] parts = cmd.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (parts.Length < 3 || !parts[1].Equals("nav", StringComparison.OrdinalIgnoreCase)) return false;
|
||||
if (parts[2].Equals("restart", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
RynthLog.Write(LogCat.Meta, "[Meta] /ra nav restart: not run again for the macro start (it ran when the rule first fired)");
|
||||
return true;
|
||||
}
|
||||
return parts[2].Equals("load", StringComparison.OrdinalIgnoreCase) && parts.Length >= 4
|
||||
&& KeepRunningNavFile(string.Join(" ", parts, 3, parts.Length - 3));
|
||||
}
|
||||
|
||||
private static bool SameNavPath(string? a, string? b)
|
||||
{
|
||||
if (string.IsNullOrEmpty(a) || string.IsNullOrEmpty(b)) return false;
|
||||
if (string.Equals(a, b, StringComparison.OrdinalIgnoreCase)) return true;
|
||||
if (a.StartsWith('<') || b.StartsWith('<')) return false; // "<embedded:...>" is not a file
|
||||
try { return string.Equals(Path.GetFullPath(a), Path.GetFullPath(b), StringComparison.OrdinalIgnoreCase); }
|
||||
catch { return false; }
|
||||
}
|
||||
|
||||
private static bool SameLines(List<string> a, List<string> b)
|
||||
{
|
||||
if (a.Count != b.Count) return false;
|
||||
for (int i = 0; i < a.Count; i++)
|
||||
if (!string.Equals(a[i], b[i], StringComparison.Ordinal)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
public ExpressionEngine Expressions => _expressions ??= CreateExpressionEngine();
|
||||
|
||||
private ExpressionEngine CreateExpressionEngine()
|
||||
|
|
@ -312,7 +395,10 @@ internal sealed class MetaManager
|
|||
// Macro just started — force reset so rules re-evaluate even if state
|
||||
// name matches where we stopped. Otherwise HasFired stays latched across
|
||||
// a stop/start cycle and IF:Always rules like EmbedNav never re-fire.
|
||||
if (!_lastMacroRunning)
|
||||
// The rules that had already fired replay (see _replayRules): a replayed nav
|
||||
// load of the route still running keeps its place instead of starting it over.
|
||||
bool macroStarted = !_lastMacroRunning;
|
||||
if (macroStarted)
|
||||
_settings.ForceStateReset = true;
|
||||
_lastMacroRunning = true;
|
||||
|
||||
|
|
@ -343,9 +429,21 @@ internal sealed class MetaManager
|
|||
_statePStartTime = _statePResume is double resumed ? Clock().AddSeconds(-resumed) : Clock();
|
||||
_statePResume = null;
|
||||
_settings.ForceStateReset = false;
|
||||
// A bare stop/start (no state entry, no meta load pending) replays the rules that
|
||||
// had fired; any other reset is a real state entry and nothing is a replay.
|
||||
bool replay = macroStarted && !realStateEntry && !metaReloaded;
|
||||
lock (_settings.MetaRulesLock)
|
||||
foreach (var r in _settings.MetaRules) r.HasFired = false;
|
||||
{
|
||||
_replayRules.Clear();
|
||||
foreach (var r in _settings.MetaRules)
|
||||
{
|
||||
if (replay && r.HasFired) _replayRules.Add(r);
|
||||
r.HasFired = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (stateChanged)
|
||||
_replayRules.Clear();
|
||||
_lastState = _settings.CurrentState;
|
||||
|
||||
double secondsInState = (Clock() - _stateStartTime).TotalSeconds;
|
||||
|
|
@ -434,7 +532,9 @@ internal sealed class MetaManager
|
|||
if (_settings.MetaDebug)
|
||||
_host.WriteToChat($"[Meta] {rule.State} | {DescribeCondition(rule)} → {DescribeAction(rule)}", 1);
|
||||
|
||||
ExecuteAction(rule);
|
||||
_replaying = _replayRules.Contains(rule);
|
||||
try { ExecuteAction(rule); }
|
||||
finally { _replaying = false; }
|
||||
|
||||
// If state changed during this action, stop evaluating further rules this tick
|
||||
if (_settings.CurrentState != _lastState || _settings.ForceStateReset)
|
||||
|
|
@ -888,7 +988,10 @@ internal sealed class MetaManager
|
|||
if (cmd.StartsWith("/ra ", StringComparison.OrdinalIgnoreCase)
|
||||
|| cmd.Equals("/ra", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
_raCommandHandler?.Invoke(cmd);
|
||||
// A replayed "/ra nav load" of the route still running, or "/ra nav restart",
|
||||
// would start the route over: skipped.
|
||||
if (!(_replaying && SkipReplayedNavCommand(cmd)))
|
||||
_raCommandHandler?.Invoke(cmd);
|
||||
}
|
||||
else if (_host.HasInvokeChatParser)
|
||||
_host.InvokeChatParser(cmd);
|
||||
|
|
@ -977,7 +1080,7 @@ internal sealed class MetaManager
|
|||
// circular hunt through every cell of this dungeon, no nav file). The Meta panel
|
||||
// offers it first in Embedded Nav Route's list. A real route called Patrol wins.
|
||||
if (IsPatrolRoute(routeName) && !_settings.EmbeddedNavs.ContainsKey(routeName)
|
||||
&& !File.Exists(Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "NavProfiles", routeName + ".nav")))
|
||||
&& !File.Exists(Path.Combine(NavFolder, routeName + ".nav")))
|
||||
{
|
||||
_host.Log("[Meta] EmbedNav: Patrol -> /ra dunnav-patrol");
|
||||
if (_raCommandHandler != null) _raCommandHandler("/ra dunnav-patrol");
|
||||
|
|
@ -1002,6 +1105,8 @@ internal sealed class MetaManager
|
|||
if (_settings.EmbeddedNavs.TryGetValue(routeName, out var embedded))
|
||||
{
|
||||
var newRoute = NavRouteParser.LoadFromLines(embedded);
|
||||
// The macro was started again: the route still running keeps its place.
|
||||
if (_replaying && KeepRunningRoute($"<embedded:{routeName}>", newRoute, $"EmbedNav '{routeName}'")) break;
|
||||
_settings.CurrentNavPath = $"<embedded:{routeName}>";
|
||||
_settings.CurrentRoute = newRoute;
|
||||
_settings.ActiveNavIndex = StartIndexForRoute(newRoute);
|
||||
|
|
@ -1012,11 +1117,11 @@ internal sealed class MetaManager
|
|||
}
|
||||
|
||||
// Fallback: a standalone .nav file in NavProfiles.
|
||||
string navFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "NavProfiles");
|
||||
string fullPath = Path.Combine(navFolder, routeName + ".nav");
|
||||
string fullPath = Path.Combine(NavFolder, routeName + ".nav");
|
||||
if (File.Exists(fullPath))
|
||||
{
|
||||
var newRoute = NavRouteParser.Load(fullPath);
|
||||
if (_replaying && KeepRunningRoute(fullPath, newRoute, $"EmbedNav file '{routeName}'")) break;
|
||||
_settings.CurrentNavPath = fullPath;
|
||||
_settings.CurrentRoute = newRoute;
|
||||
_settings.ActiveNavIndex = StartIndexForRoute(newRoute);
|
||||
|
|
@ -1257,6 +1362,9 @@ internal sealed class MetaManager
|
|||
|| parts[2].Equals("save", StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
string name = string.Join(" ", parts, 3, parts.Length - 3);
|
||||
// The macro was started again: the route still running keeps its place.
|
||||
if (_replaying && parts[2].Equals("load", StringComparison.OrdinalIgnoreCase) && KeepRunningNavFile(name))
|
||||
return true;
|
||||
_raCommandHandler?.Invoke($"/ra nav {parts[2].ToLowerInvariant()} {name}");
|
||||
return true;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -763,8 +763,9 @@ internal sealed class NavigationEngine
|
|||
/// Points the route at the waypoint nearest the player (macro start). Circular
|
||||
/// and Linear routes pick from the whole route; a Once route only from the
|
||||
/// current waypoint onward, so finished steps (a recall, a portal) aren't
|
||||
/// repeated. Only plain waypoints are candidates; if the current one is a
|
||||
/// Recall/Portal/Chat/Pause step it is kept. With <c>NavResumeNearest</c> off the
|
||||
/// repeated, and a finished Once route stays finished. Only plain waypoints are
|
||||
/// candidates; if the current one is a Recall/Portal/Chat/Pause step it is kept.
|
||||
/// A Linear route keeps its direction. With <c>NavResumeNearest</c> off the
|
||||
/// route keeps its last waypoint, unless <paramref name="always"/> (hazard escapes
|
||||
/// and corpse runs, which leave the route behind).
|
||||
/// </summary>
|
||||
|
|
@ -781,6 +782,9 @@ internal sealed class NavigationEngine
|
|||
var route = _settings.CurrentRoute;
|
||||
if (route == null || route.Points.Count == 0) return;
|
||||
if (route.RouteType == NavRouteType.Follow) return;
|
||||
// A finished Once route (index left past its end) is done: picking from [0] here
|
||||
// used to turn it back on at the nearest point, so a stop + start re-ran it.
|
||||
if (_settings.NavRouteFinished()) return;
|
||||
if (!TryGetPos(out double ns, out double ew)) return;
|
||||
|
||||
int cur = _settings.ActiveNavIndex;
|
||||
|
|
@ -922,6 +926,23 @@ internal sealed class NavigationEngine
|
|||
_hasGoodHeading = false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// /ra nav restart: the loaded route starts over from its first point, as when it was
|
||||
/// loaded with NavResumeNearest off (a Linear route heading out again, a finished Once
|
||||
/// route running again). Nav is switched on; the macro is left as it is. False (nothing
|
||||
/// done) with no waypoints to walk (none loaded, or a Follow route).
|
||||
/// </summary>
|
||||
public bool RestartRoute()
|
||||
{
|
||||
var route = _settings.CurrentRoute;
|
||||
if (route == null || route.Points.Count == 0 || route.RouteType == NavRouteType.Follow) return false;
|
||||
ResetRouteState();
|
||||
_settings.ActiveNavIndex = 0;
|
||||
_settings.EnableNavigation = true;
|
||||
_host.Log($"Nav: route restarted from [0] ({route.RouteType}, {route.Points.Count} pts)");
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One-shot view of everything the nav engine is keying off. Nav had no
|
||||
/// snapshot (Combat/Buff/Meta did), so a wedged route meant guessing which
|
||||
|
|
@ -1454,14 +1475,17 @@ internal sealed class NavigationEngine
|
|||
/// A finite (Once) route ran off its last point: stop and disable nav, but leave
|
||||
/// the points intact. This used to <c>Points.Clear()</c> the in-memory route, so
|
||||
/// re-enabling nav was a silent no-op until the profile was reloaded
|
||||
/// (2026-06-03 audit P2). The index is left past the end; re-enabling nav lands
|
||||
/// in <see cref="HandleRouteEnd"/>, which rewinds it for a genuine re-run.
|
||||
/// (2026-06-03 audit P2). The index is left past the end, which marks the route
|
||||
/// finished (<see cref="LegacyUiSettings.NavRouteFinished"/>): it stays finished
|
||||
/// over a macro stop/start and a meta turning nav on, and runs again when it is
|
||||
/// loaded again, edited, or restarted (/ra nav restart, or the player's Nav switch /
|
||||
/// Start Navigation button, <see cref="LegacyUiSettings.RearmFinishedNavRoute"/>).
|
||||
/// </summary>
|
||||
private void CompleteOnceRoute(NavRouteParser route)
|
||||
{
|
||||
_settings.EnableNavigation = false;
|
||||
StopMovement();
|
||||
_host.Log($"Nav: Once route complete ({route.Points.Count} pts) — nav disabled, route retained for re-run");
|
||||
_host.Log($"Nav: Once route complete ({route.Points.Count} pts) — nav disabled, route retained (load it again or /ra nav restart to re-run)");
|
||||
}
|
||||
|
||||
private void HandleRouteEnd(NavRouteParser route)
|
||||
|
|
@ -1472,16 +1496,19 @@ internal sealed class NavigationEngine
|
|||
return;
|
||||
}
|
||||
|
||||
// Nav was re-enabled on a finished Once route (CompleteOnceRoute leaves the
|
||||
// index past the end). Rewind so the re-run actually walks instead of
|
||||
// silently doing nothing. Cannot loop: completion always disables nav, and
|
||||
// Tick returns early while it is disabled.
|
||||
if (route.RouteType == NavRouteType.Once
|
||||
&& _settings.ActiveNavIndex >= route.Points.Count
|
||||
&& route.Points.Count > 0)
|
||||
// Nav was switched on over a finished Once route (CompleteOnceRoute leaves the
|
||||
// index past the end). This used to rewind it to [0], so anything that turned nav
|
||||
// on re-ran the route: a meta's "/vt opt set enablenav true" replayed by a macro
|
||||
// start, an expression. It stays finished, as a finished VTank Once route (its
|
||||
// points used up) does; the player's Nav switch / Start Navigation button and
|
||||
// /ra nav restart rewind it before nav gets here. Nav goes off again so the
|
||||
// arbiter doesn't hold "Navigating" (above combat with BoostNavPriority) for a
|
||||
// route with nothing left to walk.
|
||||
if (_settings.NavRouteFinished())
|
||||
{
|
||||
_host.Log("Nav: Once route re-armed — restarting from point [0]");
|
||||
_settings.ActiveNavIndex = 0;
|
||||
_settings.EnableNavigation = false;
|
||||
StopMovement();
|
||||
_host.Log($"Nav: the Once route is finished ({route.Points.Count} pts) — nav stays off; load it again or /ra nav restart to re-run it");
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -66,6 +66,7 @@ public sealed partial class RynthAiPlugin
|
|||
ChatLine("[RynthAi] /ra nav save [name] — save the route; a name saves it as <name>.nav");
|
||||
ChatLine("[RynthAi] /ra nav load <name> — load a nav from NavProfiles (none by that name: a new empty one)");
|
||||
ChatLine("[RynthAi] /ra nav list — list the navs in NavProfiles");
|
||||
ChatLine("[RynthAi] /ra nav restart — run the loaded route again from its first point (a stop/start keeps its place; a finished Once route stays done)");
|
||||
ChatLine("[RynthAi] /ra meta load <name> — load a meta from MetaFiles (none by that name: a new blank one)");
|
||||
ChatLine("[RynthAi] /ra meta new <name> — create a blank meta and load it");
|
||||
ChatLine("[RynthAi] /ra meta list — list the metas in MetaFiles");
|
||||
|
|
@ -1148,8 +1149,24 @@ public sealed partial class RynthAiPlugin
|
|||
var names = _dashboard.NavFileNames();
|
||||
ChatLine(names.Count == 0 ? "[RynthAi] No navs in NavProfiles." : $"[RynthAi] Navs ({names.Count}): {string.Join(", ", names)}");
|
||||
break;
|
||||
case "restart":
|
||||
{
|
||||
// Stopping and starting the macro keeps the route where it was (a finished Once
|
||||
// route stays finished); this is the way to run it again from the top on purpose.
|
||||
var route = _dashboard.Settings.CurrentRoute;
|
||||
if (_navigationEngine == null) { ChatLine("[RynthAi] Navigation engine not ready."); break; }
|
||||
if (!_navigationEngine.RestartRoute())
|
||||
{
|
||||
ChatLine(route != null && route.RouteType == NavRouteType.Follow && route.FollowTargetName.Length > 0
|
||||
? "[RynthAi] A Follow route has no waypoints to restart."
|
||||
: "[RynthAi] No nav route loaded to restart.");
|
||||
break;
|
||||
}
|
||||
ChatLine($"[RynthAi] Nav route restarted from its first point ({route!.RouteType}, {route.Points.Count} waypoints).");
|
||||
break;
|
||||
}
|
||||
default:
|
||||
ChatLine("[RynthAi] /ra nav save [name] | /ra nav load <name> | /ra nav list");
|
||||
ChatLine("[RynthAi] /ra nav save [name] | /ra nav load <name> | /ra nav list | /ra nav restart");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1795,7 +1795,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
// The hold timer keys off wantBuffRaw, NOT off the decision: keying it
|
||||
// off the decision would reset it on the bypass tick itself and the
|
||||
// ~10s retry cadence would silently become "once every 5 minutes".
|
||||
if (!wantBuffRaw)
|
||||
// Only while the macro runs (2026-10-28): stopped mid-heal, buffing still "wanted"
|
||||
// a vital recharge nothing acts on, and 5 min later a stopped character was told
|
||||
// buffing was stuck (stance wedge?) with nothing wrong.
|
||||
if (!wantBuffRaw || !settings.IsMacroRunning)
|
||||
{
|
||||
_buffingHeldSince = DateTime.MinValue;
|
||||
_buffComaWarned = false;
|
||||
|
|
|
|||
|
|
@ -30,6 +30,8 @@ internal sealed class DefSession
|
|||
public Func<uint[], uint[], bool> ReadRetail = (_, _) => false;
|
||||
/// <summary>An object's name as the client knows it (an item in one of AC's slots that the pack read missed); null = unknown.</summary>
|
||||
public Func<uint, string?> ObjectName = _ => null;
|
||||
/// <summary>The spells the character knows, with names, A-Z (empty = can't be read now). Spell slots.</summary>
|
||||
public Func<IReadOnlyList<SpellInfo>> KnownSpells = () => Array.Empty<SpellInfo>();
|
||||
/// <summary>The keys the engine's hotkeys give a chat command ("/rdef use 3"): "F9, Ctrl+1"; "" = none.</summary>
|
||||
public Func<string, string> CommandKeys = _ => string.Empty;
|
||||
/// <summary>Gives own slot N the key (it comes off whatever had it): the plugin's BindOwnSlotKey. False when it can't.</summary>
|
||||
|
|
@ -70,6 +72,11 @@ internal sealed class DefSession
|
|||
{
|
||||
if (slotNumber < 1 || slotNumber > DefSettings.SlotsMax) return $"There is no slot {slotNumber}.";
|
||||
DefSlot slot = Data.Slots[slotNumber - 1];
|
||||
if (slot.IsSpell)
|
||||
{
|
||||
Use.Request(UseRequest.Cast(slot.SpellId, slot.SpellLabel, "slot " + slotNumber, Now()));
|
||||
return null;
|
||||
}
|
||||
if (slot.Item == null) return $"Slot {slotNumber} is empty. Set it from the bar (Edit slots) or with /rdef set {slotNumber}.";
|
||||
Use.Request(new UseRequest(slot.Item, null, slot.Mode, "slot " + slotNumber, Now()));
|
||||
return null;
|
||||
|
|
@ -129,12 +136,48 @@ internal sealed class DefSession
|
|||
if (slotNumber < 1 || slotNumber > DefSettings.SlotsMax) return $"There is no slot {slotNumber}.";
|
||||
DefSlot slot = Data.Slots[slotNumber - 1];
|
||||
slot.Item = ItemRef.From(it);
|
||||
slot.SpellId = 0;
|
||||
slot.SpellName = string.Empty;
|
||||
slot.Mode = UseMode.Auto;
|
||||
Save();
|
||||
ItemKind kind = ItemKinds.Classify(it);
|
||||
return $"Slot {slotNumber}: {it.FullName} ({UseModes.Describe(ItemKinds.DefaultAction(kind))} when pressed).";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Puts a spell the character knows in a slot (the bar's "Put a spell here...": a search over the
|
||||
/// known spells; the engine can't tell which spell is selected in the game's spellbook). Refused for
|
||||
/// a spell the character doesn't know, when the spellbook can be read.
|
||||
/// </summary>
|
||||
public string SetSpell(int slotNumber, uint spellId)
|
||||
{
|
||||
if (slotNumber < 1 || slotNumber > DefSettings.SlotsMax) return $"There is no slot {slotNumber}.";
|
||||
if (spellId == 0) return "That isn't a spell.";
|
||||
IReadOnlyList<SpellInfo> known = KnownSpells();
|
||||
SpellInfo? spell = null;
|
||||
foreach (SpellInfo s in known)
|
||||
if (s.Id == spellId) { spell = s; break; }
|
||||
if (spell == null && known.Count > 0) return $"You don't know {SpellTable.Name(spellId)}, so it can't go in a slot.";
|
||||
SpellInfo info = spell ?? (SpellTable.TryGet(spellId, out SpellInfo t) ? t : new SpellInfo(spellId, SpellTable.Name(spellId), false, false));
|
||||
Data.Slots[slotNumber - 1] = new DefSlot { SpellId = spellId, SpellName = info.Name };
|
||||
Save();
|
||||
return $"Slot {slotNumber}: {info.Name} ({SpellTargeting.Describe(info)} when pressed).";
|
||||
}
|
||||
|
||||
/// <summary>/rdef spell <slot> <name>: one of the character's spells by what the player typed.</summary>
|
||||
public string SetSpellFromName(int slotNumber, string text)
|
||||
{
|
||||
if (slotNumber < 1 || slotNumber > DefSettings.SlotsMax) return $"There is no slot {slotNumber}.";
|
||||
IReadOnlyList<SpellInfo> known = KnownSpells();
|
||||
if (known.Count == 0) return "Your spells can't be read right now (in the world, on RynthCore with ReadKnownSpells).";
|
||||
List<SpellInfo> found = SpellTable.Search(known, text, 6, out int total);
|
||||
if (total == 0) return $"You know no spell named '{text}'.";
|
||||
bool exact = found[0].Name.Equals((text ?? string.Empty).Trim(), StringComparison.OrdinalIgnoreCase);
|
||||
if (total > 1 && !exact)
|
||||
return $"{total} of your spells match '{text}': {string.Join(", ", found.ConvertAll(s => s.Name))}{(total > found.Count ? ", ..." : "")}. Type more of the name.";
|
||||
return SetSpell(slotNumber, found[0].Id);
|
||||
}
|
||||
|
||||
public string ClearSlot(int slotNumber)
|
||||
{
|
||||
if (slotNumber < 1 || slotNumber > DefSettings.SlotsMax) return $"There is no slot {slotNumber}.";
|
||||
|
|
@ -212,6 +255,7 @@ internal sealed class DefSession
|
|||
if (combo.IndexOf(' ') >= 0) return "A key has no spaces, e.g. Ctrl+F9.";
|
||||
if (slotNumber < 1 || slotNumber > DefSettings.SlotsMax) return $"There is no slot {slotNumber}.";
|
||||
ItemRef? item = Data.Slots[slotNumber - 1].Item;
|
||||
if (byName && Data.Slots[slotNumber - 1].IsSpell) return $"Slot {slotNumber} holds a spell: bind the slot itself (/rdef bind {slotNumber} <key>).";
|
||||
if (byName && item == null) return $"Slot {slotNumber} is empty: nothing to bind by name.";
|
||||
|
||||
string command = byName ? NameCommand(item!) : DefCommandParser.UseCommand(slotNumber);
|
||||
|
|
@ -261,12 +305,12 @@ internal sealed class DefSession
|
|||
return "The Shortcuts bar shows the game's 18 slots first again; RynthDefective's own slots follow them from slot 19 (its slot 1 there).";
|
||||
var ids = new uint[DefSettings.RetailSlots];
|
||||
var spells = new uint[DefSettings.RetailSlots];
|
||||
int items = ReadRetail(ids, spells) ? BarMapping.RetailItems(ids) : 0;
|
||||
int items = ReadRetail(ids, spells) ? BarMapping.RetailShortcuts(ids, spells) : 0;
|
||||
CopyOffer = items;
|
||||
const string what = "The Shortcuts bar is independent of the game's toolbar now: every slot is RynthDefective's own "
|
||||
+ "(clicks one-touch, keys RynthCore hotkeys). The game's toolbar and its keys are unchanged.";
|
||||
return items == 0 ? what
|
||||
: what + $" The game's 18 slots hold {items} item{(items == 1 ? "" : "s")}: Defective Settings offers to copy them in.";
|
||||
: what + $" The game's 18 slots hold {items} shortcut{(items == 1 ? "" : "s")} (items and spells): Defective Settings offers to copy them in.";
|
||||
}
|
||||
|
||||
/// <summary>The player said no to the copy.</summary>
|
||||
|
|
@ -301,8 +345,8 @@ internal sealed class DefSession
|
|||
if (BindOwnKey(to, key)) keysMoved++; else keysFailed++;
|
||||
Keys.Invalidate();
|
||||
|
||||
string msg = r.Copied == 0 ? "None of the game's slots held an item to copy." : $"Copied {r.Copied} of the game's slots into this bar (slots 1-18).";
|
||||
if (r.Skipped > 0) msg += $" {r.Skipped} couldn't be (a spell, or an item not in your pack).";
|
||||
string msg = r.Copied == 0 ? "None of the game's slots held an item or a spell to copy." : $"Copied {r.Copied} of the game's slots into this bar (slots 1-18).";
|
||||
if (r.Skipped > 0) msg += $" {r.Skipped} couldn't be (an item not in your pack whose name the game doesn't know).";
|
||||
if (r.Moved.Count > 0)
|
||||
msg += $" Your own {r.Moved.Count} slot{(r.Moved.Count == 1 ? "" : "s")} moved after them, to 19 and on"
|
||||
+ (keysMoved > 0 ? $", {keysMoved} key{(keysMoved == 1 ? "" : "s")} with them" : "") + ".";
|
||||
|
|
|
|||
|
|
@ -2,7 +2,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 }
|
||||
internal enum DefVerb { Toggle, Help, Use, Set, Clear, Bind, Unbind, Weapons, Favourite, Slots, List, Status, Error, Panels, Selection, Settings, Spell }
|
||||
|
||||
/// <summary>A parsed "/rdef ..." line. Use: <see cref="Slot"/> (1-based) or <see cref="Text"/> (an item name).</summary>
|
||||
internal sealed record DefCommand(DefVerb Verb, int Slot = 0, string Text = "", string Error = "");
|
||||
|
|
@ -10,7 +10,7 @@ internal sealed record DefCommand(DefVerb Verb, int Slot = 0, string Text = "",
|
|||
internal static class DefCommandParser
|
||||
{
|
||||
public const string Usage =
|
||||
"/rdef [use <slot or item name> | set <slot> [item name] | clear <slot> | bind <slot> <key> | unbind <slot> | "
|
||||
"/rdef [use <slot or item name> | set <slot> [item name] | spell <slot> <spell name> | clear <slot> | bind <slot> <key> | unbind <slot> | "
|
||||
+ "weapons [search] | fav | slots <count> | list | status | settings | panels (the game panel buttons) | selection]";
|
||||
|
||||
/// <summary>Parses the arguments after "/rdef" (blank = show or hide the bar).</summary>
|
||||
|
|
@ -43,6 +43,13 @@ internal static class DefCommandParser
|
|||
if (slotText == null || !TrySlot(slotText, out int slot)) return Fail("Which slot? e.g. /rdef set 3 (the item selected in the game goes in slot 3) or /rdef set 3 Peerless Healing Kit");
|
||||
return new DefCommand(DefVerb.Set, slot, tail);
|
||||
}
|
||||
case "spell":
|
||||
{
|
||||
SplitSlot(rest, out string? slotText, out string tail);
|
||||
if (slotText == null || !TrySlot(slotText, out int slot) || tail.Length == 0)
|
||||
return Fail("Usage: /rdef spell <slot> <spell name>, e.g. /rdef spell 3 Heal Self VI (one of your spells; the slot casts it)");
|
||||
return new DefCommand(DefVerb.Spell, slot, tail);
|
||||
}
|
||||
case "clear":
|
||||
{
|
||||
return TrySlot(rest, out int slot) ? new DefCommand(DefVerb.Clear, slot) : Fail("Which slot? e.g. /rdef clear 3");
|
||||
|
|
|
|||
|
|
@ -4,17 +4,29 @@ using RynthCore.Plugin.RynthDefective.Items;
|
|||
|
||||
namespace RynthCore.Plugin.RynthDefective.Model;
|
||||
|
||||
/// <summary>One slot of the bar: an item (or nothing) and how pressing it uses that item.</summary>
|
||||
/// <summary>One slot of the bar: an item or a spell (or nothing), and how pressing it uses that item.</summary>
|
||||
internal sealed class DefSlot
|
||||
{
|
||||
/// <summary>The item the slot holds; null = empty.</summary>
|
||||
/// <summary>The item the slot holds; null = none.</summary>
|
||||
public ItemRef? Item;
|
||||
/// <summary>How pressing it uses the item. <see cref="UseMode.Auto"/> picks by what the item is.</summary>
|
||||
public UseMode Mode = UseMode.Auto;
|
||||
/// <summary>The spell the slot casts (2026-10-28); 0 = none. A slot holds an item or a spell, never both.</summary>
|
||||
public uint SpellId;
|
||||
/// <summary>The spell's name when it was put in the slot (shown when the spell table doesn't know it).</summary>
|
||||
public string SpellName = string.Empty;
|
||||
|
||||
public bool Empty => Item == null;
|
||||
public bool Empty => Item == null && SpellId == 0;
|
||||
public bool IsSpell => Item == null && SpellId != 0;
|
||||
|
||||
public DefSlot Clone() => new() { Item = Item?.Clone(), Mode = Mode };
|
||||
/// <summary>What the slot holds, by name: the item's, the spell's, or "".</summary>
|
||||
public string Label => Item?.FullName ?? (SpellId != 0 ? SpellLabel : string.Empty);
|
||||
|
||||
/// <summary>The spell's name: the table's, else the saved one, else "Spell 1234".</summary>
|
||||
public string SpellLabel =>
|
||||
SpellTable.TryGet(SpellId, out SpellInfo s) ? s.Name : SpellName.Length > 0 ? SpellName : SpellTable.Name(SpellId);
|
||||
|
||||
public DefSlot Clone() => new() { Item = Item?.Clone(), Mode = Mode, SpellId = SpellId, SpellName = SpellName };
|
||||
}
|
||||
|
||||
/// <summary>The "use as" choice of a slot.</summary>
|
||||
|
|
|
|||
|
|
@ -83,6 +83,12 @@ internal sealed class DefStore
|
|||
slot.Item = ParseRef(e, "item");
|
||||
int mode = Int(e, "mode", 0);
|
||||
slot.Mode = mode >= 0 && mode <= (int)UseMode.Equip ? (UseMode)mode : UseMode.Auto;
|
||||
// A spell (2026-10-28; a file from before has none): only in a slot without an item.
|
||||
if (slot.Item == null && e.TryGetProperty("spell", out JsonElement sp) && sp.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
slot.SpellId = UInt(sp, "id");
|
||||
slot.SpellName = slot.SpellId != 0 ? Str(sp, "name") : string.Empty;
|
||||
}
|
||||
}
|
||||
}
|
||||
ParseRefs(root, "favourites", d.Favourites, DefData.MaxFavourites);
|
||||
|
|
@ -167,6 +173,13 @@ internal sealed class DefStore
|
|||
{
|
||||
w.WriteStartObject();
|
||||
if (slot.Item != null) WriteRef(w, "item", slot.Item);
|
||||
else if (slot.SpellId != 0)
|
||||
{
|
||||
w.WriteStartObject("spell");
|
||||
w.WriteNumber("id", slot.SpellId);
|
||||
w.WriteString("name", slot.SpellLabel);
|
||||
w.WriteEndObject();
|
||||
}
|
||||
w.WriteNumber("mode", (int)slot.Mode);
|
||||
w.WriteEndObject();
|
||||
}
|
||||
|
|
|
|||
188
Plugins/RynthCore.Plugin.RynthDefective/Model/Spells.cs
Normal file
188
Plugins/RynthCore.Plugin.RynthDefective/Model/Spells.cs
Normal file
|
|
@ -0,0 +1,188 @@
|
|||
// ============================================================================
|
||||
// RynthDefective - Model/Spells.cs
|
||||
// Spell slots (2026-10-28): what a spell is called, whom it is cast on, and
|
||||
// finding one of the character's spells by name. Pure (the tests run it).
|
||||
//
|
||||
// The engine's plugin API has no spell names or targets and no way to read
|
||||
// the spell selected in AC's spellbook or spell bar, so the names and the
|
||||
// "self-targeted" / "harmful" flags come from RynthAi's spell table
|
||||
// (Combat\SpellData.txt, linked in as RynthInventory and RynthOracle link it:
|
||||
// id, name, category, family, words, duration, difficulty, then three flags,
|
||||
// the second harmful, the third self-targeted), and the player picks a spell
|
||||
// by name from the ones the character knows (ReadKnownSpells).
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
|
||||
namespace RynthCore.Plugin.RynthDefective.Model;
|
||||
|
||||
/// <summary>One spell: its name, and whether it is cast on yourself only (recalls, Self buffs) or harms its target (war, debuffs).</summary>
|
||||
internal readonly record struct SpellInfo(uint Id, string Name, bool SelfTargeted, bool Harmful);
|
||||
|
||||
internal static class SpellTable
|
||||
{
|
||||
private const string ResourceName = "RynthDefective.SpellData.txt";
|
||||
private static Dictionary<uint, SpellInfo>? _byId;
|
||||
|
||||
public static bool TryGet(uint id, out SpellInfo info)
|
||||
{
|
||||
EnsureLoaded();
|
||||
return _byId!.TryGetValue(id, out info);
|
||||
}
|
||||
|
||||
/// <summary>The spell's name, or "Spell 1234" for one the table doesn't have (a server's own).</summary>
|
||||
public static string Name(uint id) => TryGet(id, out SpellInfo s) ? s.Name : "Spell " + id.ToString(CultureInfo.InvariantCulture);
|
||||
|
||||
public static int Count
|
||||
{
|
||||
get { EnsureLoaded(); return _byId!.Count; }
|
||||
}
|
||||
|
||||
private static void EnsureLoaded()
|
||||
{
|
||||
if (_byId != null) return;
|
||||
Dictionary<uint, SpellInfo> map;
|
||||
try
|
||||
{
|
||||
using Stream? s = Assembly.GetExecutingAssembly().GetManifestResourceStream(ResourceName);
|
||||
if (s == null) map = new Dictionary<uint, SpellInfo>();
|
||||
else
|
||||
{
|
||||
using var reader = new StreamReader(s, detectEncodingFromByteOrderMarks: true);
|
||||
map = Parse(reader);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
map = new Dictionary<uint, SpellInfo>(); // a missing table costs names ("Spell 1234") and targets (by the selection)
|
||||
}
|
||||
_byId = map;
|
||||
}
|
||||
|
||||
/// <summary>The table's lines (the tests read their own).</summary>
|
||||
internal static Dictionary<uint, SpellInfo> Parse(TextReader reader)
|
||||
{
|
||||
var map = new Dictionary<uint, SpellInfo>(6400);
|
||||
while (reader.ReadLine() is string line)
|
||||
{
|
||||
string[] c = line.Split('\t');
|
||||
if (c.Length < 2 || !uint.TryParse(c[0].Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out uint id) || id == 0) continue;
|
||||
string name = c[1].Trim();
|
||||
if (name.Length == 0) continue;
|
||||
bool harmful = c.Length > 8 && c[8].Trim().Equals("True", StringComparison.OrdinalIgnoreCase);
|
||||
bool self = c.Length > 9 && c[9].Trim().Equals("True", StringComparison.OrdinalIgnoreCase);
|
||||
map[id] = new SpellInfo(id, name, self, harmful);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
/// <summary>The character's spells (ids) with names, A-Z; ones the table doesn't name are listed by number.</summary>
|
||||
public static SpellInfo[] Known(ReadOnlySpan<uint> ids)
|
||||
{
|
||||
var list = new List<SpellInfo>(ids.Length);
|
||||
var seen = new HashSet<uint>();
|
||||
foreach (uint id in ids)
|
||||
{
|
||||
if (id == 0 || !seen.Add(id)) continue;
|
||||
list.Add(TryGet(id, out SpellInfo s) ? s : new SpellInfo(id, Name(id), false, false));
|
||||
}
|
||||
list.Sort((a, b) =>
|
||||
{
|
||||
int c = string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase);
|
||||
return c != 0 ? c : a.Id.CompareTo(b.Id);
|
||||
});
|
||||
return list.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The spells in <paramref name="known"/> that match what the player typed, best first: the exact
|
||||
/// name, then names starting with it, then names holding every word of it ("heal self", "vi heal").
|
||||
/// At most <paramref name="max"/>; <paramref name="total"/> is how many matched. Blank = all of them.
|
||||
/// </summary>
|
||||
public static List<SpellInfo> Search(IReadOnlyList<SpellInfo> known, string? query, int max, out int total)
|
||||
{
|
||||
string q = (query ?? string.Empty).Trim();
|
||||
string[] words = q.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
var exact = new List<SpellInfo>();
|
||||
var starts = new List<SpellInfo>();
|
||||
var contains = new List<SpellInfo>();
|
||||
foreach (SpellInfo s in known)
|
||||
{
|
||||
if (q.Length == 0) { contains.Add(s); continue; }
|
||||
if (s.Name.Equals(q, StringComparison.OrdinalIgnoreCase)) exact.Add(s);
|
||||
else if (s.Name.StartsWith(q, StringComparison.OrdinalIgnoreCase)) starts.Add(s);
|
||||
else if (AllWords(s.Name, words)) contains.Add(s);
|
||||
}
|
||||
total = exact.Count + starts.Count + contains.Count;
|
||||
var result = new List<SpellInfo>(Math.Min(total, Math.Max(0, max)));
|
||||
foreach (List<SpellInfo> group in new[] { exact, starts, contains })
|
||||
foreach (SpellInfo s in group)
|
||||
{
|
||||
if (result.Count >= max) return result;
|
||||
result.Add(s);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static bool AllWords(string name, string[] words)
|
||||
{
|
||||
if (words.Length == 0) return false;
|
||||
foreach (string w in words)
|
||||
if (name.IndexOf(w, StringComparison.OrdinalIgnoreCase) < 0) return false;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Whom a spell slot's cast goes to.</summary>
|
||||
internal enum CastAt { Yourself, Selection, Refused }
|
||||
|
||||
internal static class SpellTargeting
|
||||
{
|
||||
/// <summary>
|
||||
/// The target for casting <paramref name="spell"/> now. A self-targeted spell (a recall, a Self buff)
|
||||
/// is cast on yourself whatever is selected. Any other spell goes on the selection; with nothing
|
||||
/// selected a beneficial one (Heal Other, a buff, an item spell) is cast on yourself, a harmful one
|
||||
/// (war, void, a debuff) is refused, and so is a harmful one with yourself selected. A spell the table
|
||||
/// doesn't know goes on the selection, else on yourself. <paramref name="why"/> says why it was refused.
|
||||
/// </summary>
|
||||
public static CastAt Decide(SpellInfo? spell, uint selected, uint player, out uint target, out string why)
|
||||
{
|
||||
why = string.Empty;
|
||||
target = 0;
|
||||
if (player == 0)
|
||||
{
|
||||
why = "the character isn't ready";
|
||||
return CastAt.Refused;
|
||||
}
|
||||
if (spell is { SelfTargeted: true })
|
||||
{
|
||||
target = player;
|
||||
return CastAt.Yourself;
|
||||
}
|
||||
bool harmful = spell is { Harmful: true };
|
||||
if (selected != 0 && selected != player)
|
||||
{
|
||||
target = selected;
|
||||
return CastAt.Selection;
|
||||
}
|
||||
if (harmful)
|
||||
{
|
||||
why = selected == player ? "select a monster first (you have yourself selected)" : "select a target first";
|
||||
return CastAt.Refused;
|
||||
}
|
||||
target = player;
|
||||
return CastAt.Yourself;
|
||||
}
|
||||
|
||||
/// <summary>"cast on you" / "cast on the selection (else on you)" / "cast on the selected monster", for the slot's tooltip.</summary>
|
||||
public static string Describe(SpellInfo? spell) => spell switch
|
||||
{
|
||||
{ SelfTargeted: true } => "cast on you",
|
||||
{ Harmful: true } => "cast on the selected target",
|
||||
_ => "cast on the selected target, or on you with nothing selected",
|
||||
};
|
||||
}
|
||||
|
|
@ -30,7 +30,7 @@ all three go.
|
|||
* **Independent of the game's toolbar** (per character, off by default): every slot on the bar is
|
||||
RynthDefective's own. The game's 18 slots are not on it; clicks are one-touch (a kit on yourself, a
|
||||
potion used, a weapon wielded) and keys are RynthCore hotkeys (`/rdef use N` for bar slot N). Turning it
|
||||
on offers to copy the items in the game's 18 slots into the bar's slots 1-18 (nothing is copied unless you
|
||||
on offers to copy the items and spells in the game's 18 slots into the bar's slots 1-18 (nothing is copied unless you
|
||||
say so); your own slots move after them, to 19 and on, with their keys, so the bar looks as it did. The
|
||||
game's toolbar and its keys are not changed. Turning it off shows the game's 18 first again, RynthDefective's
|
||||
slot 1 at 19.
|
||||
|
|
@ -51,6 +51,17 @@ a potion, a scroll, a weapon, a wand, a shield... Click a slot, or press its key
|
|||
|
||||
A slot can be set to another way: use it, use it on me, use it on the selected target, or wield it.
|
||||
|
||||
**Spell slots.** One of RynthDefective's own slots can hold a spell instead: right-click it on the Shortcuts
|
||||
bar and choose *Put a spell here...*, then find the spell by name among the ones the character knows (the
|
||||
engine can't tell RynthDefective which spell is selected in the game's spellbook, so it is picked there), or
|
||||
type `/rdef spell 3 Heal Self VI`. Its picture is the spell's. Pressing it casts the spell, in Magic mode
|
||||
(asked for first when the character is in another stance; the cast waits for the stance to settle): a spell
|
||||
cast on yourself only (Self buffs, recalls) goes on you; any other on the selection, or on you when nothing is
|
||||
selected and the spell is a helpful one (Heal Other, a buff); a war, void or debuff spell with nothing (or
|
||||
yourself) selected is refused and says so, as is a spell the character doesn't know. The same one-at-a-time
|
||||
and busy rules as items apply. The game's own 18 slots keep the game's own spell handling; copying them into an
|
||||
independent bar brings their spells along as spell slots.
|
||||
|
||||
**Put an item in a slot** (Edit slots in the bar): *Set from selected* takes the item you have selected
|
||||
in the game, or *Pick from pack* chooses from a searchable list of what you carry. `/rdef set 3` does the
|
||||
first, `/rdef set 3 Health Potion` the second.
|
||||
|
|
@ -84,6 +95,13 @@ weapons you wielded are listed first (they are also in their kind's group).
|
|||
the server, or the last action is unanswered (the server's UseDone; a wield is answered by the item
|
||||
reading in hand). Pressing again while one waits does not queue a second; pressing another slot replaces the
|
||||
waiting one. A request not sent within 6 s gives up and says why.
|
||||
* A busy reading that just sits there is a leftover, not a reason to wait: the client's busy count can stay
|
||||
up with nothing in flight after a death, a login or an interrupted action (and RynthAi's "waiting on the
|
||||
server" with it). A count that hasn't moved for 4 s with nothing of RynthDefective's in flight, a gesture
|
||||
that has "animated" for 4 s, or RynthAi's bit on for 5.5 s holds nothing (logged once); only a count above
|
||||
that leftover holds again. RynthDefective never resets the count itself (the engine owns it). If the server
|
||||
really is busy it answers "You're too busy" and the use is tried once more a second later.
|
||||
* A key pressed in portal space (a death's too) is not kept for later: it says so.
|
||||
* After a wield from a fighting stance the stance follows the weapon (wand: magic, melee weapon: melee,
|
||||
launcher with ammunition in hand: missile) once the character is still. At peace you stay at peace. A bow
|
||||
without arrows in hand returns you to peace rather than leaving a stance it can't use. Shields, armor and
|
||||
|
|
@ -99,6 +117,7 @@ weapons you wielded are listed first (they are also in their kind's group).
|
|||
/rdef panels | selection show / hide the Game Panels buttons, the Selection window
|
||||
/rdef use <slot | item name> use the slot's item, or the carried item with that name
|
||||
/rdef set <slot> [item name] put the selected item (or the named one) in a slot
|
||||
/rdef spell <slot> <name> put one of your spells in a slot (it casts it)
|
||||
/rdef clear <slot> empty a slot
|
||||
/rdef bind <slot> <key> bind a key (F9, Ctrl+1 ...) to the slot; /rdef unbind <slot>
|
||||
/rdef weapons [search] show the weapon picker
|
||||
|
|
@ -107,7 +126,7 @@ weapons you wielded are listed first (they are also in their kind's group).
|
|||
/rdef list | status | help
|
||||
```
|
||||
|
||||
`/rdef use`, `set`, `clear`, `bind` take RynthDefective's own slot numbers (1-42): on the Shortcuts bar own
|
||||
`/rdef use`, `set`, `spell`, `clear`, `bind` take RynthDefective's own slot numbers (1-42): on the Shortcuts bar own
|
||||
slot N is bar slot 18+N, or bar slot N when the bar is independent of the game's toolbar.
|
||||
|
||||
## Settings
|
||||
|
|
@ -120,8 +139,8 @@ with the slots, favourites and recent weapons in
|
|||
|
||||
## Not in 0.1
|
||||
|
||||
Pages, spell slots, arrow auto-equip, gear highlight, summon cooldown counters and the war-magic element
|
||||
changer (Defective has them).
|
||||
Pages, arrow auto-equip, gear highlight, summon cooldown counters and the war-magic element changer
|
||||
(Defective has them).
|
||||
|
||||
## Needs
|
||||
|
||||
|
|
|
|||
|
|
@ -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). -->
|
||||
<RynthPluginMinEngineApi>66</RynthPluginMinEngineApi>
|
||||
<RynthPluginDescription>Draws the Shortcuts bar (the game's 18 slots and its own), the Game Panels buttons and the Selection window: one-touch kits, potions and weapons by slot or key, and a fast weapon picker. Settings: the bar's gear or /rdef settings.</RynthPluginDescription>
|
||||
<RynthPluginDescription>Draws the Shortcuts bar (the game's 18 slots and its own), the Game Panels buttons and the Selection window: one-touch kits, potions, weapons and spells by slot or key, and a fast weapon picker. Settings: the bar's gear or /rdef settings.</RynthPluginDescription>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
|
@ -42,6 +42,11 @@
|
|||
<!-- Install-folder resolver (env, HKCU, HKLM, default C:\Games). Read only; same file as RynthCore src\Shared. -->
|
||||
<Compile Include="..\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<!-- Spell slots (2026-10-28): spell names and whom a spell is cast on, from RynthAi's spell table
|
||||
(linked as RynthInventory and RynthOracle link it; Model/Spells.cs reads it). -->
|
||||
<EmbeddedResource Include="..\RynthCore.Plugin.RynthAi\Combat\SpellData.txt" LogicalName="RynthDefective.SpellData.txt" Link="Shared\SpellData.txt" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<!-- The shortcut bar (2026-10-22): drawn with ImGui.NET bound to the engine's cimgui, in the
|
||||
engine's look (Shared\RynthUi; plugin API v90 hosts the frameless window and gives AC's
|
||||
|
|
|
|||
|
|
@ -235,6 +235,14 @@ public sealed partial class RynthDefectivePlugin : IBarActions
|
|||
_nextBarBuildMs = 0;
|
||||
});
|
||||
|
||||
public void SetSpell(int number, uint spellId) => QueueBar(() =>
|
||||
{
|
||||
// The game's own slots take spells from the game's spellbook (drag one onto the retail toolbar).
|
||||
if (IsRetail(number)) { Print($"Slot {number} is the game's own: drag the spell onto it from the game's spellbook."); return; }
|
||||
Print(_session.SetSpell(OwnOf(number), spellId));
|
||||
_nextBarBuildMs = 0;
|
||||
});
|
||||
|
||||
public void ChangeSlotCount(int delta) => QueueBar(() =>
|
||||
{
|
||||
DefSettings st = _session.Settings;
|
||||
|
|
|
|||
|
|
@ -72,6 +72,7 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
|
|||
_session.Save = RequestSave;
|
||||
_session.ReadRetail = ReadRetail;
|
||||
_session.ObjectName = id => Host.TryGetObjectName(id, out string n) && n.Length > 0 ? n : null;
|
||||
_session.KnownSpells = () => _world.KnownSpells(HostDefWorld.KnownMaxAgeMs);
|
||||
_session.CommandKeys = command => Host.HasKeyBinding ? Host.GetActionKeys(command) : string.Empty;
|
||||
_session.BindOwnKey = (own, key) => Host.HasKeyBinding && BindOwnSlotKey(own, key, out _);
|
||||
|
||||
|
|
@ -108,7 +109,7 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
|
|||
_inWorld = true;
|
||||
_identityKnown = false;
|
||||
_nextIdentityTryMs = Environment.TickCount64;
|
||||
_session.Use.Reset();
|
||||
_session.Use.ResetSession();
|
||||
_world?.Reset();
|
||||
}
|
||||
|
||||
|
|
@ -118,7 +119,7 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
|
|||
_inWorld = false;
|
||||
_identityKnown = false;
|
||||
_session.LoggedIn = false;
|
||||
_session.Use.Reset();
|
||||
_session.Use.ResetSession();
|
||||
_world?.Reset();
|
||||
_barView = RynthCore.Plugin.RynthDefective.ShortcutBar.BarSnapshot.NotReady;
|
||||
foreach (UiWindow? w in new[] { _barWindow, _pickerWindow, _settingsWindow })
|
||||
|
|
@ -130,7 +131,7 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
|
|||
public override void Shutdown()
|
||||
{
|
||||
SaveNow();
|
||||
_session.Use.Reset();
|
||||
_session.Use.ResetSession();
|
||||
_ui.SubmitEmpty(Host);
|
||||
}
|
||||
|
||||
|
|
@ -209,6 +210,9 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
|
|||
case DefVerb.Set:
|
||||
Print(c.Text.Length > 0 ? _session.SetFromName(c.Slot, c.Text) : _session.SetFromSelected(c.Slot));
|
||||
break;
|
||||
case DefVerb.Spell:
|
||||
Print(_session.SetSpellFromName(c.Slot, c.Text));
|
||||
break;
|
||||
case DefVerb.Clear:
|
||||
Print(_session.ClearSlot(c.Slot));
|
||||
break;
|
||||
|
|
@ -252,6 +256,11 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
|
|||
for (int i = 1; i <= _session.Settings.SlotCount; i++)
|
||||
{
|
||||
DefSlot slot = _session.Data.Slots[i - 1];
|
||||
if (slot.IsSpell)
|
||||
{
|
||||
Print($"{i}: {slot.SpellLabel} (a spell){(_session.KeyOfSlot(i) is { } sk ? " [" + sk + "]" : "")}");
|
||||
continue;
|
||||
}
|
||||
if (slot.Item == null) { Print($"{i}: (empty)"); continue; }
|
||||
SlotStatus s = ItemMatcher.Status(slot.Item, items);
|
||||
sb.Clear();
|
||||
|
|
|
|||
|
|
@ -59,8 +59,9 @@ internal static class BarMapping
|
|||
/// Copies AC's 18 slots (<paramref name="ids"/>, <paramref name="spells"/>, slot 1 first) into the own
|
||||
/// slots 1-18, so an independent bar looks as the usual one did: the own slots that were after AC's
|
||||
/// (own N at bar 18+N) move to own 18+N, where an independent bar shows them. <see cref="BarCopyResult.Moved"/>
|
||||
/// lists the moves of the slots that held something (their "/rdef use N" keys go with them). A spell, or
|
||||
/// an item <paramref name="resolve"/> can't name, can't go in an own slot: that slot stays empty (Skipped).
|
||||
/// lists the moves of the slots that held something (their "/rdef use N" keys go with them). A spell goes
|
||||
/// in as a spell slot (2026-10-28); an item <paramref name="resolve"/> can't name can't go in an own slot:
|
||||
/// that slot stays empty (Skipped).
|
||||
/// Refused (nothing changed) when an own slot past 24 holds something: there is no room to move it.
|
||||
/// </summary>
|
||||
public static BarCopyResult CopyRetail(List<DefSlot> own, ReadOnlySpan<uint> ids, ReadOnlySpan<uint> spells, Func<uint, ItemRef?> resolve)
|
||||
|
|
@ -68,7 +69,7 @@ internal static class BarMapping
|
|||
const int retail = DefSettings.RetailSlots, room = DefSettings.SlotsMax - DefSettings.RetailSlots;
|
||||
for (int n = room + 1; n <= own.Count; n++)
|
||||
if (!own[n - 1].Empty)
|
||||
return new BarCopyResult(0, 0, Array.Empty<(int, int)>(), $"Your slot {n} holds {own[n - 1].Item!.FullName}: there is no room to move "
|
||||
return new BarCopyResult(0, 0, Array.Empty<(int, int)>(), $"Your slot {n} holds {own[n - 1].Label}: there is no room to move "
|
||||
+ $"slots {room + 1}-{DefSettings.SlotsMax} after the game's {retail}. Empty them (or copy by hand) first.");
|
||||
|
||||
var next = DefData.NewSlots();
|
||||
|
|
@ -85,7 +86,11 @@ internal static class BarMapping
|
|||
uint id = i < ids.Length ? ids[i] : 0, spell = i < spells.Length ? spells[i] : 0;
|
||||
if (id == 0)
|
||||
{
|
||||
if (spell != 0) skipped++;
|
||||
if (spell != 0)
|
||||
{
|
||||
next[i] = new DefSlot { SpellId = spell, SpellName = SpellTable.Name(spell) };
|
||||
copied++;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
ItemRef? r = resolve(id);
|
||||
|
|
@ -97,11 +102,12 @@ internal static class BarMapping
|
|||
return new BarCopyResult(copied, skipped, moved, null);
|
||||
}
|
||||
|
||||
/// <summary>How many of AC's slots hold an item (spells can't be copied, so they don't count).</summary>
|
||||
public static int RetailItems(ReadOnlySpan<uint> ids)
|
||||
/// <summary>How many of AC's slots hold an item or a spell (what a copy would bring over).</summary>
|
||||
public static int RetailShortcuts(ReadOnlySpan<uint> ids, ReadOnlySpan<uint> spells)
|
||||
{
|
||||
int n = 0;
|
||||
foreach (uint id in ids) if (id != 0) n++;
|
||||
for (int i = 0; i < ids.Length; i++)
|
||||
if (ids[i] != 0 || (i < spells.Length && spells[i] != 0)) n++;
|
||||
return n;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -11,6 +11,8 @@
|
|||
// the bar shows (DefSettings.BarSlots).
|
||||
// An independent bar (DefSettings.IndependentBar) has no AC slots: every slot
|
||||
// N is own slot N (BarMapping), and AC's toolbar isn't read at all.
|
||||
// An own slot can hold a spell (2026-10-28): its picture is the spell's, and
|
||||
// the snapshot carries the character's spells for the slot menu's search.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
|
|
@ -43,10 +45,17 @@ internal sealed record BarSlot(
|
|||
public bool Empty => ObjectId == 0 && SpellId == 0 && Name.Length == 0;
|
||||
}
|
||||
|
||||
/// <summary>The bar as drawn. Independent: every slot is RynthDefective's own (DefSettings.IndependentBar).</summary>
|
||||
internal sealed record BarSnapshot(BarSlot[] Slots, bool Ready, int IconSize, bool Independent = false)
|
||||
/// <summary>
|
||||
/// The bar as drawn. Independent: every slot is RynthDefective's own (DefSettings.IndependentBar).
|
||||
/// Spells: the character's spells, A-Z, for "Put a spell here..." (empty when they can't be read);
|
||||
/// CanCast: the engine casts for plugins.
|
||||
/// </summary>
|
||||
internal sealed record BarSnapshot(BarSlot[] Slots, bool Ready, int IconSize, bool Independent = false,
|
||||
IReadOnlyList<SpellInfo>? Spells = null, bool CanCast = false)
|
||||
{
|
||||
public static readonly BarSnapshot NotReady = new(Array.Empty<BarSlot>(), false, 36);
|
||||
|
||||
public IReadOnlyList<SpellInfo> KnownSpells => Spells ?? Array.Empty<SpellInfo>();
|
||||
}
|
||||
|
||||
/// <summary>Builds the snapshot on the plugin tick (reads the host and the carried items).</summary>
|
||||
|
|
@ -82,12 +91,14 @@ internal sealed class BarSnapshotBuilder
|
|||
{
|
||||
if (!_host.HasShortcuts) return BarSnapshot.NotReady;
|
||||
DefSettings st = session.Settings;
|
||||
IReadOnlyList<SpellInfo> spells = session.KnownSpells();
|
||||
bool canCast = _host.HasCastSpell;
|
||||
if (st.IndependentBar)
|
||||
{
|
||||
// Every slot is RynthDefective's own: AC's toolbar isn't read or shown (BarMapping).
|
||||
var own = new BarSlot[st.BarSlots];
|
||||
for (int n = 1; n <= st.BarSlots; n++) own[n - 1] = Own(n, BarMapping.OwnSlot(n, true), true, session, items, _host);
|
||||
return new BarSnapshot(own, true, st.ButtonSize, true);
|
||||
for (int n = 1; n <= st.BarSlots; n++) own[n - 1] = Own(n, BarMapping.OwnSlot(n, true), true, session, items, spells, _host);
|
||||
return new BarSnapshot(own, true, st.ButtonSize, true, spells, canCast);
|
||||
}
|
||||
if (_host.GetShortcuts(_ids, _spells) == 0) return BarSnapshot.NotReady;
|
||||
RefreshKeys(now);
|
||||
|
|
@ -96,8 +107,8 @@ internal sealed class BarSnapshotBuilder
|
|||
|
||||
var slots = new BarSlot[st.BarSlots];
|
||||
for (int n = 1; n <= st.BarSlots; n++)
|
||||
slots[n - 1] = BarMapping.IsRetail(n, false) ? Retail(n, byId) : Own(n, BarMapping.OwnSlot(n, false), false, session, items, _host);
|
||||
return new BarSnapshot(slots, true, st.ButtonSize);
|
||||
slots[n - 1] = BarMapping.IsRetail(n, false) ? Retail(n, byId) : Own(n, BarMapping.OwnSlot(n, false), false, session, items, spells, _host);
|
||||
return new BarSnapshot(slots, true, st.ButtonSize, false, spells, canCast);
|
||||
}
|
||||
|
||||
private BarSlot Retail(int n, Dictionary<uint, CarriedItem> byId)
|
||||
|
|
@ -123,13 +134,14 @@ internal sealed class BarSnapshotBuilder
|
|||
count = "none";
|
||||
tone = CountTone.Missing;
|
||||
}
|
||||
else name = $"Spell {spell}";
|
||||
else name = SpellTable.Name(spell);
|
||||
string tip = $"Slot {n} (the game's own): {name}{(count.Length > 0 ? " - " + count : "")}.{KeysLine(allKeys)}\n" +
|
||||
"Click: use it, as its key does. Right-click: change the slot or its keys.";
|
||||
return new BarSlot(n, true, 0, id, id == 0 ? spell : 0, name, count, tone, key, allKeys, tip);
|
||||
}
|
||||
|
||||
private static BarSlot Own(int n, int own, bool independent, DefSession session, IReadOnlyList<CarriedItem> items, RynthCoreHost host)
|
||||
private static BarSlot Own(int n, int own, bool independent, DefSession session, IReadOnlyList<CarriedItem> items,
|
||||
IReadOnlyList<SpellInfo> spells, RynthCoreHost host)
|
||||
{
|
||||
DefSlot slot = own >= 1 && own <= session.Data.Slots.Count ? session.Data.Slots[own - 1] : new DefSlot();
|
||||
// Every key of "/rdef use N" (the engine's hotkeys), else the one bound to the item by name.
|
||||
|
|
@ -137,9 +149,10 @@ internal sealed class BarSnapshotBuilder
|
|||
string key = all.Length > 0 ? FirstKey(all) : session.KeyOfSlot(own) ?? string.Empty;
|
||||
if (all.Length == 0) all = key;
|
||||
string whose = independent ? "RynthCore's: this bar is independent of the game's toolbar" : "RynthCore's: the game holds 18";
|
||||
if (slot.IsSpell) return OwnSpell(n, own, slot, whose, key, all, spells);
|
||||
if (slot.Item == null)
|
||||
return new BarSlot(n, false, own, 0, 0, string.Empty, string.Empty, CountTone.Plain, SlotText.ShortKey(key), all,
|
||||
$"Slot {n} ({whose}): empty.{KeysLine(all)}\nRight-click: put the selected item here, or change its keys.");
|
||||
$"Slot {n} ({whose}): empty.{KeysLine(all)}\nRight-click: put the selected item or one of your spells here, or change its keys.");
|
||||
SlotStatus s = ItemMatcher.Status(slot.Item, items);
|
||||
string count = SlotText.Count(s, out uint color);
|
||||
CountTone tone = color == SlotText.InHand ? CountTone.InHand : color == SlotText.Missing ? CountTone.Missing : CountTone.Plain;
|
||||
|
|
@ -149,6 +162,24 @@ internal sealed class BarSnapshotBuilder
|
|||
SlotText.ShortKey(key), all, tip);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A spell slot: the spell's picture and name. A spell the character doesn't know (another
|
||||
/// character's file, a spell lost) shows dimmed with "?" (when the spellbook can be read at all).
|
||||
/// </summary>
|
||||
private static BarSlot OwnSpell(int n, int own, DefSlot slot, string whose, string key, string all, IReadOnlyList<SpellInfo> spells)
|
||||
{
|
||||
string name = slot.SpellLabel;
|
||||
SpellInfo? info = SpellTable.TryGet(slot.SpellId, out SpellInfo si) ? si : null;
|
||||
bool known = spells.Count == 0;
|
||||
foreach (SpellInfo s in spells)
|
||||
if (s.Id == slot.SpellId) { known = true; break; }
|
||||
string tip = $"Slot {n}: {name}, a spell.\nClick or press the key: {SpellTargeting.Describe(info)} (Magic mode first)."
|
||||
+ (known ? "" : "\nYou don't know this spell: pressing it does nothing.")
|
||||
+ (key.Length > 0 ? "\nKey: " + key : "\nNo key yet.") + $"\n({whose}.)\nRight-click: change the slot or its keys.";
|
||||
return new BarSlot(n, false, own, 0, slot.SpellId, name, known ? string.Empty : "?", known ? CountTone.Plain : CountTone.Missing,
|
||||
SlotText.ShortKey(key), all, tip);
|
||||
}
|
||||
|
||||
/// <summary>The first of "1, Ctrl+1": what fits on the slot.</summary>
|
||||
private static string FirstKey(string keys)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -25,12 +25,16 @@
|
|||
// /rdef use N. A key comes off whatever had it, after the player says so.
|
||||
// An independent bar (DefSettings.IndependentBar) has only RynthDefective's
|
||||
// own slots: every key is an engine hotkey (BarMapping, BarSlot.Own).
|
||||
// Spells (2026-10-28): an own slot's menu has "Put a spell here...", a search
|
||||
// over the character's spells (the engine can't read the spell selected in
|
||||
// the game's spellbook); the slot then casts it (UseController).
|
||||
//
|
||||
// AC's render thread. Reads the snapshot the tick built; every click is
|
||||
// queued for the tick (IBarActions).
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Numerics;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Plugin.RynthDefective.Model;
|
||||
|
|
@ -48,6 +52,8 @@ internal interface IBarActions
|
|||
void SetFromSelected(int number);
|
||||
void Clear(int number);
|
||||
void ChangeSlotCount(int delta);
|
||||
/// <summary>Puts spell <paramref name="spellId"/> in bar slot <paramref name="number"/> (one of RynthDefective's own).</summary>
|
||||
void SetSpell(int number, uint spellId);
|
||||
/// <summary>An item dragged out of AC's UI was let go over slot <paramref name="number"/>.</summary>
|
||||
void DropItem(int number, uint objectId);
|
||||
/// <summary>A key was bound or removed: the bar asks for its keys again.</summary>
|
||||
|
|
@ -155,6 +161,12 @@ internal sealed class ShortcutBarWindow
|
|||
ImGui.OpenPopup(KeyPopupId);
|
||||
}
|
||||
KeyPopup();
|
||||
if (_openSpellPopup)
|
||||
{
|
||||
_openSpellPopup = false;
|
||||
ImGui.OpenPopup(SpellPopupId);
|
||||
}
|
||||
SpellPopup(view);
|
||||
return height;
|
||||
}
|
||||
|
||||
|
|
@ -367,6 +379,15 @@ internal sealed class ShortcutBarWindow
|
|||
ImGui.Separator();
|
||||
bool hasSelection = _host.HasGetSelectedItemId && _host.GetSelectedItemId() != 0;
|
||||
if (ImGui.MenuItem("Put the selected item here", null, false, hasSelection)) _act.SetFromSelected(s.Number);
|
||||
if (!s.Retail)
|
||||
{
|
||||
if (ImGui.MenuItem("Put a spell here...", null, false, view.CanCast)) StartSpellPick(s);
|
||||
SafeImGui.SetItemTooltip(view.CanCast
|
||||
? "One of your spells, found by name: the slot casts it, in Magic mode, on the selection\n"
|
||||
+ "(on you for your own spells, or with nothing selected for a helpful one).\n"
|
||||
+ "The game doesn't tell RynthCore which spell is selected in its spellbook, so you find it here."
|
||||
: "This RynthCore can't cast spells for a plugin.");
|
||||
}
|
||||
if (ImGui.MenuItem("Empty this slot", null, false, !s.Empty)) _act.Clear(s.Number);
|
||||
ImGui.Separator();
|
||||
if (!_host.HasKeyBinding)
|
||||
|
|
@ -441,6 +462,95 @@ internal sealed class ShortcutBarWindow
|
|||
SafeImGui.SetItemTooltip(tip);
|
||||
}
|
||||
|
||||
// ── Spells: "Put a spell here..." ─────────────────────────────────────
|
||||
|
||||
private const string SpellPopupId = "##sb_spell_popup";
|
||||
private const int SpellRows = 40;
|
||||
private bool _openSpellPopup, _spellFocus;
|
||||
private BarSlot? _spellSlot;
|
||||
private string _spellSearch = string.Empty, _spellQuery = "\0";
|
||||
private IReadOnlyList<SpellInfo>? _spellSource;
|
||||
private List<SpellInfo> _spellMatches = new();
|
||||
private int _spellTotal;
|
||||
|
||||
private void StartSpellPick(BarSlot slot)
|
||||
{
|
||||
_spellSlot = slot;
|
||||
_spellSearch = string.Empty;
|
||||
_spellSource = null;
|
||||
_spellFocus = true;
|
||||
_openSpellPopup = true;
|
||||
}
|
||||
|
||||
private void SpellPopup(BarSnapshot view)
|
||||
{
|
||||
if (!ImGui.IsPopupOpen(SpellPopupId)) return;
|
||||
ImGui.PushStyleColor(ImGuiCol.PopupBg, WithAlpha(_bg, 0xFA));
|
||||
ImGui.PushStyleColor(ImGuiCol.Border, _line);
|
||||
ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, Px(4));
|
||||
ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(Px(8), Px(7)));
|
||||
bool open = ImGui.BeginPopup(SpellPopupId);
|
||||
ImGui.PopStyleVar(2);
|
||||
ImGui.PopStyleColor(2);
|
||||
if (!open) return;
|
||||
try
|
||||
{
|
||||
BarSlot? ss = _spellSlot;
|
||||
if (ss == null) { ImGui.CloseCurrentPopup(); return; }
|
||||
float w = Px(250), row = Px(20);
|
||||
ImGui.TextDisabled($"Slot {ss.Number}: a spell to cast");
|
||||
IReadOnlyList<SpellInfo> known = view.KnownSpells;
|
||||
if (_spellFocus)
|
||||
{
|
||||
ImGui.SetKeyboardFocusHere();
|
||||
_spellFocus = false;
|
||||
}
|
||||
ImGui.SetNextItemWidth(w);
|
||||
ImGui.InputTextWithHint("##sb_spell_search", "type a spell's name", ref _spellSearch, 64u);
|
||||
if (!ReferenceEquals(known, _spellSource) || _spellSearch != _spellQuery)
|
||||
{
|
||||
_spellSource = known;
|
||||
_spellQuery = _spellSearch;
|
||||
_spellMatches = SpellTable.Search(known, _spellSearch, SpellRows, out _spellTotal);
|
||||
}
|
||||
if (known.Count == 0) ImGui.TextDisabled("Your spells can't be read right now.");
|
||||
else
|
||||
{
|
||||
int shown = Math.Clamp(_spellMatches.Count, 1, 10);
|
||||
if (ImGui.BeginChild("##sb_spell_list", new Vector2(w, shown * (row + Px(2)) + Px(8)), ImGuiChildFlags.Borders))
|
||||
{
|
||||
foreach (SpellInfo sp in _spellMatches)
|
||||
{
|
||||
ImGui.PushID(unchecked((int)sp.Id));
|
||||
Vector2 start = ImGui.GetCursorPos();
|
||||
bool clicked = ImGui.Selectable("##sp", false, ImGuiSelectableFlags.AllowOverlap, new Vector2(0, row));
|
||||
SafeImGui.SetItemTooltip($"{sp.Name}: {SpellTargeting.Describe(sp)}.");
|
||||
ImGui.SetCursorPos(start);
|
||||
IntPtr tex = _host.GetIconTexture(RynthIconKind.Spell, sp.Id);
|
||||
if (tex != IntPtr.Zero) ImGui.Image(tex, new Vector2(row, row));
|
||||
else ImGui.Dummy(new Vector2(row, row));
|
||||
ImGui.SameLine();
|
||||
ImGui.SetCursorPosY(start.Y + (row - ImGui.GetTextLineHeight()) * 0.5f);
|
||||
ImGui.TextUnformatted(sp.Name);
|
||||
ImGui.PopID();
|
||||
if (clicked)
|
||||
{
|
||||
_act.SetSpell(ss.Number, sp.Id);
|
||||
_spellSlot = null;
|
||||
ImGui.CloseCurrentPopup();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
ImGui.EndChild();
|
||||
if (_spellMatches.Count == 0) ImGui.TextDisabled("You know no spell by that name.");
|
||||
else if (_spellTotal > _spellMatches.Count) SafeImGui.TextDisabled($"{_spellTotal - _spellMatches.Count} more: type more of the name.");
|
||||
}
|
||||
if (ImGui.Button("Cancel")) { _spellSlot = null; ImGui.CloseCurrentPopup(); }
|
||||
}
|
||||
finally { ImGui.EndPopup(); }
|
||||
}
|
||||
|
||||
// ── Keys: "press a key" ───────────────────────────────────────────────
|
||||
|
||||
private enum KeyStep { Waiting, Confirm, Message }
|
||||
|
|
|
|||
|
|
@ -60,6 +60,7 @@ internal static class UiFormat
|
|||
// Image icon kinds (op level 2)
|
||||
public const byte IconKindIcon = 0; // a 0x06 texture id
|
||||
public const byte IconKindObject = 1; // a live object's icon with underlay and overlay
|
||||
public const byte IconKindSpell = 2; // a spell id: the spell's icon
|
||||
|
||||
// Selectable flags
|
||||
public const uint SelectableAllowDoubleClick = 4;
|
||||
|
|
|
|||
200
Plugins/RynthCore.Plugin.RynthDefective/Use/BusyGate.cs
Normal file
200
Plugins/RynthCore.Plugin.RynthDefective/Use/BusyGate.cs
Normal file
|
|
@ -0,0 +1,200 @@
|
|||
// ============================================================================
|
||||
// RynthDefective - Use/BusyGate.cs
|
||||
// Whether the client's "busy" readings really hold a use back (2026-10-28).
|
||||
//
|
||||
// Why: the busy count the engine reports (GetBusyState) can stay above zero
|
||||
// with nothing at all in flight: after a death (the engine's own resync waits
|
||||
// out the death portal and 5 s more), after a logout and a login (the engine
|
||||
// keeps its count across the session and can't clear it again), after an
|
||||
// interrupted action. Holding every use on it made the bar "not work at all
|
||||
// after logging in" until the client was restarted, and kits wait seconds
|
||||
// after every death. RynthAi copes the same way (Combat/CombatBusyGate: a
|
||||
// leftover count doesn't hold a heal), and RynthAi's "waiting on the server"
|
||||
// bit includes its copy of the same count, so it sticks with it.
|
||||
//
|
||||
// The rule (pure: BusyRule.Decide; BusyGate keeps the clocks):
|
||||
// * a gesture animating holds, for at most AnimationMaxMs without a break
|
||||
// (RynthAi's ActionPacer.GestureHoldMaxMs: no real gesture lasts longer);
|
||||
// * the busy count holds while it is above the count already judged a
|
||||
// leftover AND it moved within CountTrustMs or our own last use went out
|
||||
// within OwnTrustMs. A count that has read the same for longer, with
|
||||
// nothing of ours in flight, is a leftover: it holds nothing, and only a
|
||||
// count above it holds again (our own next use raises it and the server's
|
||||
// answer brings it back down to the leftover);
|
||||
// * RynthAi's "waiting on the server" bit holds while it is fresh:
|
||||
// BotTrustMs since it came on (RynthAi's own actions are answered or let
|
||||
// go well inside it), or only CountTrustMs when a leftover count explains it.
|
||||
// After that the use is sent: if the server really is busy it answers
|
||||
// "You're too busy" (UseDone 0x1D) and the use controller tries once more.
|
||||
//
|
||||
// RynthDefective never resets the client's count itself (ForceResetBusyCount):
|
||||
// the count is the engine's (its reconciler and watchdogs own it), RynthAi
|
||||
// stopped resetting it on 2026-10-06 because a reset zeroes actions the server
|
||||
// hasn't answered yet (each later answer then drives it negative), and nothing
|
||||
// here needs it at zero: ignoring a leftover is enough to send.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
|
||||
namespace RynthCore.Plugin.RynthDefective.Use;
|
||||
|
||||
/// <summary>What holds a use back now; None = send.</summary>
|
||||
internal enum BusyHold { None, Busy, Animation, Bot }
|
||||
|
||||
/// <summary>The readings that were ignored as leftovers (each logged once).</summary>
|
||||
[Flags]
|
||||
internal enum BusyStale { None = 0, Count = 1, Animation = 2, Bot = 4 }
|
||||
|
||||
/// <summary>The readings at one moment, and how long each has read so. Pure data.</summary>
|
||||
/// <param name="Count">The client's busy count (GetBusyState).</param>
|
||||
/// <param name="CountSteadyMs">How long it has read this value.</param>
|
||||
/// <param name="Leftover">The count already judged a leftover (0 = none): a reading at or under it holds nothing.</param>
|
||||
/// <param name="SinceOwnSendMs">Since RynthDefective's own last use or cast went out.</param>
|
||||
/// <param name="Animating">A cast or use gesture is animating.</param>
|
||||
/// <param name="AnimatingMs">How long it has animated without a break.</param>
|
||||
/// <param name="BotWaiting">RynthAi is waiting on the server (null = RynthAi isn't there).</param>
|
||||
/// <param name="BotSteadyMs">How long that bit has read its current value.</param>
|
||||
internal readonly record struct BusyFacts(
|
||||
int Count, long CountSteadyMs, int Leftover, long SinceOwnSendMs,
|
||||
bool Animating, long AnimatingMs, bool? BotWaiting, long BotSteadyMs);
|
||||
|
||||
internal static class BusyRule
|
||||
{
|
||||
/// <summary>A count that moved this recently is an action under way (a kit 2.5 s, a corpse use 3.7 s at the most seen).</summary>
|
||||
public const long CountTrustMs = 4000;
|
||||
/// <summary>After our own use went out the count is ours this long.</summary>
|
||||
public const long OwnTrustMs = 4000;
|
||||
/// <summary>A gesture that lasts longer is a stuck motion queue (RynthAi's ActionPacer.GestureHoldMaxMs).</summary>
|
||||
public const long AnimationMaxMs = 4000;
|
||||
/// <summary>RynthAi's bit this long: its corpse uses are let go at 5 s (ActionPacer.WorldUseMaxMs).</summary>
|
||||
public const long BotTrustMs = 5500;
|
||||
|
||||
/// <summary>What holds a use back; <paramref name="stale"/> names the readings ignored as leftovers.</summary>
|
||||
public static BusyHold Decide(in BusyFacts f, out BusyStale stale)
|
||||
{
|
||||
stale = BusyStale.None;
|
||||
if (f.Animating)
|
||||
{
|
||||
if (f.AnimatingMs < AnimationMaxMs) return BusyHold.Animation;
|
||||
stale |= BusyStale.Animation;
|
||||
}
|
||||
if (f.Count > 0)
|
||||
{
|
||||
bool fresh = f.CountSteadyMs < CountTrustMs || f.SinceOwnSendMs < OwnTrustMs;
|
||||
if (f.Count > f.Leftover && fresh) return BusyHold.Busy;
|
||||
stale |= BusyStale.Count;
|
||||
}
|
||||
if (f.BotWaiting == true)
|
||||
{
|
||||
// RynthAi's bit includes its copy of the same count: a leftover count explains it.
|
||||
long trust = (stale & BusyStale.Count) != 0 ? CountTrustMs : BotTrustMs;
|
||||
if (f.BotSteadyMs < trust) return BusyHold.Bot;
|
||||
stale |= BusyStale.Bot;
|
||||
}
|
||||
return BusyHold.None;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The clocks behind <see cref="BusyRule"/>: how long each reading has read the same, our own last
|
||||
/// send, and the leftover count. <see cref="Observe"/> every tick (in or out of the world: a count
|
||||
/// left by a death has read the same all through the death portal), <see cref="Judge"/> when a use
|
||||
/// wants to go. Plugin pump thread only.
|
||||
/// </summary>
|
||||
internal sealed class BusyGate
|
||||
{
|
||||
private bool _started;
|
||||
private int _count, _leftover;
|
||||
private long _countSinceMs;
|
||||
private bool _animating;
|
||||
private long _animatingSinceMs;
|
||||
private bool? _bot;
|
||||
private long _botSinceMs;
|
||||
private long _ownSendMs = long.MinValue / 4;
|
||||
private BusyStale _logged;
|
||||
|
||||
/// <summary>The count judged a leftover (0 = none).</summary>
|
||||
public int Leftover => _leftover;
|
||||
|
||||
public void Observe(int count, bool animating, bool? botWaiting, long now)
|
||||
{
|
||||
if (count < 0) count = 0;
|
||||
if (!_started)
|
||||
{
|
||||
_started = true;
|
||||
_count = count;
|
||||
_countSinceMs = now;
|
||||
_animating = animating;
|
||||
_animatingSinceMs = now;
|
||||
_bot = botWaiting;
|
||||
_botSinceMs = now;
|
||||
}
|
||||
if (count != _count)
|
||||
{
|
||||
_count = count;
|
||||
_countSinceMs = now;
|
||||
}
|
||||
if (_leftover > count) _leftover = count; // part of it was answered or cleared: what is left is the leftover
|
||||
if (count == 0) _logged &= ~BusyStale.Count;
|
||||
if (animating != _animating)
|
||||
{
|
||||
_animating = animating;
|
||||
_animatingSinceMs = now;
|
||||
if (!animating) _logged &= ~BusyStale.Animation;
|
||||
}
|
||||
if (botWaiting != _bot)
|
||||
{
|
||||
_bot = botWaiting;
|
||||
_botSinceMs = now;
|
||||
if (botWaiting != true) _logged &= ~BusyStale.Bot;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Our own use or cast went out now.</summary>
|
||||
public void NoteOwnSend(long now) => _ownSendMs = now;
|
||||
|
||||
public BusyFacts Facts(long now) => new(
|
||||
_count, now - _countSinceMs, _leftover, now - _ownSendMs,
|
||||
_animating, _animating ? now - _animatingSinceMs : 0, _bot, now - _botSinceMs);
|
||||
|
||||
/// <summary>
|
||||
/// What holds a use back now. A count found to be a leftover becomes the new leftover;
|
||||
/// <paramref name="newlyIgnored"/> names the leftovers not reported before (log them once).
|
||||
/// </summary>
|
||||
public BusyHold Judge(long now, out BusyStale newlyIgnored)
|
||||
{
|
||||
BusyHold hold = BusyRule.Decide(Facts(now), out BusyStale stale);
|
||||
if ((stale & BusyStale.Count) != 0 && _count > _leftover)
|
||||
{
|
||||
_leftover = _count;
|
||||
_logged &= ~BusyStale.Count; // a new leftover is worth its own line
|
||||
}
|
||||
newlyIgnored = stale & ~_logged;
|
||||
_logged |= stale;
|
||||
return hold;
|
||||
}
|
||||
|
||||
/// <summary>The words for the log line when a leftover is first ignored.</summary>
|
||||
public string Describe(BusyStale what, long now)
|
||||
{
|
||||
BusyFacts f = Facts(now);
|
||||
var parts = new System.Collections.Generic.List<string>(3);
|
||||
if ((what & BusyStale.Count) != 0)
|
||||
parts.Add($"the client's busy count has read {f.Count} for {f.CountSteadyMs / 1000.0:0.0} s with nothing of ours in flight");
|
||||
if ((what & BusyStale.Animation) != 0)
|
||||
parts.Add($"the character has read 'animating' for {f.AnimatingMs / 1000.0:0.0} s");
|
||||
if ((what & BusyStale.Bot) != 0)
|
||||
parts.Add($"RynthAi has read 'waiting on the server' for {f.BotSteadyMs / 1000.0:0.0} s"
|
||||
+ ((what & BusyStale.Count) != 0 || (_logged & BusyStale.Count) != 0 ? " (its copy of the same count)" : ""));
|
||||
return "[RynthDefective] " + string.Join("; ", parts)
|
||||
+ ": a leftover (a death, a login or an interrupted action), not waited on. The count itself is left alone.";
|
||||
}
|
||||
|
||||
public void Reset()
|
||||
{
|
||||
_started = false;
|
||||
_leftover = 0;
|
||||
_logged = BusyStale.None;
|
||||
_ownSendMs = long.MinValue / 4;
|
||||
}
|
||||
}
|
||||
|
|
@ -3,6 +3,7 @@ using System.Collections.Generic;
|
|||
using System.Runtime.InteropServices;
|
||||
using System.Text.Json;
|
||||
using RynthCore.Plugin.RynthDefective.Items;
|
||||
using RynthCore.Plugin.RynthDefective.Model;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
|
|
@ -29,9 +30,12 @@ internal sealed unsafe class HostDefWorld : IDefWorld
|
|||
public bool InWorld => _host.HasGetPlayerId && _host.GetPlayerId() != 0 && !(_host.HasIsPortaling && _host.IsPortaling());
|
||||
public uint PlayerId => _host.HasGetPlayerId ? _host.GetPlayerId() : 0;
|
||||
public uint SelectedId => _host.HasGetSelectedItemId ? _host.GetSelectedItemId() : 0;
|
||||
public bool ClientBusy => _host.HasGetBusyState && _host.GetBusyState() != 0;
|
||||
public int BusyCount => _host.HasGetBusyState ? Math.Max(0, _host.GetBusyState()) : 0;
|
||||
public bool Animating => _host.HasGetCastBusyState && _host.GetCastBusyState() != 0;
|
||||
public int UseDoneSeq => _host.HasUseDoneSeq ? _host.GetUseDoneSeq() : 0;
|
||||
|
||||
public uint UseDoneError(int seqAtSend) =>
|
||||
_host.TryGetLastUseDone(out int seq, out uint error) && seq == seqAtSend + 1 ? error : 0;
|
||||
public int CombatMode => _host.GetCurrentCombatMode();
|
||||
|
||||
public bool? BotWaitingOnServer => BotActivity.Read(_host) is { } a ? (a & RynthAiActivity.ServerAction) != 0 : null;
|
||||
|
|
@ -67,11 +71,81 @@ internal sealed unsafe class HostDefWorld : IDefWorld
|
|||
public bool UseObjectOn(uint id, uint target) => _host.HasUseObjectOn && _host.UseObjectOn(id, target);
|
||||
public bool SetCombatMode(int mode) => _host.HasChangeCombatMode && _host.ChangeCombatMode(mode);
|
||||
|
||||
// ── Spells (spell slots) ────────────────────────────────────────────────
|
||||
|
||||
/// <summary>The character's spells are re-read when older than this (a spell scribed since shows within it).</summary>
|
||||
public const long KnownMaxAgeMs = 5000;
|
||||
private uint[] _knownBuf = new uint[2048];
|
||||
private HashSet<uint>? _known;
|
||||
private SpellInfo[] _knownList = Array.Empty<SpellInfo>();
|
||||
private long _knownAtMs = long.MinValue / 4;
|
||||
|
||||
public bool CanCast => _host.HasCastSpell;
|
||||
|
||||
public bool CastSpell(uint target, uint spellId) =>
|
||||
_host.HasCastSpell && spellId != 0 && spellId <= int.MaxValue && _host.CastSpell(target, (int)spellId);
|
||||
|
||||
/// <summary>
|
||||
/// From the spellbook the engine reads (ReadKnownSpells; RynthAi's note: the engine's IsSpellKnown
|
||||
/// answers "known" for spells the character doesn't have, so it isn't asked). A "no" is checked
|
||||
/// against a fresh read before it is believed. Null when the spellbook can't be read.
|
||||
/// </summary>
|
||||
public bool? KnowsSpell(uint spellId)
|
||||
{
|
||||
HashSet<uint>? known = KnownIds(KnownMaxAgeMs);
|
||||
if (known == null) return null;
|
||||
if (known.Contains(spellId)) return true;
|
||||
known = KnownIds(0);
|
||||
return known == null ? null : known.Contains(spellId);
|
||||
}
|
||||
|
||||
/// <summary>The character's spells with names, A-Z (the bar's spell search); empty when they can't be read.</summary>
|
||||
public SpellInfo[] KnownSpells(long maxAgeMs)
|
||||
{
|
||||
KnownIds(maxAgeMs);
|
||||
return _knownList;
|
||||
}
|
||||
|
||||
private HashSet<uint>? KnownIds(long maxAgeMs)
|
||||
{
|
||||
long now = NowMs;
|
||||
if (now - _knownAtMs < maxAgeMs) return _known;
|
||||
_knownAtMs = now;
|
||||
if (!_host.HasReadKnownSpells)
|
||||
{
|
||||
_known = null;
|
||||
_knownList = Array.Empty<SpellInfo>();
|
||||
return null;
|
||||
}
|
||||
int n = _host.ReadKnownSpells(_knownBuf, _knownBuf.Length);
|
||||
if (n > _knownBuf.Length && n <= 65536)
|
||||
{
|
||||
_knownBuf = new uint[n];
|
||||
n = _host.ReadKnownSpells(_knownBuf, _knownBuf.Length);
|
||||
}
|
||||
if (n <= 0)
|
||||
{
|
||||
// Not readable yet (before the character's description arrives): can't tell.
|
||||
_known = null;
|
||||
_knownList = Array.Empty<SpellInfo>();
|
||||
return null;
|
||||
}
|
||||
n = Math.Min(n, _knownBuf.Length);
|
||||
var set = new HashSet<uint>(n);
|
||||
for (int i = 0; i < n; i++) if (_knownBuf[i] != 0) set.Add(_knownBuf[i]);
|
||||
if (_known == null || !set.SetEquals(_known)) _knownList = SpellTable.Known(_knownBuf.AsSpan(0, n));
|
||||
_known = set;
|
||||
return set;
|
||||
}
|
||||
|
||||
public void Reset()
|
||||
{
|
||||
_reader.Reset();
|
||||
_items = new List<CarriedItem>();
|
||||
_itemsAtMs = long.MinValue / 4;
|
||||
_known = null;
|
||||
_knownList = Array.Empty<SpellInfo>();
|
||||
_knownAtMs = long.MinValue / 4;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -16,8 +16,11 @@ internal interface IDefWorld
|
|||
bool InWorld { get; }
|
||||
uint PlayerId { get; }
|
||||
uint SelectedId { get; }
|
||||
/// <summary>The client's busy count is above zero (an item action it sent has not been answered).</summary>
|
||||
bool ClientBusy { get; }
|
||||
/// <summary>
|
||||
/// The client's busy count (0 = idle): the item actions and casts it sent that the server hasn't
|
||||
/// answered. It can read above zero with nothing in flight (BusyGate says when it holds a use).
|
||||
/// </summary>
|
||||
int BusyCount { get; }
|
||||
/// <summary>A cast or use gesture is animating.</summary>
|
||||
bool Animating { get; }
|
||||
/// <summary>RynthAi is waiting on the server for an action it sent (null = RynthAi isn't there).</summary>
|
||||
|
|
@ -26,6 +29,8 @@ internal interface IDefWorld
|
|||
bool? BotMacroRunning { get; }
|
||||
/// <summary>Count of the server's UseDone events; 0 when the engine can't report them.</summary>
|
||||
int UseDoneSeq { get; }
|
||||
/// <summary>The error of the server's first UseDone after <paramref name="seqAtSend"/> (0x1D: "You're too busy"); 0 = none or unknown.</summary>
|
||||
uint UseDoneError(int seqAtSend);
|
||||
/// <summary>1 NonCombat, 2 Melee, 4 Missile, 8 Magic.</summary>
|
||||
int CombatMode { get; }
|
||||
/// <summary>The server's refusals so far (0x028A / 0x00A0 ... count), to tell a new one.</summary>
|
||||
|
|
@ -41,18 +46,40 @@ internal interface IDefWorld
|
|||
bool UseObject(uint id);
|
||||
bool UseObjectOn(uint id, uint target);
|
||||
bool SetCombatMode(int mode);
|
||||
|
||||
/// <summary>The engine can cast (CastSpell).</summary>
|
||||
bool CanCast { get; }
|
||||
/// <summary>Whether the character knows the spell; null = can't tell (the server refuses one it doesn't).</summary>
|
||||
bool? KnowsSpell(uint spellId);
|
||||
/// <summary>Casts the spell at <paramref name="target"/> (the player id for yourself).</summary>
|
||||
bool CastSpell(uint target, uint spellId);
|
||||
}
|
||||
|
||||
/// <summary>One thing the player asked to use: an exact item (a slot's) or a name typed in a command.</summary>
|
||||
/// <summary>
|
||||
/// One thing the player asked to use: an exact item (a slot's), a name typed in a command, or a spell
|
||||
/// to cast (<see cref="Spell"/>, a spell slot's; Item and Name are null then).
|
||||
/// </summary>
|
||||
internal sealed record UseRequest(ItemRef? Item, string? Name, UseMode Mode, string Source, long AtMs)
|
||||
{
|
||||
/// <summary>Same item, same way: pressing the key again must not queue a second one.</summary>
|
||||
/// <summary>Sent once already and answered "You're too busy": this is the one more try.</summary>
|
||||
public bool Retry { get; init; }
|
||||
/// <summary>The spell to cast (2026-10-28); 0 = an item.</summary>
|
||||
public uint Spell { get; init; }
|
||||
/// <summary>The spell's name as the slot has it.</summary>
|
||||
public string SpellName { get; init; } = string.Empty;
|
||||
|
||||
/// <summary>A spell slot's cast for <paramref name="spellId"/>.</summary>
|
||||
public static UseRequest Cast(uint spellId, string name, string source, long atMs) =>
|
||||
new(null, null, UseMode.Auto, source, atMs) { Spell = spellId, SpellName = name };
|
||||
|
||||
/// <summary>Same item (or spell), same way: pressing the key again must not queue a second one.</summary>
|
||||
public bool SameAs(UseRequest o) =>
|
||||
Mode == o.Mode
|
||||
&& ((Item != null && o.Item != null && Item.SameAs(o.Item))
|
||||
|| (Name != null && o.Name != null && string.Equals(Name, o.Name, StringComparison.OrdinalIgnoreCase)));
|
||||
|| (Name != null && o.Name != null && string.Equals(Name, o.Name, StringComparison.OrdinalIgnoreCase))
|
||||
|| (Spell != 0 && Spell == o.Spell));
|
||||
|
||||
public string Label => Item?.FullName ?? Name ?? "item";
|
||||
public string Label => Item?.FullName ?? (Spell != 0 ? (SpellName.Length > 0 ? SpellName : SpellTable.Name(Spell)) : Name) ?? "item";
|
||||
}
|
||||
|
||||
/// <summary>The combat stance a weapon swap leaves the character in.</summary>
|
||||
|
|
@ -104,8 +131,11 @@ internal static class Stance
|
|||
/// is put right (<see cref="Stance.Wanted"/>) once the character is still.
|
||||
/// Busy: nothing is sent while the client's busy count is up, a gesture animates, RynthAi waits on
|
||||
/// the server, the last action is unanswered, or for <see cref="MinGapMs"/> after it - the "one item
|
||||
/// action at a time" rule RynthAi's ActionPacer keeps. Weapon swaps also wait out a running RynthAi
|
||||
/// macro unless the player allowed them (it would swap straight back).
|
||||
/// action at a time" rule RynthAi's ActionPacer keeps. A busy reading that has sat unchanged with
|
||||
/// nothing in flight (a count left by a death, a login or an interrupted action) is a leftover and
|
||||
/// holds nothing (<see cref="BusyGate"/>, logged once); if the server really is busy it answers
|
||||
/// "You're too busy" and the use is tried once more after <see cref="RetryAfterMs"/>. Weapon swaps
|
||||
/// also wait out a running RynthAi macro unless the player allowed them (it would swap straight back).
|
||||
/// </summary>
|
||||
internal sealed class UseController
|
||||
{
|
||||
|
|
@ -119,25 +149,44 @@ internal sealed class UseController
|
|||
public const long MinGapMs = 250;
|
||||
public const long StanceSettleMs = 500;
|
||||
public const long StanceTimeoutMs = 4000;
|
||||
/// <summary>A cast waits this long after the client reads Magic mode (RynthAi's ActionPacer.ModeSettleMs: a cast
|
||||
/// sent into the stance animation hangs).</summary>
|
||||
public const long MagicSettleMs = 800;
|
||||
/// <summary>A use the server answered "You're too busy" is tried once more after this.</summary>
|
||||
public const long RetryAfterMs = 1000;
|
||||
/// <summary>ACE's YoureTooBusy, as a UseDone error.</summary>
|
||||
public const uint TooBusyError = 0x1D;
|
||||
|
||||
private enum Stage { Sent, WaitWield, Stance }
|
||||
private enum Stage { Sent, WaitWield, Stance, Magic }
|
||||
|
||||
private sealed class Flight
|
||||
{
|
||||
public UseRequest Request = null!;
|
||||
/// <summary>The item used (null for a cast).</summary>
|
||||
public CarriedItem Item = null!;
|
||||
/// <summary>What the player reads ("Peerless Healing Kit", "Heal Self VI") and what the log reads.</summary>
|
||||
public string Name = string.Empty, What = string.Empty;
|
||||
public UseAction Action;
|
||||
public ItemKind Kind;
|
||||
public long SentMs;
|
||||
public int UseDoneAtSend, RefusalAtSend, ModeBefore;
|
||||
public Stage Stage;
|
||||
public long StageMs;
|
||||
// A cast: the spell, its target, and the Magic stance it waits for.
|
||||
public uint SpellId, Target;
|
||||
public bool ModeAsked;
|
||||
public long MagicSeenMs;
|
||||
}
|
||||
|
||||
private UseRequest? _pending;
|
||||
private Flight? _flight;
|
||||
private long _lastDoneMs = long.MinValue / 4;
|
||||
private long _retryNotBeforeMs = long.MinValue / 4;
|
||||
private string _lastWait = string.Empty;
|
||||
private readonly BusyGate _busy = new();
|
||||
|
||||
/// <summary>The busy readings' clocks (tests look at the leftover).</summary>
|
||||
internal BusyGate Busy => _busy;
|
||||
|
||||
/// <summary>Plain information ("Using Peerless Healing Kit ..."): the status line, not the chat.</summary>
|
||||
public Action<string>? Say;
|
||||
|
|
@ -155,6 +204,10 @@ internal sealed class UseController
|
|||
public bool Involves(ItemRef r) =>
|
||||
(_pending?.Item != null && _pending.Item.SameAs(r)) || (_flight?.Request.Item != null && _flight.Request.Item.SameAs(r));
|
||||
|
||||
/// <summary>The spell a cast in flight or waiting is about.</summary>
|
||||
public bool InvolvesSpell(uint spellId) =>
|
||||
spellId != 0 && (_pending?.Spell == spellId || _flight?.Request.Spell == spellId);
|
||||
|
||||
public DefSettings Settings = new();
|
||||
|
||||
/// <summary>Queues a request. False when it is the one already waiting or in flight (a held key).</summary>
|
||||
|
|
@ -167,22 +220,38 @@ internal sealed class UseController
|
|||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Drops what is waiting and forgets what is in flight (logout, portal space, shutdown).</summary>
|
||||
/// <summary>Drops what is waiting and forgets what is in flight (portal space).</summary>
|
||||
public void Reset()
|
||||
{
|
||||
_pending = null;
|
||||
_flight = null;
|
||||
_lastWait = string.Empty;
|
||||
_retryNotBeforeMs = long.MinValue / 4;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="Reset"/>, and the busy readings' clocks start again (login, logout, shutdown). Not on
|
||||
/// portal space: a count a death left has read the same all through the death portal, and that is
|
||||
/// what shows it is a leftover once the character lands.
|
||||
/// </summary>
|
||||
public void ResetSession()
|
||||
{
|
||||
Reset();
|
||||
_busy.Reset();
|
||||
}
|
||||
|
||||
public void Tick(IDefWorld w)
|
||||
{
|
||||
long now = w.NowMs;
|
||||
_busy.Observe(w.BusyCount, w.Animating, w.BotWaitingOnServer, now);
|
||||
if (!w.InWorld)
|
||||
{
|
||||
// Portal space (a death's too): what was waiting is dropped, and said so (a key pressed in the
|
||||
// portal did nothing). A use in flight is the server's now; nothing to say about it.
|
||||
if (_pending != null) Warn?.Invoke($"{_pending.Label}: not used, the character is in portal space.");
|
||||
if (_pending != null || _flight != null) Reset();
|
||||
return;
|
||||
}
|
||||
long now = w.NowMs;
|
||||
if (_flight != null && !AdvanceFlight(w, now)) return; // still in flight: nothing new goes out
|
||||
if (_pending == null) return;
|
||||
|
||||
|
|
@ -205,16 +274,36 @@ internal sealed class UseController
|
|||
private string? WaitReason(IDefWorld w, long now)
|
||||
{
|
||||
if (now - _lastDoneMs < MinGapMs) return "the last action just finished";
|
||||
if (w.ClientBusy) return "the character is busy";
|
||||
if (w.Animating) return "an animation is playing";
|
||||
if (w.BotWaitingOnServer == true) return "RynthAi is waiting on the server";
|
||||
return null;
|
||||
if (now < _retryNotBeforeMs) return "the server said the character was busy";
|
||||
return Hold(now) switch
|
||||
{
|
||||
BusyHold.Busy => "the character is busy",
|
||||
BusyHold.Animation => "an animation is playing",
|
||||
BusyHold.Bot => "RynthAi is waiting on the server",
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>The busy gate's verdict now; a leftover it ignores for the first time is logged.</summary>
|
||||
private BusyHold Hold(long now)
|
||||
{
|
||||
BusyHold hold = _busy.Judge(now, out BusyStale ignored);
|
||||
if (ignored != BusyStale.None) Log?.Invoke(_busy.Describe(ignored, now));
|
||||
return hold;
|
||||
}
|
||||
|
||||
/// <summary>The client's count or a gesture holds the character (RynthAi's bit doesn't: it is about RynthAi's own actions).</summary>
|
||||
private bool CharacterHeld(long now) => Hold(now) is BusyHold.Busy or BusyHold.Animation;
|
||||
|
||||
// ── Sending ─────────────────────────────────────────────────────────────
|
||||
|
||||
private void Send(IDefWorld w, UseRequest req, long now)
|
||||
{
|
||||
if (req.Spell != 0)
|
||||
{
|
||||
SendSpell(w, req, now);
|
||||
return;
|
||||
}
|
||||
IReadOnlyList<CarriedItem> items = w.Items();
|
||||
CarriedItem? item = req.Item != null
|
||||
? ItemMatcher.Find(req.Item, items, out _)
|
||||
|
|
@ -268,11 +357,14 @@ internal sealed class UseController
|
|||
Warn?.Invoke($"{name}: the client didn't take the request (nothing was sent).");
|
||||
return;
|
||||
}
|
||||
_busy.NoteOwnSend(now);
|
||||
|
||||
_flight = new Flight
|
||||
{
|
||||
Request = req,
|
||||
Item = item,
|
||||
Name = name,
|
||||
What = item.ToString(),
|
||||
Action = action,
|
||||
Kind = kind,
|
||||
SentMs = now,
|
||||
|
|
@ -282,10 +374,124 @@ internal sealed class UseController
|
|||
ModeBefore = w.CombatMode,
|
||||
Stage = action == UseAction.Equip ? Stage.WaitWield : Stage.Sent,
|
||||
};
|
||||
Log?.Invoke($"[RynthDefective] {req.Source}: {(action == UseAction.Equip ? "wield" : target != 0 ? "use on " + (target == w.PlayerId ? "you" : "0x" + target.ToString("X8")) : "use")} {item} (stack {item.Stack}, mode {Stance.Name(w.CombatMode)})");
|
||||
Log?.Invoke($"[RynthDefective] {req.Source}: {(action == UseAction.Equip ? "wield" : target != 0 ? "use on " + (target == w.PlayerId ? "you" : "0x" + target.ToString("X8")) : "use")} {item} (stack {item.Stack}, mode {Stance.Name(w.CombatMode)}{(req.Retry ? ", the one more try" : "")})");
|
||||
Say?.Invoke(action == UseAction.Equip ? $"Wielding {name}..." : $"Using {name}...");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The server answered "You're too busy" (UseDone 0x1D) to <paramref name="f"/>'s use: it is tried
|
||||
/// once more after <see cref="RetryAfterMs"/>, unless a newer request is waiting (the newest wish
|
||||
/// wins) or this was the one more try already. Returns whether it was queued again.
|
||||
/// </summary>
|
||||
private bool RetryTooBusy(Flight f, long now)
|
||||
{
|
||||
string name = f.Name;
|
||||
if (f.Request.Retry)
|
||||
{
|
||||
Warn?.Invoke($"{name}: not {(f.SpellId != 0 ? "cast" : "used")}, the server says the character is busy. Try again in a moment.");
|
||||
return false;
|
||||
}
|
||||
if (_pending != null) return false;
|
||||
_pending = f.Request with { Retry = true, AtMs = now };
|
||||
_retryNotBeforeMs = now + RetryAfterMs;
|
||||
Log?.Invoke($"[RynthDefective] {f.Request.Source}: the server answered 'too busy' to {f.What}; trying once more in {RetryAfterMs} ms");
|
||||
Say?.Invoke($"{name}: the server said busy, trying again...");
|
||||
return true;
|
||||
}
|
||||
|
||||
// ── Casting (a spell slot) ──────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// A spell slot's cast: refused when the character doesn't know the spell or it needs a target
|
||||
/// (SpellTargeting); else into Magic mode first (the client's stance for casting; RynthAi buffs the
|
||||
/// same way), then cast once the stance has settled, answered by the server's UseDone like a use.
|
||||
/// </summary>
|
||||
private void SendSpell(IDefWorld w, UseRequest req, long now)
|
||||
{
|
||||
uint id = req.Spell;
|
||||
SpellInfo? info = SpellTable.TryGet(id, out SpellInfo s) ? s : null;
|
||||
string name = info?.Name ?? req.Label;
|
||||
if (!w.CanCast)
|
||||
{
|
||||
Warn?.Invoke($"{name}: not cast, this RynthCore can't cast spells for a plugin.");
|
||||
return;
|
||||
}
|
||||
if (w.KnowsSpell(id) == false)
|
||||
{
|
||||
Warn?.Invoke($"{name}: not cast, you don't know that spell.");
|
||||
return;
|
||||
}
|
||||
if (SpellTargeting.Decide(info, w.SelectedId, w.PlayerId, out uint target, out string why) == CastAt.Refused)
|
||||
{
|
||||
Warn?.Invoke($"{name}: not cast, {why}.");
|
||||
return;
|
||||
}
|
||||
var f = new Flight
|
||||
{
|
||||
Request = req,
|
||||
Name = name,
|
||||
What = $"spell {id} '{name}'",
|
||||
Action = UseAction.Use,
|
||||
SpellId = id,
|
||||
Target = target,
|
||||
SentMs = now,
|
||||
StageMs = now,
|
||||
ModeBefore = w.CombatMode,
|
||||
Stage = Stage.Magic,
|
||||
};
|
||||
_flight = f;
|
||||
if (w.CombatMode == Stance.Magic)
|
||||
{
|
||||
f.MagicSeenMs = now - MagicSettleMs; // already there and settled (nothing holds the character: WaitReason)
|
||||
AdvanceMagic(w, f, now);
|
||||
return;
|
||||
}
|
||||
f.ModeAsked = w.SetCombatMode(Stance.Magic);
|
||||
Log?.Invoke($"[RynthDefective] {req.Source}: {f.What}: {Stance.Name(w.CombatMode)} -> magic first{(f.ModeAsked ? "" : " (the client turned it away; asking again)")}");
|
||||
Say?.Invoke($"Magic mode for {name}...");
|
||||
}
|
||||
|
||||
/// <summary>A cast waiting for Magic mode: cast once it has settled. True when finished (cast refused or failed).</summary>
|
||||
private bool AdvanceMagic(IDefWorld w, Flight f, long now)
|
||||
{
|
||||
long age = now - f.StageMs;
|
||||
if (w.CombatMode == Stance.Magic)
|
||||
{
|
||||
if (f.MagicSeenMs == 0) f.MagicSeenMs = now;
|
||||
bool settling = now - f.MagicSeenMs < MagicSettleMs || CharacterHeld(now);
|
||||
if (settling && age < WaitLimitMs) return false;
|
||||
return Cast(w, f, now);
|
||||
}
|
||||
if (age >= StanceTimeoutMs)
|
||||
{
|
||||
Warn?.Invoke($"{f.Name}: not cast, the character didn't go into magic mode ({Stance.Name(w.CombatMode)} now). "
|
||||
+ "A weapon in your hands? Wield a wand, or nothing, and try again.");
|
||||
Finish(now);
|
||||
return true;
|
||||
}
|
||||
if (!f.ModeAsked && !CharacterHeld(now)) f.ModeAsked = w.SetCombatMode(Stance.Magic);
|
||||
return false;
|
||||
}
|
||||
|
||||
private bool Cast(IDefWorld w, Flight f, long now)
|
||||
{
|
||||
f.UseDoneAtSend = w.UseDoneSeq;
|
||||
f.RefusalAtSend = w.RefusalSeq;
|
||||
if (!w.CastSpell(f.Target, f.SpellId))
|
||||
{
|
||||
Warn?.Invoke($"{f.Name}: the client didn't take the cast (nothing was sent).");
|
||||
Finish(now);
|
||||
return true;
|
||||
}
|
||||
_busy.NoteOwnSend(now);
|
||||
f.Stage = Stage.Sent;
|
||||
f.SentMs = now;
|
||||
f.StageMs = now;
|
||||
Log?.Invoke($"[RynthDefective] {f.Request.Source}: cast {f.What} on {(f.Target == w.PlayerId ? "you" : "0x" + f.Target.ToString("X8"))} (mode {Stance.Name(w.CombatMode)}{(f.Request.Retry ? ", the one more try" : "")})");
|
||||
Say?.Invoke(f.Target == w.PlayerId ? $"Casting {f.Name}..." : $"Casting {f.Name} on the selection...");
|
||||
return false;
|
||||
}
|
||||
|
||||
// ── In flight ───────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Steps the action in flight; true when it is finished (a new one may go out this tick).</summary>
|
||||
|
|
@ -298,11 +504,12 @@ internal sealed class UseController
|
|||
case Stage.Sent:
|
||||
{
|
||||
bool answered = w.UseDoneSeq != f.UseDoneAtSend;
|
||||
bool quiet = age >= UseQuietMs && !w.ClientBusy && !w.Animating;
|
||||
bool quiet = !answered && age >= UseQuietMs && !CharacterHeld(now);
|
||||
if (answered || quiet || age >= UseTimeoutMs)
|
||||
{
|
||||
if (!answered && age >= UseTimeoutMs) Log?.Invoke($"[RynthDefective] no UseDone for {f.Item} after {age} ms; carrying on");
|
||||
if (!answered && age >= UseTimeoutMs) Log?.Invoke($"[RynthDefective] no UseDone for {f.What} after {age} ms; carrying on");
|
||||
Finish(now);
|
||||
if (answered && w.UseDoneError(f.UseDoneAtSend) == TooBusyError) RetryTooBusy(f, now);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
|
|
@ -332,6 +539,8 @@ internal sealed class UseController
|
|||
}
|
||||
return false;
|
||||
}
|
||||
case Stage.Magic:
|
||||
return AdvanceMagic(w, f, now);
|
||||
default:
|
||||
return AdvanceStance(w, f, now);
|
||||
}
|
||||
|
|
@ -354,7 +563,7 @@ internal sealed class UseController
|
|||
Finish(now);
|
||||
return true;
|
||||
}
|
||||
if (since < StanceSettleMs || w.ClientBusy || w.Animating) return false;
|
||||
if (since < StanceSettleMs || CharacterHeld(now)) return false;
|
||||
if (w.SetCombatMode(want))
|
||||
{
|
||||
Log?.Invoke($"[RynthDefective] stance {Stance.Name(w.CombatMode)} -> {Stance.Name(want)} for {f.Item}");
|
||||
|
|
|
|||
|
|
@ -59,7 +59,7 @@ internal sealed class BarSettingsView
|
|||
if (st.IndependentBar && _s.CopyOffer > 0)
|
||||
{
|
||||
int n = _s.CopyOffer;
|
||||
w.TextColored(SlotText.Waiting, $"The game's 18 slots hold {n} item{(n == 1 ? "" : "s")}. Copy {(n == 1 ? "it" : "them")} into this bar's slots 1-18?");
|
||||
w.TextColored(SlotText.Waiting, $"The game's 18 slots hold {n} shortcut{(n == 1 ? "" : "s")} (items and spells). Copy {(n == 1 ? "it" : "them")} into this bar's slots 1-18?");
|
||||
w.TextWrapped("Your own slots move after them, to 19 and on, with their keys, so the bar looks as before. "
|
||||
+ "The game's toolbar and its keys stay as they are.");
|
||||
w.SmallButton("Copy them", "set.copy", () => Tell(_s.CopyRetailSlots()));
|
||||
|
|
|
|||
|
|
@ -121,6 +121,24 @@ internal sealed class BarView
|
|||
color = SlotText.Plain;
|
||||
bool icons = _s.Settings.ShowIcons && _s.IconsAvailable;
|
||||
|
||||
if (slot.IsSpell)
|
||||
{
|
||||
// A spell slot (set with /rdef spell or on the Shortcuts bar): its picture, or its initials.
|
||||
string spell = slot.SpellLabel;
|
||||
SpellInfo? info = SpellTable.TryGet(slot.SpellId, out SpellInfo si) ? si : null;
|
||||
bool casting = _s.Use.InvolvesSpell(slot.SpellId);
|
||||
if (icons) w.ImageButton(UiFormat.IconKindSpell, slot.SpellId, id, () => Press(number), size, size, 0xFFFFFFFFu, casting ? SlotText.Waiting : 0u);
|
||||
else
|
||||
{
|
||||
if (casting) w.PushStyleColor(UiFormat.ColButton, SlotText.Waiting);
|
||||
w.Button(SlotText.Abbreviation(spell), id, () => Press(number), size + 8f, size + 8f);
|
||||
if (casting) w.PopStyleColor();
|
||||
}
|
||||
w.Tooltip($"Slot {number}: {spell}, a spell.\nClick or press the key: {SpellTargeting.Describe(info)} (Magic mode first)."
|
||||
+ (keyFull != null ? "\nKey: " + keyFull : "\nNo key yet (Edit slots)."));
|
||||
return;
|
||||
}
|
||||
|
||||
if (slot.Item == null)
|
||||
{
|
||||
w.Button("+", id, () => Choose(number), size + 8f, size + 8f);
|
||||
|
|
|
|||
|
|
@ -57,11 +57,12 @@ internal sealed class SlotEditor
|
|||
DefSlot slot = _s.Data.Slots[n - 1];
|
||||
int number = n;
|
||||
string? key = _s.KeyOfSlot(n);
|
||||
string name = slot.Item == null ? "(empty)" : slot.Item.FullName;
|
||||
string name = slot.Empty ? "(empty)" : slot.Label;
|
||||
if (icons)
|
||||
{
|
||||
CarriedItem? have = slot.Item == null ? null : ItemMatcher.Find(slot.Item, items, out _);
|
||||
if (have != null) w.Image(UiFormat.IconKindObject, have.Id, RowIcon, RowIcon);
|
||||
if (slot.IsSpell) w.Image(UiFormat.IconKindSpell, slot.SpellId, RowIcon, RowIcon);
|
||||
else if (have != null) w.Image(UiFormat.IconKindObject, have.Id, RowIcon, RowIcon);
|
||||
else if (slot.Item != null && slot.Item.Icon != 0) w.Image(UiFormat.IconKindIcon, slot.Item.Icon, RowIcon, RowIcon, UiFormat.Rgb(255, 255, 255, 90));
|
||||
else w.Dummy(RowIcon, RowIcon);
|
||||
w.SameLine();
|
||||
|
|
@ -78,7 +79,7 @@ internal sealed class SlotEditor
|
|||
{
|
||||
int n = _selected;
|
||||
DefSlot slot = _s.Data.Slots[n - 1];
|
||||
w.TextColored(UiColors.Gold, $"Slot {n}: " + (slot.Item == null ? "(empty)" : slot.Item.FullName));
|
||||
w.TextColored(UiColors.Gold, $"Slot {n}: " + (slot.Empty ? "(empty)" : slot.Label));
|
||||
|
||||
w.Button("Set from selected", "ed.set", () => Say(_s.SetFromSelected(n)));
|
||||
w.Tooltip("Select an item in the game (click it in your pack), then press this: it goes in this slot.");
|
||||
|
|
@ -99,6 +100,13 @@ internal sealed class SlotEditor
|
|||
|
||||
if (_picking) DrawPackPicker(w, items, n);
|
||||
|
||||
if (slot.IsSpell)
|
||||
{
|
||||
SpellInfo? info = SpellTable.TryGet(slot.SpellId, out SpellInfo si) ? si : null;
|
||||
w.TextDisabled($"A spell: pressing the slot has it {SpellTargeting.Describe(info)} (Magic mode first). /rdef spell {n} <name> puts another in.");
|
||||
DrawKey(w, n, slot);
|
||||
return;
|
||||
}
|
||||
if (slot.Item == null) return;
|
||||
|
||||
int mode = (int)slot.Mode;
|
||||
|
|
|
|||
Loading…
Reference in a new issue